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