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