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