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