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