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