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