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