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