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