dpif-netdev: Add functions to modify rxq without reloading pmd threads.
[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 "openvswitch/dynamic-string.h"
33 #include "flow.h"
34 #include "netlink.h"
35 #include "openvswitch/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;
2085
2086     HMAP_FOR_EACH_POP (odp_portno_names, hmap_node, portno_names) {
2087         free(odp_portno_names->name);
2088         free(odp_portno_names);
2089     }
2090 }
2091
2092 /* Format helpers. */
2093
2094 static void
2095 format_eth(struct ds *ds, const char *name, const struct eth_addr key,
2096            const struct eth_addr *mask, bool verbose)
2097 {
2098     bool mask_empty = mask && eth_addr_is_zero(*mask);
2099
2100     if (verbose || !mask_empty) {
2101         bool mask_full = !mask || eth_mask_is_exact(*mask);
2102
2103         if (mask_full) {
2104             ds_put_format(ds, "%s="ETH_ADDR_FMT",", name, ETH_ADDR_ARGS(key));
2105         } else {
2106             ds_put_format(ds, "%s=", name);
2107             eth_format_masked(key, mask, ds);
2108             ds_put_char(ds, ',');
2109         }
2110     }
2111 }
2112
2113 static void
2114 format_be64(struct ds *ds, const char *name, ovs_be64 key,
2115             const ovs_be64 *mask, bool verbose)
2116 {
2117     bool mask_empty = mask && !*mask;
2118
2119     if (verbose || !mask_empty) {
2120         bool mask_full = !mask || *mask == OVS_BE64_MAX;
2121
2122         ds_put_format(ds, "%s=0x%"PRIx64, name, ntohll(key));
2123         if (!mask_full) { /* Partially masked. */
2124             ds_put_format(ds, "/%#"PRIx64, ntohll(*mask));
2125         }
2126         ds_put_char(ds, ',');
2127     }
2128 }
2129
2130 static void
2131 format_ipv4(struct ds *ds, const char *name, ovs_be32 key,
2132             const ovs_be32 *mask, bool verbose)
2133 {
2134     bool mask_empty = mask && !*mask;
2135
2136     if (verbose || !mask_empty) {
2137         bool mask_full = !mask || *mask == OVS_BE32_MAX;
2138
2139         ds_put_format(ds, "%s="IP_FMT, name, IP_ARGS(key));
2140         if (!mask_full) { /* Partially masked. */
2141             ds_put_format(ds, "/"IP_FMT, IP_ARGS(*mask));
2142         }
2143         ds_put_char(ds, ',');
2144     }
2145 }
2146
2147 static void
2148 format_in6_addr(struct ds *ds, const char *name,
2149                 const struct in6_addr *key,
2150                 const struct in6_addr *mask,
2151                 bool verbose)
2152 {
2153     char buf[INET6_ADDRSTRLEN];
2154     bool mask_empty = mask && ipv6_mask_is_any(mask);
2155
2156     if (verbose || !mask_empty) {
2157         bool mask_full = !mask || ipv6_mask_is_exact(mask);
2158
2159         inet_ntop(AF_INET6, key, buf, sizeof buf);
2160         ds_put_format(ds, "%s=%s", name, buf);
2161         if (!mask_full) { /* Partially masked. */
2162             inet_ntop(AF_INET6, mask, buf, sizeof buf);
2163             ds_put_format(ds, "/%s", buf);
2164         }
2165         ds_put_char(ds, ',');
2166     }
2167 }
2168
2169 static void
2170 format_ipv6(struct ds *ds, const char *name, const ovs_be32 key_[4],
2171             const ovs_be32 (*mask_)[4], bool verbose)
2172 {
2173     format_in6_addr(ds, name,
2174                     (const struct in6_addr *)key_,
2175                     mask_ ? (const struct in6_addr *)*mask_ : NULL,
2176                     verbose);
2177 }
2178
2179 static void
2180 format_ipv6_label(struct ds *ds, const char *name, ovs_be32 key,
2181                   const ovs_be32 *mask, bool verbose)
2182 {
2183     bool mask_empty = mask && !*mask;
2184
2185     if (verbose || !mask_empty) {
2186         bool mask_full = !mask
2187             || (*mask & htonl(IPV6_LABEL_MASK)) == htonl(IPV6_LABEL_MASK);
2188
2189         ds_put_format(ds, "%s=%#"PRIx32, name, ntohl(key));
2190         if (!mask_full) { /* Partially masked. */
2191             ds_put_format(ds, "/%#"PRIx32, ntohl(*mask));
2192         }
2193         ds_put_char(ds, ',');
2194     }
2195 }
2196
2197 static void
2198 format_u8x(struct ds *ds, const char *name, uint8_t key,
2199            const uint8_t *mask, bool verbose)
2200 {
2201     bool mask_empty = mask && !*mask;
2202
2203     if (verbose || !mask_empty) {
2204         bool mask_full = !mask || *mask == UINT8_MAX;
2205
2206         ds_put_format(ds, "%s=%#"PRIx8, name, key);
2207         if (!mask_full) { /* Partially masked. */
2208             ds_put_format(ds, "/%#"PRIx8, *mask);
2209         }
2210         ds_put_char(ds, ',');
2211     }
2212 }
2213
2214 static void
2215 format_u8u(struct ds *ds, const char *name, uint8_t key,
2216            const uint8_t *mask, bool verbose)
2217 {
2218     bool mask_empty = mask && !*mask;
2219
2220     if (verbose || !mask_empty) {
2221         bool mask_full = !mask || *mask == UINT8_MAX;
2222
2223         ds_put_format(ds, "%s=%"PRIu8, name, key);
2224         if (!mask_full) { /* Partially masked. */
2225             ds_put_format(ds, "/%#"PRIx8, *mask);
2226         }
2227         ds_put_char(ds, ',');
2228     }
2229 }
2230
2231 static void
2232 format_be16(struct ds *ds, const char *name, ovs_be16 key,
2233             const ovs_be16 *mask, bool verbose)
2234 {
2235     bool mask_empty = mask && !*mask;
2236
2237     if (verbose || !mask_empty) {
2238         bool mask_full = !mask || *mask == OVS_BE16_MAX;
2239
2240         ds_put_format(ds, "%s=%"PRIu16, name, ntohs(key));
2241         if (!mask_full) { /* Partially masked. */
2242             ds_put_format(ds, "/%#"PRIx16, ntohs(*mask));
2243         }
2244         ds_put_char(ds, ',');
2245     }
2246 }
2247
2248 static void
2249 format_be16x(struct ds *ds, const char *name, ovs_be16 key,
2250              const ovs_be16 *mask, bool verbose)
2251 {
2252     bool mask_empty = mask && !*mask;
2253
2254     if (verbose || !mask_empty) {
2255         bool mask_full = !mask || *mask == OVS_BE16_MAX;
2256
2257         ds_put_format(ds, "%s=%#"PRIx16, name, ntohs(key));
2258         if (!mask_full) { /* Partially masked. */
2259             ds_put_format(ds, "/%#"PRIx16, ntohs(*mask));
2260         }
2261         ds_put_char(ds, ',');
2262     }
2263 }
2264
2265 static void
2266 format_tun_flags(struct ds *ds, const char *name, uint16_t key,
2267                  const uint16_t *mask, bool verbose)
2268 {
2269     bool mask_empty = mask && !*mask;
2270
2271     if (verbose || !mask_empty) {
2272         ds_put_cstr(ds, name);
2273         ds_put_char(ds, '(');
2274         if (mask) {
2275             format_flags_masked(ds, NULL, flow_tun_flag_to_string, key,
2276                                 *mask & FLOW_TNL_F_MASK, FLOW_TNL_F_MASK);
2277         } else { /* Fully masked. */
2278             format_flags(ds, flow_tun_flag_to_string, key, '|');
2279         }
2280         ds_put_cstr(ds, "),");
2281     }
2282 }
2283
2284 static bool
2285 check_attr_len(struct ds *ds, const struct nlattr *a, const struct nlattr *ma,
2286                const struct attr_len_tbl tbl[], int max_len, bool need_key)
2287 {
2288     int expected_len;
2289
2290     expected_len = odp_key_attr_len(tbl, max_len, nl_attr_type(a));
2291     if (expected_len != ATTR_LEN_VARIABLE &&
2292         expected_len != ATTR_LEN_NESTED) {
2293
2294         bool bad_key_len = nl_attr_get_size(a) != expected_len;
2295         bool bad_mask_len = ma && nl_attr_get_size(ma) != expected_len;
2296
2297         if (bad_key_len || bad_mask_len) {
2298             if (need_key) {
2299                 ds_put_format(ds, "key%u", nl_attr_type(a));
2300             }
2301             if (bad_key_len) {
2302                 ds_put_format(ds, "(bad key length %"PRIuSIZE", expected %d)(",
2303                               nl_attr_get_size(a), expected_len);
2304             }
2305             format_generic_odp_key(a, ds);
2306             if (ma) {
2307                 ds_put_char(ds, '/');
2308                 if (bad_mask_len) {
2309                     ds_put_format(ds, "(bad mask length %"PRIuSIZE", expected %d)(",
2310                                   nl_attr_get_size(ma), expected_len);
2311                 }
2312                 format_generic_odp_key(ma, ds);
2313             }
2314             ds_put_char(ds, ')');
2315             return false;
2316         }
2317     }
2318
2319     return true;
2320 }
2321
2322 static void
2323 format_unknown_key(struct ds *ds, const struct nlattr *a,
2324                    const struct nlattr *ma)
2325 {
2326     ds_put_format(ds, "key%u(", nl_attr_type(a));
2327     format_generic_odp_key(a, ds);
2328     if (ma && !odp_mask_attr_is_exact(ma)) {
2329         ds_put_char(ds, '/');
2330         format_generic_odp_key(ma, ds);
2331     }
2332     ds_put_cstr(ds, "),");
2333 }
2334
2335 static void
2336 format_odp_tun_vxlan_opt(const struct nlattr *attr,
2337                          const struct nlattr *mask_attr, struct ds *ds,
2338                          bool verbose)
2339 {
2340     unsigned int left;
2341     const struct nlattr *a;
2342     struct ofpbuf ofp;
2343
2344     ofpbuf_init(&ofp, 100);
2345     NL_NESTED_FOR_EACH(a, left, attr) {
2346         uint16_t type = nl_attr_type(a);
2347         const struct nlattr *ma = NULL;
2348
2349         if (mask_attr) {
2350             ma = nl_attr_find__(nl_attr_get(mask_attr),
2351                                 nl_attr_get_size(mask_attr), type);
2352             if (!ma) {
2353                 ma = generate_all_wildcard_mask(ovs_vxlan_ext_attr_lens,
2354                                                 OVS_VXLAN_EXT_MAX,
2355                                                 &ofp, a);
2356             }
2357         }
2358
2359         if (!check_attr_len(ds, a, ma, ovs_vxlan_ext_attr_lens,
2360                             OVS_VXLAN_EXT_MAX, true)) {
2361             continue;
2362         }
2363
2364         switch (type) {
2365         case OVS_VXLAN_EXT_GBP: {
2366             uint32_t key = nl_attr_get_u32(a);
2367             ovs_be16 id, id_mask;
2368             uint8_t flags, flags_mask = 0;
2369
2370             id = htons(key & 0xFFFF);
2371             flags = (key >> 16) & 0xFF;
2372             if (ma) {
2373                 uint32_t mask = nl_attr_get_u32(ma);
2374                 id_mask = htons(mask & 0xFFFF);
2375                 flags_mask = (mask >> 16) & 0xFF;
2376             }
2377
2378             ds_put_cstr(ds, "gbp(");
2379             format_be16(ds, "id", id, ma ? &id_mask : NULL, verbose);
2380             format_u8x(ds, "flags", flags, ma ? &flags_mask : NULL, verbose);
2381             ds_chomp(ds, ',');
2382             ds_put_cstr(ds, "),");
2383             break;
2384         }
2385
2386         default:
2387             format_unknown_key(ds, a, ma);
2388         }
2389         ofpbuf_clear(&ofp);
2390     }
2391
2392     ds_chomp(ds, ',');
2393     ofpbuf_uninit(&ofp);
2394 }
2395
2396 #define MASK(PTR, FIELD) PTR ? &PTR->FIELD : NULL
2397
2398 static void
2399 format_geneve_opts(const struct geneve_opt *opt,
2400                    const struct geneve_opt *mask, int opts_len,
2401                    struct ds *ds, bool verbose)
2402 {
2403     while (opts_len > 0) {
2404         unsigned int len;
2405         uint8_t data_len, data_len_mask;
2406
2407         if (opts_len < sizeof *opt) {
2408             ds_put_format(ds, "opt len %u less than minimum %"PRIuSIZE,
2409                           opts_len, sizeof *opt);
2410             return;
2411         }
2412
2413         data_len = opt->length * 4;
2414         if (mask) {
2415             if (mask->length == 0x1f) {
2416                 data_len_mask = UINT8_MAX;
2417             } else {
2418                 data_len_mask = mask->length;
2419             }
2420         }
2421         len = sizeof *opt + data_len;
2422         if (len > opts_len) {
2423             ds_put_format(ds, "opt len %u greater than remaining %u",
2424                           len, opts_len);
2425             return;
2426         }
2427
2428         ds_put_char(ds, '{');
2429         format_be16x(ds, "class", opt->opt_class, MASK(mask, opt_class),
2430                     verbose);
2431         format_u8x(ds, "type", opt->type, MASK(mask, type), verbose);
2432         format_u8u(ds, "len", data_len, mask ? &data_len_mask : NULL, verbose);
2433         if (data_len &&
2434             (verbose || !mask || !is_all_zeros(mask + 1, data_len))) {
2435             ds_put_hex(ds, opt + 1, data_len);
2436             if (mask && !is_all_ones(mask + 1, data_len)) {
2437                 ds_put_char(ds, '/');
2438                 ds_put_hex(ds, mask + 1, data_len);
2439             }
2440         } else {
2441             ds_chomp(ds, ',');
2442         }
2443         ds_put_char(ds, '}');
2444
2445         opt += len / sizeof(*opt);
2446         if (mask) {
2447             mask += len / sizeof(*opt);
2448         }
2449         opts_len -= len;
2450     };
2451 }
2452
2453 static void
2454 format_odp_tun_geneve(const struct nlattr *attr,
2455                       const struct nlattr *mask_attr, struct ds *ds,
2456                       bool verbose)
2457 {
2458     int opts_len = nl_attr_get_size(attr);
2459     const struct geneve_opt *opt = nl_attr_get(attr);
2460     const struct geneve_opt *mask = mask_attr ?
2461                                     nl_attr_get(mask_attr) : NULL;
2462
2463     if (mask && nl_attr_get_size(attr) != nl_attr_get_size(mask_attr)) {
2464         ds_put_format(ds, "value len %"PRIuSIZE" different from mask len %"PRIuSIZE,
2465                       nl_attr_get_size(attr), nl_attr_get_size(mask_attr));
2466         return;
2467     }
2468
2469     format_geneve_opts(opt, mask, opts_len, ds, verbose);
2470 }
2471
2472 static void
2473 format_odp_tun_attr(const struct nlattr *attr, const struct nlattr *mask_attr,
2474                     struct ds *ds, bool verbose)
2475 {
2476     unsigned int left;
2477     const struct nlattr *a;
2478     uint16_t flags = 0;
2479     uint16_t mask_flags = 0;
2480     struct ofpbuf ofp;
2481
2482     ofpbuf_init(&ofp, 100);
2483     NL_NESTED_FOR_EACH(a, left, attr) {
2484         enum ovs_tunnel_key_attr type = nl_attr_type(a);
2485         const struct nlattr *ma = NULL;
2486
2487         if (mask_attr) {
2488             ma = nl_attr_find__(nl_attr_get(mask_attr),
2489                                 nl_attr_get_size(mask_attr), type);
2490             if (!ma) {
2491                 ma = generate_all_wildcard_mask(ovs_tun_key_attr_lens,
2492                                                 OVS_TUNNEL_KEY_ATTR_MAX,
2493                                                 &ofp, a);
2494             }
2495         }
2496
2497         if (!check_attr_len(ds, a, ma, ovs_tun_key_attr_lens,
2498                             OVS_TUNNEL_KEY_ATTR_MAX, true)) {
2499             continue;
2500         }
2501
2502         switch (type) {
2503         case OVS_TUNNEL_KEY_ATTR_ID:
2504             format_be64(ds, "tun_id", nl_attr_get_be64(a),
2505                         ma ? nl_attr_get(ma) : NULL, verbose);
2506             flags |= FLOW_TNL_F_KEY;
2507             if (ma) {
2508                 mask_flags |= FLOW_TNL_F_KEY;
2509             }
2510             break;
2511         case OVS_TUNNEL_KEY_ATTR_IPV4_SRC:
2512             format_ipv4(ds, "src", nl_attr_get_be32(a),
2513                         ma ? nl_attr_get(ma) : NULL, verbose);
2514             break;
2515         case OVS_TUNNEL_KEY_ATTR_IPV4_DST:
2516             format_ipv4(ds, "dst", nl_attr_get_be32(a),
2517                         ma ? nl_attr_get(ma) : NULL, verbose);
2518             break;
2519         case OVS_TUNNEL_KEY_ATTR_IPV6_SRC: {
2520             struct in6_addr ipv6_src;
2521             ipv6_src = nl_attr_get_in6_addr(a);
2522             format_in6_addr(ds, "ipv6_src", &ipv6_src,
2523                             ma ? nl_attr_get(ma) : NULL, verbose);
2524             break;
2525         }
2526         case OVS_TUNNEL_KEY_ATTR_IPV6_DST: {
2527             struct in6_addr ipv6_dst;
2528             ipv6_dst = nl_attr_get_in6_addr(a);
2529             format_in6_addr(ds, "ipv6_dst", &ipv6_dst,
2530                             ma ? nl_attr_get(ma) : NULL, verbose);
2531             break;
2532         }
2533         case OVS_TUNNEL_KEY_ATTR_TOS:
2534             format_u8x(ds, "tos", nl_attr_get_u8(a),
2535                        ma ? nl_attr_get(ma) : NULL, verbose);
2536             break;
2537         case OVS_TUNNEL_KEY_ATTR_TTL:
2538             format_u8u(ds, "ttl", nl_attr_get_u8(a),
2539                        ma ? nl_attr_get(ma) : NULL, verbose);
2540             break;
2541         case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT:
2542             flags |= FLOW_TNL_F_DONT_FRAGMENT;
2543             break;
2544         case OVS_TUNNEL_KEY_ATTR_CSUM:
2545             flags |= FLOW_TNL_F_CSUM;
2546             break;
2547         case OVS_TUNNEL_KEY_ATTR_TP_SRC:
2548             format_be16(ds, "tp_src", nl_attr_get_be16(a),
2549                         ma ? nl_attr_get(ma) : NULL, verbose);
2550             break;
2551         case OVS_TUNNEL_KEY_ATTR_TP_DST:
2552             format_be16(ds, "tp_dst", nl_attr_get_be16(a),
2553                         ma ? nl_attr_get(ma) : NULL, verbose);
2554             break;
2555         case OVS_TUNNEL_KEY_ATTR_OAM:
2556             flags |= FLOW_TNL_F_OAM;
2557             break;
2558         case OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS:
2559             ds_put_cstr(ds, "vxlan(");
2560             format_odp_tun_vxlan_opt(a, ma, ds, verbose);
2561             ds_put_cstr(ds, "),");
2562             break;
2563         case OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS:
2564             ds_put_cstr(ds, "geneve(");
2565             format_odp_tun_geneve(a, ma, ds, verbose);
2566             ds_put_cstr(ds, "),");
2567             break;
2568         case __OVS_TUNNEL_KEY_ATTR_MAX:
2569         default:
2570             format_unknown_key(ds, a, ma);
2571         }
2572         ofpbuf_clear(&ofp);
2573     }
2574
2575     /* Flags can have a valid mask even if the attribute is not set, so
2576      * we need to collect these separately. */
2577     if (mask_attr) {
2578         NL_NESTED_FOR_EACH(a, left, mask_attr) {
2579             switch (nl_attr_type(a)) {
2580             case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT:
2581                 mask_flags |= FLOW_TNL_F_DONT_FRAGMENT;
2582                 break;
2583             case OVS_TUNNEL_KEY_ATTR_CSUM:
2584                 mask_flags |= FLOW_TNL_F_CSUM;
2585                 break;
2586             case OVS_TUNNEL_KEY_ATTR_OAM:
2587                 mask_flags |= FLOW_TNL_F_OAM;
2588                 break;
2589             }
2590         }
2591     }
2592
2593     format_tun_flags(ds, "flags", flags, mask_attr ? &mask_flags : NULL,
2594                      verbose);
2595     ds_chomp(ds, ',');
2596     ofpbuf_uninit(&ofp);
2597 }
2598
2599 static const char *
2600 odp_ct_state_to_string(uint32_t flag)
2601 {
2602     switch (flag) {
2603     case OVS_CS_F_REPLY_DIR:
2604         return "rpl";
2605     case OVS_CS_F_TRACKED:
2606         return "trk";
2607     case OVS_CS_F_NEW:
2608         return "new";
2609     case OVS_CS_F_ESTABLISHED:
2610         return "est";
2611     case OVS_CS_F_RELATED:
2612         return "rel";
2613     case OVS_CS_F_INVALID:
2614         return "inv";
2615     case OVS_CS_F_SRC_NAT:
2616         return "snat";
2617     case OVS_CS_F_DST_NAT:
2618         return "dnat";
2619     default:
2620         return NULL;
2621     }
2622 }
2623
2624 static void
2625 format_frag(struct ds *ds, const char *name, uint8_t key,
2626             const uint8_t *mask, bool verbose)
2627 {
2628     bool mask_empty = mask && !*mask;
2629
2630     /* ODP frag is an enumeration field; partial masks are not meaningful. */
2631     if (verbose || !mask_empty) {
2632         bool mask_full = !mask || *mask == UINT8_MAX;
2633
2634         if (!mask_full) { /* Partially masked. */
2635             ds_put_format(ds, "error: partial mask not supported for frag (%#"
2636                           PRIx8"),", *mask);
2637         } else {
2638             ds_put_format(ds, "%s=%s,", name, ovs_frag_type_to_string(key));
2639         }
2640     }
2641 }
2642
2643 static bool
2644 mask_empty(const struct nlattr *ma)
2645 {
2646     const void *mask;
2647     size_t n;
2648
2649     if (!ma) {
2650         return true;
2651     }
2652     mask = nl_attr_get(ma);
2653     n = nl_attr_get_size(ma);
2654
2655     return is_all_zeros(mask, n);
2656 }
2657
2658 static void
2659 format_odp_key_attr(const struct nlattr *a, const struct nlattr *ma,
2660                     const struct hmap *portno_names, struct ds *ds,
2661                     bool verbose)
2662 {
2663     enum ovs_key_attr attr = nl_attr_type(a);
2664     char namebuf[OVS_KEY_ATTR_BUFSIZE];
2665     bool is_exact;
2666
2667     is_exact = ma ? odp_mask_attr_is_exact(ma) : true;
2668
2669     ds_put_cstr(ds, ovs_key_attr_to_string(attr, namebuf, sizeof namebuf));
2670
2671     if (!check_attr_len(ds, a, ma, ovs_flow_key_attr_lens,
2672                         OVS_KEY_ATTR_MAX, false)) {
2673         return;
2674     }
2675
2676     ds_put_char(ds, '(');
2677     switch (attr) {
2678     case OVS_KEY_ATTR_ENCAP:
2679         if (ma && nl_attr_get_size(ma) && nl_attr_get_size(a)) {
2680             odp_flow_format(nl_attr_get(a), nl_attr_get_size(a),
2681                             nl_attr_get(ma), nl_attr_get_size(ma), NULL, ds,
2682                             verbose);
2683         } else if (nl_attr_get_size(a)) {
2684             odp_flow_format(nl_attr_get(a), nl_attr_get_size(a), NULL, 0, NULL,
2685                             ds, verbose);
2686         }
2687         break;
2688
2689     case OVS_KEY_ATTR_PRIORITY:
2690     case OVS_KEY_ATTR_SKB_MARK:
2691     case OVS_KEY_ATTR_DP_HASH:
2692     case OVS_KEY_ATTR_RECIRC_ID:
2693         ds_put_format(ds, "%#"PRIx32, nl_attr_get_u32(a));
2694         if (!is_exact) {
2695             ds_put_format(ds, "/%#"PRIx32, nl_attr_get_u32(ma));
2696         }
2697         break;
2698
2699     case OVS_KEY_ATTR_CT_MARK:
2700         if (verbose || !mask_empty(ma)) {
2701             ds_put_format(ds, "%#"PRIx32, nl_attr_get_u32(a));
2702             if (!is_exact) {
2703                 ds_put_format(ds, "/%#"PRIx32, nl_attr_get_u32(ma));
2704             }
2705         }
2706         break;
2707
2708     case OVS_KEY_ATTR_CT_STATE:
2709         if (verbose) {
2710                 ds_put_format(ds, "%#"PRIx32, nl_attr_get_u32(a));
2711                 if (!is_exact) {
2712                     ds_put_format(ds, "/%#"PRIx32,
2713                                   mask_empty(ma) ? 0 : nl_attr_get_u32(ma));
2714                 }
2715         } else if (!is_exact) {
2716             format_flags_masked(ds, NULL, odp_ct_state_to_string,
2717                                 nl_attr_get_u32(a),
2718                                 mask_empty(ma) ? 0 : nl_attr_get_u32(ma),
2719                                 UINT32_MAX);
2720         } else {
2721             format_flags(ds, odp_ct_state_to_string, nl_attr_get_u32(a), '|');
2722         }
2723         break;
2724
2725     case OVS_KEY_ATTR_CT_ZONE:
2726         if (verbose || !mask_empty(ma)) {
2727             ds_put_format(ds, "%#"PRIx16, nl_attr_get_u16(a));
2728             if (!is_exact) {
2729                 ds_put_format(ds, "/%#"PRIx16, nl_attr_get_u16(ma));
2730             }
2731         }
2732         break;
2733
2734     case OVS_KEY_ATTR_CT_LABELS: {
2735         const ovs_u128 *value = nl_attr_get(a);
2736         const ovs_u128 *mask = ma ? nl_attr_get(ma) : NULL;
2737
2738         format_u128(ds, value, mask, verbose);
2739         break;
2740     }
2741
2742     case OVS_KEY_ATTR_TUNNEL:
2743         format_odp_tun_attr(a, ma, ds, verbose);
2744         break;
2745
2746     case OVS_KEY_ATTR_IN_PORT:
2747         if (portno_names && verbose && is_exact) {
2748             char *name = odp_portno_names_get(portno_names,
2749                             u32_to_odp(nl_attr_get_u32(a)));
2750             if (name) {
2751                 ds_put_format(ds, "%s", name);
2752             } else {
2753                 ds_put_format(ds, "%"PRIu32, nl_attr_get_u32(a));
2754             }
2755         } else {
2756             ds_put_format(ds, "%"PRIu32, nl_attr_get_u32(a));
2757             if (!is_exact) {
2758                 ds_put_format(ds, "/%#"PRIx32, nl_attr_get_u32(ma));
2759             }
2760         }
2761         break;
2762
2763     case OVS_KEY_ATTR_ETHERNET: {
2764         const struct ovs_key_ethernet *mask = ma ? nl_attr_get(ma) : NULL;
2765         const struct ovs_key_ethernet *key = nl_attr_get(a);
2766
2767         format_eth(ds, "src", key->eth_src, MASK(mask, eth_src), verbose);
2768         format_eth(ds, "dst", key->eth_dst, MASK(mask, eth_dst), verbose);
2769         ds_chomp(ds, ',');
2770         break;
2771     }
2772     case OVS_KEY_ATTR_VLAN:
2773         format_vlan_tci(ds, nl_attr_get_be16(a),
2774                         ma ? nl_attr_get_be16(ma) : OVS_BE16_MAX, verbose);
2775         break;
2776
2777     case OVS_KEY_ATTR_MPLS: {
2778         const struct ovs_key_mpls *mpls_key = nl_attr_get(a);
2779         const struct ovs_key_mpls *mpls_mask = NULL;
2780         size_t size = nl_attr_get_size(a);
2781
2782         if (!size || size % sizeof *mpls_key) {
2783             ds_put_format(ds, "(bad key length %"PRIuSIZE")", size);
2784             return;
2785         }
2786         if (!is_exact) {
2787             mpls_mask = nl_attr_get(ma);
2788             if (size != nl_attr_get_size(ma)) {
2789                 ds_put_format(ds, "(key length %"PRIuSIZE" != "
2790                               "mask length %"PRIuSIZE")",
2791                               size, nl_attr_get_size(ma));
2792                 return;
2793             }
2794         }
2795         format_mpls(ds, mpls_key, mpls_mask, size / sizeof *mpls_key);
2796         break;
2797     }
2798     case OVS_KEY_ATTR_ETHERTYPE:
2799         ds_put_format(ds, "0x%04"PRIx16, ntohs(nl_attr_get_be16(a)));
2800         if (!is_exact) {
2801             ds_put_format(ds, "/0x%04"PRIx16, ntohs(nl_attr_get_be16(ma)));
2802         }
2803         break;
2804
2805     case OVS_KEY_ATTR_IPV4: {
2806         const struct ovs_key_ipv4 *key = nl_attr_get(a);
2807         const struct ovs_key_ipv4 *mask = ma ? nl_attr_get(ma) : NULL;
2808
2809         format_ipv4(ds, "src", key->ipv4_src, MASK(mask, ipv4_src), verbose);
2810         format_ipv4(ds, "dst", key->ipv4_dst, MASK(mask, ipv4_dst), verbose);
2811         format_u8u(ds, "proto", key->ipv4_proto, MASK(mask, ipv4_proto),
2812                       verbose);
2813         format_u8x(ds, "tos", key->ipv4_tos, MASK(mask, ipv4_tos), verbose);
2814         format_u8u(ds, "ttl", key->ipv4_ttl, MASK(mask, ipv4_ttl), verbose);
2815         format_frag(ds, "frag", key->ipv4_frag, MASK(mask, ipv4_frag),
2816                     verbose);
2817         ds_chomp(ds, ',');
2818         break;
2819     }
2820     case OVS_KEY_ATTR_IPV6: {
2821         const struct ovs_key_ipv6 *key = nl_attr_get(a);
2822         const struct ovs_key_ipv6 *mask = ma ? nl_attr_get(ma) : NULL;
2823
2824         format_ipv6(ds, "src", key->ipv6_src, MASK(mask, ipv6_src), verbose);
2825         format_ipv6(ds, "dst", key->ipv6_dst, MASK(mask, ipv6_dst), verbose);
2826         format_ipv6_label(ds, "label", key->ipv6_label, MASK(mask, ipv6_label),
2827                           verbose);
2828         format_u8u(ds, "proto", key->ipv6_proto, MASK(mask, ipv6_proto),
2829                       verbose);
2830         format_u8x(ds, "tclass", key->ipv6_tclass, MASK(mask, ipv6_tclass),
2831                       verbose);
2832         format_u8u(ds, "hlimit", key->ipv6_hlimit, MASK(mask, ipv6_hlimit),
2833                       verbose);
2834         format_frag(ds, "frag", key->ipv6_frag, MASK(mask, ipv6_frag),
2835                     verbose);
2836         ds_chomp(ds, ',');
2837         break;
2838     }
2839         /* These have the same structure and format. */
2840     case OVS_KEY_ATTR_TCP:
2841     case OVS_KEY_ATTR_UDP:
2842     case OVS_KEY_ATTR_SCTP: {
2843         const struct ovs_key_tcp *key = nl_attr_get(a);
2844         const struct ovs_key_tcp *mask = ma ? nl_attr_get(ma) : NULL;
2845
2846         format_be16(ds, "src", key->tcp_src, MASK(mask, tcp_src), verbose);
2847         format_be16(ds, "dst", key->tcp_dst, MASK(mask, tcp_dst), verbose);
2848         ds_chomp(ds, ',');
2849         break;
2850     }
2851     case OVS_KEY_ATTR_TCP_FLAGS:
2852         if (!is_exact) {
2853             format_flags_masked(ds, NULL, packet_tcp_flag_to_string,
2854                                 ntohs(nl_attr_get_be16(a)),
2855                                 TCP_FLAGS(nl_attr_get_be16(ma)),
2856                                 TCP_FLAGS(OVS_BE16_MAX));
2857         } else {
2858             format_flags(ds, packet_tcp_flag_to_string,
2859                          ntohs(nl_attr_get_be16(a)), '|');
2860         }
2861         break;
2862
2863     case OVS_KEY_ATTR_ICMP: {
2864         const struct ovs_key_icmp *key = nl_attr_get(a);
2865         const struct ovs_key_icmp *mask = ma ? nl_attr_get(ma) : NULL;
2866
2867         format_u8u(ds, "type", key->icmp_type, MASK(mask, icmp_type), verbose);
2868         format_u8u(ds, "code", key->icmp_code, MASK(mask, icmp_code), verbose);
2869         ds_chomp(ds, ',');
2870         break;
2871     }
2872     case OVS_KEY_ATTR_ICMPV6: {
2873         const struct ovs_key_icmpv6 *key = nl_attr_get(a);
2874         const struct ovs_key_icmpv6 *mask = ma ? nl_attr_get(ma) : NULL;
2875
2876         format_u8u(ds, "type", key->icmpv6_type, MASK(mask, icmpv6_type),
2877                    verbose);
2878         format_u8u(ds, "code", key->icmpv6_code, MASK(mask, icmpv6_code),
2879                    verbose);
2880         ds_chomp(ds, ',');
2881         break;
2882     }
2883     case OVS_KEY_ATTR_ARP: {
2884         const struct ovs_key_arp *mask = ma ? nl_attr_get(ma) : NULL;
2885         const struct ovs_key_arp *key = nl_attr_get(a);
2886
2887         format_ipv4(ds, "sip", key->arp_sip, MASK(mask, arp_sip), verbose);
2888         format_ipv4(ds, "tip", key->arp_tip, MASK(mask, arp_tip), verbose);
2889         format_be16(ds, "op", key->arp_op, MASK(mask, arp_op), verbose);
2890         format_eth(ds, "sha", key->arp_sha, MASK(mask, arp_sha), verbose);
2891         format_eth(ds, "tha", key->arp_tha, MASK(mask, arp_tha), verbose);
2892         ds_chomp(ds, ',');
2893         break;
2894     }
2895     case OVS_KEY_ATTR_ND: {
2896         const struct ovs_key_nd *mask = ma ? nl_attr_get(ma) : NULL;
2897         const struct ovs_key_nd *key = nl_attr_get(a);
2898
2899         format_ipv6(ds, "target", key->nd_target, MASK(mask, nd_target),
2900                     verbose);
2901         format_eth(ds, "sll", key->nd_sll, MASK(mask, nd_sll), verbose);
2902         format_eth(ds, "tll", key->nd_tll, MASK(mask, nd_tll), verbose);
2903
2904         ds_chomp(ds, ',');
2905         break;
2906     }
2907     case OVS_KEY_ATTR_UNSPEC:
2908     case __OVS_KEY_ATTR_MAX:
2909     default:
2910         format_generic_odp_key(a, ds);
2911         if (!is_exact) {
2912             ds_put_char(ds, '/');
2913             format_generic_odp_key(ma, ds);
2914         }
2915         break;
2916     }
2917     ds_put_char(ds, ')');
2918 }
2919
2920 static struct nlattr *
2921 generate_all_wildcard_mask(const struct attr_len_tbl tbl[], int max,
2922                            struct ofpbuf *ofp, const struct nlattr *key)
2923 {
2924     const struct nlattr *a;
2925     unsigned int left;
2926     int type = nl_attr_type(key);
2927     int size = nl_attr_get_size(key);
2928
2929     if (odp_key_attr_len(tbl, max, type) != ATTR_LEN_NESTED) {
2930         nl_msg_put_unspec_zero(ofp, type, size);
2931     } else {
2932         size_t nested_mask;
2933
2934         if (tbl[type].next) {
2935             tbl = tbl[type].next;
2936             max = tbl[type].next_max;
2937         }
2938
2939         nested_mask = nl_msg_start_nested(ofp, type);
2940         NL_ATTR_FOR_EACH(a, left, key, nl_attr_get_size(key)) {
2941             generate_all_wildcard_mask(tbl, max, ofp, nl_attr_get(a));
2942         }
2943         nl_msg_end_nested(ofp, nested_mask);
2944     }
2945
2946     return ofp->base;
2947 }
2948
2949 static void
2950 format_u128(struct ds *ds, const ovs_u128 *key, const ovs_u128 *mask,
2951             bool verbose)
2952 {
2953     if (verbose || (mask && !ovs_u128_is_zero(*mask))) {
2954         ovs_be128 value;
2955
2956         value = hton128(*key);
2957         ds_put_hex(ds, &value, sizeof value);
2958         if (mask && !(ovs_u128_is_ones(*mask))) {
2959             value = hton128(*mask);
2960             ds_put_char(ds, '/');
2961             ds_put_hex(ds, &value, sizeof value);
2962         }
2963     }
2964 }
2965
2966 static int
2967 scan_u128(const char *s_, ovs_u128 *value, ovs_u128 *mask)
2968 {
2969     char *s = CONST_CAST(char *, s_);
2970     ovs_be128 be_value;
2971     ovs_be128 be_mask;
2972
2973     if (!parse_int_string(s, (uint8_t *)&be_value, sizeof be_value, &s)) {
2974         *value = ntoh128(be_value);
2975
2976         if (mask) {
2977             int n;
2978
2979             if (ovs_scan(s, "/%n", &n)) {
2980                 int error;
2981
2982                 s += n;
2983                 error = parse_int_string(s, (uint8_t *)&be_mask,
2984                                          sizeof be_mask, &s);
2985                 if (error) {
2986                     return error;
2987                 }
2988                 *mask = ntoh128(be_mask);
2989             } else {
2990                 *mask = OVS_U128_MAX;
2991             }
2992         }
2993         return s - s_;
2994     }
2995
2996     return 0;
2997 }
2998
2999 int
3000 odp_ufid_from_string(const char *s_, ovs_u128 *ufid)
3001 {
3002     const char *s = s_;
3003
3004     if (ovs_scan(s, "ufid:")) {
3005         s += 5;
3006
3007         if (!uuid_from_string_prefix((struct uuid *)ufid, s)) {
3008             return -EINVAL;
3009         }
3010         s += UUID_LEN;
3011
3012         return s - s_;
3013     }
3014
3015     return 0;
3016 }
3017
3018 void
3019 odp_format_ufid(const ovs_u128 *ufid, struct ds *ds)
3020 {
3021     ds_put_format(ds, "ufid:"UUID_FMT, UUID_ARGS((struct uuid *)ufid));
3022 }
3023
3024 /* Appends to 'ds' a string representation of the 'key_len' bytes of
3025  * OVS_KEY_ATTR_* attributes in 'key'. If non-null, additionally formats the
3026  * 'mask_len' bytes of 'mask' which apply to 'key'. If 'portno_names' is
3027  * non-null and 'verbose' is true, translates odp port number to its name. */
3028 void
3029 odp_flow_format(const struct nlattr *key, size_t key_len,
3030                 const struct nlattr *mask, size_t mask_len,
3031                 const struct hmap *portno_names, struct ds *ds, bool verbose)
3032 {
3033     if (key_len) {
3034         const struct nlattr *a;
3035         unsigned int left;
3036         bool has_ethtype_key = false;
3037         const struct nlattr *ma = NULL;
3038         struct ofpbuf ofp;
3039         bool first_field = true;
3040
3041         ofpbuf_init(&ofp, 100);
3042         NL_ATTR_FOR_EACH (a, left, key, key_len) {
3043             bool is_nested_attr;
3044             bool is_wildcard = false;
3045             int attr_type = nl_attr_type(a);
3046
3047             if (attr_type == OVS_KEY_ATTR_ETHERTYPE) {
3048                 has_ethtype_key = true;
3049             }
3050
3051             is_nested_attr = odp_key_attr_len(ovs_flow_key_attr_lens,
3052                                               OVS_KEY_ATTR_MAX, attr_type) ==
3053                              ATTR_LEN_NESTED;
3054
3055             if (mask && mask_len) {
3056                 ma = nl_attr_find__(mask, mask_len, nl_attr_type(a));
3057                 is_wildcard = ma ? odp_mask_attr_is_wildcard(ma) : true;
3058             }
3059
3060             if (verbose || !is_wildcard  || is_nested_attr) {
3061                 if (is_wildcard && !ma) {
3062                     ma = generate_all_wildcard_mask(ovs_flow_key_attr_lens,
3063                                                     OVS_KEY_ATTR_MAX,
3064                                                     &ofp, a);
3065                 }
3066                 if (!first_field) {
3067                     ds_put_char(ds, ',');
3068                 }
3069                 format_odp_key_attr(a, ma, portno_names, ds, verbose);
3070                 first_field = false;
3071             }
3072             ofpbuf_clear(&ofp);
3073         }
3074         ofpbuf_uninit(&ofp);
3075
3076         if (left) {
3077             int i;
3078
3079             if (left == key_len) {
3080                 ds_put_cstr(ds, "<empty>");
3081             }
3082             ds_put_format(ds, ",***%u leftover bytes*** (", left);
3083             for (i = 0; i < left; i++) {
3084                 ds_put_format(ds, "%02x", ((const uint8_t *) a)[i]);
3085             }
3086             ds_put_char(ds, ')');
3087         }
3088         if (!has_ethtype_key) {
3089             ma = nl_attr_find__(mask, mask_len, OVS_KEY_ATTR_ETHERTYPE);
3090             if (ma) {
3091                 ds_put_format(ds, ",eth_type(0/0x%04"PRIx16")",
3092                               ntohs(nl_attr_get_be16(ma)));
3093             }
3094         }
3095     } else {
3096         ds_put_cstr(ds, "<empty>");
3097     }
3098 }
3099
3100 /* Appends to 'ds' a string representation of the 'key_len' bytes of
3101  * OVS_KEY_ATTR_* attributes in 'key'. */
3102 void
3103 odp_flow_key_format(const struct nlattr *key,
3104                     size_t key_len, struct ds *ds)
3105 {
3106     odp_flow_format(key, key_len, NULL, 0, NULL, ds, true);
3107 }
3108
3109 static bool
3110 ovs_frag_type_from_string(const char *s, enum ovs_frag_type *type)
3111 {
3112     if (!strcasecmp(s, "no")) {
3113         *type = OVS_FRAG_TYPE_NONE;
3114     } else if (!strcasecmp(s, "first")) {
3115         *type = OVS_FRAG_TYPE_FIRST;
3116     } else if (!strcasecmp(s, "later")) {
3117         *type = OVS_FRAG_TYPE_LATER;
3118     } else {
3119         return false;
3120     }
3121     return true;
3122 }
3123
3124 /* Parsing. */
3125
3126 static int
3127 scan_eth(const char *s, struct eth_addr *key, struct eth_addr *mask)
3128 {
3129     int n;
3130
3131     if (ovs_scan(s, ETH_ADDR_SCAN_FMT"%n",
3132                  ETH_ADDR_SCAN_ARGS(*key), &n)) {
3133         int len = n;
3134
3135         if (mask) {
3136             if (ovs_scan(s + len, "/"ETH_ADDR_SCAN_FMT"%n",
3137                          ETH_ADDR_SCAN_ARGS(*mask), &n)) {
3138                 len += n;
3139             } else {
3140                 memset(mask, 0xff, sizeof *mask);
3141             }
3142         }
3143         return len;
3144     }
3145     return 0;
3146 }
3147
3148 static int
3149 scan_ipv4(const char *s, ovs_be32 *key, ovs_be32 *mask)
3150 {
3151     int n;
3152
3153     if (ovs_scan(s, IP_SCAN_FMT"%n", IP_SCAN_ARGS(key), &n)) {
3154         int len = n;
3155
3156         if (mask) {
3157             if (ovs_scan(s + len, "/"IP_SCAN_FMT"%n",
3158                          IP_SCAN_ARGS(mask), &n)) {
3159                 len += n;
3160             } else {
3161                 *mask = OVS_BE32_MAX;
3162             }
3163         }
3164         return len;
3165     }
3166     return 0;
3167 }
3168
3169 static int
3170 scan_in6_addr(const char *s, struct in6_addr *key, struct in6_addr *mask)
3171 {
3172     int n;
3173     char ipv6_s[IPV6_SCAN_LEN + 1];
3174
3175     if (ovs_scan(s, IPV6_SCAN_FMT"%n", ipv6_s, &n)
3176         && inet_pton(AF_INET6, ipv6_s, key) == 1) {
3177         int len = n;
3178
3179         if (mask) {
3180             if (ovs_scan(s + len, "/"IPV6_SCAN_FMT"%n", ipv6_s, &n)
3181                 && inet_pton(AF_INET6, ipv6_s, mask) == 1) {
3182                 len += n;
3183             } else {
3184                 memset(mask, 0xff, sizeof *mask);
3185             }
3186         }
3187         return len;
3188     }
3189     return 0;
3190 }
3191
3192 static int
3193 scan_ipv6(const char *s, ovs_be32 (*key)[4], ovs_be32 (*mask)[4])
3194 {
3195     return scan_in6_addr(s, key ? (struct in6_addr *) *key : NULL,
3196                          mask ? (struct in6_addr *) *mask : NULL);
3197 }
3198
3199 static int
3200 scan_ipv6_label(const char *s, ovs_be32 *key, ovs_be32 *mask)
3201 {
3202     int key_, mask_;
3203     int n;
3204
3205     if (ovs_scan(s, "%i%n", &key_, &n)
3206         && (key_ & ~IPV6_LABEL_MASK) == 0) {
3207         int len = n;
3208
3209         *key = htonl(key_);
3210         if (mask) {
3211             if (ovs_scan(s + len, "/%i%n", &mask_, &n)
3212                 && (mask_ & ~IPV6_LABEL_MASK) == 0) {
3213                 len += n;
3214                 *mask = htonl(mask_);
3215             } else {
3216                 *mask = htonl(IPV6_LABEL_MASK);
3217             }
3218         }
3219         return len;
3220     }
3221     return 0;
3222 }
3223
3224 static int
3225 scan_u8(const char *s, uint8_t *key, uint8_t *mask)
3226 {
3227     int n;
3228
3229     if (ovs_scan(s, "%"SCNi8"%n", key, &n)) {
3230         int len = n;
3231
3232         if (mask) {
3233             if (ovs_scan(s + len, "/%"SCNi8"%n", mask, &n)) {
3234                 len += n;
3235             } else {
3236                 *mask = UINT8_MAX;
3237             }
3238         }
3239         return len;
3240     }
3241     return 0;
3242 }
3243
3244 static int
3245 scan_u16(const char *s, uint16_t *key, uint16_t *mask)
3246 {
3247     int n;
3248
3249     if (ovs_scan(s, "%"SCNi16"%n", key, &n)) {
3250         int len = n;
3251
3252         if (mask) {
3253             if (ovs_scan(s + len, "/%"SCNi16"%n", mask, &n)) {
3254                 len += n;
3255             } else {
3256                 *mask = UINT16_MAX;
3257             }
3258         }
3259         return len;
3260     }
3261     return 0;
3262 }
3263
3264 static int
3265 scan_u32(const char *s, uint32_t *key, uint32_t *mask)
3266 {
3267     int n;
3268
3269     if (ovs_scan(s, "%"SCNi32"%n", key, &n)) {
3270         int len = n;
3271
3272         if (mask) {
3273             if (ovs_scan(s + len, "/%"SCNi32"%n", mask, &n)) {
3274                 len += n;
3275             } else {
3276                 *mask = UINT32_MAX;
3277             }
3278         }
3279         return len;
3280     }
3281     return 0;
3282 }
3283
3284 static int
3285 scan_be16(const char *s, ovs_be16 *key, ovs_be16 *mask)
3286 {
3287     uint16_t key_, mask_;
3288     int n;
3289
3290     if (ovs_scan(s, "%"SCNi16"%n", &key_, &n)) {
3291         int len = n;
3292
3293         *key = htons(key_);
3294         if (mask) {
3295             if (ovs_scan(s + len, "/%"SCNi16"%n", &mask_, &n)) {
3296                 len += n;
3297                 *mask = htons(mask_);
3298             } else {
3299                 *mask = OVS_BE16_MAX;
3300             }
3301         }
3302         return len;
3303     }
3304     return 0;
3305 }
3306
3307 static int
3308 scan_be64(const char *s, ovs_be64 *key, ovs_be64 *mask)
3309 {
3310     uint64_t key_, mask_;
3311     int n;
3312
3313     if (ovs_scan(s, "%"SCNi64"%n", &key_, &n)) {
3314         int len = n;
3315
3316         *key = htonll(key_);
3317         if (mask) {
3318             if (ovs_scan(s + len, "/%"SCNi64"%n", &mask_, &n)) {
3319                 len += n;
3320                 *mask = htonll(mask_);
3321             } else {
3322                 *mask = OVS_BE64_MAX;
3323             }
3324         }
3325         return len;
3326     }
3327     return 0;
3328 }
3329
3330 static int
3331 scan_tun_flags(const char *s, uint16_t *key, uint16_t *mask)
3332 {
3333     uint32_t flags, fmask;
3334     int n;
3335
3336     n = parse_odp_flags(s, flow_tun_flag_to_string, &flags,
3337                         FLOW_TNL_F_MASK, mask ? &fmask : NULL);
3338     if (n >= 0 && s[n] == ')') {
3339         *key = flags;
3340         if (mask) {
3341             *mask = fmask;
3342         }
3343         return n + 1;
3344     }
3345     return 0;
3346 }
3347
3348 static int
3349 scan_tcp_flags(const char *s, ovs_be16 *key, ovs_be16 *mask)
3350 {
3351     uint32_t flags, fmask;
3352     int n;
3353
3354     n = parse_odp_flags(s, packet_tcp_flag_to_string, &flags,
3355                         TCP_FLAGS(OVS_BE16_MAX), mask ? &fmask : NULL);
3356     if (n >= 0) {
3357         *key = htons(flags);
3358         if (mask) {
3359             *mask = htons(fmask);
3360         }
3361         return n;
3362     }
3363     return 0;
3364 }
3365
3366 static uint32_t
3367 ovs_to_odp_ct_state(uint8_t state)
3368 {
3369     uint32_t odp = 0;
3370
3371     if (state & CS_NEW) {
3372         odp |= OVS_CS_F_NEW;
3373     }
3374     if (state & CS_ESTABLISHED) {
3375         odp |= OVS_CS_F_ESTABLISHED;
3376     }
3377     if (state & CS_RELATED) {
3378         odp |= OVS_CS_F_RELATED;
3379     }
3380     if (state & CS_INVALID) {
3381         odp |= OVS_CS_F_INVALID;
3382     }
3383     if (state & CS_REPLY_DIR) {
3384         odp |= OVS_CS_F_REPLY_DIR;
3385     }
3386     if (state & CS_TRACKED) {
3387         odp |= OVS_CS_F_TRACKED;
3388     }
3389     if (state & CS_SRC_NAT) {
3390         odp |= OVS_CS_F_SRC_NAT;
3391     }
3392     if (state & CS_DST_NAT) {
3393         odp |= OVS_CS_F_DST_NAT;
3394     }
3395
3396     return odp;
3397 }
3398
3399 static uint8_t
3400 odp_to_ovs_ct_state(uint32_t flags)
3401 {
3402     uint32_t state = 0;
3403
3404     if (flags & OVS_CS_F_NEW) {
3405         state |= CS_NEW;
3406     }
3407     if (flags & OVS_CS_F_ESTABLISHED) {
3408         state |= CS_ESTABLISHED;
3409     }
3410     if (flags & OVS_CS_F_RELATED) {
3411         state |= CS_RELATED;
3412     }
3413     if (flags & OVS_CS_F_INVALID) {
3414         state |= CS_INVALID;
3415     }
3416     if (flags & OVS_CS_F_REPLY_DIR) {
3417         state |= CS_REPLY_DIR;
3418     }
3419     if (flags & OVS_CS_F_TRACKED) {
3420         state |= CS_TRACKED;
3421     }
3422     if (flags & OVS_CS_F_SRC_NAT) {
3423         state |= CS_SRC_NAT;
3424     }
3425     if (flags & OVS_CS_F_DST_NAT) {
3426         state |= CS_DST_NAT;
3427     }
3428
3429     return state;
3430 }
3431
3432 static int
3433 scan_ct_state(const char *s, uint32_t *key, uint32_t *mask)
3434 {
3435     uint32_t flags, fmask;
3436     int n;
3437
3438     n = parse_flags(s, odp_ct_state_to_string, ')', NULL, NULL, &flags,
3439                     ovs_to_odp_ct_state(CS_SUPPORTED_MASK),
3440                     mask ? &fmask : NULL);
3441
3442     if (n >= 0) {
3443         *key = flags;
3444         if (mask) {
3445             *mask = fmask;
3446         }
3447         return n;
3448     }
3449     return 0;
3450 }
3451
3452 static int
3453 scan_frag(const char *s, uint8_t *key, uint8_t *mask)
3454 {
3455     int n;
3456     char frag[8];
3457     enum ovs_frag_type frag_type;
3458
3459     if (ovs_scan(s, "%7[a-z]%n", frag, &n)
3460         && ovs_frag_type_from_string(frag, &frag_type)) {
3461         int len = n;
3462
3463         *key = frag_type;
3464         if (mask) {
3465             *mask = UINT8_MAX;
3466         }
3467         return len;
3468     }
3469     return 0;
3470 }
3471
3472 static int
3473 scan_port(const char *s, uint32_t *key, uint32_t *mask,
3474           const struct simap *port_names)
3475 {
3476     int n;
3477
3478     if (ovs_scan(s, "%"SCNi32"%n", key, &n)) {
3479         int len = n;
3480
3481         if (mask) {
3482             if (ovs_scan(s + len, "/%"SCNi32"%n", mask, &n)) {
3483                 len += n;
3484             } else {
3485                 *mask = UINT32_MAX;
3486             }
3487         }
3488         return len;
3489     } else if (port_names) {
3490         const struct simap_node *node;
3491         int len;
3492
3493         len = strcspn(s, ")");
3494         node = simap_find_len(port_names, s, len);
3495         if (node) {
3496             *key = node->data;
3497
3498             if (mask) {
3499                 *mask = UINT32_MAX;
3500             }
3501             return len;
3502         }
3503     }
3504     return 0;
3505 }
3506
3507 /* Helper for vlan parsing. */
3508 struct ovs_key_vlan__ {
3509     ovs_be16 tci;
3510 };
3511
3512 static bool
3513 set_be16_bf(ovs_be16 *bf, uint8_t bits, uint8_t offset, uint16_t value)
3514 {
3515     const uint16_t mask = ((1U << bits) - 1) << offset;
3516
3517     if (value >> bits) {
3518         return false;
3519     }
3520
3521     *bf = htons((ntohs(*bf) & ~mask) | (value << offset));
3522     return true;
3523 }
3524
3525 static int
3526 scan_be16_bf(const char *s, ovs_be16 *key, ovs_be16 *mask, uint8_t bits,
3527              uint8_t offset)
3528 {
3529     uint16_t key_, mask_;
3530     int n;
3531
3532     if (ovs_scan(s, "%"SCNi16"%n", &key_, &n)) {
3533         int len = n;
3534
3535         if (set_be16_bf(key, bits, offset, key_)) {
3536             if (mask) {
3537                 if (ovs_scan(s + len, "/%"SCNi16"%n", &mask_, &n)) {
3538                     len += n;
3539
3540                     if (!set_be16_bf(mask, bits, offset, mask_)) {
3541                         return 0;
3542                     }
3543                 } else {
3544                     *mask |= htons(((1U << bits) - 1) << offset);
3545                 }
3546             }
3547             return len;
3548         }
3549     }
3550     return 0;
3551 }
3552
3553 static int
3554 scan_vid(const char *s, ovs_be16 *key, ovs_be16 *mask)
3555 {
3556     return scan_be16_bf(s, key, mask, 12, VLAN_VID_SHIFT);
3557 }
3558
3559 static int
3560 scan_pcp(const char *s, ovs_be16 *key, ovs_be16 *mask)
3561 {
3562     return scan_be16_bf(s, key, mask, 3, VLAN_PCP_SHIFT);
3563 }
3564
3565 static int
3566 scan_cfi(const char *s, ovs_be16 *key, ovs_be16 *mask)
3567 {
3568     return scan_be16_bf(s, key, mask, 1, VLAN_CFI_SHIFT);
3569 }
3570
3571 /* For MPLS. */
3572 static bool
3573 set_be32_bf(ovs_be32 *bf, uint8_t bits, uint8_t offset, uint32_t value)
3574 {
3575     const uint32_t mask = ((1U << bits) - 1) << offset;
3576
3577     if (value >> bits) {
3578         return false;
3579     }
3580
3581     *bf = htonl((ntohl(*bf) & ~mask) | (value << offset));
3582     return true;
3583 }
3584
3585 static int
3586 scan_be32_bf(const char *s, ovs_be32 *key, ovs_be32 *mask, uint8_t bits,
3587              uint8_t offset)
3588 {
3589     uint32_t key_, mask_;
3590     int n;
3591
3592     if (ovs_scan(s, "%"SCNi32"%n", &key_, &n)) {
3593         int len = n;
3594
3595         if (set_be32_bf(key, bits, offset, key_)) {
3596             if (mask) {
3597                 if (ovs_scan(s + len, "/%"SCNi32"%n", &mask_, &n)) {
3598                     len += n;
3599
3600                     if (!set_be32_bf(mask, bits, offset, mask_)) {
3601                         return 0;
3602                     }
3603                 } else {
3604                     *mask |= htonl(((1U << bits) - 1) << offset);
3605                 }
3606             }
3607             return len;
3608         }
3609     }
3610     return 0;
3611 }
3612
3613 static int
3614 scan_mpls_label(const char *s, ovs_be32 *key, ovs_be32 *mask)
3615 {
3616     return scan_be32_bf(s, key, mask, 20, MPLS_LABEL_SHIFT);
3617 }
3618
3619 static int
3620 scan_mpls_tc(const char *s, ovs_be32 *key, ovs_be32 *mask)
3621 {
3622     return scan_be32_bf(s, key, mask, 3, MPLS_TC_SHIFT);
3623 }
3624
3625 static int
3626 scan_mpls_ttl(const char *s, ovs_be32 *key, ovs_be32 *mask)
3627 {
3628     return scan_be32_bf(s, key, mask, 8, MPLS_TTL_SHIFT);
3629 }
3630
3631 static int
3632 scan_mpls_bos(const char *s, ovs_be32 *key, ovs_be32 *mask)
3633 {
3634     return scan_be32_bf(s, key, mask, 1, MPLS_BOS_SHIFT);
3635 }
3636
3637 static int
3638 scan_vxlan_gbp(const char *s, uint32_t *key, uint32_t *mask)
3639 {
3640     const char *s_base = s;
3641     ovs_be16 id = 0, id_mask = 0;
3642     uint8_t flags = 0, flags_mask = 0;
3643
3644     if (!strncmp(s, "id=", 3)) {
3645         s += 3;
3646         s += scan_be16(s, &id, mask ? &id_mask : NULL);
3647     }
3648
3649     if (s[0] == ',') {
3650         s++;
3651     }
3652     if (!strncmp(s, "flags=", 6)) {
3653         s += 6;
3654         s += scan_u8(s, &flags, mask ? &flags_mask : NULL);
3655     }
3656
3657     if (!strncmp(s, "))", 2)) {
3658         s += 2;
3659
3660         *key = (flags << 16) | ntohs(id);
3661         if (mask) {
3662             *mask = (flags_mask << 16) | ntohs(id_mask);
3663         }
3664
3665         return s - s_base;
3666     }
3667
3668     return 0;
3669 }
3670
3671 static int
3672 scan_geneve(const char *s, struct geneve_scan *key, struct geneve_scan *mask)
3673 {
3674     const char *s_base = s;
3675     struct geneve_opt *opt = key->d;
3676     struct geneve_opt *opt_mask = mask ? mask->d : NULL;
3677     int len_remain = sizeof key->d;
3678
3679     while (s[0] == '{' && len_remain >= sizeof *opt) {
3680         int data_len = 0;
3681
3682         s++;
3683         len_remain -= sizeof *opt;
3684
3685         if (!strncmp(s, "class=", 6)) {
3686             s += 6;
3687             s += scan_be16(s, &opt->opt_class,
3688                            mask ? &opt_mask->opt_class : NULL);
3689         } else if (mask) {
3690             memset(&opt_mask->opt_class, 0, sizeof opt_mask->opt_class);
3691         }
3692
3693         if (s[0] == ',') {
3694             s++;
3695         }
3696         if (!strncmp(s, "type=", 5)) {
3697             s += 5;
3698             s += scan_u8(s, &opt->type, mask ? &opt_mask->type : NULL);
3699         } else if (mask) {
3700             memset(&opt_mask->type, 0, sizeof opt_mask->type);
3701         }
3702
3703         if (s[0] == ',') {
3704             s++;
3705         }
3706         if (!strncmp(s, "len=", 4)) {
3707             uint8_t opt_len, opt_len_mask;
3708             s += 4;
3709             s += scan_u8(s, &opt_len, mask ? &opt_len_mask : NULL);
3710
3711             if (opt_len > 124 || opt_len % 4 || opt_len > len_remain) {
3712                 return 0;
3713             }
3714             opt->length = opt_len / 4;
3715             if (mask) {
3716                 opt_mask->length = opt_len_mask;
3717             }
3718             data_len = opt_len;
3719         } else if (mask) {
3720             memset(&opt_mask->type, 0, sizeof opt_mask->type);
3721         }
3722
3723         if (s[0] == ',') {
3724             s++;
3725         }
3726         if (parse_int_string(s, (uint8_t *)(opt + 1), data_len, (char **)&s)) {
3727             return 0;
3728         }
3729
3730         if (mask) {
3731             if (s[0] == '/') {
3732                 s++;
3733                 if (parse_int_string(s, (uint8_t *)(opt_mask + 1),
3734                                      data_len, (char **)&s)) {
3735                     return 0;
3736                 }
3737             }
3738             opt_mask->r1 = 0;
3739             opt_mask->r2 = 0;
3740             opt_mask->r3 = 0;
3741         }
3742
3743         if (s[0] == '}') {
3744             s++;
3745             opt += 1 + data_len / 4;
3746             if (mask) {
3747                 opt_mask += 1 + data_len / 4;
3748             }
3749             len_remain -= data_len;
3750         }
3751     }
3752
3753     if (s[0] == ')') {
3754         int len = sizeof key->d - len_remain;
3755
3756         s++;
3757         key->len = len;
3758         if (mask) {
3759             mask->len = len;
3760         }
3761         return s - s_base;
3762     }
3763
3764     return 0;
3765 }
3766
3767 static void
3768 tun_flags_to_attr(struct ofpbuf *a, const void *data_)
3769 {
3770     const uint16_t *flags = data_;
3771
3772     if (*flags & FLOW_TNL_F_DONT_FRAGMENT) {
3773         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT);
3774     }
3775     if (*flags & FLOW_TNL_F_CSUM) {
3776         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_CSUM);
3777     }
3778     if (*flags & FLOW_TNL_F_OAM) {
3779         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_OAM);
3780     }
3781 }
3782
3783 static void
3784 vxlan_gbp_to_attr(struct ofpbuf *a, const void *data_)
3785 {
3786     const uint32_t *gbp = data_;
3787
3788     if (*gbp) {
3789         size_t vxlan_opts_ofs;
3790
3791         vxlan_opts_ofs = nl_msg_start_nested(a, OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS);
3792         nl_msg_put_u32(a, OVS_VXLAN_EXT_GBP, *gbp);
3793         nl_msg_end_nested(a, vxlan_opts_ofs);
3794     }
3795 }
3796
3797 static void
3798 geneve_to_attr(struct ofpbuf *a, const void *data_)
3799 {
3800     const struct geneve_scan *geneve = data_;
3801
3802     nl_msg_put_unspec(a, OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS, geneve->d,
3803                       geneve->len);
3804 }
3805
3806 #define SCAN_PUT_ATTR(BUF, ATTR, DATA, FUNC)                      \
3807     {                                                             \
3808         unsigned long call_fn = (unsigned long)FUNC;              \
3809         if (call_fn) {                                            \
3810             typedef void (*fn)(struct ofpbuf *, const void *);    \
3811             fn func = FUNC;                                       \
3812             func(BUF, &(DATA));                                   \
3813         } else {                                                  \
3814             nl_msg_put_unspec(BUF, ATTR, &(DATA), sizeof (DATA)); \
3815         }                                                         \
3816     }
3817
3818 #define SCAN_IF(NAME)                           \
3819     if (strncmp(s, NAME, strlen(NAME)) == 0) {  \
3820         const char *start = s;                  \
3821         int len;                                \
3822                                                 \
3823         s += strlen(NAME)
3824
3825 /* Usually no special initialization is needed. */
3826 #define SCAN_BEGIN(NAME, TYPE)                  \
3827     SCAN_IF(NAME);                              \
3828         TYPE skey, smask;                       \
3829         memset(&skey, 0, sizeof skey);          \
3830         memset(&smask, 0, sizeof smask);        \
3831         do {                                    \
3832             len = 0;
3833
3834 /* Init as fully-masked as mask will not be scanned. */
3835 #define SCAN_BEGIN_FULLY_MASKED(NAME, TYPE)     \
3836     SCAN_IF(NAME);                              \
3837         TYPE skey, smask;                       \
3838         memset(&skey, 0, sizeof skey);          \
3839         memset(&smask, 0xff, sizeof smask);     \
3840         do {                                    \
3841             len = 0;
3842
3843 /* VLAN needs special initialization. */
3844 #define SCAN_BEGIN_INIT(NAME, TYPE, KEY_INIT, MASK_INIT)  \
3845     SCAN_IF(NAME);                                        \
3846         TYPE skey = KEY_INIT;                       \
3847         TYPE smask = MASK_INIT;                     \
3848         do {                                        \
3849             len = 0;
3850
3851 /* Scan unnamed entry as 'TYPE' */
3852 #define SCAN_TYPE(TYPE, KEY, MASK)              \
3853     len = scan_##TYPE(s, KEY, MASK);            \
3854     if (len == 0) {                             \
3855         return -EINVAL;                         \
3856     }                                           \
3857     s += len
3858
3859 /* Scan named ('NAME') entry 'FIELD' as 'TYPE'. */
3860 #define SCAN_FIELD(NAME, TYPE, FIELD)                                   \
3861     if (strncmp(s, NAME, strlen(NAME)) == 0) {                          \
3862         s += strlen(NAME);                                              \
3863         SCAN_TYPE(TYPE, &skey.FIELD, mask ? &smask.FIELD : NULL);       \
3864         continue;                                                       \
3865     }
3866
3867 #define SCAN_FINISH()                           \
3868         } while (*s++ == ',' && len != 0);      \
3869         if (s[-1] != ')') {                     \
3870             return -EINVAL;                     \
3871         }
3872
3873 #define SCAN_FINISH_SINGLE()                    \
3874         } while (false);                        \
3875         if (*s++ != ')') {                      \
3876             return -EINVAL;                     \
3877         }
3878
3879 /* Beginning of nested attribute. */
3880 #define SCAN_BEGIN_NESTED(NAME, ATTR)                      \
3881     SCAN_IF(NAME);                                         \
3882         size_t key_offset, mask_offset;                    \
3883         key_offset = nl_msg_start_nested(key, ATTR);       \
3884         if (mask) {                                        \
3885             mask_offset = nl_msg_start_nested(mask, ATTR); \
3886         }                                                  \
3887         do {                                               \
3888             len = 0;
3889
3890 #define SCAN_END_NESTED()                               \
3891         SCAN_FINISH();                                  \
3892         nl_msg_end_nested(key, key_offset);             \
3893         if (mask) {                                     \
3894             nl_msg_end_nested(mask, mask_offset);       \
3895         }                                               \
3896         return s - start;                               \
3897     }
3898
3899 #define SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, ATTR, FUNC)  \
3900     if (strncmp(s, NAME, strlen(NAME)) == 0) {                \
3901         TYPE skey, smask;                                     \
3902         memset(&skey, 0, sizeof skey);                        \
3903         memset(&smask, 0xff, sizeof smask);                   \
3904         s += strlen(NAME);                                    \
3905         SCAN_TYPE(SCAN_AS, &skey, &smask);                    \
3906         SCAN_PUT(ATTR, FUNC);                                 \
3907         continue;                                             \
3908     }
3909
3910 #define SCAN_FIELD_NESTED(NAME, TYPE, SCAN_AS, ATTR)  \
3911         SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, ATTR, NULL)
3912
3913 #define SCAN_FIELD_NESTED_FUNC(NAME, TYPE, SCAN_AS, FUNC)  \
3914         SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, 0, FUNC)
3915
3916 #define SCAN_PUT(ATTR, FUNC)                            \
3917         SCAN_PUT_ATTR(key, ATTR, skey, FUNC);           \
3918         if (mask)                                       \
3919             SCAN_PUT_ATTR(mask, ATTR, smask, FUNC);     \
3920
3921 #define SCAN_END(ATTR)                                  \
3922         SCAN_FINISH();                                  \
3923         SCAN_PUT(ATTR, NULL);                           \
3924         return s - start;                               \
3925     }
3926
3927 #define SCAN_BEGIN_ARRAY(NAME, TYPE, CNT)       \
3928     SCAN_IF(NAME);                              \
3929         TYPE skey[CNT], smask[CNT];             \
3930         memset(&skey, 0, sizeof skey);          \
3931         memset(&smask, 0, sizeof smask);        \
3932         int idx = 0, cnt = CNT;                 \
3933         uint64_t fields = 0;                    \
3934         do {                                    \
3935             int field = 0;                      \
3936             len = 0;
3937
3938 /* Scan named ('NAME') entry 'FIELD' as 'TYPE'. */
3939 #define SCAN_FIELD_ARRAY(NAME, TYPE, FIELD)                             \
3940     if (strncmp(s, NAME, strlen(NAME)) == 0) {                          \
3941         if (fields & (1UL << field)) {                                  \
3942             fields = 0;                                                 \
3943             if (++idx == cnt) {                                         \
3944                 break;                                                  \
3945             }                                                           \
3946         }                                                               \
3947         s += strlen(NAME);                                              \
3948         SCAN_TYPE(TYPE, &skey[idx].FIELD, mask ? &smask[idx].FIELD : NULL); \
3949         fields |= 1UL << field;                                         \
3950         continue;                                                       \
3951     }                                                                   \
3952     field++;
3953
3954 #define SCAN_PUT_ATTR_ARRAY(BUF, ATTR, DATA, CNT)                    \
3955     nl_msg_put_unspec(BUF, ATTR, &(DATA), sizeof (DATA)[0] * (CNT)); \
3956
3957 #define SCAN_PUT_ARRAY(ATTR, CNT)                        \
3958     SCAN_PUT_ATTR_ARRAY(key, ATTR, skey, CNT);       \
3959     if (mask) {                                      \
3960         SCAN_PUT_ATTR_ARRAY(mask, ATTR, smask, CNT); \
3961     }
3962
3963 #define SCAN_END_ARRAY(ATTR)             \
3964         SCAN_FINISH();                   \
3965         if (idx == cnt) {                \
3966             return -EINVAL;              \
3967         }                                \
3968         SCAN_PUT_ARRAY(ATTR, idx + 1);   \
3969         return s - start;                \
3970     }
3971
3972 #define SCAN_END_SINGLE(ATTR)                           \
3973         SCAN_FINISH_SINGLE();                           \
3974         SCAN_PUT(ATTR, NULL);                           \
3975         return s - start;                               \
3976     }
3977
3978 #define SCAN_SINGLE(NAME, TYPE, SCAN_AS, ATTR)       \
3979     SCAN_BEGIN(NAME, TYPE) {                         \
3980         SCAN_TYPE(SCAN_AS, &skey, &smask);           \
3981     } SCAN_END_SINGLE(ATTR)
3982
3983 #define SCAN_SINGLE_FULLY_MASKED(NAME, TYPE, SCAN_AS, ATTR) \
3984     SCAN_BEGIN_FULLY_MASKED(NAME, TYPE) {                   \
3985         SCAN_TYPE(SCAN_AS, &skey, NULL);                    \
3986     } SCAN_END_SINGLE(ATTR)
3987
3988 /* scan_port needs one extra argument. */
3989 #define SCAN_SINGLE_PORT(NAME, TYPE, ATTR)  \
3990     SCAN_BEGIN(NAME, TYPE) {                            \
3991         len = scan_port(s, &skey, &smask, port_names);  \
3992         if (len == 0) {                                 \
3993             return -EINVAL;                             \
3994         }                                               \
3995         s += len;                                       \
3996     } SCAN_END_SINGLE(ATTR)
3997
3998 static int
3999 parse_odp_key_mask_attr(const char *s, const struct simap *port_names,
4000                         struct ofpbuf *key, struct ofpbuf *mask)
4001 {
4002     ovs_u128 ufid;
4003     int len;
4004
4005     /* Skip UFID. */
4006     len = odp_ufid_from_string(s, &ufid);
4007     if (len) {
4008         return len;
4009     }
4010
4011     SCAN_SINGLE("skb_priority(", uint32_t, u32, OVS_KEY_ATTR_PRIORITY);
4012     SCAN_SINGLE("skb_mark(", uint32_t, u32, OVS_KEY_ATTR_SKB_MARK);
4013     SCAN_SINGLE_FULLY_MASKED("recirc_id(", uint32_t, u32,
4014                              OVS_KEY_ATTR_RECIRC_ID);
4015     SCAN_SINGLE("dp_hash(", uint32_t, u32, OVS_KEY_ATTR_DP_HASH);
4016
4017     SCAN_SINGLE("ct_state(", uint32_t, ct_state, OVS_KEY_ATTR_CT_STATE);
4018     SCAN_SINGLE("ct_zone(", uint16_t, u16, OVS_KEY_ATTR_CT_ZONE);
4019     SCAN_SINGLE("ct_mark(", uint32_t, u32, OVS_KEY_ATTR_CT_MARK);
4020     SCAN_SINGLE("ct_label(", ovs_u128, u128, OVS_KEY_ATTR_CT_LABELS);
4021
4022     SCAN_BEGIN_NESTED("tunnel(", OVS_KEY_ATTR_TUNNEL) {
4023         SCAN_FIELD_NESTED("tun_id=", ovs_be64, be64, OVS_TUNNEL_KEY_ATTR_ID);
4024         SCAN_FIELD_NESTED("src=", ovs_be32, ipv4, OVS_TUNNEL_KEY_ATTR_IPV4_SRC);
4025         SCAN_FIELD_NESTED("dst=", ovs_be32, ipv4, OVS_TUNNEL_KEY_ATTR_IPV4_DST);
4026         SCAN_FIELD_NESTED("ipv6_src=", struct in6_addr, in6_addr, OVS_TUNNEL_KEY_ATTR_IPV6_SRC);
4027         SCAN_FIELD_NESTED("ipv6_dst=", struct in6_addr, in6_addr, OVS_TUNNEL_KEY_ATTR_IPV6_DST);
4028         SCAN_FIELD_NESTED("tos=", uint8_t, u8, OVS_TUNNEL_KEY_ATTR_TOS);
4029         SCAN_FIELD_NESTED("ttl=", uint8_t, u8, OVS_TUNNEL_KEY_ATTR_TTL);
4030         SCAN_FIELD_NESTED("tp_src=", ovs_be16, be16, OVS_TUNNEL_KEY_ATTR_TP_SRC);
4031         SCAN_FIELD_NESTED("tp_dst=", ovs_be16, be16, OVS_TUNNEL_KEY_ATTR_TP_DST);
4032         SCAN_FIELD_NESTED_FUNC("vxlan(gbp(", uint32_t, vxlan_gbp, vxlan_gbp_to_attr);
4033         SCAN_FIELD_NESTED_FUNC("geneve(", struct geneve_scan, geneve,
4034                                geneve_to_attr);
4035         SCAN_FIELD_NESTED_FUNC("flags(", uint16_t, tun_flags, tun_flags_to_attr);
4036     } SCAN_END_NESTED();
4037
4038     SCAN_SINGLE_PORT("in_port(", uint32_t, OVS_KEY_ATTR_IN_PORT);
4039
4040     SCAN_BEGIN("eth(", struct ovs_key_ethernet) {
4041         SCAN_FIELD("src=", eth, eth_src);
4042         SCAN_FIELD("dst=", eth, eth_dst);
4043     } SCAN_END(OVS_KEY_ATTR_ETHERNET);
4044
4045     SCAN_BEGIN_INIT("vlan(", struct ovs_key_vlan__,
4046                     { htons(VLAN_CFI) }, { htons(VLAN_CFI) }) {
4047         SCAN_FIELD("vid=", vid, tci);
4048         SCAN_FIELD("pcp=", pcp, tci);
4049         SCAN_FIELD("cfi=", cfi, tci);
4050     } SCAN_END(OVS_KEY_ATTR_VLAN);
4051
4052     SCAN_SINGLE("eth_type(", ovs_be16, be16, OVS_KEY_ATTR_ETHERTYPE);
4053
4054     SCAN_BEGIN_ARRAY("mpls(", struct ovs_key_mpls, FLOW_MAX_MPLS_LABELS) {
4055         SCAN_FIELD_ARRAY("label=", mpls_label, mpls_lse);
4056         SCAN_FIELD_ARRAY("tc=", mpls_tc, mpls_lse);
4057         SCAN_FIELD_ARRAY("ttl=", mpls_ttl, mpls_lse);
4058         SCAN_FIELD_ARRAY("bos=", mpls_bos, mpls_lse);
4059     } SCAN_END_ARRAY(OVS_KEY_ATTR_MPLS);
4060
4061     SCAN_BEGIN("ipv4(", struct ovs_key_ipv4) {
4062         SCAN_FIELD("src=", ipv4, ipv4_src);
4063         SCAN_FIELD("dst=", ipv4, ipv4_dst);
4064         SCAN_FIELD("proto=", u8, ipv4_proto);
4065         SCAN_FIELD("tos=", u8, ipv4_tos);
4066         SCAN_FIELD("ttl=", u8, ipv4_ttl);
4067         SCAN_FIELD("frag=", frag, ipv4_frag);
4068     } SCAN_END(OVS_KEY_ATTR_IPV4);
4069
4070     SCAN_BEGIN("ipv6(", struct ovs_key_ipv6) {
4071         SCAN_FIELD("src=", ipv6, ipv6_src);
4072         SCAN_FIELD("dst=", ipv6, ipv6_dst);
4073         SCAN_FIELD("label=", ipv6_label, ipv6_label);
4074         SCAN_FIELD("proto=", u8, ipv6_proto);
4075         SCAN_FIELD("tclass=", u8, ipv6_tclass);
4076         SCAN_FIELD("hlimit=", u8, ipv6_hlimit);
4077         SCAN_FIELD("frag=", frag, ipv6_frag);
4078     } SCAN_END(OVS_KEY_ATTR_IPV6);
4079
4080     SCAN_BEGIN("tcp(", struct ovs_key_tcp) {
4081         SCAN_FIELD("src=", be16, tcp_src);
4082         SCAN_FIELD("dst=", be16, tcp_dst);
4083     } SCAN_END(OVS_KEY_ATTR_TCP);
4084
4085     SCAN_SINGLE("tcp_flags(", ovs_be16, tcp_flags, OVS_KEY_ATTR_TCP_FLAGS);
4086
4087     SCAN_BEGIN("udp(", struct ovs_key_udp) {
4088         SCAN_FIELD("src=", be16, udp_src);
4089         SCAN_FIELD("dst=", be16, udp_dst);
4090     } SCAN_END(OVS_KEY_ATTR_UDP);
4091
4092     SCAN_BEGIN("sctp(", struct ovs_key_sctp) {
4093         SCAN_FIELD("src=", be16, sctp_src);
4094         SCAN_FIELD("dst=", be16, sctp_dst);
4095     } SCAN_END(OVS_KEY_ATTR_SCTP);
4096
4097     SCAN_BEGIN("icmp(", struct ovs_key_icmp) {
4098         SCAN_FIELD("type=", u8, icmp_type);
4099         SCAN_FIELD("code=", u8, icmp_code);
4100     } SCAN_END(OVS_KEY_ATTR_ICMP);
4101
4102     SCAN_BEGIN("icmpv6(", struct ovs_key_icmpv6) {
4103         SCAN_FIELD("type=", u8, icmpv6_type);
4104         SCAN_FIELD("code=", u8, icmpv6_code);
4105     } SCAN_END(OVS_KEY_ATTR_ICMPV6);
4106
4107     SCAN_BEGIN("arp(", struct ovs_key_arp) {
4108         SCAN_FIELD("sip=", ipv4, arp_sip);
4109         SCAN_FIELD("tip=", ipv4, arp_tip);
4110         SCAN_FIELD("op=", be16, arp_op);
4111         SCAN_FIELD("sha=", eth, arp_sha);
4112         SCAN_FIELD("tha=", eth, arp_tha);
4113     } SCAN_END(OVS_KEY_ATTR_ARP);
4114
4115     SCAN_BEGIN("nd(", struct ovs_key_nd) {
4116         SCAN_FIELD("target=", ipv6, nd_target);
4117         SCAN_FIELD("sll=", eth, nd_sll);
4118         SCAN_FIELD("tll=", eth, nd_tll);
4119     } SCAN_END(OVS_KEY_ATTR_ND);
4120
4121     /* Encap open-coded. */
4122     if (!strncmp(s, "encap(", 6)) {
4123         const char *start = s;
4124         size_t encap, encap_mask = 0;
4125
4126         encap = nl_msg_start_nested(key, OVS_KEY_ATTR_ENCAP);
4127         if (mask) {
4128             encap_mask = nl_msg_start_nested(mask, OVS_KEY_ATTR_ENCAP);
4129         }
4130
4131         s += 6;
4132         for (;;) {
4133             int retval;
4134
4135             s += strspn(s, delimiters);
4136             if (!*s) {
4137                 return -EINVAL;
4138             } else if (*s == ')') {
4139                 break;
4140             }
4141
4142             retval = parse_odp_key_mask_attr(s, port_names, key, mask);
4143             if (retval < 0) {
4144                 return retval;
4145             }
4146             s += retval;
4147         }
4148         s++;
4149
4150         nl_msg_end_nested(key, encap);
4151         if (mask) {
4152             nl_msg_end_nested(mask, encap_mask);
4153         }
4154
4155         return s - start;
4156     }
4157
4158     return -EINVAL;
4159 }
4160
4161 /* Parses the string representation of a datapath flow key, in the
4162  * format output by odp_flow_key_format().  Returns 0 if successful,
4163  * otherwise a positive errno value.  On success, the flow key is
4164  * appended to 'key' as a series of Netlink attributes.  On failure, no
4165  * data is appended to 'key'.  Either way, 'key''s data might be
4166  * reallocated.
4167  *
4168  * If 'port_names' is nonnull, it points to an simap that maps from a port name
4169  * to a port number.  (Port names may be used instead of port numbers in
4170  * in_port.)
4171  *
4172  * On success, the attributes appended to 'key' are individually syntactically
4173  * valid, but they may not be valid as a sequence.  'key' might, for example,
4174  * have duplicated keys.  odp_flow_key_to_flow() will detect those errors. */
4175 int
4176 odp_flow_from_string(const char *s, const struct simap *port_names,
4177                      struct ofpbuf *key, struct ofpbuf *mask)
4178 {
4179     const size_t old_size = key->size;
4180     for (;;) {
4181         int retval;
4182
4183         s += strspn(s, delimiters);
4184         if (!*s) {
4185             return 0;
4186         }
4187
4188         retval = parse_odp_key_mask_attr(s, port_names, key, mask);
4189         if (retval < 0) {
4190             key->size = old_size;
4191             return -retval;
4192         }
4193         s += retval;
4194     }
4195
4196     return 0;
4197 }
4198
4199 static uint8_t
4200 ovs_to_odp_frag(uint8_t nw_frag, bool is_mask)
4201 {
4202     if (is_mask) {
4203         /* Netlink interface 'enum ovs_frag_type' is an 8-bit enumeration type,
4204          * not a set of flags or bitfields. Hence, if the struct flow nw_frag
4205          * mask, which is a set of bits, has the FLOW_NW_FRAG_ANY as zero, we
4206          * must use a zero mask for the netlink frag field, and all ones mask
4207          * otherwise. */
4208         return (nw_frag & FLOW_NW_FRAG_ANY) ? UINT8_MAX : 0;
4209     }
4210     return !(nw_frag & FLOW_NW_FRAG_ANY) ? OVS_FRAG_TYPE_NONE
4211         : nw_frag & FLOW_NW_FRAG_LATER ? OVS_FRAG_TYPE_LATER
4212         : OVS_FRAG_TYPE_FIRST;
4213 }
4214
4215 static void get_ethernet_key(const struct flow *, struct ovs_key_ethernet *);
4216 static void put_ethernet_key(const struct ovs_key_ethernet *, struct flow *);
4217 static void get_ipv4_key(const struct flow *, struct ovs_key_ipv4 *,
4218                          bool is_mask);
4219 static void put_ipv4_key(const struct ovs_key_ipv4 *, struct flow *,
4220                          bool is_mask);
4221 static void get_ipv6_key(const struct flow *, struct ovs_key_ipv6 *,
4222                          bool is_mask);
4223 static void put_ipv6_key(const struct ovs_key_ipv6 *, struct flow *,
4224                          bool is_mask);
4225 static void get_arp_key(const struct flow *, struct ovs_key_arp *);
4226 static void put_arp_key(const struct ovs_key_arp *, struct flow *);
4227 static void get_nd_key(const struct flow *, struct ovs_key_nd *);
4228 static void put_nd_key(const struct ovs_key_nd *, struct flow *);
4229
4230 /* These share the same layout. */
4231 union ovs_key_tp {
4232     struct ovs_key_tcp tcp;
4233     struct ovs_key_udp udp;
4234     struct ovs_key_sctp sctp;
4235 };
4236
4237 static void get_tp_key(const struct flow *, union ovs_key_tp *);
4238 static void put_tp_key(const union ovs_key_tp *, struct flow *);
4239
4240 static void
4241 odp_flow_key_from_flow__(const struct odp_flow_key_parms *parms,
4242                          bool export_mask, struct ofpbuf *buf)
4243 {
4244     struct ovs_key_ethernet *eth_key;
4245     size_t encap;
4246     const struct flow *flow = parms->flow;
4247     const struct flow *data = export_mask ? parms->mask : parms->flow;
4248
4249     nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, data->skb_priority);
4250
4251     if (flow_tnl_dst_is_set(&flow->tunnel) || export_mask) {
4252         tun_key_to_attr(buf, &data->tunnel, &parms->flow->tunnel,
4253                         parms->key_buf);
4254     }
4255
4256     nl_msg_put_u32(buf, OVS_KEY_ATTR_SKB_MARK, data->pkt_mark);
4257
4258     if (parms->support.ct_state) {
4259         nl_msg_put_u32(buf, OVS_KEY_ATTR_CT_STATE,
4260                        ovs_to_odp_ct_state(data->ct_state));
4261     }
4262     if (parms->support.ct_zone) {
4263         nl_msg_put_u16(buf, OVS_KEY_ATTR_CT_ZONE, data->ct_zone);
4264     }
4265     if (parms->support.ct_mark) {
4266         nl_msg_put_u32(buf, OVS_KEY_ATTR_CT_MARK, data->ct_mark);
4267     }
4268     if (parms->support.ct_label) {
4269         nl_msg_put_unspec(buf, OVS_KEY_ATTR_CT_LABELS, &data->ct_label,
4270                           sizeof(data->ct_label));
4271     }
4272     if (parms->support.recirc) {
4273         nl_msg_put_u32(buf, OVS_KEY_ATTR_RECIRC_ID, data->recirc_id);
4274         nl_msg_put_u32(buf, OVS_KEY_ATTR_DP_HASH, data->dp_hash);
4275     }
4276
4277     /* Add an ingress port attribute if this is a mask or 'odp_in_port'
4278      * is not the magical value "ODPP_NONE". */
4279     if (export_mask || parms->odp_in_port != ODPP_NONE) {
4280         nl_msg_put_odp_port(buf, OVS_KEY_ATTR_IN_PORT, parms->odp_in_port);
4281     }
4282
4283     eth_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ETHERNET,
4284                                        sizeof *eth_key);
4285     get_ethernet_key(data, eth_key);
4286
4287     if (flow->vlan_tci != htons(0) || flow->dl_type == htons(ETH_TYPE_VLAN)) {
4288         if (export_mask) {
4289             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, OVS_BE16_MAX);
4290         } else {
4291             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, htons(ETH_TYPE_VLAN));
4292         }
4293         nl_msg_put_be16(buf, OVS_KEY_ATTR_VLAN, data->vlan_tci);
4294         encap = nl_msg_start_nested(buf, OVS_KEY_ATTR_ENCAP);
4295         if (flow->vlan_tci == htons(0)) {
4296             goto unencap;
4297         }
4298     } else {
4299         encap = 0;
4300     }
4301
4302     if (ntohs(flow->dl_type) < ETH_TYPE_MIN) {
4303         /* For backwards compatibility with kernels that don't support
4304          * wildcarding, the following convention is used to encode the
4305          * OVS_KEY_ATTR_ETHERTYPE for key and mask:
4306          *
4307          *   key      mask    matches
4308          * -------- --------  -------
4309          *  >0x5ff   0xffff   Specified Ethernet II Ethertype.
4310          *  >0x5ff      0     Any Ethernet II or non-Ethernet II frame.
4311          *  <none>   0xffff   Any non-Ethernet II frame (except valid
4312          *                    802.3 SNAP packet with valid eth_type).
4313          */
4314         if (export_mask) {
4315             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, OVS_BE16_MAX);
4316         }
4317         goto unencap;
4318     }
4319
4320     nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, data->dl_type);
4321
4322     if (flow->dl_type == htons(ETH_TYPE_IP)) {
4323         struct ovs_key_ipv4 *ipv4_key;
4324
4325         ipv4_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV4,
4326                                             sizeof *ipv4_key);
4327         get_ipv4_key(data, ipv4_key, export_mask);
4328     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
4329         struct ovs_key_ipv6 *ipv6_key;
4330
4331         ipv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV6,
4332                                             sizeof *ipv6_key);
4333         get_ipv6_key(data, ipv6_key, export_mask);
4334     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
4335                flow->dl_type == htons(ETH_TYPE_RARP)) {
4336         struct ovs_key_arp *arp_key;
4337
4338         arp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ARP,
4339                                            sizeof *arp_key);
4340         get_arp_key(data, arp_key);
4341     } else if (eth_type_mpls(flow->dl_type)) {
4342         struct ovs_key_mpls *mpls_key;
4343         int i, n;
4344
4345         n = flow_count_mpls_labels(flow, NULL);
4346         if (export_mask) {
4347             n = MIN(n, parms->support.max_mpls_depth);
4348         }
4349         mpls_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_MPLS,
4350                                             n * sizeof *mpls_key);
4351         for (i = 0; i < n; i++) {
4352             mpls_key[i].mpls_lse = data->mpls_lse[i];
4353         }
4354     }
4355
4356     if (is_ip_any(flow) && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4357         if (flow->nw_proto == IPPROTO_TCP) {
4358             union ovs_key_tp *tcp_key;
4359
4360             tcp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_TCP,
4361                                                sizeof *tcp_key);
4362             get_tp_key(data, tcp_key);
4363             if (data->tcp_flags) {
4364                 nl_msg_put_be16(buf, OVS_KEY_ATTR_TCP_FLAGS, data->tcp_flags);
4365             }
4366         } else if (flow->nw_proto == IPPROTO_UDP) {
4367             union ovs_key_tp *udp_key;
4368
4369             udp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_UDP,
4370                                                sizeof *udp_key);
4371             get_tp_key(data, udp_key);
4372         } else if (flow->nw_proto == IPPROTO_SCTP) {
4373             union ovs_key_tp *sctp_key;
4374
4375             sctp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_SCTP,
4376                                                sizeof *sctp_key);
4377             get_tp_key(data, sctp_key);
4378         } else if (flow->dl_type == htons(ETH_TYPE_IP)
4379                 && flow->nw_proto == IPPROTO_ICMP) {
4380             struct ovs_key_icmp *icmp_key;
4381
4382             icmp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMP,
4383                                                 sizeof *icmp_key);
4384             icmp_key->icmp_type = ntohs(data->tp_src);
4385             icmp_key->icmp_code = ntohs(data->tp_dst);
4386         } else if (flow->dl_type == htons(ETH_TYPE_IPV6)
4387                 && flow->nw_proto == IPPROTO_ICMPV6) {
4388             struct ovs_key_icmpv6 *icmpv6_key;
4389
4390             icmpv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMPV6,
4391                                                   sizeof *icmpv6_key);
4392             icmpv6_key->icmpv6_type = ntohs(data->tp_src);
4393             icmpv6_key->icmpv6_code = ntohs(data->tp_dst);
4394
4395             if (flow->tp_dst == htons(0)
4396                 && (flow->tp_src == htons(ND_NEIGHBOR_SOLICIT)
4397                     || flow->tp_src == htons(ND_NEIGHBOR_ADVERT))
4398                 /* Even though 'tp_src' and 'tp_dst' are 16 bits wide, ICMP
4399                  * type and code are 8 bits wide.  Therefore, an exact match
4400                  * looks like htons(0xff), not htons(0xffff).  See
4401                  * xlate_wc_finish() for details. */
4402                 && (!export_mask || (data->tp_src == htons(0xff)
4403                                      && data->tp_dst == htons(0xff)))) {
4404
4405                 struct ovs_key_nd *nd_key;
4406
4407                 nd_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ND,
4408                                                     sizeof *nd_key);
4409                 memcpy(nd_key->nd_target, &data->nd_target,
4410                         sizeof nd_key->nd_target);
4411                 nd_key->nd_sll = data->arp_sha;
4412                 nd_key->nd_tll = data->arp_tha;
4413             }
4414         }
4415     }
4416
4417 unencap:
4418     if (encap) {
4419         nl_msg_end_nested(buf, encap);
4420     }
4421 }
4422
4423 /* Appends a representation of 'flow' as OVS_KEY_ATTR_* attributes to 'buf'.
4424  *
4425  * 'buf' must have at least ODPUTIL_FLOW_KEY_BYTES bytes of space, or be
4426  * capable of being expanded to allow for that much space. */
4427 void
4428 odp_flow_key_from_flow(const struct odp_flow_key_parms *parms,
4429                        struct ofpbuf *buf)
4430 {
4431     odp_flow_key_from_flow__(parms, false, buf);
4432 }
4433
4434 /* Appends a representation of 'mask' as OVS_KEY_ATTR_* attributes to
4435  * 'buf'.
4436  *
4437  * 'buf' must have at least ODPUTIL_FLOW_KEY_BYTES bytes of space, or be
4438  * capable of being expanded to allow for that much space. */
4439 void
4440 odp_flow_key_from_mask(const struct odp_flow_key_parms *parms,
4441                        struct ofpbuf *buf)
4442 {
4443     odp_flow_key_from_flow__(parms, true, buf);
4444 }
4445
4446 /* Generate ODP flow key from the given packet metadata */
4447 void
4448 odp_key_from_pkt_metadata(struct ofpbuf *buf, const struct pkt_metadata *md)
4449 {
4450     nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, md->skb_priority);
4451
4452     if (flow_tnl_dst_is_set(&md->tunnel)) {
4453         tun_key_to_attr(buf, &md->tunnel, &md->tunnel, NULL);
4454     }
4455
4456     nl_msg_put_u32(buf, OVS_KEY_ATTR_SKB_MARK, md->pkt_mark);
4457
4458     if (md->ct_state) {
4459         nl_msg_put_u32(buf, OVS_KEY_ATTR_CT_STATE,
4460                        ovs_to_odp_ct_state(md->ct_state));
4461         if (md->ct_zone) {
4462             nl_msg_put_u16(buf, OVS_KEY_ATTR_CT_ZONE, md->ct_zone);
4463         }
4464         if (md->ct_mark) {
4465             nl_msg_put_u32(buf, OVS_KEY_ATTR_CT_MARK, md->ct_mark);
4466         }
4467         if (!ovs_u128_is_zero(md->ct_label)) {
4468             nl_msg_put_unspec(buf, OVS_KEY_ATTR_CT_LABELS, &md->ct_label,
4469                               sizeof(md->ct_label));
4470         }
4471     }
4472
4473     /* Add an ingress port attribute if 'odp_in_port' is not the magical
4474      * value "ODPP_NONE". */
4475     if (md->in_port.odp_port != ODPP_NONE) {
4476         nl_msg_put_odp_port(buf, OVS_KEY_ATTR_IN_PORT, md->in_port.odp_port);
4477     }
4478 }
4479
4480 /* Generate packet metadata from the given ODP flow key. */
4481 void
4482 odp_key_to_pkt_metadata(const struct nlattr *key, size_t key_len,
4483                         struct pkt_metadata *md)
4484 {
4485     const struct nlattr *nla;
4486     size_t left;
4487     uint32_t wanted_attrs = 1u << OVS_KEY_ATTR_PRIORITY |
4488         1u << OVS_KEY_ATTR_SKB_MARK | 1u << OVS_KEY_ATTR_TUNNEL |
4489         1u << OVS_KEY_ATTR_IN_PORT;
4490
4491     pkt_metadata_init(md, ODPP_NONE);
4492
4493     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
4494         uint16_t type = nl_attr_type(nla);
4495         size_t len = nl_attr_get_size(nla);
4496         int expected_len = odp_key_attr_len(ovs_flow_key_attr_lens,
4497                                             OVS_KEY_ATTR_MAX, type);
4498
4499         if (len != expected_len && expected_len >= 0) {
4500             continue;
4501         }
4502
4503         switch (type) {
4504         case OVS_KEY_ATTR_RECIRC_ID:
4505             md->recirc_id = nl_attr_get_u32(nla);
4506             wanted_attrs &= ~(1u << OVS_KEY_ATTR_RECIRC_ID);
4507             break;
4508         case OVS_KEY_ATTR_DP_HASH:
4509             md->dp_hash = nl_attr_get_u32(nla);
4510             wanted_attrs &= ~(1u << OVS_KEY_ATTR_DP_HASH);
4511             break;
4512         case OVS_KEY_ATTR_PRIORITY:
4513             md->skb_priority = nl_attr_get_u32(nla);
4514             wanted_attrs &= ~(1u << OVS_KEY_ATTR_PRIORITY);
4515             break;
4516         case OVS_KEY_ATTR_SKB_MARK:
4517             md->pkt_mark = nl_attr_get_u32(nla);
4518             wanted_attrs &= ~(1u << OVS_KEY_ATTR_SKB_MARK);
4519             break;
4520         case OVS_KEY_ATTR_CT_STATE:
4521             md->ct_state = odp_to_ovs_ct_state(nl_attr_get_u32(nla));
4522             wanted_attrs &= ~(1u << OVS_KEY_ATTR_CT_STATE);
4523             break;
4524         case OVS_KEY_ATTR_CT_ZONE:
4525             md->ct_zone = nl_attr_get_u16(nla);
4526             wanted_attrs &= ~(1u << OVS_KEY_ATTR_CT_ZONE);
4527             break;
4528         case OVS_KEY_ATTR_CT_MARK:
4529             md->ct_mark = nl_attr_get_u32(nla);
4530             wanted_attrs &= ~(1u << OVS_KEY_ATTR_CT_MARK);
4531             break;
4532         case OVS_KEY_ATTR_CT_LABELS: {
4533             const ovs_u128 *cl = nl_attr_get(nla);
4534
4535             md->ct_label = *cl;
4536             wanted_attrs &= ~(1u << OVS_KEY_ATTR_CT_LABELS);
4537             break;
4538         }
4539         case OVS_KEY_ATTR_TUNNEL: {
4540             enum odp_key_fitness res;
4541
4542             res = odp_tun_key_from_attr(nla, true, &md->tunnel);
4543             if (res == ODP_FIT_ERROR) {
4544                 memset(&md->tunnel, 0, sizeof md->tunnel);
4545             } else if (res == ODP_FIT_PERFECT) {
4546                 wanted_attrs &= ~(1u << OVS_KEY_ATTR_TUNNEL);
4547             }
4548             break;
4549         }
4550         case OVS_KEY_ATTR_IN_PORT:
4551             md->in_port.odp_port = nl_attr_get_odp_port(nla);
4552             wanted_attrs &= ~(1u << OVS_KEY_ATTR_IN_PORT);
4553             break;
4554         default:
4555             break;
4556         }
4557
4558         if (!wanted_attrs) {
4559             return; /* Have everything. */
4560         }
4561     }
4562 }
4563
4564 uint32_t
4565 odp_flow_key_hash(const struct nlattr *key, size_t key_len)
4566 {
4567     BUILD_ASSERT_DECL(!(NLA_ALIGNTO % sizeof(uint32_t)));
4568     return hash_bytes32(ALIGNED_CAST(const uint32_t *, key), key_len, 0);
4569 }
4570
4571 static void
4572 log_odp_key_attributes(struct vlog_rate_limit *rl, const char *title,
4573                        uint64_t attrs, int out_of_range_attr,
4574                        const struct nlattr *key, size_t key_len)
4575 {
4576     struct ds s;
4577     int i;
4578
4579     if (VLOG_DROP_DBG(rl)) {
4580         return;
4581     }
4582
4583     ds_init(&s);
4584     for (i = 0; i < 64; i++) {
4585         if (attrs & (UINT64_C(1) << i)) {
4586             char namebuf[OVS_KEY_ATTR_BUFSIZE];
4587
4588             ds_put_format(&s, " %s",
4589                           ovs_key_attr_to_string(i, namebuf, sizeof namebuf));
4590         }
4591     }
4592     if (out_of_range_attr) {
4593         ds_put_format(&s, " %d (and possibly others)", out_of_range_attr);
4594     }
4595
4596     ds_put_cstr(&s, ": ");
4597     odp_flow_key_format(key, key_len, &s);
4598
4599     VLOG_DBG("%s:%s", title, ds_cstr(&s));
4600     ds_destroy(&s);
4601 }
4602
4603 static uint8_t
4604 odp_to_ovs_frag(uint8_t odp_frag, bool is_mask)
4605 {
4606     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4607
4608     if (is_mask) {
4609         return odp_frag ? FLOW_NW_FRAG_MASK : 0;
4610     }
4611
4612     if (odp_frag > OVS_FRAG_TYPE_LATER) {
4613         VLOG_ERR_RL(&rl, "invalid frag %"PRIu8" in flow key", odp_frag);
4614         return 0xff; /* Error. */
4615     }
4616
4617     return (odp_frag == OVS_FRAG_TYPE_NONE) ? 0
4618         : (odp_frag == OVS_FRAG_TYPE_FIRST) ? FLOW_NW_FRAG_ANY
4619         :  FLOW_NW_FRAG_ANY | FLOW_NW_FRAG_LATER;
4620 }
4621
4622 static bool
4623 parse_flow_nlattrs(const struct nlattr *key, size_t key_len,
4624                    const struct nlattr *attrs[], uint64_t *present_attrsp,
4625                    int *out_of_range_attrp)
4626 {
4627     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
4628     const struct nlattr *nla;
4629     uint64_t present_attrs;
4630     size_t left;
4631
4632     BUILD_ASSERT(OVS_KEY_ATTR_MAX < CHAR_BIT * sizeof present_attrs);
4633     present_attrs = 0;
4634     *out_of_range_attrp = 0;
4635     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
4636         uint16_t type = nl_attr_type(nla);
4637         size_t len = nl_attr_get_size(nla);
4638         int expected_len = odp_key_attr_len(ovs_flow_key_attr_lens,
4639                                             OVS_KEY_ATTR_MAX, type);
4640
4641         if (len != expected_len && expected_len >= 0) {
4642             char namebuf[OVS_KEY_ATTR_BUFSIZE];
4643
4644             VLOG_ERR_RL(&rl, "attribute %s has length %"PRIuSIZE" but should have "
4645                         "length %d", ovs_key_attr_to_string(type, namebuf,
4646                                                             sizeof namebuf),
4647                         len, expected_len);
4648             return false;
4649         }
4650
4651         if (type > OVS_KEY_ATTR_MAX) {
4652             *out_of_range_attrp = type;
4653         } else {
4654             if (present_attrs & (UINT64_C(1) << type)) {
4655                 char namebuf[OVS_KEY_ATTR_BUFSIZE];
4656
4657                 VLOG_ERR_RL(&rl, "duplicate %s attribute in flow key",
4658                             ovs_key_attr_to_string(type,
4659                                                    namebuf, sizeof namebuf));
4660                 return false;
4661             }
4662
4663             present_attrs |= UINT64_C(1) << type;
4664             attrs[type] = nla;
4665         }
4666     }
4667     if (left) {
4668         VLOG_ERR_RL(&rl, "trailing garbage in flow key");
4669         return false;
4670     }
4671
4672     *present_attrsp = present_attrs;
4673     return true;
4674 }
4675
4676 static enum odp_key_fitness
4677 check_expectations(uint64_t present_attrs, int out_of_range_attr,
4678                    uint64_t expected_attrs,
4679                    const struct nlattr *key, size_t key_len)
4680 {
4681     uint64_t missing_attrs;
4682     uint64_t extra_attrs;
4683
4684     missing_attrs = expected_attrs & ~present_attrs;
4685     if (missing_attrs) {
4686         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
4687         log_odp_key_attributes(&rl, "expected but not present",
4688                                missing_attrs, 0, key, key_len);
4689         return ODP_FIT_TOO_LITTLE;
4690     }
4691
4692     extra_attrs = present_attrs & ~expected_attrs;
4693     if (extra_attrs || out_of_range_attr) {
4694         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
4695         log_odp_key_attributes(&rl, "present but not expected",
4696                                extra_attrs, out_of_range_attr, key, key_len);
4697         return ODP_FIT_TOO_MUCH;
4698     }
4699
4700     return ODP_FIT_PERFECT;
4701 }
4702
4703 static bool
4704 parse_ethertype(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
4705                 uint64_t present_attrs, uint64_t *expected_attrs,
4706                 struct flow *flow, const struct flow *src_flow)
4707 {
4708     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4709     bool is_mask = flow != src_flow;
4710
4711     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE)) {
4712         flow->dl_type = nl_attr_get_be16(attrs[OVS_KEY_ATTR_ETHERTYPE]);
4713         if (!is_mask && ntohs(flow->dl_type) < ETH_TYPE_MIN) {
4714             VLOG_ERR_RL(&rl, "invalid Ethertype %"PRIu16" in flow key",
4715                         ntohs(flow->dl_type));
4716             return false;
4717         }
4718         if (is_mask && ntohs(src_flow->dl_type) < ETH_TYPE_MIN &&
4719             flow->dl_type != htons(0xffff)) {
4720             return false;
4721         }
4722         *expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE;
4723     } else {
4724         if (!is_mask) {
4725             flow->dl_type = htons(FLOW_DL_TYPE_NONE);
4726         } else if (ntohs(src_flow->dl_type) < ETH_TYPE_MIN) {
4727             /* See comments in odp_flow_key_from_flow__(). */
4728             VLOG_ERR_RL(&rl, "mask expected for non-Ethernet II frame");
4729             return false;
4730         }
4731     }
4732     return true;
4733 }
4734
4735 static enum odp_key_fitness
4736 parse_l2_5_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
4737                   uint64_t present_attrs, int out_of_range_attr,
4738                   uint64_t expected_attrs, struct flow *flow,
4739                   const struct nlattr *key, size_t key_len,
4740                   const struct flow *src_flow)
4741 {
4742     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4743     bool is_mask = src_flow != flow;
4744     const void *check_start = NULL;
4745     size_t check_len = 0;
4746     enum ovs_key_attr expected_bit = 0xff;
4747
4748     if (eth_type_mpls(src_flow->dl_type)) {
4749         if (!is_mask || present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_MPLS)) {
4750             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_MPLS);
4751         }
4752         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_MPLS)) {
4753             size_t size = nl_attr_get_size(attrs[OVS_KEY_ATTR_MPLS]);
4754             const ovs_be32 *mpls_lse = nl_attr_get(attrs[OVS_KEY_ATTR_MPLS]);
4755             int n = size / sizeof(ovs_be32);
4756             int i;
4757
4758             if (!size || size % sizeof(ovs_be32)) {
4759                 return ODP_FIT_ERROR;
4760             }
4761             if (flow->mpls_lse[0] && flow->dl_type != htons(0xffff)) {
4762                 return ODP_FIT_ERROR;
4763             }
4764
4765             for (i = 0; i < n && i < FLOW_MAX_MPLS_LABELS; i++) {
4766                 flow->mpls_lse[i] = mpls_lse[i];
4767             }
4768             if (n > FLOW_MAX_MPLS_LABELS) {
4769                 return ODP_FIT_TOO_MUCH;
4770             }
4771
4772             if (!is_mask) {
4773                 /* BOS may be set only in the innermost label. */
4774                 for (i = 0; i < n - 1; i++) {
4775                     if (flow->mpls_lse[i] & htonl(MPLS_BOS_MASK)) {
4776                         return ODP_FIT_ERROR;
4777                     }
4778                 }
4779
4780                 /* BOS must be set in the innermost label. */
4781                 if (n < FLOW_MAX_MPLS_LABELS
4782                     && !(flow->mpls_lse[n - 1] & htonl(MPLS_BOS_MASK))) {
4783                     return ODP_FIT_TOO_LITTLE;
4784                 }
4785             }
4786         }
4787
4788         goto done;
4789     } else if (src_flow->dl_type == htons(ETH_TYPE_IP)) {
4790         if (!is_mask) {
4791             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV4;
4792         }
4793         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV4)) {
4794             const struct ovs_key_ipv4 *ipv4_key;
4795
4796             ipv4_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV4]);
4797             put_ipv4_key(ipv4_key, flow, is_mask);
4798             if (flow->nw_frag > FLOW_NW_FRAG_MASK) {
4799                 return ODP_FIT_ERROR;
4800             }
4801             if (is_mask) {
4802                 check_start = ipv4_key;
4803                 check_len = sizeof *ipv4_key;
4804                 expected_bit = OVS_KEY_ATTR_IPV4;
4805             }
4806         }
4807     } else if (src_flow->dl_type == htons(ETH_TYPE_IPV6)) {
4808         if (!is_mask) {
4809             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV6;
4810         }
4811         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV6)) {
4812             const struct ovs_key_ipv6 *ipv6_key;
4813
4814             ipv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV6]);
4815             put_ipv6_key(ipv6_key, flow, is_mask);
4816             if (flow->nw_frag > FLOW_NW_FRAG_MASK) {
4817                 return ODP_FIT_ERROR;
4818             }
4819             if (is_mask) {
4820                 check_start = ipv6_key;
4821                 check_len = sizeof *ipv6_key;
4822                 expected_bit = OVS_KEY_ATTR_IPV6;
4823             }
4824         }
4825     } else if (src_flow->dl_type == htons(ETH_TYPE_ARP) ||
4826                src_flow->dl_type == htons(ETH_TYPE_RARP)) {
4827         if (!is_mask) {
4828             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ARP;
4829         }
4830         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ARP)) {
4831             const struct ovs_key_arp *arp_key;
4832
4833             arp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ARP]);
4834             if (!is_mask && (arp_key->arp_op & htons(0xff00))) {
4835                 VLOG_ERR_RL(&rl, "unsupported ARP opcode %"PRIu16" in flow "
4836                             "key", ntohs(arp_key->arp_op));
4837                 return ODP_FIT_ERROR;
4838             }
4839             put_arp_key(arp_key, flow);
4840             if (is_mask) {
4841                 check_start = arp_key;
4842                 check_len = sizeof *arp_key;
4843                 expected_bit = OVS_KEY_ATTR_ARP;
4844             }
4845         }
4846     } else {
4847         goto done;
4848     }
4849     if (check_len > 0) { /* Happens only when 'is_mask'. */
4850         if (!is_all_zeros(check_start, check_len) &&
4851             flow->dl_type != htons(0xffff)) {
4852             return ODP_FIT_ERROR;
4853         } else {
4854             expected_attrs |= UINT64_C(1) << expected_bit;
4855         }
4856     }
4857
4858     expected_bit = OVS_KEY_ATTR_UNSPEC;
4859     if (src_flow->nw_proto == IPPROTO_TCP
4860         && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
4861             src_flow->dl_type == htons(ETH_TYPE_IPV6))
4862         && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4863         if (!is_mask) {
4864             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP;
4865         }
4866         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP)) {
4867             const union ovs_key_tp *tcp_key;
4868
4869             tcp_key = nl_attr_get(attrs[OVS_KEY_ATTR_TCP]);
4870             put_tp_key(tcp_key, flow);
4871             expected_bit = OVS_KEY_ATTR_TCP;
4872         }
4873         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP_FLAGS)) {
4874             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP_FLAGS;
4875             flow->tcp_flags = nl_attr_get_be16(attrs[OVS_KEY_ATTR_TCP_FLAGS]);
4876         }
4877     } else if (src_flow->nw_proto == IPPROTO_UDP
4878                && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
4879                    src_flow->dl_type == htons(ETH_TYPE_IPV6))
4880                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4881         if (!is_mask) {
4882             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_UDP;
4883         }
4884         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_UDP)) {
4885             const union ovs_key_tp *udp_key;
4886
4887             udp_key = nl_attr_get(attrs[OVS_KEY_ATTR_UDP]);
4888             put_tp_key(udp_key, flow);
4889             expected_bit = OVS_KEY_ATTR_UDP;
4890         }
4891     } else if (src_flow->nw_proto == IPPROTO_SCTP
4892                && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
4893                    src_flow->dl_type == htons(ETH_TYPE_IPV6))
4894                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4895         if (!is_mask) {
4896             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_SCTP;
4897         }
4898         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_SCTP)) {
4899             const union ovs_key_tp *sctp_key;
4900
4901             sctp_key = nl_attr_get(attrs[OVS_KEY_ATTR_SCTP]);
4902             put_tp_key(sctp_key, flow);
4903             expected_bit = OVS_KEY_ATTR_SCTP;
4904         }
4905     } else if (src_flow->nw_proto == IPPROTO_ICMP
4906                && src_flow->dl_type == htons(ETH_TYPE_IP)
4907                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4908         if (!is_mask) {
4909             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMP;
4910         }
4911         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMP)) {
4912             const struct ovs_key_icmp *icmp_key;
4913
4914             icmp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMP]);
4915             flow->tp_src = htons(icmp_key->icmp_type);
4916             flow->tp_dst = htons(icmp_key->icmp_code);
4917             expected_bit = OVS_KEY_ATTR_ICMP;
4918         }
4919     } else if (src_flow->nw_proto == IPPROTO_ICMPV6
4920                && src_flow->dl_type == htons(ETH_TYPE_IPV6)
4921                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
4922         if (!is_mask) {
4923             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMPV6;
4924         }
4925         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMPV6)) {
4926             const struct ovs_key_icmpv6 *icmpv6_key;
4927
4928             icmpv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMPV6]);
4929             flow->tp_src = htons(icmpv6_key->icmpv6_type);
4930             flow->tp_dst = htons(icmpv6_key->icmpv6_code);
4931             expected_bit = OVS_KEY_ATTR_ICMPV6;
4932             if (src_flow->tp_dst == htons(0) &&
4933                 (src_flow->tp_src == htons(ND_NEIGHBOR_SOLICIT) ||
4934                  src_flow->tp_src == htons(ND_NEIGHBOR_ADVERT))) {
4935                 if (!is_mask) {
4936                     expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
4937                 }
4938                 if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ND)) {
4939                     const struct ovs_key_nd *nd_key;
4940
4941                     nd_key = nl_attr_get(attrs[OVS_KEY_ATTR_ND]);
4942                     memcpy(&flow->nd_target, nd_key->nd_target,
4943                            sizeof flow->nd_target);
4944                     flow->arp_sha = nd_key->nd_sll;
4945                     flow->arp_tha = nd_key->nd_tll;
4946                     if (is_mask) {
4947                         /* Even though 'tp_src' and 'tp_dst' are 16 bits wide,
4948                          * ICMP type and code are 8 bits wide.  Therefore, an
4949                          * exact match looks like htons(0xff), not
4950                          * htons(0xffff).  See xlate_wc_finish() for details.
4951                          * */
4952                         if (!is_all_zeros(nd_key, sizeof *nd_key) &&
4953                             (flow->tp_src != htons(0xff) ||
4954                              flow->tp_dst != htons(0xff))) {
4955                             return ODP_FIT_ERROR;
4956                         } else {
4957                             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
4958                         }
4959                     }
4960                 }
4961             }
4962         }
4963     }
4964     if (is_mask && expected_bit != OVS_KEY_ATTR_UNSPEC) {
4965         if ((flow->tp_src || flow->tp_dst) && flow->nw_proto != 0xff) {
4966             return ODP_FIT_ERROR;
4967         } else {
4968             expected_attrs |= UINT64_C(1) << expected_bit;
4969         }
4970     }
4971
4972 done:
4973     return check_expectations(present_attrs, out_of_range_attr, expected_attrs,
4974                               key, key_len);
4975 }
4976
4977 /* Parse 802.1Q header then encapsulated L3 attributes. */
4978 static enum odp_key_fitness
4979 parse_8021q_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
4980                    uint64_t present_attrs, int out_of_range_attr,
4981                    uint64_t expected_attrs, struct flow *flow,
4982                    const struct nlattr *key, size_t key_len,
4983                    const struct flow *src_flow)
4984 {
4985     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4986     bool is_mask = src_flow != flow;
4987
4988     const struct nlattr *encap
4989         = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)
4990            ? attrs[OVS_KEY_ATTR_ENCAP] : NULL);
4991     enum odp_key_fitness encap_fitness;
4992     enum odp_key_fitness fitness;
4993
4994     /* Calculate fitness of outer attributes. */
4995     if (!is_mask) {
4996         expected_attrs |= ((UINT64_C(1) << OVS_KEY_ATTR_VLAN) |
4997                           (UINT64_C(1) << OVS_KEY_ATTR_ENCAP));
4998     } else {
4999         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)) {
5000             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_VLAN);
5001         }
5002         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)) {
5003             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_ENCAP);
5004         }
5005     }
5006     fitness = check_expectations(present_attrs, out_of_range_attr,
5007                                  expected_attrs, key, key_len);
5008
5009     /* Set vlan_tci.
5010      * Remove the TPID from dl_type since it's not the real Ethertype.  */
5011     flow->dl_type = htons(0);
5012     flow->vlan_tci = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)
5013                       ? nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN])
5014                       : htons(0));
5015     if (!is_mask) {
5016         if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN))) {
5017             return ODP_FIT_TOO_LITTLE;
5018         } else if (flow->vlan_tci == htons(0)) {
5019             /* Corner case for a truncated 802.1Q header. */
5020             if (fitness == ODP_FIT_PERFECT && nl_attr_get_size(encap)) {
5021                 return ODP_FIT_TOO_MUCH;
5022             }
5023             return fitness;
5024         } else if (!(flow->vlan_tci & htons(VLAN_CFI))) {
5025             VLOG_ERR_RL(&rl, "OVS_KEY_ATTR_VLAN 0x%04"PRIx16" is nonzero "
5026                         "but CFI bit is not set", ntohs(flow->vlan_tci));
5027             return ODP_FIT_ERROR;
5028         }
5029     } else {
5030         if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP))) {
5031             return fitness;
5032         }
5033     }
5034
5035     /* Now parse the encapsulated attributes. */
5036     if (!parse_flow_nlattrs(nl_attr_get(encap), nl_attr_get_size(encap),
5037                             attrs, &present_attrs, &out_of_range_attr)) {
5038         return ODP_FIT_ERROR;
5039     }
5040     expected_attrs = 0;
5041
5042     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow, src_flow)) {
5043         return ODP_FIT_ERROR;
5044     }
5045     encap_fitness = parse_l2_5_onward(attrs, present_attrs, out_of_range_attr,
5046                                       expected_attrs, flow, key, key_len,
5047                                       src_flow);
5048
5049     /* The overall fitness is the worse of the outer and inner attributes. */
5050     return MAX(fitness, encap_fitness);
5051 }
5052
5053 static enum odp_key_fitness
5054 odp_flow_key_to_flow__(const struct nlattr *key, size_t key_len,
5055                        const struct nlattr *src_key, size_t src_key_len,
5056                        struct flow *flow, const struct flow *src_flow,
5057                        bool udpif)
5058 {
5059     const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1];
5060     uint64_t expected_attrs;
5061     uint64_t present_attrs;
5062     int out_of_range_attr;
5063     bool is_mask = src_flow != flow;
5064
5065     memset(flow, 0, sizeof *flow);
5066
5067     /* Parse attributes. */
5068     if (!parse_flow_nlattrs(key, key_len, attrs, &present_attrs,
5069                             &out_of_range_attr)) {
5070         return ODP_FIT_ERROR;
5071     }
5072     expected_attrs = 0;
5073
5074     /* Metadata. */
5075     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_RECIRC_ID)) {
5076         flow->recirc_id = nl_attr_get_u32(attrs[OVS_KEY_ATTR_RECIRC_ID]);
5077         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_RECIRC_ID;
5078     } else if (is_mask) {
5079         /* Always exact match recirc_id if it is not specified. */
5080         flow->recirc_id = UINT32_MAX;
5081     }
5082
5083     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_DP_HASH)) {
5084         flow->dp_hash = nl_attr_get_u32(attrs[OVS_KEY_ATTR_DP_HASH]);
5085         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_DP_HASH;
5086     }
5087     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_PRIORITY)) {
5088         flow->skb_priority = nl_attr_get_u32(attrs[OVS_KEY_ATTR_PRIORITY]);
5089         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_PRIORITY;
5090     }
5091
5092     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_SKB_MARK)) {
5093         flow->pkt_mark = nl_attr_get_u32(attrs[OVS_KEY_ATTR_SKB_MARK]);
5094         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_SKB_MARK;
5095     }
5096
5097     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_CT_STATE)) {
5098         uint32_t odp_state = nl_attr_get_u32(attrs[OVS_KEY_ATTR_CT_STATE]);
5099
5100         flow->ct_state = odp_to_ovs_ct_state(odp_state);
5101         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_CT_STATE;
5102     }
5103     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_CT_ZONE)) {
5104         flow->ct_zone = nl_attr_get_u16(attrs[OVS_KEY_ATTR_CT_ZONE]);
5105         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_CT_ZONE;
5106     }
5107     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_CT_MARK)) {
5108         flow->ct_mark = nl_attr_get_u32(attrs[OVS_KEY_ATTR_CT_MARK]);
5109         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_CT_MARK;
5110     }
5111     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_CT_LABELS)) {
5112         const ovs_u128 *cl = nl_attr_get(attrs[OVS_KEY_ATTR_CT_LABELS]);
5113
5114         flow->ct_label = *cl;
5115         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_CT_LABELS;
5116     }
5117
5118     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TUNNEL)) {
5119         enum odp_key_fitness res;
5120
5121         res = odp_tun_key_from_attr__(attrs[OVS_KEY_ATTR_TUNNEL],
5122                                       is_mask ? src_key : NULL,
5123                                       src_key_len, &src_flow->tunnel,
5124                                       &flow->tunnel, udpif);
5125         if (res == ODP_FIT_ERROR) {
5126             return ODP_FIT_ERROR;
5127         } else if (res == ODP_FIT_PERFECT) {
5128             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TUNNEL;
5129         }
5130     }
5131
5132     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IN_PORT)) {
5133         flow->in_port.odp_port
5134             = nl_attr_get_odp_port(attrs[OVS_KEY_ATTR_IN_PORT]);
5135         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IN_PORT;
5136     } else if (!is_mask) {
5137         flow->in_port.odp_port = ODPP_NONE;
5138     }
5139
5140     /* Ethernet header. */
5141     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERNET)) {
5142         const struct ovs_key_ethernet *eth_key;
5143
5144         eth_key = nl_attr_get(attrs[OVS_KEY_ATTR_ETHERNET]);
5145         put_ethernet_key(eth_key, flow);
5146         if (is_mask) {
5147             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
5148         }
5149     }
5150     if (!is_mask) {
5151         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
5152     }
5153
5154     /* Get Ethertype or 802.1Q TPID or FLOW_DL_TYPE_NONE. */
5155     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow,
5156         src_flow)) {
5157         return ODP_FIT_ERROR;
5158     }
5159
5160     if (is_mask
5161         ? (src_flow->vlan_tci & htons(VLAN_CFI)) != 0
5162         : src_flow->dl_type == htons(ETH_TYPE_VLAN)) {
5163         return parse_8021q_onward(attrs, present_attrs, out_of_range_attr,
5164                                   expected_attrs, flow, key, key_len, src_flow);
5165     }
5166     if (is_mask) {
5167         /* A missing VLAN mask means exact match on vlan_tci 0 (== no VLAN). */
5168         flow->vlan_tci = htons(0xffff);
5169         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)) {
5170             flow->vlan_tci = nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN]);
5171             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_VLAN);
5172         }
5173     }
5174     return parse_l2_5_onward(attrs, present_attrs, out_of_range_attr,
5175                              expected_attrs, flow, key, key_len, src_flow);
5176 }
5177
5178 /* Converts the 'key_len' bytes of OVS_KEY_ATTR_* attributes in 'key' to a flow
5179  * structure in 'flow'.  Returns an ODP_FIT_* value that indicates how well
5180  * 'key' fits our expectations for what a flow key should contain.
5181  *
5182  * The 'in_port' will be the datapath's understanding of the port.  The
5183  * caller will need to translate with odp_port_to_ofp_port() if the
5184  * OpenFlow port is needed.
5185  *
5186  * This function doesn't take the packet itself as an argument because none of
5187  * the currently understood OVS_KEY_ATTR_* attributes require it.  Currently,
5188  * it is always possible to infer which additional attribute(s) should appear
5189  * by looking at the attributes for lower-level protocols, e.g. if the network
5190  * protocol in OVS_KEY_ATTR_IPV4 or OVS_KEY_ATTR_IPV6 is IPPROTO_TCP then we
5191  * know that a OVS_KEY_ATTR_TCP attribute must appear and that otherwise it
5192  * must be absent. */
5193 enum odp_key_fitness
5194 odp_flow_key_to_flow(const struct nlattr *key, size_t key_len,
5195                      struct flow *flow)
5196 {
5197    return odp_flow_key_to_flow__(key, key_len, NULL, 0, flow, flow, false);
5198 }
5199
5200 static enum odp_key_fitness
5201 odp_flow_key_to_mask__(const struct nlattr *mask_key, size_t mask_key_len,
5202                        const struct nlattr *flow_key, size_t flow_key_len,
5203                        struct flow_wildcards *mask,
5204                        const struct flow *src_flow,
5205                        bool udpif)
5206 {
5207     if (mask_key_len) {
5208         return odp_flow_key_to_flow__(mask_key, mask_key_len,
5209                                       flow_key, flow_key_len,
5210                                       &mask->masks, src_flow, udpif);
5211
5212     } else {
5213         /* A missing mask means that the flow should be exact matched.
5214          * Generate an appropriate exact wildcard for the flow. */
5215         flow_wildcards_init_for_packet(mask, src_flow);
5216
5217         return ODP_FIT_PERFECT;
5218     }
5219 }
5220 /* Converts the 'mask_key_len' bytes of OVS_KEY_ATTR_* attributes in 'mask_key'
5221  * to a mask structure in 'mask'.  'flow' must be a previously translated flow
5222  * corresponding to 'mask' and similarly flow_key/flow_key_len must be the
5223  * attributes from that flow.  Returns an ODP_FIT_* value that indicates how
5224  * well 'key' fits our expectations for what a flow key should contain. */
5225 enum odp_key_fitness
5226 odp_flow_key_to_mask(const struct nlattr *mask_key, size_t mask_key_len,
5227                      const struct nlattr *flow_key, size_t flow_key_len,
5228                      struct flow_wildcards *mask, const struct flow *flow)
5229 {
5230     return odp_flow_key_to_mask__(mask_key, mask_key_len,
5231                                   flow_key, flow_key_len,
5232                                   mask, flow, false);
5233 }
5234
5235 /* These functions are similar to their non-"_udpif" variants but output a
5236  * 'flow' that is suitable for fast-path packet processing.
5237  *
5238  * Some fields have different representation for flow setup and per-
5239  * packet processing (i.e. different between ofproto-dpif and userspace
5240  * datapath). In particular, with the non-"_udpif" functions, struct
5241  * tun_metadata is in the per-flow format (using 'present.map' and 'opts.u8');
5242  * with these functions, struct tun_metadata is in the per-packet format
5243  * (using 'present.len' and 'opts.gnv'). */
5244 enum odp_key_fitness
5245 odp_flow_key_to_flow_udpif(const struct nlattr *key, size_t key_len,
5246                            struct flow *flow)
5247 {
5248    return odp_flow_key_to_flow__(key, key_len, NULL, 0, flow, flow, true);
5249 }
5250
5251 enum odp_key_fitness
5252 odp_flow_key_to_mask_udpif(const struct nlattr *mask_key, size_t mask_key_len,
5253                            const struct nlattr *flow_key, size_t flow_key_len,
5254                            struct flow_wildcards *mask,
5255                            const struct flow *flow)
5256 {
5257     return odp_flow_key_to_mask__(mask_key, mask_key_len,
5258                                   flow_key, flow_key_len,
5259                                   mask, flow, true);
5260 }
5261
5262 /* Returns 'fitness' as a string, for use in debug messages. */
5263 const char *
5264 odp_key_fitness_to_string(enum odp_key_fitness fitness)
5265 {
5266     switch (fitness) {
5267     case ODP_FIT_PERFECT:
5268         return "OK";
5269     case ODP_FIT_TOO_MUCH:
5270         return "too_much";
5271     case ODP_FIT_TOO_LITTLE:
5272         return "too_little";
5273     case ODP_FIT_ERROR:
5274         return "error";
5275     default:
5276         return "<unknown>";
5277     }
5278 }
5279
5280 /* Appends an OVS_ACTION_ATTR_USERSPACE action to 'odp_actions' that specifies
5281  * Netlink PID 'pid'.  If 'userdata' is nonnull, adds a userdata attribute
5282  * whose contents are the 'userdata_size' bytes at 'userdata' and returns the
5283  * offset within 'odp_actions' of the start of the cookie.  (If 'userdata' is
5284  * null, then the return value is not meaningful.) */
5285 size_t
5286 odp_put_userspace_action(uint32_t pid,
5287                          const void *userdata, size_t userdata_size,
5288                          odp_port_t tunnel_out_port,
5289                          bool include_actions,
5290                          struct ofpbuf *odp_actions)
5291 {
5292     size_t userdata_ofs;
5293     size_t offset;
5294
5295     offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_USERSPACE);
5296     nl_msg_put_u32(odp_actions, OVS_USERSPACE_ATTR_PID, pid);
5297     if (userdata) {
5298         userdata_ofs = odp_actions->size + NLA_HDRLEN;
5299
5300         /* The OVS kernel module before OVS 1.11 and the upstream Linux kernel
5301          * module before Linux 3.10 required the userdata to be exactly 8 bytes
5302          * long:
5303          *
5304          *   - The kernel rejected shorter userdata with -ERANGE.
5305          *
5306          *   - The kernel silently dropped userdata beyond the first 8 bytes.
5307          *
5308          * Thus, for maximum compatibility, always put at least 8 bytes.  (We
5309          * separately disable features that required more than 8 bytes.) */
5310         memcpy(nl_msg_put_unspec_zero(odp_actions, OVS_USERSPACE_ATTR_USERDATA,
5311                                       MAX(8, userdata_size)),
5312                userdata, userdata_size);
5313     } else {
5314         userdata_ofs = 0;
5315     }
5316     if (tunnel_out_port != ODPP_NONE) {
5317         nl_msg_put_odp_port(odp_actions, OVS_USERSPACE_ATTR_EGRESS_TUN_PORT,
5318                             tunnel_out_port);
5319     }
5320     if (include_actions) {
5321         nl_msg_put_flag(odp_actions, OVS_USERSPACE_ATTR_ACTIONS);
5322     }
5323     nl_msg_end_nested(odp_actions, offset);
5324
5325     return userdata_ofs;
5326 }
5327
5328 void
5329 odp_put_tunnel_action(const struct flow_tnl *tunnel,
5330                       struct ofpbuf *odp_actions)
5331 {
5332     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
5333     tun_key_to_attr(odp_actions, tunnel, tunnel, NULL);
5334     nl_msg_end_nested(odp_actions, offset);
5335 }
5336
5337 void
5338 odp_put_tnl_push_action(struct ofpbuf *odp_actions,
5339                         struct ovs_action_push_tnl *data)
5340 {
5341     int size = offsetof(struct ovs_action_push_tnl, header);
5342
5343     size += data->header_len;
5344     nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_TUNNEL_PUSH, data, size);
5345 }
5346
5347 \f
5348 /* The commit_odp_actions() function and its helpers. */
5349
5350 static void
5351 commit_set_action(struct ofpbuf *odp_actions, enum ovs_key_attr key_type,
5352                   const void *key, size_t key_size)
5353 {
5354     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
5355     nl_msg_put_unspec(odp_actions, key_type, key, key_size);
5356     nl_msg_end_nested(odp_actions, offset);
5357 }
5358
5359 /* Masked set actions have a mask following the data within the netlink
5360  * attribute.  The unmasked bits in the data will be cleared as the data
5361  * is copied to the action. */
5362 void
5363 commit_masked_set_action(struct ofpbuf *odp_actions,
5364                          enum ovs_key_attr key_type,
5365                          const void *key_, const void *mask_, size_t key_size)
5366 {
5367     size_t offset = nl_msg_start_nested(odp_actions,
5368                                         OVS_ACTION_ATTR_SET_MASKED);
5369     char *data = nl_msg_put_unspec_uninit(odp_actions, key_type, key_size * 2);
5370     const char *key = key_, *mask = mask_;
5371
5372     memcpy(data + key_size, mask, key_size);
5373     /* Clear unmasked bits while copying. */
5374     while (key_size--) {
5375         *data++ = *key++ & *mask++;
5376     }
5377     nl_msg_end_nested(odp_actions, offset);
5378 }
5379
5380 /* If any of the flow key data that ODP actions can modify are different in
5381  * 'base->tunnel' and 'flow->tunnel', appends a set_tunnel ODP action to
5382  * 'odp_actions' that change the flow tunneling information in key from
5383  * 'base->tunnel' into 'flow->tunnel', and then changes 'base->tunnel' in the
5384  * same way.  In other words, operates the same as commit_odp_actions(), but
5385  * only on tunneling information. */
5386 void
5387 commit_odp_tunnel_action(const struct flow *flow, struct flow *base,
5388                          struct ofpbuf *odp_actions)
5389 {
5390     /* A valid IPV4_TUNNEL must have non-zero ip_dst; a valid IPv6 tunnel
5391      * must have non-zero ipv6_dst. */
5392     if (flow_tnl_dst_is_set(&flow->tunnel)) {
5393         if (!memcmp(&base->tunnel, &flow->tunnel, sizeof base->tunnel)) {
5394             return;
5395         }
5396         memcpy(&base->tunnel, &flow->tunnel, sizeof base->tunnel);
5397         odp_put_tunnel_action(&base->tunnel, odp_actions);
5398     }
5399 }
5400
5401 static bool
5402 commit(enum ovs_key_attr attr, bool use_masked_set,
5403        const void *key, void *base, void *mask, size_t size,
5404        struct ofpbuf *odp_actions)
5405 {
5406     if (memcmp(key, base, size)) {
5407         bool fully_masked = odp_mask_is_exact(attr, mask, size);
5408
5409         if (use_masked_set && !fully_masked) {
5410             commit_masked_set_action(odp_actions, attr, key, mask, size);
5411         } else {
5412             if (!fully_masked) {
5413                 memset(mask, 0xff, size);
5414             }
5415             commit_set_action(odp_actions, attr, key, size);
5416         }
5417         memcpy(base, key, size);
5418         return true;
5419     } else {
5420         /* Mask bits are set when we have either read or set the corresponding
5421          * values.  Masked bits will be exact-matched, no need to set them
5422          * if the value did not actually change. */
5423         return false;
5424     }
5425 }
5426
5427 static void
5428 get_ethernet_key(const struct flow *flow, struct ovs_key_ethernet *eth)
5429 {
5430     eth->eth_src = flow->dl_src;
5431     eth->eth_dst = flow->dl_dst;
5432 }
5433
5434 static void
5435 put_ethernet_key(const struct ovs_key_ethernet *eth, struct flow *flow)
5436 {
5437     flow->dl_src = eth->eth_src;
5438     flow->dl_dst = eth->eth_dst;
5439 }
5440
5441 static void
5442 commit_set_ether_addr_action(const struct flow *flow, struct flow *base_flow,
5443                              struct ofpbuf *odp_actions,
5444                              struct flow_wildcards *wc,
5445                              bool use_masked)
5446 {
5447     struct ovs_key_ethernet key, base, mask;
5448
5449     get_ethernet_key(flow, &key);
5450     get_ethernet_key(base_flow, &base);
5451     get_ethernet_key(&wc->masks, &mask);
5452
5453     if (commit(OVS_KEY_ATTR_ETHERNET, use_masked,
5454                &key, &base, &mask, sizeof key, odp_actions)) {
5455         put_ethernet_key(&base, base_flow);
5456         put_ethernet_key(&mask, &wc->masks);
5457     }
5458 }
5459
5460 static void
5461 pop_vlan(struct flow *base,
5462          struct ofpbuf *odp_actions, struct flow_wildcards *wc)
5463 {
5464     memset(&wc->masks.vlan_tci, 0xff, sizeof wc->masks.vlan_tci);
5465
5466     if (base->vlan_tci & htons(VLAN_CFI)) {
5467         nl_msg_put_flag(odp_actions, OVS_ACTION_ATTR_POP_VLAN);
5468         base->vlan_tci = 0;
5469     }
5470 }
5471
5472 static void
5473 commit_vlan_action(ovs_be16 vlan_tci, struct flow *base,
5474                    struct ofpbuf *odp_actions, struct flow_wildcards *wc)
5475 {
5476     if (base->vlan_tci == vlan_tci) {
5477         return;
5478     }
5479
5480     pop_vlan(base, odp_actions, wc);
5481     if (vlan_tci & htons(VLAN_CFI)) {
5482         struct ovs_action_push_vlan vlan;
5483
5484         vlan.vlan_tpid = htons(ETH_TYPE_VLAN);
5485         vlan.vlan_tci = vlan_tci;
5486         nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_PUSH_VLAN,
5487                           &vlan, sizeof vlan);
5488     }
5489     base->vlan_tci = vlan_tci;
5490 }
5491
5492 /* Wildcarding already done at action translation time. */
5493 static void
5494 commit_mpls_action(const struct flow *flow, struct flow *base,
5495                    struct ofpbuf *odp_actions)
5496 {
5497     int base_n = flow_count_mpls_labels(base, NULL);
5498     int flow_n = flow_count_mpls_labels(flow, NULL);
5499     int common_n = flow_count_common_mpls_labels(flow, flow_n, base, base_n,
5500                                                  NULL);
5501
5502     while (base_n > common_n) {
5503         if (base_n - 1 == common_n && flow_n > common_n) {
5504             /* If there is only one more LSE in base than there are common
5505              * between base and flow; and flow has at least one more LSE than
5506              * is common then the topmost LSE of base may be updated using
5507              * set */
5508             struct ovs_key_mpls mpls_key;
5509
5510             mpls_key.mpls_lse = flow->mpls_lse[flow_n - base_n];
5511             commit_set_action(odp_actions, OVS_KEY_ATTR_MPLS,
5512                               &mpls_key, sizeof mpls_key);
5513             flow_set_mpls_lse(base, 0, mpls_key.mpls_lse);
5514             common_n++;
5515         } else {
5516             /* Otherwise, if there more LSEs in base than are common between
5517              * base and flow then pop the topmost one. */
5518             ovs_be16 dl_type;
5519             bool popped;
5520
5521             /* If all the LSEs are to be popped and this is not the outermost
5522              * LSE then use ETH_TYPE_MPLS as the ethertype parameter of the
5523              * POP_MPLS action instead of flow->dl_type.
5524              *
5525              * This is because the POP_MPLS action requires its ethertype
5526              * argument to be an MPLS ethernet type but in this case
5527              * flow->dl_type will be a non-MPLS ethernet type.
5528              *
5529              * When the final POP_MPLS action occurs it use flow->dl_type and
5530              * the and the resulting packet will have the desired dl_type. */
5531             if ((!eth_type_mpls(flow->dl_type)) && base_n > 1) {
5532                 dl_type = htons(ETH_TYPE_MPLS);
5533             } else {
5534                 dl_type = flow->dl_type;
5535             }
5536             nl_msg_put_be16(odp_actions, OVS_ACTION_ATTR_POP_MPLS, dl_type);
5537             popped = flow_pop_mpls(base, base_n, flow->dl_type, NULL);
5538             ovs_assert(popped);
5539             base_n--;
5540         }
5541     }
5542
5543     /* If, after the above popping and setting, there are more LSEs in flow
5544      * than base then some LSEs need to be pushed. */
5545     while (base_n < flow_n) {
5546         struct ovs_action_push_mpls *mpls;
5547
5548         mpls = nl_msg_put_unspec_zero(odp_actions,
5549                                       OVS_ACTION_ATTR_PUSH_MPLS,
5550                                       sizeof *mpls);
5551         mpls->mpls_ethertype = flow->dl_type;
5552         mpls->mpls_lse = flow->mpls_lse[flow_n - base_n - 1];
5553         flow_push_mpls(base, base_n, mpls->mpls_ethertype, NULL);
5554         flow_set_mpls_lse(base, 0, mpls->mpls_lse);
5555         base_n++;
5556     }
5557 }
5558
5559 static void
5560 get_ipv4_key(const struct flow *flow, struct ovs_key_ipv4 *ipv4, bool is_mask)
5561 {
5562     ipv4->ipv4_src = flow->nw_src;
5563     ipv4->ipv4_dst = flow->nw_dst;
5564     ipv4->ipv4_proto = flow->nw_proto;
5565     ipv4->ipv4_tos = flow->nw_tos;
5566     ipv4->ipv4_ttl = flow->nw_ttl;
5567     ipv4->ipv4_frag = ovs_to_odp_frag(flow->nw_frag, is_mask);
5568 }
5569
5570 static void
5571 put_ipv4_key(const struct ovs_key_ipv4 *ipv4, struct flow *flow, bool is_mask)
5572 {
5573     flow->nw_src = ipv4->ipv4_src;
5574     flow->nw_dst = ipv4->ipv4_dst;
5575     flow->nw_proto = ipv4->ipv4_proto;
5576     flow->nw_tos = ipv4->ipv4_tos;
5577     flow->nw_ttl = ipv4->ipv4_ttl;
5578     flow->nw_frag = odp_to_ovs_frag(ipv4->ipv4_frag, is_mask);
5579 }
5580
5581 static void
5582 commit_set_ipv4_action(const struct flow *flow, struct flow *base_flow,
5583                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
5584                        bool use_masked)
5585 {
5586     struct ovs_key_ipv4 key, mask, base;
5587
5588     /* Check that nw_proto and nw_frag remain unchanged. */
5589     ovs_assert(flow->nw_proto == base_flow->nw_proto &&
5590                flow->nw_frag == base_flow->nw_frag);
5591
5592     get_ipv4_key(flow, &key, false);
5593     get_ipv4_key(base_flow, &base, false);
5594     get_ipv4_key(&wc->masks, &mask, true);
5595     mask.ipv4_proto = 0;        /* Not writeable. */
5596     mask.ipv4_frag = 0;         /* Not writable. */
5597
5598     if (commit(OVS_KEY_ATTR_IPV4, use_masked, &key, &base, &mask, sizeof key,
5599                odp_actions)) {
5600         put_ipv4_key(&base, base_flow, false);
5601         if (mask.ipv4_proto != 0) { /* Mask was changed by commit(). */
5602             put_ipv4_key(&mask, &wc->masks, true);
5603         }
5604    }
5605 }
5606
5607 static void
5608 get_ipv6_key(const struct flow *flow, struct ovs_key_ipv6 *ipv6, bool is_mask)
5609 {
5610     memcpy(ipv6->ipv6_src, &flow->ipv6_src, sizeof ipv6->ipv6_src);
5611     memcpy(ipv6->ipv6_dst, &flow->ipv6_dst, sizeof ipv6->ipv6_dst);
5612     ipv6->ipv6_label = flow->ipv6_label;
5613     ipv6->ipv6_proto = flow->nw_proto;
5614     ipv6->ipv6_tclass = flow->nw_tos;
5615     ipv6->ipv6_hlimit = flow->nw_ttl;
5616     ipv6->ipv6_frag = ovs_to_odp_frag(flow->nw_frag, is_mask);
5617 }
5618
5619 static void
5620 put_ipv6_key(const struct ovs_key_ipv6 *ipv6, struct flow *flow, bool is_mask)
5621 {
5622     memcpy(&flow->ipv6_src, ipv6->ipv6_src, sizeof flow->ipv6_src);
5623     memcpy(&flow->ipv6_dst, ipv6->ipv6_dst, sizeof flow->ipv6_dst);
5624     flow->ipv6_label = ipv6->ipv6_label;
5625     flow->nw_proto = ipv6->ipv6_proto;
5626     flow->nw_tos = ipv6->ipv6_tclass;
5627     flow->nw_ttl = ipv6->ipv6_hlimit;
5628     flow->nw_frag = odp_to_ovs_frag(ipv6->ipv6_frag, is_mask);
5629 }
5630
5631 static void
5632 commit_set_ipv6_action(const struct flow *flow, struct flow *base_flow,
5633                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
5634                        bool use_masked)
5635 {
5636     struct ovs_key_ipv6 key, mask, base;
5637
5638     /* Check that nw_proto and nw_frag remain unchanged. */
5639     ovs_assert(flow->nw_proto == base_flow->nw_proto &&
5640                flow->nw_frag == base_flow->nw_frag);
5641
5642     get_ipv6_key(flow, &key, false);
5643     get_ipv6_key(base_flow, &base, false);
5644     get_ipv6_key(&wc->masks, &mask, true);
5645     mask.ipv6_proto = 0;        /* Not writeable. */
5646     mask.ipv6_frag = 0;         /* Not writable. */
5647
5648     if (commit(OVS_KEY_ATTR_IPV6, use_masked, &key, &base, &mask, sizeof key,
5649                odp_actions)) {
5650         put_ipv6_key(&base, base_flow, false);
5651         if (mask.ipv6_proto != 0) { /* Mask was changed by commit(). */
5652             put_ipv6_key(&mask, &wc->masks, true);
5653         }
5654     }
5655 }
5656
5657 static void
5658 get_arp_key(const struct flow *flow, struct ovs_key_arp *arp)
5659 {
5660     /* ARP key has padding, clear it. */
5661     memset(arp, 0, sizeof *arp);
5662
5663     arp->arp_sip = flow->nw_src;
5664     arp->arp_tip = flow->nw_dst;
5665     arp->arp_op = htons(flow->nw_proto);
5666     arp->arp_sha = flow->arp_sha;
5667     arp->arp_tha = flow->arp_tha;
5668 }
5669
5670 static void
5671 put_arp_key(const struct ovs_key_arp *arp, struct flow *flow)
5672 {
5673     flow->nw_src = arp->arp_sip;
5674     flow->nw_dst = arp->arp_tip;
5675     flow->nw_proto = ntohs(arp->arp_op);
5676     flow->arp_sha = arp->arp_sha;
5677     flow->arp_tha = arp->arp_tha;
5678 }
5679
5680 static enum slow_path_reason
5681 commit_set_arp_action(const struct flow *flow, struct flow *base_flow,
5682                       struct ofpbuf *odp_actions, struct flow_wildcards *wc)
5683 {
5684     struct ovs_key_arp key, mask, base;
5685
5686     get_arp_key(flow, &key);
5687     get_arp_key(base_flow, &base);
5688     get_arp_key(&wc->masks, &mask);
5689
5690     if (commit(OVS_KEY_ATTR_ARP, true, &key, &base, &mask, sizeof key,
5691                odp_actions)) {
5692         put_arp_key(&base, base_flow);
5693         put_arp_key(&mask, &wc->masks);
5694         return SLOW_ACTION;
5695     }
5696     return 0;
5697 }
5698
5699 static void
5700 get_icmp_key(const struct flow *flow, struct ovs_key_icmp *icmp)
5701 {
5702     /* icmp_type and icmp_code are stored in tp_src and tp_dst, respectively */
5703     icmp->icmp_type = ntohs(flow->tp_src);
5704     icmp->icmp_code = ntohs(flow->tp_dst);
5705 }
5706
5707 static void
5708 put_icmp_key(const struct ovs_key_icmp *icmp, struct flow *flow)
5709 {
5710     /* icmp_type and icmp_code are stored in tp_src and tp_dst, respectively */
5711     flow->tp_src = htons(icmp->icmp_type);
5712     flow->tp_dst = htons(icmp->icmp_code);
5713 }
5714
5715 static enum slow_path_reason
5716 commit_set_icmp_action(const struct flow *flow, struct flow *base_flow,
5717                        struct ofpbuf *odp_actions, struct flow_wildcards *wc)
5718 {
5719     struct ovs_key_icmp key, mask, base;
5720     enum ovs_key_attr attr;
5721
5722     if (is_icmpv4(flow, NULL)) {
5723         attr = OVS_KEY_ATTR_ICMP;
5724     } else if (is_icmpv6(flow, NULL)) {
5725         attr = OVS_KEY_ATTR_ICMPV6;
5726     } else {
5727         return 0;
5728     }
5729
5730     get_icmp_key(flow, &key);
5731     get_icmp_key(base_flow, &base);
5732     get_icmp_key(&wc->masks, &mask);
5733
5734     if (commit(attr, false, &key, &base, &mask, sizeof key, odp_actions)) {
5735         put_icmp_key(&base, base_flow);
5736         put_icmp_key(&mask, &wc->masks);
5737         return SLOW_ACTION;
5738     }
5739     return 0;
5740 }
5741
5742 static void
5743 get_nd_key(const struct flow *flow, struct ovs_key_nd *nd)
5744 {
5745     memcpy(nd->nd_target, &flow->nd_target, sizeof flow->nd_target);
5746     /* nd_sll and nd_tll are stored in arp_sha and arp_tha, respectively */
5747     nd->nd_sll = flow->arp_sha;
5748     nd->nd_tll = flow->arp_tha;
5749 }
5750
5751 static void
5752 put_nd_key(const struct ovs_key_nd *nd, struct flow *flow)
5753 {
5754     memcpy(&flow->nd_target, nd->nd_target, sizeof flow->nd_target);
5755     /* nd_sll and nd_tll are stored in arp_sha and arp_tha, respectively */
5756     flow->arp_sha = nd->nd_sll;
5757     flow->arp_tha = nd->nd_tll;
5758 }
5759
5760 static enum slow_path_reason
5761 commit_set_nd_action(const struct flow *flow, struct flow *base_flow,
5762                      struct ofpbuf *odp_actions,
5763                      struct flow_wildcards *wc, bool use_masked)
5764 {
5765     struct ovs_key_nd key, mask, base;
5766
5767     get_nd_key(flow, &key);
5768     get_nd_key(base_flow, &base);
5769     get_nd_key(&wc->masks, &mask);
5770
5771     if (commit(OVS_KEY_ATTR_ND, use_masked, &key, &base, &mask, sizeof key,
5772                odp_actions)) {
5773         put_nd_key(&base, base_flow);
5774         put_nd_key(&mask, &wc->masks);
5775         return SLOW_ACTION;
5776     }
5777
5778     return 0;
5779 }
5780
5781 static enum slow_path_reason
5782 commit_set_nw_action(const struct flow *flow, struct flow *base,
5783                      struct ofpbuf *odp_actions, struct flow_wildcards *wc,
5784                      bool use_masked)
5785 {
5786     /* Check if 'flow' really has an L3 header. */
5787     if (!flow->nw_proto) {
5788         return 0;
5789     }
5790
5791     switch (ntohs(base->dl_type)) {
5792     case ETH_TYPE_IP:
5793         commit_set_ipv4_action(flow, base, odp_actions, wc, use_masked);
5794         break;
5795
5796     case ETH_TYPE_IPV6:
5797         commit_set_ipv6_action(flow, base, odp_actions, wc, use_masked);
5798         return commit_set_nd_action(flow, base, odp_actions, wc, use_masked);
5799
5800     case ETH_TYPE_ARP:
5801         return commit_set_arp_action(flow, base, odp_actions, wc);
5802     }
5803
5804     return 0;
5805 }
5806
5807 /* TCP, UDP, and SCTP keys have the same layout. */
5808 BUILD_ASSERT_DECL(sizeof(struct ovs_key_tcp) == sizeof(struct ovs_key_udp) &&
5809                   sizeof(struct ovs_key_tcp) == sizeof(struct ovs_key_sctp));
5810
5811 static void
5812 get_tp_key(const struct flow *flow, union ovs_key_tp *tp)
5813 {
5814     tp->tcp.tcp_src = flow->tp_src;
5815     tp->tcp.tcp_dst = flow->tp_dst;
5816 }
5817
5818 static void
5819 put_tp_key(const union ovs_key_tp *tp, struct flow *flow)
5820 {
5821     flow->tp_src = tp->tcp.tcp_src;
5822     flow->tp_dst = tp->tcp.tcp_dst;
5823 }
5824
5825 static void
5826 commit_set_port_action(const struct flow *flow, struct flow *base_flow,
5827                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
5828                        bool use_masked)
5829 {
5830     enum ovs_key_attr key_type;
5831     union ovs_key_tp key, mask, base;
5832
5833     /* Check if 'flow' really has an L3 header. */
5834     if (!flow->nw_proto) {
5835         return;
5836     }
5837
5838     if (!is_ip_any(base_flow)) {
5839         return;
5840     }
5841
5842     if (flow->nw_proto == IPPROTO_TCP) {
5843         key_type = OVS_KEY_ATTR_TCP;
5844     } else if (flow->nw_proto == IPPROTO_UDP) {
5845         key_type = OVS_KEY_ATTR_UDP;
5846     } else if (flow->nw_proto == IPPROTO_SCTP) {
5847         key_type = OVS_KEY_ATTR_SCTP;
5848     } else {
5849         return;
5850     }
5851
5852     get_tp_key(flow, &key);
5853     get_tp_key(base_flow, &base);
5854     get_tp_key(&wc->masks, &mask);
5855
5856     if (commit(key_type, use_masked, &key, &base, &mask, sizeof key,
5857                odp_actions)) {
5858         put_tp_key(&base, base_flow);
5859         put_tp_key(&mask, &wc->masks);
5860     }
5861 }
5862
5863 static void
5864 commit_set_priority_action(const struct flow *flow, struct flow *base_flow,
5865                            struct ofpbuf *odp_actions,
5866                            struct flow_wildcards *wc,
5867                            bool use_masked)
5868 {
5869     uint32_t key, mask, base;
5870
5871     key = flow->skb_priority;
5872     base = base_flow->skb_priority;
5873     mask = wc->masks.skb_priority;
5874
5875     if (commit(OVS_KEY_ATTR_PRIORITY, use_masked, &key, &base, &mask,
5876                sizeof key, odp_actions)) {
5877         base_flow->skb_priority = base;
5878         wc->masks.skb_priority = mask;
5879     }
5880 }
5881
5882 static void
5883 commit_set_pkt_mark_action(const struct flow *flow, struct flow *base_flow,
5884                            struct ofpbuf *odp_actions,
5885                            struct flow_wildcards *wc,
5886                            bool use_masked)
5887 {
5888     uint32_t key, mask, base;
5889
5890     key = flow->pkt_mark;
5891     base = base_flow->pkt_mark;
5892     mask = wc->masks.pkt_mark;
5893
5894     if (commit(OVS_KEY_ATTR_SKB_MARK, use_masked, &key, &base, &mask,
5895                sizeof key, odp_actions)) {
5896         base_flow->pkt_mark = base;
5897         wc->masks.pkt_mark = mask;
5898     }
5899 }
5900
5901 /* If any of the flow key data that ODP actions can modify are different in
5902  * 'base' and 'flow', appends ODP actions to 'odp_actions' that change the flow
5903  * key from 'base' into 'flow', and then changes 'base' the same way.  Does not
5904  * commit set_tunnel actions.  Users should call commit_odp_tunnel_action()
5905  * in addition to this function if needed.  Sets fields in 'wc' that are
5906  * used as part of the action.
5907  *
5908  * Returns a reason to force processing the flow's packets into the userspace
5909  * slow path, if there is one, otherwise 0. */
5910 enum slow_path_reason
5911 commit_odp_actions(const struct flow *flow, struct flow *base,
5912                    struct ofpbuf *odp_actions, struct flow_wildcards *wc,
5913                    bool use_masked)
5914 {
5915     enum slow_path_reason slow1, slow2;
5916
5917     commit_set_ether_addr_action(flow, base, odp_actions, wc, use_masked);
5918     slow1 = commit_set_nw_action(flow, base, odp_actions, wc, use_masked);
5919     commit_set_port_action(flow, base, odp_actions, wc, use_masked);
5920     slow2 = commit_set_icmp_action(flow, base, odp_actions, wc);
5921     commit_mpls_action(flow, base, odp_actions);
5922     commit_vlan_action(flow->vlan_tci, base, odp_actions, wc);
5923     commit_set_priority_action(flow, base, odp_actions, wc, use_masked);
5924     commit_set_pkt_mark_action(flow, base, odp_actions, wc, use_masked);
5925
5926     return slow1 ? slow1 : slow2;
5927 }