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