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