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