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