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