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