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