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