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