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