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