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