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