util: Make hexits_value() support 64-bit integers too.
[cascardo/ovs.git] / lib / nx-match.c
1 /*
2  * Copyright (c) 2010, 2011, 2012, 2013, 2014 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 <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 "hmap.h"
26 #include "meta-flow.h"
27 #include "ofp-actions.h"
28 #include "ofp-errors.h"
29 #include "ofp-util.h"
30 #include "ofpbuf.h"
31 #include "openflow/nicira-ext.h"
32 #include "packets.h"
33 #include "shash.h"
34 #include "unaligned.h"
35 #include "util.h"
36 #include "vlog.h"
37
38 VLOG_DEFINE_THIS_MODULE(nx_match);
39
40 /*
41  * OXM Class IDs.
42  * The high order bit differentiate reserved classes from member classes.
43  * Classes 0x0000 to 0x7FFF are member classes, allocated by ONF.
44  * Classes 0x8000 to 0xFFFE are reserved classes, reserved for standardisation.
45  */
46 enum ofp12_oxm_class {
47     OFPXMC12_NXM_0          = 0x0000, /* Backward compatibility with NXM */
48     OFPXMC12_NXM_1          = 0x0001, /* Backward compatibility with NXM */
49     OFPXMC12_OPENFLOW_BASIC = 0x8000, /* Basic class for OpenFlow */
50     OFPXMC15_PACKET_REGS    = 0x8001, /* Packet registers (pipeline fields). */
51     OFPXMC12_EXPERIMENTER   = 0xffff, /* Experimenter class */
52 };
53
54 /* Functions for extracting fields from OXM/NXM headers. */
55 static int nxm_class(uint32_t header) { return header >> 16; }
56 static int nxm_field(uint32_t header) { return (header >> 9) & 0x7f; }
57 static bool nxm_hasmask(uint32_t header) { return (header & 0x100) != 0; }
58 static int nxm_length(uint32_t header) { return header & 0xff; }
59
60 /* Returns true if 'header' is a legacy NXM header, false if it is an OXM
61  * header.*/
62 static bool
63 is_nxm_header(uint32_t header)
64 {
65     return nxm_class(header) <= 1;
66 }
67
68 #define NXM_HEADER(CLASS, FIELD, HASMASK, LENGTH)                       \
69     (((CLASS) << 16) | ((FIELD) << 9) | ((HASMASK) << 8) | (LENGTH))
70
71 #define NXM_HEADER_FMT "%d:%d:%d:%d"
72 #define NXM_HEADER_ARGS(HEADER)                 \
73     nxm_class(HEADER), nxm_field(HEADER),      \
74     nxm_hasmask(HEADER), nxm_length(HEADER)
75
76 /* Functions for turning the "hasmask" bit on or off.  (This also requires
77  * adjusting the length.) */
78 static uint32_t
79 nxm_make_exact_header(uint32_t header)
80 {
81     return NXM_HEADER(nxm_class(header), nxm_field(header), 0,
82                       nxm_length(header) / 2);
83 }
84 static uint32_t
85 nxm_make_wild_header(uint32_t header)
86 {
87     return NXM_HEADER(nxm_class(header), nxm_field(header), 1,
88                       nxm_length(header) * 2);
89 }
90
91 /* Flow cookie.
92  *
93  * This may be used to gain the OpenFlow 1.1-like ability to restrict
94  * certain NXM-based Flow Mod and Flow Stats Request messages to flows
95  * with specific cookies.  See the "nx_flow_mod" and "nx_flow_stats_request"
96  * structure definitions for more details.  This match is otherwise not
97  * allowed. */
98 #define NXM_NX_COOKIE     NXM_HEADER  (0x0001, 30, 0, 8)
99 #define NXM_NX_COOKIE_W   nxm_make_wild_header(NXM_NX_COOKIE)
100
101 struct nxm_field {
102     uint32_t header;
103     enum ofp_version version;
104     const char *name;           /* e.g. "NXM_OF_IN_PORT". */
105
106     enum mf_field_id id;
107 };
108
109 static const struct nxm_field *nxm_field_by_header(uint32_t header);
110 static const struct nxm_field *nxm_field_by_name(const char *name, size_t len);
111 static const struct nxm_field *nxm_field_by_mf_id(enum mf_field_id);
112 static const struct nxm_field *oxm_field_by_mf_id(enum mf_field_id);
113
114 static void nx_put_header__(struct ofpbuf *, uint32_t header, bool masked);
115
116 /* Rate limit for nx_match parse errors.  These always indicate a bug in the
117  * peer and so there's not much point in showing a lot of them. */
118 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
119
120 static const struct nxm_field *
121 mf_parse_subfield_name(const char *name, int name_len, bool *wild);
122
123 static const struct nxm_field *
124 nxm_field_from_mf_field(enum mf_field_id id, enum ofp_version version)
125 {
126     const struct nxm_field *oxm = oxm_field_by_mf_id(id);
127     const struct nxm_field *nxm = nxm_field_by_mf_id(id);
128     return oxm && (version >= oxm->version || !nxm) ? oxm : nxm;
129 }
130
131 /* Returns the preferred OXM header to use for field 'id' in OpenFlow version
132  * 'version'.  Specify 0 for 'version' if an NXM legacy header should be
133  * preferred over any standardized OXM header.  Returns 0 if field 'id' cannot
134  * be expressed in NXM or OXM. */
135 uint32_t
136 mf_oxm_header(enum mf_field_id id, enum ofp_version version)
137 {
138     const struct nxm_field *f = nxm_field_from_mf_field(id, version);
139     return f ? f->header : 0;
140 }
141
142 /* Returns the "struct mf_field" that corresponds to NXM or OXM header
143  * 'header', or NULL if 'header' doesn't correspond to any known field.  */
144 const struct mf_field *
145 mf_from_nxm_header(uint32_t header)
146 {
147     const struct nxm_field *f = nxm_field_by_header(header);
148     return f ? mf_from_id(f->id) : NULL;
149 }
150
151 /* Returns the width of the data for a field with the given 'header', in
152  * bytes. */
153 static int
154 nxm_field_bytes(uint32_t header)
155 {
156     unsigned int length = nxm_length(header);
157     return nxm_hasmask(header) ? length / 2 : length;
158 }
159
160 /* Returns the earliest version of OpenFlow that standardized an OXM header for
161  * field 'id', or UINT8_MAX if no version of OpenFlow does. */
162 static enum ofp_version
163 mf_oxm_version(enum mf_field_id id)
164 {
165     const struct nxm_field *oxm = oxm_field_by_mf_id(id);
166     return oxm ? oxm->version : UINT8_MAX;
167 }
168  \f
169 /* nx_pull_match() and helpers. */
170
171 /* Given NXM/OXM value 'value' and mask 'mask' associated with 'header', checks
172  * for any 1-bit in the value where there is a 0-bit in the mask.  Returns 0 if
173  * none, otherwise an error code. */
174 static bool
175 is_mask_consistent(uint32_t header, const uint8_t *value, const uint8_t *mask)
176 {
177     unsigned int width = nxm_field_bytes(header);
178     unsigned int i;
179
180     for (i = 0; i < width; i++) {
181         if (value[i] & ~mask[i]) {
182             if (!VLOG_DROP_WARN(&rl)) {
183                 VLOG_WARN_RL(&rl, "Rejecting NXM/OXM entry "NXM_HEADER_FMT " "
184                              "with 1-bits in value for bits wildcarded by the "
185                              "mask.", NXM_HEADER_ARGS(header));
186             }
187             return false;
188         }
189     }
190     return true;
191 }
192
193 static bool
194 is_cookie_pseudoheader(uint32_t header)
195 {
196     return header == NXM_NX_COOKIE || header == NXM_NX_COOKIE_W;
197 }
198
199 static enum ofperr
200 nx_pull_header__(struct ofpbuf *b, bool allow_cookie, uint32_t *header,
201                  const struct mf_field **field)
202 {
203     if (ofpbuf_size(b) < 4) {
204         VLOG_DBG_RL(&rl, "encountered partial (%"PRIu32"-byte) OXM entry",
205                     ofpbuf_size(b));
206         goto error;
207     }
208     *header = ntohl(get_unaligned_be32(ofpbuf_pull(b, 4)));
209     if (nxm_length(*header) == 0) {
210         VLOG_WARN_RL(&rl, "OXM header "NXM_HEADER_FMT" has zero length",
211                      NXM_HEADER_ARGS(*header));
212         goto error;
213     }
214     if (field) {
215         *field = mf_from_nxm_header(*header);
216         if (!*field && !(allow_cookie && is_cookie_pseudoheader(*header))) {
217             VLOG_DBG_RL(&rl, "OXM header "NXM_HEADER_FMT" is unknown",
218                         NXM_HEADER_ARGS(*header));
219             return OFPERR_OFPBMC_BAD_FIELD;
220         }
221     }
222
223     return 0;
224
225 error:
226     *header = 0;
227     *field = NULL;
228     return OFPERR_OFPBMC_BAD_LEN;
229 }
230
231 static enum ofperr
232 nx_pull_entry__(struct ofpbuf *b, bool allow_cookie, uint32_t *header,
233                 const struct mf_field **field,
234                 union mf_value *value, union mf_value *mask)
235 {
236     enum ofperr header_error;
237     unsigned int payload_len;
238     const uint8_t *payload;
239     int width;
240
241     header_error = nx_pull_header__(b, allow_cookie, header, field);
242     if (header_error && header_error != OFPERR_OFPBMC_BAD_FIELD) {
243         return header_error;
244     }
245
246     payload_len = nxm_length(*header);
247     payload = ofpbuf_try_pull(b, payload_len);
248     if (!payload) {
249         VLOG_DBG_RL(&rl, "OXM header "NXM_HEADER_FMT" calls for %u-byte "
250                     "payload but only %"PRIu32" bytes follow OXM header",
251                     NXM_HEADER_ARGS(*header), payload_len, ofpbuf_size(b));
252         return OFPERR_OFPBMC_BAD_LEN;
253     }
254
255     width = nxm_field_bytes(*header);
256     if (nxm_hasmask(*header)
257         && !is_mask_consistent(*header, payload, payload + width)) {
258         return OFPERR_OFPBMC_BAD_WILDCARDS;
259     }
260
261     memcpy(value, payload, MIN(width, sizeof *value));
262     if (mask) {
263         if (nxm_hasmask(*header)) {
264             memcpy(mask, payload + width, MIN(width, sizeof *mask));
265         } else {
266             memset(mask, 0xff, MIN(width, sizeof *mask));
267         }
268     } else if (nxm_hasmask(*header)) {
269         VLOG_DBG_RL(&rl, "OXM header "NXM_HEADER_FMT" includes mask but "
270                     "masked OXMs are not allowed here",
271                     NXM_HEADER_ARGS(*header));
272         return OFPERR_OFPBMC_BAD_MASK;
273     }
274
275     return header_error;
276 }
277
278 /* Attempts to pull an NXM or OXM header, value, and mask (if present) from the
279  * beginning of 'b'.  If successful, stores a pointer to the "struct mf_field"
280  * corresponding to the pulled header in '*field', the value into '*value',
281  * and the mask into '*mask', and returns 0.  On error, returns an OpenFlow
282  * error; in this case, some bytes might have been pulled off 'b' anyhow, and
283  * the output parameters might have been modified.
284  *
285  * If a NULL 'mask' is supplied, masked OXM or NXM entries are treated as
286  * errors (with OFPERR_OFPBMC_BAD_MASK).
287  */
288 enum ofperr
289 nx_pull_entry(struct ofpbuf *b, const struct mf_field **field,
290               union mf_value *value, union mf_value *mask)
291 {
292     uint32_t header;
293
294     return nx_pull_entry__(b, false, &header, field, value, mask);
295 }
296
297 /* Attempts to pull an NXM or OXM header from the beginning of 'b'.  If
298  * successful, stores a pointer to the "struct mf_field" corresponding to the
299  * pulled header in '*field', stores the header's hasmask bit in '*masked'
300  * (true if hasmask=1, false if hasmask=0), and returns 0.  On error, returns
301  * an OpenFlow error; in this case, some bytes might have been pulled off 'b'
302  * anyhow, and the output parameters might have been modified.
303  *
304  * If NULL 'masked' is supplied, masked OXM or NXM headers are treated as
305  * errors (with OFPERR_OFPBMC_BAD_MASK).
306  */
307 enum ofperr
308 nx_pull_header(struct ofpbuf *b, const struct mf_field **field, bool *masked)
309 {
310     enum ofperr error;
311     uint32_t header;
312
313     error = nx_pull_header__(b, false, &header, field);
314     if (masked) {
315         *masked = !error && nxm_hasmask(header);
316     } else if (!error && nxm_hasmask(header)) {
317         error = OFPERR_OFPBMC_BAD_MASK;
318     }
319     return error;
320 }
321
322 static enum ofperr
323 nx_pull_match_entry(struct ofpbuf *b, bool allow_cookie,
324                     const struct mf_field **field,
325                     union mf_value *value, union mf_value *mask)
326 {
327     enum ofperr error;
328     uint32_t header;
329
330     error = nx_pull_entry__(b, allow_cookie, &header, field, value, mask);
331     if (error) {
332         return error;
333     }
334     if (field && *field) {
335         if (!mf_is_mask_valid(*field, mask)) {
336             VLOG_DBG_RL(&rl, "bad mask for field %s", (*field)->name);
337             return OFPERR_OFPBMC_BAD_MASK;
338         }
339         if (!mf_is_value_valid(*field, value)) {
340             VLOG_DBG_RL(&rl, "bad value for field %s", (*field)->name);
341             return OFPERR_OFPBMC_BAD_VALUE;
342         }
343     }
344     return 0;
345 }
346
347 static enum ofperr
348 nx_pull_raw(const uint8_t *p, unsigned int match_len, bool strict,
349             struct match *match, ovs_be64 *cookie, ovs_be64 *cookie_mask)
350 {
351     struct ofpbuf b;
352
353     ovs_assert((cookie != NULL) == (cookie_mask != NULL));
354
355     match_init_catchall(match);
356     if (cookie) {
357         *cookie = *cookie_mask = htonll(0);
358     }
359
360     ofpbuf_use_const(&b, p, match_len);
361     while (ofpbuf_size(&b)) {
362         const uint8_t *pos = ofpbuf_data(&b);
363         const struct mf_field *field;
364         union mf_value value;
365         union mf_value mask;
366         enum ofperr error;
367
368         error = nx_pull_match_entry(&b, cookie != NULL, &field, &value, &mask);
369         if (error) {
370             if (error == OFPERR_OFPBMC_BAD_FIELD && !strict) {
371                 continue;
372             }
373         } else if (!field) {
374             if (!cookie) {
375                 error = OFPERR_OFPBMC_BAD_FIELD;
376             } else if (*cookie_mask) {
377                 error = OFPERR_OFPBMC_DUP_FIELD;
378             } else {
379                 *cookie = value.be64;
380                 *cookie_mask = mask.be64;
381             }
382         } else if (!mf_are_prereqs_ok(field, &match->flow)) {
383             error = OFPERR_OFPBMC_BAD_PREREQ;
384         } else if (!mf_is_all_wild(field, &match->wc)) {
385             error = OFPERR_OFPBMC_DUP_FIELD;
386         } else {
387             mf_set(field, &value, &mask, match);
388         }
389
390         if (error) {
391             VLOG_DBG_RL(&rl, "error parsing OXM at offset %"PRIdPTR" "
392                         "within match (%s)", pos -
393                         p, ofperr_to_string(error));
394             return error;
395         }
396     }
397
398     return 0;
399 }
400
401 static enum ofperr
402 nx_pull_match__(struct ofpbuf *b, unsigned int match_len, bool strict,
403                 struct match *match,
404                 ovs_be64 *cookie, ovs_be64 *cookie_mask)
405 {
406     uint8_t *p = NULL;
407
408     if (match_len) {
409         p = ofpbuf_try_pull(b, ROUND_UP(match_len, 8));
410         if (!p) {
411             VLOG_DBG_RL(&rl, "nx_match length %u, rounded up to a "
412                         "multiple of 8, is longer than space in message (max "
413                         "length %"PRIu32")", match_len, ofpbuf_size(b));
414             return OFPERR_OFPBMC_BAD_LEN;
415         }
416     }
417
418     return nx_pull_raw(p, match_len, strict, match, cookie, cookie_mask);
419 }
420
421 /* Parses the nx_match formatted match description in 'b' with length
422  * 'match_len'.  Stores the results in 'match'.  If 'cookie' and 'cookie_mask'
423  * are valid pointers, then stores the cookie and mask in them if 'b' contains
424  * a "NXM_NX_COOKIE*" match.  Otherwise, stores 0 in both.
425  *
426  * Fails with an error upon encountering an unknown NXM header.
427  *
428  * Returns 0 if successful, otherwise an OpenFlow error code. */
429 enum ofperr
430 nx_pull_match(struct ofpbuf *b, unsigned int match_len, struct match *match,
431               ovs_be64 *cookie, ovs_be64 *cookie_mask)
432 {
433     return nx_pull_match__(b, match_len, true, match, cookie, cookie_mask);
434 }
435
436 /* Behaves the same as nx_pull_match(), but skips over unknown NXM headers,
437  * instead of failing with an error. */
438 enum ofperr
439 nx_pull_match_loose(struct ofpbuf *b, unsigned int match_len,
440                     struct match *match,
441                     ovs_be64 *cookie, ovs_be64 *cookie_mask)
442 {
443     return nx_pull_match__(b, match_len, false, match, cookie, cookie_mask);
444 }
445
446 static enum ofperr
447 oxm_pull_match__(struct ofpbuf *b, bool strict, struct match *match)
448 {
449     struct ofp11_match_header *omh = ofpbuf_data(b);
450     uint8_t *p;
451     uint16_t match_len;
452
453     if (ofpbuf_size(b) < sizeof *omh) {
454         return OFPERR_OFPBMC_BAD_LEN;
455     }
456
457     match_len = ntohs(omh->length);
458     if (match_len < sizeof *omh) {
459         return OFPERR_OFPBMC_BAD_LEN;
460     }
461
462     if (omh->type != htons(OFPMT_OXM)) {
463         return OFPERR_OFPBMC_BAD_TYPE;
464     }
465
466     p = ofpbuf_try_pull(b, ROUND_UP(match_len, 8));
467     if (!p) {
468         VLOG_DBG_RL(&rl, "oxm length %u, rounded up to a "
469                     "multiple of 8, is longer than space in message (max "
470                     "length %"PRIu32")", match_len, ofpbuf_size(b));
471         return OFPERR_OFPBMC_BAD_LEN;
472     }
473
474     return nx_pull_raw(p + sizeof *omh, match_len - sizeof *omh,
475                        strict, match, NULL, NULL);
476 }
477
478 /* Parses the oxm formatted match description preceded by a struct
479  * ofp11_match_header in 'b'.  Stores the result in 'match'.
480  *
481  * Fails with an error when encountering unknown OXM headers.
482  *
483  * Returns 0 if successful, otherwise an OpenFlow error code. */
484 enum ofperr
485 oxm_pull_match(struct ofpbuf *b, struct match *match)
486 {
487     return oxm_pull_match__(b, true, match);
488 }
489
490 /* Behaves the same as oxm_pull_match() with one exception.  Skips over unknown
491  * OXM headers instead of failing with an error when they are encountered. */
492 enum ofperr
493 oxm_pull_match_loose(struct ofpbuf *b, struct match *match)
494 {
495     return oxm_pull_match__(b, false, match);
496 }
497 \f
498 /* nx_put_match() and helpers.
499  *
500  * 'put' functions whose names end in 'w' add a wildcarded field.
501  * 'put' functions whose names end in 'm' add a field that might be wildcarded.
502  * Other 'put' functions add exact-match fields.
503  */
504
505 static void
506 nxm_put_unmasked(struct ofpbuf *b, enum mf_field_id field,
507                  enum ofp_version version, const void *value, size_t n_bytes)
508 {
509     nx_put_header(b, field, version, false);
510     ofpbuf_put(b, value, n_bytes);
511 }
512
513 static void
514 nxm_put(struct ofpbuf *b, enum mf_field_id field, enum ofp_version version,
515         const void *value, const void *mask, size_t n_bytes)
516 {
517     if (!is_all_zeros(mask, n_bytes)) {
518         bool masked = !is_all_ones(mask, n_bytes);
519         nx_put_header(b, field, version, masked);
520         ofpbuf_put(b, value, n_bytes);
521         if (masked) {
522             ofpbuf_put(b, mask, n_bytes);
523         }
524     }
525 }
526
527 static void
528 nxm_put_8m(struct ofpbuf *b, enum mf_field_id field, enum ofp_version version,
529            uint8_t value, uint8_t mask)
530 {
531     nxm_put(b, field, version, &value, &mask, sizeof value);
532 }
533
534 static void
535 nxm_put_8(struct ofpbuf *b, enum mf_field_id field, enum ofp_version version,
536           uint8_t value)
537 {
538     nxm_put_unmasked(b, field, version, &value, sizeof value);
539 }
540
541 static void
542 nxm_put_16m(struct ofpbuf *b, enum mf_field_id field, enum ofp_version version,
543             ovs_be16 value, ovs_be16 mask)
544 {
545     nxm_put(b, field, version, &value, &mask, sizeof value);
546 }
547
548 static void
549 nxm_put_16(struct ofpbuf *b, enum mf_field_id field, enum ofp_version version,
550            ovs_be16 value)
551 {
552     nxm_put_unmasked(b, field, version, &value, sizeof value);
553 }
554
555 static void
556 nxm_put_32m(struct ofpbuf *b, enum mf_field_id field, enum ofp_version version,
557             ovs_be32 value, ovs_be32 mask)
558 {
559     nxm_put(b, field, version, &value, &mask, sizeof value);
560 }
561
562 static void
563 nxm_put_32(struct ofpbuf *b, enum mf_field_id field, enum ofp_version version,
564            ovs_be32 value)
565 {
566     nxm_put_unmasked(b, field, version, &value, sizeof value);
567 }
568
569 static void
570 nxm_put_64m(struct ofpbuf *b, enum mf_field_id field, enum ofp_version version,
571             ovs_be64 value, ovs_be64 mask)
572 {
573     nxm_put(b, field, version, &value, &mask, sizeof value);
574 }
575
576 static void
577 nxm_put_eth_masked(struct ofpbuf *b,
578                    enum mf_field_id field, enum ofp_version version,
579                    const uint8_t value[ETH_ADDR_LEN],
580                    const uint8_t mask[ETH_ADDR_LEN])
581 {
582     nxm_put(b, field, version, value, mask, ETH_ADDR_LEN);
583 }
584
585 static void
586 nxm_put_ipv6(struct ofpbuf *b,
587              enum mf_field_id field, enum ofp_version version,
588              const struct in6_addr *value, const struct in6_addr *mask)
589 {
590     nxm_put(b, field, version, value->s6_addr, mask->s6_addr,
591             sizeof value->s6_addr);
592 }
593
594 static void
595 nxm_put_frag(struct ofpbuf *b, const struct match *match,
596              enum ofp_version version)
597 {
598     uint8_t nw_frag = match->flow.nw_frag & FLOW_NW_FRAG_MASK;
599     uint8_t nw_frag_mask = match->wc.masks.nw_frag & FLOW_NW_FRAG_MASK;
600
601     nxm_put_8m(b, MFF_IP_FRAG, version, nw_frag,
602                nw_frag_mask == FLOW_NW_FRAG_MASK ? UINT8_MAX : nw_frag_mask);
603 }
604
605 /* Appends to 'b' a set of OXM or NXM matches for the IPv4 or IPv6 fields in
606  * 'match'.  */
607 static void
608 nxm_put_ip(struct ofpbuf *b, const struct match *match, enum ofp_version oxm)
609 {
610     const struct flow *flow = &match->flow;
611
612     if (flow->dl_type == htons(ETH_TYPE_IP)) {
613         nxm_put_32m(b, MFF_IPV4_SRC, oxm,
614                     flow->nw_src, match->wc.masks.nw_src);
615         nxm_put_32m(b, MFF_IPV4_DST, oxm,
616                     flow->nw_dst, match->wc.masks.nw_dst);
617     } else {
618         nxm_put_ipv6(b, MFF_IPV6_SRC, oxm,
619                      &flow->ipv6_src, &match->wc.masks.ipv6_src);
620         nxm_put_ipv6(b, MFF_IPV6_DST, oxm,
621                      &flow->ipv6_dst, &match->wc.masks.ipv6_dst);
622     }
623
624     nxm_put_frag(b, match, oxm);
625
626     if (match->wc.masks.nw_tos & IP_DSCP_MASK) {
627         if (oxm) {
628             nxm_put_8(b, MFF_IP_DSCP_SHIFTED, oxm,
629                       flow->nw_tos >> 2);
630         } else {
631             nxm_put_8(b, MFF_IP_DSCP, oxm,
632                       flow->nw_tos & IP_DSCP_MASK);
633         }
634     }
635
636     if (match->wc.masks.nw_tos & IP_ECN_MASK) {
637         nxm_put_8(b, MFF_IP_ECN, oxm,
638                   flow->nw_tos & IP_ECN_MASK);
639     }
640
641     if (!oxm && match->wc.masks.nw_ttl) {
642         nxm_put_8(b, MFF_IP_TTL, oxm, flow->nw_ttl);
643     }
644
645     nxm_put_32m(b, MFF_IPV6_LABEL, oxm,
646                 flow->ipv6_label, match->wc.masks.ipv6_label);
647
648     if (match->wc.masks.nw_proto) {
649         nxm_put_8(b, MFF_IP_PROTO, oxm, flow->nw_proto);
650
651         if (flow->nw_proto == IPPROTO_TCP) {
652             nxm_put_16m(b, MFF_TCP_SRC, oxm,
653                         flow->tp_src, match->wc.masks.tp_src);
654             nxm_put_16m(b, MFF_TCP_DST, oxm,
655                         flow->tp_dst, match->wc.masks.tp_dst);
656             nxm_put_16m(b, MFF_TCP_FLAGS, oxm,
657                         flow->tcp_flags, match->wc.masks.tcp_flags);
658         } else if (flow->nw_proto == IPPROTO_UDP) {
659             nxm_put_16m(b, MFF_UDP_SRC, oxm,
660                         flow->tp_src, match->wc.masks.tp_src);
661             nxm_put_16m(b, MFF_UDP_DST, oxm,
662                         flow->tp_dst, match->wc.masks.tp_dst);
663         } else if (flow->nw_proto == IPPROTO_SCTP) {
664             nxm_put_16m(b, MFF_SCTP_SRC, oxm, flow->tp_src,
665                         match->wc.masks.tp_src);
666             nxm_put_16m(b, MFF_SCTP_DST, oxm, flow->tp_dst,
667                         match->wc.masks.tp_dst);
668         } else if (is_icmpv4(flow)) {
669             if (match->wc.masks.tp_src) {
670                 nxm_put_8(b, MFF_ICMPV4_TYPE, oxm,
671                           ntohs(flow->tp_src));
672             }
673             if (match->wc.masks.tp_dst) {
674                 nxm_put_8(b, MFF_ICMPV4_CODE, oxm,
675                           ntohs(flow->tp_dst));
676             }
677         } else if (is_icmpv6(flow)) {
678             if (match->wc.masks.tp_src) {
679                 nxm_put_8(b, MFF_ICMPV6_TYPE, oxm,
680                           ntohs(flow->tp_src));
681             }
682             if (match->wc.masks.tp_dst) {
683                 nxm_put_8(b, MFF_ICMPV6_CODE, oxm,
684                           ntohs(flow->tp_dst));
685             }
686             if (flow->tp_src == htons(ND_NEIGHBOR_SOLICIT) ||
687                 flow->tp_src == htons(ND_NEIGHBOR_ADVERT)) {
688                 nxm_put_ipv6(b, MFF_ND_TARGET, oxm,
689                              &flow->nd_target, &match->wc.masks.nd_target);
690                 if (flow->tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
691                     nxm_put_eth_masked(b, MFF_ND_SLL, oxm,
692                                        flow->arp_sha, match->wc.masks.arp_sha);
693                 }
694                 if (flow->tp_src == htons(ND_NEIGHBOR_ADVERT)) {
695                     nxm_put_eth_masked(b, MFF_ND_TLL, oxm,
696                                        flow->arp_tha, match->wc.masks.arp_tha);
697                 }
698             }
699         }
700     }
701 }
702
703 /* Appends to 'b' the nx_match format that expresses 'match'.  For Flow Mod and
704  * Flow Stats Requests messages, a 'cookie' and 'cookie_mask' may be supplied.
705  * Otherwise, 'cookie_mask' should be zero.
706  *
707  * Specify 'oxm' as 0 to express the match in NXM format; otherwise, specify
708  * 'oxm' as the OpenFlow version number for the OXM format to use.
709  *
710  * This function can cause 'b''s data to be reallocated.
711  *
712  * Returns the number of bytes appended to 'b', excluding padding.
713  *
714  * If 'match' is a catch-all rule that matches every packet, then this function
715  * appends nothing to 'b' and returns 0. */
716 static int
717 nx_put_raw(struct ofpbuf *b, enum ofp_version oxm, const struct match *match,
718            ovs_be64 cookie, ovs_be64 cookie_mask)
719 {
720     const struct flow *flow = &match->flow;
721     const size_t start_len = ofpbuf_size(b);
722     int match_len;
723     int i;
724
725     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 27);
726
727     /* Metadata. */
728     if (match->wc.masks.dp_hash) {
729         nxm_put_32m(b, MFF_DP_HASH, oxm,
730                     htonl(flow->dp_hash), htonl(match->wc.masks.dp_hash));
731     }
732
733     if (match->wc.masks.recirc_id) {
734         nxm_put_32(b, MFF_RECIRC_ID, oxm, htonl(flow->recirc_id));
735     }
736
737     if (match->wc.masks.in_port.ofp_port) {
738         ofp_port_t in_port = flow->in_port.ofp_port;
739         if (oxm) {
740             nxm_put_32(b, MFF_IN_PORT_OXM, oxm,
741                        ofputil_port_to_ofp11(in_port));
742         } else {
743             nxm_put_16(b, MFF_IN_PORT, oxm,
744                        htons(ofp_to_u16(in_port)));
745         }
746     }
747
748     /* Ethernet. */
749     nxm_put_eth_masked(b, MFF_ETH_SRC, oxm,
750                        flow->dl_src, match->wc.masks.dl_src);
751     nxm_put_eth_masked(b, MFF_ETH_DST, oxm,
752                        flow->dl_dst, match->wc.masks.dl_dst);
753     nxm_put_16m(b, MFF_ETH_TYPE, oxm,
754                 ofputil_dl_type_to_openflow(flow->dl_type),
755                 match->wc.masks.dl_type);
756
757     /* 802.1Q. */
758     if (oxm) {
759         ovs_be16 VID_CFI_MASK = htons(VLAN_VID_MASK | VLAN_CFI);
760         ovs_be16 vid = flow->vlan_tci & VID_CFI_MASK;
761         ovs_be16 mask = match->wc.masks.vlan_tci & VID_CFI_MASK;
762
763         if (mask == htons(VLAN_VID_MASK | VLAN_CFI)) {
764             nxm_put_16(b, MFF_VLAN_VID, oxm, vid);
765         } else if (mask) {
766             nxm_put_16m(b, MFF_VLAN_VID, oxm, vid, mask);
767         }
768
769         if (vid && vlan_tci_to_pcp(match->wc.masks.vlan_tci)) {
770             nxm_put_8(b, MFF_VLAN_PCP, oxm,
771                       vlan_tci_to_pcp(flow->vlan_tci));
772         }
773
774     } else {
775         nxm_put_16m(b, MFF_VLAN_TCI, oxm, flow->vlan_tci,
776                     match->wc.masks.vlan_tci);
777     }
778
779     /* MPLS. */
780     if (eth_type_mpls(flow->dl_type)) {
781         if (match->wc.masks.mpls_lse[0] & htonl(MPLS_TC_MASK)) {
782             nxm_put_8(b, MFF_MPLS_TC, oxm,
783                       mpls_lse_to_tc(flow->mpls_lse[0]));
784         }
785
786         if (match->wc.masks.mpls_lse[0] & htonl(MPLS_BOS_MASK)) {
787             nxm_put_8(b, MFF_MPLS_BOS, oxm,
788                       mpls_lse_to_bos(flow->mpls_lse[0]));
789         }
790
791         if (match->wc.masks.mpls_lse[0] & htonl(MPLS_LABEL_MASK)) {
792             nxm_put_32(b, MFF_MPLS_LABEL, oxm,
793                        htonl(mpls_lse_to_label(flow->mpls_lse[0])));
794         }
795     }
796
797     /* L3. */
798     if (is_ip_any(flow)) {
799         nxm_put_ip(b, match, oxm);
800     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
801                flow->dl_type == htons(ETH_TYPE_RARP)) {
802         /* ARP. */
803         if (match->wc.masks.nw_proto) {
804             nxm_put_16(b, MFF_ARP_OP, oxm,
805                        htons(flow->nw_proto));
806         }
807         nxm_put_32m(b, MFF_ARP_SPA, oxm,
808                     flow->nw_src, match->wc.masks.nw_src);
809         nxm_put_32m(b, MFF_ARP_TPA, oxm,
810                     flow->nw_dst, match->wc.masks.nw_dst);
811         nxm_put_eth_masked(b, MFF_ARP_SHA, oxm,
812                            flow->arp_sha, match->wc.masks.arp_sha);
813         nxm_put_eth_masked(b, MFF_ARP_THA, oxm,
814                            flow->arp_tha, match->wc.masks.arp_tha);
815     }
816
817     /* Tunnel ID. */
818     nxm_put_64m(b, MFF_TUN_ID, oxm,
819                 flow->tunnel.tun_id, match->wc.masks.tunnel.tun_id);
820
821     /* Other tunnel metadata. */
822     nxm_put_32m(b, MFF_TUN_SRC, oxm,
823                 flow->tunnel.ip_src, match->wc.masks.tunnel.ip_src);
824     nxm_put_32m(b, MFF_TUN_DST, oxm,
825                 flow->tunnel.ip_dst, match->wc.masks.tunnel.ip_dst);
826
827     /* Registers. */
828     if (oxm < OFP15_VERSION) {
829         for (i = 0; i < FLOW_N_REGS; i++) {
830             nxm_put_32m(b, MFF_REG0 + i, oxm,
831                         htonl(flow->regs[i]), htonl(match->wc.masks.regs[i]));
832         }
833     } else {
834         for (i = 0; i < FLOW_N_XREGS; i++) {
835             nxm_put_64m(b, MFF_XREG0 + i, oxm,
836                         htonll(flow_get_xreg(flow, i)),
837                         htonll(flow_get_xreg(&match->wc.masks, i)));
838         }
839     }
840
841     /* Mark. */
842     nxm_put_32m(b, MFF_PKT_MARK, oxm, htonl(flow->pkt_mark),
843                 htonl(match->wc.masks.pkt_mark));
844
845     /* OpenFlow 1.1+ Metadata. */
846     nxm_put_64m(b, MFF_METADATA, oxm,
847                 flow->metadata, match->wc.masks.metadata);
848
849     /* Cookie. */
850     if (cookie_mask) {
851         bool masked = cookie_mask != OVS_BE64_MAX;
852
853         cookie &= cookie_mask;
854         nx_put_header__(b, NXM_NX_COOKIE, masked);
855         ofpbuf_put(b, &cookie, sizeof cookie);
856         if (masked) {
857             ofpbuf_put(b, &cookie_mask, sizeof cookie_mask);
858         }
859     }
860
861     match_len = ofpbuf_size(b) - start_len;
862     return match_len;
863 }
864
865 /* Appends to 'b' the nx_match format that expresses 'match', plus enough zero
866  * bytes to pad the nx_match out to a multiple of 8.  For Flow Mod and Flow
867  * Stats Requests messages, a 'cookie' and 'cookie_mask' may be supplied.
868  * Otherwise, 'cookie_mask' should be zero.
869  *
870  * This function can cause 'b''s data to be reallocated.
871  *
872  * Returns the number of bytes appended to 'b', excluding padding.  The return
873  * value can be zero if it appended nothing at all to 'b' (which happens if
874  * 'cr' is a catch-all rule that matches every packet). */
875 int
876 nx_put_match(struct ofpbuf *b, const struct match *match,
877              ovs_be64 cookie, ovs_be64 cookie_mask)
878 {
879     int match_len = nx_put_raw(b, 0, match, cookie, cookie_mask);
880
881     ofpbuf_put_zeros(b, PAD_SIZE(match_len, 8));
882     return match_len;
883 }
884
885 /* Appends to 'b' an struct ofp11_match_header followed by the OXM format that
886  * expresses 'cr', plus enough zero bytes to pad the data appended out to a
887  * multiple of 8.
888  *
889  * OXM differs slightly among versions of OpenFlow.  Specify the OpenFlow
890  * version in use as 'version'.
891  *
892  * This function can cause 'b''s data to be reallocated.
893  *
894  * Returns the number of bytes appended to 'b', excluding the padding.  Never
895  * returns zero. */
896 int
897 oxm_put_match(struct ofpbuf *b, const struct match *match,
898               enum ofp_version version)
899 {
900     int match_len;
901     struct ofp11_match_header *omh;
902     size_t start_len = ofpbuf_size(b);
903     ovs_be64 cookie = htonll(0), cookie_mask = htonll(0);
904
905     ofpbuf_put_uninit(b, sizeof *omh);
906     match_len = (nx_put_raw(b, version, match, cookie, cookie_mask)
907                  + sizeof *omh);
908     ofpbuf_put_zeros(b, PAD_SIZE(match_len, 8));
909
910     omh = ofpbuf_at(b, start_len, sizeof *omh);
911     omh->type = htons(OFPMT_OXM);
912     omh->length = htons(match_len);
913
914     return match_len;
915 }
916
917 static void
918 nx_put_header__(struct ofpbuf *b, uint32_t header, bool masked)
919 {
920     uint32_t masked_header = masked ? nxm_make_wild_header(header) : header;
921     ovs_be32 network_header = htonl(masked_header);
922
923     ofpbuf_put(b, &network_header, sizeof network_header);
924 }
925
926 void
927 nx_put_header(struct ofpbuf *b, enum mf_field_id field,
928               enum ofp_version version, bool masked)
929 {
930     nx_put_header__(b, mf_oxm_header(field, version), masked);
931 }
932
933 void
934 nx_put_entry(struct ofpbuf *b,
935              enum mf_field_id field, enum ofp_version version,
936              const union mf_value *value, const union mf_value *mask)
937 {
938     int n_bytes = mf_from_id(field)->n_bytes;
939     bool masked = mask && !is_all_ones(mask, n_bytes);
940
941     nx_put_header(b, field, version, masked);
942     ofpbuf_put(b, value, n_bytes);
943     if (masked) {
944         ofpbuf_put(b, mask, n_bytes);
945     }
946 }
947 \f
948 /* nx_match_to_string() and helpers. */
949
950 static void format_nxm_field_name(struct ds *, uint32_t header);
951
952 char *
953 nx_match_to_string(const uint8_t *p, unsigned int match_len)
954 {
955     struct ofpbuf b;
956     struct ds s;
957
958     if (!match_len) {
959         return xstrdup("<any>");
960     }
961
962     ofpbuf_use_const(&b, p, match_len);
963     ds_init(&s);
964     while (ofpbuf_size(&b)) {
965         union mf_value value;
966         union mf_value mask;
967         enum ofperr error;
968         uint32_t header;
969         int value_len;
970
971         error = nx_pull_entry__(&b, true, &header, NULL, &value, &mask);
972         if (error) {
973             break;
974         }
975         value_len = MIN(sizeof value, nxm_field_bytes(header));
976
977         if (s.length) {
978             ds_put_cstr(&s, ", ");
979         }
980
981         format_nxm_field_name(&s, header);
982         ds_put_char(&s, '(');
983
984         for (int i = 0; i < value_len; i++) {
985             ds_put_format(&s, "%02x", ((const uint8_t *) &value)[i]);
986         }
987         if (nxm_hasmask(header)) {
988             ds_put_char(&s, '/');
989             for (int i = 0; i < value_len; i++) {
990                 ds_put_format(&s, "%02x", ((const uint8_t *) &mask)[i]);
991             }
992         }
993         ds_put_char(&s, ')');
994     }
995
996     if (ofpbuf_size(&b)) {
997         if (s.length) {
998             ds_put_cstr(&s, ", ");
999         }
1000
1001         ds_put_format(&s, "<%u invalid bytes>", ofpbuf_size(&b));
1002     }
1003
1004     return ds_steal_cstr(&s);
1005 }
1006
1007 char *
1008 oxm_match_to_string(const struct ofpbuf *p, unsigned int match_len)
1009 {
1010     const struct ofp11_match_header *omh = ofpbuf_data(p);
1011     uint16_t match_len_;
1012     struct ds s;
1013
1014     ds_init(&s);
1015
1016     if (match_len < sizeof *omh) {
1017         ds_put_format(&s, "<match too short: %u>", match_len);
1018         goto err;
1019     }
1020
1021     if (omh->type != htons(OFPMT_OXM)) {
1022         ds_put_format(&s, "<bad match type field: %u>", ntohs(omh->type));
1023         goto err;
1024     }
1025
1026     match_len_ = ntohs(omh->length);
1027     if (match_len_ < sizeof *omh) {
1028         ds_put_format(&s, "<match length field too short: %u>", match_len_);
1029         goto err;
1030     }
1031
1032     if (match_len_ != match_len) {
1033         ds_put_format(&s, "<match length field incorrect: %u != %u>",
1034                       match_len_, match_len);
1035         goto err;
1036     }
1037
1038     return nx_match_to_string(ofpbuf_at(p, sizeof *omh, 0),
1039                               match_len - sizeof *omh);
1040
1041 err:
1042     return ds_steal_cstr(&s);
1043 }
1044
1045 void
1046 nx_format_field_name(enum mf_field_id id, enum ofp_version version,
1047                      struct ds *s)
1048 {
1049     format_nxm_field_name(s, mf_oxm_header(id, version));
1050 }
1051
1052 static void
1053 format_nxm_field_name(struct ds *s, uint32_t header)
1054 {
1055     const struct nxm_field *f = nxm_field_by_header(header);
1056     if (f) {
1057         ds_put_cstr(s, f->name);
1058         if (nxm_hasmask(header)) {
1059             ds_put_cstr(s, "_W");
1060         }
1061     } else if (header == NXM_NX_COOKIE) {
1062         ds_put_cstr(s, "NXM_NX_COOKIE");
1063     } else if (header == NXM_NX_COOKIE_W) {
1064         ds_put_cstr(s, "NXM_NX_COOKIE_W");
1065     } else {
1066         ds_put_format(s, "%d:%d", nxm_class(header), nxm_field(header));
1067     }
1068 }
1069
1070 static bool
1071 streq_len(const char *a, size_t a_len, const char *b)
1072 {
1073     return strlen(b) == a_len && !memcmp(a, b, a_len);
1074 }
1075
1076 static uint32_t
1077 parse_nxm_field_name(const char *name, int name_len)
1078 {
1079     const struct nxm_field *f;
1080     bool wild;
1081
1082     f = mf_parse_subfield_name(name, name_len, &wild);
1083     if (f) {
1084         if (!wild) {
1085             return f->header;
1086         } else if (mf_from_id(f->id)->maskable != MFM_NONE) {
1087             return nxm_make_wild_header(f->header);
1088         }
1089     }
1090
1091     if (streq_len(name, name_len, "NXM_NX_COOKIE")) {
1092         return NXM_NX_COOKIE;
1093     } else if (streq_len(name, name_len, "NXM_NX_COOKIE_W")) {
1094         return NXM_NX_COOKIE_W;
1095     }
1096
1097     /* Check whether it's a 32-bit field header value as hex.
1098      * (This isn't ordinarily useful except for testing error behavior.) */
1099     if (name_len == 8) {
1100         uint32_t header;
1101         bool ok;
1102
1103         header = hexits_value(name, name_len, &ok);
1104         if (ok) {
1105             return header;
1106         }
1107     }
1108
1109     return 0;
1110 }
1111 \f
1112 /* nx_match_from_string(). */
1113
1114 static int
1115 nx_match_from_string_raw(const char *s, struct ofpbuf *b)
1116 {
1117     const char *full_s = s;
1118     const size_t start_len = ofpbuf_size(b);
1119
1120     if (!strcmp(s, "<any>")) {
1121         /* Ensure that 'ofpbuf_data(b)' isn't actually null. */
1122         ofpbuf_prealloc_tailroom(b, 1);
1123         return 0;
1124     }
1125
1126     for (s += strspn(s, ", "); *s; s += strspn(s, ", ")) {
1127         const char *name;
1128         uint32_t header;
1129         int name_len;
1130         size_t n;
1131
1132         name = s;
1133         name_len = strcspn(s, "(");
1134         if (s[name_len] != '(') {
1135             ovs_fatal(0, "%s: missing ( at end of nx_match", full_s);
1136         }
1137
1138         header = parse_nxm_field_name(name, name_len);
1139         if (!header) {
1140             ovs_fatal(0, "%s: unknown field `%.*s'", full_s, name_len, s);
1141         }
1142
1143         s += name_len + 1;
1144
1145         nx_put_header__(b, header, false);
1146         s = ofpbuf_put_hex(b, s, &n);
1147         if (n != nxm_field_bytes(header)) {
1148             ovs_fatal(0, "%.2s: hex digits expected", s);
1149         }
1150         if (nxm_hasmask(header)) {
1151             s += strspn(s, " ");
1152             if (*s != '/') {
1153                 ovs_fatal(0, "%s: missing / in masked field %.*s",
1154                           full_s, name_len, name);
1155             }
1156             s = ofpbuf_put_hex(b, s + 1, &n);
1157             if (n != nxm_field_bytes(header)) {
1158                 ovs_fatal(0, "%.2s: hex digits expected", s);
1159             }
1160         }
1161
1162         s += strspn(s, " ");
1163         if (*s != ')') {
1164             ovs_fatal(0, "%s: missing ) following field %.*s",
1165                       full_s, name_len, name);
1166         }
1167         s++;
1168     }
1169
1170     return ofpbuf_size(b) - start_len;
1171 }
1172
1173 int
1174 nx_match_from_string(const char *s, struct ofpbuf *b)
1175 {
1176     int match_len = nx_match_from_string_raw(s, b);
1177     ofpbuf_put_zeros(b, PAD_SIZE(match_len, 8));
1178     return match_len;
1179 }
1180
1181 int
1182 oxm_match_from_string(const char *s, struct ofpbuf *b)
1183 {
1184     int match_len;
1185     struct ofp11_match_header *omh;
1186     size_t start_len = ofpbuf_size(b);
1187
1188     ofpbuf_put_uninit(b, sizeof *omh);
1189     match_len = nx_match_from_string_raw(s, b) + sizeof *omh;
1190     ofpbuf_put_zeros(b, PAD_SIZE(match_len, 8));
1191
1192     omh = ofpbuf_at(b, start_len, sizeof *omh);
1193     omh->type = htons(OFPMT_OXM);
1194     omh->length = htons(match_len);
1195
1196     return match_len;
1197 }
1198 \f
1199 /* Parses 's' as a "move" action, in the form described in ovs-ofctl(8), into
1200  * '*move'.
1201  *
1202  * Returns NULL if successful, otherwise a malloc()'d string describing the
1203  * error.  The caller is responsible for freeing the returned string. */
1204 char * WARN_UNUSED_RESULT
1205 nxm_parse_reg_move(struct ofpact_reg_move *move, const char *s)
1206 {
1207     const char *full_s = s;
1208     char *error;
1209
1210     error = mf_parse_subfield__(&move->src, &s);
1211     if (error) {
1212         return error;
1213     }
1214     if (strncmp(s, "->", 2)) {
1215         return xasprintf("%s: missing `->' following source", full_s);
1216     }
1217     s += 2;
1218     error = mf_parse_subfield(&move->dst, s);
1219     if (error) {
1220         return error;
1221     }
1222
1223     if (move->src.n_bits != move->dst.n_bits) {
1224         return xasprintf("%s: source field is %d bits wide but destination is "
1225                          "%d bits wide", full_s,
1226                          move->src.n_bits, move->dst.n_bits);
1227     }
1228     return NULL;
1229 }
1230 \f
1231 /* nxm_format_reg_move(). */
1232
1233 void
1234 nxm_format_reg_move(const struct ofpact_reg_move *move, struct ds *s)
1235 {
1236     ds_put_format(s, "move:");
1237     mf_format_subfield(&move->src, s);
1238     ds_put_cstr(s, "->");
1239     mf_format_subfield(&move->dst, s);
1240 }
1241
1242 \f
1243 enum ofperr
1244 nxm_reg_move_check(const struct ofpact_reg_move *move, const struct flow *flow)
1245 {
1246     enum ofperr error;
1247
1248     error = mf_check_src(&move->src, flow);
1249     if (error) {
1250         return error;
1251     }
1252
1253     return mf_check_dst(&move->dst, NULL);
1254 }
1255 \f
1256 /* nxm_execute_reg_move(). */
1257
1258 void
1259 nxm_execute_reg_move(const struct ofpact_reg_move *move,
1260                      struct flow *flow, struct flow_wildcards *wc)
1261 {
1262     union mf_value src_value;
1263     union mf_value dst_value;
1264
1265     mf_mask_field_and_prereqs(move->dst.field, &wc->masks);
1266     mf_mask_field_and_prereqs(move->src.field, &wc->masks);
1267
1268     mf_get_value(move->dst.field, flow, &dst_value);
1269     mf_get_value(move->src.field, flow, &src_value);
1270     bitwise_copy(&src_value, move->src.field->n_bytes, move->src.ofs,
1271                  &dst_value, move->dst.field->n_bytes, move->dst.ofs,
1272                  move->src.n_bits);
1273     mf_set_flow_value(move->dst.field, &dst_value, flow);
1274 }
1275
1276 void
1277 nxm_reg_load(const struct mf_subfield *dst, uint64_t src_data,
1278              struct flow *flow, struct flow_wildcards *wc)
1279 {
1280     union mf_subvalue src_subvalue;
1281     union mf_subvalue mask_value;
1282     ovs_be64 src_data_be = htonll(src_data);
1283
1284     memset(&mask_value, 0xff, sizeof mask_value);
1285     mf_write_subfield_flow(dst, &mask_value, &wc->masks);
1286
1287     bitwise_copy(&src_data_be, sizeof src_data_be, 0,
1288                  &src_subvalue, sizeof src_subvalue, 0,
1289                  sizeof src_data_be * 8);
1290     mf_write_subfield_flow(dst, &src_subvalue, flow);
1291 }
1292 \f
1293 /* nxm_parse_stack_action, works for both push() and pop(). */
1294
1295 /* Parses 's' as a "push" or "pop" action, in the form described in
1296  * ovs-ofctl(8), into '*stack_action'.
1297  *
1298  * Returns NULL if successful, otherwise a malloc()'d string describing the
1299  * error.  The caller is responsible for freeing the returned string. */
1300 char * WARN_UNUSED_RESULT
1301 nxm_parse_stack_action(struct ofpact_stack *stack_action, const char *s)
1302 {
1303     char *error;
1304
1305     error = mf_parse_subfield__(&stack_action->subfield, &s);
1306     if (error) {
1307         return error;
1308     }
1309
1310     if (*s != '\0') {
1311         return xasprintf("%s: trailing garbage following push or pop", s);
1312     }
1313
1314     return NULL;
1315 }
1316
1317 void
1318 nxm_format_stack_push(const struct ofpact_stack *push, struct ds *s)
1319 {
1320     ds_put_cstr(s, "push:");
1321     mf_format_subfield(&push->subfield, s);
1322 }
1323
1324 void
1325 nxm_format_stack_pop(const struct ofpact_stack *pop, struct ds *s)
1326 {
1327     ds_put_cstr(s, "pop:");
1328     mf_format_subfield(&pop->subfield, s);
1329 }
1330
1331 enum ofperr
1332 nxm_stack_push_check(const struct ofpact_stack *push,
1333                      const struct flow *flow)
1334 {
1335     return mf_check_src(&push->subfield, flow);
1336 }
1337
1338 enum ofperr
1339 nxm_stack_pop_check(const struct ofpact_stack *pop,
1340                     const struct flow *flow)
1341 {
1342     return mf_check_dst(&pop->subfield, flow);
1343 }
1344
1345 /* nxm_execute_stack_push(), nxm_execute_stack_pop(). */
1346 static void
1347 nx_stack_push(struct ofpbuf *stack, union mf_subvalue *v)
1348 {
1349     ofpbuf_put(stack, v, sizeof *v);
1350 }
1351
1352 static union mf_subvalue *
1353 nx_stack_pop(struct ofpbuf *stack)
1354 {
1355     union mf_subvalue *v = NULL;
1356
1357     if (ofpbuf_size(stack)) {
1358
1359         ofpbuf_set_size(stack, ofpbuf_size(stack) - sizeof *v);
1360         v = (union mf_subvalue *) ofpbuf_tail(stack);
1361     }
1362
1363     return v;
1364 }
1365
1366 void
1367 nxm_execute_stack_push(const struct ofpact_stack *push,
1368                        const struct flow *flow, struct flow_wildcards *wc,
1369                        struct ofpbuf *stack)
1370 {
1371     union mf_subvalue mask_value;
1372     union mf_subvalue dst_value;
1373
1374     memset(&mask_value, 0xff, sizeof mask_value);
1375     mf_write_subfield_flow(&push->subfield, &mask_value, &wc->masks);
1376
1377     mf_read_subfield(&push->subfield, flow, &dst_value);
1378     nx_stack_push(stack, &dst_value);
1379 }
1380
1381 void
1382 nxm_execute_stack_pop(const struct ofpact_stack *pop,
1383                       struct flow *flow, struct flow_wildcards *wc,
1384                       struct ofpbuf *stack)
1385 {
1386     union mf_subvalue *src_value;
1387
1388     src_value = nx_stack_pop(stack);
1389
1390     /* Only pop if stack is not empty. Otherwise, give warning. */
1391     if (src_value) {
1392         union mf_subvalue mask_value;
1393
1394         memset(&mask_value, 0xff, sizeof mask_value);
1395         mf_write_subfield_flow(&pop->subfield, &mask_value, &wc->masks);
1396         mf_write_subfield_flow(&pop->subfield, src_value, flow);
1397     } else {
1398         if (!VLOG_DROP_WARN(&rl)) {
1399             char *flow_str = flow_to_string(flow);
1400             VLOG_WARN_RL(&rl, "Failed to pop from an empty stack. On flow \n"
1401                            " %s", flow_str);
1402             free(flow_str);
1403         }
1404     }
1405 }
1406 \f
1407 /* Formats 'sf' into 's' in a format normally acceptable to
1408  * mf_parse_subfield().  (It won't be acceptable if sf->field is NULL or if
1409  * sf->field has no NXM name.) */
1410 void
1411 mf_format_subfield(const struct mf_subfield *sf, struct ds *s)
1412 {
1413     if (!sf->field) {
1414         ds_put_cstr(s, "<unknown>");
1415     } else {
1416         const struct nxm_field *f = nxm_field_from_mf_field(sf->field->id, 0);
1417         ds_put_cstr(s, f ? f->name : sf->field->name);
1418     }
1419
1420     if (sf->field && sf->ofs == 0 && sf->n_bits == sf->field->n_bits) {
1421         ds_put_cstr(s, "[]");
1422     } else if (sf->n_bits == 1) {
1423         ds_put_format(s, "[%d]", sf->ofs);
1424     } else {
1425         ds_put_format(s, "[%d..%d]", sf->ofs, sf->ofs + sf->n_bits - 1);
1426     }
1427 }
1428
1429 static const struct nxm_field *
1430 mf_parse_subfield_name(const char *name, int name_len, bool *wild)
1431 {
1432     *wild = name_len > 2 && !memcmp(&name[name_len - 2], "_W", 2);
1433     if (*wild) {
1434         name_len -= 2;
1435     }
1436
1437     return nxm_field_by_name(name, name_len);
1438 }
1439
1440 /* Parses a subfield from the beginning of '*sp' into 'sf'.  If successful,
1441  * returns NULL and advances '*sp' to the first byte following the parsed
1442  * string.  On failure, returns a malloc()'d error message, does not modify
1443  * '*sp', and does not properly initialize 'sf'.
1444  *
1445  * The syntax parsed from '*sp' takes the form "header[start..end]" where
1446  * 'header' is the name of an NXM field and 'start' and 'end' are (inclusive)
1447  * bit indexes.  "..end" may be omitted to indicate a single bit.  "start..end"
1448  * may both be omitted (the [] are still required) to indicate an entire
1449  * field. */
1450 char * WARN_UNUSED_RESULT
1451 mf_parse_subfield__(struct mf_subfield *sf, const char **sp)
1452 {
1453     const struct mf_field *field;
1454     const struct nxm_field *f;
1455     const char *name;
1456     int start, end;
1457     const char *s;
1458     int name_len;
1459     bool wild;
1460
1461     s = *sp;
1462     name = s;
1463     name_len = strcspn(s, "[");
1464     if (s[name_len] != '[') {
1465         return xasprintf("%s: missing [ looking for field name", *sp);
1466     }
1467
1468     f = mf_parse_subfield_name(name, name_len, &wild);
1469     if (!f) {
1470         return xasprintf("%s: unknown field `%.*s'", *sp, name_len, s);
1471     }
1472     field = mf_from_id(f->id);
1473
1474     s += name_len;
1475     if (ovs_scan(s, "[%d..%d]", &start, &end)) {
1476         /* Nothing to do. */
1477     } else if (ovs_scan(s, "[%d]", &start)) {
1478         end = start;
1479     } else if (!strncmp(s, "[]", 2)) {
1480         start = 0;
1481         end = field->n_bits - 1;
1482     } else {
1483         return xasprintf("%s: syntax error expecting [] or [<bit>] or "
1484                          "[<start>..<end>]", *sp);
1485     }
1486     s = strchr(s, ']') + 1;
1487
1488     if (start > end) {
1489         return xasprintf("%s: starting bit %d is after ending bit %d",
1490                          *sp, start, end);
1491     } else if (start >= field->n_bits) {
1492         return xasprintf("%s: starting bit %d is not valid because field is "
1493                          "only %d bits wide", *sp, start, field->n_bits);
1494     } else if (end >= field->n_bits){
1495         return xasprintf("%s: ending bit %d is not valid because field is "
1496                          "only %d bits wide", *sp, end, field->n_bits);
1497     }
1498
1499     sf->field = field;
1500     sf->ofs = start;
1501     sf->n_bits = end - start + 1;
1502
1503     *sp = s;
1504     return NULL;
1505 }
1506
1507 /* Parses a subfield from the entirety of 's' into 'sf'.  Returns NULL if
1508  * successful, otherwise a malloc()'d string describing the error.  The caller
1509  * is responsible for freeing the returned string.
1510  *
1511  * The syntax parsed from 's' takes the form "header[start..end]" where
1512  * 'header' is the name of an NXM field and 'start' and 'end' are (inclusive)
1513  * bit indexes.  "..end" may be omitted to indicate a single bit.  "start..end"
1514  * may both be omitted (the [] are still required) to indicate an entire
1515  * field.  */
1516 char * WARN_UNUSED_RESULT
1517 mf_parse_subfield(struct mf_subfield *sf, const char *s)
1518 {
1519     char *error = mf_parse_subfield__(sf, &s);
1520     if (!error && s[0]) {
1521         error = xstrdup("unexpected input following field syntax");
1522     }
1523     return error;
1524 }
1525 \f
1526 /* Returns an bitmap in which each bit corresponds to the like-numbered field
1527  * in the OFPXMC12_OPENFLOW_BASIC OXM class, in which the bit values are taken
1528  * from the 'fields' bitmap.  Only fields defined in OpenFlow 'version' are
1529  * considered.
1530  *
1531  * This is useful for encoding OpenFlow 1.2 table stats messages. */
1532 ovs_be64
1533 oxm_bitmap_from_mf_bitmap(const struct mf_bitmap *fields,
1534                           enum ofp_version version)
1535 {
1536     uint64_t oxm_bitmap = 0;
1537     int i;
1538
1539     BITMAP_FOR_EACH_1 (i, MFF_N_IDS, fields->bm) {
1540         uint32_t oxm = mf_oxm_header(i, version);
1541         uint32_t class = nxm_class(oxm);
1542         int field = nxm_field(oxm);
1543
1544         if (class == OFPXMC12_OPENFLOW_BASIC && field < 64) {
1545             oxm_bitmap |= UINT64_C(1) << field;
1546         }
1547     }
1548     return htonll(oxm_bitmap);
1549 }
1550
1551 /* Opposite conversion from oxm_bitmap_from_mf_bitmap().
1552  *
1553  * This is useful for decoding OpenFlow 1.2 table stats messages. */
1554 struct mf_bitmap
1555 oxm_bitmap_to_mf_bitmap(ovs_be64 oxm_bitmap, enum ofp_version version)
1556 {
1557     struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
1558
1559     for (enum mf_field_id id = 0; id < MFF_N_IDS; id++) {
1560         if (version >= mf_oxm_version(id)) {
1561             uint32_t oxm = mf_oxm_header(id, version);
1562             uint32_t class = nxm_class(oxm);
1563             int field = nxm_field(oxm);
1564
1565             if (class == OFPXMC12_OPENFLOW_BASIC
1566                 && field < 64
1567                 && oxm_bitmap & htonll(UINT64_C(1) << field)) {
1568                 bitmap_set1(fields.bm, id);
1569             }
1570         }
1571     }
1572     return fields;
1573 }
1574
1575 /* Returns a bitmap of fields that can be encoded in OXM and that can be
1576  * modified with a "set_field" action.  */
1577 struct mf_bitmap
1578 oxm_writable_fields(void)
1579 {
1580     struct mf_bitmap b = MF_BITMAP_INITIALIZER;
1581     int i;
1582
1583     for (i = 0; i < MFF_N_IDS; i++) {
1584         if (mf_oxm_header(i, 0) && mf_from_id(i)->writable) {
1585             bitmap_set1(b.bm, i);
1586         }
1587     }
1588     return b;
1589 }
1590
1591 /* Returns a bitmap of fields that can be encoded in OXM and that can be
1592  * matched in a flow table.  */
1593 struct mf_bitmap
1594 oxm_matchable_fields(void)
1595 {
1596     struct mf_bitmap b = MF_BITMAP_INITIALIZER;
1597     int i;
1598
1599     for (i = 0; i < MFF_N_IDS; i++) {
1600         if (mf_oxm_header(i, 0)) {
1601             bitmap_set1(b.bm, i);
1602         }
1603     }
1604     return b;
1605 }
1606
1607 /* Returns a bitmap of fields that can be encoded in OXM and that can be
1608  * matched in a flow table with an arbitrary bitmask.  */
1609 struct mf_bitmap
1610 oxm_maskable_fields(void)
1611 {
1612     struct mf_bitmap b = MF_BITMAP_INITIALIZER;
1613     int i;
1614
1615     for (i = 0; i < MFF_N_IDS; i++) {
1616         if (mf_oxm_header(i, 0) && mf_from_id(i)->maskable == MFM_FULLY) {
1617             bitmap_set1(b.bm, i);
1618         }
1619     }
1620     return b;
1621 }
1622 \f
1623 struct nxm_field_index {
1624     struct hmap_node header_node;
1625     struct hmap_node name_node;
1626     struct nxm_field nf;
1627 };
1628
1629 #include "nx-match.inc"
1630
1631 static struct hmap nxm_header_map;
1632 static struct hmap nxm_name_map;
1633 static struct nxm_field *nxm_fields[MFF_N_IDS];
1634 static struct nxm_field *oxm_fields[MFF_N_IDS];
1635
1636 static void
1637 nxm_init(void)
1638 {
1639     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1640     if (ovsthread_once_start(&once)) {
1641         hmap_init(&nxm_header_map);
1642         hmap_init(&nxm_name_map);
1643         for (struct nxm_field_index *nfi = all_nxm_fields;
1644              nfi < &all_nxm_fields[ARRAY_SIZE(all_nxm_fields)]; nfi++) {
1645             hmap_insert(&nxm_header_map, &nfi->header_node,
1646                         hash_int(nfi->nf.header, 0));
1647             hmap_insert(&nxm_name_map, &nfi->name_node,
1648                         hash_string(nfi->nf.name, 0));
1649             if (is_nxm_header(nfi->nf.header)) {
1650                 nxm_fields[nfi->nf.id] = &nfi->nf;
1651             } else {
1652                 oxm_fields[nfi->nf.id] = &nfi->nf;
1653             }
1654         }
1655         ovsthread_once_done(&once);
1656     }
1657 }
1658
1659 static const struct nxm_field *
1660 nxm_field_by_header(uint32_t header)
1661 {
1662     const struct nxm_field_index *nfi;
1663
1664     nxm_init();
1665     if (nxm_hasmask(header)) {
1666         header = nxm_make_exact_header(header);
1667     }
1668
1669     HMAP_FOR_EACH_IN_BUCKET (nfi, header_node, hash_int(header, 0),
1670                              &nxm_header_map) {
1671         if (header == nfi->nf.header) {
1672             return &nfi->nf;
1673         }
1674     }
1675     return NULL;
1676 }
1677
1678 static const struct nxm_field *
1679 nxm_field_by_name(const char *name, size_t len)
1680 {
1681     const struct nxm_field_index *nfi;
1682
1683     nxm_init();
1684     HMAP_FOR_EACH_WITH_HASH (nfi, name_node, hash_bytes(name, len, 0),
1685                              &nxm_name_map) {
1686         if (strlen(nfi->nf.name) == len && !memcmp(nfi->nf.name, name, len)) {
1687             return &nfi->nf;
1688         }
1689     }
1690     return NULL;
1691 }
1692
1693 static const struct nxm_field *
1694 nxm_field_by_mf_id(enum mf_field_id id)
1695 {
1696     nxm_init();
1697     return nxm_fields[id];
1698 }
1699
1700 static const struct nxm_field *
1701 oxm_field_by_mf_id(enum mf_field_id id)
1702 {
1703     nxm_init();
1704     return oxm_fields[id];
1705 }
1706