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