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