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