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