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