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