ofproto-dpif: Ignore subfacet install errors.
[cascardo/ovs.git] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 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-provider.h"
20
21 #include <errno.h>
22
23 #include "autopath.h"
24 #include "bond.h"
25 #include "bundle.h"
26 #include "byte-order.h"
27 #include "connmgr.h"
28 #include "coverage.h"
29 #include "cfm.h"
30 #include "dpif.h"
31 #include "dynamic-string.h"
32 #include "fail-open.h"
33 #include "hmapx.h"
34 #include "lacp.h"
35 #include "learn.h"
36 #include "mac-learning.h"
37 #include "meta-flow.h"
38 #include "multipath.h"
39 #include "netdev-vport.h"
40 #include "netdev.h"
41 #include "netlink.h"
42 #include "nx-match.h"
43 #include "odp-util.h"
44 #include "ofp-util.h"
45 #include "ofpbuf.h"
46 #include "ofp-actions.h"
47 #include "ofp-parse.h"
48 #include "ofp-print.h"
49 #include "ofproto-dpif-governor.h"
50 #include "ofproto-dpif-sflow.h"
51 #include "poll-loop.h"
52 #include "simap.h"
53 #include "smap.h"
54 #include "timer.h"
55 #include "tunnel.h"
56 #include "unaligned.h"
57 #include "unixctl.h"
58 #include "vlan-bitmap.h"
59 #include "vlog.h"
60
61 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
62
63 COVERAGE_DEFINE(ofproto_dpif_expired);
64 COVERAGE_DEFINE(ofproto_dpif_xlate);
65 COVERAGE_DEFINE(facet_changed_rule);
66 COVERAGE_DEFINE(facet_revalidate);
67 COVERAGE_DEFINE(facet_unexpected);
68 COVERAGE_DEFINE(facet_suppress);
69
70 /* Maximum depth of flow table recursion (due to resubmit actions) in a
71  * flow translation. */
72 #define MAX_RESUBMIT_RECURSION 64
73
74 /* Number of implemented OpenFlow tables. */
75 enum { N_TABLES = 255 };
76 enum { TBL_INTERNAL = N_TABLES - 1 };    /* Used for internal hidden rules. */
77 BUILD_ASSERT_DECL(N_TABLES >= 2 && N_TABLES <= 255);
78
79 struct ofport_dpif;
80 struct ofproto_dpif;
81 struct flow_miss;
82
83 struct rule_dpif {
84     struct rule up;
85
86     /* These statistics:
87      *
88      *   - Do include packets and bytes from facets that have been deleted or
89      *     whose own statistics have been folded into the rule.
90      *
91      *   - Do include packets and bytes sent "by hand" that were accounted to
92      *     the rule without any facet being involved (this is a rare corner
93      *     case in rule_execute()).
94      *
95      *   - Do not include packet or bytes that can be obtained from any facet's
96      *     packet_count or byte_count member or that can be obtained from the
97      *     datapath by, e.g., dpif_flow_get() for any subfacet.
98      */
99     uint64_t packet_count;       /* Number of packets received. */
100     uint64_t byte_count;         /* Number of bytes received. */
101
102     tag_type tag;                /* Caches rule_calculate_tag() result. */
103
104     struct list facets;          /* List of "struct facet"s. */
105 };
106
107 static struct rule_dpif *rule_dpif_cast(const struct rule *rule)
108 {
109     return rule ? CONTAINER_OF(rule, struct rule_dpif, up) : NULL;
110 }
111
112 static struct rule_dpif *rule_dpif_lookup(struct ofproto_dpif *,
113                                           const struct flow *);
114 static struct rule_dpif *rule_dpif_lookup__(struct ofproto_dpif *,
115                                             const struct flow *,
116                                             uint8_t table);
117 static struct rule_dpif *rule_dpif_miss_rule(struct ofproto_dpif *ofproto,
118                                              const struct flow *flow);
119
120 static void rule_credit_stats(struct rule_dpif *,
121                               const struct dpif_flow_stats *);
122 static void flow_push_stats(struct rule_dpif *, const struct flow *,
123                             const struct dpif_flow_stats *);
124 static tag_type rule_calculate_tag(const struct flow *,
125                                    const struct minimask *, uint32_t basis);
126 static void rule_invalidate(const struct rule_dpif *);
127
128 #define MAX_MIRRORS 32
129 typedef uint32_t mirror_mask_t;
130 #define MIRROR_MASK_C(X) UINT32_C(X)
131 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
132 struct ofmirror {
133     struct ofproto_dpif *ofproto; /* Owning ofproto. */
134     size_t idx;                 /* In ofproto's "mirrors" array. */
135     void *aux;                  /* Key supplied by ofproto's client. */
136     char *name;                 /* Identifier for log messages. */
137
138     /* Selection criteria. */
139     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
140     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
141     unsigned long *vlans;       /* Bitmap of chosen VLANs, NULL selects all. */
142
143     /* Output (exactly one of out == NULL and out_vlan == -1 is true). */
144     struct ofbundle *out;       /* Output port or NULL. */
145     int out_vlan;               /* Output VLAN or -1. */
146     mirror_mask_t dup_mirrors;  /* Bitmap of mirrors with the same output. */
147
148     /* Counters. */
149     int64_t packet_count;       /* Number of packets sent. */
150     int64_t byte_count;         /* Number of bytes sent. */
151 };
152
153 static void mirror_destroy(struct ofmirror *);
154 static void update_mirror_stats(struct ofproto_dpif *ofproto,
155                                 mirror_mask_t mirrors,
156                                 uint64_t packets, uint64_t bytes);
157
158 struct ofbundle {
159     struct hmap_node hmap_node; /* In struct ofproto's "bundles" hmap. */
160     struct ofproto_dpif *ofproto; /* Owning ofproto. */
161     void *aux;                  /* Key supplied by ofproto's client. */
162     char *name;                 /* Identifier for log messages. */
163
164     /* Configuration. */
165     struct list ports;          /* Contains "struct ofport"s. */
166     enum port_vlan_mode vlan_mode; /* VLAN mode */
167     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
168     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
169                                  * NULL if all VLANs are trunked. */
170     struct lacp *lacp;          /* LACP if LACP is enabled, otherwise NULL. */
171     struct bond *bond;          /* Nonnull iff more than one port. */
172     bool use_priority_tags;     /* Use 802.1p tag for frames in VLAN 0? */
173
174     /* Status. */
175     bool floodable;          /* True if no port has OFPUTIL_PC_NO_FLOOD set. */
176
177     /* Port mirroring info. */
178     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
179     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
180     mirror_mask_t mirror_out;   /* Mirrors that output to this bundle. */
181 };
182
183 static void bundle_remove(struct ofport *);
184 static void bundle_update(struct ofbundle *);
185 static void bundle_destroy(struct ofbundle *);
186 static void bundle_del_port(struct ofport_dpif *);
187 static void bundle_run(struct ofbundle *);
188 static void bundle_wait(struct ofbundle *);
189 static struct ofbundle *lookup_input_bundle(const struct ofproto_dpif *,
190                                             uint16_t in_port, bool warn,
191                                             struct ofport_dpif **in_ofportp);
192
193 /* A controller may use OFPP_NONE as the ingress port to indicate that
194  * it did not arrive on a "real" port.  'ofpp_none_bundle' exists for
195  * when an input bundle is needed for validation (e.g., mirroring or
196  * OFPP_NORMAL processing).  It is not connected to an 'ofproto' or have
197  * any 'port' structs, so care must be taken when dealing with it. */
198 static struct ofbundle ofpp_none_bundle = {
199     .name      = "OFPP_NONE",
200     .vlan_mode = PORT_VLAN_TRUNK
201 };
202
203 static void stp_run(struct ofproto_dpif *ofproto);
204 static void stp_wait(struct ofproto_dpif *ofproto);
205 static int set_stp_port(struct ofport *,
206                         const struct ofproto_port_stp_settings *);
207
208 static bool ofbundle_includes_vlan(const struct ofbundle *, uint16_t vlan);
209
210 struct action_xlate_ctx {
211 /* action_xlate_ctx_init() initializes these members. */
212
213     /* The ofproto. */
214     struct ofproto_dpif *ofproto;
215
216     /* Flow to which the OpenFlow actions apply.  xlate_actions() will modify
217      * this flow when actions change header fields. */
218     struct flow flow;
219
220     /* The packet corresponding to 'flow', or a null pointer if we are
221      * revalidating without a packet to refer to. */
222     const struct ofpbuf *packet;
223
224     /* Should OFPP_NORMAL update the MAC learning table?  Should "learn"
225      * actions update the flow table?
226      *
227      * We want to update these tables if we are actually processing a packet,
228      * or if we are accounting for packets that the datapath has processed, but
229      * not if we are just revalidating. */
230     bool may_learn;
231
232     /* The rule that we are currently translating, or NULL. */
233     struct rule_dpif *rule;
234
235     /* Union of the set of TCP flags seen so far in this flow.  (Used only by
236      * NXAST_FIN_TIMEOUT.  Set to zero to avoid updating updating rules'
237      * timeouts.) */
238     uint8_t tcp_flags;
239
240     /* If nonnull, flow translation calls this function just before executing a
241      * resubmit or OFPP_TABLE action.  In addition, disables logging of traces
242      * when the recursion depth is exceeded.
243      *
244      * 'rule' is the rule being submitted into.  It will be null if the
245      * resubmit or OFPP_TABLE action didn't find a matching rule.
246      *
247      * This is normally null so the client has to set it manually after
248      * calling action_xlate_ctx_init(). */
249     void (*resubmit_hook)(struct action_xlate_ctx *, struct rule_dpif *rule);
250
251     /* If nonnull, flow translation calls this function to report some
252      * significant decision, e.g. to explain why OFPP_NORMAL translation
253      * dropped a packet. */
254     void (*report_hook)(struct action_xlate_ctx *, const char *s);
255
256     /* If nonnull, flow translation credits the specified statistics to each
257      * rule reached through a resubmit or OFPP_TABLE action.
258      *
259      * This is normally null so the client has to set it manually after
260      * calling action_xlate_ctx_init(). */
261     const struct dpif_flow_stats *resubmit_stats;
262
263 /* xlate_actions() initializes and uses these members.  The client might want
264  * to look at them after it returns. */
265
266     struct ofpbuf *odp_actions; /* Datapath actions. */
267     tag_type tags;              /* Tags associated with actions. */
268     enum slow_path_reason slow; /* 0 if fast path may be used. */
269     bool has_learn;             /* Actions include NXAST_LEARN? */
270     bool has_normal;            /* Actions output to OFPP_NORMAL? */
271     bool has_fin_timeout;       /* Actions include NXAST_FIN_TIMEOUT? */
272     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
273     mirror_mask_t mirrors;      /* Bitmap of associated mirrors. */
274
275 /* xlate_actions() initializes and uses these members, but the client has no
276  * reason to look at them. */
277
278     int recurse;                /* Recursion level, via xlate_table_action. */
279     bool max_resubmit_trigger;  /* Recursed too deeply during translation. */
280     struct flow base_flow;      /* Flow at the last commit. */
281     uint32_t orig_skb_priority; /* Priority when packet arrived. */
282     uint8_t table_id;           /* OpenFlow table ID where flow was found. */
283     uint32_t sflow_n_outputs;   /* Number of output ports. */
284     uint32_t sflow_odp_port;    /* Output port for composing sFlow action. */
285     uint16_t user_cookie_offset;/* Used for user_action_cookie fixup. */
286     bool exit;                  /* No further actions should be processed. */
287     struct flow orig_flow;      /* Copy of original flow. */
288 };
289
290 static void action_xlate_ctx_init(struct action_xlate_ctx *,
291                                   struct ofproto_dpif *, const struct flow *,
292                                   ovs_be16 initial_tci, struct rule_dpif *,
293                                   uint8_t tcp_flags, const struct ofpbuf *);
294 static void xlate_actions(struct action_xlate_ctx *,
295                           const struct ofpact *ofpacts, size_t ofpacts_len,
296                           struct ofpbuf *odp_actions);
297 static void xlate_actions_for_side_effects(struct action_xlate_ctx *,
298                                            const struct ofpact *ofpacts,
299                                            size_t ofpacts_len);
300 static void xlate_table_action(struct action_xlate_ctx *, uint16_t in_port,
301                                uint8_t table_id, bool may_packet_in);
302
303 static size_t put_userspace_action(const struct ofproto_dpif *,
304                                    struct ofpbuf *odp_actions,
305                                    const struct flow *,
306                                    const union user_action_cookie *);
307
308 static void compose_slow_path(const struct ofproto_dpif *, const struct flow *,
309                               enum slow_path_reason,
310                               uint64_t *stub, size_t stub_size,
311                               const struct nlattr **actionsp,
312                               size_t *actions_lenp);
313
314 static void xlate_report(struct action_xlate_ctx *ctx, const char *s);
315
316 /* A subfacet (see "struct subfacet" below) has three possible installation
317  * states:
318  *
319  *   - SF_NOT_INSTALLED: Not installed in the datapath.  This will only be the
320  *     case just after the subfacet is created, just before the subfacet is
321  *     destroyed, or if the datapath returns an error when we try to install a
322  *     subfacet.
323  *
324  *   - SF_FAST_PATH: The subfacet's actions are installed in the datapath.
325  *
326  *   - SF_SLOW_PATH: An action that sends every packet for the subfacet through
327  *     ofproto_dpif is installed in the datapath.
328  */
329 enum subfacet_path {
330     SF_NOT_INSTALLED,           /* No datapath flow for this subfacet. */
331     SF_FAST_PATH,               /* Full actions are installed. */
332     SF_SLOW_PATH,               /* Send-to-userspace action is installed. */
333 };
334
335 static const char *subfacet_path_to_string(enum subfacet_path);
336
337 /* A dpif flow and actions associated with a facet.
338  *
339  * See also the large comment on struct facet. */
340 struct subfacet {
341     /* Owners. */
342     struct hmap_node hmap_node; /* In struct ofproto_dpif 'subfacets' list. */
343     struct list list_node;      /* In struct facet's 'facets' list. */
344     struct facet *facet;        /* Owning facet. */
345
346     enum odp_key_fitness key_fitness;
347     struct nlattr *key;
348     int key_len;
349
350     long long int used;         /* Time last used; time created if not used. */
351
352     uint64_t dp_packet_count;   /* Last known packet count in the datapath. */
353     uint64_t dp_byte_count;     /* Last known byte count in the datapath. */
354
355     /* Datapath actions.
356      *
357      * These should be essentially identical for every subfacet in a facet, but
358      * may differ in trivial ways due to VLAN splinters. */
359     size_t actions_len;         /* Number of bytes in actions[]. */
360     struct nlattr *actions;     /* Datapath actions. */
361
362     enum slow_path_reason slow; /* 0 if fast path may be used. */
363     enum subfacet_path path;    /* Installed in datapath? */
364
365     /* This value is normally the same as ->facet->flow.vlan_tci.  Only VLAN
366      * splinters can cause it to differ.  This value should be removed when
367      * the VLAN splinters feature is no longer needed.  */
368     ovs_be16 initial_tci;       /* Initial VLAN TCI value. */
369
370     /* Datapath port the packet arrived on.  This is needed to remove
371      * flows for ports that are no longer part of the bridge.  Since the
372      * flow definition only has the OpenFlow port number and the port is
373      * no longer part of the bridge, we can't determine the datapath port
374      * number needed to delete the flow from the datapath. */
375     uint32_t odp_in_port;
376 };
377
378 #define SUBFACET_DESTROY_MAX_BATCH 50
379
380 static struct subfacet *subfacet_create(struct facet *, struct flow_miss *miss,
381                                         long long int now);
382 static struct subfacet *subfacet_find(struct ofproto_dpif *,
383                                       const struct nlattr *key, size_t key_len,
384                                       uint32_t key_hash);
385 static void subfacet_destroy(struct subfacet *);
386 static void subfacet_destroy__(struct subfacet *);
387 static void subfacet_destroy_batch(struct ofproto_dpif *,
388                                    struct subfacet **, int n);
389 static void subfacet_reset_dp_stats(struct subfacet *,
390                                     struct dpif_flow_stats *);
391 static void subfacet_update_time(struct subfacet *, long long int used);
392 static void subfacet_update_stats(struct subfacet *,
393                                   const struct dpif_flow_stats *);
394 static void subfacet_make_actions(struct subfacet *,
395                                   const struct ofpbuf *packet,
396                                   struct ofpbuf *odp_actions);
397 static int subfacet_install(struct subfacet *,
398                             const struct nlattr *actions, size_t actions_len,
399                             struct dpif_flow_stats *, enum slow_path_reason);
400 static void subfacet_uninstall(struct subfacet *);
401
402 static enum subfacet_path subfacet_want_path(enum slow_path_reason);
403
404 /* An exact-match instantiation of an OpenFlow flow.
405  *
406  * A facet associates a "struct flow", which represents the Open vSwitch
407  * userspace idea of an exact-match flow, with one or more subfacets.  Each
408  * subfacet tracks the datapath's idea of the exact-match flow equivalent to
409  * the facet.  When the kernel module (or other dpif implementation) and Open
410  * vSwitch userspace agree on the definition of a flow key, there is exactly
411  * one subfacet per facet.  If the dpif implementation supports more-specific
412  * flow matching than userspace, however, a facet can have more than one
413  * subfacet, each of which corresponds to some distinction in flow that
414  * userspace simply doesn't understand.
415  *
416  * Flow expiration works in terms of subfacets, so a facet must have at least
417  * one subfacet or it will never expire, leaking memory. */
418 struct facet {
419     /* Owners. */
420     struct hmap_node hmap_node;  /* In owning ofproto's 'facets' hmap. */
421     struct list list_node;       /* In owning rule's 'facets' list. */
422     struct rule_dpif *rule;      /* Owning rule. */
423
424     /* Owned data. */
425     struct list subfacets;
426     long long int used;         /* Time last used; time created if not used. */
427
428     /* Key. */
429     struct flow flow;
430
431     /* These statistics:
432      *
433      *   - Do include packets and bytes sent "by hand", e.g. with
434      *     dpif_execute().
435      *
436      *   - Do include packets and bytes that were obtained from the datapath
437      *     when a subfacet's statistics were reset (e.g. dpif_flow_put() with
438      *     DPIF_FP_ZERO_STATS).
439      *
440      *   - Do not include packets or bytes that can be obtained from the
441      *     datapath for any existing subfacet.
442      */
443     uint64_t packet_count;       /* Number of packets received. */
444     uint64_t byte_count;         /* Number of bytes received. */
445
446     /* Resubmit statistics. */
447     uint64_t prev_packet_count;  /* Number of packets from last stats push. */
448     uint64_t prev_byte_count;    /* Number of bytes from last stats push. */
449     long long int prev_used;     /* Used time from last stats push. */
450
451     /* Accounting. */
452     uint64_t accounted_bytes;    /* Bytes processed by facet_account(). */
453     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
454     uint8_t tcp_flags;           /* TCP flags seen for this 'rule'. */
455
456     /* Properties of datapath actions.
457      *
458      * Every subfacet has its own actions because actions can differ slightly
459      * between splintered and non-splintered subfacets due to the VLAN tag
460      * being initially different (present vs. absent).  All of them have these
461      * properties in common so we just store one copy of them here. */
462     bool has_learn;              /* Actions include NXAST_LEARN? */
463     bool has_normal;             /* Actions output to OFPP_NORMAL? */
464     bool has_fin_timeout;        /* Actions include NXAST_FIN_TIMEOUT? */
465     tag_type tags;               /* Tags that would require revalidation. */
466     mirror_mask_t mirrors;       /* Bitmap of dependent mirrors. */
467
468     /* Storage for a single subfacet, to reduce malloc() time and space
469      * overhead.  (A facet always has at least one subfacet and in the common
470      * case has exactly one subfacet.) */
471     struct subfacet one_subfacet;
472 };
473
474 static struct facet *facet_create(struct rule_dpif *,
475                                   const struct flow *, uint32_t hash);
476 static void facet_remove(struct facet *);
477 static void facet_free(struct facet *);
478
479 static struct facet *facet_find(struct ofproto_dpif *,
480                                 const struct flow *, uint32_t hash);
481 static struct facet *facet_lookup_valid(struct ofproto_dpif *,
482                                         const struct flow *, uint32_t hash);
483 static void facet_revalidate(struct facet *);
484 static bool facet_check_consistency(struct facet *);
485
486 static void facet_flush_stats(struct facet *);
487
488 static void facet_update_time(struct facet *, long long int used);
489 static void facet_reset_counters(struct facet *);
490 static void facet_push_stats(struct facet *);
491 static void facet_learn(struct facet *);
492 static void facet_account(struct facet *);
493
494 static bool facet_is_controller_flow(struct facet *);
495
496 struct ofport_dpif {
497     struct hmap_node odp_port_node; /* In dpif_backer's "odp_to_ofport_map". */
498     struct ofport up;
499
500     uint32_t odp_port;
501     struct ofbundle *bundle;    /* Bundle that contains this port, if any. */
502     struct list bundle_node;    /* In struct ofbundle's "ports" list. */
503     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
504     tag_type tag;               /* Tag associated with this port. */
505     uint32_t bond_stable_id;    /* stable_id to use as bond slave, or 0. */
506     bool may_enable;            /* May be enabled in bonds. */
507     long long int carrier_seq;  /* Carrier status changes. */
508     struct tnl_port *tnl_port;  /* Tunnel handle, or null. */
509
510     /* Spanning tree. */
511     struct stp_port *stp_port;  /* Spanning Tree Protocol, if any. */
512     enum stp_state stp_state;   /* Always STP_DISABLED if STP not in use. */
513     long long int stp_state_entered;
514
515     struct hmap priorities;     /* Map of attached 'priority_to_dscp's. */
516
517     /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
518      *
519      * This is deprecated.  It is only for compatibility with broken device
520      * drivers in old versions of Linux that do not properly support VLANs when
521      * VLAN devices are not used.  When broken device drivers are no longer in
522      * widespread use, we will delete these interfaces. */
523     uint16_t realdev_ofp_port;
524     int vlandev_vid;
525 };
526
527 /* Node in 'ofport_dpif''s 'priorities' map.  Used to maintain a map from
528  * 'priority' (the datapath's term for QoS queue) to the dscp bits which all
529  * traffic egressing the 'ofport' with that priority should be marked with. */
530 struct priority_to_dscp {
531     struct hmap_node hmap_node; /* Node in 'ofport_dpif''s 'priorities' map. */
532     uint32_t priority;          /* Priority of this queue (see struct flow). */
533
534     uint8_t dscp;               /* DSCP bits to mark outgoing traffic with. */
535 };
536
537 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
538  *
539  * This is deprecated.  It is only for compatibility with broken device drivers
540  * in old versions of Linux that do not properly support VLANs when VLAN
541  * devices are not used.  When broken device drivers are no longer in
542  * widespread use, we will delete these interfaces. */
543 struct vlan_splinter {
544     struct hmap_node realdev_vid_node;
545     struct hmap_node vlandev_node;
546     uint16_t realdev_ofp_port;
547     uint16_t vlandev_ofp_port;
548     int vid;
549 };
550
551 static uint32_t vsp_realdev_to_vlandev(const struct ofproto_dpif *,
552                                        uint32_t realdev, ovs_be16 vlan_tci);
553 static bool vsp_adjust_flow(const struct ofproto_dpif *, struct flow *);
554 static void vsp_remove(struct ofport_dpif *);
555 static void vsp_add(struct ofport_dpif *, uint16_t realdev_ofp_port, int vid);
556
557 static uint32_t ofp_port_to_odp_port(const struct ofproto_dpif *,
558                                      uint16_t ofp_port);
559 static uint16_t odp_port_to_ofp_port(const struct ofproto_dpif *,
560                                      uint32_t odp_port);
561
562 static struct ofport_dpif *
563 ofport_dpif_cast(const struct ofport *ofport)
564 {
565     ovs_assert(ofport->ofproto->ofproto_class == &ofproto_dpif_class);
566     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
567 }
568
569 static void port_run(struct ofport_dpif *);
570 static void port_run_fast(struct ofport_dpif *);
571 static void port_wait(struct ofport_dpif *);
572 static int set_cfm(struct ofport *, const struct cfm_settings *);
573 static void ofport_clear_priorities(struct ofport_dpif *);
574
575 struct dpif_completion {
576     struct list list_node;
577     struct ofoperation *op;
578 };
579
580 /* Extra information about a classifier table.
581  * Currently used just for optimized flow revalidation. */
582 struct table_dpif {
583     /* If either of these is nonnull, then this table has a form that allows
584      * flows to be tagged to avoid revalidating most flows for the most common
585      * kinds of flow table changes. */
586     struct cls_table *catchall_table; /* Table that wildcards all fields. */
587     struct cls_table *other_table;    /* Table with any other wildcard set. */
588     uint32_t basis;                   /* Keeps each table's tags separate. */
589 };
590
591 /* Reasons that we might need to revalidate every facet, and corresponding
592  * coverage counters.
593  *
594  * A value of 0 means that there is no need to revalidate.
595  *
596  * It would be nice to have some cleaner way to integrate with coverage
597  * counters, but with only a few reasons I guess this is good enough for
598  * now. */
599 enum revalidate_reason {
600     REV_RECONFIGURE = 1,       /* Switch configuration changed. */
601     REV_STP,                   /* Spanning tree protocol port status change. */
602     REV_PORT_TOGGLED,          /* Port enabled or disabled by CFM, LACP, ...*/
603     REV_FLOW_TABLE,            /* Flow table changed. */
604     REV_INCONSISTENCY          /* Facet self-check failed. */
605 };
606 COVERAGE_DEFINE(rev_reconfigure);
607 COVERAGE_DEFINE(rev_stp);
608 COVERAGE_DEFINE(rev_port_toggled);
609 COVERAGE_DEFINE(rev_flow_table);
610 COVERAGE_DEFINE(rev_inconsistency);
611
612 /* Drop keys are odp flow keys which have drop flows installed in the kernel.
613  * These are datapath flows which have no associated ofproto, if they did we
614  * would use facets. */
615 struct drop_key {
616     struct hmap_node hmap_node;
617     struct nlattr *key;
618     size_t key_len;
619 };
620
621 /* All datapaths of a given type share a single dpif backer instance. */
622 struct dpif_backer {
623     char *type;
624     int refcount;
625     struct dpif *dpif;
626     struct timer next_expiration;
627     struct hmap odp_to_ofport_map; /* ODP port to ofport mapping. */
628
629     struct simap tnl_backers;      /* Set of dpif ports backing tunnels. */
630
631     /* Facet revalidation flags applying to facets which use this backer. */
632     enum revalidate_reason need_revalidate; /* Revalidate every facet. */
633     struct tag_set revalidate_set; /* Revalidate only matching facets. */
634
635     struct hmap drop_keys; /* Set of dropped odp keys. */
636 };
637
638 /* All existing ofproto_backer instances, indexed by ofproto->up.type. */
639 static struct shash all_dpif_backers = SHASH_INITIALIZER(&all_dpif_backers);
640
641 static void drop_key_clear(struct dpif_backer *);
642 static struct ofport_dpif *
643 odp_port_to_ofport(const struct dpif_backer *, uint32_t odp_port);
644
645 struct ofproto_dpif {
646     struct hmap_node all_ofproto_dpifs_node; /* In 'all_ofproto_dpifs'. */
647     struct ofproto up;
648     struct dpif_backer *backer;
649
650     /* Special OpenFlow rules. */
651     struct rule_dpif *miss_rule; /* Sends flow table misses to controller. */
652     struct rule_dpif *no_packet_in_rule; /* Drops flow table misses. */
653
654     /* Statistics. */
655     uint64_t n_matches;
656
657     /* Bridging. */
658     struct netflow *netflow;
659     struct dpif_sflow *sflow;
660     struct hmap bundles;        /* Contains "struct ofbundle"s. */
661     struct mac_learning *ml;
662     struct ofmirror *mirrors[MAX_MIRRORS];
663     bool has_mirrors;
664     bool has_bonded_bundles;
665
666     /* Facets. */
667     struct hmap facets;
668     struct hmap subfacets;
669     struct governor *governor;
670
671     /* Revalidation. */
672     struct table_dpif tables[N_TABLES];
673
674     /* Support for debugging async flow mods. */
675     struct list completions;
676
677     bool has_bundle_action; /* True when the first bundle action appears. */
678     struct netdev_stats stats; /* To account packets generated and consumed in
679                                 * userspace. */
680
681     /* Spanning tree. */
682     struct stp *stp;
683     long long int stp_last_tick;
684
685     /* VLAN splinters. */
686     struct hmap realdev_vid_map; /* (realdev,vid) -> vlandev. */
687     struct hmap vlandev_map;     /* vlandev -> (realdev,vid). */
688
689     /* Ports. */
690     struct sset ports;             /* Set of standard port names. */
691     struct sset ghost_ports;       /* Ports with no datapath port. */
692     struct sset port_poll_set;     /* Queued names for port_poll() reply. */
693     int port_poll_errno;           /* Last errno for port_poll() reply. */
694 };
695
696 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
697  * for debugging the asynchronous flow_mod implementation.) */
698 static bool clogged;
699
700 /* All existing ofproto_dpif instances, indexed by ->up.name. */
701 static struct hmap all_ofproto_dpifs = HMAP_INITIALIZER(&all_ofproto_dpifs);
702
703 static void ofproto_dpif_unixctl_init(void);
704
705 static struct ofproto_dpif *
706 ofproto_dpif_cast(const struct ofproto *ofproto)
707 {
708     ovs_assert(ofproto->ofproto_class == &ofproto_dpif_class);
709     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
710 }
711
712 static struct ofport_dpif *get_ofp_port(const struct ofproto_dpif *,
713                                         uint16_t ofp_port);
714 static struct ofport_dpif *get_odp_port(const struct ofproto_dpif *,
715                                         uint32_t odp_port);
716 static void ofproto_trace(struct ofproto_dpif *, const struct flow *,
717                           const struct ofpbuf *, ovs_be16 initial_tci,
718                           struct ds *);
719
720 /* Packet processing. */
721 static void update_learning_table(struct ofproto_dpif *,
722                                   const struct flow *, int vlan,
723                                   struct ofbundle *);
724 /* Upcalls. */
725 #define FLOW_MISS_MAX_BATCH 50
726 static int handle_upcalls(struct dpif_backer *, unsigned int max_batch);
727
728 /* Flow expiration. */
729 static int expire(struct dpif_backer *);
730
731 /* NetFlow. */
732 static void send_netflow_active_timeouts(struct ofproto_dpif *);
733
734 /* Utilities. */
735 static int send_packet(const struct ofport_dpif *, struct ofpbuf *packet);
736 static size_t compose_sflow_action(const struct ofproto_dpif *,
737                                    struct ofpbuf *odp_actions,
738                                    const struct flow *, uint32_t odp_port);
739 static void add_mirror_actions(struct action_xlate_ctx *ctx,
740                                const struct flow *flow);
741 /* Global variables. */
742 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
743
744 /* Initial mappings of port to bridge mappings. */
745 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
746 \f
747 /* Factory functions. */
748
749 static void
750 init(const struct shash *iface_hints)
751 {
752     struct shash_node *node;
753
754     /* Make a local copy, since we don't own 'iface_hints' elements. */
755     SHASH_FOR_EACH(node, iface_hints) {
756         const struct iface_hint *orig_hint = node->data;
757         struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
758
759         new_hint->br_name = xstrdup(orig_hint->br_name);
760         new_hint->br_type = xstrdup(orig_hint->br_type);
761         new_hint->ofp_port = orig_hint->ofp_port;
762
763         shash_add(&init_ofp_ports, node->name, new_hint);
764     }
765 }
766
767 static void
768 enumerate_types(struct sset *types)
769 {
770     dp_enumerate_types(types);
771 }
772
773 static int
774 enumerate_names(const char *type, struct sset *names)
775 {
776     struct ofproto_dpif *ofproto;
777
778     sset_clear(names);
779     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
780         if (strcmp(type, ofproto->up.type)) {
781             continue;
782         }
783         sset_add(names, ofproto->up.name);
784     }
785
786     return 0;
787 }
788
789 static int
790 del(const char *type, const char *name)
791 {
792     struct dpif *dpif;
793     int error;
794
795     error = dpif_open(name, type, &dpif);
796     if (!error) {
797         error = dpif_delete(dpif);
798         dpif_close(dpif);
799     }
800     return error;
801 }
802 \f
803 static const char *
804 port_open_type(const char *datapath_type, const char *port_type)
805 {
806     return dpif_port_open_type(datapath_type, port_type);
807 }
808
809 /* Type functions. */
810
811 static struct ofproto_dpif *
812 lookup_ofproto_dpif_by_port_name(const char *name)
813 {
814     struct ofproto_dpif *ofproto;
815
816     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
817         if (sset_contains(&ofproto->ports, name)) {
818             return ofproto;
819         }
820     }
821
822     return NULL;
823 }
824
825 static int
826 type_run(const char *type)
827 {
828     struct dpif_backer *backer;
829     char *devname;
830     int error;
831
832     backer = shash_find_data(&all_dpif_backers, type);
833     if (!backer) {
834         /* This is not necessarily a problem, since backers are only
835          * created on demand. */
836         return 0;
837     }
838
839     dpif_run(backer->dpif);
840
841     if (backer->need_revalidate
842         || !tag_set_is_empty(&backer->revalidate_set)) {
843         struct tag_set revalidate_set = backer->revalidate_set;
844         bool need_revalidate = backer->need_revalidate;
845         struct ofproto_dpif *ofproto;
846         struct simap_node *node;
847         struct simap tmp_backers;
848
849         /* Handle tunnel garbage collection. */
850         simap_init(&tmp_backers);
851         simap_swap(&backer->tnl_backers, &tmp_backers);
852
853         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
854             struct ofport_dpif *iter;
855
856             if (backer != ofproto->backer) {
857                 continue;
858             }
859
860             HMAP_FOR_EACH (iter, up.hmap_node, &ofproto->up.ports) {
861                 const char *dp_port;
862
863                 if (!iter->tnl_port) {
864                     continue;
865                 }
866
867                 dp_port = netdev_vport_get_dpif_port(iter->up.netdev);
868                 node = simap_find(&tmp_backers, dp_port);
869                 if (node) {
870                     simap_put(&backer->tnl_backers, dp_port, node->data);
871                     simap_delete(&tmp_backers, node);
872                     node = simap_find(&backer->tnl_backers, dp_port);
873                 } else {
874                     node = simap_find(&backer->tnl_backers, dp_port);
875                     if (!node) {
876                         uint32_t odp_port = UINT32_MAX;
877
878                         if (!dpif_port_add(backer->dpif, iter->up.netdev,
879                                            &odp_port)) {
880                             simap_put(&backer->tnl_backers, dp_port, odp_port);
881                             node = simap_find(&backer->tnl_backers, dp_port);
882                         }
883                     }
884                 }
885
886                 iter->odp_port = node ? node->data : OVSP_NONE;
887                 if (tnl_port_reconfigure(&iter->up, iter->odp_port,
888                                          &iter->tnl_port)) {
889                     backer->need_revalidate = REV_RECONFIGURE;
890                 }
891             }
892         }
893
894         SIMAP_FOR_EACH (node, &tmp_backers) {
895             dpif_port_del(backer->dpif, node->data);
896         }
897         simap_destroy(&tmp_backers);
898
899         switch (backer->need_revalidate) {
900         case REV_RECONFIGURE:   COVERAGE_INC(rev_reconfigure);   break;
901         case REV_STP:           COVERAGE_INC(rev_stp);           break;
902         case REV_PORT_TOGGLED:  COVERAGE_INC(rev_port_toggled);  break;
903         case REV_FLOW_TABLE:    COVERAGE_INC(rev_flow_table);    break;
904         case REV_INCONSISTENCY: COVERAGE_INC(rev_inconsistency); break;
905         }
906
907         if (backer->need_revalidate) {
908             /* Clear the drop_keys in case we should now be accepting some
909              * formerly dropped flows. */
910             drop_key_clear(backer);
911         }
912
913         /* Clear the revalidation flags. */
914         tag_set_init(&backer->revalidate_set);
915         backer->need_revalidate = 0;
916
917         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
918             struct facet *facet;
919
920             if (ofproto->backer != backer) {
921                 continue;
922             }
923
924             HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
925                 if (need_revalidate
926                     || tag_set_intersects(&revalidate_set, facet->tags)) {
927                     facet_revalidate(facet);
928                 }
929             }
930         }
931     }
932
933     if (timer_expired(&backer->next_expiration)) {
934         int delay = expire(backer);
935         timer_set_duration(&backer->next_expiration, delay);
936     }
937
938     /* Check for port changes in the dpif. */
939     while ((error = dpif_port_poll(backer->dpif, &devname)) == 0) {
940         struct ofproto_dpif *ofproto;
941         struct dpif_port port;
942
943         /* Don't report on the datapath's device. */
944         if (!strcmp(devname, dpif_base_name(backer->dpif))) {
945             goto next;
946         }
947
948         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node,
949                        &all_ofproto_dpifs) {
950             if (simap_contains(&ofproto->backer->tnl_backers, devname)) {
951                 goto next;
952             }
953         }
954
955         ofproto = lookup_ofproto_dpif_by_port_name(devname);
956         if (dpif_port_query_by_name(backer->dpif, devname, &port)) {
957             /* The port was removed.  If we know the datapath,
958              * report it through poll_set().  If we don't, it may be
959              * notifying us of a removal we initiated, so ignore it.
960              * If there's a pending ENOBUFS, let it stand, since
961              * everything will be reevaluated. */
962             if (ofproto && ofproto->port_poll_errno != ENOBUFS) {
963                 sset_add(&ofproto->port_poll_set, devname);
964                 ofproto->port_poll_errno = 0;
965             }
966         } else if (!ofproto) {
967             /* The port was added, but we don't know with which
968              * ofproto we should associate it.  Delete it. */
969             dpif_port_del(backer->dpif, port.port_no);
970         }
971         dpif_port_destroy(&port);
972
973     next:
974         free(devname);
975     }
976
977     if (error != EAGAIN) {
978         struct ofproto_dpif *ofproto;
979
980         /* There was some sort of error, so propagate it to all
981          * ofprotos that use this backer. */
982         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node,
983                        &all_ofproto_dpifs) {
984             if (ofproto->backer == backer) {
985                 sset_clear(&ofproto->port_poll_set);
986                 ofproto->port_poll_errno = error;
987             }
988         }
989     }
990
991     return 0;
992 }
993
994 static int
995 type_run_fast(const char *type)
996 {
997     struct dpif_backer *backer;
998     unsigned int work;
999
1000     backer = shash_find_data(&all_dpif_backers, type);
1001     if (!backer) {
1002         /* This is not necessarily a problem, since backers are only
1003          * created on demand. */
1004         return 0;
1005     }
1006
1007     /* Handle one or more batches of upcalls, until there's nothing left to do
1008      * or until we do a fixed total amount of work.
1009      *
1010      * We do work in batches because it can be much cheaper to set up a number
1011      * of flows and fire off their patches all at once.  We do multiple batches
1012      * because in some cases handling a packet can cause another packet to be
1013      * queued almost immediately as part of the return flow.  Both
1014      * optimizations can make major improvements on some benchmarks and
1015      * presumably for real traffic as well. */
1016     work = 0;
1017     while (work < FLOW_MISS_MAX_BATCH) {
1018         int retval = handle_upcalls(backer, FLOW_MISS_MAX_BATCH - work);
1019         if (retval <= 0) {
1020             return -retval;
1021         }
1022         work += retval;
1023     }
1024
1025     return 0;
1026 }
1027
1028 static void
1029 type_wait(const char *type)
1030 {
1031     struct dpif_backer *backer;
1032
1033     backer = shash_find_data(&all_dpif_backers, type);
1034     if (!backer) {
1035         /* This is not necessarily a problem, since backers are only
1036          * created on demand. */
1037         return;
1038     }
1039
1040     timer_wait(&backer->next_expiration);
1041 }
1042 \f
1043 /* Basic life-cycle. */
1044
1045 static int add_internal_flows(struct ofproto_dpif *);
1046
1047 static struct ofproto *
1048 alloc(void)
1049 {
1050     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
1051     return &ofproto->up;
1052 }
1053
1054 static void
1055 dealloc(struct ofproto *ofproto_)
1056 {
1057     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1058     free(ofproto);
1059 }
1060
1061 static void
1062 close_dpif_backer(struct dpif_backer *backer)
1063 {
1064     struct shash_node *node;
1065
1066     ovs_assert(backer->refcount > 0);
1067
1068     if (--backer->refcount) {
1069         return;
1070     }
1071
1072     drop_key_clear(backer);
1073     hmap_destroy(&backer->drop_keys);
1074
1075     simap_destroy(&backer->tnl_backers);
1076     hmap_destroy(&backer->odp_to_ofport_map);
1077     node = shash_find(&all_dpif_backers, backer->type);
1078     free(backer->type);
1079     shash_delete(&all_dpif_backers, node);
1080     dpif_close(backer->dpif);
1081
1082     free(backer);
1083 }
1084
1085 /* Datapath port slated for removal from datapath. */
1086 struct odp_garbage {
1087     struct list list_node;
1088     uint32_t odp_port;
1089 };
1090
1091 static int
1092 open_dpif_backer(const char *type, struct dpif_backer **backerp)
1093 {
1094     struct dpif_backer *backer;
1095     struct dpif_port_dump port_dump;
1096     struct dpif_port port;
1097     struct shash_node *node;
1098     struct list garbage_list;
1099     struct odp_garbage *garbage, *next;
1100     struct sset names;
1101     char *backer_name;
1102     const char *name;
1103     int error;
1104
1105     backer = shash_find_data(&all_dpif_backers, type);
1106     if (backer) {
1107         backer->refcount++;
1108         *backerp = backer;
1109         return 0;
1110     }
1111
1112     backer_name = xasprintf("ovs-%s", type);
1113
1114     /* Remove any existing datapaths, since we assume we're the only
1115      * userspace controlling the datapath. */
1116     sset_init(&names);
1117     dp_enumerate_names(type, &names);
1118     SSET_FOR_EACH(name, &names) {
1119         struct dpif *old_dpif;
1120
1121         /* Don't remove our backer if it exists. */
1122         if (!strcmp(name, backer_name)) {
1123             continue;
1124         }
1125
1126         if (dpif_open(name, type, &old_dpif)) {
1127             VLOG_WARN("couldn't open old datapath %s to remove it", name);
1128         } else {
1129             dpif_delete(old_dpif);
1130             dpif_close(old_dpif);
1131         }
1132     }
1133     sset_destroy(&names);
1134
1135     backer = xmalloc(sizeof *backer);
1136
1137     error = dpif_create_and_open(backer_name, type, &backer->dpif);
1138     free(backer_name);
1139     if (error) {
1140         VLOG_ERR("failed to open datapath of type %s: %s", type,
1141                  strerror(error));
1142         free(backer);
1143         return error;
1144     }
1145
1146     backer->type = xstrdup(type);
1147     backer->refcount = 1;
1148     hmap_init(&backer->odp_to_ofport_map);
1149     hmap_init(&backer->drop_keys);
1150     timer_set_duration(&backer->next_expiration, 1000);
1151     backer->need_revalidate = 0;
1152     simap_init(&backer->tnl_backers);
1153     tag_set_init(&backer->revalidate_set);
1154     *backerp = backer;
1155
1156     dpif_flow_flush(backer->dpif);
1157
1158     /* Loop through the ports already on the datapath and remove any
1159      * that we don't need anymore. */
1160     list_init(&garbage_list);
1161     dpif_port_dump_start(&port_dump, backer->dpif);
1162     while (dpif_port_dump_next(&port_dump, &port)) {
1163         node = shash_find(&init_ofp_ports, port.name);
1164         if (!node && strcmp(port.name, dpif_base_name(backer->dpif))) {
1165             garbage = xmalloc(sizeof *garbage);
1166             garbage->odp_port = port.port_no;
1167             list_push_front(&garbage_list, &garbage->list_node);
1168         }
1169     }
1170     dpif_port_dump_done(&port_dump);
1171
1172     LIST_FOR_EACH_SAFE (garbage, next, list_node, &garbage_list) {
1173         dpif_port_del(backer->dpif, garbage->odp_port);
1174         list_remove(&garbage->list_node);
1175         free(garbage);
1176     }
1177
1178     shash_add(&all_dpif_backers, type, backer);
1179
1180     error = dpif_recv_set(backer->dpif, true);
1181     if (error) {
1182         VLOG_ERR("failed to listen on datapath of type %s: %s",
1183                  type, strerror(error));
1184         close_dpif_backer(backer);
1185         return error;
1186     }
1187
1188     return error;
1189 }
1190
1191 static int
1192 construct(struct ofproto *ofproto_)
1193 {
1194     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1195     struct shash_node *node, *next;
1196     int max_ports;
1197     int error;
1198     int i;
1199
1200     error = open_dpif_backer(ofproto->up.type, &ofproto->backer);
1201     if (error) {
1202         return error;
1203     }
1204
1205     max_ports = dpif_get_max_ports(ofproto->backer->dpif);
1206     ofproto_init_max_ports(ofproto_, MIN(max_ports, OFPP_MAX));
1207
1208     ofproto->n_matches = 0;
1209
1210     ofproto->netflow = NULL;
1211     ofproto->sflow = NULL;
1212     ofproto->stp = NULL;
1213     hmap_init(&ofproto->bundles);
1214     ofproto->ml = mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME);
1215     for (i = 0; i < MAX_MIRRORS; i++) {
1216         ofproto->mirrors[i] = NULL;
1217     }
1218     ofproto->has_bonded_bundles = false;
1219
1220     hmap_init(&ofproto->facets);
1221     hmap_init(&ofproto->subfacets);
1222     ofproto->governor = NULL;
1223
1224     for (i = 0; i < N_TABLES; i++) {
1225         struct table_dpif *table = &ofproto->tables[i];
1226
1227         table->catchall_table = NULL;
1228         table->other_table = NULL;
1229         table->basis = random_uint32();
1230     }
1231
1232     list_init(&ofproto->completions);
1233
1234     ofproto_dpif_unixctl_init();
1235
1236     ofproto->has_mirrors = false;
1237     ofproto->has_bundle_action = false;
1238
1239     hmap_init(&ofproto->vlandev_map);
1240     hmap_init(&ofproto->realdev_vid_map);
1241
1242     sset_init(&ofproto->ports);
1243     sset_init(&ofproto->ghost_ports);
1244     sset_init(&ofproto->port_poll_set);
1245     ofproto->port_poll_errno = 0;
1246
1247     SHASH_FOR_EACH_SAFE (node, next, &init_ofp_ports) {
1248         struct iface_hint *iface_hint = node->data;
1249
1250         if (!strcmp(iface_hint->br_name, ofproto->up.name)) {
1251             /* Check if the datapath already has this port. */
1252             if (dpif_port_exists(ofproto->backer->dpif, node->name)) {
1253                 sset_add(&ofproto->ports, node->name);
1254             }
1255
1256             free(iface_hint->br_name);
1257             free(iface_hint->br_type);
1258             free(iface_hint);
1259             shash_delete(&init_ofp_ports, node);
1260         }
1261     }
1262
1263     hmap_insert(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node,
1264                 hash_string(ofproto->up.name, 0));
1265     memset(&ofproto->stats, 0, sizeof ofproto->stats);
1266
1267     ofproto_init_tables(ofproto_, N_TABLES);
1268     error = add_internal_flows(ofproto);
1269     ofproto->up.tables[TBL_INTERNAL].flags = OFTABLE_HIDDEN | OFTABLE_READONLY;
1270
1271     return error;
1272 }
1273
1274 static int
1275 add_internal_flow(struct ofproto_dpif *ofproto, int id,
1276                   const struct ofpbuf *ofpacts, struct rule_dpif **rulep)
1277 {
1278     struct ofputil_flow_mod fm;
1279     int error;
1280
1281     match_init_catchall(&fm.match);
1282     fm.priority = 0;
1283     match_set_reg(&fm.match, 0, id);
1284     fm.new_cookie = htonll(0);
1285     fm.cookie = htonll(0);
1286     fm.cookie_mask = htonll(0);
1287     fm.table_id = TBL_INTERNAL;
1288     fm.command = OFPFC_ADD;
1289     fm.idle_timeout = 0;
1290     fm.hard_timeout = 0;
1291     fm.buffer_id = 0;
1292     fm.out_port = 0;
1293     fm.flags = 0;
1294     fm.ofpacts = ofpacts->data;
1295     fm.ofpacts_len = ofpacts->size;
1296
1297     error = ofproto_flow_mod(&ofproto->up, &fm);
1298     if (error) {
1299         VLOG_ERR_RL(&rl, "failed to add internal flow %d (%s)",
1300                     id, ofperr_to_string(error));
1301         return error;
1302     }
1303
1304     *rulep = rule_dpif_lookup__(ofproto, &fm.match.flow, TBL_INTERNAL);
1305     ovs_assert(*rulep != NULL);
1306
1307     return 0;
1308 }
1309
1310 static int
1311 add_internal_flows(struct ofproto_dpif *ofproto)
1312 {
1313     struct ofpact_controller *controller;
1314     uint64_t ofpacts_stub[128 / 8];
1315     struct ofpbuf ofpacts;
1316     int error;
1317     int id;
1318
1319     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
1320     id = 1;
1321
1322     controller = ofpact_put_CONTROLLER(&ofpacts);
1323     controller->max_len = UINT16_MAX;
1324     controller->controller_id = 0;
1325     controller->reason = OFPR_NO_MATCH;
1326     ofpact_pad(&ofpacts);
1327
1328     error = add_internal_flow(ofproto, id++, &ofpacts, &ofproto->miss_rule);
1329     if (error) {
1330         return error;
1331     }
1332
1333     ofpbuf_clear(&ofpacts);
1334     error = add_internal_flow(ofproto, id++, &ofpacts,
1335                               &ofproto->no_packet_in_rule);
1336     return error;
1337 }
1338
1339 static void
1340 complete_operations(struct ofproto_dpif *ofproto)
1341 {
1342     struct dpif_completion *c, *next;
1343
1344     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
1345         ofoperation_complete(c->op, 0);
1346         list_remove(&c->list_node);
1347         free(c);
1348     }
1349 }
1350
1351 static void
1352 destruct(struct ofproto *ofproto_)
1353 {
1354     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1355     struct rule_dpif *rule, *next_rule;
1356     struct oftable *table;
1357     int i;
1358
1359     hmap_remove(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node);
1360     complete_operations(ofproto);
1361
1362     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
1363         struct cls_cursor cursor;
1364
1365         cls_cursor_init(&cursor, &table->cls, NULL);
1366         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
1367             ofproto_rule_destroy(&rule->up);
1368         }
1369     }
1370
1371     for (i = 0; i < MAX_MIRRORS; i++) {
1372         mirror_destroy(ofproto->mirrors[i]);
1373     }
1374
1375     netflow_destroy(ofproto->netflow);
1376     dpif_sflow_destroy(ofproto->sflow);
1377     hmap_destroy(&ofproto->bundles);
1378     mac_learning_destroy(ofproto->ml);
1379
1380     hmap_destroy(&ofproto->facets);
1381     hmap_destroy(&ofproto->subfacets);
1382     governor_destroy(ofproto->governor);
1383
1384     hmap_destroy(&ofproto->vlandev_map);
1385     hmap_destroy(&ofproto->realdev_vid_map);
1386
1387     sset_destroy(&ofproto->ports);
1388     sset_destroy(&ofproto->ghost_ports);
1389     sset_destroy(&ofproto->port_poll_set);
1390
1391     close_dpif_backer(ofproto->backer);
1392 }
1393
1394 static int
1395 run_fast(struct ofproto *ofproto_)
1396 {
1397     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1398     struct ofport_dpif *ofport;
1399
1400     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1401         port_run_fast(ofport);
1402     }
1403
1404     return 0;
1405 }
1406
1407 static int
1408 run(struct ofproto *ofproto_)
1409 {
1410     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1411     struct ofport_dpif *ofport;
1412     struct ofbundle *bundle;
1413     int error;
1414
1415     if (!clogged) {
1416         complete_operations(ofproto);
1417     }
1418
1419     error = run_fast(ofproto_);
1420     if (error) {
1421         return error;
1422     }
1423
1424     if (ofproto->netflow) {
1425         if (netflow_run(ofproto->netflow)) {
1426             send_netflow_active_timeouts(ofproto);
1427         }
1428     }
1429     if (ofproto->sflow) {
1430         dpif_sflow_run(ofproto->sflow);
1431     }
1432
1433     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1434         port_run(ofport);
1435     }
1436     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1437         bundle_run(bundle);
1438     }
1439
1440     stp_run(ofproto);
1441     mac_learning_run(ofproto->ml, &ofproto->backer->revalidate_set);
1442
1443     /* Check the consistency of a random facet, to aid debugging. */
1444     if (!hmap_is_empty(&ofproto->facets)
1445         && !ofproto->backer->need_revalidate) {
1446         struct facet *facet;
1447
1448         facet = CONTAINER_OF(hmap_random_node(&ofproto->facets),
1449                              struct facet, hmap_node);
1450         if (!tag_set_intersects(&ofproto->backer->revalidate_set,
1451                                 facet->tags)) {
1452             if (!facet_check_consistency(facet)) {
1453                 ofproto->backer->need_revalidate = REV_INCONSISTENCY;
1454             }
1455         }
1456     }
1457
1458     if (ofproto->governor) {
1459         size_t n_subfacets;
1460
1461         governor_run(ofproto->governor);
1462
1463         /* If the governor has shrunk to its minimum size and the number of
1464          * subfacets has dwindled, then drop the governor entirely.
1465          *
1466          * For hysteresis, the number of subfacets to drop the governor is
1467          * smaller than the number needed to trigger its creation. */
1468         n_subfacets = hmap_count(&ofproto->subfacets);
1469         if (n_subfacets * 4 < ofproto->up.flow_eviction_threshold
1470             && governor_is_idle(ofproto->governor)) {
1471             governor_destroy(ofproto->governor);
1472             ofproto->governor = NULL;
1473         }
1474     }
1475
1476     return 0;
1477 }
1478
1479 static void
1480 wait(struct ofproto *ofproto_)
1481 {
1482     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1483     struct ofport_dpif *ofport;
1484     struct ofbundle *bundle;
1485
1486     if (!clogged && !list_is_empty(&ofproto->completions)) {
1487         poll_immediate_wake();
1488     }
1489
1490     dpif_wait(ofproto->backer->dpif);
1491     dpif_recv_wait(ofproto->backer->dpif);
1492     if (ofproto->sflow) {
1493         dpif_sflow_wait(ofproto->sflow);
1494     }
1495     if (!tag_set_is_empty(&ofproto->backer->revalidate_set)) {
1496         poll_immediate_wake();
1497     }
1498     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1499         port_wait(ofport);
1500     }
1501     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1502         bundle_wait(bundle);
1503     }
1504     if (ofproto->netflow) {
1505         netflow_wait(ofproto->netflow);
1506     }
1507     mac_learning_wait(ofproto->ml);
1508     stp_wait(ofproto);
1509     if (ofproto->backer->need_revalidate) {
1510         /* Shouldn't happen, but if it does just go around again. */
1511         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1512         poll_immediate_wake();
1513     }
1514     if (ofproto->governor) {
1515         governor_wait(ofproto->governor);
1516     }
1517 }
1518
1519 static void
1520 get_memory_usage(const struct ofproto *ofproto_, struct simap *usage)
1521 {
1522     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1523
1524     simap_increase(usage, "facets", hmap_count(&ofproto->facets));
1525     simap_increase(usage, "subfacets", hmap_count(&ofproto->subfacets));
1526 }
1527
1528 static void
1529 flush(struct ofproto *ofproto_)
1530 {
1531     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1532     struct subfacet *subfacet, *next_subfacet;
1533     struct subfacet *batch[SUBFACET_DESTROY_MAX_BATCH];
1534     int n_batch;
1535
1536     n_batch = 0;
1537     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
1538                         &ofproto->subfacets) {
1539         if (subfacet->path != SF_NOT_INSTALLED) {
1540             batch[n_batch++] = subfacet;
1541             if (n_batch >= SUBFACET_DESTROY_MAX_BATCH) {
1542                 subfacet_destroy_batch(ofproto, batch, n_batch);
1543                 n_batch = 0;
1544             }
1545         } else {
1546             subfacet_destroy(subfacet);
1547         }
1548     }
1549
1550     if (n_batch > 0) {
1551         subfacet_destroy_batch(ofproto, batch, n_batch);
1552     }
1553 }
1554
1555 static void
1556 get_features(struct ofproto *ofproto_ OVS_UNUSED,
1557              bool *arp_match_ip, enum ofputil_action_bitmap *actions)
1558 {
1559     *arp_match_ip = true;
1560     *actions = (OFPUTIL_A_OUTPUT |
1561                 OFPUTIL_A_SET_VLAN_VID |
1562                 OFPUTIL_A_SET_VLAN_PCP |
1563                 OFPUTIL_A_STRIP_VLAN |
1564                 OFPUTIL_A_SET_DL_SRC |
1565                 OFPUTIL_A_SET_DL_DST |
1566                 OFPUTIL_A_SET_NW_SRC |
1567                 OFPUTIL_A_SET_NW_DST |
1568                 OFPUTIL_A_SET_NW_TOS |
1569                 OFPUTIL_A_SET_TP_SRC |
1570                 OFPUTIL_A_SET_TP_DST |
1571                 OFPUTIL_A_ENQUEUE);
1572 }
1573
1574 static void
1575 get_tables(struct ofproto *ofproto_, struct ofp12_table_stats *ots)
1576 {
1577     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1578     struct dpif_dp_stats s;
1579
1580     strcpy(ots->name, "classifier");
1581
1582     dpif_get_dp_stats(ofproto->backer->dpif, &s);
1583
1584     ots->lookup_count = htonll(s.n_hit + s.n_missed);
1585     ots->matched_count = htonll(s.n_hit + ofproto->n_matches);
1586 }
1587
1588 static struct ofport *
1589 port_alloc(void)
1590 {
1591     struct ofport_dpif *port = xmalloc(sizeof *port);
1592     return &port->up;
1593 }
1594
1595 static void
1596 port_dealloc(struct ofport *port_)
1597 {
1598     struct ofport_dpif *port = ofport_dpif_cast(port_);
1599     free(port);
1600 }
1601
1602 static int
1603 port_construct(struct ofport *port_)
1604 {
1605     struct ofport_dpif *port = ofport_dpif_cast(port_);
1606     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1607     const struct netdev *netdev = port->up.netdev;
1608     struct dpif_port dpif_port;
1609     int error;
1610
1611     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1612     port->bundle = NULL;
1613     port->cfm = NULL;
1614     port->tag = tag_create_random();
1615     port->may_enable = true;
1616     port->stp_port = NULL;
1617     port->stp_state = STP_DISABLED;
1618     port->tnl_port = NULL;
1619     hmap_init(&port->priorities);
1620     port->realdev_ofp_port = 0;
1621     port->vlandev_vid = 0;
1622     port->carrier_seq = netdev_get_carrier_resets(netdev);
1623
1624     if (netdev_vport_is_patch(netdev)) {
1625         /* XXX By bailing out here, we don't do required sFlow work. */
1626         port->odp_port = OVSP_NONE;
1627         return 0;
1628     }
1629
1630     error = dpif_port_query_by_name(ofproto->backer->dpif,
1631                                     netdev_vport_get_dpif_port(netdev),
1632                                     &dpif_port);
1633     if (error) {
1634         return error;
1635     }
1636
1637     port->odp_port = dpif_port.port_no;
1638
1639     if (netdev_get_tunnel_config(netdev)) {
1640         port->tnl_port = tnl_port_add(&port->up, port->odp_port);
1641     } else {
1642         /* Sanity-check that a mapping doesn't already exist.  This
1643          * shouldn't happen for non-tunnel ports. */
1644         if (odp_port_to_ofp_port(ofproto, port->odp_port) != OFPP_NONE) {
1645             VLOG_ERR("port %s already has an OpenFlow port number",
1646                      dpif_port.name);
1647             dpif_port_destroy(&dpif_port);
1648             return EBUSY;
1649         }
1650
1651         hmap_insert(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node,
1652                     hash_int(port->odp_port, 0));
1653     }
1654     dpif_port_destroy(&dpif_port);
1655
1656     if (ofproto->sflow) {
1657         dpif_sflow_add_port(ofproto->sflow, port_, port->odp_port);
1658     }
1659
1660     return 0;
1661 }
1662
1663 static void
1664 port_destruct(struct ofport *port_)
1665 {
1666     struct ofport_dpif *port = ofport_dpif_cast(port_);
1667     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1668     const char *dp_port_name = netdev_vport_get_dpif_port(port->up.netdev);
1669     const char *devname = netdev_get_name(port->up.netdev);
1670
1671     if (dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
1672         /* The underlying device is still there, so delete it.  This
1673          * happens when the ofproto is being destroyed, since the caller
1674          * assumes that removal of attached ports will happen as part of
1675          * destruction. */
1676         if (!port->tnl_port) {
1677             dpif_port_del(ofproto->backer->dpif, port->odp_port);
1678         }
1679         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1680     }
1681
1682     if (port->odp_port != OVSP_NONE && !port->tnl_port) {
1683         hmap_remove(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node);
1684     }
1685
1686     tnl_port_del(port->tnl_port);
1687     sset_find_and_delete(&ofproto->ports, devname);
1688     sset_find_and_delete(&ofproto->ghost_ports, devname);
1689     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1690     bundle_remove(port_);
1691     set_cfm(port_, NULL);
1692     if (ofproto->sflow) {
1693         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
1694     }
1695
1696     ofport_clear_priorities(port);
1697     hmap_destroy(&port->priorities);
1698 }
1699
1700 static void
1701 port_modified(struct ofport *port_)
1702 {
1703     struct ofport_dpif *port = ofport_dpif_cast(port_);
1704
1705     if (port->bundle && port->bundle->bond) {
1706         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
1707     }
1708 }
1709
1710 static void
1711 port_reconfigured(struct ofport *port_, enum ofputil_port_config old_config)
1712 {
1713     struct ofport_dpif *port = ofport_dpif_cast(port_);
1714     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1715     enum ofputil_port_config changed = old_config ^ port->up.pp.config;
1716
1717     if (changed & (OFPUTIL_PC_NO_RECV | OFPUTIL_PC_NO_RECV_STP |
1718                    OFPUTIL_PC_NO_FWD | OFPUTIL_PC_NO_FLOOD |
1719                    OFPUTIL_PC_NO_PACKET_IN)) {
1720         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1721
1722         if (changed & OFPUTIL_PC_NO_FLOOD && port->bundle) {
1723             bundle_update(port->bundle);
1724         }
1725     }
1726 }
1727
1728 static int
1729 set_sflow(struct ofproto *ofproto_,
1730           const struct ofproto_sflow_options *sflow_options)
1731 {
1732     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1733     struct dpif_sflow *ds = ofproto->sflow;
1734
1735     if (sflow_options) {
1736         if (!ds) {
1737             struct ofport_dpif *ofport;
1738
1739             ds = ofproto->sflow = dpif_sflow_create();
1740             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1741                 dpif_sflow_add_port(ds, &ofport->up, ofport->odp_port);
1742             }
1743             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1744         }
1745         dpif_sflow_set_options(ds, sflow_options);
1746     } else {
1747         if (ds) {
1748             dpif_sflow_destroy(ds);
1749             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1750             ofproto->sflow = NULL;
1751         }
1752     }
1753     return 0;
1754 }
1755
1756 static int
1757 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
1758 {
1759     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1760     int error;
1761
1762     if (!s) {
1763         error = 0;
1764     } else {
1765         if (!ofport->cfm) {
1766             struct ofproto_dpif *ofproto;
1767
1768             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1769             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1770             ofport->cfm = cfm_create(netdev_get_name(ofport->up.netdev));
1771         }
1772
1773         if (cfm_configure(ofport->cfm, s)) {
1774             return 0;
1775         }
1776
1777         error = EINVAL;
1778     }
1779     cfm_destroy(ofport->cfm);
1780     ofport->cfm = NULL;
1781     return error;
1782 }
1783
1784 static int
1785 get_cfm_fault(const struct ofport *ofport_)
1786 {
1787     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1788
1789     return ofport->cfm ? cfm_get_fault(ofport->cfm) : -1;
1790 }
1791
1792 static int
1793 get_cfm_opup(const struct ofport *ofport_)
1794 {
1795     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1796
1797     return ofport->cfm ? cfm_get_opup(ofport->cfm) : -1;
1798 }
1799
1800 static int
1801 get_cfm_remote_mpids(const struct ofport *ofport_, const uint64_t **rmps,
1802                      size_t *n_rmps)
1803 {
1804     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1805
1806     if (ofport->cfm) {
1807         cfm_get_remote_mpids(ofport->cfm, rmps, n_rmps);
1808         return 0;
1809     } else {
1810         return -1;
1811     }
1812 }
1813
1814 static int
1815 get_cfm_health(const struct ofport *ofport_)
1816 {
1817     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1818
1819     return ofport->cfm ? cfm_get_health(ofport->cfm) : -1;
1820 }
1821 \f
1822 /* Spanning Tree. */
1823
1824 static void
1825 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
1826 {
1827     struct ofproto_dpif *ofproto = ofproto_;
1828     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
1829     struct ofport_dpif *ofport;
1830
1831     ofport = stp_port_get_aux(sp);
1832     if (!ofport) {
1833         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
1834                      ofproto->up.name, port_num);
1835     } else {
1836         struct eth_header *eth = pkt->l2;
1837
1838         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
1839         if (eth_addr_is_zero(eth->eth_src)) {
1840             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
1841                          "with unknown MAC", ofproto->up.name, port_num);
1842         } else {
1843             send_packet(ofport, pkt);
1844         }
1845     }
1846     ofpbuf_delete(pkt);
1847 }
1848
1849 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
1850 static int
1851 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
1852 {
1853     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1854
1855     /* Only revalidate flows if the configuration changed. */
1856     if (!s != !ofproto->stp) {
1857         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1858     }
1859
1860     if (s) {
1861         if (!ofproto->stp) {
1862             ofproto->stp = stp_create(ofproto_->name, s->system_id,
1863                                       send_bpdu_cb, ofproto);
1864             ofproto->stp_last_tick = time_msec();
1865         }
1866
1867         stp_set_bridge_id(ofproto->stp, s->system_id);
1868         stp_set_bridge_priority(ofproto->stp, s->priority);
1869         stp_set_hello_time(ofproto->stp, s->hello_time);
1870         stp_set_max_age(ofproto->stp, s->max_age);
1871         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
1872     }  else {
1873         struct ofport *ofport;
1874
1875         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
1876             set_stp_port(ofport, NULL);
1877         }
1878
1879         stp_destroy(ofproto->stp);
1880         ofproto->stp = NULL;
1881     }
1882
1883     return 0;
1884 }
1885
1886 static int
1887 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
1888 {
1889     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1890
1891     if (ofproto->stp) {
1892         s->enabled = true;
1893         s->bridge_id = stp_get_bridge_id(ofproto->stp);
1894         s->designated_root = stp_get_designated_root(ofproto->stp);
1895         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
1896     } else {
1897         s->enabled = false;
1898     }
1899
1900     return 0;
1901 }
1902
1903 static void
1904 update_stp_port_state(struct ofport_dpif *ofport)
1905 {
1906     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1907     enum stp_state state;
1908
1909     /* Figure out new state. */
1910     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
1911                              : STP_DISABLED;
1912
1913     /* Update state. */
1914     if (ofport->stp_state != state) {
1915         enum ofputil_port_state of_state;
1916         bool fwd_change;
1917
1918         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
1919                     netdev_get_name(ofport->up.netdev),
1920                     stp_state_name(ofport->stp_state),
1921                     stp_state_name(state));
1922         if (stp_learn_in_state(ofport->stp_state)
1923                 != stp_learn_in_state(state)) {
1924             /* xxx Learning action flows should also be flushed. */
1925             mac_learning_flush(ofproto->ml,
1926                                &ofproto->backer->revalidate_set);
1927         }
1928         fwd_change = stp_forward_in_state(ofport->stp_state)
1929                         != stp_forward_in_state(state);
1930
1931         ofproto->backer->need_revalidate = REV_STP;
1932         ofport->stp_state = state;
1933         ofport->stp_state_entered = time_msec();
1934
1935         if (fwd_change && ofport->bundle) {
1936             bundle_update(ofport->bundle);
1937         }
1938
1939         /* Update the STP state bits in the OpenFlow port description. */
1940         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
1941         of_state |= (state == STP_LISTENING ? OFPUTIL_PS_STP_LISTEN
1942                      : state == STP_LEARNING ? OFPUTIL_PS_STP_LEARN
1943                      : state == STP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
1944                      : state == STP_BLOCKING ?  OFPUTIL_PS_STP_BLOCK
1945                      : 0);
1946         ofproto_port_set_state(&ofport->up, of_state);
1947     }
1948 }
1949
1950 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
1951  * caller is responsible for assigning STP port numbers and ensuring
1952  * there are no duplicates. */
1953 static int
1954 set_stp_port(struct ofport *ofport_,
1955              const struct ofproto_port_stp_settings *s)
1956 {
1957     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1958     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1959     struct stp_port *sp = ofport->stp_port;
1960
1961     if (!s || !s->enable) {
1962         if (sp) {
1963             ofport->stp_port = NULL;
1964             stp_port_disable(sp);
1965             update_stp_port_state(ofport);
1966         }
1967         return 0;
1968     } else if (sp && stp_port_no(sp) != s->port_num
1969             && ofport == stp_port_get_aux(sp)) {
1970         /* The port-id changed, so disable the old one if it's not
1971          * already in use by another port. */
1972         stp_port_disable(sp);
1973     }
1974
1975     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
1976     stp_port_enable(sp);
1977
1978     stp_port_set_aux(sp, ofport);
1979     stp_port_set_priority(sp, s->priority);
1980     stp_port_set_path_cost(sp, s->path_cost);
1981
1982     update_stp_port_state(ofport);
1983
1984     return 0;
1985 }
1986
1987 static int
1988 get_stp_port_status(struct ofport *ofport_,
1989                     struct ofproto_port_stp_status *s)
1990 {
1991     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1992     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1993     struct stp_port *sp = ofport->stp_port;
1994
1995     if (!ofproto->stp || !sp) {
1996         s->enabled = false;
1997         return 0;
1998     }
1999
2000     s->enabled = true;
2001     s->port_id = stp_port_get_id(sp);
2002     s->state = stp_port_get_state(sp);
2003     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
2004     s->role = stp_port_get_role(sp);
2005     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
2006
2007     return 0;
2008 }
2009
2010 static void
2011 stp_run(struct ofproto_dpif *ofproto)
2012 {
2013     if (ofproto->stp) {
2014         long long int now = time_msec();
2015         long long int elapsed = now - ofproto->stp_last_tick;
2016         struct stp_port *sp;
2017
2018         if (elapsed > 0) {
2019             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
2020             ofproto->stp_last_tick = now;
2021         }
2022         while (stp_get_changed_port(ofproto->stp, &sp)) {
2023             struct ofport_dpif *ofport = stp_port_get_aux(sp);
2024
2025             if (ofport) {
2026                 update_stp_port_state(ofport);
2027             }
2028         }
2029
2030         if (stp_check_and_reset_fdb_flush(ofproto->stp)) {
2031             mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
2032         }
2033     }
2034 }
2035
2036 static void
2037 stp_wait(struct ofproto_dpif *ofproto)
2038 {
2039     if (ofproto->stp) {
2040         poll_timer_wait(1000);
2041     }
2042 }
2043
2044 /* Returns true if STP should process 'flow'. */
2045 static bool
2046 stp_should_process_flow(const struct flow *flow)
2047 {
2048     return eth_addr_equals(flow->dl_dst, eth_addr_stp);
2049 }
2050
2051 static void
2052 stp_process_packet(const struct ofport_dpif *ofport,
2053                    const struct ofpbuf *packet)
2054 {
2055     struct ofpbuf payload = *packet;
2056     struct eth_header *eth = payload.data;
2057     struct stp_port *sp = ofport->stp_port;
2058
2059     /* Sink packets on ports that have STP disabled when the bridge has
2060      * STP enabled. */
2061     if (!sp || stp_port_get_state(sp) == STP_DISABLED) {
2062         return;
2063     }
2064
2065     /* Trim off padding on payload. */
2066     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
2067         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
2068     }
2069
2070     if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
2071         stp_received_bpdu(sp, payload.data, payload.size);
2072     }
2073 }
2074 \f
2075 static struct priority_to_dscp *
2076 get_priority(const struct ofport_dpif *ofport, uint32_t priority)
2077 {
2078     struct priority_to_dscp *pdscp;
2079     uint32_t hash;
2080
2081     hash = hash_int(priority, 0);
2082     HMAP_FOR_EACH_IN_BUCKET (pdscp, hmap_node, hash, &ofport->priorities) {
2083         if (pdscp->priority == priority) {
2084             return pdscp;
2085         }
2086     }
2087     return NULL;
2088 }
2089
2090 static void
2091 ofport_clear_priorities(struct ofport_dpif *ofport)
2092 {
2093     struct priority_to_dscp *pdscp, *next;
2094
2095     HMAP_FOR_EACH_SAFE (pdscp, next, hmap_node, &ofport->priorities) {
2096         hmap_remove(&ofport->priorities, &pdscp->hmap_node);
2097         free(pdscp);
2098     }
2099 }
2100
2101 static int
2102 set_queues(struct ofport *ofport_,
2103            const struct ofproto_port_queue *qdscp_list,
2104            size_t n_qdscp)
2105 {
2106     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2107     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2108     struct hmap new = HMAP_INITIALIZER(&new);
2109     size_t i;
2110
2111     for (i = 0; i < n_qdscp; i++) {
2112         struct priority_to_dscp *pdscp;
2113         uint32_t priority;
2114         uint8_t dscp;
2115
2116         dscp = (qdscp_list[i].dscp << 2) & IP_DSCP_MASK;
2117         if (dpif_queue_to_priority(ofproto->backer->dpif, qdscp_list[i].queue,
2118                                    &priority)) {
2119             continue;
2120         }
2121
2122         pdscp = get_priority(ofport, priority);
2123         if (pdscp) {
2124             hmap_remove(&ofport->priorities, &pdscp->hmap_node);
2125         } else {
2126             pdscp = xmalloc(sizeof *pdscp);
2127             pdscp->priority = priority;
2128             pdscp->dscp = dscp;
2129             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2130         }
2131
2132         if (pdscp->dscp != dscp) {
2133             pdscp->dscp = dscp;
2134             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2135         }
2136
2137         hmap_insert(&new, &pdscp->hmap_node, hash_int(pdscp->priority, 0));
2138     }
2139
2140     if (!hmap_is_empty(&ofport->priorities)) {
2141         ofport_clear_priorities(ofport);
2142         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2143     }
2144
2145     hmap_swap(&new, &ofport->priorities);
2146     hmap_destroy(&new);
2147
2148     return 0;
2149 }
2150 \f
2151 /* Bundles. */
2152
2153 /* Expires all MAC learning entries associated with 'bundle' and forces its
2154  * ofproto to revalidate every flow.
2155  *
2156  * Normally MAC learning entries are removed only from the ofproto associated
2157  * with 'bundle', but if 'all_ofprotos' is true, then the MAC learning entries
2158  * are removed from every ofproto.  When patch ports and SLB bonds are in use
2159  * and a VM migration happens and the gratuitous ARPs are somehow lost, this
2160  * avoids a MAC_ENTRY_IDLE_TIME delay before the migrated VM can communicate
2161  * with the host from which it migrated. */
2162 static void
2163 bundle_flush_macs(struct ofbundle *bundle, bool all_ofprotos)
2164 {
2165     struct ofproto_dpif *ofproto = bundle->ofproto;
2166     struct mac_learning *ml = ofproto->ml;
2167     struct mac_entry *mac, *next_mac;
2168
2169     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2170     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
2171         if (mac->port.p == bundle) {
2172             if (all_ofprotos) {
2173                 struct ofproto_dpif *o;
2174
2175                 HMAP_FOR_EACH (o, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2176                     if (o != ofproto) {
2177                         struct mac_entry *e;
2178
2179                         e = mac_learning_lookup(o->ml, mac->mac, mac->vlan,
2180                                                 NULL);
2181                         if (e) {
2182                             mac_learning_expire(o->ml, e);
2183                         }
2184                     }
2185                 }
2186             }
2187
2188             mac_learning_expire(ml, mac);
2189         }
2190     }
2191 }
2192
2193 static struct ofbundle *
2194 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
2195 {
2196     struct ofbundle *bundle;
2197
2198     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
2199                              &ofproto->bundles) {
2200         if (bundle->aux == aux) {
2201             return bundle;
2202         }
2203     }
2204     return NULL;
2205 }
2206
2207 /* Looks up each of the 'n_auxes' pointers in 'auxes' as bundles and adds the
2208  * ones that are found to 'bundles'. */
2209 static void
2210 bundle_lookup_multiple(struct ofproto_dpif *ofproto,
2211                        void **auxes, size_t n_auxes,
2212                        struct hmapx *bundles)
2213 {
2214     size_t i;
2215
2216     hmapx_init(bundles);
2217     for (i = 0; i < n_auxes; i++) {
2218         struct ofbundle *bundle = bundle_lookup(ofproto, auxes[i]);
2219         if (bundle) {
2220             hmapx_add(bundles, bundle);
2221         }
2222     }
2223 }
2224
2225 static void
2226 bundle_update(struct ofbundle *bundle)
2227 {
2228     struct ofport_dpif *port;
2229
2230     bundle->floodable = true;
2231     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2232         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2233             || !stp_forward_in_state(port->stp_state)) {
2234             bundle->floodable = false;
2235             break;
2236         }
2237     }
2238 }
2239
2240 static void
2241 bundle_del_port(struct ofport_dpif *port)
2242 {
2243     struct ofbundle *bundle = port->bundle;
2244
2245     bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2246
2247     list_remove(&port->bundle_node);
2248     port->bundle = NULL;
2249
2250     if (bundle->lacp) {
2251         lacp_slave_unregister(bundle->lacp, port);
2252     }
2253     if (bundle->bond) {
2254         bond_slave_unregister(bundle->bond, port);
2255     }
2256
2257     bundle_update(bundle);
2258 }
2259
2260 static bool
2261 bundle_add_port(struct ofbundle *bundle, uint32_t ofp_port,
2262                 struct lacp_slave_settings *lacp,
2263                 uint32_t bond_stable_id)
2264 {
2265     struct ofport_dpif *port;
2266
2267     port = get_ofp_port(bundle->ofproto, ofp_port);
2268     if (!port) {
2269         return false;
2270     }
2271
2272     if (port->bundle != bundle) {
2273         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2274         if (port->bundle) {
2275             bundle_del_port(port);
2276         }
2277
2278         port->bundle = bundle;
2279         list_push_back(&bundle->ports, &port->bundle_node);
2280         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2281             || !stp_forward_in_state(port->stp_state)) {
2282             bundle->floodable = false;
2283         }
2284     }
2285     if (lacp) {
2286         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2287         lacp_slave_register(bundle->lacp, port, lacp);
2288     }
2289
2290     port->bond_stable_id = bond_stable_id;
2291
2292     return true;
2293 }
2294
2295 static void
2296 bundle_destroy(struct ofbundle *bundle)
2297 {
2298     struct ofproto_dpif *ofproto;
2299     struct ofport_dpif *port, *next_port;
2300     int i;
2301
2302     if (!bundle) {
2303         return;
2304     }
2305
2306     ofproto = bundle->ofproto;
2307     for (i = 0; i < MAX_MIRRORS; i++) {
2308         struct ofmirror *m = ofproto->mirrors[i];
2309         if (m) {
2310             if (m->out == bundle) {
2311                 mirror_destroy(m);
2312             } else if (hmapx_find_and_delete(&m->srcs, bundle)
2313                        || hmapx_find_and_delete(&m->dsts, bundle)) {
2314                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2315             }
2316         }
2317     }
2318
2319     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2320         bundle_del_port(port);
2321     }
2322
2323     bundle_flush_macs(bundle, true);
2324     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
2325     free(bundle->name);
2326     free(bundle->trunks);
2327     lacp_destroy(bundle->lacp);
2328     bond_destroy(bundle->bond);
2329     free(bundle);
2330 }
2331
2332 static int
2333 bundle_set(struct ofproto *ofproto_, void *aux,
2334            const struct ofproto_bundle_settings *s)
2335 {
2336     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2337     bool need_flush = false;
2338     struct ofport_dpif *port;
2339     struct ofbundle *bundle;
2340     unsigned long *trunks;
2341     int vlan;
2342     size_t i;
2343     bool ok;
2344
2345     if (!s) {
2346         bundle_destroy(bundle_lookup(ofproto, aux));
2347         return 0;
2348     }
2349
2350     ovs_assert(s->n_slaves == 1 || s->bond != NULL);
2351     ovs_assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
2352
2353     bundle = bundle_lookup(ofproto, aux);
2354     if (!bundle) {
2355         bundle = xmalloc(sizeof *bundle);
2356
2357         bundle->ofproto = ofproto;
2358         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
2359                     hash_pointer(aux, 0));
2360         bundle->aux = aux;
2361         bundle->name = NULL;
2362
2363         list_init(&bundle->ports);
2364         bundle->vlan_mode = PORT_VLAN_TRUNK;
2365         bundle->vlan = -1;
2366         bundle->trunks = NULL;
2367         bundle->use_priority_tags = s->use_priority_tags;
2368         bundle->lacp = NULL;
2369         bundle->bond = NULL;
2370
2371         bundle->floodable = true;
2372
2373         bundle->src_mirrors = 0;
2374         bundle->dst_mirrors = 0;
2375         bundle->mirror_out = 0;
2376     }
2377
2378     if (!bundle->name || strcmp(s->name, bundle->name)) {
2379         free(bundle->name);
2380         bundle->name = xstrdup(s->name);
2381     }
2382
2383     /* LACP. */
2384     if (s->lacp) {
2385         if (!bundle->lacp) {
2386             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2387             bundle->lacp = lacp_create();
2388         }
2389         lacp_configure(bundle->lacp, s->lacp);
2390     } else {
2391         lacp_destroy(bundle->lacp);
2392         bundle->lacp = NULL;
2393     }
2394
2395     /* Update set of ports. */
2396     ok = true;
2397     for (i = 0; i < s->n_slaves; i++) {
2398         if (!bundle_add_port(bundle, s->slaves[i],
2399                              s->lacp ? &s->lacp_slaves[i] : NULL,
2400                              s->bond_stable_ids ? s->bond_stable_ids[i] : 0)) {
2401             ok = false;
2402         }
2403     }
2404     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
2405         struct ofport_dpif *next_port;
2406
2407         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2408             for (i = 0; i < s->n_slaves; i++) {
2409                 if (s->slaves[i] == port->up.ofp_port) {
2410                     goto found;
2411                 }
2412             }
2413
2414             bundle_del_port(port);
2415         found: ;
2416         }
2417     }
2418     ovs_assert(list_size(&bundle->ports) <= s->n_slaves);
2419
2420     if (list_is_empty(&bundle->ports)) {
2421         bundle_destroy(bundle);
2422         return EINVAL;
2423     }
2424
2425     /* Set VLAN tagging mode */
2426     if (s->vlan_mode != bundle->vlan_mode
2427         || s->use_priority_tags != bundle->use_priority_tags) {
2428         bundle->vlan_mode = s->vlan_mode;
2429         bundle->use_priority_tags = s->use_priority_tags;
2430         need_flush = true;
2431     }
2432
2433     /* Set VLAN tag. */
2434     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
2435             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
2436             : 0);
2437     if (vlan != bundle->vlan) {
2438         bundle->vlan = vlan;
2439         need_flush = true;
2440     }
2441
2442     /* Get trunked VLANs. */
2443     switch (s->vlan_mode) {
2444     case PORT_VLAN_ACCESS:
2445         trunks = NULL;
2446         break;
2447
2448     case PORT_VLAN_TRUNK:
2449         trunks = CONST_CAST(unsigned long *, s->trunks);
2450         break;
2451
2452     case PORT_VLAN_NATIVE_UNTAGGED:
2453     case PORT_VLAN_NATIVE_TAGGED:
2454         if (vlan != 0 && (!s->trunks
2455                           || !bitmap_is_set(s->trunks, vlan)
2456                           || bitmap_is_set(s->trunks, 0))) {
2457             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
2458             if (s->trunks) {
2459                 trunks = bitmap_clone(s->trunks, 4096);
2460             } else {
2461                 trunks = bitmap_allocate1(4096);
2462             }
2463             bitmap_set1(trunks, vlan);
2464             bitmap_set0(trunks, 0);
2465         } else {
2466             trunks = CONST_CAST(unsigned long *, s->trunks);
2467         }
2468         break;
2469
2470     default:
2471         NOT_REACHED();
2472     }
2473     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
2474         free(bundle->trunks);
2475         if (trunks == s->trunks) {
2476             bundle->trunks = vlan_bitmap_clone(trunks);
2477         } else {
2478             bundle->trunks = trunks;
2479             trunks = NULL;
2480         }
2481         need_flush = true;
2482     }
2483     if (trunks != s->trunks) {
2484         free(trunks);
2485     }
2486
2487     /* Bonding. */
2488     if (!list_is_short(&bundle->ports)) {
2489         bundle->ofproto->has_bonded_bundles = true;
2490         if (bundle->bond) {
2491             if (bond_reconfigure(bundle->bond, s->bond)) {
2492                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2493             }
2494         } else {
2495             bundle->bond = bond_create(s->bond);
2496             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2497         }
2498
2499         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2500             bond_slave_register(bundle->bond, port, port->bond_stable_id,
2501                                 port->up.netdev);
2502         }
2503     } else {
2504         bond_destroy(bundle->bond);
2505         bundle->bond = NULL;
2506     }
2507
2508     /* If we changed something that would affect MAC learning, un-learn
2509      * everything on this port and force flow revalidation. */
2510     if (need_flush) {
2511         bundle_flush_macs(bundle, false);
2512     }
2513
2514     return 0;
2515 }
2516
2517 static void
2518 bundle_remove(struct ofport *port_)
2519 {
2520     struct ofport_dpif *port = ofport_dpif_cast(port_);
2521     struct ofbundle *bundle = port->bundle;
2522
2523     if (bundle) {
2524         bundle_del_port(port);
2525         if (list_is_empty(&bundle->ports)) {
2526             bundle_destroy(bundle);
2527         } else if (list_is_short(&bundle->ports)) {
2528             bond_destroy(bundle->bond);
2529             bundle->bond = NULL;
2530         }
2531     }
2532 }
2533
2534 static void
2535 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
2536 {
2537     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
2538     struct ofport_dpif *port = port_;
2539     uint8_t ea[ETH_ADDR_LEN];
2540     int error;
2541
2542     error = netdev_get_etheraddr(port->up.netdev, ea);
2543     if (!error) {
2544         struct ofpbuf packet;
2545         void *packet_pdu;
2546
2547         ofpbuf_init(&packet, 0);
2548         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
2549                                  pdu_size);
2550         memcpy(packet_pdu, pdu, pdu_size);
2551
2552         send_packet(port, &packet);
2553         ofpbuf_uninit(&packet);
2554     } else {
2555         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
2556                     "%s (%s)", port->bundle->name,
2557                     netdev_get_name(port->up.netdev), strerror(error));
2558     }
2559 }
2560
2561 static void
2562 bundle_send_learning_packets(struct ofbundle *bundle)
2563 {
2564     struct ofproto_dpif *ofproto = bundle->ofproto;
2565     int error, n_packets, n_errors;
2566     struct mac_entry *e;
2567
2568     error = n_packets = n_errors = 0;
2569     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
2570         if (e->port.p != bundle) {
2571             struct ofpbuf *learning_packet;
2572             struct ofport_dpif *port;
2573             void *port_void;
2574             int ret;
2575
2576             /* The assignment to "port" is unnecessary but makes "grep"ing for
2577              * struct ofport_dpif more effective. */
2578             learning_packet = bond_compose_learning_packet(bundle->bond,
2579                                                            e->mac, e->vlan,
2580                                                            &port_void);
2581             port = port_void;
2582             ret = send_packet(port, learning_packet);
2583             ofpbuf_delete(learning_packet);
2584             if (ret) {
2585                 error = ret;
2586                 n_errors++;
2587             }
2588             n_packets++;
2589         }
2590     }
2591
2592     if (n_errors) {
2593         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2594         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
2595                      "packets, last error was: %s",
2596                      bundle->name, n_errors, n_packets, strerror(error));
2597     } else {
2598         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
2599                  bundle->name, n_packets);
2600     }
2601 }
2602
2603 static void
2604 bundle_run(struct ofbundle *bundle)
2605 {
2606     if (bundle->lacp) {
2607         lacp_run(bundle->lacp, send_pdu_cb);
2608     }
2609     if (bundle->bond) {
2610         struct ofport_dpif *port;
2611
2612         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2613             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
2614         }
2615
2616         bond_run(bundle->bond, &bundle->ofproto->backer->revalidate_set,
2617                  lacp_status(bundle->lacp));
2618         if (bond_should_send_learning_packets(bundle->bond)) {
2619             bundle_send_learning_packets(bundle);
2620         }
2621     }
2622 }
2623
2624 static void
2625 bundle_wait(struct ofbundle *bundle)
2626 {
2627     if (bundle->lacp) {
2628         lacp_wait(bundle->lacp);
2629     }
2630     if (bundle->bond) {
2631         bond_wait(bundle->bond);
2632     }
2633 }
2634 \f
2635 /* Mirrors. */
2636
2637 static int
2638 mirror_scan(struct ofproto_dpif *ofproto)
2639 {
2640     int idx;
2641
2642     for (idx = 0; idx < MAX_MIRRORS; idx++) {
2643         if (!ofproto->mirrors[idx]) {
2644             return idx;
2645         }
2646     }
2647     return -1;
2648 }
2649
2650 static struct ofmirror *
2651 mirror_lookup(struct ofproto_dpif *ofproto, void *aux)
2652 {
2653     int i;
2654
2655     for (i = 0; i < MAX_MIRRORS; i++) {
2656         struct ofmirror *mirror = ofproto->mirrors[i];
2657         if (mirror && mirror->aux == aux) {
2658             return mirror;
2659         }
2660     }
2661
2662     return NULL;
2663 }
2664
2665 /* Update the 'dup_mirrors' member of each of the ofmirrors in 'ofproto'. */
2666 static void
2667 mirror_update_dups(struct ofproto_dpif *ofproto)
2668 {
2669     int i;
2670
2671     for (i = 0; i < MAX_MIRRORS; i++) {
2672         struct ofmirror *m = ofproto->mirrors[i];
2673
2674         if (m) {
2675             m->dup_mirrors = MIRROR_MASK_C(1) << i;
2676         }
2677     }
2678
2679     for (i = 0; i < MAX_MIRRORS; i++) {
2680         struct ofmirror *m1 = ofproto->mirrors[i];
2681         int j;
2682
2683         if (!m1) {
2684             continue;
2685         }
2686
2687         for (j = i + 1; j < MAX_MIRRORS; j++) {
2688             struct ofmirror *m2 = ofproto->mirrors[j];
2689
2690             if (m2 && m1->out == m2->out && m1->out_vlan == m2->out_vlan) {
2691                 m1->dup_mirrors |= MIRROR_MASK_C(1) << j;
2692                 m2->dup_mirrors |= m1->dup_mirrors;
2693             }
2694         }
2695     }
2696 }
2697
2698 static int
2699 mirror_set(struct ofproto *ofproto_, void *aux,
2700            const struct ofproto_mirror_settings *s)
2701 {
2702     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2703     mirror_mask_t mirror_bit;
2704     struct ofbundle *bundle;
2705     struct ofmirror *mirror;
2706     struct ofbundle *out;
2707     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
2708     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
2709     int out_vlan;
2710
2711     mirror = mirror_lookup(ofproto, aux);
2712     if (!s) {
2713         mirror_destroy(mirror);
2714         return 0;
2715     }
2716     if (!mirror) {
2717         int idx;
2718
2719         idx = mirror_scan(ofproto);
2720         if (idx < 0) {
2721             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
2722                       "cannot create %s",
2723                       ofproto->up.name, MAX_MIRRORS, s->name);
2724             return EFBIG;
2725         }
2726
2727         mirror = ofproto->mirrors[idx] = xzalloc(sizeof *mirror);
2728         mirror->ofproto = ofproto;
2729         mirror->idx = idx;
2730         mirror->aux = aux;
2731         mirror->out_vlan = -1;
2732         mirror->name = NULL;
2733     }
2734
2735     if (!mirror->name || strcmp(s->name, mirror->name)) {
2736         free(mirror->name);
2737         mirror->name = xstrdup(s->name);
2738     }
2739
2740     /* Get the new configuration. */
2741     if (s->out_bundle) {
2742         out = bundle_lookup(ofproto, s->out_bundle);
2743         if (!out) {
2744             mirror_destroy(mirror);
2745             return EINVAL;
2746         }
2747         out_vlan = -1;
2748     } else {
2749         out = NULL;
2750         out_vlan = s->out_vlan;
2751     }
2752     bundle_lookup_multiple(ofproto, s->srcs, s->n_srcs, &srcs);
2753     bundle_lookup_multiple(ofproto, s->dsts, s->n_dsts, &dsts);
2754
2755     /* If the configuration has not changed, do nothing. */
2756     if (hmapx_equals(&srcs, &mirror->srcs)
2757         && hmapx_equals(&dsts, &mirror->dsts)
2758         && vlan_bitmap_equal(mirror->vlans, s->src_vlans)
2759         && mirror->out == out
2760         && mirror->out_vlan == out_vlan)
2761     {
2762         hmapx_destroy(&srcs);
2763         hmapx_destroy(&dsts);
2764         return 0;
2765     }
2766
2767     hmapx_swap(&srcs, &mirror->srcs);
2768     hmapx_destroy(&srcs);
2769
2770     hmapx_swap(&dsts, &mirror->dsts);
2771     hmapx_destroy(&dsts);
2772
2773     free(mirror->vlans);
2774     mirror->vlans = vlan_bitmap_clone(s->src_vlans);
2775
2776     mirror->out = out;
2777     mirror->out_vlan = out_vlan;
2778
2779     /* Update bundles. */
2780     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
2781     HMAP_FOR_EACH (bundle, hmap_node, &mirror->ofproto->bundles) {
2782         if (hmapx_contains(&mirror->srcs, bundle)) {
2783             bundle->src_mirrors |= mirror_bit;
2784         } else {
2785             bundle->src_mirrors &= ~mirror_bit;
2786         }
2787
2788         if (hmapx_contains(&mirror->dsts, bundle)) {
2789             bundle->dst_mirrors |= mirror_bit;
2790         } else {
2791             bundle->dst_mirrors &= ~mirror_bit;
2792         }
2793
2794         if (mirror->out == bundle) {
2795             bundle->mirror_out |= mirror_bit;
2796         } else {
2797             bundle->mirror_out &= ~mirror_bit;
2798         }
2799     }
2800
2801     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2802     ofproto->has_mirrors = true;
2803     mac_learning_flush(ofproto->ml,
2804                        &ofproto->backer->revalidate_set);
2805     mirror_update_dups(ofproto);
2806
2807     return 0;
2808 }
2809
2810 static void
2811 mirror_destroy(struct ofmirror *mirror)
2812 {
2813     struct ofproto_dpif *ofproto;
2814     mirror_mask_t mirror_bit;
2815     struct ofbundle *bundle;
2816     int i;
2817
2818     if (!mirror) {
2819         return;
2820     }
2821
2822     ofproto = mirror->ofproto;
2823     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2824     mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
2825
2826     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
2827     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
2828         bundle->src_mirrors &= ~mirror_bit;
2829         bundle->dst_mirrors &= ~mirror_bit;
2830         bundle->mirror_out &= ~mirror_bit;
2831     }
2832
2833     hmapx_destroy(&mirror->srcs);
2834     hmapx_destroy(&mirror->dsts);
2835     free(mirror->vlans);
2836
2837     ofproto->mirrors[mirror->idx] = NULL;
2838     free(mirror->name);
2839     free(mirror);
2840
2841     mirror_update_dups(ofproto);
2842
2843     ofproto->has_mirrors = false;
2844     for (i = 0; i < MAX_MIRRORS; i++) {
2845         if (ofproto->mirrors[i]) {
2846             ofproto->has_mirrors = true;
2847             break;
2848         }
2849     }
2850 }
2851
2852 static int
2853 mirror_get_stats(struct ofproto *ofproto_, void *aux,
2854                  uint64_t *packets, uint64_t *bytes)
2855 {
2856     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2857     struct ofmirror *mirror = mirror_lookup(ofproto, aux);
2858
2859     if (!mirror) {
2860         *packets = *bytes = UINT64_MAX;
2861         return 0;
2862     }
2863
2864     *packets = mirror->packet_count;
2865     *bytes = mirror->byte_count;
2866
2867     return 0;
2868 }
2869
2870 static int
2871 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
2872 {
2873     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2874     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
2875         mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
2876     }
2877     return 0;
2878 }
2879
2880 static bool
2881 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
2882 {
2883     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2884     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
2885     return bundle && bundle->mirror_out != 0;
2886 }
2887
2888 static void
2889 forward_bpdu_changed(struct ofproto *ofproto_)
2890 {
2891     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2892     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2893 }
2894
2895 static void
2896 set_mac_table_config(struct ofproto *ofproto_, unsigned int idle_time,
2897                      size_t max_entries)
2898 {
2899     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2900     mac_learning_set_idle_time(ofproto->ml, idle_time);
2901     mac_learning_set_max_entries(ofproto->ml, max_entries);
2902 }
2903 \f
2904 /* Ports. */
2905
2906 static struct ofport_dpif *
2907 get_ofp_port(const struct ofproto_dpif *ofproto, uint16_t ofp_port)
2908 {
2909     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
2910     return ofport ? ofport_dpif_cast(ofport) : NULL;
2911 }
2912
2913 static struct ofport_dpif *
2914 get_odp_port(const struct ofproto_dpif *ofproto, uint32_t odp_port)
2915 {
2916     struct ofport_dpif *port = odp_port_to_ofport(ofproto->backer, odp_port);
2917     return port && &ofproto->up == port->up.ofproto ? port : NULL;
2918 }
2919
2920 static void
2921 ofproto_port_from_dpif_port(struct ofproto_dpif *ofproto,
2922                             struct ofproto_port *ofproto_port,
2923                             struct dpif_port *dpif_port)
2924 {
2925     ofproto_port->name = dpif_port->name;
2926     ofproto_port->type = dpif_port->type;
2927     ofproto_port->ofp_port = odp_port_to_ofp_port(ofproto, dpif_port->port_no);
2928 }
2929
2930 static struct ofport_dpif *
2931 ofport_get_peer(const struct ofport_dpif *ofport_dpif)
2932 {
2933     const struct ofproto_dpif *ofproto;
2934     const char *peer;
2935
2936     peer = netdev_vport_patch_peer(ofport_dpif->up.netdev);
2937     if (!peer) {
2938         return NULL;
2939     }
2940
2941     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2942         struct ofport *ofport;
2943
2944         ofport = shash_find_data(&ofproto->up.port_by_name, peer);
2945         if (ofport && ofport->ofproto->ofproto_class == &ofproto_dpif_class) {
2946             return ofport_dpif_cast(ofport);
2947         }
2948     }
2949     return NULL;
2950 }
2951
2952 static void
2953 port_run_fast(struct ofport_dpif *ofport)
2954 {
2955     if (ofport->cfm && cfm_should_send_ccm(ofport->cfm)) {
2956         struct ofpbuf packet;
2957
2958         ofpbuf_init(&packet, 0);
2959         cfm_compose_ccm(ofport->cfm, &packet, ofport->up.pp.hw_addr);
2960         send_packet(ofport, &packet);
2961         ofpbuf_uninit(&packet);
2962     }
2963 }
2964
2965 static void
2966 port_run(struct ofport_dpif *ofport)
2967 {
2968     long long int carrier_seq = netdev_get_carrier_resets(ofport->up.netdev);
2969     bool carrier_changed = carrier_seq != ofport->carrier_seq;
2970     bool enable = netdev_get_carrier(ofport->up.netdev);
2971
2972     ofport->carrier_seq = carrier_seq;
2973
2974     port_run_fast(ofport);
2975
2976     if (ofport->tnl_port
2977         && tnl_port_reconfigure(&ofport->up, ofport->odp_port,
2978                                 &ofport->tnl_port)) {
2979         ofproto_dpif_cast(ofport->up.ofproto)->backer->need_revalidate = true;
2980     }
2981
2982     if (ofport->cfm) {
2983         int cfm_opup = cfm_get_opup(ofport->cfm);
2984
2985         cfm_run(ofport->cfm);
2986         enable = enable && !cfm_get_fault(ofport->cfm);
2987
2988         if (cfm_opup >= 0) {
2989             enable = enable && cfm_opup;
2990         }
2991     }
2992
2993     if (ofport->bundle) {
2994         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
2995         if (carrier_changed) {
2996             lacp_slave_carrier_changed(ofport->bundle->lacp, ofport);
2997         }
2998     }
2999
3000     if (ofport->may_enable != enable) {
3001         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3002
3003         if (ofproto->has_bundle_action) {
3004             ofproto->backer->need_revalidate = REV_PORT_TOGGLED;
3005         }
3006     }
3007
3008     ofport->may_enable = enable;
3009 }
3010
3011 static void
3012 port_wait(struct ofport_dpif *ofport)
3013 {
3014     if (ofport->cfm) {
3015         cfm_wait(ofport->cfm);
3016     }
3017 }
3018
3019 static int
3020 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
3021                    struct ofproto_port *ofproto_port)
3022 {
3023     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3024     struct dpif_port dpif_port;
3025     int error;
3026
3027     if (sset_contains(&ofproto->ghost_ports, devname)) {
3028         const char *type = netdev_get_type_from_name(devname);
3029
3030         /* We may be called before ofproto->up.port_by_name is populated with
3031          * the appropriate ofport.  For this reason, we must get the name and
3032          * type from the netdev layer directly. */
3033         if (type) {
3034             const struct ofport *ofport;
3035
3036             ofport = shash_find_data(&ofproto->up.port_by_name, devname);
3037             ofproto_port->ofp_port = ofport ? ofport->ofp_port : OFPP_NONE;
3038             ofproto_port->name = xstrdup(devname);
3039             ofproto_port->type = xstrdup(type);
3040             return 0;
3041         }
3042         return ENODEV;
3043     }
3044
3045     if (!sset_contains(&ofproto->ports, devname)) {
3046         return ENODEV;
3047     }
3048     error = dpif_port_query_by_name(ofproto->backer->dpif,
3049                                     devname, &dpif_port);
3050     if (!error) {
3051         ofproto_port_from_dpif_port(ofproto, ofproto_port, &dpif_port);
3052     }
3053     return error;
3054 }
3055
3056 static int
3057 port_add(struct ofproto *ofproto_, struct netdev *netdev)
3058 {
3059     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3060     const char *dp_port_name = netdev_vport_get_dpif_port(netdev);
3061     const char *devname = netdev_get_name(netdev);
3062
3063     if (netdev_vport_is_patch(netdev)) {
3064         sset_add(&ofproto->ghost_ports, netdev_get_name(netdev));
3065         return 0;
3066     }
3067
3068     if (!dpif_port_exists(ofproto->backer->dpif, dp_port_name)) {
3069         uint32_t port_no = UINT32_MAX;
3070         int error;
3071
3072         error = dpif_port_add(ofproto->backer->dpif, netdev, &port_no);
3073         if (error) {
3074             return error;
3075         }
3076         if (netdev_get_tunnel_config(netdev)) {
3077             simap_put(&ofproto->backer->tnl_backers, dp_port_name, port_no);
3078         }
3079     }
3080
3081     if (netdev_get_tunnel_config(netdev)) {
3082         sset_add(&ofproto->ghost_ports, devname);
3083     } else {
3084         sset_add(&ofproto->ports, devname);
3085     }
3086     return 0;
3087 }
3088
3089 static int
3090 port_del(struct ofproto *ofproto_, uint16_t ofp_port)
3091 {
3092     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3093     struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
3094     int error = 0;
3095
3096     if (!ofport) {
3097         return 0;
3098     }
3099
3100     sset_find_and_delete(&ofproto->ghost_ports,
3101                          netdev_get_name(ofport->up.netdev));
3102     ofproto->backer->need_revalidate = REV_RECONFIGURE;
3103     if (!ofport->tnl_port) {
3104         error = dpif_port_del(ofproto->backer->dpif, ofport->odp_port);
3105         if (!error) {
3106             /* The caller is going to close ofport->up.netdev.  If this is a
3107              * bonded port, then the bond is using that netdev, so remove it
3108              * from the bond.  The client will need to reconfigure everything
3109              * after deleting ports, so then the slave will get re-added. */
3110             bundle_remove(&ofport->up);
3111         }
3112     }
3113     return error;
3114 }
3115
3116 static int
3117 port_get_stats(const struct ofport *ofport_, struct netdev_stats *stats)
3118 {
3119     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3120     int error;
3121
3122     error = netdev_get_stats(ofport->up.netdev, stats);
3123
3124     if (!error && ofport_->ofp_port == OFPP_LOCAL) {
3125         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3126
3127         /* ofproto->stats.tx_packets represents packets that we created
3128          * internally and sent to some port (e.g. packets sent with
3129          * send_packet()).  Account for them as if they had come from
3130          * OFPP_LOCAL and got forwarded. */
3131
3132         if (stats->rx_packets != UINT64_MAX) {
3133             stats->rx_packets += ofproto->stats.tx_packets;
3134         }
3135
3136         if (stats->rx_bytes != UINT64_MAX) {
3137             stats->rx_bytes += ofproto->stats.tx_bytes;
3138         }
3139
3140         /* ofproto->stats.rx_packets represents packets that were received on
3141          * some port and we processed internally and dropped (e.g. STP).
3142          * Account for them as if they had been forwarded to OFPP_LOCAL. */
3143
3144         if (stats->tx_packets != UINT64_MAX) {
3145             stats->tx_packets += ofproto->stats.rx_packets;
3146         }
3147
3148         if (stats->tx_bytes != UINT64_MAX) {
3149             stats->tx_bytes += ofproto->stats.rx_bytes;
3150         }
3151     }
3152
3153     return error;
3154 }
3155
3156 /* Account packets for LOCAL port. */
3157 static void
3158 ofproto_update_local_port_stats(const struct ofproto *ofproto_,
3159                                 size_t tx_size, size_t rx_size)
3160 {
3161     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3162
3163     if (rx_size) {
3164         ofproto->stats.rx_packets++;
3165         ofproto->stats.rx_bytes += rx_size;
3166     }
3167     if (tx_size) {
3168         ofproto->stats.tx_packets++;
3169         ofproto->stats.tx_bytes += tx_size;
3170     }
3171 }
3172
3173 struct port_dump_state {
3174     uint32_t bucket;
3175     uint32_t offset;
3176     bool ghost;
3177
3178     struct ofproto_port port;
3179     bool has_port;
3180 };
3181
3182 static int
3183 port_dump_start(const struct ofproto *ofproto_ OVS_UNUSED, void **statep)
3184 {
3185     *statep = xzalloc(sizeof(struct port_dump_state));
3186     return 0;
3187 }
3188
3189 static int
3190 port_dump_next(const struct ofproto *ofproto_, void *state_,
3191                struct ofproto_port *port)
3192 {
3193     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3194     struct port_dump_state *state = state_;
3195     const struct sset *sset;
3196     struct sset_node *node;
3197
3198     if (state->has_port) {
3199         ofproto_port_destroy(&state->port);
3200         state->has_port = false;
3201     }
3202     sset = state->ghost ? &ofproto->ghost_ports : &ofproto->ports;
3203     while ((node = sset_at_position(sset, &state->bucket, &state->offset))) {
3204         int error;
3205
3206         error = port_query_by_name(ofproto_, node->name, &state->port);
3207         if (!error) {
3208             *port = state->port;
3209             state->has_port = true;
3210             return 0;
3211         } else if (error != ENODEV) {
3212             return error;
3213         }
3214     }
3215
3216     if (!state->ghost) {
3217         state->ghost = true;
3218         state->bucket = 0;
3219         state->offset = 0;
3220         return port_dump_next(ofproto_, state_, port);
3221     }
3222
3223     return EOF;
3224 }
3225
3226 static int
3227 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
3228 {
3229     struct port_dump_state *state = state_;
3230
3231     if (state->has_port) {
3232         ofproto_port_destroy(&state->port);
3233     }
3234     free(state);
3235     return 0;
3236 }
3237
3238 static int
3239 port_poll(const struct ofproto *ofproto_, char **devnamep)
3240 {
3241     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3242
3243     if (ofproto->port_poll_errno) {
3244         int error = ofproto->port_poll_errno;
3245         ofproto->port_poll_errno = 0;
3246         return error;
3247     }
3248
3249     if (sset_is_empty(&ofproto->port_poll_set)) {
3250         return EAGAIN;
3251     }
3252
3253     *devnamep = sset_pop(&ofproto->port_poll_set);
3254     return 0;
3255 }
3256
3257 static void
3258 port_poll_wait(const struct ofproto *ofproto_)
3259 {
3260     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3261     dpif_port_poll_wait(ofproto->backer->dpif);
3262 }
3263
3264 static int
3265 port_is_lacp_current(const struct ofport *ofport_)
3266 {
3267     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3268     return (ofport->bundle && ofport->bundle->lacp
3269             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
3270             : -1);
3271 }
3272 \f
3273 /* Upcall handling. */
3274
3275 /* Flow miss batching.
3276  *
3277  * Some dpifs implement operations faster when you hand them off in a batch.
3278  * To allow batching, "struct flow_miss" queues the dpif-related work needed
3279  * for a given flow.  Each "struct flow_miss" corresponds to sending one or
3280  * more packets, plus possibly installing the flow in the dpif.
3281  *
3282  * So far we only batch the operations that affect flow setup time the most.
3283  * It's possible to batch more than that, but the benefit might be minimal. */
3284 struct flow_miss {
3285     struct hmap_node hmap_node;
3286     struct ofproto_dpif *ofproto;
3287     struct flow flow;
3288     enum odp_key_fitness key_fitness;
3289     const struct nlattr *key;
3290     size_t key_len;
3291     ovs_be16 initial_tci;
3292     struct list packets;
3293     enum dpif_upcall_type upcall_type;
3294     uint32_t odp_in_port;
3295 };
3296
3297 struct flow_miss_op {
3298     struct dpif_op dpif_op;
3299     void *garbage;              /* Pointer to pass to free(), NULL if none. */
3300     uint64_t stub[1024 / 8];    /* Temporary buffer. */
3301 };
3302
3303 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_NO_MATCH to each
3304  * OpenFlow controller as necessary according to their individual
3305  * configurations. */
3306 static void
3307 send_packet_in_miss(struct ofproto_dpif *ofproto, const struct ofpbuf *packet,
3308                     const struct flow *flow)
3309 {
3310     struct ofputil_packet_in pin;
3311
3312     pin.packet = packet->data;
3313     pin.packet_len = packet->size;
3314     pin.reason = OFPR_NO_MATCH;
3315     pin.controller_id = 0;
3316
3317     pin.table_id = 0;
3318     pin.cookie = 0;
3319
3320     pin.send_len = 0;           /* not used for flow table misses */
3321
3322     flow_get_metadata(flow, &pin.fmd);
3323
3324     connmgr_send_packet_in(ofproto->up.connmgr, &pin);
3325 }
3326
3327 static enum slow_path_reason
3328 process_special(struct ofproto_dpif *ofproto, const struct flow *flow,
3329                 const struct ofport_dpif *ofport, const struct ofpbuf *packet)
3330 {
3331     if (!ofport) {
3332         return 0;
3333     } else if (ofport->cfm && cfm_should_process_flow(ofport->cfm, flow)) {
3334         if (packet) {
3335             cfm_process_heartbeat(ofport->cfm, packet);
3336         }
3337         return SLOW_CFM;
3338     } else if (ofport->bundle && ofport->bundle->lacp
3339                && flow->dl_type == htons(ETH_TYPE_LACP)) {
3340         if (packet) {
3341             lacp_process_packet(ofport->bundle->lacp, ofport, packet);
3342         }
3343         return SLOW_LACP;
3344     } else if (ofproto->stp && stp_should_process_flow(flow)) {
3345         if (packet) {
3346             stp_process_packet(ofport, packet);
3347         }
3348         return SLOW_STP;
3349     } else {
3350         return 0;
3351     }
3352 }
3353
3354 static struct flow_miss *
3355 flow_miss_find(struct hmap *todo, const struct ofproto_dpif *ofproto,
3356                const struct flow *flow, uint32_t hash)
3357 {
3358     struct flow_miss *miss;
3359
3360     HMAP_FOR_EACH_WITH_HASH (miss, hmap_node, hash, todo) {
3361         if (miss->ofproto == ofproto && flow_equal(&miss->flow, flow)) {
3362             return miss;
3363         }
3364     }
3365
3366     return NULL;
3367 }
3368
3369 /* Partially Initializes 'op' as an "execute" operation for 'miss' and
3370  * 'packet'.  The caller must initialize op->actions and op->actions_len.  If
3371  * 'miss' is associated with a subfacet the caller must also initialize the
3372  * returned op->subfacet, and if anything needs to be freed after processing
3373  * the op, the caller must initialize op->garbage also. */
3374 static void
3375 init_flow_miss_execute_op(struct flow_miss *miss, struct ofpbuf *packet,
3376                           struct flow_miss_op *op)
3377 {
3378     if (miss->flow.vlan_tci != miss->initial_tci) {
3379         /* This packet was received on a VLAN splinter port.  We
3380          * added a VLAN to the packet to make the packet resemble
3381          * the flow, but the actions were composed assuming that
3382          * the packet contained no VLAN.  So, we must remove the
3383          * VLAN header from the packet before trying to execute the
3384          * actions. */
3385         eth_pop_vlan(packet);
3386     }
3387
3388     op->garbage = NULL;
3389     op->dpif_op.type = DPIF_OP_EXECUTE;
3390     op->dpif_op.u.execute.key = miss->key;
3391     op->dpif_op.u.execute.key_len = miss->key_len;
3392     op->dpif_op.u.execute.packet = packet;
3393 }
3394
3395 /* Helper for handle_flow_miss_without_facet() and
3396  * handle_flow_miss_with_facet(). */
3397 static void
3398 handle_flow_miss_common(struct rule_dpif *rule,
3399                         struct ofpbuf *packet, const struct flow *flow)
3400 {
3401     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3402
3403     ofproto->n_matches++;
3404
3405     if (rule->up.cr.priority == FAIL_OPEN_PRIORITY) {
3406         /*
3407          * Extra-special case for fail-open mode.
3408          *
3409          * We are in fail-open mode and the packet matched the fail-open
3410          * rule, but we are connected to a controller too.  We should send
3411          * the packet up to the controller in the hope that it will try to
3412          * set up a flow and thereby allow us to exit fail-open.
3413          *
3414          * See the top-level comment in fail-open.c for more information.
3415          */
3416         send_packet_in_miss(ofproto, packet, flow);
3417     }
3418 }
3419
3420 /* Figures out whether a flow that missed in 'ofproto', whose details are in
3421  * 'miss', is likely to be worth tracking in detail in userspace and (usually)
3422  * installing a datapath flow.  The answer is usually "yes" (a return value of
3423  * true).  However, for short flows the cost of bookkeeping is much higher than
3424  * the benefits, so when the datapath holds a large number of flows we impose
3425  * some heuristics to decide which flows are likely to be worth tracking. */
3426 static bool
3427 flow_miss_should_make_facet(struct ofproto_dpif *ofproto,
3428                             struct flow_miss *miss, uint32_t hash)
3429 {
3430     if (!ofproto->governor) {
3431         size_t n_subfacets;
3432
3433         n_subfacets = hmap_count(&ofproto->subfacets);
3434         if (n_subfacets * 2 <= ofproto->up.flow_eviction_threshold) {
3435             return true;
3436         }
3437
3438         ofproto->governor = governor_create(ofproto->up.name);
3439     }
3440
3441     return governor_should_install_flow(ofproto->governor, hash,
3442                                         list_size(&miss->packets));
3443 }
3444
3445 /* Handles 'miss', which matches 'rule', without creating a facet or subfacet
3446  * or creating any datapath flow.  May add an "execute" operation to 'ops' and
3447  * increment '*n_ops'. */
3448 static void
3449 handle_flow_miss_without_facet(struct flow_miss *miss,
3450                                struct rule_dpif *rule,
3451                                struct flow_miss_op *ops, size_t *n_ops)
3452 {
3453     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3454     long long int now = time_msec();
3455     struct action_xlate_ctx ctx;
3456     struct ofpbuf *packet;
3457
3458     LIST_FOR_EACH (packet, list_node, &miss->packets) {
3459         struct flow_miss_op *op = &ops[*n_ops];
3460         struct dpif_flow_stats stats;
3461         struct ofpbuf odp_actions;
3462
3463         COVERAGE_INC(facet_suppress);
3464
3465         ofpbuf_use_stub(&odp_actions, op->stub, sizeof op->stub);
3466
3467         dpif_flow_stats_extract(&miss->flow, packet, now, &stats);
3468         rule_credit_stats(rule, &stats);
3469
3470         action_xlate_ctx_init(&ctx, ofproto, &miss->flow, miss->initial_tci,
3471                               rule, 0, packet);
3472         ctx.resubmit_stats = &stats;
3473         xlate_actions(&ctx, rule->up.ofpacts, rule->up.ofpacts_len,
3474                       &odp_actions);
3475
3476         if (odp_actions.size) {
3477             struct dpif_execute *execute = &op->dpif_op.u.execute;
3478
3479             init_flow_miss_execute_op(miss, packet, op);
3480             execute->actions = odp_actions.data;
3481             execute->actions_len = odp_actions.size;
3482             op->garbage = ofpbuf_get_uninit_pointer(&odp_actions);
3483
3484             (*n_ops)++;
3485         } else {
3486             ofpbuf_uninit(&odp_actions);
3487         }
3488     }
3489 }
3490
3491 /* Handles 'miss', which matches 'facet'.  May add any required datapath
3492  * operations to 'ops', incrementing '*n_ops' for each new op.
3493  *
3494  * All of the packets in 'miss' are considered to have arrived at time 'now'.
3495  * This is really important only for new facets: if we just called time_msec()
3496  * here, then the new subfacet or its packets could look (occasionally) as
3497  * though it was used some time after the facet was used.  That can make a
3498  * one-packet flow look like it has a nonzero duration, which looks odd in
3499  * e.g. NetFlow statistics. */
3500 static void
3501 handle_flow_miss_with_facet(struct flow_miss *miss, struct facet *facet,
3502                             long long int now,
3503                             struct flow_miss_op *ops, size_t *n_ops)
3504 {
3505     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3506     enum subfacet_path want_path;
3507     struct subfacet *subfacet;
3508     struct ofpbuf *packet;
3509
3510     subfacet = subfacet_create(facet, miss, now);
3511
3512     LIST_FOR_EACH (packet, list_node, &miss->packets) {
3513         struct flow_miss_op *op = &ops[*n_ops];
3514         struct dpif_flow_stats stats;
3515         struct ofpbuf odp_actions;
3516
3517         handle_flow_miss_common(facet->rule, packet, &miss->flow);
3518
3519         ofpbuf_use_stub(&odp_actions, op->stub, sizeof op->stub);
3520         if (!subfacet->actions || subfacet->slow) {
3521             subfacet_make_actions(subfacet, packet, &odp_actions);
3522         }
3523
3524         dpif_flow_stats_extract(&facet->flow, packet, now, &stats);
3525         subfacet_update_stats(subfacet, &stats);
3526
3527         if (subfacet->actions_len) {
3528             struct dpif_execute *execute = &op->dpif_op.u.execute;
3529
3530             init_flow_miss_execute_op(miss, packet, op);
3531             if (!subfacet->slow) {
3532                 execute->actions = subfacet->actions;
3533                 execute->actions_len = subfacet->actions_len;
3534                 ofpbuf_uninit(&odp_actions);
3535             } else {
3536                 execute->actions = odp_actions.data;
3537                 execute->actions_len = odp_actions.size;
3538                 op->garbage = ofpbuf_get_uninit_pointer(&odp_actions);
3539             }
3540
3541             (*n_ops)++;
3542         } else {
3543             ofpbuf_uninit(&odp_actions);
3544         }
3545     }
3546
3547     want_path = subfacet_want_path(subfacet->slow);
3548     if (miss->upcall_type == DPIF_UC_MISS || subfacet->path != want_path) {
3549         struct flow_miss_op *op = &ops[(*n_ops)++];
3550         struct dpif_flow_put *put = &op->dpif_op.u.flow_put;
3551
3552         subfacet->path = want_path;
3553
3554         op->garbage = NULL;
3555         op->dpif_op.type = DPIF_OP_FLOW_PUT;
3556         put->flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
3557         put->key = miss->key;
3558         put->key_len = miss->key_len;
3559         if (want_path == SF_FAST_PATH) {
3560             put->actions = subfacet->actions;
3561             put->actions_len = subfacet->actions_len;
3562         } else {
3563             compose_slow_path(ofproto, &facet->flow, subfacet->slow,
3564                               op->stub, sizeof op->stub,
3565                               &put->actions, &put->actions_len);
3566         }
3567         put->stats = NULL;
3568     }
3569 }
3570
3571 /* Handles flow miss 'miss'.  May add any required datapath operations
3572  * to 'ops', incrementing '*n_ops' for each new op. */
3573 static void
3574 handle_flow_miss(struct flow_miss *miss, struct flow_miss_op *ops,
3575                  size_t *n_ops)
3576 {
3577     struct ofproto_dpif *ofproto = miss->ofproto;
3578     struct facet *facet;
3579     long long int now;
3580     uint32_t hash;
3581
3582     /* The caller must ensure that miss->hmap_node.hash contains
3583      * flow_hash(miss->flow, 0). */
3584     hash = miss->hmap_node.hash;
3585
3586     facet = facet_lookup_valid(ofproto, &miss->flow, hash);
3587     if (!facet) {
3588         struct rule_dpif *rule = rule_dpif_lookup(ofproto, &miss->flow);
3589
3590         if (!flow_miss_should_make_facet(ofproto, miss, hash)) {
3591             handle_flow_miss_without_facet(miss, rule, ops, n_ops);
3592             return;
3593         }
3594
3595         facet = facet_create(rule, &miss->flow, hash);
3596         now = facet->used;
3597     } else {
3598         now = time_msec();
3599     }
3600     handle_flow_miss_with_facet(miss, facet, now, ops, n_ops);
3601 }
3602
3603 static struct drop_key *
3604 drop_key_lookup(const struct dpif_backer *backer, const struct nlattr *key,
3605                 size_t key_len)
3606 {
3607     struct drop_key *drop_key;
3608
3609     HMAP_FOR_EACH_WITH_HASH (drop_key, hmap_node, hash_bytes(key, key_len, 0),
3610                              &backer->drop_keys) {
3611         if (drop_key->key_len == key_len
3612             && !memcmp(drop_key->key, key, key_len)) {
3613             return drop_key;
3614         }
3615     }
3616     return NULL;
3617 }
3618
3619 static void
3620 drop_key_clear(struct dpif_backer *backer)
3621 {
3622     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 15);
3623     struct drop_key *drop_key, *next;
3624
3625     HMAP_FOR_EACH_SAFE (drop_key, next, hmap_node, &backer->drop_keys) {
3626         int error;
3627
3628         error = dpif_flow_del(backer->dpif, drop_key->key, drop_key->key_len,
3629                               NULL);
3630         if (error && !VLOG_DROP_WARN(&rl)) {
3631             struct ds ds = DS_EMPTY_INITIALIZER;
3632             odp_flow_key_format(drop_key->key, drop_key->key_len, &ds);
3633             VLOG_WARN("Failed to delete drop key (%s) (%s)", strerror(error),
3634                       ds_cstr(&ds));
3635             ds_destroy(&ds);
3636         }
3637
3638         hmap_remove(&backer->drop_keys, &drop_key->hmap_node);
3639         free(drop_key->key);
3640         free(drop_key);
3641     }
3642 }
3643
3644 /* Given a datpath, packet, and flow metadata ('backer', 'packet', and 'key'
3645  * respectively), populates 'flow' with the result of odp_flow_key_to_flow().
3646  * Optionally, if nonnull, populates 'fitnessp' with the fitness of 'flow' as
3647  * returned by odp_flow_key_to_flow().  Also, optionally populates 'ofproto'
3648  * with the ofproto_dpif, and 'odp_in_port' with the datapath in_port, that
3649  * 'packet' ingressed.
3650  *
3651  * If 'ofproto' is nonnull, requires 'flow''s in_port to exist.  Otherwise sets
3652  * 'flow''s in_port to OFPP_NONE.
3653  *
3654  * This function does post-processing on data returned from
3655  * odp_flow_key_to_flow() to help make VLAN splinters transparent to the rest
3656  * of the upcall processing logic.  In particular, if the extracted in_port is
3657  * a VLAN splinter port, it replaces flow->in_port by the "real" port, sets
3658  * flow->vlan_tci correctly for the VLAN of the VLAN splinter port, and pushes
3659  * a VLAN header onto 'packet' (if it is nonnull).
3660  *
3661  * Optionally, if nonnull, sets '*initial_tci' to the VLAN TCI with which the
3662  * packet was really received, that is, the actual VLAN TCI extracted by
3663  * odp_flow_key_to_flow().  (This differs from the value returned in
3664  * flow->vlan_tci only for packets received on VLAN splinters.)
3665  *
3666  * Similarly, this function also includes some logic to help with tunnels.  It
3667  * may modify 'flow' as necessary to make the tunneling implementation
3668  * transparent to the upcall processing logic.
3669  *
3670  * Returns 0 if successful, ENODEV if the parsed flow has no associated ofport,
3671  * or some other positive errno if there are other problems. */
3672 static int
3673 ofproto_receive(const struct dpif_backer *backer, struct ofpbuf *packet,
3674                 const struct nlattr *key, size_t key_len,
3675                 struct flow *flow, enum odp_key_fitness *fitnessp,
3676                 struct ofproto_dpif **ofproto, uint32_t *odp_in_port,
3677                 ovs_be16 *initial_tci)
3678 {
3679     const struct ofport_dpif *port;
3680     enum odp_key_fitness fitness;
3681     int error = ENODEV;
3682
3683     fitness = odp_flow_key_to_flow(key, key_len, flow);
3684     if (fitness == ODP_FIT_ERROR) {
3685         error = EINVAL;
3686         goto exit;
3687     }
3688
3689     if (initial_tci) {
3690         *initial_tci = flow->vlan_tci;
3691     }
3692
3693     if (odp_in_port) {
3694         *odp_in_port = flow->in_port;
3695     }
3696
3697     if (tnl_port_should_receive(flow)) {
3698         const struct ofport *ofport = tnl_port_receive(flow);
3699         if (!ofport) {
3700             flow->in_port = OFPP_NONE;
3701             goto exit;
3702         }
3703         port = ofport_dpif_cast(ofport);
3704
3705         /* We can't reproduce 'key' from 'flow'. */
3706         fitness = fitness == ODP_FIT_PERFECT ? ODP_FIT_TOO_MUCH : fitness;
3707
3708         /* XXX: Since the tunnel module is not scoped per backer, it's
3709          * theoretically possible that we'll receive an ofport belonging to an
3710          * entirely different datapath.  In practice, this can't happen because
3711          * no platforms has two separate datapaths which each support
3712          * tunneling. */
3713         ovs_assert(ofproto_dpif_cast(port->up.ofproto)->backer == backer);
3714     } else {
3715         port = odp_port_to_ofport(backer, flow->in_port);
3716         if (!port) {
3717             flow->in_port = OFPP_NONE;
3718             goto exit;
3719         }
3720
3721         flow->in_port = port->up.ofp_port;
3722         if (vsp_adjust_flow(ofproto_dpif_cast(port->up.ofproto), flow)) {
3723             if (packet) {
3724                 /* Make the packet resemble the flow, so that it gets sent to
3725                  * an OpenFlow controller properly, so that it looks correct
3726                  * for sFlow, and so that flow_extract() will get the correct
3727                  * vlan_tci if it is called on 'packet'.
3728                  *
3729                  * The allocated space inside 'packet' probably also contains
3730                  * 'key', that is, both 'packet' and 'key' are probably part of
3731                  * a struct dpif_upcall (see the large comment on that
3732                  * structure definition), so pushing data on 'packet' is in
3733                  * general not a good idea since it could overwrite 'key' or
3734                  * free it as a side effect.  However, it's OK in this special
3735                  * case because we know that 'packet' is inside a Netlink
3736                  * attribute: pushing 4 bytes will just overwrite the 4-byte
3737                  * "struct nlattr", which is fine since we don't need that
3738                  * header anymore. */
3739                 eth_push_vlan(packet, flow->vlan_tci);
3740             }
3741             /* We can't reproduce 'key' from 'flow'. */
3742             fitness = fitness == ODP_FIT_PERFECT ? ODP_FIT_TOO_MUCH : fitness;
3743         }
3744     }
3745     error = 0;
3746
3747     if (ofproto) {
3748         *ofproto = ofproto_dpif_cast(port->up.ofproto);
3749     }
3750
3751 exit:
3752     if (fitnessp) {
3753         *fitnessp = fitness;
3754     }
3755     return error;
3756 }
3757
3758 static void
3759 handle_miss_upcalls(struct dpif_backer *backer, struct dpif_upcall *upcalls,
3760                     size_t n_upcalls)
3761 {
3762     struct dpif_upcall *upcall;
3763     struct flow_miss *miss;
3764     struct flow_miss misses[FLOW_MISS_MAX_BATCH];
3765     struct flow_miss_op flow_miss_ops[FLOW_MISS_MAX_BATCH * 2];
3766     struct dpif_op *dpif_ops[FLOW_MISS_MAX_BATCH * 2];
3767     struct hmap todo;
3768     int n_misses;
3769     size_t n_ops;
3770     size_t i;
3771
3772     if (!n_upcalls) {
3773         return;
3774     }
3775
3776     /* Construct the to-do list.
3777      *
3778      * This just amounts to extracting the flow from each packet and sticking
3779      * the packets that have the same flow in the same "flow_miss" structure so
3780      * that we can process them together. */
3781     hmap_init(&todo);
3782     n_misses = 0;
3783     for (upcall = upcalls; upcall < &upcalls[n_upcalls]; upcall++) {
3784         struct flow_miss *miss = &misses[n_misses];
3785         struct flow_miss *existing_miss;
3786         struct ofproto_dpif *ofproto;
3787         uint32_t odp_in_port;
3788         struct flow flow;
3789         uint32_t hash;
3790         int error;
3791
3792         error = ofproto_receive(backer, upcall->packet, upcall->key,
3793                                 upcall->key_len, &flow, &miss->key_fitness,
3794                                 &ofproto, &odp_in_port, &miss->initial_tci);
3795         if (error == ENODEV) {
3796             struct drop_key *drop_key;
3797
3798             /* Received packet on port for which we couldn't associate
3799              * an ofproto.  This can happen if a port is removed while
3800              * traffic is being received.  Print a rate-limited message
3801              * in case it happens frequently.  Install a drop flow so
3802              * that future packets of the flow are inexpensively dropped
3803              * in the kernel. */
3804             VLOG_INFO_RL(&rl, "received packet on unassociated port %"PRIu32,
3805                          flow.in_port);
3806
3807             drop_key = drop_key_lookup(backer, upcall->key, upcall->key_len);
3808             if (!drop_key) {
3809                 drop_key = xmalloc(sizeof *drop_key);
3810                 drop_key->key = xmemdup(upcall->key, upcall->key_len);
3811                 drop_key->key_len = upcall->key_len;
3812
3813                 hmap_insert(&backer->drop_keys, &drop_key->hmap_node,
3814                             hash_bytes(drop_key->key, drop_key->key_len, 0));
3815                 dpif_flow_put(backer->dpif, DPIF_FP_CREATE | DPIF_FP_MODIFY,
3816                               drop_key->key, drop_key->key_len, NULL, 0, NULL);
3817             }
3818             continue;
3819         }
3820         if (error) {
3821             continue;
3822         }
3823         flow_extract(upcall->packet, flow.skb_priority, flow.skb_mark,
3824                      &flow.tunnel, flow.in_port, &miss->flow);
3825
3826         /* Add other packets to a to-do list. */
3827         hash = flow_hash(&miss->flow, 0);
3828         existing_miss = flow_miss_find(&todo, ofproto, &miss->flow, hash);
3829         if (!existing_miss) {
3830             hmap_insert(&todo, &miss->hmap_node, hash);
3831             miss->ofproto = ofproto;
3832             miss->key = upcall->key;
3833             miss->key_len = upcall->key_len;
3834             miss->upcall_type = upcall->type;
3835             miss->odp_in_port = odp_in_port;
3836             list_init(&miss->packets);
3837
3838             n_misses++;
3839         } else {
3840             miss = existing_miss;
3841         }
3842         list_push_back(&miss->packets, &upcall->packet->list_node);
3843     }
3844
3845     /* Process each element in the to-do list, constructing the set of
3846      * operations to batch. */
3847     n_ops = 0;
3848     HMAP_FOR_EACH (miss, hmap_node, &todo) {
3849         handle_flow_miss(miss, flow_miss_ops, &n_ops);
3850     }
3851     ovs_assert(n_ops <= ARRAY_SIZE(flow_miss_ops));
3852
3853     /* Execute batch. */
3854     for (i = 0; i < n_ops; i++) {
3855         dpif_ops[i] = &flow_miss_ops[i].dpif_op;
3856     }
3857     dpif_operate(backer->dpif, dpif_ops, n_ops);
3858
3859     /* Free memory. */
3860     for (i = 0; i < n_ops; i++) {
3861         free(flow_miss_ops[i].garbage);
3862     }
3863     hmap_destroy(&todo);
3864 }
3865
3866 static enum { SFLOW_UPCALL, MISS_UPCALL, BAD_UPCALL }
3867 classify_upcall(const struct dpif_upcall *upcall)
3868 {
3869     union user_action_cookie cookie;
3870
3871     /* First look at the upcall type. */
3872     switch (upcall->type) {
3873     case DPIF_UC_ACTION:
3874         break;
3875
3876     case DPIF_UC_MISS:
3877         return MISS_UPCALL;
3878
3879     case DPIF_N_UC_TYPES:
3880     default:
3881         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
3882         return BAD_UPCALL;
3883     }
3884
3885     /* "action" upcalls need a closer look. */
3886     memcpy(&cookie, &upcall->userdata, sizeof(cookie));
3887     switch (cookie.type) {
3888     case USER_ACTION_COOKIE_SFLOW:
3889         return SFLOW_UPCALL;
3890
3891     case USER_ACTION_COOKIE_SLOW_PATH:
3892         return MISS_UPCALL;
3893
3894     case USER_ACTION_COOKIE_UNSPEC:
3895     default:
3896         VLOG_WARN_RL(&rl, "invalid user cookie : 0x%"PRIx64, upcall->userdata);
3897         return BAD_UPCALL;
3898     }
3899 }
3900
3901 static void
3902 handle_sflow_upcall(struct dpif_backer *backer,
3903                     const struct dpif_upcall *upcall)
3904 {
3905     struct ofproto_dpif *ofproto;
3906     union user_action_cookie cookie;
3907     struct flow flow;
3908     uint32_t odp_in_port;
3909
3910     if (ofproto_receive(backer, upcall->packet, upcall->key, upcall->key_len,
3911                         &flow, NULL, &ofproto, &odp_in_port, NULL)
3912         || !ofproto->sflow) {
3913         return;
3914     }
3915
3916     memcpy(&cookie, &upcall->userdata, sizeof(cookie));
3917     dpif_sflow_received(ofproto->sflow, upcall->packet, &flow,
3918                         odp_in_port, &cookie);
3919 }
3920
3921 static int
3922 handle_upcalls(struct dpif_backer *backer, unsigned int max_batch)
3923 {
3924     struct dpif_upcall misses[FLOW_MISS_MAX_BATCH];
3925     struct ofpbuf miss_bufs[FLOW_MISS_MAX_BATCH];
3926     uint64_t miss_buf_stubs[FLOW_MISS_MAX_BATCH][4096 / 8];
3927     int n_processed;
3928     int n_misses;
3929     int i;
3930
3931     ovs_assert(max_batch <= FLOW_MISS_MAX_BATCH);
3932
3933     n_misses = 0;
3934     for (n_processed = 0; n_processed < max_batch; n_processed++) {
3935         struct dpif_upcall *upcall = &misses[n_misses];
3936         struct ofpbuf *buf = &miss_bufs[n_misses];
3937         int error;
3938
3939         ofpbuf_use_stub(buf, miss_buf_stubs[n_misses],
3940                         sizeof miss_buf_stubs[n_misses]);
3941         error = dpif_recv(backer->dpif, upcall, buf);
3942         if (error) {
3943             ofpbuf_uninit(buf);
3944             break;
3945         }
3946
3947         switch (classify_upcall(upcall)) {
3948         case MISS_UPCALL:
3949             /* Handle it later. */
3950             n_misses++;
3951             break;
3952
3953         case SFLOW_UPCALL:
3954             handle_sflow_upcall(backer, upcall);
3955             ofpbuf_uninit(buf);
3956             break;
3957
3958         case BAD_UPCALL:
3959             ofpbuf_uninit(buf);
3960             break;
3961         }
3962     }
3963
3964     /* Handle deferred MISS_UPCALL processing. */
3965     handle_miss_upcalls(backer, misses, n_misses);
3966     for (i = 0; i < n_misses; i++) {
3967         ofpbuf_uninit(&miss_bufs[i]);
3968     }
3969
3970     return n_processed;
3971 }
3972 \f
3973 /* Flow expiration. */
3974
3975 static int subfacet_max_idle(const struct ofproto_dpif *);
3976 static void update_stats(struct dpif_backer *);
3977 static void rule_expire(struct rule_dpif *);
3978 static void expire_subfacets(struct ofproto_dpif *, int dp_max_idle);
3979
3980 /* This function is called periodically by run().  Its job is to collect
3981  * updates for the flows that have been installed into the datapath, most
3982  * importantly when they last were used, and then use that information to
3983  * expire flows that have not been used recently.
3984  *
3985  * Returns the number of milliseconds after which it should be called again. */
3986 static int
3987 expire(struct dpif_backer *backer)
3988 {
3989     struct ofproto_dpif *ofproto;
3990     int max_idle = INT32_MAX;
3991
3992     /* Periodically clear out the drop keys in an effort to keep them
3993      * relatively few. */
3994     drop_key_clear(backer);
3995
3996     /* Update stats for each flow in the backer. */
3997     update_stats(backer);
3998
3999     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
4000         struct rule *rule, *next_rule;
4001         int dp_max_idle;
4002
4003         if (ofproto->backer != backer) {
4004             continue;
4005         }
4006
4007         /* Expire subfacets that have been idle too long. */
4008         dp_max_idle = subfacet_max_idle(ofproto);
4009         expire_subfacets(ofproto, dp_max_idle);
4010
4011         max_idle = MIN(max_idle, dp_max_idle);
4012
4013         /* Expire OpenFlow flows whose idle_timeout or hard_timeout
4014          * has passed. */
4015         LIST_FOR_EACH_SAFE (rule, next_rule, expirable,
4016                             &ofproto->up.expirable) {
4017             rule_expire(rule_dpif_cast(rule));
4018         }
4019
4020         /* All outstanding data in existing flows has been accounted, so it's a
4021          * good time to do bond rebalancing. */
4022         if (ofproto->has_bonded_bundles) {
4023             struct ofbundle *bundle;
4024
4025             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
4026                 if (bundle->bond) {
4027                     bond_rebalance(bundle->bond, &backer->revalidate_set);
4028                 }
4029             }
4030         }
4031     }
4032
4033     return MIN(max_idle, 1000);
4034 }
4035
4036 /* Updates flow table statistics given that the datapath just reported 'stats'
4037  * as 'subfacet''s statistics. */
4038 static void
4039 update_subfacet_stats(struct subfacet *subfacet,
4040                       const struct dpif_flow_stats *stats)
4041 {
4042     struct facet *facet = subfacet->facet;
4043
4044     if (stats->n_packets >= subfacet->dp_packet_count) {
4045         uint64_t extra = stats->n_packets - subfacet->dp_packet_count;
4046         facet->packet_count += extra;
4047     } else {
4048         VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
4049     }
4050
4051     if (stats->n_bytes >= subfacet->dp_byte_count) {
4052         facet->byte_count += stats->n_bytes - subfacet->dp_byte_count;
4053     } else {
4054         VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
4055     }
4056
4057     subfacet->dp_packet_count = stats->n_packets;
4058     subfacet->dp_byte_count = stats->n_bytes;
4059
4060     facet->tcp_flags |= stats->tcp_flags;
4061
4062     subfacet_update_time(subfacet, stats->used);
4063     if (facet->accounted_bytes < facet->byte_count) {
4064         facet_learn(facet);
4065         facet_account(facet);
4066         facet->accounted_bytes = facet->byte_count;
4067     }
4068     facet_push_stats(facet);
4069 }
4070
4071 /* 'key' with length 'key_len' bytes is a flow in 'dpif' that we know nothing
4072  * about, or a flow that shouldn't be installed but was anyway.  Delete it. */
4073 static void
4074 delete_unexpected_flow(struct ofproto_dpif *ofproto,
4075                        const struct nlattr *key, size_t key_len)
4076 {
4077     if (!VLOG_DROP_WARN(&rl)) {
4078         struct ds s;
4079
4080         ds_init(&s);
4081         odp_flow_key_format(key, key_len, &s);
4082         VLOG_WARN("unexpected flow on %s: %s", ofproto->up.name, ds_cstr(&s));
4083         ds_destroy(&s);
4084     }
4085
4086     COVERAGE_INC(facet_unexpected);
4087     dpif_flow_del(ofproto->backer->dpif, key, key_len, NULL);
4088 }
4089
4090 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
4091  *
4092  * This function also pushes statistics updates to rules which each facet
4093  * resubmits into.  Generally these statistics will be accurate.  However, if a
4094  * facet changes the rule it resubmits into at some time in between
4095  * update_stats() runs, it is possible that statistics accrued to the
4096  * old rule will be incorrectly attributed to the new rule.  This could be
4097  * avoided by calling update_stats() whenever rules are created or
4098  * deleted.  However, the performance impact of making so many calls to the
4099  * datapath do not justify the benefit of having perfectly accurate statistics.
4100  */
4101 static void
4102 update_stats(struct dpif_backer *backer)
4103 {
4104     const struct dpif_flow_stats *stats;
4105     struct dpif_flow_dump dump;
4106     const struct nlattr *key;
4107     size_t key_len;
4108
4109     dpif_flow_dump_start(&dump, backer->dpif);
4110     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
4111         struct flow flow;
4112         struct subfacet *subfacet;
4113         struct ofproto_dpif *ofproto;
4114         struct ofport_dpif *ofport;
4115         uint32_t key_hash;
4116
4117         if (ofproto_receive(backer, NULL, key, key_len, &flow, NULL, &ofproto,
4118                             NULL, NULL)) {
4119             continue;
4120         }
4121
4122         ofport = get_ofp_port(ofproto, flow.in_port);
4123         if (ofport && ofport->tnl_port) {
4124             netdev_vport_inc_rx(ofport->up.netdev, stats);
4125         }
4126
4127         key_hash = odp_flow_key_hash(key, key_len);
4128         subfacet = subfacet_find(ofproto, key, key_len, key_hash);
4129         switch (subfacet ? subfacet->path : SF_NOT_INSTALLED) {
4130         case SF_FAST_PATH:
4131             update_subfacet_stats(subfacet, stats);
4132             break;
4133
4134         case SF_SLOW_PATH:
4135             /* Stats are updated per-packet. */
4136             break;
4137
4138         case SF_NOT_INSTALLED:
4139         default:
4140             delete_unexpected_flow(ofproto, key, key_len);
4141             break;
4142         }
4143     }
4144     dpif_flow_dump_done(&dump);
4145 }
4146
4147 /* Calculates and returns the number of milliseconds of idle time after which
4148  * subfacets should expire from the datapath.  When a subfacet expires, we fold
4149  * its statistics into its facet, and when a facet's last subfacet expires, we
4150  * fold its statistic into its rule. */
4151 static int
4152 subfacet_max_idle(const struct ofproto_dpif *ofproto)
4153 {
4154     /*
4155      * Idle time histogram.
4156      *
4157      * Most of the time a switch has a relatively small number of subfacets.
4158      * When this is the case we might as well keep statistics for all of them
4159      * in userspace and to cache them in the kernel datapath for performance as
4160      * well.
4161      *
4162      * As the number of subfacets increases, the memory required to maintain
4163      * statistics about them in userspace and in the kernel becomes
4164      * significant.  However, with a large number of subfacets it is likely
4165      * that only a few of them are "heavy hitters" that consume a large amount
4166      * of bandwidth.  At this point, only heavy hitters are worth caching in
4167      * the kernel and maintaining in userspaces; other subfacets we can
4168      * discard.
4169      *
4170      * The technique used to compute the idle time is to build a histogram with
4171      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each subfacet
4172      * that is installed in the kernel gets dropped in the appropriate bucket.
4173      * After the histogram has been built, we compute the cutoff so that only
4174      * the most-recently-used 1% of subfacets (but at least
4175      * ofproto->up.flow_eviction_threshold flows) are kept cached.  At least
4176      * the most-recently-used bucket of subfacets is kept, so actually an
4177      * arbitrary number of subfacets can be kept in any given expiration run
4178      * (though the next run will delete most of those unless they receive
4179      * additional data).
4180      *
4181      * This requires a second pass through the subfacets, in addition to the
4182      * pass made by update_stats(), because the former function never looks at
4183      * uninstallable subfacets.
4184      */
4185     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
4186     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
4187     int buckets[N_BUCKETS] = { 0 };
4188     int total, subtotal, bucket;
4189     struct subfacet *subfacet;
4190     long long int now;
4191     int i;
4192
4193     total = hmap_count(&ofproto->subfacets);
4194     if (total <= ofproto->up.flow_eviction_threshold) {
4195         return N_BUCKETS * BUCKET_WIDTH;
4196     }
4197
4198     /* Build histogram. */
4199     now = time_msec();
4200     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->subfacets) {
4201         long long int idle = now - subfacet->used;
4202         int bucket = (idle <= 0 ? 0
4203                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4204                       : (unsigned int) idle / BUCKET_WIDTH);
4205         buckets[bucket]++;
4206     }
4207
4208     /* Find the first bucket whose flows should be expired. */
4209     subtotal = bucket = 0;
4210     do {
4211         subtotal += buckets[bucket++];
4212     } while (bucket < N_BUCKETS &&
4213              subtotal < MAX(ofproto->up.flow_eviction_threshold, total / 100));
4214
4215     if (VLOG_IS_DBG_ENABLED()) {
4216         struct ds s;
4217
4218         ds_init(&s);
4219         ds_put_cstr(&s, "keep");
4220         for (i = 0; i < N_BUCKETS; i++) {
4221             if (i == bucket) {
4222                 ds_put_cstr(&s, ", drop");
4223             }
4224             if (buckets[i]) {
4225                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4226             }
4227         }
4228         VLOG_INFO("%s: %s (msec:count)", ofproto->up.name, ds_cstr(&s));
4229         ds_destroy(&s);
4230     }
4231
4232     return bucket * BUCKET_WIDTH;
4233 }
4234
4235 static void
4236 expire_subfacets(struct ofproto_dpif *ofproto, int dp_max_idle)
4237 {
4238     /* Cutoff time for most flows. */
4239     long long int normal_cutoff = time_msec() - dp_max_idle;
4240
4241     /* We really want to keep flows for special protocols around, so use a more
4242      * conservative cutoff. */
4243     long long int special_cutoff = time_msec() - 10000;
4244
4245     struct subfacet *subfacet, *next_subfacet;
4246     struct subfacet *batch[SUBFACET_DESTROY_MAX_BATCH];
4247     int n_batch;
4248
4249     n_batch = 0;
4250     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
4251                         &ofproto->subfacets) {
4252         long long int cutoff;
4253
4254         cutoff = (subfacet->slow & (SLOW_CFM | SLOW_LACP | SLOW_STP)
4255                   ? special_cutoff
4256                   : normal_cutoff);
4257         if (subfacet->used < cutoff) {
4258             if (subfacet->path != SF_NOT_INSTALLED) {
4259                 batch[n_batch++] = subfacet;
4260                 if (n_batch >= SUBFACET_DESTROY_MAX_BATCH) {
4261                     subfacet_destroy_batch(ofproto, batch, n_batch);
4262                     n_batch = 0;
4263                 }
4264             } else {
4265                 subfacet_destroy(subfacet);
4266             }
4267         }
4268     }
4269
4270     if (n_batch > 0) {
4271         subfacet_destroy_batch(ofproto, batch, n_batch);
4272     }
4273 }
4274
4275 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4276  * then delete it entirely. */
4277 static void
4278 rule_expire(struct rule_dpif *rule)
4279 {
4280     struct facet *facet, *next_facet;
4281     long long int now;
4282     uint8_t reason;
4283
4284     if (rule->up.pending) {
4285         /* We'll have to expire it later. */
4286         return;
4287     }
4288
4289     /* Has 'rule' expired? */
4290     now = time_msec();
4291     if (rule->up.hard_timeout
4292         && now > rule->up.modified + rule->up.hard_timeout * 1000) {
4293         reason = OFPRR_HARD_TIMEOUT;
4294     } else if (rule->up.idle_timeout
4295                && now > rule->up.used + rule->up.idle_timeout * 1000) {
4296         reason = OFPRR_IDLE_TIMEOUT;
4297     } else {
4298         return;
4299     }
4300
4301     COVERAGE_INC(ofproto_dpif_expired);
4302
4303     /* Update stats.  (This is a no-op if the rule expired due to an idle
4304      * timeout, because that only happens when the rule has no facets left.) */
4305     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4306         facet_remove(facet);
4307     }
4308
4309     /* Get rid of the rule. */
4310     ofproto_rule_expire(&rule->up, reason);
4311 }
4312 \f
4313 /* Facets. */
4314
4315 /* Creates and returns a new facet owned by 'rule', given a 'flow'.
4316  *
4317  * The caller must already have determined that no facet with an identical
4318  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
4319  * the ofproto's classifier table.
4320  *
4321  * 'hash' must be the return value of flow_hash(flow, 0).
4322  *
4323  * The facet will initially have no subfacets.  The caller should create (at
4324  * least) one subfacet with subfacet_create(). */
4325 static struct facet *
4326 facet_create(struct rule_dpif *rule, const struct flow *flow, uint32_t hash)
4327 {
4328     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4329     struct facet *facet;
4330
4331     facet = xzalloc(sizeof *facet);
4332     facet->used = time_msec();
4333     hmap_insert(&ofproto->facets, &facet->hmap_node, hash);
4334     list_push_back(&rule->facets, &facet->list_node);
4335     facet->rule = rule;
4336     facet->flow = *flow;
4337     list_init(&facet->subfacets);
4338     netflow_flow_init(&facet->nf_flow);
4339     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
4340
4341     return facet;
4342 }
4343
4344 static void
4345 facet_free(struct facet *facet)
4346 {
4347     free(facet);
4348 }
4349
4350 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
4351  * 'packet', which arrived on 'in_port'. */
4352 static bool
4353 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
4354                     const struct nlattr *odp_actions, size_t actions_len,
4355                     struct ofpbuf *packet)
4356 {
4357     struct odputil_keybuf keybuf;
4358     struct ofpbuf key;
4359     int error;
4360
4361     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
4362     odp_flow_key_from_flow(&key, flow,
4363                            ofp_port_to_odp_port(ofproto, flow->in_port));
4364
4365     error = dpif_execute(ofproto->backer->dpif, key.data, key.size,
4366                          odp_actions, actions_len, packet);
4367     return !error;
4368 }
4369
4370 /* Remove 'facet' from 'ofproto' and free up the associated memory:
4371  *
4372  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
4373  *     rule's statistics, via subfacet_uninstall().
4374  *
4375  *   - Removes 'facet' from its rule and from ofproto->facets.
4376  */
4377 static void
4378 facet_remove(struct facet *facet)
4379 {
4380     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4381     struct subfacet *subfacet, *next_subfacet;
4382
4383     ovs_assert(!list_is_empty(&facet->subfacets));
4384
4385     /* First uninstall all of the subfacets to get final statistics. */
4386     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4387         subfacet_uninstall(subfacet);
4388     }
4389
4390     /* Flush the final stats to the rule.
4391      *
4392      * This might require us to have at least one subfacet around so that we
4393      * can use its actions for accounting in facet_account(), which is why we
4394      * have uninstalled but not yet destroyed the subfacets. */
4395     facet_flush_stats(facet);
4396
4397     /* Now we're really all done so destroy everything. */
4398     LIST_FOR_EACH_SAFE (subfacet, next_subfacet, list_node,
4399                         &facet->subfacets) {
4400         subfacet_destroy__(subfacet);
4401     }
4402     hmap_remove(&ofproto->facets, &facet->hmap_node);
4403     list_remove(&facet->list_node);
4404     facet_free(facet);
4405 }
4406
4407 /* Feed information from 'facet' back into the learning table to keep it in
4408  * sync with what is actually flowing through the datapath. */
4409 static void
4410 facet_learn(struct facet *facet)
4411 {
4412     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4413     struct action_xlate_ctx ctx;
4414
4415     if (!facet->has_learn
4416         && !facet->has_normal
4417         && (!facet->has_fin_timeout
4418             || !(facet->tcp_flags & (TCP_FIN | TCP_RST)))) {
4419         return;
4420     }
4421
4422     action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
4423                           facet->flow.vlan_tci,
4424                           facet->rule, facet->tcp_flags, NULL);
4425     ctx.may_learn = true;
4426     xlate_actions_for_side_effects(&ctx, facet->rule->up.ofpacts,
4427                                    facet->rule->up.ofpacts_len);
4428 }
4429
4430 static void
4431 facet_account(struct facet *facet)
4432 {
4433     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4434     struct subfacet *subfacet;
4435     const struct nlattr *a;
4436     unsigned int left;
4437     ovs_be16 vlan_tci;
4438     uint64_t n_bytes;
4439
4440     if (!facet->has_normal || !ofproto->has_bonded_bundles) {
4441         return;
4442     }
4443     n_bytes = facet->byte_count - facet->accounted_bytes;
4444
4445     /* This loop feeds byte counters to bond_account() for rebalancing to use
4446      * as a basis.  We also need to track the actual VLAN on which the packet
4447      * is going to be sent to ensure that it matches the one passed to
4448      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
4449      * hash bucket.)
4450      *
4451      * We use the actions from an arbitrary subfacet because they should all
4452      * be equally valid for our purpose. */
4453     subfacet = CONTAINER_OF(list_front(&facet->subfacets),
4454                             struct subfacet, list_node);
4455     vlan_tci = facet->flow.vlan_tci;
4456     NL_ATTR_FOR_EACH_UNSAFE (a, left,
4457                              subfacet->actions, subfacet->actions_len) {
4458         const struct ovs_action_push_vlan *vlan;
4459         struct ofport_dpif *port;
4460
4461         switch (nl_attr_type(a)) {
4462         case OVS_ACTION_ATTR_OUTPUT:
4463             port = get_odp_port(ofproto, nl_attr_get_u32(a));
4464             if (port && port->bundle && port->bundle->bond) {
4465                 bond_account(port->bundle->bond, &facet->flow,
4466                              vlan_tci_to_vid(vlan_tci), n_bytes);
4467             }
4468             break;
4469
4470         case OVS_ACTION_ATTR_POP_VLAN:
4471             vlan_tci = htons(0);
4472             break;
4473
4474         case OVS_ACTION_ATTR_PUSH_VLAN:
4475             vlan = nl_attr_get(a);
4476             vlan_tci = vlan->vlan_tci;
4477             break;
4478         }
4479     }
4480 }
4481
4482 /* Returns true if the only action for 'facet' is to send to the controller.
4483  * (We don't report NetFlow expiration messages for such facets because they
4484  * are just part of the control logic for the network, not real traffic). */
4485 static bool
4486 facet_is_controller_flow(struct facet *facet)
4487 {
4488     if (facet) {
4489         const struct rule *rule = &facet->rule->up;
4490         const struct ofpact *ofpacts = rule->ofpacts;
4491         size_t ofpacts_len = rule->ofpacts_len;
4492
4493         if (ofpacts_len > 0 &&
4494             ofpacts->type == OFPACT_CONTROLLER &&
4495             ofpact_next(ofpacts) >= ofpact_end(ofpacts, ofpacts_len)) {
4496             return true;
4497         }
4498     }
4499     return false;
4500 }
4501
4502 /* Folds all of 'facet''s statistics into its rule.  Also updates the
4503  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
4504  * 'facet''s statistics in the datapath should have been zeroed and folded into
4505  * its packet and byte counts before this function is called. */
4506 static void
4507 facet_flush_stats(struct facet *facet)
4508 {
4509     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4510     struct subfacet *subfacet;
4511
4512     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4513         ovs_assert(!subfacet->dp_byte_count);
4514         ovs_assert(!subfacet->dp_packet_count);
4515     }
4516
4517     facet_push_stats(facet);
4518     if (facet->accounted_bytes < facet->byte_count) {
4519         facet_account(facet);
4520         facet->accounted_bytes = facet->byte_count;
4521     }
4522
4523     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
4524         struct ofexpired expired;
4525         expired.flow = facet->flow;
4526         expired.packet_count = facet->packet_count;
4527         expired.byte_count = facet->byte_count;
4528         expired.used = facet->used;
4529         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4530     }
4531
4532     facet->rule->packet_count += facet->packet_count;
4533     facet->rule->byte_count += facet->byte_count;
4534
4535     /* Reset counters to prevent double counting if 'facet' ever gets
4536      * reinstalled. */
4537     facet_reset_counters(facet);
4538
4539     netflow_flow_clear(&facet->nf_flow);
4540     facet->tcp_flags = 0;
4541 }
4542
4543 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
4544  * Returns it if found, otherwise a null pointer.
4545  *
4546  * 'hash' must be the return value of flow_hash(flow, 0).
4547  *
4548  * The returned facet might need revalidation; use facet_lookup_valid()
4549  * instead if that is important. */
4550 static struct facet *
4551 facet_find(struct ofproto_dpif *ofproto,
4552            const struct flow *flow, uint32_t hash)
4553 {
4554     struct facet *facet;
4555
4556     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, hash, &ofproto->facets) {
4557         if (flow_equal(flow, &facet->flow)) {
4558             return facet;
4559         }
4560     }
4561
4562     return NULL;
4563 }
4564
4565 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
4566  * Returns it if found, otherwise a null pointer.
4567  *
4568  * 'hash' must be the return value of flow_hash(flow, 0).
4569  *
4570  * The returned facet is guaranteed to be valid. */
4571 static struct facet *
4572 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow,
4573                    uint32_t hash)
4574 {
4575     struct facet *facet;
4576
4577     facet = facet_find(ofproto, flow, hash);
4578     if (facet
4579         && (ofproto->backer->need_revalidate
4580             || tag_set_intersects(&ofproto->backer->revalidate_set,
4581                                   facet->tags))) {
4582         facet_revalidate(facet);
4583     }
4584
4585     return facet;
4586 }
4587
4588 static const char *
4589 subfacet_path_to_string(enum subfacet_path path)
4590 {
4591     switch (path) {
4592     case SF_NOT_INSTALLED:
4593         return "not installed";
4594     case SF_FAST_PATH:
4595         return "in fast path";
4596     case SF_SLOW_PATH:
4597         return "in slow path";
4598     default:
4599         return "<error>";
4600     }
4601 }
4602
4603 /* Returns the path in which a subfacet should be installed if its 'slow'
4604  * member has the specified value. */
4605 static enum subfacet_path
4606 subfacet_want_path(enum slow_path_reason slow)
4607 {
4608     return slow ? SF_SLOW_PATH : SF_FAST_PATH;
4609 }
4610
4611 /* Returns true if 'subfacet' needs to have its datapath flow updated,
4612  * supposing that its actions have been recalculated as 'want_actions' and that
4613  * 'slow' is nonzero iff 'subfacet' should be in the slow path. */
4614 static bool
4615 subfacet_should_install(struct subfacet *subfacet, enum slow_path_reason slow,
4616                         const struct ofpbuf *want_actions)
4617 {
4618     enum subfacet_path want_path = subfacet_want_path(slow);
4619     return (want_path != subfacet->path
4620             || (want_path == SF_FAST_PATH
4621                 && (subfacet->actions_len != want_actions->size
4622                     || memcmp(subfacet->actions, want_actions->data,
4623                               subfacet->actions_len))));
4624 }
4625
4626 static bool
4627 facet_check_consistency(struct facet *facet)
4628 {
4629     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 15);
4630
4631     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4632
4633     uint64_t odp_actions_stub[1024 / 8];
4634     struct ofpbuf odp_actions;
4635
4636     struct rule_dpif *rule;
4637     struct subfacet *subfacet;
4638     bool may_log = false;
4639     bool ok;
4640
4641     /* Check the rule for consistency. */
4642     rule = rule_dpif_lookup(ofproto, &facet->flow);
4643     ok = rule == facet->rule;
4644     if (!ok) {
4645         may_log = !VLOG_DROP_WARN(&rl);
4646         if (may_log) {
4647             struct ds s;
4648
4649             ds_init(&s);
4650             flow_format(&s, &facet->flow);
4651             ds_put_format(&s, ": facet associated with wrong rule (was "
4652                           "table=%"PRIu8",", facet->rule->up.table_id);
4653             cls_rule_format(&facet->rule->up.cr, &s);
4654             ds_put_format(&s, ") (should have been table=%"PRIu8",",
4655                           rule->up.table_id);
4656             cls_rule_format(&rule->up.cr, &s);
4657             ds_put_char(&s, ')');
4658
4659             VLOG_WARN("%s", ds_cstr(&s));
4660             ds_destroy(&s);
4661         }
4662     }
4663
4664     /* Check the datapath actions for consistency. */
4665     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
4666     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4667         enum subfacet_path want_path;
4668         struct action_xlate_ctx ctx;
4669         struct ds s;
4670
4671         action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
4672                               subfacet->initial_tci, rule, 0, NULL);
4673         xlate_actions(&ctx, rule->up.ofpacts, rule->up.ofpacts_len,
4674                       &odp_actions);
4675
4676         if (subfacet->path == SF_NOT_INSTALLED) {
4677             /* This only happens if the datapath reported an error when we
4678              * tried to install the flow.  Don't flag another error here. */
4679             continue;
4680         }
4681
4682         want_path = subfacet_want_path(subfacet->slow);
4683         if (want_path == SF_SLOW_PATH && subfacet->path == SF_SLOW_PATH) {
4684             /* The actions for slow-path flows may legitimately vary from one
4685              * packet to the next.  We're done. */
4686             continue;
4687         }
4688
4689         if (!subfacet_should_install(subfacet, subfacet->slow, &odp_actions)) {
4690             continue;
4691         }
4692
4693         /* Inconsistency! */
4694         if (ok) {
4695             may_log = !VLOG_DROP_WARN(&rl);
4696             ok = false;
4697         }
4698         if (!may_log) {
4699             /* Rate-limited, skip reporting. */
4700             continue;
4701         }
4702
4703         ds_init(&s);
4704         odp_flow_key_format(subfacet->key, subfacet->key_len, &s);
4705
4706         ds_put_cstr(&s, ": inconsistency in subfacet");
4707         if (want_path != subfacet->path) {
4708             enum odp_key_fitness fitness = subfacet->key_fitness;
4709
4710             ds_put_format(&s, " (%s, fitness=%s)",
4711                           subfacet_path_to_string(subfacet->path),
4712                           odp_key_fitness_to_string(fitness));
4713             ds_put_format(&s, " (should have been %s)",
4714                           subfacet_path_to_string(want_path));
4715         } else if (want_path == SF_FAST_PATH) {
4716             ds_put_cstr(&s, " (actions were: ");
4717             format_odp_actions(&s, subfacet->actions,
4718                                subfacet->actions_len);
4719             ds_put_cstr(&s, ") (correct actions: ");
4720             format_odp_actions(&s, odp_actions.data, odp_actions.size);
4721             ds_put_char(&s, ')');
4722         } else {
4723             ds_put_cstr(&s, " (actions: ");
4724             format_odp_actions(&s, subfacet->actions,
4725                                subfacet->actions_len);
4726             ds_put_char(&s, ')');
4727         }
4728         VLOG_WARN("%s", ds_cstr(&s));
4729         ds_destroy(&s);
4730     }
4731     ofpbuf_uninit(&odp_actions);
4732
4733     return ok;
4734 }
4735
4736 /* Re-searches the classifier for 'facet':
4737  *
4738  *   - If the rule found is different from 'facet''s current rule, moves
4739  *     'facet' to the new rule and recompiles its actions.
4740  *
4741  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
4742  *     where it is and recompiles its actions anyway. */
4743 static void
4744 facet_revalidate(struct facet *facet)
4745 {
4746     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4747     struct actions {
4748         struct nlattr *odp_actions;
4749         size_t actions_len;
4750     };
4751     struct actions *new_actions;
4752
4753     struct action_xlate_ctx ctx;
4754     uint64_t odp_actions_stub[1024 / 8];
4755     struct ofpbuf odp_actions;
4756
4757     struct rule_dpif *new_rule;
4758     struct subfacet *subfacet;
4759     int i;
4760
4761     COVERAGE_INC(facet_revalidate);
4762
4763     new_rule = rule_dpif_lookup(ofproto, &facet->flow);
4764
4765     /* Calculate new datapath actions.
4766      *
4767      * We do not modify any 'facet' state yet, because we might need to, e.g.,
4768      * emit a NetFlow expiration and, if so, we need to have the old state
4769      * around to properly compose it. */
4770
4771     /* If the datapath actions changed or the installability changed,
4772      * then we need to talk to the datapath. */
4773     i = 0;
4774     new_actions = NULL;
4775     memset(&ctx, 0, sizeof ctx);
4776     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
4777     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4778         enum slow_path_reason slow;
4779
4780         action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
4781                               subfacet->initial_tci, new_rule, 0, NULL);
4782         xlate_actions(&ctx, new_rule->up.ofpacts, new_rule->up.ofpacts_len,
4783                       &odp_actions);
4784
4785         slow = (subfacet->slow & SLOW_MATCH) | ctx.slow;
4786         if (subfacet_should_install(subfacet, slow, &odp_actions)) {
4787             struct dpif_flow_stats stats;
4788
4789             subfacet_install(subfacet,
4790                              odp_actions.data, odp_actions.size, &stats, slow);
4791             subfacet_update_stats(subfacet, &stats);
4792
4793             if (!new_actions) {
4794                 new_actions = xcalloc(list_size(&facet->subfacets),
4795                                       sizeof *new_actions);
4796             }
4797             new_actions[i].odp_actions = xmemdup(odp_actions.data,
4798                                                  odp_actions.size);
4799             new_actions[i].actions_len = odp_actions.size;
4800         }
4801
4802         i++;
4803     }
4804     ofpbuf_uninit(&odp_actions);
4805
4806     if (new_actions) {
4807         facet_flush_stats(facet);
4808     }
4809
4810     /* Update 'facet' now that we've taken care of all the old state. */
4811     facet->tags = ctx.tags;
4812     facet->nf_flow.output_iface = ctx.nf_output_iface;
4813     facet->has_learn = ctx.has_learn;
4814     facet->has_normal = ctx.has_normal;
4815     facet->has_fin_timeout = ctx.has_fin_timeout;
4816     facet->mirrors = ctx.mirrors;
4817
4818     i = 0;
4819     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4820         subfacet->slow = (subfacet->slow & SLOW_MATCH) | ctx.slow;
4821
4822         if (new_actions && new_actions[i].odp_actions) {
4823             free(subfacet->actions);
4824             subfacet->actions = new_actions[i].odp_actions;
4825             subfacet->actions_len = new_actions[i].actions_len;
4826         }
4827         i++;
4828     }
4829     free(new_actions);
4830
4831     if (facet->rule != new_rule) {
4832         COVERAGE_INC(facet_changed_rule);
4833         list_remove(&facet->list_node);
4834         list_push_back(&new_rule->facets, &facet->list_node);
4835         facet->rule = new_rule;
4836         facet->used = new_rule->up.created;
4837         facet->prev_used = facet->used;
4838     }
4839 }
4840
4841 /* Updates 'facet''s used time.  Caller is responsible for calling
4842  * facet_push_stats() to update the flows which 'facet' resubmits into. */
4843 static void
4844 facet_update_time(struct facet *facet, long long int used)
4845 {
4846     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4847     if (used > facet->used) {
4848         facet->used = used;
4849         ofproto_rule_update_used(&facet->rule->up, used);
4850         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
4851     }
4852 }
4853
4854 static void
4855 facet_reset_counters(struct facet *facet)
4856 {
4857     facet->packet_count = 0;
4858     facet->byte_count = 0;
4859     facet->prev_packet_count = 0;
4860     facet->prev_byte_count = 0;
4861     facet->accounted_bytes = 0;
4862 }
4863
4864 static void
4865 facet_push_stats(struct facet *facet)
4866 {
4867     struct dpif_flow_stats stats;
4868
4869     ovs_assert(facet->packet_count >= facet->prev_packet_count);
4870     ovs_assert(facet->byte_count >= facet->prev_byte_count);
4871     ovs_assert(facet->used >= facet->prev_used);
4872
4873     stats.n_packets = facet->packet_count - facet->prev_packet_count;
4874     stats.n_bytes = facet->byte_count - facet->prev_byte_count;
4875     stats.used = facet->used;
4876     stats.tcp_flags = 0;
4877
4878     if (stats.n_packets || stats.n_bytes || facet->used > facet->prev_used) {
4879         facet->prev_packet_count = facet->packet_count;
4880         facet->prev_byte_count = facet->byte_count;
4881         facet->prev_used = facet->used;
4882
4883         flow_push_stats(facet->rule, &facet->flow, &stats);
4884
4885         update_mirror_stats(ofproto_dpif_cast(facet->rule->up.ofproto),
4886                             facet->mirrors, stats.n_packets, stats.n_bytes);
4887     }
4888 }
4889
4890 static void
4891 rule_credit_stats(struct rule_dpif *rule, const struct dpif_flow_stats *stats)
4892 {
4893     rule->packet_count += stats->n_packets;
4894     rule->byte_count += stats->n_bytes;
4895     ofproto_rule_update_used(&rule->up, stats->used);
4896 }
4897
4898 /* Pushes flow statistics to the rules which 'flow' resubmits into given
4899  * 'rule''s actions and mirrors. */
4900 static void
4901 flow_push_stats(struct rule_dpif *rule,
4902                 const struct flow *flow, const struct dpif_flow_stats *stats)
4903 {
4904     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4905     struct action_xlate_ctx ctx;
4906
4907     ofproto_rule_update_used(&rule->up, stats->used);
4908
4909     action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci, rule,
4910                           0, NULL);
4911     ctx.resubmit_stats = stats;
4912     xlate_actions_for_side_effects(&ctx, rule->up.ofpacts,
4913                                    rule->up.ofpacts_len);
4914 }
4915 \f
4916 /* Subfacets. */
4917
4918 static struct subfacet *
4919 subfacet_find(struct ofproto_dpif *ofproto,
4920               const struct nlattr *key, size_t key_len, uint32_t key_hash)
4921 {
4922     struct subfacet *subfacet;
4923
4924     HMAP_FOR_EACH_WITH_HASH (subfacet, hmap_node, key_hash,
4925                              &ofproto->subfacets) {
4926         if (subfacet->key_len == key_len
4927             && !memcmp(key, subfacet->key, key_len)) {
4928             return subfacet;
4929         }
4930     }
4931
4932     return NULL;
4933 }
4934
4935 /* Searches 'facet' (within 'ofproto') for a subfacet with the specified
4936  * 'key_fitness', 'key', and 'key_len' members in 'miss'.  Returns the
4937  * existing subfacet if there is one, otherwise creates and returns a
4938  * new subfacet.
4939  *
4940  * If the returned subfacet is new, then subfacet->actions will be NULL, in
4941  * which case the caller must populate the actions with
4942  * subfacet_make_actions(). */
4943 static struct subfacet *
4944 subfacet_create(struct facet *facet, struct flow_miss *miss,
4945                 long long int now)
4946 {
4947     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4948     enum odp_key_fitness key_fitness = miss->key_fitness;
4949     const struct nlattr *key = miss->key;
4950     size_t key_len = miss->key_len;
4951     uint32_t key_hash;
4952     struct subfacet *subfacet;
4953
4954     key_hash = odp_flow_key_hash(key, key_len);
4955
4956     if (list_is_empty(&facet->subfacets)) {
4957         subfacet = &facet->one_subfacet;
4958     } else {
4959         subfacet = subfacet_find(ofproto, key, key_len, key_hash);
4960         if (subfacet) {
4961             if (subfacet->facet == facet) {
4962                 return subfacet;
4963             }
4964
4965             /* This shouldn't happen. */
4966             VLOG_ERR_RL(&rl, "subfacet with wrong facet");
4967             subfacet_destroy(subfacet);
4968         }
4969
4970         subfacet = xmalloc(sizeof *subfacet);
4971     }
4972
4973     hmap_insert(&ofproto->subfacets, &subfacet->hmap_node, key_hash);
4974     list_push_back(&facet->subfacets, &subfacet->list_node);
4975     subfacet->facet = facet;
4976     subfacet->key_fitness = key_fitness;
4977     subfacet->key = xmemdup(key, key_len);
4978     subfacet->key_len = key_len;
4979     subfacet->used = now;
4980     subfacet->dp_packet_count = 0;
4981     subfacet->dp_byte_count = 0;
4982     subfacet->actions_len = 0;
4983     subfacet->actions = NULL;
4984     subfacet->slow = (subfacet->key_fitness == ODP_FIT_TOO_LITTLE
4985                       ? SLOW_MATCH
4986                       : 0);
4987     subfacet->path = SF_NOT_INSTALLED;
4988     subfacet->initial_tci = miss->initial_tci;
4989     subfacet->odp_in_port = miss->odp_in_port;
4990
4991     return subfacet;
4992 }
4993
4994 /* Uninstalls 'subfacet' from the datapath, if it is installed, removes it from
4995  * its facet within 'ofproto', and frees it. */
4996 static void
4997 subfacet_destroy__(struct subfacet *subfacet)
4998 {
4999     struct facet *facet = subfacet->facet;
5000     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
5001
5002     subfacet_uninstall(subfacet);
5003     hmap_remove(&ofproto->subfacets, &subfacet->hmap_node);
5004     list_remove(&subfacet->list_node);
5005     free(subfacet->key);
5006     free(subfacet->actions);
5007     if (subfacet != &facet->one_subfacet) {
5008         free(subfacet);
5009     }
5010 }
5011
5012 /* Destroys 'subfacet', as with subfacet_destroy__(), and then if this was the
5013  * last remaining subfacet in its facet destroys the facet too. */
5014 static void
5015 subfacet_destroy(struct subfacet *subfacet)
5016 {
5017     struct facet *facet = subfacet->facet;
5018
5019     if (list_is_singleton(&facet->subfacets)) {
5020         /* facet_remove() needs at least one subfacet (it will remove it). */
5021         facet_remove(facet);
5022     } else {
5023         subfacet_destroy__(subfacet);
5024     }
5025 }
5026
5027 static void
5028 subfacet_destroy_batch(struct ofproto_dpif *ofproto,
5029                        struct subfacet **subfacets, int n)
5030 {
5031     struct dpif_op ops[SUBFACET_DESTROY_MAX_BATCH];
5032     struct dpif_op *opsp[SUBFACET_DESTROY_MAX_BATCH];
5033     struct dpif_flow_stats stats[SUBFACET_DESTROY_MAX_BATCH];
5034     int i;
5035
5036     for (i = 0; i < n; i++) {
5037         ops[i].type = DPIF_OP_FLOW_DEL;
5038         ops[i].u.flow_del.key = subfacets[i]->key;
5039         ops[i].u.flow_del.key_len = subfacets[i]->key_len;
5040         ops[i].u.flow_del.stats = &stats[i];
5041         opsp[i] = &ops[i];
5042     }
5043
5044     dpif_operate(ofproto->backer->dpif, opsp, n);
5045     for (i = 0; i < n; i++) {
5046         subfacet_reset_dp_stats(subfacets[i], &stats[i]);
5047         subfacets[i]->path = SF_NOT_INSTALLED;
5048         subfacet_destroy(subfacets[i]);
5049     }
5050 }
5051
5052 /* Composes the datapath actions for 'subfacet' based on its rule's actions.
5053  * Translates the actions into 'odp_actions', which the caller must have
5054  * initialized and is responsible for uninitializing. */
5055 static void
5056 subfacet_make_actions(struct subfacet *subfacet, const struct ofpbuf *packet,
5057                       struct ofpbuf *odp_actions)
5058 {
5059     struct facet *facet = subfacet->facet;
5060     struct rule_dpif *rule = facet->rule;
5061     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5062
5063     struct action_xlate_ctx ctx;
5064
5065     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, subfacet->initial_tci,
5066                           rule, 0, packet);
5067     xlate_actions(&ctx, rule->up.ofpacts, rule->up.ofpacts_len, odp_actions);
5068     facet->tags = ctx.tags;
5069     facet->has_learn = ctx.has_learn;
5070     facet->has_normal = ctx.has_normal;
5071     facet->has_fin_timeout = ctx.has_fin_timeout;
5072     facet->nf_flow.output_iface = ctx.nf_output_iface;
5073     facet->mirrors = ctx.mirrors;
5074
5075     subfacet->slow = (subfacet->slow & SLOW_MATCH) | ctx.slow;
5076     if (subfacet->actions_len != odp_actions->size
5077         || memcmp(subfacet->actions, odp_actions->data, odp_actions->size)) {
5078         free(subfacet->actions);
5079         subfacet->actions_len = odp_actions->size;
5080         subfacet->actions = xmemdup(odp_actions->data, odp_actions->size);
5081     }
5082 }
5083
5084 /* Updates 'subfacet''s datapath flow, setting its actions to 'actions_len'
5085  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
5086  * in the datapath will be zeroed and 'stats' will be updated with traffic new
5087  * since 'subfacet' was last updated.
5088  *
5089  * Returns 0 if successful, otherwise a positive errno value. */
5090 static int
5091 subfacet_install(struct subfacet *subfacet,
5092                  const struct nlattr *actions, size_t actions_len,
5093                  struct dpif_flow_stats *stats,
5094                  enum slow_path_reason slow)
5095 {
5096     struct facet *facet = subfacet->facet;
5097     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
5098     enum subfacet_path path = subfacet_want_path(slow);
5099     uint64_t slow_path_stub[128 / 8];
5100     enum dpif_flow_put_flags flags;
5101     int ret;
5102
5103     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
5104     if (stats) {
5105         flags |= DPIF_FP_ZERO_STATS;
5106     }
5107
5108     if (path == SF_SLOW_PATH) {
5109         compose_slow_path(ofproto, &facet->flow, slow,
5110                           slow_path_stub, sizeof slow_path_stub,
5111                           &actions, &actions_len);
5112     }
5113
5114     ret = dpif_flow_put(ofproto->backer->dpif, flags, subfacet->key,
5115                         subfacet->key_len, actions, actions_len, stats);
5116
5117     if (stats) {
5118         subfacet_reset_dp_stats(subfacet, stats);
5119     }
5120
5121     if (!ret) {
5122         subfacet->path = path;
5123     }
5124     return ret;
5125 }
5126
5127 static int
5128 subfacet_reinstall(struct subfacet *subfacet, struct dpif_flow_stats *stats)
5129 {
5130     return subfacet_install(subfacet, subfacet->actions, subfacet->actions_len,
5131                             stats, subfacet->slow);
5132 }
5133
5134 /* If 'subfacet' is installed in the datapath, uninstalls it. */
5135 static void
5136 subfacet_uninstall(struct subfacet *subfacet)
5137 {
5138     if (subfacet->path != SF_NOT_INSTALLED) {
5139         struct rule_dpif *rule = subfacet->facet->rule;
5140         struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5141         struct dpif_flow_stats stats;
5142         int error;
5143
5144         error = dpif_flow_del(ofproto->backer->dpif, subfacet->key,
5145                               subfacet->key_len, &stats);
5146         subfacet_reset_dp_stats(subfacet, &stats);
5147         if (!error) {
5148             subfacet_update_stats(subfacet, &stats);
5149         }
5150         subfacet->path = SF_NOT_INSTALLED;
5151     } else {
5152         ovs_assert(subfacet->dp_packet_count == 0);
5153         ovs_assert(subfacet->dp_byte_count == 0);
5154     }
5155 }
5156
5157 /* Resets 'subfacet''s datapath statistics counters.  This should be called
5158  * when 'subfacet''s statistics are cleared in the datapath.  If 'stats' is
5159  * non-null, it should contain the statistics returned by dpif when 'subfacet'
5160  * was reset in the datapath.  'stats' will be modified to include only
5161  * statistics new since 'subfacet' was last updated. */
5162 static void
5163 subfacet_reset_dp_stats(struct subfacet *subfacet,
5164                         struct dpif_flow_stats *stats)
5165 {
5166     if (stats
5167         && subfacet->dp_packet_count <= stats->n_packets
5168         && subfacet->dp_byte_count <= stats->n_bytes) {
5169         stats->n_packets -= subfacet->dp_packet_count;
5170         stats->n_bytes -= subfacet->dp_byte_count;
5171     }
5172
5173     subfacet->dp_packet_count = 0;
5174     subfacet->dp_byte_count = 0;
5175 }
5176
5177 /* Updates 'subfacet''s used time.  The caller is responsible for calling
5178  * facet_push_stats() to update the flows which 'subfacet' resubmits into. */
5179 static void
5180 subfacet_update_time(struct subfacet *subfacet, long long int used)
5181 {
5182     if (used > subfacet->used) {
5183         subfacet->used = used;
5184         facet_update_time(subfacet->facet, used);
5185     }
5186 }
5187
5188 /* Folds the statistics from 'stats' into the counters in 'subfacet'.
5189  *
5190  * Because of the meaning of a subfacet's counters, it only makes sense to do
5191  * this if 'stats' are not tracked in the datapath, that is, if 'stats'
5192  * represents a packet that was sent by hand or if it represents statistics
5193  * that have been cleared out of the datapath. */
5194 static void
5195 subfacet_update_stats(struct subfacet *subfacet,
5196                       const struct dpif_flow_stats *stats)
5197 {
5198     if (stats->n_packets || stats->used > subfacet->used) {
5199         struct facet *facet = subfacet->facet;
5200
5201         subfacet_update_time(subfacet, stats->used);
5202         facet->packet_count += stats->n_packets;
5203         facet->byte_count += stats->n_bytes;
5204         facet->tcp_flags |= stats->tcp_flags;
5205         facet_push_stats(facet);
5206         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
5207     }
5208 }
5209 \f
5210 /* Rules. */
5211
5212 static struct rule_dpif *
5213 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow)
5214 {
5215     struct rule_dpif *rule;
5216
5217     rule = rule_dpif_lookup__(ofproto, flow, 0);
5218     if (rule) {
5219         return rule;
5220     }
5221
5222     return rule_dpif_miss_rule(ofproto, flow);
5223 }
5224
5225 static struct rule_dpif *
5226 rule_dpif_lookup__(struct ofproto_dpif *ofproto, const struct flow *flow,
5227                    uint8_t table_id)
5228 {
5229     struct cls_rule *cls_rule;
5230     struct classifier *cls;
5231
5232     if (table_id >= N_TABLES) {
5233         return NULL;
5234     }
5235
5236     cls = &ofproto->up.tables[table_id].cls;
5237     if (flow->nw_frag & FLOW_NW_FRAG_ANY
5238         && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
5239         /* For OFPC_NORMAL frag_handling, we must pretend that transport ports
5240          * are unavailable. */
5241         struct flow ofpc_normal_flow = *flow;
5242         ofpc_normal_flow.tp_src = htons(0);
5243         ofpc_normal_flow.tp_dst = htons(0);
5244         cls_rule = classifier_lookup(cls, &ofpc_normal_flow);
5245     } else {
5246         cls_rule = classifier_lookup(cls, flow);
5247     }
5248     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
5249 }
5250
5251 static struct rule_dpif *
5252 rule_dpif_miss_rule(struct ofproto_dpif *ofproto, const struct flow *flow)
5253 {
5254     struct ofport_dpif *port;
5255
5256     port = get_ofp_port(ofproto, flow->in_port);
5257     if (!port) {
5258         VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16, flow->in_port);
5259         return ofproto->miss_rule;
5260     }
5261
5262     if (port->up.pp.config & OFPUTIL_PC_NO_PACKET_IN) {
5263         return ofproto->no_packet_in_rule;
5264     }
5265     return ofproto->miss_rule;
5266 }
5267
5268 static void
5269 complete_operation(struct rule_dpif *rule)
5270 {
5271     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5272
5273     rule_invalidate(rule);
5274     if (clogged) {
5275         struct dpif_completion *c = xmalloc(sizeof *c);
5276         c->op = rule->up.pending;
5277         list_push_back(&ofproto->completions, &c->list_node);
5278     } else {
5279         ofoperation_complete(rule->up.pending, 0);
5280     }
5281 }
5282
5283 static struct rule *
5284 rule_alloc(void)
5285 {
5286     struct rule_dpif *rule = xmalloc(sizeof *rule);
5287     return &rule->up;
5288 }
5289
5290 static void
5291 rule_dealloc(struct rule *rule_)
5292 {
5293     struct rule_dpif *rule = rule_dpif_cast(rule_);
5294     free(rule);
5295 }
5296
5297 static enum ofperr
5298 rule_construct(struct rule *rule_)
5299 {
5300     struct rule_dpif *rule = rule_dpif_cast(rule_);
5301     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5302     struct rule_dpif *victim;
5303     uint8_t table_id;
5304
5305     rule->packet_count = 0;
5306     rule->byte_count = 0;
5307
5308     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
5309     if (victim && !list_is_empty(&victim->facets)) {
5310         struct facet *facet;
5311
5312         rule->facets = victim->facets;
5313         list_moved(&rule->facets);
5314         LIST_FOR_EACH (facet, list_node, &rule->facets) {
5315             /* XXX: We're only clearing our local counters here.  It's possible
5316              * that quite a few packets are unaccounted for in the datapath
5317              * statistics.  These will be accounted to the new rule instead of
5318              * cleared as required.  This could be fixed by clearing out the
5319              * datapath statistics for this facet, but currently it doesn't
5320              * seem worth it. */
5321             facet_reset_counters(facet);
5322             facet->rule = rule;
5323         }
5324     } else {
5325         /* Must avoid list_moved() in this case. */
5326         list_init(&rule->facets);
5327     }
5328
5329     table_id = rule->up.table_id;
5330     if (victim) {
5331         rule->tag = victim->tag;
5332     } else if (table_id == 0) {
5333         rule->tag = 0;
5334     } else {
5335         struct flow flow;
5336
5337         miniflow_expand(&rule->up.cr.match.flow, &flow);
5338         rule->tag = rule_calculate_tag(&flow, &rule->up.cr.match.mask,
5339                                        ofproto->tables[table_id].basis);
5340     }
5341
5342     complete_operation(rule);
5343     return 0;
5344 }
5345
5346 static void
5347 rule_destruct(struct rule *rule_)
5348 {
5349     struct rule_dpif *rule = rule_dpif_cast(rule_);
5350     struct facet *facet, *next_facet;
5351
5352     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
5353         facet_revalidate(facet);
5354     }
5355
5356     complete_operation(rule);
5357 }
5358
5359 static void
5360 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
5361 {
5362     struct rule_dpif *rule = rule_dpif_cast(rule_);
5363     struct facet *facet;
5364
5365     /* Start from historical data for 'rule' itself that are no longer tracked
5366      * in facets.  This counts, for example, facets that have expired. */
5367     *packets = rule->packet_count;
5368     *bytes = rule->byte_count;
5369
5370     /* Add any statistics that are tracked by facets.  This includes
5371      * statistical data recently updated by ofproto_update_stats() as well as
5372      * stats for packets that were executed "by hand" via dpif_execute(). */
5373     LIST_FOR_EACH (facet, list_node, &rule->facets) {
5374         *packets += facet->packet_count;
5375         *bytes += facet->byte_count;
5376     }
5377 }
5378
5379 static void
5380 rule_dpif_execute(struct rule_dpif *rule, const struct flow *flow,
5381                   struct ofpbuf *packet)
5382 {
5383     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5384
5385     struct dpif_flow_stats stats;
5386
5387     struct action_xlate_ctx ctx;
5388     uint64_t odp_actions_stub[1024 / 8];
5389     struct ofpbuf odp_actions;
5390
5391     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
5392     rule_credit_stats(rule, &stats);
5393
5394     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
5395     action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci,
5396                           rule, stats.tcp_flags, packet);
5397     ctx.resubmit_stats = &stats;
5398     xlate_actions(&ctx, rule->up.ofpacts, rule->up.ofpacts_len, &odp_actions);
5399
5400     execute_odp_actions(ofproto, flow, odp_actions.data,
5401                         odp_actions.size, packet);
5402
5403     ofpbuf_uninit(&odp_actions);
5404 }
5405
5406 static enum ofperr
5407 rule_execute(struct rule *rule, const struct flow *flow,
5408              struct ofpbuf *packet)
5409 {
5410     rule_dpif_execute(rule_dpif_cast(rule), flow, packet);
5411     ofpbuf_delete(packet);
5412     return 0;
5413 }
5414
5415 static void
5416 rule_modify_actions(struct rule *rule_)
5417 {
5418     struct rule_dpif *rule = rule_dpif_cast(rule_);
5419
5420     complete_operation(rule);
5421 }
5422 \f
5423 /* Sends 'packet' out 'ofport'.
5424  * May modify 'packet'.
5425  * Returns 0 if successful, otherwise a positive errno value. */
5426 static int
5427 send_packet(const struct ofport_dpif *ofport, struct ofpbuf *packet)
5428 {
5429     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
5430     uint64_t odp_actions_stub[1024 / 8];
5431     struct ofpbuf key, odp_actions;
5432     struct odputil_keybuf keybuf;
5433     uint32_t odp_port;
5434     struct flow flow;
5435     int error;
5436
5437     flow_extract(packet, 0, 0, NULL, OFPP_LOCAL, &flow);
5438     if (netdev_vport_is_patch(ofport->up.netdev)) {
5439         struct ofproto_dpif *peer_ofproto;
5440         struct dpif_flow_stats stats;
5441         struct ofport_dpif *peer;
5442         struct rule_dpif *rule;
5443
5444         peer = ofport_get_peer(ofport);
5445         if (!peer) {
5446             return ENODEV;
5447         }
5448
5449         dpif_flow_stats_extract(&flow, packet, time_msec(), &stats);
5450         netdev_vport_inc_tx(ofport->up.netdev, &stats);
5451         netdev_vport_inc_rx(peer->up.netdev, &stats);
5452
5453         flow.in_port = peer->up.ofp_port;
5454         peer_ofproto = ofproto_dpif_cast(peer->up.ofproto);
5455         rule = rule_dpif_lookup(peer_ofproto, &flow);
5456         rule_dpif_execute(rule, &flow, packet);
5457
5458         return 0;
5459     }
5460
5461     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
5462
5463     if (ofport->tnl_port) {
5464         struct dpif_flow_stats stats;
5465
5466         odp_port = tnl_port_send(ofport->tnl_port, &flow);
5467         if (odp_port == OVSP_NONE) {
5468             return ENODEV;
5469         }
5470
5471         dpif_flow_stats_extract(&flow, packet, time_msec(), &stats);
5472         netdev_vport_inc_tx(ofport->up.netdev, &stats);
5473         odp_put_tunnel_action(&flow.tunnel, &odp_actions);
5474         odp_put_skb_mark_action(flow.skb_mark, &odp_actions);
5475     } else {
5476         odp_port = vsp_realdev_to_vlandev(ofproto, ofport->odp_port,
5477                                           flow.vlan_tci);
5478         if (odp_port != ofport->odp_port) {
5479             eth_pop_vlan(packet);
5480             flow.vlan_tci = htons(0);
5481         }
5482     }
5483
5484     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5485     odp_flow_key_from_flow(&key, &flow,
5486                            ofp_port_to_odp_port(ofproto, flow.in_port));
5487
5488     compose_sflow_action(ofproto, &odp_actions, &flow, odp_port);
5489
5490     nl_msg_put_u32(&odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
5491     error = dpif_execute(ofproto->backer->dpif,
5492                          key.data, key.size,
5493                          odp_actions.data, odp_actions.size,
5494                          packet);
5495     ofpbuf_uninit(&odp_actions);
5496
5497     if (error) {
5498         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
5499                      ofproto->up.name, odp_port, strerror(error));
5500     }
5501     ofproto_update_local_port_stats(ofport->up.ofproto, packet->size, 0);
5502     return error;
5503 }
5504 \f
5505 /* OpenFlow to datapath action translation. */
5506
5507 static bool may_receive(const struct ofport_dpif *, struct action_xlate_ctx *);
5508 static void do_xlate_actions(const struct ofpact *, size_t ofpacts_len,
5509                              struct action_xlate_ctx *);
5510 static void xlate_normal(struct action_xlate_ctx *);
5511
5512 /* Composes an ODP action for a "slow path" action for 'flow' within 'ofproto'.
5513  * The action will state 'slow' as the reason that the action is in the slow
5514  * path.  (This is purely informational: it allows a human viewing "ovs-dpctl
5515  * dump-flows" output to see why a flow is in the slow path.)
5516  *
5517  * The 'stub_size' bytes in 'stub' will be used to store the action.
5518  * 'stub_size' must be large enough for the action.
5519  *
5520  * The action and its size will be stored in '*actionsp' and '*actions_lenp',
5521  * respectively. */
5522 static void
5523 compose_slow_path(const struct ofproto_dpif *ofproto, const struct flow *flow,
5524                   enum slow_path_reason slow,
5525                   uint64_t *stub, size_t stub_size,
5526                   const struct nlattr **actionsp, size_t *actions_lenp)
5527 {
5528     union user_action_cookie cookie;
5529     struct ofpbuf buf;
5530
5531     cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
5532     cookie.slow_path.unused = 0;
5533     cookie.slow_path.reason = slow;
5534
5535     ofpbuf_use_stack(&buf, stub, stub_size);
5536     if (slow & (SLOW_CFM | SLOW_LACP | SLOW_STP)) {
5537         uint32_t pid = dpif_port_get_pid(ofproto->backer->dpif, UINT32_MAX);
5538         odp_put_userspace_action(pid, &cookie, &buf);
5539     } else {
5540         put_userspace_action(ofproto, &buf, flow, &cookie);
5541     }
5542     *actionsp = buf.data;
5543     *actions_lenp = buf.size;
5544 }
5545
5546 static size_t
5547 put_userspace_action(const struct ofproto_dpif *ofproto,
5548                      struct ofpbuf *odp_actions,
5549                      const struct flow *flow,
5550                      const union user_action_cookie *cookie)
5551 {
5552     uint32_t pid;
5553
5554     pid = dpif_port_get_pid(ofproto->backer->dpif,
5555                             ofp_port_to_odp_port(ofproto, flow->in_port));
5556
5557     return odp_put_userspace_action(pid, cookie, odp_actions);
5558 }
5559
5560 static void
5561 compose_sflow_cookie(const struct ofproto_dpif *ofproto,
5562                      ovs_be16 vlan_tci, uint32_t odp_port,
5563                      unsigned int n_outputs, union user_action_cookie *cookie)
5564 {
5565     int ifindex;
5566
5567     cookie->type = USER_ACTION_COOKIE_SFLOW;
5568     cookie->sflow.vlan_tci = vlan_tci;
5569
5570     /* See http://www.sflow.org/sflow_version_5.txt (search for "Input/output
5571      * port information") for the interpretation of cookie->output. */
5572     switch (n_outputs) {
5573     case 0:
5574         /* 0x40000000 | 256 means "packet dropped for unknown reason". */
5575         cookie->sflow.output = 0x40000000 | 256;
5576         break;
5577
5578     case 1:
5579         ifindex = dpif_sflow_odp_port_to_ifindex(ofproto->sflow, odp_port);
5580         if (ifindex) {
5581             cookie->sflow.output = ifindex;
5582             break;
5583         }
5584         /* Fall through. */
5585     default:
5586         /* 0x80000000 means "multiple output ports. */
5587         cookie->sflow.output = 0x80000000 | n_outputs;
5588         break;
5589     }
5590 }
5591
5592 /* Compose SAMPLE action for sFlow. */
5593 static size_t
5594 compose_sflow_action(const struct ofproto_dpif *ofproto,
5595                      struct ofpbuf *odp_actions,
5596                      const struct flow *flow,
5597                      uint32_t odp_port)
5598 {
5599     uint32_t probability;
5600     union user_action_cookie cookie;
5601     size_t sample_offset, actions_offset;
5602     int cookie_offset;
5603
5604     if (!ofproto->sflow || flow->in_port == OFPP_NONE) {
5605         return 0;
5606     }
5607
5608     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
5609
5610     /* Number of packets out of UINT_MAX to sample. */
5611     probability = dpif_sflow_get_probability(ofproto->sflow);
5612     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
5613
5614     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
5615     compose_sflow_cookie(ofproto, htons(0), odp_port,
5616                          odp_port == OVSP_NONE ? 0 : 1, &cookie);
5617     cookie_offset = put_userspace_action(ofproto, odp_actions, flow, &cookie);
5618
5619     nl_msg_end_nested(odp_actions, actions_offset);
5620     nl_msg_end_nested(odp_actions, sample_offset);
5621     return cookie_offset;
5622 }
5623
5624 /* SAMPLE action must be first action in any given list of actions.
5625  * At this point we do not have all information required to build it. So try to
5626  * build sample action as complete as possible. */
5627 static void
5628 add_sflow_action(struct action_xlate_ctx *ctx)
5629 {
5630     ctx->user_cookie_offset = compose_sflow_action(ctx->ofproto,
5631                                                    ctx->odp_actions,
5632                                                    &ctx->flow, OVSP_NONE);
5633     ctx->sflow_odp_port = 0;
5634     ctx->sflow_n_outputs = 0;
5635 }
5636
5637 /* Fix SAMPLE action according to data collected while composing ODP actions.
5638  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
5639  * USERSPACE action's user-cookie which is required for sflow. */
5640 static void
5641 fix_sflow_action(struct action_xlate_ctx *ctx)
5642 {
5643     const struct flow *base = &ctx->base_flow;
5644     union user_action_cookie *cookie;
5645
5646     if (!ctx->user_cookie_offset) {
5647         return;
5648     }
5649
5650     cookie = ofpbuf_at(ctx->odp_actions, ctx->user_cookie_offset,
5651                        sizeof(*cookie));
5652     ovs_assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
5653
5654     compose_sflow_cookie(ctx->ofproto, base->vlan_tci,
5655                          ctx->sflow_odp_port, ctx->sflow_n_outputs, cookie);
5656 }
5657
5658 static void
5659 compose_output_action__(struct action_xlate_ctx *ctx, uint16_t ofp_port,
5660                         bool check_stp)
5661 {
5662     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
5663     ovs_be16 flow_vlan_tci = ctx->flow.vlan_tci;
5664     ovs_be64 flow_tun_id = ctx->flow.tunnel.tun_id;
5665     uint8_t flow_nw_tos = ctx->flow.nw_tos;
5666     struct priority_to_dscp *pdscp;
5667     uint32_t out_port, odp_port;
5668
5669     /* If 'struct flow' gets additional metadata, we'll need to zero it out
5670      * before traversing a patch port. */
5671     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 18);
5672
5673     if (!ofport) {
5674         xlate_report(ctx, "Nonexistent output port");
5675         return;
5676     } else if (ofport->up.pp.config & OFPUTIL_PC_NO_FWD) {
5677         xlate_report(ctx, "OFPPC_NO_FWD set, skipping output");
5678         return;
5679     } else if (check_stp && !stp_forward_in_state(ofport->stp_state)) {
5680         xlate_report(ctx, "STP not in forwarding state, skipping output");
5681         return;
5682     }
5683
5684     if (netdev_vport_is_patch(ofport->up.netdev)) {
5685         struct ofport_dpif *peer = ofport_get_peer(ofport);
5686         struct flow old_flow = ctx->flow;
5687         const struct ofproto_dpif *peer_ofproto;
5688         enum slow_path_reason special;
5689         struct ofport_dpif *in_port;
5690
5691         if (!peer) {
5692             xlate_report(ctx, "Nonexistent patch port peer");
5693             return;
5694         }
5695
5696         peer_ofproto = ofproto_dpif_cast(peer->up.ofproto);
5697         if (peer_ofproto->backer != ctx->ofproto->backer) {
5698             xlate_report(ctx, "Patch port peer on a different datapath");
5699             return;
5700         }
5701
5702         ctx->ofproto = ofproto_dpif_cast(peer->up.ofproto);
5703         ctx->flow.in_port = peer->up.ofp_port;
5704         ctx->flow.metadata = htonll(0);
5705         memset(&ctx->flow.tunnel, 0, sizeof ctx->flow.tunnel);
5706         memset(ctx->flow.regs, 0, sizeof ctx->flow.regs);
5707
5708         in_port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
5709         special = process_special(ctx->ofproto, &ctx->flow, in_port,
5710                                   ctx->packet);
5711         if (special) {
5712             ctx->slow |= special;
5713         } else if (!in_port || may_receive(in_port, ctx)) {
5714             if (!in_port || stp_forward_in_state(in_port->stp_state)) {
5715                 xlate_table_action(ctx, ctx->flow.in_port, 0, true);
5716             } else {
5717                 /* Forwarding is disabled by STP.  Let OFPP_NORMAL and the
5718                  * learning action look at the packet, then drop it. */
5719                 struct flow old_base_flow = ctx->base_flow;
5720                 size_t old_size = ctx->odp_actions->size;
5721                 xlate_table_action(ctx, ctx->flow.in_port, 0, true);
5722                 ctx->base_flow = old_base_flow;
5723                 ctx->odp_actions->size = old_size;
5724             }
5725         }
5726
5727         ctx->flow = old_flow;
5728         ctx->ofproto = ofproto_dpif_cast(ofport->up.ofproto);
5729
5730         if (ctx->resubmit_stats) {
5731             netdev_vport_inc_tx(ofport->up.netdev, ctx->resubmit_stats);
5732             netdev_vport_inc_rx(peer->up.netdev, ctx->resubmit_stats);
5733         }
5734
5735         return;
5736     }
5737
5738     pdscp = get_priority(ofport, ctx->flow.skb_priority);
5739     if (pdscp) {
5740         ctx->flow.nw_tos &= ~IP_DSCP_MASK;
5741         ctx->flow.nw_tos |= pdscp->dscp;
5742     }
5743
5744     odp_port = ofp_port_to_odp_port(ctx->ofproto, ofp_port);
5745     if (ofport->tnl_port) {
5746         odp_port = tnl_port_send(ofport->tnl_port, &ctx->flow);
5747         if (odp_port == OVSP_NONE) {
5748             xlate_report(ctx, "Tunneling decided against output");
5749             return;
5750         }
5751
5752         if (ctx->resubmit_stats) {
5753             netdev_vport_inc_tx(ofport->up.netdev, ctx->resubmit_stats);
5754         }
5755         out_port = odp_port;
5756         commit_odp_tunnel_action(&ctx->flow, &ctx->base_flow,
5757                                  ctx->odp_actions);
5758     } else {
5759         out_port = vsp_realdev_to_vlandev(ctx->ofproto, odp_port,
5760                                           ctx->flow.vlan_tci);
5761         if (out_port != odp_port) {
5762             ctx->flow.vlan_tci = htons(0);
5763         }
5764     }
5765     commit_odp_actions(&ctx->flow, &ctx->base_flow, ctx->odp_actions);
5766     nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_OUTPUT, out_port);
5767
5768     ctx->sflow_odp_port = odp_port;
5769     ctx->sflow_n_outputs++;
5770     ctx->nf_output_iface = ofp_port;
5771     ctx->flow.tunnel.tun_id = flow_tun_id;
5772     ctx->flow.vlan_tci = flow_vlan_tci;
5773     ctx->flow.nw_tos = flow_nw_tos;
5774 }
5775
5776 static void
5777 compose_output_action(struct action_xlate_ctx *ctx, uint16_t ofp_port)
5778 {
5779     compose_output_action__(ctx, ofp_port, true);
5780 }
5781
5782 static void
5783 xlate_table_action(struct action_xlate_ctx *ctx,
5784                    uint16_t in_port, uint8_t table_id, bool may_packet_in)
5785 {
5786     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
5787         struct ofproto_dpif *ofproto = ctx->ofproto;
5788         struct rule_dpif *rule;
5789         uint16_t old_in_port;
5790         uint8_t old_table_id;
5791
5792         old_table_id = ctx->table_id;
5793         ctx->table_id = table_id;
5794
5795         /* Look up a flow with 'in_port' as the input port. */
5796         old_in_port = ctx->flow.in_port;
5797         ctx->flow.in_port = in_port;
5798         rule = rule_dpif_lookup__(ofproto, &ctx->flow, table_id);
5799
5800         /* Tag the flow. */
5801         if (table_id > 0 && table_id < N_TABLES) {
5802             struct table_dpif *table = &ofproto->tables[table_id];
5803             if (table->other_table) {
5804                 ctx->tags |= (rule && rule->tag
5805                               ? rule->tag
5806                               : rule_calculate_tag(&ctx->flow,
5807                                                    &table->other_table->mask,
5808                                                    table->basis));
5809             }
5810         }
5811
5812         /* Restore the original input port.  Otherwise OFPP_NORMAL and
5813          * OFPP_IN_PORT will have surprising behavior. */
5814         ctx->flow.in_port = old_in_port;
5815
5816         if (ctx->resubmit_hook) {
5817             ctx->resubmit_hook(ctx, rule);
5818         }
5819
5820         if (rule == NULL && may_packet_in) {
5821             /* XXX
5822              * check if table configuration flags
5823              * OFPTC_TABLE_MISS_CONTROLLER, default.
5824              * OFPTC_TABLE_MISS_CONTINUE,
5825              * OFPTC_TABLE_MISS_DROP
5826              * When OF1.0, OFPTC_TABLE_MISS_CONTINUE is used. What to do?
5827              */
5828             rule = rule_dpif_miss_rule(ofproto, &ctx->flow);
5829         }
5830
5831         if (rule) {
5832             struct rule_dpif *old_rule = ctx->rule;
5833
5834             if (ctx->resubmit_stats) {
5835                 rule_credit_stats(rule, ctx->resubmit_stats);
5836             }
5837
5838             ctx->recurse++;
5839             ctx->rule = rule;
5840             do_xlate_actions(rule->up.ofpacts, rule->up.ofpacts_len, ctx);
5841             ctx->rule = old_rule;
5842             ctx->recurse--;
5843         }
5844
5845         ctx->table_id = old_table_id;
5846     } else {
5847         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
5848
5849         VLOG_ERR_RL(&recurse_rl, "resubmit actions recursed over %d times",
5850                     MAX_RESUBMIT_RECURSION);
5851         ctx->max_resubmit_trigger = true;
5852     }
5853 }
5854
5855 static void
5856 xlate_ofpact_resubmit(struct action_xlate_ctx *ctx,
5857                       const struct ofpact_resubmit *resubmit)
5858 {
5859     uint16_t in_port;
5860     uint8_t table_id;
5861
5862     in_port = resubmit->in_port;
5863     if (in_port == OFPP_IN_PORT) {
5864         in_port = ctx->flow.in_port;
5865     }
5866
5867     table_id = resubmit->table_id;
5868     if (table_id == 255) {
5869         table_id = ctx->table_id;
5870     }
5871
5872     xlate_table_action(ctx, in_port, table_id, false);
5873 }
5874
5875 static void
5876 flood_packets(struct action_xlate_ctx *ctx, bool all)
5877 {
5878     struct ofport_dpif *ofport;
5879
5880     HMAP_FOR_EACH (ofport, up.hmap_node, &ctx->ofproto->up.ports) {
5881         uint16_t ofp_port = ofport->up.ofp_port;
5882
5883         if (ofp_port == ctx->flow.in_port) {
5884             continue;
5885         }
5886
5887         if (all) {
5888             compose_output_action__(ctx, ofp_port, false);
5889         } else if (!(ofport->up.pp.config & OFPUTIL_PC_NO_FLOOD)) {
5890             compose_output_action(ctx, ofp_port);
5891         }
5892     }
5893
5894     ctx->nf_output_iface = NF_OUT_FLOOD;
5895 }
5896
5897 static void
5898 execute_controller_action(struct action_xlate_ctx *ctx, int len,
5899                           enum ofp_packet_in_reason reason,
5900                           uint16_t controller_id)
5901 {
5902     struct ofputil_packet_in pin;
5903     struct ofpbuf *packet;
5904
5905     ctx->slow |= SLOW_CONTROLLER;
5906     if (!ctx->packet) {
5907         return;
5908     }
5909
5910     packet = ofpbuf_clone(ctx->packet);
5911
5912     if (packet->l2 && packet->l3) {
5913         struct eth_header *eh;
5914
5915         eth_pop_vlan(packet);
5916         eh = packet->l2;
5917
5918         /* If the Ethernet type is less than ETH_TYPE_MIN, it's likely an 802.2
5919          * LLC frame.  Calculating the Ethernet type of these frames is more
5920          * trouble than seems appropriate for a simple assertion. */
5921         ovs_assert(ntohs(eh->eth_type) < ETH_TYPE_MIN
5922                    || eh->eth_type == ctx->flow.dl_type);
5923
5924         memcpy(eh->eth_src, ctx->flow.dl_src, sizeof eh->eth_src);
5925         memcpy(eh->eth_dst, ctx->flow.dl_dst, sizeof eh->eth_dst);
5926
5927         if (ctx->flow.vlan_tci & htons(VLAN_CFI)) {
5928             eth_push_vlan(packet, ctx->flow.vlan_tci);
5929         }
5930
5931         if (packet->l4) {
5932             if (ctx->flow.dl_type == htons(ETH_TYPE_IP)) {
5933                 packet_set_ipv4(packet, ctx->flow.nw_src, ctx->flow.nw_dst,
5934                                 ctx->flow.nw_tos, ctx->flow.nw_ttl);
5935             }
5936
5937             if (packet->l7) {
5938                 if (ctx->flow.nw_proto == IPPROTO_TCP) {
5939                     packet_set_tcp_port(packet, ctx->flow.tp_src,
5940                                         ctx->flow.tp_dst);
5941                 } else if (ctx->flow.nw_proto == IPPROTO_UDP) {
5942                     packet_set_udp_port(packet, ctx->flow.tp_src,
5943                                         ctx->flow.tp_dst);
5944                 }
5945             }
5946         }
5947     }
5948
5949     pin.packet = packet->data;
5950     pin.packet_len = packet->size;
5951     pin.reason = reason;
5952     pin.controller_id = controller_id;
5953     pin.table_id = ctx->table_id;
5954     pin.cookie = ctx->rule ? ctx->rule->up.flow_cookie : 0;
5955
5956     pin.send_len = len;
5957     flow_get_metadata(&ctx->flow, &pin.fmd);
5958
5959     connmgr_send_packet_in(ctx->ofproto->up.connmgr, &pin);
5960     ofpbuf_delete(packet);
5961 }
5962
5963 static bool
5964 compose_dec_ttl(struct action_xlate_ctx *ctx, struct ofpact_cnt_ids *ids)
5965 {
5966     if (ctx->flow.dl_type != htons(ETH_TYPE_IP) &&
5967         ctx->flow.dl_type != htons(ETH_TYPE_IPV6)) {
5968         return false;
5969     }
5970
5971     if (ctx->flow.nw_ttl > 1) {
5972         ctx->flow.nw_ttl--;
5973         return false;
5974     } else {
5975         size_t i;
5976
5977         for (i = 0; i < ids->n_controllers; i++) {
5978             execute_controller_action(ctx, UINT16_MAX, OFPR_INVALID_TTL,
5979                                       ids->cnt_ids[i]);
5980         }
5981
5982         /* Stop processing for current table. */
5983         return true;
5984     }
5985 }
5986
5987 static void
5988 xlate_output_action(struct action_xlate_ctx *ctx,
5989                     uint16_t port, uint16_t max_len, bool may_packet_in)
5990 {
5991     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
5992
5993     ctx->nf_output_iface = NF_OUT_DROP;
5994
5995     switch (port) {
5996     case OFPP_IN_PORT:
5997         compose_output_action(ctx, ctx->flow.in_port);
5998         break;
5999     case OFPP_TABLE:
6000         xlate_table_action(ctx, ctx->flow.in_port, 0, may_packet_in);
6001         break;
6002     case OFPP_NORMAL:
6003         xlate_normal(ctx);
6004         break;
6005     case OFPP_FLOOD:
6006         flood_packets(ctx,  false);
6007         break;
6008     case OFPP_ALL:
6009         flood_packets(ctx, true);
6010         break;
6011     case OFPP_CONTROLLER:
6012         execute_controller_action(ctx, max_len, OFPR_ACTION, 0);
6013         break;
6014     case OFPP_NONE:
6015         break;
6016     case OFPP_LOCAL:
6017     default:
6018         if (port != ctx->flow.in_port) {
6019             compose_output_action(ctx, port);
6020         } else {
6021             xlate_report(ctx, "skipping output to input port");
6022         }
6023         break;
6024     }
6025
6026     if (prev_nf_output_iface == NF_OUT_FLOOD) {
6027         ctx->nf_output_iface = NF_OUT_FLOOD;
6028     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
6029         ctx->nf_output_iface = prev_nf_output_iface;
6030     } else if (prev_nf_output_iface != NF_OUT_DROP &&
6031                ctx->nf_output_iface != NF_OUT_FLOOD) {
6032         ctx->nf_output_iface = NF_OUT_MULTI;
6033     }
6034 }
6035
6036 static void
6037 xlate_output_reg_action(struct action_xlate_ctx *ctx,
6038                         const struct ofpact_output_reg *or)
6039 {
6040     uint64_t port = mf_get_subfield(&or->src, &ctx->flow);
6041     if (port <= UINT16_MAX) {
6042         xlate_output_action(ctx, port, or->max_len, false);
6043     }
6044 }
6045
6046 static void
6047 xlate_enqueue_action(struct action_xlate_ctx *ctx,
6048                      const struct ofpact_enqueue *enqueue)
6049 {
6050     uint16_t ofp_port = enqueue->port;
6051     uint32_t queue_id = enqueue->queue;
6052     uint32_t flow_priority, priority;
6053     int error;
6054
6055     /* Translate queue to priority. */
6056     error = dpif_queue_to_priority(ctx->ofproto->backer->dpif,
6057                                    queue_id, &priority);
6058     if (error) {
6059         /* Fall back to ordinary output action. */
6060         xlate_output_action(ctx, enqueue->port, 0, false);
6061         return;
6062     }
6063
6064     /* Check output port. */
6065     if (ofp_port == OFPP_IN_PORT) {
6066         ofp_port = ctx->flow.in_port;
6067     } else if (ofp_port == ctx->flow.in_port) {
6068         return;
6069     }
6070
6071     /* Add datapath actions. */
6072     flow_priority = ctx->flow.skb_priority;
6073     ctx->flow.skb_priority = priority;
6074     compose_output_action(ctx, ofp_port);
6075     ctx->flow.skb_priority = flow_priority;
6076
6077     /* Update NetFlow output port. */
6078     if (ctx->nf_output_iface == NF_OUT_DROP) {
6079         ctx->nf_output_iface = ofp_port;
6080     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
6081         ctx->nf_output_iface = NF_OUT_MULTI;
6082     }
6083 }
6084
6085 static void
6086 xlate_set_queue_action(struct action_xlate_ctx *ctx, uint32_t queue_id)
6087 {
6088     uint32_t skb_priority;
6089
6090     if (!dpif_queue_to_priority(ctx->ofproto->backer->dpif,
6091                                 queue_id, &skb_priority)) {
6092         ctx->flow.skb_priority = skb_priority;
6093     } else {
6094         /* Couldn't translate queue to a priority.  Nothing to do.  A warning
6095          * has already been logged. */
6096     }
6097 }
6098
6099 struct xlate_reg_state {
6100     ovs_be16 vlan_tci;
6101     ovs_be64 tun_id;
6102 };
6103
6104 static void
6105 xlate_autopath(struct action_xlate_ctx *ctx,
6106                const struct ofpact_autopath *ap)
6107 {
6108     uint16_t ofp_port = ap->port;
6109     struct ofport_dpif *port = get_ofp_port(ctx->ofproto, ofp_port);
6110
6111     if (!port || !port->bundle) {
6112         ofp_port = OFPP_NONE;
6113     } else if (port->bundle->bond) {
6114         /* Autopath does not support VLAN hashing. */
6115         struct ofport_dpif *slave = bond_choose_output_slave(
6116             port->bundle->bond, &ctx->flow, 0, &ctx->tags);
6117         if (slave) {
6118             ofp_port = slave->up.ofp_port;
6119         }
6120     }
6121     nxm_reg_load(&ap->dst, ofp_port, &ctx->flow);
6122 }
6123
6124 static bool
6125 slave_enabled_cb(uint16_t ofp_port, void *ofproto_)
6126 {
6127     struct ofproto_dpif *ofproto = ofproto_;
6128     struct ofport_dpif *port;
6129
6130     switch (ofp_port) {
6131     case OFPP_IN_PORT:
6132     case OFPP_TABLE:
6133     case OFPP_NORMAL:
6134     case OFPP_FLOOD:
6135     case OFPP_ALL:
6136     case OFPP_NONE:
6137         return true;
6138     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
6139         return false;
6140     default:
6141         port = get_ofp_port(ofproto, ofp_port);
6142         return port ? port->may_enable : false;
6143     }
6144 }
6145
6146 static void
6147 xlate_bundle_action(struct action_xlate_ctx *ctx,
6148                     const struct ofpact_bundle *bundle)
6149 {
6150     uint16_t port;
6151
6152     port = bundle_execute(bundle, &ctx->flow, slave_enabled_cb, ctx->ofproto);
6153     if (bundle->dst.field) {
6154         nxm_reg_load(&bundle->dst, port, &ctx->flow);
6155     } else {
6156         xlate_output_action(ctx, port, 0, false);
6157     }
6158 }
6159
6160 static void
6161 xlate_learn_action(struct action_xlate_ctx *ctx,
6162                    const struct ofpact_learn *learn)
6163 {
6164     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
6165     struct ofputil_flow_mod fm;
6166     uint64_t ofpacts_stub[1024 / 8];
6167     struct ofpbuf ofpacts;
6168     int error;
6169
6170     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
6171     learn_execute(learn, &ctx->flow, &fm, &ofpacts);
6172
6173     error = ofproto_flow_mod(&ctx->ofproto->up, &fm);
6174     if (error && !VLOG_DROP_WARN(&rl)) {
6175         VLOG_WARN("learning action failed to modify flow table (%s)",
6176                   ofperr_get_name(error));
6177     }
6178
6179     ofpbuf_uninit(&ofpacts);
6180 }
6181
6182 /* Reduces '*timeout' to no more than 'max'.  A value of zero in either case
6183  * means "infinite". */
6184 static void
6185 reduce_timeout(uint16_t max, uint16_t *timeout)
6186 {
6187     if (max && (!*timeout || *timeout > max)) {
6188         *timeout = max;
6189     }
6190 }
6191
6192 static void
6193 xlate_fin_timeout(struct action_xlate_ctx *ctx,
6194                   const struct ofpact_fin_timeout *oft)
6195 {
6196     if (ctx->tcp_flags & (TCP_FIN | TCP_RST) && ctx->rule) {
6197         struct rule_dpif *rule = ctx->rule;
6198
6199         reduce_timeout(oft->fin_idle_timeout, &rule->up.idle_timeout);
6200         reduce_timeout(oft->fin_hard_timeout, &rule->up.hard_timeout);
6201     }
6202 }
6203
6204 static bool
6205 may_receive(const struct ofport_dpif *port, struct action_xlate_ctx *ctx)
6206 {
6207     if (port->up.pp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
6208                               ? OFPUTIL_PC_NO_RECV_STP
6209                               : OFPUTIL_PC_NO_RECV)) {
6210         return false;
6211     }
6212
6213     /* Only drop packets here if both forwarding and learning are
6214      * disabled.  If just learning is enabled, we need to have
6215      * OFPP_NORMAL and the learning action have a look at the packet
6216      * before we can drop it. */
6217     if (!stp_forward_in_state(port->stp_state)
6218             && !stp_learn_in_state(port->stp_state)) {
6219         return false;
6220     }
6221
6222     return true;
6223 }
6224
6225 static void
6226 do_xlate_actions(const struct ofpact *ofpacts, size_t ofpacts_len,
6227                  struct action_xlate_ctx *ctx)
6228 {
6229     bool was_evictable = true;
6230     const struct ofpact *a;
6231
6232     if (ctx->rule) {
6233         /* Don't let the rule we're working on get evicted underneath us. */
6234         was_evictable = ctx->rule->up.evictable;
6235         ctx->rule->up.evictable = false;
6236     }
6237     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6238         struct ofpact_controller *controller;
6239         const struct ofpact_metadata *metadata;
6240
6241         if (ctx->exit) {
6242             break;
6243         }
6244
6245         switch (a->type) {
6246         case OFPACT_OUTPUT:
6247             xlate_output_action(ctx, ofpact_get_OUTPUT(a)->port,
6248                                 ofpact_get_OUTPUT(a)->max_len, true);
6249             break;
6250
6251         case OFPACT_CONTROLLER:
6252             controller = ofpact_get_CONTROLLER(a);
6253             execute_controller_action(ctx, controller->max_len,
6254                                       controller->reason,
6255                                       controller->controller_id);
6256             break;
6257
6258         case OFPACT_ENQUEUE:
6259             xlate_enqueue_action(ctx, ofpact_get_ENQUEUE(a));
6260             break;
6261
6262         case OFPACT_SET_VLAN_VID:
6263             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
6264             ctx->flow.vlan_tci |= (htons(ofpact_get_SET_VLAN_VID(a)->vlan_vid)
6265                                    | htons(VLAN_CFI));
6266             break;
6267
6268         case OFPACT_SET_VLAN_PCP:
6269             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
6270             ctx->flow.vlan_tci |= htons((ofpact_get_SET_VLAN_PCP(a)->vlan_pcp
6271                                          << VLAN_PCP_SHIFT)
6272                                         | VLAN_CFI);
6273             break;
6274
6275         case OFPACT_STRIP_VLAN:
6276             ctx->flow.vlan_tci = htons(0);
6277             break;
6278
6279         case OFPACT_PUSH_VLAN:
6280             /* XXX 802.1AD(QinQ) */
6281             ctx->flow.vlan_tci = htons(VLAN_CFI);
6282             break;
6283
6284         case OFPACT_SET_ETH_SRC:
6285             memcpy(ctx->flow.dl_src, ofpact_get_SET_ETH_SRC(a)->mac,
6286                    ETH_ADDR_LEN);
6287             break;
6288
6289         case OFPACT_SET_ETH_DST:
6290             memcpy(ctx->flow.dl_dst, ofpact_get_SET_ETH_DST(a)->mac,
6291                    ETH_ADDR_LEN);
6292             break;
6293
6294         case OFPACT_SET_IPV4_SRC:
6295             ctx->flow.nw_src = ofpact_get_SET_IPV4_SRC(a)->ipv4;
6296             break;
6297
6298         case OFPACT_SET_IPV4_DST:
6299             ctx->flow.nw_dst = ofpact_get_SET_IPV4_DST(a)->ipv4;
6300             break;
6301
6302         case OFPACT_SET_IPV4_DSCP:
6303             /* OpenFlow 1.0 only supports IPv4. */
6304             if (ctx->flow.dl_type == htons(ETH_TYPE_IP)) {
6305                 ctx->flow.nw_tos &= ~IP_DSCP_MASK;
6306                 ctx->flow.nw_tos |= ofpact_get_SET_IPV4_DSCP(a)->dscp;
6307             }
6308             break;
6309
6310         case OFPACT_SET_L4_SRC_PORT:
6311             ctx->flow.tp_src = htons(ofpact_get_SET_L4_SRC_PORT(a)->port);
6312             break;
6313
6314         case OFPACT_SET_L4_DST_PORT:
6315             ctx->flow.tp_dst = htons(ofpact_get_SET_L4_DST_PORT(a)->port);
6316             break;
6317
6318         case OFPACT_RESUBMIT:
6319             xlate_ofpact_resubmit(ctx, ofpact_get_RESUBMIT(a));
6320             break;
6321
6322         case OFPACT_SET_TUNNEL:
6323             ctx->flow.tunnel.tun_id = htonll(ofpact_get_SET_TUNNEL(a)->tun_id);
6324             break;
6325
6326         case OFPACT_SET_QUEUE:
6327             xlate_set_queue_action(ctx, ofpact_get_SET_QUEUE(a)->queue_id);
6328             break;
6329
6330         case OFPACT_POP_QUEUE:
6331             ctx->flow.skb_priority = ctx->orig_skb_priority;
6332             break;
6333
6334         case OFPACT_REG_MOVE:
6335             nxm_execute_reg_move(ofpact_get_REG_MOVE(a), &ctx->flow);
6336             break;
6337
6338         case OFPACT_REG_LOAD:
6339             nxm_execute_reg_load(ofpact_get_REG_LOAD(a), &ctx->flow);
6340             break;
6341
6342         case OFPACT_DEC_TTL:
6343             if (compose_dec_ttl(ctx, ofpact_get_DEC_TTL(a))) {
6344                 goto out;
6345             }
6346             break;
6347
6348         case OFPACT_NOTE:
6349             /* Nothing to do. */
6350             break;
6351
6352         case OFPACT_MULTIPATH:
6353             multipath_execute(ofpact_get_MULTIPATH(a), &ctx->flow);
6354             break;
6355
6356         case OFPACT_AUTOPATH:
6357             xlate_autopath(ctx, ofpact_get_AUTOPATH(a));
6358             break;
6359
6360         case OFPACT_BUNDLE:
6361             ctx->ofproto->has_bundle_action = true;
6362             xlate_bundle_action(ctx, ofpact_get_BUNDLE(a));
6363             break;
6364
6365         case OFPACT_OUTPUT_REG:
6366             xlate_output_reg_action(ctx, ofpact_get_OUTPUT_REG(a));
6367             break;
6368
6369         case OFPACT_LEARN:
6370             ctx->has_learn = true;
6371             if (ctx->may_learn) {
6372                 xlate_learn_action(ctx, ofpact_get_LEARN(a));
6373             }
6374             break;
6375
6376         case OFPACT_EXIT:
6377             ctx->exit = true;
6378             break;
6379
6380         case OFPACT_FIN_TIMEOUT:
6381             ctx->has_fin_timeout = true;
6382             xlate_fin_timeout(ctx, ofpact_get_FIN_TIMEOUT(a));
6383             break;
6384
6385         case OFPACT_CLEAR_ACTIONS:
6386             /* XXX
6387              * Nothing to do because writa-actions is not supported for now.
6388              * When writa-actions is supported, clear-actions also must
6389              * be supported at the same time.
6390              */
6391             break;
6392
6393         case OFPACT_WRITE_METADATA:
6394             metadata = ofpact_get_WRITE_METADATA(a);
6395             ctx->flow.metadata &= ~metadata->mask;
6396             ctx->flow.metadata |= metadata->metadata & metadata->mask;
6397             break;
6398
6399         case OFPACT_GOTO_TABLE: {
6400             /* XXX remove recursion */
6401             /* It is assumed that goto-table is last action */
6402             struct ofpact_goto_table *ogt = ofpact_get_GOTO_TABLE(a);
6403             ovs_assert(ctx->table_id < ogt->table_id);
6404             xlate_table_action(ctx, ctx->flow.in_port, ogt->table_id, true);
6405             break;
6406         }
6407         }
6408     }
6409
6410 out:
6411     if (ctx->rule) {
6412         ctx->rule->up.evictable = was_evictable;
6413     }
6414 }
6415
6416 static void
6417 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
6418                       struct ofproto_dpif *ofproto, const struct flow *flow,
6419                       ovs_be16 initial_tci, struct rule_dpif *rule,
6420                       uint8_t tcp_flags, const struct ofpbuf *packet)
6421 {
6422     ovs_be64 initial_tun_id = flow->tunnel.tun_id;
6423
6424     /* Flow initialization rules:
6425      * - 'base_flow' must match the kernel's view of the packet at the
6426      *   time that action processing starts.  'flow' represents any
6427      *   transformations we wish to make through actions.
6428      * - By default 'base_flow' and 'flow' are the same since the input
6429      *   packet matches the output before any actions are applied.
6430      * - When using VLAN splinters, 'base_flow''s VLAN is set to the value
6431      *   of the received packet as seen by the kernel.  If we later output
6432      *   to another device without any modifications this will cause us to
6433      *   insert a new tag since the original one was stripped off by the
6434      *   VLAN device.
6435      * - Tunnel 'flow' is largely cleared when transitioning between
6436      *   the input and output stages since it does not make sense to output
6437      *   a packet with the exact headers that it was received with (i.e.
6438      *   the destination IP is us).  The one exception is the tun_id, which
6439      *   is preserved to allow use in later resubmit lookups and loads into
6440      *   registers.
6441      * - Tunnel 'base_flow' is completely cleared since that is what the
6442      *   kernel does.  If we wish to maintain the original values an action
6443      *   needs to be generated. */
6444
6445     ctx->ofproto = ofproto;
6446     ctx->flow = *flow;
6447     memset(&ctx->flow.tunnel, 0, sizeof ctx->flow.tunnel);
6448     ctx->base_flow = ctx->flow;
6449     ctx->base_flow.vlan_tci = initial_tci;
6450     ctx->flow.tunnel.tun_id = initial_tun_id;
6451     ctx->rule = rule;
6452     ctx->packet = packet;
6453     ctx->may_learn = packet != NULL;
6454     ctx->tcp_flags = tcp_flags;
6455     ctx->resubmit_hook = NULL;
6456     ctx->report_hook = NULL;
6457     ctx->resubmit_stats = NULL;
6458 }
6459
6460 /* Translates the 'ofpacts_len' bytes of "struct ofpacts" starting at 'ofpacts'
6461  * into datapath actions in 'odp_actions', using 'ctx'. */
6462 static void
6463 xlate_actions(struct action_xlate_ctx *ctx,
6464               const struct ofpact *ofpacts, size_t ofpacts_len,
6465               struct ofpbuf *odp_actions)
6466 {
6467     /* Normally false.  Set to true if we ever hit MAX_RESUBMIT_RECURSION, so
6468      * that in the future we always keep a copy of the original flow for
6469      * tracing purposes. */
6470     static bool hit_resubmit_limit;
6471
6472     enum slow_path_reason special;
6473     struct ofport_dpif *in_port;
6474
6475     COVERAGE_INC(ofproto_dpif_xlate);
6476
6477     ofpbuf_clear(odp_actions);
6478     ofpbuf_reserve(odp_actions, NL_A_U32_SIZE);
6479
6480     ctx->odp_actions = odp_actions;
6481     ctx->tags = 0;
6482     ctx->slow = 0;
6483     ctx->has_learn = false;
6484     ctx->has_normal = false;
6485     ctx->has_fin_timeout = false;
6486     ctx->nf_output_iface = NF_OUT_DROP;
6487     ctx->mirrors = 0;
6488     ctx->recurse = 0;
6489     ctx->max_resubmit_trigger = false;
6490     ctx->orig_skb_priority = ctx->flow.skb_priority;
6491     ctx->table_id = 0;
6492     ctx->exit = false;
6493
6494     if (ctx->ofproto->has_mirrors || hit_resubmit_limit) {
6495         /* Do this conditionally because the copy is expensive enough that it
6496          * shows up in profiles.
6497          *
6498          * We keep orig_flow in 'ctx' only because I couldn't make GCC 4.4
6499          * believe that I wasn't using it without initializing it if I kept it
6500          * in a local variable. */
6501         ctx->orig_flow = ctx->flow;
6502     }
6503
6504     if (ctx->flow.nw_frag & FLOW_NW_FRAG_ANY) {
6505         switch (ctx->ofproto->up.frag_handling) {
6506         case OFPC_FRAG_NORMAL:
6507             /* We must pretend that transport ports are unavailable. */
6508             ctx->flow.tp_src = ctx->base_flow.tp_src = htons(0);
6509             ctx->flow.tp_dst = ctx->base_flow.tp_dst = htons(0);
6510             break;
6511
6512         case OFPC_FRAG_DROP:
6513             return;
6514
6515         case OFPC_FRAG_REASM:
6516             NOT_REACHED();
6517
6518         case OFPC_FRAG_NX_MATCH:
6519             /* Nothing to do. */
6520             break;
6521
6522         case OFPC_INVALID_TTL_TO_CONTROLLER:
6523             NOT_REACHED();
6524         }
6525     }
6526
6527     in_port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
6528     special = process_special(ctx->ofproto, &ctx->flow, in_port, ctx->packet);
6529     if (special) {
6530         ctx->slow |= special;
6531     } else {
6532         static struct vlog_rate_limit trace_rl = VLOG_RATE_LIMIT_INIT(1, 1);
6533         ovs_be16 initial_tci = ctx->base_flow.vlan_tci;
6534         uint32_t local_odp_port;
6535
6536         add_sflow_action(ctx);
6537
6538         if (!in_port || may_receive(in_port, ctx)) {
6539             do_xlate_actions(ofpacts, ofpacts_len, ctx);
6540
6541             /* We've let OFPP_NORMAL and the learning action look at the
6542              * packet, so drop it now if forwarding is disabled. */
6543             if (in_port && !stp_forward_in_state(in_port->stp_state)) {
6544                 ofpbuf_clear(ctx->odp_actions);
6545                 add_sflow_action(ctx);
6546             }
6547         }
6548
6549         if (ctx->max_resubmit_trigger && !ctx->resubmit_hook) {
6550             if (!hit_resubmit_limit) {
6551                 /* We didn't record the original flow.  Make sure we do from
6552                  * now on. */
6553                 hit_resubmit_limit = true;
6554             } else if (!VLOG_DROP_ERR(&trace_rl)) {
6555                 struct ds ds = DS_EMPTY_INITIALIZER;
6556
6557                 ofproto_trace(ctx->ofproto, &ctx->orig_flow, ctx->packet,
6558                               initial_tci, &ds);
6559                 VLOG_ERR("Trace triggered by excessive resubmit "
6560                          "recursion:\n%s", ds_cstr(&ds));
6561                 ds_destroy(&ds);
6562             }
6563         }
6564
6565         local_odp_port = ofp_port_to_odp_port(ctx->ofproto, OFPP_LOCAL);
6566         if (!connmgr_may_set_up_flow(ctx->ofproto->up.connmgr, &ctx->flow,
6567                                      local_odp_port,
6568                                      ctx->odp_actions->data,
6569                                      ctx->odp_actions->size)) {
6570             ctx->slow |= SLOW_IN_BAND;
6571             if (ctx->packet
6572                 && connmgr_msg_in_hook(ctx->ofproto->up.connmgr, &ctx->flow,
6573                                        ctx->packet)) {
6574                 compose_output_action(ctx, OFPP_LOCAL);
6575             }
6576         }
6577         if (ctx->ofproto->has_mirrors) {
6578             add_mirror_actions(ctx, &ctx->orig_flow);
6579         }
6580         fix_sflow_action(ctx);
6581     }
6582 }
6583
6584 /* Translates the 'ofpacts_len' bytes of "struct ofpact"s starting at 'ofpacts'
6585  * into datapath actions, using 'ctx', and discards the datapath actions. */
6586 static void
6587 xlate_actions_for_side_effects(struct action_xlate_ctx *ctx,
6588                                const struct ofpact *ofpacts,
6589                                size_t ofpacts_len)
6590 {
6591     uint64_t odp_actions_stub[1024 / 8];
6592     struct ofpbuf odp_actions;
6593
6594     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
6595     xlate_actions(ctx, ofpacts, ofpacts_len, &odp_actions);
6596     ofpbuf_uninit(&odp_actions);
6597 }
6598
6599 static void
6600 xlate_report(struct action_xlate_ctx *ctx, const char *s)
6601 {
6602     if (ctx->report_hook) {
6603         ctx->report_hook(ctx, s);
6604     }
6605 }
6606 \f
6607 /* OFPP_NORMAL implementation. */
6608
6609 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
6610
6611 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
6612  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_bundle',
6613  * the bundle on which the packet was received, returns the VLAN to which the
6614  * packet belongs.
6615  *
6616  * Both 'vid' and the return value are in the range 0...4095. */
6617 static uint16_t
6618 input_vid_to_vlan(const struct ofbundle *in_bundle, uint16_t vid)
6619 {
6620     switch (in_bundle->vlan_mode) {
6621     case PORT_VLAN_ACCESS:
6622         return in_bundle->vlan;
6623         break;
6624
6625     case PORT_VLAN_TRUNK:
6626         return vid;
6627
6628     case PORT_VLAN_NATIVE_UNTAGGED:
6629     case PORT_VLAN_NATIVE_TAGGED:
6630         return vid ? vid : in_bundle->vlan;
6631
6632     default:
6633         NOT_REACHED();
6634     }
6635 }
6636
6637 /* Checks whether a packet with the given 'vid' may ingress on 'in_bundle'.
6638  * If so, returns true.  Otherwise, returns false and, if 'warn' is true, logs
6639  * a warning.
6640  *
6641  * 'vid' should be the VID obtained from the 802.1Q header that was received as
6642  * part of a packet (specify 0 if there was no 802.1Q header), in the range
6643  * 0...4095. */
6644 static bool
6645 input_vid_is_valid(uint16_t vid, struct ofbundle *in_bundle, bool warn)
6646 {
6647     /* Allow any VID on the OFPP_NONE port. */
6648     if (in_bundle == &ofpp_none_bundle) {
6649         return true;
6650     }
6651
6652     switch (in_bundle->vlan_mode) {
6653     case PORT_VLAN_ACCESS:
6654         if (vid) {
6655             if (warn) {
6656                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6657                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" tagged "
6658                              "packet received on port %s configured as VLAN "
6659                              "%"PRIu16" access port",
6660                              in_bundle->ofproto->up.name, vid,
6661                              in_bundle->name, in_bundle->vlan);
6662             }
6663             return false;
6664         }
6665         return true;
6666
6667     case PORT_VLAN_NATIVE_UNTAGGED:
6668     case PORT_VLAN_NATIVE_TAGGED:
6669         if (!vid) {
6670             /* Port must always carry its native VLAN. */
6671             return true;
6672         }
6673         /* Fall through. */
6674     case PORT_VLAN_TRUNK:
6675         if (!ofbundle_includes_vlan(in_bundle, vid)) {
6676             if (warn) {
6677                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6678                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" packet "
6679                              "received on port %s not configured for trunking "
6680                              "VLAN %"PRIu16,
6681                              in_bundle->ofproto->up.name, vid,
6682                              in_bundle->name, vid);
6683             }
6684             return false;
6685         }
6686         return true;
6687
6688     default:
6689         NOT_REACHED();
6690     }
6691
6692 }
6693
6694 /* Given 'vlan', the VLAN that a packet belongs to, and
6695  * 'out_bundle', a bundle on which the packet is to be output, returns the VID
6696  * that should be included in the 802.1Q header.  (If the return value is 0,
6697  * then the 802.1Q header should only be included in the packet if there is a
6698  * nonzero PCP.)
6699  *
6700  * Both 'vlan' and the return value are in the range 0...4095. */
6701 static uint16_t
6702 output_vlan_to_vid(const struct ofbundle *out_bundle, uint16_t vlan)
6703 {
6704     switch (out_bundle->vlan_mode) {
6705     case PORT_VLAN_ACCESS:
6706         return 0;
6707
6708     case PORT_VLAN_TRUNK:
6709     case PORT_VLAN_NATIVE_TAGGED:
6710         return vlan;
6711
6712     case PORT_VLAN_NATIVE_UNTAGGED:
6713         return vlan == out_bundle->vlan ? 0 : vlan;
6714
6715     default:
6716         NOT_REACHED();
6717     }
6718 }
6719
6720 static void
6721 output_normal(struct action_xlate_ctx *ctx, const struct ofbundle *out_bundle,
6722               uint16_t vlan)
6723 {
6724     struct ofport_dpif *port;
6725     uint16_t vid;
6726     ovs_be16 tci, old_tci;
6727
6728     vid = output_vlan_to_vid(out_bundle, vlan);
6729     if (!out_bundle->bond) {
6730         port = ofbundle_get_a_port(out_bundle);
6731     } else {
6732         port = bond_choose_output_slave(out_bundle->bond, &ctx->flow,
6733                                         vid, &ctx->tags);
6734         if (!port) {
6735             /* No slaves enabled, so drop packet. */
6736             return;
6737         }
6738     }
6739
6740     old_tci = ctx->flow.vlan_tci;
6741     tci = htons(vid);
6742     if (tci || out_bundle->use_priority_tags) {
6743         tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
6744         if (tci) {
6745             tci |= htons(VLAN_CFI);
6746         }
6747     }
6748     ctx->flow.vlan_tci = tci;
6749
6750     compose_output_action(ctx, port->up.ofp_port);
6751     ctx->flow.vlan_tci = old_tci;
6752 }
6753
6754 static int
6755 mirror_mask_ffs(mirror_mask_t mask)
6756 {
6757     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
6758     return ffs(mask);
6759 }
6760
6761 static bool
6762 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
6763 {
6764     return (bundle->vlan_mode != PORT_VLAN_ACCESS
6765             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
6766 }
6767
6768 static bool
6769 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
6770 {
6771     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
6772 }
6773
6774 /* Returns an arbitrary interface within 'bundle'. */
6775 static struct ofport_dpif *
6776 ofbundle_get_a_port(const struct ofbundle *bundle)
6777 {
6778     return CONTAINER_OF(list_front(&bundle->ports),
6779                         struct ofport_dpif, bundle_node);
6780 }
6781
6782 static bool
6783 vlan_is_mirrored(const struct ofmirror *m, int vlan)
6784 {
6785     return !m->vlans || bitmap_is_set(m->vlans, vlan);
6786 }
6787
6788 static void
6789 add_mirror_actions(struct action_xlate_ctx *ctx, const struct flow *orig_flow)
6790 {
6791     struct ofproto_dpif *ofproto = ctx->ofproto;
6792     mirror_mask_t mirrors;
6793     struct ofbundle *in_bundle;
6794     uint16_t vlan;
6795     uint16_t vid;
6796     const struct nlattr *a;
6797     size_t left;
6798
6799     in_bundle = lookup_input_bundle(ctx->ofproto, orig_flow->in_port,
6800                                     ctx->packet != NULL, NULL);
6801     if (!in_bundle) {
6802         return;
6803     }
6804     mirrors = in_bundle->src_mirrors;
6805
6806     /* Drop frames on bundles reserved for mirroring. */
6807     if (in_bundle->mirror_out) {
6808         if (ctx->packet != NULL) {
6809             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6810             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
6811                          "%s, which is reserved exclusively for mirroring",
6812                          ctx->ofproto->up.name, in_bundle->name);
6813         }
6814         return;
6815     }
6816
6817     /* Check VLAN. */
6818     vid = vlan_tci_to_vid(orig_flow->vlan_tci);
6819     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
6820         return;
6821     }
6822     vlan = input_vid_to_vlan(in_bundle, vid);
6823
6824     /* Look at the output ports to check for destination selections. */
6825
6826     NL_ATTR_FOR_EACH (a, left, ctx->odp_actions->data,
6827                       ctx->odp_actions->size) {
6828         enum ovs_action_attr type = nl_attr_type(a);
6829         struct ofport_dpif *ofport;
6830
6831         if (type != OVS_ACTION_ATTR_OUTPUT) {
6832             continue;
6833         }
6834
6835         ofport = get_odp_port(ofproto, nl_attr_get_u32(a));
6836         if (ofport && ofport->bundle) {
6837             mirrors |= ofport->bundle->dst_mirrors;
6838         }
6839     }
6840
6841     if (!mirrors) {
6842         return;
6843     }
6844
6845     /* Restore the original packet before adding the mirror actions. */
6846     ctx->flow = *orig_flow;
6847
6848     while (mirrors) {
6849         struct ofmirror *m;
6850
6851         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
6852
6853         if (!vlan_is_mirrored(m, vlan)) {
6854             mirrors = zero_rightmost_1bit(mirrors);
6855             continue;
6856         }
6857
6858         mirrors &= ~m->dup_mirrors;
6859         ctx->mirrors |= m->dup_mirrors;
6860         if (m->out) {
6861             output_normal(ctx, m->out, vlan);
6862         } else if (vlan != m->out_vlan
6863                    && !eth_addr_is_reserved(orig_flow->dl_dst)) {
6864             struct ofbundle *bundle;
6865
6866             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
6867                 if (ofbundle_includes_vlan(bundle, m->out_vlan)
6868                     && !bundle->mirror_out) {
6869                     output_normal(ctx, bundle, m->out_vlan);
6870                 }
6871             }
6872         }
6873     }
6874 }
6875
6876 static void
6877 update_mirror_stats(struct ofproto_dpif *ofproto, mirror_mask_t mirrors,
6878                     uint64_t packets, uint64_t bytes)
6879 {
6880     if (!mirrors) {
6881         return;
6882     }
6883
6884     for (; mirrors; mirrors = zero_rightmost_1bit(mirrors)) {
6885         struct ofmirror *m;
6886
6887         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
6888
6889         if (!m) {
6890             /* In normal circumstances 'm' will not be NULL.  However,
6891              * if mirrors are reconfigured, we can temporarily get out
6892              * of sync in facet_revalidate().  We could "correct" the
6893              * mirror list before reaching here, but doing that would
6894              * not properly account the traffic stats we've currently
6895              * accumulated for previous mirror configuration. */
6896             continue;
6897         }
6898
6899         m->packet_count += packets;
6900         m->byte_count += bytes;
6901     }
6902 }
6903
6904 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
6905  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
6906  * indicate this; newer upstream kernels use gratuitous ARP requests. */
6907 static bool
6908 is_gratuitous_arp(const struct flow *flow)
6909 {
6910     return (flow->dl_type == htons(ETH_TYPE_ARP)
6911             && eth_addr_is_broadcast(flow->dl_dst)
6912             && (flow->nw_proto == ARP_OP_REPLY
6913                 || (flow->nw_proto == ARP_OP_REQUEST
6914                     && flow->nw_src == flow->nw_dst)));
6915 }
6916
6917 static void
6918 update_learning_table(struct ofproto_dpif *ofproto,
6919                       const struct flow *flow, int vlan,
6920                       struct ofbundle *in_bundle)
6921 {
6922     struct mac_entry *mac;
6923
6924     /* Don't learn the OFPP_NONE port. */
6925     if (in_bundle == &ofpp_none_bundle) {
6926         return;
6927     }
6928
6929     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
6930         return;
6931     }
6932
6933     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
6934     if (is_gratuitous_arp(flow)) {
6935         /* We don't want to learn from gratuitous ARP packets that are
6936          * reflected back over bond slaves so we lock the learning table. */
6937         if (!in_bundle->bond) {
6938             mac_entry_set_grat_arp_lock(mac);
6939         } else if (mac_entry_is_grat_arp_locked(mac)) {
6940             return;
6941         }
6942     }
6943
6944     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
6945         /* The log messages here could actually be useful in debugging,
6946          * so keep the rate limit relatively high. */
6947         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
6948         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
6949                     "on port %s in VLAN %d",
6950                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
6951                     in_bundle->name, vlan);
6952
6953         mac->port.p = in_bundle;
6954         tag_set_add(&ofproto->backer->revalidate_set,
6955                     mac_learning_changed(ofproto->ml, mac));
6956     }
6957 }
6958
6959 static struct ofbundle *
6960 lookup_input_bundle(const struct ofproto_dpif *ofproto, uint16_t in_port,
6961                     bool warn, struct ofport_dpif **in_ofportp)
6962 {
6963     struct ofport_dpif *ofport;
6964
6965     /* Find the port and bundle for the received packet. */
6966     ofport = get_ofp_port(ofproto, in_port);
6967     if (in_ofportp) {
6968         *in_ofportp = ofport;
6969     }
6970     if (ofport && ofport->bundle) {
6971         return ofport->bundle;
6972     }
6973
6974     /* Special-case OFPP_NONE, which a controller may use as the ingress
6975      * port for traffic that it is sourcing. */
6976     if (in_port == OFPP_NONE) {
6977         return &ofpp_none_bundle;
6978     }
6979
6980     /* Odd.  A few possible reasons here:
6981      *
6982      * - We deleted a port but there are still a few packets queued up
6983      *   from it.
6984      *
6985      * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
6986      *   we don't know about.
6987      *
6988      * - The ofproto client didn't configure the port as part of a bundle.
6989      *   This is particularly likely to happen if a packet was received on the
6990      *   port after it was created, but before the client had a chance to
6991      *   configure its bundle.
6992      */
6993     if (warn) {
6994         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6995
6996         VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
6997                      "port %"PRIu16, ofproto->up.name, in_port);
6998     }
6999     return NULL;
7000 }
7001
7002 /* Determines whether packets in 'flow' within 'ofproto' should be forwarded or
7003  * dropped.  Returns true if they may be forwarded, false if they should be
7004  * dropped.
7005  *
7006  * 'in_port' must be the ofport_dpif that corresponds to flow->in_port.
7007  * 'in_port' must be part of a bundle (e.g. in_port->bundle must be nonnull).
7008  *
7009  * 'vlan' must be the VLAN that corresponds to flow->vlan_tci on 'in_port', as
7010  * returned by input_vid_to_vlan().  It must be a valid VLAN for 'in_port', as
7011  * checked by input_vid_is_valid().
7012  *
7013  * May also add tags to '*tags', although the current implementation only does
7014  * so in one special case.
7015  */
7016 static bool
7017 is_admissible(struct action_xlate_ctx *ctx, struct ofport_dpif *in_port,
7018               uint16_t vlan)
7019 {
7020     struct ofproto_dpif *ofproto = ctx->ofproto;
7021     struct flow *flow = &ctx->flow;
7022     struct ofbundle *in_bundle = in_port->bundle;
7023
7024     /* Drop frames for reserved multicast addresses
7025      * only if forward_bpdu option is absent. */
7026     if (!ofproto->up.forward_bpdu && eth_addr_is_reserved(flow->dl_dst)) {
7027         xlate_report(ctx, "packet has reserved destination MAC, dropping");
7028         return false;
7029     }
7030
7031     if (in_bundle->bond) {
7032         struct mac_entry *mac;
7033
7034         switch (bond_check_admissibility(in_bundle->bond, in_port,
7035                                          flow->dl_dst, &ctx->tags)) {
7036         case BV_ACCEPT:
7037             break;
7038
7039         case BV_DROP:
7040             xlate_report(ctx, "bonding refused admissibility, dropping");
7041             return false;
7042
7043         case BV_DROP_IF_MOVED:
7044             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
7045             if (mac && mac->port.p != in_bundle &&
7046                 (!is_gratuitous_arp(flow)
7047                  || mac_entry_is_grat_arp_locked(mac))) {
7048                 xlate_report(ctx, "SLB bond thinks this packet looped back, "
7049                             "dropping");
7050                 return false;
7051             }
7052             break;
7053         }
7054     }
7055
7056     return true;
7057 }
7058
7059 static void
7060 xlate_normal(struct action_xlate_ctx *ctx)
7061 {
7062     struct ofport_dpif *in_port;
7063     struct ofbundle *in_bundle;
7064     struct mac_entry *mac;
7065     uint16_t vlan;
7066     uint16_t vid;
7067
7068     ctx->has_normal = true;
7069
7070     in_bundle = lookup_input_bundle(ctx->ofproto, ctx->flow.in_port,
7071                                     ctx->packet != NULL, &in_port);
7072     if (!in_bundle) {
7073         xlate_report(ctx, "no input bundle, dropping");
7074         return;
7075     }
7076
7077     /* Drop malformed frames. */
7078     if (ctx->flow.dl_type == htons(ETH_TYPE_VLAN) &&
7079         !(ctx->flow.vlan_tci & htons(VLAN_CFI))) {
7080         if (ctx->packet != NULL) {
7081             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
7082             VLOG_WARN_RL(&rl, "bridge %s: dropping packet with partial "
7083                          "VLAN tag received on port %s",
7084                          ctx->ofproto->up.name, in_bundle->name);
7085         }
7086         xlate_report(ctx, "partial VLAN tag, dropping");
7087         return;
7088     }
7089
7090     /* Drop frames on bundles reserved for mirroring. */
7091     if (in_bundle->mirror_out) {
7092         if (ctx->packet != NULL) {
7093             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
7094             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
7095                          "%s, which is reserved exclusively for mirroring",
7096                          ctx->ofproto->up.name, in_bundle->name);
7097         }
7098         xlate_report(ctx, "input port is mirror output port, dropping");
7099         return;
7100     }
7101
7102     /* Check VLAN. */
7103     vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
7104     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
7105         xlate_report(ctx, "disallowed VLAN VID for this input port, dropping");
7106         return;
7107     }
7108     vlan = input_vid_to_vlan(in_bundle, vid);
7109
7110     /* Check other admissibility requirements. */
7111     if (in_port && !is_admissible(ctx, in_port, vlan)) {
7112         return;
7113     }
7114
7115     /* Learn source MAC. */
7116     if (ctx->may_learn) {
7117         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
7118     }
7119
7120     /* Determine output bundle. */
7121     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
7122                               &ctx->tags);
7123     if (mac) {
7124         if (mac->port.p != in_bundle) {
7125             xlate_report(ctx, "forwarding to learned port");
7126             output_normal(ctx, mac->port.p, vlan);
7127         } else {
7128             xlate_report(ctx, "learned port is input port, dropping");
7129         }
7130     } else {
7131         struct ofbundle *bundle;
7132
7133         xlate_report(ctx, "no learned MAC for destination, flooding");
7134         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
7135             if (bundle != in_bundle
7136                 && ofbundle_includes_vlan(bundle, vlan)
7137                 && bundle->floodable
7138                 && !bundle->mirror_out) {
7139                 output_normal(ctx, bundle, vlan);
7140             }
7141         }
7142         ctx->nf_output_iface = NF_OUT_FLOOD;
7143     }
7144 }
7145 \f
7146 /* Optimized flow revalidation.
7147  *
7148  * It's a difficult problem, in general, to tell which facets need to have
7149  * their actions recalculated whenever the OpenFlow flow table changes.  We
7150  * don't try to solve that general problem: for most kinds of OpenFlow flow
7151  * table changes, we recalculate the actions for every facet.  This is
7152  * relatively expensive, but it's good enough if the OpenFlow flow table
7153  * doesn't change very often.
7154  *
7155  * However, we can expect one particular kind of OpenFlow flow table change to
7156  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
7157  * of CPU on revalidating every facet whenever MAC learning modifies the flow
7158  * table, we add a special case that applies to flow tables in which every rule
7159  * has the same form (that is, the same wildcards), except that the table is
7160  * also allowed to have a single "catch-all" flow that matches all packets.  We
7161  * optimize this case by tagging all of the facets that resubmit into the table
7162  * and invalidating the same tag whenever a flow changes in that table.  The
7163  * end result is that we revalidate just the facets that need it (and sometimes
7164  * a few more, but not all of the facets or even all of the facets that
7165  * resubmit to the table modified by MAC learning). */
7166
7167 /* Calculates the tag to use for 'flow' and mask 'mask' when it is inserted
7168  * into an OpenFlow table with the given 'basis'. */
7169 static tag_type
7170 rule_calculate_tag(const struct flow *flow, const struct minimask *mask,
7171                    uint32_t secret)
7172 {
7173     if (minimask_is_catchall(mask)) {
7174         return 0;
7175     } else {
7176         uint32_t hash = flow_hash_in_minimask(flow, mask, secret);
7177         return tag_create_deterministic(hash);
7178     }
7179 }
7180
7181 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
7182  * taggability of that table.
7183  *
7184  * This function must be called after *each* change to a flow table.  If you
7185  * skip calling it on some changes then the pointer comparisons at the end can
7186  * be invalid if you get unlucky.  For example, if a flow removal causes a
7187  * cls_table to be destroyed and then a flow insertion causes a cls_table with
7188  * different wildcards to be created with the same address, then this function
7189  * will incorrectly skip revalidation. */
7190 static void
7191 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
7192 {
7193     struct table_dpif *table = &ofproto->tables[table_id];
7194     const struct oftable *oftable = &ofproto->up.tables[table_id];
7195     struct cls_table *catchall, *other;
7196     struct cls_table *t;
7197
7198     catchall = other = NULL;
7199
7200     switch (hmap_count(&oftable->cls.tables)) {
7201     case 0:
7202         /* We could tag this OpenFlow table but it would make the logic a
7203          * little harder and it's a corner case that doesn't seem worth it
7204          * yet. */
7205         break;
7206
7207     case 1:
7208     case 2:
7209         HMAP_FOR_EACH (t, hmap_node, &oftable->cls.tables) {
7210             if (cls_table_is_catchall(t)) {
7211                 catchall = t;
7212             } else if (!other) {
7213                 other = t;
7214             } else {
7215                 /* Indicate that we can't tag this by setting both tables to
7216                  * NULL.  (We know that 'catchall' is already NULL.) */
7217                 other = NULL;
7218             }
7219         }
7220         break;
7221
7222     default:
7223         /* Can't tag this table. */
7224         break;
7225     }
7226
7227     if (table->catchall_table != catchall || table->other_table != other) {
7228         table->catchall_table = catchall;
7229         table->other_table = other;
7230         ofproto->backer->need_revalidate = REV_FLOW_TABLE;
7231     }
7232 }
7233
7234 /* Given 'rule' that has changed in some way (either it is a rule being
7235  * inserted, a rule being deleted, or a rule whose actions are being
7236  * modified), marks facets for revalidation to ensure that packets will be
7237  * forwarded correctly according to the new state of the flow table.
7238  *
7239  * This function must be called after *each* change to a flow table.  See
7240  * the comment on table_update_taggable() for more information. */
7241 static void
7242 rule_invalidate(const struct rule_dpif *rule)
7243 {
7244     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
7245
7246     table_update_taggable(ofproto, rule->up.table_id);
7247
7248     if (!ofproto->backer->need_revalidate) {
7249         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
7250
7251         if (table->other_table && rule->tag) {
7252             tag_set_add(&ofproto->backer->revalidate_set, rule->tag);
7253         } else {
7254             ofproto->backer->need_revalidate = REV_FLOW_TABLE;
7255         }
7256     }
7257 }
7258 \f
7259 static bool
7260 set_frag_handling(struct ofproto *ofproto_,
7261                   enum ofp_config_flags frag_handling)
7262 {
7263     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7264     if (frag_handling != OFPC_FRAG_REASM) {
7265         ofproto->backer->need_revalidate = REV_RECONFIGURE;
7266         return true;
7267     } else {
7268         return false;
7269     }
7270 }
7271
7272 static enum ofperr
7273 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
7274            const struct flow *flow,
7275            const struct ofpact *ofpacts, size_t ofpacts_len)
7276 {
7277     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7278     struct odputil_keybuf keybuf;
7279     struct dpif_flow_stats stats;
7280
7281     struct ofpbuf key;
7282
7283     struct action_xlate_ctx ctx;
7284     uint64_t odp_actions_stub[1024 / 8];
7285     struct ofpbuf odp_actions;
7286
7287     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
7288     odp_flow_key_from_flow(&key, flow,
7289                            ofp_port_to_odp_port(ofproto, flow->in_port));
7290
7291     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
7292
7293     action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci, NULL,
7294                           packet_get_tcp_flags(packet, flow), packet);
7295     ctx.resubmit_stats = &stats;
7296
7297     ofpbuf_use_stub(&odp_actions,
7298                     odp_actions_stub, sizeof odp_actions_stub);
7299     xlate_actions(&ctx, ofpacts, ofpacts_len, &odp_actions);
7300     dpif_execute(ofproto->backer->dpif, key.data, key.size,
7301                  odp_actions.data, odp_actions.size, packet);
7302     ofpbuf_uninit(&odp_actions);
7303
7304     return 0;
7305 }
7306 \f
7307 /* NetFlow. */
7308
7309 static int
7310 set_netflow(struct ofproto *ofproto_,
7311             const struct netflow_options *netflow_options)
7312 {
7313     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7314
7315     if (netflow_options) {
7316         if (!ofproto->netflow) {
7317             ofproto->netflow = netflow_create();
7318         }
7319         return netflow_set_options(ofproto->netflow, netflow_options);
7320     } else {
7321         netflow_destroy(ofproto->netflow);
7322         ofproto->netflow = NULL;
7323         return 0;
7324     }
7325 }
7326
7327 static void
7328 get_netflow_ids(const struct ofproto *ofproto_,
7329                 uint8_t *engine_type, uint8_t *engine_id)
7330 {
7331     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7332
7333     dpif_get_netflow_ids(ofproto->backer->dpif, engine_type, engine_id);
7334 }
7335
7336 static void
7337 send_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
7338 {
7339     if (!facet_is_controller_flow(facet) &&
7340         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
7341         struct subfacet *subfacet;
7342         struct ofexpired expired;
7343
7344         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
7345             if (subfacet->path == SF_FAST_PATH) {
7346                 struct dpif_flow_stats stats;
7347
7348                 subfacet_reinstall(subfacet, &stats);
7349                 subfacet_update_stats(subfacet, &stats);
7350             }
7351         }
7352
7353         expired.flow = facet->flow;
7354         expired.packet_count = facet->packet_count;
7355         expired.byte_count = facet->byte_count;
7356         expired.used = facet->used;
7357         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
7358     }
7359 }
7360
7361 static void
7362 send_netflow_active_timeouts(struct ofproto_dpif *ofproto)
7363 {
7364     struct facet *facet;
7365
7366     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
7367         send_active_timeout(ofproto, facet);
7368     }
7369 }
7370 \f
7371 static struct ofproto_dpif *
7372 ofproto_dpif_lookup(const char *name)
7373 {
7374     struct ofproto_dpif *ofproto;
7375
7376     HMAP_FOR_EACH_WITH_HASH (ofproto, all_ofproto_dpifs_node,
7377                              hash_string(name, 0), &all_ofproto_dpifs) {
7378         if (!strcmp(ofproto->up.name, name)) {
7379             return ofproto;
7380         }
7381     }
7382     return NULL;
7383 }
7384
7385 static void
7386 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn, int argc,
7387                           const char *argv[], void *aux OVS_UNUSED)
7388 {
7389     struct ofproto_dpif *ofproto;
7390
7391     if (argc > 1) {
7392         ofproto = ofproto_dpif_lookup(argv[1]);
7393         if (!ofproto) {
7394             unixctl_command_reply_error(conn, "no such bridge");
7395             return;
7396         }
7397         mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
7398     } else {
7399         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
7400             mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
7401         }
7402     }
7403
7404     unixctl_command_reply(conn, "table successfully flushed");
7405 }
7406
7407 static void
7408 ofproto_unixctl_fdb_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
7409                          const char *argv[], void *aux OVS_UNUSED)
7410 {
7411     struct ds ds = DS_EMPTY_INITIALIZER;
7412     const struct ofproto_dpif *ofproto;
7413     const struct mac_entry *e;
7414
7415     ofproto = ofproto_dpif_lookup(argv[1]);
7416     if (!ofproto) {
7417         unixctl_command_reply_error(conn, "no such bridge");
7418         return;
7419     }
7420
7421     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
7422     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
7423         struct ofbundle *bundle = e->port.p;
7424         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
7425                       ofbundle_get_a_port(bundle)->odp_port,
7426                       e->vlan, ETH_ADDR_ARGS(e->mac),
7427                       mac_entry_age(ofproto->ml, e));
7428     }
7429     unixctl_command_reply(conn, ds_cstr(&ds));
7430     ds_destroy(&ds);
7431 }
7432
7433 struct trace_ctx {
7434     struct action_xlate_ctx ctx;
7435     struct flow flow;
7436     struct ds *result;
7437 };
7438
7439 static void
7440 trace_format_rule(struct ds *result, uint8_t table_id, int level,
7441                   const struct rule_dpif *rule)
7442 {
7443     ds_put_char_multiple(result, '\t', level);
7444     if (!rule) {
7445         ds_put_cstr(result, "No match\n");
7446         return;
7447     }
7448
7449     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
7450                   table_id, ntohll(rule->up.flow_cookie));
7451     cls_rule_format(&rule->up.cr, result);
7452     ds_put_char(result, '\n');
7453
7454     ds_put_char_multiple(result, '\t', level);
7455     ds_put_cstr(result, "OpenFlow ");
7456     ofpacts_format(rule->up.ofpacts, rule->up.ofpacts_len, result);
7457     ds_put_char(result, '\n');
7458 }
7459
7460 static void
7461 trace_format_flow(struct ds *result, int level, const char *title,
7462                  struct trace_ctx *trace)
7463 {
7464     ds_put_char_multiple(result, '\t', level);
7465     ds_put_format(result, "%s: ", title);
7466     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
7467         ds_put_cstr(result, "unchanged");
7468     } else {
7469         flow_format(result, &trace->ctx.flow);
7470         trace->flow = trace->ctx.flow;
7471     }
7472     ds_put_char(result, '\n');
7473 }
7474
7475 static void
7476 trace_format_regs(struct ds *result, int level, const char *title,
7477                   struct trace_ctx *trace)
7478 {
7479     size_t i;
7480
7481     ds_put_char_multiple(result, '\t', level);
7482     ds_put_format(result, "%s:", title);
7483     for (i = 0; i < FLOW_N_REGS; i++) {
7484         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
7485     }
7486     ds_put_char(result, '\n');
7487 }
7488
7489 static void
7490 trace_format_odp(struct ds *result, int level, const char *title,
7491                  struct trace_ctx *trace)
7492 {
7493     struct ofpbuf *odp_actions = trace->ctx.odp_actions;
7494
7495     ds_put_char_multiple(result, '\t', level);
7496     ds_put_format(result, "%s: ", title);
7497     format_odp_actions(result, odp_actions->data, odp_actions->size);
7498     ds_put_char(result, '\n');
7499 }
7500
7501 static void
7502 trace_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
7503 {
7504     struct trace_ctx *trace = CONTAINER_OF(ctx, struct trace_ctx, ctx);
7505     struct ds *result = trace->result;
7506
7507     ds_put_char(result, '\n');
7508     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
7509     trace_format_regs(result, ctx->recurse + 1, "Resubmitted regs", trace);
7510     trace_format_odp(result,  ctx->recurse + 1, "Resubmitted  odp", trace);
7511     trace_format_rule(result, ctx->table_id, ctx->recurse + 1, rule);
7512 }
7513
7514 static void
7515 trace_report(struct action_xlate_ctx *ctx, const char *s)
7516 {
7517     struct trace_ctx *trace = CONTAINER_OF(ctx, struct trace_ctx, ctx);
7518     struct ds *result = trace->result;
7519
7520     ds_put_char_multiple(result, '\t', ctx->recurse);
7521     ds_put_cstr(result, s);
7522     ds_put_char(result, '\n');
7523 }
7524
7525 static void
7526 ofproto_unixctl_trace(struct unixctl_conn *conn, int argc, const char *argv[],
7527                       void *aux OVS_UNUSED)
7528 {
7529     const char *dpname = argv[1];
7530     struct ofproto_dpif *ofproto;
7531     struct ofpbuf odp_key;
7532     struct ofpbuf *packet;
7533     ovs_be16 initial_tci;
7534     struct ds result;
7535     struct flow flow;
7536     char *s;
7537
7538     packet = NULL;
7539     ofpbuf_init(&odp_key, 0);
7540     ds_init(&result);
7541
7542     ofproto = ofproto_dpif_lookup(dpname);
7543     if (!ofproto) {
7544         unixctl_command_reply_error(conn, "Unknown ofproto (use ofproto/list "
7545                                     "for help)");
7546         goto exit;
7547     }
7548     if (argc == 3 || (argc == 4 && !strcmp(argv[3], "-generate"))) {
7549         /* ofproto/trace dpname flow [-generate] */
7550         const char *flow_s = argv[2];
7551         const char *generate_s = argv[3];
7552
7553         /* Allow 'flow_s' to be either a datapath flow or an OpenFlow-like
7554          * flow.  We guess which type it is based on whether 'flow_s' contains
7555          * an '(', since a datapath flow always contains '(') but an
7556          * OpenFlow-like flow should not (in fact it's allowed but I believe
7557          * that's not documented anywhere).
7558          *
7559          * An alternative would be to try to parse 'flow_s' both ways, but then
7560          * it would be tricky giving a sensible error message.  After all, do
7561          * you just say "syntax error" or do you present both error messages?
7562          * Both choices seem lousy. */
7563         if (strchr(flow_s, '(')) {
7564             int error;
7565
7566             /* Convert string to datapath key. */
7567             ofpbuf_init(&odp_key, 0);
7568             error = odp_flow_key_from_string(flow_s, NULL, &odp_key);
7569             if (error) {
7570                 unixctl_command_reply_error(conn, "Bad flow syntax");
7571                 goto exit;
7572             }
7573
7574             /* XXX: Since we allow the user to specify an ofproto, it's
7575              * possible they will specify a different ofproto than the one the
7576              * port actually belongs too.  Ideally we should simply remove the
7577              * ability to specify the ofproto. */
7578             if (ofproto_receive(ofproto->backer, NULL, odp_key.data,
7579                                 odp_key.size, &flow, NULL, NULL, NULL,
7580                                 &initial_tci)) {
7581                 unixctl_command_reply_error(conn, "Invalid flow");
7582                 goto exit;
7583             }
7584         } else {
7585             char *error_s;
7586
7587             error_s = parse_ofp_exact_flow(&flow, argv[2]);
7588             if (error_s) {
7589                 unixctl_command_reply_error(conn, error_s);
7590                 free(error_s);
7591                 goto exit;
7592             }
7593
7594             initial_tci = flow.vlan_tci;
7595         }
7596
7597         /* Generate a packet, if requested. */
7598         if (generate_s) {
7599             packet = ofpbuf_new(0);
7600             flow_compose(packet, &flow);
7601         }
7602     } else if (argc == 7) {
7603         /* ofproto/trace dpname priority tun_id in_port mark packet */
7604         const char *priority_s = argv[2];
7605         const char *tun_id_s = argv[3];
7606         const char *in_port_s = argv[4];
7607         const char *mark_s = argv[5];
7608         const char *packet_s = argv[6];
7609         uint32_t in_port = atoi(in_port_s);
7610         ovs_be64 tun_id = htonll(strtoull(tun_id_s, NULL, 0));
7611         uint32_t priority = atoi(priority_s);
7612         uint32_t mark = atoi(mark_s);
7613         const char *msg;
7614
7615         msg = eth_from_hex(packet_s, &packet);
7616         if (msg) {
7617             unixctl_command_reply_error(conn, msg);
7618             goto exit;
7619         }
7620
7621         ds_put_cstr(&result, "Packet: ");
7622         s = ofp_packet_to_string(packet->data, packet->size);
7623         ds_put_cstr(&result, s);
7624         free(s);
7625
7626         flow_extract(packet, priority, mark, NULL, in_port, &flow);
7627         flow.tunnel.tun_id = tun_id;
7628         initial_tci = flow.vlan_tci;
7629     } else {
7630         unixctl_command_reply_error(conn, "Bad command syntax");
7631         goto exit;
7632     }
7633
7634     ofproto_trace(ofproto, &flow, packet, initial_tci, &result);
7635     unixctl_command_reply(conn, ds_cstr(&result));
7636
7637 exit:
7638     ds_destroy(&result);
7639     ofpbuf_delete(packet);
7640     ofpbuf_uninit(&odp_key);
7641 }
7642
7643 static void
7644 ofproto_trace(struct ofproto_dpif *ofproto, const struct flow *flow,
7645               const struct ofpbuf *packet, ovs_be16 initial_tci,
7646               struct ds *ds)
7647 {
7648     struct rule_dpif *rule;
7649
7650     ds_put_cstr(ds, "Flow: ");
7651     flow_format(ds, flow);
7652     ds_put_char(ds, '\n');
7653
7654     rule = rule_dpif_lookup(ofproto, flow);
7655
7656     trace_format_rule(ds, 0, 0, rule);
7657     if (rule == ofproto->miss_rule) {
7658         ds_put_cstr(ds, "\nNo match, flow generates \"packet in\"s.\n");
7659     } else if (rule == ofproto->no_packet_in_rule) {
7660         ds_put_cstr(ds, "\nNo match, packets dropped because "
7661                     "OFPPC_NO_PACKET_IN is set on in_port.\n");
7662     }
7663
7664     if (rule) {
7665         uint64_t odp_actions_stub[1024 / 8];
7666         struct ofpbuf odp_actions;
7667
7668         struct trace_ctx trace;
7669         uint8_t tcp_flags;
7670
7671         tcp_flags = packet ? packet_get_tcp_flags(packet, flow) : 0;
7672         trace.result = ds;
7673         trace.flow = *flow;
7674         ofpbuf_use_stub(&odp_actions,
7675                         odp_actions_stub, sizeof odp_actions_stub);
7676         action_xlate_ctx_init(&trace.ctx, ofproto, flow, initial_tci,
7677                               rule, tcp_flags, packet);
7678         trace.ctx.resubmit_hook = trace_resubmit;
7679         trace.ctx.report_hook = trace_report;
7680         xlate_actions(&trace.ctx, rule->up.ofpacts, rule->up.ofpacts_len,
7681                       &odp_actions);
7682
7683         ds_put_char(ds, '\n');
7684         trace_format_flow(ds, 0, "Final flow", &trace);
7685         ds_put_cstr(ds, "Datapath actions: ");
7686         format_odp_actions(ds, odp_actions.data, odp_actions.size);
7687         ofpbuf_uninit(&odp_actions);
7688
7689         if (trace.ctx.slow) {
7690             enum slow_path_reason slow;
7691
7692             ds_put_cstr(ds, "\nThis flow is handled by the userspace "
7693                         "slow path because it:");
7694             for (slow = trace.ctx.slow; slow; ) {
7695                 enum slow_path_reason bit = rightmost_1bit(slow);
7696
7697                 switch (bit) {
7698                 case SLOW_CFM:
7699                     ds_put_cstr(ds, "\n\t- Consists of CFM packets.");
7700                     break;
7701                 case SLOW_LACP:
7702                     ds_put_cstr(ds, "\n\t- Consists of LACP packets.");
7703                     break;
7704                 case SLOW_STP:
7705                     ds_put_cstr(ds, "\n\t- Consists of STP packets.");
7706                     break;
7707                 case SLOW_IN_BAND:
7708                     ds_put_cstr(ds, "\n\t- Needs in-band special case "
7709                                 "processing.");
7710                     if (!packet) {
7711                         ds_put_cstr(ds, "\n\t  (The datapath actions are "
7712                                     "incomplete--for complete actions, "
7713                                     "please supply a packet.)");
7714                     }
7715                     break;
7716                 case SLOW_CONTROLLER:
7717                     ds_put_cstr(ds, "\n\t- Sends \"packet-in\" messages "
7718                                 "to the OpenFlow controller.");
7719                     break;
7720                 case SLOW_MATCH:
7721                     ds_put_cstr(ds, "\n\t- Needs more specific matching "
7722                                 "than the datapath supports.");
7723                     break;
7724                 }
7725
7726                 slow &= ~bit;
7727             }
7728
7729             if (slow & ~SLOW_MATCH) {
7730                 ds_put_cstr(ds, "\nThe datapath actions above do not reflect "
7731                             "the special slow-path processing.");
7732             }
7733         }
7734     }
7735 }
7736
7737 static void
7738 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
7739                   const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
7740 {
7741     clogged = true;
7742     unixctl_command_reply(conn, NULL);
7743 }
7744
7745 static void
7746 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
7747                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
7748 {
7749     clogged = false;
7750     unixctl_command_reply(conn, NULL);
7751 }
7752
7753 /* Runs a self-check of flow translations in 'ofproto'.  Appends a message to
7754  * 'reply' describing the results. */
7755 static void
7756 ofproto_dpif_self_check__(struct ofproto_dpif *ofproto, struct ds *reply)
7757 {
7758     struct facet *facet;
7759     int errors;
7760
7761     errors = 0;
7762     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
7763         if (!facet_check_consistency(facet)) {
7764             errors++;
7765         }
7766     }
7767     if (errors) {
7768         ofproto->backer->need_revalidate = REV_INCONSISTENCY;
7769     }
7770
7771     if (errors) {
7772         ds_put_format(reply, "%s: self-check failed (%d errors)\n",
7773                       ofproto->up.name, errors);
7774     } else {
7775         ds_put_format(reply, "%s: self-check passed\n", ofproto->up.name);
7776     }
7777 }
7778
7779 static void
7780 ofproto_dpif_self_check(struct unixctl_conn *conn,
7781                         int argc, const char *argv[], void *aux OVS_UNUSED)
7782 {
7783     struct ds reply = DS_EMPTY_INITIALIZER;
7784     struct ofproto_dpif *ofproto;
7785
7786     if (argc > 1) {
7787         ofproto = ofproto_dpif_lookup(argv[1]);
7788         if (!ofproto) {
7789             unixctl_command_reply_error(conn, "Unknown ofproto (use "
7790                                         "ofproto/list for help)");
7791             return;
7792         }
7793         ofproto_dpif_self_check__(ofproto, &reply);
7794     } else {
7795         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
7796             ofproto_dpif_self_check__(ofproto, &reply);
7797         }
7798     }
7799
7800     unixctl_command_reply(conn, ds_cstr(&reply));
7801     ds_destroy(&reply);
7802 }
7803
7804 /* Store the current ofprotos in 'ofproto_shash'.  Returns a sorted list
7805  * of the 'ofproto_shash' nodes.  It is the responsibility of the caller
7806  * to destroy 'ofproto_shash' and free the returned value. */
7807 static const struct shash_node **
7808 get_ofprotos(struct shash *ofproto_shash)
7809 {
7810     const struct ofproto_dpif *ofproto;
7811
7812     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
7813         char *name = xasprintf("%s@%s", ofproto->up.type, ofproto->up.name);
7814         shash_add_nocopy(ofproto_shash, name, ofproto);
7815     }
7816
7817     return shash_sort(ofproto_shash);
7818 }
7819
7820 static void
7821 ofproto_unixctl_dpif_dump_dps(struct unixctl_conn *conn, int argc OVS_UNUSED,
7822                               const char *argv[] OVS_UNUSED,
7823                               void *aux OVS_UNUSED)
7824 {
7825     struct ds ds = DS_EMPTY_INITIALIZER;
7826     struct shash ofproto_shash;
7827     const struct shash_node **sorted_ofprotos;
7828     int i;
7829
7830     shash_init(&ofproto_shash);
7831     sorted_ofprotos = get_ofprotos(&ofproto_shash);
7832     for (i = 0; i < shash_count(&ofproto_shash); i++) {
7833         const struct shash_node *node = sorted_ofprotos[i];
7834         ds_put_format(&ds, "%s\n", node->name);
7835     }
7836
7837     shash_destroy(&ofproto_shash);
7838     free(sorted_ofprotos);
7839
7840     unixctl_command_reply(conn, ds_cstr(&ds));
7841     ds_destroy(&ds);
7842 }
7843
7844 static void
7845 show_dp_format(const struct ofproto_dpif *ofproto, struct ds *ds)
7846 {
7847     struct dpif_dp_stats s;
7848     const struct shash_node **ports;
7849     int i;
7850
7851     dpif_get_dp_stats(ofproto->backer->dpif, &s);
7852
7853     ds_put_format(ds, "%s (%s):\n", ofproto->up.name,
7854                   dpif_name(ofproto->backer->dpif));
7855     /* xxx It would be better to show bridge-specific stats instead
7856      * xxx of dp ones. */
7857     ds_put_format(ds,
7858                   "\tlookups: hit:%"PRIu64" missed:%"PRIu64" lost:%"PRIu64"\n",
7859                   s.n_hit, s.n_missed, s.n_lost);
7860     ds_put_format(ds, "\tflows: %zu\n",
7861                   hmap_count(&ofproto->subfacets));
7862
7863     ports = shash_sort(&ofproto->up.port_by_name);
7864     for (i = 0; i < shash_count(&ofproto->up.port_by_name); i++) {
7865         const struct shash_node *node = ports[i];
7866         struct ofport *ofport = node->data;
7867         const char *name = netdev_get_name(ofport->netdev);
7868         const char *type = netdev_get_type(ofport->netdev);
7869         uint32_t odp_port;
7870
7871         ds_put_format(ds, "\t%s %u/", name, ofport->ofp_port);
7872
7873         odp_port = ofp_port_to_odp_port(ofproto, ofport->ofp_port);
7874         if (odp_port != OVSP_NONE) {
7875             ds_put_format(ds, "%"PRIu32":", odp_port);
7876         } else {
7877             ds_put_cstr(ds, "none:");
7878         }
7879
7880         if (strcmp(type, "system")) {
7881             struct netdev *netdev;
7882             int error;
7883
7884             ds_put_format(ds, " (%s", type);
7885
7886             error = netdev_open(name, type, &netdev);
7887             if (!error) {
7888                 struct smap config;
7889
7890                 smap_init(&config);
7891                 error = netdev_get_config(netdev, &config);
7892                 if (!error) {
7893                     const struct smap_node **nodes;
7894                     size_t i;
7895
7896                     nodes = smap_sort(&config);
7897                     for (i = 0; i < smap_count(&config); i++) {
7898                         const struct smap_node *node = nodes[i];
7899                         ds_put_format(ds, "%c %s=%s", i ? ',' : ':',
7900                                       node->key, node->value);
7901                     }
7902                     free(nodes);
7903                 }
7904                 smap_destroy(&config);
7905
7906                 netdev_close(netdev);
7907             }
7908             ds_put_char(ds, ')');
7909         }
7910         ds_put_char(ds, '\n');
7911     }
7912     free(ports);
7913 }
7914
7915 static void
7916 ofproto_unixctl_dpif_show(struct unixctl_conn *conn, int argc,
7917                           const char *argv[], void *aux OVS_UNUSED)
7918 {
7919     struct ds ds = DS_EMPTY_INITIALIZER;
7920     const struct ofproto_dpif *ofproto;
7921
7922     if (argc > 1) {
7923         int i;
7924         for (i = 1; i < argc; i++) {
7925             ofproto = ofproto_dpif_lookup(argv[i]);
7926             if (!ofproto) {
7927                 ds_put_format(&ds, "Unknown bridge %s (use dpif/dump-dps "
7928                                    "for help)", argv[i]);
7929                 unixctl_command_reply_error(conn, ds_cstr(&ds));
7930                 return;
7931             }
7932             show_dp_format(ofproto, &ds);
7933         }
7934     } else {
7935         struct shash ofproto_shash;
7936         const struct shash_node **sorted_ofprotos;
7937         int i;
7938
7939         shash_init(&ofproto_shash);
7940         sorted_ofprotos = get_ofprotos(&ofproto_shash);
7941         for (i = 0; i < shash_count(&ofproto_shash); i++) {
7942             const struct shash_node *node = sorted_ofprotos[i];
7943             show_dp_format(node->data, &ds);
7944         }
7945
7946         shash_destroy(&ofproto_shash);
7947         free(sorted_ofprotos);
7948     }
7949
7950     unixctl_command_reply(conn, ds_cstr(&ds));
7951     ds_destroy(&ds);
7952 }
7953
7954 static void
7955 ofproto_unixctl_dpif_dump_flows(struct unixctl_conn *conn,
7956                                 int argc OVS_UNUSED, const char *argv[],
7957                                 void *aux OVS_UNUSED)
7958 {
7959     struct ds ds = DS_EMPTY_INITIALIZER;
7960     const struct ofproto_dpif *ofproto;
7961     struct subfacet *subfacet;
7962
7963     ofproto = ofproto_dpif_lookup(argv[1]);
7964     if (!ofproto) {
7965         unixctl_command_reply_error(conn, "no such bridge");
7966         return;
7967     }
7968
7969     update_stats(ofproto->backer);
7970
7971     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->subfacets) {
7972         odp_flow_key_format(subfacet->key, subfacet->key_len, &ds);
7973
7974         ds_put_format(&ds, ", packets:%"PRIu64", bytes:%"PRIu64", used:",
7975                       subfacet->dp_packet_count, subfacet->dp_byte_count);
7976         if (subfacet->used) {
7977             ds_put_format(&ds, "%.3fs",
7978                           (time_msec() - subfacet->used) / 1000.0);
7979         } else {
7980             ds_put_format(&ds, "never");
7981         }
7982         if (subfacet->facet->tcp_flags) {
7983             ds_put_cstr(&ds, ", flags:");
7984             packet_format_tcp_flags(&ds, subfacet->facet->tcp_flags);
7985         }
7986
7987         ds_put_cstr(&ds, ", actions:");
7988         format_odp_actions(&ds, subfacet->actions, subfacet->actions_len);
7989         ds_put_char(&ds, '\n');
7990     }
7991
7992     unixctl_command_reply(conn, ds_cstr(&ds));
7993     ds_destroy(&ds);
7994 }
7995
7996 static void
7997 ofproto_unixctl_dpif_del_flows(struct unixctl_conn *conn,
7998                                int argc OVS_UNUSED, const char *argv[],
7999                                void *aux OVS_UNUSED)
8000 {
8001     struct ds ds = DS_EMPTY_INITIALIZER;
8002     struct ofproto_dpif *ofproto;
8003
8004     ofproto = ofproto_dpif_lookup(argv[1]);
8005     if (!ofproto) {
8006         unixctl_command_reply_error(conn, "no such bridge");
8007         return;
8008     }
8009
8010     flush(&ofproto->up);
8011
8012     unixctl_command_reply(conn, ds_cstr(&ds));
8013     ds_destroy(&ds);
8014 }
8015
8016 static void
8017 ofproto_dpif_unixctl_init(void)
8018 {
8019     static bool registered;
8020     if (registered) {
8021         return;
8022     }
8023     registered = true;
8024
8025     unixctl_command_register(
8026         "ofproto/trace",
8027         "bridge {priority tun_id in_port mark packet | odp_flow [-generate]}",
8028         2, 6, ofproto_unixctl_trace, NULL);
8029     unixctl_command_register("fdb/flush", "[bridge]", 0, 1,
8030                              ofproto_unixctl_fdb_flush, NULL);
8031     unixctl_command_register("fdb/show", "bridge", 1, 1,
8032                              ofproto_unixctl_fdb_show, NULL);
8033     unixctl_command_register("ofproto/clog", "", 0, 0,
8034                              ofproto_dpif_clog, NULL);
8035     unixctl_command_register("ofproto/unclog", "", 0, 0,
8036                              ofproto_dpif_unclog, NULL);
8037     unixctl_command_register("ofproto/self-check", "[bridge]", 0, 1,
8038                              ofproto_dpif_self_check, NULL);
8039     unixctl_command_register("dpif/dump-dps", "", 0, 0,
8040                              ofproto_unixctl_dpif_dump_dps, NULL);
8041     unixctl_command_register("dpif/show", "[bridge]", 0, INT_MAX,
8042                              ofproto_unixctl_dpif_show, NULL);
8043     unixctl_command_register("dpif/dump-flows", "bridge", 1, 1,
8044                              ofproto_unixctl_dpif_dump_flows, NULL);
8045     unixctl_command_register("dpif/del-flows", "bridge", 1, 1,
8046                              ofproto_unixctl_dpif_del_flows, NULL);
8047 }
8048 \f
8049 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
8050  *
8051  * This is deprecated.  It is only for compatibility with broken device drivers
8052  * in old versions of Linux that do not properly support VLANs when VLAN
8053  * devices are not used.  When broken device drivers are no longer in
8054  * widespread use, we will delete these interfaces. */
8055
8056 static int
8057 set_realdev(struct ofport *ofport_, uint16_t realdev_ofp_port, int vid)
8058 {
8059     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
8060     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
8061
8062     if (realdev_ofp_port == ofport->realdev_ofp_port
8063         && vid == ofport->vlandev_vid) {
8064         return 0;
8065     }
8066
8067     ofproto->backer->need_revalidate = REV_RECONFIGURE;
8068
8069     if (ofport->realdev_ofp_port) {
8070         vsp_remove(ofport);
8071     }
8072     if (realdev_ofp_port && ofport->bundle) {
8073         /* vlandevs are enslaved to their realdevs, so they are not allowed to
8074          * themselves be part of a bundle. */
8075         bundle_set(ofport->up.ofproto, ofport->bundle, NULL);
8076     }
8077
8078     ofport->realdev_ofp_port = realdev_ofp_port;
8079     ofport->vlandev_vid = vid;
8080
8081     if (realdev_ofp_port) {
8082         vsp_add(ofport, realdev_ofp_port, vid);
8083     }
8084
8085     return 0;
8086 }
8087
8088 static uint32_t
8089 hash_realdev_vid(uint16_t realdev_ofp_port, int vid)
8090 {
8091     return hash_2words(realdev_ofp_port, vid);
8092 }
8093
8094 /* Returns the ODP port number of the Linux VLAN device that corresponds to
8095  * 'vlan_tci' on the network device with port number 'realdev_odp_port' in
8096  * 'ofproto'.  For example, given 'realdev_odp_port' of eth0 and 'vlan_tci' 9,
8097  * it would return the port number of eth0.9.
8098  *
8099  * Unless VLAN splinters are enabled for port 'realdev_odp_port', this
8100  * function just returns its 'realdev_odp_port' argument. */
8101 static uint32_t
8102 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
8103                        uint32_t realdev_odp_port, ovs_be16 vlan_tci)
8104 {
8105     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
8106         uint16_t realdev_ofp_port;
8107         int vid = vlan_tci_to_vid(vlan_tci);
8108         const struct vlan_splinter *vsp;
8109
8110         realdev_ofp_port = odp_port_to_ofp_port(ofproto, realdev_odp_port);
8111         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
8112                                  hash_realdev_vid(realdev_ofp_port, vid),
8113                                  &ofproto->realdev_vid_map) {
8114             if (vsp->realdev_ofp_port == realdev_ofp_port
8115                 && vsp->vid == vid) {
8116                 return ofp_port_to_odp_port(ofproto, vsp->vlandev_ofp_port);
8117             }
8118         }
8119     }
8120     return realdev_odp_port;
8121 }
8122
8123 static struct vlan_splinter *
8124 vlandev_find(const struct ofproto_dpif *ofproto, uint16_t vlandev_ofp_port)
8125 {
8126     struct vlan_splinter *vsp;
8127
8128     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node, hash_int(vlandev_ofp_port, 0),
8129                              &ofproto->vlandev_map) {
8130         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
8131             return vsp;
8132         }
8133     }
8134
8135     return NULL;
8136 }
8137
8138 /* Returns the OpenFlow port number of the "real" device underlying the Linux
8139  * VLAN device with OpenFlow port number 'vlandev_ofp_port' and stores the
8140  * VLAN VID of the Linux VLAN device in '*vid'.  For example, given
8141  * 'vlandev_ofp_port' of eth0.9, it would return the OpenFlow port number of
8142  * eth0 and store 9 in '*vid'.
8143  *
8144  * Returns 0 and does not modify '*vid' if 'vlandev_ofp_port' is not a Linux
8145  * VLAN device.  Unless VLAN splinters are enabled, this is what this function
8146  * always does.*/
8147 static uint16_t
8148 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
8149                        uint16_t vlandev_ofp_port, int *vid)
8150 {
8151     if (!hmap_is_empty(&ofproto->vlandev_map)) {
8152         const struct vlan_splinter *vsp;
8153
8154         vsp = vlandev_find(ofproto, vlandev_ofp_port);
8155         if (vsp) {
8156             if (vid) {
8157                 *vid = vsp->vid;
8158             }
8159             return vsp->realdev_ofp_port;
8160         }
8161     }
8162     return 0;
8163 }
8164
8165 /* Given 'flow', a flow representing a packet received on 'ofproto', checks
8166  * whether 'flow->in_port' represents a Linux VLAN device.  If so, changes
8167  * 'flow->in_port' to the "real" device backing the VLAN device, sets
8168  * 'flow->vlan_tci' to the VLAN VID, and returns true.  Otherwise (which is
8169  * always the case unless VLAN splinters are enabled), returns false without
8170  * making any changes. */
8171 static bool
8172 vsp_adjust_flow(const struct ofproto_dpif *ofproto, struct flow *flow)
8173 {
8174     uint16_t realdev;
8175     int vid;
8176
8177     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port, &vid);
8178     if (!realdev) {
8179         return false;
8180     }
8181
8182     /* Cause the flow to be processed as if it came in on the real device with
8183      * the VLAN device's VLAN ID. */
8184     flow->in_port = realdev;
8185     flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
8186     return true;
8187 }
8188
8189 static void
8190 vsp_remove(struct ofport_dpif *port)
8191 {
8192     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
8193     struct vlan_splinter *vsp;
8194
8195     vsp = vlandev_find(ofproto, port->up.ofp_port);
8196     if (vsp) {
8197         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
8198         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
8199         free(vsp);
8200
8201         port->realdev_ofp_port = 0;
8202     } else {
8203         VLOG_ERR("missing vlan device record");
8204     }
8205 }
8206
8207 static void
8208 vsp_add(struct ofport_dpif *port, uint16_t realdev_ofp_port, int vid)
8209 {
8210     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
8211
8212     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
8213         && (vsp_realdev_to_vlandev(ofproto, realdev_ofp_port, htons(vid))
8214             == realdev_ofp_port)) {
8215         struct vlan_splinter *vsp;
8216
8217         vsp = xmalloc(sizeof *vsp);
8218         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
8219                     hash_int(port->up.ofp_port, 0));
8220         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
8221                     hash_realdev_vid(realdev_ofp_port, vid));
8222         vsp->realdev_ofp_port = realdev_ofp_port;
8223         vsp->vlandev_ofp_port = port->up.ofp_port;
8224         vsp->vid = vid;
8225
8226         port->realdev_ofp_port = realdev_ofp_port;
8227     } else {
8228         VLOG_ERR("duplicate vlan device record");
8229     }
8230 }
8231
8232 static uint32_t
8233 ofp_port_to_odp_port(const struct ofproto_dpif *ofproto, uint16_t ofp_port)
8234 {
8235     const struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
8236     return ofport ? ofport->odp_port : OVSP_NONE;
8237 }
8238
8239 static struct ofport_dpif *
8240 odp_port_to_ofport(const struct dpif_backer *backer, uint32_t odp_port)
8241 {
8242     struct ofport_dpif *port;
8243
8244     HMAP_FOR_EACH_IN_BUCKET (port, odp_port_node,
8245                              hash_int(odp_port, 0),
8246                              &backer->odp_to_ofport_map) {
8247         if (port->odp_port == odp_port) {
8248             return port;
8249         }
8250     }
8251
8252     return NULL;
8253 }
8254
8255 static uint16_t
8256 odp_port_to_ofp_port(const struct ofproto_dpif *ofproto, uint32_t odp_port)
8257 {
8258     struct ofport_dpif *port;
8259
8260     port = odp_port_to_ofport(ofproto->backer, odp_port);
8261     if (port && &ofproto->up == port->up.ofproto) {
8262         return port->up.ofp_port;
8263     } else {
8264         return OFPP_NONE;
8265     }
8266 }
8267
8268 const struct ofproto_class ofproto_dpif_class = {
8269     init,
8270     enumerate_types,
8271     enumerate_names,
8272     del,
8273     port_open_type,
8274     type_run,
8275     type_run_fast,
8276     type_wait,
8277     alloc,
8278     construct,
8279     destruct,
8280     dealloc,
8281     run,
8282     run_fast,
8283     wait,
8284     get_memory_usage,
8285     flush,
8286     get_features,
8287     get_tables,
8288     port_alloc,
8289     port_construct,
8290     port_destruct,
8291     port_dealloc,
8292     port_modified,
8293     port_reconfigured,
8294     port_query_by_name,
8295     port_add,
8296     port_del,
8297     port_get_stats,
8298     port_dump_start,
8299     port_dump_next,
8300     port_dump_done,
8301     port_poll,
8302     port_poll_wait,
8303     port_is_lacp_current,
8304     NULL,                       /* rule_choose_table */
8305     rule_alloc,
8306     rule_construct,
8307     rule_destruct,
8308     rule_dealloc,
8309     rule_get_stats,
8310     rule_execute,
8311     rule_modify_actions,
8312     set_frag_handling,
8313     packet_out,
8314     set_netflow,
8315     get_netflow_ids,
8316     set_sflow,
8317     set_cfm,
8318     get_cfm_fault,
8319     get_cfm_opup,
8320     get_cfm_remote_mpids,
8321     get_cfm_health,
8322     set_stp,
8323     get_stp_status,
8324     set_stp_port,
8325     get_stp_port_status,
8326     set_queues,
8327     bundle_set,
8328     bundle_remove,
8329     mirror_set,
8330     mirror_get_stats,
8331     set_flood_vlans,
8332     is_mirror_output_bundle,
8333     forward_bpdu_changed,
8334     set_mac_table_config,
8335     set_realdev,
8336 };