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