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