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