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