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