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