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