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