776be964439353efb42a79721fd8e01b22812de6
[cascardo/ovs.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_char(&s, ')');
4947
4948             VLOG_WARN("%s", ds_cstr(&s));
4949             ds_destroy(&s);
4950         }
4951         return false;
4952     }
4953
4954     /* Check the datapath actions for consistency. */
4955     xlate_in_init(&xin, ofproto, &facet->flow, &facet->initial_vals, rule,
4956                   0, NULL);
4957     xlate_actions(&xin, &xout);
4958
4959     ok = ofpbuf_equal(&facet->xout.odp_actions, &xout.odp_actions)
4960         && facet->xout.slow == xout.slow;
4961     if (!ok && !VLOG_DROP_WARN(&rl)) {
4962         struct ds s = DS_EMPTY_INITIALIZER;
4963
4964         flow_format(&s, &facet->flow);
4965         ds_put_cstr(&s, ": inconsistency in facet");
4966
4967         if (!ofpbuf_equal(&facet->xout.odp_actions, &xout.odp_actions)) {
4968             ds_put_cstr(&s, " (actions were: ");
4969             format_odp_actions(&s, facet->xout.odp_actions.data,
4970                                facet->xout.odp_actions.size);
4971             ds_put_cstr(&s, ") (correct actions: ");
4972             format_odp_actions(&s, xout.odp_actions.data,
4973                                xout.odp_actions.size);
4974             ds_put_char(&s, ')');
4975         }
4976
4977         if (facet->xout.slow != xout.slow) {
4978             ds_put_format(&s, " slow path incorrect. should be %d", xout.slow);
4979         }
4980
4981         VLOG_WARN("%s", ds_cstr(&s));
4982         ds_destroy(&s);
4983     }
4984     xlate_out_uninit(&xout);
4985
4986     return ok;
4987 }
4988
4989 /* Re-searches the classifier for 'facet':
4990  *
4991  *   - If the rule found is different from 'facet''s current rule, moves
4992  *     'facet' to the new rule and recompiles its actions.
4993  *
4994  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
4995  *     where it is and recompiles its actions anyway.
4996  *
4997  *   - If any of 'facet''s subfacets correspond to a new flow according to
4998  *     ofproto_receive(), 'facet' is removed.
4999  *
5000  *   Returns true if 'facet' is still valid.  False if 'facet' was removed. */
5001 static bool
5002 facet_revalidate(struct facet *facet)
5003 {
5004     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
5005     struct rule_dpif *new_rule;
5006     struct subfacet *subfacet;
5007     struct xlate_out xout;
5008     struct xlate_in xin;
5009
5010     COVERAGE_INC(facet_revalidate);
5011
5012     /* Check that child subfacets still correspond to this facet.  Tunnel
5013      * configuration changes could cause a subfacet's OpenFlow in_port to
5014      * change. */
5015     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
5016         struct ofproto_dpif *recv_ofproto;
5017         struct flow recv_flow;
5018         int error;
5019
5020         error = ofproto_receive(ofproto->backer, NULL, subfacet->key,
5021                                 subfacet->key_len, &recv_flow, NULL,
5022                                 &recv_ofproto, NULL, NULL);
5023         if (error
5024             || recv_ofproto != ofproto
5025             || memcmp(&recv_flow, &facet->flow, sizeof recv_flow)) {
5026             facet_remove(facet);
5027             return false;
5028         }
5029     }
5030
5031     new_rule = rule_dpif_lookup(ofproto, &facet->flow);
5032
5033     /* Calculate new datapath actions.
5034      *
5035      * We do not modify any 'facet' state yet, because we might need to, e.g.,
5036      * emit a NetFlow expiration and, if so, we need to have the old state
5037      * around to properly compose it. */
5038     xlate_in_init(&xin, ofproto, &facet->flow, &facet->initial_vals, new_rule,
5039                   0, NULL);
5040     xlate_actions(&xin, &xout);
5041
5042     /* A facet's slow path reason should only change under dramatic
5043      * circumstances.  Rather than try to update everything, it's simpler to
5044      * remove the facet and start over. */
5045     if (facet->xout.slow != xout.slow) {
5046         facet_remove(facet);
5047         xlate_out_uninit(&xout);
5048         return false;
5049     }
5050
5051     if (!ofpbuf_equal(&facet->xout.odp_actions, &xout.odp_actions)) {
5052         LIST_FOR_EACH(subfacet, list_node, &facet->subfacets) {
5053             if (subfacet->path == SF_FAST_PATH) {
5054                 struct dpif_flow_stats stats;
5055
5056                 subfacet_install(subfacet, &xout.odp_actions, &stats);
5057                 subfacet_update_stats(subfacet, &stats);
5058             }
5059         }
5060
5061         facet_flush_stats(facet);
5062
5063         ofpbuf_clear(&facet->xout.odp_actions);
5064         ofpbuf_put(&facet->xout.odp_actions, xout.odp_actions.data,
5065                    xout.odp_actions.size);
5066     }
5067
5068     /* Update 'facet' now that we've taken care of all the old state. */
5069     facet->xout.tags = xout.tags;
5070     facet->xout.slow = xout.slow;
5071     facet->xout.has_learn = xout.has_learn;
5072     facet->xout.has_normal = xout.has_normal;
5073     facet->xout.has_fin_timeout = xout.has_fin_timeout;
5074     facet->xout.nf_output_iface = xout.nf_output_iface;
5075     facet->xout.mirrors = xout.mirrors;
5076     facet->nf_flow.output_iface = facet->xout.nf_output_iface;
5077
5078     if (facet->rule != new_rule) {
5079         COVERAGE_INC(facet_changed_rule);
5080         list_remove(&facet->list_node);
5081         list_push_back(&new_rule->facets, &facet->list_node);
5082         facet->rule = new_rule;
5083         facet->used = new_rule->up.created;
5084         facet->prev_used = facet->used;
5085     }
5086
5087     xlate_out_uninit(&xout);
5088     return true;
5089 }
5090
5091 static void
5092 facet_reset_counters(struct facet *facet)
5093 {
5094     facet->packet_count = 0;
5095     facet->byte_count = 0;
5096     facet->prev_packet_count = 0;
5097     facet->prev_byte_count = 0;
5098     facet->accounted_bytes = 0;
5099 }
5100
5101 static void
5102 facet_push_stats(struct facet *facet, bool may_learn)
5103 {
5104     struct dpif_flow_stats stats;
5105
5106     ovs_assert(facet->packet_count >= facet->prev_packet_count);
5107     ovs_assert(facet->byte_count >= facet->prev_byte_count);
5108     ovs_assert(facet->used >= facet->prev_used);
5109
5110     stats.n_packets = facet->packet_count - facet->prev_packet_count;
5111     stats.n_bytes = facet->byte_count - facet->prev_byte_count;
5112     stats.used = facet->used;
5113     stats.tcp_flags = facet->tcp_flags;
5114
5115     if (may_learn || stats.n_packets || facet->used > facet->prev_used) {
5116         struct ofproto_dpif *ofproto =
5117             ofproto_dpif_cast(facet->rule->up.ofproto);
5118
5119         struct ofport_dpif *in_port;
5120         struct xlate_in xin;
5121
5122         facet->prev_packet_count = facet->packet_count;
5123         facet->prev_byte_count = facet->byte_count;
5124         facet->prev_used = facet->used;
5125
5126         in_port = get_ofp_port(ofproto, facet->flow.in_port);
5127         if (in_port && in_port->tnl_port) {
5128             netdev_vport_inc_rx(in_port->up.netdev, &stats);
5129         }
5130
5131         rule_credit_stats(facet->rule, &stats);
5132         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow,
5133                                  facet->used);
5134         netflow_flow_update_flags(&facet->nf_flow, facet->tcp_flags);
5135         update_mirror_stats(ofproto, facet->xout.mirrors, stats.n_packets,
5136                             stats.n_bytes);
5137
5138         xlate_in_init(&xin, ofproto, &facet->flow, &facet->initial_vals,
5139                       facet->rule, stats.tcp_flags, NULL);
5140         xin.resubmit_stats = &stats;
5141         xin.may_learn = may_learn;
5142         xlate_actions_for_side_effects(&xin);
5143     }
5144 }
5145
5146 static void
5147 push_all_stats__(bool run_fast)
5148 {
5149     static long long int rl = LLONG_MIN;
5150     struct ofproto_dpif *ofproto;
5151
5152     if (time_msec() < rl) {
5153         return;
5154     }
5155
5156     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
5157         struct facet *facet;
5158
5159         HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
5160             facet_push_stats(facet, false);
5161             if (run_fast) {
5162                 run_fast_rl();
5163             }
5164         }
5165     }
5166
5167     rl = time_msec() + 100;
5168 }
5169
5170 static void
5171 push_all_stats(void)
5172 {
5173     push_all_stats__(true);
5174 }
5175
5176 static void
5177 rule_credit_stats(struct rule_dpif *rule, const struct dpif_flow_stats *stats)
5178 {
5179     rule->packet_count += stats->n_packets;
5180     rule->byte_count += stats->n_bytes;
5181     ofproto_rule_update_used(&rule->up, stats->used);
5182 }
5183 \f
5184 /* Subfacets. */
5185
5186 static struct subfacet *
5187 subfacet_find(struct ofproto_dpif *ofproto,
5188               const struct nlattr *key, size_t key_len, uint32_t key_hash)
5189 {
5190     struct subfacet *subfacet;
5191
5192     HMAP_FOR_EACH_WITH_HASH (subfacet, hmap_node, key_hash,
5193                              &ofproto->subfacets) {
5194         if (subfacet->key_len == key_len
5195             && !memcmp(key, subfacet->key, key_len)) {
5196             return subfacet;
5197         }
5198     }
5199
5200     return NULL;
5201 }
5202
5203 /* Searches 'facet' (within 'ofproto') for a subfacet with the specified
5204  * 'key_fitness', 'key', and 'key_len' members in 'miss'.  Returns the
5205  * existing subfacet if there is one, otherwise creates and returns a
5206  * new subfacet. */
5207 static struct subfacet *
5208 subfacet_create(struct facet *facet, struct flow_miss *miss,
5209                 long long int now)
5210 {
5211     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
5212     enum odp_key_fitness key_fitness = miss->key_fitness;
5213     const struct nlattr *key = miss->key;
5214     size_t key_len = miss->key_len;
5215     uint32_t key_hash;
5216     struct subfacet *subfacet;
5217
5218     key_hash = odp_flow_key_hash(key, key_len);
5219
5220     if (list_is_empty(&facet->subfacets)) {
5221         subfacet = &facet->one_subfacet;
5222     } else {
5223         subfacet = subfacet_find(ofproto, key, key_len, key_hash);
5224         if (subfacet) {
5225             if (subfacet->facet == facet) {
5226                 return subfacet;
5227             }
5228
5229             /* This shouldn't happen. */
5230             VLOG_ERR_RL(&rl, "subfacet with wrong facet");
5231             subfacet_destroy(subfacet);
5232         }
5233
5234         subfacet = xmalloc(sizeof *subfacet);
5235     }
5236
5237     hmap_insert(&ofproto->subfacets, &subfacet->hmap_node, key_hash);
5238     list_push_back(&facet->subfacets, &subfacet->list_node);
5239     subfacet->facet = facet;
5240     subfacet->key_fitness = key_fitness;
5241     subfacet->key = xmemdup(key, key_len);
5242     subfacet->key_len = key_len;
5243     subfacet->used = now;
5244     subfacet->created = now;
5245     subfacet->dp_packet_count = 0;
5246     subfacet->dp_byte_count = 0;
5247     subfacet->path = SF_NOT_INSTALLED;
5248
5249     ofproto->subfacet_add_count++;
5250     return subfacet;
5251 }
5252
5253 /* Uninstalls 'subfacet' from the datapath, if it is installed, removes it from
5254  * its facet within 'ofproto', and frees it. */
5255 static void
5256 subfacet_destroy__(struct subfacet *subfacet)
5257 {
5258     struct facet *facet = subfacet->facet;
5259     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
5260
5261     /* Update ofproto stats before uninstall the subfacet. */
5262     ofproto->subfacet_del_count++;
5263     ofproto->total_subfacet_life_span += (time_msec() - subfacet->created);
5264
5265     subfacet_uninstall(subfacet);
5266     hmap_remove(&ofproto->subfacets, &subfacet->hmap_node);
5267     list_remove(&subfacet->list_node);
5268     free(subfacet->key);
5269     if (subfacet != &facet->one_subfacet) {
5270         free(subfacet);
5271     }
5272 }
5273
5274 /* Destroys 'subfacet', as with subfacet_destroy__(), and then if this was the
5275  * last remaining subfacet in its facet destroys the facet too. */
5276 static void
5277 subfacet_destroy(struct subfacet *subfacet)
5278 {
5279     struct facet *facet = subfacet->facet;
5280
5281     if (list_is_singleton(&facet->subfacets)) {
5282         /* facet_remove() needs at least one subfacet (it will remove it). */
5283         facet_remove(facet);
5284     } else {
5285         subfacet_destroy__(subfacet);
5286     }
5287 }
5288
5289 static void
5290 subfacet_destroy_batch(struct ofproto_dpif *ofproto,
5291                        struct subfacet **subfacets, int n)
5292 {
5293     struct dpif_op ops[SUBFACET_DESTROY_MAX_BATCH];
5294     struct dpif_op *opsp[SUBFACET_DESTROY_MAX_BATCH];
5295     struct dpif_flow_stats stats[SUBFACET_DESTROY_MAX_BATCH];
5296     int i;
5297
5298     for (i = 0; i < n; i++) {
5299         ops[i].type = DPIF_OP_FLOW_DEL;
5300         ops[i].u.flow_del.key = subfacets[i]->key;
5301         ops[i].u.flow_del.key_len = subfacets[i]->key_len;
5302         ops[i].u.flow_del.stats = &stats[i];
5303         opsp[i] = &ops[i];
5304     }
5305
5306     dpif_operate(ofproto->backer->dpif, opsp, n);
5307     for (i = 0; i < n; i++) {
5308         subfacet_reset_dp_stats(subfacets[i], &stats[i]);
5309         subfacets[i]->path = SF_NOT_INSTALLED;
5310         subfacet_destroy(subfacets[i]);
5311         run_fast_rl();
5312     }
5313 }
5314
5315 /* Updates 'subfacet''s datapath flow, setting its actions to 'actions_len'
5316  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
5317  * in the datapath will be zeroed and 'stats' will be updated with traffic new
5318  * since 'subfacet' was last updated.
5319  *
5320  * Returns 0 if successful, otherwise a positive errno value. */
5321 static int
5322 subfacet_install(struct subfacet *subfacet, const struct ofpbuf *odp_actions,
5323                  struct dpif_flow_stats *stats)
5324 {
5325     struct facet *facet = subfacet->facet;
5326     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
5327     enum subfacet_path path = facet->xout.slow ? SF_SLOW_PATH : SF_FAST_PATH;
5328     const struct nlattr *actions = odp_actions->data;
5329     size_t actions_len = odp_actions->size;
5330
5331     uint64_t slow_path_stub[128 / 8];
5332     enum dpif_flow_put_flags flags;
5333     int ret;
5334
5335     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
5336     if (stats) {
5337         flags |= DPIF_FP_ZERO_STATS;
5338     }
5339
5340     if (path == SF_SLOW_PATH) {
5341         compose_slow_path(ofproto, &facet->flow, facet->xout.slow,
5342                           slow_path_stub, sizeof slow_path_stub,
5343                           &actions, &actions_len);
5344     }
5345
5346     ret = dpif_flow_put(ofproto->backer->dpif, flags, subfacet->key,
5347                         subfacet->key_len, actions, actions_len, stats);
5348
5349     if (stats) {
5350         subfacet_reset_dp_stats(subfacet, stats);
5351     }
5352
5353     if (!ret) {
5354         subfacet->path = path;
5355     }
5356     return ret;
5357 }
5358
5359 /* If 'subfacet' is installed in the datapath, uninstalls it. */
5360 static void
5361 subfacet_uninstall(struct subfacet *subfacet)
5362 {
5363     if (subfacet->path != SF_NOT_INSTALLED) {
5364         struct rule_dpif *rule = subfacet->facet->rule;
5365         struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5366         struct dpif_flow_stats stats;
5367         int error;
5368
5369         error = dpif_flow_del(ofproto->backer->dpif, subfacet->key,
5370                               subfacet->key_len, &stats);
5371         subfacet_reset_dp_stats(subfacet, &stats);
5372         if (!error) {
5373             subfacet_update_stats(subfacet, &stats);
5374         }
5375         subfacet->path = SF_NOT_INSTALLED;
5376     } else {
5377         ovs_assert(subfacet->dp_packet_count == 0);
5378         ovs_assert(subfacet->dp_byte_count == 0);
5379     }
5380 }
5381
5382 /* Resets 'subfacet''s datapath statistics counters.  This should be called
5383  * when 'subfacet''s statistics are cleared in the datapath.  If 'stats' is
5384  * non-null, it should contain the statistics returned by dpif when 'subfacet'
5385  * was reset in the datapath.  'stats' will be modified to include only
5386  * statistics new since 'subfacet' was last updated. */
5387 static void
5388 subfacet_reset_dp_stats(struct subfacet *subfacet,
5389                         struct dpif_flow_stats *stats)
5390 {
5391     if (stats
5392         && subfacet->dp_packet_count <= stats->n_packets
5393         && subfacet->dp_byte_count <= stats->n_bytes) {
5394         stats->n_packets -= subfacet->dp_packet_count;
5395         stats->n_bytes -= subfacet->dp_byte_count;
5396     }
5397
5398     subfacet->dp_packet_count = 0;
5399     subfacet->dp_byte_count = 0;
5400 }
5401
5402 /* Folds the statistics from 'stats' into the counters in 'subfacet'.
5403  *
5404  * Because of the meaning of a subfacet's counters, it only makes sense to do
5405  * this if 'stats' are not tracked in the datapath, that is, if 'stats'
5406  * represents a packet that was sent by hand or if it represents statistics
5407  * that have been cleared out of the datapath. */
5408 static void
5409 subfacet_update_stats(struct subfacet *subfacet,
5410                       const struct dpif_flow_stats *stats)
5411 {
5412     if (stats->n_packets || stats->used > subfacet->used) {
5413         struct facet *facet = subfacet->facet;
5414
5415         subfacet->used = MAX(subfacet->used, stats->used);
5416         facet->used = MAX(facet->used, stats->used);
5417         facet->packet_count += stats->n_packets;
5418         facet->byte_count += stats->n_bytes;
5419         facet->tcp_flags |= stats->tcp_flags;
5420     }
5421 }
5422 \f
5423 /* Rules. */
5424
5425 static struct rule_dpif *
5426 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow)
5427 {
5428     struct rule_dpif *rule;
5429
5430     rule = rule_dpif_lookup__(ofproto, flow, 0);
5431     if (rule) {
5432         return rule;
5433     }
5434
5435     return rule_dpif_miss_rule(ofproto, flow);
5436 }
5437
5438 static struct rule_dpif *
5439 rule_dpif_lookup__(struct ofproto_dpif *ofproto, const struct flow *flow,
5440                    uint8_t table_id)
5441 {
5442     struct cls_rule *cls_rule;
5443     struct classifier *cls;
5444     bool frag;
5445
5446     if (table_id >= N_TABLES) {
5447         return NULL;
5448     }
5449
5450     cls = &ofproto->up.tables[table_id].cls;
5451     frag = (flow->nw_frag & FLOW_NW_FRAG_ANY) != 0;
5452     if (frag && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
5453         /* We must pretend that transport ports are unavailable. */
5454         struct flow ofpc_normal_flow = *flow;
5455         ofpc_normal_flow.tp_src = htons(0);
5456         ofpc_normal_flow.tp_dst = htons(0);
5457         cls_rule = classifier_lookup(cls, &ofpc_normal_flow);
5458     } else if (frag && ofproto->up.frag_handling == OFPC_FRAG_DROP) {
5459         cls_rule = &ofproto->drop_frags_rule->up.cr;
5460     } else {
5461         cls_rule = classifier_lookup(cls, flow);
5462     }
5463     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
5464 }
5465
5466 static struct rule_dpif *
5467 rule_dpif_miss_rule(struct ofproto_dpif *ofproto, const struct flow *flow)
5468 {
5469     struct ofport_dpif *port;
5470
5471     port = get_ofp_port(ofproto, flow->in_port);
5472     if (!port) {
5473         VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16, flow->in_port);
5474         return ofproto->miss_rule;
5475     }
5476
5477     if (port->up.pp.config & OFPUTIL_PC_NO_PACKET_IN) {
5478         return ofproto->no_packet_in_rule;
5479     }
5480     return ofproto->miss_rule;
5481 }
5482
5483 static void
5484 complete_operation(struct rule_dpif *rule)
5485 {
5486     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5487
5488     rule_invalidate(rule);
5489     if (clogged) {
5490         struct dpif_completion *c = xmalloc(sizeof *c);
5491         c->op = rule->up.pending;
5492         list_push_back(&ofproto->completions, &c->list_node);
5493     } else {
5494         ofoperation_complete(rule->up.pending, 0);
5495     }
5496 }
5497
5498 static struct rule *
5499 rule_alloc(void)
5500 {
5501     struct rule_dpif *rule = xmalloc(sizeof *rule);
5502     return &rule->up;
5503 }
5504
5505 static void
5506 rule_dealloc(struct rule *rule_)
5507 {
5508     struct rule_dpif *rule = rule_dpif_cast(rule_);
5509     free(rule);
5510 }
5511
5512 static enum ofperr
5513 rule_construct(struct rule *rule_)
5514 {
5515     struct rule_dpif *rule = rule_dpif_cast(rule_);
5516     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5517     struct rule_dpif *victim;
5518     uint8_t table_id;
5519
5520     rule->packet_count = 0;
5521     rule->byte_count = 0;
5522
5523     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
5524     if (victim && !list_is_empty(&victim->facets)) {
5525         struct facet *facet;
5526
5527         rule->facets = victim->facets;
5528         list_moved(&rule->facets);
5529         LIST_FOR_EACH (facet, list_node, &rule->facets) {
5530             /* XXX: We're only clearing our local counters here.  It's possible
5531              * that quite a few packets are unaccounted for in the datapath
5532              * statistics.  These will be accounted to the new rule instead of
5533              * cleared as required.  This could be fixed by clearing out the
5534              * datapath statistics for this facet, but currently it doesn't
5535              * seem worth it. */
5536             facet_reset_counters(facet);
5537             facet->rule = rule;
5538         }
5539     } else {
5540         /* Must avoid list_moved() in this case. */
5541         list_init(&rule->facets);
5542     }
5543
5544     table_id = rule->up.table_id;
5545     if (victim) {
5546         rule->tag = victim->tag;
5547     } else if (table_id == 0) {
5548         rule->tag = 0;
5549     } else {
5550         struct flow flow;
5551
5552         miniflow_expand(&rule->up.cr.match.flow, &flow);
5553         rule->tag = rule_calculate_tag(&flow, &rule->up.cr.match.mask,
5554                                        ofproto->tables[table_id].basis);
5555     }
5556
5557     complete_operation(rule);
5558     return 0;
5559 }
5560
5561 static void
5562 rule_destruct(struct rule *rule_)
5563 {
5564     struct rule_dpif *rule = rule_dpif_cast(rule_);
5565     struct facet *facet, *next_facet;
5566
5567     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
5568         facet_revalidate(facet);
5569     }
5570
5571     complete_operation(rule);
5572 }
5573
5574 static void
5575 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
5576 {
5577     struct rule_dpif *rule = rule_dpif_cast(rule_);
5578
5579     /* push_all_stats() can handle flow misses which, when using the learn
5580      * action, can cause rules to be added and deleted.  This can corrupt our
5581      * caller's datastructures which assume that rule_get_stats() doesn't have
5582      * an impact on the flow table. To be safe, we disable miss handling. */
5583     push_all_stats__(false);
5584
5585     /* Start from historical data for 'rule' itself that are no longer tracked
5586      * in facets.  This counts, for example, facets that have expired. */
5587     *packets = rule->packet_count;
5588     *bytes = rule->byte_count;
5589 }
5590
5591 static void
5592 rule_dpif_execute(struct rule_dpif *rule, const struct flow *flow,
5593                   struct ofpbuf *packet)
5594 {
5595     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5596     struct initial_vals initial_vals;
5597     struct dpif_flow_stats stats;
5598     struct xlate_out xout;
5599     struct xlate_in xin;
5600
5601     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
5602     rule_credit_stats(rule, &stats);
5603
5604     initial_vals.vlan_tci = flow->vlan_tci;
5605     xlate_in_init(&xin, ofproto, flow, &initial_vals, rule, stats.tcp_flags,
5606                   packet);
5607     xin.resubmit_stats = &stats;
5608     xlate_actions(&xin, &xout);
5609
5610     execute_odp_actions(ofproto, flow, xout.odp_actions.data,
5611                         xout.odp_actions.size, packet);
5612
5613     xlate_out_uninit(&xout);
5614 }
5615
5616 static enum ofperr
5617 rule_execute(struct rule *rule, const struct flow *flow,
5618              struct ofpbuf *packet)
5619 {
5620     rule_dpif_execute(rule_dpif_cast(rule), flow, packet);
5621     ofpbuf_delete(packet);
5622     return 0;
5623 }
5624
5625 static void
5626 rule_modify_actions(struct rule *rule_)
5627 {
5628     struct rule_dpif *rule = rule_dpif_cast(rule_);
5629
5630     complete_operation(rule);
5631 }
5632 \f
5633 /* Sends 'packet' out 'ofport'.
5634  * May modify 'packet'.
5635  * Returns 0 if successful, otherwise a positive errno value. */
5636 static int
5637 send_packet(const struct ofport_dpif *ofport, struct ofpbuf *packet)
5638 {
5639     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
5640     uint64_t odp_actions_stub[1024 / 8];
5641     struct ofpbuf key, odp_actions;
5642     struct dpif_flow_stats stats;
5643     struct odputil_keybuf keybuf;
5644     struct ofpact_output output;
5645     struct xlate_out xout;
5646     struct xlate_in xin;
5647     struct flow flow;
5648     int error;
5649
5650     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
5651     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5652
5653     /* Use OFPP_NONE as the in_port to avoid special packet processing. */
5654     flow_extract(packet, 0, 0, NULL, OFPP_NONE, &flow);
5655     odp_flow_key_from_flow(&key, &flow, ofp_port_to_odp_port(ofproto,
5656                                                              OFPP_LOCAL));
5657     dpif_flow_stats_extract(&flow, packet, time_msec(), &stats);
5658
5659     ofpact_init(&output.ofpact, OFPACT_OUTPUT, sizeof output);
5660     output.port = ofport->up.ofp_port;
5661     output.max_len = 0;
5662
5663     xlate_in_init(&xin, ofproto, &flow, NULL, NULL, 0, packet);
5664     xin.ofpacts_len = sizeof output;
5665     xin.ofpacts = &output.ofpact;
5666     xin.resubmit_stats = &stats;
5667     xlate_actions(&xin, &xout);
5668
5669     error = dpif_execute(ofproto->backer->dpif,
5670                          key.data, key.size,
5671                          xout.odp_actions.data, xout.odp_actions.size,
5672                          packet);
5673     xlate_out_uninit(&xout);
5674
5675     if (error) {
5676         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %s (%s)",
5677                      ofproto->up.name, netdev_get_name(ofport->up.netdev),
5678                      strerror(error));
5679     }
5680
5681     ofproto->stats.tx_packets++;
5682     ofproto->stats.tx_bytes += packet->size;
5683     return error;
5684 }
5685 \f
5686 /* OpenFlow to datapath action translation. */
5687
5688 static bool may_receive(const struct ofport_dpif *, struct xlate_ctx *);
5689 static void do_xlate_actions(const struct ofpact *, size_t ofpacts_len,
5690                              struct xlate_ctx *);
5691 static void xlate_normal(struct xlate_ctx *);
5692
5693 /* Composes an ODP action for a "slow path" action for 'flow' within 'ofproto'.
5694  * The action will state 'slow' as the reason that the action is in the slow
5695  * path.  (This is purely informational: it allows a human viewing "ovs-dpctl
5696  * dump-flows" output to see why a flow is in the slow path.)
5697  *
5698  * The 'stub_size' bytes in 'stub' will be used to store the action.
5699  * 'stub_size' must be large enough for the action.
5700  *
5701  * The action and its size will be stored in '*actionsp' and '*actions_lenp',
5702  * respectively. */
5703 static void
5704 compose_slow_path(const struct ofproto_dpif *ofproto, const struct flow *flow,
5705                   enum slow_path_reason slow,
5706                   uint64_t *stub, size_t stub_size,
5707                   const struct nlattr **actionsp, size_t *actions_lenp)
5708 {
5709     union user_action_cookie cookie;
5710     struct ofpbuf buf;
5711
5712     cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
5713     cookie.slow_path.unused = 0;
5714     cookie.slow_path.reason = slow;
5715
5716     ofpbuf_use_stack(&buf, stub, stub_size);
5717     if (slow & (SLOW_CFM | SLOW_BFD | SLOW_LACP | SLOW_STP)) {
5718         uint32_t pid = dpif_port_get_pid(ofproto->backer->dpif, UINT32_MAX);
5719         odp_put_userspace_action(pid, &cookie, sizeof cookie.slow_path, &buf);
5720     } else {
5721         put_userspace_action(ofproto, &buf, flow, &cookie,
5722                              sizeof cookie.slow_path);
5723     }
5724     *actionsp = buf.data;
5725     *actions_lenp = buf.size;
5726 }
5727
5728 static size_t
5729 put_userspace_action(const struct ofproto_dpif *ofproto,
5730                      struct ofpbuf *odp_actions,
5731                      const struct flow *flow,
5732                      const union user_action_cookie *cookie,
5733                      const size_t cookie_size)
5734 {
5735     uint32_t pid;
5736
5737     pid = dpif_port_get_pid(ofproto->backer->dpif,
5738                             ofp_port_to_odp_port(ofproto, flow->in_port));
5739
5740     return odp_put_userspace_action(pid, cookie, cookie_size, odp_actions);
5741 }
5742
5743 /* Compose SAMPLE action for sFlow or IPFIX.  The given probability is
5744  * the number of packets out of UINT32_MAX to sample.  The given
5745  * cookie is passed back in the callback for each sampled packet.
5746  */
5747 static size_t
5748 compose_sample_action(const struct ofproto_dpif *ofproto,
5749                       struct ofpbuf *odp_actions,
5750                       const struct flow *flow,
5751                       const uint32_t probability,
5752                       const union user_action_cookie *cookie,
5753                       const size_t cookie_size)
5754 {
5755     size_t sample_offset, actions_offset;
5756     int cookie_offset;
5757
5758     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
5759
5760     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
5761
5762     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
5763     cookie_offset = put_userspace_action(ofproto, odp_actions, flow, cookie,
5764                                          cookie_size);
5765
5766     nl_msg_end_nested(odp_actions, actions_offset);
5767     nl_msg_end_nested(odp_actions, sample_offset);
5768     return cookie_offset;
5769 }
5770
5771 static void
5772 compose_sflow_cookie(const struct ofproto_dpif *ofproto,
5773                      ovs_be16 vlan_tci, uint32_t odp_port,
5774                      unsigned int n_outputs, union user_action_cookie *cookie)
5775 {
5776     int ifindex;
5777
5778     cookie->type = USER_ACTION_COOKIE_SFLOW;
5779     cookie->sflow.vlan_tci = vlan_tci;
5780
5781     /* See http://www.sflow.org/sflow_version_5.txt (search for "Input/output
5782      * port information") for the interpretation of cookie->output. */
5783     switch (n_outputs) {
5784     case 0:
5785         /* 0x40000000 | 256 means "packet dropped for unknown reason". */
5786         cookie->sflow.output = 0x40000000 | 256;
5787         break;
5788
5789     case 1:
5790         ifindex = dpif_sflow_odp_port_to_ifindex(ofproto->sflow, odp_port);
5791         if (ifindex) {
5792             cookie->sflow.output = ifindex;
5793             break;
5794         }
5795         /* Fall through. */
5796     default:
5797         /* 0x80000000 means "multiple output ports. */
5798         cookie->sflow.output = 0x80000000 | n_outputs;
5799         break;
5800     }
5801 }
5802
5803 /* Compose SAMPLE action for sFlow bridge sampling. */
5804 static size_t
5805 compose_sflow_action(const struct ofproto_dpif *ofproto,
5806                      struct ofpbuf *odp_actions,
5807                      const struct flow *flow,
5808                      uint32_t odp_port)
5809 {
5810     uint32_t probability;
5811     union user_action_cookie cookie;
5812
5813     if (!ofproto->sflow || flow->in_port == OFPP_NONE) {
5814         return 0;
5815     }
5816
5817     probability = dpif_sflow_get_probability(ofproto->sflow);
5818     compose_sflow_cookie(ofproto, htons(0), odp_port,
5819                          odp_port == OVSP_NONE ? 0 : 1, &cookie);
5820
5821     return compose_sample_action(ofproto, odp_actions, flow,  probability,
5822                                  &cookie, sizeof cookie.sflow);
5823 }
5824
5825 static void
5826 compose_flow_sample_cookie(uint16_t probability, uint32_t collector_set_id,
5827                            uint32_t obs_domain_id, uint32_t obs_point_id,
5828                            union user_action_cookie *cookie)
5829 {
5830     cookie->type = USER_ACTION_COOKIE_FLOW_SAMPLE;
5831     cookie->flow_sample.probability = probability;
5832     cookie->flow_sample.collector_set_id = collector_set_id;
5833     cookie->flow_sample.obs_domain_id = obs_domain_id;
5834     cookie->flow_sample.obs_point_id = obs_point_id;
5835 }
5836
5837 static void
5838 compose_ipfix_cookie(union user_action_cookie *cookie)
5839 {
5840     cookie->type = USER_ACTION_COOKIE_IPFIX;
5841 }
5842
5843 /* Compose SAMPLE action for IPFIX bridge sampling. */
5844 static void
5845 compose_ipfix_action(const struct ofproto_dpif *ofproto,
5846                      struct ofpbuf *odp_actions,
5847                      const struct flow *flow)
5848 {
5849     uint32_t probability;
5850     union user_action_cookie cookie;
5851
5852     if (!ofproto->ipfix || flow->in_port == OFPP_NONE) {
5853         return;
5854     }
5855
5856     probability = dpif_ipfix_get_bridge_exporter_probability(ofproto->ipfix);
5857     compose_ipfix_cookie(&cookie);
5858
5859     compose_sample_action(ofproto, odp_actions, flow,  probability,
5860                           &cookie, sizeof cookie.ipfix);
5861 }
5862
5863 /* SAMPLE action for sFlow must be first action in any given list of
5864  * actions.  At this point we do not have all information required to
5865  * build it. So try to build sample action as complete as possible. */
5866 static void
5867 add_sflow_action(struct xlate_ctx *ctx)
5868 {
5869     ctx->user_cookie_offset = compose_sflow_action(ctx->ofproto,
5870                                                    &ctx->xout->odp_actions,
5871                                                    &ctx->xin->flow, OVSP_NONE);
5872     ctx->sflow_odp_port = 0;
5873     ctx->sflow_n_outputs = 0;
5874 }
5875
5876 /* SAMPLE action for IPFIX must be 1st or 2nd action in any given list
5877  * of actions, eventually after the SAMPLE action for sFlow. */
5878 static void
5879 add_ipfix_action(struct xlate_ctx *ctx)
5880 {
5881     compose_ipfix_action(ctx->ofproto, &ctx->xout->odp_actions,
5882                          &ctx->xin->flow);
5883 }
5884
5885 /* Fix SAMPLE action according to data collected while composing ODP actions.
5886  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
5887  * USERSPACE action's user-cookie which is required for sflow. */
5888 static void
5889 fix_sflow_action(struct xlate_ctx *ctx)
5890 {
5891     const struct flow *base = &ctx->base_flow;
5892     union user_action_cookie *cookie;
5893
5894     if (!ctx->user_cookie_offset) {
5895         return;
5896     }
5897
5898     cookie = ofpbuf_at(&ctx->xout->odp_actions, ctx->user_cookie_offset,
5899                        sizeof cookie->sflow);
5900     ovs_assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
5901
5902     compose_sflow_cookie(ctx->ofproto, base->vlan_tci,
5903                          ctx->sflow_odp_port, ctx->sflow_n_outputs, cookie);
5904 }
5905
5906 static void
5907 compose_output_action__(struct xlate_ctx *ctx, uint16_t ofp_port,
5908                         bool check_stp)
5909 {
5910     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
5911     ovs_be16 flow_vlan_tci;
5912     uint32_t flow_skb_mark;
5913     uint8_t flow_nw_tos;
5914     struct priority_to_dscp *pdscp;
5915     uint32_t out_port, odp_port;
5916
5917     /* If 'struct flow' gets additional metadata, we'll need to zero it out
5918      * before traversing a patch port. */
5919     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 20);
5920
5921     if (!ofport) {
5922         xlate_report(ctx, "Nonexistent output port");
5923         return;
5924     } else if (ofport->up.pp.config & OFPUTIL_PC_NO_FWD) {
5925         xlate_report(ctx, "OFPPC_NO_FWD set, skipping output");
5926         return;
5927     } else if (check_stp && !stp_forward_in_state(ofport->stp_state)) {
5928         xlate_report(ctx, "STP not in forwarding state, skipping output");
5929         return;
5930     }
5931
5932     if (netdev_vport_is_patch(ofport->up.netdev)) {
5933         struct ofport_dpif *peer = ofport_get_peer(ofport);
5934         struct flow old_flow = ctx->xin->flow;
5935         const struct ofproto_dpif *peer_ofproto;
5936         enum slow_path_reason special;
5937         struct ofport_dpif *in_port;
5938
5939         if (!peer) {
5940             xlate_report(ctx, "Nonexistent patch port peer");
5941             return;
5942         }
5943
5944         peer_ofproto = ofproto_dpif_cast(peer->up.ofproto);
5945         if (peer_ofproto->backer != ctx->ofproto->backer) {
5946             xlate_report(ctx, "Patch port peer on a different datapath");
5947             return;
5948         }
5949
5950         ctx->ofproto = ofproto_dpif_cast(peer->up.ofproto);
5951         ctx->xin->flow.in_port = peer->up.ofp_port;
5952         ctx->xin->flow.metadata = htonll(0);
5953         memset(&ctx->xin->flow.tunnel, 0, sizeof ctx->xin->flow.tunnel);
5954         memset(ctx->xin->flow.regs, 0, sizeof ctx->xin->flow.regs);
5955
5956         in_port = get_ofp_port(ctx->ofproto, ctx->xin->flow.in_port);
5957         special = process_special(ctx->ofproto, &ctx->xin->flow, in_port,
5958                                   ctx->xin->packet);
5959         if (special) {
5960             ctx->xout->slow = special;
5961         } else if (!in_port || may_receive(in_port, ctx)) {
5962             if (!in_port || stp_forward_in_state(in_port->stp_state)) {
5963                 xlate_table_action(ctx, ctx->xin->flow.in_port, 0, true);
5964             } else {
5965                 /* Forwarding is disabled by STP.  Let OFPP_NORMAL and the
5966                  * learning action look at the packet, then drop it. */
5967                 struct flow old_base_flow = ctx->base_flow;
5968                 size_t old_size = ctx->xout->odp_actions.size;
5969                 xlate_table_action(ctx, ctx->xin->flow.in_port, 0, true);
5970                 ctx->base_flow = old_base_flow;
5971                 ctx->xout->odp_actions.size = old_size;
5972             }
5973         }
5974
5975         ctx->xin->flow = old_flow;
5976         ctx->ofproto = ofproto_dpif_cast(ofport->up.ofproto);
5977
5978         if (ctx->xin->resubmit_stats) {
5979             netdev_vport_inc_tx(ofport->up.netdev, ctx->xin->resubmit_stats);
5980             netdev_vport_inc_rx(peer->up.netdev, ctx->xin->resubmit_stats);
5981         }
5982
5983         return;
5984     }
5985
5986     flow_vlan_tci = ctx->xin->flow.vlan_tci;
5987     flow_skb_mark = ctx->xin->flow.skb_mark;
5988     flow_nw_tos = ctx->xin->flow.nw_tos;
5989
5990     pdscp = get_priority(ofport, ctx->xin->flow.skb_priority);
5991     if (pdscp) {
5992         ctx->xin->flow.nw_tos &= ~IP_DSCP_MASK;
5993         ctx->xin->flow.nw_tos |= pdscp->dscp;
5994     }
5995
5996     if (ofport->tnl_port) {
5997          /* Save tunnel metadata so that changes made due to
5998           * the Logical (tunnel) Port are not visible for any further
5999           * matches, while explicit set actions on tunnel metadata are.
6000           */
6001         struct flow_tnl flow_tnl = ctx->xin->flow.tunnel;
6002         odp_port = tnl_port_send(ofport->tnl_port, &ctx->xin->flow);
6003         if (odp_port == OVSP_NONE) {
6004             xlate_report(ctx, "Tunneling decided against output");
6005             goto out; /* restore flow_nw_tos */
6006         }
6007         if (ctx->xin->flow.tunnel.ip_dst == ctx->orig_tunnel_ip_dst) {
6008             xlate_report(ctx, "Not tunneling to our own address");
6009             goto out; /* restore flow_nw_tos */
6010         }
6011         if (ctx->xin->resubmit_stats) {
6012             netdev_vport_inc_tx(ofport->up.netdev, ctx->xin->resubmit_stats);
6013         }
6014         out_port = odp_port;
6015         commit_odp_tunnel_action(&ctx->xin->flow, &ctx->base_flow,
6016                                  &ctx->xout->odp_actions);
6017         ctx->xin->flow.tunnel = flow_tnl; /* Restore tunnel metadata */
6018     } else {
6019         uint16_t vlandev_port;
6020         odp_port = ofport->odp_port;
6021         vlandev_port = vsp_realdev_to_vlandev(ctx->ofproto, ofp_port,
6022                                               ctx->xin->flow.vlan_tci);
6023         if (vlandev_port == ofp_port) {
6024             out_port = odp_port;
6025         } else {
6026             out_port = ofp_port_to_odp_port(ctx->ofproto, vlandev_port);
6027             ctx->xin->flow.vlan_tci = htons(0);
6028         }
6029         ctx->xin->flow.skb_mark &= ~IPSEC_MARK;
6030     }
6031     commit_odp_actions(&ctx->xin->flow, &ctx->base_flow,
6032                        &ctx->xout->odp_actions);
6033     nl_msg_put_u32(&ctx->xout->odp_actions, OVS_ACTION_ATTR_OUTPUT, out_port);
6034
6035     ctx->sflow_odp_port = odp_port;
6036     ctx->sflow_n_outputs++;
6037     ctx->xout->nf_output_iface = ofp_port;
6038
6039     /* Restore flow */
6040     ctx->xin->flow.vlan_tci = flow_vlan_tci;
6041     ctx->xin->flow.skb_mark = flow_skb_mark;
6042  out:
6043     ctx->xin->flow.nw_tos = flow_nw_tos;
6044 }
6045
6046 static void
6047 compose_output_action(struct xlate_ctx *ctx, uint16_t ofp_port)
6048 {
6049     compose_output_action__(ctx, ofp_port, true);
6050 }
6051
6052 static void
6053 tag_the_flow(struct xlate_ctx *ctx, struct rule_dpif *rule)
6054 {
6055     struct ofproto_dpif *ofproto = ctx->ofproto;
6056     uint8_t table_id = ctx->table_id;
6057
6058     if (table_id > 0 && table_id < N_TABLES) {
6059         struct table_dpif *table = &ofproto->tables[table_id];
6060         if (table->other_table) {
6061             ctx->xout->tags |= (rule && rule->tag
6062                                 ? rule->tag
6063                                 : rule_calculate_tag(&ctx->xin->flow,
6064                                                      &table->other_table->mask,
6065                                                      table->basis));
6066         }
6067     }
6068 }
6069
6070 /* Common rule processing in one place to avoid duplicating code. */
6071 static struct rule_dpif *
6072 ctx_rule_hooks(struct xlate_ctx *ctx, struct rule_dpif *rule,
6073                bool may_packet_in)
6074 {
6075     if (ctx->xin->resubmit_hook) {
6076         ctx->xin->resubmit_hook(ctx, rule);
6077     }
6078     if (rule == NULL && may_packet_in) {
6079         /* XXX
6080          * check if table configuration flags
6081          * OFPTC_TABLE_MISS_CONTROLLER, default.
6082          * OFPTC_TABLE_MISS_CONTINUE,
6083          * OFPTC_TABLE_MISS_DROP
6084          * When OF1.0, OFPTC_TABLE_MISS_CONTINUE is used. What to do?
6085          */
6086         rule = rule_dpif_miss_rule(ctx->ofproto, &ctx->xin->flow);
6087     }
6088     if (rule && ctx->xin->resubmit_stats) {
6089         rule_credit_stats(rule, ctx->xin->resubmit_stats);
6090     }
6091     return rule;
6092 }
6093
6094 static void
6095 xlate_table_action(struct xlate_ctx *ctx,
6096                    uint16_t in_port, uint8_t table_id, bool may_packet_in)
6097 {
6098     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
6099         struct rule_dpif *rule;
6100         uint16_t old_in_port = ctx->xin->flow.in_port;
6101         uint8_t old_table_id = ctx->table_id;
6102
6103         ctx->table_id = table_id;
6104
6105         /* Look up a flow with 'in_port' as the input port. */
6106         ctx->xin->flow.in_port = in_port;
6107         rule = rule_dpif_lookup__(ctx->ofproto, &ctx->xin->flow, table_id);
6108
6109         tag_the_flow(ctx, rule);
6110
6111         /* Restore the original input port.  Otherwise OFPP_NORMAL and
6112          * OFPP_IN_PORT will have surprising behavior. */
6113         ctx->xin->flow.in_port = old_in_port;
6114
6115         rule = ctx_rule_hooks(ctx, rule, may_packet_in);
6116
6117         if (rule) {
6118             struct rule_dpif *old_rule = ctx->rule;
6119
6120             ctx->recurse++;
6121             ctx->rule = rule;
6122             do_xlate_actions(rule->up.ofpacts, rule->up.ofpacts_len, ctx);
6123             ctx->rule = old_rule;
6124             ctx->recurse--;
6125         }
6126
6127         ctx->table_id = old_table_id;
6128     } else {
6129         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
6130
6131         VLOG_ERR_RL(&recurse_rl, "resubmit actions recursed over %d times",
6132                     MAX_RESUBMIT_RECURSION);
6133         ctx->max_resubmit_trigger = true;
6134     }
6135 }
6136
6137 static void
6138 xlate_ofpact_resubmit(struct xlate_ctx *ctx,
6139                       const struct ofpact_resubmit *resubmit)
6140 {
6141     uint16_t in_port;
6142     uint8_t table_id;
6143
6144     in_port = resubmit->in_port;
6145     if (in_port == OFPP_IN_PORT) {
6146         in_port = ctx->xin->flow.in_port;
6147     }
6148
6149     table_id = resubmit->table_id;
6150     if (table_id == 255) {
6151         table_id = ctx->table_id;
6152     }
6153
6154     xlate_table_action(ctx, in_port, table_id, false);
6155 }
6156
6157 static void
6158 flood_packets(struct xlate_ctx *ctx, bool all)
6159 {
6160     struct ofport_dpif *ofport;
6161
6162     HMAP_FOR_EACH (ofport, up.hmap_node, &ctx->ofproto->up.ports) {
6163         uint16_t ofp_port = ofport->up.ofp_port;
6164
6165         if (ofp_port == ctx->xin->flow.in_port) {
6166             continue;
6167         }
6168
6169         if (all) {
6170             compose_output_action__(ctx, ofp_port, false);
6171         } else if (!(ofport->up.pp.config & OFPUTIL_PC_NO_FLOOD)) {
6172             compose_output_action(ctx, ofp_port);
6173         }
6174     }
6175
6176     ctx->xout->nf_output_iface = NF_OUT_FLOOD;
6177 }
6178
6179 static void
6180 execute_controller_action(struct xlate_ctx *ctx, int len,
6181                           enum ofp_packet_in_reason reason,
6182                           uint16_t controller_id)
6183 {
6184     struct ofputil_packet_in pin;
6185     struct ofpbuf *packet;
6186     struct flow key;
6187
6188     ovs_assert(!ctx->xout->slow || ctx->xout->slow == SLOW_CONTROLLER);
6189     ctx->xout->slow = SLOW_CONTROLLER;
6190     if (!ctx->xin->packet) {
6191         return;
6192     }
6193
6194     packet = ofpbuf_clone(ctx->xin->packet);
6195
6196     key.skb_priority = 0;
6197     key.skb_mark = 0;
6198     memset(&key.tunnel, 0, sizeof key.tunnel);
6199
6200     commit_odp_actions(&ctx->xin->flow, &ctx->base_flow,
6201                        &ctx->xout->odp_actions);
6202
6203     odp_execute_actions(NULL, packet, &key, ctx->xout->odp_actions.data,
6204                         ctx->xout->odp_actions.size, NULL, NULL);
6205
6206     pin.packet = packet->data;
6207     pin.packet_len = packet->size;
6208     pin.reason = reason;
6209     pin.controller_id = controller_id;
6210     pin.table_id = ctx->table_id;
6211     pin.cookie = ctx->rule ? ctx->rule->up.flow_cookie : 0;
6212
6213     pin.send_len = len;
6214     flow_get_metadata(&ctx->xin->flow, &pin.fmd);
6215
6216     connmgr_send_packet_in(ctx->ofproto->up.connmgr, &pin);
6217     ofpbuf_delete(packet);
6218 }
6219
6220 static void
6221 execute_mpls_push_action(struct xlate_ctx *ctx, ovs_be16 eth_type)
6222 {
6223     ovs_assert(eth_type_mpls(eth_type));
6224
6225     if (ctx->base_flow.mpls_depth) {
6226         ctx->xin->flow.mpls_lse &= ~htonl(MPLS_BOS_MASK);
6227         ctx->xin->flow.mpls_depth++;
6228     } else {
6229         ovs_be32 label;
6230         uint8_t tc, ttl;
6231
6232         if (ctx->xin->flow.dl_type == htons(ETH_TYPE_IPV6)) {
6233             label = htonl(0x2); /* IPV6 Explicit Null. */
6234         } else {
6235             label = htonl(0x0); /* IPV4 Explicit Null. */
6236         }
6237         tc = (ctx->xin->flow.nw_tos & IP_DSCP_MASK) >> 2;
6238         ttl = ctx->xin->flow.nw_ttl ? ctx->xin->flow.nw_ttl : 0x40;
6239         ctx->xin->flow.mpls_lse = set_mpls_lse_values(ttl, tc, 1, label);
6240         ctx->xin->flow.mpls_depth = 1;
6241     }
6242     ctx->xin->flow.dl_type = eth_type;
6243 }
6244
6245 static void
6246 execute_mpls_pop_action(struct xlate_ctx *ctx, ovs_be16 eth_type)
6247 {
6248     ovs_assert(eth_type_mpls(ctx->xin->flow.dl_type));
6249     ovs_assert(!eth_type_mpls(eth_type));
6250
6251     if (ctx->xin->flow.mpls_depth) {
6252         ctx->xin->flow.mpls_depth--;
6253         ctx->xin->flow.mpls_lse = htonl(0);
6254         if (!ctx->xin->flow.mpls_depth) {
6255             ctx->xin->flow.dl_type = eth_type;
6256         }
6257     }
6258 }
6259
6260 static bool
6261 compose_dec_ttl(struct xlate_ctx *ctx, struct ofpact_cnt_ids *ids)
6262 {
6263     if (ctx->xin->flow.dl_type != htons(ETH_TYPE_IP) &&
6264         ctx->xin->flow.dl_type != htons(ETH_TYPE_IPV6)) {
6265         return false;
6266     }
6267
6268     if (ctx->xin->flow.nw_ttl > 1) {
6269         ctx->xin->flow.nw_ttl--;
6270         return false;
6271     } else {
6272         size_t i;
6273
6274         for (i = 0; i < ids->n_controllers; i++) {
6275             execute_controller_action(ctx, UINT16_MAX, OFPR_INVALID_TTL,
6276                                       ids->cnt_ids[i]);
6277         }
6278
6279         /* Stop processing for current table. */
6280         return true;
6281     }
6282 }
6283
6284 static bool
6285 execute_set_mpls_ttl_action(struct xlate_ctx *ctx, uint8_t ttl)
6286 {
6287     if (!eth_type_mpls(ctx->xin->flow.dl_type)) {
6288         return true;
6289     }
6290
6291     set_mpls_lse_ttl(&ctx->xin->flow.mpls_lse, ttl);
6292     return false;
6293 }
6294
6295 static bool
6296 execute_dec_mpls_ttl_action(struct xlate_ctx *ctx)
6297 {
6298     uint8_t ttl = mpls_lse_to_ttl(ctx->xin->flow.mpls_lse);
6299
6300     if (!eth_type_mpls(ctx->xin->flow.dl_type)) {
6301         return false;
6302     }
6303
6304     if (ttl > 1) {
6305         ttl--;
6306         set_mpls_lse_ttl(&ctx->xin->flow.mpls_lse, ttl);
6307         return false;
6308     } else {
6309         execute_controller_action(ctx, UINT16_MAX, OFPR_INVALID_TTL, 0);
6310
6311         /* Stop processing for current table. */
6312         return true;
6313     }
6314 }
6315
6316 static void
6317 xlate_output_action(struct xlate_ctx *ctx,
6318                     uint16_t port, uint16_t max_len, bool may_packet_in)
6319 {
6320     uint16_t prev_nf_output_iface = ctx->xout->nf_output_iface;
6321
6322     ctx->xout->nf_output_iface = NF_OUT_DROP;
6323
6324     switch (port) {
6325     case OFPP_IN_PORT:
6326         compose_output_action(ctx, ctx->xin->flow.in_port);
6327         break;
6328     case OFPP_TABLE:
6329         xlate_table_action(ctx, ctx->xin->flow.in_port, 0, may_packet_in);
6330         break;
6331     case OFPP_NORMAL:
6332         xlate_normal(ctx);
6333         break;
6334     case OFPP_FLOOD:
6335         flood_packets(ctx,  false);
6336         break;
6337     case OFPP_ALL:
6338         flood_packets(ctx, true);
6339         break;
6340     case OFPP_CONTROLLER:
6341         execute_controller_action(ctx, max_len, OFPR_ACTION, 0);
6342         break;
6343     case OFPP_NONE:
6344         break;
6345     case OFPP_LOCAL:
6346     default:
6347         if (port != ctx->xin->flow.in_port) {
6348             compose_output_action(ctx, port);
6349         } else {
6350             xlate_report(ctx, "skipping output to input port");
6351         }
6352         break;
6353     }
6354
6355     if (prev_nf_output_iface == NF_OUT_FLOOD) {
6356         ctx->xout->nf_output_iface = NF_OUT_FLOOD;
6357     } else if (ctx->xout->nf_output_iface == NF_OUT_DROP) {
6358         ctx->xout->nf_output_iface = prev_nf_output_iface;
6359     } else if (prev_nf_output_iface != NF_OUT_DROP &&
6360                ctx->xout->nf_output_iface != NF_OUT_FLOOD) {
6361         ctx->xout->nf_output_iface = NF_OUT_MULTI;
6362     }
6363 }
6364
6365 static void
6366 xlate_output_reg_action(struct xlate_ctx *ctx,
6367                         const struct ofpact_output_reg *or)
6368 {
6369     uint64_t port = mf_get_subfield(&or->src, &ctx->xin->flow);
6370     if (port <= UINT16_MAX) {
6371         xlate_output_action(ctx, port, or->max_len, false);
6372     }
6373 }
6374
6375 static void
6376 xlate_enqueue_action(struct xlate_ctx *ctx,
6377                      const struct ofpact_enqueue *enqueue)
6378 {
6379     uint16_t ofp_port = enqueue->port;
6380     uint32_t queue_id = enqueue->queue;
6381     uint32_t flow_priority, priority;
6382     int error;
6383
6384     /* Translate queue to priority. */
6385     error = dpif_queue_to_priority(ctx->ofproto->backer->dpif,
6386                                    queue_id, &priority);
6387     if (error) {
6388         /* Fall back to ordinary output action. */
6389         xlate_output_action(ctx, enqueue->port, 0, false);
6390         return;
6391     }
6392
6393     /* Check output port. */
6394     if (ofp_port == OFPP_IN_PORT) {
6395         ofp_port = ctx->xin->flow.in_port;
6396     } else if (ofp_port == ctx->xin->flow.in_port) {
6397         return;
6398     }
6399
6400     /* Add datapath actions. */
6401     flow_priority = ctx->xin->flow.skb_priority;
6402     ctx->xin->flow.skb_priority = priority;
6403     compose_output_action(ctx, ofp_port);
6404     ctx->xin->flow.skb_priority = flow_priority;
6405
6406     /* Update NetFlow output port. */
6407     if (ctx->xout->nf_output_iface == NF_OUT_DROP) {
6408         ctx->xout->nf_output_iface = ofp_port;
6409     } else if (ctx->xout->nf_output_iface != NF_OUT_FLOOD) {
6410         ctx->xout->nf_output_iface = NF_OUT_MULTI;
6411     }
6412 }
6413
6414 static void
6415 xlate_set_queue_action(struct xlate_ctx *ctx, uint32_t queue_id)
6416 {
6417     uint32_t skb_priority;
6418
6419     if (!dpif_queue_to_priority(ctx->ofproto->backer->dpif,
6420                                 queue_id, &skb_priority)) {
6421         ctx->xin->flow.skb_priority = skb_priority;
6422     } else {
6423         /* Couldn't translate queue to a priority.  Nothing to do.  A warning
6424          * has already been logged. */
6425     }
6426 }
6427
6428 static bool
6429 slave_enabled_cb(uint16_t ofp_port, void *ofproto_)
6430 {
6431     struct ofproto_dpif *ofproto = ofproto_;
6432     struct ofport_dpif *port;
6433
6434     switch (ofp_port) {
6435     case OFPP_IN_PORT:
6436     case OFPP_TABLE:
6437     case OFPP_NORMAL:
6438     case OFPP_FLOOD:
6439     case OFPP_ALL:
6440     case OFPP_NONE:
6441         return true;
6442     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
6443         return false;
6444     default:
6445         port = get_ofp_port(ofproto, ofp_port);
6446         return port ? port->may_enable : false;
6447     }
6448 }
6449
6450 static void
6451 xlate_bundle_action(struct xlate_ctx *ctx,
6452                     const struct ofpact_bundle *bundle)
6453 {
6454     uint16_t port;
6455
6456     port = bundle_execute(bundle, &ctx->xin->flow, slave_enabled_cb,
6457                           ctx->ofproto);
6458     if (bundle->dst.field) {
6459         nxm_reg_load(&bundle->dst, port, &ctx->xin->flow);
6460     } else {
6461         xlate_output_action(ctx, port, 0, false);
6462     }
6463 }
6464
6465 static void
6466 xlate_learn_action(struct xlate_ctx *ctx,
6467                    const struct ofpact_learn *learn)
6468 {
6469     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
6470     struct ofputil_flow_mod fm;
6471     uint64_t ofpacts_stub[1024 / 8];
6472     struct ofpbuf ofpacts;
6473     int error;
6474
6475     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
6476     learn_execute(learn, &ctx->xin->flow, &fm, &ofpacts);
6477
6478     error = ofproto_flow_mod(&ctx->ofproto->up, &fm);
6479     if (error && !VLOG_DROP_WARN(&rl)) {
6480         VLOG_WARN("learning action failed to modify flow table (%s)",
6481                   ofperr_get_name(error));
6482     }
6483
6484     ofpbuf_uninit(&ofpacts);
6485 }
6486
6487 /* Reduces '*timeout' to no more than 'max'.  A value of zero in either case
6488  * means "infinite". */
6489 static void
6490 reduce_timeout(uint16_t max, uint16_t *timeout)
6491 {
6492     if (max && (!*timeout || *timeout > max)) {
6493         *timeout = max;
6494     }
6495 }
6496
6497 static void
6498 xlate_fin_timeout(struct xlate_ctx *ctx,
6499                   const struct ofpact_fin_timeout *oft)
6500 {
6501     if (ctx->xin->tcp_flags & (TCP_FIN | TCP_RST) && ctx->rule) {
6502         struct rule_dpif *rule = ctx->rule;
6503
6504         reduce_timeout(oft->fin_idle_timeout, &rule->up.idle_timeout);
6505         reduce_timeout(oft->fin_hard_timeout, &rule->up.hard_timeout);
6506     }
6507 }
6508
6509 static void
6510 xlate_sample_action(struct xlate_ctx *ctx,
6511                     const struct ofpact_sample *os)
6512 {
6513   union user_action_cookie cookie;
6514   /* Scale the probability from 16-bit to 32-bit while representing
6515    * the same percentage. */
6516   uint32_t probability = (os->probability << 16) | os->probability;
6517
6518   commit_odp_actions(&ctx->xin->flow, &ctx->base_flow,
6519                      &ctx->xout->odp_actions);
6520
6521   compose_flow_sample_cookie(os->probability, os->collector_set_id,
6522                              os->obs_domain_id, os->obs_point_id, &cookie);
6523   compose_sample_action(ctx->ofproto, &ctx->xout->odp_actions, &ctx->xin->flow,
6524                         probability, &cookie, sizeof cookie.flow_sample);
6525 }
6526
6527 static bool
6528 may_receive(const struct ofport_dpif *port, struct xlate_ctx *ctx)
6529 {
6530     if (port->up.pp.config & (eth_addr_equals(ctx->xin->flow.dl_dst,
6531                                               eth_addr_stp)
6532                               ? OFPUTIL_PC_NO_RECV_STP
6533                               : OFPUTIL_PC_NO_RECV)) {
6534         return false;
6535     }
6536
6537     /* Only drop packets here if both forwarding and learning are
6538      * disabled.  If just learning is enabled, we need to have
6539      * OFPP_NORMAL and the learning action have a look at the packet
6540      * before we can drop it. */
6541     if (!stp_forward_in_state(port->stp_state)
6542             && !stp_learn_in_state(port->stp_state)) {
6543         return false;
6544     }
6545
6546     return true;
6547 }
6548
6549 static bool
6550 tunnel_ecn_ok(struct xlate_ctx *ctx)
6551 {
6552     if (is_ip_any(&ctx->base_flow)
6553         && (ctx->xin->flow.tunnel.ip_tos & IP_ECN_MASK) == IP_ECN_CE) {
6554         if ((ctx->base_flow.nw_tos & IP_ECN_MASK) == IP_ECN_NOT_ECT) {
6555             VLOG_WARN_RL(&rl, "dropping tunnel packet marked ECN CE"
6556                          " but is not ECN capable");
6557             return false;
6558         } else {
6559             /* Set the ECN CE value in the tunneled packet. */
6560             ctx->xin->flow.nw_tos |= IP_ECN_CE;
6561         }
6562     }
6563
6564     return true;
6565 }
6566
6567 static void
6568 do_xlate_actions(const struct ofpact *ofpacts, size_t ofpacts_len,
6569                  struct xlate_ctx *ctx)
6570 {
6571     bool was_evictable = true;
6572     const struct ofpact *a;
6573
6574     if (ctx->rule) {
6575         /* Don't let the rule we're working on get evicted underneath us. */
6576         was_evictable = ctx->rule->up.evictable;
6577         ctx->rule->up.evictable = false;
6578     }
6579
6580  do_xlate_actions_again:
6581     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6582         struct ofpact_controller *controller;
6583         const struct ofpact_metadata *metadata;
6584
6585         if (ctx->exit) {
6586             break;
6587         }
6588
6589         switch (a->type) {
6590         case OFPACT_OUTPUT:
6591             xlate_output_action(ctx, ofpact_get_OUTPUT(a)->port,
6592                                 ofpact_get_OUTPUT(a)->max_len, true);
6593             break;
6594
6595         case OFPACT_CONTROLLER:
6596             controller = ofpact_get_CONTROLLER(a);
6597             execute_controller_action(ctx, controller->max_len,
6598                                       controller->reason,
6599                                       controller->controller_id);
6600             break;
6601
6602         case OFPACT_ENQUEUE:
6603             xlate_enqueue_action(ctx, ofpact_get_ENQUEUE(a));
6604             break;
6605
6606         case OFPACT_SET_VLAN_VID:
6607             ctx->xin->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
6608             ctx->xin->flow.vlan_tci |=
6609                 (htons(ofpact_get_SET_VLAN_VID(a)->vlan_vid)
6610                  | htons(VLAN_CFI));
6611             break;
6612
6613         case OFPACT_SET_VLAN_PCP:
6614             ctx->xin->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
6615             ctx->xin->flow.vlan_tci |=
6616                 htons((ofpact_get_SET_VLAN_PCP(a)->vlan_pcp << VLAN_PCP_SHIFT)
6617                       | VLAN_CFI);
6618             break;
6619
6620         case OFPACT_STRIP_VLAN:
6621             ctx->xin->flow.vlan_tci = htons(0);
6622             break;
6623
6624         case OFPACT_PUSH_VLAN:
6625             /* XXX 802.1AD(QinQ) */
6626             ctx->xin->flow.vlan_tci = htons(VLAN_CFI);
6627             break;
6628
6629         case OFPACT_SET_ETH_SRC:
6630             memcpy(ctx->xin->flow.dl_src, ofpact_get_SET_ETH_SRC(a)->mac,
6631                    ETH_ADDR_LEN);
6632             break;
6633
6634         case OFPACT_SET_ETH_DST:
6635             memcpy(ctx->xin->flow.dl_dst, ofpact_get_SET_ETH_DST(a)->mac,
6636                    ETH_ADDR_LEN);
6637             break;
6638
6639         case OFPACT_SET_IPV4_SRC:
6640             if (ctx->xin->flow.dl_type == htons(ETH_TYPE_IP)) {
6641                 ctx->xin->flow.nw_src = ofpact_get_SET_IPV4_SRC(a)->ipv4;
6642             }
6643             break;
6644
6645         case OFPACT_SET_IPV4_DST:
6646             if (ctx->xin->flow.dl_type == htons(ETH_TYPE_IP)) {
6647                 ctx->xin->flow.nw_dst = ofpact_get_SET_IPV4_DST(a)->ipv4;
6648             }
6649             break;
6650
6651         case OFPACT_SET_IPV4_DSCP:
6652             /* OpenFlow 1.0 only supports IPv4. */
6653             if (ctx->xin->flow.dl_type == htons(ETH_TYPE_IP)) {
6654                 ctx->xin->flow.nw_tos &= ~IP_DSCP_MASK;
6655                 ctx->xin->flow.nw_tos |= ofpact_get_SET_IPV4_DSCP(a)->dscp;
6656             }
6657             break;
6658
6659         case OFPACT_SET_L4_SRC_PORT:
6660             if (is_ip_any(&ctx->xin->flow)) {
6661                 ctx->xin->flow.tp_src =
6662                     htons(ofpact_get_SET_L4_SRC_PORT(a)->port);
6663             }
6664             break;
6665
6666         case OFPACT_SET_L4_DST_PORT:
6667             if (is_ip_any(&ctx->xin->flow)) {
6668                 ctx->xin->flow.tp_dst =
6669                     htons(ofpact_get_SET_L4_DST_PORT(a)->port);
6670             }
6671             break;
6672
6673         case OFPACT_RESUBMIT:
6674             xlate_ofpact_resubmit(ctx, ofpact_get_RESUBMIT(a));
6675             break;
6676
6677         case OFPACT_SET_TUNNEL:
6678             ctx->xin->flow.tunnel.tun_id =
6679                 htonll(ofpact_get_SET_TUNNEL(a)->tun_id);
6680             break;
6681
6682         case OFPACT_SET_QUEUE:
6683             xlate_set_queue_action(ctx, ofpact_get_SET_QUEUE(a)->queue_id);
6684             break;
6685
6686         case OFPACT_POP_QUEUE:
6687             ctx->xin->flow.skb_priority = ctx->orig_skb_priority;
6688             break;
6689
6690         case OFPACT_REG_MOVE:
6691             nxm_execute_reg_move(ofpact_get_REG_MOVE(a), &ctx->xin->flow);
6692             break;
6693
6694         case OFPACT_REG_LOAD:
6695             nxm_execute_reg_load(ofpact_get_REG_LOAD(a), &ctx->xin->flow);
6696             break;
6697
6698         case OFPACT_STACK_PUSH:
6699             nxm_execute_stack_push(ofpact_get_STACK_PUSH(a), &ctx->xin->flow,
6700                                    &ctx->stack);
6701             break;
6702
6703         case OFPACT_STACK_POP:
6704             nxm_execute_stack_pop(ofpact_get_STACK_POP(a), &ctx->xin->flow,
6705                                   &ctx->stack);
6706             break;
6707
6708         case OFPACT_PUSH_MPLS:
6709             execute_mpls_push_action(ctx, ofpact_get_PUSH_MPLS(a)->ethertype);
6710             break;
6711
6712         case OFPACT_POP_MPLS:
6713             execute_mpls_pop_action(ctx, ofpact_get_POP_MPLS(a)->ethertype);
6714             break;
6715
6716         case OFPACT_SET_MPLS_TTL:
6717             if (execute_set_mpls_ttl_action(ctx,
6718                                             ofpact_get_SET_MPLS_TTL(a)->ttl)) {
6719                 goto out;
6720             }
6721             break;
6722
6723         case OFPACT_DEC_MPLS_TTL:
6724             if (execute_dec_mpls_ttl_action(ctx)) {
6725                 goto out;
6726             }
6727             break;
6728
6729         case OFPACT_DEC_TTL:
6730             if (compose_dec_ttl(ctx, ofpact_get_DEC_TTL(a))) {
6731                 goto out;
6732             }
6733             break;
6734
6735         case OFPACT_NOTE:
6736             /* Nothing to do. */
6737             break;
6738
6739         case OFPACT_MULTIPATH:
6740             multipath_execute(ofpact_get_MULTIPATH(a), &ctx->xin->flow);
6741             break;
6742
6743         case OFPACT_BUNDLE:
6744             ctx->ofproto->has_bundle_action = true;
6745             xlate_bundle_action(ctx, ofpact_get_BUNDLE(a));
6746             break;
6747
6748         case OFPACT_OUTPUT_REG:
6749             xlate_output_reg_action(ctx, ofpact_get_OUTPUT_REG(a));
6750             break;
6751
6752         case OFPACT_LEARN:
6753             ctx->xout->has_learn = true;
6754             if (ctx->xin->may_learn) {
6755                 xlate_learn_action(ctx, ofpact_get_LEARN(a));
6756             }
6757             break;
6758
6759         case OFPACT_EXIT:
6760             ctx->exit = true;
6761             break;
6762
6763         case OFPACT_FIN_TIMEOUT:
6764             ctx->xout->has_fin_timeout = true;
6765             xlate_fin_timeout(ctx, ofpact_get_FIN_TIMEOUT(a));
6766             break;
6767
6768         case OFPACT_CLEAR_ACTIONS:
6769             /* XXX
6770              * Nothing to do because writa-actions is not supported for now.
6771              * When writa-actions is supported, clear-actions also must
6772              * be supported at the same time.
6773              */
6774             break;
6775
6776         case OFPACT_WRITE_METADATA:
6777             metadata = ofpact_get_WRITE_METADATA(a);
6778             ctx->xin->flow.metadata &= ~metadata->mask;
6779             ctx->xin->flow.metadata |= metadata->metadata & metadata->mask;
6780             break;
6781
6782         case OFPACT_GOTO_TABLE: {
6783             /* It is assumed that goto-table is the last action. */
6784             struct ofpact_goto_table *ogt = ofpact_get_GOTO_TABLE(a);
6785             struct rule_dpif *rule;
6786
6787             ovs_assert(ctx->table_id < ogt->table_id);
6788
6789             ctx->table_id = ogt->table_id;
6790
6791             /* Look up a flow from the new table. */
6792             rule = rule_dpif_lookup__(ctx->ofproto, &ctx->xin->flow, ctx->table_id);
6793
6794             tag_the_flow(ctx, rule);
6795
6796             rule = ctx_rule_hooks(ctx, rule, true);
6797
6798             if (rule) {
6799                 if (ctx->rule) {
6800                     ctx->rule->up.evictable = was_evictable;
6801                 }
6802                 ctx->rule = rule;
6803                 was_evictable = rule->up.evictable;
6804                 rule->up.evictable = false;
6805
6806                 /* Tail recursion removal. */
6807                 ofpacts = rule->up.ofpacts;
6808                 ofpacts_len = rule->up.ofpacts_len;
6809                 goto do_xlate_actions_again;
6810             }
6811             break;
6812         }
6813
6814         case OFPACT_SAMPLE:
6815             xlate_sample_action(ctx, ofpact_get_SAMPLE(a));
6816             break;
6817         }
6818     }
6819
6820 out:
6821     if (ctx->rule) {
6822         ctx->rule->up.evictable = was_evictable;
6823     }
6824 }
6825
6826 static void
6827 xlate_in_init(struct xlate_in *xin, struct ofproto_dpif *ofproto,
6828               const struct flow *flow,
6829               const struct initial_vals *initial_vals,
6830               struct rule_dpif *rule, uint8_t tcp_flags,
6831               const struct ofpbuf *packet)
6832 {
6833     xin->ofproto = ofproto;
6834     xin->flow = *flow;
6835     xin->packet = packet;
6836     xin->may_learn = packet != NULL;
6837     xin->rule = rule;
6838     xin->ofpacts = NULL;
6839     xin->ofpacts_len = 0;
6840     xin->tcp_flags = tcp_flags;
6841     xin->resubmit_hook = NULL;
6842     xin->report_hook = NULL;
6843     xin->resubmit_stats = NULL;
6844
6845     if (initial_vals) {
6846         xin->initial_vals = *initial_vals;
6847     } else {
6848         xin->initial_vals.vlan_tci = xin->flow.vlan_tci;
6849     }
6850 }
6851
6852 static void
6853 xlate_out_uninit(struct xlate_out *xout)
6854 {
6855     if (xout) {
6856         ofpbuf_uninit(&xout->odp_actions);
6857     }
6858 }
6859
6860 /* Translates the 'ofpacts_len' bytes of "struct ofpacts" starting at 'ofpacts'
6861  * into datapath actions in 'odp_actions', using 'ctx'. */
6862 static void
6863 xlate_actions(struct xlate_in *xin, struct xlate_out *xout)
6864 {
6865     /* Normally false.  Set to true if we ever hit MAX_RESUBMIT_RECURSION, so
6866      * that in the future we always keep a copy of the original flow for
6867      * tracing purposes. */
6868     static bool hit_resubmit_limit;
6869
6870     enum slow_path_reason special;
6871     const struct ofpact *ofpacts;
6872     struct ofport_dpif *in_port;
6873     struct flow orig_flow;
6874     struct xlate_ctx ctx;
6875     size_t ofpacts_len;
6876
6877     COVERAGE_INC(ofproto_dpif_xlate);
6878
6879     /* Flow initialization rules:
6880      * - 'base_flow' must match the kernel's view of the packet at the
6881      *   time that action processing starts.  'flow' represents any
6882      *   transformations we wish to make through actions.
6883      * - By default 'base_flow' and 'flow' are the same since the input
6884      *   packet matches the output before any actions are applied.
6885      * - When using VLAN splinters, 'base_flow''s VLAN is set to the value
6886      *   of the received packet as seen by the kernel.  If we later output
6887      *   to another device without any modifications this will cause us to
6888      *   insert a new tag since the original one was stripped off by the
6889      *   VLAN device.
6890      * - Tunnel metadata as received is retained in 'flow'. This allows
6891      *   tunnel metadata matching also in later tables.
6892      *   Since a kernel action for setting the tunnel metadata will only be
6893      *   generated with actual tunnel output, changing the tunnel metadata
6894      *   values in 'flow' (such as tun_id) will only have effect with a later
6895      *   tunnel output action.
6896      * - Tunnel 'base_flow' is completely cleared since that is what the
6897      *   kernel does.  If we wish to maintain the original values an action
6898      *   needs to be generated. */
6899
6900     ctx.xin = xin;
6901     ctx.xout = xout;
6902
6903     ctx.ofproto = xin->ofproto;
6904     ctx.rule = xin->rule;
6905
6906     ctx.base_flow = ctx.xin->flow;
6907     ctx.base_flow.vlan_tci = xin->initial_vals.vlan_tci;
6908     memset(&ctx.base_flow.tunnel, 0, sizeof ctx.base_flow.tunnel);
6909     ctx.orig_tunnel_ip_dst = ctx.xin->flow.tunnel.ip_dst;
6910
6911     ctx.xout->tags = 0;
6912     ctx.xout->slow = 0;
6913     ctx.xout->has_learn = false;
6914     ctx.xout->has_normal = false;
6915     ctx.xout->has_fin_timeout = false;
6916     ctx.xout->nf_output_iface = NF_OUT_DROP;
6917     ctx.xout->mirrors = 0;
6918
6919     ofpbuf_use_stub(&ctx.xout->odp_actions, ctx.xout->odp_actions_stub,
6920                     sizeof ctx.xout->odp_actions_stub);
6921     ofpbuf_reserve(&ctx.xout->odp_actions, NL_A_U32_SIZE);
6922
6923     ctx.recurse = 0;
6924     ctx.max_resubmit_trigger = false;
6925     ctx.orig_skb_priority = ctx.xin->flow.skb_priority;
6926     ctx.table_id = 0;
6927     ctx.exit = false;
6928
6929     if (xin->ofpacts) {
6930         ofpacts = xin->ofpacts;
6931         ofpacts_len = xin->ofpacts_len;
6932     } else if (xin->rule) {
6933         ofpacts = xin->rule->up.ofpacts;
6934         ofpacts_len = xin->rule->up.ofpacts_len;
6935     } else {
6936         NOT_REACHED();
6937     }
6938
6939     ofpbuf_use_stub(&ctx.stack, ctx.init_stack, sizeof ctx.init_stack);
6940
6941     if (ctx.ofproto->has_mirrors || hit_resubmit_limit) {
6942         /* Do this conditionally because the copy is expensive enough that it
6943          * shows up in profiles. */
6944         orig_flow = ctx.xin->flow;
6945     }
6946
6947     if (ctx.xin->flow.nw_frag & FLOW_NW_FRAG_ANY) {
6948         switch (ctx.ofproto->up.frag_handling) {
6949         case OFPC_FRAG_NORMAL:
6950             /* We must pretend that transport ports are unavailable. */
6951             ctx.xin->flow.tp_src = ctx.base_flow.tp_src = htons(0);
6952             ctx.xin->flow.tp_dst = ctx.base_flow.tp_dst = htons(0);
6953             break;
6954
6955         case OFPC_FRAG_DROP:
6956             return;
6957
6958         case OFPC_FRAG_REASM:
6959             NOT_REACHED();
6960
6961         case OFPC_FRAG_NX_MATCH:
6962             /* Nothing to do. */
6963             break;
6964
6965         case OFPC_INVALID_TTL_TO_CONTROLLER:
6966             NOT_REACHED();
6967         }
6968     }
6969
6970     in_port = get_ofp_port(ctx.ofproto, ctx.xin->flow.in_port);
6971     special = process_special(ctx.ofproto, &ctx.xin->flow, in_port,
6972                               ctx.xin->packet);
6973     if (special) {
6974         ctx.xout->slow = special;
6975     } else {
6976         static struct vlog_rate_limit trace_rl = VLOG_RATE_LIMIT_INIT(1, 1);
6977         struct initial_vals initial_vals;
6978         size_t sample_actions_len;
6979         uint32_t local_odp_port;
6980
6981         initial_vals.vlan_tci = ctx.base_flow.vlan_tci;
6982
6983         add_sflow_action(&ctx);
6984         add_ipfix_action(&ctx);
6985         sample_actions_len = ctx.xout->odp_actions.size;
6986
6987         if (tunnel_ecn_ok(&ctx) && (!in_port || may_receive(in_port, &ctx))) {
6988             do_xlate_actions(ofpacts, ofpacts_len, &ctx);
6989
6990             /* We've let OFPP_NORMAL and the learning action look at the
6991              * packet, so drop it now if forwarding is disabled. */
6992             if (in_port && !stp_forward_in_state(in_port->stp_state)) {
6993                 ctx.xout->odp_actions.size = sample_actions_len;
6994             }
6995         }
6996
6997         if (ctx.max_resubmit_trigger && !ctx.xin->resubmit_hook) {
6998             if (!hit_resubmit_limit) {
6999                 /* We didn't record the original flow.  Make sure we do from
7000                  * now on. */
7001                 hit_resubmit_limit = true;
7002             } else if (!VLOG_DROP_ERR(&trace_rl)) {
7003                 struct ds ds = DS_EMPTY_INITIALIZER;
7004
7005                 ofproto_trace(ctx.ofproto, &orig_flow, ctx.xin->packet,
7006                               &initial_vals, &ds);
7007                 VLOG_ERR("Trace triggered by excessive resubmit "
7008                          "recursion:\n%s", ds_cstr(&ds));
7009                 ds_destroy(&ds);
7010             }
7011         }
7012
7013         local_odp_port = ofp_port_to_odp_port(ctx.ofproto, OFPP_LOCAL);
7014         if (!connmgr_must_output_local(ctx.ofproto->up.connmgr, &ctx.xin->flow,
7015                                        local_odp_port,
7016                                        ctx.xout->odp_actions.data,
7017                                        ctx.xout->odp_actions.size)) {
7018             compose_output_action(&ctx, OFPP_LOCAL);
7019         }
7020         if (ctx.ofproto->has_mirrors) {
7021             add_mirror_actions(&ctx, &orig_flow);
7022         }
7023         fix_sflow_action(&ctx);
7024     }
7025
7026     ofpbuf_uninit(&ctx.stack);
7027 }
7028
7029 /* Translates the 'ofpacts_len' bytes of "struct ofpact"s starting at 'ofpacts'
7030  * into datapath actions, using 'ctx', and discards the datapath actions. */
7031 static void
7032 xlate_actions_for_side_effects(struct xlate_in *xin)
7033 {
7034     struct xlate_out xout;
7035
7036     xlate_actions(xin, &xout);
7037     xlate_out_uninit(&xout);
7038 }
7039
7040 static void
7041 xlate_report(struct xlate_ctx *ctx, const char *s)
7042 {
7043     if (ctx->xin->report_hook) {
7044         ctx->xin->report_hook(ctx, s);
7045     }
7046 }
7047 \f
7048 /* OFPP_NORMAL implementation. */
7049
7050 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
7051
7052 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
7053  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_bundle',
7054  * the bundle on which the packet was received, returns the VLAN to which the
7055  * packet belongs.
7056  *
7057  * Both 'vid' and the return value are in the range 0...4095. */
7058 static uint16_t
7059 input_vid_to_vlan(const struct ofbundle *in_bundle, uint16_t vid)
7060 {
7061     switch (in_bundle->vlan_mode) {
7062     case PORT_VLAN_ACCESS:
7063         return in_bundle->vlan;
7064         break;
7065
7066     case PORT_VLAN_TRUNK:
7067         return vid;
7068
7069     case PORT_VLAN_NATIVE_UNTAGGED:
7070     case PORT_VLAN_NATIVE_TAGGED:
7071         return vid ? vid : in_bundle->vlan;
7072
7073     default:
7074         NOT_REACHED();
7075     }
7076 }
7077
7078 /* Checks whether a packet with the given 'vid' may ingress on 'in_bundle'.
7079  * If so, returns true.  Otherwise, returns false and, if 'warn' is true, logs
7080  * a warning.
7081  *
7082  * 'vid' should be the VID obtained from the 802.1Q header that was received as
7083  * part of a packet (specify 0 if there was no 802.1Q header), in the range
7084  * 0...4095. */
7085 static bool
7086 input_vid_is_valid(uint16_t vid, struct ofbundle *in_bundle, bool warn)
7087 {
7088     /* Allow any VID on the OFPP_NONE port. */
7089     if (in_bundle == &ofpp_none_bundle) {
7090         return true;
7091     }
7092
7093     switch (in_bundle->vlan_mode) {
7094     case PORT_VLAN_ACCESS:
7095         if (vid) {
7096             if (warn) {
7097                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
7098                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" tagged "
7099                              "packet received on port %s configured as VLAN "
7100                              "%"PRIu16" access port",
7101                              in_bundle->ofproto->up.name, vid,
7102                              in_bundle->name, in_bundle->vlan);
7103             }
7104             return false;
7105         }
7106         return true;
7107
7108     case PORT_VLAN_NATIVE_UNTAGGED:
7109     case PORT_VLAN_NATIVE_TAGGED:
7110         if (!vid) {
7111             /* Port must always carry its native VLAN. */
7112             return true;
7113         }
7114         /* Fall through. */
7115     case PORT_VLAN_TRUNK:
7116         if (!ofbundle_includes_vlan(in_bundle, vid)) {
7117             if (warn) {
7118                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
7119                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" packet "
7120                              "received on port %s not configured for trunking "
7121                              "VLAN %"PRIu16,
7122                              in_bundle->ofproto->up.name, vid,
7123                              in_bundle->name, vid);
7124             }
7125             return false;
7126         }
7127         return true;
7128
7129     default:
7130         NOT_REACHED();
7131     }
7132
7133 }
7134
7135 /* Given 'vlan', the VLAN that a packet belongs to, and
7136  * 'out_bundle', a bundle on which the packet is to be output, returns the VID
7137  * that should be included in the 802.1Q header.  (If the return value is 0,
7138  * then the 802.1Q header should only be included in the packet if there is a
7139  * nonzero PCP.)
7140  *
7141  * Both 'vlan' and the return value are in the range 0...4095. */
7142 static uint16_t
7143 output_vlan_to_vid(const struct ofbundle *out_bundle, uint16_t vlan)
7144 {
7145     switch (out_bundle->vlan_mode) {
7146     case PORT_VLAN_ACCESS:
7147         return 0;
7148
7149     case PORT_VLAN_TRUNK:
7150     case PORT_VLAN_NATIVE_TAGGED:
7151         return vlan;
7152
7153     case PORT_VLAN_NATIVE_UNTAGGED:
7154         return vlan == out_bundle->vlan ? 0 : vlan;
7155
7156     default:
7157         NOT_REACHED();
7158     }
7159 }
7160
7161 static void
7162 output_normal(struct xlate_ctx *ctx, const struct ofbundle *out_bundle,
7163               uint16_t vlan)
7164 {
7165     struct ofport_dpif *port;
7166     uint16_t vid;
7167     ovs_be16 tci, old_tci;
7168
7169     vid = output_vlan_to_vid(out_bundle, vlan);
7170     if (!out_bundle->bond) {
7171         port = ofbundle_get_a_port(out_bundle);
7172     } else {
7173         port = bond_choose_output_slave(out_bundle->bond, &ctx->xin->flow,
7174                                         vid, &ctx->xout->tags);
7175         if (!port) {
7176             /* No slaves enabled, so drop packet. */
7177             return;
7178         }
7179     }
7180
7181     old_tci = ctx->xin->flow.vlan_tci;
7182     tci = htons(vid);
7183     if (tci || out_bundle->use_priority_tags) {
7184         tci |= ctx->xin->flow.vlan_tci & htons(VLAN_PCP_MASK);
7185         if (tci) {
7186             tci |= htons(VLAN_CFI);
7187         }
7188     }
7189     ctx->xin->flow.vlan_tci = tci;
7190
7191     compose_output_action(ctx, port->up.ofp_port);
7192     ctx->xin->flow.vlan_tci = old_tci;
7193 }
7194
7195 static int
7196 mirror_mask_ffs(mirror_mask_t mask)
7197 {
7198     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
7199     return ffs(mask);
7200 }
7201
7202 static bool
7203 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
7204 {
7205     return (bundle->vlan_mode != PORT_VLAN_ACCESS
7206             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
7207 }
7208
7209 static bool
7210 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
7211 {
7212     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
7213 }
7214
7215 /* Returns an arbitrary interface within 'bundle'. */
7216 static struct ofport_dpif *
7217 ofbundle_get_a_port(const struct ofbundle *bundle)
7218 {
7219     return CONTAINER_OF(list_front(&bundle->ports),
7220                         struct ofport_dpif, bundle_node);
7221 }
7222
7223 static bool
7224 vlan_is_mirrored(const struct ofmirror *m, int vlan)
7225 {
7226     return !m->vlans || bitmap_is_set(m->vlans, vlan);
7227 }
7228
7229 static void
7230 add_mirror_actions(struct xlate_ctx *ctx, const struct flow *orig_flow)
7231 {
7232     struct ofproto_dpif *ofproto = ctx->ofproto;
7233     mirror_mask_t mirrors;
7234     struct ofbundle *in_bundle;
7235     uint16_t vlan;
7236     uint16_t vid;
7237     const struct nlattr *a;
7238     size_t left;
7239
7240     in_bundle = lookup_input_bundle(ctx->ofproto, orig_flow->in_port,
7241                                     ctx->xin->packet != NULL, NULL);
7242     if (!in_bundle) {
7243         return;
7244     }
7245     mirrors = in_bundle->src_mirrors;
7246
7247     /* Drop frames on bundles reserved for mirroring. */
7248     if (in_bundle->mirror_out) {
7249         if (ctx->xin->packet != NULL) {
7250             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
7251             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
7252                          "%s, which is reserved exclusively for mirroring",
7253                          ctx->ofproto->up.name, in_bundle->name);
7254         }
7255         return;
7256     }
7257
7258     /* Check VLAN. */
7259     vid = vlan_tci_to_vid(orig_flow->vlan_tci);
7260     if (!input_vid_is_valid(vid, in_bundle, ctx->xin->packet != NULL)) {
7261         return;
7262     }
7263     vlan = input_vid_to_vlan(in_bundle, vid);
7264
7265     /* Look at the output ports to check for destination selections. */
7266
7267     NL_ATTR_FOR_EACH (a, left, ctx->xout->odp_actions.data,
7268                       ctx->xout->odp_actions.size) {
7269         enum ovs_action_attr type = nl_attr_type(a);
7270         struct ofport_dpif *ofport;
7271
7272         if (type != OVS_ACTION_ATTR_OUTPUT) {
7273             continue;
7274         }
7275
7276         ofport = get_odp_port(ofproto, nl_attr_get_u32(a));
7277         if (ofport && ofport->bundle) {
7278             mirrors |= ofport->bundle->dst_mirrors;
7279         }
7280     }
7281
7282     if (!mirrors) {
7283         return;
7284     }
7285
7286     /* Restore the original packet before adding the mirror actions. */
7287     ctx->xin->flow = *orig_flow;
7288
7289     while (mirrors) {
7290         struct ofmirror *m;
7291
7292         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
7293
7294         if (!vlan_is_mirrored(m, vlan)) {
7295             mirrors = zero_rightmost_1bit(mirrors);
7296             continue;
7297         }
7298
7299         mirrors &= ~m->dup_mirrors;
7300         ctx->xout->mirrors |= m->dup_mirrors;
7301         if (m->out) {
7302             output_normal(ctx, m->out, vlan);
7303         } else if (vlan != m->out_vlan
7304                    && !eth_addr_is_reserved(orig_flow->dl_dst)) {
7305             struct ofbundle *bundle;
7306
7307             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
7308                 if (ofbundle_includes_vlan(bundle, m->out_vlan)
7309                     && !bundle->mirror_out) {
7310                     output_normal(ctx, bundle, m->out_vlan);
7311                 }
7312             }
7313         }
7314     }
7315 }
7316
7317 static void
7318 update_mirror_stats(struct ofproto_dpif *ofproto, mirror_mask_t mirrors,
7319                     uint64_t packets, uint64_t bytes)
7320 {
7321     if (!mirrors) {
7322         return;
7323     }
7324
7325     for (; mirrors; mirrors = zero_rightmost_1bit(mirrors)) {
7326         struct ofmirror *m;
7327
7328         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
7329
7330         if (!m) {
7331             /* In normal circumstances 'm' will not be NULL.  However,
7332              * if mirrors are reconfigured, we can temporarily get out
7333              * of sync in facet_revalidate().  We could "correct" the
7334              * mirror list before reaching here, but doing that would
7335              * not properly account the traffic stats we've currently
7336              * accumulated for previous mirror configuration. */
7337             continue;
7338         }
7339
7340         m->packet_count += packets;
7341         m->byte_count += bytes;
7342     }
7343 }
7344
7345 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
7346  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
7347  * indicate this; newer upstream kernels use gratuitous ARP requests. */
7348 static bool
7349 is_gratuitous_arp(const struct flow *flow)
7350 {
7351     return (flow->dl_type == htons(ETH_TYPE_ARP)
7352             && eth_addr_is_broadcast(flow->dl_dst)
7353             && (flow->nw_proto == ARP_OP_REPLY
7354                 || (flow->nw_proto == ARP_OP_REQUEST
7355                     && flow->nw_src == flow->nw_dst)));
7356 }
7357
7358 static void
7359 update_learning_table(struct ofproto_dpif *ofproto,
7360                       const struct flow *flow, int vlan,
7361                       struct ofbundle *in_bundle)
7362 {
7363     struct mac_entry *mac;
7364
7365     /* Don't learn the OFPP_NONE port. */
7366     if (in_bundle == &ofpp_none_bundle) {
7367         return;
7368     }
7369
7370     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
7371         return;
7372     }
7373
7374     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
7375     if (is_gratuitous_arp(flow)) {
7376         /* We don't want to learn from gratuitous ARP packets that are
7377          * reflected back over bond slaves so we lock the learning table. */
7378         if (!in_bundle->bond) {
7379             mac_entry_set_grat_arp_lock(mac);
7380         } else if (mac_entry_is_grat_arp_locked(mac)) {
7381             return;
7382         }
7383     }
7384
7385     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
7386         /* The log messages here could actually be useful in debugging,
7387          * so keep the rate limit relatively high. */
7388         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
7389         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
7390                     "on port %s in VLAN %d",
7391                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
7392                     in_bundle->name, vlan);
7393
7394         mac->port.p = in_bundle;
7395         tag_set_add(&ofproto->backer->revalidate_set,
7396                     mac_learning_changed(ofproto->ml, mac));
7397     }
7398 }
7399
7400 static struct ofbundle *
7401 lookup_input_bundle(const struct ofproto_dpif *ofproto, uint16_t in_port,
7402                     bool warn, struct ofport_dpif **in_ofportp)
7403 {
7404     struct ofport_dpif *ofport;
7405
7406     /* Find the port and bundle for the received packet. */
7407     ofport = get_ofp_port(ofproto, in_port);
7408     if (in_ofportp) {
7409         *in_ofportp = ofport;
7410     }
7411     if (ofport && ofport->bundle) {
7412         return ofport->bundle;
7413     }
7414
7415     /* Special-case OFPP_NONE, which a controller may use as the ingress
7416      * port for traffic that it is sourcing. */
7417     if (in_port == OFPP_NONE) {
7418         return &ofpp_none_bundle;
7419     }
7420
7421     /* Odd.  A few possible reasons here:
7422      *
7423      * - We deleted a port but there are still a few packets queued up
7424      *   from it.
7425      *
7426      * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
7427      *   we don't know about.
7428      *
7429      * - The ofproto client didn't configure the port as part of a bundle.
7430      *   This is particularly likely to happen if a packet was received on the
7431      *   port after it was created, but before the client had a chance to
7432      *   configure its bundle.
7433      */
7434     if (warn) {
7435         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
7436
7437         VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
7438                      "port %"PRIu16, ofproto->up.name, in_port);
7439     }
7440     return NULL;
7441 }
7442
7443 /* Determines whether packets in 'flow' within 'ofproto' should be forwarded or
7444  * dropped.  Returns true if they may be forwarded, false if they should be
7445  * dropped.
7446  *
7447  * 'in_port' must be the ofport_dpif that corresponds to flow->in_port.
7448  * 'in_port' must be part of a bundle (e.g. in_port->bundle must be nonnull).
7449  *
7450  * 'vlan' must be the VLAN that corresponds to flow->vlan_tci on 'in_port', as
7451  * returned by input_vid_to_vlan().  It must be a valid VLAN for 'in_port', as
7452  * checked by input_vid_is_valid().
7453  *
7454  * May also add tags to '*tags', although the current implementation only does
7455  * so in one special case.
7456  */
7457 static bool
7458 is_admissible(struct xlate_ctx *ctx, struct ofport_dpif *in_port,
7459               uint16_t vlan)
7460 {
7461     struct ofproto_dpif *ofproto = ctx->ofproto;
7462     struct flow *flow = &ctx->xin->flow;
7463     struct ofbundle *in_bundle = in_port->bundle;
7464
7465     /* Drop frames for reserved multicast addresses
7466      * only if forward_bpdu option is absent. */
7467     if (!ofproto->up.forward_bpdu && eth_addr_is_reserved(flow->dl_dst)) {
7468         xlate_report(ctx, "packet has reserved destination MAC, dropping");
7469         return false;
7470     }
7471
7472     if (in_bundle->bond) {
7473         struct mac_entry *mac;
7474
7475         switch (bond_check_admissibility(in_bundle->bond, in_port,
7476                                          flow->dl_dst, &ctx->xout->tags)) {
7477         case BV_ACCEPT:
7478             break;
7479
7480         case BV_DROP:
7481             xlate_report(ctx, "bonding refused admissibility, dropping");
7482             return false;
7483
7484         case BV_DROP_IF_MOVED:
7485             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
7486             if (mac && mac->port.p != in_bundle &&
7487                 (!is_gratuitous_arp(flow)
7488                  || mac_entry_is_grat_arp_locked(mac))) {
7489                 xlate_report(ctx, "SLB bond thinks this packet looped back, "
7490                             "dropping");
7491                 return false;
7492             }
7493             break;
7494         }
7495     }
7496
7497     return true;
7498 }
7499
7500 static void
7501 xlate_normal(struct xlate_ctx *ctx)
7502 {
7503     struct ofport_dpif *in_port;
7504     struct ofbundle *in_bundle;
7505     struct mac_entry *mac;
7506     uint16_t vlan;
7507     uint16_t vid;
7508
7509     ctx->xout->has_normal = true;
7510
7511     in_bundle = lookup_input_bundle(ctx->ofproto, ctx->xin->flow.in_port,
7512                                     ctx->xin->packet != NULL, &in_port);
7513     if (!in_bundle) {
7514         xlate_report(ctx, "no input bundle, dropping");
7515         return;
7516     }
7517
7518     /* Drop malformed frames. */
7519     if (ctx->xin->flow.dl_type == htons(ETH_TYPE_VLAN) &&
7520         !(ctx->xin->flow.vlan_tci & htons(VLAN_CFI))) {
7521         if (ctx->xin->packet != NULL) {
7522             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
7523             VLOG_WARN_RL(&rl, "bridge %s: dropping packet with partial "
7524                          "VLAN tag received on port %s",
7525                          ctx->ofproto->up.name, in_bundle->name);
7526         }
7527         xlate_report(ctx, "partial VLAN tag, dropping");
7528         return;
7529     }
7530
7531     /* Drop frames on bundles reserved for mirroring. */
7532     if (in_bundle->mirror_out) {
7533         if (ctx->xin->packet != NULL) {
7534             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
7535             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
7536                          "%s, which is reserved exclusively for mirroring",
7537                          ctx->ofproto->up.name, in_bundle->name);
7538         }
7539         xlate_report(ctx, "input port is mirror output port, dropping");
7540         return;
7541     }
7542
7543     /* Check VLAN. */
7544     vid = vlan_tci_to_vid(ctx->xin->flow.vlan_tci);
7545     if (!input_vid_is_valid(vid, in_bundle, ctx->xin->packet != NULL)) {
7546         xlate_report(ctx, "disallowed VLAN VID for this input port, dropping");
7547         return;
7548     }
7549     vlan = input_vid_to_vlan(in_bundle, vid);
7550
7551     /* Check other admissibility requirements. */
7552     if (in_port && !is_admissible(ctx, in_port, vlan)) {
7553         return;
7554     }
7555
7556     /* Learn source MAC. */
7557     if (ctx->xin->may_learn) {
7558         update_learning_table(ctx->ofproto, &ctx->xin->flow, vlan, in_bundle);
7559     }
7560
7561     /* Determine output bundle. */
7562     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->xin->flow.dl_dst, vlan,
7563                               &ctx->xout->tags);
7564     if (mac) {
7565         if (mac->port.p != in_bundle) {
7566             xlate_report(ctx, "forwarding to learned port");
7567             output_normal(ctx, mac->port.p, vlan);
7568         } else {
7569             xlate_report(ctx, "learned port is input port, dropping");
7570         }
7571     } else {
7572         struct ofbundle *bundle;
7573
7574         xlate_report(ctx, "no learned MAC for destination, flooding");
7575         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
7576             if (bundle != in_bundle
7577                 && ofbundle_includes_vlan(bundle, vlan)
7578                 && bundle->floodable
7579                 && !bundle->mirror_out) {
7580                 output_normal(ctx, bundle, vlan);
7581             }
7582         }
7583         ctx->xout->nf_output_iface = NF_OUT_FLOOD;
7584     }
7585 }
7586 \f
7587 /* Optimized flow revalidation.
7588  *
7589  * It's a difficult problem, in general, to tell which facets need to have
7590  * their actions recalculated whenever the OpenFlow flow table changes.  We
7591  * don't try to solve that general problem: for most kinds of OpenFlow flow
7592  * table changes, we recalculate the actions for every facet.  This is
7593  * relatively expensive, but it's good enough if the OpenFlow flow table
7594  * doesn't change very often.
7595  *
7596  * However, we can expect one particular kind of OpenFlow flow table change to
7597  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
7598  * of CPU on revalidating every facet whenever MAC learning modifies the flow
7599  * table, we add a special case that applies to flow tables in which every rule
7600  * has the same form (that is, the same wildcards), except that the table is
7601  * also allowed to have a single "catch-all" flow that matches all packets.  We
7602  * optimize this case by tagging all of the facets that resubmit into the table
7603  * and invalidating the same tag whenever a flow changes in that table.  The
7604  * end result is that we revalidate just the facets that need it (and sometimes
7605  * a few more, but not all of the facets or even all of the facets that
7606  * resubmit to the table modified by MAC learning). */
7607
7608 /* Calculates the tag to use for 'flow' and mask 'mask' when it is inserted
7609  * into an OpenFlow table with the given 'basis'. */
7610 static tag_type
7611 rule_calculate_tag(const struct flow *flow, const struct minimask *mask,
7612                    uint32_t secret)
7613 {
7614     if (minimask_is_catchall(mask)) {
7615         return 0;
7616     } else {
7617         uint32_t hash = flow_hash_in_minimask(flow, mask, secret);
7618         return tag_create_deterministic(hash);
7619     }
7620 }
7621
7622 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
7623  * taggability of that table.
7624  *
7625  * This function must be called after *each* change to a flow table.  If you
7626  * skip calling it on some changes then the pointer comparisons at the end can
7627  * be invalid if you get unlucky.  For example, if a flow removal causes a
7628  * cls_table to be destroyed and then a flow insertion causes a cls_table with
7629  * different wildcards to be created with the same address, then this function
7630  * will incorrectly skip revalidation. */
7631 static void
7632 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
7633 {
7634     struct table_dpif *table = &ofproto->tables[table_id];
7635     const struct oftable *oftable = &ofproto->up.tables[table_id];
7636     struct cls_table *catchall, *other;
7637     struct cls_table *t;
7638
7639     catchall = other = NULL;
7640
7641     switch (hmap_count(&oftable->cls.tables)) {
7642     case 0:
7643         /* We could tag this OpenFlow table but it would make the logic a
7644          * little harder and it's a corner case that doesn't seem worth it
7645          * yet. */
7646         break;
7647
7648     case 1:
7649     case 2:
7650         HMAP_FOR_EACH (t, hmap_node, &oftable->cls.tables) {
7651             if (cls_table_is_catchall(t)) {
7652                 catchall = t;
7653             } else if (!other) {
7654                 other = t;
7655             } else {
7656                 /* Indicate that we can't tag this by setting both tables to
7657                  * NULL.  (We know that 'catchall' is already NULL.) */
7658                 other = NULL;
7659             }
7660         }
7661         break;
7662
7663     default:
7664         /* Can't tag this table. */
7665         break;
7666     }
7667
7668     if (table->catchall_table != catchall || table->other_table != other) {
7669         table->catchall_table = catchall;
7670         table->other_table = other;
7671         ofproto->backer->need_revalidate = REV_FLOW_TABLE;
7672     }
7673 }
7674
7675 /* Given 'rule' that has changed in some way (either it is a rule being
7676  * inserted, a rule being deleted, or a rule whose actions are being
7677  * modified), marks facets for revalidation to ensure that packets will be
7678  * forwarded correctly according to the new state of the flow table.
7679  *
7680  * This function must be called after *each* change to a flow table.  See
7681  * the comment on table_update_taggable() for more information. */
7682 static void
7683 rule_invalidate(const struct rule_dpif *rule)
7684 {
7685     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
7686
7687     table_update_taggable(ofproto, rule->up.table_id);
7688
7689     if (!ofproto->backer->need_revalidate) {
7690         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
7691
7692         if (table->other_table && rule->tag) {
7693             tag_set_add(&ofproto->backer->revalidate_set, rule->tag);
7694         } else {
7695             ofproto->backer->need_revalidate = REV_FLOW_TABLE;
7696         }
7697     }
7698 }
7699 \f
7700 static bool
7701 set_frag_handling(struct ofproto *ofproto_,
7702                   enum ofp_config_flags frag_handling)
7703 {
7704     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7705     if (frag_handling != OFPC_FRAG_REASM) {
7706         ofproto->backer->need_revalidate = REV_RECONFIGURE;
7707         return true;
7708     } else {
7709         return false;
7710     }
7711 }
7712
7713 static enum ofperr
7714 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
7715            const struct flow *flow,
7716            const struct ofpact *ofpacts, size_t ofpacts_len)
7717 {
7718     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7719     struct initial_vals initial_vals;
7720     struct odputil_keybuf keybuf;
7721     struct dpif_flow_stats stats;
7722     struct xlate_out xout;
7723     struct xlate_in xin;
7724     struct ofpbuf key;
7725
7726
7727     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
7728     odp_flow_key_from_flow(&key, flow,
7729                            ofp_port_to_odp_port(ofproto, flow->in_port));
7730
7731     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
7732
7733     initial_vals.vlan_tci = flow->vlan_tci;
7734     xlate_in_init(&xin, ofproto, flow, &initial_vals, NULL, stats.tcp_flags,
7735                   packet);
7736     xin.resubmit_stats = &stats;
7737     xin.ofpacts_len = ofpacts_len;
7738     xin.ofpacts = ofpacts;
7739
7740     xlate_actions(&xin, &xout);
7741     dpif_execute(ofproto->backer->dpif, key.data, key.size,
7742                  xout.odp_actions.data, xout.odp_actions.size, packet);
7743     xlate_out_uninit(&xout);
7744
7745     return 0;
7746 }
7747 \f
7748 /* NetFlow. */
7749
7750 static int
7751 set_netflow(struct ofproto *ofproto_,
7752             const struct netflow_options *netflow_options)
7753 {
7754     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7755
7756     if (netflow_options) {
7757         if (!ofproto->netflow) {
7758             ofproto->netflow = netflow_create();
7759         }
7760         return netflow_set_options(ofproto->netflow, netflow_options);
7761     } else {
7762         netflow_destroy(ofproto->netflow);
7763         ofproto->netflow = NULL;
7764         return 0;
7765     }
7766 }
7767
7768 static void
7769 get_netflow_ids(const struct ofproto *ofproto_,
7770                 uint8_t *engine_type, uint8_t *engine_id)
7771 {
7772     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7773
7774     dpif_get_netflow_ids(ofproto->backer->dpif, engine_type, engine_id);
7775 }
7776
7777 static void
7778 send_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
7779 {
7780     if (!facet_is_controller_flow(facet) &&
7781         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
7782         struct subfacet *subfacet;
7783         struct ofexpired expired;
7784
7785         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
7786             if (subfacet->path == SF_FAST_PATH) {
7787                 struct dpif_flow_stats stats;
7788
7789                 subfacet_install(subfacet, &facet->xout.odp_actions, &stats);
7790                 subfacet_update_stats(subfacet, &stats);
7791             }
7792         }
7793
7794         expired.flow = facet->flow;
7795         expired.packet_count = facet->packet_count;
7796         expired.byte_count = facet->byte_count;
7797         expired.used = facet->used;
7798         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
7799     }
7800 }
7801
7802 static void
7803 send_netflow_active_timeouts(struct ofproto_dpif *ofproto)
7804 {
7805     struct facet *facet;
7806
7807     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
7808         send_active_timeout(ofproto, facet);
7809     }
7810 }
7811 \f
7812 static struct ofproto_dpif *
7813 ofproto_dpif_lookup(const char *name)
7814 {
7815     struct ofproto_dpif *ofproto;
7816
7817     HMAP_FOR_EACH_WITH_HASH (ofproto, all_ofproto_dpifs_node,
7818                              hash_string(name, 0), &all_ofproto_dpifs) {
7819         if (!strcmp(ofproto->up.name, name)) {
7820             return ofproto;
7821         }
7822     }
7823     return NULL;
7824 }
7825
7826 static void
7827 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn, int argc,
7828                           const char *argv[], void *aux OVS_UNUSED)
7829 {
7830     struct ofproto_dpif *ofproto;
7831
7832     if (argc > 1) {
7833         ofproto = ofproto_dpif_lookup(argv[1]);
7834         if (!ofproto) {
7835             unixctl_command_reply_error(conn, "no such bridge");
7836             return;
7837         }
7838         mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
7839     } else {
7840         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
7841             mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
7842         }
7843     }
7844
7845     unixctl_command_reply(conn, "table successfully flushed");
7846 }
7847
7848 static void
7849 ofproto_unixctl_fdb_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
7850                          const char *argv[], void *aux OVS_UNUSED)
7851 {
7852     struct ds ds = DS_EMPTY_INITIALIZER;
7853     const struct ofproto_dpif *ofproto;
7854     const struct mac_entry *e;
7855
7856     ofproto = ofproto_dpif_lookup(argv[1]);
7857     if (!ofproto) {
7858         unixctl_command_reply_error(conn, "no such bridge");
7859         return;
7860     }
7861
7862     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
7863     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
7864         struct ofbundle *bundle = e->port.p;
7865         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
7866                       ofbundle_get_a_port(bundle)->odp_port,
7867                       e->vlan, ETH_ADDR_ARGS(e->mac),
7868                       mac_entry_age(ofproto->ml, e));
7869     }
7870     unixctl_command_reply(conn, ds_cstr(&ds));
7871     ds_destroy(&ds);
7872 }
7873
7874 struct trace_ctx {
7875     struct xlate_out xout;
7876     struct xlate_in xin;
7877     struct flow flow;
7878     struct ds *result;
7879 };
7880
7881 static void
7882 trace_format_rule(struct ds *result, uint8_t table_id, int level,
7883                   const struct rule_dpif *rule)
7884 {
7885     ds_put_char_multiple(result, '\t', level);
7886     if (!rule) {
7887         ds_put_cstr(result, "No match\n");
7888         return;
7889     }
7890
7891     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
7892                   table_id, ntohll(rule->up.flow_cookie));
7893     cls_rule_format(&rule->up.cr, result);
7894     ds_put_char(result, '\n');
7895
7896     ds_put_char_multiple(result, '\t', level);
7897     ds_put_cstr(result, "OpenFlow ");
7898     ofpacts_format(rule->up.ofpacts, rule->up.ofpacts_len, result);
7899     ds_put_char(result, '\n');
7900 }
7901
7902 static void
7903 trace_format_flow(struct ds *result, int level, const char *title,
7904                   struct trace_ctx *trace)
7905 {
7906     ds_put_char_multiple(result, '\t', level);
7907     ds_put_format(result, "%s: ", title);
7908     if (flow_equal(&trace->xin.flow, &trace->flow)) {
7909         ds_put_cstr(result, "unchanged");
7910     } else {
7911         flow_format(result, &trace->xin.flow);
7912         trace->flow = trace->xin.flow;
7913     }
7914     ds_put_char(result, '\n');
7915 }
7916
7917 static void
7918 trace_format_regs(struct ds *result, int level, const char *title,
7919                   struct trace_ctx *trace)
7920 {
7921     size_t i;
7922
7923     ds_put_char_multiple(result, '\t', level);
7924     ds_put_format(result, "%s:", title);
7925     for (i = 0; i < FLOW_N_REGS; i++) {
7926         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
7927     }
7928     ds_put_char(result, '\n');
7929 }
7930
7931 static void
7932 trace_format_odp(struct ds *result, int level, const char *title,
7933                  struct trace_ctx *trace)
7934 {
7935     struct ofpbuf *odp_actions = &trace->xout.odp_actions;
7936
7937     ds_put_char_multiple(result, '\t', level);
7938     ds_put_format(result, "%s: ", title);
7939     format_odp_actions(result, odp_actions->data, odp_actions->size);
7940     ds_put_char(result, '\n');
7941 }
7942
7943 static void
7944 trace_resubmit(struct xlate_ctx *ctx, struct rule_dpif *rule)
7945 {
7946     struct trace_ctx *trace = CONTAINER_OF(ctx->xin, struct trace_ctx, xin);
7947     struct ds *result = trace->result;
7948
7949     ds_put_char(result, '\n');
7950     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
7951     trace_format_regs(result, ctx->recurse + 1, "Resubmitted regs", trace);
7952     trace_format_odp(result,  ctx->recurse + 1, "Resubmitted  odp", trace);
7953     trace_format_rule(result, ctx->table_id, ctx->recurse + 1, rule);
7954 }
7955
7956 static void
7957 trace_report(struct xlate_ctx *ctx, const char *s)
7958 {
7959     struct trace_ctx *trace = CONTAINER_OF(ctx->xin, struct trace_ctx, xin);
7960     struct ds *result = trace->result;
7961
7962     ds_put_char_multiple(result, '\t', ctx->recurse);
7963     ds_put_cstr(result, s);
7964     ds_put_char(result, '\n');
7965 }
7966
7967 static void
7968 ofproto_unixctl_trace(struct unixctl_conn *conn, int argc, const char *argv[],
7969                       void *aux OVS_UNUSED)
7970 {
7971     const struct dpif_backer *backer;
7972     struct ofproto_dpif *ofproto;
7973     struct ofpbuf odp_key;
7974     struct ofpbuf *packet;
7975     struct initial_vals initial_vals;
7976     struct ds result;
7977     struct flow flow;
7978     char *s;
7979
7980     packet = NULL;
7981     backer = NULL;
7982     ds_init(&result);
7983     ofpbuf_init(&odp_key, 0);
7984
7985     /* Handle "-generate" or a hex string as the last argument. */
7986     if (!strcmp(argv[argc - 1], "-generate")) {
7987         packet = ofpbuf_new(0);
7988         argc--;
7989     } else {
7990         const char *error = eth_from_hex(argv[argc - 1], &packet);
7991         if (!error) {
7992             argc--;
7993         } else if (argc == 4) {
7994             /* The 3-argument form must end in "-generate' or a hex string. */
7995             unixctl_command_reply_error(conn, error);
7996             goto exit;
7997         }
7998     }
7999
8000     /* Parse the flow and determine whether a datapath or
8001      * bridge is specified. If function odp_flow_key_from_string()
8002      * returns 0, the flow is a odp_flow. If function
8003      * parse_ofp_exact_flow() returns 0, the flow is a br_flow. */
8004     if (!odp_flow_key_from_string(argv[argc - 1], NULL, &odp_key)) {
8005         /* If the odp_flow is the second argument,
8006          * the datapath name is the first argument. */
8007         if (argc == 3) {
8008             const char *dp_type;
8009             if (!strncmp(argv[1], "ovs-", 4)) {
8010                 dp_type = argv[1] + 4;
8011             } else {
8012                 dp_type = argv[1];
8013             }
8014             backer = shash_find_data(&all_dpif_backers, dp_type);
8015             if (!backer) {
8016                 unixctl_command_reply_error(conn, "Cannot find datapath "
8017                                "of this name");
8018                 goto exit;
8019             }
8020         } else {
8021             /* No datapath name specified, so there should be only one
8022              * datapath. */
8023             struct shash_node *node;
8024             if (shash_count(&all_dpif_backers) != 1) {
8025                 unixctl_command_reply_error(conn, "Must specify datapath "
8026                          "name, there is more than one type of datapath");
8027                 goto exit;
8028             }
8029             node = shash_first(&all_dpif_backers);
8030             backer = node->data;
8031         }
8032
8033         /* Extract the ofproto_dpif object from the ofproto_receive()
8034          * function. */
8035         if (ofproto_receive(backer, NULL, odp_key.data,
8036                             odp_key.size, &flow, NULL, &ofproto, NULL,
8037                             &initial_vals)) {
8038             unixctl_command_reply_error(conn, "Invalid datapath flow");
8039             goto exit;
8040         }
8041         ds_put_format(&result, "Bridge: %s\n", ofproto->up.name);
8042     } else if (!parse_ofp_exact_flow(&flow, argv[argc - 1])) {
8043         if (argc != 3) {
8044             unixctl_command_reply_error(conn, "Must specify bridge name");
8045             goto exit;
8046         }
8047
8048         ofproto = ofproto_dpif_lookup(argv[1]);
8049         if (!ofproto) {
8050             unixctl_command_reply_error(conn, "Unknown bridge name");
8051             goto exit;
8052         }
8053         initial_vals.vlan_tci = flow.vlan_tci;
8054     } else {
8055         unixctl_command_reply_error(conn, "Bad flow syntax");
8056         goto exit;
8057     }
8058
8059     /* Generate a packet, if requested. */
8060     if (packet) {
8061         if (!packet->size) {
8062             flow_compose(packet, &flow);
8063         } else {
8064             ds_put_cstr(&result, "Packet: ");
8065             s = ofp_packet_to_string(packet->data, packet->size);
8066             ds_put_cstr(&result, s);
8067             free(s);
8068
8069             /* Use the metadata from the flow and the packet argument
8070              * to reconstruct the flow. */
8071             flow_extract(packet, flow.skb_priority, flow.skb_mark, NULL,
8072                          flow.in_port, &flow);
8073             initial_vals.vlan_tci = flow.vlan_tci;
8074         }
8075     }
8076
8077     ofproto_trace(ofproto, &flow, packet, &initial_vals, &result);
8078     unixctl_command_reply(conn, ds_cstr(&result));
8079
8080 exit:
8081     ds_destroy(&result);
8082     ofpbuf_delete(packet);
8083     ofpbuf_uninit(&odp_key);
8084 }
8085
8086 static void
8087 ofproto_trace(struct ofproto_dpif *ofproto, const struct flow *flow,
8088               const struct ofpbuf *packet,
8089               const struct initial_vals *initial_vals, struct ds *ds)
8090 {
8091     struct rule_dpif *rule;
8092
8093     ds_put_cstr(ds, "Flow: ");
8094     flow_format(ds, flow);
8095     ds_put_char(ds, '\n');
8096
8097     rule = rule_dpif_lookup(ofproto, flow);
8098
8099     trace_format_rule(ds, 0, 0, rule);
8100     if (rule == ofproto->miss_rule) {
8101         ds_put_cstr(ds, "\nNo match, flow generates \"packet in\"s.\n");
8102     } else if (rule == ofproto->no_packet_in_rule) {
8103         ds_put_cstr(ds, "\nNo match, packets dropped because "
8104                     "OFPPC_NO_PACKET_IN is set on in_port.\n");
8105     } else if (rule == ofproto->drop_frags_rule) {
8106         ds_put_cstr(ds, "\nPackets dropped because they are IP fragments "
8107                     "and the fragment handling mode is \"drop\".\n");
8108     }
8109
8110     if (rule) {
8111         uint64_t odp_actions_stub[1024 / 8];
8112         struct ofpbuf odp_actions;
8113
8114         struct trace_ctx trace;
8115         uint8_t tcp_flags;
8116
8117         tcp_flags = packet ? packet_get_tcp_flags(packet, flow) : 0;
8118         trace.result = ds;
8119         trace.flow = *flow;
8120         ofpbuf_use_stub(&odp_actions,
8121                         odp_actions_stub, sizeof odp_actions_stub);
8122         xlate_in_init(&trace.xin, ofproto, flow, initial_vals, rule, tcp_flags,
8123                       packet);
8124         trace.xin.resubmit_hook = trace_resubmit;
8125         trace.xin.report_hook = trace_report;
8126         xlate_actions(&trace.xin, &trace.xout);
8127
8128         ds_put_char(ds, '\n');
8129         trace_format_flow(ds, 0, "Final flow", &trace);
8130         ds_put_cstr(ds, "Datapath actions: ");
8131         format_odp_actions(ds, trace.xout.odp_actions.data,
8132                            trace.xout.odp_actions.size);
8133
8134         if (trace.xout.slow) {
8135             ds_put_cstr(ds, "\nThis flow is handled by the userspace "
8136                         "slow path because it:");
8137             switch (trace.xout.slow) {
8138             case SLOW_CFM:
8139                 ds_put_cstr(ds, "\n\t- Consists of CFM packets.");
8140                 break;
8141             case SLOW_LACP:
8142                 ds_put_cstr(ds, "\n\t- Consists of LACP packets.");
8143                 break;
8144             case SLOW_STP:
8145                 ds_put_cstr(ds, "\n\t- Consists of STP packets.");
8146                 break;
8147             case SLOW_BFD:
8148                 ds_put_cstr(ds, "\n\t- Consists of BFD packets.");
8149                 break;
8150             case SLOW_CONTROLLER:
8151                 ds_put_cstr(ds, "\n\t- Sends \"packet-in\" messages "
8152                             "to the OpenFlow controller.");
8153                 break;
8154             case __SLOW_MAX:
8155                 NOT_REACHED();
8156             }
8157         }
8158
8159         xlate_out_uninit(&trace.xout);
8160     }
8161 }
8162
8163 static void
8164 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
8165                   const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
8166 {
8167     clogged = true;
8168     unixctl_command_reply(conn, NULL);
8169 }
8170
8171 static void
8172 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
8173                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
8174 {
8175     clogged = false;
8176     unixctl_command_reply(conn, NULL);
8177 }
8178
8179 /* Runs a self-check of flow translations in 'ofproto'.  Appends a message to
8180  * 'reply' describing the results. */
8181 static void
8182 ofproto_dpif_self_check__(struct ofproto_dpif *ofproto, struct ds *reply)
8183 {
8184     struct facet *facet;
8185     int errors;
8186
8187     errors = 0;
8188     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
8189         if (!facet_check_consistency(facet)) {
8190             errors++;
8191         }
8192     }
8193     if (errors) {
8194         ofproto->backer->need_revalidate = REV_INCONSISTENCY;
8195     }
8196
8197     if (errors) {
8198         ds_put_format(reply, "%s: self-check failed (%d errors)\n",
8199                       ofproto->up.name, errors);
8200     } else {
8201         ds_put_format(reply, "%s: self-check passed\n", ofproto->up.name);
8202     }
8203 }
8204
8205 static void
8206 ofproto_dpif_self_check(struct unixctl_conn *conn,
8207                         int argc, const char *argv[], void *aux OVS_UNUSED)
8208 {
8209     struct ds reply = DS_EMPTY_INITIALIZER;
8210     struct ofproto_dpif *ofproto;
8211
8212     if (argc > 1) {
8213         ofproto = ofproto_dpif_lookup(argv[1]);
8214         if (!ofproto) {
8215             unixctl_command_reply_error(conn, "Unknown ofproto (use "
8216                                         "ofproto/list for help)");
8217             return;
8218         }
8219         ofproto_dpif_self_check__(ofproto, &reply);
8220     } else {
8221         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
8222             ofproto_dpif_self_check__(ofproto, &reply);
8223         }
8224     }
8225
8226     unixctl_command_reply(conn, ds_cstr(&reply));
8227     ds_destroy(&reply);
8228 }
8229
8230 /* Store the current ofprotos in 'ofproto_shash'.  Returns a sorted list
8231  * of the 'ofproto_shash' nodes.  It is the responsibility of the caller
8232  * to destroy 'ofproto_shash' and free the returned value. */
8233 static const struct shash_node **
8234 get_ofprotos(struct shash *ofproto_shash)
8235 {
8236     const struct ofproto_dpif *ofproto;
8237
8238     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
8239         char *name = xasprintf("%s@%s", ofproto->up.type, ofproto->up.name);
8240         shash_add_nocopy(ofproto_shash, name, ofproto);
8241     }
8242
8243     return shash_sort(ofproto_shash);
8244 }
8245
8246 static void
8247 ofproto_unixctl_dpif_dump_dps(struct unixctl_conn *conn, int argc OVS_UNUSED,
8248                               const char *argv[] OVS_UNUSED,
8249                               void *aux OVS_UNUSED)
8250 {
8251     struct ds ds = DS_EMPTY_INITIALIZER;
8252     struct shash ofproto_shash;
8253     const struct shash_node **sorted_ofprotos;
8254     int i;
8255
8256     shash_init(&ofproto_shash);
8257     sorted_ofprotos = get_ofprotos(&ofproto_shash);
8258     for (i = 0; i < shash_count(&ofproto_shash); i++) {
8259         const struct shash_node *node = sorted_ofprotos[i];
8260         ds_put_format(&ds, "%s\n", node->name);
8261     }
8262
8263     shash_destroy(&ofproto_shash);
8264     free(sorted_ofprotos);
8265
8266     unixctl_command_reply(conn, ds_cstr(&ds));
8267     ds_destroy(&ds);
8268 }
8269
8270 static void
8271 show_dp_format(const struct ofproto_dpif *ofproto, struct ds *ds)
8272 {
8273     const struct shash_node **ports;
8274     int i;
8275     struct avg_subfacet_rates lifetime;
8276     unsigned long long int minutes;
8277     const int min_ms = 60 * 1000; /* milliseconds in one minute. */
8278
8279     minutes = (time_msec() - ofproto->created) / min_ms;
8280
8281     if (minutes > 0) {
8282         lifetime.add_rate = (double)ofproto->total_subfacet_add_count
8283                             / minutes;
8284         lifetime.del_rate = (double)ofproto->total_subfacet_del_count
8285                             / minutes;
8286     }else {
8287         lifetime.add_rate = 0.0;
8288         lifetime.del_rate = 0.0;
8289     }
8290
8291     ds_put_format(ds, "%s (%s):\n", ofproto->up.name,
8292                   dpif_name(ofproto->backer->dpif));
8293     ds_put_format(ds,
8294                   "\tlookups: hit:%"PRIu64" missed:%"PRIu64"\n",
8295                   ofproto->n_hit, ofproto->n_missed);
8296     ds_put_format(ds, "\tflows: cur: %zu, avg: %5.3f, max: %d,"
8297                   " life span: %llu(ms)\n",
8298                   hmap_count(&ofproto->subfacets),
8299                   avg_subfacet_count(ofproto),
8300                   ofproto->max_n_subfacet,
8301                   avg_subfacet_life_span(ofproto));
8302     if (minutes >= 60) {
8303         show_dp_rates(ds, "\t\thourly avg:", &ofproto->hourly);
8304     }
8305     if (minutes >= 60 * 24) {
8306         show_dp_rates(ds, "\t\tdaily avg:",  &ofproto->daily);
8307     }
8308     show_dp_rates(ds, "\t\toverall avg:",  &lifetime);
8309
8310     ports = shash_sort(&ofproto->up.port_by_name);
8311     for (i = 0; i < shash_count(&ofproto->up.port_by_name); i++) {
8312         const struct shash_node *node = ports[i];
8313         struct ofport *ofport = node->data;
8314         const char *name = netdev_get_name(ofport->netdev);
8315         const char *type = netdev_get_type(ofport->netdev);
8316         uint32_t odp_port;
8317
8318         ds_put_format(ds, "\t%s %u/", name, ofport->ofp_port);
8319
8320         odp_port = ofp_port_to_odp_port(ofproto, ofport->ofp_port);
8321         if (odp_port != OVSP_NONE) {
8322             ds_put_format(ds, "%"PRIu32":", odp_port);
8323         } else {
8324             ds_put_cstr(ds, "none:");
8325         }
8326
8327         if (strcmp(type, "system")) {
8328             struct netdev *netdev;
8329             int error;
8330
8331             ds_put_format(ds, " (%s", type);
8332
8333             error = netdev_open(name, type, &netdev);
8334             if (!error) {
8335                 struct smap config;
8336
8337                 smap_init(&config);
8338                 error = netdev_get_config(netdev, &config);
8339                 if (!error) {
8340                     const struct smap_node **nodes;
8341                     size_t i;
8342
8343                     nodes = smap_sort(&config);
8344                     for (i = 0; i < smap_count(&config); i++) {
8345                         const struct smap_node *node = nodes[i];
8346                         ds_put_format(ds, "%c %s=%s", i ? ',' : ':',
8347                                       node->key, node->value);
8348                     }
8349                     free(nodes);
8350                 }
8351                 smap_destroy(&config);
8352
8353                 netdev_close(netdev);
8354             }
8355             ds_put_char(ds, ')');
8356         }
8357         ds_put_char(ds, '\n');
8358     }
8359     free(ports);
8360 }
8361
8362 static void
8363 ofproto_unixctl_dpif_show(struct unixctl_conn *conn, int argc,
8364                           const char *argv[], void *aux OVS_UNUSED)
8365 {
8366     struct ds ds = DS_EMPTY_INITIALIZER;
8367     const struct ofproto_dpif *ofproto;
8368
8369     if (argc > 1) {
8370         int i;
8371         for (i = 1; i < argc; i++) {
8372             ofproto = ofproto_dpif_lookup(argv[i]);
8373             if (!ofproto) {
8374                 ds_put_format(&ds, "Unknown bridge %s (use dpif/dump-dps "
8375                                    "for help)", argv[i]);
8376                 unixctl_command_reply_error(conn, ds_cstr(&ds));
8377                 return;
8378             }
8379             show_dp_format(ofproto, &ds);
8380         }
8381     } else {
8382         struct shash ofproto_shash;
8383         const struct shash_node **sorted_ofprotos;
8384         int i;
8385
8386         shash_init(&ofproto_shash);
8387         sorted_ofprotos = get_ofprotos(&ofproto_shash);
8388         for (i = 0; i < shash_count(&ofproto_shash); i++) {
8389             const struct shash_node *node = sorted_ofprotos[i];
8390             show_dp_format(node->data, &ds);
8391         }
8392
8393         shash_destroy(&ofproto_shash);
8394         free(sorted_ofprotos);
8395     }
8396
8397     unixctl_command_reply(conn, ds_cstr(&ds));
8398     ds_destroy(&ds);
8399 }
8400
8401 static void
8402 ofproto_unixctl_dpif_dump_flows(struct unixctl_conn *conn,
8403                                 int argc OVS_UNUSED, const char *argv[],
8404                                 void *aux OVS_UNUSED)
8405 {
8406     struct ds ds = DS_EMPTY_INITIALIZER;
8407     const struct ofproto_dpif *ofproto;
8408     struct subfacet *subfacet;
8409
8410     ofproto = ofproto_dpif_lookup(argv[1]);
8411     if (!ofproto) {
8412         unixctl_command_reply_error(conn, "no such bridge");
8413         return;
8414     }
8415
8416     update_stats(ofproto->backer);
8417
8418     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->subfacets) {
8419         struct facet *facet = subfacet->facet;
8420
8421         odp_flow_key_format(subfacet->key, subfacet->key_len, &ds);
8422
8423         ds_put_format(&ds, ", packets:%"PRIu64", bytes:%"PRIu64", used:",
8424                       subfacet->dp_packet_count, subfacet->dp_byte_count);
8425         if (subfacet->used) {
8426             ds_put_format(&ds, "%.3fs",
8427                           (time_msec() - subfacet->used) / 1000.0);
8428         } else {
8429             ds_put_format(&ds, "never");
8430         }
8431         if (subfacet->facet->tcp_flags) {
8432             ds_put_cstr(&ds, ", flags:");
8433             packet_format_tcp_flags(&ds, subfacet->facet->tcp_flags);
8434         }
8435
8436         ds_put_cstr(&ds, ", actions:");
8437         if (facet->xout.slow) {
8438             uint64_t slow_path_stub[128 / 8];
8439             const struct nlattr *actions;
8440             size_t actions_len;
8441
8442             compose_slow_path(ofproto, &facet->flow, facet->xout.slow,
8443                               slow_path_stub, sizeof slow_path_stub,
8444                               &actions, &actions_len);
8445             format_odp_actions(&ds, actions, actions_len);
8446         } else {
8447             format_odp_actions(&ds, facet->xout.odp_actions.data,
8448                                facet->xout.odp_actions.size);
8449         }
8450         ds_put_char(&ds, '\n');
8451     }
8452
8453     unixctl_command_reply(conn, ds_cstr(&ds));
8454     ds_destroy(&ds);
8455 }
8456
8457 static void
8458 ofproto_unixctl_dpif_del_flows(struct unixctl_conn *conn,
8459                                int argc OVS_UNUSED, const char *argv[],
8460                                void *aux OVS_UNUSED)
8461 {
8462     struct ds ds = DS_EMPTY_INITIALIZER;
8463     struct ofproto_dpif *ofproto;
8464
8465     ofproto = ofproto_dpif_lookup(argv[1]);
8466     if (!ofproto) {
8467         unixctl_command_reply_error(conn, "no such bridge");
8468         return;
8469     }
8470
8471     flush(&ofproto->up);
8472
8473     unixctl_command_reply(conn, ds_cstr(&ds));
8474     ds_destroy(&ds);
8475 }
8476
8477 static void
8478 ofproto_dpif_unixctl_init(void)
8479 {
8480     static bool registered;
8481     if (registered) {
8482         return;
8483     }
8484     registered = true;
8485
8486     unixctl_command_register(
8487         "ofproto/trace",
8488         "[dp_name]|bridge odp_flow|br_flow [-generate|packet]",
8489         1, 3, ofproto_unixctl_trace, NULL);
8490     unixctl_command_register("fdb/flush", "[bridge]", 0, 1,
8491                              ofproto_unixctl_fdb_flush, NULL);
8492     unixctl_command_register("fdb/show", "bridge", 1, 1,
8493                              ofproto_unixctl_fdb_show, NULL);
8494     unixctl_command_register("ofproto/clog", "", 0, 0,
8495                              ofproto_dpif_clog, NULL);
8496     unixctl_command_register("ofproto/unclog", "", 0, 0,
8497                              ofproto_dpif_unclog, NULL);
8498     unixctl_command_register("ofproto/self-check", "[bridge]", 0, 1,
8499                              ofproto_dpif_self_check, NULL);
8500     unixctl_command_register("dpif/dump-dps", "", 0, 0,
8501                              ofproto_unixctl_dpif_dump_dps, NULL);
8502     unixctl_command_register("dpif/show", "[bridge]", 0, INT_MAX,
8503                              ofproto_unixctl_dpif_show, NULL);
8504     unixctl_command_register("dpif/dump-flows", "bridge", 1, 1,
8505                              ofproto_unixctl_dpif_dump_flows, NULL);
8506     unixctl_command_register("dpif/del-flows", "bridge", 1, 1,
8507                              ofproto_unixctl_dpif_del_flows, NULL);
8508 }
8509 \f
8510 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
8511  *
8512  * This is deprecated.  It is only for compatibility with broken device drivers
8513  * in old versions of Linux that do not properly support VLANs when VLAN
8514  * devices are not used.  When broken device drivers are no longer in
8515  * widespread use, we will delete these interfaces. */
8516
8517 static int
8518 set_realdev(struct ofport *ofport_, uint16_t realdev_ofp_port, int vid)
8519 {
8520     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
8521     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
8522
8523     if (realdev_ofp_port == ofport->realdev_ofp_port
8524         && vid == ofport->vlandev_vid) {
8525         return 0;
8526     }
8527
8528     ofproto->backer->need_revalidate = REV_RECONFIGURE;
8529
8530     if (ofport->realdev_ofp_port) {
8531         vsp_remove(ofport);
8532     }
8533     if (realdev_ofp_port && ofport->bundle) {
8534         /* vlandevs are enslaved to their realdevs, so they are not allowed to
8535          * themselves be part of a bundle. */
8536         bundle_set(ofport->up.ofproto, ofport->bundle, NULL);
8537     }
8538
8539     ofport->realdev_ofp_port = realdev_ofp_port;
8540     ofport->vlandev_vid = vid;
8541
8542     if (realdev_ofp_port) {
8543         vsp_add(ofport, realdev_ofp_port, vid);
8544     }
8545
8546     return 0;
8547 }
8548
8549 static uint32_t
8550 hash_realdev_vid(uint16_t realdev_ofp_port, int vid)
8551 {
8552     return hash_2words(realdev_ofp_port, vid);
8553 }
8554
8555 /* Returns the OFP port number of the Linux VLAN device that corresponds to
8556  * 'vlan_tci' on the network device with port number 'realdev_ofp_port' in
8557  * 'struct ofport_dpif'.  For example, given 'realdev_ofp_port' of eth0 and
8558  * 'vlan_tci' 9, it would return the port number of eth0.9.
8559  *
8560  * Unless VLAN splinters are enabled for port 'realdev_ofp_port', this
8561  * function just returns its 'realdev_ofp_port' argument. */
8562 static uint16_t
8563 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
8564                        uint16_t realdev_ofp_port, ovs_be16 vlan_tci)
8565 {
8566     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
8567         int vid = vlan_tci_to_vid(vlan_tci);
8568         const struct vlan_splinter *vsp;
8569
8570         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
8571                                  hash_realdev_vid(realdev_ofp_port, vid),
8572                                  &ofproto->realdev_vid_map) {
8573             if (vsp->realdev_ofp_port == realdev_ofp_port
8574                 && vsp->vid == vid) {
8575                 return vsp->vlandev_ofp_port;
8576             }
8577         }
8578     }
8579     return realdev_ofp_port;
8580 }
8581
8582 static struct vlan_splinter *
8583 vlandev_find(const struct ofproto_dpif *ofproto, uint16_t vlandev_ofp_port)
8584 {
8585     struct vlan_splinter *vsp;
8586
8587     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node, hash_int(vlandev_ofp_port, 0),
8588                              &ofproto->vlandev_map) {
8589         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
8590             return vsp;
8591         }
8592     }
8593
8594     return NULL;
8595 }
8596
8597 /* Returns the OpenFlow port number of the "real" device underlying the Linux
8598  * VLAN device with OpenFlow port number 'vlandev_ofp_port' and stores the
8599  * VLAN VID of the Linux VLAN device in '*vid'.  For example, given
8600  * 'vlandev_ofp_port' of eth0.9, it would return the OpenFlow port number of
8601  * eth0 and store 9 in '*vid'.
8602  *
8603  * Returns 0 and does not modify '*vid' if 'vlandev_ofp_port' is not a Linux
8604  * VLAN device.  Unless VLAN splinters are enabled, this is what this function
8605  * always does.*/
8606 static uint16_t
8607 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
8608                        uint16_t vlandev_ofp_port, int *vid)
8609 {
8610     if (!hmap_is_empty(&ofproto->vlandev_map)) {
8611         const struct vlan_splinter *vsp;
8612
8613         vsp = vlandev_find(ofproto, vlandev_ofp_port);
8614         if (vsp) {
8615             if (vid) {
8616                 *vid = vsp->vid;
8617             }
8618             return vsp->realdev_ofp_port;
8619         }
8620     }
8621     return 0;
8622 }
8623
8624 /* Given 'flow', a flow representing a packet received on 'ofproto', checks
8625  * whether 'flow->in_port' represents a Linux VLAN device.  If so, changes
8626  * 'flow->in_port' to the "real" device backing the VLAN device, sets
8627  * 'flow->vlan_tci' to the VLAN VID, and returns true.  Otherwise (which is
8628  * always the case unless VLAN splinters are enabled), returns false without
8629  * making any changes. */
8630 static bool
8631 vsp_adjust_flow(const struct ofproto_dpif *ofproto, struct flow *flow)
8632 {
8633     uint16_t realdev;
8634     int vid;
8635
8636     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port, &vid);
8637     if (!realdev) {
8638         return false;
8639     }
8640
8641     /* Cause the flow to be processed as if it came in on the real device with
8642      * the VLAN device's VLAN ID. */
8643     flow->in_port = realdev;
8644     flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
8645     return true;
8646 }
8647
8648 static void
8649 vsp_remove(struct ofport_dpif *port)
8650 {
8651     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
8652     struct vlan_splinter *vsp;
8653
8654     vsp = vlandev_find(ofproto, port->up.ofp_port);
8655     if (vsp) {
8656         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
8657         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
8658         free(vsp);
8659
8660         port->realdev_ofp_port = 0;
8661     } else {
8662         VLOG_ERR("missing vlan device record");
8663     }
8664 }
8665
8666 static void
8667 vsp_add(struct ofport_dpif *port, uint16_t realdev_ofp_port, int vid)
8668 {
8669     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
8670
8671     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
8672         && (vsp_realdev_to_vlandev(ofproto, realdev_ofp_port, htons(vid))
8673             == realdev_ofp_port)) {
8674         struct vlan_splinter *vsp;
8675
8676         vsp = xmalloc(sizeof *vsp);
8677         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
8678                     hash_int(port->up.ofp_port, 0));
8679         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
8680                     hash_realdev_vid(realdev_ofp_port, vid));
8681         vsp->realdev_ofp_port = realdev_ofp_port;
8682         vsp->vlandev_ofp_port = port->up.ofp_port;
8683         vsp->vid = vid;
8684
8685         port->realdev_ofp_port = realdev_ofp_port;
8686     } else {
8687         VLOG_ERR("duplicate vlan device record");
8688     }
8689 }
8690
8691 static uint32_t
8692 ofp_port_to_odp_port(const struct ofproto_dpif *ofproto, uint16_t ofp_port)
8693 {
8694     const struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
8695     return ofport ? ofport->odp_port : OVSP_NONE;
8696 }
8697
8698 static struct ofport_dpif *
8699 odp_port_to_ofport(const struct dpif_backer *backer, uint32_t odp_port)
8700 {
8701     struct ofport_dpif *port;
8702
8703     HMAP_FOR_EACH_IN_BUCKET (port, odp_port_node,
8704                              hash_int(odp_port, 0),
8705                              &backer->odp_to_ofport_map) {
8706         if (port->odp_port == odp_port) {
8707             return port;
8708         }
8709     }
8710
8711     return NULL;
8712 }
8713
8714 static uint16_t
8715 odp_port_to_ofp_port(const struct ofproto_dpif *ofproto, uint32_t odp_port)
8716 {
8717     struct ofport_dpif *port;
8718
8719     port = odp_port_to_ofport(ofproto->backer, odp_port);
8720     if (port && &ofproto->up == port->up.ofproto) {
8721         return port->up.ofp_port;
8722     } else {
8723         return OFPP_NONE;
8724     }
8725 }
8726 static unsigned long long int
8727 avg_subfacet_life_span(const struct ofproto_dpif *ofproto)
8728 {
8729     unsigned long long int dc;
8730     unsigned long long int avg;
8731
8732     dc = ofproto->total_subfacet_del_count + ofproto->subfacet_del_count;
8733     avg = dc ? ofproto->total_subfacet_life_span / dc : 0;
8734
8735     return avg;
8736 }
8737
8738 static double
8739 avg_subfacet_count(const struct ofproto_dpif *ofproto)
8740 {
8741     double avg_c = 0.0;
8742
8743     if (ofproto->n_update_stats) {
8744         avg_c = (double)ofproto->total_subfacet_count
8745                 / ofproto->n_update_stats;
8746     }
8747
8748     return avg_c;
8749 }
8750
8751 static void
8752 show_dp_rates(struct ds *ds, const char *heading,
8753               const struct avg_subfacet_rates *rates)
8754 {
8755     ds_put_format(ds, "%s add rate: %5.3f/min, del rate: %5.3f/min\n",
8756                   heading, rates->add_rate, rates->del_rate);
8757 }
8758
8759 static void
8760 update_max_subfacet_count(struct ofproto_dpif *ofproto)
8761 {
8762     ofproto->max_n_subfacet = MAX(ofproto->max_n_subfacet,
8763                                   hmap_count(&ofproto->subfacets));
8764 }
8765
8766 /* Compute exponentially weighted moving average, adding 'new' as the newest,
8767  * most heavily weighted element.  'base' designates the rate of decay: after
8768  * 'base' further updates, 'new''s weight in the EWMA decays to about 1/e
8769  * (about .37). */
8770 static void
8771 exp_mavg(double *avg, int base, double new)
8772 {
8773     *avg = (*avg * (base - 1) + new) / base;
8774 }
8775
8776 static void
8777 update_moving_averages(struct ofproto_dpif *ofproto)
8778 {
8779     const int min_ms = 60 * 1000; /* milliseconds in one minute. */
8780
8781     /* Update hourly averages on the minute boundaries. */
8782     if (time_msec() - ofproto->last_minute >= min_ms) {
8783         exp_mavg(&ofproto->hourly.add_rate, 60, ofproto->subfacet_add_count);
8784         exp_mavg(&ofproto->hourly.del_rate, 60, ofproto->subfacet_del_count);
8785
8786         /* Update daily averages on the hour boundaries. */
8787         if ((ofproto->last_minute - ofproto->created) / min_ms % 60 == 59) {
8788             exp_mavg(&ofproto->daily.add_rate, 24, ofproto->hourly.add_rate);
8789             exp_mavg(&ofproto->daily.del_rate, 24, ofproto->hourly.del_rate);
8790         }
8791
8792         ofproto->total_subfacet_add_count += ofproto->subfacet_add_count;
8793         ofproto->total_subfacet_del_count += ofproto->subfacet_del_count;
8794         ofproto->subfacet_add_count = 0;
8795         ofproto->subfacet_del_count = 0;
8796         ofproto->last_minute += min_ms;
8797     }
8798 }
8799
8800 const struct ofproto_class ofproto_dpif_class = {
8801     init,
8802     enumerate_types,
8803     enumerate_names,
8804     del,
8805     port_open_type,
8806     type_run,
8807     type_run_fast,
8808     type_wait,
8809     alloc,
8810     construct,
8811     destruct,
8812     dealloc,
8813     run,
8814     run_fast,
8815     wait,
8816     get_memory_usage,
8817     flush,
8818     get_features,
8819     get_tables,
8820     port_alloc,
8821     port_construct,
8822     port_destruct,
8823     port_dealloc,
8824     port_modified,
8825     port_reconfigured,
8826     port_query_by_name,
8827     port_add,
8828     port_del,
8829     port_get_stats,
8830     port_dump_start,
8831     port_dump_next,
8832     port_dump_done,
8833     port_poll,
8834     port_poll_wait,
8835     port_is_lacp_current,
8836     NULL,                       /* rule_choose_table */
8837     rule_alloc,
8838     rule_construct,
8839     rule_destruct,
8840     rule_dealloc,
8841     rule_get_stats,
8842     rule_execute,
8843     rule_modify_actions,
8844     set_frag_handling,
8845     packet_out,
8846     set_netflow,
8847     get_netflow_ids,
8848     set_sflow,
8849     set_ipfix,
8850     set_cfm,
8851     get_cfm_status,
8852     set_bfd,
8853     get_bfd_status,
8854     set_stp,
8855     get_stp_status,
8856     set_stp_port,
8857     get_stp_port_status,
8858     set_queues,
8859     bundle_set,
8860     bundle_remove,
8861     mirror_set,
8862     mirror_get_stats,
8863     set_flood_vlans,
8864     is_mirror_output_bundle,
8865     forward_bpdu_changed,
8866     set_mac_table_config,
8867     set_realdev,
8868 };