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