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