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