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