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