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