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