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