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