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