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