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