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