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