ca7c0b131a3251d79e38709047d3544d8ef0fc9d
[cascardo/ovs.git] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "ofproto/ofproto-dpif.h"
20 #include "ofproto/ofproto-provider.h"
21
22 #include <errno.h>
23
24 #include "bfd.h"
25 #include "bond.h"
26 #include "bundle.h"
27 #include "byte-order.h"
28 #include "connectivity.h"
29 #include "connmgr.h"
30 #include "coverage.h"
31 #include "cfm.h"
32 #include "dpif.h"
33 #include "dynamic-string.h"
34 #include "fail-open.h"
35 #include "guarded-list.h"
36 #include "hmapx.h"
37 #include "lacp.h"
38 #include "learn.h"
39 #include "mac-learning.h"
40 #include "meta-flow.h"
41 #include "multipath.h"
42 #include "netdev-vport.h"
43 #include "netdev.h"
44 #include "netlink.h"
45 #include "nx-match.h"
46 #include "odp-util.h"
47 #include "odp-execute.h"
48 #include "ofp-util.h"
49 #include "ofpbuf.h"
50 #include "ofp-actions.h"
51 #include "ofp-parse.h"
52 #include "ofp-print.h"
53 #include "ofproto-dpif-ipfix.h"
54 #include "ofproto-dpif-mirror.h"
55 #include "ofproto-dpif-monitor.h"
56 #include "ofproto-dpif-sflow.h"
57 #include "ofproto-dpif-upcall.h"
58 #include "ofproto-dpif-xlate.h"
59 #include "poll-loop.h"
60 #include "seq.h"
61 #include "simap.h"
62 #include "smap.h"
63 #include "timer.h"
64 #include "tunnel.h"
65 #include "unaligned.h"
66 #include "unixctl.h"
67 #include "vlan-bitmap.h"
68 #include "vlog.h"
69
70 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
71
72 COVERAGE_DEFINE(ofproto_dpif_expired);
73 COVERAGE_DEFINE(packet_in_overflow);
74
75 /* Number of implemented OpenFlow tables. */
76 enum { N_TABLES = 255 };
77 enum { TBL_INTERNAL = N_TABLES - 1 };    /* Used for internal hidden rules. */
78 BUILD_ASSERT_DECL(N_TABLES >= 2 && N_TABLES <= 255);
79
80 struct flow_miss;
81
82 struct rule_dpif {
83     struct rule up;
84
85     /* These statistics:
86      *
87      *   - Do include packets and bytes from datapath flows which have not
88      *   recently been processed by a revalidator. */
89     struct ovs_mutex stats_mutex;
90     uint64_t packet_count OVS_GUARDED;  /* Number of packets received. */
91     uint64_t byte_count OVS_GUARDED;    /* Number of bytes received. */
92 };
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     /* Ensure that the upcall processing threads have no remaining references
1039      * to the ofproto or anything in it. */
1040     udpif_synchronize(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         fat_rwlock_rdlock(&table->cls.rwlock);
1048         cls_cursor_init(&cursor, &table->cls, NULL);
1049         fat_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 (port->stp_port) {
1405         stp_port_disable(port->stp_port);
1406     }
1407     if (ofproto->sflow) {
1408         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
1409     }
1410
1411     free(port->qdscp);
1412 }
1413
1414 static void
1415 port_modified(struct ofport *port_)
1416 {
1417     struct ofport_dpif *port = ofport_dpif_cast(port_);
1418
1419     if (port->bundle && port->bundle->bond) {
1420         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
1421     }
1422
1423     if (port->cfm) {
1424         cfm_set_netdev(port->cfm, port->up.netdev);
1425     }
1426
1427     if (port->bfd) {
1428         bfd_set_netdev(port->bfd, port->up.netdev);
1429     }
1430
1431     ofproto_dpif_monitor_port_update(port, port->bfd, port->cfm,
1432                                      port->up.pp.hw_addr);
1433
1434     if (port->is_tunnel && tnl_port_reconfigure(port, port->up.netdev,
1435                                                 port->odp_port)) {
1436         ofproto_dpif_cast(port->up.ofproto)->backer->need_revalidate =
1437             REV_RECONFIGURE;
1438     }
1439
1440     ofport_update_peer(port);
1441 }
1442
1443 static void
1444 port_reconfigured(struct ofport *port_, enum ofputil_port_config old_config)
1445 {
1446     struct ofport_dpif *port = ofport_dpif_cast(port_);
1447     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1448     enum ofputil_port_config changed = old_config ^ port->up.pp.config;
1449
1450     if (changed & (OFPUTIL_PC_NO_RECV | OFPUTIL_PC_NO_RECV_STP |
1451                    OFPUTIL_PC_NO_FWD | OFPUTIL_PC_NO_FLOOD |
1452                    OFPUTIL_PC_NO_PACKET_IN)) {
1453         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1454
1455         if (changed & OFPUTIL_PC_NO_FLOOD && port->bundle) {
1456             bundle_update(port->bundle);
1457         }
1458     }
1459 }
1460
1461 static int
1462 set_sflow(struct ofproto *ofproto_,
1463           const struct ofproto_sflow_options *sflow_options)
1464 {
1465     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1466     struct dpif_sflow *ds = ofproto->sflow;
1467
1468     if (sflow_options) {
1469         if (!ds) {
1470             struct ofport_dpif *ofport;
1471
1472             ds = ofproto->sflow = dpif_sflow_create();
1473             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1474                 dpif_sflow_add_port(ds, &ofport->up, ofport->odp_port);
1475             }
1476             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1477         }
1478         dpif_sflow_set_options(ds, sflow_options);
1479     } else {
1480         if (ds) {
1481             dpif_sflow_unref(ds);
1482             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1483             ofproto->sflow = NULL;
1484         }
1485     }
1486     return 0;
1487 }
1488
1489 static int
1490 set_ipfix(
1491     struct ofproto *ofproto_,
1492     const struct ofproto_ipfix_bridge_exporter_options *bridge_exporter_options,
1493     const struct ofproto_ipfix_flow_exporter_options *flow_exporters_options,
1494     size_t n_flow_exporters_options)
1495 {
1496     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1497     struct dpif_ipfix *di = ofproto->ipfix;
1498     bool has_options = bridge_exporter_options || flow_exporters_options;
1499
1500     if (has_options && !di) {
1501         di = ofproto->ipfix = dpif_ipfix_create();
1502     }
1503
1504     if (di) {
1505         /* Call set_options in any case to cleanly flush the flow
1506          * caches in the last exporters that are to be destroyed. */
1507         dpif_ipfix_set_options(
1508             di, bridge_exporter_options, flow_exporters_options,
1509             n_flow_exporters_options);
1510
1511         if (!has_options) {
1512             dpif_ipfix_unref(di);
1513             ofproto->ipfix = NULL;
1514         }
1515     }
1516
1517     return 0;
1518 }
1519
1520 static int
1521 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
1522 {
1523     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1524     int error = 0;
1525
1526     if (s) {
1527         if (!ofport->cfm) {
1528             struct ofproto_dpif *ofproto;
1529
1530             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1531             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1532             ofport->cfm = cfm_create(ofport->up.netdev);
1533         }
1534
1535         if (cfm_configure(ofport->cfm, s)) {
1536             error = 0;
1537             goto out;
1538         }
1539
1540         error = EINVAL;
1541     }
1542     cfm_unref(ofport->cfm);
1543     ofport->cfm = NULL;
1544 out:
1545     ofproto_dpif_monitor_port_update(ofport, ofport->bfd, ofport->cfm,
1546                                      ofport->up.pp.hw_addr);
1547     return error;
1548 }
1549
1550 static bool
1551 get_cfm_status(const struct ofport *ofport_,
1552                struct ofproto_cfm_status *status)
1553 {
1554     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1555
1556     if (ofport->cfm) {
1557         status->faults = cfm_get_fault(ofport->cfm);
1558         status->flap_count = cfm_get_flap_count(ofport->cfm);
1559         status->remote_opstate = cfm_get_opup(ofport->cfm);
1560         status->health = cfm_get_health(ofport->cfm);
1561         cfm_get_remote_mpids(ofport->cfm, &status->rmps, &status->n_rmps);
1562         return true;
1563     } else {
1564         return false;
1565     }
1566 }
1567
1568 static int
1569 set_bfd(struct ofport *ofport_, const struct smap *cfg)
1570 {
1571     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
1572     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1573     struct bfd *old;
1574
1575     old = ofport->bfd;
1576     ofport->bfd = bfd_configure(old, netdev_get_name(ofport->up.netdev),
1577                                 cfg, ofport->up.netdev);
1578     if (ofport->bfd != old) {
1579         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1580     }
1581     ofproto_dpif_monitor_port_update(ofport, ofport->bfd, ofport->cfm,
1582                                      ofport->up.pp.hw_addr);
1583     return 0;
1584 }
1585
1586 static int
1587 get_bfd_status(struct ofport *ofport_, struct smap *smap)
1588 {
1589     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1590
1591     if (ofport->bfd) {
1592         bfd_get_status(ofport->bfd, smap);
1593         return 0;
1594     } else {
1595         return ENOENT;
1596     }
1597 }
1598 \f
1599 /* Spanning Tree. */
1600
1601 static void
1602 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
1603 {
1604     struct ofproto_dpif *ofproto = ofproto_;
1605     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
1606     struct ofport_dpif *ofport;
1607
1608     ofport = stp_port_get_aux(sp);
1609     if (!ofport) {
1610         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
1611                      ofproto->up.name, port_num);
1612     } else {
1613         struct eth_header *eth = pkt->l2;
1614
1615         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
1616         if (eth_addr_is_zero(eth->eth_src)) {
1617             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
1618                          "with unknown MAC", ofproto->up.name, port_num);
1619         } else {
1620             ofproto_dpif_send_packet(ofport, pkt);
1621         }
1622     }
1623     ofpbuf_delete(pkt);
1624 }
1625
1626 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
1627 static int
1628 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
1629 {
1630     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1631
1632     /* Only revalidate flows if the configuration changed. */
1633     if (!s != !ofproto->stp) {
1634         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1635     }
1636
1637     if (s) {
1638         if (!ofproto->stp) {
1639             ofproto->stp = stp_create(ofproto_->name, s->system_id,
1640                                       send_bpdu_cb, ofproto);
1641             ofproto->stp_last_tick = time_msec();
1642         }
1643
1644         stp_set_bridge_id(ofproto->stp, s->system_id);
1645         stp_set_bridge_priority(ofproto->stp, s->priority);
1646         stp_set_hello_time(ofproto->stp, s->hello_time);
1647         stp_set_max_age(ofproto->stp, s->max_age);
1648         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
1649     }  else {
1650         struct ofport *ofport;
1651
1652         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
1653             set_stp_port(ofport, NULL);
1654         }
1655
1656         stp_unref(ofproto->stp);
1657         ofproto->stp = NULL;
1658     }
1659
1660     return 0;
1661 }
1662
1663 static int
1664 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
1665 {
1666     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1667
1668     if (ofproto->stp) {
1669         s->enabled = true;
1670         s->bridge_id = stp_get_bridge_id(ofproto->stp);
1671         s->designated_root = stp_get_designated_root(ofproto->stp);
1672         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
1673     } else {
1674         s->enabled = false;
1675     }
1676
1677     return 0;
1678 }
1679
1680 static void
1681 update_stp_port_state(struct ofport_dpif *ofport)
1682 {
1683     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1684     enum stp_state state;
1685
1686     /* Figure out new state. */
1687     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
1688                              : STP_DISABLED;
1689
1690     /* Update state. */
1691     if (ofport->stp_state != state) {
1692         enum ofputil_port_state of_state;
1693         bool fwd_change;
1694
1695         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
1696                     netdev_get_name(ofport->up.netdev),
1697                     stp_state_name(ofport->stp_state),
1698                     stp_state_name(state));
1699         if (stp_learn_in_state(ofport->stp_state)
1700                 != stp_learn_in_state(state)) {
1701             /* xxx Learning action flows should also be flushed. */
1702             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
1703             mac_learning_flush(ofproto->ml);
1704             ovs_rwlock_unlock(&ofproto->ml->rwlock);
1705         }
1706         fwd_change = stp_forward_in_state(ofport->stp_state)
1707                         != stp_forward_in_state(state);
1708
1709         ofproto->backer->need_revalidate = REV_STP;
1710         ofport->stp_state = state;
1711         ofport->stp_state_entered = time_msec();
1712
1713         if (fwd_change && ofport->bundle) {
1714             bundle_update(ofport->bundle);
1715         }
1716
1717         /* Update the STP state bits in the OpenFlow port description. */
1718         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
1719         of_state |= (state == STP_LISTENING ? OFPUTIL_PS_STP_LISTEN
1720                      : state == STP_LEARNING ? OFPUTIL_PS_STP_LEARN
1721                      : state == STP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
1722                      : state == STP_BLOCKING ?  OFPUTIL_PS_STP_BLOCK
1723                      : 0);
1724         ofproto_port_set_state(&ofport->up, of_state);
1725     }
1726 }
1727
1728 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
1729  * caller is responsible for assigning STP port numbers and ensuring
1730  * there are no duplicates. */
1731 static int
1732 set_stp_port(struct ofport *ofport_,
1733              const struct ofproto_port_stp_settings *s)
1734 {
1735     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1736     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1737     struct stp_port *sp = ofport->stp_port;
1738
1739     if (!s || !s->enable) {
1740         if (sp) {
1741             ofport->stp_port = NULL;
1742             stp_port_disable(sp);
1743             update_stp_port_state(ofport);
1744         }
1745         return 0;
1746     } else if (sp && stp_port_no(sp) != s->port_num
1747             && ofport == stp_port_get_aux(sp)) {
1748         /* The port-id changed, so disable the old one if it's not
1749          * already in use by another port. */
1750         stp_port_disable(sp);
1751     }
1752
1753     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
1754     stp_port_enable(sp);
1755
1756     stp_port_set_aux(sp, ofport);
1757     stp_port_set_priority(sp, s->priority);
1758     stp_port_set_path_cost(sp, s->path_cost);
1759
1760     update_stp_port_state(ofport);
1761
1762     return 0;
1763 }
1764
1765 static int
1766 get_stp_port_status(struct ofport *ofport_,
1767                     struct ofproto_port_stp_status *s)
1768 {
1769     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1770     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1771     struct stp_port *sp = ofport->stp_port;
1772
1773     if (!ofproto->stp || !sp) {
1774         s->enabled = false;
1775         return 0;
1776     }
1777
1778     s->enabled = true;
1779     s->port_id = stp_port_get_id(sp);
1780     s->state = stp_port_get_state(sp);
1781     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
1782     s->role = stp_port_get_role(sp);
1783
1784     return 0;
1785 }
1786
1787 static int
1788 get_stp_port_stats(struct ofport *ofport_,
1789                    struct ofproto_port_stp_stats *s)
1790 {
1791     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1792     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1793     struct stp_port *sp = ofport->stp_port;
1794
1795     if (!ofproto->stp || !sp) {
1796         s->enabled = false;
1797         return 0;
1798     }
1799
1800     s->enabled = true;
1801     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
1802
1803     return 0;
1804 }
1805
1806 static void
1807 stp_run(struct ofproto_dpif *ofproto)
1808 {
1809     if (ofproto->stp) {
1810         long long int now = time_msec();
1811         long long int elapsed = now - ofproto->stp_last_tick;
1812         struct stp_port *sp;
1813
1814         if (elapsed > 0) {
1815             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
1816             ofproto->stp_last_tick = now;
1817         }
1818         while (stp_get_changed_port(ofproto->stp, &sp)) {
1819             struct ofport_dpif *ofport = stp_port_get_aux(sp);
1820
1821             if (ofport) {
1822                 update_stp_port_state(ofport);
1823             }
1824         }
1825
1826         if (stp_check_and_reset_fdb_flush(ofproto->stp)) {
1827             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
1828             mac_learning_flush(ofproto->ml);
1829             ovs_rwlock_unlock(&ofproto->ml->rwlock);
1830         }
1831     }
1832 }
1833
1834 static void
1835 stp_wait(struct ofproto_dpif *ofproto)
1836 {
1837     if (ofproto->stp) {
1838         poll_timer_wait(1000);
1839     }
1840 }
1841 \f
1842 static int
1843 set_queues(struct ofport *ofport_, const struct ofproto_port_queue *qdscp,
1844            size_t n_qdscp)
1845 {
1846     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1847     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1848
1849     if (ofport->n_qdscp != n_qdscp
1850         || (n_qdscp && memcmp(ofport->qdscp, qdscp,
1851                               n_qdscp * sizeof *qdscp))) {
1852         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1853         free(ofport->qdscp);
1854         ofport->qdscp = n_qdscp
1855             ? xmemdup(qdscp, n_qdscp * sizeof *qdscp)
1856             : NULL;
1857         ofport->n_qdscp = n_qdscp;
1858     }
1859
1860     return 0;
1861 }
1862 \f
1863 /* Bundles. */
1864
1865 /* Expires all MAC learning entries associated with 'bundle' and forces its
1866  * ofproto to revalidate every flow.
1867  *
1868  * Normally MAC learning entries are removed only from the ofproto associated
1869  * with 'bundle', but if 'all_ofprotos' is true, then the MAC learning entries
1870  * are removed from every ofproto.  When patch ports and SLB bonds are in use
1871  * and a VM migration happens and the gratuitous ARPs are somehow lost, this
1872  * avoids a MAC_ENTRY_IDLE_TIME delay before the migrated VM can communicate
1873  * with the host from which it migrated. */
1874 static void
1875 bundle_flush_macs(struct ofbundle *bundle, bool all_ofprotos)
1876 {
1877     struct ofproto_dpif *ofproto = bundle->ofproto;
1878     struct mac_learning *ml = ofproto->ml;
1879     struct mac_entry *mac, *next_mac;
1880
1881     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1882     ovs_rwlock_wrlock(&ml->rwlock);
1883     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
1884         if (mac->port.p == bundle) {
1885             if (all_ofprotos) {
1886                 struct ofproto_dpif *o;
1887
1888                 HMAP_FOR_EACH (o, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
1889                     if (o != ofproto) {
1890                         struct mac_entry *e;
1891
1892                         ovs_rwlock_wrlock(&o->ml->rwlock);
1893                         e = mac_learning_lookup(o->ml, mac->mac, mac->vlan);
1894                         if (e) {
1895                             mac_learning_expire(o->ml, e);
1896                         }
1897                         ovs_rwlock_unlock(&o->ml->rwlock);
1898                     }
1899                 }
1900             }
1901
1902             mac_learning_expire(ml, mac);
1903         }
1904     }
1905     ovs_rwlock_unlock(&ml->rwlock);
1906 }
1907
1908 static struct ofbundle *
1909 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
1910 {
1911     struct ofbundle *bundle;
1912
1913     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
1914                              &ofproto->bundles) {
1915         if (bundle->aux == aux) {
1916             return bundle;
1917         }
1918     }
1919     return NULL;
1920 }
1921
1922 static void
1923 bundle_update(struct ofbundle *bundle)
1924 {
1925     struct ofport_dpif *port;
1926
1927     bundle->floodable = true;
1928     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1929         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
1930             || port->is_layer3
1931             || !stp_forward_in_state(port->stp_state)) {
1932             bundle->floodable = false;
1933             break;
1934         }
1935     }
1936 }
1937
1938 static void
1939 bundle_del_port(struct ofport_dpif *port)
1940 {
1941     struct ofbundle *bundle = port->bundle;
1942
1943     bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
1944
1945     list_remove(&port->bundle_node);
1946     port->bundle = NULL;
1947
1948     if (bundle->lacp) {
1949         lacp_slave_unregister(bundle->lacp, port);
1950     }
1951     if (bundle->bond) {
1952         bond_slave_unregister(bundle->bond, port);
1953     }
1954
1955     bundle_update(bundle);
1956 }
1957
1958 static bool
1959 bundle_add_port(struct ofbundle *bundle, ofp_port_t ofp_port,
1960                 struct lacp_slave_settings *lacp)
1961 {
1962     struct ofport_dpif *port;
1963
1964     port = get_ofp_port(bundle->ofproto, ofp_port);
1965     if (!port) {
1966         return false;
1967     }
1968
1969     if (port->bundle != bundle) {
1970         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
1971         if (port->bundle) {
1972             bundle_remove(&port->up);
1973         }
1974
1975         port->bundle = bundle;
1976         list_push_back(&bundle->ports, &port->bundle_node);
1977         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
1978             || port->is_layer3
1979             || !stp_forward_in_state(port->stp_state)) {
1980             bundle->floodable = false;
1981         }
1982     }
1983     if (lacp) {
1984         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
1985         lacp_slave_register(bundle->lacp, port, lacp);
1986     }
1987
1988     return true;
1989 }
1990
1991 static void
1992 bundle_destroy(struct ofbundle *bundle)
1993 {
1994     struct ofproto_dpif *ofproto;
1995     struct ofport_dpif *port, *next_port;
1996
1997     if (!bundle) {
1998         return;
1999     }
2000
2001     ofproto = bundle->ofproto;
2002     mbridge_unregister_bundle(ofproto->mbridge, bundle->aux);
2003
2004     ovs_rwlock_wrlock(&xlate_rwlock);
2005     xlate_bundle_remove(bundle);
2006     ovs_rwlock_unlock(&xlate_rwlock);
2007
2008     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2009         bundle_del_port(port);
2010     }
2011
2012     bundle_flush_macs(bundle, true);
2013     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
2014     free(bundle->name);
2015     free(bundle->trunks);
2016     lacp_unref(bundle->lacp);
2017     bond_unref(bundle->bond);
2018     free(bundle);
2019 }
2020
2021 static int
2022 bundle_set(struct ofproto *ofproto_, void *aux,
2023            const struct ofproto_bundle_settings *s)
2024 {
2025     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2026     bool need_flush = false;
2027     struct ofport_dpif *port;
2028     struct ofbundle *bundle;
2029     unsigned long *trunks;
2030     int vlan;
2031     size_t i;
2032     bool ok;
2033
2034     if (!s) {
2035         bundle_destroy(bundle_lookup(ofproto, aux));
2036         return 0;
2037     }
2038
2039     ovs_assert(s->n_slaves == 1 || s->bond != NULL);
2040     ovs_assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
2041
2042     bundle = bundle_lookup(ofproto, aux);
2043     if (!bundle) {
2044         bundle = xmalloc(sizeof *bundle);
2045
2046         bundle->ofproto = ofproto;
2047         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
2048                     hash_pointer(aux, 0));
2049         bundle->aux = aux;
2050         bundle->name = NULL;
2051
2052         list_init(&bundle->ports);
2053         bundle->vlan_mode = PORT_VLAN_TRUNK;
2054         bundle->vlan = -1;
2055         bundle->trunks = NULL;
2056         bundle->use_priority_tags = s->use_priority_tags;
2057         bundle->lacp = NULL;
2058         bundle->bond = NULL;
2059
2060         bundle->floodable = true;
2061         mbridge_register_bundle(ofproto->mbridge, bundle);
2062     }
2063
2064     if (!bundle->name || strcmp(s->name, bundle->name)) {
2065         free(bundle->name);
2066         bundle->name = xstrdup(s->name);
2067     }
2068
2069     /* LACP. */
2070     if (s->lacp) {
2071         ofproto->lacp_enabled = true;
2072         if (!bundle->lacp) {
2073             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2074             bundle->lacp = lacp_create();
2075         }
2076         lacp_configure(bundle->lacp, s->lacp);
2077     } else {
2078         lacp_unref(bundle->lacp);
2079         bundle->lacp = NULL;
2080     }
2081
2082     /* Update set of ports. */
2083     ok = true;
2084     for (i = 0; i < s->n_slaves; i++) {
2085         if (!bundle_add_port(bundle, s->slaves[i],
2086                              s->lacp ? &s->lacp_slaves[i] : NULL)) {
2087             ok = false;
2088         }
2089     }
2090     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
2091         struct ofport_dpif *next_port;
2092
2093         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2094             for (i = 0; i < s->n_slaves; i++) {
2095                 if (s->slaves[i] == port->up.ofp_port) {
2096                     goto found;
2097                 }
2098             }
2099
2100             bundle_del_port(port);
2101         found: ;
2102         }
2103     }
2104     ovs_assert(list_size(&bundle->ports) <= s->n_slaves);
2105
2106     if (list_is_empty(&bundle->ports)) {
2107         bundle_destroy(bundle);
2108         return EINVAL;
2109     }
2110
2111     /* Set VLAN tagging mode */
2112     if (s->vlan_mode != bundle->vlan_mode
2113         || s->use_priority_tags != bundle->use_priority_tags) {
2114         bundle->vlan_mode = s->vlan_mode;
2115         bundle->use_priority_tags = s->use_priority_tags;
2116         need_flush = true;
2117     }
2118
2119     /* Set VLAN tag. */
2120     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
2121             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
2122             : 0);
2123     if (vlan != bundle->vlan) {
2124         bundle->vlan = vlan;
2125         need_flush = true;
2126     }
2127
2128     /* Get trunked VLANs. */
2129     switch (s->vlan_mode) {
2130     case PORT_VLAN_ACCESS:
2131         trunks = NULL;
2132         break;
2133
2134     case PORT_VLAN_TRUNK:
2135         trunks = CONST_CAST(unsigned long *, s->trunks);
2136         break;
2137
2138     case PORT_VLAN_NATIVE_UNTAGGED:
2139     case PORT_VLAN_NATIVE_TAGGED:
2140         if (vlan != 0 && (!s->trunks
2141                           || !bitmap_is_set(s->trunks, vlan)
2142                           || bitmap_is_set(s->trunks, 0))) {
2143             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
2144             if (s->trunks) {
2145                 trunks = bitmap_clone(s->trunks, 4096);
2146             } else {
2147                 trunks = bitmap_allocate1(4096);
2148             }
2149             bitmap_set1(trunks, vlan);
2150             bitmap_set0(trunks, 0);
2151         } else {
2152             trunks = CONST_CAST(unsigned long *, s->trunks);
2153         }
2154         break;
2155
2156     default:
2157         OVS_NOT_REACHED();
2158     }
2159     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
2160         free(bundle->trunks);
2161         if (trunks == s->trunks) {
2162             bundle->trunks = vlan_bitmap_clone(trunks);
2163         } else {
2164             bundle->trunks = trunks;
2165             trunks = NULL;
2166         }
2167         need_flush = true;
2168     }
2169     if (trunks != s->trunks) {
2170         free(trunks);
2171     }
2172
2173     /* Bonding. */
2174     if (!list_is_short(&bundle->ports)) {
2175         bundle->ofproto->has_bonded_bundles = true;
2176         if (bundle->bond) {
2177             if (bond_reconfigure(bundle->bond, s->bond)) {
2178                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2179             }
2180         } else {
2181             bundle->bond = bond_create(s->bond);
2182             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2183         }
2184
2185         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2186             bond_slave_register(bundle->bond, port, port->up.netdev);
2187         }
2188     } else {
2189         bond_unref(bundle->bond);
2190         bundle->bond = NULL;
2191     }
2192
2193     /* If we changed something that would affect MAC learning, un-learn
2194      * everything on this port and force flow revalidation. */
2195     if (need_flush) {
2196         bundle_flush_macs(bundle, false);
2197     }
2198
2199     return 0;
2200 }
2201
2202 static void
2203 bundle_remove(struct ofport *port_)
2204 {
2205     struct ofport_dpif *port = ofport_dpif_cast(port_);
2206     struct ofbundle *bundle = port->bundle;
2207
2208     if (bundle) {
2209         bundle_del_port(port);
2210         if (list_is_empty(&bundle->ports)) {
2211             bundle_destroy(bundle);
2212         } else if (list_is_short(&bundle->ports)) {
2213             bond_unref(bundle->bond);
2214             bundle->bond = NULL;
2215         }
2216     }
2217 }
2218
2219 static void
2220 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
2221 {
2222     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
2223     struct ofport_dpif *port = port_;
2224     uint8_t ea[ETH_ADDR_LEN];
2225     int error;
2226
2227     error = netdev_get_etheraddr(port->up.netdev, ea);
2228     if (!error) {
2229         struct ofpbuf packet;
2230         void *packet_pdu;
2231
2232         ofpbuf_init(&packet, 0);
2233         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
2234                                  pdu_size);
2235         memcpy(packet_pdu, pdu, pdu_size);
2236
2237         ofproto_dpif_send_packet(port, &packet);
2238         ofpbuf_uninit(&packet);
2239     } else {
2240         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
2241                     "%s (%s)", port->bundle->name,
2242                     netdev_get_name(port->up.netdev), ovs_strerror(error));
2243     }
2244 }
2245
2246 static void
2247 bundle_send_learning_packets(struct ofbundle *bundle)
2248 {
2249     struct ofproto_dpif *ofproto = bundle->ofproto;
2250     struct ofpbuf *learning_packet;
2251     int error, n_packets, n_errors;
2252     struct mac_entry *e;
2253     struct list packets;
2254
2255     list_init(&packets);
2256     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
2257     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
2258         if (e->port.p != bundle) {
2259             void *port_void;
2260
2261             learning_packet = bond_compose_learning_packet(bundle->bond,
2262                                                            e->mac, e->vlan,
2263                                                            &port_void);
2264             learning_packet->private_p = port_void;
2265             list_push_back(&packets, &learning_packet->list_node);
2266         }
2267     }
2268     ovs_rwlock_unlock(&ofproto->ml->rwlock);
2269
2270     error = n_packets = n_errors = 0;
2271     LIST_FOR_EACH (learning_packet, list_node, &packets) {
2272         int ret;
2273
2274         ret = ofproto_dpif_send_packet(learning_packet->private_p, learning_packet);
2275         if (ret) {
2276             error = ret;
2277             n_errors++;
2278         }
2279         n_packets++;
2280     }
2281     ofpbuf_list_delete(&packets);
2282
2283     if (n_errors) {
2284         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2285         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
2286                      "packets, last error was: %s",
2287                      bundle->name, n_errors, n_packets, ovs_strerror(error));
2288     } else {
2289         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
2290                  bundle->name, n_packets);
2291     }
2292 }
2293
2294 static void
2295 bundle_run(struct ofbundle *bundle)
2296 {
2297     if (bundle->lacp) {
2298         lacp_run(bundle->lacp, send_pdu_cb);
2299     }
2300     if (bundle->bond) {
2301         struct ofport_dpif *port;
2302
2303         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2304             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
2305         }
2306
2307         if (bond_run(bundle->bond, lacp_status(bundle->lacp))) {
2308             bundle->ofproto->backer->need_revalidate = REV_BOND;
2309         }
2310
2311         if (bond_should_send_learning_packets(bundle->bond)) {
2312             bundle_send_learning_packets(bundle);
2313         }
2314     }
2315 }
2316
2317 static void
2318 bundle_wait(struct ofbundle *bundle)
2319 {
2320     if (bundle->lacp) {
2321         lacp_wait(bundle->lacp);
2322     }
2323     if (bundle->bond) {
2324         bond_wait(bundle->bond);
2325     }
2326 }
2327 \f
2328 /* Mirrors. */
2329
2330 static int
2331 mirror_set__(struct ofproto *ofproto_, void *aux,
2332              const struct ofproto_mirror_settings *s)
2333 {
2334     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2335     struct ofbundle **srcs, **dsts;
2336     int error;
2337     size_t i;
2338
2339     if (!s) {
2340         mirror_destroy(ofproto->mbridge, aux);
2341         return 0;
2342     }
2343
2344     srcs = xmalloc(s->n_srcs * sizeof *srcs);
2345     dsts = xmalloc(s->n_dsts * sizeof *dsts);
2346
2347     for (i = 0; i < s->n_srcs; i++) {
2348         srcs[i] = bundle_lookup(ofproto, s->srcs[i]);
2349     }
2350
2351     for (i = 0; i < s->n_dsts; i++) {
2352         dsts[i] = bundle_lookup(ofproto, s->dsts[i]);
2353     }
2354
2355     error = mirror_set(ofproto->mbridge, aux, s->name, srcs, s->n_srcs, dsts,
2356                        s->n_dsts, s->src_vlans,
2357                        bundle_lookup(ofproto, s->out_bundle), s->out_vlan);
2358     free(srcs);
2359     free(dsts);
2360     return error;
2361 }
2362
2363 static int
2364 mirror_get_stats__(struct ofproto *ofproto, void *aux,
2365                    uint64_t *packets, uint64_t *bytes)
2366 {
2367     return mirror_get_stats(ofproto_dpif_cast(ofproto)->mbridge, aux, packets,
2368                             bytes);
2369 }
2370
2371 static int
2372 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
2373 {
2374     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2375     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
2376     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
2377         mac_learning_flush(ofproto->ml);
2378     }
2379     ovs_rwlock_unlock(&ofproto->ml->rwlock);
2380     return 0;
2381 }
2382
2383 static bool
2384 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
2385 {
2386     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2387     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
2388     return bundle && mirror_bundle_out(ofproto->mbridge, bundle) != 0;
2389 }
2390
2391 static void
2392 forward_bpdu_changed(struct ofproto *ofproto_)
2393 {
2394     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2395     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2396 }
2397
2398 static void
2399 set_mac_table_config(struct ofproto *ofproto_, unsigned int idle_time,
2400                      size_t max_entries)
2401 {
2402     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2403     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
2404     mac_learning_set_idle_time(ofproto->ml, idle_time);
2405     mac_learning_set_max_entries(ofproto->ml, max_entries);
2406     ovs_rwlock_unlock(&ofproto->ml->rwlock);
2407 }
2408 \f
2409 /* Ports. */
2410
2411 static struct ofport_dpif *
2412 get_ofp_port(const struct ofproto_dpif *ofproto, ofp_port_t ofp_port)
2413 {
2414     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
2415     return ofport ? ofport_dpif_cast(ofport) : NULL;
2416 }
2417
2418 static void
2419 ofproto_port_from_dpif_port(struct ofproto_dpif *ofproto,
2420                             struct ofproto_port *ofproto_port,
2421                             struct dpif_port *dpif_port)
2422 {
2423     ofproto_port->name = dpif_port->name;
2424     ofproto_port->type = dpif_port->type;
2425     ofproto_port->ofp_port = odp_port_to_ofp_port(ofproto, dpif_port->port_no);
2426 }
2427
2428 static void
2429 ofport_update_peer(struct ofport_dpif *ofport)
2430 {
2431     const struct ofproto_dpif *ofproto;
2432     struct dpif_backer *backer;
2433     char *peer_name;
2434
2435     if (!netdev_vport_is_patch(ofport->up.netdev)) {
2436         return;
2437     }
2438
2439     backer = ofproto_dpif_cast(ofport->up.ofproto)->backer;
2440     backer->need_revalidate = REV_RECONFIGURE;
2441
2442     if (ofport->peer) {
2443         ofport->peer->peer = NULL;
2444         ofport->peer = NULL;
2445     }
2446
2447     peer_name = netdev_vport_patch_peer(ofport->up.netdev);
2448     if (!peer_name) {
2449         return;
2450     }
2451
2452     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2453         struct ofport *peer_ofport;
2454         struct ofport_dpif *peer;
2455         char *peer_peer;
2456
2457         if (ofproto->backer != backer) {
2458             continue;
2459         }
2460
2461         peer_ofport = shash_find_data(&ofproto->up.port_by_name, peer_name);
2462         if (!peer_ofport) {
2463             continue;
2464         }
2465
2466         peer = ofport_dpif_cast(peer_ofport);
2467         peer_peer = netdev_vport_patch_peer(peer->up.netdev);
2468         if (peer_peer && !strcmp(netdev_get_name(ofport->up.netdev),
2469                                  peer_peer)) {
2470             ofport->peer = peer;
2471             ofport->peer->peer = ofport;
2472         }
2473         free(peer_peer);
2474
2475         break;
2476     }
2477     free(peer_name);
2478 }
2479
2480 static void
2481 port_run(struct ofport_dpif *ofport)
2482 {
2483     long long int carrier_seq = netdev_get_carrier_resets(ofport->up.netdev);
2484     bool carrier_changed = carrier_seq != ofport->carrier_seq;
2485     bool enable = netdev_get_carrier(ofport->up.netdev);
2486     bool cfm_enable = false;
2487     bool bfd_enable = false;
2488
2489     ofport->carrier_seq = carrier_seq;
2490
2491     if (ofport->cfm) {
2492         int cfm_opup = cfm_get_opup(ofport->cfm);
2493
2494         cfm_enable = !cfm_get_fault(ofport->cfm);
2495
2496         if (cfm_opup >= 0) {
2497             cfm_enable = cfm_enable && cfm_opup;
2498         }
2499     }
2500
2501     if (ofport->bfd) {
2502         bfd_enable = bfd_forwarding(ofport->bfd);
2503     }
2504
2505     if (ofport->bfd || ofport->cfm) {
2506         enable = enable && (cfm_enable || bfd_enable);
2507     }
2508
2509     if (ofport->bundle) {
2510         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
2511         if (carrier_changed) {
2512             lacp_slave_carrier_changed(ofport->bundle->lacp, ofport);
2513         }
2514     }
2515
2516     if (ofport->may_enable != enable) {
2517         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2518         ofproto->backer->need_revalidate = REV_PORT_TOGGLED;
2519     }
2520
2521     ofport->may_enable = enable;
2522 }
2523
2524 static int
2525 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
2526                    struct ofproto_port *ofproto_port)
2527 {
2528     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2529     struct dpif_port dpif_port;
2530     int error;
2531
2532     if (sset_contains(&ofproto->ghost_ports, devname)) {
2533         const char *type = netdev_get_type_from_name(devname);
2534
2535         /* We may be called before ofproto->up.port_by_name is populated with
2536          * the appropriate ofport.  For this reason, we must get the name and
2537          * type from the netdev layer directly. */
2538         if (type) {
2539             const struct ofport *ofport;
2540
2541             ofport = shash_find_data(&ofproto->up.port_by_name, devname);
2542             ofproto_port->ofp_port = ofport ? ofport->ofp_port : OFPP_NONE;
2543             ofproto_port->name = xstrdup(devname);
2544             ofproto_port->type = xstrdup(type);
2545             return 0;
2546         }
2547         return ENODEV;
2548     }
2549
2550     if (!sset_contains(&ofproto->ports, devname)) {
2551         return ENODEV;
2552     }
2553     error = dpif_port_query_by_name(ofproto->backer->dpif,
2554                                     devname, &dpif_port);
2555     if (!error) {
2556         ofproto_port_from_dpif_port(ofproto, ofproto_port, &dpif_port);
2557     }
2558     return error;
2559 }
2560
2561 static int
2562 port_add(struct ofproto *ofproto_, struct netdev *netdev)
2563 {
2564     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2565     const char *devname = netdev_get_name(netdev);
2566     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
2567     const char *dp_port_name;
2568
2569     if (netdev_vport_is_patch(netdev)) {
2570         sset_add(&ofproto->ghost_ports, netdev_get_name(netdev));
2571         return 0;
2572     }
2573
2574     dp_port_name = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
2575     if (!dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
2576         odp_port_t port_no = ODPP_NONE;
2577         int error;
2578
2579         error = dpif_port_add(ofproto->backer->dpif, netdev, &port_no);
2580         if (error) {
2581             return error;
2582         }
2583         if (netdev_get_tunnel_config(netdev)) {
2584             simap_put(&ofproto->backer->tnl_backers,
2585                       dp_port_name, odp_to_u32(port_no));
2586         }
2587     }
2588
2589     if (netdev_get_tunnel_config(netdev)) {
2590         sset_add(&ofproto->ghost_ports, devname);
2591     } else {
2592         sset_add(&ofproto->ports, devname);
2593     }
2594     return 0;
2595 }
2596
2597 static int
2598 port_del(struct ofproto *ofproto_, ofp_port_t ofp_port)
2599 {
2600     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2601     struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
2602     int error = 0;
2603
2604     if (!ofport) {
2605         return 0;
2606     }
2607
2608     sset_find_and_delete(&ofproto->ghost_ports,
2609                          netdev_get_name(ofport->up.netdev));
2610     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2611     if (!ofport->is_tunnel && !netdev_vport_is_patch(ofport->up.netdev)) {
2612         error = dpif_port_del(ofproto->backer->dpif, ofport->odp_port);
2613         if (!error) {
2614             /* The caller is going to close ofport->up.netdev.  If this is a
2615              * bonded port, then the bond is using that netdev, so remove it
2616              * from the bond.  The client will need to reconfigure everything
2617              * after deleting ports, so then the slave will get re-added. */
2618             bundle_remove(&ofport->up);
2619         }
2620     }
2621     return error;
2622 }
2623
2624 static int
2625 port_get_stats(const struct ofport *ofport_, struct netdev_stats *stats)
2626 {
2627     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2628     int error;
2629
2630     error = netdev_get_stats(ofport->up.netdev, stats);
2631
2632     if (!error && ofport_->ofp_port == OFPP_LOCAL) {
2633         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2634
2635         ovs_mutex_lock(&ofproto->stats_mutex);
2636         /* ofproto->stats.tx_packets represents packets that we created
2637          * internally and sent to some port (e.g. packets sent with
2638          * ofproto_dpif_send_packet()).  Account for them as if they had
2639          * come from OFPP_LOCAL and got forwarded. */
2640
2641         if (stats->rx_packets != UINT64_MAX) {
2642             stats->rx_packets += ofproto->stats.tx_packets;
2643         }
2644
2645         if (stats->rx_bytes != UINT64_MAX) {
2646             stats->rx_bytes += ofproto->stats.tx_bytes;
2647         }
2648
2649         /* ofproto->stats.rx_packets represents packets that were received on
2650          * some port and we processed internally and dropped (e.g. STP).
2651          * Account for them as if they had been forwarded to OFPP_LOCAL. */
2652
2653         if (stats->tx_packets != UINT64_MAX) {
2654             stats->tx_packets += ofproto->stats.rx_packets;
2655         }
2656
2657         if (stats->tx_bytes != UINT64_MAX) {
2658             stats->tx_bytes += ofproto->stats.rx_bytes;
2659         }
2660         ovs_mutex_unlock(&ofproto->stats_mutex);
2661     }
2662
2663     return error;
2664 }
2665
2666 struct port_dump_state {
2667     uint32_t bucket;
2668     uint32_t offset;
2669     bool ghost;
2670
2671     struct ofproto_port port;
2672     bool has_port;
2673 };
2674
2675 static int
2676 port_dump_start(const struct ofproto *ofproto_ OVS_UNUSED, void **statep)
2677 {
2678     *statep = xzalloc(sizeof(struct port_dump_state));
2679     return 0;
2680 }
2681
2682 static int
2683 port_dump_next(const struct ofproto *ofproto_, void *state_,
2684                struct ofproto_port *port)
2685 {
2686     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2687     struct port_dump_state *state = state_;
2688     const struct sset *sset;
2689     struct sset_node *node;
2690
2691     if (state->has_port) {
2692         ofproto_port_destroy(&state->port);
2693         state->has_port = false;
2694     }
2695     sset = state->ghost ? &ofproto->ghost_ports : &ofproto->ports;
2696     while ((node = sset_at_position(sset, &state->bucket, &state->offset))) {
2697         int error;
2698
2699         error = port_query_by_name(ofproto_, node->name, &state->port);
2700         if (!error) {
2701             *port = state->port;
2702             state->has_port = true;
2703             return 0;
2704         } else if (error != ENODEV) {
2705             return error;
2706         }
2707     }
2708
2709     if (!state->ghost) {
2710         state->ghost = true;
2711         state->bucket = 0;
2712         state->offset = 0;
2713         return port_dump_next(ofproto_, state_, port);
2714     }
2715
2716     return EOF;
2717 }
2718
2719 static int
2720 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
2721 {
2722     struct port_dump_state *state = state_;
2723
2724     if (state->has_port) {
2725         ofproto_port_destroy(&state->port);
2726     }
2727     free(state);
2728     return 0;
2729 }
2730
2731 static int
2732 port_poll(const struct ofproto *ofproto_, char **devnamep)
2733 {
2734     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2735
2736     if (ofproto->port_poll_errno) {
2737         int error = ofproto->port_poll_errno;
2738         ofproto->port_poll_errno = 0;
2739         return error;
2740     }
2741
2742     if (sset_is_empty(&ofproto->port_poll_set)) {
2743         return EAGAIN;
2744     }
2745
2746     *devnamep = sset_pop(&ofproto->port_poll_set);
2747     return 0;
2748 }
2749
2750 static void
2751 port_poll_wait(const struct ofproto *ofproto_)
2752 {
2753     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2754     dpif_port_poll_wait(ofproto->backer->dpif);
2755 }
2756
2757 static int
2758 port_is_lacp_current(const struct ofport *ofport_)
2759 {
2760     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2761     return (ofport->bundle && ofport->bundle->lacp
2762             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
2763             : -1);
2764 }
2765 \f
2766 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
2767  * then delete it entirely. */
2768 static void
2769 rule_expire(struct rule_dpif *rule)
2770     OVS_REQUIRES(ofproto_mutex)
2771 {
2772     uint16_t idle_timeout, hard_timeout;
2773     long long int now = time_msec();
2774     int reason;
2775
2776     ovs_assert(!rule->up.pending);
2777
2778     /* Has 'rule' expired? */
2779     ovs_mutex_lock(&rule->up.mutex);
2780     hard_timeout = rule->up.hard_timeout;
2781     idle_timeout = rule->up.idle_timeout;
2782     if (hard_timeout && now > rule->up.modified + hard_timeout * 1000) {
2783         reason = OFPRR_HARD_TIMEOUT;
2784     } else if (idle_timeout && now > rule->up.used + idle_timeout * 1000) {
2785         reason = OFPRR_IDLE_TIMEOUT;
2786     } else {
2787         reason = -1;
2788     }
2789     ovs_mutex_unlock(&rule->up.mutex);
2790
2791     if (reason >= 0) {
2792         COVERAGE_INC(ofproto_dpif_expired);
2793         ofproto_rule_expire(&rule->up, reason);
2794     }
2795 }
2796
2797 /* Executes, within 'ofproto', the actions in 'rule' or 'ofpacts' on 'packet'.
2798  * 'flow' must reflect the data in 'packet'. */
2799 int
2800 ofproto_dpif_execute_actions(struct ofproto_dpif *ofproto,
2801                              const struct flow *flow,
2802                              struct rule_dpif *rule,
2803                              const struct ofpact *ofpacts, size_t ofpacts_len,
2804                              struct ofpbuf *packet)
2805 {
2806     struct odputil_keybuf keybuf;
2807     struct dpif_flow_stats stats;
2808     struct xlate_out xout;
2809     struct xlate_in xin;
2810     ofp_port_t in_port;
2811     struct ofpbuf key;
2812     int error;
2813
2814     ovs_assert((rule != NULL) != (ofpacts != NULL));
2815
2816     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
2817     if (rule) {
2818         rule_dpif_credit_stats(rule, &stats);
2819     }
2820
2821     xlate_in_init(&xin, ofproto, flow, rule, stats.tcp_flags, packet);
2822     xin.ofpacts = ofpacts;
2823     xin.ofpacts_len = ofpacts_len;
2824     xin.resubmit_stats = &stats;
2825     xlate_actions(&xin, &xout);
2826
2827     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2828     in_port = flow->in_port.ofp_port;
2829     if (in_port == OFPP_NONE) {
2830         in_port = OFPP_LOCAL;
2831     }
2832     odp_flow_key_from_flow(&key, flow, ofp_port_to_odp_port(ofproto, in_port));
2833
2834     error = dpif_execute(ofproto->backer->dpif, key.data, key.size,
2835                          xout.odp_actions.data, xout.odp_actions.size, packet,
2836                          (xout.slow & SLOW_ACTION) != 0);
2837     xlate_out_uninit(&xout);
2838
2839     return error;
2840 }
2841
2842 void
2843 rule_dpif_credit_stats(struct rule_dpif *rule,
2844                        const struct dpif_flow_stats *stats)
2845 {
2846     ovs_mutex_lock(&rule->stats_mutex);
2847     rule->packet_count += stats->n_packets;
2848     rule->byte_count += stats->n_bytes;
2849     rule->up.used = MAX(rule->up.used, stats->used);
2850     ovs_mutex_unlock(&rule->stats_mutex);
2851 }
2852
2853 bool
2854 rule_dpif_is_fail_open(const struct rule_dpif *rule)
2855 {
2856     return is_fail_open_rule(&rule->up);
2857 }
2858
2859 bool
2860 rule_dpif_is_table_miss(const struct rule_dpif *rule)
2861 {
2862     return rule_is_table_miss(&rule->up);
2863 }
2864
2865 ovs_be64
2866 rule_dpif_get_flow_cookie(const struct rule_dpif *rule)
2867     OVS_REQUIRES(rule->up.mutex)
2868 {
2869     return rule->up.flow_cookie;
2870 }
2871
2872 void
2873 rule_dpif_reduce_timeouts(struct rule_dpif *rule, uint16_t idle_timeout,
2874                      uint16_t hard_timeout)
2875 {
2876     ofproto_rule_reduce_timeouts(&rule->up, idle_timeout, hard_timeout);
2877 }
2878
2879 /* Returns 'rule''s actions.  The caller owns a reference on the returned
2880  * actions and must eventually release it (with rule_actions_unref()) to avoid
2881  * a memory leak. */
2882 struct rule_actions *
2883 rule_dpif_get_actions(const struct rule_dpif *rule)
2884 {
2885     return rule_get_actions(&rule->up);
2886 }
2887
2888 /* Lookup 'flow' in 'ofproto''s classifier.  If 'wc' is non-null, sets
2889  * the fields that were relevant as part of the lookup. */
2890 void
2891 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
2892                  struct flow_wildcards *wc, struct rule_dpif **rule)
2893 {
2894     struct ofport_dpif *port;
2895
2896     if (rule_dpif_lookup_in_table(ofproto, flow, wc, 0, rule)) {
2897         return;
2898     }
2899     port = get_ofp_port(ofproto, flow->in_port.ofp_port);
2900     if (!port) {
2901         VLOG_WARN_RL(&rl, "packet-in on unknown OpenFlow port %"PRIu16,
2902                      flow->in_port.ofp_port);
2903     }
2904
2905     choose_miss_rule(port ? port->up.pp.config : 0, ofproto->miss_rule,
2906                      ofproto->no_packet_in_rule, rule);
2907 }
2908
2909 bool
2910 rule_dpif_lookup_in_table(struct ofproto_dpif *ofproto,
2911                           const struct flow *flow, struct flow_wildcards *wc,
2912                           uint8_t table_id, struct rule_dpif **rule)
2913 {
2914     const struct cls_rule *cls_rule;
2915     struct classifier *cls;
2916     bool frag;
2917
2918     *rule = NULL;
2919     if (table_id >= N_TABLES) {
2920         return false;
2921     }
2922
2923     if (wc) {
2924         memset(&wc->masks.dl_type, 0xff, sizeof wc->masks.dl_type);
2925         if (is_ip_any(flow)) {
2926             wc->masks.nw_frag |= FLOW_NW_FRAG_MASK;
2927         }
2928     }
2929
2930     cls = &ofproto->up.tables[table_id].cls;
2931     fat_rwlock_rdlock(&cls->rwlock);
2932     frag = (flow->nw_frag & FLOW_NW_FRAG_ANY) != 0;
2933     if (frag && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
2934         /* We must pretend that transport ports are unavailable. */
2935         struct flow ofpc_normal_flow = *flow;
2936         ofpc_normal_flow.tp_src = htons(0);
2937         ofpc_normal_flow.tp_dst = htons(0);
2938         cls_rule = classifier_lookup(cls, &ofpc_normal_flow, wc);
2939     } else if (frag && ofproto->up.frag_handling == OFPC_FRAG_DROP) {
2940         cls_rule = &ofproto->drop_frags_rule->up.cr;
2941         /* Frag mask in wc already set above. */
2942     } else {
2943         cls_rule = classifier_lookup(cls, flow, wc);
2944     }
2945
2946     *rule = rule_dpif_cast(rule_from_cls_rule(cls_rule));
2947     rule_dpif_ref(*rule);
2948     fat_rwlock_unlock(&cls->rwlock);
2949
2950     return *rule != NULL;
2951 }
2952
2953 /* Given a port configuration (specified as zero if there's no port), chooses
2954  * which of 'miss_rule' and 'no_packet_in_rule' should be used in case of a
2955  * flow table miss. */
2956 void
2957 choose_miss_rule(enum ofputil_port_config config, struct rule_dpif *miss_rule,
2958                  struct rule_dpif *no_packet_in_rule, struct rule_dpif **rule)
2959 {
2960     *rule = config & OFPUTIL_PC_NO_PACKET_IN ? no_packet_in_rule : miss_rule;
2961     rule_dpif_ref(*rule);
2962 }
2963
2964 void
2965 rule_dpif_ref(struct rule_dpif *rule)
2966 {
2967     if (rule) {
2968         ofproto_rule_ref(&rule->up);
2969     }
2970 }
2971
2972 void
2973 rule_dpif_unref(struct rule_dpif *rule)
2974 {
2975     if (rule) {
2976         ofproto_rule_unref(&rule->up);
2977     }
2978 }
2979
2980 static void
2981 complete_operation(struct rule_dpif *rule)
2982     OVS_REQUIRES(ofproto_mutex)
2983 {
2984     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2985
2986     ofproto->backer->need_revalidate = REV_FLOW_TABLE;
2987     ofoperation_complete(rule->up.pending, 0);
2988 }
2989
2990 static struct rule_dpif *rule_dpif_cast(const struct rule *rule)
2991 {
2992     return rule ? CONTAINER_OF(rule, struct rule_dpif, up) : NULL;
2993 }
2994
2995 static struct rule *
2996 rule_alloc(void)
2997 {
2998     struct rule_dpif *rule = xmalloc(sizeof *rule);
2999     return &rule->up;
3000 }
3001
3002 static void
3003 rule_dealloc(struct rule *rule_)
3004 {
3005     struct rule_dpif *rule = rule_dpif_cast(rule_);
3006     free(rule);
3007 }
3008
3009 static enum ofperr
3010 rule_construct(struct rule *rule_)
3011 {
3012     struct rule_dpif *rule = rule_dpif_cast(rule_);
3013     ovs_mutex_init(&rule->stats_mutex);
3014     ovs_mutex_lock(&rule->stats_mutex);
3015     rule->packet_count = 0;
3016     rule->byte_count = 0;
3017     ovs_mutex_unlock(&rule->stats_mutex);
3018     return 0;
3019 }
3020
3021 static void
3022 rule_insert(struct rule *rule_)
3023     OVS_REQUIRES(ofproto_mutex)
3024 {
3025     struct rule_dpif *rule = rule_dpif_cast(rule_);
3026     complete_operation(rule);
3027 }
3028
3029 static void
3030 rule_delete(struct rule *rule_)
3031     OVS_REQUIRES(ofproto_mutex)
3032 {
3033     struct rule_dpif *rule = rule_dpif_cast(rule_);
3034     complete_operation(rule);
3035 }
3036
3037 static void
3038 rule_destruct(struct rule *rule_)
3039 {
3040     struct rule_dpif *rule = rule_dpif_cast(rule_);
3041     ovs_mutex_destroy(&rule->stats_mutex);
3042 }
3043
3044 static void
3045 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
3046 {
3047     struct rule_dpif *rule = rule_dpif_cast(rule_);
3048
3049     ovs_mutex_lock(&rule->stats_mutex);
3050     *packets = rule->packet_count;
3051     *bytes = rule->byte_count;
3052     ovs_mutex_unlock(&rule->stats_mutex);
3053 }
3054
3055 static void
3056 rule_dpif_execute(struct rule_dpif *rule, const struct flow *flow,
3057                   struct ofpbuf *packet)
3058 {
3059     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3060
3061     ofproto_dpif_execute_actions(ofproto, flow, rule, NULL, 0, packet);
3062 }
3063
3064 static enum ofperr
3065 rule_execute(struct rule *rule, const struct flow *flow,
3066              struct ofpbuf *packet)
3067 {
3068     rule_dpif_execute(rule_dpif_cast(rule), flow, packet);
3069     ofpbuf_delete(packet);
3070     return 0;
3071 }
3072
3073 static void
3074 rule_modify_actions(struct rule *rule_, bool reset_counters)
3075     OVS_REQUIRES(ofproto_mutex)
3076 {
3077     struct rule_dpif *rule = rule_dpif_cast(rule_);
3078
3079     if (reset_counters) {
3080         ovs_mutex_lock(&rule->stats_mutex);
3081         rule->packet_count = 0;
3082         rule->byte_count = 0;
3083         ovs_mutex_unlock(&rule->stats_mutex);
3084     }
3085
3086     complete_operation(rule);
3087 }
3088
3089 static struct group_dpif *group_dpif_cast(const struct ofgroup *group)
3090 {
3091     return group ? CONTAINER_OF(group, struct group_dpif, up) : NULL;
3092 }
3093
3094 static struct ofgroup *
3095 group_alloc(void)
3096 {
3097     struct group_dpif *group = xzalloc(sizeof *group);
3098     return &group->up;
3099 }
3100
3101 static void
3102 group_dealloc(struct ofgroup *group_)
3103 {
3104     struct group_dpif *group = group_dpif_cast(group_);
3105     free(group);
3106 }
3107
3108 static void
3109 group_construct_stats(struct group_dpif *group)
3110     OVS_REQUIRES(group->stats_mutex)
3111 {
3112     group->packet_count = 0;
3113     group->byte_count = 0;
3114     if (!group->bucket_stats) {
3115         group->bucket_stats = xcalloc(group->up.n_buckets,
3116                                       sizeof *group->bucket_stats);
3117     } else {
3118         memset(group->bucket_stats, 0, group->up.n_buckets *
3119                sizeof *group->bucket_stats);
3120     }
3121 }
3122
3123 static enum ofperr
3124 group_construct(struct ofgroup *group_)
3125 {
3126     struct group_dpif *group = group_dpif_cast(group_);
3127     ovs_mutex_init(&group->stats_mutex);
3128     ovs_mutex_lock(&group->stats_mutex);
3129     group_construct_stats(group);
3130     ovs_mutex_unlock(&group->stats_mutex);
3131     return 0;
3132 }
3133
3134 static void
3135 group_destruct__(struct group_dpif *group)
3136     OVS_REQUIRES(group->stats_mutex)
3137 {
3138     free(group->bucket_stats);
3139     group->bucket_stats = NULL;
3140 }
3141
3142 static void
3143 group_destruct(struct ofgroup *group_)
3144 {
3145     struct group_dpif *group = group_dpif_cast(group_);
3146     ovs_mutex_lock(&group->stats_mutex);
3147     group_destruct__(group);
3148     ovs_mutex_unlock(&group->stats_mutex);
3149     ovs_mutex_destroy(&group->stats_mutex);
3150 }
3151
3152 static enum ofperr
3153 group_modify(struct ofgroup *group_, struct ofgroup *victim_)
3154 {
3155     struct group_dpif *group = group_dpif_cast(group_);
3156     struct group_dpif *victim = group_dpif_cast(victim_);
3157
3158     ovs_mutex_lock(&group->stats_mutex);
3159     if (victim->up.n_buckets < group->up.n_buckets) {
3160         group_destruct__(group);
3161     }
3162     group_construct_stats(group);
3163     ovs_mutex_unlock(&group->stats_mutex);
3164
3165     return 0;
3166 }
3167
3168 static enum ofperr
3169 group_get_stats(const struct ofgroup *group_, struct ofputil_group_stats *ogs)
3170 {
3171     struct group_dpif *group = group_dpif_cast(group_);
3172
3173     ovs_mutex_lock(&group->stats_mutex);
3174     ogs->packet_count = group->packet_count;
3175     ogs->byte_count = group->byte_count;
3176     memcpy(ogs->bucket_stats, group->bucket_stats,
3177            group->up.n_buckets * sizeof *group->bucket_stats);
3178     ovs_mutex_unlock(&group->stats_mutex);
3179
3180     return 0;
3181 }
3182
3183 bool
3184 group_dpif_lookup(struct ofproto_dpif *ofproto, uint32_t group_id,
3185                   struct group_dpif **group)
3186     OVS_TRY_RDLOCK(true, (*group)->up.rwlock)
3187 {
3188     struct ofgroup *ofgroup;
3189     bool found;
3190
3191     *group = NULL;
3192     found = ofproto_group_lookup(&ofproto->up, group_id, &ofgroup);
3193     *group = found ?  group_dpif_cast(ofgroup) : NULL;
3194
3195     return found;
3196 }
3197
3198 void
3199 group_dpif_release(struct group_dpif *group)
3200     OVS_RELEASES(group->up.rwlock)
3201 {
3202     ofproto_group_release(&group->up);
3203 }
3204
3205 void
3206 group_dpif_get_buckets(const struct group_dpif *group,
3207                        const struct list **buckets)
3208 {
3209     *buckets = &group->up.buckets;
3210 }
3211
3212 enum ofp11_group_type
3213 group_dpif_get_type(const struct group_dpif *group)
3214 {
3215     return group->up.type;
3216 }
3217 \f
3218 /* Sends 'packet' out 'ofport'.
3219  * May modify 'packet'.
3220  * Returns 0 if successful, otherwise a positive errno value. */
3221 int
3222 ofproto_dpif_send_packet(const struct ofport_dpif *ofport, struct ofpbuf *packet)
3223 {
3224     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3225     int error;
3226
3227     error = xlate_send_packet(ofport, packet);
3228
3229     ovs_mutex_lock(&ofproto->stats_mutex);
3230     ofproto->stats.tx_packets++;
3231     ofproto->stats.tx_bytes += packet->size;
3232     ovs_mutex_unlock(&ofproto->stats_mutex);
3233     return error;
3234 }
3235 \f
3236 static bool
3237 set_frag_handling(struct ofproto *ofproto_,
3238                   enum ofp_config_flags frag_handling)
3239 {
3240     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3241     if (frag_handling != OFPC_FRAG_REASM) {
3242         ofproto->backer->need_revalidate = REV_RECONFIGURE;
3243         return true;
3244     } else {
3245         return false;
3246     }
3247 }
3248
3249 static enum ofperr
3250 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
3251            const struct flow *flow,
3252            const struct ofpact *ofpacts, size_t ofpacts_len)
3253 {
3254     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3255
3256     ofproto_dpif_execute_actions(ofproto, flow, NULL, ofpacts,
3257                                  ofpacts_len, packet);
3258     return 0;
3259 }
3260 \f
3261 /* NetFlow. */
3262
3263 static int
3264 set_netflow(struct ofproto *ofproto_,
3265             const struct netflow_options *netflow_options)
3266 {
3267     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3268
3269     if (netflow_options) {
3270         if (!ofproto->netflow) {
3271             ofproto->netflow = netflow_create();
3272             ofproto->backer->need_revalidate = REV_RECONFIGURE;
3273         }
3274         return netflow_set_options(ofproto->netflow, netflow_options);
3275     } else if (ofproto->netflow) {
3276         ofproto->backer->need_revalidate = REV_RECONFIGURE;
3277         netflow_unref(ofproto->netflow);
3278         ofproto->netflow = NULL;
3279     }
3280
3281     return 0;
3282 }
3283
3284 static void
3285 get_netflow_ids(const struct ofproto *ofproto_,
3286                 uint8_t *engine_type, uint8_t *engine_id)
3287 {
3288     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3289
3290     dpif_get_netflow_ids(ofproto->backer->dpif, engine_type, engine_id);
3291 }
3292 \f
3293 static struct ofproto_dpif *
3294 ofproto_dpif_lookup(const char *name)
3295 {
3296     struct ofproto_dpif *ofproto;
3297
3298     HMAP_FOR_EACH_WITH_HASH (ofproto, all_ofproto_dpifs_node,
3299                              hash_string(name, 0), &all_ofproto_dpifs) {
3300         if (!strcmp(ofproto->up.name, name)) {
3301             return ofproto;
3302         }
3303     }
3304     return NULL;
3305 }
3306
3307 static void
3308 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn, int argc,
3309                           const char *argv[], void *aux OVS_UNUSED)
3310 {
3311     struct ofproto_dpif *ofproto;
3312
3313     if (argc > 1) {
3314         ofproto = ofproto_dpif_lookup(argv[1]);
3315         if (!ofproto) {
3316             unixctl_command_reply_error(conn, "no such bridge");
3317             return;
3318         }
3319         ovs_rwlock_wrlock(&ofproto->ml->rwlock);
3320         mac_learning_flush(ofproto->ml);
3321         ovs_rwlock_unlock(&ofproto->ml->rwlock);
3322     } else {
3323         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
3324             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
3325             mac_learning_flush(ofproto->ml);
3326             ovs_rwlock_unlock(&ofproto->ml->rwlock);
3327         }
3328     }
3329
3330     unixctl_command_reply(conn, "table successfully flushed");
3331 }
3332
3333 static struct ofport_dpif *
3334 ofbundle_get_a_port(const struct ofbundle *bundle)
3335 {
3336     return CONTAINER_OF(list_front(&bundle->ports), struct ofport_dpif,
3337                         bundle_node);
3338 }
3339
3340 static void
3341 ofproto_unixctl_fdb_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
3342                          const char *argv[], void *aux OVS_UNUSED)
3343 {
3344     struct ds ds = DS_EMPTY_INITIALIZER;
3345     const struct ofproto_dpif *ofproto;
3346     const struct mac_entry *e;
3347
3348     ofproto = ofproto_dpif_lookup(argv[1]);
3349     if (!ofproto) {
3350         unixctl_command_reply_error(conn, "no such bridge");
3351         return;
3352     }
3353
3354     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
3355     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
3356     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
3357         struct ofbundle *bundle = e->port.p;
3358         char name[OFP_MAX_PORT_NAME_LEN];
3359
3360         ofputil_port_to_string(ofbundle_get_a_port(bundle)->up.ofp_port,
3361                                name, sizeof name);
3362         ds_put_format(&ds, "%5s  %4d  "ETH_ADDR_FMT"  %3d\n",
3363                       name, e->vlan, ETH_ADDR_ARGS(e->mac),
3364                       mac_entry_age(ofproto->ml, e));
3365     }
3366     ovs_rwlock_unlock(&ofproto->ml->rwlock);
3367     unixctl_command_reply(conn, ds_cstr(&ds));
3368     ds_destroy(&ds);
3369 }
3370
3371 struct trace_ctx {
3372     struct xlate_out xout;
3373     struct xlate_in xin;
3374     struct flow flow;
3375     struct ds *result;
3376 };
3377
3378 static void
3379 trace_format_rule(struct ds *result, int level, const struct rule_dpif *rule)
3380 {
3381     struct rule_actions *actions;
3382     ovs_be64 cookie;
3383
3384     ds_put_char_multiple(result, '\t', level);
3385     if (!rule) {
3386         ds_put_cstr(result, "No match\n");
3387         return;
3388     }
3389
3390     ovs_mutex_lock(&rule->up.mutex);
3391     cookie = rule->up.flow_cookie;
3392     ovs_mutex_unlock(&rule->up.mutex);
3393
3394     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
3395                   rule ? rule->up.table_id : 0, ntohll(cookie));
3396     cls_rule_format(&rule->up.cr, result);
3397     ds_put_char(result, '\n');
3398
3399     actions = rule_dpif_get_actions(rule);
3400
3401     ds_put_char_multiple(result, '\t', level);
3402     ds_put_cstr(result, "OpenFlow actions=");
3403     ofpacts_format(actions->ofpacts, actions->ofpacts_len, result);
3404     ds_put_char(result, '\n');
3405
3406     rule_actions_unref(actions);
3407 }
3408
3409 static void
3410 trace_format_flow(struct ds *result, int level, const char *title,
3411                   struct trace_ctx *trace)
3412 {
3413     ds_put_char_multiple(result, '\t', level);
3414     ds_put_format(result, "%s: ", title);
3415     if (flow_equal(&trace->xin.flow, &trace->flow)) {
3416         ds_put_cstr(result, "unchanged");
3417     } else {
3418         flow_format(result, &trace->xin.flow);
3419         trace->flow = trace->xin.flow;
3420     }
3421     ds_put_char(result, '\n');
3422 }
3423
3424 static void
3425 trace_format_regs(struct ds *result, int level, const char *title,
3426                   struct trace_ctx *trace)
3427 {
3428     size_t i;
3429
3430     ds_put_char_multiple(result, '\t', level);
3431     ds_put_format(result, "%s:", title);
3432     for (i = 0; i < FLOW_N_REGS; i++) {
3433         ds_put_format(result, " reg%"PRIuSIZE"=0x%"PRIx32, i, trace->flow.regs[i]);
3434     }
3435     ds_put_char(result, '\n');
3436 }
3437
3438 static void
3439 trace_format_odp(struct ds *result, int level, const char *title,
3440                  struct trace_ctx *trace)
3441 {
3442     struct ofpbuf *odp_actions = &trace->xout.odp_actions;
3443
3444     ds_put_char_multiple(result, '\t', level);
3445     ds_put_format(result, "%s: ", title);
3446     format_odp_actions(result, odp_actions->data, odp_actions->size);
3447     ds_put_char(result, '\n');
3448 }
3449
3450 static void
3451 trace_resubmit(struct xlate_in *xin, struct rule_dpif *rule, int recurse)
3452 {
3453     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
3454     struct ds *result = trace->result;
3455
3456     ds_put_char(result, '\n');
3457     trace_format_flow(result, recurse + 1, "Resubmitted flow", trace);
3458     trace_format_regs(result, recurse + 1, "Resubmitted regs", trace);
3459     trace_format_odp(result,  recurse + 1, "Resubmitted  odp", trace);
3460     trace_format_rule(result, recurse + 1, rule);
3461 }
3462
3463 static void
3464 trace_report(struct xlate_in *xin, const char *s, int recurse)
3465 {
3466     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
3467     struct ds *result = trace->result;
3468
3469     ds_put_char_multiple(result, '\t', recurse);
3470     ds_put_cstr(result, s);
3471     ds_put_char(result, '\n');
3472 }
3473
3474 /* Parses the 'argc' elements of 'argv', ignoring argv[0].  The following
3475  * forms are supported:
3476  *
3477  *     - [dpname] odp_flow [-generate | packet]
3478  *     - bridge br_flow [-generate | packet]
3479  *
3480  * On success, initializes '*ofprotop' and 'flow' and returns NULL.  On failure
3481  * returns a nonnull malloced error message. */
3482 static char * WARN_UNUSED_RESULT
3483 parse_flow_and_packet(int argc, const char *argv[],
3484                       struct ofproto_dpif **ofprotop, struct flow *flow,
3485                       struct ofpbuf **packetp)
3486 {
3487     const struct dpif_backer *backer = NULL;
3488     const char *error = NULL;
3489     char *m_err = NULL;
3490     struct simap port_names = SIMAP_INITIALIZER(&port_names);
3491     struct ofpbuf *packet;
3492     struct ofpbuf odp_key;
3493     struct ofpbuf odp_mask;
3494
3495     ofpbuf_init(&odp_key, 0);
3496     ofpbuf_init(&odp_mask, 0);
3497
3498     /* Handle "-generate" or a hex string as the last argument. */
3499     if (!strcmp(argv[argc - 1], "-generate")) {
3500         packet = ofpbuf_new(0);
3501         argc--;
3502     } else {
3503         error = eth_from_hex(argv[argc - 1], &packet);
3504         if (!error) {
3505             argc--;
3506         } else if (argc == 4) {
3507             /* The 3-argument form must end in "-generate' or a hex string. */
3508             goto exit;
3509         }
3510         error = NULL;
3511     }
3512
3513     /* odp_flow can have its in_port specified as a name instead of port no.
3514      * We do not yet know whether a given flow is a odp_flow or a br_flow.
3515      * But, to know whether a flow is odp_flow through odp_flow_from_string(),
3516      * we need to create a simap of name to port no. */
3517     if (argc == 3) {
3518         const char *dp_type;
3519         if (!strncmp(argv[1], "ovs-", 4)) {
3520             dp_type = argv[1] + 4;
3521         } else {
3522             dp_type = argv[1];
3523         }
3524         backer = shash_find_data(&all_dpif_backers, dp_type);
3525     } else if (argc == 2) {
3526         struct shash_node *node;
3527         if (shash_count(&all_dpif_backers) == 1) {
3528             node = shash_first(&all_dpif_backers);
3529             backer = node->data;
3530         }
3531     } else {
3532         error = "Syntax error";
3533         goto exit;
3534     }
3535     if (backer && backer->dpif) {
3536         struct dpif_port dpif_port;
3537         struct dpif_port_dump port_dump;
3538         DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, backer->dpif) {
3539             simap_put(&port_names, dpif_port.name,
3540                       odp_to_u32(dpif_port.port_no));
3541         }
3542     }
3543
3544     /* Parse the flow and determine whether a datapath or
3545      * bridge is specified. If function odp_flow_key_from_string()
3546      * returns 0, the flow is a odp_flow. If function
3547      * parse_ofp_exact_flow() returns NULL, the flow is a br_flow. */
3548     if (!odp_flow_from_string(argv[argc - 1], &port_names,
3549                               &odp_key, &odp_mask)) {
3550         if (!backer) {
3551             error = "Cannot find the datapath";
3552             goto exit;
3553         }
3554
3555         if (xlate_receive(backer, NULL, odp_key.data, odp_key.size, flow,
3556                           NULL, ofprotop, NULL, NULL, NULL, NULL)) {
3557             error = "Invalid datapath flow";
3558             goto exit;
3559         }
3560     } else {
3561         char *err = parse_ofp_exact_flow(flow, NULL, argv[argc - 1], NULL);
3562
3563         if (err) {
3564             m_err = xasprintf("Bad flow syntax: %s", err);
3565             free(err);
3566             goto exit;
3567         } else {
3568             if (argc != 3) {
3569                 error = "Must specify bridge name";
3570                 goto exit;
3571             }
3572
3573             *ofprotop = ofproto_dpif_lookup(argv[1]);
3574             if (!*ofprotop) {
3575                 error = "Unknown bridge name";
3576                 goto exit;
3577             }
3578         }
3579     }
3580
3581     /* Generate a packet, if requested. */
3582     if (packet) {
3583         if (!packet->size) {
3584             flow_compose(packet, flow);
3585         } else {
3586             union flow_in_port in_port = flow->in_port;
3587
3588             /* Use the metadata from the flow and the packet argument
3589              * to reconstruct the flow. */
3590             flow_extract(packet, flow->skb_priority, flow->pkt_mark, NULL,
3591                          &in_port, flow);
3592         }
3593     }
3594
3595 exit:
3596     if (error && !m_err) {
3597         m_err = xstrdup(error);
3598     }
3599     if (m_err) {
3600         ofpbuf_delete(packet);
3601         packet = NULL;
3602     }
3603     *packetp = packet;
3604     ofpbuf_uninit(&odp_key);
3605     ofpbuf_uninit(&odp_mask);
3606     simap_destroy(&port_names);
3607     return m_err;
3608 }
3609
3610 static void
3611 ofproto_unixctl_trace(struct unixctl_conn *conn, int argc, const char *argv[],
3612                       void *aux OVS_UNUSED)
3613 {
3614     struct ofproto_dpif *ofproto;
3615     struct ofpbuf *packet;
3616     char *error;
3617     struct flow flow;
3618
3619     error = parse_flow_and_packet(argc, argv, &ofproto, &flow, &packet);
3620     if (!error) {
3621         struct ds result;
3622
3623         ds_init(&result);
3624         ofproto_trace(ofproto, &flow, packet, NULL, 0, &result);
3625         unixctl_command_reply(conn, ds_cstr(&result));
3626         ds_destroy(&result);
3627         ofpbuf_delete(packet);
3628     } else {
3629         unixctl_command_reply_error(conn, error);
3630         free(error);
3631     }
3632 }
3633
3634 static void
3635 ofproto_unixctl_trace_actions(struct unixctl_conn *conn, int argc,
3636                               const char *argv[], void *aux OVS_UNUSED)
3637 {
3638     enum ofputil_protocol usable_protocols;
3639     struct ofproto_dpif *ofproto;
3640     bool enforce_consistency;
3641     struct ofpbuf ofpacts;
3642     struct ofpbuf *packet;
3643     struct ds result;
3644     struct flow flow;
3645     uint16_t in_port;
3646
3647     /* Three kinds of error return values! */
3648     enum ofperr retval;
3649     char *error;
3650
3651     packet = NULL;
3652     ds_init(&result);
3653     ofpbuf_init(&ofpacts, 0);
3654
3655     /* Parse actions. */
3656     error = parse_ofpacts(argv[--argc], &ofpacts, &usable_protocols);
3657     if (error) {
3658         unixctl_command_reply_error(conn, error);
3659         free(error);
3660         goto exit;
3661     }
3662
3663     /* OpenFlow 1.1 and later suggest that the switch enforces certain forms of
3664      * consistency between the flow and the actions.  With -consistent, we
3665      * enforce consistency even for a flow supported in OpenFlow 1.0. */
3666     if (!strcmp(argv[1], "-consistent")) {
3667         enforce_consistency = true;
3668         argv++;
3669         argc--;
3670     } else {
3671         enforce_consistency = false;
3672     }
3673
3674     error = parse_flow_and_packet(argc, argv, &ofproto, &flow, &packet);
3675     if (error) {
3676         unixctl_command_reply_error(conn, error);
3677         free(error);
3678         goto exit;
3679     }
3680
3681     /* Do the same checks as handle_packet_out() in ofproto.c.
3682      *
3683      * We pass a 'table_id' of 0 to ofproto_check_ofpacts(), which isn't
3684      * strictly correct because these actions aren't in any table, but it's OK
3685      * because it 'table_id' is used only to check goto_table instructions, but
3686      * packet-outs take a list of actions and therefore it can't include
3687      * instructions.
3688      *
3689      * We skip the "meter" check here because meter is an instruction, not an
3690      * action, and thus cannot appear in ofpacts. */
3691     in_port = ofp_to_u16(flow.in_port.ofp_port);
3692     if (in_port >= ofproto->up.max_ports && in_port < ofp_to_u16(OFPP_MAX)) {
3693         unixctl_command_reply_error(conn, "invalid in_port");
3694         goto exit;
3695     }
3696     if (enforce_consistency) {
3697         retval = ofpacts_check_consistency(ofpacts.data, ofpacts.size, &flow,
3698                                            u16_to_ofp(ofproto->up.max_ports),
3699                                            0, 0, usable_protocols);
3700     } else {
3701         retval = ofpacts_check(ofpacts.data, ofpacts.size, &flow,
3702                                u16_to_ofp(ofproto->up.max_ports), 0, 0,
3703                                &usable_protocols);
3704     }
3705
3706     if (retval) {
3707         ds_clear(&result);
3708         ds_put_format(&result, "Bad actions: %s", ofperr_to_string(retval));
3709         unixctl_command_reply_error(conn, ds_cstr(&result));
3710         goto exit;
3711     }
3712
3713     ofproto_trace(ofproto, &flow, packet, ofpacts.data, ofpacts.size, &result);
3714     unixctl_command_reply(conn, ds_cstr(&result));
3715
3716 exit:
3717     ds_destroy(&result);
3718     ofpbuf_delete(packet);
3719     ofpbuf_uninit(&ofpacts);
3720 }
3721
3722 /* Implements a "trace" through 'ofproto''s flow table, appending a textual
3723  * description of the results to 'ds'.
3724  *
3725  * The trace follows a packet with the specified 'flow' through the flow
3726  * table.  'packet' may be nonnull to trace an actual packet, with consequent
3727  * side effects (if it is nonnull then its flow must be 'flow').
3728  *
3729  * If 'ofpacts' is nonnull then its 'ofpacts_len' bytes specify the actions to
3730  * trace, otherwise the actions are determined by a flow table lookup. */
3731 static void
3732 ofproto_trace(struct ofproto_dpif *ofproto, const struct flow *flow,
3733               const struct ofpbuf *packet,
3734               const struct ofpact ofpacts[], size_t ofpacts_len,
3735               struct ds *ds)
3736 {
3737     struct rule_dpif *rule;
3738     struct flow_wildcards wc;
3739
3740     ds_put_format(ds, "Bridge: %s\n", ofproto->up.name);
3741     ds_put_cstr(ds, "Flow: ");
3742     flow_format(ds, flow);
3743     ds_put_char(ds, '\n');
3744
3745     flow_wildcards_init_catchall(&wc);
3746     if (ofpacts) {
3747         rule = NULL;
3748     } else {
3749         rule_dpif_lookup(ofproto, flow, &wc, &rule);
3750
3751         trace_format_rule(ds, 0, rule);
3752         if (rule == ofproto->miss_rule) {
3753             ds_put_cstr(ds, "\nNo match, flow generates \"packet in\"s.\n");
3754         } else if (rule == ofproto->no_packet_in_rule) {
3755             ds_put_cstr(ds, "\nNo match, packets dropped because "
3756                         "OFPPC_NO_PACKET_IN is set on in_port.\n");
3757         } else if (rule == ofproto->drop_frags_rule) {
3758             ds_put_cstr(ds, "\nPackets dropped because they are IP fragments "
3759                         "and the fragment handling mode is \"drop\".\n");
3760         }
3761     }
3762
3763     if (rule || ofpacts) {
3764         uint64_t odp_actions_stub[1024 / 8];
3765         struct ofpbuf odp_actions;
3766         struct trace_ctx trace;
3767         struct match match;
3768         uint16_t tcp_flags;
3769
3770         tcp_flags = packet ? packet_get_tcp_flags(packet, flow) : 0;
3771         trace.result = ds;
3772         trace.flow = *flow;
3773         ofpbuf_use_stub(&odp_actions,
3774                         odp_actions_stub, sizeof odp_actions_stub);
3775         xlate_in_init(&trace.xin, ofproto, flow, rule, tcp_flags, packet);
3776         if (ofpacts) {
3777             trace.xin.ofpacts = ofpacts;
3778             trace.xin.ofpacts_len = ofpacts_len;
3779         }
3780         trace.xin.resubmit_hook = trace_resubmit;
3781         trace.xin.report_hook = trace_report;
3782
3783         xlate_actions(&trace.xin, &trace.xout);
3784         flow_wildcards_or(&trace.xout.wc, &trace.xout.wc, &wc);
3785
3786         ds_put_char(ds, '\n');
3787         trace_format_flow(ds, 0, "Final flow", &trace);
3788
3789         match_init(&match, flow, &trace.xout.wc);
3790         ds_put_cstr(ds, "Relevant fields: ");
3791         match_format(&match, ds, OFP_DEFAULT_PRIORITY);
3792         ds_put_char(ds, '\n');
3793
3794         ds_put_cstr(ds, "Datapath actions: ");
3795         format_odp_actions(ds, trace.xout.odp_actions.data,
3796                            trace.xout.odp_actions.size);
3797
3798         if (trace.xout.slow) {
3799             enum slow_path_reason slow;
3800
3801             ds_put_cstr(ds, "\nThis flow is handled by the userspace "
3802                         "slow path because it:");
3803
3804             slow = trace.xout.slow;
3805             while (slow) {
3806                 enum slow_path_reason bit = rightmost_1bit(slow);
3807
3808                 ds_put_format(ds, "\n\t- %s.",
3809                               slow_path_reason_to_explanation(bit));
3810
3811                 slow &= ~bit;
3812             }
3813         }
3814
3815         xlate_out_uninit(&trace.xout);
3816     }
3817
3818     rule_dpif_unref(rule);
3819 }
3820
3821 /* Store the current ofprotos in 'ofproto_shash'.  Returns a sorted list
3822  * of the 'ofproto_shash' nodes.  It is the responsibility of the caller
3823  * to destroy 'ofproto_shash' and free the returned value. */
3824 static const struct shash_node **
3825 get_ofprotos(struct shash *ofproto_shash)
3826 {
3827     const struct ofproto_dpif *ofproto;
3828
3829     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
3830         char *name = xasprintf("%s@%s", ofproto->up.type, ofproto->up.name);
3831         shash_add_nocopy(ofproto_shash, name, ofproto);
3832     }
3833
3834     return shash_sort(ofproto_shash);
3835 }
3836
3837 static void
3838 ofproto_unixctl_dpif_dump_dps(struct unixctl_conn *conn, int argc OVS_UNUSED,
3839                               const char *argv[] OVS_UNUSED,
3840                               void *aux OVS_UNUSED)
3841 {
3842     struct ds ds = DS_EMPTY_INITIALIZER;
3843     struct shash ofproto_shash;
3844     const struct shash_node **sorted_ofprotos;
3845     int i;
3846
3847     shash_init(&ofproto_shash);
3848     sorted_ofprotos = get_ofprotos(&ofproto_shash);
3849     for (i = 0; i < shash_count(&ofproto_shash); i++) {
3850         const struct shash_node *node = sorted_ofprotos[i];
3851         ds_put_format(&ds, "%s\n", node->name);
3852     }
3853
3854     shash_destroy(&ofproto_shash);
3855     free(sorted_ofprotos);
3856
3857     unixctl_command_reply(conn, ds_cstr(&ds));
3858     ds_destroy(&ds);
3859 }
3860
3861 static void
3862 dpif_show_backer(const struct dpif_backer *backer, struct ds *ds)
3863 {
3864     const struct shash_node **ofprotos;
3865     struct dpif_dp_stats dp_stats;
3866     struct shash ofproto_shash;
3867     size_t i;
3868
3869     dpif_get_dp_stats(backer->dpif, &dp_stats);
3870
3871     ds_put_format(ds, "%s: hit:%"PRIu64" missed:%"PRIu64"\n",
3872                   dpif_name(backer->dpif), dp_stats.n_hit, dp_stats.n_missed);
3873
3874     shash_init(&ofproto_shash);
3875     ofprotos = get_ofprotos(&ofproto_shash);
3876     for (i = 0; i < shash_count(&ofproto_shash); i++) {
3877         struct ofproto_dpif *ofproto = ofprotos[i]->data;
3878         const struct shash_node **ports;
3879         size_t j;
3880
3881         if (ofproto->backer != backer) {
3882             continue;
3883         }
3884
3885         ds_put_format(ds, "\t%s:\n", ofproto->up.name);
3886
3887         ports = shash_sort(&ofproto->up.port_by_name);
3888         for (j = 0; j < shash_count(&ofproto->up.port_by_name); j++) {
3889             const struct shash_node *node = ports[j];
3890             struct ofport *ofport = node->data;
3891             struct smap config;
3892             odp_port_t odp_port;
3893
3894             ds_put_format(ds, "\t\t%s %u/", netdev_get_name(ofport->netdev),
3895                           ofport->ofp_port);
3896
3897             odp_port = ofp_port_to_odp_port(ofproto, ofport->ofp_port);
3898             if (odp_port != ODPP_NONE) {
3899                 ds_put_format(ds, "%"PRIu32":", odp_port);
3900             } else {
3901                 ds_put_cstr(ds, "none:");
3902             }
3903
3904             ds_put_format(ds, " (%s", netdev_get_type(ofport->netdev));
3905
3906             smap_init(&config);
3907             if (!netdev_get_config(ofport->netdev, &config)) {
3908                 const struct smap_node **nodes;
3909                 size_t i;
3910
3911                 nodes = smap_sort(&config);
3912                 for (i = 0; i < smap_count(&config); i++) {
3913                     const struct smap_node *node = nodes[i];
3914                     ds_put_format(ds, "%c %s=%s", i ? ',' : ':',
3915                                   node->key, node->value);
3916                 }
3917                 free(nodes);
3918             }
3919             smap_destroy(&config);
3920
3921             ds_put_char(ds, ')');
3922             ds_put_char(ds, '\n');
3923         }
3924         free(ports);
3925     }
3926     shash_destroy(&ofproto_shash);
3927     free(ofprotos);
3928 }
3929
3930 static void
3931 ofproto_unixctl_dpif_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
3932                           const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
3933 {
3934     struct ds ds = DS_EMPTY_INITIALIZER;
3935     const struct shash_node **backers;
3936     int i;
3937
3938     backers = shash_sort(&all_dpif_backers);
3939     for (i = 0; i < shash_count(&all_dpif_backers); i++) {
3940         dpif_show_backer(backers[i]->data, &ds);
3941     }
3942     free(backers);
3943
3944     unixctl_command_reply(conn, ds_cstr(&ds));
3945     ds_destroy(&ds);
3946 }
3947
3948 static bool
3949 ofproto_dpif_contains_flow(const struct ofproto_dpif *ofproto,
3950                            const struct nlattr *key, size_t key_len)
3951 {
3952     enum odp_key_fitness fitness;
3953     struct ofproto_dpif *ofp;
3954     struct flow flow;
3955
3956     xlate_receive(ofproto->backer, NULL, key, key_len, &flow, &fitness, &ofp,
3957                   NULL, NULL, NULL, NULL);
3958     return ofp == ofproto;
3959 }
3960
3961 static void
3962 ofproto_unixctl_dpif_dump_flows(struct unixctl_conn *conn,
3963                                 int argc OVS_UNUSED, const char *argv[],
3964                                 void *aux OVS_UNUSED)
3965 {
3966     struct ds ds = DS_EMPTY_INITIALIZER;
3967     const struct dpif_flow_stats *stats;
3968     const struct ofproto_dpif *ofproto;
3969     struct dpif_flow_dump flow_dump;
3970     const struct nlattr *actions;
3971     const struct nlattr *mask;
3972     const struct nlattr *key;
3973     size_t actions_len;
3974     size_t mask_len;
3975     size_t key_len;
3976
3977     ofproto = ofproto_dpif_lookup(argv[1]);
3978     if (!ofproto) {
3979         unixctl_command_reply_error(conn, "no such bridge");
3980         return;
3981     }
3982
3983     ds_init(&ds);
3984     dpif_flow_dump_start(&flow_dump, ofproto->backer->dpif);
3985     while (dpif_flow_dump_next(&flow_dump, &key, &key_len, &mask, &mask_len,
3986                                &actions, &actions_len, &stats)) {
3987         if (!ofproto_dpif_contains_flow(ofproto, key, key_len)) {
3988             continue;
3989         }
3990
3991         odp_flow_format(key, key_len, mask, mask_len, NULL, &ds, false);
3992         ds_put_cstr(&ds, ", ");
3993         dpif_flow_stats_format(stats, &ds);
3994         ds_put_cstr(&ds, ", actions:");
3995         format_odp_actions(&ds, actions, actions_len);
3996         ds_put_char(&ds, '\n');
3997     }
3998
3999     if (dpif_flow_dump_done(&flow_dump)) {
4000         ds_clear(&ds);
4001         ds_put_format(&ds, "dpif/dump_flows failed: %s", ovs_strerror(errno));
4002         unixctl_command_reply_error(conn, ds_cstr(&ds));
4003     } else {
4004         unixctl_command_reply(conn, ds_cstr(&ds));
4005     }
4006     ds_destroy(&ds);
4007 }
4008
4009 static void
4010 ofproto_dpif_unixctl_init(void)
4011 {
4012     static bool registered;
4013     if (registered) {
4014         return;
4015     }
4016     registered = true;
4017
4018     unixctl_command_register(
4019         "ofproto/trace",
4020         "{[dp_name] odp_flow | bridge br_flow} [-generate|packet]",
4021         1, 3, ofproto_unixctl_trace, NULL);
4022     unixctl_command_register(
4023         "ofproto/trace-packet-out",
4024         "[-consistent] {[dp_name] odp_flow | bridge br_flow} [-generate|packet] actions",
4025         2, 6, ofproto_unixctl_trace_actions, NULL);
4026     unixctl_command_register("fdb/flush", "[bridge]", 0, 1,
4027                              ofproto_unixctl_fdb_flush, NULL);
4028     unixctl_command_register("fdb/show", "bridge", 1, 1,
4029                              ofproto_unixctl_fdb_show, NULL);
4030     unixctl_command_register("dpif/dump-dps", "", 0, 0,
4031                              ofproto_unixctl_dpif_dump_dps, NULL);
4032     unixctl_command_register("dpif/show", "", 0, 0, ofproto_unixctl_dpif_show,
4033                              NULL);
4034     unixctl_command_register("dpif/dump-flows", "bridge", 1, 1,
4035                              ofproto_unixctl_dpif_dump_flows, NULL);
4036 }
4037 \f
4038 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
4039  *
4040  * This is deprecated.  It is only for compatibility with broken device drivers
4041  * in old versions of Linux that do not properly support VLANs when VLAN
4042  * devices are not used.  When broken device drivers are no longer in
4043  * widespread use, we will delete these interfaces. */
4044
4045 static int
4046 set_realdev(struct ofport *ofport_, ofp_port_t realdev_ofp_port, int vid)
4047 {
4048     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
4049     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
4050
4051     if (realdev_ofp_port == ofport->realdev_ofp_port
4052         && vid == ofport->vlandev_vid) {
4053         return 0;
4054     }
4055
4056     ofproto->backer->need_revalidate = REV_RECONFIGURE;
4057
4058     if (ofport->realdev_ofp_port) {
4059         vsp_remove(ofport);
4060     }
4061     if (realdev_ofp_port && ofport->bundle) {
4062         /* vlandevs are enslaved to their realdevs, so they are not allowed to
4063          * themselves be part of a bundle. */
4064         bundle_set(ofport->up.ofproto, ofport->bundle, NULL);
4065     }
4066
4067     ofport->realdev_ofp_port = realdev_ofp_port;
4068     ofport->vlandev_vid = vid;
4069
4070     if (realdev_ofp_port) {
4071         vsp_add(ofport, realdev_ofp_port, vid);
4072     }
4073
4074     return 0;
4075 }
4076
4077 static uint32_t
4078 hash_realdev_vid(ofp_port_t realdev_ofp_port, int vid)
4079 {
4080     return hash_2words(ofp_to_u16(realdev_ofp_port), vid);
4081 }
4082
4083 bool
4084 ofproto_has_vlan_splinters(const struct ofproto_dpif *ofproto)
4085     OVS_EXCLUDED(ofproto->vsp_mutex)
4086 {
4087     bool ret;
4088
4089     ovs_mutex_lock(&ofproto->vsp_mutex);
4090     ret = !hmap_is_empty(&ofproto->realdev_vid_map);
4091     ovs_mutex_unlock(&ofproto->vsp_mutex);
4092     return ret;
4093 }
4094
4095 static ofp_port_t
4096 vsp_realdev_to_vlandev__(const struct ofproto_dpif *ofproto,
4097                          ofp_port_t realdev_ofp_port, ovs_be16 vlan_tci)
4098     OVS_REQUIRES(ofproto->vsp_mutex)
4099 {
4100     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
4101         int vid = vlan_tci_to_vid(vlan_tci);
4102         const struct vlan_splinter *vsp;
4103
4104         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
4105                                  hash_realdev_vid(realdev_ofp_port, vid),
4106                                  &ofproto->realdev_vid_map) {
4107             if (vsp->realdev_ofp_port == realdev_ofp_port
4108                 && vsp->vid == vid) {
4109                 return vsp->vlandev_ofp_port;
4110             }
4111         }
4112     }
4113     return realdev_ofp_port;
4114 }
4115
4116 /* Returns the OFP port number of the Linux VLAN device that corresponds to
4117  * 'vlan_tci' on the network device with port number 'realdev_ofp_port' in
4118  * 'struct ofport_dpif'.  For example, given 'realdev_ofp_port' of eth0 and
4119  * 'vlan_tci' 9, it would return the port number of eth0.9.
4120  *
4121  * Unless VLAN splinters are enabled for port 'realdev_ofp_port', this
4122  * function just returns its 'realdev_ofp_port' argument. */
4123 ofp_port_t
4124 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
4125                        ofp_port_t realdev_ofp_port, ovs_be16 vlan_tci)
4126     OVS_EXCLUDED(ofproto->vsp_mutex)
4127 {
4128     ofp_port_t ret;
4129
4130     ovs_mutex_lock(&ofproto->vsp_mutex);
4131     ret = vsp_realdev_to_vlandev__(ofproto, realdev_ofp_port, vlan_tci);
4132     ovs_mutex_unlock(&ofproto->vsp_mutex);
4133     return ret;
4134 }
4135
4136 static struct vlan_splinter *
4137 vlandev_find(const struct ofproto_dpif *ofproto, ofp_port_t vlandev_ofp_port)
4138 {
4139     struct vlan_splinter *vsp;
4140
4141     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node,
4142                              hash_ofp_port(vlandev_ofp_port),
4143                              &ofproto->vlandev_map) {
4144         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
4145             return vsp;
4146         }
4147     }
4148
4149     return NULL;
4150 }
4151
4152 /* Returns the OpenFlow port number of the "real" device underlying the Linux
4153  * VLAN device with OpenFlow port number 'vlandev_ofp_port' and stores the
4154  * VLAN VID of the Linux VLAN device in '*vid'.  For example, given
4155  * 'vlandev_ofp_port' of eth0.9, it would return the OpenFlow port number of
4156  * eth0 and store 9 in '*vid'.
4157  *
4158  * Returns 0 and does not modify '*vid' if 'vlandev_ofp_port' is not a Linux
4159  * VLAN device.  Unless VLAN splinters are enabled, this is what this function
4160  * always does.*/
4161 static ofp_port_t
4162 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
4163                        ofp_port_t vlandev_ofp_port, int *vid)
4164     OVS_REQUIRES(ofproto->vsp_mutex)
4165 {
4166     if (!hmap_is_empty(&ofproto->vlandev_map)) {
4167         const struct vlan_splinter *vsp;
4168
4169         vsp = vlandev_find(ofproto, vlandev_ofp_port);
4170         if (vsp) {
4171             if (vid) {
4172                 *vid = vsp->vid;
4173             }
4174             return vsp->realdev_ofp_port;
4175         }
4176     }
4177     return 0;
4178 }
4179
4180 /* Given 'flow', a flow representing a packet received on 'ofproto', checks
4181  * whether 'flow->in_port' represents a Linux VLAN device.  If so, changes
4182  * 'flow->in_port' to the "real" device backing the VLAN device, sets
4183  * 'flow->vlan_tci' to the VLAN VID, and returns true.  Otherwise (which is
4184  * always the case unless VLAN splinters are enabled), returns false without
4185  * making any changes. */
4186 bool
4187 vsp_adjust_flow(const struct ofproto_dpif *ofproto, struct flow *flow)
4188     OVS_EXCLUDED(ofproto->vsp_mutex)
4189 {
4190     ofp_port_t realdev;
4191     int vid;
4192
4193     ovs_mutex_lock(&ofproto->vsp_mutex);
4194     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port.ofp_port, &vid);
4195     ovs_mutex_unlock(&ofproto->vsp_mutex);
4196     if (!realdev) {
4197         return false;
4198     }
4199
4200     /* Cause the flow to be processed as if it came in on the real device with
4201      * the VLAN device's VLAN ID. */
4202     flow->in_port.ofp_port = realdev;
4203     flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
4204     return true;
4205 }
4206
4207 static void
4208 vsp_remove(struct ofport_dpif *port)
4209 {
4210     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
4211     struct vlan_splinter *vsp;
4212
4213     ovs_mutex_lock(&ofproto->vsp_mutex);
4214     vsp = vlandev_find(ofproto, port->up.ofp_port);
4215     if (vsp) {
4216         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
4217         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
4218         free(vsp);
4219
4220         port->realdev_ofp_port = 0;
4221     } else {
4222         VLOG_ERR("missing vlan device record");
4223     }
4224     ovs_mutex_unlock(&ofproto->vsp_mutex);
4225 }
4226
4227 static void
4228 vsp_add(struct ofport_dpif *port, ofp_port_t realdev_ofp_port, int vid)
4229 {
4230     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
4231
4232     ovs_mutex_lock(&ofproto->vsp_mutex);
4233     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
4234         && (vsp_realdev_to_vlandev__(ofproto, realdev_ofp_port, htons(vid))
4235             == realdev_ofp_port)) {
4236         struct vlan_splinter *vsp;
4237
4238         vsp = xmalloc(sizeof *vsp);
4239         vsp->realdev_ofp_port = realdev_ofp_port;
4240         vsp->vlandev_ofp_port = port->up.ofp_port;
4241         vsp->vid = vid;
4242
4243         port->realdev_ofp_port = realdev_ofp_port;
4244
4245         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
4246                     hash_ofp_port(port->up.ofp_port));
4247         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
4248                     hash_realdev_vid(realdev_ofp_port, vid));
4249     } else {
4250         VLOG_ERR("duplicate vlan device record");
4251     }
4252     ovs_mutex_unlock(&ofproto->vsp_mutex);
4253 }
4254
4255 static odp_port_t
4256 ofp_port_to_odp_port(const struct ofproto_dpif *ofproto, ofp_port_t ofp_port)
4257 {
4258     const struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
4259     return ofport ? ofport->odp_port : ODPP_NONE;
4260 }
4261
4262 struct ofport_dpif *
4263 odp_port_to_ofport(const struct dpif_backer *backer, odp_port_t odp_port)
4264 {
4265     struct ofport_dpif *port;
4266
4267     ovs_rwlock_rdlock(&backer->odp_to_ofport_lock);
4268     HMAP_FOR_EACH_IN_BUCKET (port, odp_port_node, hash_odp_port(odp_port),
4269                              &backer->odp_to_ofport_map) {
4270         if (port->odp_port == odp_port) {
4271             ovs_rwlock_unlock(&backer->odp_to_ofport_lock);
4272             return port;
4273         }
4274     }
4275
4276     ovs_rwlock_unlock(&backer->odp_to_ofport_lock);
4277     return NULL;
4278 }
4279
4280 static ofp_port_t
4281 odp_port_to_ofp_port(const struct ofproto_dpif *ofproto, odp_port_t odp_port)
4282 {
4283     struct ofport_dpif *port;
4284
4285     port = odp_port_to_ofport(ofproto->backer, odp_port);
4286     if (port && &ofproto->up == port->up.ofproto) {
4287         return port->up.ofp_port;
4288     } else {
4289         return OFPP_NONE;
4290     }
4291 }
4292
4293 const struct ofproto_class ofproto_dpif_class = {
4294     init,
4295     enumerate_types,
4296     enumerate_names,
4297     del,
4298     port_open_type,
4299     type_run,
4300     type_wait,
4301     alloc,
4302     construct,
4303     destruct,
4304     dealloc,
4305     run,
4306     wait,
4307     NULL,                       /* get_memory_usage. */
4308     type_get_memory_usage,
4309     flush,
4310     get_features,
4311     get_tables,
4312     port_alloc,
4313     port_construct,
4314     port_destruct,
4315     port_dealloc,
4316     port_modified,
4317     port_reconfigured,
4318     port_query_by_name,
4319     port_add,
4320     port_del,
4321     port_get_stats,
4322     port_dump_start,
4323     port_dump_next,
4324     port_dump_done,
4325     port_poll,
4326     port_poll_wait,
4327     port_is_lacp_current,
4328     NULL,                       /* rule_choose_table */
4329     rule_alloc,
4330     rule_construct,
4331     rule_insert,
4332     rule_delete,
4333     rule_destruct,
4334     rule_dealloc,
4335     rule_get_stats,
4336     rule_execute,
4337     rule_modify_actions,
4338     set_frag_handling,
4339     packet_out,
4340     set_netflow,
4341     get_netflow_ids,
4342     set_sflow,
4343     set_ipfix,
4344     set_cfm,
4345     get_cfm_status,
4346     set_bfd,
4347     get_bfd_status,
4348     set_stp,
4349     get_stp_status,
4350     set_stp_port,
4351     get_stp_port_status,
4352     get_stp_port_stats,
4353     set_queues,
4354     bundle_set,
4355     bundle_remove,
4356     mirror_set__,
4357     mirror_get_stats__,
4358     set_flood_vlans,
4359     is_mirror_output_bundle,
4360     forward_bpdu_changed,
4361     set_mac_table_config,
4362     set_realdev,
4363     NULL,                       /* meter_get_features */
4364     NULL,                       /* meter_set */
4365     NULL,                       /* meter_get */
4366     NULL,                       /* meter_del */
4367     group_alloc,                /* group_alloc */
4368     group_construct,            /* group_construct */
4369     group_destruct,             /* group_destruct */
4370     group_dealloc,              /* group_dealloc */
4371     group_modify,               /* group_modify */
4372     group_get_stats,            /* group_get_stats */
4373 };