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