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