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