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