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