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