ofproto-dpif-xlate: Fix MPLS recirculation.
[cascardo/ovs.git] / ofproto / ofproto-dpif-xlate.c
1 /* Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Nicira, Inc.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License. */
14
15 #include <config.h>
16
17 #include "ofproto/ofproto-dpif-xlate.h"
18
19 #include <errno.h>
20 #include <arpa/inet.h>
21 #include <net/if.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24
25 #include "tnl-arp-cache.h"
26 #include "bfd.h"
27 #include "bitmap.h"
28 #include "bond.h"
29 #include "bundle.h"
30 #include "byte-order.h"
31 #include "cfm.h"
32 #include "connmgr.h"
33 #include "coverage.h"
34 #include "dp-packet.h"
35 #include "dpif.h"
36 #include "dynamic-string.h"
37 #include "in-band.h"
38 #include "lacp.h"
39 #include "learn.h"
40 #include "list.h"
41 #include "ovs-lldp.h"
42 #include "mac-learning.h"
43 #include "mcast-snooping.h"
44 #include "meta-flow.h"
45 #include "multipath.h"
46 #include "netdev-vport.h"
47 #include "netlink.h"
48 #include "nx-match.h"
49 #include "odp-execute.h"
50 #include "ofp-actions.h"
51 #include "ofproto/ofproto-dpif-ipfix.h"
52 #include "ofproto/ofproto-dpif-mirror.h"
53 #include "ofproto/ofproto-dpif-monitor.h"
54 #include "ofproto/ofproto-dpif-sflow.h"
55 #include "ofproto/ofproto-dpif.h"
56 #include "ofproto/ofproto-provider.h"
57 #include "ovs-router.h"
58 #include "tnl-ports.h"
59 #include "tunnel.h"
60 #include "openvswitch/vlog.h"
61
62 COVERAGE_DEFINE(xlate_actions);
63 COVERAGE_DEFINE(xlate_actions_oversize);
64 COVERAGE_DEFINE(xlate_actions_too_many_output);
65
66 VLOG_DEFINE_THIS_MODULE(ofproto_dpif_xlate);
67
68 /* Maximum depth of flow table recursion (due to resubmit actions) in a
69  * flow translation. */
70 #define MAX_RESUBMIT_RECURSION 64
71 #define MAX_INTERNAL_RESUBMITS 1   /* Max resbmits allowed using rules in
72                                       internal table. */
73
74 /* Maximum number of resubmit actions in a flow translation, whether they are
75  * recursive or not. */
76 #define MAX_RESUBMITS (MAX_RESUBMIT_RECURSION * MAX_RESUBMIT_RECURSION)
77
78 struct xbridge {
79     struct hmap_node hmap_node;   /* Node in global 'xbridges' map. */
80     struct ofproto_dpif *ofproto; /* Key in global 'xbridges' map. */
81
82     struct ovs_list xbundles;     /* Owned xbundles. */
83     struct hmap xports;           /* Indexed by ofp_port. */
84
85     char *name;                   /* Name used in log messages. */
86     struct dpif *dpif;            /* Datapath interface. */
87     struct mac_learning *ml;      /* Mac learning handle. */
88     struct mcast_snooping *ms;    /* Multicast Snooping handle. */
89     struct mbridge *mbridge;      /* Mirroring. */
90     struct dpif_sflow *sflow;     /* SFlow handle, or null. */
91     struct dpif_ipfix *ipfix;     /* Ipfix handle, or null. */
92     struct netflow *netflow;      /* Netflow handle, or null. */
93     struct stp *stp;              /* STP or null if disabled. */
94     struct rstp *rstp;            /* RSTP or null if disabled. */
95
96     bool has_in_band;             /* Bridge has in band control? */
97     bool forward_bpdu;            /* Bridge forwards STP BPDUs? */
98
99     /* True if the datapath supports recirculation. */
100     bool enable_recirc;
101
102     /* True if the datapath supports variable-length
103      * OVS_USERSPACE_ATTR_USERDATA in OVS_ACTION_ATTR_USERSPACE actions.
104      * False if the datapath supports only 8-byte (or shorter) userdata. */
105     bool variable_length_userdata;
106
107     /* Number of MPLS label stack entries that the datapath supports
108      * in matches. */
109     size_t max_mpls_depth;
110
111     /* True if the datapath supports masked data in OVS_ACTION_ATTR_SET
112      * actions. */
113     bool masked_set_action;
114 };
115
116 struct xbundle {
117     struct hmap_node hmap_node;    /* In global 'xbundles' map. */
118     struct ofbundle *ofbundle;     /* Key in global 'xbundles' map. */
119
120     struct ovs_list list_node;     /* In parent 'xbridges' list. */
121     struct xbridge *xbridge;       /* Parent xbridge. */
122
123     struct ovs_list xports;        /* Contains "struct xport"s. */
124
125     char *name;                    /* Name used in log messages. */
126     struct bond *bond;             /* Nonnull iff more than one port. */
127     struct lacp *lacp;             /* LACP handle or null. */
128
129     enum port_vlan_mode vlan_mode; /* VLAN mode. */
130     int vlan;                      /* -1=trunk port, else a 12-bit VLAN ID. */
131     unsigned long *trunks;         /* Bitmap of trunked VLANs, if 'vlan' == -1.
132                                     * NULL if all VLANs are trunked. */
133     bool use_priority_tags;        /* Use 802.1p tag for frames in VLAN 0? */
134     bool floodable;                /* No port has OFPUTIL_PC_NO_FLOOD set? */
135 };
136
137 struct xport {
138     struct hmap_node hmap_node;      /* Node in global 'xports' map. */
139     struct ofport_dpif *ofport;      /* Key in global 'xports map. */
140
141     struct hmap_node ofp_node;       /* Node in parent xbridge 'xports' map. */
142     ofp_port_t ofp_port;             /* Key in parent xbridge 'xports' map. */
143
144     odp_port_t odp_port;             /* Datapath port number or ODPP_NONE. */
145
146     struct ovs_list bundle_node;     /* In parent xbundle (if it exists). */
147     struct xbundle *xbundle;         /* Parent xbundle or null. */
148
149     struct netdev *netdev;           /* 'ofport''s netdev. */
150
151     struct xbridge *xbridge;         /* Parent bridge. */
152     struct xport *peer;              /* Patch port peer or null. */
153
154     enum ofputil_port_config config; /* OpenFlow port configuration. */
155     enum ofputil_port_state state;   /* OpenFlow port state. */
156     int stp_port_no;                 /* STP port number or -1 if not in use. */
157     struct rstp_port *rstp_port;     /* RSTP port or null. */
158
159     struct hmap skb_priorities;      /* Map of 'skb_priority_to_dscp's. */
160
161     bool may_enable;                 /* May be enabled in bonds. */
162     bool is_tunnel;                  /* Is a tunnel port. */
163
164     struct cfm *cfm;                 /* CFM handle or null. */
165     struct bfd *bfd;                 /* BFD handle or null. */
166     struct lldp *lldp;               /* LLDP handle or null. */
167 };
168
169 struct xlate_ctx {
170     struct xlate_in *xin;
171     struct xlate_out *xout;
172
173     const struct xbridge *xbridge;
174
175     /* Flow at the last commit. */
176     struct flow base_flow;
177
178     /* Tunnel IP destination address as received.  This is stored separately
179      * as the base_flow.tunnel is cleared on init to reflect the datapath
180      * behavior.  Used to make sure not to send tunneled output to ourselves,
181      * which might lead to an infinite loop.  This could happen easily
182      * if a tunnel is marked as 'ip_remote=flow', and the flow does not
183      * actually set the tun_dst field. */
184     ovs_be32 orig_tunnel_ip_dst;
185
186     /* Stack for the push and pop actions.  Each stack element is of type
187      * "union mf_subvalue". */
188     union mf_subvalue init_stack[1024 / sizeof(union mf_subvalue)];
189     struct ofpbuf stack;
190
191     /* The rule that we are currently translating, or NULL. */
192     struct rule_dpif *rule;
193
194     /* Resubmit statistics, via xlate_table_action(). */
195     int recurse;                /* Current resubmit nesting depth. */
196     int resubmits;              /* Total number of resubmits. */
197     bool in_group;              /* Currently translating ofgroup, if true. */
198     bool in_action_set;         /* Currently translating action_set, if true. */
199
200     uint8_t table_id;           /* OpenFlow table ID where flow was found. */
201     ovs_be64 rule_cookie;       /* Cookie of the rule being translated. */
202     uint32_t orig_skb_priority; /* Priority when packet arrived. */
203     uint32_t sflow_n_outputs;   /* Number of output ports. */
204     odp_port_t sflow_odp_port;  /* Output port for composing sFlow action. */
205     uint16_t user_cookie_offset;/* Used for user_action_cookie fixup. */
206     bool exit;                  /* No further actions should be processed. */
207
208    /* These are used for non-bond recirculation.  The recirculation IDs are
209     * stored in xout and must be associated with a datapath flow (ukey),
210     * otherwise they will be freed when the xout is uninitialized.
211     *
212     *
213     * Steps in Recirculation Translation
214     * ==================================
215     *
216     * At some point during translation, the code recognizes the need for
217     * recirculation.  For example, recirculation is necessary when, after
218     * popping the last MPLS label, an action or a match tries to examine or
219     * modify a field that has been newly revealed following the MPLS label.
220     *
221     * The simplest part of the work to be done is to commit existing changes to
222     * the packet, which produces datapath actions corresponding to the changes,
223     * and after this, add an OVS_ACTION_ATTR_RECIRC datapath action.
224     *
225     * The main problem here is preserving state.  When the datapath executes
226     * OVS_ACTION_ATTR_RECIRC, it will upcall to userspace to get a translation
227     * for the post-recirculation actions.  At this point userspace has to
228     * resume the translation where it left off, which means that it has to
229     * execute the following:
230     *
231     *     - The action that prompted recirculation, and any actions following
232     *       it within the same flow.
233     *
234     *     - If the action that prompted recirculation was invoked within a
235     *       NXAST_RESUBMIT, then any actions following the resubmit.  These
236     *       "resubmit"s can be nested, so this has to go all the way up the
237     *       control stack.
238     *
239     *     - The OpenFlow 1.1+ action set.
240     *
241     * State that actions and flow table lookups can depend on, such as the
242     * following, must also be preserved:
243     *
244     *     - Metadata fields (input port, registers, OF1.1+ metadata, ...).
245     *
246     *     - Action set, stack
247     *
248     *     - The table ID and cookie of the flow being translated at each level
249     *       of the control stack (since OFPAT_CONTROLLER actions send these to
250     *       the controller).
251     *
252     * Translation allows for the control of this state preservation via these
253     * members.  When a need for recirculation is identified, the translation
254     * process:
255     *
256     * 1. Sets 'recirc_action_offset' to the current size of 'action_set'.  The
257     *    action set is part of what needs to be preserved, so this allows the
258     *    action set and the additional state to share the 'action_set' buffer.
259     *    Later steps can tell that setup for recirculation is in progress from
260     *    the nonnegative value of 'recirc_action_offset'.
261     *
262     * 2. Sets 'exit' to true to tell later steps that we're exiting from the
263     *    translation process.
264     *
265     * 3. Adds an OFPACT_UNROLL_XLATE action to 'action_set'.  This action
266     *    holds the current table ID and cookie so that they can be restored
267     *    during a post-recirculation upcall translation.
268     *
269     * 4. Adds the action that prompted recirculation and any actions following
270     *    it within the same flow to 'action_set', so that they can be executed
271     *    during a post-recirculation upcall translation.
272     *
273     * 5. Returns.
274     *
275     * 6. The action that prompted recirculation might be nested in a stack of
276     *    nested "resubmit"s that have actions remaining.  Each of these notices
277     *    that we're exiting (from 'exit') and that recirculation setup is in
278     *    progress (from 'recirc_action_offset') and responds by adding more
279     *    OFPACT_UNROLL_XLATE actions to 'action_set', as necessary, and any
280     *    actions that were yet unprocessed.
281     *
282     * The caller stores all the state produced by this process associated with
283     * the recirculation ID.  For post-recirculation upcall translation, the
284     * caller passes it back in for the new translation to execute.  The
285     * process yielded a set of ofpacts that can be translated directly, so it
286     * is not much of a special case at that point.
287     */
288     int recirc_action_offset;   /* Offset in 'action_set' to actions to be
289                                  * executed after recirculation, or -1. */
290     int last_unroll_offset;     /* Offset in 'action_set' to the latest unroll
291                                  * action, or -1. */
292
293     /* True if a packet was but is no longer MPLS (due to an MPLS pop action).
294      * This is a trigger for recirculation in cases where translating an action
295      * or looking up a flow requires access to the fields of the packet after
296      * the MPLS label stack that was originally present. */
297     bool was_mpls;
298
299     /* OpenFlow 1.1+ action set.
300      *
301      * 'action_set' accumulates "struct ofpact"s added by OFPACT_WRITE_ACTIONS.
302      * When translation is otherwise complete, ofpacts_execute_action_set()
303      * converts it to a set of "struct ofpact"s that can be translated into
304      * datapath actions. */
305     bool action_set_has_group;  /* Action set contains OFPACT_GROUP? */
306     struct ofpbuf action_set;   /* Action set. */
307     uint64_t action_set_stub[1024 / 8];
308 };
309
310 static void xlate_action_set(struct xlate_ctx *ctx);
311
312 static void
313 ctx_trigger_recirculation(struct xlate_ctx *ctx)
314 {
315     ctx->exit = true;
316     ctx->recirc_action_offset = ctx->action_set.size;
317 }
318
319 static bool
320 ctx_first_recirculation_action(const struct xlate_ctx *ctx)
321 {
322     return ctx->recirc_action_offset == ctx->action_set.size;
323 }
324
325 static inline bool
326 exit_recirculates(const struct xlate_ctx *ctx)
327 {
328     /* When recirculating the 'recirc_action_offset' has a non-negative value.
329      */
330     return ctx->recirc_action_offset >= 0;
331 }
332
333 static void compose_recirculate_action(struct xlate_ctx *ctx);
334
335 /* A controller may use OFPP_NONE as the ingress port to indicate that
336  * it did not arrive on a "real" port.  'ofpp_none_bundle' exists for
337  * when an input bundle is needed for validation (e.g., mirroring or
338  * OFPP_NORMAL processing).  It is not connected to an 'ofproto' or have
339  * any 'port' structs, so care must be taken when dealing with it. */
340 static struct xbundle ofpp_none_bundle = {
341     .name      = "OFPP_NONE",
342     .vlan_mode = PORT_VLAN_TRUNK
343 };
344
345 /* Node in 'xport''s 'skb_priorities' map.  Used to maintain a map from
346  * 'priority' (the datapath's term for QoS queue) to the dscp bits which all
347  * traffic egressing the 'ofport' with that priority should be marked with. */
348 struct skb_priority_to_dscp {
349     struct hmap_node hmap_node; /* Node in 'ofport_dpif''s 'skb_priorities'. */
350     uint32_t skb_priority;      /* Priority of this queue (see struct flow). */
351
352     uint8_t dscp;               /* DSCP bits to mark outgoing traffic with. */
353 };
354
355 enum xc_type {
356     XC_RULE,
357     XC_BOND,
358     XC_NETDEV,
359     XC_NETFLOW,
360     XC_MIRROR,
361     XC_LEARN,
362     XC_NORMAL,
363     XC_FIN_TIMEOUT,
364     XC_GROUP,
365     XC_TNL_ARP,
366 };
367
368 /* xlate_cache entries hold enough information to perform the side effects of
369  * xlate_actions() for a rule, without needing to perform rule translation
370  * from scratch. The primary usage of these is to submit statistics to objects
371  * that a flow relates to, although they may be used for other effects as well
372  * (for instance, refreshing hard timeouts for learned flows). */
373 struct xc_entry {
374     enum xc_type type;
375     union {
376         struct rule_dpif *rule;
377         struct {
378             struct netdev *tx;
379             struct netdev *rx;
380             struct bfd *bfd;
381         } dev;
382         struct {
383             struct netflow *netflow;
384             struct flow *flow;
385             ofp_port_t iface;
386         } nf;
387         struct {
388             struct mbridge *mbridge;
389             mirror_mask_t mirrors;
390         } mirror;
391         struct {
392             struct bond *bond;
393             struct flow *flow;
394             uint16_t vid;
395         } bond;
396         struct {
397             struct ofproto_dpif *ofproto;
398             struct ofputil_flow_mod *fm;
399             struct ofpbuf *ofpacts;
400         } learn;
401         struct {
402             struct ofproto_dpif *ofproto;
403             struct flow *flow;
404             int vlan;
405         } normal;
406         struct {
407             struct rule_dpif *rule;
408             uint16_t idle;
409             uint16_t hard;
410         } fin;
411         struct {
412             struct group_dpif *group;
413             struct ofputil_bucket *bucket;
414         } group;
415         struct {
416             char br_name[IFNAMSIZ];
417             ovs_be32 d_ip;
418         } tnl_arp_cache;
419     } u;
420 };
421
422 #define XC_ENTRY_FOR_EACH(entry, entries, xcache)               \
423     entries = xcache->entries;                                  \
424     for (entry = ofpbuf_try_pull(&entries, sizeof *entry);      \
425          entry;                                                 \
426          entry = ofpbuf_try_pull(&entries, sizeof *entry))
427
428 struct xlate_cache {
429     struct ofpbuf entries;
430 };
431
432 /* Xlate config contains hash maps of all bridges, bundles and ports.
433  * Xcfgp contains the pointer to the current xlate configuration.
434  * When the main thread needs to change the configuration, it copies xcfgp to
435  * new_xcfg and edits new_xcfg. This enables the use of RCU locking which
436  * does not block handler and revalidator threads. */
437 struct xlate_cfg {
438     struct hmap xbridges;
439     struct hmap xbundles;
440     struct hmap xports;
441 };
442 static OVSRCU_TYPE(struct xlate_cfg *) xcfgp = OVSRCU_INITIALIZER(NULL);
443 static struct xlate_cfg *new_xcfg = NULL;
444
445 static bool may_receive(const struct xport *, struct xlate_ctx *);
446 static void do_xlate_actions(const struct ofpact *, size_t ofpacts_len,
447                              struct xlate_ctx *);
448 static void xlate_normal(struct xlate_ctx *);
449 static inline void xlate_report(struct xlate_ctx *, const char *);
450 static void xlate_table_action(struct xlate_ctx *, ofp_port_t in_port,
451                                uint8_t table_id, bool may_packet_in,
452                                bool honor_table_miss);
453 static bool input_vid_is_valid(uint16_t vid, struct xbundle *, bool warn);
454 static uint16_t input_vid_to_vlan(const struct xbundle *, uint16_t vid);
455 static void output_normal(struct xlate_ctx *, const struct xbundle *,
456                           uint16_t vlan);
457
458 /* Optional bond recirculation parameter to compose_output_action(). */
459 struct xlate_bond_recirc {
460     uint32_t recirc_id;  /* !0 Use recirculation instead of output. */
461     uint8_t  hash_alg;   /* !0 Compute hash for recirc before. */
462     uint32_t hash_basis;  /* Compute hash for recirc before. */
463 };
464
465 static void compose_output_action(struct xlate_ctx *, ofp_port_t ofp_port,
466                                   const struct xlate_bond_recirc *xr);
467
468 static struct xbridge *xbridge_lookup(struct xlate_cfg *,
469                                       const struct ofproto_dpif *);
470 static struct xbundle *xbundle_lookup(struct xlate_cfg *,
471                                       const struct ofbundle *);
472 static struct xport *xport_lookup(struct xlate_cfg *,
473                                   const struct ofport_dpif *);
474 static struct xport *get_ofp_port(const struct xbridge *, ofp_port_t ofp_port);
475 static struct skb_priority_to_dscp *get_skb_priority(const struct xport *,
476                                                      uint32_t skb_priority);
477 static void clear_skb_priorities(struct xport *);
478 static size_t count_skb_priorities(const struct xport *);
479 static bool dscp_from_skb_priority(const struct xport *, uint32_t skb_priority,
480                                    uint8_t *dscp);
481
482 static struct xc_entry *xlate_cache_add_entry(struct xlate_cache *xc,
483                                               enum xc_type type);
484 static void xlate_xbridge_init(struct xlate_cfg *, struct xbridge *);
485 static void xlate_xbundle_init(struct xlate_cfg *, struct xbundle *);
486 static void xlate_xport_init(struct xlate_cfg *, struct xport *);
487 static void xlate_xbridge_set(struct xbridge *, struct dpif *,
488                               const struct mac_learning *, struct stp *,
489                               struct rstp *, const struct mcast_snooping *,
490                               const struct mbridge *,
491                               const struct dpif_sflow *,
492                               const struct dpif_ipfix *,
493                               const struct netflow *,
494                               bool forward_bpdu, bool has_in_band,
495                               bool enable_recirc,
496                               bool variable_length_userdata,
497                               size_t max_mpls_depth,
498                               bool masked_set_action);
499 static void xlate_xbundle_set(struct xbundle *xbundle,
500                               enum port_vlan_mode vlan_mode, int vlan,
501                               unsigned long *trunks, bool use_priority_tags,
502                               const struct bond *bond, const struct lacp *lacp,
503                               bool floodable);
504 static void xlate_xport_set(struct xport *xport, odp_port_t odp_port,
505                             const struct netdev *netdev, const struct cfm *cfm,
506                             const struct bfd *bfd, const struct lldp *lldp,
507                             int stp_port_no, const struct rstp_port *rstp_port,
508                             enum ofputil_port_config config,
509                             enum ofputil_port_state state, bool is_tunnel,
510                             bool may_enable);
511 static void xlate_xbridge_remove(struct xlate_cfg *, struct xbridge *);
512 static void xlate_xbundle_remove(struct xlate_cfg *, struct xbundle *);
513 static void xlate_xport_remove(struct xlate_cfg *, struct xport *);
514 static void xlate_xbridge_copy(struct xbridge *);
515 static void xlate_xbundle_copy(struct xbridge *, struct xbundle *);
516 static void xlate_xport_copy(struct xbridge *, struct xbundle *,
517                              struct xport *);
518 static void xlate_xcfg_free(struct xlate_cfg *);
519
520 static inline void
521 xlate_report(struct xlate_ctx *ctx, const char *s)
522 {
523     if (OVS_UNLIKELY(ctx->xin->report_hook)) {
524         ctx->xin->report_hook(ctx->xin, s, ctx->recurse);
525     }
526 }
527
528 static void
529 xlate_xbridge_init(struct xlate_cfg *xcfg, struct xbridge *xbridge)
530 {
531     list_init(&xbridge->xbundles);
532     hmap_init(&xbridge->xports);
533     hmap_insert(&xcfg->xbridges, &xbridge->hmap_node,
534                 hash_pointer(xbridge->ofproto, 0));
535 }
536
537 static void
538 xlate_xbundle_init(struct xlate_cfg *xcfg, struct xbundle *xbundle)
539 {
540     list_init(&xbundle->xports);
541     list_insert(&xbundle->xbridge->xbundles, &xbundle->list_node);
542     hmap_insert(&xcfg->xbundles, &xbundle->hmap_node,
543                 hash_pointer(xbundle->ofbundle, 0));
544 }
545
546 static void
547 xlate_xport_init(struct xlate_cfg *xcfg, struct xport *xport)
548 {
549     hmap_init(&xport->skb_priorities);
550     hmap_insert(&xcfg->xports, &xport->hmap_node,
551                 hash_pointer(xport->ofport, 0));
552     hmap_insert(&xport->xbridge->xports, &xport->ofp_node,
553                 hash_ofp_port(xport->ofp_port));
554 }
555
556 static void
557 xlate_xbridge_set(struct xbridge *xbridge,
558                   struct dpif *dpif,
559                   const struct mac_learning *ml, struct stp *stp,
560                   struct rstp *rstp, const struct mcast_snooping *ms,
561                   const struct mbridge *mbridge,
562                   const struct dpif_sflow *sflow,
563                   const struct dpif_ipfix *ipfix,
564                   const struct netflow *netflow,
565                   bool forward_bpdu, bool has_in_band,
566                   bool enable_recirc,
567                   bool variable_length_userdata,
568                   size_t max_mpls_depth,
569                   bool masked_set_action)
570 {
571     if (xbridge->ml != ml) {
572         mac_learning_unref(xbridge->ml);
573         xbridge->ml = mac_learning_ref(ml);
574     }
575
576     if (xbridge->ms != ms) {
577         mcast_snooping_unref(xbridge->ms);
578         xbridge->ms = mcast_snooping_ref(ms);
579     }
580
581     if (xbridge->mbridge != mbridge) {
582         mbridge_unref(xbridge->mbridge);
583         xbridge->mbridge = mbridge_ref(mbridge);
584     }
585
586     if (xbridge->sflow != sflow) {
587         dpif_sflow_unref(xbridge->sflow);
588         xbridge->sflow = dpif_sflow_ref(sflow);
589     }
590
591     if (xbridge->ipfix != ipfix) {
592         dpif_ipfix_unref(xbridge->ipfix);
593         xbridge->ipfix = dpif_ipfix_ref(ipfix);
594     }
595
596     if (xbridge->stp != stp) {
597         stp_unref(xbridge->stp);
598         xbridge->stp = stp_ref(stp);
599     }
600
601     if (xbridge->rstp != rstp) {
602         rstp_unref(xbridge->rstp);
603         xbridge->rstp = rstp_ref(rstp);
604     }
605
606     if (xbridge->netflow != netflow) {
607         netflow_unref(xbridge->netflow);
608         xbridge->netflow = netflow_ref(netflow);
609     }
610
611     xbridge->dpif = dpif;
612     xbridge->forward_bpdu = forward_bpdu;
613     xbridge->has_in_band = has_in_band;
614     xbridge->enable_recirc = enable_recirc;
615     xbridge->variable_length_userdata = variable_length_userdata;
616     xbridge->max_mpls_depth = max_mpls_depth;
617     xbridge->masked_set_action = masked_set_action;
618 }
619
620 static void
621 xlate_xbundle_set(struct xbundle *xbundle,
622                   enum port_vlan_mode vlan_mode, int vlan,
623                   unsigned long *trunks, bool use_priority_tags,
624                   const struct bond *bond, const struct lacp *lacp,
625                   bool floodable)
626 {
627     ovs_assert(xbundle->xbridge);
628
629     xbundle->vlan_mode = vlan_mode;
630     xbundle->vlan = vlan;
631     xbundle->trunks = trunks;
632     xbundle->use_priority_tags = use_priority_tags;
633     xbundle->floodable = floodable;
634
635     if (xbundle->bond != bond) {
636         bond_unref(xbundle->bond);
637         xbundle->bond = bond_ref(bond);
638     }
639
640     if (xbundle->lacp != lacp) {
641         lacp_unref(xbundle->lacp);
642         xbundle->lacp = lacp_ref(lacp);
643     }
644 }
645
646 static void
647 xlate_xport_set(struct xport *xport, odp_port_t odp_port,
648                 const struct netdev *netdev, const struct cfm *cfm,
649                 const struct bfd *bfd, const struct lldp *lldp, int stp_port_no,
650                 const struct rstp_port* rstp_port,
651                 enum ofputil_port_config config, enum ofputil_port_state state,
652                 bool is_tunnel, bool may_enable)
653 {
654     xport->config = config;
655     xport->state = state;
656     xport->stp_port_no = stp_port_no;
657     xport->is_tunnel = is_tunnel;
658     xport->may_enable = may_enable;
659     xport->odp_port = odp_port;
660
661     if (xport->rstp_port != rstp_port) {
662         rstp_port_unref(xport->rstp_port);
663         xport->rstp_port = rstp_port_ref(rstp_port);
664     }
665
666     if (xport->cfm != cfm) {
667         cfm_unref(xport->cfm);
668         xport->cfm = cfm_ref(cfm);
669     }
670
671     if (xport->bfd != bfd) {
672         bfd_unref(xport->bfd);
673         xport->bfd = bfd_ref(bfd);
674     }
675
676     if (xport->lldp != lldp) {
677         lldp_unref(xport->lldp);
678         xport->lldp = lldp_ref(lldp);
679     }
680
681     if (xport->netdev != netdev) {
682         netdev_close(xport->netdev);
683         xport->netdev = netdev_ref(netdev);
684     }
685 }
686
687 static void
688 xlate_xbridge_copy(struct xbridge *xbridge)
689 {
690     struct xbundle *xbundle;
691     struct xport *xport;
692     struct xbridge *new_xbridge = xzalloc(sizeof *xbridge);
693     new_xbridge->ofproto = xbridge->ofproto;
694     new_xbridge->name = xstrdup(xbridge->name);
695     xlate_xbridge_init(new_xcfg, new_xbridge);
696
697     xlate_xbridge_set(new_xbridge,
698                       xbridge->dpif, xbridge->ml, xbridge->stp,
699                       xbridge->rstp, xbridge->ms, xbridge->mbridge,
700                       xbridge->sflow, xbridge->ipfix, xbridge->netflow,
701                       xbridge->forward_bpdu,
702                       xbridge->has_in_band, xbridge->enable_recirc,
703                       xbridge->variable_length_userdata,
704                       xbridge->max_mpls_depth, xbridge->masked_set_action);
705     LIST_FOR_EACH (xbundle, list_node, &xbridge->xbundles) {
706         xlate_xbundle_copy(new_xbridge, xbundle);
707     }
708
709     /* Copy xports which are not part of a xbundle */
710     HMAP_FOR_EACH (xport, ofp_node, &xbridge->xports) {
711         if (!xport->xbundle) {
712             xlate_xport_copy(new_xbridge, NULL, xport);
713         }
714     }
715 }
716
717 static void
718 xlate_xbundle_copy(struct xbridge *xbridge, struct xbundle *xbundle)
719 {
720     struct xport *xport;
721     struct xbundle *new_xbundle = xzalloc(sizeof *xbundle);
722     new_xbundle->ofbundle = xbundle->ofbundle;
723     new_xbundle->xbridge = xbridge;
724     new_xbundle->name = xstrdup(xbundle->name);
725     xlate_xbundle_init(new_xcfg, new_xbundle);
726
727     xlate_xbundle_set(new_xbundle, xbundle->vlan_mode,
728                       xbundle->vlan, xbundle->trunks,
729                       xbundle->use_priority_tags, xbundle->bond, xbundle->lacp,
730                       xbundle->floodable);
731     LIST_FOR_EACH (xport, bundle_node, &xbundle->xports) {
732         xlate_xport_copy(xbridge, new_xbundle, xport);
733     }
734 }
735
736 static void
737 xlate_xport_copy(struct xbridge *xbridge, struct xbundle *xbundle,
738                  struct xport *xport)
739 {
740     struct skb_priority_to_dscp *pdscp, *new_pdscp;
741     struct xport *new_xport = xzalloc(sizeof *xport);
742     new_xport->ofport = xport->ofport;
743     new_xport->ofp_port = xport->ofp_port;
744     new_xport->xbridge = xbridge;
745     xlate_xport_init(new_xcfg, new_xport);
746
747     xlate_xport_set(new_xport, xport->odp_port, xport->netdev, xport->cfm,
748                     xport->bfd, xport->lldp, xport->stp_port_no,
749                     xport->rstp_port, xport->config, xport->state,
750                     xport->is_tunnel, xport->may_enable);
751
752     if (xport->peer) {
753         struct xport *peer = xport_lookup(new_xcfg, xport->peer->ofport);
754         if (peer) {
755             new_xport->peer = peer;
756             new_xport->peer->peer = new_xport;
757         }
758     }
759
760     if (xbundle) {
761         new_xport->xbundle = xbundle;
762         list_insert(&new_xport->xbundle->xports, &new_xport->bundle_node);
763     }
764
765     HMAP_FOR_EACH (pdscp, hmap_node, &xport->skb_priorities) {
766         new_pdscp = xmalloc(sizeof *pdscp);
767         new_pdscp->skb_priority = pdscp->skb_priority;
768         new_pdscp->dscp = pdscp->dscp;
769         hmap_insert(&new_xport->skb_priorities, &new_pdscp->hmap_node,
770                     hash_int(new_pdscp->skb_priority, 0));
771     }
772 }
773
774 /* Sets the current xlate configuration to new_xcfg and frees the old xlate
775  * configuration in xcfgp.
776  *
777  * This needs to be called after editing the xlate configuration.
778  *
779  * Functions that edit the new xlate configuration are
780  * xlate_<ofport/bundle/ofport>_set and xlate_<ofport/bundle/ofport>_remove.
781  *
782  * A sample workflow:
783  *
784  * xlate_txn_start();
785  * ...
786  * edit_xlate_configuration();
787  * ...
788  * xlate_txn_commit(); */
789 void
790 xlate_txn_commit(void)
791 {
792     struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
793
794     ovsrcu_set(&xcfgp, new_xcfg);
795     ovsrcu_synchronize();
796     xlate_xcfg_free(xcfg);
797     new_xcfg = NULL;
798 }
799
800 /* Copies the current xlate configuration in xcfgp to new_xcfg.
801  *
802  * This needs to be called prior to editing the xlate configuration. */
803 void
804 xlate_txn_start(void)
805 {
806     struct xbridge *xbridge;
807     struct xlate_cfg *xcfg;
808
809     ovs_assert(!new_xcfg);
810
811     new_xcfg = xmalloc(sizeof *new_xcfg);
812     hmap_init(&new_xcfg->xbridges);
813     hmap_init(&new_xcfg->xbundles);
814     hmap_init(&new_xcfg->xports);
815
816     xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
817     if (!xcfg) {
818         return;
819     }
820
821     HMAP_FOR_EACH (xbridge, hmap_node, &xcfg->xbridges) {
822         xlate_xbridge_copy(xbridge);
823     }
824 }
825
826
827 static void
828 xlate_xcfg_free(struct xlate_cfg *xcfg)
829 {
830     struct xbridge *xbridge, *next_xbridge;
831
832     if (!xcfg) {
833         return;
834     }
835
836     HMAP_FOR_EACH_SAFE (xbridge, next_xbridge, hmap_node, &xcfg->xbridges) {
837         xlate_xbridge_remove(xcfg, xbridge);
838     }
839
840     hmap_destroy(&xcfg->xbridges);
841     hmap_destroy(&xcfg->xbundles);
842     hmap_destroy(&xcfg->xports);
843     free(xcfg);
844 }
845
846 void
847 xlate_ofproto_set(struct ofproto_dpif *ofproto, const char *name,
848                   struct dpif *dpif,
849                   const struct mac_learning *ml, struct stp *stp,
850                   struct rstp *rstp, const struct mcast_snooping *ms,
851                   const struct mbridge *mbridge,
852                   const struct dpif_sflow *sflow,
853                   const struct dpif_ipfix *ipfix,
854                   const struct netflow *netflow,
855                   bool forward_bpdu, bool has_in_band, bool enable_recirc,
856                   bool variable_length_userdata, size_t max_mpls_depth,
857                   bool masked_set_action)
858 {
859     struct xbridge *xbridge;
860
861     ovs_assert(new_xcfg);
862
863     xbridge = xbridge_lookup(new_xcfg, ofproto);
864     if (!xbridge) {
865         xbridge = xzalloc(sizeof *xbridge);
866         xbridge->ofproto = ofproto;
867
868         xlate_xbridge_init(new_xcfg, xbridge);
869     }
870
871     free(xbridge->name);
872     xbridge->name = xstrdup(name);
873
874     xlate_xbridge_set(xbridge, dpif, ml, stp, rstp, ms, mbridge, sflow, ipfix,
875                       netflow, forward_bpdu, has_in_band, enable_recirc,
876                       variable_length_userdata, max_mpls_depth,
877                       masked_set_action);
878 }
879
880 static void
881 xlate_xbridge_remove(struct xlate_cfg *xcfg, struct xbridge *xbridge)
882 {
883     struct xbundle *xbundle, *next_xbundle;
884     struct xport *xport, *next_xport;
885
886     if (!xbridge) {
887         return;
888     }
889
890     HMAP_FOR_EACH_SAFE (xport, next_xport, ofp_node, &xbridge->xports) {
891         xlate_xport_remove(xcfg, xport);
892     }
893
894     LIST_FOR_EACH_SAFE (xbundle, next_xbundle, list_node, &xbridge->xbundles) {
895         xlate_xbundle_remove(xcfg, xbundle);
896     }
897
898     hmap_remove(&xcfg->xbridges, &xbridge->hmap_node);
899     mac_learning_unref(xbridge->ml);
900     mcast_snooping_unref(xbridge->ms);
901     mbridge_unref(xbridge->mbridge);
902     dpif_sflow_unref(xbridge->sflow);
903     dpif_ipfix_unref(xbridge->ipfix);
904     stp_unref(xbridge->stp);
905     rstp_unref(xbridge->rstp);
906     hmap_destroy(&xbridge->xports);
907     free(xbridge->name);
908     free(xbridge);
909 }
910
911 void
912 xlate_remove_ofproto(struct ofproto_dpif *ofproto)
913 {
914     struct xbridge *xbridge;
915
916     ovs_assert(new_xcfg);
917
918     xbridge = xbridge_lookup(new_xcfg, ofproto);
919     xlate_xbridge_remove(new_xcfg, xbridge);
920 }
921
922 void
923 xlate_bundle_set(struct ofproto_dpif *ofproto, struct ofbundle *ofbundle,
924                  const char *name, enum port_vlan_mode vlan_mode, int vlan,
925                  unsigned long *trunks, bool use_priority_tags,
926                  const struct bond *bond, const struct lacp *lacp,
927                  bool floodable)
928 {
929     struct xbundle *xbundle;
930
931     ovs_assert(new_xcfg);
932
933     xbundle = xbundle_lookup(new_xcfg, ofbundle);
934     if (!xbundle) {
935         xbundle = xzalloc(sizeof *xbundle);
936         xbundle->ofbundle = ofbundle;
937         xbundle->xbridge = xbridge_lookup(new_xcfg, ofproto);
938
939         xlate_xbundle_init(new_xcfg, xbundle);
940     }
941
942     free(xbundle->name);
943     xbundle->name = xstrdup(name);
944
945     xlate_xbundle_set(xbundle, vlan_mode, vlan, trunks,
946                       use_priority_tags, bond, lacp, floodable);
947 }
948
949 static void
950 xlate_xbundle_remove(struct xlate_cfg *xcfg, struct xbundle *xbundle)
951 {
952     struct xport *xport, *next;
953
954     if (!xbundle) {
955         return;
956     }
957
958     LIST_FOR_EACH_SAFE (xport, next, bundle_node, &xbundle->xports) {
959         list_remove(&xport->bundle_node);
960         xport->xbundle = NULL;
961     }
962
963     hmap_remove(&xcfg->xbundles, &xbundle->hmap_node);
964     list_remove(&xbundle->list_node);
965     bond_unref(xbundle->bond);
966     lacp_unref(xbundle->lacp);
967     free(xbundle->name);
968     free(xbundle);
969 }
970
971 void
972 xlate_bundle_remove(struct ofbundle *ofbundle)
973 {
974     struct xbundle *xbundle;
975
976     ovs_assert(new_xcfg);
977
978     xbundle = xbundle_lookup(new_xcfg, ofbundle);
979     xlate_xbundle_remove(new_xcfg, xbundle);
980 }
981
982 void
983 xlate_ofport_set(struct ofproto_dpif *ofproto, struct ofbundle *ofbundle,
984                  struct ofport_dpif *ofport, ofp_port_t ofp_port,
985                  odp_port_t odp_port, const struct netdev *netdev,
986                  const struct cfm *cfm, const struct bfd *bfd,
987                  const struct lldp *lldp, struct ofport_dpif *peer,
988                  int stp_port_no, const struct rstp_port *rstp_port,
989                  const struct ofproto_port_queue *qdscp_list, size_t n_qdscp,
990                  enum ofputil_port_config config,
991                  enum ofputil_port_state state, bool is_tunnel,
992                  bool may_enable)
993 {
994     size_t i;
995     struct xport *xport;
996
997     ovs_assert(new_xcfg);
998
999     xport = xport_lookup(new_xcfg, ofport);
1000     if (!xport) {
1001         xport = xzalloc(sizeof *xport);
1002         xport->ofport = ofport;
1003         xport->xbridge = xbridge_lookup(new_xcfg, ofproto);
1004         xport->ofp_port = ofp_port;
1005
1006         xlate_xport_init(new_xcfg, xport);
1007     }
1008
1009     ovs_assert(xport->ofp_port == ofp_port);
1010
1011     xlate_xport_set(xport, odp_port, netdev, cfm, bfd, lldp,
1012                     stp_port_no, rstp_port, config, state, is_tunnel,
1013                     may_enable);
1014
1015     if (xport->peer) {
1016         xport->peer->peer = NULL;
1017     }
1018     xport->peer = xport_lookup(new_xcfg, peer);
1019     if (xport->peer) {
1020         xport->peer->peer = xport;
1021     }
1022
1023     if (xport->xbundle) {
1024         list_remove(&xport->bundle_node);
1025     }
1026     xport->xbundle = xbundle_lookup(new_xcfg, ofbundle);
1027     if (xport->xbundle) {
1028         list_insert(&xport->xbundle->xports, &xport->bundle_node);
1029     }
1030
1031     clear_skb_priorities(xport);
1032     for (i = 0; i < n_qdscp; i++) {
1033         struct skb_priority_to_dscp *pdscp;
1034         uint32_t skb_priority;
1035
1036         if (dpif_queue_to_priority(xport->xbridge->dpif, qdscp_list[i].queue,
1037                                    &skb_priority)) {
1038             continue;
1039         }
1040
1041         pdscp = xmalloc(sizeof *pdscp);
1042         pdscp->skb_priority = skb_priority;
1043         pdscp->dscp = (qdscp_list[i].dscp << 2) & IP_DSCP_MASK;
1044         hmap_insert(&xport->skb_priorities, &pdscp->hmap_node,
1045                     hash_int(pdscp->skb_priority, 0));
1046     }
1047 }
1048
1049 static void
1050 xlate_xport_remove(struct xlate_cfg *xcfg, struct xport *xport)
1051 {
1052     if (!xport) {
1053         return;
1054     }
1055
1056     if (xport->peer) {
1057         xport->peer->peer = NULL;
1058         xport->peer = NULL;
1059     }
1060
1061     if (xport->xbundle) {
1062         list_remove(&xport->bundle_node);
1063     }
1064
1065     clear_skb_priorities(xport);
1066     hmap_destroy(&xport->skb_priorities);
1067
1068     hmap_remove(&xcfg->xports, &xport->hmap_node);
1069     hmap_remove(&xport->xbridge->xports, &xport->ofp_node);
1070
1071     netdev_close(xport->netdev);
1072     rstp_port_unref(xport->rstp_port);
1073     cfm_unref(xport->cfm);
1074     bfd_unref(xport->bfd);
1075     lldp_unref(xport->lldp);
1076     free(xport);
1077 }
1078
1079 void
1080 xlate_ofport_remove(struct ofport_dpif *ofport)
1081 {
1082     struct xport *xport;
1083
1084     ovs_assert(new_xcfg);
1085
1086     xport = xport_lookup(new_xcfg, ofport);
1087     xlate_xport_remove(new_xcfg, xport);
1088 }
1089
1090 static struct ofproto_dpif *
1091 xlate_lookup_ofproto_(const struct dpif_backer *backer, const struct flow *flow,
1092                       ofp_port_t *ofp_in_port, const struct xport **xportp)
1093 {
1094     struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
1095     const struct xport *xport;
1096
1097     xport = xport_lookup(xcfg, tnl_port_should_receive(flow)
1098                          ? tnl_port_receive(flow)
1099                          : odp_port_to_ofport(backer, flow->in_port.odp_port));
1100     if (OVS_UNLIKELY(!xport)) {
1101         return NULL;
1102     }
1103     *xportp = xport;
1104     if (ofp_in_port) {
1105         *ofp_in_port = xport->ofp_port;
1106     }
1107     return xport->xbridge->ofproto;
1108 }
1109
1110 /* Given a datapath and flow metadata ('backer', and 'flow' respectively)
1111  * returns the corresponding struct ofproto_dpif and OpenFlow port number. */
1112 struct ofproto_dpif *
1113 xlate_lookup_ofproto(const struct dpif_backer *backer, const struct flow *flow,
1114                      ofp_port_t *ofp_in_port)
1115 {
1116     const struct xport *xport;
1117
1118     return xlate_lookup_ofproto_(backer, flow, ofp_in_port, &xport);
1119 }
1120
1121 /* Given a datapath and flow metadata ('backer', and 'flow' respectively),
1122  * optionally populates 'ofproto' with the ofproto_dpif, 'ofp_in_port' with the
1123  * openflow in_port, and 'ipfix', 'sflow', and 'netflow' with the appropriate
1124  * handles for those protocols if they're enabled.  Caller may use the returned
1125  * pointers until quiescing, for longer term use additional references must
1126  * be taken.
1127  *
1128  * Returns 0 if successful, ENODEV if the parsed flow has no associated ofproto.
1129  */
1130 int
1131 xlate_lookup(const struct dpif_backer *backer, const struct flow *flow,
1132              struct ofproto_dpif **ofprotop, struct dpif_ipfix **ipfix,
1133              struct dpif_sflow **sflow, struct netflow **netflow,
1134              ofp_port_t *ofp_in_port)
1135 {
1136     struct ofproto_dpif *ofproto;
1137     const struct xport *xport;
1138
1139     ofproto = xlate_lookup_ofproto_(backer, flow, ofp_in_port, &xport);
1140
1141     if (!ofproto) {
1142         return ENODEV;
1143     }
1144
1145     if (ofprotop) {
1146         *ofprotop = ofproto;
1147     }
1148
1149     if (ipfix) {
1150         *ipfix = xport ? xport->xbridge->ipfix : NULL;
1151     }
1152
1153     if (sflow) {
1154         *sflow = xport ? xport->xbridge->sflow : NULL;
1155     }
1156
1157     if (netflow) {
1158         *netflow = xport ? xport->xbridge->netflow : NULL;
1159     }
1160
1161     return 0;
1162 }
1163
1164 static struct xbridge *
1165 xbridge_lookup(struct xlate_cfg *xcfg, const struct ofproto_dpif *ofproto)
1166 {
1167     struct hmap *xbridges;
1168     struct xbridge *xbridge;
1169
1170     if (!ofproto || !xcfg) {
1171         return NULL;
1172     }
1173
1174     xbridges = &xcfg->xbridges;
1175
1176     HMAP_FOR_EACH_IN_BUCKET (xbridge, hmap_node, hash_pointer(ofproto, 0),
1177                              xbridges) {
1178         if (xbridge->ofproto == ofproto) {
1179             return xbridge;
1180         }
1181     }
1182     return NULL;
1183 }
1184
1185 static struct xbundle *
1186 xbundle_lookup(struct xlate_cfg *xcfg, const struct ofbundle *ofbundle)
1187 {
1188     struct hmap *xbundles;
1189     struct xbundle *xbundle;
1190
1191     if (!ofbundle || !xcfg) {
1192         return NULL;
1193     }
1194
1195     xbundles = &xcfg->xbundles;
1196
1197     HMAP_FOR_EACH_IN_BUCKET (xbundle, hmap_node, hash_pointer(ofbundle, 0),
1198                              xbundles) {
1199         if (xbundle->ofbundle == ofbundle) {
1200             return xbundle;
1201         }
1202     }
1203     return NULL;
1204 }
1205
1206 static struct xport *
1207 xport_lookup(struct xlate_cfg *xcfg, const struct ofport_dpif *ofport)
1208 {
1209     struct hmap *xports;
1210     struct xport *xport;
1211
1212     if (!ofport || !xcfg) {
1213         return NULL;
1214     }
1215
1216     xports = &xcfg->xports;
1217
1218     HMAP_FOR_EACH_IN_BUCKET (xport, hmap_node, hash_pointer(ofport, 0),
1219                              xports) {
1220         if (xport->ofport == ofport) {
1221             return xport;
1222         }
1223     }
1224     return NULL;
1225 }
1226
1227 static struct stp_port *
1228 xport_get_stp_port(const struct xport *xport)
1229 {
1230     return xport->xbridge->stp && xport->stp_port_no != -1
1231         ? stp_get_port(xport->xbridge->stp, xport->stp_port_no)
1232         : NULL;
1233 }
1234
1235 static bool
1236 xport_stp_learn_state(const struct xport *xport)
1237 {
1238     struct stp_port *sp = xport_get_stp_port(xport);
1239     return sp
1240         ? stp_learn_in_state(stp_port_get_state(sp))
1241         : true;
1242 }
1243
1244 static bool
1245 xport_stp_forward_state(const struct xport *xport)
1246 {
1247     struct stp_port *sp = xport_get_stp_port(xport);
1248     return sp
1249         ? stp_forward_in_state(stp_port_get_state(sp))
1250         : true;
1251 }
1252
1253 static bool
1254 xport_stp_should_forward_bpdu(const struct xport *xport)
1255 {
1256     struct stp_port *sp = xport_get_stp_port(xport);
1257     return stp_should_forward_bpdu(sp ? stp_port_get_state(sp) : STP_DISABLED);
1258 }
1259
1260 /* Returns true if STP should process 'flow'.  Sets fields in 'wc' that
1261  * were used to make the determination.*/
1262 static bool
1263 stp_should_process_flow(const struct flow *flow, struct flow_wildcards *wc)
1264 {
1265     /* is_stp() also checks dl_type, but dl_type is always set in 'wc'. */
1266     memset(&wc->masks.dl_dst, 0xff, sizeof wc->masks.dl_dst);
1267     return is_stp(flow);
1268 }
1269
1270 static void
1271 stp_process_packet(const struct xport *xport, const struct dp_packet *packet)
1272 {
1273     struct stp_port *sp = xport_get_stp_port(xport);
1274     struct dp_packet payload = *packet;
1275     struct eth_header *eth = dp_packet_data(&payload);
1276
1277     /* Sink packets on ports that have STP disabled when the bridge has
1278      * STP enabled. */
1279     if (!sp || stp_port_get_state(sp) == STP_DISABLED) {
1280         return;
1281     }
1282
1283     /* Trim off padding on payload. */
1284     if (dp_packet_size(&payload) > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1285         dp_packet_set_size(&payload, ntohs(eth->eth_type) + ETH_HEADER_LEN);
1286     }
1287
1288     if (dp_packet_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1289         stp_received_bpdu(sp, dp_packet_data(&payload), dp_packet_size(&payload));
1290     }
1291 }
1292
1293 static enum rstp_state
1294 xport_get_rstp_port_state(const struct xport *xport)
1295 {
1296     return xport->rstp_port
1297         ? rstp_port_get_state(xport->rstp_port)
1298         : RSTP_DISABLED;
1299 }
1300
1301 static bool
1302 xport_rstp_learn_state(const struct xport *xport)
1303 {
1304     return xport->xbridge->rstp && xport->rstp_port
1305         ? rstp_learn_in_state(xport_get_rstp_port_state(xport))
1306         : true;
1307 }
1308
1309 static bool
1310 xport_rstp_forward_state(const struct xport *xport)
1311 {
1312     return xport->xbridge->rstp && xport->rstp_port
1313         ? rstp_forward_in_state(xport_get_rstp_port_state(xport))
1314         : true;
1315 }
1316
1317 static bool
1318 xport_rstp_should_manage_bpdu(const struct xport *xport)
1319 {
1320     return rstp_should_manage_bpdu(xport_get_rstp_port_state(xport));
1321 }
1322
1323 static void
1324 rstp_process_packet(const struct xport *xport, const struct dp_packet *packet)
1325 {
1326     struct dp_packet payload = *packet;
1327     struct eth_header *eth = dp_packet_data(&payload);
1328
1329     /* Sink packets on ports that have no RSTP. */
1330     if (!xport->rstp_port) {
1331         return;
1332     }
1333
1334     /* Trim off padding on payload. */
1335     if (dp_packet_size(&payload) > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1336         dp_packet_set_size(&payload, ntohs(eth->eth_type) + ETH_HEADER_LEN);
1337     }
1338
1339     if (dp_packet_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1340         rstp_port_received_bpdu(xport->rstp_port, dp_packet_data(&payload),
1341                                 dp_packet_size(&payload));
1342     }
1343 }
1344
1345 static struct xport *
1346 get_ofp_port(const struct xbridge *xbridge, ofp_port_t ofp_port)
1347 {
1348     struct xport *xport;
1349
1350     HMAP_FOR_EACH_IN_BUCKET (xport, ofp_node, hash_ofp_port(ofp_port),
1351                              &xbridge->xports) {
1352         if (xport->ofp_port == ofp_port) {
1353             return xport;
1354         }
1355     }
1356     return NULL;
1357 }
1358
1359 static odp_port_t
1360 ofp_port_to_odp_port(const struct xbridge *xbridge, ofp_port_t ofp_port)
1361 {
1362     const struct xport *xport = get_ofp_port(xbridge, ofp_port);
1363     return xport ? xport->odp_port : ODPP_NONE;
1364 }
1365
1366 static bool
1367 odp_port_is_alive(const struct xlate_ctx *ctx, ofp_port_t ofp_port)
1368 {
1369     struct xport *xport = get_ofp_port(ctx->xbridge, ofp_port);
1370     return xport && xport->may_enable;
1371 }
1372
1373 static struct ofputil_bucket *
1374 group_first_live_bucket(const struct xlate_ctx *, const struct group_dpif *,
1375                         int depth);
1376
1377 static bool
1378 group_is_alive(const struct xlate_ctx *ctx, uint32_t group_id, int depth)
1379 {
1380     struct group_dpif *group;
1381
1382     if (group_dpif_lookup(ctx->xbridge->ofproto, group_id, &group)) {
1383         struct ofputil_bucket *bucket;
1384
1385         bucket = group_first_live_bucket(ctx, group, depth);
1386         group_dpif_unref(group);
1387         return bucket == NULL;
1388     }
1389
1390     return false;
1391 }
1392
1393 #define MAX_LIVENESS_RECURSION 128 /* Arbitrary limit */
1394
1395 static bool
1396 bucket_is_alive(const struct xlate_ctx *ctx,
1397                 struct ofputil_bucket *bucket, int depth)
1398 {
1399     if (depth >= MAX_LIVENESS_RECURSION) {
1400         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1401
1402         VLOG_WARN_RL(&rl, "bucket chaining exceeded %d links",
1403                      MAX_LIVENESS_RECURSION);
1404         return false;
1405     }
1406
1407     return (!ofputil_bucket_has_liveness(bucket)
1408             || (bucket->watch_port != OFPP_ANY
1409                && odp_port_is_alive(ctx, bucket->watch_port))
1410             || (bucket->watch_group != OFPG_ANY
1411                && group_is_alive(ctx, bucket->watch_group, depth + 1)));
1412 }
1413
1414 static struct ofputil_bucket *
1415 group_first_live_bucket(const struct xlate_ctx *ctx,
1416                         const struct group_dpif *group, int depth)
1417 {
1418     struct ofputil_bucket *bucket;
1419     const struct ovs_list *buckets;
1420
1421     group_dpif_get_buckets(group, &buckets);
1422     LIST_FOR_EACH (bucket, list_node, buckets) {
1423         if (bucket_is_alive(ctx, bucket, depth)) {
1424             return bucket;
1425         }
1426     }
1427
1428     return NULL;
1429 }
1430
1431 static struct ofputil_bucket *
1432 group_best_live_bucket(const struct xlate_ctx *ctx,
1433                        const struct group_dpif *group,
1434                        uint32_t basis)
1435 {
1436     struct ofputil_bucket *best_bucket = NULL;
1437     uint32_t best_score = 0;
1438     int i = 0;
1439
1440     struct ofputil_bucket *bucket;
1441     const struct ovs_list *buckets;
1442
1443     group_dpif_get_buckets(group, &buckets);
1444     LIST_FOR_EACH (bucket, list_node, buckets) {
1445         if (bucket_is_alive(ctx, bucket, 0)) {
1446             uint32_t score = (hash_int(i, basis) & 0xffff) * bucket->weight;
1447             if (score >= best_score) {
1448                 best_bucket = bucket;
1449                 best_score = score;
1450             }
1451         }
1452         i++;
1453     }
1454
1455     return best_bucket;
1456 }
1457
1458 static bool
1459 xbundle_trunks_vlan(const struct xbundle *bundle, uint16_t vlan)
1460 {
1461     return (bundle->vlan_mode != PORT_VLAN_ACCESS
1462             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
1463 }
1464
1465 static bool
1466 xbundle_includes_vlan(const struct xbundle *xbundle, uint16_t vlan)
1467 {
1468     return vlan == xbundle->vlan || xbundle_trunks_vlan(xbundle, vlan);
1469 }
1470
1471 static mirror_mask_t
1472 xbundle_mirror_out(const struct xbridge *xbridge, struct xbundle *xbundle)
1473 {
1474     return xbundle != &ofpp_none_bundle
1475         ? mirror_bundle_out(xbridge->mbridge, xbundle->ofbundle)
1476         : 0;
1477 }
1478
1479 static mirror_mask_t
1480 xbundle_mirror_src(const struct xbridge *xbridge, struct xbundle *xbundle)
1481 {
1482     return xbundle != &ofpp_none_bundle
1483         ? mirror_bundle_src(xbridge->mbridge, xbundle->ofbundle)
1484         : 0;
1485 }
1486
1487 static mirror_mask_t
1488 xbundle_mirror_dst(const struct xbridge *xbridge, struct xbundle *xbundle)
1489 {
1490     return xbundle != &ofpp_none_bundle
1491         ? mirror_bundle_dst(xbridge->mbridge, xbundle->ofbundle)
1492         : 0;
1493 }
1494
1495 static struct xbundle *
1496 lookup_input_bundle(const struct xbridge *xbridge, ofp_port_t in_port,
1497                     bool warn, struct xport **in_xportp)
1498 {
1499     struct xport *xport;
1500
1501     /* Find the port and bundle for the received packet. */
1502     xport = get_ofp_port(xbridge, in_port);
1503     if (in_xportp) {
1504         *in_xportp = xport;
1505     }
1506     if (xport && xport->xbundle) {
1507         return xport->xbundle;
1508     }
1509
1510     /* Special-case OFPP_NONE (OF1.0) and OFPP_CONTROLLER (OF1.1+),
1511      * which a controller may use as the ingress port for traffic that
1512      * it is sourcing. */
1513     if (in_port == OFPP_CONTROLLER || in_port == OFPP_NONE) {
1514         return &ofpp_none_bundle;
1515     }
1516
1517     /* Odd.  A few possible reasons here:
1518      *
1519      * - We deleted a port but there are still a few packets queued up
1520      *   from it.
1521      *
1522      * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
1523      *   we don't know about.
1524      *
1525      * - The ofproto client didn't configure the port as part of a bundle.
1526      *   This is particularly likely to happen if a packet was received on the
1527      *   port after it was created, but before the client had a chance to
1528      *   configure its bundle.
1529      */
1530     if (warn) {
1531         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1532
1533         VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
1534                      "port %"PRIu16, xbridge->name, in_port);
1535     }
1536     return NULL;
1537 }
1538
1539 static void
1540 add_mirror_actions(struct xlate_ctx *ctx, const struct flow *orig_flow)
1541 {
1542     const struct xbridge *xbridge = ctx->xbridge;
1543     mirror_mask_t mirrors;
1544     struct xbundle *in_xbundle;
1545     uint16_t vlan;
1546     uint16_t vid;
1547
1548     mirrors = ctx->xout->mirrors;
1549     ctx->xout->mirrors = 0;
1550
1551     in_xbundle = lookup_input_bundle(xbridge, orig_flow->in_port.ofp_port,
1552                                      ctx->xin->packet != NULL, NULL);
1553     if (!in_xbundle) {
1554         return;
1555     }
1556     mirrors |= xbundle_mirror_src(xbridge, in_xbundle);
1557
1558     /* Drop frames on bundles reserved for mirroring. */
1559     if (xbundle_mirror_out(xbridge, in_xbundle)) {
1560         if (ctx->xin->packet != NULL) {
1561             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1562             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
1563                          "%s, which is reserved exclusively for mirroring",
1564                          ctx->xbridge->name, in_xbundle->name);
1565         }
1566         ofpbuf_clear(ctx->xout->odp_actions);
1567         return;
1568     }
1569
1570     /* Check VLAN. */
1571     vid = vlan_tci_to_vid(orig_flow->vlan_tci);
1572     if (!input_vid_is_valid(vid, in_xbundle, ctx->xin->packet != NULL)) {
1573         return;
1574     }
1575     vlan = input_vid_to_vlan(in_xbundle, vid);
1576
1577     if (!mirrors) {
1578         return;
1579     }
1580
1581     /* Restore the original packet before adding the mirror actions. */
1582     ctx->xin->flow = *orig_flow;
1583
1584     while (mirrors) {
1585         mirror_mask_t dup_mirrors;
1586         struct ofbundle *out;
1587         unsigned long *vlans;
1588         bool vlan_mirrored;
1589         bool has_mirror;
1590         int out_vlan;
1591
1592         has_mirror = mirror_get(xbridge->mbridge, raw_ctz(mirrors),
1593                                 &vlans, &dup_mirrors, &out, &out_vlan);
1594         ovs_assert(has_mirror);
1595
1596         if (vlans) {
1597             ctx->xout->wc.masks.vlan_tci |= htons(VLAN_CFI | VLAN_VID_MASK);
1598         }
1599         vlan_mirrored = !vlans || bitmap_is_set(vlans, vlan);
1600         free(vlans);
1601
1602         if (!vlan_mirrored) {
1603             mirrors = zero_rightmost_1bit(mirrors);
1604             continue;
1605         }
1606
1607         mirrors &= ~dup_mirrors;
1608         ctx->xout->mirrors |= dup_mirrors;
1609         if (out) {
1610             struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
1611             struct xbundle *out_xbundle = xbundle_lookup(xcfg, out);
1612             if (out_xbundle) {
1613                 output_normal(ctx, out_xbundle, vlan);
1614             }
1615         } else if (vlan != out_vlan
1616                    && !eth_addr_is_reserved(orig_flow->dl_dst)) {
1617             struct xbundle *xbundle;
1618
1619             LIST_FOR_EACH (xbundle, list_node, &xbridge->xbundles) {
1620                 if (xbundle_includes_vlan(xbundle, out_vlan)
1621                     && !xbundle_mirror_out(xbridge, xbundle)) {
1622                     output_normal(ctx, xbundle, out_vlan);
1623                 }
1624             }
1625         }
1626     }
1627 }
1628
1629 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
1630  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_xbundle',
1631  * the bundle on which the packet was received, returns the VLAN to which the
1632  * packet belongs.
1633  *
1634  * Both 'vid' and the return value are in the range 0...4095. */
1635 static uint16_t
1636 input_vid_to_vlan(const struct xbundle *in_xbundle, uint16_t vid)
1637 {
1638     switch (in_xbundle->vlan_mode) {
1639     case PORT_VLAN_ACCESS:
1640         return in_xbundle->vlan;
1641         break;
1642
1643     case PORT_VLAN_TRUNK:
1644         return vid;
1645
1646     case PORT_VLAN_NATIVE_UNTAGGED:
1647     case PORT_VLAN_NATIVE_TAGGED:
1648         return vid ? vid : in_xbundle->vlan;
1649
1650     default:
1651         OVS_NOT_REACHED();
1652     }
1653 }
1654
1655 /* Checks whether a packet with the given 'vid' may ingress on 'in_xbundle'.
1656  * If so, returns true.  Otherwise, returns false and, if 'warn' is true, logs
1657  * a warning.
1658  *
1659  * 'vid' should be the VID obtained from the 802.1Q header that was received as
1660  * part of a packet (specify 0 if there was no 802.1Q header), in the range
1661  * 0...4095. */
1662 static bool
1663 input_vid_is_valid(uint16_t vid, struct xbundle *in_xbundle, bool warn)
1664 {
1665     /* Allow any VID on the OFPP_NONE port. */
1666     if (in_xbundle == &ofpp_none_bundle) {
1667         return true;
1668     }
1669
1670     switch (in_xbundle->vlan_mode) {
1671     case PORT_VLAN_ACCESS:
1672         if (vid) {
1673             if (warn) {
1674                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1675                 VLOG_WARN_RL(&rl, "dropping VLAN %"PRIu16" tagged "
1676                              "packet received on port %s configured as VLAN "
1677                              "%"PRIu16" access port", vid, in_xbundle->name,
1678                              in_xbundle->vlan);
1679             }
1680             return false;
1681         }
1682         return true;
1683
1684     case PORT_VLAN_NATIVE_UNTAGGED:
1685     case PORT_VLAN_NATIVE_TAGGED:
1686         if (!vid) {
1687             /* Port must always carry its native VLAN. */
1688             return true;
1689         }
1690         /* Fall through. */
1691     case PORT_VLAN_TRUNK:
1692         if (!xbundle_includes_vlan(in_xbundle, vid)) {
1693             if (warn) {
1694                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1695                 VLOG_WARN_RL(&rl, "dropping VLAN %"PRIu16" packet "
1696                              "received on port %s not configured for trunking "
1697                              "VLAN %"PRIu16, vid, in_xbundle->name, vid);
1698             }
1699             return false;
1700         }
1701         return true;
1702
1703     default:
1704         OVS_NOT_REACHED();
1705     }
1706
1707 }
1708
1709 /* Given 'vlan', the VLAN that a packet belongs to, and
1710  * 'out_xbundle', a bundle on which the packet is to be output, returns the VID
1711  * that should be included in the 802.1Q header.  (If the return value is 0,
1712  * then the 802.1Q header should only be included in the packet if there is a
1713  * nonzero PCP.)
1714  *
1715  * Both 'vlan' and the return value are in the range 0...4095. */
1716 static uint16_t
1717 output_vlan_to_vid(const struct xbundle *out_xbundle, uint16_t vlan)
1718 {
1719     switch (out_xbundle->vlan_mode) {
1720     case PORT_VLAN_ACCESS:
1721         return 0;
1722
1723     case PORT_VLAN_TRUNK:
1724     case PORT_VLAN_NATIVE_TAGGED:
1725         return vlan;
1726
1727     case PORT_VLAN_NATIVE_UNTAGGED:
1728         return vlan == out_xbundle->vlan ? 0 : vlan;
1729
1730     default:
1731         OVS_NOT_REACHED();
1732     }
1733 }
1734
1735 static void
1736 output_normal(struct xlate_ctx *ctx, const struct xbundle *out_xbundle,
1737               uint16_t vlan)
1738 {
1739     ovs_be16 *flow_tci = &ctx->xin->flow.vlan_tci;
1740     uint16_t vid;
1741     ovs_be16 tci, old_tci;
1742     struct xport *xport;
1743     struct xlate_bond_recirc xr;
1744     bool use_recirc = false;
1745
1746     vid = output_vlan_to_vid(out_xbundle, vlan);
1747     if (list_is_empty(&out_xbundle->xports)) {
1748         /* Partially configured bundle with no slaves.  Drop the packet. */
1749         return;
1750     } else if (!out_xbundle->bond) {
1751         xport = CONTAINER_OF(list_front(&out_xbundle->xports), struct xport,
1752                              bundle_node);
1753     } else {
1754         struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
1755         struct flow_wildcards *wc = &ctx->xout->wc;
1756         struct ofport_dpif *ofport;
1757
1758         if (ctx->xbridge->enable_recirc) {
1759             use_recirc = bond_may_recirc(
1760                 out_xbundle->bond, &xr.recirc_id, &xr.hash_basis);
1761
1762             if (use_recirc) {
1763                 /* Only TCP mode uses recirculation. */
1764                 xr.hash_alg = OVS_HASH_ALG_L4;
1765                 bond_update_post_recirc_rules(out_xbundle->bond, false);
1766
1767                 /* Recirculation does not require unmasking hash fields. */
1768                 wc = NULL;
1769             }
1770         }
1771
1772         ofport = bond_choose_output_slave(out_xbundle->bond,
1773                                           &ctx->xin->flow, wc, vid);
1774         xport = xport_lookup(xcfg, ofport);
1775
1776         if (!xport) {
1777             /* No slaves enabled, so drop packet. */
1778             return;
1779         }
1780
1781         /* If use_recirc is set, the main thread will handle stats
1782          * accounting for this bond. */
1783         if (!use_recirc) {
1784             if (ctx->xin->resubmit_stats) {
1785                 bond_account(out_xbundle->bond, &ctx->xin->flow, vid,
1786                              ctx->xin->resubmit_stats->n_bytes);
1787             }
1788             if (ctx->xin->xcache) {
1789                 struct xc_entry *entry;
1790                 struct flow *flow;
1791
1792                 flow = &ctx->xin->flow;
1793                 entry = xlate_cache_add_entry(ctx->xin->xcache, XC_BOND);
1794                 entry->u.bond.bond = bond_ref(out_xbundle->bond);
1795                 entry->u.bond.flow = xmemdup(flow, sizeof *flow);
1796                 entry->u.bond.vid = vid;
1797             }
1798         }
1799     }
1800
1801     old_tci = *flow_tci;
1802     tci = htons(vid);
1803     if (tci || out_xbundle->use_priority_tags) {
1804         tci |= *flow_tci & htons(VLAN_PCP_MASK);
1805         if (tci) {
1806             tci |= htons(VLAN_CFI);
1807         }
1808     }
1809     *flow_tci = tci;
1810
1811     compose_output_action(ctx, xport->ofp_port, use_recirc ? &xr : NULL);
1812     *flow_tci = old_tci;
1813 }
1814
1815 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
1816  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
1817  * indicate this; newer upstream kernels use gratuitous ARP requests. */
1818 static bool
1819 is_gratuitous_arp(const struct flow *flow, struct flow_wildcards *wc)
1820 {
1821     if (flow->dl_type != htons(ETH_TYPE_ARP)) {
1822         return false;
1823     }
1824
1825     memset(&wc->masks.dl_dst, 0xff, sizeof wc->masks.dl_dst);
1826     if (!eth_addr_is_broadcast(flow->dl_dst)) {
1827         return false;
1828     }
1829
1830     memset(&wc->masks.nw_proto, 0xff, sizeof wc->masks.nw_proto);
1831     if (flow->nw_proto == ARP_OP_REPLY) {
1832         return true;
1833     } else if (flow->nw_proto == ARP_OP_REQUEST) {
1834         memset(&wc->masks.nw_src, 0xff, sizeof wc->masks.nw_src);
1835         memset(&wc->masks.nw_dst, 0xff, sizeof wc->masks.nw_dst);
1836
1837         return flow->nw_src == flow->nw_dst;
1838     } else {
1839         return false;
1840     }
1841 }
1842
1843 /* Determines whether packets in 'flow' within 'xbridge' should be forwarded or
1844  * dropped.  Returns true if they may be forwarded, false if they should be
1845  * dropped.
1846  *
1847  * 'in_port' must be the xport that corresponds to flow->in_port.
1848  * 'in_port' must be part of a bundle (e.g. in_port->bundle must be nonnull).
1849  *
1850  * 'vlan' must be the VLAN that corresponds to flow->vlan_tci on 'in_port', as
1851  * returned by input_vid_to_vlan().  It must be a valid VLAN for 'in_port', as
1852  * checked by input_vid_is_valid().
1853  *
1854  * May also add tags to '*tags', although the current implementation only does
1855  * so in one special case.
1856  */
1857 static bool
1858 is_admissible(struct xlate_ctx *ctx, struct xport *in_port,
1859               uint16_t vlan)
1860 {
1861     struct xbundle *in_xbundle = in_port->xbundle;
1862     const struct xbridge *xbridge = ctx->xbridge;
1863     struct flow *flow = &ctx->xin->flow;
1864
1865     /* Drop frames for reserved multicast addresses
1866      * only if forward_bpdu option is absent. */
1867     if (!xbridge->forward_bpdu && eth_addr_is_reserved(flow->dl_dst)) {
1868         xlate_report(ctx, "packet has reserved destination MAC, dropping");
1869         return false;
1870     }
1871
1872     if (in_xbundle->bond) {
1873         struct mac_entry *mac;
1874
1875         switch (bond_check_admissibility(in_xbundle->bond, in_port->ofport,
1876                                          flow->dl_dst)) {
1877         case BV_ACCEPT:
1878             break;
1879
1880         case BV_DROP:
1881             xlate_report(ctx, "bonding refused admissibility, dropping");
1882             return false;
1883
1884         case BV_DROP_IF_MOVED:
1885             ovs_rwlock_rdlock(&xbridge->ml->rwlock);
1886             mac = mac_learning_lookup(xbridge->ml, flow->dl_src, vlan);
1887             if (mac
1888                 && mac_entry_get_port(xbridge->ml, mac) != in_xbundle->ofbundle
1889                 && (!is_gratuitous_arp(flow, &ctx->xout->wc)
1890                     || mac_entry_is_grat_arp_locked(mac))) {
1891                 ovs_rwlock_unlock(&xbridge->ml->rwlock);
1892                 xlate_report(ctx, "SLB bond thinks this packet looped back, "
1893                              "dropping");
1894                 return false;
1895             }
1896             ovs_rwlock_unlock(&xbridge->ml->rwlock);
1897             break;
1898         }
1899     }
1900
1901     return true;
1902 }
1903
1904 /* Checks whether a MAC learning update is necessary for MAC learning table
1905  * 'ml' given that a packet matching 'flow' was received  on 'in_xbundle' in
1906  * 'vlan'.
1907  *
1908  * Most packets processed through the MAC learning table do not actually
1909  * change it in any way.  This function requires only a read lock on the MAC
1910  * learning table, so it is much cheaper in this common case.
1911  *
1912  * Keep the code here synchronized with that in update_learning_table__()
1913  * below. */
1914 static bool
1915 is_mac_learning_update_needed(const struct mac_learning *ml,
1916                               const struct flow *flow,
1917                               struct flow_wildcards *wc,
1918                               int vlan, struct xbundle *in_xbundle)
1919 OVS_REQ_RDLOCK(ml->rwlock)
1920 {
1921     struct mac_entry *mac;
1922
1923     if (!mac_learning_may_learn(ml, flow->dl_src, vlan)) {
1924         return false;
1925     }
1926
1927     mac = mac_learning_lookup(ml, flow->dl_src, vlan);
1928     if (!mac || mac_entry_age(ml, mac)) {
1929         return true;
1930     }
1931
1932     if (is_gratuitous_arp(flow, wc)) {
1933         /* We don't want to learn from gratuitous ARP packets that are
1934          * reflected back over bond slaves so we lock the learning table. */
1935         if (!in_xbundle->bond) {
1936             return true;
1937         } else if (mac_entry_is_grat_arp_locked(mac)) {
1938             return false;
1939         }
1940     }
1941
1942     return mac_entry_get_port(ml, mac) != in_xbundle->ofbundle;
1943 }
1944
1945
1946 /* Updates MAC learning table 'ml' given that a packet matching 'flow' was
1947  * received on 'in_xbundle' in 'vlan'.
1948  *
1949  * This code repeats all the checks in is_mac_learning_update_needed() because
1950  * the lock was released between there and here and thus the MAC learning state
1951  * could have changed.
1952  *
1953  * Keep the code here synchronized with that in is_mac_learning_update_needed()
1954  * above. */
1955 static void
1956 update_learning_table__(const struct xbridge *xbridge,
1957                         const struct flow *flow, struct flow_wildcards *wc,
1958                         int vlan, struct xbundle *in_xbundle)
1959 OVS_REQ_WRLOCK(xbridge->ml->rwlock)
1960 {
1961     struct mac_entry *mac;
1962
1963     if (!mac_learning_may_learn(xbridge->ml, flow->dl_src, vlan)) {
1964         return;
1965     }
1966
1967     mac = mac_learning_insert(xbridge->ml, flow->dl_src, vlan);
1968     if (is_gratuitous_arp(flow, wc)) {
1969         /* We don't want to learn from gratuitous ARP packets that are
1970          * reflected back over bond slaves so we lock the learning table. */
1971         if (!in_xbundle->bond) {
1972             mac_entry_set_grat_arp_lock(mac);
1973         } else if (mac_entry_is_grat_arp_locked(mac)) {
1974             return;
1975         }
1976     }
1977
1978     if (mac_entry_get_port(xbridge->ml, mac) != in_xbundle->ofbundle) {
1979         /* The log messages here could actually be useful in debugging,
1980          * so keep the rate limit relatively high. */
1981         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
1982
1983         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
1984                     "on port %s in VLAN %d",
1985                     xbridge->name, ETH_ADDR_ARGS(flow->dl_src),
1986                     in_xbundle->name, vlan);
1987
1988         mac_entry_set_port(xbridge->ml, mac, in_xbundle->ofbundle);
1989     }
1990 }
1991
1992 static void
1993 update_learning_table(const struct xbridge *xbridge,
1994                       const struct flow *flow, struct flow_wildcards *wc,
1995                       int vlan, struct xbundle *in_xbundle)
1996 {
1997     bool need_update;
1998
1999     /* Don't learn the OFPP_NONE port. */
2000     if (in_xbundle == &ofpp_none_bundle) {
2001         return;
2002     }
2003
2004     /* First try the common case: no change to MAC learning table. */
2005     ovs_rwlock_rdlock(&xbridge->ml->rwlock);
2006     need_update = is_mac_learning_update_needed(xbridge->ml, flow, wc, vlan,
2007                                                 in_xbundle);
2008     ovs_rwlock_unlock(&xbridge->ml->rwlock);
2009
2010     if (need_update) {
2011         /* Slow path: MAC learning table might need an update. */
2012         ovs_rwlock_wrlock(&xbridge->ml->rwlock);
2013         update_learning_table__(xbridge, flow, wc, vlan, in_xbundle);
2014         ovs_rwlock_unlock(&xbridge->ml->rwlock);
2015     }
2016 }
2017
2018 /* Updates multicast snooping table 'ms' given that a packet matching 'flow'
2019  * was received on 'in_xbundle' in 'vlan' and is either Report or Query. */
2020 static void
2021 update_mcast_snooping_table__(const struct xbridge *xbridge,
2022                               const struct flow *flow,
2023                               struct mcast_snooping *ms,
2024                               ovs_be32 ip4, int vlan,
2025                               struct xbundle *in_xbundle)
2026     OVS_REQ_WRLOCK(ms->rwlock)
2027 {
2028     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 30);
2029
2030     switch (ntohs(flow->tp_src)) {
2031     case IGMP_HOST_MEMBERSHIP_REPORT:
2032     case IGMPV2_HOST_MEMBERSHIP_REPORT:
2033         if (mcast_snooping_add_group(ms, ip4, vlan, in_xbundle->ofbundle)) {
2034             VLOG_DBG_RL(&rl, "bridge %s: multicast snooping learned that "
2035                         IP_FMT" is on port %s in VLAN %d",
2036                         xbridge->name, IP_ARGS(ip4), in_xbundle->name, vlan);
2037         }
2038         break;
2039     case IGMP_HOST_LEAVE_MESSAGE:
2040         if (mcast_snooping_leave_group(ms, ip4, vlan, in_xbundle->ofbundle)) {
2041             VLOG_DBG_RL(&rl, "bridge %s: multicast snooping leaving "
2042                         IP_FMT" is on port %s in VLAN %d",
2043                         xbridge->name, IP_ARGS(ip4), in_xbundle->name, vlan);
2044         }
2045         break;
2046     case IGMP_HOST_MEMBERSHIP_QUERY:
2047         if (flow->nw_src && mcast_snooping_add_mrouter(ms, vlan,
2048             in_xbundle->ofbundle)) {
2049             VLOG_DBG_RL(&rl, "bridge %s: multicast snooping query from "
2050                         IP_FMT" is on port %s in VLAN %d",
2051                         xbridge->name, IP_ARGS(flow->nw_src),
2052                         in_xbundle->name, vlan);
2053         }
2054         break;
2055     }
2056 }
2057
2058 /* Updates multicast snooping table 'ms' given that a packet matching 'flow'
2059  * was received on 'in_xbundle' in 'vlan'. */
2060 static void
2061 update_mcast_snooping_table(const struct xbridge *xbridge,
2062                             const struct flow *flow, int vlan,
2063                             struct xbundle *in_xbundle)
2064 {
2065     struct mcast_snooping *ms = xbridge->ms;
2066     struct xlate_cfg *xcfg;
2067     struct xbundle *mcast_xbundle;
2068     struct mcast_port_bundle *fport;
2069
2070     /* Don't learn the OFPP_NONE port. */
2071     if (in_xbundle == &ofpp_none_bundle) {
2072         return;
2073     }
2074
2075     /* Don't learn from flood ports */
2076     mcast_xbundle = NULL;
2077     ovs_rwlock_wrlock(&ms->rwlock);
2078     xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
2079     LIST_FOR_EACH(fport, node, &ms->fport_list) {
2080         mcast_xbundle = xbundle_lookup(xcfg, fport->port);
2081         if (mcast_xbundle == in_xbundle) {
2082             break;
2083         }
2084     }
2085
2086     if (!mcast_xbundle || mcast_xbundle != in_xbundle) {
2087         update_mcast_snooping_table__(xbridge, flow, ms, flow->igmp_group_ip4,
2088                                       vlan, in_xbundle);
2089     }
2090     ovs_rwlock_unlock(&ms->rwlock);
2091 }
2092
2093 /* send the packet to ports having the multicast group learned */
2094 static void
2095 xlate_normal_mcast_send_group(struct xlate_ctx *ctx,
2096                               struct mcast_snooping *ms OVS_UNUSED,
2097                               struct mcast_group *grp,
2098                               struct xbundle *in_xbundle, uint16_t vlan)
2099     OVS_REQ_RDLOCK(ms->rwlock)
2100 {
2101     struct xlate_cfg *xcfg;
2102     struct mcast_group_bundle *b;
2103     struct xbundle *mcast_xbundle;
2104
2105     xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
2106     LIST_FOR_EACH(b, bundle_node, &grp->bundle_lru) {
2107         mcast_xbundle = xbundle_lookup(xcfg, b->port);
2108         if (mcast_xbundle && mcast_xbundle != in_xbundle) {
2109             xlate_report(ctx, "forwarding to mcast group port");
2110             output_normal(ctx, mcast_xbundle, vlan);
2111         } else if (!mcast_xbundle) {
2112             xlate_report(ctx, "mcast group port is unknown, dropping");
2113         } else {
2114             xlate_report(ctx, "mcast group port is input port, dropping");
2115         }
2116     }
2117 }
2118
2119 /* send the packet to ports connected to multicast routers */
2120 static void
2121 xlate_normal_mcast_send_mrouters(struct xlate_ctx *ctx,
2122                                  struct mcast_snooping *ms,
2123                                  struct xbundle *in_xbundle, uint16_t vlan)
2124     OVS_REQ_RDLOCK(ms->rwlock)
2125 {
2126     struct xlate_cfg *xcfg;
2127     struct mcast_mrouter_bundle *mrouter;
2128     struct xbundle *mcast_xbundle;
2129
2130     xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
2131     LIST_FOR_EACH(mrouter, mrouter_node, &ms->mrouter_lru) {
2132         mcast_xbundle = xbundle_lookup(xcfg, mrouter->port);
2133         if (mcast_xbundle && mcast_xbundle != in_xbundle) {
2134             xlate_report(ctx, "forwarding to mcast router port");
2135             output_normal(ctx, mcast_xbundle, vlan);
2136         } else if (!mcast_xbundle) {
2137             xlate_report(ctx, "mcast router port is unknown, dropping");
2138         } else {
2139             xlate_report(ctx, "mcast router port is input port, dropping");
2140         }
2141     }
2142 }
2143
2144 /* send the packet to ports flagged to be flooded */
2145 static void
2146 xlate_normal_mcast_send_fports(struct xlate_ctx *ctx,
2147                                struct mcast_snooping *ms,
2148                                struct xbundle *in_xbundle, uint16_t vlan)
2149     OVS_REQ_RDLOCK(ms->rwlock)
2150 {
2151     struct xlate_cfg *xcfg;
2152     struct mcast_port_bundle *fport;
2153     struct xbundle *mcast_xbundle;
2154
2155     xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
2156     LIST_FOR_EACH(fport, node, &ms->fport_list) {
2157         mcast_xbundle = xbundle_lookup(xcfg, fport->port);
2158         if (mcast_xbundle && mcast_xbundle != in_xbundle) {
2159             xlate_report(ctx, "forwarding to mcast flood port");
2160             output_normal(ctx, mcast_xbundle, vlan);
2161         } else if (!mcast_xbundle) {
2162             xlate_report(ctx, "mcast flood port is unknown, dropping");
2163         } else {
2164             xlate_report(ctx, "mcast flood port is input port, dropping");
2165         }
2166     }
2167 }
2168
2169 /* forward the Reports to configured ports */
2170 static void
2171 xlate_normal_mcast_send_rports(struct xlate_ctx *ctx,
2172                                struct mcast_snooping *ms,
2173                                struct xbundle *in_xbundle, uint16_t vlan)
2174     OVS_REQ_RDLOCK(ms->rwlock)
2175 {
2176     struct xlate_cfg *xcfg;
2177     struct mcast_port_bundle *rport;
2178     struct xbundle *mcast_xbundle;
2179
2180     xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
2181     LIST_FOR_EACH(rport, node, &ms->rport_list) {
2182         mcast_xbundle = xbundle_lookup(xcfg, rport->port);
2183         if (mcast_xbundle && mcast_xbundle != in_xbundle) {
2184             xlate_report(ctx, "forwarding Report to mcast flagged port");
2185             output_normal(ctx, mcast_xbundle, vlan);
2186         } else if (!mcast_xbundle) {
2187             xlate_report(ctx, "mcast port is unknown, dropping the Report");
2188         } else {
2189             xlate_report(ctx, "mcast port is input port, dropping the Report");
2190         }
2191     }
2192 }
2193
2194 static void
2195 xlate_normal_flood(struct xlate_ctx *ctx, struct xbundle *in_xbundle,
2196                    uint16_t vlan)
2197 {
2198     struct xbundle *xbundle;
2199
2200     LIST_FOR_EACH (xbundle, list_node, &ctx->xbridge->xbundles) {
2201         if (xbundle != in_xbundle
2202             && xbundle_includes_vlan(xbundle, vlan)
2203             && xbundle->floodable
2204             && !xbundle_mirror_out(ctx->xbridge, xbundle)) {
2205             output_normal(ctx, xbundle, vlan);
2206         }
2207     }
2208     ctx->xout->nf_output_iface = NF_OUT_FLOOD;
2209 }
2210
2211 static void
2212 xlate_normal(struct xlate_ctx *ctx)
2213 {
2214     struct flow_wildcards *wc = &ctx->xout->wc;
2215     struct flow *flow = &ctx->xin->flow;
2216     struct xbundle *in_xbundle;
2217     struct xport *in_port;
2218     struct mac_entry *mac;
2219     void *mac_port;
2220     uint16_t vlan;
2221     uint16_t vid;
2222
2223     ctx->xout->has_normal = true;
2224
2225     memset(&wc->masks.dl_src, 0xff, sizeof wc->masks.dl_src);
2226     memset(&wc->masks.dl_dst, 0xff, sizeof wc->masks.dl_dst);
2227     wc->masks.vlan_tci |= htons(VLAN_VID_MASK | VLAN_CFI);
2228
2229     in_xbundle = lookup_input_bundle(ctx->xbridge, flow->in_port.ofp_port,
2230                                      ctx->xin->packet != NULL, &in_port);
2231     if (!in_xbundle) {
2232         xlate_report(ctx, "no input bundle, dropping");
2233         return;
2234     }
2235
2236     /* Drop malformed frames. */
2237     if (flow->dl_type == htons(ETH_TYPE_VLAN) &&
2238         !(flow->vlan_tci & htons(VLAN_CFI))) {
2239         if (ctx->xin->packet != NULL) {
2240             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2241             VLOG_WARN_RL(&rl, "bridge %s: dropping packet with partial "
2242                          "VLAN tag received on port %s",
2243                          ctx->xbridge->name, in_xbundle->name);
2244         }
2245         xlate_report(ctx, "partial VLAN tag, dropping");
2246         return;
2247     }
2248
2249     /* Drop frames on bundles reserved for mirroring. */
2250     if (xbundle_mirror_out(ctx->xbridge, in_xbundle)) {
2251         if (ctx->xin->packet != NULL) {
2252             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2253             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
2254                          "%s, which is reserved exclusively for mirroring",
2255                          ctx->xbridge->name, in_xbundle->name);
2256         }
2257         xlate_report(ctx, "input port is mirror output port, dropping");
2258         return;
2259     }
2260
2261     /* Check VLAN. */
2262     vid = vlan_tci_to_vid(flow->vlan_tci);
2263     if (!input_vid_is_valid(vid, in_xbundle, ctx->xin->packet != NULL)) {
2264         xlate_report(ctx, "disallowed VLAN VID for this input port, dropping");
2265         return;
2266     }
2267     vlan = input_vid_to_vlan(in_xbundle, vid);
2268
2269     /* Check other admissibility requirements. */
2270     if (in_port && !is_admissible(ctx, in_port, vlan)) {
2271         return;
2272     }
2273
2274     /* Learn source MAC. */
2275     if (ctx->xin->may_learn) {
2276         update_learning_table(ctx->xbridge, flow, wc, vlan, in_xbundle);
2277     }
2278     if (ctx->xin->xcache) {
2279         struct xc_entry *entry;
2280
2281         /* Save enough info to update mac learning table later. */
2282         entry = xlate_cache_add_entry(ctx->xin->xcache, XC_NORMAL);
2283         entry->u.normal.ofproto = ctx->xbridge->ofproto;
2284         entry->u.normal.flow = xmemdup(flow, sizeof *flow);
2285         entry->u.normal.vlan = vlan;
2286     }
2287
2288     /* Determine output bundle. */
2289     if (mcast_snooping_enabled(ctx->xbridge->ms)
2290         && !eth_addr_is_broadcast(flow->dl_dst)
2291         && eth_addr_is_multicast(flow->dl_dst)
2292         && flow->dl_type == htons(ETH_TYPE_IP)) {
2293         struct mcast_snooping *ms = ctx->xbridge->ms;
2294         struct mcast_group *grp;
2295
2296         if (flow->nw_proto == IPPROTO_IGMP) {
2297             if (ctx->xin->may_learn) {
2298                 if (mcast_snooping_is_membership(flow->tp_src) ||
2299                     mcast_snooping_is_query(flow->tp_src)) {
2300                     update_mcast_snooping_table(ctx->xbridge, flow, vlan,
2301                                                 in_xbundle);
2302                     }
2303             }
2304
2305             if (mcast_snooping_is_membership(flow->tp_src)) {
2306                 ovs_rwlock_rdlock(&ms->rwlock);
2307                 xlate_normal_mcast_send_mrouters(ctx, ms, in_xbundle, vlan);
2308                 /* RFC4541: section 2.1.1, item 1: A snooping switch should
2309                  * forward IGMP Membership Reports only to those ports where
2310                  * multicast routers are attached.  Alternatively stated: a
2311                  * snooping switch should not forward IGMP Membership Reports
2312                  * to ports on which only hosts are attached.
2313                  * An administrative control may be provided to override this
2314                  * restriction, allowing the report messages to be flooded to
2315                  * other ports. */
2316                 xlate_normal_mcast_send_rports(ctx, ms, in_xbundle, vlan);
2317                 ovs_rwlock_unlock(&ms->rwlock);
2318             } else {
2319                 xlate_report(ctx, "multicast traffic, flooding");
2320                 xlate_normal_flood(ctx, in_xbundle, vlan);
2321             }
2322             return;
2323         } else {
2324             if (ip_is_local_multicast(flow->nw_dst)) {
2325                 /* RFC4541: section 2.1.2, item 2: Packets with a dst IP
2326                  * address in the 224.0.0.x range which are not IGMP must
2327                  * be forwarded on all ports */
2328                 xlate_report(ctx, "RFC4541: section 2.1.2, item 2, flooding");
2329                 xlate_normal_flood(ctx, in_xbundle, vlan);
2330                 return;
2331             }
2332         }
2333
2334         /* forwarding to group base ports */
2335         ovs_rwlock_rdlock(&ms->rwlock);
2336         grp = mcast_snooping_lookup(ms, flow->nw_dst, vlan);
2337         if (grp) {
2338             xlate_normal_mcast_send_group(ctx, ms, grp, in_xbundle, vlan);
2339             xlate_normal_mcast_send_fports(ctx, ms, in_xbundle, vlan);
2340             xlate_normal_mcast_send_mrouters(ctx, ms, in_xbundle, vlan);
2341         } else {
2342             if (mcast_snooping_flood_unreg(ms)) {
2343                 xlate_report(ctx, "unregistered multicast, flooding");
2344                 xlate_normal_flood(ctx, in_xbundle, vlan);
2345             } else {
2346                 xlate_normal_mcast_send_mrouters(ctx, ms, in_xbundle, vlan);
2347                 xlate_normal_mcast_send_fports(ctx, ms, in_xbundle, vlan);
2348             }
2349         }
2350         ovs_rwlock_unlock(&ms->rwlock);
2351     } else {
2352         ovs_rwlock_rdlock(&ctx->xbridge->ml->rwlock);
2353         mac = mac_learning_lookup(ctx->xbridge->ml, flow->dl_dst, vlan);
2354         mac_port = mac ? mac_entry_get_port(ctx->xbridge->ml, mac) : NULL;
2355         ovs_rwlock_unlock(&ctx->xbridge->ml->rwlock);
2356
2357         if (mac_port) {
2358             struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
2359             struct xbundle *mac_xbundle = xbundle_lookup(xcfg, mac_port);
2360             if (mac_xbundle && mac_xbundle != in_xbundle) {
2361                 xlate_report(ctx, "forwarding to learned port");
2362                 output_normal(ctx, mac_xbundle, vlan);
2363             } else if (!mac_xbundle) {
2364                 xlate_report(ctx, "learned port is unknown, dropping");
2365             } else {
2366                 xlate_report(ctx, "learned port is input port, dropping");
2367             }
2368         } else {
2369             xlate_report(ctx, "no learned MAC for destination, flooding");
2370             xlate_normal_flood(ctx, in_xbundle, vlan);
2371         }
2372     }
2373 }
2374
2375 /* Compose SAMPLE action for sFlow or IPFIX.  The given probability is
2376  * the number of packets out of UINT32_MAX to sample.  The given
2377  * cookie is passed back in the callback for each sampled packet.
2378  */
2379 static size_t
2380 compose_sample_action(const struct xbridge *xbridge,
2381                       struct ofpbuf *odp_actions,
2382                       const struct flow *flow,
2383                       const uint32_t probability,
2384                       const union user_action_cookie *cookie,
2385                       const size_t cookie_size,
2386                       const odp_port_t tunnel_out_port)
2387 {
2388     size_t sample_offset, actions_offset;
2389     odp_port_t odp_port;
2390     int cookie_offset;
2391     uint32_t pid;
2392
2393     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
2394
2395     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
2396
2397     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
2398
2399     odp_port = ofp_port_to_odp_port(xbridge, flow->in_port.ofp_port);
2400     pid = dpif_port_get_pid(xbridge->dpif, odp_port,
2401                             flow_hash_5tuple(flow, 0));
2402     cookie_offset = odp_put_userspace_action(pid, cookie, cookie_size,
2403                                              tunnel_out_port, odp_actions);
2404
2405     nl_msg_end_nested(odp_actions, actions_offset);
2406     nl_msg_end_nested(odp_actions, sample_offset);
2407     return cookie_offset;
2408 }
2409
2410 static void
2411 compose_sflow_cookie(const struct xbridge *xbridge, ovs_be16 vlan_tci,
2412                      odp_port_t odp_port, unsigned int n_outputs,
2413                      union user_action_cookie *cookie)
2414 {
2415     int ifindex;
2416
2417     cookie->type = USER_ACTION_COOKIE_SFLOW;
2418     cookie->sflow.vlan_tci = vlan_tci;
2419
2420     /* See http://www.sflow.org/sflow_version_5.txt (search for "Input/output
2421      * port information") for the interpretation of cookie->output. */
2422     switch (n_outputs) {
2423     case 0:
2424         /* 0x40000000 | 256 means "packet dropped for unknown reason". */
2425         cookie->sflow.output = 0x40000000 | 256;
2426         break;
2427
2428     case 1:
2429         ifindex = dpif_sflow_odp_port_to_ifindex(xbridge->sflow, odp_port);
2430         if (ifindex) {
2431             cookie->sflow.output = ifindex;
2432             break;
2433         }
2434         /* Fall through. */
2435     default:
2436         /* 0x80000000 means "multiple output ports. */
2437         cookie->sflow.output = 0x80000000 | n_outputs;
2438         break;
2439     }
2440 }
2441
2442 /* Compose SAMPLE action for sFlow bridge sampling. */
2443 static size_t
2444 compose_sflow_action(const struct xbridge *xbridge,
2445                      struct ofpbuf *odp_actions,
2446                      const struct flow *flow,
2447                      odp_port_t odp_port)
2448 {
2449     uint32_t probability;
2450     union user_action_cookie cookie;
2451
2452     if (!xbridge->sflow || flow->in_port.ofp_port == OFPP_NONE) {
2453         return 0;
2454     }
2455
2456     probability = dpif_sflow_get_probability(xbridge->sflow);
2457     compose_sflow_cookie(xbridge, htons(0), odp_port,
2458                          odp_port == ODPP_NONE ? 0 : 1, &cookie);
2459
2460     return compose_sample_action(xbridge, odp_actions, flow,  probability,
2461                                  &cookie, sizeof cookie.sflow, ODPP_NONE);
2462 }
2463
2464 static void
2465 compose_flow_sample_cookie(uint16_t probability, uint32_t collector_set_id,
2466                            uint32_t obs_domain_id, uint32_t obs_point_id,
2467                            union user_action_cookie *cookie)
2468 {
2469     cookie->type = USER_ACTION_COOKIE_FLOW_SAMPLE;
2470     cookie->flow_sample.probability = probability;
2471     cookie->flow_sample.collector_set_id = collector_set_id;
2472     cookie->flow_sample.obs_domain_id = obs_domain_id;
2473     cookie->flow_sample.obs_point_id = obs_point_id;
2474 }
2475
2476 static void
2477 compose_ipfix_cookie(union user_action_cookie *cookie,
2478                      odp_port_t output_odp_port)
2479 {
2480     cookie->type = USER_ACTION_COOKIE_IPFIX;
2481     cookie->ipfix.output_odp_port = output_odp_port;
2482 }
2483
2484 /* Compose SAMPLE action for IPFIX bridge sampling. */
2485 static void
2486 compose_ipfix_action(const struct xbridge *xbridge,
2487                      struct ofpbuf *odp_actions,
2488                      const struct flow *flow,
2489                      odp_port_t output_odp_port)
2490 {
2491     uint32_t probability;
2492     union user_action_cookie cookie;
2493     odp_port_t tunnel_out_port = ODPP_NONE;
2494
2495     if (!xbridge->ipfix || flow->in_port.ofp_port == OFPP_NONE) {
2496         return;
2497     }
2498
2499     /* For input case, output_odp_port is ODPP_NONE, which is an invalid port
2500      * number. */
2501     if (output_odp_port == ODPP_NONE &&
2502         !dpif_ipfix_get_bridge_exporter_input_sampling(xbridge->ipfix)) {
2503         return;
2504     }
2505
2506     /* For output case, output_odp_port is valid*/
2507     if (output_odp_port != ODPP_NONE) {
2508         if (!dpif_ipfix_get_bridge_exporter_output_sampling(xbridge->ipfix)) {
2509             return;
2510         }
2511         /* If tunnel sampling is enabled, put an additional option attribute:
2512          * OVS_USERSPACE_ATTR_TUNNEL_OUT_PORT
2513          */
2514         if (dpif_ipfix_get_bridge_exporter_tunnel_sampling(xbridge->ipfix) &&
2515             dpif_ipfix_get_tunnel_port(xbridge->ipfix, output_odp_port) ) {
2516            tunnel_out_port = output_odp_port;
2517         }
2518     }
2519
2520     probability = dpif_ipfix_get_bridge_exporter_probability(xbridge->ipfix);
2521     compose_ipfix_cookie(&cookie, output_odp_port);
2522
2523     compose_sample_action(xbridge, odp_actions, flow,  probability,
2524                           &cookie, sizeof cookie.ipfix, tunnel_out_port);
2525 }
2526
2527 /* SAMPLE action for sFlow must be first action in any given list of
2528  * actions.  At this point we do not have all information required to
2529  * build it. So try to build sample action as complete as possible. */
2530 static void
2531 add_sflow_action(struct xlate_ctx *ctx)
2532 {
2533     ctx->user_cookie_offset = compose_sflow_action(ctx->xbridge,
2534                                                    ctx->xout->odp_actions,
2535                                                    &ctx->xin->flow, ODPP_NONE);
2536     ctx->sflow_odp_port = 0;
2537     ctx->sflow_n_outputs = 0;
2538 }
2539
2540 /* SAMPLE action for IPFIX must be 1st or 2nd action in any given list
2541  * of actions, eventually after the SAMPLE action for sFlow. */
2542 static void
2543 add_ipfix_action(struct xlate_ctx *ctx)
2544 {
2545     compose_ipfix_action(ctx->xbridge, ctx->xout->odp_actions,
2546                          &ctx->xin->flow, ODPP_NONE);
2547 }
2548
2549 static void
2550 add_ipfix_output_action(struct xlate_ctx *ctx, odp_port_t port)
2551 {
2552     compose_ipfix_action(ctx->xbridge, ctx->xout->odp_actions,
2553                          &ctx->xin->flow, port);
2554 }
2555
2556 /* Fix SAMPLE action according to data collected while composing ODP actions.
2557  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
2558  * USERSPACE action's user-cookie which is required for sflow. */
2559 static void
2560 fix_sflow_action(struct xlate_ctx *ctx)
2561 {
2562     const struct flow *base = &ctx->base_flow;
2563     union user_action_cookie *cookie;
2564
2565     if (!ctx->user_cookie_offset) {
2566         return;
2567     }
2568
2569     cookie = ofpbuf_at(ctx->xout->odp_actions, ctx->user_cookie_offset,
2570                        sizeof cookie->sflow);
2571     ovs_assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
2572
2573     compose_sflow_cookie(ctx->xbridge, base->vlan_tci,
2574                          ctx->sflow_odp_port, ctx->sflow_n_outputs, cookie);
2575 }
2576
2577 static enum slow_path_reason
2578 process_special(struct xlate_ctx *ctx, const struct flow *flow,
2579                 const struct xport *xport, const struct dp_packet *packet)
2580 {
2581     struct flow_wildcards *wc = &ctx->xout->wc;
2582     const struct xbridge *xbridge = ctx->xbridge;
2583
2584     if (!xport) {
2585         return 0;
2586     } else if (xport->cfm && cfm_should_process_flow(xport->cfm, flow, wc)) {
2587         if (packet) {
2588             cfm_process_heartbeat(xport->cfm, packet);
2589         }
2590         return SLOW_CFM;
2591     } else if (xport->bfd && bfd_should_process_flow(xport->bfd, flow, wc)) {
2592         if (packet) {
2593             bfd_process_packet(xport->bfd, flow, packet);
2594             /* If POLL received, immediately sends FINAL back. */
2595             if (bfd_should_send_packet(xport->bfd)) {
2596                 ofproto_dpif_monitor_port_send_soon(xport->ofport);
2597             }
2598         }
2599         return SLOW_BFD;
2600     } else if (xport->xbundle && xport->xbundle->lacp
2601                && flow->dl_type == htons(ETH_TYPE_LACP)) {
2602         if (packet) {
2603             lacp_process_packet(xport->xbundle->lacp, xport->ofport, packet);
2604         }
2605         return SLOW_LACP;
2606     } else if ((xbridge->stp || xbridge->rstp) &&
2607                stp_should_process_flow(flow, wc)) {
2608         if (packet) {
2609             xbridge->stp
2610                 ? stp_process_packet(xport, packet)
2611                 : rstp_process_packet(xport, packet);
2612         }
2613         return SLOW_STP;
2614     } else if (xport->lldp && lldp_should_process_flow(flow)) {
2615         if (packet) {
2616             lldp_process_packet(xport->lldp, packet);
2617         }
2618         return SLOW_LLDP;
2619     } else {
2620         return 0;
2621     }
2622 }
2623
2624 static int
2625 tnl_route_lookup_flow(const struct flow *oflow,
2626                       ovs_be32 *ip, struct xport **out_port)
2627 {
2628     char out_dev[IFNAMSIZ];
2629     struct xbridge *xbridge;
2630     struct xlate_cfg *xcfg;
2631     ovs_be32 gw;
2632
2633     if (!ovs_router_lookup(oflow->tunnel.ip_dst, out_dev, &gw)) {
2634         return -ENOENT;
2635     }
2636
2637     if (gw) {
2638         *ip = gw;
2639     } else {
2640         *ip = oflow->tunnel.ip_dst;
2641     }
2642
2643     xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
2644     ovs_assert(xcfg);
2645
2646     HMAP_FOR_EACH (xbridge, hmap_node, &xcfg->xbridges) {
2647         if (!strncmp(xbridge->name, out_dev, IFNAMSIZ)) {
2648             struct xport *port;
2649
2650             HMAP_FOR_EACH (port, ofp_node, &xbridge->xports) {
2651                 if (!strncmp(netdev_get_name(port->netdev), out_dev, IFNAMSIZ)) {
2652                     *out_port = port;
2653                     return 0;
2654                 }
2655             }
2656         }
2657     }
2658     return -ENOENT;
2659 }
2660
2661 static int
2662 xlate_flood_packet(struct xbridge *xbridge, struct dp_packet *packet)
2663 {
2664     struct ofpact_output output;
2665     struct flow flow;
2666
2667     ofpact_init(&output.ofpact, OFPACT_OUTPUT, sizeof output);
2668     /* Use OFPP_NONE as the in_port to avoid special packet processing. */
2669     flow_extract(packet, &flow);
2670     flow.in_port.ofp_port = OFPP_NONE;
2671     output.port = OFPP_FLOOD;
2672     output.max_len = 0;
2673
2674     return ofproto_dpif_execute_actions(xbridge->ofproto, &flow, NULL,
2675                                         &output.ofpact, sizeof output,
2676                                         packet);
2677 }
2678
2679 static void
2680 tnl_send_arp_request(const struct xport *out_dev, const uint8_t eth_src[ETH_ADDR_LEN],
2681                      ovs_be32 ip_src, ovs_be32 ip_dst)
2682 {
2683     struct xbridge *xbridge = out_dev->xbridge;
2684     struct dp_packet packet;
2685
2686     dp_packet_init(&packet, 0);
2687     compose_arp(&packet, eth_src, ip_src, ip_dst);
2688
2689     xlate_flood_packet(xbridge, &packet);
2690     dp_packet_uninit(&packet);
2691 }
2692
2693 static int
2694 build_tunnel_send(const struct xlate_ctx *ctx, const struct xport *xport,
2695                   const struct flow *flow, odp_port_t tunnel_odp_port)
2696 {
2697     struct ovs_action_push_tnl tnl_push_data;
2698     struct xport *out_dev = NULL;
2699     ovs_be32 s_ip, d_ip = 0;
2700     uint8_t smac[ETH_ADDR_LEN];
2701     uint8_t dmac[ETH_ADDR_LEN];
2702     int err;
2703
2704     err = tnl_route_lookup_flow(flow, &d_ip, &out_dev);
2705     if (err) {
2706         return err;
2707     }
2708
2709     /* Use mac addr of bridge port of the peer. */
2710     err = netdev_get_etheraddr(out_dev->netdev, smac);
2711     if (err) {
2712         return err;
2713     }
2714
2715     err = netdev_get_in4(out_dev->netdev, (struct in_addr *) &s_ip, NULL);
2716     if (err) {
2717         return err;
2718     }
2719
2720     err = tnl_arp_lookup(out_dev->xbridge->name, d_ip, dmac);
2721     if (err) {
2722         tnl_send_arp_request(out_dev, smac, s_ip, d_ip);
2723         return err;
2724     }
2725     if (ctx->xin->xcache) {
2726         struct xc_entry *entry;
2727
2728         entry = xlate_cache_add_entry(ctx->xin->xcache, XC_TNL_ARP);
2729         ovs_strlcpy(entry->u.tnl_arp_cache.br_name, out_dev->xbridge->name,
2730                     sizeof entry->u.tnl_arp_cache.br_name);
2731         entry->u.tnl_arp_cache.d_ip = d_ip;
2732     }
2733     err = tnl_port_build_header(xport->ofport, flow,
2734                                 dmac, smac, s_ip, &tnl_push_data);
2735     if (err) {
2736         return err;
2737     }
2738     tnl_push_data.tnl_port = odp_to_u32(tunnel_odp_port);
2739     tnl_push_data.out_port = odp_to_u32(out_dev->odp_port);
2740     odp_put_tnl_push_action(ctx->xout->odp_actions, &tnl_push_data);
2741     return 0;
2742 }
2743
2744 static void
2745 compose_output_action__(struct xlate_ctx *ctx, ofp_port_t ofp_port,
2746                         const struct xlate_bond_recirc *xr, bool check_stp)
2747 {
2748     const struct xport *xport = get_ofp_port(ctx->xbridge, ofp_port);
2749     struct flow_wildcards *wc = &ctx->xout->wc;
2750     struct flow *flow = &ctx->xin->flow;
2751     struct flow_tnl flow_tnl;
2752     ovs_be16 flow_vlan_tci;
2753     uint32_t flow_pkt_mark;
2754     uint8_t flow_nw_tos;
2755     odp_port_t out_port, odp_port;
2756     bool tnl_push_pop_send = false;
2757     uint8_t dscp;
2758
2759     /* If 'struct flow' gets additional metadata, we'll need to zero it out
2760      * before traversing a patch port. */
2761     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 31);
2762     memset(&flow_tnl, 0, sizeof flow_tnl);
2763
2764     if (!xport) {
2765         xlate_report(ctx, "Nonexistent output port");
2766         return;
2767     } else if (xport->config & OFPUTIL_PC_NO_FWD) {
2768         xlate_report(ctx, "OFPPC_NO_FWD set, skipping output");
2769         return;
2770     } else if (check_stp) {
2771         if (is_stp(&ctx->base_flow)) {
2772             if (!xport_stp_should_forward_bpdu(xport) &&
2773                 !xport_rstp_should_manage_bpdu(xport)) {
2774                 if (ctx->xbridge->stp != NULL) {
2775                     xlate_report(ctx, "STP not in listening state, "
2776                             "skipping bpdu output");
2777                 } else if (ctx->xbridge->rstp != NULL) {
2778                     xlate_report(ctx, "RSTP not managing BPDU in this state, "
2779                             "skipping bpdu output");
2780                 }
2781                 return;
2782             }
2783         } else if (!xport_stp_forward_state(xport) ||
2784                    !xport_rstp_forward_state(xport)) {
2785             if (ctx->xbridge->stp != NULL) {
2786                 xlate_report(ctx, "STP not in forwarding state, "
2787                         "skipping output");
2788             } else if (ctx->xbridge->rstp != NULL) {
2789                 xlate_report(ctx, "RSTP not in forwarding state, "
2790                         "skipping output");
2791             }
2792             return;
2793         }
2794     }
2795
2796     if (mbridge_has_mirrors(ctx->xbridge->mbridge) && xport->xbundle) {
2797         ctx->xout->mirrors |= xbundle_mirror_dst(xport->xbundle->xbridge,
2798                                                  xport->xbundle);
2799     }
2800
2801     if (xport->peer) {
2802         const struct xport *peer = xport->peer;
2803         struct flow old_flow = ctx->xin->flow;
2804         bool old_was_mpls = ctx->was_mpls;
2805         enum slow_path_reason special;
2806         struct ofpbuf old_stack = ctx->stack;
2807         union mf_subvalue new_stack[1024 / sizeof(union mf_subvalue)];
2808         struct ofpbuf old_action_set = ctx->action_set;
2809         uint64_t actset_stub[1024 / 8];
2810
2811         ofpbuf_use_stub(&ctx->stack, new_stack, sizeof new_stack);
2812         ofpbuf_use_stub(&ctx->action_set, actset_stub, sizeof actset_stub);
2813         ctx->xbridge = peer->xbridge;
2814         flow->in_port.ofp_port = peer->ofp_port;
2815         flow->metadata = htonll(0);
2816         memset(&flow->tunnel, 0, sizeof flow->tunnel);
2817         memset(flow->regs, 0, sizeof flow->regs);
2818         flow->actset_output = OFPP_UNSET;
2819
2820         special = process_special(ctx, &ctx->xin->flow, peer,
2821                                   ctx->xin->packet);
2822         if (special) {
2823             ctx->xout->slow |= special;
2824         } else if (may_receive(peer, ctx)) {
2825             if (xport_stp_forward_state(peer) && xport_rstp_forward_state(peer)) {
2826                 xlate_table_action(ctx, flow->in_port.ofp_port, 0, true, true);
2827                 if (ctx->action_set.size) {
2828                     /* Translate action set only if not dropping the packet and
2829                      * not recirculating. */
2830                     if (!exit_recirculates(ctx)) {
2831                         xlate_action_set(ctx);
2832                     }
2833                 }
2834                 /* Check if need to recirculate. */
2835                 if (exit_recirculates(ctx)) {
2836                     compose_recirculate_action(ctx);
2837                 }
2838             } else {
2839                 /* Forwarding is disabled by STP and RSTP.  Let OFPP_NORMAL and
2840                  * the learning action look at the packet, then drop it. */
2841                 struct flow old_base_flow = ctx->base_flow;
2842                 size_t old_size = ctx->xout->odp_actions->size;
2843                 mirror_mask_t old_mirrors = ctx->xout->mirrors;
2844
2845                 xlate_table_action(ctx, flow->in_port.ofp_port, 0, true, true);
2846                 ctx->xout->mirrors = old_mirrors;
2847                 ctx->base_flow = old_base_flow;
2848                 ctx->xout->odp_actions->size = old_size;
2849
2850                 /* Undo changes that may have been done for recirculation. */
2851                 if (exit_recirculates(ctx)) {
2852                     ctx->action_set.size = ctx->recirc_action_offset;
2853                     ctx->recirc_action_offset = -1;
2854                     ctx->last_unroll_offset = -1;
2855                 }
2856             }
2857         }
2858
2859         ctx->xin->flow = old_flow;
2860         ctx->xbridge = xport->xbridge;
2861         ofpbuf_uninit(&ctx->action_set);
2862         ctx->action_set = old_action_set;
2863         ofpbuf_uninit(&ctx->stack);
2864         ctx->stack = old_stack;
2865
2866         /* The peer bridge popping MPLS should have no effect on the original
2867          * bridge. */
2868         ctx->was_mpls = old_was_mpls;
2869
2870         /* The fact that the peer bridge exits (for any reason) does not mean
2871          * that the original bridge should exit.  Specifically, if the peer
2872          * bridge recirculates (which typically modifies the packet), the
2873          * original bridge must continue processing with the original, not the
2874          * recirculated packet! */
2875         ctx->exit = false;
2876
2877         if (ctx->xin->resubmit_stats) {
2878             netdev_vport_inc_tx(xport->netdev, ctx->xin->resubmit_stats);
2879             netdev_vport_inc_rx(peer->netdev, ctx->xin->resubmit_stats);
2880             if (peer->bfd) {
2881                 bfd_account_rx(peer->bfd, ctx->xin->resubmit_stats);
2882             }
2883         }
2884         if (ctx->xin->xcache) {
2885             struct xc_entry *entry;
2886
2887             entry = xlate_cache_add_entry(ctx->xin->xcache, XC_NETDEV);
2888             entry->u.dev.tx = netdev_ref(xport->netdev);
2889             entry->u.dev.rx = netdev_ref(peer->netdev);
2890             entry->u.dev.bfd = bfd_ref(peer->bfd);
2891         }
2892         return;
2893     }
2894
2895     flow_vlan_tci = flow->vlan_tci;
2896     flow_pkt_mark = flow->pkt_mark;
2897     flow_nw_tos = flow->nw_tos;
2898
2899     if (count_skb_priorities(xport)) {
2900         memset(&wc->masks.skb_priority, 0xff, sizeof wc->masks.skb_priority);
2901         if (dscp_from_skb_priority(xport, flow->skb_priority, &dscp)) {
2902             wc->masks.nw_tos |= IP_DSCP_MASK;
2903             flow->nw_tos &= ~IP_DSCP_MASK;
2904             flow->nw_tos |= dscp;
2905         }
2906     }
2907
2908     if (xport->is_tunnel) {
2909          /* Save tunnel metadata so that changes made due to
2910           * the Logical (tunnel) Port are not visible for any further
2911           * matches, while explicit set actions on tunnel metadata are.
2912           */
2913         flow_tnl = flow->tunnel;
2914         odp_port = tnl_port_send(xport->ofport, flow, &ctx->xout->wc);
2915         if (odp_port == ODPP_NONE) {
2916             xlate_report(ctx, "Tunneling decided against output");
2917             goto out; /* restore flow_nw_tos */
2918         }
2919         if (flow->tunnel.ip_dst == ctx->orig_tunnel_ip_dst) {
2920             xlate_report(ctx, "Not tunneling to our own address");
2921             goto out; /* restore flow_nw_tos */
2922         }
2923         if (ctx->xin->resubmit_stats) {
2924             netdev_vport_inc_tx(xport->netdev, ctx->xin->resubmit_stats);
2925         }
2926         if (ctx->xin->xcache) {
2927             struct xc_entry *entry;
2928
2929             entry = xlate_cache_add_entry(ctx->xin->xcache, XC_NETDEV);
2930             entry->u.dev.tx = netdev_ref(xport->netdev);
2931         }
2932         out_port = odp_port;
2933         if (ovs_native_tunneling_is_on(ctx->xbridge->ofproto)) {
2934             tnl_push_pop_send = true;
2935         } else {
2936             commit_odp_tunnel_action(flow, &ctx->base_flow,
2937                                      ctx->xout->odp_actions);
2938             flow->tunnel = flow_tnl; /* Restore tunnel metadata */
2939         }
2940     } else {
2941         odp_port = xport->odp_port;
2942         out_port = odp_port;
2943         if (ofproto_has_vlan_splinters(ctx->xbridge->ofproto)) {
2944             ofp_port_t vlandev_port;
2945
2946             wc->masks.vlan_tci |= htons(VLAN_VID_MASK | VLAN_CFI);
2947             vlandev_port = vsp_realdev_to_vlandev(ctx->xbridge->ofproto,
2948                                                   ofp_port, flow->vlan_tci);
2949             if (vlandev_port != ofp_port) {
2950                 out_port = ofp_port_to_odp_port(ctx->xbridge, vlandev_port);
2951                 flow->vlan_tci = htons(0);
2952             }
2953         }
2954     }
2955
2956     if (out_port != ODPP_NONE) {
2957         ctx->xout->slow |= commit_odp_actions(flow, &ctx->base_flow,
2958                                               ctx->xout->odp_actions,
2959                                               wc,
2960                                               ctx->xbridge->masked_set_action);
2961
2962         if (xr) {
2963             struct ovs_action_hash *act_hash;
2964
2965             /* Hash action. */
2966             act_hash = nl_msg_put_unspec_uninit(ctx->xout->odp_actions,
2967                                                 OVS_ACTION_ATTR_HASH,
2968                                                 sizeof *act_hash);
2969             act_hash->hash_alg = xr->hash_alg;
2970             act_hash->hash_basis = xr->hash_basis;
2971
2972             /* Recirc action. */
2973             nl_msg_put_u32(ctx->xout->odp_actions, OVS_ACTION_ATTR_RECIRC,
2974                            xr->recirc_id);
2975         } else {
2976
2977             if (tnl_push_pop_send) {
2978                 build_tunnel_send(ctx, xport, flow, odp_port);
2979                 flow->tunnel = flow_tnl; /* Restore tunnel metadata */
2980             } else {
2981                 odp_port_t odp_tnl_port = ODPP_NONE;
2982
2983                 /* XXX: Write better Filter for tunnel port. We can use inport
2984                 * int tunnel-port flow to avoid these checks completely. */
2985                 if (ofp_port == OFPP_LOCAL &&
2986                     ovs_native_tunneling_is_on(ctx->xbridge->ofproto)) {
2987
2988                     odp_tnl_port = tnl_port_map_lookup(flow, wc);
2989                 }
2990
2991                 if (odp_tnl_port != ODPP_NONE) {
2992                     nl_msg_put_odp_port(ctx->xout->odp_actions,
2993                                         OVS_ACTION_ATTR_TUNNEL_POP,
2994                                         odp_tnl_port);
2995                 } else {
2996                     /* Tunnel push-pop action is not compatible with
2997                      * IPFIX action. */
2998                     add_ipfix_output_action(ctx, out_port);
2999                     nl_msg_put_odp_port(ctx->xout->odp_actions,
3000                                         OVS_ACTION_ATTR_OUTPUT,
3001                                         out_port);
3002                }
3003            }
3004         }
3005
3006         ctx->sflow_odp_port = odp_port;
3007         ctx->sflow_n_outputs++;
3008         ctx->xout->nf_output_iface = ofp_port;
3009     }
3010
3011  out:
3012     /* Restore flow */
3013     flow->vlan_tci = flow_vlan_tci;
3014     flow->pkt_mark = flow_pkt_mark;
3015     flow->nw_tos = flow_nw_tos;
3016 }
3017
3018 static void
3019 compose_output_action(struct xlate_ctx *ctx, ofp_port_t ofp_port,
3020                       const struct xlate_bond_recirc *xr)
3021 {
3022     compose_output_action__(ctx, ofp_port, xr, true);
3023 }
3024
3025 static void
3026 xlate_recursively(struct xlate_ctx *ctx, struct rule_dpif *rule)
3027 {
3028     struct rule_dpif *old_rule = ctx->rule;
3029     ovs_be64 old_cookie = ctx->rule_cookie;
3030     const struct rule_actions *actions;
3031
3032     if (ctx->xin->resubmit_stats) {
3033         rule_dpif_credit_stats(rule, ctx->xin->resubmit_stats);
3034     }
3035
3036     ctx->resubmits++;
3037     ctx->recurse++;
3038     ctx->rule = rule;
3039     ctx->rule_cookie = rule_dpif_get_flow_cookie(rule);
3040     actions = rule_dpif_get_actions(rule);
3041     do_xlate_actions(actions->ofpacts, actions->ofpacts_len, ctx);
3042     ctx->rule_cookie = old_cookie;
3043     ctx->rule = old_rule;
3044     ctx->recurse--;
3045 }
3046
3047 static bool
3048 xlate_resubmit_resource_check(struct xlate_ctx *ctx)
3049 {
3050     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
3051
3052     if (ctx->recurse >= MAX_RESUBMIT_RECURSION + MAX_INTERNAL_RESUBMITS) {
3053         VLOG_ERR_RL(&rl, "resubmit actions recursed over %d times",
3054                     MAX_RESUBMIT_RECURSION);
3055     } else if (ctx->resubmits >= MAX_RESUBMITS + MAX_INTERNAL_RESUBMITS) {
3056         VLOG_ERR_RL(&rl, "over %d resubmit actions", MAX_RESUBMITS);
3057     } else if (ctx->xout->odp_actions->size > UINT16_MAX) {
3058         VLOG_ERR_RL(&rl, "resubmits yielded over 64 kB of actions");
3059     } else if (ctx->stack.size >= 65536) {
3060         VLOG_ERR_RL(&rl, "resubmits yielded over 64 kB of stack");
3061     } else {
3062         return true;
3063     }
3064
3065     return false;
3066 }
3067
3068 static void
3069 xlate_table_action(struct xlate_ctx *ctx, ofp_port_t in_port, uint8_t table_id,
3070                    bool may_packet_in, bool honor_table_miss)
3071 {
3072     /* Check if we need to recirculate before matching in a table. */
3073     if (ctx->was_mpls) {
3074         ctx_trigger_recirculation(ctx);
3075         return;
3076     }
3077     if (xlate_resubmit_resource_check(ctx)) {
3078         struct flow_wildcards *wc;
3079         uint8_t old_table_id = ctx->table_id;
3080         struct rule_dpif *rule;
3081
3082         ctx->table_id = table_id;
3083         wc = (ctx->xin->skip_wildcards) ? NULL : &ctx->xout->wc;
3084
3085         rule = rule_dpif_lookup_from_table(ctx->xbridge->ofproto,
3086                                            &ctx->xin->flow, wc,
3087                                            ctx->xin->xcache != NULL,
3088                                            ctx->xin->resubmit_stats,
3089                                            &ctx->table_id, in_port,
3090                                            may_packet_in, honor_table_miss);
3091
3092         if (OVS_UNLIKELY(ctx->xin->resubmit_hook)) {
3093             ctx->xin->resubmit_hook(ctx->xin, rule, ctx->recurse + 1);
3094         }
3095
3096         if (rule) {
3097             /* Fill in the cache entry here instead of xlate_recursively
3098              * to make the reference counting more explicit.  We take a
3099              * reference in the lookups above if we are going to cache the
3100              * rule. */
3101             if (ctx->xin->xcache) {
3102                 struct xc_entry *entry;
3103
3104                 entry = xlate_cache_add_entry(ctx->xin->xcache, XC_RULE);
3105                 entry->u.rule = rule;
3106             }
3107             xlate_recursively(ctx, rule);
3108         }
3109
3110         ctx->table_id = old_table_id;
3111         return;
3112     }
3113
3114     ctx->exit = true;
3115 }
3116
3117 static void
3118 xlate_group_stats(struct xlate_ctx *ctx, struct group_dpif *group,
3119                   struct ofputil_bucket *bucket)
3120 {
3121     if (ctx->xin->resubmit_stats) {
3122         group_dpif_credit_stats(group, bucket, ctx->xin->resubmit_stats);
3123     }
3124     if (ctx->xin->xcache) {
3125         struct xc_entry *entry;
3126
3127         entry = xlate_cache_add_entry(ctx->xin->xcache, XC_GROUP);
3128         entry->u.group.group = group_dpif_ref(group);
3129         entry->u.group.bucket = bucket;
3130     }
3131 }
3132
3133 static void
3134 xlate_group_bucket(struct xlate_ctx *ctx, struct ofputil_bucket *bucket)
3135 {
3136     uint64_t action_list_stub[1024 / 8];
3137     struct ofpbuf action_list, action_set;
3138     struct flow old_flow = ctx->xin->flow;
3139     bool old_was_mpls = ctx->was_mpls;
3140
3141     ofpbuf_use_const(&action_set, bucket->ofpacts, bucket->ofpacts_len);
3142     ofpbuf_use_stub(&action_list, action_list_stub, sizeof action_list_stub);
3143
3144     ofpacts_execute_action_set(&action_list, &action_set);
3145     ctx->recurse++;
3146     do_xlate_actions(action_list.data, action_list.size, ctx);
3147     ctx->recurse--;
3148
3149     ofpbuf_uninit(&action_set);
3150     ofpbuf_uninit(&action_list);
3151
3152     /* Check if need to recirculate. */
3153     if (exit_recirculates(ctx)) {
3154         compose_recirculate_action(ctx);
3155     }
3156
3157     /* Roll back flow to previous state.
3158      * This is equivalent to cloning the packet for each bucket.
3159      *
3160      * As a side effect any subsequently applied actions will
3161      * also effectively be applied to a clone of the packet taken
3162      * just before applying the all or indirect group.
3163      *
3164      * Note that group buckets are action sets, hence they cannot modify the
3165      * main action set.  Also any stack actions are ignored when executing an
3166      * action set, so group buckets cannot change the stack either.
3167      * However, we do allow resubmit actions in group buckets, which could
3168      * break the above assumptions.  It is up to the controller to not mess up
3169      * with the action_set and stack in the tables resubmitted to from
3170      * group buckets. */
3171     ctx->xin->flow = old_flow;
3172
3173     /* The group bucket popping MPLS should have no effect after bucket
3174      * execution. */
3175     ctx->was_mpls = old_was_mpls;
3176
3177     /* The fact that the group bucket exits (for any reason) does not mean that
3178      * the translation after the group action should exit.  Specifically, if
3179      * the group bucket recirculates (which typically modifies the packet), the
3180      * actions after the group action must continue processing with the
3181      * original, not the recirculated packet! */
3182     ctx->exit = false;
3183 }
3184
3185 static void
3186 xlate_all_group(struct xlate_ctx *ctx, struct group_dpif *group)
3187 {
3188     struct ofputil_bucket *bucket;
3189     const struct ovs_list *buckets;
3190
3191     group_dpif_get_buckets(group, &buckets);
3192
3193     LIST_FOR_EACH (bucket, list_node, buckets) {
3194         xlate_group_bucket(ctx, bucket);
3195     }
3196     xlate_group_stats(ctx, group, NULL);
3197 }
3198
3199 static void
3200 xlate_ff_group(struct xlate_ctx *ctx, struct group_dpif *group)
3201 {
3202     struct ofputil_bucket *bucket;
3203
3204     bucket = group_first_live_bucket(ctx, group, 0);
3205     if (bucket) {
3206         xlate_group_bucket(ctx, bucket);
3207         xlate_group_stats(ctx, group, bucket);
3208     }
3209 }
3210
3211 static void
3212 xlate_default_select_group(struct xlate_ctx *ctx, struct group_dpif *group)
3213 {
3214     struct flow_wildcards *wc = &ctx->xout->wc;
3215     struct ofputil_bucket *bucket;
3216     uint32_t basis;
3217
3218     basis = flow_hash_symmetric_l4(&ctx->xin->flow, 0);
3219     flow_mask_hash_fields(&ctx->xin->flow, wc, NX_HASH_FIELDS_SYMMETRIC_L4);
3220     bucket = group_best_live_bucket(ctx, group, basis);
3221     if (bucket) {
3222         xlate_group_bucket(ctx, bucket);
3223         xlate_group_stats(ctx, group, bucket);
3224     }
3225 }
3226
3227 static void
3228 xlate_hash_fields_select_group(struct xlate_ctx *ctx, struct group_dpif *group)
3229 {
3230     struct mf_bitmap hash_fields = MF_BITMAP_INITIALIZER;
3231     struct flow_wildcards *wc = &ctx->xout->wc;
3232     const struct field_array *fields;
3233     struct ofputil_bucket *bucket;
3234     uint32_t basis;
3235     int i;
3236
3237     fields = group_dpif_get_fields(group);
3238     basis = hash_uint64(group_dpif_get_selection_method_param(group));
3239
3240     /* Determine which fields to hash */
3241     for (i = 0; i < MFF_N_IDS; i++) {
3242         if (bitmap_is_set(fields->used.bm, i)) {
3243             const struct mf_field *mf;
3244
3245             /* If the field is already present in 'hash_fields' then
3246              * this loop has already checked that it and its pre-requisites
3247              * are present in the flow and its pre-requisites have
3248              * already been added to 'hash_fields'. There is nothing more
3249              * to do here and as an optimisation the loop can continue. */
3250             if (bitmap_is_set(hash_fields.bm, i)) {
3251                 continue;
3252             }
3253
3254             mf = mf_from_id(i);
3255
3256             /* Only hash a field if it and its pre-requisites are present
3257              * in the flow. */
3258             if (!mf_are_prereqs_ok(mf, &ctx->xin->flow)) {
3259                 continue;
3260             }
3261
3262             /* Hash both the field and its pre-requisites */
3263             mf_bitmap_set_field_and_prereqs(mf, &hash_fields);
3264         }
3265     }
3266
3267     /* Hash the fields */
3268     for (i = 0; i < MFF_N_IDS; i++) {
3269         if (bitmap_is_set(hash_fields.bm, i)) {
3270             const struct mf_field *mf = mf_from_id(i);
3271             union mf_value value;
3272             int j;
3273
3274             mf_get_value(mf, &ctx->xin->flow, &value);
3275             /* This seems inefficient but so does apply_mask() */
3276             for (j = 0; j < mf->n_bytes; j++) {
3277                 ((uint8_t *) &value)[j] &= ((uint8_t *) &fields->value[i])[j];
3278             }
3279             basis = hash_bytes(&value, mf->n_bytes, basis);
3280
3281             mf_mask_field(mf, &wc->masks);
3282         }
3283     }
3284
3285     bucket = group_best_live_bucket(ctx, group, basis);
3286     if (bucket) {
3287         xlate_group_bucket(ctx, bucket);
3288         xlate_group_stats(ctx, group, bucket);
3289     }
3290 }
3291
3292 static void
3293 xlate_select_group(struct xlate_ctx *ctx, struct group_dpif *group)
3294 {
3295     const char *selection_method = group_dpif_get_selection_method(group);
3296
3297     if (selection_method[0] == '\0') {
3298         xlate_default_select_group(ctx, group);
3299     } else if (!strcasecmp("hash", selection_method)) {
3300         xlate_hash_fields_select_group(ctx, group);
3301     } else {
3302         /* Parsing of groups should ensure this never happens */
3303         OVS_NOT_REACHED();
3304     }
3305 }
3306
3307 static void
3308 xlate_group_action__(struct xlate_ctx *ctx, struct group_dpif *group)
3309 {
3310     ctx->in_group = true;
3311
3312     switch (group_dpif_get_type(group)) {
3313     case OFPGT11_ALL:
3314     case OFPGT11_INDIRECT:
3315         xlate_all_group(ctx, group);
3316         break;
3317     case OFPGT11_SELECT:
3318         xlate_select_group(ctx, group);
3319         break;
3320     case OFPGT11_FF:
3321         xlate_ff_group(ctx, group);
3322         break;
3323     default:
3324         OVS_NOT_REACHED();
3325     }
3326     group_dpif_unref(group);
3327
3328     ctx->in_group = false;
3329 }
3330
3331 static bool
3332 xlate_group_resource_check(struct xlate_ctx *ctx)
3333 {
3334     if (!xlate_resubmit_resource_check(ctx)) {
3335         return false;
3336     } else if (ctx->in_group) {
3337         /* Prevent nested translation of OpenFlow groups.
3338          *
3339          * OpenFlow allows this restriction.  We enforce this restriction only
3340          * because, with the current architecture, we would otherwise have to
3341          * take a possibly recursive read lock on the ofgroup rwlock, which is
3342          * unsafe given that POSIX allows taking a read lock to block if there
3343          * is a thread blocked on taking the write lock.  Other solutions
3344          * without this restriction are also possible, but seem unwarranted
3345          * given the current limited use of groups. */
3346         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
3347
3348         VLOG_ERR_RL(&rl, "cannot recursively translate OpenFlow group");
3349         return false;
3350     } else {
3351         return true;
3352     }
3353 }
3354
3355 static bool
3356 xlate_group_action(struct xlate_ctx *ctx, uint32_t group_id)
3357 {
3358     if (xlate_group_resource_check(ctx)) {
3359         struct group_dpif *group;
3360         bool got_group;
3361
3362         got_group = group_dpif_lookup(ctx->xbridge->ofproto, group_id, &group);
3363         if (got_group) {
3364             xlate_group_action__(ctx, group);
3365         } else {
3366             return true;
3367         }
3368     }
3369
3370     return false;
3371 }
3372
3373 static void
3374 xlate_ofpact_resubmit(struct xlate_ctx *ctx,
3375                       const struct ofpact_resubmit *resubmit)
3376 {
3377     ofp_port_t in_port;
3378     uint8_t table_id;
3379     bool may_packet_in = false;
3380     bool honor_table_miss = false;
3381
3382     if (ctx->rule && rule_dpif_is_internal(ctx->rule)) {
3383         /* Still allow missed packets to be sent to the controller
3384          * if resubmitting from an internal table. */
3385         may_packet_in = true;
3386         honor_table_miss = true;
3387     }
3388
3389     in_port = resubmit->in_port;
3390     if (in_port == OFPP_IN_PORT) {
3391         in_port = ctx->xin->flow.in_port.ofp_port;
3392     }
3393
3394     table_id = resubmit->table_id;
3395     if (table_id == 255) {
3396         table_id = ctx->table_id;
3397     }
3398
3399     xlate_table_action(ctx, in_port, table_id, may_packet_in,
3400                        honor_table_miss);
3401 }
3402
3403 static void
3404 flood_packets(struct xlate_ctx *ctx, bool all)
3405 {
3406     const struct xport *xport;
3407
3408     HMAP_FOR_EACH (xport, ofp_node, &ctx->xbridge->xports) {
3409         if (xport->ofp_port == ctx->xin->flow.in_port.ofp_port) {
3410             continue;
3411         }
3412
3413         if (all) {
3414             compose_output_action__(ctx, xport->ofp_port, NULL, false);
3415         } else if (!(xport->config & OFPUTIL_PC_NO_FLOOD)) {
3416             compose_output_action(ctx, xport->ofp_port, NULL);
3417         }
3418     }
3419
3420     ctx->xout->nf_output_iface = NF_OUT_FLOOD;
3421 }
3422
3423 static void
3424 execute_controller_action(struct xlate_ctx *ctx, int len,
3425                           enum ofp_packet_in_reason reason,
3426                           uint16_t controller_id)
3427 {
3428     struct ofproto_packet_in *pin;
3429     struct dp_packet *packet;
3430
3431     ctx->xout->slow |= SLOW_CONTROLLER;
3432     if (!ctx->xin->packet) {
3433         return;
3434     }
3435
3436     packet = dp_packet_clone(ctx->xin->packet);
3437
3438     ctx->xout->slow |= commit_odp_actions(&ctx->xin->flow, &ctx->base_flow,
3439                                           ctx->xout->odp_actions,
3440                                           &ctx->xout->wc,
3441                                           ctx->xbridge->masked_set_action);
3442
3443     odp_execute_actions(NULL, &packet, 1, false,
3444                         ctx->xout->odp_actions->data,
3445                         ctx->xout->odp_actions->size, NULL);
3446
3447     pin = xmalloc(sizeof *pin);
3448     pin->up.packet_len = dp_packet_size(packet);
3449     pin->up.packet = dp_packet_steal_data(packet);
3450     pin->up.reason = reason;
3451     pin->up.table_id = ctx->table_id;
3452     pin->up.cookie = ctx->rule_cookie;
3453
3454     flow_get_metadata(&ctx->xin->flow, &pin->up.fmd);
3455
3456     pin->controller_id = controller_id;
3457     pin->send_len = len;
3458     /* If a rule is a table-miss rule then this is
3459      * a table-miss handled by a table-miss rule.
3460      *
3461      * Else, if rule is internal and has a controller action,
3462      * the later being implied by the rule being processed here,
3463      * then this is a table-miss handled without a table-miss rule.
3464      *
3465      * Otherwise this is not a table-miss. */
3466     pin->miss_type = OFPROTO_PACKET_IN_NO_MISS;
3467     if (ctx->rule) {
3468         if (rule_dpif_is_table_miss(ctx->rule)) {
3469             pin->miss_type = OFPROTO_PACKET_IN_MISS_FLOW;
3470         } else if (rule_dpif_is_internal(ctx->rule)) {
3471             pin->miss_type = OFPROTO_PACKET_IN_MISS_WITHOUT_FLOW;
3472         }
3473     }
3474     ofproto_dpif_send_packet_in(ctx->xbridge->ofproto, pin);
3475     dp_packet_delete(packet);
3476 }
3477
3478 /* Called only when ctx->recirc_action_offset is set. */
3479 static void
3480 compose_recirculate_action(struct xlate_ctx *ctx)
3481 {
3482     struct recirc_metadata md;
3483     uint32_t id;
3484
3485     ctx->xout->slow |= commit_odp_actions(&ctx->xin->flow, &ctx->base_flow,
3486                                           ctx->xout->odp_actions,
3487                                           &ctx->xout->wc,
3488                                           ctx->xbridge->masked_set_action);
3489
3490     recirc_metadata_from_flow(&md, &ctx->xin->flow);
3491
3492     ovs_assert(ctx->recirc_action_offset >= 0);
3493
3494     /* Only allocate recirculation ID if we have a packet. */
3495     if (ctx->xin->packet) {
3496         /* Allocate a unique recirc id for the given metadata state in the
3497          * flow.  The life-cycle of this recirc id is managed by associating it
3498          * with the udpif key ('ukey') created for each new datapath flow. */
3499         id = recirc_alloc_id_ctx(ctx->xbridge->ofproto, 0, &md, &ctx->stack,
3500                                  ctx->recirc_action_offset,
3501                                  ctx->action_set.size, ctx->action_set.data);
3502         if (!id) {
3503             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3504             VLOG_ERR_RL(&rl, "Failed to allocate recirculation id");
3505             return;
3506         }
3507         xlate_out_add_recirc(ctx->xout, id);
3508     } else {
3509         /* Look up an existing recirc id for the given metadata state in the
3510          * flow.  No new reference is taken, as the ID is RCU protected and is
3511          * only required temporarily for verification. */
3512         id = recirc_find_id(ctx->xbridge->ofproto, 0, &md, &ctx->stack,
3513                             ctx->recirc_action_offset,
3514                             ctx->action_set.size, ctx->action_set.data);
3515         /* We let zero 'id' to be used in the RECIRC action below, which will
3516          * fail all revalidations as zero is not a valid recirculation ID. */
3517     }
3518
3519     nl_msg_put_u32(ctx->xout->odp_actions, OVS_ACTION_ATTR_RECIRC, id);
3520
3521     /* Undo changes done by recirculation. */
3522     ctx->action_set.size = ctx->recirc_action_offset;
3523     ctx->recirc_action_offset = -1;
3524     ctx->last_unroll_offset = -1;
3525 }
3526
3527 static void
3528 compose_mpls_push_action(struct xlate_ctx *ctx, struct ofpact_push_mpls *mpls)
3529 {
3530     struct flow_wildcards *wc = &ctx->xout->wc;
3531     struct flow *flow = &ctx->xin->flow;
3532     int n;
3533
3534     ovs_assert(eth_type_mpls(mpls->ethertype));
3535
3536     n = flow_count_mpls_labels(flow, wc);
3537     if (!n) {
3538         ctx->xout->slow |= commit_odp_actions(flow, &ctx->base_flow,
3539                                               ctx->xout->odp_actions,
3540                                               &ctx->xout->wc,
3541                                               ctx->xbridge->masked_set_action);
3542     } else if (n >= FLOW_MAX_MPLS_LABELS) {
3543         if (ctx->xin->packet != NULL) {
3544             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3545             VLOG_WARN_RL(&rl, "bridge %s: dropping packet on which an "
3546                          "MPLS push action can't be performed as it would "
3547                          "have more MPLS LSEs than the %d supported.",
3548                          ctx->xbridge->name, FLOW_MAX_MPLS_LABELS);
3549         }
3550         ctx->exit = true;
3551         return;
3552     }
3553
3554     flow_push_mpls(flow, n, mpls->ethertype, wc);
3555 }
3556
3557 static void
3558 compose_mpls_pop_action(struct xlate_ctx *ctx, ovs_be16 eth_type)
3559 {
3560     struct flow_wildcards *wc = &ctx->xout->wc;
3561     struct flow *flow = &ctx->xin->flow;
3562     int n = flow_count_mpls_labels(flow, wc);
3563
3564     if (flow_pop_mpls(flow, n, eth_type, wc)) {
3565         if (ctx->xbridge->enable_recirc) {
3566             ctx->was_mpls = true;
3567         }
3568     } else if (n >= FLOW_MAX_MPLS_LABELS) {
3569         if (ctx->xin->packet != NULL) {
3570             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3571             VLOG_WARN_RL(&rl, "bridge %s: dropping packet on which an "
3572                          "MPLS pop action can't be performed as it has "
3573                          "more MPLS LSEs than the %d supported.",
3574                          ctx->xbridge->name, FLOW_MAX_MPLS_LABELS);
3575         }
3576         ctx->exit = true;
3577         ofpbuf_clear(ctx->xout->odp_actions);
3578     }
3579 }
3580
3581 static bool
3582 compose_dec_ttl(struct xlate_ctx *ctx, struct ofpact_cnt_ids *ids)
3583 {
3584     struct flow *flow = &ctx->xin->flow;
3585
3586     if (!is_ip_any(flow)) {
3587         return false;
3588     }
3589
3590     ctx->xout->wc.masks.nw_ttl = 0xff;
3591     if (flow->nw_ttl > 1) {
3592         flow->nw_ttl--;
3593         return false;
3594     } else {
3595         size_t i;
3596
3597         for (i = 0; i < ids->n_controllers; i++) {
3598             execute_controller_action(ctx, UINT16_MAX, OFPR_INVALID_TTL,
3599                                       ids->cnt_ids[i]);
3600         }
3601
3602         /* Stop processing for current table. */
3603         return true;
3604     }
3605 }
3606
3607 static void
3608 compose_set_mpls_label_action(struct xlate_ctx *ctx, ovs_be32 label)
3609 {
3610     if (eth_type_mpls(ctx->xin->flow.dl_type)) {
3611         ctx->xout->wc.masks.mpls_lse[0] |= htonl(MPLS_LABEL_MASK);
3612         set_mpls_lse_label(&ctx->xin->flow.mpls_lse[0], label);
3613     }
3614 }
3615
3616 static void
3617 compose_set_mpls_tc_action(struct xlate_ctx *ctx, uint8_t tc)
3618 {
3619     if (eth_type_mpls(ctx->xin->flow.dl_type)) {
3620         ctx->xout->wc.masks.mpls_lse[0] |= htonl(MPLS_TC_MASK);
3621         set_mpls_lse_tc(&ctx->xin->flow.mpls_lse[0], tc);
3622     }
3623 }
3624
3625 static void
3626 compose_set_mpls_ttl_action(struct xlate_ctx *ctx, uint8_t ttl)
3627 {
3628     if (eth_type_mpls(ctx->xin->flow.dl_type)) {
3629         ctx->xout->wc.masks.mpls_lse[0] |= htonl(MPLS_TTL_MASK);
3630         set_mpls_lse_ttl(&ctx->xin->flow.mpls_lse[0], ttl);
3631     }
3632 }
3633
3634 static bool
3635 compose_dec_mpls_ttl_action(struct xlate_ctx *ctx)
3636 {
3637     struct flow *flow = &ctx->xin->flow;
3638     struct flow_wildcards *wc = &ctx->xout->wc;
3639
3640     if (eth_type_mpls(flow->dl_type)) {
3641         uint8_t ttl = mpls_lse_to_ttl(flow->mpls_lse[0]);
3642
3643         wc->masks.mpls_lse[0] |= htonl(MPLS_TTL_MASK);
3644         if (ttl > 1) {
3645             ttl--;
3646             set_mpls_lse_ttl(&flow->mpls_lse[0], ttl);
3647             return false;
3648         } else {
3649             execute_controller_action(ctx, UINT16_MAX, OFPR_INVALID_TTL, 0);
3650         }
3651     }
3652
3653     /* Stop processing for current table. */
3654     return true;
3655 }
3656
3657 static void
3658 xlate_output_action(struct xlate_ctx *ctx,
3659                     ofp_port_t port, uint16_t max_len, bool may_packet_in)
3660 {
3661     ofp_port_t prev_nf_output_iface = ctx->xout->nf_output_iface;
3662
3663     ctx->xout->nf_output_iface = NF_OUT_DROP;
3664
3665     switch (port) {
3666     case OFPP_IN_PORT:
3667         compose_output_action(ctx, ctx->xin->flow.in_port.ofp_port, NULL);
3668         break;
3669     case OFPP_TABLE:
3670         xlate_table_action(ctx, ctx->xin->flow.in_port.ofp_port,
3671                            0, may_packet_in, true);
3672         break;
3673     case OFPP_NORMAL:
3674         xlate_normal(ctx);
3675         break;
3676     case OFPP_FLOOD:
3677         flood_packets(ctx,  false);
3678         break;
3679     case OFPP_ALL:
3680         flood_packets(ctx, true);
3681         break;
3682     case OFPP_CONTROLLER:
3683         execute_controller_action(ctx, max_len,
3684                                   (ctx->in_group ? OFPR_GROUP
3685                                    : ctx->in_action_set ? OFPR_ACTION_SET
3686                                    : OFPR_ACTION),
3687                                   0);
3688         break;
3689     case OFPP_NONE:
3690         break;
3691     case OFPP_LOCAL:
3692     default:
3693         if (port != ctx->xin->flow.in_port.ofp_port) {
3694             compose_output_action(ctx, port, NULL);
3695         } else {
3696             xlate_report(ctx, "skipping output to input port");
3697         }
3698         break;
3699     }
3700
3701     if (prev_nf_output_iface == NF_OUT_FLOOD) {
3702         ctx->xout->nf_output_iface = NF_OUT_FLOOD;
3703     } else if (ctx->xout->nf_output_iface == NF_OUT_DROP) {
3704         ctx->xout->nf_output_iface = prev_nf_output_iface;
3705     } else if (prev_nf_output_iface != NF_OUT_DROP &&
3706                ctx->xout->nf_output_iface != NF_OUT_FLOOD) {
3707         ctx->xout->nf_output_iface = NF_OUT_MULTI;
3708     }
3709 }
3710
3711 static void
3712 xlate_output_reg_action(struct xlate_ctx *ctx,
3713                         const struct ofpact_output_reg *or)
3714 {
3715     uint64_t port = mf_get_subfield(&or->src, &ctx->xin->flow);
3716     if (port <= UINT16_MAX) {
3717         union mf_subvalue value;
3718
3719         memset(&value, 0xff, sizeof value);
3720         mf_write_subfield_flow(&or->src, &value, &ctx->xout->wc.masks);
3721         xlate_output_action(ctx, u16_to_ofp(port),
3722                             or->max_len, false);
3723     }
3724 }
3725
3726 static void
3727 xlate_enqueue_action(struct xlate_ctx *ctx,
3728                      const struct ofpact_enqueue *enqueue)
3729 {
3730     ofp_port_t ofp_port = enqueue->port;
3731     uint32_t queue_id = enqueue->queue;
3732     uint32_t flow_priority, priority;
3733     int error;
3734
3735     /* Translate queue to priority. */
3736     error = dpif_queue_to_priority(ctx->xbridge->dpif, queue_id, &priority);
3737     if (error) {
3738         /* Fall back to ordinary output action. */
3739         xlate_output_action(ctx, enqueue->port, 0, false);
3740         return;
3741     }
3742
3743     /* Check output port. */
3744     if (ofp_port == OFPP_IN_PORT) {
3745         ofp_port = ctx->xin->flow.in_port.ofp_port;
3746     } else if (ofp_port == ctx->xin->flow.in_port.ofp_port) {
3747         return;
3748     }
3749
3750     /* Add datapath actions. */
3751     flow_priority = ctx->xin->flow.skb_priority;
3752     ctx->xin->flow.skb_priority = priority;
3753     compose_output_action(ctx, ofp_port, NULL);
3754     ctx->xin->flow.skb_priority = flow_priority;
3755
3756     /* Update NetFlow output port. */
3757     if (ctx->xout->nf_output_iface == NF_OUT_DROP) {
3758         ctx->xout->nf_output_iface = ofp_port;
3759     } else if (ctx->xout->nf_output_iface != NF_OUT_FLOOD) {
3760         ctx->xout->nf_output_iface = NF_OUT_MULTI;
3761     }
3762 }
3763
3764 static void
3765 xlate_set_queue_action(struct xlate_ctx *ctx, uint32_t queue_id)
3766 {
3767     uint32_t skb_priority;
3768
3769     if (!dpif_queue_to_priority(ctx->xbridge->dpif, queue_id, &skb_priority)) {
3770         ctx->xin->flow.skb_priority = skb_priority;
3771     } else {
3772         /* Couldn't translate queue to a priority.  Nothing to do.  A warning
3773          * has already been logged. */
3774     }
3775 }
3776
3777 static bool
3778 slave_enabled_cb(ofp_port_t ofp_port, void *xbridge_)
3779 {
3780     const struct xbridge *xbridge = xbridge_;
3781     struct xport *port;
3782
3783     switch (ofp_port) {
3784     case OFPP_IN_PORT:
3785     case OFPP_TABLE:
3786     case OFPP_NORMAL:
3787     case OFPP_FLOOD:
3788     case OFPP_ALL:
3789     case OFPP_NONE:
3790         return true;
3791     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
3792         return false;
3793     default:
3794         port = get_ofp_port(xbridge, ofp_port);
3795         return port ? port->may_enable : false;
3796     }
3797 }
3798
3799 static void
3800 xlate_bundle_action(struct xlate_ctx *ctx,
3801                     const struct ofpact_bundle *bundle)
3802 {
3803     ofp_port_t port;
3804
3805     port = bundle_execute(bundle, &ctx->xin->flow, &ctx->xout->wc,
3806                           slave_enabled_cb,
3807                           CONST_CAST(struct xbridge *, ctx->xbridge));
3808     if (bundle->dst.field) {
3809         nxm_reg_load(&bundle->dst, ofp_to_u16(port), &ctx->xin->flow,
3810                      &ctx->xout->wc);
3811     } else {
3812         xlate_output_action(ctx, port, 0, false);
3813     }
3814 }
3815
3816 static void
3817 xlate_learn_action__(struct xlate_ctx *ctx, const struct ofpact_learn *learn,
3818                      struct ofputil_flow_mod *fm, struct ofpbuf *ofpacts)
3819 {
3820     learn_execute(learn, &ctx->xin->flow, fm, ofpacts);
3821     if (ctx->xin->may_learn) {
3822         ofproto_dpif_flow_mod(ctx->xbridge->ofproto, fm);
3823     }
3824 }
3825
3826 static void
3827 xlate_learn_action(struct xlate_ctx *ctx, const struct ofpact_learn *learn)
3828 {
3829     ctx->xout->has_learn = true;
3830     learn_mask(learn, &ctx->xout->wc);
3831
3832     if (ctx->xin->xcache) {
3833         struct xc_entry *entry;
3834
3835         entry = xlate_cache_add_entry(ctx->xin->xcache, XC_LEARN);
3836         entry->u.learn.ofproto = ctx->xbridge->ofproto;
3837         entry->u.learn.fm = xmalloc(sizeof *entry->u.learn.fm);
3838         entry->u.learn.ofpacts = ofpbuf_new(64);
3839         xlate_learn_action__(ctx, learn, entry->u.learn.fm,
3840                              entry->u.learn.ofpacts);
3841     } else if (ctx->xin->may_learn) {
3842         uint64_t ofpacts_stub[1024 / 8];
3843         struct ofputil_flow_mod fm;
3844         struct ofpbuf ofpacts;
3845
3846         ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
3847         xlate_learn_action__(ctx, learn, &fm, &ofpacts);
3848         ofpbuf_uninit(&ofpacts);
3849     }
3850 }
3851
3852 static void
3853 xlate_fin_timeout__(struct rule_dpif *rule, uint16_t tcp_flags,
3854                     uint16_t idle_timeout, uint16_t hard_timeout)
3855 {
3856     if (tcp_flags & (TCP_FIN | TCP_RST)) {
3857         rule_dpif_reduce_timeouts(rule, idle_timeout, hard_timeout);
3858     }
3859 }
3860
3861 static void
3862 xlate_fin_timeout(struct xlate_ctx *ctx,
3863                   const struct ofpact_fin_timeout *oft)
3864 {
3865     if (ctx->rule) {
3866         xlate_fin_timeout__(ctx->rule, ctx->xin->tcp_flags,
3867                             oft->fin_idle_timeout, oft->fin_hard_timeout);
3868         if (ctx->xin->xcache) {
3869             struct xc_entry *entry;
3870
3871             entry = xlate_cache_add_entry(ctx->xin->xcache, XC_FIN_TIMEOUT);
3872             /* XC_RULE already holds a reference on the rule, none is taken
3873              * here. */
3874             entry->u.fin.rule = ctx->rule;
3875             entry->u.fin.idle = oft->fin_idle_timeout;
3876             entry->u.fin.hard = oft->fin_hard_timeout;
3877         }
3878     }
3879 }
3880
3881 static void
3882 xlate_sample_action(struct xlate_ctx *ctx,
3883                     const struct ofpact_sample *os)
3884 {
3885     union user_action_cookie cookie;
3886     /* Scale the probability from 16-bit to 32-bit while representing
3887      * the same percentage. */
3888     uint32_t probability = (os->probability << 16) | os->probability;
3889
3890     if (!ctx->xbridge->variable_length_userdata) {
3891         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
3892
3893         VLOG_ERR_RL(&rl, "ignoring NXAST_SAMPLE action because datapath "
3894                     "lacks support (needs Linux 3.10+ or kernel module from "
3895                     "OVS 1.11+)");
3896         return;
3897     }
3898
3899     ctx->xout->slow |= commit_odp_actions(&ctx->xin->flow, &ctx->base_flow,
3900                                           ctx->xout->odp_actions,
3901                                           &ctx->xout->wc,
3902                                           ctx->xbridge->masked_set_action);
3903
3904     compose_flow_sample_cookie(os->probability, os->collector_set_id,
3905                                os->obs_domain_id, os->obs_point_id, &cookie);
3906     compose_sample_action(ctx->xbridge, ctx->xout->odp_actions,
3907                           &ctx->xin->flow, probability, &cookie,
3908                           sizeof cookie.flow_sample, ODPP_NONE);
3909 }
3910
3911 static bool
3912 may_receive(const struct xport *xport, struct xlate_ctx *ctx)
3913 {
3914     if (xport->config & (is_stp(&ctx->xin->flow)
3915                          ? OFPUTIL_PC_NO_RECV_STP
3916                          : OFPUTIL_PC_NO_RECV)) {
3917         return false;
3918     }
3919
3920     /* Only drop packets here if both forwarding and learning are
3921      * disabled.  If just learning is enabled, we need to have
3922      * OFPP_NORMAL and the learning action have a look at the packet
3923      * before we can drop it. */
3924     if ((!xport_stp_forward_state(xport) && !xport_stp_learn_state(xport)) ||
3925         (!xport_rstp_forward_state(xport) && !xport_rstp_learn_state(xport))) {
3926         return false;
3927     }
3928
3929     return true;
3930 }
3931
3932 static void
3933 xlate_write_actions(struct xlate_ctx *ctx, const struct ofpact *a)
3934 {
3935     const struct ofpact_nest *on = ofpact_get_WRITE_ACTIONS(a);
3936     size_t on_len = ofpact_nest_get_action_len(on);
3937     const struct ofpact *inner;
3938
3939     /* Maintain actset_output depending on the contents of the action set:
3940      *
3941      *   - OFPP_UNSET, if there is no "output" action.
3942      *
3943      *   - The output port, if there is an "output" action and no "group"
3944      *     action.
3945      *
3946      *   - OFPP_UNSET, if there is a "group" action.
3947      */
3948     if (!ctx->action_set_has_group) {
3949         OFPACT_FOR_EACH (inner, on->actions, on_len) {
3950             if (inner->type == OFPACT_OUTPUT) {
3951                 ctx->xin->flow.actset_output = ofpact_get_OUTPUT(inner)->port;
3952             } else if (inner->type == OFPACT_GROUP) {
3953                 ctx->xin->flow.actset_output = OFPP_UNSET;
3954                 ctx->action_set_has_group = true;
3955             }
3956         }
3957     }
3958
3959     ofpbuf_put(&ctx->action_set, on->actions, on_len);
3960     ofpact_pad(&ctx->action_set);
3961 }
3962
3963 static void
3964 xlate_action_set(struct xlate_ctx *ctx)
3965 {
3966     uint64_t action_list_stub[1024 / 64];
3967     struct ofpbuf action_list;
3968
3969     ctx->in_action_set = true;
3970     ofpbuf_use_stub(&action_list, action_list_stub, sizeof action_list_stub);
3971     ofpacts_execute_action_set(&action_list, &ctx->action_set);
3972     /* Clear the action set, as it is not needed any more. */
3973     ofpbuf_clear(&ctx->action_set);
3974     do_xlate_actions(action_list.data, action_list.size, ctx);
3975     ctx->in_action_set = false;
3976     ofpbuf_uninit(&action_list);
3977 }
3978
3979 static void
3980 recirc_put_unroll_xlate(struct xlate_ctx *ctx)
3981 {
3982     struct ofpact_unroll_xlate *unroll;
3983
3984     unroll = ctx->last_unroll_offset < 0
3985         ? NULL
3986         : ALIGNED_CAST(struct ofpact_unroll_xlate *,
3987                        (char *)ctx->action_set.data + ctx->last_unroll_offset);
3988
3989     /* Restore the table_id and rule cookie for a potential PACKET
3990      * IN if needed. */
3991     if (!unroll ||
3992         (ctx->table_id != unroll->rule_table_id
3993          || ctx->rule_cookie != unroll->rule_cookie)) {
3994
3995         ctx->last_unroll_offset = ctx->action_set.size;
3996         unroll = ofpact_put_UNROLL_XLATE(&ctx->action_set);
3997         unroll->rule_table_id = ctx->table_id;
3998         unroll->rule_cookie = ctx->rule_cookie;
3999     }
4000 }
4001
4002
4003 /* Copy remaining actions to the action_set to be executed after recirculation.
4004  * UNROLL_XLATE action is inserted, if not already done so, before actions that
4005  * may generate PACKET_INs from the current table and without matching another
4006  * rule. */
4007 static void
4008 recirc_unroll_actions(const struct ofpact *ofpacts, size_t ofpacts_len,
4009                       struct xlate_ctx *ctx)
4010 {
4011     const struct ofpact *a;
4012
4013     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
4014         switch (a->type) {
4015             /* May generate PACKET INs. */
4016         case OFPACT_OUTPUT_REG:
4017         case OFPACT_GROUP:
4018         case OFPACT_OUTPUT:
4019         case OFPACT_CONTROLLER:
4020         case OFPACT_DEC_MPLS_TTL:
4021         case OFPACT_DEC_TTL:
4022             recirc_put_unroll_xlate(ctx);
4023             break;
4024
4025             /* These may not generate PACKET INs. */
4026         case OFPACT_SET_TUNNEL:
4027         case OFPACT_REG_MOVE:
4028         case OFPACT_SET_FIELD:
4029         case OFPACT_STACK_PUSH:
4030         case OFPACT_STACK_POP:
4031         case OFPACT_LEARN:
4032         case OFPACT_WRITE_METADATA:
4033         case OFPACT_RESUBMIT:        /* May indirectly generate PACKET INs, */
4034         case OFPACT_GOTO_TABLE:      /* but from a different table and rule. */
4035         case OFPACT_ENQUEUE:
4036         case OFPACT_SET_VLAN_VID:
4037         case OFPACT_SET_VLAN_PCP:
4038         case OFPACT_STRIP_VLAN:
4039         case OFPACT_PUSH_VLAN:
4040         case OFPACT_SET_ETH_SRC:
4041         case OFPACT_SET_ETH_DST:
4042         case OFPACT_SET_IPV4_SRC:
4043         case OFPACT_SET_IPV4_DST:
4044         case OFPACT_SET_IP_DSCP:
4045         case OFPACT_SET_IP_ECN:
4046         case OFPACT_SET_IP_TTL:
4047         case OFPACT_SET_L4_SRC_PORT:
4048         case OFPACT_SET_L4_DST_PORT:
4049         case OFPACT_SET_QUEUE:
4050         case OFPACT_POP_QUEUE:
4051         case OFPACT_PUSH_MPLS:
4052         case OFPACT_POP_MPLS:
4053         case OFPACT_SET_MPLS_LABEL:
4054         case OFPACT_SET_MPLS_TC:
4055         case OFPACT_SET_MPLS_TTL:
4056         case OFPACT_MULTIPATH:
4057         case OFPACT_BUNDLE:
4058         case OFPACT_EXIT:
4059         case OFPACT_UNROLL_XLATE:
4060         case OFPACT_FIN_TIMEOUT:
4061         case OFPACT_CLEAR_ACTIONS:
4062         case OFPACT_WRITE_ACTIONS:
4063         case OFPACT_METER:
4064         case OFPACT_SAMPLE:
4065             break;
4066
4067             /* These need not be copied for restoration. */
4068         case OFPACT_NOTE:
4069         case OFPACT_CONJUNCTION:
4070             continue;
4071         }
4072         /* Copy the action over. */
4073         ofpbuf_put(&ctx->action_set, a, OFPACT_ALIGN(a->len));
4074     }
4075 }
4076
4077 #define CHECK_MPLS_RECIRCULATION()      \
4078     if (ctx->was_mpls) {                \
4079         ctx_trigger_recirculation(ctx); \
4080         break;                          \
4081     }
4082 #define CHECK_MPLS_RECIRCULATION_IF(COND) \
4083     if (COND) {                           \
4084         CHECK_MPLS_RECIRCULATION();       \
4085     }
4086
4087 static void
4088 do_xlate_actions(const struct ofpact *ofpacts, size_t ofpacts_len,
4089                  struct xlate_ctx *ctx)
4090 {
4091     struct flow_wildcards *wc = &ctx->xout->wc;
4092     struct flow *flow = &ctx->xin->flow;
4093     const struct ofpact *a;
4094
4095     if (ovs_native_tunneling_is_on(ctx->xbridge->ofproto)) {
4096         tnl_arp_snoop(flow, wc, ctx->xbridge->name);
4097     }
4098     /* dl_type already in the mask, not set below. */
4099
4100     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
4101         struct ofpact_controller *controller;
4102         const struct ofpact_metadata *metadata;
4103         const struct ofpact_set_field *set_field;
4104         const struct mf_field *mf;
4105
4106         if (ctx->exit) {
4107             /* Check if need to store the remaining actions for later
4108              * execution. */
4109             if (exit_recirculates(ctx)) {
4110                 recirc_unroll_actions(a, OFPACT_ALIGN(ofpacts_len -
4111                                                       ((uint8_t *)a -
4112                                                        (uint8_t *)ofpacts)),
4113                                       ctx);
4114             }
4115             break;
4116         }
4117
4118         switch (a->type) {
4119         case OFPACT_OUTPUT:
4120             xlate_output_action(ctx, ofpact_get_OUTPUT(a)->port,
4121                                 ofpact_get_OUTPUT(a)->max_len, true);
4122             break;
4123
4124         case OFPACT_GROUP:
4125             if (xlate_group_action(ctx, ofpact_get_GROUP(a)->group_id)) {
4126                 /* Group could not be found. */
4127                 return;
4128             }
4129             break;
4130
4131         case OFPACT_CONTROLLER:
4132             controller = ofpact_get_CONTROLLER(a);
4133             execute_controller_action(ctx, controller->max_len,
4134                                       controller->reason,
4135                                       controller->controller_id);
4136             break;
4137
4138         case OFPACT_ENQUEUE:
4139             memset(&wc->masks.skb_priority, 0xff,
4140                    sizeof wc->masks.skb_priority);
4141             xlate_enqueue_action(ctx, ofpact_get_ENQUEUE(a));
4142             break;
4143
4144         case OFPACT_SET_VLAN_VID:
4145             wc->masks.vlan_tci |= htons(VLAN_VID_MASK | VLAN_CFI);
4146             if (flow->vlan_tci & htons(VLAN_CFI) ||
4147                 ofpact_get_SET_VLAN_VID(a)->push_vlan_if_needed) {
4148                 flow->vlan_tci &= ~htons(VLAN_VID_MASK);
4149                 flow->vlan_tci |= (htons(ofpact_get_SET_VLAN_VID(a)->vlan_vid)
4150                                    | htons(VLAN_CFI));
4151             }
4152             break;
4153
4154         case OFPACT_SET_VLAN_PCP:
4155             wc->masks.vlan_tci |= htons(VLAN_PCP_MASK | VLAN_CFI);
4156             if (flow->vlan_tci & htons(VLAN_CFI) ||
4157                 ofpact_get_SET_VLAN_PCP(a)->push_vlan_if_needed) {
4158                 flow->vlan_tci &= ~htons(VLAN_PCP_MASK);
4159                 flow->vlan_tci |= htons((ofpact_get_SET_VLAN_PCP(a)->vlan_pcp
4160                                          << VLAN_PCP_SHIFT) | VLAN_CFI);
4161             }
4162             break;
4163
4164         case OFPACT_STRIP_VLAN:
4165             memset(&wc->masks.vlan_tci, 0xff, sizeof wc->masks.vlan_tci);
4166             flow->vlan_tci = htons(0);
4167             break;
4168
4169         case OFPACT_PUSH_VLAN:
4170             /* XXX 802.1AD(QinQ) */
4171             memset(&wc->masks.vlan_tci, 0xff, sizeof wc->masks.vlan_tci);
4172             flow->vlan_tci = htons(VLAN_CFI);
4173             break;
4174
4175         case OFPACT_SET_ETH_SRC:
4176             memset(&wc->masks.dl_src, 0xff, sizeof wc->masks.dl_src);
4177             memcpy(flow->dl_src, ofpact_get_SET_ETH_SRC(a)->mac, ETH_ADDR_LEN);
4178             break;
4179
4180         case OFPACT_SET_ETH_DST:
4181             memset(&wc->masks.dl_dst, 0xff, sizeof wc->masks.dl_dst);
4182             memcpy(flow->dl_dst, ofpact_get_SET_ETH_DST(a)->mac, ETH_ADDR_LEN);
4183             break;
4184
4185         case OFPACT_SET_IPV4_SRC:
4186             CHECK_MPLS_RECIRCULATION();
4187             if (flow->dl_type == htons(ETH_TYPE_IP)) {
4188                 memset(&wc->masks.nw_src, 0xff, sizeof wc->masks.nw_src);
4189                 flow->nw_src = ofpact_get_SET_IPV4_SRC(a)->ipv4;
4190             }
4191             break;
4192
4193         case OFPACT_SET_IPV4_DST:
4194             CHECK_MPLS_RECIRCULATION();
4195             if (flow->dl_type == htons(ETH_TYPE_IP)) {
4196                 memset(&wc->masks.nw_dst, 0xff, sizeof wc->masks.nw_dst);
4197                 flow->nw_dst = ofpact_get_SET_IPV4_DST(a)->ipv4;
4198             }
4199             break;
4200
4201         case OFPACT_SET_IP_DSCP:
4202             CHECK_MPLS_RECIRCULATION();
4203             if (is_ip_any(flow)) {
4204                 wc->masks.nw_tos |= IP_DSCP_MASK;
4205                 flow->nw_tos &= ~IP_DSCP_MASK;
4206                 flow->nw_tos |= ofpact_get_SET_IP_DSCP(a)->dscp;
4207             }
4208             break;
4209
4210         case OFPACT_SET_IP_ECN:
4211             CHECK_MPLS_RECIRCULATION();
4212             if (is_ip_any(flow)) {
4213                 wc->masks.nw_tos |= IP_ECN_MASK;
4214                 flow->nw_tos &= ~IP_ECN_MASK;
4215                 flow->nw_tos |= ofpact_get_SET_IP_ECN(a)->ecn;
4216             }
4217             break;
4218
4219         case OFPACT_SET_IP_TTL:
4220             CHECK_MPLS_RECIRCULATION();
4221             if (is_ip_any(flow)) {
4222                 wc->masks.nw_ttl = 0xff;
4223                 flow->nw_ttl = ofpact_get_SET_IP_TTL(a)->ttl;
4224             }
4225             break;
4226
4227         case OFPACT_SET_L4_SRC_PORT:
4228             CHECK_MPLS_RECIRCULATION();
4229             if (is_ip_any(flow) && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4230                 memset(&wc->masks.nw_proto, 0xff, sizeof wc->masks.nw_proto);
4231                 memset(&wc->masks.tp_src, 0xff, sizeof wc->masks.tp_src);
4232                 flow->tp_src = htons(ofpact_get_SET_L4_SRC_PORT(a)->port);
4233             }
4234             break;
4235
4236         case OFPACT_SET_L4_DST_PORT:
4237             CHECK_MPLS_RECIRCULATION();
4238             if (is_ip_any(flow) && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4239                 memset(&wc->masks.nw_proto, 0xff, sizeof wc->masks.nw_proto);
4240                 memset(&wc->masks.tp_dst, 0xff, sizeof wc->masks.tp_dst);
4241                 flow->tp_dst = htons(ofpact_get_SET_L4_DST_PORT(a)->port);
4242             }
4243             break;
4244
4245         case OFPACT_RESUBMIT:
4246             xlate_ofpact_resubmit(ctx, ofpact_get_RESUBMIT(a));
4247             break;
4248
4249         case OFPACT_SET_TUNNEL:
4250             flow->tunnel.tun_id = htonll(ofpact_get_SET_TUNNEL(a)->tun_id);
4251             break;
4252
4253         case OFPACT_SET_QUEUE:
4254             memset(&wc->masks.skb_priority, 0xff,
4255                    sizeof wc->masks.skb_priority);
4256             xlate_set_queue_action(ctx, ofpact_get_SET_QUEUE(a)->queue_id);
4257             break;
4258
4259         case OFPACT_POP_QUEUE:
4260             memset(&wc->masks.skb_priority, 0xff,
4261                    sizeof wc->masks.skb_priority);
4262             flow->skb_priority = ctx->orig_skb_priority;
4263             break;
4264
4265         case OFPACT_REG_MOVE:
4266             CHECK_MPLS_RECIRCULATION_IF(
4267                 mf_is_l3_or_higher(ofpact_get_REG_MOVE(a)->dst.field) ||
4268                 mf_is_l3_or_higher(ofpact_get_REG_MOVE(a)->src.field));
4269             nxm_execute_reg_move(ofpact_get_REG_MOVE(a), flow, wc);
4270             break;
4271
4272         case OFPACT_SET_FIELD:
4273             CHECK_MPLS_RECIRCULATION_IF(
4274                 mf_is_l3_or_higher(ofpact_get_SET_FIELD(a)->field));
4275             set_field = ofpact_get_SET_FIELD(a);
4276             mf = set_field->field;
4277
4278             /* Set field action only ever overwrites packet's outermost
4279              * applicable header fields.  Do nothing if no header exists. */
4280             if (mf->id == MFF_VLAN_VID) {
4281                 wc->masks.vlan_tci |= htons(VLAN_CFI);
4282                 if (!(flow->vlan_tci & htons(VLAN_CFI))) {
4283                     break;
4284                 }
4285             } else if ((mf->id == MFF_MPLS_LABEL || mf->id == MFF_MPLS_TC)
4286                        /* 'dl_type' is already unwildcarded. */
4287                        && !eth_type_mpls(flow->dl_type)) {
4288                 break;
4289             }
4290             /* A flow may wildcard nw_frag.  Do nothing if setting a trasport
4291              * header field on a packet that does not have them. */
4292             mf_mask_field_and_prereqs(mf, &wc->masks);
4293             if (mf_are_prereqs_ok(mf, flow)) {
4294                 mf_set_flow_value_masked(mf, &set_field->value,
4295                                          &set_field->mask, flow);
4296             }
4297             break;
4298
4299         case OFPACT_STACK_PUSH:
4300             CHECK_MPLS_RECIRCULATION_IF(
4301                 mf_is_l3_or_higher(ofpact_get_STACK_PUSH(a)->subfield.field));
4302             nxm_execute_stack_push(ofpact_get_STACK_PUSH(a), flow, wc,
4303                                    &ctx->stack);
4304             break;
4305
4306         case OFPACT_STACK_POP:
4307             CHECK_MPLS_RECIRCULATION_IF(
4308                 mf_is_l3_or_higher(ofpact_get_STACK_POP(a)->subfield.field));
4309             nxm_execute_stack_pop(ofpact_get_STACK_POP(a), flow, wc,
4310                                   &ctx->stack);
4311             break;
4312
4313         case OFPACT_PUSH_MPLS:
4314             /* Recirculate if it is an IP packet with a zero ttl.  This may
4315              * indicate that the packet was previously MPLS and an MPLS pop
4316              * action converted it to IP. In this case recirculating should
4317              * reveal the IP TTL which is used as the basis for a new MPLS
4318              * LSE. */
4319             CHECK_MPLS_RECIRCULATION_IF(
4320                 !flow_count_mpls_labels(flow, wc)
4321                 && flow->nw_ttl == 0
4322                 && is_ip_any(flow));
4323             compose_mpls_push_action(ctx, ofpact_get_PUSH_MPLS(a));
4324             break;
4325
4326         case OFPACT_POP_MPLS:
4327             CHECK_MPLS_RECIRCULATION();
4328             compose_mpls_pop_action(ctx, ofpact_get_POP_MPLS(a)->ethertype);
4329             break;
4330
4331         case OFPACT_SET_MPLS_LABEL:
4332             CHECK_MPLS_RECIRCULATION();
4333             compose_set_mpls_label_action(
4334                 ctx, ofpact_get_SET_MPLS_LABEL(a)->label);
4335             break;
4336
4337         case OFPACT_SET_MPLS_TC:
4338             CHECK_MPLS_RECIRCULATION();
4339             compose_set_mpls_tc_action(ctx, ofpact_get_SET_MPLS_TC(a)->tc);
4340             break;
4341
4342         case OFPACT_SET_MPLS_TTL:
4343             CHECK_MPLS_RECIRCULATION();
4344             compose_set_mpls_ttl_action(ctx, ofpact_get_SET_MPLS_TTL(a)->ttl);
4345             break;
4346
4347         case OFPACT_DEC_MPLS_TTL:
4348             CHECK_MPLS_RECIRCULATION();
4349             if (compose_dec_mpls_ttl_action(ctx)) {
4350                 return;
4351             }
4352             break;
4353
4354         case OFPACT_DEC_TTL:
4355             CHECK_MPLS_RECIRCULATION();
4356             wc->masks.nw_ttl = 0xff;
4357             if (compose_dec_ttl(ctx, ofpact_get_DEC_TTL(a))) {
4358                 return;
4359             }
4360             break;
4361
4362         case OFPACT_NOTE:
4363             /* Nothing to do. */
4364             break;
4365
4366         case OFPACT_MULTIPATH:
4367             CHECK_MPLS_RECIRCULATION();
4368             multipath_execute(ofpact_get_MULTIPATH(a), flow, wc);
4369             break;
4370
4371         case OFPACT_BUNDLE:
4372             CHECK_MPLS_RECIRCULATION();
4373             xlate_bundle_action(ctx, ofpact_get_BUNDLE(a));
4374             break;
4375
4376         case OFPACT_OUTPUT_REG:
4377             xlate_output_reg_action(ctx, ofpact_get_OUTPUT_REG(a));
4378             break;
4379
4380         case OFPACT_LEARN:
4381             CHECK_MPLS_RECIRCULATION();
4382             xlate_learn_action(ctx, ofpact_get_LEARN(a));
4383             break;
4384
4385         case OFPACT_CONJUNCTION: {
4386             /* A flow with a "conjunction" action represents part of a special
4387              * kind of "set membership match".  Such a flow should not actually
4388              * get executed, but it could via, say, a "packet-out", even though
4389              * that wouldn't be useful.  Log it to help debugging. */
4390             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
4391             VLOG_INFO_RL(&rl, "executing no-op conjunction action");
4392             break;
4393         }
4394
4395         case OFPACT_EXIT:
4396             ctx->exit = true;
4397             break;
4398
4399         case OFPACT_UNROLL_XLATE: {
4400             struct ofpact_unroll_xlate *unroll = ofpact_get_UNROLL_XLATE(a);
4401
4402             /* Restore translation context data that was stored earlier. */
4403             ctx->table_id = unroll->rule_table_id;
4404             ctx->rule_cookie = unroll->rule_cookie;
4405             break;
4406         }
4407         case OFPACT_FIN_TIMEOUT:
4408             CHECK_MPLS_RECIRCULATION();
4409             memset(&wc->masks.nw_proto, 0xff, sizeof wc->masks.nw_proto);
4410             ctx->xout->has_fin_timeout = true;
4411             xlate_fin_timeout(ctx, ofpact_get_FIN_TIMEOUT(a));
4412             break;
4413
4414         case OFPACT_CLEAR_ACTIONS:
4415             ofpbuf_clear(&ctx->action_set);
4416             ctx->xin->flow.actset_output = OFPP_UNSET;
4417             ctx->action_set_has_group = false;
4418             break;
4419
4420         case OFPACT_WRITE_ACTIONS:
4421             xlate_write_actions(ctx, a);
4422             break;
4423
4424         case OFPACT_WRITE_METADATA:
4425             metadata = ofpact_get_WRITE_METADATA(a);
4426             flow->metadata &= ~metadata->mask;
4427             flow->metadata |= metadata->metadata & metadata->mask;
4428             break;
4429
4430         case OFPACT_METER:
4431             /* Not implemented yet. */
4432             break;
4433
4434         case OFPACT_GOTO_TABLE: {
4435             struct ofpact_goto_table *ogt = ofpact_get_GOTO_TABLE(a);
4436
4437             /* Allow ctx->table_id == TBL_INTERNAL, which will be greater
4438              * than ogt->table_id. This is to allow goto_table actions that
4439              * triggered recirculation: ctx->table_id will be TBL_INTERNAL
4440              * after recirculation. */
4441             ovs_assert(ctx->table_id == TBL_INTERNAL
4442                        || ctx->table_id < ogt->table_id);
4443             xlate_table_action(ctx, ctx->xin->flow.in_port.ofp_port,
4444                                ogt->table_id, true, true);
4445             break;
4446         }
4447
4448         case OFPACT_SAMPLE:
4449             xlate_sample_action(ctx, ofpact_get_SAMPLE(a));
4450             break;
4451         }
4452
4453         /* Check if need to store this and the remaining actions for later
4454          * execution. */
4455         if (ctx->exit && ctx_first_recirculation_action(ctx)) {
4456             recirc_unroll_actions(a, OFPACT_ALIGN(ofpacts_len -
4457                                                   ((uint8_t *)a -
4458                                                    (uint8_t *)ofpacts)),
4459                                   ctx);
4460             break;
4461         }
4462     }
4463 }
4464
4465 void
4466 xlate_in_init(struct xlate_in *xin, struct ofproto_dpif *ofproto,
4467               const struct flow *flow, ofp_port_t in_port,
4468               struct rule_dpif *rule, uint16_t tcp_flags,
4469               const struct dp_packet *packet)
4470 {
4471     xin->ofproto = ofproto;
4472     xin->flow = *flow;
4473     xin->flow.in_port.ofp_port = in_port;
4474     xin->flow.actset_output = OFPP_UNSET;
4475     xin->packet = packet;
4476     xin->may_learn = packet != NULL;
4477     xin->rule = rule;
4478     xin->xcache = NULL;
4479     xin->ofpacts = NULL;
4480     xin->ofpacts_len = 0;
4481     xin->tcp_flags = tcp_flags;
4482     xin->resubmit_hook = NULL;
4483     xin->report_hook = NULL;
4484     xin->resubmit_stats = NULL;
4485     xin->skip_wildcards = false;
4486     xin->odp_actions = NULL;
4487
4488     /* Do recirc lookup. */
4489     xin->recirc = flow->recirc_id
4490         ? recirc_id_node_find(flow->recirc_id)
4491         : NULL;
4492 }
4493
4494 void
4495 xlate_out_uninit(struct xlate_out *xout)
4496 {
4497     if (xout) {
4498         if (xout->odp_actions == &xout->odp_actions_buf) {
4499             ofpbuf_uninit(xout->odp_actions);
4500         }
4501         xlate_out_free_recircs(xout);
4502     }
4503 }
4504
4505 /* Translates the 'ofpacts_len' bytes of "struct ofpact"s starting at 'ofpacts'
4506  * into datapath actions, using 'ctx', and discards the datapath actions. */
4507 void
4508 xlate_actions_for_side_effects(struct xlate_in *xin)
4509 {
4510     struct xlate_out xout;
4511
4512     xlate_actions(xin, &xout);
4513     xlate_out_uninit(&xout);
4514 }
4515
4516 void
4517 xlate_out_copy(struct xlate_out *dst, const struct xlate_out *src)
4518 {
4519     dst->wc = src->wc;
4520     dst->slow = src->slow;
4521     dst->has_learn = src->has_learn;
4522     dst->has_normal = src->has_normal;
4523     dst->has_fin_timeout = src->has_fin_timeout;
4524     dst->nf_output_iface = src->nf_output_iface;
4525     dst->mirrors = src->mirrors;
4526
4527     dst->odp_actions = &dst->odp_actions_buf;
4528     ofpbuf_use_stub(dst->odp_actions, dst->odp_actions_stub,
4529                     sizeof dst->odp_actions_stub);
4530     ofpbuf_put(dst->odp_actions, src->odp_actions->data, src->odp_actions->size);
4531 }
4532 \f
4533 static struct skb_priority_to_dscp *
4534 get_skb_priority(const struct xport *xport, uint32_t skb_priority)
4535 {
4536     struct skb_priority_to_dscp *pdscp;
4537     uint32_t hash;
4538
4539     hash = hash_int(skb_priority, 0);
4540     HMAP_FOR_EACH_IN_BUCKET (pdscp, hmap_node, hash, &xport->skb_priorities) {
4541         if (pdscp->skb_priority == skb_priority) {
4542             return pdscp;
4543         }
4544     }
4545     return NULL;
4546 }
4547
4548 static bool
4549 dscp_from_skb_priority(const struct xport *xport, uint32_t skb_priority,
4550                        uint8_t *dscp)
4551 {
4552     struct skb_priority_to_dscp *pdscp = get_skb_priority(xport, skb_priority);
4553     *dscp = pdscp ? pdscp->dscp : 0;
4554     return pdscp != NULL;
4555 }
4556
4557 static size_t
4558 count_skb_priorities(const struct xport *xport)
4559 {
4560     return hmap_count(&xport->skb_priorities);
4561 }
4562
4563 static void
4564 clear_skb_priorities(struct xport *xport)
4565 {
4566     struct skb_priority_to_dscp *pdscp, *next;
4567
4568     HMAP_FOR_EACH_SAFE (pdscp, next, hmap_node, &xport->skb_priorities) {
4569         hmap_remove(&xport->skb_priorities, &pdscp->hmap_node);
4570         free(pdscp);
4571     }
4572 }
4573
4574 static bool
4575 actions_output_to_local_port(const struct xlate_ctx *ctx)
4576 {
4577     odp_port_t local_odp_port = ofp_port_to_odp_port(ctx->xbridge, OFPP_LOCAL);
4578     const struct nlattr *a;
4579     unsigned int left;
4580
4581     NL_ATTR_FOR_EACH_UNSAFE (a, left, ctx->xout->odp_actions->data,
4582                              ctx->xout->odp_actions->size) {
4583         if (nl_attr_type(a) == OVS_ACTION_ATTR_OUTPUT
4584             && nl_attr_get_odp_port(a) == local_odp_port) {
4585             return true;
4586         }
4587     }
4588     return false;
4589 }
4590
4591 #if defined(__linux__)
4592 /* Returns the maximum number of packets that the Linux kernel is willing to
4593  * queue up internally to certain kinds of software-implemented ports, or the
4594  * default (and rarely modified) value if it cannot be determined. */
4595 static int
4596 netdev_max_backlog(void)
4597 {
4598     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
4599     static int max_backlog = 1000; /* The normal default value. */
4600
4601     if (ovsthread_once_start(&once)) {
4602         static const char filename[] = "/proc/sys/net/core/netdev_max_backlog";
4603         FILE *stream;
4604         int n;
4605
4606         stream = fopen(filename, "r");
4607         if (!stream) {
4608             VLOG_WARN("%s: open failed (%s)", filename, ovs_strerror(errno));
4609         } else {
4610             if (fscanf(stream, "%d", &n) != 1) {
4611                 VLOG_WARN("%s: read error", filename);
4612             } else if (n <= 100) {
4613                 VLOG_WARN("%s: unexpectedly small value %d", filename, n);
4614             } else {
4615                 max_backlog = n;
4616             }
4617             fclose(stream);
4618         }
4619         ovsthread_once_done(&once);
4620
4621         VLOG_DBG("%s: using %d max_backlog", filename, max_backlog);
4622     }
4623
4624     return max_backlog;
4625 }
4626
4627 /* Counts and returns the number of OVS_ACTION_ATTR_OUTPUT actions in
4628  * 'odp_actions'. */
4629 static int
4630 count_output_actions(const struct ofpbuf *odp_actions)
4631 {
4632     const struct nlattr *a;
4633     size_t left;
4634     int n = 0;
4635
4636     NL_ATTR_FOR_EACH_UNSAFE (a, left, odp_actions->data, odp_actions->size) {
4637         if (a->nla_type == OVS_ACTION_ATTR_OUTPUT) {
4638             n++;
4639         }
4640     }
4641     return n;
4642 }
4643 #endif /* defined(__linux__) */
4644
4645 /* Returns true if 'odp_actions' contains more output actions than the datapath
4646  * can reliably handle in one go.  On Linux, this is the value of the
4647  * net.core.netdev_max_backlog sysctl, which limits the maximum number of
4648  * packets that the kernel is willing to queue up for processing while the
4649  * datapath is processing a set of actions. */
4650 static bool
4651 too_many_output_actions(const struct ofpbuf *odp_actions OVS_UNUSED)
4652 {
4653 #ifdef __linux__
4654     return (odp_actions->size / NL_A_U32_SIZE > netdev_max_backlog()
4655             && count_output_actions(odp_actions) > netdev_max_backlog());
4656 #else
4657     /* OSes other than Linux might have similar limits, but we don't know how
4658      * to determine them.*/
4659     return false;
4660 #endif
4661 }
4662
4663 /* Translates the flow, actions, or rule in 'xin' into datapath actions in
4664  * 'xout'.
4665  * The caller must take responsibility for eventually freeing 'xout', with
4666  * xlate_out_uninit(). */
4667 void
4668 xlate_actions(struct xlate_in *xin, struct xlate_out *xout)
4669 {
4670     struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
4671     struct flow_wildcards *wc = NULL;
4672     struct flow *flow = &xin->flow;
4673     struct rule_dpif *rule = NULL;
4674
4675     enum slow_path_reason special;
4676     const struct ofpact *ofpacts;
4677     struct xbridge *xbridge;
4678     struct xport *in_port;
4679     struct flow orig_flow;
4680     struct xlate_ctx ctx;
4681     size_t ofpacts_len;
4682     bool tnl_may_send;
4683     bool is_icmp;
4684
4685     COVERAGE_INC(xlate_actions);
4686
4687     /* Flow initialization rules:
4688      * - 'base_flow' must match the kernel's view of the packet at the
4689      *   time that action processing starts.  'flow' represents any
4690      *   transformations we wish to make through actions.
4691      * - By default 'base_flow' and 'flow' are the same since the input
4692      *   packet matches the output before any actions are applied.
4693      * - When using VLAN splinters, 'base_flow''s VLAN is set to the value
4694      *   of the received packet as seen by the kernel.  If we later output
4695      *   to another device without any modifications this will cause us to
4696      *   insert a new tag since the original one was stripped off by the
4697      *   VLAN device.
4698      * - Tunnel metadata as received is retained in 'flow'. This allows
4699      *   tunnel metadata matching also in later tables.
4700      *   Since a kernel action for setting the tunnel metadata will only be
4701      *   generated with actual tunnel output, changing the tunnel metadata
4702      *   values in 'flow' (such as tun_id) will only have effect with a later
4703      *   tunnel output action.
4704      * - Tunnel 'base_flow' is completely cleared since that is what the
4705      *   kernel does.  If we wish to maintain the original values an action
4706      *   needs to be generated. */
4707
4708     ctx.xin = xin;
4709     ctx.xout = xout;
4710     ctx.xout->slow = 0;
4711     ctx.xout->has_learn = false;
4712     ctx.xout->has_normal = false;
4713     ctx.xout->has_fin_timeout = false;
4714     ctx.xout->nf_output_iface = NF_OUT_DROP;
4715     ctx.xout->mirrors = 0;
4716     ctx.xout->n_recircs = 0;
4717
4718     xout->odp_actions = xin->odp_actions;
4719     if (!xout->odp_actions) {
4720         xout->odp_actions = &xout->odp_actions_buf;
4721         ofpbuf_use_stub(xout->odp_actions, xout->odp_actions_stub,
4722                         sizeof xout->odp_actions_stub);
4723     }
4724     ofpbuf_reserve(xout->odp_actions, NL_A_U32_SIZE);
4725
4726     xbridge = xbridge_lookup(xcfg, xin->ofproto);
4727     if (!xbridge) {
4728         return;
4729     }
4730     /* 'ctx.xbridge' may be changed by action processing, whereas 'xbridge'
4731      * will remain set on the original input bridge. */
4732     ctx.xbridge = xbridge;
4733     ctx.rule = xin->rule;
4734
4735     ctx.base_flow = *flow;
4736     memset(&ctx.base_flow.tunnel, 0, sizeof ctx.base_flow.tunnel);
4737     ctx.orig_tunnel_ip_dst = flow->tunnel.ip_dst;
4738
4739     if (!xin->skip_wildcards) {
4740         wc = &xout->wc;
4741         flow_wildcards_init_catchall(wc);
4742         memset(&wc->masks.in_port, 0xff, sizeof wc->masks.in_port);
4743         memset(&wc->masks.dl_type, 0xff, sizeof wc->masks.dl_type);
4744         if (is_ip_any(flow)) {
4745             wc->masks.nw_frag |= FLOW_NW_FRAG_MASK;
4746         }
4747         if (xbridge->enable_recirc) {
4748             /* Always exactly match recirc_id when datapath supports
4749              * recirculation.  */
4750             wc->masks.recirc_id = UINT32_MAX;
4751         }
4752         if (xbridge->netflow) {
4753             netflow_mask_wc(flow, wc);
4754         }
4755     }
4756     is_icmp = is_icmpv4(flow) || is_icmpv6(flow);
4757
4758     tnl_may_send = tnl_xlate_init(&ctx.base_flow, flow, wc);
4759
4760     ctx.recurse = 0;
4761     ctx.resubmits = 0;
4762     ctx.in_group = false;
4763     ctx.in_action_set = false;
4764     ctx.orig_skb_priority = flow->skb_priority;
4765     ctx.table_id = 0;
4766     ctx.rule_cookie = OVS_BE64_MAX;
4767     ctx.exit = false;
4768     ctx.was_mpls = false;
4769     ctx.recirc_action_offset = -1;
4770     ctx.last_unroll_offset = -1;
4771
4772     ctx.action_set_has_group = false;
4773     ofpbuf_use_stub(&ctx.action_set,
4774                     ctx.action_set_stub, sizeof ctx.action_set_stub);
4775
4776     ofpbuf_use_stub(&ctx.stack, ctx.init_stack, sizeof ctx.init_stack);
4777
4778     /* The in_port of the original packet before recirculation. */
4779     in_port = get_ofp_port(xbridge, flow->in_port.ofp_port);
4780
4781     if (xin->recirc) {
4782         const struct recirc_id_node *recirc = xin->recirc;
4783
4784         if (xin->ofpacts_len > 0 || ctx.rule) {
4785             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
4786
4787             VLOG_WARN_RL(&rl, "Recirculation conflict (%s)!",
4788                          xin->ofpacts_len > 0
4789                          ? "actions"
4790                          : "rule");
4791             return;
4792         }
4793
4794         /* Set the bridge for post-recirculation processing if needed. */
4795         if (ctx.xbridge->ofproto != recirc->ofproto) {
4796             struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
4797             const struct xbridge *new_bridge = xbridge_lookup(xcfg,
4798                                                               recirc->ofproto);
4799
4800             if (OVS_UNLIKELY(!new_bridge)) {
4801                 /* Drop the packet if the bridge cannot be found. */
4802                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
4803                 VLOG_WARN_RL(&rl, "Recirculation bridge no longer exists.");
4804                 return;
4805             }
4806             ctx.xbridge = new_bridge;
4807         }
4808
4809         /* Set the post-recirculation table id.  Note: A table lookup is done
4810          * only if there are no post-recirculation actions. */
4811         ctx.table_id = recirc->table_id;
4812
4813         /* Restore pipeline metadata. May change flow's in_port and other
4814          * metadata to the values that existed when recirculation was
4815          * triggered. */
4816         recirc_metadata_to_flow(&recirc->metadata, flow);
4817
4818         /* Restore stack, if any. */
4819         if (recirc->stack) {
4820             ofpbuf_put(&ctx.stack, recirc->stack->data, recirc->stack->size);
4821         }
4822
4823         /* Restore action set, if any. */
4824         if (recirc->action_set_len) {
4825             const struct ofpact *a;
4826
4827             ofpbuf_put(&ctx.action_set, recirc->ofpacts,
4828                        recirc->action_set_len);
4829
4830             OFPACT_FOR_EACH(a, recirc->ofpacts, recirc->action_set_len) {
4831                 if (a->type == OFPACT_GROUP) {
4832                     ctx.action_set_has_group = true;
4833                     break;
4834                 }
4835             }
4836         }
4837
4838         /* Restore recirculation actions.  If there are no actions, processing
4839          * will start with a lookup in the table set above. */
4840         if (recirc->ofpacts_len > recirc->action_set_len) {
4841             xin->ofpacts_len = recirc->ofpacts_len - recirc->action_set_len;
4842             xin->ofpacts = recirc->ofpacts +
4843                 recirc->action_set_len / sizeof *recirc->ofpacts;
4844         }
4845     } else if (OVS_UNLIKELY(flow->recirc_id)) {
4846         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
4847
4848         VLOG_WARN_RL(&rl, "Recirculation context not found for ID %"PRIx32,
4849                      flow->recirc_id);
4850         return;
4851     }
4852
4853     if (!xin->ofpacts && !ctx.rule) {
4854         rule = rule_dpif_lookup_from_table(ctx.xbridge->ofproto, flow, wc,
4855                                            ctx.xin->xcache != NULL,
4856                                            ctx.xin->resubmit_stats,
4857                                            &ctx.table_id,
4858                                            flow->in_port.ofp_port, true, true);
4859         if (ctx.xin->resubmit_stats) {
4860             rule_dpif_credit_stats(rule, ctx.xin->resubmit_stats);
4861         }
4862         if (ctx.xin->xcache) {
4863             struct xc_entry *entry;
4864
4865             entry = xlate_cache_add_entry(ctx.xin->xcache, XC_RULE);
4866             entry->u.rule = rule;
4867         }
4868         ctx.rule = rule;
4869
4870         if (OVS_UNLIKELY(ctx.xin->resubmit_hook)) {
4871             ctx.xin->resubmit_hook(ctx.xin, rule, 0);
4872         }
4873     }
4874     xout->fail_open = ctx.rule && rule_dpif_is_fail_open(ctx.rule);
4875
4876     if (xin->ofpacts) {
4877         ofpacts = xin->ofpacts;
4878         ofpacts_len = xin->ofpacts_len;
4879     } else if (ctx.rule) {
4880         const struct rule_actions *actions = rule_dpif_get_actions(ctx.rule);
4881
4882         ofpacts = actions->ofpacts;
4883         ofpacts_len = actions->ofpacts_len;
4884
4885         ctx.rule_cookie = rule_dpif_get_flow_cookie(ctx.rule);
4886     } else {
4887         OVS_NOT_REACHED();
4888     }
4889
4890     if (mbridge_has_mirrors(xbridge->mbridge)) {
4891         /* Do this conditionally because the copy is expensive enough that it
4892          * shows up in profiles. */
4893         orig_flow = *flow;
4894     }
4895
4896     /* Tunnel stats only for non-recirculated packets. */
4897     if (!xin->recirc && in_port && in_port->is_tunnel) {
4898         if (ctx.xin->resubmit_stats) {
4899             netdev_vport_inc_rx(in_port->netdev, ctx.xin->resubmit_stats);
4900             if (in_port->bfd) {
4901                 bfd_account_rx(in_port->bfd, ctx.xin->resubmit_stats);
4902             }
4903         }
4904         if (ctx.xin->xcache) {
4905             struct xc_entry *entry;
4906
4907             entry = xlate_cache_add_entry(ctx.xin->xcache, XC_NETDEV);
4908             entry->u.dev.rx = netdev_ref(in_port->netdev);
4909             entry->u.dev.bfd = bfd_ref(in_port->bfd);
4910         }
4911     }
4912
4913     /* Do not perform special processing on recirculated packets,
4914      * as recirculated packets are not really received by the bridge. */
4915     if (!xin->recirc &&
4916         (special = process_special(&ctx, flow, in_port, ctx.xin->packet))) {
4917         ctx.xout->slow |= special;
4918     } else {
4919         size_t sample_actions_len;
4920
4921         if (flow->in_port.ofp_port
4922             != vsp_realdev_to_vlandev(xbridge->ofproto,
4923                                       flow->in_port.ofp_port,
4924                                       flow->vlan_tci)) {
4925             ctx.base_flow.vlan_tci = 0;
4926         }
4927
4928         /* Sampling is done only for packets really received by the bridge. */
4929         if (!xin->recirc) {
4930             add_sflow_action(&ctx);
4931             add_ipfix_action(&ctx);
4932             sample_actions_len = ctx.xout->odp_actions->size;
4933         } else {
4934             sample_actions_len = 0;
4935         }
4936
4937         if (tnl_may_send && (!in_port || may_receive(in_port, &ctx))) {
4938             do_xlate_actions(ofpacts, ofpacts_len, &ctx);
4939
4940             /* We've let OFPP_NORMAL and the learning action look at the
4941              * packet, so drop it now if forwarding is disabled. */
4942             if (in_port && (!xport_stp_forward_state(in_port) ||
4943                             !xport_rstp_forward_state(in_port))) {
4944                 /* Drop all actions added by do_xlate_actions() above. */
4945                 ctx.xout->odp_actions->size = sample_actions_len;
4946
4947                 /* Undo changes that may have been done for recirculation. */
4948                 if (exit_recirculates(&ctx)) {
4949                     ctx.action_set.size = ctx.recirc_action_offset;
4950                     ctx.recirc_action_offset = -1;
4951                     ctx.last_unroll_offset = -1;
4952                 }
4953             } else if (ctx.action_set.size) {
4954                 /* Translate action set only if not dropping the packet and
4955                  * not recirculating. */
4956                 if (!exit_recirculates(&ctx)) {
4957                     xlate_action_set(&ctx);
4958                 }
4959             }
4960             /* Check if need to recirculate. */
4961             if (exit_recirculates(&ctx)) {
4962                 compose_recirculate_action(&ctx);
4963             }
4964         }
4965
4966         /* Output only fully processed packets. */
4967         if (!exit_recirculates(&ctx)
4968             && xbridge->has_in_band
4969             && in_band_must_output_to_local_port(flow)
4970             && !actions_output_to_local_port(&ctx)) {
4971             compose_output_action(&ctx, OFPP_LOCAL, NULL);
4972         }
4973
4974         if (!xin->recirc) {
4975             fix_sflow_action(&ctx);
4976         }
4977         /* Only mirror fully processed packets. */
4978         if (!exit_recirculates(&ctx)
4979             && mbridge_has_mirrors(xbridge->mbridge)) {
4980             add_mirror_actions(&ctx, &orig_flow);
4981         }
4982     }
4983
4984     if (nl_attr_oversized(ctx.xout->odp_actions->size)) {
4985         /* These datapath actions are too big for a Netlink attribute, so we
4986          * can't hand them to the kernel directly.  dpif_execute() can execute
4987          * them one by one with help, so just mark the result as SLOW_ACTION to
4988          * prevent the flow from being installed. */
4989         COVERAGE_INC(xlate_actions_oversize);
4990         ctx.xout->slow |= SLOW_ACTION;
4991     } else if (too_many_output_actions(ctx.xout->odp_actions)) {
4992         COVERAGE_INC(xlate_actions_too_many_output);
4993         ctx.xout->slow |= SLOW_ACTION;
4994     }
4995
4996     /* Update mirror stats only for packets really received by the bridge. */
4997     if (!xin->recirc && mbridge_has_mirrors(xbridge->mbridge)) {
4998         if (ctx.xin->resubmit_stats) {
4999             mirror_update_stats(xbridge->mbridge, xout->mirrors,
5000                                 ctx.xin->resubmit_stats->n_packets,
5001                                 ctx.xin->resubmit_stats->n_bytes);
5002         }
5003         if (ctx.xin->xcache) {
5004             struct xc_entry *entry;
5005
5006             entry = xlate_cache_add_entry(ctx.xin->xcache, XC_MIRROR);
5007             entry->u.mirror.mbridge = mbridge_ref(xbridge->mbridge);
5008             entry->u.mirror.mirrors = xout->mirrors;
5009         }
5010     }
5011
5012     /* Do netflow only for packets really received by the bridge. */
5013     if (!xin->recirc && xbridge->netflow) {
5014         /* Only update netflow if we don't have controller flow.  We don't
5015          * report NetFlow expiration messages for such facets because they
5016          * are just part of the control logic for the network, not real
5017          * traffic. */
5018         if (ofpacts_len == 0
5019             || ofpacts->type != OFPACT_CONTROLLER
5020             || ofpact_next(ofpacts) < ofpact_end(ofpacts, ofpacts_len)) {
5021             if (ctx.xin->resubmit_stats) {
5022                 netflow_flow_update(xbridge->netflow, flow,
5023                                     xout->nf_output_iface,
5024                                     ctx.xin->resubmit_stats);
5025             }
5026             if (ctx.xin->xcache) {
5027                 struct xc_entry *entry;
5028
5029                 entry = xlate_cache_add_entry(ctx.xin->xcache, XC_NETFLOW);
5030                 entry->u.nf.netflow = netflow_ref(xbridge->netflow);
5031                 entry->u.nf.flow = xmemdup(flow, sizeof *flow);
5032                 entry->u.nf.iface = xout->nf_output_iface;
5033             }
5034         }
5035     }
5036
5037     ofpbuf_uninit(&ctx.stack);
5038     ofpbuf_uninit(&ctx.action_set);
5039
5040     if (wc) {
5041         /* Clear the metadata and register wildcard masks, because we won't
5042          * use non-header fields as part of the cache. */
5043         flow_wildcards_clear_non_packet_fields(wc);
5044
5045         /* ICMPv4 and ICMPv6 have 8-bit "type" and "code" fields.  struct flow
5046          * uses the low 8 bits of the 16-bit tp_src and tp_dst members to
5047          * represent these fields.  The datapath interface, on the other hand,
5048          * represents them with just 8 bits each.  This means that if the high
5049          * 8 bits of the masks for these fields somehow become set, then they
5050          * will get chopped off by a round trip through the datapath, and
5051          * revalidation will spot that as an inconsistency and delete the flow.
5052          * Avoid the problem here by making sure that only the low 8 bits of
5053          * either field can be unwildcarded for ICMP.
5054          */
5055         if (is_icmp) {
5056             wc->masks.tp_src &= htons(UINT8_MAX);
5057             wc->masks.tp_dst &= htons(UINT8_MAX);
5058         }
5059     }
5060 }
5061
5062 /* Sends 'packet' out 'ofport'.
5063  * May modify 'packet'.
5064  * Returns 0 if successful, otherwise a positive errno value. */
5065 int
5066 xlate_send_packet(const struct ofport_dpif *ofport, struct dp_packet *packet)
5067 {
5068     struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
5069     struct xport *xport;
5070     struct ofpact_output output;
5071     struct flow flow;
5072
5073     ofpact_init(&output.ofpact, OFPACT_OUTPUT, sizeof output);
5074     /* Use OFPP_NONE as the in_port to avoid special packet processing. */
5075     flow_extract(packet, &flow);
5076     flow.in_port.ofp_port = OFPP_NONE;
5077
5078     xport = xport_lookup(xcfg, ofport);
5079     if (!xport) {
5080         return EINVAL;
5081     }
5082     output.port = xport->ofp_port;
5083     output.max_len = 0;
5084
5085     return ofproto_dpif_execute_actions(xport->xbridge->ofproto, &flow, NULL,
5086                                         &output.ofpact, sizeof output,
5087                                         packet);
5088 }
5089
5090 struct xlate_cache *
5091 xlate_cache_new(void)
5092 {
5093     struct xlate_cache *xcache = xmalloc(sizeof *xcache);
5094
5095     ofpbuf_init(&xcache->entries, 512);
5096     return xcache;
5097 }
5098
5099 static struct xc_entry *
5100 xlate_cache_add_entry(struct xlate_cache *xcache, enum xc_type type)
5101 {
5102     struct xc_entry *entry;
5103
5104     entry = ofpbuf_put_zeros(&xcache->entries, sizeof *entry);
5105     entry->type = type;
5106
5107     return entry;
5108 }
5109
5110 static void
5111 xlate_cache_netdev(struct xc_entry *entry, const struct dpif_flow_stats *stats)
5112 {
5113     if (entry->u.dev.tx) {
5114         netdev_vport_inc_tx(entry->u.dev.tx, stats);
5115     }
5116     if (entry->u.dev.rx) {
5117         netdev_vport_inc_rx(entry->u.dev.rx, stats);
5118     }
5119     if (entry->u.dev.bfd) {
5120         bfd_account_rx(entry->u.dev.bfd, stats);
5121     }
5122 }
5123
5124 static void
5125 xlate_cache_normal(struct ofproto_dpif *ofproto, struct flow *flow, int vlan)
5126 {
5127     struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
5128     struct xbridge *xbridge;
5129     struct xbundle *xbundle;
5130     struct flow_wildcards wc;
5131
5132     xbridge = xbridge_lookup(xcfg, ofproto);
5133     if (!xbridge) {
5134         return;
5135     }
5136
5137     xbundle = lookup_input_bundle(xbridge, flow->in_port.ofp_port, false,
5138                                   NULL);
5139     if (!xbundle) {
5140         return;
5141     }
5142
5143     update_learning_table(xbridge, flow, &wc, vlan, xbundle);
5144 }
5145
5146 /* Push stats and perform side effects of flow translation. */
5147 void
5148 xlate_push_stats(struct xlate_cache *xcache,
5149                  const struct dpif_flow_stats *stats)
5150 {
5151     struct xc_entry *entry;
5152     struct ofpbuf entries = xcache->entries;
5153     uint8_t dmac[ETH_ADDR_LEN];
5154
5155     if (!stats->n_packets) {
5156         return;
5157     }
5158
5159     XC_ENTRY_FOR_EACH (entry, entries, xcache) {
5160         switch (entry->type) {
5161         case XC_RULE:
5162             rule_dpif_credit_stats(entry->u.rule, stats);
5163             break;
5164         case XC_BOND:
5165             bond_account(entry->u.bond.bond, entry->u.bond.flow,
5166                          entry->u.bond.vid, stats->n_bytes);
5167             break;
5168         case XC_NETDEV:
5169             xlate_cache_netdev(entry, stats);
5170             break;
5171         case XC_NETFLOW:
5172             netflow_flow_update(entry->u.nf.netflow, entry->u.nf.flow,
5173                                 entry->u.nf.iface, stats);
5174             break;
5175         case XC_MIRROR:
5176             mirror_update_stats(entry->u.mirror.mbridge,
5177                                 entry->u.mirror.mirrors,
5178                                 stats->n_packets, stats->n_bytes);
5179             break;
5180         case XC_LEARN:
5181             ofproto_dpif_flow_mod(entry->u.learn.ofproto, entry->u.learn.fm);
5182             break;
5183         case XC_NORMAL:
5184             xlate_cache_normal(entry->u.normal.ofproto, entry->u.normal.flow,
5185                                entry->u.normal.vlan);
5186             break;
5187         case XC_FIN_TIMEOUT:
5188             xlate_fin_timeout__(entry->u.fin.rule, stats->tcp_flags,
5189                                 entry->u.fin.idle, entry->u.fin.hard);
5190             break;
5191         case XC_GROUP:
5192             group_dpif_credit_stats(entry->u.group.group, entry->u.group.bucket,
5193                                     stats);
5194             break;
5195         case XC_TNL_ARP:
5196             /* Lookup arp to avoid arp timeout. */
5197             tnl_arp_lookup(entry->u.tnl_arp_cache.br_name, entry->u.tnl_arp_cache.d_ip, dmac);
5198             break;
5199         default:
5200             OVS_NOT_REACHED();
5201         }
5202     }
5203 }
5204
5205 static void
5206 xlate_dev_unref(struct xc_entry *entry)
5207 {
5208     if (entry->u.dev.tx) {
5209         netdev_close(entry->u.dev.tx);
5210     }
5211     if (entry->u.dev.rx) {
5212         netdev_close(entry->u.dev.rx);
5213     }
5214     if (entry->u.dev.bfd) {
5215         bfd_unref(entry->u.dev.bfd);
5216     }
5217 }
5218
5219 static void
5220 xlate_cache_clear_netflow(struct netflow *netflow, struct flow *flow)
5221 {
5222     netflow_flow_clear(netflow, flow);
5223     netflow_unref(netflow);
5224     free(flow);
5225 }
5226
5227 void
5228 xlate_cache_clear(struct xlate_cache *xcache)
5229 {
5230     struct xc_entry *entry;
5231     struct ofpbuf entries;
5232
5233     if (!xcache) {
5234         return;
5235     }
5236
5237     XC_ENTRY_FOR_EACH (entry, entries, xcache) {
5238         switch (entry->type) {
5239         case XC_RULE:
5240             rule_dpif_unref(entry->u.rule);
5241             break;
5242         case XC_BOND:
5243             free(entry->u.bond.flow);
5244             bond_unref(entry->u.bond.bond);
5245             break;
5246         case XC_NETDEV:
5247             xlate_dev_unref(entry);
5248             break;
5249         case XC_NETFLOW:
5250             xlate_cache_clear_netflow(entry->u.nf.netflow, entry->u.nf.flow);
5251             break;
5252         case XC_MIRROR:
5253             mbridge_unref(entry->u.mirror.mbridge);
5254             break;
5255         case XC_LEARN:
5256             free(entry->u.learn.fm);
5257             ofpbuf_delete(entry->u.learn.ofpacts);
5258             break;
5259         case XC_NORMAL:
5260             free(entry->u.normal.flow);
5261             break;
5262         case XC_FIN_TIMEOUT:
5263             /* 'u.fin.rule' is always already held as a XC_RULE, which
5264              * has already released it's reference above. */
5265             break;
5266         case XC_GROUP:
5267             group_dpif_unref(entry->u.group.group);
5268             break;
5269         case XC_TNL_ARP:
5270             break;
5271         default:
5272             OVS_NOT_REACHED();
5273         }
5274     }
5275
5276     ofpbuf_clear(&xcache->entries);
5277 }
5278
5279 void
5280 xlate_cache_delete(struct xlate_cache *xcache)
5281 {
5282     xlate_cache_clear(xcache);
5283     ofpbuf_uninit(&xcache->entries);
5284     free(xcache);
5285 }