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