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