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