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