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