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