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