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