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