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