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