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