42655f2391300f85b8df6ebb3b94334ea8fc4d1a
[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, unsigned int include)
1548 {
1549     struct wx *wx = wx_cast(wdp);
1550     struct wx_rule *rule;
1551     int table_id;
1552
1553     table_id = flow->wildcards ? TABLEID_CLASSIFIER : TABLEID_HASH;
1554     if (!(include & (1u << table_id))) {
1555         return NULL;
1556     }
1557
1558     rule = wx_rule_cast(classifier_find_rule_exactly(&wx->cls, flow));
1559     return rule && !wx_rule_is_hidden(rule) ? &rule->wr : NULL;
1560 }
1561
1562 static struct wdp_rule *
1563 wx_flow_match(const struct wdp *wdp, const flow_t *flow)
1564 {
1565     struct wx *wx = wx_cast(wdp);
1566     struct wx_rule *rule;
1567
1568     rule = wx_rule_cast(classifier_lookup(&wx->cls, flow));
1569     if (rule) {
1570         if (wx_rule_is_hidden(rule)) {
1571             rule = rule->super;
1572         }
1573         return &rule->wr;
1574     } else {
1575         return NULL;
1576     }
1577 }
1578
1579 struct wx_for_each_thunk_aux {
1580     wdp_flow_cb_func *client_callback;
1581     void *client_aux;
1582 };
1583
1584 static void
1585 wx_for_each_thunk(struct cls_rule *cls_rule, void *aux_)
1586 {
1587     struct wx_for_each_thunk_aux *aux = aux_;
1588     struct wx_rule *rule = wx_rule_cast(cls_rule);
1589
1590     if (!wx_rule_is_hidden(rule)) {
1591         aux->client_callback(&rule->wr, aux->client_aux);
1592     }
1593 }
1594
1595 static void
1596 wx_flow_for_each_match(const struct wdp *wdp, const flow_t *target,
1597                        unsigned int include,
1598                        wdp_flow_cb_func *client_callback, void *client_aux)
1599 {
1600     struct wx *wx = wx_cast(wdp);
1601     struct wx_for_each_thunk_aux aux;
1602     int cls_include;
1603
1604     cls_include = 0;
1605     if (include & (1u << TABLEID_HASH)) {
1606         cls_include |= CLS_INC_EXACT;
1607     }
1608     if (include & (1u << TABLEID_CLASSIFIER)) {
1609         cls_include |= CLS_INC_WILD;
1610     }
1611
1612     aux.client_callback = client_callback;
1613     aux.client_aux = client_aux;
1614     classifier_for_each_match(&wx->cls, target, cls_include,
1615                               wx_for_each_thunk, &aux);
1616 }
1617
1618 /* Obtains statistic counters for 'rule' within 'wx' and stores them into
1619  * '*stats'.  If 'rule' is a wildcarded rule, the returned statistic include
1620  * statistics for all of 'rule''s subrules. */
1621 static void
1622 query_stats(struct wx *wx, struct wx_rule *rule, struct wdp_flow_stats *stats)
1623 {
1624     struct wx_rule *subrule;
1625     struct xflow_flow *xflow_flows;
1626     size_t n_xflow_flows;
1627
1628     /* Start from historical data for 'rule' itself that are no longer tracked
1629      * by the datapath.  This counts, for example, subrules that have
1630      * expired. */
1631     stats->n_packets = rule->packet_count;
1632     stats->n_bytes = rule->byte_count;
1633     stats->inserted = rule->wr.created;
1634     stats->used = LLONG_MIN;
1635     stats->tcp_flags = 0;
1636     stats->ip_tos = 0;
1637
1638     /* Prepare to ask the datapath for statistics on 'rule', or if it is
1639      * wildcarded then on all of its subrules.
1640      *
1641      * Also, add any statistics that are not tracked by the datapath for each
1642      * subrule.  This includes, for example, statistics for packets that were
1643      * executed "by hand" by ofproto via xfif_execute() but must be accounted
1644      * to a flow. */
1645     n_xflow_flows = rule->wr.cr.flow.wildcards ? list_size(&rule->list) : 1;
1646     xflow_flows = xzalloc(n_xflow_flows * sizeof *xflow_flows);
1647     if (rule->wr.cr.flow.wildcards) {
1648         size_t i = 0;
1649         LIST_FOR_EACH (subrule, struct wx_rule, list, &rule->list) {
1650             xflow_key_from_flow(&xflow_flows[i++].key, &subrule->wr.cr.flow);
1651             stats->n_packets += subrule->packet_count;
1652             stats->n_bytes += subrule->byte_count;
1653         }
1654     } else {
1655         xflow_key_from_flow(&xflow_flows[0].key, &rule->wr.cr.flow);
1656     }
1657
1658     /* Fetch up-to-date statistics from the datapath and add them in. */
1659     if (!xfif_flow_get_multiple(wx->xfif, xflow_flows, n_xflow_flows)) {
1660         size_t i;
1661         for (i = 0; i < n_xflow_flows; i++) {
1662             struct xflow_flow *xflow_flow = &xflow_flows[i];
1663             long long int used;
1664
1665             stats->n_packets += xflow_flow->stats.n_packets;
1666             stats->n_bytes += xflow_flow->stats.n_bytes;
1667             used = xflow_flow_stats_to_msec(&xflow_flow->stats);
1668             if (used > stats->used) {
1669                 stats->used = used;
1670                 if (xflow_flow->key.dl_type == htons(ETH_TYPE_IP)
1671                     && xflow_flow->key.nw_proto == IP_TYPE_TCP) {
1672                     stats->ip_tos = xflow_flow->stats.ip_tos;
1673                 }
1674             }
1675             stats->tcp_flags |= xflow_flow->stats.tcp_flags;
1676         }
1677     }
1678     free(xflow_flows);
1679 }
1680
1681 static int
1682 wx_flow_get_stats(const struct wdp *wdp,
1683                   const struct wdp_rule *wdp_rule,
1684                   struct wdp_flow_stats *stats)
1685 {
1686     struct wx *wx = wx_cast(wdp);
1687     struct wx_rule *rule = wx_rule_cast(&wdp_rule->cr);
1688
1689     query_stats(wx, rule, stats);
1690     return 0;
1691 }
1692
1693 static bool
1694 wx_flow_overlaps(const struct wdp *wdp, const flow_t *flow)
1695 {
1696     struct wx *wx = wx_cast(wdp);
1697
1698     /* XXX overlap with a subrule? */
1699     return classifier_rule_overlaps(&wx->cls, flow);
1700 }
1701
1702 static int
1703 wx_flow_put(struct wdp *wdp, const struct wdp_flow_put *put,
1704             struct wdp_flow_stats *old_stats, struct wdp_rule **rulep)
1705 {
1706     struct wx *wx = wx_cast(wdp);
1707     struct wx_rule *rule;
1708     uint8_t ofp_table_id;
1709
1710     ofp_table_id = put->flow->wildcards ? TABLEID_CLASSIFIER : TABLEID_HASH;
1711     if (put->ofp_table_id != 0xff && put->ofp_table_id != ofp_table_id) {
1712         return EINVAL;
1713     }
1714
1715     rule = wx_rule_cast(classifier_find_rule_exactly(&wx->cls, put->flow));
1716     if (rule && wx_rule_is_hidden(rule)) {
1717         rule = NULL;
1718     }
1719
1720     if (rule) {
1721         if (!(put->flags & WDP_PUT_MODIFY)) {
1722             return EEXIST;
1723         }
1724     } else {
1725         if (!(put->flags & WDP_PUT_CREATE)) {
1726             return EINVAL;
1727         }
1728         if ((put->flow->wildcards
1729              ? classifier_count_wild(&wx->cls) >= WX_MAX_WILD
1730              : classifier_count_exact(&wx->cls) >= WX_MAX_EXACT)) {
1731             /* XXX subrules should not count against exact-match limit */
1732             return ENOBUFS;
1733         }
1734     }
1735
1736     rule = wx_rule_create(NULL, put->actions, put->n_actions,
1737                           put->idle_timeout, put->hard_timeout);
1738     cls_rule_from_flow(put->flow, &rule->wr.cr);
1739     rule->wr.ofp_table_id = ofp_table_id;
1740     wx_rule_insert(wx, rule, NULL, 0);
1741
1742     if (old_stats) {
1743         /* XXX */
1744         memset(old_stats, 0, sizeof *old_stats);
1745     }
1746     if (rulep) {
1747         *rulep = &rule->wr;
1748     }
1749
1750     return 0;
1751 }
1752
1753 static int
1754 wx_flow_delete(struct wdp *wdp, struct wdp_rule *wdp_rule,
1755                struct wdp_flow_stats *final_stats)
1756 {
1757     struct wx *wx = wx_cast(wdp);
1758     struct wx_rule *rule = wx_rule_cast(&wdp_rule->cr);
1759
1760     wx_rule_remove(wx, rule);
1761     if (final_stats) {
1762         memset(final_stats, 0, sizeof *final_stats); /* XXX */
1763     }
1764     return 0;
1765 }
1766
1767 static void
1768 wx_flush_rule(struct cls_rule *cls_rule, void *wx_)
1769 {
1770     struct wx_rule *rule = wx_rule_cast(cls_rule);
1771     struct wx *wx = wx_;
1772
1773     /* Mark the flow as not installed, even though it might really be
1774      * installed, so that wx_rule_remove() doesn't bother trying to uninstall
1775      * it.  There is no point in uninstalling it individually since we are
1776      * about to blow away all the flows with xfif_flow_flush(). */
1777     rule->installed = false;
1778
1779     wx_rule_remove(wx, rule);
1780 }
1781
1782 static int
1783 wx_flow_flush(struct wdp *wdp)
1784 {
1785     struct wx *wx = wx_cast(wdp);
1786
1787     COVERAGE_INC(wx_flow_flush);
1788     classifier_for_each(&wx->cls, CLS_INC_ALL, wx_flush_rule, wx);
1789     xfif_flow_flush(wx->xfif);
1790     return 0;
1791 }
1792
1793 static int
1794 wx_execute(struct wdp *wdp, uint16_t in_port,
1795            const union ofp_action actions[], int n_actions,
1796            const struct ofpbuf *packet)
1797 {
1798     struct wx *wx = wx_cast(wdp);
1799     struct xflow_actions xflow_actions;
1800     flow_t flow;
1801     int error;
1802
1803     flow_extract((struct ofpbuf *) packet, 0, in_port, &flow);
1804     error = wx_xlate_actions(wx, actions, n_actions, &flow, packet,
1805                              NULL, &xflow_actions, NULL);
1806     if (error) {
1807         return error;
1808     }
1809     xfif_execute(wx->xfif, ofp_port_to_xflow_port(in_port),
1810                  xflow_actions.actions, xflow_actions.n_actions, packet);
1811     return 0;
1812 }
1813
1814 static int
1815 wx_flow_inject(struct wdp *wdp, struct wdp_rule *wdp_rule,
1816                uint16_t in_port, const struct ofpbuf *packet)
1817 {
1818     struct wx_rule *rule = wx_rule_cast(&wdp_rule->cr);
1819     int error;
1820
1821     error = wx_execute(wdp, in_port, rule->wr.actions, rule->wr.n_actions,
1822                        packet);
1823     if (!error) {
1824         rule->packet_count++;
1825         rule->byte_count += packet->size;
1826         rule->used = time_msec();
1827     }
1828     return error;
1829 }
1830
1831 static int
1832 wx_recv_get_mask(const struct wdp *wdp, int *listen_mask)
1833 {
1834     struct wx *wx = wx_cast(wdp);
1835     int xflow_listen_mask;
1836     int error;
1837
1838     error = xfif_recv_get_mask(wx->xfif, &xflow_listen_mask);
1839     if (!error) {
1840         *listen_mask = 0;
1841         if (xflow_listen_mask & XFLOWL_MISS) {
1842             *listen_mask |= 1 << WDP_CHAN_MISS;
1843         }
1844         if (xflow_listen_mask & XFLOWL_ACTION) {
1845             *listen_mask |= 1 << WDP_CHAN_ACTION;
1846         }
1847         if (xflow_listen_mask & XFLOWL_SFLOW) {
1848             *listen_mask |= 1 << WDP_CHAN_SFLOW;
1849         }
1850     }
1851     return error;
1852 }
1853
1854 static int
1855 wx_recv_set_mask(struct wdp *wdp, int listen_mask)
1856 {
1857     struct wx *wx = wx_cast(wdp);
1858     int xflow_listen_mask;
1859
1860     xflow_listen_mask = 0;
1861     if (listen_mask & (1 << WDP_CHAN_MISS)) {
1862         xflow_listen_mask |= XFLOWL_MISS;
1863     }
1864     if (listen_mask & (1 << WDP_CHAN_ACTION)) {
1865         xflow_listen_mask |= XFLOWL_ACTION;
1866     }
1867     if (listen_mask & (1 << WDP_CHAN_SFLOW)) {
1868         xflow_listen_mask |= XFLOWL_SFLOW;
1869     }
1870
1871     return xfif_recv_set_mask(wx->xfif, xflow_listen_mask);
1872 }
1873
1874 static int
1875 wx_get_sflow_probability(const struct wdp *wdp, uint32_t *probability)
1876 {
1877     struct wx *wx = wx_cast(wdp);
1878
1879     return xfif_get_sflow_probability(wx->xfif, probability);
1880 }
1881
1882 static int
1883 wx_set_sflow_probability(struct wdp *wdp, uint32_t probability)
1884 {
1885     struct wx *wx = wx_cast(wdp);
1886
1887     return xfif_set_sflow_probability(wx->xfif, probability);
1888 }
1889
1890 static int
1891 wx_translate_xflow_msg(struct xflow_msg *msg, struct ofpbuf *payload,
1892                        struct wdp_packet *packet)
1893 {
1894     packet->in_port = xflow_port_to_ofp_port(msg->port);
1895     packet->send_len = 0;
1896     packet->tun_id = 0;
1897
1898     switch (msg->type) {
1899     case _XFLOWL_MISS_NR:
1900         packet->channel = WDP_CHAN_MISS;
1901         packet->payload = payload;
1902         packet->tun_id = msg->arg;
1903         return 0;
1904
1905     case _XFLOWL_ACTION_NR:
1906         packet->channel = WDP_CHAN_ACTION;
1907         packet->payload = payload;
1908         packet->send_len = msg->arg;
1909         return 0;
1910
1911     case _XFLOWL_SFLOW_NR:
1912         /* XXX */
1913         ofpbuf_delete(payload);
1914         return ENOSYS;
1915
1916     default:
1917         VLOG_WARN_RL(&rl, "received XFLOW message of unexpected type %"PRIu32,
1918                      msg->type);
1919         ofpbuf_delete(payload);
1920         return ENOSYS;
1921     }
1922 }
1923
1924 static const uint8_t *
1925 get_local_mac(const struct wx *wx)
1926 {
1927     const struct wdp_port *port = port_array_get(&wx->ports, XFLOWP_LOCAL);
1928     return port ? port->opp.hw_addr : NULL;
1929 }
1930
1931 /* Returns true if 'packet' is a DHCP reply to the local port.  Such a reply
1932  * should be sent to the local port regardless of the flow table.
1933  *
1934  * We only need this, strictly speaking, when in-band control is turned on. */
1935 static bool
1936 wx_is_local_dhcp_reply(const struct wx *wx,
1937                        const flow_t *flow, const struct ofpbuf *packet)
1938 {
1939     if (flow->dl_type == htons(ETH_TYPE_IP)
1940         && flow->nw_proto == IP_TYPE_UDP
1941         && flow->tp_src == htons(DHCP_SERVER_PORT)
1942         && flow->tp_dst == htons(DHCP_CLIENT_PORT)
1943         && packet->l7)
1944     {
1945         const uint8_t *local_mac = get_local_mac(wx);
1946         struct dhcp_header *dhcp = ofpbuf_at(
1947             packet, (char *)packet->l7 - (char *)packet->data, sizeof *dhcp);
1948         return dhcp && local_mac && eth_addr_equals(dhcp->chaddr, local_mac);
1949     }
1950
1951     return false;
1952 }
1953
1954 static bool
1955 wx_explode_rule(struct wx *wx, struct xflow_msg *msg, struct ofpbuf *payload)
1956 {
1957     struct wx_rule *rule;
1958     flow_t flow;
1959
1960     flow_extract(payload, 0, xflow_port_to_ofp_port(msg->port), &flow);
1961
1962     if (wx_is_local_dhcp_reply(wx, &flow, payload)) {
1963         union xflow_action action;
1964
1965         memset(&action, 0, sizeof(action));
1966         action.output.type = XFLOWAT_OUTPUT;
1967         action.output.port = XFLOWP_LOCAL;
1968         xfif_execute(wx->xfif, msg->port, &action, 1, payload);
1969     }
1970
1971     rule = wx_rule_lookup_valid(wx, &flow);
1972     if (!rule) {
1973         return false;
1974     }
1975
1976     if (rule->wr.cr.flow.wildcards) {
1977         rule = wx_rule_create_subrule(wx, rule, &flow);
1978         wx_rule_make_actions(wx, rule, payload);
1979     } else {
1980         if (!rule->may_install) {
1981             /* The rule is not installable, that is, we need to process every
1982              * packet, so process the current packet and set its actions into
1983              * 'subrule'. */
1984             wx_rule_make_actions(wx, rule, payload);
1985         } else {
1986             /* XXX revalidate rule if it needs it */
1987         }
1988     }
1989
1990     wx_rule_execute(wx, rule, payload, &flow);
1991     wx_rule_reinstall(wx, rule);
1992
1993     return true;
1994 }
1995
1996 static int
1997 wx_recv(struct wdp *wdp, struct wdp_packet *packet)
1998 {
1999     struct wx *wx = wx_cast(wdp);
2000     int i;
2001
2002     /* XXX need to avoid 50*50 potential cost for caller. */
2003     for (i = 0; i < 50; i++) {
2004         struct xflow_msg *msg;
2005         struct ofpbuf *buf;
2006         int error;
2007
2008         error = xfif_recv(wx->xfif, &buf);
2009         if (error) {
2010             return error;
2011         }
2012
2013         msg = ofpbuf_pull(buf, sizeof *msg);
2014         if (msg->type != _XFLOWL_MISS_NR || !wx_explode_rule(wx, msg, buf)) {
2015             return wx_translate_xflow_msg(msg, buf, packet);
2016         }
2017         ofpbuf_delete(buf);
2018     }
2019     return EAGAIN;
2020 }
2021
2022 static void
2023 wx_recv_purge_queue__(struct wx *wx, int max, int xflow_listen_mask,
2024                       int *errorp)
2025 {
2026     int error;
2027
2028     error = xfif_recv_set_mask(wx->xfif, xflow_listen_mask);
2029     if (!error) {
2030         struct ofpbuf *buf;
2031
2032         while (max > 0 && (error = xfif_recv(wx->xfif, &buf)) == 0) {
2033             ofpbuf_delete(buf);
2034             max--;
2035         }
2036     }
2037     if (error && error != EAGAIN) {
2038         *errorp = error;
2039     }
2040 }
2041
2042 static int
2043 wx_recv_purge(struct wdp *wdp)
2044 {
2045     struct wx *wx = wx_cast(wdp);
2046     struct xflow_stats xflow_stats;
2047     int xflow_listen_mask;
2048     int retval, error;
2049
2050     xfif_get_xf_stats(wx->xfif, &xflow_stats);
2051
2052     error = xfif_recv_get_mask(wx->xfif, &xflow_listen_mask);
2053     if (error || !(xflow_listen_mask & XFLOWL_ALL)) {
2054         return error;
2055     }
2056
2057     if (xflow_listen_mask & XFLOWL_MISS) {
2058         wx_recv_purge_queue__(wx, xflow_stats.max_miss_queue, XFLOWL_MISS,
2059                               &error);
2060     }
2061     if (xflow_listen_mask & XFLOWL_ACTION) {
2062         wx_recv_purge_queue__(wx, xflow_stats.max_action_queue, XFLOWL_ACTION,
2063                               &error);
2064     }
2065     if (xflow_listen_mask & XFLOWL_SFLOW) {
2066         wx_recv_purge_queue__(wx, xflow_stats.max_sflow_queue, XFLOWL_SFLOW,
2067                               &error);
2068     }
2069
2070     retval = xfif_recv_set_mask(wx->xfif, xflow_listen_mask);
2071     return retval ? retval : error;
2072 }
2073
2074
2075 static void
2076 wx_recv_wait(struct wdp *wdp)
2077 {
2078     struct wx *wx = wx_cast(wdp);
2079
2080     xfif_recv_wait(wx->xfif);
2081 }
2082
2083 static int
2084 wx_set_ofhooks(struct wdp *wdp, const struct ofhooks *ofhooks, void *aux)
2085 {
2086     struct wx *wx = wx_cast(wdp);
2087
2088     if (wx->ofhooks == &default_ofhooks) {
2089         mac_learning_destroy(wx->ml);
2090         wx->ml = NULL;
2091     }
2092
2093     wx->ofhooks = ofhooks;
2094     wx->aux = aux;
2095     return 0;
2096 }
2097
2098 static void
2099 wx_revalidate(struct wdp *wdp, tag_type tag)
2100 {
2101     struct wx *wx = wx_cast(wdp);
2102
2103     tag_set_add(&wx->revalidate_set, tag);
2104 }
2105
2106 static void
2107 wx_revalidate_all(struct wdp *wdp)
2108 {
2109     struct wx *wx = wx_cast(wdp);
2110
2111     wx->revalidate_all = true;
2112 }
2113 \f
2114 static void wx_port_update(struct wx *, const char *devname,
2115                            wdp_port_poll_cb_func *cb, void *aux);
2116 static void wx_port_reinit(struct wx *, wdp_port_poll_cb_func *cb, void *aux);
2117
2118 static void
2119 wx_port_process_change(struct wx *wx, int error, char *devname,
2120                        wdp_port_poll_cb_func *cb, void *aux)
2121 {
2122     if (error == ENOBUFS) {
2123         wx_port_reinit(wx, cb, aux);
2124     } else if (!error) {
2125         wx_port_update(wx, devname, cb, aux);
2126         free(devname);
2127     }
2128 }
2129
2130 static size_t
2131 wx_port_refresh_group(struct wx *wx, unsigned int group)
2132 {
2133     uint16_t *ports;
2134     size_t n_ports;
2135     struct wdp_port *port;
2136     unsigned int port_no;
2137
2138     assert(group == WX_GROUP_ALL || group == WX_GROUP_FLOOD);
2139
2140     ports = xmalloc(port_array_count(&wx->ports) * sizeof *ports);
2141     n_ports = 0;
2142     PORT_ARRAY_FOR_EACH (port, &wx->ports, port_no) {
2143         if (group == WX_GROUP_ALL || !(port->opp.config & OFPPC_NO_FLOOD)) {
2144             ports[n_ports++] = port_no;
2145         }
2146     }
2147     xfif_port_group_set(wx->xfif, group, ports, n_ports);
2148     free(ports);
2149
2150     return n_ports;
2151 }
2152
2153 static void
2154 wx_port_refresh_groups(struct wx *wx)
2155 {
2156     wx_port_refresh_group(wx, WX_GROUP_FLOOD);
2157     wx_port_refresh_group(wx, WX_GROUP_ALL);
2158 }
2159
2160 static void
2161 wx_port_reinit(struct wx *wx, wdp_port_poll_cb_func *cb, void *aux)
2162 {
2163     struct svec devnames;
2164     struct wdp_port *wdp_port;
2165     unsigned int port_no;
2166     struct xflow_port *xflow_ports;
2167     size_t n_xflow_ports;
2168     size_t i;
2169
2170     svec_init(&devnames);
2171     PORT_ARRAY_FOR_EACH (wdp_port, &wx->ports, port_no) {
2172         svec_add (&devnames, (char *) wdp_port->opp.name);
2173     }
2174     xfif_port_list(wx->xfif, &xflow_ports, &n_xflow_ports);
2175     for (i = 0; i < n_xflow_ports; i++) {
2176         svec_add(&devnames, xflow_ports[i].devname);
2177     }
2178     free(xflow_ports);
2179
2180     svec_sort_unique(&devnames);
2181     for (i = 0; i < devnames.n; i++) {
2182         wx_port_update(wx, devnames.names[i], cb, aux);
2183     }
2184     svec_destroy(&devnames);
2185
2186     wx_port_refresh_groups(wx);
2187 }
2188
2189 static struct wdp_port *
2190 make_wdp_port(const struct xflow_port *xflow_port)
2191 {
2192     struct netdev_options netdev_options;
2193     enum netdev_flags flags;
2194     struct wdp_port *wdp_port;
2195     struct netdev *netdev;
2196     bool carrier;
2197     int error;
2198
2199     memset(&netdev_options, 0, sizeof netdev_options);
2200     netdev_options.name = xflow_port->devname;
2201     netdev_options.ethertype = NETDEV_ETH_TYPE_NONE;
2202
2203     error = netdev_open(&netdev_options, &netdev);
2204     if (error) {
2205         VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
2206                      "cannot be opened (%s)",
2207                      xflow_port->devname, xflow_port->port,
2208                      xflow_port->devname, strerror(error));
2209         return NULL;
2210     }
2211
2212     wdp_port = xmalloc(sizeof *wdp_port);
2213     wdp_port->netdev = netdev;
2214     wdp_port->opp.port_no = xflow_port_to_ofp_port(xflow_port->port);
2215     netdev_get_etheraddr(netdev, wdp_port->opp.hw_addr);
2216     strncpy((char *) wdp_port->opp.name, xflow_port->devname,
2217             sizeof wdp_port->opp.name);
2218     wdp_port->opp.name[sizeof wdp_port->opp.name - 1] = '\0';
2219
2220     netdev_get_flags(netdev, &flags);
2221     wdp_port->opp.config = flags & NETDEV_UP ? 0 : OFPPC_PORT_DOWN;
2222
2223     netdev_get_carrier(netdev, &carrier);
2224     wdp_port->opp.state = carrier ? 0 : OFPPS_LINK_DOWN;
2225
2226     netdev_get_features(netdev,
2227                         &wdp_port->opp.curr, &wdp_port->opp.advertised,
2228                         &wdp_port->opp.supported, &wdp_port->opp.peer);
2229
2230     wdp_port->devname = xstrdup(xflow_port->devname);
2231     wdp_port->internal = (xflow_port->flags & XFLOW_PORT_INTERNAL) != 0;
2232     return wdp_port;
2233 }
2234
2235 static bool
2236 wx_port_conflicts(const struct wx *wx, const struct xflow_port *xflow_port)
2237 {
2238     if (port_array_get(&wx->ports, xflow_port->port)) {
2239         VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
2240                      xflow_port->port);
2241         return true;
2242     } else if (shash_find(&wx->port_by_name, xflow_port->devname)) {
2243         VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
2244                      xflow_port->devname);
2245         return true;
2246     } else {
2247         return false;
2248     }
2249 }
2250
2251 static int
2252 wdp_port_equal(const struct wdp_port *a_, const struct wdp_port *b_)
2253 {
2254     const struct ofp_phy_port *a = &a_->opp;
2255     const struct ofp_phy_port *b = &b_->opp;
2256
2257     BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
2258     return (a->port_no == b->port_no
2259             && !memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
2260             && !strcmp((char *) a->name, (char *) b->name)
2261             && a->state == b->state
2262             && a->config == b->config
2263             && a->curr == b->curr
2264             && a->advertised == b->advertised
2265             && a->supported == b->supported
2266             && a->peer == b->peer);
2267 }
2268
2269 static void
2270 wx_port_install(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     const char *netdev_name = (const char *) wdp_port->opp.name;
2274
2275     netdev_monitor_add(wx->netdev_monitor, wdp_port->netdev);
2276     port_array_set(&wx->ports, xflow_port, wdp_port);
2277     shash_add(&wx->port_by_name, netdev_name, wdp_port);
2278 }
2279
2280 static void
2281 wx_port_remove(struct wx *wx, struct wdp_port *wdp_port)
2282 {
2283     uint16_t xflow_port = ofp_port_to_xflow_port(wdp_port->opp.port_no);
2284
2285     netdev_monitor_remove(wx->netdev_monitor, wdp_port->netdev);
2286     port_array_delete(&wx->ports, xflow_port);
2287     shash_delete(&wx->port_by_name,
2288                  shash_find(&wx->port_by_name, (char *) wdp_port->opp.name));
2289 }
2290
2291 static void
2292 wx_port_free(struct wdp_port *wdp_port)
2293 {
2294     if (wdp_port) {
2295         netdev_close(wdp_port->netdev);
2296         free(wdp_port);
2297     }
2298 }
2299
2300 static void
2301 wx_port_update(struct wx *wx, const char *devname,
2302                wdp_port_poll_cb_func *cb, void *aux)
2303 {
2304     struct xflow_port xflow_port;
2305     struct wdp_port *old_wdp_port;
2306     struct wdp_port *new_wdp_port;
2307     int error;
2308
2309     COVERAGE_INC(wx_update_port);
2310
2311     /* Query the datapath for port information. */
2312     error = xfif_port_query_by_name(wx->xfif, devname, &xflow_port);
2313
2314     /* Find the old wdp_port. */
2315     old_wdp_port = shash_find_data(&wx->port_by_name, devname);
2316     if (!error) {
2317         if (!old_wdp_port) {
2318             /* There's no port named 'devname' but there might be a port with
2319              * the same port number.  This could happen if a port is deleted
2320              * and then a new one added in its place very quickly, or if a port
2321              * is renamed.  In the former case we want to send an OFPPR_DELETE
2322              * and an OFPPR_ADD, and in the latter case we want to send a
2323              * single OFPPR_MODIFY.  We can distinguish the cases by comparing
2324              * the old port's ifindex against the new port, or perhaps less
2325              * reliably but more portably by comparing the old port's MAC
2326              * against the new port's MAC.  However, this code isn't that smart
2327              * and always sends an OFPPR_MODIFY (XXX). */
2328             old_wdp_port = port_array_get(&wx->ports, xflow_port.port);
2329         }
2330     } else if (error != ENOENT && error != ENODEV) {
2331         VLOG_WARN_RL(&rl, "xfif_port_query_by_name returned unexpected error "
2332                      "%s", strerror(error));
2333         return;
2334     }
2335
2336     /* Create a new wdp_port. */
2337     new_wdp_port = !error ? make_wdp_port(&xflow_port) : NULL;
2338
2339     /* Eliminate a few pathological cases. */
2340     if (!old_wdp_port && !new_wdp_port) {
2341         return;
2342     } else if (old_wdp_port && new_wdp_port) {
2343         /* Most of the 'config' bits are OpenFlow soft state, but
2344          * OFPPC_PORT_DOWN is maintained by the kernel.  So transfer the
2345          * OpenFlow bits from old_wdp_port.  (make_wdp_port() only sets
2346          * OFPPC_PORT_DOWN and leaves the other bits 0.)  */
2347         new_wdp_port->opp.config |= old_wdp_port->opp.config & ~OFPPC_PORT_DOWN;
2348
2349         if (wdp_port_equal(old_wdp_port, new_wdp_port)) {
2350             /* False alarm--no change. */
2351             wx_port_free(new_wdp_port);
2352             return;
2353         }
2354     }
2355
2356     /* Now deal with the normal cases. */
2357     if (old_wdp_port) {
2358         wx_port_remove(wx, old_wdp_port);
2359     }
2360     if (new_wdp_port) {
2361         wx_port_install(wx, new_wdp_port);
2362     }
2363
2364     /* Call back. */
2365     if (!old_wdp_port) {
2366         (*cb)(&new_wdp_port->opp, OFPPR_ADD, aux);
2367     } else if (!new_wdp_port) {
2368         (*cb)(&old_wdp_port->opp, OFPPR_DELETE, aux);
2369     } else {
2370         (*cb)(&new_wdp_port->opp, OFPPR_MODIFY, aux);
2371     }
2372
2373     /* Update port groups. */
2374     wx_port_refresh_groups(wx);
2375
2376     /* Clean up. */
2377     wx_port_free(old_wdp_port);
2378 }
2379
2380 static int
2381 wx_port_init(struct wx *wx)
2382 {
2383     struct xflow_port *ports;
2384     size_t n_ports;
2385     size_t i;
2386     int error;
2387
2388     error = xfif_port_list(wx->xfif, &ports, &n_ports);
2389     if (error) {
2390         return error;
2391     }
2392
2393     for (i = 0; i < n_ports; i++) {
2394         const struct xflow_port *xflow_port = &ports[i];
2395         if (!wx_port_conflicts(wx, xflow_port)) {
2396             struct wdp_port *wdp_port = make_wdp_port(xflow_port);
2397             if (wdp_port) {
2398                 wx_port_install(wx, wdp_port);
2399             }
2400         }
2401     }
2402     free(ports);
2403     wx_port_refresh_groups(wx);
2404     return 0;
2405 }
2406 \f
2407 void
2408 wdp_xflow_register(void)
2409 {
2410     static const struct wdp_class wdp_xflow_class = {
2411         NULL,                   /* name */
2412         wx_run,
2413         wx_wait,
2414         wx_enumerate,
2415         wx_open,
2416         wx_close,
2417         wx_get_all_names,
2418         wx_destroy,
2419         wx_get_features,
2420         wx_get_stats,
2421         wx_get_table_stats,
2422         wx_get_drop_frags,
2423         wx_set_drop_frags,
2424         wx_port_add,
2425         wx_port_del,
2426         wx_port_query_by_number,
2427         wx_port_query_by_name,
2428         wx_port_list,
2429         wx_port_set_config,
2430         wx_port_poll,
2431         wx_port_poll_wait,
2432         wx_flow_get,
2433         wx_flow_match,
2434         wx_flow_for_each_match,
2435         wx_flow_get_stats,
2436         wx_flow_overlaps,
2437         wx_flow_put,
2438         wx_flow_delete,
2439         wx_flow_flush,
2440         wx_flow_inject,
2441         wx_execute,
2442         wx_recv_get_mask,
2443         wx_recv_set_mask,
2444         wx_get_sflow_probability,
2445         wx_set_sflow_probability,
2446         wx_recv,
2447         wx_recv_purge,
2448         wx_recv_wait,
2449         wx_set_ofhooks,
2450         wx_revalidate,
2451         wx_revalidate_all,
2452     };
2453
2454     static bool inited = false;
2455
2456     struct svec types;
2457     const char *type;
2458     bool registered;
2459     int i;
2460
2461     if (inited) {
2462         return;
2463     }
2464     inited = true;
2465
2466     svec_init(&types);
2467     xf_enumerate_types(&types);
2468
2469     registered = false;
2470     SVEC_FOR_EACH (i, type, &types) {
2471         struct wdp_class *class;
2472
2473         class = xmalloc(sizeof *class);
2474         *class = wdp_xflow_class;
2475         class->type = xstrdup(type);
2476         if (registered) {
2477             class->run = NULL;
2478             class->wait = NULL;
2479         }
2480         if (!wdp_register_provider(class)) {
2481             registered = true;
2482         }
2483     }
2484
2485     svec_destroy(&types);
2486 }
2487 \f
2488 static bool
2489 default_normal_ofhook_cb(const flow_t *flow, const struct ofpbuf *packet,
2490                          struct xflow_actions *actions, tag_type *tags,
2491                          uint16_t *nf_output_iface, void *wx_)
2492 {
2493     struct wx *wx = wx_;
2494     int out_port;
2495
2496     /* Drop frames for reserved multicast addresses. */
2497     if (eth_addr_is_reserved(flow->dl_dst)) {
2498         return true;
2499     }
2500
2501     /* Learn source MAC (but don't try to learn from revalidation). */
2502     if (packet != NULL) {
2503         tag_type rev_tag = mac_learning_learn(wx->ml, flow->dl_src,
2504                                               0, flow->in_port,
2505                                               GRAT_ARP_LOCK_NONE);
2506         if (rev_tag) {
2507             /* The log messages here could actually be useful in debugging,
2508              * so keep the rate limit relatively high. */
2509             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
2510             VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
2511                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
2512             tag_set_add(&wx->revalidate_set, rev_tag);
2513         }
2514     }
2515
2516     /* Determine output port. */
2517     out_port = mac_learning_lookup_tag(wx->ml, flow->dl_dst, 0, tags,
2518                                        NULL);
2519     if (out_port < 0) {
2520         add_output_group_action(actions, WX_GROUP_FLOOD, nf_output_iface);
2521     } else if (out_port != flow->in_port) {
2522         xflow_actions_add(actions, XFLOWAT_OUTPUT)->output.port = out_port;
2523         *nf_output_iface = out_port;
2524     } else {
2525         /* Drop. */
2526     }
2527
2528     return true;
2529 }
2530
2531 static const struct ofhooks default_ofhooks = {
2532     NULL,
2533     default_normal_ofhook_cb,
2534     NULL,
2535     NULL
2536 };