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