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