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