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