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