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