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