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