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