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