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