Merge "master" into "wdp".
[sliver-openvswitch.git] / ofproto / wdp-xflow.c
1 /*
2  * Copyright (c) 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "wdp-xflow.h"
20
21 #include <errno.h>
22 #include <inttypes.h>
23
24 #include "coverage.h"
25 #include "dhcp.h"
26 #include "mac-learning.h"
27 #include "netdev.h"
28 #include "netflow.h"
29 #include "ofp-util.h"
30 #include "ofpbuf.h"
31 #include "ofproto.h"
32 #include "openflow/nicira-ext.h"
33 #include "openflow/openflow.h"
34 #include "packets.h"
35 #include "poll-loop.h"
36 #include "port-array.h"
37 #include "shash.h"
38 #include "stp.h"
39 #include "svec.h"
40 #include "timeval.h"
41 #include "util.h"
42 #include "vconn.h"
43 #include "wdp-provider.h"
44 #include "xfif.h"
45 #include "xflow-util.h"
46 #include "vlog.h"
47 #include "xtoxll.h"
48
49 VLOG_DEFINE_THIS_MODULE(wdp_xflow)
50
51 enum {
52     TABLEID_HASH = 0,
53     TABLEID_CLASSIFIER = 1
54 };
55
56 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
57 \f
58 /* Maximum numbers of rules. */
59 #define WX_MAX_WILD     65536   /* Wildcarded rules. */
60 #define WX_MAX_EXACT    1048576 /* Exact-match rules. */
61
62 struct wx {
63     struct list list_node;
64     struct wdp wdp;
65     struct xfif *xfif;
66     struct classifier cls;
67     struct netdev_monitor *netdev_monitor;
68     struct port_array ports;    /* Index is xflow port nr;
69                                  * wdp_port->opp.port_no is OFP port nr. */
70     struct shash port_by_name;
71     long long int next_expiration;
72
73     /* Rules that might need to be revalidated. */
74     bool need_revalidate;      /* Revalidate all subrules? */
75     bool revalidate_all;       /* Revalidate all subrules and other rules? */
76     struct tag_set revalidate_set; /* Tag set of (sub)rules to revalidate. */
77
78     /* Hooks for ovs-vswitchd. */
79     const struct ofhooks *ofhooks;
80     void *aux;
81
82     /* Used by default ofhooks. */
83     struct mac_learning *ml;
84 };
85
86 static const struct ofhooks default_ofhooks;
87
88 static struct list all_wx = LIST_INITIALIZER(&all_wx);
89
90 static int wx_port_init(struct wx *);
91 static void wx_port_process_change(struct wx *wx, int error, char *devname,
92                                    wdp_port_poll_cb_func *cb, void *aux);
93 static void wx_port_refresh_groups(struct wx *);
94
95 enum {
96     WX_GROUP_FLOOD = 0,
97     WX_GROUP_ALL = 1
98 };
99
100 static struct wx *
101 wx_cast(const struct wdp *wdp)
102 {
103     return CONTAINER_OF(wdp, struct wx, wdp);
104 }
105
106 static int
107 wx_xlate_actions(struct wx *, const union ofp_action *, size_t n,
108                  const flow_t *flow, const struct ofpbuf *packet,
109                  tag_type *tags, struct xflow_actions *out,
110                  bool *may_set_up_flow);
111 \f
112 struct wx_rule {
113     struct wdp_rule wr;
114
115     uint64_t packet_count;      /* Number of packets received. */
116     uint64_t byte_count;        /* Number of bytes received. */
117     uint64_t accounted_bytes;   /* Number of bytes passed to account_cb. */
118     long long int used;         /* Last-used time (0 if never used). */
119     tag_type tags;              /* Tags (set only by hooks). */
120
121     /* If 'super' is non-NULL, this rule is a subrule, that is, it is an
122      * exact-match rule (having cr.wc.wildcards of 0) generated from the
123      * wildcard rule 'super'.  In this case, 'list' is an element of the
124      * super-rule's list.
125      *
126      * If 'super' is NULL, this rule is a super-rule, and 'list' is the head of
127      * a list of subrules.  A super-rule with no wildcards (where
128      * cr.wc.wildcards is 0) will never have any subrules. */
129     struct wx_rule *super;
130     struct list list;
131
132     /* Datapath actions.
133      *
134      * A super-rule with wildcard fields never has xflow actions (since the
135      * datapath only supports exact-match flows). */
136     bool installed;             /* Installed in datapath? */
137     bool may_install;           /* True ordinarily; false if actions must
138                                  * be reassessed for every packet. */
139     int n_xflow_actions;
140     union xflow_action *xflow_actions;
141 };
142
143 static void wx_rule_destroy(struct wx *, struct wx_rule *);
144 static void wx_rule_update_actions(struct wx *, struct wx_rule *);
145 static void wx_rule_execute(struct wx *, struct wx_rule *,
146                             struct ofpbuf *packet, const flow_t *);
147 static bool wx_rule_make_actions(struct wx *, struct wx_rule *,
148                                  const struct ofpbuf *packet);
149 static void wx_rule_install(struct wx *, struct wx_rule *,
150                             struct wx_rule *displaced_rule);
151
152 static struct wx_rule *
153 wx_rule_cast(const struct cls_rule *cls_rule)
154 {
155     return cls_rule ? CONTAINER_OF(cls_rule, struct wx_rule, wr.cr) : NULL;
156 }
157
158 /* Returns true if 'rule' is merely an implementation detail that should be
159  * hidden from the client. */
160 static inline bool
161 wx_rule_is_hidden(const struct wx_rule *rule)
162 {
163     return rule->super != NULL;
164 }
165
166 static void
167 wx_rule_free(struct wx_rule *rule)
168 {
169     wdp_rule_uninit(&rule->wr);
170     free(rule->xflow_actions);
171     free(rule);
172 }
173
174 static void
175 wx_rule_account(struct wx *wx OVS_UNUSED, struct wx_rule *rule OVS_UNUSED,
176                 uint64_t extra_bytes OVS_UNUSED)
177 {
178     /* XXX call account_cb hook */
179 }
180
181 static void
182 wx_rule_post_uninstall(struct wx *wx, struct wx_rule *rule)
183 {
184     struct wx_rule *super = rule->super;
185
186     wx_rule_account(wx, rule, 0);
187
188     /* XXX netflow expiration */
189
190     if (super) {
191         super->packet_count += rule->packet_count;
192         super->byte_count += rule->byte_count;
193
194         /* Reset counters to prevent double counting if the rule ever gets
195          * reinstalled. */
196         rule->packet_count = 0;
197         rule->byte_count = 0;
198         rule->accounted_bytes = 0;
199
200         //XXX netflow_flow_clear(&rule->nf_flow);
201     }
202 }
203
204 static long long int
205 xflow_flow_stats_to_msec(const struct xflow_flow_stats *stats)
206 {
207     return (stats->used_sec
208             ? stats->used_sec * 1000 + stats->used_nsec / 1000000
209             : 0);
210 }
211
212 static void
213 wx_rule_update_time(struct wx *wx OVS_UNUSED, struct wx_rule *rule,
214                     const struct xflow_flow_stats *stats)
215 {
216     long long int used = xflow_flow_stats_to_msec(stats);
217     if (used > rule->used) {
218         rule->used = used;
219         if (rule->super && used > rule->super->used) {
220             rule->super->used = used;
221         }
222         //XXX netflow_flow_update_time(ofproto->netflow, &rule->nf_flow, used);
223     }
224 }
225
226 static void
227 wx_rule_update_stats(struct wx *wx, struct wx_rule *rule,
228                      const struct xflow_flow_stats *stats)
229 {
230     if (stats->n_packets) {
231         wx_rule_update_time(wx, rule, stats);
232         rule->packet_count += stats->n_packets;
233         rule->byte_count += stats->n_bytes;
234         /* XXX netflow_flow_update_flags(&rule->nf_flow, stats->tcp_flags); */
235     }
236 }
237
238 static void
239 wx_rule_uninstall(struct wx *wx, struct wx_rule *rule)
240 {
241     assert(!rule->wr.cr.flow.wildcards);
242     if (rule->installed) {
243         struct xflow_flow xflow_flow;
244
245         xflow_key_from_flow(&xflow_flow.key, &rule->wr.cr.flow);
246         xflow_flow.actions = NULL;
247         xflow_flow.n_actions = 0;
248         xflow_flow.flags = 0;
249         if (!xfif_flow_del(wx->xfif, &xflow_flow)) {
250             wx_rule_update_stats(wx, rule, &xflow_flow.stats);
251         }
252         rule->installed = false;
253
254         wx_rule_post_uninstall(wx, rule);
255     }
256 }
257
258 #if 0
259 static bool
260 is_controller_rule(struct wx_rule *rule)
261 {
262     /* If the only action is send to the controller then don't report
263      * NetFlow expiration messages since it is just part of the control
264      * logic for the network and not real traffic. */
265
266     return (rule
267             && rule->super
268             && rule->super->n_actions == 1
269             && action_outputs_to_port(&rule->super->actions[0],
270                                       htons(OFPP_CONTROLLER)));
271 }
272 #endif
273
274 static void
275 wx_rule_remove(struct wx *wx, struct wx_rule *rule)
276 {
277     if (rule->wr.cr.flow.wildcards) {
278         COVERAGE_INC(wx_del_wc_flow);
279         wx->need_revalidate = true;
280     } else {
281         wx_rule_uninstall(wx, rule);
282     }
283     classifier_remove(&wx->cls, &rule->wr.cr);
284     wx_rule_destroy(wx, rule);
285 }
286
287 static bool
288 wx_rule_revalidate(struct wx *wx, struct wx_rule *rule)
289 {
290     const flow_t *flow = &rule->wr.cr.flow;
291
292     COVERAGE_INC(wx_rule_revalidate);
293     if (rule->super) {
294         struct wx_rule *super;
295         super = wx_rule_cast(classifier_lookup_wild(&wx->cls, flow));
296         if (!super) {
297             wx_rule_remove(wx, rule);
298             return false;
299         } else if (super != rule->super) {
300             COVERAGE_INC(wx_revalidate_moved);
301             list_remove(&rule->list);
302             list_push_back(&super->list, &rule->list);
303             rule->super = super;
304             rule->wr.hard_timeout = super->wr.hard_timeout;
305             rule->wr.idle_timeout = super->wr.idle_timeout;
306             rule->wr.created = super->wr.created;
307             rule->used = 0;
308         }
309     }
310
311     wx_rule_update_actions(wx, rule);
312     return true;
313 }
314
315 /* Destroys 'rule'.  If 'rule' is a subrule, also removes it from its
316  * super-rule's list of subrules.  If 'rule' is a super-rule, also iterates
317  * through all of its subrules and revalidates them, destroying any that no
318  * longer has a super-rule (which is probably all of them).
319  *
320  * Before calling this function, the caller must make have removed 'rule' from
321  * the classifier.  If 'rule' is an exact-match rule, the caller is also
322  * responsible for ensuring that it has been uninstalled from the datapath. */
323 static void
324 wx_rule_destroy(struct wx *wx, struct wx_rule *rule)
325 {
326     if (!rule->super) {
327         struct wx_rule *subrule, *next;
328         LIST_FOR_EACH_SAFE (subrule, next, struct wx_rule, list, &rule->list) {
329             wx_rule_revalidate(wx, subrule);
330         }
331     } else {
332         list_remove(&rule->list);
333     }
334     wx_rule_free(rule);
335 }
336
337 #if 0
338 static bool
339 wx_rule_has_out_port(const struct wx_rule *rule, uint16_t out_port)
340 {
341     const union ofp_action *oa;
342     struct actions_iterator i;
343
344     if (out_port == htons(OFPP_NONE)) {
345         return true;
346     }
347     for (oa = actions_first(&i, rule->wr.actions,
348                             rule->wr.n_actions);
349          oa;
350          oa = actions_next(&i)) {
351         if (oa->type == htons(OFPAT_OUTPUT) && oa->output.port == out_port) {
352             return true;
353         }
354     }
355     return false;
356 }
357 #endif
358
359 /* Caller is responsible for initializing the 'cr' and ofp_table_id members of
360  * the returned rule. */
361 static struct wx_rule *
362 wx_rule_create(struct wx_rule *super,
363                const union ofp_action *actions, size_t n_actions,
364                uint16_t idle_timeout, uint16_t hard_timeout)
365 {
366     struct wx_rule *rule = xzalloc(sizeof *rule);
367     wdp_rule_init(&rule->wr, actions, n_actions);
368     rule->wr.idle_timeout = idle_timeout;
369     rule->wr.hard_timeout = hard_timeout;
370     rule->used = rule->wr.created;
371     rule->super = super;
372     if (super) {
373         list_push_back(&super->list, &rule->list);
374     } else {
375         list_init(&rule->list);
376     }
377 #if 0
378     netflow_flow_clear(&rule->nf_flow);
379     netflow_flow_update_time(ofproto->netflow, &rule->nf_flow, rule->created);
380 #endif
381
382     return rule;
383 }
384
385 /* Executes the actions indicated by 'rule' on 'packet', which is in flow
386  * 'flow' and is considered to have arrived on xflow port 'in_port'.
387  *
388  * The flow that 'packet' actually contains does not need to actually match
389  * 'rule'; the actions in 'rule' will be applied to it either way.  Likewise,
390  * the packet and byte counters for 'rule' will be credited for the packet sent
391  * out whether or not the packet actually matches 'rule'.
392  *
393  * If 'rule' is an exact-match rule and 'flow' actually equals the rule's flow,
394  * the caller must already have accurately composed xflow actions for it given
395  * 'packet' using rule_make_actions().  If 'rule' is a wildcard rule, or if
396  * 'rule' is an exact-match rule but 'flow' is not the rule's flow, then this
397  * function will compose a set of xflow actions based on 'rule''s OpenFlow
398  * actions and apply them to 'packet'. */
399 static void
400 wx_rule_execute(struct wx *wx, struct wx_rule *rule,
401                 struct ofpbuf *packet, const flow_t *flow)
402 {
403     const union xflow_action *actions;
404     size_t n_actions;
405     struct xflow_actions a;
406
407     /* Grab or compose the xflow actions.
408      *
409      * The special case for an exact-match 'rule' where 'flow' is not the
410      * rule's flow is important to avoid, e.g., sending a packet out its input
411      * port simply because the xflow actions were composed for the wrong
412      * scenario. */
413     if (rule->wr.cr.flow.wildcards
414         || !flow_equal_headers(flow, &rule->wr.cr.flow))
415     {
416         struct wx_rule *super = rule->super ? rule->super : rule;
417         if (wx_xlate_actions(wx, super->wr.actions, super->wr.n_actions, flow,
418                              packet, NULL, &a, NULL)) {
419             return;
420         }
421         actions = a.actions;
422         n_actions = a.n_actions;
423     } else {
424         actions = rule->xflow_actions;
425         n_actions = rule->n_xflow_actions;
426     }
427
428     /* Execute the xflow actions. */
429     if (!xfif_execute(wx->xfif, flow->in_port,
430                       actions, n_actions, packet)) {
431         struct xflow_flow_stats stats;
432         flow_extract_stats(flow, packet, &stats);
433         wx_rule_update_stats(wx, rule, &stats);
434         rule->used = time_msec();
435         //XXX netflow_flow_update_time(wx->netflow, &rule->nf_flow, rule->used);
436     }
437 }
438
439 static void
440 wx_rule_insert(struct wx *wx, struct wx_rule *rule, struct ofpbuf *packet,
441                uint16_t in_port)
442 {
443     struct wx_rule *displaced_rule;
444
445     /* Insert the rule in the classifier. */
446     displaced_rule = wx_rule_cast(classifier_insert(&wx->cls, &rule->wr.cr));
447     if (!rule->wr.cr.flow.wildcards) {
448         wx_rule_make_actions(wx, rule, packet);
449     }
450
451     /* Send the packet and credit it to the rule. */
452     if (packet) {
453         flow_t flow;
454         flow_extract(packet, 0, in_port, &flow);
455         wx_rule_execute(wx, rule, packet, &flow);
456     }
457
458     /* Install the rule in the datapath only after sending the packet, to
459      * avoid packet reordering.  */
460     if (rule->wr.cr.flow.wildcards) {
461         COVERAGE_INC(wx_add_wc_flow);
462         wx->need_revalidate = true;
463     } else {
464         wx_rule_install(wx, rule, displaced_rule);
465     }
466
467     /* Free the rule that was displaced, if any. */
468     if (displaced_rule) {
469         rule->wr.client_data = displaced_rule->wr.client_data;
470         wx_rule_destroy(wx, displaced_rule);
471     }
472 }
473
474 static struct wx_rule *
475 wx_rule_create_subrule(struct wx *wx, struct wx_rule *rule, const flow_t *flow)
476 {
477     struct wx_rule *subrule;
478
479     subrule = wx_rule_create(rule, NULL, 0,
480                              rule->wr.idle_timeout,
481                              rule->wr.hard_timeout);
482     /* Subrules aren't really in any OpenFlow table, so don't bother with
483      * subrule->wr.ofp_table_id. */
484     COVERAGE_INC(wx_subrule_create);
485     cls_rule_from_flow(flow, &subrule->wr.cr);
486     classifier_insert_exact(&wx->cls, &subrule->wr.cr);
487
488     return subrule;
489 }
490
491 /* Returns true if the actions changed, false otherwise. */
492 static bool
493 wx_rule_make_actions(struct wx *wx, struct wx_rule *rule,
494                      const struct ofpbuf *packet)
495 {
496     const struct wx_rule *super;
497     struct xflow_actions a;
498     size_t actions_len;
499
500     assert(!rule->wr.cr.flow.wildcards);
501
502     super = rule->super ? rule->super : rule;
503     wx_xlate_actions(wx, super->wr.actions, super->wr.n_actions,
504                      &rule->wr.cr.flow, packet,
505                      &rule->tags, &a, &rule->may_install);
506
507     actions_len = a.n_actions * sizeof *a.actions;
508     if (rule->n_xflow_actions != a.n_actions
509         || memcmp(rule->xflow_actions, a.actions, actions_len)) {
510         COVERAGE_INC(wx_xflow_unchanged);
511         free(rule->xflow_actions);
512         rule->n_xflow_actions = a.n_actions;
513         rule->xflow_actions = xmemdup(a.actions, actions_len);
514         return true;
515     } else {
516         return false;
517     }
518 }
519
520 static int
521 do_put_flow(struct wx *wx, struct wx_rule *rule, int flags,
522             struct xflow_flow_put *put)
523 {
524     memset(&put->flow.stats, 0, sizeof put->flow.stats);
525     xflow_key_from_flow(&put->flow.key, &rule->wr.cr.flow);
526     put->flow.actions = rule->xflow_actions;
527     put->flow.n_actions = rule->n_xflow_actions;
528     put->flow.flags = 0;
529     put->flags = flags;
530     return xfif_flow_put(wx->xfif, put);
531 }
532
533 static void
534 wx_rule_install(struct wx *wx, struct wx_rule *rule, struct wx_rule *displaced_rule)
535 {
536     assert(!rule->wr.cr.flow.wildcards);
537
538     if (rule->may_install) {
539         struct xflow_flow_put put;
540         if (!do_put_flow(wx, rule,
541                          XFLOWPF_CREATE | XFLOWPF_MODIFY | XFLOWPF_ZERO_STATS,
542                          &put)) {
543             rule->installed = true;
544             if (displaced_rule) {
545                 wx_rule_update_stats(wx, displaced_rule, &put.flow.stats);
546                 wx_rule_post_uninstall(wx, displaced_rule);
547             }
548         }
549     } else if (displaced_rule) {
550         wx_rule_uninstall(wx, displaced_rule);
551     }
552 }
553
554 static void
555 wx_rule_reinstall(struct wx *wx, struct wx_rule *rule)
556 {
557     if (rule->installed) {
558         struct xflow_flow_put put;
559         COVERAGE_INC(wx_dp_missed);
560         do_put_flow(wx, rule, XFLOWPF_CREATE | XFLOWPF_MODIFY, &put);
561     } else {
562         wx_rule_install(wx, rule, NULL);
563     }
564 }
565
566 static void
567 wx_rule_update_actions(struct wx *wx, struct wx_rule *rule)
568 {
569     bool actions_changed;
570 #if 0
571     uint16_t new_out_iface, old_out_iface;
572
573     old_out_iface = rule->nf_flow.output_iface;
574 #endif
575     actions_changed = wx_rule_make_actions(wx, rule, NULL);
576
577     if (rule->may_install) {
578         if (rule->installed) {
579             if (actions_changed) {
580                 struct xflow_flow_put put;
581                 do_put_flow(wx, rule, XFLOWPF_CREATE | XFLOWPF_MODIFY
582                             | XFLOWPF_ZERO_STATS, &put);
583                 wx_rule_update_stats(wx, rule, &put.flow.stats);
584 #if 0
585                 /* Temporarily set the old output iface so that NetFlow
586                  * messages have the correct output interface for the old
587                  * stats. */
588                 new_out_iface = rule->nf_flow.output_iface;
589                 rule->nf_flow.output_iface = old_out_iface;
590 #endif
591                 wx_rule_post_uninstall(wx, rule);
592                 //rule->nf_flow.output_iface = new_out_iface;
593             }
594         } else {
595             wx_rule_install(wx, rule, NULL);
596         }
597     } else {
598         wx_rule_uninstall(wx, rule);
599     }
600 }
601 \f
602 static void
603 add_output_group_action(struct xflow_actions *actions, uint16_t group,
604                         uint16_t *nf_output_iface)
605 {
606     xflow_actions_add(actions, XFLOWAT_OUTPUT_GROUP)->output_group.group = group;
607
608     if (group == WX_GROUP_ALL || group == WX_GROUP_FLOOD) {
609         *nf_output_iface = NF_OUT_FLOOD;
610     }
611 }
612
613 static void
614 add_controller_action(struct xflow_actions *actions, uint16_t max_len)
615 {
616     union xflow_action *a = xflow_actions_add(actions, XFLOWAT_CONTROLLER);
617     a->controller.arg = max_len;
618 }
619
620 struct wx_xlate_ctx {
621     /* Input. */
622     flow_t flow;                /* Flow to which these actions correspond. */
623     int recurse;                /* Recursion level, via xlate_table_action. */
624     struct wx *wx;
625     const struct ofpbuf *packet; /* The packet corresponding to 'flow', or a
626                                   * null pointer if we are revalidating
627                                   * without a packet to refer to. */
628
629     /* Output. */
630     struct xflow_actions *out;    /* Datapath actions. */
631     tag_type *tags;             /* Tags associated with OFPP_NORMAL actions. */
632     bool may_set_up_flow;       /* True ordinarily; false if the actions must
633                                  * be reassessed for every packet. */
634     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
635 };
636
637 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
638                              struct wx_xlate_ctx *ctx);
639
640 static void
641 add_output_action(struct wx_xlate_ctx *ctx, uint16_t port)
642 {
643     const struct wdp_port *wdp_port = port_array_get(&ctx->wx->ports, port);
644
645     if (wdp_port) {
646         if (wdp_port->opp.config & OFPPC_NO_FWD) {
647             /* Forwarding disabled on port. */
648             return;
649         }
650     } else {
651         /*
652          * We don't have an ofport record for this port, but it doesn't hurt to
653          * allow forwarding to it anyhow.  Maybe such a port will appear later
654          * and we're pre-populating the flow table.
655          */
656     }
657
658     xflow_actions_add(ctx->out, XFLOWAT_OUTPUT)->output.port = port;
659     //ctx->nf_output_iface = port;
660 }
661
662 static struct wx_rule *
663 wx_rule_lookup_valid(struct wx *wx, const flow_t *flow)
664 {
665     struct wx_rule *rule = wx_rule_cast(classifier_lookup(&wx->cls, flow));
666
667     /* The rule we found might not be valid, since we could be in need of
668      * revalidation.  If it is not valid, don't return it. */
669     if (rule
670         && rule->super
671         && wx->need_revalidate
672         && !wx_rule_revalidate(wx, rule)) {
673         COVERAGE_INC(wx_invalidated);
674         return NULL;
675     }
676
677     return rule;
678 }
679
680 static void
681 xlate_table_action(struct wx_xlate_ctx *ctx, uint16_t in_port)
682 {
683     if (!ctx->recurse) {
684         uint16_t old_in_port;
685         struct wx_rule *rule;
686
687         /* Look up a flow with 'in_port' as the input port.  Then restore the
688          * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
689          * have surprising behavior). */
690         old_in_port = ctx->flow.in_port;
691         ctx->flow.in_port = in_port;
692         rule = wx_rule_lookup_valid(ctx->wx, &ctx->flow);
693         ctx->flow.in_port = old_in_port;
694
695         if (rule) {
696             if (rule->super) {
697                 rule = rule->super;
698             }
699
700             ctx->recurse++;
701             do_xlate_actions(rule->wr.actions, rule->wr.n_actions, ctx);
702             ctx->recurse--;
703         }
704     }
705 }
706
707 static void
708 xlate_output_action__(struct wx_xlate_ctx *ctx,
709                       uint16_t port, uint16_t max_len)
710 {
711     uint16_t xflow_port;
712     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
713
714     ctx->nf_output_iface = NF_OUT_DROP;
715
716     switch (port) {
717     case OFPP_IN_PORT:
718         add_output_action(ctx, ctx->flow.in_port);
719         break;
720     case OFPP_TABLE:
721         xlate_table_action(ctx, ctx->flow.in_port);
722         break;
723     case OFPP_NORMAL:
724         if (!ctx->wx->ofhooks->normal_cb(&ctx->flow, ctx->packet,
725                                          ctx->out, ctx->tags,
726                                          &ctx->nf_output_iface,
727                                          ctx->wx->aux)) {
728             COVERAGE_INC(wx_uninstallable);
729             ctx->may_set_up_flow = false;
730         }
731         break;
732
733     case OFPP_FLOOD:
734         add_output_group_action(ctx->out, WX_GROUP_FLOOD,
735                                 &ctx->nf_output_iface);
736         break;
737     case OFPP_ALL:
738         add_output_group_action(ctx->out, WX_GROUP_ALL, &ctx->nf_output_iface);
739         break;
740     case OFPP_CONTROLLER:
741         add_controller_action(ctx->out, max_len);
742         break;
743     case OFPP_LOCAL:
744         add_output_action(ctx, XFLOWP_LOCAL);
745         break;
746     default:
747         xflow_port = ofp_port_to_xflow_port(port);
748         if (xflow_port != ctx->flow.in_port) {
749             add_output_action(ctx, xflow_port);
750         }
751         break;
752     }
753
754     if (prev_nf_output_iface == NF_OUT_FLOOD) {
755         ctx->nf_output_iface = NF_OUT_FLOOD;
756     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
757         ctx->nf_output_iface = prev_nf_output_iface;
758     } else if (prev_nf_output_iface != NF_OUT_DROP &&
759                ctx->nf_output_iface != NF_OUT_FLOOD) {
760         ctx->nf_output_iface = NF_OUT_MULTI;
761     }
762 }
763
764 static void
765 xlate_output_action(struct wx_xlate_ctx *ctx,
766                     const struct ofp_action_output *oao)
767 {
768     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
769 }
770
771 /* If the final xflow action in 'ctx' is "pop priority", drop it, as an
772  * optimization, because we're going to add another action that sets the
773  * priority immediately after, or because there are no actions following the
774  * pop.  */
775 static void
776 remove_pop_action(struct wx_xlate_ctx *ctx)
777 {
778     size_t n = ctx->out->n_actions;
779     if (n > 0 && ctx->out->actions[n - 1].type == XFLOWAT_POP_PRIORITY) {
780         ctx->out->n_actions--;
781     }
782 }
783
784 static void
785 xlate_enqueue_action(struct wx_xlate_ctx *ctx,
786                      const struct ofp_action_enqueue *oae)
787 {
788     uint16_t ofp_port, xflow_port;
789     uint32_t priority;
790     int error;
791
792     error = xfif_queue_to_priority(ctx->wx->xfif, ntohl(oae->queue_id),
793                                    &priority);
794     if (error) {
795         /* Fall back to ordinary output action. */
796         xlate_output_action__(ctx, ntohs(oae->port), 0);
797         return;
798     }
799
800     /* Figure out xflow output port. */
801     ofp_port = ntohs(oae->port);
802     if (ofp_port != OFPP_IN_PORT) {
803         xflow_port = ofp_port_to_xflow_port(ofp_port);
804     } else {
805         xflow_port = ctx->flow.in_port;
806     }
807
808     /* Add xflow actions. */
809     remove_pop_action(ctx);
810     xflow_actions_add(ctx->out, XFLOWAT_SET_PRIORITY)->priority.priority
811         = priority;
812     add_output_action(ctx, xflow_port);
813     xflow_actions_add(ctx->out, XFLOWAT_POP_PRIORITY);
814
815     /* Update NetFlow output port. */
816     if (ctx->nf_output_iface == NF_OUT_DROP) {
817         ctx->nf_output_iface = xflow_port;
818     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
819         ctx->nf_output_iface = NF_OUT_MULTI;
820     }
821 }
822
823 static void
824 xlate_nicira_action(struct wx_xlate_ctx *ctx,
825                     const struct nx_action_header *nah)
826 {
827     const struct nx_action_resubmit *nar;
828     const struct nx_action_set_tunnel *nast;
829     union xflow_action *oa;
830     int subtype = ntohs(nah->subtype);
831
832     assert(nah->vendor == htonl(NX_VENDOR_ID));
833     switch (subtype) {
834     case NXAST_RESUBMIT:
835         nar = (const struct nx_action_resubmit *) nah;
836         xlate_table_action(ctx, ofp_port_to_xflow_port(ntohs(nar->in_port)));
837         break;
838
839     case NXAST_SET_TUNNEL:
840         nast = (const struct nx_action_set_tunnel *) nah;
841         oa = xflow_actions_add(ctx->out, XFLOWAT_SET_TUNNEL);
842         ctx->flow.tun_id = oa->tunnel.tun_id = nast->tun_id;
843         break;
844
845     /* If you add a new action here that modifies flow data, don't forget to
846      * update the flow key in ctx->flow at the same time. */
847
848     default:
849         VLOG_DBG_RL(&rl, "unknown Nicira action type %"PRIu16, subtype);
850         break;
851     }
852 }
853
854 static void
855 do_xlate_actions(const union ofp_action *in, size_t n_in,
856                  struct wx_xlate_ctx *ctx)
857 {
858     struct actions_iterator iter;
859     const union ofp_action *ia;
860     const struct wdp_port *port;
861
862     port = port_array_get(&ctx->wx->ports, ctx->flow.in_port);
863     if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
864         port->opp.config & (eth_addr_equals(ctx->flow.dl_dst, stp_eth_addr)
865                             ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
866         /* Drop this flow. */
867         return;
868     }
869
870     for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
871         uint16_t type = ntohs(ia->type);
872         union xflow_action *oa;
873
874         switch (type) {
875         case OFPAT_OUTPUT:
876             xlate_output_action(ctx, &ia->output);
877             break;
878
879         case OFPAT_SET_VLAN_VID:
880             oa = xflow_actions_add(ctx->out, XFLOWAT_SET_DL_TCI);
881             oa->dl_tci.tci = ia->vlan_vid.vlan_vid & htons(VLAN_VID_MASK);
882             oa->dl_tci.mask = htons(VLAN_VID_MASK);
883             ctx->flow.dl_vlan = ia->vlan_vid.vlan_vid;
884             break;
885
886         case OFPAT_SET_VLAN_PCP:
887             oa = xflow_actions_add(ctx->out, XFLOWAT_SET_DL_TCI);
888             oa->dl_tci.tci = htons((ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT)
889                                    & VLAN_PCP_MASK);
890             oa->dl_tci.mask = htons(VLAN_PCP_MASK);
891
892             if (ctx->flow.dl_vlan == htons(OFP_VLAN_NONE)) {
893                 ctx->flow.dl_vlan = htons(0);
894             }
895             ctx->flow.dl_vlan_pcp = ia->vlan_pcp.vlan_pcp;
896             break;
897
898         case OFPAT_STRIP_VLAN:
899             xflow_actions_add(ctx->out, XFLOWAT_STRIP_VLAN);
900             ctx->flow.dl_vlan = htons(OFP_VLAN_NONE);
901             ctx->flow.dl_vlan_pcp = 0;
902             break;
903
904         case OFPAT_SET_DL_SRC:
905             oa = xflow_actions_add(ctx->out, XFLOWAT_SET_DL_SRC);
906             memcpy(oa->dl_addr.dl_addr,
907                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
908             memcpy(ctx->flow.dl_src,
909                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
910             break;
911
912         case OFPAT_SET_DL_DST:
913             oa = xflow_actions_add(ctx->out, XFLOWAT_SET_DL_DST);
914             memcpy(oa->dl_addr.dl_addr,
915                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
916             memcpy(ctx->flow.dl_dst,
917                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
918             break;
919
920         case OFPAT_SET_NW_SRC:
921             oa = xflow_actions_add(ctx->out, XFLOWAT_SET_NW_SRC);
922             ctx->flow.nw_src = oa->nw_addr.nw_addr = ia->nw_addr.nw_addr;
923             break;
924
925         case OFPAT_SET_NW_DST:
926             oa = xflow_actions_add(ctx->out, XFLOWAT_SET_NW_DST);
927             ctx->flow.nw_dst = oa->nw_addr.nw_addr = ia->nw_addr.nw_addr;
928             break;
929
930         case OFPAT_SET_NW_TOS:
931             oa = xflow_actions_add(ctx->out, XFLOWAT_SET_NW_TOS);
932             ctx->flow.nw_tos = oa->nw_tos.nw_tos = ia->nw_tos.nw_tos;
933             break;
934
935         case OFPAT_SET_TP_SRC:
936             oa = xflow_actions_add(ctx->out, XFLOWAT_SET_TP_SRC);
937             ctx->flow.tp_src = oa->tp_port.tp_port = ia->tp_port.tp_port;
938             break;
939
940         case OFPAT_SET_TP_DST:
941             oa = xflow_actions_add(ctx->out, XFLOWAT_SET_TP_DST);
942             ctx->flow.tp_dst = oa->tp_port.tp_port = ia->tp_port.tp_port;
943             break;
944
945         case OFPAT_ENQUEUE:
946             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
947             break;
948
949         case OFPAT_VENDOR:
950             xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
951             break;
952
953         default:
954             VLOG_DBG_RL(&rl, "unknown action type %"PRIu16, type);
955             break;
956         }
957     }
958 }
959
960 /* Returns true if 'flow' and 'actions' may be set up as a flow in the kernel.
961  * This is true most of the time, but we don't allow flows that would prevent
962  * DHCP replies from being seen by the local port to be set up in the
963  * kernel.
964  *
965  * We only need this, strictly speaking, when in-band control is turned on. */
966 static bool
967 wx_may_set_up(const flow_t *flow, const struct xflow_actions *actions)
968 {
969     if (flow->dl_type == htons(ETH_TYPE_IP)
970         && flow->nw_proto == IP_TYPE_UDP
971         && flow->tp_src == htons(DHCP_SERVER_PORT)
972         && flow->tp_dst == htons(DHCP_CLIENT_PORT)) {
973         int i;
974
975         for (i = 0; i < actions->n_actions; i++) {
976             const struct xflow_action_output *oao = &actions->actions[i].output;
977             if (oao->type == XFLOWAT_OUTPUT && oao->port == XFLOWP_LOCAL) {
978                 return true;
979             }
980         }
981         return false;
982     }
983
984     return true;
985 }
986
987 static int
988 wx_xlate_actions(struct wx *wx, const union ofp_action *in, size_t n_in,
989                  const flow_t *flow, const struct ofpbuf *packet,
990                  tag_type *tags, struct xflow_actions *out,
991                  bool *may_set_up_flow)
992 {
993     tag_type no_tags = 0;
994     struct wx_xlate_ctx ctx;
995     COVERAGE_INC(wx_ofp2xflow);
996     xflow_actions_init(out);
997     ctx.flow = *flow;
998     ctx.recurse = 0;
999     ctx.wx = wx;
1000     ctx.packet = packet;
1001     ctx.out = out;
1002     ctx.tags = tags ? tags : &no_tags;
1003     ctx.may_set_up_flow = true;
1004     ctx.nf_output_iface = NF_OUT_DROP;
1005     do_xlate_actions(in, n_in, &ctx);
1006     remove_pop_action(&ctx);
1007
1008     if (may_set_up_flow) {
1009         *may_set_up_flow = ctx.may_set_up_flow && wx_may_set_up(flow, out);
1010     }
1011 #if 0
1012     if (nf_output_iface) {
1013         *nf_output_iface = ctx.nf_output_iface;
1014     }
1015 #endif
1016     if (xflow_actions_overflow(out)) {
1017         xflow_actions_init(out);
1018         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_TOO_MANY);
1019     }
1020     return 0;
1021 }
1022 \f
1023 static void
1024 update_used(struct wx *wx)
1025 {
1026     struct xflow_flow *flows;
1027     size_t n_flows;
1028     size_t i;
1029     int error;
1030
1031     error = xfif_flow_list_all(wx->xfif, &flows, &n_flows);
1032     if (error) {
1033         return;
1034     }
1035
1036     for (i = 0; i < n_flows; i++) {
1037         struct xflow_flow *f = &flows[i];
1038         struct wx_rule *rule;
1039         flow_t flow;
1040
1041         xflow_key_to_flow(&f->key, &flow);
1042         rule = wx_rule_cast(classifier_find_rule_exactly(&wx->cls, &flow));
1043         if (!rule || !rule->installed) {
1044             COVERAGE_INC(wx_unexpected_rule);
1045             xfif_flow_del(wx->xfif, f);
1046             continue;
1047         }
1048
1049         wx_rule_update_time(wx, rule, &f->stats);
1050         wx_rule_account(wx, rule, f->stats.n_bytes);
1051     }
1052     free(flows);
1053 }
1054
1055 static void
1056 uninstall_idle_flow(struct wx *wx, struct wx_rule *rule)
1057 {
1058     assert(rule->installed);
1059     assert(!rule->wr.cr.flow.wildcards);
1060
1061     if (rule->super) {
1062         wx_rule_remove(wx, rule);
1063     } else {
1064         wx_rule_uninstall(wx, rule);
1065     }
1066 }
1067
1068 static void
1069 expire_rule(struct cls_rule *cls_rule, void *wx_)
1070 {
1071     struct wx *wx = wx_;
1072     struct wx_rule *rule = wx_rule_cast(cls_rule);
1073     long long int hard_expire, idle_expire, expire, now;
1074
1075     hard_expire = (rule->wr.hard_timeout
1076                    ? rule->wr.created + rule->wr.hard_timeout * 1000
1077                    : LLONG_MAX);
1078     idle_expire = (rule->wr.idle_timeout
1079                    && (rule->super || list_is_empty(&rule->list))
1080                    ? rule->used + rule->wr.idle_timeout * 1000
1081                    : LLONG_MAX);
1082     expire = MIN(hard_expire, idle_expire);
1083
1084     now = time_msec();
1085     if (now < expire) {
1086         if (rule->installed && now >= rule->used + 5000) {
1087             uninstall_idle_flow(wx, rule);
1088         } else if (!rule->wr.cr.flow.wildcards) {
1089             //XXX active_timeout(wx, rule);
1090         }
1091
1092         return;
1093     }
1094
1095     COVERAGE_INC(wx_expired);
1096
1097     /* Update stats.  This code will be a no-op if the rule expired
1098      * due to an idle timeout. */
1099     if (rule->wr.cr.flow.wildcards) {
1100         struct wx_rule *subrule, *next;
1101         LIST_FOR_EACH_SAFE (subrule, next, struct wx_rule, list, &rule->list) {
1102             wx_rule_remove(wx, subrule);
1103         }
1104     } else {
1105         wx_rule_uninstall(wx, rule);
1106     }
1107
1108 #if 0                           /* XXX */
1109     if (!wx_rule_is_hidden(rule)) {
1110         send_flow_removed(wx, rule, now,
1111                           (now >= hard_expire
1112                            ? OFPRR_HARD_TIMEOUT : OFPRR_IDLE_TIMEOUT));
1113     }
1114 #endif
1115     wx_rule_remove(wx, rule);
1116 }
1117
1118 struct revalidate_cbdata {
1119     struct wx *wx;
1120     bool revalidate_all;        /* Revalidate all exact-match rules? */
1121     bool revalidate_subrules;   /* Revalidate all exact-match subrules? */
1122     struct tag_set revalidate_set; /* Set of tags to revalidate. */
1123 };
1124
1125 static bool
1126 revalidate_rule(struct wx *wx, struct wx_rule *rule)
1127 {
1128     const flow_t *flow = &rule->wr.cr.flow;
1129
1130     COVERAGE_INC(wx_revalidate_rule);
1131     if (rule->super) {
1132         struct wx_rule *super;
1133         super = wx_rule_cast(classifier_lookup_wild(&wx->cls, flow));
1134         if (!super) {
1135             wx_rule_remove(wx, rule);
1136             return false;
1137         } else if (super != rule->super) {
1138             COVERAGE_INC(wx_revalidate_moved);
1139             list_remove(&rule->list);
1140             list_push_back(&super->list, &rule->list);
1141             rule->super = super;
1142             rule->wr.hard_timeout = super->wr.hard_timeout;
1143             rule->wr.idle_timeout = super->wr.idle_timeout;
1144             rule->wr.created = super->wr.created;
1145             rule->used = 0;
1146         }
1147     }
1148
1149     wx_rule_update_actions(wx, rule);
1150     return true;
1151 }
1152
1153 static void
1154 revalidate_cb(struct cls_rule *sub_, void *cbdata_)
1155 {
1156     struct wx_rule *sub = wx_rule_cast(sub_);
1157     struct revalidate_cbdata *cbdata = cbdata_;
1158
1159     if (cbdata->revalidate_all
1160         || (cbdata->revalidate_subrules && sub->super)
1161         || tag_set_intersects(&cbdata->revalidate_set, sub->tags)) {
1162         revalidate_rule(cbdata->wx, sub);
1163     }
1164 }
1165
1166 static void
1167 wx_run_one(struct wx *wx)
1168 {
1169     if (time_msec() >= wx->next_expiration) {
1170         COVERAGE_INC(wx_expiration);
1171         wx->next_expiration = time_msec() + 1000;
1172         update_used(wx);
1173
1174         classifier_for_each(&wx->cls, CLS_INC_ALL, expire_rule, wx);
1175
1176         /* XXX account_checkpoint_cb */
1177     }
1178
1179     if (wx->need_revalidate || !tag_set_is_empty(&wx->revalidate_set)) {
1180         struct revalidate_cbdata cbdata;
1181         cbdata.wx = wx;
1182         cbdata.revalidate_all = wx->revalidate_all;
1183         cbdata.revalidate_subrules = wx->need_revalidate;
1184         cbdata.revalidate_set = wx->revalidate_set;
1185         tag_set_init(&wx->revalidate_set);
1186         COVERAGE_INC(wx_revalidate);
1187         classifier_for_each(&wx->cls, CLS_INC_EXACT, revalidate_cb, &cbdata);
1188         wx->need_revalidate = false;
1189     }
1190 }
1191
1192 static void
1193 wx_run(void)
1194 {
1195     struct wx *wx;
1196
1197     LIST_FOR_EACH (wx, struct wx, list_node, &all_wx) {
1198         wx_run_one(wx);
1199     }
1200     xf_run();
1201 }
1202
1203 static void
1204 wx_wait_one(struct wx *wx)
1205 {
1206     if (wx->need_revalidate || !tag_set_is_empty(&wx->revalidate_set)) {
1207         poll_immediate_wake();
1208     } else if (wx->next_expiration != LLONG_MAX) {
1209         poll_timer_wait_until(wx->next_expiration);
1210     }
1211 }
1212
1213 static void
1214 wx_wait(void)
1215 {
1216     struct wx *wx;
1217
1218     LIST_FOR_EACH (wx, struct wx, list_node, &all_wx) {
1219         wx_wait_one(wx);
1220     }
1221     xf_wait();
1222 }
1223 \f
1224 static int wx_flow_flush(struct wdp *);
1225
1226 static int
1227 wx_enumerate(const struct wdp_class *wdp_class, struct svec *all_wdps)
1228 {
1229     struct svec names = SVEC_EMPTY_INITIALIZER;
1230     int error = xf_enumerate_names(wdp_class->type, &names);
1231     svec_move(all_wdps, &names);
1232     return error;
1233 }
1234
1235 static int
1236 wx_open(const struct wdp_class *wdp_class, const char *name, bool create,
1237         struct wdp **wdpp)
1238 {
1239     struct xfif *xfif;
1240     int error;
1241
1242     error = (create
1243              ? xfif_create_and_open(name, wdp_class->type, &xfif)
1244              : xfif_open(name, wdp_class->type, &xfif));
1245     if (!error) {
1246         struct wx *wx;
1247
1248         wx = xzalloc(sizeof *wx);
1249         list_push_back(&all_wx, &wx->list_node);
1250         wdp_init(&wx->wdp, wdp_class, name, 0, 0);
1251         wx->xfif = xfif;
1252         classifier_init(&wx->cls);
1253         wx->netdev_monitor = netdev_monitor_create();
1254         port_array_init(&wx->ports);
1255         shash_init(&wx->port_by_name);
1256         wx->next_expiration = time_msec() + 1000;
1257         tag_set_init(&wx->revalidate_set);
1258
1259         wx_port_init(wx);
1260
1261         wx->ofhooks = &default_ofhooks;
1262         wx->aux = wx;
1263         wx->ml = mac_learning_create();
1264
1265         *wdpp = &wx->wdp;
1266     }
1267
1268     return error;
1269 }
1270
1271 static void
1272 wx_close(struct wdp *wdp)
1273 {
1274     struct wx *wx = wx_cast(wdp);
1275
1276     wx_flow_flush(wdp);
1277     xfif_close(wx->xfif);
1278     classifier_destroy(&wx->cls);
1279     netdev_monitor_destroy(wx->netdev_monitor);
1280     list_remove(&wx->list_node);
1281     mac_learning_destroy(wx->ml);
1282     free(wx);
1283 }
1284
1285 static int
1286 wx_get_all_names(const struct wdp *wdp, struct svec *all_names)
1287 {
1288     struct wx *wx = wx_cast(wdp);
1289
1290     return xfif_get_all_names(wx->xfif, all_names);
1291 }
1292
1293 static int
1294 wx_destroy(struct wdp *wdp)
1295 {
1296     struct wx *wx = wx_cast(wdp);
1297
1298     return xfif_delete(wx->xfif);
1299 }
1300
1301 static int
1302 wx_get_features(const struct wdp *wdp, struct ofpbuf **featuresp)
1303 {
1304     struct wx *wx = wx_cast(wdp);
1305     struct ofp_switch_features *osf;
1306     struct ofpbuf *buf;
1307     unsigned int port_no;
1308     struct wdp_port *port;
1309
1310     buf = ofpbuf_new(sizeof *osf);
1311     osf = ofpbuf_put_zeros(buf, sizeof *osf);
1312     osf->n_tables = 2;
1313     osf->capabilities = htonl(OFPC_ARP_MATCH_IP);
1314     osf->actions = htonl((1u << OFPAT_OUTPUT) |
1315                          (1u << OFPAT_SET_VLAN_VID) |
1316                          (1u << OFPAT_SET_VLAN_PCP) |
1317                          (1u << OFPAT_STRIP_VLAN) |
1318                          (1u << OFPAT_SET_DL_SRC) |
1319                          (1u << OFPAT_SET_DL_DST) |
1320                          (1u << OFPAT_SET_NW_SRC) |
1321                          (1u << OFPAT_SET_NW_DST) |
1322                          (1u << OFPAT_SET_NW_TOS) |
1323                          (1u << OFPAT_SET_TP_SRC) |
1324                          (1u << OFPAT_SET_TP_DST) |
1325                          (1u << OFPAT_ENQUEUE));
1326
1327     PORT_ARRAY_FOR_EACH (port, &wx->ports, port_no) {
1328         hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
1329     }
1330
1331     *featuresp = buf;
1332     return 0;
1333 }
1334
1335 static void
1336 count_subrules(struct cls_rule *cls_rule, void *n_subrules_)
1337 {
1338     struct wx_rule *rule = wx_rule_cast(cls_rule);
1339     int *n_subrules = n_subrules_;
1340
1341     if (rule->super) {
1342         (*n_subrules)++;
1343     }
1344 }
1345
1346 static int
1347 wx_get_stats(const struct wdp *wdp, struct wdp_stats *stats)
1348 {
1349     struct wx *wx = wx_cast(wdp);
1350     struct xflow_stats xflow_stats;
1351     int error;
1352
1353     error = xfif_get_xf_stats(wx->xfif, &xflow_stats);
1354     stats->max_ports = xflow_stats.max_ports;
1355     return error;
1356 }
1357
1358 static int
1359 wx_get_table_stats(const struct wdp *wdp, struct ofpbuf *stats)
1360 {
1361     struct wx *wx = wx_cast(wdp);
1362     struct xflow_stats xflow_stats;
1363     struct ofp_table_stats *exact, *wild;
1364     int n_subrules;
1365
1366     xfif_get_xf_stats(wx->xfif, &xflow_stats);
1367     /* XXX should pass up errors, but there are no appropriate OpenFlow error
1368      * codes. */
1369
1370     n_subrules = 0;
1371     classifier_for_each(&wx->cls, CLS_INC_EXACT, count_subrules, &n_subrules);
1372
1373     exact = ofpbuf_put_zeros(stats, sizeof *exact);
1374     exact->table_id = TABLEID_HASH;
1375     strcpy(exact->name, "exact");
1376     exact->wildcards = htonl(0);
1377     exact->max_entries = htonl(MIN(WX_MAX_EXACT, xflow_stats.max_capacity));
1378     exact->active_count = htonl(classifier_count_exact(&wx->cls) - n_subrules);
1379     exact->lookup_count = htonll(xflow_stats.n_hit + xflow_stats.n_missed);
1380     exact->matched_count = htonll(xflow_stats.n_hit);
1381
1382     wild = ofpbuf_put_zeros(stats, sizeof *exact);
1383     wild->table_id = TABLEID_CLASSIFIER;
1384     strcpy(wild->name, "classifier");
1385     wild->wildcards = htonl(OVSFW_ALL);
1386     wild->max_entries = htonl(WX_MAX_WILD);
1387     wild->active_count = htonl(classifier_count_wild(&wx->cls));
1388     wild->lookup_count = htonll(0);  /* XXX */
1389     wild->matched_count = htonll(0); /* XXX */
1390
1391     return 0;
1392 }
1393
1394 static int
1395 wx_get_drop_frags(const struct wdp *wdp, bool *drop_frags)
1396 {
1397     struct wx *wx = wx_cast(wdp);
1398
1399     return xfif_get_drop_frags(wx->xfif, drop_frags);
1400 }
1401
1402 static int
1403 wx_set_drop_frags(struct wdp *wdp, bool drop_frags)
1404 {
1405     struct wx *wx = wx_cast(wdp);
1406
1407     return xfif_set_drop_frags(wx->xfif, drop_frags);
1408 }
1409
1410 static int
1411 wx_port_add(struct wdp *wdp, const char *devname,
1412             bool internal, uint16_t *port_no)
1413 {
1414     struct wx *wx = wx_cast(wdp);
1415     uint16_t xflow_flags = internal ? XFLOW_PORT_INTERNAL : 0;
1416     return xfif_port_add(wx->xfif, devname, xflow_flags, port_no);
1417 }
1418
1419 static int
1420 wx_port_del(struct wdp *wdp, uint16_t port_no)
1421 {
1422     struct wx *wx = wx_cast(wdp);
1423
1424     return xfif_port_del(wx->xfif, port_no);
1425 }
1426
1427 static int
1428 wx_answer_port_query(const struct wdp_port *port, struct wdp_port *portp)
1429 {
1430     if (port) {
1431         wdp_port_copy(portp, port);
1432         return 0;
1433     } else {
1434         return ENOENT;
1435     }
1436 }
1437
1438 static int
1439 wx_port_query_by_number(const struct wdp *wdp, uint16_t port_no,
1440                         struct wdp_port *portp)
1441 {
1442     struct wx *wx = wx_cast(wdp);
1443     const struct wdp_port *port;
1444
1445     port = port_array_get(&wx->ports, ofp_port_to_xflow_port(port_no));
1446     return wx_answer_port_query(port, portp);
1447 }
1448
1449 static int
1450 wx_port_query_by_name(const struct wdp *wdp, const char *devname,
1451                       struct wdp_port *portp)
1452 {
1453     struct wx *wx = wx_cast(wdp);
1454
1455     return wx_answer_port_query(shash_find_data(&wx->port_by_name, devname),
1456                                 portp);
1457 }
1458
1459 static int
1460 wx_port_set_config(struct wdp *wdp, uint16_t port_no, uint32_t config)
1461 {
1462     struct wx *wx = wx_cast(wdp);
1463     struct wdp_port *port;
1464     uint32_t changes;
1465
1466     port = port_array_get(&wx->ports, ofp_port_to_xflow_port(port_no));
1467     if (!port) {
1468         return ENOENT;
1469     }
1470     changes = config ^ port->opp.config;
1471
1472     if (changes & OFPPC_PORT_DOWN) {
1473         int error;
1474         if (config & OFPPC_PORT_DOWN) {
1475             error = netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
1476         } else {
1477             error = netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
1478         }
1479         if (!error) {
1480             port->opp.config ^= OFPPC_PORT_DOWN;
1481         }
1482     }
1483
1484 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP | OFPPC_NO_FWD)
1485     if (changes & REVALIDATE_BITS) {
1486         COVERAGE_INC(wx_costly_flags);
1487         port->opp.config ^= changes & REVALIDATE_BITS;
1488         wx->need_revalidate = true;
1489     }
1490 #undef REVALIDATE_BITS
1491
1492     if (changes & OFPPC_NO_FLOOD) {
1493         port->opp.config ^= OFPPC_NO_FLOOD;
1494         wx_port_refresh_groups(wx);
1495     }
1496
1497     if (changes & OFPPC_NO_PACKET_IN) {
1498         port->opp.config ^= OFPPC_NO_PACKET_IN;
1499     }
1500
1501     return 0;
1502 }
1503
1504 static int
1505 wx_port_list(const struct wdp *wdp, struct wdp_port **portsp, size_t *n_portsp)
1506 {
1507     struct wx *wx = wx_cast(wdp);
1508     struct wdp_port *ports, *port;
1509     unsigned int port_no;
1510     size_t n_ports, i;
1511
1512     *n_portsp = n_ports = port_array_count(&wx->ports);
1513     *portsp = ports = xmalloc(n_ports * sizeof *ports);
1514     i = 0;
1515     PORT_ARRAY_FOR_EACH (port, &wx->ports, port_no) {
1516         wdp_port_copy(&ports[i++], port);
1517     }
1518     assert(i == n_ports);
1519
1520     return 0;
1521 }
1522
1523 static int
1524 wx_port_poll(struct wdp *wdp, wdp_port_poll_cb_func *cb, void *aux)
1525 {
1526     struct wx *wx = wx_cast(wdp);
1527     char *devname;
1528     int retval;
1529     int error;
1530
1531     retval = 0;
1532     while ((error = xfif_port_poll(wx->xfif, &devname)) != EAGAIN) {
1533         wx_port_process_change(wx, error, devname, cb, aux);
1534         if (error && error != ENOBUFS) {
1535             retval = error;
1536         }
1537     }
1538     while ((error = netdev_monitor_poll(wx->netdev_monitor,
1539                                         &devname)) != EAGAIN) {
1540         wx_port_process_change(wx, error, devname, cb, aux);
1541         if (error && error != ENOBUFS) {
1542             retval = error;
1543         }
1544     }
1545     return retval;
1546 }
1547
1548 static int
1549 wx_port_poll_wait(const struct wdp *wdp)
1550 {
1551     struct wx *wx = wx_cast(wdp);
1552
1553     xfif_port_poll_wait(wx->xfif);
1554     netdev_monitor_poll_wait(wx->netdev_monitor);
1555     return 0;
1556 }
1557
1558 static struct wdp_rule *
1559 wx_flow_get(const struct wdp *wdp, const flow_t *flow, unsigned int include)
1560 {
1561     struct wx *wx = wx_cast(wdp);
1562     struct wx_rule *rule;
1563     int table_id;
1564
1565     table_id = flow->wildcards ? TABLEID_CLASSIFIER : TABLEID_HASH;
1566     if (!(include & (1u << table_id))) {
1567         return NULL;
1568     }
1569
1570     rule = wx_rule_cast(classifier_find_rule_exactly(&wx->cls, flow));
1571     return rule && !wx_rule_is_hidden(rule) ? &rule->wr : NULL;
1572 }
1573
1574 static struct wdp_rule *
1575 wx_flow_match(const struct wdp *wdp, const flow_t *flow)
1576 {
1577     struct wx *wx = wx_cast(wdp);
1578     struct wx_rule *rule;
1579
1580     rule = wx_rule_cast(classifier_lookup(&wx->cls, flow));
1581     if (rule) {
1582         if (wx_rule_is_hidden(rule)) {
1583             rule = rule->super;
1584         }
1585         return &rule->wr;
1586     } else {
1587         return NULL;
1588     }
1589 }
1590
1591 struct wx_for_each_thunk_aux {
1592     wdp_flow_cb_func *client_callback;
1593     void *client_aux;
1594 };
1595
1596 static void
1597 wx_for_each_thunk(struct cls_rule *cls_rule, void *aux_)
1598 {
1599     struct wx_for_each_thunk_aux *aux = aux_;
1600     struct wx_rule *rule = wx_rule_cast(cls_rule);
1601
1602     if (!wx_rule_is_hidden(rule)) {
1603         aux->client_callback(&rule->wr, aux->client_aux);
1604     }
1605 }
1606
1607 static void
1608 wx_flow_for_each_match(const struct wdp *wdp, const flow_t *target,
1609                        unsigned int include,
1610                        wdp_flow_cb_func *client_callback, void *client_aux)
1611 {
1612     struct wx *wx = wx_cast(wdp);
1613     struct wx_for_each_thunk_aux aux;
1614     int cls_include;
1615
1616     cls_include = 0;
1617     if (include & (1u << TABLEID_HASH)) {
1618         cls_include |= CLS_INC_EXACT;
1619     }
1620     if (include & (1u << TABLEID_CLASSIFIER)) {
1621         cls_include |= CLS_INC_WILD;
1622     }
1623
1624     aux.client_callback = client_callback;
1625     aux.client_aux = client_aux;
1626     classifier_for_each_match(&wx->cls, target, cls_include,
1627                               wx_for_each_thunk, &aux);
1628 }
1629
1630 /* Obtains statistic counters for 'rule' within 'wx' and stores them into
1631  * '*stats'.  If 'rule' is a wildcarded rule, the returned statistic include
1632  * statistics for all of 'rule''s subrules. */
1633 static void
1634 query_stats(struct wx *wx, struct wx_rule *rule, struct wdp_flow_stats *stats)
1635 {
1636     struct wx_rule *subrule;
1637     struct xflow_flow *xflow_flows;
1638     size_t n_xflow_flows;
1639
1640     /* Start from historical data for 'rule' itself that are no longer tracked
1641      * by the datapath.  This counts, for example, subrules that have
1642      * expired. */
1643     stats->n_packets = rule->packet_count;
1644     stats->n_bytes = rule->byte_count;
1645     stats->inserted = rule->wr.created;
1646     stats->used = LLONG_MIN;
1647     stats->tcp_flags = 0;
1648     stats->ip_tos = 0;
1649
1650     /* Prepare to ask the datapath for statistics on 'rule', or if it is
1651      * wildcarded then on all of its subrules.
1652      *
1653      * Also, add any statistics that are not tracked by the datapath for each
1654      * subrule.  This includes, for example, statistics for packets that were
1655      * executed "by hand" by ofproto via xfif_execute() but must be accounted
1656      * to a flow. */
1657     n_xflow_flows = rule->wr.cr.flow.wildcards ? list_size(&rule->list) : 1;
1658     xflow_flows = xzalloc(n_xflow_flows * sizeof *xflow_flows);
1659     if (rule->wr.cr.flow.wildcards) {
1660         size_t i = 0;
1661         LIST_FOR_EACH (subrule, struct wx_rule, list, &rule->list) {
1662             xflow_key_from_flow(&xflow_flows[i++].key, &subrule->wr.cr.flow);
1663             stats->n_packets += subrule->packet_count;
1664             stats->n_bytes += subrule->byte_count;
1665         }
1666     } else {
1667         xflow_key_from_flow(&xflow_flows[0].key, &rule->wr.cr.flow);
1668     }
1669
1670     /* Fetch up-to-date statistics from the datapath and add them in. */
1671     if (!xfif_flow_get_multiple(wx->xfif, xflow_flows, n_xflow_flows)) {
1672         size_t i;
1673         for (i = 0; i < n_xflow_flows; i++) {
1674             struct xflow_flow *xflow_flow = &xflow_flows[i];
1675             long long int used;
1676
1677             stats->n_packets += xflow_flow->stats.n_packets;
1678             stats->n_bytes += xflow_flow->stats.n_bytes;
1679             used = xflow_flow_stats_to_msec(&xflow_flow->stats);
1680             if (used > stats->used) {
1681                 stats->used = used;
1682             }
1683             stats->tcp_flags |= xflow_flow->stats.tcp_flags;
1684         }
1685     }
1686     free(xflow_flows);
1687 }
1688
1689 static int
1690 wx_flow_get_stats(const struct wdp *wdp,
1691                   const struct wdp_rule *wdp_rule,
1692                   struct wdp_flow_stats *stats)
1693 {
1694     struct wx *wx = wx_cast(wdp);
1695     struct wx_rule *rule = wx_rule_cast(&wdp_rule->cr);
1696
1697     query_stats(wx, rule, stats);
1698     return 0;
1699 }
1700
1701 static bool
1702 wx_flow_overlaps(const struct wdp *wdp, const flow_t *flow)
1703 {
1704     struct wx *wx = wx_cast(wdp);
1705
1706     /* XXX overlap with a subrule? */
1707     return classifier_rule_overlaps(&wx->cls, flow);
1708 }
1709
1710 static int
1711 wx_flow_put(struct wdp *wdp, const struct wdp_flow_put *put,
1712             struct wdp_flow_stats *old_stats, struct wdp_rule **rulep)
1713 {
1714     struct wx *wx = wx_cast(wdp);
1715     struct wx_rule *rule;
1716     uint8_t ofp_table_id;
1717
1718     ofp_table_id = put->flow->wildcards ? TABLEID_CLASSIFIER : TABLEID_HASH;
1719     if (put->ofp_table_id != 0xff && put->ofp_table_id != ofp_table_id) {
1720         return EINVAL;
1721     }
1722
1723     rule = wx_rule_cast(classifier_find_rule_exactly(&wx->cls, put->flow));
1724     if (rule && wx_rule_is_hidden(rule)) {
1725         rule = NULL;
1726     }
1727
1728     if (rule) {
1729         if (!(put->flags & WDP_PUT_MODIFY)) {
1730             return EEXIST;
1731         }
1732     } else {
1733         if (!(put->flags & WDP_PUT_CREATE)) {
1734             return EINVAL;
1735         }
1736         if ((put->flow->wildcards
1737              ? classifier_count_wild(&wx->cls) >= WX_MAX_WILD
1738              : classifier_count_exact(&wx->cls) >= WX_MAX_EXACT)) {
1739             /* XXX subrules should not count against exact-match limit */
1740             return ENOBUFS;
1741         }
1742     }
1743
1744     rule = wx_rule_create(NULL, put->actions, put->n_actions,
1745                           put->idle_timeout, put->hard_timeout);
1746     cls_rule_from_flow(put->flow, &rule->wr.cr);
1747     rule->wr.ofp_table_id = ofp_table_id;
1748     wx_rule_insert(wx, rule, NULL, 0);
1749
1750     if (old_stats) {
1751         /* XXX */
1752         memset(old_stats, 0, sizeof *old_stats);
1753     }
1754     if (rulep) {
1755         *rulep = &rule->wr;
1756     }
1757
1758     return 0;
1759 }
1760
1761 static int
1762 wx_flow_delete(struct wdp *wdp, struct wdp_rule *wdp_rule,
1763                struct wdp_flow_stats *final_stats)
1764 {
1765     struct wx *wx = wx_cast(wdp);
1766     struct wx_rule *rule = wx_rule_cast(&wdp_rule->cr);
1767
1768     wx_rule_remove(wx, rule);
1769     if (final_stats) {
1770         memset(final_stats, 0, sizeof *final_stats); /* XXX */
1771     }
1772     return 0;
1773 }
1774
1775 static void
1776 wx_flush_rule(struct cls_rule *cls_rule, void *wx_)
1777 {
1778     struct wx_rule *rule = wx_rule_cast(cls_rule);
1779     struct wx *wx = wx_;
1780
1781     /* Mark the flow as not installed, even though it might really be
1782      * installed, so that wx_rule_remove() doesn't bother trying to uninstall
1783      * it.  There is no point in uninstalling it individually since we are
1784      * about to blow away all the flows with xfif_flow_flush(). */
1785     rule->installed = false;
1786
1787     wx_rule_remove(wx, rule);
1788 }
1789
1790 static int
1791 wx_flow_flush(struct wdp *wdp)
1792 {
1793     struct wx *wx = wx_cast(wdp);
1794
1795     COVERAGE_INC(wx_flow_flush);
1796     classifier_for_each(&wx->cls, CLS_INC_ALL, wx_flush_rule, wx);
1797     xfif_flow_flush(wx->xfif);
1798     return 0;
1799 }
1800
1801 static int
1802 wx_execute(struct wdp *wdp, uint16_t in_port,
1803            const union ofp_action actions[], int n_actions,
1804            const struct ofpbuf *packet)
1805 {
1806     struct wx *wx = wx_cast(wdp);
1807     struct xflow_actions xflow_actions;
1808     flow_t flow;
1809     int error;
1810
1811     flow_extract((struct ofpbuf *) packet, 0, in_port, &flow);
1812     error = wx_xlate_actions(wx, actions, n_actions, &flow, packet,
1813                              NULL, &xflow_actions, NULL);
1814     if (error) {
1815         return error;
1816     }
1817     xfif_execute(wx->xfif, ofp_port_to_xflow_port(in_port),
1818                  xflow_actions.actions, xflow_actions.n_actions, packet);
1819     return 0;
1820 }
1821
1822 static int
1823 wx_flow_inject(struct wdp *wdp, struct wdp_rule *wdp_rule,
1824                uint16_t in_port, const struct ofpbuf *packet)
1825 {
1826     struct wx_rule *rule = wx_rule_cast(&wdp_rule->cr);
1827     int error;
1828
1829     error = wx_execute(wdp, in_port, rule->wr.actions, rule->wr.n_actions,
1830                        packet);
1831     if (!error) {
1832         rule->packet_count++;
1833         rule->byte_count += packet->size;
1834         rule->used = time_msec();
1835     }
1836     return error;
1837 }
1838
1839 static int
1840 wx_recv_get_mask(const struct wdp *wdp, int *listen_mask)
1841 {
1842     struct wx *wx = wx_cast(wdp);
1843     int xflow_listen_mask;
1844     int error;
1845
1846     error = xfif_recv_get_mask(wx->xfif, &xflow_listen_mask);
1847     if (!error) {
1848         *listen_mask = 0;
1849         if (xflow_listen_mask & XFLOWL_MISS) {
1850             *listen_mask |= 1 << WDP_CHAN_MISS;
1851         }
1852         if (xflow_listen_mask & XFLOWL_ACTION) {
1853             *listen_mask |= 1 << WDP_CHAN_ACTION;
1854         }
1855         if (xflow_listen_mask & XFLOWL_SFLOW) {
1856             *listen_mask |= 1 << WDP_CHAN_SFLOW;
1857         }
1858     }
1859     return error;
1860 }
1861
1862 static int
1863 wx_recv_set_mask(struct wdp *wdp, int listen_mask)
1864 {
1865     struct wx *wx = wx_cast(wdp);
1866     int xflow_listen_mask;
1867
1868     xflow_listen_mask = 0;
1869     if (listen_mask & (1 << WDP_CHAN_MISS)) {
1870         xflow_listen_mask |= XFLOWL_MISS;
1871     }
1872     if (listen_mask & (1 << WDP_CHAN_ACTION)) {
1873         xflow_listen_mask |= XFLOWL_ACTION;
1874     }
1875     if (listen_mask & (1 << WDP_CHAN_SFLOW)) {
1876         xflow_listen_mask |= XFLOWL_SFLOW;
1877     }
1878
1879     return xfif_recv_set_mask(wx->xfif, xflow_listen_mask);
1880 }
1881
1882 static int
1883 wx_get_sflow_probability(const struct wdp *wdp, uint32_t *probability)
1884 {
1885     struct wx *wx = wx_cast(wdp);
1886
1887     return xfif_get_sflow_probability(wx->xfif, probability);
1888 }
1889
1890 static int
1891 wx_set_sflow_probability(struct wdp *wdp, uint32_t probability)
1892 {
1893     struct wx *wx = wx_cast(wdp);
1894
1895     return xfif_set_sflow_probability(wx->xfif, probability);
1896 }
1897
1898 static int
1899 wx_translate_xflow_msg(struct xflow_msg *msg, struct ofpbuf *payload,
1900                        struct wdp_packet *packet)
1901 {
1902     packet->in_port = xflow_port_to_ofp_port(msg->port);
1903     packet->send_len = 0;
1904     packet->tun_id = 0;
1905
1906     switch (msg->type) {
1907     case _XFLOWL_MISS_NR:
1908         packet->channel = WDP_CHAN_MISS;
1909         packet->payload = payload;
1910         packet->tun_id = msg->arg;
1911         return 0;
1912
1913     case _XFLOWL_ACTION_NR:
1914         packet->channel = WDP_CHAN_ACTION;
1915         packet->payload = payload;
1916         packet->send_len = msg->arg;
1917         return 0;
1918
1919     case _XFLOWL_SFLOW_NR:
1920         /* XXX */
1921         ofpbuf_delete(payload);
1922         return ENOSYS;
1923
1924     default:
1925         VLOG_WARN_RL(&rl, "received XFLOW message of unexpected type %"PRIu32,
1926                      msg->type);
1927         ofpbuf_delete(payload);
1928         return ENOSYS;
1929     }
1930 }
1931
1932 static const uint8_t *
1933 get_local_mac(const struct wx *wx)
1934 {
1935     const struct wdp_port *port = port_array_get(&wx->ports, XFLOWP_LOCAL);
1936     return port ? port->opp.hw_addr : NULL;
1937 }
1938
1939 /* Returns true if 'packet' is a DHCP reply to the local port.  Such a reply
1940  * should be sent to the local port regardless of the flow table.
1941  *
1942  * We only need this, strictly speaking, when in-band control is turned on. */
1943 static bool
1944 wx_is_local_dhcp_reply(const struct wx *wx,
1945                        const flow_t *flow, const struct ofpbuf *packet)
1946 {
1947     if (flow->dl_type == htons(ETH_TYPE_IP)
1948         && flow->nw_proto == IP_TYPE_UDP
1949         && flow->tp_src == htons(DHCP_SERVER_PORT)
1950         && flow->tp_dst == htons(DHCP_CLIENT_PORT)
1951         && packet->l7)
1952     {
1953         const uint8_t *local_mac = get_local_mac(wx);
1954         struct dhcp_header *dhcp = ofpbuf_at(
1955             packet, (char *)packet->l7 - (char *)packet->data, sizeof *dhcp);
1956         return dhcp && local_mac && eth_addr_equals(dhcp->chaddr, local_mac);
1957     }
1958
1959     return false;
1960 }
1961
1962 static bool
1963 wx_explode_rule(struct wx *wx, struct xflow_msg *msg, struct ofpbuf *payload)
1964 {
1965     struct wx_rule *rule;
1966     flow_t flow;
1967
1968     flow_extract(payload, 0, xflow_port_to_ofp_port(msg->port), &flow);
1969
1970     if (wx_is_local_dhcp_reply(wx, &flow, payload)) {
1971         union xflow_action action;
1972
1973         memset(&action, 0, sizeof(action));
1974         action.output.type = XFLOWAT_OUTPUT;
1975         action.output.port = XFLOWP_LOCAL;
1976         xfif_execute(wx->xfif, msg->port, &action, 1, payload);
1977     }
1978
1979     rule = wx_rule_lookup_valid(wx, &flow);
1980     if (!rule) {
1981         return false;
1982     }
1983
1984     if (rule->wr.cr.flow.wildcards) {
1985         rule = wx_rule_create_subrule(wx, rule, &flow);
1986         wx_rule_make_actions(wx, rule, payload);
1987     } else {
1988         if (!rule->may_install) {
1989             /* The rule is not installable, that is, we need to process every
1990              * packet, so process the current packet and set its actions into
1991              * 'subrule'. */
1992             wx_rule_make_actions(wx, rule, payload);
1993         } else {
1994             /* XXX revalidate rule if it needs it */
1995         }
1996     }
1997
1998     wx_rule_execute(wx, rule, payload, &flow);
1999     wx_rule_reinstall(wx, rule);
2000
2001     return true;
2002 }
2003
2004 static int
2005 wx_recv(struct wdp *wdp, struct wdp_packet *packet)
2006 {
2007     struct wx *wx = wx_cast(wdp);
2008     int i;
2009
2010     /* XXX need to avoid 50*50 potential cost for caller. */
2011     for (i = 0; i < 50; i++) {
2012         struct xflow_msg *msg;
2013         struct ofpbuf *buf;
2014         int error;
2015
2016         error = xfif_recv(wx->xfif, &buf);
2017         if (error) {
2018             return error;
2019         }
2020
2021         msg = ofpbuf_pull(buf, sizeof *msg);
2022         if (msg->type != _XFLOWL_MISS_NR || !wx_explode_rule(wx, msg, buf)) {
2023             return wx_translate_xflow_msg(msg, buf, packet);
2024         }
2025         ofpbuf_delete(buf);
2026     }
2027     return EAGAIN;
2028 }
2029
2030 static void
2031 wx_recv_purge_queue__(struct wx *wx, int max, int xflow_listen_mask,
2032                       int *errorp)
2033 {
2034     int error;
2035
2036     error = xfif_recv_set_mask(wx->xfif, xflow_listen_mask);
2037     if (!error) {
2038         struct ofpbuf *buf;
2039
2040         while (max > 0 && (error = xfif_recv(wx->xfif, &buf)) == 0) {
2041             ofpbuf_delete(buf);
2042             max--;
2043         }
2044     }
2045     if (error && error != EAGAIN) {
2046         *errorp = error;
2047     }
2048 }
2049
2050 static int
2051 wx_recv_purge(struct wdp *wdp)
2052 {
2053     struct wx *wx = wx_cast(wdp);
2054     struct xflow_stats xflow_stats;
2055     int xflow_listen_mask;
2056     int retval, error;
2057
2058     xfif_get_xf_stats(wx->xfif, &xflow_stats);
2059
2060     error = xfif_recv_get_mask(wx->xfif, &xflow_listen_mask);
2061     if (error || !(xflow_listen_mask & XFLOWL_ALL)) {
2062         return error;
2063     }
2064
2065     if (xflow_listen_mask & XFLOWL_MISS) {
2066         wx_recv_purge_queue__(wx, xflow_stats.max_miss_queue, XFLOWL_MISS,
2067                               &error);
2068     }
2069     if (xflow_listen_mask & XFLOWL_ACTION) {
2070         wx_recv_purge_queue__(wx, xflow_stats.max_action_queue, XFLOWL_ACTION,
2071                               &error);
2072     }
2073     if (xflow_listen_mask & XFLOWL_SFLOW) {
2074         wx_recv_purge_queue__(wx, xflow_stats.max_sflow_queue, XFLOWL_SFLOW,
2075                               &error);
2076     }
2077
2078     retval = xfif_recv_set_mask(wx->xfif, xflow_listen_mask);
2079     return retval ? retval : error;
2080 }
2081
2082
2083 static void
2084 wx_recv_wait(struct wdp *wdp)
2085 {
2086     struct wx *wx = wx_cast(wdp);
2087
2088     xfif_recv_wait(wx->xfif);
2089 }
2090
2091 static int
2092 wx_set_ofhooks(struct wdp *wdp, const struct ofhooks *ofhooks, void *aux)
2093 {
2094     struct wx *wx = wx_cast(wdp);
2095
2096     if (wx->ofhooks == &default_ofhooks) {
2097         mac_learning_destroy(wx->ml);
2098         wx->ml = NULL;
2099     }
2100
2101     wx->ofhooks = ofhooks;
2102     wx->aux = aux;
2103     return 0;
2104 }
2105
2106 static void
2107 wx_revalidate(struct wdp *wdp, tag_type tag)
2108 {
2109     struct wx *wx = wx_cast(wdp);
2110
2111     tag_set_add(&wx->revalidate_set, tag);
2112 }
2113
2114 static void
2115 wx_revalidate_all(struct wdp *wdp)
2116 {
2117     struct wx *wx = wx_cast(wdp);
2118
2119     wx->revalidate_all = true;
2120 }
2121 \f
2122 static void wx_port_update(struct wx *, const char *devname,
2123                            wdp_port_poll_cb_func *cb, void *aux);
2124 static void wx_port_reinit(struct wx *, wdp_port_poll_cb_func *cb, void *aux);
2125
2126 static void
2127 wx_port_process_change(struct wx *wx, int error, char *devname,
2128                        wdp_port_poll_cb_func *cb, void *aux)
2129 {
2130     if (error == ENOBUFS) {
2131         wx_port_reinit(wx, cb, aux);
2132     } else if (!error) {
2133         wx_port_update(wx, devname, cb, aux);
2134         free(devname);
2135     }
2136 }
2137
2138 static size_t
2139 wx_port_refresh_group(struct wx *wx, unsigned int group)
2140 {
2141     uint16_t *ports;
2142     size_t n_ports;
2143     struct wdp_port *port;
2144     unsigned int port_no;
2145
2146     assert(group == WX_GROUP_ALL || group == WX_GROUP_FLOOD);
2147
2148     ports = xmalloc(port_array_count(&wx->ports) * sizeof *ports);
2149     n_ports = 0;
2150     PORT_ARRAY_FOR_EACH (port, &wx->ports, port_no) {
2151         if (group == WX_GROUP_ALL || !(port->opp.config & OFPPC_NO_FLOOD)) {
2152             ports[n_ports++] = port_no;
2153         }
2154     }
2155     xfif_port_group_set(wx->xfif, group, ports, n_ports);
2156     free(ports);
2157
2158     return n_ports;
2159 }
2160
2161 static void
2162 wx_port_refresh_groups(struct wx *wx)
2163 {
2164     wx_port_refresh_group(wx, WX_GROUP_FLOOD);
2165     wx_port_refresh_group(wx, WX_GROUP_ALL);
2166 }
2167
2168 static void
2169 wx_port_reinit(struct wx *wx, wdp_port_poll_cb_func *cb, void *aux)
2170 {
2171     struct svec devnames;
2172     struct wdp_port *wdp_port;
2173     unsigned int port_no;
2174     struct xflow_port *xflow_ports;
2175     size_t n_xflow_ports;
2176     size_t i;
2177
2178     svec_init(&devnames);
2179     PORT_ARRAY_FOR_EACH (wdp_port, &wx->ports, port_no) {
2180         svec_add (&devnames, (char *) wdp_port->opp.name);
2181     }
2182     xfif_port_list(wx->xfif, &xflow_ports, &n_xflow_ports);
2183     for (i = 0; i < n_xflow_ports; i++) {
2184         svec_add(&devnames, xflow_ports[i].devname);
2185     }
2186     free(xflow_ports);
2187
2188     svec_sort_unique(&devnames);
2189     for (i = 0; i < devnames.n; i++) {
2190         wx_port_update(wx, devnames.names[i], cb, aux);
2191     }
2192     svec_destroy(&devnames);
2193
2194     wx_port_refresh_groups(wx);
2195 }
2196
2197 static struct wdp_port *
2198 make_wdp_port(const struct xflow_port *xflow_port)
2199 {
2200     struct netdev_options netdev_options;
2201     enum netdev_flags flags;
2202     struct wdp_port *wdp_port;
2203     struct netdev *netdev;
2204     bool carrier;
2205     int error;
2206
2207     memset(&netdev_options, 0, sizeof netdev_options);
2208     netdev_options.name = xflow_port->devname;
2209     netdev_options.ethertype = NETDEV_ETH_TYPE_NONE;
2210
2211     error = netdev_open(&netdev_options, &netdev);
2212     if (error) {
2213         VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
2214                      "cannot be opened (%s)",
2215                      xflow_port->devname, xflow_port->port,
2216                      xflow_port->devname, strerror(error));
2217         return NULL;
2218     }
2219
2220     wdp_port = xmalloc(sizeof *wdp_port);
2221     wdp_port->netdev = netdev;
2222     wdp_port->opp.port_no = xflow_port_to_ofp_port(xflow_port->port);
2223     netdev_get_etheraddr(netdev, wdp_port->opp.hw_addr);
2224     strncpy((char *) wdp_port->opp.name, xflow_port->devname,
2225             sizeof wdp_port->opp.name);
2226     wdp_port->opp.name[sizeof wdp_port->opp.name - 1] = '\0';
2227
2228     netdev_get_flags(netdev, &flags);
2229     wdp_port->opp.config = flags & NETDEV_UP ? 0 : OFPPC_PORT_DOWN;
2230
2231     netdev_get_carrier(netdev, &carrier);
2232     wdp_port->opp.state = carrier ? 0 : OFPPS_LINK_DOWN;
2233
2234     netdev_get_features(netdev,
2235                         &wdp_port->opp.curr, &wdp_port->opp.advertised,
2236                         &wdp_port->opp.supported, &wdp_port->opp.peer);
2237
2238     wdp_port->devname = xstrdup(xflow_port->devname);
2239     wdp_port->internal = (xflow_port->flags & XFLOW_PORT_INTERNAL) != 0;
2240     return wdp_port;
2241 }
2242
2243 static bool
2244 wx_port_conflicts(const struct wx *wx, const struct xflow_port *xflow_port)
2245 {
2246     if (port_array_get(&wx->ports, xflow_port->port)) {
2247         VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
2248                      xflow_port->port);
2249         return true;
2250     } else if (shash_find(&wx->port_by_name, xflow_port->devname)) {
2251         VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
2252                      xflow_port->devname);
2253         return true;
2254     } else {
2255         return false;
2256     }
2257 }
2258
2259 static int
2260 wdp_port_equal(const struct wdp_port *a_, const struct wdp_port *b_)
2261 {
2262     const struct ofp_phy_port *a = &a_->opp;
2263     const struct ofp_phy_port *b = &b_->opp;
2264
2265     BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
2266     return (a->port_no == b->port_no
2267             && !memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
2268             && !strcmp((char *) a->name, (char *) b->name)
2269             && a->state == b->state
2270             && a->config == b->config
2271             && a->curr == b->curr
2272             && a->advertised == b->advertised
2273             && a->supported == b->supported
2274             && a->peer == b->peer);
2275 }
2276
2277 static void
2278 wx_port_install(struct wx *wx, struct wdp_port *wdp_port)
2279 {
2280     uint16_t xflow_port = ofp_port_to_xflow_port(wdp_port->opp.port_no);
2281     const char *netdev_name = (const char *) wdp_port->opp.name;
2282
2283     netdev_monitor_add(wx->netdev_monitor, wdp_port->netdev);
2284     port_array_set(&wx->ports, xflow_port, wdp_port);
2285     shash_add(&wx->port_by_name, netdev_name, wdp_port);
2286 }
2287
2288 static void
2289 wx_port_remove(struct wx *wx, struct wdp_port *wdp_port)
2290 {
2291     uint16_t xflow_port = ofp_port_to_xflow_port(wdp_port->opp.port_no);
2292
2293     netdev_monitor_remove(wx->netdev_monitor, wdp_port->netdev);
2294     port_array_delete(&wx->ports, xflow_port);
2295     shash_delete(&wx->port_by_name,
2296                  shash_find(&wx->port_by_name, (char *) wdp_port->opp.name));
2297 }
2298
2299 static void
2300 wx_port_free(struct wdp_port *wdp_port)
2301 {
2302     if (wdp_port) {
2303         netdev_close(wdp_port->netdev);
2304         free(wdp_port);
2305     }
2306 }
2307
2308 static void
2309 wx_port_update(struct wx *wx, const char *devname,
2310                wdp_port_poll_cb_func *cb, void *aux)
2311 {
2312     struct xflow_port xflow_port;
2313     struct wdp_port *old_wdp_port;
2314     struct wdp_port *new_wdp_port;
2315     int error;
2316
2317     COVERAGE_INC(wx_update_port);
2318
2319     /* Query the datapath for port information. */
2320     error = xfif_port_query_by_name(wx->xfif, devname, &xflow_port);
2321
2322     /* Find the old wdp_port. */
2323     old_wdp_port = shash_find_data(&wx->port_by_name, devname);
2324     if (!error) {
2325         if (!old_wdp_port) {
2326             /* There's no port named 'devname' but there might be a port with
2327              * the same port number.  This could happen if a port is deleted
2328              * and then a new one added in its place very quickly, or if a port
2329              * is renamed.  In the former case we want to send an OFPPR_DELETE
2330              * and an OFPPR_ADD, and in the latter case we want to send a
2331              * single OFPPR_MODIFY.  We can distinguish the cases by comparing
2332              * the old port's ifindex against the new port, or perhaps less
2333              * reliably but more portably by comparing the old port's MAC
2334              * against the new port's MAC.  However, this code isn't that smart
2335              * and always sends an OFPPR_MODIFY (XXX). */
2336             old_wdp_port = port_array_get(&wx->ports, xflow_port.port);
2337         }
2338     } else if (error != ENOENT && error != ENODEV) {
2339         VLOG_WARN_RL(&rl, "xfif_port_query_by_name returned unexpected error "
2340                      "%s", strerror(error));
2341         return;
2342     }
2343
2344     /* Create a new wdp_port. */
2345     new_wdp_port = !error ? make_wdp_port(&xflow_port) : NULL;
2346
2347     /* Eliminate a few pathological cases. */
2348     if (!old_wdp_port && !new_wdp_port) {
2349         return;
2350     } else if (old_wdp_port && new_wdp_port) {
2351         /* Most of the 'config' bits are OpenFlow soft state, but
2352          * OFPPC_PORT_DOWN is maintained by the kernel.  So transfer the
2353          * OpenFlow bits from old_wdp_port.  (make_wdp_port() only sets
2354          * OFPPC_PORT_DOWN and leaves the other bits 0.)  */
2355         new_wdp_port->opp.config |= old_wdp_port->opp.config & ~OFPPC_PORT_DOWN;
2356
2357         if (wdp_port_equal(old_wdp_port, new_wdp_port)) {
2358             /* False alarm--no change. */
2359             wx_port_free(new_wdp_port);
2360             return;
2361         }
2362     }
2363
2364     /* Now deal with the normal cases. */
2365     if (old_wdp_port) {
2366         wx_port_remove(wx, old_wdp_port);
2367     }
2368     if (new_wdp_port) {
2369         wx_port_install(wx, new_wdp_port);
2370     }
2371
2372     /* Call back. */
2373     if (!old_wdp_port) {
2374         (*cb)(&new_wdp_port->opp, OFPPR_ADD, aux);
2375     } else if (!new_wdp_port) {
2376         (*cb)(&old_wdp_port->opp, OFPPR_DELETE, aux);
2377     } else {
2378         (*cb)(&new_wdp_port->opp, OFPPR_MODIFY, aux);
2379     }
2380
2381     /* Update port groups. */
2382     wx_port_refresh_groups(wx);
2383
2384     /* Clean up. */
2385     wx_port_free(old_wdp_port);
2386 }
2387
2388 static int
2389 wx_port_init(struct wx *wx)
2390 {
2391     struct xflow_port *ports;
2392     size_t n_ports;
2393     size_t i;
2394     int error;
2395
2396     error = xfif_port_list(wx->xfif, &ports, &n_ports);
2397     if (error) {
2398         return error;
2399     }
2400
2401     for (i = 0; i < n_ports; i++) {
2402         const struct xflow_port *xflow_port = &ports[i];
2403         if (!wx_port_conflicts(wx, xflow_port)) {
2404             struct wdp_port *wdp_port = make_wdp_port(xflow_port);
2405             if (wdp_port) {
2406                 wx_port_install(wx, wdp_port);
2407             }
2408         }
2409     }
2410     free(ports);
2411     wx_port_refresh_groups(wx);
2412     return 0;
2413 }
2414 \f
2415 void
2416 wdp_xflow_register(void)
2417 {
2418     static const struct wdp_class wdp_xflow_class = {
2419         NULL,                   /* name */
2420         wx_run,
2421         wx_wait,
2422         wx_enumerate,
2423         wx_open,
2424         wx_close,
2425         wx_get_all_names,
2426         wx_destroy,
2427         wx_get_features,
2428         wx_get_stats,
2429         wx_get_table_stats,
2430         wx_get_drop_frags,
2431         wx_set_drop_frags,
2432         wx_port_add,
2433         wx_port_del,
2434         wx_port_query_by_number,
2435         wx_port_query_by_name,
2436         wx_port_list,
2437         wx_port_set_config,
2438         wx_port_poll,
2439         wx_port_poll_wait,
2440         wx_flow_get,
2441         wx_flow_match,
2442         wx_flow_for_each_match,
2443         wx_flow_get_stats,
2444         wx_flow_overlaps,
2445         wx_flow_put,
2446         wx_flow_delete,
2447         wx_flow_flush,
2448         wx_flow_inject,
2449         wx_execute,
2450         wx_recv_get_mask,
2451         wx_recv_set_mask,
2452         wx_get_sflow_probability,
2453         wx_set_sflow_probability,
2454         wx_recv,
2455         wx_recv_purge,
2456         wx_recv_wait,
2457         wx_set_ofhooks,
2458         wx_revalidate,
2459         wx_revalidate_all,
2460     };
2461
2462     static bool inited = false;
2463
2464     struct svec types;
2465     const char *type;
2466     bool registered;
2467     int i;
2468
2469     if (inited) {
2470         return;
2471     }
2472     inited = true;
2473
2474     svec_init(&types);
2475     xf_enumerate_types(&types);
2476
2477     registered = false;
2478     SVEC_FOR_EACH (i, type, &types) {
2479         struct wdp_class *class;
2480
2481         class = xmalloc(sizeof *class);
2482         *class = wdp_xflow_class;
2483         class->type = xstrdup(type);
2484         if (registered) {
2485             class->run = NULL;
2486             class->wait = NULL;
2487         }
2488         if (!wdp_register_provider(class)) {
2489             registered = true;
2490         }
2491     }
2492
2493     svec_destroy(&types);
2494 }
2495 \f
2496 static bool
2497 default_normal_ofhook_cb(const flow_t *flow, const struct ofpbuf *packet,
2498                          struct xflow_actions *actions, tag_type *tags,
2499                          uint16_t *nf_output_iface, void *wx_)
2500 {
2501     struct wx *wx = wx_;
2502     int out_port;
2503
2504     /* Drop frames for reserved multicast addresses. */
2505     if (eth_addr_is_reserved(flow->dl_dst)) {
2506         return true;
2507     }
2508
2509     /* Learn source MAC (but don't try to learn from revalidation). */
2510     if (packet != NULL) {
2511         tag_type rev_tag = mac_learning_learn(wx->ml, flow->dl_src,
2512                                               0, flow->in_port,
2513                                               GRAT_ARP_LOCK_NONE);
2514         if (rev_tag) {
2515             /* The log messages here could actually be useful in debugging,
2516              * so keep the rate limit relatively high. */
2517             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
2518             VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
2519                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
2520             tag_set_add(&wx->revalidate_set, rev_tag);
2521         }
2522     }
2523
2524     /* Determine output port. */
2525     out_port = mac_learning_lookup_tag(wx->ml, flow->dl_dst, 0, tags,
2526                                        NULL);
2527     if (out_port < 0) {
2528         add_output_group_action(actions, WX_GROUP_FLOOD, nf_output_iface);
2529     } else if (out_port != flow->in_port) {
2530         xflow_actions_add(actions, XFLOWAT_OUTPUT)->output.port = out_port;
2531         *nf_output_iface = out_port;
2532     } else {
2533         /* Drop. */
2534     }
2535
2536     return true;
2537 }
2538
2539 static const struct ofhooks default_ofhooks = {
2540     NULL,
2541     default_normal_ofhook_cb,
2542     NULL,
2543     NULL
2544 };