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