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