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