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