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