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