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