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