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