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