dpif-netdev: Translate Geneve options per-flow, not per-packet.
[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                         bool udpif)
1269 {
1270     unsigned int left;
1271     const struct nlattr *a;
1272     bool ttl = false;
1273     bool unknown = false;
1274
1275     NL_NESTED_FOR_EACH(a, left, attr) {
1276         uint16_t type = nl_attr_type(a);
1277         size_t len = nl_attr_get_size(a);
1278         int expected_len = odp_key_attr_len(ovs_tun_key_attr_lens,
1279                                             OVS_TUNNEL_ATTR_MAX, type);
1280
1281         if (len != expected_len && expected_len >= 0) {
1282             return ODP_FIT_ERROR;
1283         }
1284
1285         switch (type) {
1286         case OVS_TUNNEL_KEY_ATTR_ID:
1287             tun->tun_id = nl_attr_get_be64(a);
1288             tun->flags |= FLOW_TNL_F_KEY;
1289             break;
1290         case OVS_TUNNEL_KEY_ATTR_IPV4_SRC:
1291             tun->ip_src = nl_attr_get_be32(a);
1292             break;
1293         case OVS_TUNNEL_KEY_ATTR_IPV4_DST:
1294             tun->ip_dst = nl_attr_get_be32(a);
1295             break;
1296         case OVS_TUNNEL_KEY_ATTR_TOS:
1297             tun->ip_tos = nl_attr_get_u8(a);
1298             break;
1299         case OVS_TUNNEL_KEY_ATTR_TTL:
1300             tun->ip_ttl = nl_attr_get_u8(a);
1301             ttl = true;
1302             break;
1303         case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT:
1304             tun->flags |= FLOW_TNL_F_DONT_FRAGMENT;
1305             break;
1306         case OVS_TUNNEL_KEY_ATTR_CSUM:
1307             tun->flags |= FLOW_TNL_F_CSUM;
1308             break;
1309         case OVS_TUNNEL_KEY_ATTR_TP_SRC:
1310             tun->tp_src = nl_attr_get_be16(a);
1311             break;
1312         case OVS_TUNNEL_KEY_ATTR_TP_DST:
1313             tun->tp_dst = nl_attr_get_be16(a);
1314             break;
1315         case OVS_TUNNEL_KEY_ATTR_OAM:
1316             tun->flags |= FLOW_TNL_F_OAM;
1317             break;
1318         case OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS: {
1319             static const struct nl_policy vxlan_opts_policy[] = {
1320                 [OVS_VXLAN_EXT_GBP] = { .type = NL_A_U32 },
1321             };
1322             struct nlattr *ext[ARRAY_SIZE(vxlan_opts_policy)];
1323
1324             if (!nl_parse_nested(a, vxlan_opts_policy, ext, ARRAY_SIZE(ext))) {
1325                 return ODP_FIT_ERROR;
1326             }
1327
1328             if (ext[OVS_VXLAN_EXT_GBP]) {
1329                 uint32_t gbp = nl_attr_get_u32(ext[OVS_VXLAN_EXT_GBP]);
1330
1331                 tun->gbp_id = htons(gbp & 0xFFFF);
1332                 tun->gbp_flags = (gbp >> 16) & 0xFF;
1333             }
1334
1335             break;
1336         }
1337         case OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS:
1338             if (tun_metadata_from_geneve_nlattr(a, flow_attrs, flow_attr_len,
1339                                                 src_tun, udpif, tun)) {
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, bool udpif,
1363                       struct flow_tnl *tun)
1364 {
1365     memset(tun, 0, sizeof *tun);
1366     return odp_tun_key_from_attr__(attr, NULL, 0, NULL, tun, udpif);
1367 }
1368
1369 static void
1370 tun_key_to_attr(struct ofpbuf *a, const struct flow_tnl *tun_key,
1371                 const struct flow_tnl *tun_flow_key,
1372                 const struct ofpbuf *key_buf)
1373 {
1374     size_t tun_key_ofs;
1375
1376     tun_key_ofs = nl_msg_start_nested(a, OVS_KEY_ATTR_TUNNEL);
1377
1378     /* tun_id != 0 without FLOW_TNL_F_KEY is valid if tun_key is a mask. */
1379     if (tun_key->tun_id || tun_key->flags & FLOW_TNL_F_KEY) {
1380         nl_msg_put_be64(a, OVS_TUNNEL_KEY_ATTR_ID, tun_key->tun_id);
1381     }
1382     if (tun_key->ip_src) {
1383         nl_msg_put_be32(a, OVS_TUNNEL_KEY_ATTR_IPV4_SRC, tun_key->ip_src);
1384     }
1385     if (tun_key->ip_dst) {
1386         nl_msg_put_be32(a, OVS_TUNNEL_KEY_ATTR_IPV4_DST, tun_key->ip_dst);
1387     }
1388     if (tun_key->ip_tos) {
1389         nl_msg_put_u8(a, OVS_TUNNEL_KEY_ATTR_TOS, tun_key->ip_tos);
1390     }
1391     nl_msg_put_u8(a, OVS_TUNNEL_KEY_ATTR_TTL, tun_key->ip_ttl);
1392     if (tun_key->flags & FLOW_TNL_F_DONT_FRAGMENT) {
1393         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT);
1394     }
1395     if (tun_key->flags & FLOW_TNL_F_CSUM) {
1396         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_CSUM);
1397     }
1398     if (tun_key->tp_src) {
1399         nl_msg_put_be16(a, OVS_TUNNEL_KEY_ATTR_TP_SRC, tun_key->tp_src);
1400     }
1401     if (tun_key->tp_dst) {
1402         nl_msg_put_be16(a, OVS_TUNNEL_KEY_ATTR_TP_DST, tun_key->tp_dst);
1403     }
1404     if (tun_key->flags & FLOW_TNL_F_OAM) {
1405         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_OAM);
1406     }
1407     if (tun_key->gbp_flags || tun_key->gbp_id) {
1408         size_t vxlan_opts_ofs;
1409
1410         vxlan_opts_ofs = nl_msg_start_nested(a, OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS);
1411         nl_msg_put_u32(a, OVS_VXLAN_EXT_GBP,
1412                        (tun_key->gbp_flags << 16) | ntohs(tun_key->gbp_id));
1413         nl_msg_end_nested(a, vxlan_opts_ofs);
1414     }
1415     tun_metadata_to_geneve_nlattr(tun_key, tun_flow_key, key_buf, a);
1416
1417     nl_msg_end_nested(a, tun_key_ofs);
1418 }
1419
1420 static bool
1421 odp_mask_attr_is_wildcard(const struct nlattr *ma)
1422 {
1423     return is_all_zeros(nl_attr_get(ma), nl_attr_get_size(ma));
1424 }
1425
1426 static bool
1427 odp_mask_is_exact(enum ovs_key_attr attr, const void *mask, size_t size)
1428 {
1429     if (attr == OVS_KEY_ATTR_TCP_FLAGS) {
1430         return TCP_FLAGS(*(ovs_be16 *)mask) == TCP_FLAGS(OVS_BE16_MAX);
1431     }
1432     if (attr == OVS_KEY_ATTR_IPV6) {
1433         const struct ovs_key_ipv6 *ipv6_mask = mask;
1434
1435         return
1436             ((ipv6_mask->ipv6_label & htonl(IPV6_LABEL_MASK))
1437              == htonl(IPV6_LABEL_MASK))
1438             && ipv6_mask->ipv6_proto == UINT8_MAX
1439             && ipv6_mask->ipv6_tclass == UINT8_MAX
1440             && ipv6_mask->ipv6_hlimit == UINT8_MAX
1441             && ipv6_mask->ipv6_frag == UINT8_MAX
1442             && ipv6_mask_is_exact((const struct in6_addr *)ipv6_mask->ipv6_src)
1443             && ipv6_mask_is_exact((const struct in6_addr *)ipv6_mask->ipv6_dst);
1444     }
1445     if (attr == OVS_KEY_ATTR_TUNNEL) {
1446         return false;
1447     }
1448
1449     if (attr == OVS_KEY_ATTR_ARP) {
1450         /* ARP key has padding, ignore it. */
1451         BUILD_ASSERT_DECL(sizeof(struct ovs_key_arp) == 24);
1452         BUILD_ASSERT_DECL(offsetof(struct ovs_key_arp, arp_tha) == 10 + 6);
1453         size = offsetof(struct ovs_key_arp, arp_tha) + ETH_ADDR_LEN;
1454         ovs_assert(((uint16_t *)mask)[size/2] == 0);
1455     }
1456
1457     return is_all_ones(mask, size);
1458 }
1459
1460 static bool
1461 odp_mask_attr_is_exact(const struct nlattr *ma)
1462 {
1463     enum ovs_key_attr attr = nl_attr_type(ma);
1464     const void *mask;
1465     size_t size;
1466
1467     if (attr == OVS_KEY_ATTR_TUNNEL) {
1468         return false;
1469     } else {
1470         mask = nl_attr_get(ma);
1471         size = nl_attr_get_size(ma);
1472     }
1473
1474     return odp_mask_is_exact(attr, mask, size);
1475 }
1476
1477 void
1478 odp_portno_names_set(struct hmap *portno_names, odp_port_t port_no,
1479                      char *port_name)
1480 {
1481     struct odp_portno_names *odp_portno_names;
1482
1483     odp_portno_names = xmalloc(sizeof *odp_portno_names);
1484     odp_portno_names->port_no = port_no;
1485     odp_portno_names->name = xstrdup(port_name);
1486     hmap_insert(portno_names, &odp_portno_names->hmap_node,
1487                 hash_odp_port(port_no));
1488 }
1489
1490 static char *
1491 odp_portno_names_get(const struct hmap *portno_names, odp_port_t port_no)
1492 {
1493     struct odp_portno_names *odp_portno_names;
1494
1495     HMAP_FOR_EACH_IN_BUCKET (odp_portno_names, hmap_node,
1496                              hash_odp_port(port_no), portno_names) {
1497         if (odp_portno_names->port_no == port_no) {
1498             return odp_portno_names->name;
1499         }
1500     }
1501     return NULL;
1502 }
1503
1504 void
1505 odp_portno_names_destroy(struct hmap *portno_names)
1506 {
1507     struct odp_portno_names *odp_portno_names, *odp_portno_names_next;
1508     HMAP_FOR_EACH_SAFE (odp_portno_names, odp_portno_names_next,
1509                         hmap_node, portno_names) {
1510         hmap_remove(portno_names, &odp_portno_names->hmap_node);
1511         free(odp_portno_names->name);
1512         free(odp_portno_names);
1513     }
1514 }
1515
1516 /* Format helpers. */
1517
1518 static void
1519 format_eth(struct ds *ds, const char *name, const uint8_t key[ETH_ADDR_LEN],
1520            const uint8_t (*mask)[ETH_ADDR_LEN], bool verbose)
1521 {
1522     bool mask_empty = mask && eth_addr_is_zero(*mask);
1523
1524     if (verbose || !mask_empty) {
1525         bool mask_full = !mask || eth_mask_is_exact(*mask);
1526
1527         if (mask_full) {
1528             ds_put_format(ds, "%s="ETH_ADDR_FMT",", name, ETH_ADDR_ARGS(key));
1529         } else {
1530             ds_put_format(ds, "%s=", name);
1531             eth_format_masked(key, *mask, ds);
1532             ds_put_char(ds, ',');
1533         }
1534     }
1535 }
1536
1537 static void
1538 format_be64(struct ds *ds, const char *name, ovs_be64 key,
1539             const ovs_be64 *mask, bool verbose)
1540 {
1541     bool mask_empty = mask && !*mask;
1542
1543     if (verbose || !mask_empty) {
1544         bool mask_full = !mask || *mask == OVS_BE64_MAX;
1545
1546         ds_put_format(ds, "%s=0x%"PRIx64, name, ntohll(key));
1547         if (!mask_full) { /* Partially masked. */
1548             ds_put_format(ds, "/%#"PRIx64, ntohll(*mask));
1549         }
1550         ds_put_char(ds, ',');
1551     }
1552 }
1553
1554 static void
1555 format_ipv4(struct ds *ds, const char *name, ovs_be32 key,
1556             const ovs_be32 *mask, bool verbose)
1557 {
1558     bool mask_empty = mask && !*mask;
1559
1560     if (verbose || !mask_empty) {
1561         bool mask_full = !mask || *mask == OVS_BE32_MAX;
1562
1563         ds_put_format(ds, "%s="IP_FMT, name, IP_ARGS(key));
1564         if (!mask_full) { /* Partially masked. */
1565             ds_put_format(ds, "/"IP_FMT, IP_ARGS(*mask));
1566         }
1567         ds_put_char(ds, ',');
1568     }
1569 }
1570
1571 static void
1572 format_ipv6(struct ds *ds, const char *name, const ovs_be32 key_[4],
1573             const ovs_be32 (*mask_)[4], bool verbose)
1574 {
1575     char buf[INET6_ADDRSTRLEN];
1576     const struct in6_addr *key = (const struct in6_addr *)key_;
1577     const struct in6_addr *mask = mask_ ? (const struct in6_addr *)*mask_
1578         : NULL;
1579     bool mask_empty = mask && ipv6_mask_is_any(mask);
1580
1581     if (verbose || !mask_empty) {
1582         bool mask_full = !mask || ipv6_mask_is_exact(mask);
1583
1584         inet_ntop(AF_INET6, key, buf, sizeof buf);
1585         ds_put_format(ds, "%s=%s", name, buf);
1586         if (!mask_full) { /* Partially masked. */
1587             inet_ntop(AF_INET6, mask, buf, sizeof buf);
1588             ds_put_format(ds, "/%s", buf);
1589         }
1590         ds_put_char(ds, ',');
1591     }
1592 }
1593
1594 static void
1595 format_ipv6_label(struct ds *ds, const char *name, ovs_be32 key,
1596                   const ovs_be32 *mask, bool verbose)
1597 {
1598     bool mask_empty = mask && !*mask;
1599
1600     if (verbose || !mask_empty) {
1601         bool mask_full = !mask
1602             || (*mask & htonl(IPV6_LABEL_MASK)) == htonl(IPV6_LABEL_MASK);
1603
1604         ds_put_format(ds, "%s=%#"PRIx32, name, ntohl(key));
1605         if (!mask_full) { /* Partially masked. */
1606             ds_put_format(ds, "/%#"PRIx32, ntohl(*mask));
1607         }
1608         ds_put_char(ds, ',');
1609     }
1610 }
1611
1612 static void
1613 format_u8x(struct ds *ds, const char *name, uint8_t key,
1614            const uint8_t *mask, bool verbose)
1615 {
1616     bool mask_empty = mask && !*mask;
1617
1618     if (verbose || !mask_empty) {
1619         bool mask_full = !mask || *mask == UINT8_MAX;
1620
1621         ds_put_format(ds, "%s=%#"PRIx8, name, key);
1622         if (!mask_full) { /* Partially masked. */
1623             ds_put_format(ds, "/%#"PRIx8, *mask);
1624         }
1625         ds_put_char(ds, ',');
1626     }
1627 }
1628
1629 static void
1630 format_u8u(struct ds *ds, const char *name, uint8_t key,
1631            const uint8_t *mask, bool verbose)
1632 {
1633     bool mask_empty = mask && !*mask;
1634
1635     if (verbose || !mask_empty) {
1636         bool mask_full = !mask || *mask == UINT8_MAX;
1637
1638         ds_put_format(ds, "%s=%"PRIu8, name, key);
1639         if (!mask_full) { /* Partially masked. */
1640             ds_put_format(ds, "/%#"PRIx8, *mask);
1641         }
1642         ds_put_char(ds, ',');
1643     }
1644 }
1645
1646 static void
1647 format_be16(struct ds *ds, const char *name, ovs_be16 key,
1648             const ovs_be16 *mask, bool verbose)
1649 {
1650     bool mask_empty = mask && !*mask;
1651
1652     if (verbose || !mask_empty) {
1653         bool mask_full = !mask || *mask == OVS_BE16_MAX;
1654
1655         ds_put_format(ds, "%s=%"PRIu16, name, ntohs(key));
1656         if (!mask_full) { /* Partially masked. */
1657             ds_put_format(ds, "/%#"PRIx16, ntohs(*mask));
1658         }
1659         ds_put_char(ds, ',');
1660     }
1661 }
1662
1663 static void
1664 format_be16x(struct ds *ds, const char *name, ovs_be16 key,
1665              const ovs_be16 *mask, bool verbose)
1666 {
1667     bool mask_empty = mask && !*mask;
1668
1669     if (verbose || !mask_empty) {
1670         bool mask_full = !mask || *mask == OVS_BE16_MAX;
1671
1672         ds_put_format(ds, "%s=%#"PRIx16, name, ntohs(key));
1673         if (!mask_full) { /* Partially masked. */
1674             ds_put_format(ds, "/%#"PRIx16, ntohs(*mask));
1675         }
1676         ds_put_char(ds, ',');
1677     }
1678 }
1679
1680 static void
1681 format_tun_flags(struct ds *ds, const char *name, uint16_t key,
1682                  const uint16_t *mask, bool verbose)
1683 {
1684     bool mask_empty = mask && !*mask;
1685
1686     if (verbose || !mask_empty) {
1687         ds_put_cstr(ds, name);
1688         ds_put_char(ds, '(');
1689         if (mask) {
1690             format_flags_masked(ds, NULL, flow_tun_flag_to_string, key,
1691                                 *mask & FLOW_TNL_F_MASK, FLOW_TNL_F_MASK);
1692         } else { /* Fully masked. */
1693             format_flags(ds, flow_tun_flag_to_string, key, '|');
1694         }
1695         ds_put_cstr(ds, "),");
1696     }
1697 }
1698
1699 static bool
1700 check_attr_len(struct ds *ds, const struct nlattr *a, const struct nlattr *ma,
1701                const struct attr_len_tbl tbl[], int max_len, bool need_key)
1702 {
1703     int expected_len;
1704
1705     expected_len = odp_key_attr_len(tbl, max_len, nl_attr_type(a));
1706     if (expected_len != ATTR_LEN_VARIABLE &&
1707         expected_len != ATTR_LEN_NESTED) {
1708
1709         bool bad_key_len = nl_attr_get_size(a) != expected_len;
1710         bool bad_mask_len = ma && nl_attr_get_size(ma) != expected_len;
1711
1712         if (bad_key_len || bad_mask_len) {
1713             if (need_key) {
1714                 ds_put_format(ds, "key%u", nl_attr_type(a));
1715             }
1716             if (bad_key_len) {
1717                 ds_put_format(ds, "(bad key length %"PRIuSIZE", expected %d)(",
1718                               nl_attr_get_size(a), expected_len);
1719             }
1720             format_generic_odp_key(a, ds);
1721             if (ma) {
1722                 ds_put_char(ds, '/');
1723                 if (bad_mask_len) {
1724                     ds_put_format(ds, "(bad mask length %"PRIuSIZE", expected %d)(",
1725                                   nl_attr_get_size(ma), expected_len);
1726                 }
1727                 format_generic_odp_key(ma, ds);
1728             }
1729             ds_put_char(ds, ')');
1730             return false;
1731         }
1732     }
1733
1734     return true;
1735 }
1736
1737 static void
1738 format_unknown_key(struct ds *ds, const struct nlattr *a,
1739                    const struct nlattr *ma)
1740 {
1741     ds_put_format(ds, "key%u(", nl_attr_type(a));
1742     format_generic_odp_key(a, ds);
1743     if (ma && !odp_mask_attr_is_exact(ma)) {
1744         ds_put_char(ds, '/');
1745         format_generic_odp_key(ma, ds);
1746     }
1747     ds_put_cstr(ds, "),");
1748 }
1749
1750 static void
1751 format_odp_tun_vxlan_opt(const struct nlattr *attr,
1752                          const struct nlattr *mask_attr, struct ds *ds,
1753                          bool verbose)
1754 {
1755     unsigned int left;
1756     const struct nlattr *a;
1757     struct ofpbuf ofp;
1758
1759     ofpbuf_init(&ofp, 100);
1760     NL_NESTED_FOR_EACH(a, left, attr) {
1761         uint16_t type = nl_attr_type(a);
1762         const struct nlattr *ma = NULL;
1763
1764         if (mask_attr) {
1765             ma = nl_attr_find__(nl_attr_get(mask_attr),
1766                                 nl_attr_get_size(mask_attr), type);
1767             if (!ma) {
1768                 ma = generate_all_wildcard_mask(ovs_vxlan_ext_attr_lens,
1769                                                 OVS_VXLAN_EXT_MAX,
1770                                                 &ofp, a);
1771             }
1772         }
1773
1774         if (!check_attr_len(ds, a, ma, ovs_vxlan_ext_attr_lens,
1775                             OVS_VXLAN_EXT_MAX, true)) {
1776             continue;
1777         }
1778
1779         switch (type) {
1780         case OVS_VXLAN_EXT_GBP: {
1781             uint32_t key = nl_attr_get_u32(a);
1782             ovs_be16 id, id_mask;
1783             uint8_t flags, flags_mask;
1784
1785             id = htons(key & 0xFFFF);
1786             flags = (key >> 16) & 0xFF;
1787             if (ma) {
1788                 uint32_t mask = nl_attr_get_u32(ma);
1789                 id_mask = htons(mask & 0xFFFF);
1790                 flags_mask = (mask >> 16) & 0xFF;
1791             }
1792
1793             ds_put_cstr(ds, "gbp(");
1794             format_be16(ds, "id", id, ma ? &id_mask : NULL, verbose);
1795             format_u8x(ds, "flags", flags, ma ? &flags_mask : NULL, verbose);
1796             ds_chomp(ds, ',');
1797             ds_put_cstr(ds, "),");
1798             break;
1799         }
1800
1801         default:
1802             format_unknown_key(ds, a, ma);
1803         }
1804         ofpbuf_clear(&ofp);
1805     }
1806
1807     ds_chomp(ds, ',');
1808     ofpbuf_uninit(&ofp);
1809 }
1810
1811 #define MASK(PTR, FIELD) PTR ? &PTR->FIELD : NULL
1812
1813 static void
1814 format_geneve_opts(const struct geneve_opt *opt,
1815                    const struct geneve_opt *mask, int opts_len,
1816                    struct ds *ds, bool verbose)
1817 {
1818     while (opts_len > 0) {
1819         unsigned int len;
1820         uint8_t data_len, data_len_mask;
1821
1822         if (opts_len < sizeof *opt) {
1823             ds_put_format(ds, "opt len %u less than minimum %"PRIuSIZE,
1824                           opts_len, sizeof *opt);
1825             return;
1826         }
1827
1828         data_len = opt->length * 4;
1829         if (mask) {
1830             if (mask->length == 0x1f) {
1831                 data_len_mask = UINT8_MAX;
1832             } else {
1833                 data_len_mask = mask->length;
1834             }
1835         }
1836         len = sizeof *opt + data_len;
1837         if (len > opts_len) {
1838             ds_put_format(ds, "opt len %u greater than remaining %u",
1839                           len, opts_len);
1840             return;
1841         }
1842
1843         ds_put_char(ds, '{');
1844         format_be16x(ds, "class", opt->opt_class, MASK(mask, opt_class),
1845                     verbose);
1846         format_u8x(ds, "type", opt->type, MASK(mask, type), verbose);
1847         format_u8u(ds, "len", data_len, mask ? &data_len_mask : NULL, verbose);
1848         if (verbose || !mask || !is_all_zeros(mask + 1, data_len)) {
1849             ds_put_hex(ds, opt + 1, data_len);
1850             if (mask && !is_all_ones(mask + 1, data_len)) {
1851                 ds_put_char(ds, '/');
1852                 ds_put_hex(ds, mask + 1, data_len);
1853             }
1854         } else {
1855             ds_chomp(ds, ',');
1856         }
1857         ds_put_char(ds, '}');
1858
1859         opt += len / sizeof(*opt);
1860         if (mask) {
1861             mask += len / sizeof(*opt);
1862         }
1863         opts_len -= len;
1864     };
1865 }
1866
1867 static void
1868 format_odp_tun_geneve(const struct nlattr *attr,
1869                       const struct nlattr *mask_attr, struct ds *ds,
1870                       bool verbose)
1871 {
1872     int opts_len = nl_attr_get_size(attr);
1873     const struct geneve_opt *opt = nl_attr_get(attr);
1874     const struct geneve_opt *mask = mask_attr ?
1875                                     nl_attr_get(mask_attr) : NULL;
1876
1877     if (mask && nl_attr_get_size(attr) != nl_attr_get_size(mask_attr)) {
1878         ds_put_format(ds, "value len %"PRIuSIZE" different from mask len %"PRIuSIZE,
1879                       nl_attr_get_size(attr), nl_attr_get_size(mask_attr));
1880         return;
1881     }
1882
1883     format_geneve_opts(opt, mask, opts_len, ds, verbose);
1884 }
1885
1886 static void
1887 format_odp_tun_attr(const struct nlattr *attr, const struct nlattr *mask_attr,
1888                     struct ds *ds, bool verbose)
1889 {
1890     unsigned int left;
1891     const struct nlattr *a;
1892     uint16_t flags = 0;
1893     uint16_t mask_flags = 0;
1894     struct ofpbuf ofp;
1895
1896     ofpbuf_init(&ofp, 100);
1897     NL_NESTED_FOR_EACH(a, left, attr) {
1898         enum ovs_tunnel_key_attr type = nl_attr_type(a);
1899         const struct nlattr *ma = NULL;
1900
1901         if (mask_attr) {
1902             ma = nl_attr_find__(nl_attr_get(mask_attr),
1903                                 nl_attr_get_size(mask_attr), type);
1904             if (!ma) {
1905                 ma = generate_all_wildcard_mask(ovs_tun_key_attr_lens,
1906                                                 OVS_TUNNEL_KEY_ATTR_MAX,
1907                                                 &ofp, a);
1908             }
1909         }
1910
1911         if (!check_attr_len(ds, a, ma, ovs_tun_key_attr_lens,
1912                             OVS_TUNNEL_KEY_ATTR_MAX, true)) {
1913             continue;
1914         }
1915
1916         switch (type) {
1917         case OVS_TUNNEL_KEY_ATTR_ID:
1918             format_be64(ds, "tun_id", nl_attr_get_be64(a),
1919                         ma ? nl_attr_get(ma) : NULL, verbose);
1920             flags |= FLOW_TNL_F_KEY;
1921             if (ma) {
1922                 mask_flags |= FLOW_TNL_F_KEY;
1923             }
1924             break;
1925         case OVS_TUNNEL_KEY_ATTR_IPV4_SRC:
1926             format_ipv4(ds, "src", nl_attr_get_be32(a),
1927                         ma ? nl_attr_get(ma) : NULL, verbose);
1928             break;
1929         case OVS_TUNNEL_KEY_ATTR_IPV4_DST:
1930             format_ipv4(ds, "dst", nl_attr_get_be32(a),
1931                         ma ? nl_attr_get(ma) : NULL, verbose);
1932             break;
1933         case OVS_TUNNEL_KEY_ATTR_TOS:
1934             format_u8x(ds, "tos", nl_attr_get_u8(a),
1935                        ma ? nl_attr_get(ma) : NULL, verbose);
1936             break;
1937         case OVS_TUNNEL_KEY_ATTR_TTL:
1938             format_u8u(ds, "ttl", nl_attr_get_u8(a),
1939                        ma ? nl_attr_get(ma) : NULL, verbose);
1940             break;
1941         case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT:
1942             flags |= FLOW_TNL_F_DONT_FRAGMENT;
1943             break;
1944         case OVS_TUNNEL_KEY_ATTR_CSUM:
1945             flags |= FLOW_TNL_F_CSUM;
1946             break;
1947         case OVS_TUNNEL_KEY_ATTR_TP_SRC:
1948             format_be16(ds, "tp_src", nl_attr_get_be16(a),
1949                         ma ? nl_attr_get(ma) : NULL, verbose);
1950             break;
1951         case OVS_TUNNEL_KEY_ATTR_TP_DST:
1952             format_be16(ds, "tp_dst", nl_attr_get_be16(a),
1953                         ma ? nl_attr_get(ma) : NULL, verbose);
1954             break;
1955         case OVS_TUNNEL_KEY_ATTR_OAM:
1956             flags |= FLOW_TNL_F_OAM;
1957             break;
1958         case OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS:
1959             ds_put_cstr(ds, "vxlan(");
1960             format_odp_tun_vxlan_opt(a, ma, ds, verbose);
1961             ds_put_cstr(ds, "),");
1962             break;
1963         case OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS:
1964             ds_put_cstr(ds, "geneve(");
1965             format_odp_tun_geneve(a, ma, ds, verbose);
1966             ds_put_cstr(ds, "),");
1967             break;
1968         case __OVS_TUNNEL_KEY_ATTR_MAX:
1969         default:
1970             format_unknown_key(ds, a, ma);
1971         }
1972         ofpbuf_clear(&ofp);
1973     }
1974
1975     /* Flags can have a valid mask even if the attribute is not set, so
1976      * we need to collect these separately. */
1977     if (mask_attr) {
1978         NL_NESTED_FOR_EACH(a, left, mask_attr) {
1979             switch (nl_attr_type(a)) {
1980             case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT:
1981                 mask_flags |= FLOW_TNL_F_DONT_FRAGMENT;
1982                 break;
1983             case OVS_TUNNEL_KEY_ATTR_CSUM:
1984                 mask_flags |= FLOW_TNL_F_CSUM;
1985                 break;
1986             case OVS_TUNNEL_KEY_ATTR_OAM:
1987                 mask_flags |= FLOW_TNL_F_OAM;
1988                 break;
1989             }
1990         }
1991     }
1992
1993     format_tun_flags(ds, "flags", flags, mask_attr ? &mask_flags : NULL,
1994                      verbose);
1995     ds_chomp(ds, ',');
1996     ofpbuf_uninit(&ofp);
1997 }
1998
1999 static void
2000 format_frag(struct ds *ds, const char *name, uint8_t key,
2001             const uint8_t *mask, bool verbose)
2002 {
2003     bool mask_empty = mask && !*mask;
2004
2005     /* ODP frag is an enumeration field; partial masks are not meaningful. */
2006     if (verbose || !mask_empty) {
2007         bool mask_full = !mask || *mask == UINT8_MAX;
2008
2009         if (!mask_full) { /* Partially masked. */
2010             ds_put_format(ds, "error: partial mask not supported for frag (%#"
2011                           PRIx8"),", *mask);
2012         } else {
2013             ds_put_format(ds, "%s=%s,", name, ovs_frag_type_to_string(key));
2014         }
2015     }
2016 }
2017
2018 static void
2019 format_odp_key_attr(const struct nlattr *a, const struct nlattr *ma,
2020                     const struct hmap *portno_names, struct ds *ds,
2021                     bool verbose)
2022 {
2023     enum ovs_key_attr attr = nl_attr_type(a);
2024     char namebuf[OVS_KEY_ATTR_BUFSIZE];
2025     bool is_exact;
2026
2027     is_exact = ma ? odp_mask_attr_is_exact(ma) : true;
2028
2029     ds_put_cstr(ds, ovs_key_attr_to_string(attr, namebuf, sizeof namebuf));
2030
2031     if (!check_attr_len(ds, a, ma, ovs_flow_key_attr_lens,
2032                         OVS_KEY_ATTR_MAX, false)) {
2033         return;
2034     }
2035
2036     ds_put_char(ds, '(');
2037     switch (attr) {
2038     case OVS_KEY_ATTR_ENCAP:
2039         if (ma && nl_attr_get_size(ma) && nl_attr_get_size(a)) {
2040             odp_flow_format(nl_attr_get(a), nl_attr_get_size(a),
2041                             nl_attr_get(ma), nl_attr_get_size(ma), NULL, ds,
2042                             verbose);
2043         } else if (nl_attr_get_size(a)) {
2044             odp_flow_format(nl_attr_get(a), nl_attr_get_size(a), NULL, 0, NULL,
2045                             ds, verbose);
2046         }
2047         break;
2048
2049     case OVS_KEY_ATTR_PRIORITY:
2050     case OVS_KEY_ATTR_SKB_MARK:
2051     case OVS_KEY_ATTR_DP_HASH:
2052     case OVS_KEY_ATTR_RECIRC_ID:
2053         ds_put_format(ds, "%#"PRIx32, nl_attr_get_u32(a));
2054         if (!is_exact) {
2055             ds_put_format(ds, "/%#"PRIx32, nl_attr_get_u32(ma));
2056         }
2057         break;
2058
2059     case OVS_KEY_ATTR_TUNNEL:
2060         format_odp_tun_attr(a, ma, ds, verbose);
2061         break;
2062
2063     case OVS_KEY_ATTR_IN_PORT:
2064         if (portno_names && verbose && is_exact) {
2065             char *name = odp_portno_names_get(portno_names,
2066                             u32_to_odp(nl_attr_get_u32(a)));
2067             if (name) {
2068                 ds_put_format(ds, "%s", name);
2069             } else {
2070                 ds_put_format(ds, "%"PRIu32, nl_attr_get_u32(a));
2071             }
2072         } else {
2073             ds_put_format(ds, "%"PRIu32, nl_attr_get_u32(a));
2074             if (!is_exact) {
2075                 ds_put_format(ds, "/%#"PRIx32, nl_attr_get_u32(ma));
2076             }
2077         }
2078         break;
2079
2080     case OVS_KEY_ATTR_ETHERNET: {
2081         const struct ovs_key_ethernet *mask = ma ? nl_attr_get(ma) : NULL;
2082         const struct ovs_key_ethernet *key = nl_attr_get(a);
2083
2084         format_eth(ds, "src", key->eth_src, MASK(mask, eth_src), verbose);
2085         format_eth(ds, "dst", key->eth_dst, MASK(mask, eth_dst), verbose);
2086         ds_chomp(ds, ',');
2087         break;
2088     }
2089     case OVS_KEY_ATTR_VLAN:
2090         format_vlan_tci(ds, nl_attr_get_be16(a),
2091                         ma ? nl_attr_get_be16(ma) : OVS_BE16_MAX, verbose);
2092         break;
2093
2094     case OVS_KEY_ATTR_MPLS: {
2095         const struct ovs_key_mpls *mpls_key = nl_attr_get(a);
2096         const struct ovs_key_mpls *mpls_mask = NULL;
2097         size_t size = nl_attr_get_size(a);
2098
2099         if (!size || size % sizeof *mpls_key) {
2100             ds_put_format(ds, "(bad key length %"PRIuSIZE")", size);
2101             return;
2102         }
2103         if (!is_exact) {
2104             mpls_mask = nl_attr_get(ma);
2105             if (size != nl_attr_get_size(ma)) {
2106                 ds_put_format(ds, "(key length %"PRIuSIZE" != "
2107                               "mask length %"PRIuSIZE")",
2108                               size, nl_attr_get_size(ma));
2109                 return;
2110             }
2111         }
2112         format_mpls(ds, mpls_key, mpls_mask, size / sizeof *mpls_key);
2113         break;
2114     }
2115     case OVS_KEY_ATTR_ETHERTYPE:
2116         ds_put_format(ds, "0x%04"PRIx16, ntohs(nl_attr_get_be16(a)));
2117         if (!is_exact) {
2118             ds_put_format(ds, "/0x%04"PRIx16, ntohs(nl_attr_get_be16(ma)));
2119         }
2120         break;
2121
2122     case OVS_KEY_ATTR_IPV4: {
2123         const struct ovs_key_ipv4 *key = nl_attr_get(a);
2124         const struct ovs_key_ipv4 *mask = ma ? nl_attr_get(ma) : NULL;
2125
2126         format_ipv4(ds, "src", key->ipv4_src, MASK(mask, ipv4_src), verbose);
2127         format_ipv4(ds, "dst", key->ipv4_dst, MASK(mask, ipv4_dst), verbose);
2128         format_u8u(ds, "proto", key->ipv4_proto, MASK(mask, ipv4_proto),
2129                       verbose);
2130         format_u8x(ds, "tos", key->ipv4_tos, MASK(mask, ipv4_tos), verbose);
2131         format_u8u(ds, "ttl", key->ipv4_ttl, MASK(mask, ipv4_ttl), verbose);
2132         format_frag(ds, "frag", key->ipv4_frag, MASK(mask, ipv4_frag),
2133                     verbose);
2134         ds_chomp(ds, ',');
2135         break;
2136     }
2137     case OVS_KEY_ATTR_IPV6: {
2138         const struct ovs_key_ipv6 *key = nl_attr_get(a);
2139         const struct ovs_key_ipv6 *mask = ma ? nl_attr_get(ma) : NULL;
2140
2141         format_ipv6(ds, "src", key->ipv6_src, MASK(mask, ipv6_src), verbose);
2142         format_ipv6(ds, "dst", key->ipv6_dst, MASK(mask, ipv6_dst), verbose);
2143         format_ipv6_label(ds, "label", key->ipv6_label, MASK(mask, ipv6_label),
2144                           verbose);
2145         format_u8u(ds, "proto", key->ipv6_proto, MASK(mask, ipv6_proto),
2146                       verbose);
2147         format_u8x(ds, "tclass", key->ipv6_tclass, MASK(mask, ipv6_tclass),
2148                       verbose);
2149         format_u8u(ds, "hlimit", key->ipv6_hlimit, MASK(mask, ipv6_hlimit),
2150                       verbose);
2151         format_frag(ds, "frag", key->ipv6_frag, MASK(mask, ipv6_frag),
2152                     verbose);
2153         ds_chomp(ds, ',');
2154         break;
2155     }
2156         /* These have the same structure and format. */
2157     case OVS_KEY_ATTR_TCP:
2158     case OVS_KEY_ATTR_UDP:
2159     case OVS_KEY_ATTR_SCTP: {
2160         const struct ovs_key_tcp *key = nl_attr_get(a);
2161         const struct ovs_key_tcp *mask = ma ? nl_attr_get(ma) : NULL;
2162
2163         format_be16(ds, "src", key->tcp_src, MASK(mask, tcp_src), verbose);
2164         format_be16(ds, "dst", key->tcp_dst, MASK(mask, tcp_dst), verbose);
2165         ds_chomp(ds, ',');
2166         break;
2167     }
2168     case OVS_KEY_ATTR_TCP_FLAGS:
2169         if (!is_exact) {
2170             format_flags_masked(ds, NULL, packet_tcp_flag_to_string,
2171                                 ntohs(nl_attr_get_be16(a)),
2172                                 TCP_FLAGS(nl_attr_get_be16(ma)),
2173                                 TCP_FLAGS(OVS_BE16_MAX));
2174         } else {
2175             format_flags(ds, packet_tcp_flag_to_string,
2176                          ntohs(nl_attr_get_be16(a)), '|');
2177         }
2178         break;
2179
2180     case OVS_KEY_ATTR_ICMP: {
2181         const struct ovs_key_icmp *key = nl_attr_get(a);
2182         const struct ovs_key_icmp *mask = ma ? nl_attr_get(ma) : NULL;
2183
2184         format_u8u(ds, "type", key->icmp_type, MASK(mask, icmp_type), verbose);
2185         format_u8u(ds, "code", key->icmp_code, MASK(mask, icmp_code), verbose);
2186         ds_chomp(ds, ',');
2187         break;
2188     }
2189     case OVS_KEY_ATTR_ICMPV6: {
2190         const struct ovs_key_icmpv6 *key = nl_attr_get(a);
2191         const struct ovs_key_icmpv6 *mask = ma ? nl_attr_get(ma) : NULL;
2192
2193         format_u8u(ds, "type", key->icmpv6_type, MASK(mask, icmpv6_type),
2194                    verbose);
2195         format_u8u(ds, "code", key->icmpv6_code, MASK(mask, icmpv6_code),
2196                    verbose);
2197         ds_chomp(ds, ',');
2198         break;
2199     }
2200     case OVS_KEY_ATTR_ARP: {
2201         const struct ovs_key_arp *mask = ma ? nl_attr_get(ma) : NULL;
2202         const struct ovs_key_arp *key = nl_attr_get(a);
2203
2204         format_ipv4(ds, "sip", key->arp_sip, MASK(mask, arp_sip), verbose);
2205         format_ipv4(ds, "tip", key->arp_tip, MASK(mask, arp_tip), verbose);
2206         format_be16(ds, "op", key->arp_op, MASK(mask, arp_op), verbose);
2207         format_eth(ds, "sha", key->arp_sha, MASK(mask, arp_sha), verbose);
2208         format_eth(ds, "tha", key->arp_tha, MASK(mask, arp_tha), verbose);
2209         ds_chomp(ds, ',');
2210         break;
2211     }
2212     case OVS_KEY_ATTR_ND: {
2213         const struct ovs_key_nd *mask = ma ? nl_attr_get(ma) : NULL;
2214         const struct ovs_key_nd *key = nl_attr_get(a);
2215
2216         format_ipv6(ds, "target", key->nd_target, MASK(mask, nd_target),
2217                     verbose);
2218         format_eth(ds, "sll", key->nd_sll, MASK(mask, nd_sll), verbose);
2219         format_eth(ds, "tll", key->nd_tll, MASK(mask, nd_tll), verbose);
2220
2221         ds_chomp(ds, ',');
2222         break;
2223     }
2224     case OVS_KEY_ATTR_UNSPEC:
2225     case __OVS_KEY_ATTR_MAX:
2226     default:
2227         format_generic_odp_key(a, ds);
2228         if (!is_exact) {
2229             ds_put_char(ds, '/');
2230             format_generic_odp_key(ma, ds);
2231         }
2232         break;
2233     }
2234     ds_put_char(ds, ')');
2235 }
2236
2237 static struct nlattr *
2238 generate_all_wildcard_mask(const struct attr_len_tbl tbl[], int max,
2239                            struct ofpbuf *ofp, const struct nlattr *key)
2240 {
2241     const struct nlattr *a;
2242     unsigned int left;
2243     int type = nl_attr_type(key);
2244     int size = nl_attr_get_size(key);
2245
2246     if (odp_key_attr_len(tbl, max, type) != ATTR_LEN_NESTED) {
2247         nl_msg_put_unspec_zero(ofp, type, size);
2248     } else {
2249         size_t nested_mask;
2250
2251         if (tbl[type].next) {
2252             tbl = tbl[type].next;
2253             max = tbl[type].next_max;
2254         }
2255
2256         nested_mask = nl_msg_start_nested(ofp, type);
2257         NL_ATTR_FOR_EACH(a, left, key, nl_attr_get_size(key)) {
2258             generate_all_wildcard_mask(tbl, max, ofp, nl_attr_get(a));
2259         }
2260         nl_msg_end_nested(ofp, nested_mask);
2261     }
2262
2263     return ofp->base;
2264 }
2265
2266 int
2267 odp_ufid_from_string(const char *s_, ovs_u128 *ufid)
2268 {
2269     const char *s = s_;
2270
2271     if (ovs_scan(s, "ufid:")) {
2272         s += 5;
2273
2274         if (!uuid_from_string_prefix((struct uuid *)ufid, s)) {
2275             return -EINVAL;
2276         }
2277         s += UUID_LEN;
2278
2279         return s - s_;
2280     }
2281
2282     return 0;
2283 }
2284
2285 void
2286 odp_format_ufid(const ovs_u128 *ufid, struct ds *ds)
2287 {
2288     ds_put_format(ds, "ufid:"UUID_FMT, UUID_ARGS((struct uuid *)ufid));
2289 }
2290
2291 /* Appends to 'ds' a string representation of the 'key_len' bytes of
2292  * OVS_KEY_ATTR_* attributes in 'key'. If non-null, additionally formats the
2293  * 'mask_len' bytes of 'mask' which apply to 'key'. If 'portno_names' is
2294  * non-null and 'verbose' is true, translates odp port number to its name. */
2295 void
2296 odp_flow_format(const struct nlattr *key, size_t key_len,
2297                 const struct nlattr *mask, size_t mask_len,
2298                 const struct hmap *portno_names, struct ds *ds, bool verbose)
2299 {
2300     if (key_len) {
2301         const struct nlattr *a;
2302         unsigned int left;
2303         bool has_ethtype_key = false;
2304         const struct nlattr *ma = NULL;
2305         struct ofpbuf ofp;
2306         bool first_field = true;
2307
2308         ofpbuf_init(&ofp, 100);
2309         NL_ATTR_FOR_EACH (a, left, key, key_len) {
2310             bool is_nested_attr;
2311             bool is_wildcard = false;
2312             int attr_type = nl_attr_type(a);
2313
2314             if (attr_type == OVS_KEY_ATTR_ETHERTYPE) {
2315                 has_ethtype_key = true;
2316             }
2317
2318             is_nested_attr = odp_key_attr_len(ovs_flow_key_attr_lens,
2319                                               OVS_KEY_ATTR_MAX, attr_type) ==
2320                              ATTR_LEN_NESTED;
2321
2322             if (mask && mask_len) {
2323                 ma = nl_attr_find__(mask, mask_len, nl_attr_type(a));
2324                 is_wildcard = ma ? odp_mask_attr_is_wildcard(ma) : true;
2325             }
2326
2327             if (verbose || !is_wildcard  || is_nested_attr) {
2328                 if (is_wildcard && !ma) {
2329                     ma = generate_all_wildcard_mask(ovs_flow_key_attr_lens,
2330                                                     OVS_KEY_ATTR_MAX,
2331                                                     &ofp, a);
2332                 }
2333                 if (!first_field) {
2334                     ds_put_char(ds, ',');
2335                 }
2336                 format_odp_key_attr(a, ma, portno_names, ds, verbose);
2337                 first_field = false;
2338             }
2339             ofpbuf_clear(&ofp);
2340         }
2341         ofpbuf_uninit(&ofp);
2342
2343         if (left) {
2344             int i;
2345
2346             if (left == key_len) {
2347                 ds_put_cstr(ds, "<empty>");
2348             }
2349             ds_put_format(ds, ",***%u leftover bytes*** (", left);
2350             for (i = 0; i < left; i++) {
2351                 ds_put_format(ds, "%02x", ((const uint8_t *) a)[i]);
2352             }
2353             ds_put_char(ds, ')');
2354         }
2355         if (!has_ethtype_key) {
2356             ma = nl_attr_find__(mask, mask_len, OVS_KEY_ATTR_ETHERTYPE);
2357             if (ma) {
2358                 ds_put_format(ds, ",eth_type(0/0x%04"PRIx16")",
2359                               ntohs(nl_attr_get_be16(ma)));
2360             }
2361         }
2362     } else {
2363         ds_put_cstr(ds, "<empty>");
2364     }
2365 }
2366
2367 /* Appends to 'ds' a string representation of the 'key_len' bytes of
2368  * OVS_KEY_ATTR_* attributes in 'key'. */
2369 void
2370 odp_flow_key_format(const struct nlattr *key,
2371                     size_t key_len, struct ds *ds)
2372 {
2373     odp_flow_format(key, key_len, NULL, 0, NULL, ds, true);
2374 }
2375
2376 static bool
2377 ovs_frag_type_from_string(const char *s, enum ovs_frag_type *type)
2378 {
2379     if (!strcasecmp(s, "no")) {
2380         *type = OVS_FRAG_TYPE_NONE;
2381     } else if (!strcasecmp(s, "first")) {
2382         *type = OVS_FRAG_TYPE_FIRST;
2383     } else if (!strcasecmp(s, "later")) {
2384         *type = OVS_FRAG_TYPE_LATER;
2385     } else {
2386         return false;
2387     }
2388     return true;
2389 }
2390
2391 /* Parsing. */
2392
2393 static int
2394 scan_eth(const char *s, uint8_t (*key)[ETH_ADDR_LEN],
2395          uint8_t (*mask)[ETH_ADDR_LEN])
2396 {
2397     int n;
2398
2399     if (ovs_scan(s, ETH_ADDR_SCAN_FMT"%n", ETH_ADDR_SCAN_ARGS(*key), &n)) {
2400         int len = n;
2401
2402         if (mask) {
2403             if (ovs_scan(s + len, "/"ETH_ADDR_SCAN_FMT"%n",
2404                          ETH_ADDR_SCAN_ARGS(*mask), &n)) {
2405                 len += n;
2406             } else {
2407                 memset(mask, 0xff, sizeof *mask);
2408             }
2409         }
2410         return len;
2411     }
2412     return 0;
2413 }
2414
2415 static int
2416 scan_ipv4(const char *s, ovs_be32 *key, ovs_be32 *mask)
2417 {
2418     int n;
2419
2420     if (ovs_scan(s, IP_SCAN_FMT"%n", IP_SCAN_ARGS(key), &n)) {
2421         int len = n;
2422
2423         if (mask) {
2424             if (ovs_scan(s + len, "/"IP_SCAN_FMT"%n",
2425                          IP_SCAN_ARGS(mask), &n)) {
2426                 len += n;
2427             } else {
2428                 *mask = OVS_BE32_MAX;
2429             }
2430         }
2431         return len;
2432     }
2433     return 0;
2434 }
2435
2436 static int
2437 scan_ipv6(const char *s, ovs_be32 (*key)[4], ovs_be32 (*mask)[4])
2438 {
2439     int n;
2440     char ipv6_s[IPV6_SCAN_LEN + 1];
2441
2442     if (ovs_scan(s, IPV6_SCAN_FMT"%n", ipv6_s, &n)
2443         && inet_pton(AF_INET6, ipv6_s, key) == 1) {
2444         int len = n;
2445
2446         if (mask) {
2447             if (ovs_scan(s + len, "/"IPV6_SCAN_FMT"%n", ipv6_s, &n)
2448                 && inet_pton(AF_INET6, ipv6_s, mask) == 1) {
2449                 len += n;
2450             } else {
2451                 memset(mask, 0xff, sizeof *mask);
2452             }
2453         }
2454         return len;
2455     }
2456     return 0;
2457 }
2458
2459 static int
2460 scan_ipv6_label(const char *s, ovs_be32 *key, ovs_be32 *mask)
2461 {
2462     int key_, mask_;
2463     int n;
2464
2465     if (ovs_scan(s, "%i%n", &key_, &n)
2466         && (key_ & ~IPV6_LABEL_MASK) == 0) {
2467         int len = n;
2468
2469         *key = htonl(key_);
2470         if (mask) {
2471             if (ovs_scan(s + len, "/%i%n", &mask_, &n)
2472                 && (mask_ & ~IPV6_LABEL_MASK) == 0) {
2473                 len += n;
2474                 *mask = htonl(mask_);
2475             } else {
2476                 *mask = htonl(IPV6_LABEL_MASK);
2477             }
2478         }
2479         return len;
2480     }
2481     return 0;
2482 }
2483
2484 static int
2485 scan_u8(const char *s, uint8_t *key, uint8_t *mask)
2486 {
2487     int n;
2488
2489     if (ovs_scan(s, "%"SCNi8"%n", key, &n)) {
2490         int len = n;
2491
2492         if (mask) {
2493             if (ovs_scan(s + len, "/%"SCNi8"%n", mask, &n)) {
2494                 len += n;
2495             } else {
2496                 *mask = UINT8_MAX;
2497             }
2498         }
2499         return len;
2500     }
2501     return 0;
2502 }
2503
2504 static int
2505 scan_u32(const char *s, uint32_t *key, uint32_t *mask)
2506 {
2507     int n;
2508
2509     if (ovs_scan(s, "%"SCNi32"%n", key, &n)) {
2510         int len = n;
2511
2512         if (mask) {
2513             if (ovs_scan(s + len, "/%"SCNi32"%n", mask, &n)) {
2514                 len += n;
2515             } else {
2516                 *mask = UINT32_MAX;
2517             }
2518         }
2519         return len;
2520     }
2521     return 0;
2522 }
2523
2524 static int
2525 scan_be16(const char *s, ovs_be16 *key, ovs_be16 *mask)
2526 {
2527     uint16_t key_, mask_;
2528     int n;
2529
2530     if (ovs_scan(s, "%"SCNi16"%n", &key_, &n)) {
2531         int len = n;
2532
2533         *key = htons(key_);
2534         if (mask) {
2535             if (ovs_scan(s + len, "/%"SCNi16"%n", &mask_, &n)) {
2536                 len += n;
2537                 *mask = htons(mask_);
2538             } else {
2539                 *mask = OVS_BE16_MAX;
2540             }
2541         }
2542         return len;
2543     }
2544     return 0;
2545 }
2546
2547 static int
2548 scan_be64(const char *s, ovs_be64 *key, ovs_be64 *mask)
2549 {
2550     uint64_t key_, mask_;
2551     int n;
2552
2553     if (ovs_scan(s, "%"SCNi64"%n", &key_, &n)) {
2554         int len = n;
2555
2556         *key = htonll(key_);
2557         if (mask) {
2558             if (ovs_scan(s + len, "/%"SCNi64"%n", &mask_, &n)) {
2559                 len += n;
2560                 *mask = htonll(mask_);
2561             } else {
2562                 *mask = OVS_BE64_MAX;
2563             }
2564         }
2565         return len;
2566     }
2567     return 0;
2568 }
2569
2570 static int
2571 scan_tun_flags(const char *s, uint16_t *key, uint16_t *mask)
2572 {
2573     uint32_t flags, fmask;
2574     int n;
2575
2576     n = parse_odp_flags(s, flow_tun_flag_to_string, &flags,
2577                         FLOW_TNL_F_MASK, mask ? &fmask : NULL);
2578     if (n >= 0 && s[n] == ')') {
2579         *key = flags;
2580         if (mask) {
2581             *mask = fmask;
2582         }
2583         return n + 1;
2584     }
2585     return 0;
2586 }
2587
2588 static int
2589 scan_tcp_flags(const char *s, ovs_be16 *key, ovs_be16 *mask)
2590 {
2591     uint32_t flags, fmask;
2592     int n;
2593
2594     n = parse_odp_flags(s, packet_tcp_flag_to_string, &flags,
2595                         TCP_FLAGS(OVS_BE16_MAX), mask ? &fmask : NULL);
2596     if (n >= 0) {
2597         *key = htons(flags);
2598         if (mask) {
2599             *mask = htons(fmask);
2600         }
2601         return n;
2602     }
2603     return 0;
2604 }
2605
2606 static int
2607 scan_frag(const char *s, uint8_t *key, uint8_t *mask)
2608 {
2609     int n;
2610     char frag[8];
2611     enum ovs_frag_type frag_type;
2612
2613     if (ovs_scan(s, "%7[a-z]%n", frag, &n)
2614         && ovs_frag_type_from_string(frag, &frag_type)) {
2615         int len = n;
2616
2617         *key = frag_type;
2618         if (mask) {
2619             *mask = UINT8_MAX;
2620         }
2621         return len;
2622     }
2623     return 0;
2624 }
2625
2626 static int
2627 scan_port(const char *s, uint32_t *key, uint32_t *mask,
2628           const struct simap *port_names)
2629 {
2630     int n;
2631
2632     if (ovs_scan(s, "%"SCNi32"%n", key, &n)) {
2633         int len = n;
2634
2635         if (mask) {
2636             if (ovs_scan(s + len, "/%"SCNi32"%n", mask, &n)) {
2637                 len += n;
2638             } else {
2639                 *mask = UINT32_MAX;
2640             }
2641         }
2642         return len;
2643     } else if (port_names) {
2644         const struct simap_node *node;
2645         int len;
2646
2647         len = strcspn(s, ")");
2648         node = simap_find_len(port_names, s, len);
2649         if (node) {
2650             *key = node->data;
2651
2652             if (mask) {
2653                 *mask = UINT32_MAX;
2654             }
2655             return len;
2656         }
2657     }
2658     return 0;
2659 }
2660
2661 /* Helper for vlan parsing. */
2662 struct ovs_key_vlan__ {
2663     ovs_be16 tci;
2664 };
2665
2666 static bool
2667 set_be16_bf(ovs_be16 *bf, uint8_t bits, uint8_t offset, uint16_t value)
2668 {
2669     const uint16_t mask = ((1U << bits) - 1) << offset;
2670
2671     if (value >> bits) {
2672         return false;
2673     }
2674
2675     *bf = htons((ntohs(*bf) & ~mask) | (value << offset));
2676     return true;
2677 }
2678
2679 static int
2680 scan_be16_bf(const char *s, ovs_be16 *key, ovs_be16 *mask, uint8_t bits,
2681              uint8_t offset)
2682 {
2683     uint16_t key_, mask_;
2684     int n;
2685
2686     if (ovs_scan(s, "%"SCNi16"%n", &key_, &n)) {
2687         int len = n;
2688
2689         if (set_be16_bf(key, bits, offset, key_)) {
2690             if (mask) {
2691                 if (ovs_scan(s + len, "/%"SCNi16"%n", &mask_, &n)) {
2692                     len += n;
2693
2694                     if (!set_be16_bf(mask, bits, offset, mask_)) {
2695                         return 0;
2696                     }
2697                 } else {
2698                     *mask |= htons(((1U << bits) - 1) << offset);
2699                 }
2700             }
2701             return len;
2702         }
2703     }
2704     return 0;
2705 }
2706
2707 static int
2708 scan_vid(const char *s, ovs_be16 *key, ovs_be16 *mask)
2709 {
2710     return scan_be16_bf(s, key, mask, 12, VLAN_VID_SHIFT);
2711 }
2712
2713 static int
2714 scan_pcp(const char *s, ovs_be16 *key, ovs_be16 *mask)
2715 {
2716     return scan_be16_bf(s, key, mask, 3, VLAN_PCP_SHIFT);
2717 }
2718
2719 static int
2720 scan_cfi(const char *s, ovs_be16 *key, ovs_be16 *mask)
2721 {
2722     return scan_be16_bf(s, key, mask, 1, VLAN_CFI_SHIFT);
2723 }
2724
2725 /* For MPLS. */
2726 static bool
2727 set_be32_bf(ovs_be32 *bf, uint8_t bits, uint8_t offset, uint32_t value)
2728 {
2729     const uint32_t mask = ((1U << bits) - 1) << offset;
2730
2731     if (value >> bits) {
2732         return false;
2733     }
2734
2735     *bf = htonl((ntohl(*bf) & ~mask) | (value << offset));
2736     return true;
2737 }
2738
2739 static int
2740 scan_be32_bf(const char *s, ovs_be32 *key, ovs_be32 *mask, uint8_t bits,
2741              uint8_t offset)
2742 {
2743     uint32_t key_, mask_;
2744     int n;
2745
2746     if (ovs_scan(s, "%"SCNi32"%n", &key_, &n)) {
2747         int len = n;
2748
2749         if (set_be32_bf(key, bits, offset, key_)) {
2750             if (mask) {
2751                 if (ovs_scan(s + len, "/%"SCNi32"%n", &mask_, &n)) {
2752                     len += n;
2753
2754                     if (!set_be32_bf(mask, bits, offset, mask_)) {
2755                         return 0;
2756                     }
2757                 } else {
2758                     *mask |= htonl(((1U << bits) - 1) << offset);
2759                 }
2760             }
2761             return len;
2762         }
2763     }
2764     return 0;
2765 }
2766
2767 static int
2768 scan_mpls_label(const char *s, ovs_be32 *key, ovs_be32 *mask)
2769 {
2770     return scan_be32_bf(s, key, mask, 20, MPLS_LABEL_SHIFT);
2771 }
2772
2773 static int
2774 scan_mpls_tc(const char *s, ovs_be32 *key, ovs_be32 *mask)
2775 {
2776     return scan_be32_bf(s, key, mask, 3, MPLS_TC_SHIFT);
2777 }
2778
2779 static int
2780 scan_mpls_ttl(const char *s, ovs_be32 *key, ovs_be32 *mask)
2781 {
2782     return scan_be32_bf(s, key, mask, 8, MPLS_TTL_SHIFT);
2783 }
2784
2785 static int
2786 scan_mpls_bos(const char *s, ovs_be32 *key, ovs_be32 *mask)
2787 {
2788     return scan_be32_bf(s, key, mask, 1, MPLS_BOS_SHIFT);
2789 }
2790
2791 static int
2792 scan_vxlan_gbp(const char *s, uint32_t *key, uint32_t *mask)
2793 {
2794     const char *s_base = s;
2795     ovs_be16 id = 0, id_mask = 0;
2796     uint8_t flags = 0, flags_mask = 0;
2797
2798     if (!strncmp(s, "id=", 3)) {
2799         s += 3;
2800         s += scan_be16(s, &id, mask ? &id_mask : NULL);
2801     }
2802
2803     if (s[0] == ',') {
2804         s++;
2805     }
2806     if (!strncmp(s, "flags=", 6)) {
2807         s += 6;
2808         s += scan_u8(s, &flags, mask ? &flags_mask : NULL);
2809     }
2810
2811     if (!strncmp(s, "))", 2)) {
2812         s += 2;
2813
2814         *key = (flags << 16) | ntohs(id);
2815         if (mask) {
2816             *mask = (flags_mask << 16) | ntohs(id_mask);
2817         }
2818
2819         return s - s_base;
2820     }
2821
2822     return 0;
2823 }
2824
2825 static int
2826 scan_geneve(const char *s, struct geneve_scan *key, struct geneve_scan *mask)
2827 {
2828     const char *s_base = s;
2829     struct geneve_opt *opt = key->d;
2830     struct geneve_opt *opt_mask = mask ? mask->d : NULL;
2831     int len_remain = sizeof key->d;
2832
2833     while (s[0] == '{' && len_remain >= sizeof *opt) {
2834         int data_len = 0;
2835
2836         s++;
2837         len_remain -= sizeof *opt;
2838
2839         if (!strncmp(s, "class=", 6)) {
2840             s += 6;
2841             s += scan_be16(s, &opt->opt_class,
2842                            mask ? &opt_mask->opt_class : NULL);
2843         } else if (mask) {
2844             memset(&opt_mask->opt_class, 0, sizeof opt_mask->opt_class);
2845         }
2846
2847         if (s[0] == ',') {
2848             s++;
2849         }
2850         if (!strncmp(s, "type=", 5)) {
2851             s += 5;
2852             s += scan_u8(s, &opt->type, mask ? &opt_mask->type : NULL);
2853         } else if (mask) {
2854             memset(&opt_mask->type, 0, sizeof opt_mask->type);
2855         }
2856
2857         if (s[0] == ',') {
2858             s++;
2859         }
2860         if (!strncmp(s, "len=", 4)) {
2861             uint8_t opt_len, opt_len_mask;
2862             s += 4;
2863             s += scan_u8(s, &opt_len, mask ? &opt_len_mask : NULL);
2864
2865             if (opt_len > 124 || opt_len % 4 || opt_len > len_remain) {
2866                 return 0;
2867             }
2868             opt->length = opt_len / 4;
2869             if (mask) {
2870                 opt_mask->length = opt_len_mask;
2871             }
2872             data_len = opt_len;
2873         } else if (mask) {
2874             memset(&opt_mask->type, 0, sizeof opt_mask->type);
2875         }
2876
2877         if (s[0] == ',') {
2878             s++;
2879         }
2880         if (parse_int_string(s, (uint8_t *)(opt + 1), data_len, (char **)&s)) {
2881             return 0;
2882         }
2883
2884         if (mask) {
2885             if (s[0] == '/') {
2886                 s++;
2887                 if (parse_int_string(s, (uint8_t *)(opt_mask + 1),
2888                                      data_len, (char **)&s)) {
2889                     return 0;
2890                 }
2891             }
2892             opt_mask->r1 = 0;
2893             opt_mask->r2 = 0;
2894             opt_mask->r3 = 0;
2895         }
2896
2897         if (s[0] == '}') {
2898             s++;
2899             opt += 1 + data_len / 4;
2900             if (mask) {
2901                 opt_mask += 1 + data_len / 4;
2902             }
2903             len_remain -= data_len;
2904         }
2905     }
2906
2907     if (s[0] == ')') {
2908         int len = sizeof key->d - len_remain;
2909
2910         s++;
2911         key->len = len;
2912         if (mask) {
2913             mask->len = len;
2914         }
2915         return s - s_base;
2916     }
2917
2918     return 0;
2919 }
2920
2921 static void
2922 tun_flags_to_attr(struct ofpbuf *a, const void *data_)
2923 {
2924     const uint16_t *flags = data_;
2925
2926     if (*flags & FLOW_TNL_F_DONT_FRAGMENT) {
2927         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT);
2928     }
2929     if (*flags & FLOW_TNL_F_CSUM) {
2930         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_CSUM);
2931     }
2932     if (*flags & FLOW_TNL_F_OAM) {
2933         nl_msg_put_flag(a, OVS_TUNNEL_KEY_ATTR_OAM);
2934     }
2935 }
2936
2937 static void
2938 vxlan_gbp_to_attr(struct ofpbuf *a, const void *data_)
2939 {
2940     const uint32_t *gbp = data_;
2941
2942     if (*gbp) {
2943         size_t vxlan_opts_ofs;
2944
2945         vxlan_opts_ofs = nl_msg_start_nested(a, OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS);
2946         nl_msg_put_u32(a, OVS_VXLAN_EXT_GBP, *gbp);
2947         nl_msg_end_nested(a, vxlan_opts_ofs);
2948     }
2949 }
2950
2951 static void
2952 geneve_to_attr(struct ofpbuf *a, const void *data_)
2953 {
2954     const struct geneve_scan *geneve = data_;
2955
2956     nl_msg_put_unspec(a, OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS, geneve->d,
2957                       geneve->len);
2958 }
2959
2960 #define SCAN_PUT_ATTR(BUF, ATTR, DATA, FUNC)                      \
2961     {                                                             \
2962         unsigned long call_fn = (unsigned long)FUNC;              \
2963         if (call_fn) {                                            \
2964             typedef void (*fn)(struct ofpbuf *, const void *);    \
2965             fn func = FUNC;                                       \
2966             func(BUF, &(DATA));                                   \
2967         } else {                                                  \
2968             nl_msg_put_unspec(BUF, ATTR, &(DATA), sizeof (DATA)); \
2969         }                                                         \
2970     }
2971
2972 #define SCAN_IF(NAME)                           \
2973     if (strncmp(s, NAME, strlen(NAME)) == 0) {  \
2974         const char *start = s;                  \
2975         int len;                                \
2976                                                 \
2977         s += strlen(NAME)
2978
2979 /* Usually no special initialization is needed. */
2980 #define SCAN_BEGIN(NAME, TYPE)                  \
2981     SCAN_IF(NAME);                              \
2982         TYPE skey, smask;                       \
2983         memset(&skey, 0, sizeof skey);          \
2984         memset(&smask, 0, sizeof smask);        \
2985         do {                                    \
2986             len = 0;
2987
2988 /* Init as fully-masked as mask will not be scanned. */
2989 #define SCAN_BEGIN_FULLY_MASKED(NAME, TYPE)     \
2990     SCAN_IF(NAME);                              \
2991         TYPE skey, smask;                       \
2992         memset(&skey, 0, sizeof skey);          \
2993         memset(&smask, 0xff, sizeof smask);     \
2994         do {                                    \
2995             len = 0;
2996
2997 /* VLAN needs special initialization. */
2998 #define SCAN_BEGIN_INIT(NAME, TYPE, KEY_INIT, MASK_INIT)  \
2999     SCAN_IF(NAME);                                        \
3000         TYPE skey = KEY_INIT;                       \
3001         TYPE smask = MASK_INIT;                     \
3002         do {                                        \
3003             len = 0;
3004
3005 /* Scan unnamed entry as 'TYPE' */
3006 #define SCAN_TYPE(TYPE, KEY, MASK)              \
3007     len = scan_##TYPE(s, KEY, MASK);            \
3008     if (len == 0) {                             \
3009         return -EINVAL;                         \
3010     }                                           \
3011     s += len
3012
3013 /* Scan named ('NAME') entry 'FIELD' as 'TYPE'. */
3014 #define SCAN_FIELD(NAME, TYPE, FIELD)                                   \
3015     if (strncmp(s, NAME, strlen(NAME)) == 0) {                          \
3016         s += strlen(NAME);                                              \
3017         SCAN_TYPE(TYPE, &skey.FIELD, mask ? &smask.FIELD : NULL);       \
3018         continue;                                                       \
3019     }
3020
3021 #define SCAN_FINISH()                           \
3022         } while (*s++ == ',' && len != 0);      \
3023         if (s[-1] != ')') {                     \
3024             return -EINVAL;                     \
3025         }
3026
3027 #define SCAN_FINISH_SINGLE()                    \
3028         } while (false);                        \
3029         if (*s++ != ')') {                      \
3030             return -EINVAL;                     \
3031         }
3032
3033 /* Beginning of nested attribute. */
3034 #define SCAN_BEGIN_NESTED(NAME, ATTR)                      \
3035     SCAN_IF(NAME);                                         \
3036         size_t key_offset, mask_offset;                    \
3037         key_offset = nl_msg_start_nested(key, ATTR);       \
3038         if (mask) {                                        \
3039             mask_offset = nl_msg_start_nested(mask, ATTR); \
3040         }                                                  \
3041         do {                                               \
3042             len = 0;
3043
3044 #define SCAN_END_NESTED()                               \
3045         SCAN_FINISH();                                  \
3046         nl_msg_end_nested(key, key_offset);             \
3047         if (mask) {                                     \
3048             nl_msg_end_nested(mask, mask_offset);       \
3049         }                                               \
3050         return s - start;                               \
3051     }
3052
3053 #define SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, ATTR, FUNC)  \
3054     if (strncmp(s, NAME, strlen(NAME)) == 0) {                \
3055         TYPE skey, smask;                                     \
3056         memset(&skey, 0, sizeof skey);                        \
3057         memset(&smask, 0xff, sizeof smask);                   \
3058         s += strlen(NAME);                                    \
3059         SCAN_TYPE(SCAN_AS, &skey, &smask);                    \
3060         SCAN_PUT(ATTR, FUNC);                                 \
3061         continue;                                             \
3062     }
3063
3064 #define SCAN_FIELD_NESTED(NAME, TYPE, SCAN_AS, ATTR)  \
3065         SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, ATTR, NULL)
3066
3067 #define SCAN_FIELD_NESTED_FUNC(NAME, TYPE, SCAN_AS, FUNC)  \
3068         SCAN_FIELD_NESTED__(NAME, TYPE, SCAN_AS, 0, FUNC)
3069
3070 #define SCAN_PUT(ATTR, FUNC)                            \
3071         if (!mask || !is_all_zeros(&smask, sizeof smask)) { \
3072             SCAN_PUT_ATTR(key, ATTR, skey, FUNC);       \
3073             if (mask) {                                 \
3074                 SCAN_PUT_ATTR(mask, ATTR, smask, FUNC); \
3075             }                                           \
3076         }
3077
3078 #define SCAN_END(ATTR)                                  \
3079         SCAN_FINISH();                                  \
3080         SCAN_PUT(ATTR, NULL);                           \
3081         return s - start;                               \
3082     }
3083
3084 #define SCAN_END_SINGLE(ATTR)                           \
3085         SCAN_FINISH_SINGLE();                           \
3086         SCAN_PUT(ATTR, NULL);                           \
3087         return s - start;                               \
3088     }
3089
3090 #define SCAN_SINGLE(NAME, TYPE, SCAN_AS, ATTR)       \
3091     SCAN_BEGIN(NAME, TYPE) {                         \
3092         SCAN_TYPE(SCAN_AS, &skey, &smask);           \
3093     } SCAN_END_SINGLE(ATTR)
3094
3095 #define SCAN_SINGLE_FULLY_MASKED(NAME, TYPE, SCAN_AS, ATTR) \
3096     SCAN_BEGIN_FULLY_MASKED(NAME, TYPE) {                   \
3097         SCAN_TYPE(SCAN_AS, &skey, NULL);                    \
3098     } SCAN_END_SINGLE(ATTR)
3099
3100 /* scan_port needs one extra argument. */
3101 #define SCAN_SINGLE_PORT(NAME, TYPE, ATTR)  \
3102     SCAN_BEGIN(NAME, TYPE) {                            \
3103         len = scan_port(s, &skey, &smask, port_names);  \
3104         if (len == 0) {                                 \
3105             return -EINVAL;                             \
3106         }                                               \
3107         s += len;                                       \
3108     } SCAN_END_SINGLE(ATTR)
3109
3110 static int
3111 parse_odp_key_mask_attr(const char *s, const struct simap *port_names,
3112                         struct ofpbuf *key, struct ofpbuf *mask)
3113 {
3114     ovs_u128 ufid;
3115     int len;
3116
3117     /* Skip UFID. */
3118     len = odp_ufid_from_string(s, &ufid);
3119     if (len) {
3120         return len;
3121     }
3122
3123     SCAN_SINGLE("skb_priority(", uint32_t, u32, OVS_KEY_ATTR_PRIORITY);
3124     SCAN_SINGLE("skb_mark(", uint32_t, u32, OVS_KEY_ATTR_SKB_MARK);
3125     SCAN_SINGLE_FULLY_MASKED("recirc_id(", uint32_t, u32,
3126                              OVS_KEY_ATTR_RECIRC_ID);
3127     SCAN_SINGLE("dp_hash(", uint32_t, u32, OVS_KEY_ATTR_DP_HASH);
3128
3129     SCAN_BEGIN_NESTED("tunnel(", OVS_KEY_ATTR_TUNNEL) {
3130         SCAN_FIELD_NESTED("tun_id=", ovs_be64, be64, OVS_TUNNEL_KEY_ATTR_ID);
3131         SCAN_FIELD_NESTED("src=", ovs_be32, ipv4, OVS_TUNNEL_KEY_ATTR_IPV4_SRC);
3132         SCAN_FIELD_NESTED("dst=", ovs_be32, ipv4, OVS_TUNNEL_KEY_ATTR_IPV4_DST);
3133         SCAN_FIELD_NESTED("tos=", uint8_t, u8, OVS_TUNNEL_KEY_ATTR_TOS);
3134         SCAN_FIELD_NESTED("ttl=", uint8_t, u8, OVS_TUNNEL_KEY_ATTR_TTL);
3135         SCAN_FIELD_NESTED("tp_src=", ovs_be16, be16, OVS_TUNNEL_KEY_ATTR_TP_SRC);
3136         SCAN_FIELD_NESTED("tp_dst=", ovs_be16, be16, OVS_TUNNEL_KEY_ATTR_TP_DST);
3137         SCAN_FIELD_NESTED_FUNC("vxlan(gbp(", uint32_t, vxlan_gbp, vxlan_gbp_to_attr);
3138         SCAN_FIELD_NESTED_FUNC("geneve(", struct geneve_scan, geneve,
3139                                geneve_to_attr);
3140         SCAN_FIELD_NESTED_FUNC("flags(", uint16_t, tun_flags, tun_flags_to_attr);
3141     } SCAN_END_NESTED();
3142
3143     SCAN_SINGLE_PORT("in_port(", uint32_t, OVS_KEY_ATTR_IN_PORT);
3144
3145     SCAN_BEGIN("eth(", struct ovs_key_ethernet) {
3146         SCAN_FIELD("src=", eth, eth_src);
3147         SCAN_FIELD("dst=", eth, eth_dst);
3148     } SCAN_END(OVS_KEY_ATTR_ETHERNET);
3149
3150     SCAN_BEGIN_INIT("vlan(", struct ovs_key_vlan__,
3151                     { htons(VLAN_CFI) }, { htons(VLAN_CFI) }) {
3152         SCAN_FIELD("vid=", vid, tci);
3153         SCAN_FIELD("pcp=", pcp, tci);
3154         SCAN_FIELD("cfi=", cfi, tci);
3155     } SCAN_END(OVS_KEY_ATTR_VLAN);
3156
3157     SCAN_SINGLE("eth_type(", ovs_be16, be16, OVS_KEY_ATTR_ETHERTYPE);
3158
3159     SCAN_BEGIN("mpls(", struct ovs_key_mpls) {
3160         SCAN_FIELD("label=", mpls_label, mpls_lse);
3161         SCAN_FIELD("tc=", mpls_tc, mpls_lse);
3162         SCAN_FIELD("ttl=", mpls_ttl, mpls_lse);
3163         SCAN_FIELD("bos=", mpls_bos, mpls_lse);
3164     } SCAN_END(OVS_KEY_ATTR_MPLS);
3165
3166     SCAN_BEGIN("ipv4(", struct ovs_key_ipv4) {
3167         SCAN_FIELD("src=", ipv4, ipv4_src);
3168         SCAN_FIELD("dst=", ipv4, ipv4_dst);
3169         SCAN_FIELD("proto=", u8, ipv4_proto);
3170         SCAN_FIELD("tos=", u8, ipv4_tos);
3171         SCAN_FIELD("ttl=", u8, ipv4_ttl);
3172         SCAN_FIELD("frag=", frag, ipv4_frag);
3173     } SCAN_END(OVS_KEY_ATTR_IPV4);
3174
3175     SCAN_BEGIN("ipv6(", struct ovs_key_ipv6) {
3176         SCAN_FIELD("src=", ipv6, ipv6_src);
3177         SCAN_FIELD("dst=", ipv6, ipv6_dst);
3178         SCAN_FIELD("label=", ipv6_label, ipv6_label);
3179         SCAN_FIELD("proto=", u8, ipv6_proto);
3180         SCAN_FIELD("tclass=", u8, ipv6_tclass);
3181         SCAN_FIELD("hlimit=", u8, ipv6_hlimit);
3182         SCAN_FIELD("frag=", frag, ipv6_frag);
3183     } SCAN_END(OVS_KEY_ATTR_IPV6);
3184
3185     SCAN_BEGIN("tcp(", struct ovs_key_tcp) {
3186         SCAN_FIELD("src=", be16, tcp_src);
3187         SCAN_FIELD("dst=", be16, tcp_dst);
3188     } SCAN_END(OVS_KEY_ATTR_TCP);
3189
3190     SCAN_SINGLE("tcp_flags(", ovs_be16, tcp_flags, OVS_KEY_ATTR_TCP_FLAGS);
3191
3192     SCAN_BEGIN("udp(", struct ovs_key_udp) {
3193         SCAN_FIELD("src=", be16, udp_src);
3194         SCAN_FIELD("dst=", be16, udp_dst);
3195     } SCAN_END(OVS_KEY_ATTR_UDP);
3196
3197     SCAN_BEGIN("sctp(", struct ovs_key_sctp) {
3198         SCAN_FIELD("src=", be16, sctp_src);
3199         SCAN_FIELD("dst=", be16, sctp_dst);
3200     } SCAN_END(OVS_KEY_ATTR_SCTP);
3201
3202     SCAN_BEGIN("icmp(", struct ovs_key_icmp) {
3203         SCAN_FIELD("type=", u8, icmp_type);
3204         SCAN_FIELD("code=", u8, icmp_code);
3205     } SCAN_END(OVS_KEY_ATTR_ICMP);
3206
3207     SCAN_BEGIN("icmpv6(", struct ovs_key_icmpv6) {
3208         SCAN_FIELD("type=", u8, icmpv6_type);
3209         SCAN_FIELD("code=", u8, icmpv6_code);
3210     } SCAN_END(OVS_KEY_ATTR_ICMPV6);
3211
3212     SCAN_BEGIN("arp(", struct ovs_key_arp) {
3213         SCAN_FIELD("sip=", ipv4, arp_sip);
3214         SCAN_FIELD("tip=", ipv4, arp_tip);
3215         SCAN_FIELD("op=", be16, arp_op);
3216         SCAN_FIELD("sha=", eth, arp_sha);
3217         SCAN_FIELD("tha=", eth, arp_tha);
3218     } SCAN_END(OVS_KEY_ATTR_ARP);
3219
3220     SCAN_BEGIN("nd(", struct ovs_key_nd) {
3221         SCAN_FIELD("target=", ipv6, nd_target);
3222         SCAN_FIELD("sll=", eth, nd_sll);
3223         SCAN_FIELD("tll=", eth, nd_tll);
3224     } SCAN_END(OVS_KEY_ATTR_ND);
3225
3226     /* Encap open-coded. */
3227     if (!strncmp(s, "encap(", 6)) {
3228         const char *start = s;
3229         size_t encap, encap_mask = 0;
3230
3231         encap = nl_msg_start_nested(key, OVS_KEY_ATTR_ENCAP);
3232         if (mask) {
3233             encap_mask = nl_msg_start_nested(mask, OVS_KEY_ATTR_ENCAP);
3234         }
3235
3236         s += 6;
3237         for (;;) {
3238             int retval;
3239
3240             s += strspn(s, delimiters);
3241             if (!*s) {
3242                 return -EINVAL;
3243             } else if (*s == ')') {
3244                 break;
3245             }
3246
3247             retval = parse_odp_key_mask_attr(s, port_names, key, mask);
3248             if (retval < 0) {
3249                 return retval;
3250             }
3251             s += retval;
3252         }
3253         s++;
3254
3255         nl_msg_end_nested(key, encap);
3256         if (mask) {
3257             nl_msg_end_nested(mask, encap_mask);
3258         }
3259
3260         return s - start;
3261     }
3262
3263     return -EINVAL;
3264 }
3265
3266 /* Parses the string representation of a datapath flow key, in the
3267  * format output by odp_flow_key_format().  Returns 0 if successful,
3268  * otherwise a positive errno value.  On success, the flow key is
3269  * appended to 'key' as a series of Netlink attributes.  On failure, no
3270  * data is appended to 'key'.  Either way, 'key''s data might be
3271  * reallocated.
3272  *
3273  * If 'port_names' is nonnull, it points to an simap that maps from a port name
3274  * to a port number.  (Port names may be used instead of port numbers in
3275  * in_port.)
3276  *
3277  * On success, the attributes appended to 'key' are individually syntactically
3278  * valid, but they may not be valid as a sequence.  'key' might, for example,
3279  * have duplicated keys.  odp_flow_key_to_flow() will detect those errors. */
3280 int
3281 odp_flow_from_string(const char *s, const struct simap *port_names,
3282                      struct ofpbuf *key, struct ofpbuf *mask)
3283 {
3284     const size_t old_size = key->size;
3285     for (;;) {
3286         int retval;
3287
3288         s += strspn(s, delimiters);
3289         if (!*s) {
3290             return 0;
3291         }
3292
3293         retval = parse_odp_key_mask_attr(s, port_names, key, mask);
3294         if (retval < 0) {
3295             key->size = old_size;
3296             return -retval;
3297         }
3298         s += retval;
3299     }
3300
3301     return 0;
3302 }
3303
3304 static uint8_t
3305 ovs_to_odp_frag(uint8_t nw_frag, bool is_mask)
3306 {
3307     if (is_mask) {
3308         /* Netlink interface 'enum ovs_frag_type' is an 8-bit enumeration type,
3309          * not a set of flags or bitfields. Hence, if the struct flow nw_frag
3310          * mask, which is a set of bits, has the FLOW_NW_FRAG_ANY as zero, we
3311          * must use a zero mask for the netlink frag field, and all ones mask
3312          * otherwise. */
3313         return (nw_frag & FLOW_NW_FRAG_ANY) ? UINT8_MAX : 0;
3314     }
3315     return !(nw_frag & FLOW_NW_FRAG_ANY) ? OVS_FRAG_TYPE_NONE
3316         : nw_frag & FLOW_NW_FRAG_LATER ? OVS_FRAG_TYPE_LATER
3317         : OVS_FRAG_TYPE_FIRST;
3318 }
3319
3320 static void get_ethernet_key(const struct flow *, struct ovs_key_ethernet *);
3321 static void put_ethernet_key(const struct ovs_key_ethernet *, struct flow *);
3322 static void get_ipv4_key(const struct flow *, struct ovs_key_ipv4 *,
3323                          bool is_mask);
3324 static void put_ipv4_key(const struct ovs_key_ipv4 *, struct flow *,
3325                          bool is_mask);
3326 static void get_ipv6_key(const struct flow *, struct ovs_key_ipv6 *,
3327                          bool is_mask);
3328 static void put_ipv6_key(const struct ovs_key_ipv6 *, struct flow *,
3329                          bool is_mask);
3330 static void get_arp_key(const struct flow *, struct ovs_key_arp *);
3331 static void put_arp_key(const struct ovs_key_arp *, struct flow *);
3332 static void get_nd_key(const struct flow *, struct ovs_key_nd *);
3333 static void put_nd_key(const struct ovs_key_nd *, struct flow *);
3334
3335 /* These share the same layout. */
3336 union ovs_key_tp {
3337     struct ovs_key_tcp tcp;
3338     struct ovs_key_udp udp;
3339     struct ovs_key_sctp sctp;
3340 };
3341
3342 static void get_tp_key(const struct flow *, union ovs_key_tp *);
3343 static void put_tp_key(const union ovs_key_tp *, struct flow *);
3344
3345 static void
3346 odp_flow_key_from_flow__(const struct odp_flow_key_parms *parms,
3347                          bool export_mask, struct ofpbuf *buf)
3348 {
3349     struct ovs_key_ethernet *eth_key;
3350     size_t encap;
3351     const struct flow *flow = parms->flow;
3352     const struct flow *data = export_mask ? parms->mask : parms->flow;
3353
3354     nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, data->skb_priority);
3355
3356     if (flow->tunnel.ip_dst || export_mask) {
3357         tun_key_to_attr(buf, &data->tunnel, &parms->flow->tunnel,
3358                         parms->key_buf);
3359     }
3360
3361     nl_msg_put_u32(buf, OVS_KEY_ATTR_SKB_MARK, data->pkt_mark);
3362
3363     if (parms->support.recirc) {
3364         nl_msg_put_u32(buf, OVS_KEY_ATTR_RECIRC_ID, data->recirc_id);
3365         nl_msg_put_u32(buf, OVS_KEY_ATTR_DP_HASH, data->dp_hash);
3366     }
3367
3368     /* Add an ingress port attribute if this is a mask or 'odp_in_port'
3369      * is not the magical value "ODPP_NONE". */
3370     if (export_mask || parms->odp_in_port != ODPP_NONE) {
3371         nl_msg_put_odp_port(buf, OVS_KEY_ATTR_IN_PORT, parms->odp_in_port);
3372     }
3373
3374     eth_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ETHERNET,
3375                                        sizeof *eth_key);
3376     get_ethernet_key(data, eth_key);
3377
3378     if (flow->vlan_tci != htons(0) || flow->dl_type == htons(ETH_TYPE_VLAN)) {
3379         if (export_mask) {
3380             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, OVS_BE16_MAX);
3381         } else {
3382             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, htons(ETH_TYPE_VLAN));
3383         }
3384         nl_msg_put_be16(buf, OVS_KEY_ATTR_VLAN, data->vlan_tci);
3385         encap = nl_msg_start_nested(buf, OVS_KEY_ATTR_ENCAP);
3386         if (flow->vlan_tci == htons(0)) {
3387             goto unencap;
3388         }
3389     } else {
3390         encap = 0;
3391     }
3392
3393     if (ntohs(flow->dl_type) < ETH_TYPE_MIN) {
3394         /* For backwards compatibility with kernels that don't support
3395          * wildcarding, the following convention is used to encode the
3396          * OVS_KEY_ATTR_ETHERTYPE for key and mask:
3397          *
3398          *   key      mask    matches
3399          * -------- --------  -------
3400          *  >0x5ff   0xffff   Specified Ethernet II Ethertype.
3401          *  >0x5ff      0     Any Ethernet II or non-Ethernet II frame.
3402          *  <none>   0xffff   Any non-Ethernet II frame (except valid
3403          *                    802.3 SNAP packet with valid eth_type).
3404          */
3405         if (export_mask) {
3406             nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, OVS_BE16_MAX);
3407         }
3408         goto unencap;
3409     }
3410
3411     nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, data->dl_type);
3412
3413     if (flow->dl_type == htons(ETH_TYPE_IP)) {
3414         struct ovs_key_ipv4 *ipv4_key;
3415
3416         ipv4_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV4,
3417                                             sizeof *ipv4_key);
3418         get_ipv4_key(data, ipv4_key, export_mask);
3419     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
3420         struct ovs_key_ipv6 *ipv6_key;
3421
3422         ipv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV6,
3423                                             sizeof *ipv6_key);
3424         get_ipv6_key(data, ipv6_key, export_mask);
3425     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
3426                flow->dl_type == htons(ETH_TYPE_RARP)) {
3427         struct ovs_key_arp *arp_key;
3428
3429         arp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ARP,
3430                                            sizeof *arp_key);
3431         get_arp_key(data, arp_key);
3432     } else if (eth_type_mpls(flow->dl_type)) {
3433         struct ovs_key_mpls *mpls_key;
3434         int i, n;
3435
3436         n = flow_count_mpls_labels(flow, NULL);
3437         if (export_mask) {
3438             n = MIN(n, parms->support.max_mpls_depth);
3439         }
3440         mpls_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_MPLS,
3441                                             n * sizeof *mpls_key);
3442         for (i = 0; i < n; i++) {
3443             mpls_key[i].mpls_lse = data->mpls_lse[i];
3444         }
3445     }
3446
3447     if (is_ip_any(flow) && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3448         if (flow->nw_proto == IPPROTO_TCP) {
3449             union ovs_key_tp *tcp_key;
3450
3451             tcp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_TCP,
3452                                                sizeof *tcp_key);
3453             get_tp_key(data, tcp_key);
3454             if (data->tcp_flags) {
3455                 nl_msg_put_be16(buf, OVS_KEY_ATTR_TCP_FLAGS, data->tcp_flags);
3456             }
3457         } else if (flow->nw_proto == IPPROTO_UDP) {
3458             union ovs_key_tp *udp_key;
3459
3460             udp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_UDP,
3461                                                sizeof *udp_key);
3462             get_tp_key(data, udp_key);
3463         } else if (flow->nw_proto == IPPROTO_SCTP) {
3464             union ovs_key_tp *sctp_key;
3465
3466             sctp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_SCTP,
3467                                                sizeof *sctp_key);
3468             get_tp_key(data, sctp_key);
3469         } else if (flow->dl_type == htons(ETH_TYPE_IP)
3470                 && flow->nw_proto == IPPROTO_ICMP) {
3471             struct ovs_key_icmp *icmp_key;
3472
3473             icmp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMP,
3474                                                 sizeof *icmp_key);
3475             icmp_key->icmp_type = ntohs(data->tp_src);
3476             icmp_key->icmp_code = ntohs(data->tp_dst);
3477         } else if (flow->dl_type == htons(ETH_TYPE_IPV6)
3478                 && flow->nw_proto == IPPROTO_ICMPV6) {
3479             struct ovs_key_icmpv6 *icmpv6_key;
3480
3481             icmpv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMPV6,
3482                                                   sizeof *icmpv6_key);
3483             icmpv6_key->icmpv6_type = ntohs(data->tp_src);
3484             icmpv6_key->icmpv6_code = ntohs(data->tp_dst);
3485
3486             if (flow->tp_dst == htons(0)
3487                 && (flow->tp_src == htons(ND_NEIGHBOR_SOLICIT)
3488                     || flow->tp_src == htons(ND_NEIGHBOR_ADVERT))
3489                 && (!export_mask || (data->tp_src == htons(0xffff)
3490                                      && data->tp_dst == htons(0xffff)))) {
3491
3492                 struct ovs_key_nd *nd_key;
3493
3494                 nd_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ND,
3495                                                     sizeof *nd_key);
3496                 memcpy(nd_key->nd_target, &data->nd_target,
3497                         sizeof nd_key->nd_target);
3498                 memcpy(nd_key->nd_sll, data->arp_sha, ETH_ADDR_LEN);
3499                 memcpy(nd_key->nd_tll, data->arp_tha, ETH_ADDR_LEN);
3500             }
3501         }
3502     }
3503
3504 unencap:
3505     if (encap) {
3506         nl_msg_end_nested(buf, encap);
3507     }
3508 }
3509
3510 /* Appends a representation of 'flow' as OVS_KEY_ATTR_* attributes to 'buf'.
3511  *
3512  * 'buf' must have at least ODPUTIL_FLOW_KEY_BYTES bytes of space, or be
3513  * capable of being expanded to allow for that much space. */
3514 void
3515 odp_flow_key_from_flow(const struct odp_flow_key_parms *parms,
3516                        struct ofpbuf *buf)
3517 {
3518     odp_flow_key_from_flow__(parms, false, buf);
3519 }
3520
3521 /* Appends a representation of 'mask' as OVS_KEY_ATTR_* attributes to
3522  * 'buf'.
3523  *
3524  * 'buf' must have at least ODPUTIL_FLOW_KEY_BYTES bytes of space, or be
3525  * capable of being expanded to allow for that much space. */
3526 void
3527 odp_flow_key_from_mask(const struct odp_flow_key_parms *parms,
3528                        struct ofpbuf *buf)
3529 {
3530     odp_flow_key_from_flow__(parms, true, buf);
3531 }
3532
3533 /* Generate ODP flow key from the given packet metadata */
3534 void
3535 odp_key_from_pkt_metadata(struct ofpbuf *buf, const struct pkt_metadata *md)
3536 {
3537     nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, md->skb_priority);
3538
3539     if (md->tunnel.ip_dst) {
3540         tun_key_to_attr(buf, &md->tunnel, &md->tunnel, NULL);
3541     }
3542
3543     nl_msg_put_u32(buf, OVS_KEY_ATTR_SKB_MARK, md->pkt_mark);
3544
3545     /* Add an ingress port attribute if 'odp_in_port' is not the magical
3546      * value "ODPP_NONE". */
3547     if (md->in_port.odp_port != ODPP_NONE) {
3548         nl_msg_put_odp_port(buf, OVS_KEY_ATTR_IN_PORT, md->in_port.odp_port);
3549     }
3550 }
3551
3552 /* Generate packet metadata from the given ODP flow key. */
3553 void
3554 odp_key_to_pkt_metadata(const struct nlattr *key, size_t key_len,
3555                         struct pkt_metadata *md)
3556 {
3557     const struct nlattr *nla;
3558     size_t left;
3559     uint32_t wanted_attrs = 1u << OVS_KEY_ATTR_PRIORITY |
3560         1u << OVS_KEY_ATTR_SKB_MARK | 1u << OVS_KEY_ATTR_TUNNEL |
3561         1u << OVS_KEY_ATTR_IN_PORT;
3562
3563     pkt_metadata_init(md, ODPP_NONE);
3564
3565     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
3566         uint16_t type = nl_attr_type(nla);
3567         size_t len = nl_attr_get_size(nla);
3568         int expected_len = odp_key_attr_len(ovs_flow_key_attr_lens,
3569                                             OVS_KEY_ATTR_MAX, type);
3570
3571         if (len != expected_len && expected_len >= 0) {
3572             continue;
3573         }
3574
3575         switch (type) {
3576         case OVS_KEY_ATTR_RECIRC_ID:
3577             md->recirc_id = nl_attr_get_u32(nla);
3578             wanted_attrs &= ~(1u << OVS_KEY_ATTR_RECIRC_ID);
3579             break;
3580         case OVS_KEY_ATTR_DP_HASH:
3581             md->dp_hash = nl_attr_get_u32(nla);
3582             wanted_attrs &= ~(1u << OVS_KEY_ATTR_DP_HASH);
3583             break;
3584         case OVS_KEY_ATTR_PRIORITY:
3585             md->skb_priority = nl_attr_get_u32(nla);
3586             wanted_attrs &= ~(1u << OVS_KEY_ATTR_PRIORITY);
3587             break;
3588         case OVS_KEY_ATTR_SKB_MARK:
3589             md->pkt_mark = nl_attr_get_u32(nla);
3590             wanted_attrs &= ~(1u << OVS_KEY_ATTR_SKB_MARK);
3591             break;
3592         case OVS_KEY_ATTR_TUNNEL: {
3593             enum odp_key_fitness res;
3594
3595             res = odp_tun_key_from_attr(nla, true, &md->tunnel);
3596             if (res == ODP_FIT_ERROR) {
3597                 memset(&md->tunnel, 0, sizeof md->tunnel);
3598             } else if (res == ODP_FIT_PERFECT) {
3599                 wanted_attrs &= ~(1u << OVS_KEY_ATTR_TUNNEL);
3600             }
3601             break;
3602         }
3603         case OVS_KEY_ATTR_IN_PORT:
3604             md->in_port.odp_port = nl_attr_get_odp_port(nla);
3605             wanted_attrs &= ~(1u << OVS_KEY_ATTR_IN_PORT);
3606             break;
3607         default:
3608             break;
3609         }
3610
3611         if (!wanted_attrs) {
3612             return; /* Have everything. */
3613         }
3614     }
3615 }
3616
3617 uint32_t
3618 odp_flow_key_hash(const struct nlattr *key, size_t key_len)
3619 {
3620     BUILD_ASSERT_DECL(!(NLA_ALIGNTO % sizeof(uint32_t)));
3621     return hash_words(ALIGNED_CAST(const uint32_t *, key),
3622                       key_len / sizeof(uint32_t), 0);
3623 }
3624
3625 static void
3626 log_odp_key_attributes(struct vlog_rate_limit *rl, const char *title,
3627                        uint64_t attrs, int out_of_range_attr,
3628                        const struct nlattr *key, size_t key_len)
3629 {
3630     struct ds s;
3631     int i;
3632
3633     if (VLOG_DROP_DBG(rl)) {
3634         return;
3635     }
3636
3637     ds_init(&s);
3638     for (i = 0; i < 64; i++) {
3639         if (attrs & (UINT64_C(1) << i)) {
3640             char namebuf[OVS_KEY_ATTR_BUFSIZE];
3641
3642             ds_put_format(&s, " %s",
3643                           ovs_key_attr_to_string(i, namebuf, sizeof namebuf));
3644         }
3645     }
3646     if (out_of_range_attr) {
3647         ds_put_format(&s, " %d (and possibly others)", out_of_range_attr);
3648     }
3649
3650     ds_put_cstr(&s, ": ");
3651     odp_flow_key_format(key, key_len, &s);
3652
3653     VLOG_DBG("%s:%s", title, ds_cstr(&s));
3654     ds_destroy(&s);
3655 }
3656
3657 static uint8_t
3658 odp_to_ovs_frag(uint8_t odp_frag, bool is_mask)
3659 {
3660     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3661
3662     if (is_mask) {
3663         return odp_frag ? FLOW_NW_FRAG_MASK : 0;
3664     }
3665
3666     if (odp_frag > OVS_FRAG_TYPE_LATER) {
3667         VLOG_ERR_RL(&rl, "invalid frag %"PRIu8" in flow key", odp_frag);
3668         return 0xff; /* Error. */
3669     }
3670
3671     return (odp_frag == OVS_FRAG_TYPE_NONE) ? 0
3672         : (odp_frag == OVS_FRAG_TYPE_FIRST) ? FLOW_NW_FRAG_ANY
3673         :  FLOW_NW_FRAG_ANY | FLOW_NW_FRAG_LATER;
3674 }
3675
3676 static bool
3677 parse_flow_nlattrs(const struct nlattr *key, size_t key_len,
3678                    const struct nlattr *attrs[], uint64_t *present_attrsp,
3679                    int *out_of_range_attrp)
3680 {
3681     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3682     const struct nlattr *nla;
3683     uint64_t present_attrs;
3684     size_t left;
3685
3686     BUILD_ASSERT(OVS_KEY_ATTR_MAX < CHAR_BIT * sizeof present_attrs);
3687     present_attrs = 0;
3688     *out_of_range_attrp = 0;
3689     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
3690         uint16_t type = nl_attr_type(nla);
3691         size_t len = nl_attr_get_size(nla);
3692         int expected_len = odp_key_attr_len(ovs_flow_key_attr_lens,
3693                                             OVS_KEY_ATTR_MAX, type);
3694
3695         if (len != expected_len && expected_len >= 0) {
3696             char namebuf[OVS_KEY_ATTR_BUFSIZE];
3697
3698             VLOG_ERR_RL(&rl, "attribute %s has length %"PRIuSIZE" but should have "
3699                         "length %d", ovs_key_attr_to_string(type, namebuf,
3700                                                             sizeof namebuf),
3701                         len, expected_len);
3702             return false;
3703         }
3704
3705         if (type > OVS_KEY_ATTR_MAX) {
3706             *out_of_range_attrp = type;
3707         } else {
3708             if (present_attrs & (UINT64_C(1) << type)) {
3709                 char namebuf[OVS_KEY_ATTR_BUFSIZE];
3710
3711                 VLOG_ERR_RL(&rl, "duplicate %s attribute in flow key",
3712                             ovs_key_attr_to_string(type,
3713                                                    namebuf, sizeof namebuf));
3714                 return false;
3715             }
3716
3717             present_attrs |= UINT64_C(1) << type;
3718             attrs[type] = nla;
3719         }
3720     }
3721     if (left) {
3722         VLOG_ERR_RL(&rl, "trailing garbage in flow key");
3723         return false;
3724     }
3725
3726     *present_attrsp = present_attrs;
3727     return true;
3728 }
3729
3730 static enum odp_key_fitness
3731 check_expectations(uint64_t present_attrs, int out_of_range_attr,
3732                    uint64_t expected_attrs,
3733                    const struct nlattr *key, size_t key_len)
3734 {
3735     uint64_t missing_attrs;
3736     uint64_t extra_attrs;
3737
3738     missing_attrs = expected_attrs & ~present_attrs;
3739     if (missing_attrs) {
3740         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3741         log_odp_key_attributes(&rl, "expected but not present",
3742                                missing_attrs, 0, key, key_len);
3743         return ODP_FIT_TOO_LITTLE;
3744     }
3745
3746     extra_attrs = present_attrs & ~expected_attrs;
3747     if (extra_attrs || out_of_range_attr) {
3748         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3749         log_odp_key_attributes(&rl, "present but not expected",
3750                                extra_attrs, out_of_range_attr, key, key_len);
3751         return ODP_FIT_TOO_MUCH;
3752     }
3753
3754     return ODP_FIT_PERFECT;
3755 }
3756
3757 static bool
3758 parse_ethertype(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
3759                 uint64_t present_attrs, uint64_t *expected_attrs,
3760                 struct flow *flow, const struct flow *src_flow)
3761 {
3762     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3763     bool is_mask = flow != src_flow;
3764
3765     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE)) {
3766         flow->dl_type = nl_attr_get_be16(attrs[OVS_KEY_ATTR_ETHERTYPE]);
3767         if (!is_mask && ntohs(flow->dl_type) < ETH_TYPE_MIN) {
3768             VLOG_ERR_RL(&rl, "invalid Ethertype %"PRIu16" in flow key",
3769                         ntohs(flow->dl_type));
3770             return false;
3771         }
3772         if (is_mask && ntohs(src_flow->dl_type) < ETH_TYPE_MIN &&
3773             flow->dl_type != htons(0xffff)) {
3774             return false;
3775         }
3776         *expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE;
3777     } else {
3778         if (!is_mask) {
3779             flow->dl_type = htons(FLOW_DL_TYPE_NONE);
3780         } else if (ntohs(src_flow->dl_type) < ETH_TYPE_MIN) {
3781             /* See comments in odp_flow_key_from_flow__(). */
3782             VLOG_ERR_RL(&rl, "mask expected for non-Ethernet II frame");
3783             return false;
3784         }
3785     }
3786     return true;
3787 }
3788
3789 static enum odp_key_fitness
3790 parse_l2_5_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
3791                   uint64_t present_attrs, int out_of_range_attr,
3792                   uint64_t expected_attrs, struct flow *flow,
3793                   const struct nlattr *key, size_t key_len,
3794                   const struct flow *src_flow)
3795 {
3796     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3797     bool is_mask = src_flow != flow;
3798     const void *check_start = NULL;
3799     size_t check_len = 0;
3800     enum ovs_key_attr expected_bit = 0xff;
3801
3802     if (eth_type_mpls(src_flow->dl_type)) {
3803         if (!is_mask || present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_MPLS)) {
3804             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_MPLS);
3805         }
3806         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_MPLS)) {
3807             size_t size = nl_attr_get_size(attrs[OVS_KEY_ATTR_MPLS]);
3808             const ovs_be32 *mpls_lse = nl_attr_get(attrs[OVS_KEY_ATTR_MPLS]);
3809             int n = size / sizeof(ovs_be32);
3810             int i;
3811
3812             if (!size || size % sizeof(ovs_be32)) {
3813                 return ODP_FIT_ERROR;
3814             }
3815             if (flow->mpls_lse[0] && flow->dl_type != htons(0xffff)) {
3816                 return ODP_FIT_ERROR;
3817             }
3818
3819             for (i = 0; i < n && i < FLOW_MAX_MPLS_LABELS; i++) {
3820                 flow->mpls_lse[i] = mpls_lse[i];
3821             }
3822             if (n > FLOW_MAX_MPLS_LABELS) {
3823                 return ODP_FIT_TOO_MUCH;
3824             }
3825
3826             if (!is_mask) {
3827                 /* BOS may be set only in the innermost label. */
3828                 for (i = 0; i < n - 1; i++) {
3829                     if (flow->mpls_lse[i] & htonl(MPLS_BOS_MASK)) {
3830                         return ODP_FIT_ERROR;
3831                     }
3832                 }
3833
3834                 /* BOS must be set in the innermost label. */
3835                 if (n < FLOW_MAX_MPLS_LABELS
3836                     && !(flow->mpls_lse[n - 1] & htonl(MPLS_BOS_MASK))) {
3837                     return ODP_FIT_TOO_LITTLE;
3838                 }
3839             }
3840         }
3841
3842         goto done;
3843     } else if (src_flow->dl_type == htons(ETH_TYPE_IP)) {
3844         if (!is_mask) {
3845             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV4;
3846         }
3847         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV4)) {
3848             const struct ovs_key_ipv4 *ipv4_key;
3849
3850             ipv4_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV4]);
3851             put_ipv4_key(ipv4_key, flow, is_mask);
3852             if (flow->nw_frag > FLOW_NW_FRAG_MASK) {
3853                 return ODP_FIT_ERROR;
3854             }
3855             if (is_mask) {
3856                 check_start = ipv4_key;
3857                 check_len = sizeof *ipv4_key;
3858                 expected_bit = OVS_KEY_ATTR_IPV4;
3859             }
3860         }
3861     } else if (src_flow->dl_type == htons(ETH_TYPE_IPV6)) {
3862         if (!is_mask) {
3863             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV6;
3864         }
3865         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV6)) {
3866             const struct ovs_key_ipv6 *ipv6_key;
3867
3868             ipv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV6]);
3869             put_ipv6_key(ipv6_key, flow, is_mask);
3870             if (flow->nw_frag > FLOW_NW_FRAG_MASK) {
3871                 return ODP_FIT_ERROR;
3872             }
3873             if (is_mask) {
3874                 check_start = ipv6_key;
3875                 check_len = sizeof *ipv6_key;
3876                 expected_bit = OVS_KEY_ATTR_IPV6;
3877             }
3878         }
3879     } else if (src_flow->dl_type == htons(ETH_TYPE_ARP) ||
3880                src_flow->dl_type == htons(ETH_TYPE_RARP)) {
3881         if (!is_mask) {
3882             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ARP;
3883         }
3884         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ARP)) {
3885             const struct ovs_key_arp *arp_key;
3886
3887             arp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ARP]);
3888             if (!is_mask && (arp_key->arp_op & htons(0xff00))) {
3889                 VLOG_ERR_RL(&rl, "unsupported ARP opcode %"PRIu16" in flow "
3890                             "key", ntohs(arp_key->arp_op));
3891                 return ODP_FIT_ERROR;
3892             }
3893             put_arp_key(arp_key, flow);
3894             if (is_mask) {
3895                 check_start = arp_key;
3896                 check_len = sizeof *arp_key;
3897                 expected_bit = OVS_KEY_ATTR_ARP;
3898             }
3899         }
3900     } else {
3901         goto done;
3902     }
3903     if (check_len > 0) { /* Happens only when 'is_mask'. */
3904         if (!is_all_zeros(check_start, check_len) &&
3905             flow->dl_type != htons(0xffff)) {
3906             return ODP_FIT_ERROR;
3907         } else {
3908             expected_attrs |= UINT64_C(1) << expected_bit;
3909         }
3910     }
3911
3912     expected_bit = OVS_KEY_ATTR_UNSPEC;
3913     if (src_flow->nw_proto == IPPROTO_TCP
3914         && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
3915             src_flow->dl_type == htons(ETH_TYPE_IPV6))
3916         && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3917         if (!is_mask) {
3918             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP;
3919         }
3920         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP)) {
3921             const union ovs_key_tp *tcp_key;
3922
3923             tcp_key = nl_attr_get(attrs[OVS_KEY_ATTR_TCP]);
3924             put_tp_key(tcp_key, flow);
3925             expected_bit = OVS_KEY_ATTR_TCP;
3926         }
3927         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP_FLAGS)) {
3928             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP_FLAGS;
3929             flow->tcp_flags = nl_attr_get_be16(attrs[OVS_KEY_ATTR_TCP_FLAGS]);
3930         }
3931     } else if (src_flow->nw_proto == IPPROTO_UDP
3932                && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
3933                    src_flow->dl_type == htons(ETH_TYPE_IPV6))
3934                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3935         if (!is_mask) {
3936             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_UDP;
3937         }
3938         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_UDP)) {
3939             const union ovs_key_tp *udp_key;
3940
3941             udp_key = nl_attr_get(attrs[OVS_KEY_ATTR_UDP]);
3942             put_tp_key(udp_key, flow);
3943             expected_bit = OVS_KEY_ATTR_UDP;
3944         }
3945     } else if (src_flow->nw_proto == IPPROTO_SCTP
3946                && (src_flow->dl_type == htons(ETH_TYPE_IP) ||
3947                    src_flow->dl_type == htons(ETH_TYPE_IPV6))
3948                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3949         if (!is_mask) {
3950             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_SCTP;
3951         }
3952         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_SCTP)) {
3953             const union ovs_key_tp *sctp_key;
3954
3955             sctp_key = nl_attr_get(attrs[OVS_KEY_ATTR_SCTP]);
3956             put_tp_key(sctp_key, flow);
3957             expected_bit = OVS_KEY_ATTR_SCTP;
3958         }
3959     } else if (src_flow->nw_proto == IPPROTO_ICMP
3960                && src_flow->dl_type == htons(ETH_TYPE_IP)
3961                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3962         if (!is_mask) {
3963             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMP;
3964         }
3965         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMP)) {
3966             const struct ovs_key_icmp *icmp_key;
3967
3968             icmp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMP]);
3969             flow->tp_src = htons(icmp_key->icmp_type);
3970             flow->tp_dst = htons(icmp_key->icmp_code);
3971             expected_bit = OVS_KEY_ATTR_ICMP;
3972         }
3973     } else if (src_flow->nw_proto == IPPROTO_ICMPV6
3974                && src_flow->dl_type == htons(ETH_TYPE_IPV6)
3975                && !(src_flow->nw_frag & FLOW_NW_FRAG_LATER)) {
3976         if (!is_mask) {
3977             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMPV6;
3978         }
3979         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMPV6)) {
3980             const struct ovs_key_icmpv6 *icmpv6_key;
3981
3982             icmpv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMPV6]);
3983             flow->tp_src = htons(icmpv6_key->icmpv6_type);
3984             flow->tp_dst = htons(icmpv6_key->icmpv6_code);
3985             expected_bit = OVS_KEY_ATTR_ICMPV6;
3986             if (src_flow->tp_dst == htons(0) &&
3987                 (src_flow->tp_src == htons(ND_NEIGHBOR_SOLICIT) ||
3988                  src_flow->tp_src == htons(ND_NEIGHBOR_ADVERT))) {
3989                 if (!is_mask) {
3990                     expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
3991                 }
3992                 if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ND)) {
3993                     const struct ovs_key_nd *nd_key;
3994
3995                     nd_key = nl_attr_get(attrs[OVS_KEY_ATTR_ND]);
3996                     memcpy(&flow->nd_target, nd_key->nd_target,
3997                            sizeof flow->nd_target);
3998                     memcpy(flow->arp_sha, nd_key->nd_sll, ETH_ADDR_LEN);
3999                     memcpy(flow->arp_tha, nd_key->nd_tll, ETH_ADDR_LEN);
4000                     if (is_mask) {
4001                         if (!is_all_zeros(nd_key, sizeof *nd_key) &&
4002                             (flow->tp_src != htons(0xffff) ||
4003                              flow->tp_dst != htons(0xffff))) {
4004                             return ODP_FIT_ERROR;
4005                         } else {
4006                             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
4007                         }
4008                     }
4009                 }
4010             }
4011         }
4012     }
4013     if (is_mask && expected_bit != OVS_KEY_ATTR_UNSPEC) {
4014         if ((flow->tp_src || flow->tp_dst) && flow->nw_proto != 0xff) {
4015             return ODP_FIT_ERROR;
4016         } else {
4017             expected_attrs |= UINT64_C(1) << expected_bit;
4018         }
4019     }
4020
4021 done:
4022     return check_expectations(present_attrs, out_of_range_attr, expected_attrs,
4023                               key, key_len);
4024 }
4025
4026 /* Parse 802.1Q header then encapsulated L3 attributes. */
4027 static enum odp_key_fitness
4028 parse_8021q_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
4029                    uint64_t present_attrs, int out_of_range_attr,
4030                    uint64_t expected_attrs, struct flow *flow,
4031                    const struct nlattr *key, size_t key_len,
4032                    const struct flow *src_flow)
4033 {
4034     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4035     bool is_mask = src_flow != flow;
4036
4037     const struct nlattr *encap
4038         = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)
4039            ? attrs[OVS_KEY_ATTR_ENCAP] : NULL);
4040     enum odp_key_fitness encap_fitness;
4041     enum odp_key_fitness fitness;
4042
4043     /* Calculate fitness of outer attributes. */
4044     if (!is_mask) {
4045         expected_attrs |= ((UINT64_C(1) << OVS_KEY_ATTR_VLAN) |
4046                           (UINT64_C(1) << OVS_KEY_ATTR_ENCAP));
4047     } else {
4048         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)) {
4049             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_VLAN);
4050         }
4051         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)) {
4052             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_ENCAP);
4053         }
4054     }
4055     fitness = check_expectations(present_attrs, out_of_range_attr,
4056                                  expected_attrs, key, key_len);
4057
4058     /* Set vlan_tci.
4059      * Remove the TPID from dl_type since it's not the real Ethertype.  */
4060     flow->dl_type = htons(0);
4061     flow->vlan_tci = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)
4062                       ? nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN])
4063                       : htons(0));
4064     if (!is_mask) {
4065         if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN))) {
4066             return ODP_FIT_TOO_LITTLE;
4067         } else if (flow->vlan_tci == htons(0)) {
4068             /* Corner case for a truncated 802.1Q header. */
4069             if (fitness == ODP_FIT_PERFECT && nl_attr_get_size(encap)) {
4070                 return ODP_FIT_TOO_MUCH;
4071             }
4072             return fitness;
4073         } else if (!(flow->vlan_tci & htons(VLAN_CFI))) {
4074             VLOG_ERR_RL(&rl, "OVS_KEY_ATTR_VLAN 0x%04"PRIx16" is nonzero "
4075                         "but CFI bit is not set", ntohs(flow->vlan_tci));
4076             return ODP_FIT_ERROR;
4077         }
4078     } else {
4079         if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP))) {
4080             return fitness;
4081         }
4082     }
4083
4084     /* Now parse the encapsulated attributes. */
4085     if (!parse_flow_nlattrs(nl_attr_get(encap), nl_attr_get_size(encap),
4086                             attrs, &present_attrs, &out_of_range_attr)) {
4087         return ODP_FIT_ERROR;
4088     }
4089     expected_attrs = 0;
4090
4091     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow, src_flow)) {
4092         return ODP_FIT_ERROR;
4093     }
4094     encap_fitness = parse_l2_5_onward(attrs, present_attrs, out_of_range_attr,
4095                                       expected_attrs, flow, key, key_len,
4096                                       src_flow);
4097
4098     /* The overall fitness is the worse of the outer and inner attributes. */
4099     return MAX(fitness, encap_fitness);
4100 }
4101
4102 static enum odp_key_fitness
4103 odp_flow_key_to_flow__(const struct nlattr *key, size_t key_len,
4104                        const struct nlattr *src_key, size_t src_key_len,
4105                        struct flow *flow, const struct flow *src_flow,
4106                        bool udpif)
4107 {
4108     const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1];
4109     uint64_t expected_attrs;
4110     uint64_t present_attrs;
4111     int out_of_range_attr;
4112     bool is_mask = src_flow != flow;
4113
4114     memset(flow, 0, sizeof *flow);
4115
4116     /* Parse attributes. */
4117     if (!parse_flow_nlattrs(key, key_len, attrs, &present_attrs,
4118                             &out_of_range_attr)) {
4119         return ODP_FIT_ERROR;
4120     }
4121     expected_attrs = 0;
4122
4123     /* Metadata. */
4124     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_RECIRC_ID)) {
4125         flow->recirc_id = nl_attr_get_u32(attrs[OVS_KEY_ATTR_RECIRC_ID]);
4126         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_RECIRC_ID;
4127     } else if (is_mask) {
4128         /* Always exact match recirc_id if it is not specified. */
4129         flow->recirc_id = UINT32_MAX;
4130     }
4131
4132     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_DP_HASH)) {
4133         flow->dp_hash = nl_attr_get_u32(attrs[OVS_KEY_ATTR_DP_HASH]);
4134         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_DP_HASH;
4135     }
4136     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_PRIORITY)) {
4137         flow->skb_priority = nl_attr_get_u32(attrs[OVS_KEY_ATTR_PRIORITY]);
4138         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_PRIORITY;
4139     }
4140
4141     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_SKB_MARK)) {
4142         flow->pkt_mark = nl_attr_get_u32(attrs[OVS_KEY_ATTR_SKB_MARK]);
4143         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_SKB_MARK;
4144     }
4145
4146     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TUNNEL)) {
4147         enum odp_key_fitness res;
4148
4149         res = odp_tun_key_from_attr__(attrs[OVS_KEY_ATTR_TUNNEL],
4150                                       is_mask ? src_key : NULL,
4151                                       src_key_len, &src_flow->tunnel,
4152                                       &flow->tunnel, udpif);
4153         if (res == ODP_FIT_ERROR) {
4154             return ODP_FIT_ERROR;
4155         } else if (res == ODP_FIT_PERFECT) {
4156             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TUNNEL;
4157         }
4158     }
4159
4160     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IN_PORT)) {
4161         flow->in_port.odp_port
4162             = nl_attr_get_odp_port(attrs[OVS_KEY_ATTR_IN_PORT]);
4163         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IN_PORT;
4164     } else if (!is_mask) {
4165         flow->in_port.odp_port = ODPP_NONE;
4166     }
4167
4168     /* Ethernet header. */
4169     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERNET)) {
4170         const struct ovs_key_ethernet *eth_key;
4171
4172         eth_key = nl_attr_get(attrs[OVS_KEY_ATTR_ETHERNET]);
4173         put_ethernet_key(eth_key, flow);
4174         if (is_mask) {
4175             expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
4176         }
4177     }
4178     if (!is_mask) {
4179         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
4180     }
4181
4182     /* Get Ethertype or 802.1Q TPID or FLOW_DL_TYPE_NONE. */
4183     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow,
4184         src_flow)) {
4185         return ODP_FIT_ERROR;
4186     }
4187
4188     if (is_mask
4189         ? (src_flow->vlan_tci & htons(VLAN_CFI)) != 0
4190         : src_flow->dl_type == htons(ETH_TYPE_VLAN)) {
4191         return parse_8021q_onward(attrs, present_attrs, out_of_range_attr,
4192                                   expected_attrs, flow, key, key_len, src_flow);
4193     }
4194     if (is_mask) {
4195         flow->vlan_tci = htons(0xffff);
4196         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN)) {
4197             flow->vlan_tci = nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN]);
4198             expected_attrs |= (UINT64_C(1) << OVS_KEY_ATTR_VLAN);
4199         }
4200     }
4201     return parse_l2_5_onward(attrs, present_attrs, out_of_range_attr,
4202                              expected_attrs, flow, key, key_len, src_flow);
4203 }
4204
4205 /* Converts the 'key_len' bytes of OVS_KEY_ATTR_* attributes in 'key' to a flow
4206  * structure in 'flow'.  Returns an ODP_FIT_* value that indicates how well
4207  * 'key' fits our expectations for what a flow key should contain.
4208  *
4209  * The 'in_port' will be the datapath's understanding of the port.  The
4210  * caller will need to translate with odp_port_to_ofp_port() if the
4211  * OpenFlow port is needed.
4212  *
4213  * This function doesn't take the packet itself as an argument because none of
4214  * the currently understood OVS_KEY_ATTR_* attributes require it.  Currently,
4215  * it is always possible to infer which additional attribute(s) should appear
4216  * by looking at the attributes for lower-level protocols, e.g. if the network
4217  * protocol in OVS_KEY_ATTR_IPV4 or OVS_KEY_ATTR_IPV6 is IPPROTO_TCP then we
4218  * know that a OVS_KEY_ATTR_TCP attribute must appear and that otherwise it
4219  * must be absent. */
4220 enum odp_key_fitness
4221 odp_flow_key_to_flow(const struct nlattr *key, size_t key_len,
4222                      struct flow *flow)
4223 {
4224    return odp_flow_key_to_flow__(key, key_len, NULL, 0, flow, flow, false);
4225 }
4226
4227 /* Converts the 'mask_key_len' bytes of OVS_KEY_ATTR_* attributes in 'mask_key'
4228  * to a mask structure in 'mask'.  'flow' must be a previously translated flow
4229  * corresponding to 'mask' and similarly flow_key/flow_key_len must be the
4230  * attributes from that flow.  Returns an ODP_FIT_* value that indicates how
4231  * well 'key' fits our expectations for what a flow key should contain. */
4232 enum odp_key_fitness
4233 odp_flow_key_to_mask(const struct nlattr *mask_key, size_t mask_key_len,
4234                      const struct nlattr *flow_key, size_t flow_key_len,
4235                      struct flow *mask, const struct flow *flow)
4236 {
4237    return odp_flow_key_to_flow__(mask_key, mask_key_len, flow_key, flow_key_len,
4238                                  mask, flow, false);
4239 }
4240
4241 /* These functions are similar to their non-"_udpif" variants but output a
4242  * 'flow' that is suitable for fast-path packet processing.
4243  *
4244  * Some fields have different representation for flow setup and per-
4245  * packet processing (i.e. different between ofproto-dpif and userspace
4246  * datapath). In particular, with the non-"_udpif" functions, struct
4247  * tun_metadata is in the per-flow format (using 'present.map' and 'opts.u8');
4248  * with these functions, struct tun_metadata is in the per-packet format
4249  * (using 'present.len' and 'opts.gnv'). */
4250 enum odp_key_fitness
4251 odp_flow_key_to_flow_udpif(const struct nlattr *key, size_t key_len,
4252                            struct flow *flow)
4253 {
4254    return odp_flow_key_to_flow__(key, key_len, NULL, 0, flow, flow, true);
4255 }
4256
4257 enum odp_key_fitness
4258 odp_flow_key_to_mask_udpif(const struct nlattr *mask_key, size_t mask_key_len,
4259                            const struct nlattr *flow_key, size_t flow_key_len,
4260                            struct flow *mask, const struct flow *flow)
4261 {
4262    return odp_flow_key_to_flow__(mask_key, mask_key_len, flow_key, flow_key_len,
4263                                  mask, flow, true);
4264 }
4265
4266 /* Returns 'fitness' as a string, for use in debug messages. */
4267 const char *
4268 odp_key_fitness_to_string(enum odp_key_fitness fitness)
4269 {
4270     switch (fitness) {
4271     case ODP_FIT_PERFECT:
4272         return "OK";
4273     case ODP_FIT_TOO_MUCH:
4274         return "too_much";
4275     case ODP_FIT_TOO_LITTLE:
4276         return "too_little";
4277     case ODP_FIT_ERROR:
4278         return "error";
4279     default:
4280         return "<unknown>";
4281     }
4282 }
4283
4284 /* Appends an OVS_ACTION_ATTR_USERSPACE action to 'odp_actions' that specifies
4285  * Netlink PID 'pid'.  If 'userdata' is nonnull, adds a userdata attribute
4286  * whose contents are the 'userdata_size' bytes at 'userdata' and returns the
4287  * offset within 'odp_actions' of the start of the cookie.  (If 'userdata' is
4288  * null, then the return value is not meaningful.) */
4289 size_t
4290 odp_put_userspace_action(uint32_t pid,
4291                          const void *userdata, size_t userdata_size,
4292                          odp_port_t tunnel_out_port,
4293                          bool include_actions,
4294                          struct ofpbuf *odp_actions)
4295 {
4296     size_t userdata_ofs;
4297     size_t offset;
4298
4299     offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_USERSPACE);
4300     nl_msg_put_u32(odp_actions, OVS_USERSPACE_ATTR_PID, pid);
4301     if (userdata) {
4302         userdata_ofs = odp_actions->size + NLA_HDRLEN;
4303
4304         /* The OVS kernel module before OVS 1.11 and the upstream Linux kernel
4305          * module before Linux 3.10 required the userdata to be exactly 8 bytes
4306          * long:
4307          *
4308          *   - The kernel rejected shorter userdata with -ERANGE.
4309          *
4310          *   - The kernel silently dropped userdata beyond the first 8 bytes.
4311          *
4312          * Thus, for maximum compatibility, always put at least 8 bytes.  (We
4313          * separately disable features that required more than 8 bytes.) */
4314         memcpy(nl_msg_put_unspec_zero(odp_actions, OVS_USERSPACE_ATTR_USERDATA,
4315                                       MAX(8, userdata_size)),
4316                userdata, userdata_size);
4317     } else {
4318         userdata_ofs = 0;
4319     }
4320     if (tunnel_out_port != ODPP_NONE) {
4321         nl_msg_put_odp_port(odp_actions, OVS_USERSPACE_ATTR_EGRESS_TUN_PORT,
4322                             tunnel_out_port);
4323     }
4324     if (include_actions) {
4325         nl_msg_put_flag(odp_actions, OVS_USERSPACE_ATTR_ACTIONS);
4326     }
4327     nl_msg_end_nested(odp_actions, offset);
4328
4329     return userdata_ofs;
4330 }
4331
4332 void
4333 odp_put_tunnel_action(const struct flow_tnl *tunnel,
4334                       struct ofpbuf *odp_actions)
4335 {
4336     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
4337     tun_key_to_attr(odp_actions, tunnel, tunnel, NULL);
4338     nl_msg_end_nested(odp_actions, offset);
4339 }
4340
4341 void
4342 odp_put_tnl_push_action(struct ofpbuf *odp_actions,
4343                         struct ovs_action_push_tnl *data)
4344 {
4345     int size = offsetof(struct ovs_action_push_tnl, header);
4346
4347     size += data->header_len;
4348     nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_TUNNEL_PUSH, data, size);
4349 }
4350
4351 \f
4352 /* The commit_odp_actions() function and its helpers. */
4353
4354 static void
4355 commit_set_action(struct ofpbuf *odp_actions, enum ovs_key_attr key_type,
4356                   const void *key, size_t key_size)
4357 {
4358     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
4359     nl_msg_put_unspec(odp_actions, key_type, key, key_size);
4360     nl_msg_end_nested(odp_actions, offset);
4361 }
4362
4363 /* Masked set actions have a mask following the data within the netlink
4364  * attribute.  The unmasked bits in the data will be cleared as the data
4365  * is copied to the action. */
4366 void
4367 commit_masked_set_action(struct ofpbuf *odp_actions,
4368                          enum ovs_key_attr key_type,
4369                          const void *key_, const void *mask_, size_t key_size)
4370 {
4371     size_t offset = nl_msg_start_nested(odp_actions,
4372                                         OVS_ACTION_ATTR_SET_MASKED);
4373     char *data = nl_msg_put_unspec_uninit(odp_actions, key_type, key_size * 2);
4374     const char *key = key_, *mask = mask_;
4375
4376     memcpy(data + key_size, mask, key_size);
4377     /* Clear unmasked bits while copying. */
4378     while (key_size--) {
4379         *data++ = *key++ & *mask++;
4380     }
4381     nl_msg_end_nested(odp_actions, offset);
4382 }
4383
4384 /* If any of the flow key data that ODP actions can modify are different in
4385  * 'base->tunnel' and 'flow->tunnel', appends a set_tunnel ODP action to
4386  * 'odp_actions' that change the flow tunneling information in key from
4387  * 'base->tunnel' into 'flow->tunnel', and then changes 'base->tunnel' in the
4388  * same way.  In other words, operates the same as commit_odp_actions(), but
4389  * only on tunneling information. */
4390 void
4391 commit_odp_tunnel_action(const struct flow *flow, struct flow *base,
4392                          struct ofpbuf *odp_actions)
4393 {
4394     /* A valid IPV4_TUNNEL must have non-zero ip_dst. */
4395     if (flow->tunnel.ip_dst) {
4396         if (!memcmp(&base->tunnel, &flow->tunnel, sizeof base->tunnel)) {
4397             return;
4398         }
4399         memcpy(&base->tunnel, &flow->tunnel, sizeof base->tunnel);
4400         odp_put_tunnel_action(&base->tunnel, odp_actions);
4401     }
4402 }
4403
4404 static bool
4405 commit(enum ovs_key_attr attr, bool use_masked_set,
4406        const void *key, void *base, void *mask, size_t size,
4407        struct ofpbuf *odp_actions)
4408 {
4409     if (memcmp(key, base, size)) {
4410         bool fully_masked = odp_mask_is_exact(attr, mask, size);
4411
4412         if (use_masked_set && !fully_masked) {
4413             commit_masked_set_action(odp_actions, attr, key, mask, size);
4414         } else {
4415             if (!fully_masked) {
4416                 memset(mask, 0xff, size);
4417             }
4418             commit_set_action(odp_actions, attr, key, size);
4419         }
4420         memcpy(base, key, size);
4421         return true;
4422     } else {
4423         /* Mask bits are set when we have either read or set the corresponding
4424          * values.  Masked bits will be exact-matched, no need to set them
4425          * if the value did not actually change. */
4426         return false;
4427     }
4428 }
4429
4430 static void
4431 get_ethernet_key(const struct flow *flow, struct ovs_key_ethernet *eth)
4432 {
4433     memcpy(eth->eth_src, flow->dl_src, ETH_ADDR_LEN);
4434     memcpy(eth->eth_dst, flow->dl_dst, ETH_ADDR_LEN);
4435 }
4436
4437 static void
4438 put_ethernet_key(const struct ovs_key_ethernet *eth, struct flow *flow)
4439 {
4440     memcpy(flow->dl_src, eth->eth_src, ETH_ADDR_LEN);
4441     memcpy(flow->dl_dst, eth->eth_dst, ETH_ADDR_LEN);
4442 }
4443
4444 static void
4445 commit_set_ether_addr_action(const struct flow *flow, struct flow *base_flow,
4446                              struct ofpbuf *odp_actions,
4447                              struct flow_wildcards *wc,
4448                              bool use_masked)
4449 {
4450     struct ovs_key_ethernet key, base, mask;
4451
4452     get_ethernet_key(flow, &key);
4453     get_ethernet_key(base_flow, &base);
4454     get_ethernet_key(&wc->masks, &mask);
4455
4456     if (commit(OVS_KEY_ATTR_ETHERNET, use_masked,
4457                &key, &base, &mask, sizeof key, odp_actions)) {
4458         put_ethernet_key(&base, base_flow);
4459         put_ethernet_key(&mask, &wc->masks);
4460     }
4461 }
4462
4463 static void
4464 pop_vlan(struct flow *base,
4465          struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4466 {
4467     memset(&wc->masks.vlan_tci, 0xff, sizeof wc->masks.vlan_tci);
4468
4469     if (base->vlan_tci & htons(VLAN_CFI)) {
4470         nl_msg_put_flag(odp_actions, OVS_ACTION_ATTR_POP_VLAN);
4471         base->vlan_tci = 0;
4472     }
4473 }
4474
4475 static void
4476 commit_vlan_action(ovs_be16 vlan_tci, struct flow *base,
4477                    struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4478 {
4479     if (base->vlan_tci == vlan_tci) {
4480         return;
4481     }
4482
4483     pop_vlan(base, odp_actions, wc);
4484     if (vlan_tci & htons(VLAN_CFI)) {
4485         struct ovs_action_push_vlan vlan;
4486
4487         vlan.vlan_tpid = htons(ETH_TYPE_VLAN);
4488         vlan.vlan_tci = vlan_tci;
4489         nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_PUSH_VLAN,
4490                           &vlan, sizeof vlan);
4491     }
4492     base->vlan_tci = vlan_tci;
4493 }
4494
4495 /* Wildcarding already done at action translation time. */
4496 static void
4497 commit_mpls_action(const struct flow *flow, struct flow *base,
4498                    struct ofpbuf *odp_actions)
4499 {
4500     int base_n = flow_count_mpls_labels(base, NULL);
4501     int flow_n = flow_count_mpls_labels(flow, NULL);
4502     int common_n = flow_count_common_mpls_labels(flow, flow_n, base, base_n,
4503                                                  NULL);
4504
4505     while (base_n > common_n) {
4506         if (base_n - 1 == common_n && flow_n > common_n) {
4507             /* If there is only one more LSE in base than there are common
4508              * between base and flow; and flow has at least one more LSE than
4509              * is common then the topmost LSE of base may be updated using
4510              * set */
4511             struct ovs_key_mpls mpls_key;
4512
4513             mpls_key.mpls_lse = flow->mpls_lse[flow_n - base_n];
4514             commit_set_action(odp_actions, OVS_KEY_ATTR_MPLS,
4515                               &mpls_key, sizeof mpls_key);
4516             flow_set_mpls_lse(base, 0, mpls_key.mpls_lse);
4517             common_n++;
4518         } else {
4519             /* Otherwise, if there more LSEs in base than are common between
4520              * base and flow then pop the topmost one. */
4521             ovs_be16 dl_type;
4522             bool popped;
4523
4524             /* If all the LSEs are to be popped and this is not the outermost
4525              * LSE then use ETH_TYPE_MPLS as the ethertype parameter of the
4526              * POP_MPLS action instead of flow->dl_type.
4527              *
4528              * This is because the POP_MPLS action requires its ethertype
4529              * argument to be an MPLS ethernet type but in this case
4530              * flow->dl_type will be a non-MPLS ethernet type.
4531              *
4532              * When the final POP_MPLS action occurs it use flow->dl_type and
4533              * the and the resulting packet will have the desired dl_type. */
4534             if ((!eth_type_mpls(flow->dl_type)) && base_n > 1) {
4535                 dl_type = htons(ETH_TYPE_MPLS);
4536             } else {
4537                 dl_type = flow->dl_type;
4538             }
4539             nl_msg_put_be16(odp_actions, OVS_ACTION_ATTR_POP_MPLS, dl_type);
4540             popped = flow_pop_mpls(base, base_n, flow->dl_type, NULL);
4541             ovs_assert(popped);
4542             base_n--;
4543         }
4544     }
4545
4546     /* If, after the above popping and setting, there are more LSEs in flow
4547      * than base then some LSEs need to be pushed. */
4548     while (base_n < flow_n) {
4549         struct ovs_action_push_mpls *mpls;
4550
4551         mpls = nl_msg_put_unspec_zero(odp_actions,
4552                                       OVS_ACTION_ATTR_PUSH_MPLS,
4553                                       sizeof *mpls);
4554         mpls->mpls_ethertype = flow->dl_type;
4555         mpls->mpls_lse = flow->mpls_lse[flow_n - base_n - 1];
4556         flow_push_mpls(base, base_n, mpls->mpls_ethertype, NULL);
4557         flow_set_mpls_lse(base, 0, mpls->mpls_lse);
4558         base_n++;
4559     }
4560 }
4561
4562 static void
4563 get_ipv4_key(const struct flow *flow, struct ovs_key_ipv4 *ipv4, bool is_mask)
4564 {
4565     ipv4->ipv4_src = flow->nw_src;
4566     ipv4->ipv4_dst = flow->nw_dst;
4567     ipv4->ipv4_proto = flow->nw_proto;
4568     ipv4->ipv4_tos = flow->nw_tos;
4569     ipv4->ipv4_ttl = flow->nw_ttl;
4570     ipv4->ipv4_frag = ovs_to_odp_frag(flow->nw_frag, is_mask);
4571 }
4572
4573 static void
4574 put_ipv4_key(const struct ovs_key_ipv4 *ipv4, struct flow *flow, bool is_mask)
4575 {
4576     flow->nw_src = ipv4->ipv4_src;
4577     flow->nw_dst = ipv4->ipv4_dst;
4578     flow->nw_proto = ipv4->ipv4_proto;
4579     flow->nw_tos = ipv4->ipv4_tos;
4580     flow->nw_ttl = ipv4->ipv4_ttl;
4581     flow->nw_frag = odp_to_ovs_frag(ipv4->ipv4_frag, is_mask);
4582 }
4583
4584 static void
4585 commit_set_ipv4_action(const struct flow *flow, struct flow *base_flow,
4586                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4587                        bool use_masked)
4588 {
4589     struct ovs_key_ipv4 key, mask, base;
4590
4591     /* Check that nw_proto and nw_frag remain unchanged. */
4592     ovs_assert(flow->nw_proto == base_flow->nw_proto &&
4593                flow->nw_frag == base_flow->nw_frag);
4594
4595     get_ipv4_key(flow, &key, false);
4596     get_ipv4_key(base_flow, &base, false);
4597     get_ipv4_key(&wc->masks, &mask, true);
4598     mask.ipv4_proto = 0;        /* Not writeable. */
4599     mask.ipv4_frag = 0;         /* Not writable. */
4600
4601     if (commit(OVS_KEY_ATTR_IPV4, use_masked, &key, &base, &mask, sizeof key,
4602                odp_actions)) {
4603         put_ipv4_key(&base, base_flow, false);
4604         if (mask.ipv4_proto != 0) { /* Mask was changed by commit(). */
4605             put_ipv4_key(&mask, &wc->masks, true);
4606         }
4607    }
4608 }
4609
4610 static void
4611 get_ipv6_key(const struct flow *flow, struct ovs_key_ipv6 *ipv6, bool is_mask)
4612 {
4613     memcpy(ipv6->ipv6_src, &flow->ipv6_src, sizeof ipv6->ipv6_src);
4614     memcpy(ipv6->ipv6_dst, &flow->ipv6_dst, sizeof ipv6->ipv6_dst);
4615     ipv6->ipv6_label = flow->ipv6_label;
4616     ipv6->ipv6_proto = flow->nw_proto;
4617     ipv6->ipv6_tclass = flow->nw_tos;
4618     ipv6->ipv6_hlimit = flow->nw_ttl;
4619     ipv6->ipv6_frag = ovs_to_odp_frag(flow->nw_frag, is_mask);
4620 }
4621
4622 static void
4623 put_ipv6_key(const struct ovs_key_ipv6 *ipv6, struct flow *flow, bool is_mask)
4624 {
4625     memcpy(&flow->ipv6_src, ipv6->ipv6_src, sizeof flow->ipv6_src);
4626     memcpy(&flow->ipv6_dst, ipv6->ipv6_dst, sizeof flow->ipv6_dst);
4627     flow->ipv6_label = ipv6->ipv6_label;
4628     flow->nw_proto = ipv6->ipv6_proto;
4629     flow->nw_tos = ipv6->ipv6_tclass;
4630     flow->nw_ttl = ipv6->ipv6_hlimit;
4631     flow->nw_frag = odp_to_ovs_frag(ipv6->ipv6_frag, is_mask);
4632 }
4633
4634 static void
4635 commit_set_ipv6_action(const struct flow *flow, struct flow *base_flow,
4636                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4637                        bool use_masked)
4638 {
4639     struct ovs_key_ipv6 key, mask, base;
4640
4641     /* Check that nw_proto and nw_frag remain unchanged. */
4642     ovs_assert(flow->nw_proto == base_flow->nw_proto &&
4643                flow->nw_frag == base_flow->nw_frag);
4644
4645     get_ipv6_key(flow, &key, false);
4646     get_ipv6_key(base_flow, &base, false);
4647     get_ipv6_key(&wc->masks, &mask, true);
4648     mask.ipv6_proto = 0;        /* Not writeable. */
4649     mask.ipv6_frag = 0;         /* Not writable. */
4650
4651     if (commit(OVS_KEY_ATTR_IPV6, use_masked, &key, &base, &mask, sizeof key,
4652                odp_actions)) {
4653         put_ipv6_key(&base, base_flow, false);
4654         if (mask.ipv6_proto != 0) { /* Mask was changed by commit(). */
4655             put_ipv6_key(&mask, &wc->masks, true);
4656         }
4657     }
4658 }
4659
4660 static void
4661 get_arp_key(const struct flow *flow, struct ovs_key_arp *arp)
4662 {
4663     /* ARP key has padding, clear it. */
4664     memset(arp, 0, sizeof *arp);
4665
4666     arp->arp_sip = flow->nw_src;
4667     arp->arp_tip = flow->nw_dst;
4668     arp->arp_op = htons(flow->nw_proto);
4669     memcpy(arp->arp_sha, flow->arp_sha, ETH_ADDR_LEN);
4670     memcpy(arp->arp_tha, flow->arp_tha, ETH_ADDR_LEN);
4671 }
4672
4673 static void
4674 put_arp_key(const struct ovs_key_arp *arp, struct flow *flow)
4675 {
4676     flow->nw_src = arp->arp_sip;
4677     flow->nw_dst = arp->arp_tip;
4678     flow->nw_proto = ntohs(arp->arp_op);
4679     memcpy(flow->arp_sha, arp->arp_sha, ETH_ADDR_LEN);
4680     memcpy(flow->arp_tha, arp->arp_tha, ETH_ADDR_LEN);
4681 }
4682
4683 static enum slow_path_reason
4684 commit_set_arp_action(const struct flow *flow, struct flow *base_flow,
4685                       struct ofpbuf *odp_actions, struct flow_wildcards *wc)
4686 {
4687     struct ovs_key_arp key, mask, base;
4688
4689     get_arp_key(flow, &key);
4690     get_arp_key(base_flow, &base);
4691     get_arp_key(&wc->masks, &mask);
4692
4693     if (commit(OVS_KEY_ATTR_ARP, true, &key, &base, &mask, sizeof key,
4694                odp_actions)) {
4695         put_arp_key(&base, base_flow);
4696         put_arp_key(&mask, &wc->masks);
4697         return SLOW_ACTION;
4698     }
4699     return 0;
4700 }
4701
4702 static void
4703 get_nd_key(const struct flow *flow, struct ovs_key_nd *nd)
4704 {
4705     memcpy(nd->nd_target, &flow->nd_target, sizeof flow->nd_target);
4706     /* nd_sll and nd_tll are stored in arp_sha and arp_tha, respectively */
4707     memcpy(nd->nd_sll, flow->arp_sha, ETH_ADDR_LEN);
4708     memcpy(nd->nd_tll, flow->arp_tha, ETH_ADDR_LEN);
4709 }
4710
4711 static void
4712 put_nd_key(const struct ovs_key_nd *nd, struct flow *flow)
4713 {
4714     memcpy(&flow->nd_target, &flow->nd_target, sizeof flow->nd_target);
4715     /* nd_sll and nd_tll are stored in arp_sha and arp_tha, respectively */
4716     memcpy(flow->arp_sha, nd->nd_sll, ETH_ADDR_LEN);
4717     memcpy(flow->arp_tha, nd->nd_tll, ETH_ADDR_LEN);
4718 }
4719
4720 static enum slow_path_reason
4721 commit_set_nd_action(const struct flow *flow, struct flow *base_flow,
4722                      struct ofpbuf *odp_actions,
4723                      struct flow_wildcards *wc, bool use_masked)
4724 {
4725     struct ovs_key_nd key, mask, base;
4726
4727     get_nd_key(flow, &key);
4728     get_nd_key(base_flow, &base);
4729     get_nd_key(&wc->masks, &mask);
4730
4731     if (commit(OVS_KEY_ATTR_ND, use_masked, &key, &base, &mask, sizeof key,
4732                odp_actions)) {
4733         put_nd_key(&base, base_flow);
4734         put_nd_key(&mask, &wc->masks);
4735         return SLOW_ACTION;
4736     }
4737
4738     return 0;
4739 }
4740
4741 static enum slow_path_reason
4742 commit_set_nw_action(const struct flow *flow, struct flow *base,
4743                      struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4744                      bool use_masked)
4745 {
4746     /* Check if 'flow' really has an L3 header. */
4747     if (!flow->nw_proto) {
4748         return 0;
4749     }
4750
4751     switch (ntohs(base->dl_type)) {
4752     case ETH_TYPE_IP:
4753         commit_set_ipv4_action(flow, base, odp_actions, wc, use_masked);
4754         break;
4755
4756     case ETH_TYPE_IPV6:
4757         commit_set_ipv6_action(flow, base, odp_actions, wc, use_masked);
4758         return commit_set_nd_action(flow, base, odp_actions, wc, use_masked);
4759
4760     case ETH_TYPE_ARP:
4761         return commit_set_arp_action(flow, base, odp_actions, wc);
4762     }
4763
4764     return 0;
4765 }
4766
4767 /* TCP, UDP, and SCTP keys have the same layout. */
4768 BUILD_ASSERT_DECL(sizeof(struct ovs_key_tcp) == sizeof(struct ovs_key_udp) &&
4769                   sizeof(struct ovs_key_tcp) == sizeof(struct ovs_key_sctp));
4770
4771 static void
4772 get_tp_key(const struct flow *flow, union ovs_key_tp *tp)
4773 {
4774     tp->tcp.tcp_src = flow->tp_src;
4775     tp->tcp.tcp_dst = flow->tp_dst;
4776 }
4777
4778 static void
4779 put_tp_key(const union ovs_key_tp *tp, struct flow *flow)
4780 {
4781     flow->tp_src = tp->tcp.tcp_src;
4782     flow->tp_dst = tp->tcp.tcp_dst;
4783 }
4784
4785 static void
4786 commit_set_port_action(const struct flow *flow, struct flow *base_flow,
4787                        struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4788                        bool use_masked)
4789 {
4790     enum ovs_key_attr key_type;
4791     union ovs_key_tp key, mask, base;
4792
4793     /* Check if 'flow' really has an L3 header. */
4794     if (!flow->nw_proto) {
4795         return;
4796     }
4797
4798     if (!is_ip_any(base_flow)) {
4799         return;
4800     }
4801
4802     if (flow->nw_proto == IPPROTO_TCP) {
4803         key_type = OVS_KEY_ATTR_TCP;
4804     } else if (flow->nw_proto == IPPROTO_UDP) {
4805         key_type = OVS_KEY_ATTR_UDP;
4806     } else if (flow->nw_proto == IPPROTO_SCTP) {
4807         key_type = OVS_KEY_ATTR_SCTP;
4808     } else {
4809         return;
4810     }
4811
4812     get_tp_key(flow, &key);
4813     get_tp_key(base_flow, &base);
4814     get_tp_key(&wc->masks, &mask);
4815
4816     if (commit(key_type, use_masked, &key, &base, &mask, sizeof key,
4817                odp_actions)) {
4818         put_tp_key(&base, base_flow);
4819         put_tp_key(&mask, &wc->masks);
4820     }
4821 }
4822
4823 static void
4824 commit_set_priority_action(const struct flow *flow, struct flow *base_flow,
4825                            struct ofpbuf *odp_actions,
4826                            struct flow_wildcards *wc,
4827                            bool use_masked)
4828 {
4829     uint32_t key, mask, base;
4830
4831     key = flow->skb_priority;
4832     base = base_flow->skb_priority;
4833     mask = wc->masks.skb_priority;
4834
4835     if (commit(OVS_KEY_ATTR_PRIORITY, use_masked, &key, &base, &mask,
4836                sizeof key, odp_actions)) {
4837         base_flow->skb_priority = base;
4838         wc->masks.skb_priority = mask;
4839     }
4840 }
4841
4842 static void
4843 commit_set_pkt_mark_action(const struct flow *flow, struct flow *base_flow,
4844                            struct ofpbuf *odp_actions,
4845                            struct flow_wildcards *wc,
4846                            bool use_masked)
4847 {
4848     uint32_t key, mask, base;
4849
4850     key = flow->pkt_mark;
4851     base = base_flow->pkt_mark;
4852     mask = wc->masks.pkt_mark;
4853
4854     if (commit(OVS_KEY_ATTR_SKB_MARK, use_masked, &key, &base, &mask,
4855                sizeof key, odp_actions)) {
4856         base_flow->pkt_mark = base;
4857         wc->masks.pkt_mark = mask;
4858     }
4859 }
4860
4861 /* If any of the flow key data that ODP actions can modify are different in
4862  * 'base' and 'flow', appends ODP actions to 'odp_actions' that change the flow
4863  * key from 'base' into 'flow', and then changes 'base' the same way.  Does not
4864  * commit set_tunnel actions.  Users should call commit_odp_tunnel_action()
4865  * in addition to this function if needed.  Sets fields in 'wc' that are
4866  * used as part of the action.
4867  *
4868  * Returns a reason to force processing the flow's packets into the userspace
4869  * slow path, if there is one, otherwise 0. */
4870 enum slow_path_reason
4871 commit_odp_actions(const struct flow *flow, struct flow *base,
4872                    struct ofpbuf *odp_actions, struct flow_wildcards *wc,
4873                    bool use_masked)
4874 {
4875     enum slow_path_reason slow;
4876
4877     commit_set_ether_addr_action(flow, base, odp_actions, wc, use_masked);
4878     slow = commit_set_nw_action(flow, base, odp_actions, wc, use_masked);
4879     commit_set_port_action(flow, base, odp_actions, wc, use_masked);
4880     commit_mpls_action(flow, base, odp_actions);
4881     commit_vlan_action(flow->vlan_tci, base, odp_actions, wc);
4882     commit_set_priority_action(flow, base, odp_actions, wc, use_masked);
4883     commit_set_pkt_mark_action(flow, base, odp_actions, wc, use_masked);
4884
4885     return slow;
4886 }