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