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