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