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