odp-util: Fix parsing of actions encapsulated within "sample" actions.
[sliver-openvswitch.git] / lib / odp-util.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012 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 <arpa/inet.h>
18 #include <config.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 #include "byte-order.h"
28 #include "coverage.h"
29 #include "dynamic-string.h"
30 #include "flow.h"
31 #include "netlink.h"
32 #include "ofpbuf.h"
33 #include "openvswitch/tunnel.h"
34 #include "packets.h"
35 #include "shash.h"
36 #include "timeval.h"
37 #include "util.h"
38 #include "vlog.h"
39
40 VLOG_DEFINE_THIS_MODULE(odp_util);
41
42 /* The interface between userspace and kernel uses an "OVS_*" prefix.
43  * Since this is fairly non-specific for the OVS userspace components,
44  * "ODP_*" (Open vSwitch Datapath) is used as the prefix for
45  * interactions with the datapath.
46  */
47
48 /* The set of characters that may separate one action or one key attribute
49  * from another. */
50 static const char *delimiters = ", \t\r\n";
51
52 static int parse_odp_key_attr(const char *, const struct shash *port_names,
53                               struct ofpbuf *);
54 static void format_odp_key_attr(const struct nlattr *a, struct ds *ds);
55
56 /* Returns one the following for the action with the given OVS_ACTION_ATTR_*
57  * 'type':
58  *
59  *   - For an action whose argument has a fixed length, returned that
60  *     nonnegative length in bytes.
61  *
62  *   - For an action with a variable-length argument, returns -2.
63  *
64  *   - For an invalid 'type', returns -1. */
65 static int
66 odp_action_len(uint16_t type)
67 {
68     if (type > OVS_ACTION_ATTR_MAX) {
69         return -1;
70     }
71
72     switch ((enum ovs_action_attr) type) {
73     case OVS_ACTION_ATTR_OUTPUT: return sizeof(uint32_t);
74     case OVS_ACTION_ATTR_USERSPACE: return -2;
75     case OVS_ACTION_ATTR_PUSH_VLAN: return sizeof(struct ovs_action_push_vlan);
76     case OVS_ACTION_ATTR_POP_VLAN: return 0;
77     case OVS_ACTION_ATTR_SET: return -2;
78     case OVS_ACTION_ATTR_SAMPLE: return -2;
79
80     case OVS_ACTION_ATTR_UNSPEC:
81     case __OVS_ACTION_ATTR_MAX:
82         return -1;
83     }
84
85     return -1;
86 }
87
88 static const char *
89 ovs_key_attr_to_string(enum ovs_key_attr attr)
90 {
91     static char unknown_attr[3 + INT_STRLEN(unsigned int) + 1];
92
93     switch (attr) {
94     case OVS_KEY_ATTR_UNSPEC: return "unspec";
95     case OVS_KEY_ATTR_ENCAP: return "encap";
96     case OVS_KEY_ATTR_PRIORITY: return "priority";
97     case OVS_KEY_ATTR_IN_PORT: return "in_port";
98     case OVS_KEY_ATTR_ETHERNET: return "eth";
99     case OVS_KEY_ATTR_VLAN: return "vlan";
100     case OVS_KEY_ATTR_ETHERTYPE: return "eth_type";
101     case OVS_KEY_ATTR_IPV4: return "ipv4";
102     case OVS_KEY_ATTR_IPV6: return "ipv6";
103     case OVS_KEY_ATTR_TCP: return "tcp";
104     case OVS_KEY_ATTR_UDP: return "udp";
105     case OVS_KEY_ATTR_ICMP: return "icmp";
106     case OVS_KEY_ATTR_ICMPV6: return "icmpv6";
107     case OVS_KEY_ATTR_ARP: return "arp";
108     case OVS_KEY_ATTR_ND: return "nd";
109     case OVS_KEY_ATTR_TUN_ID: return "tun_id";
110
111     case __OVS_KEY_ATTR_MAX:
112     default:
113         snprintf(unknown_attr, sizeof unknown_attr, "key%u",
114                  (unsigned int) attr);
115         return unknown_attr;
116     }
117 }
118
119 static void
120 format_generic_odp_action(struct ds *ds, const struct nlattr *a)
121 {
122     size_t len = nl_attr_get_size(a);
123
124     ds_put_format(ds, "action%"PRId16, nl_attr_type(a));
125     if (len) {
126         const uint8_t *unspec;
127         unsigned int i;
128
129         unspec = nl_attr_get(a);
130         for (i = 0; i < len; i++) {
131             ds_put_char(ds, i ? ' ': '(');
132             ds_put_format(ds, "%02x", unspec[i]);
133         }
134         ds_put_char(ds, ')');
135     }
136 }
137
138 static void
139 format_odp_sample_action(struct ds *ds, const struct nlattr *attr)
140 {
141     static const struct nl_policy ovs_sample_policy[] = {
142         [OVS_SAMPLE_ATTR_PROBABILITY] = { .type = NL_A_U32 },
143         [OVS_SAMPLE_ATTR_ACTIONS] = { .type = NL_A_NESTED }
144     };
145     struct nlattr *a[ARRAY_SIZE(ovs_sample_policy)];
146     double percentage;
147     const struct nlattr *nla_acts;
148     int len;
149
150     ds_put_cstr(ds, "sample");
151
152     if (!nl_parse_nested(attr, ovs_sample_policy, a, ARRAY_SIZE(a))) {
153         ds_put_cstr(ds, "(error)");
154         return;
155     }
156
157     percentage = (100.0 * nl_attr_get_u32(a[OVS_SAMPLE_ATTR_PROBABILITY])) /
158                         UINT32_MAX;
159
160     ds_put_format(ds, "(sample=%.1f%%,", percentage);
161
162     ds_put_cstr(ds, "actions(");
163     nla_acts = nl_attr_get(a[OVS_SAMPLE_ATTR_ACTIONS]);
164     len = nl_attr_get_size(a[OVS_SAMPLE_ATTR_ACTIONS]);
165     format_odp_actions(ds, nla_acts, len);
166     ds_put_format(ds, "))");
167 }
168
169 static const char *
170 slow_path_reason_to_string(enum slow_path_reason bit)
171 {
172     switch (bit) {
173     case SLOW_CFM:
174         return "cfm";
175     case SLOW_LACP:
176         return "lacp";
177     case SLOW_STP:
178         return "stp";
179     case SLOW_IN_BAND:
180         return "in_band";
181     case SLOW_CONTROLLER:
182         return "controller";
183     case SLOW_MATCH:
184         return "match";
185     default:
186         return NULL;
187     }
188 }
189
190 static void
191 format_slow_path_reason(struct ds *ds, uint32_t slow)
192 {
193     uint32_t bad = 0;
194
195     while (slow) {
196         uint32_t bit = rightmost_1bit(slow);
197         const char *s;
198
199         s = slow_path_reason_to_string(bit);
200         if (s) {
201             ds_put_format(ds, "%s,", s);
202         } else {
203             bad |= bit;
204         }
205
206         slow &= ~bit;
207     }
208
209     if (bad) {
210         ds_put_format(ds, "0x%"PRIx32",", bad);
211     }
212     ds_chomp(ds, ',');
213 }
214
215 static void
216 format_odp_userspace_action(struct ds *ds, const struct nlattr *attr)
217 {
218     static const struct nl_policy ovs_userspace_policy[] = {
219         [OVS_USERSPACE_ATTR_PID] = { .type = NL_A_U32 },
220         [OVS_USERSPACE_ATTR_USERDATA] = { .type = NL_A_U64, .optional = true },
221     };
222     struct nlattr *a[ARRAY_SIZE(ovs_userspace_policy)];
223
224     if (!nl_parse_nested(attr, ovs_userspace_policy, a, ARRAY_SIZE(a))) {
225         ds_put_cstr(ds, "userspace(error)");
226         return;
227     }
228
229     ds_put_format(ds, "userspace(pid=%"PRIu32,
230                   nl_attr_get_u32(a[OVS_USERSPACE_ATTR_PID]));
231
232     if (a[OVS_USERSPACE_ATTR_USERDATA]) {
233         uint64_t userdata = nl_attr_get_u64(a[OVS_USERSPACE_ATTR_USERDATA]);
234         union user_action_cookie cookie;
235
236         memcpy(&cookie, &userdata, sizeof cookie);
237
238         switch (cookie.type) {
239         case USER_ACTION_COOKIE_SFLOW:
240             ds_put_format(ds, ",sFlow("
241                           "vid=%"PRIu16",pcp=%"PRIu8",output=%"PRIu32")",
242                           vlan_tci_to_vid(cookie.sflow.vlan_tci),
243                           vlan_tci_to_pcp(cookie.sflow.vlan_tci),
244                           cookie.sflow.output);
245             break;
246
247         case USER_ACTION_COOKIE_SLOW_PATH:
248             ds_put_cstr(ds, ",slow_path(");
249             if (cookie.slow_path.reason) {
250                 format_slow_path_reason(ds, cookie.slow_path.reason);
251             }
252             ds_put_char(ds, ')');
253             break;
254
255         case USER_ACTION_COOKIE_UNSPEC:
256         default:
257             ds_put_format(ds, ",userdata=0x%"PRIx64, userdata);
258             break;
259         }
260     }
261
262     ds_put_char(ds, ')');
263 }
264
265 static void
266 format_vlan_tci(struct ds *ds, ovs_be16 vlan_tci)
267 {
268     ds_put_format(ds, "vid=%"PRIu16",pcp=%d",
269                   vlan_tci_to_vid(vlan_tci),
270                   vlan_tci_to_pcp(vlan_tci));
271     if (!(vlan_tci & htons(VLAN_CFI))) {
272         ds_put_cstr(ds, ",cfi=0");
273     }
274 }
275
276 static void
277 format_odp_action(struct ds *ds, const struct nlattr *a)
278 {
279     int expected_len;
280     enum ovs_action_attr type = nl_attr_type(a);
281     const struct ovs_action_push_vlan *vlan;
282
283     expected_len = odp_action_len(nl_attr_type(a));
284     if (expected_len != -2 && nl_attr_get_size(a) != expected_len) {
285         ds_put_format(ds, "bad length %zu, expected %d for: ",
286                       nl_attr_get_size(a), expected_len);
287         format_generic_odp_action(ds, a);
288         return;
289     }
290
291     switch (type) {
292     case OVS_ACTION_ATTR_OUTPUT:
293         ds_put_format(ds, "%"PRIu16, nl_attr_get_u32(a));
294         break;
295     case OVS_ACTION_ATTR_USERSPACE:
296         format_odp_userspace_action(ds, a);
297         break;
298     case OVS_ACTION_ATTR_SET:
299         ds_put_cstr(ds, "set(");
300         format_odp_key_attr(nl_attr_get(a), ds);
301         ds_put_cstr(ds, ")");
302         break;
303     case OVS_ACTION_ATTR_PUSH_VLAN:
304         vlan = nl_attr_get(a);
305         ds_put_cstr(ds, "push_vlan(");
306         if (vlan->vlan_tpid != htons(ETH_TYPE_VLAN)) {
307             ds_put_format(ds, "tpid=0x%04"PRIx16",", ntohs(vlan->vlan_tpid));
308         }
309         format_vlan_tci(ds, vlan->vlan_tci);
310         ds_put_char(ds, ')');
311         break;
312     case OVS_ACTION_ATTR_POP_VLAN:
313         ds_put_cstr(ds, "pop_vlan");
314         break;
315     case OVS_ACTION_ATTR_SAMPLE:
316         format_odp_sample_action(ds, a);
317         break;
318     case OVS_ACTION_ATTR_UNSPEC:
319     case __OVS_ACTION_ATTR_MAX:
320     default:
321         format_generic_odp_action(ds, a);
322         break;
323     }
324 }
325
326 void
327 format_odp_actions(struct ds *ds, const struct nlattr *actions,
328                    size_t actions_len)
329 {
330     if (actions_len) {
331         const struct nlattr *a;
332         unsigned int left;
333
334         NL_ATTR_FOR_EACH (a, left, actions, actions_len) {
335             if (a != actions) {
336                 ds_put_char(ds, ',');
337             }
338             format_odp_action(ds, a);
339         }
340         if (left) {
341             int i;
342
343             if (left == actions_len) {
344                 ds_put_cstr(ds, "<empty>");
345             }
346             ds_put_format(ds, ",***%u leftover bytes*** (", left);
347             for (i = 0; i < left; i++) {
348                 ds_put_format(ds, "%02x", ((const uint8_t *) a)[i]);
349             }
350             ds_put_char(ds, ')');
351         }
352     } else {
353         ds_put_cstr(ds, "drop");
354     }
355 }
356
357 static int
358 parse_odp_action(const char *s, const struct shash *port_names,
359                  struct ofpbuf *actions)
360 {
361     /* Many of the sscanf calls in this function use oversized destination
362      * fields because some sscanf() implementations truncate the range of %i
363      * directives, so that e.g. "%"SCNi16 interprets input of "0xfedc" as a
364      * value of 0x7fff.  The other alternatives are to allow only a single
365      * radix (e.g. decimal or hexadecimal) or to write more sophisticated
366      * parsers.
367      *
368      * The tun_id parser has to use an alternative approach because there is no
369      * type larger than 64 bits. */
370
371     {
372         unsigned long long int port;
373         int n = -1;
374
375         if (sscanf(s, "%lli%n", &port, &n) > 0 && n > 0) {
376             nl_msg_put_u32(actions, OVS_ACTION_ATTR_OUTPUT, port);
377             return n;
378         }
379     }
380
381     if (port_names) {
382         int len = strcspn(s, delimiters);
383         struct shash_node *node;
384
385         node = shash_find_len(port_names, s, len);
386         if (node) {
387             nl_msg_put_u32(actions, OVS_ACTION_ATTR_OUTPUT,
388                            (uintptr_t) node->data);
389             return len;
390         }
391     }
392
393     {
394         unsigned long long int pid;
395         unsigned long long int output;
396         char userdata_s[32];
397         int vid, pcp;
398         int n = -1;
399
400         if (sscanf(s, "userspace(pid=%lli)%n", &pid, &n) > 0 && n > 0) {
401             odp_put_userspace_action(pid, NULL, actions);
402             return n;
403         } else if (sscanf(s, "userspace(pid=%lli,sFlow(vid=%i,"
404                           "pcp=%i,output=%lli))%n",
405                           &pid, &vid, &pcp, &output, &n) > 0 && n > 0) {
406             union user_action_cookie cookie;
407             uint16_t tci;
408
409             tci = vid | (pcp << VLAN_PCP_SHIFT);
410             if (tci) {
411                 tci |= VLAN_CFI;
412             }
413
414             cookie.type = USER_ACTION_COOKIE_SFLOW;
415             cookie.sflow.vlan_tci = htons(tci);
416             cookie.sflow.output = output;
417             odp_put_userspace_action(pid, &cookie, actions);
418             return n;
419         } else if (sscanf(s, "userspace(pid=%lli,slow_path(%n", &pid, &n) > 0
420                    && n > 0) {
421             union user_action_cookie cookie;
422
423             cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
424             cookie.slow_path.unused = 0;
425             cookie.slow_path.reason = 0;
426
427             while (s[n] != ')') {
428                 uint32_t bit;
429
430                 for (bit = 1; bit; bit <<= 1) {
431                     const char *reason = slow_path_reason_to_string(bit);
432                     size_t len = strlen(reason);
433
434                     if (reason
435                         && !strncmp(s + n, reason, len)
436                         && (s[n + len] == ',' || s[n + len] == ')'))
437                     {
438                         cookie.slow_path.reason |= bit;
439                         n += len + (s[n + len] == ',');
440                         break;
441                     }
442                 }
443
444                 if (!bit) {
445                     return -EINVAL;
446                 }
447             }
448             if (s[n + 1] != ')') {
449                 return -EINVAL;
450             }
451             n += 2;
452
453             odp_put_userspace_action(pid, &cookie, actions);
454             return n;
455         } else if (sscanf(s, "userspace(pid=%lli,userdata="
456                           "%31[x0123456789abcdefABCDEF])%n", &pid, userdata_s,
457                           &n) > 0 && n > 0) {
458             union user_action_cookie cookie;
459             uint64_t userdata;
460
461             userdata = strtoull(userdata_s, NULL, 0);
462             memcpy(&cookie, &userdata, sizeof cookie);
463             odp_put_userspace_action(pid, &cookie, actions);
464             return n;
465         }
466     }
467
468     if (!strncmp(s, "set(", 4)) {
469         size_t start_ofs;
470         int retval;
471
472         start_ofs = nl_msg_start_nested(actions, OVS_ACTION_ATTR_SET);
473         retval = parse_odp_key_attr(s + 4, port_names, actions);
474         if (retval < 0) {
475             return retval;
476         }
477         if (s[retval + 4] != ')') {
478             return -EINVAL;
479         }
480         nl_msg_end_nested(actions, start_ofs);
481         return retval + 5;
482     }
483
484     {
485         struct ovs_action_push_vlan push;
486         int tpid = ETH_TYPE_VLAN;
487         int vid, pcp;
488         int cfi = 1;
489         int n = -1;
490
491         if ((sscanf(s, "push_vlan(vid=%i,pcp=%i)%n", &vid, &pcp, &n) > 0
492              && n > 0)
493             || (sscanf(s, "push_vlan(vid=%i,pcp=%i,cfi=%i)%n",
494                        &vid, &pcp, &cfi, &n) > 0 && n > 0)
495             || (sscanf(s, "push_vlan(tpid=%i,vid=%i,pcp=%i)%n",
496                        &tpid, &vid, &pcp, &n) > 0 && n > 0)
497             || (sscanf(s, "push_vlan(tpid=%i,vid=%i,pcp=%i,cfi=%i)%n",
498                        &tpid, &vid, &pcp, &cfi, &n) > 0 && n > 0)) {
499             push.vlan_tpid = htons(tpid);
500             push.vlan_tci = htons((vid << VLAN_VID_SHIFT)
501                                   | (pcp << VLAN_PCP_SHIFT)
502                                   | (cfi ? VLAN_CFI : 0));
503             nl_msg_put_unspec(actions, OVS_ACTION_ATTR_PUSH_VLAN,
504                               &push, sizeof push);
505
506             return n;
507         }
508     }
509
510     if (!strncmp(s, "pop_vlan", 8)) {
511         nl_msg_put_flag(actions, OVS_ACTION_ATTR_POP_VLAN);
512         return 8;
513     }
514
515     {
516         double percentage;
517         int n = -1;
518
519         if (sscanf(s, "sample(sample=%lf%%,actions(%n", &percentage, &n) > 0
520             && percentage >= 0. && percentage <= 100.0
521             && n > 0) {
522             size_t sample_ofs, actions_ofs;
523             double probability;
524
525             probability = floor(UINT32_MAX * (percentage / 100.0) + .5);
526             sample_ofs = nl_msg_start_nested(actions, OVS_ACTION_ATTR_SAMPLE);
527             nl_msg_put_u32(actions, OVS_SAMPLE_ATTR_PROBABILITY,
528                            (probability <= 0 ? 0
529                             : probability >= UINT32_MAX ? UINT32_MAX
530                             : probability));
531
532             actions_ofs = nl_msg_start_nested(actions,
533                                               OVS_SAMPLE_ATTR_ACTIONS);
534             for (;;) {
535                 int retval;
536
537                 n += strspn(s + n, delimiters);
538                 if (s[n] == ')') {
539                     break;
540                 }
541
542                 retval = parse_odp_action(s + n, port_names, actions);
543                 if (retval < 0) {
544                     return retval;
545                 }
546                 n += retval;
547             }
548             nl_msg_end_nested(actions, actions_ofs);
549             nl_msg_end_nested(actions, sample_ofs);
550
551             return s[n + 1] == ')' ? n + 2 : -EINVAL;
552         }
553     }
554
555     return -EINVAL;
556 }
557
558 /* Parses the string representation of datapath actions, in the format output
559  * by format_odp_action().  Returns 0 if successful, otherwise a positive errno
560  * value.  On success, the ODP actions are appended to 'actions' as a series of
561  * Netlink attributes.  On failure, no data is appended to 'actions'.  Either
562  * way, 'actions''s data might be reallocated. */
563 int
564 odp_actions_from_string(const char *s, const struct shash *port_names,
565                         struct ofpbuf *actions)
566 {
567     size_t old_size;
568
569     if (!strcasecmp(s, "drop")) {
570         return 0;
571     }
572
573     old_size = actions->size;
574     for (;;) {
575         int retval;
576
577         s += strspn(s, delimiters);
578         if (!*s) {
579             return 0;
580         }
581
582         retval = parse_odp_action(s, port_names, actions);
583         if (retval < 0 || !strchr(delimiters, s[retval])) {
584             actions->size = old_size;
585             return -retval;
586         }
587         s += retval;
588     }
589
590     return 0;
591 }
592 \f
593 /* Returns the correct length of the payload for a flow key attribute of the
594  * specified 'type', -1 if 'type' is unknown, or -2 if the attribute's payload
595  * is variable length. */
596 static int
597 odp_flow_key_attr_len(uint16_t type)
598 {
599     if (type > OVS_KEY_ATTR_MAX) {
600         return -1;
601     }
602
603     switch ((enum ovs_key_attr) type) {
604     case OVS_KEY_ATTR_ENCAP: return -2;
605     case OVS_KEY_ATTR_PRIORITY: return 4;
606     case OVS_KEY_ATTR_TUN_ID: return 8;
607     case OVS_KEY_ATTR_IN_PORT: return 4;
608     case OVS_KEY_ATTR_ETHERNET: return sizeof(struct ovs_key_ethernet);
609     case OVS_KEY_ATTR_VLAN: return sizeof(ovs_be16);
610     case OVS_KEY_ATTR_ETHERTYPE: return 2;
611     case OVS_KEY_ATTR_IPV4: return sizeof(struct ovs_key_ipv4);
612     case OVS_KEY_ATTR_IPV6: return sizeof(struct ovs_key_ipv6);
613     case OVS_KEY_ATTR_TCP: return sizeof(struct ovs_key_tcp);
614     case OVS_KEY_ATTR_UDP: return sizeof(struct ovs_key_udp);
615     case OVS_KEY_ATTR_ICMP: return sizeof(struct ovs_key_icmp);
616     case OVS_KEY_ATTR_ICMPV6: return sizeof(struct ovs_key_icmpv6);
617     case OVS_KEY_ATTR_ARP: return sizeof(struct ovs_key_arp);
618     case OVS_KEY_ATTR_ND: return sizeof(struct ovs_key_nd);
619
620     case OVS_KEY_ATTR_UNSPEC:
621     case __OVS_KEY_ATTR_MAX:
622         return -1;
623     }
624
625     return -1;
626 }
627
628 static void
629 format_generic_odp_key(const struct nlattr *a, struct ds *ds)
630 {
631     size_t len = nl_attr_get_size(a);
632     if (len) {
633         const uint8_t *unspec;
634         unsigned int i;
635
636         unspec = nl_attr_get(a);
637         for (i = 0; i < len; i++) {
638             ds_put_char(ds, i ? ' ': '(');
639             ds_put_format(ds, "%02x", unspec[i]);
640         }
641         ds_put_char(ds, ')');
642     }
643 }
644
645 static const char *
646 ovs_frag_type_to_string(enum ovs_frag_type type)
647 {
648     switch (type) {
649     case OVS_FRAG_TYPE_NONE:
650         return "no";
651     case OVS_FRAG_TYPE_FIRST:
652         return "first";
653     case OVS_FRAG_TYPE_LATER:
654         return "later";
655     case __OVS_FRAG_TYPE_MAX:
656     default:
657         return "<error>";
658     }
659 }
660
661 static void
662 format_odp_key_attr(const struct nlattr *a, struct ds *ds)
663 {
664     const struct ovs_key_ethernet *eth_key;
665     const struct ovs_key_ipv4 *ipv4_key;
666     const struct ovs_key_ipv6 *ipv6_key;
667     const struct ovs_key_tcp *tcp_key;
668     const struct ovs_key_udp *udp_key;
669     const struct ovs_key_icmp *icmp_key;
670     const struct ovs_key_icmpv6 *icmpv6_key;
671     const struct ovs_key_arp *arp_key;
672     const struct ovs_key_nd *nd_key;
673     enum ovs_key_attr attr = nl_attr_type(a);
674     int expected_len;
675
676     ds_put_cstr(ds, ovs_key_attr_to_string(attr));
677     expected_len = odp_flow_key_attr_len(nl_attr_type(a));
678     if (expected_len != -2 && nl_attr_get_size(a) != expected_len) {
679         ds_put_format(ds, "(bad length %zu, expected %d)",
680                       nl_attr_get_size(a),
681                       odp_flow_key_attr_len(nl_attr_type(a)));
682         format_generic_odp_key(a, ds);
683         return;
684     }
685
686     switch (attr) {
687     case OVS_KEY_ATTR_ENCAP:
688         ds_put_cstr(ds, "(");
689         if (nl_attr_get_size(a)) {
690             odp_flow_key_format(nl_attr_get(a), nl_attr_get_size(a), ds);
691         }
692         ds_put_char(ds, ')');
693         break;
694
695     case OVS_KEY_ATTR_PRIORITY:
696         ds_put_format(ds, "(%"PRIu32")", nl_attr_get_u32(a));
697         break;
698
699     case OVS_KEY_ATTR_TUN_ID:
700         ds_put_format(ds, "(%#"PRIx64")", ntohll(nl_attr_get_be64(a)));
701         break;
702
703     case OVS_KEY_ATTR_IN_PORT:
704         ds_put_format(ds, "(%"PRIu32")", nl_attr_get_u32(a));
705         break;
706
707     case OVS_KEY_ATTR_ETHERNET:
708         eth_key = nl_attr_get(a);
709         ds_put_format(ds, "(src="ETH_ADDR_FMT",dst="ETH_ADDR_FMT")",
710                       ETH_ADDR_ARGS(eth_key->eth_src),
711                       ETH_ADDR_ARGS(eth_key->eth_dst));
712         break;
713
714     case OVS_KEY_ATTR_VLAN:
715         ds_put_char(ds, '(');
716         format_vlan_tci(ds, nl_attr_get_be16(a));
717         ds_put_char(ds, ')');
718         break;
719
720     case OVS_KEY_ATTR_ETHERTYPE:
721         ds_put_format(ds, "(0x%04"PRIx16")",
722                       ntohs(nl_attr_get_be16(a)));
723         break;
724
725     case OVS_KEY_ATTR_IPV4:
726         ipv4_key = nl_attr_get(a);
727         ds_put_format(ds, "(src="IP_FMT",dst="IP_FMT",proto=%"PRIu8
728                       ",tos=%#"PRIx8",ttl=%"PRIu8",frag=%s)",
729                       IP_ARGS(&ipv4_key->ipv4_src),
730                       IP_ARGS(&ipv4_key->ipv4_dst),
731                       ipv4_key->ipv4_proto, ipv4_key->ipv4_tos,
732                       ipv4_key->ipv4_ttl,
733                       ovs_frag_type_to_string(ipv4_key->ipv4_frag));
734         break;
735
736     case OVS_KEY_ATTR_IPV6: {
737         char src_str[INET6_ADDRSTRLEN];
738         char dst_str[INET6_ADDRSTRLEN];
739
740         ipv6_key = nl_attr_get(a);
741         inet_ntop(AF_INET6, ipv6_key->ipv6_src, src_str, sizeof src_str);
742         inet_ntop(AF_INET6, ipv6_key->ipv6_dst, dst_str, sizeof dst_str);
743
744         ds_put_format(ds, "(src=%s,dst=%s,label=%#"PRIx32",proto=%"PRIu8
745                       ",tclass=%#"PRIx8",hlimit=%"PRIu8",frag=%s)",
746                       src_str, dst_str, ntohl(ipv6_key->ipv6_label),
747                       ipv6_key->ipv6_proto, ipv6_key->ipv6_tclass,
748                       ipv6_key->ipv6_hlimit,
749                       ovs_frag_type_to_string(ipv6_key->ipv6_frag));
750         break;
751     }
752
753     case OVS_KEY_ATTR_TCP:
754         tcp_key = nl_attr_get(a);
755         ds_put_format(ds, "(src=%"PRIu16",dst=%"PRIu16")",
756                       ntohs(tcp_key->tcp_src), ntohs(tcp_key->tcp_dst));
757         break;
758
759     case OVS_KEY_ATTR_UDP:
760         udp_key = nl_attr_get(a);
761         ds_put_format(ds, "(src=%"PRIu16",dst=%"PRIu16")",
762                       ntohs(udp_key->udp_src), ntohs(udp_key->udp_dst));
763         break;
764
765     case OVS_KEY_ATTR_ICMP:
766         icmp_key = nl_attr_get(a);
767         ds_put_format(ds, "(type=%"PRIu8",code=%"PRIu8")",
768                       icmp_key->icmp_type, icmp_key->icmp_code);
769         break;
770
771     case OVS_KEY_ATTR_ICMPV6:
772         icmpv6_key = nl_attr_get(a);
773         ds_put_format(ds, "(type=%"PRIu8",code=%"PRIu8")",
774                       icmpv6_key->icmpv6_type, icmpv6_key->icmpv6_code);
775         break;
776
777     case OVS_KEY_ATTR_ARP:
778         arp_key = nl_attr_get(a);
779         ds_put_format(ds, "(sip="IP_FMT",tip="IP_FMT",op=%"PRIu16","
780                       "sha="ETH_ADDR_FMT",tha="ETH_ADDR_FMT")",
781                       IP_ARGS(&arp_key->arp_sip), IP_ARGS(&arp_key->arp_tip),
782                       ntohs(arp_key->arp_op), ETH_ADDR_ARGS(arp_key->arp_sha),
783                       ETH_ADDR_ARGS(arp_key->arp_tha));
784         break;
785
786     case OVS_KEY_ATTR_ND: {
787         char target[INET6_ADDRSTRLEN];
788
789         nd_key = nl_attr_get(a);
790         inet_ntop(AF_INET6, nd_key->nd_target, target, sizeof target);
791
792         ds_put_format(ds, "(target=%s", target);
793         if (!eth_addr_is_zero(nd_key->nd_sll)) {
794             ds_put_format(ds, ",sll="ETH_ADDR_FMT,
795                           ETH_ADDR_ARGS(nd_key->nd_sll));
796         }
797         if (!eth_addr_is_zero(nd_key->nd_tll)) {
798             ds_put_format(ds, ",tll="ETH_ADDR_FMT,
799                           ETH_ADDR_ARGS(nd_key->nd_tll));
800         }
801         ds_put_char(ds, ')');
802         break;
803     }
804
805     case OVS_KEY_ATTR_UNSPEC:
806     case __OVS_KEY_ATTR_MAX:
807     default:
808         format_generic_odp_key(a, ds);
809         break;
810     }
811 }
812
813 /* Appends to 'ds' a string representation of the 'key_len' bytes of
814  * OVS_KEY_ATTR_* attributes in 'key'. */
815 void
816 odp_flow_key_format(const struct nlattr *key, size_t key_len, struct ds *ds)
817 {
818     if (key_len) {
819         const struct nlattr *a;
820         unsigned int left;
821
822         NL_ATTR_FOR_EACH (a, left, key, key_len) {
823             if (a != key) {
824                 ds_put_char(ds, ',');
825             }
826             format_odp_key_attr(a, ds);
827         }
828         if (left) {
829             int i;
830             
831             if (left == key_len) {
832                 ds_put_cstr(ds, "<empty>");
833             }
834             ds_put_format(ds, ",***%u leftover bytes*** (", left);
835             for (i = 0; i < left; i++) {
836                 ds_put_format(ds, "%02x", ((const uint8_t *) a)[i]);
837             }
838             ds_put_char(ds, ')');
839         }
840     } else {
841         ds_put_cstr(ds, "<empty>");
842     }
843 }
844
845 static int
846 put_nd_key(int n, const char *nd_target_s,
847            const uint8_t *nd_sll, const uint8_t *nd_tll, struct ofpbuf *key)
848 {
849     struct ovs_key_nd nd_key;
850
851     memset(&nd_key, 0, sizeof nd_key);
852     if (inet_pton(AF_INET6, nd_target_s, nd_key.nd_target) != 1) {
853         return -EINVAL;
854     }
855     if (nd_sll) {
856         memcpy(nd_key.nd_sll, nd_sll, ETH_ADDR_LEN);
857     }
858     if (nd_tll) {
859         memcpy(nd_key.nd_tll, nd_tll, ETH_ADDR_LEN);
860     }
861     nl_msg_put_unspec(key, OVS_KEY_ATTR_ND, &nd_key, sizeof nd_key);
862     return n;
863 }
864
865 static bool
866 ovs_frag_type_from_string(const char *s, enum ovs_frag_type *type)
867 {
868     if (!strcasecmp(s, "no")) {
869         *type = OVS_FRAG_TYPE_NONE;
870     } else if (!strcasecmp(s, "first")) {
871         *type = OVS_FRAG_TYPE_FIRST;
872     } else if (!strcasecmp(s, "later")) {
873         *type = OVS_FRAG_TYPE_LATER;
874     } else {
875         return false;
876     }
877     return true;
878 }
879
880 static int
881 parse_odp_key_attr(const char *s, const struct shash *port_names,
882                    struct ofpbuf *key)
883 {
884     /* Many of the sscanf calls in this function use oversized destination
885      * fields because some sscanf() implementations truncate the range of %i
886      * directives, so that e.g. "%"SCNi16 interprets input of "0xfedc" as a
887      * value of 0x7fff.  The other alternatives are to allow only a single
888      * radix (e.g. decimal or hexadecimal) or to write more sophisticated
889      * parsers.
890      *
891      * The tun_id parser has to use an alternative approach because there is no
892      * type larger than 64 bits. */
893
894     {
895         unsigned long long int priority;
896         int n = -1;
897
898         if (sscanf(s, "priority(%lli)%n", &priority, &n) > 0 && n > 0) {
899             nl_msg_put_u32(key, OVS_KEY_ATTR_PRIORITY, priority);
900             return n;
901         }
902     }
903
904     {
905         char tun_id_s[32];
906         int n = -1;
907
908         if (sscanf(s, "tun_id(%31[x0123456789abcdefABCDEF])%n",
909                    tun_id_s, &n) > 0 && n > 0) {
910             uint64_t tun_id = strtoull(tun_id_s, NULL, 0);
911             nl_msg_put_be64(key, OVS_KEY_ATTR_TUN_ID, htonll(tun_id));
912             return n;
913         }
914     }
915
916     {
917         unsigned long long int in_port;
918         int n = -1;
919
920         if (sscanf(s, "in_port(%lli)%n", &in_port, &n) > 0 && n > 0) {
921             nl_msg_put_u32(key, OVS_KEY_ATTR_IN_PORT, in_port);
922             return n;
923         }
924     }
925
926     if (port_names && !strncmp(s, "in_port(", 8)) {
927         const char *name;
928         const struct shash_node *node;
929         int name_len;
930
931         name = s + 8;
932         name_len = strcspn(s, ")");
933         node = shash_find_len(port_names, name, name_len);
934         if (node) {
935             nl_msg_put_u32(key, OVS_KEY_ATTR_IN_PORT, (uintptr_t) node->data);
936             return 8 + name_len + 1;
937         }
938     }
939
940     {
941         struct ovs_key_ethernet eth_key;
942         int n = -1;
943
944         if (sscanf(s,
945                    "eth(src="ETH_ADDR_SCAN_FMT",dst="ETH_ADDR_SCAN_FMT")%n",
946                    ETH_ADDR_SCAN_ARGS(eth_key.eth_src),
947                    ETH_ADDR_SCAN_ARGS(eth_key.eth_dst), &n) > 0 && n > 0) {
948             nl_msg_put_unspec(key, OVS_KEY_ATTR_ETHERNET,
949                               &eth_key, sizeof eth_key);
950             return n;
951         }
952     }
953
954     {
955         uint16_t vid;
956         int pcp;
957         int cfi;
958         int n = -1;
959
960         if ((sscanf(s, "vlan(vid=%"SCNi16",pcp=%i)%n", &vid, &pcp, &n) > 0
961              && n > 0)) {
962             nl_msg_put_be16(key, OVS_KEY_ATTR_VLAN,
963                             htons((vid << VLAN_VID_SHIFT) |
964                                   (pcp << VLAN_PCP_SHIFT) |
965                                   VLAN_CFI));
966             return n;
967         } else if ((sscanf(s, "vlan(vid=%"SCNi16",pcp=%i,cfi=%i)%n",
968                            &vid, &pcp, &cfi, &n) > 0
969              && n > 0)) {
970             nl_msg_put_be16(key, OVS_KEY_ATTR_VLAN,
971                             htons((vid << VLAN_VID_SHIFT) |
972                                   (pcp << VLAN_PCP_SHIFT) |
973                                   (cfi ? VLAN_CFI : 0)));
974             return n;
975         }
976     }
977
978     {
979         int eth_type;
980         int n = -1;
981
982         if (sscanf(s, "eth_type(%i)%n", &eth_type, &n) > 0 && n > 0) {
983             nl_msg_put_be16(key, OVS_KEY_ATTR_ETHERTYPE, htons(eth_type));
984             return n;
985         }
986     }
987
988     {
989         ovs_be32 ipv4_src;
990         ovs_be32 ipv4_dst;
991         int ipv4_proto;
992         int ipv4_tos;
993         int ipv4_ttl;
994         char frag[8];
995         enum ovs_frag_type ipv4_frag;
996         int n = -1;
997
998         if (sscanf(s, "ipv4(src="IP_SCAN_FMT",dst="IP_SCAN_FMT","
999                    "proto=%i,tos=%i,ttl=%i,frag=%7[a-z])%n",
1000                    IP_SCAN_ARGS(&ipv4_src), IP_SCAN_ARGS(&ipv4_dst),
1001                    &ipv4_proto, &ipv4_tos, &ipv4_ttl, frag, &n) > 0
1002             && n > 0
1003             && ovs_frag_type_from_string(frag, &ipv4_frag)) {
1004             struct ovs_key_ipv4 ipv4_key;
1005
1006             ipv4_key.ipv4_src = ipv4_src;
1007             ipv4_key.ipv4_dst = ipv4_dst;
1008             ipv4_key.ipv4_proto = ipv4_proto;
1009             ipv4_key.ipv4_tos = ipv4_tos;
1010             ipv4_key.ipv4_ttl = ipv4_ttl;
1011             ipv4_key.ipv4_frag = ipv4_frag;
1012             nl_msg_put_unspec(key, OVS_KEY_ATTR_IPV4,
1013                               &ipv4_key, sizeof ipv4_key);
1014             return n;
1015         }
1016     }
1017
1018     {
1019         char ipv6_src_s[IPV6_SCAN_LEN + 1];
1020         char ipv6_dst_s[IPV6_SCAN_LEN + 1];
1021         int ipv6_label;
1022         int ipv6_proto;
1023         int ipv6_tclass;
1024         int ipv6_hlimit;
1025         char frag[8];
1026         enum ovs_frag_type ipv6_frag;
1027         int n = -1;
1028
1029         if (sscanf(s, "ipv6(src="IPV6_SCAN_FMT",dst="IPV6_SCAN_FMT","
1030                    "label=%i,proto=%i,tclass=%i,hlimit=%i,frag=%7[a-z])%n",
1031                    ipv6_src_s, ipv6_dst_s, &ipv6_label,
1032                    &ipv6_proto, &ipv6_tclass, &ipv6_hlimit, frag, &n) > 0
1033             && n > 0
1034             && ovs_frag_type_from_string(frag, &ipv6_frag)) {
1035             struct ovs_key_ipv6 ipv6_key;
1036
1037             if (inet_pton(AF_INET6, ipv6_src_s, &ipv6_key.ipv6_src) != 1 ||
1038                 inet_pton(AF_INET6, ipv6_dst_s, &ipv6_key.ipv6_dst) != 1) {
1039                 return -EINVAL;
1040             }
1041             ipv6_key.ipv6_label = htonl(ipv6_label);
1042             ipv6_key.ipv6_proto = ipv6_proto;
1043             ipv6_key.ipv6_tclass = ipv6_tclass;
1044             ipv6_key.ipv6_hlimit = ipv6_hlimit;
1045             ipv6_key.ipv6_frag = ipv6_frag;
1046             nl_msg_put_unspec(key, OVS_KEY_ATTR_IPV6,
1047                               &ipv6_key, sizeof ipv6_key);
1048             return n;
1049         }
1050     }
1051
1052     {
1053         int tcp_src;
1054         int tcp_dst;
1055         int n = -1;
1056
1057         if (sscanf(s, "tcp(src=%i,dst=%i)%n",&tcp_src, &tcp_dst, &n) > 0
1058             && n > 0) {
1059             struct ovs_key_tcp tcp_key;
1060
1061             tcp_key.tcp_src = htons(tcp_src);
1062             tcp_key.tcp_dst = htons(tcp_dst);
1063             nl_msg_put_unspec(key, OVS_KEY_ATTR_TCP, &tcp_key, sizeof tcp_key);
1064             return n;
1065         }
1066     }
1067
1068     {
1069         int udp_src;
1070         int udp_dst;
1071         int n = -1;
1072
1073         if (sscanf(s, "udp(src=%i,dst=%i)%n", &udp_src, &udp_dst, &n) > 0
1074             && n > 0) {
1075             struct ovs_key_udp udp_key;
1076
1077             udp_key.udp_src = htons(udp_src);
1078             udp_key.udp_dst = htons(udp_dst);
1079             nl_msg_put_unspec(key, OVS_KEY_ATTR_UDP, &udp_key, sizeof udp_key);
1080             return n;
1081         }
1082     }
1083
1084     {
1085         int icmp_type;
1086         int icmp_code;
1087         int n = -1;
1088
1089         if (sscanf(s, "icmp(type=%i,code=%i)%n",
1090                    &icmp_type, &icmp_code, &n) > 0
1091             && n > 0) {
1092             struct ovs_key_icmp icmp_key;
1093
1094             icmp_key.icmp_type = icmp_type;
1095             icmp_key.icmp_code = icmp_code;
1096             nl_msg_put_unspec(key, OVS_KEY_ATTR_ICMP,
1097                               &icmp_key, sizeof icmp_key);
1098             return n;
1099         }
1100     }
1101
1102     {
1103         struct ovs_key_icmpv6 icmpv6_key;
1104         int n = -1;
1105
1106         if (sscanf(s, "icmpv6(type=%"SCNi8",code=%"SCNi8")%n",
1107                    &icmpv6_key.icmpv6_type, &icmpv6_key.icmpv6_code,&n) > 0
1108             && n > 0) {
1109             nl_msg_put_unspec(key, OVS_KEY_ATTR_ICMPV6,
1110                               &icmpv6_key, sizeof icmpv6_key);
1111             return n;
1112         }
1113     }
1114
1115     {
1116         ovs_be32 arp_sip;
1117         ovs_be32 arp_tip;
1118         int arp_op;
1119         uint8_t arp_sha[ETH_ADDR_LEN];
1120         uint8_t arp_tha[ETH_ADDR_LEN];
1121         int n = -1;
1122
1123         if (sscanf(s, "arp(sip="IP_SCAN_FMT",tip="IP_SCAN_FMT","
1124                    "op=%i,sha="ETH_ADDR_SCAN_FMT",tha="ETH_ADDR_SCAN_FMT")%n",
1125                    IP_SCAN_ARGS(&arp_sip),
1126                    IP_SCAN_ARGS(&arp_tip),
1127                    &arp_op,
1128                    ETH_ADDR_SCAN_ARGS(arp_sha),
1129                    ETH_ADDR_SCAN_ARGS(arp_tha), &n) > 0 && n > 0) {
1130             struct ovs_key_arp arp_key;
1131
1132             memset(&arp_key, 0, sizeof arp_key);
1133             arp_key.arp_sip = arp_sip;
1134             arp_key.arp_tip = arp_tip;
1135             arp_key.arp_op = htons(arp_op);
1136             memcpy(arp_key.arp_sha, arp_sha, ETH_ADDR_LEN);
1137             memcpy(arp_key.arp_tha, arp_tha, ETH_ADDR_LEN);
1138             nl_msg_put_unspec(key, OVS_KEY_ATTR_ARP, &arp_key, sizeof arp_key);
1139             return n;
1140         }
1141     }
1142
1143     {
1144         char nd_target_s[IPV6_SCAN_LEN + 1];
1145         uint8_t nd_sll[ETH_ADDR_LEN];
1146         uint8_t nd_tll[ETH_ADDR_LEN];
1147         int n = -1;
1148
1149         if (sscanf(s, "nd(target="IPV6_SCAN_FMT")%n",
1150                    nd_target_s, &n) > 0 && n > 0) {
1151             return put_nd_key(n, nd_target_s, NULL, NULL, key);
1152         }
1153         if (sscanf(s, "nd(target="IPV6_SCAN_FMT",sll="ETH_ADDR_SCAN_FMT")%n",
1154                    nd_target_s, ETH_ADDR_SCAN_ARGS(nd_sll), &n) > 0
1155             && n > 0) {
1156             return put_nd_key(n, nd_target_s, nd_sll, NULL, key);
1157         }
1158         if (sscanf(s, "nd(target="IPV6_SCAN_FMT",tll="ETH_ADDR_SCAN_FMT")%n",
1159                    nd_target_s, ETH_ADDR_SCAN_ARGS(nd_tll), &n) > 0
1160             && n > 0) {
1161             return put_nd_key(n, nd_target_s, NULL, nd_tll, key);
1162         }
1163         if (sscanf(s, "nd(target="IPV6_SCAN_FMT",sll="ETH_ADDR_SCAN_FMT","
1164                    "tll="ETH_ADDR_SCAN_FMT")%n",
1165                    nd_target_s, ETH_ADDR_SCAN_ARGS(nd_sll),
1166                    ETH_ADDR_SCAN_ARGS(nd_tll), &n) > 0
1167             && n > 0) {
1168             return put_nd_key(n, nd_target_s, nd_sll, nd_tll, key);
1169         }
1170     }
1171
1172     if (!strncmp(s, "encap(", 6)) {
1173         const char *start = s;
1174         size_t encap;
1175
1176         encap = nl_msg_start_nested(key, OVS_KEY_ATTR_ENCAP);
1177
1178         s += 6;
1179         for (;;) {
1180             int retval;
1181
1182             s += strspn(s, ", \t\r\n");
1183             if (!*s) {
1184                 return -EINVAL;
1185             } else if (*s == ')') {
1186                 break;
1187             }
1188
1189             retval = parse_odp_key_attr(s, port_names, key);
1190             if (retval < 0) {
1191                 return retval;
1192             }
1193             s += retval;
1194         }
1195         s++;
1196
1197         nl_msg_end_nested(key, encap);
1198
1199         return s - start;
1200     }
1201
1202     return -EINVAL;
1203 }
1204
1205 /* Parses the string representation of a datapath flow key, in the
1206  * format output by odp_flow_key_format().  Returns 0 if successful,
1207  * otherwise a positive errno value.  On success, the flow key is
1208  * appended to 'key' as a series of Netlink attributes.  On failure, no
1209  * data is appended to 'key'.  Either way, 'key''s data might be
1210  * reallocated.
1211  *
1212  * If 'port_names' is nonnull, it points to an shash that maps from a port name
1213  * to a port number cast to void *.  (Port names may be used instead of port
1214  * numbers in in_port.)
1215  *
1216  * On success, the attributes appended to 'key' are individually syntactically
1217  * valid, but they may not be valid as a sequence.  'key' might, for example,
1218  * have duplicated keys.  odp_flow_key_to_flow() will detect those errors. */
1219 int
1220 odp_flow_key_from_string(const char *s, const struct shash *port_names,
1221                          struct ofpbuf *key)
1222 {
1223     const size_t old_size = key->size;
1224     for (;;) {
1225         int retval;
1226
1227         s += strspn(s, delimiters);
1228         if (!*s) {
1229             return 0;
1230         }
1231
1232         retval = parse_odp_key_attr(s, port_names, key);
1233         if (retval < 0) {
1234             key->size = old_size;
1235             return -retval;
1236         }
1237         s += retval;
1238     }
1239
1240     return 0;
1241 }
1242
1243 static uint8_t
1244 ovs_to_odp_frag(uint8_t nw_frag)
1245 {
1246     return (nw_frag == 0 ? OVS_FRAG_TYPE_NONE
1247           : nw_frag == FLOW_NW_FRAG_ANY ? OVS_FRAG_TYPE_FIRST
1248           : OVS_FRAG_TYPE_LATER);
1249 }
1250
1251 /* Appends a representation of 'flow' as OVS_KEY_ATTR_* attributes to 'buf'. */
1252 void
1253 odp_flow_key_from_flow(struct ofpbuf *buf, const struct flow *flow)
1254 {
1255     struct ovs_key_ethernet *eth_key;
1256     size_t encap;
1257
1258     if (flow->skb_priority) {
1259         nl_msg_put_u32(buf, OVS_KEY_ATTR_PRIORITY, flow->skb_priority);
1260     }
1261
1262     if (flow->tun_id != htonll(0)) {
1263         nl_msg_put_be64(buf, OVS_KEY_ATTR_TUN_ID, flow->tun_id);
1264     }
1265
1266     if (flow->in_port != OFPP_NONE && flow->in_port != OFPP_CONTROLLER) {
1267         nl_msg_put_u32(buf, OVS_KEY_ATTR_IN_PORT,
1268                        ofp_port_to_odp_port(flow->in_port));
1269     }
1270
1271     eth_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ETHERNET,
1272                                        sizeof *eth_key);
1273     memcpy(eth_key->eth_src, flow->dl_src, ETH_ADDR_LEN);
1274     memcpy(eth_key->eth_dst, flow->dl_dst, ETH_ADDR_LEN);
1275
1276     if (flow->vlan_tci != htons(0) || flow->dl_type == htons(ETH_TYPE_VLAN)) {
1277         nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, htons(ETH_TYPE_VLAN));
1278         nl_msg_put_be16(buf, OVS_KEY_ATTR_VLAN, flow->vlan_tci);
1279         encap = nl_msg_start_nested(buf, OVS_KEY_ATTR_ENCAP);
1280         if (flow->vlan_tci == htons(0)) {
1281             goto unencap;
1282         }
1283     } else {
1284         encap = 0;
1285     }
1286
1287     if (ntohs(flow->dl_type) < ETH_TYPE_MIN) {
1288         goto unencap;
1289     }
1290
1291     nl_msg_put_be16(buf, OVS_KEY_ATTR_ETHERTYPE, flow->dl_type);
1292
1293     if (flow->dl_type == htons(ETH_TYPE_IP)) {
1294         struct ovs_key_ipv4 *ipv4_key;
1295
1296         ipv4_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV4,
1297                                             sizeof *ipv4_key);
1298         ipv4_key->ipv4_src = flow->nw_src;
1299         ipv4_key->ipv4_dst = flow->nw_dst;
1300         ipv4_key->ipv4_proto = flow->nw_proto;
1301         ipv4_key->ipv4_tos = flow->nw_tos;
1302         ipv4_key->ipv4_ttl = flow->nw_ttl;
1303         ipv4_key->ipv4_frag = ovs_to_odp_frag(flow->nw_frag);
1304     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
1305         struct ovs_key_ipv6 *ipv6_key;
1306
1307         ipv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_IPV6,
1308                                             sizeof *ipv6_key);
1309         memcpy(ipv6_key->ipv6_src, &flow->ipv6_src, sizeof ipv6_key->ipv6_src);
1310         memcpy(ipv6_key->ipv6_dst, &flow->ipv6_dst, sizeof ipv6_key->ipv6_dst);
1311         ipv6_key->ipv6_label = flow->ipv6_label;
1312         ipv6_key->ipv6_proto = flow->nw_proto;
1313         ipv6_key->ipv6_tclass = flow->nw_tos;
1314         ipv6_key->ipv6_hlimit = flow->nw_ttl;
1315         ipv6_key->ipv6_frag = ovs_to_odp_frag(flow->nw_frag);
1316     } else if (flow->dl_type == htons(ETH_TYPE_ARP)) {
1317         struct ovs_key_arp *arp_key;
1318
1319         arp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ARP,
1320                                            sizeof *arp_key);
1321         memset(arp_key, 0, sizeof *arp_key);
1322         arp_key->arp_sip = flow->nw_src;
1323         arp_key->arp_tip = flow->nw_dst;
1324         arp_key->arp_op = htons(flow->nw_proto);
1325         memcpy(arp_key->arp_sha, flow->arp_sha, ETH_ADDR_LEN);
1326         memcpy(arp_key->arp_tha, flow->arp_tha, ETH_ADDR_LEN);
1327     }
1328
1329     if ((flow->dl_type == htons(ETH_TYPE_IP)
1330          || flow->dl_type == htons(ETH_TYPE_IPV6))
1331         && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
1332
1333         if (flow->nw_proto == IPPROTO_TCP) {
1334             struct ovs_key_tcp *tcp_key;
1335
1336             tcp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_TCP,
1337                                                sizeof *tcp_key);
1338             tcp_key->tcp_src = flow->tp_src;
1339             tcp_key->tcp_dst = flow->tp_dst;
1340         } else if (flow->nw_proto == IPPROTO_UDP) {
1341             struct ovs_key_udp *udp_key;
1342
1343             udp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_UDP,
1344                                                sizeof *udp_key);
1345             udp_key->udp_src = flow->tp_src;
1346             udp_key->udp_dst = flow->tp_dst;
1347         } else if (flow->dl_type == htons(ETH_TYPE_IP)
1348                 && flow->nw_proto == IPPROTO_ICMP) {
1349             struct ovs_key_icmp *icmp_key;
1350
1351             icmp_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMP,
1352                                                 sizeof *icmp_key);
1353             icmp_key->icmp_type = ntohs(flow->tp_src);
1354             icmp_key->icmp_code = ntohs(flow->tp_dst);
1355         } else if (flow->dl_type == htons(ETH_TYPE_IPV6)
1356                 && flow->nw_proto == IPPROTO_ICMPV6) {
1357             struct ovs_key_icmpv6 *icmpv6_key;
1358
1359             icmpv6_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ICMPV6,
1360                                                   sizeof *icmpv6_key);
1361             icmpv6_key->icmpv6_type = ntohs(flow->tp_src);
1362             icmpv6_key->icmpv6_code = ntohs(flow->tp_dst);
1363
1364             if (icmpv6_key->icmpv6_type == ND_NEIGHBOR_SOLICIT
1365                     || icmpv6_key->icmpv6_type == ND_NEIGHBOR_ADVERT) {
1366                 struct ovs_key_nd *nd_key;
1367
1368                 nd_key = nl_msg_put_unspec_uninit(buf, OVS_KEY_ATTR_ND,
1369                                                     sizeof *nd_key);
1370                 memcpy(nd_key->nd_target, &flow->nd_target,
1371                         sizeof nd_key->nd_target);
1372                 memcpy(nd_key->nd_sll, flow->arp_sha, ETH_ADDR_LEN);
1373                 memcpy(nd_key->nd_tll, flow->arp_tha, ETH_ADDR_LEN);
1374             }
1375         }
1376     }
1377
1378 unencap:
1379     if (encap) {
1380         nl_msg_end_nested(buf, encap);
1381     }
1382 }
1383
1384 uint32_t
1385 odp_flow_key_hash(const struct nlattr *key, size_t key_len)
1386 {
1387     BUILD_ASSERT_DECL(!(NLA_ALIGNTO % sizeof(uint32_t)));
1388     return hash_words((const uint32_t *) key, key_len / sizeof(uint32_t), 0);
1389 }
1390
1391 static void
1392 log_odp_key_attributes(struct vlog_rate_limit *rl, const char *title,
1393                        uint64_t attrs, int out_of_range_attr,
1394                        const struct nlattr *key, size_t key_len)
1395 {
1396     struct ds s;
1397     int i;
1398
1399     if (VLOG_DROP_DBG(rl)) {
1400         return;
1401     }
1402
1403     ds_init(&s);
1404     for (i = 0; i < 64; i++) {
1405         if (attrs & (UINT64_C(1) << i)) {
1406             ds_put_format(&s, " %s", ovs_key_attr_to_string(i));
1407         }
1408     }
1409     if (out_of_range_attr) {
1410         ds_put_format(&s, " %d (and possibly others)", out_of_range_attr);
1411     }
1412
1413     ds_put_cstr(&s, ": ");
1414     odp_flow_key_format(key, key_len, &s);
1415
1416     VLOG_DBG("%s:%s", title, ds_cstr(&s));
1417     ds_destroy(&s);
1418 }
1419
1420 static bool
1421 odp_to_ovs_frag(uint8_t odp_frag, struct flow *flow)
1422 {
1423     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1424
1425     if (odp_frag > OVS_FRAG_TYPE_LATER) {
1426         VLOG_ERR_RL(&rl, "invalid frag %"PRIu8" in flow key", odp_frag);
1427         return false;
1428     }
1429
1430     if (odp_frag != OVS_FRAG_TYPE_NONE) {
1431         flow->nw_frag |= FLOW_NW_FRAG_ANY;
1432         if (odp_frag == OVS_FRAG_TYPE_LATER) {
1433             flow->nw_frag |= FLOW_NW_FRAG_LATER;
1434         }
1435     }
1436     return true;
1437 }
1438
1439 static bool
1440 parse_flow_nlattrs(const struct nlattr *key, size_t key_len,
1441                    const struct nlattr *attrs[], uint64_t *present_attrsp,
1442                    int *out_of_range_attrp)
1443 {
1444     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
1445     const struct nlattr *nla;
1446     uint64_t present_attrs;
1447     size_t left;
1448
1449     present_attrs = 0;
1450     *out_of_range_attrp = 0;
1451     NL_ATTR_FOR_EACH (nla, left, key, key_len) {
1452         uint16_t type = nl_attr_type(nla);
1453         size_t len = nl_attr_get_size(nla);
1454         int expected_len = odp_flow_key_attr_len(type);
1455
1456         if (len != expected_len && expected_len >= 0) {
1457             VLOG_ERR_RL(&rl, "attribute %s has length %zu but should have "
1458                         "length %d", ovs_key_attr_to_string(type),
1459                         len, expected_len);
1460             return false;
1461         }
1462
1463         if (type >= CHAR_BIT * sizeof present_attrs) {
1464             *out_of_range_attrp = type;
1465         } else {
1466             if (present_attrs & (UINT64_C(1) << type)) {
1467                 VLOG_ERR_RL(&rl, "duplicate %s attribute in flow key",
1468                             ovs_key_attr_to_string(type));
1469                 return false;
1470             }
1471
1472             present_attrs |= UINT64_C(1) << type;
1473             attrs[type] = nla;
1474         }
1475     }
1476     if (left) {
1477         VLOG_ERR_RL(&rl, "trailing garbage in flow key");
1478         return false;
1479     }
1480
1481     *present_attrsp = present_attrs;
1482     return true;
1483 }
1484
1485 static enum odp_key_fitness
1486 check_expectations(uint64_t present_attrs, int out_of_range_attr,
1487                    uint64_t expected_attrs,
1488                    const struct nlattr *key, size_t key_len)
1489 {
1490     uint64_t missing_attrs;
1491     uint64_t extra_attrs;
1492
1493     missing_attrs = expected_attrs & ~present_attrs;
1494     if (missing_attrs) {
1495         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
1496         log_odp_key_attributes(&rl, "expected but not present",
1497                                missing_attrs, 0, key, key_len);
1498         return ODP_FIT_TOO_LITTLE;
1499     }
1500
1501     extra_attrs = present_attrs & ~expected_attrs;
1502     if (extra_attrs || out_of_range_attr) {
1503         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
1504         log_odp_key_attributes(&rl, "present but not expected",
1505                                extra_attrs, out_of_range_attr, key, key_len);
1506         return ODP_FIT_TOO_MUCH;
1507     }
1508
1509     return ODP_FIT_PERFECT;
1510 }
1511
1512 static bool
1513 parse_ethertype(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
1514                 uint64_t present_attrs, uint64_t *expected_attrs,
1515                 struct flow *flow)
1516 {
1517     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1518
1519     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE)) {
1520         flow->dl_type = nl_attr_get_be16(attrs[OVS_KEY_ATTR_ETHERTYPE]);
1521         if (ntohs(flow->dl_type) < 1536) {
1522             VLOG_ERR_RL(&rl, "invalid Ethertype %"PRIu16" in flow key",
1523                         ntohs(flow->dl_type));
1524             return false;
1525         }
1526         *expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERTYPE;
1527     } else {
1528         flow->dl_type = htons(FLOW_DL_TYPE_NONE);
1529     }
1530     return true;
1531 }
1532
1533 static enum odp_key_fitness
1534 parse_l3_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
1535                 uint64_t present_attrs, int out_of_range_attr,
1536                 uint64_t expected_attrs, struct flow *flow,
1537                 const struct nlattr *key, size_t key_len)
1538 {
1539     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1540
1541     if (flow->dl_type == htons(ETH_TYPE_IP)) {
1542         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV4;
1543         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV4)) {
1544             const struct ovs_key_ipv4 *ipv4_key;
1545
1546             ipv4_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV4]);
1547             flow->nw_src = ipv4_key->ipv4_src;
1548             flow->nw_dst = ipv4_key->ipv4_dst;
1549             flow->nw_proto = ipv4_key->ipv4_proto;
1550             flow->nw_tos = ipv4_key->ipv4_tos;
1551             flow->nw_ttl = ipv4_key->ipv4_ttl;
1552             if (!odp_to_ovs_frag(ipv4_key->ipv4_frag, flow)) {
1553                 return ODP_FIT_ERROR;
1554             }
1555         }
1556     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
1557         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IPV6;
1558         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IPV6)) {
1559             const struct ovs_key_ipv6 *ipv6_key;
1560
1561             ipv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_IPV6]);
1562             memcpy(&flow->ipv6_src, ipv6_key->ipv6_src, sizeof flow->ipv6_src);
1563             memcpy(&flow->ipv6_dst, ipv6_key->ipv6_dst, sizeof flow->ipv6_dst);
1564             flow->ipv6_label = ipv6_key->ipv6_label;
1565             flow->nw_proto = ipv6_key->ipv6_proto;
1566             flow->nw_tos = ipv6_key->ipv6_tclass;
1567             flow->nw_ttl = ipv6_key->ipv6_hlimit;
1568             if (!odp_to_ovs_frag(ipv6_key->ipv6_frag, flow)) {
1569                 return ODP_FIT_ERROR;
1570             }
1571         }
1572     } else if (flow->dl_type == htons(ETH_TYPE_ARP)) {
1573         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ARP;
1574         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ARP)) {
1575             const struct ovs_key_arp *arp_key;
1576
1577             arp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ARP]);
1578             flow->nw_src = arp_key->arp_sip;
1579             flow->nw_dst = arp_key->arp_tip;
1580             if (arp_key->arp_op & htons(0xff00)) {
1581                 VLOG_ERR_RL(&rl, "unsupported ARP opcode %"PRIu16" in flow "
1582                             "key", ntohs(arp_key->arp_op));
1583                 return ODP_FIT_ERROR;
1584             }
1585             flow->nw_proto = ntohs(arp_key->arp_op);
1586             memcpy(flow->arp_sha, arp_key->arp_sha, ETH_ADDR_LEN);
1587             memcpy(flow->arp_tha, arp_key->arp_tha, ETH_ADDR_LEN);
1588         }
1589     }
1590
1591     if (flow->nw_proto == IPPROTO_TCP
1592         && (flow->dl_type == htons(ETH_TYPE_IP) ||
1593             flow->dl_type == htons(ETH_TYPE_IPV6))
1594         && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
1595         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TCP;
1596         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TCP)) {
1597             const struct ovs_key_tcp *tcp_key;
1598
1599             tcp_key = nl_attr_get(attrs[OVS_KEY_ATTR_TCP]);
1600             flow->tp_src = tcp_key->tcp_src;
1601             flow->tp_dst = tcp_key->tcp_dst;
1602         }
1603     } else if (flow->nw_proto == IPPROTO_UDP
1604                && (flow->dl_type == htons(ETH_TYPE_IP) ||
1605                    flow->dl_type == htons(ETH_TYPE_IPV6))
1606                && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
1607         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_UDP;
1608         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_UDP)) {
1609             const struct ovs_key_udp *udp_key;
1610
1611             udp_key = nl_attr_get(attrs[OVS_KEY_ATTR_UDP]);
1612             flow->tp_src = udp_key->udp_src;
1613             flow->tp_dst = udp_key->udp_dst;
1614         }
1615     } else if (flow->nw_proto == IPPROTO_ICMP
1616                && flow->dl_type == htons(ETH_TYPE_IP)
1617                && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
1618         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMP;
1619         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMP)) {
1620             const struct ovs_key_icmp *icmp_key;
1621
1622             icmp_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMP]);
1623             flow->tp_src = htons(icmp_key->icmp_type);
1624             flow->tp_dst = htons(icmp_key->icmp_code);
1625         }
1626     } else if (flow->nw_proto == IPPROTO_ICMPV6
1627                && flow->dl_type == htons(ETH_TYPE_IPV6)
1628                && !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
1629         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ICMPV6;
1630         if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ICMPV6)) {
1631             const struct ovs_key_icmpv6 *icmpv6_key;
1632
1633             icmpv6_key = nl_attr_get(attrs[OVS_KEY_ATTR_ICMPV6]);
1634             flow->tp_src = htons(icmpv6_key->icmpv6_type);
1635             flow->tp_dst = htons(icmpv6_key->icmpv6_code);
1636
1637             if (flow->tp_src == htons(ND_NEIGHBOR_SOLICIT) ||
1638                 flow->tp_src == htons(ND_NEIGHBOR_ADVERT)) {
1639                 expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ND;
1640                 if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ND)) {
1641                     const struct ovs_key_nd *nd_key;
1642
1643                     nd_key = nl_attr_get(attrs[OVS_KEY_ATTR_ND]);
1644                     memcpy(&flow->nd_target, nd_key->nd_target,
1645                            sizeof flow->nd_target);
1646                     memcpy(flow->arp_sha, nd_key->nd_sll, ETH_ADDR_LEN);
1647                     memcpy(flow->arp_tha, nd_key->nd_tll, ETH_ADDR_LEN);
1648                 }
1649             }
1650         }
1651     }
1652
1653     return check_expectations(present_attrs, out_of_range_attr, expected_attrs,
1654                               key, key_len);
1655 }
1656
1657 /* Parse 802.1Q header then encapsulated L3 attributes. */
1658 static enum odp_key_fitness
1659 parse_8021q_onward(const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1],
1660                    uint64_t present_attrs, int out_of_range_attr,
1661                    uint64_t expected_attrs, struct flow *flow,
1662                    const struct nlattr *key, size_t key_len)
1663 {
1664     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1665
1666     const struct nlattr *encap
1667         = (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ENCAP)
1668            ? attrs[OVS_KEY_ATTR_ENCAP] : NULL);
1669     enum odp_key_fitness encap_fitness;
1670     enum odp_key_fitness fitness;
1671     ovs_be16 tci;
1672
1673     /* Calulate fitness of outer attributes. */
1674     expected_attrs |= ((UINT64_C(1) << OVS_KEY_ATTR_VLAN) |
1675                        (UINT64_C(1) << OVS_KEY_ATTR_ENCAP));
1676     fitness = check_expectations(present_attrs, out_of_range_attr,
1677                                  expected_attrs, key, key_len);
1678
1679     /* Get the VLAN TCI value. */
1680     if (!(present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_VLAN))) {
1681         return ODP_FIT_TOO_LITTLE;
1682     }
1683     tci = nl_attr_get_be16(attrs[OVS_KEY_ATTR_VLAN]);
1684     if (tci == htons(0)) {
1685         /* Corner case for a truncated 802.1Q header. */
1686         if (fitness == ODP_FIT_PERFECT && nl_attr_get_size(encap)) {
1687             return ODP_FIT_TOO_MUCH;
1688         }
1689         return fitness;
1690     } else if (!(tci & htons(VLAN_CFI))) {
1691         VLOG_ERR_RL(&rl, "OVS_KEY_ATTR_VLAN 0x%04"PRIx16" is nonzero "
1692                     "but CFI bit is not set", ntohs(tci));
1693         return ODP_FIT_ERROR;
1694     }
1695
1696     /* Set vlan_tci.
1697      * Remove the TPID from dl_type since it's not the real Ethertype.  */
1698     flow->vlan_tci = tci;
1699     flow->dl_type = htons(0);
1700
1701     /* Now parse the encapsulated attributes. */
1702     if (!parse_flow_nlattrs(nl_attr_get(encap), nl_attr_get_size(encap),
1703                             attrs, &present_attrs, &out_of_range_attr)) {
1704         return ODP_FIT_ERROR;
1705     }
1706     expected_attrs = 0;
1707
1708     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow)) {
1709         return ODP_FIT_ERROR;
1710     }
1711     encap_fitness = parse_l3_onward(attrs, present_attrs, out_of_range_attr,
1712                                     expected_attrs, flow, key, key_len);
1713
1714     /* The overall fitness is the worse of the outer and inner attributes. */
1715     return MAX(fitness, encap_fitness);
1716 }
1717
1718 /* Converts the 'key_len' bytes of OVS_KEY_ATTR_* attributes in 'key' to a flow
1719  * structure in 'flow'.  Returns an ODP_FIT_* value that indicates how well
1720  * 'key' fits our expectations for what a flow key should contain.
1721  *
1722  * This function doesn't take the packet itself as an argument because none of
1723  * the currently understood OVS_KEY_ATTR_* attributes require it.  Currently,
1724  * it is always possible to infer which additional attribute(s) should appear
1725  * by looking at the attributes for lower-level protocols, e.g. if the network
1726  * protocol in OVS_KEY_ATTR_IPV4 or OVS_KEY_ATTR_IPV6 is IPPROTO_TCP then we
1727  * know that a OVS_KEY_ATTR_TCP attribute must appear and that otherwise it
1728  * must be absent. */
1729 enum odp_key_fitness
1730 odp_flow_key_to_flow(const struct nlattr *key, size_t key_len,
1731                      struct flow *flow)
1732 {
1733     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1734     const struct nlattr *attrs[OVS_KEY_ATTR_MAX + 1];
1735     uint64_t expected_attrs;
1736     uint64_t present_attrs;
1737     int out_of_range_attr;
1738
1739     memset(flow, 0, sizeof *flow);
1740
1741     /* Parse attributes. */
1742     if (!parse_flow_nlattrs(key, key_len, attrs, &present_attrs,
1743                             &out_of_range_attr)) {
1744         return ODP_FIT_ERROR;
1745     }
1746     expected_attrs = 0;
1747
1748     /* Metadata. */
1749     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_PRIORITY)) {
1750         flow->skb_priority = nl_attr_get_u32(attrs[OVS_KEY_ATTR_PRIORITY]);
1751         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_PRIORITY;
1752     }
1753
1754     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_TUN_ID)) {
1755         flow->tun_id = nl_attr_get_be64(attrs[OVS_KEY_ATTR_TUN_ID]);
1756         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_TUN_ID;
1757     }
1758
1759     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_IN_PORT)) {
1760         uint32_t in_port = nl_attr_get_u32(attrs[OVS_KEY_ATTR_IN_PORT]);
1761         if (in_port >= UINT16_MAX || in_port >= OFPP_MAX) {
1762             VLOG_ERR_RL(&rl, "in_port %"PRIu32" out of supported range",
1763                         in_port);
1764             return ODP_FIT_ERROR;
1765         }
1766         flow->in_port = odp_port_to_ofp_port(in_port);
1767         expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_IN_PORT;
1768     } else {
1769         flow->in_port = OFPP_NONE;
1770     }
1771
1772     /* Ethernet header. */
1773     if (present_attrs & (UINT64_C(1) << OVS_KEY_ATTR_ETHERNET)) {
1774         const struct ovs_key_ethernet *eth_key;
1775
1776         eth_key = nl_attr_get(attrs[OVS_KEY_ATTR_ETHERNET]);
1777         memcpy(flow->dl_src, eth_key->eth_src, ETH_ADDR_LEN);
1778         memcpy(flow->dl_dst, eth_key->eth_dst, ETH_ADDR_LEN);
1779     }
1780     expected_attrs |= UINT64_C(1) << OVS_KEY_ATTR_ETHERNET;
1781
1782     /* Get Ethertype or 802.1Q TPID or FLOW_DL_TYPE_NONE. */
1783     if (!parse_ethertype(attrs, present_attrs, &expected_attrs, flow)) {
1784         return ODP_FIT_ERROR;
1785     }
1786
1787     if (flow->dl_type == htons(ETH_TYPE_VLAN)) {
1788         return parse_8021q_onward(attrs, present_attrs, out_of_range_attr,
1789                                   expected_attrs, flow, key, key_len);
1790     }
1791     return parse_l3_onward(attrs, present_attrs, out_of_range_attr,
1792                            expected_attrs, flow, key, key_len);
1793 }
1794
1795 /* Returns 'fitness' as a string, for use in debug messages. */
1796 const char *
1797 odp_key_fitness_to_string(enum odp_key_fitness fitness)
1798 {
1799     switch (fitness) {
1800     case ODP_FIT_PERFECT:
1801         return "OK";
1802     case ODP_FIT_TOO_MUCH:
1803         return "too_much";
1804     case ODP_FIT_TOO_LITTLE:
1805         return "too_little";
1806     case ODP_FIT_ERROR:
1807         return "error";
1808     default:
1809         return "<unknown>";
1810     }
1811 }
1812
1813 /* Appends an OVS_ACTION_ATTR_USERSPACE action to 'odp_actions' that specifies
1814  * Netlink PID 'pid'.  If 'cookie' is nonnull, adds a userdata attribute whose
1815  * contents contains 'cookie' and returns the offset within 'odp_actions' of
1816  * the start of the cookie.  (If 'cookie' is null, then the return value is not
1817  * meaningful.) */
1818 size_t
1819 odp_put_userspace_action(uint32_t pid, const union user_action_cookie *cookie,
1820                          struct ofpbuf *odp_actions)
1821 {
1822     size_t offset;
1823
1824     offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_USERSPACE);
1825     nl_msg_put_u32(odp_actions, OVS_USERSPACE_ATTR_PID, pid);
1826     if (cookie) {
1827         nl_msg_put_unspec(odp_actions, OVS_USERSPACE_ATTR_USERDATA,
1828                           cookie, sizeof *cookie);
1829     }
1830     nl_msg_end_nested(odp_actions, offset);
1831
1832     return cookie ? odp_actions->size - NLA_ALIGN(sizeof *cookie) : 0;
1833 }
1834 \f
1835 /* The commit_odp_actions() function and its helpers. */
1836
1837 static void
1838 commit_set_action(struct ofpbuf *odp_actions, enum ovs_key_attr key_type,
1839                   const void *key, size_t key_size)
1840 {
1841     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
1842     nl_msg_put_unspec(odp_actions, key_type, key, key_size);
1843     nl_msg_end_nested(odp_actions, offset);
1844 }
1845
1846 static void
1847 commit_set_tun_id_action(const struct flow *flow, struct flow *base,
1848                          struct ofpbuf *odp_actions)
1849 {
1850     if (base->tun_id == flow->tun_id) {
1851         return;
1852     }
1853     base->tun_id = flow->tun_id;
1854
1855     commit_set_action(odp_actions, OVS_KEY_ATTR_TUN_ID,
1856                       &base->tun_id, sizeof(base->tun_id));
1857 }
1858
1859 static void
1860 commit_set_ether_addr_action(const struct flow *flow, struct flow *base,
1861                              struct ofpbuf *odp_actions)
1862 {
1863     struct ovs_key_ethernet eth_key;
1864
1865     if (eth_addr_equals(base->dl_src, flow->dl_src) &&
1866         eth_addr_equals(base->dl_dst, flow->dl_dst)) {
1867         return;
1868     }
1869
1870     memcpy(base->dl_src, flow->dl_src, ETH_ADDR_LEN);
1871     memcpy(base->dl_dst, flow->dl_dst, ETH_ADDR_LEN);
1872
1873     memcpy(eth_key.eth_src, base->dl_src, ETH_ADDR_LEN);
1874     memcpy(eth_key.eth_dst, base->dl_dst, ETH_ADDR_LEN);
1875
1876     commit_set_action(odp_actions, OVS_KEY_ATTR_ETHERNET,
1877                       &eth_key, sizeof(eth_key));
1878 }
1879
1880 static void
1881 commit_vlan_action(const struct flow *flow, struct flow *base,
1882                    struct ofpbuf *odp_actions)
1883 {
1884     if (base->vlan_tci == flow->vlan_tci) {
1885         return;
1886     }
1887
1888     if (base->vlan_tci & htons(VLAN_CFI)) {
1889         nl_msg_put_flag(odp_actions, OVS_ACTION_ATTR_POP_VLAN);
1890     }
1891
1892     if (flow->vlan_tci & htons(VLAN_CFI)) {
1893         struct ovs_action_push_vlan vlan;
1894
1895         vlan.vlan_tpid = htons(ETH_TYPE_VLAN);
1896         vlan.vlan_tci = flow->vlan_tci;
1897         nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_PUSH_VLAN,
1898                           &vlan, sizeof vlan);
1899     }
1900     base->vlan_tci = flow->vlan_tci;
1901 }
1902
1903 static void
1904 commit_set_ipv4_action(const struct flow *flow, struct flow *base,
1905                      struct ofpbuf *odp_actions)
1906 {
1907     struct ovs_key_ipv4 ipv4_key;
1908
1909     if (base->nw_src == flow->nw_src &&
1910         base->nw_dst == flow->nw_dst &&
1911         base->nw_tos == flow->nw_tos &&
1912         base->nw_ttl == flow->nw_ttl &&
1913         base->nw_frag == flow->nw_frag) {
1914         return;
1915     }
1916
1917     ipv4_key.ipv4_src = base->nw_src = flow->nw_src;
1918     ipv4_key.ipv4_dst = base->nw_dst = flow->nw_dst;
1919     ipv4_key.ipv4_tos = base->nw_tos = flow->nw_tos;
1920     ipv4_key.ipv4_ttl = base->nw_ttl = flow->nw_ttl;
1921     ipv4_key.ipv4_proto = base->nw_proto;
1922     ipv4_key.ipv4_frag = ovs_to_odp_frag(base->nw_frag);
1923
1924     commit_set_action(odp_actions, OVS_KEY_ATTR_IPV4,
1925                       &ipv4_key, sizeof(ipv4_key));
1926 }
1927
1928 static void
1929 commit_set_ipv6_action(const struct flow *flow, struct flow *base,
1930                        struct ofpbuf *odp_actions)
1931 {
1932     struct ovs_key_ipv6 ipv6_key;
1933
1934     if (ipv6_addr_equals(&base->ipv6_src, &flow->ipv6_src) &&
1935         ipv6_addr_equals(&base->ipv6_dst, &flow->ipv6_dst) &&
1936         base->ipv6_label == flow->ipv6_label &&
1937         base->nw_tos == flow->nw_tos &&
1938         base->nw_ttl == flow->nw_ttl &&
1939         base->nw_frag == flow->nw_frag) {
1940         return;
1941     }
1942
1943     base->ipv6_src = flow->ipv6_src;
1944     memcpy(&ipv6_key.ipv6_src, &base->ipv6_src, sizeof(ipv6_key.ipv6_src));
1945     base->ipv6_dst = flow->ipv6_dst;
1946     memcpy(&ipv6_key.ipv6_dst, &base->ipv6_dst, sizeof(ipv6_key.ipv6_dst));
1947
1948     ipv6_key.ipv6_label = base->ipv6_label = flow->ipv6_label;
1949     ipv6_key.ipv6_tclass = base->nw_tos = flow->nw_tos;
1950     ipv6_key.ipv6_hlimit = base->nw_ttl = flow->nw_ttl;
1951     ipv6_key.ipv6_proto = base->nw_proto;
1952     ipv6_key.ipv6_frag = ovs_to_odp_frag(base->nw_frag);
1953
1954     commit_set_action(odp_actions, OVS_KEY_ATTR_IPV6,
1955                       &ipv6_key, sizeof(ipv6_key));
1956 }
1957
1958 static void
1959 commit_set_nw_action(const struct flow *flow, struct flow *base,
1960                      struct ofpbuf *odp_actions)
1961 {
1962     /* Check if flow really have an IP header. */
1963     if (!flow->nw_proto) {
1964         return;
1965     }
1966
1967     if (base->dl_type == htons(ETH_TYPE_IP)) {
1968         commit_set_ipv4_action(flow, base, odp_actions);
1969     } else if (base->dl_type == htons(ETH_TYPE_IPV6)) {
1970         commit_set_ipv6_action(flow, base, odp_actions);
1971     }
1972 }
1973
1974 static void
1975 commit_set_port_action(const struct flow *flow, struct flow *base,
1976                        struct ofpbuf *odp_actions)
1977 {
1978     if (!base->tp_src || !base->tp_dst) {
1979         return;
1980     }
1981
1982     if (base->tp_src == flow->tp_src &&
1983         base->tp_dst == flow->tp_dst) {
1984         return;
1985     }
1986
1987     if (flow->nw_proto == IPPROTO_TCP) {
1988         struct ovs_key_tcp port_key;
1989
1990         port_key.tcp_src = base->tp_src = flow->tp_src;
1991         port_key.tcp_dst = base->tp_dst = flow->tp_dst;
1992
1993         commit_set_action(odp_actions, OVS_KEY_ATTR_TCP,
1994                           &port_key, sizeof(port_key));
1995
1996     } else if (flow->nw_proto == IPPROTO_UDP) {
1997         struct ovs_key_udp port_key;
1998
1999         port_key.udp_src = base->tp_src = flow->tp_src;
2000         port_key.udp_dst = base->tp_dst = flow->tp_dst;
2001
2002         commit_set_action(odp_actions, OVS_KEY_ATTR_UDP,
2003                           &port_key, sizeof(port_key));
2004     }
2005 }
2006
2007 static void
2008 commit_set_priority_action(const struct flow *flow, struct flow *base,
2009                            struct ofpbuf *odp_actions)
2010 {
2011     if (base->skb_priority == flow->skb_priority) {
2012         return;
2013     }
2014     base->skb_priority = flow->skb_priority;
2015
2016     commit_set_action(odp_actions, OVS_KEY_ATTR_PRIORITY,
2017                       &base->skb_priority, sizeof(base->skb_priority));
2018 }
2019
2020 /* If any of the flow key data that ODP actions can modify are different in
2021  * 'base' and 'flow', appends ODP actions to 'odp_actions' that change the flow
2022  * key from 'base' into 'flow', and then changes 'base' the same way. */
2023 void
2024 commit_odp_actions(const struct flow *flow, struct flow *base,
2025                    struct ofpbuf *odp_actions)
2026 {
2027     commit_set_tun_id_action(flow, base, odp_actions);
2028     commit_set_ether_addr_action(flow, base, odp_actions);
2029     commit_vlan_action(flow, base, odp_actions);
2030     commit_set_nw_action(flow, base, odp_actions);
2031     commit_set_port_action(flow, base, odp_actions);
2032     commit_set_priority_action(flow, base, odp_actions);
2033 }