ofproto-dpif: Process multiple batches of upcalls in a single poll loop.
[cascardo/ovs.git] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 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 "ofproto/ofproto-provider.h"
20
21 #include <errno.h>
22
23 #include "autopath.h"
24 #include "bond.h"
25 #include "bundle.h"
26 #include "byte-order.h"
27 #include "connmgr.h"
28 #include "coverage.h"
29 #include "cfm.h"
30 #include "dpif.h"
31 #include "dynamic-string.h"
32 #include "fail-open.h"
33 #include "hmapx.h"
34 #include "lacp.h"
35 #include "learn.h"
36 #include "mac-learning.h"
37 #include "multipath.h"
38 #include "netdev.h"
39 #include "netlink.h"
40 #include "nx-match.h"
41 #include "odp-util.h"
42 #include "ofp-util.h"
43 #include "ofpbuf.h"
44 #include "ofp-print.h"
45 #include "ofproto-dpif-sflow.h"
46 #include "poll-loop.h"
47 #include "timer.h"
48 #include "unaligned.h"
49 #include "unixctl.h"
50 #include "vlan-bitmap.h"
51 #include "vlog.h"
52
53 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
54
55 COVERAGE_DEFINE(ofproto_dpif_ctlr_action);
56 COVERAGE_DEFINE(ofproto_dpif_expired);
57 COVERAGE_DEFINE(ofproto_dpif_no_packet_in);
58 COVERAGE_DEFINE(ofproto_dpif_xlate);
59 COVERAGE_DEFINE(facet_changed_rule);
60 COVERAGE_DEFINE(facet_invalidated);
61 COVERAGE_DEFINE(facet_revalidate);
62 COVERAGE_DEFINE(facet_unexpected);
63
64 /* Maximum depth of flow table recursion (due to resubmit actions) in a
65  * flow translation. */
66 #define MAX_RESUBMIT_RECURSION 32
67
68 /* Number of implemented OpenFlow tables. */
69 enum { N_TABLES = 255 };
70 BUILD_ASSERT_DECL(N_TABLES >= 1 && N_TABLES <= 255);
71
72 struct ofport_dpif;
73 struct ofproto_dpif;
74
75 struct rule_dpif {
76     struct rule up;
77
78     long long int used;         /* Time last used; time created if not used. */
79
80     /* These statistics:
81      *
82      *   - Do include packets and bytes from facets that have been deleted or
83      *     whose own statistics have been folded into the rule.
84      *
85      *   - Do include packets and bytes sent "by hand" that were accounted to
86      *     the rule without any facet being involved (this is a rare corner
87      *     case in rule_execute()).
88      *
89      *   - Do not include packet or bytes that can be obtained from any facet's
90      *     packet_count or byte_count member or that can be obtained from the
91      *     datapath by, e.g., dpif_flow_get() for any facet.
92      */
93     uint64_t packet_count;       /* Number of packets received. */
94     uint64_t byte_count;         /* Number of bytes received. */
95
96     tag_type tag;                /* Caches rule_calculate_tag() result. */
97
98     struct list facets;          /* List of "struct facet"s. */
99 };
100
101 static struct rule_dpif *rule_dpif_cast(const struct rule *rule)
102 {
103     return rule ? CONTAINER_OF(rule, struct rule_dpif, up) : NULL;
104 }
105
106 static struct rule_dpif *rule_dpif_lookup(struct ofproto_dpif *,
107                                           const struct flow *, uint8_t table);
108
109 #define MAX_MIRRORS 32
110 typedef uint32_t mirror_mask_t;
111 #define MIRROR_MASK_C(X) UINT32_C(X)
112 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
113 struct ofmirror {
114     struct ofproto_dpif *ofproto; /* Owning ofproto. */
115     size_t idx;                 /* In ofproto's "mirrors" array. */
116     void *aux;                  /* Key supplied by ofproto's client. */
117     char *name;                 /* Identifier for log messages. */
118
119     /* Selection criteria. */
120     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
121     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
122     unsigned long *vlans;       /* Bitmap of chosen VLANs, NULL selects all. */
123
124     /* Output (mutually exclusive). */
125     struct ofbundle *out;       /* Output port or NULL. */
126     int out_vlan;               /* Output VLAN or -1. */
127 };
128
129 static void mirror_destroy(struct ofmirror *);
130
131 /* A group of one or more OpenFlow ports. */
132 #define OFBUNDLE_FLOOD ((struct ofbundle *) 1)
133 struct ofbundle {
134     struct ofproto_dpif *ofproto; /* Owning ofproto. */
135     struct hmap_node hmap_node; /* In struct ofproto's "bundles" hmap. */
136     void *aux;                  /* Key supplied by ofproto's client. */
137     char *name;                 /* Identifier for log messages. */
138
139     /* Configuration. */
140     struct list ports;          /* Contains "struct ofport"s. */
141     enum port_vlan_mode vlan_mode; /* VLAN mode */
142     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
143     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
144                                  * NULL if all VLANs are trunked. */
145     struct lacp *lacp;          /* LACP if LACP is enabled, otherwise NULL. */
146     struct bond *bond;          /* Nonnull iff more than one port. */
147
148     /* Status. */
149     bool floodable;             /* True if no port has OFPPC_NO_FLOOD set. */
150
151     /* Port mirroring info. */
152     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
153     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
154     mirror_mask_t mirror_out;   /* Mirrors that output to this bundle. */
155 };
156
157 static void bundle_remove(struct ofport *);
158 static void bundle_update(struct ofbundle *);
159 static void bundle_destroy(struct ofbundle *);
160 static void bundle_del_port(struct ofport_dpif *);
161 static void bundle_run(struct ofbundle *);
162 static void bundle_wait(struct ofbundle *);
163
164 static void stp_run(struct ofproto_dpif *ofproto);
165 static void stp_wait(struct ofproto_dpif *ofproto);
166
167 struct action_xlate_ctx {
168 /* action_xlate_ctx_init() initializes these members. */
169
170     /* The ofproto. */
171     struct ofproto_dpif *ofproto;
172
173     /* Flow to which the OpenFlow actions apply.  xlate_actions() will modify
174      * this flow when actions change header fields. */
175     struct flow flow;
176
177     /* The packet corresponding to 'flow', or a null pointer if we are
178      * revalidating without a packet to refer to. */
179     const struct ofpbuf *packet;
180
181     /* Should OFPP_NORMAL MAC learning and NXAST_LEARN actions execute?  We
182      * want to execute them if we are actually processing a packet, or if we
183      * are accounting for packets that the datapath has processed, but not if
184      * we are just revalidating. */
185     bool may_learn;
186
187     /* If nonnull, called just before executing a resubmit action.
188      *
189      * This is normally null so the client has to set it manually after
190      * calling action_xlate_ctx_init(). */
191     void (*resubmit_hook)(struct action_xlate_ctx *, struct rule_dpif *);
192
193 /* xlate_actions() initializes and uses these members.  The client might want
194  * to look at them after it returns. */
195
196     struct ofpbuf *odp_actions; /* Datapath actions. */
197     tag_type tags;              /* Tags associated with actions. */
198     bool may_set_up_flow;       /* True ordinarily; false if the actions must
199                                  * be reassessed for every packet. */
200     bool has_learn;             /* Actions include NXAST_LEARN? */
201     bool has_normal;            /* Actions output to OFPP_NORMAL? */
202     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
203
204 /* xlate_actions() initializes and uses these members, but the client has no
205  * reason to look at them. */
206
207     int recurse;                /* Recursion level, via xlate_table_action. */
208     uint32_t priority;          /* Current flow priority. 0 if none. */
209     struct flow base_flow;      /* Flow at the last commit. */
210     uint32_t base_priority;     /* Priority at the last commit. */
211     uint8_t table_id;           /* OpenFlow table ID where flow was found. */
212     uint32_t sflow_n_outputs;   /* Number of output ports. */
213     uint16_t sflow_odp_port;    /* Output port for composing sFlow action. */
214     uint16_t user_cookie_offset;/* Used for user_action_cookie fixup. */
215 };
216
217 static void action_xlate_ctx_init(struct action_xlate_ctx *,
218                                   struct ofproto_dpif *, const struct flow *,
219                                   const struct ofpbuf *);
220 static struct ofpbuf *xlate_actions(struct action_xlate_ctx *,
221                                     const union ofp_action *in, size_t n_in);
222
223 /* An exact-match instantiation of an OpenFlow flow. */
224 struct facet {
225     long long int used;         /* Time last used; time created if not used. */
226
227     /* These statistics:
228      *
229      *   - Do include packets and bytes sent "by hand", e.g. with
230      *     dpif_execute().
231      *
232      *   - Do include packets and bytes that were obtained from the datapath
233      *     when its statistics were reset (e.g. dpif_flow_put() with
234      *     DPIF_FP_ZERO_STATS).
235      */
236     uint64_t packet_count;       /* Number of packets received. */
237     uint64_t byte_count;         /* Number of bytes received. */
238
239     uint64_t dp_packet_count;    /* Last known packet count in the datapath. */
240     uint64_t dp_byte_count;      /* Last known byte count in the datapath. */
241
242     uint64_t rs_packet_count;    /* Packets pushed to resubmit children. */
243     uint64_t rs_byte_count;      /* Bytes pushed to resubmit children. */
244     long long int rs_used;       /* Used time pushed to resubmit children. */
245
246     uint64_t accounted_bytes;    /* Bytes processed by facet_account(). */
247
248     struct hmap_node hmap_node;  /* In owning ofproto's 'facets' hmap. */
249     struct list list_node;       /* In owning rule's 'facets' list. */
250     struct rule_dpif *rule;      /* Owning rule. */
251     struct flow flow;            /* Exact-match flow. */
252     bool installed;              /* Installed in datapath? */
253     bool may_install;            /* True ordinarily; false if actions must
254                                   * be reassessed for every packet. */
255     bool has_learn;              /* Actions include NXAST_LEARN? */
256     bool has_normal;             /* Actions output to OFPP_NORMAL? */
257     size_t actions_len;          /* Number of bytes in actions[]. */
258     struct nlattr *actions;      /* Datapath actions. */
259     tag_type tags;               /* Tags. */
260     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
261 };
262
263 static struct facet *facet_create(struct rule_dpif *, const struct flow *);
264 static void facet_remove(struct ofproto_dpif *, struct facet *);
265 static void facet_free(struct facet *);
266
267 static struct facet *facet_find(struct ofproto_dpif *, const struct flow *);
268 static struct facet *facet_lookup_valid(struct ofproto_dpif *,
269                                         const struct flow *);
270 static bool facet_revalidate(struct ofproto_dpif *, struct facet *);
271
272 static bool execute_controller_action(struct ofproto_dpif *,
273                                       const struct flow *,
274                                       const struct nlattr *odp_actions,
275                                       size_t actions_len,
276                                       struct ofpbuf *packet);
277 static void facet_execute(struct ofproto_dpif *, struct facet *,
278                           struct ofpbuf *packet);
279
280 static int facet_put__(struct ofproto_dpif *, struct facet *,
281                        const struct nlattr *actions, size_t actions_len,
282                        struct dpif_flow_stats *);
283 static void facet_install(struct ofproto_dpif *, struct facet *,
284                           bool zero_stats);
285 static void facet_uninstall(struct ofproto_dpif *, struct facet *);
286 static void facet_flush_stats(struct ofproto_dpif *, struct facet *);
287
288 static void facet_make_actions(struct ofproto_dpif *, struct facet *,
289                                const struct ofpbuf *packet);
290 static void facet_update_time(struct ofproto_dpif *, struct facet *,
291                               long long int used);
292 static void facet_update_stats(struct ofproto_dpif *, struct facet *,
293                                const struct dpif_flow_stats *);
294 static void facet_reset_counters(struct facet *);
295 static void facet_reset_dp_stats(struct facet *, struct dpif_flow_stats *);
296 static void facet_push_stats(struct facet *);
297 static void facet_account(struct ofproto_dpif *, struct facet *);
298
299 static bool facet_is_controller_flow(struct facet *);
300
301 static void flow_push_stats(const struct rule_dpif *,
302                             struct flow *, uint64_t packets, uint64_t bytes,
303                             long long int used);
304
305 static uint32_t rule_calculate_tag(const struct flow *,
306                                    const struct flow_wildcards *,
307                                    uint32_t basis);
308 static void rule_invalidate(const struct rule_dpif *);
309
310 struct ofport_dpif {
311     struct ofport up;
312
313     uint32_t odp_port;
314     struct ofbundle *bundle;    /* Bundle that contains this port, if any. */
315     struct list bundle_node;    /* In struct ofbundle's "ports" list. */
316     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
317     tag_type tag;               /* Tag associated with this port. */
318     uint32_t bond_stable_id;    /* stable_id to use as bond slave, or 0. */
319     bool may_enable;            /* May be enabled in bonds. */
320
321     struct stp_port *stp_port;  /* Spanning Tree Protocol, if any. */
322     enum stp_state stp_state;   /* Always STP_DISABLED if STP not in use. */
323     long long int stp_state_entered;
324 };
325
326 static struct ofport_dpif *
327 ofport_dpif_cast(const struct ofport *ofport)
328 {
329     assert(ofport->ofproto->ofproto_class == &ofproto_dpif_class);
330     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
331 }
332
333 static void port_run(struct ofport_dpif *);
334 static void port_wait(struct ofport_dpif *);
335 static int set_cfm(struct ofport *, const struct cfm_settings *);
336
337 struct dpif_completion {
338     struct list list_node;
339     struct ofoperation *op;
340 };
341
342 /* Extra information about a classifier table.
343  * Currently used just for optimized flow revalidation. */
344 struct table_dpif {
345     /* If either of these is nonnull, then this table has a form that allows
346      * flows to be tagged to avoid revalidating most flows for the most common
347      * kinds of flow table changes. */
348     struct cls_table *catchall_table; /* Table that wildcards all fields. */
349     struct cls_table *other_table;    /* Table with any other wildcard set. */
350     uint32_t basis;                   /* Keeps each table's tags separate. */
351 };
352
353 struct ofproto_dpif {
354     struct ofproto up;
355     struct dpif *dpif;
356     int max_ports;
357
358     /* Statistics. */
359     uint64_t n_matches;
360
361     /* Bridging. */
362     struct netflow *netflow;
363     struct dpif_sflow *sflow;
364     struct hmap bundles;        /* Contains "struct ofbundle"s. */
365     struct mac_learning *ml;
366     struct ofmirror *mirrors[MAX_MIRRORS];
367     bool has_bonded_bundles;
368
369     /* Expiration. */
370     struct timer next_expiration;
371
372     /* Facets. */
373     struct hmap facets;
374
375     /* Revalidation. */
376     struct table_dpif tables[N_TABLES];
377     bool need_revalidate;
378     struct tag_set revalidate_set;
379
380     /* Support for debugging async flow mods. */
381     struct list completions;
382
383     bool has_bundle_action; /* True when the first bundle action appears. */
384
385     /* Spanning tree. */
386     struct stp *stp;
387     long long int stp_last_tick;
388 };
389
390 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
391  * for debugging the asynchronous flow_mod implementation.) */
392 static bool clogged;
393
394 static void ofproto_dpif_unixctl_init(void);
395
396 static struct ofproto_dpif *
397 ofproto_dpif_cast(const struct ofproto *ofproto)
398 {
399     assert(ofproto->ofproto_class == &ofproto_dpif_class);
400     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
401 }
402
403 static struct ofport_dpif *get_ofp_port(struct ofproto_dpif *,
404                                         uint16_t ofp_port);
405 static struct ofport_dpif *get_odp_port(struct ofproto_dpif *,
406                                         uint32_t odp_port);
407
408 /* Packet processing. */
409 static void update_learning_table(struct ofproto_dpif *,
410                                   const struct flow *, int vlan,
411                                   struct ofbundle *);
412 static bool is_admissible(struct ofproto_dpif *, const struct flow *,
413                           bool have_packet, tag_type *, int *vlanp,
414                           struct ofbundle **in_bundlep);
415
416 /* Upcalls. */
417 #define FLOW_MISS_MAX_BATCH 50
418 static int handle_upcalls(struct ofproto_dpif *, unsigned int max_batch);
419
420 /* Flow expiration. */
421 static int expire(struct ofproto_dpif *);
422
423 /* Utilities. */
424 static int send_packet(struct ofproto_dpif *, uint32_t odp_port,
425                        const struct ofpbuf *packet);
426 static size_t
427 compose_sflow_action(const struct ofproto_dpif *, struct ofpbuf *odp_actions,
428                      const struct flow *, uint32_t odp_port);
429 /* Global variables. */
430 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
431 \f
432 /* Factory functions. */
433
434 static void
435 enumerate_types(struct sset *types)
436 {
437     dp_enumerate_types(types);
438 }
439
440 static int
441 enumerate_names(const char *type, struct sset *names)
442 {
443     return dp_enumerate_names(type, names);
444 }
445
446 static int
447 del(const char *type, const char *name)
448 {
449     struct dpif *dpif;
450     int error;
451
452     error = dpif_open(name, type, &dpif);
453     if (!error) {
454         error = dpif_delete(dpif);
455         dpif_close(dpif);
456     }
457     return error;
458 }
459 \f
460 /* Basic life-cycle. */
461
462 static struct ofproto *
463 alloc(void)
464 {
465     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
466     return &ofproto->up;
467 }
468
469 static void
470 dealloc(struct ofproto *ofproto_)
471 {
472     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
473     free(ofproto);
474 }
475
476 static int
477 construct(struct ofproto *ofproto_, int *n_tablesp)
478 {
479     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
480     const char *name = ofproto->up.name;
481     int error;
482     int i;
483
484     error = dpif_create_and_open(name, ofproto->up.type, &ofproto->dpif);
485     if (error) {
486         VLOG_ERR("failed to open datapath %s: %s", name, strerror(error));
487         return error;
488     }
489
490     ofproto->max_ports = dpif_get_max_ports(ofproto->dpif);
491     ofproto->n_matches = 0;
492
493     dpif_flow_flush(ofproto->dpif);
494     dpif_recv_purge(ofproto->dpif);
495
496     error = dpif_recv_set_mask(ofproto->dpif,
497                                ((1u << DPIF_UC_MISS) |
498                                 (1u << DPIF_UC_ACTION)));
499     if (error) {
500         VLOG_ERR("failed to listen on datapath %s: %s", name, strerror(error));
501         dpif_close(ofproto->dpif);
502         return error;
503     }
504
505     ofproto->netflow = NULL;
506     ofproto->sflow = NULL;
507     ofproto->stp = NULL;
508     hmap_init(&ofproto->bundles);
509     ofproto->ml = mac_learning_create();
510     for (i = 0; i < MAX_MIRRORS; i++) {
511         ofproto->mirrors[i] = NULL;
512     }
513     ofproto->has_bonded_bundles = false;
514
515     timer_set_duration(&ofproto->next_expiration, 1000);
516
517     hmap_init(&ofproto->facets);
518
519     for (i = 0; i < N_TABLES; i++) {
520         struct table_dpif *table = &ofproto->tables[i];
521
522         table->catchall_table = NULL;
523         table->other_table = NULL;
524         table->basis = random_uint32();
525     }
526     ofproto->need_revalidate = false;
527     tag_set_init(&ofproto->revalidate_set);
528
529     list_init(&ofproto->completions);
530
531     ofproto_dpif_unixctl_init();
532
533     ofproto->has_bundle_action = false;
534
535     *n_tablesp = N_TABLES;
536     return 0;
537 }
538
539 static void
540 complete_operations(struct ofproto_dpif *ofproto)
541 {
542     struct dpif_completion *c, *next;
543
544     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
545         ofoperation_complete(c->op, 0);
546         list_remove(&c->list_node);
547         free(c);
548     }
549 }
550
551 static void
552 destruct(struct ofproto *ofproto_)
553 {
554     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
555     struct rule_dpif *rule, *next_rule;
556     struct classifier *table;
557     int i;
558
559     complete_operations(ofproto);
560
561     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
562         struct cls_cursor cursor;
563
564         cls_cursor_init(&cursor, table, NULL);
565         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
566             ofproto_rule_destroy(&rule->up);
567         }
568     }
569
570     for (i = 0; i < MAX_MIRRORS; i++) {
571         mirror_destroy(ofproto->mirrors[i]);
572     }
573
574     netflow_destroy(ofproto->netflow);
575     dpif_sflow_destroy(ofproto->sflow);
576     hmap_destroy(&ofproto->bundles);
577     mac_learning_destroy(ofproto->ml);
578
579     hmap_destroy(&ofproto->facets);
580
581     dpif_close(ofproto->dpif);
582 }
583
584 static int
585 run(struct ofproto *ofproto_)
586 {
587     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
588     struct ofport_dpif *ofport;
589     struct ofbundle *bundle;
590     unsigned int work;
591
592     if (!clogged) {
593         complete_operations(ofproto);
594     }
595     dpif_run(ofproto->dpif);
596
597     /* Handle one or more batches of upcalls, until there's nothing left to do
598      * or until we do a fixed total amount of work.
599      *
600      * We do work in batches because it can be much cheaper to set up a number
601      * of flows and fire off their patches all at once.  We do multiple batches
602      * because in some cases handling a packet can cause another packet to be
603      * queued almost immediately as part of the return flow.  Both
604      * optimizations can make major improvements on some benchmarks and
605      * presumably for real traffic as well. */
606     work = 0;
607     while (work < FLOW_MISS_MAX_BATCH) {
608         int retval = handle_upcalls(ofproto, FLOW_MISS_MAX_BATCH - work);
609         if (retval < 0) {
610             return -retval;
611         } else if (!retval) {
612             break;
613         } else {
614             work += retval;
615         }
616     }
617
618     if (timer_expired(&ofproto->next_expiration)) {
619         int delay = expire(ofproto);
620         timer_set_duration(&ofproto->next_expiration, delay);
621     }
622
623     if (ofproto->netflow) {
624         netflow_run(ofproto->netflow);
625     }
626     if (ofproto->sflow) {
627         dpif_sflow_run(ofproto->sflow);
628     }
629
630     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
631         port_run(ofport);
632     }
633     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
634         bundle_run(bundle);
635     }
636
637     stp_run(ofproto);
638     mac_learning_run(ofproto->ml, &ofproto->revalidate_set);
639
640     /* Now revalidate if there's anything to do. */
641     if (ofproto->need_revalidate
642         || !tag_set_is_empty(&ofproto->revalidate_set)) {
643         struct tag_set revalidate_set = ofproto->revalidate_set;
644         bool revalidate_all = ofproto->need_revalidate;
645         struct facet *facet, *next;
646
647         /* Clear the revalidation flags. */
648         tag_set_init(&ofproto->revalidate_set);
649         ofproto->need_revalidate = false;
650
651         HMAP_FOR_EACH_SAFE (facet, next, hmap_node, &ofproto->facets) {
652             if (revalidate_all
653                 || tag_set_intersects(&revalidate_set, facet->tags)) {
654                 facet_revalidate(ofproto, facet);
655             }
656         }
657     }
658
659     return 0;
660 }
661
662 static void
663 wait(struct ofproto *ofproto_)
664 {
665     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
666     struct ofport_dpif *ofport;
667     struct ofbundle *bundle;
668
669     if (!clogged && !list_is_empty(&ofproto->completions)) {
670         poll_immediate_wake();
671     }
672
673     dpif_wait(ofproto->dpif);
674     dpif_recv_wait(ofproto->dpif);
675     if (ofproto->sflow) {
676         dpif_sflow_wait(ofproto->sflow);
677     }
678     if (!tag_set_is_empty(&ofproto->revalidate_set)) {
679         poll_immediate_wake();
680     }
681     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
682         port_wait(ofport);
683     }
684     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
685         bundle_wait(bundle);
686     }
687     mac_learning_wait(ofproto->ml);
688     stp_wait(ofproto);
689     if (ofproto->need_revalidate) {
690         /* Shouldn't happen, but if it does just go around again. */
691         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
692         poll_immediate_wake();
693     } else {
694         timer_wait(&ofproto->next_expiration);
695     }
696 }
697
698 static void
699 flush(struct ofproto *ofproto_)
700 {
701     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
702     struct facet *facet, *next_facet;
703
704     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
705         /* Mark the facet as not installed so that facet_remove() doesn't
706          * bother trying to uninstall it.  There is no point in uninstalling it
707          * individually since we are about to blow away all the facets with
708          * dpif_flow_flush(). */
709         facet->installed = false;
710         facet->dp_packet_count = 0;
711         facet->dp_byte_count = 0;
712         facet_remove(ofproto, facet);
713     }
714     dpif_flow_flush(ofproto->dpif);
715 }
716
717 static void
718 get_features(struct ofproto *ofproto_ OVS_UNUSED,
719              bool *arp_match_ip, uint32_t *actions)
720 {
721     *arp_match_ip = true;
722     *actions = ((1u << OFPAT_OUTPUT) |
723                 (1u << OFPAT_SET_VLAN_VID) |
724                 (1u << OFPAT_SET_VLAN_PCP) |
725                 (1u << OFPAT_STRIP_VLAN) |
726                 (1u << OFPAT_SET_DL_SRC) |
727                 (1u << OFPAT_SET_DL_DST) |
728                 (1u << OFPAT_SET_NW_SRC) |
729                 (1u << OFPAT_SET_NW_DST) |
730                 (1u << OFPAT_SET_NW_TOS) |
731                 (1u << OFPAT_SET_TP_SRC) |
732                 (1u << OFPAT_SET_TP_DST) |
733                 (1u << OFPAT_ENQUEUE));
734 }
735
736 static void
737 get_tables(struct ofproto *ofproto_, struct ofp_table_stats *ots)
738 {
739     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
740     struct dpif_dp_stats s;
741
742     strcpy(ots->name, "classifier");
743
744     dpif_get_dp_stats(ofproto->dpif, &s);
745     put_32aligned_be64(&ots->lookup_count, htonll(s.n_hit + s.n_missed));
746     put_32aligned_be64(&ots->matched_count,
747                        htonll(s.n_hit + ofproto->n_matches));
748 }
749
750 static int
751 set_netflow(struct ofproto *ofproto_,
752             const struct netflow_options *netflow_options)
753 {
754     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
755
756     if (netflow_options) {
757         if (!ofproto->netflow) {
758             ofproto->netflow = netflow_create();
759         }
760         return netflow_set_options(ofproto->netflow, netflow_options);
761     } else {
762         netflow_destroy(ofproto->netflow);
763         ofproto->netflow = NULL;
764         return 0;
765     }
766 }
767
768 static struct ofport *
769 port_alloc(void)
770 {
771     struct ofport_dpif *port = xmalloc(sizeof *port);
772     return &port->up;
773 }
774
775 static void
776 port_dealloc(struct ofport *port_)
777 {
778     struct ofport_dpif *port = ofport_dpif_cast(port_);
779     free(port);
780 }
781
782 static int
783 port_construct(struct ofport *port_)
784 {
785     struct ofport_dpif *port = ofport_dpif_cast(port_);
786     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
787
788     ofproto->need_revalidate = true;
789     port->odp_port = ofp_port_to_odp_port(port->up.ofp_port);
790     port->bundle = NULL;
791     port->cfm = NULL;
792     port->tag = tag_create_random();
793     port->may_enable = true;
794     port->stp_port = NULL;
795     port->stp_state = STP_DISABLED;
796
797     if (ofproto->sflow) {
798         dpif_sflow_add_port(ofproto->sflow, port->odp_port,
799                             netdev_get_name(port->up.netdev));
800     }
801
802     return 0;
803 }
804
805 static void
806 port_destruct(struct ofport *port_)
807 {
808     struct ofport_dpif *port = ofport_dpif_cast(port_);
809     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
810
811     ofproto->need_revalidate = true;
812     bundle_remove(port_);
813     set_cfm(port_, NULL);
814     if (ofproto->sflow) {
815         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
816     }
817 }
818
819 static void
820 port_modified(struct ofport *port_)
821 {
822     struct ofport_dpif *port = ofport_dpif_cast(port_);
823
824     if (port->bundle && port->bundle->bond) {
825         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
826     }
827 }
828
829 static void
830 port_reconfigured(struct ofport *port_, ovs_be32 old_config)
831 {
832     struct ofport_dpif *port = ofport_dpif_cast(port_);
833     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
834     ovs_be32 changed = old_config ^ port->up.opp.config;
835
836     if (changed & htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP |
837                         OFPPC_NO_FWD | OFPPC_NO_FLOOD)) {
838         ofproto->need_revalidate = true;
839
840         if (changed & htonl(OFPPC_NO_FLOOD) && port->bundle) {
841             bundle_update(port->bundle);
842         }
843     }
844 }
845
846 static int
847 set_sflow(struct ofproto *ofproto_,
848           const struct ofproto_sflow_options *sflow_options)
849 {
850     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
851     struct dpif_sflow *ds = ofproto->sflow;
852
853     if (sflow_options) {
854         if (!ds) {
855             struct ofport_dpif *ofport;
856
857             ds = ofproto->sflow = dpif_sflow_create(ofproto->dpif);
858             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
859                 dpif_sflow_add_port(ds, ofport->odp_port,
860                                     netdev_get_name(ofport->up.netdev));
861             }
862             ofproto->need_revalidate = true;
863         }
864         dpif_sflow_set_options(ds, sflow_options);
865     } else {
866         if (ds) {
867             dpif_sflow_destroy(ds);
868             ofproto->need_revalidate = true;
869             ofproto->sflow = NULL;
870         }
871     }
872     return 0;
873 }
874
875 static int
876 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
877 {
878     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
879     int error;
880
881     if (!s) {
882         error = 0;
883     } else {
884         if (!ofport->cfm) {
885             struct ofproto_dpif *ofproto;
886
887             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
888             ofproto->need_revalidate = true;
889             ofport->cfm = cfm_create(netdev_get_name(ofport->up.netdev));
890         }
891
892         if (cfm_configure(ofport->cfm, s)) {
893             return 0;
894         }
895
896         error = EINVAL;
897     }
898     cfm_destroy(ofport->cfm);
899     ofport->cfm = NULL;
900     return error;
901 }
902
903 static int
904 get_cfm_fault(const struct ofport *ofport_)
905 {
906     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
907
908     return ofport->cfm ? cfm_get_fault(ofport->cfm) : -1;
909 }
910
911 static int
912 get_cfm_remote_mpids(const struct ofport *ofport_, const uint64_t **rmps,
913                      size_t *n_rmps)
914 {
915     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
916
917     if (ofport->cfm) {
918         cfm_get_remote_mpids(ofport->cfm, rmps, n_rmps);
919         return 0;
920     } else {
921         return -1;
922     }
923 }
924 \f
925 /* Spanning Tree. */
926
927 static void
928 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
929 {
930     struct ofproto_dpif *ofproto = ofproto_;
931     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
932     struct ofport_dpif *ofport;
933
934     ofport = stp_port_get_aux(sp);
935     if (!ofport) {
936         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
937                      ofproto->up.name, port_num);
938     } else {
939         struct eth_header *eth = pkt->l2;
940
941         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
942         if (eth_addr_is_zero(eth->eth_src)) {
943             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
944                          "with unknown MAC", ofproto->up.name, port_num);
945         } else {
946             int error = netdev_send(ofport->up.netdev, pkt);
947             if (error) {
948                 VLOG_WARN_RL(&rl, "%s: sending BPDU on port %s failed (%s)",
949                              ofproto->up.name,
950                              netdev_get_name(ofport->up.netdev),
951                              strerror(error));
952             }
953         }
954     }
955     ofpbuf_delete(pkt);
956 }
957
958 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
959 static int
960 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
961 {
962     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
963
964     /* Only revalidate flows if the configuration changed. */
965     if (!s != !ofproto->stp) {
966         ofproto->need_revalidate = true;
967     }
968
969     if (s) {
970         if (!ofproto->stp) {
971             ofproto->stp = stp_create(ofproto_->name, s->system_id,
972                                       send_bpdu_cb, ofproto);
973             ofproto->stp_last_tick = time_msec();
974         }
975
976         stp_set_bridge_id(ofproto->stp, s->system_id);
977         stp_set_bridge_priority(ofproto->stp, s->priority);
978         stp_set_hello_time(ofproto->stp, s->hello_time);
979         stp_set_max_age(ofproto->stp, s->max_age);
980         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
981     }  else {
982         stp_destroy(ofproto->stp);
983         ofproto->stp = NULL;
984     }
985
986     return 0;
987 }
988
989 static int
990 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
991 {
992     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
993
994     if (ofproto->stp) {
995         s->enabled = true;
996         s->bridge_id = stp_get_bridge_id(ofproto->stp);
997         s->designated_root = stp_get_designated_root(ofproto->stp);
998         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
999     } else {
1000         s->enabled = false;
1001     }
1002
1003     return 0;
1004 }
1005
1006 static void
1007 update_stp_port_state(struct ofport_dpif *ofport)
1008 {
1009     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1010     enum stp_state state;
1011
1012     /* Figure out new state. */
1013     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
1014                              : STP_DISABLED;
1015
1016     /* Update state. */
1017     if (ofport->stp_state != state) {
1018         ovs_be32 of_state;
1019         bool fwd_change;
1020
1021         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
1022                     netdev_get_name(ofport->up.netdev),
1023                     stp_state_name(ofport->stp_state),
1024                     stp_state_name(state));
1025         if (stp_learn_in_state(ofport->stp_state)
1026                 != stp_learn_in_state(state)) {
1027             /* xxx Learning action flows should also be flushed. */
1028             mac_learning_flush(ofproto->ml);
1029         }
1030         fwd_change = stp_forward_in_state(ofport->stp_state)
1031                         != stp_forward_in_state(state);
1032
1033         ofproto->need_revalidate = true;
1034         ofport->stp_state = state;
1035         ofport->stp_state_entered = time_msec();
1036
1037         if (fwd_change && ofport->bundle) {
1038             bundle_update(ofport->bundle);
1039         }
1040
1041         /* Update the STP state bits in the OpenFlow port description. */
1042         of_state = (ofport->up.opp.state & htonl(~OFPPS_STP_MASK))
1043                          | htonl(state == STP_LISTENING ? OFPPS_STP_LISTEN
1044                                : state == STP_LEARNING ? OFPPS_STP_LEARN
1045                                : state == STP_FORWARDING ? OFPPS_STP_FORWARD
1046                                : state == STP_BLOCKING ?  OFPPS_STP_BLOCK
1047                                : 0);
1048         ofproto_port_set_state(&ofport->up, of_state);
1049     }
1050 }
1051
1052 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
1053  * caller is responsible for assigning STP port numbers and ensuring
1054  * there are no duplicates. */
1055 static int
1056 set_stp_port(struct ofport *ofport_,
1057              const struct ofproto_port_stp_settings *s)
1058 {
1059     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1060     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1061     struct stp_port *sp = ofport->stp_port;
1062
1063     if (!s || !s->enable) {
1064         if (sp) {
1065             ofport->stp_port = NULL;
1066             stp_port_disable(sp);
1067             update_stp_port_state(ofport);
1068         }
1069         return 0;
1070     } else if (sp && stp_port_no(sp) != s->port_num
1071             && ofport == stp_port_get_aux(sp)) {
1072         /* The port-id changed, so disable the old one if it's not
1073          * already in use by another port. */
1074         stp_port_disable(sp);
1075     }
1076
1077     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
1078     stp_port_enable(sp);
1079
1080     stp_port_set_aux(sp, ofport);
1081     stp_port_set_priority(sp, s->priority);
1082     stp_port_set_path_cost(sp, s->path_cost);
1083
1084     update_stp_port_state(ofport);
1085
1086     return 0;
1087 }
1088
1089 static int
1090 get_stp_port_status(struct ofport *ofport_,
1091                     struct ofproto_port_stp_status *s)
1092 {
1093     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1094     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1095     struct stp_port *sp = ofport->stp_port;
1096
1097     if (!ofproto->stp || !sp) {
1098         s->enabled = false;
1099         return 0;
1100     }
1101
1102     s->enabled = true;
1103     s->port_id = stp_port_get_id(sp);
1104     s->state = stp_port_get_state(sp);
1105     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
1106     s->role = stp_port_get_role(sp);
1107     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
1108
1109     return 0;
1110 }
1111
1112 static void
1113 stp_run(struct ofproto_dpif *ofproto)
1114 {
1115     if (ofproto->stp) {
1116         long long int now = time_msec();
1117         long long int elapsed = now - ofproto->stp_last_tick;
1118         struct stp_port *sp;
1119
1120         if (elapsed > 0) {
1121             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
1122             ofproto->stp_last_tick = now;
1123         }
1124         while (stp_get_changed_port(ofproto->stp, &sp)) {
1125             struct ofport_dpif *ofport = stp_port_get_aux(sp);
1126
1127             if (ofport) {
1128                 update_stp_port_state(ofport);
1129             }
1130         }
1131     }
1132 }
1133
1134 static void
1135 stp_wait(struct ofproto_dpif *ofproto)
1136 {
1137     if (ofproto->stp) {
1138         poll_timer_wait(1000);
1139     }
1140 }
1141
1142 /* Returns true if STP should process 'flow'. */
1143 static bool
1144 stp_should_process_flow(const struct flow *flow)
1145 {
1146     return eth_addr_equals(flow->dl_dst, eth_addr_stp);
1147 }
1148
1149 static void
1150 stp_process_packet(const struct ofport_dpif *ofport,
1151                    const struct ofpbuf *packet)
1152 {
1153     struct ofpbuf payload = *packet;
1154     struct eth_header *eth = payload.data;
1155     struct stp_port *sp = ofport->stp_port;
1156
1157     /* Sink packets on ports that have STP disabled when the bridge has
1158      * STP enabled. */
1159     if (!sp || stp_port_get_state(sp) == STP_DISABLED) {
1160         return;
1161     }
1162
1163     /* Trim off padding on payload. */
1164     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1165         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
1166     }
1167
1168     if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1169         stp_received_bpdu(sp, payload.data, payload.size);
1170     }
1171 }
1172 \f
1173 /* Bundles. */
1174
1175 /* Expires all MAC learning entries associated with 'port' and forces ofproto
1176  * to revalidate every flow. */
1177 static void
1178 bundle_flush_macs(struct ofbundle *bundle)
1179 {
1180     struct ofproto_dpif *ofproto = bundle->ofproto;
1181     struct mac_learning *ml = ofproto->ml;
1182     struct mac_entry *mac, *next_mac;
1183
1184     ofproto->need_revalidate = true;
1185     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
1186         if (mac->port.p == bundle) {
1187             mac_learning_expire(ml, mac);
1188         }
1189     }
1190 }
1191
1192 static struct ofbundle *
1193 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
1194 {
1195     struct ofbundle *bundle;
1196
1197     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
1198                              &ofproto->bundles) {
1199         if (bundle->aux == aux) {
1200             return bundle;
1201         }
1202     }
1203     return NULL;
1204 }
1205
1206 /* Looks up each of the 'n_auxes' pointers in 'auxes' as bundles and adds the
1207  * ones that are found to 'bundles'. */
1208 static void
1209 bundle_lookup_multiple(struct ofproto_dpif *ofproto,
1210                        void **auxes, size_t n_auxes,
1211                        struct hmapx *bundles)
1212 {
1213     size_t i;
1214
1215     hmapx_init(bundles);
1216     for (i = 0; i < n_auxes; i++) {
1217         struct ofbundle *bundle = bundle_lookup(ofproto, auxes[i]);
1218         if (bundle) {
1219             hmapx_add(bundles, bundle);
1220         }
1221     }
1222 }
1223
1224 static void
1225 bundle_update(struct ofbundle *bundle)
1226 {
1227     struct ofport_dpif *port;
1228
1229     bundle->floodable = true;
1230     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1231         if (port->up.opp.config & htonl(OFPPC_NO_FLOOD)
1232                     || !stp_forward_in_state(port->stp_state)) {
1233             bundle->floodable = false;
1234             break;
1235         }
1236     }
1237 }
1238
1239 static void
1240 bundle_del_port(struct ofport_dpif *port)
1241 {
1242     struct ofbundle *bundle = port->bundle;
1243
1244     bundle->ofproto->need_revalidate = true;
1245
1246     list_remove(&port->bundle_node);
1247     port->bundle = NULL;
1248
1249     if (bundle->lacp) {
1250         lacp_slave_unregister(bundle->lacp, port);
1251     }
1252     if (bundle->bond) {
1253         bond_slave_unregister(bundle->bond, port);
1254     }
1255
1256     bundle_update(bundle);
1257 }
1258
1259 static bool
1260 bundle_add_port(struct ofbundle *bundle, uint32_t ofp_port,
1261                 struct lacp_slave_settings *lacp,
1262                 uint32_t bond_stable_id)
1263 {
1264     struct ofport_dpif *port;
1265
1266     port = get_ofp_port(bundle->ofproto, ofp_port);
1267     if (!port) {
1268         return false;
1269     }
1270
1271     if (port->bundle != bundle) {
1272         bundle->ofproto->need_revalidate = true;
1273         if (port->bundle) {
1274             bundle_del_port(port);
1275         }
1276
1277         port->bundle = bundle;
1278         list_push_back(&bundle->ports, &port->bundle_node);
1279         if (port->up.opp.config & htonl(OFPPC_NO_FLOOD)
1280                     || !stp_forward_in_state(port->stp_state)) {
1281             bundle->floodable = false;
1282         }
1283     }
1284     if (lacp) {
1285         port->bundle->ofproto->need_revalidate = true;
1286         lacp_slave_register(bundle->lacp, port, lacp);
1287     }
1288
1289     port->bond_stable_id = bond_stable_id;
1290
1291     return true;
1292 }
1293
1294 static void
1295 bundle_destroy(struct ofbundle *bundle)
1296 {
1297     struct ofproto_dpif *ofproto;
1298     struct ofport_dpif *port, *next_port;
1299     int i;
1300
1301     if (!bundle) {
1302         return;
1303     }
1304
1305     ofproto = bundle->ofproto;
1306     for (i = 0; i < MAX_MIRRORS; i++) {
1307         struct ofmirror *m = ofproto->mirrors[i];
1308         if (m) {
1309             if (m->out == bundle) {
1310                 mirror_destroy(m);
1311             } else if (hmapx_find_and_delete(&m->srcs, bundle)
1312                        || hmapx_find_and_delete(&m->dsts, bundle)) {
1313                 ofproto->need_revalidate = true;
1314             }
1315         }
1316     }
1317
1318     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
1319         bundle_del_port(port);
1320     }
1321
1322     bundle_flush_macs(bundle);
1323     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
1324     free(bundle->name);
1325     free(bundle->trunks);
1326     lacp_destroy(bundle->lacp);
1327     bond_destroy(bundle->bond);
1328     free(bundle);
1329 }
1330
1331 static int
1332 bundle_set(struct ofproto *ofproto_, void *aux,
1333            const struct ofproto_bundle_settings *s)
1334 {
1335     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1336     bool need_flush = false;
1337     struct ofport_dpif *port;
1338     struct ofbundle *bundle;
1339     unsigned long *trunks;
1340     int vlan;
1341     size_t i;
1342     bool ok;
1343
1344     if (!s) {
1345         bundle_destroy(bundle_lookup(ofproto, aux));
1346         return 0;
1347     }
1348
1349     assert(s->n_slaves == 1 || s->bond != NULL);
1350     assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
1351
1352     bundle = bundle_lookup(ofproto, aux);
1353     if (!bundle) {
1354         bundle = xmalloc(sizeof *bundle);
1355
1356         bundle->ofproto = ofproto;
1357         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
1358                     hash_pointer(aux, 0));
1359         bundle->aux = aux;
1360         bundle->name = NULL;
1361
1362         list_init(&bundle->ports);
1363         bundle->vlan_mode = PORT_VLAN_TRUNK;
1364         bundle->vlan = -1;
1365         bundle->trunks = NULL;
1366         bundle->lacp = NULL;
1367         bundle->bond = NULL;
1368
1369         bundle->floodable = true;
1370
1371         bundle->src_mirrors = 0;
1372         bundle->dst_mirrors = 0;
1373         bundle->mirror_out = 0;
1374     }
1375
1376     if (!bundle->name || strcmp(s->name, bundle->name)) {
1377         free(bundle->name);
1378         bundle->name = xstrdup(s->name);
1379     }
1380
1381     /* LACP. */
1382     if (s->lacp) {
1383         if (!bundle->lacp) {
1384             ofproto->need_revalidate = true;
1385             bundle->lacp = lacp_create();
1386         }
1387         lacp_configure(bundle->lacp, s->lacp);
1388     } else {
1389         lacp_destroy(bundle->lacp);
1390         bundle->lacp = NULL;
1391     }
1392
1393     /* Update set of ports. */
1394     ok = true;
1395     for (i = 0; i < s->n_slaves; i++) {
1396         if (!bundle_add_port(bundle, s->slaves[i],
1397                              s->lacp ? &s->lacp_slaves[i] : NULL,
1398                              s->bond_stable_ids ? s->bond_stable_ids[i] : 0)) {
1399             ok = false;
1400         }
1401     }
1402     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
1403         struct ofport_dpif *next_port;
1404
1405         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
1406             for (i = 0; i < s->n_slaves; i++) {
1407                 if (s->slaves[i] == port->up.ofp_port) {
1408                     goto found;
1409                 }
1410             }
1411
1412             bundle_del_port(port);
1413         found: ;
1414         }
1415     }
1416     assert(list_size(&bundle->ports) <= s->n_slaves);
1417
1418     if (list_is_empty(&bundle->ports)) {
1419         bundle_destroy(bundle);
1420         return EINVAL;
1421     }
1422
1423     /* Set VLAN tagging mode */
1424     if (s->vlan_mode != bundle->vlan_mode) {
1425         bundle->vlan_mode = s->vlan_mode;
1426         need_flush = true;
1427     }
1428
1429     /* Set VLAN tag. */
1430     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
1431             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
1432             : 0);
1433     if (vlan != bundle->vlan) {
1434         bundle->vlan = vlan;
1435         need_flush = true;
1436     }
1437
1438     /* Get trunked VLANs. */
1439     switch (s->vlan_mode) {
1440     case PORT_VLAN_ACCESS:
1441         trunks = NULL;
1442         break;
1443
1444     case PORT_VLAN_TRUNK:
1445         trunks = (unsigned long *) s->trunks;
1446         break;
1447
1448     case PORT_VLAN_NATIVE_UNTAGGED:
1449     case PORT_VLAN_NATIVE_TAGGED:
1450         if (vlan != 0 && (!s->trunks
1451                           || !bitmap_is_set(s->trunks, vlan)
1452                           || bitmap_is_set(s->trunks, 0))) {
1453             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
1454             if (s->trunks) {
1455                 trunks = bitmap_clone(s->trunks, 4096);
1456             } else {
1457                 trunks = bitmap_allocate1(4096);
1458             }
1459             bitmap_set1(trunks, vlan);
1460             bitmap_set0(trunks, 0);
1461         } else {
1462             trunks = (unsigned long *) s->trunks;
1463         }
1464         break;
1465
1466     default:
1467         NOT_REACHED();
1468     }
1469     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
1470         free(bundle->trunks);
1471         if (trunks == s->trunks) {
1472             bundle->trunks = vlan_bitmap_clone(trunks);
1473         } else {
1474             bundle->trunks = trunks;
1475             trunks = NULL;
1476         }
1477         need_flush = true;
1478     }
1479     if (trunks != s->trunks) {
1480         free(trunks);
1481     }
1482
1483     /* Bonding. */
1484     if (!list_is_short(&bundle->ports)) {
1485         bundle->ofproto->has_bonded_bundles = true;
1486         if (bundle->bond) {
1487             if (bond_reconfigure(bundle->bond, s->bond)) {
1488                 ofproto->need_revalidate = true;
1489             }
1490         } else {
1491             bundle->bond = bond_create(s->bond);
1492             ofproto->need_revalidate = true;
1493         }
1494
1495         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1496             bond_slave_register(bundle->bond, port, port->bond_stable_id,
1497                                 port->up.netdev);
1498         }
1499     } else {
1500         bond_destroy(bundle->bond);
1501         bundle->bond = NULL;
1502     }
1503
1504     /* If we changed something that would affect MAC learning, un-learn
1505      * everything on this port and force flow revalidation. */
1506     if (need_flush) {
1507         bundle_flush_macs(bundle);
1508     }
1509
1510     return 0;
1511 }
1512
1513 static void
1514 bundle_remove(struct ofport *port_)
1515 {
1516     struct ofport_dpif *port = ofport_dpif_cast(port_);
1517     struct ofbundle *bundle = port->bundle;
1518
1519     if (bundle) {
1520         bundle_del_port(port);
1521         if (list_is_empty(&bundle->ports)) {
1522             bundle_destroy(bundle);
1523         } else if (list_is_short(&bundle->ports)) {
1524             bond_destroy(bundle->bond);
1525             bundle->bond = NULL;
1526         }
1527     }
1528 }
1529
1530 static void
1531 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
1532 {
1533     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
1534     struct ofport_dpif *port = port_;
1535     uint8_t ea[ETH_ADDR_LEN];
1536     int error;
1537
1538     error = netdev_get_etheraddr(port->up.netdev, ea);
1539     if (!error) {
1540         struct ofpbuf packet;
1541         void *packet_pdu;
1542
1543         ofpbuf_init(&packet, 0);
1544         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
1545                                  pdu_size);
1546         memcpy(packet_pdu, pdu, pdu_size);
1547
1548         error = netdev_send(port->up.netdev, &packet);
1549         if (error) {
1550             VLOG_WARN_RL(&rl, "port %s: sending LACP PDU on iface %s failed "
1551                          "(%s)", port->bundle->name,
1552                          netdev_get_name(port->up.netdev), strerror(error));
1553         }
1554         ofpbuf_uninit(&packet);
1555     } else {
1556         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
1557                     "%s (%s)", port->bundle->name,
1558                     netdev_get_name(port->up.netdev), strerror(error));
1559     }
1560 }
1561
1562 static void
1563 bundle_send_learning_packets(struct ofbundle *bundle)
1564 {
1565     struct ofproto_dpif *ofproto = bundle->ofproto;
1566     int error, n_packets, n_errors;
1567     struct mac_entry *e;
1568
1569     error = n_packets = n_errors = 0;
1570     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
1571         if (e->port.p != bundle) {
1572             int ret = bond_send_learning_packet(bundle->bond, e->mac, e->vlan);
1573             if (ret) {
1574                 error = ret;
1575                 n_errors++;
1576             }
1577             n_packets++;
1578         }
1579     }
1580
1581     if (n_errors) {
1582         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1583         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
1584                      "packets, last error was: %s",
1585                      bundle->name, n_errors, n_packets, strerror(error));
1586     } else {
1587         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
1588                  bundle->name, n_packets);
1589     }
1590 }
1591
1592 static void
1593 bundle_run(struct ofbundle *bundle)
1594 {
1595     if (bundle->lacp) {
1596         lacp_run(bundle->lacp, send_pdu_cb);
1597     }
1598     if (bundle->bond) {
1599         struct ofport_dpif *port;
1600
1601         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1602             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
1603         }
1604
1605         bond_run(bundle->bond, &bundle->ofproto->revalidate_set,
1606                  lacp_negotiated(bundle->lacp));
1607         if (bond_should_send_learning_packets(bundle->bond)) {
1608             bundle_send_learning_packets(bundle);
1609         }
1610     }
1611 }
1612
1613 static void
1614 bundle_wait(struct ofbundle *bundle)
1615 {
1616     if (bundle->lacp) {
1617         lacp_wait(bundle->lacp);
1618     }
1619     if (bundle->bond) {
1620         bond_wait(bundle->bond);
1621     }
1622 }
1623 \f
1624 /* Mirrors. */
1625
1626 static int
1627 mirror_scan(struct ofproto_dpif *ofproto)
1628 {
1629     int idx;
1630
1631     for (idx = 0; idx < MAX_MIRRORS; idx++) {
1632         if (!ofproto->mirrors[idx]) {
1633             return idx;
1634         }
1635     }
1636     return -1;
1637 }
1638
1639 static struct ofmirror *
1640 mirror_lookup(struct ofproto_dpif *ofproto, void *aux)
1641 {
1642     int i;
1643
1644     for (i = 0; i < MAX_MIRRORS; i++) {
1645         struct ofmirror *mirror = ofproto->mirrors[i];
1646         if (mirror && mirror->aux == aux) {
1647             return mirror;
1648         }
1649     }
1650
1651     return NULL;
1652 }
1653
1654 static int
1655 mirror_set(struct ofproto *ofproto_, void *aux,
1656            const struct ofproto_mirror_settings *s)
1657 {
1658     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1659     mirror_mask_t mirror_bit;
1660     struct ofbundle *bundle;
1661     struct ofmirror *mirror;
1662     struct ofbundle *out;
1663     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
1664     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
1665     int out_vlan;
1666
1667     mirror = mirror_lookup(ofproto, aux);
1668     if (!s) {
1669         mirror_destroy(mirror);
1670         return 0;
1671     }
1672     if (!mirror) {
1673         int idx;
1674
1675         idx = mirror_scan(ofproto);
1676         if (idx < 0) {
1677             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
1678                       "cannot create %s",
1679                       ofproto->up.name, MAX_MIRRORS, s->name);
1680             return EFBIG;
1681         }
1682
1683         mirror = ofproto->mirrors[idx] = xzalloc(sizeof *mirror);
1684         mirror->ofproto = ofproto;
1685         mirror->idx = idx;
1686         mirror->aux = aux;
1687         mirror->out_vlan = -1;
1688         mirror->name = NULL;
1689     }
1690
1691     if (!mirror->name || strcmp(s->name, mirror->name)) {
1692         free(mirror->name);
1693         mirror->name = xstrdup(s->name);
1694     }
1695
1696     /* Get the new configuration. */
1697     if (s->out_bundle) {
1698         out = bundle_lookup(ofproto, s->out_bundle);
1699         if (!out) {
1700             mirror_destroy(mirror);
1701             return EINVAL;
1702         }
1703         out_vlan = -1;
1704     } else {
1705         out = NULL;
1706         out_vlan = s->out_vlan;
1707     }
1708     bundle_lookup_multiple(ofproto, s->srcs, s->n_srcs, &srcs);
1709     bundle_lookup_multiple(ofproto, s->dsts, s->n_dsts, &dsts);
1710
1711     /* If the configuration has not changed, do nothing. */
1712     if (hmapx_equals(&srcs, &mirror->srcs)
1713         && hmapx_equals(&dsts, &mirror->dsts)
1714         && vlan_bitmap_equal(mirror->vlans, s->src_vlans)
1715         && mirror->out == out
1716         && mirror->out_vlan == out_vlan)
1717     {
1718         hmapx_destroy(&srcs);
1719         hmapx_destroy(&dsts);
1720         return 0;
1721     }
1722
1723     hmapx_swap(&srcs, &mirror->srcs);
1724     hmapx_destroy(&srcs);
1725
1726     hmapx_swap(&dsts, &mirror->dsts);
1727     hmapx_destroy(&dsts);
1728
1729     free(mirror->vlans);
1730     mirror->vlans = vlan_bitmap_clone(s->src_vlans);
1731
1732     mirror->out = out;
1733     mirror->out_vlan = out_vlan;
1734
1735     /* Update bundles. */
1736     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
1737     HMAP_FOR_EACH (bundle, hmap_node, &mirror->ofproto->bundles) {
1738         if (hmapx_contains(&mirror->srcs, bundle)) {
1739             bundle->src_mirrors |= mirror_bit;
1740         } else {
1741             bundle->src_mirrors &= ~mirror_bit;
1742         }
1743
1744         if (hmapx_contains(&mirror->dsts, bundle)) {
1745             bundle->dst_mirrors |= mirror_bit;
1746         } else {
1747             bundle->dst_mirrors &= ~mirror_bit;
1748         }
1749
1750         if (mirror->out == bundle) {
1751             bundle->mirror_out |= mirror_bit;
1752         } else {
1753             bundle->mirror_out &= ~mirror_bit;
1754         }
1755     }
1756
1757     ofproto->need_revalidate = true;
1758     mac_learning_flush(ofproto->ml);
1759
1760     return 0;
1761 }
1762
1763 static void
1764 mirror_destroy(struct ofmirror *mirror)
1765 {
1766     struct ofproto_dpif *ofproto;
1767     mirror_mask_t mirror_bit;
1768     struct ofbundle *bundle;
1769
1770     if (!mirror) {
1771         return;
1772     }
1773
1774     ofproto = mirror->ofproto;
1775     ofproto->need_revalidate = true;
1776     mac_learning_flush(ofproto->ml);
1777
1778     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
1779     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1780         bundle->src_mirrors &= ~mirror_bit;
1781         bundle->dst_mirrors &= ~mirror_bit;
1782         bundle->mirror_out &= ~mirror_bit;
1783     }
1784
1785     hmapx_destroy(&mirror->srcs);
1786     hmapx_destroy(&mirror->dsts);
1787     free(mirror->vlans);
1788
1789     ofproto->mirrors[mirror->idx] = NULL;
1790     free(mirror->name);
1791     free(mirror);
1792 }
1793
1794 static int
1795 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
1796 {
1797     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1798     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
1799         ofproto->need_revalidate = true;
1800         mac_learning_flush(ofproto->ml);
1801     }
1802     return 0;
1803 }
1804
1805 static bool
1806 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
1807 {
1808     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1809     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
1810     return bundle && bundle->mirror_out != 0;
1811 }
1812
1813 static void
1814 forward_bpdu_changed(struct ofproto *ofproto_)
1815 {
1816     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1817     /* Revalidate cached flows whenever forward_bpdu option changes. */
1818     ofproto->need_revalidate = true;
1819 }
1820 \f
1821 /* Ports. */
1822
1823 static struct ofport_dpif *
1824 get_ofp_port(struct ofproto_dpif *ofproto, uint16_t ofp_port)
1825 {
1826     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
1827     return ofport ? ofport_dpif_cast(ofport) : NULL;
1828 }
1829
1830 static struct ofport_dpif *
1831 get_odp_port(struct ofproto_dpif *ofproto, uint32_t odp_port)
1832 {
1833     return get_ofp_port(ofproto, odp_port_to_ofp_port(odp_port));
1834 }
1835
1836 static void
1837 ofproto_port_from_dpif_port(struct ofproto_port *ofproto_port,
1838                             struct dpif_port *dpif_port)
1839 {
1840     ofproto_port->name = dpif_port->name;
1841     ofproto_port->type = dpif_port->type;
1842     ofproto_port->ofp_port = odp_port_to_ofp_port(dpif_port->port_no);
1843 }
1844
1845 static void
1846 port_run(struct ofport_dpif *ofport)
1847 {
1848     bool enable = netdev_get_carrier(ofport->up.netdev);
1849
1850     if (ofport->cfm) {
1851         cfm_run(ofport->cfm);
1852
1853         if (cfm_should_send_ccm(ofport->cfm)) {
1854             struct ofpbuf packet;
1855
1856             ofpbuf_init(&packet, 0);
1857             cfm_compose_ccm(ofport->cfm, &packet, ofport->up.opp.hw_addr);
1858             send_packet(ofproto_dpif_cast(ofport->up.ofproto),
1859                         ofport->odp_port, &packet);
1860             ofpbuf_uninit(&packet);
1861         }
1862
1863         enable = enable && !cfm_get_fault(ofport->cfm)
1864             && cfm_get_opup(ofport->cfm);
1865     }
1866
1867     if (ofport->bundle) {
1868         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
1869     }
1870
1871     if (ofport->may_enable != enable) {
1872         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1873
1874         if (ofproto->has_bundle_action) {
1875             ofproto->need_revalidate = true;
1876         }
1877     }
1878
1879     ofport->may_enable = enable;
1880 }
1881
1882 static void
1883 port_wait(struct ofport_dpif *ofport)
1884 {
1885     if (ofport->cfm) {
1886         cfm_wait(ofport->cfm);
1887     }
1888 }
1889
1890 static int
1891 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
1892                    struct ofproto_port *ofproto_port)
1893 {
1894     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1895     struct dpif_port dpif_port;
1896     int error;
1897
1898     error = dpif_port_query_by_name(ofproto->dpif, devname, &dpif_port);
1899     if (!error) {
1900         ofproto_port_from_dpif_port(ofproto_port, &dpif_port);
1901     }
1902     return error;
1903 }
1904
1905 static int
1906 port_add(struct ofproto *ofproto_, struct netdev *netdev, uint16_t *ofp_portp)
1907 {
1908     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1909     uint16_t odp_port;
1910     int error;
1911
1912     error = dpif_port_add(ofproto->dpif, netdev, &odp_port);
1913     if (!error) {
1914         *ofp_portp = odp_port_to_ofp_port(odp_port);
1915     }
1916     return error;
1917 }
1918
1919 static int
1920 port_del(struct ofproto *ofproto_, uint16_t ofp_port)
1921 {
1922     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1923     int error;
1924
1925     error = dpif_port_del(ofproto->dpif, ofp_port_to_odp_port(ofp_port));
1926     if (!error) {
1927         struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
1928         if (ofport) {
1929             /* The caller is going to close ofport->up.netdev.  If this is a
1930              * bonded port, then the bond is using that netdev, so remove it
1931              * from the bond.  The client will need to reconfigure everything
1932              * after deleting ports, so then the slave will get re-added. */
1933             bundle_remove(&ofport->up);
1934         }
1935     }
1936     return error;
1937 }
1938
1939 struct port_dump_state {
1940     struct dpif_port_dump dump;
1941     bool done;
1942 };
1943
1944 static int
1945 port_dump_start(const struct ofproto *ofproto_, void **statep)
1946 {
1947     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1948     struct port_dump_state *state;
1949
1950     *statep = state = xmalloc(sizeof *state);
1951     dpif_port_dump_start(&state->dump, ofproto->dpif);
1952     state->done = false;
1953     return 0;
1954 }
1955
1956 static int
1957 port_dump_next(const struct ofproto *ofproto_ OVS_UNUSED, void *state_,
1958                struct ofproto_port *port)
1959 {
1960     struct port_dump_state *state = state_;
1961     struct dpif_port dpif_port;
1962
1963     if (dpif_port_dump_next(&state->dump, &dpif_port)) {
1964         ofproto_port_from_dpif_port(port, &dpif_port);
1965         return 0;
1966     } else {
1967         int error = dpif_port_dump_done(&state->dump);
1968         state->done = true;
1969         return error ? error : EOF;
1970     }
1971 }
1972
1973 static int
1974 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
1975 {
1976     struct port_dump_state *state = state_;
1977
1978     if (!state->done) {
1979         dpif_port_dump_done(&state->dump);
1980     }
1981     free(state);
1982     return 0;
1983 }
1984
1985 static int
1986 port_poll(const struct ofproto *ofproto_, char **devnamep)
1987 {
1988     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1989     return dpif_port_poll(ofproto->dpif, devnamep);
1990 }
1991
1992 static void
1993 port_poll_wait(const struct ofproto *ofproto_)
1994 {
1995     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1996     dpif_port_poll_wait(ofproto->dpif);
1997 }
1998
1999 static int
2000 port_is_lacp_current(const struct ofport *ofport_)
2001 {
2002     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2003     return (ofport->bundle && ofport->bundle->lacp
2004             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
2005             : -1);
2006 }
2007 \f
2008 /* Upcall handling. */
2009
2010 /* Flow miss batching.
2011  *
2012  * Some dpifs implement operations faster when you hand them off in a batch.
2013  * To allow batching, "struct flow_miss" queues the dpif-related work needed
2014  * for a given flow.  Each "struct flow_miss" corresponds to sending one or
2015  * more packets, plus possibly installing the flow in the dpif.
2016  *
2017  * So far we only batch the operations that affect flow setup time the most.
2018  * It's possible to batch more than that, but the benefit might be minimal. */
2019 struct flow_miss {
2020     struct hmap_node hmap_node;
2021     struct flow flow;
2022     const struct nlattr *key;
2023     size_t key_len;
2024     struct list packets;
2025 };
2026
2027 struct flow_miss_op {
2028     union dpif_op dpif_op;
2029     struct facet *facet;
2030 };
2031
2032 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_NO_MATCH to each
2033  * OpenFlow controller as necessary according to their individual
2034  * configurations.
2035  *
2036  * If 'clone' is true, the caller retains ownership of 'packet'.  Otherwise,
2037  * ownership is transferred to this function. */
2038 static void
2039 send_packet_in_miss(struct ofproto_dpif *ofproto, struct ofpbuf *packet,
2040                     const struct flow *flow, bool clone)
2041 {
2042     struct ofputil_packet_in pin;
2043
2044     pin.packet = packet;
2045     pin.in_port = flow->in_port;
2046     pin.reason = OFPR_NO_MATCH;
2047     pin.buffer_id = 0;          /* not yet known */
2048     pin.send_len = 0;           /* not used for flow table misses */
2049     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
2050                            clone ? NULL : packet);
2051 }
2052
2053 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_ACTION to each
2054  * OpenFlow controller as necessary according to their individual
2055  * configurations.
2056  *
2057  * 'send_len' should be the number of bytes of 'packet' to send to the
2058  * controller, as specified in the action that caused the packet to be sent.
2059  *
2060  * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
2061  * Otherwise, ownership is transferred to this function. */
2062 static void
2063 send_packet_in_action(struct ofproto_dpif *ofproto, struct ofpbuf *packet,
2064                       uint64_t userdata, const struct flow *flow, bool clone)
2065 {
2066     struct ofputil_packet_in pin;
2067     struct user_action_cookie cookie;
2068
2069     memcpy(&cookie, &userdata, sizeof(cookie));
2070
2071     pin.packet = packet;
2072     pin.in_port = flow->in_port;
2073     pin.reason = OFPR_ACTION;
2074     pin.buffer_id = 0;          /* not yet known */
2075     pin.send_len = cookie.data;
2076     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
2077                            clone ? NULL : packet);
2078 }
2079
2080 static bool
2081 process_special(struct ofproto_dpif *ofproto, const struct flow *flow,
2082                 const struct ofpbuf *packet)
2083 {
2084     struct ofport_dpif *ofport = get_ofp_port(ofproto, flow->in_port);
2085
2086     if (!ofport) {
2087         return false;
2088     }
2089
2090     if (ofport->cfm && cfm_should_process_flow(ofport->cfm, flow)) {
2091         if (packet) {
2092             cfm_process_heartbeat(ofport->cfm, packet);
2093         }
2094         return true;
2095     } else if (ofport->bundle && ofport->bundle->lacp
2096                && flow->dl_type == htons(ETH_TYPE_LACP)) {
2097         if (packet) {
2098             lacp_process_packet(ofport->bundle->lacp, ofport, packet);
2099         }
2100         return true;
2101     } else if (ofproto->stp && stp_should_process_flow(flow)) {
2102         if (packet) {
2103             stp_process_packet(ofport, packet);
2104         }
2105         return true;
2106     }
2107     return false;
2108 }
2109
2110 static struct flow_miss *
2111 flow_miss_create(struct hmap *todo, const struct flow *flow,
2112                  const struct nlattr *key, size_t key_len)
2113 {
2114     uint32_t hash = flow_hash(flow, 0);
2115     struct flow_miss *miss;
2116
2117     HMAP_FOR_EACH_WITH_HASH (miss, hmap_node, hash, todo) {
2118         if (flow_equal(&miss->flow, flow)) {
2119             return miss;
2120         }
2121     }
2122
2123     miss = xmalloc(sizeof *miss);
2124     hmap_insert(todo, &miss->hmap_node, hash);
2125     miss->flow = *flow;
2126     miss->key = key;
2127     miss->key_len = key_len;
2128     list_init(&miss->packets);
2129     return miss;
2130 }
2131
2132 static void
2133 handle_flow_miss(struct ofproto_dpif *ofproto, struct flow_miss *miss,
2134                  struct flow_miss_op *ops, size_t *n_ops)
2135 {
2136     const struct flow *flow = &miss->flow;
2137     struct ofpbuf *packet, *next_packet;
2138     struct facet *facet;
2139
2140     facet = facet_lookup_valid(ofproto, flow);
2141     if (!facet) {
2142         struct rule_dpif *rule;
2143
2144         rule = rule_dpif_lookup(ofproto, flow, 0);
2145         if (!rule) {
2146             /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
2147             struct ofport_dpif *port = get_ofp_port(ofproto, flow->in_port);
2148             if (port) {
2149                 if (port->up.opp.config & htonl(OFPPC_NO_PACKET_IN)) {
2150                     COVERAGE_INC(ofproto_dpif_no_packet_in);
2151                     /* XXX install 'drop' flow entry */
2152                     return;
2153                 }
2154             } else {
2155                 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
2156                              flow->in_port);
2157             }
2158
2159             LIST_FOR_EACH_SAFE (packet, next_packet, list_node,
2160                                 &miss->packets) {
2161                 list_remove(&packet->list_node);
2162                 send_packet_in_miss(ofproto, packet, flow, false);
2163             }
2164
2165             return;
2166         }
2167
2168         facet = facet_create(rule, flow);
2169     }
2170
2171     LIST_FOR_EACH_SAFE (packet, next_packet, list_node, &miss->packets) {
2172         list_remove(&packet->list_node);
2173         ofproto->n_matches++;
2174
2175         if (facet->rule->up.cr.priority == FAIL_OPEN_PRIORITY) {
2176             /*
2177              * Extra-special case for fail-open mode.
2178              *
2179              * We are in fail-open mode and the packet matched the fail-open
2180              * rule, but we are connected to a controller too.  We should send
2181              * the packet up to the controller in the hope that it will try to
2182              * set up a flow and thereby allow us to exit fail-open.
2183              *
2184              * See the top-level comment in fail-open.c for more information.
2185              */
2186             send_packet_in_miss(ofproto, packet, flow, true);
2187         }
2188
2189         if (!facet->may_install) {
2190             facet_make_actions(ofproto, facet, packet);
2191         }
2192         if (!execute_controller_action(ofproto, &facet->flow,
2193                                        facet->actions, facet->actions_len,
2194                                        packet)) {
2195             struct flow_miss_op *op = &ops[(*n_ops)++];
2196             struct dpif_execute *execute = &op->dpif_op.execute;
2197
2198             op->facet = facet;
2199             execute->type = DPIF_OP_EXECUTE;
2200             execute->key = miss->key;
2201             execute->key_len = miss->key_len;
2202             execute->actions
2203                 = (facet->may_install
2204                    ? facet->actions
2205                    : xmemdup(facet->actions, facet->actions_len));
2206             execute->actions_len = facet->actions_len;
2207             execute->packet = packet;
2208         }
2209     }
2210
2211     if (facet->may_install) {
2212         struct flow_miss_op *op = &ops[(*n_ops)++];
2213         struct dpif_flow_put *put = &op->dpif_op.flow_put;
2214
2215         op->facet = facet;
2216         put->type = DPIF_OP_FLOW_PUT;
2217         put->flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
2218         put->key = miss->key;
2219         put->key_len = miss->key_len;
2220         put->actions = facet->actions;
2221         put->actions_len = facet->actions_len;
2222         put->stats = NULL;
2223     }
2224 }
2225
2226 static void
2227 handle_miss_upcalls(struct ofproto_dpif *ofproto, struct dpif_upcall *upcalls,
2228                     size_t n_upcalls)
2229 {
2230     struct dpif_upcall *upcall;
2231     struct flow_miss *miss, *next_miss;
2232     struct flow_miss_op flow_miss_ops[FLOW_MISS_MAX_BATCH * 2];
2233     union dpif_op *dpif_ops[FLOW_MISS_MAX_BATCH * 2];
2234     struct hmap todo;
2235     size_t n_ops;
2236     size_t i;
2237
2238     if (!n_upcalls) {
2239         return;
2240     }
2241
2242     /* Construct the to-do list.
2243      *
2244      * This just amounts to extracting the flow from each packet and sticking
2245      * the packets that have the same flow in the same "flow_miss" structure so
2246      * that we can process them together. */
2247     hmap_init(&todo);
2248     for (upcall = upcalls; upcall < &upcalls[n_upcalls]; upcall++) {
2249         struct flow_miss *miss;
2250         struct flow flow;
2251
2252         /* Obtain in_port and tun_id, at least, then set 'flow''s header
2253          * pointers. */
2254         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
2255         flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
2256
2257         /* Handle 802.1ag, LACP, and STP specially. */
2258         if (process_special(ofproto, &flow, upcall->packet)) {
2259             ofpbuf_delete(upcall->packet);
2260             ofproto->n_matches++;
2261             continue;
2262         }
2263
2264         /* Add other packets to a to-do list. */
2265         miss = flow_miss_create(&todo, &flow, upcall->key, upcall->key_len);
2266         list_push_back(&miss->packets, &upcall->packet->list_node);
2267     }
2268
2269     /* Process each element in the to-do list, constructing the set of
2270      * operations to batch. */
2271     n_ops = 0;
2272     HMAP_FOR_EACH_SAFE (miss, next_miss, hmap_node, &todo) {
2273         handle_flow_miss(ofproto, miss, flow_miss_ops, &n_ops);
2274         ofpbuf_list_delete(&miss->packets);
2275         hmap_remove(&todo, &miss->hmap_node);
2276         free(miss);
2277     }
2278     assert(n_ops <= ARRAY_SIZE(flow_miss_ops));
2279     hmap_destroy(&todo);
2280
2281     /* Execute batch. */
2282     for (i = 0; i < n_ops; i++) {
2283         dpif_ops[i] = &flow_miss_ops[i].dpif_op;
2284     }
2285     dpif_operate(ofproto->dpif, dpif_ops, n_ops);
2286
2287     /* Free memory and update facets. */
2288     for (i = 0; i < n_ops; i++) {
2289         struct flow_miss_op *op = &flow_miss_ops[i];
2290         struct dpif_execute *execute;
2291         struct dpif_flow_put *put;
2292
2293         switch (op->dpif_op.type) {
2294         case DPIF_OP_EXECUTE:
2295             execute = &op->dpif_op.execute;
2296             if (op->facet->actions != execute->actions) {
2297                 free((struct nlattr *) execute->actions);
2298             }
2299             ofpbuf_delete((struct ofpbuf *) execute->packet);
2300             break;
2301
2302         case DPIF_OP_FLOW_PUT:
2303             put = &op->dpif_op.flow_put;
2304             if (!put->error) {
2305                 op->facet->installed = true;
2306             }
2307             break;
2308         }
2309     }
2310 }
2311
2312 static void
2313 handle_userspace_upcall(struct ofproto_dpif *ofproto,
2314                         struct dpif_upcall *upcall)
2315 {
2316     struct flow flow;
2317     struct user_action_cookie cookie;
2318
2319     memcpy(&cookie, &upcall->userdata, sizeof(cookie));
2320
2321     if (cookie.type == USER_ACTION_COOKIE_SFLOW) {
2322         if (ofproto->sflow) {
2323             odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
2324             dpif_sflow_received(ofproto->sflow, upcall->packet, &flow, &cookie);
2325         }
2326         ofpbuf_delete(upcall->packet);
2327
2328     } else if (cookie.type == USER_ACTION_COOKIE_CONTROLLER) {
2329         COVERAGE_INC(ofproto_dpif_ctlr_action);
2330         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
2331         send_packet_in_action(ofproto, upcall->packet, upcall->userdata,
2332                               &flow, false);
2333     } else {
2334         VLOG_WARN_RL(&rl, "invalid user cookie : 0x%"PRIx64, upcall->userdata);
2335     }
2336 }
2337
2338 static int
2339 handle_upcalls(struct ofproto_dpif *ofproto, unsigned int max_batch)
2340 {
2341     struct dpif_upcall misses[FLOW_MISS_MAX_BATCH];
2342     int n_misses;
2343     int i;
2344
2345     assert (max_batch <= FLOW_MISS_MAX_BATCH);
2346
2347     n_misses = 0;
2348     for (i = 0; i < max_batch; i++) {
2349         struct dpif_upcall *upcall = &misses[n_misses];
2350         int error;
2351
2352         error = dpif_recv(ofproto->dpif, upcall);
2353         if (error) {
2354             if (error == ENODEV && n_misses == 0) {
2355                 return -ENODEV;
2356             }
2357             break;
2358         }
2359
2360         switch (upcall->type) {
2361         case DPIF_UC_ACTION:
2362             handle_userspace_upcall(ofproto, upcall);
2363             break;
2364
2365         case DPIF_UC_MISS:
2366             /* Handle it later. */
2367             n_misses++;
2368             break;
2369
2370         case DPIF_N_UC_TYPES:
2371         default:
2372             VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32,
2373                          upcall->type);
2374             break;
2375         }
2376     }
2377
2378     handle_miss_upcalls(ofproto, misses, n_misses);
2379
2380     return i;
2381 }
2382 \f
2383 /* Flow expiration. */
2384
2385 static int facet_max_idle(const struct ofproto_dpif *);
2386 static void update_stats(struct ofproto_dpif *);
2387 static void rule_expire(struct rule_dpif *);
2388 static void expire_facets(struct ofproto_dpif *, int dp_max_idle);
2389
2390 /* This function is called periodically by run().  Its job is to collect
2391  * updates for the flows that have been installed into the datapath, most
2392  * importantly when they last were used, and then use that information to
2393  * expire flows that have not been used recently.
2394  *
2395  * Returns the number of milliseconds after which it should be called again. */
2396 static int
2397 expire(struct ofproto_dpif *ofproto)
2398 {
2399     struct rule_dpif *rule, *next_rule;
2400     struct classifier *table;
2401     int dp_max_idle;
2402
2403     /* Update stats for each flow in the datapath. */
2404     update_stats(ofproto);
2405
2406     /* Expire facets that have been idle too long. */
2407     dp_max_idle = facet_max_idle(ofproto);
2408     expire_facets(ofproto, dp_max_idle);
2409
2410     /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
2411     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
2412         struct cls_cursor cursor;
2413
2414         cls_cursor_init(&cursor, table, NULL);
2415         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
2416             rule_expire(rule);
2417         }
2418     }
2419
2420     /* All outstanding data in existing flows has been accounted, so it's a
2421      * good time to do bond rebalancing. */
2422     if (ofproto->has_bonded_bundles) {
2423         struct ofbundle *bundle;
2424
2425         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
2426             if (bundle->bond) {
2427                 bond_rebalance(bundle->bond, &ofproto->revalidate_set);
2428             }
2429         }
2430     }
2431
2432     return MIN(dp_max_idle, 1000);
2433 }
2434
2435 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
2436  *
2437  * This function also pushes statistics updates to rules which each facet
2438  * resubmits into.  Generally these statistics will be accurate.  However, if a
2439  * facet changes the rule it resubmits into at some time in between
2440  * update_stats() runs, it is possible that statistics accrued to the
2441  * old rule will be incorrectly attributed to the new rule.  This could be
2442  * avoided by calling update_stats() whenever rules are created or
2443  * deleted.  However, the performance impact of making so many calls to the
2444  * datapath do not justify the benefit of having perfectly accurate statistics.
2445  */
2446 static void
2447 update_stats(struct ofproto_dpif *p)
2448 {
2449     const struct dpif_flow_stats *stats;
2450     struct dpif_flow_dump dump;
2451     const struct nlattr *key;
2452     size_t key_len;
2453
2454     dpif_flow_dump_start(&dump, p->dpif);
2455     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
2456         struct facet *facet;
2457         struct flow flow;
2458
2459         if (odp_flow_key_to_flow(key, key_len, &flow)) {
2460             struct ds s;
2461
2462             ds_init(&s);
2463             odp_flow_key_format(key, key_len, &s);
2464             VLOG_WARN_RL(&rl, "failed to convert datapath flow key to flow: %s",
2465                          ds_cstr(&s));
2466             ds_destroy(&s);
2467
2468             continue;
2469         }
2470         facet = facet_find(p, &flow);
2471
2472         if (facet && facet->installed) {
2473
2474             if (stats->n_packets >= facet->dp_packet_count) {
2475                 uint64_t extra = stats->n_packets - facet->dp_packet_count;
2476                 facet->packet_count += extra;
2477             } else {
2478                 VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
2479             }
2480
2481             if (stats->n_bytes >= facet->dp_byte_count) {
2482                 facet->byte_count += stats->n_bytes - facet->dp_byte_count;
2483             } else {
2484                 VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
2485             }
2486
2487             facet->dp_packet_count = stats->n_packets;
2488             facet->dp_byte_count = stats->n_bytes;
2489
2490             facet_update_time(p, facet, stats->used);
2491             facet_account(p, facet);
2492             facet_push_stats(facet);
2493         } else {
2494             /* There's a flow in the datapath that we know nothing about.
2495              * Delete it. */
2496             COVERAGE_INC(facet_unexpected);
2497             dpif_flow_del(p->dpif, key, key_len, NULL);
2498         }
2499     }
2500     dpif_flow_dump_done(&dump);
2501 }
2502
2503 /* Calculates and returns the number of milliseconds of idle time after which
2504  * facets should expire from the datapath and we should fold their statistics
2505  * into their parent rules in userspace. */
2506 static int
2507 facet_max_idle(const struct ofproto_dpif *ofproto)
2508 {
2509     /*
2510      * Idle time histogram.
2511      *
2512      * Most of the time a switch has a relatively small number of facets.  When
2513      * this is the case we might as well keep statistics for all of them in
2514      * userspace and to cache them in the kernel datapath for performance as
2515      * well.
2516      *
2517      * As the number of facets increases, the memory required to maintain
2518      * statistics about them in userspace and in the kernel becomes
2519      * significant.  However, with a large number of facets it is likely that
2520      * only a few of them are "heavy hitters" that consume a large amount of
2521      * bandwidth.  At this point, only heavy hitters are worth caching in the
2522      * kernel and maintaining in userspaces; other facets we can discard.
2523      *
2524      * The technique used to compute the idle time is to build a histogram with
2525      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each facet
2526      * that is installed in the kernel gets dropped in the appropriate bucket.
2527      * After the histogram has been built, we compute the cutoff so that only
2528      * the most-recently-used 1% of facets (but at least
2529      * ofproto->up.flow_eviction_threshold flows) are kept cached.  At least
2530      * the most-recently-used bucket of facets is kept, so actually an
2531      * arbitrary number of facets can be kept in any given expiration run
2532      * (though the next run will delete most of those unless they receive
2533      * additional data).
2534      *
2535      * This requires a second pass through the facets, in addition to the pass
2536      * made by update_stats(), because the former function never looks
2537      * at uninstallable facets.
2538      */
2539     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
2540     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
2541     int buckets[N_BUCKETS] = { 0 };
2542     int total, subtotal, bucket;
2543     struct facet *facet;
2544     long long int now;
2545     int i;
2546
2547     total = hmap_count(&ofproto->facets);
2548     if (total <= ofproto->up.flow_eviction_threshold) {
2549         return N_BUCKETS * BUCKET_WIDTH;
2550     }
2551
2552     /* Build histogram. */
2553     now = time_msec();
2554     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
2555         long long int idle = now - facet->used;
2556         int bucket = (idle <= 0 ? 0
2557                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
2558                       : (unsigned int) idle / BUCKET_WIDTH);
2559         buckets[bucket]++;
2560     }
2561
2562     /* Find the first bucket whose flows should be expired. */
2563     subtotal = bucket = 0;
2564     do {
2565         subtotal += buckets[bucket++];
2566     } while (bucket < N_BUCKETS &&
2567              subtotal < MAX(ofproto->up.flow_eviction_threshold, total / 100));
2568
2569     if (VLOG_IS_DBG_ENABLED()) {
2570         struct ds s;
2571
2572         ds_init(&s);
2573         ds_put_cstr(&s, "keep");
2574         for (i = 0; i < N_BUCKETS; i++) {
2575             if (i == bucket) {
2576                 ds_put_cstr(&s, ", drop");
2577             }
2578             if (buckets[i]) {
2579                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
2580             }
2581         }
2582         VLOG_INFO("%s: %s (msec:count)", ofproto->up.name, ds_cstr(&s));
2583         ds_destroy(&s);
2584     }
2585
2586     return bucket * BUCKET_WIDTH;
2587 }
2588
2589 static void
2590 facet_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
2591 {
2592     if (ofproto->netflow && !facet_is_controller_flow(facet) &&
2593         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
2594         struct ofexpired expired;
2595
2596         if (facet->installed) {
2597             struct dpif_flow_stats stats;
2598
2599             facet_put__(ofproto, facet, facet->actions, facet->actions_len,
2600                         &stats);
2601             facet_update_stats(ofproto, facet, &stats);
2602         }
2603
2604         expired.flow = facet->flow;
2605         expired.packet_count = facet->packet_count;
2606         expired.byte_count = facet->byte_count;
2607         expired.used = facet->used;
2608         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2609     }
2610 }
2611
2612 static void
2613 expire_facets(struct ofproto_dpif *ofproto, int dp_max_idle)
2614 {
2615     long long int cutoff = time_msec() - dp_max_idle;
2616     struct facet *facet, *next_facet;
2617
2618     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
2619         facet_active_timeout(ofproto, facet);
2620         if (facet->used < cutoff) {
2621             facet_remove(ofproto, facet);
2622         }
2623     }
2624 }
2625
2626 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
2627  * then delete it entirely. */
2628 static void
2629 rule_expire(struct rule_dpif *rule)
2630 {
2631     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2632     struct facet *facet, *next_facet;
2633     long long int now;
2634     uint8_t reason;
2635
2636     /* Has 'rule' expired? */
2637     now = time_msec();
2638     if (rule->up.hard_timeout
2639         && now > rule->up.modified + rule->up.hard_timeout * 1000) {
2640         reason = OFPRR_HARD_TIMEOUT;
2641     } else if (rule->up.idle_timeout && list_is_empty(&rule->facets)
2642                && now > rule->used + rule->up.idle_timeout * 1000) {
2643         reason = OFPRR_IDLE_TIMEOUT;
2644     } else {
2645         return;
2646     }
2647
2648     COVERAGE_INC(ofproto_dpif_expired);
2649
2650     /* Update stats.  (This is a no-op if the rule expired due to an idle
2651      * timeout, because that only happens when the rule has no facets left.) */
2652     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
2653         facet_remove(ofproto, facet);
2654     }
2655
2656     /* Get rid of the rule. */
2657     ofproto_rule_expire(&rule->up, reason);
2658 }
2659 \f
2660 /* Facets. */
2661
2662 /* Creates and returns a new facet owned by 'rule', given a 'flow'.
2663  *
2664  * The caller must already have determined that no facet with an identical
2665  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
2666  * the ofproto's classifier table.
2667  *
2668  * The facet will initially have no ODP actions.  The caller should fix that
2669  * by calling facet_make_actions(). */
2670 static struct facet *
2671 facet_create(struct rule_dpif *rule, const struct flow *flow)
2672 {
2673     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2674     struct facet *facet;
2675
2676     facet = xzalloc(sizeof *facet);
2677     facet->used = time_msec();
2678     hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
2679     list_push_back(&rule->facets, &facet->list_node);
2680     facet->rule = rule;
2681     facet->flow = *flow;
2682     netflow_flow_init(&facet->nf_flow);
2683     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
2684
2685     return facet;
2686 }
2687
2688 static void
2689 facet_free(struct facet *facet)
2690 {
2691     free(facet->actions);
2692     free(facet);
2693 }
2694
2695 static bool
2696 execute_controller_action(struct ofproto_dpif *ofproto,
2697                           const struct flow *flow,
2698                           const struct nlattr *odp_actions, size_t actions_len,
2699                           struct ofpbuf *packet)
2700 {
2701     if (actions_len
2702         && odp_actions->nla_type == OVS_ACTION_ATTR_USERSPACE
2703         && NLA_ALIGN(odp_actions->nla_len) == actions_len) {
2704         /* As an optimization, avoid a round-trip from userspace to kernel to
2705          * userspace.  This also avoids possibly filling up kernel packet
2706          * buffers along the way.
2707          *
2708          * This optimization will not accidentally catch sFlow
2709          * OVS_ACTION_ATTR_USERSPACE actions, since those are encapsulated
2710          * inside OVS_ACTION_ATTR_SAMPLE. */
2711         const struct nlattr *nla;
2712
2713         nla = nl_attr_find_nested(odp_actions, OVS_USERSPACE_ATTR_USERDATA);
2714         send_packet_in_action(ofproto, packet, nl_attr_get_u64(nla), flow,
2715                               false);
2716         return true;
2717     } else {
2718         return false;
2719     }
2720 }
2721
2722 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
2723  * 'packet', which arrived on 'in_port'.
2724  *
2725  * Takes ownership of 'packet'. */
2726 static bool
2727 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
2728                     const struct nlattr *odp_actions, size_t actions_len,
2729                     struct ofpbuf *packet)
2730 {
2731     struct odputil_keybuf keybuf;
2732     struct ofpbuf key;
2733     int error;
2734
2735     if (execute_controller_action(ofproto, flow, odp_actions, actions_len,
2736                                   packet)) {
2737         return true;
2738     }
2739
2740     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2741     odp_flow_key_from_flow(&key, flow);
2742
2743     error = dpif_execute(ofproto->dpif, key.data, key.size,
2744                          odp_actions, actions_len, packet);
2745
2746     ofpbuf_delete(packet);
2747     return !error;
2748 }
2749
2750 /* Executes the actions indicated by 'facet' on 'packet' and credits 'facet''s
2751  * statistics appropriately.  'packet' must have at least sizeof(struct
2752  * ofp_packet_in) bytes of headroom.
2753  *
2754  * For correct results, 'packet' must actually be in 'facet''s flow; that is,
2755  * applying flow_extract() to 'packet' would yield the same flow as
2756  * 'facet->flow'.
2757  *
2758  * 'facet' must have accurately composed datapath actions; that is, it must
2759  * not be in need of revalidation.
2760  *
2761  * Takes ownership of 'packet'. */
2762 static void
2763 facet_execute(struct ofproto_dpif *ofproto, struct facet *facet,
2764               struct ofpbuf *packet)
2765 {
2766     struct dpif_flow_stats stats;
2767
2768     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2769
2770     dpif_flow_stats_extract(&facet->flow, packet, &stats);
2771     stats.used = time_msec();
2772     if (execute_odp_actions(ofproto, &facet->flow,
2773                             facet->actions, facet->actions_len, packet)) {
2774         facet_update_stats(ofproto, facet, &stats);
2775     }
2776 }
2777
2778 /* Remove 'facet' from 'ofproto' and free up the associated memory:
2779  *
2780  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
2781  *     rule's statistics, via facet_uninstall().
2782  *
2783  *   - Removes 'facet' from its rule and from ofproto->facets.
2784  */
2785 static void
2786 facet_remove(struct ofproto_dpif *ofproto, struct facet *facet)
2787 {
2788     facet_uninstall(ofproto, facet);
2789     facet_flush_stats(ofproto, facet);
2790     hmap_remove(&ofproto->facets, &facet->hmap_node);
2791     list_remove(&facet->list_node);
2792     facet_free(facet);
2793 }
2794
2795 /* Composes the datapath actions for 'facet' based on its rule's actions. */
2796 static void
2797 facet_make_actions(struct ofproto_dpif *p, struct facet *facet,
2798                    const struct ofpbuf *packet)
2799 {
2800     const struct rule_dpif *rule = facet->rule;
2801     struct ofpbuf *odp_actions;
2802     struct action_xlate_ctx ctx;
2803
2804     action_xlate_ctx_init(&ctx, p, &facet->flow, packet);
2805     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
2806     facet->tags = ctx.tags;
2807     facet->may_install = ctx.may_set_up_flow;
2808     facet->has_learn = ctx.has_learn;
2809     facet->has_normal = ctx.has_normal;
2810     facet->nf_flow.output_iface = ctx.nf_output_iface;
2811
2812     if (facet->actions_len != odp_actions->size
2813         || memcmp(facet->actions, odp_actions->data, odp_actions->size)) {
2814         free(facet->actions);
2815         facet->actions_len = odp_actions->size;
2816         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2817     }
2818
2819     ofpbuf_delete(odp_actions);
2820 }
2821
2822 /* Updates 'facet''s flow in the datapath setting its actions to 'actions_len'
2823  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
2824  * in the datapath will be zeroed and 'stats' will be updated with traffic new
2825  * since 'facet' was last updated.
2826  *
2827  * Returns 0 if successful, otherwise a positive errno value.*/
2828 static int
2829 facet_put__(struct ofproto_dpif *ofproto, struct facet *facet,
2830             const struct nlattr *actions, size_t actions_len,
2831             struct dpif_flow_stats *stats)
2832 {
2833     struct odputil_keybuf keybuf;
2834     enum dpif_flow_put_flags flags;
2835     struct ofpbuf key;
2836     int ret;
2837
2838     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
2839     if (stats) {
2840         flags |= DPIF_FP_ZERO_STATS;
2841     }
2842
2843     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2844     odp_flow_key_from_flow(&key, &facet->flow);
2845
2846     ret = dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
2847                         actions, actions_len, stats);
2848
2849     if (stats) {
2850         facet_reset_dp_stats(facet, stats);
2851     }
2852
2853     return ret;
2854 }
2855
2856 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath.  If
2857  * 'zero_stats' is true, clears any existing statistics from the datapath for
2858  * 'facet'. */
2859 static void
2860 facet_install(struct ofproto_dpif *p, struct facet *facet, bool zero_stats)
2861 {
2862     struct dpif_flow_stats stats;
2863
2864     if (facet->may_install
2865         && !facet_put__(p, facet, facet->actions, facet->actions_len,
2866                         zero_stats ? &stats : NULL)) {
2867         facet->installed = true;
2868     }
2869 }
2870
2871 static void
2872 facet_account(struct ofproto_dpif *ofproto, struct facet *facet)
2873 {
2874     uint64_t n_bytes;
2875     const struct nlattr *a;
2876     unsigned int left;
2877     ovs_be16 vlan_tci;
2878
2879     if (facet->byte_count <= facet->accounted_bytes) {
2880         return;
2881     }
2882     n_bytes = facet->byte_count - facet->accounted_bytes;
2883     facet->accounted_bytes = facet->byte_count;
2884
2885     /* Feed information from the active flows back into the learning table to
2886      * ensure that table is always in sync with what is actually flowing
2887      * through the datapath. */
2888     if (facet->has_learn || facet->has_normal) {
2889         struct action_xlate_ctx ctx;
2890
2891         action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2892         ctx.may_learn = true;
2893         ofpbuf_delete(xlate_actions(&ctx, facet->rule->up.actions,
2894                                     facet->rule->up.n_actions));
2895     }
2896
2897     if (!facet->has_normal || !ofproto->has_bonded_bundles) {
2898         return;
2899     }
2900
2901     /* This loop feeds byte counters to bond_account() for rebalancing to use
2902      * as a basis.  We also need to track the actual VLAN on which the packet
2903      * is going to be sent to ensure that it matches the one passed to
2904      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
2905      * hash bucket.) */
2906     vlan_tci = facet->flow.vlan_tci;
2907     NL_ATTR_FOR_EACH_UNSAFE (a, left, facet->actions, facet->actions_len) {
2908         struct ofport_dpif *port;
2909
2910         switch (nl_attr_type(a)) {
2911         const struct nlattr *nested;
2912         case OVS_ACTION_ATTR_OUTPUT:
2913             port = get_odp_port(ofproto, nl_attr_get_u32(a));
2914             if (port && port->bundle && port->bundle->bond) {
2915                 bond_account(port->bundle->bond, &facet->flow,
2916                              vlan_tci_to_vid(vlan_tci), n_bytes);
2917             }
2918             break;
2919
2920         case OVS_ACTION_ATTR_POP:
2921             if (nl_attr_get_u16(a) == OVS_KEY_ATTR_8021Q) {
2922                 vlan_tci = htons(0);
2923             }
2924             break;
2925
2926         case OVS_ACTION_ATTR_PUSH:
2927             nested = nl_attr_get(a);
2928             if (nl_attr_type(nested) == OVS_KEY_ATTR_8021Q) {
2929                 const struct ovs_key_8021q *q_key;
2930
2931                 q_key = nl_attr_get_unspec(nested, sizeof(*q_key));
2932                 vlan_tci = q_key->q_tci;
2933             }
2934             break;
2935         }
2936     }
2937 }
2938
2939 /* If 'rule' is installed in the datapath, uninstalls it. */
2940 static void
2941 facet_uninstall(struct ofproto_dpif *p, struct facet *facet)
2942 {
2943     if (facet->installed) {
2944         struct odputil_keybuf keybuf;
2945         struct dpif_flow_stats stats;
2946         struct ofpbuf key;
2947         int error;
2948
2949         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2950         odp_flow_key_from_flow(&key, &facet->flow);
2951
2952         error = dpif_flow_del(p->dpif, key.data, key.size, &stats);
2953         facet_reset_dp_stats(facet, &stats);
2954         if (!error) {
2955             facet_update_stats(p, facet, &stats);
2956         }
2957         facet->installed = false;
2958     } else {
2959         assert(facet->dp_packet_count == 0);
2960         assert(facet->dp_byte_count == 0);
2961     }
2962 }
2963
2964 /* Returns true if the only action for 'facet' is to send to the controller.
2965  * (We don't report NetFlow expiration messages for such facets because they
2966  * are just part of the control logic for the network, not real traffic). */
2967 static bool
2968 facet_is_controller_flow(struct facet *facet)
2969 {
2970     return (facet
2971             && facet->rule->up.n_actions == 1
2972             && action_outputs_to_port(&facet->rule->up.actions[0],
2973                                       htons(OFPP_CONTROLLER)));
2974 }
2975
2976 /* Resets 'facet''s datapath statistics counters.  This should be called when
2977  * 'facet''s statistics are cleared in the datapath.  If 'stats' is non-null,
2978  * it should contain the statistics returned by dpif when 'facet' was reset in
2979  * the datapath.  'stats' will be modified to only included statistics new
2980  * since 'facet' was last updated. */
2981 static void
2982 facet_reset_dp_stats(struct facet *facet, struct dpif_flow_stats *stats)
2983 {
2984     if (stats && facet->dp_packet_count <= stats->n_packets
2985         && facet->dp_byte_count <= stats->n_bytes) {
2986         stats->n_packets -= facet->dp_packet_count;
2987         stats->n_bytes -= facet->dp_byte_count;
2988     }
2989
2990     facet->dp_packet_count = 0;
2991     facet->dp_byte_count = 0;
2992 }
2993
2994 /* Folds all of 'facet''s statistics into its rule.  Also updates the
2995  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
2996  * 'facet''s statistics in the datapath should have been zeroed and folded into
2997  * its packet and byte counts before this function is called. */
2998 static void
2999 facet_flush_stats(struct ofproto_dpif *ofproto, struct facet *facet)
3000 {
3001     assert(!facet->dp_byte_count);
3002     assert(!facet->dp_packet_count);
3003
3004     facet_push_stats(facet);
3005     facet_account(ofproto, facet);
3006
3007     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
3008         struct ofexpired expired;
3009         expired.flow = facet->flow;
3010         expired.packet_count = facet->packet_count;
3011         expired.byte_count = facet->byte_count;
3012         expired.used = facet->used;
3013         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
3014     }
3015
3016     facet->rule->packet_count += facet->packet_count;
3017     facet->rule->byte_count += facet->byte_count;
3018
3019     /* Reset counters to prevent double counting if 'facet' ever gets
3020      * reinstalled. */
3021     facet_reset_counters(facet);
3022
3023     netflow_flow_clear(&facet->nf_flow);
3024 }
3025
3026 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3027  * Returns it if found, otherwise a null pointer.
3028  *
3029  * The returned facet might need revalidation; use facet_lookup_valid()
3030  * instead if that is important. */
3031 static struct facet *
3032 facet_find(struct ofproto_dpif *ofproto, const struct flow *flow)
3033 {
3034     struct facet *facet;
3035
3036     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
3037                              &ofproto->facets) {
3038         if (flow_equal(flow, &facet->flow)) {
3039             return facet;
3040         }
3041     }
3042
3043     return NULL;
3044 }
3045
3046 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3047  * Returns it if found, otherwise a null pointer.
3048  *
3049  * The returned facet is guaranteed to be valid. */
3050 static struct facet *
3051 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow)
3052 {
3053     struct facet *facet = facet_find(ofproto, flow);
3054
3055     /* The facet we found might not be valid, since we could be in need of
3056      * revalidation.  If it is not valid, don't return it. */
3057     if (facet
3058         && (ofproto->need_revalidate
3059             || tag_set_intersects(&ofproto->revalidate_set, facet->tags))
3060         && !facet_revalidate(ofproto, facet)) {
3061         COVERAGE_INC(facet_invalidated);
3062         return NULL;
3063     }
3064
3065     return facet;
3066 }
3067
3068 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
3069  *
3070  *   - If the rule found is different from 'facet''s current rule, moves
3071  *     'facet' to the new rule and recompiles its actions.
3072  *
3073  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
3074  *     where it is and recompiles its actions anyway.
3075  *
3076  *   - If there is none, destroys 'facet'.
3077  *
3078  * Returns true if 'facet' still exists, false if it has been destroyed. */
3079 static bool
3080 facet_revalidate(struct ofproto_dpif *ofproto, struct facet *facet)
3081 {
3082     struct action_xlate_ctx ctx;
3083     struct ofpbuf *odp_actions;
3084     struct rule_dpif *new_rule;
3085     bool actions_changed;
3086
3087     COVERAGE_INC(facet_revalidate);
3088
3089     /* Determine the new rule. */
3090     new_rule = rule_dpif_lookup(ofproto, &facet->flow, 0);
3091     if (!new_rule) {
3092         /* No new rule, so delete the facet. */
3093         facet_remove(ofproto, facet);
3094         return false;
3095     }
3096
3097     /* Calculate new datapath actions.
3098      *
3099      * We do not modify any 'facet' state yet, because we might need to, e.g.,
3100      * emit a NetFlow expiration and, if so, we need to have the old state
3101      * around to properly compose it. */
3102     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
3103     odp_actions = xlate_actions(&ctx,
3104                                 new_rule->up.actions, new_rule->up.n_actions);
3105     actions_changed = (facet->actions_len != odp_actions->size
3106                        || memcmp(facet->actions, odp_actions->data,
3107                                  facet->actions_len));
3108
3109     /* If the datapath actions changed or the installability changed,
3110      * then we need to talk to the datapath. */
3111     if (actions_changed || ctx.may_set_up_flow != facet->installed) {
3112         if (ctx.may_set_up_flow) {
3113             struct dpif_flow_stats stats;
3114
3115             facet_put__(ofproto, facet,
3116                         odp_actions->data, odp_actions->size, &stats);
3117             facet_update_stats(ofproto, facet, &stats);
3118         } else {
3119             facet_uninstall(ofproto, facet);
3120         }
3121
3122         /* The datapath flow is gone or has zeroed stats, so push stats out of
3123          * 'facet' into 'rule'. */
3124         facet_flush_stats(ofproto, facet);
3125     }
3126
3127     /* Update 'facet' now that we've taken care of all the old state. */
3128     facet->tags = ctx.tags;
3129     facet->nf_flow.output_iface = ctx.nf_output_iface;
3130     facet->may_install = ctx.may_set_up_flow;
3131     facet->has_learn = ctx.has_learn;
3132     facet->has_normal = ctx.has_normal;
3133     if (actions_changed) {
3134         free(facet->actions);
3135         facet->actions_len = odp_actions->size;
3136         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
3137     }
3138     if (facet->rule != new_rule) {
3139         COVERAGE_INC(facet_changed_rule);
3140         list_remove(&facet->list_node);
3141         list_push_back(&new_rule->facets, &facet->list_node);
3142         facet->rule = new_rule;
3143         facet->used = new_rule->up.created;
3144         facet->rs_used = facet->used;
3145     }
3146
3147     ofpbuf_delete(odp_actions);
3148
3149     return true;
3150 }
3151
3152 /* Updates 'facet''s used time.  Caller is responsible for calling
3153  * facet_push_stats() to update the flows which 'facet' resubmits into. */
3154 static void
3155 facet_update_time(struct ofproto_dpif *ofproto, struct facet *facet,
3156                   long long int used)
3157 {
3158     if (used > facet->used) {
3159         facet->used = used;
3160         if (used > facet->rule->used) {
3161             facet->rule->used = used;
3162         }
3163         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3164     }
3165 }
3166
3167 /* Folds the statistics from 'stats' into the counters in 'facet'.
3168  *
3169  * Because of the meaning of a facet's counters, it only makes sense to do this
3170  * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
3171  * packet that was sent by hand or if it represents statistics that have been
3172  * cleared out of the datapath. */
3173 static void
3174 facet_update_stats(struct ofproto_dpif *ofproto, struct facet *facet,
3175                    const struct dpif_flow_stats *stats)
3176 {
3177     if (stats->n_packets || stats->used > facet->used) {
3178         facet_update_time(ofproto, facet, stats->used);
3179         facet->packet_count += stats->n_packets;
3180         facet->byte_count += stats->n_bytes;
3181         facet_push_stats(facet);
3182         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3183     }
3184 }
3185
3186 static void
3187 facet_reset_counters(struct facet *facet)
3188 {
3189     facet->packet_count = 0;
3190     facet->byte_count = 0;
3191     facet->rs_packet_count = 0;
3192     facet->rs_byte_count = 0;
3193     facet->accounted_bytes = 0;
3194 }
3195
3196 static void
3197 facet_push_stats(struct facet *facet)
3198 {
3199     uint64_t rs_packets, rs_bytes;
3200
3201     assert(facet->packet_count >= facet->rs_packet_count);
3202     assert(facet->byte_count >= facet->rs_byte_count);
3203     assert(facet->used >= facet->rs_used);
3204
3205     rs_packets = facet->packet_count - facet->rs_packet_count;
3206     rs_bytes = facet->byte_count - facet->rs_byte_count;
3207
3208     if (rs_packets || rs_bytes || facet->used > facet->rs_used) {
3209         facet->rs_packet_count = facet->packet_count;
3210         facet->rs_byte_count = facet->byte_count;
3211         facet->rs_used = facet->used;
3212
3213         flow_push_stats(facet->rule, &facet->flow,
3214                         rs_packets, rs_bytes, facet->used);
3215     }
3216 }
3217
3218 struct ofproto_push {
3219     struct action_xlate_ctx ctx;
3220     uint64_t packets;
3221     uint64_t bytes;
3222     long long int used;
3223 };
3224
3225 static void
3226 push_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
3227 {
3228     struct ofproto_push *push = CONTAINER_OF(ctx, struct ofproto_push, ctx);
3229
3230     if (rule) {
3231         rule->packet_count += push->packets;
3232         rule->byte_count += push->bytes;
3233         rule->used = MAX(push->used, rule->used);
3234     }
3235 }
3236
3237 /* Pushes flow statistics to the rules which 'flow' resubmits into given
3238  * 'rule''s actions. */
3239 static void
3240 flow_push_stats(const struct rule_dpif *rule,
3241                 struct flow *flow, uint64_t packets, uint64_t bytes,
3242                 long long int used)
3243 {
3244     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3245     struct ofproto_push push;
3246
3247     push.packets = packets;
3248     push.bytes = bytes;
3249     push.used = used;
3250
3251     action_xlate_ctx_init(&push.ctx, ofproto, flow, NULL);
3252     push.ctx.resubmit_hook = push_resubmit;
3253     ofpbuf_delete(xlate_actions(&push.ctx,
3254                                 rule->up.actions, rule->up.n_actions));
3255 }
3256 \f
3257 /* Rules. */
3258
3259 static struct rule_dpif *
3260 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
3261                  uint8_t table_id)
3262 {
3263     struct cls_rule *cls_rule;
3264     struct classifier *cls;
3265
3266     if (table_id >= N_TABLES) {
3267         return NULL;
3268     }
3269
3270     cls = &ofproto->up.tables[table_id];
3271     if (flow->tos_frag & FLOW_FRAG_ANY
3272         && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
3273         /* For OFPC_NORMAL frag_handling, we must pretend that transport ports
3274          * are unavailable. */
3275         struct flow ofpc_normal_flow = *flow;
3276         ofpc_normal_flow.tp_src = htons(0);
3277         ofpc_normal_flow.tp_dst = htons(0);
3278         cls_rule = classifier_lookup(cls, &ofpc_normal_flow);
3279     } else {
3280         cls_rule = classifier_lookup(cls, flow);
3281     }
3282     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
3283 }
3284
3285 static void
3286 complete_operation(struct rule_dpif *rule)
3287 {
3288     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3289
3290     rule_invalidate(rule);
3291     if (clogged) {
3292         struct dpif_completion *c = xmalloc(sizeof *c);
3293         c->op = rule->up.pending;
3294         list_push_back(&ofproto->completions, &c->list_node);
3295     } else {
3296         ofoperation_complete(rule->up.pending, 0);
3297     }
3298 }
3299
3300 static struct rule *
3301 rule_alloc(void)
3302 {
3303     struct rule_dpif *rule = xmalloc(sizeof *rule);
3304     return &rule->up;
3305 }
3306
3307 static void
3308 rule_dealloc(struct rule *rule_)
3309 {
3310     struct rule_dpif *rule = rule_dpif_cast(rule_);
3311     free(rule);
3312 }
3313
3314 static int
3315 rule_construct(struct rule *rule_)
3316 {
3317     struct rule_dpif *rule = rule_dpif_cast(rule_);
3318     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3319     struct rule_dpif *victim;
3320     uint8_t table_id;
3321     int error;
3322
3323     error = validate_actions(rule->up.actions, rule->up.n_actions,
3324                              &rule->up.cr.flow, ofproto->max_ports);
3325     if (error) {
3326         return error;
3327     }
3328
3329     rule->used = rule->up.created;
3330     rule->packet_count = 0;
3331     rule->byte_count = 0;
3332
3333     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
3334     if (victim && !list_is_empty(&victim->facets)) {
3335         struct facet *facet;
3336
3337         rule->facets = victim->facets;
3338         list_moved(&rule->facets);
3339         LIST_FOR_EACH (facet, list_node, &rule->facets) {
3340             /* XXX: We're only clearing our local counters here.  It's possible
3341              * that quite a few packets are unaccounted for in the datapath
3342              * statistics.  These will be accounted to the new rule instead of
3343              * cleared as required.  This could be fixed by clearing out the
3344              * datapath statistics for this facet, but currently it doesn't
3345              * seem worth it. */
3346             facet_reset_counters(facet);
3347             facet->rule = rule;
3348         }
3349     } else {
3350         /* Must avoid list_moved() in this case. */
3351         list_init(&rule->facets);
3352     }
3353
3354     table_id = rule->up.table_id;
3355     rule->tag = (victim ? victim->tag
3356                  : table_id == 0 ? 0
3357                  : rule_calculate_tag(&rule->up.cr.flow, &rule->up.cr.wc,
3358                                       ofproto->tables[table_id].basis));
3359
3360     complete_operation(rule);
3361     return 0;
3362 }
3363
3364 static void
3365 rule_destruct(struct rule *rule_)
3366 {
3367     struct rule_dpif *rule = rule_dpif_cast(rule_);
3368     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3369     struct facet *facet, *next_facet;
3370
3371     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
3372         facet_revalidate(ofproto, facet);
3373     }
3374
3375     complete_operation(rule);
3376 }
3377
3378 static void
3379 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
3380 {
3381     struct rule_dpif *rule = rule_dpif_cast(rule_);
3382     struct facet *facet;
3383
3384     /* Start from historical data for 'rule' itself that are no longer tracked
3385      * in facets.  This counts, for example, facets that have expired. */
3386     *packets = rule->packet_count;
3387     *bytes = rule->byte_count;
3388
3389     /* Add any statistics that are tracked by facets.  This includes
3390      * statistical data recently updated by ofproto_update_stats() as well as
3391      * stats for packets that were executed "by hand" via dpif_execute(). */
3392     LIST_FOR_EACH (facet, list_node, &rule->facets) {
3393         *packets += facet->packet_count;
3394         *bytes += facet->byte_count;
3395     }
3396 }
3397
3398 static int
3399 rule_execute(struct rule *rule_, struct flow *flow, struct ofpbuf *packet)
3400 {
3401     struct rule_dpif *rule = rule_dpif_cast(rule_);
3402     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3403     struct action_xlate_ctx ctx;
3404     struct ofpbuf *odp_actions;
3405     struct facet *facet;
3406     size_t size;
3407
3408     /* First look for a related facet.  If we find one, account it to that. */
3409     facet = facet_lookup_valid(ofproto, flow);
3410     if (facet && facet->rule == rule) {
3411         if (!facet->may_install) {
3412             facet_make_actions(ofproto, facet, packet);
3413         }
3414         facet_execute(ofproto, facet, packet);
3415         return 0;
3416     }
3417
3418     /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
3419      * create a new facet for it and use that. */
3420     if (rule_dpif_lookup(ofproto, flow, 0) == rule) {
3421         facet = facet_create(rule, flow);
3422         facet_make_actions(ofproto, facet, packet);
3423         facet_execute(ofproto, facet, packet);
3424         facet_install(ofproto, facet, true);
3425         return 0;
3426     }
3427
3428     /* We can't account anything to a facet.  If we were to try, then that
3429      * facet would have a non-matching rule, busting our invariants. */
3430     action_xlate_ctx_init(&ctx, ofproto, flow, packet);
3431     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
3432     size = packet->size;
3433     if (execute_odp_actions(ofproto, flow, odp_actions->data,
3434                             odp_actions->size, packet)) {
3435         rule->used = time_msec();
3436         rule->packet_count++;
3437         rule->byte_count += size;
3438         flow_push_stats(rule, flow, 1, size, rule->used);
3439     }
3440     ofpbuf_delete(odp_actions);
3441
3442     return 0;
3443 }
3444
3445 static void
3446 rule_modify_actions(struct rule *rule_)
3447 {
3448     struct rule_dpif *rule = rule_dpif_cast(rule_);
3449     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3450     int error;
3451
3452     error = validate_actions(rule->up.actions, rule->up.n_actions,
3453                              &rule->up.cr.flow, ofproto->max_ports);
3454     if (error) {
3455         ofoperation_complete(rule->up.pending, error);
3456         return;
3457     }
3458
3459     complete_operation(rule);
3460 }
3461 \f
3462 /* Sends 'packet' out of port 'odp_port' within 'ofproto'.
3463  * Returns 0 if successful, otherwise a positive errno value. */
3464 static int
3465 send_packet(struct ofproto_dpif *ofproto, uint32_t odp_port,
3466             const struct ofpbuf *packet)
3467 {
3468     struct ofpbuf key, odp_actions;
3469     struct odputil_keybuf keybuf;
3470     struct flow flow;
3471     int error;
3472
3473     flow_extract((struct ofpbuf *) packet, 0, 0, &flow);
3474     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
3475     odp_flow_key_from_flow(&key, &flow);
3476
3477     ofpbuf_init(&odp_actions, 32);
3478     compose_sflow_action(ofproto, &odp_actions, &flow, odp_port);
3479
3480     nl_msg_put_u32(&odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
3481     error = dpif_execute(ofproto->dpif,
3482                          key.data, key.size,
3483                          odp_actions.data, odp_actions.size,
3484                          packet);
3485     ofpbuf_uninit(&odp_actions);
3486
3487     if (error) {
3488         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
3489                      ofproto->up.name, odp_port, strerror(error));
3490     }
3491     return error;
3492 }
3493 \f
3494 /* OpenFlow to datapath action translation. */
3495
3496 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
3497                              struct action_xlate_ctx *ctx);
3498 static void xlate_normal(struct action_xlate_ctx *);
3499
3500 static size_t
3501 put_userspace_action(const struct ofproto_dpif *ofproto,
3502                      struct ofpbuf *odp_actions,
3503                      const struct flow *flow,
3504                      const struct user_action_cookie *cookie)
3505 {
3506     size_t offset;
3507     uint32_t pid;
3508
3509     pid = dpif_port_get_pid(ofproto->dpif,
3510                             ofp_port_to_odp_port(flow->in_port));
3511
3512     offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_USERSPACE);
3513     nl_msg_put_u32(odp_actions, OVS_USERSPACE_ATTR_PID, pid);
3514     nl_msg_put_unspec(odp_actions, OVS_USERSPACE_ATTR_USERDATA,
3515                       cookie, sizeof *cookie);
3516     nl_msg_end_nested(odp_actions, offset);
3517
3518     return odp_actions->size - NLA_ALIGN(sizeof *cookie);
3519 }
3520
3521 /* Compose SAMPLE action for sFlow. */
3522 static size_t
3523 compose_sflow_action(const struct ofproto_dpif *ofproto,
3524                      struct ofpbuf *odp_actions,
3525                      const struct flow *flow,
3526                      uint32_t odp_port)
3527 {
3528     uint32_t port_ifindex;
3529     uint32_t probability;
3530     struct user_action_cookie cookie;
3531     size_t sample_offset, actions_offset;
3532     int cookie_offset, n_output;
3533
3534     if (!ofproto->sflow || flow->in_port == OFPP_NONE) {
3535         return 0;
3536     }
3537
3538     if (odp_port == OVSP_NONE) {
3539         port_ifindex = 0;
3540         n_output = 0;
3541     } else {
3542         port_ifindex = dpif_sflow_odp_port_to_ifindex(ofproto->sflow, odp_port);
3543         n_output = 1;
3544     }
3545
3546     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
3547
3548     /* Number of packets out of UINT_MAX to sample. */
3549     probability = dpif_sflow_get_probability(ofproto->sflow);
3550     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
3551
3552     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
3553
3554     cookie.type = USER_ACTION_COOKIE_SFLOW;
3555     cookie.data = port_ifindex;
3556     cookie.n_output = n_output;
3557     cookie.vlan_tci = 0;
3558     cookie_offset = put_userspace_action(ofproto, odp_actions, flow, &cookie);
3559
3560     nl_msg_end_nested(odp_actions, actions_offset);
3561     nl_msg_end_nested(odp_actions, sample_offset);
3562     return cookie_offset;
3563 }
3564
3565 /* SAMPLE action must be first action in any given list of actions.
3566  * At this point we do not have all information required to build it. So try to
3567  * build sample action as complete as possible. */
3568 static void
3569 add_sflow_action(struct action_xlate_ctx *ctx)
3570 {
3571     ctx->user_cookie_offset = compose_sflow_action(ctx->ofproto,
3572                                                    ctx->odp_actions,
3573                                                    &ctx->flow, OVSP_NONE);
3574     ctx->sflow_odp_port = 0;
3575     ctx->sflow_n_outputs = 0;
3576 }
3577
3578 /* Fix SAMPLE action according to data collected while composing ODP actions.
3579  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
3580  * USERSPACE action's user-cookie which is required for sflow. */
3581 static void
3582 fix_sflow_action(struct action_xlate_ctx *ctx)
3583 {
3584     const struct flow *base = &ctx->base_flow;
3585     struct user_action_cookie *cookie;
3586
3587     if (!ctx->user_cookie_offset) {
3588         return;
3589     }
3590
3591     cookie = ofpbuf_at(ctx->odp_actions, ctx->user_cookie_offset,
3592                      sizeof(*cookie));
3593     assert(cookie != NULL);
3594     assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
3595
3596     if (ctx->sflow_n_outputs) {
3597         cookie->data = dpif_sflow_odp_port_to_ifindex(ctx->ofproto->sflow,
3598                                                     ctx->sflow_odp_port);
3599     }
3600     if (ctx->sflow_n_outputs >= 255) {
3601         cookie->n_output = 255;
3602     } else {
3603         cookie->n_output = ctx->sflow_n_outputs;
3604     }
3605     cookie->vlan_tci = base->vlan_tci;
3606 }
3607
3608 static void
3609 commit_action__(struct ofpbuf *odp_actions,
3610                 enum ovs_action_attr act_type,
3611                 enum ovs_key_attr key_type,
3612                 const void *key, size_t key_size)
3613 {
3614     size_t offset = nl_msg_start_nested(odp_actions, act_type);
3615
3616     nl_msg_put_unspec(odp_actions, key_type, key, key_size);
3617     nl_msg_end_nested(odp_actions, offset);
3618 }
3619
3620 static void
3621 commit_set_tun_id_action(const struct flow *flow, struct flow *base,
3622                          struct ofpbuf *odp_actions)
3623 {
3624     if (base->tun_id == flow->tun_id) {
3625         return;
3626     }
3627     base->tun_id = flow->tun_id;
3628
3629     commit_action__(odp_actions, OVS_ACTION_ATTR_SET,
3630              OVS_KEY_ATTR_TUN_ID, &base->tun_id, sizeof(base->tun_id));
3631 }
3632
3633 static void
3634 commit_set_ether_addr_action(const struct flow *flow, struct flow *base,
3635                              struct ofpbuf *odp_actions)
3636 {
3637     struct ovs_key_ethernet eth_key;
3638
3639     if (eth_addr_equals(base->dl_src, flow->dl_src) &&
3640         eth_addr_equals(base->dl_dst, flow->dl_dst)) {
3641         return;
3642     }
3643
3644     memcpy(base->dl_src, flow->dl_src, ETH_ADDR_LEN);
3645     memcpy(base->dl_dst, flow->dl_dst, ETH_ADDR_LEN);
3646
3647     memcpy(eth_key.eth_src, base->dl_src, ETH_ADDR_LEN);
3648     memcpy(eth_key.eth_dst, base->dl_dst, ETH_ADDR_LEN);
3649
3650     commit_action__(odp_actions, OVS_ACTION_ATTR_SET,
3651              OVS_KEY_ATTR_ETHERNET, &eth_key, sizeof(eth_key));
3652 }
3653
3654 static void
3655 commit_vlan_action(struct action_xlate_ctx *ctx, ovs_be16 new_tci)
3656 {
3657     struct flow *base = &ctx->base_flow;
3658
3659     if (base->vlan_tci == new_tci) {
3660         return;
3661     }
3662
3663     if (base->vlan_tci & htons(VLAN_CFI)) {
3664         nl_msg_put_u16(ctx->odp_actions, OVS_ACTION_ATTR_POP,
3665                                        OVS_KEY_ATTR_8021Q);
3666     }
3667
3668     if (new_tci & htons(VLAN_CFI)) {
3669         struct ovs_key_8021q q_key;
3670
3671         q_key.q_tpid = htons(ETH_TYPE_VLAN);
3672         q_key.q_tci = new_tci & ~htons(VLAN_CFI);
3673
3674         commit_action__(ctx->odp_actions, OVS_ACTION_ATTR_PUSH,
3675                             OVS_KEY_ATTR_8021Q, &q_key, sizeof(q_key));
3676     }
3677     base->vlan_tci = new_tci;
3678 }
3679
3680 static void
3681 commit_set_nw_action(const struct flow *flow, struct flow *base,
3682                      struct ofpbuf *odp_actions)
3683 {
3684     int frag = base->tos_frag & FLOW_FRAG_MASK;
3685     struct ovs_key_ipv4 ipv4_key;
3686
3687     if (base->dl_type != htons(ETH_TYPE_IP) ||
3688         !base->nw_src || !base->nw_dst) {
3689         return;
3690     }
3691
3692     if (base->nw_src == flow->nw_src &&
3693         base->nw_dst == flow->nw_dst &&
3694         base->tos_frag == flow->tos_frag) {
3695         return;
3696     }
3697
3698
3699     memset(&ipv4_key, 0, sizeof(ipv4_key));
3700     ipv4_key.ipv4_src = base->nw_src = flow->nw_src;
3701     ipv4_key.ipv4_dst = base->nw_dst = flow->nw_dst;
3702     ipv4_key.ipv4_proto = base->nw_proto;
3703     ipv4_key.ipv4_tos = flow->tos_frag & IP_DSCP_MASK;
3704     ipv4_key.ipv4_frag = (frag == 0 ? OVS_FRAG_TYPE_NONE
3705                           : frag == FLOW_FRAG_ANY ? OVS_FRAG_TYPE_FIRST
3706                           : OVS_FRAG_TYPE_LATER);
3707
3708     commit_action__(odp_actions, OVS_ACTION_ATTR_SET,
3709              OVS_KEY_ATTR_IPV4, &ipv4_key, sizeof(ipv4_key));
3710 }
3711
3712 static void
3713 commit_set_port_action(const struct flow *flow, struct flow *base,
3714                        struct ofpbuf *odp_actions)
3715 {
3716     if (!base->tp_src || !base->tp_dst) {
3717         return;
3718     }
3719
3720     if (base->tp_src == flow->tp_src &&
3721         base->tp_dst == flow->tp_dst) {
3722         return;
3723     }
3724
3725     if (flow->nw_proto == IPPROTO_TCP) {
3726         struct ovs_key_tcp port_key;
3727
3728         port_key.tcp_src = base->tp_src = flow->tp_src;
3729         port_key.tcp_dst = base->tp_dst = flow->tp_dst;
3730
3731         commit_action__(odp_actions, OVS_ACTION_ATTR_SET,
3732              OVS_KEY_ATTR_TCP, &port_key, sizeof(port_key));
3733
3734     } else if (flow->nw_proto == IPPROTO_UDP) {
3735         struct ovs_key_udp port_key;
3736
3737         port_key.udp_src = base->tp_src = flow->tp_src;
3738         port_key.udp_dst = base->tp_dst = flow->tp_dst;
3739
3740         commit_action__(odp_actions, OVS_ACTION_ATTR_SET,
3741              OVS_KEY_ATTR_UDP, &port_key, sizeof(port_key));
3742     }
3743 }
3744
3745 static void
3746 commit_priority_action(struct action_xlate_ctx *ctx)
3747 {
3748     if (ctx->base_priority == ctx->priority) {
3749         return;
3750     }
3751
3752     if (ctx->priority) {
3753         nl_msg_put_u32(ctx->odp_actions,
3754                         OVS_ACTION_ATTR_SET_PRIORITY, ctx->priority);
3755     } else {
3756         nl_msg_put_flag(ctx->odp_actions, OVS_ACTION_ATTR_POP_PRIORITY);
3757     }
3758     ctx->base_priority = ctx->priority;
3759 }
3760
3761 static void
3762 commit_odp_actions(struct action_xlate_ctx *ctx)
3763 {
3764     const struct flow *flow = &ctx->flow;
3765     struct flow *base = &ctx->base_flow;
3766     struct ofpbuf *odp_actions = ctx->odp_actions;
3767
3768     commit_set_tun_id_action(flow, base, odp_actions);
3769     commit_set_ether_addr_action(flow, base, odp_actions);
3770     commit_vlan_action(ctx, flow->vlan_tci);
3771     commit_set_nw_action(flow, base, odp_actions);
3772     commit_set_port_action(flow, base, odp_actions);
3773     commit_priority_action(ctx);
3774 }
3775
3776 static void
3777 compose_output_action(struct action_xlate_ctx *ctx, uint16_t odp_port)
3778 {
3779     nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
3780     ctx->sflow_odp_port = odp_port;
3781     ctx->sflow_n_outputs++;
3782 }
3783
3784 static void
3785 add_output_action(struct action_xlate_ctx *ctx, uint16_t ofp_port)
3786 {
3787     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
3788     uint16_t odp_port = ofp_port_to_odp_port(ofp_port);
3789
3790     if (ofport) {
3791         if (ofport->up.opp.config & htonl(OFPPC_NO_FWD)
3792                 || !stp_forward_in_state(ofport->stp_state)) {
3793             /* Forwarding disabled on port. */
3794             return;
3795         }
3796     } else {
3797         /*
3798          * We don't have an ofport record for this port, but it doesn't hurt to
3799          * allow forwarding to it anyhow.  Maybe such a port will appear later
3800          * and we're pre-populating the flow table.
3801          */
3802     }
3803
3804     commit_odp_actions(ctx);
3805     compose_output_action(ctx, odp_port);
3806     ctx->nf_output_iface = ofp_port;
3807 }
3808
3809 static void
3810 xlate_table_action(struct action_xlate_ctx *ctx,
3811                    uint16_t in_port, uint8_t table_id)
3812 {
3813     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
3814         struct ofproto_dpif *ofproto = ctx->ofproto;
3815         struct rule_dpif *rule;
3816         uint16_t old_in_port;
3817         uint8_t old_table_id;
3818
3819         old_table_id = ctx->table_id;
3820         ctx->table_id = table_id;
3821
3822         /* Look up a flow with 'in_port' as the input port. */
3823         old_in_port = ctx->flow.in_port;
3824         ctx->flow.in_port = in_port;
3825         rule = rule_dpif_lookup(ofproto, &ctx->flow, table_id);
3826
3827         /* Tag the flow. */
3828         if (table_id > 0 && table_id < N_TABLES) {
3829             struct table_dpif *table = &ofproto->tables[table_id];
3830             if (table->other_table) {
3831                 ctx->tags |= (rule
3832                               ? rule->tag
3833                               : rule_calculate_tag(&ctx->flow,
3834                                                    &table->other_table->wc,
3835                                                    table->basis));
3836             }
3837         }
3838
3839         /* Restore the original input port.  Otherwise OFPP_NORMAL and
3840          * OFPP_IN_PORT will have surprising behavior. */
3841         ctx->flow.in_port = old_in_port;
3842
3843         if (ctx->resubmit_hook) {
3844             ctx->resubmit_hook(ctx, rule);
3845         }
3846
3847         if (rule) {
3848             ctx->recurse++;
3849             do_xlate_actions(rule->up.actions, rule->up.n_actions, ctx);
3850             ctx->recurse--;
3851         }
3852
3853         ctx->table_id = old_table_id;
3854     } else {
3855         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
3856
3857         VLOG_ERR_RL(&recurse_rl, "resubmit actions recursed over %d times",
3858                     MAX_RESUBMIT_RECURSION);
3859     }
3860 }
3861
3862 static void
3863 xlate_resubmit_table(struct action_xlate_ctx *ctx,
3864                      const struct nx_action_resubmit *nar)
3865 {
3866     uint16_t in_port;
3867     uint8_t table_id;
3868
3869     in_port = (nar->in_port == htons(OFPP_IN_PORT)
3870                ? ctx->flow.in_port
3871                : ntohs(nar->in_port));
3872     table_id = nar->table == 255 ? ctx->table_id : nar->table;
3873
3874     xlate_table_action(ctx, in_port, table_id);
3875 }
3876
3877 static void
3878 flood_packets(struct action_xlate_ctx *ctx, ovs_be32 mask)
3879 {
3880     struct ofport_dpif *ofport;
3881
3882     commit_odp_actions(ctx);
3883     HMAP_FOR_EACH (ofport, up.hmap_node, &ctx->ofproto->up.ports) {
3884         uint16_t ofp_port = ofport->up.ofp_port;
3885         if (ofp_port != ctx->flow.in_port
3886                 && !(ofport->up.opp.config & mask)
3887                 && stp_forward_in_state(ofport->stp_state)) {
3888             compose_output_action(ctx, ofport->odp_port);
3889         }
3890     }
3891
3892     ctx->nf_output_iface = NF_OUT_FLOOD;
3893 }
3894
3895 static void
3896 compose_controller_action(struct action_xlate_ctx *ctx, int len)
3897 {
3898     struct user_action_cookie cookie;
3899
3900     cookie.type = USER_ACTION_COOKIE_CONTROLLER;
3901     cookie.data = len;
3902     cookie.n_output = 0;
3903     cookie.vlan_tci = 0;
3904     put_userspace_action(ctx->ofproto, ctx->odp_actions, &ctx->flow, &cookie);
3905 }
3906
3907 static void
3908 xlate_output_action__(struct action_xlate_ctx *ctx,
3909                       uint16_t port, uint16_t max_len)
3910 {
3911     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
3912
3913     ctx->nf_output_iface = NF_OUT_DROP;
3914
3915     switch (port) {
3916     case OFPP_IN_PORT:
3917         add_output_action(ctx, ctx->flow.in_port);
3918         break;
3919     case OFPP_TABLE:
3920         xlate_table_action(ctx, ctx->flow.in_port, ctx->table_id);
3921         break;
3922     case OFPP_NORMAL:
3923         xlate_normal(ctx);
3924         break;
3925     case OFPP_FLOOD:
3926         flood_packets(ctx,  htonl(OFPPC_NO_FLOOD));
3927         break;
3928     case OFPP_ALL:
3929         flood_packets(ctx, htonl(0));
3930         break;
3931     case OFPP_CONTROLLER:
3932         commit_odp_actions(ctx);
3933         compose_controller_action(ctx, max_len);
3934         break;
3935     case OFPP_LOCAL:
3936         add_output_action(ctx, OFPP_LOCAL);
3937         break;
3938     case OFPP_NONE:
3939         break;
3940     default:
3941         if (port != ctx->flow.in_port) {
3942             add_output_action(ctx, port);
3943         }
3944         break;
3945     }
3946
3947     if (prev_nf_output_iface == NF_OUT_FLOOD) {
3948         ctx->nf_output_iface = NF_OUT_FLOOD;
3949     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
3950         ctx->nf_output_iface = prev_nf_output_iface;
3951     } else if (prev_nf_output_iface != NF_OUT_DROP &&
3952                ctx->nf_output_iface != NF_OUT_FLOOD) {
3953         ctx->nf_output_iface = NF_OUT_MULTI;
3954     }
3955 }
3956
3957 static void
3958 xlate_output_reg_action(struct action_xlate_ctx *ctx,
3959                         const struct nx_action_output_reg *naor)
3960 {
3961     uint64_t ofp_port;
3962
3963     ofp_port = nxm_read_field_bits(naor->src, naor->ofs_nbits, &ctx->flow);
3964
3965     if (ofp_port <= UINT16_MAX) {
3966         xlate_output_action__(ctx, ofp_port, ntohs(naor->max_len));
3967     }
3968 }
3969
3970 static void
3971 xlate_output_action(struct action_xlate_ctx *ctx,
3972                     const struct ofp_action_output *oao)
3973 {
3974     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
3975 }
3976
3977 static void
3978 xlate_enqueue_action(struct action_xlate_ctx *ctx,
3979                      const struct ofp_action_enqueue *oae)
3980 {
3981     uint16_t ofp_port, odp_port;
3982     uint32_t ctx_priority, priority;
3983     int error;
3984
3985     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
3986                                    &priority);
3987     if (error) {
3988         /* Fall back to ordinary output action. */
3989         xlate_output_action__(ctx, ntohs(oae->port), 0);
3990         return;
3991     }
3992
3993     /* Figure out datapath output port. */
3994     ofp_port = ntohs(oae->port);
3995     if (ofp_port == OFPP_IN_PORT) {
3996         ofp_port = ctx->flow.in_port;
3997     } else if (ofp_port == ctx->flow.in_port) {
3998         return;
3999     }
4000     odp_port = ofp_port_to_odp_port(ofp_port);
4001
4002     /* Add datapath actions. */
4003     ctx_priority = ctx->priority;
4004     ctx->priority = priority;
4005     add_output_action(ctx, odp_port);
4006     ctx->priority = ctx_priority;
4007
4008     /* Update NetFlow output port. */
4009     if (ctx->nf_output_iface == NF_OUT_DROP) {
4010         ctx->nf_output_iface = odp_port;
4011     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
4012         ctx->nf_output_iface = NF_OUT_MULTI;
4013     }
4014 }
4015
4016 static void
4017 xlate_set_queue_action(struct action_xlate_ctx *ctx,
4018                        const struct nx_action_set_queue *nasq)
4019 {
4020     uint32_t priority;
4021     int error;
4022
4023     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
4024                                    &priority);
4025     if (error) {
4026         /* Couldn't translate queue to a priority, so ignore.  A warning
4027          * has already been logged. */
4028         return;
4029     }
4030
4031     ctx->priority = priority;
4032 }
4033
4034 struct xlate_reg_state {
4035     ovs_be16 vlan_tci;
4036     ovs_be64 tun_id;
4037 };
4038
4039 static void
4040 xlate_autopath(struct action_xlate_ctx *ctx,
4041                const struct nx_action_autopath *naa)
4042 {
4043     uint16_t ofp_port = ntohl(naa->id);
4044     struct ofport_dpif *port = get_ofp_port(ctx->ofproto, ofp_port);
4045
4046     if (!port || !port->bundle) {
4047         ofp_port = OFPP_NONE;
4048     } else if (port->bundle->bond) {
4049         /* Autopath does not support VLAN hashing. */
4050         struct ofport_dpif *slave = bond_choose_output_slave(
4051             port->bundle->bond, &ctx->flow, 0, &ctx->tags);
4052         if (slave) {
4053             ofp_port = slave->up.ofp_port;
4054         }
4055     }
4056     autopath_execute(naa, &ctx->flow, ofp_port);
4057 }
4058
4059 static bool
4060 slave_enabled_cb(uint16_t ofp_port, void *ofproto_)
4061 {
4062     struct ofproto_dpif *ofproto = ofproto_;
4063     struct ofport_dpif *port;
4064
4065     switch (ofp_port) {
4066     case OFPP_IN_PORT:
4067     case OFPP_TABLE:
4068     case OFPP_NORMAL:
4069     case OFPP_FLOOD:
4070     case OFPP_ALL:
4071     case OFPP_LOCAL:
4072         return true;
4073     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
4074         return false;
4075     default:
4076         port = get_ofp_port(ofproto, ofp_port);
4077         return port ? port->may_enable : false;
4078     }
4079 }
4080
4081 static void
4082 xlate_learn_action(struct action_xlate_ctx *ctx,
4083                    const struct nx_action_learn *learn)
4084 {
4085     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
4086     struct ofputil_flow_mod fm;
4087     int error;
4088
4089     learn_execute(learn, &ctx->flow, &fm);
4090
4091     error = ofproto_flow_mod(&ctx->ofproto->up, &fm);
4092     if (error && !VLOG_DROP_WARN(&rl)) {
4093         char *msg = ofputil_error_to_string(error);
4094         VLOG_WARN("learning action failed to modify flow table (%s)", msg);
4095         free(msg);
4096     }
4097
4098     free(fm.actions);
4099 }
4100
4101 static bool
4102 may_receive(const struct ofport_dpif *port, struct action_xlate_ctx *ctx)
4103 {
4104     if (port->up.opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
4105                                ? htonl(OFPPC_NO_RECV_STP)
4106                                : htonl(OFPPC_NO_RECV))) {
4107         return false;
4108     }
4109
4110     /* Only drop packets here if both forwarding and learning are
4111      * disabled.  If just learning is enabled, we need to have
4112      * OFPP_NORMAL and the learning action have a look at the packet
4113      * before we can drop it. */
4114     if (!stp_forward_in_state(port->stp_state)
4115             && !stp_learn_in_state(port->stp_state)) {
4116         return false;
4117     }
4118
4119     return true;
4120 }
4121
4122 static void
4123 do_xlate_actions(const union ofp_action *in, size_t n_in,
4124                  struct action_xlate_ctx *ctx)
4125 {
4126     const struct ofport_dpif *port;
4127     const union ofp_action *ia;
4128     size_t left;
4129
4130     port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
4131     if (port && !may_receive(port, ctx)) {
4132         /* Drop this flow. */
4133         return;
4134     }
4135
4136     OFPUTIL_ACTION_FOR_EACH_UNSAFE (ia, left, in, n_in) {
4137         const struct ofp_action_dl_addr *oada;
4138         const struct nx_action_resubmit *nar;
4139         const struct nx_action_set_tunnel *nast;
4140         const struct nx_action_set_queue *nasq;
4141         const struct nx_action_multipath *nam;
4142         const struct nx_action_autopath *naa;
4143         const struct nx_action_bundle *nab;
4144         const struct nx_action_output_reg *naor;
4145         enum ofputil_action_code code;
4146         ovs_be64 tun_id;
4147
4148         code = ofputil_decode_action_unsafe(ia);
4149         switch (code) {
4150         case OFPUTIL_OFPAT_OUTPUT:
4151             xlate_output_action(ctx, &ia->output);
4152             break;
4153
4154         case OFPUTIL_OFPAT_SET_VLAN_VID:
4155             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
4156             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
4157             break;
4158
4159         case OFPUTIL_OFPAT_SET_VLAN_PCP:
4160             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
4161             ctx->flow.vlan_tci |= htons(
4162                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
4163             break;
4164
4165         case OFPUTIL_OFPAT_STRIP_VLAN:
4166             ctx->flow.vlan_tci = htons(0);
4167             break;
4168
4169         case OFPUTIL_OFPAT_SET_DL_SRC:
4170             oada = ((struct ofp_action_dl_addr *) ia);
4171             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
4172             break;
4173
4174         case OFPUTIL_OFPAT_SET_DL_DST:
4175             oada = ((struct ofp_action_dl_addr *) ia);
4176             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
4177             break;
4178
4179         case OFPUTIL_OFPAT_SET_NW_SRC:
4180             ctx->flow.nw_src = ia->nw_addr.nw_addr;
4181             break;
4182
4183         case OFPUTIL_OFPAT_SET_NW_DST:
4184             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
4185             break;
4186
4187         case OFPUTIL_OFPAT_SET_NW_TOS:
4188             ctx->flow.tos_frag &= ~IP_DSCP_MASK;
4189             ctx->flow.tos_frag |= ia->nw_tos.nw_tos & IP_DSCP_MASK;
4190             break;
4191
4192         case OFPUTIL_OFPAT_SET_TP_SRC:
4193             ctx->flow.tp_src = ia->tp_port.tp_port;
4194             break;
4195
4196         case OFPUTIL_OFPAT_SET_TP_DST:
4197             ctx->flow.tp_dst = ia->tp_port.tp_port;
4198             break;
4199
4200         case OFPUTIL_OFPAT_ENQUEUE:
4201             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
4202             break;
4203
4204         case OFPUTIL_NXAST_RESUBMIT:
4205             nar = (const struct nx_action_resubmit *) ia;
4206             xlate_table_action(ctx, ntohs(nar->in_port), ctx->table_id);
4207             break;
4208
4209         case OFPUTIL_NXAST_RESUBMIT_TABLE:
4210             xlate_resubmit_table(ctx, (const struct nx_action_resubmit *) ia);
4211             break;
4212
4213         case OFPUTIL_NXAST_SET_TUNNEL:
4214             nast = (const struct nx_action_set_tunnel *) ia;
4215             tun_id = htonll(ntohl(nast->tun_id));
4216             ctx->flow.tun_id = tun_id;
4217             break;
4218
4219         case OFPUTIL_NXAST_SET_QUEUE:
4220             nasq = (const struct nx_action_set_queue *) ia;
4221             xlate_set_queue_action(ctx, nasq);
4222             break;
4223
4224         case OFPUTIL_NXAST_POP_QUEUE:
4225             ctx->priority = 0;
4226             break;
4227
4228         case OFPUTIL_NXAST_REG_MOVE:
4229             nxm_execute_reg_move((const struct nx_action_reg_move *) ia,
4230                                  &ctx->flow);
4231             break;
4232
4233         case OFPUTIL_NXAST_REG_LOAD:
4234             nxm_execute_reg_load((const struct nx_action_reg_load *) ia,
4235                                  &ctx->flow);
4236             break;
4237
4238         case OFPUTIL_NXAST_NOTE:
4239             /* Nothing to do. */
4240             break;
4241
4242         case OFPUTIL_NXAST_SET_TUNNEL64:
4243             tun_id = ((const struct nx_action_set_tunnel64 *) ia)->tun_id;
4244             ctx->flow.tun_id = tun_id;
4245             break;
4246
4247         case OFPUTIL_NXAST_MULTIPATH:
4248             nam = (const struct nx_action_multipath *) ia;
4249             multipath_execute(nam, &ctx->flow);
4250             break;
4251
4252         case OFPUTIL_NXAST_AUTOPATH:
4253             naa = (const struct nx_action_autopath *) ia;
4254             xlate_autopath(ctx, naa);
4255             break;
4256
4257         case OFPUTIL_NXAST_BUNDLE:
4258             ctx->ofproto->has_bundle_action = true;
4259             nab = (const struct nx_action_bundle *) ia;
4260             xlate_output_action__(ctx, bundle_execute(nab, &ctx->flow,
4261                                                       slave_enabled_cb,
4262                                                       ctx->ofproto), 0);
4263             break;
4264
4265         case OFPUTIL_NXAST_BUNDLE_LOAD:
4266             ctx->ofproto->has_bundle_action = true;
4267             nab = (const struct nx_action_bundle *) ia;
4268             bundle_execute_load(nab, &ctx->flow, slave_enabled_cb,
4269                                 ctx->ofproto);
4270             break;
4271
4272         case OFPUTIL_NXAST_OUTPUT_REG:
4273             naor = (const struct nx_action_output_reg *) ia;
4274             xlate_output_reg_action(ctx, naor);
4275             break;
4276
4277         case OFPUTIL_NXAST_LEARN:
4278             ctx->has_learn = true;
4279             if (ctx->may_learn) {
4280                 xlate_learn_action(ctx, (const struct nx_action_learn *) ia);
4281             }
4282             break;
4283         }
4284     }
4285
4286     /* We've let OFPP_NORMAL and the learning action look at the packet,
4287      * so drop it now if forwarding is disabled. */
4288     if (port && !stp_forward_in_state(port->stp_state)) {
4289         ofpbuf_clear(ctx->odp_actions);
4290         add_sflow_action(ctx);
4291     }
4292 }
4293
4294 static void
4295 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
4296                       struct ofproto_dpif *ofproto, const struct flow *flow,
4297                       const struct ofpbuf *packet)
4298 {
4299     ctx->ofproto = ofproto;
4300     ctx->flow = *flow;
4301     ctx->packet = packet;
4302     ctx->may_learn = packet != NULL;
4303     ctx->resubmit_hook = NULL;
4304 }
4305
4306 static struct ofpbuf *
4307 xlate_actions(struct action_xlate_ctx *ctx,
4308               const union ofp_action *in, size_t n_in)
4309 {
4310     COVERAGE_INC(ofproto_dpif_xlate);
4311
4312     ctx->odp_actions = ofpbuf_new(512);
4313     ofpbuf_reserve(ctx->odp_actions, NL_A_U32_SIZE);
4314     ctx->tags = 0;
4315     ctx->may_set_up_flow = true;
4316     ctx->has_learn = false;
4317     ctx->has_normal = false;
4318     ctx->nf_output_iface = NF_OUT_DROP;
4319     ctx->recurse = 0;
4320     ctx->priority = 0;
4321     ctx->base_priority = 0;
4322     ctx->base_flow = ctx->flow;
4323     ctx->base_flow.tun_id = 0;
4324     ctx->table_id = 0;
4325
4326     if (ctx->flow.tos_frag & FLOW_FRAG_ANY) {
4327         switch (ctx->ofproto->up.frag_handling) {
4328         case OFPC_FRAG_NORMAL:
4329             /* We must pretend that transport ports are unavailable. */
4330             ctx->flow.tp_src = ctx->base_flow.tp_src = htons(0);
4331             ctx->flow.tp_dst = ctx->base_flow.tp_dst = htons(0);
4332             break;
4333
4334         case OFPC_FRAG_DROP:
4335             return ctx->odp_actions;
4336
4337         case OFPC_FRAG_REASM:
4338             NOT_REACHED();
4339
4340         case OFPC_FRAG_NX_MATCH:
4341             /* Nothing to do. */
4342             break;
4343         }
4344     }
4345
4346     if (process_special(ctx->ofproto, &ctx->flow, ctx->packet)) {
4347         ctx->may_set_up_flow = false;
4348         return ctx->odp_actions;
4349     } else {
4350         add_sflow_action(ctx);
4351         do_xlate_actions(in, n_in, ctx);
4352
4353         if (!connmgr_may_set_up_flow(ctx->ofproto->up.connmgr, &ctx->flow,
4354                                      ctx->odp_actions->data,
4355                                      ctx->odp_actions->size)) {
4356             ctx->may_set_up_flow = false;
4357             if (ctx->packet
4358                 && connmgr_msg_in_hook(ctx->ofproto->up.connmgr, &ctx->flow,
4359                                        ctx->packet)) {
4360                 compose_output_action(ctx, OVSP_LOCAL);
4361             }
4362         }
4363         fix_sflow_action(ctx);
4364     }
4365
4366     return ctx->odp_actions;
4367 }
4368 \f
4369 /* OFPP_NORMAL implementation. */
4370
4371 struct dst {
4372     struct ofport_dpif *port;
4373     uint16_t vid;
4374 };
4375
4376 struct dst_set {
4377     struct dst builtin[32];
4378     struct dst *dsts;
4379     size_t n, allocated;
4380 };
4381
4382 static void dst_set_init(struct dst_set *);
4383 static void dst_set_add(struct dst_set *, const struct dst *);
4384 static void dst_set_free(struct dst_set *);
4385
4386 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
4387
4388 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
4389  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_bundle',
4390  * the bundle on which the packet was received, returns the VLAN to which the
4391  * packet belongs.
4392  *
4393  * Both 'vid' and the return value are in the range 0...4095. */
4394 static uint16_t
4395 input_vid_to_vlan(const struct ofbundle *in_bundle, uint16_t vid)
4396 {
4397     switch (in_bundle->vlan_mode) {
4398     case PORT_VLAN_ACCESS:
4399         return in_bundle->vlan;
4400         break;
4401
4402     case PORT_VLAN_TRUNK:
4403         return vid;
4404
4405     case PORT_VLAN_NATIVE_UNTAGGED:
4406     case PORT_VLAN_NATIVE_TAGGED:
4407         return vid ? vid : in_bundle->vlan;
4408
4409     default:
4410         NOT_REACHED();
4411     }
4412 }
4413
4414 /* Given 'vlan', the VLAN that a packet belongs to, and
4415  * 'out_bundle', a bundle on which the packet is to be output, returns the VID
4416  * that should be included in the 802.1Q header.  (If the return value is 0,
4417  * then the 802.1Q header should only be included in the packet if there is a
4418  * nonzero PCP.)
4419  *
4420  * Both 'vlan' and the return value are in the range 0...4095. */
4421 static uint16_t
4422 output_vlan_to_vid(const struct ofbundle *out_bundle, uint16_t vlan)
4423 {
4424     switch (out_bundle->vlan_mode) {
4425     case PORT_VLAN_ACCESS:
4426         return 0;
4427
4428     case PORT_VLAN_TRUNK:
4429     case PORT_VLAN_NATIVE_TAGGED:
4430         return vlan;
4431
4432     case PORT_VLAN_NATIVE_UNTAGGED:
4433         return vlan == out_bundle->vlan ? 0 : vlan;
4434
4435     default:
4436         NOT_REACHED();
4437     }
4438 }
4439
4440 static bool
4441 set_dst(struct action_xlate_ctx *ctx, struct dst *dst,
4442         const struct ofbundle *in_bundle, const struct ofbundle *out_bundle)
4443 {
4444     uint16_t vlan;
4445
4446     vlan = input_vid_to_vlan(in_bundle, vlan_tci_to_vid(ctx->flow.vlan_tci));
4447     dst->vid = output_vlan_to_vid(out_bundle, vlan);
4448
4449     dst->port = (!out_bundle->bond
4450                  ? ofbundle_get_a_port(out_bundle)
4451                  : bond_choose_output_slave(out_bundle->bond, &ctx->flow,
4452                                             dst->vid, &ctx->tags));
4453     return dst->port != NULL;
4454 }
4455
4456 static int
4457 mirror_mask_ffs(mirror_mask_t mask)
4458 {
4459     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
4460     return ffs(mask);
4461 }
4462
4463 static void
4464 dst_set_init(struct dst_set *set)
4465 {
4466     set->dsts = set->builtin;
4467     set->n = 0;
4468     set->allocated = ARRAY_SIZE(set->builtin);
4469 }
4470
4471 static void
4472 dst_set_add(struct dst_set *set, const struct dst *dst)
4473 {
4474     if (set->n >= set->allocated) {
4475         size_t new_allocated;
4476         struct dst *new_dsts;
4477
4478         new_allocated = set->allocated * 2;
4479         new_dsts = xmalloc(new_allocated * sizeof *new_dsts);
4480         memcpy(new_dsts, set->dsts, set->n * sizeof *new_dsts);
4481
4482         dst_set_free(set);
4483
4484         set->dsts = new_dsts;
4485         set->allocated = new_allocated;
4486     }
4487     set->dsts[set->n++] = *dst;
4488 }
4489
4490 static void
4491 dst_set_free(struct dst_set *set)
4492 {
4493     if (set->dsts != set->builtin) {
4494         free(set->dsts);
4495     }
4496 }
4497
4498 static bool
4499 dst_is_duplicate(const struct dst_set *set, const struct dst *test)
4500 {
4501     size_t i;
4502     for (i = 0; i < set->n; i++) {
4503         if (set->dsts[i].vid == test->vid
4504             && set->dsts[i].port == test->port) {
4505             return true;
4506         }
4507     }
4508     return false;
4509 }
4510
4511 static bool
4512 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
4513 {
4514     return (bundle->vlan_mode != PORT_VLAN_ACCESS
4515             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
4516 }
4517
4518 static bool
4519 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
4520 {
4521     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
4522 }
4523
4524 /* Returns an arbitrary interface within 'bundle'. */
4525 static struct ofport_dpif *
4526 ofbundle_get_a_port(const struct ofbundle *bundle)
4527 {
4528     return CONTAINER_OF(list_front(&bundle->ports),
4529                         struct ofport_dpif, bundle_node);
4530 }
4531
4532 static void
4533 compose_dsts(struct action_xlate_ctx *ctx, uint16_t vlan,
4534              const struct ofbundle *in_bundle,
4535              const struct ofbundle *out_bundle, struct dst_set *set)
4536 {
4537     struct dst dst;
4538
4539     if (out_bundle == OFBUNDLE_FLOOD) {
4540         struct ofbundle *bundle;
4541
4542         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
4543             if (bundle != in_bundle
4544                 && ofbundle_includes_vlan(bundle, vlan)
4545                 && bundle->floodable
4546                 && !bundle->mirror_out
4547                 && set_dst(ctx, &dst, in_bundle, bundle)) {
4548                 dst_set_add(set, &dst);
4549             }
4550         }
4551         ctx->nf_output_iface = NF_OUT_FLOOD;
4552     } else if (out_bundle && set_dst(ctx, &dst, in_bundle, out_bundle)) {
4553         dst_set_add(set, &dst);
4554         ctx->nf_output_iface = dst.port->odp_port;
4555     }
4556 }
4557
4558 static bool
4559 vlan_is_mirrored(const struct ofmirror *m, int vlan)
4560 {
4561     return !m->vlans || bitmap_is_set(m->vlans, vlan);
4562 }
4563
4564 /* Returns true if a packet with Ethernet destination MAC 'dst' may be mirrored
4565  * to a VLAN.  In general most packets may be mirrored but we want to drop
4566  * protocols that may confuse switches. */
4567 static bool
4568 eth_dst_may_rspan(const uint8_t dst[ETH_ADDR_LEN])
4569 {
4570     /* If you change this function's behavior, please update corresponding
4571      * documentation in vswitch.xml at the same time. */
4572     if (dst[0] != 0x01) {
4573         /* All the currently banned MACs happen to start with 01 currently, so
4574          * this is a quick way to eliminate most of the good ones. */
4575     } else {
4576         if (eth_addr_is_reserved(dst)) {
4577             /* Drop STP, IEEE pause frames, and other reserved protocols
4578              * (01-80-c2-00-00-0x). */
4579             return false;
4580         }
4581
4582         if (dst[0] == 0x01 && dst[1] == 0x00 && dst[2] == 0x0c) {
4583             /* Cisco OUI. */
4584             if ((dst[3] & 0xfe) == 0xcc &&
4585                 (dst[4] & 0xfe) == 0xcc &&
4586                 (dst[5] & 0xfe) == 0xcc) {
4587                 /* Drop the following protocols plus others following the same
4588                    pattern:
4589
4590                    CDP, VTP, DTP, PAgP  (01-00-0c-cc-cc-cc)
4591                    Spanning Tree PVSTP+ (01-00-0c-cc-cc-cd)
4592                    STP Uplink Fast      (01-00-0c-cd-cd-cd) */
4593                 return false;
4594             }
4595
4596             if (!(dst[3] | dst[4] | dst[5])) {
4597                 /* Drop Inter Switch Link packets (01-00-0c-00-00-00). */
4598                 return false;
4599             }
4600         }
4601     }
4602     return true;
4603 }
4604
4605 static void
4606 compose_mirror_dsts(struct action_xlate_ctx *ctx,
4607                     uint16_t vlan, const struct ofbundle *in_bundle,
4608                     struct dst_set *set)
4609 {
4610     struct ofproto_dpif *ofproto = ctx->ofproto;
4611     mirror_mask_t mirrors;
4612     uint16_t flow_vid;
4613     size_t i;
4614
4615     mirrors = in_bundle->src_mirrors;
4616     for (i = 0; i < set->n; i++) {
4617         mirrors |= set->dsts[i].port->bundle->dst_mirrors;
4618     }
4619
4620     if (!mirrors) {
4621         return;
4622     }
4623
4624     flow_vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
4625     while (mirrors) {
4626         struct ofmirror *m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
4627         if (vlan_is_mirrored(m, vlan)) {
4628             struct dst dst;
4629
4630             if (m->out) {
4631                 if (set_dst(ctx, &dst, in_bundle, m->out)
4632                     && !dst_is_duplicate(set, &dst)) {
4633                     dst_set_add(set, &dst);
4634                 }
4635             } else if (eth_dst_may_rspan(ctx->flow.dl_dst)) {
4636                 struct ofbundle *bundle;
4637
4638                 HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
4639                     if (ofbundle_includes_vlan(bundle, m->out_vlan)
4640                         && set_dst(ctx, &dst, in_bundle, bundle))
4641                     {
4642                         /* set_dst() got dst->vid from the input packet's VLAN,
4643                          * not from m->out_vlan, so recompute it. */
4644                         dst.vid = output_vlan_to_vid(bundle, m->out_vlan);
4645
4646                         if (dst_is_duplicate(set, &dst)) {
4647                             continue;
4648                         }
4649
4650                         if (bundle == in_bundle && dst.vid == flow_vid) {
4651                             /* Don't send out input port on same VLAN. */
4652                             continue;
4653                         }
4654                         dst_set_add(set, &dst);
4655                     }
4656                 }
4657             }
4658         }
4659         mirrors &= mirrors - 1;
4660     }
4661 }
4662
4663 static void
4664 compose_dst_output_action(struct action_xlate_ctx *ctx, const struct dst *dst)
4665 {
4666     ovs_be16 tci;
4667
4668     tci = htons(dst->vid);
4669     if (tci) {
4670         tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
4671         tci |= htons(VLAN_CFI);
4672     }
4673     commit_vlan_action(ctx, tci);
4674
4675     compose_output_action(ctx, dst->port->odp_port);
4676 }
4677
4678 static void
4679 compose_actions(struct action_xlate_ctx *ctx, uint16_t vlan,
4680                 const struct ofbundle *in_bundle,
4681                 const struct ofbundle *out_bundle)
4682 {
4683     uint16_t initial_vid;
4684     const struct dst *dst;
4685     struct dst_set set;
4686
4687     dst_set_init(&set);
4688     compose_dsts(ctx, vlan, in_bundle, out_bundle, &set);
4689     compose_mirror_dsts(ctx, vlan, in_bundle, &set);
4690     if (!set.n) {
4691         dst_set_free(&set);
4692         return;
4693     }
4694
4695     /* Output all the packets we can without having to change the VLAN. */
4696     commit_odp_actions(ctx);
4697     initial_vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
4698     for (dst = set.dsts; dst < &set.dsts[set.n]; dst++) {
4699         if (dst->vid == initial_vid) {
4700             compose_dst_output_action(ctx, dst);
4701         }
4702     }
4703
4704     /* Then output the rest. */
4705     for (dst = set.dsts; dst < &set.dsts[set.n]; dst++) {
4706         if (dst->vid != initial_vid) {
4707             compose_dst_output_action(ctx, dst);
4708         }
4709     }
4710
4711     dst_set_free(&set);
4712 }
4713
4714 /* Returns the effective vlan of a packet, taking into account both the
4715  * 802.1Q header and implicitly tagged ports.  A value of 0 indicates that
4716  * the packet is untagged and -1 indicates it has an invalid header and
4717  * should be dropped. */
4718 static int
4719 flow_get_vlan(struct ofproto_dpif *ofproto, const struct flow *flow,
4720               struct ofbundle *in_bundle, bool have_packet)
4721 {
4722     int vlan = vlan_tci_to_vid(flow->vlan_tci);
4723     if (vlan) {
4724         if (in_bundle->vlan_mode == PORT_VLAN_ACCESS) {
4725             /* Drop tagged packet on access port */
4726             if (have_packet) {
4727                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4728                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
4729                              "packet received on port %s configured with "
4730                              "implicit VLAN %"PRIu16,
4731                              ofproto->up.name, vlan,
4732                              in_bundle->name, in_bundle->vlan);
4733             }
4734             return -1;
4735         } else if (ofbundle_includes_vlan(in_bundle, vlan)) {
4736             return vlan;
4737         } else {
4738             /* Drop packets from a VLAN not member of the trunk */
4739             if (have_packet) {
4740                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4741                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
4742                              "packet received on port %s not configured for "
4743                              "trunking VLAN %d",
4744                              ofproto->up.name, vlan, in_bundle->name, vlan);
4745             }
4746             return -1;
4747         }
4748     } else {
4749         if (in_bundle->vlan_mode != PORT_VLAN_TRUNK) {
4750             return in_bundle->vlan;
4751         } else {
4752             return ofbundle_includes_vlan(in_bundle, 0) ? 0 : -1;
4753         }
4754     }
4755 }
4756
4757 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
4758  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
4759  * indicate this; newer upstream kernels use gratuitous ARP requests. */
4760 static bool
4761 is_gratuitous_arp(const struct flow *flow)
4762 {
4763     return (flow->dl_type == htons(ETH_TYPE_ARP)
4764             && eth_addr_is_broadcast(flow->dl_dst)
4765             && (flow->nw_proto == ARP_OP_REPLY
4766                 || (flow->nw_proto == ARP_OP_REQUEST
4767                     && flow->nw_src == flow->nw_dst)));
4768 }
4769
4770 static void
4771 update_learning_table(struct ofproto_dpif *ofproto,
4772                       const struct flow *flow, int vlan,
4773                       struct ofbundle *in_bundle)
4774 {
4775     struct mac_entry *mac;
4776
4777     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
4778         return;
4779     }
4780
4781     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
4782     if (is_gratuitous_arp(flow)) {
4783         /* We don't want to learn from gratuitous ARP packets that are
4784          * reflected back over bond slaves so we lock the learning table. */
4785         if (!in_bundle->bond) {
4786             mac_entry_set_grat_arp_lock(mac);
4787         } else if (mac_entry_is_grat_arp_locked(mac)) {
4788             return;
4789         }
4790     }
4791
4792     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
4793         /* The log messages here could actually be useful in debugging,
4794          * so keep the rate limit relatively high. */
4795         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
4796         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
4797                     "on port %s in VLAN %d",
4798                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
4799                     in_bundle->name, vlan);
4800
4801         mac->port.p = in_bundle;
4802         tag_set_add(&ofproto->revalidate_set,
4803                     mac_learning_changed(ofproto->ml, mac));
4804     }
4805 }
4806
4807 /* Determines whether packets in 'flow' within 'br' should be forwarded or
4808  * dropped.  Returns true if they may be forwarded, false if they should be
4809  * dropped.
4810  *
4811  * If 'have_packet' is true, it indicates that the caller is processing a
4812  * received packet.  If 'have_packet' is false, then the caller is just
4813  * revalidating an existing flow because configuration has changed.  Either
4814  * way, 'have_packet' only affects logging (there is no point in logging errors
4815  * during revalidation).
4816  *
4817  * Sets '*in_portp' to the input port.  This will be a null pointer if
4818  * flow->in_port does not designate a known input port (in which case
4819  * is_admissible() returns false).
4820  *
4821  * When returning true, sets '*vlanp' to the effective VLAN of the input
4822  * packet, as returned by flow_get_vlan().
4823  *
4824  * May also add tags to '*tags', although the current implementation only does
4825  * so in one special case.
4826  */
4827 static bool
4828 is_admissible(struct ofproto_dpif *ofproto, const struct flow *flow,
4829               bool have_packet,
4830               tag_type *tags, int *vlanp, struct ofbundle **in_bundlep)
4831 {
4832     struct ofport_dpif *in_port;
4833     struct ofbundle *in_bundle;
4834     int vlan;
4835
4836     /* Find the port and bundle for the received packet. */
4837     in_port = get_ofp_port(ofproto, flow->in_port);
4838     *in_bundlep = in_bundle = in_port ? in_port->bundle : NULL;
4839     if (!in_port || !in_bundle) {
4840         /* No interface?  Something fishy... */
4841         if (have_packet) {
4842             /* Odd.  A few possible reasons here:
4843              *
4844              * - We deleted a port but there are still a few packets queued up
4845              *   from it.
4846              *
4847              * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
4848              *   we don't know about.
4849              *
4850              * - Packet arrived on the local port but the local port is not
4851              *   part of a bundle.
4852              */
4853             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4854
4855             VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
4856                          "port %"PRIu16,
4857                          ofproto->up.name, flow->in_port);
4858         }
4859         *vlanp = -1;
4860         return false;
4861     }
4862     *vlanp = vlan = flow_get_vlan(ofproto, flow, in_bundle, have_packet);
4863     if (vlan < 0) {
4864         return false;
4865     }
4866
4867     /* Drop frames for reserved multicast addresses only if forward_bpdu
4868      * option is absent. */
4869     if (eth_addr_is_reserved(flow->dl_dst) && !ofproto->up.forward_bpdu) {
4870         return false;
4871     }
4872
4873     /* Drop frames on bundles reserved for mirroring. */
4874     if (in_bundle->mirror_out) {
4875         if (have_packet) {
4876             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4877             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
4878                          "%s, which is reserved exclusively for mirroring",
4879                          ofproto->up.name, in_bundle->name);
4880         }
4881         return false;
4882     }
4883
4884     if (in_bundle->bond) {
4885         struct mac_entry *mac;
4886
4887         switch (bond_check_admissibility(in_bundle->bond, in_port,
4888                                          flow->dl_dst, tags)) {
4889         case BV_ACCEPT:
4890             break;
4891
4892         case BV_DROP:
4893             return false;
4894
4895         case BV_DROP_IF_MOVED:
4896             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
4897             if (mac && mac->port.p != in_bundle &&
4898                 (!is_gratuitous_arp(flow)
4899                  || mac_entry_is_grat_arp_locked(mac))) {
4900                 return false;
4901             }
4902             break;
4903         }
4904     }
4905
4906     return true;
4907 }
4908
4909 static void
4910 xlate_normal(struct action_xlate_ctx *ctx)
4911 {
4912     struct ofbundle *in_bundle;
4913     struct ofbundle *out_bundle;
4914     struct mac_entry *mac;
4915     int vlan;
4916
4917     ctx->has_normal = true;
4918
4919     /* Check whether we should drop packets in this flow. */
4920     if (!is_admissible(ctx->ofproto, &ctx->flow, ctx->packet != NULL,
4921                        &ctx->tags, &vlan, &in_bundle)) {
4922         out_bundle = NULL;
4923         goto done;
4924     }
4925
4926     /* Learn source MAC. */
4927     if (ctx->may_learn) {
4928         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
4929     }
4930
4931     /* Determine output bundle. */
4932     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
4933                               &ctx->tags);
4934     if (mac) {
4935         out_bundle = mac->port.p;
4936     } else if (!ctx->packet && !eth_addr_is_multicast(ctx->flow.dl_dst)) {
4937         /* If we are revalidating but don't have a learning entry then eject
4938          * the flow.  Installing a flow that floods packets opens up a window
4939          * of time where we could learn from a packet reflected on a bond and
4940          * blackhole packets before the learning table is updated to reflect
4941          * the correct port. */
4942         ctx->may_set_up_flow = false;
4943         return;
4944     } else {
4945         out_bundle = OFBUNDLE_FLOOD;
4946     }
4947
4948     /* Don't send packets out their input bundles. */
4949     if (in_bundle == out_bundle) {
4950         out_bundle = NULL;
4951     }
4952
4953 done:
4954     if (in_bundle) {
4955         compose_actions(ctx, vlan, in_bundle, out_bundle);
4956     }
4957 }
4958 \f
4959 /* Optimized flow revalidation.
4960  *
4961  * It's a difficult problem, in general, to tell which facets need to have
4962  * their actions recalculated whenever the OpenFlow flow table changes.  We
4963  * don't try to solve that general problem: for most kinds of OpenFlow flow
4964  * table changes, we recalculate the actions for every facet.  This is
4965  * relatively expensive, but it's good enough if the OpenFlow flow table
4966  * doesn't change very often.
4967  *
4968  * However, we can expect one particular kind of OpenFlow flow table change to
4969  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
4970  * of CPU on revalidating every facet whenever MAC learning modifies the flow
4971  * table, we add a special case that applies to flow tables in which every rule
4972  * has the same form (that is, the same wildcards), except that the table is
4973  * also allowed to have a single "catch-all" flow that matches all packets.  We
4974  * optimize this case by tagging all of the facets that resubmit into the table
4975  * and invalidating the same tag whenever a flow changes in that table.  The
4976  * end result is that we revalidate just the facets that need it (and sometimes
4977  * a few more, but not all of the facets or even all of the facets that
4978  * resubmit to the table modified by MAC learning). */
4979
4980 /* Calculates the tag to use for 'flow' and wildcards 'wc' when it is inserted
4981  * into an OpenFlow table with the given 'basis'. */
4982 static uint32_t
4983 rule_calculate_tag(const struct flow *flow, const struct flow_wildcards *wc,
4984                    uint32_t secret)
4985 {
4986     if (flow_wildcards_is_catchall(wc)) {
4987         return 0;
4988     } else {
4989         struct flow tag_flow = *flow;
4990         flow_zero_wildcards(&tag_flow, wc);
4991         return tag_create_deterministic(flow_hash(&tag_flow, secret));
4992     }
4993 }
4994
4995 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
4996  * taggability of that table.
4997  *
4998  * This function must be called after *each* change to a flow table.  If you
4999  * skip calling it on some changes then the pointer comparisons at the end can
5000  * be invalid if you get unlucky.  For example, if a flow removal causes a
5001  * cls_table to be destroyed and then a flow insertion causes a cls_table with
5002  * different wildcards to be created with the same address, then this function
5003  * will incorrectly skip revalidation. */
5004 static void
5005 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
5006 {
5007     struct table_dpif *table = &ofproto->tables[table_id];
5008     const struct classifier *cls = &ofproto->up.tables[table_id];
5009     struct cls_table *catchall, *other;
5010     struct cls_table *t;
5011
5012     catchall = other = NULL;
5013
5014     switch (hmap_count(&cls->tables)) {
5015     case 0:
5016         /* We could tag this OpenFlow table but it would make the logic a
5017          * little harder and it's a corner case that doesn't seem worth it
5018          * yet. */
5019         break;
5020
5021     case 1:
5022     case 2:
5023         HMAP_FOR_EACH (t, hmap_node, &cls->tables) {
5024             if (cls_table_is_catchall(t)) {
5025                 catchall = t;
5026             } else if (!other) {
5027                 other = t;
5028             } else {
5029                 /* Indicate that we can't tag this by setting both tables to
5030                  * NULL.  (We know that 'catchall' is already NULL.) */
5031                 other = NULL;
5032             }
5033         }
5034         break;
5035
5036     default:
5037         /* Can't tag this table. */
5038         break;
5039     }
5040
5041     if (table->catchall_table != catchall || table->other_table != other) {
5042         table->catchall_table = catchall;
5043         table->other_table = other;
5044         ofproto->need_revalidate = true;
5045     }
5046 }
5047
5048 /* Given 'rule' that has changed in some way (either it is a rule being
5049  * inserted, a rule being deleted, or a rule whose actions are being
5050  * modified), marks facets for revalidation to ensure that packets will be
5051  * forwarded correctly according to the new state of the flow table.
5052  *
5053  * This function must be called after *each* change to a flow table.  See
5054  * the comment on table_update_taggable() for more information. */
5055 static void
5056 rule_invalidate(const struct rule_dpif *rule)
5057 {
5058     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5059
5060     table_update_taggable(ofproto, rule->up.table_id);
5061
5062     if (!ofproto->need_revalidate) {
5063         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
5064
5065         if (table->other_table && rule->tag) {
5066             tag_set_add(&ofproto->revalidate_set, rule->tag);
5067         } else {
5068             ofproto->need_revalidate = true;
5069         }
5070     }
5071 }
5072 \f
5073 static bool
5074 set_frag_handling(struct ofproto *ofproto_,
5075                   enum ofp_config_flags frag_handling)
5076 {
5077     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5078
5079     if (frag_handling != OFPC_FRAG_REASM) {
5080         ofproto->need_revalidate = true;
5081         return true;
5082     } else {
5083         return false;
5084     }
5085 }
5086
5087 static int
5088 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
5089            const struct flow *flow,
5090            const union ofp_action *ofp_actions, size_t n_ofp_actions)
5091 {
5092     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5093     int error;
5094
5095     error = validate_actions(ofp_actions, n_ofp_actions, flow,
5096                              ofproto->max_ports);
5097     if (!error) {
5098         struct odputil_keybuf keybuf;
5099         struct action_xlate_ctx ctx;
5100         struct ofpbuf *odp_actions;
5101         struct ofpbuf key;
5102
5103         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5104         odp_flow_key_from_flow(&key, flow);
5105
5106         action_xlate_ctx_init(&ctx, ofproto, flow, packet);
5107         odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
5108         dpif_execute(ofproto->dpif, key.data, key.size,
5109                      odp_actions->data, odp_actions->size, packet);
5110         ofpbuf_delete(odp_actions);
5111     }
5112     return error;
5113 }
5114
5115 static void
5116 get_netflow_ids(const struct ofproto *ofproto_,
5117                 uint8_t *engine_type, uint8_t *engine_id)
5118 {
5119     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5120
5121     dpif_get_netflow_ids(ofproto->dpif, engine_type, engine_id);
5122 }
5123 \f
5124 static struct ofproto_dpif *
5125 ofproto_dpif_lookup(const char *name)
5126 {
5127     struct ofproto *ofproto = ofproto_lookup(name);
5128     return (ofproto && ofproto->ofproto_class == &ofproto_dpif_class
5129             ? ofproto_dpif_cast(ofproto)
5130             : NULL);
5131 }
5132
5133 static void
5134 ofproto_unixctl_fdb_show(struct unixctl_conn *conn,
5135                          const char *args, void *aux OVS_UNUSED)
5136 {
5137     struct ds ds = DS_EMPTY_INITIALIZER;
5138     const struct ofproto_dpif *ofproto;
5139     const struct mac_entry *e;
5140
5141     ofproto = ofproto_dpif_lookup(args);
5142     if (!ofproto) {
5143         unixctl_command_reply(conn, 501, "no such bridge");
5144         return;
5145     }
5146
5147     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
5148     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
5149         struct ofbundle *bundle = e->port.p;
5150         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
5151                       ofbundle_get_a_port(bundle)->odp_port,
5152                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
5153     }
5154     unixctl_command_reply(conn, 200, ds_cstr(&ds));
5155     ds_destroy(&ds);
5156 }
5157
5158 struct ofproto_trace {
5159     struct action_xlate_ctx ctx;
5160     struct flow flow;
5161     struct ds *result;
5162 };
5163
5164 static void
5165 trace_format_rule(struct ds *result, uint8_t table_id, int level,
5166                   const struct rule_dpif *rule)
5167 {
5168     ds_put_char_multiple(result, '\t', level);
5169     if (!rule) {
5170         ds_put_cstr(result, "No match\n");
5171         return;
5172     }
5173
5174     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
5175                   table_id, ntohll(rule->up.flow_cookie));
5176     cls_rule_format(&rule->up.cr, result);
5177     ds_put_char(result, '\n');
5178
5179     ds_put_char_multiple(result, '\t', level);
5180     ds_put_cstr(result, "OpenFlow ");
5181     ofp_print_actions(result, rule->up.actions, rule->up.n_actions);
5182     ds_put_char(result, '\n');
5183 }
5184
5185 static void
5186 trace_format_flow(struct ds *result, int level, const char *title,
5187                  struct ofproto_trace *trace)
5188 {
5189     ds_put_char_multiple(result, '\t', level);
5190     ds_put_format(result, "%s: ", title);
5191     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
5192         ds_put_cstr(result, "unchanged");
5193     } else {
5194         flow_format(result, &trace->ctx.flow);
5195         trace->flow = trace->ctx.flow;
5196     }
5197     ds_put_char(result, '\n');
5198 }
5199
5200 static void
5201 trace_format_regs(struct ds *result, int level, const char *title,
5202                   struct ofproto_trace *trace)
5203 {
5204     size_t i;
5205
5206     ds_put_char_multiple(result, '\t', level);
5207     ds_put_format(result, "%s:", title);
5208     for (i = 0; i < FLOW_N_REGS; i++) {
5209         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
5210     }
5211     ds_put_char(result, '\n');
5212 }
5213
5214 static void
5215 trace_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
5216 {
5217     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5218     struct ds *result = trace->result;
5219
5220     ds_put_char(result, '\n');
5221     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5222     trace_format_regs(result, ctx->recurse + 1, "Resubmitted regs", trace);
5223     trace_format_rule(result, ctx->table_id, ctx->recurse + 1, rule);
5224 }
5225
5226 static void
5227 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5228                       void *aux OVS_UNUSED)
5229 {
5230     char *dpname, *arg1, *arg2, *arg3;
5231     char *args = xstrdup(args_);
5232     char *save_ptr = NULL;
5233     struct ofproto_dpif *ofproto;
5234     struct ofpbuf odp_key;
5235     struct ofpbuf *packet;
5236     struct rule_dpif *rule;
5237     struct ds result;
5238     struct flow flow;
5239     char *s;
5240
5241     packet = NULL;
5242     ofpbuf_init(&odp_key, 0);
5243     ds_init(&result);
5244
5245     dpname = strtok_r(args, " ", &save_ptr);
5246     arg1 = strtok_r(NULL, " ", &save_ptr);
5247     arg2 = strtok_r(NULL, " ", &save_ptr);
5248     arg3 = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5249     if (dpname && arg1 && (!arg2 || !strcmp(arg2, "-generate")) && !arg3) {
5250         /* ofproto/trace dpname flow [-generate] */
5251         int error;
5252
5253         /* Convert string to datapath key. */
5254         ofpbuf_init(&odp_key, 0);
5255         error = odp_flow_key_from_string(arg1, &odp_key);
5256         if (error) {
5257             unixctl_command_reply(conn, 501, "Bad flow syntax");
5258             goto exit;
5259         }
5260
5261         /* Convert odp_key to flow. */
5262         error = odp_flow_key_to_flow(odp_key.data, odp_key.size, &flow);
5263         if (error) {
5264             unixctl_command_reply(conn, 501, "Invalid flow");
5265             goto exit;
5266         }
5267
5268         /* Generate a packet, if requested. */
5269         if (arg2) {
5270             packet = ofpbuf_new(0);
5271             flow_compose(packet, &flow);
5272         }
5273     } else if (dpname && arg1 && arg2 && arg3) {
5274         /* ofproto/trace dpname tun_id in_port packet */
5275         uint16_t in_port;
5276         ovs_be64 tun_id;
5277
5278         tun_id = htonll(strtoull(arg1, NULL, 0));
5279         in_port = ofp_port_to_odp_port(atoi(arg2));
5280
5281         packet = ofpbuf_new(strlen(args) / 2);
5282         arg3 = ofpbuf_put_hex(packet, arg3, NULL);
5283         arg3 += strspn(arg3, " ");
5284         if (*arg3 != '\0') {
5285             unixctl_command_reply(conn, 501, "Trailing garbage in command");
5286             goto exit;
5287         }
5288         if (packet->size < ETH_HEADER_LEN) {
5289             unixctl_command_reply(conn, 501,
5290                                   "Packet data too short for Ethernet");
5291             goto exit;
5292         }
5293
5294         ds_put_cstr(&result, "Packet: ");
5295         s = ofp_packet_to_string(packet->data, packet->size, packet->size);
5296         ds_put_cstr(&result, s);
5297         free(s);
5298
5299         flow_extract(packet, tun_id, in_port, &flow);
5300     } else {
5301         unixctl_command_reply(conn, 501, "Bad command syntax");
5302         goto exit;
5303     }
5304
5305     ofproto = ofproto_dpif_lookup(dpname);
5306     if (!ofproto) {
5307         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5308                               "for help)");
5309         goto exit;
5310     }
5311
5312     ds_put_cstr(&result, "Flow: ");
5313     flow_format(&result, &flow);
5314     ds_put_char(&result, '\n');
5315
5316     rule = rule_dpif_lookup(ofproto, &flow, 0);
5317     trace_format_rule(&result, 0, 0, rule);
5318     if (rule) {
5319         struct ofproto_trace trace;
5320         struct ofpbuf *odp_actions;
5321
5322         trace.result = &result;
5323         trace.flow = flow;
5324         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, packet);
5325         trace.ctx.resubmit_hook = trace_resubmit;
5326         odp_actions = xlate_actions(&trace.ctx,
5327                                     rule->up.actions, rule->up.n_actions);
5328
5329         ds_put_char(&result, '\n');
5330         trace_format_flow(&result, 0, "Final flow", &trace);
5331         ds_put_cstr(&result, "Datapath actions: ");
5332         format_odp_actions(&result, odp_actions->data, odp_actions->size);
5333         ofpbuf_delete(odp_actions);
5334
5335         if (!trace.ctx.may_set_up_flow) {
5336             if (packet) {
5337                 ds_put_cstr(&result, "\nThis flow is not cachable.");
5338             } else {
5339                 ds_put_cstr(&result, "\nThe datapath actions are incomplete--"
5340                             "for complete actions, please supply a packet.");
5341             }
5342         }
5343     }
5344
5345     unixctl_command_reply(conn, 200, ds_cstr(&result));
5346
5347 exit:
5348     ds_destroy(&result);
5349     ofpbuf_delete(packet);
5350     ofpbuf_uninit(&odp_key);
5351     free(args);
5352 }
5353
5354 static void
5355 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED,
5356                   const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
5357 {
5358     clogged = true;
5359     unixctl_command_reply(conn, 200, NULL);
5360 }
5361
5362 static void
5363 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED,
5364                     const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
5365 {
5366     clogged = false;
5367     unixctl_command_reply(conn, 200, NULL);
5368 }
5369
5370 static void
5371 ofproto_dpif_unixctl_init(void)
5372 {
5373     static bool registered;
5374     if (registered) {
5375         return;
5376     }
5377     registered = true;
5378
5379     unixctl_command_register("ofproto/trace",
5380                       "bridge {tun_id in_port packet | odp_flow [-generate]}",
5381                       ofproto_unixctl_trace, NULL);
5382     unixctl_command_register("fdb/show", "bridge", ofproto_unixctl_fdb_show,
5383                              NULL); 
5384     unixctl_command_register("ofproto/clog", "", ofproto_dpif_clog, NULL);
5385     unixctl_command_register("ofproto/unclog", "", ofproto_dpif_unclog, NULL);
5386 }
5387 \f
5388 const struct ofproto_class ofproto_dpif_class = {
5389     enumerate_types,
5390     enumerate_names,
5391     del,
5392     alloc,
5393     construct,
5394     destruct,
5395     dealloc,
5396     run,
5397     wait,
5398     flush,
5399     get_features,
5400     get_tables,
5401     port_alloc,
5402     port_construct,
5403     port_destruct,
5404     port_dealloc,
5405     port_modified,
5406     port_reconfigured,
5407     port_query_by_name,
5408     port_add,
5409     port_del,
5410     port_dump_start,
5411     port_dump_next,
5412     port_dump_done,
5413     port_poll,
5414     port_poll_wait,
5415     port_is_lacp_current,
5416     NULL,                       /* rule_choose_table */
5417     rule_alloc,
5418     rule_construct,
5419     rule_destruct,
5420     rule_dealloc,
5421     rule_get_stats,
5422     rule_execute,
5423     rule_modify_actions,
5424     set_frag_handling,
5425     packet_out,
5426     set_netflow,
5427     get_netflow_ids,
5428     set_sflow,
5429     set_cfm,
5430     get_cfm_fault,
5431     get_cfm_remote_mpids,
5432     set_stp,
5433     get_stp_status,
5434     set_stp_port,
5435     get_stp_port_status,
5436     bundle_set,
5437     bundle_remove,
5438     mirror_set,
5439     set_flood_vlans,
5440     is_mirror_output_bundle,
5441     forward_bpdu_changed,
5442 };