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