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