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