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