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