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