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