2d42c83b2762987aad5ed447f0c2ae778b569ba4
[cascardo/ovs.git] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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-dpif.h"
20 #include "ofproto/ofproto-provider.h"
21
22 #include <errno.h>
23
24 #include "bfd.h"
25 #include "bond.h"
26 #include "bundle.h"
27 #include "byte-order.h"
28 #include "connmgr.h"
29 #include "coverage.h"
30 #include "cfm.h"
31 #include "dpif.h"
32 #include "dynamic-string.h"
33 #include "fail-open.h"
34 #include "hmapx.h"
35 #include "lacp.h"
36 #include "learn.h"
37 #include "mac-learning.h"
38 #include "meta-flow.h"
39 #include "multipath.h"
40 #include "netdev-vport.h"
41 #include "netdev.h"
42 #include "netlink.h"
43 #include "nx-match.h"
44 #include "odp-util.h"
45 #include "odp-execute.h"
46 #include "ofp-util.h"
47 #include "ofpbuf.h"
48 #include "ofp-actions.h"
49 #include "ofp-parse.h"
50 #include "ofp-print.h"
51 #include "ofproto-dpif-governor.h"
52 #include "ofproto-dpif-ipfix.h"
53 #include "ofproto-dpif-sflow.h"
54 #include "ofproto-dpif-xlate.h"
55 #include "poll-loop.h"
56 #include "simap.h"
57 #include "smap.h"
58 #include "timer.h"
59 #include "tunnel.h"
60 #include "unaligned.h"
61 #include "unixctl.h"
62 #include "vlan-bitmap.h"
63 #include "vlog.h"
64
65 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
66
67 COVERAGE_DEFINE(ofproto_dpif_expired);
68 COVERAGE_DEFINE(facet_changed_rule);
69 COVERAGE_DEFINE(facet_revalidate);
70 COVERAGE_DEFINE(facet_unexpected);
71 COVERAGE_DEFINE(facet_suppress);
72 COVERAGE_DEFINE(subfacet_install_fail);
73
74 struct flow_miss;
75 struct facet;
76
77 static struct rule_dpif *rule_dpif_lookup(struct ofproto_dpif *,
78                                           const struct flow *,
79                                           struct flow_wildcards *wc);
80
81 static void rule_get_stats(struct rule *, uint64_t *packets, uint64_t *bytes);
82 static void rule_invalidate(const struct rule_dpif *);
83
84 static void mirror_destroy(struct ofmirror *);
85 static void update_mirror_stats(struct ofproto_dpif *ofproto,
86                                 mirror_mask_t mirrors,
87                                 uint64_t packets, uint64_t bytes);
88
89 static void bundle_remove(struct ofport *);
90 static void bundle_update(struct ofbundle *);
91 static void bundle_destroy(struct ofbundle *);
92 static void bundle_del_port(struct ofport_dpif *);
93 static void bundle_run(struct ofbundle *);
94 static void bundle_wait(struct ofbundle *);
95
96 static void stp_run(struct ofproto_dpif *ofproto);
97 static void stp_wait(struct ofproto_dpif *ofproto);
98 static int set_stp_port(struct ofport *,
99                         const struct ofproto_port_stp_settings *);
100
101 static void compose_slow_path(const struct ofproto_dpif *, const struct flow *,
102                               enum slow_path_reason,
103                               uint64_t *stub, size_t stub_size,
104                               const struct nlattr **actionsp,
105                               size_t *actions_lenp);
106
107 /* A subfacet (see "struct subfacet" below) has three possible installation
108  * states:
109  *
110  *   - SF_NOT_INSTALLED: Not installed in the datapath.  This will only be the
111  *     case just after the subfacet is created, just before the subfacet is
112  *     destroyed, or if the datapath returns an error when we try to install a
113  *     subfacet.
114  *
115  *   - SF_FAST_PATH: The subfacet's actions are installed in the datapath.
116  *
117  *   - SF_SLOW_PATH: An action that sends every packet for the subfacet through
118  *     ofproto_dpif is installed in the datapath.
119  */
120 enum subfacet_path {
121     SF_NOT_INSTALLED,           /* No datapath flow for this subfacet. */
122     SF_FAST_PATH,               /* Full actions are installed. */
123     SF_SLOW_PATH,               /* Send-to-userspace action is installed. */
124 };
125
126 /* A dpif flow and actions associated with a facet.
127  *
128  * See also the large comment on struct facet. */
129 struct subfacet {
130     /* Owners. */
131     struct hmap_node hmap_node; /* In struct ofproto_dpif 'subfacets' list. */
132     struct list list_node;      /* In struct facet's 'facets' list. */
133     struct facet *facet;        /* Owning facet. */
134     struct dpif_backer *backer; /* Owning backer. */
135
136     enum odp_key_fitness key_fitness;
137     struct nlattr *key;
138     int key_len;
139
140     long long int used;         /* Time last used; time created if not used. */
141     long long int created;      /* Time created. */
142
143     uint64_t dp_packet_count;   /* Last known packet count in the datapath. */
144     uint64_t dp_byte_count;     /* Last known byte count in the datapath. */
145
146     enum subfacet_path path;    /* Installed in datapath? */
147 };
148
149 #define SUBFACET_DESTROY_MAX_BATCH 50
150
151 static struct subfacet *subfacet_create(struct facet *, struct flow_miss *miss,
152                                         long long int now);
153 static struct subfacet *subfacet_find(struct dpif_backer *,
154                                       const struct nlattr *key, size_t key_len,
155                                       uint32_t key_hash);
156 static void subfacet_destroy(struct subfacet *);
157 static void subfacet_destroy__(struct subfacet *);
158 static void subfacet_destroy_batch(struct dpif_backer *,
159                                    struct subfacet **, int n);
160 static void subfacet_reset_dp_stats(struct subfacet *,
161                                     struct dpif_flow_stats *);
162 static void subfacet_update_stats(struct subfacet *,
163                                   const struct dpif_flow_stats *);
164 static int subfacet_install(struct subfacet *,
165                             const struct ofpbuf *odp_actions,
166                             struct dpif_flow_stats *);
167 static void subfacet_uninstall(struct subfacet *);
168
169 /* A unique, non-overlapping instantiation of an OpenFlow flow.
170  *
171  * A facet associates a "struct flow", which represents the Open vSwitch
172  * userspace idea of an exact-match flow, with one or more subfacets.
173  * While the facet is created based on an exact-match flow, it is stored
174  * within the ofproto based on the wildcards that could be expressed
175  * based on the flow table and other configuration.  (See the 'wc'
176  * description in "struct xlate_out" for more details.)
177  *
178  * Each subfacet tracks the datapath's idea of the flow equivalent to
179  * the facet.  When the kernel module (or other dpif implementation) and
180  * Open vSwitch userspace agree on the definition of a flow key, there
181  * is exactly one subfacet per facet.  If the dpif implementation
182  * supports more-specific flow matching than userspace, however, a facet
183  * can have more than one subfacet.  Examples include the dpif
184  * implementation not supporting the same wildcards as userspace or some
185  * distinction in flow that userspace simply doesn't understand.
186  *
187  * Flow expiration works in terms of subfacets, so a facet must have at
188  * least one subfacet or it will never expire, leaking memory. */
189 struct facet {
190     /* Owners. */
191     struct hmap_node hmap_node;  /* In owning ofproto's 'facets' hmap. */
192     struct list list_node;       /* In owning rule's 'facets' list. */
193     struct rule_dpif *rule;      /* Owning rule. */
194
195     /* Owned data. */
196     struct list subfacets;
197     long long int used;         /* Time last used; time created if not used. */
198
199     /* Key. */
200     struct flow flow;           /* Flow of the creating subfacet. */
201     struct cls_rule cr;         /* In 'ofproto_dpif's facets classifier. */
202
203     /* These statistics:
204      *
205      *   - Do include packets and bytes sent "by hand", e.g. with
206      *     dpif_execute().
207      *
208      *   - Do include packets and bytes that were obtained from the datapath
209      *     when a subfacet's statistics were reset (e.g. dpif_flow_put() with
210      *     DPIF_FP_ZERO_STATS).
211      *
212      *   - Do not include packets or bytes that can be obtained from the
213      *     datapath for any existing subfacet.
214      */
215     uint64_t packet_count;       /* Number of packets received. */
216     uint64_t byte_count;         /* Number of bytes received. */
217
218     /* Resubmit statistics. */
219     uint64_t prev_packet_count;  /* Number of packets from last stats push. */
220     uint64_t prev_byte_count;    /* Number of bytes from last stats push. */
221     long long int prev_used;     /* Used time from last stats push. */
222
223     /* Accounting. */
224     uint64_t accounted_bytes;    /* Bytes processed by facet_account(). */
225     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
226     uint8_t tcp_flags;           /* TCP flags seen for this 'rule'. */
227
228     struct xlate_out xout;
229
230     /* Storage for a single subfacet, to reduce malloc() time and space
231      * overhead.  (A facet always has at least one subfacet and in the common
232      * case has exactly one subfacet.  However, 'one_subfacet' may not
233      * always be valid, since it could have been removed after newer
234      * subfacets were pushed onto the 'subfacets' list.) */
235     struct subfacet one_subfacet;
236
237     long long int learn_rl;      /* Rate limiter for facet_learn(). */
238 };
239
240 static struct facet *facet_create(const struct flow_miss *, struct rule_dpif *,
241                                   struct xlate_out *,
242                                   struct dpif_flow_stats *);
243 static void facet_remove(struct facet *);
244 static void facet_free(struct facet *);
245
246 static struct facet *facet_find(struct ofproto_dpif *, const struct flow *);
247 static struct facet *facet_lookup_valid(struct ofproto_dpif *,
248                                         const struct flow *);
249 static bool facet_revalidate(struct facet *);
250 static bool facet_check_consistency(struct facet *);
251
252 static void facet_flush_stats(struct facet *);
253
254 static void facet_reset_counters(struct facet *);
255 static void facet_push_stats(struct facet *, bool may_learn);
256 static void facet_learn(struct facet *);
257 static void facet_account(struct facet *);
258 static void push_all_stats(void);
259
260 static bool facet_is_controller_flow(struct facet *);
261
262 /* Node in 'ofport_dpif''s 'priorities' map.  Used to maintain a map from
263  * 'priority' (the datapath's term for QoS queue) to the dscp bits which all
264  * traffic egressing the 'ofport' with that priority should be marked with. */
265 struct priority_to_dscp {
266     struct hmap_node hmap_node; /* Node in 'ofport_dpif''s 'priorities' map. */
267     uint32_t priority;          /* Priority of this queue (see struct flow). */
268
269     uint8_t dscp;               /* DSCP bits to mark outgoing traffic with. */
270 };
271
272 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
273  *
274  * This is deprecated.  It is only for compatibility with broken device drivers
275  * in old versions of Linux that do not properly support VLANs when VLAN
276  * devices are not used.  When broken device drivers are no longer in
277  * widespread use, we will delete these interfaces. */
278 struct vlan_splinter {
279     struct hmap_node realdev_vid_node;
280     struct hmap_node vlandev_node;
281     ofp_port_t realdev_ofp_port;
282     ofp_port_t vlandev_ofp_port;
283     int vid;
284 };
285
286 static bool vsp_adjust_flow(const struct ofproto_dpif *, struct flow *);
287 static void vsp_remove(struct ofport_dpif *);
288 static void vsp_add(struct ofport_dpif *, ofp_port_t realdev_ofp_port, int vid);
289
290 static ofp_port_t odp_port_to_ofp_port(const struct ofproto_dpif *,
291                                        odp_port_t odp_port);
292
293 static struct ofport_dpif *
294 ofport_dpif_cast(const struct ofport *ofport)
295 {
296     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
297 }
298
299 static void port_run(struct ofport_dpif *);
300 static void port_run_fast(struct ofport_dpif *);
301 static void port_wait(struct ofport_dpif *);
302 static int set_bfd(struct ofport *, const struct smap *);
303 static int set_cfm(struct ofport *, const struct cfm_settings *);
304 static void ofport_clear_priorities(struct ofport_dpif *);
305 static void ofport_update_peer(struct ofport_dpif *);
306 static void run_fast_rl(void);
307
308 struct dpif_completion {
309     struct list list_node;
310     struct ofoperation *op;
311 };
312
313 /* Reasons that we might need to revalidate every facet, and corresponding
314  * coverage counters.
315  *
316  * A value of 0 means that there is no need to revalidate.
317  *
318  * It would be nice to have some cleaner way to integrate with coverage
319  * counters, but with only a few reasons I guess this is good enough for
320  * now. */
321 enum revalidate_reason {
322     REV_RECONFIGURE = 1,       /* Switch configuration changed. */
323     REV_STP,                   /* Spanning tree protocol port status change. */
324     REV_PORT_TOGGLED,          /* Port enabled or disabled by CFM, LACP, ...*/
325     REV_FLOW_TABLE,            /* Flow table changed. */
326     REV_INCONSISTENCY          /* Facet self-check failed. */
327 };
328 COVERAGE_DEFINE(rev_reconfigure);
329 COVERAGE_DEFINE(rev_stp);
330 COVERAGE_DEFINE(rev_port_toggled);
331 COVERAGE_DEFINE(rev_flow_table);
332 COVERAGE_DEFINE(rev_inconsistency);
333
334 /* Drop keys are odp flow keys which have drop flows installed in the kernel.
335  * These are datapath flows which have no associated ofproto, if they did we
336  * would use facets. */
337 struct drop_key {
338     struct hmap_node hmap_node;
339     struct nlattr *key;
340     size_t key_len;
341 };
342
343 struct avg_subfacet_rates {
344     double add_rate;   /* Moving average of new flows created per minute. */
345     double del_rate;   /* Moving average of flows deleted per minute. */
346 };
347
348 /* All datapaths of a given type share a single dpif backer instance. */
349 struct dpif_backer {
350     char *type;
351     int refcount;
352     struct dpif *dpif;
353     struct timer next_expiration;
354     struct hmap odp_to_ofport_map; /* ODP port to ofport mapping. */
355
356     struct simap tnl_backers;      /* Set of dpif ports backing tunnels. */
357
358     /* Facet revalidation flags applying to facets which use this backer. */
359     enum revalidate_reason need_revalidate; /* Revalidate every facet. */
360     struct tag_set revalidate_set; /* Revalidate only matching facets. */
361
362     struct hmap drop_keys; /* Set of dropped odp keys. */
363     bool recv_set_enable; /* Enables or disables receiving packets. */
364
365     struct hmap subfacets;
366     struct governor *governor;
367
368     /* Subfacet statistics.
369      *
370      * These keep track of the total number of subfacets added and deleted and
371      * flow life span.  They are useful for computing the flow rates stats
372      * exposed via "ovs-appctl dpif/show".  The goal is to learn about
373      * traffic patterns in ways that we can use later to improve Open vSwitch
374      * performance in new situations.  */
375     long long int created;           /* Time when it is created. */
376     unsigned max_n_subfacet;         /* Maximum number of flows */
377     unsigned avg_n_subfacet;         /* Average number of flows. */
378     long long int avg_subfacet_life; /* Average life span of subfacets. */
379
380     /* The average number of subfacets... */
381     struct avg_subfacet_rates hourly;   /* ...over the last hour. */
382     struct avg_subfacet_rates daily;    /* ...over the last day. */
383     struct avg_subfacet_rates lifetime; /* ...over the switch lifetime. */
384     long long int last_minute;          /* Last time 'hourly' was updated. */
385
386     /* Number of subfacets added or deleted since 'last_minute'. */
387     unsigned subfacet_add_count;
388     unsigned subfacet_del_count;
389
390     /* Number of subfacets added or deleted from 'created' to 'last_minute.' */
391     unsigned long long int total_subfacet_add_count;
392     unsigned long long int total_subfacet_del_count;
393 };
394
395 /* All existing ofproto_backer instances, indexed by ofproto->up.type. */
396 static struct shash all_dpif_backers = SHASH_INITIALIZER(&all_dpif_backers);
397
398 static void drop_key_clear(struct dpif_backer *);
399 static struct ofport_dpif *
400 odp_port_to_ofport(const struct dpif_backer *, odp_port_t odp_port);
401 static void update_moving_averages(struct dpif_backer *backer);
402
403 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
404  * for debugging the asynchronous flow_mod implementation.) */
405 static bool clogged;
406
407 /* By default, flows in the datapath are wildcarded (megaflows).  They
408  * may be disabled with the "ovs-appctl dpif/disable-megaflows" command. */
409 static bool enable_megaflows = true;
410
411 /* All existing ofproto_dpif instances, indexed by ->up.name. */
412 static struct hmap all_ofproto_dpifs = HMAP_INITIALIZER(&all_ofproto_dpifs);
413
414 static void ofproto_dpif_unixctl_init(void);
415
416 /* Upcalls. */
417 #define FLOW_MISS_MAX_BATCH 50
418 static int handle_upcalls(struct dpif_backer *, unsigned int max_batch);
419
420 /* Flow expiration. */
421 static int expire(struct dpif_backer *);
422
423 /* NetFlow. */
424 static void send_netflow_active_timeouts(struct ofproto_dpif *);
425
426 /* Utilities. */
427 static int send_packet(const struct ofport_dpif *, struct ofpbuf *packet);
428
429 /* Global variables. */
430 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
431
432 /* Initial mappings of port to bridge mappings. */
433 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
434 \f
435 /* Factory functions. */
436
437 static void
438 init(const struct shash *iface_hints)
439 {
440     struct shash_node *node;
441
442     /* Make a local copy, since we don't own 'iface_hints' elements. */
443     SHASH_FOR_EACH(node, iface_hints) {
444         const struct iface_hint *orig_hint = node->data;
445         struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
446
447         new_hint->br_name = xstrdup(orig_hint->br_name);
448         new_hint->br_type = xstrdup(orig_hint->br_type);
449         new_hint->ofp_port = orig_hint->ofp_port;
450
451         shash_add(&init_ofp_ports, node->name, new_hint);
452     }
453 }
454
455 static void
456 enumerate_types(struct sset *types)
457 {
458     dp_enumerate_types(types);
459 }
460
461 static int
462 enumerate_names(const char *type, struct sset *names)
463 {
464     struct ofproto_dpif *ofproto;
465
466     sset_clear(names);
467     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
468         if (strcmp(type, ofproto->up.type)) {
469             continue;
470         }
471         sset_add(names, ofproto->up.name);
472     }
473
474     return 0;
475 }
476
477 static int
478 del(const char *type, const char *name)
479 {
480     struct dpif *dpif;
481     int error;
482
483     error = dpif_open(name, type, &dpif);
484     if (!error) {
485         error = dpif_delete(dpif);
486         dpif_close(dpif);
487     }
488     return error;
489 }
490 \f
491 static const char *
492 port_open_type(const char *datapath_type, const char *port_type)
493 {
494     return dpif_port_open_type(datapath_type, port_type);
495 }
496
497 /* Type functions. */
498
499 static struct ofproto_dpif *
500 lookup_ofproto_dpif_by_port_name(const char *name)
501 {
502     struct ofproto_dpif *ofproto;
503
504     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
505         if (sset_contains(&ofproto->ports, name)) {
506             return ofproto;
507         }
508     }
509
510     return NULL;
511 }
512
513 static int
514 type_run(const char *type)
515 {
516     static long long int push_timer = LLONG_MIN;
517     struct dpif_backer *backer;
518     char *devname;
519     int error;
520
521     backer = shash_find_data(&all_dpif_backers, type);
522     if (!backer) {
523         /* This is not necessarily a problem, since backers are only
524          * created on demand. */
525         return 0;
526     }
527
528     dpif_run(backer->dpif);
529
530     /* The most natural place to push facet statistics is when they're pulled
531      * from the datapath.  However, when there are many flows in the datapath,
532      * this expensive operation can occur so frequently, that it reduces our
533      * ability to quickly set up flows.  To reduce the cost, we push statistics
534      * here instead. */
535     if (time_msec() > push_timer) {
536         push_timer = time_msec() + 2000;
537         push_all_stats();
538     }
539
540     /* If vswitchd started with other_config:flow_restore_wait set as "true",
541      * and the configuration has now changed to "false", enable receiving
542      * packets from the datapath. */
543     if (!backer->recv_set_enable && !ofproto_get_flow_restore_wait()) {
544         backer->recv_set_enable = true;
545
546         error = dpif_recv_set(backer->dpif, backer->recv_set_enable);
547         if (error) {
548             VLOG_ERR("Failed to enable receiving packets in dpif.");
549             return error;
550         }
551         dpif_flow_flush(backer->dpif);
552         backer->need_revalidate = REV_RECONFIGURE;
553     }
554
555     if (backer->need_revalidate
556         || !tag_set_is_empty(&backer->revalidate_set)) {
557         struct tag_set revalidate_set = backer->revalidate_set;
558         bool need_revalidate = backer->need_revalidate;
559         struct ofproto_dpif *ofproto;
560         struct simap_node *node;
561         struct simap tmp_backers;
562
563         /* Handle tunnel garbage collection. */
564         simap_init(&tmp_backers);
565         simap_swap(&backer->tnl_backers, &tmp_backers);
566
567         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
568             struct ofport_dpif *iter;
569
570             if (backer != ofproto->backer) {
571                 continue;
572             }
573
574             HMAP_FOR_EACH (iter, up.hmap_node, &ofproto->up.ports) {
575                 char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
576                 const char *dp_port;
577
578                 if (!iter->is_tunnel) {
579                     continue;
580                 }
581
582                 dp_port = netdev_vport_get_dpif_port(iter->up.netdev,
583                                                      namebuf, sizeof namebuf);
584                 node = simap_find(&tmp_backers, dp_port);
585                 if (node) {
586                     simap_put(&backer->tnl_backers, dp_port, node->data);
587                     simap_delete(&tmp_backers, node);
588                     node = simap_find(&backer->tnl_backers, dp_port);
589                 } else {
590                     node = simap_find(&backer->tnl_backers, dp_port);
591                     if (!node) {
592                         odp_port_t odp_port = ODPP_NONE;
593
594                         if (!dpif_port_add(backer->dpif, iter->up.netdev,
595                                            &odp_port)) {
596                             simap_put(&backer->tnl_backers, dp_port,
597                                       odp_to_u32(odp_port));
598                             node = simap_find(&backer->tnl_backers, dp_port);
599                         }
600                     }
601                 }
602
603                 iter->odp_port = node ? u32_to_odp(node->data) : ODPP_NONE;
604                 if (tnl_port_reconfigure(iter, iter->up.netdev,
605                                          iter->odp_port)) {
606                     backer->need_revalidate = REV_RECONFIGURE;
607                 }
608             }
609         }
610
611         SIMAP_FOR_EACH (node, &tmp_backers) {
612             dpif_port_del(backer->dpif, u32_to_odp(node->data));
613         }
614         simap_destroy(&tmp_backers);
615
616         switch (backer->need_revalidate) {
617         case REV_RECONFIGURE:   COVERAGE_INC(rev_reconfigure);   break;
618         case REV_STP:           COVERAGE_INC(rev_stp);           break;
619         case REV_PORT_TOGGLED:  COVERAGE_INC(rev_port_toggled);  break;
620         case REV_FLOW_TABLE:    COVERAGE_INC(rev_flow_table);    break;
621         case REV_INCONSISTENCY: COVERAGE_INC(rev_inconsistency); break;
622         }
623
624         if (backer->need_revalidate) {
625             /* Clear the drop_keys in case we should now be accepting some
626              * formerly dropped flows. */
627             drop_key_clear(backer);
628         }
629
630         /* Clear the revalidation flags. */
631         tag_set_init(&backer->revalidate_set);
632         backer->need_revalidate = 0;
633
634         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
635             struct facet *facet, *next;
636             struct cls_cursor cursor;
637
638             if (ofproto->backer != backer) {
639                 continue;
640             }
641
642             cls_cursor_init(&cursor, &ofproto->facets, NULL);
643             CLS_CURSOR_FOR_EACH_SAFE (facet, next, cr, &cursor) {
644                 if (need_revalidate
645                     || tag_set_intersects(&revalidate_set, facet->xout.tags)) {
646                     facet_revalidate(facet);
647                     run_fast_rl();
648                 }
649             }
650         }
651     }
652
653     if (!backer->recv_set_enable) {
654         /* Wake up before a max of 1000ms. */
655         timer_set_duration(&backer->next_expiration, 1000);
656     } else if (timer_expired(&backer->next_expiration)) {
657         int delay = expire(backer);
658         timer_set_duration(&backer->next_expiration, delay);
659     }
660
661     /* Check for port changes in the dpif. */
662     while ((error = dpif_port_poll(backer->dpif, &devname)) == 0) {
663         struct ofproto_dpif *ofproto;
664         struct dpif_port port;
665
666         /* Don't report on the datapath's device. */
667         if (!strcmp(devname, dpif_base_name(backer->dpif))) {
668             goto next;
669         }
670
671         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node,
672                        &all_ofproto_dpifs) {
673             if (simap_contains(&ofproto->backer->tnl_backers, devname)) {
674                 goto next;
675             }
676         }
677
678         ofproto = lookup_ofproto_dpif_by_port_name(devname);
679         if (dpif_port_query_by_name(backer->dpif, devname, &port)) {
680             /* The port was removed.  If we know the datapath,
681              * report it through poll_set().  If we don't, it may be
682              * notifying us of a removal we initiated, so ignore it.
683              * If there's a pending ENOBUFS, let it stand, since
684              * everything will be reevaluated. */
685             if (ofproto && ofproto->port_poll_errno != ENOBUFS) {
686                 sset_add(&ofproto->port_poll_set, devname);
687                 ofproto->port_poll_errno = 0;
688             }
689         } else if (!ofproto) {
690             /* The port was added, but we don't know with which
691              * ofproto we should associate it.  Delete it. */
692             dpif_port_del(backer->dpif, port.port_no);
693         }
694         dpif_port_destroy(&port);
695
696     next:
697         free(devname);
698     }
699
700     if (error != EAGAIN) {
701         struct ofproto_dpif *ofproto;
702
703         /* There was some sort of error, so propagate it to all
704          * ofprotos that use this backer. */
705         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node,
706                        &all_ofproto_dpifs) {
707             if (ofproto->backer == backer) {
708                 sset_clear(&ofproto->port_poll_set);
709                 ofproto->port_poll_errno = error;
710             }
711         }
712     }
713
714     if (backer->governor) {
715         size_t n_subfacets;
716
717         governor_run(backer->governor);
718
719         /* If the governor has shrunk to its minimum size and the number of
720          * subfacets has dwindled, then drop the governor entirely.
721          *
722          * For hysteresis, the number of subfacets to drop the governor is
723          * smaller than the number needed to trigger its creation. */
724         n_subfacets = hmap_count(&backer->subfacets);
725         if (n_subfacets * 4 < flow_eviction_threshold
726             && governor_is_idle(backer->governor)) {
727             governor_destroy(backer->governor);
728             backer->governor = NULL;
729         }
730     }
731
732     return 0;
733 }
734
735 static int
736 dpif_backer_run_fast(struct dpif_backer *backer, int max_batch)
737 {
738     unsigned int work;
739
740     /* If recv_set_enable is false, we should not handle upcalls. */
741     if (!backer->recv_set_enable) {
742         return 0;
743     }
744
745     /* Handle one or more batches of upcalls, until there's nothing left to do
746      * or until we do a fixed total amount of work.
747      *
748      * We do work in batches because it can be much cheaper to set up a number
749      * of flows and fire off their patches all at once.  We do multiple batches
750      * because in some cases handling a packet can cause another packet to be
751      * queued almost immediately as part of the return flow.  Both
752      * optimizations can make major improvements on some benchmarks and
753      * presumably for real traffic as well. */
754     work = 0;
755     while (work < max_batch) {
756         int retval = handle_upcalls(backer, max_batch - work);
757         if (retval <= 0) {
758             return -retval;
759         }
760         work += retval;
761     }
762
763     return 0;
764 }
765
766 static int
767 type_run_fast(const char *type)
768 {
769     struct dpif_backer *backer;
770
771     backer = shash_find_data(&all_dpif_backers, type);
772     if (!backer) {
773         /* This is not necessarily a problem, since backers are only
774          * created on demand. */
775         return 0;
776     }
777
778     return dpif_backer_run_fast(backer, FLOW_MISS_MAX_BATCH);
779 }
780
781 static void
782 run_fast_rl(void)
783 {
784     static long long int port_rl = LLONG_MIN;
785     static unsigned int backer_rl = 0;
786
787     if (time_msec() >= port_rl) {
788         struct ofproto_dpif *ofproto;
789         struct ofport_dpif *ofport;
790
791         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
792
793             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
794                 port_run_fast(ofport);
795             }
796         }
797         port_rl = time_msec() + 200;
798     }
799
800     /* XXX: We have to be careful not to do too much work in this function.  If
801      * we call dpif_backer_run_fast() too often, or with too large a batch,
802      * performance improves signifcantly, but at a cost.  It's possible for the
803      * number of flows in the datapath to increase without bound, and for poll
804      * loops to take 10s of seconds.   The correct solution to this problem,
805      * long term, is to separate flow miss handling into it's own thread so it
806      * isn't affected by revalidations, and expirations.  Until then, this is
807      * the best we can do. */
808     if (++backer_rl >= 10) {
809         struct shash_node *node;
810
811         backer_rl = 0;
812         SHASH_FOR_EACH (node, &all_dpif_backers) {
813             dpif_backer_run_fast(node->data, 1);
814         }
815     }
816 }
817
818 static void
819 type_wait(const char *type)
820 {
821     struct dpif_backer *backer;
822
823     backer = shash_find_data(&all_dpif_backers, type);
824     if (!backer) {
825         /* This is not necessarily a problem, since backers are only
826          * created on demand. */
827         return;
828     }
829
830     if (backer->governor) {
831         governor_wait(backer->governor);
832     }
833
834     timer_wait(&backer->next_expiration);
835 }
836 \f
837 /* Basic life-cycle. */
838
839 static int add_internal_flows(struct ofproto_dpif *);
840
841 static struct ofproto *
842 alloc(void)
843 {
844     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
845     return &ofproto->up;
846 }
847
848 static void
849 dealloc(struct ofproto *ofproto_)
850 {
851     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
852     free(ofproto);
853 }
854
855 static void
856 close_dpif_backer(struct dpif_backer *backer)
857 {
858     struct shash_node *node;
859
860     ovs_assert(backer->refcount > 0);
861
862     if (--backer->refcount) {
863         return;
864     }
865
866     drop_key_clear(backer);
867     hmap_destroy(&backer->drop_keys);
868
869     simap_destroy(&backer->tnl_backers);
870     hmap_destroy(&backer->odp_to_ofport_map);
871     node = shash_find(&all_dpif_backers, backer->type);
872     free(backer->type);
873     shash_delete(&all_dpif_backers, node);
874     dpif_close(backer->dpif);
875
876     ovs_assert(hmap_is_empty(&backer->subfacets));
877     hmap_destroy(&backer->subfacets);
878     governor_destroy(backer->governor);
879
880     free(backer);
881 }
882
883 /* Datapath port slated for removal from datapath. */
884 struct odp_garbage {
885     struct list list_node;
886     odp_port_t odp_port;
887 };
888
889 static int
890 open_dpif_backer(const char *type, struct dpif_backer **backerp)
891 {
892     struct dpif_backer *backer;
893     struct dpif_port_dump port_dump;
894     struct dpif_port port;
895     struct shash_node *node;
896     struct list garbage_list;
897     struct odp_garbage *garbage, *next;
898     struct sset names;
899     char *backer_name;
900     const char *name;
901     int error;
902
903     backer = shash_find_data(&all_dpif_backers, type);
904     if (backer) {
905         backer->refcount++;
906         *backerp = backer;
907         return 0;
908     }
909
910     backer_name = xasprintf("ovs-%s", type);
911
912     /* Remove any existing datapaths, since we assume we're the only
913      * userspace controlling the datapath. */
914     sset_init(&names);
915     dp_enumerate_names(type, &names);
916     SSET_FOR_EACH(name, &names) {
917         struct dpif *old_dpif;
918
919         /* Don't remove our backer if it exists. */
920         if (!strcmp(name, backer_name)) {
921             continue;
922         }
923
924         if (dpif_open(name, type, &old_dpif)) {
925             VLOG_WARN("couldn't open old datapath %s to remove it", name);
926         } else {
927             dpif_delete(old_dpif);
928             dpif_close(old_dpif);
929         }
930     }
931     sset_destroy(&names);
932
933     backer = xmalloc(sizeof *backer);
934
935     error = dpif_create_and_open(backer_name, type, &backer->dpif);
936     free(backer_name);
937     if (error) {
938         VLOG_ERR("failed to open datapath of type %s: %s", type,
939                  ovs_strerror(error));
940         free(backer);
941         return error;
942     }
943
944     backer->type = xstrdup(type);
945     backer->governor = NULL;
946     backer->refcount = 1;
947     hmap_init(&backer->odp_to_ofport_map);
948     hmap_init(&backer->drop_keys);
949     hmap_init(&backer->subfacets);
950     timer_set_duration(&backer->next_expiration, 1000);
951     backer->need_revalidate = 0;
952     simap_init(&backer->tnl_backers);
953     tag_set_init(&backer->revalidate_set);
954     backer->recv_set_enable = !ofproto_get_flow_restore_wait();
955     *backerp = backer;
956
957     if (backer->recv_set_enable) {
958         dpif_flow_flush(backer->dpif);
959     }
960
961     /* Loop through the ports already on the datapath and remove any
962      * that we don't need anymore. */
963     list_init(&garbage_list);
964     dpif_port_dump_start(&port_dump, backer->dpif);
965     while (dpif_port_dump_next(&port_dump, &port)) {
966         node = shash_find(&init_ofp_ports, port.name);
967         if (!node && strcmp(port.name, dpif_base_name(backer->dpif))) {
968             garbage = xmalloc(sizeof *garbage);
969             garbage->odp_port = port.port_no;
970             list_push_front(&garbage_list, &garbage->list_node);
971         }
972     }
973     dpif_port_dump_done(&port_dump);
974
975     LIST_FOR_EACH_SAFE (garbage, next, list_node, &garbage_list) {
976         dpif_port_del(backer->dpif, garbage->odp_port);
977         list_remove(&garbage->list_node);
978         free(garbage);
979     }
980
981     shash_add(&all_dpif_backers, type, backer);
982
983     error = dpif_recv_set(backer->dpif, backer->recv_set_enable);
984     if (error) {
985         VLOG_ERR("failed to listen on datapath of type %s: %s",
986                  type, ovs_strerror(error));
987         close_dpif_backer(backer);
988         return error;
989     }
990
991     backer->max_n_subfacet = 0;
992     backer->created = time_msec();
993     backer->last_minute = backer->created;
994     memset(&backer->hourly, 0, sizeof backer->hourly);
995     memset(&backer->daily, 0, sizeof backer->daily);
996     memset(&backer->lifetime, 0, sizeof backer->lifetime);
997     backer->subfacet_add_count = 0;
998     backer->subfacet_del_count = 0;
999     backer->total_subfacet_add_count = 0;
1000     backer->total_subfacet_del_count = 0;
1001     backer->avg_n_subfacet = 0;
1002     backer->avg_subfacet_life = 0;
1003
1004     return error;
1005 }
1006
1007 static int
1008 construct(struct ofproto *ofproto_)
1009 {
1010     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1011     struct shash_node *node, *next;
1012     odp_port_t max_ports;
1013     int error;
1014     int i;
1015
1016     error = open_dpif_backer(ofproto->up.type, &ofproto->backer);
1017     if (error) {
1018         return error;
1019     }
1020
1021     max_ports = dpif_get_max_ports(ofproto->backer->dpif);
1022     ofproto_init_max_ports(ofproto_, u16_to_ofp(MIN(odp_to_u32(max_ports),
1023                                                     ofp_to_u16(OFPP_MAX))));
1024
1025     ofproto->netflow = NULL;
1026     ofproto->sflow = NULL;
1027     ofproto->ipfix = NULL;
1028     ofproto->stp = NULL;
1029     hmap_init(&ofproto->bundles);
1030     ofproto->ml = mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME);
1031     for (i = 0; i < MAX_MIRRORS; i++) {
1032         ofproto->mirrors[i] = NULL;
1033     }
1034     ofproto->has_bonded_bundles = false;
1035
1036     classifier_init(&ofproto->facets);
1037     ofproto->consistency_rl = LLONG_MIN;
1038
1039     for (i = 0; i < N_TABLES; i++) {
1040         struct table_dpif *table = &ofproto->tables[i];
1041
1042         table->catchall_table = NULL;
1043         table->other_table = NULL;
1044         table->basis = random_uint32();
1045     }
1046
1047     list_init(&ofproto->completions);
1048
1049     ofproto_dpif_unixctl_init();
1050
1051     ofproto->has_mirrors = false;
1052     hmap_init(&ofproto->vlandev_map);
1053     hmap_init(&ofproto->realdev_vid_map);
1054
1055     sset_init(&ofproto->ports);
1056     sset_init(&ofproto->ghost_ports);
1057     sset_init(&ofproto->port_poll_set);
1058     ofproto->port_poll_errno = 0;
1059
1060     SHASH_FOR_EACH_SAFE (node, next, &init_ofp_ports) {
1061         struct iface_hint *iface_hint = node->data;
1062
1063         if (!strcmp(iface_hint->br_name, ofproto->up.name)) {
1064             /* Check if the datapath already has this port. */
1065             if (dpif_port_exists(ofproto->backer->dpif, node->name)) {
1066                 sset_add(&ofproto->ports, node->name);
1067             }
1068
1069             free(iface_hint->br_name);
1070             free(iface_hint->br_type);
1071             free(iface_hint);
1072             shash_delete(&init_ofp_ports, node);
1073         }
1074     }
1075
1076     hmap_insert(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node,
1077                 hash_string(ofproto->up.name, 0));
1078     memset(&ofproto->stats, 0, sizeof ofproto->stats);
1079
1080     ofproto_init_tables(ofproto_, N_TABLES);
1081     error = add_internal_flows(ofproto);
1082     ofproto->up.tables[TBL_INTERNAL].flags = OFTABLE_HIDDEN | OFTABLE_READONLY;
1083
1084     ofproto->n_hit = 0;
1085     ofproto->n_missed = 0;
1086
1087     return error;
1088 }
1089
1090 static int
1091 add_internal_flow(struct ofproto_dpif *ofproto, int id,
1092                   const struct ofpbuf *ofpacts, struct rule_dpif **rulep)
1093 {
1094     struct ofputil_flow_mod fm;
1095     int error;
1096
1097     match_init_catchall(&fm.match);
1098     fm.priority = 0;
1099     match_set_reg(&fm.match, 0, id);
1100     fm.new_cookie = htonll(0);
1101     fm.cookie = htonll(0);
1102     fm.cookie_mask = htonll(0);
1103     fm.table_id = TBL_INTERNAL;
1104     fm.command = OFPFC_ADD;
1105     fm.idle_timeout = 0;
1106     fm.hard_timeout = 0;
1107     fm.buffer_id = 0;
1108     fm.out_port = 0;
1109     fm.flags = 0;
1110     fm.ofpacts = ofpacts->data;
1111     fm.ofpacts_len = ofpacts->size;
1112
1113     error = ofproto_flow_mod(&ofproto->up, &fm);
1114     if (error) {
1115         VLOG_ERR_RL(&rl, "failed to add internal flow %d (%s)",
1116                     id, ofperr_to_string(error));
1117         return error;
1118     }
1119
1120     *rulep = rule_dpif_lookup_in_table(ofproto, &fm.match.flow, NULL,
1121                                        TBL_INTERNAL);
1122     ovs_assert(*rulep != NULL);
1123
1124     return 0;
1125 }
1126
1127 static int
1128 add_internal_flows(struct ofproto_dpif *ofproto)
1129 {
1130     struct ofpact_controller *controller;
1131     uint64_t ofpacts_stub[128 / 8];
1132     struct ofpbuf ofpacts;
1133     int error;
1134     int id;
1135
1136     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
1137     id = 1;
1138
1139     controller = ofpact_put_CONTROLLER(&ofpacts);
1140     controller->max_len = UINT16_MAX;
1141     controller->controller_id = 0;
1142     controller->reason = OFPR_NO_MATCH;
1143     ofpact_pad(&ofpacts);
1144
1145     error = add_internal_flow(ofproto, id++, &ofpacts, &ofproto->miss_rule);
1146     if (error) {
1147         return error;
1148     }
1149
1150     ofpbuf_clear(&ofpacts);
1151     error = add_internal_flow(ofproto, id++, &ofpacts,
1152                               &ofproto->no_packet_in_rule);
1153     if (error) {
1154         return error;
1155     }
1156
1157     error = add_internal_flow(ofproto, id++, &ofpacts,
1158                               &ofproto->drop_frags_rule);
1159     return error;
1160 }
1161
1162 static void
1163 complete_operations(struct ofproto_dpif *ofproto)
1164 {
1165     struct dpif_completion *c, *next;
1166
1167     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
1168         ofoperation_complete(c->op, 0);
1169         list_remove(&c->list_node);
1170         free(c);
1171     }
1172 }
1173
1174 static void
1175 destruct(struct ofproto *ofproto_)
1176 {
1177     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1178     struct rule_dpif *rule, *next_rule;
1179     struct oftable *table;
1180     int i;
1181
1182     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1183     hmap_remove(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node);
1184     complete_operations(ofproto);
1185
1186     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
1187         struct cls_cursor cursor;
1188
1189         cls_cursor_init(&cursor, &table->cls, NULL);
1190         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
1191             ofproto_rule_destroy(&rule->up);
1192         }
1193     }
1194
1195     for (i = 0; i < MAX_MIRRORS; i++) {
1196         mirror_destroy(ofproto->mirrors[i]);
1197     }
1198
1199     netflow_destroy(ofproto->netflow);
1200     dpif_sflow_unref(ofproto->sflow);
1201     hmap_destroy(&ofproto->bundles);
1202     mac_learning_unref(ofproto->ml);
1203
1204     classifier_destroy(&ofproto->facets);
1205
1206     hmap_destroy(&ofproto->vlandev_map);
1207     hmap_destroy(&ofproto->realdev_vid_map);
1208
1209     sset_destroy(&ofproto->ports);
1210     sset_destroy(&ofproto->ghost_ports);
1211     sset_destroy(&ofproto->port_poll_set);
1212
1213     close_dpif_backer(ofproto->backer);
1214 }
1215
1216 static int
1217 run_fast(struct ofproto *ofproto_)
1218 {
1219     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1220     struct ofport_dpif *ofport;
1221
1222     /* Do not perform any periodic activity required by 'ofproto' while
1223      * waiting for flow restore to complete. */
1224     if (ofproto_get_flow_restore_wait()) {
1225         return 0;
1226     }
1227
1228     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1229         port_run_fast(ofport);
1230     }
1231
1232     return 0;
1233 }
1234
1235 static int
1236 run(struct ofproto *ofproto_)
1237 {
1238     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1239     struct ofport_dpif *ofport;
1240     struct ofbundle *bundle;
1241     int error;
1242
1243     if (!clogged) {
1244         complete_operations(ofproto);
1245     }
1246
1247     /* Do not perform any periodic activity below required by 'ofproto' while
1248      * waiting for flow restore to complete. */
1249     if (ofproto_get_flow_restore_wait()) {
1250         return 0;
1251     }
1252
1253     error = run_fast(ofproto_);
1254     if (error) {
1255         return error;
1256     }
1257
1258     if (ofproto->netflow) {
1259         if (netflow_run(ofproto->netflow)) {
1260             send_netflow_active_timeouts(ofproto);
1261         }
1262     }
1263     if (ofproto->sflow) {
1264         dpif_sflow_run(ofproto->sflow);
1265     }
1266
1267     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1268         port_run(ofport);
1269     }
1270     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1271         bundle_run(bundle);
1272     }
1273
1274     stp_run(ofproto);
1275     mac_learning_run(ofproto->ml, &ofproto->backer->revalidate_set);
1276
1277     /* Check the consistency of a random facet, to aid debugging. */
1278     if (time_msec() >= ofproto->consistency_rl
1279         && !classifier_is_empty(&ofproto->facets)
1280         && !ofproto->backer->need_revalidate) {
1281         struct cls_table *table;
1282         struct cls_rule *cr;
1283         struct facet *facet;
1284
1285         ofproto->consistency_rl = time_msec() + 250;
1286
1287         table = CONTAINER_OF(hmap_random_node(&ofproto->facets.tables),
1288                              struct cls_table, hmap_node);
1289         cr = CONTAINER_OF(hmap_random_node(&table->rules), struct cls_rule,
1290                           hmap_node);
1291         facet = CONTAINER_OF(cr, struct facet, cr);
1292
1293         if (!tag_set_intersects(&ofproto->backer->revalidate_set,
1294                                 facet->xout.tags)) {
1295             if (!facet_check_consistency(facet)) {
1296                 ofproto->backer->need_revalidate = REV_INCONSISTENCY;
1297             }
1298         }
1299     }
1300
1301     return 0;
1302 }
1303
1304 static void
1305 wait(struct ofproto *ofproto_)
1306 {
1307     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1308     struct ofport_dpif *ofport;
1309     struct ofbundle *bundle;
1310
1311     if (!clogged && !list_is_empty(&ofproto->completions)) {
1312         poll_immediate_wake();
1313     }
1314
1315     if (ofproto_get_flow_restore_wait()) {
1316         return;
1317     }
1318
1319     dpif_wait(ofproto->backer->dpif);
1320     dpif_recv_wait(ofproto->backer->dpif);
1321     if (ofproto->sflow) {
1322         dpif_sflow_wait(ofproto->sflow);
1323     }
1324     if (!tag_set_is_empty(&ofproto->backer->revalidate_set)) {
1325         poll_immediate_wake();
1326     }
1327     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1328         port_wait(ofport);
1329     }
1330     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1331         bundle_wait(bundle);
1332     }
1333     if (ofproto->netflow) {
1334         netflow_wait(ofproto->netflow);
1335     }
1336     mac_learning_wait(ofproto->ml);
1337     stp_wait(ofproto);
1338     if (ofproto->backer->need_revalidate) {
1339         /* Shouldn't happen, but if it does just go around again. */
1340         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1341         poll_immediate_wake();
1342     }
1343 }
1344
1345 static void
1346 get_memory_usage(const struct ofproto *ofproto_, struct simap *usage)
1347 {
1348     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1349     struct cls_cursor cursor;
1350     size_t n_subfacets = 0;
1351     struct facet *facet;
1352
1353     simap_increase(usage, "facets", classifier_count(&ofproto->facets));
1354
1355     cls_cursor_init(&cursor, &ofproto->facets, NULL);
1356     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
1357         n_subfacets += list_size(&facet->subfacets);
1358     }
1359     simap_increase(usage, "subfacets", n_subfacets);
1360 }
1361
1362 static void
1363 flush(struct ofproto *ofproto_)
1364 {
1365     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1366     struct subfacet *subfacet, *next_subfacet;
1367     struct subfacet *batch[SUBFACET_DESTROY_MAX_BATCH];
1368     int n_batch;
1369
1370     n_batch = 0;
1371     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
1372                         &ofproto->backer->subfacets) {
1373         if (ofproto_dpif_cast(subfacet->facet->rule->up.ofproto) != ofproto) {
1374             continue;
1375         }
1376
1377         if (subfacet->path != SF_NOT_INSTALLED) {
1378             batch[n_batch++] = subfacet;
1379             if (n_batch >= SUBFACET_DESTROY_MAX_BATCH) {
1380                 subfacet_destroy_batch(ofproto->backer, batch, n_batch);
1381                 n_batch = 0;
1382             }
1383         } else {
1384             subfacet_destroy(subfacet);
1385         }
1386     }
1387
1388     if (n_batch > 0) {
1389         subfacet_destroy_batch(ofproto->backer, batch, n_batch);
1390     }
1391 }
1392
1393 static void
1394 get_features(struct ofproto *ofproto_ OVS_UNUSED,
1395              bool *arp_match_ip, enum ofputil_action_bitmap *actions)
1396 {
1397     *arp_match_ip = true;
1398     *actions = (OFPUTIL_A_OUTPUT |
1399                 OFPUTIL_A_SET_VLAN_VID |
1400                 OFPUTIL_A_SET_VLAN_PCP |
1401                 OFPUTIL_A_STRIP_VLAN |
1402                 OFPUTIL_A_SET_DL_SRC |
1403                 OFPUTIL_A_SET_DL_DST |
1404                 OFPUTIL_A_SET_NW_SRC |
1405                 OFPUTIL_A_SET_NW_DST |
1406                 OFPUTIL_A_SET_NW_TOS |
1407                 OFPUTIL_A_SET_TP_SRC |
1408                 OFPUTIL_A_SET_TP_DST |
1409                 OFPUTIL_A_ENQUEUE);
1410 }
1411
1412 static void
1413 get_tables(struct ofproto *ofproto_, struct ofp12_table_stats *ots)
1414 {
1415     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1416     struct dpif_dp_stats s;
1417     uint64_t n_miss, n_no_pkt_in, n_bytes, n_dropped_frags;
1418     uint64_t n_lookup;
1419
1420     strcpy(ots->name, "classifier");
1421
1422     dpif_get_dp_stats(ofproto->backer->dpif, &s);
1423     rule_get_stats(&ofproto->miss_rule->up, &n_miss, &n_bytes);
1424     rule_get_stats(&ofproto->no_packet_in_rule->up, &n_no_pkt_in, &n_bytes);
1425     rule_get_stats(&ofproto->drop_frags_rule->up, &n_dropped_frags, &n_bytes);
1426
1427     n_lookup = s.n_hit + s.n_missed - n_dropped_frags;
1428     ots->lookup_count = htonll(n_lookup);
1429     ots->matched_count = htonll(n_lookup - n_miss - n_no_pkt_in);
1430 }
1431
1432 static struct ofport *
1433 port_alloc(void)
1434 {
1435     struct ofport_dpif *port = xmalloc(sizeof *port);
1436     return &port->up;
1437 }
1438
1439 static void
1440 port_dealloc(struct ofport *port_)
1441 {
1442     struct ofport_dpif *port = ofport_dpif_cast(port_);
1443     free(port);
1444 }
1445
1446 static int
1447 port_construct(struct ofport *port_)
1448 {
1449     struct ofport_dpif *port = ofport_dpif_cast(port_);
1450     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1451     const struct netdev *netdev = port->up.netdev;
1452     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1453     struct dpif_port dpif_port;
1454     int error;
1455
1456     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1457     port->bundle = NULL;
1458     port->cfm = NULL;
1459     port->bfd = NULL;
1460     port->tag = tag_create_random();
1461     port->may_enable = true;
1462     port->stp_port = NULL;
1463     port->stp_state = STP_DISABLED;
1464     port->is_tunnel = false;
1465     port->peer = NULL;
1466     hmap_init(&port->priorities);
1467     port->realdev_ofp_port = 0;
1468     port->vlandev_vid = 0;
1469     port->carrier_seq = netdev_get_carrier_resets(netdev);
1470
1471     if (netdev_vport_is_patch(netdev)) {
1472         /* By bailing out here, we don't submit the port to the sFlow module
1473          * to be considered for counter polling export.  This is correct
1474          * because the patch port represents an interface that sFlow considers
1475          * to be "internal" to the switch as a whole, and therefore not an
1476          * candidate for counter polling. */
1477         port->odp_port = ODPP_NONE;
1478         ofport_update_peer(port);
1479         return 0;
1480     }
1481
1482     error = dpif_port_query_by_name(ofproto->backer->dpif,
1483                                     netdev_vport_get_dpif_port(netdev, namebuf,
1484                                                                sizeof namebuf),
1485                                     &dpif_port);
1486     if (error) {
1487         return error;
1488     }
1489
1490     port->odp_port = dpif_port.port_no;
1491
1492     if (netdev_get_tunnel_config(netdev)) {
1493         tnl_port_add(port, port->up.netdev, port->odp_port);
1494         port->is_tunnel = true;
1495     } else {
1496         /* Sanity-check that a mapping doesn't already exist.  This
1497          * shouldn't happen for non-tunnel ports. */
1498         if (odp_port_to_ofp_port(ofproto, port->odp_port) != OFPP_NONE) {
1499             VLOG_ERR("port %s already has an OpenFlow port number",
1500                      dpif_port.name);
1501             dpif_port_destroy(&dpif_port);
1502             return EBUSY;
1503         }
1504
1505         hmap_insert(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node,
1506                     hash_odp_port(port->odp_port));
1507     }
1508     dpif_port_destroy(&dpif_port);
1509
1510     if (ofproto->sflow) {
1511         dpif_sflow_add_port(ofproto->sflow, port_, port->odp_port);
1512     }
1513
1514     return 0;
1515 }
1516
1517 static void
1518 port_destruct(struct ofport *port_)
1519 {
1520     struct ofport_dpif *port = ofport_dpif_cast(port_);
1521     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1522     const char *devname = netdev_get_name(port->up.netdev);
1523     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1524     const char *dp_port_name;
1525
1526     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1527
1528     dp_port_name = netdev_vport_get_dpif_port(port->up.netdev, namebuf,
1529                                               sizeof namebuf);
1530     if (dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
1531         /* The underlying device is still there, so delete it.  This
1532          * happens when the ofproto is being destroyed, since the caller
1533          * assumes that removal of attached ports will happen as part of
1534          * destruction. */
1535         if (!port->is_tunnel) {
1536             dpif_port_del(ofproto->backer->dpif, port->odp_port);
1537         }
1538     }
1539
1540     if (port->peer) {
1541         port->peer->peer = NULL;
1542         port->peer = NULL;
1543     }
1544
1545     if (port->odp_port != ODPP_NONE && !port->is_tunnel) {
1546         hmap_remove(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node);
1547     }
1548
1549     tnl_port_del(port);
1550     sset_find_and_delete(&ofproto->ports, devname);
1551     sset_find_and_delete(&ofproto->ghost_ports, devname);
1552     bundle_remove(port_);
1553     set_cfm(port_, NULL);
1554     set_bfd(port_, NULL);
1555     if (ofproto->sflow) {
1556         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
1557     }
1558
1559     ofport_clear_priorities(port);
1560     hmap_destroy(&port->priorities);
1561 }
1562
1563 static void
1564 port_modified(struct ofport *port_)
1565 {
1566     struct ofport_dpif *port = ofport_dpif_cast(port_);
1567
1568     if (port->bundle && port->bundle->bond) {
1569         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
1570     }
1571
1572     if (port->cfm) {
1573         cfm_set_netdev(port->cfm, port->up.netdev);
1574     }
1575
1576     if (port->is_tunnel && tnl_port_reconfigure(port, port->up.netdev,
1577                                                 port->odp_port)) {
1578         ofproto_dpif_cast(port->up.ofproto)->backer->need_revalidate =
1579             REV_RECONFIGURE;
1580     }
1581
1582     ofport_update_peer(port);
1583 }
1584
1585 static void
1586 port_reconfigured(struct ofport *port_, enum ofputil_port_config old_config)
1587 {
1588     struct ofport_dpif *port = ofport_dpif_cast(port_);
1589     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1590     enum ofputil_port_config changed = old_config ^ port->up.pp.config;
1591
1592     if (changed & (OFPUTIL_PC_NO_RECV | OFPUTIL_PC_NO_RECV_STP |
1593                    OFPUTIL_PC_NO_FWD | OFPUTIL_PC_NO_FLOOD |
1594                    OFPUTIL_PC_NO_PACKET_IN)) {
1595         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1596
1597         if (changed & OFPUTIL_PC_NO_FLOOD && port->bundle) {
1598             bundle_update(port->bundle);
1599         }
1600     }
1601 }
1602
1603 static int
1604 set_sflow(struct ofproto *ofproto_,
1605           const struct ofproto_sflow_options *sflow_options)
1606 {
1607     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1608     struct dpif_sflow *ds = ofproto->sflow;
1609
1610     if (sflow_options) {
1611         if (!ds) {
1612             struct ofport_dpif *ofport;
1613
1614             ds = ofproto->sflow = dpif_sflow_create();
1615             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1616                 dpif_sflow_add_port(ds, &ofport->up, ofport->odp_port);
1617             }
1618             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1619         }
1620         dpif_sflow_set_options(ds, sflow_options);
1621     } else {
1622         if (ds) {
1623             dpif_sflow_unref(ds);
1624             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1625             ofproto->sflow = NULL;
1626         }
1627     }
1628     return 0;
1629 }
1630
1631 static int
1632 set_ipfix(
1633     struct ofproto *ofproto_,
1634     const struct ofproto_ipfix_bridge_exporter_options *bridge_exporter_options,
1635     const struct ofproto_ipfix_flow_exporter_options *flow_exporters_options,
1636     size_t n_flow_exporters_options)
1637 {
1638     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1639     struct dpif_ipfix *di = ofproto->ipfix;
1640
1641     if (bridge_exporter_options || flow_exporters_options) {
1642         if (!di) {
1643             di = ofproto->ipfix = dpif_ipfix_create();
1644         }
1645         dpif_ipfix_set_options(
1646             di, bridge_exporter_options, flow_exporters_options,
1647             n_flow_exporters_options);
1648     } else {
1649         if (di) {
1650             dpif_ipfix_unref(di);
1651             ofproto->ipfix = NULL;
1652         }
1653     }
1654     return 0;
1655 }
1656
1657 static int
1658 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
1659 {
1660     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1661     int error;
1662
1663     if (!s) {
1664         error = 0;
1665     } else {
1666         if (!ofport->cfm) {
1667             struct ofproto_dpif *ofproto;
1668
1669             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1670             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1671             ofport->cfm = cfm_create(ofport->up.netdev);
1672         }
1673
1674         if (cfm_configure(ofport->cfm, s)) {
1675             return 0;
1676         }
1677
1678         error = EINVAL;
1679     }
1680     cfm_unref(ofport->cfm);
1681     ofport->cfm = NULL;
1682     return error;
1683 }
1684
1685 static bool
1686 get_cfm_status(const struct ofport *ofport_,
1687                struct ofproto_cfm_status *status)
1688 {
1689     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1690
1691     if (ofport->cfm) {
1692         status->faults = cfm_get_fault(ofport->cfm);
1693         status->remote_opstate = cfm_get_opup(ofport->cfm);
1694         status->health = cfm_get_health(ofport->cfm);
1695         cfm_get_remote_mpids(ofport->cfm, &status->rmps, &status->n_rmps);
1696         return true;
1697     } else {
1698         return false;
1699     }
1700 }
1701
1702 static int
1703 set_bfd(struct ofport *ofport_, const struct smap *cfg)
1704 {
1705     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
1706     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1707     struct bfd *old;
1708
1709     old = ofport->bfd;
1710     ofport->bfd = bfd_configure(old, netdev_get_name(ofport->up.netdev), cfg);
1711     if (ofport->bfd != old) {
1712         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1713     }
1714
1715     return 0;
1716 }
1717
1718 static int
1719 get_bfd_status(struct ofport *ofport_, struct smap *smap)
1720 {
1721     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1722
1723     if (ofport->bfd) {
1724         bfd_get_status(ofport->bfd, smap);
1725         return 0;
1726     } else {
1727         return ENOENT;
1728     }
1729 }
1730 \f
1731 /* Spanning Tree. */
1732
1733 static void
1734 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
1735 {
1736     struct ofproto_dpif *ofproto = ofproto_;
1737     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
1738     struct ofport_dpif *ofport;
1739
1740     ofport = stp_port_get_aux(sp);
1741     if (!ofport) {
1742         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
1743                      ofproto->up.name, port_num);
1744     } else {
1745         struct eth_header *eth = pkt->l2;
1746
1747         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
1748         if (eth_addr_is_zero(eth->eth_src)) {
1749             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
1750                          "with unknown MAC", ofproto->up.name, port_num);
1751         } else {
1752             send_packet(ofport, pkt);
1753         }
1754     }
1755     ofpbuf_delete(pkt);
1756 }
1757
1758 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
1759 static int
1760 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
1761 {
1762     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1763
1764     /* Only revalidate flows if the configuration changed. */
1765     if (!s != !ofproto->stp) {
1766         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1767     }
1768
1769     if (s) {
1770         if (!ofproto->stp) {
1771             ofproto->stp = stp_create(ofproto_->name, s->system_id,
1772                                       send_bpdu_cb, ofproto);
1773             ofproto->stp_last_tick = time_msec();
1774         }
1775
1776         stp_set_bridge_id(ofproto->stp, s->system_id);
1777         stp_set_bridge_priority(ofproto->stp, s->priority);
1778         stp_set_hello_time(ofproto->stp, s->hello_time);
1779         stp_set_max_age(ofproto->stp, s->max_age);
1780         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
1781     }  else {
1782         struct ofport *ofport;
1783
1784         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
1785             set_stp_port(ofport, NULL);
1786         }
1787
1788         stp_destroy(ofproto->stp);
1789         ofproto->stp = NULL;
1790     }
1791
1792     return 0;
1793 }
1794
1795 static int
1796 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
1797 {
1798     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1799
1800     if (ofproto->stp) {
1801         s->enabled = true;
1802         s->bridge_id = stp_get_bridge_id(ofproto->stp);
1803         s->designated_root = stp_get_designated_root(ofproto->stp);
1804         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
1805     } else {
1806         s->enabled = false;
1807     }
1808
1809     return 0;
1810 }
1811
1812 static void
1813 update_stp_port_state(struct ofport_dpif *ofport)
1814 {
1815     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1816     enum stp_state state;
1817
1818     /* Figure out new state. */
1819     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
1820                              : STP_DISABLED;
1821
1822     /* Update state. */
1823     if (ofport->stp_state != state) {
1824         enum ofputil_port_state of_state;
1825         bool fwd_change;
1826
1827         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
1828                     netdev_get_name(ofport->up.netdev),
1829                     stp_state_name(ofport->stp_state),
1830                     stp_state_name(state));
1831         if (stp_learn_in_state(ofport->stp_state)
1832                 != stp_learn_in_state(state)) {
1833             /* xxx Learning action flows should also be flushed. */
1834             mac_learning_flush(ofproto->ml,
1835                                &ofproto->backer->revalidate_set);
1836         }
1837         fwd_change = stp_forward_in_state(ofport->stp_state)
1838                         != stp_forward_in_state(state);
1839
1840         ofproto->backer->need_revalidate = REV_STP;
1841         ofport->stp_state = state;
1842         ofport->stp_state_entered = time_msec();
1843
1844         if (fwd_change && ofport->bundle) {
1845             bundle_update(ofport->bundle);
1846         }
1847
1848         /* Update the STP state bits in the OpenFlow port description. */
1849         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
1850         of_state |= (state == STP_LISTENING ? OFPUTIL_PS_STP_LISTEN
1851                      : state == STP_LEARNING ? OFPUTIL_PS_STP_LEARN
1852                      : state == STP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
1853                      : state == STP_BLOCKING ?  OFPUTIL_PS_STP_BLOCK
1854                      : 0);
1855         ofproto_port_set_state(&ofport->up, of_state);
1856     }
1857 }
1858
1859 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
1860  * caller is responsible for assigning STP port numbers and ensuring
1861  * there are no duplicates. */
1862 static int
1863 set_stp_port(struct ofport *ofport_,
1864              const struct ofproto_port_stp_settings *s)
1865 {
1866     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1867     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1868     struct stp_port *sp = ofport->stp_port;
1869
1870     if (!s || !s->enable) {
1871         if (sp) {
1872             ofport->stp_port = NULL;
1873             stp_port_disable(sp);
1874             update_stp_port_state(ofport);
1875         }
1876         return 0;
1877     } else if (sp && stp_port_no(sp) != s->port_num
1878             && ofport == stp_port_get_aux(sp)) {
1879         /* The port-id changed, so disable the old one if it's not
1880          * already in use by another port. */
1881         stp_port_disable(sp);
1882     }
1883
1884     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
1885     stp_port_enable(sp);
1886
1887     stp_port_set_aux(sp, ofport);
1888     stp_port_set_priority(sp, s->priority);
1889     stp_port_set_path_cost(sp, s->path_cost);
1890
1891     update_stp_port_state(ofport);
1892
1893     return 0;
1894 }
1895
1896 static int
1897 get_stp_port_status(struct ofport *ofport_,
1898                     struct ofproto_port_stp_status *s)
1899 {
1900     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1901     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1902     struct stp_port *sp = ofport->stp_port;
1903
1904     if (!ofproto->stp || !sp) {
1905         s->enabled = false;
1906         return 0;
1907     }
1908
1909     s->enabled = true;
1910     s->port_id = stp_port_get_id(sp);
1911     s->state = stp_port_get_state(sp);
1912     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
1913     s->role = stp_port_get_role(sp);
1914     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
1915
1916     return 0;
1917 }
1918
1919 static void
1920 stp_run(struct ofproto_dpif *ofproto)
1921 {
1922     if (ofproto->stp) {
1923         long long int now = time_msec();
1924         long long int elapsed = now - ofproto->stp_last_tick;
1925         struct stp_port *sp;
1926
1927         if (elapsed > 0) {
1928             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
1929             ofproto->stp_last_tick = now;
1930         }
1931         while (stp_get_changed_port(ofproto->stp, &sp)) {
1932             struct ofport_dpif *ofport = stp_port_get_aux(sp);
1933
1934             if (ofport) {
1935                 update_stp_port_state(ofport);
1936             }
1937         }
1938
1939         if (stp_check_and_reset_fdb_flush(ofproto->stp)) {
1940             mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
1941         }
1942     }
1943 }
1944
1945 static void
1946 stp_wait(struct ofproto_dpif *ofproto)
1947 {
1948     if (ofproto->stp) {
1949         poll_timer_wait(1000);
1950     }
1951 }
1952
1953 /* Returns true if STP should process 'flow'.  Sets fields in 'wc' that
1954  * were used to make the determination.*/
1955 bool
1956 stp_should_process_flow(const struct flow *flow, struct flow_wildcards *wc)
1957 {
1958     memset(&wc->masks.dl_dst, 0xff, sizeof wc->masks.dl_dst);
1959     return eth_addr_equals(flow->dl_dst, eth_addr_stp);
1960 }
1961
1962 void
1963 stp_process_packet(const struct ofport_dpif *ofport,
1964                    const struct ofpbuf *packet)
1965 {
1966     struct ofpbuf payload = *packet;
1967     struct eth_header *eth = payload.data;
1968     struct stp_port *sp = ofport->stp_port;
1969
1970     /* Sink packets on ports that have STP disabled when the bridge has
1971      * STP enabled. */
1972     if (!sp || stp_port_get_state(sp) == STP_DISABLED) {
1973         return;
1974     }
1975
1976     /* Trim off padding on payload. */
1977     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1978         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
1979     }
1980
1981     if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1982         stp_received_bpdu(sp, payload.data, payload.size);
1983     }
1984 }
1985 \f
1986 int
1987 ofproto_dpif_queue_to_priority(const struct ofproto_dpif *ofproto,
1988                                uint32_t queue_id, uint32_t *priority)
1989 {
1990     return dpif_queue_to_priority(ofproto->backer->dpif, queue_id, priority);
1991 }
1992
1993 static struct priority_to_dscp *
1994 get_priority(const struct ofport_dpif *ofport, uint32_t priority)
1995 {
1996     struct priority_to_dscp *pdscp;
1997     uint32_t hash;
1998
1999     hash = hash_int(priority, 0);
2000     HMAP_FOR_EACH_IN_BUCKET (pdscp, hmap_node, hash, &ofport->priorities) {
2001         if (pdscp->priority == priority) {
2002             return pdscp;
2003         }
2004     }
2005     return NULL;
2006 }
2007
2008 bool
2009 ofproto_dpif_dscp_from_priority(const struct ofport_dpif *ofport,
2010                                 uint32_t priority, uint8_t *dscp)
2011 {
2012     struct priority_to_dscp *pdscp = get_priority(ofport, priority);
2013     *dscp = pdscp ? pdscp->dscp : 0;
2014     return pdscp != NULL;
2015 }
2016
2017 static void
2018 ofport_clear_priorities(struct ofport_dpif *ofport)
2019 {
2020     struct priority_to_dscp *pdscp, *next;
2021
2022     HMAP_FOR_EACH_SAFE (pdscp, next, hmap_node, &ofport->priorities) {
2023         hmap_remove(&ofport->priorities, &pdscp->hmap_node);
2024         free(pdscp);
2025     }
2026 }
2027
2028 static int
2029 set_queues(struct ofport *ofport_,
2030            const struct ofproto_port_queue *qdscp_list,
2031            size_t n_qdscp)
2032 {
2033     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2034     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2035     struct hmap new = HMAP_INITIALIZER(&new);
2036     size_t i;
2037
2038     for (i = 0; i < n_qdscp; i++) {
2039         struct priority_to_dscp *pdscp;
2040         uint32_t priority;
2041         uint8_t dscp;
2042
2043         dscp = (qdscp_list[i].dscp << 2) & IP_DSCP_MASK;
2044         if (dpif_queue_to_priority(ofproto->backer->dpif, qdscp_list[i].queue,
2045                                    &priority)) {
2046             continue;
2047         }
2048
2049         pdscp = get_priority(ofport, priority);
2050         if (pdscp) {
2051             hmap_remove(&ofport->priorities, &pdscp->hmap_node);
2052         } else {
2053             pdscp = xmalloc(sizeof *pdscp);
2054             pdscp->priority = priority;
2055             pdscp->dscp = dscp;
2056             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2057         }
2058
2059         if (pdscp->dscp != dscp) {
2060             pdscp->dscp = dscp;
2061             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2062         }
2063
2064         hmap_insert(&new, &pdscp->hmap_node, hash_int(pdscp->priority, 0));
2065     }
2066
2067     if (!hmap_is_empty(&ofport->priorities)) {
2068         ofport_clear_priorities(ofport);
2069         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2070     }
2071
2072     hmap_swap(&new, &ofport->priorities);
2073     hmap_destroy(&new);
2074
2075     return 0;
2076 }
2077 \f
2078 /* Bundles. */
2079
2080 /* Expires all MAC learning entries associated with 'bundle' and forces its
2081  * ofproto to revalidate every flow.
2082  *
2083  * Normally MAC learning entries are removed only from the ofproto associated
2084  * with 'bundle', but if 'all_ofprotos' is true, then the MAC learning entries
2085  * are removed from every ofproto.  When patch ports and SLB bonds are in use
2086  * and a VM migration happens and the gratuitous ARPs are somehow lost, this
2087  * avoids a MAC_ENTRY_IDLE_TIME delay before the migrated VM can communicate
2088  * with the host from which it migrated. */
2089 static void
2090 bundle_flush_macs(struct ofbundle *bundle, bool all_ofprotos)
2091 {
2092     struct ofproto_dpif *ofproto = bundle->ofproto;
2093     struct mac_learning *ml = ofproto->ml;
2094     struct mac_entry *mac, *next_mac;
2095
2096     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2097     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
2098         if (mac->port.p == bundle) {
2099             if (all_ofprotos) {
2100                 struct ofproto_dpif *o;
2101
2102                 HMAP_FOR_EACH (o, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2103                     if (o != ofproto) {
2104                         struct mac_entry *e;
2105
2106                         e = mac_learning_lookup(o->ml, mac->mac, mac->vlan,
2107                                                 NULL);
2108                         if (e) {
2109                             mac_learning_expire(o->ml, e);
2110                         }
2111                     }
2112                 }
2113             }
2114
2115             mac_learning_expire(ml, mac);
2116         }
2117     }
2118 }
2119
2120 static struct ofbundle *
2121 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
2122 {
2123     struct ofbundle *bundle;
2124
2125     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
2126                              &ofproto->bundles) {
2127         if (bundle->aux == aux) {
2128             return bundle;
2129         }
2130     }
2131     return NULL;
2132 }
2133
2134 /* Looks up each of the 'n_auxes' pointers in 'auxes' as bundles and adds the
2135  * ones that are found to 'bundles'. */
2136 static void
2137 bundle_lookup_multiple(struct ofproto_dpif *ofproto,
2138                        void **auxes, size_t n_auxes,
2139                        struct hmapx *bundles)
2140 {
2141     size_t i;
2142
2143     hmapx_init(bundles);
2144     for (i = 0; i < n_auxes; i++) {
2145         struct ofbundle *bundle = bundle_lookup(ofproto, auxes[i]);
2146         if (bundle) {
2147             hmapx_add(bundles, bundle);
2148         }
2149     }
2150 }
2151
2152 static void
2153 bundle_update(struct ofbundle *bundle)
2154 {
2155     struct ofport_dpif *port;
2156
2157     bundle->floodable = true;
2158     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2159         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2160             || !stp_forward_in_state(port->stp_state)) {
2161             bundle->floodable = false;
2162             break;
2163         }
2164     }
2165 }
2166
2167 static void
2168 bundle_del_port(struct ofport_dpif *port)
2169 {
2170     struct ofbundle *bundle = port->bundle;
2171
2172     bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2173
2174     list_remove(&port->bundle_node);
2175     port->bundle = NULL;
2176
2177     if (bundle->lacp) {
2178         lacp_slave_unregister(bundle->lacp, port);
2179     }
2180     if (bundle->bond) {
2181         bond_slave_unregister(bundle->bond, port);
2182     }
2183
2184     bundle_update(bundle);
2185 }
2186
2187 static bool
2188 bundle_add_port(struct ofbundle *bundle, ofp_port_t ofp_port,
2189                 struct lacp_slave_settings *lacp)
2190 {
2191     struct ofport_dpif *port;
2192
2193     port = get_ofp_port(bundle->ofproto, ofp_port);
2194     if (!port) {
2195         return false;
2196     }
2197
2198     if (port->bundle != bundle) {
2199         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2200         if (port->bundle) {
2201             bundle_del_port(port);
2202         }
2203
2204         port->bundle = bundle;
2205         list_push_back(&bundle->ports, &port->bundle_node);
2206         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2207             || !stp_forward_in_state(port->stp_state)) {
2208             bundle->floodable = false;
2209         }
2210     }
2211     if (lacp) {
2212         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2213         lacp_slave_register(bundle->lacp, port, lacp);
2214     }
2215
2216     return true;
2217 }
2218
2219 static void
2220 bundle_destroy(struct ofbundle *bundle)
2221 {
2222     struct ofproto_dpif *ofproto;
2223     struct ofport_dpif *port, *next_port;
2224     int i;
2225
2226     if (!bundle) {
2227         return;
2228     }
2229
2230     ofproto = bundle->ofproto;
2231     for (i = 0; i < MAX_MIRRORS; i++) {
2232         struct ofmirror *m = ofproto->mirrors[i];
2233         if (m) {
2234             if (m->out == bundle) {
2235                 mirror_destroy(m);
2236             } else if (hmapx_find_and_delete(&m->srcs, bundle)
2237                        || hmapx_find_and_delete(&m->dsts, bundle)) {
2238                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2239             }
2240         }
2241     }
2242
2243     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2244         bundle_del_port(port);
2245     }
2246
2247     bundle_flush_macs(bundle, true);
2248     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
2249     free(bundle->name);
2250     free(bundle->trunks);
2251     lacp_unref(bundle->lacp);
2252     bond_unref(bundle->bond);
2253     free(bundle);
2254 }
2255
2256 static int
2257 bundle_set(struct ofproto *ofproto_, void *aux,
2258            const struct ofproto_bundle_settings *s)
2259 {
2260     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2261     bool need_flush = false;
2262     struct ofport_dpif *port;
2263     struct ofbundle *bundle;
2264     unsigned long *trunks;
2265     int vlan;
2266     size_t i;
2267     bool ok;
2268
2269     if (!s) {
2270         bundle_destroy(bundle_lookup(ofproto, aux));
2271         return 0;
2272     }
2273
2274     ovs_assert(s->n_slaves == 1 || s->bond != NULL);
2275     ovs_assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
2276
2277     bundle = bundle_lookup(ofproto, aux);
2278     if (!bundle) {
2279         bundle = xmalloc(sizeof *bundle);
2280
2281         bundle->ofproto = ofproto;
2282         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
2283                     hash_pointer(aux, 0));
2284         bundle->aux = aux;
2285         bundle->name = NULL;
2286
2287         list_init(&bundle->ports);
2288         bundle->vlan_mode = PORT_VLAN_TRUNK;
2289         bundle->vlan = -1;
2290         bundle->trunks = NULL;
2291         bundle->use_priority_tags = s->use_priority_tags;
2292         bundle->lacp = NULL;
2293         bundle->bond = NULL;
2294
2295         bundle->floodable = true;
2296
2297         bundle->src_mirrors = 0;
2298         bundle->dst_mirrors = 0;
2299         bundle->mirror_out = 0;
2300     }
2301
2302     if (!bundle->name || strcmp(s->name, bundle->name)) {
2303         free(bundle->name);
2304         bundle->name = xstrdup(s->name);
2305     }
2306
2307     /* LACP. */
2308     if (s->lacp) {
2309         if (!bundle->lacp) {
2310             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2311             bundle->lacp = lacp_create();
2312         }
2313         lacp_configure(bundle->lacp, s->lacp);
2314     } else {
2315         lacp_unref(bundle->lacp);
2316         bundle->lacp = NULL;
2317     }
2318
2319     /* Update set of ports. */
2320     ok = true;
2321     for (i = 0; i < s->n_slaves; i++) {
2322         if (!bundle_add_port(bundle, s->slaves[i],
2323                              s->lacp ? &s->lacp_slaves[i] : NULL)) {
2324             ok = false;
2325         }
2326     }
2327     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
2328         struct ofport_dpif *next_port;
2329
2330         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2331             for (i = 0; i < s->n_slaves; i++) {
2332                 if (s->slaves[i] == port->up.ofp_port) {
2333                     goto found;
2334                 }
2335             }
2336
2337             bundle_del_port(port);
2338         found: ;
2339         }
2340     }
2341     ovs_assert(list_size(&bundle->ports) <= s->n_slaves);
2342
2343     if (list_is_empty(&bundle->ports)) {
2344         bundle_destroy(bundle);
2345         return EINVAL;
2346     }
2347
2348     /* Set VLAN tagging mode */
2349     if (s->vlan_mode != bundle->vlan_mode
2350         || s->use_priority_tags != bundle->use_priority_tags) {
2351         bundle->vlan_mode = s->vlan_mode;
2352         bundle->use_priority_tags = s->use_priority_tags;
2353         need_flush = true;
2354     }
2355
2356     /* Set VLAN tag. */
2357     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
2358             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
2359             : 0);
2360     if (vlan != bundle->vlan) {
2361         bundle->vlan = vlan;
2362         need_flush = true;
2363     }
2364
2365     /* Get trunked VLANs. */
2366     switch (s->vlan_mode) {
2367     case PORT_VLAN_ACCESS:
2368         trunks = NULL;
2369         break;
2370
2371     case PORT_VLAN_TRUNK:
2372         trunks = CONST_CAST(unsigned long *, s->trunks);
2373         break;
2374
2375     case PORT_VLAN_NATIVE_UNTAGGED:
2376     case PORT_VLAN_NATIVE_TAGGED:
2377         if (vlan != 0 && (!s->trunks
2378                           || !bitmap_is_set(s->trunks, vlan)
2379                           || bitmap_is_set(s->trunks, 0))) {
2380             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
2381             if (s->trunks) {
2382                 trunks = bitmap_clone(s->trunks, 4096);
2383             } else {
2384                 trunks = bitmap_allocate1(4096);
2385             }
2386             bitmap_set1(trunks, vlan);
2387             bitmap_set0(trunks, 0);
2388         } else {
2389             trunks = CONST_CAST(unsigned long *, s->trunks);
2390         }
2391         break;
2392
2393     default:
2394         NOT_REACHED();
2395     }
2396     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
2397         free(bundle->trunks);
2398         if (trunks == s->trunks) {
2399             bundle->trunks = vlan_bitmap_clone(trunks);
2400         } else {
2401             bundle->trunks = trunks;
2402             trunks = NULL;
2403         }
2404         need_flush = true;
2405     }
2406     if (trunks != s->trunks) {
2407         free(trunks);
2408     }
2409
2410     /* Bonding. */
2411     if (!list_is_short(&bundle->ports)) {
2412         bundle->ofproto->has_bonded_bundles = true;
2413         if (bundle->bond) {
2414             if (bond_reconfigure(bundle->bond, s->bond)) {
2415                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2416             }
2417         } else {
2418             bundle->bond = bond_create(s->bond);
2419             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2420         }
2421
2422         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2423             bond_slave_register(bundle->bond, port, port->up.netdev);
2424         }
2425     } else {
2426         bond_unref(bundle->bond);
2427         bundle->bond = NULL;
2428     }
2429
2430     /* If we changed something that would affect MAC learning, un-learn
2431      * everything on this port and force flow revalidation. */
2432     if (need_flush) {
2433         bundle_flush_macs(bundle, false);
2434     }
2435
2436     return 0;
2437 }
2438
2439 static void
2440 bundle_remove(struct ofport *port_)
2441 {
2442     struct ofport_dpif *port = ofport_dpif_cast(port_);
2443     struct ofbundle *bundle = port->bundle;
2444
2445     if (bundle) {
2446         bundle_del_port(port);
2447         if (list_is_empty(&bundle->ports)) {
2448             bundle_destroy(bundle);
2449         } else if (list_is_short(&bundle->ports)) {
2450             bond_unref(bundle->bond);
2451             bundle->bond = NULL;
2452         }
2453     }
2454 }
2455
2456 static void
2457 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
2458 {
2459     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
2460     struct ofport_dpif *port = port_;
2461     uint8_t ea[ETH_ADDR_LEN];
2462     int error;
2463
2464     error = netdev_get_etheraddr(port->up.netdev, ea);
2465     if (!error) {
2466         struct ofpbuf packet;
2467         void *packet_pdu;
2468
2469         ofpbuf_init(&packet, 0);
2470         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
2471                                  pdu_size);
2472         memcpy(packet_pdu, pdu, pdu_size);
2473
2474         send_packet(port, &packet);
2475         ofpbuf_uninit(&packet);
2476     } else {
2477         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
2478                     "%s (%s)", port->bundle->name,
2479                     netdev_get_name(port->up.netdev), ovs_strerror(error));
2480     }
2481 }
2482
2483 static void
2484 bundle_send_learning_packets(struct ofbundle *bundle)
2485 {
2486     struct ofproto_dpif *ofproto = bundle->ofproto;
2487     int error, n_packets, n_errors;
2488     struct mac_entry *e;
2489
2490     error = n_packets = n_errors = 0;
2491     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
2492         if (e->port.p != bundle) {
2493             struct ofpbuf *learning_packet;
2494             struct ofport_dpif *port;
2495             void *port_void;
2496             int ret;
2497
2498             /* The assignment to "port" is unnecessary but makes "grep"ing for
2499              * struct ofport_dpif more effective. */
2500             learning_packet = bond_compose_learning_packet(bundle->bond,
2501                                                            e->mac, e->vlan,
2502                                                            &port_void);
2503             port = port_void;
2504             ret = send_packet(port, learning_packet);
2505             ofpbuf_delete(learning_packet);
2506             if (ret) {
2507                 error = ret;
2508                 n_errors++;
2509             }
2510             n_packets++;
2511         }
2512     }
2513
2514     if (n_errors) {
2515         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2516         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
2517                      "packets, last error was: %s",
2518                      bundle->name, n_errors, n_packets, ovs_strerror(error));
2519     } else {
2520         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
2521                  bundle->name, n_packets);
2522     }
2523 }
2524
2525 static void
2526 bundle_run(struct ofbundle *bundle)
2527 {
2528     if (bundle->lacp) {
2529         lacp_run(bundle->lacp, send_pdu_cb);
2530     }
2531     if (bundle->bond) {
2532         struct ofport_dpif *port;
2533
2534         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2535             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
2536         }
2537
2538         bond_run(bundle->bond, &bundle->ofproto->backer->revalidate_set,
2539                  lacp_status(bundle->lacp));
2540         if (bond_should_send_learning_packets(bundle->bond)) {
2541             bundle_send_learning_packets(bundle);
2542         }
2543     }
2544 }
2545
2546 static void
2547 bundle_wait(struct ofbundle *bundle)
2548 {
2549     if (bundle->lacp) {
2550         lacp_wait(bundle->lacp);
2551     }
2552     if (bundle->bond) {
2553         bond_wait(bundle->bond);
2554     }
2555 }
2556 \f
2557 /* Mirrors. */
2558
2559 static int
2560 mirror_scan(struct ofproto_dpif *ofproto)
2561 {
2562     int idx;
2563
2564     for (idx = 0; idx < MAX_MIRRORS; idx++) {
2565         if (!ofproto->mirrors[idx]) {
2566             return idx;
2567         }
2568     }
2569     return -1;
2570 }
2571
2572 static struct ofmirror *
2573 mirror_lookup(struct ofproto_dpif *ofproto, void *aux)
2574 {
2575     int i;
2576
2577     for (i = 0; i < MAX_MIRRORS; i++) {
2578         struct ofmirror *mirror = ofproto->mirrors[i];
2579         if (mirror && mirror->aux == aux) {
2580             return mirror;
2581         }
2582     }
2583
2584     return NULL;
2585 }
2586
2587 /* Update the 'dup_mirrors' member of each of the ofmirrors in 'ofproto'. */
2588 static void
2589 mirror_update_dups(struct ofproto_dpif *ofproto)
2590 {
2591     int i;
2592
2593     for (i = 0; i < MAX_MIRRORS; i++) {
2594         struct ofmirror *m = ofproto->mirrors[i];
2595
2596         if (m) {
2597             m->dup_mirrors = MIRROR_MASK_C(1) << i;
2598         }
2599     }
2600
2601     for (i = 0; i < MAX_MIRRORS; i++) {
2602         struct ofmirror *m1 = ofproto->mirrors[i];
2603         int j;
2604
2605         if (!m1) {
2606             continue;
2607         }
2608
2609         for (j = i + 1; j < MAX_MIRRORS; j++) {
2610             struct ofmirror *m2 = ofproto->mirrors[j];
2611
2612             if (m2 && m1->out == m2->out && m1->out_vlan == m2->out_vlan) {
2613                 m1->dup_mirrors |= MIRROR_MASK_C(1) << j;
2614                 m2->dup_mirrors |= m1->dup_mirrors;
2615             }
2616         }
2617     }
2618 }
2619
2620 static int
2621 mirror_set(struct ofproto *ofproto_, void *aux,
2622            const struct ofproto_mirror_settings *s)
2623 {
2624     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2625     mirror_mask_t mirror_bit;
2626     struct ofbundle *bundle;
2627     struct ofmirror *mirror;
2628     struct ofbundle *out;
2629     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
2630     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
2631     int out_vlan;
2632
2633     mirror = mirror_lookup(ofproto, aux);
2634     if (!s) {
2635         mirror_destroy(mirror);
2636         return 0;
2637     }
2638     if (!mirror) {
2639         int idx;
2640
2641         idx = mirror_scan(ofproto);
2642         if (idx < 0) {
2643             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
2644                       "cannot create %s",
2645                       ofproto->up.name, MAX_MIRRORS, s->name);
2646             return EFBIG;
2647         }
2648
2649         mirror = ofproto->mirrors[idx] = xzalloc(sizeof *mirror);
2650         mirror->ofproto = ofproto;
2651         mirror->idx = idx;
2652         mirror->aux = aux;
2653         mirror->out_vlan = -1;
2654         mirror->name = NULL;
2655     }
2656
2657     if (!mirror->name || strcmp(s->name, mirror->name)) {
2658         free(mirror->name);
2659         mirror->name = xstrdup(s->name);
2660     }
2661
2662     /* Get the new configuration. */
2663     if (s->out_bundle) {
2664         out = bundle_lookup(ofproto, s->out_bundle);
2665         if (!out) {
2666             mirror_destroy(mirror);
2667             return EINVAL;
2668         }
2669         out_vlan = -1;
2670     } else {
2671         out = NULL;
2672         out_vlan = s->out_vlan;
2673     }
2674     bundle_lookup_multiple(ofproto, s->srcs, s->n_srcs, &srcs);
2675     bundle_lookup_multiple(ofproto, s->dsts, s->n_dsts, &dsts);
2676
2677     /* If the configuration has not changed, do nothing. */
2678     if (hmapx_equals(&srcs, &mirror->srcs)
2679         && hmapx_equals(&dsts, &mirror->dsts)
2680         && vlan_bitmap_equal(mirror->vlans, s->src_vlans)
2681         && mirror->out == out
2682         && mirror->out_vlan == out_vlan)
2683     {
2684         hmapx_destroy(&srcs);
2685         hmapx_destroy(&dsts);
2686         return 0;
2687     }
2688
2689     hmapx_swap(&srcs, &mirror->srcs);
2690     hmapx_destroy(&srcs);
2691
2692     hmapx_swap(&dsts, &mirror->dsts);
2693     hmapx_destroy(&dsts);
2694
2695     free(mirror->vlans);
2696     mirror->vlans = vlan_bitmap_clone(s->src_vlans);
2697
2698     mirror->out = out;
2699     mirror->out_vlan = out_vlan;
2700
2701     /* Update bundles. */
2702     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
2703     HMAP_FOR_EACH (bundle, hmap_node, &mirror->ofproto->bundles) {
2704         if (hmapx_contains(&mirror->srcs, bundle)) {
2705             bundle->src_mirrors |= mirror_bit;
2706         } else {
2707             bundle->src_mirrors &= ~mirror_bit;
2708         }
2709
2710         if (hmapx_contains(&mirror->dsts, bundle)) {
2711             bundle->dst_mirrors |= mirror_bit;
2712         } else {
2713             bundle->dst_mirrors &= ~mirror_bit;
2714         }
2715
2716         if (mirror->out == bundle) {
2717             bundle->mirror_out |= mirror_bit;
2718         } else {
2719             bundle->mirror_out &= ~mirror_bit;
2720         }
2721     }
2722
2723     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2724     ofproto->has_mirrors = true;
2725     mac_learning_flush(ofproto->ml,
2726                        &ofproto->backer->revalidate_set);
2727     mirror_update_dups(ofproto);
2728
2729     return 0;
2730 }
2731
2732 static void
2733 mirror_destroy(struct ofmirror *mirror)
2734 {
2735     struct ofproto_dpif *ofproto;
2736     mirror_mask_t mirror_bit;
2737     struct ofbundle *bundle;
2738     int i;
2739
2740     if (!mirror) {
2741         return;
2742     }
2743
2744     ofproto = mirror->ofproto;
2745     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2746     mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
2747
2748     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
2749     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
2750         bundle->src_mirrors &= ~mirror_bit;
2751         bundle->dst_mirrors &= ~mirror_bit;
2752         bundle->mirror_out &= ~mirror_bit;
2753     }
2754
2755     hmapx_destroy(&mirror->srcs);
2756     hmapx_destroy(&mirror->dsts);
2757     free(mirror->vlans);
2758
2759     ofproto->mirrors[mirror->idx] = NULL;
2760     free(mirror->name);
2761     free(mirror);
2762
2763     mirror_update_dups(ofproto);
2764
2765     ofproto->has_mirrors = false;
2766     for (i = 0; i < MAX_MIRRORS; i++) {
2767         if (ofproto->mirrors[i]) {
2768             ofproto->has_mirrors = true;
2769             break;
2770         }
2771     }
2772 }
2773
2774 static int
2775 mirror_get_stats(struct ofproto *ofproto_, void *aux,
2776                  uint64_t *packets, uint64_t *bytes)
2777 {
2778     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2779     struct ofmirror *mirror = mirror_lookup(ofproto, aux);
2780
2781     if (!mirror) {
2782         *packets = *bytes = UINT64_MAX;
2783         return 0;
2784     }
2785
2786     push_all_stats();
2787
2788     *packets = mirror->packet_count;
2789     *bytes = mirror->byte_count;
2790
2791     return 0;
2792 }
2793
2794 static int
2795 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
2796 {
2797     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2798     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
2799         mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
2800     }
2801     return 0;
2802 }
2803
2804 static bool
2805 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
2806 {
2807     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2808     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
2809     return bundle && bundle->mirror_out != 0;
2810 }
2811
2812 static void
2813 forward_bpdu_changed(struct ofproto *ofproto_)
2814 {
2815     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2816     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2817 }
2818
2819 static void
2820 set_mac_table_config(struct ofproto *ofproto_, unsigned int idle_time,
2821                      size_t max_entries)
2822 {
2823     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2824     mac_learning_set_idle_time(ofproto->ml, idle_time);
2825     mac_learning_set_max_entries(ofproto->ml, max_entries);
2826 }
2827 \f
2828 /* Ports. */
2829
2830 struct ofport_dpif *
2831 get_ofp_port(const struct ofproto_dpif *ofproto, ofp_port_t ofp_port)
2832 {
2833     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
2834     return ofport ? ofport_dpif_cast(ofport) : NULL;
2835 }
2836
2837 struct ofport_dpif *
2838 get_odp_port(const struct ofproto_dpif *ofproto, odp_port_t odp_port)
2839 {
2840     struct ofport_dpif *port = odp_port_to_ofport(ofproto->backer, odp_port);
2841     return port && &ofproto->up == port->up.ofproto ? port : NULL;
2842 }
2843
2844 static void
2845 ofproto_port_from_dpif_port(struct ofproto_dpif *ofproto,
2846                             struct ofproto_port *ofproto_port,
2847                             struct dpif_port *dpif_port)
2848 {
2849     ofproto_port->name = dpif_port->name;
2850     ofproto_port->type = dpif_port->type;
2851     ofproto_port->ofp_port = odp_port_to_ofp_port(ofproto, dpif_port->port_no);
2852 }
2853
2854 static void
2855 ofport_update_peer(struct ofport_dpif *ofport)
2856 {
2857     const struct ofproto_dpif *ofproto;
2858     struct dpif_backer *backer;
2859     const char *peer_name;
2860
2861     if (!netdev_vport_is_patch(ofport->up.netdev)) {
2862         return;
2863     }
2864
2865     backer = ofproto_dpif_cast(ofport->up.ofproto)->backer;
2866     backer->need_revalidate = REV_RECONFIGURE;
2867
2868     if (ofport->peer) {
2869         ofport->peer->peer = NULL;
2870         ofport->peer = NULL;
2871     }
2872
2873     peer_name = netdev_vport_patch_peer(ofport->up.netdev);
2874     if (!peer_name) {
2875         return;
2876     }
2877
2878     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2879         struct ofport *peer_ofport;
2880         struct ofport_dpif *peer;
2881         const char *peer_peer;
2882
2883         if (ofproto->backer != backer) {
2884             continue;
2885         }
2886
2887         peer_ofport = shash_find_data(&ofproto->up.port_by_name, peer_name);
2888         if (!peer_ofport) {
2889             continue;
2890         }
2891
2892         peer = ofport_dpif_cast(peer_ofport);
2893         peer_peer = netdev_vport_patch_peer(peer->up.netdev);
2894         if (peer_peer && !strcmp(netdev_get_name(ofport->up.netdev),
2895                                  peer_peer)) {
2896             ofport->peer = peer;
2897             ofport->peer->peer = ofport;
2898         }
2899
2900         return;
2901     }
2902 }
2903
2904 static void
2905 port_run_fast(struct ofport_dpif *ofport)
2906 {
2907     if (ofport->cfm && cfm_should_send_ccm(ofport->cfm)) {
2908         struct ofpbuf packet;
2909
2910         ofpbuf_init(&packet, 0);
2911         cfm_compose_ccm(ofport->cfm, &packet, ofport->up.pp.hw_addr);
2912         send_packet(ofport, &packet);
2913         ofpbuf_uninit(&packet);
2914     }
2915
2916     if (ofport->bfd && bfd_should_send_packet(ofport->bfd)) {
2917         struct ofpbuf packet;
2918
2919         ofpbuf_init(&packet, 0);
2920         bfd_put_packet(ofport->bfd, &packet, ofport->up.pp.hw_addr);
2921         send_packet(ofport, &packet);
2922         ofpbuf_uninit(&packet);
2923     }
2924 }
2925
2926 static void
2927 port_run(struct ofport_dpif *ofport)
2928 {
2929     long long int carrier_seq = netdev_get_carrier_resets(ofport->up.netdev);
2930     bool carrier_changed = carrier_seq != ofport->carrier_seq;
2931     bool enable = netdev_get_carrier(ofport->up.netdev);
2932
2933     ofport->carrier_seq = carrier_seq;
2934
2935     port_run_fast(ofport);
2936
2937     if (ofport->cfm) {
2938         int cfm_opup = cfm_get_opup(ofport->cfm);
2939
2940         cfm_run(ofport->cfm);
2941         enable = enable && !cfm_get_fault(ofport->cfm);
2942
2943         if (cfm_opup >= 0) {
2944             enable = enable && cfm_opup;
2945         }
2946     }
2947
2948     if (ofport->bfd) {
2949         bfd_run(ofport->bfd);
2950         enable = enable && bfd_forwarding(ofport->bfd);
2951     }
2952
2953     if (ofport->bundle) {
2954         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
2955         if (carrier_changed) {
2956             lacp_slave_carrier_changed(ofport->bundle->lacp, ofport);
2957         }
2958     }
2959
2960     if (ofport->may_enable != enable) {
2961         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2962         ofproto->backer->need_revalidate = REV_PORT_TOGGLED;
2963     }
2964
2965     ofport->may_enable = enable;
2966 }
2967
2968 static void
2969 port_wait(struct ofport_dpif *ofport)
2970 {
2971     if (ofport->cfm) {
2972         cfm_wait(ofport->cfm);
2973     }
2974
2975     if (ofport->bfd) {
2976         bfd_wait(ofport->bfd);
2977     }
2978 }
2979
2980 static int
2981 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
2982                    struct ofproto_port *ofproto_port)
2983 {
2984     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2985     struct dpif_port dpif_port;
2986     int error;
2987
2988     if (sset_contains(&ofproto->ghost_ports, devname)) {
2989         const char *type = netdev_get_type_from_name(devname);
2990
2991         /* We may be called before ofproto->up.port_by_name is populated with
2992          * the appropriate ofport.  For this reason, we must get the name and
2993          * type from the netdev layer directly. */
2994         if (type) {
2995             const struct ofport *ofport;
2996
2997             ofport = shash_find_data(&ofproto->up.port_by_name, devname);
2998             ofproto_port->ofp_port = ofport ? ofport->ofp_port : OFPP_NONE;
2999             ofproto_port->name = xstrdup(devname);
3000             ofproto_port->type = xstrdup(type);
3001             return 0;
3002         }
3003         return ENODEV;
3004     }
3005
3006     if (!sset_contains(&ofproto->ports, devname)) {
3007         return ENODEV;
3008     }
3009     error = dpif_port_query_by_name(ofproto->backer->dpif,
3010                                     devname, &dpif_port);
3011     if (!error) {
3012         ofproto_port_from_dpif_port(ofproto, ofproto_port, &dpif_port);
3013     }
3014     return error;
3015 }
3016
3017 static int
3018 port_add(struct ofproto *ofproto_, struct netdev *netdev)
3019 {
3020     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3021     const char *devname = netdev_get_name(netdev);
3022     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
3023     const char *dp_port_name;
3024
3025     if (netdev_vport_is_patch(netdev)) {
3026         sset_add(&ofproto->ghost_ports, netdev_get_name(netdev));
3027         return 0;
3028     }
3029
3030     dp_port_name = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
3031     if (!dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
3032         odp_port_t port_no = ODPP_NONE;
3033         int error;
3034
3035         error = dpif_port_add(ofproto->backer->dpif, netdev, &port_no);
3036         if (error) {
3037             return error;
3038         }
3039         if (netdev_get_tunnel_config(netdev)) {
3040             simap_put(&ofproto->backer->tnl_backers,
3041                       dp_port_name, odp_to_u32(port_no));
3042         }
3043     }
3044
3045     if (netdev_get_tunnel_config(netdev)) {
3046         sset_add(&ofproto->ghost_ports, devname);
3047     } else {
3048         sset_add(&ofproto->ports, devname);
3049     }
3050     return 0;
3051 }
3052
3053 static int
3054 port_del(struct ofproto *ofproto_, ofp_port_t ofp_port)
3055 {
3056     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3057     struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
3058     int error = 0;
3059
3060     if (!ofport) {
3061         return 0;
3062     }
3063
3064     sset_find_and_delete(&ofproto->ghost_ports,
3065                          netdev_get_name(ofport->up.netdev));
3066     ofproto->backer->need_revalidate = REV_RECONFIGURE;
3067     if (!ofport->is_tunnel) {
3068         error = dpif_port_del(ofproto->backer->dpif, ofport->odp_port);
3069         if (!error) {
3070             /* The caller is going to close ofport->up.netdev.  If this is a
3071              * bonded port, then the bond is using that netdev, so remove it
3072              * from the bond.  The client will need to reconfigure everything
3073              * after deleting ports, so then the slave will get re-added. */
3074             bundle_remove(&ofport->up);
3075         }
3076     }
3077     return error;
3078 }
3079
3080 static int
3081 port_get_stats(const struct ofport *ofport_, struct netdev_stats *stats)
3082 {
3083     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3084     int error;
3085
3086     push_all_stats();
3087
3088     error = netdev_get_stats(ofport->up.netdev, stats);
3089
3090     if (!error && ofport_->ofp_port == OFPP_LOCAL) {
3091         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3092
3093         /* ofproto->stats.tx_packets represents packets that we created
3094          * internally and sent to some port (e.g. packets sent with
3095          * send_packet()).  Account for them as if they had come from
3096          * OFPP_LOCAL and got forwarded. */
3097
3098         if (stats->rx_packets != UINT64_MAX) {
3099             stats->rx_packets += ofproto->stats.tx_packets;
3100         }
3101
3102         if (stats->rx_bytes != UINT64_MAX) {
3103             stats->rx_bytes += ofproto->stats.tx_bytes;
3104         }
3105
3106         /* ofproto->stats.rx_packets represents packets that were received on
3107          * some port and we processed internally and dropped (e.g. STP).
3108          * Account for them as if they had been forwarded to OFPP_LOCAL. */
3109
3110         if (stats->tx_packets != UINT64_MAX) {
3111             stats->tx_packets += ofproto->stats.rx_packets;
3112         }
3113
3114         if (stats->tx_bytes != UINT64_MAX) {
3115             stats->tx_bytes += ofproto->stats.rx_bytes;
3116         }
3117     }
3118
3119     return error;
3120 }
3121
3122 struct port_dump_state {
3123     uint32_t bucket;
3124     uint32_t offset;
3125     bool ghost;
3126
3127     struct ofproto_port port;
3128     bool has_port;
3129 };
3130
3131 static int
3132 port_dump_start(const struct ofproto *ofproto_ OVS_UNUSED, void **statep)
3133 {
3134     *statep = xzalloc(sizeof(struct port_dump_state));
3135     return 0;
3136 }
3137
3138 static int
3139 port_dump_next(const struct ofproto *ofproto_, void *state_,
3140                struct ofproto_port *port)
3141 {
3142     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3143     struct port_dump_state *state = state_;
3144     const struct sset *sset;
3145     struct sset_node *node;
3146
3147     if (state->has_port) {
3148         ofproto_port_destroy(&state->port);
3149         state->has_port = false;
3150     }
3151     sset = state->ghost ? &ofproto->ghost_ports : &ofproto->ports;
3152     while ((node = sset_at_position(sset, &state->bucket, &state->offset))) {
3153         int error;
3154
3155         error = port_query_by_name(ofproto_, node->name, &state->port);
3156         if (!error) {
3157             *port = state->port;
3158             state->has_port = true;
3159             return 0;
3160         } else if (error != ENODEV) {
3161             return error;
3162         }
3163     }
3164
3165     if (!state->ghost) {
3166         state->ghost = true;
3167         state->bucket = 0;
3168         state->offset = 0;
3169         return port_dump_next(ofproto_, state_, port);
3170     }
3171
3172     return EOF;
3173 }
3174
3175 static int
3176 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
3177 {
3178     struct port_dump_state *state = state_;
3179
3180     if (state->has_port) {
3181         ofproto_port_destroy(&state->port);
3182     }
3183     free(state);
3184     return 0;
3185 }
3186
3187 static int
3188 port_poll(const struct ofproto *ofproto_, char **devnamep)
3189 {
3190     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3191
3192     if (ofproto->port_poll_errno) {
3193         int error = ofproto->port_poll_errno;
3194         ofproto->port_poll_errno = 0;
3195         return error;
3196     }
3197
3198     if (sset_is_empty(&ofproto->port_poll_set)) {
3199         return EAGAIN;
3200     }
3201
3202     *devnamep = sset_pop(&ofproto->port_poll_set);
3203     return 0;
3204 }
3205
3206 static void
3207 port_poll_wait(const struct ofproto *ofproto_)
3208 {
3209     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3210     dpif_port_poll_wait(ofproto->backer->dpif);
3211 }
3212
3213 static int
3214 port_is_lacp_current(const struct ofport *ofport_)
3215 {
3216     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3217     return (ofport->bundle && ofport->bundle->lacp
3218             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
3219             : -1);
3220 }
3221 \f
3222 /* Upcall handling. */
3223
3224 /* Flow miss batching.
3225  *
3226  * Some dpifs implement operations faster when you hand them off in a batch.
3227  * To allow batching, "struct flow_miss" queues the dpif-related work needed
3228  * for a given flow.  Each "struct flow_miss" corresponds to sending one or
3229  * more packets, plus possibly installing the flow in the dpif.
3230  *
3231  * So far we only batch the operations that affect flow setup time the most.
3232  * It's possible to batch more than that, but the benefit might be minimal. */
3233 struct flow_miss {
3234     struct hmap_node hmap_node;
3235     struct ofproto_dpif *ofproto;
3236     struct flow flow;
3237     enum odp_key_fitness key_fitness;
3238     const struct nlattr *key;
3239     size_t key_len;
3240     struct list packets;
3241     enum dpif_upcall_type upcall_type;
3242 };
3243
3244 struct flow_miss_op {
3245     struct dpif_op dpif_op;
3246
3247     uint64_t slow_stub[128 / 8]; /* Buffer for compose_slow_path() */
3248     struct xlate_out xout;
3249     bool xout_garbage;           /* 'xout' needs to be uninitialized? */
3250
3251     struct ofpbuf mask;          /* Flow mask for "put" ops. */
3252     struct odputil_keybuf maskbuf;
3253
3254     /* If this is a "put" op, then a pointer to the subfacet that should
3255      * be marked as uninstalled if the operation fails. */
3256     struct subfacet *subfacet;
3257 };
3258
3259 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_NO_MATCH to each
3260  * OpenFlow controller as necessary according to their individual
3261  * configurations. */
3262 static void
3263 send_packet_in_miss(struct ofproto_dpif *ofproto, const struct ofpbuf *packet,
3264                     const struct flow *flow)
3265 {
3266     struct ofputil_packet_in pin;
3267
3268     pin.packet = packet->data;
3269     pin.packet_len = packet->size;
3270     pin.reason = OFPR_NO_MATCH;
3271     pin.controller_id = 0;
3272
3273     pin.table_id = 0;
3274     pin.cookie = 0;
3275
3276     pin.send_len = 0;           /* not used for flow table misses */
3277
3278     flow_get_metadata(flow, &pin.fmd);
3279
3280     connmgr_send_packet_in(ofproto->up.connmgr, &pin);
3281 }
3282
3283 static struct flow_miss *
3284 flow_miss_find(struct hmap *todo, const struct ofproto_dpif *ofproto,
3285                const struct flow *flow, uint32_t hash)
3286 {
3287     struct flow_miss *miss;
3288
3289     HMAP_FOR_EACH_WITH_HASH (miss, hmap_node, hash, todo) {
3290         if (miss->ofproto == ofproto && flow_equal(&miss->flow, flow)) {
3291             return miss;
3292         }
3293     }
3294
3295     return NULL;
3296 }
3297
3298 /* Partially Initializes 'op' as an "execute" operation for 'miss' and
3299  * 'packet'.  The caller must initialize op->actions and op->actions_len.  If
3300  * 'miss' is associated with a subfacet the caller must also initialize the
3301  * returned op->subfacet, and if anything needs to be freed after processing
3302  * the op, the caller must initialize op->garbage also. */
3303 static void
3304 init_flow_miss_execute_op(struct flow_miss *miss, struct ofpbuf *packet,
3305                           struct flow_miss_op *op)
3306 {
3307     if (miss->flow.in_port.ofp_port
3308         != vsp_realdev_to_vlandev(miss->ofproto, miss->flow.in_port.ofp_port,
3309                                   miss->flow.vlan_tci)) {
3310         /* This packet was received on a VLAN splinter port.  We
3311          * added a VLAN to the packet to make the packet resemble
3312          * the flow, but the actions were composed assuming that
3313          * the packet contained no VLAN.  So, we must remove the
3314          * VLAN header from the packet before trying to execute the
3315          * actions. */
3316         eth_pop_vlan(packet);
3317     }
3318
3319     op->subfacet = NULL;
3320     op->xout_garbage = false;
3321     op->dpif_op.type = DPIF_OP_EXECUTE;
3322     op->dpif_op.u.execute.key = miss->key;
3323     op->dpif_op.u.execute.key_len = miss->key_len;
3324     op->dpif_op.u.execute.packet = packet;
3325     ofpbuf_use_stack(&op->mask, &op->maskbuf, sizeof op->maskbuf);
3326 }
3327
3328 /* Helper for handle_flow_miss_without_facet() and
3329  * handle_flow_miss_with_facet(). */
3330 static void
3331 handle_flow_miss_common(struct rule_dpif *rule,
3332                         struct ofpbuf *packet, const struct flow *flow)
3333 {
3334     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3335
3336     if (rule->up.cr.priority == FAIL_OPEN_PRIORITY) {
3337         /*
3338          * Extra-special case for fail-open mode.
3339          *
3340          * We are in fail-open mode and the packet matched the fail-open
3341          * rule, but we are connected to a controller too.  We should send
3342          * the packet up to the controller in the hope that it will try to
3343          * set up a flow and thereby allow us to exit fail-open.
3344          *
3345          * See the top-level comment in fail-open.c for more information.
3346          */
3347         send_packet_in_miss(ofproto, packet, flow);
3348     }
3349 }
3350
3351 /* Figures out whether a flow that missed in 'ofproto', whose details are in
3352  * 'miss' masked by 'wc', is likely to be worth tracking in detail in userspace
3353  * and (usually) installing a datapath flow.  The answer is usually "yes" (a
3354  * return value of true).  However, for short flows the cost of bookkeeping is
3355  * much higher than the benefits, so when the datapath holds a large number of
3356  * flows we impose some heuristics to decide which flows are likely to be worth
3357  * tracking. */
3358 static bool
3359 flow_miss_should_make_facet(struct flow_miss *miss, struct flow_wildcards *wc)
3360 {
3361     struct dpif_backer *backer = miss->ofproto->backer;
3362     uint32_t hash;
3363
3364     switch (flow_miss_model) {
3365     case OFPROTO_HANDLE_MISS_AUTO:
3366         break;
3367     case OFPROTO_HANDLE_MISS_WITH_FACETS:
3368         return true;
3369     case OFPROTO_HANDLE_MISS_WITHOUT_FACETS:
3370         return false;
3371     }
3372
3373     if (!backer->governor) {
3374         size_t n_subfacets;
3375
3376         n_subfacets = hmap_count(&backer->subfacets);
3377         if (n_subfacets * 2 <= flow_eviction_threshold) {
3378             return true;
3379         }
3380
3381         backer->governor = governor_create();
3382     }
3383
3384     hash = flow_hash_in_wildcards(&miss->flow, wc, 0);
3385     return governor_should_install_flow(backer->governor, hash,
3386                                         list_size(&miss->packets));
3387 }
3388
3389 /* Handles 'miss' without creating a facet or subfacet or creating any datapath
3390  * flow.  'miss->flow' must have matched 'rule' and been xlated into 'xout'.
3391  * May add an "execute" operation to 'ops' and increment '*n_ops'. */
3392 static void
3393 handle_flow_miss_without_facet(struct rule_dpif *rule, struct xlate_out *xout,
3394                                struct flow_miss *miss,
3395                                struct flow_miss_op *ops, size_t *n_ops)
3396 {
3397     struct ofpbuf *packet;
3398
3399     LIST_FOR_EACH (packet, list_node, &miss->packets) {
3400
3401         COVERAGE_INC(facet_suppress);
3402
3403         handle_flow_miss_common(rule, packet, &miss->flow);
3404
3405         if (xout->slow) {
3406             struct xlate_in xin;
3407
3408             xlate_in_init(&xin, miss->ofproto, &miss->flow, rule, 0, packet);
3409             xlate_actions_for_side_effects(&xin);
3410         }
3411
3412         if (xout->odp_actions.size) {
3413             struct flow_miss_op *op = &ops[*n_ops];
3414             struct dpif_execute *execute = &op->dpif_op.u.execute;
3415
3416             init_flow_miss_execute_op(miss, packet, op);
3417             xlate_out_copy(&op->xout, xout);
3418             execute->actions = op->xout.odp_actions.data;
3419             execute->actions_len = op->xout.odp_actions.size;
3420             op->xout_garbage = true;
3421
3422             (*n_ops)++;
3423         }
3424     }
3425 }
3426
3427 /* Handles 'miss', which matches 'facet'.  May add any required datapath
3428  * operations to 'ops', incrementing '*n_ops' for each new op.
3429  *
3430  * All of the packets in 'miss' are considered to have arrived at time 'now'.
3431  * This is really important only for new facets: if we just called time_msec()
3432  * here, then the new subfacet or its packets could look (occasionally) as
3433  * though it was used some time after the facet was used.  That can make a
3434  * one-packet flow look like it has a nonzero duration, which looks odd in
3435  * e.g. NetFlow statistics.
3436  *
3437  * If non-null, 'stats' will be folded into 'facet'. */
3438 static void
3439 handle_flow_miss_with_facet(struct flow_miss *miss, struct facet *facet,
3440                             long long int now, struct dpif_flow_stats *stats,
3441                             struct flow_miss_op *ops, size_t *n_ops)
3442 {
3443     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3444     enum subfacet_path want_path;
3445     struct subfacet *subfacet;
3446     struct ofpbuf *packet;
3447
3448     subfacet = subfacet_create(facet, miss, now);
3449     want_path = facet->xout.slow ? SF_SLOW_PATH : SF_FAST_PATH;
3450     if (stats) {
3451         subfacet_update_stats(subfacet, stats);
3452     }
3453
3454     LIST_FOR_EACH (packet, list_node, &miss->packets) {
3455         struct flow_miss_op *op = &ops[*n_ops];
3456
3457         handle_flow_miss_common(facet->rule, packet, &miss->flow);
3458
3459         if (want_path != SF_FAST_PATH) {
3460             struct xlate_in xin;
3461
3462             xlate_in_init(&xin, ofproto, &miss->flow, facet->rule, 0, packet);
3463             xlate_actions_for_side_effects(&xin);
3464         }
3465
3466         if (facet->xout.odp_actions.size) {
3467             struct dpif_execute *execute = &op->dpif_op.u.execute;
3468
3469             init_flow_miss_execute_op(miss, packet, op);
3470             execute->actions = facet->xout.odp_actions.data,
3471             execute->actions_len = facet->xout.odp_actions.size;
3472             (*n_ops)++;
3473         }
3474     }
3475
3476     if (miss->upcall_type == DPIF_UC_MISS || subfacet->path != want_path) {
3477         struct flow_miss_op *op = &ops[(*n_ops)++];
3478         struct dpif_flow_put *put = &op->dpif_op.u.flow_put;
3479
3480         subfacet->path = want_path;
3481
3482         ofpbuf_use_stack(&op->mask, &op->maskbuf, sizeof op->maskbuf);
3483         if (enable_megaflows) {
3484             odp_flow_key_from_mask(&op->mask, &facet->xout.wc.masks,
3485                                    &miss->flow, UINT32_MAX);
3486         }
3487
3488         op->xout_garbage = false;
3489         op->dpif_op.type = DPIF_OP_FLOW_PUT;
3490         op->subfacet = subfacet;
3491         put->flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
3492         put->key = miss->key;
3493         put->key_len = miss->key_len;
3494         put->mask = op->mask.data;
3495         put->mask_len = op->mask.size;
3496
3497         if (want_path == SF_FAST_PATH) {
3498             put->actions = facet->xout.odp_actions.data;
3499             put->actions_len = facet->xout.odp_actions.size;
3500         } else {
3501             compose_slow_path(ofproto, &miss->flow, facet->xout.slow,
3502                               op->slow_stub, sizeof op->slow_stub,
3503                               &put->actions, &put->actions_len);
3504         }
3505         put->stats = NULL;
3506     }
3507 }
3508
3509 /* Handles flow miss 'miss'.  May add any required datapath operations
3510  * to 'ops', incrementing '*n_ops' for each new op. */
3511 static void
3512 handle_flow_miss(struct flow_miss *miss, struct flow_miss_op *ops,
3513                  size_t *n_ops)
3514 {
3515     struct ofproto_dpif *ofproto = miss->ofproto;
3516     struct dpif_flow_stats stats__;
3517     struct dpif_flow_stats *stats = &stats__;
3518     struct ofpbuf *packet;
3519     struct facet *facet;
3520     long long int now;
3521
3522     now = time_msec();
3523     memset(stats, 0, sizeof *stats);
3524     stats->used = now;
3525     LIST_FOR_EACH (packet, list_node, &miss->packets) {
3526         stats->tcp_flags |= packet_get_tcp_flags(packet, &miss->flow);
3527         stats->n_bytes += packet->size;
3528         stats->n_packets++;
3529     }
3530
3531     facet = facet_lookup_valid(ofproto, &miss->flow);
3532     if (!facet) {
3533         struct flow_wildcards wc;
3534         struct rule_dpif *rule;
3535         struct xlate_out xout;
3536         struct xlate_in xin;
3537
3538         flow_wildcards_init_catchall(&wc);
3539         rule = rule_dpif_lookup(ofproto, &miss->flow, &wc);
3540         rule_credit_stats(rule, stats);
3541
3542         xlate_in_init(&xin, ofproto, &miss->flow, rule, stats->tcp_flags,
3543                       NULL);
3544         xin.resubmit_stats = stats;
3545         xin.may_learn = true;
3546         xlate_actions(&xin, &xout);
3547         flow_wildcards_or(&xout.wc, &xout.wc, &wc);
3548
3549         /* There does not exist a bijection between 'struct flow' and datapath
3550          * flow keys with fitness ODP_FIT_TO_LITTLE.  This breaks a fundamental
3551          * assumption used throughout the facet and subfacet handling code.
3552          * Since we have to handle these misses in userspace anyway, we simply
3553          * skip facet creation, avoiding the problem altogether. */
3554         if (miss->key_fitness == ODP_FIT_TOO_LITTLE
3555             || !flow_miss_should_make_facet(miss, &xout.wc)) {
3556             handle_flow_miss_without_facet(rule, &xout, miss, ops, n_ops);
3557             return;
3558         }
3559
3560         facet = facet_create(miss, rule, &xout, stats);
3561         stats = NULL;
3562     }
3563     handle_flow_miss_with_facet(miss, facet, now, stats, ops, n_ops);
3564 }
3565
3566 static struct drop_key *
3567 drop_key_lookup(const struct dpif_backer *backer, const struct nlattr *key,
3568                 size_t key_len)
3569 {
3570     struct drop_key *drop_key;
3571
3572     HMAP_FOR_EACH_WITH_HASH (drop_key, hmap_node, hash_bytes(key, key_len, 0),
3573                              &backer->drop_keys) {
3574         if (drop_key->key_len == key_len
3575             && !memcmp(drop_key->key, key, key_len)) {
3576             return drop_key;
3577         }
3578     }
3579     return NULL;
3580 }
3581
3582 static void
3583 drop_key_clear(struct dpif_backer *backer)
3584 {
3585     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 15);
3586     struct drop_key *drop_key, *next;
3587
3588     HMAP_FOR_EACH_SAFE (drop_key, next, hmap_node, &backer->drop_keys) {
3589         int error;
3590
3591         error = dpif_flow_del(backer->dpif, drop_key->key, drop_key->key_len,
3592                               NULL);
3593         if (error && !VLOG_DROP_WARN(&rl)) {
3594             struct ds ds = DS_EMPTY_INITIALIZER;
3595             odp_flow_key_format(drop_key->key, drop_key->key_len, &ds);
3596             VLOG_WARN("Failed to delete drop key (%s) (%s)",
3597                       ovs_strerror(error), ds_cstr(&ds));
3598             ds_destroy(&ds);
3599         }
3600
3601         hmap_remove(&backer->drop_keys, &drop_key->hmap_node);
3602         free(drop_key->key);
3603         free(drop_key);
3604     }
3605 }
3606
3607 /* Given a datpath, packet, and flow metadata ('backer', 'packet', and 'key'
3608  * respectively), populates 'flow' with the result of odp_flow_key_to_flow().
3609  * Optionally, if nonnull, populates 'fitnessp' with the fitness of 'flow' as
3610  * returned by odp_flow_key_to_flow().  Also, optionally populates 'ofproto'
3611  * with the ofproto_dpif, and 'odp_in_port' with the datapath in_port, that
3612  * 'packet' ingressed.
3613  *
3614  * If 'ofproto' is nonnull, requires 'flow''s in_port to exist.  Otherwise sets
3615  * 'flow''s in_port to OFPP_NONE.
3616  *
3617  * This function does post-processing on data returned from
3618  * odp_flow_key_to_flow() to help make VLAN splinters transparent to the rest
3619  * of the upcall processing logic.  In particular, if the extracted in_port is
3620  * a VLAN splinter port, it replaces flow->in_port by the "real" port, sets
3621  * flow->vlan_tci correctly for the VLAN of the VLAN splinter port, and pushes
3622  * a VLAN header onto 'packet' (if it is nonnull).
3623  *
3624  * Similarly, this function also includes some logic to help with tunnels.  It
3625  * may modify 'flow' as necessary to make the tunneling implementation
3626  * transparent to the upcall processing logic.
3627  *
3628  * Returns 0 if successful, ENODEV if the parsed flow has no associated ofport,
3629  * or some other positive errno if there are other problems. */
3630 static int
3631 ofproto_receive(const struct dpif_backer *backer, struct ofpbuf *packet,
3632                 const struct nlattr *key, size_t key_len,
3633                 struct flow *flow, enum odp_key_fitness *fitnessp,
3634                 struct ofproto_dpif **ofproto, odp_port_t *odp_in_port)
3635 {
3636     const struct ofport_dpif *port;
3637     enum odp_key_fitness fitness;
3638     int error = ENODEV;
3639
3640     fitness = odp_flow_key_to_flow(key, key_len, flow);
3641     if (fitness == ODP_FIT_ERROR) {
3642         error = EINVAL;
3643         goto exit;
3644     }
3645
3646     if (odp_in_port) {
3647         *odp_in_port = flow->in_port.odp_port;
3648     }
3649
3650     port = (tnl_port_should_receive(flow)
3651             ? tnl_port_receive(flow)
3652             : odp_port_to_ofport(backer, flow->in_port.odp_port));
3653     flow->in_port.ofp_port = port ? port->up.ofp_port : OFPP_NONE;
3654     if (!port) {
3655         goto exit;
3656     }
3657
3658     /* XXX: Since the tunnel module is not scoped per backer, for a tunnel port
3659      * it's theoretically possible that we'll receive an ofport belonging to an
3660      * entirely different datapath.  In practice, this can't happen because no
3661      * platforms has two separate datapaths which each support tunneling. */
3662     ovs_assert(ofproto_dpif_cast(port->up.ofproto)->backer == backer);
3663
3664     if (vsp_adjust_flow(ofproto_dpif_cast(port->up.ofproto), flow)) {
3665         if (packet) {
3666             /* Make the packet resemble the flow, so that it gets sent to
3667              * an OpenFlow controller properly, so that it looks correct
3668              * for sFlow, and so that flow_extract() will get the correct
3669              * vlan_tci if it is called on 'packet'.
3670              *
3671              * The allocated space inside 'packet' probably also contains
3672              * 'key', that is, both 'packet' and 'key' are probably part of
3673              * a struct dpif_upcall (see the large comment on that
3674              * structure definition), so pushing data on 'packet' is in
3675              * general not a good idea since it could overwrite 'key' or
3676              * free it as a side effect.  However, it's OK in this special
3677              * case because we know that 'packet' is inside a Netlink
3678              * attribute: pushing 4 bytes will just overwrite the 4-byte
3679              * "struct nlattr", which is fine since we don't need that
3680              * header anymore. */
3681             eth_push_vlan(packet, flow->vlan_tci);
3682         }
3683         /* We can't reproduce 'key' from 'flow'. */
3684         fitness = fitness == ODP_FIT_PERFECT ? ODP_FIT_TOO_MUCH : fitness;
3685     }
3686     error = 0;
3687
3688     if (ofproto) {
3689         *ofproto = ofproto_dpif_cast(port->up.ofproto);
3690     }
3691
3692 exit:
3693     if (fitnessp) {
3694         *fitnessp = fitness;
3695     }
3696     return error;
3697 }
3698
3699 static void
3700 handle_miss_upcalls(struct dpif_backer *backer, struct dpif_upcall *upcalls,
3701                     size_t n_upcalls)
3702 {
3703     struct dpif_upcall *upcall;
3704     struct flow_miss *miss;
3705     struct flow_miss misses[FLOW_MISS_MAX_BATCH];
3706     struct flow_miss_op flow_miss_ops[FLOW_MISS_MAX_BATCH * 2];
3707     struct dpif_op *dpif_ops[FLOW_MISS_MAX_BATCH * 2];
3708     struct hmap todo;
3709     int n_misses;
3710     size_t n_ops;
3711     size_t i;
3712
3713     if (!n_upcalls) {
3714         return;
3715     }
3716
3717     /* Construct the to-do list.
3718      *
3719      * This just amounts to extracting the flow from each packet and sticking
3720      * the packets that have the same flow in the same "flow_miss" structure so
3721      * that we can process them together. */
3722     hmap_init(&todo);
3723     n_misses = 0;
3724     for (upcall = upcalls; upcall < &upcalls[n_upcalls]; upcall++) {
3725         struct flow_miss *miss = &misses[n_misses];
3726         struct flow_miss *existing_miss;
3727         struct ofproto_dpif *ofproto;
3728         odp_port_t odp_in_port;
3729         struct flow flow;
3730         uint32_t hash;
3731         int error;
3732
3733         error = ofproto_receive(backer, upcall->packet, upcall->key,
3734                                 upcall->key_len, &flow, &miss->key_fitness,
3735                                 &ofproto, &odp_in_port);
3736         if (error == ENODEV) {
3737             struct drop_key *drop_key;
3738
3739             /* Received packet on datapath port for which we couldn't
3740              * associate an ofproto.  This can happen if a port is removed
3741              * while traffic is being received.  Print a rate-limited message
3742              * in case it happens frequently.  Install a drop flow so
3743              * that future packets of the flow are inexpensively dropped
3744              * in the kernel. */
3745             VLOG_INFO_RL(&rl, "received packet on unassociated datapath port "
3746                               "%"PRIu32, odp_in_port);
3747
3748             drop_key = drop_key_lookup(backer, upcall->key, upcall->key_len);
3749             if (!drop_key) {
3750                 drop_key = xmalloc(sizeof *drop_key);
3751                 drop_key->key = xmemdup(upcall->key, upcall->key_len);
3752                 drop_key->key_len = upcall->key_len;
3753
3754                 hmap_insert(&backer->drop_keys, &drop_key->hmap_node,
3755                             hash_bytes(drop_key->key, drop_key->key_len, 0));
3756                 dpif_flow_put(backer->dpif, DPIF_FP_CREATE | DPIF_FP_MODIFY,
3757                               drop_key->key, drop_key->key_len,
3758                               NULL, 0, NULL, 0, NULL);
3759             }
3760             continue;
3761         }
3762         if (error) {
3763             continue;
3764         }
3765
3766         ofproto->n_missed++;
3767         flow_extract(upcall->packet, flow.skb_priority, flow.skb_mark,
3768                      &flow.tunnel, &flow.in_port, &miss->flow);
3769
3770         /* Add other packets to a to-do list. */
3771         hash = flow_hash(&miss->flow, 0);
3772         existing_miss = flow_miss_find(&todo, ofproto, &miss->flow, hash);
3773         if (!existing_miss) {
3774             hmap_insert(&todo, &miss->hmap_node, hash);
3775             miss->ofproto = ofproto;
3776             miss->key = upcall->key;
3777             miss->key_len = upcall->key_len;
3778             miss->upcall_type = upcall->type;
3779             list_init(&miss->packets);
3780
3781             n_misses++;
3782         } else {
3783             miss = existing_miss;
3784         }
3785         list_push_back(&miss->packets, &upcall->packet->list_node);
3786     }
3787
3788     /* Process each element in the to-do list, constructing the set of
3789      * operations to batch. */
3790     n_ops = 0;
3791     HMAP_FOR_EACH (miss, hmap_node, &todo) {
3792         handle_flow_miss(miss, flow_miss_ops, &n_ops);
3793     }
3794     ovs_assert(n_ops <= ARRAY_SIZE(flow_miss_ops));
3795
3796     /* Execute batch. */
3797     for (i = 0; i < n_ops; i++) {
3798         dpif_ops[i] = &flow_miss_ops[i].dpif_op;
3799     }
3800     dpif_operate(backer->dpif, dpif_ops, n_ops);
3801
3802     for (i = 0; i < n_ops; i++) {
3803         if (dpif_ops[i]->error != 0
3804             && flow_miss_ops[i].dpif_op.type == DPIF_OP_FLOW_PUT
3805             && flow_miss_ops[i].subfacet) {
3806             struct subfacet *subfacet = flow_miss_ops[i].subfacet;
3807
3808             COVERAGE_INC(subfacet_install_fail);
3809
3810             subfacet->path = SF_NOT_INSTALLED;
3811         }
3812
3813         /* Free memory. */
3814         if (flow_miss_ops[i].xout_garbage) {
3815             xlate_out_uninit(&flow_miss_ops[i].xout);
3816         }
3817     }
3818     hmap_destroy(&todo);
3819 }
3820
3821 static enum { SFLOW_UPCALL, MISS_UPCALL, BAD_UPCALL, FLOW_SAMPLE_UPCALL,
3822               IPFIX_UPCALL }
3823 classify_upcall(const struct dpif_upcall *upcall)
3824 {
3825     size_t userdata_len;
3826     union user_action_cookie cookie;
3827
3828     /* First look at the upcall type. */
3829     switch (upcall->type) {
3830     case DPIF_UC_ACTION:
3831         break;
3832
3833     case DPIF_UC_MISS:
3834         return MISS_UPCALL;
3835
3836     case DPIF_N_UC_TYPES:
3837     default:
3838         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
3839         return BAD_UPCALL;
3840     }
3841
3842     /* "action" upcalls need a closer look. */
3843     if (!upcall->userdata) {
3844         VLOG_WARN_RL(&rl, "action upcall missing cookie");
3845         return BAD_UPCALL;
3846     }
3847     userdata_len = nl_attr_get_size(upcall->userdata);
3848     if (userdata_len < sizeof cookie.type
3849         || userdata_len > sizeof cookie) {
3850         VLOG_WARN_RL(&rl, "action upcall cookie has unexpected size %zu",
3851                      userdata_len);
3852         return BAD_UPCALL;
3853     }
3854     memset(&cookie, 0, sizeof cookie);
3855     memcpy(&cookie, nl_attr_get(upcall->userdata), userdata_len);
3856     if (userdata_len == sizeof cookie.sflow
3857         && cookie.type == USER_ACTION_COOKIE_SFLOW) {
3858         return SFLOW_UPCALL;
3859     } else if (userdata_len == sizeof cookie.slow_path
3860                && cookie.type == USER_ACTION_COOKIE_SLOW_PATH) {
3861         return MISS_UPCALL;
3862     } else if (userdata_len == sizeof cookie.flow_sample
3863                && cookie.type == USER_ACTION_COOKIE_FLOW_SAMPLE) {
3864         return FLOW_SAMPLE_UPCALL;
3865     } else if (userdata_len == sizeof cookie.ipfix
3866                && cookie.type == USER_ACTION_COOKIE_IPFIX) {
3867         return IPFIX_UPCALL;
3868     } else {
3869         VLOG_WARN_RL(&rl, "invalid user cookie of type %"PRIu16
3870                      " and size %zu", cookie.type, userdata_len);
3871         return BAD_UPCALL;
3872     }
3873 }
3874
3875 static void
3876 handle_sflow_upcall(struct dpif_backer *backer,
3877                     const struct dpif_upcall *upcall)
3878 {
3879     struct ofproto_dpif *ofproto;
3880     union user_action_cookie cookie;
3881     struct flow flow;
3882     odp_port_t odp_in_port;
3883
3884     if (ofproto_receive(backer, upcall->packet, upcall->key, upcall->key_len,
3885                         &flow, NULL, &ofproto, &odp_in_port)
3886         || !ofproto->sflow) {
3887         return;
3888     }
3889
3890     memset(&cookie, 0, sizeof cookie);
3891     memcpy(&cookie, nl_attr_get(upcall->userdata), sizeof cookie.sflow);
3892     dpif_sflow_received(ofproto->sflow, upcall->packet, &flow,
3893                         odp_in_port, &cookie);
3894 }
3895
3896 static void
3897 handle_flow_sample_upcall(struct dpif_backer *backer,
3898                           const struct dpif_upcall *upcall)
3899 {
3900     struct ofproto_dpif *ofproto;
3901     union user_action_cookie cookie;
3902     struct flow flow;
3903
3904     if (ofproto_receive(backer, upcall->packet, upcall->key, upcall->key_len,
3905                         &flow, NULL, &ofproto, NULL)
3906         || !ofproto->ipfix) {
3907         return;
3908     }
3909
3910     memset(&cookie, 0, sizeof cookie);
3911     memcpy(&cookie, nl_attr_get(upcall->userdata), sizeof cookie.flow_sample);
3912
3913     /* The flow reflects exactly the contents of the packet.  Sample
3914      * the packet using it. */
3915     dpif_ipfix_flow_sample(ofproto->ipfix, upcall->packet, &flow,
3916                            cookie.flow_sample.collector_set_id,
3917                            cookie.flow_sample.probability,
3918                            cookie.flow_sample.obs_domain_id,
3919                            cookie.flow_sample.obs_point_id);
3920 }
3921
3922 static void
3923 handle_ipfix_upcall(struct dpif_backer *backer,
3924                     const struct dpif_upcall *upcall)
3925 {
3926     struct ofproto_dpif *ofproto;
3927     struct flow flow;
3928
3929     if (ofproto_receive(backer, upcall->packet, upcall->key, upcall->key_len,
3930                         &flow, NULL, &ofproto, NULL)
3931         || !ofproto->ipfix) {
3932         return;
3933     }
3934
3935     /* The flow reflects exactly the contents of the packet.  Sample
3936      * the packet using it. */
3937     dpif_ipfix_bridge_sample(ofproto->ipfix, upcall->packet, &flow);
3938 }
3939
3940 static int
3941 handle_upcalls(struct dpif_backer *backer, unsigned int max_batch)
3942 {
3943     struct dpif_upcall misses[FLOW_MISS_MAX_BATCH];
3944     struct ofpbuf miss_bufs[FLOW_MISS_MAX_BATCH];
3945     uint64_t miss_buf_stubs[FLOW_MISS_MAX_BATCH][4096 / 8];
3946     int n_processed;
3947     int n_misses;
3948     int i;
3949
3950     ovs_assert(max_batch <= FLOW_MISS_MAX_BATCH);
3951
3952     n_misses = 0;
3953     for (n_processed = 0; n_processed < max_batch; n_processed++) {
3954         struct dpif_upcall *upcall = &misses[n_misses];
3955         struct ofpbuf *buf = &miss_bufs[n_misses];
3956         int error;
3957
3958         ofpbuf_use_stub(buf, miss_buf_stubs[n_misses],
3959                         sizeof miss_buf_stubs[n_misses]);
3960         error = dpif_recv(backer->dpif, upcall, buf);
3961         if (error) {
3962             ofpbuf_uninit(buf);
3963             break;
3964         }
3965
3966         switch (classify_upcall(upcall)) {
3967         case MISS_UPCALL:
3968             /* Handle it later. */
3969             n_misses++;
3970             break;
3971
3972         case SFLOW_UPCALL:
3973             handle_sflow_upcall(backer, upcall);
3974             ofpbuf_uninit(buf);
3975             break;
3976
3977         case FLOW_SAMPLE_UPCALL:
3978             handle_flow_sample_upcall(backer, upcall);
3979             ofpbuf_uninit(buf);
3980             break;
3981
3982         case IPFIX_UPCALL:
3983             handle_ipfix_upcall(backer, upcall);
3984             ofpbuf_uninit(buf);
3985             break;
3986
3987         case BAD_UPCALL:
3988             ofpbuf_uninit(buf);
3989             break;
3990         }
3991     }
3992
3993     /* Handle deferred MISS_UPCALL processing. */
3994     handle_miss_upcalls(backer, misses, n_misses);
3995     for (i = 0; i < n_misses; i++) {
3996         ofpbuf_uninit(&miss_bufs[i]);
3997     }
3998
3999     return n_processed;
4000 }
4001 \f
4002 /* Flow expiration. */
4003
4004 static int subfacet_max_idle(const struct dpif_backer *);
4005 static void update_stats(struct dpif_backer *);
4006 static void rule_expire(struct rule_dpif *);
4007 static void expire_subfacets(struct dpif_backer *, int dp_max_idle);
4008
4009 /* This function is called periodically by run().  Its job is to collect
4010  * updates for the flows that have been installed into the datapath, most
4011  * importantly when they last were used, and then use that information to
4012  * expire flows that have not been used recently.
4013  *
4014  * Returns the number of milliseconds after which it should be called again. */
4015 static int
4016 expire(struct dpif_backer *backer)
4017 {
4018     struct ofproto_dpif *ofproto;
4019     size_t n_subfacets;
4020     int max_idle;
4021
4022     /* Periodically clear out the drop keys in an effort to keep them
4023      * relatively few. */
4024     drop_key_clear(backer);
4025
4026     /* Update stats for each flow in the backer. */
4027     update_stats(backer);
4028
4029     n_subfacets = hmap_count(&backer->subfacets);
4030     if (n_subfacets) {
4031         struct subfacet *subfacet;
4032         long long int total, now;
4033
4034         total = 0;
4035         now = time_msec();
4036         HMAP_FOR_EACH (subfacet, hmap_node, &backer->subfacets) {
4037             total += now - subfacet->created;
4038         }
4039         backer->avg_subfacet_life += total / n_subfacets;
4040     }
4041     backer->avg_subfacet_life /= 2;
4042
4043     backer->avg_n_subfacet += n_subfacets;
4044     backer->avg_n_subfacet /= 2;
4045
4046     backer->max_n_subfacet = MAX(backer->max_n_subfacet, n_subfacets);
4047
4048     max_idle = subfacet_max_idle(backer);
4049     expire_subfacets(backer, max_idle);
4050
4051     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4052         struct rule *rule, *next_rule;
4053
4054         if (ofproto->backer != backer) {
4055             continue;
4056         }
4057
4058         /* Expire OpenFlow flows whose idle_timeout or hard_timeout
4059          * has passed. */
4060         LIST_FOR_EACH_SAFE (rule, next_rule, expirable,
4061                             &ofproto->up.expirable) {
4062             rule_expire(rule_dpif_cast(rule));
4063         }
4064
4065         /* All outstanding data in existing flows has been accounted, so it's a
4066          * good time to do bond rebalancing. */
4067         if (ofproto->has_bonded_bundles) {
4068             struct ofbundle *bundle;
4069
4070             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
4071                 if (bundle->bond) {
4072                     bond_rebalance(bundle->bond, &backer->revalidate_set);
4073                 }
4074             }
4075         }
4076     }
4077
4078     return MIN(max_idle, 1000);
4079 }
4080
4081 /* Updates flow table statistics given that the datapath just reported 'stats'
4082  * as 'subfacet''s statistics. */
4083 static void
4084 update_subfacet_stats(struct subfacet *subfacet,
4085                       const struct dpif_flow_stats *stats)
4086 {
4087     struct facet *facet = subfacet->facet;
4088     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4089     struct dpif_flow_stats diff;
4090
4091     diff.tcp_flags = stats->tcp_flags;
4092     diff.used = stats->used;
4093
4094     if (stats->n_packets >= subfacet->dp_packet_count) {
4095         diff.n_packets = stats->n_packets - subfacet->dp_packet_count;
4096     } else {
4097         VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
4098         diff.n_packets = 0;
4099     }
4100
4101     if (stats->n_bytes >= subfacet->dp_byte_count) {
4102         diff.n_bytes = stats->n_bytes - subfacet->dp_byte_count;
4103     } else {
4104         VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
4105         diff.n_bytes = 0;
4106     }
4107
4108     ofproto->n_hit += diff.n_packets;
4109     subfacet->dp_packet_count = stats->n_packets;
4110     subfacet->dp_byte_count = stats->n_bytes;
4111     subfacet_update_stats(subfacet, &diff);
4112
4113     if (facet->accounted_bytes < facet->byte_count) {
4114         facet_learn(facet);
4115         facet_account(facet);
4116         facet->accounted_bytes = facet->byte_count;
4117     }
4118 }
4119
4120 /* 'key' with length 'key_len' bytes is a flow in 'dpif' that we know nothing
4121  * about, or a flow that shouldn't be installed but was anyway.  Delete it. */
4122 static void
4123 delete_unexpected_flow(struct dpif_backer *backer,
4124                        const struct nlattr *key, size_t key_len)
4125 {
4126     if (!VLOG_DROP_WARN(&rl)) {
4127         struct ds s;
4128
4129         ds_init(&s);
4130         odp_flow_key_format(key, key_len, &s);
4131         VLOG_WARN("unexpected flow: %s", ds_cstr(&s));
4132         ds_destroy(&s);
4133     }
4134
4135     COVERAGE_INC(facet_unexpected);
4136     dpif_flow_del(backer->dpif, key, key_len, NULL);
4137 }
4138
4139 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
4140  *
4141  * This function also pushes statistics updates to rules which each facet
4142  * resubmits into.  Generally these statistics will be accurate.  However, if a
4143  * facet changes the rule it resubmits into at some time in between
4144  * update_stats() runs, it is possible that statistics accrued to the
4145  * old rule will be incorrectly attributed to the new rule.  This could be
4146  * avoided by calling update_stats() whenever rules are created or
4147  * deleted.  However, the performance impact of making so many calls to the
4148  * datapath do not justify the benefit of having perfectly accurate statistics.
4149  *
4150  * In addition, this function maintains per ofproto flow hit counts. The patch
4151  * port is not treated specially. e.g. A packet ingress from br0 patched into
4152  * br1 will increase the hit count of br0 by 1, however, does not affect
4153  * the hit or miss counts of br1.
4154  */
4155 static void
4156 update_stats(struct dpif_backer *backer)
4157 {
4158     const struct dpif_flow_stats *stats;
4159     struct dpif_flow_dump dump;
4160     const struct nlattr *key, *mask;
4161     size_t key_len, mask_len;
4162
4163     dpif_flow_dump_start(&dump, backer->dpif);
4164     while (dpif_flow_dump_next(&dump, &key, &key_len,
4165                                &mask, &mask_len, NULL, NULL, &stats)) {
4166         struct subfacet *subfacet;
4167         uint32_t key_hash;
4168
4169         key_hash = odp_flow_key_hash(key, key_len);
4170         subfacet = subfacet_find(backer, key, key_len, key_hash);
4171         switch (subfacet ? subfacet->path : SF_NOT_INSTALLED) {
4172         case SF_FAST_PATH:
4173             update_subfacet_stats(subfacet, stats);
4174             break;
4175
4176         case SF_SLOW_PATH:
4177             /* Stats are updated per-packet. */
4178             break;
4179
4180         case SF_NOT_INSTALLED:
4181         default:
4182             delete_unexpected_flow(backer, key, key_len);
4183             break;
4184         }
4185         run_fast_rl();
4186     }
4187     dpif_flow_dump_done(&dump);
4188
4189     update_moving_averages(backer);
4190 }
4191
4192 /* Calculates and returns the number of milliseconds of idle time after which
4193  * subfacets should expire from the datapath.  When a subfacet expires, we fold
4194  * its statistics into its facet, and when a facet's last subfacet expires, we
4195  * fold its statistic into its rule. */
4196 static int
4197 subfacet_max_idle(const struct dpif_backer *backer)
4198 {
4199     /*
4200      * Idle time histogram.
4201      *
4202      * Most of the time a switch has a relatively small number of subfacets.
4203      * When this is the case we might as well keep statistics for all of them
4204      * in userspace and to cache them in the kernel datapath for performance as
4205      * well.
4206      *
4207      * As the number of subfacets increases, the memory required to maintain
4208      * statistics about them in userspace and in the kernel becomes
4209      * significant.  However, with a large number of subfacets it is likely
4210      * that only a few of them are "heavy hitters" that consume a large amount
4211      * of bandwidth.  At this point, only heavy hitters are worth caching in
4212      * the kernel and maintaining in userspaces; other subfacets we can
4213      * discard.
4214      *
4215      * The technique used to compute the idle time is to build a histogram with
4216      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each subfacet
4217      * that is installed in the kernel gets dropped in the appropriate bucket.
4218      * After the histogram has been built, we compute the cutoff so that only
4219      * the most-recently-used 1% of subfacets (but at least
4220      * flow_eviction_threshold flows) are kept cached.  At least
4221      * the most-recently-used bucket of subfacets is kept, so actually an
4222      * arbitrary number of subfacets can be kept in any given expiration run
4223      * (though the next run will delete most of those unless they receive
4224      * additional data).
4225      *
4226      * This requires a second pass through the subfacets, in addition to the
4227      * pass made by update_stats(), because the former function never looks at
4228      * uninstallable subfacets.
4229      */
4230     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
4231     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
4232     int buckets[N_BUCKETS] = { 0 };
4233     int total, subtotal, bucket;
4234     struct subfacet *subfacet;
4235     long long int now;
4236     int i;
4237
4238     total = hmap_count(&backer->subfacets);
4239     if (total <= flow_eviction_threshold) {
4240         return N_BUCKETS * BUCKET_WIDTH;
4241     }
4242
4243     /* Build histogram. */
4244     now = time_msec();
4245     HMAP_FOR_EACH (subfacet, hmap_node, &backer->subfacets) {
4246         long long int idle = now - subfacet->used;
4247         int bucket = (idle <= 0 ? 0
4248                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4249                       : (unsigned int) idle / BUCKET_WIDTH);
4250         buckets[bucket]++;
4251     }
4252
4253     /* Find the first bucket whose flows should be expired. */
4254     subtotal = bucket = 0;
4255     do {
4256         subtotal += buckets[bucket++];
4257     } while (bucket < N_BUCKETS &&
4258              subtotal < MAX(flow_eviction_threshold, total / 100));
4259
4260     if (VLOG_IS_DBG_ENABLED()) {
4261         struct ds s;
4262
4263         ds_init(&s);
4264         ds_put_cstr(&s, "keep");
4265         for (i = 0; i < N_BUCKETS; i++) {
4266             if (i == bucket) {
4267                 ds_put_cstr(&s, ", drop");
4268             }
4269             if (buckets[i]) {
4270                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4271             }
4272         }
4273         VLOG_INFO("%s (msec:count)", ds_cstr(&s));
4274         ds_destroy(&s);
4275     }
4276
4277     return bucket * BUCKET_WIDTH;
4278 }
4279
4280 static void
4281 expire_subfacets(struct dpif_backer *backer, int dp_max_idle)
4282 {
4283     /* Cutoff time for most flows. */
4284     long long int normal_cutoff = time_msec() - dp_max_idle;
4285
4286     /* We really want to keep flows for special protocols around, so use a more
4287      * conservative cutoff. */
4288     long long int special_cutoff = time_msec() - 10000;
4289
4290     struct subfacet *subfacet, *next_subfacet;
4291     struct subfacet *batch[SUBFACET_DESTROY_MAX_BATCH];
4292     int n_batch;
4293
4294     n_batch = 0;
4295     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
4296                         &backer->subfacets) {
4297         long long int cutoff;
4298
4299         cutoff = (subfacet->facet->xout.slow & (SLOW_CFM | SLOW_BFD | SLOW_LACP
4300                                                 | SLOW_STP)
4301                   ? special_cutoff
4302                   : normal_cutoff);
4303         if (subfacet->used < cutoff) {
4304             if (subfacet->path != SF_NOT_INSTALLED) {
4305                 batch[n_batch++] = subfacet;
4306                 if (n_batch >= SUBFACET_DESTROY_MAX_BATCH) {
4307                     subfacet_destroy_batch(backer, batch, n_batch);
4308                     n_batch = 0;
4309                 }
4310             } else {
4311                 subfacet_destroy(subfacet);
4312             }
4313         }
4314     }
4315
4316     if (n_batch > 0) {
4317         subfacet_destroy_batch(backer, batch, n_batch);
4318     }
4319 }
4320
4321 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4322  * then delete it entirely. */
4323 static void
4324 rule_expire(struct rule_dpif *rule)
4325 {
4326     struct facet *facet, *next_facet;
4327     long long int now;
4328     uint8_t reason;
4329
4330     if (rule->up.pending) {
4331         /* We'll have to expire it later. */
4332         return;
4333     }
4334
4335     /* Has 'rule' expired? */
4336     now = time_msec();
4337     if (rule->up.hard_timeout
4338         && now > rule->up.modified + rule->up.hard_timeout * 1000) {
4339         reason = OFPRR_HARD_TIMEOUT;
4340     } else if (rule->up.idle_timeout
4341                && now > rule->up.used + rule->up.idle_timeout * 1000) {
4342         reason = OFPRR_IDLE_TIMEOUT;
4343     } else {
4344         return;
4345     }
4346
4347     COVERAGE_INC(ofproto_dpif_expired);
4348
4349     /* Update stats.  (This is a no-op if the rule expired due to an idle
4350      * timeout, because that only happens when the rule has no facets left.) */
4351     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4352         facet_remove(facet);
4353     }
4354
4355     /* Get rid of the rule. */
4356     ofproto_rule_expire(&rule->up, reason);
4357 }
4358 \f
4359 /* Facets. */
4360
4361 /* Creates and returns a new facet based on 'miss'.
4362  *
4363  * The caller must already have determined that no facet with an identical
4364  * 'miss->flow' exists in 'miss->ofproto'.
4365  *
4366  * 'rule' and 'xout' must have been created based on 'miss'.
4367  *
4368  * 'facet'' statistics are initialized based on 'stats'.
4369  *
4370  * The facet will initially have no subfacets.  The caller should create (at
4371  * least) one subfacet with subfacet_create(). */
4372 static struct facet *
4373 facet_create(const struct flow_miss *miss, struct rule_dpif *rule,
4374              struct xlate_out *xout, struct dpif_flow_stats *stats)
4375 {
4376     struct ofproto_dpif *ofproto = miss->ofproto;
4377     struct facet *facet;
4378     struct match match;
4379
4380     facet = xzalloc(sizeof *facet);
4381     facet->packet_count = facet->prev_packet_count = stats->n_packets;
4382     facet->byte_count = facet->prev_byte_count = stats->n_bytes;
4383     facet->tcp_flags = stats->tcp_flags;
4384     facet->used = stats->used;
4385     facet->flow = miss->flow;
4386     facet->learn_rl = time_msec() + 500;
4387     facet->rule = rule;
4388
4389     list_push_back(&facet->rule->facets, &facet->list_node);
4390     list_init(&facet->subfacets);
4391     netflow_flow_init(&facet->nf_flow);
4392     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
4393
4394     xlate_out_copy(&facet->xout, xout);
4395
4396     match_init(&match, &facet->flow, &facet->xout.wc);
4397     cls_rule_init(&facet->cr, &match, OFP_DEFAULT_PRIORITY);
4398     classifier_insert(&ofproto->facets, &facet->cr);
4399
4400     facet->nf_flow.output_iface = facet->xout.nf_output_iface;
4401
4402     return facet;
4403 }
4404
4405 static void
4406 facet_free(struct facet *facet)
4407 {
4408     if (facet) {
4409         xlate_out_uninit(&facet->xout);
4410         free(facet);
4411     }
4412 }
4413
4414 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
4415  * 'packet', which arrived on 'in_port'. */
4416 static bool
4417 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
4418                     const struct nlattr *odp_actions, size_t actions_len,
4419                     struct ofpbuf *packet)
4420 {
4421     struct odputil_keybuf keybuf;
4422     struct ofpbuf key;
4423     int error;
4424
4425     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
4426     odp_flow_key_from_flow(&key, flow,
4427                            ofp_port_to_odp_port(ofproto, flow->in_port.ofp_port));
4428
4429     error = dpif_execute(ofproto->backer->dpif, key.data, key.size,
4430                          odp_actions, actions_len, packet);
4431     return !error;
4432 }
4433
4434 /* Remove 'facet' from its ofproto and free up the associated memory:
4435  *
4436  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
4437  *     rule's statistics, via subfacet_uninstall().
4438  *
4439  *   - Removes 'facet' from its rule and from ofproto->facets.
4440  */
4441 static void
4442 facet_remove(struct facet *facet)
4443 {
4444     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4445     struct subfacet *subfacet, *next_subfacet;
4446
4447     ovs_assert(!list_is_empty(&facet->subfacets));
4448
4449     /* First uninstall all of the subfacets to get final statistics. */
4450     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4451         subfacet_uninstall(subfacet);
4452     }
4453
4454     /* Flush the final stats to the rule.
4455      *
4456      * This might require us to have at least one subfacet around so that we
4457      * can use its actions for accounting in facet_account(), which is why we
4458      * have uninstalled but not yet destroyed the subfacets. */
4459     facet_flush_stats(facet);
4460
4461     /* Now we're really all done so destroy everything. */
4462     LIST_FOR_EACH_SAFE (subfacet, next_subfacet, list_node,
4463                         &facet->subfacets) {
4464         subfacet_destroy__(subfacet);
4465     }
4466     classifier_remove(&ofproto->facets, &facet->cr);
4467     cls_rule_destroy(&facet->cr);
4468     list_remove(&facet->list_node);
4469     facet_free(facet);
4470 }
4471
4472 /* Feed information from 'facet' back into the learning table to keep it in
4473  * sync with what is actually flowing through the datapath. */
4474 static void
4475 facet_learn(struct facet *facet)
4476 {
4477     long long int now = time_msec();
4478
4479     if (!facet->xout.has_fin_timeout && now < facet->learn_rl) {
4480         return;
4481     }
4482
4483     facet->learn_rl = now + 500;
4484
4485     if (!facet->xout.has_learn
4486         && !facet->xout.has_normal
4487         && (!facet->xout.has_fin_timeout
4488             || !(facet->tcp_flags & (TCP_FIN | TCP_RST)))) {
4489         return;
4490     }
4491
4492     facet_push_stats(facet, true);
4493 }
4494
4495 static void
4496 facet_account(struct facet *facet)
4497 {
4498     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4499     const struct nlattr *a;
4500     unsigned int left;
4501     ovs_be16 vlan_tci;
4502     uint64_t n_bytes;
4503
4504     if (!facet->xout.has_normal || !ofproto->has_bonded_bundles) {
4505         return;
4506     }
4507     n_bytes = facet->byte_count - facet->accounted_bytes;
4508
4509     /* This loop feeds byte counters to bond_account() for rebalancing to use
4510      * as a basis.  We also need to track the actual VLAN on which the packet
4511      * is going to be sent to ensure that it matches the one passed to
4512      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
4513      * hash bucket.)
4514      *
4515      * We use the actions from an arbitrary subfacet because they should all
4516      * be equally valid for our purpose. */
4517     vlan_tci = facet->flow.vlan_tci;
4518     NL_ATTR_FOR_EACH_UNSAFE (a, left, facet->xout.odp_actions.data,
4519                              facet->xout.odp_actions.size) {
4520         const struct ovs_action_push_vlan *vlan;
4521         struct ofport_dpif *port;
4522
4523         switch (nl_attr_type(a)) {
4524         case OVS_ACTION_ATTR_OUTPUT:
4525             port = get_odp_port(ofproto, nl_attr_get_odp_port(a));
4526             if (port && port->bundle && port->bundle->bond) {
4527                 bond_account(port->bundle->bond, &facet->flow,
4528                              vlan_tci_to_vid(vlan_tci), n_bytes);
4529             }
4530             break;
4531
4532         case OVS_ACTION_ATTR_POP_VLAN:
4533             vlan_tci = htons(0);
4534             break;
4535
4536         case OVS_ACTION_ATTR_PUSH_VLAN:
4537             vlan = nl_attr_get(a);
4538             vlan_tci = vlan->vlan_tci;
4539             break;
4540         }
4541     }
4542 }
4543
4544 /* Returns true if the only action for 'facet' is to send to the controller.
4545  * (We don't report NetFlow expiration messages for such facets because they
4546  * are just part of the control logic for the network, not real traffic). */
4547 static bool
4548 facet_is_controller_flow(struct facet *facet)
4549 {
4550     if (facet) {
4551         const struct rule *rule = &facet->rule->up;
4552         const struct ofpact *ofpacts = rule->ofpacts;
4553         size_t ofpacts_len = rule->ofpacts_len;
4554
4555         if (ofpacts_len > 0 &&
4556             ofpacts->type == OFPACT_CONTROLLER &&
4557             ofpact_next(ofpacts) >= ofpact_end(ofpacts, ofpacts_len)) {
4558             return true;
4559         }
4560     }
4561     return false;
4562 }
4563
4564 /* Folds all of 'facet''s statistics into its rule.  Also updates the
4565  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
4566  * 'facet''s statistics in the datapath should have been zeroed and folded into
4567  * its packet and byte counts before this function is called. */
4568 static void
4569 facet_flush_stats(struct facet *facet)
4570 {
4571     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4572     struct subfacet *subfacet;
4573
4574     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4575         ovs_assert(!subfacet->dp_byte_count);
4576         ovs_assert(!subfacet->dp_packet_count);
4577     }
4578
4579     facet_push_stats(facet, false);
4580     if (facet->accounted_bytes < facet->byte_count) {
4581         facet_account(facet);
4582         facet->accounted_bytes = facet->byte_count;
4583     }
4584
4585     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
4586         struct ofexpired expired;
4587         expired.flow = facet->flow;
4588         expired.packet_count = facet->packet_count;
4589         expired.byte_count = facet->byte_count;
4590         expired.used = facet->used;
4591         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4592     }
4593
4594     /* Reset counters to prevent double counting if 'facet' ever gets
4595      * reinstalled. */
4596     facet_reset_counters(facet);
4597
4598     netflow_flow_clear(&facet->nf_flow);
4599     facet->tcp_flags = 0;
4600 }
4601
4602 /* Searches 'ofproto''s table of facets for one which would be responsible for
4603  * 'flow'.  Returns it if found, otherwise a null pointer.
4604  *
4605  * The returned facet might need revalidation; use facet_lookup_valid()
4606  * instead if that is important. */
4607 static struct facet *
4608 facet_find(struct ofproto_dpif *ofproto, const struct flow *flow)
4609 {
4610     struct cls_rule *cr = classifier_lookup(&ofproto->facets, flow, NULL);
4611     return cr ? CONTAINER_OF(cr, struct facet, cr) : NULL;
4612 }
4613
4614 /* Searches 'ofproto''s table of facets for one capable that covers
4615  * 'flow'.  Returns it if found, otherwise a null pointer.
4616  *
4617  * The returned facet is guaranteed to be valid. */
4618 static struct facet *
4619 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow)
4620 {
4621     struct facet *facet;
4622
4623     facet = facet_find(ofproto, flow);
4624     if (facet
4625         && (ofproto->backer->need_revalidate
4626             || tag_set_intersects(&ofproto->backer->revalidate_set,
4627                                   facet->xout.tags))
4628         && !facet_revalidate(facet)) {
4629         return NULL;
4630     }
4631
4632     return facet;
4633 }
4634
4635 static bool
4636 facet_check_consistency(struct facet *facet)
4637 {
4638     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 15);
4639
4640     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4641
4642     struct xlate_out xout;
4643     struct xlate_in xin;
4644
4645     struct rule_dpif *rule;
4646     bool ok;
4647
4648     /* Check the rule for consistency. */
4649     rule = rule_dpif_lookup(ofproto, &facet->flow, NULL);
4650     if (rule != facet->rule) {
4651         if (!VLOG_DROP_WARN(&rl)) {
4652             struct ds s = DS_EMPTY_INITIALIZER;
4653
4654             flow_format(&s, &facet->flow);
4655             ds_put_format(&s, ": facet associated with wrong rule (was "
4656                           "table=%"PRIu8",", facet->rule->up.table_id);
4657             cls_rule_format(&facet->rule->up.cr, &s);
4658             ds_put_format(&s, ") (should have been table=%"PRIu8",",
4659                           rule->up.table_id);
4660             cls_rule_format(&rule->up.cr, &s);
4661             ds_put_char(&s, ')');
4662
4663             VLOG_WARN("%s", ds_cstr(&s));
4664             ds_destroy(&s);
4665         }
4666         return false;
4667     }
4668
4669     /* Check the datapath actions for consistency. */
4670     xlate_in_init(&xin, ofproto, &facet->flow, rule, 0, NULL);
4671     xlate_actions(&xin, &xout);
4672
4673     ok = ofpbuf_equal(&facet->xout.odp_actions, &xout.odp_actions)
4674         && facet->xout.slow == xout.slow;
4675     if (!ok && !VLOG_DROP_WARN(&rl)) {
4676         struct ds s = DS_EMPTY_INITIALIZER;
4677
4678         flow_format(&s, &facet->flow);
4679         ds_put_cstr(&s, ": inconsistency in facet");
4680
4681         if (!ofpbuf_equal(&facet->xout.odp_actions, &xout.odp_actions)) {
4682             ds_put_cstr(&s, " (actions were: ");
4683             format_odp_actions(&s, facet->xout.odp_actions.data,
4684                                facet->xout.odp_actions.size);
4685             ds_put_cstr(&s, ") (correct actions: ");
4686             format_odp_actions(&s, xout.odp_actions.data,
4687                                xout.odp_actions.size);
4688             ds_put_char(&s, ')');
4689         }
4690
4691         if (facet->xout.slow != xout.slow) {
4692             ds_put_format(&s, " slow path incorrect. should be %d", xout.slow);
4693         }
4694
4695         VLOG_WARN("%s", ds_cstr(&s));
4696         ds_destroy(&s);
4697     }
4698     xlate_out_uninit(&xout);
4699
4700     return ok;
4701 }
4702
4703 /* Re-searches the classifier for 'facet':
4704  *
4705  *   - If the rule found is different from 'facet''s current rule, moves
4706  *     'facet' to the new rule and recompiles its actions.
4707  *
4708  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
4709  *     where it is and recompiles its actions anyway.
4710  *
4711  *   - If any of 'facet''s subfacets correspond to a new flow according to
4712  *     ofproto_receive(), 'facet' is removed.
4713  *
4714  *   Returns true if 'facet' is still valid.  False if 'facet' was removed. */
4715 static bool
4716 facet_revalidate(struct facet *facet)
4717 {
4718     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4719     struct rule_dpif *new_rule;
4720     struct subfacet *subfacet;
4721     struct flow_wildcards wc;
4722     struct xlate_out xout;
4723     struct xlate_in xin;
4724
4725     COVERAGE_INC(facet_revalidate);
4726
4727     /* Check that child subfacets still correspond to this facet.  Tunnel
4728      * configuration changes could cause a subfacet's OpenFlow in_port to
4729      * change. */
4730     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4731         struct ofproto_dpif *recv_ofproto;
4732         struct flow recv_flow;
4733         int error;
4734
4735         error = ofproto_receive(ofproto->backer, NULL, subfacet->key,
4736                                 subfacet->key_len, &recv_flow, NULL,
4737                                 &recv_ofproto, NULL);
4738         if (error
4739             || recv_ofproto != ofproto
4740             || facet != facet_find(ofproto, &recv_flow)) {
4741             facet_remove(facet);
4742             return false;
4743         }
4744     }
4745
4746     flow_wildcards_init_catchall(&wc);
4747     new_rule = rule_dpif_lookup(ofproto, &facet->flow, &wc);
4748
4749     /* Calculate new datapath actions.
4750      *
4751      * We do not modify any 'facet' state yet, because we might need to, e.g.,
4752      * emit a NetFlow expiration and, if so, we need to have the old state
4753      * around to properly compose it. */
4754     xlate_in_init(&xin, ofproto, &facet->flow, new_rule, 0, NULL);
4755     xlate_actions(&xin, &xout);
4756     flow_wildcards_or(&xout.wc, &xout.wc, &wc);
4757
4758     /* A facet's slow path reason should only change under dramatic
4759      * circumstances.  Rather than try to update everything, it's simpler to
4760      * remove the facet and start over.
4761      *
4762      * More importantly, if a facet's wildcards change, it will be relatively
4763      * difficult to figure out if its subfacets still belong to it, and if not
4764      * which facet they may belong to.  Again, to avoid the complexity, we
4765      * simply give up instead. */
4766     if (facet->xout.slow != xout.slow
4767         || memcmp(&facet->xout.wc, &xout.wc, sizeof xout.wc)) {
4768         facet_remove(facet);
4769         xlate_out_uninit(&xout);
4770         return false;
4771     }
4772
4773     if (!ofpbuf_equal(&facet->xout.odp_actions, &xout.odp_actions)) {
4774         LIST_FOR_EACH(subfacet, list_node, &facet->subfacets) {
4775             if (subfacet->path == SF_FAST_PATH) {
4776                 struct dpif_flow_stats stats;
4777
4778                 subfacet_install(subfacet, &xout.odp_actions, &stats);
4779                 subfacet_update_stats(subfacet, &stats);
4780             }
4781         }
4782
4783         facet_flush_stats(facet);
4784
4785         ofpbuf_clear(&facet->xout.odp_actions);
4786         ofpbuf_put(&facet->xout.odp_actions, xout.odp_actions.data,
4787                    xout.odp_actions.size);
4788     }
4789
4790     /* Update 'facet' now that we've taken care of all the old state. */
4791     facet->xout.tags = xout.tags;
4792     facet->xout.slow = xout.slow;
4793     facet->xout.has_learn = xout.has_learn;
4794     facet->xout.has_normal = xout.has_normal;
4795     facet->xout.has_fin_timeout = xout.has_fin_timeout;
4796     facet->xout.nf_output_iface = xout.nf_output_iface;
4797     facet->xout.mirrors = xout.mirrors;
4798     facet->nf_flow.output_iface = facet->xout.nf_output_iface;
4799
4800     if (facet->rule != new_rule) {
4801         COVERAGE_INC(facet_changed_rule);
4802         list_remove(&facet->list_node);
4803         list_push_back(&new_rule->facets, &facet->list_node);
4804         facet->rule = new_rule;
4805         facet->used = new_rule->up.created;
4806         facet->prev_used = facet->used;
4807     }
4808
4809     xlate_out_uninit(&xout);
4810     return true;
4811 }
4812
4813 static void
4814 facet_reset_counters(struct facet *facet)
4815 {
4816     facet->packet_count = 0;
4817     facet->byte_count = 0;
4818     facet->prev_packet_count = 0;
4819     facet->prev_byte_count = 0;
4820     facet->accounted_bytes = 0;
4821 }
4822
4823 static void
4824 facet_push_stats(struct facet *facet, bool may_learn)
4825 {
4826     struct dpif_flow_stats stats;
4827
4828     ovs_assert(facet->packet_count >= facet->prev_packet_count);
4829     ovs_assert(facet->byte_count >= facet->prev_byte_count);
4830     ovs_assert(facet->used >= facet->prev_used);
4831
4832     stats.n_packets = facet->packet_count - facet->prev_packet_count;
4833     stats.n_bytes = facet->byte_count - facet->prev_byte_count;
4834     stats.used = facet->used;
4835     stats.tcp_flags = facet->tcp_flags;
4836
4837     if (may_learn || stats.n_packets || facet->used > facet->prev_used) {
4838         struct ofproto_dpif *ofproto =
4839             ofproto_dpif_cast(facet->rule->up.ofproto);
4840
4841         struct ofport_dpif *in_port;
4842         struct xlate_in xin;
4843
4844         facet->prev_packet_count = facet->packet_count;
4845         facet->prev_byte_count = facet->byte_count;
4846         facet->prev_used = facet->used;
4847
4848         in_port = get_ofp_port(ofproto, facet->flow.in_port.ofp_port);
4849         if (in_port && in_port->is_tunnel) {
4850             netdev_vport_inc_rx(in_port->up.netdev, &stats);
4851         }
4852
4853         rule_credit_stats(facet->rule, &stats);
4854         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow,
4855                                  facet->used);
4856         netflow_flow_update_flags(&facet->nf_flow, facet->tcp_flags);
4857         update_mirror_stats(ofproto, facet->xout.mirrors, stats.n_packets,
4858                             stats.n_bytes);
4859
4860         xlate_in_init(&xin, ofproto, &facet->flow, facet->rule,
4861                       stats.tcp_flags, NULL);
4862         xin.resubmit_stats = &stats;
4863         xin.may_learn = may_learn;
4864         xlate_actions_for_side_effects(&xin);
4865     }
4866 }
4867
4868 static void
4869 push_all_stats__(bool run_fast)
4870 {
4871     static long long int rl = LLONG_MIN;
4872     struct ofproto_dpif *ofproto;
4873
4874     if (time_msec() < rl) {
4875         return;
4876     }
4877
4878     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4879         struct cls_cursor cursor;
4880         struct facet *facet;
4881
4882         cls_cursor_init(&cursor, &ofproto->facets, NULL);
4883         CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
4884             facet_push_stats(facet, false);
4885             if (run_fast) {
4886                 run_fast_rl();
4887             }
4888         }
4889     }
4890
4891     rl = time_msec() + 100;
4892 }
4893
4894 static void
4895 push_all_stats(void)
4896 {
4897     push_all_stats__(true);
4898 }
4899
4900 void
4901 rule_credit_stats(struct rule_dpif *rule, const struct dpif_flow_stats *stats)
4902 {
4903     rule->packet_count += stats->n_packets;
4904     rule->byte_count += stats->n_bytes;
4905     ofproto_rule_update_used(&rule->up, stats->used);
4906 }
4907 \f
4908 /* Subfacets. */
4909
4910 static struct subfacet *
4911 subfacet_find(struct dpif_backer *backer, const struct nlattr *key,
4912               size_t key_len, uint32_t key_hash)
4913 {
4914     struct subfacet *subfacet;
4915
4916     HMAP_FOR_EACH_WITH_HASH (subfacet, hmap_node, key_hash,
4917                              &backer->subfacets) {
4918         if (subfacet->key_len == key_len
4919             && !memcmp(key, subfacet->key, key_len)) {
4920             return subfacet;
4921         }
4922     }
4923
4924     return NULL;
4925 }
4926
4927 /* Searches 'facet' (within 'ofproto') for a subfacet with the specified
4928  * 'key_fitness', 'key', and 'key_len' members in 'miss'.  Returns the
4929  * existing subfacet if there is one, otherwise creates and returns a
4930  * new subfacet. */
4931 static struct subfacet *
4932 subfacet_create(struct facet *facet, struct flow_miss *miss,
4933                 long long int now)
4934 {
4935     struct dpif_backer *backer = miss->ofproto->backer;
4936     enum odp_key_fitness key_fitness = miss->key_fitness;
4937     const struct nlattr *key = miss->key;
4938     size_t key_len = miss->key_len;
4939     uint32_t key_hash;
4940     struct subfacet *subfacet;
4941
4942     key_hash = odp_flow_key_hash(key, key_len);
4943
4944     if (list_is_empty(&facet->subfacets)) {
4945         subfacet = &facet->one_subfacet;
4946     } else {
4947         subfacet = subfacet_find(backer, key, key_len, key_hash);
4948         if (subfacet) {
4949             if (subfacet->facet == facet) {
4950                 return subfacet;
4951             }
4952
4953             /* This shouldn't happen. */
4954             VLOG_ERR_RL(&rl, "subfacet with wrong facet");
4955             subfacet_destroy(subfacet);
4956         }
4957
4958         subfacet = xmalloc(sizeof *subfacet);
4959     }
4960
4961     hmap_insert(&backer->subfacets, &subfacet->hmap_node, key_hash);
4962     list_push_back(&facet->subfacets, &subfacet->list_node);
4963     subfacet->facet = facet;
4964     subfacet->key_fitness = key_fitness;
4965     subfacet->key = xmemdup(key, key_len);
4966     subfacet->key_len = key_len;
4967     subfacet->used = now;
4968     subfacet->created = now;
4969     subfacet->dp_packet_count = 0;
4970     subfacet->dp_byte_count = 0;
4971     subfacet->path = SF_NOT_INSTALLED;
4972     subfacet->backer = backer;
4973
4974     backer->subfacet_add_count++;
4975     return subfacet;
4976 }
4977
4978 /* Uninstalls 'subfacet' from the datapath, if it is installed, removes it from
4979  * its facet within 'ofproto', and frees it. */
4980 static void
4981 subfacet_destroy__(struct subfacet *subfacet)
4982 {
4983     struct facet *facet = subfacet->facet;
4984     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4985
4986     /* Update ofproto stats before uninstall the subfacet. */
4987     ofproto->backer->subfacet_del_count++;
4988
4989     subfacet_uninstall(subfacet);
4990     hmap_remove(&subfacet->backer->subfacets, &subfacet->hmap_node);
4991     list_remove(&subfacet->list_node);
4992     free(subfacet->key);
4993     if (subfacet != &facet->one_subfacet) {
4994         free(subfacet);
4995     }
4996 }
4997
4998 /* Destroys 'subfacet', as with subfacet_destroy__(), and then if this was the
4999  * last remaining subfacet in its facet destroys the facet too. */
5000 static void
5001 subfacet_destroy(struct subfacet *subfacet)
5002 {
5003     struct facet *facet = subfacet->facet;
5004
5005     if (list_is_singleton(&facet->subfacets)) {
5006         /* facet_remove() needs at least one subfacet (it will remove it). */
5007         facet_remove(facet);
5008     } else {
5009         subfacet_destroy__(subfacet);
5010     }
5011 }
5012
5013 static void
5014 subfacet_destroy_batch(struct dpif_backer *backer,
5015                        struct subfacet **subfacets, int n)
5016 {
5017     struct dpif_op ops[SUBFACET_DESTROY_MAX_BATCH];
5018     struct dpif_op *opsp[SUBFACET_DESTROY_MAX_BATCH];
5019     struct dpif_flow_stats stats[SUBFACET_DESTROY_MAX_BATCH];
5020     int i;
5021
5022     for (i = 0; i < n; i++) {
5023         ops[i].type = DPIF_OP_FLOW_DEL;
5024         ops[i].u.flow_del.key = subfacets[i]->key;
5025         ops[i].u.flow_del.key_len = subfacets[i]->key_len;
5026         ops[i].u.flow_del.stats = &stats[i];
5027         opsp[i] = &ops[i];
5028     }
5029
5030     dpif_operate(backer->dpif, opsp, n);
5031     for (i = 0; i < n; i++) {
5032         subfacet_reset_dp_stats(subfacets[i], &stats[i]);
5033         subfacets[i]->path = SF_NOT_INSTALLED;
5034         subfacet_destroy(subfacets[i]);
5035         run_fast_rl();
5036     }
5037 }
5038
5039 /* Updates 'subfacet''s datapath flow, setting its actions to 'actions_len'
5040  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
5041  * in the datapath will be zeroed and 'stats' will be updated with traffic new
5042  * since 'subfacet' was last updated.
5043  *
5044  * Returns 0 if successful, otherwise a positive errno value. */
5045 static int
5046 subfacet_install(struct subfacet *subfacet, const struct ofpbuf *odp_actions,
5047                  struct dpif_flow_stats *stats)
5048 {
5049     struct facet *facet = subfacet->facet;
5050     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
5051     enum subfacet_path path = facet->xout.slow ? SF_SLOW_PATH : SF_FAST_PATH;
5052     const struct nlattr *actions = odp_actions->data;
5053     size_t actions_len = odp_actions->size;
5054     struct odputil_keybuf maskbuf;
5055     struct ofpbuf mask;
5056
5057     uint64_t slow_path_stub[128 / 8];
5058     enum dpif_flow_put_flags flags;
5059     int ret;
5060
5061     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
5062     if (stats) {
5063         flags |= DPIF_FP_ZERO_STATS;
5064     }
5065
5066     if (path == SF_SLOW_PATH) {
5067         compose_slow_path(ofproto, &facet->flow, facet->xout.slow,
5068                           slow_path_stub, sizeof slow_path_stub,
5069                           &actions, &actions_len);
5070     }
5071
5072     ofpbuf_use_stack(&mask, &maskbuf, sizeof maskbuf);
5073     if (enable_megaflows) {
5074         odp_flow_key_from_mask(&mask, &facet->xout.wc.masks,
5075                                &facet->flow, UINT32_MAX);
5076     }
5077
5078     ret = dpif_flow_put(subfacet->backer->dpif, flags, subfacet->key,
5079                         subfacet->key_len,  mask.data, mask.size,
5080                         actions, actions_len, stats);
5081
5082     if (stats) {
5083         subfacet_reset_dp_stats(subfacet, stats);
5084     }
5085
5086     if (ret) {
5087         COVERAGE_INC(subfacet_install_fail);
5088     } else {
5089         subfacet->path = path;
5090     }
5091     return ret;
5092 }
5093
5094 /* If 'subfacet' is installed in the datapath, uninstalls it. */
5095 static void
5096 subfacet_uninstall(struct subfacet *subfacet)
5097 {
5098     if (subfacet->path != SF_NOT_INSTALLED) {
5099         struct rule_dpif *rule = subfacet->facet->rule;
5100         struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5101         struct dpif_flow_stats stats;
5102         int error;
5103
5104         error = dpif_flow_del(ofproto->backer->dpif, subfacet->key,
5105                               subfacet->key_len, &stats);
5106         subfacet_reset_dp_stats(subfacet, &stats);
5107         if (!error) {
5108             subfacet_update_stats(subfacet, &stats);
5109         }
5110         subfacet->path = SF_NOT_INSTALLED;
5111     } else {
5112         ovs_assert(subfacet->dp_packet_count == 0);
5113         ovs_assert(subfacet->dp_byte_count == 0);
5114     }
5115 }
5116
5117 /* Resets 'subfacet''s datapath statistics counters.  This should be called
5118  * when 'subfacet''s statistics are cleared in the datapath.  If 'stats' is
5119  * non-null, it should contain the statistics returned by dpif when 'subfacet'
5120  * was reset in the datapath.  'stats' will be modified to include only
5121  * statistics new since 'subfacet' was last updated. */
5122 static void
5123 subfacet_reset_dp_stats(struct subfacet *subfacet,
5124                         struct dpif_flow_stats *stats)
5125 {
5126     if (stats
5127         && subfacet->dp_packet_count <= stats->n_packets
5128         && subfacet->dp_byte_count <= stats->n_bytes) {
5129         stats->n_packets -= subfacet->dp_packet_count;
5130         stats->n_bytes -= subfacet->dp_byte_count;
5131     }
5132
5133     subfacet->dp_packet_count = 0;
5134     subfacet->dp_byte_count = 0;
5135 }
5136
5137 /* Folds the statistics from 'stats' into the counters in 'subfacet'.
5138  *
5139  * Because of the meaning of a subfacet's counters, it only makes sense to do
5140  * this if 'stats' are not tracked in the datapath, that is, if 'stats'
5141  * represents a packet that was sent by hand or if it represents statistics
5142  * that have been cleared out of the datapath. */
5143 static void
5144 subfacet_update_stats(struct subfacet *subfacet,
5145                       const struct dpif_flow_stats *stats)
5146 {
5147     if (stats->n_packets || stats->used > subfacet->used) {
5148         struct facet *facet = subfacet->facet;
5149
5150         subfacet->used = MAX(subfacet->used, stats->used);
5151         facet->used = MAX(facet->used, stats->used);
5152         facet->packet_count += stats->n_packets;
5153         facet->byte_count += stats->n_bytes;
5154         facet->tcp_flags |= stats->tcp_flags;
5155     }
5156 }
5157 \f
5158 /* Rules. */
5159
5160 /* Lookup 'flow' in 'ofproto''s classifier.  If 'wc' is non-null, sets
5161  * the fields that were relevant as part of the lookup. */
5162 static struct rule_dpif *
5163 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
5164                  struct flow_wildcards *wc)
5165 {
5166     struct rule_dpif *rule;
5167
5168     rule = rule_dpif_lookup_in_table(ofproto, flow, wc, 0);
5169     if (rule) {
5170         return rule;
5171     }
5172
5173     return rule_dpif_miss_rule(ofproto, flow);
5174 }
5175
5176 struct rule_dpif *
5177 rule_dpif_lookup_in_table(struct ofproto_dpif *ofproto,
5178                           const struct flow *flow, struct flow_wildcards *wc,
5179                           uint8_t table_id)
5180 {
5181     struct cls_rule *cls_rule;
5182     struct classifier *cls;
5183     bool frag;
5184
5185     if (table_id >= N_TABLES) {
5186         return NULL;
5187     }
5188
5189     if (wc) {
5190         memset(&wc->masks.dl_type, 0xff, sizeof wc->masks.dl_type);
5191         wc->masks.nw_frag |= FLOW_NW_FRAG_MASK;
5192     }
5193
5194     cls = &ofproto->up.tables[table_id].cls;
5195     frag = (flow->nw_frag & FLOW_NW_FRAG_ANY) != 0;
5196     if (frag && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
5197         /* We must pretend that transport ports are unavailable. */
5198         struct flow ofpc_normal_flow = *flow;
5199         ofpc_normal_flow.tp_src = htons(0);
5200         ofpc_normal_flow.tp_dst = htons(0);
5201         cls_rule = classifier_lookup(cls, &ofpc_normal_flow, wc);
5202     } else if (frag && ofproto->up.frag_handling == OFPC_FRAG_DROP) {
5203         cls_rule = &ofproto->drop_frags_rule->up.cr;
5204         if (wc) {
5205             flow_wildcards_init_exact(wc);
5206         }
5207     } else {
5208         cls_rule = classifier_lookup(cls, flow, wc);
5209     }
5210     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
5211 }
5212
5213 struct rule_dpif *
5214 rule_dpif_miss_rule(struct ofproto_dpif *ofproto, const struct flow *flow)
5215 {
5216     struct ofport_dpif *port;
5217
5218     port = get_ofp_port(ofproto, flow->in_port.ofp_port);
5219     if (!port) {
5220         VLOG_WARN_RL(&rl, "packet-in on unknown OpenFlow port %"PRIu16,
5221                      flow->in_port.ofp_port);
5222         return ofproto->miss_rule;
5223     }
5224
5225     if (port->up.pp.config & OFPUTIL_PC_NO_PACKET_IN) {
5226         return ofproto->no_packet_in_rule;
5227     }
5228     return ofproto->miss_rule;
5229 }
5230
5231 static void
5232 complete_operation(struct rule_dpif *rule)
5233 {
5234     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5235
5236     rule_invalidate(rule);
5237     if (clogged) {
5238         struct dpif_completion *c = xmalloc(sizeof *c);
5239         c->op = rule->up.pending;
5240         list_push_back(&ofproto->completions, &c->list_node);
5241     } else {
5242         ofoperation_complete(rule->up.pending, 0);
5243     }
5244 }
5245
5246 static struct rule *
5247 rule_alloc(void)
5248 {
5249     struct rule_dpif *rule = xmalloc(sizeof *rule);
5250     return &rule->up;
5251 }
5252
5253 static void
5254 rule_dealloc(struct rule *rule_)
5255 {
5256     struct rule_dpif *rule = rule_dpif_cast(rule_);
5257     free(rule);
5258 }
5259
5260 static enum ofperr
5261 rule_construct(struct rule *rule_)
5262 {
5263     struct rule_dpif *rule = rule_dpif_cast(rule_);
5264     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5265     struct rule_dpif *victim;
5266     uint8_t table_id;
5267
5268     rule->packet_count = 0;
5269     rule->byte_count = 0;
5270
5271     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
5272     if (victim && !list_is_empty(&victim->facets)) {
5273         struct facet *facet;
5274
5275         rule->facets = victim->facets;
5276         list_moved(&rule->facets);
5277         LIST_FOR_EACH (facet, list_node, &rule->facets) {
5278             /* XXX: We're only clearing our local counters here.  It's possible
5279              * that quite a few packets are unaccounted for in the datapath
5280              * statistics.  These will be accounted to the new rule instead of
5281              * cleared as required.  This could be fixed by clearing out the
5282              * datapath statistics for this facet, but currently it doesn't
5283              * seem worth it. */
5284             facet_reset_counters(facet);
5285             facet->rule = rule;
5286         }
5287     } else {
5288         /* Must avoid list_moved() in this case. */
5289         list_init(&rule->facets);
5290     }
5291
5292     table_id = rule->up.table_id;
5293     if (victim) {
5294         rule->tag = victim->tag;
5295     } else if (table_id == 0) {
5296         rule->tag = 0;
5297     } else {
5298         struct flow flow;
5299
5300         miniflow_expand(&rule->up.cr.match.flow, &flow);
5301         rule->tag = rule_calculate_tag(&flow, &rule->up.cr.match.mask,
5302                                        ofproto->tables[table_id].basis);
5303     }
5304
5305     complete_operation(rule);
5306     return 0;
5307 }
5308
5309 static void
5310 rule_destruct(struct rule *rule_)
5311 {
5312     struct rule_dpif *rule = rule_dpif_cast(rule_);
5313     struct facet *facet, *next_facet;
5314
5315     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
5316         facet_revalidate(facet);
5317     }
5318
5319     complete_operation(rule);
5320 }
5321
5322 static void
5323 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
5324 {
5325     struct rule_dpif *rule = rule_dpif_cast(rule_);
5326
5327     /* push_all_stats() can handle flow misses which, when using the learn
5328      * action, can cause rules to be added and deleted.  This can corrupt our
5329      * caller's datastructures which assume that rule_get_stats() doesn't have
5330      * an impact on the flow table. To be safe, we disable miss handling. */
5331     push_all_stats__(false);
5332
5333     /* Start from historical data for 'rule' itself that are no longer tracked
5334      * in facets.  This counts, for example, facets that have expired. */
5335     *packets = rule->packet_count;
5336     *bytes = rule->byte_count;
5337 }
5338
5339 static void
5340 rule_dpif_execute(struct rule_dpif *rule, const struct flow *flow,
5341                   struct ofpbuf *packet)
5342 {
5343     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5344     struct dpif_flow_stats stats;
5345     struct xlate_out xout;
5346     struct xlate_in xin;
5347
5348     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
5349     rule_credit_stats(rule, &stats);
5350
5351     xlate_in_init(&xin, ofproto, flow, rule, stats.tcp_flags, packet);
5352     xin.resubmit_stats = &stats;
5353     xlate_actions(&xin, &xout);
5354
5355     execute_odp_actions(ofproto, flow, xout.odp_actions.data,
5356                         xout.odp_actions.size, packet);
5357
5358     xlate_out_uninit(&xout);
5359 }
5360
5361 static enum ofperr
5362 rule_execute(struct rule *rule, const struct flow *flow,
5363              struct ofpbuf *packet)
5364 {
5365     rule_dpif_execute(rule_dpif_cast(rule), flow, packet);
5366     ofpbuf_delete(packet);
5367     return 0;
5368 }
5369
5370 static void
5371 rule_modify_actions(struct rule *rule_)
5372 {
5373     struct rule_dpif *rule = rule_dpif_cast(rule_);
5374
5375     complete_operation(rule);
5376 }
5377 \f
5378 /* Sends 'packet' out 'ofport'.
5379  * May modify 'packet'.
5380  * Returns 0 if successful, otherwise a positive errno value. */
5381 static int
5382 send_packet(const struct ofport_dpif *ofport, struct ofpbuf *packet)
5383 {
5384     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
5385     uint64_t odp_actions_stub[1024 / 8];
5386     struct ofpbuf key, odp_actions;
5387     struct dpif_flow_stats stats;
5388     struct odputil_keybuf keybuf;
5389     struct ofpact_output output;
5390     struct xlate_out xout;
5391     struct xlate_in xin;
5392     struct flow flow;
5393     union flow_in_port in_port_;
5394     int error;
5395
5396     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
5397     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5398
5399     /* Use OFPP_NONE as the in_port to avoid special packet processing. */
5400     in_port_.ofp_port = OFPP_NONE;
5401     flow_extract(packet, 0, 0, NULL, &in_port_, &flow);
5402     odp_flow_key_from_flow(&key, &flow, ofp_port_to_odp_port(ofproto,
5403                                                              OFPP_LOCAL));
5404     dpif_flow_stats_extract(&flow, packet, time_msec(), &stats);
5405
5406     ofpact_init(&output.ofpact, OFPACT_OUTPUT, sizeof output);
5407     output.port = ofport->up.ofp_port;
5408     output.max_len = 0;
5409
5410     xlate_in_init(&xin, ofproto, &flow, NULL, 0, packet);
5411     xin.ofpacts_len = sizeof output;
5412     xin.ofpacts = &output.ofpact;
5413     xin.resubmit_stats = &stats;
5414     xlate_actions(&xin, &xout);
5415
5416     error = dpif_execute(ofproto->backer->dpif,
5417                          key.data, key.size,
5418                          xout.odp_actions.data, xout.odp_actions.size,
5419                          packet);
5420     xlate_out_uninit(&xout);
5421
5422     if (error) {
5423         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %s (%s)",
5424                      ofproto->up.name, netdev_get_name(ofport->up.netdev),
5425                      ovs_strerror(error));
5426     }
5427
5428     ofproto->stats.tx_packets++;
5429     ofproto->stats.tx_bytes += packet->size;
5430     return error;
5431 }
5432
5433 /* Composes an ODP action for a "slow path" action for 'flow' within 'ofproto'.
5434  * The action will state 'slow' as the reason that the action is in the slow
5435  * path.  (This is purely informational: it allows a human viewing "ovs-dpctl
5436  * dump-flows" output to see why a flow is in the slow path.)
5437  *
5438  * The 'stub_size' bytes in 'stub' will be used to store the action.
5439  * 'stub_size' must be large enough for the action.
5440  *
5441  * The action and its size will be stored in '*actionsp' and '*actions_lenp',
5442  * respectively. */
5443 static void
5444 compose_slow_path(const struct ofproto_dpif *ofproto, const struct flow *flow,
5445                   enum slow_path_reason slow,
5446                   uint64_t *stub, size_t stub_size,
5447                   const struct nlattr **actionsp, size_t *actions_lenp)
5448 {
5449     union user_action_cookie cookie;
5450     struct ofpbuf buf;
5451
5452     cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
5453     cookie.slow_path.unused = 0;
5454     cookie.slow_path.reason = slow;
5455
5456     ofpbuf_use_stack(&buf, stub, stub_size);
5457     if (slow & (SLOW_CFM | SLOW_BFD | SLOW_LACP | SLOW_STP)) {
5458         uint32_t pid = dpif_port_get_pid(ofproto->backer->dpif,
5459                                          ODPP_NONE);
5460         odp_put_userspace_action(pid, &cookie, sizeof cookie.slow_path, &buf);
5461     } else {
5462         put_userspace_action(ofproto, &buf, flow, &cookie,
5463                              sizeof cookie.slow_path);
5464     }
5465     *actionsp = buf.data;
5466     *actions_lenp = buf.size;
5467 }
5468
5469 size_t
5470 put_userspace_action(const struct ofproto_dpif *ofproto,
5471                      struct ofpbuf *odp_actions,
5472                      const struct flow *flow,
5473                      const union user_action_cookie *cookie,
5474                      const size_t cookie_size)
5475 {
5476     uint32_t pid;
5477
5478     pid = dpif_port_get_pid(ofproto->backer->dpif,
5479                             ofp_port_to_odp_port(ofproto,
5480                                                  flow->in_port.ofp_port));
5481
5482     return odp_put_userspace_action(pid, cookie, cookie_size, odp_actions);
5483 }
5484
5485
5486 static void
5487 update_mirror_stats(struct ofproto_dpif *ofproto, mirror_mask_t mirrors,
5488                     uint64_t packets, uint64_t bytes)
5489 {
5490     if (!mirrors) {
5491         return;
5492     }
5493
5494     for (; mirrors; mirrors = zero_rightmost_1bit(mirrors)) {
5495         struct ofmirror *m;
5496
5497         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
5498
5499         if (!m) {
5500             /* In normal circumstances 'm' will not be NULL.  However,
5501              * if mirrors are reconfigured, we can temporarily get out
5502              * of sync in facet_revalidate().  We could "correct" the
5503              * mirror list before reaching here, but doing that would
5504              * not properly account the traffic stats we've currently
5505              * accumulated for previous mirror configuration. */
5506             continue;
5507         }
5508
5509         m->packet_count += packets;
5510         m->byte_count += bytes;
5511     }
5512 }
5513
5514 tag_type
5515 calculate_flow_tag(struct ofproto_dpif *ofproto, const struct flow *flow,
5516                    uint8_t table_id, struct rule_dpif *rule)
5517 {
5518     if (table_id > 0 && table_id < N_TABLES) {
5519         struct table_dpif *table = &ofproto->tables[table_id];
5520         if (table->other_table) {
5521             return (rule && rule->tag
5522                     ? rule->tag
5523                     : rule_calculate_tag(flow, &table->other_table->mask,
5524                                          table->basis));
5525         }
5526     }
5527
5528     return 0;
5529 }
5530 \f
5531 /* Optimized flow revalidation.
5532  *
5533  * It's a difficult problem, in general, to tell which facets need to have
5534  * their actions recalculated whenever the OpenFlow flow table changes.  We
5535  * don't try to solve that general problem: for most kinds of OpenFlow flow
5536  * table changes, we recalculate the actions for every facet.  This is
5537  * relatively expensive, but it's good enough if the OpenFlow flow table
5538  * doesn't change very often.
5539  *
5540  * However, we can expect one particular kind of OpenFlow flow table change to
5541  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
5542  * of CPU on revalidating every facet whenever MAC learning modifies the flow
5543  * table, we add a special case that applies to flow tables in which every rule
5544  * has the same form (that is, the same wildcards), except that the table is
5545  * also allowed to have a single "catch-all" flow that matches all packets.  We
5546  * optimize this case by tagging all of the facets that resubmit into the table
5547  * and invalidating the same tag whenever a flow changes in that table.  The
5548  * end result is that we revalidate just the facets that need it (and sometimes
5549  * a few more, but not all of the facets or even all of the facets that
5550  * resubmit to the table modified by MAC learning). */
5551
5552 /* Calculates the tag to use for 'flow' and mask 'mask' when it is inserted
5553  * into an OpenFlow table with the given 'basis'. */
5554 tag_type
5555 rule_calculate_tag(const struct flow *flow, const struct minimask *mask,
5556                    uint32_t secret)
5557 {
5558     if (minimask_is_catchall(mask)) {
5559         return 0;
5560     } else {
5561         uint32_t hash = flow_hash_in_minimask(flow, mask, secret);
5562         return tag_create_deterministic(hash);
5563     }
5564 }
5565
5566 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
5567  * taggability of that table.
5568  *
5569  * This function must be called after *each* change to a flow table.  If you
5570  * skip calling it on some changes then the pointer comparisons at the end can
5571  * be invalid if you get unlucky.  For example, if a flow removal causes a
5572  * cls_table to be destroyed and then a flow insertion causes a cls_table with
5573  * different wildcards to be created with the same address, then this function
5574  * will incorrectly skip revalidation. */
5575 static void
5576 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
5577 {
5578     struct table_dpif *table = &ofproto->tables[table_id];
5579     const struct oftable *oftable = &ofproto->up.tables[table_id];
5580     struct cls_table *catchall, *other;
5581     struct cls_table *t;
5582
5583     catchall = other = NULL;
5584
5585     switch (hmap_count(&oftable->cls.tables)) {
5586     case 0:
5587         /* We could tag this OpenFlow table but it would make the logic a
5588          * little harder and it's a corner case that doesn't seem worth it
5589          * yet. */
5590         break;
5591
5592     case 1:
5593     case 2:
5594         HMAP_FOR_EACH (t, hmap_node, &oftable->cls.tables) {
5595             if (cls_table_is_catchall(t)) {
5596                 catchall = t;
5597             } else if (!other) {
5598                 other = t;
5599             } else {
5600                 /* Indicate that we can't tag this by setting both tables to
5601                  * NULL.  (We know that 'catchall' is already NULL.) */
5602                 other = NULL;
5603             }
5604         }
5605         break;
5606
5607     default:
5608         /* Can't tag this table. */
5609         break;
5610     }
5611
5612     if (table->catchall_table != catchall || table->other_table != other) {
5613         table->catchall_table = catchall;
5614         table->other_table = other;
5615         ofproto->backer->need_revalidate = REV_FLOW_TABLE;
5616     }
5617 }
5618
5619 /* Given 'rule' that has changed in some way (either it is a rule being
5620  * inserted, a rule being deleted, or a rule whose actions are being
5621  * modified), marks facets for revalidation to ensure that packets will be
5622  * forwarded correctly according to the new state of the flow table.
5623  *
5624  * This function must be called after *each* change to a flow table.  See
5625  * the comment on table_update_taggable() for more information. */
5626 static void
5627 rule_invalidate(const struct rule_dpif *rule)
5628 {
5629     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5630
5631     table_update_taggable(ofproto, rule->up.table_id);
5632
5633     if (!ofproto->backer->need_revalidate) {
5634         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
5635
5636         if (table->other_table && rule->tag) {
5637             tag_set_add(&ofproto->backer->revalidate_set, rule->tag);
5638         } else {
5639             ofproto->backer->need_revalidate = REV_FLOW_TABLE;
5640         }
5641     }
5642 }
5643 \f
5644 static bool
5645 set_frag_handling(struct ofproto *ofproto_,
5646                   enum ofp_config_flags frag_handling)
5647 {
5648     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5649     if (frag_handling != OFPC_FRAG_REASM) {
5650         ofproto->backer->need_revalidate = REV_RECONFIGURE;
5651         return true;
5652     } else {
5653         return false;
5654     }
5655 }
5656
5657 static enum ofperr
5658 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
5659            const struct flow *flow,
5660            const struct ofpact *ofpacts, size_t ofpacts_len)
5661 {
5662     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5663     struct odputil_keybuf keybuf;
5664     struct dpif_flow_stats stats;
5665     struct xlate_out xout;
5666     struct xlate_in xin;
5667     struct ofpbuf key;
5668
5669
5670     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5671     odp_flow_key_from_flow(&key, flow,
5672                            ofp_port_to_odp_port(ofproto,
5673                                       flow->in_port.ofp_port));
5674
5675     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
5676
5677     xlate_in_init(&xin, ofproto, flow, NULL, stats.tcp_flags, packet);
5678     xin.resubmit_stats = &stats;
5679     xin.ofpacts_len = ofpacts_len;
5680     xin.ofpacts = ofpacts;
5681
5682     xlate_actions(&xin, &xout);
5683     dpif_execute(ofproto->backer->dpif, key.data, key.size,
5684                  xout.odp_actions.data, xout.odp_actions.size, packet);
5685     xlate_out_uninit(&xout);
5686
5687     return 0;
5688 }
5689 \f
5690 /* NetFlow. */
5691
5692 static int
5693 set_netflow(struct ofproto *ofproto_,
5694             const struct netflow_options *netflow_options)
5695 {
5696     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5697
5698     if (netflow_options) {
5699         if (!ofproto->netflow) {
5700             ofproto->netflow = netflow_create();
5701             ofproto->backer->need_revalidate = REV_RECONFIGURE;
5702         }
5703         return netflow_set_options(ofproto->netflow, netflow_options);
5704     } else if (ofproto->netflow) {
5705         ofproto->backer->need_revalidate = REV_RECONFIGURE;
5706         netflow_destroy(ofproto->netflow);
5707         ofproto->netflow = NULL;
5708     }
5709
5710     return 0;
5711 }
5712
5713 static void
5714 get_netflow_ids(const struct ofproto *ofproto_,
5715                 uint8_t *engine_type, uint8_t *engine_id)
5716 {
5717     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5718
5719     dpif_get_netflow_ids(ofproto->backer->dpif, engine_type, engine_id);
5720 }
5721
5722 static void
5723 send_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
5724 {
5725     if (!facet_is_controller_flow(facet) &&
5726         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
5727         struct subfacet *subfacet;
5728         struct ofexpired expired;
5729
5730         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
5731             if (subfacet->path == SF_FAST_PATH) {
5732                 struct dpif_flow_stats stats;
5733
5734                 subfacet_install(subfacet, &facet->xout.odp_actions,
5735                                  &stats);
5736                 subfacet_update_stats(subfacet, &stats);
5737             }
5738         }
5739
5740         expired.flow = facet->flow;
5741         expired.packet_count = facet->packet_count;
5742         expired.byte_count = facet->byte_count;
5743         expired.used = facet->used;
5744         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
5745     }
5746 }
5747
5748 static void
5749 send_netflow_active_timeouts(struct ofproto_dpif *ofproto)
5750 {
5751     struct cls_cursor cursor;
5752     struct facet *facet;
5753
5754     cls_cursor_init(&cursor, &ofproto->facets, NULL);
5755     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
5756         send_active_timeout(ofproto, facet);
5757     }
5758 }
5759 \f
5760 static struct ofproto_dpif *
5761 ofproto_dpif_lookup(const char *name)
5762 {
5763     struct ofproto_dpif *ofproto;
5764
5765     HMAP_FOR_EACH_WITH_HASH (ofproto, all_ofproto_dpifs_node,
5766                              hash_string(name, 0), &all_ofproto_dpifs) {
5767         if (!strcmp(ofproto->up.name, name)) {
5768             return ofproto;
5769         }
5770     }
5771     return NULL;
5772 }
5773
5774 static void
5775 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn, int argc,
5776                           const char *argv[], void *aux OVS_UNUSED)
5777 {
5778     struct ofproto_dpif *ofproto;
5779
5780     if (argc > 1) {
5781         ofproto = ofproto_dpif_lookup(argv[1]);
5782         if (!ofproto) {
5783             unixctl_command_reply_error(conn, "no such bridge");
5784             return;
5785         }
5786         mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
5787     } else {
5788         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
5789             mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
5790         }
5791     }
5792
5793     unixctl_command_reply(conn, "table successfully flushed");
5794 }
5795
5796 static void
5797 ofproto_unixctl_fdb_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
5798                          const char *argv[], void *aux OVS_UNUSED)
5799 {
5800     struct ds ds = DS_EMPTY_INITIALIZER;
5801     const struct ofproto_dpif *ofproto;
5802     const struct mac_entry *e;
5803
5804     ofproto = ofproto_dpif_lookup(argv[1]);
5805     if (!ofproto) {
5806         unixctl_command_reply_error(conn, "no such bridge");
5807         return;
5808     }
5809
5810     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
5811     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
5812         struct ofbundle *bundle = e->port.p;
5813         char name[OFP_MAX_PORT_NAME_LEN];
5814
5815         ofputil_port_to_string(ofbundle_get_a_port(bundle)->up.ofp_port,
5816                                name, sizeof name);
5817         ds_put_format(&ds, "%5s  %4d  "ETH_ADDR_FMT"  %3d\n",
5818                       name, e->vlan, ETH_ADDR_ARGS(e->mac),
5819                       mac_entry_age(ofproto->ml, e));
5820     }
5821     unixctl_command_reply(conn, ds_cstr(&ds));
5822     ds_destroy(&ds);
5823 }
5824
5825 struct trace_ctx {
5826     struct xlate_out xout;
5827     struct xlate_in xin;
5828     struct flow flow;
5829     struct ds *result;
5830 };
5831
5832 static void
5833 trace_format_rule(struct ds *result, int level, const struct rule_dpif *rule)
5834 {
5835     ds_put_char_multiple(result, '\t', level);
5836     if (!rule) {
5837         ds_put_cstr(result, "No match\n");
5838         return;
5839     }
5840
5841     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
5842                   rule ? rule->up.table_id : 0, ntohll(rule->up.flow_cookie));
5843     cls_rule_format(&rule->up.cr, result);
5844     ds_put_char(result, '\n');
5845
5846     ds_put_char_multiple(result, '\t', level);
5847     ds_put_cstr(result, "OpenFlow ");
5848     ofpacts_format(rule->up.ofpacts, rule->up.ofpacts_len, result);
5849     ds_put_char(result, '\n');
5850 }
5851
5852 static void
5853 trace_format_flow(struct ds *result, int level, const char *title,
5854                   struct trace_ctx *trace)
5855 {
5856     ds_put_char_multiple(result, '\t', level);
5857     ds_put_format(result, "%s: ", title);
5858     if (flow_equal(&trace->xin.flow, &trace->flow)) {
5859         ds_put_cstr(result, "unchanged");
5860     } else {
5861         flow_format(result, &trace->xin.flow);
5862         trace->flow = trace->xin.flow;
5863     }
5864     ds_put_char(result, '\n');
5865 }
5866
5867 static void
5868 trace_format_regs(struct ds *result, int level, const char *title,
5869                   struct trace_ctx *trace)
5870 {
5871     size_t i;
5872
5873     ds_put_char_multiple(result, '\t', level);
5874     ds_put_format(result, "%s:", title);
5875     for (i = 0; i < FLOW_N_REGS; i++) {
5876         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
5877     }
5878     ds_put_char(result, '\n');
5879 }
5880
5881 static void
5882 trace_format_odp(struct ds *result, int level, const char *title,
5883                  struct trace_ctx *trace)
5884 {
5885     struct ofpbuf *odp_actions = &trace->xout.odp_actions;
5886
5887     ds_put_char_multiple(result, '\t', level);
5888     ds_put_format(result, "%s: ", title);
5889     format_odp_actions(result, odp_actions->data, odp_actions->size);
5890     ds_put_char(result, '\n');
5891 }
5892
5893 static void
5894 trace_resubmit(struct xlate_in *xin, struct rule_dpif *rule, int recurse)
5895 {
5896     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
5897     struct ds *result = trace->result;
5898
5899     ds_put_char(result, '\n');
5900     trace_format_flow(result, recurse + 1, "Resubmitted flow", trace);
5901     trace_format_regs(result, recurse + 1, "Resubmitted regs", trace);
5902     trace_format_odp(result,  recurse + 1, "Resubmitted  odp", trace);
5903     trace_format_rule(result, recurse + 1, rule);
5904 }
5905
5906 static void
5907 trace_report(struct xlate_in *xin, const char *s, int recurse)
5908 {
5909     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
5910     struct ds *result = trace->result;
5911
5912     ds_put_char_multiple(result, '\t', recurse);
5913     ds_put_cstr(result, s);
5914     ds_put_char(result, '\n');
5915 }
5916
5917 static void
5918 ofproto_unixctl_trace(struct unixctl_conn *conn, int argc, const char *argv[],
5919                       void *aux OVS_UNUSED)
5920 {
5921     const struct dpif_backer *backer;
5922     struct ofproto_dpif *ofproto;
5923     struct ofpbuf odp_key, odp_mask;
5924     struct ofpbuf *packet;
5925     struct ds result;
5926     struct flow flow;
5927     char *s;
5928
5929     packet = NULL;
5930     backer = NULL;
5931     ds_init(&result);
5932     ofpbuf_init(&odp_key, 0);
5933     ofpbuf_init(&odp_mask, 0);
5934
5935     /* Handle "-generate" or a hex string as the last argument. */
5936     if (!strcmp(argv[argc - 1], "-generate")) {
5937         packet = ofpbuf_new(0);
5938         argc--;
5939     } else {
5940         const char *error = eth_from_hex(argv[argc - 1], &packet);
5941         if (!error) {
5942             argc--;
5943         } else if (argc == 4) {
5944             /* The 3-argument form must end in "-generate' or a hex string. */
5945             unixctl_command_reply_error(conn, error);
5946             goto exit;
5947         }
5948     }
5949
5950     /* Parse the flow and determine whether a datapath or
5951      * bridge is specified. If function odp_flow_key_from_string()
5952      * returns 0, the flow is a odp_flow. If function
5953      * parse_ofp_exact_flow() returns 0, the flow is a br_flow. */
5954     if (!odp_flow_from_string(argv[argc - 1], NULL, &odp_key, &odp_mask)) {
5955         /* If the odp_flow is the second argument,
5956          * the datapath name is the first argument. */
5957         if (argc == 3) {
5958             const char *dp_type;
5959             if (!strncmp(argv[1], "ovs-", 4)) {
5960                 dp_type = argv[1] + 4;
5961             } else {
5962                 dp_type = argv[1];
5963             }
5964             backer = shash_find_data(&all_dpif_backers, dp_type);
5965             if (!backer) {
5966                 unixctl_command_reply_error(conn, "Cannot find datapath "
5967                                "of this name");
5968                 goto exit;
5969             }
5970         } else {
5971             /* No datapath name specified, so there should be only one
5972              * datapath. */
5973             struct shash_node *node;
5974             if (shash_count(&all_dpif_backers) != 1) {
5975                 unixctl_command_reply_error(conn, "Must specify datapath "
5976                          "name, there is more than one type of datapath");
5977                 goto exit;
5978             }
5979             node = shash_first(&all_dpif_backers);
5980             backer = node->data;
5981         }
5982
5983         /* Extract the ofproto_dpif object from the ofproto_receive()
5984          * function. */
5985         if (ofproto_receive(backer, NULL, odp_key.data,
5986                             odp_key.size, &flow, NULL, &ofproto, NULL)) {
5987             unixctl_command_reply_error(conn, "Invalid datapath flow");
5988             goto exit;
5989         }
5990         ds_put_format(&result, "Bridge: %s\n", ofproto->up.name);
5991     } else if (!parse_ofp_exact_flow(&flow, argv[argc - 1])) {
5992         if (argc != 3) {
5993             unixctl_command_reply_error(conn, "Must specify bridge name");
5994             goto exit;
5995         }
5996
5997         ofproto = ofproto_dpif_lookup(argv[1]);
5998         if (!ofproto) {
5999             unixctl_command_reply_error(conn, "Unknown bridge name");
6000             goto exit;
6001         }
6002     } else {
6003         unixctl_command_reply_error(conn, "Bad flow syntax");
6004         goto exit;
6005     }
6006
6007     /* Generate a packet, if requested. */
6008     if (packet) {
6009         if (!packet->size) {
6010             flow_compose(packet, &flow);
6011         } else {
6012             union flow_in_port in_port_;
6013
6014             in_port_ = flow.in_port;
6015             ds_put_cstr(&result, "Packet: ");
6016             s = ofp_packet_to_string(packet->data, packet->size);
6017             ds_put_cstr(&result, s);
6018             free(s);
6019
6020             /* Use the metadata from the flow and the packet argument
6021              * to reconstruct the flow. */
6022             flow_extract(packet, flow.skb_priority, flow.skb_mark, NULL,
6023                          &in_port_, &flow);
6024         }
6025     }
6026
6027     ofproto_trace(ofproto, &flow, packet, &result);
6028     unixctl_command_reply(conn, ds_cstr(&result));
6029
6030 exit:
6031     ds_destroy(&result);
6032     ofpbuf_delete(packet);
6033     ofpbuf_uninit(&odp_key);
6034     ofpbuf_uninit(&odp_mask);
6035 }
6036
6037 void
6038 ofproto_trace(struct ofproto_dpif *ofproto, const struct flow *flow,
6039               const struct ofpbuf *packet, struct ds *ds)
6040 {
6041     struct rule_dpif *rule;
6042
6043     ds_put_cstr(ds, "Flow: ");
6044     flow_format(ds, flow);
6045     ds_put_char(ds, '\n');
6046
6047     rule = rule_dpif_lookup(ofproto, flow, NULL);
6048
6049     trace_format_rule(ds, 0, rule);
6050     if (rule == ofproto->miss_rule) {
6051         ds_put_cstr(ds, "\nNo match, flow generates \"packet in\"s.\n");
6052     } else if (rule == ofproto->no_packet_in_rule) {
6053         ds_put_cstr(ds, "\nNo match, packets dropped because "
6054                     "OFPPC_NO_PACKET_IN is set on in_port.\n");
6055     } else if (rule == ofproto->drop_frags_rule) {
6056         ds_put_cstr(ds, "\nPackets dropped because they are IP fragments "
6057                     "and the fragment handling mode is \"drop\".\n");
6058     }
6059
6060     if (rule) {
6061         uint64_t odp_actions_stub[1024 / 8];
6062         struct ofpbuf odp_actions;
6063         struct trace_ctx trace;
6064         struct match match;
6065         uint8_t tcp_flags;
6066
6067         tcp_flags = packet ? packet_get_tcp_flags(packet, flow) : 0;
6068         trace.result = ds;
6069         trace.flow = *flow;
6070         ofpbuf_use_stub(&odp_actions,
6071                         odp_actions_stub, sizeof odp_actions_stub);
6072         xlate_in_init(&trace.xin, ofproto, flow, rule, tcp_flags, packet);
6073         trace.xin.resubmit_hook = trace_resubmit;
6074         trace.xin.report_hook = trace_report;
6075
6076         xlate_actions(&trace.xin, &trace.xout);
6077
6078         ds_put_char(ds, '\n');
6079         trace_format_flow(ds, 0, "Final flow", &trace);
6080
6081         match_init(&match, flow, &trace.xout.wc);
6082         ds_put_cstr(ds, "Relevant fields: ");
6083         match_format(&match, ds, OFP_DEFAULT_PRIORITY);
6084         ds_put_char(ds, '\n');
6085
6086         ds_put_cstr(ds, "Datapath actions: ");
6087         format_odp_actions(ds, trace.xout.odp_actions.data,
6088                            trace.xout.odp_actions.size);
6089
6090         if (trace.xout.slow) {
6091             ds_put_cstr(ds, "\nThis flow is handled by the userspace "
6092                         "slow path because it:");
6093             switch (trace.xout.slow) {
6094             case SLOW_CFM:
6095                 ds_put_cstr(ds, "\n\t- Consists of CFM packets.");
6096                 break;
6097             case SLOW_LACP:
6098                 ds_put_cstr(ds, "\n\t- Consists of LACP packets.");
6099                 break;
6100             case SLOW_STP:
6101                 ds_put_cstr(ds, "\n\t- Consists of STP packets.");
6102                 break;
6103             case SLOW_BFD:
6104                 ds_put_cstr(ds, "\n\t- Consists of BFD packets.");
6105                 break;
6106             case SLOW_CONTROLLER:
6107                 ds_put_cstr(ds, "\n\t- Sends \"packet-in\" messages "
6108                             "to the OpenFlow controller.");
6109                 break;
6110             case __SLOW_MAX:
6111                 NOT_REACHED();
6112             }
6113         }
6114
6115         xlate_out_uninit(&trace.xout);
6116     }
6117 }
6118
6119 static void
6120 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
6121                   const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6122 {
6123     clogged = true;
6124     unixctl_command_reply(conn, NULL);
6125 }
6126
6127 static void
6128 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
6129                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6130 {
6131     clogged = false;
6132     unixctl_command_reply(conn, NULL);
6133 }
6134
6135 /* Runs a self-check of flow translations in 'ofproto'.  Appends a message to
6136  * 'reply' describing the results. */
6137 static void
6138 ofproto_dpif_self_check__(struct ofproto_dpif *ofproto, struct ds *reply)
6139 {
6140     struct cls_cursor cursor;
6141     struct facet *facet;
6142     int errors;
6143
6144     errors = 0;
6145     cls_cursor_init(&cursor, &ofproto->facets, NULL);
6146     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
6147         if (!facet_check_consistency(facet)) {
6148             errors++;
6149         }
6150     }
6151     if (errors) {
6152         ofproto->backer->need_revalidate = REV_INCONSISTENCY;
6153     }
6154
6155     if (errors) {
6156         ds_put_format(reply, "%s: self-check failed (%d errors)\n",
6157                       ofproto->up.name, errors);
6158     } else {
6159         ds_put_format(reply, "%s: self-check passed\n", ofproto->up.name);
6160     }
6161 }
6162
6163 static void
6164 ofproto_dpif_self_check(struct unixctl_conn *conn,
6165                         int argc, const char *argv[], void *aux OVS_UNUSED)
6166 {
6167     struct ds reply = DS_EMPTY_INITIALIZER;
6168     struct ofproto_dpif *ofproto;
6169
6170     if (argc > 1) {
6171         ofproto = ofproto_dpif_lookup(argv[1]);
6172         if (!ofproto) {
6173             unixctl_command_reply_error(conn, "Unknown ofproto (use "
6174                                         "ofproto/list for help)");
6175             return;
6176         }
6177         ofproto_dpif_self_check__(ofproto, &reply);
6178     } else {
6179         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6180             ofproto_dpif_self_check__(ofproto, &reply);
6181         }
6182     }
6183
6184     unixctl_command_reply(conn, ds_cstr(&reply));
6185     ds_destroy(&reply);
6186 }
6187
6188 /* Store the current ofprotos in 'ofproto_shash'.  Returns a sorted list
6189  * of the 'ofproto_shash' nodes.  It is the responsibility of the caller
6190  * to destroy 'ofproto_shash' and free the returned value. */
6191 static const struct shash_node **
6192 get_ofprotos(struct shash *ofproto_shash)
6193 {
6194     const struct ofproto_dpif *ofproto;
6195
6196     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6197         char *name = xasprintf("%s@%s", ofproto->up.type, ofproto->up.name);
6198         shash_add_nocopy(ofproto_shash, name, ofproto);
6199     }
6200
6201     return shash_sort(ofproto_shash);
6202 }
6203
6204 static void
6205 ofproto_unixctl_dpif_dump_dps(struct unixctl_conn *conn, int argc OVS_UNUSED,
6206                               const char *argv[] OVS_UNUSED,
6207                               void *aux OVS_UNUSED)
6208 {
6209     struct ds ds = DS_EMPTY_INITIALIZER;
6210     struct shash ofproto_shash;
6211     const struct shash_node **sorted_ofprotos;
6212     int i;
6213
6214     shash_init(&ofproto_shash);
6215     sorted_ofprotos = get_ofprotos(&ofproto_shash);
6216     for (i = 0; i < shash_count(&ofproto_shash); i++) {
6217         const struct shash_node *node = sorted_ofprotos[i];
6218         ds_put_format(&ds, "%s\n", node->name);
6219     }
6220
6221     shash_destroy(&ofproto_shash);
6222     free(sorted_ofprotos);
6223
6224     unixctl_command_reply(conn, ds_cstr(&ds));
6225     ds_destroy(&ds);
6226 }
6227
6228 static void
6229 show_dp_rates(struct ds *ds, const char *heading,
6230               const struct avg_subfacet_rates *rates)
6231 {
6232     ds_put_format(ds, "%s add rate: %5.3f/min, del rate: %5.3f/min\n",
6233                   heading, rates->add_rate, rates->del_rate);
6234 }
6235
6236 static void
6237 dpif_show_backer(const struct dpif_backer *backer, struct ds *ds)
6238 {
6239     const struct shash_node **ofprotos;
6240     struct ofproto_dpif *ofproto;
6241     struct shash ofproto_shash;
6242     uint64_t n_hit, n_missed;
6243     long long int minutes;
6244     size_t i;
6245
6246     n_hit = n_missed = 0;
6247     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6248         if (ofproto->backer == backer) {
6249             n_missed += ofproto->n_missed;
6250             n_hit += ofproto->n_hit;
6251         }
6252     }
6253
6254     ds_put_format(ds, "%s: hit:%"PRIu64" missed:%"PRIu64"\n",
6255                   dpif_name(backer->dpif), n_hit, n_missed);
6256     ds_put_format(ds, "\tflows: cur: %zu, avg: %u, max: %u,"
6257                   " life span: %lldms\n", hmap_count(&backer->subfacets),
6258                   backer->avg_n_subfacet, backer->max_n_subfacet,
6259                   backer->avg_subfacet_life);
6260
6261     minutes = (time_msec() - backer->created) / (1000 * 60);
6262     if (minutes >= 60) {
6263         show_dp_rates(ds, "\thourly avg:", &backer->hourly);
6264     }
6265     if (minutes >= 60 * 24) {
6266         show_dp_rates(ds, "\tdaily avg:",  &backer->daily);
6267     }
6268     show_dp_rates(ds, "\toverall avg:",  &backer->lifetime);
6269
6270     shash_init(&ofproto_shash);
6271     ofprotos = get_ofprotos(&ofproto_shash);
6272     for (i = 0; i < shash_count(&ofproto_shash); i++) {
6273         struct ofproto_dpif *ofproto = ofprotos[i]->data;
6274         const struct shash_node **ports;
6275         size_t j;
6276
6277         if (ofproto->backer != backer) {
6278             continue;
6279         }
6280
6281         ds_put_format(ds, "\t%s: hit:%"PRIu64" missed:%"PRIu64"\n",
6282                       ofproto->up.name, ofproto->n_hit, ofproto->n_missed);
6283
6284         ports = shash_sort(&ofproto->up.port_by_name);
6285         for (j = 0; j < shash_count(&ofproto->up.port_by_name); j++) {
6286             const struct shash_node *node = ports[j];
6287             struct ofport *ofport = node->data;
6288             struct smap config;
6289             odp_port_t odp_port;
6290
6291             ds_put_format(ds, "\t\t%s %u/", netdev_get_name(ofport->netdev),
6292                           ofport->ofp_port);
6293
6294             odp_port = ofp_port_to_odp_port(ofproto, ofport->ofp_port);
6295             if (odp_port != ODPP_NONE) {
6296                 ds_put_format(ds, "%"PRIu32":", odp_port);
6297             } else {
6298                 ds_put_cstr(ds, "none:");
6299             }
6300
6301             ds_put_format(ds, " (%s", netdev_get_type(ofport->netdev));
6302
6303             smap_init(&config);
6304             if (!netdev_get_config(ofport->netdev, &config)) {
6305                 const struct smap_node **nodes;
6306                 size_t i;
6307
6308                 nodes = smap_sort(&config);
6309                 for (i = 0; i < smap_count(&config); i++) {
6310                     const struct smap_node *node = nodes[i];
6311                     ds_put_format(ds, "%c %s=%s", i ? ',' : ':',
6312                                   node->key, node->value);
6313                 }
6314                 free(nodes);
6315             }
6316             smap_destroy(&config);
6317
6318             ds_put_char(ds, ')');
6319             ds_put_char(ds, '\n');
6320         }
6321         free(ports);
6322     }
6323     shash_destroy(&ofproto_shash);
6324     free(ofprotos);
6325 }
6326
6327 static void
6328 ofproto_unixctl_dpif_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
6329                           const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6330 {
6331     struct ds ds = DS_EMPTY_INITIALIZER;
6332     const struct shash_node **backers;
6333     int i;
6334
6335     backers = shash_sort(&all_dpif_backers);
6336     for (i = 0; i < shash_count(&all_dpif_backers); i++) {
6337         dpif_show_backer(backers[i]->data, &ds);
6338     }
6339     free(backers);
6340
6341     unixctl_command_reply(conn, ds_cstr(&ds));
6342     ds_destroy(&ds);
6343 }
6344
6345 /* Dump the megaflow (facet) cache.  This is useful to check the
6346  * correctness of flow wildcarding, since the same mechanism is used for
6347  * both xlate caching and kernel wildcarding.
6348  *
6349  * It's important to note that in the output the flow description uses
6350  * OpenFlow (OFP) ports, but the actions use datapath (ODP) ports.
6351  *
6352  * This command is only needed for advanced debugging, so it's not
6353  * documented in the man page. */
6354 static void
6355 ofproto_unixctl_dpif_dump_megaflows(struct unixctl_conn *conn,
6356                                     int argc OVS_UNUSED, const char *argv[],
6357                                     void *aux OVS_UNUSED)
6358 {
6359     struct ds ds = DS_EMPTY_INITIALIZER;
6360     const struct ofproto_dpif *ofproto;
6361     long long int now = time_msec();
6362     struct cls_cursor cursor;
6363     struct facet *facet;
6364
6365     ofproto = ofproto_dpif_lookup(argv[1]);
6366     if (!ofproto) {
6367         unixctl_command_reply_error(conn, "no such bridge");
6368         return;
6369     }
6370
6371     cls_cursor_init(&cursor, &ofproto->facets, NULL);
6372     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
6373         cls_rule_format(&facet->cr, &ds);
6374         ds_put_cstr(&ds, ", ");
6375         ds_put_format(&ds, "n_subfacets:%zu, ", list_size(&facet->subfacets));
6376         ds_put_format(&ds, "used:%.3fs, ", (now - facet->used) / 1000.0);
6377         ds_put_cstr(&ds, "Datapath actions: ");
6378         if (facet->xout.slow) {
6379             uint64_t slow_path_stub[128 / 8];
6380             const struct nlattr *actions;
6381             size_t actions_len;
6382
6383             compose_slow_path(ofproto, &facet->flow, facet->xout.slow,
6384                               slow_path_stub, sizeof slow_path_stub,
6385                               &actions, &actions_len);
6386             format_odp_actions(&ds, actions, actions_len);
6387         } else {
6388             format_odp_actions(&ds, facet->xout.odp_actions.data,
6389                                facet->xout.odp_actions.size);
6390         }
6391         ds_put_cstr(&ds, "\n");
6392     }
6393
6394     ds_chomp(&ds, '\n');
6395     unixctl_command_reply(conn, ds_cstr(&ds));
6396     ds_destroy(&ds);
6397 }
6398
6399 /* Disable using the megaflows.
6400  *
6401  * This command is only needed for advanced debugging, so it's not
6402  * documented in the man page. */
6403 static void
6404 ofproto_unixctl_dpif_disable_megaflows(struct unixctl_conn *conn,
6405                                        int argc OVS_UNUSED,
6406                                        const char *argv[] OVS_UNUSED,
6407                                        void *aux OVS_UNUSED)
6408 {
6409     struct ofproto_dpif *ofproto;
6410
6411     enable_megaflows = false;
6412
6413     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6414         flush(&ofproto->up);
6415     }
6416
6417     unixctl_command_reply(conn, "megaflows disabled");
6418 }
6419
6420 /* Re-enable using megaflows.
6421  *
6422  * This command is only needed for advanced debugging, so it's not
6423  * documented in the man page. */
6424 static void
6425 ofproto_unixctl_dpif_enable_megaflows(struct unixctl_conn *conn,
6426                                       int argc OVS_UNUSED,
6427                                       const char *argv[] OVS_UNUSED,
6428                                       void *aux OVS_UNUSED)
6429 {
6430     struct ofproto_dpif *ofproto;
6431
6432     enable_megaflows = true;
6433
6434     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6435         flush(&ofproto->up);
6436     }
6437
6438     unixctl_command_reply(conn, "megaflows enabled");
6439 }
6440
6441 static void
6442 ofproto_unixctl_dpif_dump_flows(struct unixctl_conn *conn,
6443                                 int argc OVS_UNUSED, const char *argv[],
6444                                 void *aux OVS_UNUSED)
6445 {
6446     struct ds ds = DS_EMPTY_INITIALIZER;
6447     const struct ofproto_dpif *ofproto;
6448     struct subfacet *subfacet;
6449
6450     ofproto = ofproto_dpif_lookup(argv[1]);
6451     if (!ofproto) {
6452         unixctl_command_reply_error(conn, "no such bridge");
6453         return;
6454     }
6455
6456     update_stats(ofproto->backer);
6457
6458     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->backer->subfacets) {
6459         struct facet *facet = subfacet->facet;
6460
6461         if (ofproto_dpif_cast(facet->rule->up.ofproto) != ofproto) {
6462             continue;
6463         }
6464
6465         odp_flow_key_format(subfacet->key, subfacet->key_len, &ds);
6466
6467         ds_put_format(&ds, ", packets:%"PRIu64", bytes:%"PRIu64", used:",
6468                       subfacet->dp_packet_count, subfacet->dp_byte_count);
6469         if (subfacet->used) {
6470             ds_put_format(&ds, "%.3fs",
6471                           (time_msec() - subfacet->used) / 1000.0);
6472         } else {
6473             ds_put_format(&ds, "never");
6474         }
6475         if (subfacet->facet->tcp_flags) {
6476             ds_put_cstr(&ds, ", flags:");
6477             packet_format_tcp_flags(&ds, subfacet->facet->tcp_flags);
6478         }
6479
6480         ds_put_cstr(&ds, ", actions:");
6481         if (facet->xout.slow) {
6482             uint64_t slow_path_stub[128 / 8];
6483             const struct nlattr *actions;
6484             size_t actions_len;
6485
6486             compose_slow_path(ofproto, &facet->flow, facet->xout.slow,
6487                               slow_path_stub, sizeof slow_path_stub,
6488                               &actions, &actions_len);
6489             format_odp_actions(&ds, actions, actions_len);
6490         } else {
6491             format_odp_actions(&ds, facet->xout.odp_actions.data,
6492                                facet->xout.odp_actions.size);
6493         }
6494         ds_put_char(&ds, '\n');
6495     }
6496
6497     unixctl_command_reply(conn, ds_cstr(&ds));
6498     ds_destroy(&ds);
6499 }
6500
6501 static void
6502 ofproto_unixctl_dpif_del_flows(struct unixctl_conn *conn,
6503                                int argc OVS_UNUSED, const char *argv[],
6504                                void *aux OVS_UNUSED)
6505 {
6506     struct ds ds = DS_EMPTY_INITIALIZER;
6507     struct ofproto_dpif *ofproto;
6508
6509     ofproto = ofproto_dpif_lookup(argv[1]);
6510     if (!ofproto) {
6511         unixctl_command_reply_error(conn, "no such bridge");
6512         return;
6513     }
6514
6515     flush(&ofproto->up);
6516
6517     unixctl_command_reply(conn, ds_cstr(&ds));
6518     ds_destroy(&ds);
6519 }
6520
6521 static void
6522 ofproto_dpif_unixctl_init(void)
6523 {
6524     static bool registered;
6525     if (registered) {
6526         return;
6527     }
6528     registered = true;
6529
6530     unixctl_command_register(
6531         "ofproto/trace",
6532         "[dp_name]|bridge odp_flow|br_flow [-generate|packet]",
6533         1, 3, ofproto_unixctl_trace, NULL);
6534     unixctl_command_register("fdb/flush", "[bridge]", 0, 1,
6535                              ofproto_unixctl_fdb_flush, NULL);
6536     unixctl_command_register("fdb/show", "bridge", 1, 1,
6537                              ofproto_unixctl_fdb_show, NULL);
6538     unixctl_command_register("ofproto/clog", "", 0, 0,
6539                              ofproto_dpif_clog, NULL);
6540     unixctl_command_register("ofproto/unclog", "", 0, 0,
6541                              ofproto_dpif_unclog, NULL);
6542     unixctl_command_register("ofproto/self-check", "[bridge]", 0, 1,
6543                              ofproto_dpif_self_check, NULL);
6544     unixctl_command_register("dpif/dump-dps", "", 0, 0,
6545                              ofproto_unixctl_dpif_dump_dps, NULL);
6546     unixctl_command_register("dpif/show", "", 0, 0, ofproto_unixctl_dpif_show,
6547                              NULL);
6548     unixctl_command_register("dpif/dump-flows", "bridge", 1, 1,
6549                              ofproto_unixctl_dpif_dump_flows, NULL);
6550     unixctl_command_register("dpif/del-flows", "bridge", 1, 1,
6551                              ofproto_unixctl_dpif_del_flows, NULL);
6552     unixctl_command_register("dpif/dump-megaflows", "bridge", 1, 1,
6553                              ofproto_unixctl_dpif_dump_megaflows, NULL);
6554     unixctl_command_register("dpif/disable-megaflows", "", 0, 0,
6555                              ofproto_unixctl_dpif_disable_megaflows, NULL);
6556     unixctl_command_register("dpif/enable-megaflows", "", 0, 0,
6557                              ofproto_unixctl_dpif_enable_megaflows, NULL);
6558 }
6559 \f
6560 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
6561  *
6562  * This is deprecated.  It is only for compatibility with broken device drivers
6563  * in old versions of Linux that do not properly support VLANs when VLAN
6564  * devices are not used.  When broken device drivers are no longer in
6565  * widespread use, we will delete these interfaces. */
6566
6567 static int
6568 set_realdev(struct ofport *ofport_, ofp_port_t realdev_ofp_port, int vid)
6569 {
6570     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
6571     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
6572
6573     if (realdev_ofp_port == ofport->realdev_ofp_port
6574         && vid == ofport->vlandev_vid) {
6575         return 0;
6576     }
6577
6578     ofproto->backer->need_revalidate = REV_RECONFIGURE;
6579
6580     if (ofport->realdev_ofp_port) {
6581         vsp_remove(ofport);
6582     }
6583     if (realdev_ofp_port && ofport->bundle) {
6584         /* vlandevs are enslaved to their realdevs, so they are not allowed to
6585          * themselves be part of a bundle. */
6586         bundle_set(ofport->up.ofproto, ofport->bundle, NULL);
6587     }
6588
6589     ofport->realdev_ofp_port = realdev_ofp_port;
6590     ofport->vlandev_vid = vid;
6591
6592     if (realdev_ofp_port) {
6593         vsp_add(ofport, realdev_ofp_port, vid);
6594     }
6595
6596     return 0;
6597 }
6598
6599 static uint32_t
6600 hash_realdev_vid(ofp_port_t realdev_ofp_port, int vid)
6601 {
6602     return hash_2words(ofp_to_u16(realdev_ofp_port), vid);
6603 }
6604
6605 /* Returns the OFP port number of the Linux VLAN device that corresponds to
6606  * 'vlan_tci' on the network device with port number 'realdev_ofp_port' in
6607  * 'struct ofport_dpif'.  For example, given 'realdev_ofp_port' of eth0 and
6608  * 'vlan_tci' 9, it would return the port number of eth0.9.
6609  *
6610  * Unless VLAN splinters are enabled for port 'realdev_ofp_port', this
6611  * function just returns its 'realdev_ofp_port' argument. */
6612 ofp_port_t
6613 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
6614                        ofp_port_t realdev_ofp_port, ovs_be16 vlan_tci)
6615 {
6616     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
6617         int vid = vlan_tci_to_vid(vlan_tci);
6618         const struct vlan_splinter *vsp;
6619
6620         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
6621                                  hash_realdev_vid(realdev_ofp_port, vid),
6622                                  &ofproto->realdev_vid_map) {
6623             if (vsp->realdev_ofp_port == realdev_ofp_port
6624                 && vsp->vid == vid) {
6625                 return vsp->vlandev_ofp_port;
6626             }
6627         }
6628     }
6629     return realdev_ofp_port;
6630 }
6631
6632 static struct vlan_splinter *
6633 vlandev_find(const struct ofproto_dpif *ofproto, ofp_port_t vlandev_ofp_port)
6634 {
6635     struct vlan_splinter *vsp;
6636
6637     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node,
6638                              hash_ofp_port(vlandev_ofp_port),
6639                              &ofproto->vlandev_map) {
6640         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
6641             return vsp;
6642         }
6643     }
6644
6645     return NULL;
6646 }
6647
6648 /* Returns the OpenFlow port number of the "real" device underlying the Linux
6649  * VLAN device with OpenFlow port number 'vlandev_ofp_port' and stores the
6650  * VLAN VID of the Linux VLAN device in '*vid'.  For example, given
6651  * 'vlandev_ofp_port' of eth0.9, it would return the OpenFlow port number of
6652  * eth0 and store 9 in '*vid'.
6653  *
6654  * Returns 0 and does not modify '*vid' if 'vlandev_ofp_port' is not a Linux
6655  * VLAN device.  Unless VLAN splinters are enabled, this is what this function
6656  * always does.*/
6657 static ofp_port_t
6658 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
6659                        ofp_port_t vlandev_ofp_port, int *vid)
6660 {
6661     if (!hmap_is_empty(&ofproto->vlandev_map)) {
6662         const struct vlan_splinter *vsp;
6663
6664         vsp = vlandev_find(ofproto, vlandev_ofp_port);
6665         if (vsp) {
6666             if (vid) {
6667                 *vid = vsp->vid;
6668             }
6669             return vsp->realdev_ofp_port;
6670         }
6671     }
6672     return 0;
6673 }
6674
6675 /* Given 'flow', a flow representing a packet received on 'ofproto', checks
6676  * whether 'flow->in_port' represents a Linux VLAN device.  If so, changes
6677  * 'flow->in_port' to the "real" device backing the VLAN device, sets
6678  * 'flow->vlan_tci' to the VLAN VID, and returns true.  Otherwise (which is
6679  * always the case unless VLAN splinters are enabled), returns false without
6680  * making any changes. */
6681 static bool
6682 vsp_adjust_flow(const struct ofproto_dpif *ofproto, struct flow *flow)
6683 {
6684     ofp_port_t realdev;
6685     int vid;
6686
6687     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port.ofp_port, &vid);
6688     if (!realdev) {
6689         return false;
6690     }
6691
6692     /* Cause the flow to be processed as if it came in on the real device with
6693      * the VLAN device's VLAN ID. */
6694     flow->in_port.ofp_port = realdev;
6695     flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
6696     return true;
6697 }
6698
6699 static void
6700 vsp_remove(struct ofport_dpif *port)
6701 {
6702     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
6703     struct vlan_splinter *vsp;
6704
6705     vsp = vlandev_find(ofproto, port->up.ofp_port);
6706     if (vsp) {
6707         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
6708         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
6709         free(vsp);
6710
6711         port->realdev_ofp_port = 0;
6712     } else {
6713         VLOG_ERR("missing vlan device record");
6714     }
6715 }
6716
6717 static void
6718 vsp_add(struct ofport_dpif *port, ofp_port_t realdev_ofp_port, int vid)
6719 {
6720     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
6721
6722     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
6723         && (vsp_realdev_to_vlandev(ofproto, realdev_ofp_port, htons(vid))
6724             == realdev_ofp_port)) {
6725         struct vlan_splinter *vsp;
6726
6727         vsp = xmalloc(sizeof *vsp);
6728         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
6729                     hash_ofp_port(port->up.ofp_port));
6730         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
6731                     hash_realdev_vid(realdev_ofp_port, vid));
6732         vsp->realdev_ofp_port = realdev_ofp_port;
6733         vsp->vlandev_ofp_port = port->up.ofp_port;
6734         vsp->vid = vid;
6735
6736         port->realdev_ofp_port = realdev_ofp_port;
6737     } else {
6738         VLOG_ERR("duplicate vlan device record");
6739     }
6740 }
6741
6742 odp_port_t
6743 ofp_port_to_odp_port(const struct ofproto_dpif *ofproto, ofp_port_t ofp_port)
6744 {
6745     const struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
6746     return ofport ? ofport->odp_port : ODPP_NONE;
6747 }
6748
6749 static struct ofport_dpif *
6750 odp_port_to_ofport(const struct dpif_backer *backer, odp_port_t odp_port)
6751 {
6752     struct ofport_dpif *port;
6753
6754     HMAP_FOR_EACH_IN_BUCKET (port, odp_port_node, hash_odp_port(odp_port),
6755                              &backer->odp_to_ofport_map) {
6756         if (port->odp_port == odp_port) {
6757             return port;
6758         }
6759     }
6760
6761     return NULL;
6762 }
6763
6764 static ofp_port_t
6765 odp_port_to_ofp_port(const struct ofproto_dpif *ofproto, odp_port_t odp_port)
6766 {
6767     struct ofport_dpif *port;
6768
6769     port = odp_port_to_ofport(ofproto->backer, odp_port);
6770     if (port && &ofproto->up == port->up.ofproto) {
6771         return port->up.ofp_port;
6772     } else {
6773         return OFPP_NONE;
6774     }
6775 }
6776
6777 /* Compute exponentially weighted moving average, adding 'new' as the newest,
6778  * most heavily weighted element.  'base' designates the rate of decay: after
6779  * 'base' further updates, 'new''s weight in the EWMA decays to about 1/e
6780  * (about .37). */
6781 static void
6782 exp_mavg(double *avg, int base, double new)
6783 {
6784     *avg = (*avg * (base - 1) + new) / base;
6785 }
6786
6787 static void
6788 update_moving_averages(struct dpif_backer *backer)
6789 {
6790     const int min_ms = 60 * 1000; /* milliseconds in one minute. */
6791     long long int minutes = (time_msec() - backer->created) / min_ms;
6792
6793     if (minutes > 0) {
6794         backer->lifetime.add_rate = (double) backer->total_subfacet_add_count
6795             / minutes;
6796         backer->lifetime.del_rate = (double) backer->total_subfacet_del_count
6797             / minutes;
6798     } else {
6799         backer->lifetime.add_rate = 0.0;
6800         backer->lifetime.del_rate = 0.0;
6801     }
6802
6803     /* Update hourly averages on the minute boundaries. */
6804     if (time_msec() - backer->last_minute >= min_ms) {
6805         exp_mavg(&backer->hourly.add_rate, 60, backer->subfacet_add_count);
6806         exp_mavg(&backer->hourly.del_rate, 60, backer->subfacet_del_count);
6807
6808         /* Update daily averages on the hour boundaries. */
6809         if ((backer->last_minute - backer->created) / min_ms % 60 == 59) {
6810             exp_mavg(&backer->daily.add_rate, 24, backer->hourly.add_rate);
6811             exp_mavg(&backer->daily.del_rate, 24, backer->hourly.del_rate);
6812         }
6813
6814         backer->total_subfacet_add_count += backer->subfacet_add_count;
6815         backer->total_subfacet_del_count += backer->subfacet_del_count;
6816         backer->subfacet_add_count = 0;
6817         backer->subfacet_del_count = 0;
6818         backer->last_minute += min_ms;
6819     }
6820 }
6821
6822 const struct ofproto_class ofproto_dpif_class = {
6823     init,
6824     enumerate_types,
6825     enumerate_names,
6826     del,
6827     port_open_type,
6828     type_run,
6829     type_run_fast,
6830     type_wait,
6831     alloc,
6832     construct,
6833     destruct,
6834     dealloc,
6835     run,
6836     run_fast,
6837     wait,
6838     get_memory_usage,
6839     flush,
6840     get_features,
6841     get_tables,
6842     port_alloc,
6843     port_construct,
6844     port_destruct,
6845     port_dealloc,
6846     port_modified,
6847     port_reconfigured,
6848     port_query_by_name,
6849     port_add,
6850     port_del,
6851     port_get_stats,
6852     port_dump_start,
6853     port_dump_next,
6854     port_dump_done,
6855     port_poll,
6856     port_poll_wait,
6857     port_is_lacp_current,
6858     NULL,                       /* rule_choose_table */
6859     rule_alloc,
6860     rule_construct,
6861     rule_destruct,
6862     rule_dealloc,
6863     rule_get_stats,
6864     rule_execute,
6865     rule_modify_actions,
6866     set_frag_handling,
6867     packet_out,
6868     set_netflow,
6869     get_netflow_ids,
6870     set_sflow,
6871     set_ipfix,
6872     set_cfm,
6873     get_cfm_status,
6874     set_bfd,
6875     get_bfd_status,
6876     set_stp,
6877     get_stp_status,
6878     set_stp_port,
6879     get_stp_port_status,
6880     set_queues,
6881     bundle_set,
6882     bundle_remove,
6883     mirror_set,
6884     mirror_get_stats,
6885     set_flood_vlans,
6886     is_mirror_output_bundle,
6887     forward_bpdu_changed,
6888     set_mac_table_config,
6889     set_realdev,
6890     NULL,                       /* meter_get_features */
6891     NULL,                       /* meter_set */
6892     NULL,                       /* meter_get */
6893     NULL,                       /* meter_del */
6894 };