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