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