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