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