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