nx-match: New function nx_pull_match_loose().
[sliver-openvswitch.git] / lib / nx-match.c
1 /*
2  * Copyright (c) 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "nx-match.h"
20
21 #include <netinet/icmp6.h>
22
23 #include "classifier.h"
24 #include "dynamic-string.h"
25 #include "meta-flow.h"
26 #include "ofp-util.h"
27 #include "ofpbuf.h"
28 #include "openflow/nicira-ext.h"
29 #include "packets.h"
30 #include "unaligned.h"
31 #include "vlog.h"
32
33 VLOG_DEFINE_THIS_MODULE(nx_match);
34
35 /* Rate limit for nx_match parse errors.  These always indicate a bug in the
36  * peer and so there's not much point in showing a lot of them. */
37 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
38
39 enum {
40     NXM_INVALID = OFP_MKERR_NICIRA(OFPET_BAD_REQUEST, NXBRC_NXM_INVALID),
41     NXM_BAD_TYPE = OFP_MKERR_NICIRA(OFPET_BAD_REQUEST, NXBRC_NXM_BAD_TYPE),
42     NXM_BAD_VALUE = OFP_MKERR_NICIRA(OFPET_BAD_REQUEST, NXBRC_NXM_BAD_VALUE),
43     NXM_BAD_MASK = OFP_MKERR_NICIRA(OFPET_BAD_REQUEST, NXBRC_NXM_BAD_MASK),
44     NXM_BAD_PREREQ = OFP_MKERR_NICIRA(OFPET_BAD_REQUEST, NXBRC_NXM_BAD_PREREQ),
45     NXM_DUP_TYPE = OFP_MKERR_NICIRA(OFPET_BAD_REQUEST, NXBRC_NXM_DUP_TYPE),
46     BAD_ARGUMENT = OFP_MKERR(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT)
47 };
48
49 /* Returns the width of the data for a field with the given 'header', in
50  * bytes. */
51 int
52 nxm_field_bytes(uint32_t header)
53 {
54     unsigned int length = NXM_LENGTH(header);
55     return NXM_HASMASK(header) ? length / 2 : length;
56 }
57
58 /* Returns the width of the data for a field with the given 'header', in
59  * bits. */
60 int
61 nxm_field_bits(uint32_t header)
62 {
63     return nxm_field_bytes(header) * 8;
64 }
65 \f
66 /* nx_pull_match() and helpers. */
67
68 static uint32_t
69 nx_entry_ok(const void *p, unsigned int match_len)
70 {
71     unsigned int payload_len;
72     ovs_be32 header_be;
73     uint32_t header;
74
75     if (match_len < 4) {
76         if (match_len) {
77             VLOG_DBG_RL(&rl, "nx_match ends with partial nxm_header");
78         }
79         return 0;
80     }
81     memcpy(&header_be, p, 4);
82     header = ntohl(header_be);
83
84     payload_len = NXM_LENGTH(header);
85     if (!payload_len) {
86         VLOG_DBG_RL(&rl, "nxm_entry %08"PRIx32" has invalid payload "
87                     "length 0", header);
88         return 0;
89     }
90     if (match_len < payload_len + 4) {
91         VLOG_DBG_RL(&rl, "%"PRIu32"-byte nxm_entry but only "
92                     "%u bytes left in nx_match", payload_len + 4, match_len);
93         return 0;
94     }
95
96     return header;
97 }
98
99 static int
100 nx_pull_match__(struct ofpbuf *b, unsigned int match_len, bool strict,
101                 uint16_t priority, struct cls_rule *rule,
102                 ovs_be64 *cookie, ovs_be64 *cookie_mask)
103 {
104     uint32_t header;
105     uint8_t *p;
106
107     assert((cookie != NULL) == (cookie_mask != NULL));
108
109     p = ofpbuf_try_pull(b, ROUND_UP(match_len, 8));
110     if (!p) {
111         VLOG_DBG_RL(&rl, "nx_match length %u, rounded up to a "
112                     "multiple of 8, is longer than space in message (max "
113                     "length %zu)", match_len, b->size);
114         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
115     }
116
117     cls_rule_init_catchall(rule, priority);
118     if (cookie) {
119         *cookie = *cookie_mask = htonll(0);
120     }
121     for (;
122          (header = nx_entry_ok(p, match_len)) != 0;
123          p += 4 + NXM_LENGTH(header), match_len -= 4 + NXM_LENGTH(header)) {
124         const struct mf_field *mf;
125         int error;
126
127         mf = mf_from_nxm_header(header);
128         if (!mf) {
129             if (strict) {
130                 error = NXM_BAD_TYPE;
131             } else {
132                 continue;
133             }
134         } else if (!mf_are_prereqs_ok(mf, &rule->flow)) {
135             error = NXM_BAD_PREREQ;
136         } else if (!mf_is_all_wild(mf, &rule->wc)) {
137             error = NXM_DUP_TYPE;
138         } else {
139             unsigned int width = mf->n_bytes;
140             union mf_value value;
141
142             memcpy(&value, p + 4, width);
143             if (!mf_is_value_valid(mf, &value)) {
144                 error = NXM_BAD_VALUE;
145             } else if (!NXM_HASMASK(header)) {
146                 error = 0;
147                 mf_set_value(mf, &value, rule);
148             } else {
149                 union mf_value mask;
150
151                 memcpy(&mask, p + 4 + width, width);
152                 if (!mf_is_mask_valid(mf, &mask)) {
153                     error = NXM_BAD_MASK;
154                 } else {
155                     error = 0;
156                     mf_set(mf, &value, &mask, rule);
157                 }
158             }
159         }
160
161         /* Check if the match is for a cookie rather than a classifier rule. */
162         if ((header == NXM_NX_COOKIE || header == NXM_NX_COOKIE_W) && cookie) {
163             if (*cookie_mask) {
164                 error = NXM_DUP_TYPE;
165             } else {
166                 unsigned int width = sizeof *cookie;
167
168                 memcpy(cookie, p + 4, width);
169                 if (NXM_HASMASK(header)) {
170                     memcpy(cookie_mask, p + 4 + width, width);
171                 } else {
172                     *cookie_mask = htonll(UINT64_MAX);
173                 }
174                 error = 0;
175             }
176         }
177
178         if (error) {
179             char *msg = ofputil_error_to_string(error);
180             VLOG_DBG_RL(&rl, "bad nxm_entry %#08"PRIx32" (vendor=%"PRIu32", "
181                         "field=%"PRIu32", hasmask=%"PRIu32", len=%"PRIu32"), "
182                         "(%s)", header,
183                         NXM_VENDOR(header), NXM_FIELD(header),
184                         NXM_HASMASK(header), NXM_LENGTH(header),
185                         msg);
186             free(msg);
187
188             return error;
189         }
190     }
191
192     return match_len ? NXM_INVALID : 0;
193 }
194
195 /* Parses the nx_match formatted match description in 'b' with length
196  * 'match_len'.  The results are stored in 'rule', which is initialized with
197  * 'priority'.  If 'cookie' and 'cookie_mask' contain valid pointers, then the
198  * cookie and mask will be stored in them if a "NXM_NX_COOKIE*" match is
199  * defined.  Otherwise, 0 is stored in both.
200  *
201  * Fails with an error when encountering unknown NXM headers.
202  *
203  * Returns 0 if successful, otherwise an OpenFlow error code. */
204 int
205 nx_pull_match(struct ofpbuf *b, unsigned int match_len,
206               uint16_t priority, struct cls_rule *rule,
207               ovs_be64 *cookie, ovs_be64 *cookie_mask)
208 {
209     return nx_pull_match__(b, match_len, true, priority, rule, cookie,
210                            cookie_mask);
211 }
212
213 /* Behaves the same as nx_pull_match() with one exception.  Skips over unknown
214  * NXM headers instead of failing with an error when they are encountered. */
215 int
216 nx_pull_match_loose(struct ofpbuf *b, unsigned int match_len,
217                     uint16_t priority, struct cls_rule *rule,
218                     ovs_be64 *cookie, ovs_be64 *cookie_mask)
219 {
220     return nx_pull_match__(b, match_len, false, priority, rule, cookie,
221                            cookie_mask);
222 }
223 \f
224 /* nx_put_match() and helpers.
225  *
226  * 'put' functions whose names end in 'w' add a wildcarded field.
227  * 'put' functions whose names end in 'm' add a field that might be wildcarded.
228  * Other 'put' functions add exact-match fields.
229  */
230
231 static void
232 nxm_put_header(struct ofpbuf *b, uint32_t header)
233 {
234     ovs_be32 n_header = htonl(header);
235     ofpbuf_put(b, &n_header, sizeof n_header);
236 }
237
238 static void
239 nxm_put_8(struct ofpbuf *b, uint32_t header, uint8_t value)
240 {
241     nxm_put_header(b, header);
242     ofpbuf_put(b, &value, sizeof value);
243 }
244
245 static void
246 nxm_put_8m(struct ofpbuf *b, uint32_t header, uint8_t value, uint8_t mask)
247 {
248     switch (mask) {
249     case 0:
250         break;
251
252     case UINT8_MAX:
253         nxm_put_8(b, header, value);
254         break;
255
256     default:
257         nxm_put_header(b, NXM_MAKE_WILD_HEADER(header));
258         ofpbuf_put(b, &value, sizeof value);
259         ofpbuf_put(b, &mask, sizeof mask);
260     }
261 }
262
263 static void
264 nxm_put_16(struct ofpbuf *b, uint32_t header, ovs_be16 value)
265 {
266     nxm_put_header(b, header);
267     ofpbuf_put(b, &value, sizeof value);
268 }
269
270 static void
271 nxm_put_16w(struct ofpbuf *b, uint32_t header, ovs_be16 value, ovs_be16 mask)
272 {
273     nxm_put_header(b, header);
274     ofpbuf_put(b, &value, sizeof value);
275     ofpbuf_put(b, &mask, sizeof mask);
276 }
277
278 static void
279 nxm_put_16m(struct ofpbuf *b, uint32_t header, ovs_be16 value, ovs_be16 mask)
280 {
281     switch (mask) {
282     case 0:
283         break;
284
285     case CONSTANT_HTONS(UINT16_MAX):
286         nxm_put_16(b, header, value);
287         break;
288
289     default:
290         nxm_put_16w(b, NXM_MAKE_WILD_HEADER(header), value, mask);
291         break;
292     }
293 }
294
295 static void
296 nxm_put_32(struct ofpbuf *b, uint32_t header, ovs_be32 value)
297 {
298     nxm_put_header(b, header);
299     ofpbuf_put(b, &value, sizeof value);
300 }
301
302 static void
303 nxm_put_32w(struct ofpbuf *b, uint32_t header, ovs_be32 value, ovs_be32 mask)
304 {
305     nxm_put_header(b, header);
306     ofpbuf_put(b, &value, sizeof value);
307     ofpbuf_put(b, &mask, sizeof mask);
308 }
309
310 static void
311 nxm_put_32m(struct ofpbuf *b, uint32_t header, ovs_be32 value, ovs_be32 mask)
312 {
313     switch (mask) {
314     case 0:
315         break;
316
317     case CONSTANT_HTONL(UINT32_MAX):
318         nxm_put_32(b, header, value);
319         break;
320
321     default:
322         nxm_put_32w(b, NXM_MAKE_WILD_HEADER(header), value, mask);
323         break;
324     }
325 }
326
327 static void
328 nxm_put_64(struct ofpbuf *b, uint32_t header, ovs_be64 value)
329 {
330     nxm_put_header(b, header);
331     ofpbuf_put(b, &value, sizeof value);
332 }
333
334 static void
335 nxm_put_64w(struct ofpbuf *b, uint32_t header, ovs_be64 value, ovs_be64 mask)
336 {
337     nxm_put_header(b, header);
338     ofpbuf_put(b, &value, sizeof value);
339     ofpbuf_put(b, &mask, sizeof mask);
340 }
341
342 static void
343 nxm_put_64m(struct ofpbuf *b, uint32_t header, ovs_be64 value, ovs_be64 mask)
344 {
345     switch (mask) {
346     case 0:
347         break;
348
349     case CONSTANT_HTONLL(UINT64_MAX):
350         nxm_put_64(b, header, value);
351         break;
352
353     default:
354         nxm_put_64w(b, NXM_MAKE_WILD_HEADER(header), value, mask);
355         break;
356     }
357 }
358
359 static void
360 nxm_put_eth(struct ofpbuf *b, uint32_t header,
361             const uint8_t value[ETH_ADDR_LEN])
362 {
363     nxm_put_header(b, header);
364     ofpbuf_put(b, value, ETH_ADDR_LEN);
365 }
366
367 static void
368 nxm_put_eth_dst(struct ofpbuf *b,
369                 flow_wildcards_t wc, const uint8_t value[ETH_ADDR_LEN])
370 {
371     switch (wc & (FWW_DL_DST | FWW_ETH_MCAST)) {
372     case FWW_DL_DST | FWW_ETH_MCAST:
373         break;
374     default:
375         nxm_put_header(b, NXM_OF_ETH_DST_W);
376         ofpbuf_put(b, value, ETH_ADDR_LEN);
377         ofpbuf_put(b, flow_wildcards_to_dl_dst_mask(wc), ETH_ADDR_LEN);
378         break;
379     case 0:
380         nxm_put_eth(b, NXM_OF_ETH_DST, value);
381         break;
382     }
383 }
384
385 static void
386 nxm_put_ipv6(struct ofpbuf *b, uint32_t header,
387              const struct in6_addr *value, const struct in6_addr *mask)
388 {
389     if (ipv6_mask_is_any(mask)) {
390         return;
391     } else if (ipv6_mask_is_exact(mask)) {
392         nxm_put_header(b, header);
393         ofpbuf_put(b, value, sizeof *value);
394     } else {
395         nxm_put_header(b, NXM_MAKE_WILD_HEADER(header));
396         ofpbuf_put(b, value, sizeof *value);
397         ofpbuf_put(b, mask, sizeof *mask);
398     }
399 }
400
401 static void
402 nxm_put_frag(struct ofpbuf *b, const struct cls_rule *cr)
403 {
404     uint8_t nw_frag = cr->flow.nw_frag;
405     uint8_t nw_frag_mask = cr->wc.nw_frag_mask;
406
407     switch (nw_frag_mask) {
408     case 0:
409         break;
410
411     case FLOW_NW_FRAG_MASK:
412         nxm_put_8(b, NXM_NX_IP_FRAG, nw_frag);
413         break;
414
415     default:
416         nxm_put_8m(b, NXM_NX_IP_FRAG, nw_frag,
417                    nw_frag_mask & FLOW_NW_FRAG_MASK);
418         break;
419     }
420 }
421
422 /* Appends to 'b' the nx_match format that expresses 'cr' (except for
423  * 'cr->priority', because priority is not part of nx_match), plus enough
424  * zero bytes to pad the nx_match out to a multiple of 8.  For Flow Mod
425  * and Flow Stats Requests messages, a 'cookie' and 'cookie_mask' may be
426  * supplied.  Otherwise, 'cookie_mask' should be zero.
427  *
428  * This function can cause 'b''s data to be reallocated.
429  *
430  * Returns the number of bytes appended to 'b', excluding padding.
431  *
432  * If 'cr' is a catch-all rule that matches every packet, then this function
433  * appends nothing to 'b' and returns 0. */
434 int
435 nx_put_match(struct ofpbuf *b, const struct cls_rule *cr,
436              ovs_be64 cookie, ovs_be64 cookie_mask)
437 {
438     const flow_wildcards_t wc = cr->wc.wildcards;
439     const struct flow *flow = &cr->flow;
440     const size_t start_len = b->size;
441     int match_len;
442     int i;
443
444     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 7);
445
446     /* Metadata. */
447     if (!(wc & FWW_IN_PORT)) {
448         uint16_t in_port = flow->in_port;
449         nxm_put_16(b, NXM_OF_IN_PORT, htons(in_port));
450     }
451
452     /* Ethernet. */
453     nxm_put_eth_dst(b, wc, flow->dl_dst);
454     if (!(wc & FWW_DL_SRC)) {
455         nxm_put_eth(b, NXM_OF_ETH_SRC, flow->dl_src);
456     }
457     if (!(wc & FWW_DL_TYPE)) {
458         nxm_put_16(b, NXM_OF_ETH_TYPE,
459                    ofputil_dl_type_to_openflow(flow->dl_type));
460     }
461
462     /* 802.1Q. */
463     nxm_put_16m(b, NXM_OF_VLAN_TCI, flow->vlan_tci, cr->wc.vlan_tci_mask);
464
465     /* L3. */
466     if (!(wc & FWW_DL_TYPE) && flow->dl_type == htons(ETH_TYPE_IP)) {
467         /* IP. */
468         nxm_put_32m(b, NXM_OF_IP_SRC, flow->nw_src, cr->wc.nw_src_mask);
469         nxm_put_32m(b, NXM_OF_IP_DST, flow->nw_dst, cr->wc.nw_dst_mask);
470         nxm_put_frag(b, cr);
471
472         if (!(wc & FWW_NW_DSCP)) {
473             nxm_put_8(b, NXM_OF_IP_TOS, flow->nw_tos & IP_DSCP_MASK);
474         }
475
476         if (!(wc & FWW_NW_ECN)) {
477             nxm_put_8(b, NXM_NX_IP_ECN, flow->nw_tos & IP_ECN_MASK);
478         }
479
480         if (!(wc & FWW_NW_TTL)) {
481             nxm_put_8(b, NXM_NX_IP_TTL, flow->nw_ttl);
482         }
483
484         if (!(wc & FWW_NW_PROTO)) {
485             nxm_put_8(b, NXM_OF_IP_PROTO, flow->nw_proto);
486             switch (flow->nw_proto) {
487                 /* TCP. */
488             case IPPROTO_TCP:
489                 if (!(wc & FWW_TP_SRC)) {
490                     nxm_put_16(b, NXM_OF_TCP_SRC, flow->tp_src);
491                 }
492                 if (!(wc & FWW_TP_DST)) {
493                     nxm_put_16(b, NXM_OF_TCP_DST, flow->tp_dst);
494                 }
495                 break;
496
497                 /* UDP. */
498             case IPPROTO_UDP:
499                 if (!(wc & FWW_TP_SRC)) {
500                     nxm_put_16(b, NXM_OF_UDP_SRC, flow->tp_src);
501                 }
502                 if (!(wc & FWW_TP_DST)) {
503                     nxm_put_16(b, NXM_OF_UDP_DST, flow->tp_dst);
504                 }
505                 break;
506
507                 /* ICMP. */
508             case IPPROTO_ICMP:
509                 if (!(wc & FWW_TP_SRC)) {
510                     nxm_put_8(b, NXM_OF_ICMP_TYPE, ntohs(flow->tp_src));
511                 }
512                 if (!(wc & FWW_TP_DST)) {
513                     nxm_put_8(b, NXM_OF_ICMP_CODE, ntohs(flow->tp_dst));
514                 }
515                 break;
516             }
517         }
518     } else if (!(wc & FWW_DL_TYPE) && flow->dl_type == htons(ETH_TYPE_IPV6)) {
519         /* IPv6. */
520         nxm_put_ipv6(b, NXM_NX_IPV6_SRC, &flow->ipv6_src,
521                 &cr->wc.ipv6_src_mask);
522         nxm_put_ipv6(b, NXM_NX_IPV6_DST, &flow->ipv6_dst,
523                 &cr->wc.ipv6_dst_mask);
524         nxm_put_frag(b, cr);
525
526         if (!(wc & FWW_IPV6_LABEL)) {
527             nxm_put_32(b, NXM_NX_IPV6_LABEL, flow->ipv6_label);
528         }
529
530         if (!(wc & FWW_NW_DSCP)) {
531             nxm_put_8(b, NXM_OF_IP_TOS, flow->nw_tos & IP_DSCP_MASK);
532         }
533
534         if (!(wc & FWW_NW_ECN)) {
535             nxm_put_8(b, NXM_NX_IP_ECN, flow->nw_tos & IP_ECN_MASK);
536         }
537
538         if (!(wc & FWW_NW_TTL)) {
539             nxm_put_8(b, NXM_NX_IP_TTL, flow->nw_ttl);
540         }
541
542         if (!(wc & FWW_NW_PROTO)) {
543             nxm_put_8(b, NXM_OF_IP_PROTO, flow->nw_proto);
544             switch (flow->nw_proto) {
545                 /* TCP. */
546             case IPPROTO_TCP:
547                 if (!(wc & FWW_TP_SRC)) {
548                     nxm_put_16(b, NXM_OF_TCP_SRC, flow->tp_src);
549                 }
550                 if (!(wc & FWW_TP_DST)) {
551                     nxm_put_16(b, NXM_OF_TCP_DST, flow->tp_dst);
552                 }
553                 break;
554
555                 /* UDP. */
556             case IPPROTO_UDP:
557                 if (!(wc & FWW_TP_SRC)) {
558                     nxm_put_16(b, NXM_OF_UDP_SRC, flow->tp_src);
559                 }
560                 if (!(wc & FWW_TP_DST)) {
561                     nxm_put_16(b, NXM_OF_UDP_DST, flow->tp_dst);
562                 }
563                 break;
564
565                 /* ICMPv6. */
566             case IPPROTO_ICMPV6:
567                 if (!(wc & FWW_TP_SRC)) {
568                     nxm_put_8(b, NXM_NX_ICMPV6_TYPE, ntohs(flow->tp_src));
569
570                     if (flow->tp_src == htons(ND_NEIGHBOR_SOLICIT) ||
571                         flow->tp_src == htons(ND_NEIGHBOR_ADVERT)) {
572                         if (!(wc & FWW_ND_TARGET)) {
573                             nxm_put_ipv6(b, NXM_NX_ND_TARGET, &flow->nd_target,
574                                          &in6addr_exact);
575                         }
576                         if (!(wc & FWW_ARP_SHA)
577                             && flow->tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
578                             nxm_put_eth(b, NXM_NX_ND_SLL, flow->arp_sha);
579                         }
580                         if (!(wc & FWW_ARP_THA)
581                             && flow->tp_src == htons(ND_NEIGHBOR_ADVERT)) {
582                             nxm_put_eth(b, NXM_NX_ND_TLL, flow->arp_tha);
583                         }
584                     }
585                 }
586                 if (!(wc & FWW_TP_DST)) {
587                     nxm_put_8(b, NXM_NX_ICMPV6_CODE, ntohs(flow->tp_dst));
588                 }
589                 break;
590             }
591         }
592     } else if (!(wc & FWW_DL_TYPE) && flow->dl_type == htons(ETH_TYPE_ARP)) {
593         /* ARP. */
594         if (!(wc & FWW_NW_PROTO)) {
595             nxm_put_16(b, NXM_OF_ARP_OP, htons(flow->nw_proto));
596         }
597         nxm_put_32m(b, NXM_OF_ARP_SPA, flow->nw_src, cr->wc.nw_src_mask);
598         nxm_put_32m(b, NXM_OF_ARP_TPA, flow->nw_dst, cr->wc.nw_dst_mask);
599         if (!(wc & FWW_ARP_SHA)) {
600             nxm_put_eth(b, NXM_NX_ARP_SHA, flow->arp_sha);
601         }
602         if (!(wc & FWW_ARP_THA)) {
603             nxm_put_eth(b, NXM_NX_ARP_THA, flow->arp_tha);
604         }
605     }
606
607     /* Tunnel ID. */
608     nxm_put_64m(b, NXM_NX_TUN_ID, flow->tun_id, cr->wc.tun_id_mask);
609
610     /* Registers. */
611     for (i = 0; i < FLOW_N_REGS; i++) {
612         nxm_put_32m(b, NXM_NX_REG(i),
613                     htonl(flow->regs[i]), htonl(cr->wc.reg_masks[i]));
614     }
615
616     /* Cookie. */
617     nxm_put_64m(b, NXM_NX_COOKIE, cookie, cookie_mask);
618
619     match_len = b->size - start_len;
620     ofpbuf_put_zeros(b, ROUND_UP(match_len, 8) - match_len);
621     return match_len;
622 }
623 \f
624 /* nx_match_to_string() and helpers. */
625
626 static void format_nxm_field_name(struct ds *, uint32_t header);
627
628 char *
629 nx_match_to_string(const uint8_t *p, unsigned int match_len)
630 {
631     uint32_t header;
632     struct ds s;
633
634     if (!match_len) {
635         return xstrdup("<any>");
636     }
637
638     ds_init(&s);
639     while ((header = nx_entry_ok(p, match_len)) != 0) {
640         unsigned int length = NXM_LENGTH(header);
641         unsigned int value_len = nxm_field_bytes(header);
642         const uint8_t *value = p + 4;
643         const uint8_t *mask = value + value_len;
644         unsigned int i;
645
646         if (s.length) {
647             ds_put_cstr(&s, ", ");
648         }
649
650         format_nxm_field_name(&s, header);
651         ds_put_char(&s, '(');
652
653         for (i = 0; i < value_len; i++) {
654             ds_put_format(&s, "%02x", value[i]);
655         }
656         if (NXM_HASMASK(header)) {
657             ds_put_char(&s, '/');
658             for (i = 0; i < value_len; i++) {
659                 ds_put_format(&s, "%02x", mask[i]);
660             }
661         }
662         ds_put_char(&s, ')');
663
664         p += 4 + length;
665         match_len -= 4 + length;
666     }
667
668     if (match_len) {
669         if (s.length) {
670             ds_put_cstr(&s, ", ");
671         }
672
673         ds_put_format(&s, "<%u invalid bytes>", match_len);
674     }
675
676     return ds_steal_cstr(&s);
677 }
678
679 static void
680 format_nxm_field_name(struct ds *s, uint32_t header)
681 {
682     const struct mf_field *mf = mf_from_nxm_header(header);
683     if (mf) {
684         ds_put_cstr(s, mf->nxm_name);
685         if (NXM_HASMASK(header)) {
686             ds_put_cstr(s, "_W");
687         }
688     } else if (header == NXM_NX_COOKIE) {
689         ds_put_cstr(s, "NXM_NX_COOKIE");
690     } else if (header == NXM_NX_COOKIE_W) {
691         ds_put_cstr(s, "NXM_NX_COOKIE_W");
692     } else {
693         ds_put_format(s, "%d:%d", NXM_VENDOR(header), NXM_FIELD(header));
694     }
695 }
696
697 static uint32_t
698 parse_nxm_field_name(const char *name, int name_len)
699 {
700     bool wild;
701     int i;
702
703     /* Check whether it's a field name. */
704     wild = name_len > 2 && !memcmp(&name[name_len - 2], "_W", 2);
705     if (wild) {
706         name_len -= 2;
707     }
708
709     for (i = 0; i < MFF_N_IDS; i++) {
710         const struct mf_field *mf = mf_from_id(i);
711
712         if (mf->nxm_name
713             && !strncmp(mf->nxm_name, name, name_len)
714             && mf->nxm_name[name_len] == '\0') {
715             if (!wild) {
716                 return mf->nxm_header;
717             } else if (mf->maskable != MFM_NONE) {
718                 return NXM_MAKE_WILD_HEADER(mf->nxm_header);
719             }
720         }
721     }
722
723     if (!strncmp("NXM_NX_COOKIE", name, name_len)
724                 && (name_len == strlen("NXM_NX_COOKIE"))) {
725         if (!wild) {
726             return NXM_NX_COOKIE;
727         } else {
728             return NXM_NX_COOKIE_W;
729         }
730     }
731
732     /* Check whether it's a 32-bit field header value as hex.
733      * (This isn't ordinarily useful except for testing error behavior.) */
734     if (name_len == 8) {
735         uint32_t header = hexits_value(name, name_len, NULL);
736         if (header != UINT_MAX) {
737             return header;
738         }
739     }
740
741     return 0;
742 }
743 \f
744 /* nx_match_from_string(). */
745
746 int
747 nx_match_from_string(const char *s, struct ofpbuf *b)
748 {
749     const char *full_s = s;
750     const size_t start_len = b->size;
751     int match_len;
752
753     if (!strcmp(s, "<any>")) {
754         /* Ensure that 'b->data' isn't actually null. */
755         ofpbuf_prealloc_tailroom(b, 1);
756         return 0;
757     }
758
759     for (s += strspn(s, ", "); *s; s += strspn(s, ", ")) {
760         const char *name;
761         uint32_t header;
762         int name_len;
763         size_t n;
764
765         name = s;
766         name_len = strcspn(s, "(");
767         if (s[name_len] != '(') {
768             ovs_fatal(0, "%s: missing ( at end of nx_match", full_s);
769         }
770
771         header = parse_nxm_field_name(name, name_len);
772         if (!header) {
773             ovs_fatal(0, "%s: unknown field `%.*s'", full_s, name_len, s);
774         }
775
776         s += name_len + 1;
777
778         nxm_put_header(b, header);
779         s = ofpbuf_put_hex(b, s, &n);
780         if (n != nxm_field_bytes(header)) {
781             ovs_fatal(0, "%.2s: hex digits expected", s);
782         }
783         if (NXM_HASMASK(header)) {
784             s += strspn(s, " ");
785             if (*s != '/') {
786                 ovs_fatal(0, "%s: missing / in masked field %.*s",
787                           full_s, name_len, name);
788             }
789             s = ofpbuf_put_hex(b, s + 1, &n);
790             if (n != nxm_field_bytes(header)) {
791                 ovs_fatal(0, "%.2s: hex digits expected", s);
792             }
793         }
794
795         s += strspn(s, " ");
796         if (*s != ')') {
797             ovs_fatal(0, "%s: missing ) following field %.*s",
798                       full_s, name_len, name);
799         }
800         s++;
801     }
802
803     match_len = b->size - start_len;
804     ofpbuf_put_zeros(b, ROUND_UP(match_len, 8) - match_len);
805     return match_len;
806 }
807 \f
808 const char *
809 nxm_parse_field_bits(const char *s, uint32_t *headerp, int *ofsp, int *n_bitsp)
810 {
811     const char *full_s = s;
812     const char *name;
813     uint32_t header;
814     int start, end;
815     int name_len;
816     int width;
817
818     name = s;
819     name_len = strcspn(s, "[");
820     if (s[name_len] != '[') {
821         ovs_fatal(0, "%s: missing [ looking for field name", full_s);
822     }
823
824     header = parse_nxm_field_name(name, name_len);
825     if (!header) {
826         ovs_fatal(0, "%s: unknown field `%.*s'", full_s, name_len, s);
827     }
828     width = nxm_field_bits(header);
829
830     s += name_len;
831     if (sscanf(s, "[%d..%d]", &start, &end) == 2) {
832         /* Nothing to do. */
833     } else if (sscanf(s, "[%d]", &start) == 1) {
834         end = start;
835     } else if (!strncmp(s, "[]", 2)) {
836         start = 0;
837         end = width - 1;
838     } else {
839         ovs_fatal(0, "%s: syntax error expecting [] or [<bit>] or "
840                   "[<start>..<end>]", full_s);
841     }
842     s = strchr(s, ']') + 1;
843
844     if (start > end) {
845         ovs_fatal(0, "%s: starting bit %d is after ending bit %d",
846                   full_s, start, end);
847     } else if (start >= width) {
848         ovs_fatal(0, "%s: starting bit %d is not valid because field is only "
849                   "%d bits wide", full_s, start, width);
850     } else if (end >= width){
851         ovs_fatal(0, "%s: ending bit %d is not valid because field is only "
852                   "%d bits wide", full_s, end, width);
853     }
854
855     *headerp = header;
856     *ofsp = start;
857     *n_bitsp = end - start + 1;
858
859     return s;
860 }
861
862 void
863 nxm_parse_reg_move(struct nx_action_reg_move *move, const char *s)
864 {
865     const char *full_s = s;
866     uint32_t src, dst;
867     int src_ofs, dst_ofs;
868     int src_n_bits, dst_n_bits;
869
870     s = nxm_parse_field_bits(s, &src, &src_ofs, &src_n_bits);
871     if (strncmp(s, "->", 2)) {
872         ovs_fatal(0, "%s: missing `->' following source", full_s);
873     }
874     s += 2;
875     s = nxm_parse_field_bits(s, &dst, &dst_ofs, &dst_n_bits);
876     if (*s != '\0') {
877         ovs_fatal(0, "%s: trailing garbage following destination", full_s);
878     }
879
880     if (src_n_bits != dst_n_bits) {
881         ovs_fatal(0, "%s: source field is %d bits wide but destination is "
882                   "%d bits wide", full_s, src_n_bits, dst_n_bits);
883     }
884
885     ofputil_init_NXAST_REG_MOVE(move);
886     move->n_bits = htons(src_n_bits);
887     move->src_ofs = htons(src_ofs);
888     move->dst_ofs = htons(dst_ofs);
889     move->src = htonl(src);
890     move->dst = htonl(dst);
891 }
892
893 void
894 nxm_parse_reg_load(struct nx_action_reg_load *load, const char *s)
895 {
896     const char *full_s = s;
897     uint32_t dst;
898     int ofs, n_bits;
899     uint64_t value;
900
901     value = strtoull(s, (char **) &s, 0);
902     if (strncmp(s, "->", 2)) {
903         ovs_fatal(0, "%s: missing `->' following value", full_s);
904     }
905     s += 2;
906     s = nxm_parse_field_bits(s, &dst, &ofs, &n_bits);
907     if (*s != '\0') {
908         ovs_fatal(0, "%s: trailing garbage following destination", full_s);
909     }
910
911     if (n_bits < 64 && (value >> n_bits) != 0) {
912         ovs_fatal(0, "%s: value %"PRIu64" does not fit into %d bits",
913                   full_s, value, n_bits);
914     }
915
916     ofputil_init_NXAST_REG_LOAD(load);
917     load->ofs_nbits = nxm_encode_ofs_nbits(ofs, n_bits);
918     load->dst = htonl(dst);
919     load->value = htonll(value);
920 }
921 \f
922 /* nxm_format_reg_move(), nxm_format_reg_load(). */
923
924 void
925 nxm_format_field_bits(struct ds *s, uint32_t header, int ofs, int n_bits)
926 {
927     format_nxm_field_name(s, header);
928     if (ofs == 0 && n_bits == nxm_field_bits(header)) {
929         ds_put_cstr(s, "[]");
930     } else if (n_bits == 1) {
931         ds_put_format(s, "[%d]", ofs);
932     } else {
933         ds_put_format(s, "[%d..%d]", ofs, ofs + n_bits - 1);
934     }
935 }
936
937 void
938 nxm_format_reg_move(const struct nx_action_reg_move *move, struct ds *s)
939 {
940     int n_bits = ntohs(move->n_bits);
941     int src_ofs = ntohs(move->src_ofs);
942     int dst_ofs = ntohs(move->dst_ofs);
943     uint32_t src = ntohl(move->src);
944     uint32_t dst = ntohl(move->dst);
945
946     ds_put_format(s, "move:");
947     nxm_format_field_bits(s, src, src_ofs, n_bits);
948     ds_put_cstr(s, "->");
949     nxm_format_field_bits(s, dst, dst_ofs, n_bits);
950 }
951
952 void
953 nxm_format_reg_load(const struct nx_action_reg_load *load, struct ds *s)
954 {
955     int ofs = nxm_decode_ofs(load->ofs_nbits);
956     int n_bits = nxm_decode_n_bits(load->ofs_nbits);
957     uint32_t dst = ntohl(load->dst);
958     uint64_t value = ntohll(load->value);
959
960     ds_put_format(s, "load:%#"PRIx64"->", value);
961     nxm_format_field_bits(s, dst, ofs, n_bits);
962 }
963 \f
964 /* nxm_check_reg_move(), nxm_check_reg_load(). */
965
966 static bool
967 field_ok(const struct mf_field *mf, const struct flow *flow, int size)
968 {
969     return (mf
970             && mf_are_prereqs_ok(mf, flow)
971             && size <= nxm_field_bits(mf->nxm_header));
972 }
973
974 int
975 nxm_check_reg_move(const struct nx_action_reg_move *action,
976                    const struct flow *flow)
977 {
978     int src_ofs, dst_ofs, n_bits;
979     int error;
980
981     n_bits = ntohs(action->n_bits);
982     src_ofs = ntohs(action->src_ofs);
983     dst_ofs = ntohs(action->dst_ofs);
984
985     error = nxm_src_check(action->src, src_ofs, n_bits, flow);
986     if (error) {
987         return error;
988     }
989
990     return nxm_dst_check(action->dst, dst_ofs, n_bits, flow);
991 }
992
993 /* Given a flow, checks that the source field represented by 'src_header'
994  * in the range ['ofs', 'ofs' + 'n_bits') is valid. */
995 int
996 nxm_src_check(ovs_be32 src_header_, unsigned int ofs, unsigned int n_bits,
997               const struct flow *flow)
998 {
999     uint32_t src_header = ntohl(src_header_);
1000     const struct mf_field *src = mf_from_nxm_header(src_header);
1001
1002     if (!n_bits) {
1003         VLOG_WARN_RL(&rl, "zero bit source field");
1004     } else if (NXM_HASMASK(src_header) || !field_ok(src, flow, ofs + n_bits)) {
1005         VLOG_WARN_RL(&rl, "invalid source field");
1006     } else {
1007         return 0;
1008     }
1009
1010     return BAD_ARGUMENT;
1011 }
1012
1013 /* Given a flow, checks that the destination field represented by 'dst_header'
1014  * in the range ['ofs', 'ofs' + 'n_bits') is valid. */
1015 int
1016 nxm_dst_check(ovs_be32 dst_header_, unsigned int ofs, unsigned int n_bits,
1017               const struct flow *flow)
1018 {
1019     uint32_t dst_header = ntohl(dst_header_);
1020     const struct mf_field *dst = mf_from_nxm_header(dst_header);
1021
1022     if (!n_bits) {
1023         VLOG_WARN_RL(&rl, "zero bit destination field");
1024     } else if (NXM_HASMASK(dst_header) || !field_ok(dst, flow, ofs + n_bits)) {
1025         VLOG_WARN_RL(&rl, "invalid destination field");
1026     } else if (!dst->writable) {
1027         VLOG_WARN_RL(&rl, "destination field is not writable");
1028     } else {
1029         return 0;
1030     }
1031
1032     return BAD_ARGUMENT;
1033 }
1034
1035 int
1036 nxm_check_reg_load(const struct nx_action_reg_load *action,
1037                    const struct flow *flow)
1038 {
1039     unsigned int ofs = nxm_decode_ofs(action->ofs_nbits);
1040     unsigned int n_bits = nxm_decode_n_bits(action->ofs_nbits);
1041     int error;
1042
1043     error = nxm_dst_check(action->dst, ofs, n_bits, flow);
1044     if (error) {
1045         return error;
1046     }
1047
1048     /* Reject 'action' if a bit numbered 'n_bits' or higher is set to 1 in
1049      * action->value. */
1050     if (n_bits < 64 && ntohll(action->value) >> n_bits) {
1051         return BAD_ARGUMENT;
1052     }
1053
1054     return 0;
1055 }
1056 \f
1057 /* nxm_execute_reg_move(), nxm_execute_reg_load(). */
1058
1059 static void
1060 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
1061              void *dst_, unsigned int dst_len, unsigned int dst_ofs,
1062              unsigned int n_bits)
1063 {
1064     const uint8_t *src = src_;
1065     uint8_t *dst = dst_;
1066
1067     src += src_len - (src_ofs / 8 + 1);
1068     src_ofs %= 8;
1069
1070     dst += dst_len - (dst_ofs / 8 + 1);
1071     dst_ofs %= 8;
1072
1073     if (src_ofs == 0 && dst_ofs == 0) {
1074         unsigned int n_bytes = n_bits / 8;
1075         if (n_bytes) {
1076             dst -= n_bytes - 1;
1077             src -= n_bytes - 1;
1078             memcpy(dst, src, n_bytes);
1079
1080             n_bits %= 8;
1081             src--;
1082             dst--;
1083         }
1084         if (n_bits) {
1085             uint8_t mask = (1 << n_bits) - 1;
1086             *dst = (*dst & ~mask) | (*src & mask);
1087         }
1088     } else {
1089         while (n_bits > 0) {
1090             unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
1091             unsigned int chunk = MIN(n_bits, max_copy);
1092             uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1093
1094             *dst &= ~mask;
1095             *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1096
1097             src_ofs += chunk;
1098             if (src_ofs == 8) {
1099                 src--;
1100                 src_ofs = 0;
1101             }
1102             dst_ofs += chunk;
1103             if (dst_ofs == 8) {
1104                 dst--;
1105                 dst_ofs = 0;
1106             }
1107             n_bits -= chunk;
1108         }
1109     }
1110 }
1111
1112 /* Returns the value of the NXM field corresponding to 'header' at 'ofs_nbits'
1113  * in 'flow'. */
1114 uint64_t
1115 nxm_read_field_bits(ovs_be32 header, ovs_be16 ofs_nbits,
1116                     const struct flow *flow)
1117 {
1118     const struct mf_field *field = mf_from_nxm_header(ntohl(header));
1119     union mf_value value;
1120     union mf_value bits;
1121
1122     mf_get_value(field, flow, &value);
1123     bits.be64 = htonll(0);
1124     bitwise_copy(&value, field->n_bytes, nxm_decode_ofs(ofs_nbits),
1125                  &bits, sizeof bits.be64, 0,
1126                  nxm_decode_n_bits(ofs_nbits));
1127     return ntohll(bits.be64);
1128 }
1129
1130 void
1131 nxm_execute_reg_move(const struct nx_action_reg_move *action,
1132                      struct flow *flow)
1133 {
1134     const struct mf_field *src = mf_from_nxm_header(ntohl(action->src));
1135     const struct mf_field *dst = mf_from_nxm_header(ntohl(action->dst));
1136     union mf_value src_value;
1137     union mf_value dst_value;
1138
1139     mf_get_value(dst, flow, &dst_value);
1140     mf_get_value(src, flow, &src_value);
1141     bitwise_copy(&src_value, src->n_bytes, ntohs(action->src_ofs),
1142                  &dst_value, dst->n_bytes, ntohs(action->dst_ofs),
1143                  ntohs(action->n_bits));
1144     mf_set_flow_value(dst, &dst_value, flow);
1145 }
1146
1147 void
1148 nxm_execute_reg_load(const struct nx_action_reg_load *action,
1149                      struct flow *flow)
1150 {
1151     nxm_reg_load(action->dst, action->ofs_nbits, ntohll(action->value), flow);
1152 }
1153
1154 /* Calculates ofs and n_bits from the given 'ofs_nbits' parameter, and copies
1155  * 'src_data'[0:n_bits] to 'dst_header'[ofs:ofs+n_bits] in the given 'flow'. */
1156 void
1157 nxm_reg_load(ovs_be32 dst_header, ovs_be16 ofs_nbits, uint64_t src_data,
1158              struct flow *flow)
1159 {
1160     const struct mf_field *dst = mf_from_nxm_header(ntohl(dst_header));
1161     int n_bits = nxm_decode_n_bits(ofs_nbits);
1162     int dst_ofs = nxm_decode_ofs(ofs_nbits);
1163     union mf_value dst_value;
1164     union mf_value src_value;
1165
1166     mf_get_value(dst, flow, &dst_value);
1167     src_value.be64 = htonll(src_data);
1168     bitwise_copy(&src_value, sizeof src_value.be64, 0,
1169                  &dst_value, dst->n_bytes, dst_ofs,
1170                  n_bits);
1171     mf_set_flow_value(dst, &dst_value, flow);
1172 }