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