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