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