odp-util: Simplify parsing function for GCC.
[cascardo/ovs.git] / lib / odp-util.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <arpa/inet.h>
19 #include "odp-util.h"
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <math.h>
23 #include <netinet/in.h>
24 #include <netinet/icmp6.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "byte-order.h"
29 #include "coverage.h"
30 #include "dpif.h"
31 #include "dynamic-string.h"
32 #include "flow.h"
33 #include "netlink.h"
34 #include "ofpbuf.h"
35 #include "packets.h"
36 #include "simap.h"
37 #include "timeval.h"
38 #include "unaligned.h"
39 #include "util.h"
40 #include "openvswitch/vlog.h"
41
42 VLOG_DEFINE_THIS_MODULE(odp_util);
43
44 /* The interface between userspace and kernel uses an "OVS_*" prefix.
45  * Since this is fairly non-specific for the OVS userspace components,
46  * "ODP_*" (Open vSwitch Datapath) is used as the prefix for
47  * interactions with the datapath.
48  */
49
50 /* The set of characters that may separate one action or one key attribute
51  * from another. */
52 static const char *delimiters = ", \t\r\n";
53
54 static const char *hex_chars = "0123456789abcdefABCDEF";
55
56 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 #define GENEVE_OPT(class, type) ((OVS_FORCE uint32_t)(class) << 8 | (type))
1322 static int
1323 parse_geneve_opts(const struct nlattr *attr)
1324 {
1325     int opts_len = nl_attr_get_size(attr);
1326     const struct geneve_opt *opt = nl_attr_get(attr);
1327
1328     while (opts_len > 0) {
1329         int len;
1330
1331         if (opts_len < sizeof(*opt)) {
1332             return -EINVAL;
1333         }
1334
1335         len = sizeof(*opt) + opt->length * 4;
1336         if (len > opts_len) {
1337             return -EINVAL;
1338         }
1339
1340         switch (GENEVE_OPT(opt->opt_class, opt->type)) {
1341         default:
1342             if (opt->type & GENEVE_CRIT_OPT_TYPE) {
1343                 return -EINVAL;
1344             }
1345         };
1346
1347         opt = opt + len / sizeof(*opt);
1348         opts_len -= len;
1349     };
1350
1351     return 0;
1352 }
1353
1354 enum odp_key_fitness
1355 odp_tun_key_from_attr(const struct nlattr *attr, struct flow_tnl *tun)
1356 {
1357     unsigned int left;
1358     const struct nlattr *a;
1359     bool ttl = false;
1360     bool unknown = false;
1361
1362     NL_NESTED_FOR_EACH(a, left, attr) {
1363         uint16_t type = nl_attr_type(a);
1364         size_t len = nl_attr_get_size(a);
1365         int expected_len = odp_key_attr_len(ovs_tun_key_attr_lens,
1366                                             OVS_TUNNEL_ATTR_MAX, type);
1367
1368         if (len != expected_len && expected_len >= 0) {
1369             return ODP_FIT_ERROR;
1370         }
1371
1372         switch (type) {
1373         case OVS_TUNNEL_KEY_ATTR_ID:
1374             tun->tun_id = nl_attr_get_be64(a);
1375             tun->flags |= FLOW_TNL_F_KEY;
1376             break;
1377         case OVS_TUNNEL_KEY_ATTR_IPV4_SRC:
1378             tun->ip_src = nl_attr_get_be32(a);
1379             break;
1380         case OVS_TUNNEL_KEY_ATTR_IPV4_DST:
1381             tun->ip_dst = nl_attr_get_be32(a);
1382             break;
1383         case OVS_TUNNEL_KEY_ATTR_TOS:
1384             tun->ip_tos = nl_attr_get_u8(a);
1385             break;
1386         case OVS_TUNNEL_KEY_ATTR_TTL:
1387             tun->ip_ttl = nl_attr_get_u8(a);
1388             ttl = true;
1389             break;
1390         case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT:
1391             tun->flags |= FLOW_TNL_F_DONT_FRAGMENT;
1392             break;
1393         case OVS_TUNNEL_KEY_ATTR_CSUM:
1394             tun->flags |= FLOW_TNL_F_CSUM;
1395             break;
1396         case OVS_TUNNEL_KEY_ATTR_TP_SRC:
1397             tun->tp_src = nl_attr_get_be16(a);
1398             break;
1399         case OVS_TUNNEL_KEY_ATTR_TP_DST:
1400             tun->tp_dst = nl_attr_get_be16(a);
1401             break;
1402         case OVS_TUNNEL_KEY_ATTR_OAM:
1403             tun->flags |= FLOW_TNL_F_OAM;
1404             break;
1405         case OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS: {
1406             static const struct nl_policy vxlan_opts_policy[] = {
1407                 [OVS_VXLAN_EXT_GBP] = { .type = NL_A_U32 },
1408             };
1409             struct nlattr *ext[ARRAY_SIZE(vxlan_opts_policy)];
1410
1411             if (!nl_parse_nested(a, vxlan_opts_policy, ext, ARRAY_SIZE(ext))) {
1412                 return ODP_FIT_ERROR;
1413             }
1414
1415             if (ext[OVS_VXLAN_EXT_GBP]) {
1416                 uint32_t gbp = nl_attr_get_u32(ext[OVS_VXLAN_EXT_GBP]);
1417
1418                 tun->gbp_id = htons(gbp & 0xFFFF);
1419                 tun->gbp_flags = (gbp >> 16) & 0xFF;
1420             }
1421
1422             break;
1423         }
1424         case OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS: {
1425             if (parse_geneve_opts(a)) {
1426                 return ODP_FIT_ERROR;
1427             }
1428             /* It is necessary to reproduce options exactly (including order)
1429              * so it's easiest to just echo them back. */
1430             unknown = true;
1431             break;
1432         }
1433         default:
1434             /* Allow this to show up as unexpected, if there are unknown
1435              * tunnel attribute, eventually resulting in ODP_FIT_TOO_MUCH. */
1436             unknown = true;
1437             break;
1438         }
1439     }
1440
1441     if (!ttl) {
1442         return ODP_FIT_ERROR;
1443     }
1444     if (unknown) {
1445         return ODP_FIT_TOO_MUCH;
1446     }
1447     return ODP_FIT_PERFECT;
1448 }
1449
1450 static void
1451 tun_key_to_attr(struct ofpbuf *a, const struct flow_tnl *tun_key)
1452 {
1453     size_t tun_key_ofs;
1454
1455     tun_key_ofs = nl_msg_start_nested(a, OVS_KEY_ATTR_TUNNEL);
1456
1457     /* tun_id != 0 without FLOW_TNL_F_KEY is valid if tun_key is a mask. */
1458     if (tun_key->tun_id || tun_key->flags & FLOW_TNL_F_KEY) {
1459         nl_msg_put_be64(a, OVS_TUNNEL_KEY_ATTR_ID, tun_key->tun_id);
1460     }
1461     if (tun_key->ip_src) {
1462         nl_msg_put_be32(a, OVS_TUNNEL_KEY_ATTR_IPV4_SRC, tun_key->ip_src);
1463     }
1464     if (tun_key->ip_dst) {
1465         nl_msg_put_be32(a, OVS_TUNNEL_KEY_ATTR_IPV4_DST, tun_key->ip_dst);
1466     }
1467     if (tun_key->ip_tos) {
1468         nl_msg_put_u8(a, OVS_TUNNEL_KEY_ATTR_TOS, tun_key->ip_tos);
1469     }
1470     nl_msg_put_u8(a, OVS_TUNNEL_KEY_ATTR_TTL, tun_key->ip_ttl);
1471     if (tun_key->flags & FLOW_TNL_F_DONT_FRAGMENT) {
1472         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT);
1473     }
1474     if (tun_key->flags & FLOW_TNL_F_CSUM) {
1475         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_CSUM);
1476     }
1477     if (tun_key->tp_src) {
1478         nl_msg_put_be16(a, OVS_TUNNEL_KEY_ATTR_TP_SRC, tun_key->tp_src);
1479     }
1480     if (tun_key->tp_dst) {
1481         nl_msg_put_be16(a, OVS_TUNNEL_KEY_ATTR_TP_DST, tun_key->tp_dst);
1482     }
1483     if (tun_key->flags & FLOW_TNL_F_OAM) {
1484         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_OAM);
1485     }
1486     if (tun_key->gbp_flags || tun_key->gbp_id) {
1487         size_t vxlan_opts_ofs;
1488
1489         vxlan_opts_ofs = nl_msg_start_nested(a, OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS);
1490         nl_msg_put_u32(a, OVS_VXLAN_EXT_GBP,
1491                        (tun_key->gbp_flags << 16) | ntohs(tun_key->gbp_id));
1492         nl_msg_end_nested(a, vxlan_opts_ofs);
1493     }
1494
1495     nl_msg_end_nested(a, tun_key_ofs);
1496 }
1497
1498 static bool
1499 odp_mask_attr_is_wildcard(const struct nlattr *ma)
1500 {
1501     return is_all_zeros(nl_attr_get(ma), nl_attr_get_size(ma));
1502 }
1503
1504 static bool
1505 odp_mask_is_exact(enum ovs_key_attr attr, const void *mask, size_t size)
1506 {
1507     if (attr == OVS_KEY_ATTR_TCP_FLAGS) {
1508         return TCP_FLAGS(*(ovs_be16 *)mask) == TCP_FLAGS(OVS_BE16_MAX);
1509     }
1510     if (attr == OVS_KEY_ATTR_IPV6) {
1511         const struct ovs_key_ipv6 *ipv6_mask = mask;
1512
1513         return
1514             ((ipv6_mask->ipv6_label & htonl(IPV6_LABEL_MASK))
1515              == htonl(IPV6_LABEL_MASK))
1516             && ipv6_mask->ipv6_proto == UINT8_MAX
1517             && ipv6_mask->ipv6_tclass == UINT8_MAX
1518             && ipv6_mask->ipv6_hlimit == UINT8_MAX
1519             && ipv6_mask->ipv6_frag == UINT8_MAX
1520             && ipv6_mask_is_exact((const struct in6_addr *)ipv6_mask->ipv6_src)
1521             && ipv6_mask_is_exact((const struct in6_addr *)ipv6_mask->ipv6_dst);
1522     }
1523     if (attr == OVS_KEY_ATTR_TUNNEL) {
1524         const struct flow_tnl *tun_mask = mask;
1525
1526         return tun_mask->flags == FLOW_TNL_F_MASK
1527             && tun_mask->tun_id == OVS_BE64_MAX
1528             && tun_mask->ip_src == OVS_BE32_MAX
1529             && tun_mask->ip_dst == OVS_BE32_MAX
1530             && tun_mask->ip_tos == UINT8_MAX
1531             && tun_mask->ip_ttl == UINT8_MAX
1532             && tun_mask->tp_src == OVS_BE16_MAX
1533             && tun_mask->tp_dst == OVS_BE16_MAX
1534             && tun_mask->gbp_id == OVS_BE16_MAX
1535             && tun_mask->gbp_flags == UINT8_MAX;
1536     }
1537
1538     if (attr == OVS_KEY_ATTR_ARP) {
1539         /* ARP key has padding, ignore it. */
1540         BUILD_ASSERT_DECL(sizeof(struct ovs_key_arp) == 24);
1541         BUILD_ASSERT_DECL(offsetof(struct ovs_key_arp, arp_tha) == 10 + 6);
1542         size = offsetof(struct ovs_key_arp, arp_tha) + ETH_ADDR_LEN;
1543         ovs_assert(((uint16_t *)mask)[size/2] == 0);
1544     }
1545
1546     return is_all_ones(mask, size);
1547 }
1548
1549 static bool
1550 odp_mask_attr_is_exact(const struct nlattr *ma)
1551 {
1552     struct flow_tnl tun_mask;
1553     enum ovs_key_attr attr = nl_attr_type(ma);
1554     const void *mask;
1555     size_t size;
1556
1557     if (attr == OVS_KEY_ATTR_TUNNEL) {
1558         memset(&tun_mask, 0, sizeof tun_mask);
1559         odp_tun_key_from_attr(ma, &tun_mask);
1560         mask = &tun_mask;
1561         size = sizeof tun_mask;
1562     } else {
1563         mask = nl_attr_get(ma);
1564         size = nl_attr_get_size(ma);
1565     }
1566
1567     return odp_mask_is_exact(attr, mask, size);
1568 }
1569
1570 void
1571 odp_portno_names_set(struct hmap *portno_names, odp_port_t port_no,
1572                      char *port_name)
1573 {
1574     struct odp_portno_names *odp_portno_names;
1575
1576     odp_portno_names = xmalloc(sizeof *odp_portno_names);
1577     odp_portno_names->port_no = port_no;
1578     odp_portno_names->name = xstrdup(port_name);
1579     hmap_insert(portno_names, &odp_portno_names->hmap_node,
1580                 hash_odp_port(port_no));
1581 }
1582
1583 static char *
1584 odp_portno_names_get(const struct hmap *portno_names, odp_port_t port_no)
1585 {
1586     struct odp_portno_names *odp_portno_names;
1587
1588     HMAP_FOR_EACH_IN_BUCKET (odp_portno_names, hmap_node,
1589                              hash_odp_port(port_no), portno_names) {
1590         if (odp_portno_names->port_no == port_no) {
1591             return odp_portno_names->name;
1592         }
1593     }
1594     return NULL;
1595 }
1596
1597 void
1598 odp_portno_names_destroy(struct hmap *portno_names)
1599 {
1600     struct odp_portno_names *odp_portno_names, *odp_portno_names_next;
1601     HMAP_FOR_EACH_SAFE (odp_portno_names, odp_portno_names_next,
1602                         hmap_node, portno_names) {
1603         hmap_remove(portno_names, &odp_portno_names->hmap_node);
1604         free(odp_portno_names->name);
1605         free(odp_portno_names);
1606     }
1607 }
1608
1609 /* Format helpers. */
1610
1611 static void
1612 format_eth(struct ds *ds, const char *name, const uint8_t key[ETH_ADDR_LEN],
1613            const uint8_t (*mask)[ETH_ADDR_LEN], bool verbose)
1614 {
1615     bool mask_empty = mask && eth_addr_is_zero(*mask);
1616
1617     if (verbose || !mask_empty) {
1618         bool mask_full = !mask || eth_mask_is_exact(*mask);
1619
1620         if (mask_full) {
1621             ds_put_format(ds, "%s="ETH_ADDR_FMT",", name, ETH_ADDR_ARGS(key));
1622         } else {
1623             ds_put_format(ds, "%s=", name);
1624             eth_format_masked(key, *mask, ds);
1625             ds_put_char(ds, ',');
1626         }
1627     }
1628 }
1629
1630 static void
1631 format_be64(struct ds *ds, const char *name, ovs_be64 key,
1632             const ovs_be64 *mask, bool verbose)
1633 {
1634     bool mask_empty = mask && !*mask;
1635
1636     if (verbose || !mask_empty) {
1637         bool mask_full = !mask || *mask == OVS_BE64_MAX;
1638
1639         ds_put_format(ds, "%s=0x%"PRIx64, name, ntohll(key));
1640         if (!mask_full) { /* Partially masked. */
1641             ds_put_format(ds, "/%#"PRIx64, ntohll(*mask));
1642         }
1643         ds_put_char(ds, ',');
1644     }
1645 }
1646
1647 static void
1648 format_ipv4(struct ds *ds, const char *name, ovs_be32 key,
1649             const ovs_be32 *mask, bool verbose)
1650 {
1651     bool mask_empty = mask && !*mask;
1652
1653     if (verbose || !mask_empty) {
1654         bool mask_full = !mask || *mask == OVS_BE32_MAX;
1655
1656         ds_put_format(ds, "%s="IP_FMT, name, IP_ARGS(key));
1657         if (!mask_full) { /* Partially masked. */
1658             ds_put_format(ds, "/"IP_FMT, IP_ARGS(*mask));
1659         }
1660         ds_put_char(ds, ',');
1661     }
1662 }
1663
1664 static void
1665 format_ipv6(struct ds *ds, const char *name, const ovs_be32 key_[4],
1666             const ovs_be32 (*mask_)[4], bool verbose)
1667 {
1668     char buf[INET6_ADDRSTRLEN];
1669     const struct in6_addr *key = (const struct in6_addr *)key_;
1670     const struct in6_addr *mask = mask_ ? (const struct in6_addr *)*mask_
1671         : NULL;
1672     bool mask_empty = mask && ipv6_mask_is_any(mask);
1673
1674     if (verbose || !mask_empty) {
1675         bool mask_full = !mask || ipv6_mask_is_exact(mask);
1676
1677         inet_ntop(AF_INET6, key, buf, sizeof buf);
1678         ds_put_format(ds, "%s=%s", name, buf);
1679         if (!mask_full) { /* Partially masked. */
1680             inet_ntop(AF_INET6, mask, buf, sizeof buf);
1681             ds_put_format(ds, "/%s", buf);
1682         }
1683         ds_put_char(ds, ',');
1684     }
1685 }
1686
1687 static void
1688 format_ipv6_label(struct ds *ds, const char *name, ovs_be32 key,
1689                   const ovs_be32 *mask, bool verbose)
1690 {
1691     bool mask_empty = mask && !*mask;
1692
1693     if (verbose || !mask_empty) {
1694         bool mask_full = !mask
1695             || (*mask & htonl(IPV6_LABEL_MASK)) == htonl(IPV6_LABEL_MASK);
1696
1697         ds_put_format(ds, "%s=%#"PRIx32, name, ntohl(key));
1698         if (!mask_full) { /* Partially masked. */
1699             ds_put_format(ds, "/%#"PRIx32, ntohl(*mask));
1700         }
1701         ds_put_char(ds, ',');
1702     }
1703 }
1704
1705 static void
1706 format_u8x(struct ds *ds, const char *name, uint8_t key,
1707            const uint8_t *mask, bool verbose)
1708 {
1709     bool mask_empty = mask && !*mask;
1710
1711     if (verbose || !mask_empty) {
1712         bool mask_full = !mask || *mask == UINT8_MAX;
1713
1714         ds_put_format(ds, "%s=%#"PRIx8, name, key);
1715         if (!mask_full) { /* Partially masked. */
1716             ds_put_format(ds, "/%#"PRIx8, *mask);
1717         }
1718         ds_put_char(ds, ',');
1719     }
1720 }
1721
1722 static void
1723 format_u8u(struct ds *ds, const char *name, uint8_t key,
1724            const uint8_t *mask, bool verbose)
1725 {
1726     bool mask_empty = mask && !*mask;
1727
1728     if (verbose || !mask_empty) {
1729         bool mask_full = !mask || *mask == UINT8_MAX;
1730
1731         ds_put_format(ds, "%s=%"PRIu8, name, key);
1732         if (!mask_full) { /* Partially masked. */
1733             ds_put_format(ds, "/%#"PRIx8, *mask);
1734         }
1735         ds_put_char(ds, ',');
1736     }
1737 }
1738
1739 static void
1740 format_be16(struct ds *ds, const char *name, ovs_be16 key,
1741             const ovs_be16 *mask, bool verbose)
1742 {
1743     bool mask_empty = mask && !*mask;
1744
1745     if (verbose || !mask_empty) {
1746         bool mask_full = !mask || *mask == OVS_BE16_MAX;
1747
1748         ds_put_format(ds, "%s=%"PRIu16, name, ntohs(key));
1749         if (!mask_full) { /* Partially masked. */
1750             ds_put_format(ds, "/%#"PRIx16, ntohs(*mask));
1751         }
1752         ds_put_char(ds, ',');
1753     }
1754 }
1755
1756 static void
1757 format_be16x(struct ds *ds, const char *name, ovs_be16 key,
1758              const ovs_be16 *mask, bool verbose)
1759 {
1760     bool mask_empty = mask && !*mask;
1761
1762     if (verbose || !mask_empty) {
1763         bool mask_full = !mask || *mask == OVS_BE16_MAX;
1764
1765         ds_put_format(ds, "%s=%#"PRIx16, name, ntohs(key));
1766         if (!mask_full) { /* Partially masked. */
1767             ds_put_format(ds, "/%#"PRIx16, ntohs(*mask));
1768         }
1769         ds_put_char(ds, ',');
1770     }
1771 }
1772
1773 static void
1774 format_tun_flags(struct ds *ds, const char *name, uint16_t key,
1775                  const uint16_t *mask, bool verbose)
1776 {
1777     bool mask_empty = mask && !*mask;
1778
1779     if (verbose || !mask_empty) {
1780         bool mask_full = !mask || (*mask & FLOW_TNL_F_MASK) == FLOW_TNL_F_MASK;
1781
1782         ds_put_cstr(ds, name);
1783         ds_put_char(ds, '(');
1784         if (!mask_full) { /* Partially masked. */
1785             format_flags_masked(ds, NULL, flow_tun_flag_to_string, key, *mask);
1786         } else { /* Fully masked. */
1787             format_flags(ds, flow_tun_flag_to_string, key, ',');
1788         }
1789         ds_put_cstr(ds, "),");
1790     }
1791 }
1792
1793 static bool
1794 check_attr_len(struct ds *ds, const struct nlattr *a, const struct nlattr *ma,
1795                const struct attr_len_tbl tbl[], int max_len, bool need_key)
1796 {
1797     int expected_len;
1798
1799     expected_len = odp_key_attr_len(tbl, max_len, nl_attr_type(a));
1800     if (expected_len != ATTR_LEN_VARIABLE &&
1801         expected_len != ATTR_LEN_NESTED) {
1802
1803         bool bad_key_len = nl_attr_get_size(a) != expected_len;
1804         bool bad_mask_len = ma && nl_attr_get_size(ma) != expected_len;
1805
1806         if (bad_key_len || bad_mask_len) {
1807             if (need_key) {
1808                 ds_put_format(ds, "key%u", nl_attr_type(a));
1809             }
1810             if (bad_key_len) {
1811                 ds_put_format(ds, "(bad key length %"PRIuSIZE", expected %d)(",
1812                               nl_attr_get_size(a), expected_len);
1813             }
1814             format_generic_odp_key(a, ds);
1815             if (ma) {
1816                 ds_put_char(ds, '/');
1817                 if (bad_mask_len) {
1818                     ds_put_format(ds, "(bad mask length %"PRIuSIZE", expected %d)(",
1819                                   nl_attr_get_size(ma), expected_len);
1820                 }
1821                 format_generic_odp_key(ma, ds);
1822             }
1823             ds_put_char(ds, ')');
1824             return false;
1825         }
1826     }
1827
1828     return true;
1829 }
1830
1831 static void
1832 format_unknown_key(struct ds *ds, const struct nlattr *a,
1833                    const struct nlattr *ma)
1834 {
1835     ds_put_format(ds, "key%u(", nl_attr_type(a));
1836     format_generic_odp_key(a, ds);
1837     if (ma && !odp_mask_attr_is_exact(ma)) {
1838         ds_put_char(ds, '/');
1839         format_generic_odp_key(ma, ds);
1840     }
1841     ds_put_cstr(ds, "),");
1842 }
1843
1844 static void
1845 format_odp_tun_vxlan_opt(const struct nlattr *attr,
1846                          const struct nlattr *mask_attr, struct ds *ds,
1847                          bool verbose)
1848 {
1849     unsigned int left;
1850     const struct nlattr *a;
1851     struct ofpbuf ofp;
1852
1853     ofpbuf_init(&ofp, 100);
1854     NL_NESTED_FOR_EACH(a, left, attr) {
1855         uint16_t type = nl_attr_type(a);
1856         const struct nlattr *ma = NULL;
1857
1858         if (mask_attr) {
1859             ma = nl_attr_find__(nl_attr_get(mask_attr),
1860                                 nl_attr_get_size(mask_attr), type);
1861             if (!ma) {
1862                 ma = generate_all_wildcard_mask(ovs_vxlan_ext_attr_lens,
1863                                                 OVS_VXLAN_EXT_MAX,
1864                                                 &ofp, a);
1865             }
1866         }
1867
1868         if (!check_attr_len(ds, a, ma, ovs_vxlan_ext_attr_lens,
1869                             OVS_VXLAN_EXT_MAX, true)) {
1870             continue;
1871         }
1872
1873         switch (type) {
1874         case OVS_VXLAN_EXT_GBP: {
1875             uint32_t key = nl_attr_get_u32(a);
1876             ovs_be16 id, id_mask;
1877             uint8_t flags, flags_mask;
1878
1879             id = htons(key & 0xFFFF);
1880             flags = (key >> 16) & 0xFF;
1881             if (ma) {
1882                 uint32_t mask = nl_attr_get_u32(ma);
1883                 id_mask = htons(mask & 0xFFFF);
1884                 flags_mask = (mask >> 16) & 0xFF;
1885             }
1886
1887             ds_put_cstr(ds, "gbp(");
1888             format_be16(ds, "id", id, ma ? &id_mask : NULL, verbose);
1889             format_u8x(ds, "flags", flags, ma ? &flags_mask : NULL, verbose);
1890             ds_chomp(ds, ',');
1891             ds_put_cstr(ds, "),");
1892             break;
1893         }
1894
1895         default:
1896             format_unknown_key(ds, a, ma);
1897         }
1898         ofpbuf_clear(&ofp);
1899     }
1900
1901     ds_chomp(ds, ',');
1902     ofpbuf_uninit(&ofp);
1903 }
1904
1905 #define MASK(PTR, FIELD) PTR ? &PTR->FIELD : NULL
1906
1907 static void
1908 format_odp_tun_geneve(const struct nlattr *attr,
1909                       const struct nlattr *mask_attr, struct ds *ds,
1910                       bool verbose)
1911 {
1912     int opts_len = nl_attr_get_size(attr);
1913     const struct geneve_opt *opt = nl_attr_get(attr);
1914     const struct geneve_opt *mask = mask_attr ?
1915                                     nl_attr_get(mask_attr) : NULL;
1916
1917     if (mask && nl_attr_get_size(attr) != nl_attr_get_size(mask_attr)) {
1918         ds_put_format(ds, "value len %"PRIuSIZE" different from mask len %"PRIuSIZE,
1919                       nl_attr_get_size(attr), nl_attr_get_size(mask_attr));
1920         return;
1921     }
1922
1923     while (opts_len > 0) {
1924         unsigned int len;
1925         uint8_t data_len, data_len_mask;
1926
1927         if (opts_len < sizeof *opt) {
1928             ds_put_format(ds, "opt len %u less than minimum %"PRIuSIZE,
1929                           opts_len, sizeof *opt);
1930             return;
1931         }
1932
1933         data_len = opt->length * 4;
1934         if (mask) {
1935             if (mask->length == 0x1f) {
1936                 data_len_mask = UINT8_MAX;
1937             } else {
1938                 data_len_mask = mask->length;
1939             }
1940         }
1941         len = sizeof *opt + data_len;
1942         if (len > opts_len) {
1943             ds_put_format(ds, "opt len %u greater than remaining %u",
1944                           len, opts_len);
1945             return;
1946         }
1947
1948         ds_put_char(ds, '{');
1949         format_be16x(ds, "class", opt->opt_class, MASK(mask, opt_class),
1950                     verbose);
1951         format_u8x(ds, "type", opt->type, MASK(mask, type), verbose);
1952         format_u8u(ds, "len", data_len, mask ? &data_len_mask : NULL, verbose);
1953         if (verbose || !mask || !is_all_zeros(mask + 1, data_len)) {
1954             ds_put_hex(ds, opt + 1, data_len);
1955             if (mask && !is_all_ones(mask + 1, data_len)) {
1956                 ds_put_char(ds, '/');
1957                 ds_put_hex(ds, mask + 1, data_len);
1958             }
1959         } else {
1960             ds_chomp(ds, ',');
1961         }
1962         ds_put_char(ds, '}');
1963
1964         opt += len / sizeof(*opt);
1965         if (mask) {
1966             mask += len / sizeof(*opt);
1967         }
1968         opts_len -= len;
1969     };
1970 }
1971
1972 static void
1973 format_odp_tun_attr(const struct nlattr *attr, const struct nlattr *mask_attr,
1974                     struct ds *ds, bool verbose)
1975 {
1976     unsigned int left;
1977     const struct nlattr *a;
1978     uint16_t flags = 0;
1979     uint16_t mask_flags = 0;
1980     struct ofpbuf ofp;
1981
1982     ofpbuf_init(&ofp, 100);
1983     NL_NESTED_FOR_EACH(a, left, attr) {
1984         enum ovs_tunnel_key_attr type = nl_attr_type(a);
1985         const struct nlattr *ma = NULL;
1986
1987         if (mask_attr) {
1988             ma = nl_attr_find__(nl_attr_get(mask_attr),
1989                                 nl_attr_get_size(mask_attr), type);
1990             if (!ma) {
1991                 ma = generate_all_wildcard_mask(ovs_tun_key_attr_lens,
1992                                                 OVS_TUNNEL_KEY_ATTR_MAX,
1993                                                 &ofp, a);
1994             }
1995         }
1996
1997         if (!check_attr_len(ds, a, ma, ovs_tun_key_attr_lens,
1998                             OVS_TUNNEL_KEY_ATTR_MAX, true)) {
1999             continue;
2000         }
2001
2002         switch (type) {
2003         case OVS_TUNNEL_KEY_ATTR_ID:
2004             format_be64(ds, "tun_id", nl_attr_get_be64(a),
2005                         ma ? nl_attr_get(ma) : NULL, verbose);
2006             flags |= FLOW_TNL_F_KEY;
2007             if (ma) {
2008                 mask_flags |= FLOW_TNL_F_KEY;
2009             }
2010             break;
2011         case OVS_TUNNEL_KEY_ATTR_IPV4_SRC:
2012             format_ipv4(ds, "src", nl_attr_get_be32(a),
2013                         ma ? nl_attr_get(ma) : NULL, verbose);
2014             break;
2015         case OVS_TUNNEL_KEY_ATTR_IPV4_DST:
2016             format_ipv4(ds, "dst", nl_attr_get_be32(a),
2017                         ma ? nl_attr_get(ma) : NULL, verbose);
2018             break;
2019         case OVS_TUNNEL_KEY_ATTR_TOS:
2020             format_u8x(ds, "tos", nl_attr_get_u8(a),
2021                        ma ? nl_attr_get(ma) : NULL, verbose);
2022             break;
2023         case OVS_TUNNEL_KEY_ATTR_TTL:
2024             format_u8u(ds, "ttl", nl_attr_get_u8(a),
2025                        ma ? nl_attr_get(ma) : NULL, verbose);
2026             break;
2027         case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT:
2028             flags |= FLOW_TNL_F_DONT_FRAGMENT;
2029             break;
2030         case OVS_TUNNEL_KEY_ATTR_CSUM:
2031             flags |= FLOW_TNL_F_CSUM;
2032             break;
2033         case OVS_TUNNEL_KEY_ATTR_TP_SRC:
2034             format_be16(ds, "tp_src", nl_attr_get_be16(a),
2035                         ma ? nl_attr_get(ma) : NULL, verbose);
2036             break;
2037         case OVS_TUNNEL_KEY_ATTR_TP_DST:
2038             format_be16(ds, "tp_dst", nl_attr_get_be16(a),
2039                         ma ? nl_attr_get(ma) : NULL, verbose);
2040             break;
2041         case OVS_TUNNEL_KEY_ATTR_OAM:
2042             flags |= FLOW_TNL_F_OAM;
2043             break;
2044         case OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS:
2045             ds_put_cstr(ds, "vxlan(");
2046             format_odp_tun_vxlan_opt(a, ma, ds, verbose);
2047             ds_put_cstr(ds, "),");
2048             break;
2049         case OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS:
2050             ds_put_cstr(ds, "geneve(");
2051             format_odp_tun_geneve(a, ma, ds, verbose);
2052             ds_put_cstr(ds, "),");
2053             break;
2054         case __OVS_TUNNEL_KEY_ATTR_MAX:
2055         default:
2056             format_unknown_key(ds, a, ma);
2057         }
2058         ofpbuf_clear(&ofp);
2059     }
2060
2061     /* Flags can have a valid mask even if the attribute is not set, so
2062      * we need to collect these separately. */
2063     if (mask_attr) {
2064         NL_NESTED_FOR_EACH(a, left, mask_attr) {
2065             switch (nl_attr_type(a)) {
2066             case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT:
2067                 mask_flags |= FLOW_TNL_F_DONT_FRAGMENT;
2068                 break;
2069             case OVS_TUNNEL_KEY_ATTR_CSUM:
2070                 mask_flags |= FLOW_TNL_F_CSUM;
2071                 break;
2072             case OVS_TUNNEL_KEY_ATTR_OAM:
2073                 mask_flags |= FLOW_TNL_F_OAM;
2074                 break;
2075             }
2076         }
2077     }
2078
2079     format_tun_flags(ds, "flags", flags, mask_attr ? &mask_flags : NULL,
2080                      verbose);
2081     ds_chomp(ds, ',');
2082     ofpbuf_uninit(&ofp);
2083 }
2084
2085 static void
2086 format_frag(struct ds *ds, const char *name, uint8_t key,
2087             const uint8_t *mask, bool verbose)
2088 {
2089     bool mask_empty = mask && !*mask;
2090
2091     /* ODP frag is an enumeration field; partial masks are not meaningful. */
2092     if (verbose || !mask_empty) {
2093         bool mask_full = !mask || *mask == UINT8_MAX;
2094
2095         if (!mask_full) { /* Partially masked. */
2096             ds_put_format(ds, "error: partial mask not supported for frag (%#"
2097                           PRIx8"),", *mask);
2098         } else {
2099             ds_put_format(ds, "%s=%s,", name, ovs_frag_type_to_string(key));
2100         }
2101     }
2102 }
2103
2104 static void
2105 format_odp_key_attr(const struct nlattr *a, const struct nlattr *ma,
2106                     const struct hmap *portno_names, struct ds *ds,
2107                     bool verbose)
2108 {
2109     enum ovs_key_attr attr = nl_attr_type(a);
2110     char namebuf[OVS_KEY_ATTR_BUFSIZE];
2111     bool is_exact;
2112
2113     is_exact = ma ? odp_mask_attr_is_exact(ma) : true;
2114
2115     ds_put_cstr(ds, ovs_key_attr_to_string(attr, namebuf, sizeof namebuf));
2116
2117     if (!check_attr_len(ds, a, ma, ovs_flow_key_attr_lens,
2118                         OVS_KEY_ATTR_MAX, false)) {
2119         return;
2120     }
2121
2122     ds_put_char(ds, '(');
2123     switch (attr) {
2124     case OVS_KEY_ATTR_ENCAP:
2125         if (ma && nl_attr_get_size(ma) && nl_attr_get_size(a)) {
2126             odp_flow_format(nl_attr_get(a), nl_attr_get_size(a),
2127                             nl_attr_get(ma), nl_attr_get_size(ma), NULL, ds,
2128                             verbose);
2129         } else if (nl_attr_get_size(a)) {
2130             odp_flow_format(nl_attr_get(a), nl_attr_get_size(a), NULL, 0, NULL,
2131                             ds, verbose);
2132         }
2133         break;
2134
2135     case OVS_KEY_ATTR_PRIORITY:
2136     case OVS_KEY_ATTR_SKB_MARK:
2137     case OVS_KEY_ATTR_DP_HASH:
2138     case OVS_KEY_ATTR_RECIRC_ID:
2139         ds_put_format(ds, "%#"PRIx32, nl_attr_get_u32(a));
2140         if (!is_exact) {
2141             ds_put_format(ds, "/%#"PRIx32, nl_attr_get_u32(ma));
2142         }
2143         break;
2144
2145     case OVS_KEY_ATTR_TUNNEL:
2146         format_odp_tun_attr(a, ma, ds, verbose);
2147         break;
2148
2149     case OVS_KEY_ATTR_IN_PORT:
2150         if (portno_names && verbose && is_exact) {
2151             char *name = odp_portno_names_get(portno_names,
2152                             u32_to_odp(nl_attr_get_u32(a)));
2153             if (name) {
2154                 ds_put_format(ds, "%s", name);
2155             } else {
2156                 ds_put_format(ds, "%"PRIu32, nl_attr_get_u32(a));
2157             }
2158         } else {
2159             ds_put_format(ds, "%"PRIu32, nl_attr_get_u32(a));
2160             if (!is_exact) {
2161                 ds_put_format(ds, "/%#"PRIx32, nl_attr_get_u32(ma));
2162             }
2163         }
2164         break;
2165
2166     case OVS_KEY_ATTR_ETHERNET: {
2167         const struct ovs_key_ethernet *mask = ma ? nl_attr_get(ma) : NULL;
2168         const struct ovs_key_ethernet *key = nl_attr_get(a);
2169
2170         format_eth(ds, "src", key->eth_src, MASK(mask, eth_src), verbose);
2171         format_eth(ds, "dst", key->eth_dst, MASK(mask, eth_dst), verbose);
2172         ds_chomp(ds, ',');
2173         break;
2174     }
2175     case OVS_KEY_ATTR_VLAN:
2176         format_vlan_tci(ds, nl_attr_get_be16(a),
2177                         ma ? nl_attr_get_be16(ma) : OVS_BE16_MAX, verbose);
2178         break;
2179
2180     case OVS_KEY_ATTR_MPLS: {
2181         const struct ovs_key_mpls *mpls_key = nl_attr_get(a);
2182         const struct ovs_key_mpls *mpls_mask = NULL;
2183         size_t size = nl_attr_get_size(a);
2184
2185         if (!size || size % sizeof *mpls_key) {
2186             ds_put_format(ds, "(bad key length %"PRIuSIZE")", size);
2187             return;
2188         }
2189         if (!is_exact) {
2190             mpls_mask = nl_attr_get(ma);
2191             if (size != nl_attr_get_size(ma)) {
2192                 ds_put_format(ds, "(key length %"PRIuSIZE" != "
2193                               "mask length %"PRIuSIZE")",
2194                               size, nl_attr_get_size(ma));
2195                 return;
2196             }
2197         }
2198         format_mpls(ds, mpls_key, mpls_mask, size / sizeof *mpls_key);
2199         break;
2200     }
2201     case OVS_KEY_ATTR_ETHERTYPE:
2202         ds_put_format(ds, "0x%04"PRIx16, ntohs(nl_attr_get_be16(a)));
2203         if (!is_exact) {
2204             ds_put_format(ds, "/0x%04"PRIx16, ntohs(nl_attr_get_be16(ma)));
2205         }
2206         break;
2207
2208     case OVS_KEY_ATTR_IPV4: {
2209         const struct ovs_key_ipv4 *key = nl_attr_get(a);
2210         const struct ovs_key_ipv4 *mask = ma ? nl_attr_get(ma) : NULL;
2211
2212         format_ipv4(ds, "src", key->ipv4_src, MASK(mask, ipv4_src), verbose);
2213         format_ipv4(ds, "dst", key->ipv4_dst, MASK(mask, ipv4_dst), verbose);
2214         format_u8u(ds, "proto", key->ipv4_proto, MASK(mask, ipv4_proto),
2215                       verbose);
2216         format_u8x(ds, "tos", key->ipv4_tos, MASK(mask, ipv4_tos), verbose);
2217         format_u8u(ds, "ttl", key->ipv4_ttl, MASK(mask, ipv4_ttl), verbose);
2218         format_frag(ds, "frag", key->ipv4_frag, MASK(mask, ipv4_frag),
2219                     verbose);
2220         ds_chomp(ds, ',');
2221         break;
2222     }
2223     case OVS_KEY_ATTR_IPV6: {
2224         const struct ovs_key_ipv6 *key = nl_attr_get(a);
2225         const struct ovs_key_ipv6 *mask = ma ? nl_attr_get(ma) : NULL;
2226
2227         format_ipv6(ds, "src", key->ipv6_src, MASK(mask, ipv6_src), verbose);
2228         format_ipv6(ds, "dst", key->ipv6_dst, MASK(mask, ipv6_dst), verbose);
2229         format_ipv6_label(ds, "label", key->ipv6_label, MASK(mask, ipv6_label),
2230                           verbose);
2231         format_u8u(ds, "proto", key->ipv6_proto, MASK(mask, ipv6_proto),
2232                       verbose);
2233         format_u8x(ds, "tclass", key->ipv6_tclass, MASK(mask, ipv6_tclass),
2234                       verbose);
2235         format_u8u(ds, "hlimit", key->ipv6_hlimit, MASK(mask, ipv6_hlimit),
2236                       verbose);
2237         format_frag(ds, "frag", key->ipv6_frag, MASK(mask, ipv6_frag),
2238                     verbose);
2239         ds_chomp(ds, ',');
2240         break;
2241     }
2242         /* These have the same structure and format. */
2243     case OVS_KEY_ATTR_TCP:
2244     case OVS_KEY_ATTR_UDP:
2245     case OVS_KEY_ATTR_SCTP: {
2246         const struct ovs_key_tcp *key = nl_attr_get(a);
2247         const struct ovs_key_tcp *mask = ma ? nl_attr_get(ma) : NULL;
2248
2249         format_be16(ds, "src", key->tcp_src, MASK(mask, tcp_src), verbose);
2250         format_be16(ds, "dst", key->tcp_dst, MASK(mask, tcp_dst), verbose);
2251         ds_chomp(ds, ',');
2252         break;
2253     }
2254     case OVS_KEY_ATTR_TCP_FLAGS:
2255         if (!is_exact) {
2256             format_flags_masked(ds, NULL, packet_tcp_flag_to_string,
2257                                 ntohs(nl_attr_get_be16(a)),
2258                                 ntohs(nl_attr_get_be16(ma)));
2259         } else {
2260             format_flags(ds, packet_tcp_flag_to_string,
2261                          ntohs(nl_attr_get_be16(a)), ',');
2262         }
2263         break;
2264
2265     case OVS_KEY_ATTR_ICMP: {
2266         const struct ovs_key_icmp *key = nl_attr_get(a);
2267         const struct ovs_key_icmp *mask = ma ? nl_attr_get(ma) : NULL;
2268
2269         format_u8u(ds, "type", key->icmp_type, MASK(mask, icmp_type), verbose);
2270         format_u8u(ds, "code", key->icmp_code, MASK(mask, icmp_code), verbose);
2271         ds_chomp(ds, ',');
2272         break;
2273     }
2274     case OVS_KEY_ATTR_ICMPV6: {
2275         const struct ovs_key_icmpv6 *key = nl_attr_get(a);
2276         const struct ovs_key_icmpv6 *mask = ma ? nl_attr_get(ma) : NULL;
2277
2278         format_u8u(ds, "type", key->icmpv6_type, MASK(mask, icmpv6_type),
2279                    verbose);
2280         format_u8u(ds, "code", key->icmpv6_code, MASK(mask, icmpv6_code),
2281                    verbose);
2282         ds_chomp(ds, ',');
2283         break;
2284     }
2285     case OVS_KEY_ATTR_ARP: {
2286         const struct ovs_key_arp *mask = ma ? nl_attr_get(ma) : NULL;
2287         const struct ovs_key_arp *key = nl_attr_get(a);
2288
2289         format_ipv4(ds, "sip", key->arp_sip, MASK(mask, arp_sip), verbose);
2290         format_ipv4(ds, "tip", key->arp_tip, MASK(mask, arp_tip), verbose);
2291         format_be16(ds, "op", key->arp_op, MASK(mask, arp_op), verbose);
2292         format_eth(ds, "sha", key->arp_sha, MASK(mask, arp_sha), verbose);
2293         format_eth(ds, "tha", key->arp_tha, MASK(mask, arp_tha), verbose);
2294         ds_chomp(ds, ',');
2295         break;
2296     }
2297     case OVS_KEY_ATTR_ND: {
2298         const struct ovs_key_nd *mask = ma ? nl_attr_get(ma) : NULL;
2299         const struct ovs_key_nd *key = nl_attr_get(a);
2300
2301         format_ipv6(ds, "target", key->nd_target, MASK(mask, nd_target),
2302                     verbose);
2303         format_eth(ds, "sll", key->nd_sll, MASK(mask, nd_sll), verbose);
2304         format_eth(ds, "tll", key->nd_tll, MASK(mask, nd_tll), verbose);
2305
2306         ds_chomp(ds, ',');
2307         break;
2308     }
2309     case OVS_KEY_ATTR_UNSPEC:
2310     case __OVS_KEY_ATTR_MAX:
2311     default:
2312         format_generic_odp_key(a, ds);
2313         if (!is_exact) {
2314             ds_put_char(ds, '/');
2315             format_generic_odp_key(ma, ds);
2316         }
2317         break;
2318     }
2319     ds_put_char(ds, ')');
2320 }
2321
2322 static struct nlattr *
2323 generate_all_wildcard_mask(const struct attr_len_tbl tbl[], int max,
2324                            struct ofpbuf *ofp, const struct nlattr *key)
2325 {
2326     const struct nlattr *a;
2327     unsigned int left;
2328     int type = nl_attr_type(key);
2329     int size = nl_attr_get_size(key);
2330
2331     if (odp_key_attr_len(tbl, max, type) != ATTR_LEN_NESTED) {
2332         nl_msg_put_unspec_zero(ofp, type, size);
2333     } else {
2334         size_t nested_mask;
2335
2336         if (tbl[type].next) {
2337             tbl = tbl[type].next;
2338             max = tbl[type].next_max;
2339         }
2340
2341         nested_mask = nl_msg_start_nested(ofp, type);
2342         NL_ATTR_FOR_EACH(a, left, key, nl_attr_get_size(key)) {
2343             generate_all_wildcard_mask(tbl, max, ofp, nl_attr_get(a));
2344         }
2345         nl_msg_end_nested(ofp, nested_mask);
2346     }
2347
2348     return ofp->base;
2349 }
2350
2351 int
2352 odp_ufid_from_string(const char *s_, ovs_u128 *ufid)
2353 {
2354     const char *s = s_;
2355
2356     if (ovs_scan(s, "ufid:")) {
2357         size_t n;
2358
2359         s += 5;
2360         if (ovs_scan(s, "0x")) {
2361             s += 2;
2362         }
2363
2364         n = strspn(s, hex_chars);
2365         if (n != 32) {
2366             return -EINVAL;
2367         }
2368
2369         if (!ovs_scan(s, "%16"SCNx64"%16"SCNx64, &ufid->u64.hi,
2370                       &ufid->u64.lo)) {
2371             return -EINVAL;
2372         }
2373         s += n;
2374         s += strspn(s, delimiters);
2375
2376         return s - s_;
2377     }
2378
2379     return 0;
2380 }
2381
2382 void
2383 odp_format_ufid(const ovs_u128 *ufid, struct ds *ds)
2384 {
2385     ds_put_format(ds, "ufid:%016"PRIx64"%016"PRIx64, ufid->u64.hi,
2386                   ufid->u64.lo);
2387 }
2388
2389 /* Appends to 'ds' a string representation of the 'key_len' bytes of
2390  * OVS_KEY_ATTR_* attributes in 'key'. If non-null, additionally formats the
2391  * 'mask_len' bytes of 'mask' which apply to 'key'. If 'portno_names' is
2392  * non-null and 'verbose' is true, translates odp port number to its name. */
2393 void
2394 odp_flow_format(const struct nlattr *key, size_t key_len,
2395                 const struct nlattr *mask, size_t mask_len,
2396                 const struct hmap *portno_names, struct ds *ds, bool verbose)
2397 {
2398     if (key_len) {
2399         const struct nlattr *a;
2400         unsigned int left;
2401         bool has_ethtype_key = false;
2402         const struct nlattr *ma = NULL;
2403         struct ofpbuf ofp;
2404         bool first_field = true;
2405
2406         ofpbuf_init(&ofp, 100);
2407         NL_ATTR_FOR_EACH (a, left, key, key_len) {
2408             bool is_nested_attr;
2409             bool is_wildcard = false;
2410             int attr_type = nl_attr_type(a);
2411
2412             if (attr_type == OVS_KEY_ATTR_ETHERTYPE) {
2413                 has_ethtype_key = true;
2414             }
2415
2416             is_nested_attr = odp_key_attr_len(ovs_flow_key_attr_lens,
2417                                               OVS_KEY_ATTR_MAX, attr_type) ==
2418                              ATTR_LEN_NESTED;
2419
2420             if (mask && mask_len) {
2421                 ma = nl_attr_find__(mask, mask_len, nl_attr_type(a));
2422                 is_wildcard = ma ? odp_mask_attr_is_wildcard(ma) : true;
2423             }
2424
2425             if (verbose || !is_wildcard  || is_nested_attr) {
2426                 if (is_wildcard && !ma) {
2427                     ma = generate_all_wildcard_mask(ovs_flow_key_attr_lens,
2428                                                     OVS_KEY_ATTR_MAX,
2429                                                     &ofp, a);
2430                 }
2431                 if (!first_field) {
2432                     ds_put_char(ds, ',');
2433                 }
2434                 format_odp_key_attr(a, ma, portno_names, ds, verbose);
2435                 first_field = false;
2436             }
2437             ofpbuf_clear(&ofp);
2438         }
2439         ofpbuf_uninit(&ofp);
2440
2441         if (left) {
2442             int i;
2443
2444             if (left == key_len) {
2445                 ds_put_cstr(ds, "<empty>");
2446             }
2447             ds_put_format(ds, ",***%u leftover bytes*** (", left);
2448             for (i = 0; i < left; i++) {
2449                 ds_put_format(ds, "%02x", ((const uint8_t *) a)[i]);
2450             }
2451             ds_put_char(ds, ')');
2452         }
2453         if (!has_ethtype_key) {
2454             ma = nl_attr_find__(mask, mask_len, OVS_KEY_ATTR_ETHERTYPE);
2455             if (ma) {
2456                 ds_put_format(ds, ",eth_type(0/0x%04"PRIx16")",
2457                               ntohs(nl_attr_get_be16(ma)));
2458             }
2459         }
2460     } else {
2461         ds_put_cstr(ds, "<empty>");
2462     }
2463 }
2464
2465 /* Appends to 'ds' a string representation of the 'key_len' bytes of
2466  * OVS_KEY_ATTR_* attributes in 'key'. */
2467 void
2468 odp_flow_key_format(const struct nlattr *key,
2469                     size_t key_len, struct ds *ds)
2470 {
2471     odp_flow_format(key, key_len, NULL, 0, NULL, ds, true);
2472 }
2473
2474 static bool
2475 ovs_frag_type_from_string(const char *s, enum ovs_frag_type *type)
2476 {
2477     if (!strcasecmp(s, "no")) {
2478         *type = OVS_FRAG_TYPE_NONE;
2479     } else if (!strcasecmp(s, "first")) {
2480         *type = OVS_FRAG_TYPE_FIRST;
2481     } else if (!strcasecmp(s, "later")) {
2482         *type = OVS_FRAG_TYPE_LATER;
2483     } else {
2484         return false;
2485     }
2486     return true;
2487 }
2488
2489 /* Parsing. */
2490
2491 static int
2492 scan_eth(const char *s, uint8_t (*key)[ETH_ADDR_LEN],
2493          uint8_t (*mask)[ETH_ADDR_LEN])
2494 {
2495     int n;
2496
2497     if (ovs_scan(s, ETH_ADDR_SCAN_FMT"%n", ETH_ADDR_SCAN_ARGS(*key), &n)) {
2498         int len = n;
2499
2500         if (mask) {
2501             if (ovs_scan(s + len, "/"ETH_ADDR_SCAN_FMT"%n",
2502                          ETH_ADDR_SCAN_ARGS(*mask), &n)) {
2503                 len += n;
2504             } else {
2505                 memset(mask, 0xff, sizeof *mask);
2506             }
2507         }
2508         return len;
2509     }
2510     return 0;
2511 }
2512
2513 static int
2514 scan_ipv4(const char *s, ovs_be32 *key, ovs_be32 *mask)
2515 {
2516     int n;
2517
2518     if (ovs_scan(s, IP_SCAN_FMT"%n", IP_SCAN_ARGS(key), &n)) {
2519         int len = n;
2520
2521         if (mask) {
2522             if (ovs_scan(s + len, "/"IP_SCAN_FMT"%n",
2523                          IP_SCAN_ARGS(mask), &n)) {
2524                 len += n;
2525             } else {
2526                 *mask = OVS_BE32_MAX;
2527             }
2528         }
2529         return len;
2530     }
2531     return 0;
2532 }
2533
2534 static int
2535 scan_ipv6(const char *s, ovs_be32 (*key)[4], ovs_be32 (*mask)[4])
2536 {
2537     int n;
2538     char ipv6_s[IPV6_SCAN_LEN + 1];
2539
2540     if (ovs_scan(s, IPV6_SCAN_FMT"%n", ipv6_s, &n)
2541         && inet_pton(AF_INET6, ipv6_s, key) == 1) {
2542         int len = n;
2543
2544         if (mask) {
2545             if (ovs_scan(s + len, "/"IPV6_SCAN_FMT"%n", ipv6_s, &n)
2546                 && inet_pton(AF_INET6, ipv6_s, mask) == 1) {
2547                 len += n;
2548             } else {
2549                 memset(mask, 0xff, sizeof *mask);
2550             }
2551         }
2552         return len;
2553     }
2554     return 0;
2555 }
2556
2557 static int
2558 scan_ipv6_label(const char *s, ovs_be32 *key, ovs_be32 *mask)
2559 {
2560     int key_, mask_;
2561     int n;
2562
2563     if (ovs_scan(s, "%i%n", &key_, &n)
2564         && (key_ & ~IPV6_LABEL_MASK) == 0) {
2565         int len = n;
2566
2567         *key = htonl(key_);
2568         if (mask) {
2569             if (ovs_scan(s + len, "/%i%n", &mask_, &n)
2570                 && (mask_ & ~IPV6_LABEL_MASK) == 0) {
2571                 len += n;
2572                 *mask = htonl(mask_);
2573             } else {
2574                 *mask = htonl(IPV6_LABEL_MASK);
2575             }
2576         }
2577         return len;
2578     }
2579     return 0;
2580 }
2581
2582 static int
2583 scan_u8(const char *s, uint8_t *key, uint8_t *mask)
2584 {
2585     int n;
2586
2587     if (ovs_scan(s, "%"SCNi8"%n", key, &n)) {
2588         int len = n;
2589
2590         if (mask) {
2591             if (ovs_scan(s + len, "/%"SCNi8"%n", mask, &n)) {
2592                 len += n;
2593             } else {
2594                 *mask = UINT8_MAX;
2595             }
2596         }
2597         return len;
2598     }
2599     return 0;
2600 }
2601
2602 static int
2603 scan_u32(const char *s, uint32_t *key, uint32_t *mask)
2604 {
2605     int n;
2606
2607     if (ovs_scan(s, "%"SCNi32"%n", key, &n)) {
2608         int len = n;
2609
2610         if (mask) {
2611             if (ovs_scan(s + len, "/%"SCNi32"%n", mask, &n)) {
2612                 len += n;
2613             } else {
2614                 *mask = UINT32_MAX;
2615             }
2616         }
2617         return len;
2618     }
2619     return 0;
2620 }
2621
2622 static int
2623 scan_be16(const char *s, ovs_be16 *key, ovs_be16 *mask)
2624 {
2625     uint16_t key_, mask_;
2626     int n;
2627
2628     if (ovs_scan(s, "%"SCNi16"%n", &key_, &n)) {
2629         int len = n;
2630
2631         *key = htons(key_);
2632         if (mask) {
2633             if (ovs_scan(s + len, "/%"SCNi16"%n", &mask_, &n)) {
2634                 len += n;
2635                 *mask = htons(mask_);
2636             } else {
2637                 *mask = OVS_BE16_MAX;
2638             }
2639         }
2640         return len;
2641     }
2642     return 0;
2643 }
2644
2645 static int
2646 scan_be64(const char *s, ovs_be64 *key, ovs_be64 *mask)
2647 {
2648     uint64_t key_, mask_;
2649     int n;
2650
2651     if (ovs_scan(s, "%"SCNi64"%n", &key_, &n)) {
2652         int len = n;
2653
2654         *key = htonll(key_);
2655         if (mask) {
2656             if (ovs_scan(s + len, "/%"SCNi64"%n", &mask_, &n)) {
2657                 len += n;
2658                 *mask = htonll(mask_);
2659             } else {
2660                 *mask = OVS_BE64_MAX;
2661             }
2662         }
2663         return len;
2664     }
2665     return 0;
2666 }
2667
2668 static int
2669 scan_tun_flags(const char *s, uint16_t *key, uint16_t *mask)
2670 {
2671     uint32_t flags, fmask;
2672     int n;
2673
2674     n = parse_flags(s, flow_tun_flag_to_string, &flags,
2675                     FLOW_TNL_F_MASK, mask ? &fmask : NULL);
2676     if (n >= 0 && s[n] == ')') {
2677         *key = flags;
2678         if (mask) {
2679             *mask = fmask;
2680         }
2681         return n + 1;
2682     }
2683     return 0;
2684 }
2685
2686 static int
2687 scan_tcp_flags(const char *s, ovs_be16 *key, ovs_be16 *mask)
2688 {
2689     uint32_t flags, fmask;
2690     int n;
2691
2692     n = parse_flags(s, packet_tcp_flag_to_string, &flags,
2693                     TCP_FLAGS(OVS_BE16_MAX), mask ? &fmask : NULL);
2694     if (n >= 0) {
2695         *key = htons(flags);
2696         if (mask) {
2697             *mask = htons(fmask);
2698         }
2699         return n;
2700     }
2701     return 0;
2702 }
2703
2704 static int
2705 scan_frag(const char *s, uint8_t *key, uint8_t *mask)
2706 {
2707     int n;
2708     char frag[8];
2709     enum ovs_frag_type frag_type;
2710
2711     if (ovs_scan(s, "%7[a-z]%n", frag, &n)
2712         && ovs_frag_type_from_string(frag, &frag_type)) {
2713         int len = n;
2714
2715         *key = frag_type;
2716         if (mask) {
2717             *mask = UINT8_MAX;
2718         }
2719         return len;
2720     }
2721     return 0;
2722 }
2723
2724 static int
2725 scan_port(const char *s, uint32_t *key, uint32_t *mask,
2726           const struct simap *port_names)
2727 {
2728     int n;
2729
2730     if (ovs_scan(s, "%"SCNi32"%n", key, &n)) {
2731         int len = n;
2732
2733         if (mask) {
2734             if (ovs_scan(s + len, "/%"SCNi32"%n", mask, &n)) {
2735                 len += n;
2736             } else {
2737                 *mask = UINT32_MAX;
2738             }
2739         }
2740         return len;
2741     } else if (port_names) {
2742         const struct simap_node *node;
2743         int len;
2744
2745         len = strcspn(s, ")");
2746         node = simap_find_len(port_names, s, len);
2747         if (node) {
2748             *key = node->data;
2749
2750             if (mask) {
2751                 *mask = UINT32_MAX;
2752             }
2753             return len;
2754         }
2755     }
2756     return 0;
2757 }
2758
2759 /* Helper for vlan parsing. */
2760 struct ovs_key_vlan__ {
2761     ovs_be16 tci;
2762 };
2763
2764 static bool
2765 set_be16_bf(ovs_be16 *bf, uint8_t bits, uint8_t offset, uint16_t value)
2766 {
2767     const uint16_t mask = ((1U << bits) - 1) << offset;
2768
2769     if (value >> bits) {
2770         return false;
2771     }
2772
2773     *bf = htons((ntohs(*bf) & ~mask) | (value << offset));
2774     return true;
2775 }
2776
2777 static int
2778 scan_be16_bf(const char *s, ovs_be16 *key, ovs_be16 *mask, uint8_t bits,
2779              uint8_t offset)
2780 {
2781     uint16_t key_, mask_;
2782     int n;
2783
2784     if (ovs_scan(s, "%"SCNi16"%n", &key_, &n)) {
2785         int len = n;
2786
2787         if (set_be16_bf(key, bits, offset, key_)) {
2788             if (mask) {
2789                 if (ovs_scan(s + len, "/%"SCNi16"%n", &mask_, &n)) {
2790                     len += n;
2791
2792                     if (!set_be16_bf(mask, bits, offset, mask_)) {
2793                         return 0;
2794                     }
2795                 } else {
2796                     *mask |= htons(((1U << bits) - 1) << offset);
2797                 }
2798             }
2799             return len;
2800         }
2801     }
2802     return 0;
2803 }
2804
2805 static int
2806 scan_vid(const char *s, ovs_be16 *key, ovs_be16 *mask)
2807 {
2808     return scan_be16_bf(s, key, mask, 12, VLAN_VID_SHIFT);
2809 }
2810
2811 static int
2812 scan_pcp(const char *s, ovs_be16 *key, ovs_be16 *mask)
2813 {
2814     return scan_be16_bf(s, key, mask, 3, VLAN_PCP_SHIFT);
2815 }
2816
2817 static int
2818 scan_cfi(const char *s, ovs_be16 *key, ovs_be16 *mask)
2819 {
2820     return scan_be16_bf(s, key, mask, 1, VLAN_CFI_SHIFT);
2821 }
2822
2823 /* For MPLS. */
2824 static bool
2825 set_be32_bf(ovs_be32 *bf, uint8_t bits, uint8_t offset, uint32_t value)
2826 {
2827     const uint32_t mask = ((1U << bits) - 1) << offset;
2828
2829     if (value >> bits) {
2830         return false;
2831     }
2832
2833     *bf = htonl((ntohl(*bf) & ~mask) | (value << offset));
2834     return true;
2835 }
2836
2837 static int
2838 scan_be32_bf(const char *s, ovs_be32 *key, ovs_be32 *mask, uint8_t bits,
2839              uint8_t offset)
2840 {
2841     uint32_t key_, mask_;
2842     int n;
2843
2844     if (ovs_scan(s, "%"SCNi32"%n", &key_, &n)) {
2845         int len = n;
2846
2847         if (set_be32_bf(key, bits, offset, key_)) {
2848             if (mask) {
2849                 if (ovs_scan(s + len, "/%"SCNi32"%n", &mask_, &n)) {
2850                     len += n;
2851
2852                     if (!set_be32_bf(mask, bits, offset, mask_)) {
2853                         return 0;
2854                     }
2855                 } else {
2856                     *mask |= htonl(((1U << bits) - 1) << offset);
2857                 }
2858             }
2859             return len;
2860         }
2861     }
2862     return 0;
2863 }
2864
2865 static int
2866 scan_mpls_label(const char *s, ovs_be32 *key, ovs_be32 *mask)
2867 {
2868     return scan_be32_bf(s, key, mask, 20, MPLS_LABEL_SHIFT);
2869 }
2870
2871 static int
2872 scan_mpls_tc(const char *s, ovs_be32 *key, ovs_be32 *mask)
2873 {
2874     return scan_be32_bf(s, key, mask, 3, MPLS_TC_SHIFT);
2875 }
2876
2877 static int
2878 scan_mpls_ttl(const char *s, ovs_be32 *key, ovs_be32 *mask)
2879 {
2880     return scan_be32_bf(s, key, mask, 8, MPLS_TTL_SHIFT);
2881 }
2882
2883 static int
2884 scan_mpls_bos(const char *s, ovs_be32 *key, ovs_be32 *mask)
2885 {
2886     return scan_be32_bf(s, key, mask, 1, MPLS_BOS_SHIFT);
2887 }
2888
2889 static int
2890 scan_vxlan_gbp(const char *s, uint32_t *key, uint32_t *mask)
2891 {
2892     const char *s_base = s;
2893     ovs_be16 id = 0, id_mask = 0;
2894     uint8_t flags = 0, flags_mask = 0;
2895
2896     if (!strncmp(s, "id=", 3)) {
2897         s += 3;
2898         s += scan_be16(s, &id, mask ? &id_mask : NULL);
2899     }
2900
2901     if (s[0] == ',') {
2902         s++;
2903     }
2904     if (!strncmp(s, "flags=", 6)) {
2905         s += 6;
2906         s += scan_u8(s, &flags, mask ? &flags_mask : NULL);
2907     }
2908
2909     if (!strncmp(s, "))", 2)) {
2910         s += 2;
2911
2912         *key = (flags << 16) | ntohs(id);
2913         if (mask) {
2914             *mask = (flags_mask << 16) | ntohs(id_mask);
2915         }
2916
2917         return s - s_base;
2918     }
2919
2920     return 0;
2921 }
2922
2923 struct geneve_scan {
2924     struct geneve_opt d[63];
2925     int len;
2926 };
2927
2928 static int
2929 scan_geneve(const char *s, struct geneve_scan *key, struct geneve_scan *mask)
2930 {
2931     const char *s_base = s;
2932     struct geneve_opt *opt = key->d;
2933     struct geneve_opt *opt_mask = mask ? mask->d : NULL;
2934     int len_remain = sizeof key->d;
2935
2936     while (s[0] == '{' && len_remain >= sizeof *opt) {
2937         int data_len = 0;
2938
2939         s++;
2940         len_remain -= sizeof *opt;
2941
2942         if (!strncmp(s, "class=", 6)) {
2943             s += 6;
2944             s += scan_be16(s, &opt->opt_class,
2945                            mask ? &opt_mask->opt_class : NULL);
2946         } else if (mask) {
2947             memset(&opt_mask->opt_class, 0, sizeof opt_mask->opt_class);
2948         }
2949
2950         if (s[0] == ',') {
2951             s++;
2952         }
2953         if (!strncmp(s, "type=", 5)) {
2954             s += 5;
2955             s += scan_u8(s, &opt->type, mask ? &opt_mask->type : NULL);
2956         } else if (mask) {
2957             memset(&opt_mask->type, 0, sizeof opt_mask->type);
2958         }
2959
2960         if (s[0] == ',') {
2961             s++;
2962         }
2963         if (!strncmp(s, "len=", 4)) {
2964             uint8_t opt_len, opt_len_mask;
2965             s += 4;
2966             s += scan_u8(s, &opt_len, mask ? &opt_len_mask : NULL);
2967
2968             if (opt_len > 124 || opt_len % 4 || opt_len > len_remain) {
2969                 return 0;
2970             }
2971             opt->length = opt_len / 4;
2972             if (mask) {
2973                 opt_mask->length = opt_len_mask;
2974             }
2975             data_len = opt_len;
2976         } else if (mask) {
2977             memset(&opt_mask->type, 0, sizeof opt_mask->type);
2978         }
2979
2980         if (s[0] == ',') {
2981             s++;
2982         }
2983         if (parse_int_string(s, (uint8_t *)(opt + 1), data_len, (char **)&s)) {
2984             return 0;
2985         }
2986
2987         if (mask) {
2988             if (s[0] == '/') {
2989                 s++;
2990                 if (parse_int_string(s, (uint8_t *)(opt_mask + 1),
2991                                      data_len, (char **)&s)) {
2992                     return 0;
2993                 }
2994             }
2995             opt_mask->r1 = 0;
2996             opt_mask->r2 = 0;
2997             opt_mask->r3 = 0;
2998         }
2999
3000         if (s[0] == '}') {
3001             s++;
3002             opt += 1 + data_len / 4;
3003             if (mask) {
3004                 opt_mask += 1 + data_len / 4;
3005             }
3006             len_remain -= data_len;
3007         }
3008     }
3009
3010     if (s[0] == ')') {
3011         int len = sizeof key->d - len_remain;
3012
3013         s++;
3014         key->len = len;
3015         if (mask) {
3016             mask->len = len;
3017         }
3018         return s - s_base;
3019     }
3020
3021     return 0;
3022 }
3023
3024 static void
3025 tun_flags_to_attr(struct ofpbuf *a, const void *data_)
3026 {
3027     const uint16_t *flags = data_;
3028
3029     if (*flags & FLOW_TNL_F_DONT_FRAGMENT) {
3030         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT);
3031     }
3032     if (*flags & FLOW_TNL_F_CSUM) {
3033         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_CSUM);
3034     }
3035     if (*flags & FLOW_TNL_F_OAM) {
3036         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_OAM);
3037     }
3038 }
3039
3040 static void
3041 vxlan_gbp_to_attr(struct ofpbuf *a, const void *data_)
3042 {
3043     const uint32_t *gbp = data_;
3044
3045     if (*gbp) {
3046         size_t vxlan_opts_ofs;
3047
3048         vxlan_opts_ofs = nl_msg_start_nested(a, OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS);
3049         nl_msg_put_u32(a, OVS_VXLAN_EXT_GBP, *gbp);
3050         nl_msg_end_nested(a, vxlan_opts_ofs);
3051     }
3052 }
3053
3054 static void
3055 geneve_to_attr(struct ofpbuf *a, const void *data_)
3056 {
3057     const struct geneve_scan *geneve = data_;
3058
3059     nl_msg_put_unspec(a, OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS, geneve->d,
3060                       geneve->len);
3061 }
3062
3063 #define SCAN_PUT_ATTR(BUF, ATTR, DATA, FUNC)                      \
3064     {                                                             \
3065         unsigned long call_fn = (unsigned long)FUNC;              \
3066         if (call_fn) {                                            \
3067             typedef void (*fn)(struct ofpbuf *, const void *);    \
3068             fn func = FUNC;                                       \
3069             func(BUF, &(DATA));                                   \
3070         } else {                                                  \
3071             nl_msg_put_unspec(BUF, ATTR, &(DATA), sizeof (DATA)); \
3072         }                                                         \
3073     }
3074
3075 #define SCAN_IF(NAME)                           \
3076     if (strncmp(s, NAME, strlen(NAME)) == 0) {  \
3077         const char *start = s;                  \
3078         int len;                                \
3079                                                 \
3080         s += strlen(NAME)
3081
3082 /* Usually no special initialization is needed. */
3083 #define SCAN_BEGIN(NAME, TYPE)                  \
3084     SCAN_IF(NAME);                              \
3085         TYPE skey, smask;                       \
3086         memset(&skey, 0, sizeof skey);          \
3087         memset(&smask, 0, sizeof smask);        \
3088         do {                                    \
3089             len = 0;
3090
3091 /* Init as fully-masked as mask will not be scanned. */
3092 #define SCAN_BEGIN_FULLY_MASKED(NAME, TYPE)     \
3093     SCAN_IF(NAME);                              \
3094         TYPE skey, smask;                       \
3095         memset(&skey, 0, sizeof skey);          \
3096         memset(&smask, 0xff, sizeof smask);     \
3097         do {                                    \
3098             len = 0;
3099
3100 /* VLAN needs special initialization. */
3101 #define SCAN_BEGIN_INIT(NAME, TYPE, KEY_INIT, MASK_INIT)  \
3102     SCAN_IF(NAME);                                        \
3103         TYPE skey = KEY_INIT;                       \
3104         TYPE smask = MASK_INIT;                     \
3105         do {                                        \
3106             len = 0;
3107
3108 /* Scan unnamed entry as 'TYPE' */
3109 #define SCAN_TYPE(TYPE, KEY, MASK)              \
3110     len = scan_##TYPE(s, KEY, MASK);            \
3111     if (len == 0) {                             \
3112         return -EINVAL;                         \
3113     }                                           \
3114     s += len
3115
3116 /* Scan named ('NAME') entry 'FIELD' as 'TYPE'. */
3117 #define SCAN_FIELD(NAME, TYPE, FIELD)                                   \
3118     if (strncmp(s, NAME, strlen(NAME)) == 0) {                          \
3119         s += strlen(NAME);                                              \
3120         SCAN_TYPE(TYPE, &skey.FIELD, mask ? &smask.FIELD : NULL);       \
3121         continue;                                                       \
3122     }
3123
3124 #define SCAN_FINISH()                           \
3125         } while (*s++ == ',' && len != 0);      \
3126         if (s[-1] != ')') {                     \
3127             return -EINVAL;                     \
3128         }
3129
3130 #define SCAN_FINISH_SINGLE()                    \
3131         } while (false);                        \
3132         if (*s++ != ')') {                      \
3133             return -EINVAL;                     \
3134         }
3135
3136 /* Beginning of nested attribute. */
3137 #define SCAN_BEGIN_NESTED(NAME, ATTR)                      \
3138     SCAN_IF(NAME);                                         \
3139         size_t key_offset, mask_offset;                    \
3140         key_offset = nl_msg_start_nested(key, ATTR);       \
3141         if (mask) {                                        \
3142             mask_offset = nl_msg_start_nested(mask, ATTR); \
3143         }                                                  \
3144         do {                                               \
3145             len = 0;
3146
3147 #define SCAN_END_NESTED()                               \
3148         SCAN_FINISH();                                  \
3149         nl_msg_end_nested(key, key_offset);             \
3150         if (mask) {                                     \
3151             nl_msg_end_nested(mask, mask_offset);       \
3152         }                                               \
3153         return s - start;                               \
3154     }
3155
3156 #define SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, ATTR, FUNC)  \
3157     if (strncmp(s, NAME, strlen(NAME)) == 0) {                \
3158         TYPE skey, smask;                                     \
3159         memset(&skey, 0, sizeof skey);                        \
3160         memset(&smask, 0xff, sizeof smask);                   \
3161         s += strlen(NAME);                                    \
3162         SCAN_TYPE(SCAN_AS, &skey, &smask);                    \
3163         SCAN_PUT(ATTR, FUNC);                                 \
3164         continue;                                             \
3165     }
3166
3167 #define SCAN_FIELD_NESTED(NAME, TYPE, SCAN_AS, ATTR)  \
3168         SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, ATTR, NULL)
3169
3170 #define SCAN_FIELD_NESTED_FUNC(NAME, TYPE, SCAN_AS, FUNC)  \
3171         SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, 0, FUNC)
3172
3173 #define SCAN_PUT(ATTR, FUNC)                            \
3174         if (!mask || !is_all_zeros(&smask, sizeof smask)) { \
3175             SCAN_PUT_ATTR(key, ATTR, skey, FUNC);       \
3176             if (mask) {                                 \
3177                 SCAN_PUT_ATTR(mask, ATTR, smask, FUNC); \
3178             }                                           \
3179         }
3180
3181 #define SCAN_END(ATTR)                                  \
3182         SCAN_FINISH();                                  \
3183         SCAN_PUT(ATTR, NULL);                           \
3184         return s - start;                               \
3185     }
3186
3187 #define SCAN_END_SINGLE(ATTR)                           \
3188         SCAN_FINISH_SINGLE();                           \
3189         SCAN_PUT(ATTR, NULL);                           \
3190         return s - start;                               \
3191     }
3192
3193 #define SCAN_SINGLE(NAME, TYPE, SCAN_AS, ATTR)       \
3194     SCAN_BEGIN(NAME, TYPE) {                         \
3195         SCAN_TYPE(SCAN_AS, &skey, &smask);           \
3196     } SCAN_END_SINGLE(ATTR)
3197
3198 #define SCAN_SINGLE_FULLY_MASKED(NAME, TYPE, SCAN_AS, ATTR) \
3199     SCAN_BEGIN_FULLY_MASKED(NAME, TYPE) {                   \
3200         SCAN_TYPE(SCAN_AS, &skey, NULL);                    \
3201     } SCAN_END_SINGLE(ATTR)
3202
3203 /* scan_port needs one extra argument. */
3204 #define SCAN_SINGLE_PORT(NAME, TYPE, ATTR)  \
3205     SCAN_BEGIN(NAME, TYPE) {                            \
3206         len = scan_port(s, &skey, &smask, port_names);  \
3207         if (len == 0) {                                 \
3208             return -EINVAL;                             \
3209         }                                               \
3210         s += len;                                       \
3211     } SCAN_END_SINGLE(ATTR)
3212
3213 static int
3214 parse_odp_key_mask_attr(const char *s, const struct simap *port_names,
3215                         struct ofpbuf *key, struct ofpbuf *mask)
3216 {
3217     if (!strncmp(s, "ufid:", 5)) {
3218         const char *start = s;
3219
3220         /* Skip UFID. */
3221         s += 5;
3222         s += strspn(s, hex_chars);
3223         s += strspn(s, delimiters);
3224
3225         return s - start;
3226     }
3227
3228     SCAN_SINGLE("skb_priority(", uint32_t, u32, OVS_KEY_ATTR_PRIORITY);
3229     SCAN_SINGLE("skb_mark(", uint32_t, u32, OVS_KEY_ATTR_SKB_MARK);
3230     SCAN_SINGLE_FULLY_MASKED("recirc_id(", uint32_t, u32,
3231                              OVS_KEY_ATTR_RECIRC_ID);
3232     SCAN_SINGLE("dp_hash(", uint32_t, u32, OVS_KEY_ATTR_DP_HASH);
3233
3234     SCAN_BEGIN_NESTED("tunnel(", OVS_KEY_ATTR_TUNNEL) {
3235         SCAN_FIELD_NESTED("tun_id=", ovs_be64, be64, OVS_TUNNEL_KEY_ATTR_ID);
3236         SCAN_FIELD_NESTED("src=", ovs_be32, ipv4, OVS_TUNNEL_KEY_ATTR_IPV4_SRC);
3237         SCAN_FIELD_NESTED("dst=", ovs_be32, ipv4, OVS_TUNNEL_KEY_ATTR_IPV4_DST);
3238         SCAN_FIELD_NESTED("tos=", uint8_t, u8, OVS_TUNNEL_KEY_ATTR_TOS);
3239         SCAN_FIELD_NESTED("ttl=", uint8_t, u8, OVS_TUNNEL_KEY_ATTR_TTL);
3240         SCAN_FIELD_NESTED("tp_src=", ovs_be16, be16, OVS_TUNNEL_KEY_ATTR_TP_SRC);
3241         SCAN_FIELD_NESTED("tp_dst=", ovs_be16, be16, OVS_TUNNEL_KEY_ATTR_TP_DST);
3242         SCAN_FIELD_NESTED_FUNC("vxlan(gbp(", uint32_t, vxlan_gbp, vxlan_gbp_to_attr);
3243         SCAN_FIELD_NESTED_FUNC("geneve(", struct geneve_scan, geneve,
3244                                geneve_to_attr);
3245         SCAN_FIELD_NESTED_FUNC("flags(", uint16_t, tun_flags, tun_flags_to_attr);
3246     } SCAN_END_NESTED();
3247
3248     SCAN_SINGLE_PORT("in_port(", uint32_t, OVS_KEY_ATTR_IN_PORT);
3249
3250     SCAN_BEGIN("eth(", struct ovs_key_ethernet) {
3251         SCAN_FIELD("src=", eth, eth_src);
3252         SCAN_FIELD("dst=", eth, eth_dst);
3253     } SCAN_END(OVS_KEY_ATTR_ETHERNET);
3254
3255     SCAN_BEGIN_INIT("vlan(", struct ovs_key_vlan__,
3256                     { htons(VLAN_CFI) }, { htons(VLAN_CFI) }) {
3257         SCAN_FIELD("vid=", vid, tci);
3258         SCAN_FIELD("pcp=", pcp, tci);
3259         SCAN_FIELD("cfi=", cfi, tci);
3260     } SCAN_END(OVS_KEY_ATTR_VLAN);
3261
3262     SCAN_SINGLE("eth_type(", ovs_be16, be16, OVS_KEY_ATTR_ETHERTYPE);
3263
3264     SCAN_BEGIN("mpls(", struct ovs_key_mpls) {
3265         SCAN_FIELD("label=", mpls_label, mpls_lse);
3266         SCAN_FIELD("tc=", mpls_tc, mpls_lse);
3267         SCAN_FIELD("ttl=", mpls_ttl, mpls_lse);
3268         SCAN_FIELD("bos=", mpls_bos, mpls_lse);
3269     } SCAN_END(OVS_KEY_ATTR_MPLS);
3270
3271     SCAN_BEGIN("ipv4(", struct ovs_key_ipv4) {
3272         SCAN_FIELD("src=", ipv4, ipv4_src);
3273         SCAN_FIELD("dst=", ipv4, ipv4_dst);
3274         SCAN_FIELD("proto=", u8, ipv4_proto);
3275         SCAN_FIELD("tos=", u8, ipv4_tos);
3276         SCAN_FIELD("ttl=", u8, ipv4_ttl);
3277         SCAN_FIELD("frag=", frag, ipv4_frag);
3278     } SCAN_END(OVS_KEY_ATTR_IPV4);
3279
3280     SCAN_BEGIN("ipv6(", struct ovs_key_ipv6) {
3281         SCAN_FIELD("src=", ipv6, ipv6_src);
3282         SCAN_FIELD("dst=", ipv6, ipv6_dst);
3283         SCAN_FIELD("label=", ipv6_label, ipv6_label);
3284         SCAN_FIELD("proto=", u8, ipv6_proto);
3285         SCAN_FIELD("tclass=", u8, ipv6_tclass);
3286         SCAN_FIELD("hlimit=", u8, ipv6_hlimit);
3287         SCAN_FIELD("frag=", frag, ipv6_frag);
3288     } SCAN_END(OVS_KEY_ATTR_IPV6);
3289
3290     SCAN_BEGIN("tcp(", struct ovs_key_tcp) {
3291         SCAN_FIELD("src=", be16, tcp_src);
3292         SCAN_FIELD("dst=", be16, tcp_dst);
3293     } SCAN_END(OVS_KEY_ATTR_TCP);
3294
3295     SCAN_SINGLE("tcp_flags(", ovs_be16, tcp_flags, OVS_KEY_ATTR_TCP_FLAGS);
3296
3297     SCAN_BEGIN("udp(", struct ovs_key_udp) {
3298         SCAN_FIELD("src=", be16, udp_src);
3299         SCAN_FIELD("dst=", be16, udp_dst);
3300     } SCAN_END(OVS_KEY_ATTR_UDP);
3301
3302     SCAN_BEGIN("sctp(", struct ovs_key_sctp) {
3303         SCAN_FIELD("src=", be16, sctp_src);
3304         SCAN_FIELD("dst=", be16, sctp_dst);
3305     } SCAN_END(OVS_KEY_ATTR_SCTP);
3306
3307     SCAN_BEGIN("icmp(", struct ovs_key_icmp) {
3308         SCAN_FIELD("type=", u8, icmp_type);
3309         SCAN_FIELD("code=", u8, icmp_code);
3310     } SCAN_END(OVS_KEY_ATTR_ICMP);
3311
3312     SCAN_BEGIN("icmpv6(", struct ovs_key_icmpv6) {
3313         SCAN_FIELD("type=", u8, icmpv6_type);
3314         SCAN_FIELD("code=", u8, icmpv6_code);
3315     } SCAN_END(OVS_KEY_ATTR_ICMPV6);
3316
3317     SCAN_BEGIN("arp(", struct ovs_key_arp) {
3318         SCAN_FIELD("sip=", ipv4, arp_sip);
3319         SCAN_FIELD("tip=", ipv4, arp_tip);
3320         SCAN_FIELD("op=", be16, arp_op);
3321         SCAN_FIELD("sha=", eth, arp_sha);
3322         SCAN_FIELD("tha=", eth, arp_tha);
3323     } SCAN_END(OVS_KEY_ATTR_ARP);
3324
3325     SCAN_BEGIN("nd(", struct ovs_key_nd) {
3326         SCAN_FIELD("target=", ipv6, nd_target);
3327         SCAN_FIELD("sll=", eth, nd_sll);
3328         SCAN_FIELD("tll=", eth, nd_tll);
3329     } SCAN_END(OVS_KEY_ATTR_ND);
3330
3331     /* Encap open-coded. */
3332     if (!strncmp(s, "encap(", 6)) {
3333         const char *start = s;
3334         size_t encap, encap_mask = 0;
3335
3336         encap = nl_msg_start_nested(key, OVS_KEY_ATTR_ENCAP);
3337         if (mask) {
3338             encap_mask = nl_msg_start_nested(mask, OVS_KEY_ATTR_ENCAP);
3339         }
3340
3341         s += 6;
3342         for (;;) {
3343             int retval;
3344
3345             s += strspn(s, delimiters);
3346             if (!*s) {
3347                 return -EINVAL;
3348             } else if (*s == ')') {
3349                 break;
3350             }
3351
3352             retval = parse_odp_key_mask_attr(s, port_names, key, mask);
3353             if (retval < 0) {
3354                 return retval;
3355             }
3356             s += retval;
3357         }
3358         s++;
3359
3360         nl_msg_end_nested(key, encap);
3361         if (mask) {
3362             nl_msg_end_nested(mask, encap_mask);
3363         }
3364
3365         return s - start;
3366     }
3367
3368     return -EINVAL;
3369 }
3370
3371 /* Parses the string representation of a datapath flow key, in the
3372  * format output by odp_flow_key_format().  Returns 0 if successful,
3373  * otherwise a positive errno value.  On success, the flow key is
3374  * appended to 'key' as a series of Netlink attributes.  On failure, no
3375  * data is appended to 'key'.  Either way, 'key''s data might be
3376  * reallocated.
3377  *
3378  * If 'port_names' is nonnull, it points to an simap that maps from a port name
3379  * to a port number.  (Port names may be used instead of port numbers in
3380  * in_port.)
3381  *
3382  * On success, the attributes appended to 'key' are individually syntactically
3383  * valid, but they may not be valid as a sequence.  'key' might, for example,
3384  * have duplicated keys.  odp_flow_key_to_flow() will detect those errors. */
3385 int
3386 odp_flow_from_string(const char *s, const struct simap *port_names,
3387                      struct ofpbuf *key, struct ofpbuf *mask)
3388 {
3389     const size_t old_size = key->size;
3390     for (;;) {
3391         int retval;
3392
3393         s += strspn(s, delimiters);
3394         if (!*s) {
3395             return 0;
3396         }
3397
3398         retval = parse_odp_key_mask_attr(s, port_names, key, mask);
3399         if (retval < 0) {
3400             key->size = old_size;
3401             return -retval;
3402         }
3403         s += retval;
3404     }
3405
3406     return 0;
3407 }
3408
3409 static uint8_t
3410 ovs_to_odp_frag(uint8_t nw_frag, bool is_mask)
3411 {
3412     if (is_mask) {
3413         /* Netlink interface 'enum ovs_frag_type' is an 8-bit enumeration type,
3414          * not a set of flags or bitfields. Hence, if the struct flow nw_frag
3415          * mask, which is a set of bits, has the FLOW_NW_FRAG_ANY as zero, we
3416          * must use a zero mask for the netlink frag field, and all ones mask
3417          * otherwise. */
3418         return (nw_frag & FLOW_NW_FRAG_ANY) ? UINT8_MAX : 0;
3419     }
3420     return !(nw_frag & FLOW_NW_FRAG_ANY) ? OVS_FRAG_TYPE_NONE
3421         : nw_frag & FLOW_NW_FRAG_LATER ? OVS_FRAG_TYPE_LATER
3422         : OVS_FRAG_TYPE_FIRST;
3423 }
3424
3425 static void get_ethernet_key(const struct flow *, struct ovs_key_ethernet *);
3426 static void put_ethernet_key(const struct ovs_key_ethernet *, struct flow *);
3427 static void get_ipv4_key(const struct flow *, struct ovs_key_ipv4 *,
3428                          bool is_mask);
3429 static void put_ipv4_key(const struct ovs_key_ipv4 *, struct flow *,
3430                          bool is_mask);
3431 static void get_ipv6_key(const struct flow *, struct ovs_key_ipv6 *,
3432                          bool is_mask);
3433 static void put_ipv6_key(const struct ovs_key_ipv6 *, struct flow *,
3434                          bool is_mask);
3435 static void get_arp_key(const struct flow *, struct ovs_key_arp *);
3436 static void put_arp_key(const struct ovs_key_arp *, struct flow *);
3437 static void get_nd_key(const struct flow *, struct ovs_key_nd *);
3438 static void put_nd_key(const struct ovs_key_nd *, struct flow *);
3439
3440 /* These share the same layout. */
3441 union ovs_key_tp {
3442     struct ovs_key_tcp tcp;
3443     struct ovs_key_udp udp;
3444     struct ovs_key_sctp sctp;
3445 };
3446
3447 static void get_tp_key(const struct flow *, union ovs_key_tp *);
3448 static void put_tp_key(const union ovs_key_tp *, struct flow *);
3449
3450 static void
3451 odp_flow_key_from_flow__(struct ofpbuf *buf, const struct flow *flow,
3452                          const struct flow *mask, odp_port_t odp_in_port,
3453                          size_t max_mpls_depth, bool recirc, bool export_mask)
3454 {
3455     struct ovs_key_ethernet *eth_key;
3456     size_t encap;
3457     const struct flow *data = export_mask ? mask : flow;
3458
3459     nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, data->skb_priority);
3460
3461     if (flow->tunnel.ip_dst || export_mask) {
3462         tun_key_to_attr(buf, &data->tunnel);
3463     }
3464
3465     nl_msg_put_u32(buf, OVS_KEY_ATTR_SKB_MARK, data->pkt_mark);
3466
3467     if (recirc) {
3468         nl_msg_put_u32(buf, OVS_KEY_ATTR_RECIRC_ID, data->recirc_id);
3469         nl_msg_put_u32(buf, OVS_KEY_ATTR_DP_HASH, data->dp_hash);
3470     }
3471
3472     /* Add an ingress port attribute if this is a mask or 'odp_in_port'
3473      * is not the magical value "ODPP_NONE". */
3474     if (export_mask || odp_in_port != ODPP_NONE) {
3475         nl_msg_put_odp_port(buf, OVS_KEY_ATTR_IN_PORT, odp_in_port);
3476     }
3477
3478     eth_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ETHERNET,
3479                                        sizeof *eth_key);
3480     get_ethernet_key(data, eth_key);
3481
3482     if (flow->vlan_tci != htons(0) || flow->dl_type == htons(ETH_TYPE_VLAN)) {
3483         if (export_mask) {
3484             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, OVS_BE16_MAX);
3485         } else {
3486             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, htons(ETH_TYPE_VLAN));
3487         }
3488         nl_msg_put_be16(buf, OVS_KEY_ATTR_VLAN, data->vlan_tci);
3489         encap = nl_msg_start_nested(buf, OVS_KEY_ATTR_ENCAP);
3490         if (flow->vlan_tci == htons(0)) {
3491             goto unencap;
3492         }
3493     } else {
3494         encap = 0;
3495     }
3496
3497     if (ntohs(flow->dl_type) < ETH_TYPE_MIN) {
3498         /* For backwards compatibility with kernels that don't support
3499          * wildcarding, the following convention is used to encode the
3500          * OVS_KEY_ATTR_ETHERTYPE for key and mask:
3501          *
3502          *   key      mask    matches
3503          * -------- --------  -------
3504          *  >0x5ff   0xffff   Specified Ethernet II Ethertype.
3505          *  >0x5ff      0     Any Ethernet II or non-Ethernet II frame.
3506          *  <none>   0xffff   Any non-Ethernet II frame (except valid
3507          *                    802.3 SNAP packet with valid eth_type).
3508          */
3509         if (export_mask) {
3510             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, OVS_BE16_MAX);
3511         }
3512         goto unencap;
3513     }
3514
3515     nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, data->dl_type);
3516
3517     if (flow->dl_type == htons(ETH_TYPE_IP)) {
3518         struct ovs_key_ipv4 *ipv4_key;
3519
3520         ipv4_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV4,
3521                                             sizeof *ipv4_key);
3522         get_ipv4_key(data, ipv4_key, export_mask);
3523     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
3524         struct ovs_key_ipv6 *ipv6_key;
3525
3526         ipv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV6,
3527                                             sizeof *ipv6_key);
3528         get_ipv6_key(data, ipv6_key, export_mask);
3529     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
3530                flow->dl_type == htons(ETH_TYPE_RARP)) {
3531         struct ovs_key_arp *arp_key;
3532
3533         arp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ARP,
3534                                            sizeof *arp_key);
3535         get_arp_key(data, arp_key);
3536     } else if (eth_type_mpls(flow->dl_type)) {
3537         struct ovs_key_mpls *mpls_key;
3538         int i, n;
3539
3540         n = flow_count_mpls_labels(flow, NULL);
3541         n = MIN(n, max_mpls_depth);
3542         mpls_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_MPLS,
3543                                             n * sizeof *mpls_key);
3544         for (i = 0; i < n; i++) {
3545             mpls_key[i].mpls_lse = data->mpls_lse[i];
3546         }
3547     }
3548
3549     if (is_ip_any(flow) && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3550         if (flow->nw_proto == IPPROTO_TCP) {
3551             union ovs_key_tp *tcp_key;
3552
3553             tcp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_TCP,
3554                                                sizeof *tcp_key);
3555             get_tp_key(data, tcp_key);
3556             if (data->tcp_flags) {
3557                 nl_msg_put_be16(buf, OVS_KEY_ATTR_TCP_FLAGS, data->tcp_flags);
3558             }
3559         } else if (flow->nw_proto == IPPROTO_UDP) {
3560             union ovs_key_tp *udp_key;
3561
3562             udp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_UDP,
3563                                                sizeof *udp_key);
3564             get_tp_key(data, udp_key);
3565         } else if (flow->nw_proto == IPPROTO_SCTP) {
3566             union ovs_key_tp *sctp_key;
3567
3568             sctp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_SCTP,
3569                                                sizeof *sctp_key);
3570             get_tp_key(data, sctp_key);
3571         } else if (flow->dl_type == htons(ETH_TYPE_IP)
3572                 && flow->nw_proto == IPPROTO_ICMP) {
3573             struct ovs_key_icmp *icmp_key;
3574
3575             icmp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMP,
3576                                                 sizeof *icmp_key);
3577             icmp_key->icmp_type = ntohs(data->tp_src);
3578             icmp_key->icmp_code = ntohs(data->tp_dst);
3579         } else if (flow->dl_type == htons(ETH_TYPE_IPV6)
3580                 && flow->nw_proto == IPPROTO_ICMPV6) {
3581             struct ovs_key_icmpv6 *icmpv6_key;
3582
3583             icmpv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMPV6,
3584                                                   sizeof *icmpv6_key);
3585             icmpv6_key->icmpv6_type = ntohs(data->tp_src);
3586             icmpv6_key->icmpv6_code = ntohs(data->tp_dst);
3587
3588             if (flow->tp_dst == htons(0)
3589                 && (flow->tp_src == htons(ND_NEIGHBOR_SOLICIT)
3590                     || flow->tp_src == htons(ND_NEIGHBOR_ADVERT))
3591                 && (!export_mask || (data->tp_src == htons(0xffff)
3592                                      && data->tp_dst == htons(0xffff)))) {
3593
3594                 struct ovs_key_nd *nd_key;
3595
3596                 nd_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ND,
3597                                                     sizeof *nd_key);
3598                 memcpy(nd_key->nd_target, &data->nd_target,
3599                         sizeof nd_key->nd_target);
3600                 memcpy(nd_key->nd_sll, data->arp_sha, ETH_ADDR_LEN);
3601                 memcpy(nd_key->nd_tll, data->arp_tha, ETH_ADDR_LEN);
3602             }
3603         }
3604     }
3605
3606 unencap:
3607     if (encap) {
3608         nl_msg_end_nested(buf, encap);
3609     }
3610 }
3611
3612 /* Appends a representation of 'flow' as OVS_KEY_ATTR_* attributes to 'buf'.
3613  * 'flow->in_port' is ignored (since it is likely to be an OpenFlow port
3614  * number rather than a datapath port number).  Instead, if 'odp_in_port'
3615  * is anything other than ODPP_NONE, it is included in 'buf' as the input
3616  * port.
3617  *
3618  * 'buf' must have at least ODPUTIL_FLOW_KEY_BYTES bytes of space, or be
3619  * capable of being expanded to allow for that much space.
3620  *
3621  * 'recirc' indicates support for recirculation fields. If this is true, then
3622  * these fields will always be serialised. */
3623 void
3624 odp_flow_key_from_flow(struct ofpbuf *buf, const struct flow *flow,
3625                        const struct flow *mask, odp_port_t odp_in_port,
3626                        bool recirc)
3627 {
3628     odp_flow_key_from_flow__(buf, flow, mask, odp_in_port, SIZE_MAX, recirc,
3629                              false);
3630 }
3631
3632 /* Appends a representation of 'mask' as OVS_KEY_ATTR_* attributes to
3633  * 'buf'.  'flow' is used as a template to determine how to interpret
3634  * 'mask'.  For example, the 'dl_type' of 'mask' describes the mask, but
3635  * it doesn't indicate whether the other fields should be interpreted as
3636  * ARP, IPv4, IPv6, etc.
3637  *
3638  * 'buf' must have at least ODPUTIL_FLOW_KEY_BYTES bytes of space, or be
3639  * capable of being expanded to allow for that much space.
3640  *
3641  * 'recirc' indicates support for recirculation fields. If this is true, then
3642  * these fields will always be serialised. */
3643 void
3644 odp_flow_key_from_mask(struct ofpbuf *buf, const struct flow *mask,
3645                        const struct flow *flow, uint32_t odp_in_port_mask,
3646                        size_t max_mpls_depth, bool recirc)
3647 {
3648     odp_flow_key_from_flow__(buf, flow, mask, u32_to_odp(odp_in_port_mask),
3649                              max_mpls_depth, recirc, true);
3650 }
3651
3652 /* Generate ODP flow key from the given packet metadata */
3653 void
3654 odp_key_from_pkt_metadata(struct ofpbuf *buf, const struct pkt_metadata *md)
3655 {
3656     nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, md->skb_priority);
3657
3658     if (md->tunnel.ip_dst) {
3659         tun_key_to_attr(buf, &md->tunnel);
3660     }
3661
3662     nl_msg_put_u32(buf, OVS_KEY_ATTR_SKB_MARK, md->pkt_mark);
3663
3664     /* Add an ingress port attribute if 'odp_in_port' is not the magical
3665      * value "ODPP_NONE". */
3666     if (md->in_port.odp_port != ODPP_NONE) {
3667         nl_msg_put_odp_port(buf, OVS_KEY_ATTR_IN_PORT, md->in_port.odp_port);
3668     }
3669 }
3670
3671 /* Generate packet metadata from the given ODP flow key. */
3672 void
3673 odp_key_to_pkt_metadata(const struct nlattr *key, size_t key_len,
3674                         struct pkt_metadata *md)
3675 {
3676     const struct nlattr *nla;
3677     size_t left;
3678     uint32_t wanted_attrs = 1u << OVS_KEY_ATTR_PRIORITY |
3679         1u << OVS_KEY_ATTR_SKB_MARK | 1u << OVS_KEY_ATTR_TUNNEL |
3680         1u << OVS_KEY_ATTR_IN_PORT;
3681
3682     *md = PKT_METADATA_INITIALIZER(ODPP_NONE);
3683
3684     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
3685         uint16_t type = nl_attr_type(nla);
3686         size_t len = nl_attr_get_size(nla);
3687         int expected_len = odp_key_attr_len(ovs_flow_key_attr_lens,
3688                                             OVS_KEY_ATTR_MAX, type);
3689
3690         if (len != expected_len && expected_len >= 0) {
3691             continue;
3692         }
3693
3694         switch (type) {
3695         case OVS_KEY_ATTR_RECIRC_ID:
3696             md->recirc_id = nl_attr_get_u32(nla);
3697             wanted_attrs &= ~(1u << OVS_KEY_ATTR_RECIRC_ID);
3698             break;
3699         case OVS_KEY_ATTR_DP_HASH:
3700             md->dp_hash = nl_attr_get_u32(nla);
3701             wanted_attrs &= ~(1u << OVS_KEY_ATTR_DP_HASH);
3702             break;
3703         case OVS_KEY_ATTR_PRIORITY:
3704             md->skb_priority = nl_attr_get_u32(nla);
3705             wanted_attrs &= ~(1u << OVS_KEY_ATTR_PRIORITY);
3706             break;
3707         case OVS_KEY_ATTR_SKB_MARK:
3708             md->pkt_mark = nl_attr_get_u32(nla);
3709             wanted_attrs &= ~(1u << OVS_KEY_ATTR_SKB_MARK);
3710             break;
3711         case OVS_KEY_ATTR_TUNNEL: {
3712             enum odp_key_fitness res;
3713
3714             res = odp_tun_key_from_attr(nla, &md->tunnel);
3715             if (res == ODP_FIT_ERROR) {
3716                 memset(&md->tunnel, 0, sizeof md->tunnel);
3717             } else if (res == ODP_FIT_PERFECT) {
3718                 wanted_attrs &= ~(1u << OVS_KEY_ATTR_TUNNEL);
3719             }
3720             break;
3721         }
3722         case OVS_KEY_ATTR_IN_PORT:
3723             md->in_port.odp_port = nl_attr_get_odp_port(nla);
3724             wanted_attrs &= ~(1u << OVS_KEY_ATTR_IN_PORT);
3725             break;
3726         default:
3727             break;
3728         }
3729
3730         if (!wanted_attrs) {
3731             return; /* Have everything. */
3732         }
3733     }
3734 }
3735
3736 uint32_t
3737 odp_flow_key_hash(const struct nlattr *key, size_t key_len)
3738 {
3739     BUILD_ASSERT_DECL(!(NLA_ALIGNTO % sizeof(uint32_t)));
3740     return hash_words(ALIGNED_CAST(const uint32_t *, key),
3741                       key_len / sizeof(uint32_t), 0);
3742 }
3743
3744 static void
3745 log_odp_key_attributes(struct vlog_rate_limit *rl, const char *title,
3746                        uint64_t attrs, int out_of_range_attr,
3747                        const struct nlattr *key, size_t key_len)
3748 {
3749     struct ds s;
3750     int i;
3751
3752     if (VLOG_DROP_DBG(rl)) {
3753         return;
3754     }
3755
3756     ds_init(&s);
3757     for (i = 0; i < 64; i++) {
3758         if (attrs & (UINT64_C(1) << i)) {
3759             char namebuf[OVS_KEY_ATTR_BUFSIZE];
3760
3761             ds_put_format(&s, " %s",
3762                           ovs_key_attr_to_string(i, namebuf, sizeof namebuf));
3763         }
3764     }
3765     if (out_of_range_attr) {
3766         ds_put_format(&s, " %d (and possibly others)", out_of_range_attr);
3767     }
3768
3769     ds_put_cstr(&s, ": ");
3770     odp_flow_key_format(key, key_len, &s);
3771
3772     VLOG_DBG("%s:%s", title, ds_cstr(&s));
3773     ds_destroy(&s);
3774 }
3775
3776 static uint8_t
3777 odp_to_ovs_frag(uint8_t odp_frag, bool is_mask)
3778 {
3779     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3780
3781     if (is_mask) {
3782         return odp_frag ? FLOW_NW_FRAG_MASK : 0;
3783     }
3784
3785     if (odp_frag > OVS_FRAG_TYPE_LATER) {
3786         VLOG_ERR_RL(&rl, "invalid frag %"PRIu8" in flow key", odp_frag);
3787         return 0xff; /* Error. */
3788     }
3789
3790     return (odp_frag == OVS_FRAG_TYPE_NONE) ? 0
3791         : (odp_frag == OVS_FRAG_TYPE_FIRST) ? FLOW_NW_FRAG_ANY
3792         :  FLOW_NW_FRAG_ANY | FLOW_NW_FRAG_LATER;
3793 }
3794
3795 static bool
3796 parse_flow_nlattrs(const struct nlattr *key, size_t key_len,
3797                    const struct nlattr *attrs[], uint64_t *present_attrsp,
3798                    int *out_of_range_attrp)
3799 {
3800     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3801     const struct nlattr *nla;
3802     uint64_t present_attrs;
3803     size_t left;
3804
3805     BUILD_ASSERT(OVS_KEY_ATTR_MAX < CHAR_BIT * sizeof present_attrs);
3806     present_attrs = 0;
3807     *out_of_range_attrp = 0;
3808     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
3809         uint16_t type = nl_attr_type(nla);
3810         size_t len = nl_attr_get_size(nla);
3811         int expected_len = odp_key_attr_len(ovs_flow_key_attr_lens,
3812                                             OVS_KEY_ATTR_MAX, type);
3813
3814         if (len != expected_len && expected_len >= 0) {
3815             char namebuf[OVS_KEY_ATTR_BUFSIZE];
3816
3817             VLOG_ERR_RL(&rl, "attribute %s has length %"PRIuSIZE" but should have "
3818                         "length %d", ovs_key_attr_to_string(type, namebuf,
3819                                                             sizeof namebuf),
3820                         len, expected_len);
3821             return false;
3822         }
3823
3824         if (type > OVS_KEY_ATTR_MAX) {
3825             *out_of_range_attrp = type;
3826         } else {
3827             if (present_attrs & (UINT64_C(1) << type)) {
3828                 char namebuf[OVS_KEY_ATTR_BUFSIZE];
3829
3830                 VLOG_ERR_RL(&rl, "duplicate %s attribute in flow key",
3831                             ovs_key_attr_to_string(type,
3832                                                    namebuf, sizeof namebuf));
3833                 return false;
3834             }
3835
3836             present_attrs |= UINT64_C(1) << type;
3837             attrs[type] = nla;
3838         }
3839     }
3840     if (left) {
3841         VLOG_ERR_RL(&rl, "trailing garbage in flow key");
3842         return false;
3843     }
3844
3845     *present_attrsp = present_attrs;
3846     return true;
3847 }
3848
3849 static enum odp_key_fitness
3850 check_expectations(uint64_t present_attrs, int out_of_range_attr,
3851                    uint64_t expected_attrs,
3852                    const struct nlattr *key, size_t key_len)
3853 {
3854     uint64_t missing_attrs;
3855     uint64_t extra_attrs;
3856
3857     missing_attrs = expected_attrs & ~present_attrs;
3858     if (missing_attrs) {
3859         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3860         log_odp_key_attributes(&rl, "expected but not present",
3861                                missing_attrs, 0, key, key_len);
3862         return ODP_FIT_TOO_LITTLE;
3863     }
3864
3865     extra_attrs = present_attrs & ~expected_attrs;
3866     if (extra_attrs || out_of_range_attr) {
3867         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3868         log_odp_key_attributes(&rl, "present but not expected",
3869                                extra_attrs, out_of_range_attr, key, key_len);
3870         return ODP_FIT_TOO_MUCH;
3871     }
3872
3873     return ODP_FIT_PERFECT;
3874 }
3875
3876 static bool
3877 parse_ethertype(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
3878                 uint64_t present_attrs, uint64_t *expected_attrs,
3879                 struct flow *flow, const struct flow *src_flow)
3880 {
3881     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3882     bool is_mask = flow != src_flow;
3883
3884     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE)) {
3885         flow->dl_type = nl_attr_get_be16(attrs[OVS_KEY_ATTR_ETHERTYPE]);
3886         if (!is_mask && ntohs(flow->dl_type) < ETH_TYPE_MIN) {
3887             VLOG_ERR_RL(&rl, "invalid Ethertype %"PRIu16" in flow key",
3888                         ntohs(flow->dl_type));
3889             return false;
3890         }
3891         if (is_mask && ntohs(src_flow->dl_type) < ETH_TYPE_MIN &&
3892             flow->dl_type != htons(0xffff)) {
3893             return false;
3894         }
3895         *expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE;
3896     } else {
3897         if (!is_mask) {
3898             flow->dl_type = htons(FLOW_DL_TYPE_NONE);
3899         } else if (ntohs(src_flow->dl_type) < ETH_TYPE_MIN) {
3900             /* See comments in odp_flow_key_from_flow__(). */
3901             VLOG_ERR_RL(&rl, "mask expected for non-Ethernet II frame");
3902             return false;
3903         }
3904     }
3905     return true;
3906 }
3907
3908 static enum odp_key_fitness
3909 parse_l2_5_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
3910                   uint64_t present_attrs, int out_of_range_attr,
3911                   uint64_t expected_attrs, struct flow *flow,
3912                   const struct nlattr *key, size_t key_len,
3913                   const struct flow *src_flow)
3914 {
3915     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3916     bool is_mask = src_flow != flow;
3917     const void *check_start = NULL;
3918     size_t check_len = 0;
3919     enum ovs_key_attr expected_bit = 0xff;
3920
3921     if (eth_type_mpls(src_flow->dl_type)) {
3922         if (!is_mask || present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_MPLS)) {
3923             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_MPLS);
3924         }
3925         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_MPLS)) {
3926             size_t size = nl_attr_get_size(attrs[OVS_KEY_ATTR_MPLS]);
3927             const ovs_be32 *mpls_lse = nl_attr_get(attrs[OVS_KEY_ATTR_MPLS]);
3928             int n = size / sizeof(ovs_be32);
3929             int i;
3930
3931             if (!size || size % sizeof(ovs_be32)) {
3932                 return ODP_FIT_ERROR;
3933             }
3934             if (flow->mpls_lse[0] && flow->dl_type != htons(0xffff)) {
3935                 return ODP_FIT_ERROR;
3936             }
3937
3938             for (i = 0; i < n && i < FLOW_MAX_MPLS_LABELS; i++) {
3939                 flow->mpls_lse[i] = mpls_lse[i];
3940             }
3941             if (n > FLOW_MAX_MPLS_LABELS) {
3942                 return ODP_FIT_TOO_MUCH;
3943             }
3944
3945             if (!is_mask) {
3946                 /* BOS may be set only in the innermost label. */
3947                 for (i = 0; i < n - 1; i++) {
3948                     if (flow->mpls_lse[i] & htonl(MPLS_BOS_MASK)) {
3949                         return ODP_FIT_ERROR;
3950                     }
3951                 }
3952
3953                 /* BOS must be set in the innermost label. */
3954                 if (n < FLOW_MAX_MPLS_LABELS
3955                     && !(flow->mpls_lse[n - 1] & htonl(MPLS_BOS_MASK))) {
3956                     return ODP_FIT_TOO_LITTLE;
3957                 }
3958             }
3959         }
3960
3961         goto done;
3962     } else if (src_flow->dl_type == htons(ETH_TYPE_IP)) {
3963         if (!is_mask) {
3964             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV4;
3965         }
3966         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV4)) {
3967             const struct ovs_key_ipv4 *ipv4_key;
3968
3969             ipv4_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV4]);
3970             put_ipv4_key(ipv4_key, flow, is_mask);
3971             if (flow->nw_frag > FLOW_NW_FRAG_MASK) {
3972                 return ODP_FIT_ERROR;
3973             }
3974             if (is_mask) {
3975                 check_start = ipv4_key;
3976                 check_len = sizeof *ipv4_key;
3977                 expected_bit = OVS_KEY_ATTR_IPV4;
3978             }
3979         }
3980     } else if (src_flow->dl_type == htons(ETH_TYPE_IPV6)) {
3981         if (!is_mask) {
3982             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV6;
3983         }
3984         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV6)) {
3985             const struct ovs_key_ipv6 *ipv6_key;
3986
3987             ipv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV6]);
3988             put_ipv6_key(ipv6_key, flow, is_mask);
3989             if (flow->nw_frag > FLOW_NW_FRAG_MASK) {
3990                 return ODP_FIT_ERROR;
3991             }
3992             if (is_mask) {
3993                 check_start = ipv6_key;
3994                 check_len = sizeof *ipv6_key;
3995                 expected_bit = OVS_KEY_ATTR_IPV6;
3996             }
3997         }
3998     } else if (src_flow->dl_type == htons(ETH_TYPE_ARP) ||
3999                src_flow->dl_type == htons(ETH_TYPE_RARP)) {
4000         if (!is_mask) {
4001             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ARP;
4002         }
4003         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ARP)) {
4004             const struct ovs_key_arp *arp_key;
4005
4006             arp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ARP]);
4007             if (!is_mask && (arp_key->arp_op & htons(0xff00))) {
4008                 VLOG_ERR_RL(&rl, "unsupported ARP opcode %"PRIu16" in flow "
4009                             "key", ntohs(arp_key->arp_op));
4010                 return ODP_FIT_ERROR;
4011             }
4012             put_arp_key(arp_key, flow);
4013             if (is_mask) {
4014                 check_start = arp_key;
4015                 check_len = sizeof *arp_key;
4016                 expected_bit = OVS_KEY_ATTR_ARP;
4017             }
4018         }
4019     } else {
4020         goto done;
4021     }
4022     if (check_len > 0) { /* Happens only when 'is_mask'. */
4023         if (!is_all_zeros(check_start, check_len) &&
4024             flow->dl_type != htons(0xffff)) {
4025             return ODP_FIT_ERROR;
4026         } else {
4027             expected_attrs |= UINT64_C(1) << expected_bit;
4028         }
4029     }
4030
4031     expected_bit = OVS_KEY_ATTR_UNSPEC;
4032     if (src_flow->nw_proto == IPPROTO_TCP
4033         && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
4034             src_flow->dl_type == htons(ETH_TYPE_IPV6))
4035         && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4036         if (!is_mask) {
4037             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP;
4038         }
4039         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP)) {
4040             const union ovs_key_tp *tcp_key;
4041
4042             tcp_key = nl_attr_get(attrs[OVS_KEY_ATTR_TCP]);
4043             put_tp_key(tcp_key, flow);
4044             expected_bit = OVS_KEY_ATTR_TCP;
4045         }
4046         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP_FLAGS)) {
4047             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP_FLAGS;
4048             flow->tcp_flags = nl_attr_get_be16(attrs[OVS_KEY_ATTR_TCP_FLAGS]);
4049         }
4050     } else if (src_flow->nw_proto == IPPROTO_UDP
4051                && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
4052                    src_flow->dl_type == htons(ETH_TYPE_IPV6))
4053                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4054         if (!is_mask) {
4055             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_UDP;
4056         }
4057         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_UDP)) {
4058             const union ovs_key_tp *udp_key;
4059
4060             udp_key = nl_attr_get(attrs[OVS_KEY_ATTR_UDP]);
4061             put_tp_key(udp_key, flow);
4062             expected_bit = OVS_KEY_ATTR_UDP;
4063         }
4064     } else if (src_flow->nw_proto == IPPROTO_SCTP
4065                && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
4066                    src_flow->dl_type == htons(ETH_TYPE_IPV6))
4067                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4068         if (!is_mask) {
4069             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_SCTP;
4070         }
4071         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_SCTP)) {
4072             const union ovs_key_tp *sctp_key;
4073
4074             sctp_key = nl_attr_get(attrs[OVS_KEY_ATTR_SCTP]);
4075             put_tp_key(sctp_key, flow);
4076             expected_bit = OVS_KEY_ATTR_SCTP;
4077         }
4078     } else if (src_flow->nw_proto == IPPROTO_ICMP
4079                && src_flow->dl_type == htons(ETH_TYPE_IP)
4080                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4081         if (!is_mask) {
4082             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMP;
4083         }
4084         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMP)) {
4085             const struct ovs_key_icmp *icmp_key;
4086
4087             icmp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMP]);
4088             flow->tp_src = htons(icmp_key->icmp_type);
4089             flow->tp_dst = htons(icmp_key->icmp_code);
4090             expected_bit = OVS_KEY_ATTR_ICMP;
4091         }
4092     } else if (src_flow->nw_proto == IPPROTO_ICMPV6
4093                && src_flow->dl_type == htons(ETH_TYPE_IPV6)
4094                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4095         if (!is_mask) {
4096             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMPV6;
4097         }
4098         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMPV6)) {
4099             const struct ovs_key_icmpv6 *icmpv6_key;
4100
4101             icmpv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMPV6]);
4102             flow->tp_src = htons(icmpv6_key->icmpv6_type);
4103             flow->tp_dst = htons(icmpv6_key->icmpv6_code);
4104             expected_bit = OVS_KEY_ATTR_ICMPV6;
4105             if (src_flow->tp_dst == htons(0) &&
4106                 (src_flow->tp_src == htons(ND_NEIGHBOR_SOLICIT) ||
4107                  src_flow->tp_src == htons(ND_NEIGHBOR_ADVERT))) {
4108                 if (!is_mask) {
4109                     expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
4110                 }
4111                 if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ND)) {
4112                     const struct ovs_key_nd *nd_key;
4113
4114                     nd_key = nl_attr_get(attrs[OVS_KEY_ATTR_ND]);
4115                     memcpy(&flow->nd_target, nd_key->nd_target,
4116                            sizeof flow->nd_target);
4117                     memcpy(flow->arp_sha, nd_key->nd_sll, ETH_ADDR_LEN);
4118                     memcpy(flow->arp_tha, nd_key->nd_tll, ETH_ADDR_LEN);
4119                     if (is_mask) {
4120                         if (!is_all_zeros(nd_key, sizeof *nd_key) &&
4121                             (flow->tp_src != htons(0xffff) ||
4122                              flow->tp_dst != htons(0xffff))) {
4123                             return ODP_FIT_ERROR;
4124                         } else {
4125                             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
4126                         }
4127                     }
4128                 }
4129             }
4130         }
4131     }
4132     if (is_mask && expected_bit != OVS_KEY_ATTR_UNSPEC) {
4133         if ((flow->tp_src || flow->tp_dst) && flow->nw_proto != 0xff) {
4134             return ODP_FIT_ERROR;
4135         } else {
4136             expected_attrs |= UINT64_C(1) << expected_bit;
4137         }
4138     }
4139
4140 done:
4141     return check_expectations(present_attrs, out_of_range_attr, expected_attrs,
4142                               key, key_len);
4143 }
4144
4145 /* Parse 802.1Q header then encapsulated L3 attributes. */
4146 static enum odp_key_fitness
4147 parse_8021q_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
4148                    uint64_t present_attrs, int out_of_range_attr,
4149                    uint64_t expected_attrs, struct flow *flow,
4150                    const struct nlattr *key, size_t key_len,
4151                    const struct flow *src_flow)
4152 {
4153     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4154     bool is_mask = src_flow != flow;
4155
4156     const struct nlattr *encap
4157         = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)
4158            ? attrs[OVS_KEY_ATTR_ENCAP] : NULL);
4159     enum odp_key_fitness encap_fitness;
4160     enum odp_key_fitness fitness;
4161
4162     /* Calculate fitness of outer attributes. */
4163     if (!is_mask) {
4164         expected_attrs |= ((UINT64_C(1) << OVS_KEY_ATTR_VLAN) |
4165                           (UINT64_C(1) << OVS_KEY_ATTR_ENCAP));
4166     } else {
4167         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)) {
4168             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_VLAN);
4169         }
4170         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)) {
4171             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_ENCAP);
4172         }
4173     }
4174     fitness = check_expectations(present_attrs, out_of_range_attr,
4175                                  expected_attrs, key, key_len);
4176
4177     /* Set vlan_tci.
4178      * Remove the TPID from dl_type since it's not the real Ethertype.  */
4179     flow->dl_type = htons(0);
4180     flow->vlan_tci = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)
4181                       ? nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN])
4182                       : htons(0));
4183     if (!is_mask) {
4184         if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN))) {
4185             return ODP_FIT_TOO_LITTLE;
4186         } else if (flow->vlan_tci == htons(0)) {
4187             /* Corner case for a truncated 802.1Q header. */
4188             if (fitness == ODP_FIT_PERFECT && nl_attr_get_size(encap)) {
4189                 return ODP_FIT_TOO_MUCH;
4190             }
4191             return fitness;
4192         } else if (!(flow->vlan_tci & htons(VLAN_CFI))) {
4193             VLOG_ERR_RL(&rl, "OVS_KEY_ATTR_VLAN 0x%04"PRIx16" is nonzero "
4194                         "but CFI bit is not set", ntohs(flow->vlan_tci));
4195             return ODP_FIT_ERROR;
4196         }
4197     } else {
4198         if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP))) {
4199             return fitness;
4200         }
4201     }
4202
4203     /* Now parse the encapsulated attributes. */
4204     if (!parse_flow_nlattrs(nl_attr_get(encap), nl_attr_get_size(encap),
4205                             attrs, &present_attrs, &out_of_range_attr)) {
4206         return ODP_FIT_ERROR;
4207     }
4208     expected_attrs = 0;
4209
4210     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow, src_flow)) {
4211         return ODP_FIT_ERROR;
4212     }
4213     encap_fitness = parse_l2_5_onward(attrs, present_attrs, out_of_range_attr,
4214                                       expected_attrs, flow, key, key_len,
4215                                       src_flow);
4216
4217     /* The overall fitness is the worse of the outer and inner attributes. */
4218     return MAX(fitness, encap_fitness);
4219 }
4220
4221 static enum odp_key_fitness
4222 odp_flow_key_to_flow__(const struct nlattr *key, size_t key_len,
4223                        struct flow *flow, const struct flow *src_flow)
4224 {
4225     const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1];
4226     uint64_t expected_attrs;
4227     uint64_t present_attrs;
4228     int out_of_range_attr;
4229     bool is_mask = src_flow != flow;
4230
4231     memset(flow, 0, sizeof *flow);
4232
4233     /* Parse attributes. */
4234     if (!parse_flow_nlattrs(key, key_len, attrs, &present_attrs,
4235                             &out_of_range_attr)) {
4236         return ODP_FIT_ERROR;
4237     }
4238     expected_attrs = 0;
4239
4240     /* Metadata. */
4241     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_RECIRC_ID)) {
4242         flow->recirc_id = nl_attr_get_u32(attrs[OVS_KEY_ATTR_RECIRC_ID]);
4243         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_RECIRC_ID;
4244     } else if (is_mask) {
4245         /* Always exact match recirc_id if it is not specified. */
4246         flow->recirc_id = UINT32_MAX;
4247     }
4248
4249     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_DP_HASH)) {
4250         flow->dp_hash = nl_attr_get_u32(attrs[OVS_KEY_ATTR_DP_HASH]);
4251         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_DP_HASH;
4252     }
4253     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_PRIORITY)) {
4254         flow->skb_priority = nl_attr_get_u32(attrs[OVS_KEY_ATTR_PRIORITY]);
4255         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_PRIORITY;
4256     }
4257
4258     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_SKB_MARK)) {
4259         flow->pkt_mark = nl_attr_get_u32(attrs[OVS_KEY_ATTR_SKB_MARK]);
4260         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_SKB_MARK;
4261     }
4262
4263     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TUNNEL)) {
4264         enum odp_key_fitness res;
4265
4266         res = odp_tun_key_from_attr(attrs[OVS_KEY_ATTR_TUNNEL], &flow->tunnel);
4267         if (res == ODP_FIT_ERROR) {
4268             return ODP_FIT_ERROR;
4269         } else if (res == ODP_FIT_PERFECT) {
4270             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TUNNEL;
4271         }
4272     }
4273
4274     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IN_PORT)) {
4275         flow->in_port.odp_port
4276             = nl_attr_get_odp_port(attrs[OVS_KEY_ATTR_IN_PORT]);
4277         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IN_PORT;
4278     } else if (!is_mask) {
4279         flow->in_port.odp_port = ODPP_NONE;
4280     }
4281
4282     /* Ethernet header. */
4283     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERNET)) {
4284         const struct ovs_key_ethernet *eth_key;
4285
4286         eth_key = nl_attr_get(attrs[OVS_KEY_ATTR_ETHERNET]);
4287         put_ethernet_key(eth_key, flow);
4288         if (is_mask) {
4289             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
4290         }
4291     }
4292     if (!is_mask) {
4293         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
4294     }
4295
4296     /* Get Ethertype or 802.1Q TPID or FLOW_DL_TYPE_NONE. */
4297     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow,
4298         src_flow)) {
4299         return ODP_FIT_ERROR;
4300     }
4301
4302     if (is_mask
4303         ? (src_flow->vlan_tci & htons(VLAN_CFI)) != 0
4304         : src_flow->dl_type == htons(ETH_TYPE_VLAN)) {
4305         return parse_8021q_onward(attrs, present_attrs, out_of_range_attr,
4306                                   expected_attrs, flow, key, key_len, src_flow);
4307     }
4308     if (is_mask) {
4309         flow->vlan_tci = htons(0xffff);
4310         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)) {
4311             flow->vlan_tci = nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN]);
4312             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_VLAN);
4313         }
4314     }
4315     return parse_l2_5_onward(attrs, present_attrs, out_of_range_attr,
4316                              expected_attrs, flow, key, key_len, src_flow);
4317 }
4318
4319 /* Converts the 'key_len' bytes of OVS_KEY_ATTR_* attributes in 'key' to a flow
4320  * structure in 'flow'.  Returns an ODP_FIT_* value that indicates how well
4321  * 'key' fits our expectations for what a flow key should contain.
4322  *
4323  * The 'in_port' will be the datapath's understanding of the port.  The
4324  * caller will need to translate with odp_port_to_ofp_port() if the
4325  * OpenFlow port is needed.
4326  *
4327  * This function doesn't take the packet itself as an argument because none of
4328  * the currently understood OVS_KEY_ATTR_* attributes require it.  Currently,
4329  * it is always possible to infer which additional attribute(s) should appear
4330  * by looking at the attributes for lower-level protocols, e.g. if the network
4331  * protocol in OVS_KEY_ATTR_IPV4 or OVS_KEY_ATTR_IPV6 is IPPROTO_TCP then we
4332  * know that a OVS_KEY_ATTR_TCP attribute must appear and that otherwise it
4333  * must be absent. */
4334 enum odp_key_fitness
4335 odp_flow_key_to_flow(const struct nlattr *key, size_t key_len,
4336                      struct flow *flow)
4337 {
4338    return odp_flow_key_to_flow__(key, key_len, flow, flow);
4339 }
4340
4341 /* Converts the 'key_len' bytes of OVS_KEY_ATTR_* attributes in 'key' to a mask
4342  * structure in 'mask'.  'flow' must be a previously translated flow
4343  * corresponding to 'mask'.  Returns an ODP_FIT_* value that indicates how well
4344  * 'key' fits our expectations for what a flow key should contain. */
4345 enum odp_key_fitness
4346 odp_flow_key_to_mask(const struct nlattr *key, size_t key_len,
4347                      struct flow *mask, const struct flow *flow)
4348 {
4349    return odp_flow_key_to_flow__(key, key_len, mask, flow);
4350 }
4351
4352 /* Returns 'fitness' as a string, for use in debug messages. */
4353 const char *
4354 odp_key_fitness_to_string(enum odp_key_fitness fitness)
4355 {
4356     switch (fitness) {
4357     case ODP_FIT_PERFECT:
4358         return "OK";
4359     case ODP_FIT_TOO_MUCH:
4360         return "too_much";
4361     case ODP_FIT_TOO_LITTLE:
4362         return "too_little";
4363     case ODP_FIT_ERROR:
4364         return "error";
4365     default:
4366         return "<unknown>";
4367     }
4368 }
4369
4370 /* Appends an OVS_ACTION_ATTR_USERSPACE action to 'odp_actions' that specifies
4371  * Netlink PID 'pid'.  If 'userdata' is nonnull, adds a userdata attribute
4372  * whose contents are the 'userdata_size' bytes at 'userdata' and returns the
4373  * offset within 'odp_actions' of the start of the cookie.  (If 'userdata' is
4374  * null, then the return value is not meaningful.) */
4375 size_t
4376 odp_put_userspace_action(uint32_t pid,
4377                          const void *userdata, size_t userdata_size,
4378                          odp_port_t tunnel_out_port,
4379                          struct ofpbuf *odp_actions)
4380 {
4381     size_t userdata_ofs;
4382     size_t offset;
4383
4384     offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_USERSPACE);
4385     nl_msg_put_u32(odp_actions, OVS_USERSPACE_ATTR_PID, pid);
4386     if (userdata) {
4387         userdata_ofs = odp_actions->size + NLA_HDRLEN;
4388
4389         /* The OVS kernel module before OVS 1.11 and the upstream Linux kernel
4390          * module before Linux 3.10 required the userdata to be exactly 8 bytes
4391          * long:
4392          *
4393          *   - The kernel rejected shorter userdata with -ERANGE.
4394          *
4395          *   - The kernel silently dropped userdata beyond the first 8 bytes.
4396          *
4397          * Thus, for maximum compatibility, always put at least 8 bytes.  (We
4398          * separately disable features that required more than 8 bytes.) */
4399         memcpy(nl_msg_put_unspec_zero(odp_actions, OVS_USERSPACE_ATTR_USERDATA,
4400                                       MAX(8, userdata_size)),
4401                userdata, userdata_size);
4402     } else {
4403         userdata_ofs = 0;
4404     }
4405     if (tunnel_out_port != ODPP_NONE) {
4406         nl_msg_put_odp_port(odp_actions, OVS_USERSPACE_ATTR_EGRESS_TUN_PORT,
4407                             tunnel_out_port);
4408     }
4409     nl_msg_end_nested(odp_actions, offset);
4410
4411     return userdata_ofs;
4412 }
4413
4414 void
4415 odp_put_tunnel_action(const struct flow_tnl *tunnel,
4416                       struct ofpbuf *odp_actions)
4417 {
4418     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
4419     tun_key_to_attr(odp_actions, tunnel);
4420     nl_msg_end_nested(odp_actions, offset);
4421 }
4422
4423 void
4424 odp_put_tnl_push_action(struct ofpbuf *odp_actions,
4425                         struct ovs_action_push_tnl *data)
4426 {
4427     int size = offsetof(struct ovs_action_push_tnl, header);
4428
4429     size += data->header_len;
4430     nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_TUNNEL_PUSH, data, size);
4431 }
4432
4433 \f
4434 /* The commit_odp_actions() function and its helpers. */
4435
4436 static void
4437 commit_set_action(struct ofpbuf *odp_actions, enum ovs_key_attr key_type,
4438                   const void *key, size_t key_size)
4439 {
4440     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
4441     nl_msg_put_unspec(odp_actions, key_type, key, key_size);
4442     nl_msg_end_nested(odp_actions, offset);
4443 }
4444
4445 /* Masked set actions have a mask following the data within the netlink
4446  * attribute.  The unmasked bits in the data will be cleared as the data
4447  * is copied to the action. */
4448 void
4449 commit_masked_set_action(struct ofpbuf *odp_actions,
4450                          enum ovs_key_attr key_type,
4451                          const void *key_, const void *mask_, size_t key_size)
4452 {
4453     size_t offset = nl_msg_start_nested(odp_actions,
4454                                         OVS_ACTION_ATTR_SET_MASKED);
4455     char *data = nl_msg_put_unspec_uninit(odp_actions, key_type, key_size * 2);
4456     const char *key = key_, *mask = mask_;
4457
4458     memcpy(data + key_size, mask, key_size);
4459     /* Clear unmasked bits while copying. */
4460     while (key_size--) {
4461         *data++ = *key++ & *mask++;
4462     }
4463     nl_msg_end_nested(odp_actions, offset);
4464 }
4465
4466 /* If any of the flow key data that ODP actions can modify are different in
4467  * 'base->tunnel' and 'flow->tunnel', appends a set_tunnel ODP action to
4468  * 'odp_actions' that change the flow tunneling information in key from
4469  * 'base->tunnel' into 'flow->tunnel', and then changes 'base->tunnel' in the
4470  * same way.  In other words, operates the same as commit_odp_actions(), but
4471  * only on tunneling information. */
4472 void
4473 commit_odp_tunnel_action(const struct flow *flow, struct flow *base,
4474                          struct ofpbuf *odp_actions)
4475 {
4476     /* A valid IPV4_TUNNEL must have non-zero ip_dst. */
4477     if (flow->tunnel.ip_dst) {
4478         if (!memcmp(&base->tunnel, &flow->tunnel, sizeof base->tunnel)) {
4479             return;
4480         }
4481         memcpy(&base->tunnel, &flow->tunnel, sizeof base->tunnel);
4482         odp_put_tunnel_action(&base->tunnel, odp_actions);
4483     }
4484 }
4485
4486 static bool
4487 commit(enum ovs_key_attr attr, bool use_masked_set,
4488        const void *key, void *base, void *mask, size_t size,
4489        struct ofpbuf *odp_actions)
4490 {
4491     if (memcmp(key, base, size)) {
4492         bool fully_masked = odp_mask_is_exact(attr, mask, size);
4493
4494         if (use_masked_set && !fully_masked) {
4495             commit_masked_set_action(odp_actions, attr, key, mask, size);
4496         } else {
4497             if (!fully_masked) {
4498                 memset(mask, 0xff, size);
4499             }
4500             commit_set_action(odp_actions, attr, key, size);
4501         }
4502         memcpy(base, key, size);
4503         return true;
4504     } else {
4505         /* Mask bits are set when we have either read or set the corresponding
4506          * values.  Masked bits will be exact-matched, no need to set them
4507          * if the value did not actually change. */
4508         return false;
4509     }
4510 }
4511
4512 static void
4513 get_ethernet_key(const struct flow *flow, struct ovs_key_ethernet *eth)
4514 {
4515     memcpy(eth->eth_src, flow->dl_src, ETH_ADDR_LEN);
4516     memcpy(eth->eth_dst, flow->dl_dst, ETH_ADDR_LEN);
4517 }
4518
4519 static void
4520 put_ethernet_key(const struct ovs_key_ethernet *eth, struct flow *flow)
4521 {
4522     memcpy(flow->dl_src, eth->eth_src, ETH_ADDR_LEN);
4523     memcpy(flow->dl_dst, eth->eth_dst, ETH_ADDR_LEN);
4524 }
4525
4526 static void
4527 commit_set_ether_addr_action(const struct flow *flow, struct flow *base_flow,
4528                              struct ofpbuf *odp_actions,
4529                              struct flow_wildcards *wc,
4530                              bool use_masked)
4531 {
4532     struct ovs_key_ethernet key, base, mask;
4533
4534     get_ethernet_key(flow, &key);
4535     get_ethernet_key(base_flow, &base);
4536     get_ethernet_key(&wc->masks, &mask);
4537
4538     if (commit(OVS_KEY_ATTR_ETHERNET, use_masked,
4539                &key, &base, &mask, sizeof key, odp_actions)) {
4540         put_ethernet_key(&base, base_flow);
4541         put_ethernet_key(&mask, &wc->masks);
4542     }
4543 }
4544
4545 static void
4546 pop_vlan(struct flow *base,
4547          struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4548 {
4549     memset(&wc->masks.vlan_tci, 0xff, sizeof wc->masks.vlan_tci);
4550
4551     if (base->vlan_tci & htons(VLAN_CFI)) {
4552         nl_msg_put_flag(odp_actions, OVS_ACTION_ATTR_POP_VLAN);
4553         base->vlan_tci = 0;
4554     }
4555 }
4556
4557 static void
4558 commit_vlan_action(ovs_be16 vlan_tci, struct flow *base,
4559                    struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4560 {
4561     if (base->vlan_tci == vlan_tci) {
4562         return;
4563     }
4564
4565     pop_vlan(base, odp_actions, wc);
4566     if (vlan_tci & htons(VLAN_CFI)) {
4567         struct ovs_action_push_vlan vlan;
4568
4569         vlan.vlan_tpid = htons(ETH_TYPE_VLAN);
4570         vlan.vlan_tci = vlan_tci;
4571         nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_PUSH_VLAN,
4572                           &vlan, sizeof vlan);
4573     }
4574     base->vlan_tci = vlan_tci;
4575 }
4576
4577 /* Wildcarding already done at action translation time. */
4578 static void
4579 commit_mpls_action(const struct flow *flow, struct flow *base,
4580                    struct ofpbuf *odp_actions)
4581 {
4582     int base_n = flow_count_mpls_labels(base, NULL);
4583     int flow_n = flow_count_mpls_labels(flow, NULL);
4584     int common_n = flow_count_common_mpls_labels(flow, flow_n, base, base_n,
4585                                                  NULL);
4586
4587     while (base_n > common_n) {
4588         if (base_n - 1 == common_n && flow_n > common_n) {
4589             /* If there is only one more LSE in base than there are common
4590              * between base and flow; and flow has at least one more LSE than
4591              * is common then the topmost LSE of base may be updated using
4592              * set */
4593             struct ovs_key_mpls mpls_key;
4594
4595             mpls_key.mpls_lse = flow->mpls_lse[flow_n - base_n];
4596             commit_set_action(odp_actions, OVS_KEY_ATTR_MPLS,
4597                               &mpls_key, sizeof mpls_key);
4598             flow_set_mpls_lse(base, 0, mpls_key.mpls_lse);
4599             common_n++;
4600         } else {
4601             /* Otherwise, if there more LSEs in base than are common between
4602              * base and flow then pop the topmost one. */
4603             ovs_be16 dl_type;
4604             bool popped;
4605
4606             /* If all the LSEs are to be popped and this is not the outermost
4607              * LSE then use ETH_TYPE_MPLS as the ethertype parameter of the
4608              * POP_MPLS action instead of flow->dl_type.
4609              *
4610              * This is because the POP_MPLS action requires its ethertype
4611              * argument to be an MPLS ethernet type but in this case
4612              * flow->dl_type will be a non-MPLS ethernet type.
4613              *
4614              * When the final POP_MPLS action occurs it use flow->dl_type and
4615              * the and the resulting packet will have the desired dl_type. */
4616             if ((!eth_type_mpls(flow->dl_type)) && base_n > 1) {
4617                 dl_type = htons(ETH_TYPE_MPLS);
4618             } else {
4619                 dl_type = flow->dl_type;
4620             }
4621             nl_msg_put_be16(odp_actions, OVS_ACTION_ATTR_POP_MPLS, dl_type);
4622             popped = flow_pop_mpls(base, base_n, flow->dl_type, NULL);
4623             ovs_assert(popped);
4624             base_n--;
4625         }
4626     }
4627
4628     /* If, after the above popping and setting, there are more LSEs in flow
4629      * than base then some LSEs need to be pushed. */
4630     while (base_n < flow_n) {
4631         struct ovs_action_push_mpls *mpls;
4632
4633         mpls = nl_msg_put_unspec_zero(odp_actions,
4634                                       OVS_ACTION_ATTR_PUSH_MPLS,
4635                                       sizeof *mpls);
4636         mpls->mpls_ethertype = flow->dl_type;
4637         mpls->mpls_lse = flow->mpls_lse[flow_n - base_n - 1];
4638         flow_push_mpls(base, base_n, mpls->mpls_ethertype, NULL);
4639         flow_set_mpls_lse(base, 0, mpls->mpls_lse);
4640         base_n++;
4641     }
4642 }
4643
4644 static void
4645 get_ipv4_key(const struct flow *flow, struct ovs_key_ipv4 *ipv4, bool is_mask)
4646 {
4647     ipv4->ipv4_src = flow->nw_src;
4648     ipv4->ipv4_dst = flow->nw_dst;
4649     ipv4->ipv4_proto = flow->nw_proto;
4650     ipv4->ipv4_tos = flow->nw_tos;
4651     ipv4->ipv4_ttl = flow->nw_ttl;
4652     ipv4->ipv4_frag = ovs_to_odp_frag(flow->nw_frag, is_mask);
4653 }
4654
4655 static void
4656 put_ipv4_key(const struct ovs_key_ipv4 *ipv4, struct flow *flow, bool is_mask)
4657 {
4658     flow->nw_src = ipv4->ipv4_src;
4659     flow->nw_dst = ipv4->ipv4_dst;
4660     flow->nw_proto = ipv4->ipv4_proto;
4661     flow->nw_tos = ipv4->ipv4_tos;
4662     flow->nw_ttl = ipv4->ipv4_ttl;
4663     flow->nw_frag = odp_to_ovs_frag(ipv4->ipv4_frag, is_mask);
4664 }
4665
4666 static void
4667 commit_set_ipv4_action(const struct flow *flow, struct flow *base_flow,
4668                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4669                        bool use_masked)
4670 {
4671     struct ovs_key_ipv4 key, mask, base;
4672
4673     /* Check that nw_proto and nw_frag remain unchanged. */
4674     ovs_assert(flow->nw_proto == base_flow->nw_proto &&
4675                flow->nw_frag == base_flow->nw_frag);
4676
4677     get_ipv4_key(flow, &key, false);
4678     get_ipv4_key(base_flow, &base, false);
4679     get_ipv4_key(&wc->masks, &mask, true);
4680     mask.ipv4_proto = 0;        /* Not writeable. */
4681     mask.ipv4_frag = 0;         /* Not writable. */
4682
4683     if (commit(OVS_KEY_ATTR_IPV4, use_masked, &key, &base, &mask, sizeof key,
4684                odp_actions)) {
4685         put_ipv4_key(&base, base_flow, false);
4686         if (mask.ipv4_proto != 0) { /* Mask was changed by commit(). */
4687             put_ipv4_key(&mask, &wc->masks, true);
4688         }
4689    }
4690 }
4691
4692 static void
4693 get_ipv6_key(const struct flow *flow, struct ovs_key_ipv6 *ipv6, bool is_mask)
4694 {
4695     memcpy(ipv6->ipv6_src, &flow->ipv6_src, sizeof ipv6->ipv6_src);
4696     memcpy(ipv6->ipv6_dst, &flow->ipv6_dst, sizeof ipv6->ipv6_dst);
4697     ipv6->ipv6_label = flow->ipv6_label;
4698     ipv6->ipv6_proto = flow->nw_proto;
4699     ipv6->ipv6_tclass = flow->nw_tos;
4700     ipv6->ipv6_hlimit = flow->nw_ttl;
4701     ipv6->ipv6_frag = ovs_to_odp_frag(flow->nw_frag, is_mask);
4702 }
4703
4704 static void
4705 put_ipv6_key(const struct ovs_key_ipv6 *ipv6, struct flow *flow, bool is_mask)
4706 {
4707     memcpy(&flow->ipv6_src, ipv6->ipv6_src, sizeof flow->ipv6_src);
4708     memcpy(&flow->ipv6_dst, ipv6->ipv6_dst, sizeof flow->ipv6_dst);
4709     flow->ipv6_label = ipv6->ipv6_label;
4710     flow->nw_proto = ipv6->ipv6_proto;
4711     flow->nw_tos = ipv6->ipv6_tclass;
4712     flow->nw_ttl = ipv6->ipv6_hlimit;
4713     flow->nw_frag = odp_to_ovs_frag(ipv6->ipv6_frag, is_mask);
4714 }
4715
4716 static void
4717 commit_set_ipv6_action(const struct flow *flow, struct flow *base_flow,
4718                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4719                        bool use_masked)
4720 {
4721     struct ovs_key_ipv6 key, mask, base;
4722
4723     /* Check that nw_proto and nw_frag remain unchanged. */
4724     ovs_assert(flow->nw_proto == base_flow->nw_proto &&
4725                flow->nw_frag == base_flow->nw_frag);
4726
4727     get_ipv6_key(flow, &key, false);
4728     get_ipv6_key(base_flow, &base, false);
4729     get_ipv6_key(&wc->masks, &mask, true);
4730     mask.ipv6_proto = 0;        /* Not writeable. */
4731     mask.ipv6_frag = 0;         /* Not writable. */
4732
4733     if (commit(OVS_KEY_ATTR_IPV6, use_masked, &key, &base, &mask, sizeof key,
4734                odp_actions)) {
4735         put_ipv6_key(&base, base_flow, false);
4736         if (mask.ipv6_proto != 0) { /* Mask was changed by commit(). */
4737             put_ipv6_key(&mask, &wc->masks, true);
4738         }
4739     }
4740 }
4741
4742 static void
4743 get_arp_key(const struct flow *flow, struct ovs_key_arp *arp)
4744 {
4745     /* ARP key has padding, clear it. */
4746     memset(arp, 0, sizeof *arp);
4747
4748     arp->arp_sip = flow->nw_src;
4749     arp->arp_tip = flow->nw_dst;
4750     arp->arp_op = htons(flow->nw_proto);
4751     memcpy(arp->arp_sha, flow->arp_sha, ETH_ADDR_LEN);
4752     memcpy(arp->arp_tha, flow->arp_tha, ETH_ADDR_LEN);
4753 }
4754
4755 static void
4756 put_arp_key(const struct ovs_key_arp *arp, struct flow *flow)
4757 {
4758     flow->nw_src = arp->arp_sip;
4759     flow->nw_dst = arp->arp_tip;
4760     flow->nw_proto = ntohs(arp->arp_op);
4761     memcpy(flow->arp_sha, arp->arp_sha, ETH_ADDR_LEN);
4762     memcpy(flow->arp_tha, arp->arp_tha, ETH_ADDR_LEN);
4763 }
4764
4765 static enum slow_path_reason
4766 commit_set_arp_action(const struct flow *flow, struct flow *base_flow,
4767                       struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4768 {
4769     struct ovs_key_arp key, mask, base;
4770
4771     get_arp_key(flow, &key);
4772     get_arp_key(base_flow, &base);
4773     get_arp_key(&wc->masks, &mask);
4774
4775     if (commit(OVS_KEY_ATTR_ARP, true, &key, &base, &mask, sizeof key,
4776                odp_actions)) {
4777         put_arp_key(&base, base_flow);
4778         put_arp_key(&mask, &wc->masks);
4779         return SLOW_ACTION;
4780     }
4781     return 0;
4782 }
4783
4784 static void
4785 get_nd_key(const struct flow *flow, struct ovs_key_nd *nd)
4786 {
4787     memcpy(nd->nd_target, &flow->nd_target, sizeof flow->nd_target);
4788     /* nd_sll and nd_tll are stored in arp_sha and arp_tha, respectively */
4789     memcpy(nd->nd_sll, flow->arp_sha, ETH_ADDR_LEN);
4790     memcpy(nd->nd_tll, flow->arp_tha, ETH_ADDR_LEN);
4791 }
4792
4793 static void
4794 put_nd_key(const struct ovs_key_nd *nd, struct flow *flow)
4795 {
4796     memcpy(&flow->nd_target, &flow->nd_target, sizeof flow->nd_target);
4797     /* nd_sll and nd_tll are stored in arp_sha and arp_tha, respectively */
4798     memcpy(flow->arp_sha, nd->nd_sll, ETH_ADDR_LEN);
4799     memcpy(flow->arp_tha, nd->nd_tll, ETH_ADDR_LEN);
4800 }
4801
4802 static enum slow_path_reason
4803 commit_set_nd_action(const struct flow *flow, struct flow *base_flow,
4804                      struct ofpbuf *odp_actions,
4805                      struct flow_wildcards *wc, bool use_masked)
4806 {
4807     struct ovs_key_nd key, mask, base;
4808
4809     get_nd_key(flow, &key);
4810     get_nd_key(base_flow, &base);
4811     get_nd_key(&wc->masks, &mask);
4812
4813     if (commit(OVS_KEY_ATTR_ND, use_masked, &key, &base, &mask, sizeof key,
4814                odp_actions)) {
4815         put_nd_key(&base, base_flow);
4816         put_nd_key(&mask, &wc->masks);
4817         return SLOW_ACTION;
4818     }
4819
4820     return 0;
4821 }
4822
4823 static enum slow_path_reason
4824 commit_set_nw_action(const struct flow *flow, struct flow *base,
4825                      struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4826                      bool use_masked)
4827 {
4828     /* Check if 'flow' really has an L3 header. */
4829     if (!flow->nw_proto) {
4830         return 0;
4831     }
4832
4833     switch (ntohs(base->dl_type)) {
4834     case ETH_TYPE_IP:
4835         commit_set_ipv4_action(flow, base, odp_actions, wc, use_masked);
4836         break;
4837
4838     case ETH_TYPE_IPV6:
4839         commit_set_ipv6_action(flow, base, odp_actions, wc, use_masked);
4840         return commit_set_nd_action(flow, base, odp_actions, wc, use_masked);
4841
4842     case ETH_TYPE_ARP:
4843         return commit_set_arp_action(flow, base, odp_actions, wc);
4844     }
4845
4846     return 0;
4847 }
4848
4849 /* TCP, UDP, and SCTP keys have the same layout. */
4850 BUILD_ASSERT_DECL(sizeof(struct ovs_key_tcp) == sizeof(struct ovs_key_udp) &&
4851                   sizeof(struct ovs_key_tcp) == sizeof(struct ovs_key_sctp));
4852
4853 static void
4854 get_tp_key(const struct flow *flow, union ovs_key_tp *tp)
4855 {
4856     tp->tcp.tcp_src = flow->tp_src;
4857     tp->tcp.tcp_dst = flow->tp_dst;
4858 }
4859
4860 static void
4861 put_tp_key(const union ovs_key_tp *tp, struct flow *flow)
4862 {
4863     flow->tp_src = tp->tcp.tcp_src;
4864     flow->tp_dst = tp->tcp.tcp_dst;
4865 }
4866
4867 static void
4868 commit_set_port_action(const struct flow *flow, struct flow *base_flow,
4869                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4870                        bool use_masked)
4871 {
4872     enum ovs_key_attr key_type;
4873     union ovs_key_tp key, mask, base;
4874
4875     /* Check if 'flow' really has an L3 header. */
4876     if (!flow->nw_proto) {
4877         return;
4878     }
4879
4880     if (!is_ip_any(base_flow)) {
4881         return;
4882     }
4883
4884     if (flow->nw_proto == IPPROTO_TCP) {
4885         key_type = OVS_KEY_ATTR_TCP;
4886     } else if (flow->nw_proto == IPPROTO_UDP) {
4887         key_type = OVS_KEY_ATTR_UDP;
4888     } else if (flow->nw_proto == IPPROTO_SCTP) {
4889         key_type = OVS_KEY_ATTR_SCTP;
4890     } else {
4891         return;
4892     }
4893
4894     get_tp_key(flow, &key);
4895     get_tp_key(base_flow, &base);
4896     get_tp_key(&wc->masks, &mask);
4897
4898     if (commit(key_type, use_masked, &key, &base, &mask, sizeof key,
4899                odp_actions)) {
4900         put_tp_key(&base, base_flow);
4901         put_tp_key(&mask, &wc->masks);
4902     }
4903 }
4904
4905 static void
4906 commit_set_priority_action(const struct flow *flow, struct flow *base_flow,
4907                            struct ofpbuf *odp_actions,
4908                            struct flow_wildcards *wc,
4909                            bool use_masked)
4910 {
4911     uint32_t key, mask, base;
4912
4913     key = flow->skb_priority;
4914     base = base_flow->skb_priority;
4915     mask = wc->masks.skb_priority;
4916
4917     if (commit(OVS_KEY_ATTR_PRIORITY, use_masked, &key, &base, &mask,
4918                sizeof key, odp_actions)) {
4919         base_flow->skb_priority = base;
4920         wc->masks.skb_priority = mask;
4921     }
4922 }
4923
4924 static void
4925 commit_set_pkt_mark_action(const struct flow *flow, struct flow *base_flow,
4926                            struct ofpbuf *odp_actions,
4927                            struct flow_wildcards *wc,
4928                            bool use_masked)
4929 {
4930     uint32_t key, mask, base;
4931
4932     key = flow->pkt_mark;
4933     base = base_flow->pkt_mark;
4934     mask = wc->masks.pkt_mark;
4935
4936     if (commit(OVS_KEY_ATTR_SKB_MARK, use_masked, &key, &base, &mask,
4937                sizeof key, odp_actions)) {
4938         base_flow->pkt_mark = base;
4939         wc->masks.pkt_mark = mask;
4940     }
4941 }
4942
4943 /* If any of the flow key data that ODP actions can modify are different in
4944  * 'base' and 'flow', appends ODP actions to 'odp_actions' that change the flow
4945  * key from 'base' into 'flow', and then changes 'base' the same way.  Does not
4946  * commit set_tunnel actions.  Users should call commit_odp_tunnel_action()
4947  * in addition to this function if needed.  Sets fields in 'wc' that are
4948  * used as part of the action.
4949  *
4950  * Returns a reason to force processing the flow's packets into the userspace
4951  * slow path, if there is one, otherwise 0. */
4952 enum slow_path_reason
4953 commit_odp_actions(const struct flow *flow, struct flow *base,
4954                    struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4955                    bool use_masked)
4956 {
4957     enum slow_path_reason slow;
4958
4959     commit_set_ether_addr_action(flow, base, odp_actions, wc, use_masked);
4960     slow = commit_set_nw_action(flow, base, odp_actions, wc, use_masked);
4961     commit_set_port_action(flow, base, odp_actions, wc, use_masked);
4962     commit_mpls_action(flow, base, odp_actions);
4963     commit_vlan_action(flow->vlan_tci, base, odp_actions, wc);
4964     commit_set_priority_action(flow, base, odp_actions, wc, use_masked);
4965     commit_set_pkt_mark_action(flow, base, odp_actions, wc, use_masked);
4966
4967     return slow;
4968 }