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