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