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