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