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