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