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