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