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