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