ofproto: Implement OF1.4 error code for set-async-config
[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-neigh-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     struct in6_addr orig_tunnel_ipv6_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_NEIGH,
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             struct in6_addr d_ipv6;
455         } tnl_neigh_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_NEIGH);
2814         ovs_strlcpy(entry->u.tnl_neigh_cache.br_name, out_dev->xbridge->name,
2815                     sizeof entry->u.tnl_neigh_cache.br_name);
2816         in6_addr_set_mapped_ipv4(&entry->u.tnl_neigh_cache.d_ipv6, 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 == 35);
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         ovs_be32 dst;
3027          /* Save tunnel metadata so that changes made due to
3028           * the Logical (tunnel) Port are not visible for any further
3029           * matches, while explicit set actions on tunnel metadata are.
3030           */
3031         flow_tnl = flow->tunnel;
3032         odp_port = tnl_port_send(xport->ofport, flow, ctx->wc);
3033         if (odp_port == ODPP_NONE) {
3034             xlate_report(ctx, "Tunneling decided against output");
3035             goto out; /* restore flow_nw_tos */
3036         }
3037         dst = in6_addr_get_mapped_ipv4(&ctx->orig_tunnel_ipv6_dst);
3038         if (flow->tunnel.ip_dst == dst) {
3039             xlate_report(ctx, "Not tunneling to our own address");
3040             goto out; /* restore flow_nw_tos */
3041         }
3042         if (ctx->xin->resubmit_stats) {
3043             netdev_vport_inc_tx(xport->netdev, ctx->xin->resubmit_stats);
3044         }
3045         if (ctx->xin->xcache) {
3046             struct xc_entry *entry;
3047
3048             entry = xlate_cache_add_entry(ctx->xin->xcache, XC_NETDEV);
3049             entry->u.dev.tx = netdev_ref(xport->netdev);
3050         }
3051         out_port = odp_port;
3052         if (ovs_native_tunneling_is_on(ctx->xbridge->ofproto)) {
3053             xlate_report(ctx, "output to native tunnel");
3054             tnl_push_pop_send = true;
3055         } else {
3056             xlate_report(ctx, "output to kernel tunnel");
3057             commit_odp_tunnel_action(flow, &ctx->base_flow, ctx->odp_actions);
3058             flow->tunnel = flow_tnl; /* Restore tunnel metadata */
3059         }
3060     } else {
3061         odp_port = xport->odp_port;
3062         out_port = odp_port;
3063         if (ofproto_has_vlan_splinters(ctx->xbridge->ofproto)) {
3064             ofp_port_t vlandev_port;
3065
3066             wc->masks.vlan_tci |= htons(VLAN_VID_MASK | VLAN_CFI);
3067             vlandev_port = vsp_realdev_to_vlandev(ctx->xbridge->ofproto,
3068                                                   ofp_port, flow->vlan_tci);
3069             if (vlandev_port != ofp_port) {
3070                 out_port = ofp_port_to_odp_port(ctx->xbridge, vlandev_port);
3071                 flow->vlan_tci = htons(0);
3072             }
3073         }
3074     }
3075
3076     if (out_port != ODPP_NONE) {
3077         xlate_commit_actions(ctx);
3078
3079         if (xr) {
3080             struct ovs_action_hash *act_hash;
3081
3082             /* Hash action. */
3083             act_hash = nl_msg_put_unspec_uninit(ctx->odp_actions,
3084                                                 OVS_ACTION_ATTR_HASH,
3085                                                 sizeof *act_hash);
3086             act_hash->hash_alg = xr->hash_alg;
3087             act_hash->hash_basis = xr->hash_basis;
3088
3089             /* Recirc action. */
3090             nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_RECIRC,
3091                            xr->recirc_id);
3092         } else {
3093
3094             if (tnl_push_pop_send) {
3095                 build_tunnel_send(ctx, xport, flow, odp_port);
3096                 flow->tunnel = flow_tnl; /* Restore tunnel metadata */
3097             } else {
3098                 odp_port_t odp_tnl_port = ODPP_NONE;
3099
3100                 /* XXX: Write better Filter for tunnel port. We can use inport
3101                 * int tunnel-port flow to avoid these checks completely. */
3102                 if (ofp_port == OFPP_LOCAL &&
3103                     ovs_native_tunneling_is_on(ctx->xbridge->ofproto)) {
3104
3105                     odp_tnl_port = tnl_port_map_lookup(flow, wc);
3106                 }
3107
3108                 if (odp_tnl_port != ODPP_NONE) {
3109                     nl_msg_put_odp_port(ctx->odp_actions,
3110                                         OVS_ACTION_ATTR_TUNNEL_POP,
3111                                         odp_tnl_port);
3112                 } else {
3113                     /* Tunnel push-pop action is not compatible with
3114                      * IPFIX action. */
3115                     compose_ipfix_action(ctx, out_port);
3116                     nl_msg_put_odp_port(ctx->odp_actions,
3117                                         OVS_ACTION_ATTR_OUTPUT,
3118                                         out_port);
3119                }
3120            }
3121         }
3122
3123         ctx->sflow_odp_port = odp_port;
3124         ctx->sflow_n_outputs++;
3125         ctx->nf_output_iface = ofp_port;
3126     }
3127
3128     if (mbridge_has_mirrors(ctx->xbridge->mbridge) && xport->xbundle) {
3129         mirror_packet(ctx, xport->xbundle,
3130                       xbundle_mirror_dst(xport->xbundle->xbridge,
3131                                          xport->xbundle));
3132     }
3133
3134  out:
3135     /* Restore flow */
3136     flow->vlan_tci = flow_vlan_tci;
3137     flow->pkt_mark = flow_pkt_mark;
3138     flow->nw_tos = flow_nw_tos;
3139 }
3140
3141 static void
3142 compose_output_action(struct xlate_ctx *ctx, ofp_port_t ofp_port,
3143                       const struct xlate_bond_recirc *xr)
3144 {
3145     compose_output_action__(ctx, ofp_port, xr, true);
3146 }
3147
3148 static void
3149 xlate_recursively(struct xlate_ctx *ctx, struct rule_dpif *rule)
3150 {
3151     struct rule_dpif *old_rule = ctx->rule;
3152     ovs_be64 old_cookie = ctx->rule_cookie;
3153     const struct rule_actions *actions;
3154
3155     if (ctx->xin->resubmit_stats) {
3156         rule_dpif_credit_stats(rule, ctx->xin->resubmit_stats);
3157     }
3158
3159     ctx->resubmits++;
3160     ctx->recurse++;
3161     ctx->rule = rule;
3162     ctx->rule_cookie = rule_dpif_get_flow_cookie(rule);
3163     actions = rule_dpif_get_actions(rule);
3164     do_xlate_actions(actions->ofpacts, actions->ofpacts_len, ctx);
3165     ctx->rule_cookie = old_cookie;
3166     ctx->rule = old_rule;
3167     ctx->recurse--;
3168 }
3169
3170 static bool
3171 xlate_resubmit_resource_check(struct xlate_ctx *ctx)
3172 {
3173     if (ctx->recurse >= MAX_RESUBMIT_RECURSION + MAX_INTERNAL_RESUBMITS) {
3174         XLATE_REPORT_ERROR(ctx, "resubmit actions recursed over %d times",
3175                            MAX_RESUBMIT_RECURSION);
3176         ctx->error = XLATE_RECURSION_TOO_DEEP;
3177     } else if (ctx->resubmits >= MAX_RESUBMITS + MAX_INTERNAL_RESUBMITS) {
3178         XLATE_REPORT_ERROR(ctx, "over %d resubmit actions", MAX_RESUBMITS);
3179         ctx->error = XLATE_TOO_MANY_RESUBMITS;
3180     } else if (ctx->odp_actions->size > UINT16_MAX) {
3181         XLATE_REPORT_ERROR(ctx, "resubmits yielded over 64 kB of actions");
3182         /* NOT an error, as we'll be slow-pathing the flow in this case? */
3183         ctx->exit = true; /* XXX: translation still terminated! */
3184     } else if (ctx->stack.size >= 65536) {
3185         XLATE_REPORT_ERROR(ctx, "resubmits yielded over 64 kB of stack");
3186         ctx->error = XLATE_STACK_TOO_DEEP;
3187     } else {
3188         return true;
3189     }
3190
3191     return false;
3192 }
3193
3194 static void
3195 xlate_table_action(struct xlate_ctx *ctx, ofp_port_t in_port, uint8_t table_id,
3196                    bool may_packet_in, bool honor_table_miss)
3197 {
3198     /* Check if we need to recirculate before matching in a table. */
3199     if (ctx->was_mpls) {
3200         ctx_trigger_recirculation(ctx);
3201         return;
3202     }
3203     if (xlate_resubmit_resource_check(ctx)) {
3204         uint8_t old_table_id = ctx->table_id;
3205         struct rule_dpif *rule;
3206
3207         ctx->table_id = table_id;
3208
3209         rule = rule_dpif_lookup_from_table(ctx->xbridge->ofproto,
3210                                            ctx->tables_version,
3211                                            &ctx->xin->flow, ctx->xin->wc,
3212                                            ctx->xin->resubmit_stats,
3213                                            &ctx->table_id, in_port,
3214                                            may_packet_in, honor_table_miss);
3215
3216         if (OVS_UNLIKELY(ctx->xin->resubmit_hook)) {
3217             ctx->xin->resubmit_hook(ctx->xin, rule, ctx->recurse + 1);
3218         }
3219
3220         if (rule) {
3221             /* Fill in the cache entry here instead of xlate_recursively
3222              * to make the reference counting more explicit.  We take a
3223              * reference in the lookups above if we are going to cache the
3224              * rule. */
3225             if (ctx->xin->xcache) {
3226                 struct xc_entry *entry;
3227
3228                 entry = xlate_cache_add_entry(ctx->xin->xcache, XC_RULE);
3229                 entry->u.rule = rule;
3230                 rule_dpif_ref(rule);
3231             }
3232             xlate_recursively(ctx, rule);
3233         }
3234
3235         ctx->table_id = old_table_id;
3236         return;
3237     }
3238 }
3239
3240 static void
3241 xlate_group_stats(struct xlate_ctx *ctx, struct group_dpif *group,
3242                   struct ofputil_bucket *bucket)
3243 {
3244     if (ctx->xin->resubmit_stats) {
3245         group_dpif_credit_stats(group, bucket, ctx->xin->resubmit_stats);
3246     }
3247     if (ctx->xin->xcache) {
3248         struct xc_entry *entry;
3249
3250         entry = xlate_cache_add_entry(ctx->xin->xcache, XC_GROUP);
3251         entry->u.group.group = group_dpif_ref(group);
3252         entry->u.group.bucket = bucket;
3253     }
3254 }
3255
3256 static void
3257 xlate_group_bucket(struct xlate_ctx *ctx, struct ofputil_bucket *bucket)
3258 {
3259     uint64_t action_list_stub[1024 / 8];
3260     struct ofpbuf action_list, action_set;
3261     struct flow old_flow = ctx->xin->flow;
3262     bool old_was_mpls = ctx->was_mpls;
3263
3264     ofpbuf_use_const(&action_set, bucket->ofpacts, bucket->ofpacts_len);
3265     ofpbuf_use_stub(&action_list, action_list_stub, sizeof action_list_stub);
3266
3267     ofpacts_execute_action_set(&action_list, &action_set);
3268     ctx->recurse++;
3269     do_xlate_actions(action_list.data, action_list.size, ctx);
3270     ctx->recurse--;
3271
3272     ofpbuf_uninit(&action_set);
3273     ofpbuf_uninit(&action_list);
3274
3275     /* Check if need to recirculate. */
3276     if (exit_recirculates(ctx)) {
3277         compose_recirculate_action(ctx);
3278     }
3279
3280     /* Roll back flow to previous state.
3281      * This is equivalent to cloning the packet for each bucket.
3282      *
3283      * As a side effect any subsequently applied actions will
3284      * also effectively be applied to a clone of the packet taken
3285      * just before applying the all or indirect group.
3286      *
3287      * Note that group buckets are action sets, hence they cannot modify the
3288      * main action set.  Also any stack actions are ignored when executing an
3289      * action set, so group buckets cannot change the stack either.
3290      * However, we do allow resubmit actions in group buckets, which could
3291      * break the above assumptions.  It is up to the controller to not mess up
3292      * with the action_set and stack in the tables resubmitted to from
3293      * group buckets. */
3294     ctx->xin->flow = old_flow;
3295
3296     /* The group bucket popping MPLS should have no effect after bucket
3297      * execution. */
3298     ctx->was_mpls = old_was_mpls;
3299
3300     /* The fact that the group bucket exits (for any reason) does not mean that
3301      * the translation after the group action should exit.  Specifically, if
3302      * the group bucket recirculates (which typically modifies the packet), the
3303      * actions after the group action must continue processing with the
3304      * original, not the recirculated packet! */
3305     ctx->exit = false;
3306 }
3307
3308 static void
3309 xlate_all_group(struct xlate_ctx *ctx, struct group_dpif *group)
3310 {
3311     struct ofputil_bucket *bucket;
3312     const struct ovs_list *buckets;
3313
3314     group_dpif_get_buckets(group, &buckets);
3315
3316     LIST_FOR_EACH (bucket, list_node, buckets) {
3317         xlate_group_bucket(ctx, bucket);
3318     }
3319     xlate_group_stats(ctx, group, NULL);
3320 }
3321
3322 static void
3323 xlate_ff_group(struct xlate_ctx *ctx, struct group_dpif *group)
3324 {
3325     struct ofputil_bucket *bucket;
3326
3327     bucket = group_first_live_bucket(ctx, group, 0);
3328     if (bucket) {
3329         xlate_group_bucket(ctx, bucket);
3330         xlate_group_stats(ctx, group, bucket);
3331     }
3332 }
3333
3334 static void
3335 xlate_default_select_group(struct xlate_ctx *ctx, struct group_dpif *group)
3336 {
3337     struct flow_wildcards *wc = ctx->wc;
3338     struct ofputil_bucket *bucket;
3339     uint32_t basis;
3340
3341     basis = flow_hash_symmetric_l4(&ctx->xin->flow, 0);
3342     flow_mask_hash_fields(&ctx->xin->flow, wc, NX_HASH_FIELDS_SYMMETRIC_L4);
3343     bucket = group_best_live_bucket(ctx, group, basis);
3344     if (bucket) {
3345         xlate_group_bucket(ctx, bucket);
3346         xlate_group_stats(ctx, group, bucket);
3347     }
3348 }
3349
3350 static void
3351 xlate_hash_fields_select_group(struct xlate_ctx *ctx, struct group_dpif *group)
3352 {
3353     struct mf_bitmap hash_fields = MF_BITMAP_INITIALIZER;
3354     const struct field_array *fields;
3355     struct ofputil_bucket *bucket;
3356     uint32_t basis;
3357     int i;
3358
3359     fields = group_dpif_get_fields(group);
3360     basis = hash_uint64(group_dpif_get_selection_method_param(group));
3361
3362     /* Determine which fields to hash */
3363     for (i = 0; i < MFF_N_IDS; i++) {
3364         if (bitmap_is_set(fields->used.bm, i)) {
3365             const struct mf_field *mf;
3366
3367             /* If the field is already present in 'hash_fields' then
3368              * this loop has already checked that it and its pre-requisites
3369              * are present in the flow and its pre-requisites have
3370              * already been added to 'hash_fields'. There is nothing more
3371              * to do here and as an optimisation the loop can continue. */
3372             if (bitmap_is_set(hash_fields.bm, i)) {
3373                 continue;
3374             }
3375
3376             mf = mf_from_id(i);
3377
3378             /* Only hash a field if it and its pre-requisites are present
3379              * in the flow. */
3380             if (!mf_are_prereqs_ok(mf, &ctx->xin->flow)) {
3381                 continue;
3382             }
3383
3384             /* Hash both the field and its pre-requisites */
3385             mf_bitmap_set_field_and_prereqs(mf, &hash_fields);
3386         }
3387     }
3388
3389     /* Hash the fields */
3390     for (i = 0; i < MFF_N_IDS; i++) {
3391         if (bitmap_is_set(hash_fields.bm, i)) {
3392             const struct mf_field *mf = mf_from_id(i);
3393             union mf_value value;
3394             int j;
3395
3396             mf_get_value(mf, &ctx->xin->flow, &value);
3397             /* This seems inefficient but so does apply_mask() */
3398             for (j = 0; j < mf->n_bytes; j++) {
3399                 ((uint8_t *) &value)[j] &= ((uint8_t *) &fields->value[i])[j];
3400             }
3401             basis = hash_bytes(&value, mf->n_bytes, basis);
3402
3403             /* For tunnels, hash in whether the field is present. */
3404             if (mf_is_tun_metadata(mf)) {
3405                 basis = hash_boolean(mf_is_set(mf, &ctx->xin->flow), basis);
3406             }
3407
3408             mf_mask_field(mf, &ctx->wc->masks);
3409         }
3410     }
3411
3412     bucket = group_best_live_bucket(ctx, group, basis);
3413     if (bucket) {
3414         xlate_group_bucket(ctx, bucket);
3415         xlate_group_stats(ctx, group, bucket);
3416     }
3417 }
3418
3419 static void
3420 xlate_select_group(struct xlate_ctx *ctx, struct group_dpif *group)
3421 {
3422     const char *selection_method = group_dpif_get_selection_method(group);
3423
3424     if (selection_method[0] == '\0') {
3425         xlate_default_select_group(ctx, group);
3426     } else if (!strcasecmp("hash", selection_method)) {
3427         xlate_hash_fields_select_group(ctx, group);
3428     } else {
3429         /* Parsing of groups should ensure this never happens */
3430         OVS_NOT_REACHED();
3431     }
3432 }
3433
3434 static void
3435 xlate_group_action__(struct xlate_ctx *ctx, struct group_dpif *group)
3436 {
3437     bool was_in_group = ctx->in_group;
3438     ctx->in_group = true;
3439
3440     switch (group_dpif_get_type(group)) {
3441     case OFPGT11_ALL:
3442     case OFPGT11_INDIRECT:
3443         xlate_all_group(ctx, group);
3444         break;
3445     case OFPGT11_SELECT:
3446         xlate_select_group(ctx, group);
3447         break;
3448     case OFPGT11_FF:
3449         xlate_ff_group(ctx, group);
3450         break;
3451     default:
3452         OVS_NOT_REACHED();
3453     }
3454     group_dpif_unref(group);
3455
3456     ctx->in_group = was_in_group;
3457 }
3458
3459 static bool
3460 xlate_group_action(struct xlate_ctx *ctx, uint32_t group_id)
3461 {
3462     if (xlate_resubmit_resource_check(ctx)) {
3463         struct group_dpif *group;
3464         bool got_group;
3465
3466         got_group = group_dpif_lookup(ctx->xbridge->ofproto, group_id, &group);
3467         if (got_group) {
3468             xlate_group_action__(ctx, group);
3469         } else {
3470             return true;
3471         }
3472     }
3473
3474     return false;
3475 }
3476
3477 static void
3478 xlate_ofpact_resubmit(struct xlate_ctx *ctx,
3479                       const struct ofpact_resubmit *resubmit)
3480 {
3481     ofp_port_t in_port;
3482     uint8_t table_id;
3483     bool may_packet_in = false;
3484     bool honor_table_miss = false;
3485
3486     if (ctx->rule && rule_dpif_is_internal(ctx->rule)) {
3487         /* Still allow missed packets to be sent to the controller
3488          * if resubmitting from an internal table. */
3489         may_packet_in = true;
3490         honor_table_miss = true;
3491     }
3492
3493     in_port = resubmit->in_port;
3494     if (in_port == OFPP_IN_PORT) {
3495         in_port = ctx->xin->flow.in_port.ofp_port;
3496     }
3497
3498     table_id = resubmit->table_id;
3499     if (table_id == 255) {
3500         table_id = ctx->table_id;
3501     }
3502
3503     xlate_table_action(ctx, in_port, table_id, may_packet_in,
3504                        honor_table_miss);
3505 }
3506
3507 static void
3508 flood_packets(struct xlate_ctx *ctx, bool all)
3509 {
3510     const struct xport *xport;
3511
3512     HMAP_FOR_EACH (xport, ofp_node, &ctx->xbridge->xports) {
3513         if (xport->ofp_port == ctx->xin->flow.in_port.ofp_port) {
3514             continue;
3515         }
3516
3517         if (all) {
3518             compose_output_action__(ctx, xport->ofp_port, NULL, false);
3519         } else if (!(xport->config & OFPUTIL_PC_NO_FLOOD)) {
3520             compose_output_action(ctx, xport->ofp_port, NULL);
3521         }
3522     }
3523
3524     ctx->nf_output_iface = NF_OUT_FLOOD;
3525 }
3526
3527 static void
3528 execute_controller_action(struct xlate_ctx *ctx, int len,
3529                           enum ofp_packet_in_reason reason,
3530                           uint16_t controller_id)
3531 {
3532     struct ofproto_packet_in *pin;
3533     struct dp_packet *packet;
3534
3535     ctx->xout->slow |= SLOW_CONTROLLER;
3536     if (!ctx->xin->packet) {
3537         return;
3538     }
3539
3540     packet = dp_packet_clone(ctx->xin->packet);
3541
3542     xlate_commit_actions(ctx);
3543
3544     odp_execute_actions(NULL, &packet, 1, false,
3545                         ctx->odp_actions->data, ctx->odp_actions->size, NULL);
3546
3547     pin = xmalloc(sizeof *pin);
3548     pin->up.packet_len = dp_packet_size(packet);
3549     pin->up.packet = dp_packet_steal_data(packet);
3550     pin->up.reason = reason;
3551     pin->up.table_id = ctx->table_id;
3552     pin->up.cookie = ctx->rule_cookie;
3553
3554     flow_get_metadata(&ctx->xin->flow, &pin->up.flow_metadata);
3555
3556     pin->controller_id = controller_id;
3557     pin->send_len = len;
3558     /* If a rule is a table-miss rule then this is
3559      * a table-miss handled by a table-miss rule.
3560      *
3561      * Else, if rule is internal and has a controller action,
3562      * the later being implied by the rule being processed here,
3563      * then this is a table-miss handled without a table-miss rule.
3564      *
3565      * Otherwise this is not a table-miss. */
3566     pin->miss_type = OFPROTO_PACKET_IN_NO_MISS;
3567     if (ctx->rule) {
3568         if (rule_dpif_is_table_miss(ctx->rule)) {
3569             pin->miss_type = OFPROTO_PACKET_IN_MISS_FLOW;
3570         } else if (rule_dpif_is_internal(ctx->rule)) {
3571             pin->miss_type = OFPROTO_PACKET_IN_MISS_WITHOUT_FLOW;
3572         }
3573     }
3574     ofproto_dpif_send_packet_in(ctx->xbridge->ofproto, pin);
3575     dp_packet_delete(packet);
3576 }
3577
3578 static void
3579 compose_recirculate_action__(struct xlate_ctx *ctx, uint8_t table)
3580 {
3581     struct recirc_metadata md;
3582     uint32_t id;
3583
3584     recirc_metadata_from_flow(&md, &ctx->xin->flow);
3585
3586     ovs_assert(ctx->recirc_action_offset >= 0);
3587
3588     struct recirc_state state = {
3589         .table_id = table,
3590         .ofproto = ctx->xbridge->ofproto,
3591         .metadata = md,
3592         .stack = &ctx->stack,
3593         .mirrors = ctx->mirrors,
3594         .conntracked = ctx->conntracked,
3595         .action_set_len = ctx->recirc_action_offset,
3596         .ofpacts_len = ctx->action_set.size,
3597         .ofpacts = ctx->action_set.data,
3598     };
3599
3600     /* Allocate a unique recirc id for the given metadata state in the
3601      * flow.  An existing id, with a new reference to the corresponding
3602      * recirculation context, will be returned if possible.
3603      * The life-cycle of this recirc id is managed by associating it
3604      * with the udpif key ('ukey') created for each new datapath flow. */
3605     id = recirc_alloc_id_ctx(&state);
3606     if (!id) {
3607         XLATE_REPORT_ERROR(ctx, "Failed to allocate recirculation id");
3608         ctx->error = XLATE_NO_RECIRCULATION_CONTEXT;
3609         return;
3610     }
3611     recirc_refs_add(&ctx->xout->recircs, id);
3612
3613     nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_RECIRC, id);
3614
3615     /* Undo changes done by recirculation. */
3616     ctx->action_set.size = ctx->recirc_action_offset;
3617     ctx->recirc_action_offset = -1;
3618     ctx->last_unroll_offset = -1;
3619 }
3620
3621 /* Called only when ctx->recirc_action_offset is set. */
3622 static void
3623 compose_recirculate_action(struct xlate_ctx *ctx)
3624 {
3625     xlate_commit_actions(ctx);
3626     compose_recirculate_action__(ctx, 0);
3627 }
3628
3629 /* Fork the pipeline here. The current packet will continue processing the
3630  * current action list. A clone of the current packet will recirculate, skip
3631  * the remainder of the current action list and asynchronously resume pipeline
3632  * processing in 'table' with the current metadata and action set. */
3633 static void
3634 compose_recirculate_and_fork(struct xlate_ctx *ctx, uint8_t table)
3635 {
3636     ctx->recirc_action_offset = ctx->action_set.size;
3637     compose_recirculate_action__(ctx, table);
3638 }
3639
3640 static void
3641 compose_mpls_push_action(struct xlate_ctx *ctx, struct ofpact_push_mpls *mpls)
3642 {
3643     struct flow *flow = &ctx->xin->flow;
3644     int n;
3645
3646     ovs_assert(eth_type_mpls(mpls->ethertype));
3647
3648     n = flow_count_mpls_labels(flow, ctx->wc);
3649     if (!n) {
3650         xlate_commit_actions(ctx);
3651     } else if (n >= FLOW_MAX_MPLS_LABELS) {
3652         if (ctx->xin->packet != NULL) {
3653             XLATE_REPORT_ERROR(ctx, "bridge %s: dropping packet on which an "
3654                          "MPLS push action can't be performed as it would "
3655                          "have more MPLS LSEs than the %d supported.",
3656                          ctx->xbridge->name, FLOW_MAX_MPLS_LABELS);
3657         }
3658         ctx->error = XLATE_TOO_MANY_MPLS_LABELS;
3659         return;
3660     }
3661
3662     flow_push_mpls(flow, n, mpls->ethertype, ctx->wc);
3663 }
3664
3665 static void
3666 compose_mpls_pop_action(struct xlate_ctx *ctx, ovs_be16 eth_type)
3667 {
3668     struct flow *flow = &ctx->xin->flow;
3669     int n = flow_count_mpls_labels(flow, ctx->wc);
3670
3671     if (flow_pop_mpls(flow, n, eth_type, ctx->wc)) {
3672         if (ctx->xbridge->support.odp.recirc) {
3673             ctx->was_mpls = true;
3674         }
3675     } else if (n >= FLOW_MAX_MPLS_LABELS) {
3676         if (ctx->xin->packet != NULL) {
3677             XLATE_REPORT_ERROR(ctx, "bridge %s: dropping packet on which an "
3678                          "MPLS pop action can't be performed as it has "
3679                          "more MPLS LSEs than the %d supported.",
3680                          ctx->xbridge->name, FLOW_MAX_MPLS_LABELS);
3681         }
3682         ctx->error = XLATE_TOO_MANY_MPLS_LABELS;
3683         ofpbuf_clear(ctx->odp_actions);
3684     }
3685 }
3686
3687 static bool
3688 compose_dec_ttl(struct xlate_ctx *ctx, struct ofpact_cnt_ids *ids)
3689 {
3690     struct flow *flow = &ctx->xin->flow;
3691
3692     if (!is_ip_any(flow)) {
3693         return false;
3694     }
3695
3696     ctx->wc->masks.nw_ttl = 0xff;
3697     if (flow->nw_ttl > 1) {
3698         flow->nw_ttl--;
3699         return false;
3700     } else {
3701         size_t i;
3702
3703         for (i = 0; i < ids->n_controllers; i++) {
3704             execute_controller_action(ctx, UINT16_MAX, OFPR_INVALID_TTL,
3705                                       ids->cnt_ids[i]);
3706         }
3707
3708         /* Stop processing for current table. */
3709         return true;
3710     }
3711 }
3712
3713 static void
3714 compose_set_mpls_label_action(struct xlate_ctx *ctx, ovs_be32 label)
3715 {
3716     if (eth_type_mpls(ctx->xin->flow.dl_type)) {
3717         ctx->wc->masks.mpls_lse[0] |= htonl(MPLS_LABEL_MASK);
3718         set_mpls_lse_label(&ctx->xin->flow.mpls_lse[0], label);
3719     }
3720 }
3721
3722 static void
3723 compose_set_mpls_tc_action(struct xlate_ctx *ctx, uint8_t tc)
3724 {
3725     if (eth_type_mpls(ctx->xin->flow.dl_type)) {
3726         ctx->wc->masks.mpls_lse[0] |= htonl(MPLS_TC_MASK);
3727         set_mpls_lse_tc(&ctx->xin->flow.mpls_lse[0], tc);
3728     }
3729 }
3730
3731 static void
3732 compose_set_mpls_ttl_action(struct xlate_ctx *ctx, uint8_t ttl)
3733 {
3734     if (eth_type_mpls(ctx->xin->flow.dl_type)) {
3735         ctx->wc->masks.mpls_lse[0] |= htonl(MPLS_TTL_MASK);
3736         set_mpls_lse_ttl(&ctx->xin->flow.mpls_lse[0], ttl);
3737     }
3738 }
3739
3740 static bool
3741 compose_dec_mpls_ttl_action(struct xlate_ctx *ctx)
3742 {
3743     struct flow *flow = &ctx->xin->flow;
3744
3745     if (eth_type_mpls(flow->dl_type)) {
3746         uint8_t ttl = mpls_lse_to_ttl(flow->mpls_lse[0]);
3747
3748         ctx->wc->masks.mpls_lse[0] |= htonl(MPLS_TTL_MASK);
3749         if (ttl > 1) {
3750             ttl--;
3751             set_mpls_lse_ttl(&flow->mpls_lse[0], ttl);
3752             return false;
3753         } else {
3754             execute_controller_action(ctx, UINT16_MAX, OFPR_INVALID_TTL, 0);
3755         }
3756     }
3757
3758     /* Stop processing for current table. */
3759     return true;
3760 }
3761
3762 static void
3763 xlate_output_action(struct xlate_ctx *ctx,
3764                     ofp_port_t port, uint16_t max_len, bool may_packet_in)
3765 {
3766     ofp_port_t prev_nf_output_iface = ctx->nf_output_iface;
3767
3768     ctx->nf_output_iface = NF_OUT_DROP;
3769
3770     switch (port) {
3771     case OFPP_IN_PORT:
3772         compose_output_action(ctx, ctx->xin->flow.in_port.ofp_port, NULL);
3773         break;
3774     case OFPP_TABLE:
3775         xlate_table_action(ctx, ctx->xin->flow.in_port.ofp_port,
3776                            0, may_packet_in, true);
3777         break;
3778     case OFPP_NORMAL:
3779         xlate_normal(ctx);
3780         break;
3781     case OFPP_FLOOD:
3782         flood_packets(ctx,  false);
3783         break;
3784     case OFPP_ALL:
3785         flood_packets(ctx, true);
3786         break;
3787     case OFPP_CONTROLLER:
3788         execute_controller_action(ctx, max_len,
3789                                   (ctx->in_group ? OFPR_GROUP
3790                                    : ctx->in_action_set ? OFPR_ACTION_SET
3791                                    : OFPR_ACTION),
3792                                   0);
3793         break;
3794     case OFPP_NONE:
3795         break;
3796     case OFPP_LOCAL:
3797     default:
3798         if (port != ctx->xin->flow.in_port.ofp_port) {
3799             compose_output_action(ctx, port, NULL);
3800         } else {
3801             xlate_report(ctx, "skipping output to input port");
3802         }
3803         break;
3804     }
3805
3806     if (prev_nf_output_iface == NF_OUT_FLOOD) {
3807         ctx->nf_output_iface = NF_OUT_FLOOD;
3808     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
3809         ctx->nf_output_iface = prev_nf_output_iface;
3810     } else if (prev_nf_output_iface != NF_OUT_DROP &&
3811                ctx->nf_output_iface != NF_OUT_FLOOD) {
3812         ctx->nf_output_iface = NF_OUT_MULTI;
3813     }
3814 }
3815
3816 static void
3817 xlate_output_reg_action(struct xlate_ctx *ctx,
3818                         const struct ofpact_output_reg *or)
3819 {
3820     uint64_t port = mf_get_subfield(&or->src, &ctx->xin->flow);
3821     if (port <= UINT16_MAX) {
3822         union mf_subvalue value;
3823
3824         memset(&value, 0xff, sizeof value);
3825         mf_write_subfield_flow(&or->src, &value, &ctx->wc->masks);
3826         xlate_output_action(ctx, u16_to_ofp(port),
3827                             or->max_len, false);
3828     }
3829 }
3830
3831 static void
3832 xlate_enqueue_action(struct xlate_ctx *ctx,
3833                      const struct ofpact_enqueue *enqueue)
3834 {
3835     ofp_port_t ofp_port = enqueue->port;
3836     uint32_t queue_id = enqueue->queue;
3837     uint32_t flow_priority, priority;
3838     int error;
3839
3840     /* Translate queue to priority. */
3841     error = dpif_queue_to_priority(ctx->xbridge->dpif, queue_id, &priority);
3842     if (error) {
3843         /* Fall back to ordinary output action. */
3844         xlate_output_action(ctx, enqueue->port, 0, false);
3845         return;
3846     }
3847
3848     /* Check output port. */
3849     if (ofp_port == OFPP_IN_PORT) {
3850         ofp_port = ctx->xin->flow.in_port.ofp_port;
3851     } else if (ofp_port == ctx->xin->flow.in_port.ofp_port) {
3852         return;
3853     }
3854
3855     /* Add datapath actions. */
3856     flow_priority = ctx->xin->flow.skb_priority;
3857     ctx->xin->flow.skb_priority = priority;
3858     compose_output_action(ctx, ofp_port, NULL);
3859     ctx->xin->flow.skb_priority = flow_priority;
3860
3861     /* Update NetFlow output port. */
3862     if (ctx->nf_output_iface == NF_OUT_DROP) {
3863         ctx->nf_output_iface = ofp_port;
3864     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
3865         ctx->nf_output_iface = NF_OUT_MULTI;
3866     }
3867 }
3868
3869 static void
3870 xlate_set_queue_action(struct xlate_ctx *ctx, uint32_t queue_id)
3871 {
3872     uint32_t skb_priority;
3873
3874     if (!dpif_queue_to_priority(ctx->xbridge->dpif, queue_id, &skb_priority)) {
3875         ctx->xin->flow.skb_priority = skb_priority;
3876     } else {
3877         /* Couldn't translate queue to a priority.  Nothing to do.  A warning
3878          * has already been logged. */
3879     }
3880 }
3881
3882 static bool
3883 slave_enabled_cb(ofp_port_t ofp_port, void *xbridge_)
3884 {
3885     const struct xbridge *xbridge = xbridge_;
3886     struct xport *port;
3887
3888     switch (ofp_port) {
3889     case OFPP_IN_PORT:
3890     case OFPP_TABLE:
3891     case OFPP_NORMAL:
3892     case OFPP_FLOOD:
3893     case OFPP_ALL:
3894     case OFPP_NONE:
3895         return true;
3896     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
3897         return false;
3898     default:
3899         port = get_ofp_port(xbridge, ofp_port);
3900         return port ? port->may_enable : false;
3901     }
3902 }
3903
3904 static void
3905 xlate_bundle_action(struct xlate_ctx *ctx,
3906                     const struct ofpact_bundle *bundle)
3907 {
3908     ofp_port_t port;
3909
3910     port = bundle_execute(bundle, &ctx->xin->flow, ctx->wc, slave_enabled_cb,
3911                           CONST_CAST(struct xbridge *, ctx->xbridge));
3912     if (bundle->dst.field) {
3913         nxm_reg_load(&bundle->dst, ofp_to_u16(port), &ctx->xin->flow, ctx->wc);
3914     } else {
3915         xlate_output_action(ctx, port, 0, false);
3916     }
3917 }
3918
3919 static void
3920 xlate_learn_action__(struct xlate_ctx *ctx, const struct ofpact_learn *learn,
3921                      struct ofputil_flow_mod *fm, struct ofpbuf *ofpacts)
3922 {
3923     learn_execute(learn, &ctx->xin->flow, fm, ofpacts);
3924     if (ctx->xin->may_learn) {
3925         ofproto_dpif_flow_mod(ctx->xbridge->ofproto, fm);
3926     }
3927 }
3928
3929 static void
3930 xlate_learn_action(struct xlate_ctx *ctx, const struct ofpact_learn *learn)
3931 {
3932     learn_mask(learn, ctx->wc);
3933
3934     if (ctx->xin->xcache) {
3935         struct xc_entry *entry;
3936
3937         entry = xlate_cache_add_entry(ctx->xin->xcache, XC_LEARN);
3938         entry->u.learn.ofproto = ctx->xbridge->ofproto;
3939         entry->u.learn.fm = xmalloc(sizeof *entry->u.learn.fm);
3940         entry->u.learn.ofpacts = ofpbuf_new(64);
3941         xlate_learn_action__(ctx, learn, entry->u.learn.fm,
3942                              entry->u.learn.ofpacts);
3943     } else if (ctx->xin->may_learn) {
3944         uint64_t ofpacts_stub[1024 / 8];
3945         struct ofputil_flow_mod fm;
3946         struct ofpbuf ofpacts;
3947
3948         ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
3949         xlate_learn_action__(ctx, learn, &fm, &ofpacts);
3950         ofpbuf_uninit(&ofpacts);
3951     }
3952 }
3953
3954 static void
3955 xlate_fin_timeout__(struct rule_dpif *rule, uint16_t tcp_flags,
3956                     uint16_t idle_timeout, uint16_t hard_timeout)
3957 {
3958     if (tcp_flags & (TCP_FIN | TCP_RST)) {
3959         rule_dpif_reduce_timeouts(rule, idle_timeout, hard_timeout);
3960     }
3961 }
3962
3963 static void
3964 xlate_fin_timeout(struct xlate_ctx *ctx,
3965                   const struct ofpact_fin_timeout *oft)
3966 {
3967     if (ctx->rule) {
3968         xlate_fin_timeout__(ctx->rule, ctx->xin->tcp_flags,
3969                             oft->fin_idle_timeout, oft->fin_hard_timeout);
3970         if (ctx->xin->xcache) {
3971             struct xc_entry *entry;
3972
3973             entry = xlate_cache_add_entry(ctx->xin->xcache, XC_FIN_TIMEOUT);
3974             /* XC_RULE already holds a reference on the rule, none is taken
3975              * here. */
3976             entry->u.fin.rule = ctx->rule;
3977             entry->u.fin.idle = oft->fin_idle_timeout;
3978             entry->u.fin.hard = oft->fin_hard_timeout;
3979         }
3980     }
3981 }
3982
3983 static void
3984 xlate_sample_action(struct xlate_ctx *ctx,
3985                     const struct ofpact_sample *os)
3986 {
3987     /* Scale the probability from 16-bit to 32-bit while representing
3988      * the same percentage. */
3989     uint32_t probability = (os->probability << 16) | os->probability;
3990
3991     if (!ctx->xbridge->support.variable_length_userdata) {
3992         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
3993
3994         VLOG_ERR_RL(&rl, "ignoring NXAST_SAMPLE action because datapath "
3995                     "lacks support (needs Linux 3.10+ or kernel module from "
3996                     "OVS 1.11+)");
3997         return;
3998     }
3999
4000     xlate_commit_actions(ctx);
4001
4002     union user_action_cookie cookie = {
4003         .flow_sample = {
4004             .type = USER_ACTION_COOKIE_FLOW_SAMPLE,
4005             .probability = os->probability,
4006             .collector_set_id = os->collector_set_id,
4007             .obs_domain_id = os->obs_domain_id,
4008             .obs_point_id = os->obs_point_id,
4009         }
4010     };
4011     compose_sample_action(ctx, probability, &cookie, sizeof cookie.flow_sample,
4012                           ODPP_NONE, false);
4013 }
4014
4015 static bool
4016 may_receive(const struct xport *xport, struct xlate_ctx *ctx)
4017 {
4018     if (xport->config & (is_stp(&ctx->xin->flow)
4019                          ? OFPUTIL_PC_NO_RECV_STP
4020                          : OFPUTIL_PC_NO_RECV)) {
4021         return false;
4022     }
4023
4024     /* Only drop packets here if both forwarding and learning are
4025      * disabled.  If just learning is enabled, we need to have
4026      * OFPP_NORMAL and the learning action have a look at the packet
4027      * before we can drop it. */
4028     if ((!xport_stp_forward_state(xport) && !xport_stp_learn_state(xport)) ||
4029         (!xport_rstp_forward_state(xport) && !xport_rstp_learn_state(xport))) {
4030         return false;
4031     }
4032
4033     return true;
4034 }
4035
4036 static void
4037 xlate_write_actions(struct xlate_ctx *ctx, const struct ofpact *a)
4038 {
4039     const struct ofpact_nest *on = ofpact_get_WRITE_ACTIONS(a);
4040     size_t on_len = ofpact_nest_get_action_len(on);
4041     const struct ofpact *inner;
4042
4043     /* Maintain actset_output depending on the contents of the action set:
4044      *
4045      *   - OFPP_UNSET, if there is no "output" action.
4046      *
4047      *   - The output port, if there is an "output" action and no "group"
4048      *     action.
4049      *
4050      *   - OFPP_UNSET, if there is a "group" action.
4051      */
4052     if (!ctx->action_set_has_group) {
4053         OFPACT_FOR_EACH (inner, on->actions, on_len) {
4054             if (inner->type == OFPACT_OUTPUT) {
4055                 ctx->xin->flow.actset_output = ofpact_get_OUTPUT(inner)->port;
4056             } else if (inner->type == OFPACT_GROUP) {
4057                 ctx->xin->flow.actset_output = OFPP_UNSET;
4058                 ctx->action_set_has_group = true;
4059                 break;
4060             }
4061         }
4062     }
4063
4064     ofpbuf_put(&ctx->action_set, on->actions, on_len);
4065     ofpact_pad(&ctx->action_set);
4066 }
4067
4068 static void
4069 xlate_action_set(struct xlate_ctx *ctx)
4070 {
4071     uint64_t action_list_stub[1024 / 64];
4072     struct ofpbuf action_list;
4073
4074     ctx->in_action_set = true;
4075     ofpbuf_use_stub(&action_list, action_list_stub, sizeof action_list_stub);
4076     ofpacts_execute_action_set(&action_list, &ctx->action_set);
4077     /* Clear the action set, as it is not needed any more. */
4078     ofpbuf_clear(&ctx->action_set);
4079     do_xlate_actions(action_list.data, action_list.size, ctx);
4080     ctx->in_action_set = false;
4081     ofpbuf_uninit(&action_list);
4082 }
4083
4084 static void
4085 recirc_put_unroll_xlate(struct xlate_ctx *ctx)
4086 {
4087     struct ofpact_unroll_xlate *unroll;
4088
4089     unroll = ctx->last_unroll_offset < 0
4090         ? NULL
4091         : ALIGNED_CAST(struct ofpact_unroll_xlate *,
4092                        (char *)ctx->action_set.data + ctx->last_unroll_offset);
4093
4094     /* Restore the table_id and rule cookie for a potential PACKET
4095      * IN if needed. */
4096     if (!unroll ||
4097         (ctx->table_id != unroll->rule_table_id
4098          || ctx->rule_cookie != unroll->rule_cookie)) {
4099
4100         ctx->last_unroll_offset = ctx->action_set.size;
4101         unroll = ofpact_put_UNROLL_XLATE(&ctx->action_set);
4102         unroll->rule_table_id = ctx->table_id;
4103         unroll->rule_cookie = ctx->rule_cookie;
4104     }
4105 }
4106
4107
4108 /* Copy remaining actions to the action_set to be executed after recirculation.
4109  * UNROLL_XLATE action is inserted, if not already done so, before actions that
4110  * may generate PACKET_INs from the current table and without matching another
4111  * rule. */
4112 static void
4113 recirc_unroll_actions(const struct ofpact *ofpacts, size_t ofpacts_len,
4114                       struct xlate_ctx *ctx)
4115 {
4116     const struct ofpact *a;
4117
4118     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
4119         switch (a->type) {
4120             /* May generate PACKET INs. */
4121         case OFPACT_OUTPUT_REG:
4122         case OFPACT_GROUP:
4123         case OFPACT_OUTPUT:
4124         case OFPACT_CONTROLLER:
4125         case OFPACT_DEC_MPLS_TTL:
4126         case OFPACT_DEC_TTL:
4127             recirc_put_unroll_xlate(ctx);
4128             break;
4129
4130             /* These may not generate PACKET INs. */
4131         case OFPACT_SET_TUNNEL:
4132         case OFPACT_REG_MOVE:
4133         case OFPACT_SET_FIELD:
4134         case OFPACT_STACK_PUSH:
4135         case OFPACT_STACK_POP:
4136         case OFPACT_LEARN:
4137         case OFPACT_WRITE_METADATA:
4138         case OFPACT_RESUBMIT:        /* May indirectly generate PACKET INs, */
4139         case OFPACT_GOTO_TABLE:      /* but from a different table and rule. */
4140         case OFPACT_ENQUEUE:
4141         case OFPACT_SET_VLAN_VID:
4142         case OFPACT_SET_VLAN_PCP:
4143         case OFPACT_STRIP_VLAN:
4144         case OFPACT_PUSH_VLAN:
4145         case OFPACT_SET_ETH_SRC:
4146         case OFPACT_SET_ETH_DST:
4147         case OFPACT_SET_IPV4_SRC:
4148         case OFPACT_SET_IPV4_DST:
4149         case OFPACT_SET_IP_DSCP:
4150         case OFPACT_SET_IP_ECN:
4151         case OFPACT_SET_IP_TTL:
4152         case OFPACT_SET_L4_SRC_PORT:
4153         case OFPACT_SET_L4_DST_PORT:
4154         case OFPACT_SET_QUEUE:
4155         case OFPACT_POP_QUEUE:
4156         case OFPACT_PUSH_MPLS:
4157         case OFPACT_POP_MPLS:
4158         case OFPACT_SET_MPLS_LABEL:
4159         case OFPACT_SET_MPLS_TC:
4160         case OFPACT_SET_MPLS_TTL:
4161         case OFPACT_MULTIPATH:
4162         case OFPACT_BUNDLE:
4163         case OFPACT_EXIT:
4164         case OFPACT_UNROLL_XLATE:
4165         case OFPACT_FIN_TIMEOUT:
4166         case OFPACT_CLEAR_ACTIONS:
4167         case OFPACT_WRITE_ACTIONS:
4168         case OFPACT_METER:
4169         case OFPACT_SAMPLE:
4170         case OFPACT_DEBUG_RECIRC:
4171         case OFPACT_CT:
4172         case OFPACT_NAT:
4173             break;
4174
4175             /* These need not be copied for restoration. */
4176         case OFPACT_NOTE:
4177         case OFPACT_CONJUNCTION:
4178             continue;
4179         }
4180         /* Copy the action over. */
4181         ofpbuf_put(&ctx->action_set, a, OFPACT_ALIGN(a->len));
4182     }
4183 }
4184
4185 #define CHECK_MPLS_RECIRCULATION()      \
4186     if (ctx->was_mpls) {                \
4187         ctx_trigger_recirculation(ctx); \
4188         break;                          \
4189     }
4190 #define CHECK_MPLS_RECIRCULATION_IF(COND) \
4191     if (COND) {                           \
4192         CHECK_MPLS_RECIRCULATION();       \
4193     }
4194
4195 static void
4196 put_ct_mark(const struct flow *flow, struct flow *base_flow,
4197             struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4198 {
4199     struct {
4200         uint32_t key;
4201         uint32_t mask;
4202     } odp_attr;
4203
4204     odp_attr.key = flow->ct_mark;
4205     odp_attr.mask = wc->masks.ct_mark;
4206
4207     if (odp_attr.mask && odp_attr.key != base_flow->ct_mark) {
4208         nl_msg_put_unspec(odp_actions, OVS_CT_ATTR_MARK, &odp_attr,
4209                           sizeof(odp_attr));
4210     }
4211 }
4212
4213 static void
4214 put_ct_label(const struct flow *flow, struct flow *base_flow,
4215              struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4216 {
4217     if (!ovs_u128_is_zero(&wc->masks.ct_label)
4218         && !ovs_u128_equals(&flow->ct_label, &base_flow->ct_label)) {
4219         struct {
4220             ovs_u128 key;
4221             ovs_u128 mask;
4222         } *odp_ct_label;
4223
4224         odp_ct_label = nl_msg_put_unspec_uninit(odp_actions,
4225                                                 OVS_CT_ATTR_LABELS,
4226                                                 sizeof(*odp_ct_label));
4227         odp_ct_label->key = flow->ct_label;
4228         odp_ct_label->mask = wc->masks.ct_label;
4229     }
4230 }
4231
4232 static void
4233 put_ct_helper(struct ofpbuf *odp_actions, struct ofpact_conntrack *ofc)
4234 {
4235     if (ofc->alg) {
4236         if (ofc->alg == IPPORT_FTP) {
4237             nl_msg_put_string(odp_actions, OVS_CT_ATTR_HELPER, "ftp");
4238         } else {
4239             VLOG_WARN("Cannot serialize ct_helper %d\n", ofc->alg);
4240         }
4241     }
4242 }
4243
4244 static void
4245 put_ct_nat(struct xlate_ctx *ctx)
4246 {
4247     struct ofpact_nat *ofn = ctx->ct_nat_action;
4248     size_t nat_offset;
4249
4250     if (!ofn) {
4251         return;
4252     }
4253
4254     nat_offset = nl_msg_start_nested(ctx->odp_actions, OVS_CT_ATTR_NAT);
4255     if (ofn->flags & NX_NAT_F_SRC || ofn->flags & NX_NAT_F_DST) {
4256         nl_msg_put_flag(ctx->odp_actions, ofn->flags & NX_NAT_F_SRC
4257                         ? OVS_NAT_ATTR_SRC : OVS_NAT_ATTR_DST);
4258         if (ofn->flags & NX_NAT_F_PERSISTENT) {
4259             nl_msg_put_flag(ctx->odp_actions, OVS_NAT_ATTR_PERSISTENT);
4260         }
4261         if (ofn->flags & NX_NAT_F_PROTO_HASH) {
4262             nl_msg_put_flag(ctx->odp_actions, OVS_NAT_ATTR_PROTO_HASH);
4263         } else if (ofn->flags & NX_NAT_F_PROTO_RANDOM) {
4264             nl_msg_put_flag(ctx->odp_actions, OVS_NAT_ATTR_PROTO_RANDOM);
4265         }
4266         if (ofn->range_af == AF_INET) {
4267             nl_msg_put_be32(ctx->odp_actions, OVS_NAT_ATTR_IP_MIN,
4268                            ofn->range.addr.ipv4.min);
4269             if (ofn->range.addr.ipv4.max &&
4270                 (ntohl(ofn->range.addr.ipv4.max)
4271                  > ntohl(ofn->range.addr.ipv4.min))) {
4272                 nl_msg_put_be32(ctx->odp_actions, OVS_NAT_ATTR_IP_MAX,
4273                                 ofn->range.addr.ipv4.max);
4274             }
4275         } else if (ofn->range_af == AF_INET6) {
4276             nl_msg_put_unspec(ctx->odp_actions, OVS_NAT_ATTR_IP_MIN,
4277                               &ofn->range.addr.ipv6.min,
4278                               sizeof ofn->range.addr.ipv6.min);
4279             if (!ipv6_mask_is_any(&ofn->range.addr.ipv6.max) &&
4280                 memcmp(&ofn->range.addr.ipv6.max, &ofn->range.addr.ipv6.min,
4281                        sizeof ofn->range.addr.ipv6.max) > 0) {
4282                 nl_msg_put_unspec(ctx->odp_actions, OVS_NAT_ATTR_IP_MAX,
4283                                   &ofn->range.addr.ipv6.max,
4284                                   sizeof ofn->range.addr.ipv6.max);
4285             }
4286         }
4287         if (ofn->range_af != AF_UNSPEC && ofn->range.proto.min) {
4288             nl_msg_put_u16(ctx->odp_actions, OVS_NAT_ATTR_PROTO_MIN,
4289                            ofn->range.proto.min);
4290             if (ofn->range.proto.max &&
4291                 ofn->range.proto.max > ofn->range.proto.min) {
4292                 nl_msg_put_u16(ctx->odp_actions, OVS_NAT_ATTR_PROTO_MAX,
4293                                ofn->range.proto.max);
4294             }
4295         }
4296     }
4297     nl_msg_end_nested(ctx->odp_actions, nat_offset);
4298 }
4299
4300 static void
4301 compose_conntrack_action(struct xlate_ctx *ctx, struct ofpact_conntrack *ofc)
4302 {
4303     ovs_u128 old_ct_label = ctx->base_flow.ct_label;
4304     uint32_t old_ct_mark = ctx->base_flow.ct_mark;
4305     size_t ct_offset;
4306     uint16_t zone;
4307
4308     /* Ensure that any prior actions are applied before composing the new
4309      * conntrack action. */
4310     xlate_commit_actions(ctx);
4311
4312     /* Process nested actions first, to populate the key. */
4313     ctx->ct_nat_action = NULL;
4314     do_xlate_actions(ofc->actions, ofpact_ct_get_action_len(ofc), ctx);
4315
4316     if (ofc->zone_src.field) {
4317         zone = mf_get_subfield(&ofc->zone_src, &ctx->xin->flow);
4318     } else {
4319         zone = ofc->zone_imm;
4320     }
4321
4322     ct_offset = nl_msg_start_nested(ctx->odp_actions, OVS_ACTION_ATTR_CT);
4323     if (ofc->flags & NX_CT_F_COMMIT) {
4324         nl_msg_put_flag(ctx->odp_actions, OVS_CT_ATTR_COMMIT);
4325     }
4326     nl_msg_put_u16(ctx->odp_actions, OVS_CT_ATTR_ZONE, zone);
4327     put_ct_mark(&ctx->xin->flow, &ctx->base_flow, ctx->odp_actions, ctx->wc);
4328     put_ct_label(&ctx->xin->flow, &ctx->base_flow, ctx->odp_actions, ctx->wc);
4329     put_ct_helper(ctx->odp_actions, ofc);
4330     put_ct_nat(ctx);
4331     ctx->ct_nat_action = NULL;
4332     nl_msg_end_nested(ctx->odp_actions, ct_offset);
4333
4334     /* Restore the original ct fields in the key. These should only be exposed
4335      * after recirculation to another table. */
4336     ctx->base_flow.ct_mark = old_ct_mark;
4337     ctx->base_flow.ct_label = old_ct_label;
4338
4339     if (ofc->recirc_table == NX_CT_RECIRC_NONE) {
4340         /* If we do not recirculate as part of this action, hide the results of
4341          * connection tracking from subsequent recirculations. */
4342         ctx->conntracked = false;
4343     } else {
4344         /* Use ct_* fields from datapath during recirculation upcall. */
4345         ctx->conntracked = true;
4346         compose_recirculate_and_fork(ctx, ofc->recirc_table);
4347     }
4348 }
4349
4350 static void
4351 do_xlate_actions(const struct ofpact *ofpacts, size_t ofpacts_len,
4352                  struct xlate_ctx *ctx)
4353 {
4354     struct flow_wildcards *wc = ctx->wc;
4355     struct flow *flow = &ctx->xin->flow;
4356     const struct ofpact *a;
4357
4358     if (ovs_native_tunneling_is_on(ctx->xbridge->ofproto)) {
4359         tnl_neigh_snoop(flow, wc, ctx->xbridge->name);
4360     }
4361     /* dl_type already in the mask, not set below. */
4362
4363     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
4364         struct ofpact_controller *controller;
4365         const struct ofpact_metadata *metadata;
4366         const struct ofpact_set_field *set_field;
4367         const struct mf_field *mf;
4368
4369         if (ctx->error) {
4370             break;
4371         }
4372
4373         if (ctx->exit) {
4374             /* Check if need to store the remaining actions for later
4375              * execution. */
4376             if (exit_recirculates(ctx)) {
4377                 recirc_unroll_actions(a, OFPACT_ALIGN(ofpacts_len -
4378                                                       ((uint8_t *)a -
4379                                                        (uint8_t *)ofpacts)),
4380                                       ctx);
4381             }
4382             break;
4383         }
4384
4385         switch (a->type) {
4386         case OFPACT_OUTPUT:
4387             xlate_output_action(ctx, ofpact_get_OUTPUT(a)->port,
4388                                 ofpact_get_OUTPUT(a)->max_len, true);
4389             break;
4390
4391         case OFPACT_GROUP:
4392             if (xlate_group_action(ctx, ofpact_get_GROUP(a)->group_id)) {
4393                 /* Group could not be found. */
4394                 return;
4395             }
4396             break;
4397
4398         case OFPACT_CONTROLLER:
4399             controller = ofpact_get_CONTROLLER(a);
4400             execute_controller_action(ctx, controller->max_len,
4401                                       controller->reason,
4402                                       controller->controller_id);
4403             break;
4404
4405         case OFPACT_ENQUEUE:
4406             memset(&wc->masks.skb_priority, 0xff,
4407                    sizeof wc->masks.skb_priority);
4408             xlate_enqueue_action(ctx, ofpact_get_ENQUEUE(a));
4409             break;
4410
4411         case OFPACT_SET_VLAN_VID:
4412             wc->masks.vlan_tci |= htons(VLAN_VID_MASK | VLAN_CFI);
4413             if (flow->vlan_tci & htons(VLAN_CFI) ||
4414                 ofpact_get_SET_VLAN_VID(a)->push_vlan_if_needed) {
4415                 flow->vlan_tci &= ~htons(VLAN_VID_MASK);
4416                 flow->vlan_tci |= (htons(ofpact_get_SET_VLAN_VID(a)->vlan_vid)
4417                                    | htons(VLAN_CFI));
4418             }
4419             break;
4420
4421         case OFPACT_SET_VLAN_PCP:
4422             wc->masks.vlan_tci |= htons(VLAN_PCP_MASK | VLAN_CFI);
4423             if (flow->vlan_tci & htons(VLAN_CFI) ||
4424                 ofpact_get_SET_VLAN_PCP(a)->push_vlan_if_needed) {
4425                 flow->vlan_tci &= ~htons(VLAN_PCP_MASK);
4426                 flow->vlan_tci |= htons((ofpact_get_SET_VLAN_PCP(a)->vlan_pcp
4427                                          << VLAN_PCP_SHIFT) | VLAN_CFI);
4428             }
4429             break;
4430
4431         case OFPACT_STRIP_VLAN:
4432             memset(&wc->masks.vlan_tci, 0xff, sizeof wc->masks.vlan_tci);
4433             flow->vlan_tci = htons(0);
4434             break;
4435
4436         case OFPACT_PUSH_VLAN:
4437             /* XXX 802.1AD(QinQ) */
4438             memset(&wc->masks.vlan_tci, 0xff, sizeof wc->masks.vlan_tci);
4439             flow->vlan_tci = htons(VLAN_CFI);
4440             break;
4441
4442         case OFPACT_SET_ETH_SRC:
4443             WC_MASK_FIELD(wc, dl_src);
4444             flow->dl_src = ofpact_get_SET_ETH_SRC(a)->mac;
4445             break;
4446
4447         case OFPACT_SET_ETH_DST:
4448             WC_MASK_FIELD(wc, dl_dst);
4449             flow->dl_dst = ofpact_get_SET_ETH_DST(a)->mac;
4450             break;
4451
4452         case OFPACT_SET_IPV4_SRC:
4453             CHECK_MPLS_RECIRCULATION();
4454             if (flow->dl_type == htons(ETH_TYPE_IP)) {
4455                 memset(&wc->masks.nw_src, 0xff, sizeof wc->masks.nw_src);
4456                 flow->nw_src = ofpact_get_SET_IPV4_SRC(a)->ipv4;
4457             }
4458             break;
4459
4460         case OFPACT_SET_IPV4_DST:
4461             CHECK_MPLS_RECIRCULATION();
4462             if (flow->dl_type == htons(ETH_TYPE_IP)) {
4463                 memset(&wc->masks.nw_dst, 0xff, sizeof wc->masks.nw_dst);
4464                 flow->nw_dst = ofpact_get_SET_IPV4_DST(a)->ipv4;
4465             }
4466             break;
4467
4468         case OFPACT_SET_IP_DSCP:
4469             CHECK_MPLS_RECIRCULATION();
4470             if (is_ip_any(flow)) {
4471                 wc->masks.nw_tos |= IP_DSCP_MASK;
4472                 flow->nw_tos &= ~IP_DSCP_MASK;
4473                 flow->nw_tos |= ofpact_get_SET_IP_DSCP(a)->dscp;
4474             }
4475             break;
4476
4477         case OFPACT_SET_IP_ECN:
4478             CHECK_MPLS_RECIRCULATION();
4479             if (is_ip_any(flow)) {
4480                 wc->masks.nw_tos |= IP_ECN_MASK;
4481                 flow->nw_tos &= ~IP_ECN_MASK;
4482                 flow->nw_tos |= ofpact_get_SET_IP_ECN(a)->ecn;
4483             }
4484             break;
4485
4486         case OFPACT_SET_IP_TTL:
4487             CHECK_MPLS_RECIRCULATION();
4488             if (is_ip_any(flow)) {
4489                 wc->masks.nw_ttl = 0xff;
4490                 flow->nw_ttl = ofpact_get_SET_IP_TTL(a)->ttl;
4491             }
4492             break;
4493
4494         case OFPACT_SET_L4_SRC_PORT:
4495             CHECK_MPLS_RECIRCULATION();
4496             if (is_ip_any(flow) && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4497                 memset(&wc->masks.nw_proto, 0xff, sizeof wc->masks.nw_proto);
4498                 memset(&wc->masks.tp_src, 0xff, sizeof wc->masks.tp_src);
4499                 flow->tp_src = htons(ofpact_get_SET_L4_SRC_PORT(a)->port);
4500             }
4501             break;
4502
4503         case OFPACT_SET_L4_DST_PORT:
4504             CHECK_MPLS_RECIRCULATION();
4505             if (is_ip_any(flow) && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4506                 memset(&wc->masks.nw_proto, 0xff, sizeof wc->masks.nw_proto);
4507                 memset(&wc->masks.tp_dst, 0xff, sizeof wc->masks.tp_dst);
4508                 flow->tp_dst = htons(ofpact_get_SET_L4_DST_PORT(a)->port);
4509             }
4510             break;
4511
4512         case OFPACT_RESUBMIT:
4513             xlate_ofpact_resubmit(ctx, ofpact_get_RESUBMIT(a));
4514             break;
4515
4516         case OFPACT_SET_TUNNEL:
4517             flow->tunnel.tun_id = htonll(ofpact_get_SET_TUNNEL(a)->tun_id);
4518             break;
4519
4520         case OFPACT_SET_QUEUE:
4521             memset(&wc->masks.skb_priority, 0xff,
4522                    sizeof wc->masks.skb_priority);
4523             xlate_set_queue_action(ctx, ofpact_get_SET_QUEUE(a)->queue_id);
4524             break;
4525
4526         case OFPACT_POP_QUEUE:
4527             memset(&wc->masks.skb_priority, 0xff,
4528                    sizeof wc->masks.skb_priority);
4529             flow->skb_priority = ctx->orig_skb_priority;
4530             break;
4531
4532         case OFPACT_REG_MOVE:
4533             CHECK_MPLS_RECIRCULATION_IF(
4534                 mf_is_l3_or_higher(ofpact_get_REG_MOVE(a)->dst.field) ||
4535                 mf_is_l3_or_higher(ofpact_get_REG_MOVE(a)->src.field));
4536             nxm_execute_reg_move(ofpact_get_REG_MOVE(a), flow, wc);
4537             break;
4538
4539         case OFPACT_SET_FIELD:
4540             CHECK_MPLS_RECIRCULATION_IF(
4541                 mf_is_l3_or_higher(ofpact_get_SET_FIELD(a)->field));
4542             set_field = ofpact_get_SET_FIELD(a);
4543             mf = set_field->field;
4544
4545             /* Set field action only ever overwrites packet's outermost
4546              * applicable header fields.  Do nothing if no header exists. */
4547             if (mf->id == MFF_VLAN_VID) {
4548                 wc->masks.vlan_tci |= htons(VLAN_CFI);
4549                 if (!(flow->vlan_tci & htons(VLAN_CFI))) {
4550                     break;
4551                 }
4552             } else if ((mf->id == MFF_MPLS_LABEL || mf->id == MFF_MPLS_TC)
4553                        /* 'dl_type' is already unwildcarded. */
4554                        && !eth_type_mpls(flow->dl_type)) {
4555                 break;
4556             }
4557             /* A flow may wildcard nw_frag.  Do nothing if setting a transport
4558              * header field on a packet that does not have them. */
4559             mf_mask_field_and_prereqs(mf, wc);
4560             if (mf_are_prereqs_ok(mf, flow)) {
4561                 mf_set_flow_value_masked(mf, &set_field->value,
4562                                          &set_field->mask, flow);
4563             }
4564             break;
4565
4566         case OFPACT_STACK_PUSH:
4567             CHECK_MPLS_RECIRCULATION_IF(
4568                 mf_is_l3_or_higher(ofpact_get_STACK_PUSH(a)->subfield.field));
4569             nxm_execute_stack_push(ofpact_get_STACK_PUSH(a), flow, wc,
4570                                    &ctx->stack);
4571             break;
4572
4573         case OFPACT_STACK_POP:
4574             CHECK_MPLS_RECIRCULATION_IF(
4575                 mf_is_l3_or_higher(ofpact_get_STACK_POP(a)->subfield.field));
4576             nxm_execute_stack_pop(ofpact_get_STACK_POP(a), flow, wc,
4577                                   &ctx->stack);
4578             break;
4579
4580         case OFPACT_PUSH_MPLS:
4581             /* Recirculate if it is an IP packet with a zero ttl.  This may
4582              * indicate that the packet was previously MPLS and an MPLS pop
4583              * action converted it to IP. In this case recirculating should
4584              * reveal the IP TTL which is used as the basis for a new MPLS
4585              * LSE. */
4586             CHECK_MPLS_RECIRCULATION_IF(
4587                 !flow_count_mpls_labels(flow, wc)
4588                 && flow->nw_ttl == 0
4589                 && is_ip_any(flow));
4590             compose_mpls_push_action(ctx, ofpact_get_PUSH_MPLS(a));
4591             break;
4592
4593         case OFPACT_POP_MPLS:
4594             CHECK_MPLS_RECIRCULATION();
4595             compose_mpls_pop_action(ctx, ofpact_get_POP_MPLS(a)->ethertype);
4596             break;
4597
4598         case OFPACT_SET_MPLS_LABEL:
4599             CHECK_MPLS_RECIRCULATION();
4600             compose_set_mpls_label_action(
4601                 ctx, ofpact_get_SET_MPLS_LABEL(a)->label);
4602             break;
4603
4604         case OFPACT_SET_MPLS_TC:
4605             CHECK_MPLS_RECIRCULATION();
4606             compose_set_mpls_tc_action(ctx, ofpact_get_SET_MPLS_TC(a)->tc);
4607             break;
4608
4609         case OFPACT_SET_MPLS_TTL:
4610             CHECK_MPLS_RECIRCULATION();
4611             compose_set_mpls_ttl_action(ctx, ofpact_get_SET_MPLS_TTL(a)->ttl);
4612             break;
4613
4614         case OFPACT_DEC_MPLS_TTL:
4615             CHECK_MPLS_RECIRCULATION();
4616             if (compose_dec_mpls_ttl_action(ctx)) {
4617                 return;
4618             }
4619             break;
4620
4621         case OFPACT_DEC_TTL:
4622             CHECK_MPLS_RECIRCULATION();
4623             wc->masks.nw_ttl = 0xff;
4624             if (compose_dec_ttl(ctx, ofpact_get_DEC_TTL(a))) {
4625                 return;
4626             }
4627             break;
4628
4629         case OFPACT_NOTE:
4630             /* Nothing to do. */
4631             break;
4632
4633         case OFPACT_MULTIPATH:
4634             CHECK_MPLS_RECIRCULATION();
4635             multipath_execute(ofpact_get_MULTIPATH(a), flow, wc);
4636             break;
4637
4638         case OFPACT_BUNDLE:
4639             CHECK_MPLS_RECIRCULATION();
4640             xlate_bundle_action(ctx, ofpact_get_BUNDLE(a));
4641             break;
4642
4643         case OFPACT_OUTPUT_REG:
4644             xlate_output_reg_action(ctx, ofpact_get_OUTPUT_REG(a));
4645             break;
4646
4647         case OFPACT_LEARN:
4648             CHECK_MPLS_RECIRCULATION();
4649             xlate_learn_action(ctx, ofpact_get_LEARN(a));
4650             break;
4651
4652         case OFPACT_CONJUNCTION: {
4653             /* A flow with a "conjunction" action represents part of a special
4654              * kind of "set membership match".  Such a flow should not actually
4655              * get executed, but it could via, say, a "packet-out", even though
4656              * that wouldn't be useful.  Log it to help debugging. */
4657             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
4658             VLOG_INFO_RL(&rl, "executing no-op conjunction action");
4659             break;
4660         }
4661
4662         case OFPACT_EXIT:
4663             ctx->exit = true;
4664             break;
4665
4666         case OFPACT_UNROLL_XLATE: {
4667             struct ofpact_unroll_xlate *unroll = ofpact_get_UNROLL_XLATE(a);
4668
4669             /* Restore translation context data that was stored earlier. */
4670             ctx->table_id = unroll->rule_table_id;
4671             ctx->rule_cookie = unroll->rule_cookie;
4672             break;
4673         }
4674         case OFPACT_FIN_TIMEOUT:
4675             CHECK_MPLS_RECIRCULATION();
4676             memset(&wc->masks.nw_proto, 0xff, sizeof wc->masks.nw_proto);
4677             xlate_fin_timeout(ctx, ofpact_get_FIN_TIMEOUT(a));
4678             break;
4679
4680         case OFPACT_CLEAR_ACTIONS:
4681             ofpbuf_clear(&ctx->action_set);
4682             ctx->xin->flow.actset_output = OFPP_UNSET;
4683             ctx->action_set_has_group = false;
4684             break;
4685
4686         case OFPACT_WRITE_ACTIONS:
4687             xlate_write_actions(ctx, a);
4688             break;
4689
4690         case OFPACT_WRITE_METADATA:
4691             metadata = ofpact_get_WRITE_METADATA(a);
4692             flow->metadata &= ~metadata->mask;
4693             flow->metadata |= metadata->metadata & metadata->mask;
4694             break;
4695
4696         case OFPACT_METER:
4697             /* Not implemented yet. */
4698             break;
4699
4700         case OFPACT_GOTO_TABLE: {
4701             struct ofpact_goto_table *ogt = ofpact_get_GOTO_TABLE(a);
4702
4703             /* Allow ctx->table_id == TBL_INTERNAL, which will be greater
4704              * than ogt->table_id. This is to allow goto_table actions that
4705              * triggered recirculation: ctx->table_id will be TBL_INTERNAL
4706              * after recirculation. */
4707             ovs_assert(ctx->table_id == TBL_INTERNAL
4708                        || ctx->table_id < ogt->table_id);
4709             xlate_table_action(ctx, ctx->xin->flow.in_port.ofp_port,
4710                                ogt->table_id, true, true);
4711             break;
4712         }
4713
4714         case OFPACT_SAMPLE:
4715             xlate_sample_action(ctx, ofpact_get_SAMPLE(a));
4716             break;
4717
4718         case OFPACT_CT:
4719             CHECK_MPLS_RECIRCULATION();
4720             compose_conntrack_action(ctx, ofpact_get_CT(a));
4721             break;
4722
4723         case OFPACT_NAT:
4724             /* This will be processed by compose_conntrack_action(). */
4725             ctx->ct_nat_action = ofpact_get_NAT(a);
4726             break;
4727
4728         case OFPACT_DEBUG_RECIRC:
4729             ctx_trigger_recirculation(ctx);
4730             a = ofpact_next(a);
4731             break;
4732         }
4733
4734         /* Check if need to store this and the remaining actions for later
4735          * execution. */
4736         if (!ctx->error && ctx->exit && ctx_first_recirculation_action(ctx)) {
4737             recirc_unroll_actions(a, OFPACT_ALIGN(ofpacts_len -
4738                                                   ((uint8_t *)a -
4739                                                    (uint8_t *)ofpacts)),
4740                                   ctx);
4741             break;
4742         }
4743     }
4744 }
4745
4746 void
4747 xlate_in_init(struct xlate_in *xin, struct ofproto_dpif *ofproto,
4748               const struct flow *flow, ofp_port_t in_port,
4749               struct rule_dpif *rule, uint16_t tcp_flags,
4750               const struct dp_packet *packet, struct flow_wildcards *wc,
4751               struct ofpbuf *odp_actions)
4752 {
4753     xin->ofproto = ofproto;
4754     xin->flow = *flow;
4755     xin->flow.in_port.ofp_port = in_port;
4756     xin->flow.actset_output = OFPP_UNSET;
4757     xin->packet = packet;
4758     xin->may_learn = packet != NULL;
4759     xin->rule = rule;
4760     xin->xcache = NULL;
4761     xin->ofpacts = NULL;
4762     xin->ofpacts_len = 0;
4763     xin->tcp_flags = tcp_flags;
4764     xin->resubmit_hook = NULL;
4765     xin->report_hook = NULL;
4766     xin->resubmit_stats = NULL;
4767     xin->recurse = 0;
4768     xin->resubmits = 0;
4769     xin->wc = wc;
4770     xin->odp_actions = odp_actions;
4771
4772     /* Do recirc lookup. */
4773     xin->recirc = flow->recirc_id
4774         ? recirc_id_node_find(flow->recirc_id)
4775         : NULL;
4776 }
4777
4778 void
4779 xlate_out_uninit(struct xlate_out *xout)
4780 {
4781     if (xout) {
4782         recirc_refs_unref(&xout->recircs);
4783     }
4784 }
4785
4786 /* Translates the 'ofpacts_len' bytes of "struct ofpact"s starting at 'ofpacts'
4787  * into datapath actions, using 'ctx', and discards the datapath actions. */
4788 void
4789 xlate_actions_for_side_effects(struct xlate_in *xin)
4790 {
4791     struct xlate_out xout;
4792     enum xlate_error error;
4793
4794     error = xlate_actions(xin, &xout);
4795     if (error) {
4796         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4797
4798         VLOG_WARN_RL(&rl, "xlate_actions failed (%s)!", xlate_strerror(error));
4799     }
4800
4801     xlate_out_uninit(&xout);
4802 }
4803 \f
4804 static struct skb_priority_to_dscp *
4805 get_skb_priority(const struct xport *xport, uint32_t skb_priority)
4806 {
4807     struct skb_priority_to_dscp *pdscp;
4808     uint32_t hash;
4809
4810     hash = hash_int(skb_priority, 0);
4811     HMAP_FOR_EACH_IN_BUCKET (pdscp, hmap_node, hash, &xport->skb_priorities) {
4812         if (pdscp->skb_priority == skb_priority) {
4813             return pdscp;
4814         }
4815     }
4816     return NULL;
4817 }
4818
4819 static bool
4820 dscp_from_skb_priority(const struct xport *xport, uint32_t skb_priority,
4821                        uint8_t *dscp)
4822 {
4823     struct skb_priority_to_dscp *pdscp = get_skb_priority(xport, skb_priority);
4824     *dscp = pdscp ? pdscp->dscp : 0;
4825     return pdscp != NULL;
4826 }
4827
4828 static size_t
4829 count_skb_priorities(const struct xport *xport)
4830 {
4831     return hmap_count(&xport->skb_priorities);
4832 }
4833
4834 static void
4835 clear_skb_priorities(struct xport *xport)
4836 {
4837     struct skb_priority_to_dscp *pdscp, *next;
4838
4839     HMAP_FOR_EACH_SAFE (pdscp, next, hmap_node, &xport->skb_priorities) {
4840         hmap_remove(&xport->skb_priorities, &pdscp->hmap_node);
4841         free(pdscp);
4842     }
4843 }
4844
4845 static bool
4846 actions_output_to_local_port(const struct xlate_ctx *ctx)
4847 {
4848     odp_port_t local_odp_port = ofp_port_to_odp_port(ctx->xbridge, OFPP_LOCAL);
4849     const struct nlattr *a;
4850     unsigned int left;
4851
4852     NL_ATTR_FOR_EACH_UNSAFE (a, left, ctx->odp_actions->data,
4853                              ctx->odp_actions->size) {
4854         if (nl_attr_type(a) == OVS_ACTION_ATTR_OUTPUT
4855             && nl_attr_get_odp_port(a) == local_odp_port) {
4856             return true;
4857         }
4858     }
4859     return false;
4860 }
4861
4862 #if defined(__linux__)
4863 /* Returns the maximum number of packets that the Linux kernel is willing to
4864  * queue up internally to certain kinds of software-implemented ports, or the
4865  * default (and rarely modified) value if it cannot be determined. */
4866 static int
4867 netdev_max_backlog(void)
4868 {
4869     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
4870     static int max_backlog = 1000; /* The normal default value. */
4871
4872     if (ovsthread_once_start(&once)) {
4873         static const char filename[] = "/proc/sys/net/core/netdev_max_backlog";
4874         FILE *stream;
4875         int n;
4876
4877         stream = fopen(filename, "r");
4878         if (!stream) {
4879             VLOG_INFO("%s: open failed (%s)", filename, ovs_strerror(errno));
4880         } else {
4881             if (fscanf(stream, "%d", &n) != 1) {
4882                 VLOG_WARN("%s: read error", filename);
4883             } else if (n <= 100) {
4884                 VLOG_WARN("%s: unexpectedly small value %d", filename, n);
4885             } else {
4886                 max_backlog = n;
4887             }
4888             fclose(stream);
4889         }
4890         ovsthread_once_done(&once);
4891
4892         VLOG_DBG("%s: using %d max_backlog", filename, max_backlog);
4893     }
4894
4895     return max_backlog;
4896 }
4897
4898 /* Counts and returns the number of OVS_ACTION_ATTR_OUTPUT actions in
4899  * 'odp_actions'. */
4900 static int
4901 count_output_actions(const struct ofpbuf *odp_actions)
4902 {
4903     const struct nlattr *a;
4904     size_t left;
4905     int n = 0;
4906
4907     NL_ATTR_FOR_EACH_UNSAFE (a, left, odp_actions->data, odp_actions->size) {
4908         if (a->nla_type == OVS_ACTION_ATTR_OUTPUT) {
4909             n++;
4910         }
4911     }
4912     return n;
4913 }
4914 #endif /* defined(__linux__) */
4915
4916 /* Returns true if 'odp_actions' contains more output actions than the datapath
4917  * can reliably handle in one go.  On Linux, this is the value of the
4918  * net.core.netdev_max_backlog sysctl, which limits the maximum number of
4919  * packets that the kernel is willing to queue up for processing while the
4920  * datapath is processing a set of actions. */
4921 static bool
4922 too_many_output_actions(const struct ofpbuf *odp_actions OVS_UNUSED)
4923 {
4924 #ifdef __linux__
4925     return (odp_actions->size / NL_A_U32_SIZE > netdev_max_backlog()
4926             && count_output_actions(odp_actions) > netdev_max_backlog());
4927 #else
4928     /* OSes other than Linux might have similar limits, but we don't know how
4929      * to determine them.*/
4930     return false;
4931 #endif
4932 }
4933
4934 static void
4935 xlate_wc_init(struct xlate_ctx *ctx)
4936 {
4937     flow_wildcards_init_catchall(ctx->wc);
4938
4939     /* Some fields we consider to always be examined. */
4940     WC_MASK_FIELD(ctx->wc, in_port);
4941     WC_MASK_FIELD(ctx->wc, dl_type);
4942     if (is_ip_any(&ctx->xin->flow)) {
4943         WC_MASK_FIELD_MASK(ctx->wc, nw_frag, FLOW_NW_FRAG_MASK);
4944     }
4945
4946     if (ctx->xbridge->support.odp.recirc) {
4947         /* Always exactly match recirc_id when datapath supports
4948          * recirculation.  */
4949         WC_MASK_FIELD(ctx->wc, recirc_id);
4950     }
4951
4952     if (ctx->xbridge->netflow) {
4953         netflow_mask_wc(&ctx->xin->flow, ctx->wc);
4954     }
4955
4956     tnl_wc_init(&ctx->xin->flow, ctx->wc);
4957 }
4958
4959 static void
4960 xlate_wc_finish(struct xlate_ctx *ctx)
4961 {
4962     /* Clear the metadata and register wildcard masks, because we won't
4963      * use non-header fields as part of the cache. */
4964     flow_wildcards_clear_non_packet_fields(ctx->wc);
4965
4966     /* ICMPv4 and ICMPv6 have 8-bit "type" and "code" fields.  struct flow
4967      * uses the low 8 bits of the 16-bit tp_src and tp_dst members to
4968      * represent these fields.  The datapath interface, on the other hand,
4969      * represents them with just 8 bits each.  This means that if the high
4970      * 8 bits of the masks for these fields somehow become set, then they
4971      * will get chopped off by a round trip through the datapath, and
4972      * revalidation will spot that as an inconsistency and delete the flow.
4973      * Avoid the problem here by making sure that only the low 8 bits of
4974      * either field can be unwildcarded for ICMP.
4975      */
4976     if (is_icmpv4(&ctx->xin->flow) || is_icmpv6(&ctx->xin->flow)) {
4977         ctx->wc->masks.tp_src &= htons(UINT8_MAX);
4978         ctx->wc->masks.tp_dst &= htons(UINT8_MAX);
4979     }
4980     /* VLAN_TCI CFI bit must be matched if any of the TCI is matched. */
4981     if (ctx->wc->masks.vlan_tci) {
4982         ctx->wc->masks.vlan_tci |= htons(VLAN_CFI);
4983     }
4984 }
4985
4986 /* Translates the flow, actions, or rule in 'xin' into datapath actions in
4987  * 'xout'.
4988  * The caller must take responsibility for eventually freeing 'xout', with
4989  * xlate_out_uninit().
4990  * Returns 'XLATE_OK' if translation was successful.  In case of an error an
4991  * empty set of actions will be returned in 'xin->odp_actions' (if non-NULL),
4992  * so that most callers may ignore the return value and transparently install a
4993  * drop flow when the translation fails. */
4994 enum xlate_error
4995 xlate_actions(struct xlate_in *xin, struct xlate_out *xout)
4996 {
4997     *xout = (struct xlate_out) {
4998         .slow = 0,
4999         .fail_open = false,
5000         .recircs = RECIRC_REFS_EMPTY_INITIALIZER,
5001     };
5002
5003     struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
5004     struct xbridge *xbridge = xbridge_lookup(xcfg, xin->ofproto);
5005     if (!xbridge) {
5006         return XLATE_BRIDGE_NOT_FOUND;
5007     }
5008
5009     struct flow *flow = &xin->flow;
5010
5011     union mf_subvalue stack_stub[1024 / sizeof(union mf_subvalue)];
5012     uint64_t action_set_stub[1024 / 8];
5013     struct flow_wildcards scratch_wc;
5014     uint64_t actions_stub[256 / 8];
5015     struct ofpbuf scratch_actions = OFPBUF_STUB_INITIALIZER(actions_stub);
5016     struct xlate_ctx ctx = {
5017         .xin = xin,
5018         .xout = xout,
5019         .base_flow = *flow,
5020         .xbridge = xbridge,
5021         .stack = OFPBUF_STUB_INITIALIZER(stack_stub),
5022         .rule = xin->rule,
5023         .wc = xin->wc ? xin->wc : &scratch_wc,
5024         .odp_actions = xin->odp_actions ? xin->odp_actions : &scratch_actions,
5025
5026         .recurse = xin->recurse,
5027         .resubmits = xin->resubmits,
5028         .in_group = false,
5029         .in_action_set = false,
5030
5031         .table_id = 0,
5032         .rule_cookie = OVS_BE64_MAX,
5033         .orig_skb_priority = flow->skb_priority,
5034         .sflow_n_outputs = 0,
5035         .sflow_odp_port = 0,
5036         .nf_output_iface = NF_OUT_DROP,
5037         .exit = false,
5038         .error = XLATE_OK,
5039         .mirrors = 0,
5040
5041         .recirc_action_offset = -1,
5042         .last_unroll_offset = -1,
5043
5044         .was_mpls = false,
5045         .conntracked = false,
5046
5047         .ct_nat_action = NULL,
5048
5049         .action_set_has_group = false,
5050         .action_set = OFPBUF_STUB_INITIALIZER(action_set_stub),
5051     };
5052     in6_addr_set_mapped_ipv4(&ctx.orig_tunnel_ipv6_dst, flow->tunnel.ip_dst);
5053
5054     /* 'base_flow' reflects the packet as it came in, but we need it to reflect
5055      * the packet as the datapath will treat it for output actions:
5056      *
5057      *     - Our datapath doesn't retain tunneling information without us
5058      *       re-setting it, so clear the tunnel data.
5059      *
5060      *     - For VLAN splinters, a higher layer may pretend that the packet
5061      *       came in on 'flow->in_port.ofp_port' with 'flow->vlan_tci'
5062      *       attached, because that's how we want to treat it from an OpenFlow
5063      *       perspective.  But from the datapath's perspective it actually came
5064      *       in on a VLAN device without any VLAN attached.  So here we put the
5065      *       datapath's view of the VLAN information in 'base_flow' to ensure
5066      *       correct treatment.
5067      */
5068     memset(&ctx.base_flow.tunnel, 0, sizeof ctx.base_flow.tunnel);
5069     if (flow->in_port.ofp_port
5070         != vsp_realdev_to_vlandev(xbridge->ofproto,
5071                                   flow->in_port.ofp_port,
5072                                   flow->vlan_tci)) {
5073         ctx.base_flow.vlan_tci = 0;
5074     }
5075
5076     ofpbuf_reserve(ctx.odp_actions, NL_A_U32_SIZE);
5077     if (xin->wc) {
5078         xlate_wc_init(&ctx);
5079     }
5080
5081     COVERAGE_INC(xlate_actions);
5082
5083     if (xin->recirc) {
5084         const struct recirc_state *state = &xin->recirc->state;
5085
5086         xlate_report(&ctx, "Restoring state post-recirculation:");
5087
5088         if (xin->ofpacts_len > 0 || ctx.rule) {
5089             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
5090             const char *conflict = xin->ofpacts_len ? "actions" : "rule";
5091
5092             VLOG_WARN_RL(&rl, "Recirculation conflict (%s)!", conflict);
5093             xlate_report(&ctx, "- Recirculation conflict (%s)!", conflict);
5094             ctx.error = XLATE_RECIRCULATION_CONFLICT;
5095             goto exit;
5096         }
5097
5098         /* Set the bridge for post-recirculation processing if needed. */
5099         if (ctx.xbridge->ofproto != state->ofproto) {
5100             struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
5101             const struct xbridge *new_bridge
5102                 = xbridge_lookup(xcfg, state->ofproto);
5103
5104             if (OVS_UNLIKELY(!new_bridge)) {
5105                 /* Drop the packet if the bridge cannot be found. */
5106                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
5107                 VLOG_WARN_RL(&rl, "Recirculation bridge no longer exists.");
5108                 xlate_report(&ctx, "- Recirculation bridge no longer exists.");
5109                 ctx.error = XLATE_BRIDGE_NOT_FOUND;
5110                 goto exit;
5111             }
5112             ctx.xbridge = new_bridge;
5113         }
5114
5115         /* Set the post-recirculation table id.  Note: A table lookup is done
5116          * only if there are no post-recirculation actions. */
5117         ctx.table_id = state->table_id;
5118         xlate_report(&ctx, "- Resuming from table %"PRIu8, ctx.table_id);
5119
5120         if (!state->conntracked) {
5121             clear_conntrack(flow);
5122         }
5123
5124         /* Restore pipeline metadata. May change flow's in_port and other
5125          * metadata to the values that existed when recirculation was
5126          * triggered. */
5127         recirc_metadata_to_flow(&state->metadata, flow);
5128
5129         /* Restore stack, if any. */
5130         if (state->stack) {
5131             ofpbuf_put(&ctx.stack, state->stack->data, state->stack->size);
5132         }
5133
5134         /* Restore mirror state. */
5135         ctx.mirrors = state->mirrors;
5136
5137         /* Restore action set, if any. */
5138         if (state->action_set_len) {
5139             const struct ofpact *a;
5140
5141             xlate_report_actions(&ctx, "- Restoring action set",
5142                                  state->ofpacts, state->action_set_len);
5143
5144             ofpbuf_put(&ctx.action_set, state->ofpacts, state->action_set_len);
5145
5146             OFPACT_FOR_EACH(a, state->ofpacts, state->action_set_len) {
5147                 if (a->type == OFPACT_GROUP) {
5148                     ctx.action_set_has_group = true;
5149                     break;
5150                 }
5151             }
5152         }
5153
5154         /* Restore recirculation actions.  If there are no actions, processing
5155          * will start with a lookup in the table set above. */
5156         if (state->ofpacts_len > state->action_set_len) {
5157             xin->ofpacts_len = state->ofpacts_len - state->action_set_len;
5158             xin->ofpacts = state->ofpacts +
5159                 state->action_set_len / sizeof *state->ofpacts;
5160
5161             xlate_report_actions(&ctx, "- Restoring actions",
5162                                  xin->ofpacts, xin->ofpacts_len);
5163         }
5164     } else if (OVS_UNLIKELY(flow->recirc_id)) {
5165         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
5166
5167         VLOG_WARN_RL(&rl, "Recirculation context not found for ID %"PRIx32,
5168                      flow->recirc_id);
5169         ctx.error = XLATE_NO_RECIRCULATION_CONTEXT;
5170         goto exit;
5171     }
5172     /* The bridge is now known so obtain its table version. */
5173     ctx.tables_version = ofproto_dpif_get_tables_version(ctx.xbridge->ofproto);
5174
5175     if (!xin->ofpacts && !ctx.rule) {
5176         ctx.rule = rule_dpif_lookup_from_table(
5177             ctx.xbridge->ofproto, ctx.tables_version, flow, xin->wc,
5178             ctx.xin->resubmit_stats, &ctx.table_id,
5179             flow->in_port.ofp_port, true, true);
5180         if (ctx.xin->resubmit_stats) {
5181             rule_dpif_credit_stats(ctx.rule, ctx.xin->resubmit_stats);
5182         }
5183         if (ctx.xin->xcache) {
5184             struct xc_entry *entry;
5185
5186             entry = xlate_cache_add_entry(ctx.xin->xcache, XC_RULE);
5187             entry->u.rule = ctx.rule;
5188             rule_dpif_ref(ctx.rule);
5189         }
5190
5191         if (OVS_UNLIKELY(ctx.xin->resubmit_hook)) {
5192             ctx.xin->resubmit_hook(ctx.xin, ctx.rule, 0);
5193         }
5194     }
5195     xout->fail_open = ctx.rule && rule_dpif_is_fail_open(ctx.rule);
5196
5197     /* Get the proximate input port of the packet.  (If xin->recirc,
5198      * flow->in_port is the ultimate input port of the packet.) */
5199     struct xport *in_port = get_ofp_port(xbridge,
5200                                          ctx.base_flow.in_port.ofp_port);
5201
5202     /* Tunnel stats only for non-recirculated packets. */
5203     if (!xin->recirc && in_port && in_port->is_tunnel) {
5204         if (ctx.xin->resubmit_stats) {
5205             netdev_vport_inc_rx(in_port->netdev, ctx.xin->resubmit_stats);
5206             if (in_port->bfd) {
5207                 bfd_account_rx(in_port->bfd, ctx.xin->resubmit_stats);
5208             }
5209         }
5210         if (ctx.xin->xcache) {
5211             struct xc_entry *entry;
5212
5213             entry = xlate_cache_add_entry(ctx.xin->xcache, XC_NETDEV);
5214             entry->u.dev.rx = netdev_ref(in_port->netdev);
5215             entry->u.dev.bfd = bfd_ref(in_port->bfd);
5216         }
5217     }
5218
5219     if (!xin->recirc && process_special(&ctx, in_port)) {
5220         /* process_special() did all the processing for this packet.
5221          *
5222          * We do not perform special processing on recirculated packets, as
5223          * recirculated packets are not really received by the bridge.*/
5224     } else if (in_port && in_port->xbundle
5225                && xbundle_mirror_out(xbridge, in_port->xbundle)) {
5226         if (ctx.xin->packet != NULL) {
5227             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5228             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
5229                          "%s, which is reserved exclusively for mirroring",
5230                          ctx.xbridge->name, in_port->xbundle->name);
5231         }
5232     } else {
5233         /* Sampling is done only for packets really received by the bridge. */
5234         unsigned int user_cookie_offset = 0;
5235         if (!xin->recirc) {
5236             user_cookie_offset = compose_sflow_action(&ctx);
5237             compose_ipfix_action(&ctx, ODPP_NONE);
5238         }
5239         size_t sample_actions_len = ctx.odp_actions->size;
5240
5241         if (tnl_process_ecn(flow)
5242             && (!in_port || may_receive(in_port, &ctx))) {
5243             const struct ofpact *ofpacts;
5244             size_t ofpacts_len;
5245
5246             if (xin->ofpacts) {
5247                 ofpacts = xin->ofpacts;
5248                 ofpacts_len = xin->ofpacts_len;
5249             } else if (ctx.rule) {
5250                 const struct rule_actions *actions
5251                     = rule_dpif_get_actions(ctx.rule);
5252                 ofpacts = actions->ofpacts;
5253                 ofpacts_len = actions->ofpacts_len;
5254                 ctx.rule_cookie = rule_dpif_get_flow_cookie(ctx.rule);
5255             } else {
5256                 OVS_NOT_REACHED();
5257             }
5258
5259             mirror_ingress_packet(&ctx);
5260             do_xlate_actions(ofpacts, ofpacts_len, &ctx);
5261             if (ctx.error) {
5262                 goto exit;
5263             }
5264
5265             /* We've let OFPP_NORMAL and the learning action look at the
5266              * packet, so drop it now if forwarding is disabled. */
5267             if (in_port && (!xport_stp_forward_state(in_port) ||
5268                             !xport_rstp_forward_state(in_port))) {
5269                 /* Drop all actions added by do_xlate_actions() above. */
5270                 ctx.odp_actions->size = sample_actions_len;
5271
5272                 /* Undo changes that may have been done for recirculation. */
5273                 if (exit_recirculates(&ctx)) {
5274                     ctx.action_set.size = ctx.recirc_action_offset;
5275                     ctx.recirc_action_offset = -1;
5276                     ctx.last_unroll_offset = -1;
5277                 }
5278             } else if (ctx.action_set.size) {
5279                 /* Translate action set only if not dropping the packet and
5280                  * not recirculating. */
5281                 if (!exit_recirculates(&ctx)) {
5282                     xlate_action_set(&ctx);
5283                 }
5284             }
5285             /* Check if need to recirculate. */
5286             if (exit_recirculates(&ctx)) {
5287                 compose_recirculate_action(&ctx);
5288             }
5289         }
5290
5291         /* Output only fully processed packets. */
5292         if (!exit_recirculates(&ctx)
5293             && xbridge->has_in_band
5294             && in_band_must_output_to_local_port(flow)
5295             && !actions_output_to_local_port(&ctx)) {
5296             compose_output_action(&ctx, OFPP_LOCAL, NULL);
5297         }
5298
5299         if (user_cookie_offset) {
5300             fix_sflow_action(&ctx, user_cookie_offset);
5301         }
5302     }
5303
5304     if (nl_attr_oversized(ctx.odp_actions->size)) {
5305         /* These datapath actions are too big for a Netlink attribute, so we
5306          * can't hand them to the kernel directly.  dpif_execute() can execute
5307          * them one by one with help, so just mark the result as SLOW_ACTION to
5308          * prevent the flow from being installed. */
5309         COVERAGE_INC(xlate_actions_oversize);
5310         ctx.xout->slow |= SLOW_ACTION;
5311     } else if (too_many_output_actions(ctx.odp_actions)) {
5312         COVERAGE_INC(xlate_actions_too_many_output);
5313         ctx.xout->slow |= SLOW_ACTION;
5314     }
5315
5316     /* Do netflow only for packets really received by the bridge and not sent
5317      * to the controller.  We consider packets sent to the controller to be
5318      * part of the control plane rather than the data plane. */
5319     if (!xin->recirc && xbridge->netflow && !(xout->slow & SLOW_CONTROLLER)) {
5320         if (ctx.xin->resubmit_stats) {
5321             netflow_flow_update(xbridge->netflow, flow,
5322                                 ctx.nf_output_iface,
5323                                 ctx.xin->resubmit_stats);
5324         }
5325         if (ctx.xin->xcache) {
5326             struct xc_entry *entry;
5327
5328             entry = xlate_cache_add_entry(ctx.xin->xcache, XC_NETFLOW);
5329             entry->u.nf.netflow = netflow_ref(xbridge->netflow);
5330             entry->u.nf.flow = xmemdup(flow, sizeof *flow);
5331             entry->u.nf.iface = ctx.nf_output_iface;
5332         }
5333     }
5334
5335     if (xin->wc) {
5336         xlate_wc_finish(&ctx);
5337     }
5338
5339 exit:
5340     ofpbuf_uninit(&ctx.stack);
5341     ofpbuf_uninit(&ctx.action_set);
5342     ofpbuf_uninit(&scratch_actions);
5343
5344     /* Make sure we return a "drop flow" in case of an error. */
5345     if (ctx.error) {
5346         xout->slow = 0;
5347         if (xin->odp_actions) {
5348             ofpbuf_clear(xin->odp_actions);
5349         }
5350     }
5351     return ctx.error;
5352 }
5353
5354 /* Sends 'packet' out 'ofport'.
5355  * May modify 'packet'.
5356  * Returns 0 if successful, otherwise a positive errno value. */
5357 int
5358 xlate_send_packet(const struct ofport_dpif *ofport, struct dp_packet *packet)
5359 {
5360     struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
5361     struct xport *xport;
5362     struct ofpact_output output;
5363     struct flow flow;
5364
5365     ofpact_init(&output.ofpact, OFPACT_OUTPUT, sizeof output);
5366     /* Use OFPP_NONE as the in_port to avoid special packet processing. */
5367     flow_extract(packet, &flow);
5368     flow.in_port.ofp_port = OFPP_NONE;
5369
5370     xport = xport_lookup(xcfg, ofport);
5371     if (!xport) {
5372         return EINVAL;
5373     }
5374     output.port = xport->ofp_port;
5375     output.max_len = 0;
5376
5377     return ofproto_dpif_execute_actions(xport->xbridge->ofproto, &flow, NULL,
5378                                         &output.ofpact, sizeof output,
5379                                         packet);
5380 }
5381
5382 struct xlate_cache *
5383 xlate_cache_new(void)
5384 {
5385     struct xlate_cache *xcache = xmalloc(sizeof *xcache);
5386
5387     ofpbuf_init(&xcache->entries, 512);
5388     return xcache;
5389 }
5390
5391 static struct xc_entry *
5392 xlate_cache_add_entry(struct xlate_cache *xcache, enum xc_type type)
5393 {
5394     struct xc_entry *entry;
5395
5396     entry = ofpbuf_put_zeros(&xcache->entries, sizeof *entry);
5397     entry->type = type;
5398
5399     return entry;
5400 }
5401
5402 static void
5403 xlate_cache_netdev(struct xc_entry *entry, const struct dpif_flow_stats *stats)
5404 {
5405     if (entry->u.dev.tx) {
5406         netdev_vport_inc_tx(entry->u.dev.tx, stats);
5407     }
5408     if (entry->u.dev.rx) {
5409         netdev_vport_inc_rx(entry->u.dev.rx, stats);
5410     }
5411     if (entry->u.dev.bfd) {
5412         bfd_account_rx(entry->u.dev.bfd, stats);
5413     }
5414 }
5415
5416 static void
5417 xlate_cache_normal(struct ofproto_dpif *ofproto, struct flow *flow, int vlan)
5418 {
5419     struct xlate_cfg *xcfg = ovsrcu_get(struct xlate_cfg *, &xcfgp);
5420     struct xbridge *xbridge;
5421     struct xbundle *xbundle;
5422     struct flow_wildcards wc;
5423
5424     xbridge = xbridge_lookup(xcfg, ofproto);
5425     if (!xbridge) {
5426         return;
5427     }
5428
5429     xbundle = lookup_input_bundle(xbridge, flow->in_port.ofp_port, false,
5430                                   NULL);
5431     if (!xbundle) {
5432         return;
5433     }
5434
5435     update_learning_table(xbridge, flow, &wc, vlan, xbundle);
5436 }
5437
5438 /* Push stats and perform side effects of flow translation. */
5439 void
5440 xlate_push_stats(struct xlate_cache *xcache,
5441                  const struct dpif_flow_stats *stats)
5442 {
5443     struct xc_entry *entry;
5444     struct ofpbuf entries = xcache->entries;
5445     struct eth_addr dmac;
5446
5447     if (!stats->n_packets) {
5448         return;
5449     }
5450
5451     XC_ENTRY_FOR_EACH (entry, entries, xcache) {
5452         switch (entry->type) {
5453         case XC_RULE:
5454             rule_dpif_credit_stats(entry->u.rule, stats);
5455             break;
5456         case XC_BOND:
5457             bond_account(entry->u.bond.bond, entry->u.bond.flow,
5458                          entry->u.bond.vid, stats->n_bytes);
5459             break;
5460         case XC_NETDEV:
5461             xlate_cache_netdev(entry, stats);
5462             break;
5463         case XC_NETFLOW:
5464             netflow_flow_update(entry->u.nf.netflow, entry->u.nf.flow,
5465                                 entry->u.nf.iface, stats);
5466             break;
5467         case XC_MIRROR:
5468             mirror_update_stats(entry->u.mirror.mbridge,
5469                                 entry->u.mirror.mirrors,
5470                                 stats->n_packets, stats->n_bytes);
5471             break;
5472         case XC_LEARN:
5473             ofproto_dpif_flow_mod(entry->u.learn.ofproto, entry->u.learn.fm);
5474             break;
5475         case XC_NORMAL:
5476             xlate_cache_normal(entry->u.normal.ofproto, entry->u.normal.flow,
5477                                entry->u.normal.vlan);
5478             break;
5479         case XC_FIN_TIMEOUT:
5480             xlate_fin_timeout__(entry->u.fin.rule, stats->tcp_flags,
5481                                 entry->u.fin.idle, entry->u.fin.hard);
5482             break;
5483         case XC_GROUP:
5484             group_dpif_credit_stats(entry->u.group.group, entry->u.group.bucket,
5485                                     stats);
5486             break;
5487         case XC_TNL_NEIGH:
5488             /* Lookup neighbor to avoid timeout. */
5489             tnl_neigh_lookup(entry->u.tnl_neigh_cache.br_name,
5490                              &entry->u.tnl_neigh_cache.d_ipv6, &dmac);
5491             break;
5492         default:
5493             OVS_NOT_REACHED();
5494         }
5495     }
5496 }
5497
5498 static void
5499 xlate_dev_unref(struct xc_entry *entry)
5500 {
5501     if (entry->u.dev.tx) {
5502         netdev_close(entry->u.dev.tx);
5503     }
5504     if (entry->u.dev.rx) {
5505         netdev_close(entry->u.dev.rx);
5506     }
5507     if (entry->u.dev.bfd) {
5508         bfd_unref(entry->u.dev.bfd);
5509     }
5510 }
5511
5512 static void
5513 xlate_cache_clear_netflow(struct netflow *netflow, struct flow *flow)
5514 {
5515     netflow_flow_clear(netflow, flow);
5516     netflow_unref(netflow);
5517     free(flow);
5518 }
5519
5520 void
5521 xlate_cache_clear(struct xlate_cache *xcache)
5522 {
5523     struct xc_entry *entry;
5524     struct ofpbuf entries;
5525
5526     if (!xcache) {
5527         return;
5528     }
5529
5530     XC_ENTRY_FOR_EACH (entry, entries, xcache) {
5531         switch (entry->type) {
5532         case XC_RULE:
5533             rule_dpif_unref(entry->u.rule);
5534             break;
5535         case XC_BOND:
5536             free(entry->u.bond.flow);
5537             bond_unref(entry->u.bond.bond);
5538             break;
5539         case XC_NETDEV:
5540             xlate_dev_unref(entry);
5541             break;
5542         case XC_NETFLOW:
5543             xlate_cache_clear_netflow(entry->u.nf.netflow, entry->u.nf.flow);
5544             break;
5545         case XC_MIRROR:
5546             mbridge_unref(entry->u.mirror.mbridge);
5547             break;
5548         case XC_LEARN:
5549             free(entry->u.learn.fm);
5550             ofpbuf_delete(entry->u.learn.ofpacts);
5551             break;
5552         case XC_NORMAL:
5553             free(entry->u.normal.flow);
5554             break;
5555         case XC_FIN_TIMEOUT:
5556             /* 'u.fin.rule' is always already held as a XC_RULE, which
5557              * has already released it's reference above. */
5558             break;
5559         case XC_GROUP:
5560             group_dpif_unref(entry->u.group.group);
5561             break;
5562         case XC_TNL_NEIGH:
5563             break;
5564         default:
5565             OVS_NOT_REACHED();
5566         }
5567     }
5568
5569     ofpbuf_clear(&xcache->entries);
5570 }
5571
5572 void
5573 xlate_cache_delete(struct xlate_cache *xcache)
5574 {
5575     xlate_cache_clear(xcache);
5576     ofpbuf_uninit(&xcache->entries);
5577     free(xcache);
5578 }