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