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