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