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