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