odp-util: Geneve netlink decoding.
[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, id_mask;
2894     uint8_t flags, flags_mask;
2895
2896     if (!strncmp(s, "id=", 3)) {
2897         s += 3;
2898         s += scan_be16(s, &id, mask ? &id_mask : NULL);
2899     } else if (mask) {
2900         memset(&id_mask, 0, sizeof id_mask);
2901     }
2902
2903     if (s[0] == ',') {
2904         s++;
2905     }
2906     if (!strncmp(s, "flags=", 6)) {
2907         s += 6;
2908         s += scan_u8(s, &flags, mask ? &flags_mask : NULL);
2909     } else if (mask) {
2910         memset(&flags_mask, 0, sizeof flags_mask);
2911     }
2912
2913     if (!strncmp(s, "))", 2)) {
2914         s += 2;
2915
2916         *key = (flags << 16) | ntohs(id);
2917         if (mask) {
2918             *mask = (flags_mask << 16) | ntohs(id_mask);
2919         }
2920
2921         return s - s_base;
2922     }
2923
2924     return 0;
2925 }
2926
2927 struct geneve_scan {
2928     uint8_t d[252];
2929     int len;
2930 };
2931
2932 static int
2933 scan_geneve(const char *s, struct geneve_scan *key, struct geneve_scan *mask)
2934 {
2935     const char *s_base = s;
2936     struct geneve_opt *opt = (struct geneve_opt *)key->d;
2937     struct geneve_opt *opt_mask = (struct geneve_opt *)(mask ? mask->d : NULL);
2938     int len_remain = sizeof key->d;
2939
2940     while (s[0] == '{' && len_remain >= sizeof *opt) {
2941         int data_len = 0;
2942
2943         s++;
2944         len_remain -= sizeof *opt;
2945
2946         if (!strncmp(s, "class=", 6)) {
2947             s += 6;
2948             s += scan_be16(s, &opt->opt_class,
2949                            mask ? &opt_mask->opt_class : NULL);
2950         } else if (mask) {
2951             memset(&opt_mask->opt_class, 0, sizeof opt_mask->opt_class);
2952         }
2953
2954         if (s[0] == ',') {
2955             s++;
2956         }
2957         if (!strncmp(s, "type=", 5)) {
2958             s += 5;
2959             s += scan_u8(s, &opt->type, mask ? &opt_mask->type : NULL);
2960         } else if (mask) {
2961             memset(&opt_mask->type, 0, sizeof opt_mask->type);
2962         }
2963
2964         if (s[0] == ',') {
2965             s++;
2966         }
2967         if (!strncmp(s, "len=", 4)) {
2968             uint8_t opt_len, opt_len_mask;
2969             s += 4;
2970             s += scan_u8(s, &opt_len, mask ? &opt_len_mask : NULL);
2971
2972             if (opt_len > 124 || opt_len % 4 || opt_len > len_remain) {
2973                 return 0;
2974             }
2975             opt->length = opt_len / 4;
2976             if (mask) {
2977                 opt_mask->length = opt_len_mask;
2978             }
2979             data_len = opt_len;
2980         } else if (mask) {
2981             memset(&opt_mask->type, 0, sizeof opt_mask->type);
2982         }
2983
2984         if (s[0] == ',') {
2985             s++;
2986         }
2987         if (parse_int_string(s, (uint8_t *)(opt + 1), data_len, (char **)&s)) {
2988             return 0;
2989         }
2990
2991         if (mask) {
2992             if (s[0] == '/') {
2993                 s++;
2994                 if (parse_int_string(s, (uint8_t *)(opt_mask + 1),
2995                                      data_len, (char **)&s)) {
2996                     return 0;
2997                 }
2998             }
2999             opt_mask->r1 = 0;
3000             opt_mask->r2 = 0;
3001             opt_mask->r3 = 0;
3002         }
3003
3004         if (s[0] == '}') {
3005             s++;
3006             opt += 1 + data_len / 4;
3007             if (mask) {
3008                 opt_mask += 1 + data_len / 4;
3009             }
3010             len_remain -= data_len;
3011         }
3012     }
3013
3014     if (s[0] == ')') {
3015         int len = sizeof key->d - len_remain;
3016
3017         s++;
3018         key->len = len;
3019         if (mask) {
3020             mask->len = len;
3021         }
3022         return s - s_base;
3023     }
3024
3025     return 0;
3026 }
3027
3028 static void
3029 tun_flags_to_attr(struct ofpbuf *a, const void *data_)
3030 {
3031     const uint16_t *flags = data_;
3032
3033     if (*flags & FLOW_TNL_F_DONT_FRAGMENT) {
3034         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT);
3035     }
3036     if (*flags & FLOW_TNL_F_CSUM) {
3037         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_CSUM);
3038     }
3039     if (*flags & FLOW_TNL_F_OAM) {
3040         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_OAM);
3041     }
3042 }
3043
3044 static void
3045 vxlan_gbp_to_attr(struct ofpbuf *a, const void *data_)
3046 {
3047     const uint32_t *gbp = data_;
3048
3049     if (*gbp) {
3050         size_t vxlan_opts_ofs;
3051
3052         vxlan_opts_ofs = nl_msg_start_nested(a, OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS);
3053         nl_msg_put_u32(a, OVS_VXLAN_EXT_GBP, *gbp);
3054         nl_msg_end_nested(a, vxlan_opts_ofs);
3055     }
3056 }
3057
3058 static void
3059 geneve_to_attr(struct ofpbuf *a, const void *data_)
3060 {
3061     const struct geneve_scan *geneve = data_;
3062
3063     nl_msg_put_unspec(a, OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS, geneve->d,
3064                       geneve->len);
3065 }
3066
3067 #define SCAN_PUT_ATTR(BUF, ATTR, DATA, FUNC)                      \
3068     {                                                             \
3069         unsigned long call_fn = (unsigned long)FUNC;              \
3070         if (call_fn) {                                            \
3071             typedef void (*fn)(struct ofpbuf *, const void *);    \
3072             fn func = FUNC;                                       \
3073             func(BUF, &(DATA));                                   \
3074         } else {                                                  \
3075             nl_msg_put_unspec(BUF, ATTR, &(DATA), sizeof (DATA)); \
3076         }                                                         \
3077     }
3078
3079 #define SCAN_IF(NAME)                           \
3080     if (strncmp(s, NAME, strlen(NAME)) == 0) {  \
3081         const char *start = s;                  \
3082         int len;                                \
3083                                                 \
3084         s += strlen(NAME)
3085
3086 /* Usually no special initialization is needed. */
3087 #define SCAN_BEGIN(NAME, TYPE)                  \
3088     SCAN_IF(NAME);                              \
3089         TYPE skey, smask;                       \
3090         memset(&skey, 0, sizeof skey);          \
3091         memset(&smask, 0, sizeof smask);        \
3092         do {                                    \
3093             len = 0;
3094
3095 /* Init as fully-masked as mask will not be scanned. */
3096 #define SCAN_BEGIN_FULLY_MASKED(NAME, TYPE)     \
3097     SCAN_IF(NAME);                              \
3098         TYPE skey, smask;                       \
3099         memset(&skey, 0, sizeof skey);          \
3100         memset(&smask, 0xff, sizeof smask);     \
3101         do {                                    \
3102             len = 0;
3103
3104 /* VLAN needs special initialization. */
3105 #define SCAN_BEGIN_INIT(NAME, TYPE, KEY_INIT, MASK_INIT)  \
3106     SCAN_IF(NAME);                                        \
3107         TYPE skey = KEY_INIT;                       \
3108         TYPE smask = MASK_INIT;                     \
3109         do {                                        \
3110             len = 0;
3111
3112 /* Scan unnamed entry as 'TYPE' */
3113 #define SCAN_TYPE(TYPE, KEY, MASK)              \
3114     len = scan_##TYPE(s, KEY, MASK);            \
3115     if (len == 0) {                             \
3116         return -EINVAL;                         \
3117     }                                           \
3118     s += len
3119
3120 /* Scan named ('NAME') entry 'FIELD' as 'TYPE'. */
3121 #define SCAN_FIELD(NAME, TYPE, FIELD)                                   \
3122     if (strncmp(s, NAME, strlen(NAME)) == 0) {                          \
3123         s += strlen(NAME);                                              \
3124         SCAN_TYPE(TYPE, &skey.FIELD, mask ? &smask.FIELD : NULL);       \
3125         continue;                                                       \
3126     }
3127
3128 #define SCAN_FINISH()                           \
3129         } while (*s++ == ',' && len != 0);      \
3130         if (s[-1] != ')') {                     \
3131             return -EINVAL;                     \
3132         }
3133
3134 #define SCAN_FINISH_SINGLE()                    \
3135         } while (false);                        \
3136         if (*s++ != ')') {                      \
3137             return -EINVAL;                     \
3138         }
3139
3140 /* Beginning of nested attribute. */
3141 #define SCAN_BEGIN_NESTED(NAME, ATTR)                      \
3142     SCAN_IF(NAME);                                         \
3143         size_t key_offset, mask_offset;                    \
3144         key_offset = nl_msg_start_nested(key, ATTR);       \
3145         if (mask) {                                        \
3146             mask_offset = nl_msg_start_nested(mask, ATTR); \
3147         }                                                  \
3148         do {                                               \
3149             len = 0;
3150
3151 #define SCAN_END_NESTED()                               \
3152         SCAN_FINISH();                                  \
3153         nl_msg_end_nested(key, key_offset);             \
3154         if (mask) {                                     \
3155             nl_msg_end_nested(mask, mask_offset);       \
3156         }                                               \
3157         return s - start;                               \
3158     }
3159
3160 #define SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, ATTR, FUNC)  \
3161     if (strncmp(s, NAME, strlen(NAME)) == 0) {                \
3162         TYPE skey, smask;                                     \
3163         memset(&skey, 0, sizeof skey);                        \
3164         memset(&smask, 0xff, sizeof smask);                   \
3165         s += strlen(NAME);                                    \
3166         SCAN_TYPE(SCAN_AS, &skey, &smask);                    \
3167         SCAN_PUT(ATTR, FUNC);                                 \
3168         continue;                                             \
3169     }
3170
3171 #define SCAN_FIELD_NESTED(NAME, TYPE, SCAN_AS, ATTR)  \
3172         SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, ATTR, NULL)
3173
3174 #define SCAN_FIELD_NESTED_FUNC(NAME, TYPE, SCAN_AS, FUNC)  \
3175         SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, 0, FUNC)
3176
3177 #define SCAN_PUT(ATTR, FUNC)                            \
3178         if (!mask || !is_all_zeros(&smask, sizeof smask)) { \
3179             SCAN_PUT_ATTR(key, ATTR, skey, FUNC);       \
3180             if (mask) {                                 \
3181                 SCAN_PUT_ATTR(mask, ATTR, smask, FUNC); \
3182             }                                           \
3183         }
3184
3185 #define SCAN_END(ATTR)                                  \
3186         SCAN_FINISH();                                  \
3187         SCAN_PUT(ATTR, NULL);                           \
3188         return s - start;                               \
3189     }
3190
3191 #define SCAN_END_SINGLE(ATTR)                           \
3192         SCAN_FINISH_SINGLE();                           \
3193         SCAN_PUT(ATTR, NULL);                           \
3194         return s - start;                               \
3195     }
3196
3197 #define SCAN_SINGLE(NAME, TYPE, SCAN_AS, ATTR)       \
3198     SCAN_BEGIN(NAME, TYPE) {                         \
3199         SCAN_TYPE(SCAN_AS, &skey, &smask);           \
3200     } SCAN_END_SINGLE(ATTR)
3201
3202 #define SCAN_SINGLE_FULLY_MASKED(NAME, TYPE, SCAN_AS, ATTR) \
3203     SCAN_BEGIN_FULLY_MASKED(NAME, TYPE) {                   \
3204         SCAN_TYPE(SCAN_AS, &skey, NULL);                    \
3205     } SCAN_END_SINGLE(ATTR)
3206
3207 /* scan_port needs one extra argument. */
3208 #define SCAN_SINGLE_PORT(NAME, TYPE, ATTR)  \
3209     SCAN_BEGIN(NAME, TYPE) {                            \
3210         len = scan_port(s, &skey, &smask, port_names);  \
3211         if (len == 0) {                                 \
3212             return -EINVAL;                             \
3213         }                                               \
3214         s += len;                                       \
3215     } SCAN_END_SINGLE(ATTR)
3216
3217 static int
3218 parse_odp_key_mask_attr(const char *s, const struct simap *port_names,
3219                         struct ofpbuf *key, struct ofpbuf *mask)
3220 {
3221     if (!strncmp(s, "ufid:", 5)) {
3222         const char *start = s;
3223
3224         /* Skip UFID. */
3225         s += 5;
3226         s += strspn(s, hex_chars);
3227         s += strspn(s, delimiters);
3228
3229         return s - start;
3230     }
3231
3232     SCAN_SINGLE("skb_priority(", uint32_t, u32, OVS_KEY_ATTR_PRIORITY);
3233     SCAN_SINGLE("skb_mark(", uint32_t, u32, OVS_KEY_ATTR_SKB_MARK);
3234     SCAN_SINGLE_FULLY_MASKED("recirc_id(", uint32_t, u32,
3235                              OVS_KEY_ATTR_RECIRC_ID);
3236     SCAN_SINGLE("dp_hash(", uint32_t, u32, OVS_KEY_ATTR_DP_HASH);
3237
3238     SCAN_BEGIN_NESTED("tunnel(", OVS_KEY_ATTR_TUNNEL) {
3239         SCAN_FIELD_NESTED("tun_id=", ovs_be64, be64, OVS_TUNNEL_KEY_ATTR_ID);
3240         SCAN_FIELD_NESTED("src=", ovs_be32, ipv4, OVS_TUNNEL_KEY_ATTR_IPV4_SRC);
3241         SCAN_FIELD_NESTED("dst=", ovs_be32, ipv4, OVS_TUNNEL_KEY_ATTR_IPV4_DST);
3242         SCAN_FIELD_NESTED("tos=", uint8_t, u8, OVS_TUNNEL_KEY_ATTR_TOS);
3243         SCAN_FIELD_NESTED("ttl=", uint8_t, u8, OVS_TUNNEL_KEY_ATTR_TTL);
3244         SCAN_FIELD_NESTED("tp_src=", ovs_be16, be16, OVS_TUNNEL_KEY_ATTR_TP_SRC);
3245         SCAN_FIELD_NESTED("tp_dst=", ovs_be16, be16, OVS_TUNNEL_KEY_ATTR_TP_DST);
3246         SCAN_FIELD_NESTED_FUNC("vxlan(gbp(", uint32_t, vxlan_gbp, vxlan_gbp_to_attr);
3247         SCAN_FIELD_NESTED_FUNC("geneve(", struct geneve_scan, geneve,
3248                                geneve_to_attr);
3249         SCAN_FIELD_NESTED_FUNC("flags(", uint16_t, tun_flags, tun_flags_to_attr);
3250     } SCAN_END_NESTED();
3251
3252     SCAN_SINGLE_PORT("in_port(", uint32_t, OVS_KEY_ATTR_IN_PORT);
3253
3254     SCAN_BEGIN("eth(", struct ovs_key_ethernet) {
3255         SCAN_FIELD("src=", eth, eth_src);
3256         SCAN_FIELD("dst=", eth, eth_dst);
3257     } SCAN_END(OVS_KEY_ATTR_ETHERNET);
3258
3259     SCAN_BEGIN_INIT("vlan(", struct ovs_key_vlan__,
3260                     { htons(VLAN_CFI) }, { htons(VLAN_CFI) }) {
3261         SCAN_FIELD("vid=", vid, tci);
3262         SCAN_FIELD("pcp=", pcp, tci);
3263         SCAN_FIELD("cfi=", cfi, tci);
3264     } SCAN_END(OVS_KEY_ATTR_VLAN);
3265
3266     SCAN_SINGLE("eth_type(", ovs_be16, be16, OVS_KEY_ATTR_ETHERTYPE);
3267
3268     SCAN_BEGIN("mpls(", struct ovs_key_mpls) {
3269         SCAN_FIELD("label=", mpls_label, mpls_lse);
3270         SCAN_FIELD("tc=", mpls_tc, mpls_lse);
3271         SCAN_FIELD("ttl=", mpls_ttl, mpls_lse);
3272         SCAN_FIELD("bos=", mpls_bos, mpls_lse);
3273     } SCAN_END(OVS_KEY_ATTR_MPLS);
3274
3275     SCAN_BEGIN("ipv4(", struct ovs_key_ipv4) {
3276         SCAN_FIELD("src=", ipv4, ipv4_src);
3277         SCAN_FIELD("dst=", ipv4, ipv4_dst);
3278         SCAN_FIELD("proto=", u8, ipv4_proto);
3279         SCAN_FIELD("tos=", u8, ipv4_tos);
3280         SCAN_FIELD("ttl=", u8, ipv4_ttl);
3281         SCAN_FIELD("frag=", frag, ipv4_frag);
3282     } SCAN_END(OVS_KEY_ATTR_IPV4);
3283
3284     SCAN_BEGIN("ipv6(", struct ovs_key_ipv6) {
3285         SCAN_FIELD("src=", ipv6, ipv6_src);
3286         SCAN_FIELD("dst=", ipv6, ipv6_dst);
3287         SCAN_FIELD("label=", ipv6_label, ipv6_label);
3288         SCAN_FIELD("proto=", u8, ipv6_proto);
3289         SCAN_FIELD("tclass=", u8, ipv6_tclass);
3290         SCAN_FIELD("hlimit=", u8, ipv6_hlimit);
3291         SCAN_FIELD("frag=", frag, ipv6_frag);
3292     } SCAN_END(OVS_KEY_ATTR_IPV6);
3293
3294     SCAN_BEGIN("tcp(", struct ovs_key_tcp) {
3295         SCAN_FIELD("src=", be16, tcp_src);
3296         SCAN_FIELD("dst=", be16, tcp_dst);
3297     } SCAN_END(OVS_KEY_ATTR_TCP);
3298
3299     SCAN_SINGLE("tcp_flags(", ovs_be16, tcp_flags, OVS_KEY_ATTR_TCP_FLAGS);
3300
3301     SCAN_BEGIN("udp(", struct ovs_key_udp) {
3302         SCAN_FIELD("src=", be16, udp_src);
3303         SCAN_FIELD("dst=", be16, udp_dst);
3304     } SCAN_END(OVS_KEY_ATTR_UDP);
3305
3306     SCAN_BEGIN("sctp(", struct ovs_key_sctp) {
3307         SCAN_FIELD("src=", be16, sctp_src);
3308         SCAN_FIELD("dst=", be16, sctp_dst);
3309     } SCAN_END(OVS_KEY_ATTR_SCTP);
3310
3311     SCAN_BEGIN("icmp(", struct ovs_key_icmp) {
3312         SCAN_FIELD("type=", u8, icmp_type);
3313         SCAN_FIELD("code=", u8, icmp_code);
3314     } SCAN_END(OVS_KEY_ATTR_ICMP);
3315
3316     SCAN_BEGIN("icmpv6(", struct ovs_key_icmpv6) {
3317         SCAN_FIELD("type=", u8, icmpv6_type);
3318         SCAN_FIELD("code=", u8, icmpv6_code);
3319     } SCAN_END(OVS_KEY_ATTR_ICMPV6);
3320
3321     SCAN_BEGIN("arp(", struct ovs_key_arp) {
3322         SCAN_FIELD("sip=", ipv4, arp_sip);
3323         SCAN_FIELD("tip=", ipv4, arp_tip);
3324         SCAN_FIELD("op=", be16, arp_op);
3325         SCAN_FIELD("sha=", eth, arp_sha);
3326         SCAN_FIELD("tha=", eth, arp_tha);
3327     } SCAN_END(OVS_KEY_ATTR_ARP);
3328
3329     SCAN_BEGIN("nd(", struct ovs_key_nd) {
3330         SCAN_FIELD("target=", ipv6, nd_target);
3331         SCAN_FIELD("sll=", eth, nd_sll);
3332         SCAN_FIELD("tll=", eth, nd_tll);
3333     } SCAN_END(OVS_KEY_ATTR_ND);
3334
3335     /* Encap open-coded. */
3336     if (!strncmp(s, "encap(", 6)) {
3337         const char *start = s;
3338         size_t encap, encap_mask = 0;
3339
3340         encap = nl_msg_start_nested(key, OVS_KEY_ATTR_ENCAP);
3341         if (mask) {
3342             encap_mask = nl_msg_start_nested(mask, OVS_KEY_ATTR_ENCAP);
3343         }
3344
3345         s += 6;
3346         for (;;) {
3347             int retval;
3348
3349             s += strspn(s, delimiters);
3350             if (!*s) {
3351                 return -EINVAL;
3352             } else if (*s == ')') {
3353                 break;
3354             }
3355
3356             retval = parse_odp_key_mask_attr(s, port_names, key, mask);
3357             if (retval < 0) {
3358                 return retval;
3359             }
3360             s += retval;
3361         }
3362         s++;
3363
3364         nl_msg_end_nested(key, encap);
3365         if (mask) {
3366             nl_msg_end_nested(mask, encap_mask);
3367         }
3368
3369         return s - start;
3370     }
3371
3372     return -EINVAL;
3373 }
3374
3375 /* Parses the string representation of a datapath flow key, in the
3376  * format output by odp_flow_key_format().  Returns 0 if successful,
3377  * otherwise a positive errno value.  On success, the flow key is
3378  * appended to 'key' as a series of Netlink attributes.  On failure, no
3379  * data is appended to 'key'.  Either way, 'key''s data might be
3380  * reallocated.
3381  *
3382  * If 'port_names' is nonnull, it points to an simap that maps from a port name
3383  * to a port number.  (Port names may be used instead of port numbers in
3384  * in_port.)
3385  *
3386  * On success, the attributes appended to 'key' are individually syntactically
3387  * valid, but they may not be valid as a sequence.  'key' might, for example,
3388  * have duplicated keys.  odp_flow_key_to_flow() will detect those errors. */
3389 int
3390 odp_flow_from_string(const char *s, const struct simap *port_names,
3391                      struct ofpbuf *key, struct ofpbuf *mask)
3392 {
3393     const size_t old_size = key->size;
3394     for (;;) {
3395         int retval;
3396
3397         s += strspn(s, delimiters);
3398         if (!*s) {
3399             return 0;
3400         }
3401
3402         retval = parse_odp_key_mask_attr(s, port_names, key, mask);
3403         if (retval < 0) {
3404             key->size = old_size;
3405             return -retval;
3406         }
3407         s += retval;
3408     }
3409
3410     return 0;
3411 }
3412
3413 static uint8_t
3414 ovs_to_odp_frag(uint8_t nw_frag, bool is_mask)
3415 {
3416     if (is_mask) {
3417         /* Netlink interface 'enum ovs_frag_type' is an 8-bit enumeration type,
3418          * not a set of flags or bitfields. Hence, if the struct flow nw_frag
3419          * mask, which is a set of bits, has the FLOW_NW_FRAG_ANY as zero, we
3420          * must use a zero mask for the netlink frag field, and all ones mask
3421          * otherwise. */
3422         return (nw_frag & FLOW_NW_FRAG_ANY) ? UINT8_MAX : 0;
3423     }
3424     return !(nw_frag & FLOW_NW_FRAG_ANY) ? OVS_FRAG_TYPE_NONE
3425         : nw_frag & FLOW_NW_FRAG_LATER ? OVS_FRAG_TYPE_LATER
3426         : OVS_FRAG_TYPE_FIRST;
3427 }
3428
3429 static void get_ethernet_key(const struct flow *, struct ovs_key_ethernet *);
3430 static void put_ethernet_key(const struct ovs_key_ethernet *, struct flow *);
3431 static void get_ipv4_key(const struct flow *, struct ovs_key_ipv4 *,
3432                          bool is_mask);
3433 static void put_ipv4_key(const struct ovs_key_ipv4 *, struct flow *,
3434                          bool is_mask);
3435 static void get_ipv6_key(const struct flow *, struct ovs_key_ipv6 *,
3436                          bool is_mask);
3437 static void put_ipv6_key(const struct ovs_key_ipv6 *, struct flow *,
3438                          bool is_mask);
3439 static void get_arp_key(const struct flow *, struct ovs_key_arp *);
3440 static void put_arp_key(const struct ovs_key_arp *, struct flow *);
3441 static void get_nd_key(const struct flow *, struct ovs_key_nd *);
3442 static void put_nd_key(const struct ovs_key_nd *, struct flow *);
3443
3444 /* These share the same layout. */
3445 union ovs_key_tp {
3446     struct ovs_key_tcp tcp;
3447     struct ovs_key_udp udp;
3448     struct ovs_key_sctp sctp;
3449 };
3450
3451 static void get_tp_key(const struct flow *, union ovs_key_tp *);
3452 static void put_tp_key(const union ovs_key_tp *, struct flow *);
3453
3454 static void
3455 odp_flow_key_from_flow__(struct ofpbuf *buf, const struct flow *flow,
3456                          const struct flow *mask, odp_port_t odp_in_port,
3457                          size_t max_mpls_depth, bool recirc, bool export_mask)
3458 {
3459     struct ovs_key_ethernet *eth_key;
3460     size_t encap;
3461     const struct flow *data = export_mask ? mask : flow;
3462
3463     nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, data->skb_priority);
3464
3465     if (flow->tunnel.ip_dst || export_mask) {
3466         tun_key_to_attr(buf, &data->tunnel);
3467     }
3468
3469     nl_msg_put_u32(buf, OVS_KEY_ATTR_SKB_MARK, data->pkt_mark);
3470
3471     if (recirc) {
3472         nl_msg_put_u32(buf, OVS_KEY_ATTR_RECIRC_ID, data->recirc_id);
3473         nl_msg_put_u32(buf, OVS_KEY_ATTR_DP_HASH, data->dp_hash);
3474     }
3475
3476     /* Add an ingress port attribute if this is a mask or 'odp_in_port'
3477      * is not the magical value "ODPP_NONE". */
3478     if (export_mask || odp_in_port != ODPP_NONE) {
3479         nl_msg_put_odp_port(buf, OVS_KEY_ATTR_IN_PORT, odp_in_port);
3480     }
3481
3482     eth_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ETHERNET,
3483                                        sizeof *eth_key);
3484     get_ethernet_key(data, eth_key);
3485
3486     if (flow->vlan_tci != htons(0) || flow->dl_type == htons(ETH_TYPE_VLAN)) {
3487         if (export_mask) {
3488             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, OVS_BE16_MAX);
3489         } else {
3490             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, htons(ETH_TYPE_VLAN));
3491         }
3492         nl_msg_put_be16(buf, OVS_KEY_ATTR_VLAN, data->vlan_tci);
3493         encap = nl_msg_start_nested(buf, OVS_KEY_ATTR_ENCAP);
3494         if (flow->vlan_tci == htons(0)) {
3495             goto unencap;
3496         }
3497     } else {
3498         encap = 0;
3499     }
3500
3501     if (ntohs(flow->dl_type) < ETH_TYPE_MIN) {
3502         /* For backwards compatibility with kernels that don't support
3503          * wildcarding, the following convention is used to encode the
3504          * OVS_KEY_ATTR_ETHERTYPE for key and mask:
3505          *
3506          *   key      mask    matches
3507          * -------- --------  -------
3508          *  >0x5ff   0xffff   Specified Ethernet II Ethertype.
3509          *  >0x5ff      0     Any Ethernet II or non-Ethernet II frame.
3510          *  <none>   0xffff   Any non-Ethernet II frame (except valid
3511          *                    802.3 SNAP packet with valid eth_type).
3512          */
3513         if (export_mask) {
3514             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, OVS_BE16_MAX);
3515         }
3516         goto unencap;
3517     }
3518
3519     nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, data->dl_type);
3520
3521     if (flow->dl_type == htons(ETH_TYPE_IP)) {
3522         struct ovs_key_ipv4 *ipv4_key;
3523
3524         ipv4_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV4,
3525                                             sizeof *ipv4_key);
3526         get_ipv4_key(data, ipv4_key, export_mask);
3527     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
3528         struct ovs_key_ipv6 *ipv6_key;
3529
3530         ipv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV6,
3531                                             sizeof *ipv6_key);
3532         get_ipv6_key(data, ipv6_key, export_mask);
3533     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
3534                flow->dl_type == htons(ETH_TYPE_RARP)) {
3535         struct ovs_key_arp *arp_key;
3536
3537         arp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ARP,
3538                                            sizeof *arp_key);
3539         get_arp_key(data, arp_key);
3540     } else if (eth_type_mpls(flow->dl_type)) {
3541         struct ovs_key_mpls *mpls_key;
3542         int i, n;
3543
3544         n = flow_count_mpls_labels(flow, NULL);
3545         n = MIN(n, max_mpls_depth);
3546         mpls_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_MPLS,
3547                                             n * sizeof *mpls_key);
3548         for (i = 0; i < n; i++) {
3549             mpls_key[i].mpls_lse = data->mpls_lse[i];
3550         }
3551     }
3552
3553     if (is_ip_any(flow) && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3554         if (flow->nw_proto == IPPROTO_TCP) {
3555             union ovs_key_tp *tcp_key;
3556
3557             tcp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_TCP,
3558                                                sizeof *tcp_key);
3559             get_tp_key(data, tcp_key);
3560             if (data->tcp_flags) {
3561                 nl_msg_put_be16(buf, OVS_KEY_ATTR_TCP_FLAGS, data->tcp_flags);
3562             }
3563         } else if (flow->nw_proto == IPPROTO_UDP) {
3564             union ovs_key_tp *udp_key;
3565
3566             udp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_UDP,
3567                                                sizeof *udp_key);
3568             get_tp_key(data, udp_key);
3569         } else if (flow->nw_proto == IPPROTO_SCTP) {
3570             union ovs_key_tp *sctp_key;
3571
3572             sctp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_SCTP,
3573                                                sizeof *sctp_key);
3574             get_tp_key(data, sctp_key);
3575         } else if (flow->dl_type == htons(ETH_TYPE_IP)
3576                 && flow->nw_proto == IPPROTO_ICMP) {
3577             struct ovs_key_icmp *icmp_key;
3578
3579             icmp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMP,
3580                                                 sizeof *icmp_key);
3581             icmp_key->icmp_type = ntohs(data->tp_src);
3582             icmp_key->icmp_code = ntohs(data->tp_dst);
3583         } else if (flow->dl_type == htons(ETH_TYPE_IPV6)
3584                 && flow->nw_proto == IPPROTO_ICMPV6) {
3585             struct ovs_key_icmpv6 *icmpv6_key;
3586
3587             icmpv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMPV6,
3588                                                   sizeof *icmpv6_key);
3589             icmpv6_key->icmpv6_type = ntohs(data->tp_src);
3590             icmpv6_key->icmpv6_code = ntohs(data->tp_dst);
3591
3592             if (flow->tp_dst == htons(0)
3593                 && (flow->tp_src == htons(ND_NEIGHBOR_SOLICIT)
3594                     || flow->tp_src == htons(ND_NEIGHBOR_ADVERT))
3595                 && (!export_mask || (data->tp_src == htons(0xffff)
3596                                      && data->tp_dst == htons(0xffff)))) {
3597
3598                 struct ovs_key_nd *nd_key;
3599
3600                 nd_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ND,
3601                                                     sizeof *nd_key);
3602                 memcpy(nd_key->nd_target, &data->nd_target,
3603                         sizeof nd_key->nd_target);
3604                 memcpy(nd_key->nd_sll, data->arp_sha, ETH_ADDR_LEN);
3605                 memcpy(nd_key->nd_tll, data->arp_tha, ETH_ADDR_LEN);
3606             }
3607         }
3608     }
3609
3610 unencap:
3611     if (encap) {
3612         nl_msg_end_nested(buf, encap);
3613     }
3614 }
3615
3616 /* Appends a representation of 'flow' as OVS_KEY_ATTR_* attributes to 'buf'.
3617  * 'flow->in_port' is ignored (since it is likely to be an OpenFlow port
3618  * number rather than a datapath port number).  Instead, if 'odp_in_port'
3619  * is anything other than ODPP_NONE, it is included in 'buf' as the input
3620  * port.
3621  *
3622  * 'buf' must have at least ODPUTIL_FLOW_KEY_BYTES bytes of space, or be
3623  * capable of being expanded to allow for that much space.
3624  *
3625  * 'recirc' indicates support for recirculation fields. If this is true, then
3626  * these fields will always be serialised. */
3627 void
3628 odp_flow_key_from_flow(struct ofpbuf *buf, const struct flow *flow,
3629                        const struct flow *mask, odp_port_t odp_in_port,
3630                        bool recirc)
3631 {
3632     odp_flow_key_from_flow__(buf, flow, mask, odp_in_port, SIZE_MAX, recirc,
3633                              false);
3634 }
3635
3636 /* Appends a representation of 'mask' as OVS_KEY_ATTR_* attributes to
3637  * 'buf'.  'flow' is used as a template to determine how to interpret
3638  * 'mask'.  For example, the 'dl_type' of 'mask' describes the mask, but
3639  * it doesn't indicate whether the other fields should be interpreted as
3640  * ARP, IPv4, IPv6, etc.
3641  *
3642  * 'buf' must have at least ODPUTIL_FLOW_KEY_BYTES bytes of space, or be
3643  * capable of being expanded to allow for that much space.
3644  *
3645  * 'recirc' indicates support for recirculation fields. If this is true, then
3646  * these fields will always be serialised. */
3647 void
3648 odp_flow_key_from_mask(struct ofpbuf *buf, const struct flow *mask,
3649                        const struct flow *flow, uint32_t odp_in_port_mask,
3650                        size_t max_mpls_depth, bool recirc)
3651 {
3652     odp_flow_key_from_flow__(buf, flow, mask, u32_to_odp(odp_in_port_mask),
3653                              max_mpls_depth, recirc, true);
3654 }
3655
3656 /* Generate ODP flow key from the given packet metadata */
3657 void
3658 odp_key_from_pkt_metadata(struct ofpbuf *buf, const struct pkt_metadata *md)
3659 {
3660     nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, md->skb_priority);
3661
3662     if (md->tunnel.ip_dst) {
3663         tun_key_to_attr(buf, &md->tunnel);
3664     }
3665
3666     nl_msg_put_u32(buf, OVS_KEY_ATTR_SKB_MARK, md->pkt_mark);
3667
3668     /* Add an ingress port attribute if 'odp_in_port' is not the magical
3669      * value "ODPP_NONE". */
3670     if (md->in_port.odp_port != ODPP_NONE) {
3671         nl_msg_put_odp_port(buf, OVS_KEY_ATTR_IN_PORT, md->in_port.odp_port);
3672     }
3673 }
3674
3675 /* Generate packet metadata from the given ODP flow key. */
3676 void
3677 odp_key_to_pkt_metadata(const struct nlattr *key, size_t key_len,
3678                         struct pkt_metadata *md)
3679 {
3680     const struct nlattr *nla;
3681     size_t left;
3682     uint32_t wanted_attrs = 1u << OVS_KEY_ATTR_PRIORITY |
3683         1u << OVS_KEY_ATTR_SKB_MARK | 1u << OVS_KEY_ATTR_TUNNEL |
3684         1u << OVS_KEY_ATTR_IN_PORT;
3685
3686     *md = PKT_METADATA_INITIALIZER(ODPP_NONE);
3687
3688     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
3689         uint16_t type = nl_attr_type(nla);
3690         size_t len = nl_attr_get_size(nla);
3691         int expected_len = odp_key_attr_len(ovs_flow_key_attr_lens,
3692                                             OVS_KEY_ATTR_MAX, type);
3693
3694         if (len != expected_len && expected_len >= 0) {
3695             continue;
3696         }
3697
3698         switch (type) {
3699         case OVS_KEY_ATTR_RECIRC_ID:
3700             md->recirc_id = nl_attr_get_u32(nla);
3701             wanted_attrs &= ~(1u << OVS_KEY_ATTR_RECIRC_ID);
3702             break;
3703         case OVS_KEY_ATTR_DP_HASH:
3704             md->dp_hash = nl_attr_get_u32(nla);
3705             wanted_attrs &= ~(1u << OVS_KEY_ATTR_DP_HASH);
3706             break;
3707         case OVS_KEY_ATTR_PRIORITY:
3708             md->skb_priority = nl_attr_get_u32(nla);
3709             wanted_attrs &= ~(1u << OVS_KEY_ATTR_PRIORITY);
3710             break;
3711         case OVS_KEY_ATTR_SKB_MARK:
3712             md->pkt_mark = nl_attr_get_u32(nla);
3713             wanted_attrs &= ~(1u << OVS_KEY_ATTR_SKB_MARK);
3714             break;
3715         case OVS_KEY_ATTR_TUNNEL: {
3716             enum odp_key_fitness res;
3717
3718             res = odp_tun_key_from_attr(nla, &md->tunnel);
3719             if (res == ODP_FIT_ERROR) {
3720                 memset(&md->tunnel, 0, sizeof md->tunnel);
3721             } else if (res == ODP_FIT_PERFECT) {
3722                 wanted_attrs &= ~(1u << OVS_KEY_ATTR_TUNNEL);
3723             }
3724             break;
3725         }
3726         case OVS_KEY_ATTR_IN_PORT:
3727             md->in_port.odp_port = nl_attr_get_odp_port(nla);
3728             wanted_attrs &= ~(1u << OVS_KEY_ATTR_IN_PORT);
3729             break;
3730         default:
3731             break;
3732         }
3733
3734         if (!wanted_attrs) {
3735             return; /* Have everything. */
3736         }
3737     }
3738 }
3739
3740 uint32_t
3741 odp_flow_key_hash(const struct nlattr *key, size_t key_len)
3742 {
3743     BUILD_ASSERT_DECL(!(NLA_ALIGNTO % sizeof(uint32_t)));
3744     return hash_words(ALIGNED_CAST(const uint32_t *, key),
3745                       key_len / sizeof(uint32_t), 0);
3746 }
3747
3748 static void
3749 log_odp_key_attributes(struct vlog_rate_limit *rl, const char *title,
3750                        uint64_t attrs, int out_of_range_attr,
3751                        const struct nlattr *key, size_t key_len)
3752 {
3753     struct ds s;
3754     int i;
3755
3756     if (VLOG_DROP_DBG(rl)) {
3757         return;
3758     }
3759
3760     ds_init(&s);
3761     for (i = 0; i < 64; i++) {
3762         if (attrs & (UINT64_C(1) << i)) {
3763             char namebuf[OVS_KEY_ATTR_BUFSIZE];
3764
3765             ds_put_format(&s, " %s",
3766                           ovs_key_attr_to_string(i, namebuf, sizeof namebuf));
3767         }
3768     }
3769     if (out_of_range_attr) {
3770         ds_put_format(&s, " %d (and possibly others)", out_of_range_attr);
3771     }
3772
3773     ds_put_cstr(&s, ": ");
3774     odp_flow_key_format(key, key_len, &s);
3775
3776     VLOG_DBG("%s:%s", title, ds_cstr(&s));
3777     ds_destroy(&s);
3778 }
3779
3780 static uint8_t
3781 odp_to_ovs_frag(uint8_t odp_frag, bool is_mask)
3782 {
3783     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3784
3785     if (is_mask) {
3786         return odp_frag ? FLOW_NW_FRAG_MASK : 0;
3787     }
3788
3789     if (odp_frag > OVS_FRAG_TYPE_LATER) {
3790         VLOG_ERR_RL(&rl, "invalid frag %"PRIu8" in flow key", odp_frag);
3791         return 0xff; /* Error. */
3792     }
3793
3794     return (odp_frag == OVS_FRAG_TYPE_NONE) ? 0
3795         : (odp_frag == OVS_FRAG_TYPE_FIRST) ? FLOW_NW_FRAG_ANY
3796         :  FLOW_NW_FRAG_ANY | FLOW_NW_FRAG_LATER;
3797 }
3798
3799 static bool
3800 parse_flow_nlattrs(const struct nlattr *key, size_t key_len,
3801                    const struct nlattr *attrs[], uint64_t *present_attrsp,
3802                    int *out_of_range_attrp)
3803 {
3804     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3805     const struct nlattr *nla;
3806     uint64_t present_attrs;
3807     size_t left;
3808
3809     BUILD_ASSERT(OVS_KEY_ATTR_MAX < CHAR_BIT * sizeof present_attrs);
3810     present_attrs = 0;
3811     *out_of_range_attrp = 0;
3812     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
3813         uint16_t type = nl_attr_type(nla);
3814         size_t len = nl_attr_get_size(nla);
3815         int expected_len = odp_key_attr_len(ovs_flow_key_attr_lens,
3816                                             OVS_KEY_ATTR_MAX, type);
3817
3818         if (len != expected_len && expected_len >= 0) {
3819             char namebuf[OVS_KEY_ATTR_BUFSIZE];
3820
3821             VLOG_ERR_RL(&rl, "attribute %s has length %"PRIuSIZE" but should have "
3822                         "length %d", ovs_key_attr_to_string(type, namebuf,
3823                                                             sizeof namebuf),
3824                         len, expected_len);
3825             return false;
3826         }
3827
3828         if (type > OVS_KEY_ATTR_MAX) {
3829             *out_of_range_attrp = type;
3830         } else {
3831             if (present_attrs & (UINT64_C(1) << type)) {
3832                 char namebuf[OVS_KEY_ATTR_BUFSIZE];
3833
3834                 VLOG_ERR_RL(&rl, "duplicate %s attribute in flow key",
3835                             ovs_key_attr_to_string(type,
3836                                                    namebuf, sizeof namebuf));
3837                 return false;
3838             }
3839
3840             present_attrs |= UINT64_C(1) << type;
3841             attrs[type] = nla;
3842         }
3843     }
3844     if (left) {
3845         VLOG_ERR_RL(&rl, "trailing garbage in flow key");
3846         return false;
3847     }
3848
3849     *present_attrsp = present_attrs;
3850     return true;
3851 }
3852
3853 static enum odp_key_fitness
3854 check_expectations(uint64_t present_attrs, int out_of_range_attr,
3855                    uint64_t expected_attrs,
3856                    const struct nlattr *key, size_t key_len)
3857 {
3858     uint64_t missing_attrs;
3859     uint64_t extra_attrs;
3860
3861     missing_attrs = expected_attrs & ~present_attrs;
3862     if (missing_attrs) {
3863         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3864         log_odp_key_attributes(&rl, "expected but not present",
3865                                missing_attrs, 0, key, key_len);
3866         return ODP_FIT_TOO_LITTLE;
3867     }
3868
3869     extra_attrs = present_attrs & ~expected_attrs;
3870     if (extra_attrs || out_of_range_attr) {
3871         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3872         log_odp_key_attributes(&rl, "present but not expected",
3873                                extra_attrs, out_of_range_attr, key, key_len);
3874         return ODP_FIT_TOO_MUCH;
3875     }
3876
3877     return ODP_FIT_PERFECT;
3878 }
3879
3880 static bool
3881 parse_ethertype(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
3882                 uint64_t present_attrs, uint64_t *expected_attrs,
3883                 struct flow *flow, const struct flow *src_flow)
3884 {
3885     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3886     bool is_mask = flow != src_flow;
3887
3888     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE)) {
3889         flow->dl_type = nl_attr_get_be16(attrs[OVS_KEY_ATTR_ETHERTYPE]);
3890         if (!is_mask && ntohs(flow->dl_type) < ETH_TYPE_MIN) {
3891             VLOG_ERR_RL(&rl, "invalid Ethertype %"PRIu16" in flow key",
3892                         ntohs(flow->dl_type));
3893             return false;
3894         }
3895         if (is_mask && ntohs(src_flow->dl_type) < ETH_TYPE_MIN &&
3896             flow->dl_type != htons(0xffff)) {
3897             return false;
3898         }
3899         *expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE;
3900     } else {
3901         if (!is_mask) {
3902             flow->dl_type = htons(FLOW_DL_TYPE_NONE);
3903         } else if (ntohs(src_flow->dl_type) < ETH_TYPE_MIN) {
3904             /* See comments in odp_flow_key_from_flow__(). */
3905             VLOG_ERR_RL(&rl, "mask expected for non-Ethernet II frame");
3906             return false;
3907         }
3908     }
3909     return true;
3910 }
3911
3912 static enum odp_key_fitness
3913 parse_l2_5_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
3914                   uint64_t present_attrs, int out_of_range_attr,
3915                   uint64_t expected_attrs, struct flow *flow,
3916                   const struct nlattr *key, size_t key_len,
3917                   const struct flow *src_flow)
3918 {
3919     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3920     bool is_mask = src_flow != flow;
3921     const void *check_start = NULL;
3922     size_t check_len = 0;
3923     enum ovs_key_attr expected_bit = 0xff;
3924
3925     if (eth_type_mpls(src_flow->dl_type)) {
3926         if (!is_mask || present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_MPLS)) {
3927             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_MPLS);
3928         }
3929         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_MPLS)) {
3930             size_t size = nl_attr_get_size(attrs[OVS_KEY_ATTR_MPLS]);
3931             const ovs_be32 *mpls_lse = nl_attr_get(attrs[OVS_KEY_ATTR_MPLS]);
3932             int n = size / sizeof(ovs_be32);
3933             int i;
3934
3935             if (!size || size % sizeof(ovs_be32)) {
3936                 return ODP_FIT_ERROR;
3937             }
3938             if (flow->mpls_lse[0] && flow->dl_type != htons(0xffff)) {
3939                 return ODP_FIT_ERROR;
3940             }
3941
3942             for (i = 0; i < n && i < FLOW_MAX_MPLS_LABELS; i++) {
3943                 flow->mpls_lse[i] = mpls_lse[i];
3944             }
3945             if (n > FLOW_MAX_MPLS_LABELS) {
3946                 return ODP_FIT_TOO_MUCH;
3947             }
3948
3949             if (!is_mask) {
3950                 /* BOS may be set only in the innermost label. */
3951                 for (i = 0; i < n - 1; i++) {
3952                     if (flow->mpls_lse[i] & htonl(MPLS_BOS_MASK)) {
3953                         return ODP_FIT_ERROR;
3954                     }
3955                 }
3956
3957                 /* BOS must be set in the innermost label. */
3958                 if (n < FLOW_MAX_MPLS_LABELS
3959                     && !(flow->mpls_lse[n - 1] & htonl(MPLS_BOS_MASK))) {
3960                     return ODP_FIT_TOO_LITTLE;
3961                 }
3962             }
3963         }
3964
3965         goto done;
3966     } else if (src_flow->dl_type == htons(ETH_TYPE_IP)) {
3967         if (!is_mask) {
3968             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV4;
3969         }
3970         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV4)) {
3971             const struct ovs_key_ipv4 *ipv4_key;
3972
3973             ipv4_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV4]);
3974             put_ipv4_key(ipv4_key, flow, is_mask);
3975             if (flow->nw_frag > FLOW_NW_FRAG_MASK) {
3976                 return ODP_FIT_ERROR;
3977             }
3978             if (is_mask) {
3979                 check_start = ipv4_key;
3980                 check_len = sizeof *ipv4_key;
3981                 expected_bit = OVS_KEY_ATTR_IPV4;
3982             }
3983         }
3984     } else if (src_flow->dl_type == htons(ETH_TYPE_IPV6)) {
3985         if (!is_mask) {
3986             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV6;
3987         }
3988         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV6)) {
3989             const struct ovs_key_ipv6 *ipv6_key;
3990
3991             ipv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV6]);
3992             put_ipv6_key(ipv6_key, flow, is_mask);
3993             if (flow->nw_frag > FLOW_NW_FRAG_MASK) {
3994                 return ODP_FIT_ERROR;
3995             }
3996             if (is_mask) {
3997                 check_start = ipv6_key;
3998                 check_len = sizeof *ipv6_key;
3999                 expected_bit = OVS_KEY_ATTR_IPV6;
4000             }
4001         }
4002     } else if (src_flow->dl_type == htons(ETH_TYPE_ARP) ||
4003                src_flow->dl_type == htons(ETH_TYPE_RARP)) {
4004         if (!is_mask) {
4005             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ARP;
4006         }
4007         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ARP)) {
4008             const struct ovs_key_arp *arp_key;
4009
4010             arp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ARP]);
4011             if (!is_mask && (arp_key->arp_op & htons(0xff00))) {
4012                 VLOG_ERR_RL(&rl, "unsupported ARP opcode %"PRIu16" in flow "
4013                             "key", ntohs(arp_key->arp_op));
4014                 return ODP_FIT_ERROR;
4015             }
4016             put_arp_key(arp_key, flow);
4017             if (is_mask) {
4018                 check_start = arp_key;
4019                 check_len = sizeof *arp_key;
4020                 expected_bit = OVS_KEY_ATTR_ARP;
4021             }
4022         }
4023     } else {
4024         goto done;
4025     }
4026     if (check_len > 0) { /* Happens only when 'is_mask'. */
4027         if (!is_all_zeros(check_start, check_len) &&
4028             flow->dl_type != htons(0xffff)) {
4029             return ODP_FIT_ERROR;
4030         } else {
4031             expected_attrs |= UINT64_C(1) << expected_bit;
4032         }
4033     }
4034
4035     expected_bit = OVS_KEY_ATTR_UNSPEC;
4036     if (src_flow->nw_proto == IPPROTO_TCP
4037         && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
4038             src_flow->dl_type == htons(ETH_TYPE_IPV6))
4039         && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4040         if (!is_mask) {
4041             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP;
4042         }
4043         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP)) {
4044             const union ovs_key_tp *tcp_key;
4045
4046             tcp_key = nl_attr_get(attrs[OVS_KEY_ATTR_TCP]);
4047             put_tp_key(tcp_key, flow);
4048             expected_bit = OVS_KEY_ATTR_TCP;
4049         }
4050         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP_FLAGS)) {
4051             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP_FLAGS;
4052             flow->tcp_flags = nl_attr_get_be16(attrs[OVS_KEY_ATTR_TCP_FLAGS]);
4053         }
4054     } else if (src_flow->nw_proto == IPPROTO_UDP
4055                && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
4056                    src_flow->dl_type == htons(ETH_TYPE_IPV6))
4057                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4058         if (!is_mask) {
4059             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_UDP;
4060         }
4061         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_UDP)) {
4062             const union ovs_key_tp *udp_key;
4063
4064             udp_key = nl_attr_get(attrs[OVS_KEY_ATTR_UDP]);
4065             put_tp_key(udp_key, flow);
4066             expected_bit = OVS_KEY_ATTR_UDP;
4067         }
4068     } else if (src_flow->nw_proto == IPPROTO_SCTP
4069                && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
4070                    src_flow->dl_type == htons(ETH_TYPE_IPV6))
4071                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4072         if (!is_mask) {
4073             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_SCTP;
4074         }
4075         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_SCTP)) {
4076             const union ovs_key_tp *sctp_key;
4077
4078             sctp_key = nl_attr_get(attrs[OVS_KEY_ATTR_SCTP]);
4079             put_tp_key(sctp_key, flow);
4080             expected_bit = OVS_KEY_ATTR_SCTP;
4081         }
4082     } else if (src_flow->nw_proto == IPPROTO_ICMP
4083                && src_flow->dl_type == htons(ETH_TYPE_IP)
4084                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4085         if (!is_mask) {
4086             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMP;
4087         }
4088         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMP)) {
4089             const struct ovs_key_icmp *icmp_key;
4090
4091             icmp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMP]);
4092             flow->tp_src = htons(icmp_key->icmp_type);
4093             flow->tp_dst = htons(icmp_key->icmp_code);
4094             expected_bit = OVS_KEY_ATTR_ICMP;
4095         }
4096     } else if (src_flow->nw_proto == IPPROTO_ICMPV6
4097                && src_flow->dl_type == htons(ETH_TYPE_IPV6)
4098                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4099         if (!is_mask) {
4100             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMPV6;
4101         }
4102         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMPV6)) {
4103             const struct ovs_key_icmpv6 *icmpv6_key;
4104
4105             icmpv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMPV6]);
4106             flow->tp_src = htons(icmpv6_key->icmpv6_type);
4107             flow->tp_dst = htons(icmpv6_key->icmpv6_code);
4108             expected_bit = OVS_KEY_ATTR_ICMPV6;
4109             if (src_flow->tp_dst == htons(0) &&
4110                 (src_flow->tp_src == htons(ND_NEIGHBOR_SOLICIT) ||
4111                  src_flow->tp_src == htons(ND_NEIGHBOR_ADVERT))) {
4112                 if (!is_mask) {
4113                     expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
4114                 }
4115                 if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ND)) {
4116                     const struct ovs_key_nd *nd_key;
4117
4118                     nd_key = nl_attr_get(attrs[OVS_KEY_ATTR_ND]);
4119                     memcpy(&flow->nd_target, nd_key->nd_target,
4120                            sizeof flow->nd_target);
4121                     memcpy(flow->arp_sha, nd_key->nd_sll, ETH_ADDR_LEN);
4122                     memcpy(flow->arp_tha, nd_key->nd_tll, ETH_ADDR_LEN);
4123                     if (is_mask) {
4124                         if (!is_all_zeros(nd_key, sizeof *nd_key) &&
4125                             (flow->tp_src != htons(0xffff) ||
4126                              flow->tp_dst != htons(0xffff))) {
4127                             return ODP_FIT_ERROR;
4128                         } else {
4129                             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
4130                         }
4131                     }
4132                 }
4133             }
4134         }
4135     }
4136     if (is_mask && expected_bit != OVS_KEY_ATTR_UNSPEC) {
4137         if ((flow->tp_src || flow->tp_dst) && flow->nw_proto != 0xff) {
4138             return ODP_FIT_ERROR;
4139         } else {
4140             expected_attrs |= UINT64_C(1) << expected_bit;
4141         }
4142     }
4143
4144 done:
4145     return check_expectations(present_attrs, out_of_range_attr, expected_attrs,
4146                               key, key_len);
4147 }
4148
4149 /* Parse 802.1Q header then encapsulated L3 attributes. */
4150 static enum odp_key_fitness
4151 parse_8021q_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
4152                    uint64_t present_attrs, int out_of_range_attr,
4153                    uint64_t expected_attrs, struct flow *flow,
4154                    const struct nlattr *key, size_t key_len,
4155                    const struct flow *src_flow)
4156 {
4157     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4158     bool is_mask = src_flow != flow;
4159
4160     const struct nlattr *encap
4161         = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)
4162            ? attrs[OVS_KEY_ATTR_ENCAP] : NULL);
4163     enum odp_key_fitness encap_fitness;
4164     enum odp_key_fitness fitness;
4165
4166     /* Calculate fitness of outer attributes. */
4167     if (!is_mask) {
4168         expected_attrs |= ((UINT64_C(1) << OVS_KEY_ATTR_VLAN) |
4169                           (UINT64_C(1) << OVS_KEY_ATTR_ENCAP));
4170     } else {
4171         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)) {
4172             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_VLAN);
4173         }
4174         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)) {
4175             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_ENCAP);
4176         }
4177     }
4178     fitness = check_expectations(present_attrs, out_of_range_attr,
4179                                  expected_attrs, key, key_len);
4180
4181     /* Set vlan_tci.
4182      * Remove the TPID from dl_type since it's not the real Ethertype.  */
4183     flow->dl_type = htons(0);
4184     flow->vlan_tci = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)
4185                       ? nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN])
4186                       : htons(0));
4187     if (!is_mask) {
4188         if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN))) {
4189             return ODP_FIT_TOO_LITTLE;
4190         } else if (flow->vlan_tci == htons(0)) {
4191             /* Corner case for a truncated 802.1Q header. */
4192             if (fitness == ODP_FIT_PERFECT && nl_attr_get_size(encap)) {
4193                 return ODP_FIT_TOO_MUCH;
4194             }
4195             return fitness;
4196         } else if (!(flow->vlan_tci & htons(VLAN_CFI))) {
4197             VLOG_ERR_RL(&rl, "OVS_KEY_ATTR_VLAN 0x%04"PRIx16" is nonzero "
4198                         "but CFI bit is not set", ntohs(flow->vlan_tci));
4199             return ODP_FIT_ERROR;
4200         }
4201     } else {
4202         if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP))) {
4203             return fitness;
4204         }
4205     }
4206
4207     /* Now parse the encapsulated attributes. */
4208     if (!parse_flow_nlattrs(nl_attr_get(encap), nl_attr_get_size(encap),
4209                             attrs, &present_attrs, &out_of_range_attr)) {
4210         return ODP_FIT_ERROR;
4211     }
4212     expected_attrs = 0;
4213
4214     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow, src_flow)) {
4215         return ODP_FIT_ERROR;
4216     }
4217     encap_fitness = parse_l2_5_onward(attrs, present_attrs, out_of_range_attr,
4218                                       expected_attrs, flow, key, key_len,
4219                                       src_flow);
4220
4221     /* The overall fitness is the worse of the outer and inner attributes. */
4222     return MAX(fitness, encap_fitness);
4223 }
4224
4225 static enum odp_key_fitness
4226 odp_flow_key_to_flow__(const struct nlattr *key, size_t key_len,
4227                        struct flow *flow, const struct flow *src_flow)
4228 {
4229     const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1];
4230     uint64_t expected_attrs;
4231     uint64_t present_attrs;
4232     int out_of_range_attr;
4233     bool is_mask = src_flow != flow;
4234
4235     memset(flow, 0, sizeof *flow);
4236
4237     /* Parse attributes. */
4238     if (!parse_flow_nlattrs(key, key_len, attrs, &present_attrs,
4239                             &out_of_range_attr)) {
4240         return ODP_FIT_ERROR;
4241     }
4242     expected_attrs = 0;
4243
4244     /* Metadata. */
4245     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_RECIRC_ID)) {
4246         flow->recirc_id = nl_attr_get_u32(attrs[OVS_KEY_ATTR_RECIRC_ID]);
4247         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_RECIRC_ID;
4248     } else if (is_mask) {
4249         /* Always exact match recirc_id if it is not specified. */
4250         flow->recirc_id = UINT32_MAX;
4251     }
4252
4253     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_DP_HASH)) {
4254         flow->dp_hash = nl_attr_get_u32(attrs[OVS_KEY_ATTR_DP_HASH]);
4255         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_DP_HASH;
4256     }
4257     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_PRIORITY)) {
4258         flow->skb_priority = nl_attr_get_u32(attrs[OVS_KEY_ATTR_PRIORITY]);
4259         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_PRIORITY;
4260     }
4261
4262     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_SKB_MARK)) {
4263         flow->pkt_mark = nl_attr_get_u32(attrs[OVS_KEY_ATTR_SKB_MARK]);
4264         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_SKB_MARK;
4265     }
4266
4267     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TUNNEL)) {
4268         enum odp_key_fitness res;
4269
4270         res = odp_tun_key_from_attr(attrs[OVS_KEY_ATTR_TUNNEL], &flow->tunnel);
4271         if (res == ODP_FIT_ERROR) {
4272             return ODP_FIT_ERROR;
4273         } else if (res == ODP_FIT_PERFECT) {
4274             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TUNNEL;
4275         }
4276     }
4277
4278     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IN_PORT)) {
4279         flow->in_port.odp_port
4280             = nl_attr_get_odp_port(attrs[OVS_KEY_ATTR_IN_PORT]);
4281         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IN_PORT;
4282     } else if (!is_mask) {
4283         flow->in_port.odp_port = ODPP_NONE;
4284     }
4285
4286     /* Ethernet header. */
4287     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERNET)) {
4288         const struct ovs_key_ethernet *eth_key;
4289
4290         eth_key = nl_attr_get(attrs[OVS_KEY_ATTR_ETHERNET]);
4291         put_ethernet_key(eth_key, flow);
4292         if (is_mask) {
4293             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
4294         }
4295     }
4296     if (!is_mask) {
4297         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
4298     }
4299
4300     /* Get Ethertype or 802.1Q TPID or FLOW_DL_TYPE_NONE. */
4301     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow,
4302         src_flow)) {
4303         return ODP_FIT_ERROR;
4304     }
4305
4306     if (is_mask
4307         ? (src_flow->vlan_tci & htons(VLAN_CFI)) != 0
4308         : src_flow->dl_type == htons(ETH_TYPE_VLAN)) {
4309         return parse_8021q_onward(attrs, present_attrs, out_of_range_attr,
4310                                   expected_attrs, flow, key, key_len, src_flow);
4311     }
4312     if (is_mask) {
4313         flow->vlan_tci = htons(0xffff);
4314         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)) {
4315             flow->vlan_tci = nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN]);
4316             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_VLAN);
4317         }
4318     }
4319     return parse_l2_5_onward(attrs, present_attrs, out_of_range_attr,
4320                              expected_attrs, flow, key, key_len, src_flow);
4321 }
4322
4323 /* Converts the 'key_len' bytes of OVS_KEY_ATTR_* attributes in 'key' to a flow
4324  * structure in 'flow'.  Returns an ODP_FIT_* value that indicates how well
4325  * 'key' fits our expectations for what a flow key should contain.
4326  *
4327  * The 'in_port' will be the datapath's understanding of the port.  The
4328  * caller will need to translate with odp_port_to_ofp_port() if the
4329  * OpenFlow port is needed.
4330  *
4331  * This function doesn't take the packet itself as an argument because none of
4332  * the currently understood OVS_KEY_ATTR_* attributes require it.  Currently,
4333  * it is always possible to infer which additional attribute(s) should appear
4334  * by looking at the attributes for lower-level protocols, e.g. if the network
4335  * protocol in OVS_KEY_ATTR_IPV4 or OVS_KEY_ATTR_IPV6 is IPPROTO_TCP then we
4336  * know that a OVS_KEY_ATTR_TCP attribute must appear and that otherwise it
4337  * must be absent. */
4338 enum odp_key_fitness
4339 odp_flow_key_to_flow(const struct nlattr *key, size_t key_len,
4340                      struct flow *flow)
4341 {
4342    return odp_flow_key_to_flow__(key, key_len, flow, flow);
4343 }
4344
4345 /* Converts the 'key_len' bytes of OVS_KEY_ATTR_* attributes in 'key' to a mask
4346  * structure in 'mask'.  'flow' must be a previously translated flow
4347  * corresponding to 'mask'.  Returns an ODP_FIT_* value that indicates how well
4348  * 'key' fits our expectations for what a flow key should contain. */
4349 enum odp_key_fitness
4350 odp_flow_key_to_mask(const struct nlattr *key, size_t key_len,
4351                      struct flow *mask, const struct flow *flow)
4352 {
4353    return odp_flow_key_to_flow__(key, key_len, mask, flow);
4354 }
4355
4356 /* Returns 'fitness' as a string, for use in debug messages. */
4357 const char *
4358 odp_key_fitness_to_string(enum odp_key_fitness fitness)
4359 {
4360     switch (fitness) {
4361     case ODP_FIT_PERFECT:
4362         return "OK";
4363     case ODP_FIT_TOO_MUCH:
4364         return "too_much";
4365     case ODP_FIT_TOO_LITTLE:
4366         return "too_little";
4367     case ODP_FIT_ERROR:
4368         return "error";
4369     default:
4370         return "<unknown>";
4371     }
4372 }
4373
4374 /* Appends an OVS_ACTION_ATTR_USERSPACE action to 'odp_actions' that specifies
4375  * Netlink PID 'pid'.  If 'userdata' is nonnull, adds a userdata attribute
4376  * whose contents are the 'userdata_size' bytes at 'userdata' and returns the
4377  * offset within 'odp_actions' of the start of the cookie.  (If 'userdata' is
4378  * null, then the return value is not meaningful.) */
4379 size_t
4380 odp_put_userspace_action(uint32_t pid,
4381                          const void *userdata, size_t userdata_size,
4382                          odp_port_t tunnel_out_port,
4383                          struct ofpbuf *odp_actions)
4384 {
4385     size_t userdata_ofs;
4386     size_t offset;
4387
4388     offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_USERSPACE);
4389     nl_msg_put_u32(odp_actions, OVS_USERSPACE_ATTR_PID, pid);
4390     if (userdata) {
4391         userdata_ofs = odp_actions->size + NLA_HDRLEN;
4392
4393         /* The OVS kernel module before OVS 1.11 and the upstream Linux kernel
4394          * module before Linux 3.10 required the userdata to be exactly 8 bytes
4395          * long:
4396          *
4397          *   - The kernel rejected shorter userdata with -ERANGE.
4398          *
4399          *   - The kernel silently dropped userdata beyond the first 8 bytes.
4400          *
4401          * Thus, for maximum compatibility, always put at least 8 bytes.  (We
4402          * separately disable features that required more than 8 bytes.) */
4403         memcpy(nl_msg_put_unspec_zero(odp_actions, OVS_USERSPACE_ATTR_USERDATA,
4404                                       MAX(8, userdata_size)),
4405                userdata, userdata_size);
4406     } else {
4407         userdata_ofs = 0;
4408     }
4409     if (tunnel_out_port != ODPP_NONE) {
4410         nl_msg_put_odp_port(odp_actions, OVS_USERSPACE_ATTR_EGRESS_TUN_PORT,
4411                             tunnel_out_port);
4412     }
4413     nl_msg_end_nested(odp_actions, offset);
4414
4415     return userdata_ofs;
4416 }
4417
4418 void
4419 odp_put_tunnel_action(const struct flow_tnl *tunnel,
4420                       struct ofpbuf *odp_actions)
4421 {
4422     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
4423     tun_key_to_attr(odp_actions, tunnel);
4424     nl_msg_end_nested(odp_actions, offset);
4425 }
4426
4427 void
4428 odp_put_tnl_push_action(struct ofpbuf *odp_actions,
4429                         struct ovs_action_push_tnl *data)
4430 {
4431     int size = offsetof(struct ovs_action_push_tnl, header);
4432
4433     size += data->header_len;
4434     nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_TUNNEL_PUSH, data, size);
4435 }
4436
4437 \f
4438 /* The commit_odp_actions() function and its helpers. */
4439
4440 static void
4441 commit_set_action(struct ofpbuf *odp_actions, enum ovs_key_attr key_type,
4442                   const void *key, size_t key_size)
4443 {
4444     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
4445     nl_msg_put_unspec(odp_actions, key_type, key, key_size);
4446     nl_msg_end_nested(odp_actions, offset);
4447 }
4448
4449 /* Masked set actions have a mask following the data within the netlink
4450  * attribute.  The unmasked bits in the data will be cleared as the data
4451  * is copied to the action. */
4452 void
4453 commit_masked_set_action(struct ofpbuf *odp_actions,
4454                          enum ovs_key_attr key_type,
4455                          const void *key_, const void *mask_, size_t key_size)
4456 {
4457     size_t offset = nl_msg_start_nested(odp_actions,
4458                                         OVS_ACTION_ATTR_SET_MASKED);
4459     char *data = nl_msg_put_unspec_uninit(odp_actions, key_type, key_size * 2);
4460     const char *key = key_, *mask = mask_;
4461
4462     memcpy(data + key_size, mask, key_size);
4463     /* Clear unmasked bits while copying. */
4464     while (key_size--) {
4465         *data++ = *key++ & *mask++;
4466     }
4467     nl_msg_end_nested(odp_actions, offset);
4468 }
4469
4470 /* If any of the flow key data that ODP actions can modify are different in
4471  * 'base->tunnel' and 'flow->tunnel', appends a set_tunnel ODP action to
4472  * 'odp_actions' that change the flow tunneling information in key from
4473  * 'base->tunnel' into 'flow->tunnel', and then changes 'base->tunnel' in the
4474  * same way.  In other words, operates the same as commit_odp_actions(), but
4475  * only on tunneling information. */
4476 void
4477 commit_odp_tunnel_action(const struct flow *flow, struct flow *base,
4478                          struct ofpbuf *odp_actions)
4479 {
4480     /* A valid IPV4_TUNNEL must have non-zero ip_dst. */
4481     if (flow->tunnel.ip_dst) {
4482         if (!memcmp(&base->tunnel, &flow->tunnel, sizeof base->tunnel)) {
4483             return;
4484         }
4485         memcpy(&base->tunnel, &flow->tunnel, sizeof base->tunnel);
4486         odp_put_tunnel_action(&base->tunnel, odp_actions);
4487     }
4488 }
4489
4490 static bool
4491 commit(enum ovs_key_attr attr, bool use_masked_set,
4492        const void *key, void *base, void *mask, size_t size,
4493        struct ofpbuf *odp_actions)
4494 {
4495     if (memcmp(key, base, size)) {
4496         bool fully_masked = odp_mask_is_exact(attr, mask, size);
4497
4498         if (use_masked_set && !fully_masked) {
4499             commit_masked_set_action(odp_actions, attr, key, mask, size);
4500         } else {
4501             if (!fully_masked) {
4502                 memset(mask, 0xff, size);
4503             }
4504             commit_set_action(odp_actions, attr, key, size);
4505         }
4506         memcpy(base, key, size);
4507         return true;
4508     } else {
4509         /* Mask bits are set when we have either read or set the corresponding
4510          * values.  Masked bits will be exact-matched, no need to set them
4511          * if the value did not actually change. */
4512         return false;
4513     }
4514 }
4515
4516 static void
4517 get_ethernet_key(const struct flow *flow, struct ovs_key_ethernet *eth)
4518 {
4519     memcpy(eth->eth_src, flow->dl_src, ETH_ADDR_LEN);
4520     memcpy(eth->eth_dst, flow->dl_dst, ETH_ADDR_LEN);
4521 }
4522
4523 static void
4524 put_ethernet_key(const struct ovs_key_ethernet *eth, struct flow *flow)
4525 {
4526     memcpy(flow->dl_src, eth->eth_src, ETH_ADDR_LEN);
4527     memcpy(flow->dl_dst, eth->eth_dst, ETH_ADDR_LEN);
4528 }
4529
4530 static void
4531 commit_set_ether_addr_action(const struct flow *flow, struct flow *base_flow,
4532                              struct ofpbuf *odp_actions,
4533                              struct flow_wildcards *wc,
4534                              bool use_masked)
4535 {
4536     struct ovs_key_ethernet key, base, mask;
4537
4538     get_ethernet_key(flow, &key);
4539     get_ethernet_key(base_flow, &base);
4540     get_ethernet_key(&wc->masks, &mask);
4541
4542     if (commit(OVS_KEY_ATTR_ETHERNET, use_masked,
4543                &key, &base, &mask, sizeof key, odp_actions)) {
4544         put_ethernet_key(&base, base_flow);
4545         put_ethernet_key(&mask, &wc->masks);
4546     }
4547 }
4548
4549 static void
4550 pop_vlan(struct flow *base,
4551          struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4552 {
4553     memset(&wc->masks.vlan_tci, 0xff, sizeof wc->masks.vlan_tci);
4554
4555     if (base->vlan_tci & htons(VLAN_CFI)) {
4556         nl_msg_put_flag(odp_actions, OVS_ACTION_ATTR_POP_VLAN);
4557         base->vlan_tci = 0;
4558     }
4559 }
4560
4561 static void
4562 commit_vlan_action(ovs_be16 vlan_tci, struct flow *base,
4563                    struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4564 {
4565     if (base->vlan_tci == vlan_tci) {
4566         return;
4567     }
4568
4569     pop_vlan(base, odp_actions, wc);
4570     if (vlan_tci & htons(VLAN_CFI)) {
4571         struct ovs_action_push_vlan vlan;
4572
4573         vlan.vlan_tpid = htons(ETH_TYPE_VLAN);
4574         vlan.vlan_tci = vlan_tci;
4575         nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_PUSH_VLAN,
4576                           &vlan, sizeof vlan);
4577     }
4578     base->vlan_tci = vlan_tci;
4579 }
4580
4581 /* Wildcarding already done at action translation time. */
4582 static void
4583 commit_mpls_action(const struct flow *flow, struct flow *base,
4584                    struct ofpbuf *odp_actions)
4585 {
4586     int base_n = flow_count_mpls_labels(base, NULL);
4587     int flow_n = flow_count_mpls_labels(flow, NULL);
4588     int common_n = flow_count_common_mpls_labels(flow, flow_n, base, base_n,
4589                                                  NULL);
4590
4591     while (base_n > common_n) {
4592         if (base_n - 1 == common_n && flow_n > common_n) {
4593             /* If there is only one more LSE in base than there are common
4594              * between base and flow; and flow has at least one more LSE than
4595              * is common then the topmost LSE of base may be updated using
4596              * set */
4597             struct ovs_key_mpls mpls_key;
4598
4599             mpls_key.mpls_lse = flow->mpls_lse[flow_n - base_n];
4600             commit_set_action(odp_actions, OVS_KEY_ATTR_MPLS,
4601                               &mpls_key, sizeof mpls_key);
4602             flow_set_mpls_lse(base, 0, mpls_key.mpls_lse);
4603             common_n++;
4604         } else {
4605             /* Otherwise, if there more LSEs in base than are common between
4606              * base and flow then pop the topmost one. */
4607             ovs_be16 dl_type;
4608             bool popped;
4609
4610             /* If all the LSEs are to be popped and this is not the outermost
4611              * LSE then use ETH_TYPE_MPLS as the ethertype parameter of the
4612              * POP_MPLS action instead of flow->dl_type.
4613              *
4614              * This is because the POP_MPLS action requires its ethertype
4615              * argument to be an MPLS ethernet type but in this case
4616              * flow->dl_type will be a non-MPLS ethernet type.
4617              *
4618              * When the final POP_MPLS action occurs it use flow->dl_type and
4619              * the and the resulting packet will have the desired dl_type. */
4620             if ((!eth_type_mpls(flow->dl_type)) && base_n > 1) {
4621                 dl_type = htons(ETH_TYPE_MPLS);
4622             } else {
4623                 dl_type = flow->dl_type;
4624             }
4625             nl_msg_put_be16(odp_actions, OVS_ACTION_ATTR_POP_MPLS, dl_type);
4626             popped = flow_pop_mpls(base, base_n, flow->dl_type, NULL);
4627             ovs_assert(popped);
4628             base_n--;
4629         }
4630     }
4631
4632     /* If, after the above popping and setting, there are more LSEs in flow
4633      * than base then some LSEs need to be pushed. */
4634     while (base_n < flow_n) {
4635         struct ovs_action_push_mpls *mpls;
4636
4637         mpls = nl_msg_put_unspec_zero(odp_actions,
4638                                       OVS_ACTION_ATTR_PUSH_MPLS,
4639                                       sizeof *mpls);
4640         mpls->mpls_ethertype = flow->dl_type;
4641         mpls->mpls_lse = flow->mpls_lse[flow_n - base_n - 1];
4642         flow_push_mpls(base, base_n, mpls->mpls_ethertype, NULL);
4643         flow_set_mpls_lse(base, 0, mpls->mpls_lse);
4644         base_n++;
4645     }
4646 }
4647
4648 static void
4649 get_ipv4_key(const struct flow *flow, struct ovs_key_ipv4 *ipv4, bool is_mask)
4650 {
4651     ipv4->ipv4_src = flow->nw_src;
4652     ipv4->ipv4_dst = flow->nw_dst;
4653     ipv4->ipv4_proto = flow->nw_proto;
4654     ipv4->ipv4_tos = flow->nw_tos;
4655     ipv4->ipv4_ttl = flow->nw_ttl;
4656     ipv4->ipv4_frag = ovs_to_odp_frag(flow->nw_frag, is_mask);
4657 }
4658
4659 static void
4660 put_ipv4_key(const struct ovs_key_ipv4 *ipv4, struct flow *flow, bool is_mask)
4661 {
4662     flow->nw_src = ipv4->ipv4_src;
4663     flow->nw_dst = ipv4->ipv4_dst;
4664     flow->nw_proto = ipv4->ipv4_proto;
4665     flow->nw_tos = ipv4->ipv4_tos;
4666     flow->nw_ttl = ipv4->ipv4_ttl;
4667     flow->nw_frag = odp_to_ovs_frag(ipv4->ipv4_frag, is_mask);
4668 }
4669
4670 static void
4671 commit_set_ipv4_action(const struct flow *flow, struct flow *base_flow,
4672                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4673                        bool use_masked)
4674 {
4675     struct ovs_key_ipv4 key, mask, base;
4676
4677     /* Check that nw_proto and nw_frag remain unchanged. */
4678     ovs_assert(flow->nw_proto == base_flow->nw_proto &&
4679                flow->nw_frag == base_flow->nw_frag);
4680
4681     get_ipv4_key(flow, &key, false);
4682     get_ipv4_key(base_flow, &base, false);
4683     get_ipv4_key(&wc->masks, &mask, true);
4684     mask.ipv4_proto = 0;        /* Not writeable. */
4685     mask.ipv4_frag = 0;         /* Not writable. */
4686
4687     if (commit(OVS_KEY_ATTR_IPV4, use_masked, &key, &base, &mask, sizeof key,
4688                odp_actions)) {
4689         put_ipv4_key(&base, base_flow, false);
4690         if (mask.ipv4_proto != 0) { /* Mask was changed by commit(). */
4691             put_ipv4_key(&mask, &wc->masks, true);
4692         }
4693    }
4694 }
4695
4696 static void
4697 get_ipv6_key(const struct flow *flow, struct ovs_key_ipv6 *ipv6, bool is_mask)
4698 {
4699     memcpy(ipv6->ipv6_src, &flow->ipv6_src, sizeof ipv6->ipv6_src);
4700     memcpy(ipv6->ipv6_dst, &flow->ipv6_dst, sizeof ipv6->ipv6_dst);
4701     ipv6->ipv6_label = flow->ipv6_label;
4702     ipv6->ipv6_proto = flow->nw_proto;
4703     ipv6->ipv6_tclass = flow->nw_tos;
4704     ipv6->ipv6_hlimit = flow->nw_ttl;
4705     ipv6->ipv6_frag = ovs_to_odp_frag(flow->nw_frag, is_mask);
4706 }
4707
4708 static void
4709 put_ipv6_key(const struct ovs_key_ipv6 *ipv6, struct flow *flow, bool is_mask)
4710 {
4711     memcpy(&flow->ipv6_src, ipv6->ipv6_src, sizeof flow->ipv6_src);
4712     memcpy(&flow->ipv6_dst, ipv6->ipv6_dst, sizeof flow->ipv6_dst);
4713     flow->ipv6_label = ipv6->ipv6_label;
4714     flow->nw_proto = ipv6->ipv6_proto;
4715     flow->nw_tos = ipv6->ipv6_tclass;
4716     flow->nw_ttl = ipv6->ipv6_hlimit;
4717     flow->nw_frag = odp_to_ovs_frag(ipv6->ipv6_frag, is_mask);
4718 }
4719
4720 static void
4721 commit_set_ipv6_action(const struct flow *flow, struct flow *base_flow,
4722                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4723                        bool use_masked)
4724 {
4725     struct ovs_key_ipv6 key, mask, base;
4726
4727     /* Check that nw_proto and nw_frag remain unchanged. */
4728     ovs_assert(flow->nw_proto == base_flow->nw_proto &&
4729                flow->nw_frag == base_flow->nw_frag);
4730
4731     get_ipv6_key(flow, &key, false);
4732     get_ipv6_key(base_flow, &base, false);
4733     get_ipv6_key(&wc->masks, &mask, true);
4734     mask.ipv6_proto = 0;        /* Not writeable. */
4735     mask.ipv6_frag = 0;         /* Not writable. */
4736
4737     if (commit(OVS_KEY_ATTR_IPV6, use_masked, &key, &base, &mask, sizeof key,
4738                odp_actions)) {
4739         put_ipv6_key(&base, base_flow, false);
4740         if (mask.ipv6_proto != 0) { /* Mask was changed by commit(). */
4741             put_ipv6_key(&mask, &wc->masks, true);
4742         }
4743     }
4744 }
4745
4746 static void
4747 get_arp_key(const struct flow *flow, struct ovs_key_arp *arp)
4748 {
4749     /* ARP key has padding, clear it. */
4750     memset(arp, 0, sizeof *arp);
4751
4752     arp->arp_sip = flow->nw_src;
4753     arp->arp_tip = flow->nw_dst;
4754     arp->arp_op = htons(flow->nw_proto);
4755     memcpy(arp->arp_sha, flow->arp_sha, ETH_ADDR_LEN);
4756     memcpy(arp->arp_tha, flow->arp_tha, ETH_ADDR_LEN);
4757 }
4758
4759 static void
4760 put_arp_key(const struct ovs_key_arp *arp, struct flow *flow)
4761 {
4762     flow->nw_src = arp->arp_sip;
4763     flow->nw_dst = arp->arp_tip;
4764     flow->nw_proto = ntohs(arp->arp_op);
4765     memcpy(flow->arp_sha, arp->arp_sha, ETH_ADDR_LEN);
4766     memcpy(flow->arp_tha, arp->arp_tha, ETH_ADDR_LEN);
4767 }
4768
4769 static enum slow_path_reason
4770 commit_set_arp_action(const struct flow *flow, struct flow *base_flow,
4771                       struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4772 {
4773     struct ovs_key_arp key, mask, base;
4774
4775     get_arp_key(flow, &key);
4776     get_arp_key(base_flow, &base);
4777     get_arp_key(&wc->masks, &mask);
4778
4779     if (commit(OVS_KEY_ATTR_ARP, true, &key, &base, &mask, sizeof key,
4780                odp_actions)) {
4781         put_arp_key(&base, base_flow);
4782         put_arp_key(&mask, &wc->masks);
4783         return SLOW_ACTION;
4784     }
4785     return 0;
4786 }
4787
4788 static void
4789 get_nd_key(const struct flow *flow, struct ovs_key_nd *nd)
4790 {
4791     memcpy(nd->nd_target, &flow->nd_target, sizeof flow->nd_target);
4792     /* nd_sll and nd_tll are stored in arp_sha and arp_tha, respectively */
4793     memcpy(nd->nd_sll, flow->arp_sha, ETH_ADDR_LEN);
4794     memcpy(nd->nd_tll, flow->arp_tha, ETH_ADDR_LEN);
4795 }
4796
4797 static void
4798 put_nd_key(const struct ovs_key_nd *nd, struct flow *flow)
4799 {
4800     memcpy(&flow->nd_target, &flow->nd_target, sizeof flow->nd_target);
4801     /* nd_sll and nd_tll are stored in arp_sha and arp_tha, respectively */
4802     memcpy(flow->arp_sha, nd->nd_sll, ETH_ADDR_LEN);
4803     memcpy(flow->arp_tha, nd->nd_tll, ETH_ADDR_LEN);
4804 }
4805
4806 static enum slow_path_reason
4807 commit_set_nd_action(const struct flow *flow, struct flow *base_flow,
4808                      struct ofpbuf *odp_actions,
4809                      struct flow_wildcards *wc, bool use_masked)
4810 {
4811     struct ovs_key_nd key, mask, base;
4812
4813     get_nd_key(flow, &key);
4814     get_nd_key(base_flow, &base);
4815     get_nd_key(&wc->masks, &mask);
4816
4817     if (commit(OVS_KEY_ATTR_ND, use_masked, &key, &base, &mask, sizeof key,
4818                odp_actions)) {
4819         put_nd_key(&base, base_flow);
4820         put_nd_key(&mask, &wc->masks);
4821         return SLOW_ACTION;
4822     }
4823
4824     return 0;
4825 }
4826
4827 static enum slow_path_reason
4828 commit_set_nw_action(const struct flow *flow, struct flow *base,
4829                      struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4830                      bool use_masked)
4831 {
4832     /* Check if 'flow' really has an L3 header. */
4833     if (!flow->nw_proto) {
4834         return 0;
4835     }
4836
4837     switch (ntohs(base->dl_type)) {
4838     case ETH_TYPE_IP:
4839         commit_set_ipv4_action(flow, base, odp_actions, wc, use_masked);
4840         break;
4841
4842     case ETH_TYPE_IPV6:
4843         commit_set_ipv6_action(flow, base, odp_actions, wc, use_masked);
4844         return commit_set_nd_action(flow, base, odp_actions, wc, use_masked);
4845
4846     case ETH_TYPE_ARP:
4847         return commit_set_arp_action(flow, base, odp_actions, wc);
4848     }
4849
4850     return 0;
4851 }
4852
4853 /* TCP, UDP, and SCTP keys have the same layout. */
4854 BUILD_ASSERT_DECL(sizeof(struct ovs_key_tcp) == sizeof(struct ovs_key_udp) &&
4855                   sizeof(struct ovs_key_tcp) == sizeof(struct ovs_key_sctp));
4856
4857 static void
4858 get_tp_key(const struct flow *flow, union ovs_key_tp *tp)
4859 {
4860     tp->tcp.tcp_src = flow->tp_src;
4861     tp->tcp.tcp_dst = flow->tp_dst;
4862 }
4863
4864 static void
4865 put_tp_key(const union ovs_key_tp *tp, struct flow *flow)
4866 {
4867     flow->tp_src = tp->tcp.tcp_src;
4868     flow->tp_dst = tp->tcp.tcp_dst;
4869 }
4870
4871 static void
4872 commit_set_port_action(const struct flow *flow, struct flow *base_flow,
4873                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4874                        bool use_masked)
4875 {
4876     enum ovs_key_attr key_type;
4877     union ovs_key_tp key, mask, base;
4878
4879     /* Check if 'flow' really has an L3 header. */
4880     if (!flow->nw_proto) {
4881         return;
4882     }
4883
4884     if (!is_ip_any(base_flow)) {
4885         return;
4886     }
4887
4888     if (flow->nw_proto == IPPROTO_TCP) {
4889         key_type = OVS_KEY_ATTR_TCP;
4890     } else if (flow->nw_proto == IPPROTO_UDP) {
4891         key_type = OVS_KEY_ATTR_UDP;
4892     } else if (flow->nw_proto == IPPROTO_SCTP) {
4893         key_type = OVS_KEY_ATTR_SCTP;
4894     } else {
4895         return;
4896     }
4897
4898     get_tp_key(flow, &key);
4899     get_tp_key(base_flow, &base);
4900     get_tp_key(&wc->masks, &mask);
4901
4902     if (commit(key_type, use_masked, &key, &base, &mask, sizeof key,
4903                odp_actions)) {
4904         put_tp_key(&base, base_flow);
4905         put_tp_key(&mask, &wc->masks);
4906     }
4907 }
4908
4909 static void
4910 commit_set_priority_action(const struct flow *flow, struct flow *base_flow,
4911                            struct ofpbuf *odp_actions,
4912                            struct flow_wildcards *wc,
4913                            bool use_masked)
4914 {
4915     uint32_t key, mask, base;
4916
4917     key = flow->skb_priority;
4918     base = base_flow->skb_priority;
4919     mask = wc->masks.skb_priority;
4920
4921     if (commit(OVS_KEY_ATTR_PRIORITY, use_masked, &key, &base, &mask,
4922                sizeof key, odp_actions)) {
4923         base_flow->skb_priority = base;
4924         wc->masks.skb_priority = mask;
4925     }
4926 }
4927
4928 static void
4929 commit_set_pkt_mark_action(const struct flow *flow, struct flow *base_flow,
4930                            struct ofpbuf *odp_actions,
4931                            struct flow_wildcards *wc,
4932                            bool use_masked)
4933 {
4934     uint32_t key, mask, base;
4935
4936     key = flow->pkt_mark;
4937     base = base_flow->pkt_mark;
4938     mask = wc->masks.pkt_mark;
4939
4940     if (commit(OVS_KEY_ATTR_SKB_MARK, use_masked, &key, &base, &mask,
4941                sizeof key, odp_actions)) {
4942         base_flow->pkt_mark = base;
4943         wc->masks.pkt_mark = mask;
4944     }
4945 }
4946
4947 /* If any of the flow key data that ODP actions can modify are different in
4948  * 'base' and 'flow', appends ODP actions to 'odp_actions' that change the flow
4949  * key from 'base' into 'flow', and then changes 'base' the same way.  Does not
4950  * commit set_tunnel actions.  Users should call commit_odp_tunnel_action()
4951  * in addition to this function if needed.  Sets fields in 'wc' that are
4952  * used as part of the action.
4953  *
4954  * Returns a reason to force processing the flow's packets into the userspace
4955  * slow path, if there is one, otherwise 0. */
4956 enum slow_path_reason
4957 commit_odp_actions(const struct flow *flow, struct flow *base,
4958                    struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4959                    bool use_masked)
4960 {
4961     enum slow_path_reason slow;
4962
4963     commit_set_ether_addr_action(flow, base, odp_actions, wc, use_masked);
4964     slow = commit_set_nw_action(flow, base, odp_actions, wc, use_masked);
4965     commit_set_port_action(flow, base, odp_actions, wc, use_masked);
4966     commit_mpls_action(flow, base, odp_actions);
4967     commit_vlan_action(flow->vlan_tci, base, odp_actions, wc);
4968     commit_set_priority_action(flow, base, odp_actions, wc, use_masked);
4969     commit_set_pkt_mark_action(flow, base, odp_actions, wc, use_masked);
4970
4971     return slow;
4972 }