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