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