dpif: Use explicit packet metadata.
[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 dpif_execute execute;
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 a dummy ethernet packet. */
926     ofpbuf_init(&packet, ETH_HEADER_LEN);
927     eth = ofpbuf_put_zeros(&packet, ETH_HEADER_LEN);
928     eth->eth_type = htons(0x1234);
929
930     /* Execute the actions.  On older datapaths this fails with ERANGE, on
931      * newer datapaths it succeeds. */
932     execute.actions = actions.data;
933     execute.actions_len = actions.size;
934     execute.packet = &packet;
935     execute.md = PKT_METADATA_INITIALIZER(0);
936     execute.needs_help = false;
937
938     error = dpif_execute(backer->dpif, &execute);
939
940     ofpbuf_uninit(&packet);
941     ofpbuf_uninit(&actions);
942
943     switch (error) {
944     case 0:
945         /* Variable-length userdata is supported.
946          *
947          * Purge received packets to avoid processing the nonsense packet we
948          * sent to userspace, then report success. */
949         dpif_recv_purge(backer->dpif);
950         return true;
951
952     case ERANGE:
953         /* Variable-length userdata is not supported. */
954         VLOG_WARN("%s: datapath does not support variable-length userdata "
955                   "feature (needs Linux 3.10+ or kernel module from OVS "
956                   "1..11+).  The NXAST_SAMPLE action will be ignored.",
957                   dpif_name(backer->dpif));
958         return false;
959
960     default:
961         /* Something odd happened.  We're not sure whether variable-length
962          * userdata is supported.  Default to "yes". */
963         VLOG_WARN("%s: variable-length userdata feature probe failed (%s)",
964                   dpif_name(backer->dpif), ovs_strerror(error));
965         return true;
966     }
967 }
968
969 static int
970 construct(struct ofproto *ofproto_)
971 {
972     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
973     struct shash_node *node, *next;
974     int error;
975
976     error = open_dpif_backer(ofproto->up.type, &ofproto->backer);
977     if (error) {
978         return error;
979     }
980
981     ofproto->netflow = NULL;
982     ofproto->sflow = NULL;
983     ofproto->ipfix = NULL;
984     ofproto->stp = NULL;
985     ofproto->dump_seq = 0;
986     hmap_init(&ofproto->bundles);
987     ofproto->ml = mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME);
988     ofproto->mbridge = mbridge_create();
989     ofproto->has_bonded_bundles = false;
990     ofproto->lacp_enabled = false;
991     ovs_mutex_init(&ofproto->stats_mutex);
992     ovs_mutex_init(&ofproto->vsp_mutex);
993
994     guarded_list_init(&ofproto->pins);
995
996     ofproto_dpif_unixctl_init();
997
998     hmap_init(&ofproto->vlandev_map);
999     hmap_init(&ofproto->realdev_vid_map);
1000
1001     sset_init(&ofproto->ports);
1002     sset_init(&ofproto->ghost_ports);
1003     sset_init(&ofproto->port_poll_set);
1004     ofproto->port_poll_errno = 0;
1005     ofproto->change_seq = 0;
1006
1007     SHASH_FOR_EACH_SAFE (node, next, &init_ofp_ports) {
1008         struct iface_hint *iface_hint = node->data;
1009
1010         if (!strcmp(iface_hint->br_name, ofproto->up.name)) {
1011             /* Check if the datapath already has this port. */
1012             if (dpif_port_exists(ofproto->backer->dpif, node->name)) {
1013                 sset_add(&ofproto->ports, node->name);
1014             }
1015
1016             free(iface_hint->br_name);
1017             free(iface_hint->br_type);
1018             free(iface_hint);
1019             shash_delete(&init_ofp_ports, node);
1020         }
1021     }
1022
1023     hmap_insert(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node,
1024                 hash_string(ofproto->up.name, 0));
1025     memset(&ofproto->stats, 0, sizeof ofproto->stats);
1026
1027     ofproto_init_tables(ofproto_, N_TABLES);
1028     error = add_internal_flows(ofproto);
1029     ofproto->up.tables[TBL_INTERNAL].flags = OFTABLE_HIDDEN | OFTABLE_READONLY;
1030
1031     return error;
1032 }
1033
1034 static int
1035 add_internal_flow(struct ofproto_dpif *ofproto, int id,
1036                   const struct ofpbuf *ofpacts, struct rule_dpif **rulep)
1037 {
1038     struct ofputil_flow_mod fm;
1039     int error;
1040
1041     match_init_catchall(&fm.match);
1042     fm.priority = 0;
1043     match_set_reg(&fm.match, 0, id);
1044     fm.new_cookie = htonll(0);
1045     fm.cookie = htonll(0);
1046     fm.cookie_mask = htonll(0);
1047     fm.modify_cookie = false;
1048     fm.table_id = TBL_INTERNAL;
1049     fm.command = OFPFC_ADD;
1050     fm.idle_timeout = 0;
1051     fm.hard_timeout = 0;
1052     fm.buffer_id = 0;
1053     fm.out_port = 0;
1054     fm.flags = 0;
1055     fm.ofpacts = ofpacts->data;
1056     fm.ofpacts_len = ofpacts->size;
1057
1058     error = ofproto_flow_mod(&ofproto->up, &fm);
1059     if (error) {
1060         VLOG_ERR_RL(&rl, "failed to add internal flow %d (%s)",
1061                     id, ofperr_to_string(error));
1062         return error;
1063     }
1064
1065     if (rule_dpif_lookup_in_table(ofproto, &fm.match.flow, NULL, TBL_INTERNAL,
1066                                   rulep)) {
1067         rule_dpif_unref(*rulep);
1068     } else {
1069         OVS_NOT_REACHED();
1070     }
1071
1072     return 0;
1073 }
1074
1075 static int
1076 add_internal_flows(struct ofproto_dpif *ofproto)
1077 {
1078     struct ofpact_controller *controller;
1079     uint64_t ofpacts_stub[128 / 8];
1080     struct ofpbuf ofpacts;
1081     int error;
1082     int id;
1083
1084     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
1085     id = 1;
1086
1087     controller = ofpact_put_CONTROLLER(&ofpacts);
1088     controller->max_len = UINT16_MAX;
1089     controller->controller_id = 0;
1090     controller->reason = OFPR_NO_MATCH;
1091     ofpact_pad(&ofpacts);
1092
1093     error = add_internal_flow(ofproto, id++, &ofpacts, &ofproto->miss_rule);
1094     if (error) {
1095         return error;
1096     }
1097
1098     ofpbuf_clear(&ofpacts);
1099     error = add_internal_flow(ofproto, id++, &ofpacts,
1100                               &ofproto->no_packet_in_rule);
1101     if (error) {
1102         return error;
1103     }
1104
1105     error = add_internal_flow(ofproto, id++, &ofpacts,
1106                               &ofproto->drop_frags_rule);
1107     return error;
1108 }
1109
1110 static void
1111 destruct(struct ofproto *ofproto_)
1112 {
1113     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1114     struct rule_dpif *rule, *next_rule;
1115     struct ofproto_packet_in *pin, *next_pin;
1116     struct oftable *table;
1117     struct list pins;
1118
1119     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1120     ovs_rwlock_wrlock(&xlate_rwlock);
1121     xlate_remove_ofproto(ofproto);
1122     ovs_rwlock_unlock(&xlate_rwlock);
1123
1124     /* Discard any flow_miss_batches queued up for 'ofproto', avoiding a
1125      * use-after-free error. */
1126     udpif_revalidate(ofproto->backer->udpif);
1127
1128     hmap_remove(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node);
1129
1130     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
1131         struct cls_cursor cursor;
1132
1133         ovs_rwlock_rdlock(&table->cls.rwlock);
1134         cls_cursor_init(&cursor, &table->cls, NULL);
1135         ovs_rwlock_unlock(&table->cls.rwlock);
1136         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
1137             ofproto_rule_delete(&ofproto->up, &rule->up);
1138         }
1139     }
1140
1141     guarded_list_pop_all(&ofproto->pins, &pins);
1142     LIST_FOR_EACH_SAFE (pin, next_pin, list_node, &pins) {
1143         list_remove(&pin->list_node);
1144         free(CONST_CAST(void *, pin->up.packet));
1145         free(pin);
1146     }
1147     guarded_list_destroy(&ofproto->pins);
1148
1149     mbridge_unref(ofproto->mbridge);
1150
1151     netflow_unref(ofproto->netflow);
1152     dpif_sflow_unref(ofproto->sflow);
1153     hmap_destroy(&ofproto->bundles);
1154     mac_learning_unref(ofproto->ml);
1155
1156     hmap_destroy(&ofproto->vlandev_map);
1157     hmap_destroy(&ofproto->realdev_vid_map);
1158
1159     sset_destroy(&ofproto->ports);
1160     sset_destroy(&ofproto->ghost_ports);
1161     sset_destroy(&ofproto->port_poll_set);
1162
1163     ovs_mutex_destroy(&ofproto->stats_mutex);
1164     ovs_mutex_destroy(&ofproto->vsp_mutex);
1165
1166     close_dpif_backer(ofproto->backer);
1167 }
1168
1169 static int
1170 run(struct ofproto *ofproto_)
1171 {
1172     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1173     uint64_t new_seq, new_dump_seq;
1174
1175     if (mbridge_need_revalidate(ofproto->mbridge)) {
1176         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1177         ovs_rwlock_wrlock(&ofproto->ml->rwlock);
1178         mac_learning_flush(ofproto->ml);
1179         ovs_rwlock_unlock(&ofproto->ml->rwlock);
1180     }
1181
1182     /* Do not perform any periodic activity required by 'ofproto' while
1183      * waiting for flow restore to complete. */
1184     if (!ofproto_get_flow_restore_wait()) {
1185         struct ofproto_packet_in *pin, *next_pin;
1186         struct list pins;
1187
1188         guarded_list_pop_all(&ofproto->pins, &pins);
1189         LIST_FOR_EACH_SAFE (pin, next_pin, list_node, &pins) {
1190             connmgr_send_packet_in(ofproto->up.connmgr, pin);
1191             list_remove(&pin->list_node);
1192             free(CONST_CAST(void *, pin->up.packet));
1193             free(pin);
1194         }
1195     }
1196
1197     if (ofproto->netflow) {
1198         netflow_run(ofproto->netflow);
1199     }
1200     if (ofproto->sflow) {
1201         dpif_sflow_run(ofproto->sflow);
1202     }
1203     if (ofproto->ipfix) {
1204         dpif_ipfix_run(ofproto->ipfix);
1205     }
1206
1207     new_seq = seq_read(connectivity_seq_get());
1208     if (ofproto->change_seq != new_seq) {
1209         struct ofport_dpif *ofport;
1210
1211         HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1212             port_run(ofport);
1213         }
1214
1215         ofproto->change_seq = new_seq;
1216     }
1217     if (ofproto->lacp_enabled || ofproto->has_bonded_bundles) {
1218         struct ofbundle *bundle;
1219
1220         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1221             bundle_run(bundle);
1222         }
1223     }
1224
1225     stp_run(ofproto);
1226     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
1227     if (mac_learning_run(ofproto->ml)) {
1228         ofproto->backer->need_revalidate = REV_MAC_LEARNING;
1229     }
1230     ovs_rwlock_unlock(&ofproto->ml->rwlock);
1231
1232     new_dump_seq = seq_read(udpif_dump_seq(ofproto->backer->udpif));
1233     if (ofproto->dump_seq != new_dump_seq) {
1234         struct rule *rule, *next_rule;
1235
1236         /* We know stats are relatively fresh, so now is a good time to do some
1237          * periodic work. */
1238         ofproto->dump_seq = new_dump_seq;
1239
1240         /* Expire OpenFlow flows whose idle_timeout or hard_timeout
1241          * has passed. */
1242         ovs_mutex_lock(&ofproto_mutex);
1243         LIST_FOR_EACH_SAFE (rule, next_rule, expirable,
1244                             &ofproto->up.expirable) {
1245             rule_expire(rule_dpif_cast(rule));
1246         }
1247         ovs_mutex_unlock(&ofproto_mutex);
1248
1249         /* All outstanding data in existing flows has been accounted, so it's a
1250          * good time to do bond rebalancing. */
1251         if (ofproto->has_bonded_bundles) {
1252             struct ofbundle *bundle;
1253
1254             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1255                 if (bundle->bond) {
1256                     bond_rebalance(bundle->bond);
1257                 }
1258             }
1259         }
1260     }
1261
1262     return 0;
1263 }
1264
1265 static void
1266 wait(struct ofproto *ofproto_)
1267 {
1268     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1269
1270     if (ofproto_get_flow_restore_wait()) {
1271         return;
1272     }
1273
1274     if (ofproto->sflow) {
1275         dpif_sflow_wait(ofproto->sflow);
1276     }
1277     if (ofproto->ipfix) {
1278         dpif_ipfix_wait(ofproto->ipfix);
1279     }
1280     if (ofproto->lacp_enabled || ofproto->has_bonded_bundles) {
1281         struct ofbundle *bundle;
1282
1283         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1284             bundle_wait(bundle);
1285         }
1286     }
1287     if (ofproto->netflow) {
1288         netflow_wait(ofproto->netflow);
1289     }
1290     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
1291     mac_learning_wait(ofproto->ml);
1292     ovs_rwlock_unlock(&ofproto->ml->rwlock);
1293     stp_wait(ofproto);
1294     if (ofproto->backer->need_revalidate) {
1295         /* Shouldn't happen, but if it does just go around again. */
1296         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1297         poll_immediate_wake();
1298     }
1299
1300     seq_wait(udpif_dump_seq(ofproto->backer->udpif), ofproto->dump_seq);
1301 }
1302
1303 static void
1304 type_get_memory_usage(const char *type, struct simap *usage)
1305 {
1306     struct dpif_backer *backer;
1307
1308     backer = shash_find_data(&all_dpif_backers, type);
1309     if (backer) {
1310         udpif_get_memory_usage(backer->udpif, usage);
1311     }
1312 }
1313
1314 static void
1315 flush(struct ofproto *ofproto OVS_UNUSED)
1316 {
1317     udpif_flush();
1318 }
1319
1320 static void
1321 get_features(struct ofproto *ofproto_ OVS_UNUSED,
1322              bool *arp_match_ip, enum ofputil_action_bitmap *actions)
1323 {
1324     *arp_match_ip = true;
1325     *actions = (OFPUTIL_A_OUTPUT |
1326                 OFPUTIL_A_SET_VLAN_VID |
1327                 OFPUTIL_A_SET_VLAN_PCP |
1328                 OFPUTIL_A_STRIP_VLAN |
1329                 OFPUTIL_A_SET_DL_SRC |
1330                 OFPUTIL_A_SET_DL_DST |
1331                 OFPUTIL_A_SET_NW_SRC |
1332                 OFPUTIL_A_SET_NW_DST |
1333                 OFPUTIL_A_SET_NW_TOS |
1334                 OFPUTIL_A_SET_TP_SRC |
1335                 OFPUTIL_A_SET_TP_DST |
1336                 OFPUTIL_A_ENQUEUE);
1337 }
1338
1339 static void
1340 get_tables(struct ofproto *ofproto_, struct ofp12_table_stats *ots)
1341 {
1342     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1343     struct dpif_dp_stats s;
1344     uint64_t n_miss, n_no_pkt_in, n_bytes, n_dropped_frags;
1345     uint64_t n_lookup;
1346
1347     strcpy(ots->name, "classifier");
1348
1349     dpif_get_dp_stats(ofproto->backer->dpif, &s);
1350     rule_get_stats(&ofproto->miss_rule->up, &n_miss, &n_bytes);
1351     rule_get_stats(&ofproto->no_packet_in_rule->up, &n_no_pkt_in, &n_bytes);
1352     rule_get_stats(&ofproto->drop_frags_rule->up, &n_dropped_frags, &n_bytes);
1353
1354     n_lookup = s.n_hit + s.n_missed - n_dropped_frags;
1355     ots->lookup_count = htonll(n_lookup);
1356     ots->matched_count = htonll(n_lookup - n_miss - n_no_pkt_in);
1357 }
1358
1359 static struct ofport *
1360 port_alloc(void)
1361 {
1362     struct ofport_dpif *port = xmalloc(sizeof *port);
1363     return &port->up;
1364 }
1365
1366 static void
1367 port_dealloc(struct ofport *port_)
1368 {
1369     struct ofport_dpif *port = ofport_dpif_cast(port_);
1370     free(port);
1371 }
1372
1373 static int
1374 port_construct(struct ofport *port_)
1375 {
1376     struct ofport_dpif *port = ofport_dpif_cast(port_);
1377     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1378     const struct netdev *netdev = port->up.netdev;
1379     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1380     struct dpif_port dpif_port;
1381     int error;
1382
1383     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1384     port->bundle = NULL;
1385     port->cfm = NULL;
1386     port->bfd = NULL;
1387     port->may_enable = true;
1388     port->stp_port = NULL;
1389     port->stp_state = STP_DISABLED;
1390     port->is_tunnel = false;
1391     port->peer = NULL;
1392     port->qdscp = NULL;
1393     port->n_qdscp = 0;
1394     port->realdev_ofp_port = 0;
1395     port->vlandev_vid = 0;
1396     port->carrier_seq = netdev_get_carrier_resets(netdev);
1397     port->is_layer3 = netdev_vport_is_layer3(netdev);
1398
1399     if (netdev_vport_is_patch(netdev)) {
1400         /* By bailing out here, we don't submit the port to the sFlow module
1401          * to be considered for counter polling export.  This is correct
1402          * because the patch port represents an interface that sFlow considers
1403          * to be "internal" to the switch as a whole, and therefore not an
1404          * candidate for counter polling. */
1405         port->odp_port = ODPP_NONE;
1406         ofport_update_peer(port);
1407         return 0;
1408     }
1409
1410     error = dpif_port_query_by_name(ofproto->backer->dpif,
1411                                     netdev_vport_get_dpif_port(netdev, namebuf,
1412                                                                sizeof namebuf),
1413                                     &dpif_port);
1414     if (error) {
1415         return error;
1416     }
1417
1418     port->odp_port = dpif_port.port_no;
1419
1420     if (netdev_get_tunnel_config(netdev)) {
1421         tnl_port_add(port, port->up.netdev, port->odp_port);
1422         port->is_tunnel = true;
1423     } else {
1424         /* Sanity-check that a mapping doesn't already exist.  This
1425          * shouldn't happen for non-tunnel ports. */
1426         if (odp_port_to_ofp_port(ofproto, port->odp_port) != OFPP_NONE) {
1427             VLOG_ERR("port %s already has an OpenFlow port number",
1428                      dpif_port.name);
1429             dpif_port_destroy(&dpif_port);
1430             return EBUSY;
1431         }
1432
1433         ovs_rwlock_wrlock(&ofproto->backer->odp_to_ofport_lock);
1434         hmap_insert(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node,
1435                     hash_odp_port(port->odp_port));
1436         ovs_rwlock_unlock(&ofproto->backer->odp_to_ofport_lock);
1437     }
1438     dpif_port_destroy(&dpif_port);
1439
1440     if (ofproto->sflow) {
1441         dpif_sflow_add_port(ofproto->sflow, port_, port->odp_port);
1442     }
1443
1444     return 0;
1445 }
1446
1447 static void
1448 port_destruct(struct ofport *port_)
1449 {
1450     struct ofport_dpif *port = ofport_dpif_cast(port_);
1451     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1452     const char *devname = netdev_get_name(port->up.netdev);
1453     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1454     const char *dp_port_name;
1455
1456     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1457     ovs_rwlock_wrlock(&xlate_rwlock);
1458     xlate_ofport_remove(port);
1459     ovs_rwlock_unlock(&xlate_rwlock);
1460
1461     dp_port_name = netdev_vport_get_dpif_port(port->up.netdev, namebuf,
1462                                               sizeof namebuf);
1463     if (dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
1464         /* The underlying device is still there, so delete it.  This
1465          * happens when the ofproto is being destroyed, since the caller
1466          * assumes that removal of attached ports will happen as part of
1467          * destruction. */
1468         if (!port->is_tunnel) {
1469             dpif_port_del(ofproto->backer->dpif, port->odp_port);
1470         }
1471     }
1472
1473     if (port->peer) {
1474         port->peer->peer = NULL;
1475         port->peer = NULL;
1476     }
1477
1478     if (port->odp_port != ODPP_NONE && !port->is_tunnel) {
1479         ovs_rwlock_wrlock(&ofproto->backer->odp_to_ofport_lock);
1480         hmap_remove(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node);
1481         ovs_rwlock_unlock(&ofproto->backer->odp_to_ofport_lock);
1482     }
1483
1484     tnl_port_del(port);
1485     sset_find_and_delete(&ofproto->ports, devname);
1486     sset_find_and_delete(&ofproto->ghost_ports, devname);
1487     bundle_remove(port_);
1488     set_cfm(port_, NULL);
1489     set_bfd(port_, NULL);
1490     if (ofproto->sflow) {
1491         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
1492     }
1493
1494     free(port->qdscp);
1495 }
1496
1497 static void
1498 port_modified(struct ofport *port_)
1499 {
1500     struct ofport_dpif *port = ofport_dpif_cast(port_);
1501
1502     if (port->bundle && port->bundle->bond) {
1503         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
1504     }
1505
1506     if (port->cfm) {
1507         cfm_set_netdev(port->cfm, port->up.netdev);
1508     }
1509
1510     if (port->bfd) {
1511         bfd_set_netdev(port->bfd, port->up.netdev);
1512     }
1513
1514     ofproto_dpif_monitor_port_update(port, port->bfd, port->cfm,
1515                                      port->up.pp.hw_addr);
1516
1517     if (port->is_tunnel && tnl_port_reconfigure(port, port->up.netdev,
1518                                                 port->odp_port)) {
1519         ofproto_dpif_cast(port->up.ofproto)->backer->need_revalidate =
1520             REV_RECONFIGURE;
1521     }
1522
1523     ofport_update_peer(port);
1524 }
1525
1526 static void
1527 port_reconfigured(struct ofport *port_, enum ofputil_port_config old_config)
1528 {
1529     struct ofport_dpif *port = ofport_dpif_cast(port_);
1530     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1531     enum ofputil_port_config changed = old_config ^ port->up.pp.config;
1532
1533     if (changed & (OFPUTIL_PC_NO_RECV | OFPUTIL_PC_NO_RECV_STP |
1534                    OFPUTIL_PC_NO_FWD | OFPUTIL_PC_NO_FLOOD |
1535                    OFPUTIL_PC_NO_PACKET_IN)) {
1536         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1537
1538         if (changed & OFPUTIL_PC_NO_FLOOD && port->bundle) {
1539             bundle_update(port->bundle);
1540         }
1541     }
1542 }
1543
1544 static int
1545 set_sflow(struct ofproto *ofproto_,
1546           const struct ofproto_sflow_options *sflow_options)
1547 {
1548     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1549     struct dpif_sflow *ds = ofproto->sflow;
1550
1551     if (sflow_options) {
1552         if (!ds) {
1553             struct ofport_dpif *ofport;
1554
1555             ds = ofproto->sflow = dpif_sflow_create();
1556             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1557                 dpif_sflow_add_port(ds, &ofport->up, ofport->odp_port);
1558             }
1559             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1560         }
1561         dpif_sflow_set_options(ds, sflow_options);
1562     } else {
1563         if (ds) {
1564             dpif_sflow_unref(ds);
1565             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1566             ofproto->sflow = NULL;
1567         }
1568     }
1569     return 0;
1570 }
1571
1572 static int
1573 set_ipfix(
1574     struct ofproto *ofproto_,
1575     const struct ofproto_ipfix_bridge_exporter_options *bridge_exporter_options,
1576     const struct ofproto_ipfix_flow_exporter_options *flow_exporters_options,
1577     size_t n_flow_exporters_options)
1578 {
1579     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1580     struct dpif_ipfix *di = ofproto->ipfix;
1581     bool has_options = bridge_exporter_options || flow_exporters_options;
1582
1583     if (has_options && !di) {
1584         di = ofproto->ipfix = dpif_ipfix_create();
1585     }
1586
1587     if (di) {
1588         /* Call set_options in any case to cleanly flush the flow
1589          * caches in the last exporters that are to be destroyed. */
1590         dpif_ipfix_set_options(
1591             di, bridge_exporter_options, flow_exporters_options,
1592             n_flow_exporters_options);
1593
1594         if (!has_options) {
1595             dpif_ipfix_unref(di);
1596             ofproto->ipfix = NULL;
1597         }
1598     }
1599
1600     return 0;
1601 }
1602
1603 static int
1604 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
1605 {
1606     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1607     int error = 0;
1608
1609     if (s) {
1610         if (!ofport->cfm) {
1611             struct ofproto_dpif *ofproto;
1612
1613             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1614             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1615             ofport->cfm = cfm_create(ofport->up.netdev);
1616         }
1617
1618         if (cfm_configure(ofport->cfm, s)) {
1619             error = 0;
1620             goto out;
1621         }
1622
1623         error = EINVAL;
1624     }
1625     cfm_unref(ofport->cfm);
1626     ofport->cfm = NULL;
1627 out:
1628     ofproto_dpif_monitor_port_update(ofport, ofport->bfd, ofport->cfm,
1629                                      ofport->up.pp.hw_addr);
1630     return error;
1631 }
1632
1633 static bool
1634 get_cfm_status(const struct ofport *ofport_,
1635                struct ofproto_cfm_status *status)
1636 {
1637     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1638
1639     if (ofport->cfm) {
1640         status->faults = cfm_get_fault(ofport->cfm);
1641         status->flap_count = cfm_get_flap_count(ofport->cfm);
1642         status->remote_opstate = cfm_get_opup(ofport->cfm);
1643         status->health = cfm_get_health(ofport->cfm);
1644         cfm_get_remote_mpids(ofport->cfm, &status->rmps, &status->n_rmps);
1645         return true;
1646     } else {
1647         return false;
1648     }
1649 }
1650
1651 static int
1652 set_bfd(struct ofport *ofport_, const struct smap *cfg)
1653 {
1654     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
1655     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1656     struct bfd *old;
1657
1658     old = ofport->bfd;
1659     ofport->bfd = bfd_configure(old, netdev_get_name(ofport->up.netdev),
1660                                 cfg, ofport->up.netdev);
1661     if (ofport->bfd != old) {
1662         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1663     }
1664     ofproto_dpif_monitor_port_update(ofport, ofport->bfd, ofport->cfm,
1665                                      ofport->up.pp.hw_addr);
1666     return 0;
1667 }
1668
1669 static int
1670 get_bfd_status(struct ofport *ofport_, struct smap *smap)
1671 {
1672     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1673
1674     if (ofport->bfd) {
1675         bfd_get_status(ofport->bfd, smap);
1676         return 0;
1677     } else {
1678         return ENOENT;
1679     }
1680 }
1681 \f
1682 /* Spanning Tree. */
1683
1684 static void
1685 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
1686 {
1687     struct ofproto_dpif *ofproto = ofproto_;
1688     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
1689     struct ofport_dpif *ofport;
1690
1691     ofport = stp_port_get_aux(sp);
1692     if (!ofport) {
1693         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
1694                      ofproto->up.name, port_num);
1695     } else {
1696         struct eth_header *eth = pkt->l2;
1697
1698         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
1699         if (eth_addr_is_zero(eth->eth_src)) {
1700             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
1701                          "with unknown MAC", ofproto->up.name, port_num);
1702         } else {
1703             ofproto_dpif_send_packet(ofport, pkt);
1704         }
1705     }
1706     ofpbuf_delete(pkt);
1707 }
1708
1709 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
1710 static int
1711 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
1712 {
1713     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1714
1715     /* Only revalidate flows if the configuration changed. */
1716     if (!s != !ofproto->stp) {
1717         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1718     }
1719
1720     if (s) {
1721         if (!ofproto->stp) {
1722             ofproto->stp = stp_create(ofproto_->name, s->system_id,
1723                                       send_bpdu_cb, ofproto);
1724             ofproto->stp_last_tick = time_msec();
1725         }
1726
1727         stp_set_bridge_id(ofproto->stp, s->system_id);
1728         stp_set_bridge_priority(ofproto->stp, s->priority);
1729         stp_set_hello_time(ofproto->stp, s->hello_time);
1730         stp_set_max_age(ofproto->stp, s->max_age);
1731         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
1732     }  else {
1733         struct ofport *ofport;
1734
1735         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
1736             set_stp_port(ofport, NULL);
1737         }
1738
1739         stp_unref(ofproto->stp);
1740         ofproto->stp = NULL;
1741     }
1742
1743     return 0;
1744 }
1745
1746 static int
1747 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
1748 {
1749     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1750
1751     if (ofproto->stp) {
1752         s->enabled = true;
1753         s->bridge_id = stp_get_bridge_id(ofproto->stp);
1754         s->designated_root = stp_get_designated_root(ofproto->stp);
1755         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
1756     } else {
1757         s->enabled = false;
1758     }
1759
1760     return 0;
1761 }
1762
1763 static void
1764 update_stp_port_state(struct ofport_dpif *ofport)
1765 {
1766     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1767     enum stp_state state;
1768
1769     /* Figure out new state. */
1770     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
1771                              : STP_DISABLED;
1772
1773     /* Update state. */
1774     if (ofport->stp_state != state) {
1775         enum ofputil_port_state of_state;
1776         bool fwd_change;
1777
1778         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
1779                     netdev_get_name(ofport->up.netdev),
1780                     stp_state_name(ofport->stp_state),
1781                     stp_state_name(state));
1782         if (stp_learn_in_state(ofport->stp_state)
1783                 != stp_learn_in_state(state)) {
1784             /* xxx Learning action flows should also be flushed. */
1785             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
1786             mac_learning_flush(ofproto->ml);
1787             ovs_rwlock_unlock(&ofproto->ml->rwlock);
1788         }
1789         fwd_change = stp_forward_in_state(ofport->stp_state)
1790                         != stp_forward_in_state(state);
1791
1792         ofproto->backer->need_revalidate = REV_STP;
1793         ofport->stp_state = state;
1794         ofport->stp_state_entered = time_msec();
1795
1796         if (fwd_change && ofport->bundle) {
1797             bundle_update(ofport->bundle);
1798         }
1799
1800         /* Update the STP state bits in the OpenFlow port description. */
1801         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
1802         of_state |= (state == STP_LISTENING ? OFPUTIL_PS_STP_LISTEN
1803                      : state == STP_LEARNING ? OFPUTIL_PS_STP_LEARN
1804                      : state == STP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
1805                      : state == STP_BLOCKING ?  OFPUTIL_PS_STP_BLOCK
1806                      : 0);
1807         ofproto_port_set_state(&ofport->up, of_state);
1808     }
1809 }
1810
1811 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
1812  * caller is responsible for assigning STP port numbers and ensuring
1813  * there are no duplicates. */
1814 static int
1815 set_stp_port(struct ofport *ofport_,
1816              const struct ofproto_port_stp_settings *s)
1817 {
1818     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1819     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1820     struct stp_port *sp = ofport->stp_port;
1821
1822     if (!s || !s->enable) {
1823         if (sp) {
1824             ofport->stp_port = NULL;
1825             stp_port_disable(sp);
1826             update_stp_port_state(ofport);
1827         }
1828         return 0;
1829     } else if (sp && stp_port_no(sp) != s->port_num
1830             && ofport == stp_port_get_aux(sp)) {
1831         /* The port-id changed, so disable the old one if it's not
1832          * already in use by another port. */
1833         stp_port_disable(sp);
1834     }
1835
1836     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
1837     stp_port_enable(sp);
1838
1839     stp_port_set_aux(sp, ofport);
1840     stp_port_set_priority(sp, s->priority);
1841     stp_port_set_path_cost(sp, s->path_cost);
1842
1843     update_stp_port_state(ofport);
1844
1845     return 0;
1846 }
1847
1848 static int
1849 get_stp_port_status(struct ofport *ofport_,
1850                     struct ofproto_port_stp_status *s)
1851 {
1852     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1853     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1854     struct stp_port *sp = ofport->stp_port;
1855
1856     if (!ofproto->stp || !sp) {
1857         s->enabled = false;
1858         return 0;
1859     }
1860
1861     s->enabled = true;
1862     s->port_id = stp_port_get_id(sp);
1863     s->state = stp_port_get_state(sp);
1864     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
1865     s->role = stp_port_get_role(sp);
1866
1867     return 0;
1868 }
1869
1870 static int
1871 get_stp_port_stats(struct ofport *ofport_,
1872                    struct ofproto_port_stp_stats *s)
1873 {
1874     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1875     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1876     struct stp_port *sp = ofport->stp_port;
1877
1878     if (!ofproto->stp || !sp) {
1879         s->enabled = false;
1880         return 0;
1881     }
1882
1883     s->enabled = true;
1884     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
1885
1886     return 0;
1887 }
1888
1889 static void
1890 stp_run(struct ofproto_dpif *ofproto)
1891 {
1892     if (ofproto->stp) {
1893         long long int now = time_msec();
1894         long long int elapsed = now - ofproto->stp_last_tick;
1895         struct stp_port *sp;
1896
1897         if (elapsed > 0) {
1898             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
1899             ofproto->stp_last_tick = now;
1900         }
1901         while (stp_get_changed_port(ofproto->stp, &sp)) {
1902             struct ofport_dpif *ofport = stp_port_get_aux(sp);
1903
1904             if (ofport) {
1905                 update_stp_port_state(ofport);
1906             }
1907         }
1908
1909         if (stp_check_and_reset_fdb_flush(ofproto->stp)) {
1910             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
1911             mac_learning_flush(ofproto->ml);
1912             ovs_rwlock_unlock(&ofproto->ml->rwlock);
1913         }
1914     }
1915 }
1916
1917 static void
1918 stp_wait(struct ofproto_dpif *ofproto)
1919 {
1920     if (ofproto->stp) {
1921         poll_timer_wait(1000);
1922     }
1923 }
1924 \f
1925 static int
1926 set_queues(struct ofport *ofport_, const struct ofproto_port_queue *qdscp,
1927            size_t n_qdscp)
1928 {
1929     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1930     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1931
1932     if (ofport->n_qdscp != n_qdscp
1933         || (n_qdscp && memcmp(ofport->qdscp, qdscp,
1934                               n_qdscp * sizeof *qdscp))) {
1935         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1936         free(ofport->qdscp);
1937         ofport->qdscp = n_qdscp
1938             ? xmemdup(qdscp, n_qdscp * sizeof *qdscp)
1939             : NULL;
1940         ofport->n_qdscp = n_qdscp;
1941     }
1942
1943     return 0;
1944 }
1945 \f
1946 /* Bundles. */
1947
1948 /* Expires all MAC learning entries associated with 'bundle' and forces its
1949  * ofproto to revalidate every flow.
1950  *
1951  * Normally MAC learning entries are removed only from the ofproto associated
1952  * with 'bundle', but if 'all_ofprotos' is true, then the MAC learning entries
1953  * are removed from every ofproto.  When patch ports and SLB bonds are in use
1954  * and a VM migration happens and the gratuitous ARPs are somehow lost, this
1955  * avoids a MAC_ENTRY_IDLE_TIME delay before the migrated VM can communicate
1956  * with the host from which it migrated. */
1957 static void
1958 bundle_flush_macs(struct ofbundle *bundle, bool all_ofprotos)
1959 {
1960     struct ofproto_dpif *ofproto = bundle->ofproto;
1961     struct mac_learning *ml = ofproto->ml;
1962     struct mac_entry *mac, *next_mac;
1963
1964     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1965     ovs_rwlock_wrlock(&ml->rwlock);
1966     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
1967         if (mac->port.p == bundle) {
1968             if (all_ofprotos) {
1969                 struct ofproto_dpif *o;
1970
1971                 HMAP_FOR_EACH (o, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
1972                     if (o != ofproto) {
1973                         struct mac_entry *e;
1974
1975                         ovs_rwlock_wrlock(&o->ml->rwlock);
1976                         e = mac_learning_lookup(o->ml, mac->mac, mac->vlan);
1977                         if (e) {
1978                             mac_learning_expire(o->ml, e);
1979                         }
1980                         ovs_rwlock_unlock(&o->ml->rwlock);
1981                     }
1982                 }
1983             }
1984
1985             mac_learning_expire(ml, mac);
1986         }
1987     }
1988     ovs_rwlock_unlock(&ml->rwlock);
1989 }
1990
1991 static struct ofbundle *
1992 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
1993 {
1994     struct ofbundle *bundle;
1995
1996     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
1997                              &ofproto->bundles) {
1998         if (bundle->aux == aux) {
1999             return bundle;
2000         }
2001     }
2002     return NULL;
2003 }
2004
2005 static void
2006 bundle_update(struct ofbundle *bundle)
2007 {
2008     struct ofport_dpif *port;
2009
2010     bundle->floodable = true;
2011     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2012         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2013             || port->is_layer3
2014             || !stp_forward_in_state(port->stp_state)) {
2015             bundle->floodable = false;
2016             break;
2017         }
2018     }
2019 }
2020
2021 static void
2022 bundle_del_port(struct ofport_dpif *port)
2023 {
2024     struct ofbundle *bundle = port->bundle;
2025
2026     bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2027
2028     list_remove(&port->bundle_node);
2029     port->bundle = NULL;
2030
2031     if (bundle->lacp) {
2032         lacp_slave_unregister(bundle->lacp, port);
2033     }
2034     if (bundle->bond) {
2035         bond_slave_unregister(bundle->bond, port);
2036     }
2037
2038     bundle_update(bundle);
2039 }
2040
2041 static bool
2042 bundle_add_port(struct ofbundle *bundle, ofp_port_t ofp_port,
2043                 struct lacp_slave_settings *lacp)
2044 {
2045     struct ofport_dpif *port;
2046
2047     port = get_ofp_port(bundle->ofproto, ofp_port);
2048     if (!port) {
2049         return false;
2050     }
2051
2052     if (port->bundle != bundle) {
2053         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2054         if (port->bundle) {
2055             bundle_remove(&port->up);
2056         }
2057
2058         port->bundle = bundle;
2059         list_push_back(&bundle->ports, &port->bundle_node);
2060         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2061             || port->is_layer3
2062             || !stp_forward_in_state(port->stp_state)) {
2063             bundle->floodable = false;
2064         }
2065     }
2066     if (lacp) {
2067         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2068         lacp_slave_register(bundle->lacp, port, lacp);
2069     }
2070
2071     return true;
2072 }
2073
2074 static void
2075 bundle_destroy(struct ofbundle *bundle)
2076 {
2077     struct ofproto_dpif *ofproto;
2078     struct ofport_dpif *port, *next_port;
2079
2080     if (!bundle) {
2081         return;
2082     }
2083
2084     ofproto = bundle->ofproto;
2085     mbridge_unregister_bundle(ofproto->mbridge, bundle->aux);
2086
2087     ovs_rwlock_wrlock(&xlate_rwlock);
2088     xlate_bundle_remove(bundle);
2089     ovs_rwlock_unlock(&xlate_rwlock);
2090
2091     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2092         bundle_del_port(port);
2093     }
2094
2095     bundle_flush_macs(bundle, true);
2096     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
2097     free(bundle->name);
2098     free(bundle->trunks);
2099     lacp_unref(bundle->lacp);
2100     bond_unref(bundle->bond);
2101     free(bundle);
2102 }
2103
2104 static int
2105 bundle_set(struct ofproto *ofproto_, void *aux,
2106            const struct ofproto_bundle_settings *s)
2107 {
2108     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2109     bool need_flush = false;
2110     struct ofport_dpif *port;
2111     struct ofbundle *bundle;
2112     unsigned long *trunks;
2113     int vlan;
2114     size_t i;
2115     bool ok;
2116
2117     if (!s) {
2118         bundle_destroy(bundle_lookup(ofproto, aux));
2119         return 0;
2120     }
2121
2122     ovs_assert(s->n_slaves == 1 || s->bond != NULL);
2123     ovs_assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
2124
2125     bundle = bundle_lookup(ofproto, aux);
2126     if (!bundle) {
2127         bundle = xmalloc(sizeof *bundle);
2128
2129         bundle->ofproto = ofproto;
2130         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
2131                     hash_pointer(aux, 0));
2132         bundle->aux = aux;
2133         bundle->name = NULL;
2134
2135         list_init(&bundle->ports);
2136         bundle->vlan_mode = PORT_VLAN_TRUNK;
2137         bundle->vlan = -1;
2138         bundle->trunks = NULL;
2139         bundle->use_priority_tags = s->use_priority_tags;
2140         bundle->lacp = NULL;
2141         bundle->bond = NULL;
2142
2143         bundle->floodable = true;
2144         mbridge_register_bundle(ofproto->mbridge, bundle);
2145     }
2146
2147     if (!bundle->name || strcmp(s->name, bundle->name)) {
2148         free(bundle->name);
2149         bundle->name = xstrdup(s->name);
2150     }
2151
2152     /* LACP. */
2153     if (s->lacp) {
2154         ofproto->lacp_enabled = true;
2155         if (!bundle->lacp) {
2156             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2157             bundle->lacp = lacp_create();
2158         }
2159         lacp_configure(bundle->lacp, s->lacp);
2160     } else {
2161         lacp_unref(bundle->lacp);
2162         bundle->lacp = NULL;
2163     }
2164
2165     /* Update set of ports. */
2166     ok = true;
2167     for (i = 0; i < s->n_slaves; i++) {
2168         if (!bundle_add_port(bundle, s->slaves[i],
2169                              s->lacp ? &s->lacp_slaves[i] : NULL)) {
2170             ok = false;
2171         }
2172     }
2173     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
2174         struct ofport_dpif *next_port;
2175
2176         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2177             for (i = 0; i < s->n_slaves; i++) {
2178                 if (s->slaves[i] == port->up.ofp_port) {
2179                     goto found;
2180                 }
2181             }
2182
2183             bundle_del_port(port);
2184         found: ;
2185         }
2186     }
2187     ovs_assert(list_size(&bundle->ports) <= s->n_slaves);
2188
2189     if (list_is_empty(&bundle->ports)) {
2190         bundle_destroy(bundle);
2191         return EINVAL;
2192     }
2193
2194     /* Set VLAN tagging mode */
2195     if (s->vlan_mode != bundle->vlan_mode
2196         || s->use_priority_tags != bundle->use_priority_tags) {
2197         bundle->vlan_mode = s->vlan_mode;
2198         bundle->use_priority_tags = s->use_priority_tags;
2199         need_flush = true;
2200     }
2201
2202     /* Set VLAN tag. */
2203     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
2204             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
2205             : 0);
2206     if (vlan != bundle->vlan) {
2207         bundle->vlan = vlan;
2208         need_flush = true;
2209     }
2210
2211     /* Get trunked VLANs. */
2212     switch (s->vlan_mode) {
2213     case PORT_VLAN_ACCESS:
2214         trunks = NULL;
2215         break;
2216
2217     case PORT_VLAN_TRUNK:
2218         trunks = CONST_CAST(unsigned long *, s->trunks);
2219         break;
2220
2221     case PORT_VLAN_NATIVE_UNTAGGED:
2222     case PORT_VLAN_NATIVE_TAGGED:
2223         if (vlan != 0 && (!s->trunks
2224                           || !bitmap_is_set(s->trunks, vlan)
2225                           || bitmap_is_set(s->trunks, 0))) {
2226             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
2227             if (s->trunks) {
2228                 trunks = bitmap_clone(s->trunks, 4096);
2229             } else {
2230                 trunks = bitmap_allocate1(4096);
2231             }
2232             bitmap_set1(trunks, vlan);
2233             bitmap_set0(trunks, 0);
2234         } else {
2235             trunks = CONST_CAST(unsigned long *, s->trunks);
2236         }
2237         break;
2238
2239     default:
2240         OVS_NOT_REACHED();
2241     }
2242     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
2243         free(bundle->trunks);
2244         if (trunks == s->trunks) {
2245             bundle->trunks = vlan_bitmap_clone(trunks);
2246         } else {
2247             bundle->trunks = trunks;
2248             trunks = NULL;
2249         }
2250         need_flush = true;
2251     }
2252     if (trunks != s->trunks) {
2253         free(trunks);
2254     }
2255
2256     /* Bonding. */
2257     if (!list_is_short(&bundle->ports)) {
2258         bundle->ofproto->has_bonded_bundles = true;
2259         if (bundle->bond) {
2260             if (bond_reconfigure(bundle->bond, s->bond)) {
2261                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2262             }
2263         } else {
2264             bundle->bond = bond_create(s->bond);
2265             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2266         }
2267
2268         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2269             bond_slave_register(bundle->bond, port, port->up.netdev);
2270         }
2271     } else {
2272         bond_unref(bundle->bond);
2273         bundle->bond = NULL;
2274     }
2275
2276     /* If we changed something that would affect MAC learning, un-learn
2277      * everything on this port and force flow revalidation. */
2278     if (need_flush) {
2279         bundle_flush_macs(bundle, false);
2280     }
2281
2282     return 0;
2283 }
2284
2285 static void
2286 bundle_remove(struct ofport *port_)
2287 {
2288     struct ofport_dpif *port = ofport_dpif_cast(port_);
2289     struct ofbundle *bundle = port->bundle;
2290
2291     if (bundle) {
2292         bundle_del_port(port);
2293         if (list_is_empty(&bundle->ports)) {
2294             bundle_destroy(bundle);
2295         } else if (list_is_short(&bundle->ports)) {
2296             bond_unref(bundle->bond);
2297             bundle->bond = NULL;
2298         }
2299     }
2300 }
2301
2302 static void
2303 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
2304 {
2305     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
2306     struct ofport_dpif *port = port_;
2307     uint8_t ea[ETH_ADDR_LEN];
2308     int error;
2309
2310     error = netdev_get_etheraddr(port->up.netdev, ea);
2311     if (!error) {
2312         struct ofpbuf packet;
2313         void *packet_pdu;
2314
2315         ofpbuf_init(&packet, 0);
2316         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
2317                                  pdu_size);
2318         memcpy(packet_pdu, pdu, pdu_size);
2319
2320         ofproto_dpif_send_packet(port, &packet);
2321         ofpbuf_uninit(&packet);
2322     } else {
2323         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
2324                     "%s (%s)", port->bundle->name,
2325                     netdev_get_name(port->up.netdev), ovs_strerror(error));
2326     }
2327 }
2328
2329 static void
2330 bundle_send_learning_packets(struct ofbundle *bundle)
2331 {
2332     struct ofproto_dpif *ofproto = bundle->ofproto;
2333     struct ofpbuf *learning_packet;
2334     int error, n_packets, n_errors;
2335     struct mac_entry *e;
2336     struct list packets;
2337
2338     list_init(&packets);
2339     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
2340     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
2341         if (e->port.p != bundle) {
2342             void *port_void;
2343
2344             learning_packet = bond_compose_learning_packet(bundle->bond,
2345                                                            e->mac, e->vlan,
2346                                                            &port_void);
2347             learning_packet->private_p = port_void;
2348             list_push_back(&packets, &learning_packet->list_node);
2349         }
2350     }
2351     ovs_rwlock_unlock(&ofproto->ml->rwlock);
2352
2353     error = n_packets = n_errors = 0;
2354     LIST_FOR_EACH (learning_packet, list_node, &packets) {
2355         int ret;
2356
2357         ret = ofproto_dpif_send_packet(learning_packet->private_p, learning_packet);
2358         if (ret) {
2359             error = ret;
2360             n_errors++;
2361         }
2362         n_packets++;
2363     }
2364     ofpbuf_list_delete(&packets);
2365
2366     if (n_errors) {
2367         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2368         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
2369                      "packets, last error was: %s",
2370                      bundle->name, n_errors, n_packets, ovs_strerror(error));
2371     } else {
2372         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
2373                  bundle->name, n_packets);
2374     }
2375 }
2376
2377 static void
2378 bundle_run(struct ofbundle *bundle)
2379 {
2380     if (bundle->lacp) {
2381         lacp_run(bundle->lacp, send_pdu_cb);
2382     }
2383     if (bundle->bond) {
2384         struct ofport_dpif *port;
2385
2386         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2387             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
2388         }
2389
2390         if (bond_run(bundle->bond, lacp_status(bundle->lacp))) {
2391             bundle->ofproto->backer->need_revalidate = REV_BOND;
2392         }
2393
2394         if (bond_should_send_learning_packets(bundle->bond)) {
2395             bundle_send_learning_packets(bundle);
2396         }
2397     }
2398 }
2399
2400 static void
2401 bundle_wait(struct ofbundle *bundle)
2402 {
2403     if (bundle->lacp) {
2404         lacp_wait(bundle->lacp);
2405     }
2406     if (bundle->bond) {
2407         bond_wait(bundle->bond);
2408     }
2409 }
2410 \f
2411 /* Mirrors. */
2412
2413 static int
2414 mirror_set__(struct ofproto *ofproto_, void *aux,
2415              const struct ofproto_mirror_settings *s)
2416 {
2417     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2418     struct ofbundle **srcs, **dsts;
2419     int error;
2420     size_t i;
2421
2422     if (!s) {
2423         mirror_destroy(ofproto->mbridge, aux);
2424         return 0;
2425     }
2426
2427     srcs = xmalloc(s->n_srcs * sizeof *srcs);
2428     dsts = xmalloc(s->n_dsts * sizeof *dsts);
2429
2430     for (i = 0; i < s->n_srcs; i++) {
2431         srcs[i] = bundle_lookup(ofproto, s->srcs[i]);
2432     }
2433
2434     for (i = 0; i < s->n_dsts; i++) {
2435         dsts[i] = bundle_lookup(ofproto, s->dsts[i]);
2436     }
2437
2438     error = mirror_set(ofproto->mbridge, aux, s->name, srcs, s->n_srcs, dsts,
2439                        s->n_dsts, s->src_vlans,
2440                        bundle_lookup(ofproto, s->out_bundle), s->out_vlan);
2441     free(srcs);
2442     free(dsts);
2443     return error;
2444 }
2445
2446 static int
2447 mirror_get_stats__(struct ofproto *ofproto, void *aux,
2448                    uint64_t *packets, uint64_t *bytes)
2449 {
2450     return mirror_get_stats(ofproto_dpif_cast(ofproto)->mbridge, aux, packets,
2451                             bytes);
2452 }
2453
2454 static int
2455 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
2456 {
2457     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2458     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
2459     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
2460         mac_learning_flush(ofproto->ml);
2461     }
2462     ovs_rwlock_unlock(&ofproto->ml->rwlock);
2463     return 0;
2464 }
2465
2466 static bool
2467 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
2468 {
2469     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2470     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
2471     return bundle && mirror_bundle_out(ofproto->mbridge, bundle) != 0;
2472 }
2473
2474 static void
2475 forward_bpdu_changed(struct ofproto *ofproto_)
2476 {
2477     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2478     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2479 }
2480
2481 static void
2482 set_mac_table_config(struct ofproto *ofproto_, unsigned int idle_time,
2483                      size_t max_entries)
2484 {
2485     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2486     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
2487     mac_learning_set_idle_time(ofproto->ml, idle_time);
2488     mac_learning_set_max_entries(ofproto->ml, max_entries);
2489     ovs_rwlock_unlock(&ofproto->ml->rwlock);
2490 }
2491 \f
2492 /* Ports. */
2493
2494 static struct ofport_dpif *
2495 get_ofp_port(const struct ofproto_dpif *ofproto, ofp_port_t ofp_port)
2496 {
2497     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
2498     return ofport ? ofport_dpif_cast(ofport) : NULL;
2499 }
2500
2501 static void
2502 ofproto_port_from_dpif_port(struct ofproto_dpif *ofproto,
2503                             struct ofproto_port *ofproto_port,
2504                             struct dpif_port *dpif_port)
2505 {
2506     ofproto_port->name = dpif_port->name;
2507     ofproto_port->type = dpif_port->type;
2508     ofproto_port->ofp_port = odp_port_to_ofp_port(ofproto, dpif_port->port_no);
2509 }
2510
2511 static void
2512 ofport_update_peer(struct ofport_dpif *ofport)
2513 {
2514     const struct ofproto_dpif *ofproto;
2515     struct dpif_backer *backer;
2516     char *peer_name;
2517
2518     if (!netdev_vport_is_patch(ofport->up.netdev)) {
2519         return;
2520     }
2521
2522     backer = ofproto_dpif_cast(ofport->up.ofproto)->backer;
2523     backer->need_revalidate = REV_RECONFIGURE;
2524
2525     if (ofport->peer) {
2526         ofport->peer->peer = NULL;
2527         ofport->peer = NULL;
2528     }
2529
2530     peer_name = netdev_vport_patch_peer(ofport->up.netdev);
2531     if (!peer_name) {
2532         return;
2533     }
2534
2535     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2536         struct ofport *peer_ofport;
2537         struct ofport_dpif *peer;
2538         char *peer_peer;
2539
2540         if (ofproto->backer != backer) {
2541             continue;
2542         }
2543
2544         peer_ofport = shash_find_data(&ofproto->up.port_by_name, peer_name);
2545         if (!peer_ofport) {
2546             continue;
2547         }
2548
2549         peer = ofport_dpif_cast(peer_ofport);
2550         peer_peer = netdev_vport_patch_peer(peer->up.netdev);
2551         if (peer_peer && !strcmp(netdev_get_name(ofport->up.netdev),
2552                                  peer_peer)) {
2553             ofport->peer = peer;
2554             ofport->peer->peer = ofport;
2555         }
2556         free(peer_peer);
2557
2558         break;
2559     }
2560     free(peer_name);
2561 }
2562
2563 static void
2564 port_run(struct ofport_dpif *ofport)
2565 {
2566     long long int carrier_seq = netdev_get_carrier_resets(ofport->up.netdev);
2567     bool carrier_changed = carrier_seq != ofport->carrier_seq;
2568     bool enable = netdev_get_carrier(ofport->up.netdev);
2569     bool cfm_enable = false;
2570     bool bfd_enable = false;
2571
2572     ofport->carrier_seq = carrier_seq;
2573
2574     if (ofport->cfm) {
2575         int cfm_opup = cfm_get_opup(ofport->cfm);
2576
2577         cfm_enable = !cfm_get_fault(ofport->cfm);
2578
2579         if (cfm_opup >= 0) {
2580             cfm_enable = cfm_enable && cfm_opup;
2581         }
2582     }
2583
2584     if (ofport->bfd) {
2585         bfd_enable = bfd_forwarding(ofport->bfd);
2586     }
2587
2588     if (ofport->bfd || ofport->cfm) {
2589         enable = enable && (cfm_enable || bfd_enable);
2590     }
2591
2592     if (ofport->bundle) {
2593         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
2594         if (carrier_changed) {
2595             lacp_slave_carrier_changed(ofport->bundle->lacp, ofport);
2596         }
2597     }
2598
2599     if (ofport->may_enable != enable) {
2600         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2601         ofproto->backer->need_revalidate = REV_PORT_TOGGLED;
2602     }
2603
2604     ofport->may_enable = enable;
2605 }
2606
2607 static int
2608 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
2609                    struct ofproto_port *ofproto_port)
2610 {
2611     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2612     struct dpif_port dpif_port;
2613     int error;
2614
2615     if (sset_contains(&ofproto->ghost_ports, devname)) {
2616         const char *type = netdev_get_type_from_name(devname);
2617
2618         /* We may be called before ofproto->up.port_by_name is populated with
2619          * the appropriate ofport.  For this reason, we must get the name and
2620          * type from the netdev layer directly. */
2621         if (type) {
2622             const struct ofport *ofport;
2623
2624             ofport = shash_find_data(&ofproto->up.port_by_name, devname);
2625             ofproto_port->ofp_port = ofport ? ofport->ofp_port : OFPP_NONE;
2626             ofproto_port->name = xstrdup(devname);
2627             ofproto_port->type = xstrdup(type);
2628             return 0;
2629         }
2630         return ENODEV;
2631     }
2632
2633     if (!sset_contains(&ofproto->ports, devname)) {
2634         return ENODEV;
2635     }
2636     error = dpif_port_query_by_name(ofproto->backer->dpif,
2637                                     devname, &dpif_port);
2638     if (!error) {
2639         ofproto_port_from_dpif_port(ofproto, ofproto_port, &dpif_port);
2640     }
2641     return error;
2642 }
2643
2644 static int
2645 port_add(struct ofproto *ofproto_, struct netdev *netdev)
2646 {
2647     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2648     const char *devname = netdev_get_name(netdev);
2649     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
2650     const char *dp_port_name;
2651
2652     if (netdev_vport_is_patch(netdev)) {
2653         sset_add(&ofproto->ghost_ports, netdev_get_name(netdev));
2654         return 0;
2655     }
2656
2657     dp_port_name = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
2658     if (!dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
2659         odp_port_t port_no = ODPP_NONE;
2660         int error;
2661
2662         error = dpif_port_add(ofproto->backer->dpif, netdev, &port_no);
2663         if (error) {
2664             return error;
2665         }
2666         if (netdev_get_tunnel_config(netdev)) {
2667             simap_put(&ofproto->backer->tnl_backers,
2668                       dp_port_name, odp_to_u32(port_no));
2669         }
2670     }
2671
2672     if (netdev_get_tunnel_config(netdev)) {
2673         sset_add(&ofproto->ghost_ports, devname);
2674     } else {
2675         sset_add(&ofproto->ports, devname);
2676     }
2677     return 0;
2678 }
2679
2680 static int
2681 port_del(struct ofproto *ofproto_, ofp_port_t ofp_port)
2682 {
2683     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2684     struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
2685     int error = 0;
2686
2687     if (!ofport) {
2688         return 0;
2689     }
2690
2691     sset_find_and_delete(&ofproto->ghost_ports,
2692                          netdev_get_name(ofport->up.netdev));
2693     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2694     if (!ofport->is_tunnel && !netdev_vport_is_patch(ofport->up.netdev)) {
2695         error = dpif_port_del(ofproto->backer->dpif, ofport->odp_port);
2696         if (!error) {
2697             /* The caller is going to close ofport->up.netdev.  If this is a
2698              * bonded port, then the bond is using that netdev, so remove it
2699              * from the bond.  The client will need to reconfigure everything
2700              * after deleting ports, so then the slave will get re-added. */
2701             bundle_remove(&ofport->up);
2702         }
2703     }
2704     return error;
2705 }
2706
2707 static int
2708 port_get_stats(const struct ofport *ofport_, struct netdev_stats *stats)
2709 {
2710     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2711     int error;
2712
2713     error = netdev_get_stats(ofport->up.netdev, stats);
2714
2715     if (!error && ofport_->ofp_port == OFPP_LOCAL) {
2716         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2717
2718         ovs_mutex_lock(&ofproto->stats_mutex);
2719         /* ofproto->stats.tx_packets represents packets that we created
2720          * internally and sent to some port (e.g. packets sent with
2721          * ofproto_dpif_send_packet()).  Account for them as if they had
2722          * come from OFPP_LOCAL and got forwarded. */
2723
2724         if (stats->rx_packets != UINT64_MAX) {
2725             stats->rx_packets += ofproto->stats.tx_packets;
2726         }
2727
2728         if (stats->rx_bytes != UINT64_MAX) {
2729             stats->rx_bytes += ofproto->stats.tx_bytes;
2730         }
2731
2732         /* ofproto->stats.rx_packets represents packets that were received on
2733          * some port and we processed internally and dropped (e.g. STP).
2734          * Account for them as if they had been forwarded to OFPP_LOCAL. */
2735
2736         if (stats->tx_packets != UINT64_MAX) {
2737             stats->tx_packets += ofproto->stats.rx_packets;
2738         }
2739
2740         if (stats->tx_bytes != UINT64_MAX) {
2741             stats->tx_bytes += ofproto->stats.rx_bytes;
2742         }
2743         ovs_mutex_unlock(&ofproto->stats_mutex);
2744     }
2745
2746     return error;
2747 }
2748
2749 struct port_dump_state {
2750     uint32_t bucket;
2751     uint32_t offset;
2752     bool ghost;
2753
2754     struct ofproto_port port;
2755     bool has_port;
2756 };
2757
2758 static int
2759 port_dump_start(const struct ofproto *ofproto_ OVS_UNUSED, void **statep)
2760 {
2761     *statep = xzalloc(sizeof(struct port_dump_state));
2762     return 0;
2763 }
2764
2765 static int
2766 port_dump_next(const struct ofproto *ofproto_, void *state_,
2767                struct ofproto_port *port)
2768 {
2769     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2770     struct port_dump_state *state = state_;
2771     const struct sset *sset;
2772     struct sset_node *node;
2773
2774     if (state->has_port) {
2775         ofproto_port_destroy(&state->port);
2776         state->has_port = false;
2777     }
2778     sset = state->ghost ? &ofproto->ghost_ports : &ofproto->ports;
2779     while ((node = sset_at_position(sset, &state->bucket, &state->offset))) {
2780         int error;
2781
2782         error = port_query_by_name(ofproto_, node->name, &state->port);
2783         if (!error) {
2784             *port = state->port;
2785             state->has_port = true;
2786             return 0;
2787         } else if (error != ENODEV) {
2788             return error;
2789         }
2790     }
2791
2792     if (!state->ghost) {
2793         state->ghost = true;
2794         state->bucket = 0;
2795         state->offset = 0;
2796         return port_dump_next(ofproto_, state_, port);
2797     }
2798
2799     return EOF;
2800 }
2801
2802 static int
2803 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
2804 {
2805     struct port_dump_state *state = state_;
2806
2807     if (state->has_port) {
2808         ofproto_port_destroy(&state->port);
2809     }
2810     free(state);
2811     return 0;
2812 }
2813
2814 static int
2815 port_poll(const struct ofproto *ofproto_, char **devnamep)
2816 {
2817     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2818
2819     if (ofproto->port_poll_errno) {
2820         int error = ofproto->port_poll_errno;
2821         ofproto->port_poll_errno = 0;
2822         return error;
2823     }
2824
2825     if (sset_is_empty(&ofproto->port_poll_set)) {
2826         return EAGAIN;
2827     }
2828
2829     *devnamep = sset_pop(&ofproto->port_poll_set);
2830     return 0;
2831 }
2832
2833 static void
2834 port_poll_wait(const struct ofproto *ofproto_)
2835 {
2836     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2837     dpif_port_poll_wait(ofproto->backer->dpif);
2838 }
2839
2840 static int
2841 port_is_lacp_current(const struct ofport *ofport_)
2842 {
2843     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2844     return (ofport->bundle && ofport->bundle->lacp
2845             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
2846             : -1);
2847 }
2848 \f
2849 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
2850  * then delete it entirely. */
2851 static void
2852 rule_expire(struct rule_dpif *rule)
2853     OVS_REQUIRES(ofproto_mutex)
2854 {
2855     uint16_t idle_timeout, hard_timeout;
2856     long long int now = time_msec();
2857     int reason;
2858
2859     ovs_assert(!rule->up.pending);
2860
2861     /* Has 'rule' expired? */
2862     ovs_mutex_lock(&rule->up.mutex);
2863     hard_timeout = rule->up.hard_timeout;
2864     idle_timeout = rule->up.idle_timeout;
2865     if (hard_timeout && now > rule->up.modified + hard_timeout * 1000) {
2866         reason = OFPRR_HARD_TIMEOUT;
2867     } else if (idle_timeout && now > rule->up.used + idle_timeout * 1000) {
2868         reason = OFPRR_IDLE_TIMEOUT;
2869     } else {
2870         reason = -1;
2871     }
2872     ovs_mutex_unlock(&rule->up.mutex);
2873
2874     if (reason >= 0) {
2875         COVERAGE_INC(ofproto_dpif_expired);
2876         ofproto_rule_expire(&rule->up, reason);
2877     }
2878 }
2879
2880 /* Executes, within 'ofproto', the actions in 'rule' or 'ofpacts' on 'packet'.
2881  * 'flow' must reflect the data in 'packet'. */
2882 int
2883 ofproto_dpif_execute_actions(struct ofproto_dpif *ofproto,
2884                              const struct flow *flow,
2885                              struct rule_dpif *rule,
2886                              const struct ofpact *ofpacts, size_t ofpacts_len,
2887                              struct ofpbuf *packet)
2888 {
2889     struct dpif_flow_stats stats;
2890     struct xlate_out xout;
2891     struct xlate_in xin;
2892     ofp_port_t in_port;
2893     struct dpif_execute execute;
2894     int error;
2895
2896     ovs_assert((rule != NULL) != (ofpacts != NULL));
2897
2898     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
2899     if (rule) {
2900         rule_dpif_credit_stats(rule, &stats);
2901     }
2902
2903     xlate_in_init(&xin, ofproto, flow, rule, stats.tcp_flags, packet);
2904     xin.ofpacts = ofpacts;
2905     xin.ofpacts_len = ofpacts_len;
2906     xin.resubmit_stats = &stats;
2907     xlate_actions(&xin, &xout);
2908
2909     in_port = flow->in_port.ofp_port;
2910     if (in_port == OFPP_NONE) {
2911         in_port = OFPP_LOCAL;
2912     }
2913     execute.actions = xout.odp_actions.data;
2914     execute.actions_len = xout.odp_actions.size;
2915     execute.packet = packet;
2916     execute.md.tunnel = flow->tunnel;
2917     execute.md.skb_priority = flow->skb_priority;
2918     execute.md.pkt_mark = flow->pkt_mark;
2919     execute.md.in_port = ofp_port_to_odp_port(ofproto, in_port);
2920     execute.needs_help = (xout.slow & SLOW_ACTION) != 0;
2921
2922     error = dpif_execute(ofproto->backer->dpif, &execute);
2923
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 };