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