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