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