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