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