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