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