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