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