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