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