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