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