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