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