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