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