ofproto: Fix use-after-free in bridge destruction with groups.
[cascardo/ovs.git] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015 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 "ovs-lldp.h"
33 #include "dpif.h"
34 #include "dynamic-string.h"
35 #include "fail-open.h"
36 #include "guarded-list.h"
37 #include "hmapx.h"
38 #include "lacp.h"
39 #include "learn.h"
40 #include "mac-learning.h"
41 #include "mcast-snooping.h"
42 #include "meta-flow.h"
43 #include "multipath.h"
44 #include "netdev-vport.h"
45 #include "netdev.h"
46 #include "netlink.h"
47 #include "nx-match.h"
48 #include "odp-util.h"
49 #include "odp-execute.h"
50 #include "ofp-util.h"
51 #include "ofpbuf.h"
52 #include "ofp-actions.h"
53 #include "ofp-parse.h"
54 #include "ofp-print.h"
55 #include "ofproto-dpif-ipfix.h"
56 #include "ofproto-dpif-mirror.h"
57 #include "ofproto-dpif-monitor.h"
58 #include "ofproto-dpif-rid.h"
59 #include "ofproto-dpif-sflow.h"
60 #include "ofproto-dpif-upcall.h"
61 #include "ofproto-dpif-xlate.h"
62 #include "poll-loop.h"
63 #include "ovs-rcu.h"
64 #include "ovs-router.h"
65 #include "seq.h"
66 #include "simap.h"
67 #include "smap.h"
68 #include "timer.h"
69 #include "tunnel.h"
70 #include "unaligned.h"
71 #include "unixctl.h"
72 #include "vlan-bitmap.h"
73 #include "openvswitch/vlog.h"
74
75 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
76
77 COVERAGE_DEFINE(ofproto_dpif_expired);
78 COVERAGE_DEFINE(packet_in_overflow);
79
80 struct flow_miss;
81
82 struct rule_dpif {
83     struct rule up;
84
85     /* These statistics:
86      *
87      *   - Do include packets and bytes from datapath flows which have not
88      *   recently been processed by a revalidator. */
89     struct ovs_mutex stats_mutex;
90     struct dpif_flow_stats stats OVS_GUARDED;
91
92    /* In non-NULL, will point to a new rule (for which a reference is held) to
93     * which all the stats updates should be forwarded. This exists only
94     * transitionally when flows are replaced.
95     *
96     * Protected by stats_mutex.  If both 'rule->stats_mutex' and
97     * 'rule->new_rule->stats_mutex' must be held together, acquire them in that
98     * order, */
99     struct rule_dpif *new_rule OVS_GUARDED;
100
101     /* If non-zero then the recirculation id that has
102      * been allocated for use with this rule.
103      * The recirculation id and associated internal flow should
104      * be freed when the rule is freed */
105     uint32_t recirc_id;
106 };
107
108 /* RULE_CAST() depends on this. */
109 BUILD_ASSERT_DECL(offsetof(struct rule_dpif, up) == 0);
110
111 static void rule_get_stats(struct rule *, uint64_t *packets, uint64_t *bytes,
112                            long long int *used);
113 static struct rule_dpif *rule_dpif_cast(const struct rule *);
114 static void rule_expire(struct rule_dpif *);
115
116 struct group_dpif {
117     struct ofgroup up;
118
119     /* These statistics:
120      *
121      *   - Do include packets and bytes from datapath flows which have not
122      *   recently been processed by a revalidator. */
123     struct ovs_mutex stats_mutex;
124     uint64_t packet_count OVS_GUARDED;  /* Number of packets received. */
125     uint64_t byte_count OVS_GUARDED;    /* Number of bytes received. */
126 };
127
128 struct ofbundle {
129     struct hmap_node hmap_node; /* In struct ofproto's "bundles" hmap. */
130     struct ofproto_dpif *ofproto; /* Owning ofproto. */
131     void *aux;                  /* Key supplied by ofproto's client. */
132     char *name;                 /* Identifier for log messages. */
133
134     /* Configuration. */
135     struct ovs_list ports;      /* Contains "struct ofport"s. */
136     enum port_vlan_mode vlan_mode; /* VLAN mode */
137     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
138     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
139                                  * NULL if all VLANs are trunked. */
140     struct lacp *lacp;          /* LACP if LACP is enabled, otherwise NULL. */
141     struct bond *bond;          /* Nonnull iff more than one port. */
142     bool use_priority_tags;     /* Use 802.1p tag for frames in VLAN 0? */
143
144     /* Status. */
145     bool floodable;          /* True if no port has OFPUTIL_PC_NO_FLOOD set. */
146 };
147
148 static void bundle_remove(struct ofport *);
149 static void bundle_update(struct ofbundle *);
150 static void bundle_destroy(struct ofbundle *);
151 static void bundle_del_port(struct ofport_dpif *);
152 static void bundle_run(struct ofbundle *);
153 static void bundle_wait(struct ofbundle *);
154 static void bundle_flush_macs(struct ofbundle *, bool);
155 static void bundle_move(struct ofbundle *, struct ofbundle *);
156
157 static void stp_run(struct ofproto_dpif *ofproto);
158 static void stp_wait(struct ofproto_dpif *ofproto);
159 static int set_stp_port(struct ofport *,
160                         const struct ofproto_port_stp_settings *);
161
162 static void rstp_run(struct ofproto_dpif *ofproto);
163 static void set_rstp_port(struct ofport *,
164                          const struct ofproto_port_rstp_settings *);
165
166 struct ofport_dpif {
167     struct hmap_node odp_port_node; /* In dpif_backer's "odp_to_ofport_map". */
168     struct ofport up;
169
170     odp_port_t odp_port;
171     struct ofbundle *bundle;    /* Bundle that contains this port, if any. */
172     struct ovs_list bundle_node;/* In struct ofbundle's "ports" list. */
173     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
174     struct bfd *bfd;            /* BFD, if any. */
175     struct lldp *lldp;          /* lldp, if any. */
176     bool may_enable;            /* May be enabled in bonds. */
177     bool is_tunnel;             /* This port is a tunnel. */
178     bool is_layer3;             /* This is a layer 3 port. */
179     long long int carrier_seq;  /* Carrier status changes. */
180     struct ofport_dpif *peer;   /* Peer if patch port. */
181
182     /* Spanning tree. */
183     struct stp_port *stp_port;  /* Spanning Tree Protocol, if any. */
184     enum stp_state stp_state;   /* Always STP_DISABLED if STP not in use. */
185     long long int stp_state_entered;
186
187     /* Rapid Spanning Tree. */
188     struct rstp_port *rstp_port; /* Rapid Spanning Tree Protocol, if any. */
189     enum rstp_state rstp_state; /* Always RSTP_DISABLED if RSTP not in use. */
190
191     /* Queue to DSCP mapping. */
192     struct ofproto_port_queue *qdscp;
193     size_t n_qdscp;
194
195     /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
196      *
197      * This is deprecated.  It is only for compatibility with broken device
198      * drivers in old versions of Linux that do not properly support VLANs when
199      * VLAN devices are not used.  When broken device drivers are no longer in
200      * widespread use, we will delete these interfaces. */
201     ofp_port_t realdev_ofp_port;
202     int vlandev_vid;
203 };
204
205 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
206  *
207  * This is deprecated.  It is only for compatibility with broken device drivers
208  * in old versions of Linux that do not properly support VLANs when VLAN
209  * devices are not used.  When broken device drivers are no longer in
210  * widespread use, we will delete these interfaces. */
211 struct vlan_splinter {
212     struct hmap_node realdev_vid_node;
213     struct hmap_node vlandev_node;
214     ofp_port_t realdev_ofp_port;
215     ofp_port_t vlandev_ofp_port;
216     int vid;
217 };
218
219 static void vsp_remove(struct ofport_dpif *);
220 static void vsp_add(struct ofport_dpif *, ofp_port_t realdev_ofp_port, int vid);
221
222 static odp_port_t ofp_port_to_odp_port(const struct ofproto_dpif *,
223                                        ofp_port_t);
224
225 static ofp_port_t odp_port_to_ofp_port(const struct ofproto_dpif *,
226                                        odp_port_t);
227
228 static struct ofport_dpif *
229 ofport_dpif_cast(const struct ofport *ofport)
230 {
231     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
232 }
233
234 static void port_run(struct ofport_dpif *);
235 static int set_bfd(struct ofport *, const struct smap *);
236 static int set_cfm(struct ofport *, const struct cfm_settings *);
237 static int set_lldp(struct ofport *ofport_, const struct smap *cfg);
238 static void ofport_update_peer(struct ofport_dpif *);
239
240 /* Reasons that we might need to revalidate every datapath flow, and
241  * corresponding coverage counters.
242  *
243  * A value of 0 means that there is no need to revalidate.
244  *
245  * It would be nice to have some cleaner way to integrate with coverage
246  * counters, but with only a few reasons I guess this is good enough for
247  * now. */
248 enum revalidate_reason {
249     REV_RECONFIGURE = 1,       /* Switch configuration changed. */
250     REV_STP,                   /* Spanning tree protocol port status change. */
251     REV_RSTP,                  /* RSTP port status change. */
252     REV_BOND,                  /* Bonding changed. */
253     REV_PORT_TOGGLED,          /* Port enabled or disabled by CFM, LACP, ...*/
254     REV_FLOW_TABLE,            /* Flow table changed. */
255     REV_MAC_LEARNING,          /* Mac learning changed. */
256     REV_MCAST_SNOOPING,        /* Multicast snooping changed. */
257 };
258 COVERAGE_DEFINE(rev_reconfigure);
259 COVERAGE_DEFINE(rev_stp);
260 COVERAGE_DEFINE(rev_rstp);
261 COVERAGE_DEFINE(rev_bond);
262 COVERAGE_DEFINE(rev_port_toggled);
263 COVERAGE_DEFINE(rev_flow_table);
264 COVERAGE_DEFINE(rev_mac_learning);
265 COVERAGE_DEFINE(rev_mcast_snooping);
266
267 /* All datapaths of a given type share a single dpif backer instance. */
268 struct dpif_backer {
269     char *type;
270     int refcount;
271     struct dpif *dpif;
272     struct udpif *udpif;
273
274     struct ovs_rwlock odp_to_ofport_lock;
275     struct hmap odp_to_ofport_map OVS_GUARDED; /* Contains "struct ofport"s. */
276
277     struct simap tnl_backers;      /* Set of dpif ports backing tunnels. */
278
279     enum revalidate_reason need_revalidate; /* Revalidate all flows. */
280
281     bool recv_set_enable; /* Enables or disables receiving packets. */
282
283     /* Version string of the datapath stored in OVSDB. */
284     char *dp_version_string;
285
286     /* Datapath feature support. */
287     struct dpif_backer_support support;
288     struct atomic_count tnl_count;
289 };
290
291 /* All existing ofproto_backer instances, indexed by ofproto->up.type. */
292 static struct shash all_dpif_backers = SHASH_INITIALIZER(&all_dpif_backers);
293
294 struct ofproto_dpif {
295     struct hmap_node all_ofproto_dpifs_node; /* In 'all_ofproto_dpifs'. */
296     struct ofproto up;
297     struct dpif_backer *backer;
298
299     ATOMIC(cls_version_t) tables_version;  /* For classifier lookups. */
300
301     uint64_t dump_seq; /* Last read of udpif_dump_seq(). */
302
303     /* Special OpenFlow rules. */
304     struct rule_dpif *miss_rule; /* Sends flow table misses to controller. */
305     struct rule_dpif *no_packet_in_rule; /* Drops flow table misses. */
306     struct rule_dpif *drop_frags_rule; /* Used in OFPC_FRAG_DROP mode. */
307
308     /* Bridging. */
309     struct netflow *netflow;
310     struct dpif_sflow *sflow;
311     struct dpif_ipfix *ipfix;
312     struct hmap bundles;        /* Contains "struct ofbundle"s. */
313     struct mac_learning *ml;
314     struct mcast_snooping *ms;
315     bool has_bonded_bundles;
316     bool lacp_enabled;
317     struct mbridge *mbridge;
318
319     struct ovs_mutex stats_mutex;
320     struct netdev_stats stats OVS_GUARDED; /* To account packets generated and
321                                             * consumed in userspace. */
322
323     /* Spanning tree. */
324     struct stp *stp;
325     long long int stp_last_tick;
326
327     /* Rapid Spanning Tree. */
328     struct rstp *rstp;
329     long long int rstp_last_tick;
330
331     /* VLAN splinters. */
332     struct ovs_mutex vsp_mutex;
333     struct hmap realdev_vid_map OVS_GUARDED; /* (realdev,vid) -> vlandev. */
334     struct hmap vlandev_map OVS_GUARDED;     /* vlandev -> (realdev,vid). */
335
336     /* Ports. */
337     struct sset ports;             /* Set of standard port names. */
338     struct sset ghost_ports;       /* Ports with no datapath port. */
339     struct sset port_poll_set;     /* Queued names for port_poll() reply. */
340     int port_poll_errno;           /* Last errno for port_poll() reply. */
341     uint64_t change_seq;           /* Connectivity status changes. */
342
343     /* Work queues. */
344     struct guarded_list pins;      /* Contains "struct ofputil_packet_in"s. */
345     struct seq *pins_seq;          /* For notifying 'pins' reception. */
346     uint64_t pins_seqno;
347 };
348
349 /* All existing ofproto_dpif instances, indexed by ->up.name. */
350 static struct hmap all_ofproto_dpifs = HMAP_INITIALIZER(&all_ofproto_dpifs);
351
352 static bool ofproto_use_tnl_push_pop = true;
353 static void ofproto_unixctl_init(void);
354
355 static inline struct ofproto_dpif *
356 ofproto_dpif_cast(const struct ofproto *ofproto)
357 {
358     ovs_assert(ofproto->ofproto_class == &ofproto_dpif_class);
359     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
360 }
361
362 size_t
363 ofproto_dpif_get_max_mpls_depth(const struct ofproto_dpif *ofproto)
364 {
365     return ofproto->backer->support.max_mpls_depth;
366 }
367
368 bool
369 ofproto_dpif_get_enable_recirc(const struct ofproto_dpif *ofproto)
370 {
371     return ofproto->backer->support.recirc;
372 }
373
374 bool
375 ofproto_dpif_get_enable_ufid(struct dpif_backer *backer)
376 {
377     return backer->support.ufid;
378 }
379
380 static void ofproto_trace(struct ofproto_dpif *, struct flow *,
381                           const struct dp_packet *packet,
382                           const struct ofpact[], size_t ofpacts_len,
383                           struct ds *);
384
385 /* Global variables. */
386 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
387
388 /* Initial mappings of port to bridge mappings. */
389 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
390
391 /* Executes 'fm'.  The caller retains ownership of 'fm' and everything in
392  * it. */
393 void
394 ofproto_dpif_flow_mod(struct ofproto_dpif *ofproto,
395                       struct ofputil_flow_mod *fm)
396 {
397     ofproto_flow_mod(&ofproto->up, fm);
398 }
399
400 /* Appends 'pin' to the queue of "packet ins" to be sent to the controller.
401  * Takes ownership of 'pin' and pin->packet. */
402 void
403 ofproto_dpif_send_packet_in(struct ofproto_dpif *ofproto,
404                             struct ofproto_packet_in *pin)
405 {
406     if (!guarded_list_push_back(&ofproto->pins, &pin->list_node, 1024)) {
407         COVERAGE_INC(packet_in_overflow);
408         free(CONST_CAST(void *, pin->up.packet));
409         free(pin);
410     }
411
412     /* Wakes up main thread for packet-in I/O. */
413     seq_change(ofproto->pins_seq);
414 }
415
416 /* The default "table-miss" behaviour for OpenFlow1.3+ is to drop the
417  * packet rather than to send the packet to the controller.
418  *
419  * This function returns false to indicate that a packet_in message
420  * for a "table-miss" should be sent to at least one controller.
421  * False otherwise. */
422 bool
423 ofproto_dpif_wants_packet_in_on_miss(struct ofproto_dpif *ofproto)
424 {
425     return connmgr_wants_packet_in_on_miss(ofproto->up.connmgr);
426 }
427 \f
428 /* Factory functions. */
429
430 static void
431 init(const struct shash *iface_hints)
432 {
433     struct shash_node *node;
434
435     /* Make a local copy, since we don't own 'iface_hints' elements. */
436     SHASH_FOR_EACH(node, iface_hints) {
437         const struct iface_hint *orig_hint = node->data;
438         struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
439
440         new_hint->br_name = xstrdup(orig_hint->br_name);
441         new_hint->br_type = xstrdup(orig_hint->br_type);
442         new_hint->ofp_port = orig_hint->ofp_port;
443
444         shash_add(&init_ofp_ports, node->name, new_hint);
445     }
446 }
447
448 static void
449 enumerate_types(struct sset *types)
450 {
451     dp_enumerate_types(types);
452 }
453
454 static int
455 enumerate_names(const char *type, struct sset *names)
456 {
457     struct ofproto_dpif *ofproto;
458
459     sset_clear(names);
460     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
461         if (strcmp(type, ofproto->up.type)) {
462             continue;
463         }
464         sset_add(names, ofproto->up.name);
465     }
466
467     return 0;
468 }
469
470 static int
471 del(const char *type, const char *name)
472 {
473     struct dpif *dpif;
474     int error;
475
476     error = dpif_open(name, type, &dpif);
477     if (!error) {
478         error = dpif_delete(dpif);
479         dpif_close(dpif);
480     }
481     return error;
482 }
483 \f
484 static const char *
485 port_open_type(const char *datapath_type, const char *port_type)
486 {
487     return dpif_port_open_type(datapath_type, port_type);
488 }
489
490 /* Type functions. */
491
492 static void process_dpif_port_changes(struct dpif_backer *);
493 static void process_dpif_all_ports_changed(struct dpif_backer *);
494 static void process_dpif_port_change(struct dpif_backer *,
495                                      const char *devname);
496 static void process_dpif_port_error(struct dpif_backer *, int error);
497
498 static struct ofproto_dpif *
499 lookup_ofproto_dpif_by_port_name(const char *name)
500 {
501     struct ofproto_dpif *ofproto;
502
503     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
504         if (sset_contains(&ofproto->ports, name)) {
505             return ofproto;
506         }
507     }
508
509     return NULL;
510 }
511
512 static int
513 type_run(const char *type)
514 {
515     struct dpif_backer *backer;
516
517     backer = shash_find_data(&all_dpif_backers, type);
518     if (!backer) {
519         /* This is not necessarily a problem, since backers are only
520          * created on demand. */
521         return 0;
522     }
523
524
525     if (dpif_run(backer->dpif)) {
526         backer->need_revalidate = REV_RECONFIGURE;
527     }
528
529     udpif_run(backer->udpif);
530
531     /* If vswitchd started with other_config:flow_restore_wait set as "true",
532      * and the configuration has now changed to "false", enable receiving
533      * packets from the datapath. */
534     if (!backer->recv_set_enable && !ofproto_get_flow_restore_wait()) {
535         int error;
536
537         backer->recv_set_enable = true;
538
539         error = dpif_recv_set(backer->dpif, backer->recv_set_enable);
540         if (error) {
541             VLOG_ERR("Failed to enable receiving packets in dpif.");
542             return error;
543         }
544         dpif_flow_flush(backer->dpif);
545         backer->need_revalidate = REV_RECONFIGURE;
546     }
547
548     if (backer->recv_set_enable) {
549         udpif_set_threads(backer->udpif, n_handlers, n_revalidators);
550     }
551
552     dpif_poll_threads_set(backer->dpif, n_dpdk_rxqs, pmd_cpu_mask);
553
554     if (backer->need_revalidate) {
555         struct ofproto_dpif *ofproto;
556         struct simap_node *node;
557         struct simap tmp_backers;
558
559         /* Handle tunnel garbage collection. */
560         simap_init(&tmp_backers);
561         simap_swap(&backer->tnl_backers, &tmp_backers);
562
563         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
564             struct ofport_dpif *iter;
565
566             if (backer != ofproto->backer) {
567                 continue;
568             }
569
570             HMAP_FOR_EACH (iter, up.hmap_node, &ofproto->up.ports) {
571                 char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
572                 const char *dp_port;
573
574                 if (!iter->is_tunnel) {
575                     continue;
576                 }
577
578                 dp_port = netdev_vport_get_dpif_port(iter->up.netdev,
579                                                      namebuf, sizeof namebuf);
580                 node = simap_find(&tmp_backers, dp_port);
581                 if (node) {
582                     simap_put(&backer->tnl_backers, dp_port, node->data);
583                     simap_delete(&tmp_backers, node);
584                     node = simap_find(&backer->tnl_backers, dp_port);
585                 } else {
586                     node = simap_find(&backer->tnl_backers, dp_port);
587                     if (!node) {
588                         odp_port_t odp_port = ODPP_NONE;
589
590                         if (!dpif_port_add(backer->dpif, iter->up.netdev,
591                                            &odp_port)) {
592                             simap_put(&backer->tnl_backers, dp_port,
593                                       odp_to_u32(odp_port));
594                             node = simap_find(&backer->tnl_backers, dp_port);
595                         }
596                     }
597                 }
598
599                 iter->odp_port = node ? u32_to_odp(node->data) : ODPP_NONE;
600                 if (tnl_port_reconfigure(iter, iter->up.netdev,
601                                          iter->odp_port,
602                                          ovs_native_tunneling_is_on(ofproto), dp_port)) {
603                     backer->need_revalidate = REV_RECONFIGURE;
604                 }
605             }
606         }
607
608         SIMAP_FOR_EACH (node, &tmp_backers) {
609             dpif_port_del(backer->dpif, u32_to_odp(node->data));
610         }
611         simap_destroy(&tmp_backers);
612
613         switch (backer->need_revalidate) {
614         case REV_RECONFIGURE:    COVERAGE_INC(rev_reconfigure);    break;
615         case REV_STP:            COVERAGE_INC(rev_stp);            break;
616         case REV_RSTP:           COVERAGE_INC(rev_rstp);           break;
617         case REV_BOND:           COVERAGE_INC(rev_bond);           break;
618         case REV_PORT_TOGGLED:   COVERAGE_INC(rev_port_toggled);   break;
619         case REV_FLOW_TABLE:     COVERAGE_INC(rev_flow_table);     break;
620         case REV_MAC_LEARNING:   COVERAGE_INC(rev_mac_learning);   break;
621         case REV_MCAST_SNOOPING: COVERAGE_INC(rev_mcast_snooping); break;
622         }
623         backer->need_revalidate = 0;
624
625         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
626             struct ofport_dpif *ofport;
627             struct ofbundle *bundle;
628
629             if (ofproto->backer != backer) {
630                 continue;
631             }
632
633             xlate_txn_start();
634             xlate_ofproto_set(ofproto, ofproto->up.name,
635                               ofproto->backer->dpif, ofproto->ml,
636                               ofproto->stp, ofproto->rstp, ofproto->ms,
637                               ofproto->mbridge, ofproto->sflow, ofproto->ipfix,
638                               ofproto->netflow,
639                               ofproto->up.forward_bpdu,
640                               connmgr_has_in_band(ofproto->up.connmgr),
641                               &ofproto->backer->support);
642
643             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
644                 xlate_bundle_set(ofproto, bundle, bundle->name,
645                                  bundle->vlan_mode, bundle->vlan,
646                                  bundle->trunks, bundle->use_priority_tags,
647                                  bundle->bond, bundle->lacp,
648                                  bundle->floodable);
649             }
650
651             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
652                 int stp_port = ofport->stp_port
653                     ? stp_port_no(ofport->stp_port)
654                     : -1;
655                 xlate_ofport_set(ofproto, ofport->bundle, ofport,
656                                  ofport->up.ofp_port, ofport->odp_port,
657                                  ofport->up.netdev, ofport->cfm, ofport->bfd,
658                                  ofport->lldp, ofport->peer, stp_port,
659                                  ofport->rstp_port, ofport->qdscp,
660                                  ofport->n_qdscp, ofport->up.pp.config,
661                                  ofport->up.pp.state, ofport->is_tunnel,
662                                  ofport->may_enable);
663             }
664             xlate_txn_commit();
665         }
666
667         udpif_revalidate(backer->udpif);
668     }
669
670     process_dpif_port_changes(backer);
671
672     return 0;
673 }
674
675 /* Check for and handle port changes in 'backer''s dpif. */
676 static void
677 process_dpif_port_changes(struct dpif_backer *backer)
678 {
679     for (;;) {
680         char *devname;
681         int error;
682
683         error = dpif_port_poll(backer->dpif, &devname);
684         switch (error) {
685         case EAGAIN:
686             return;
687
688         case ENOBUFS:
689             process_dpif_all_ports_changed(backer);
690             break;
691
692         case 0:
693             process_dpif_port_change(backer, devname);
694             free(devname);
695             break;
696
697         default:
698             process_dpif_port_error(backer, error);
699             break;
700         }
701     }
702 }
703
704 static void
705 process_dpif_all_ports_changed(struct dpif_backer *backer)
706 {
707     struct ofproto_dpif *ofproto;
708     struct dpif_port dpif_port;
709     struct dpif_port_dump dump;
710     struct sset devnames;
711     const char *devname;
712
713     sset_init(&devnames);
714     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
715         if (ofproto->backer == backer) {
716             struct ofport *ofport;
717
718             HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
719                 sset_add(&devnames, netdev_get_name(ofport->netdev));
720             }
721         }
722     }
723     DPIF_PORT_FOR_EACH (&dpif_port, &dump, backer->dpif) {
724         sset_add(&devnames, dpif_port.name);
725     }
726
727     SSET_FOR_EACH (devname, &devnames) {
728         process_dpif_port_change(backer, devname);
729     }
730     sset_destroy(&devnames);
731 }
732
733 static void
734 process_dpif_port_change(struct dpif_backer *backer, const char *devname)
735 {
736     struct ofproto_dpif *ofproto;
737     struct dpif_port port;
738
739     /* Don't report on the datapath's device. */
740     if (!strcmp(devname, dpif_base_name(backer->dpif))) {
741         return;
742     }
743
744     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node,
745                    &all_ofproto_dpifs) {
746         if (simap_contains(&ofproto->backer->tnl_backers, devname)) {
747             return;
748         }
749     }
750
751     ofproto = lookup_ofproto_dpif_by_port_name(devname);
752     if (dpif_port_query_by_name(backer->dpif, devname, &port)) {
753         /* The port was removed.  If we know the datapath,
754          * report it through poll_set().  If we don't, it may be
755          * notifying us of a removal we initiated, so ignore it.
756          * If there's a pending ENOBUFS, let it stand, since
757          * everything will be reevaluated. */
758         if (ofproto && ofproto->port_poll_errno != ENOBUFS) {
759             sset_add(&ofproto->port_poll_set, devname);
760             ofproto->port_poll_errno = 0;
761         }
762     } else if (!ofproto) {
763         /* The port was added, but we don't know with which
764          * ofproto we should associate it.  Delete it. */
765         dpif_port_del(backer->dpif, port.port_no);
766     } else {
767         struct ofport_dpif *ofport;
768
769         ofport = ofport_dpif_cast(shash_find_data(
770                                       &ofproto->up.port_by_name, devname));
771         if (ofport
772             && ofport->odp_port != port.port_no
773             && !odp_port_to_ofport(backer, port.port_no))
774         {
775             /* 'ofport''s datapath port number has changed from
776              * 'ofport->odp_port' to 'port.port_no'.  Update our internal data
777              * structures to match. */
778             ovs_rwlock_wrlock(&backer->odp_to_ofport_lock);
779             hmap_remove(&backer->odp_to_ofport_map, &ofport->odp_port_node);
780             ofport->odp_port = port.port_no;
781             hmap_insert(&backer->odp_to_ofport_map, &ofport->odp_port_node,
782                         hash_odp_port(port.port_no));
783             ovs_rwlock_unlock(&backer->odp_to_ofport_lock);
784             backer->need_revalidate = REV_RECONFIGURE;
785         }
786     }
787     dpif_port_destroy(&port);
788 }
789
790 /* Propagate 'error' to all ofprotos based on 'backer'. */
791 static void
792 process_dpif_port_error(struct dpif_backer *backer, int error)
793 {
794     struct ofproto_dpif *ofproto;
795
796     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
797         if (ofproto->backer == backer) {
798             sset_clear(&ofproto->port_poll_set);
799             ofproto->port_poll_errno = error;
800         }
801     }
802 }
803
804 static void
805 type_wait(const char *type)
806 {
807     struct dpif_backer *backer;
808
809     backer = shash_find_data(&all_dpif_backers, type);
810     if (!backer) {
811         /* This is not necessarily a problem, since backers are only
812          * created on demand. */
813         return;
814     }
815
816     dpif_wait(backer->dpif);
817 }
818 \f
819 /* Basic life-cycle. */
820
821 static int add_internal_flows(struct ofproto_dpif *);
822
823 static struct ofproto *
824 alloc(void)
825 {
826     struct ofproto_dpif *ofproto = xzalloc(sizeof *ofproto);
827     return &ofproto->up;
828 }
829
830 static void
831 dealloc(struct ofproto *ofproto_)
832 {
833     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
834     free(ofproto);
835 }
836
837 static void
838 close_dpif_backer(struct dpif_backer *backer)
839 {
840     ovs_assert(backer->refcount > 0);
841
842     if (--backer->refcount) {
843         return;
844     }
845
846     udpif_destroy(backer->udpif);
847
848     simap_destroy(&backer->tnl_backers);
849     ovs_rwlock_destroy(&backer->odp_to_ofport_lock);
850     hmap_destroy(&backer->odp_to_ofport_map);
851     shash_find_and_delete(&all_dpif_backers, backer->type);
852     free(backer->type);
853     free(backer->dp_version_string);
854     dpif_close(backer->dpif);
855     free(backer);
856 }
857
858 /* Datapath port slated for removal from datapath. */
859 struct odp_garbage {
860     struct ovs_list list_node;
861     odp_port_t odp_port;
862 };
863
864 static bool check_variable_length_userdata(struct dpif_backer *backer);
865 static void check_support(struct dpif_backer *backer);
866
867 static int
868 open_dpif_backer(const char *type, struct dpif_backer **backerp)
869 {
870     struct dpif_backer *backer;
871     struct dpif_port_dump port_dump;
872     struct dpif_port port;
873     struct shash_node *node;
874     struct ovs_list garbage_list;
875     struct odp_garbage *garbage;
876
877     struct sset names;
878     char *backer_name;
879     const char *name;
880     int error;
881
882     recirc_init();
883
884     backer = shash_find_data(&all_dpif_backers, type);
885     if (backer) {
886         backer->refcount++;
887         *backerp = backer;
888         return 0;
889     }
890
891     backer_name = xasprintf("ovs-%s", type);
892
893     /* Remove any existing datapaths, since we assume we're the only
894      * userspace controlling the datapath. */
895     sset_init(&names);
896     dp_enumerate_names(type, &names);
897     SSET_FOR_EACH(name, &names) {
898         struct dpif *old_dpif;
899
900         /* Don't remove our backer if it exists. */
901         if (!strcmp(name, backer_name)) {
902             continue;
903         }
904
905         if (dpif_open(name, type, &old_dpif)) {
906             VLOG_WARN("couldn't open old datapath %s to remove it", name);
907         } else {
908             dpif_delete(old_dpif);
909             dpif_close(old_dpif);
910         }
911     }
912     sset_destroy(&names);
913
914     backer = xmalloc(sizeof *backer);
915
916     error = dpif_create_and_open(backer_name, type, &backer->dpif);
917     free(backer_name);
918     if (error) {
919         VLOG_ERR("failed to open datapath of type %s: %s", type,
920                  ovs_strerror(error));
921         free(backer);
922         return error;
923     }
924     backer->udpif = udpif_create(backer, backer->dpif);
925
926     backer->type = xstrdup(type);
927     backer->refcount = 1;
928     hmap_init(&backer->odp_to_ofport_map);
929     ovs_rwlock_init(&backer->odp_to_ofport_lock);
930     backer->need_revalidate = 0;
931     simap_init(&backer->tnl_backers);
932     backer->recv_set_enable = !ofproto_get_flow_restore_wait();
933     *backerp = backer;
934
935     if (backer->recv_set_enable) {
936         dpif_flow_flush(backer->dpif);
937     }
938
939     /* Loop through the ports already on the datapath and remove any
940      * that we don't need anymore. */
941     list_init(&garbage_list);
942     dpif_port_dump_start(&port_dump, backer->dpif);
943     while (dpif_port_dump_next(&port_dump, &port)) {
944         node = shash_find(&init_ofp_ports, port.name);
945         if (!node && strcmp(port.name, dpif_base_name(backer->dpif))) {
946             garbage = xmalloc(sizeof *garbage);
947             garbage->odp_port = port.port_no;
948             list_push_front(&garbage_list, &garbage->list_node);
949         }
950     }
951     dpif_port_dump_done(&port_dump);
952
953     LIST_FOR_EACH_POP (garbage, list_node, &garbage_list) {
954         dpif_port_del(backer->dpif, garbage->odp_port);
955         free(garbage);
956     }
957
958     shash_add(&all_dpif_backers, type, backer);
959
960     check_support(backer);
961     atomic_count_init(&backer->tnl_count, 0);
962
963     error = dpif_recv_set(backer->dpif, backer->recv_set_enable);
964     if (error) {
965         VLOG_ERR("failed to listen on datapath of type %s: %s",
966                  type, ovs_strerror(error));
967         close_dpif_backer(backer);
968         return error;
969     }
970
971     if (backer->recv_set_enable) {
972         udpif_set_threads(backer->udpif, n_handlers, n_revalidators);
973     }
974
975     /* This check fails if performed before udpif threads have been set,
976      * as the kernel module checks that the 'pid' in userspace action
977      * is non-zero. */
978     backer->support.variable_length_userdata
979         = check_variable_length_userdata(backer);
980     backer->dp_version_string = dpif_get_dp_version(backer->dpif);
981
982     return error;
983 }
984
985 bool
986 ovs_native_tunneling_is_on(struct ofproto_dpif *ofproto)
987 {
988     return ofproto_use_tnl_push_pop && ofproto->backer->support.tnl_push_pop &&
989            atomic_count_get(&ofproto->backer->tnl_count);
990 }
991
992 /* Tests whether 'backer''s datapath supports recirculation.  Only newer
993  * datapaths support OVS_KEY_ATTR_RECIRC_ID in keys.  We need to disable some
994  * features on older datapaths that don't support this feature.
995  *
996  * Returns false if 'backer' definitely does not support recirculation, true if
997  * it seems to support recirculation or if at least the error we get is
998  * ambiguous. */
999 static bool
1000 check_recirc(struct dpif_backer *backer)
1001 {
1002     struct flow flow;
1003     struct odputil_keybuf keybuf;
1004     struct ofpbuf key;
1005     bool enable_recirc;
1006
1007     memset(&flow, 0, sizeof flow);
1008     flow.recirc_id = 1;
1009     flow.dp_hash = 1;
1010
1011     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
1012     odp_flow_key_from_flow(&key, &flow, NULL, 0, true);
1013 #ifdef _WIN32
1014     /* XXX Force disable of datapath recirculation from userspace until the
1015      * dpif_probe_feature is properly implemented in the windows datapath */
1016     enable_recirc = false;
1017 #else
1018     enable_recirc = dpif_probe_feature(backer->dpif, "recirculation", &key,
1019                                        NULL);
1020 #endif
1021
1022     if (enable_recirc) {
1023         VLOG_INFO("%s: Datapath supports recirculation",
1024                   dpif_name(backer->dpif));
1025     } else {
1026         VLOG_INFO("%s: Datapath does not support recirculation",
1027                   dpif_name(backer->dpif));
1028     }
1029
1030     return enable_recirc;
1031 }
1032
1033 /* Tests whether 'dpif' supports unique flow ids. We can skip serializing
1034  * some flow attributes for datapaths that support this feature.
1035  *
1036  * Returns true if 'dpif' supports UFID for flow operations.
1037  * Returns false if  'dpif' does not support UFID. */
1038 static bool
1039 check_ufid(struct dpif_backer *backer)
1040 {
1041     struct flow flow;
1042     struct odputil_keybuf keybuf;
1043     struct ofpbuf key;
1044     ovs_u128 ufid;
1045     bool enable_ufid;
1046
1047     memset(&flow, 0, sizeof flow);
1048     flow.dl_type = htons(0x1234);
1049
1050     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
1051     odp_flow_key_from_flow(&key, &flow, NULL, 0, true);
1052     dpif_flow_hash(backer->dpif, key.data, key.size, &ufid);
1053
1054 #ifdef _WIN32
1055     /* XXX Force disable of datapath recirculation from userspace until the
1056      * dpif_probe_feature is properly implemented in the windows datapath */
1057     enable_ufid = false;
1058 #else
1059     enable_ufid = dpif_probe_feature(backer->dpif, "UFID", &key, &ufid);
1060 #endif
1061
1062     if (enable_ufid) {
1063         VLOG_INFO("%s: Datapath supports unique flow ids",
1064                   dpif_name(backer->dpif));
1065     } else {
1066         VLOG_INFO("%s: Datapath does not support unique flow ids",
1067                   dpif_name(backer->dpif));
1068     }
1069     return enable_ufid;
1070 }
1071
1072 /* Tests whether 'backer''s datapath supports variable-length
1073  * OVS_USERSPACE_ATTR_USERDATA in OVS_ACTION_ATTR_USERSPACE actions.  We need
1074  * to disable some features on older datapaths that don't support this
1075  * feature.
1076  *
1077  * Returns false if 'backer' definitely does not support variable-length
1078  * userdata, true if it seems to support them or if at least the error we get
1079  * is ambiguous. */
1080 static bool
1081 check_variable_length_userdata(struct dpif_backer *backer)
1082 {
1083     struct eth_header *eth;
1084     struct ofpbuf actions;
1085     struct dpif_execute execute;
1086     struct dp_packet packet;
1087     size_t start;
1088     int error;
1089
1090     /* Compose a userspace action that will cause an ERANGE error on older
1091      * datapaths that don't support variable-length userdata.
1092      *
1093      * We really test for using userdata longer than 8 bytes, but older
1094      * datapaths accepted these, silently truncating the userdata to 8 bytes.
1095      * The same older datapaths rejected userdata shorter than 8 bytes, so we
1096      * test for that instead as a proxy for longer userdata support. */
1097     ofpbuf_init(&actions, 64);
1098     start = nl_msg_start_nested(&actions, OVS_ACTION_ATTR_USERSPACE);
1099     nl_msg_put_u32(&actions, OVS_USERSPACE_ATTR_PID,
1100                    dpif_port_get_pid(backer->dpif, ODPP_NONE, 0));
1101     nl_msg_put_unspec_zero(&actions, OVS_USERSPACE_ATTR_USERDATA, 4);
1102     nl_msg_end_nested(&actions, start);
1103
1104     /* Compose a dummy ethernet packet. */
1105     dp_packet_init(&packet, ETH_HEADER_LEN);
1106     eth = dp_packet_put_zeros(&packet, ETH_HEADER_LEN);
1107     eth->eth_type = htons(0x1234);
1108
1109     /* Execute the actions.  On older datapaths this fails with ERANGE, on
1110      * newer datapaths it succeeds. */
1111     execute.actions = actions.data;
1112     execute.actions_len = actions.size;
1113     execute.packet = &packet;
1114     execute.needs_help = false;
1115     execute.probe = true;
1116
1117     error = dpif_execute(backer->dpif, &execute);
1118
1119     dp_packet_uninit(&packet);
1120     ofpbuf_uninit(&actions);
1121
1122     switch (error) {
1123     case 0:
1124         return true;
1125
1126     case ERANGE:
1127         /* Variable-length userdata is not supported. */
1128         VLOG_WARN("%s: datapath does not support variable-length userdata "
1129                   "feature (needs Linux 3.10+ or kernel module from OVS "
1130                   "1..11+).  The NXAST_SAMPLE action will be ignored.",
1131                   dpif_name(backer->dpif));
1132         return false;
1133
1134     default:
1135         /* Something odd happened.  We're not sure whether variable-length
1136          * userdata is supported.  Default to "yes". */
1137         VLOG_WARN("%s: variable-length userdata feature probe failed (%s)",
1138                   dpif_name(backer->dpif), ovs_strerror(error));
1139         return true;
1140     }
1141 }
1142
1143 /* Tests the MPLS label stack depth supported by 'backer''s datapath.
1144  *
1145  * Returns the number of elements in a struct flow's mpls_lse field
1146  * if the datapath supports at least that many entries in an
1147  * MPLS label stack.
1148  * Otherwise returns the number of MPLS push actions supported by
1149  * the datapath. */
1150 static size_t
1151 check_max_mpls_depth(struct dpif_backer *backer)
1152 {
1153     struct flow flow;
1154     int n;
1155
1156     for (n = 0; n < FLOW_MAX_MPLS_LABELS; n++) {
1157         struct odputil_keybuf keybuf;
1158         struct ofpbuf key;
1159
1160         memset(&flow, 0, sizeof flow);
1161         flow.dl_type = htons(ETH_TYPE_MPLS);
1162         flow_set_mpls_bos(&flow, n, 1);
1163
1164         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
1165         odp_flow_key_from_flow(&key, &flow, NULL, 0, false);
1166 #ifdef _WIN32
1167         /* XXX Force disable of datapath recirculation from userspace until the
1168          * dpif_probe_feature is properly implemented in the windows datapath */
1169         break;
1170 #endif
1171         if (!dpif_probe_feature(backer->dpif, "MPLS", &key, NULL)) {
1172             break;
1173         }
1174     }
1175
1176     VLOG_INFO("%s: MPLS label stack length probed as %d",
1177               dpif_name(backer->dpif), n);
1178     return n;
1179 }
1180
1181 /* Tests whether 'backer''s datapath supports masked data in
1182  * OVS_ACTION_ATTR_SET actions.  We need to disable some features on older
1183  * datapaths that don't support this feature. */
1184 static bool
1185 check_masked_set_action(struct dpif_backer *backer)
1186 {
1187     struct eth_header *eth;
1188     struct ofpbuf actions;
1189     struct dpif_execute execute;
1190     struct dp_packet packet;
1191     int error;
1192     struct ovs_key_ethernet key, mask;
1193
1194     /* Compose a set action that will cause an EINVAL error on older
1195      * datapaths that don't support masked set actions.
1196      * Avoid using a full mask, as it could be translated to a non-masked
1197      * set action instead. */
1198     ofpbuf_init(&actions, 64);
1199     memset(&key, 0x53, sizeof key);
1200     memset(&mask, 0x7f, sizeof mask);
1201     commit_masked_set_action(&actions, OVS_KEY_ATTR_ETHERNET, &key, &mask,
1202                              sizeof key);
1203
1204     /* Compose a dummy ethernet packet. */
1205     dp_packet_init(&packet, ETH_HEADER_LEN);
1206     eth = dp_packet_put_zeros(&packet, ETH_HEADER_LEN);
1207     eth->eth_type = htons(0x1234);
1208
1209     /* Execute the actions.  On older datapaths this fails with EINVAL, on
1210      * newer datapaths it succeeds. */
1211     execute.actions = actions.data;
1212     execute.actions_len = actions.size;
1213     execute.packet = &packet;
1214     execute.needs_help = false;
1215     execute.probe = true;
1216
1217     error = dpif_execute(backer->dpif, &execute);
1218
1219     dp_packet_uninit(&packet);
1220     ofpbuf_uninit(&actions);
1221
1222     if (error) {
1223         /* Masked set action is not supported. */
1224         VLOG_INFO("%s: datapath does not support masked set action feature.",
1225                   dpif_name(backer->dpif));
1226     }
1227     return !error;
1228 }
1229
1230 static void
1231 check_support(struct dpif_backer *backer)
1232 {
1233     /* This feature needs to be tested after udpif threads are set. */
1234     backer->support.variable_length_userdata = false;
1235
1236     backer->support.recirc = check_recirc(backer);
1237     backer->support.max_mpls_depth = check_max_mpls_depth(backer);
1238     backer->support.masked_set_action = check_masked_set_action(backer);
1239     backer->support.ufid = check_ufid(backer);
1240     backer->support.tnl_push_pop = dpif_supports_tnl_push_pop(backer->dpif);
1241 }
1242
1243 static int
1244 construct(struct ofproto *ofproto_)
1245 {
1246     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1247     struct shash_node *node, *next;
1248     int error;
1249
1250     /* Tunnel module can get used right after the udpif threads are running. */
1251     ofproto_tunnel_init();
1252
1253     error = open_dpif_backer(ofproto->up.type, &ofproto->backer);
1254     if (error) {
1255         return error;
1256     }
1257
1258     atomic_init(&ofproto->tables_version, CLS_MIN_VERSION);
1259     ofproto->netflow = NULL;
1260     ofproto->sflow = NULL;
1261     ofproto->ipfix = NULL;
1262     ofproto->stp = NULL;
1263     ofproto->rstp = NULL;
1264     ofproto->dump_seq = 0;
1265     hmap_init(&ofproto->bundles);
1266     ofproto->ml = mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME);
1267     ofproto->ms = NULL;
1268     ofproto->mbridge = mbridge_create();
1269     ofproto->has_bonded_bundles = false;
1270     ofproto->lacp_enabled = false;
1271     ovs_mutex_init_adaptive(&ofproto->stats_mutex);
1272     ovs_mutex_init(&ofproto->vsp_mutex);
1273
1274     guarded_list_init(&ofproto->pins);
1275
1276     ofproto_unixctl_init();
1277
1278     hmap_init(&ofproto->vlandev_map);
1279     hmap_init(&ofproto->realdev_vid_map);
1280
1281     sset_init(&ofproto->ports);
1282     sset_init(&ofproto->ghost_ports);
1283     sset_init(&ofproto->port_poll_set);
1284     ofproto->port_poll_errno = 0;
1285     ofproto->change_seq = 0;
1286     ofproto->pins_seq = seq_create();
1287     ofproto->pins_seqno = seq_read(ofproto->pins_seq);
1288
1289
1290     SHASH_FOR_EACH_SAFE (node, next, &init_ofp_ports) {
1291         struct iface_hint *iface_hint = node->data;
1292
1293         if (!strcmp(iface_hint->br_name, ofproto->up.name)) {
1294             /* Check if the datapath already has this port. */
1295             if (dpif_port_exists(ofproto->backer->dpif, node->name)) {
1296                 sset_add(&ofproto->ports, node->name);
1297             }
1298
1299             free(iface_hint->br_name);
1300             free(iface_hint->br_type);
1301             free(iface_hint);
1302             shash_delete(&init_ofp_ports, node);
1303         }
1304     }
1305
1306     hmap_insert(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node,
1307                 hash_string(ofproto->up.name, 0));
1308     memset(&ofproto->stats, 0, sizeof ofproto->stats);
1309
1310     ofproto_init_tables(ofproto_, N_TABLES);
1311     error = add_internal_flows(ofproto);
1312
1313     ofproto->up.tables[TBL_INTERNAL].flags = OFTABLE_HIDDEN | OFTABLE_READONLY;
1314
1315     return error;
1316 }
1317
1318 static int
1319 add_internal_miss_flow(struct ofproto_dpif *ofproto, int id,
1320                   const struct ofpbuf *ofpacts, struct rule_dpif **rulep)
1321 {
1322     struct match match;
1323     int error;
1324     struct rule *rule;
1325
1326     match_init_catchall(&match);
1327     match_set_reg(&match, 0, id);
1328
1329     error = ofproto_dpif_add_internal_flow(ofproto, &match, 0, 0, ofpacts,
1330                                            &rule);
1331     *rulep = error ? NULL : rule_dpif_cast(rule);
1332
1333     return error;
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     struct rule *unused_rulep OVS_UNUSED;
1343     struct match match;
1344     int error;
1345     int id;
1346
1347     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
1348     id = 1;
1349
1350     controller = ofpact_put_CONTROLLER(&ofpacts);
1351     controller->max_len = UINT16_MAX;
1352     controller->controller_id = 0;
1353     controller->reason = OFPR_NO_MATCH;
1354     ofpact_pad(&ofpacts);
1355
1356     error = add_internal_miss_flow(ofproto, id++, &ofpacts,
1357                                    &ofproto->miss_rule);
1358     if (error) {
1359         return error;
1360     }
1361
1362     ofpbuf_clear(&ofpacts);
1363     error = add_internal_miss_flow(ofproto, id++, &ofpacts,
1364                                    &ofproto->no_packet_in_rule);
1365     if (error) {
1366         return error;
1367     }
1368
1369     error = add_internal_miss_flow(ofproto, id++, &ofpacts,
1370                                    &ofproto->drop_frags_rule);
1371     if (error) {
1372         return error;
1373     }
1374
1375     /* Drop any run away non-recirc rule lookups. Recirc_id has to be
1376      * zero when reaching this rule.
1377      *
1378      * (priority=2), recirc_id=0, actions=drop
1379      */
1380     ofpbuf_clear(&ofpacts);
1381     match_init_catchall(&match);
1382     match_set_recirc_id(&match, 0);
1383     error = ofproto_dpif_add_internal_flow(ofproto, &match, 2, 0, &ofpacts,
1384                                            &unused_rulep);
1385     return error;
1386 }
1387
1388 static void
1389 destruct(struct ofproto *ofproto_)
1390 {
1391     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1392     struct ofproto_packet_in *pin;
1393     struct rule_dpif *rule;
1394     struct oftable *table;
1395     struct ovs_list pins;
1396
1397     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1398     xlate_txn_start();
1399     xlate_remove_ofproto(ofproto);
1400     xlate_txn_commit();
1401
1402     /* Ensure that the upcall processing threads have no remaining references
1403      * to the ofproto or anything in it. */
1404     udpif_synchronize(ofproto->backer->udpif);
1405
1406     hmap_remove(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node);
1407
1408     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
1409         CLS_FOR_EACH (rule, up.cr, &table->cls) {
1410             ofproto_rule_delete(&ofproto->up, &rule->up);
1411         }
1412     }
1413     ofproto_group_delete_all(&ofproto->up);
1414
1415     guarded_list_pop_all(&ofproto->pins, &pins);
1416     LIST_FOR_EACH_POP (pin, list_node, &pins) {
1417         free(CONST_CAST(void *, pin->up.packet));
1418         free(pin);
1419     }
1420     guarded_list_destroy(&ofproto->pins);
1421
1422     recirc_free_ofproto(ofproto, ofproto->up.name);
1423
1424     mbridge_unref(ofproto->mbridge);
1425
1426     netflow_unref(ofproto->netflow);
1427     dpif_sflow_unref(ofproto->sflow);
1428     dpif_ipfix_unref(ofproto->ipfix);
1429     hmap_destroy(&ofproto->bundles);
1430     mac_learning_unref(ofproto->ml);
1431     mcast_snooping_unref(ofproto->ms);
1432
1433     hmap_destroy(&ofproto->vlandev_map);
1434     hmap_destroy(&ofproto->realdev_vid_map);
1435
1436     sset_destroy(&ofproto->ports);
1437     sset_destroy(&ofproto->ghost_ports);
1438     sset_destroy(&ofproto->port_poll_set);
1439
1440     ovs_mutex_destroy(&ofproto->stats_mutex);
1441     ovs_mutex_destroy(&ofproto->vsp_mutex);
1442
1443     seq_destroy(ofproto->pins_seq);
1444
1445     close_dpif_backer(ofproto->backer);
1446 }
1447
1448 static int
1449 run(struct ofproto *ofproto_)
1450 {
1451     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1452     uint64_t new_seq, new_dump_seq;
1453
1454     if (mbridge_need_revalidate(ofproto->mbridge)) {
1455         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1456         ovs_rwlock_wrlock(&ofproto->ml->rwlock);
1457         mac_learning_flush(ofproto->ml);
1458         ovs_rwlock_unlock(&ofproto->ml->rwlock);
1459         mcast_snooping_mdb_flush(ofproto->ms);
1460     }
1461
1462     /* Always updates the ofproto->pins_seqno to avoid frequent wakeup during
1463      * flow restore.  Even though nothing is processed during flow restore,
1464      * all queued 'pins' will be handled immediately when flow restore
1465      * completes. */
1466     ofproto->pins_seqno = seq_read(ofproto->pins_seq);
1467
1468     /* Do not perform any periodic activity required by 'ofproto' while
1469      * waiting for flow restore to complete. */
1470     if (!ofproto_get_flow_restore_wait()) {
1471         struct ofproto_packet_in *pin;
1472         struct ovs_list pins;
1473
1474         guarded_list_pop_all(&ofproto->pins, &pins);
1475         LIST_FOR_EACH_POP (pin, list_node, &pins) {
1476             connmgr_send_packet_in(ofproto->up.connmgr, pin);
1477             free(CONST_CAST(void *, pin->up.packet));
1478             free(pin);
1479         }
1480     }
1481
1482     if (ofproto->netflow) {
1483         netflow_run(ofproto->netflow);
1484     }
1485     if (ofproto->sflow) {
1486         dpif_sflow_run(ofproto->sflow);
1487     }
1488     if (ofproto->ipfix) {
1489         dpif_ipfix_run(ofproto->ipfix);
1490     }
1491
1492     new_seq = seq_read(connectivity_seq_get());
1493     if (ofproto->change_seq != new_seq) {
1494         struct ofport_dpif *ofport;
1495
1496         HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1497             port_run(ofport);
1498         }
1499
1500         ofproto->change_seq = new_seq;
1501     }
1502     if (ofproto->lacp_enabled || ofproto->has_bonded_bundles) {
1503         struct ofbundle *bundle;
1504
1505         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1506             bundle_run(bundle);
1507         }
1508     }
1509
1510     stp_run(ofproto);
1511     rstp_run(ofproto);
1512     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
1513     if (mac_learning_run(ofproto->ml)) {
1514         ofproto->backer->need_revalidate = REV_MAC_LEARNING;
1515     }
1516     ovs_rwlock_unlock(&ofproto->ml->rwlock);
1517
1518     if (mcast_snooping_run(ofproto->ms)) {
1519         ofproto->backer->need_revalidate = REV_MCAST_SNOOPING;
1520     }
1521
1522     new_dump_seq = seq_read(udpif_dump_seq(ofproto->backer->udpif));
1523     if (ofproto->dump_seq != new_dump_seq) {
1524         struct rule *rule, *next_rule;
1525
1526         /* We know stats are relatively fresh, so now is a good time to do some
1527          * periodic work. */
1528         ofproto->dump_seq = new_dump_seq;
1529
1530         /* Expire OpenFlow flows whose idle_timeout or hard_timeout
1531          * has passed. */
1532         ovs_mutex_lock(&ofproto_mutex);
1533         LIST_FOR_EACH_SAFE (rule, next_rule, expirable,
1534                             &ofproto->up.expirable) {
1535             rule_expire(rule_dpif_cast(rule));
1536         }
1537         ovs_mutex_unlock(&ofproto_mutex);
1538
1539         /* All outstanding data in existing flows has been accounted, so it's a
1540          * good time to do bond rebalancing. */
1541         if (ofproto->has_bonded_bundles) {
1542             struct ofbundle *bundle;
1543
1544             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1545                 if (bundle->bond) {
1546                     bond_rebalance(bundle->bond);
1547                 }
1548             }
1549         }
1550     }
1551     return 0;
1552 }
1553
1554 static void
1555 wait(struct ofproto *ofproto_)
1556 {
1557     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1558
1559     if (ofproto_get_flow_restore_wait()) {
1560         return;
1561     }
1562
1563     if (ofproto->sflow) {
1564         dpif_sflow_wait(ofproto->sflow);
1565     }
1566     if (ofproto->ipfix) {
1567         dpif_ipfix_wait(ofproto->ipfix);
1568     }
1569     if (ofproto->lacp_enabled || ofproto->has_bonded_bundles) {
1570         struct ofbundle *bundle;
1571
1572         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1573             bundle_wait(bundle);
1574         }
1575     }
1576     if (ofproto->netflow) {
1577         netflow_wait(ofproto->netflow);
1578     }
1579     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
1580     mac_learning_wait(ofproto->ml);
1581     ovs_rwlock_unlock(&ofproto->ml->rwlock);
1582     mcast_snooping_wait(ofproto->ms);
1583     stp_wait(ofproto);
1584     if (ofproto->backer->need_revalidate) {
1585         /* Shouldn't happen, but if it does just go around again. */
1586         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1587         poll_immediate_wake();
1588     }
1589
1590     seq_wait(udpif_dump_seq(ofproto->backer->udpif), ofproto->dump_seq);
1591     seq_wait(ofproto->pins_seq, ofproto->pins_seqno);
1592 }
1593
1594 static void
1595 type_get_memory_usage(const char *type, struct simap *usage)
1596 {
1597     struct dpif_backer *backer;
1598
1599     backer = shash_find_data(&all_dpif_backers, type);
1600     if (backer) {
1601         udpif_get_memory_usage(backer->udpif, usage);
1602     }
1603 }
1604
1605 static void
1606 flush(struct ofproto *ofproto_)
1607 {
1608     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1609     struct dpif_backer *backer = ofproto->backer;
1610
1611     if (backer) {
1612         udpif_flush(backer->udpif);
1613     }
1614 }
1615
1616 static void
1617 query_tables(struct ofproto *ofproto,
1618              struct ofputil_table_features *features,
1619              struct ofputil_table_stats *stats)
1620 {
1621     strcpy(features->name, "classifier");
1622
1623     if (stats) {
1624         int i;
1625
1626         for (i = 0; i < ofproto->n_tables; i++) {
1627             unsigned long missed, matched;
1628
1629             atomic_read_relaxed(&ofproto->tables[i].n_matched, &matched);
1630             atomic_read_relaxed(&ofproto->tables[i].n_missed, &missed);
1631
1632             stats[i].matched_count = matched;
1633             stats[i].lookup_count = matched + missed;
1634         }
1635     }
1636 }
1637
1638 static void
1639 set_tables_version(struct ofproto *ofproto_, cls_version_t version)
1640 {
1641     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1642
1643     atomic_store_relaxed(&ofproto->tables_version, version);
1644 }
1645
1646
1647 static struct ofport *
1648 port_alloc(void)
1649 {
1650     struct ofport_dpif *port = xzalloc(sizeof *port);
1651     return &port->up;
1652 }
1653
1654 static void
1655 port_dealloc(struct ofport *port_)
1656 {
1657     struct ofport_dpif *port = ofport_dpif_cast(port_);
1658     free(port);
1659 }
1660
1661 static int
1662 port_construct(struct ofport *port_)
1663 {
1664     struct ofport_dpif *port = ofport_dpif_cast(port_);
1665     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1666     const struct netdev *netdev = port->up.netdev;
1667     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1668     const char *dp_port_name;
1669     struct dpif_port dpif_port;
1670     int error;
1671
1672     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1673     port->bundle = NULL;
1674     port->cfm = NULL;
1675     port->bfd = NULL;
1676     port->lldp = NULL;
1677     port->may_enable = false;
1678     port->stp_port = NULL;
1679     port->stp_state = STP_DISABLED;
1680     port->rstp_port = NULL;
1681     port->rstp_state = RSTP_DISABLED;
1682     port->is_tunnel = false;
1683     port->peer = NULL;
1684     port->qdscp = NULL;
1685     port->n_qdscp = 0;
1686     port->realdev_ofp_port = 0;
1687     port->vlandev_vid = 0;
1688     port->carrier_seq = netdev_get_carrier_resets(netdev);
1689     port->is_layer3 = netdev_vport_is_layer3(netdev);
1690
1691     if (netdev_vport_is_patch(netdev)) {
1692         /* By bailing out here, we don't submit the port to the sFlow module
1693          * to be considered for counter polling export.  This is correct
1694          * because the patch port represents an interface that sFlow considers
1695          * to be "internal" to the switch as a whole, and therefore not a
1696          * candidate for counter polling. */
1697         port->odp_port = ODPP_NONE;
1698         ofport_update_peer(port);
1699         return 0;
1700     }
1701
1702     dp_port_name = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
1703     error = dpif_port_query_by_name(ofproto->backer->dpif, dp_port_name,
1704                                     &dpif_port);
1705     if (error) {
1706         return error;
1707     }
1708
1709     port->odp_port = dpif_port.port_no;
1710
1711     if (netdev_get_tunnel_config(netdev)) {
1712         atomic_count_inc(&ofproto->backer->tnl_count);
1713         error = tnl_port_add(port, port->up.netdev, port->odp_port,
1714                              ovs_native_tunneling_is_on(ofproto), dp_port_name);
1715         if (error) {
1716             atomic_count_dec(&ofproto->backer->tnl_count);
1717             dpif_port_destroy(&dpif_port);
1718             return error;
1719         }
1720
1721         port->is_tunnel = true;
1722         if (ofproto->ipfix) {
1723            dpif_ipfix_add_tunnel_port(ofproto->ipfix, port_, port->odp_port);
1724         }
1725     } else {
1726         /* Sanity-check that a mapping doesn't already exist.  This
1727          * shouldn't happen for non-tunnel ports. */
1728         if (odp_port_to_ofp_port(ofproto, port->odp_port) != OFPP_NONE) {
1729             VLOG_ERR("port %s already has an OpenFlow port number",
1730                      dpif_port.name);
1731             dpif_port_destroy(&dpif_port);
1732             return EBUSY;
1733         }
1734
1735         ovs_rwlock_wrlock(&ofproto->backer->odp_to_ofport_lock);
1736         hmap_insert(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node,
1737                     hash_odp_port(port->odp_port));
1738         ovs_rwlock_unlock(&ofproto->backer->odp_to_ofport_lock);
1739     }
1740     dpif_port_destroy(&dpif_port);
1741
1742     if (ofproto->sflow) {
1743         dpif_sflow_add_port(ofproto->sflow, port_, port->odp_port);
1744     }
1745
1746     return 0;
1747 }
1748
1749 static void
1750 port_destruct(struct ofport *port_)
1751 {
1752     struct ofport_dpif *port = ofport_dpif_cast(port_);
1753     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1754     const char *devname = netdev_get_name(port->up.netdev);
1755     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1756     const char *dp_port_name;
1757
1758     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1759     xlate_txn_start();
1760     xlate_ofport_remove(port);
1761     xlate_txn_commit();
1762
1763     dp_port_name = netdev_vport_get_dpif_port(port->up.netdev, namebuf,
1764                                               sizeof namebuf);
1765     if (dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
1766         /* The underlying device is still there, so delete it.  This
1767          * happens when the ofproto is being destroyed, since the caller
1768          * assumes that removal of attached ports will happen as part of
1769          * destruction. */
1770         if (!port->is_tunnel) {
1771             dpif_port_del(ofproto->backer->dpif, port->odp_port);
1772         }
1773     }
1774
1775     if (port->peer) {
1776         port->peer->peer = NULL;
1777         port->peer = NULL;
1778     }
1779
1780     if (port->odp_port != ODPP_NONE && !port->is_tunnel) {
1781         ovs_rwlock_wrlock(&ofproto->backer->odp_to_ofport_lock);
1782         hmap_remove(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node);
1783         ovs_rwlock_unlock(&ofproto->backer->odp_to_ofport_lock);
1784     }
1785
1786     if (port->is_tunnel) {
1787         atomic_count_dec(&ofproto->backer->tnl_count);
1788     }
1789
1790     if (port->is_tunnel && ofproto->ipfix) {
1791        dpif_ipfix_del_tunnel_port(ofproto->ipfix, port->odp_port);
1792     }
1793
1794     tnl_port_del(port);
1795     sset_find_and_delete(&ofproto->ports, devname);
1796     sset_find_and_delete(&ofproto->ghost_ports, devname);
1797     bundle_remove(port_);
1798     set_cfm(port_, NULL);
1799     set_bfd(port_, NULL);
1800     set_lldp(port_, NULL);
1801     if (port->stp_port) {
1802         stp_port_disable(port->stp_port);
1803     }
1804     set_rstp_port(port_, NULL);
1805     if (ofproto->sflow) {
1806         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
1807     }
1808
1809     free(port->qdscp);
1810 }
1811
1812 static void
1813 port_modified(struct ofport *port_)
1814 {
1815     struct ofport_dpif *port = ofport_dpif_cast(port_);
1816     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1817     const char *dp_port_name;
1818     struct netdev *netdev = port->up.netdev;
1819
1820     if (port->bundle && port->bundle->bond) {
1821         bond_slave_set_netdev(port->bundle->bond, port, netdev);
1822     }
1823
1824     if (port->cfm) {
1825         cfm_set_netdev(port->cfm, netdev);
1826     }
1827
1828     if (port->bfd) {
1829         bfd_set_netdev(port->bfd, netdev);
1830     }
1831
1832     ofproto_dpif_monitor_port_update(port, port->bfd, port->cfm,
1833                                      port->lldp, port->up.pp.hw_addr);
1834
1835     dp_port_name = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
1836
1837     if (port->is_tunnel) {
1838         struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1839
1840         if (tnl_port_reconfigure(port, netdev, port->odp_port,
1841                                  ovs_native_tunneling_is_on(ofproto),
1842                                  dp_port_name)) {
1843             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1844         }
1845     }
1846
1847     ofport_update_peer(port);
1848 }
1849
1850 static void
1851 port_reconfigured(struct ofport *port_, enum ofputil_port_config old_config)
1852 {
1853     struct ofport_dpif *port = ofport_dpif_cast(port_);
1854     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1855     enum ofputil_port_config changed = old_config ^ port->up.pp.config;
1856
1857     if (changed & (OFPUTIL_PC_NO_RECV | OFPUTIL_PC_NO_RECV_STP |
1858                    OFPUTIL_PC_NO_FWD | OFPUTIL_PC_NO_FLOOD |
1859                    OFPUTIL_PC_NO_PACKET_IN)) {
1860         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1861
1862         if (changed & OFPUTIL_PC_NO_FLOOD && port->bundle) {
1863             bundle_update(port->bundle);
1864         }
1865     }
1866 }
1867
1868 static int
1869 set_sflow(struct ofproto *ofproto_,
1870           const struct ofproto_sflow_options *sflow_options)
1871 {
1872     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1873     struct dpif_sflow *ds = ofproto->sflow;
1874
1875     if (sflow_options) {
1876         uint32_t old_probability = ds ? dpif_sflow_get_probability(ds) : 0;
1877         if (!ds) {
1878             struct ofport_dpif *ofport;
1879
1880             ds = ofproto->sflow = dpif_sflow_create();
1881             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1882                 dpif_sflow_add_port(ds, &ofport->up, ofport->odp_port);
1883             }
1884         }
1885         dpif_sflow_set_options(ds, sflow_options);
1886         if (dpif_sflow_get_probability(ds) != old_probability) {
1887             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1888         }
1889     } else {
1890         if (ds) {
1891             dpif_sflow_unref(ds);
1892             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1893             ofproto->sflow = NULL;
1894         }
1895     }
1896     return 0;
1897 }
1898
1899 static int
1900 set_ipfix(
1901     struct ofproto *ofproto_,
1902     const struct ofproto_ipfix_bridge_exporter_options *bridge_exporter_options,
1903     const struct ofproto_ipfix_flow_exporter_options *flow_exporters_options,
1904     size_t n_flow_exporters_options)
1905 {
1906     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1907     struct dpif_ipfix *di = ofproto->ipfix;
1908     bool has_options = bridge_exporter_options || flow_exporters_options;
1909     bool new_di = false;
1910
1911     if (has_options && !di) {
1912         di = ofproto->ipfix = dpif_ipfix_create();
1913         new_di = true;
1914     }
1915
1916     if (di) {
1917         /* Call set_options in any case to cleanly flush the flow
1918          * caches in the last exporters that are to be destroyed. */
1919         dpif_ipfix_set_options(
1920             di, bridge_exporter_options, flow_exporters_options,
1921             n_flow_exporters_options);
1922
1923         /* Add tunnel ports only when a new ipfix created */
1924         if (new_di == true) {
1925             struct ofport_dpif *ofport;
1926             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1927                 if (ofport->is_tunnel == true) {
1928                     dpif_ipfix_add_tunnel_port(di, &ofport->up, ofport->odp_port);
1929                 }
1930             }
1931         }
1932
1933         if (!has_options) {
1934             dpif_ipfix_unref(di);
1935             ofproto->ipfix = NULL;
1936         }
1937     }
1938
1939     return 0;
1940 }
1941
1942 static int
1943 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
1944 {
1945     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1946     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1947     struct cfm *old = ofport->cfm;
1948     int error = 0;
1949
1950     if (s) {
1951         if (!ofport->cfm) {
1952             ofport->cfm = cfm_create(ofport->up.netdev);
1953         }
1954
1955         if (cfm_configure(ofport->cfm, s)) {
1956             error = 0;
1957             goto out;
1958         }
1959
1960         error = EINVAL;
1961     }
1962     cfm_unref(ofport->cfm);
1963     ofport->cfm = NULL;
1964 out:
1965     if (ofport->cfm != old) {
1966         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1967     }
1968     ofproto_dpif_monitor_port_update(ofport, ofport->bfd, ofport->cfm,
1969                                      ofport->lldp, ofport->up.pp.hw_addr);
1970     return error;
1971 }
1972
1973 static bool
1974 cfm_status_changed(struct ofport *ofport_)
1975 {
1976     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1977
1978     return ofport->cfm ? cfm_check_status_change(ofport->cfm) : true;
1979 }
1980
1981 static int
1982 get_cfm_status(const struct ofport *ofport_,
1983                struct cfm_status *status)
1984 {
1985     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1986     int ret = 0;
1987
1988     if (ofport->cfm) {
1989         cfm_get_status(ofport->cfm, status);
1990     } else {
1991         ret = ENOENT;
1992     }
1993
1994     return ret;
1995 }
1996
1997 static int
1998 set_bfd(struct ofport *ofport_, const struct smap *cfg)
1999 {
2000     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
2001     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2002     struct bfd *old;
2003
2004     old = ofport->bfd;
2005     ofport->bfd = bfd_configure(old, netdev_get_name(ofport->up.netdev),
2006                                 cfg, ofport->up.netdev);
2007     if (ofport->bfd != old) {
2008         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2009     }
2010     ofproto_dpif_monitor_port_update(ofport, ofport->bfd, ofport->cfm,
2011                                      ofport->lldp, ofport->up.pp.hw_addr);
2012     return 0;
2013 }
2014
2015 static bool
2016 bfd_status_changed(struct ofport *ofport_)
2017 {
2018     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2019
2020     return ofport->bfd ? bfd_check_status_change(ofport->bfd) : true;
2021 }
2022
2023 static int
2024 get_bfd_status(struct ofport *ofport_, struct smap *smap)
2025 {
2026     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2027     int ret = 0;
2028
2029     if (ofport->bfd) {
2030         bfd_get_status(ofport->bfd, smap);
2031     } else {
2032         ret = ENOENT;
2033     }
2034
2035     return ret;
2036 }
2037
2038 static int
2039 set_lldp(struct ofport *ofport_,
2040          const struct smap *cfg)
2041 {
2042     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2043     int error = 0;
2044
2045     if (cfg) {
2046         if (!ofport->lldp) {
2047             struct ofproto_dpif *ofproto;
2048
2049             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2050             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2051             ofport->lldp = lldp_create(ofport->up.netdev, ofport_->mtu, cfg);
2052         }
2053
2054         if (!lldp_configure(ofport->lldp, cfg)) {
2055             error = EINVAL;
2056         }
2057     }
2058     if (error) {
2059         lldp_unref(ofport->lldp);
2060         ofport->lldp = NULL;
2061     }
2062
2063     ofproto_dpif_monitor_port_update(ofport,
2064                                      ofport->bfd,
2065                                      ofport->cfm,
2066                                      ofport->lldp,
2067                                      ofport->up.pp.hw_addr);
2068     return error;
2069 }
2070
2071 static bool
2072 get_lldp_status(const struct ofport *ofport_,
2073                struct lldp_status *status OVS_UNUSED)
2074 {
2075     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2076
2077     return ofport->lldp ? true : false;
2078 }
2079
2080 static int
2081 set_aa(struct ofproto *ofproto OVS_UNUSED,
2082        const struct aa_settings *s)
2083 {
2084     return aa_configure(s);
2085 }
2086
2087 static int
2088 aa_mapping_set(struct ofproto *ofproto_ OVS_UNUSED, void *aux,
2089                const struct aa_mapping_settings *s)
2090 {
2091     return aa_mapping_register(aux, s);
2092 }
2093
2094 static int
2095 aa_mapping_unset(struct ofproto *ofproto OVS_UNUSED, void *aux)
2096 {
2097     return aa_mapping_unregister(aux);
2098 }
2099
2100 static int
2101 aa_vlan_get_queued(struct ofproto *ofproto OVS_UNUSED, struct ovs_list *list)
2102 {
2103     return aa_get_vlan_queued(list);
2104 }
2105
2106 static unsigned int
2107 aa_vlan_get_queue_size(struct ofproto *ofproto OVS_UNUSED)
2108 {
2109     return aa_get_vlan_queue_size();
2110 }
2111
2112 \f
2113 /* Spanning Tree. */
2114
2115 /* Called while rstp_mutex is held. */
2116 static void
2117 rstp_send_bpdu_cb(struct dp_packet *pkt, void *ofport_, void *ofproto_)
2118 {
2119     struct ofproto_dpif *ofproto = ofproto_;
2120     struct ofport_dpif *ofport = ofport_;
2121     struct eth_header *eth = dp_packet_l2(pkt);
2122
2123     netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
2124     if (eth_addr_is_zero(eth->eth_src)) {
2125         VLOG_WARN_RL(&rl, "%s port %d: cannot send RSTP BPDU on a port which "
2126                      "does not have a configured source MAC address.",
2127                      ofproto->up.name, ofp_to_u16(ofport->up.ofp_port));
2128     } else {
2129         ofproto_dpif_send_packet(ofport, pkt);
2130     }
2131     dp_packet_delete(pkt);
2132 }
2133
2134 static void
2135 send_bpdu_cb(struct dp_packet *pkt, int port_num, void *ofproto_)
2136 {
2137     struct ofproto_dpif *ofproto = ofproto_;
2138     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
2139     struct ofport_dpif *ofport;
2140
2141     ofport = stp_port_get_aux(sp);
2142     if (!ofport) {
2143         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
2144                      ofproto->up.name, port_num);
2145     } else {
2146         struct eth_header *eth = dp_packet_l2(pkt);
2147
2148         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
2149         if (eth_addr_is_zero(eth->eth_src)) {
2150             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
2151                          "with unknown MAC", ofproto->up.name, port_num);
2152         } else {
2153             ofproto_dpif_send_packet(ofport, pkt);
2154         }
2155     }
2156     dp_packet_delete(pkt);
2157 }
2158
2159 /* Configure RSTP on 'ofproto_' using the settings defined in 's'. */
2160 static void
2161 set_rstp(struct ofproto *ofproto_, const struct ofproto_rstp_settings *s)
2162 {
2163     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2164
2165     /* Only revalidate flows if the configuration changed. */
2166     if (!s != !ofproto->rstp) {
2167         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2168     }
2169
2170     if (s) {
2171         if (!ofproto->rstp) {
2172             ofproto->rstp = rstp_create(ofproto_->name, s->address,
2173                                         rstp_send_bpdu_cb, ofproto);
2174             ofproto->rstp_last_tick = time_msec();
2175         }
2176         rstp_set_bridge_address(ofproto->rstp, s->address);
2177         rstp_set_bridge_priority(ofproto->rstp, s->priority);
2178         rstp_set_bridge_ageing_time(ofproto->rstp, s->ageing_time);
2179         rstp_set_bridge_force_protocol_version(ofproto->rstp,
2180                                                s->force_protocol_version);
2181         rstp_set_bridge_max_age(ofproto->rstp, s->bridge_max_age);
2182         rstp_set_bridge_forward_delay(ofproto->rstp, s->bridge_forward_delay);
2183         rstp_set_bridge_transmit_hold_count(ofproto->rstp,
2184                                             s->transmit_hold_count);
2185     } else {
2186         struct ofport *ofport;
2187         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
2188             set_rstp_port(ofport, NULL);
2189         }
2190         rstp_unref(ofproto->rstp);
2191         ofproto->rstp = NULL;
2192     }
2193 }
2194
2195 static void
2196 get_rstp_status(struct ofproto *ofproto_, struct ofproto_rstp_status *s)
2197 {
2198     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2199
2200     if (ofproto->rstp) {
2201         s->enabled = true;
2202         s->root_id = rstp_get_root_id(ofproto->rstp);
2203         s->bridge_id = rstp_get_bridge_id(ofproto->rstp);
2204         s->designated_id = rstp_get_designated_id(ofproto->rstp);
2205         s->root_path_cost = rstp_get_root_path_cost(ofproto->rstp);
2206         s->designated_port_id = rstp_get_designated_port_id(ofproto->rstp);
2207         s->bridge_port_id = rstp_get_bridge_port_id(ofproto->rstp);
2208     } else {
2209         s->enabled = false;
2210     }
2211 }
2212
2213 static void
2214 update_rstp_port_state(struct ofport_dpif *ofport)
2215 {
2216     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2217     enum rstp_state state;
2218
2219     /* Figure out new state. */
2220     state = ofport->rstp_port ? rstp_port_get_state(ofport->rstp_port)
2221         : RSTP_DISABLED;
2222
2223     /* Update state. */
2224     if (ofport->rstp_state != state) {
2225         enum ofputil_port_state of_state;
2226         bool fwd_change;
2227
2228         VLOG_DBG("port %s: RSTP state changed from %s to %s",
2229                  netdev_get_name(ofport->up.netdev),
2230                  rstp_state_name(ofport->rstp_state),
2231                  rstp_state_name(state));
2232
2233         if (rstp_learn_in_state(ofport->rstp_state)
2234             != rstp_learn_in_state(state)) {
2235             /* XXX: Learning action flows should also be flushed. */
2236             if (ofport->bundle) {
2237                 if (!rstp_shift_root_learned_address(ofproto->rstp)
2238                     || rstp_get_old_root_aux(ofproto->rstp) != ofport) {
2239                     bundle_flush_macs(ofport->bundle, false);
2240                 }
2241             }
2242         }
2243         fwd_change = rstp_forward_in_state(ofport->rstp_state)
2244             != rstp_forward_in_state(state);
2245
2246         ofproto->backer->need_revalidate = REV_RSTP;
2247         ofport->rstp_state = state;
2248
2249         if (fwd_change && ofport->bundle) {
2250             bundle_update(ofport->bundle);
2251         }
2252
2253         /* Update the RSTP state bits in the OpenFlow port description. */
2254         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
2255         of_state |= (state == RSTP_LEARNING ? OFPUTIL_PS_STP_LEARN
2256                 : state == RSTP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
2257                 : state == RSTP_DISCARDING ?  OFPUTIL_PS_STP_LISTEN
2258                 : 0);
2259         ofproto_port_set_state(&ofport->up, of_state);
2260     }
2261 }
2262
2263 static void
2264 rstp_run(struct ofproto_dpif *ofproto)
2265 {
2266     if (ofproto->rstp) {
2267         long long int now = time_msec();
2268         long long int elapsed = now - ofproto->rstp_last_tick;
2269         struct rstp_port *rp;
2270         struct ofport_dpif *ofport;
2271
2272         /* Every second, decrease the values of the timers. */
2273         if (elapsed >= 1000) {
2274             rstp_tick_timers(ofproto->rstp);
2275             ofproto->rstp_last_tick = now;
2276         }
2277         rp = NULL;
2278         while ((ofport = rstp_get_next_changed_port_aux(ofproto->rstp, &rp))) {
2279             update_rstp_port_state(ofport);
2280         }
2281         rp = NULL;
2282         ofport = NULL;
2283         /* FIXME: This check should be done on-event (i.e., when setting
2284          * p->fdb_flush) and not periodically.
2285          */
2286         while ((ofport = rstp_check_and_reset_fdb_flush(ofproto->rstp, &rp))) {
2287             if (!rstp_shift_root_learned_address(ofproto->rstp)
2288                 || rstp_get_old_root_aux(ofproto->rstp) != ofport) {
2289                 bundle_flush_macs(ofport->bundle, false);
2290             }
2291         }
2292
2293         if (rstp_shift_root_learned_address(ofproto->rstp)) {
2294             bundle_move(((struct ofport_dpif *)rstp_get_old_root_aux(ofproto->rstp))->bundle,
2295                         ((struct ofport_dpif *)rstp_get_new_root_aux(ofproto->rstp))->bundle);
2296             rstp_reset_root_changed(ofproto->rstp);
2297         }
2298     }
2299 }
2300
2301 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
2302 static int
2303 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
2304 {
2305     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2306
2307     /* Only revalidate flows if the configuration changed. */
2308     if (!s != !ofproto->stp) {
2309         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2310     }
2311
2312     if (s) {
2313         if (!ofproto->stp) {
2314             ofproto->stp = stp_create(ofproto_->name, s->system_id,
2315                                       send_bpdu_cb, ofproto);
2316             ofproto->stp_last_tick = time_msec();
2317         }
2318
2319         stp_set_bridge_id(ofproto->stp, s->system_id);
2320         stp_set_bridge_priority(ofproto->stp, s->priority);
2321         stp_set_hello_time(ofproto->stp, s->hello_time);
2322         stp_set_max_age(ofproto->stp, s->max_age);
2323         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
2324     }  else {
2325         struct ofport *ofport;
2326
2327         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
2328             set_stp_port(ofport, NULL);
2329         }
2330
2331         stp_unref(ofproto->stp);
2332         ofproto->stp = NULL;
2333     }
2334
2335     return 0;
2336 }
2337
2338 static int
2339 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
2340 {
2341     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2342
2343     if (ofproto->stp) {
2344         s->enabled = true;
2345         s->bridge_id = stp_get_bridge_id(ofproto->stp);
2346         s->designated_root = stp_get_designated_root(ofproto->stp);
2347         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
2348     } else {
2349         s->enabled = false;
2350     }
2351
2352     return 0;
2353 }
2354
2355 static void
2356 update_stp_port_state(struct ofport_dpif *ofport)
2357 {
2358     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2359     enum stp_state state;
2360
2361     /* Figure out new state. */
2362     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
2363                              : STP_DISABLED;
2364
2365     /* Update state. */
2366     if (ofport->stp_state != state) {
2367         enum ofputil_port_state of_state;
2368         bool fwd_change;
2369
2370         VLOG_DBG("port %s: STP state changed from %s to %s",
2371                  netdev_get_name(ofport->up.netdev),
2372                  stp_state_name(ofport->stp_state),
2373                  stp_state_name(state));
2374         if (stp_learn_in_state(ofport->stp_state)
2375                 != stp_learn_in_state(state)) {
2376             /* xxx Learning action flows should also be flushed. */
2377             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
2378             mac_learning_flush(ofproto->ml);
2379             ovs_rwlock_unlock(&ofproto->ml->rwlock);
2380             mcast_snooping_mdb_flush(ofproto->ms);
2381         }
2382         fwd_change = stp_forward_in_state(ofport->stp_state)
2383                         != stp_forward_in_state(state);
2384
2385         ofproto->backer->need_revalidate = REV_STP;
2386         ofport->stp_state = state;
2387         ofport->stp_state_entered = time_msec();
2388
2389         if (fwd_change && ofport->bundle) {
2390             bundle_update(ofport->bundle);
2391         }
2392
2393         /* Update the STP state bits in the OpenFlow port description. */
2394         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
2395         of_state |= (state == STP_LISTENING ? OFPUTIL_PS_STP_LISTEN
2396                      : state == STP_LEARNING ? OFPUTIL_PS_STP_LEARN
2397                      : state == STP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
2398                      : state == STP_BLOCKING ?  OFPUTIL_PS_STP_BLOCK
2399                      : 0);
2400         ofproto_port_set_state(&ofport->up, of_state);
2401     }
2402 }
2403
2404 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
2405  * caller is responsible for assigning STP port numbers and ensuring
2406  * there are no duplicates. */
2407 static int
2408 set_stp_port(struct ofport *ofport_,
2409              const struct ofproto_port_stp_settings *s)
2410 {
2411     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2412     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2413     struct stp_port *sp = ofport->stp_port;
2414
2415     if (!s || !s->enable) {
2416         if (sp) {
2417             ofport->stp_port = NULL;
2418             stp_port_disable(sp);
2419             update_stp_port_state(ofport);
2420         }
2421         return 0;
2422     } else if (sp && stp_port_no(sp) != s->port_num
2423                && ofport == stp_port_get_aux(sp)) {
2424         /* The port-id changed, so disable the old one if it's not
2425          * already in use by another port. */
2426         stp_port_disable(sp);
2427     }
2428
2429     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
2430
2431     /* Set name before enabling the port so that debugging messages can print
2432      * the name. */
2433     stp_port_set_name(sp, netdev_get_name(ofport->up.netdev));
2434     stp_port_enable(sp);
2435
2436     stp_port_set_aux(sp, ofport);
2437     stp_port_set_priority(sp, s->priority);
2438     stp_port_set_path_cost(sp, s->path_cost);
2439
2440     update_stp_port_state(ofport);
2441
2442     return 0;
2443 }
2444
2445 static int
2446 get_stp_port_status(struct ofport *ofport_,
2447                     struct ofproto_port_stp_status *s)
2448 {
2449     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2450     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2451     struct stp_port *sp = ofport->stp_port;
2452
2453     if (!ofproto->stp || !sp) {
2454         s->enabled = false;
2455         return 0;
2456     }
2457
2458     s->enabled = true;
2459     s->port_id = stp_port_get_id(sp);
2460     s->state = stp_port_get_state(sp);
2461     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
2462     s->role = stp_port_get_role(sp);
2463
2464     return 0;
2465 }
2466
2467 static int
2468 get_stp_port_stats(struct ofport *ofport_,
2469                    struct ofproto_port_stp_stats *s)
2470 {
2471     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2472     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2473     struct stp_port *sp = ofport->stp_port;
2474
2475     if (!ofproto->stp || !sp) {
2476         s->enabled = false;
2477         return 0;
2478     }
2479
2480     s->enabled = true;
2481     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
2482
2483     return 0;
2484 }
2485
2486 static void
2487 stp_run(struct ofproto_dpif *ofproto)
2488 {
2489     if (ofproto->stp) {
2490         long long int now = time_msec();
2491         long long int elapsed = now - ofproto->stp_last_tick;
2492         struct stp_port *sp;
2493
2494         if (elapsed > 0) {
2495             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
2496             ofproto->stp_last_tick = now;
2497         }
2498         while (stp_get_changed_port(ofproto->stp, &sp)) {
2499             struct ofport_dpif *ofport = stp_port_get_aux(sp);
2500
2501             if (ofport) {
2502                 update_stp_port_state(ofport);
2503             }
2504         }
2505
2506         if (stp_check_and_reset_fdb_flush(ofproto->stp)) {
2507             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
2508             mac_learning_flush(ofproto->ml);
2509             ovs_rwlock_unlock(&ofproto->ml->rwlock);
2510             mcast_snooping_mdb_flush(ofproto->ms);
2511         }
2512     }
2513 }
2514
2515 static void
2516 stp_wait(struct ofproto_dpif *ofproto)
2517 {
2518     if (ofproto->stp) {
2519         poll_timer_wait(1000);
2520     }
2521 }
2522
2523 /* Configures RSTP on 'ofport_' using the settings defined in 's'.  The
2524  * caller is responsible for assigning RSTP port numbers and ensuring
2525  * there are no duplicates. */
2526 static void
2527 set_rstp_port(struct ofport *ofport_,
2528               const struct ofproto_port_rstp_settings *s)
2529 {
2530     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2531     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2532     struct rstp_port *rp = ofport->rstp_port;
2533
2534     if (!s || !s->enable) {
2535         if (rp) {
2536             rstp_port_unref(rp);
2537             ofport->rstp_port = NULL;
2538             update_rstp_port_state(ofport);
2539         }
2540         return;
2541     }
2542
2543     /* Check if need to add a new port. */
2544     if (!rp) {
2545         rp = ofport->rstp_port = rstp_add_port(ofproto->rstp);
2546     }
2547
2548     rstp_port_set(rp, s->port_num, s->priority, s->path_cost,
2549                   s->admin_edge_port, s->auto_edge,
2550                   s->admin_p2p_mac_state, s->admin_port_state, s->mcheck,
2551                   ofport);
2552     update_rstp_port_state(ofport);
2553     /* Synchronize operational status. */
2554     rstp_port_set_mac_operational(rp, ofport->may_enable);
2555 }
2556
2557 static void
2558 get_rstp_port_status(struct ofport *ofport_,
2559         struct ofproto_port_rstp_status *s)
2560 {
2561     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2562     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2563     struct rstp_port *rp = ofport->rstp_port;
2564
2565     if (!ofproto->rstp || !rp) {
2566         s->enabled = false;
2567         return;
2568     }
2569
2570     s->enabled = true;
2571     rstp_port_get_status(rp, &s->port_id, &s->state, &s->role,
2572                          &s->designated_bridge_id, &s->designated_port_id,
2573                          &s->designated_path_cost, &s->tx_count,
2574                          &s->rx_count, &s->error_count, &s->uptime);
2575 }
2576
2577 \f
2578 static int
2579 set_queues(struct ofport *ofport_, const struct ofproto_port_queue *qdscp,
2580            size_t n_qdscp)
2581 {
2582     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2583     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2584
2585     if (ofport->n_qdscp != n_qdscp
2586         || (n_qdscp && memcmp(ofport->qdscp, qdscp,
2587                               n_qdscp * sizeof *qdscp))) {
2588         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2589         free(ofport->qdscp);
2590         ofport->qdscp = n_qdscp
2591             ? xmemdup(qdscp, n_qdscp * sizeof *qdscp)
2592             : NULL;
2593         ofport->n_qdscp = n_qdscp;
2594     }
2595
2596     return 0;
2597 }
2598 \f
2599 /* Bundles. */
2600
2601 /* Expires all MAC learning entries associated with 'bundle' and forces its
2602  * ofproto to revalidate every flow.
2603  *
2604  * Normally MAC learning entries are removed only from the ofproto associated
2605  * with 'bundle', but if 'all_ofprotos' is true, then the MAC learning entries
2606  * are removed from every ofproto.  When patch ports and SLB bonds are in use
2607  * and a VM migration happens and the gratuitous ARPs are somehow lost, this
2608  * avoids a MAC_ENTRY_IDLE_TIME delay before the migrated VM can communicate
2609  * with the host from which it migrated. */
2610 static void
2611 bundle_flush_macs(struct ofbundle *bundle, bool all_ofprotos)
2612 {
2613     struct ofproto_dpif *ofproto = bundle->ofproto;
2614     struct mac_learning *ml = ofproto->ml;
2615     struct mac_entry *mac, *next_mac;
2616
2617     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2618     ovs_rwlock_wrlock(&ml->rwlock);
2619     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
2620         if (mac_entry_get_port(ml, mac) == bundle) {
2621             if (all_ofprotos) {
2622                 struct ofproto_dpif *o;
2623
2624                 HMAP_FOR_EACH (o, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2625                     if (o != ofproto) {
2626                         struct mac_entry *e;
2627
2628                         ovs_rwlock_wrlock(&o->ml->rwlock);
2629                         e = mac_learning_lookup(o->ml, mac->mac, mac->vlan);
2630                         if (e) {
2631                             mac_learning_expire(o->ml, e);
2632                         }
2633                         ovs_rwlock_unlock(&o->ml->rwlock);
2634                     }
2635                 }
2636             }
2637
2638             mac_learning_expire(ml, mac);
2639         }
2640     }
2641     ovs_rwlock_unlock(&ml->rwlock);
2642 }
2643
2644 static void
2645 bundle_move(struct ofbundle *old, struct ofbundle *new)
2646 {
2647     struct ofproto_dpif *ofproto = old->ofproto;
2648     struct mac_learning *ml = ofproto->ml;
2649     struct mac_entry *mac, *next_mac;
2650
2651     ovs_assert(new->ofproto == old->ofproto);
2652
2653     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2654     ovs_rwlock_wrlock(&ml->rwlock);
2655     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
2656         if (mac_entry_get_port(ml, mac) == old) {
2657             mac_entry_set_port(ml, mac, new);
2658         }
2659     }
2660     ovs_rwlock_unlock(&ml->rwlock);
2661 }
2662
2663 static struct ofbundle *
2664 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
2665 {
2666     struct ofbundle *bundle;
2667
2668     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
2669                              &ofproto->bundles) {
2670         if (bundle->aux == aux) {
2671             return bundle;
2672         }
2673     }
2674     return NULL;
2675 }
2676
2677 static void
2678 bundle_update(struct ofbundle *bundle)
2679 {
2680     struct ofport_dpif *port;
2681
2682     bundle->floodable = true;
2683     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2684         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2685             || port->is_layer3
2686             || (bundle->ofproto->stp && !stp_forward_in_state(port->stp_state))
2687             || (bundle->ofproto->rstp && !rstp_forward_in_state(port->rstp_state))) {
2688             bundle->floodable = false;
2689             break;
2690         }
2691     }
2692 }
2693
2694 static void
2695 bundle_del_port(struct ofport_dpif *port)
2696 {
2697     struct ofbundle *bundle = port->bundle;
2698
2699     bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2700
2701     list_remove(&port->bundle_node);
2702     port->bundle = NULL;
2703
2704     if (bundle->lacp) {
2705         lacp_slave_unregister(bundle->lacp, port);
2706     }
2707     if (bundle->bond) {
2708         bond_slave_unregister(bundle->bond, port);
2709     }
2710
2711     bundle_update(bundle);
2712 }
2713
2714 static bool
2715 bundle_add_port(struct ofbundle *bundle, ofp_port_t ofp_port,
2716                 struct lacp_slave_settings *lacp)
2717 {
2718     struct ofport_dpif *port;
2719
2720     port = ofp_port_to_ofport(bundle->ofproto, ofp_port);
2721     if (!port) {
2722         return false;
2723     }
2724
2725     if (port->bundle != bundle) {
2726         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2727         if (port->bundle) {
2728             bundle_remove(&port->up);
2729         }
2730
2731         port->bundle = bundle;
2732         list_push_back(&bundle->ports, &port->bundle_node);
2733         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2734             || port->is_layer3
2735             || (bundle->ofproto->stp && !stp_forward_in_state(port->stp_state))
2736             || (bundle->ofproto->rstp && !rstp_forward_in_state(port->rstp_state))) {
2737             bundle->floodable = false;
2738         }
2739     }
2740     if (lacp) {
2741         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2742         lacp_slave_register(bundle->lacp, port, lacp);
2743     }
2744
2745     return true;
2746 }
2747
2748 static void
2749 bundle_destroy(struct ofbundle *bundle)
2750 {
2751     struct ofproto_dpif *ofproto;
2752     struct ofport_dpif *port, *next_port;
2753
2754     if (!bundle) {
2755         return;
2756     }
2757
2758     ofproto = bundle->ofproto;
2759     mbridge_unregister_bundle(ofproto->mbridge, bundle);
2760
2761     xlate_txn_start();
2762     xlate_bundle_remove(bundle);
2763     xlate_txn_commit();
2764
2765     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2766         bundle_del_port(port);
2767     }
2768
2769     bundle_flush_macs(bundle, true);
2770     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
2771     free(bundle->name);
2772     free(bundle->trunks);
2773     lacp_unref(bundle->lacp);
2774     bond_unref(bundle->bond);
2775     free(bundle);
2776 }
2777
2778 static int
2779 bundle_set(struct ofproto *ofproto_, void *aux,
2780            const struct ofproto_bundle_settings *s)
2781 {
2782     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2783     bool need_flush = false;
2784     struct ofport_dpif *port;
2785     struct ofbundle *bundle;
2786     unsigned long *trunks;
2787     int vlan;
2788     size_t i;
2789     bool ok;
2790
2791     if (!s) {
2792         bundle_destroy(bundle_lookup(ofproto, aux));
2793         return 0;
2794     }
2795
2796     ovs_assert(s->n_slaves == 1 || s->bond != NULL);
2797     ovs_assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
2798
2799     bundle = bundle_lookup(ofproto, aux);
2800     if (!bundle) {
2801         bundle = xmalloc(sizeof *bundle);
2802
2803         bundle->ofproto = ofproto;
2804         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
2805                     hash_pointer(aux, 0));
2806         bundle->aux = aux;
2807         bundle->name = NULL;
2808
2809         list_init(&bundle->ports);
2810         bundle->vlan_mode = PORT_VLAN_TRUNK;
2811         bundle->vlan = -1;
2812         bundle->trunks = NULL;
2813         bundle->use_priority_tags = s->use_priority_tags;
2814         bundle->lacp = NULL;
2815         bundle->bond = NULL;
2816
2817         bundle->floodable = true;
2818         mbridge_register_bundle(ofproto->mbridge, bundle);
2819     }
2820
2821     if (!bundle->name || strcmp(s->name, bundle->name)) {
2822         free(bundle->name);
2823         bundle->name = xstrdup(s->name);
2824     }
2825
2826     /* LACP. */
2827     if (s->lacp) {
2828         ofproto->lacp_enabled = true;
2829         if (!bundle->lacp) {
2830             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2831             bundle->lacp = lacp_create();
2832         }
2833         lacp_configure(bundle->lacp, s->lacp);
2834     } else {
2835         lacp_unref(bundle->lacp);
2836         bundle->lacp = NULL;
2837     }
2838
2839     /* Update set of ports. */
2840     ok = true;
2841     for (i = 0; i < s->n_slaves; i++) {
2842         if (!bundle_add_port(bundle, s->slaves[i],
2843                              s->lacp ? &s->lacp_slaves[i] : NULL)) {
2844             ok = false;
2845         }
2846     }
2847     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
2848         struct ofport_dpif *next_port;
2849
2850         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2851             for (i = 0; i < s->n_slaves; i++) {
2852                 if (s->slaves[i] == port->up.ofp_port) {
2853                     goto found;
2854                 }
2855             }
2856
2857             bundle_del_port(port);
2858         found: ;
2859         }
2860     }
2861     ovs_assert(list_size(&bundle->ports) <= s->n_slaves);
2862
2863     if (list_is_empty(&bundle->ports)) {
2864         bundle_destroy(bundle);
2865         return EINVAL;
2866     }
2867
2868     /* Set VLAN tagging mode */
2869     if (s->vlan_mode != bundle->vlan_mode
2870         || s->use_priority_tags != bundle->use_priority_tags) {
2871         bundle->vlan_mode = s->vlan_mode;
2872         bundle->use_priority_tags = s->use_priority_tags;
2873         need_flush = true;
2874     }
2875
2876     /* Set VLAN tag. */
2877     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
2878             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
2879             : 0);
2880     if (vlan != bundle->vlan) {
2881         bundle->vlan = vlan;
2882         need_flush = true;
2883     }
2884
2885     /* Get trunked VLANs. */
2886     switch (s->vlan_mode) {
2887     case PORT_VLAN_ACCESS:
2888         trunks = NULL;
2889         break;
2890
2891     case PORT_VLAN_TRUNK:
2892         trunks = CONST_CAST(unsigned long *, s->trunks);
2893         break;
2894
2895     case PORT_VLAN_NATIVE_UNTAGGED:
2896     case PORT_VLAN_NATIVE_TAGGED:
2897         if (vlan != 0 && (!s->trunks
2898                           || !bitmap_is_set(s->trunks, vlan)
2899                           || bitmap_is_set(s->trunks, 0))) {
2900             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
2901             if (s->trunks) {
2902                 trunks = bitmap_clone(s->trunks, 4096);
2903             } else {
2904                 trunks = bitmap_allocate1(4096);
2905             }
2906             bitmap_set1(trunks, vlan);
2907             bitmap_set0(trunks, 0);
2908         } else {
2909             trunks = CONST_CAST(unsigned long *, s->trunks);
2910         }
2911         break;
2912
2913     default:
2914         OVS_NOT_REACHED();
2915     }
2916     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
2917         free(bundle->trunks);
2918         if (trunks == s->trunks) {
2919             bundle->trunks = vlan_bitmap_clone(trunks);
2920         } else {
2921             bundle->trunks = trunks;
2922             trunks = NULL;
2923         }
2924         need_flush = true;
2925     }
2926     if (trunks != s->trunks) {
2927         free(trunks);
2928     }
2929
2930     /* Bonding. */
2931     if (!list_is_short(&bundle->ports)) {
2932         bundle->ofproto->has_bonded_bundles = true;
2933         if (bundle->bond) {
2934             if (bond_reconfigure(bundle->bond, s->bond)) {
2935                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2936             }
2937         } else {
2938             bundle->bond = bond_create(s->bond, ofproto);
2939             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2940         }
2941
2942         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2943             bond_slave_register(bundle->bond, port,
2944                                 port->up.ofp_port, port->up.netdev);
2945         }
2946     } else {
2947         bond_unref(bundle->bond);
2948         bundle->bond = NULL;
2949     }
2950
2951     /* If we changed something that would affect MAC learning, un-learn
2952      * everything on this port and force flow revalidation. */
2953     if (need_flush) {
2954         bundle_flush_macs(bundle, false);
2955     }
2956
2957     return 0;
2958 }
2959
2960 static void
2961 bundle_remove(struct ofport *port_)
2962 {
2963     struct ofport_dpif *port = ofport_dpif_cast(port_);
2964     struct ofbundle *bundle = port->bundle;
2965
2966     if (bundle) {
2967         bundle_del_port(port);
2968         if (list_is_empty(&bundle->ports)) {
2969             bundle_destroy(bundle);
2970         } else if (list_is_short(&bundle->ports)) {
2971             bond_unref(bundle->bond);
2972             bundle->bond = NULL;
2973         }
2974     }
2975 }
2976
2977 static void
2978 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
2979 {
2980     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
2981     struct ofport_dpif *port = port_;
2982     uint8_t ea[ETH_ADDR_LEN];
2983     int error;
2984
2985     error = netdev_get_etheraddr(port->up.netdev, ea);
2986     if (!error) {
2987         struct dp_packet packet;
2988         void *packet_pdu;
2989
2990         dp_packet_init(&packet, 0);
2991         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
2992                                  pdu_size);
2993         memcpy(packet_pdu, pdu, pdu_size);
2994
2995         ofproto_dpif_send_packet(port, &packet);
2996         dp_packet_uninit(&packet);
2997     } else {
2998         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
2999                     "%s (%s)", port->bundle->name,
3000                     netdev_get_name(port->up.netdev), ovs_strerror(error));
3001     }
3002 }
3003
3004 static void
3005 bundle_send_learning_packets(struct ofbundle *bundle)
3006 {
3007     struct ofproto_dpif *ofproto = bundle->ofproto;
3008     int error, n_packets, n_errors;
3009     struct mac_entry *e;
3010     struct pkt_list {
3011         struct ovs_list list_node;
3012         struct ofport_dpif *port;
3013         struct dp_packet *pkt;
3014     } *pkt_node;
3015     struct ovs_list packets;
3016
3017     list_init(&packets);
3018     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
3019     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
3020         if (mac_entry_get_port(ofproto->ml, e) != bundle) {
3021             pkt_node = xmalloc(sizeof *pkt_node);
3022             pkt_node->pkt = bond_compose_learning_packet(bundle->bond,
3023                                                          e->mac, e->vlan,
3024                                                          (void **)&pkt_node->port);
3025             list_push_back(&packets, &pkt_node->list_node);
3026         }
3027     }
3028     ovs_rwlock_unlock(&ofproto->ml->rwlock);
3029
3030     error = n_packets = n_errors = 0;
3031     LIST_FOR_EACH_POP (pkt_node, list_node, &packets) {
3032         int ret;
3033
3034         ret = ofproto_dpif_send_packet(pkt_node->port, pkt_node->pkt);
3035         dp_packet_delete(pkt_node->pkt);
3036         free(pkt_node);
3037         if (ret) {
3038             error = ret;
3039             n_errors++;
3040         }
3041         n_packets++;
3042     }
3043
3044     if (n_errors) {
3045         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3046         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
3047                      "packets, last error was: %s",
3048                      bundle->name, n_errors, n_packets, ovs_strerror(error));
3049     } else {
3050         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
3051                  bundle->name, n_packets);
3052     }
3053 }
3054
3055 static void
3056 bundle_run(struct ofbundle *bundle)
3057 {
3058     if (bundle->lacp) {
3059         lacp_run(bundle->lacp, send_pdu_cb);
3060     }
3061     if (bundle->bond) {
3062         struct ofport_dpif *port;
3063
3064         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
3065             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
3066         }
3067
3068         if (bond_run(bundle->bond, lacp_status(bundle->lacp))) {
3069             bundle->ofproto->backer->need_revalidate = REV_BOND;
3070         }
3071
3072         if (bond_should_send_learning_packets(bundle->bond)) {
3073             bundle_send_learning_packets(bundle);
3074         }
3075     }
3076 }
3077
3078 static void
3079 bundle_wait(struct ofbundle *bundle)
3080 {
3081     if (bundle->lacp) {
3082         lacp_wait(bundle->lacp);
3083     }
3084     if (bundle->bond) {
3085         bond_wait(bundle->bond);
3086     }
3087 }
3088 \f
3089 /* Mirrors. */
3090
3091 static int
3092 mirror_set__(struct ofproto *ofproto_, void *aux,
3093              const struct ofproto_mirror_settings *s)
3094 {
3095     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3096     struct ofbundle **srcs, **dsts;
3097     int error;
3098     size_t i;
3099
3100     if (!s) {
3101         mirror_destroy(ofproto->mbridge, aux);
3102         return 0;
3103     }
3104
3105     srcs = xmalloc(s->n_srcs * sizeof *srcs);
3106     dsts = xmalloc(s->n_dsts * sizeof *dsts);
3107
3108     for (i = 0; i < s->n_srcs; i++) {
3109         srcs[i] = bundle_lookup(ofproto, s->srcs[i]);
3110     }
3111
3112     for (i = 0; i < s->n_dsts; i++) {
3113         dsts[i] = bundle_lookup(ofproto, s->dsts[i]);
3114     }
3115
3116     error = mirror_set(ofproto->mbridge, aux, s->name, srcs, s->n_srcs, dsts,
3117                        s->n_dsts, s->src_vlans,
3118                        bundle_lookup(ofproto, s->out_bundle), s->out_vlan);
3119     free(srcs);
3120     free(dsts);
3121     return error;
3122 }
3123
3124 static int
3125 mirror_get_stats__(struct ofproto *ofproto, void *aux,
3126                    uint64_t *packets, uint64_t *bytes)
3127 {
3128     return mirror_get_stats(ofproto_dpif_cast(ofproto)->mbridge, aux, packets,
3129                             bytes);
3130 }
3131
3132 static int
3133 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
3134 {
3135     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3136     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
3137     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
3138         mac_learning_flush(ofproto->ml);
3139     }
3140     ovs_rwlock_unlock(&ofproto->ml->rwlock);
3141     return 0;
3142 }
3143
3144 static bool
3145 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
3146 {
3147     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3148     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
3149     return bundle && mirror_bundle_out(ofproto->mbridge, bundle) != 0;
3150 }
3151
3152 static void
3153 forward_bpdu_changed(struct ofproto *ofproto_)
3154 {
3155     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3156     ofproto->backer->need_revalidate = REV_RECONFIGURE;
3157 }
3158
3159 static void
3160 set_mac_table_config(struct ofproto *ofproto_, unsigned int idle_time,
3161                      size_t max_entries)
3162 {
3163     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3164     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
3165     mac_learning_set_idle_time(ofproto->ml, idle_time);
3166     mac_learning_set_max_entries(ofproto->ml, max_entries);
3167     ovs_rwlock_unlock(&ofproto->ml->rwlock);
3168 }
3169
3170 /* Configures multicast snooping on 'ofport' using the settings
3171  * defined in 's'. */
3172 static int
3173 set_mcast_snooping(struct ofproto *ofproto_,
3174                    const struct ofproto_mcast_snooping_settings *s)
3175 {
3176     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3177
3178     /* Only revalidate flows if the configuration changed. */
3179     if (!s != !ofproto->ms) {
3180         ofproto->backer->need_revalidate = REV_RECONFIGURE;
3181     }
3182
3183     if (s) {
3184         if (!ofproto->ms) {
3185             ofproto->ms = mcast_snooping_create();
3186         }
3187
3188         ovs_rwlock_wrlock(&ofproto->ms->rwlock);
3189         mcast_snooping_set_idle_time(ofproto->ms, s->idle_time);
3190         mcast_snooping_set_max_entries(ofproto->ms, s->max_entries);
3191         if (mcast_snooping_set_flood_unreg(ofproto->ms, s->flood_unreg)) {
3192             ofproto->backer->need_revalidate = REV_RECONFIGURE;
3193         }
3194         ovs_rwlock_unlock(&ofproto->ms->rwlock);
3195     } else {
3196         mcast_snooping_unref(ofproto->ms);
3197         ofproto->ms = NULL;
3198     }
3199
3200     return 0;
3201 }
3202
3203 /* Configures multicast snooping port's flood settings on 'ofproto'. */
3204 static int
3205 set_mcast_snooping_port(struct ofproto *ofproto_, void *aux,
3206                         const struct ofproto_mcast_snooping_port_settings *s)
3207 {
3208     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3209     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
3210
3211     if (ofproto->ms && s) {
3212         ovs_rwlock_wrlock(&ofproto->ms->rwlock);
3213         mcast_snooping_set_port_flood(ofproto->ms, bundle, s->flood);
3214         mcast_snooping_set_port_flood_reports(ofproto->ms, bundle,
3215                                               s->flood_reports);
3216         ovs_rwlock_unlock(&ofproto->ms->rwlock);
3217     }
3218     return 0;
3219 }
3220
3221 \f
3222 /* Ports. */
3223
3224 struct ofport_dpif *
3225 ofp_port_to_ofport(const struct ofproto_dpif *ofproto, ofp_port_t ofp_port)
3226 {
3227     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
3228     return ofport ? ofport_dpif_cast(ofport) : NULL;
3229 }
3230
3231 static void
3232 ofproto_port_from_dpif_port(struct ofproto_dpif *ofproto,
3233                             struct ofproto_port *ofproto_port,
3234                             struct dpif_port *dpif_port)
3235 {
3236     ofproto_port->name = dpif_port->name;
3237     ofproto_port->type = dpif_port->type;
3238     ofproto_port->ofp_port = odp_port_to_ofp_port(ofproto, dpif_port->port_no);
3239 }
3240
3241 static void
3242 ofport_update_peer(struct ofport_dpif *ofport)
3243 {
3244     const struct ofproto_dpif *ofproto;
3245     struct dpif_backer *backer;
3246     char *peer_name;
3247
3248     if (!netdev_vport_is_patch(ofport->up.netdev)) {
3249         return;
3250     }
3251
3252     backer = ofproto_dpif_cast(ofport->up.ofproto)->backer;
3253     backer->need_revalidate = REV_RECONFIGURE;
3254
3255     if (ofport->peer) {
3256         ofport->peer->peer = NULL;
3257         ofport->peer = NULL;
3258     }
3259
3260     peer_name = netdev_vport_patch_peer(ofport->up.netdev);
3261     if (!peer_name) {
3262         return;
3263     }
3264
3265     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
3266         struct ofport *peer_ofport;
3267         struct ofport_dpif *peer;
3268         char *peer_peer;
3269
3270         if (ofproto->backer != backer) {
3271             continue;
3272         }
3273
3274         peer_ofport = shash_find_data(&ofproto->up.port_by_name, peer_name);
3275         if (!peer_ofport) {
3276             continue;
3277         }
3278
3279         peer = ofport_dpif_cast(peer_ofport);
3280         peer_peer = netdev_vport_patch_peer(peer->up.netdev);
3281         if (peer_peer && !strcmp(netdev_get_name(ofport->up.netdev),
3282                                  peer_peer)) {
3283             ofport->peer = peer;
3284             ofport->peer->peer = ofport;
3285         }
3286         free(peer_peer);
3287
3288         break;
3289     }
3290     free(peer_name);
3291 }
3292
3293 static void
3294 port_run(struct ofport_dpif *ofport)
3295 {
3296     long long int carrier_seq = netdev_get_carrier_resets(ofport->up.netdev);
3297     bool carrier_changed = carrier_seq != ofport->carrier_seq;
3298     bool enable = netdev_get_carrier(ofport->up.netdev);
3299     bool cfm_enable = false;
3300     bool bfd_enable = false;
3301
3302     ofport->carrier_seq = carrier_seq;
3303
3304     if (ofport->cfm) {
3305         int cfm_opup = cfm_get_opup(ofport->cfm);
3306
3307         cfm_enable = !cfm_get_fault(ofport->cfm);
3308
3309         if (cfm_opup >= 0) {
3310             cfm_enable = cfm_enable && cfm_opup;
3311         }
3312     }
3313
3314     if (ofport->bfd) {
3315         bfd_enable = bfd_forwarding(ofport->bfd);
3316     }
3317
3318     if (ofport->bfd || ofport->cfm) {
3319         enable = enable && (cfm_enable || bfd_enable);
3320     }
3321
3322     if (ofport->bundle) {
3323         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
3324         if (carrier_changed) {
3325             lacp_slave_carrier_changed(ofport->bundle->lacp, ofport);
3326         }
3327     }
3328
3329     if (ofport->may_enable != enable) {
3330         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3331
3332         ofproto->backer->need_revalidate = REV_PORT_TOGGLED;
3333
3334         if (ofport->rstp_port) {
3335             rstp_port_set_mac_operational(ofport->rstp_port, enable);
3336         }
3337     }
3338
3339     ofport->may_enable = enable;
3340 }
3341
3342 static int
3343 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
3344                    struct ofproto_port *ofproto_port)
3345 {
3346     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3347     struct dpif_port dpif_port;
3348     int error;
3349
3350     if (sset_contains(&ofproto->ghost_ports, devname)) {
3351         const char *type = netdev_get_type_from_name(devname);
3352
3353         /* We may be called before ofproto->up.port_by_name is populated with
3354          * the appropriate ofport.  For this reason, we must get the name and
3355          * type from the netdev layer directly. */
3356         if (type) {
3357             const struct ofport *ofport;
3358
3359             ofport = shash_find_data(&ofproto->up.port_by_name, devname);
3360             ofproto_port->ofp_port = ofport ? ofport->ofp_port : OFPP_NONE;
3361             ofproto_port->name = xstrdup(devname);
3362             ofproto_port->type = xstrdup(type);
3363             return 0;
3364         }
3365         return ENODEV;
3366     }
3367
3368     if (!sset_contains(&ofproto->ports, devname)) {
3369         return ENODEV;
3370     }
3371     error = dpif_port_query_by_name(ofproto->backer->dpif,
3372                                     devname, &dpif_port);
3373     if (!error) {
3374         ofproto_port_from_dpif_port(ofproto, ofproto_port, &dpif_port);
3375     }
3376     return error;
3377 }
3378
3379 static int
3380 port_add(struct ofproto *ofproto_, struct netdev *netdev)
3381 {
3382     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3383     const char *devname = netdev_get_name(netdev);
3384     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
3385     const char *dp_port_name;
3386
3387     if (netdev_vport_is_patch(netdev)) {
3388         sset_add(&ofproto->ghost_ports, netdev_get_name(netdev));
3389         return 0;
3390     }
3391
3392     dp_port_name = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
3393     if (!dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
3394         odp_port_t port_no = ODPP_NONE;
3395         int error;
3396
3397         error = dpif_port_add(ofproto->backer->dpif, netdev, &port_no);
3398         if (error) {
3399             return error;
3400         }
3401         if (netdev_get_tunnel_config(netdev)) {
3402             simap_put(&ofproto->backer->tnl_backers,
3403                       dp_port_name, odp_to_u32(port_no));
3404         }
3405     }
3406
3407     if (netdev_get_tunnel_config(netdev)) {
3408         sset_add(&ofproto->ghost_ports, devname);
3409     } else {
3410         sset_add(&ofproto->ports, devname);
3411     }
3412     return 0;
3413 }
3414
3415 static int
3416 port_del(struct ofproto *ofproto_, ofp_port_t ofp_port)
3417 {
3418     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3419     struct ofport_dpif *ofport = ofp_port_to_ofport(ofproto, ofp_port);
3420     int error = 0;
3421
3422     if (!ofport) {
3423         return 0;
3424     }
3425
3426     sset_find_and_delete(&ofproto->ghost_ports,
3427                          netdev_get_name(ofport->up.netdev));
3428     ofproto->backer->need_revalidate = REV_RECONFIGURE;
3429     if (!ofport->is_tunnel && !netdev_vport_is_patch(ofport->up.netdev)) {
3430         error = dpif_port_del(ofproto->backer->dpif, ofport->odp_port);
3431         if (!error) {
3432             /* The caller is going to close ofport->up.netdev.  If this is a
3433              * bonded port, then the bond is using that netdev, so remove it
3434              * from the bond.  The client will need to reconfigure everything
3435              * after deleting ports, so then the slave will get re-added. */
3436             bundle_remove(&ofport->up);
3437         }
3438     }
3439     return error;
3440 }
3441
3442 static int
3443 port_get_stats(const struct ofport *ofport_, struct netdev_stats *stats)
3444 {
3445     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3446     int error;
3447
3448     error = netdev_get_stats(ofport->up.netdev, stats);
3449
3450     if (!error && ofport_->ofp_port == OFPP_LOCAL) {
3451         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3452
3453         ovs_mutex_lock(&ofproto->stats_mutex);
3454         /* ofproto->stats.tx_packets represents packets that we created
3455          * internally and sent to some port (e.g. packets sent with
3456          * ofproto_dpif_send_packet()).  Account for them as if they had
3457          * come from OFPP_LOCAL and got forwarded. */
3458
3459         if (stats->rx_packets != UINT64_MAX) {
3460             stats->rx_packets += ofproto->stats.tx_packets;
3461         }
3462
3463         if (stats->rx_bytes != UINT64_MAX) {
3464             stats->rx_bytes += ofproto->stats.tx_bytes;
3465         }
3466
3467         /* ofproto->stats.rx_packets represents packets that were received on
3468          * some port and we processed internally and dropped (e.g. STP).
3469          * Account for them as if they had been forwarded to OFPP_LOCAL. */
3470
3471         if (stats->tx_packets != UINT64_MAX) {
3472             stats->tx_packets += ofproto->stats.rx_packets;
3473         }
3474
3475         if (stats->tx_bytes != UINT64_MAX) {
3476             stats->tx_bytes += ofproto->stats.rx_bytes;
3477         }
3478         ovs_mutex_unlock(&ofproto->stats_mutex);
3479     }
3480
3481     return error;
3482 }
3483
3484 static int
3485 port_get_lacp_stats(const struct ofport *ofport_, struct lacp_slave_stats *stats)
3486 {
3487     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3488     if (ofport->bundle && ofport->bundle->lacp) {
3489         if (lacp_get_slave_stats(ofport->bundle->lacp, ofport, stats)) {
3490             return 0;
3491         }
3492     }
3493     return -1;
3494 }
3495
3496 struct port_dump_state {
3497     uint32_t bucket;
3498     uint32_t offset;
3499     bool ghost;
3500
3501     struct ofproto_port port;
3502     bool has_port;
3503 };
3504
3505 static int
3506 port_dump_start(const struct ofproto *ofproto_ OVS_UNUSED, void **statep)
3507 {
3508     *statep = xzalloc(sizeof(struct port_dump_state));
3509     return 0;
3510 }
3511
3512 static int
3513 port_dump_next(const struct ofproto *ofproto_, void *state_,
3514                struct ofproto_port *port)
3515 {
3516     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3517     struct port_dump_state *state = state_;
3518     const struct sset *sset;
3519     struct sset_node *node;
3520
3521     if (state->has_port) {
3522         ofproto_port_destroy(&state->port);
3523         state->has_port = false;
3524     }
3525     sset = state->ghost ? &ofproto->ghost_ports : &ofproto->ports;
3526     while ((node = sset_at_position(sset, &state->bucket, &state->offset))) {
3527         int error;
3528
3529         error = port_query_by_name(ofproto_, node->name, &state->port);
3530         if (!error) {
3531             *port = state->port;
3532             state->has_port = true;
3533             return 0;
3534         } else if (error != ENODEV) {
3535             return error;
3536         }
3537     }
3538
3539     if (!state->ghost) {
3540         state->ghost = true;
3541         state->bucket = 0;
3542         state->offset = 0;
3543         return port_dump_next(ofproto_, state_, port);
3544     }
3545
3546     return EOF;
3547 }
3548
3549 static int
3550 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
3551 {
3552     struct port_dump_state *state = state_;
3553
3554     if (state->has_port) {
3555         ofproto_port_destroy(&state->port);
3556     }
3557     free(state);
3558     return 0;
3559 }
3560
3561 static int
3562 port_poll(const struct ofproto *ofproto_, char **devnamep)
3563 {
3564     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3565
3566     if (ofproto->port_poll_errno) {
3567         int error = ofproto->port_poll_errno;
3568         ofproto->port_poll_errno = 0;
3569         return error;
3570     }
3571
3572     if (sset_is_empty(&ofproto->port_poll_set)) {
3573         return EAGAIN;
3574     }
3575
3576     *devnamep = sset_pop(&ofproto->port_poll_set);
3577     return 0;
3578 }
3579
3580 static void
3581 port_poll_wait(const struct ofproto *ofproto_)
3582 {
3583     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3584     dpif_port_poll_wait(ofproto->backer->dpif);
3585 }
3586
3587 static int
3588 port_is_lacp_current(const struct ofport *ofport_)
3589 {
3590     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3591     return (ofport->bundle && ofport->bundle->lacp
3592             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
3593             : -1);
3594 }
3595 \f
3596 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
3597  * then delete it entirely. */
3598 static void
3599 rule_expire(struct rule_dpif *rule)
3600     OVS_REQUIRES(ofproto_mutex)
3601 {
3602     uint16_t hard_timeout, idle_timeout;
3603     long long int now = time_msec();
3604     int reason = -1;
3605
3606     hard_timeout = rule->up.hard_timeout;
3607     idle_timeout = rule->up.idle_timeout;
3608
3609     /* Has 'rule' expired? */
3610     if (hard_timeout) {
3611         long long int modified;
3612
3613         ovs_mutex_lock(&rule->up.mutex);
3614         modified = rule->up.modified;
3615         ovs_mutex_unlock(&rule->up.mutex);
3616
3617         if (now > modified + hard_timeout * 1000) {
3618             reason = OFPRR_HARD_TIMEOUT;
3619         }
3620     }
3621
3622     if (reason < 0 && idle_timeout) {
3623         long long int used;
3624
3625         ovs_mutex_lock(&rule->stats_mutex);
3626         used = rule->stats.used;
3627         ovs_mutex_unlock(&rule->stats_mutex);
3628
3629         if (now > used + idle_timeout * 1000) {
3630             reason = OFPRR_IDLE_TIMEOUT;
3631         }
3632     }
3633
3634     if (reason >= 0) {
3635         COVERAGE_INC(ofproto_dpif_expired);
3636         ofproto_rule_expire(&rule->up, reason);
3637     }
3638 }
3639
3640 /* Executes, within 'ofproto', the actions in 'rule' or 'ofpacts' on 'packet'.
3641  * 'flow' must reflect the data in 'packet'. */
3642 int
3643 ofproto_dpif_execute_actions(struct ofproto_dpif *ofproto,
3644                              const struct flow *flow,
3645                              struct rule_dpif *rule,
3646                              const struct ofpact *ofpacts, size_t ofpacts_len,
3647                              struct dp_packet *packet)
3648 {
3649     struct dpif_flow_stats stats;
3650     struct xlate_out xout;
3651     struct xlate_in xin;
3652     ofp_port_t in_port;
3653     struct dpif_execute execute;
3654     int error;
3655
3656     ovs_assert((rule != NULL) != (ofpacts != NULL));
3657
3658     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
3659
3660     if (rule) {
3661         rule_dpif_credit_stats(rule, &stats);
3662     }
3663
3664     xlate_in_init(&xin, ofproto, flow, flow->in_port.ofp_port, rule,
3665                   stats.tcp_flags, packet);
3666     xin.ofpacts = ofpacts;
3667     xin.ofpacts_len = ofpacts_len;
3668     xin.resubmit_stats = &stats;
3669     xlate_actions(&xin, &xout);
3670
3671     execute.actions = xout.odp_actions->data;
3672     execute.actions_len = xout.odp_actions->size;
3673
3674     pkt_metadata_from_flow(&packet->md, flow);
3675     execute.packet = packet;
3676     execute.needs_help = (xout.slow & SLOW_ACTION) != 0;
3677     execute.probe = false;
3678
3679     /* Fix up in_port. */
3680     in_port = flow->in_port.ofp_port;
3681     if (in_port == OFPP_NONE) {
3682         in_port = OFPP_LOCAL;
3683     }
3684     execute.packet->md.in_port.odp_port = ofp_port_to_odp_port(ofproto, in_port);
3685
3686     error = dpif_execute(ofproto->backer->dpif, &execute);
3687
3688     xlate_out_uninit(&xout);
3689
3690     return error;
3691 }
3692
3693 void
3694 rule_dpif_credit_stats(struct rule_dpif *rule,
3695                        const struct dpif_flow_stats *stats)
3696 {
3697     ovs_mutex_lock(&rule->stats_mutex);
3698     if (OVS_UNLIKELY(rule->new_rule)) {
3699         rule_dpif_credit_stats(rule->new_rule, stats);
3700     } else {
3701         rule->stats.n_packets += stats->n_packets;
3702         rule->stats.n_bytes += stats->n_bytes;
3703         rule->stats.used = MAX(rule->stats.used, stats->used);
3704     }
3705     ovs_mutex_unlock(&rule->stats_mutex);
3706 }
3707
3708 ovs_be64
3709 rule_dpif_get_flow_cookie(const struct rule_dpif *rule)
3710     OVS_REQUIRES(rule->up.mutex)
3711 {
3712     return rule->up.flow_cookie;
3713 }
3714
3715 void
3716 rule_dpif_reduce_timeouts(struct rule_dpif *rule, uint16_t idle_timeout,
3717                      uint16_t hard_timeout)
3718 {
3719     ofproto_rule_reduce_timeouts(&rule->up, idle_timeout, hard_timeout);
3720 }
3721
3722 /* Returns 'rule''s actions.  The returned actions are RCU-protected, and can
3723  * be read until the calling thread quiesces. */
3724 const struct rule_actions *
3725 rule_dpif_get_actions(const struct rule_dpif *rule)
3726 {
3727     return rule_get_actions(&rule->up);
3728 }
3729
3730 /* Sets 'rule''s recirculation id. */
3731 static void
3732 rule_dpif_set_recirc_id(struct rule_dpif *rule, uint32_t id)
3733     OVS_REQUIRES(rule->up.mutex)
3734 {
3735     ovs_assert(!rule->recirc_id || rule->recirc_id == id);
3736     if (rule->recirc_id == id) {
3737         /* Release the new reference to the same id. */
3738         recirc_free_id(id);
3739     } else {
3740         rule->recirc_id = id;
3741     }
3742 }
3743
3744 /* Sets 'rule''s recirculation id. */
3745 void
3746 rule_set_recirc_id(struct rule *rule_, uint32_t id)
3747 {
3748     struct rule_dpif *rule = rule_dpif_cast(rule_);
3749
3750     ovs_mutex_lock(&rule->up.mutex);
3751     rule_dpif_set_recirc_id(rule, id);
3752     ovs_mutex_unlock(&rule->up.mutex);
3753 }
3754
3755 cls_version_t
3756 ofproto_dpif_get_tables_version(struct ofproto_dpif *ofproto OVS_UNUSED)
3757 {
3758     cls_version_t version;
3759
3760     atomic_read_relaxed(&ofproto->tables_version, &version);
3761
3762     return version;
3763 }
3764
3765 /* The returned rule (if any) is valid at least until the next RCU quiescent
3766  * period.  If the rule needs to stay around longer, a non-zero 'take_ref'
3767  * must be passed in to cause a reference to be taken on it.
3768  *
3769  * 'flow' is non-const to allow for temporary modifications during the lookup.
3770  * Any changes are restored before returning. */
3771 static struct rule_dpif *
3772 rule_dpif_lookup_in_table(struct ofproto_dpif *ofproto, cls_version_t version,
3773                           uint8_t table_id, struct flow *flow,
3774                           struct flow_wildcards *wc, bool take_ref)
3775 {
3776     struct classifier *cls = &ofproto->up.tables[table_id].cls;
3777     const struct cls_rule *cls_rule;
3778     struct rule_dpif *rule;
3779
3780     do {
3781         cls_rule = classifier_lookup(cls, version, flow, wc);
3782
3783         rule = rule_dpif_cast(rule_from_cls_rule(cls_rule));
3784
3785         /* Try again if the rule was released before we get the reference. */
3786     } while (rule && take_ref && !rule_dpif_try_ref(rule));
3787
3788     return rule;
3789 }
3790
3791 /* Look up 'flow' in 'ofproto''s classifier version 'version', starting from
3792  * table '*table_id'.  Returns the rule that was found, which may be one of the
3793  * special rules according to packet miss hadling.  If 'may_packet_in' is
3794  * false, returning of the miss_rule (which issues packet ins for the
3795  * controller) is avoided.  Updates 'wc', if nonnull, to reflect the fields
3796  * that were used during the lookup.
3797  *
3798  * If 'honor_table_miss' is true, the first lookup occurs in '*table_id', but
3799  * if none is found then the table miss configuration for that table is
3800  * honored, which can result in additional lookups in other OpenFlow tables.
3801  * In this case the function updates '*table_id' to reflect the final OpenFlow
3802  * table that was searched.
3803  *
3804  * If 'honor_table_miss' is false, then only one table lookup occurs, in
3805  * '*table_id'.
3806  *
3807  * The rule is returned in '*rule', which is valid at least until the next
3808  * RCU quiescent period.  If the '*rule' needs to stay around longer,
3809  * a non-zero 'take_ref' must be passed in to cause a reference to be taken
3810  * on it before this returns.
3811  *
3812  * 'in_port' allows the lookup to take place as if the in port had the value
3813  * 'in_port'.  This is needed for resubmit action support.
3814  *
3815  * 'flow' is non-const to allow for temporary modifications during the lookup.
3816  * Any changes are restored before returning. */
3817 struct rule_dpif *
3818 rule_dpif_lookup_from_table(struct ofproto_dpif *ofproto,
3819                             cls_version_t version, struct flow *flow,
3820                             struct flow_wildcards *wc, bool take_ref,
3821                             const struct dpif_flow_stats *stats,
3822                             uint8_t *table_id, ofp_port_t in_port,
3823                             bool may_packet_in, bool honor_table_miss)
3824 {
3825     ovs_be16 old_tp_src = flow->tp_src, old_tp_dst = flow->tp_dst;
3826     ofp_port_t old_in_port = flow->in_port.ofp_port;
3827     enum ofputil_table_miss miss_config;
3828     struct rule_dpif *rule;
3829     uint8_t next_id;
3830
3831     /* We always unwildcard nw_frag (for IP), so they
3832      * need not be unwildcarded here. */
3833     if (flow->nw_frag & FLOW_NW_FRAG_ANY
3834         && ofproto->up.frag_handling != OFPC_FRAG_NX_MATCH) {
3835         if (ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
3836             /* We must pretend that transport ports are unavailable. */
3837             flow->tp_src = htons(0);
3838             flow->tp_dst = htons(0);
3839         } else {
3840             /* Must be OFPC_FRAG_DROP (we don't have OFPC_FRAG_REASM).
3841              * Use the drop_frags_rule (which cannot disappear). */
3842             rule = ofproto->drop_frags_rule;
3843             if (take_ref) {
3844                 rule_dpif_ref(rule);
3845             }
3846             if (stats) {
3847                 struct oftable *tbl = &ofproto->up.tables[*table_id];
3848                 unsigned long orig;
3849
3850                 atomic_add_relaxed(&tbl->n_matched, stats->n_packets, &orig);
3851             }
3852             return rule;
3853         }
3854     }
3855
3856     /* Look up a flow with 'in_port' as the input port.  Then restore the
3857      * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
3858      * have surprising behavior). */
3859     flow->in_port.ofp_port = in_port;
3860
3861     /* Our current implementation depends on n_tables == N_TABLES, and
3862      * TBL_INTERNAL being the last table. */
3863     BUILD_ASSERT_DECL(N_TABLES == TBL_INTERNAL + 1);
3864
3865     miss_config = OFPUTIL_TABLE_MISS_CONTINUE;
3866
3867     for (next_id = *table_id;
3868          next_id < ofproto->up.n_tables;
3869          next_id++, next_id += (next_id == TBL_INTERNAL))
3870     {
3871         *table_id = next_id;
3872         rule = rule_dpif_lookup_in_table(ofproto, version, next_id, flow, wc,
3873                                          take_ref);
3874         if (stats) {
3875             struct oftable *tbl = &ofproto->up.tables[next_id];
3876             unsigned long orig;
3877
3878             atomic_add_relaxed(rule ? &tbl->n_matched : &tbl->n_missed,
3879                                stats->n_packets, &orig);
3880         }
3881         if (rule) {
3882             goto out;   /* Match. */
3883         }
3884         if (honor_table_miss) {
3885             miss_config = ofproto_table_get_miss_config(&ofproto->up,
3886                                                         *table_id);
3887             if (miss_config == OFPUTIL_TABLE_MISS_CONTINUE) {
3888                 continue;
3889             }
3890         }
3891         break;
3892     }
3893     /* Miss. */
3894     rule = ofproto->no_packet_in_rule;
3895     if (may_packet_in) {
3896         if (miss_config == OFPUTIL_TABLE_MISS_CONTINUE
3897             || miss_config == OFPUTIL_TABLE_MISS_CONTROLLER) {
3898             struct ofport_dpif *port;
3899
3900             port = ofp_port_to_ofport(ofproto, old_in_port);
3901             if (!port) {
3902                 VLOG_WARN_RL(&rl, "packet-in on unknown OpenFlow port %"PRIu16,
3903                              old_in_port);
3904             } else if (!(port->up.pp.config & OFPUTIL_PC_NO_PACKET_IN)) {
3905                 rule = ofproto->miss_rule;
3906             }
3907         } else if (miss_config == OFPUTIL_TABLE_MISS_DEFAULT &&
3908                    connmgr_wants_packet_in_on_miss(ofproto->up.connmgr)) {
3909             rule = ofproto->miss_rule;
3910         }
3911     }
3912     if (take_ref) {
3913         rule_dpif_ref(rule);
3914     }
3915 out:
3916     /* Restore port numbers, as they may have been modified above. */
3917     flow->tp_src = old_tp_src;
3918     flow->tp_dst = old_tp_dst;
3919     /* Restore the old in port. */
3920     flow->in_port.ofp_port = old_in_port;
3921
3922     return rule;
3923 }
3924
3925 static void
3926 complete_operation(struct rule_dpif *rule)
3927     OVS_REQUIRES(ofproto_mutex)
3928 {
3929     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3930
3931     ofproto->backer->need_revalidate = REV_FLOW_TABLE;
3932 }
3933
3934 static struct rule_dpif *rule_dpif_cast(const struct rule *rule)
3935 {
3936     return rule ? CONTAINER_OF(rule, struct rule_dpif, up) : NULL;
3937 }
3938
3939 static struct rule *
3940 rule_alloc(void)
3941 {
3942     struct rule_dpif *rule = xzalloc(sizeof *rule);
3943     return &rule->up;
3944 }
3945
3946 static void
3947 rule_dealloc(struct rule *rule_)
3948 {
3949     struct rule_dpif *rule = rule_dpif_cast(rule_);
3950     free(rule);
3951 }
3952
3953 static enum ofperr
3954 rule_construct(struct rule *rule_)
3955     OVS_NO_THREAD_SAFETY_ANALYSIS
3956 {
3957     struct rule_dpif *rule = rule_dpif_cast(rule_);
3958     ovs_mutex_init_adaptive(&rule->stats_mutex);
3959     rule->stats.n_packets = 0;
3960     rule->stats.n_bytes = 0;
3961     rule->stats.used = rule->up.modified;
3962     rule->recirc_id = 0;
3963     rule->new_rule = NULL;
3964
3965     return 0;
3966 }
3967
3968 static void
3969 rule_insert(struct rule *rule_, struct rule *old_rule_, bool forward_stats)
3970     OVS_REQUIRES(ofproto_mutex)
3971 {
3972     struct rule_dpif *rule = rule_dpif_cast(rule_);
3973
3974     if (old_rule_ && forward_stats) {
3975         struct rule_dpif *old_rule = rule_dpif_cast(old_rule_);
3976
3977         ovs_assert(!old_rule->new_rule);
3978
3979         /* Take a reference to the new rule, and refer all stats updates from
3980          * the old rule to the new rule. */
3981         rule_dpif_ref(rule);
3982
3983         ovs_mutex_lock(&old_rule->stats_mutex);
3984         ovs_mutex_lock(&rule->stats_mutex);
3985         old_rule->new_rule = rule;       /* Forward future stats. */
3986         rule->stats = old_rule->stats;   /* Transfer stats to the new rule. */
3987         ovs_mutex_unlock(&rule->stats_mutex);
3988         ovs_mutex_unlock(&old_rule->stats_mutex);
3989     }
3990
3991     complete_operation(rule);
3992 }
3993
3994 static void
3995 rule_delete(struct rule *rule_)
3996     OVS_REQUIRES(ofproto_mutex)
3997 {
3998     struct rule_dpif *rule = rule_dpif_cast(rule_);
3999     complete_operation(rule);
4000 }
4001
4002 static void
4003 rule_destruct(struct rule *rule_)
4004     OVS_NO_THREAD_SAFETY_ANALYSIS
4005 {
4006     struct rule_dpif *rule = rule_dpif_cast(rule_);
4007
4008     ovs_mutex_destroy(&rule->stats_mutex);
4009     /* Release reference to the new rule, if any. */
4010     if (rule->new_rule) {
4011         rule_dpif_unref(rule->new_rule);
4012     }
4013     if (rule->recirc_id) {
4014         recirc_free_id(rule->recirc_id);
4015     }
4016 }
4017
4018 static void
4019 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes,
4020                long long int *used)
4021 {
4022     struct rule_dpif *rule = rule_dpif_cast(rule_);
4023
4024     ovs_mutex_lock(&rule->stats_mutex);
4025     if (OVS_UNLIKELY(rule->new_rule)) {
4026         rule_get_stats(&rule->new_rule->up, packets, bytes, used);
4027     } else {
4028         *packets = rule->stats.n_packets;
4029         *bytes = rule->stats.n_bytes;
4030         *used = rule->stats.used;
4031     }
4032     ovs_mutex_unlock(&rule->stats_mutex);
4033 }
4034
4035 static void
4036 rule_dpif_execute(struct rule_dpif *rule, const struct flow *flow,
4037                   struct dp_packet *packet)
4038 {
4039     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4040
4041     ofproto_dpif_execute_actions(ofproto, flow, rule, NULL, 0, packet);
4042 }
4043
4044 static enum ofperr
4045 rule_execute(struct rule *rule, const struct flow *flow,
4046              struct dp_packet *packet)
4047 {
4048     rule_dpif_execute(rule_dpif_cast(rule), flow, packet);
4049     dp_packet_delete(packet);
4050     return 0;
4051 }
4052
4053 static struct group_dpif *group_dpif_cast(const struct ofgroup *group)
4054 {
4055     return group ? CONTAINER_OF(group, struct group_dpif, up) : NULL;
4056 }
4057
4058 static struct ofgroup *
4059 group_alloc(void)
4060 {
4061     struct group_dpif *group = xzalloc(sizeof *group);
4062     return &group->up;
4063 }
4064
4065 static void
4066 group_dealloc(struct ofgroup *group_)
4067 {
4068     struct group_dpif *group = group_dpif_cast(group_);
4069     free(group);
4070 }
4071
4072 static void
4073 group_construct_stats(struct group_dpif *group)
4074     OVS_REQUIRES(group->stats_mutex)
4075 {
4076     struct ofputil_bucket *bucket;
4077     const struct ovs_list *buckets;
4078
4079     group->packet_count = 0;
4080     group->byte_count = 0;
4081
4082     group_dpif_get_buckets(group, &buckets);
4083     LIST_FOR_EACH (bucket, list_node, buckets) {
4084         bucket->stats.packet_count = 0;
4085         bucket->stats.byte_count = 0;
4086     }
4087 }
4088
4089 void
4090 group_dpif_credit_stats(struct group_dpif *group,
4091                         struct ofputil_bucket *bucket,
4092                         const struct dpif_flow_stats *stats)
4093 {
4094     ovs_mutex_lock(&group->stats_mutex);
4095     group->packet_count += stats->n_packets;
4096     group->byte_count += stats->n_bytes;
4097     if (bucket) {
4098         bucket->stats.packet_count += stats->n_packets;
4099         bucket->stats.byte_count += stats->n_bytes;
4100     } else { /* Credit to all buckets */
4101         const struct ovs_list *buckets;
4102
4103         group_dpif_get_buckets(group, &buckets);
4104         LIST_FOR_EACH (bucket, list_node, buckets) {
4105             bucket->stats.packet_count += stats->n_packets;
4106             bucket->stats.byte_count += stats->n_bytes;
4107         }
4108     }
4109     ovs_mutex_unlock(&group->stats_mutex);
4110 }
4111
4112 static enum ofperr
4113 group_construct(struct ofgroup *group_)
4114 {
4115     struct group_dpif *group = group_dpif_cast(group_);
4116     const struct ofputil_bucket *bucket;
4117
4118     /* Prevent group chaining because our locking structure makes it hard to
4119      * implement deadlock-free.  (See xlate_group_resource_check().) */
4120     LIST_FOR_EACH (bucket, list_node, &group->up.buckets) {
4121         const struct ofpact *a;
4122
4123         OFPACT_FOR_EACH (a, bucket->ofpacts, bucket->ofpacts_len) {
4124             if (a->type == OFPACT_GROUP) {
4125                 return OFPERR_OFPGMFC_CHAINING_UNSUPPORTED;
4126             }
4127         }
4128     }
4129
4130     ovs_mutex_init_adaptive(&group->stats_mutex);
4131     ovs_mutex_lock(&group->stats_mutex);
4132     group_construct_stats(group);
4133     ovs_mutex_unlock(&group->stats_mutex);
4134     return 0;
4135 }
4136
4137 static void
4138 group_destruct(struct ofgroup *group_)
4139 {
4140     struct group_dpif *group = group_dpif_cast(group_);
4141     ovs_mutex_destroy(&group->stats_mutex);
4142 }
4143
4144 static enum ofperr
4145 group_modify(struct ofgroup *group_)
4146 {
4147     struct ofproto_dpif *ofproto = ofproto_dpif_cast(group_->ofproto);
4148
4149     ofproto->backer->need_revalidate = REV_FLOW_TABLE;
4150
4151     return 0;
4152 }
4153
4154 static enum ofperr
4155 group_get_stats(const struct ofgroup *group_, struct ofputil_group_stats *ogs)
4156 {
4157     struct group_dpif *group = group_dpif_cast(group_);
4158     struct ofputil_bucket *bucket;
4159     const struct ovs_list *buckets;
4160     struct bucket_counter *bucket_stats;
4161
4162     ovs_mutex_lock(&group->stats_mutex);
4163     ogs->packet_count = group->packet_count;
4164     ogs->byte_count = group->byte_count;
4165
4166     group_dpif_get_buckets(group, &buckets);
4167     bucket_stats = ogs->bucket_stats;
4168     LIST_FOR_EACH (bucket, list_node, buckets) {
4169         bucket_stats->packet_count = bucket->stats.packet_count;
4170         bucket_stats->byte_count = bucket->stats.byte_count;
4171         bucket_stats++;
4172     }
4173     ovs_mutex_unlock(&group->stats_mutex);
4174
4175     return 0;
4176 }
4177
4178 /* If the group exists, this function increments the groups's reference count.
4179  *
4180  * Make sure to call group_dpif_unref() after no longer needing to maintain
4181  * a reference to the group. */
4182 bool
4183 group_dpif_lookup(struct ofproto_dpif *ofproto, uint32_t group_id,
4184                   struct group_dpif **group)
4185 {
4186     struct ofgroup *ofgroup;
4187     bool found;
4188
4189     found = ofproto_group_lookup(&ofproto->up, group_id, &ofgroup);
4190     *group = found ?  group_dpif_cast(ofgroup) : NULL;
4191
4192     return found;
4193 }
4194
4195 void
4196 group_dpif_get_buckets(const struct group_dpif *group,
4197                        const struct ovs_list **buckets)
4198 {
4199     *buckets = &group->up.buckets;
4200 }
4201
4202 enum ofp11_group_type
4203 group_dpif_get_type(const struct group_dpif *group)
4204 {
4205     return group->up.type;
4206 }
4207
4208 const char *
4209 group_dpif_get_selection_method(const struct group_dpif *group)
4210 {
4211     return group->up.props.selection_method;
4212 }
4213 \f
4214 /* Sends 'packet' out 'ofport'.
4215  * May modify 'packet'.
4216  * Returns 0 if successful, otherwise a positive errno value. */
4217 int
4218 ofproto_dpif_send_packet(const struct ofport_dpif *ofport, struct dp_packet *packet)
4219 {
4220     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
4221     int error;
4222
4223     error = xlate_send_packet(ofport, packet);
4224
4225     ovs_mutex_lock(&ofproto->stats_mutex);
4226     ofproto->stats.tx_packets++;
4227     ofproto->stats.tx_bytes += dp_packet_size(packet);
4228     ovs_mutex_unlock(&ofproto->stats_mutex);
4229     return error;
4230 }
4231
4232 uint64_t
4233 group_dpif_get_selection_method_param(const struct group_dpif *group)
4234 {
4235     return group->up.props.selection_method_param;
4236 }
4237
4238 const struct field_array *
4239 group_dpif_get_fields(const struct group_dpif *group)
4240 {
4241     return &group->up.props.fields;
4242 }
4243 \f
4244 /* Return the version string of the datapath that backs up
4245  * this 'ofproto'.
4246  */
4247 static const char *
4248 get_datapath_version(const struct ofproto *ofproto_)
4249 {
4250     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4251
4252     return ofproto->backer->dp_version_string;
4253 }
4254
4255 static bool
4256 set_frag_handling(struct ofproto *ofproto_,
4257                   enum ofp_config_flags frag_handling)
4258 {
4259     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4260     if (frag_handling != OFPC_FRAG_REASM) {
4261         ofproto->backer->need_revalidate = REV_RECONFIGURE;
4262         return true;
4263     } else {
4264         return false;
4265     }
4266 }
4267
4268 static enum ofperr
4269 packet_out(struct ofproto *ofproto_, struct dp_packet *packet,
4270            const struct flow *flow,
4271            const struct ofpact *ofpacts, size_t ofpacts_len)
4272 {
4273     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4274
4275     ofproto_dpif_execute_actions(ofproto, flow, NULL, ofpacts,
4276                                  ofpacts_len, packet);
4277     return 0;
4278 }
4279 \f
4280 /* NetFlow. */
4281
4282 static int
4283 set_netflow(struct ofproto *ofproto_,
4284             const struct netflow_options *netflow_options)
4285 {
4286     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4287
4288     if (netflow_options) {
4289         if (!ofproto->netflow) {
4290             ofproto->netflow = netflow_create();
4291             ofproto->backer->need_revalidate = REV_RECONFIGURE;
4292         }
4293         return netflow_set_options(ofproto->netflow, netflow_options);
4294     } else if (ofproto->netflow) {
4295         ofproto->backer->need_revalidate = REV_RECONFIGURE;
4296         netflow_unref(ofproto->netflow);
4297         ofproto->netflow = NULL;
4298     }
4299
4300     return 0;
4301 }
4302
4303 static void
4304 get_netflow_ids(const struct ofproto *ofproto_,
4305                 uint8_t *engine_type, uint8_t *engine_id)
4306 {
4307     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4308
4309     dpif_get_netflow_ids(ofproto->backer->dpif, engine_type, engine_id);
4310 }
4311 \f
4312 static struct ofproto_dpif *
4313 ofproto_dpif_lookup(const char *name)
4314 {
4315     struct ofproto_dpif *ofproto;
4316
4317     HMAP_FOR_EACH_WITH_HASH (ofproto, all_ofproto_dpifs_node,
4318                              hash_string(name, 0), &all_ofproto_dpifs) {
4319         if (!strcmp(ofproto->up.name, name)) {
4320             return ofproto;
4321         }
4322     }
4323     return NULL;
4324 }
4325
4326 static void
4327 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn, int argc,
4328                           const char *argv[], void *aux OVS_UNUSED)
4329 {
4330     struct ofproto_dpif *ofproto;
4331
4332     if (argc > 1) {
4333         ofproto = ofproto_dpif_lookup(argv[1]);
4334         if (!ofproto) {
4335             unixctl_command_reply_error(conn, "no such bridge");
4336             return;
4337         }
4338         ovs_rwlock_wrlock(&ofproto->ml->rwlock);
4339         mac_learning_flush(ofproto->ml);
4340         ovs_rwlock_unlock(&ofproto->ml->rwlock);
4341     } else {
4342         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4343             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
4344             mac_learning_flush(ofproto->ml);
4345             ovs_rwlock_unlock(&ofproto->ml->rwlock);
4346         }
4347     }
4348
4349     unixctl_command_reply(conn, "table successfully flushed");
4350 }
4351
4352 static void
4353 ofproto_unixctl_mcast_snooping_flush(struct unixctl_conn *conn, int argc,
4354                                      const char *argv[], void *aux OVS_UNUSED)
4355 {
4356     struct ofproto_dpif *ofproto;
4357
4358     if (argc > 1) {
4359         ofproto = ofproto_dpif_lookup(argv[1]);
4360         if (!ofproto) {
4361             unixctl_command_reply_error(conn, "no such bridge");
4362             return;
4363         }
4364
4365         if (!mcast_snooping_enabled(ofproto->ms)) {
4366             unixctl_command_reply_error(conn, "multicast snooping is disabled");
4367             return;
4368         }
4369         mcast_snooping_mdb_flush(ofproto->ms);
4370     } else {
4371         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4372             if (!mcast_snooping_enabled(ofproto->ms)) {
4373                 continue;
4374             }
4375             mcast_snooping_mdb_flush(ofproto->ms);
4376         }
4377     }
4378
4379     unixctl_command_reply(conn, "table successfully flushed");
4380 }
4381
4382 static struct ofport_dpif *
4383 ofbundle_get_a_port(const struct ofbundle *bundle)
4384 {
4385     return CONTAINER_OF(list_front(&bundle->ports), struct ofport_dpif,
4386                         bundle_node);
4387 }
4388
4389 static void
4390 ofproto_unixctl_fdb_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
4391                          const char *argv[], void *aux OVS_UNUSED)
4392 {
4393     struct ds ds = DS_EMPTY_INITIALIZER;
4394     const struct ofproto_dpif *ofproto;
4395     const struct mac_entry *e;
4396
4397     ofproto = ofproto_dpif_lookup(argv[1]);
4398     if (!ofproto) {
4399         unixctl_command_reply_error(conn, "no such bridge");
4400         return;
4401     }
4402
4403     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
4404     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
4405     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
4406         struct ofbundle *bundle = mac_entry_get_port(ofproto->ml, e);
4407         char name[OFP_MAX_PORT_NAME_LEN];
4408
4409         ofputil_port_to_string(ofbundle_get_a_port(bundle)->up.ofp_port,
4410                                name, sizeof name);
4411         ds_put_format(&ds, "%5s  %4d  "ETH_ADDR_FMT"  %3d\n",
4412                       name, e->vlan, ETH_ADDR_ARGS(e->mac),
4413                       mac_entry_age(ofproto->ml, e));
4414     }
4415     ovs_rwlock_unlock(&ofproto->ml->rwlock);
4416     unixctl_command_reply(conn, ds_cstr(&ds));
4417     ds_destroy(&ds);
4418 }
4419
4420 static void
4421 ofproto_unixctl_mcast_snooping_show(struct unixctl_conn *conn,
4422                                     int argc OVS_UNUSED,
4423                                     const char *argv[],
4424                                     void *aux OVS_UNUSED)
4425 {
4426     struct ds ds = DS_EMPTY_INITIALIZER;
4427     const struct ofproto_dpif *ofproto;
4428     const struct ofbundle *bundle;
4429     const struct mcast_group *grp;
4430     struct mcast_group_bundle *b;
4431     struct mcast_mrouter_bundle *mrouter;
4432
4433     ofproto = ofproto_dpif_lookup(argv[1]);
4434     if (!ofproto) {
4435         unixctl_command_reply_error(conn, "no such bridge");
4436         return;
4437     }
4438
4439     if (!mcast_snooping_enabled(ofproto->ms)) {
4440         unixctl_command_reply_error(conn, "multicast snooping is disabled");
4441         return;
4442     }
4443
4444     ds_put_cstr(&ds, " port  VLAN  GROUP                Age\n");
4445     ovs_rwlock_rdlock(&ofproto->ms->rwlock);
4446     LIST_FOR_EACH (grp, group_node, &ofproto->ms->group_lru) {
4447         LIST_FOR_EACH(b, bundle_node, &grp->bundle_lru) {
4448             char name[OFP_MAX_PORT_NAME_LEN];
4449
4450             bundle = b->port;
4451             ofputil_port_to_string(ofbundle_get_a_port(bundle)->up.ofp_port,
4452                                    name, sizeof name);
4453             ds_put_format(&ds, "%5s  %4d  "IP_FMT"         %3d\n",
4454                           name, grp->vlan, IP_ARGS(grp->ip4),
4455                           mcast_bundle_age(ofproto->ms, b));
4456         }
4457     }
4458
4459     /* ports connected to multicast routers */
4460     LIST_FOR_EACH(mrouter, mrouter_node, &ofproto->ms->mrouter_lru) {
4461         char name[OFP_MAX_PORT_NAME_LEN];
4462
4463         bundle = mrouter->port;
4464         ofputil_port_to_string(ofbundle_get_a_port(bundle)->up.ofp_port,
4465                                name, sizeof name);
4466             ds_put_format(&ds, "%5s  %4d  querier             %3d\n",
4467                       name, mrouter->vlan,
4468                       mcast_mrouter_age(ofproto->ms, mrouter));
4469     }
4470     ovs_rwlock_unlock(&ofproto->ms->rwlock);
4471     unixctl_command_reply(conn, ds_cstr(&ds));
4472     ds_destroy(&ds);
4473 }
4474
4475 struct trace_ctx {
4476     struct xlate_out xout;
4477     struct xlate_in xin;
4478     const struct flow *key;
4479     struct flow flow;
4480     struct flow_wildcards wc;
4481     struct ds *result;
4482 };
4483
4484 static void
4485 trace_format_rule(struct ds *result, int level, const struct rule_dpif *rule)
4486 {
4487     const struct rule_actions *actions;
4488     ovs_be64 cookie;
4489
4490     ds_put_char_multiple(result, '\t', level);
4491     if (!rule) {
4492         ds_put_cstr(result, "No match\n");
4493         return;
4494     }
4495
4496     ovs_mutex_lock(&rule->up.mutex);
4497     cookie = rule->up.flow_cookie;
4498     ovs_mutex_unlock(&rule->up.mutex);
4499
4500     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
4501                   rule ? rule->up.table_id : 0, ntohll(cookie));
4502     cls_rule_format(&rule->up.cr, result);
4503     ds_put_char(result, '\n');
4504
4505     actions = rule_dpif_get_actions(rule);
4506
4507     ds_put_char_multiple(result, '\t', level);
4508     ds_put_cstr(result, "OpenFlow actions=");
4509     ofpacts_format(actions->ofpacts, actions->ofpacts_len, result);
4510     ds_put_char(result, '\n');
4511 }
4512
4513 static void
4514 trace_format_flow(struct ds *result, int level, const char *title,
4515                   struct trace_ctx *trace)
4516 {
4517     ds_put_char_multiple(result, '\t', level);
4518     ds_put_format(result, "%s: ", title);
4519     /* Do not report unchanged flows for resubmits. */
4520     if ((level > 0 && flow_equal(&trace->xin.flow, &trace->flow))
4521         || (level == 0 && flow_equal(&trace->xin.flow, trace->key))) {
4522         ds_put_cstr(result, "unchanged");
4523     } else {
4524         flow_format(result, &trace->xin.flow);
4525         trace->flow = trace->xin.flow;
4526     }
4527     ds_put_char(result, '\n');
4528 }
4529
4530 static void
4531 trace_format_regs(struct ds *result, int level, const char *title,
4532                   struct trace_ctx *trace)
4533 {
4534     size_t i;
4535
4536     ds_put_char_multiple(result, '\t', level);
4537     ds_put_format(result, "%s:", title);
4538     for (i = 0; i < FLOW_N_REGS; i++) {
4539         ds_put_format(result, " reg%"PRIuSIZE"=0x%"PRIx32, i, trace->flow.regs[i]);
4540     }
4541     ds_put_char(result, '\n');
4542 }
4543
4544 static void
4545 trace_format_odp(struct ds *result, int level, const char *title,
4546                  struct trace_ctx *trace)
4547 {
4548     struct ofpbuf *odp_actions = trace->xout.odp_actions;
4549
4550     ds_put_char_multiple(result, '\t', level);
4551     ds_put_format(result, "%s: ", title);
4552     format_odp_actions(result, odp_actions->data, odp_actions->size);
4553     ds_put_char(result, '\n');
4554 }
4555
4556 static void
4557 trace_format_megaflow(struct ds *result, int level, const char *title,
4558                       struct trace_ctx *trace)
4559 {
4560     struct match match;
4561
4562     ds_put_char_multiple(result, '\t', level);
4563     ds_put_format(result, "%s: ", title);
4564     flow_wildcards_or(&trace->wc, &trace->xout.wc, &trace->wc);
4565     match_init(&match, trace->key, &trace->wc);
4566     match_format(&match, result, OFP_DEFAULT_PRIORITY);
4567     ds_put_char(result, '\n');
4568 }
4569
4570 static void trace_report(struct xlate_in *xin, const char *s, int recurse);
4571
4572 static void
4573 trace_resubmit(struct xlate_in *xin, struct rule_dpif *rule, int recurse)
4574 {
4575     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
4576     struct ds *result = trace->result;
4577
4578     if (!recurse) {
4579         if (rule == xin->ofproto->miss_rule) {
4580             trace_report(xin, "No match, flow generates \"packet in\"s.",
4581                          recurse);
4582         } else if (rule == xin->ofproto->no_packet_in_rule) {
4583             trace_report(xin, "No match, packets dropped because "
4584                          "OFPPC_NO_PACKET_IN is set on in_port.", recurse);
4585         } else if (rule == xin->ofproto->drop_frags_rule) {
4586             trace_report(xin, "Packets dropped because they are IP "
4587                          "fragments and the fragment handling mode is "
4588                          "\"drop\".", recurse);
4589         }
4590     }
4591
4592     ds_put_char(result, '\n');
4593     if (recurse) {
4594         trace_format_flow(result, recurse, "Resubmitted flow", trace);
4595         trace_format_regs(result, recurse, "Resubmitted regs", trace);
4596         trace_format_odp(result,  recurse, "Resubmitted  odp", trace);
4597         trace_format_megaflow(result, recurse, "Resubmitted megaflow", trace);
4598     }
4599     trace_format_rule(result, recurse, rule);
4600 }
4601
4602 static void
4603 trace_report(struct xlate_in *xin, const char *s, int recurse)
4604 {
4605     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
4606     struct ds *result = trace->result;
4607
4608     ds_put_char_multiple(result, '\t', recurse);
4609     ds_put_cstr(result, s);
4610     ds_put_char(result, '\n');
4611 }
4612
4613 /* Parses the 'argc' elements of 'argv', ignoring argv[0].  The following
4614  * forms are supported:
4615  *
4616  *     - [dpname] odp_flow [-generate | packet]
4617  *     - bridge br_flow [-generate | packet]
4618  *
4619  * On success, initializes '*ofprotop' and 'flow' and returns NULL.  On failure
4620  * returns a nonnull malloced error message. */
4621 static char * OVS_WARN_UNUSED_RESULT
4622 parse_flow_and_packet(int argc, const char *argv[],
4623                       struct ofproto_dpif **ofprotop, struct flow *flow,
4624                       struct dp_packet **packetp)
4625 {
4626     const struct dpif_backer *backer = NULL;
4627     const char *error = NULL;
4628     char *m_err = NULL;
4629     struct simap port_names = SIMAP_INITIALIZER(&port_names);
4630     struct dp_packet *packet;
4631     struct ofpbuf odp_key;
4632     struct ofpbuf odp_mask;
4633
4634     ofpbuf_init(&odp_key, 0);
4635     ofpbuf_init(&odp_mask, 0);
4636
4637     /* Handle "-generate" or a hex string as the last argument. */
4638     if (!strcmp(argv[argc - 1], "-generate")) {
4639         packet = dp_packet_new(0);
4640         argc--;
4641     } else {
4642         error = eth_from_hex(argv[argc - 1], &packet);
4643         if (!error) {
4644             argc--;
4645         } else if (argc == 4) {
4646             /* The 3-argument form must end in "-generate' or a hex string. */
4647             goto exit;
4648         }
4649         error = NULL;
4650     }
4651
4652     /* odp_flow can have its in_port specified as a name instead of port no.
4653      * We do not yet know whether a given flow is a odp_flow or a br_flow.
4654      * But, to know whether a flow is odp_flow through odp_flow_from_string(),
4655      * we need to create a simap of name to port no. */
4656     if (argc == 3) {
4657         const char *dp_type;
4658         if (!strncmp(argv[1], "ovs-", 4)) {
4659             dp_type = argv[1] + 4;
4660         } else {
4661             dp_type = argv[1];
4662         }
4663         backer = shash_find_data(&all_dpif_backers, dp_type);
4664     } else if (argc == 2) {
4665         struct shash_node *node;
4666         if (shash_count(&all_dpif_backers) == 1) {
4667             node = shash_first(&all_dpif_backers);
4668             backer = node->data;
4669         }
4670     } else {
4671         error = "Syntax error";
4672         goto exit;
4673     }
4674     if (backer && backer->dpif) {
4675         struct dpif_port dpif_port;
4676         struct dpif_port_dump port_dump;
4677         DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, backer->dpif) {
4678             simap_put(&port_names, dpif_port.name,
4679                       odp_to_u32(dpif_port.port_no));
4680         }
4681     }
4682
4683     /* Parse the flow and determine whether a datapath or
4684      * bridge is specified. If function odp_flow_key_from_string()
4685      * returns 0, the flow is a odp_flow. If function
4686      * parse_ofp_exact_flow() returns NULL, the flow is a br_flow. */
4687     if (!odp_flow_from_string(argv[argc - 1], &port_names,
4688                               &odp_key, &odp_mask)) {
4689         if (!backer) {
4690             error = "Cannot find the datapath";
4691             goto exit;
4692         }
4693
4694         if (odp_flow_key_to_flow(odp_key.data, odp_key.size, flow) == ODP_FIT_ERROR) {
4695             error = "Failed to parse datapath flow key";
4696             goto exit;
4697         }
4698
4699         *ofprotop = xlate_lookup_ofproto(backer, flow,
4700                                          &flow->in_port.ofp_port);
4701         if (*ofprotop == NULL) {
4702             error = "Invalid datapath flow";
4703             goto exit;
4704         }
4705
4706         vsp_adjust_flow(*ofprotop, flow, NULL);
4707
4708     } else {
4709         char *err = parse_ofp_exact_flow(flow, NULL, argv[argc - 1], NULL);
4710
4711         if (err) {
4712             m_err = xasprintf("Bad openflow flow syntax: %s", err);
4713             free(err);
4714             goto exit;
4715         } else {
4716             if (argc != 3) {
4717                 error = "Must specify bridge name";
4718                 goto exit;
4719             }
4720
4721             *ofprotop = ofproto_dpif_lookup(argv[1]);
4722             if (!*ofprotop) {
4723                 error = "Unknown bridge name";
4724                 goto exit;
4725             }
4726         }
4727     }
4728
4729     /* Generate a packet, if requested. */
4730     if (packet) {
4731         if (!dp_packet_size(packet)) {
4732             flow_compose(packet, flow);
4733         } else {
4734             /* Use the metadata from the flow and the packet argument
4735              * to reconstruct the flow. */
4736             pkt_metadata_from_flow(&packet->md, flow);
4737             flow_extract(packet, flow);
4738         }
4739     }
4740
4741 exit:
4742     if (error && !m_err) {
4743         m_err = xstrdup(error);
4744     }
4745     if (m_err) {
4746         dp_packet_delete(packet);
4747         packet = NULL;
4748     }
4749     *packetp = packet;
4750     ofpbuf_uninit(&odp_key);
4751     ofpbuf_uninit(&odp_mask);
4752     simap_destroy(&port_names);
4753     return m_err;
4754 }
4755
4756 static void
4757 ofproto_unixctl_trace(struct unixctl_conn *conn, int argc, const char *argv[],
4758                       void *aux OVS_UNUSED)
4759 {
4760     struct ofproto_dpif *ofproto;
4761     struct dp_packet *packet;
4762     char *error;
4763     struct flow flow;
4764
4765     error = parse_flow_and_packet(argc, argv, &ofproto, &flow, &packet);
4766     if (!error) {
4767         struct ds result;
4768
4769         ds_init(&result);
4770         ofproto_trace(ofproto, &flow, packet, NULL, 0, &result);
4771         unixctl_command_reply(conn, ds_cstr(&result));
4772         ds_destroy(&result);
4773         dp_packet_delete(packet);
4774     } else {
4775         unixctl_command_reply_error(conn, error);
4776         free(error);
4777     }
4778 }
4779
4780 static void
4781 ofproto_unixctl_trace_actions(struct unixctl_conn *conn, int argc,
4782                               const char *argv[], void *aux OVS_UNUSED)
4783 {
4784     enum ofputil_protocol usable_protocols;
4785     struct ofproto_dpif *ofproto;
4786     bool enforce_consistency;
4787     struct ofpbuf ofpacts;
4788     struct dp_packet *packet;
4789     struct ds result;
4790     struct flow flow;
4791     uint16_t in_port;
4792
4793     /* Three kinds of error return values! */
4794     enum ofperr retval;
4795     char *error;
4796
4797     packet = NULL;
4798     ds_init(&result);
4799     ofpbuf_init(&ofpacts, 0);
4800
4801     /* Parse actions. */
4802     error = ofpacts_parse_actions(argv[--argc], &ofpacts, &usable_protocols);
4803     if (error) {
4804         unixctl_command_reply_error(conn, error);
4805         free(error);
4806         goto exit;
4807     }
4808
4809     /* OpenFlow 1.1 and later suggest that the switch enforces certain forms of
4810      * consistency between the flow and the actions.  With -consistent, we
4811      * enforce consistency even for a flow supported in OpenFlow 1.0. */
4812     if (!strcmp(argv[1], "-consistent")) {
4813         enforce_consistency = true;
4814         argv++;
4815         argc--;
4816     } else {
4817         enforce_consistency = false;
4818     }
4819
4820     error = parse_flow_and_packet(argc, argv, &ofproto, &flow, &packet);
4821     if (error) {
4822         unixctl_command_reply_error(conn, error);
4823         free(error);
4824         goto exit;
4825     }
4826
4827     /* Do the same checks as handle_packet_out() in ofproto.c.
4828      *
4829      * We pass a 'table_id' of 0 to ofpacts_check(), which isn't
4830      * strictly correct because these actions aren't in any table, but it's OK
4831      * because it 'table_id' is used only to check goto_table instructions, but
4832      * packet-outs take a list of actions and therefore it can't include
4833      * instructions.
4834      *
4835      * We skip the "meter" check here because meter is an instruction, not an
4836      * action, and thus cannot appear in ofpacts. */
4837     in_port = ofp_to_u16(flow.in_port.ofp_port);
4838     if (in_port >= ofproto->up.max_ports && in_port < ofp_to_u16(OFPP_MAX)) {
4839         unixctl_command_reply_error(conn, "invalid in_port");
4840         goto exit;
4841     }
4842     if (enforce_consistency) {
4843         retval = ofpacts_check_consistency(ofpacts.data, ofpacts.size,
4844                                            &flow, u16_to_ofp(ofproto->up.max_ports),
4845                                            0, 0, usable_protocols);
4846     } else {
4847         retval = ofpacts_check(ofpacts.data, ofpacts.size, &flow,
4848                                u16_to_ofp(ofproto->up.max_ports), 0, 0,
4849                                &usable_protocols);
4850     }
4851
4852     if (retval) {
4853         ds_clear(&result);
4854         ds_put_format(&result, "Bad actions: %s", ofperr_to_string(retval));
4855         unixctl_command_reply_error(conn, ds_cstr(&result));
4856         goto exit;
4857     }
4858
4859     ofproto_trace(ofproto, &flow, packet,
4860                   ofpacts.data, ofpacts.size, &result);
4861     unixctl_command_reply(conn, ds_cstr(&result));
4862
4863 exit:
4864     ds_destroy(&result);
4865     dp_packet_delete(packet);
4866     ofpbuf_uninit(&ofpacts);
4867 }
4868
4869 /* Implements a "trace" through 'ofproto''s flow table, appending a textual
4870  * description of the results to 'ds'.
4871  *
4872  * The trace follows a packet with the specified 'flow' through the flow
4873  * table.  'packet' may be nonnull to trace an actual packet, with consequent
4874  * side effects (if it is nonnull then its flow must be 'flow').
4875  *
4876  * If 'ofpacts' is nonnull then its 'ofpacts_len' bytes specify the actions to
4877  * trace, otherwise the actions are determined by a flow table lookup. */
4878 static void
4879 ofproto_trace(struct ofproto_dpif *ofproto, struct flow *flow,
4880               const struct dp_packet *packet,
4881               const struct ofpact ofpacts[], size_t ofpacts_len,
4882               struct ds *ds)
4883 {
4884     struct trace_ctx trace;
4885
4886     ds_put_format(ds, "Bridge: %s\n", ofproto->up.name);
4887     ds_put_cstr(ds, "Flow: ");
4888     flow_format(ds, flow);
4889     ds_put_char(ds, '\n');
4890
4891     flow_wildcards_init_catchall(&trace.wc);
4892
4893     trace.result = ds;
4894     trace.key = flow; /* Original flow key, used for megaflow. */
4895     trace.flow = *flow; /* May be modified by actions. */
4896     xlate_in_init(&trace.xin, ofproto, flow, flow->in_port.ofp_port, NULL,
4897                   ntohs(flow->tcp_flags), packet);
4898     trace.xin.ofpacts = ofpacts;
4899     trace.xin.ofpacts_len = ofpacts_len;
4900     trace.xin.resubmit_hook = trace_resubmit;
4901     trace.xin.report_hook = trace_report;
4902
4903     xlate_actions(&trace.xin, &trace.xout);
4904
4905     ds_put_char(ds, '\n');
4906     trace_format_flow(ds, 0, "Final flow", &trace);
4907     trace_format_megaflow(ds, 0, "Megaflow", &trace);
4908
4909     ds_put_cstr(ds, "Datapath actions: ");
4910     format_odp_actions(ds, trace.xout.odp_actions->data,
4911                        trace.xout.odp_actions->size);
4912
4913     if (trace.xout.slow) {
4914         enum slow_path_reason slow;
4915
4916         ds_put_cstr(ds, "\nThis flow is handled by the userspace "
4917                     "slow path because it:");
4918
4919         slow = trace.xout.slow;
4920         while (slow) {
4921             enum slow_path_reason bit = rightmost_1bit(slow);
4922
4923             ds_put_format(ds, "\n\t- %s.",
4924                           slow_path_reason_to_explanation(bit));
4925
4926             slow &= ~bit;
4927         }
4928     }
4929
4930     xlate_out_uninit(&trace.xout);
4931 }
4932
4933 /* Store the current ofprotos in 'ofproto_shash'.  Returns a sorted list
4934  * of the 'ofproto_shash' nodes.  It is the responsibility of the caller
4935  * to destroy 'ofproto_shash' and free the returned value. */
4936 static const struct shash_node **
4937 get_ofprotos(struct shash *ofproto_shash)
4938 {
4939     const struct ofproto_dpif *ofproto;
4940
4941     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4942         char *name = xasprintf("%s@%s", ofproto->up.type, ofproto->up.name);
4943         shash_add_nocopy(ofproto_shash, name, ofproto);
4944     }
4945
4946     return shash_sort(ofproto_shash);
4947 }
4948
4949 static void
4950 ofproto_unixctl_dpif_dump_dps(struct unixctl_conn *conn, int argc OVS_UNUSED,
4951                               const char *argv[] OVS_UNUSED,
4952                               void *aux OVS_UNUSED)
4953 {
4954     struct ds ds = DS_EMPTY_INITIALIZER;
4955     struct shash ofproto_shash;
4956     const struct shash_node **sorted_ofprotos;
4957     int i;
4958
4959     shash_init(&ofproto_shash);
4960     sorted_ofprotos = get_ofprotos(&ofproto_shash);
4961     for (i = 0; i < shash_count(&ofproto_shash); i++) {
4962         const struct shash_node *node = sorted_ofprotos[i];
4963         ds_put_format(&ds, "%s\n", node->name);
4964     }
4965
4966     shash_destroy(&ofproto_shash);
4967     free(sorted_ofprotos);
4968
4969     unixctl_command_reply(conn, ds_cstr(&ds));
4970     ds_destroy(&ds);
4971 }
4972
4973 static void
4974 dpif_show_backer(const struct dpif_backer *backer, struct ds *ds)
4975 {
4976     const struct shash_node **ofprotos;
4977     struct dpif_dp_stats dp_stats;
4978     struct shash ofproto_shash;
4979     size_t i;
4980
4981     dpif_get_dp_stats(backer->dpif, &dp_stats);
4982
4983     ds_put_format(ds, "%s: hit:%"PRIu64" missed:%"PRIu64"\n",
4984                   dpif_name(backer->dpif), dp_stats.n_hit, dp_stats.n_missed);
4985
4986     shash_init(&ofproto_shash);
4987     ofprotos = get_ofprotos(&ofproto_shash);
4988     for (i = 0; i < shash_count(&ofproto_shash); i++) {
4989         struct ofproto_dpif *ofproto = ofprotos[i]->data;
4990         const struct shash_node **ports;
4991         size_t j;
4992
4993         if (ofproto->backer != backer) {
4994             continue;
4995         }
4996
4997         ds_put_format(ds, "\t%s:\n", ofproto->up.name);
4998
4999         ports = shash_sort(&ofproto->up.port_by_name);
5000         for (j = 0; j < shash_count(&ofproto->up.port_by_name); j++) {
5001             const struct shash_node *node = ports[j];
5002             struct ofport *ofport = node->data;
5003             struct smap config;
5004             odp_port_t odp_port;
5005
5006             ds_put_format(ds, "\t\t%s %u/", netdev_get_name(ofport->netdev),
5007                           ofport->ofp_port);
5008
5009             odp_port = ofp_port_to_odp_port(ofproto, ofport->ofp_port);
5010             if (odp_port != ODPP_NONE) {
5011                 ds_put_format(ds, "%"PRIu32":", odp_port);
5012             } else {
5013                 ds_put_cstr(ds, "none:");
5014             }
5015
5016             ds_put_format(ds, " (%s", netdev_get_type(ofport->netdev));
5017
5018             smap_init(&config);
5019             if (!netdev_get_config(ofport->netdev, &config)) {
5020                 const struct smap_node **nodes;
5021                 size_t i;
5022
5023                 nodes = smap_sort(&config);
5024                 for (i = 0; i < smap_count(&config); i++) {
5025                     const struct smap_node *node = nodes[i];
5026                     ds_put_format(ds, "%c %s=%s", i ? ',' : ':',
5027                                   node->key, node->value);
5028                 }
5029                 free(nodes);
5030             }
5031             smap_destroy(&config);
5032
5033             ds_put_char(ds, ')');
5034             ds_put_char(ds, '\n');
5035         }
5036         free(ports);
5037     }
5038     shash_destroy(&ofproto_shash);
5039     free(ofprotos);
5040 }
5041
5042 static void
5043 ofproto_unixctl_dpif_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
5044                           const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
5045 {
5046     struct ds ds = DS_EMPTY_INITIALIZER;
5047     const struct shash_node **backers;
5048     int i;
5049
5050     backers = shash_sort(&all_dpif_backers);
5051     for (i = 0; i < shash_count(&all_dpif_backers); i++) {
5052         dpif_show_backer(backers[i]->data, &ds);
5053     }
5054     free(backers);
5055
5056     unixctl_command_reply(conn, ds_cstr(&ds));
5057     ds_destroy(&ds);
5058 }
5059
5060 static void
5061 ofproto_unixctl_dpif_dump_flows(struct unixctl_conn *conn,
5062                                 int argc OVS_UNUSED, const char *argv[],
5063                                 void *aux OVS_UNUSED)
5064 {
5065     const struct ofproto_dpif *ofproto;
5066
5067     struct ds ds = DS_EMPTY_INITIALIZER;
5068     bool verbosity = false;
5069
5070     struct dpif_port dpif_port;
5071     struct dpif_port_dump port_dump;
5072     struct hmap portno_names;
5073
5074     struct dpif_flow_dump *flow_dump;
5075     struct dpif_flow_dump_thread *flow_dump_thread;
5076     struct dpif_flow f;
5077     int error;
5078
5079     ofproto = ofproto_dpif_lookup(argv[argc - 1]);
5080     if (!ofproto) {
5081         unixctl_command_reply_error(conn, "no such bridge");
5082         return;
5083     }
5084
5085     if (argc > 2 && !strcmp(argv[1], "-m")) {
5086         verbosity = true;
5087     }
5088
5089     hmap_init(&portno_names);
5090     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, ofproto->backer->dpif) {
5091         odp_portno_names_set(&portno_names, dpif_port.port_no, dpif_port.name);
5092     }
5093
5094     ds_init(&ds);
5095     flow_dump = dpif_flow_dump_create(ofproto->backer->dpif, false);
5096     flow_dump_thread = dpif_flow_dump_thread_create(flow_dump);
5097     while (dpif_flow_dump_next(flow_dump_thread, &f, 1)) {
5098         struct flow flow;
5099
5100         if (odp_flow_key_to_flow(f.key, f.key_len, &flow) == ODP_FIT_ERROR
5101             || xlate_lookup_ofproto(ofproto->backer, &flow, NULL) != ofproto) {
5102             continue;
5103         }
5104
5105         if (verbosity) {
5106             odp_format_ufid(&f.ufid, &ds);
5107             ds_put_cstr(&ds, " ");
5108         }
5109         odp_flow_format(f.key, f.key_len, f.mask, f.mask_len,
5110                         &portno_names, &ds, verbosity);
5111         ds_put_cstr(&ds, ", ");
5112         dpif_flow_stats_format(&f.stats, &ds);
5113         ds_put_cstr(&ds, ", actions:");
5114         format_odp_actions(&ds, f.actions, f.actions_len);
5115         ds_put_char(&ds, '\n');
5116     }
5117     dpif_flow_dump_thread_destroy(flow_dump_thread);
5118     error = dpif_flow_dump_destroy(flow_dump);
5119
5120     if (error) {
5121         ds_clear(&ds);
5122         ds_put_format(&ds, "dpif/dump_flows failed: %s", ovs_strerror(errno));
5123         unixctl_command_reply_error(conn, ds_cstr(&ds));
5124     } else {
5125         unixctl_command_reply(conn, ds_cstr(&ds));
5126     }
5127     odp_portno_names_destroy(&portno_names);
5128     hmap_destroy(&portno_names);
5129     ds_destroy(&ds);
5130 }
5131
5132 static void
5133 ofproto_revalidate_all_backers(void)
5134 {
5135     const struct shash_node **backers;
5136     int i;
5137
5138     backers = shash_sort(&all_dpif_backers);
5139     for (i = 0; i < shash_count(&all_dpif_backers); i++) {
5140         struct dpif_backer *backer = backers[i]->data;
5141         backer->need_revalidate = REV_RECONFIGURE;
5142     }
5143     free(backers);
5144 }
5145
5146 static void
5147 disable_tnl_push_pop(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
5148                      const char *argv[], void *aux OVS_UNUSED)
5149 {
5150     if (!strcasecmp(argv[1], "off")) {
5151         ofproto_use_tnl_push_pop = false;
5152         unixctl_command_reply(conn, "Tunnel push-pop off");
5153         ofproto_revalidate_all_backers();
5154     } else if (!strcasecmp(argv[1], "on")) {
5155         ofproto_use_tnl_push_pop = true;
5156         unixctl_command_reply(conn, "Tunnel push-pop on");
5157         ofproto_revalidate_all_backers();
5158     }
5159 }
5160
5161 static void
5162 ofproto_unixctl_init(void)
5163 {
5164     static bool registered;
5165     if (registered) {
5166         return;
5167     }
5168     registered = true;
5169
5170     unixctl_command_register(
5171         "ofproto/trace",
5172         "{[dp_name] odp_flow | bridge br_flow} [-generate|packet]",
5173         1, 3, ofproto_unixctl_trace, NULL);
5174     unixctl_command_register(
5175         "ofproto/trace-packet-out",
5176         "[-consistent] {[dp_name] odp_flow | bridge br_flow} [-generate|packet] actions",
5177         2, 6, ofproto_unixctl_trace_actions, NULL);
5178     unixctl_command_register("fdb/flush", "[bridge]", 0, 1,
5179                              ofproto_unixctl_fdb_flush, NULL);
5180     unixctl_command_register("fdb/show", "bridge", 1, 1,
5181                              ofproto_unixctl_fdb_show, NULL);
5182     unixctl_command_register("mdb/flush", "[bridge]", 0, 1,
5183                              ofproto_unixctl_mcast_snooping_flush, NULL);
5184     unixctl_command_register("mdb/show", "bridge", 1, 1,
5185                              ofproto_unixctl_mcast_snooping_show, NULL);
5186     unixctl_command_register("dpif/dump-dps", "", 0, 0,
5187                              ofproto_unixctl_dpif_dump_dps, NULL);
5188     unixctl_command_register("dpif/show", "", 0, 0, ofproto_unixctl_dpif_show,
5189                              NULL);
5190     unixctl_command_register("dpif/dump-flows", "[-m] bridge", 1, 2,
5191                              ofproto_unixctl_dpif_dump_flows, NULL);
5192
5193     unixctl_command_register("ofproto/tnl-push-pop", "[on]|[off]", 1, 1,
5194                              disable_tnl_push_pop, NULL);
5195 }
5196
5197 /* Returns true if 'table' is the table used for internal rules,
5198  * false otherwise. */
5199 bool
5200 table_is_internal(uint8_t table_id)
5201 {
5202     return table_id == TBL_INTERNAL;
5203 }
5204 \f
5205 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
5206  *
5207  * This is deprecated.  It is only for compatibility with broken device drivers
5208  * in old versions of Linux that do not properly support VLANs when VLAN
5209  * devices are not used.  When broken device drivers are no longer in
5210  * widespread use, we will delete these interfaces. */
5211
5212 static int
5213 set_realdev(struct ofport *ofport_, ofp_port_t realdev_ofp_port, int vid)
5214 {
5215     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
5216     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
5217
5218     if (realdev_ofp_port == ofport->realdev_ofp_port
5219         && vid == ofport->vlandev_vid) {
5220         return 0;
5221     }
5222
5223     ofproto->backer->need_revalidate = REV_RECONFIGURE;
5224
5225     if (ofport->realdev_ofp_port) {
5226         vsp_remove(ofport);
5227     }
5228     if (realdev_ofp_port && ofport->bundle) {
5229         /* vlandevs are enslaved to their realdevs, so they are not allowed to
5230          * themselves be part of a bundle. */
5231         bundle_set(ofport_->ofproto, ofport->bundle, NULL);
5232     }
5233
5234     ofport->realdev_ofp_port = realdev_ofp_port;
5235     ofport->vlandev_vid = vid;
5236
5237     if (realdev_ofp_port) {
5238         vsp_add(ofport, realdev_ofp_port, vid);
5239     }
5240
5241     return 0;
5242 }
5243
5244 static uint32_t
5245 hash_realdev_vid(ofp_port_t realdev_ofp_port, int vid)
5246 {
5247     return hash_2words(ofp_to_u16(realdev_ofp_port), vid);
5248 }
5249
5250 bool
5251 ofproto_has_vlan_splinters(const struct ofproto_dpif *ofproto)
5252     OVS_EXCLUDED(ofproto->vsp_mutex)
5253 {
5254     /* hmap_is_empty is thread safe. */
5255     return !hmap_is_empty(&ofproto->realdev_vid_map);
5256 }
5257
5258
5259 static ofp_port_t
5260 vsp_realdev_to_vlandev__(const struct ofproto_dpif *ofproto,
5261                          ofp_port_t realdev_ofp_port, ovs_be16 vlan_tci)
5262     OVS_REQUIRES(ofproto->vsp_mutex)
5263 {
5264     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
5265         int vid = vlan_tci_to_vid(vlan_tci);
5266         const struct vlan_splinter *vsp;
5267
5268         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
5269                                  hash_realdev_vid(realdev_ofp_port, vid),
5270                                  &ofproto->realdev_vid_map) {
5271             if (vsp->realdev_ofp_port == realdev_ofp_port
5272                 && vsp->vid == vid) {
5273                 return vsp->vlandev_ofp_port;
5274             }
5275         }
5276     }
5277     return realdev_ofp_port;
5278 }
5279
5280 /* Returns the OFP port number of the Linux VLAN device that corresponds to
5281  * 'vlan_tci' on the network device with port number 'realdev_ofp_port' in
5282  * 'struct ofport_dpif'.  For example, given 'realdev_ofp_port' of eth0 and
5283  * 'vlan_tci' 9, it would return the port number of eth0.9.
5284  *
5285  * Unless VLAN splinters are enabled for port 'realdev_ofp_port', this
5286  * function just returns its 'realdev_ofp_port' argument. */
5287 ofp_port_t
5288 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
5289                        ofp_port_t realdev_ofp_port, ovs_be16 vlan_tci)
5290     OVS_EXCLUDED(ofproto->vsp_mutex)
5291 {
5292     ofp_port_t ret;
5293
5294     /* hmap_is_empty is thread safe, see if we can return immediately. */
5295     if (hmap_is_empty(&ofproto->realdev_vid_map)) {
5296         return realdev_ofp_port;
5297     }
5298     ovs_mutex_lock(&ofproto->vsp_mutex);
5299     ret = vsp_realdev_to_vlandev__(ofproto, realdev_ofp_port, vlan_tci);
5300     ovs_mutex_unlock(&ofproto->vsp_mutex);
5301     return ret;
5302 }
5303
5304 static struct vlan_splinter *
5305 vlandev_find(const struct ofproto_dpif *ofproto, ofp_port_t vlandev_ofp_port)
5306 {
5307     struct vlan_splinter *vsp;
5308
5309     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node,
5310                              hash_ofp_port(vlandev_ofp_port),
5311                              &ofproto->vlandev_map) {
5312         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
5313             return vsp;
5314         }
5315     }
5316
5317     return NULL;
5318 }
5319
5320 /* Returns the OpenFlow port number of the "real" device underlying the Linux
5321  * VLAN device with OpenFlow port number 'vlandev_ofp_port' and stores the
5322  * VLAN VID of the Linux VLAN device in '*vid'.  For example, given
5323  * 'vlandev_ofp_port' of eth0.9, it would return the OpenFlow port number of
5324  * eth0 and store 9 in '*vid'.
5325  *
5326  * Returns 0 and does not modify '*vid' if 'vlandev_ofp_port' is not a Linux
5327  * VLAN device.  Unless VLAN splinters are enabled, this is what this function
5328  * always does.*/
5329 static ofp_port_t
5330 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
5331                        ofp_port_t vlandev_ofp_port, int *vid)
5332     OVS_REQUIRES(ofproto->vsp_mutex)
5333 {
5334     if (!hmap_is_empty(&ofproto->vlandev_map)) {
5335         const struct vlan_splinter *vsp;
5336
5337         vsp = vlandev_find(ofproto, vlandev_ofp_port);
5338         if (vsp) {
5339             if (vid) {
5340                 *vid = vsp->vid;
5341             }
5342             return vsp->realdev_ofp_port;
5343         }
5344     }
5345     return 0;
5346 }
5347
5348 /* Given 'flow', a flow representing a packet received on 'ofproto', checks
5349  * whether 'flow->in_port' represents a Linux VLAN device.  If so, changes
5350  * 'flow->in_port' to the "real" device backing the VLAN device, sets
5351  * 'flow->vlan_tci' to the VLAN VID, and returns true.  Optionally pushes the
5352  * appropriate VLAN on 'packet' if provided.  Otherwise (which is always the
5353  * case unless VLAN splinters are enabled), returns false without making any
5354  * changes. */
5355 bool
5356 vsp_adjust_flow(const struct ofproto_dpif *ofproto, struct flow *flow,
5357                 struct dp_packet *packet)
5358     OVS_EXCLUDED(ofproto->vsp_mutex)
5359 {
5360     ofp_port_t realdev;
5361     int vid;
5362
5363     /* hmap_is_empty is thread safe. */
5364     if (hmap_is_empty(&ofproto->vlandev_map)) {
5365         return false;
5366     }
5367
5368     ovs_mutex_lock(&ofproto->vsp_mutex);
5369     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port.ofp_port, &vid);
5370     ovs_mutex_unlock(&ofproto->vsp_mutex);
5371     if (!realdev) {
5372         return false;
5373     }
5374
5375     /* Cause the flow to be processed as if it came in on the real device with
5376      * the VLAN device's VLAN ID. */
5377     flow->in_port.ofp_port = realdev;
5378     flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
5379
5380     if (packet) {
5381         /* Make the packet resemble the flow, so that it gets sent to an
5382          * OpenFlow controller properly, so that it looks correct for sFlow,
5383          * and so that flow_extract() will get the correct vlan_tci if it is
5384          * called on 'packet'. */
5385         eth_push_vlan(packet, htons(ETH_TYPE_VLAN), flow->vlan_tci);
5386     }
5387
5388     return true;
5389 }
5390
5391 static void
5392 vsp_remove(struct ofport_dpif *port)
5393 {
5394     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
5395     struct vlan_splinter *vsp;
5396
5397     ovs_mutex_lock(&ofproto->vsp_mutex);
5398     vsp = vlandev_find(ofproto, port->up.ofp_port);
5399     if (vsp) {
5400         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
5401         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
5402         free(vsp);
5403
5404         port->realdev_ofp_port = 0;
5405     } else {
5406         VLOG_ERR("missing vlan device record");
5407     }
5408     ovs_mutex_unlock(&ofproto->vsp_mutex);
5409 }
5410
5411 static void
5412 vsp_add(struct ofport_dpif *port, ofp_port_t realdev_ofp_port, int vid)
5413 {
5414     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
5415
5416     ovs_mutex_lock(&ofproto->vsp_mutex);
5417     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
5418         && (vsp_realdev_to_vlandev__(ofproto, realdev_ofp_port, htons(vid))
5419             == realdev_ofp_port)) {
5420         struct vlan_splinter *vsp;
5421
5422         vsp = xmalloc(sizeof *vsp);
5423         vsp->realdev_ofp_port = realdev_ofp_port;
5424         vsp->vlandev_ofp_port = port->up.ofp_port;
5425         vsp->vid = vid;
5426
5427         port->realdev_ofp_port = realdev_ofp_port;
5428
5429         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
5430                     hash_ofp_port(port->up.ofp_port));
5431         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
5432                     hash_realdev_vid(realdev_ofp_port, vid));
5433     } else {
5434         VLOG_ERR("duplicate vlan device record");
5435     }
5436     ovs_mutex_unlock(&ofproto->vsp_mutex);
5437 }
5438
5439 static odp_port_t
5440 ofp_port_to_odp_port(const struct ofproto_dpif *ofproto, ofp_port_t ofp_port)
5441 {
5442     const struct ofport_dpif *ofport = ofp_port_to_ofport(ofproto, ofp_port);
5443     return ofport ? ofport->odp_port : ODPP_NONE;
5444 }
5445
5446 struct ofport_dpif *
5447 odp_port_to_ofport(const struct dpif_backer *backer, odp_port_t odp_port)
5448 {
5449     struct ofport_dpif *port;
5450
5451     ovs_rwlock_rdlock(&backer->odp_to_ofport_lock);
5452     HMAP_FOR_EACH_IN_BUCKET (port, odp_port_node, hash_odp_port(odp_port),
5453                              &backer->odp_to_ofport_map) {
5454         if (port->odp_port == odp_port) {
5455             ovs_rwlock_unlock(&backer->odp_to_ofport_lock);
5456             return port;
5457         }
5458     }
5459
5460     ovs_rwlock_unlock(&backer->odp_to_ofport_lock);
5461     return NULL;
5462 }
5463
5464 static ofp_port_t
5465 odp_port_to_ofp_port(const struct ofproto_dpif *ofproto, odp_port_t odp_port)
5466 {
5467     struct ofport_dpif *port;
5468
5469     port = odp_port_to_ofport(ofproto->backer, odp_port);
5470     if (port && &ofproto->up == port->up.ofproto) {
5471         return port->up.ofp_port;
5472     } else {
5473         return OFPP_NONE;
5474     }
5475 }
5476
5477 int
5478 ofproto_dpif_add_internal_flow(struct ofproto_dpif *ofproto,
5479                                const struct match *match, int priority,
5480                                uint16_t idle_timeout,
5481                                const struct ofpbuf *ofpacts,
5482                                struct rule **rulep)
5483 {
5484     struct ofputil_flow_mod fm;
5485     struct rule_dpif *rule;
5486     int error;
5487
5488     fm.match = *match;
5489     fm.priority = priority;
5490     fm.new_cookie = htonll(0);
5491     fm.cookie = htonll(0);
5492     fm.cookie_mask = htonll(0);
5493     fm.modify_cookie = false;
5494     fm.table_id = TBL_INTERNAL;
5495     fm.command = OFPFC_ADD;
5496     fm.idle_timeout = idle_timeout;
5497     fm.hard_timeout = 0;
5498     fm.importance = 0;
5499     fm.buffer_id = 0;
5500     fm.out_port = 0;
5501     fm.flags = OFPUTIL_FF_HIDDEN_FIELDS | OFPUTIL_FF_NO_READONLY;
5502     fm.ofpacts = ofpacts->data;
5503     fm.ofpacts_len = ofpacts->size;
5504
5505     error = ofproto_flow_mod(&ofproto->up, &fm);
5506     if (error) {
5507         VLOG_ERR_RL(&rl, "failed to add internal flow (%s)",
5508                     ofperr_to_string(error));
5509         *rulep = NULL;
5510         return error;
5511     }
5512
5513     rule = rule_dpif_lookup_in_table(ofproto,
5514                                      ofproto_dpif_get_tables_version(ofproto),
5515                                      TBL_INTERNAL, &fm.match.flow,
5516                                      &fm.match.wc, false);
5517     if (rule) {
5518         *rulep = &rule->up;
5519     } else {
5520         OVS_NOT_REACHED();
5521     }
5522     return 0;
5523 }
5524
5525 int
5526 ofproto_dpif_delete_internal_flow(struct ofproto_dpif *ofproto,
5527                                   struct match *match, int priority)
5528 {
5529     struct ofputil_flow_mod fm;
5530     int error;
5531
5532     fm.match = *match;
5533     fm.priority = priority;
5534     fm.new_cookie = htonll(0);
5535     fm.cookie = htonll(0);
5536     fm.cookie_mask = htonll(0);
5537     fm.modify_cookie = false;
5538     fm.table_id = TBL_INTERNAL;
5539     fm.flags = OFPUTIL_FF_HIDDEN_FIELDS | OFPUTIL_FF_NO_READONLY;
5540     fm.command = OFPFC_DELETE_STRICT;
5541
5542     error = ofproto_flow_mod(&ofproto->up, &fm);
5543     if (error) {
5544         VLOG_ERR_RL(&rl, "failed to delete internal flow (%s)",
5545                     ofperr_to_string(error));
5546         return error;
5547     }
5548
5549     return 0;
5550 }
5551
5552 const struct ofproto_class ofproto_dpif_class = {
5553     init,
5554     enumerate_types,
5555     enumerate_names,
5556     del,
5557     port_open_type,
5558     type_run,
5559     type_wait,
5560     alloc,
5561     construct,
5562     destruct,
5563     dealloc,
5564     run,
5565     wait,
5566     NULL,                       /* get_memory_usage. */
5567     type_get_memory_usage,
5568     flush,
5569     query_tables,
5570     set_tables_version,
5571     port_alloc,
5572     port_construct,
5573     port_destruct,
5574     port_dealloc,
5575     port_modified,
5576     port_reconfigured,
5577     port_query_by_name,
5578     port_add,
5579     port_del,
5580     port_get_stats,
5581     port_dump_start,
5582     port_dump_next,
5583     port_dump_done,
5584     port_poll,
5585     port_poll_wait,
5586     port_is_lacp_current,
5587     port_get_lacp_stats,
5588     NULL,                       /* rule_choose_table */
5589     rule_alloc,
5590     rule_construct,
5591     rule_insert,
5592     rule_delete,
5593     rule_destruct,
5594     rule_dealloc,
5595     rule_get_stats,
5596     rule_execute,
5597     set_frag_handling,
5598     packet_out,
5599     set_netflow,
5600     get_netflow_ids,
5601     set_sflow,
5602     set_ipfix,
5603     set_cfm,
5604     cfm_status_changed,
5605     get_cfm_status,
5606     set_lldp,
5607     get_lldp_status,
5608     set_aa,
5609     aa_mapping_set,
5610     aa_mapping_unset,
5611     aa_vlan_get_queued,
5612     aa_vlan_get_queue_size,
5613     set_bfd,
5614     bfd_status_changed,
5615     get_bfd_status,
5616     set_stp,
5617     get_stp_status,
5618     set_stp_port,
5619     get_stp_port_status,
5620     get_stp_port_stats,
5621     set_rstp,
5622     get_rstp_status,
5623     set_rstp_port,
5624     get_rstp_port_status,
5625     set_queues,
5626     bundle_set,
5627     bundle_remove,
5628     mirror_set__,
5629     mirror_get_stats__,
5630     set_flood_vlans,
5631     is_mirror_output_bundle,
5632     forward_bpdu_changed,
5633     set_mac_table_config,
5634     set_mcast_snooping,
5635     set_mcast_snooping_port,
5636     set_realdev,
5637     NULL,                       /* meter_get_features */
5638     NULL,                       /* meter_set */
5639     NULL,                       /* meter_get */
5640     NULL,                       /* meter_del */
5641     group_alloc,                /* group_alloc */
5642     group_construct,            /* group_construct */
5643     group_destruct,             /* group_destruct */
5644     group_dealloc,              /* group_dealloc */
5645     group_modify,               /* group_modify */
5646     group_get_stats,            /* group_get_stats */
5647     get_datapath_version,       /* get_datapath_version */
5648 };