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