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