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