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