Merge remote-tracking branch 'origin/master' into ovn
[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)) {
2024             error = 0;
2025             goto out;
2026         }
2027
2028         error = EINVAL;
2029     }
2030     lldp_unref(ofport->lldp);
2031     ofport->lldp = NULL;
2032 out:
2033     ofproto_dpif_monitor_port_update(ofport,
2034                                      ofport->bfd,
2035                                      ofport->cfm,
2036                                      ofport->lldp,
2037                                      ofport->up.pp.hw_addr);
2038     return error;
2039 }
2040
2041 static bool
2042 get_lldp_status(const struct ofport *ofport_,
2043                struct lldp_status *status OVS_UNUSED)
2044 {
2045     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2046
2047     return ofport->lldp ? true : false;
2048 }
2049
2050 static int
2051 set_aa(struct ofproto *ofproto OVS_UNUSED,
2052        const struct aa_settings *s)
2053 {
2054     return aa_configure(s);
2055 }
2056
2057 static int
2058 aa_mapping_set(struct ofproto *ofproto_ OVS_UNUSED, void *aux,
2059                const struct aa_mapping_settings *s)
2060 {
2061     return aa_mapping_register(aux, s);
2062 }
2063
2064 static int
2065 aa_mapping_unset(struct ofproto *ofproto OVS_UNUSED, void *aux)
2066 {
2067     return aa_mapping_unregister(aux);
2068 }
2069
2070 static int
2071 aa_vlan_get_queued(struct ofproto *ofproto OVS_UNUSED, struct ovs_list *list)
2072 {
2073     return aa_get_vlan_queued(list);
2074 }
2075
2076 static unsigned int
2077 aa_vlan_get_queue_size(struct ofproto *ofproto OVS_UNUSED)
2078 {
2079     return aa_get_vlan_queue_size();
2080 }
2081
2082 \f
2083 /* Spanning Tree. */
2084
2085 /* Called while rstp_mutex is held. */
2086 static void
2087 rstp_send_bpdu_cb(struct dp_packet *pkt, void *ofport_, void *ofproto_)
2088 {
2089     struct ofproto_dpif *ofproto = ofproto_;
2090     struct ofport_dpif *ofport = ofport_;
2091     struct eth_header *eth = dp_packet_l2(pkt);
2092
2093     netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
2094     if (eth_addr_is_zero(eth->eth_src)) {
2095         VLOG_WARN_RL(&rl, "%s port %d: cannot send RSTP BPDU on a port which "
2096                      "does not have a configured source MAC address.",
2097                      ofproto->up.name, ofp_to_u16(ofport->up.ofp_port));
2098     } else {
2099         ofproto_dpif_send_packet(ofport, pkt);
2100     }
2101     dp_packet_delete(pkt);
2102 }
2103
2104 static void
2105 send_bpdu_cb(struct dp_packet *pkt, int port_num, void *ofproto_)
2106 {
2107     struct ofproto_dpif *ofproto = ofproto_;
2108     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
2109     struct ofport_dpif *ofport;
2110
2111     ofport = stp_port_get_aux(sp);
2112     if (!ofport) {
2113         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
2114                      ofproto->up.name, port_num);
2115     } else {
2116         struct eth_header *eth = dp_packet_l2(pkt);
2117
2118         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
2119         if (eth_addr_is_zero(eth->eth_src)) {
2120             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
2121                          "with unknown MAC", ofproto->up.name, port_num);
2122         } else {
2123             ofproto_dpif_send_packet(ofport, pkt);
2124         }
2125     }
2126     dp_packet_delete(pkt);
2127 }
2128
2129 /* Configure RSTP on 'ofproto_' using the settings defined in 's'. */
2130 static void
2131 set_rstp(struct ofproto *ofproto_, const struct ofproto_rstp_settings *s)
2132 {
2133     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2134
2135     /* Only revalidate flows if the configuration changed. */
2136     if (!s != !ofproto->rstp) {
2137         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2138     }
2139
2140     if (s) {
2141         if (!ofproto->rstp) {
2142             ofproto->rstp = rstp_create(ofproto_->name, s->address,
2143                                         rstp_send_bpdu_cb, ofproto);
2144             ofproto->rstp_last_tick = time_msec();
2145         }
2146         rstp_set_bridge_address(ofproto->rstp, s->address);
2147         rstp_set_bridge_priority(ofproto->rstp, s->priority);
2148         rstp_set_bridge_ageing_time(ofproto->rstp, s->ageing_time);
2149         rstp_set_bridge_force_protocol_version(ofproto->rstp,
2150                                                s->force_protocol_version);
2151         rstp_set_bridge_max_age(ofproto->rstp, s->bridge_max_age);
2152         rstp_set_bridge_forward_delay(ofproto->rstp, s->bridge_forward_delay);
2153         rstp_set_bridge_transmit_hold_count(ofproto->rstp,
2154                                             s->transmit_hold_count);
2155     } else {
2156         struct ofport *ofport;
2157         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
2158             set_rstp_port(ofport, NULL);
2159         }
2160         rstp_unref(ofproto->rstp);
2161         ofproto->rstp = NULL;
2162     }
2163 }
2164
2165 static void
2166 get_rstp_status(struct ofproto *ofproto_, struct ofproto_rstp_status *s)
2167 {
2168     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2169
2170     if (ofproto->rstp) {
2171         s->enabled = true;
2172         s->root_id = rstp_get_root_id(ofproto->rstp);
2173         s->bridge_id = rstp_get_bridge_id(ofproto->rstp);
2174         s->designated_id = rstp_get_designated_id(ofproto->rstp);
2175         s->root_path_cost = rstp_get_root_path_cost(ofproto->rstp);
2176         s->designated_port_id = rstp_get_designated_port_id(ofproto->rstp);
2177         s->bridge_port_id = rstp_get_bridge_port_id(ofproto->rstp);
2178     } else {
2179         s->enabled = false;
2180     }
2181 }
2182
2183 static void
2184 update_rstp_port_state(struct ofport_dpif *ofport)
2185 {
2186     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2187     enum rstp_state state;
2188
2189     /* Figure out new state. */
2190     state = ofport->rstp_port ? rstp_port_get_state(ofport->rstp_port)
2191         : RSTP_DISABLED;
2192
2193     /* Update state. */
2194     if (ofport->rstp_state != state) {
2195         enum ofputil_port_state of_state;
2196         bool fwd_change;
2197
2198         VLOG_DBG("port %s: RSTP state changed from %s to %s",
2199                  netdev_get_name(ofport->up.netdev),
2200                  rstp_state_name(ofport->rstp_state),
2201                  rstp_state_name(state));
2202
2203         if (rstp_learn_in_state(ofport->rstp_state)
2204             != rstp_learn_in_state(state)) {
2205             /* XXX: Learning action flows should also be flushed. */
2206             if (ofport->bundle) {
2207                 if (!rstp_shift_root_learned_address(ofproto->rstp)
2208                     || rstp_get_old_root_aux(ofproto->rstp) != ofport) {
2209                     bundle_flush_macs(ofport->bundle, false);
2210                 }
2211             }
2212         }
2213         fwd_change = rstp_forward_in_state(ofport->rstp_state)
2214             != rstp_forward_in_state(state);
2215
2216         ofproto->backer->need_revalidate = REV_RSTP;
2217         ofport->rstp_state = state;
2218
2219         if (fwd_change && ofport->bundle) {
2220             bundle_update(ofport->bundle);
2221         }
2222
2223         /* Update the RSTP state bits in the OpenFlow port description. */
2224         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
2225         of_state |= (state == RSTP_LEARNING ? OFPUTIL_PS_STP_LEARN
2226                 : state == RSTP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
2227                 : state == RSTP_DISCARDING ?  OFPUTIL_PS_STP_LISTEN
2228                 : 0);
2229         ofproto_port_set_state(&ofport->up, of_state);
2230     }
2231 }
2232
2233 static void
2234 rstp_run(struct ofproto_dpif *ofproto)
2235 {
2236     if (ofproto->rstp) {
2237         long long int now = time_msec();
2238         long long int elapsed = now - ofproto->rstp_last_tick;
2239         struct rstp_port *rp;
2240         struct ofport_dpif *ofport;
2241
2242         /* Every second, decrease the values of the timers. */
2243         if (elapsed >= 1000) {
2244             rstp_tick_timers(ofproto->rstp);
2245             ofproto->rstp_last_tick = now;
2246         }
2247         rp = NULL;
2248         while ((ofport = rstp_get_next_changed_port_aux(ofproto->rstp, &rp))) {
2249             update_rstp_port_state(ofport);
2250         }
2251         rp = NULL;
2252         ofport = NULL;
2253         /* FIXME: This check should be done on-event (i.e., when setting
2254          * p->fdb_flush) and not periodically.
2255          */
2256         while ((ofport = rstp_check_and_reset_fdb_flush(ofproto->rstp, &rp))) {
2257             if (!rstp_shift_root_learned_address(ofproto->rstp)
2258                 || rstp_get_old_root_aux(ofproto->rstp) != ofport) {
2259                 bundle_flush_macs(ofport->bundle, false);
2260             }
2261         }
2262
2263         if (rstp_shift_root_learned_address(ofproto->rstp)) {
2264             bundle_move(((struct ofport_dpif *)rstp_get_old_root_aux(ofproto->rstp))->bundle,
2265                         ((struct ofport_dpif *)rstp_get_new_root_aux(ofproto->rstp))->bundle);
2266             rstp_reset_root_changed(ofproto->rstp);
2267         }
2268     }
2269 }
2270
2271 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
2272 static int
2273 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
2274 {
2275     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2276
2277     /* Only revalidate flows if the configuration changed. */
2278     if (!s != !ofproto->stp) {
2279         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2280     }
2281
2282     if (s) {
2283         if (!ofproto->stp) {
2284             ofproto->stp = stp_create(ofproto_->name, s->system_id,
2285                                       send_bpdu_cb, ofproto);
2286             ofproto->stp_last_tick = time_msec();
2287         }
2288
2289         stp_set_bridge_id(ofproto->stp, s->system_id);
2290         stp_set_bridge_priority(ofproto->stp, s->priority);
2291         stp_set_hello_time(ofproto->stp, s->hello_time);
2292         stp_set_max_age(ofproto->stp, s->max_age);
2293         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
2294     }  else {
2295         struct ofport *ofport;
2296
2297         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
2298             set_stp_port(ofport, NULL);
2299         }
2300
2301         stp_unref(ofproto->stp);
2302         ofproto->stp = NULL;
2303     }
2304
2305     return 0;
2306 }
2307
2308 static int
2309 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
2310 {
2311     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2312
2313     if (ofproto->stp) {
2314         s->enabled = true;
2315         s->bridge_id = stp_get_bridge_id(ofproto->stp);
2316         s->designated_root = stp_get_designated_root(ofproto->stp);
2317         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
2318     } else {
2319         s->enabled = false;
2320     }
2321
2322     return 0;
2323 }
2324
2325 static void
2326 update_stp_port_state(struct ofport_dpif *ofport)
2327 {
2328     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2329     enum stp_state state;
2330
2331     /* Figure out new state. */
2332     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
2333                              : STP_DISABLED;
2334
2335     /* Update state. */
2336     if (ofport->stp_state != state) {
2337         enum ofputil_port_state of_state;
2338         bool fwd_change;
2339
2340         VLOG_DBG("port %s: STP state changed from %s to %s",
2341                  netdev_get_name(ofport->up.netdev),
2342                  stp_state_name(ofport->stp_state),
2343                  stp_state_name(state));
2344         if (stp_learn_in_state(ofport->stp_state)
2345                 != stp_learn_in_state(state)) {
2346             /* xxx Learning action flows should also be flushed. */
2347             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
2348             mac_learning_flush(ofproto->ml);
2349             ovs_rwlock_unlock(&ofproto->ml->rwlock);
2350             mcast_snooping_mdb_flush(ofproto->ms);
2351         }
2352         fwd_change = stp_forward_in_state(ofport->stp_state)
2353                         != stp_forward_in_state(state);
2354
2355         ofproto->backer->need_revalidate = REV_STP;
2356         ofport->stp_state = state;
2357         ofport->stp_state_entered = time_msec();
2358
2359         if (fwd_change && ofport->bundle) {
2360             bundle_update(ofport->bundle);
2361         }
2362
2363         /* Update the STP state bits in the OpenFlow port description. */
2364         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
2365         of_state |= (state == STP_LISTENING ? OFPUTIL_PS_STP_LISTEN
2366                      : state == STP_LEARNING ? OFPUTIL_PS_STP_LEARN
2367                      : state == STP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
2368                      : state == STP_BLOCKING ?  OFPUTIL_PS_STP_BLOCK
2369                      : 0);
2370         ofproto_port_set_state(&ofport->up, of_state);
2371     }
2372 }
2373
2374 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
2375  * caller is responsible for assigning STP port numbers and ensuring
2376  * there are no duplicates. */
2377 static int
2378 set_stp_port(struct ofport *ofport_,
2379              const struct ofproto_port_stp_settings *s)
2380 {
2381     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2382     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2383     struct stp_port *sp = ofport->stp_port;
2384
2385     if (!s || !s->enable) {
2386         if (sp) {
2387             ofport->stp_port = NULL;
2388             stp_port_disable(sp);
2389             update_stp_port_state(ofport);
2390         }
2391         return 0;
2392     } else if (sp && stp_port_no(sp) != s->port_num
2393                && ofport == stp_port_get_aux(sp)) {
2394         /* The port-id changed, so disable the old one if it's not
2395          * already in use by another port. */
2396         stp_port_disable(sp);
2397     }
2398
2399     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
2400
2401     /* Set name before enabling the port so that debugging messages can print
2402      * the name. */
2403     stp_port_set_name(sp, netdev_get_name(ofport->up.netdev));
2404     stp_port_enable(sp);
2405
2406     stp_port_set_aux(sp, ofport);
2407     stp_port_set_priority(sp, s->priority);
2408     stp_port_set_path_cost(sp, s->path_cost);
2409
2410     update_stp_port_state(ofport);
2411
2412     return 0;
2413 }
2414
2415 static int
2416 get_stp_port_status(struct ofport *ofport_,
2417                     struct ofproto_port_stp_status *s)
2418 {
2419     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2420     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2421     struct stp_port *sp = ofport->stp_port;
2422
2423     if (!ofproto->stp || !sp) {
2424         s->enabled = false;
2425         return 0;
2426     }
2427
2428     s->enabled = true;
2429     s->port_id = stp_port_get_id(sp);
2430     s->state = stp_port_get_state(sp);
2431     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
2432     s->role = stp_port_get_role(sp);
2433
2434     return 0;
2435 }
2436
2437 static int
2438 get_stp_port_stats(struct ofport *ofport_,
2439                    struct ofproto_port_stp_stats *s)
2440 {
2441     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2442     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2443     struct stp_port *sp = ofport->stp_port;
2444
2445     if (!ofproto->stp || !sp) {
2446         s->enabled = false;
2447         return 0;
2448     }
2449
2450     s->enabled = true;
2451     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
2452
2453     return 0;
2454 }
2455
2456 static void
2457 stp_run(struct ofproto_dpif *ofproto)
2458 {
2459     if (ofproto->stp) {
2460         long long int now = time_msec();
2461         long long int elapsed = now - ofproto->stp_last_tick;
2462         struct stp_port *sp;
2463
2464         if (elapsed > 0) {
2465             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
2466             ofproto->stp_last_tick = now;
2467         }
2468         while (stp_get_changed_port(ofproto->stp, &sp)) {
2469             struct ofport_dpif *ofport = stp_port_get_aux(sp);
2470
2471             if (ofport) {
2472                 update_stp_port_state(ofport);
2473             }
2474         }
2475
2476         if (stp_check_and_reset_fdb_flush(ofproto->stp)) {
2477             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
2478             mac_learning_flush(ofproto->ml);
2479             ovs_rwlock_unlock(&ofproto->ml->rwlock);
2480             mcast_snooping_mdb_flush(ofproto->ms);
2481         }
2482     }
2483 }
2484
2485 static void
2486 stp_wait(struct ofproto_dpif *ofproto)
2487 {
2488     if (ofproto->stp) {
2489         poll_timer_wait(1000);
2490     }
2491 }
2492
2493 /* Configures RSTP on 'ofport_' using the settings defined in 's'.  The
2494  * caller is responsible for assigning RSTP port numbers and ensuring
2495  * there are no duplicates. */
2496 static void
2497 set_rstp_port(struct ofport *ofport_,
2498               const struct ofproto_port_rstp_settings *s)
2499 {
2500     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2501     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2502     struct rstp_port *rp = ofport->rstp_port;
2503
2504     if (!s || !s->enable) {
2505         if (rp) {
2506             rstp_port_unref(rp);
2507             ofport->rstp_port = NULL;
2508             update_rstp_port_state(ofport);
2509         }
2510         return;
2511     }
2512
2513     /* Check if need to add a new port. */
2514     if (!rp) {
2515         rp = ofport->rstp_port = rstp_add_port(ofproto->rstp);
2516     }
2517
2518     rstp_port_set(rp, s->port_num, s->priority, s->path_cost,
2519                   s->admin_edge_port, s->auto_edge,
2520                   s->admin_p2p_mac_state, s->admin_port_state, s->mcheck,
2521                   ofport);
2522     update_rstp_port_state(ofport);
2523     /* Synchronize operational status. */
2524     rstp_port_set_mac_operational(rp, ofport->may_enable);
2525 }
2526
2527 static void
2528 get_rstp_port_status(struct ofport *ofport_,
2529         struct ofproto_port_rstp_status *s)
2530 {
2531     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2532     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2533     struct rstp_port *rp = ofport->rstp_port;
2534
2535     if (!ofproto->rstp || !rp) {
2536         s->enabled = false;
2537         return;
2538     }
2539
2540     s->enabled = true;
2541     rstp_port_get_status(rp, &s->port_id, &s->state, &s->role,
2542                          &s->designated_bridge_id, &s->designated_port_id,
2543                          &s->designated_path_cost, &s->tx_count,
2544                          &s->rx_count, &s->error_count, &s->uptime);
2545 }
2546
2547 \f
2548 static int
2549 set_queues(struct ofport *ofport_, const struct ofproto_port_queue *qdscp,
2550            size_t n_qdscp)
2551 {
2552     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2553     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2554
2555     if (ofport->n_qdscp != n_qdscp
2556         || (n_qdscp && memcmp(ofport->qdscp, qdscp,
2557                               n_qdscp * sizeof *qdscp))) {
2558         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2559         free(ofport->qdscp);
2560         ofport->qdscp = n_qdscp
2561             ? xmemdup(qdscp, n_qdscp * sizeof *qdscp)
2562             : NULL;
2563         ofport->n_qdscp = n_qdscp;
2564     }
2565
2566     return 0;
2567 }
2568 \f
2569 /* Bundles. */
2570
2571 /* Expires all MAC learning entries associated with 'bundle' and forces its
2572  * ofproto to revalidate every flow.
2573  *
2574  * Normally MAC learning entries are removed only from the ofproto associated
2575  * with 'bundle', but if 'all_ofprotos' is true, then the MAC learning entries
2576  * are removed from every ofproto.  When patch ports and SLB bonds are in use
2577  * and a VM migration happens and the gratuitous ARPs are somehow lost, this
2578  * avoids a MAC_ENTRY_IDLE_TIME delay before the migrated VM can communicate
2579  * with the host from which it migrated. */
2580 static void
2581 bundle_flush_macs(struct ofbundle *bundle, bool all_ofprotos)
2582 {
2583     struct ofproto_dpif *ofproto = bundle->ofproto;
2584     struct mac_learning *ml = ofproto->ml;
2585     struct mac_entry *mac, *next_mac;
2586
2587     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2588     ovs_rwlock_wrlock(&ml->rwlock);
2589     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
2590         if (mac_entry_get_port(ml, mac) == bundle) {
2591             if (all_ofprotos) {
2592                 struct ofproto_dpif *o;
2593
2594                 HMAP_FOR_EACH (o, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2595                     if (o != ofproto) {
2596                         struct mac_entry *e;
2597
2598                         ovs_rwlock_wrlock(&o->ml->rwlock);
2599                         e = mac_learning_lookup(o->ml, mac->mac, mac->vlan);
2600                         if (e) {
2601                             mac_learning_expire(o->ml, e);
2602                         }
2603                         ovs_rwlock_unlock(&o->ml->rwlock);
2604                     }
2605                 }
2606             }
2607
2608             mac_learning_expire(ml, mac);
2609         }
2610     }
2611     ovs_rwlock_unlock(&ml->rwlock);
2612 }
2613
2614 static void
2615 bundle_move(struct ofbundle *old, struct ofbundle *new)
2616 {
2617     struct ofproto_dpif *ofproto = old->ofproto;
2618     struct mac_learning *ml = ofproto->ml;
2619     struct mac_entry *mac, *next_mac;
2620
2621     ovs_assert(new->ofproto == old->ofproto);
2622
2623     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2624     ovs_rwlock_wrlock(&ml->rwlock);
2625     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
2626         if (mac_entry_get_port(ml, mac) == old) {
2627             mac_entry_set_port(ml, mac, new);
2628         }
2629     }
2630     ovs_rwlock_unlock(&ml->rwlock);
2631 }
2632
2633 static struct ofbundle *
2634 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
2635 {
2636     struct ofbundle *bundle;
2637
2638     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
2639                              &ofproto->bundles) {
2640         if (bundle->aux == aux) {
2641             return bundle;
2642         }
2643     }
2644     return NULL;
2645 }
2646
2647 static void
2648 bundle_update(struct ofbundle *bundle)
2649 {
2650     struct ofport_dpif *port;
2651
2652     bundle->floodable = true;
2653     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2654         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2655             || port->is_layer3
2656             || (bundle->ofproto->stp && !stp_forward_in_state(port->stp_state))
2657             || (bundle->ofproto->rstp && !rstp_forward_in_state(port->rstp_state))) {
2658             bundle->floodable = false;
2659             break;
2660         }
2661     }
2662 }
2663
2664 static void
2665 bundle_del_port(struct ofport_dpif *port)
2666 {
2667     struct ofbundle *bundle = port->bundle;
2668
2669     bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2670
2671     list_remove(&port->bundle_node);
2672     port->bundle = NULL;
2673
2674     if (bundle->lacp) {
2675         lacp_slave_unregister(bundle->lacp, port);
2676     }
2677     if (bundle->bond) {
2678         bond_slave_unregister(bundle->bond, port);
2679     }
2680
2681     bundle_update(bundle);
2682 }
2683
2684 static bool
2685 bundle_add_port(struct ofbundle *bundle, ofp_port_t ofp_port,
2686                 struct lacp_slave_settings *lacp)
2687 {
2688     struct ofport_dpif *port;
2689
2690     port = ofp_port_to_ofport(bundle->ofproto, ofp_port);
2691     if (!port) {
2692         return false;
2693     }
2694
2695     if (port->bundle != bundle) {
2696         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2697         if (port->bundle) {
2698             bundle_remove(&port->up);
2699         }
2700
2701         port->bundle = bundle;
2702         list_push_back(&bundle->ports, &port->bundle_node);
2703         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2704             || port->is_layer3
2705             || (bundle->ofproto->stp && !stp_forward_in_state(port->stp_state))
2706             || (bundle->ofproto->rstp && !rstp_forward_in_state(port->rstp_state))) {
2707             bundle->floodable = false;
2708         }
2709     }
2710     if (lacp) {
2711         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2712         lacp_slave_register(bundle->lacp, port, lacp);
2713     }
2714
2715     return true;
2716 }
2717
2718 static void
2719 bundle_destroy(struct ofbundle *bundle)
2720 {
2721     struct ofproto_dpif *ofproto;
2722     struct ofport_dpif *port, *next_port;
2723
2724     if (!bundle) {
2725         return;
2726     }
2727
2728     ofproto = bundle->ofproto;
2729     mbridge_unregister_bundle(ofproto->mbridge, bundle);
2730
2731     xlate_txn_start();
2732     xlate_bundle_remove(bundle);
2733     xlate_txn_commit();
2734
2735     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2736         bundle_del_port(port);
2737     }
2738
2739     bundle_flush_macs(bundle, true);
2740     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
2741     free(bundle->name);
2742     free(bundle->trunks);
2743     lacp_unref(bundle->lacp);
2744     bond_unref(bundle->bond);
2745     free(bundle);
2746 }
2747
2748 static int
2749 bundle_set(struct ofproto *ofproto_, void *aux,
2750            const struct ofproto_bundle_settings *s)
2751 {
2752     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2753     bool need_flush = false;
2754     struct ofport_dpif *port;
2755     struct ofbundle *bundle;
2756     unsigned long *trunks;
2757     int vlan;
2758     size_t i;
2759     bool ok;
2760
2761     if (!s) {
2762         bundle_destroy(bundle_lookup(ofproto, aux));
2763         return 0;
2764     }
2765
2766     ovs_assert(s->n_slaves == 1 || s->bond != NULL);
2767     ovs_assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
2768
2769     bundle = bundle_lookup(ofproto, aux);
2770     if (!bundle) {
2771         bundle = xmalloc(sizeof *bundle);
2772
2773         bundle->ofproto = ofproto;
2774         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
2775                     hash_pointer(aux, 0));
2776         bundle->aux = aux;
2777         bundle->name = NULL;
2778
2779         list_init(&bundle->ports);
2780         bundle->vlan_mode = PORT_VLAN_TRUNK;
2781         bundle->vlan = -1;
2782         bundle->trunks = NULL;
2783         bundle->use_priority_tags = s->use_priority_tags;
2784         bundle->lacp = NULL;
2785         bundle->bond = NULL;
2786
2787         bundle->floodable = true;
2788         mbridge_register_bundle(ofproto->mbridge, bundle);
2789     }
2790
2791     if (!bundle->name || strcmp(s->name, bundle->name)) {
2792         free(bundle->name);
2793         bundle->name = xstrdup(s->name);
2794     }
2795
2796     /* LACP. */
2797     if (s->lacp) {
2798         ofproto->lacp_enabled = true;
2799         if (!bundle->lacp) {
2800             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2801             bundle->lacp = lacp_create();
2802         }
2803         lacp_configure(bundle->lacp, s->lacp);
2804     } else {
2805         lacp_unref(bundle->lacp);
2806         bundle->lacp = NULL;
2807     }
2808
2809     /* Update set of ports. */
2810     ok = true;
2811     for (i = 0; i < s->n_slaves; i++) {
2812         if (!bundle_add_port(bundle, s->slaves[i],
2813                              s->lacp ? &s->lacp_slaves[i] : NULL)) {
2814             ok = false;
2815         }
2816     }
2817     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
2818         struct ofport_dpif *next_port;
2819
2820         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2821             for (i = 0; i < s->n_slaves; i++) {
2822                 if (s->slaves[i] == port->up.ofp_port) {
2823                     goto found;
2824                 }
2825             }
2826
2827             bundle_del_port(port);
2828         found: ;
2829         }
2830     }
2831     ovs_assert(list_size(&bundle->ports) <= s->n_slaves);
2832
2833     if (list_is_empty(&bundle->ports)) {
2834         bundle_destroy(bundle);
2835         return EINVAL;
2836     }
2837
2838     /* Set VLAN tagging mode */
2839     if (s->vlan_mode != bundle->vlan_mode
2840         || s->use_priority_tags != bundle->use_priority_tags) {
2841         bundle->vlan_mode = s->vlan_mode;
2842         bundle->use_priority_tags = s->use_priority_tags;
2843         need_flush = true;
2844     }
2845
2846     /* Set VLAN tag. */
2847     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
2848             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
2849             : 0);
2850     if (vlan != bundle->vlan) {
2851         bundle->vlan = vlan;
2852         need_flush = true;
2853     }
2854
2855     /* Get trunked VLANs. */
2856     switch (s->vlan_mode) {
2857     case PORT_VLAN_ACCESS:
2858         trunks = NULL;
2859         break;
2860
2861     case PORT_VLAN_TRUNK:
2862         trunks = CONST_CAST(unsigned long *, s->trunks);
2863         break;
2864
2865     case PORT_VLAN_NATIVE_UNTAGGED:
2866     case PORT_VLAN_NATIVE_TAGGED:
2867         if (vlan != 0 && (!s->trunks
2868                           || !bitmap_is_set(s->trunks, vlan)
2869                           || bitmap_is_set(s->trunks, 0))) {
2870             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
2871             if (s->trunks) {
2872                 trunks = bitmap_clone(s->trunks, 4096);
2873             } else {
2874                 trunks = bitmap_allocate1(4096);
2875             }
2876             bitmap_set1(trunks, vlan);
2877             bitmap_set0(trunks, 0);
2878         } else {
2879             trunks = CONST_CAST(unsigned long *, s->trunks);
2880         }
2881         break;
2882
2883     default:
2884         OVS_NOT_REACHED();
2885     }
2886     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
2887         free(bundle->trunks);
2888         if (trunks == s->trunks) {
2889             bundle->trunks = vlan_bitmap_clone(trunks);
2890         } else {
2891             bundle->trunks = trunks;
2892             trunks = NULL;
2893         }
2894         need_flush = true;
2895     }
2896     if (trunks != s->trunks) {
2897         free(trunks);
2898     }
2899
2900     /* Bonding. */
2901     if (!list_is_short(&bundle->ports)) {
2902         bundle->ofproto->has_bonded_bundles = true;
2903         if (bundle->bond) {
2904             if (bond_reconfigure(bundle->bond, s->bond)) {
2905                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2906             }
2907         } else {
2908             bundle->bond = bond_create(s->bond, ofproto);
2909             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2910         }
2911
2912         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2913             bond_slave_register(bundle->bond, port,
2914                                 port->up.ofp_port, port->up.netdev);
2915         }
2916     } else {
2917         bond_unref(bundle->bond);
2918         bundle->bond = NULL;
2919     }
2920
2921     /* If we changed something that would affect MAC learning, un-learn
2922      * everything on this port and force flow revalidation. */
2923     if (need_flush) {
2924         bundle_flush_macs(bundle, false);
2925     }
2926
2927     return 0;
2928 }
2929
2930 static void
2931 bundle_remove(struct ofport *port_)
2932 {
2933     struct ofport_dpif *port = ofport_dpif_cast(port_);
2934     struct ofbundle *bundle = port->bundle;
2935
2936     if (bundle) {
2937         bundle_del_port(port);
2938         if (list_is_empty(&bundle->ports)) {
2939             bundle_destroy(bundle);
2940         } else if (list_is_short(&bundle->ports)) {
2941             bond_unref(bundle->bond);
2942             bundle->bond = NULL;
2943         }
2944     }
2945 }
2946
2947 static void
2948 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
2949 {
2950     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
2951     struct ofport_dpif *port = port_;
2952     uint8_t ea[ETH_ADDR_LEN];
2953     int error;
2954
2955     error = netdev_get_etheraddr(port->up.netdev, ea);
2956     if (!error) {
2957         struct dp_packet packet;
2958         void *packet_pdu;
2959
2960         dp_packet_init(&packet, 0);
2961         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
2962                                  pdu_size);
2963         memcpy(packet_pdu, pdu, pdu_size);
2964
2965         ofproto_dpif_send_packet(port, &packet);
2966         dp_packet_uninit(&packet);
2967     } else {
2968         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
2969                     "%s (%s)", port->bundle->name,
2970                     netdev_get_name(port->up.netdev), ovs_strerror(error));
2971     }
2972 }
2973
2974 static void
2975 bundle_send_learning_packets(struct ofbundle *bundle)
2976 {
2977     struct ofproto_dpif *ofproto = bundle->ofproto;
2978     struct dp_packet *learning_packet;
2979     int error, n_packets, n_errors;
2980     struct mac_entry *e;
2981     struct ovs_list packets;
2982
2983     list_init(&packets);
2984     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
2985     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
2986         if (mac_entry_get_port(ofproto->ml, e) != bundle) {
2987             void *port_void;
2988
2989             learning_packet = bond_compose_learning_packet(bundle->bond,
2990                                                            e->mac, e->vlan,
2991                                                            &port_void);
2992             /* Temporarily use 'frame' as a private pointer (see below). */
2993             ovs_assert(learning_packet->frame == dp_packet_data(learning_packet));
2994             learning_packet->frame = port_void;
2995             list_push_back(&packets, &learning_packet->list_node);
2996         }
2997     }
2998     ovs_rwlock_unlock(&ofproto->ml->rwlock);
2999
3000     error = n_packets = n_errors = 0;
3001     LIST_FOR_EACH (learning_packet, list_node, &packets) {
3002         int ret;
3003         void *port_void = learning_packet->frame;
3004
3005         /* Restore 'frame'. */
3006         learning_packet->frame = dp_packet_data(learning_packet);
3007         ret = ofproto_dpif_send_packet(port_void, learning_packet);
3008         if (ret) {
3009             error = ret;
3010             n_errors++;
3011         }
3012         n_packets++;
3013     }
3014     dp_packet_list_delete(&packets);
3015
3016     if (n_errors) {
3017         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3018         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
3019                      "packets, last error was: %s",
3020                      bundle->name, n_errors, n_packets, ovs_strerror(error));
3021     } else {
3022         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
3023                  bundle->name, n_packets);
3024     }
3025 }
3026
3027 static void
3028 bundle_run(struct ofbundle *bundle)
3029 {
3030     if (bundle->lacp) {
3031         lacp_run(bundle->lacp, send_pdu_cb);
3032     }
3033     if (bundle->bond) {
3034         struct ofport_dpif *port;
3035
3036         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
3037             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
3038         }
3039
3040         if (bond_run(bundle->bond, lacp_status(bundle->lacp))) {
3041             bundle->ofproto->backer->need_revalidate = REV_BOND;
3042         }
3043
3044         if (bond_should_send_learning_packets(bundle->bond)) {
3045             bundle_send_learning_packets(bundle);
3046         }
3047     }
3048 }
3049
3050 static void
3051 bundle_wait(struct ofbundle *bundle)
3052 {
3053     if (bundle->lacp) {
3054         lacp_wait(bundle->lacp);
3055     }
3056     if (bundle->bond) {
3057         bond_wait(bundle->bond);
3058     }
3059 }
3060 \f
3061 /* Mirrors. */
3062
3063 static int
3064 mirror_set__(struct ofproto *ofproto_, void *aux,
3065              const struct ofproto_mirror_settings *s)
3066 {
3067     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3068     struct ofbundle **srcs, **dsts;
3069     int error;
3070     size_t i;
3071
3072     if (!s) {
3073         mirror_destroy(ofproto->mbridge, aux);
3074         return 0;
3075     }
3076
3077     srcs = xmalloc(s->n_srcs * sizeof *srcs);
3078     dsts = xmalloc(s->n_dsts * sizeof *dsts);
3079
3080     for (i = 0; i < s->n_srcs; i++) {
3081         srcs[i] = bundle_lookup(ofproto, s->srcs[i]);
3082     }
3083
3084     for (i = 0; i < s->n_dsts; i++) {
3085         dsts[i] = bundle_lookup(ofproto, s->dsts[i]);
3086     }
3087
3088     error = mirror_set(ofproto->mbridge, aux, s->name, srcs, s->n_srcs, dsts,
3089                        s->n_dsts, s->src_vlans,
3090                        bundle_lookup(ofproto, s->out_bundle), s->out_vlan);
3091     free(srcs);
3092     free(dsts);
3093     return error;
3094 }
3095
3096 static int
3097 mirror_get_stats__(struct ofproto *ofproto, void *aux,
3098                    uint64_t *packets, uint64_t *bytes)
3099 {
3100     return mirror_get_stats(ofproto_dpif_cast(ofproto)->mbridge, aux, packets,
3101                             bytes);
3102 }
3103
3104 static int
3105 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
3106 {
3107     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3108     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
3109     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
3110         mac_learning_flush(ofproto->ml);
3111     }
3112     ovs_rwlock_unlock(&ofproto->ml->rwlock);
3113     return 0;
3114 }
3115
3116 static bool
3117 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
3118 {
3119     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3120     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
3121     return bundle && mirror_bundle_out(ofproto->mbridge, bundle) != 0;
3122 }
3123
3124 static void
3125 forward_bpdu_changed(struct ofproto *ofproto_)
3126 {
3127     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3128     ofproto->backer->need_revalidate = REV_RECONFIGURE;
3129 }
3130
3131 static void
3132 set_mac_table_config(struct ofproto *ofproto_, unsigned int idle_time,
3133                      size_t max_entries)
3134 {
3135     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3136     ovs_rwlock_wrlock(&ofproto->ml->rwlock);
3137     mac_learning_set_idle_time(ofproto->ml, idle_time);
3138     mac_learning_set_max_entries(ofproto->ml, max_entries);
3139     ovs_rwlock_unlock(&ofproto->ml->rwlock);
3140 }
3141
3142 /* Configures multicast snooping on 'ofport' using the settings
3143  * defined in 's'. */
3144 static int
3145 set_mcast_snooping(struct ofproto *ofproto_,
3146                    const struct ofproto_mcast_snooping_settings *s)
3147 {
3148     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3149
3150     /* Only revalidate flows if the configuration changed. */
3151     if (!s != !ofproto->ms) {
3152         ofproto->backer->need_revalidate = REV_RECONFIGURE;
3153     }
3154
3155     if (s) {
3156         if (!ofproto->ms) {
3157             ofproto->ms = mcast_snooping_create();
3158         }
3159
3160         ovs_rwlock_wrlock(&ofproto->ms->rwlock);
3161         mcast_snooping_set_idle_time(ofproto->ms, s->idle_time);
3162         mcast_snooping_set_max_entries(ofproto->ms, s->max_entries);
3163         if (mcast_snooping_set_flood_unreg(ofproto->ms, s->flood_unreg)) {
3164             ofproto->backer->need_revalidate = REV_RECONFIGURE;
3165         }
3166         ovs_rwlock_unlock(&ofproto->ms->rwlock);
3167     } else {
3168         mcast_snooping_unref(ofproto->ms);
3169         ofproto->ms = NULL;
3170     }
3171
3172     return 0;
3173 }
3174
3175 /* Configures multicast snooping port's flood settings on 'ofproto'. */
3176 static int
3177 set_mcast_snooping_port(struct ofproto *ofproto_, void *aux,
3178                         const struct ofproto_mcast_snooping_port_settings *s)
3179 {
3180     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3181     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
3182
3183     if (ofproto->ms && s) {
3184         ovs_rwlock_wrlock(&ofproto->ms->rwlock);
3185         mcast_snooping_set_port_flood(ofproto->ms, bundle, s->flood);
3186         mcast_snooping_set_port_flood_reports(ofproto->ms, bundle,
3187                                               s->flood_reports);
3188         ovs_rwlock_unlock(&ofproto->ms->rwlock);
3189     }
3190     return 0;
3191 }
3192
3193 \f
3194 /* Ports. */
3195
3196 struct ofport_dpif *
3197 ofp_port_to_ofport(const struct ofproto_dpif *ofproto, ofp_port_t ofp_port)
3198 {
3199     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
3200     return ofport ? ofport_dpif_cast(ofport) : NULL;
3201 }
3202
3203 static void
3204 ofproto_port_from_dpif_port(struct ofproto_dpif *ofproto,
3205                             struct ofproto_port *ofproto_port,
3206                             struct dpif_port *dpif_port)
3207 {
3208     ofproto_port->name = dpif_port->name;
3209     ofproto_port->type = dpif_port->type;
3210     ofproto_port->ofp_port = odp_port_to_ofp_port(ofproto, dpif_port->port_no);
3211 }
3212
3213 static void
3214 ofport_update_peer(struct ofport_dpif *ofport)
3215 {
3216     const struct ofproto_dpif *ofproto;
3217     struct dpif_backer *backer;
3218     char *peer_name;
3219
3220     if (!netdev_vport_is_patch(ofport->up.netdev)) {
3221         return;
3222     }
3223
3224     backer = ofproto_dpif_cast(ofport->up.ofproto)->backer;
3225     backer->need_revalidate = REV_RECONFIGURE;
3226
3227     if (ofport->peer) {
3228         ofport->peer->peer = NULL;
3229         ofport->peer = NULL;
3230     }
3231
3232     peer_name = netdev_vport_patch_peer(ofport->up.netdev);
3233     if (!peer_name) {
3234         return;
3235     }
3236
3237     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
3238         struct ofport *peer_ofport;
3239         struct ofport_dpif *peer;
3240         char *peer_peer;
3241
3242         if (ofproto->backer != backer) {
3243             continue;
3244         }
3245
3246         peer_ofport = shash_find_data(&ofproto->up.port_by_name, peer_name);
3247         if (!peer_ofport) {
3248             continue;
3249         }
3250
3251         peer = ofport_dpif_cast(peer_ofport);
3252         peer_peer = netdev_vport_patch_peer(peer->up.netdev);
3253         if (peer_peer && !strcmp(netdev_get_name(ofport->up.netdev),
3254                                  peer_peer)) {
3255             ofport->peer = peer;
3256             ofport->peer->peer = ofport;
3257         }
3258         free(peer_peer);
3259
3260         break;
3261     }
3262     free(peer_name);
3263 }
3264
3265 static void
3266 port_run(struct ofport_dpif *ofport)
3267 {
3268     long long int carrier_seq = netdev_get_carrier_resets(ofport->up.netdev);
3269     bool carrier_changed = carrier_seq != ofport->carrier_seq;
3270     bool enable = netdev_get_carrier(ofport->up.netdev);
3271     bool cfm_enable = false;
3272     bool bfd_enable = false;
3273
3274     ofport->carrier_seq = carrier_seq;
3275
3276     if (ofport->cfm) {
3277         int cfm_opup = cfm_get_opup(ofport->cfm);
3278
3279         cfm_enable = !cfm_get_fault(ofport->cfm);
3280
3281         if (cfm_opup >= 0) {
3282             cfm_enable = cfm_enable && cfm_opup;
3283         }
3284     }
3285
3286     if (ofport->bfd) {
3287         bfd_enable = bfd_forwarding(ofport->bfd);
3288     }
3289
3290     if (ofport->bfd || ofport->cfm) {
3291         enable = enable && (cfm_enable || bfd_enable);
3292     }
3293
3294     if (ofport->bundle) {
3295         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
3296         if (carrier_changed) {
3297             lacp_slave_carrier_changed(ofport->bundle->lacp, ofport);
3298         }
3299     }
3300
3301     if (ofport->may_enable != enable) {
3302         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3303
3304         ofproto->backer->need_revalidate = REV_PORT_TOGGLED;
3305
3306         if (ofport->rstp_port) {
3307             rstp_port_set_mac_operational(ofport->rstp_port, enable);
3308         }
3309     }
3310
3311     ofport->may_enable = enable;
3312 }
3313
3314 static int
3315 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
3316                    struct ofproto_port *ofproto_port)
3317 {
3318     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3319     struct dpif_port dpif_port;
3320     int error;
3321
3322     if (sset_contains(&ofproto->ghost_ports, devname)) {
3323         const char *type = netdev_get_type_from_name(devname);
3324
3325         /* We may be called before ofproto->up.port_by_name is populated with
3326          * the appropriate ofport.  For this reason, we must get the name and
3327          * type from the netdev layer directly. */
3328         if (type) {
3329             const struct ofport *ofport;
3330
3331             ofport = shash_find_data(&ofproto->up.port_by_name, devname);
3332             ofproto_port->ofp_port = ofport ? ofport->ofp_port : OFPP_NONE;
3333             ofproto_port->name = xstrdup(devname);
3334             ofproto_port->type = xstrdup(type);
3335             return 0;
3336         }
3337         return ENODEV;
3338     }
3339
3340     if (!sset_contains(&ofproto->ports, devname)) {
3341         return ENODEV;
3342     }
3343     error = dpif_port_query_by_name(ofproto->backer->dpif,
3344                                     devname, &dpif_port);
3345     if (!error) {
3346         ofproto_port_from_dpif_port(ofproto, ofproto_port, &dpif_port);
3347     }
3348     return error;
3349 }
3350
3351 static int
3352 port_add(struct ofproto *ofproto_, struct netdev *netdev)
3353 {
3354     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3355     const char *devname = netdev_get_name(netdev);
3356     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
3357     const char *dp_port_name;
3358
3359     if (netdev_vport_is_patch(netdev)) {
3360         sset_add(&ofproto->ghost_ports, netdev_get_name(netdev));
3361         return 0;
3362     }
3363
3364     dp_port_name = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
3365     if (!dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
3366         odp_port_t port_no = ODPP_NONE;
3367         int error;
3368
3369         error = dpif_port_add(ofproto->backer->dpif, netdev, &port_no);
3370         if (error) {
3371             return error;
3372         }
3373         if (netdev_get_tunnel_config(netdev)) {
3374             simap_put(&ofproto->backer->tnl_backers,
3375                       dp_port_name, odp_to_u32(port_no));
3376         }
3377     }
3378
3379     if (netdev_get_tunnel_config(netdev)) {
3380         sset_add(&ofproto->ghost_ports, devname);
3381     } else {
3382         sset_add(&ofproto->ports, devname);
3383     }
3384     return 0;
3385 }
3386
3387 static int
3388 port_del(struct ofproto *ofproto_, ofp_port_t ofp_port)
3389 {
3390     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3391     struct ofport_dpif *ofport = ofp_port_to_ofport(ofproto, ofp_port);
3392     int error = 0;
3393
3394     if (!ofport) {
3395         return 0;
3396     }
3397
3398     sset_find_and_delete(&ofproto->ghost_ports,
3399                          netdev_get_name(ofport->up.netdev));
3400     ofproto->backer->need_revalidate = REV_RECONFIGURE;
3401     if (!ofport->is_tunnel && !netdev_vport_is_patch(ofport->up.netdev)) {
3402         error = dpif_port_del(ofproto->backer->dpif, ofport->odp_port);
3403         if (!error) {
3404             /* The caller is going to close ofport->up.netdev.  If this is a
3405              * bonded port, then the bond is using that netdev, so remove it
3406              * from the bond.  The client will need to reconfigure everything
3407              * after deleting ports, so then the slave will get re-added. */
3408             bundle_remove(&ofport->up);
3409         }
3410     }
3411     return error;
3412 }
3413
3414 static int
3415 port_get_stats(const struct ofport *ofport_, struct netdev_stats *stats)
3416 {
3417     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3418     int error;
3419
3420     error = netdev_get_stats(ofport->up.netdev, stats);
3421
3422     if (!error && ofport_->ofp_port == OFPP_LOCAL) {
3423         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3424
3425         ovs_mutex_lock(&ofproto->stats_mutex);
3426         /* ofproto->stats.tx_packets represents packets that we created
3427          * internally and sent to some port (e.g. packets sent with
3428          * ofproto_dpif_send_packet()).  Account for them as if they had
3429          * come from OFPP_LOCAL and got forwarded. */
3430
3431         if (stats->rx_packets != UINT64_MAX) {
3432             stats->rx_packets += ofproto->stats.tx_packets;
3433         }
3434
3435         if (stats->rx_bytes != UINT64_MAX) {
3436             stats->rx_bytes += ofproto->stats.tx_bytes;
3437         }
3438
3439         /* ofproto->stats.rx_packets represents packets that were received on
3440          * some port and we processed internally and dropped (e.g. STP).
3441          * Account for them as if they had been forwarded to OFPP_LOCAL. */
3442
3443         if (stats->tx_packets != UINT64_MAX) {
3444             stats->tx_packets += ofproto->stats.rx_packets;
3445         }
3446
3447         if (stats->tx_bytes != UINT64_MAX) {
3448             stats->tx_bytes += ofproto->stats.rx_bytes;
3449         }
3450         ovs_mutex_unlock(&ofproto->stats_mutex);
3451     }
3452
3453     return error;
3454 }
3455
3456 static int
3457 port_get_lacp_stats(const struct ofport *ofport_, struct lacp_slave_stats *stats)
3458 {
3459     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3460     if (ofport->bundle && ofport->bundle->lacp) {
3461         if (lacp_get_slave_stats(ofport->bundle->lacp, ofport, stats)) {
3462             return 0;
3463         }
3464     }
3465     return -1;
3466 }
3467
3468 struct port_dump_state {
3469     uint32_t bucket;
3470     uint32_t offset;
3471     bool ghost;
3472
3473     struct ofproto_port port;
3474     bool has_port;
3475 };
3476
3477 static int
3478 port_dump_start(const struct ofproto *ofproto_ OVS_UNUSED, void **statep)
3479 {
3480     *statep = xzalloc(sizeof(struct port_dump_state));
3481     return 0;
3482 }
3483
3484 static int
3485 port_dump_next(const struct ofproto *ofproto_, void *state_,
3486                struct ofproto_port *port)
3487 {
3488     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3489     struct port_dump_state *state = state_;
3490     const struct sset *sset;
3491     struct sset_node *node;
3492
3493     if (state->has_port) {
3494         ofproto_port_destroy(&state->port);
3495         state->has_port = false;
3496     }
3497     sset = state->ghost ? &ofproto->ghost_ports : &ofproto->ports;
3498     while ((node = sset_at_position(sset, &state->bucket, &state->offset))) {
3499         int error;
3500
3501         error = port_query_by_name(ofproto_, node->name, &state->port);
3502         if (!error) {
3503             *port = state->port;
3504             state->has_port = true;
3505             return 0;
3506         } else if (error != ENODEV) {
3507             return error;
3508         }
3509     }
3510
3511     if (!state->ghost) {
3512         state->ghost = true;
3513         state->bucket = 0;
3514         state->offset = 0;
3515         return port_dump_next(ofproto_, state_, port);
3516     }
3517
3518     return EOF;
3519 }
3520
3521 static int
3522 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
3523 {
3524     struct port_dump_state *state = state_;
3525
3526     if (state->has_port) {
3527         ofproto_port_destroy(&state->port);
3528     }
3529     free(state);
3530     return 0;
3531 }
3532
3533 static int
3534 port_poll(const struct ofproto *ofproto_, char **devnamep)
3535 {
3536     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3537
3538     if (ofproto->port_poll_errno) {
3539         int error = ofproto->port_poll_errno;
3540         ofproto->port_poll_errno = 0;
3541         return error;
3542     }
3543
3544     if (sset_is_empty(&ofproto->port_poll_set)) {
3545         return EAGAIN;
3546     }
3547
3548     *devnamep = sset_pop(&ofproto->port_poll_set);
3549     return 0;
3550 }
3551
3552 static void
3553 port_poll_wait(const struct ofproto *ofproto_)
3554 {
3555     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3556     dpif_port_poll_wait(ofproto->backer->dpif);
3557 }
3558
3559 static int
3560 port_is_lacp_current(const struct ofport *ofport_)
3561 {
3562     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3563     return (ofport->bundle && ofport->bundle->lacp
3564             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
3565             : -1);
3566 }
3567 \f
3568 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
3569  * then delete it entirely. */
3570 static void
3571 rule_expire(struct rule_dpif *rule)
3572     OVS_REQUIRES(ofproto_mutex)
3573 {
3574     uint16_t hard_timeout, idle_timeout;
3575     long long int now = time_msec();
3576     int reason = -1;
3577
3578     hard_timeout = rule->up.hard_timeout;
3579     idle_timeout = rule->up.idle_timeout;
3580
3581     /* Has 'rule' expired? */
3582     if (hard_timeout) {
3583         long long int modified;
3584
3585         ovs_mutex_lock(&rule->up.mutex);
3586         modified = rule->up.modified;
3587         ovs_mutex_unlock(&rule->up.mutex);
3588
3589         if (now > modified + hard_timeout * 1000) {
3590             reason = OFPRR_HARD_TIMEOUT;
3591         }
3592     }
3593
3594     if (reason < 0 && idle_timeout) {
3595         long long int used;
3596
3597         ovs_mutex_lock(&rule->stats_mutex);
3598         used = rule->stats.used;
3599         ovs_mutex_unlock(&rule->stats_mutex);
3600
3601         if (now > used + idle_timeout * 1000) {
3602             reason = OFPRR_IDLE_TIMEOUT;
3603         }
3604     }
3605
3606     if (reason >= 0) {
3607         COVERAGE_INC(ofproto_dpif_expired);
3608         ofproto_rule_expire(&rule->up, reason);
3609     }
3610 }
3611
3612 /* Executes, within 'ofproto', the actions in 'rule' or 'ofpacts' on 'packet'.
3613  * 'flow' must reflect the data in 'packet'. */
3614 int
3615 ofproto_dpif_execute_actions(struct ofproto_dpif *ofproto,
3616                              const struct flow *flow,
3617                              struct rule_dpif *rule,
3618                              const struct ofpact *ofpacts, size_t ofpacts_len,
3619                              struct dp_packet *packet)
3620 {
3621     struct dpif_flow_stats stats;
3622     struct xlate_out xout;
3623     struct xlate_in xin;
3624     ofp_port_t in_port;
3625     struct dpif_execute execute;
3626     int error;
3627
3628     ovs_assert((rule != NULL) != (ofpacts != NULL));
3629
3630     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
3631
3632     if (rule) {
3633         rule_dpif_credit_stats(rule, &stats);
3634     }
3635
3636     xlate_in_init(&xin, ofproto, flow, flow->in_port.ofp_port, rule,
3637                   stats.tcp_flags, packet);
3638     xin.ofpacts = ofpacts;
3639     xin.ofpacts_len = ofpacts_len;
3640     xin.resubmit_stats = &stats;
3641     xlate_actions(&xin, &xout);
3642
3643     execute.actions = xout.odp_actions->data;
3644     execute.actions_len = xout.odp_actions->size;
3645
3646     pkt_metadata_from_flow(&packet->md, flow);
3647     execute.packet = packet;
3648     execute.needs_help = (xout.slow & SLOW_ACTION) != 0;
3649     execute.probe = false;
3650
3651     /* Fix up in_port. */
3652     in_port = flow->in_port.ofp_port;
3653     if (in_port == OFPP_NONE) {
3654         in_port = OFPP_LOCAL;
3655     }
3656     execute.packet->md.in_port.odp_port = ofp_port_to_odp_port(ofproto, in_port);
3657
3658     error = dpif_execute(ofproto->backer->dpif, &execute);
3659
3660     xlate_out_uninit(&xout);
3661
3662     return error;
3663 }
3664
3665 void
3666 rule_dpif_credit_stats(struct rule_dpif *rule,
3667                        const struct dpif_flow_stats *stats)
3668 {
3669     ovs_mutex_lock(&rule->stats_mutex);
3670     rule->stats.n_packets += stats->n_packets;
3671     rule->stats.n_bytes += stats->n_bytes;
3672     rule->stats.used = MAX(rule->stats.used, stats->used);
3673     ovs_mutex_unlock(&rule->stats_mutex);
3674 }
3675
3676 ovs_be64
3677 rule_dpif_get_flow_cookie(const struct rule_dpif *rule)
3678     OVS_REQUIRES(rule->up.mutex)
3679 {
3680     return rule->up.flow_cookie;
3681 }
3682
3683 void
3684 rule_dpif_reduce_timeouts(struct rule_dpif *rule, uint16_t idle_timeout,
3685                      uint16_t hard_timeout)
3686 {
3687     ofproto_rule_reduce_timeouts(&rule->up, idle_timeout, hard_timeout);
3688 }
3689
3690 /* Returns 'rule''s actions.  The returned actions are RCU-protected, and can
3691  * be read until the calling thread quiesces. */
3692 const struct rule_actions *
3693 rule_dpif_get_actions(const struct rule_dpif *rule)
3694 {
3695     return rule_get_actions(&rule->up);
3696 }
3697
3698 /* Sets 'rule''s recirculation id. */
3699 static void
3700 rule_dpif_set_recirc_id(struct rule_dpif *rule, uint32_t id)
3701     OVS_REQUIRES(rule->up.mutex)
3702 {
3703     ovs_assert(!rule->recirc_id || rule->recirc_id == id);
3704     if (rule->recirc_id == id) {
3705         /* Release the new reference to the same id. */
3706         recirc_free_id(id);
3707     } else {
3708         rule->recirc_id = id;
3709     }
3710 }
3711
3712 /* Sets 'rule''s recirculation id. */
3713 void
3714 rule_set_recirc_id(struct rule *rule_, uint32_t id)
3715 {
3716     struct rule_dpif *rule = rule_dpif_cast(rule_);
3717
3718     ovs_mutex_lock(&rule->up.mutex);
3719     rule_dpif_set_recirc_id(rule, id);
3720     ovs_mutex_unlock(&rule->up.mutex);
3721 }
3722
3723 /* The returned rule (if any) is valid at least until the next RCU quiescent
3724  * period.  If the rule needs to stay around longer, a non-zero 'take_ref'
3725  * must be passed in to cause a reference to be taken on it.
3726  *
3727  * 'flow' is non-const to allow for temporary modifications during the lookup.
3728  * Any changes are restored before returning. */
3729 static struct rule_dpif *
3730 rule_dpif_lookup_in_table(struct ofproto_dpif *ofproto, uint8_t table_id,
3731                           struct flow *flow, struct flow_wildcards *wc,
3732                           bool take_ref)
3733 {
3734     struct classifier *cls = &ofproto->up.tables[table_id].cls;
3735     const struct cls_rule *cls_rule;
3736     struct rule_dpif *rule;
3737
3738     do {
3739         cls_rule = classifier_lookup(cls, flow, wc);
3740
3741         rule = rule_dpif_cast(rule_from_cls_rule(cls_rule));
3742
3743         /* Try again if the rule was released before we get the reference. */
3744     } while (rule && take_ref && !rule_dpif_try_ref(rule));
3745
3746     return rule;
3747 }
3748
3749 /* Look up 'flow' in 'ofproto''s classifier starting from table '*table_id'.
3750  * Returns the rule that was found, which may be one of the special rules
3751  * according to packet miss hadling.  If 'may_packet_in' is false, returning of
3752  * the miss_rule (which issues packet ins for the controller) is avoided.
3753  * Updates 'wc', if nonnull, to reflect the fields that were used during the
3754  * lookup.
3755  *
3756  * If 'honor_table_miss' is true, the first lookup occurs in '*table_id', but
3757  * if none is found then the table miss configuration for that table is
3758  * honored, which can result in additional lookups in other OpenFlow tables.
3759  * In this case the function updates '*table_id' to reflect the final OpenFlow
3760  * table that was searched.
3761  *
3762  * If 'honor_table_miss' is false, then only one table lookup occurs, in
3763  * '*table_id'.
3764  *
3765  * The rule is returned in '*rule', which is valid at least until the next
3766  * RCU quiescent period.  If the '*rule' needs to stay around longer,
3767  * a non-zero 'take_ref' must be passed in to cause a reference to be taken
3768  * on it before this returns.
3769  *
3770  * 'in_port' allows the lookup to take place as if the in port had the value
3771  * 'in_port'.  This is needed for resubmit action support.
3772  *
3773  * 'flow' is non-const to allow for temporary modifications during the lookup.
3774  * Any changes are restored before returning. */
3775 struct rule_dpif *
3776 rule_dpif_lookup_from_table(struct ofproto_dpif *ofproto, struct flow *flow,
3777                             struct flow_wildcards *wc, bool take_ref,
3778                             const struct dpif_flow_stats *stats,
3779                             uint8_t *table_id, ofp_port_t in_port,
3780                             bool may_packet_in, bool honor_table_miss)
3781 {
3782     ovs_be16 old_tp_src = flow->tp_src, old_tp_dst = flow->tp_dst;
3783     ofp_port_t old_in_port = flow->in_port.ofp_port;
3784     enum ofputil_table_miss miss_config;
3785     struct rule_dpif *rule;
3786     uint8_t next_id;
3787
3788     /* We always unwildcard nw_frag (for IP), so they
3789      * need not be unwildcarded here. */
3790     if (flow->nw_frag & FLOW_NW_FRAG_ANY
3791         && ofproto->up.frag_handling != OFPC_FRAG_NX_MATCH) {
3792         if (ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
3793             /* We must pretend that transport ports are unavailable. */
3794             flow->tp_src = htons(0);
3795             flow->tp_dst = htons(0);
3796         } else {
3797             /* Must be OFPC_FRAG_DROP (we don't have OFPC_FRAG_REASM).
3798              * Use the drop_frags_rule (which cannot disappear). */
3799             rule = ofproto->drop_frags_rule;
3800             if (take_ref) {
3801                 rule_dpif_ref(rule);
3802             }
3803             if (stats) {
3804                 struct oftable *tbl = &ofproto->up.tables[*table_id];
3805                 unsigned long orig;
3806
3807                 atomic_add_relaxed(&tbl->n_matched, stats->n_packets, &orig);
3808             }
3809             return rule;
3810         }
3811     }
3812
3813     /* Look up a flow with 'in_port' as the input port.  Then restore the
3814      * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
3815      * have surprising behavior). */
3816     flow->in_port.ofp_port = in_port;
3817
3818     /* Our current implementation depends on n_tables == N_TABLES, and
3819      * TBL_INTERNAL being the last table. */
3820     BUILD_ASSERT_DECL(N_TABLES == TBL_INTERNAL + 1);
3821
3822     miss_config = OFPUTIL_TABLE_MISS_CONTINUE;
3823
3824     for (next_id = *table_id;
3825          next_id < ofproto->up.n_tables;
3826          next_id++, next_id += (next_id == TBL_INTERNAL))
3827     {
3828         *table_id = next_id;
3829         rule = rule_dpif_lookup_in_table(ofproto, next_id, flow, wc, take_ref);
3830         if (stats) {
3831             struct oftable *tbl = &ofproto->up.tables[next_id];
3832             unsigned long orig;
3833
3834             atomic_add_relaxed(rule ? &tbl->n_matched : &tbl->n_missed,
3835                                stats->n_packets, &orig);
3836         }
3837         if (rule) {
3838             goto out;   /* Match. */
3839         }
3840         if (honor_table_miss) {
3841             miss_config = ofproto_table_get_miss_config(&ofproto->up,
3842                                                         *table_id);
3843             if (miss_config == OFPUTIL_TABLE_MISS_CONTINUE) {
3844                 continue;
3845             }
3846         }
3847         break;
3848     }
3849     /* Miss. */
3850     rule = ofproto->no_packet_in_rule;
3851     if (may_packet_in) {
3852         if (miss_config == OFPUTIL_TABLE_MISS_CONTINUE
3853             || miss_config == OFPUTIL_TABLE_MISS_CONTROLLER) {
3854             struct ofport_dpif *port;
3855
3856             port = ofp_port_to_ofport(ofproto, old_in_port);
3857             if (!port) {
3858                 VLOG_WARN_RL(&rl, "packet-in on unknown OpenFlow port %"PRIu16,
3859                              old_in_port);
3860             } else if (!(port->up.pp.config & OFPUTIL_PC_NO_PACKET_IN)) {
3861                 rule = ofproto->miss_rule;
3862             }
3863         } else if (miss_config == OFPUTIL_TABLE_MISS_DEFAULT &&
3864                    connmgr_wants_packet_in_on_miss(ofproto->up.connmgr)) {
3865             rule = ofproto->miss_rule;
3866         }
3867     }
3868     if (take_ref) {
3869         rule_dpif_ref(rule);
3870     }
3871 out:
3872     /* Restore port numbers, as they may have been modified above. */
3873     flow->tp_src = old_tp_src;
3874     flow->tp_dst = old_tp_dst;
3875     /* Restore the old in port. */
3876     flow->in_port.ofp_port = old_in_port;
3877
3878     return rule;
3879 }
3880
3881 static void
3882 complete_operation(struct rule_dpif *rule)
3883     OVS_REQUIRES(ofproto_mutex)
3884 {
3885     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3886
3887     ofproto->backer->need_revalidate = REV_FLOW_TABLE;
3888 }
3889
3890 static struct rule_dpif *rule_dpif_cast(const struct rule *rule)
3891 {
3892     return rule ? CONTAINER_OF(rule, struct rule_dpif, up) : NULL;
3893 }
3894
3895 static struct rule *
3896 rule_alloc(void)
3897 {
3898     struct rule_dpif *rule = xmalloc(sizeof *rule);
3899     return &rule->up;
3900 }
3901
3902 static void
3903 rule_dealloc(struct rule *rule_)
3904 {
3905     struct rule_dpif *rule = rule_dpif_cast(rule_);
3906     free(rule);
3907 }
3908
3909 static enum ofperr
3910 rule_construct(struct rule *rule_)
3911     OVS_NO_THREAD_SAFETY_ANALYSIS
3912 {
3913     struct rule_dpif *rule = rule_dpif_cast(rule_);
3914     ovs_mutex_init_adaptive(&rule->stats_mutex);
3915     rule->stats.n_packets = 0;
3916     rule->stats.n_bytes = 0;
3917     rule->stats.used = rule->up.modified;
3918     rule->recirc_id = 0;
3919
3920     return 0;
3921 }
3922
3923 static enum ofperr
3924 rule_insert(struct rule *rule_)
3925     OVS_REQUIRES(ofproto_mutex)
3926 {
3927     struct rule_dpif *rule = rule_dpif_cast(rule_);
3928     complete_operation(rule);
3929     return 0;
3930 }
3931
3932 static void
3933 rule_delete(struct rule *rule_)
3934     OVS_REQUIRES(ofproto_mutex)
3935 {
3936     struct rule_dpif *rule = rule_dpif_cast(rule_);
3937     complete_operation(rule);
3938 }
3939
3940 static void
3941 rule_destruct(struct rule *rule_)
3942 {
3943     struct rule_dpif *rule = rule_dpif_cast(rule_);
3944
3945     ovs_mutex_destroy(&rule->stats_mutex);
3946     if (rule->recirc_id) {
3947         recirc_free_id(rule->recirc_id);
3948     }
3949 }
3950
3951 static void
3952 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes,
3953                long long int *used)
3954 {
3955     struct rule_dpif *rule = rule_dpif_cast(rule_);
3956
3957     ovs_mutex_lock(&rule->stats_mutex);
3958     *packets = rule->stats.n_packets;
3959     *bytes = rule->stats.n_bytes;
3960     *used = rule->stats.used;
3961     ovs_mutex_unlock(&rule->stats_mutex);
3962 }
3963
3964 static void
3965 rule_dpif_execute(struct rule_dpif *rule, const struct flow *flow,
3966                   struct dp_packet *packet)
3967 {
3968     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3969
3970     ofproto_dpif_execute_actions(ofproto, flow, rule, NULL, 0, packet);
3971 }
3972
3973 static enum ofperr
3974 rule_execute(struct rule *rule, const struct flow *flow,
3975              struct dp_packet *packet)
3976 {
3977     rule_dpif_execute(rule_dpif_cast(rule), flow, packet);
3978     dp_packet_delete(packet);
3979     return 0;
3980 }
3981
3982 static void
3983 rule_modify_actions(struct rule *rule_, bool reset_counters)
3984     OVS_REQUIRES(ofproto_mutex)
3985 {
3986     struct rule_dpif *rule = rule_dpif_cast(rule_);
3987
3988     if (reset_counters) {
3989         ovs_mutex_lock(&rule->stats_mutex);
3990         rule->stats.n_packets = 0;
3991         rule->stats.n_bytes = 0;
3992         ovs_mutex_unlock(&rule->stats_mutex);
3993     }
3994
3995     complete_operation(rule);
3996 }
3997
3998 static struct group_dpif *group_dpif_cast(const struct ofgroup *group)
3999 {
4000     return group ? CONTAINER_OF(group, struct group_dpif, up) : NULL;
4001 }
4002
4003 static struct ofgroup *
4004 group_alloc(void)
4005 {
4006     struct group_dpif *group = xzalloc(sizeof *group);
4007     return &group->up;
4008 }
4009
4010 static void
4011 group_dealloc(struct ofgroup *group_)
4012 {
4013     struct group_dpif *group = group_dpif_cast(group_);
4014     free(group);
4015 }
4016
4017 static void
4018 group_construct_stats(struct group_dpif *group)
4019     OVS_REQUIRES(group->stats_mutex)
4020 {
4021     struct ofputil_bucket *bucket;
4022     const struct ovs_list *buckets;
4023
4024     group->packet_count = 0;
4025     group->byte_count = 0;
4026
4027     group_dpif_get_buckets(group, &buckets);
4028     LIST_FOR_EACH (bucket, list_node, buckets) {
4029         bucket->stats.packet_count = 0;
4030         bucket->stats.byte_count = 0;
4031     }
4032 }
4033
4034 void
4035 group_dpif_credit_stats(struct group_dpif *group,
4036                         struct ofputil_bucket *bucket,
4037                         const struct dpif_flow_stats *stats)
4038 {
4039     ovs_mutex_lock(&group->stats_mutex);
4040     group->packet_count += stats->n_packets;
4041     group->byte_count += stats->n_bytes;
4042     if (bucket) {
4043         bucket->stats.packet_count += stats->n_packets;
4044         bucket->stats.byte_count += stats->n_bytes;
4045     } else { /* Credit to all buckets */
4046         const struct ovs_list *buckets;
4047
4048         group_dpif_get_buckets(group, &buckets);
4049         LIST_FOR_EACH (bucket, list_node, buckets) {
4050             bucket->stats.packet_count += stats->n_packets;
4051             bucket->stats.byte_count += stats->n_bytes;
4052         }
4053     }
4054     ovs_mutex_unlock(&group->stats_mutex);
4055 }
4056
4057 static enum ofperr
4058 group_construct(struct ofgroup *group_)
4059 {
4060     struct group_dpif *group = group_dpif_cast(group_);
4061     const struct ofputil_bucket *bucket;
4062
4063     /* Prevent group chaining because our locking structure makes it hard to
4064      * implement deadlock-free.  (See xlate_group_resource_check().) */
4065     LIST_FOR_EACH (bucket, list_node, &group->up.buckets) {
4066         const struct ofpact *a;
4067
4068         OFPACT_FOR_EACH (a, bucket->ofpacts, bucket->ofpacts_len) {
4069             if (a->type == OFPACT_GROUP) {
4070                 return OFPERR_OFPGMFC_CHAINING_UNSUPPORTED;
4071             }
4072         }
4073     }
4074
4075     ovs_mutex_init_adaptive(&group->stats_mutex);
4076     ovs_mutex_lock(&group->stats_mutex);
4077     group_construct_stats(group);
4078     ovs_mutex_unlock(&group->stats_mutex);
4079     return 0;
4080 }
4081
4082 static void
4083 group_destruct(struct ofgroup *group_)
4084 {
4085     struct group_dpif *group = group_dpif_cast(group_);
4086     ovs_mutex_destroy(&group->stats_mutex);
4087 }
4088
4089 static enum ofperr
4090 group_modify(struct ofgroup *group_)
4091 {
4092     struct ofproto_dpif *ofproto = ofproto_dpif_cast(group_->ofproto);
4093
4094     ofproto->backer->need_revalidate = REV_FLOW_TABLE;
4095
4096     return 0;
4097 }
4098
4099 static enum ofperr
4100 group_get_stats(const struct ofgroup *group_, struct ofputil_group_stats *ogs)
4101 {
4102     struct group_dpif *group = group_dpif_cast(group_);
4103     struct ofputil_bucket *bucket;
4104     const struct ovs_list *buckets;
4105     struct bucket_counter *bucket_stats;
4106
4107     ovs_mutex_lock(&group->stats_mutex);
4108     ogs->packet_count = group->packet_count;
4109     ogs->byte_count = group->byte_count;
4110
4111     group_dpif_get_buckets(group, &buckets);
4112     bucket_stats = ogs->bucket_stats;
4113     LIST_FOR_EACH (bucket, list_node, buckets) {
4114         bucket_stats->packet_count = bucket->stats.packet_count;
4115         bucket_stats->byte_count = bucket->stats.byte_count;
4116         bucket_stats++;
4117     }
4118     ovs_mutex_unlock(&group->stats_mutex);
4119
4120     return 0;
4121 }
4122
4123 /* If the group exists, this function increments the groups's reference count.
4124  *
4125  * Make sure to call group_dpif_unref() after no longer needing to maintain
4126  * a reference to the group. */
4127 bool
4128 group_dpif_lookup(struct ofproto_dpif *ofproto, uint32_t group_id,
4129                   struct group_dpif **group)
4130 {
4131     struct ofgroup *ofgroup;
4132     bool found;
4133
4134     found = ofproto_group_lookup(&ofproto->up, group_id, &ofgroup);
4135     *group = found ?  group_dpif_cast(ofgroup) : NULL;
4136
4137     return found;
4138 }
4139
4140 void
4141 group_dpif_get_buckets(const struct group_dpif *group,
4142                        const struct ovs_list **buckets)
4143 {
4144     *buckets = &group->up.buckets;
4145 }
4146
4147 enum ofp11_group_type
4148 group_dpif_get_type(const struct group_dpif *group)
4149 {
4150     return group->up.type;
4151 }
4152
4153 const char *
4154 group_dpif_get_selection_method(const struct group_dpif *group)
4155 {
4156     return group->up.props.selection_method;
4157 }
4158 \f
4159 /* Sends 'packet' out 'ofport'.
4160  * May modify 'packet'.
4161  * Returns 0 if successful, otherwise a positive errno value. */
4162 int
4163 ofproto_dpif_send_packet(const struct ofport_dpif *ofport, struct dp_packet *packet)
4164 {
4165     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
4166     int error;
4167
4168     error = xlate_send_packet(ofport, packet);
4169
4170     ovs_mutex_lock(&ofproto->stats_mutex);
4171     ofproto->stats.tx_packets++;
4172     ofproto->stats.tx_bytes += dp_packet_size(packet);
4173     ovs_mutex_unlock(&ofproto->stats_mutex);
4174     return error;
4175 }
4176
4177 uint64_t
4178 group_dpif_get_selection_method_param(const struct group_dpif *group)
4179 {
4180     return group->up.props.selection_method_param;
4181 }
4182
4183 const struct field_array *
4184 group_dpif_get_fields(const struct group_dpif *group)
4185 {
4186     return &group->up.props.fields;
4187 }
4188 \f
4189 /* Return the version string of the datapath that backs up
4190  * this 'ofproto'.
4191  */
4192 static const char *
4193 get_datapath_version(const struct ofproto *ofproto_)
4194 {
4195     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4196
4197     return ofproto->backer->dp_version_string;
4198 }
4199
4200 static bool
4201 set_frag_handling(struct ofproto *ofproto_,
4202                   enum ofp_config_flags frag_handling)
4203 {
4204     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4205     if (frag_handling != OFPC_FRAG_REASM) {
4206         ofproto->backer->need_revalidate = REV_RECONFIGURE;
4207         return true;
4208     } else {
4209         return false;
4210     }
4211 }
4212
4213 static enum ofperr
4214 packet_out(struct ofproto *ofproto_, struct dp_packet *packet,
4215            const struct flow *flow,
4216            const struct ofpact *ofpacts, size_t ofpacts_len)
4217 {
4218     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4219
4220     ofproto_dpif_execute_actions(ofproto, flow, NULL, ofpacts,
4221                                  ofpacts_len, packet);
4222     return 0;
4223 }
4224 \f
4225 /* NetFlow. */
4226
4227 static int
4228 set_netflow(struct ofproto *ofproto_,
4229             const struct netflow_options *netflow_options)
4230 {
4231     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4232
4233     if (netflow_options) {
4234         if (!ofproto->netflow) {
4235             ofproto->netflow = netflow_create();
4236             ofproto->backer->need_revalidate = REV_RECONFIGURE;
4237         }
4238         return netflow_set_options(ofproto->netflow, netflow_options);
4239     } else if (ofproto->netflow) {
4240         ofproto->backer->need_revalidate = REV_RECONFIGURE;
4241         netflow_unref(ofproto->netflow);
4242         ofproto->netflow = NULL;
4243     }
4244
4245     return 0;
4246 }
4247
4248 static void
4249 get_netflow_ids(const struct ofproto *ofproto_,
4250                 uint8_t *engine_type, uint8_t *engine_id)
4251 {
4252     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
4253
4254     dpif_get_netflow_ids(ofproto->backer->dpif, engine_type, engine_id);
4255 }
4256 \f
4257 static struct ofproto_dpif *
4258 ofproto_dpif_lookup(const char *name)
4259 {
4260     struct ofproto_dpif *ofproto;
4261
4262     HMAP_FOR_EACH_WITH_HASH (ofproto, all_ofproto_dpifs_node,
4263                              hash_string(name, 0), &all_ofproto_dpifs) {
4264         if (!strcmp(ofproto->up.name, name)) {
4265             return ofproto;
4266         }
4267     }
4268     return NULL;
4269 }
4270
4271 static void
4272 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn, int argc,
4273                           const char *argv[], void *aux OVS_UNUSED)
4274 {
4275     struct ofproto_dpif *ofproto;
4276
4277     if (argc > 1) {
4278         ofproto = ofproto_dpif_lookup(argv[1]);
4279         if (!ofproto) {
4280             unixctl_command_reply_error(conn, "no such bridge");
4281             return;
4282         }
4283         ovs_rwlock_wrlock(&ofproto->ml->rwlock);
4284         mac_learning_flush(ofproto->ml);
4285         ovs_rwlock_unlock(&ofproto->ml->rwlock);
4286     } else {
4287         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4288             ovs_rwlock_wrlock(&ofproto->ml->rwlock);
4289             mac_learning_flush(ofproto->ml);
4290             ovs_rwlock_unlock(&ofproto->ml->rwlock);
4291         }
4292     }
4293
4294     unixctl_command_reply(conn, "table successfully flushed");
4295 }
4296
4297 static void
4298 ofproto_unixctl_mcast_snooping_flush(struct unixctl_conn *conn, int argc,
4299                                      const char *argv[], void *aux OVS_UNUSED)
4300 {
4301     struct ofproto_dpif *ofproto;
4302
4303     if (argc > 1) {
4304         ofproto = ofproto_dpif_lookup(argv[1]);
4305         if (!ofproto) {
4306             unixctl_command_reply_error(conn, "no such bridge");
4307             return;
4308         }
4309
4310         if (!mcast_snooping_enabled(ofproto->ms)) {
4311             unixctl_command_reply_error(conn, "multicast snooping is disabled");
4312             return;
4313         }
4314         mcast_snooping_mdb_flush(ofproto->ms);
4315     } else {
4316         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4317             if (!mcast_snooping_enabled(ofproto->ms)) {
4318                 continue;
4319             }
4320             mcast_snooping_mdb_flush(ofproto->ms);
4321         }
4322     }
4323
4324     unixctl_command_reply(conn, "table successfully flushed");
4325 }
4326
4327 static struct ofport_dpif *
4328 ofbundle_get_a_port(const struct ofbundle *bundle)
4329 {
4330     return CONTAINER_OF(list_front(&bundle->ports), struct ofport_dpif,
4331                         bundle_node);
4332 }
4333
4334 static void
4335 ofproto_unixctl_fdb_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
4336                          const char *argv[], void *aux OVS_UNUSED)
4337 {
4338     struct ds ds = DS_EMPTY_INITIALIZER;
4339     const struct ofproto_dpif *ofproto;
4340     const struct mac_entry *e;
4341
4342     ofproto = ofproto_dpif_lookup(argv[1]);
4343     if (!ofproto) {
4344         unixctl_command_reply_error(conn, "no such bridge");
4345         return;
4346     }
4347
4348     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
4349     ovs_rwlock_rdlock(&ofproto->ml->rwlock);
4350     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
4351         struct ofbundle *bundle = mac_entry_get_port(ofproto->ml, e);
4352         char name[OFP_MAX_PORT_NAME_LEN];
4353
4354         ofputil_port_to_string(ofbundle_get_a_port(bundle)->up.ofp_port,
4355                                name, sizeof name);
4356         ds_put_format(&ds, "%5s  %4d  "ETH_ADDR_FMT"  %3d\n",
4357                       name, e->vlan, ETH_ADDR_ARGS(e->mac),
4358                       mac_entry_age(ofproto->ml, e));
4359     }
4360     ovs_rwlock_unlock(&ofproto->ml->rwlock);
4361     unixctl_command_reply(conn, ds_cstr(&ds));
4362     ds_destroy(&ds);
4363 }
4364
4365 static void
4366 ofproto_unixctl_mcast_snooping_show(struct unixctl_conn *conn,
4367                                     int argc OVS_UNUSED,
4368                                     const char *argv[],
4369                                     void *aux OVS_UNUSED)
4370 {
4371     struct ds ds = DS_EMPTY_INITIALIZER;
4372     const struct ofproto_dpif *ofproto;
4373     const struct ofbundle *bundle;
4374     const struct mcast_group *grp;
4375     struct mcast_group_bundle *b;
4376     struct mcast_mrouter_bundle *mrouter;
4377
4378     ofproto = ofproto_dpif_lookup(argv[1]);
4379     if (!ofproto) {
4380         unixctl_command_reply_error(conn, "no such bridge");
4381         return;
4382     }
4383
4384     if (!mcast_snooping_enabled(ofproto->ms)) {
4385         unixctl_command_reply_error(conn, "multicast snooping is disabled");
4386         return;
4387     }
4388
4389     ds_put_cstr(&ds, " port  VLAN  GROUP                Age\n");
4390     ovs_rwlock_rdlock(&ofproto->ms->rwlock);
4391     LIST_FOR_EACH (grp, group_node, &ofproto->ms->group_lru) {
4392         LIST_FOR_EACH(b, bundle_node, &grp->bundle_lru) {
4393             char name[OFP_MAX_PORT_NAME_LEN];
4394
4395             bundle = b->port;
4396             ofputil_port_to_string(ofbundle_get_a_port(bundle)->up.ofp_port,
4397                                    name, sizeof name);
4398             ds_put_format(&ds, "%5s  %4d  "IP_FMT"         %3d\n",
4399                           name, grp->vlan, IP_ARGS(grp->ip4),
4400                           mcast_bundle_age(ofproto->ms, b));
4401         }
4402     }
4403
4404     /* ports connected to multicast routers */
4405     LIST_FOR_EACH(mrouter, mrouter_node, &ofproto->ms->mrouter_lru) {
4406         char name[OFP_MAX_PORT_NAME_LEN];
4407
4408         bundle = mrouter->port;
4409         ofputil_port_to_string(ofbundle_get_a_port(bundle)->up.ofp_port,
4410                                name, sizeof name);
4411             ds_put_format(&ds, "%5s  %4d  querier             %3d\n",
4412                       name, mrouter->vlan,
4413                       mcast_mrouter_age(ofproto->ms, mrouter));
4414     }
4415     ovs_rwlock_unlock(&ofproto->ms->rwlock);
4416     unixctl_command_reply(conn, ds_cstr(&ds));
4417     ds_destroy(&ds);
4418 }
4419
4420 struct trace_ctx {
4421     struct xlate_out xout;
4422     struct xlate_in xin;
4423     const struct flow *key;
4424     struct flow flow;
4425     struct flow_wildcards wc;
4426     struct ds *result;
4427 };
4428
4429 static void
4430 trace_format_rule(struct ds *result, int level, const struct rule_dpif *rule)
4431 {
4432     const struct rule_actions *actions;
4433     ovs_be64 cookie;
4434
4435     ds_put_char_multiple(result, '\t', level);
4436     if (!rule) {
4437         ds_put_cstr(result, "No match\n");
4438         return;
4439     }
4440
4441     ovs_mutex_lock(&rule->up.mutex);
4442     cookie = rule->up.flow_cookie;
4443     ovs_mutex_unlock(&rule->up.mutex);
4444
4445     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
4446                   rule ? rule->up.table_id : 0, ntohll(cookie));
4447     cls_rule_format(&rule->up.cr, result);
4448     ds_put_char(result, '\n');
4449
4450     actions = rule_dpif_get_actions(rule);
4451
4452     ds_put_char_multiple(result, '\t', level);
4453     ds_put_cstr(result, "OpenFlow actions=");
4454     ofpacts_format(actions->ofpacts, actions->ofpacts_len, result);
4455     ds_put_char(result, '\n');
4456 }
4457
4458 static void
4459 trace_format_flow(struct ds *result, int level, const char *title,
4460                   struct trace_ctx *trace)
4461 {
4462     ds_put_char_multiple(result, '\t', level);
4463     ds_put_format(result, "%s: ", title);
4464     /* Do not report unchanged flows for resubmits. */
4465     if ((level > 0 && flow_equal(&trace->xin.flow, &trace->flow))
4466         || (level == 0 && flow_equal(&trace->xin.flow, trace->key))) {
4467         ds_put_cstr(result, "unchanged");
4468     } else {
4469         flow_format(result, &trace->xin.flow);
4470         trace->flow = trace->xin.flow;
4471     }
4472     ds_put_char(result, '\n');
4473 }
4474
4475 static void
4476 trace_format_regs(struct ds *result, int level, const char *title,
4477                   struct trace_ctx *trace)
4478 {
4479     size_t i;
4480
4481     ds_put_char_multiple(result, '\t', level);
4482     ds_put_format(result, "%s:", title);
4483     for (i = 0; i < FLOW_N_REGS; i++) {
4484         ds_put_format(result, " reg%"PRIuSIZE"=0x%"PRIx32, i, trace->flow.regs[i]);
4485     }
4486     ds_put_char(result, '\n');
4487 }
4488
4489 static void
4490 trace_format_odp(struct ds *result, int level, const char *title,
4491                  struct trace_ctx *trace)
4492 {
4493     struct ofpbuf *odp_actions = trace->xout.odp_actions;
4494
4495     ds_put_char_multiple(result, '\t', level);
4496     ds_put_format(result, "%s: ", title);
4497     format_odp_actions(result, odp_actions->data, odp_actions->size);
4498     ds_put_char(result, '\n');
4499 }
4500
4501 static void
4502 trace_format_megaflow(struct ds *result, int level, const char *title,
4503                       struct trace_ctx *trace)
4504 {
4505     struct match match;
4506
4507     ds_put_char_multiple(result, '\t', level);
4508     ds_put_format(result, "%s: ", title);
4509     flow_wildcards_or(&trace->wc, &trace->xout.wc, &trace->wc);
4510     match_init(&match, trace->key, &trace->wc);
4511     match_format(&match, result, OFP_DEFAULT_PRIORITY);
4512     ds_put_char(result, '\n');
4513 }
4514
4515 static void trace_report(struct xlate_in *xin, const char *s, int recurse);
4516
4517 static void
4518 trace_resubmit(struct xlate_in *xin, struct rule_dpif *rule, int recurse)
4519 {
4520     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
4521     struct ds *result = trace->result;
4522
4523     if (!recurse) {
4524         if (rule == xin->ofproto->miss_rule) {
4525             trace_report(xin, "No match, flow generates \"packet in\"s.",
4526                          recurse);
4527         } else if (rule == xin->ofproto->no_packet_in_rule) {
4528             trace_report(xin, "No match, packets dropped because "
4529                          "OFPPC_NO_PACKET_IN is set on in_port.", recurse);
4530         } else if (rule == xin->ofproto->drop_frags_rule) {
4531             trace_report(xin, "Packets dropped because they are IP "
4532                          "fragments and the fragment handling mode is "
4533                          "\"drop\".", recurse);
4534         }
4535     }
4536
4537     ds_put_char(result, '\n');
4538     if (recurse) {
4539         trace_format_flow(result, recurse, "Resubmitted flow", trace);
4540         trace_format_regs(result, recurse, "Resubmitted regs", trace);
4541         trace_format_odp(result,  recurse, "Resubmitted  odp", trace);
4542         trace_format_megaflow(result, recurse, "Resubmitted megaflow", trace);
4543     }
4544     trace_format_rule(result, recurse, rule);
4545 }
4546
4547 static void
4548 trace_report(struct xlate_in *xin, const char *s, int recurse)
4549 {
4550     struct trace_ctx *trace = CONTAINER_OF(xin, struct trace_ctx, xin);
4551     struct ds *result = trace->result;
4552
4553     ds_put_char_multiple(result, '\t', recurse);
4554     ds_put_cstr(result, s);
4555     ds_put_char(result, '\n');
4556 }
4557
4558 /* Parses the 'argc' elements of 'argv', ignoring argv[0].  The following
4559  * forms are supported:
4560  *
4561  *     - [dpname] odp_flow [-generate | packet]
4562  *     - bridge br_flow [-generate | packet]
4563  *
4564  * On success, initializes '*ofprotop' and 'flow' and returns NULL.  On failure
4565  * returns a nonnull malloced error message. */
4566 static char * OVS_WARN_UNUSED_RESULT
4567 parse_flow_and_packet(int argc, const char *argv[],
4568                       struct ofproto_dpif **ofprotop, struct flow *flow,
4569                       struct dp_packet **packetp)
4570 {
4571     const struct dpif_backer *backer = NULL;
4572     const char *error = NULL;
4573     char *m_err = NULL;
4574     struct simap port_names = SIMAP_INITIALIZER(&port_names);
4575     struct dp_packet *packet;
4576     struct ofpbuf odp_key;
4577     struct ofpbuf odp_mask;
4578
4579     ofpbuf_init(&odp_key, 0);
4580     ofpbuf_init(&odp_mask, 0);
4581
4582     /* Handle "-generate" or a hex string as the last argument. */
4583     if (!strcmp(argv[argc - 1], "-generate")) {
4584         packet = dp_packet_new(0);
4585         argc--;
4586     } else {
4587         error = eth_from_hex(argv[argc - 1], &packet);
4588         if (!error) {
4589             argc--;
4590         } else if (argc == 4) {
4591             /* The 3-argument form must end in "-generate' or a hex string. */
4592             goto exit;
4593         }
4594         error = NULL;
4595     }
4596
4597     /* odp_flow can have its in_port specified as a name instead of port no.
4598      * We do not yet know whether a given flow is a odp_flow or a br_flow.
4599      * But, to know whether a flow is odp_flow through odp_flow_from_string(),
4600      * we need to create a simap of name to port no. */
4601     if (argc == 3) {
4602         const char *dp_type;
4603         if (!strncmp(argv[1], "ovs-", 4)) {
4604             dp_type = argv[1] + 4;
4605         } else {
4606             dp_type = argv[1];
4607         }
4608         backer = shash_find_data(&all_dpif_backers, dp_type);
4609     } else if (argc == 2) {
4610         struct shash_node *node;
4611         if (shash_count(&all_dpif_backers) == 1) {
4612             node = shash_first(&all_dpif_backers);
4613             backer = node->data;
4614         }
4615     } else {
4616         error = "Syntax error";
4617         goto exit;
4618     }
4619     if (backer && backer->dpif) {
4620         struct dpif_port dpif_port;
4621         struct dpif_port_dump port_dump;
4622         DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, backer->dpif) {
4623             simap_put(&port_names, dpif_port.name,
4624                       odp_to_u32(dpif_port.port_no));
4625         }
4626     }
4627
4628     /* Parse the flow and determine whether a datapath or
4629      * bridge is specified. If function odp_flow_key_from_string()
4630      * returns 0, the flow is a odp_flow. If function
4631      * parse_ofp_exact_flow() returns NULL, the flow is a br_flow. */
4632     if (!odp_flow_from_string(argv[argc - 1], &port_names,
4633                               &odp_key, &odp_mask)) {
4634         if (!backer) {
4635             error = "Cannot find the datapath";
4636             goto exit;
4637         }
4638
4639         if (odp_flow_key_to_flow(odp_key.data, odp_key.size, flow) == ODP_FIT_ERROR) {
4640             error = "Failed to parse flow key";
4641             goto exit;
4642         }
4643
4644         *ofprotop = xlate_lookup_ofproto(backer, flow,
4645                                          &flow->in_port.ofp_port);
4646         if (*ofprotop == NULL) {
4647             error = "Invalid datapath flow";
4648             goto exit;
4649         }
4650
4651         vsp_adjust_flow(*ofprotop, flow, NULL);
4652
4653     } else {
4654         char *err = parse_ofp_exact_flow(flow, NULL, argv[argc - 1], NULL);
4655
4656         if (err) {
4657             m_err = xasprintf("Bad flow syntax: %s", err);
4658             free(err);
4659             goto exit;
4660         } else {
4661             if (argc != 3) {
4662                 error = "Must specify bridge name";
4663                 goto exit;
4664             }
4665
4666             *ofprotop = ofproto_dpif_lookup(argv[1]);
4667             if (!*ofprotop) {
4668                 error = "Unknown bridge name";
4669                 goto exit;
4670             }
4671         }
4672     }
4673
4674     /* Generate a packet, if requested. */
4675     if (packet) {
4676         if (!dp_packet_size(packet)) {
4677             flow_compose(packet, flow);
4678         } else {
4679             /* Use the metadata from the flow and the packet argument
4680              * to reconstruct the flow. */
4681             pkt_metadata_from_flow(&packet->md, flow);
4682             flow_extract(packet, flow);
4683         }
4684     }
4685
4686 exit:
4687     if (error && !m_err) {
4688         m_err = xstrdup(error);
4689     }
4690     if (m_err) {
4691         dp_packet_delete(packet);
4692         packet = NULL;
4693     }
4694     *packetp = packet;
4695     ofpbuf_uninit(&odp_key);
4696     ofpbuf_uninit(&odp_mask);
4697     simap_destroy(&port_names);
4698     return m_err;
4699 }
4700
4701 static void
4702 ofproto_unixctl_trace(struct unixctl_conn *conn, int argc, const char *argv[],
4703                       void *aux OVS_UNUSED)
4704 {
4705     struct ofproto_dpif *ofproto;
4706     struct dp_packet *packet;
4707     char *error;
4708     struct flow flow;
4709
4710     error = parse_flow_and_packet(argc, argv, &ofproto, &flow, &packet);
4711     if (!error) {
4712         struct ds result;
4713
4714         ds_init(&result);
4715         ofproto_trace(ofproto, &flow, packet, NULL, 0, &result);
4716         unixctl_command_reply(conn, ds_cstr(&result));
4717         ds_destroy(&result);
4718         dp_packet_delete(packet);
4719     } else {
4720         unixctl_command_reply_error(conn, error);
4721         free(error);
4722     }
4723 }
4724
4725 static void
4726 ofproto_unixctl_trace_actions(struct unixctl_conn *conn, int argc,
4727                               const char *argv[], void *aux OVS_UNUSED)
4728 {
4729     enum ofputil_protocol usable_protocols;
4730     struct ofproto_dpif *ofproto;
4731     bool enforce_consistency;
4732     struct ofpbuf ofpacts;
4733     struct dp_packet *packet;
4734     struct ds result;
4735     struct flow flow;
4736     uint16_t in_port;
4737
4738     /* Three kinds of error return values! */
4739     enum ofperr retval;
4740     char *error;
4741
4742     packet = NULL;
4743     ds_init(&result);
4744     ofpbuf_init(&ofpacts, 0);
4745
4746     /* Parse actions. */
4747     error = ofpacts_parse_actions(argv[--argc], &ofpacts, &usable_protocols);
4748     if (error) {
4749         unixctl_command_reply_error(conn, error);
4750         free(error);
4751         goto exit;
4752     }
4753
4754     /* OpenFlow 1.1 and later suggest that the switch enforces certain forms of
4755      * consistency between the flow and the actions.  With -consistent, we
4756      * enforce consistency even for a flow supported in OpenFlow 1.0. */
4757     if (!strcmp(argv[1], "-consistent")) {
4758         enforce_consistency = true;
4759         argv++;
4760         argc--;
4761     } else {
4762         enforce_consistency = false;
4763     }
4764
4765     error = parse_flow_and_packet(argc, argv, &ofproto, &flow, &packet);
4766     if (error) {
4767         unixctl_command_reply_error(conn, error);
4768         free(error);
4769         goto exit;
4770     }
4771
4772     /* Do the same checks as handle_packet_out() in ofproto.c.
4773      *
4774      * We pass a 'table_id' of 0 to ofpacts_check(), which isn't
4775      * strictly correct because these actions aren't in any table, but it's OK
4776      * because it 'table_id' is used only to check goto_table instructions, but
4777      * packet-outs take a list of actions and therefore it can't include
4778      * instructions.
4779      *
4780      * We skip the "meter" check here because meter is an instruction, not an
4781      * action, and thus cannot appear in ofpacts. */
4782     in_port = ofp_to_u16(flow.in_port.ofp_port);
4783     if (in_port >= ofproto->up.max_ports && in_port < ofp_to_u16(OFPP_MAX)) {
4784         unixctl_command_reply_error(conn, "invalid in_port");
4785         goto exit;
4786     }
4787     if (enforce_consistency) {
4788         retval = ofpacts_check_consistency(ofpacts.data, ofpacts.size,
4789                                            &flow, u16_to_ofp(ofproto->up.max_ports),
4790                                            0, 0, usable_protocols);
4791     } else {
4792         retval = ofpacts_check(ofpacts.data, ofpacts.size, &flow,
4793                                u16_to_ofp(ofproto->up.max_ports), 0, 0,
4794                                &usable_protocols);
4795     }
4796
4797     if (retval) {
4798         ds_clear(&result);
4799         ds_put_format(&result, "Bad actions: %s", ofperr_to_string(retval));
4800         unixctl_command_reply_error(conn, ds_cstr(&result));
4801         goto exit;
4802     }
4803
4804     ofproto_trace(ofproto, &flow, packet,
4805                   ofpacts.data, ofpacts.size, &result);
4806     unixctl_command_reply(conn, ds_cstr(&result));
4807
4808 exit:
4809     ds_destroy(&result);
4810     dp_packet_delete(packet);
4811     ofpbuf_uninit(&ofpacts);
4812 }
4813
4814 /* Implements a "trace" through 'ofproto''s flow table, appending a textual
4815  * description of the results to 'ds'.
4816  *
4817  * The trace follows a packet with the specified 'flow' through the flow
4818  * table.  'packet' may be nonnull to trace an actual packet, with consequent
4819  * side effects (if it is nonnull then its flow must be 'flow').
4820  *
4821  * If 'ofpacts' is nonnull then its 'ofpacts_len' bytes specify the actions to
4822  * trace, otherwise the actions are determined by a flow table lookup. */
4823 static void
4824 ofproto_trace(struct ofproto_dpif *ofproto, struct flow *flow,
4825               const struct dp_packet *packet,
4826               const struct ofpact ofpacts[], size_t ofpacts_len,
4827               struct ds *ds)
4828 {
4829     struct trace_ctx trace;
4830
4831     ds_put_format(ds, "Bridge: %s\n", ofproto->up.name);
4832     ds_put_cstr(ds, "Flow: ");
4833     flow_format(ds, flow);
4834     ds_put_char(ds, '\n');
4835
4836     flow_wildcards_init_catchall(&trace.wc);
4837
4838     trace.result = ds;
4839     trace.key = flow; /* Original flow key, used for megaflow. */
4840     trace.flow = *flow; /* May be modified by actions. */
4841     xlate_in_init(&trace.xin, ofproto, flow, flow->in_port.ofp_port, NULL,
4842                   ntohs(flow->tcp_flags), packet);
4843     trace.xin.ofpacts = ofpacts;
4844     trace.xin.ofpacts_len = ofpacts_len;
4845     trace.xin.resubmit_hook = trace_resubmit;
4846     trace.xin.report_hook = trace_report;
4847
4848     xlate_actions(&trace.xin, &trace.xout);
4849
4850     ds_put_char(ds, '\n');
4851     trace_format_flow(ds, 0, "Final flow", &trace);
4852     trace_format_megaflow(ds, 0, "Megaflow", &trace);
4853
4854     ds_put_cstr(ds, "Datapath actions: ");
4855     format_odp_actions(ds, trace.xout.odp_actions->data,
4856                        trace.xout.odp_actions->size);
4857
4858     if (trace.xout.slow) {
4859         enum slow_path_reason slow;
4860
4861         ds_put_cstr(ds, "\nThis flow is handled by the userspace "
4862                     "slow path because it:");
4863
4864         slow = trace.xout.slow;
4865         while (slow) {
4866             enum slow_path_reason bit = rightmost_1bit(slow);
4867
4868             ds_put_format(ds, "\n\t- %s.",
4869                           slow_path_reason_to_explanation(bit));
4870
4871             slow &= ~bit;
4872         }
4873     }
4874
4875     xlate_out_uninit(&trace.xout);
4876 }
4877
4878 /* Store the current ofprotos in 'ofproto_shash'.  Returns a sorted list
4879  * of the 'ofproto_shash' nodes.  It is the responsibility of the caller
4880  * to destroy 'ofproto_shash' and free the returned value. */
4881 static const struct shash_node **
4882 get_ofprotos(struct shash *ofproto_shash)
4883 {
4884     const struct ofproto_dpif *ofproto;
4885
4886     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4887         char *name = xasprintf("%s@%s", ofproto->up.type, ofproto->up.name);
4888         shash_add_nocopy(ofproto_shash, name, ofproto);
4889     }
4890
4891     return shash_sort(ofproto_shash);
4892 }
4893
4894 static void
4895 ofproto_unixctl_dpif_dump_dps(struct unixctl_conn *conn, int argc OVS_UNUSED,
4896                               const char *argv[] OVS_UNUSED,
4897                               void *aux OVS_UNUSED)
4898 {
4899     struct ds ds = DS_EMPTY_INITIALIZER;
4900     struct shash ofproto_shash;
4901     const struct shash_node **sorted_ofprotos;
4902     int i;
4903
4904     shash_init(&ofproto_shash);
4905     sorted_ofprotos = get_ofprotos(&ofproto_shash);
4906     for (i = 0; i < shash_count(&ofproto_shash); i++) {
4907         const struct shash_node *node = sorted_ofprotos[i];
4908         ds_put_format(&ds, "%s\n", node->name);
4909     }
4910
4911     shash_destroy(&ofproto_shash);
4912     free(sorted_ofprotos);
4913
4914     unixctl_command_reply(conn, ds_cstr(&ds));
4915     ds_destroy(&ds);
4916 }
4917
4918 static void
4919 dpif_show_backer(const struct dpif_backer *backer, struct ds *ds)
4920 {
4921     const struct shash_node **ofprotos;
4922     struct dpif_dp_stats dp_stats;
4923     struct shash ofproto_shash;
4924     size_t i;
4925
4926     dpif_get_dp_stats(backer->dpif, &dp_stats);
4927
4928     ds_put_format(ds, "%s: hit:%"PRIu64" missed:%"PRIu64"\n",
4929                   dpif_name(backer->dpif), dp_stats.n_hit, dp_stats.n_missed);
4930
4931     shash_init(&ofproto_shash);
4932     ofprotos = get_ofprotos(&ofproto_shash);
4933     for (i = 0; i < shash_count(&ofproto_shash); i++) {
4934         struct ofproto_dpif *ofproto = ofprotos[i]->data;
4935         const struct shash_node **ports;
4936         size_t j;
4937
4938         if (ofproto->backer != backer) {
4939             continue;
4940         }
4941
4942         ds_put_format(ds, "\t%s:\n", ofproto->up.name);
4943
4944         ports = shash_sort(&ofproto->up.port_by_name);
4945         for (j = 0; j < shash_count(&ofproto->up.port_by_name); j++) {
4946             const struct shash_node *node = ports[j];
4947             struct ofport *ofport = node->data;
4948             struct smap config;
4949             odp_port_t odp_port;
4950
4951             ds_put_format(ds, "\t\t%s %u/", netdev_get_name(ofport->netdev),
4952                           ofport->ofp_port);
4953
4954             odp_port = ofp_port_to_odp_port(ofproto, ofport->ofp_port);
4955             if (odp_port != ODPP_NONE) {
4956                 ds_put_format(ds, "%"PRIu32":", odp_port);
4957             } else {
4958                 ds_put_cstr(ds, "none:");
4959             }
4960
4961             ds_put_format(ds, " (%s", netdev_get_type(ofport->netdev));
4962
4963             smap_init(&config);
4964             if (!netdev_get_config(ofport->netdev, &config)) {
4965                 const struct smap_node **nodes;
4966                 size_t i;
4967
4968                 nodes = smap_sort(&config);
4969                 for (i = 0; i < smap_count(&config); i++) {
4970                     const struct smap_node *node = nodes[i];
4971                     ds_put_format(ds, "%c %s=%s", i ? ',' : ':',
4972                                   node->key, node->value);
4973                 }
4974                 free(nodes);
4975             }
4976             smap_destroy(&config);
4977
4978             ds_put_char(ds, ')');
4979             ds_put_char(ds, '\n');
4980         }
4981         free(ports);
4982     }
4983     shash_destroy(&ofproto_shash);
4984     free(ofprotos);
4985 }
4986
4987 static void
4988 ofproto_unixctl_dpif_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
4989                           const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
4990 {
4991     struct ds ds = DS_EMPTY_INITIALIZER;
4992     const struct shash_node **backers;
4993     int i;
4994
4995     backers = shash_sort(&all_dpif_backers);
4996     for (i = 0; i < shash_count(&all_dpif_backers); i++) {
4997         dpif_show_backer(backers[i]->data, &ds);
4998     }
4999     free(backers);
5000
5001     unixctl_command_reply(conn, ds_cstr(&ds));
5002     ds_destroy(&ds);
5003 }
5004
5005 static void
5006 ofproto_unixctl_dpif_dump_flows(struct unixctl_conn *conn,
5007                                 int argc OVS_UNUSED, const char *argv[],
5008                                 void *aux OVS_UNUSED)
5009 {
5010     const struct ofproto_dpif *ofproto;
5011
5012     struct ds ds = DS_EMPTY_INITIALIZER;
5013     bool verbosity = false;
5014
5015     struct dpif_port dpif_port;
5016     struct dpif_port_dump port_dump;
5017     struct hmap portno_names;
5018
5019     struct dpif_flow_dump *flow_dump;
5020     struct dpif_flow_dump_thread *flow_dump_thread;
5021     struct dpif_flow f;
5022     int error;
5023
5024     ofproto = ofproto_dpif_lookup(argv[argc - 1]);
5025     if (!ofproto) {
5026         unixctl_command_reply_error(conn, "no such bridge");
5027         return;
5028     }
5029
5030     if (argc > 2 && !strcmp(argv[1], "-m")) {
5031         verbosity = true;
5032     }
5033
5034     hmap_init(&portno_names);
5035     DPIF_PORT_FOR_EACH (&dpif_port, &port_dump, ofproto->backer->dpif) {
5036         odp_portno_names_set(&portno_names, dpif_port.port_no, dpif_port.name);
5037     }
5038
5039     ds_init(&ds);
5040     flow_dump = dpif_flow_dump_create(ofproto->backer->dpif, false);
5041     flow_dump_thread = dpif_flow_dump_thread_create(flow_dump);
5042     while (dpif_flow_dump_next(flow_dump_thread, &f, 1)) {
5043         struct flow flow;
5044
5045         if (odp_flow_key_to_flow(f.key, f.key_len, &flow) == ODP_FIT_ERROR
5046             || xlate_lookup_ofproto(ofproto->backer, &flow, NULL) != ofproto) {
5047             continue;
5048         }
5049
5050         if (verbosity) {
5051             odp_format_ufid(&f.ufid, &ds);
5052             ds_put_cstr(&ds, " ");
5053         }
5054         odp_flow_format(f.key, f.key_len, f.mask, f.mask_len,
5055                         &portno_names, &ds, verbosity);
5056         ds_put_cstr(&ds, ", ");
5057         dpif_flow_stats_format(&f.stats, &ds);
5058         ds_put_cstr(&ds, ", actions:");
5059         format_odp_actions(&ds, f.actions, f.actions_len);
5060         ds_put_char(&ds, '\n');
5061     }
5062     dpif_flow_dump_thread_destroy(flow_dump_thread);
5063     error = dpif_flow_dump_destroy(flow_dump);
5064
5065     if (error) {
5066         ds_clear(&ds);
5067         ds_put_format(&ds, "dpif/dump_flows failed: %s", ovs_strerror(errno));
5068         unixctl_command_reply_error(conn, ds_cstr(&ds));
5069     } else {
5070         unixctl_command_reply(conn, ds_cstr(&ds));
5071     }
5072     odp_portno_names_destroy(&portno_names);
5073     hmap_destroy(&portno_names);
5074     ds_destroy(&ds);
5075 }
5076
5077 static void
5078 ofproto_revalidate_all_backers(void)
5079 {
5080     const struct shash_node **backers;
5081     int i;
5082
5083     backers = shash_sort(&all_dpif_backers);
5084     for (i = 0; i < shash_count(&all_dpif_backers); i++) {
5085         struct dpif_backer *backer = backers[i]->data;
5086         backer->need_revalidate = REV_RECONFIGURE;
5087     }
5088     free(backers);
5089 }
5090
5091 static void
5092 disable_tnl_push_pop(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
5093                      const char *argv[], void *aux OVS_UNUSED)
5094 {
5095     if (!strcasecmp(argv[1], "off")) {
5096         ofproto_use_tnl_push_pop = false;
5097         unixctl_command_reply(conn, "Tunnel push-pop off");
5098         ofproto_revalidate_all_backers();
5099     } else if (!strcasecmp(argv[1], "on")) {
5100         ofproto_use_tnl_push_pop = true;
5101         unixctl_command_reply(conn, "Tunnel push-pop on");
5102         ofproto_revalidate_all_backers();
5103     }
5104 }
5105
5106 static void
5107 ofproto_unixctl_init(void)
5108 {
5109     static bool registered;
5110     if (registered) {
5111         return;
5112     }
5113     registered = true;
5114
5115     unixctl_command_register(
5116         "ofproto/trace",
5117         "{[dp_name] odp_flow | bridge br_flow} [-generate|packet]",
5118         1, 3, ofproto_unixctl_trace, NULL);
5119     unixctl_command_register(
5120         "ofproto/trace-packet-out",
5121         "[-consistent] {[dp_name] odp_flow | bridge br_flow} [-generate|packet] actions",
5122         2, 6, ofproto_unixctl_trace_actions, NULL);
5123     unixctl_command_register("fdb/flush", "[bridge]", 0, 1,
5124                              ofproto_unixctl_fdb_flush, NULL);
5125     unixctl_command_register("fdb/show", "bridge", 1, 1,
5126                              ofproto_unixctl_fdb_show, NULL);
5127     unixctl_command_register("mdb/flush", "[bridge]", 0, 1,
5128                              ofproto_unixctl_mcast_snooping_flush, NULL);
5129     unixctl_command_register("mdb/show", "bridge", 1, 1,
5130                              ofproto_unixctl_mcast_snooping_show, NULL);
5131     unixctl_command_register("dpif/dump-dps", "", 0, 0,
5132                              ofproto_unixctl_dpif_dump_dps, NULL);
5133     unixctl_command_register("dpif/show", "", 0, 0, ofproto_unixctl_dpif_show,
5134                              NULL);
5135     unixctl_command_register("dpif/dump-flows", "[-m] bridge", 1, 2,
5136                              ofproto_unixctl_dpif_dump_flows, NULL);
5137
5138     unixctl_command_register("ofproto/tnl-push-pop", "[on]|[off]", 1, 1,
5139                              disable_tnl_push_pop, NULL);
5140 }
5141
5142 /* Returns true if 'table' is the table used for internal rules,
5143  * false otherwise. */
5144 bool
5145 table_is_internal(uint8_t table_id)
5146 {
5147     return table_id == TBL_INTERNAL;
5148 }
5149 \f
5150 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
5151  *
5152  * This is deprecated.  It is only for compatibility with broken device drivers
5153  * in old versions of Linux that do not properly support VLANs when VLAN
5154  * devices are not used.  When broken device drivers are no longer in
5155  * widespread use, we will delete these interfaces. */
5156
5157 static int
5158 set_realdev(struct ofport *ofport_, ofp_port_t realdev_ofp_port, int vid)
5159 {
5160     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
5161     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
5162
5163     if (realdev_ofp_port == ofport->realdev_ofp_port
5164         && vid == ofport->vlandev_vid) {
5165         return 0;
5166     }
5167
5168     ofproto->backer->need_revalidate = REV_RECONFIGURE;
5169
5170     if (ofport->realdev_ofp_port) {
5171         vsp_remove(ofport);
5172     }
5173     if (realdev_ofp_port && ofport->bundle) {
5174         /* vlandevs are enslaved to their realdevs, so they are not allowed to
5175          * themselves be part of a bundle. */
5176         bundle_set(ofport_->ofproto, ofport->bundle, NULL);
5177     }
5178
5179     ofport->realdev_ofp_port = realdev_ofp_port;
5180     ofport->vlandev_vid = vid;
5181
5182     if (realdev_ofp_port) {
5183         vsp_add(ofport, realdev_ofp_port, vid);
5184     }
5185
5186     return 0;
5187 }
5188
5189 static uint32_t
5190 hash_realdev_vid(ofp_port_t realdev_ofp_port, int vid)
5191 {
5192     return hash_2words(ofp_to_u16(realdev_ofp_port), vid);
5193 }
5194
5195 bool
5196 ofproto_has_vlan_splinters(const struct ofproto_dpif *ofproto)
5197     OVS_EXCLUDED(ofproto->vsp_mutex)
5198 {
5199     /* hmap_is_empty is thread safe. */
5200     return !hmap_is_empty(&ofproto->realdev_vid_map);
5201 }
5202
5203
5204 static ofp_port_t
5205 vsp_realdev_to_vlandev__(const struct ofproto_dpif *ofproto,
5206                          ofp_port_t realdev_ofp_port, ovs_be16 vlan_tci)
5207     OVS_REQUIRES(ofproto->vsp_mutex)
5208 {
5209     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
5210         int vid = vlan_tci_to_vid(vlan_tci);
5211         const struct vlan_splinter *vsp;
5212
5213         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
5214                                  hash_realdev_vid(realdev_ofp_port, vid),
5215                                  &ofproto->realdev_vid_map) {
5216             if (vsp->realdev_ofp_port == realdev_ofp_port
5217                 && vsp->vid == vid) {
5218                 return vsp->vlandev_ofp_port;
5219             }
5220         }
5221     }
5222     return realdev_ofp_port;
5223 }
5224
5225 /* Returns the OFP port number of the Linux VLAN device that corresponds to
5226  * 'vlan_tci' on the network device with port number 'realdev_ofp_port' in
5227  * 'struct ofport_dpif'.  For example, given 'realdev_ofp_port' of eth0 and
5228  * 'vlan_tci' 9, it would return the port number of eth0.9.
5229  *
5230  * Unless VLAN splinters are enabled for port 'realdev_ofp_port', this
5231  * function just returns its 'realdev_ofp_port' argument. */
5232 ofp_port_t
5233 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
5234                        ofp_port_t realdev_ofp_port, ovs_be16 vlan_tci)
5235     OVS_EXCLUDED(ofproto->vsp_mutex)
5236 {
5237     ofp_port_t ret;
5238
5239     /* hmap_is_empty is thread safe, see if we can return immediately. */
5240     if (hmap_is_empty(&ofproto->realdev_vid_map)) {
5241         return realdev_ofp_port;
5242     }
5243     ovs_mutex_lock(&ofproto->vsp_mutex);
5244     ret = vsp_realdev_to_vlandev__(ofproto, realdev_ofp_port, vlan_tci);
5245     ovs_mutex_unlock(&ofproto->vsp_mutex);
5246     return ret;
5247 }
5248
5249 static struct vlan_splinter *
5250 vlandev_find(const struct ofproto_dpif *ofproto, ofp_port_t vlandev_ofp_port)
5251 {
5252     struct vlan_splinter *vsp;
5253
5254     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node,
5255                              hash_ofp_port(vlandev_ofp_port),
5256                              &ofproto->vlandev_map) {
5257         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
5258             return vsp;
5259         }
5260     }
5261
5262     return NULL;
5263 }
5264
5265 /* Returns the OpenFlow port number of the "real" device underlying the Linux
5266  * VLAN device with OpenFlow port number 'vlandev_ofp_port' and stores the
5267  * VLAN VID of the Linux VLAN device in '*vid'.  For example, given
5268  * 'vlandev_ofp_port' of eth0.9, it would return the OpenFlow port number of
5269  * eth0 and store 9 in '*vid'.
5270  *
5271  * Returns 0 and does not modify '*vid' if 'vlandev_ofp_port' is not a Linux
5272  * VLAN device.  Unless VLAN splinters are enabled, this is what this function
5273  * always does.*/
5274 static ofp_port_t
5275 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
5276                        ofp_port_t vlandev_ofp_port, int *vid)
5277     OVS_REQUIRES(ofproto->vsp_mutex)
5278 {
5279     if (!hmap_is_empty(&ofproto->vlandev_map)) {
5280         const struct vlan_splinter *vsp;
5281
5282         vsp = vlandev_find(ofproto, vlandev_ofp_port);
5283         if (vsp) {
5284             if (vid) {
5285                 *vid = vsp->vid;
5286             }
5287             return vsp->realdev_ofp_port;
5288         }
5289     }
5290     return 0;
5291 }
5292
5293 /* Given 'flow', a flow representing a packet received on 'ofproto', checks
5294  * whether 'flow->in_port' represents a Linux VLAN device.  If so, changes
5295  * 'flow->in_port' to the "real" device backing the VLAN device, sets
5296  * 'flow->vlan_tci' to the VLAN VID, and returns true.  Optionally pushes the
5297  * appropriate VLAN on 'packet' if provided.  Otherwise (which is always the
5298  * case unless VLAN splinters are enabled), returns false without making any
5299  * changes. */
5300 bool
5301 vsp_adjust_flow(const struct ofproto_dpif *ofproto, struct flow *flow,
5302                 struct dp_packet *packet)
5303     OVS_EXCLUDED(ofproto->vsp_mutex)
5304 {
5305     ofp_port_t realdev;
5306     int vid;
5307
5308     /* hmap_is_empty is thread safe. */
5309     if (hmap_is_empty(&ofproto->vlandev_map)) {
5310         return false;
5311     }
5312
5313     ovs_mutex_lock(&ofproto->vsp_mutex);
5314     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port.ofp_port, &vid);
5315     ovs_mutex_unlock(&ofproto->vsp_mutex);
5316     if (!realdev) {
5317         return false;
5318     }
5319
5320     /* Cause the flow to be processed as if it came in on the real device with
5321      * the VLAN device's VLAN ID. */
5322     flow->in_port.ofp_port = realdev;
5323     flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
5324
5325     if (packet) {
5326         /* Make the packet resemble the flow, so that it gets sent to an
5327          * OpenFlow controller properly, so that it looks correct for sFlow,
5328          * and so that flow_extract() will get the correct vlan_tci if it is
5329          * called on 'packet'. */
5330         eth_push_vlan(packet, htons(ETH_TYPE_VLAN), flow->vlan_tci);
5331     }
5332
5333     return true;
5334 }
5335
5336 static void
5337 vsp_remove(struct ofport_dpif *port)
5338 {
5339     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
5340     struct vlan_splinter *vsp;
5341
5342     ovs_mutex_lock(&ofproto->vsp_mutex);
5343     vsp = vlandev_find(ofproto, port->up.ofp_port);
5344     if (vsp) {
5345         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
5346         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
5347         free(vsp);
5348
5349         port->realdev_ofp_port = 0;
5350     } else {
5351         VLOG_ERR("missing vlan device record");
5352     }
5353     ovs_mutex_unlock(&ofproto->vsp_mutex);
5354 }
5355
5356 static void
5357 vsp_add(struct ofport_dpif *port, ofp_port_t realdev_ofp_port, int vid)
5358 {
5359     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
5360
5361     ovs_mutex_lock(&ofproto->vsp_mutex);
5362     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
5363         && (vsp_realdev_to_vlandev__(ofproto, realdev_ofp_port, htons(vid))
5364             == realdev_ofp_port)) {
5365         struct vlan_splinter *vsp;
5366
5367         vsp = xmalloc(sizeof *vsp);
5368         vsp->realdev_ofp_port = realdev_ofp_port;
5369         vsp->vlandev_ofp_port = port->up.ofp_port;
5370         vsp->vid = vid;
5371
5372         port->realdev_ofp_port = realdev_ofp_port;
5373
5374         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
5375                     hash_ofp_port(port->up.ofp_port));
5376         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
5377                     hash_realdev_vid(realdev_ofp_port, vid));
5378     } else {
5379         VLOG_ERR("duplicate vlan device record");
5380     }
5381     ovs_mutex_unlock(&ofproto->vsp_mutex);
5382 }
5383
5384 static odp_port_t
5385 ofp_port_to_odp_port(const struct ofproto_dpif *ofproto, ofp_port_t ofp_port)
5386 {
5387     const struct ofport_dpif *ofport = ofp_port_to_ofport(ofproto, ofp_port);
5388     return ofport ? ofport->odp_port : ODPP_NONE;
5389 }
5390
5391 struct ofport_dpif *
5392 odp_port_to_ofport(const struct dpif_backer *backer, odp_port_t odp_port)
5393 {
5394     struct ofport_dpif *port;
5395
5396     ovs_rwlock_rdlock(&backer->odp_to_ofport_lock);
5397     HMAP_FOR_EACH_IN_BUCKET (port, odp_port_node, hash_odp_port(odp_port),
5398                              &backer->odp_to_ofport_map) {
5399         if (port->odp_port == odp_port) {
5400             ovs_rwlock_unlock(&backer->odp_to_ofport_lock);
5401             return port;
5402         }
5403     }
5404
5405     ovs_rwlock_unlock(&backer->odp_to_ofport_lock);
5406     return NULL;
5407 }
5408
5409 static ofp_port_t
5410 odp_port_to_ofp_port(const struct ofproto_dpif *ofproto, odp_port_t odp_port)
5411 {
5412     struct ofport_dpif *port;
5413
5414     port = odp_port_to_ofport(ofproto->backer, odp_port);
5415     if (port && &ofproto->up == port->up.ofproto) {
5416         return port->up.ofp_port;
5417     } else {
5418         return OFPP_NONE;
5419     }
5420 }
5421
5422 int
5423 ofproto_dpif_add_internal_flow(struct ofproto_dpif *ofproto,
5424                                const struct match *match, int priority,
5425                                uint16_t idle_timeout,
5426                                const struct ofpbuf *ofpacts,
5427                                struct rule **rulep)
5428 {
5429     struct ofputil_flow_mod fm;
5430     struct rule_dpif *rule;
5431     int error;
5432
5433     fm.match = *match;
5434     fm.priority = priority;
5435     fm.new_cookie = htonll(0);
5436     fm.cookie = htonll(0);
5437     fm.cookie_mask = htonll(0);
5438     fm.modify_cookie = false;
5439     fm.table_id = TBL_INTERNAL;
5440     fm.command = OFPFC_ADD;
5441     fm.idle_timeout = idle_timeout;
5442     fm.hard_timeout = 0;
5443     fm.importance = 0;
5444     fm.buffer_id = 0;
5445     fm.out_port = 0;
5446     fm.flags = OFPUTIL_FF_HIDDEN_FIELDS | OFPUTIL_FF_NO_READONLY;
5447     fm.ofpacts = ofpacts->data;
5448     fm.ofpacts_len = ofpacts->size;
5449
5450     error = ofproto_flow_mod(&ofproto->up, &fm);
5451     if (error) {
5452         VLOG_ERR_RL(&rl, "failed to add internal flow (%s)",
5453                     ofperr_to_string(error));
5454         *rulep = NULL;
5455         return error;
5456     }
5457
5458     rule = rule_dpif_lookup_in_table(ofproto, TBL_INTERNAL, &fm.match.flow,
5459                                      &fm.match.wc, false);
5460     if (rule) {
5461         *rulep = &rule->up;
5462     } else {
5463         OVS_NOT_REACHED();
5464     }
5465     return 0;
5466 }
5467
5468 int
5469 ofproto_dpif_delete_internal_flow(struct ofproto_dpif *ofproto,
5470                                   struct match *match, int priority)
5471 {
5472     struct ofputil_flow_mod fm;
5473     int error;
5474
5475     fm.match = *match;
5476     fm.priority = priority;
5477     fm.new_cookie = htonll(0);
5478     fm.cookie = htonll(0);
5479     fm.cookie_mask = htonll(0);
5480     fm.modify_cookie = false;
5481     fm.table_id = TBL_INTERNAL;
5482     fm.flags = OFPUTIL_FF_HIDDEN_FIELDS | OFPUTIL_FF_NO_READONLY;
5483     fm.command = OFPFC_DELETE_STRICT;
5484
5485     error = ofproto_flow_mod(&ofproto->up, &fm);
5486     if (error) {
5487         VLOG_ERR_RL(&rl, "failed to delete internal flow (%s)",
5488                     ofperr_to_string(error));
5489         return error;
5490     }
5491
5492     return 0;
5493 }
5494
5495 const struct ofproto_class ofproto_dpif_class = {
5496     init,
5497     enumerate_types,
5498     enumerate_names,
5499     del,
5500     port_open_type,
5501     type_run,
5502     type_wait,
5503     alloc,
5504     construct,
5505     destruct,
5506     dealloc,
5507     run,
5508     wait,
5509     NULL,                       /* get_memory_usage. */
5510     type_get_memory_usage,
5511     flush,
5512     query_tables,
5513     port_alloc,
5514     port_construct,
5515     port_destruct,
5516     port_dealloc,
5517     port_modified,
5518     port_reconfigured,
5519     port_query_by_name,
5520     port_add,
5521     port_del,
5522     port_get_stats,
5523     port_dump_start,
5524     port_dump_next,
5525     port_dump_done,
5526     port_poll,
5527     port_poll_wait,
5528     port_is_lacp_current,
5529     port_get_lacp_stats,
5530     NULL,                       /* rule_choose_table */
5531     rule_alloc,
5532     rule_construct,
5533     rule_insert,
5534     rule_delete,
5535     rule_destruct,
5536     rule_dealloc,
5537     rule_get_stats,
5538     rule_execute,
5539     NULL,                       /* rule_premodify_actions */
5540     rule_modify_actions,
5541     set_frag_handling,
5542     packet_out,
5543     set_netflow,
5544     get_netflow_ids,
5545     set_sflow,
5546     set_ipfix,
5547     set_cfm,
5548     cfm_status_changed,
5549     get_cfm_status,
5550     set_lldp,
5551     get_lldp_status,
5552     set_aa,
5553     aa_mapping_set,
5554     aa_mapping_unset,
5555     aa_vlan_get_queued,
5556     aa_vlan_get_queue_size,
5557     set_bfd,
5558     bfd_status_changed,
5559     get_bfd_status,
5560     set_stp,
5561     get_stp_status,
5562     set_stp_port,
5563     get_stp_port_status,
5564     get_stp_port_stats,
5565     set_rstp,
5566     get_rstp_status,
5567     set_rstp_port,
5568     get_rstp_port_status,
5569     set_queues,
5570     bundle_set,
5571     bundle_remove,
5572     mirror_set__,
5573     mirror_get_stats__,
5574     set_flood_vlans,
5575     is_mirror_output_bundle,
5576     forward_bpdu_changed,
5577     set_mac_table_config,
5578     set_mcast_snooping,
5579     set_mcast_snooping_port,
5580     set_realdev,
5581     NULL,                       /* meter_get_features */
5582     NULL,                       /* meter_set */
5583     NULL,                       /* meter_get */
5584     NULL,                       /* meter_del */
5585     group_alloc,                /* group_alloc */
5586     group_construct,            /* group_construct */
5587     group_destruct,             /* group_destruct */
5588     group_dealloc,              /* group_dealloc */
5589     group_modify,               /* group_modify */
5590     group_get_stats,            /* group_get_stats */
5591     get_datapath_version,       /* get_datapath_version */
5592 };