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