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