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