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