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