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