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