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