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