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