ofpbuf: Simplify ofpbuf API.
[cascardo/ovs.git] / lib / odp-util.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <arpa/inet.h>
19 #include "odp-util.h"
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <math.h>
23 #include <netinet/in.h>
24 #include <netinet/icmp6.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "byte-order.h"
29 #include "coverage.h"
30 #include "dpif.h"
31 #include "dynamic-string.h"
32 #include "flow.h"
33 #include "netlink.h"
34 #include "ofpbuf.h"
35 #include "packets.h"
36 #include "simap.h"
37 #include "timeval.h"
38 #include "unaligned.h"
39 #include "util.h"
40 #include "openvswitch/vlog.h"
41
42 VLOG_DEFINE_THIS_MODULE(odp_util);
43
44 /* The interface between userspace and kernel uses an "OVS_*" prefix.
45  * Since this is fairly non-specific for the OVS userspace components,
46  * "ODP_*" (Open vSwitch Datapath) is used as the prefix for
47  * interactions with the datapath.
48  */
49
50 /* The set of characters that may separate one action or one key attribute
51  * from another. */
52 static const char *delimiters = ", \t\r\n";
53
54 static int parse_odp_key_mask_attr(const char *, const struct simap *port_names,
55                               struct ofpbuf *, struct ofpbuf *);
56 static void format_odp_key_attr(const struct nlattr *a,
57                                 const struct nlattr *ma,
58                                 const struct hmap *portno_names, struct ds *ds,
59                                 bool verbose);
60
61 /* Returns one the following for the action with the given OVS_ACTION_ATTR_*
62  * 'type':
63  *
64  *   - For an action whose argument has a fixed length, returned that
65  *     nonnegative length in bytes.
66  *
67  *   - For an action with a variable-length argument, returns -2.
68  *
69  *   - For an invalid 'type', returns -1. */
70 static int
71 odp_action_len(uint16_t type)
72 {
73     if (type > OVS_ACTION_ATTR_MAX) {
74         return -1;
75     }
76
77     switch ((enum ovs_action_attr) type) {
78     case OVS_ACTION_ATTR_OUTPUT: return sizeof(uint32_t);
79     case OVS_ACTION_ATTR_TUNNEL_PUSH: return -2;
80     case OVS_ACTION_ATTR_TUNNEL_POP: return sizeof(uint32_t);
81     case OVS_ACTION_ATTR_USERSPACE: return -2;
82     case OVS_ACTION_ATTR_PUSH_VLAN: return sizeof(struct ovs_action_push_vlan);
83     case OVS_ACTION_ATTR_POP_VLAN: return 0;
84     case OVS_ACTION_ATTR_PUSH_MPLS: return sizeof(struct ovs_action_push_mpls);
85     case OVS_ACTION_ATTR_POP_MPLS: return sizeof(ovs_be16);
86     case OVS_ACTION_ATTR_RECIRC: return sizeof(uint32_t);
87     case OVS_ACTION_ATTR_HASH: return sizeof(struct ovs_action_hash);
88     case OVS_ACTION_ATTR_SET: return -2;
89     case OVS_ACTION_ATTR_SET_MASKED: return -2;
90     case OVS_ACTION_ATTR_SAMPLE: return -2;
91
92     case OVS_ACTION_ATTR_UNSPEC:
93     case __OVS_ACTION_ATTR_MAX:
94         return -1;
95     }
96
97     return -1;
98 }
99
100 /* Returns a string form of 'attr'.  The return value is either a statically
101  * allocated constant string or the 'bufsize'-byte buffer 'namebuf'.  'bufsize'
102  * should be at least OVS_KEY_ATTR_BUFSIZE. */
103 enum { OVS_KEY_ATTR_BUFSIZE = 3 + INT_STRLEN(unsigned int) + 1 };
104 static const char *
105 ovs_key_attr_to_string(enum ovs_key_attr attr, char *namebuf, size_t bufsize)
106 {
107     switch (attr) {
108     case OVS_KEY_ATTR_UNSPEC: return "unspec";
109     case OVS_KEY_ATTR_ENCAP: return "encap";
110     case OVS_KEY_ATTR_PRIORITY: return "skb_priority";
111     case OVS_KEY_ATTR_SKB_MARK: return "skb_mark";
112     case OVS_KEY_ATTR_TUNNEL: return "tunnel";
113     case OVS_KEY_ATTR_IN_PORT: return "in_port";
114     case OVS_KEY_ATTR_ETHERNET: return "eth";
115     case OVS_KEY_ATTR_VLAN: return "vlan";
116     case OVS_KEY_ATTR_ETHERTYPE: return "eth_type";
117     case OVS_KEY_ATTR_IPV4: return "ipv4";
118     case OVS_KEY_ATTR_IPV6: return "ipv6";
119     case OVS_KEY_ATTR_TCP: return "tcp";
120     case OVS_KEY_ATTR_TCP_FLAGS: return "tcp_flags";
121     case OVS_KEY_ATTR_UDP: return "udp";
122     case OVS_KEY_ATTR_SCTP: return "sctp";
123     case OVS_KEY_ATTR_ICMP: return "icmp";
124     case OVS_KEY_ATTR_ICMPV6: return "icmpv6";
125     case OVS_KEY_ATTR_ARP: return "arp";
126     case OVS_KEY_ATTR_ND: return "nd";
127     case OVS_KEY_ATTR_MPLS: return "mpls";
128     case OVS_KEY_ATTR_DP_HASH: return "dp_hash";
129     case OVS_KEY_ATTR_RECIRC_ID: return "recirc_id";
130
131     case __OVS_KEY_ATTR_MAX:
132     default:
133         snprintf(namebuf, bufsize, "key%u", (unsigned int) attr);
134         return namebuf;
135     }
136 }
137
138 static void
139 format_generic_odp_action(struct ds *ds, const struct nlattr *a)
140 {
141     size_t len = nl_attr_get_size(a);
142
143     ds_put_format(ds, "action%"PRId16, nl_attr_type(a));
144     if (len) {
145         const uint8_t *unspec;
146         unsigned int i;
147
148         unspec = nl_attr_get(a);
149         for (i = 0; i < len; i++) {
150             ds_put_char(ds, i ? ' ': '(');
151             ds_put_format(ds, "%02x", unspec[i]);
152         }
153         ds_put_char(ds, ')');
154     }
155 }
156
157 static void
158 format_odp_sample_action(struct ds *ds, const struct nlattr *attr)
159 {
160     static const struct nl_policy ovs_sample_policy[] = {
161         [OVS_SAMPLE_ATTR_PROBABILITY] = { .type = NL_A_U32 },
162         [OVS_SAMPLE_ATTR_ACTIONS] = { .type = NL_A_NESTED }
163     };
164     struct nlattr *a[ARRAY_SIZE(ovs_sample_policy)];
165     double percentage;
166     const struct nlattr *nla_acts;
167     int len;
168
169     ds_put_cstr(ds, "sample");
170
171     if (!nl_parse_nested(attr, ovs_sample_policy, a, ARRAY_SIZE(a))) {
172         ds_put_cstr(ds, "(error)");
173         return;
174     }
175
176     percentage = (100.0 * nl_attr_get_u32(a[OVS_SAMPLE_ATTR_PROBABILITY])) /
177                         UINT32_MAX;
178
179     ds_put_format(ds, "(sample=%.1f%%,", percentage);
180
181     ds_put_cstr(ds, "actions(");
182     nla_acts = nl_attr_get(a[OVS_SAMPLE_ATTR_ACTIONS]);
183     len = nl_attr_get_size(a[OVS_SAMPLE_ATTR_ACTIONS]);
184     format_odp_actions(ds, nla_acts, len);
185     ds_put_format(ds, "))");
186 }
187
188 static const char *
189 slow_path_reason_to_string(uint32_t reason)
190 {
191     switch ((enum slow_path_reason) reason) {
192 #define SPR(ENUM, STRING, EXPLANATION) case ENUM: return STRING;
193         SLOW_PATH_REASONS
194 #undef SPR
195     }
196
197     return NULL;
198 }
199
200 const char *
201 slow_path_reason_to_explanation(enum slow_path_reason reason)
202 {
203     switch (reason) {
204 #define SPR(ENUM, STRING, EXPLANATION) case ENUM: return EXPLANATION;
205         SLOW_PATH_REASONS
206 #undef SPR
207     }
208
209     return "<unknown>";
210 }
211
212 static int
213 parse_flags(const char *s, const char *(*bit_to_string)(uint32_t),
214             uint32_t *res_flags, uint32_t allowed, uint32_t *res_mask)
215 {
216     uint32_t result = 0;
217     int n;
218
219     /* Parse masked flags in numeric format? */
220     if (res_mask && ovs_scan(s, "%"SCNi32"/%"SCNi32"%n",
221                              res_flags, res_mask, &n) && n > 0) {
222         if (*res_flags & ~allowed || *res_mask & ~allowed) {
223             return -EINVAL;
224         }
225         return n;
226     }
227
228     n = 0;
229
230     if (res_mask && (*s == '+' || *s == '-')) {
231         uint32_t flags = 0, mask = 0;
232
233         /* Parse masked flags. */
234         while (s[n] != ')') {
235             bool set;
236             uint32_t bit;
237             int name_len;
238
239             if (s[n] == '+') {
240                 set = true;
241             } else if (s[n] == '-') {
242                 set = false;
243             } else {
244                 return -EINVAL;
245             }
246             n++;
247
248             name_len = strcspn(s + n, "+-)");
249
250             for (bit = 1; bit; bit <<= 1) {
251                 const char *fname = bit_to_string(bit);
252                 size_t len;
253
254                 if (!fname) {
255                     continue;
256                 }
257
258                 len = strlen(fname);
259                 if (len != name_len) {
260                     continue;
261                 }
262                 if (!strncmp(s + n, fname, len)) {
263                     if (mask & bit) {
264                         /* bit already set. */
265                         return -EINVAL;
266                     }
267                     if (!(bit & allowed)) {
268                         return -EINVAL;
269                     }
270                     if (set) {
271                         flags |= bit;
272                     }
273                     mask |= bit;
274                     break;
275                 }
276             }
277
278             if (!bit) {
279                 return -EINVAL; /* Unknown flag name */
280             }
281             s += name_len;
282         }
283
284         *res_flags = flags;
285         *res_mask = mask;
286         return n;
287     }
288
289     /* Parse unmasked flags.  If a flag is present, it is set, otherwise
290      * it is not set. */
291     while (s[n] != ')') {
292         unsigned long long int flags;
293         uint32_t bit;
294         int n0;
295
296         if (ovs_scan(&s[n], "%lli%n", &flags, &n0)) {
297             if (flags & ~allowed) {
298                 return -EINVAL;
299             }
300             n += n0 + (s[n + n0] == ',');
301             result |= flags;
302             continue;
303         }
304
305         for (bit = 1; bit; bit <<= 1) {
306             const char *name = bit_to_string(bit);
307             size_t len;
308
309             if (!name) {
310                 continue;
311             }
312
313             len = strlen(name);
314             if (!strncmp(s + n, name, len) &&
315                 (s[n + len] == ',' || s[n + len] == ')')) {
316                 if (!(bit & allowed)) {
317                     return -EINVAL;
318                 }
319                 result |= bit;
320                 n += len + (s[n + len] == ',');
321                 break;
322             }
323         }
324
325         if (!bit) {
326             return -EINVAL;
327         }
328     }
329
330     *res_flags = result;
331     if (res_mask) {
332         *res_mask = UINT32_MAX;
333     }
334     return n;
335 }
336
337 static void
338 format_odp_userspace_action(struct ds *ds, const struct nlattr *attr)
339 {
340     static const struct nl_policy ovs_userspace_policy[] = {
341         [OVS_USERSPACE_ATTR_PID] = { .type = NL_A_U32 },
342         [OVS_USERSPACE_ATTR_USERDATA] = { .type = NL_A_UNSPEC,
343                                           .optional = true },
344         [OVS_USERSPACE_ATTR_EGRESS_TUN_PORT] = { .type = NL_A_U32,
345                                                  .optional = true },
346     };
347     struct nlattr *a[ARRAY_SIZE(ovs_userspace_policy)];
348     const struct nlattr *userdata_attr;
349     const struct nlattr *tunnel_out_port_attr;
350
351     if (!nl_parse_nested(attr, ovs_userspace_policy, a, ARRAY_SIZE(a))) {
352         ds_put_cstr(ds, "userspace(error)");
353         return;
354     }
355
356     ds_put_format(ds, "userspace(pid=%"PRIu32,
357                   nl_attr_get_u32(a[OVS_USERSPACE_ATTR_PID]));
358
359     userdata_attr = a[OVS_USERSPACE_ATTR_USERDATA];
360
361     if (userdata_attr) {
362         const uint8_t *userdata = nl_attr_get(userdata_attr);
363         size_t userdata_len = nl_attr_get_size(userdata_attr);
364         bool userdata_unspec = true;
365         union user_action_cookie cookie;
366
367         if (userdata_len >= sizeof cookie.type
368             && userdata_len <= sizeof cookie) {
369
370             memset(&cookie, 0, sizeof cookie);
371             memcpy(&cookie, userdata, userdata_len);
372
373             userdata_unspec = false;
374
375             if (userdata_len == sizeof cookie.sflow
376                 && cookie.type == USER_ACTION_COOKIE_SFLOW) {
377                 ds_put_format(ds, ",sFlow("
378                               "vid=%"PRIu16",pcp=%"PRIu8",output=%"PRIu32")",
379                               vlan_tci_to_vid(cookie.sflow.vlan_tci),
380                               vlan_tci_to_pcp(cookie.sflow.vlan_tci),
381                               cookie.sflow.output);
382             } else if (userdata_len == sizeof cookie.slow_path
383                        && cookie.type == USER_ACTION_COOKIE_SLOW_PATH) {
384                 ds_put_cstr(ds, ",slow_path(");
385                 format_flags(ds, slow_path_reason_to_string,
386                              cookie.slow_path.reason, ',');
387                 ds_put_format(ds, ")");
388             } else if (userdata_len == sizeof cookie.flow_sample
389                        && cookie.type == USER_ACTION_COOKIE_FLOW_SAMPLE) {
390                 ds_put_format(ds, ",flow_sample(probability=%"PRIu16
391                               ",collector_set_id=%"PRIu32
392                               ",obs_domain_id=%"PRIu32
393                               ",obs_point_id=%"PRIu32")",
394                               cookie.flow_sample.probability,
395                               cookie.flow_sample.collector_set_id,
396                               cookie.flow_sample.obs_domain_id,
397                               cookie.flow_sample.obs_point_id);
398             } else if (userdata_len >= sizeof cookie.ipfix
399                        && cookie.type == USER_ACTION_COOKIE_IPFIX) {
400                 ds_put_format(ds, ",ipfix(output_port=%"PRIu32")",
401                               cookie.ipfix.output_odp_port);
402             } else {
403                 userdata_unspec = true;
404             }
405         }
406
407         if (userdata_unspec) {
408             size_t i;
409             ds_put_format(ds, ",userdata(");
410             for (i = 0; i < userdata_len; i++) {
411                 ds_put_format(ds, "%02x", userdata[i]);
412             }
413             ds_put_char(ds, ')');
414         }
415     }
416
417     tunnel_out_port_attr = a[OVS_USERSPACE_ATTR_EGRESS_TUN_PORT];
418     if (tunnel_out_port_attr) {
419         ds_put_format(ds, ",tunnel_out_port=%"PRIu32,
420                       nl_attr_get_u32(tunnel_out_port_attr));
421     }
422
423     ds_put_char(ds, ')');
424 }
425
426 static void
427 format_vlan_tci(struct ds *ds, ovs_be16 tci, ovs_be16 mask, bool verbose)
428 {
429     if (verbose || vlan_tci_to_vid(tci) || vlan_tci_to_vid(mask)) {
430         ds_put_format(ds, "vid=%"PRIu16, vlan_tci_to_vid(tci));
431         if (vlan_tci_to_vid(mask) != VLAN_VID_MASK) { /* Partially masked. */
432             ds_put_format(ds, "/0x%"PRIx16, vlan_tci_to_vid(mask));
433         };
434         ds_put_char(ds, ',');
435     }
436     if (verbose || vlan_tci_to_pcp(tci) || vlan_tci_to_pcp(mask)) {
437         ds_put_format(ds, "pcp=%d", vlan_tci_to_pcp(tci));
438         if (vlan_tci_to_pcp(mask) != (VLAN_PCP_MASK >> VLAN_PCP_SHIFT)) {
439             ds_put_format(ds, "/0x%x", vlan_tci_to_pcp(mask));
440         }
441         ds_put_char(ds, ',');
442     }
443     if (!(tci & htons(VLAN_CFI))) {
444         ds_put_cstr(ds, "cfi=0");
445         ds_put_char(ds, ',');
446     }
447     ds_chomp(ds, ',');
448 }
449
450 static void
451 format_mpls_lse(struct ds *ds, ovs_be32 mpls_lse)
452 {
453     ds_put_format(ds, "label=%"PRIu32",tc=%d,ttl=%d,bos=%d",
454                   mpls_lse_to_label(mpls_lse),
455                   mpls_lse_to_tc(mpls_lse),
456                   mpls_lse_to_ttl(mpls_lse),
457                   mpls_lse_to_bos(mpls_lse));
458 }
459
460 static void
461 format_mpls(struct ds *ds, const struct ovs_key_mpls *mpls_key,
462             const struct ovs_key_mpls *mpls_mask, int n)
463 {
464     if (n == 1) {
465         ovs_be32 key = mpls_key->mpls_lse;
466
467         if (mpls_mask == NULL) {
468             format_mpls_lse(ds, key);
469         } else {
470             ovs_be32 mask = mpls_mask->mpls_lse;
471
472             ds_put_format(ds, "label=%"PRIu32"/0x%x,tc=%d/%x,ttl=%d/0x%x,bos=%d/%x",
473                           mpls_lse_to_label(key), mpls_lse_to_label(mask),
474                           mpls_lse_to_tc(key), mpls_lse_to_tc(mask),
475                           mpls_lse_to_ttl(key), mpls_lse_to_ttl(mask),
476                           mpls_lse_to_bos(key), mpls_lse_to_bos(mask));
477         }
478     } else {
479         int i;
480
481         for (i = 0; i < n; i++) {
482             ds_put_format(ds, "lse%d=%#"PRIx32,
483                           i, ntohl(mpls_key[i].mpls_lse));
484             if (mpls_mask) {
485                 ds_put_format(ds, "/%#"PRIx32, ntohl(mpls_mask[i].mpls_lse));
486             }
487             ds_put_char(ds, ',');
488         }
489         ds_chomp(ds, ',');
490     }
491 }
492
493 static void
494 format_odp_recirc_action(struct ds *ds, uint32_t recirc_id)
495 {
496     ds_put_format(ds, "recirc(%"PRIu32")", recirc_id);
497 }
498
499 static void
500 format_odp_hash_action(struct ds *ds, const struct ovs_action_hash *hash_act)
501 {
502     ds_put_format(ds, "hash(");
503
504     if (hash_act->hash_alg == OVS_HASH_ALG_L4) {
505         ds_put_format(ds, "hash_l4(%"PRIu32")", hash_act->hash_basis);
506     } else {
507         ds_put_format(ds, "Unknown hash algorithm(%"PRIu32")",
508                       hash_act->hash_alg);
509     }
510     ds_put_format(ds, ")");
511 }
512
513 static void
514 format_odp_tnl_push_header(struct ds *ds, struct ovs_action_push_tnl *data)
515 {
516     const struct eth_header *eth;
517     const struct ip_header *ip;
518     const void *l3;
519
520     eth = (const struct eth_header *)data->header;
521
522     l3 = eth + 1;
523     ip = (const struct ip_header *)l3;
524
525     /* Ethernet */
526     ds_put_format(ds, "header(size=%"PRIu8",type=%"PRIu8",eth(dst=",
527                   data->header_len, data->tnl_type);
528     ds_put_format(ds, ETH_ADDR_FMT, ETH_ADDR_ARGS(eth->eth_dst));
529     ds_put_format(ds, ",src=");
530     ds_put_format(ds, ETH_ADDR_FMT, ETH_ADDR_ARGS(eth->eth_src));
531     ds_put_format(ds, ",dl_type=0x%04"PRIx16"),", ntohs(eth->eth_type));
532
533     /* IPv4 */
534     ds_put_format(ds, "ipv4(src="IP_FMT",dst="IP_FMT",proto=%"PRIu8
535                   ",tos=%#"PRIx8",ttl=%"PRIu8",frag=0x%"PRIx16"),",
536                   IP_ARGS(get_16aligned_be32(&ip->ip_src)),
537                   IP_ARGS(get_16aligned_be32(&ip->ip_dst)),
538                   ip->ip_proto, ip->ip_tos,
539                   ip->ip_ttl,
540                   ip->ip_frag_off);
541
542     if (data->tnl_type == OVS_VPORT_TYPE_VXLAN) {
543         const struct vxlanhdr *vxh;
544         const struct udp_header *udp;
545
546         /* UDP */
547         udp = (const struct udp_header *) (ip + 1);
548         ds_put_format(ds, "udp(src=%"PRIu16",dst=%"PRIu16"),",
549                       ntohs(udp->udp_src), ntohs(udp->udp_dst));
550
551         /* VxLan */
552         vxh = (const struct vxlanhdr *)   (udp + 1);
553         ds_put_format(ds, "vxlan(flags=0x%"PRIx32",vni=0x%"PRIx32")",
554                       ntohl(get_16aligned_be32(&vxh->vx_flags)),
555                       ntohl(get_16aligned_be32(&vxh->vx_vni)));
556     } else if (data->tnl_type == OVS_VPORT_TYPE_GRE) {
557         const struct gre_base_hdr *greh;
558         ovs_16aligned_be32 *options;
559         void *l4;
560
561         l4 = ((uint8_t *)l3  + sizeof(struct ip_header));
562         greh = (const struct gre_base_hdr *) l4;
563
564         ds_put_format(ds, "gre((flags=0x%"PRIx16",proto=0x%"PRIx16")",
565                            greh->flags, ntohs(greh->protocol));
566         options = (ovs_16aligned_be32 *)(greh + 1);
567         if (greh->flags & htons(GRE_CSUM)) {
568             ds_put_format(ds, ",csum=0x%"PRIx32, ntohl(get_16aligned_be32(options)));
569             options++;
570         }
571         if (greh->flags & htons(GRE_KEY)) {
572             ds_put_format(ds, ",key=0x%"PRIx32, ntohl(get_16aligned_be32(options)));
573             options++;
574         }
575         if (greh->flags & htons(GRE_SEQ)) {
576             ds_put_format(ds, ",seq=0x%"PRIx32, ntohl(get_16aligned_be32(options)));
577             options++;
578         }
579         ds_put_format(ds, ")");
580     }
581     ds_put_format(ds, ")");
582 }
583
584 static void
585 format_odp_tnl_push_action(struct ds *ds, const struct nlattr *attr)
586 {
587     struct ovs_action_push_tnl *data;
588
589     data = (struct ovs_action_push_tnl *) nl_attr_get(attr);
590
591     ds_put_format(ds, "tnl_push(tnl_port(%"PRIu32"),", data->tnl_port);
592     format_odp_tnl_push_header(ds, data);
593     ds_put_format(ds, ",out_port(%"PRIu32"))", data->out_port);
594 }
595
596 static void
597 format_odp_action(struct ds *ds, const struct nlattr *a)
598 {
599     int expected_len;
600     enum ovs_action_attr type = nl_attr_type(a);
601     const struct ovs_action_push_vlan *vlan;
602     size_t size;
603
604     expected_len = odp_action_len(nl_attr_type(a));
605     if (expected_len != -2 && nl_attr_get_size(a) != expected_len) {
606         ds_put_format(ds, "bad length %"PRIuSIZE", expected %d for: ",
607                       nl_attr_get_size(a), expected_len);
608         format_generic_odp_action(ds, a);
609         return;
610     }
611
612     switch (type) {
613     case OVS_ACTION_ATTR_OUTPUT:
614         ds_put_format(ds, "%"PRIu32, nl_attr_get_u32(a));
615         break;
616     case OVS_ACTION_ATTR_TUNNEL_POP:
617         ds_put_format(ds, "tnl_pop(%"PRIu32")", nl_attr_get_u32(a));
618         break;
619     case OVS_ACTION_ATTR_TUNNEL_PUSH:
620         format_odp_tnl_push_action(ds, a);
621         break;
622     case OVS_ACTION_ATTR_USERSPACE:
623         format_odp_userspace_action(ds, a);
624         break;
625     case OVS_ACTION_ATTR_RECIRC:
626         format_odp_recirc_action(ds, nl_attr_get_u32(a));
627         break;
628     case OVS_ACTION_ATTR_HASH:
629         format_odp_hash_action(ds, nl_attr_get(a));
630         break;
631     case OVS_ACTION_ATTR_SET_MASKED:
632         a = nl_attr_get(a);
633         size = nl_attr_get_size(a) / 2;
634         ds_put_cstr(ds, "set(");
635
636         /* Masked set action not supported for tunnel key, which is bigger. */
637         if (size <= sizeof(struct ovs_key_ipv6)) {
638             struct nlattr attr[1 + DIV_ROUND_UP(sizeof(struct ovs_key_ipv6),
639                                                 sizeof(struct nlattr))];
640             struct nlattr mask[1 + DIV_ROUND_UP(sizeof(struct ovs_key_ipv6),
641                                                 sizeof(struct nlattr))];
642
643             mask->nla_type = attr->nla_type = nl_attr_type(a);
644             mask->nla_len = attr->nla_len = NLA_HDRLEN + size;
645             memcpy(attr + 1, (char *)(a + 1), size);
646             memcpy(mask + 1, (char *)(a + 1) + size, size);
647             format_odp_key_attr(attr, mask, NULL, ds, false);
648         } else {
649             format_odp_key_attr(a, NULL, NULL, ds, false);
650         }
651         ds_put_cstr(ds, ")");
652         break;
653     case OVS_ACTION_ATTR_SET:
654         ds_put_cstr(ds, "set(");
655         format_odp_key_attr(nl_attr_get(a), NULL, NULL, ds, true);
656         ds_put_cstr(ds, ")");
657         break;
658     case OVS_ACTION_ATTR_PUSH_VLAN:
659         vlan = nl_attr_get(a);
660         ds_put_cstr(ds, "push_vlan(");
661         if (vlan->vlan_tpid != htons(ETH_TYPE_VLAN)) {
662             ds_put_format(ds, "tpid=0x%04"PRIx16",", ntohs(vlan->vlan_tpid));
663         }
664         format_vlan_tci(ds, vlan->vlan_tci, OVS_BE16_MAX, false);
665         ds_put_char(ds, ')');
666         break;
667     case OVS_ACTION_ATTR_POP_VLAN:
668         ds_put_cstr(ds, "pop_vlan");
669         break;
670     case OVS_ACTION_ATTR_PUSH_MPLS: {
671         const struct ovs_action_push_mpls *mpls = nl_attr_get(a);
672         ds_put_cstr(ds, "push_mpls(");
673         format_mpls_lse(ds, mpls->mpls_lse);
674         ds_put_format(ds, ",eth_type=0x%"PRIx16")", ntohs(mpls->mpls_ethertype));
675         break;
676     }
677     case OVS_ACTION_ATTR_POP_MPLS: {
678         ovs_be16 ethertype = nl_attr_get_be16(a);
679         ds_put_format(ds, "pop_mpls(eth_type=0x%"PRIx16")", ntohs(ethertype));
680         break;
681     }
682     case OVS_ACTION_ATTR_SAMPLE:
683         format_odp_sample_action(ds, a);
684         break;
685     case OVS_ACTION_ATTR_UNSPEC:
686     case __OVS_ACTION_ATTR_MAX:
687     default:
688         format_generic_odp_action(ds, a);
689         break;
690     }
691 }
692
693 void
694 format_odp_actions(struct ds *ds, const struct nlattr *actions,
695                    size_t actions_len)
696 {
697     if (actions_len) {
698         const struct nlattr *a;
699         unsigned int left;
700
701         NL_ATTR_FOR_EACH (a, left, actions, actions_len) {
702             if (a != actions) {
703                 ds_put_char(ds, ',');
704             }
705             format_odp_action(ds, a);
706         }
707         if (left) {
708             int i;
709
710             if (left == actions_len) {
711                 ds_put_cstr(ds, "<empty>");
712             }
713             ds_put_format(ds, ",***%u leftover bytes*** (", left);
714             for (i = 0; i < left; i++) {
715                 ds_put_format(ds, "%02x", ((const uint8_t *) a)[i]);
716             }
717             ds_put_char(ds, ')');
718         }
719     } else {
720         ds_put_cstr(ds, "drop");
721     }
722 }
723
724 /* Separate out parse_odp_userspace_action() function. */
725 static int
726 parse_odp_userspace_action(const char *s, struct ofpbuf *actions)
727 {
728     uint32_t pid;
729     union user_action_cookie cookie;
730     struct ofpbuf buf;
731     odp_port_t tunnel_out_port;
732     int n = -1;
733     void *user_data = NULL;
734     size_t user_data_size = 0;
735
736     if (!ovs_scan(s, "userspace(pid=%"SCNi32"%n", &pid, &n)) {
737         return -EINVAL;
738     }
739
740     {
741         uint32_t output;
742         uint32_t probability;
743         uint32_t collector_set_id;
744         uint32_t obs_domain_id;
745         uint32_t obs_point_id;
746         int vid, pcp;
747         int n1 = -1;
748         if (ovs_scan(&s[n], ",sFlow(vid=%i,"
749                      "pcp=%i,output=%"SCNi32")%n",
750                      &vid, &pcp, &output, &n1)) {
751             uint16_t tci;
752
753             n += n1;
754             tci = vid | (pcp << VLAN_PCP_SHIFT);
755             if (tci) {
756                 tci |= VLAN_CFI;
757             }
758
759             cookie.type = USER_ACTION_COOKIE_SFLOW;
760             cookie.sflow.vlan_tci = htons(tci);
761             cookie.sflow.output = output;
762             user_data = &cookie;
763             user_data_size = sizeof cookie.sflow;
764         } else if (ovs_scan(&s[n], ",slow_path(%n",
765                             &n1)) {
766             int res;
767
768             n += n1;
769             cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
770             cookie.slow_path.unused = 0;
771             cookie.slow_path.reason = 0;
772
773             res = parse_flags(&s[n], slow_path_reason_to_string,
774                               &cookie.slow_path.reason,
775                               SLOW_PATH_REASON_MASK, NULL);
776             if (res < 0 || s[n + res] != ')') {
777                 return res;
778             }
779             n += res + 1;
780
781             user_data = &cookie;
782             user_data_size = sizeof cookie.slow_path;
783         } else if (ovs_scan(&s[n], ",flow_sample(probability=%"SCNi32","
784                             "collector_set_id=%"SCNi32","
785                             "obs_domain_id=%"SCNi32","
786                             "obs_point_id=%"SCNi32")%n",
787                             &probability, &collector_set_id,
788                             &obs_domain_id, &obs_point_id, &n1)) {
789             n += n1;
790
791             cookie.type = USER_ACTION_COOKIE_FLOW_SAMPLE;
792             cookie.flow_sample.probability = probability;
793             cookie.flow_sample.collector_set_id = collector_set_id;
794             cookie.flow_sample.obs_domain_id = obs_domain_id;
795             cookie.flow_sample.obs_point_id = obs_point_id;
796             user_data = &cookie;
797             user_data_size = sizeof cookie.flow_sample;
798         } else if (ovs_scan(&s[n], ",ipfix(output_port=%"SCNi32")%n",
799                             &output, &n1) ) {
800             n += n1;
801             cookie.type = USER_ACTION_COOKIE_IPFIX;
802             cookie.ipfix.output_odp_port = u32_to_odp(output);
803             user_data = &cookie;
804             user_data_size = sizeof cookie.ipfix;
805         } else if (ovs_scan(&s[n], ",userdata(%n",
806                             &n1)) {
807             char *end;
808
809             n += n1;
810             ofpbuf_init(&buf, 16);
811             end = ofpbuf_put_hex(&buf, &s[n], NULL);
812             if (end[0] != ')') {
813                 return -EINVAL;
814             }
815             user_data = buf.data;
816             user_data_size = buf.size;
817             n = (end + 1) - s;
818         }
819     }
820
821     {
822         int n1 = -1;
823         if (ovs_scan(&s[n], ",tunnel_out_port=%"SCNi32")%n",
824                      &tunnel_out_port, &n1)) {
825             odp_put_userspace_action(pid, user_data, user_data_size, tunnel_out_port, actions);
826             return n + n1;
827         } else if (s[n] == ')') {
828             odp_put_userspace_action(pid, user_data, user_data_size, ODPP_NONE, actions);
829             return n + 1;
830         }
831     }
832
833     return -EINVAL;
834 }
835
836 static int
837 ovs_parse_tnl_push(const char *s, struct ovs_action_push_tnl *data)
838 {
839     struct eth_header *eth;
840     struct ip_header *ip;
841     struct udp_header *udp;
842     struct gre_base_hdr *greh;
843     uint16_t gre_proto, dl_type, udp_src, udp_dst;
844     ovs_be32 sip, dip;
845     uint32_t tnl_type = 0, header_len = 0;
846     void *l3, *l4;
847     int n = 0;
848
849     if (!ovs_scan_len(s, &n, "tnl_push(tnl_port(%"SCNi32"),", &data->tnl_port)) {
850         return -EINVAL;
851     }
852     eth = (struct eth_header *) data->header;
853     l3 = (data->header + sizeof *eth);
854     l4 = ((uint8_t *) l3 + sizeof (struct ip_header));
855     ip = (struct ip_header *) l3;
856     if (!ovs_scan_len(s, &n, "header(size=%"SCNi32",type=%"SCNi32","
857                          "eth(dst="ETH_ADDR_SCAN_FMT",",
858                          &data->header_len,
859                          &data->tnl_type,
860                          ETH_ADDR_SCAN_ARGS(eth->eth_dst))) {
861         return -EINVAL;
862     }
863
864     if (!ovs_scan_len(s, &n, "src="ETH_ADDR_SCAN_FMT",",
865                   ETH_ADDR_SCAN_ARGS(eth->eth_src))) {
866         return -EINVAL;
867     }
868     if (!ovs_scan_len(s, &n, "dl_type=0x%"SCNx16"),", &dl_type)) {
869         return -EINVAL;
870     }
871     eth->eth_type = htons(dl_type);
872
873     /* IPv4 */
874     if (!ovs_scan_len(s, &n, "ipv4(src="IP_SCAN_FMT",dst="IP_SCAN_FMT",proto=%"SCNi8
875                          ",tos=%"SCNi8",ttl=%"SCNi8",frag=0x%"SCNx16"),",
876                          IP_SCAN_ARGS(&sip),
877                          IP_SCAN_ARGS(&dip),
878                          &ip->ip_proto, &ip->ip_tos,
879                          &ip->ip_ttl, &ip->ip_frag_off)) {
880         return -EINVAL;
881     }
882     put_16aligned_be32(&ip->ip_src, sip);
883     put_16aligned_be32(&ip->ip_dst, dip);
884
885     /* Tunnel header */
886     udp = (struct udp_header *) l4;
887     greh = (struct gre_base_hdr *) l4;
888     if (ovs_scan_len(s, &n, "udp(src=%"SCNi16",dst=%"SCNi16"),",
889                          &udp_src, &udp_dst)) {
890         struct vxlanhdr *vxh;
891         uint32_t vx_flags, vx_vni;
892
893         udp->udp_src = htons(udp_src);
894         udp->udp_dst = htons(udp_dst);
895         udp->udp_len = 0;
896         udp->udp_csum = 0;
897
898         vxh = (struct vxlanhdr *) (udp + 1);
899         if (!ovs_scan_len(s, &n, "vxlan(flags=0x%"SCNx32",vni=0x%"SCNx32"))",
900                             &vx_flags, &vx_vni)) {
901             return -EINVAL;
902         }
903         put_16aligned_be32(&vxh->vx_flags, htonl(vx_flags));
904         put_16aligned_be32(&vxh->vx_vni, htonl(vx_vni));
905         tnl_type = OVS_VPORT_TYPE_VXLAN;
906         header_len = sizeof *eth + sizeof *ip +
907                      sizeof *udp + sizeof *vxh;
908     } else if (ovs_scan_len(s, &n, "gre((flags=0x%"SCNx16",proto=0x%"SCNx16")",
909                          &greh->flags, &gre_proto)){
910
911         tnl_type = OVS_VPORT_TYPE_GRE;
912         greh->protocol = htons(gre_proto);
913         ovs_16aligned_be32 *options = (ovs_16aligned_be32 *) (greh + 1);
914
915         if (greh->flags & htons(GRE_CSUM)) {
916             uint32_t csum;
917
918             if (!ovs_scan_len(s, &n, ",csum=0x%"SCNx32, &csum)) {
919                 return -EINVAL;
920             }
921             put_16aligned_be32(options, htonl(csum));
922             options++;
923         }
924         if (greh->flags & htons(GRE_KEY)) {
925             uint32_t key;
926
927             if (!ovs_scan_len(s, &n, ",key=0x%"SCNx32, &key)) {
928                 return -EINVAL;
929             }
930
931             put_16aligned_be32(options, htonl(key));
932             options++;
933         }
934         if (greh->flags & htons(GRE_SEQ)) {
935             uint32_t seq;
936
937             if (!ovs_scan_len(s, &n, ",seq=0x%"SCNx32, &seq)) {
938                 return -EINVAL;
939             }
940             put_16aligned_be32(options, htonl(seq));
941             options++;
942         }
943
944         if (!ovs_scan_len(s, &n, "))")) {
945             return -EINVAL;
946         }
947
948         header_len = sizeof *eth + sizeof *ip +
949                      ((uint8_t *) options - (uint8_t *) greh);
950     } else {
951         return -EINVAL;
952     }
953
954     /* check tunnel meta data. */
955     if (data->tnl_type != tnl_type) {
956         return -EINVAL;
957     }
958     if (data->header_len != header_len) {
959         return -EINVAL;
960     }
961
962     /* Out port */
963     if (!ovs_scan_len(s, &n, ",out_port(%"SCNi32"))", &data->out_port)) {
964         return -EINVAL;
965     }
966
967     return n;
968 }
969
970 static int
971 parse_odp_action(const char *s, const struct simap *port_names,
972                  struct ofpbuf *actions)
973 {
974     {
975         uint32_t port;
976         int n;
977
978         if (ovs_scan(s, "%"SCNi32"%n", &port, &n)) {
979             nl_msg_put_u32(actions, OVS_ACTION_ATTR_OUTPUT, port);
980             return n;
981         }
982     }
983
984     if (port_names) {
985         int len = strcspn(s, delimiters);
986         struct simap_node *node;
987
988         node = simap_find_len(port_names, s, len);
989         if (node) {
990             nl_msg_put_u32(actions, OVS_ACTION_ATTR_OUTPUT, node->data);
991             return len;
992         }
993     }
994
995     {
996         uint32_t recirc_id;
997         int n = -1;
998
999         if (ovs_scan(s, "recirc(%"PRIu32")%n", &recirc_id, &n)) {
1000             nl_msg_put_u32(actions, OVS_ACTION_ATTR_RECIRC, recirc_id);
1001             return n;
1002         }
1003     }
1004
1005     if (!strncmp(s, "userspace(", 10)) {
1006         return parse_odp_userspace_action(s, actions);
1007     }
1008
1009     if (!strncmp(s, "set(", 4)) {
1010         size_t start_ofs;
1011         int retval;
1012         struct nlattr mask[128 / sizeof(struct nlattr)];
1013         struct ofpbuf maskbuf;
1014         struct nlattr *nested, *key;
1015         size_t size;
1016
1017         /* 'mask' is big enough to hold any key. */
1018         ofpbuf_use_stack(&maskbuf, mask, sizeof mask);
1019
1020         start_ofs = nl_msg_start_nested(actions, OVS_ACTION_ATTR_SET);
1021         retval = parse_odp_key_mask_attr(s + 4, port_names, actions, &maskbuf);
1022         if (retval < 0) {
1023             return retval;
1024         }
1025         if (s[retval + 4] != ')') {
1026             return -EINVAL;
1027         }
1028
1029         nested = ofpbuf_at_assert(actions, start_ofs, sizeof *nested);
1030         key = nested + 1;
1031
1032         size = nl_attr_get_size(mask);
1033         if (size == nl_attr_get_size(key)) {
1034             /* Change to masked set action if not fully masked. */
1035             if (!is_all_ones(mask + 1, size)) {
1036                 key->nla_len += size;
1037                 ofpbuf_put(actions, mask + 1, size);
1038                 /* 'actions' may have been reallocated by ofpbuf_put(). */
1039                 nested = ofpbuf_at_assert(actions, start_ofs, sizeof *nested);
1040                 nested->nla_type = OVS_ACTION_ATTR_SET_MASKED;
1041             }
1042         }
1043
1044         nl_msg_end_nested(actions, start_ofs);
1045         return retval + 5;
1046     }
1047
1048     {
1049         struct ovs_action_push_vlan push;
1050         int tpid = ETH_TYPE_VLAN;
1051         int vid, pcp;
1052         int cfi = 1;
1053         int n = -1;
1054
1055         if (ovs_scan(s, "push_vlan(vid=%i,pcp=%i)%n", &vid, &pcp, &n)
1056             || ovs_scan(s, "push_vlan(vid=%i,pcp=%i,cfi=%i)%n",
1057                         &vid, &pcp, &cfi, &n)
1058             || ovs_scan(s, "push_vlan(tpid=%i,vid=%i,pcp=%i)%n",
1059                         &tpid, &vid, &pcp, &n)
1060             || ovs_scan(s, "push_vlan(tpid=%i,vid=%i,pcp=%i,cfi=%i)%n",
1061                         &tpid, &vid, &pcp, &cfi, &n)) {
1062             push.vlan_tpid = htons(tpid);
1063             push.vlan_tci = htons((vid << VLAN_VID_SHIFT)
1064                                   | (pcp << VLAN_PCP_SHIFT)
1065                                   | (cfi ? VLAN_CFI : 0));
1066             nl_msg_put_unspec(actions, OVS_ACTION_ATTR_PUSH_VLAN,
1067                               &push, sizeof push);
1068
1069             return n;
1070         }
1071     }
1072
1073     if (!strncmp(s, "pop_vlan", 8)) {
1074         nl_msg_put_flag(actions, OVS_ACTION_ATTR_POP_VLAN);
1075         return 8;
1076     }
1077
1078     {
1079         double percentage;
1080         int n = -1;
1081
1082         if (ovs_scan(s, "sample(sample=%lf%%,actions(%n", &percentage, &n)
1083             && percentage >= 0. && percentage <= 100.0) {
1084             size_t sample_ofs, actions_ofs;
1085             double probability;
1086
1087             probability = floor(UINT32_MAX * (percentage / 100.0) + .5);
1088             sample_ofs = nl_msg_start_nested(actions, OVS_ACTION_ATTR_SAMPLE);
1089             nl_msg_put_u32(actions, OVS_SAMPLE_ATTR_PROBABILITY,
1090                            (probability <= 0 ? 0
1091                             : probability >= UINT32_MAX ? UINT32_MAX
1092                             : probability));
1093
1094             actions_ofs = nl_msg_start_nested(actions,
1095                                               OVS_SAMPLE_ATTR_ACTIONS);
1096             for (;;) {
1097                 int retval;
1098
1099                 n += strspn(s + n, delimiters);
1100                 if (s[n] == ')') {
1101                     break;
1102                 }
1103
1104                 retval = parse_odp_action(s + n, port_names, actions);
1105                 if (retval < 0) {
1106                     return retval;
1107                 }
1108                 n += retval;
1109             }
1110             nl_msg_end_nested(actions, actions_ofs);
1111             nl_msg_end_nested(actions, sample_ofs);
1112
1113             return s[n + 1] == ')' ? n + 2 : -EINVAL;
1114         }
1115     }
1116
1117     {
1118         uint32_t port;
1119         int n;
1120
1121         if (ovs_scan(s, "tnl_pop(%"SCNi32")%n", &port, &n)) {
1122             nl_msg_put_u32(actions, OVS_ACTION_ATTR_TUNNEL_POP, port);
1123             return n;
1124         }
1125     }
1126
1127     {
1128         struct ovs_action_push_tnl data;
1129         int n;
1130
1131         n = ovs_parse_tnl_push(s, &data);
1132         if (n > 0) {
1133             odp_put_tnl_push_action(actions, &data);
1134             return n;
1135         } else if (n < 0) {
1136             return n;
1137         }
1138     }
1139     return -EINVAL;
1140 }
1141
1142 /* Parses the string representation of datapath actions, in the format output
1143  * by format_odp_action().  Returns 0 if successful, otherwise a positive errno
1144  * value.  On success, the ODP actions are appended to 'actions' as a series of
1145  * Netlink attributes.  On failure, no data is appended to 'actions'.  Either
1146  * way, 'actions''s data might be reallocated. */
1147 int
1148 odp_actions_from_string(const char *s, const struct simap *port_names,
1149                         struct ofpbuf *actions)
1150 {
1151     size_t old_size;
1152
1153     if (!strcasecmp(s, "drop")) {
1154         return 0;
1155     }
1156
1157     old_size = actions->size;
1158     for (;;) {
1159         int retval;
1160
1161         s += strspn(s, delimiters);
1162         if (!*s) {
1163             return 0;
1164         }
1165
1166         retval = parse_odp_action(s, port_names, actions);
1167         if (retval < 0 || !strchr(delimiters, s[retval])) {
1168             actions->size = old_size;
1169             return -retval;
1170         }
1171         s += retval;
1172     }
1173
1174     return 0;
1175 }
1176 \f
1177 /* Returns the correct length of the payload for a flow key attribute of the
1178  * specified 'type', -1 if 'type' is unknown, or -2 if the attribute's payload
1179  * is variable length. */
1180 static int
1181 odp_flow_key_attr_len(uint16_t type)
1182 {
1183     if (type > OVS_KEY_ATTR_MAX) {
1184         return -1;
1185     }
1186
1187     switch ((enum ovs_key_attr) type) {
1188     case OVS_KEY_ATTR_ENCAP: return -2;
1189     case OVS_KEY_ATTR_PRIORITY: return 4;
1190     case OVS_KEY_ATTR_SKB_MARK: return 4;
1191     case OVS_KEY_ATTR_DP_HASH: return 4;
1192     case OVS_KEY_ATTR_RECIRC_ID: return 4;
1193     case OVS_KEY_ATTR_TUNNEL: return -2;
1194     case OVS_KEY_ATTR_IN_PORT: return 4;
1195     case OVS_KEY_ATTR_ETHERNET: return sizeof(struct ovs_key_ethernet);
1196     case OVS_KEY_ATTR_VLAN: return sizeof(ovs_be16);
1197     case OVS_KEY_ATTR_ETHERTYPE: return 2;
1198     case OVS_KEY_ATTR_MPLS: return -2;
1199     case OVS_KEY_ATTR_IPV4: return sizeof(struct ovs_key_ipv4);
1200     case OVS_KEY_ATTR_IPV6: return sizeof(struct ovs_key_ipv6);
1201     case OVS_KEY_ATTR_TCP: return sizeof(struct ovs_key_tcp);
1202     case OVS_KEY_ATTR_TCP_FLAGS: return 2;
1203     case OVS_KEY_ATTR_UDP: return sizeof(struct ovs_key_udp);
1204     case OVS_KEY_ATTR_SCTP: return sizeof(struct ovs_key_sctp);
1205     case OVS_KEY_ATTR_ICMP: return sizeof(struct ovs_key_icmp);
1206     case OVS_KEY_ATTR_ICMPV6: return sizeof(struct ovs_key_icmpv6);
1207     case OVS_KEY_ATTR_ARP: return sizeof(struct ovs_key_arp);
1208     case OVS_KEY_ATTR_ND: return sizeof(struct ovs_key_nd);
1209
1210     case OVS_KEY_ATTR_UNSPEC:
1211     case __OVS_KEY_ATTR_MAX:
1212         return -1;
1213     }
1214
1215     return -1;
1216 }
1217
1218 static void
1219 format_generic_odp_key(const struct nlattr *a, struct ds *ds)
1220 {
1221     size_t len = nl_attr_get_size(a);
1222     if (len) {
1223         const uint8_t *unspec;
1224         unsigned int i;
1225
1226         unspec = nl_attr_get(a);
1227         for (i = 0; i < len; i++) {
1228             if (i) {
1229                 ds_put_char(ds, ' ');
1230             }
1231             ds_put_format(ds, "%02x", unspec[i]);
1232         }
1233     }
1234 }
1235
1236 static const char *
1237 ovs_frag_type_to_string(enum ovs_frag_type type)
1238 {
1239     switch (type) {
1240     case OVS_FRAG_TYPE_NONE:
1241         return "no";
1242     case OVS_FRAG_TYPE_FIRST:
1243         return "first";
1244     case OVS_FRAG_TYPE_LATER:
1245         return "later";
1246     case __OVS_FRAG_TYPE_MAX:
1247     default:
1248         return "<error>";
1249     }
1250 }
1251
1252 static int
1253 tunnel_key_attr_len(int type)
1254 {
1255     switch (type) {
1256     case OVS_TUNNEL_KEY_ATTR_ID: return 8;
1257     case OVS_TUNNEL_KEY_ATTR_IPV4_SRC: return 4;
1258     case OVS_TUNNEL_KEY_ATTR_IPV4_DST: return 4;
1259     case OVS_TUNNEL_KEY_ATTR_TOS: return 1;
1260     case OVS_TUNNEL_KEY_ATTR_TTL: return 1;
1261     case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT: return 0;
1262     case OVS_TUNNEL_KEY_ATTR_CSUM: return 0;
1263     case OVS_TUNNEL_KEY_ATTR_TP_SRC: return 2;
1264     case OVS_TUNNEL_KEY_ATTR_TP_DST: return 2;
1265     case OVS_TUNNEL_KEY_ATTR_OAM: return 0;
1266     case OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS: return -2;
1267     case OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS: return -2;
1268     case __OVS_TUNNEL_KEY_ATTR_MAX:
1269         return -1;
1270     }
1271     return -1;
1272 }
1273
1274 #define GENEVE_OPT(class, type) ((OVS_FORCE uint32_t)(class) << 8 | (type))
1275 static int
1276 parse_geneve_opts(const struct nlattr *attr)
1277 {
1278     int opts_len = nl_attr_get_size(attr);
1279     const struct geneve_opt *opt = nl_attr_get(attr);
1280
1281     while (opts_len > 0) {
1282         int len;
1283
1284         if (opts_len < sizeof(*opt)) {
1285             return -EINVAL;
1286         }
1287
1288         len = sizeof(*opt) + opt->length * 4;
1289         if (len > opts_len) {
1290             return -EINVAL;
1291         }
1292
1293         switch (GENEVE_OPT(opt->opt_class, opt->type)) {
1294         default:
1295             if (opt->type & GENEVE_CRIT_OPT_TYPE) {
1296                 return -EINVAL;
1297             }
1298         };
1299
1300         opt = opt + len / sizeof(*opt);
1301         opts_len -= len;
1302     };
1303
1304     return 0;
1305 }
1306
1307 enum odp_key_fitness
1308 odp_tun_key_from_attr(const struct nlattr *attr, struct flow_tnl *tun)
1309 {
1310     unsigned int left;
1311     const struct nlattr *a;
1312     bool ttl = false;
1313     bool unknown = false;
1314
1315     NL_NESTED_FOR_EACH(a, left, attr) {
1316         uint16_t type = nl_attr_type(a);
1317         size_t len = nl_attr_get_size(a);
1318         int expected_len = tunnel_key_attr_len(type);
1319
1320         if (len != expected_len && expected_len >= 0) {
1321             return ODP_FIT_ERROR;
1322         }
1323
1324         switch (type) {
1325         case OVS_TUNNEL_KEY_ATTR_ID:
1326             tun->tun_id = nl_attr_get_be64(a);
1327             tun->flags |= FLOW_TNL_F_KEY;
1328             break;
1329         case OVS_TUNNEL_KEY_ATTR_IPV4_SRC:
1330             tun->ip_src = nl_attr_get_be32(a);
1331             break;
1332         case OVS_TUNNEL_KEY_ATTR_IPV4_DST:
1333             tun->ip_dst = nl_attr_get_be32(a);
1334             break;
1335         case OVS_TUNNEL_KEY_ATTR_TOS:
1336             tun->ip_tos = nl_attr_get_u8(a);
1337             break;
1338         case OVS_TUNNEL_KEY_ATTR_TTL:
1339             tun->ip_ttl = nl_attr_get_u8(a);
1340             ttl = true;
1341             break;
1342         case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT:
1343             tun->flags |= FLOW_TNL_F_DONT_FRAGMENT;
1344             break;
1345         case OVS_TUNNEL_KEY_ATTR_CSUM:
1346             tun->flags |= FLOW_TNL_F_CSUM;
1347             break;
1348         case OVS_TUNNEL_KEY_ATTR_TP_SRC:
1349             tun->tp_src = nl_attr_get_be16(a);
1350             break;
1351         case OVS_TUNNEL_KEY_ATTR_TP_DST:
1352             tun->tp_dst = nl_attr_get_be16(a);
1353             break;
1354         case OVS_TUNNEL_KEY_ATTR_OAM:
1355             tun->flags |= FLOW_TNL_F_OAM;
1356             break;
1357         case OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS: {
1358             static const struct nl_policy vxlan_opts_policy[] = {
1359                 [OVS_VXLAN_EXT_GBP] = { .type = NL_A_U32 },
1360             };
1361             struct nlattr *ext[ARRAY_SIZE(vxlan_opts_policy)];
1362
1363             if (!nl_parse_nested(a, vxlan_opts_policy, ext, ARRAY_SIZE(ext))) {
1364                 return ODP_FIT_ERROR;
1365             }
1366
1367             if (ext[OVS_VXLAN_EXT_GBP]) {
1368                 uint32_t gbp = nl_attr_get_u32(ext[OVS_VXLAN_EXT_GBP]);
1369
1370                 tun->gbp_id = htons(gbp & 0xFFFF);
1371                 tun->gbp_flags = (gbp >> 16) & 0xFF;
1372             }
1373
1374             break;
1375         }
1376         case OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS: {
1377             if (parse_geneve_opts(a)) {
1378                 return ODP_FIT_ERROR;
1379             }
1380             /* It is necessary to reproduce options exactly (including order)
1381              * so it's easiest to just echo them back. */
1382             unknown = true;
1383             break;
1384         }
1385         default:
1386             /* Allow this to show up as unexpected, if there are unknown
1387              * tunnel attribute, eventually resulting in ODP_FIT_TOO_MUCH. */
1388             unknown = true;
1389             break;
1390         }
1391     }
1392
1393     if (!ttl) {
1394         return ODP_FIT_ERROR;
1395     }
1396     if (unknown) {
1397         return ODP_FIT_TOO_MUCH;
1398     }
1399     return ODP_FIT_PERFECT;
1400 }
1401
1402 static void
1403 tun_key_to_attr(struct ofpbuf *a, const struct flow_tnl *tun_key)
1404 {
1405     size_t tun_key_ofs;
1406
1407     tun_key_ofs = nl_msg_start_nested(a, OVS_KEY_ATTR_TUNNEL);
1408
1409     /* tun_id != 0 without FLOW_TNL_F_KEY is valid if tun_key is a mask. */
1410     if (tun_key->tun_id || tun_key->flags & FLOW_TNL_F_KEY) {
1411         nl_msg_put_be64(a, OVS_TUNNEL_KEY_ATTR_ID, tun_key->tun_id);
1412     }
1413     if (tun_key->ip_src) {
1414         nl_msg_put_be32(a, OVS_TUNNEL_KEY_ATTR_IPV4_SRC, tun_key->ip_src);
1415     }
1416     if (tun_key->ip_dst) {
1417         nl_msg_put_be32(a, OVS_TUNNEL_KEY_ATTR_IPV4_DST, tun_key->ip_dst);
1418     }
1419     if (tun_key->ip_tos) {
1420         nl_msg_put_u8(a, OVS_TUNNEL_KEY_ATTR_TOS, tun_key->ip_tos);
1421     }
1422     nl_msg_put_u8(a, OVS_TUNNEL_KEY_ATTR_TTL, tun_key->ip_ttl);
1423     if (tun_key->flags & FLOW_TNL_F_DONT_FRAGMENT) {
1424         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT);
1425     }
1426     if (tun_key->flags & FLOW_TNL_F_CSUM) {
1427         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_CSUM);
1428     }
1429     if (tun_key->tp_src) {
1430         nl_msg_put_be16(a, OVS_TUNNEL_KEY_ATTR_TP_SRC, tun_key->tp_src);
1431     }
1432     if (tun_key->tp_dst) {
1433         nl_msg_put_be16(a, OVS_TUNNEL_KEY_ATTR_TP_DST, tun_key->tp_dst);
1434     }
1435     if (tun_key->flags & FLOW_TNL_F_OAM) {
1436         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_OAM);
1437     }
1438     if (tun_key->gbp_flags || tun_key->gbp_id) {
1439         size_t vxlan_opts_ofs;
1440
1441         vxlan_opts_ofs = nl_msg_start_nested(a, OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS);
1442         nl_msg_put_u32(a, OVS_VXLAN_EXT_GBP,
1443                        (tun_key->gbp_flags << 16) | ntohs(tun_key->gbp_id));
1444         nl_msg_end_nested(a, vxlan_opts_ofs);
1445     }
1446
1447     nl_msg_end_nested(a, tun_key_ofs);
1448 }
1449
1450 static bool
1451 odp_mask_attr_is_wildcard(const struct nlattr *ma)
1452 {
1453     return is_all_zeros(nl_attr_get(ma), nl_attr_get_size(ma));
1454 }
1455
1456 static bool
1457 odp_mask_is_exact(enum ovs_key_attr attr, const void *mask, size_t size)
1458 {
1459     if (attr == OVS_KEY_ATTR_TCP_FLAGS) {
1460         return TCP_FLAGS(*(ovs_be16 *)mask) == TCP_FLAGS(OVS_BE16_MAX);
1461     }
1462     if (attr == OVS_KEY_ATTR_IPV6) {
1463         const struct ovs_key_ipv6 *ipv6_mask = mask;
1464
1465         return
1466             ((ipv6_mask->ipv6_label & htonl(IPV6_LABEL_MASK))
1467              == htonl(IPV6_LABEL_MASK))
1468             && ipv6_mask->ipv6_proto == UINT8_MAX
1469             && ipv6_mask->ipv6_tclass == UINT8_MAX
1470             && ipv6_mask->ipv6_hlimit == UINT8_MAX
1471             && ipv6_mask->ipv6_frag == UINT8_MAX
1472             && ipv6_mask_is_exact((const struct in6_addr *)ipv6_mask->ipv6_src)
1473             && ipv6_mask_is_exact((const struct in6_addr *)ipv6_mask->ipv6_dst);
1474     }
1475     if (attr == OVS_KEY_ATTR_TUNNEL) {
1476         const struct flow_tnl *tun_mask = mask;
1477
1478         return tun_mask->flags == FLOW_TNL_F_MASK
1479             && tun_mask->tun_id == OVS_BE64_MAX
1480             && tun_mask->ip_src == OVS_BE32_MAX
1481             && tun_mask->ip_dst == OVS_BE32_MAX
1482             && tun_mask->ip_tos == UINT8_MAX
1483             && tun_mask->ip_ttl == UINT8_MAX
1484             && tun_mask->tp_src == OVS_BE16_MAX
1485             && tun_mask->tp_dst == OVS_BE16_MAX
1486             && tun_mask->gbp_id == OVS_BE16_MAX
1487             && tun_mask->gbp_flags == UINT8_MAX;
1488     }
1489
1490     if (attr == OVS_KEY_ATTR_ARP) {
1491         /* ARP key has padding, ignore it. */
1492         BUILD_ASSERT_DECL(sizeof(struct ovs_key_arp) == 24);
1493         BUILD_ASSERT_DECL(offsetof(struct ovs_key_arp, arp_tha) == 10 + 6);
1494         size = offsetof(struct ovs_key_arp, arp_tha) + ETH_ADDR_LEN;
1495         ovs_assert(((uint16_t *)mask)[size/2] == 0);
1496     }
1497
1498     return is_all_ones(mask, size);
1499 }
1500
1501 static bool
1502 odp_mask_attr_is_exact(const struct nlattr *ma)
1503 {
1504     struct flow_tnl tun_mask;
1505     enum ovs_key_attr attr = nl_attr_type(ma);
1506     const void *mask;
1507     size_t size;
1508
1509     if (attr == OVS_KEY_ATTR_TUNNEL) {
1510         memset(&tun_mask, 0, sizeof tun_mask);
1511         odp_tun_key_from_attr(ma, &tun_mask);
1512         mask = &tun_mask;
1513         size = sizeof tun_mask;
1514     } else {
1515         mask = nl_attr_get(ma);
1516         size = nl_attr_get_size(ma);
1517     }
1518
1519     return odp_mask_is_exact(attr, mask, size);
1520 }
1521
1522 void
1523 odp_portno_names_set(struct hmap *portno_names, odp_port_t port_no,
1524                      char *port_name)
1525 {
1526     struct odp_portno_names *odp_portno_names;
1527
1528     odp_portno_names = xmalloc(sizeof *odp_portno_names);
1529     odp_portno_names->port_no = port_no;
1530     odp_portno_names->name = xstrdup(port_name);
1531     hmap_insert(portno_names, &odp_portno_names->hmap_node,
1532                 hash_odp_port(port_no));
1533 }
1534
1535 static char *
1536 odp_portno_names_get(const struct hmap *portno_names, odp_port_t port_no)
1537 {
1538     struct odp_portno_names *odp_portno_names;
1539
1540     HMAP_FOR_EACH_IN_BUCKET (odp_portno_names, hmap_node,
1541                              hash_odp_port(port_no), portno_names) {
1542         if (odp_portno_names->port_no == port_no) {
1543             return odp_portno_names->name;
1544         }
1545     }
1546     return NULL;
1547 }
1548
1549 void
1550 odp_portno_names_destroy(struct hmap *portno_names)
1551 {
1552     struct odp_portno_names *odp_portno_names, *odp_portno_names_next;
1553     HMAP_FOR_EACH_SAFE (odp_portno_names, odp_portno_names_next,
1554                         hmap_node, portno_names) {
1555         hmap_remove(portno_names, &odp_portno_names->hmap_node);
1556         free(odp_portno_names->name);
1557         free(odp_portno_names);
1558     }
1559 }
1560
1561 /* Format helpers. */
1562
1563 static void
1564 format_eth(struct ds *ds, const char *name, const uint8_t key[ETH_ADDR_LEN],
1565            const uint8_t (*mask)[ETH_ADDR_LEN], bool verbose)
1566 {
1567     bool mask_empty = mask && eth_addr_is_zero(*mask);
1568
1569     if (verbose || !mask_empty) {
1570         bool mask_full = !mask || eth_mask_is_exact(*mask);
1571
1572         if (mask_full) {
1573             ds_put_format(ds, "%s="ETH_ADDR_FMT",", name, ETH_ADDR_ARGS(key));
1574         } else {
1575             ds_put_format(ds, "%s=", name);
1576             eth_format_masked(key, *mask, ds);
1577             ds_put_char(ds, ',');
1578         }
1579     }
1580 }
1581
1582 static void
1583 format_be64(struct ds *ds, const char *name, ovs_be64 key,
1584             const ovs_be64 *mask, bool verbose)
1585 {
1586     bool mask_empty = mask && !*mask;
1587
1588     if (verbose || !mask_empty) {
1589         bool mask_full = !mask || *mask == OVS_BE64_MAX;
1590
1591         ds_put_format(ds, "%s=0x%"PRIx64, name, ntohll(key));
1592         if (!mask_full) { /* Partially masked. */
1593             ds_put_format(ds, "/%#"PRIx64, ntohll(*mask));
1594         }
1595         ds_put_char(ds, ',');
1596     }
1597 }
1598
1599 static void
1600 format_ipv4(struct ds *ds, const char *name, ovs_be32 key,
1601             const ovs_be32 *mask, bool verbose)
1602 {
1603     bool mask_empty = mask && !*mask;
1604
1605     if (verbose || !mask_empty) {
1606         bool mask_full = !mask || *mask == OVS_BE32_MAX;
1607
1608         ds_put_format(ds, "%s="IP_FMT, name, IP_ARGS(key));
1609         if (!mask_full) { /* Partially masked. */
1610             ds_put_format(ds, "/"IP_FMT, IP_ARGS(*mask));
1611         }
1612         ds_put_char(ds, ',');
1613     }
1614 }
1615
1616 static void
1617 format_ipv6(struct ds *ds, const char *name, const ovs_be32 key_[4],
1618             const ovs_be32 (*mask_)[4], bool verbose)
1619 {
1620     char buf[INET6_ADDRSTRLEN];
1621     const struct in6_addr *key = (const struct in6_addr *)key_;
1622     const struct in6_addr *mask = mask_ ? (const struct in6_addr *)*mask_
1623         : NULL;
1624     bool mask_empty = mask && ipv6_mask_is_any(mask);
1625
1626     if (verbose || !mask_empty) {
1627         bool mask_full = !mask || ipv6_mask_is_exact(mask);
1628
1629         inet_ntop(AF_INET6, key, buf, sizeof buf);
1630         ds_put_format(ds, "%s=%s", name, buf);
1631         if (!mask_full) { /* Partially masked. */
1632             inet_ntop(AF_INET6, mask, buf, sizeof buf);
1633             ds_put_format(ds, "/%s", buf);
1634         }
1635         ds_put_char(ds, ',');
1636     }
1637 }
1638
1639 static void
1640 format_ipv6_label(struct ds *ds, const char *name, ovs_be32 key,
1641                   const ovs_be32 *mask, bool verbose)
1642 {
1643     bool mask_empty = mask && !*mask;
1644
1645     if (verbose || !mask_empty) {
1646         bool mask_full = !mask
1647             || (*mask & htonl(IPV6_LABEL_MASK)) == htonl(IPV6_LABEL_MASK);
1648
1649         ds_put_format(ds, "%s=%#"PRIx32, name, ntohl(key));
1650         if (!mask_full) { /* Partially masked. */
1651             ds_put_format(ds, "/%#"PRIx32, ntohl(*mask));
1652         }
1653         ds_put_char(ds, ',');
1654     }
1655 }
1656
1657 static void
1658 format_u8x(struct ds *ds, const char *name, uint8_t key,
1659            const uint8_t *mask, bool verbose)
1660 {
1661     bool mask_empty = mask && !*mask;
1662
1663     if (verbose || !mask_empty) {
1664         bool mask_full = !mask || *mask == UINT8_MAX;
1665
1666         ds_put_format(ds, "%s=%#"PRIx8, name, key);
1667         if (!mask_full) { /* Partially masked. */
1668             ds_put_format(ds, "/%#"PRIx8, *mask);
1669         }
1670         ds_put_char(ds, ',');
1671     }
1672 }
1673
1674 static void
1675 format_u8u(struct ds *ds, const char *name, uint8_t key,
1676            const uint8_t *mask, bool verbose)
1677 {
1678     bool mask_empty = mask && !*mask;
1679
1680     if (verbose || !mask_empty) {
1681         bool mask_full = !mask || *mask == UINT8_MAX;
1682
1683         ds_put_format(ds, "%s=%"PRIu8, name, key);
1684         if (!mask_full) { /* Partially masked. */
1685             ds_put_format(ds, "/%#"PRIx8, *mask);
1686         }
1687         ds_put_char(ds, ',');
1688     }
1689 }
1690
1691 static void
1692 format_be16(struct ds *ds, const char *name, ovs_be16 key,
1693             const ovs_be16 *mask, bool verbose)
1694 {
1695     bool mask_empty = mask && !*mask;
1696
1697     if (verbose || !mask_empty) {
1698         bool mask_full = !mask || *mask == OVS_BE16_MAX;
1699
1700         ds_put_format(ds, "%s=%"PRIu16, name, ntohs(key));
1701         if (!mask_full) { /* Partially masked. */
1702             ds_put_format(ds, "/%#"PRIx16, ntohs(*mask));
1703         }
1704         ds_put_char(ds, ',');
1705     }
1706 }
1707
1708 static void
1709 format_tun_flags(struct ds *ds, const char *name, uint16_t key,
1710                  const uint16_t *mask, bool verbose)
1711 {
1712     bool mask_empty = mask && !*mask;
1713
1714     if (verbose || !mask_empty) {
1715         bool mask_full = !mask || (*mask & FLOW_TNL_F_MASK) == FLOW_TNL_F_MASK;
1716
1717         ds_put_cstr(ds, name);
1718         ds_put_char(ds, '(');
1719         if (!mask_full) { /* Partially masked. */
1720             format_flags_masked(ds, NULL, flow_tun_flag_to_string, key, *mask);
1721         } else { /* Fully masked. */
1722             format_flags(ds, flow_tun_flag_to_string, key, ',');
1723         }
1724         ds_put_cstr(ds, "),");
1725     }
1726 }
1727
1728 static void
1729 format_frag(struct ds *ds, const char *name, uint8_t key,
1730             const uint8_t *mask, bool verbose)
1731 {
1732     bool mask_empty = mask && !*mask;
1733
1734     /* ODP frag is an enumeration field; partial masks are not meaningful. */
1735     if (verbose || !mask_empty) {
1736         bool mask_full = !mask || *mask == UINT8_MAX;
1737
1738         if (!mask_full) { /* Partially masked. */
1739             ds_put_format(ds, "error: partial mask not supported for frag (%#"
1740                           PRIx8"),", *mask);
1741         } else {
1742             ds_put_format(ds, "%s=%s,", name, ovs_frag_type_to_string(key));
1743         }
1744     }
1745 }
1746
1747 #define MASK(PTR, FIELD) PTR ? &PTR->FIELD : NULL
1748
1749 static void
1750 format_odp_key_attr(const struct nlattr *a, const struct nlattr *ma,
1751                     const struct hmap *portno_names, struct ds *ds,
1752                     bool verbose)
1753 {
1754     enum ovs_key_attr attr = nl_attr_type(a);
1755     char namebuf[OVS_KEY_ATTR_BUFSIZE];
1756     int expected_len;
1757     bool is_exact;
1758
1759     is_exact = ma ? odp_mask_attr_is_exact(ma) : true;
1760
1761     ds_put_cstr(ds, ovs_key_attr_to_string(attr, namebuf, sizeof namebuf));
1762
1763     {
1764         expected_len = odp_flow_key_attr_len(nl_attr_type(a));
1765         if (expected_len != -2) {
1766             bool bad_key_len = nl_attr_get_size(a) != expected_len;
1767             bool bad_mask_len = ma && nl_attr_get_size(ma) != expected_len;
1768
1769             if (bad_key_len || bad_mask_len) {
1770                 if (bad_key_len) {
1771                     ds_put_format(ds, "(bad key length %"PRIuSIZE", expected %d)(",
1772                                   nl_attr_get_size(a), expected_len);
1773                 }
1774                 format_generic_odp_key(a, ds);
1775                 if (ma) {
1776                     ds_put_char(ds, '/');
1777                     if (bad_mask_len) {
1778                         ds_put_format(ds, "(bad mask length %"PRIuSIZE", expected %d)(",
1779                                       nl_attr_get_size(ma), expected_len);
1780                     }
1781                     format_generic_odp_key(ma, ds);
1782                 }
1783                 ds_put_char(ds, ')');
1784                 return;
1785             }
1786         }
1787     }
1788
1789     ds_put_char(ds, '(');
1790     switch (attr) {
1791     case OVS_KEY_ATTR_ENCAP:
1792         if (ma && nl_attr_get_size(ma) && nl_attr_get_size(a)) {
1793             odp_flow_format(nl_attr_get(a), nl_attr_get_size(a),
1794                             nl_attr_get(ma), nl_attr_get_size(ma), NULL, ds,
1795                             verbose);
1796         } else if (nl_attr_get_size(a)) {
1797             odp_flow_format(nl_attr_get(a), nl_attr_get_size(a), NULL, 0, NULL,
1798                             ds, verbose);
1799         }
1800         break;
1801
1802     case OVS_KEY_ATTR_PRIORITY:
1803     case OVS_KEY_ATTR_SKB_MARK:
1804     case OVS_KEY_ATTR_DP_HASH:
1805     case OVS_KEY_ATTR_RECIRC_ID:
1806         ds_put_format(ds, "%#"PRIx32, nl_attr_get_u32(a));
1807         if (!is_exact) {
1808             ds_put_format(ds, "/%#"PRIx32, nl_attr_get_u32(ma));
1809         }
1810         break;
1811
1812     case OVS_KEY_ATTR_TUNNEL: {
1813         struct flow_tnl key, mask_;
1814         struct flow_tnl *mask = ma ? &mask_ : NULL;
1815
1816         if (mask) {
1817             memset(mask, 0, sizeof *mask);
1818             odp_tun_key_from_attr(ma, mask);
1819         }
1820         memset(&key, 0, sizeof key);
1821         if (odp_tun_key_from_attr(a, &key) == ODP_FIT_ERROR) {
1822             ds_put_format(ds, "error");
1823             return;
1824         }
1825         format_be64(ds, "tun_id", key.tun_id, MASK(mask, tun_id), verbose);
1826         format_ipv4(ds, "src", key.ip_src, MASK(mask, ip_src), verbose);
1827         format_ipv4(ds, "dst", key.ip_dst, MASK(mask, ip_dst), verbose);
1828         format_u8x(ds, "tos", key.ip_tos, MASK(mask, ip_tos), verbose);
1829         format_u8u(ds, "ttl", key.ip_ttl, MASK(mask, ip_ttl), verbose);
1830         format_be16(ds, "tp_src", key.tp_src, MASK(mask, tp_src), verbose);
1831         format_be16(ds, "tp_dst", key.tp_dst, MASK(mask, tp_dst), verbose);
1832         format_be16(ds, "gbp_id", key.gbp_id, MASK(mask, gbp_id), verbose);
1833         format_u8x(ds, "gbp_flags", key.gbp_flags, MASK(mask, gbp_flags), verbose);
1834         format_tun_flags(ds, "flags", key.flags, MASK(mask, flags), verbose);
1835         ds_chomp(ds, ',');
1836         break;
1837     }
1838     case OVS_KEY_ATTR_IN_PORT:
1839         if (portno_names && verbose && is_exact) {
1840             char *name = odp_portno_names_get(portno_names,
1841                             u32_to_odp(nl_attr_get_u32(a)));
1842             if (name) {
1843                 ds_put_format(ds, "%s", name);
1844             } else {
1845                 ds_put_format(ds, "%"PRIu32, nl_attr_get_u32(a));
1846             }
1847         } else {
1848             ds_put_format(ds, "%"PRIu32, nl_attr_get_u32(a));
1849             if (!is_exact) {
1850                 ds_put_format(ds, "/%#"PRIx32, nl_attr_get_u32(ma));
1851             }
1852         }
1853         break;
1854
1855     case OVS_KEY_ATTR_ETHERNET: {
1856         const struct ovs_key_ethernet *mask = ma ? nl_attr_get(ma) : NULL;
1857         const struct ovs_key_ethernet *key = nl_attr_get(a);
1858
1859         format_eth(ds, "src", key->eth_src, MASK(mask, eth_src), verbose);
1860         format_eth(ds, "dst", key->eth_dst, MASK(mask, eth_dst), verbose);
1861         ds_chomp(ds, ',');
1862         break;
1863     }
1864     case OVS_KEY_ATTR_VLAN:
1865         format_vlan_tci(ds, nl_attr_get_be16(a),
1866                         ma ? nl_attr_get_be16(ma) : OVS_BE16_MAX, verbose);
1867         break;
1868
1869     case OVS_KEY_ATTR_MPLS: {
1870         const struct ovs_key_mpls *mpls_key = nl_attr_get(a);
1871         const struct ovs_key_mpls *mpls_mask = NULL;
1872         size_t size = nl_attr_get_size(a);
1873
1874         if (!size || size % sizeof *mpls_key) {
1875             ds_put_format(ds, "(bad key length %"PRIuSIZE")", size);
1876             return;
1877         }
1878         if (!is_exact) {
1879             mpls_mask = nl_attr_get(ma);
1880             if (size != nl_attr_get_size(ma)) {
1881                 ds_put_format(ds, "(key length %"PRIuSIZE" != "
1882                               "mask length %"PRIuSIZE")",
1883                               size, nl_attr_get_size(ma));
1884                 return;
1885             }
1886         }
1887         format_mpls(ds, mpls_key, mpls_mask, size / sizeof *mpls_key);
1888         break;
1889     }
1890     case OVS_KEY_ATTR_ETHERTYPE:
1891         ds_put_format(ds, "0x%04"PRIx16, ntohs(nl_attr_get_be16(a)));
1892         if (!is_exact) {
1893             ds_put_format(ds, "/0x%04"PRIx16, ntohs(nl_attr_get_be16(ma)));
1894         }
1895         break;
1896
1897     case OVS_KEY_ATTR_IPV4: {
1898         const struct ovs_key_ipv4 *key = nl_attr_get(a);
1899         const struct ovs_key_ipv4 *mask = ma ? nl_attr_get(ma) : NULL;
1900
1901         format_ipv4(ds, "src", key->ipv4_src, MASK(mask, ipv4_src), verbose);
1902         format_ipv4(ds, "dst", key->ipv4_dst, MASK(mask, ipv4_dst), verbose);
1903         format_u8u(ds, "proto", key->ipv4_proto, MASK(mask, ipv4_proto),
1904                       verbose);
1905         format_u8x(ds, "tos", key->ipv4_tos, MASK(mask, ipv4_tos), verbose);
1906         format_u8u(ds, "ttl", key->ipv4_ttl, MASK(mask, ipv4_ttl), verbose);
1907         format_frag(ds, "frag", key->ipv4_frag, MASK(mask, ipv4_frag),
1908                     verbose);
1909         ds_chomp(ds, ',');
1910         break;
1911     }
1912     case OVS_KEY_ATTR_IPV6: {
1913         const struct ovs_key_ipv6 *key = nl_attr_get(a);
1914         const struct ovs_key_ipv6 *mask = ma ? nl_attr_get(ma) : NULL;
1915
1916         format_ipv6(ds, "src", key->ipv6_src, MASK(mask, ipv6_src), verbose);
1917         format_ipv6(ds, "dst", key->ipv6_dst, MASK(mask, ipv6_dst), verbose);
1918         format_ipv6_label(ds, "label", key->ipv6_label, MASK(mask, ipv6_label),
1919                           verbose);
1920         format_u8u(ds, "proto", key->ipv6_proto, MASK(mask, ipv6_proto),
1921                       verbose);
1922         format_u8x(ds, "tclass", key->ipv6_tclass, MASK(mask, ipv6_tclass),
1923                       verbose);
1924         format_u8u(ds, "hlimit", key->ipv6_hlimit, MASK(mask, ipv6_hlimit),
1925                       verbose);
1926         format_frag(ds, "frag", key->ipv6_frag, MASK(mask, ipv6_frag),
1927                     verbose);
1928         ds_chomp(ds, ',');
1929         break;
1930     }
1931         /* These have the same structure and format. */
1932     case OVS_KEY_ATTR_TCP:
1933     case OVS_KEY_ATTR_UDP:
1934     case OVS_KEY_ATTR_SCTP: {
1935         const struct ovs_key_tcp *key = nl_attr_get(a);
1936         const struct ovs_key_tcp *mask = ma ? nl_attr_get(ma) : NULL;
1937
1938         format_be16(ds, "src", key->tcp_src, MASK(mask, tcp_src), verbose);
1939         format_be16(ds, "dst", key->tcp_dst, MASK(mask, tcp_dst), verbose);
1940         ds_chomp(ds, ',');
1941         break;
1942     }
1943     case OVS_KEY_ATTR_TCP_FLAGS:
1944         if (!is_exact) {
1945             format_flags_masked(ds, NULL, packet_tcp_flag_to_string,
1946                                 ntohs(nl_attr_get_be16(a)),
1947                                 ntohs(nl_attr_get_be16(ma)));
1948         } else {
1949             format_flags(ds, packet_tcp_flag_to_string,
1950                          ntohs(nl_attr_get_be16(a)), ',');
1951         }
1952         break;
1953
1954     case OVS_KEY_ATTR_ICMP: {
1955         const struct ovs_key_icmp *key = nl_attr_get(a);
1956         const struct ovs_key_icmp *mask = ma ? nl_attr_get(ma) : NULL;
1957
1958         format_u8u(ds, "type", key->icmp_type, MASK(mask, icmp_type), verbose);
1959         format_u8u(ds, "code", key->icmp_code, MASK(mask, icmp_code), verbose);
1960         ds_chomp(ds, ',');
1961         break;
1962     }
1963     case OVS_KEY_ATTR_ICMPV6: {
1964         const struct ovs_key_icmpv6 *key = nl_attr_get(a);
1965         const struct ovs_key_icmpv6 *mask = ma ? nl_attr_get(ma) : NULL;
1966
1967         format_u8u(ds, "type", key->icmpv6_type, MASK(mask, icmpv6_type),
1968                    verbose);
1969         format_u8u(ds, "code", key->icmpv6_code, MASK(mask, icmpv6_code),
1970                    verbose);
1971         ds_chomp(ds, ',');
1972         break;
1973     }
1974     case OVS_KEY_ATTR_ARP: {
1975         const struct ovs_key_arp *mask = ma ? nl_attr_get(ma) : NULL;
1976         const struct ovs_key_arp *key = nl_attr_get(a);
1977
1978         format_ipv4(ds, "sip", key->arp_sip, MASK(mask, arp_sip), verbose);
1979         format_ipv4(ds, "tip", key->arp_tip, MASK(mask, arp_tip), verbose);
1980         format_be16(ds, "op", key->arp_op, MASK(mask, arp_op), verbose);
1981         format_eth(ds, "sha", key->arp_sha, MASK(mask, arp_sha), verbose);
1982         format_eth(ds, "tha", key->arp_tha, MASK(mask, arp_tha), verbose);
1983         ds_chomp(ds, ',');
1984         break;
1985     }
1986     case OVS_KEY_ATTR_ND: {
1987         const struct ovs_key_nd *mask = ma ? nl_attr_get(ma) : NULL;
1988         const struct ovs_key_nd *key = nl_attr_get(a);
1989
1990         format_ipv6(ds, "target", key->nd_target, MASK(mask, nd_target),
1991                     verbose);
1992         format_eth(ds, "sll", key->nd_sll, MASK(mask, nd_sll), verbose);
1993         format_eth(ds, "tll", key->nd_tll, MASK(mask, nd_tll), verbose);
1994
1995         ds_chomp(ds, ',');
1996         break;
1997     }
1998     case OVS_KEY_ATTR_UNSPEC:
1999     case __OVS_KEY_ATTR_MAX:
2000     default:
2001         format_generic_odp_key(a, ds);
2002         if (!is_exact) {
2003             ds_put_char(ds, '/');
2004             format_generic_odp_key(ma, ds);
2005         }
2006         break;
2007     }
2008     ds_put_char(ds, ')');
2009 }
2010
2011 static struct nlattr *
2012 generate_all_wildcard_mask(struct ofpbuf *ofp, const struct nlattr *key)
2013 {
2014     const struct nlattr *a;
2015     unsigned int left;
2016     int type = nl_attr_type(key);
2017     int size = nl_attr_get_size(key);
2018
2019     if (odp_flow_key_attr_len(type) >=0) {
2020         nl_msg_put_unspec_zero(ofp, type, size);
2021     } else {
2022         size_t nested_mask;
2023
2024         nested_mask = nl_msg_start_nested(ofp, type);
2025         NL_ATTR_FOR_EACH(a, left, key, nl_attr_get_size(key)) {
2026             generate_all_wildcard_mask(ofp, nl_attr_get(a));
2027         }
2028         nl_msg_end_nested(ofp, nested_mask);
2029     }
2030
2031     return ofp->base;
2032 }
2033
2034 int
2035 odp_ufid_from_string(const char *s_, ovs_u128 *ufid)
2036 {
2037     const char *s = s_;
2038
2039     if (ovs_scan(s, "ufid:")) {
2040         size_t n;
2041
2042         s += 5;
2043         if (ovs_scan(s, "0x")) {
2044             s += 2;
2045         }
2046
2047         n = strspn(s, "0123456789abcdefABCDEF");
2048         if (n != 32) {
2049             return -EINVAL;
2050         }
2051
2052         if (!ovs_scan(s, "%16"SCNx64"%16"SCNx64, &ufid->u64.hi,
2053                       &ufid->u64.lo)) {
2054             return -EINVAL;
2055         }
2056         s += n;
2057         s += strspn(s, delimiters);
2058
2059         return s - s_;
2060     }
2061
2062     return 0;
2063 }
2064
2065 void
2066 odp_format_ufid(const ovs_u128 *ufid, struct ds *ds)
2067 {
2068     ds_put_format(ds, "ufid:%016"PRIx64"%016"PRIx64, ufid->u64.hi,
2069                   ufid->u64.lo);
2070 }
2071
2072 /* Appends to 'ds' a string representation of the 'key_len' bytes of
2073  * OVS_KEY_ATTR_* attributes in 'key'. If non-null, additionally formats the
2074  * 'mask_len' bytes of 'mask' which apply to 'key'. If 'portno_names' is
2075  * non-null and 'verbose' is true, translates odp port number to its name. */
2076 void
2077 odp_flow_format(const struct nlattr *key, size_t key_len,
2078                 const struct nlattr *mask, size_t mask_len,
2079                 const struct hmap *portno_names, struct ds *ds, bool verbose)
2080 {
2081     if (key_len) {
2082         const struct nlattr *a;
2083         unsigned int left;
2084         bool has_ethtype_key = false;
2085         const struct nlattr *ma = NULL;
2086         struct ofpbuf ofp;
2087         bool first_field = true;
2088
2089         ofpbuf_init(&ofp, 100);
2090         NL_ATTR_FOR_EACH (a, left, key, key_len) {
2091             bool is_nested_attr;
2092             bool is_wildcard = false;
2093             int attr_type = nl_attr_type(a);
2094
2095             if (attr_type == OVS_KEY_ATTR_ETHERTYPE) {
2096                 has_ethtype_key = true;
2097             }
2098
2099             is_nested_attr = (odp_flow_key_attr_len(attr_type) == -2);
2100
2101             if (mask && mask_len) {
2102                 ma = nl_attr_find__(mask, mask_len, nl_attr_type(a));
2103                 is_wildcard = ma ? odp_mask_attr_is_wildcard(ma) : true;
2104             }
2105
2106             if (verbose || !is_wildcard  || is_nested_attr) {
2107                 if (is_wildcard && !ma) {
2108                     ma = generate_all_wildcard_mask(&ofp, a);
2109                 }
2110                 if (!first_field) {
2111                     ds_put_char(ds, ',');
2112                 }
2113                 format_odp_key_attr(a, ma, portno_names, ds, verbose);
2114                 first_field = false;
2115             }
2116             ofpbuf_clear(&ofp);
2117         }
2118         ofpbuf_uninit(&ofp);
2119
2120         if (left) {
2121             int i;
2122
2123             if (left == key_len) {
2124                 ds_put_cstr(ds, "<empty>");
2125             }
2126             ds_put_format(ds, ",***%u leftover bytes*** (", left);
2127             for (i = 0; i < left; i++) {
2128                 ds_put_format(ds, "%02x", ((const uint8_t *) a)[i]);
2129             }
2130             ds_put_char(ds, ')');
2131         }
2132         if (!has_ethtype_key) {
2133             ma = nl_attr_find__(mask, mask_len, OVS_KEY_ATTR_ETHERTYPE);
2134             if (ma) {
2135                 ds_put_format(ds, ",eth_type(0/0x%04"PRIx16")",
2136                               ntohs(nl_attr_get_be16(ma)));
2137             }
2138         }
2139     } else {
2140         ds_put_cstr(ds, "<empty>");
2141     }
2142 }
2143
2144 /* Appends to 'ds' a string representation of the 'key_len' bytes of
2145  * OVS_KEY_ATTR_* attributes in 'key'. */
2146 void
2147 odp_flow_key_format(const struct nlattr *key,
2148                     size_t key_len, struct ds *ds)
2149 {
2150     odp_flow_format(key, key_len, NULL, 0, NULL, ds, true);
2151 }
2152
2153 static bool
2154 ovs_frag_type_from_string(const char *s, enum ovs_frag_type *type)
2155 {
2156     if (!strcasecmp(s, "no")) {
2157         *type = OVS_FRAG_TYPE_NONE;
2158     } else if (!strcasecmp(s, "first")) {
2159         *type = OVS_FRAG_TYPE_FIRST;
2160     } else if (!strcasecmp(s, "later")) {
2161         *type = OVS_FRAG_TYPE_LATER;
2162     } else {
2163         return false;
2164     }
2165     return true;
2166 }
2167
2168 /* Parsing. */
2169
2170 static int
2171 scan_eth(const char *s, uint8_t (*key)[ETH_ADDR_LEN],
2172          uint8_t (*mask)[ETH_ADDR_LEN])
2173 {
2174     int n;
2175
2176     if (ovs_scan(s, ETH_ADDR_SCAN_FMT"%n", ETH_ADDR_SCAN_ARGS(*key), &n)) {
2177         int len = n;
2178
2179         if (mask) {
2180             if (ovs_scan(s + len, "/"ETH_ADDR_SCAN_FMT"%n",
2181                          ETH_ADDR_SCAN_ARGS(*mask), &n)) {
2182                 len += n;
2183             } else {
2184                 memset(mask, 0xff, sizeof *mask);
2185             }
2186         }
2187         return len;
2188     }
2189     return 0;
2190 }
2191
2192 static int
2193 scan_ipv4(const char *s, ovs_be32 *key, ovs_be32 *mask)
2194 {
2195     int n;
2196
2197     if (ovs_scan(s, IP_SCAN_FMT"%n", IP_SCAN_ARGS(key), &n)) {
2198         int len = n;
2199
2200         if (mask) {
2201             if (ovs_scan(s + len, "/"IP_SCAN_FMT"%n",
2202                          IP_SCAN_ARGS(mask), &n)) {
2203                 len += n;
2204             } else {
2205                 *mask = OVS_BE32_MAX;
2206             }
2207         }
2208         return len;
2209     }
2210     return 0;
2211 }
2212
2213 static int
2214 scan_ipv6(const char *s, ovs_be32 (*key)[4], ovs_be32 (*mask)[4])
2215 {
2216     int n;
2217     char ipv6_s[IPV6_SCAN_LEN + 1];
2218
2219     if (ovs_scan(s, IPV6_SCAN_FMT"%n", ipv6_s, &n)
2220         && inet_pton(AF_INET6, ipv6_s, key) == 1) {
2221         int len = n;
2222
2223         if (mask) {
2224             if (ovs_scan(s + len, "/"IPV6_SCAN_FMT"%n", ipv6_s, &n)
2225                 && inet_pton(AF_INET6, ipv6_s, mask) == 1) {
2226                 len += n;
2227             } else {
2228                 memset(mask, 0xff, sizeof *mask);
2229             }
2230         }
2231         return len;
2232     }
2233     return 0;
2234 }
2235
2236 static int
2237 scan_ipv6_label(const char *s, ovs_be32 *key, ovs_be32 *mask)
2238 {
2239     int key_, mask_;
2240     int n;
2241
2242     if (ovs_scan(s, "%i%n", &key_, &n)
2243         && (key_ & ~IPV6_LABEL_MASK) == 0) {
2244         int len = n;
2245
2246         *key = htonl(key_);
2247         if (mask) {
2248             if (ovs_scan(s + len, "/%i%n", &mask_, &n)
2249                 && (mask_ & ~IPV6_LABEL_MASK) == 0) {
2250                 len += n;
2251                 *mask = htonl(mask_);
2252             } else {
2253                 *mask = htonl(IPV6_LABEL_MASK);
2254             }
2255         }
2256         return len;
2257     }
2258     return 0;
2259 }
2260
2261 static int
2262 scan_u8(const char *s, uint8_t *key, uint8_t *mask)
2263 {
2264     int n;
2265
2266     if (ovs_scan(s, "%"SCNi8"%n", key, &n)) {
2267         int len = n;
2268
2269         if (mask) {
2270             if (ovs_scan(s + len, "/%"SCNi8"%n", mask, &n)) {
2271                 len += n;
2272             } else {
2273                 *mask = UINT8_MAX;
2274             }
2275         }
2276         return len;
2277     }
2278     return 0;
2279 }
2280
2281 static int
2282 scan_u32(const char *s, uint32_t *key, uint32_t *mask)
2283 {
2284     int n;
2285
2286     if (ovs_scan(s, "%"SCNi32"%n", key, &n)) {
2287         int len = n;
2288
2289         if (mask) {
2290             if (ovs_scan(s + len, "/%"SCNi32"%n", mask, &n)) {
2291                 len += n;
2292             } else {
2293                 *mask = UINT32_MAX;
2294             }
2295         }
2296         return len;
2297     }
2298     return 0;
2299 }
2300
2301 static int
2302 scan_be16(const char *s, ovs_be16 *key, ovs_be16 *mask)
2303 {
2304     uint16_t key_, mask_;
2305     int n;
2306
2307     if (ovs_scan(s, "%"SCNi16"%n", &key_, &n)) {
2308         int len = n;
2309
2310         *key = htons(key_);
2311         if (mask) {
2312             if (ovs_scan(s + len, "/%"SCNi16"%n", &mask_, &n)) {
2313                 len += n;
2314                 *mask = htons(mask_);
2315             } else {
2316                 *mask = OVS_BE16_MAX;
2317             }
2318         }
2319         return len;
2320     }
2321     return 0;
2322 }
2323
2324 static int
2325 scan_be64(const char *s, ovs_be64 *key, ovs_be64 *mask)
2326 {
2327     uint64_t key_, mask_;
2328     int n;
2329
2330     if (ovs_scan(s, "%"SCNi64"%n", &key_, &n)) {
2331         int len = n;
2332
2333         *key = htonll(key_);
2334         if (mask) {
2335             if (ovs_scan(s + len, "/%"SCNi64"%n", &mask_, &n)) {
2336                 len += n;
2337                 *mask = htonll(mask_);
2338             } else {
2339                 *mask = OVS_BE64_MAX;
2340             }
2341         }
2342         return len;
2343     }
2344     return 0;
2345 }
2346
2347 static int
2348 scan_tun_flags(const char *s, uint16_t *key, uint16_t *mask)
2349 {
2350     uint32_t flags, fmask;
2351     int n;
2352
2353     n = parse_flags(s, flow_tun_flag_to_string, &flags,
2354                     FLOW_TNL_F_MASK, mask ? &fmask : NULL);
2355     if (n >= 0 && s[n] == ')') {
2356         *key = flags;
2357         if (mask) {
2358             *mask = fmask;
2359         }
2360         return n + 1;
2361     }
2362     return 0;
2363 }
2364
2365 static int
2366 scan_tcp_flags(const char *s, ovs_be16 *key, ovs_be16 *mask)
2367 {
2368     uint32_t flags, fmask;
2369     int n;
2370
2371     n = parse_flags(s, packet_tcp_flag_to_string, &flags,
2372                     TCP_FLAGS(OVS_BE16_MAX), mask ? &fmask : NULL);
2373     if (n >= 0) {
2374         *key = htons(flags);
2375         if (mask) {
2376             *mask = htons(fmask);
2377         }
2378         return n;
2379     }
2380     return 0;
2381 }
2382
2383 static int
2384 scan_frag(const char *s, uint8_t *key, uint8_t *mask)
2385 {
2386     int n;
2387     char frag[8];
2388     enum ovs_frag_type frag_type;
2389
2390     if (ovs_scan(s, "%7[a-z]%n", frag, &n)
2391         && ovs_frag_type_from_string(frag, &frag_type)) {
2392         int len = n;
2393
2394         *key = frag_type;
2395         if (mask) {
2396             *mask = UINT8_MAX;
2397         }
2398         return len;
2399     }
2400     return 0;
2401 }
2402
2403 static int
2404 scan_port(const char *s, uint32_t *key, uint32_t *mask,
2405           const struct simap *port_names)
2406 {
2407     int n;
2408
2409     if (ovs_scan(s, "%"SCNi32"%n", key, &n)) {
2410         int len = n;
2411
2412         if (mask) {
2413             if (ovs_scan(s + len, "/%"SCNi32"%n", mask, &n)) {
2414                 len += n;
2415             } else {
2416                 *mask = UINT32_MAX;
2417             }
2418         }
2419         return len;
2420     } else if (port_names) {
2421         const struct simap_node *node;
2422         int len;
2423
2424         len = strcspn(s, ")");
2425         node = simap_find_len(port_names, s, len);
2426         if (node) {
2427             *key = node->data;
2428
2429             if (mask) {
2430                 *mask = UINT32_MAX;
2431             }
2432             return len;
2433         }
2434     }
2435     return 0;
2436 }
2437
2438 /* Helper for vlan parsing. */
2439 struct ovs_key_vlan__ {
2440     ovs_be16 tci;
2441 };
2442
2443 static bool
2444 set_be16_bf(ovs_be16 *bf, uint8_t bits, uint8_t offset, uint16_t value)
2445 {
2446     const uint16_t mask = ((1U << bits) - 1) << offset;
2447
2448     if (value >> bits) {
2449         return false;
2450     }
2451
2452     *bf = htons((ntohs(*bf) & ~mask) | (value << offset));
2453     return true;
2454 }
2455
2456 static int
2457 scan_be16_bf(const char *s, ovs_be16 *key, ovs_be16 *mask, uint8_t bits,
2458              uint8_t offset)
2459 {
2460     uint16_t key_, mask_;
2461     int n;
2462
2463     if (ovs_scan(s, "%"SCNi16"%n", &key_, &n)) {
2464         int len = n;
2465
2466         if (set_be16_bf(key, bits, offset, key_)) {
2467             if (mask) {
2468                 if (ovs_scan(s + len, "/%"SCNi16"%n", &mask_, &n)) {
2469                     len += n;
2470
2471                     if (!set_be16_bf(mask, bits, offset, mask_)) {
2472                         return 0;
2473                     }
2474                 } else {
2475                     *mask |= htons(((1U << bits) - 1) << offset);
2476                 }
2477             }
2478             return len;
2479         }
2480     }
2481     return 0;
2482 }
2483
2484 static int
2485 scan_vid(const char *s, ovs_be16 *key, ovs_be16 *mask)
2486 {
2487     return scan_be16_bf(s, key, mask, 12, VLAN_VID_SHIFT);
2488 }
2489
2490 static int
2491 scan_pcp(const char *s, ovs_be16 *key, ovs_be16 *mask)
2492 {
2493     return scan_be16_bf(s, key, mask, 3, VLAN_PCP_SHIFT);
2494 }
2495
2496 static int
2497 scan_cfi(const char *s, ovs_be16 *key, ovs_be16 *mask)
2498 {
2499     return scan_be16_bf(s, key, mask, 1, VLAN_CFI_SHIFT);
2500 }
2501
2502 /* For MPLS. */
2503 static bool
2504 set_be32_bf(ovs_be32 *bf, uint8_t bits, uint8_t offset, uint32_t value)
2505 {
2506     const uint32_t mask = ((1U << bits) - 1) << offset;
2507
2508     if (value >> bits) {
2509         return false;
2510     }
2511
2512     *bf = htonl((ntohl(*bf) & ~mask) | (value << offset));
2513     return true;
2514 }
2515
2516 static int
2517 scan_be32_bf(const char *s, ovs_be32 *key, ovs_be32 *mask, uint8_t bits,
2518              uint8_t offset)
2519 {
2520     uint32_t key_, mask_;
2521     int n;
2522
2523     if (ovs_scan(s, "%"SCNi32"%n", &key_, &n)) {
2524         int len = n;
2525
2526         if (set_be32_bf(key, bits, offset, key_)) {
2527             if (mask) {
2528                 if (ovs_scan(s + len, "/%"SCNi32"%n", &mask_, &n)) {
2529                     len += n;
2530
2531                     if (!set_be32_bf(mask, bits, offset, mask_)) {
2532                         return 0;
2533                     }
2534                 } else {
2535                     *mask |= htonl(((1U << bits) - 1) << offset);
2536                 }
2537             }
2538             return len;
2539         }
2540     }
2541     return 0;
2542 }
2543
2544 static int
2545 scan_mpls_label(const char *s, ovs_be32 *key, ovs_be32 *mask)
2546 {
2547     return scan_be32_bf(s, key, mask, 20, MPLS_LABEL_SHIFT);
2548 }
2549
2550 static int
2551 scan_mpls_tc(const char *s, ovs_be32 *key, ovs_be32 *mask)
2552 {
2553     return scan_be32_bf(s, key, mask, 3, MPLS_TC_SHIFT);
2554 }
2555
2556 static int
2557 scan_mpls_ttl(const char *s, ovs_be32 *key, ovs_be32 *mask)
2558 {
2559     return scan_be32_bf(s, key, mask, 8, MPLS_TTL_SHIFT);
2560 }
2561
2562 static int
2563 scan_mpls_bos(const char *s, ovs_be32 *key, ovs_be32 *mask)
2564 {
2565     return scan_be32_bf(s, key, mask, 1, MPLS_BOS_SHIFT);
2566 }
2567
2568 /* ATTR is compile-time constant, so only the case with correct data type
2569  * will be used.  However, the compiler complains about the data  type for
2570  * the other cases, so we must cast to make the compiler silent. */
2571 #define SCAN_PUT_ATTR(BUF, ATTR, DATA)                          \
2572     if ((ATTR) == OVS_KEY_ATTR_TUNNEL) {                              \
2573         tun_key_to_attr(BUF, (const struct flow_tnl *)(void *)&(DATA)); \
2574     } else {                                                    \
2575         nl_msg_put_unspec(BUF, ATTR, &(DATA), sizeof (DATA));   \
2576     }
2577
2578 #define SCAN_IF(NAME)                           \
2579     if (strncmp(s, NAME, strlen(NAME)) == 0) {  \
2580         const char *start = s;                  \
2581         int len;                                \
2582                                                 \
2583         s += strlen(NAME)
2584
2585 /* Usually no special initialization is needed. */
2586 #define SCAN_BEGIN(NAME, TYPE)                  \
2587     SCAN_IF(NAME);                              \
2588         TYPE skey, smask;                       \
2589         memset(&skey, 0, sizeof skey);          \
2590         memset(&smask, 0, sizeof smask);        \
2591         do {                                    \
2592             len = 0;
2593
2594 /* VLAN needs special initialization. */
2595 #define SCAN_BEGIN_INIT(NAME, TYPE, KEY_INIT, MASK_INIT)  \
2596     SCAN_IF(NAME);                                        \
2597         TYPE skey = KEY_INIT;                       \
2598         TYPE smask = MASK_INIT;                     \
2599         do {                                        \
2600             len = 0;
2601
2602 /* Scan unnamed entry as 'TYPE' */
2603 #define SCAN_TYPE(TYPE, KEY, MASK)              \
2604     len = scan_##TYPE(s, KEY, MASK);            \
2605     if (len == 0) {                             \
2606         return -EINVAL;                         \
2607     }                                           \
2608     s += len
2609
2610 /* Scan named ('NAME') entry 'FIELD' as 'TYPE'. */
2611 #define SCAN_FIELD(NAME, TYPE, FIELD)                                   \
2612     if (strncmp(s, NAME, strlen(NAME)) == 0) {                          \
2613         s += strlen(NAME);                                              \
2614         SCAN_TYPE(TYPE, &skey.FIELD, mask ? &smask.FIELD : NULL);       \
2615         continue;                                                       \
2616     }
2617
2618 #define SCAN_FINISH()                           \
2619         } while (*s++ == ',' && len != 0);      \
2620         if (s[-1] != ')') {                     \
2621             return -EINVAL;                     \
2622         }
2623
2624 #define SCAN_FINISH_SINGLE()                    \
2625         } while (false);                        \
2626         if (*s++ != ')') {                      \
2627             return -EINVAL;                     \
2628         }
2629
2630 #define SCAN_PUT(ATTR)                                  \
2631         if (!mask || !is_all_zeros(&smask, sizeof smask)) { \
2632             SCAN_PUT_ATTR(key, ATTR, skey);             \
2633             if (mask) {                                 \
2634                 SCAN_PUT_ATTR(mask, ATTR, smask);       \
2635             }                                           \
2636         }
2637
2638 #define SCAN_END(ATTR)                                  \
2639         SCAN_FINISH();                                  \
2640         SCAN_PUT(ATTR);                                 \
2641         return s - start;                               \
2642     }
2643
2644 #define SCAN_END_SINGLE(ATTR)                           \
2645         SCAN_FINISH_SINGLE();                           \
2646         SCAN_PUT(ATTR);                                 \
2647         return s - start;                               \
2648     }
2649
2650 #define SCAN_SINGLE(NAME, TYPE, SCAN_AS, ATTR)       \
2651     SCAN_BEGIN(NAME, TYPE) {                         \
2652         SCAN_TYPE(SCAN_AS, &skey, &smask);           \
2653     } SCAN_END_SINGLE(ATTR)
2654
2655 #define SCAN_SINGLE_NO_MASK(NAME, TYPE, SCAN_AS, ATTR)       \
2656     SCAN_BEGIN(NAME, TYPE) {                         \
2657         SCAN_TYPE(SCAN_AS, &skey, NULL);           \
2658     } SCAN_END_SINGLE(ATTR)
2659
2660 /* scan_port needs one extra argument. */
2661 #define SCAN_SINGLE_PORT(NAME, TYPE, ATTR)  \
2662     SCAN_BEGIN(NAME, TYPE) {                            \
2663         len = scan_port(s, &skey, &smask, port_names);  \
2664         if (len == 0) {                                 \
2665             return -EINVAL;                             \
2666         }                                               \
2667         s += len;                                       \
2668     } SCAN_END_SINGLE(ATTR)
2669
2670 static int
2671 parse_odp_key_mask_attr(const char *s, const struct simap *port_names,
2672                         struct ofpbuf *key, struct ofpbuf *mask)
2673 {
2674     SCAN_SINGLE("skb_priority(", uint32_t, u32, OVS_KEY_ATTR_PRIORITY);
2675     SCAN_SINGLE("skb_mark(", uint32_t, u32, OVS_KEY_ATTR_SKB_MARK);
2676     SCAN_SINGLE_NO_MASK("recirc_id(", uint32_t, u32, OVS_KEY_ATTR_RECIRC_ID);
2677     SCAN_SINGLE("dp_hash(", uint32_t, u32, OVS_KEY_ATTR_DP_HASH);
2678
2679     SCAN_BEGIN("tunnel(", struct flow_tnl) {
2680         SCAN_FIELD("tun_id=", be64, tun_id);
2681         SCAN_FIELD("src=", ipv4, ip_src);
2682         SCAN_FIELD("dst=", ipv4, ip_dst);
2683         SCAN_FIELD("tos=", u8, ip_tos);
2684         SCAN_FIELD("ttl=", u8, ip_ttl);
2685         SCAN_FIELD("tp_src=", be16, tp_src);
2686         SCAN_FIELD("tp_dst=", be16, tp_dst);
2687         SCAN_FIELD("gbp_id=", be16, gbp_id);
2688         SCAN_FIELD("gbp_flags=", u8, gbp_flags);
2689         SCAN_FIELD("flags(", tun_flags, flags);
2690     } SCAN_END(OVS_KEY_ATTR_TUNNEL);
2691
2692     SCAN_SINGLE_PORT("in_port(", uint32_t, OVS_KEY_ATTR_IN_PORT);
2693
2694     SCAN_BEGIN("eth(", struct ovs_key_ethernet) {
2695         SCAN_FIELD("src=", eth, eth_src);
2696         SCAN_FIELD("dst=", eth, eth_dst);
2697     } SCAN_END(OVS_KEY_ATTR_ETHERNET);
2698
2699     SCAN_BEGIN_INIT("vlan(", struct ovs_key_vlan__,
2700                     { htons(VLAN_CFI) }, { htons(VLAN_CFI) }) {
2701         SCAN_FIELD("vid=", vid, tci);
2702         SCAN_FIELD("pcp=", pcp, tci);
2703         SCAN_FIELD("cfi=", cfi, tci);
2704     } SCAN_END(OVS_KEY_ATTR_VLAN);
2705
2706     SCAN_SINGLE("eth_type(", ovs_be16, be16, OVS_KEY_ATTR_ETHERTYPE);
2707
2708     SCAN_BEGIN("mpls(", struct ovs_key_mpls) {
2709         SCAN_FIELD("label=", mpls_label, mpls_lse);
2710         SCAN_FIELD("tc=", mpls_tc, mpls_lse);
2711         SCAN_FIELD("ttl=", mpls_ttl, mpls_lse);
2712         SCAN_FIELD("bos=", mpls_bos, mpls_lse);
2713     } SCAN_END(OVS_KEY_ATTR_MPLS);
2714
2715     SCAN_BEGIN("ipv4(", struct ovs_key_ipv4) {
2716         SCAN_FIELD("src=", ipv4, ipv4_src);
2717         SCAN_FIELD("dst=", ipv4, ipv4_dst);
2718         SCAN_FIELD("proto=", u8, ipv4_proto);
2719         SCAN_FIELD("tos=", u8, ipv4_tos);
2720         SCAN_FIELD("ttl=", u8, ipv4_ttl);
2721         SCAN_FIELD("frag=", frag, ipv4_frag);
2722     } SCAN_END(OVS_KEY_ATTR_IPV4);
2723
2724     SCAN_BEGIN("ipv6(", struct ovs_key_ipv6) {
2725         SCAN_FIELD("src=", ipv6, ipv6_src);
2726         SCAN_FIELD("dst=", ipv6, ipv6_dst);
2727         SCAN_FIELD("label=", ipv6_label, ipv6_label);
2728         SCAN_FIELD("proto=", u8, ipv6_proto);
2729         SCAN_FIELD("tclass=", u8, ipv6_tclass);
2730         SCAN_FIELD("hlimit=", u8, ipv6_hlimit);
2731         SCAN_FIELD("frag=", frag, ipv6_frag);
2732     } SCAN_END(OVS_KEY_ATTR_IPV6);
2733
2734     SCAN_BEGIN("tcp(", struct ovs_key_tcp) {
2735         SCAN_FIELD("src=", be16, tcp_src);
2736         SCAN_FIELD("dst=", be16, tcp_dst);
2737     } SCAN_END(OVS_KEY_ATTR_TCP);
2738
2739     SCAN_SINGLE("tcp_flags(", ovs_be16, tcp_flags, OVS_KEY_ATTR_TCP_FLAGS);
2740
2741     SCAN_BEGIN("udp(", struct ovs_key_udp) {
2742         SCAN_FIELD("src=", be16, udp_src);
2743         SCAN_FIELD("dst=", be16, udp_dst);
2744     } SCAN_END(OVS_KEY_ATTR_UDP);
2745
2746     SCAN_BEGIN("sctp(", struct ovs_key_sctp) {
2747         SCAN_FIELD("src=", be16, sctp_src);
2748         SCAN_FIELD("dst=", be16, sctp_dst);
2749     } SCAN_END(OVS_KEY_ATTR_SCTP);
2750
2751     SCAN_BEGIN("icmp(", struct ovs_key_icmp) {
2752         SCAN_FIELD("type=", u8, icmp_type);
2753         SCAN_FIELD("code=", u8, icmp_code);
2754     } SCAN_END(OVS_KEY_ATTR_ICMP);
2755
2756     SCAN_BEGIN("icmpv6(", struct ovs_key_icmpv6) {
2757         SCAN_FIELD("type=", u8, icmpv6_type);
2758         SCAN_FIELD("code=", u8, icmpv6_code);
2759     } SCAN_END(OVS_KEY_ATTR_ICMPV6);
2760
2761     SCAN_BEGIN("arp(", struct ovs_key_arp) {
2762         SCAN_FIELD("sip=", ipv4, arp_sip);
2763         SCAN_FIELD("tip=", ipv4, arp_tip);
2764         SCAN_FIELD("op=", be16, arp_op);
2765         SCAN_FIELD("sha=", eth, arp_sha);
2766         SCAN_FIELD("tha=", eth, arp_tha);
2767     } SCAN_END(OVS_KEY_ATTR_ARP);
2768
2769     SCAN_BEGIN("nd(", struct ovs_key_nd) {
2770         SCAN_FIELD("target=", ipv6, nd_target);
2771         SCAN_FIELD("sll=", eth, nd_sll);
2772         SCAN_FIELD("tll=", eth, nd_tll);
2773     } SCAN_END(OVS_KEY_ATTR_ND);
2774
2775     /* Encap open-coded. */
2776     if (!strncmp(s, "encap(", 6)) {
2777         const char *start = s;
2778         size_t encap, encap_mask = 0;
2779
2780         encap = nl_msg_start_nested(key, OVS_KEY_ATTR_ENCAP);
2781         if (mask) {
2782             encap_mask = nl_msg_start_nested(mask, OVS_KEY_ATTR_ENCAP);
2783         }
2784
2785         s += 6;
2786         for (;;) {
2787             int retval;
2788
2789             s += strspn(s, delimiters);
2790             if (!*s) {
2791                 return -EINVAL;
2792             } else if (*s == ')') {
2793                 break;
2794             }
2795
2796             retval = parse_odp_key_mask_attr(s, port_names, key, mask);
2797             if (retval < 0) {
2798                 return retval;
2799             }
2800             s += retval;
2801         }
2802         s++;
2803
2804         nl_msg_end_nested(key, encap);
2805         if (mask) {
2806             nl_msg_end_nested(mask, encap_mask);
2807         }
2808
2809         return s - start;
2810     }
2811
2812     return -EINVAL;
2813 }
2814
2815 /* Parses the string representation of a datapath flow key, in the
2816  * format output by odp_flow_key_format().  Returns 0 if successful,
2817  * otherwise a positive errno value.  On success, the flow key is
2818  * appended to 'key' as a series of Netlink attributes.  On failure, no
2819  * data is appended to 'key'.  Either way, 'key''s data might be
2820  * reallocated.
2821  *
2822  * If 'port_names' is nonnull, it points to an simap that maps from a port name
2823  * to a port number.  (Port names may be used instead of port numbers in
2824  * in_port.)
2825  *
2826  * On success, the attributes appended to 'key' are individually syntactically
2827  * valid, but they may not be valid as a sequence.  'key' might, for example,
2828  * have duplicated keys.  odp_flow_key_to_flow() will detect those errors. */
2829 int
2830 odp_flow_from_string(const char *s, const struct simap *port_names,
2831                      struct ofpbuf *key, struct ofpbuf *mask)
2832 {
2833     const size_t old_size = key->size;
2834     for (;;) {
2835         int retval;
2836
2837         s += strspn(s, delimiters);
2838         if (!*s) {
2839             return 0;
2840         }
2841
2842         retval = parse_odp_key_mask_attr(s, port_names, key, mask);
2843         if (retval < 0) {
2844             key->size = old_size;
2845             return -retval;
2846         }
2847         s += retval;
2848     }
2849
2850     return 0;
2851 }
2852
2853 static uint8_t
2854 ovs_to_odp_frag(uint8_t nw_frag, bool is_mask)
2855 {
2856     if (is_mask) {
2857         /* Netlink interface 'enum ovs_frag_type' is an 8-bit enumeration type,
2858          * not a set of flags or bitfields. Hence, if the struct flow nw_frag
2859          * mask, which is a set of bits, has the FLOW_NW_FRAG_ANY as zero, we
2860          * must use a zero mask for the netlink frag field, and all ones mask
2861          * otherwise. */
2862         return (nw_frag & FLOW_NW_FRAG_ANY) ? UINT8_MAX : 0;
2863     }
2864     return !(nw_frag & FLOW_NW_FRAG_ANY) ? OVS_FRAG_TYPE_NONE
2865         : nw_frag & FLOW_NW_FRAG_LATER ? OVS_FRAG_TYPE_LATER
2866         : OVS_FRAG_TYPE_FIRST;
2867 }
2868
2869 static void get_ethernet_key(const struct flow *, struct ovs_key_ethernet *);
2870 static void put_ethernet_key(const struct ovs_key_ethernet *, struct flow *);
2871 static void get_ipv4_key(const struct flow *, struct ovs_key_ipv4 *,
2872                          bool is_mask);
2873 static void put_ipv4_key(const struct ovs_key_ipv4 *, struct flow *,
2874                          bool is_mask);
2875 static void get_ipv6_key(const struct flow *, struct ovs_key_ipv6 *,
2876                          bool is_mask);
2877 static void put_ipv6_key(const struct ovs_key_ipv6 *, struct flow *,
2878                          bool is_mask);
2879 static void get_arp_key(const struct flow *, struct ovs_key_arp *);
2880 static void put_arp_key(const struct ovs_key_arp *, struct flow *);
2881 static void get_nd_key(const struct flow *, struct ovs_key_nd *);
2882 static void put_nd_key(const struct ovs_key_nd *, struct flow *);
2883
2884 /* These share the same layout. */
2885 union ovs_key_tp {
2886     struct ovs_key_tcp tcp;
2887     struct ovs_key_udp udp;
2888     struct ovs_key_sctp sctp;
2889 };
2890
2891 static void get_tp_key(const struct flow *, union ovs_key_tp *);
2892 static void put_tp_key(const union ovs_key_tp *, struct flow *);
2893
2894 static void
2895 odp_flow_key_from_flow__(struct ofpbuf *buf, const struct flow *flow,
2896                          const struct flow *mask, odp_port_t odp_in_port,
2897                          size_t max_mpls_depth, bool recirc, bool export_mask)
2898 {
2899     struct ovs_key_ethernet *eth_key;
2900     size_t encap;
2901     const struct flow *data = export_mask ? mask : flow;
2902
2903     nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, data->skb_priority);
2904
2905     if (flow->tunnel.ip_dst || export_mask) {
2906         tun_key_to_attr(buf, &data->tunnel);
2907     }
2908
2909     nl_msg_put_u32(buf, OVS_KEY_ATTR_SKB_MARK, data->pkt_mark);
2910
2911     if (recirc) {
2912         nl_msg_put_u32(buf, OVS_KEY_ATTR_RECIRC_ID, data->recirc_id);
2913         nl_msg_put_u32(buf, OVS_KEY_ATTR_DP_HASH, data->dp_hash);
2914     }
2915
2916     /* Add an ingress port attribute if this is a mask or 'odp_in_port'
2917      * is not the magical value "ODPP_NONE". */
2918     if (export_mask || odp_in_port != ODPP_NONE) {
2919         nl_msg_put_odp_port(buf, OVS_KEY_ATTR_IN_PORT, odp_in_port);
2920     }
2921
2922     eth_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ETHERNET,
2923                                        sizeof *eth_key);
2924     get_ethernet_key(data, eth_key);
2925
2926     if (flow->vlan_tci != htons(0) || flow->dl_type == htons(ETH_TYPE_VLAN)) {
2927         if (export_mask) {
2928             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, OVS_BE16_MAX);
2929         } else {
2930             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, htons(ETH_TYPE_VLAN));
2931         }
2932         nl_msg_put_be16(buf, OVS_KEY_ATTR_VLAN, data->vlan_tci);
2933         encap = nl_msg_start_nested(buf, OVS_KEY_ATTR_ENCAP);
2934         if (flow->vlan_tci == htons(0)) {
2935             goto unencap;
2936         }
2937     } else {
2938         encap = 0;
2939     }
2940
2941     if (ntohs(flow->dl_type) < ETH_TYPE_MIN) {
2942         /* For backwards compatibility with kernels that don't support
2943          * wildcarding, the following convention is used to encode the
2944          * OVS_KEY_ATTR_ETHERTYPE for key and mask:
2945          *
2946          *   key      mask    matches
2947          * -------- --------  -------
2948          *  >0x5ff   0xffff   Specified Ethernet II Ethertype.
2949          *  >0x5ff      0     Any Ethernet II or non-Ethernet II frame.
2950          *  <none>   0xffff   Any non-Ethernet II frame (except valid
2951          *                    802.3 SNAP packet with valid eth_type).
2952          */
2953         if (export_mask) {
2954             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, OVS_BE16_MAX);
2955         }
2956         goto unencap;
2957     }
2958
2959     nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, data->dl_type);
2960
2961     if (flow->dl_type == htons(ETH_TYPE_IP)) {
2962         struct ovs_key_ipv4 *ipv4_key;
2963
2964         ipv4_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV4,
2965                                             sizeof *ipv4_key);
2966         get_ipv4_key(data, ipv4_key, export_mask);
2967     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
2968         struct ovs_key_ipv6 *ipv6_key;
2969
2970         ipv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV6,
2971                                             sizeof *ipv6_key);
2972         get_ipv6_key(data, ipv6_key, export_mask);
2973     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
2974                flow->dl_type == htons(ETH_TYPE_RARP)) {
2975         struct ovs_key_arp *arp_key;
2976
2977         arp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ARP,
2978                                            sizeof *arp_key);
2979         get_arp_key(data, arp_key);
2980     } else if (eth_type_mpls(flow->dl_type)) {
2981         struct ovs_key_mpls *mpls_key;
2982         int i, n;
2983
2984         n = flow_count_mpls_labels(flow, NULL);
2985         n = MIN(n, max_mpls_depth);
2986         mpls_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_MPLS,
2987                                             n * sizeof *mpls_key);
2988         for (i = 0; i < n; i++) {
2989             mpls_key[i].mpls_lse = data->mpls_lse[i];
2990         }
2991     }
2992
2993     if (is_ip_any(flow) && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
2994         if (flow->nw_proto == IPPROTO_TCP) {
2995             union ovs_key_tp *tcp_key;
2996
2997             tcp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_TCP,
2998                                                sizeof *tcp_key);
2999             get_tp_key(data, tcp_key);
3000             if (data->tcp_flags) {
3001                 nl_msg_put_be16(buf, OVS_KEY_ATTR_TCP_FLAGS, data->tcp_flags);
3002             }
3003         } else if (flow->nw_proto == IPPROTO_UDP) {
3004             union ovs_key_tp *udp_key;
3005
3006             udp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_UDP,
3007                                                sizeof *udp_key);
3008             get_tp_key(data, udp_key);
3009         } else if (flow->nw_proto == IPPROTO_SCTP) {
3010             union ovs_key_tp *sctp_key;
3011
3012             sctp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_SCTP,
3013                                                sizeof *sctp_key);
3014             get_tp_key(data, sctp_key);
3015         } else if (flow->dl_type == htons(ETH_TYPE_IP)
3016                 && flow->nw_proto == IPPROTO_ICMP) {
3017             struct ovs_key_icmp *icmp_key;
3018
3019             icmp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMP,
3020                                                 sizeof *icmp_key);
3021             icmp_key->icmp_type = ntohs(data->tp_src);
3022             icmp_key->icmp_code = ntohs(data->tp_dst);
3023         } else if (flow->dl_type == htons(ETH_TYPE_IPV6)
3024                 && flow->nw_proto == IPPROTO_ICMPV6) {
3025             struct ovs_key_icmpv6 *icmpv6_key;
3026
3027             icmpv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMPV6,
3028                                                   sizeof *icmpv6_key);
3029             icmpv6_key->icmpv6_type = ntohs(data->tp_src);
3030             icmpv6_key->icmpv6_code = ntohs(data->tp_dst);
3031
3032             if (flow->tp_dst == htons(0)
3033                 && (flow->tp_src == htons(ND_NEIGHBOR_SOLICIT)
3034                     || flow->tp_src == htons(ND_NEIGHBOR_ADVERT))
3035                 && (!export_mask || (data->tp_src == htons(0xffff)
3036                                      && data->tp_dst == htons(0xffff)))) {
3037
3038                 struct ovs_key_nd *nd_key;
3039
3040                 nd_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ND,
3041                                                     sizeof *nd_key);
3042                 memcpy(nd_key->nd_target, &data->nd_target,
3043                         sizeof nd_key->nd_target);
3044                 memcpy(nd_key->nd_sll, data->arp_sha, ETH_ADDR_LEN);
3045                 memcpy(nd_key->nd_tll, data->arp_tha, ETH_ADDR_LEN);
3046             }
3047         }
3048     }
3049
3050 unencap:
3051     if (encap) {
3052         nl_msg_end_nested(buf, encap);
3053     }
3054 }
3055
3056 /* Appends a representation of 'flow' as OVS_KEY_ATTR_* attributes to 'buf'.
3057  * 'flow->in_port' is ignored (since it is likely to be an OpenFlow port
3058  * number rather than a datapath port number).  Instead, if 'odp_in_port'
3059  * is anything other than ODPP_NONE, it is included in 'buf' as the input
3060  * port.
3061  *
3062  * 'buf' must have at least ODPUTIL_FLOW_KEY_BYTES bytes of space, or be
3063  * capable of being expanded to allow for that much space.
3064  *
3065  * 'recirc' indicates support for recirculation fields. If this is true, then
3066  * these fields will always be serialised. */
3067 void
3068 odp_flow_key_from_flow(struct ofpbuf *buf, const struct flow *flow,
3069                        const struct flow *mask, odp_port_t odp_in_port,
3070                        bool recirc)
3071 {
3072     odp_flow_key_from_flow__(buf, flow, mask, odp_in_port, SIZE_MAX, recirc,
3073                              false);
3074 }
3075
3076 /* Appends a representation of 'mask' as OVS_KEY_ATTR_* attributes to
3077  * 'buf'.  'flow' is used as a template to determine how to interpret
3078  * 'mask'.  For example, the 'dl_type' of 'mask' describes the mask, but
3079  * it doesn't indicate whether the other fields should be interpreted as
3080  * ARP, IPv4, IPv6, etc.
3081  *
3082  * 'buf' must have at least ODPUTIL_FLOW_KEY_BYTES bytes of space, or be
3083  * capable of being expanded to allow for that much space.
3084  *
3085  * 'recirc' indicates support for recirculation fields. If this is true, then
3086  * these fields will always be serialised. */
3087 void
3088 odp_flow_key_from_mask(struct ofpbuf *buf, const struct flow *mask,
3089                        const struct flow *flow, uint32_t odp_in_port_mask,
3090                        size_t max_mpls_depth, bool recirc)
3091 {
3092     odp_flow_key_from_flow__(buf, flow, mask, u32_to_odp(odp_in_port_mask),
3093                              max_mpls_depth, recirc, true);
3094 }
3095
3096 /* Generate ODP flow key from the given packet metadata */
3097 void
3098 odp_key_from_pkt_metadata(struct ofpbuf *buf, const struct pkt_metadata *md)
3099 {
3100     nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, md->skb_priority);
3101
3102     if (md->tunnel.ip_dst) {
3103         tun_key_to_attr(buf, &md->tunnel);
3104     }
3105
3106     nl_msg_put_u32(buf, OVS_KEY_ATTR_SKB_MARK, md->pkt_mark);
3107
3108     /* Add an ingress port attribute if 'odp_in_port' is not the magical
3109      * value "ODPP_NONE". */
3110     if (md->in_port.odp_port != ODPP_NONE) {
3111         nl_msg_put_odp_port(buf, OVS_KEY_ATTR_IN_PORT, md->in_port.odp_port);
3112     }
3113 }
3114
3115 /* Generate packet metadata from the given ODP flow key. */
3116 void
3117 odp_key_to_pkt_metadata(const struct nlattr *key, size_t key_len,
3118                         struct pkt_metadata *md)
3119 {
3120     const struct nlattr *nla;
3121     size_t left;
3122     uint32_t wanted_attrs = 1u << OVS_KEY_ATTR_PRIORITY |
3123         1u << OVS_KEY_ATTR_SKB_MARK | 1u << OVS_KEY_ATTR_TUNNEL |
3124         1u << OVS_KEY_ATTR_IN_PORT;
3125
3126     *md = PKT_METADATA_INITIALIZER(ODPP_NONE);
3127
3128     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
3129         uint16_t type = nl_attr_type(nla);
3130         size_t len = nl_attr_get_size(nla);
3131         int expected_len = odp_flow_key_attr_len(type);
3132
3133         if (len != expected_len && expected_len >= 0) {
3134             continue;
3135         }
3136
3137         switch (type) {
3138         case OVS_KEY_ATTR_RECIRC_ID:
3139             md->recirc_id = nl_attr_get_u32(nla);
3140             wanted_attrs &= ~(1u << OVS_KEY_ATTR_RECIRC_ID);
3141             break;
3142         case OVS_KEY_ATTR_DP_HASH:
3143             md->dp_hash = nl_attr_get_u32(nla);
3144             wanted_attrs &= ~(1u << OVS_KEY_ATTR_DP_HASH);
3145             break;
3146         case OVS_KEY_ATTR_PRIORITY:
3147             md->skb_priority = nl_attr_get_u32(nla);
3148             wanted_attrs &= ~(1u << OVS_KEY_ATTR_PRIORITY);
3149             break;
3150         case OVS_KEY_ATTR_SKB_MARK:
3151             md->pkt_mark = nl_attr_get_u32(nla);
3152             wanted_attrs &= ~(1u << OVS_KEY_ATTR_SKB_MARK);
3153             break;
3154         case OVS_KEY_ATTR_TUNNEL: {
3155             enum odp_key_fitness res;
3156
3157             res = odp_tun_key_from_attr(nla, &md->tunnel);
3158             if (res == ODP_FIT_ERROR) {
3159                 memset(&md->tunnel, 0, sizeof md->tunnel);
3160             } else if (res == ODP_FIT_PERFECT) {
3161                 wanted_attrs &= ~(1u << OVS_KEY_ATTR_TUNNEL);
3162             }
3163             break;
3164         }
3165         case OVS_KEY_ATTR_IN_PORT:
3166             md->in_port.odp_port = nl_attr_get_odp_port(nla);
3167             wanted_attrs &= ~(1u << OVS_KEY_ATTR_IN_PORT);
3168             break;
3169         default:
3170             break;
3171         }
3172
3173         if (!wanted_attrs) {
3174             return; /* Have everything. */
3175         }
3176     }
3177 }
3178
3179 uint32_t
3180 odp_flow_key_hash(const struct nlattr *key, size_t key_len)
3181 {
3182     BUILD_ASSERT_DECL(!(NLA_ALIGNTO % sizeof(uint32_t)));
3183     return hash_words(ALIGNED_CAST(const uint32_t *, key),
3184                       key_len / sizeof(uint32_t), 0);
3185 }
3186
3187 static void
3188 log_odp_key_attributes(struct vlog_rate_limit *rl, const char *title,
3189                        uint64_t attrs, int out_of_range_attr,
3190                        const struct nlattr *key, size_t key_len)
3191 {
3192     struct ds s;
3193     int i;
3194
3195     if (VLOG_DROP_DBG(rl)) {
3196         return;
3197     }
3198
3199     ds_init(&s);
3200     for (i = 0; i < 64; i++) {
3201         if (attrs & (UINT64_C(1) << i)) {
3202             char namebuf[OVS_KEY_ATTR_BUFSIZE];
3203
3204             ds_put_format(&s, " %s",
3205                           ovs_key_attr_to_string(i, namebuf, sizeof namebuf));
3206         }
3207     }
3208     if (out_of_range_attr) {
3209         ds_put_format(&s, " %d (and possibly others)", out_of_range_attr);
3210     }
3211
3212     ds_put_cstr(&s, ": ");
3213     odp_flow_key_format(key, key_len, &s);
3214
3215     VLOG_DBG("%s:%s", title, ds_cstr(&s));
3216     ds_destroy(&s);
3217 }
3218
3219 static uint8_t
3220 odp_to_ovs_frag(uint8_t odp_frag, bool is_mask)
3221 {
3222     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3223
3224     if (is_mask) {
3225         return odp_frag ? FLOW_NW_FRAG_MASK : 0;
3226     }
3227
3228     if (odp_frag > OVS_FRAG_TYPE_LATER) {
3229         VLOG_ERR_RL(&rl, "invalid frag %"PRIu8" in flow key", odp_frag);
3230         return 0xff; /* Error. */
3231     }
3232
3233     return (odp_frag == OVS_FRAG_TYPE_NONE) ? 0
3234         : (odp_frag == OVS_FRAG_TYPE_FIRST) ? FLOW_NW_FRAG_ANY
3235         :  FLOW_NW_FRAG_ANY | FLOW_NW_FRAG_LATER;
3236 }
3237
3238 static bool
3239 parse_flow_nlattrs(const struct nlattr *key, size_t key_len,
3240                    const struct nlattr *attrs[], uint64_t *present_attrsp,
3241                    int *out_of_range_attrp)
3242 {
3243     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3244     const struct nlattr *nla;
3245     uint64_t present_attrs;
3246     size_t left;
3247
3248     BUILD_ASSERT(OVS_KEY_ATTR_MAX < CHAR_BIT * sizeof present_attrs);
3249     present_attrs = 0;
3250     *out_of_range_attrp = 0;
3251     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
3252         uint16_t type = nl_attr_type(nla);
3253         size_t len = nl_attr_get_size(nla);
3254         int expected_len = odp_flow_key_attr_len(type);
3255
3256         if (len != expected_len && expected_len >= 0) {
3257             char namebuf[OVS_KEY_ATTR_BUFSIZE];
3258
3259             VLOG_ERR_RL(&rl, "attribute %s has length %"PRIuSIZE" but should have "
3260                         "length %d", ovs_key_attr_to_string(type, namebuf,
3261                                                             sizeof namebuf),
3262                         len, expected_len);
3263             return false;
3264         }
3265
3266         if (type > OVS_KEY_ATTR_MAX) {
3267             *out_of_range_attrp = type;
3268         } else {
3269             if (present_attrs & (UINT64_C(1) << type)) {
3270                 char namebuf[OVS_KEY_ATTR_BUFSIZE];
3271
3272                 VLOG_ERR_RL(&rl, "duplicate %s attribute in flow key",
3273                             ovs_key_attr_to_string(type,
3274                                                    namebuf, sizeof namebuf));
3275                 return false;
3276             }
3277
3278             present_attrs |= UINT64_C(1) << type;
3279             attrs[type] = nla;
3280         }
3281     }
3282     if (left) {
3283         VLOG_ERR_RL(&rl, "trailing garbage in flow key");
3284         return false;
3285     }
3286
3287     *present_attrsp = present_attrs;
3288     return true;
3289 }
3290
3291 static enum odp_key_fitness
3292 check_expectations(uint64_t present_attrs, int out_of_range_attr,
3293                    uint64_t expected_attrs,
3294                    const struct nlattr *key, size_t key_len)
3295 {
3296     uint64_t missing_attrs;
3297     uint64_t extra_attrs;
3298
3299     missing_attrs = expected_attrs & ~present_attrs;
3300     if (missing_attrs) {
3301         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3302         log_odp_key_attributes(&rl, "expected but not present",
3303                                missing_attrs, 0, key, key_len);
3304         return ODP_FIT_TOO_LITTLE;
3305     }
3306
3307     extra_attrs = present_attrs & ~expected_attrs;
3308     if (extra_attrs || out_of_range_attr) {
3309         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3310         log_odp_key_attributes(&rl, "present but not expected",
3311                                extra_attrs, out_of_range_attr, key, key_len);
3312         return ODP_FIT_TOO_MUCH;
3313     }
3314
3315     return ODP_FIT_PERFECT;
3316 }
3317
3318 static bool
3319 parse_ethertype(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
3320                 uint64_t present_attrs, uint64_t *expected_attrs,
3321                 struct flow *flow, const struct flow *src_flow)
3322 {
3323     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3324     bool is_mask = flow != src_flow;
3325
3326     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE)) {
3327         flow->dl_type = nl_attr_get_be16(attrs[OVS_KEY_ATTR_ETHERTYPE]);
3328         if (!is_mask && ntohs(flow->dl_type) < ETH_TYPE_MIN) {
3329             VLOG_ERR_RL(&rl, "invalid Ethertype %"PRIu16" in flow key",
3330                         ntohs(flow->dl_type));
3331             return false;
3332         }
3333         if (is_mask && ntohs(src_flow->dl_type) < ETH_TYPE_MIN &&
3334             flow->dl_type != htons(0xffff)) {
3335             return false;
3336         }
3337         *expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE;
3338     } else {
3339         if (!is_mask) {
3340             flow->dl_type = htons(FLOW_DL_TYPE_NONE);
3341         } else if (ntohs(src_flow->dl_type) < ETH_TYPE_MIN) {
3342             /* See comments in odp_flow_key_from_flow__(). */
3343             VLOG_ERR_RL(&rl, "mask expected for non-Ethernet II frame");
3344             return false;
3345         }
3346     }
3347     return true;
3348 }
3349
3350 static enum odp_key_fitness
3351 parse_l2_5_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
3352                   uint64_t present_attrs, int out_of_range_attr,
3353                   uint64_t expected_attrs, struct flow *flow,
3354                   const struct nlattr *key, size_t key_len,
3355                   const struct flow *src_flow)
3356 {
3357     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3358     bool is_mask = src_flow != flow;
3359     const void *check_start = NULL;
3360     size_t check_len = 0;
3361     enum ovs_key_attr expected_bit = 0xff;
3362
3363     if (eth_type_mpls(src_flow->dl_type)) {
3364         if (!is_mask || present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_MPLS)) {
3365             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_MPLS);
3366         }
3367         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_MPLS)) {
3368             size_t size = nl_attr_get_size(attrs[OVS_KEY_ATTR_MPLS]);
3369             const ovs_be32 *mpls_lse = nl_attr_get(attrs[OVS_KEY_ATTR_MPLS]);
3370             int n = size / sizeof(ovs_be32);
3371             int i;
3372
3373             if (!size || size % sizeof(ovs_be32)) {
3374                 return ODP_FIT_ERROR;
3375             }
3376             if (flow->mpls_lse[0] && flow->dl_type != htons(0xffff)) {
3377                 return ODP_FIT_ERROR;
3378             }
3379
3380             for (i = 0; i < n && i < FLOW_MAX_MPLS_LABELS; i++) {
3381                 flow->mpls_lse[i] = mpls_lse[i];
3382             }
3383             if (n > FLOW_MAX_MPLS_LABELS) {
3384                 return ODP_FIT_TOO_MUCH;
3385             }
3386
3387             if (!is_mask) {
3388                 /* BOS may be set only in the innermost label. */
3389                 for (i = 0; i < n - 1; i++) {
3390                     if (flow->mpls_lse[i] & htonl(MPLS_BOS_MASK)) {
3391                         return ODP_FIT_ERROR;
3392                     }
3393                 }
3394
3395                 /* BOS must be set in the innermost label. */
3396                 if (n < FLOW_MAX_MPLS_LABELS
3397                     && !(flow->mpls_lse[n - 1] & htonl(MPLS_BOS_MASK))) {
3398                     return ODP_FIT_TOO_LITTLE;
3399                 }
3400             }
3401         }
3402
3403         goto done;
3404     } else if (src_flow->dl_type == htons(ETH_TYPE_IP)) {
3405         if (!is_mask) {
3406             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV4;
3407         }
3408         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV4)) {
3409             const struct ovs_key_ipv4 *ipv4_key;
3410
3411             ipv4_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV4]);
3412             put_ipv4_key(ipv4_key, flow, is_mask);
3413             if (flow->nw_frag > FLOW_NW_FRAG_MASK) {
3414                 return ODP_FIT_ERROR;
3415             }
3416             if (is_mask) {
3417                 check_start = ipv4_key;
3418                 check_len = sizeof *ipv4_key;
3419                 expected_bit = OVS_KEY_ATTR_IPV4;
3420             }
3421         }
3422     } else if (src_flow->dl_type == htons(ETH_TYPE_IPV6)) {
3423         if (!is_mask) {
3424             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV6;
3425         }
3426         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV6)) {
3427             const struct ovs_key_ipv6 *ipv6_key;
3428
3429             ipv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV6]);
3430             put_ipv6_key(ipv6_key, flow, is_mask);
3431             if (flow->nw_frag > FLOW_NW_FRAG_MASK) {
3432                 return ODP_FIT_ERROR;
3433             }
3434             if (is_mask) {
3435                 check_start = ipv6_key;
3436                 check_len = sizeof *ipv6_key;
3437                 expected_bit = OVS_KEY_ATTR_IPV6;
3438             }
3439         }
3440     } else if (src_flow->dl_type == htons(ETH_TYPE_ARP) ||
3441                src_flow->dl_type == htons(ETH_TYPE_RARP)) {
3442         if (!is_mask) {
3443             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ARP;
3444         }
3445         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ARP)) {
3446             const struct ovs_key_arp *arp_key;
3447
3448             arp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ARP]);
3449             if (!is_mask && (arp_key->arp_op & htons(0xff00))) {
3450                 VLOG_ERR_RL(&rl, "unsupported ARP opcode %"PRIu16" in flow "
3451                             "key", ntohs(arp_key->arp_op));
3452                 return ODP_FIT_ERROR;
3453             }
3454             put_arp_key(arp_key, flow);
3455             if (is_mask) {
3456                 check_start = arp_key;
3457                 check_len = sizeof *arp_key;
3458                 expected_bit = OVS_KEY_ATTR_ARP;
3459             }
3460         }
3461     } else {
3462         goto done;
3463     }
3464     if (check_len > 0) { /* Happens only when 'is_mask'. */
3465         if (!is_all_zeros(check_start, check_len) &&
3466             flow->dl_type != htons(0xffff)) {
3467             return ODP_FIT_ERROR;
3468         } else {
3469             expected_attrs |= UINT64_C(1) << expected_bit;
3470         }
3471     }
3472
3473     expected_bit = OVS_KEY_ATTR_UNSPEC;
3474     if (src_flow->nw_proto == IPPROTO_TCP
3475         && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
3476             src_flow->dl_type == htons(ETH_TYPE_IPV6))
3477         && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3478         if (!is_mask) {
3479             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP;
3480         }
3481         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP)) {
3482             const union ovs_key_tp *tcp_key;
3483
3484             tcp_key = nl_attr_get(attrs[OVS_KEY_ATTR_TCP]);
3485             put_tp_key(tcp_key, flow);
3486             expected_bit = OVS_KEY_ATTR_TCP;
3487         }
3488         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP_FLAGS)) {
3489             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP_FLAGS;
3490             flow->tcp_flags = nl_attr_get_be16(attrs[OVS_KEY_ATTR_TCP_FLAGS]);
3491         }
3492     } else if (src_flow->nw_proto == IPPROTO_UDP
3493                && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
3494                    src_flow->dl_type == htons(ETH_TYPE_IPV6))
3495                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3496         if (!is_mask) {
3497             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_UDP;
3498         }
3499         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_UDP)) {
3500             const union ovs_key_tp *udp_key;
3501
3502             udp_key = nl_attr_get(attrs[OVS_KEY_ATTR_UDP]);
3503             put_tp_key(udp_key, flow);
3504             expected_bit = OVS_KEY_ATTR_UDP;
3505         }
3506     } else if (src_flow->nw_proto == IPPROTO_SCTP
3507                && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
3508                    src_flow->dl_type == htons(ETH_TYPE_IPV6))
3509                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3510         if (!is_mask) {
3511             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_SCTP;
3512         }
3513         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_SCTP)) {
3514             const union ovs_key_tp *sctp_key;
3515
3516             sctp_key = nl_attr_get(attrs[OVS_KEY_ATTR_SCTP]);
3517             put_tp_key(sctp_key, flow);
3518             expected_bit = OVS_KEY_ATTR_SCTP;
3519         }
3520     } else if (src_flow->nw_proto == IPPROTO_ICMP
3521                && src_flow->dl_type == htons(ETH_TYPE_IP)
3522                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3523         if (!is_mask) {
3524             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMP;
3525         }
3526         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMP)) {
3527             const struct ovs_key_icmp *icmp_key;
3528
3529             icmp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMP]);
3530             flow->tp_src = htons(icmp_key->icmp_type);
3531             flow->tp_dst = htons(icmp_key->icmp_code);
3532             expected_bit = OVS_KEY_ATTR_ICMP;
3533         }
3534     } else if (src_flow->nw_proto == IPPROTO_ICMPV6
3535                && src_flow->dl_type == htons(ETH_TYPE_IPV6)
3536                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3537         if (!is_mask) {
3538             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMPV6;
3539         }
3540         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMPV6)) {
3541             const struct ovs_key_icmpv6 *icmpv6_key;
3542
3543             icmpv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMPV6]);
3544             flow->tp_src = htons(icmpv6_key->icmpv6_type);
3545             flow->tp_dst = htons(icmpv6_key->icmpv6_code);
3546             expected_bit = OVS_KEY_ATTR_ICMPV6;
3547             if (src_flow->tp_dst == htons(0) &&
3548                 (src_flow->tp_src == htons(ND_NEIGHBOR_SOLICIT) ||
3549                  src_flow->tp_src == htons(ND_NEIGHBOR_ADVERT))) {
3550                 if (!is_mask) {
3551                     expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
3552                 }
3553                 if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ND)) {
3554                     const struct ovs_key_nd *nd_key;
3555
3556                     nd_key = nl_attr_get(attrs[OVS_KEY_ATTR_ND]);
3557                     memcpy(&flow->nd_target, nd_key->nd_target,
3558                            sizeof flow->nd_target);
3559                     memcpy(flow->arp_sha, nd_key->nd_sll, ETH_ADDR_LEN);
3560                     memcpy(flow->arp_tha, nd_key->nd_tll, ETH_ADDR_LEN);
3561                     if (is_mask) {
3562                         if (!is_all_zeros(nd_key, sizeof *nd_key) &&
3563                             (flow->tp_src != htons(0xffff) ||
3564                              flow->tp_dst != htons(0xffff))) {
3565                             return ODP_FIT_ERROR;
3566                         } else {
3567                             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
3568                         }
3569                     }
3570                 }
3571             }
3572         }
3573     }
3574     if (is_mask && expected_bit != OVS_KEY_ATTR_UNSPEC) {
3575         if ((flow->tp_src || flow->tp_dst) && flow->nw_proto != 0xff) {
3576             return ODP_FIT_ERROR;
3577         } else {
3578             expected_attrs |= UINT64_C(1) << expected_bit;
3579         }
3580     }
3581
3582 done:
3583     return check_expectations(present_attrs, out_of_range_attr, expected_attrs,
3584                               key, key_len);
3585 }
3586
3587 /* Parse 802.1Q header then encapsulated L3 attributes. */
3588 static enum odp_key_fitness
3589 parse_8021q_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
3590                    uint64_t present_attrs, int out_of_range_attr,
3591                    uint64_t expected_attrs, struct flow *flow,
3592                    const struct nlattr *key, size_t key_len,
3593                    const struct flow *src_flow)
3594 {
3595     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3596     bool is_mask = src_flow != flow;
3597
3598     const struct nlattr *encap
3599         = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)
3600            ? attrs[OVS_KEY_ATTR_ENCAP] : NULL);
3601     enum odp_key_fitness encap_fitness;
3602     enum odp_key_fitness fitness;
3603
3604     /* Calculate fitness of outer attributes. */
3605     if (!is_mask) {
3606         expected_attrs |= ((UINT64_C(1) << OVS_KEY_ATTR_VLAN) |
3607                           (UINT64_C(1) << OVS_KEY_ATTR_ENCAP));
3608     } else {
3609         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)) {
3610             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_VLAN);
3611         }
3612         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)) {
3613             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_ENCAP);
3614         }
3615     }
3616     fitness = check_expectations(present_attrs, out_of_range_attr,
3617                                  expected_attrs, key, key_len);
3618
3619     /* Set vlan_tci.
3620      * Remove the TPID from dl_type since it's not the real Ethertype.  */
3621     flow->dl_type = htons(0);
3622     flow->vlan_tci = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)
3623                       ? nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN])
3624                       : htons(0));
3625     if (!is_mask) {
3626         if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN))) {
3627             return ODP_FIT_TOO_LITTLE;
3628         } else if (flow->vlan_tci == htons(0)) {
3629             /* Corner case for a truncated 802.1Q header. */
3630             if (fitness == ODP_FIT_PERFECT && nl_attr_get_size(encap)) {
3631                 return ODP_FIT_TOO_MUCH;
3632             }
3633             return fitness;
3634         } else if (!(flow->vlan_tci & htons(VLAN_CFI))) {
3635             VLOG_ERR_RL(&rl, "OVS_KEY_ATTR_VLAN 0x%04"PRIx16" is nonzero "
3636                         "but CFI bit is not set", ntohs(flow->vlan_tci));
3637             return ODP_FIT_ERROR;
3638         }
3639     } else {
3640         if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP))) {
3641             return fitness;
3642         }
3643     }
3644
3645     /* Now parse the encapsulated attributes. */
3646     if (!parse_flow_nlattrs(nl_attr_get(encap), nl_attr_get_size(encap),
3647                             attrs, &present_attrs, &out_of_range_attr)) {
3648         return ODP_FIT_ERROR;
3649     }
3650     expected_attrs = 0;
3651
3652     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow, src_flow)) {
3653         return ODP_FIT_ERROR;
3654     }
3655     encap_fitness = parse_l2_5_onward(attrs, present_attrs, out_of_range_attr,
3656                                       expected_attrs, flow, key, key_len,
3657                                       src_flow);
3658
3659     /* The overall fitness is the worse of the outer and inner attributes. */
3660     return MAX(fitness, encap_fitness);
3661 }
3662
3663 static enum odp_key_fitness
3664 odp_flow_key_to_flow__(const struct nlattr *key, size_t key_len,
3665                        struct flow *flow, const struct flow *src_flow)
3666 {
3667     const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1];
3668     uint64_t expected_attrs;
3669     uint64_t present_attrs;
3670     int out_of_range_attr;
3671     bool is_mask = src_flow != flow;
3672
3673     memset(flow, 0, sizeof *flow);
3674
3675     /* Parse attributes. */
3676     if (!parse_flow_nlattrs(key, key_len, attrs, &present_attrs,
3677                             &out_of_range_attr)) {
3678         return ODP_FIT_ERROR;
3679     }
3680     expected_attrs = 0;
3681
3682     /* Metadata. */
3683     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_RECIRC_ID)) {
3684         flow->recirc_id = nl_attr_get_u32(attrs[OVS_KEY_ATTR_RECIRC_ID]);
3685         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_RECIRC_ID;
3686     } else if (is_mask) {
3687         /* Always exact match recirc_id if it is not specified. */
3688         flow->recirc_id = UINT32_MAX;
3689     }
3690
3691     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_DP_HASH)) {
3692         flow->dp_hash = nl_attr_get_u32(attrs[OVS_KEY_ATTR_DP_HASH]);
3693         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_DP_HASH;
3694     }
3695     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_PRIORITY)) {
3696         flow->skb_priority = nl_attr_get_u32(attrs[OVS_KEY_ATTR_PRIORITY]);
3697         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_PRIORITY;
3698     }
3699
3700     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_SKB_MARK)) {
3701         flow->pkt_mark = nl_attr_get_u32(attrs[OVS_KEY_ATTR_SKB_MARK]);
3702         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_SKB_MARK;
3703     }
3704
3705     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TUNNEL)) {
3706         enum odp_key_fitness res;
3707
3708         res = odp_tun_key_from_attr(attrs[OVS_KEY_ATTR_TUNNEL], &flow->tunnel);
3709         if (res == ODP_FIT_ERROR) {
3710             return ODP_FIT_ERROR;
3711         } else if (res == ODP_FIT_PERFECT) {
3712             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TUNNEL;
3713         }
3714     }
3715
3716     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IN_PORT)) {
3717         flow->in_port.odp_port
3718             = nl_attr_get_odp_port(attrs[OVS_KEY_ATTR_IN_PORT]);
3719         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IN_PORT;
3720     } else if (!is_mask) {
3721         flow->in_port.odp_port = ODPP_NONE;
3722     }
3723
3724     /* Ethernet header. */
3725     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERNET)) {
3726         const struct ovs_key_ethernet *eth_key;
3727
3728         eth_key = nl_attr_get(attrs[OVS_KEY_ATTR_ETHERNET]);
3729         put_ethernet_key(eth_key, flow);
3730         if (is_mask) {
3731             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
3732         }
3733     }
3734     if (!is_mask) {
3735         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
3736     }
3737
3738     /* Get Ethertype or 802.1Q TPID or FLOW_DL_TYPE_NONE. */
3739     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow,
3740         src_flow)) {
3741         return ODP_FIT_ERROR;
3742     }
3743
3744     if (is_mask
3745         ? (src_flow->vlan_tci & htons(VLAN_CFI)) != 0
3746         : src_flow->dl_type == htons(ETH_TYPE_VLAN)) {
3747         return parse_8021q_onward(attrs, present_attrs, out_of_range_attr,
3748                                   expected_attrs, flow, key, key_len, src_flow);
3749     }
3750     if (is_mask) {
3751         flow->vlan_tci = htons(0xffff);
3752         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)) {
3753             flow->vlan_tci = nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN]);
3754             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_VLAN);
3755         }
3756     }
3757     return parse_l2_5_onward(attrs, present_attrs, out_of_range_attr,
3758                              expected_attrs, flow, key, key_len, src_flow);
3759 }
3760
3761 /* Converts the 'key_len' bytes of OVS_KEY_ATTR_* attributes in 'key' to a flow
3762  * structure in 'flow'.  Returns an ODP_FIT_* value that indicates how well
3763  * 'key' fits our expectations for what a flow key should contain.
3764  *
3765  * The 'in_port' will be the datapath's understanding of the port.  The
3766  * caller will need to translate with odp_port_to_ofp_port() if the
3767  * OpenFlow port is needed.
3768  *
3769  * This function doesn't take the packet itself as an argument because none of
3770  * the currently understood OVS_KEY_ATTR_* attributes require it.  Currently,
3771  * it is always possible to infer which additional attribute(s) should appear
3772  * by looking at the attributes for lower-level protocols, e.g. if the network
3773  * protocol in OVS_KEY_ATTR_IPV4 or OVS_KEY_ATTR_IPV6 is IPPROTO_TCP then we
3774  * know that a OVS_KEY_ATTR_TCP attribute must appear and that otherwise it
3775  * must be absent. */
3776 enum odp_key_fitness
3777 odp_flow_key_to_flow(const struct nlattr *key, size_t key_len,
3778                      struct flow *flow)
3779 {
3780    return odp_flow_key_to_flow__(key, key_len, flow, flow);
3781 }
3782
3783 /* Converts the 'key_len' bytes of OVS_KEY_ATTR_* attributes in 'key' to a mask
3784  * structure in 'mask'.  'flow' must be a previously translated flow
3785  * corresponding to 'mask'.  Returns an ODP_FIT_* value that indicates how well
3786  * 'key' fits our expectations for what a flow key should contain. */
3787 enum odp_key_fitness
3788 odp_flow_key_to_mask(const struct nlattr *key, size_t key_len,
3789                      struct flow *mask, const struct flow *flow)
3790 {
3791    return odp_flow_key_to_flow__(key, key_len, mask, flow);
3792 }
3793
3794 /* Returns 'fitness' as a string, for use in debug messages. */
3795 const char *
3796 odp_key_fitness_to_string(enum odp_key_fitness fitness)
3797 {
3798     switch (fitness) {
3799     case ODP_FIT_PERFECT:
3800         return "OK";
3801     case ODP_FIT_TOO_MUCH:
3802         return "too_much";
3803     case ODP_FIT_TOO_LITTLE:
3804         return "too_little";
3805     case ODP_FIT_ERROR:
3806         return "error";
3807     default:
3808         return "<unknown>";
3809     }
3810 }
3811
3812 /* Appends an OVS_ACTION_ATTR_USERSPACE action to 'odp_actions' that specifies
3813  * Netlink PID 'pid'.  If 'userdata' is nonnull, adds a userdata attribute
3814  * whose contents are the 'userdata_size' bytes at 'userdata' and returns the
3815  * offset within 'odp_actions' of the start of the cookie.  (If 'userdata' is
3816  * null, then the return value is not meaningful.) */
3817 size_t
3818 odp_put_userspace_action(uint32_t pid,
3819                          const void *userdata, size_t userdata_size,
3820                          odp_port_t tunnel_out_port,
3821                          struct ofpbuf *odp_actions)
3822 {
3823     size_t userdata_ofs;
3824     size_t offset;
3825
3826     offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_USERSPACE);
3827     nl_msg_put_u32(odp_actions, OVS_USERSPACE_ATTR_PID, pid);
3828     if (userdata) {
3829         userdata_ofs = odp_actions->size + NLA_HDRLEN;
3830
3831         /* The OVS kernel module before OVS 1.11 and the upstream Linux kernel
3832          * module before Linux 3.10 required the userdata to be exactly 8 bytes
3833          * long:
3834          *
3835          *   - The kernel rejected shorter userdata with -ERANGE.
3836          *
3837          *   - The kernel silently dropped userdata beyond the first 8 bytes.
3838          *
3839          * Thus, for maximum compatibility, always put at least 8 bytes.  (We
3840          * separately disable features that required more than 8 bytes.) */
3841         memcpy(nl_msg_put_unspec_zero(odp_actions, OVS_USERSPACE_ATTR_USERDATA,
3842                                       MAX(8, userdata_size)),
3843                userdata, userdata_size);
3844     } else {
3845         userdata_ofs = 0;
3846     }
3847     if (tunnel_out_port != ODPP_NONE) {
3848         nl_msg_put_odp_port(odp_actions, OVS_USERSPACE_ATTR_EGRESS_TUN_PORT,
3849                             tunnel_out_port);
3850     }
3851     nl_msg_end_nested(odp_actions, offset);
3852
3853     return userdata_ofs;
3854 }
3855
3856 void
3857 odp_put_tunnel_action(const struct flow_tnl *tunnel,
3858                       struct ofpbuf *odp_actions)
3859 {
3860     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
3861     tun_key_to_attr(odp_actions, tunnel);
3862     nl_msg_end_nested(odp_actions, offset);
3863 }
3864
3865 void
3866 odp_put_tnl_push_action(struct ofpbuf *odp_actions,
3867                         struct ovs_action_push_tnl *data)
3868 {
3869     int size = offsetof(struct ovs_action_push_tnl, header);
3870
3871     size += data->header_len;
3872     nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_TUNNEL_PUSH, data, size);
3873 }
3874
3875 \f
3876 /* The commit_odp_actions() function and its helpers. */
3877
3878 static void
3879 commit_set_action(struct ofpbuf *odp_actions, enum ovs_key_attr key_type,
3880                   const void *key, size_t key_size)
3881 {
3882     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
3883     nl_msg_put_unspec(odp_actions, key_type, key, key_size);
3884     nl_msg_end_nested(odp_actions, offset);
3885 }
3886
3887 /* Masked set actions have a mask following the data within the netlink
3888  * attribute.  The unmasked bits in the data will be cleared as the data
3889  * is copied to the action. */
3890 void
3891 commit_masked_set_action(struct ofpbuf *odp_actions,
3892                          enum ovs_key_attr key_type,
3893                          const void *key_, const void *mask_, size_t key_size)
3894 {
3895     size_t offset = nl_msg_start_nested(odp_actions,
3896                                         OVS_ACTION_ATTR_SET_MASKED);
3897     char *data = nl_msg_put_unspec_uninit(odp_actions, key_type, key_size * 2);
3898     const char *key = key_, *mask = mask_;
3899
3900     memcpy(data + key_size, mask, key_size);
3901     /* Clear unmasked bits while copying. */
3902     while (key_size--) {
3903         *data++ = *key++ & *mask++;
3904     }
3905     nl_msg_end_nested(odp_actions, offset);
3906 }
3907
3908 /* If any of the flow key data that ODP actions can modify are different in
3909  * 'base->tunnel' and 'flow->tunnel', appends a set_tunnel ODP action to
3910  * 'odp_actions' that change the flow tunneling information in key from
3911  * 'base->tunnel' into 'flow->tunnel', and then changes 'base->tunnel' in the
3912  * same way.  In other words, operates the same as commit_odp_actions(), but
3913  * only on tunneling information. */
3914 void
3915 commit_odp_tunnel_action(const struct flow *flow, struct flow *base,
3916                          struct ofpbuf *odp_actions)
3917 {
3918     /* A valid IPV4_TUNNEL must have non-zero ip_dst. */
3919     if (flow->tunnel.ip_dst) {
3920         if (!memcmp(&base->tunnel, &flow->tunnel, sizeof base->tunnel)) {
3921             return;
3922         }
3923         memcpy(&base->tunnel, &flow->tunnel, sizeof base->tunnel);
3924         odp_put_tunnel_action(&base->tunnel, odp_actions);
3925     }
3926 }
3927
3928 static bool
3929 commit(enum ovs_key_attr attr, bool use_masked_set,
3930        const void *key, void *base, void *mask, size_t size,
3931        struct ofpbuf *odp_actions)
3932 {
3933     if (memcmp(key, base, size)) {
3934         bool fully_masked = odp_mask_is_exact(attr, mask, size);
3935
3936         if (use_masked_set && !fully_masked) {
3937             commit_masked_set_action(odp_actions, attr, key, mask, size);
3938         } else {
3939             if (!fully_masked) {
3940                 memset(mask, 0xff, size);
3941             }
3942             commit_set_action(odp_actions, attr, key, size);
3943         }
3944         memcpy(base, key, size);
3945         return true;
3946     } else {
3947         /* Mask bits are set when we have either read or set the corresponding
3948          * values.  Masked bits will be exact-matched, no need to set them
3949          * if the value did not actually change. */
3950         return false;
3951     }
3952 }
3953
3954 static void
3955 get_ethernet_key(const struct flow *flow, struct ovs_key_ethernet *eth)
3956 {
3957     memcpy(eth->eth_src, flow->dl_src, ETH_ADDR_LEN);
3958     memcpy(eth->eth_dst, flow->dl_dst, ETH_ADDR_LEN);
3959 }
3960
3961 static void
3962 put_ethernet_key(const struct ovs_key_ethernet *eth, struct flow *flow)
3963 {
3964     memcpy(flow->dl_src, eth->eth_src, ETH_ADDR_LEN);
3965     memcpy(flow->dl_dst, eth->eth_dst, ETH_ADDR_LEN);
3966 }
3967
3968 static void
3969 commit_set_ether_addr_action(const struct flow *flow, struct flow *base_flow,
3970                              struct ofpbuf *odp_actions,
3971                              struct flow_wildcards *wc,
3972                              bool use_masked)
3973 {
3974     struct ovs_key_ethernet key, base, mask;
3975
3976     get_ethernet_key(flow, &key);
3977     get_ethernet_key(base_flow, &base);
3978     get_ethernet_key(&wc->masks, &mask);
3979
3980     if (commit(OVS_KEY_ATTR_ETHERNET, use_masked,
3981                &key, &base, &mask, sizeof key, odp_actions)) {
3982         put_ethernet_key(&base, base_flow);
3983         put_ethernet_key(&mask, &wc->masks);
3984     }
3985 }
3986
3987 static void
3988 pop_vlan(struct flow *base,
3989          struct ofpbuf *odp_actions, struct flow_wildcards *wc)
3990 {
3991     memset(&wc->masks.vlan_tci, 0xff, sizeof wc->masks.vlan_tci);
3992
3993     if (base->vlan_tci & htons(VLAN_CFI)) {
3994         nl_msg_put_flag(odp_actions, OVS_ACTION_ATTR_POP_VLAN);
3995         base->vlan_tci = 0;
3996     }
3997 }
3998
3999 static void
4000 commit_vlan_action(ovs_be16 vlan_tci, struct flow *base,
4001                    struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4002 {
4003     if (base->vlan_tci == vlan_tci) {
4004         return;
4005     }
4006
4007     pop_vlan(base, odp_actions, wc);
4008     if (vlan_tci & htons(VLAN_CFI)) {
4009         struct ovs_action_push_vlan vlan;
4010
4011         vlan.vlan_tpid = htons(ETH_TYPE_VLAN);
4012         vlan.vlan_tci = vlan_tci;
4013         nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_PUSH_VLAN,
4014                           &vlan, sizeof vlan);
4015     }
4016     base->vlan_tci = vlan_tci;
4017 }
4018
4019 /* Wildcarding already done at action translation time. */
4020 static void
4021 commit_mpls_action(const struct flow *flow, struct flow *base,
4022                    struct ofpbuf *odp_actions)
4023 {
4024     int base_n = flow_count_mpls_labels(base, NULL);
4025     int flow_n = flow_count_mpls_labels(flow, NULL);
4026     int common_n = flow_count_common_mpls_labels(flow, flow_n, base, base_n,
4027                                                  NULL);
4028
4029     while (base_n > common_n) {
4030         if (base_n - 1 == common_n && flow_n > common_n) {
4031             /* If there is only one more LSE in base than there are common
4032              * between base and flow; and flow has at least one more LSE than
4033              * is common then the topmost LSE of base may be updated using
4034              * set */
4035             struct ovs_key_mpls mpls_key;
4036
4037             mpls_key.mpls_lse = flow->mpls_lse[flow_n - base_n];
4038             commit_set_action(odp_actions, OVS_KEY_ATTR_MPLS,
4039                               &mpls_key, sizeof mpls_key);
4040             flow_set_mpls_lse(base, 0, mpls_key.mpls_lse);
4041             common_n++;
4042         } else {
4043             /* Otherwise, if there more LSEs in base than are common between
4044              * base and flow then pop the topmost one. */
4045             ovs_be16 dl_type;
4046             bool popped;
4047
4048             /* If all the LSEs are to be popped and this is not the outermost
4049              * LSE then use ETH_TYPE_MPLS as the ethertype parameter of the
4050              * POP_MPLS action instead of flow->dl_type.
4051              *
4052              * This is because the POP_MPLS action requires its ethertype
4053              * argument to be an MPLS ethernet type but in this case
4054              * flow->dl_type will be a non-MPLS ethernet type.
4055              *
4056              * When the final POP_MPLS action occurs it use flow->dl_type and
4057              * the and the resulting packet will have the desired dl_type. */
4058             if ((!eth_type_mpls(flow->dl_type)) && base_n > 1) {
4059                 dl_type = htons(ETH_TYPE_MPLS);
4060             } else {
4061                 dl_type = flow->dl_type;
4062             }
4063             nl_msg_put_be16(odp_actions, OVS_ACTION_ATTR_POP_MPLS, dl_type);
4064             popped = flow_pop_mpls(base, base_n, flow->dl_type, NULL);
4065             ovs_assert(popped);
4066             base_n--;
4067         }
4068     }
4069
4070     /* If, after the above popping and setting, there are more LSEs in flow
4071      * than base then some LSEs need to be pushed. */
4072     while (base_n < flow_n) {
4073         struct ovs_action_push_mpls *mpls;
4074
4075         mpls = nl_msg_put_unspec_zero(odp_actions,
4076                                       OVS_ACTION_ATTR_PUSH_MPLS,
4077                                       sizeof *mpls);
4078         mpls->mpls_ethertype = flow->dl_type;
4079         mpls->mpls_lse = flow->mpls_lse[flow_n - base_n - 1];
4080         flow_push_mpls(base, base_n, mpls->mpls_ethertype, NULL);
4081         flow_set_mpls_lse(base, 0, mpls->mpls_lse);
4082         base_n++;
4083     }
4084 }
4085
4086 static void
4087 get_ipv4_key(const struct flow *flow, struct ovs_key_ipv4 *ipv4, bool is_mask)
4088 {
4089     ipv4->ipv4_src = flow->nw_src;
4090     ipv4->ipv4_dst = flow->nw_dst;
4091     ipv4->ipv4_proto = flow->nw_proto;
4092     ipv4->ipv4_tos = flow->nw_tos;
4093     ipv4->ipv4_ttl = flow->nw_ttl;
4094     ipv4->ipv4_frag = ovs_to_odp_frag(flow->nw_frag, is_mask);
4095 }
4096
4097 static void
4098 put_ipv4_key(const struct ovs_key_ipv4 *ipv4, struct flow *flow, bool is_mask)
4099 {
4100     flow->nw_src = ipv4->ipv4_src;
4101     flow->nw_dst = ipv4->ipv4_dst;
4102     flow->nw_proto = ipv4->ipv4_proto;
4103     flow->nw_tos = ipv4->ipv4_tos;
4104     flow->nw_ttl = ipv4->ipv4_ttl;
4105     flow->nw_frag = odp_to_ovs_frag(ipv4->ipv4_frag, is_mask);
4106 }
4107
4108 static void
4109 commit_set_ipv4_action(const struct flow *flow, struct flow *base_flow,
4110                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4111                        bool use_masked)
4112 {
4113     struct ovs_key_ipv4 key, mask, base;
4114
4115     /* Check that nw_proto and nw_frag remain unchanged. */
4116     ovs_assert(flow->nw_proto == base_flow->nw_proto &&
4117                flow->nw_frag == base_flow->nw_frag);
4118
4119     get_ipv4_key(flow, &key, false);
4120     get_ipv4_key(base_flow, &base, false);
4121     get_ipv4_key(&wc->masks, &mask, true);
4122     mask.ipv4_proto = 0;        /* Not writeable. */
4123     mask.ipv4_frag = 0;         /* Not writable. */
4124
4125     if (commit(OVS_KEY_ATTR_IPV4, use_masked, &key, &base, &mask, sizeof key,
4126                odp_actions)) {
4127         put_ipv4_key(&base, base_flow, false);
4128         if (mask.ipv4_proto != 0) { /* Mask was changed by commit(). */
4129             put_ipv4_key(&mask, &wc->masks, true);
4130         }
4131    }
4132 }
4133
4134 static void
4135 get_ipv6_key(const struct flow *flow, struct ovs_key_ipv6 *ipv6, bool is_mask)
4136 {
4137     memcpy(ipv6->ipv6_src, &flow->ipv6_src, sizeof ipv6->ipv6_src);
4138     memcpy(ipv6->ipv6_dst, &flow->ipv6_dst, sizeof ipv6->ipv6_dst);
4139     ipv6->ipv6_label = flow->ipv6_label;
4140     ipv6->ipv6_proto = flow->nw_proto;
4141     ipv6->ipv6_tclass = flow->nw_tos;
4142     ipv6->ipv6_hlimit = flow->nw_ttl;
4143     ipv6->ipv6_frag = ovs_to_odp_frag(flow->nw_frag, is_mask);
4144 }
4145
4146 static void
4147 put_ipv6_key(const struct ovs_key_ipv6 *ipv6, struct flow *flow, bool is_mask)
4148 {
4149     memcpy(&flow->ipv6_src, ipv6->ipv6_src, sizeof flow->ipv6_src);
4150     memcpy(&flow->ipv6_dst, ipv6->ipv6_dst, sizeof flow->ipv6_dst);
4151     flow->ipv6_label = ipv6->ipv6_label;
4152     flow->nw_proto = ipv6->ipv6_proto;
4153     flow->nw_tos = ipv6->ipv6_tclass;
4154     flow->nw_ttl = ipv6->ipv6_hlimit;
4155     flow->nw_frag = odp_to_ovs_frag(ipv6->ipv6_frag, is_mask);
4156 }
4157
4158 static void
4159 commit_set_ipv6_action(const struct flow *flow, struct flow *base_flow,
4160                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4161                        bool use_masked)
4162 {
4163     struct ovs_key_ipv6 key, mask, base;
4164
4165     /* Check that nw_proto and nw_frag remain unchanged. */
4166     ovs_assert(flow->nw_proto == base_flow->nw_proto &&
4167                flow->nw_frag == base_flow->nw_frag);
4168
4169     get_ipv6_key(flow, &key, false);
4170     get_ipv6_key(base_flow, &base, false);
4171     get_ipv6_key(&wc->masks, &mask, true);
4172     mask.ipv6_proto = 0;        /* Not writeable. */
4173     mask.ipv6_frag = 0;         /* Not writable. */
4174
4175     if (commit(OVS_KEY_ATTR_IPV6, use_masked, &key, &base, &mask, sizeof key,
4176                odp_actions)) {
4177         put_ipv6_key(&base, base_flow, false);
4178         if (mask.ipv6_proto != 0) { /* Mask was changed by commit(). */
4179             put_ipv6_key(&mask, &wc->masks, true);
4180         }
4181     }
4182 }
4183
4184 static void
4185 get_arp_key(const struct flow *flow, struct ovs_key_arp *arp)
4186 {
4187     /* ARP key has padding, clear it. */
4188     memset(arp, 0, sizeof *arp);
4189
4190     arp->arp_sip = flow->nw_src;
4191     arp->arp_tip = flow->nw_dst;
4192     arp->arp_op = htons(flow->nw_proto);
4193     memcpy(arp->arp_sha, flow->arp_sha, ETH_ADDR_LEN);
4194     memcpy(arp->arp_tha, flow->arp_tha, ETH_ADDR_LEN);
4195 }
4196
4197 static void
4198 put_arp_key(const struct ovs_key_arp *arp, struct flow *flow)
4199 {
4200     flow->nw_src = arp->arp_sip;
4201     flow->nw_dst = arp->arp_tip;
4202     flow->nw_proto = ntohs(arp->arp_op);
4203     memcpy(flow->arp_sha, arp->arp_sha, ETH_ADDR_LEN);
4204     memcpy(flow->arp_tha, arp->arp_tha, ETH_ADDR_LEN);
4205 }
4206
4207 static enum slow_path_reason
4208 commit_set_arp_action(const struct flow *flow, struct flow *base_flow,
4209                       struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4210 {
4211     struct ovs_key_arp key, mask, base;
4212
4213     get_arp_key(flow, &key);
4214     get_arp_key(base_flow, &base);
4215     get_arp_key(&wc->masks, &mask);
4216
4217     if (commit(OVS_KEY_ATTR_ARP, true, &key, &base, &mask, sizeof key,
4218                odp_actions)) {
4219         put_arp_key(&base, base_flow);
4220         put_arp_key(&mask, &wc->masks);
4221         return SLOW_ACTION;
4222     }
4223     return 0;
4224 }
4225
4226 static void
4227 get_nd_key(const struct flow *flow, struct ovs_key_nd *nd)
4228 {
4229     memcpy(nd->nd_target, &flow->nd_target, sizeof flow->nd_target);
4230     /* nd_sll and nd_tll are stored in arp_sha and arp_tha, respectively */
4231     memcpy(nd->nd_sll, flow->arp_sha, ETH_ADDR_LEN);
4232     memcpy(nd->nd_tll, flow->arp_tha, ETH_ADDR_LEN);
4233 }
4234
4235 static void
4236 put_nd_key(const struct ovs_key_nd *nd, struct flow *flow)
4237 {
4238     memcpy(&flow->nd_target, &flow->nd_target, sizeof flow->nd_target);
4239     /* nd_sll and nd_tll are stored in arp_sha and arp_tha, respectively */
4240     memcpy(flow->arp_sha, nd->nd_sll, ETH_ADDR_LEN);
4241     memcpy(flow->arp_tha, nd->nd_tll, ETH_ADDR_LEN);
4242 }
4243
4244 static enum slow_path_reason
4245 commit_set_nd_action(const struct flow *flow, struct flow *base_flow,
4246                      struct ofpbuf *odp_actions,
4247                      struct flow_wildcards *wc, bool use_masked)
4248 {
4249     struct ovs_key_nd key, mask, base;
4250
4251     get_nd_key(flow, &key);
4252     get_nd_key(base_flow, &base);
4253     get_nd_key(&wc->masks, &mask);
4254
4255     if (commit(OVS_KEY_ATTR_ND, use_masked, &key, &base, &mask, sizeof key,
4256                odp_actions)) {
4257         put_nd_key(&base, base_flow);
4258         put_nd_key(&mask, &wc->masks);
4259         return SLOW_ACTION;
4260     }
4261
4262     return 0;
4263 }
4264
4265 static enum slow_path_reason
4266 commit_set_nw_action(const struct flow *flow, struct flow *base,
4267                      struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4268                      bool use_masked)
4269 {
4270     /* Check if 'flow' really has an L3 header. */
4271     if (!flow->nw_proto) {
4272         return 0;
4273     }
4274
4275     switch (ntohs(base->dl_type)) {
4276     case ETH_TYPE_IP:
4277         commit_set_ipv4_action(flow, base, odp_actions, wc, use_masked);
4278         break;
4279
4280     case ETH_TYPE_IPV6:
4281         commit_set_ipv6_action(flow, base, odp_actions, wc, use_masked);
4282         return commit_set_nd_action(flow, base, odp_actions, wc, use_masked);
4283
4284     case ETH_TYPE_ARP:
4285         return commit_set_arp_action(flow, base, odp_actions, wc);
4286     }
4287
4288     return 0;
4289 }
4290
4291 /* TCP, UDP, and SCTP keys have the same layout. */
4292 BUILD_ASSERT_DECL(sizeof(struct ovs_key_tcp) == sizeof(struct ovs_key_udp) &&
4293                   sizeof(struct ovs_key_tcp) == sizeof(struct ovs_key_sctp));
4294
4295 static void
4296 get_tp_key(const struct flow *flow, union ovs_key_tp *tp)
4297 {
4298     tp->tcp.tcp_src = flow->tp_src;
4299     tp->tcp.tcp_dst = flow->tp_dst;
4300 }
4301
4302 static void
4303 put_tp_key(const union ovs_key_tp *tp, struct flow *flow)
4304 {
4305     flow->tp_src = tp->tcp.tcp_src;
4306     flow->tp_dst = tp->tcp.tcp_dst;
4307 }
4308
4309 static void
4310 commit_set_port_action(const struct flow *flow, struct flow *base_flow,
4311                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4312                        bool use_masked)
4313 {
4314     enum ovs_key_attr key_type;
4315     union ovs_key_tp key, mask, base;
4316
4317     /* Check if 'flow' really has an L3 header. */
4318     if (!flow->nw_proto) {
4319         return;
4320     }
4321
4322     if (!is_ip_any(base_flow)) {
4323         return;
4324     }
4325
4326     if (flow->nw_proto == IPPROTO_TCP) {
4327         key_type = OVS_KEY_ATTR_TCP;
4328     } else if (flow->nw_proto == IPPROTO_UDP) {
4329         key_type = OVS_KEY_ATTR_UDP;
4330     } else if (flow->nw_proto == IPPROTO_SCTP) {
4331         key_type = OVS_KEY_ATTR_SCTP;
4332     } else {
4333         return;
4334     }
4335
4336     get_tp_key(flow, &key);
4337     get_tp_key(base_flow, &base);
4338     get_tp_key(&wc->masks, &mask);
4339
4340     if (commit(key_type, use_masked, &key, &base, &mask, sizeof key,
4341                odp_actions)) {
4342         put_tp_key(&base, base_flow);
4343         put_tp_key(&mask, &wc->masks);
4344     }
4345 }
4346
4347 static void
4348 commit_set_priority_action(const struct flow *flow, struct flow *base_flow,
4349                            struct ofpbuf *odp_actions,
4350                            struct flow_wildcards *wc,
4351                            bool use_masked)
4352 {
4353     uint32_t key, mask, base;
4354
4355     key = flow->skb_priority;
4356     base = base_flow->skb_priority;
4357     mask = wc->masks.skb_priority;
4358
4359     if (commit(OVS_KEY_ATTR_PRIORITY, use_masked, &key, &base, &mask,
4360                sizeof key, odp_actions)) {
4361         base_flow->skb_priority = base;
4362         wc->masks.skb_priority = mask;
4363     }
4364 }
4365
4366 static void
4367 commit_set_pkt_mark_action(const struct flow *flow, struct flow *base_flow,
4368                            struct ofpbuf *odp_actions,
4369                            struct flow_wildcards *wc,
4370                            bool use_masked)
4371 {
4372     uint32_t key, mask, base;
4373
4374     key = flow->pkt_mark;
4375     base = base_flow->pkt_mark;
4376     mask = wc->masks.pkt_mark;
4377
4378     if (commit(OVS_KEY_ATTR_SKB_MARK, use_masked, &key, &base, &mask,
4379                sizeof key, odp_actions)) {
4380         base_flow->pkt_mark = base;
4381         wc->masks.pkt_mark = mask;
4382     }
4383 }
4384
4385 /* If any of the flow key data that ODP actions can modify are different in
4386  * 'base' and 'flow', appends ODP actions to 'odp_actions' that change the flow
4387  * key from 'base' into 'flow', and then changes 'base' the same way.  Does not
4388  * commit set_tunnel actions.  Users should call commit_odp_tunnel_action()
4389  * in addition to this function if needed.  Sets fields in 'wc' that are
4390  * used as part of the action.
4391  *
4392  * Returns a reason to force processing the flow's packets into the userspace
4393  * slow path, if there is one, otherwise 0. */
4394 enum slow_path_reason
4395 commit_odp_actions(const struct flow *flow, struct flow *base,
4396                    struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4397                    bool use_masked)
4398 {
4399     enum slow_path_reason slow;
4400
4401     commit_set_ether_addr_action(flow, base, odp_actions, wc, use_masked);
4402     slow = commit_set_nw_action(flow, base, odp_actions, wc, use_masked);
4403     commit_set_port_action(flow, base, odp_actions, wc, use_masked);
4404     commit_mpls_action(flow, base, odp_actions);
4405     commit_vlan_action(flow->vlan_tci, base, odp_actions, wc);
4406     commit_set_priority_action(flow, base, odp_actions, wc, use_masked);
4407     commit_set_pkt_mark_action(flow, base, odp_actions, wc, use_masked);
4408
4409     return slow;
4410 }