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