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