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