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