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