ofproto-dpif: Make vlan splinters thread safe.
[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 ovs_mutex vsp_mutex;
488     struct hmap realdev_vid_map OVS_GUARDED; /* (realdev,vid) -> vlandev. */
489     struct hmap vlandev_map OVS_GUARDED;     /* vlandev -> (realdev,vid). */
490
491     /* Ports. */
492     struct sset ports;             /* Set of standard port names. */
493     struct sset ghost_ports;       /* Ports with no datapath port. */
494     struct sset port_poll_set;     /* Queued names for port_poll() reply. */
495     int port_poll_errno;           /* Last errno for port_poll() reply. */
496
497     /* Per ofproto's dpif stats. */
498     uint64_t n_hit;
499     uint64_t n_missed;
500
501     /* Work queues. */
502     struct ovs_mutex flow_mod_mutex;
503     struct list flow_mods OVS_GUARDED;
504     size_t n_flow_mods OVS_GUARDED;
505 };
506
507 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
508  * for debugging the asynchronous flow_mod implementation.) */
509 static bool clogged;
510
511 /* By default, flows in the datapath are wildcarded (megaflows).  They
512  * may be disabled with the "ovs-appctl dpif/disable-megaflows" command. */
513 static bool enable_megaflows = true;
514
515 /* All existing ofproto_dpif instances, indexed by ->up.name. */
516 static struct hmap all_ofproto_dpifs = HMAP_INITIALIZER(&all_ofproto_dpifs);
517
518 static void ofproto_dpif_unixctl_init(void);
519
520 static inline struct ofproto_dpif *
521 ofproto_dpif_cast(const struct ofproto *ofproto)
522 {
523     ovs_assert(ofproto->ofproto_class == &ofproto_dpif_class);
524     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
525 }
526
527 static struct ofport_dpif *get_ofp_port(const struct ofproto_dpif *ofproto,
528                                         ofp_port_t ofp_port);
529 static void ofproto_trace(struct ofproto_dpif *, const struct flow *,
530                           const struct ofpbuf *packet, struct ds *);
531
532 /* Upcalls. */
533 #define FLOW_MISS_MAX_BATCH 50
534 static int handle_upcalls(struct dpif_backer *, unsigned int max_batch);
535
536 /* Flow expiration. */
537 static int expire(struct dpif_backer *);
538
539 /* NetFlow. */
540 static void send_netflow_active_timeouts(struct ofproto_dpif *);
541
542 /* Utilities. */
543 static int send_packet(const struct ofport_dpif *, struct ofpbuf *packet);
544
545 /* Global variables. */
546 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
547
548 /* Initial mappings of port to bridge mappings. */
549 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
550
551 /* Executes and takes ownership of 'fm'. */
552 void
553 ofproto_dpif_flow_mod(struct ofproto_dpif *ofproto,
554                       struct ofputil_flow_mod *fm)
555 {
556     ovs_mutex_lock(&ofproto->flow_mod_mutex);
557     if (ofproto->n_flow_mods > 1024) {
558         ovs_mutex_unlock(&ofproto->flow_mod_mutex);
559         COVERAGE_INC(flow_mod_overflow);
560         free(fm->ofpacts);
561         free(fm);
562         return;
563     }
564
565     list_push_back(&ofproto->flow_mods, &fm->list_node);
566     ofproto->n_flow_mods++;
567     ovs_mutex_unlock(&ofproto->flow_mod_mutex);
568 }
569
570 void
571 ofproto_dpif_send_packet_in(struct ofproto_dpif *ofproto,
572                             struct ofputil_packet_in *pin)
573 {
574     connmgr_send_packet_in(ofproto->up.connmgr, pin);
575 }
576 \f
577 /* Factory functions. */
578
579 static void
580 init(const struct shash *iface_hints)
581 {
582     struct shash_node *node;
583
584     /* Make a local copy, since we don't own 'iface_hints' elements. */
585     SHASH_FOR_EACH(node, iface_hints) {
586         const struct iface_hint *orig_hint = node->data;
587         struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
588
589         new_hint->br_name = xstrdup(orig_hint->br_name);
590         new_hint->br_type = xstrdup(orig_hint->br_type);
591         new_hint->ofp_port = orig_hint->ofp_port;
592
593         shash_add(&init_ofp_ports, node->name, new_hint);
594     }
595 }
596
597 static void
598 enumerate_types(struct sset *types)
599 {
600     dp_enumerate_types(types);
601 }
602
603 static int
604 enumerate_names(const char *type, struct sset *names)
605 {
606     struct ofproto_dpif *ofproto;
607
608     sset_clear(names);
609     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
610         if (strcmp(type, ofproto->up.type)) {
611             continue;
612         }
613         sset_add(names, ofproto->up.name);
614     }
615
616     return 0;
617 }
618
619 static int
620 del(const char *type, const char *name)
621 {
622     struct dpif *dpif;
623     int error;
624
625     error = dpif_open(name, type, &dpif);
626     if (!error) {
627         error = dpif_delete(dpif);
628         dpif_close(dpif);
629     }
630     return error;
631 }
632 \f
633 static const char *
634 port_open_type(const char *datapath_type, const char *port_type)
635 {
636     return dpif_port_open_type(datapath_type, port_type);
637 }
638
639 /* Type functions. */
640
641 static void process_dpif_port_changes(struct dpif_backer *);
642 static void process_dpif_all_ports_changed(struct dpif_backer *);
643 static void process_dpif_port_change(struct dpif_backer *,
644                                      const char *devname);
645 static void process_dpif_port_error(struct dpif_backer *, int error);
646
647 static struct ofproto_dpif *
648 lookup_ofproto_dpif_by_port_name(const char *name)
649 {
650     struct ofproto_dpif *ofproto;
651
652     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
653         if (sset_contains(&ofproto->ports, name)) {
654             return ofproto;
655         }
656     }
657
658     return NULL;
659 }
660
661 static int
662 type_run(const char *type)
663 {
664     static long long int push_timer = LLONG_MIN;
665     struct dpif_backer *backer;
666
667     backer = shash_find_data(&all_dpif_backers, type);
668     if (!backer) {
669         /* This is not necessarily a problem, since backers are only
670          * created on demand. */
671         return 0;
672     }
673
674     dpif_run(backer->dpif);
675
676     /* The most natural place to push facet statistics is when they're pulled
677      * from the datapath.  However, when there are many flows in the datapath,
678      * this expensive operation can occur so frequently, that it reduces our
679      * ability to quickly set up flows.  To reduce the cost, we push statistics
680      * here instead. */
681     if (time_msec() > push_timer) {
682         push_timer = time_msec() + 2000;
683         push_all_stats();
684     }
685
686     /* If vswitchd started with other_config:flow_restore_wait set as "true",
687      * and the configuration has now changed to "false", enable receiving
688      * packets from the datapath. */
689     if (!backer->recv_set_enable && !ofproto_get_flow_restore_wait()) {
690         int error;
691
692         backer->recv_set_enable = true;
693
694         error = dpif_recv_set(backer->dpif, backer->recv_set_enable);
695         if (error) {
696             VLOG_ERR("Failed to enable receiving packets in dpif.");
697             return error;
698         }
699         dpif_flow_flush(backer->dpif);
700         backer->need_revalidate = REV_RECONFIGURE;
701     }
702
703     if (backer->need_revalidate) {
704         struct ofproto_dpif *ofproto;
705         struct simap_node *node;
706         struct simap tmp_backers;
707
708         /* Handle tunnel garbage collection. */
709         simap_init(&tmp_backers);
710         simap_swap(&backer->tnl_backers, &tmp_backers);
711
712         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
713             struct ofport_dpif *iter;
714
715             if (backer != ofproto->backer) {
716                 continue;
717             }
718
719             HMAP_FOR_EACH (iter, up.hmap_node, &ofproto->up.ports) {
720                 char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
721                 const char *dp_port;
722
723                 if (!iter->is_tunnel) {
724                     continue;
725                 }
726
727                 dp_port = netdev_vport_get_dpif_port(iter->up.netdev,
728                                                      namebuf, sizeof namebuf);
729                 node = simap_find(&tmp_backers, dp_port);
730                 if (node) {
731                     simap_put(&backer->tnl_backers, dp_port, node->data);
732                     simap_delete(&tmp_backers, node);
733                     node = simap_find(&backer->tnl_backers, dp_port);
734                 } else {
735                     node = simap_find(&backer->tnl_backers, dp_port);
736                     if (!node) {
737                         odp_port_t odp_port = ODPP_NONE;
738
739                         if (!dpif_port_add(backer->dpif, iter->up.netdev,
740                                            &odp_port)) {
741                             simap_put(&backer->tnl_backers, dp_port,
742                                       odp_to_u32(odp_port));
743                             node = simap_find(&backer->tnl_backers, dp_port);
744                         }
745                     }
746                 }
747
748                 iter->odp_port = node ? u32_to_odp(node->data) : ODPP_NONE;
749                 if (tnl_port_reconfigure(iter, iter->up.netdev,
750                                          iter->odp_port)) {
751                     backer->need_revalidate = REV_RECONFIGURE;
752                 }
753             }
754         }
755
756         SIMAP_FOR_EACH (node, &tmp_backers) {
757             dpif_port_del(backer->dpif, u32_to_odp(node->data));
758         }
759         simap_destroy(&tmp_backers);
760
761         switch (backer->need_revalidate) {
762         case REV_RECONFIGURE:   COVERAGE_INC(rev_reconfigure);   break;
763         case REV_STP:           COVERAGE_INC(rev_stp);           break;
764         case REV_BOND:          COVERAGE_INC(rev_bond);          break;
765         case REV_PORT_TOGGLED:  COVERAGE_INC(rev_port_toggled);  break;
766         case REV_FLOW_TABLE:    COVERAGE_INC(rev_flow_table);    break;
767         case REV_MAC_LEARNING:  COVERAGE_INC(rev_mac_learning);  break;
768         case REV_INCONSISTENCY: COVERAGE_INC(rev_inconsistency); break;
769         }
770         backer->need_revalidate = 0;
771
772         /* Clear the drop_keys in case we should now be accepting some
773          * formerly dropped flows. */
774         drop_key_clear(backer);
775
776         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
777             struct facet *facet, *next;
778             struct ofport_dpif *ofport;
779             struct cls_cursor cursor;
780             struct ofbundle *bundle;
781
782             if (ofproto->backer != backer) {
783                 continue;
784             }
785
786             xlate_ofproto_set(ofproto, ofproto->up.name,
787                               ofproto->backer->dpif, ofproto->ml,
788                               ofproto->stp, ofproto->mbridge,
789                               ofproto->sflow, ofproto->ipfix,
790                               ofproto->up.frag_handling,
791                               ofproto->up.forward_bpdu,
792                               connmgr_has_in_band(ofproto->up.connmgr),
793                               ofproto->netflow != NULL);
794
795             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
796                 xlate_bundle_set(ofproto, bundle, bundle->name,
797                                  bundle->vlan_mode, bundle->vlan,
798                                  bundle->trunks, bundle->use_priority_tags,
799                                  bundle->bond, bundle->lacp,
800                                  bundle->floodable);
801             }
802
803             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
804                 int stp_port = ofport->stp_port
805                     ? stp_port_no(ofport->stp_port)
806                     : 0;
807                 xlate_ofport_set(ofproto, ofport->bundle, ofport,
808                                  ofport->up.ofp_port, ofport->odp_port,
809                                  ofport->up.netdev, ofport->cfm,
810                                  ofport->bfd, ofport->peer, stp_port,
811                                  ofport->qdscp, ofport->n_qdscp,
812                                  ofport->up.pp.config, ofport->is_tunnel,
813                                  ofport->may_enable);
814             }
815
816             cls_cursor_init(&cursor, &ofproto->facets, NULL);
817             CLS_CURSOR_FOR_EACH_SAFE (facet, next, cr, &cursor) {
818                 facet_revalidate(facet);
819                 run_fast_rl();
820             }
821         }
822     }
823
824     if (!backer->recv_set_enable) {
825         /* Wake up before a max of 1000ms. */
826         timer_set_duration(&backer->next_expiration, 1000);
827     } else if (timer_expired(&backer->next_expiration)) {
828         int delay = expire(backer);
829         timer_set_duration(&backer->next_expiration, delay);
830     }
831
832     process_dpif_port_changes(backer);
833
834     if (backer->governor) {
835         size_t n_subfacets;
836
837         governor_run(backer->governor);
838
839         /* If the governor has shrunk to its minimum size and the number of
840          * subfacets has dwindled, then drop the governor entirely.
841          *
842          * For hysteresis, the number of subfacets to drop the governor is
843          * smaller than the number needed to trigger its creation. */
844         n_subfacets = hmap_count(&backer->subfacets);
845         if (n_subfacets * 4 < flow_eviction_threshold
846             && governor_is_idle(backer->governor)) {
847             governor_destroy(backer->governor);
848             backer->governor = NULL;
849         }
850     }
851
852     return 0;
853 }
854
855 /* Check for and handle port changes in 'backer''s dpif. */
856 static void
857 process_dpif_port_changes(struct dpif_backer *backer)
858 {
859     for (;;) {
860         char *devname;
861         int error;
862
863         error = dpif_port_poll(backer->dpif, &devname);
864         switch (error) {
865         case EAGAIN:
866             return;
867
868         case ENOBUFS:
869             process_dpif_all_ports_changed(backer);
870             break;
871
872         case 0:
873             process_dpif_port_change(backer, devname);
874             free(devname);
875             break;
876
877         default:
878             process_dpif_port_error(backer, error);
879             break;
880         }
881     }
882 }
883
884 static void
885 process_dpif_all_ports_changed(struct dpif_backer *backer)
886 {
887     struct ofproto_dpif *ofproto;
888     struct dpif_port dpif_port;
889     struct dpif_port_dump dump;
890     struct sset devnames;
891     const char *devname;
892
893     sset_init(&devnames);
894     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
895         if (ofproto->backer == backer) {
896             struct ofport *ofport;
897
898             HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
899                 sset_add(&devnames, netdev_get_name(ofport->netdev));
900             }
901         }
902     }
903     DPIF_PORT_FOR_EACH (&dpif_port, &dump, backer->dpif) {
904         sset_add(&devnames, dpif_port.name);
905     }
906
907     SSET_FOR_EACH (devname, &devnames) {
908         process_dpif_port_change(backer, devname);
909     }
910     sset_destroy(&devnames);
911 }
912
913 static void
914 process_dpif_port_change(struct dpif_backer *backer, const char *devname)
915 {
916     struct ofproto_dpif *ofproto;
917     struct dpif_port port;
918
919     /* Don't report on the datapath's device. */
920     if (!strcmp(devname, dpif_base_name(backer->dpif))) {
921         return;
922     }
923
924     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node,
925                    &all_ofproto_dpifs) {
926         if (simap_contains(&ofproto->backer->tnl_backers, devname)) {
927             return;
928         }
929     }
930
931     ofproto = lookup_ofproto_dpif_by_port_name(devname);
932     if (dpif_port_query_by_name(backer->dpif, devname, &port)) {
933         /* The port was removed.  If we know the datapath,
934          * report it through poll_set().  If we don't, it may be
935          * notifying us of a removal we initiated, so ignore it.
936          * If there's a pending ENOBUFS, let it stand, since
937          * everything will be reevaluated. */
938         if (ofproto && ofproto->port_poll_errno != ENOBUFS) {
939             sset_add(&ofproto->port_poll_set, devname);
940             ofproto->port_poll_errno = 0;
941         }
942     } else if (!ofproto) {
943         /* The port was added, but we don't know with which
944          * ofproto we should associate it.  Delete it. */
945         dpif_port_del(backer->dpif, port.port_no);
946     } else {
947         struct ofport_dpif *ofport;
948
949         ofport = ofport_dpif_cast(shash_find_data(
950                                       &ofproto->up.port_by_name, devname));
951         if (ofport
952             && ofport->odp_port != port.port_no
953             && !odp_port_to_ofport(backer, port.port_no))
954         {
955             /* 'ofport''s datapath port number has changed from
956              * 'ofport->odp_port' to 'port.port_no'.  Update our internal data
957              * structures to match. */
958             hmap_remove(&backer->odp_to_ofport_map, &ofport->odp_port_node);
959             ofport->odp_port = port.port_no;
960             hmap_insert(&backer->odp_to_ofport_map, &ofport->odp_port_node,
961                         hash_odp_port(port.port_no));
962             backer->need_revalidate = REV_RECONFIGURE;
963         }
964     }
965     dpif_port_destroy(&port);
966 }
967
968 /* Propagate 'error' to all ofprotos based on 'backer'. */
969 static void
970 process_dpif_port_error(struct dpif_backer *backer, int error)
971 {
972     struct ofproto_dpif *ofproto;
973
974     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
975         if (ofproto->backer == backer) {
976             sset_clear(&ofproto->port_poll_set);
977             ofproto->port_poll_errno = error;
978         }
979     }
980 }
981
982 static int
983 dpif_backer_run_fast(struct dpif_backer *backer, int max_batch)
984 {
985     unsigned int work;
986
987     /* If recv_set_enable is false, we should not handle upcalls. */
988     if (!backer->recv_set_enable) {
989         return 0;
990     }
991
992     /* Handle one or more batches of upcalls, until there's nothing left to do
993      * or until we do a fixed total amount of work.
994      *
995      * We do work in batches because it can be much cheaper to set up a number
996      * of flows and fire off their patches all at once.  We do multiple batches
997      * because in some cases handling a packet can cause another packet to be
998      * queued almost immediately as part of the return flow.  Both
999      * optimizations can make major improvements on some benchmarks and
1000      * presumably for real traffic as well. */
1001     work = 0;
1002     while (work < max_batch) {
1003         int retval = handle_upcalls(backer, max_batch - work);
1004         if (retval <= 0) {
1005             return -retval;
1006         }
1007         work += retval;
1008     }
1009
1010     return 0;
1011 }
1012
1013 static int
1014 type_run_fast(const char *type)
1015 {
1016     struct dpif_backer *backer;
1017
1018     backer = shash_find_data(&all_dpif_backers, type);
1019     if (!backer) {
1020         /* This is not necessarily a problem, since backers are only
1021          * created on demand. */
1022         return 0;
1023     }
1024
1025     return dpif_backer_run_fast(backer, FLOW_MISS_MAX_BATCH);
1026 }
1027
1028 static void
1029 run_fast_rl(void)
1030 {
1031     static long long int port_rl = LLONG_MIN;
1032     static unsigned int backer_rl = 0;
1033
1034     if (time_msec() >= port_rl) {
1035         struct ofproto_dpif *ofproto;
1036
1037         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
1038             run_fast(&ofproto->up);
1039         }
1040         port_rl = time_msec() + 200;
1041     }
1042
1043     /* XXX: We have to be careful not to do too much work in this function.  If
1044      * we call dpif_backer_run_fast() too often, or with too large a batch,
1045      * performance improves signifcantly, but at a cost.  It's possible for the
1046      * number of flows in the datapath to increase without bound, and for poll
1047      * loops to take 10s of seconds.   The correct solution to this problem,
1048      * long term, is to separate flow miss handling into it's own thread so it
1049      * isn't affected by revalidations, and expirations.  Until then, this is
1050      * the best we can do. */
1051     if (++backer_rl >= 10) {
1052         struct shash_node *node;
1053
1054         backer_rl = 0;
1055         SHASH_FOR_EACH (node, &all_dpif_backers) {
1056             dpif_backer_run_fast(node->data, 1);
1057         }
1058     }
1059 }
1060
1061 static void
1062 type_wait(const char *type)
1063 {
1064     struct dpif_backer *backer;
1065
1066     backer = shash_find_data(&all_dpif_backers, type);
1067     if (!backer) {
1068         /* This is not necessarily a problem, since backers are only
1069          * created on demand. */
1070         return;
1071     }
1072
1073     if (backer->governor) {
1074         governor_wait(backer->governor);
1075     }
1076
1077     timer_wait(&backer->next_expiration);
1078 }
1079 \f
1080 /* Basic life-cycle. */
1081
1082 static int add_internal_flows(struct ofproto_dpif *);
1083
1084 static struct ofproto *
1085 alloc(void)
1086 {
1087     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
1088     return &ofproto->up;
1089 }
1090
1091 static void
1092 dealloc(struct ofproto *ofproto_)
1093 {
1094     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1095     free(ofproto);
1096 }
1097
1098 static void
1099 close_dpif_backer(struct dpif_backer *backer)
1100 {
1101     struct shash_node *node;
1102
1103     ovs_assert(backer->refcount > 0);
1104
1105     if (--backer->refcount) {
1106         return;
1107     }
1108
1109     drop_key_clear(backer);
1110     hmap_destroy(&backer->drop_keys);
1111
1112     simap_destroy(&backer->tnl_backers);
1113     hmap_destroy(&backer->odp_to_ofport_map);
1114     node = shash_find(&all_dpif_backers, backer->type);
1115     free(backer->type);
1116     shash_delete(&all_dpif_backers, node);
1117     dpif_close(backer->dpif);
1118
1119     ovs_assert(hmap_is_empty(&backer->subfacets));
1120     hmap_destroy(&backer->subfacets);
1121     governor_destroy(backer->governor);
1122
1123     free(backer);
1124 }
1125
1126 /* Datapath port slated for removal from datapath. */
1127 struct odp_garbage {
1128     struct list list_node;
1129     odp_port_t odp_port;
1130 };
1131
1132 static int
1133 open_dpif_backer(const char *type, struct dpif_backer **backerp)
1134 {
1135     struct dpif_backer *backer;
1136     struct dpif_port_dump port_dump;
1137     struct dpif_port port;
1138     struct shash_node *node;
1139     struct list garbage_list;
1140     struct odp_garbage *garbage, *next;
1141     struct sset names;
1142     char *backer_name;
1143     const char *name;
1144     int error;
1145
1146     backer = shash_find_data(&all_dpif_backers, type);
1147     if (backer) {
1148         backer->refcount++;
1149         *backerp = backer;
1150         return 0;
1151     }
1152
1153     backer_name = xasprintf("ovs-%s", type);
1154
1155     /* Remove any existing datapaths, since we assume we're the only
1156      * userspace controlling the datapath. */
1157     sset_init(&names);
1158     dp_enumerate_names(type, &names);
1159     SSET_FOR_EACH(name, &names) {
1160         struct dpif *old_dpif;
1161
1162         /* Don't remove our backer if it exists. */
1163         if (!strcmp(name, backer_name)) {
1164             continue;
1165         }
1166
1167         if (dpif_open(name, type, &old_dpif)) {
1168             VLOG_WARN("couldn't open old datapath %s to remove it", name);
1169         } else {
1170             dpif_delete(old_dpif);
1171             dpif_close(old_dpif);
1172         }
1173     }
1174     sset_destroy(&names);
1175
1176     backer = xmalloc(sizeof *backer);
1177
1178     error = dpif_create_and_open(backer_name, type, &backer->dpif);
1179     free(backer_name);
1180     if (error) {
1181         VLOG_ERR("failed to open datapath of type %s: %s", type,
1182                  ovs_strerror(error));
1183         free(backer);
1184         return error;
1185     }
1186
1187     backer->type = xstrdup(type);
1188     backer->governor = NULL;
1189     backer->refcount = 1;
1190     hmap_init(&backer->odp_to_ofport_map);
1191     hmap_init(&backer->drop_keys);
1192     hmap_init(&backer->subfacets);
1193     timer_set_duration(&backer->next_expiration, 1000);
1194     backer->need_revalidate = 0;
1195     simap_init(&backer->tnl_backers);
1196     backer->recv_set_enable = !ofproto_get_flow_restore_wait();
1197     *backerp = backer;
1198
1199     if (backer->recv_set_enable) {
1200         dpif_flow_flush(backer->dpif);
1201     }
1202
1203     /* Loop through the ports already on the datapath and remove any
1204      * that we don't need anymore. */
1205     list_init(&garbage_list);
1206     dpif_port_dump_start(&port_dump, backer->dpif);
1207     while (dpif_port_dump_next(&port_dump, &port)) {
1208         node = shash_find(&init_ofp_ports, port.name);
1209         if (!node && strcmp(port.name, dpif_base_name(backer->dpif))) {
1210             garbage = xmalloc(sizeof *garbage);
1211             garbage->odp_port = port.port_no;
1212             list_push_front(&garbage_list, &garbage->list_node);
1213         }
1214     }
1215     dpif_port_dump_done(&port_dump);
1216
1217     LIST_FOR_EACH_SAFE (garbage, next, list_node, &garbage_list) {
1218         dpif_port_del(backer->dpif, garbage->odp_port);
1219         list_remove(&garbage->list_node);
1220         free(garbage);
1221     }
1222
1223     shash_add(&all_dpif_backers, type, backer);
1224
1225     error = dpif_recv_set(backer->dpif, backer->recv_set_enable);
1226     if (error) {
1227         VLOG_ERR("failed to listen on datapath of type %s: %s",
1228                  type, ovs_strerror(error));
1229         close_dpif_backer(backer);
1230         return error;
1231     }
1232
1233     backer->max_n_subfacet = 0;
1234     backer->created = time_msec();
1235     backer->last_minute = backer->created;
1236     memset(&backer->hourly, 0, sizeof backer->hourly);
1237     memset(&backer->daily, 0, sizeof backer->daily);
1238     memset(&backer->lifetime, 0, sizeof backer->lifetime);
1239     backer->subfacet_add_count = 0;
1240     backer->subfacet_del_count = 0;
1241     backer->total_subfacet_add_count = 0;
1242     backer->total_subfacet_del_count = 0;
1243     backer->avg_n_subfacet = 0;
1244     backer->avg_subfacet_life = 0;
1245
1246     return error;
1247 }
1248
1249 static int
1250 construct(struct ofproto *ofproto_)
1251 {
1252     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1253     struct shash_node *node, *next;
1254     odp_port_t max_ports;
1255     int error;
1256
1257     error = open_dpif_backer(ofproto->up.type, &ofproto->backer);
1258     if (error) {
1259         return error;
1260     }
1261
1262     max_ports = dpif_get_max_ports(ofproto->backer->dpif);
1263     ofproto_init_max_ports(ofproto_, u16_to_ofp(MIN(odp_to_u32(max_ports),
1264                                                     ofp_to_u16(OFPP_MAX))));
1265
1266     ofproto->netflow = NULL;
1267     ofproto->sflow = NULL;
1268     ofproto->ipfix = NULL;
1269     ofproto->stp = NULL;
1270     hmap_init(&ofproto->bundles);
1271     ofproto->ml = mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME);
1272     ofproto->mbridge = mbridge_create();
1273     ofproto->has_bonded_bundles = false;
1274     ovs_mutex_init(&ofproto->vsp_mutex, PTHREAD_MUTEX_NORMAL);
1275
1276     classifier_init(&ofproto->facets);
1277     ofproto->consistency_rl = LLONG_MIN;
1278
1279     list_init(&ofproto->completions);
1280
1281     ovs_mutex_init(&ofproto->flow_mod_mutex, PTHREAD_MUTEX_NORMAL);
1282     ovs_mutex_lock(&ofproto->flow_mod_mutex);
1283     list_init(&ofproto->flow_mods);
1284     ofproto->n_flow_mods = 0;
1285     ovs_mutex_unlock(&ofproto->flow_mod_mutex);
1286
1287     ofproto_dpif_unixctl_init();
1288
1289     hmap_init(&ofproto->vlandev_map);
1290     hmap_init(&ofproto->realdev_vid_map);
1291
1292     sset_init(&ofproto->ports);
1293     sset_init(&ofproto->ghost_ports);
1294     sset_init(&ofproto->port_poll_set);
1295     ofproto->port_poll_errno = 0;
1296
1297     SHASH_FOR_EACH_SAFE (node, next, &init_ofp_ports) {
1298         struct iface_hint *iface_hint = node->data;
1299
1300         if (!strcmp(iface_hint->br_name, ofproto->up.name)) {
1301             /* Check if the datapath already has this port. */
1302             if (dpif_port_exists(ofproto->backer->dpif, node->name)) {
1303                 sset_add(&ofproto->ports, node->name);
1304             }
1305
1306             free(iface_hint->br_name);
1307             free(iface_hint->br_type);
1308             free(iface_hint);
1309             shash_delete(&init_ofp_ports, node);
1310         }
1311     }
1312
1313     hmap_insert(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node,
1314                 hash_string(ofproto->up.name, 0));
1315     memset(&ofproto->stats, 0, sizeof ofproto->stats);
1316
1317     ofproto_init_tables(ofproto_, N_TABLES);
1318     error = add_internal_flows(ofproto);
1319     ofproto->up.tables[TBL_INTERNAL].flags = OFTABLE_HIDDEN | OFTABLE_READONLY;
1320
1321     ofproto->n_hit = 0;
1322     ofproto->n_missed = 0;
1323
1324     return error;
1325 }
1326
1327 static int
1328 add_internal_flow(struct ofproto_dpif *ofproto, int id,
1329                   const struct ofpbuf *ofpacts, struct rule_dpif **rulep)
1330 {
1331     struct ofputil_flow_mod fm;
1332     int error;
1333
1334     match_init_catchall(&fm.match);
1335     fm.priority = 0;
1336     match_set_reg(&fm.match, 0, id);
1337     fm.new_cookie = htonll(0);
1338     fm.cookie = htonll(0);
1339     fm.cookie_mask = htonll(0);
1340     fm.modify_cookie = false;
1341     fm.table_id = TBL_INTERNAL;
1342     fm.command = OFPFC_ADD;
1343     fm.idle_timeout = 0;
1344     fm.hard_timeout = 0;
1345     fm.buffer_id = 0;
1346     fm.out_port = 0;
1347     fm.flags = 0;
1348     fm.ofpacts = ofpacts->data;
1349     fm.ofpacts_len = ofpacts->size;
1350
1351     error = ofproto_flow_mod(&ofproto->up, &fm);
1352     if (error) {
1353         VLOG_ERR_RL(&rl, "failed to add internal flow %d (%s)",
1354                     id, ofperr_to_string(error));
1355         return error;
1356     }
1357
1358     *rulep = rule_dpif_lookup_in_table(ofproto, &fm.match.flow, NULL,
1359                                        TBL_INTERNAL);
1360     ovs_assert(*rulep != NULL);
1361
1362     return 0;
1363 }
1364
1365 static int
1366 add_internal_flows(struct ofproto_dpif *ofproto)
1367 {
1368     struct ofpact_controller *controller;
1369     uint64_t ofpacts_stub[128 / 8];
1370     struct ofpbuf ofpacts;
1371     int error;
1372     int id;
1373
1374     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
1375     id = 1;
1376
1377     controller = ofpact_put_CONTROLLER(&ofpacts);
1378     controller->max_len = UINT16_MAX;
1379     controller->controller_id = 0;
1380     controller->reason = OFPR_NO_MATCH;
1381     ofpact_pad(&ofpacts);
1382
1383     error = add_internal_flow(ofproto, id++, &ofpacts, &ofproto->miss_rule);
1384     if (error) {
1385         return error;
1386     }
1387
1388     ofpbuf_clear(&ofpacts);
1389     error = add_internal_flow(ofproto, id++, &ofpacts,
1390                               &ofproto->no_packet_in_rule);
1391     if (error) {
1392         return error;
1393     }
1394
1395     error = add_internal_flow(ofproto, id++, &ofpacts,
1396                               &ofproto->drop_frags_rule);
1397     return error;
1398 }
1399
1400 static void
1401 complete_operations(struct ofproto_dpif *ofproto)
1402 {
1403     struct dpif_completion *c, *next;
1404
1405     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
1406         ofoperation_complete(c->op, 0);
1407         list_remove(&c->list_node);
1408         free(c);
1409     }
1410 }
1411
1412 static void
1413 destruct(struct ofproto *ofproto_)
1414 {
1415     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1416     struct rule_dpif *rule, *next_rule;
1417     struct ofputil_flow_mod *fm, *next_fm;
1418     struct oftable *table;
1419
1420     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1421     xlate_remove_ofproto(ofproto);
1422
1423     hmap_remove(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node);
1424     complete_operations(ofproto);
1425
1426     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
1427         struct cls_cursor cursor;
1428
1429         cls_cursor_init(&cursor, &table->cls, NULL);
1430         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
1431             ofproto_rule_destroy(&rule->up);
1432         }
1433     }
1434
1435     ovs_mutex_lock(&ofproto->flow_mod_mutex);
1436     LIST_FOR_EACH_SAFE (fm, next_fm, list_node, &ofproto->flow_mods) {
1437         list_remove(&fm->list_node);
1438         ofproto->n_flow_mods--;
1439         free(fm->ofpacts);
1440         free(fm);
1441     }
1442     ovs_mutex_unlock(&ofproto->flow_mod_mutex);
1443     ovs_mutex_destroy(&ofproto->flow_mod_mutex);
1444
1445     mbridge_unref(ofproto->mbridge);
1446
1447     netflow_destroy(ofproto->netflow);
1448     dpif_sflow_unref(ofproto->sflow);
1449     hmap_destroy(&ofproto->bundles);
1450     mac_learning_unref(ofproto->ml);
1451
1452     classifier_destroy(&ofproto->facets);
1453
1454     hmap_destroy(&ofproto->vlandev_map);
1455     hmap_destroy(&ofproto->realdev_vid_map);
1456
1457     sset_destroy(&ofproto->ports);
1458     sset_destroy(&ofproto->ghost_ports);
1459     sset_destroy(&ofproto->port_poll_set);
1460
1461     ovs_mutex_destroy(&ofproto->vsp_mutex);
1462
1463     close_dpif_backer(ofproto->backer);
1464 }
1465
1466 static int
1467 run_fast(struct ofproto *ofproto_)
1468 {
1469     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1470     struct ofputil_flow_mod *fm, *next;
1471     struct ofport_dpif *ofport;
1472     struct list flow_mods;
1473
1474     /* Do not perform any periodic activity required by 'ofproto' while
1475      * waiting for flow restore to complete. */
1476     if (ofproto_get_flow_restore_wait()) {
1477         return 0;
1478     }
1479
1480     ovs_mutex_lock(&ofproto->flow_mod_mutex);
1481     if (ofproto->n_flow_mods) {
1482         flow_mods = ofproto->flow_mods;
1483         list_moved(&flow_mods);
1484         list_init(&ofproto->flow_mods);
1485         ofproto->n_flow_mods = 0;
1486     } else {
1487         list_init(&flow_mods);
1488     }
1489     ovs_mutex_unlock(&ofproto->flow_mod_mutex);
1490
1491     LIST_FOR_EACH_SAFE (fm, next, list_node, &flow_mods) {
1492         int error = ofproto_flow_mod(&ofproto->up, fm);
1493         if (error && !VLOG_DROP_WARN(&rl)) {
1494             VLOG_WARN("learning action failed to modify flow table (%s)",
1495                       ofperr_get_name(error));
1496         }
1497
1498         list_remove(&fm->list_node);
1499         free(fm->ofpacts);
1500         free(fm);
1501     }
1502
1503     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1504         port_run_fast(ofport);
1505     }
1506
1507     return 0;
1508 }
1509
1510 static int
1511 run(struct ofproto *ofproto_)
1512 {
1513     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1514     struct ofport_dpif *ofport;
1515     struct ofbundle *bundle;
1516     int error;
1517
1518     if (!clogged) {
1519         complete_operations(ofproto);
1520     }
1521
1522     if (mbridge_need_revalidate(ofproto->mbridge)) {
1523         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1524         ovs_rwlock_wrlock(&ofproto->ml->rwlock);
1525         mac_learning_flush(ofproto->ml);
1526         ovs_rwlock_unlock(&ofproto->ml->rwlock);
1527     }
1528
1529     /* Do not perform any periodic activity below required by 'ofproto' while
1530      * waiting for flow restore to complete. */
1531     if (ofproto_get_flow_restore_wait()) {
1532         return 0;
1533     }
1534
1535     error = run_fast(ofproto_);
1536     if (error) {
1537         return error;
1538     }
1539
1540     if (ofproto->netflow) {
1541         if (netflow_run(ofproto->netflow)) {
1542             send_netflow_active_timeouts(ofproto);
1543         }
1544     }
1545     if (ofproto->sflow) {
1546         dpif_sflow_run(ofproto->sflow);
1547     }
1548
1549     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1550         port_run(ofport);
1551     }
1552     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1553         bundle_run(bundle);
1554     }
1555
1556     stp_run(ofproto);
1557     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
1558     if (mac_learning_run(ofproto->ml)) {
1559         ofproto->backer->need_revalidate = REV_MAC_LEARNING;
1560     }
1561     ovs_rwlock_unlock(&ofproto->ml->rwlock);
1562
1563     /* Check the consistency of a random facet, to aid debugging. */
1564     if (time_msec() >= ofproto->consistency_rl
1565         && !classifier_is_empty(&ofproto->facets)
1566         && !ofproto->backer->need_revalidate) {
1567         struct cls_table *table;
1568         struct cls_rule *cr;
1569         struct facet *facet;
1570
1571         ofproto->consistency_rl = time_msec() + 250;
1572
1573         table = CONTAINER_OF(hmap_random_node(&ofproto->facets.tables),
1574                              struct cls_table, hmap_node);
1575         cr = CONTAINER_OF(hmap_random_node(&table->rules), struct cls_rule,
1576                           hmap_node);
1577         facet = CONTAINER_OF(cr, struct facet, cr);
1578
1579         if (!facet_check_consistency(facet)) {
1580             ofproto->backer->need_revalidate = REV_INCONSISTENCY;
1581         }
1582     }
1583
1584     return 0;
1585 }
1586
1587 static void
1588 wait(struct ofproto *ofproto_)
1589 {
1590     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1591     struct ofport_dpif *ofport;
1592     struct ofbundle *bundle;
1593
1594     if (!clogged && !list_is_empty(&ofproto->completions)) {
1595         poll_immediate_wake();
1596     }
1597
1598     if (ofproto_get_flow_restore_wait()) {
1599         return;
1600     }
1601
1602     dpif_wait(ofproto->backer->dpif);
1603     dpif_recv_wait(ofproto->backer->dpif);
1604     if (ofproto->sflow) {
1605         dpif_sflow_wait(ofproto->sflow);
1606     }
1607     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1608         port_wait(ofport);
1609     }
1610     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1611         bundle_wait(bundle);
1612     }
1613     if (ofproto->netflow) {
1614         netflow_wait(ofproto->netflow);
1615     }
1616     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
1617     mac_learning_wait(ofproto->ml);
1618     ovs_rwlock_unlock(&ofproto->ml->rwlock);
1619     stp_wait(ofproto);
1620     if (ofproto->backer->need_revalidate) {
1621         /* Shouldn't happen, but if it does just go around again. */
1622         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1623         poll_immediate_wake();
1624     }
1625 }
1626
1627 static void
1628 get_memory_usage(const struct ofproto *ofproto_, struct simap *usage)
1629 {
1630     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1631     struct cls_cursor cursor;
1632     size_t n_subfacets = 0;
1633     struct facet *facet;
1634
1635     simap_increase(usage, "facets", classifier_count(&ofproto->facets));
1636
1637     cls_cursor_init(&cursor, &ofproto->facets, NULL);
1638     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
1639         n_subfacets += list_size(&facet->subfacets);
1640     }
1641     simap_increase(usage, "subfacets", n_subfacets);
1642 }
1643
1644 static void
1645 flush(struct ofproto *ofproto_)
1646 {
1647     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1648     struct subfacet *subfacet, *next_subfacet;
1649     struct subfacet *batch[SUBFACET_DESTROY_MAX_BATCH];
1650     int n_batch;
1651
1652     n_batch = 0;
1653     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
1654                         &ofproto->backer->subfacets) {
1655         if (subfacet->facet->ofproto != ofproto) {
1656             continue;
1657         }
1658
1659         if (subfacet->path != SF_NOT_INSTALLED) {
1660             batch[n_batch++] = subfacet;
1661             if (n_batch >= SUBFACET_DESTROY_MAX_BATCH) {
1662                 subfacet_destroy_batch(ofproto->backer, batch, n_batch);
1663                 n_batch = 0;
1664             }
1665         } else {
1666             subfacet_destroy(subfacet);
1667         }
1668     }
1669
1670     if (n_batch > 0) {
1671         subfacet_destroy_batch(ofproto->backer, batch, n_batch);
1672     }
1673 }
1674
1675 static void
1676 get_features(struct ofproto *ofproto_ OVS_UNUSED,
1677              bool *arp_match_ip, enum ofputil_action_bitmap *actions)
1678 {
1679     *arp_match_ip = true;
1680     *actions = (OFPUTIL_A_OUTPUT |
1681                 OFPUTIL_A_SET_VLAN_VID |
1682                 OFPUTIL_A_SET_VLAN_PCP |
1683                 OFPUTIL_A_STRIP_VLAN |
1684                 OFPUTIL_A_SET_DL_SRC |
1685                 OFPUTIL_A_SET_DL_DST |
1686                 OFPUTIL_A_SET_NW_SRC |
1687                 OFPUTIL_A_SET_NW_DST |
1688                 OFPUTIL_A_SET_NW_TOS |
1689                 OFPUTIL_A_SET_TP_SRC |
1690                 OFPUTIL_A_SET_TP_DST |
1691                 OFPUTIL_A_ENQUEUE);
1692 }
1693
1694 static void
1695 get_tables(struct ofproto *ofproto_, struct ofp12_table_stats *ots)
1696 {
1697     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1698     struct dpif_dp_stats s;
1699     uint64_t n_miss, n_no_pkt_in, n_bytes, n_dropped_frags;
1700     uint64_t n_lookup;
1701
1702     strcpy(ots->name, "classifier");
1703
1704     dpif_get_dp_stats(ofproto->backer->dpif, &s);
1705     rule_get_stats(&ofproto->miss_rule->up, &n_miss, &n_bytes);
1706     rule_get_stats(&ofproto->no_packet_in_rule->up, &n_no_pkt_in, &n_bytes);
1707     rule_get_stats(&ofproto->drop_frags_rule->up, &n_dropped_frags, &n_bytes);
1708
1709     n_lookup = s.n_hit + s.n_missed - n_dropped_frags;
1710     ots->lookup_count = htonll(n_lookup);
1711     ots->matched_count = htonll(n_lookup - n_miss - n_no_pkt_in);
1712 }
1713
1714 static struct ofport *
1715 port_alloc(void)
1716 {
1717     struct ofport_dpif *port = xmalloc(sizeof *port);
1718     return &port->up;
1719 }
1720
1721 static void
1722 port_dealloc(struct ofport *port_)
1723 {
1724     struct ofport_dpif *port = ofport_dpif_cast(port_);
1725     free(port);
1726 }
1727
1728 static int
1729 port_construct(struct ofport *port_)
1730 {
1731     struct ofport_dpif *port = ofport_dpif_cast(port_);
1732     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1733     const struct netdev *netdev = port->up.netdev;
1734     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1735     struct dpif_port dpif_port;
1736     int error;
1737
1738     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1739     port->bundle = NULL;
1740     port->cfm = NULL;
1741     port->bfd = NULL;
1742     port->may_enable = true;
1743     port->stp_port = NULL;
1744     port->stp_state = STP_DISABLED;
1745     port->is_tunnel = false;
1746     port->peer = NULL;
1747     port->qdscp = NULL;
1748     port->n_qdscp = 0;
1749     port->realdev_ofp_port = 0;
1750     port->vlandev_vid = 0;
1751     port->carrier_seq = netdev_get_carrier_resets(netdev);
1752
1753     if (netdev_vport_is_patch(netdev)) {
1754         /* By bailing out here, we don't submit the port to the sFlow module
1755          * to be considered for counter polling export.  This is correct
1756          * because the patch port represents an interface that sFlow considers
1757          * to be "internal" to the switch as a whole, and therefore not an
1758          * candidate for counter polling. */
1759         port->odp_port = ODPP_NONE;
1760         ofport_update_peer(port);
1761         return 0;
1762     }
1763
1764     error = dpif_port_query_by_name(ofproto->backer->dpif,
1765                                     netdev_vport_get_dpif_port(netdev, namebuf,
1766                                                                sizeof namebuf),
1767                                     &dpif_port);
1768     if (error) {
1769         return error;
1770     }
1771
1772     port->odp_port = dpif_port.port_no;
1773
1774     if (netdev_get_tunnel_config(netdev)) {
1775         tnl_port_add(port, port->up.netdev, port->odp_port);
1776         port->is_tunnel = true;
1777     } else {
1778         /* Sanity-check that a mapping doesn't already exist.  This
1779          * shouldn't happen for non-tunnel ports. */
1780         if (odp_port_to_ofp_port(ofproto, port->odp_port) != OFPP_NONE) {
1781             VLOG_ERR("port %s already has an OpenFlow port number",
1782                      dpif_port.name);
1783             dpif_port_destroy(&dpif_port);
1784             return EBUSY;
1785         }
1786
1787         hmap_insert(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node,
1788                     hash_odp_port(port->odp_port));
1789     }
1790     dpif_port_destroy(&dpif_port);
1791
1792     if (ofproto->sflow) {
1793         dpif_sflow_add_port(ofproto->sflow, port_, port->odp_port);
1794     }
1795
1796     return 0;
1797 }
1798
1799 static void
1800 port_destruct(struct ofport *port_)
1801 {
1802     struct ofport_dpif *port = ofport_dpif_cast(port_);
1803     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1804     const char *devname = netdev_get_name(port->up.netdev);
1805     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1806     const char *dp_port_name;
1807
1808     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1809     xlate_ofport_remove(port);
1810
1811     dp_port_name = netdev_vport_get_dpif_port(port->up.netdev, namebuf,
1812                                               sizeof namebuf);
1813     if (dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
1814         /* The underlying device is still there, so delete it.  This
1815          * happens when the ofproto is being destroyed, since the caller
1816          * assumes that removal of attached ports will happen as part of
1817          * destruction. */
1818         if (!port->is_tunnel) {
1819             dpif_port_del(ofproto->backer->dpif, port->odp_port);
1820         }
1821     }
1822
1823     if (port->peer) {
1824         port->peer->peer = NULL;
1825         port->peer = NULL;
1826     }
1827
1828     if (port->odp_port != ODPP_NONE && !port->is_tunnel) {
1829         hmap_remove(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node);
1830     }
1831
1832     tnl_port_del(port);
1833     sset_find_and_delete(&ofproto->ports, devname);
1834     sset_find_and_delete(&ofproto->ghost_ports, devname);
1835     bundle_remove(port_);
1836     set_cfm(port_, NULL);
1837     set_bfd(port_, NULL);
1838     if (ofproto->sflow) {
1839         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
1840     }
1841
1842     free(port->qdscp);
1843 }
1844
1845 static void
1846 port_modified(struct ofport *port_)
1847 {
1848     struct ofport_dpif *port = ofport_dpif_cast(port_);
1849
1850     if (port->bundle && port->bundle->bond) {
1851         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
1852     }
1853
1854     if (port->cfm) {
1855         cfm_set_netdev(port->cfm, port->up.netdev);
1856     }
1857
1858     if (port->is_tunnel && tnl_port_reconfigure(port, port->up.netdev,
1859                                                 port->odp_port)) {
1860         ofproto_dpif_cast(port->up.ofproto)->backer->need_revalidate =
1861             REV_RECONFIGURE;
1862     }
1863
1864     ofport_update_peer(port);
1865 }
1866
1867 static void
1868 port_reconfigured(struct ofport *port_, enum ofputil_port_config old_config)
1869 {
1870     struct ofport_dpif *port = ofport_dpif_cast(port_);
1871     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1872     enum ofputil_port_config changed = old_config ^ port->up.pp.config;
1873
1874     if (changed & (OFPUTIL_PC_NO_RECV | OFPUTIL_PC_NO_RECV_STP |
1875                    OFPUTIL_PC_NO_FWD | OFPUTIL_PC_NO_FLOOD |
1876                    OFPUTIL_PC_NO_PACKET_IN)) {
1877         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1878
1879         if (changed & OFPUTIL_PC_NO_FLOOD && port->bundle) {
1880             bundle_update(port->bundle);
1881         }
1882     }
1883 }
1884
1885 static int
1886 set_sflow(struct ofproto *ofproto_,
1887           const struct ofproto_sflow_options *sflow_options)
1888 {
1889     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1890     struct dpif_sflow *ds = ofproto->sflow;
1891
1892     if (sflow_options) {
1893         if (!ds) {
1894             struct ofport_dpif *ofport;
1895
1896             ds = ofproto->sflow = dpif_sflow_create();
1897             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1898                 dpif_sflow_add_port(ds, &ofport->up, ofport->odp_port);
1899             }
1900             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1901         }
1902         dpif_sflow_set_options(ds, sflow_options);
1903     } else {
1904         if (ds) {
1905             dpif_sflow_unref(ds);
1906             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1907             ofproto->sflow = NULL;
1908         }
1909     }
1910     return 0;
1911 }
1912
1913 static int
1914 set_ipfix(
1915     struct ofproto *ofproto_,
1916     const struct ofproto_ipfix_bridge_exporter_options *bridge_exporter_options,
1917     const struct ofproto_ipfix_flow_exporter_options *flow_exporters_options,
1918     size_t n_flow_exporters_options)
1919 {
1920     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1921     struct dpif_ipfix *di = ofproto->ipfix;
1922
1923     if (bridge_exporter_options || flow_exporters_options) {
1924         if (!di) {
1925             di = ofproto->ipfix = dpif_ipfix_create();
1926         }
1927         dpif_ipfix_set_options(
1928             di, bridge_exporter_options, flow_exporters_options,
1929             n_flow_exporters_options);
1930     } else {
1931         if (di) {
1932             dpif_ipfix_unref(di);
1933             ofproto->ipfix = NULL;
1934         }
1935     }
1936     return 0;
1937 }
1938
1939 static int
1940 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
1941 {
1942     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1943     int error;
1944
1945     if (!s) {
1946         error = 0;
1947     } else {
1948         if (!ofport->cfm) {
1949             struct ofproto_dpif *ofproto;
1950
1951             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1952             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1953             ofport->cfm = cfm_create(ofport->up.netdev);
1954         }
1955
1956         if (cfm_configure(ofport->cfm, s)) {
1957             return 0;
1958         }
1959
1960         error = EINVAL;
1961     }
1962     cfm_unref(ofport->cfm);
1963     ofport->cfm = NULL;
1964     return error;
1965 }
1966
1967 static bool
1968 get_cfm_status(const struct ofport *ofport_,
1969                struct ofproto_cfm_status *status)
1970 {
1971     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1972
1973     if (ofport->cfm) {
1974         status->faults = cfm_get_fault(ofport->cfm);
1975         status->remote_opstate = cfm_get_opup(ofport->cfm);
1976         status->health = cfm_get_health(ofport->cfm);
1977         cfm_get_remote_mpids(ofport->cfm, &status->rmps, &status->n_rmps);
1978         return true;
1979     } else {
1980         return false;
1981     }
1982 }
1983
1984 static int
1985 set_bfd(struct ofport *ofport_, const struct smap *cfg)
1986 {
1987     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
1988     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1989     struct bfd *old;
1990
1991     old = ofport->bfd;
1992     ofport->bfd = bfd_configure(old, netdev_get_name(ofport->up.netdev), cfg);
1993     if (ofport->bfd != old) {
1994         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1995     }
1996
1997     return 0;
1998 }
1999
2000 static int
2001 get_bfd_status(struct ofport *ofport_, struct smap *smap)
2002 {
2003     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2004
2005     if (ofport->bfd) {
2006         bfd_get_status(ofport->bfd, smap);
2007         return 0;
2008     } else {
2009         return ENOENT;
2010     }
2011 }
2012 \f
2013 /* Spanning Tree. */
2014
2015 static void
2016 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
2017 {
2018     struct ofproto_dpif *ofproto = ofproto_;
2019     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
2020     struct ofport_dpif *ofport;
2021
2022     ofport = stp_port_get_aux(sp);
2023     if (!ofport) {
2024         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
2025                      ofproto->up.name, port_num);
2026     } else {
2027         struct eth_header *eth = pkt->l2;
2028
2029         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
2030         if (eth_addr_is_zero(eth->eth_src)) {
2031             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
2032                          "with unknown MAC", ofproto->up.name, port_num);
2033         } else {
2034             send_packet(ofport, pkt);
2035         }
2036     }
2037     ofpbuf_delete(pkt);
2038 }
2039
2040 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
2041 static int
2042 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
2043 {
2044     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2045
2046     /* Only revalidate flows if the configuration changed. */
2047     if (!s != !ofproto->stp) {
2048         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2049     }
2050
2051     if (s) {
2052         if (!ofproto->stp) {
2053             ofproto->stp = stp_create(ofproto_->name, s->system_id,
2054                                       send_bpdu_cb, ofproto);
2055             ofproto->stp_last_tick = time_msec();
2056         }
2057
2058         stp_set_bridge_id(ofproto->stp, s->system_id);
2059         stp_set_bridge_priority(ofproto->stp, s->priority);
2060         stp_set_hello_time(ofproto->stp, s->hello_time);
2061         stp_set_max_age(ofproto->stp, s->max_age);
2062         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
2063     }  else {
2064         struct ofport *ofport;
2065
2066         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
2067             set_stp_port(ofport, NULL);
2068         }
2069
2070         stp_unref(ofproto->stp);
2071         ofproto->stp = NULL;
2072     }
2073
2074     return 0;
2075 }
2076
2077 static int
2078 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
2079 {
2080     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2081
2082     if (ofproto->stp) {
2083         s->enabled = true;
2084         s->bridge_id = stp_get_bridge_id(ofproto->stp);
2085         s->designated_root = stp_get_designated_root(ofproto->stp);
2086         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
2087     } else {
2088         s->enabled = false;
2089     }
2090
2091     return 0;
2092 }
2093
2094 static void
2095 update_stp_port_state(struct ofport_dpif *ofport)
2096 {
2097     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2098     enum stp_state state;
2099
2100     /* Figure out new state. */
2101     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
2102                              : STP_DISABLED;
2103
2104     /* Update state. */
2105     if (ofport->stp_state != state) {
2106         enum ofputil_port_state of_state;
2107         bool fwd_change;
2108
2109         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
2110                     netdev_get_name(ofport->up.netdev),
2111                     stp_state_name(ofport->stp_state),
2112                     stp_state_name(state));
2113         if (stp_learn_in_state(ofport->stp_state)
2114                 != stp_learn_in_state(state)) {
2115             /* xxx Learning action flows should also be flushed. */
2116             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
2117             mac_learning_flush(ofproto->ml);
2118             ovs_rwlock_unlock(&ofproto->ml->rwlock);
2119         }
2120         fwd_change = stp_forward_in_state(ofport->stp_state)
2121                         != stp_forward_in_state(state);
2122
2123         ofproto->backer->need_revalidate = REV_STP;
2124         ofport->stp_state = state;
2125         ofport->stp_state_entered = time_msec();
2126
2127         if (fwd_change && ofport->bundle) {
2128             bundle_update(ofport->bundle);
2129         }
2130
2131         /* Update the STP state bits in the OpenFlow port description. */
2132         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
2133         of_state |= (state == STP_LISTENING ? OFPUTIL_PS_STP_LISTEN
2134                      : state == STP_LEARNING ? OFPUTIL_PS_STP_LEARN
2135                      : state == STP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
2136                      : state == STP_BLOCKING ?  OFPUTIL_PS_STP_BLOCK
2137                      : 0);
2138         ofproto_port_set_state(&ofport->up, of_state);
2139     }
2140 }
2141
2142 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
2143  * caller is responsible for assigning STP port numbers and ensuring
2144  * there are no duplicates. */
2145 static int
2146 set_stp_port(struct ofport *ofport_,
2147              const struct ofproto_port_stp_settings *s)
2148 {
2149     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2150     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2151     struct stp_port *sp = ofport->stp_port;
2152
2153     if (!s || !s->enable) {
2154         if (sp) {
2155             ofport->stp_port = NULL;
2156             stp_port_disable(sp);
2157             update_stp_port_state(ofport);
2158         }
2159         return 0;
2160     } else if (sp && stp_port_no(sp) != s->port_num
2161             && ofport == stp_port_get_aux(sp)) {
2162         /* The port-id changed, so disable the old one if it's not
2163          * already in use by another port. */
2164         stp_port_disable(sp);
2165     }
2166
2167     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
2168     stp_port_enable(sp);
2169
2170     stp_port_set_aux(sp, ofport);
2171     stp_port_set_priority(sp, s->priority);
2172     stp_port_set_path_cost(sp, s->path_cost);
2173
2174     update_stp_port_state(ofport);
2175
2176     return 0;
2177 }
2178
2179 static int
2180 get_stp_port_status(struct ofport *ofport_,
2181                     struct ofproto_port_stp_status *s)
2182 {
2183     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2184     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2185     struct stp_port *sp = ofport->stp_port;
2186
2187     if (!ofproto->stp || !sp) {
2188         s->enabled = false;
2189         return 0;
2190     }
2191
2192     s->enabled = true;
2193     s->port_id = stp_port_get_id(sp);
2194     s->state = stp_port_get_state(sp);
2195     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
2196     s->role = stp_port_get_role(sp);
2197     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
2198
2199     return 0;
2200 }
2201
2202 static void
2203 stp_run(struct ofproto_dpif *ofproto)
2204 {
2205     if (ofproto->stp) {
2206         long long int now = time_msec();
2207         long long int elapsed = now - ofproto->stp_last_tick;
2208         struct stp_port *sp;
2209
2210         if (elapsed > 0) {
2211             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
2212             ofproto->stp_last_tick = now;
2213         }
2214         while (stp_get_changed_port(ofproto->stp, &sp)) {
2215             struct ofport_dpif *ofport = stp_port_get_aux(sp);
2216
2217             if (ofport) {
2218                 update_stp_port_state(ofport);
2219             }
2220         }
2221
2222         if (stp_check_and_reset_fdb_flush(ofproto->stp)) {
2223             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
2224             mac_learning_flush(ofproto->ml);
2225             ovs_rwlock_unlock(&ofproto->ml->rwlock);
2226         }
2227     }
2228 }
2229
2230 static void
2231 stp_wait(struct ofproto_dpif *ofproto)
2232 {
2233     if (ofproto->stp) {
2234         poll_timer_wait(1000);
2235     }
2236 }
2237 \f
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 (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     ovs_mutex_lock(&rule->stats_mutex);
4872     rule->packet_count += stats->n_packets;
4873     rule->byte_count += stats->n_bytes;
4874     ofproto_rule_update_used(&rule->up, stats->used);
4875     ovs_mutex_unlock(&rule->stats_mutex);
4876 }
4877 \f
4878 /* Subfacets. */
4879
4880 static struct subfacet *
4881 subfacet_find(struct dpif_backer *backer, const struct nlattr *key,
4882               size_t key_len, uint32_t key_hash)
4883 {
4884     struct subfacet *subfacet;
4885
4886     HMAP_FOR_EACH_WITH_HASH (subfacet, hmap_node, key_hash,
4887                              &backer->subfacets) {
4888         if (subfacet->key_len == key_len
4889             && !memcmp(key, subfacet->key, key_len)) {
4890             return subfacet;
4891         }
4892     }
4893
4894     return NULL;
4895 }
4896
4897 /* Searches 'facet' (within 'ofproto') for a subfacet with the specified
4898  * 'key_fitness', 'key', and 'key_len' members in 'miss'.  Returns the
4899  * existing subfacet if there is one, otherwise creates and returns a
4900  * new subfacet. */
4901 static struct subfacet *
4902 subfacet_create(struct facet *facet, struct flow_miss *miss,
4903                 long long int now)
4904 {
4905     struct dpif_backer *backer = miss->ofproto->backer;
4906     enum odp_key_fitness key_fitness = miss->key_fitness;
4907     const struct nlattr *key = miss->key;
4908     size_t key_len = miss->key_len;
4909     uint32_t key_hash;
4910     struct subfacet *subfacet;
4911
4912     key_hash = odp_flow_key_hash(key, key_len);
4913
4914     if (list_is_empty(&facet->subfacets)) {
4915         subfacet = &facet->one_subfacet;
4916     } else {
4917         subfacet = subfacet_find(backer, key, key_len, key_hash);
4918         if (subfacet) {
4919             if (subfacet->facet == facet) {
4920                 return subfacet;
4921             }
4922
4923             /* This shouldn't happen. */
4924             VLOG_ERR_RL(&rl, "subfacet with wrong facet");
4925             subfacet_destroy(subfacet);
4926         }
4927
4928         subfacet = xmalloc(sizeof *subfacet);
4929     }
4930
4931     hmap_insert(&backer->subfacets, &subfacet->hmap_node, key_hash);
4932     list_push_back(&facet->subfacets, &subfacet->list_node);
4933     subfacet->facet = facet;
4934     subfacet->key_fitness = key_fitness;
4935     subfacet->key = xmemdup(key, key_len);
4936     subfacet->key_len = key_len;
4937     subfacet->used = now;
4938     subfacet->created = now;
4939     subfacet->dp_packet_count = 0;
4940     subfacet->dp_byte_count = 0;
4941     subfacet->path = SF_NOT_INSTALLED;
4942     subfacet->backer = backer;
4943
4944     backer->subfacet_add_count++;
4945     return subfacet;
4946 }
4947
4948 /* Uninstalls 'subfacet' from the datapath, if it is installed, removes it from
4949  * its facet within 'ofproto', and frees it. */
4950 static void
4951 subfacet_destroy__(struct subfacet *subfacet)
4952 {
4953     struct facet *facet = subfacet->facet;
4954     struct ofproto_dpif *ofproto = facet->ofproto;
4955
4956     /* Update ofproto stats before uninstall the subfacet. */
4957     ofproto->backer->subfacet_del_count++;
4958
4959     subfacet_uninstall(subfacet);
4960     hmap_remove(&subfacet->backer->subfacets, &subfacet->hmap_node);
4961     list_remove(&subfacet->list_node);
4962     free(subfacet->key);
4963     if (subfacet != &facet->one_subfacet) {
4964         free(subfacet);
4965     }
4966 }
4967
4968 /* Destroys 'subfacet', as with subfacet_destroy__(), and then if this was the
4969  * last remaining subfacet in its facet destroys the facet too. */
4970 static void
4971 subfacet_destroy(struct subfacet *subfacet)
4972 {
4973     struct facet *facet = subfacet->facet;
4974
4975     if (list_is_singleton(&facet->subfacets)) {
4976         /* facet_remove() needs at least one subfacet (it will remove it). */
4977         facet_remove(facet);
4978     } else {
4979         subfacet_destroy__(subfacet);
4980     }
4981 }
4982
4983 static void
4984 subfacet_destroy_batch(struct dpif_backer *backer,
4985                        struct subfacet **subfacets, int n)
4986 {
4987     struct dpif_op ops[SUBFACET_DESTROY_MAX_BATCH];
4988     struct dpif_op *opsp[SUBFACET_DESTROY_MAX_BATCH];
4989     struct dpif_flow_stats stats[SUBFACET_DESTROY_MAX_BATCH];
4990     int i;
4991
4992     for (i = 0; i < n; i++) {
4993         ops[i].type = DPIF_OP_FLOW_DEL;
4994         ops[i].u.flow_del.key = subfacets[i]->key;
4995         ops[i].u.flow_del.key_len = subfacets[i]->key_len;
4996         ops[i].u.flow_del.stats = &stats[i];
4997         opsp[i] = &ops[i];
4998     }
4999
5000     dpif_operate(backer->dpif, opsp, n);
5001     for (i = 0; i < n; i++) {
5002         subfacet_reset_dp_stats(subfacets[i], &stats[i]);
5003         subfacets[i]->path = SF_NOT_INSTALLED;
5004         subfacet_destroy(subfacets[i]);
5005         run_fast_rl();
5006     }
5007 }
5008
5009 /* Updates 'subfacet''s datapath flow, setting its actions to 'actions_len'
5010  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
5011  * in the datapath will be zeroed and 'stats' will be updated with traffic new
5012  * since 'subfacet' was last updated.
5013  *
5014  * Returns 0 if successful, otherwise a positive errno value. */
5015 static int
5016 subfacet_install(struct subfacet *subfacet, const struct ofpbuf *odp_actions,
5017                  struct dpif_flow_stats *stats)
5018 {
5019     struct facet *facet = subfacet->facet;
5020     enum subfacet_path path = facet->xout.slow ? SF_SLOW_PATH : SF_FAST_PATH;
5021     const struct nlattr *actions = odp_actions->data;
5022     size_t actions_len = odp_actions->size;
5023     struct odputil_keybuf maskbuf;
5024     struct ofpbuf mask;
5025
5026     uint64_t slow_path_stub[128 / 8];
5027     enum dpif_flow_put_flags flags;
5028     int ret;
5029
5030     flags = subfacet->path == SF_NOT_INSTALLED ? DPIF_FP_CREATE
5031                                                : DPIF_FP_MODIFY;
5032     if (stats) {
5033         flags |= DPIF_FP_ZERO_STATS;
5034     }
5035
5036     if (path == SF_SLOW_PATH) {
5037         compose_slow_path(facet->ofproto, &facet->flow, facet->xout.slow,
5038                           slow_path_stub, sizeof slow_path_stub,
5039                           &actions, &actions_len);
5040     }
5041
5042     ofpbuf_use_stack(&mask, &maskbuf, sizeof maskbuf);
5043     if (enable_megaflows) {
5044         odp_flow_key_from_mask(&mask, &facet->xout.wc.masks,
5045                                &facet->flow, UINT32_MAX);
5046     }
5047
5048     ret = dpif_flow_put(subfacet->backer->dpif, flags, subfacet->key,
5049                         subfacet->key_len,  mask.data, mask.size,
5050                         actions, actions_len, stats);
5051
5052     if (stats) {
5053         subfacet_reset_dp_stats(subfacet, stats);
5054     }
5055
5056     if (ret) {
5057         COVERAGE_INC(subfacet_install_fail);
5058     } else {
5059         subfacet->path = path;
5060     }
5061     return ret;
5062 }
5063
5064 /* If 'subfacet' is installed in the datapath, uninstalls it. */
5065 static void
5066 subfacet_uninstall(struct subfacet *subfacet)
5067 {
5068     if (subfacet->path != SF_NOT_INSTALLED) {
5069         struct ofproto_dpif *ofproto = subfacet->facet->ofproto;
5070         struct dpif_flow_stats stats;
5071         int error;
5072
5073         error = dpif_flow_del(ofproto->backer->dpif, subfacet->key,
5074                               subfacet->key_len, &stats);
5075         subfacet_reset_dp_stats(subfacet, &stats);
5076         if (!error) {
5077             subfacet_update_stats(subfacet, &stats);
5078         }
5079         subfacet->path = SF_NOT_INSTALLED;
5080     } else {
5081         ovs_assert(subfacet->dp_packet_count == 0);
5082         ovs_assert(subfacet->dp_byte_count == 0);
5083     }
5084 }
5085
5086 /* Resets 'subfacet''s datapath statistics counters.  This should be called
5087  * when 'subfacet''s statistics are cleared in the datapath.  If 'stats' is
5088  * non-null, it should contain the statistics returned by dpif when 'subfacet'
5089  * was reset in the datapath.  'stats' will be modified to include only
5090  * statistics new since 'subfacet' was last updated. */
5091 static void
5092 subfacet_reset_dp_stats(struct subfacet *subfacet,
5093                         struct dpif_flow_stats *stats)
5094 {
5095     if (stats
5096         && subfacet->dp_packet_count <= stats->n_packets
5097         && subfacet->dp_byte_count <= stats->n_bytes) {
5098         stats->n_packets -= subfacet->dp_packet_count;
5099         stats->n_bytes -= subfacet->dp_byte_count;
5100     }
5101
5102     subfacet->dp_packet_count = 0;
5103     subfacet->dp_byte_count = 0;
5104 }
5105
5106 /* Folds the statistics from 'stats' into the counters in 'subfacet'.
5107  *
5108  * Because of the meaning of a subfacet's counters, it only makes sense to do
5109  * this if 'stats' are not tracked in the datapath, that is, if 'stats'
5110  * represents a packet that was sent by hand or if it represents statistics
5111  * that have been cleared out of the datapath. */
5112 static void
5113 subfacet_update_stats(struct subfacet *subfacet,
5114                       const struct dpif_flow_stats *stats)
5115 {
5116     if (stats->n_packets || stats->used > subfacet->used) {
5117         struct facet *facet = subfacet->facet;
5118
5119         subfacet->used = MAX(subfacet->used, stats->used);
5120         facet->used = MAX(facet->used, stats->used);
5121         facet->packet_count += stats->n_packets;
5122         facet->byte_count += stats->n_bytes;
5123         facet->tcp_flags |= stats->tcp_flags;
5124     }
5125 }
5126 \f
5127 /* Rules. */
5128
5129 /* Lookup 'flow' in 'ofproto''s classifier.  If 'wc' is non-null, sets
5130  * the fields that were relevant as part of the lookup. */
5131 static struct rule_dpif *
5132 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
5133                  struct flow_wildcards *wc)
5134 {
5135     struct rule_dpif *rule;
5136
5137     rule = rule_dpif_lookup_in_table(ofproto, flow, wc, 0);
5138     if (rule) {
5139         return rule;
5140     }
5141
5142     return rule_dpif_miss_rule(ofproto, flow);
5143 }
5144
5145 struct rule_dpif *
5146 rule_dpif_lookup_in_table(struct ofproto_dpif *ofproto,
5147                           const struct flow *flow, struct flow_wildcards *wc,
5148                           uint8_t table_id)
5149 {
5150     struct cls_rule *cls_rule;
5151     struct classifier *cls;
5152     bool frag;
5153
5154     if (table_id >= N_TABLES) {
5155         return NULL;
5156     }
5157
5158     if (wc) {
5159         memset(&wc->masks.dl_type, 0xff, sizeof wc->masks.dl_type);
5160         wc->masks.nw_frag |= FLOW_NW_FRAG_MASK;
5161     }
5162
5163     cls = &ofproto->up.tables[table_id].cls;
5164     frag = (flow->nw_frag & FLOW_NW_FRAG_ANY) != 0;
5165     if (frag && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
5166         /* We must pretend that transport ports are unavailable. */
5167         struct flow ofpc_normal_flow = *flow;
5168         ofpc_normal_flow.tp_src = htons(0);
5169         ofpc_normal_flow.tp_dst = htons(0);
5170         cls_rule = classifier_lookup(cls, &ofpc_normal_flow, wc);
5171     } else if (frag && ofproto->up.frag_handling == OFPC_FRAG_DROP) {
5172         cls_rule = &ofproto->drop_frags_rule->up.cr;
5173         if (wc) {
5174             flow_wildcards_init_exact(wc);
5175         }
5176     } else {
5177         cls_rule = classifier_lookup(cls, flow, wc);
5178     }
5179     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
5180 }
5181
5182 struct rule_dpif *
5183 rule_dpif_miss_rule(struct ofproto_dpif *ofproto, const struct flow *flow)
5184 {
5185     struct ofport_dpif *port;
5186
5187     port = get_ofp_port(ofproto, flow->in_port.ofp_port);
5188     if (!port) {
5189         VLOG_WARN_RL(&rl, "packet-in on unknown OpenFlow port %"PRIu16,
5190                      flow->in_port.ofp_port);
5191         return ofproto->miss_rule;
5192     }
5193
5194     if (port->up.pp.config & OFPUTIL_PC_NO_PACKET_IN) {
5195         return ofproto->no_packet_in_rule;
5196     }
5197     return ofproto->miss_rule;
5198 }
5199
5200 static void
5201 complete_operation(struct rule_dpif *rule)
5202 {
5203     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5204
5205     ofproto->backer->need_revalidate = REV_FLOW_TABLE;
5206     if (clogged) {
5207         struct dpif_completion *c = xmalloc(sizeof *c);
5208         c->op = rule->up.pending;
5209         list_push_back(&ofproto->completions, &c->list_node);
5210     } else {
5211         ofoperation_complete(rule->up.pending, 0);
5212     }
5213 }
5214
5215 static struct rule *
5216 rule_alloc(void)
5217 {
5218     struct rule_dpif *rule = xmalloc(sizeof *rule);
5219     return &rule->up;
5220 }
5221
5222 static void
5223 rule_dealloc(struct rule *rule_)
5224 {
5225     struct rule_dpif *rule = rule_dpif_cast(rule_);
5226     free(rule);
5227 }
5228
5229 static enum ofperr
5230 rule_construct(struct rule *rule_)
5231 {
5232     struct rule_dpif *rule = rule_dpif_cast(rule_);
5233     ovs_mutex_init(&rule->stats_mutex, PTHREAD_MUTEX_NORMAL);
5234     ovs_mutex_lock(&rule->stats_mutex);
5235     rule->packet_count = 0;
5236     rule->byte_count = 0;
5237     ovs_mutex_unlock(&rule->stats_mutex);
5238     complete_operation(rule);
5239     return 0;
5240 }
5241
5242 static void
5243 rule_destruct(struct rule *rule_)
5244 {
5245     struct rule_dpif *rule = rule_dpif_cast(rule_);
5246     complete_operation(rule);
5247     ovs_mutex_destroy(&rule->stats_mutex);
5248 }
5249
5250 static void
5251 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
5252 {
5253     struct rule_dpif *rule = rule_dpif_cast(rule_);
5254
5255     /* push_all_stats() can handle flow misses which, when using the learn
5256      * action, can cause rules to be added and deleted.  This can corrupt our
5257      * caller's datastructures which assume that rule_get_stats() doesn't have
5258      * an impact on the flow table. To be safe, we disable miss handling. */
5259     push_all_stats__(false);
5260
5261     /* Start from historical data for 'rule' itself that are no longer tracked
5262      * in facets.  This counts, for example, facets that have expired. */
5263     ovs_mutex_lock(&rule->stats_mutex);
5264     *packets = rule->packet_count;
5265     *bytes = rule->byte_count;
5266     ovs_mutex_unlock(&rule->stats_mutex);
5267 }
5268
5269 static void
5270 rule_dpif_execute(struct rule_dpif *rule, const struct flow *flow,
5271                   struct ofpbuf *packet)
5272 {
5273     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5274     struct dpif_flow_stats stats;
5275     struct xlate_out xout;
5276     struct xlate_in xin;
5277
5278     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
5279     rule_credit_stats(rule, &stats);
5280
5281     xlate_in_init(&xin, ofproto, flow, rule, stats.tcp_flags, packet);
5282     xin.resubmit_stats = &stats;
5283     xlate_actions(&xin, &xout);
5284
5285     execute_odp_actions(ofproto, flow, xout.odp_actions.data,
5286                         xout.odp_actions.size, packet);
5287
5288     xlate_out_uninit(&xout);
5289 }
5290
5291 static enum ofperr
5292 rule_execute(struct rule *rule, const struct flow *flow,
5293              struct ofpbuf *packet)
5294 {
5295     rule_dpif_execute(rule_dpif_cast(rule), flow, packet);
5296     ofpbuf_delete(packet);
5297     return 0;
5298 }
5299
5300 static void
5301 rule_modify_actions(struct rule *rule_)
5302 {
5303     struct rule_dpif *rule = rule_dpif_cast(rule_);
5304
5305     complete_operation(rule);
5306 }
5307 \f
5308 /* Sends 'packet' out 'ofport'.
5309  * May modify 'packet'.
5310  * Returns 0 if successful, otherwise a positive errno value. */
5311 static int
5312 send_packet(const struct ofport_dpif *ofport, struct ofpbuf *packet)
5313 {
5314     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
5315     uint64_t odp_actions_stub[1024 / 8];
5316     struct ofpbuf key, odp_actions;
5317     struct dpif_flow_stats stats;
5318     struct odputil_keybuf keybuf;
5319     struct ofpact_output output;
5320     struct xlate_out xout;
5321     struct xlate_in xin;
5322     struct flow flow;
5323     union flow_in_port in_port_;
5324     int error;
5325
5326     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
5327     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5328
5329     /* Use OFPP_NONE as the in_port to avoid special packet processing. */
5330     in_port_.ofp_port = OFPP_NONE;
5331     flow_extract(packet, 0, 0, NULL, &in_port_, &flow);
5332     odp_flow_key_from_flow(&key, &flow, ofp_port_to_odp_port(ofproto,
5333                                                              OFPP_LOCAL));
5334     dpif_flow_stats_extract(&flow, packet, time_msec(), &stats);
5335
5336     ofpact_init(&output.ofpact, OFPACT_OUTPUT, sizeof output);
5337     output.port = ofport->up.ofp_port;
5338     output.max_len = 0;
5339
5340     xlate_in_init(&xin, ofproto, &flow, NULL, 0, packet);
5341     xin.ofpacts_len = sizeof output;
5342     xin.ofpacts = &output.ofpact;
5343     xin.resubmit_stats = &stats;
5344     xlate_actions(&xin, &xout);
5345
5346     error = dpif_execute(ofproto->backer->dpif,
5347                          key.data, key.size,
5348                          xout.odp_actions.data, xout.odp_actions.size,
5349                          packet);
5350     xlate_out_uninit(&xout);
5351
5352     if (error) {
5353         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %s (%s)",
5354                      ofproto->up.name, netdev_get_name(ofport->up.netdev),
5355                      ovs_strerror(error));
5356     }
5357
5358     ofproto->stats.tx_packets++;
5359     ofproto->stats.tx_bytes += packet->size;
5360     return error;
5361 }
5362
5363 /* Composes an ODP action for a "slow path" action for 'flow' within 'ofproto'.
5364  * The action will state 'slow' as the reason that the action is in the slow
5365  * path.  (This is purely informational: it allows a human viewing "ovs-dpctl
5366  * dump-flows" output to see why a flow is in the slow path.)
5367  *
5368  * The 'stub_size' bytes in 'stub' will be used to store the action.
5369  * 'stub_size' must be large enough for the action.
5370  *
5371  * The action and its size will be stored in '*actionsp' and '*actions_lenp',
5372  * respectively. */
5373 static void
5374 compose_slow_path(const struct ofproto_dpif *ofproto, const struct flow *flow,
5375                   enum slow_path_reason slow,
5376                   uint64_t *stub, size_t stub_size,
5377                   const struct nlattr **actionsp, size_t *actions_lenp)
5378 {
5379     union user_action_cookie cookie;
5380     struct ofpbuf buf;
5381
5382     cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
5383     cookie.slow_path.unused = 0;
5384     cookie.slow_path.reason = slow;
5385
5386     ofpbuf_use_stack(&buf, stub, stub_size);
5387     if (slow & (SLOW_CFM | SLOW_BFD | SLOW_LACP | SLOW_STP)) {
5388         uint32_t pid = dpif_port_get_pid(ofproto->backer->dpif,
5389                                          ODPP_NONE);
5390         odp_put_userspace_action(pid, &cookie, sizeof cookie.slow_path, &buf);
5391     } else {
5392         odp_port_t odp_port;
5393         uint32_t pid;
5394
5395         odp_port = ofp_port_to_odp_port(ofproto, flow->in_port.ofp_port);
5396         pid = dpif_port_get_pid(ofproto->backer->dpif, odp_port);
5397         odp_put_userspace_action(pid, &cookie, sizeof cookie.slow_path, &buf);
5398     }
5399     *actionsp = buf.data;
5400     *actions_lenp = buf.size;
5401 }
5402 \f
5403 static bool
5404 set_frag_handling(struct ofproto *ofproto_,
5405                   enum ofp_config_flags frag_handling)
5406 {
5407     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5408     if (frag_handling != OFPC_FRAG_REASM) {
5409         ofproto->backer->need_revalidate = REV_RECONFIGURE;
5410         return true;
5411     } else {
5412         return false;
5413     }
5414 }
5415
5416 static enum ofperr
5417 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
5418            const struct flow *flow,
5419            const struct ofpact *ofpacts, size_t ofpacts_len)
5420 {
5421     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5422     struct odputil_keybuf keybuf;
5423     struct dpif_flow_stats stats;
5424     struct xlate_out xout;
5425     struct xlate_in xin;
5426     struct ofpbuf key;
5427
5428
5429     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5430     odp_flow_key_from_flow(&key, flow,
5431                            ofp_port_to_odp_port(ofproto,
5432                                       flow->in_port.ofp_port));
5433
5434     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
5435
5436     xlate_in_init(&xin, ofproto, flow, NULL, stats.tcp_flags, packet);
5437     xin.resubmit_stats = &stats;
5438     xin.ofpacts_len = ofpacts_len;
5439     xin.ofpacts = ofpacts;
5440
5441     xlate_actions(&xin, &xout);
5442     dpif_execute(ofproto->backer->dpif, key.data, key.size,
5443                  xout.odp_actions.data, xout.odp_actions.size, packet);
5444     xlate_out_uninit(&xout);
5445
5446     return 0;
5447 }
5448 \f
5449 /* NetFlow. */
5450
5451 static int
5452 set_netflow(struct ofproto *ofproto_,
5453             const struct netflow_options *netflow_options)
5454 {
5455     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5456
5457     if (netflow_options) {
5458         if (!ofproto->netflow) {
5459             ofproto->netflow = netflow_create();
5460             ofproto->backer->need_revalidate = REV_RECONFIGURE;
5461         }
5462         return netflow_set_options(ofproto->netflow, netflow_options);
5463     } else if (ofproto->netflow) {
5464         ofproto->backer->need_revalidate = REV_RECONFIGURE;
5465         netflow_destroy(ofproto->netflow);
5466         ofproto->netflow = NULL;
5467     }
5468
5469     return 0;
5470 }
5471
5472 static void
5473 get_netflow_ids(const struct ofproto *ofproto_,
5474                 uint8_t *engine_type, uint8_t *engine_id)
5475 {
5476     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5477
5478     dpif_get_netflow_ids(ofproto->backer->dpif, engine_type, engine_id);
5479 }
5480
5481 static void
5482 send_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
5483 {
5484     if (!facet_is_controller_flow(facet) &&
5485         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
5486         struct subfacet *subfacet;
5487         struct ofexpired expired;
5488
5489         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
5490             if (subfacet->path == SF_FAST_PATH) {
5491                 struct dpif_flow_stats stats;
5492
5493                 subfacet_install(subfacet, &facet->xout.odp_actions,
5494                                  &stats);
5495                 subfacet_update_stats(subfacet, &stats);
5496             }
5497         }
5498
5499         expired.flow = facet->flow;
5500         expired.packet_count = facet->packet_count;
5501         expired.byte_count = facet->byte_count;
5502         expired.used = facet->used;
5503         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
5504     }
5505 }
5506
5507 static void
5508 send_netflow_active_timeouts(struct ofproto_dpif *ofproto)
5509 {
5510     struct cls_cursor cursor;
5511     struct facet *facet;
5512
5513     cls_cursor_init(&cursor, &ofproto->facets, NULL);
5514     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
5515         send_active_timeout(ofproto, facet);
5516     }
5517 }
5518 \f
5519 static struct ofproto_dpif *
5520 ofproto_dpif_lookup(const char *name)
5521 {
5522     struct ofproto_dpif *ofproto;
5523
5524     HMAP_FOR_EACH_WITH_HASH (ofproto, all_ofproto_dpifs_node,
5525                              hash_string(name, 0), &all_ofproto_dpifs) {
5526         if (!strcmp(ofproto->up.name, name)) {
5527             return ofproto;
5528         }
5529     }
5530     return NULL;
5531 }
5532
5533 static void
5534 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn, int argc,
5535                           const char *argv[], void *aux OVS_UNUSED)
5536 {
5537     struct ofproto_dpif *ofproto;
5538
5539     if (argc > 1) {
5540         ofproto = ofproto_dpif_lookup(argv[1]);
5541         if (!ofproto) {
5542             unixctl_command_reply_error(conn, "no such bridge");
5543             return;
5544         }
5545         ovs_rwlock_wrlock(&ofproto->ml->rwlock);
5546         mac_learning_flush(ofproto->ml);
5547         ovs_rwlock_unlock(&ofproto->ml->rwlock);
5548     } else {
5549         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
5550             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
5551             mac_learning_flush(ofproto->ml);
5552             ovs_rwlock_unlock(&ofproto->ml->rwlock);
5553         }
5554     }
5555
5556     unixctl_command_reply(conn, "table successfully flushed");
5557 }
5558
5559 static struct ofport_dpif *
5560 ofbundle_get_a_port(const struct ofbundle *bundle)
5561 {
5562     return CONTAINER_OF(list_front(&bundle->ports), struct ofport_dpif,
5563                         bundle_node);
5564 }
5565
5566 static void
5567 ofproto_unixctl_fdb_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
5568                          const char *argv[], void *aux OVS_UNUSED)
5569 {
5570     struct ds ds = DS_EMPTY_INITIALIZER;
5571     const struct ofproto_dpif *ofproto;
5572     const struct mac_entry *e;
5573
5574     ofproto = ofproto_dpif_lookup(argv[1]);
5575     if (!ofproto) {
5576         unixctl_command_reply_error(conn, "no such bridge");
5577         return;
5578     }
5579
5580     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
5581     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
5582     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
5583         struct ofbundle *bundle = e->port.p;
5584         char name[OFP_MAX_PORT_NAME_LEN];
5585
5586         ofputil_port_to_string(ofbundle_get_a_port(bundle)->up.ofp_port,
5587                                name, sizeof name);
5588         ds_put_format(&ds, "%5s  %4d  "ETH_ADDR_FMT"  %3d\n",
5589                       name, e->vlan, ETH_ADDR_ARGS(e->mac),
5590                       mac_entry_age(ofproto->ml, e));
5591     }
5592     ovs_rwlock_unlock(&ofproto->ml->rwlock);
5593     unixctl_command_reply(conn, ds_cstr(&ds));
5594     ds_destroy(&ds);
5595 }
5596
5597 struct trace_ctx {
5598     struct xlate_out xout;
5599     struct xlate_in xin;
5600     struct flow flow;
5601     struct ds *result;
5602 };
5603
5604 static void
5605 trace_format_rule(struct ds *result, int level, const struct rule_dpif *rule)
5606 {
5607     ds_put_char_multiple(result, '\t', level);
5608     if (!rule) {
5609         ds_put_cstr(result, "No match\n");
5610         return;
5611     }
5612
5613     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
5614                   rule ? rule->up.table_id : 0, ntohll(rule->up.flow_cookie));
5615     cls_rule_format(&rule->up.cr, result);
5616     ds_put_char(result, '\n');
5617
5618     ds_put_char_multiple(result, '\t', level);
5619     ds_put_cstr(result, "OpenFlow ");
5620     ofpacts_format(rule->up.ofpacts, rule->up.ofpacts_len, result);
5621     ds_put_char(result, '\n');
5622 }
5623
5624 static void
5625 trace_format_flow(struct ds *result, int level, const char *title,
5626                   struct trace_ctx *trace)
5627 {
5628     ds_put_char_multiple(result, '\t', level);
5629     ds_put_format(result, "%s: ", title);
5630     if (flow_equal(&trace->xin.flow, &trace->flow)) {
5631         ds_put_cstr(result, "unchanged");
5632     } else {
5633         flow_format(result, &trace->xin.flow);
5634         trace->flow = trace->xin.flow;
5635     }
5636     ds_put_char(result, '\n');
5637 }
5638
5639 static void
5640 trace_format_regs(struct ds *result, int level, const char *title,
5641                   struct trace_ctx *trace)
5642 {
5643     size_t i;
5644
5645     ds_put_char_multiple(result, '\t', level);
5646     ds_put_format(result, "%s:", title);
5647     for (i = 0; i < FLOW_N_REGS; i++) {
5648         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
5649     }
5650     ds_put_char(result, '\n');
5651 }
5652
5653 static void
5654 trace_format_odp(struct ds *result, int level, const char *title,
5655                  struct trace_ctx *trace)
5656 {
5657     struct ofpbuf *odp_actions = &trace->xout.odp_actions;
5658
5659     ds_put_char_multiple(result, '\t', level);
5660     ds_put_format(result, "%s: ", title);
5661     format_odp_actions(result, odp_actions->data, odp_actions->size);
5662     ds_put_char(result, '\n');
5663 }
5664
5665 static void
5666 trace_resubmit(struct xlate_in *xin, struct rule_dpif *rule, int recurse)
5667 {
5668     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
5669     struct ds *result = trace->result;
5670
5671     ds_put_char(result, '\n');
5672     trace_format_flow(result, recurse + 1, "Resubmitted flow", trace);
5673     trace_format_regs(result, recurse + 1, "Resubmitted regs", trace);
5674     trace_format_odp(result,  recurse + 1, "Resubmitted  odp", trace);
5675     trace_format_rule(result, recurse + 1, rule);
5676 }
5677
5678 static void
5679 trace_report(struct xlate_in *xin, const char *s, int recurse)
5680 {
5681     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
5682     struct ds *result = trace->result;
5683
5684     ds_put_char_multiple(result, '\t', recurse);
5685     ds_put_cstr(result, s);
5686     ds_put_char(result, '\n');
5687 }
5688
5689 static void
5690 ofproto_unixctl_trace(struct unixctl_conn *conn, int argc, const char *argv[],
5691                       void *aux OVS_UNUSED)
5692 {
5693     const struct dpif_backer *backer;
5694     struct ofproto_dpif *ofproto;
5695     struct ofpbuf odp_key, odp_mask;
5696     struct ofpbuf *packet;
5697     struct ds result;
5698     struct flow flow;
5699     char *s;
5700
5701     packet = NULL;
5702     backer = NULL;
5703     ds_init(&result);
5704     ofpbuf_init(&odp_key, 0);
5705     ofpbuf_init(&odp_mask, 0);
5706
5707     /* Handle "-generate" or a hex string as the last argument. */
5708     if (!strcmp(argv[argc - 1], "-generate")) {
5709         packet = ofpbuf_new(0);
5710         argc--;
5711     } else {
5712         const char *error = eth_from_hex(argv[argc - 1], &packet);
5713         if (!error) {
5714             argc--;
5715         } else if (argc == 4) {
5716             /* The 3-argument form must end in "-generate' or a hex string. */
5717             unixctl_command_reply_error(conn, error);
5718             goto exit;
5719         }
5720     }
5721
5722     /* Parse the flow and determine whether a datapath or
5723      * bridge is specified. If function odp_flow_key_from_string()
5724      * returns 0, the flow is a odp_flow. If function
5725      * parse_ofp_exact_flow() returns 0, the flow is a br_flow. */
5726     if (!odp_flow_from_string(argv[argc - 1], NULL, &odp_key, &odp_mask)) {
5727         /* If the odp_flow is the second argument,
5728          * the datapath name is the first argument. */
5729         if (argc == 3) {
5730             const char *dp_type;
5731             if (!strncmp(argv[1], "ovs-", 4)) {
5732                 dp_type = argv[1] + 4;
5733             } else {
5734                 dp_type = argv[1];
5735             }
5736             backer = shash_find_data(&all_dpif_backers, dp_type);
5737             if (!backer) {
5738                 unixctl_command_reply_error(conn, "Cannot find datapath "
5739                                "of this name");
5740                 goto exit;
5741             }
5742         } else {
5743             /* No datapath name specified, so there should be only one
5744              * datapath. */
5745             struct shash_node *node;
5746             if (shash_count(&all_dpif_backers) != 1) {
5747                 unixctl_command_reply_error(conn, "Must specify datapath "
5748                          "name, there is more than one type of datapath");
5749                 goto exit;
5750             }
5751             node = shash_first(&all_dpif_backers);
5752             backer = node->data;
5753         }
5754
5755         /* Extract the ofproto_dpif object from the ofproto_receive()
5756          * function. */
5757         if (ofproto_receive(backer, NULL, odp_key.data,
5758                             odp_key.size, &flow, NULL, &ofproto, NULL)) {
5759             unixctl_command_reply_error(conn, "Invalid datapath flow");
5760             goto exit;
5761         }
5762         ds_put_format(&result, "Bridge: %s\n", ofproto->up.name);
5763     } else if (!parse_ofp_exact_flow(&flow, argv[argc - 1])) {
5764         if (argc != 3) {
5765             unixctl_command_reply_error(conn, "Must specify bridge name");
5766             goto exit;
5767         }
5768
5769         ofproto = ofproto_dpif_lookup(argv[1]);
5770         if (!ofproto) {
5771             unixctl_command_reply_error(conn, "Unknown bridge name");
5772             goto exit;
5773         }
5774     } else {
5775         unixctl_command_reply_error(conn, "Bad flow syntax");
5776         goto exit;
5777     }
5778
5779     /* Generate a packet, if requested. */
5780     if (packet) {
5781         if (!packet->size) {
5782             flow_compose(packet, &flow);
5783         } else {
5784             union flow_in_port in_port_;
5785
5786             in_port_ = flow.in_port;
5787             ds_put_cstr(&result, "Packet: ");
5788             s = ofp_packet_to_string(packet->data, packet->size);
5789             ds_put_cstr(&result, s);
5790             free(s);
5791
5792             /* Use the metadata from the flow and the packet argument
5793              * to reconstruct the flow. */
5794             flow_extract(packet, flow.skb_priority, flow.skb_mark, NULL,
5795                          &in_port_, &flow);
5796         }
5797     }
5798
5799     ofproto_trace(ofproto, &flow, packet, &result);
5800     unixctl_command_reply(conn, ds_cstr(&result));
5801
5802 exit:
5803     ds_destroy(&result);
5804     ofpbuf_delete(packet);
5805     ofpbuf_uninit(&odp_key);
5806     ofpbuf_uninit(&odp_mask);
5807 }
5808
5809 static void
5810 ofproto_trace(struct ofproto_dpif *ofproto, const struct flow *flow,
5811               const struct ofpbuf *packet, struct ds *ds)
5812 {
5813     struct rule_dpif *rule;
5814
5815     ds_put_cstr(ds, "Flow: ");
5816     flow_format(ds, flow);
5817     ds_put_char(ds, '\n');
5818
5819     rule = rule_dpif_lookup(ofproto, flow, NULL);
5820
5821     trace_format_rule(ds, 0, rule);
5822     if (rule == ofproto->miss_rule) {
5823         ds_put_cstr(ds, "\nNo match, flow generates \"packet in\"s.\n");
5824     } else if (rule == ofproto->no_packet_in_rule) {
5825         ds_put_cstr(ds, "\nNo match, packets dropped because "
5826                     "OFPPC_NO_PACKET_IN is set on in_port.\n");
5827     } else if (rule == ofproto->drop_frags_rule) {
5828         ds_put_cstr(ds, "\nPackets dropped because they are IP fragments "
5829                     "and the fragment handling mode is \"drop\".\n");
5830     }
5831
5832     if (rule) {
5833         uint64_t odp_actions_stub[1024 / 8];
5834         struct ofpbuf odp_actions;
5835         struct trace_ctx trace;
5836         struct match match;
5837         uint8_t tcp_flags;
5838
5839         tcp_flags = packet ? packet_get_tcp_flags(packet, flow) : 0;
5840         trace.result = ds;
5841         trace.flow = *flow;
5842         ofpbuf_use_stub(&odp_actions,
5843                         odp_actions_stub, sizeof odp_actions_stub);
5844         xlate_in_init(&trace.xin, ofproto, flow, rule, tcp_flags, packet);
5845         trace.xin.resubmit_hook = trace_resubmit;
5846         trace.xin.report_hook = trace_report;
5847
5848         xlate_actions(&trace.xin, &trace.xout);
5849
5850         ds_put_char(ds, '\n');
5851         trace_format_flow(ds, 0, "Final flow", &trace);
5852
5853         match_init(&match, flow, &trace.xout.wc);
5854         ds_put_cstr(ds, "Relevant fields: ");
5855         match_format(&match, ds, OFP_DEFAULT_PRIORITY);
5856         ds_put_char(ds, '\n');
5857
5858         ds_put_cstr(ds, "Datapath actions: ");
5859         format_odp_actions(ds, trace.xout.odp_actions.data,
5860                            trace.xout.odp_actions.size);
5861
5862         if (trace.xout.slow) {
5863             ds_put_cstr(ds, "\nThis flow is handled by the userspace "
5864                         "slow path because it:");
5865             switch (trace.xout.slow) {
5866             case SLOW_CFM:
5867                 ds_put_cstr(ds, "\n\t- Consists of CFM packets.");
5868                 break;
5869             case SLOW_LACP:
5870                 ds_put_cstr(ds, "\n\t- Consists of LACP packets.");
5871                 break;
5872             case SLOW_STP:
5873                 ds_put_cstr(ds, "\n\t- Consists of STP packets.");
5874                 break;
5875             case SLOW_BFD:
5876                 ds_put_cstr(ds, "\n\t- Consists of BFD packets.");
5877                 break;
5878             case SLOW_CONTROLLER:
5879                 ds_put_cstr(ds, "\n\t- Sends \"packet-in\" messages "
5880                             "to the OpenFlow controller.");
5881                 break;
5882             case __SLOW_MAX:
5883                 NOT_REACHED();
5884             }
5885         }
5886
5887         xlate_out_uninit(&trace.xout);
5888     }
5889 }
5890
5891 static void
5892 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
5893                   const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
5894 {
5895     clogged = true;
5896     unixctl_command_reply(conn, NULL);
5897 }
5898
5899 static void
5900 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
5901                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
5902 {
5903     clogged = false;
5904     unixctl_command_reply(conn, NULL);
5905 }
5906
5907 /* Runs a self-check of flow translations in 'ofproto'.  Appends a message to
5908  * 'reply' describing the results. */
5909 static void
5910 ofproto_dpif_self_check__(struct ofproto_dpif *ofproto, struct ds *reply)
5911 {
5912     struct cls_cursor cursor;
5913     struct facet *facet;
5914     int errors;
5915
5916     errors = 0;
5917     cls_cursor_init(&cursor, &ofproto->facets, NULL);
5918     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
5919         if (!facet_check_consistency(facet)) {
5920             errors++;
5921         }
5922     }
5923     if (errors) {
5924         ofproto->backer->need_revalidate = REV_INCONSISTENCY;
5925     }
5926
5927     if (errors) {
5928         ds_put_format(reply, "%s: self-check failed (%d errors)\n",
5929                       ofproto->up.name, errors);
5930     } else {
5931         ds_put_format(reply, "%s: self-check passed\n", ofproto->up.name);
5932     }
5933 }
5934
5935 static void
5936 ofproto_dpif_self_check(struct unixctl_conn *conn,
5937                         int argc, const char *argv[], void *aux OVS_UNUSED)
5938 {
5939     struct ds reply = DS_EMPTY_INITIALIZER;
5940     struct ofproto_dpif *ofproto;
5941
5942     if (argc > 1) {
5943         ofproto = ofproto_dpif_lookup(argv[1]);
5944         if (!ofproto) {
5945             unixctl_command_reply_error(conn, "Unknown ofproto (use "
5946                                         "ofproto/list for help)");
5947             return;
5948         }
5949         ofproto_dpif_self_check__(ofproto, &reply);
5950     } else {
5951         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
5952             ofproto_dpif_self_check__(ofproto, &reply);
5953         }
5954     }
5955
5956     unixctl_command_reply(conn, ds_cstr(&reply));
5957     ds_destroy(&reply);
5958 }
5959
5960 /* Store the current ofprotos in 'ofproto_shash'.  Returns a sorted list
5961  * of the 'ofproto_shash' nodes.  It is the responsibility of the caller
5962  * to destroy 'ofproto_shash' and free the returned value. */
5963 static const struct shash_node **
5964 get_ofprotos(struct shash *ofproto_shash)
5965 {
5966     const struct ofproto_dpif *ofproto;
5967
5968     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
5969         char *name = xasprintf("%s@%s", ofproto->up.type, ofproto->up.name);
5970         shash_add_nocopy(ofproto_shash, name, ofproto);
5971     }
5972
5973     return shash_sort(ofproto_shash);
5974 }
5975
5976 static void
5977 ofproto_unixctl_dpif_dump_dps(struct unixctl_conn *conn, int argc OVS_UNUSED,
5978                               const char *argv[] OVS_UNUSED,
5979                               void *aux OVS_UNUSED)
5980 {
5981     struct ds ds = DS_EMPTY_INITIALIZER;
5982     struct shash ofproto_shash;
5983     const struct shash_node **sorted_ofprotos;
5984     int i;
5985
5986     shash_init(&ofproto_shash);
5987     sorted_ofprotos = get_ofprotos(&ofproto_shash);
5988     for (i = 0; i < shash_count(&ofproto_shash); i++) {
5989         const struct shash_node *node = sorted_ofprotos[i];
5990         ds_put_format(&ds, "%s\n", node->name);
5991     }
5992
5993     shash_destroy(&ofproto_shash);
5994     free(sorted_ofprotos);
5995
5996     unixctl_command_reply(conn, ds_cstr(&ds));
5997     ds_destroy(&ds);
5998 }
5999
6000 static void
6001 show_dp_rates(struct ds *ds, const char *heading,
6002               const struct avg_subfacet_rates *rates)
6003 {
6004     ds_put_format(ds, "%s add rate: %5.3f/min, del rate: %5.3f/min\n",
6005                   heading, rates->add_rate, rates->del_rate);
6006 }
6007
6008 static void
6009 dpif_show_backer(const struct dpif_backer *backer, struct ds *ds)
6010 {
6011     const struct shash_node **ofprotos;
6012     struct ofproto_dpif *ofproto;
6013     struct shash ofproto_shash;
6014     uint64_t n_hit, n_missed;
6015     long long int minutes;
6016     size_t i;
6017
6018     n_hit = n_missed = 0;
6019     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6020         if (ofproto->backer == backer) {
6021             n_missed += ofproto->n_missed;
6022             n_hit += ofproto->n_hit;
6023         }
6024     }
6025
6026     ds_put_format(ds, "%s: hit:%"PRIu64" missed:%"PRIu64"\n",
6027                   dpif_name(backer->dpif), n_hit, n_missed);
6028     ds_put_format(ds, "\tflows: cur: %zu, avg: %u, max: %u,"
6029                   " life span: %lldms\n", hmap_count(&backer->subfacets),
6030                   backer->avg_n_subfacet, backer->max_n_subfacet,
6031                   backer->avg_subfacet_life);
6032
6033     minutes = (time_msec() - backer->created) / (1000 * 60);
6034     if (minutes >= 60) {
6035         show_dp_rates(ds, "\thourly avg:", &backer->hourly);
6036     }
6037     if (minutes >= 60 * 24) {
6038         show_dp_rates(ds, "\tdaily avg:",  &backer->daily);
6039     }
6040     show_dp_rates(ds, "\toverall avg:",  &backer->lifetime);
6041
6042     shash_init(&ofproto_shash);
6043     ofprotos = get_ofprotos(&ofproto_shash);
6044     for (i = 0; i < shash_count(&ofproto_shash); i++) {
6045         struct ofproto_dpif *ofproto = ofprotos[i]->data;
6046         const struct shash_node **ports;
6047         size_t j;
6048
6049         if (ofproto->backer != backer) {
6050             continue;
6051         }
6052
6053         ds_put_format(ds, "\t%s: hit:%"PRIu64" missed:%"PRIu64"\n",
6054                       ofproto->up.name, ofproto->n_hit, ofproto->n_missed);
6055
6056         ports = shash_sort(&ofproto->up.port_by_name);
6057         for (j = 0; j < shash_count(&ofproto->up.port_by_name); j++) {
6058             const struct shash_node *node = ports[j];
6059             struct ofport *ofport = node->data;
6060             struct smap config;
6061             odp_port_t odp_port;
6062
6063             ds_put_format(ds, "\t\t%s %u/", netdev_get_name(ofport->netdev),
6064                           ofport->ofp_port);
6065
6066             odp_port = ofp_port_to_odp_port(ofproto, ofport->ofp_port);
6067             if (odp_port != ODPP_NONE) {
6068                 ds_put_format(ds, "%"PRIu32":", odp_port);
6069             } else {
6070                 ds_put_cstr(ds, "none:");
6071             }
6072
6073             ds_put_format(ds, " (%s", netdev_get_type(ofport->netdev));
6074
6075             smap_init(&config);
6076             if (!netdev_get_config(ofport->netdev, &config)) {
6077                 const struct smap_node **nodes;
6078                 size_t i;
6079
6080                 nodes = smap_sort(&config);
6081                 for (i = 0; i < smap_count(&config); i++) {
6082                     const struct smap_node *node = nodes[i];
6083                     ds_put_format(ds, "%c %s=%s", i ? ',' : ':',
6084                                   node->key, node->value);
6085                 }
6086                 free(nodes);
6087             }
6088             smap_destroy(&config);
6089
6090             ds_put_char(ds, ')');
6091             ds_put_char(ds, '\n');
6092         }
6093         free(ports);
6094     }
6095     shash_destroy(&ofproto_shash);
6096     free(ofprotos);
6097 }
6098
6099 static void
6100 ofproto_unixctl_dpif_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
6101                           const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6102 {
6103     struct ds ds = DS_EMPTY_INITIALIZER;
6104     const struct shash_node **backers;
6105     int i;
6106
6107     backers = shash_sort(&all_dpif_backers);
6108     for (i = 0; i < shash_count(&all_dpif_backers); i++) {
6109         dpif_show_backer(backers[i]->data, &ds);
6110     }
6111     free(backers);
6112
6113     unixctl_command_reply(conn, ds_cstr(&ds));
6114     ds_destroy(&ds);
6115 }
6116
6117 /* Dump the megaflow (facet) cache.  This is useful to check the
6118  * correctness of flow wildcarding, since the same mechanism is used for
6119  * both xlate caching and kernel wildcarding.
6120  *
6121  * It's important to note that in the output the flow description uses
6122  * OpenFlow (OFP) ports, but the actions use datapath (ODP) ports.
6123  *
6124  * This command is only needed for advanced debugging, so it's not
6125  * documented in the man page. */
6126 static void
6127 ofproto_unixctl_dpif_dump_megaflows(struct unixctl_conn *conn,
6128                                     int argc OVS_UNUSED, const char *argv[],
6129                                     void *aux OVS_UNUSED)
6130 {
6131     struct ds ds = DS_EMPTY_INITIALIZER;
6132     const struct ofproto_dpif *ofproto;
6133     long long int now = time_msec();
6134     struct cls_cursor cursor;
6135     struct facet *facet;
6136
6137     ofproto = ofproto_dpif_lookup(argv[1]);
6138     if (!ofproto) {
6139         unixctl_command_reply_error(conn, "no such bridge");
6140         return;
6141     }
6142
6143     cls_cursor_init(&cursor, &ofproto->facets, NULL);
6144     CLS_CURSOR_FOR_EACH (facet, cr, &cursor) {
6145         cls_rule_format(&facet->cr, &ds);
6146         ds_put_cstr(&ds, ", ");
6147         ds_put_format(&ds, "n_subfacets:%zu, ", list_size(&facet->subfacets));
6148         ds_put_format(&ds, "used:%.3fs, ", (now - facet->used) / 1000.0);
6149         ds_put_cstr(&ds, "Datapath actions: ");
6150         if (facet->xout.slow) {
6151             uint64_t slow_path_stub[128 / 8];
6152             const struct nlattr *actions;
6153             size_t actions_len;
6154
6155             compose_slow_path(ofproto, &facet->flow, facet->xout.slow,
6156                               slow_path_stub, sizeof slow_path_stub,
6157                               &actions, &actions_len);
6158             format_odp_actions(&ds, actions, actions_len);
6159         } else {
6160             format_odp_actions(&ds, facet->xout.odp_actions.data,
6161                                facet->xout.odp_actions.size);
6162         }
6163         ds_put_cstr(&ds, "\n");
6164     }
6165
6166     ds_chomp(&ds, '\n');
6167     unixctl_command_reply(conn, ds_cstr(&ds));
6168     ds_destroy(&ds);
6169 }
6170
6171 /* Disable using the megaflows.
6172  *
6173  * This command is only needed for advanced debugging, so it's not
6174  * documented in the man page. */
6175 static void
6176 ofproto_unixctl_dpif_disable_megaflows(struct unixctl_conn *conn,
6177                                        int argc OVS_UNUSED,
6178                                        const char *argv[] OVS_UNUSED,
6179                                        void *aux OVS_UNUSED)
6180 {
6181     struct ofproto_dpif *ofproto;
6182
6183     enable_megaflows = false;
6184
6185     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6186         flush(&ofproto->up);
6187     }
6188
6189     unixctl_command_reply(conn, "megaflows disabled");
6190 }
6191
6192 /* Re-enable using megaflows.
6193  *
6194  * This command is only needed for advanced debugging, so it's not
6195  * documented in the man page. */
6196 static void
6197 ofproto_unixctl_dpif_enable_megaflows(struct unixctl_conn *conn,
6198                                       int argc OVS_UNUSED,
6199                                       const char *argv[] OVS_UNUSED,
6200                                       void *aux OVS_UNUSED)
6201 {
6202     struct ofproto_dpif *ofproto;
6203
6204     enable_megaflows = true;
6205
6206     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
6207         flush(&ofproto->up);
6208     }
6209
6210     unixctl_command_reply(conn, "megaflows enabled");
6211 }
6212
6213 static void
6214 ofproto_unixctl_dpif_dump_flows(struct unixctl_conn *conn,
6215                                 int argc OVS_UNUSED, const char *argv[],
6216                                 void *aux OVS_UNUSED)
6217 {
6218     struct ds ds = DS_EMPTY_INITIALIZER;
6219     const struct ofproto_dpif *ofproto;
6220     struct subfacet *subfacet;
6221
6222     ofproto = ofproto_dpif_lookup(argv[1]);
6223     if (!ofproto) {
6224         unixctl_command_reply_error(conn, "no such bridge");
6225         return;
6226     }
6227
6228     update_stats(ofproto->backer);
6229
6230     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->backer->subfacets) {
6231         struct facet *facet = subfacet->facet;
6232         struct odputil_keybuf maskbuf;
6233         struct ofpbuf mask;
6234
6235         if (facet->ofproto != ofproto) {
6236             continue;
6237         }
6238
6239         ofpbuf_use_stack(&mask, &maskbuf, sizeof maskbuf);
6240         if (enable_megaflows) {
6241             odp_flow_key_from_mask(&mask, &facet->xout.wc.masks,
6242                                    &facet->flow, UINT32_MAX);
6243         }
6244
6245         odp_flow_format(subfacet->key, subfacet->key_len,
6246                         mask.data, mask.size, &ds, false);
6247
6248         ds_put_format(&ds, ", packets:%"PRIu64", bytes:%"PRIu64", used:",
6249                       subfacet->dp_packet_count, subfacet->dp_byte_count);
6250         if (subfacet->used) {
6251             ds_put_format(&ds, "%.3fs",
6252                           (time_msec() - subfacet->used) / 1000.0);
6253         } else {
6254             ds_put_format(&ds, "never");
6255         }
6256         if (subfacet->facet->tcp_flags) {
6257             ds_put_cstr(&ds, ", flags:");
6258             packet_format_tcp_flags(&ds, subfacet->facet->tcp_flags);
6259         }
6260
6261         ds_put_cstr(&ds, ", actions:");
6262         if (facet->xout.slow) {
6263             uint64_t slow_path_stub[128 / 8];
6264             const struct nlattr *actions;
6265             size_t actions_len;
6266
6267             compose_slow_path(ofproto, &facet->flow, facet->xout.slow,
6268                               slow_path_stub, sizeof slow_path_stub,
6269                               &actions, &actions_len);
6270             format_odp_actions(&ds, actions, actions_len);
6271         } else {
6272             format_odp_actions(&ds, facet->xout.odp_actions.data,
6273                                facet->xout.odp_actions.size);
6274         }
6275         ds_put_char(&ds, '\n');
6276     }
6277
6278     unixctl_command_reply(conn, ds_cstr(&ds));
6279     ds_destroy(&ds);
6280 }
6281
6282 static void
6283 ofproto_unixctl_dpif_del_flows(struct unixctl_conn *conn,
6284                                int argc OVS_UNUSED, const char *argv[],
6285                                void *aux OVS_UNUSED)
6286 {
6287     struct ds ds = DS_EMPTY_INITIALIZER;
6288     struct ofproto_dpif *ofproto;
6289
6290     ofproto = ofproto_dpif_lookup(argv[1]);
6291     if (!ofproto) {
6292         unixctl_command_reply_error(conn, "no such bridge");
6293         return;
6294     }
6295
6296     flush(&ofproto->up);
6297
6298     unixctl_command_reply(conn, ds_cstr(&ds));
6299     ds_destroy(&ds);
6300 }
6301
6302 static void
6303 ofproto_dpif_unixctl_init(void)
6304 {
6305     static bool registered;
6306     if (registered) {
6307         return;
6308     }
6309     registered = true;
6310
6311     unixctl_command_register(
6312         "ofproto/trace",
6313         "[dp_name]|bridge odp_flow|br_flow [-generate|packet]",
6314         1, 3, ofproto_unixctl_trace, NULL);
6315     unixctl_command_register("fdb/flush", "[bridge]", 0, 1,
6316                              ofproto_unixctl_fdb_flush, NULL);
6317     unixctl_command_register("fdb/show", "bridge", 1, 1,
6318                              ofproto_unixctl_fdb_show, NULL);
6319     unixctl_command_register("ofproto/clog", "", 0, 0,
6320                              ofproto_dpif_clog, NULL);
6321     unixctl_command_register("ofproto/unclog", "", 0, 0,
6322                              ofproto_dpif_unclog, NULL);
6323     unixctl_command_register("ofproto/self-check", "[bridge]", 0, 1,
6324                              ofproto_dpif_self_check, NULL);
6325     unixctl_command_register("dpif/dump-dps", "", 0, 0,
6326                              ofproto_unixctl_dpif_dump_dps, NULL);
6327     unixctl_command_register("dpif/show", "", 0, 0, ofproto_unixctl_dpif_show,
6328                              NULL);
6329     unixctl_command_register("dpif/dump-flows", "bridge", 1, 1,
6330                              ofproto_unixctl_dpif_dump_flows, NULL);
6331     unixctl_command_register("dpif/del-flows", "bridge", 1, 1,
6332                              ofproto_unixctl_dpif_del_flows, NULL);
6333     unixctl_command_register("dpif/dump-megaflows", "bridge", 1, 1,
6334                              ofproto_unixctl_dpif_dump_megaflows, NULL);
6335     unixctl_command_register("dpif/disable-megaflows", "", 0, 0,
6336                              ofproto_unixctl_dpif_disable_megaflows, NULL);
6337     unixctl_command_register("dpif/enable-megaflows", "", 0, 0,
6338                              ofproto_unixctl_dpif_enable_megaflows, NULL);
6339 }
6340 \f
6341 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
6342  *
6343  * This is deprecated.  It is only for compatibility with broken device drivers
6344  * in old versions of Linux that do not properly support VLANs when VLAN
6345  * devices are not used.  When broken device drivers are no longer in
6346  * widespread use, we will delete these interfaces. */
6347
6348 static int
6349 set_realdev(struct ofport *ofport_, ofp_port_t realdev_ofp_port, int vid)
6350 {
6351     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
6352     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
6353
6354     if (realdev_ofp_port == ofport->realdev_ofp_port
6355         && vid == ofport->vlandev_vid) {
6356         return 0;
6357     }
6358
6359     ofproto->backer->need_revalidate = REV_RECONFIGURE;
6360
6361     if (ofport->realdev_ofp_port) {
6362         vsp_remove(ofport);
6363     }
6364     if (realdev_ofp_port && ofport->bundle) {
6365         /* vlandevs are enslaved to their realdevs, so they are not allowed to
6366          * themselves be part of a bundle. */
6367         bundle_set(ofport->up.ofproto, ofport->bundle, NULL);
6368     }
6369
6370     ofport->realdev_ofp_port = realdev_ofp_port;
6371     ofport->vlandev_vid = vid;
6372
6373     if (realdev_ofp_port) {
6374         vsp_add(ofport, realdev_ofp_port, vid);
6375     }
6376
6377     return 0;
6378 }
6379
6380 static uint32_t
6381 hash_realdev_vid(ofp_port_t realdev_ofp_port, int vid)
6382 {
6383     return hash_2words(ofp_to_u16(realdev_ofp_port), vid);
6384 }
6385
6386 bool
6387 ofproto_has_vlan_splinters(const struct ofproto_dpif *ofproto)
6388     OVS_EXCLUDED(ofproto->vsp_mutex)
6389 {
6390     bool ret;
6391
6392     ovs_mutex_lock(&ofproto->vsp_mutex);
6393     ret = !hmap_is_empty(&ofproto->realdev_vid_map);
6394     ovs_mutex_unlock(&ofproto->vsp_mutex);
6395     return ret;
6396 }
6397
6398 static ofp_port_t
6399 vsp_realdev_to_vlandev__(const struct ofproto_dpif *ofproto,
6400                          ofp_port_t realdev_ofp_port, ovs_be16 vlan_tci)
6401     OVS_REQUIRES(ofproto->vsp_mutex)
6402 {
6403     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
6404         int vid = vlan_tci_to_vid(vlan_tci);
6405         const struct vlan_splinter *vsp;
6406
6407         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
6408                                  hash_realdev_vid(realdev_ofp_port, vid),
6409                                  &ofproto->realdev_vid_map) {
6410             if (vsp->realdev_ofp_port == realdev_ofp_port
6411                 && vsp->vid == vid) {
6412                 return vsp->vlandev_ofp_port;
6413             }
6414         }
6415     }
6416     return realdev_ofp_port;
6417 }
6418
6419 /* Returns the OFP port number of the Linux VLAN device that corresponds to
6420  * 'vlan_tci' on the network device with port number 'realdev_ofp_port' in
6421  * 'struct ofport_dpif'.  For example, given 'realdev_ofp_port' of eth0 and
6422  * 'vlan_tci' 9, it would return the port number of eth0.9.
6423  *
6424  * Unless VLAN splinters are enabled for port 'realdev_ofp_port', this
6425  * function just returns its 'realdev_ofp_port' argument. */
6426 ofp_port_t
6427 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
6428                        ofp_port_t realdev_ofp_port, ovs_be16 vlan_tci)
6429     OVS_EXCLUDED(ofproto->vsp_mutex)
6430 {
6431     ofp_port_t ret;
6432
6433     ovs_mutex_lock(&ofproto->vsp_mutex);
6434     ret = vsp_realdev_to_vlandev__(ofproto, realdev_ofp_port, vlan_tci);
6435     ovs_mutex_unlock(&ofproto->vsp_mutex);
6436     return ret;
6437 }
6438
6439 static struct vlan_splinter *
6440 vlandev_find(const struct ofproto_dpif *ofproto, ofp_port_t vlandev_ofp_port)
6441 {
6442     struct vlan_splinter *vsp;
6443
6444     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node,
6445                              hash_ofp_port(vlandev_ofp_port),
6446                              &ofproto->vlandev_map) {
6447         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
6448             return vsp;
6449         }
6450     }
6451
6452     return NULL;
6453 }
6454
6455 /* Returns the OpenFlow port number of the "real" device underlying the Linux
6456  * VLAN device with OpenFlow port number 'vlandev_ofp_port' and stores the
6457  * VLAN VID of the Linux VLAN device in '*vid'.  For example, given
6458  * 'vlandev_ofp_port' of eth0.9, it would return the OpenFlow port number of
6459  * eth0 and store 9 in '*vid'.
6460  *
6461  * Returns 0 and does not modify '*vid' if 'vlandev_ofp_port' is not a Linux
6462  * VLAN device.  Unless VLAN splinters are enabled, this is what this function
6463  * always does.*/
6464 static ofp_port_t
6465 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
6466                        ofp_port_t vlandev_ofp_port, int *vid)
6467     OVS_REQ_WRLOCK(ofproto->vsp_mutex)
6468 {
6469     if (!hmap_is_empty(&ofproto->vlandev_map)) {
6470         const struct vlan_splinter *vsp;
6471
6472         vsp = vlandev_find(ofproto, vlandev_ofp_port);
6473         if (vsp) {
6474             if (vid) {
6475                 *vid = vsp->vid;
6476             }
6477             return vsp->realdev_ofp_port;
6478         }
6479     }
6480     return 0;
6481 }
6482
6483 /* Given 'flow', a flow representing a packet received on 'ofproto', checks
6484  * whether 'flow->in_port' represents a Linux VLAN device.  If so, changes
6485  * 'flow->in_port' to the "real" device backing the VLAN device, sets
6486  * 'flow->vlan_tci' to the VLAN VID, and returns true.  Otherwise (which is
6487  * always the case unless VLAN splinters are enabled), returns false without
6488  * making any changes. */
6489 static bool
6490 vsp_adjust_flow(const struct ofproto_dpif *ofproto, struct flow *flow)
6491     OVS_EXCLUDED(ofproto->vsp_mutex)
6492 {
6493     ofp_port_t realdev;
6494     int vid;
6495
6496     ovs_mutex_lock(&ofproto->vsp_mutex);
6497     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port.ofp_port, &vid);
6498     ovs_mutex_unlock(&ofproto->vsp_mutex);
6499     if (!realdev) {
6500         return false;
6501     }
6502
6503     /* Cause the flow to be processed as if it came in on the real device with
6504      * the VLAN device's VLAN ID. */
6505     flow->in_port.ofp_port = realdev;
6506     flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
6507     return true;
6508 }
6509
6510 static void
6511 vsp_remove(struct ofport_dpif *port)
6512 {
6513     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
6514     struct vlan_splinter *vsp;
6515
6516     ovs_mutex_lock(&ofproto->vsp_mutex);
6517     vsp = vlandev_find(ofproto, port->up.ofp_port);
6518     if (vsp) {
6519         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
6520         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
6521         free(vsp);
6522
6523         port->realdev_ofp_port = 0;
6524     } else {
6525         VLOG_ERR("missing vlan device record");
6526     }
6527     ovs_mutex_unlock(&ofproto->vsp_mutex);
6528 }
6529
6530 static void
6531 vsp_add(struct ofport_dpif *port, ofp_port_t realdev_ofp_port, int vid)
6532 {
6533     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
6534
6535     ovs_mutex_lock(&ofproto->vsp_mutex);
6536     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
6537         && (vsp_realdev_to_vlandev__(ofproto, realdev_ofp_port, htons(vid))
6538             == realdev_ofp_port)) {
6539         struct vlan_splinter *vsp;
6540
6541         vsp = xmalloc(sizeof *vsp);
6542         vsp->realdev_ofp_port = realdev_ofp_port;
6543         vsp->vlandev_ofp_port = port->up.ofp_port;
6544         vsp->vid = vid;
6545
6546         port->realdev_ofp_port = realdev_ofp_port;
6547
6548         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
6549                     hash_ofp_port(port->up.ofp_port));
6550         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
6551                     hash_realdev_vid(realdev_ofp_port, vid));
6552     } else {
6553         VLOG_ERR("duplicate vlan device record");
6554     }
6555     ovs_mutex_unlock(&ofproto->vsp_mutex);
6556 }
6557
6558 static odp_port_t
6559 ofp_port_to_odp_port(const struct ofproto_dpif *ofproto, ofp_port_t ofp_port)
6560 {
6561     const struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
6562     return ofport ? ofport->odp_port : ODPP_NONE;
6563 }
6564
6565 static struct ofport_dpif *
6566 odp_port_to_ofport(const struct dpif_backer *backer, odp_port_t odp_port)
6567 {
6568     struct ofport_dpif *port;
6569
6570     HMAP_FOR_EACH_IN_BUCKET (port, odp_port_node, hash_odp_port(odp_port),
6571                              &backer->odp_to_ofport_map) {
6572         if (port->odp_port == odp_port) {
6573             return port;
6574         }
6575     }
6576
6577     return NULL;
6578 }
6579
6580 static ofp_port_t
6581 odp_port_to_ofp_port(const struct ofproto_dpif *ofproto, odp_port_t odp_port)
6582 {
6583     struct ofport_dpif *port;
6584
6585     port = odp_port_to_ofport(ofproto->backer, odp_port);
6586     if (port && &ofproto->up == port->up.ofproto) {
6587         return port->up.ofp_port;
6588     } else {
6589         return OFPP_NONE;
6590     }
6591 }
6592
6593 /* Compute exponentially weighted moving average, adding 'new' as the newest,
6594  * most heavily weighted element.  'base' designates the rate of decay: after
6595  * 'base' further updates, 'new''s weight in the EWMA decays to about 1/e
6596  * (about .37). */
6597 static void
6598 exp_mavg(double *avg, int base, double new)
6599 {
6600     *avg = (*avg * (base - 1) + new) / base;
6601 }
6602
6603 static void
6604 update_moving_averages(struct dpif_backer *backer)
6605 {
6606     const int min_ms = 60 * 1000; /* milliseconds in one minute. */
6607     long long int minutes = (time_msec() - backer->created) / min_ms;
6608
6609     if (minutes > 0) {
6610         backer->lifetime.add_rate = (double) backer->total_subfacet_add_count
6611             / minutes;
6612         backer->lifetime.del_rate = (double) backer->total_subfacet_del_count
6613             / minutes;
6614     } else {
6615         backer->lifetime.add_rate = 0.0;
6616         backer->lifetime.del_rate = 0.0;
6617     }
6618
6619     /* Update hourly averages on the minute boundaries. */
6620     if (time_msec() - backer->last_minute >= min_ms) {
6621         exp_mavg(&backer->hourly.add_rate, 60, backer->subfacet_add_count);
6622         exp_mavg(&backer->hourly.del_rate, 60, backer->subfacet_del_count);
6623
6624         /* Update daily averages on the hour boundaries. */
6625         if ((backer->last_minute - backer->created) / min_ms % 60 == 59) {
6626             exp_mavg(&backer->daily.add_rate, 24, backer->hourly.add_rate);
6627             exp_mavg(&backer->daily.del_rate, 24, backer->hourly.del_rate);
6628         }
6629
6630         backer->total_subfacet_add_count += backer->subfacet_add_count;
6631         backer->total_subfacet_del_count += backer->subfacet_del_count;
6632         backer->subfacet_add_count = 0;
6633         backer->subfacet_del_count = 0;
6634         backer->last_minute += min_ms;
6635     }
6636 }
6637
6638 const struct ofproto_class ofproto_dpif_class = {
6639     init,
6640     enumerate_types,
6641     enumerate_names,
6642     del,
6643     port_open_type,
6644     type_run,
6645     type_run_fast,
6646     type_wait,
6647     alloc,
6648     construct,
6649     destruct,
6650     dealloc,
6651     run,
6652     run_fast,
6653     wait,
6654     get_memory_usage,
6655     flush,
6656     get_features,
6657     get_tables,
6658     port_alloc,
6659     port_construct,
6660     port_destruct,
6661     port_dealloc,
6662     port_modified,
6663     port_reconfigured,
6664     port_query_by_name,
6665     port_add,
6666     port_del,
6667     port_get_stats,
6668     port_dump_start,
6669     port_dump_next,
6670     port_dump_done,
6671     port_poll,
6672     port_poll_wait,
6673     port_is_lacp_current,
6674     NULL,                       /* rule_choose_table */
6675     rule_alloc,
6676     rule_construct,
6677     rule_destruct,
6678     rule_dealloc,
6679     rule_get_stats,
6680     rule_execute,
6681     rule_modify_actions,
6682     set_frag_handling,
6683     packet_out,
6684     set_netflow,
6685     get_netflow_ids,
6686     set_sflow,
6687     set_ipfix,
6688     set_cfm,
6689     get_cfm_status,
6690     set_bfd,
6691     get_bfd_status,
6692     set_stp,
6693     get_stp_status,
6694     set_stp_port,
6695     get_stp_port_status,
6696     set_queues,
6697     bundle_set,
6698     bundle_remove,
6699     mirror_set__,
6700     mirror_get_stats__,
6701     set_flood_vlans,
6702     is_mirror_output_bundle,
6703     forward_bpdu_changed,
6704     set_mac_table_config,
6705     set_realdev,
6706     NULL,                       /* meter_get_features */
6707     NULL,                       /* meter_set */
6708     NULL,                       /* meter_get */
6709     NULL,                       /* meter_del */
6710 };