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