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