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