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