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