ofp-actions: Refactor ofpact_get_mf_dst().
[cascardo/ovs.git] / lib / ofp-actions.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <netinet/in.h>
19
20 #include "ofp-actions.h"
21 #include "bundle.h"
22 #include "byte-order.h"
23 #include "compiler.h"
24 #include "dummy.h"
25 #include "dynamic-string.h"
26 #include "hmap.h"
27 #include "learn.h"
28 #include "meta-flow.h"
29 #include "multipath.h"
30 #include "nx-match.h"
31 #include "odp-netlink.h"
32 #include "ofp-parse.h"
33 #include "ofp-util.h"
34 #include "ofpbuf.h"
35 #include "unaligned.h"
36 #include "util.h"
37 #include "openvswitch/vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(ofp_actions);
40
41 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
42
43 struct ofp_action_header;
44
45 /* Raw identifiers for OpenFlow actions.
46  *
47  * Decoding and encoding OpenFlow actions across multiple versions is difficult
48  * to do in a clean, consistent way.  This enumeration lays out all of the
49  * forms of actions that Open vSwitch supports.
50  *
51  * The comments here must follow a stylized form because the
52  * "extract-ofp-actions" program parses them at build time to generate data
53  * tables.
54  *
55  *   - The first part of each comment specifies the vendor, OpenFlow versions,
56  *     and type for each protocol that supports the action:
57  *
58  *         # The vendor is OF for standard OpenFlow actions, NX for Nicira
59  *           extension actions.  (Support for other vendors can be added, but
60  *           it can't be done just based on a vendor ID definition alone
61  *           because OpenFlow doesn't define a standard way to specify a
62  *           subtype for vendor actions, so other vendors might do it different
63  *           from Nicira.)
64  *
65  *         # The version can specify a specific OpenFlow version, a version
66  *           range delimited by "-", or an open-ended range with "+".
67  *
68  *         # The type, in parentheses, is the action type number (for standard
69  *           OpenFlow actions) or subtype (for vendor extension actions).
70  *
71  *         # Optionally one may add "is deprecated" followed by a
72  *           human-readable reason in parentheses (which will be used in log
73  *           messages), if a particular action should no longer be used.
74  *
75  *     Multiple such specifications may be separated by commas.
76  *
77  *   - The second part describes the action's wire format.  It may be:
78  *
79  *         # "struct <name>": The struct fully specifies the wire format.  The
80  *           action is exactly the size of the struct.  (Thus, the struct must
81  *           be an exact multiple of 8 bytes in size.)
82  *
83  *         # "struct <name>, ...": The struct specifies the beginning of the
84  *           wire format.  An instance of the action is either the struct's
85  *           exact size, or a multiple of 8 bytes longer.
86  *
87  *         # "uint<N>_t" or "ovs_be<N>": The action consists of a (standard or
88  *           vendor extension) header, followed by 0 or more pad bytes to align
89  *           to a multiple of <N> bits, followed by an argument of the given
90  *           type, followed by 0 or more pad bytes to bring the total action up
91  *           to a multiple of 8 bytes.
92  *
93  *         # "void": The action is just a (standard or vendor extension)
94  *           header.
95  *
96  *   - Optional additional text enclosed in square brackets is commentary for
97  *     the human reader.
98  */
99 enum ofp_raw_action_type {
100 /* ## ----------------- ## */
101 /* ## Standard actions. ## */
102 /* ## ----------------- ## */
103
104     /* OF1.0(0): struct ofp10_action_output. */
105     OFPAT_RAW10_OUTPUT,
106     /* OF1.1+(0): struct ofp11_action_output. */
107     OFPAT_RAW11_OUTPUT,
108
109     /* OF1.0(1): uint16_t. */
110     OFPAT_RAW10_SET_VLAN_VID,
111     /* OF1.0(2): uint8_t. */
112     OFPAT_RAW10_SET_VLAN_PCP,
113
114     /* OF1.1(1), OF1.2+(1) is deprecated (use Set-Field): uint16_t.
115      *
116      * [Semantics differ slightly between the 1.0 and 1.1 versions of the VLAN
117      * modification actions: the 1.0 versions push a VLAN header if none is
118      * present, but the 1.1 versions do not.  That is the only reason that we
119      * distinguish their raw action types.] */
120     OFPAT_RAW11_SET_VLAN_VID,
121     /* OF1.1(2), OF1.2+(2) is deprecated (use Set-Field): uint8_t. */
122     OFPAT_RAW11_SET_VLAN_PCP,
123
124     /* OF1.1+(17): ovs_be16.
125      *
126      * [The argument is the Ethertype, e.g. ETH_TYPE_VLAN_8021Q, not the VID or
127      * TCI.] */
128     OFPAT_RAW11_PUSH_VLAN,
129
130     /* OF1.0(3): void. */
131     OFPAT_RAW10_STRIP_VLAN,
132     /* OF1.1+(18): void. */
133     OFPAT_RAW11_POP_VLAN,
134
135     /* OF1.0(4), OF1.1(3), OF1.2+(3) is deprecated (use Set-Field): struct
136      * ofp_action_dl_addr. */
137     OFPAT_RAW_SET_DL_SRC,
138
139     /* OF1.0(5), OF1.1(4), OF1.2+(4) is deprecated (use Set-Field): struct
140      * ofp_action_dl_addr. */
141     OFPAT_RAW_SET_DL_DST,
142
143     /* OF1.0(6), OF1.1(5), OF1.2+(5) is deprecated (use Set-Field):
144      * ovs_be32. */
145     OFPAT_RAW_SET_NW_SRC,
146
147     /* OF1.0(7), OF1.1(6), OF1.2+(6) is deprecated (use Set-Field):
148      * ovs_be32. */
149     OFPAT_RAW_SET_NW_DST,
150
151     /* OF1.0(8), OF1.1(7), OF1.2+(7) is deprecated (use Set-Field): uint8_t. */
152     OFPAT_RAW_SET_NW_TOS,
153
154     /* OF1.1(8), OF1.2+(8) is deprecated (use Set-Field): uint8_t. */
155     OFPAT_RAW11_SET_NW_ECN,
156
157     /* OF1.0(9), OF1.1(9), OF1.2+(9) is deprecated (use Set-Field):
158      * ovs_be16. */
159     OFPAT_RAW_SET_TP_SRC,
160
161     /* OF1.0(10), OF1.1(10), OF1.2+(10) is deprecated (use Set-Field):
162      * ovs_be16. */
163     OFPAT_RAW_SET_TP_DST,
164
165     /* OF1.0(11): struct ofp10_action_enqueue. */
166     OFPAT_RAW10_ENQUEUE,
167
168     /* NX1.0(30), OF1.1(13), OF1.2+(13) is deprecated (use Set-Field):
169      * ovs_be32. */
170     OFPAT_RAW_SET_MPLS_LABEL,
171
172     /* NX1.0(31), OF1.1(14), OF1.2+(14) is deprecated (use Set-Field):
173      * uint8_t. */
174     OFPAT_RAW_SET_MPLS_TC,
175
176     /* NX1.0(25), OF1.1(15), OF1.2+(15) is deprecated (use Set-Field):
177      * uint8_t. */
178     OFPAT_RAW_SET_MPLS_TTL,
179
180     /* NX1.0(26), OF1.1+(16): void. */
181     OFPAT_RAW_DEC_MPLS_TTL,
182
183     /* NX1.0(23), OF1.1+(19): ovs_be16.
184      *
185      * [The argument is the Ethertype, e.g. ETH_TYPE_MPLS, not the label.] */
186     OFPAT_RAW_PUSH_MPLS,
187
188     /* NX1.0(24), OF1.1+(20): ovs_be16.
189      *
190      * [The argument is the Ethertype, e.g. ETH_TYPE_IPV4 if at BoS or
191      * ETH_TYPE_MPLS otherwise, not the label.] */
192     OFPAT_RAW_POP_MPLS,
193
194     /* NX1.0(4), OF1.1+(21): uint32_t. */
195     OFPAT_RAW_SET_QUEUE,
196
197     /* OF1.1+(22): uint32_t. */
198     OFPAT_RAW11_GROUP,
199
200     /* OF1.1+(23): uint8_t. */
201     OFPAT_RAW11_SET_NW_TTL,
202
203     /* NX1.0(18), OF1.1+(24): void. */
204     OFPAT_RAW_DEC_NW_TTL,
205     /* NX1.0+(21): struct nx_action_cnt_ids, ... */
206     NXAST_RAW_DEC_TTL_CNT_IDS,
207
208     /* OF1.2-1.4(25): struct ofp12_action_set_field, ... */
209     OFPAT_RAW12_SET_FIELD,
210     /* OF1.5+(25): struct ofp12_action_set_field, ... */
211     OFPAT_RAW15_SET_FIELD,
212     /* NX1.0-1.4(7): struct nx_action_reg_load.
213      *
214      * [In OpenFlow 1.5, set_field is a superset of reg_load functionality, so
215      * we drop reg_load.] */
216     NXAST_RAW_REG_LOAD,
217     /* NX1.0-1.4(33): struct nx_action_reg_load2, ...
218      *
219      * [In OpenFlow 1.5, set_field is a superset of reg_load2 functionality, so
220      * we drop reg_load2.] */
221     NXAST_RAW_REG_LOAD2,
222
223     /* OF1.5+(28): struct ofp15_action_copy_field, ... */
224     OFPAT_RAW15_COPY_FIELD,
225     /* ONF1.3-1.4(3200): struct onf_action_copy_field, ... */
226     ONFACT_RAW13_COPY_FIELD,
227     /* NX1.0-1.4(6): struct nx_action_reg_move, ... */
228     NXAST_RAW_REG_MOVE,
229
230 /* ## ------------------------- ## */
231 /* ## Nicira extension actions. ## */
232 /* ## ------------------------- ## */
233
234 /* Actions similar to standard actions are listed with the standard actions. */
235
236     /* NX1.0+(1): uint16_t. */
237     NXAST_RAW_RESUBMIT,
238     /* NX1.0+(14): struct nx_action_resubmit. */
239     NXAST_RAW_RESUBMIT_TABLE,
240
241     /* NX1.0+(2): uint32_t. */
242     NXAST_RAW_SET_TUNNEL,
243     /* NX1.0+(9): uint64_t. */
244     NXAST_RAW_SET_TUNNEL64,
245
246     /* NX1.0+(5): void. */
247     NXAST_RAW_POP_QUEUE,
248
249     /* NX1.0+(8): struct nx_action_note, ... */
250     NXAST_RAW_NOTE,
251
252     /* NX1.0+(10): struct nx_action_multipath. */
253     NXAST_RAW_MULTIPATH,
254
255     /* NX1.0+(12): struct nx_action_bundle, ... */
256     NXAST_RAW_BUNDLE,
257     /* NX1.0+(13): struct nx_action_bundle, ... */
258     NXAST_RAW_BUNDLE_LOAD,
259
260     /* NX1.0+(15): struct nx_action_output_reg. */
261     NXAST_RAW_OUTPUT_REG,
262     /* NX1.0+(32): struct nx_action_output_reg2. */
263     NXAST_RAW_OUTPUT_REG2,
264
265     /* NX1.0+(16): struct nx_action_learn, ... */
266     NXAST_RAW_LEARN,
267
268     /* NX1.0+(17): void. */
269     NXAST_RAW_EXIT,
270
271     /* NX1.0+(19): struct nx_action_fin_timeout. */
272     NXAST_RAW_FIN_TIMEOUT,
273
274     /* NX1.0+(20): struct nx_action_controller. */
275     NXAST_RAW_CONTROLLER,
276
277     /* NX1.0+(22): struct nx_action_write_metadata. */
278     NXAST_RAW_WRITE_METADATA,
279
280     /* NX1.0+(27): struct nx_action_stack. */
281     NXAST_RAW_STACK_PUSH,
282
283     /* NX1.0+(28): struct nx_action_stack. */
284     NXAST_RAW_STACK_POP,
285
286     /* NX1.0+(29): struct nx_action_sample. */
287     NXAST_RAW_SAMPLE,
288
289     /* NX1.0+(34): struct nx_action_conjunction. */
290     NXAST_RAW_CONJUNCTION,
291
292     /* NX1.0+(35): struct nx_action_conntrack, ... */
293     NXAST_RAW_CT,
294
295     /* NX1.0+(36): struct nx_action_nat, ... */
296     NXAST_RAW_NAT,
297
298 /* ## ------------------ ## */
299 /* ## Debugging actions. ## */
300 /* ## ------------------ ## */
301
302 /* These are intentionally undocumented, subject to change, and ovs-vswitchd */
303 /* accepts them only if started with --enable-dummy. */
304
305     /* NX1.0+(255): void. */
306     NXAST_RAW_DEBUG_RECIRC,
307 };
308
309 /* OpenFlow actions are always a multiple of 8 bytes in length. */
310 #define OFP_ACTION_ALIGN 8
311
312 /* Define a few functions for working with instructions. */
313 #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME)             \
314     static inline const struct STRUCT * OVS_UNUSED              \
315     instruction_get_##ENUM(const struct ofp11_instruction *inst)\
316     {                                                           \
317         ovs_assert(inst->type == htons(ENUM));                  \
318         return ALIGNED_CAST(struct STRUCT *, inst);             \
319     }                                                           \
320                                                                 \
321     static inline void OVS_UNUSED                               \
322     instruction_init_##ENUM(struct STRUCT *s)                   \
323     {                                                           \
324         memset(s, 0, sizeof *s);                                \
325         s->type = htons(ENUM);                                  \
326         s->len = htons(sizeof *s);                              \
327     }                                                           \
328                                                                 \
329     static inline struct STRUCT * OVS_UNUSED                    \
330     instruction_put_##ENUM(struct ofpbuf *buf)                  \
331     {                                                           \
332         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
333         instruction_init_##ENUM(s);                             \
334         return s;                                               \
335     }
336 OVS_INSTRUCTIONS
337 #undef DEFINE_INST
338
339 static void ofpacts_update_instruction_actions(struct ofpbuf *openflow,
340                                                size_t ofs);
341 static void pad_ofpat(struct ofpbuf *openflow, size_t start_ofs);
342
343 static enum ofperr ofpacts_verify(const struct ofpact[], size_t ofpacts_len,
344                                   uint32_t allowed_ovsinsts,
345                                   enum ofpact_type outer_action);
346
347 static void ofpact_put_set_field(struct ofpbuf *openflow, enum ofp_version,
348                                  enum mf_field_id, uint64_t value);
349
350 static enum ofperr ofpact_pull_raw(struct ofpbuf *, enum ofp_version,
351                                    enum ofp_raw_action_type *, uint64_t *arg);
352 static void *ofpact_put_raw(struct ofpbuf *, enum ofp_version,
353                             enum ofp_raw_action_type, uint64_t arg);
354
355 static char *OVS_WARN_UNUSED_RESULT ofpacts_parse(
356     char *str, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols,
357     bool allow_instructions, enum ofpact_type outer_action);
358 static enum ofperr ofpacts_pull_openflow_actions__(
359     struct ofpbuf *openflow, unsigned int actions_len,
360     enum ofp_version version, uint32_t allowed_ovsinsts,
361     struct ofpbuf *ofpacts, enum ofpact_type outer_action);
362 static char * OVS_WARN_UNUSED_RESULT ofpacts_parse_copy(
363     const char *s_, struct ofpbuf *ofpacts,
364     enum ofputil_protocol *usable_protocols,
365     bool allow_instructions, enum ofpact_type outer_action);
366
367 /* Returns the ofpact following 'ofpact', except that if 'ofpact' contains
368  * nested ofpacts it returns the first one. */
369 struct ofpact *
370 ofpact_next_flattened(const struct ofpact *ofpact)
371 {
372     switch (ofpact->type) {
373     case OFPACT_OUTPUT:
374     case OFPACT_GROUP:
375     case OFPACT_CONTROLLER:
376     case OFPACT_ENQUEUE:
377     case OFPACT_OUTPUT_REG:
378     case OFPACT_BUNDLE:
379     case OFPACT_SET_FIELD:
380     case OFPACT_SET_VLAN_VID:
381     case OFPACT_SET_VLAN_PCP:
382     case OFPACT_STRIP_VLAN:
383     case OFPACT_PUSH_VLAN:
384     case OFPACT_SET_ETH_SRC:
385     case OFPACT_SET_ETH_DST:
386     case OFPACT_SET_IPV4_SRC:
387     case OFPACT_SET_IPV4_DST:
388     case OFPACT_SET_IP_DSCP:
389     case OFPACT_SET_IP_ECN:
390     case OFPACT_SET_IP_TTL:
391     case OFPACT_SET_L4_SRC_PORT:
392     case OFPACT_SET_L4_DST_PORT:
393     case OFPACT_REG_MOVE:
394     case OFPACT_STACK_PUSH:
395     case OFPACT_STACK_POP:
396     case OFPACT_DEC_TTL:
397     case OFPACT_SET_MPLS_LABEL:
398     case OFPACT_SET_MPLS_TC:
399     case OFPACT_SET_MPLS_TTL:
400     case OFPACT_DEC_MPLS_TTL:
401     case OFPACT_PUSH_MPLS:
402     case OFPACT_POP_MPLS:
403     case OFPACT_SET_TUNNEL:
404     case OFPACT_SET_QUEUE:
405     case OFPACT_POP_QUEUE:
406     case OFPACT_FIN_TIMEOUT:
407     case OFPACT_RESUBMIT:
408     case OFPACT_LEARN:
409     case OFPACT_CONJUNCTION:
410     case OFPACT_MULTIPATH:
411     case OFPACT_NOTE:
412     case OFPACT_EXIT:
413     case OFPACT_SAMPLE:
414     case OFPACT_UNROLL_XLATE:
415     case OFPACT_DEBUG_RECIRC:
416     case OFPACT_METER:
417     case OFPACT_CLEAR_ACTIONS:
418     case OFPACT_WRITE_METADATA:
419     case OFPACT_GOTO_TABLE:
420     case OFPACT_NAT:
421         return ofpact_next(ofpact);
422
423     case OFPACT_CT:
424         return ofpact_get_CT(ofpact)->actions;
425
426     case OFPACT_WRITE_ACTIONS:
427         return ofpact_get_WRITE_ACTIONS(ofpact)->actions;
428     }
429
430     OVS_NOT_REACHED();
431 }
432
433 /* Pull off existing actions or instructions. Used by nesting actions to keep
434  * ofpacts_parse() oblivious of actions nesting.
435  *
436  * Push the actions back on after nested parsing, e.g.:
437  *
438  *     size_t ofs = ofpacts_pull(ofpacts);
439  *     ...nested parsing...
440  *     ofpbuf_push_uninit(ofpacts, ofs);
441  */
442 static size_t
443 ofpacts_pull(struct ofpbuf *ofpacts)
444 {
445     size_t ofs;
446
447     ofpact_pad(ofpacts);
448     ofs = ofpacts->size;
449     ofpbuf_pull(ofpacts, ofs);
450
451     return ofs;
452 }
453
454 #include "ofp-actions.inc1"
455 \f
456 /* Output actions. */
457
458 /* Action structure for OFPAT10_OUTPUT, which sends packets out 'port'.
459  * When the 'port' is the OFPP_CONTROLLER, 'max_len' indicates the max
460  * number of bytes to send.  A 'max_len' of zero means no bytes of the
461  * packet should be sent. */
462 struct ofp10_action_output {
463     ovs_be16 type;                  /* OFPAT10_OUTPUT. */
464     ovs_be16 len;                   /* Length is 8. */
465     ovs_be16 port;                  /* Output port. */
466     ovs_be16 max_len;               /* Max length to send to controller. */
467 };
468 OFP_ASSERT(sizeof(struct ofp10_action_output) == 8);
469
470 /* Action structure for OFPAT_OUTPUT, which sends packets out 'port'.
471    * When the 'port' is the OFPP_CONTROLLER, 'max_len' indicates the max
472    * number of bytes to send. A 'max_len' of zero means no bytes of the
473    * packet should be sent.*/
474 struct ofp11_action_output {
475     ovs_be16 type;                    /* OFPAT11_OUTPUT. */
476     ovs_be16 len;                     /* Length is 16. */
477     ovs_be32 port;                    /* Output port. */
478     ovs_be16 max_len;                 /* Max length to send to controller. */
479     uint8_t pad[6];                   /* Pad to 64 bits. */
480 };
481 OFP_ASSERT(sizeof(struct ofp11_action_output) == 16);
482
483 static enum ofperr
484 decode_OFPAT_RAW10_OUTPUT(const struct ofp10_action_output *oao,
485                           enum ofp_version ofp_version OVS_UNUSED,
486                           struct ofpbuf *out)
487 {
488     struct ofpact_output *output;
489
490     output = ofpact_put_OUTPUT(out);
491     output->port = u16_to_ofp(ntohs(oao->port));
492     output->max_len = ntohs(oao->max_len);
493
494     return ofpact_check_output_port(output->port, OFPP_MAX);
495 }
496
497 static enum ofperr
498 decode_OFPAT_RAW11_OUTPUT(const struct ofp11_action_output *oao,
499                           enum ofp_version ofp_version OVS_UNUSED,
500                           struct ofpbuf *out)
501 {
502     struct ofpact_output *output;
503     enum ofperr error;
504
505     output = ofpact_put_OUTPUT(out);
506     output->max_len = ntohs(oao->max_len);
507
508     error = ofputil_port_from_ofp11(oao->port, &output->port);
509     if (error) {
510         return error;
511     }
512
513     return ofpact_check_output_port(output->port, OFPP_MAX);
514 }
515
516 static void
517 encode_OUTPUT(const struct ofpact_output *output,
518               enum ofp_version ofp_version, struct ofpbuf *out)
519 {
520     if (ofp_version == OFP10_VERSION) {
521         struct ofp10_action_output *oao;
522
523         oao = put_OFPAT10_OUTPUT(out);
524         oao->port = htons(ofp_to_u16(output->port));
525         oao->max_len = htons(output->max_len);
526     } else {
527         struct ofp11_action_output *oao;
528
529         oao = put_OFPAT11_OUTPUT(out);
530         oao->port = ofputil_port_to_ofp11(output->port);
531         oao->max_len = htons(output->max_len);
532     }
533 }
534
535 static char * OVS_WARN_UNUSED_RESULT
536 parse_OUTPUT(const char *arg, struct ofpbuf *ofpacts,
537              enum ofputil_protocol *usable_protocols OVS_UNUSED)
538 {
539     if (strchr(arg, '[')) {
540         struct ofpact_output_reg *output_reg;
541
542         output_reg = ofpact_put_OUTPUT_REG(ofpacts);
543         output_reg->max_len = UINT16_MAX;
544         return mf_parse_subfield(&output_reg->src, arg);
545     } else {
546         struct ofpact_output *output;
547
548         output = ofpact_put_OUTPUT(ofpacts);
549         if (!ofputil_port_from_string(arg, &output->port)) {
550             return xasprintf("%s: output to unknown port", arg);
551         }
552         output->max_len = output->port == OFPP_CONTROLLER ? UINT16_MAX : 0;
553         return NULL;
554     }
555 }
556
557 static void
558 format_OUTPUT(const struct ofpact_output *a, struct ds *s)
559 {
560     if (ofp_to_u16(a->port) < ofp_to_u16(OFPP_MAX)) {
561         ds_put_format(s, "output:%"PRIu16, a->port);
562     } else {
563         ofputil_format_port(a->port, s);
564         if (a->port == OFPP_CONTROLLER) {
565             ds_put_format(s, ":%"PRIu16, a->max_len);
566         }
567     }
568 }
569 \f
570 /* Group actions. */
571
572 static enum ofperr
573 decode_OFPAT_RAW11_GROUP(uint32_t group_id,
574                          enum ofp_version ofp_version OVS_UNUSED,
575                          struct ofpbuf *out)
576 {
577     ofpact_put_GROUP(out)->group_id = group_id;
578     return 0;
579 }
580
581 static void
582 encode_GROUP(const struct ofpact_group *group,
583              enum ofp_version ofp_version, struct ofpbuf *out)
584 {
585     if (ofp_version == OFP10_VERSION) {
586         /* XXX */
587     } else {
588         put_OFPAT11_GROUP(out, group->group_id);
589     }
590 }
591
592 static char * OVS_WARN_UNUSED_RESULT
593 parse_GROUP(char *arg, struct ofpbuf *ofpacts,
594                     enum ofputil_protocol *usable_protocols OVS_UNUSED)
595 {
596     return str_to_u32(arg, &ofpact_put_GROUP(ofpacts)->group_id);
597 }
598
599 static void
600 format_GROUP(const struct ofpact_group *a, struct ds *s)
601 {
602     ds_put_format(s, "group:%"PRIu32, a->group_id);
603 }
604 \f
605 /* Action structure for NXAST_CONTROLLER.
606  *
607  * This generalizes using OFPAT_OUTPUT to send a packet to OFPP_CONTROLLER.  In
608  * addition to the 'max_len' that OFPAT_OUTPUT supports, it also allows
609  * specifying:
610  *
611  *    - 'reason': The reason code to use in the ofp_packet_in or nx_packet_in.
612  *
613  *    - 'controller_id': The ID of the controller connection to which the
614  *      ofp_packet_in should be sent.  The ofp_packet_in or nx_packet_in is
615  *      sent only to controllers that have the specified controller connection
616  *      ID.  See "struct nx_controller_id" for more information. */
617 struct nx_action_controller {
618     ovs_be16 type;                  /* OFPAT_VENDOR. */
619     ovs_be16 len;                   /* Length is 16. */
620     ovs_be32 vendor;                /* NX_VENDOR_ID. */
621     ovs_be16 subtype;               /* NXAST_CONTROLLER. */
622     ovs_be16 max_len;               /* Maximum length to send to controller. */
623     ovs_be16 controller_id;         /* Controller ID to send packet-in. */
624     uint8_t reason;                 /* enum ofp_packet_in_reason (OFPR_*). */
625     uint8_t zero;                   /* Must be zero. */
626 };
627 OFP_ASSERT(sizeof(struct nx_action_controller) == 16);
628
629 static enum ofperr
630 decode_NXAST_RAW_CONTROLLER(const struct nx_action_controller *nac,
631                             enum ofp_version ofp_version OVS_UNUSED,
632                             struct ofpbuf *out)
633 {
634     struct ofpact_controller *oc;
635
636     oc = ofpact_put_CONTROLLER(out);
637     oc->max_len = ntohs(nac->max_len);
638     oc->controller_id = ntohs(nac->controller_id);
639     oc->reason = nac->reason;
640     return 0;
641 }
642
643 static void
644 encode_CONTROLLER(const struct ofpact_controller *controller,
645                   enum ofp_version ofp_version OVS_UNUSED,
646                   struct ofpbuf *out)
647 {
648     struct nx_action_controller *nac;
649
650     nac = put_NXAST_CONTROLLER(out);
651     nac->max_len = htons(controller->max_len);
652     nac->controller_id = htons(controller->controller_id);
653     nac->reason = controller->reason;
654 }
655
656 static char * OVS_WARN_UNUSED_RESULT
657 parse_CONTROLLER(char *arg, struct ofpbuf *ofpacts,
658                   enum ofputil_protocol *usable_protocols OVS_UNUSED)
659 {
660     enum ofp_packet_in_reason reason = OFPR_ACTION;
661     uint16_t controller_id = 0;
662     uint16_t max_len = UINT16_MAX;
663
664     if (!arg[0]) {
665         /* Use defaults. */
666     } else if (strspn(arg, "0123456789") == strlen(arg)) {
667         char *error = str_to_u16(arg, "max_len", &max_len);
668         if (error) {
669             return error;
670         }
671     } else {
672         char *name, *value;
673
674         while (ofputil_parse_key_value(&arg, &name, &value)) {
675             if (!strcmp(name, "reason")) {
676                 if (!ofputil_packet_in_reason_from_string(value, &reason)) {
677                     return xasprintf("unknown reason \"%s\"", value);
678                 }
679             } else if (!strcmp(name, "max_len")) {
680                 char *error = str_to_u16(value, "max_len", &max_len);
681                 if (error) {
682                     return error;
683                 }
684             } else if (!strcmp(name, "id")) {
685                 char *error = str_to_u16(value, "id", &controller_id);
686                 if (error) {
687                     return error;
688                 }
689             } else {
690                 return xasprintf("unknown key \"%s\" parsing controller "
691                                  "action", name);
692             }
693         }
694     }
695
696     if (reason == OFPR_ACTION && controller_id == 0) {
697         struct ofpact_output *output;
698
699         output = ofpact_put_OUTPUT(ofpacts);
700         output->port = OFPP_CONTROLLER;
701         output->max_len = max_len;
702     } else {
703         struct ofpact_controller *controller;
704
705         controller = ofpact_put_CONTROLLER(ofpacts);
706         controller->max_len = max_len;
707         controller->reason = reason;
708         controller->controller_id = controller_id;
709     }
710
711     return NULL;
712 }
713
714 static void
715 format_CONTROLLER(const struct ofpact_controller *a, struct ds *s)
716 {
717     if (a->reason == OFPR_ACTION && a->controller_id == 0) {
718         ds_put_format(s, "CONTROLLER:%"PRIu16, a->max_len);
719     } else {
720         enum ofp_packet_in_reason reason = a->reason;
721
722         ds_put_cstr(s, "controller(");
723         if (reason != OFPR_ACTION) {
724             char reasonbuf[OFPUTIL_PACKET_IN_REASON_BUFSIZE];
725
726             ds_put_format(s, "reason=%s,",
727                           ofputil_packet_in_reason_to_string(
728                               reason, reasonbuf, sizeof reasonbuf));
729         }
730         if (a->max_len != UINT16_MAX) {
731             ds_put_format(s, "max_len=%"PRIu16",", a->max_len);
732         }
733         if (a->controller_id != 0) {
734             ds_put_format(s, "id=%"PRIu16",", a->controller_id);
735         }
736         ds_chomp(s, ',');
737         ds_put_char(s, ')');
738     }
739 }
740 \f
741 /* Enqueue action. */
742 struct ofp10_action_enqueue {
743     ovs_be16 type;            /* OFPAT10_ENQUEUE. */
744     ovs_be16 len;             /* Len is 16. */
745     ovs_be16 port;            /* Port that queue belongs. Should
746                                  refer to a valid physical port
747                                  (i.e. < OFPP_MAX) or OFPP_IN_PORT. */
748     uint8_t pad[6];           /* Pad for 64-bit alignment. */
749     ovs_be32 queue_id;        /* Where to enqueue the packets. */
750 };
751 OFP_ASSERT(sizeof(struct ofp10_action_enqueue) == 16);
752
753 static enum ofperr
754 decode_OFPAT_RAW10_ENQUEUE(const struct ofp10_action_enqueue *oae,
755                            enum ofp_version ofp_version OVS_UNUSED,
756                            struct ofpbuf *out)
757 {
758     struct ofpact_enqueue *enqueue;
759
760     enqueue = ofpact_put_ENQUEUE(out);
761     enqueue->port = u16_to_ofp(ntohs(oae->port));
762     enqueue->queue = ntohl(oae->queue_id);
763     if (ofp_to_u16(enqueue->port) >= ofp_to_u16(OFPP_MAX)
764         && enqueue->port != OFPP_IN_PORT
765         && enqueue->port != OFPP_LOCAL) {
766         return OFPERR_OFPBAC_BAD_OUT_PORT;
767     }
768     return 0;
769 }
770
771 static void
772 encode_ENQUEUE(const struct ofpact_enqueue *enqueue,
773                enum ofp_version ofp_version, struct ofpbuf *out)
774 {
775     if (ofp_version == OFP10_VERSION) {
776         struct ofp10_action_enqueue *oae;
777
778         oae = put_OFPAT10_ENQUEUE(out);
779         oae->port = htons(ofp_to_u16(enqueue->port));
780         oae->queue_id = htonl(enqueue->queue);
781     } else {
782         /* XXX */
783     }
784 }
785
786 static char * OVS_WARN_UNUSED_RESULT
787 parse_ENQUEUE(char *arg, struct ofpbuf *ofpacts,
788               enum ofputil_protocol *usable_protocols OVS_UNUSED)
789 {
790     char *sp = NULL;
791     char *port = strtok_r(arg, ":q,", &sp);
792     char *queue = strtok_r(NULL, "", &sp);
793     struct ofpact_enqueue *enqueue;
794
795     if (port == NULL || queue == NULL) {
796         return xstrdup("\"enqueue\" syntax is \"enqueue:PORT:QUEUE\" or "
797                        "\"enqueue(PORT,QUEUE)\"");
798     }
799
800     enqueue = ofpact_put_ENQUEUE(ofpacts);
801     if (!ofputil_port_from_string(port, &enqueue->port)) {
802         return xasprintf("%s: enqueue to unknown port", port);
803     }
804     return str_to_u32(queue, &enqueue->queue);
805 }
806
807 static void
808 format_ENQUEUE(const struct ofpact_enqueue *a, struct ds *s)
809 {
810     ds_put_format(s, "enqueue:");
811     ofputil_format_port(a->port, s);
812     ds_put_format(s, ":%"PRIu32, a->queue);
813 }
814 \f
815 /* Action structure for NXAST_OUTPUT_REG.
816  *
817  * Outputs to the OpenFlow port number written to src[ofs:ofs+nbits].
818  *
819  * The format and semantics of 'src' and 'ofs_nbits' are similar to those for
820  * the NXAST_REG_LOAD action.
821  *
822  * The acceptable nxm_header values for 'src' are the same as the acceptable
823  * nxm_header values for the 'src' field of NXAST_REG_MOVE.
824  *
825  * The 'max_len' field indicates the number of bytes to send when the chosen
826  * port is OFPP_CONTROLLER.  Its semantics are equivalent to the 'max_len'
827  * field of OFPAT_OUTPUT.
828  *
829  * The 'zero' field is required to be zeroed for forward compatibility. */
830 struct nx_action_output_reg {
831     ovs_be16 type;              /* OFPAT_VENDOR. */
832     ovs_be16 len;               /* 24. */
833     ovs_be32 vendor;            /* NX_VENDOR_ID. */
834     ovs_be16 subtype;           /* NXAST_OUTPUT_REG. */
835
836     ovs_be16 ofs_nbits;         /* (ofs << 6) | (n_bits - 1). */
837     ovs_be32 src;               /* Source. */
838
839     ovs_be16 max_len;           /* Max length to send to controller. */
840
841     uint8_t zero[6];            /* Reserved, must be zero. */
842 };
843 OFP_ASSERT(sizeof(struct nx_action_output_reg) == 24);
844
845 /* Action structure for NXAST_OUTPUT_REG2.
846  *
847  * Like the NXAST_OUTPUT_REG but organized so that there is room for a 64-bit
848  * experimenter OXM as 'src'.
849  */
850 struct nx_action_output_reg2 {
851     ovs_be16 type;              /* OFPAT_VENDOR. */
852     ovs_be16 len;               /* 24. */
853     ovs_be32 vendor;            /* NX_VENDOR_ID. */
854     ovs_be16 subtype;           /* NXAST_OUTPUT_REG2. */
855
856     ovs_be16 ofs_nbits;         /* (ofs << 6) | (n_bits - 1). */
857     ovs_be16 max_len;           /* Max length to send to controller. */
858
859     /* Followed by:
860      * - 'src', as an OXM/NXM header (either 4 or 8 bytes).
861      * - Enough 0-bytes to pad the action out to 24 bytes. */
862     uint8_t pad[10];
863 };
864 OFP_ASSERT(sizeof(struct nx_action_output_reg2) == 24);
865
866 static enum ofperr
867 decode_NXAST_RAW_OUTPUT_REG(const struct nx_action_output_reg *naor,
868                             enum ofp_version ofp_version OVS_UNUSED,
869                             struct ofpbuf *out)
870 {
871     struct ofpact_output_reg *output_reg;
872
873     if (!is_all_zeros(naor->zero, sizeof naor->zero)) {
874         return OFPERR_OFPBAC_BAD_ARGUMENT;
875     }
876
877     output_reg = ofpact_put_OUTPUT_REG(out);
878     output_reg->ofpact.raw = NXAST_RAW_OUTPUT_REG;
879     output_reg->src.field = mf_from_nxm_header(ntohl(naor->src));
880     output_reg->src.ofs = nxm_decode_ofs(naor->ofs_nbits);
881     output_reg->src.n_bits = nxm_decode_n_bits(naor->ofs_nbits);
882     output_reg->max_len = ntohs(naor->max_len);
883
884     return mf_check_src(&output_reg->src, NULL);
885 }
886
887 static enum ofperr
888 decode_NXAST_RAW_OUTPUT_REG2(const struct nx_action_output_reg2 *naor,
889                              enum ofp_version ofp_version OVS_UNUSED,
890                              struct ofpbuf *out)
891 {
892     struct ofpact_output_reg *output_reg;
893     enum ofperr error;
894     struct ofpbuf b;
895
896     output_reg = ofpact_put_OUTPUT_REG(out);
897     output_reg->ofpact.raw = NXAST_RAW_OUTPUT_REG2;
898     output_reg->src.ofs = nxm_decode_ofs(naor->ofs_nbits);
899     output_reg->src.n_bits = nxm_decode_n_bits(naor->ofs_nbits);
900     output_reg->max_len = ntohs(naor->max_len);
901
902     ofpbuf_use_const(&b, naor, ntohs(naor->len));
903     ofpbuf_pull(&b, OBJECT_OFFSETOF(naor, pad));
904     error = nx_pull_header(&b, &output_reg->src.field, NULL);
905     if (error) {
906         return error;
907     }
908     if (!is_all_zeros(b.data, b.size)) {
909         return OFPERR_NXBRC_MUST_BE_ZERO;
910     }
911
912     return mf_check_src(&output_reg->src, NULL);
913 }
914
915 static void
916 encode_OUTPUT_REG(const struct ofpact_output_reg *output_reg,
917                   enum ofp_version ofp_version OVS_UNUSED,
918                   struct ofpbuf *out)
919 {
920     /* If 'output_reg' came in as an NXAST_RAW_OUTPUT_REG2 action, or if it
921      * cannot be encoded in the older form, encode it as
922      * NXAST_RAW_OUTPUT_REG2. */
923     if (output_reg->ofpact.raw == NXAST_RAW_OUTPUT_REG2
924         || !mf_nxm_header(output_reg->src.field->id)) {
925         struct nx_action_output_reg2 *naor = put_NXAST_OUTPUT_REG2(out);
926         size_t size = out->size;
927
928         naor->ofs_nbits = nxm_encode_ofs_nbits(output_reg->src.ofs,
929                                                output_reg->src.n_bits);
930         naor->max_len = htons(output_reg->max_len);
931
932         out->size = size - sizeof naor->pad;
933         nx_put_header(out, output_reg->src.field->id, 0, false);
934         out->size = size;
935     } else {
936         struct nx_action_output_reg *naor = put_NXAST_OUTPUT_REG(out);
937
938         naor->ofs_nbits = nxm_encode_ofs_nbits(output_reg->src.ofs,
939                                                output_reg->src.n_bits);
940         naor->src = htonl(mf_nxm_header(output_reg->src.field->id));
941         naor->max_len = htons(output_reg->max_len);
942     }
943 }
944
945 static char * OVS_WARN_UNUSED_RESULT
946 parse_OUTPUT_REG(const char *arg, struct ofpbuf *ofpacts,
947                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
948 {
949     return parse_OUTPUT(arg, ofpacts, usable_protocols);
950 }
951
952 static void
953 format_OUTPUT_REG(const struct ofpact_output_reg *a, struct ds *s)
954 {
955     ds_put_cstr(s, "output:");
956     mf_format_subfield(&a->src, s);
957 }
958 \f
959 /* Action structure for NXAST_BUNDLE and NXAST_BUNDLE_LOAD.
960  *
961  * The bundle actions choose a slave from a supplied list of options.
962  * NXAST_BUNDLE outputs to its selection.  NXAST_BUNDLE_LOAD writes its
963  * selection to a register.
964  *
965  * The list of possible slaves follows the nx_action_bundle structure. The size
966  * of each slave is governed by its type as indicated by the 'slave_type'
967  * parameter. The list of slaves should be padded at its end with zeros to make
968  * the total length of the action a multiple of 8.
969  *
970  * Switches infer from the 'slave_type' parameter the size of each slave.  All
971  * implementations must support the NXM_OF_IN_PORT 'slave_type' which indicates
972  * that the slaves are OpenFlow port numbers with NXM_LENGTH(NXM_OF_IN_PORT) ==
973  * 2 byte width.  Switches should reject actions which indicate unknown or
974  * unsupported slave types.
975  *
976  * Switches use a strategy dictated by the 'algorithm' parameter to choose a
977  * slave.  If the switch does not support the specified 'algorithm' parameter,
978  * it should reject the action.
979  *
980  * Several algorithms take into account liveness when selecting slaves.  The
981  * liveness of a slave is implementation defined (with one exception), but will
982  * generally take into account things like its carrier status and the results
983  * of any link monitoring protocols which happen to be running on it.  In order
984  * to give controllers a place-holder value, the OFPP_NONE port is always
985  * considered live.
986  *
987  * Some slave selection strategies require the use of a hash function, in which
988  * case the 'fields' and 'basis' parameters should be populated.  The 'fields'
989  * parameter (one of NX_HASH_FIELDS_*) designates which parts of the flow to
990  * hash.  Refer to the definition of "enum nx_hash_fields" for details.  The
991  * 'basis' parameter is used as a universal hash parameter.  Different values
992  * of 'basis' yield different hash results.
993  *
994  * The 'zero' parameter at the end of the action structure is reserved for
995  * future use.  Switches are required to reject actions which have nonzero
996  * bytes in the 'zero' field.
997  *
998  * NXAST_BUNDLE actions should have 'ofs_nbits' and 'dst' zeroed.  Switches
999  * should reject actions which have nonzero bytes in either of these fields.
1000  *
1001  * NXAST_BUNDLE_LOAD stores the OpenFlow port number of the selected slave in
1002  * dst[ofs:ofs+n_bits].  The format and semantics of 'dst' and 'ofs_nbits' are
1003  * similar to those for the NXAST_REG_LOAD action. */
1004 struct nx_action_bundle {
1005     ovs_be16 type;              /* OFPAT_VENDOR. */
1006     ovs_be16 len;               /* Length including slaves. */
1007     ovs_be32 vendor;            /* NX_VENDOR_ID. */
1008     ovs_be16 subtype;           /* NXAST_BUNDLE or NXAST_BUNDLE_LOAD. */
1009
1010     /* Slave choice algorithm to apply to hash value. */
1011     ovs_be16 algorithm;         /* One of NX_BD_ALG_*. */
1012
1013     /* What fields to hash and how. */
1014     ovs_be16 fields;            /* One of NX_HASH_FIELDS_*. */
1015     ovs_be16 basis;             /* Universal hash parameter. */
1016
1017     ovs_be32 slave_type;        /* NXM_OF_IN_PORT. */
1018     ovs_be16 n_slaves;          /* Number of slaves. */
1019
1020     ovs_be16 ofs_nbits;         /* (ofs << 6) | (n_bits - 1). */
1021     ovs_be32 dst;               /* Destination. */
1022
1023     uint8_t zero[4];            /* Reserved. Must be zero. */
1024 };
1025 OFP_ASSERT(sizeof(struct nx_action_bundle) == 32);
1026
1027 static enum ofperr
1028 decode_bundle(bool load, const struct nx_action_bundle *nab,
1029               struct ofpbuf *ofpacts)
1030 {
1031     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1032     struct ofpact_bundle *bundle;
1033     uint32_t slave_type;
1034     size_t slaves_size, i;
1035     enum ofperr error;
1036
1037     bundle = ofpact_put_BUNDLE(ofpacts);
1038
1039     bundle->n_slaves = ntohs(nab->n_slaves);
1040     bundle->basis = ntohs(nab->basis);
1041     bundle->fields = ntohs(nab->fields);
1042     bundle->algorithm = ntohs(nab->algorithm);
1043     slave_type = ntohl(nab->slave_type);
1044     slaves_size = ntohs(nab->len) - sizeof *nab;
1045
1046     error = OFPERR_OFPBAC_BAD_ARGUMENT;
1047     if (!flow_hash_fields_valid(bundle->fields)) {
1048         VLOG_WARN_RL(&rl, "unsupported fields %d", (int) bundle->fields);
1049     } else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) {
1050         VLOG_WARN_RL(&rl, "too many slaves");
1051     } else if (bundle->algorithm != NX_BD_ALG_HRW
1052                && bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) {
1053         VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) bundle->algorithm);
1054     } else if (slave_type != mf_nxm_header(MFF_IN_PORT)) {
1055         VLOG_WARN_RL(&rl, "unsupported slave type %"PRIu16, slave_type);
1056     } else {
1057         error = 0;
1058     }
1059
1060     if (!is_all_zeros(nab->zero, sizeof nab->zero)) {
1061         VLOG_WARN_RL(&rl, "reserved field is nonzero");
1062         error = OFPERR_OFPBAC_BAD_ARGUMENT;
1063     }
1064
1065     if (load) {
1066         bundle->dst.field = mf_from_nxm_header(ntohl(nab->dst));
1067         bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits);
1068         bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits);
1069
1070         if (bundle->dst.n_bits < 16) {
1071             VLOG_WARN_RL(&rl, "bundle_load action requires at least 16 bit "
1072                          "destination.");
1073             error = OFPERR_OFPBAC_BAD_ARGUMENT;
1074         }
1075     } else {
1076         if (nab->ofs_nbits || nab->dst) {
1077             VLOG_WARN_RL(&rl, "bundle action has nonzero reserved fields");
1078             error = OFPERR_OFPBAC_BAD_ARGUMENT;
1079         }
1080     }
1081
1082     if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) {
1083         VLOG_WARN_RL(&rl, "Nicira action %s only has %"PRIuSIZE" bytes "
1084                      "allocated for slaves.  %"PRIuSIZE" bytes are required "
1085                      "for %"PRIu16" slaves.",
1086                      load ? "bundle_load" : "bundle", slaves_size,
1087                      bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves);
1088         error = OFPERR_OFPBAC_BAD_LEN;
1089     }
1090
1091     for (i = 0; i < bundle->n_slaves; i++) {
1092         uint16_t ofp_port = ntohs(((ovs_be16 *)(nab + 1))[i]);
1093         ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);
1094     }
1095
1096     bundle = ofpacts->header;
1097     ofpact_update_len(ofpacts, &bundle->ofpact);
1098
1099     if (!error) {
1100         error = bundle_check(bundle, OFPP_MAX, NULL);
1101     }
1102     return error;
1103 }
1104
1105 static enum ofperr
1106 decode_NXAST_RAW_BUNDLE(const struct nx_action_bundle *nab,
1107                         enum ofp_version ofp_version OVS_UNUSED,
1108                         struct ofpbuf *out)
1109 {
1110     return decode_bundle(false, nab, out);
1111 }
1112
1113 static enum ofperr
1114 decode_NXAST_RAW_BUNDLE_LOAD(const struct nx_action_bundle *nab,
1115                              enum ofp_version ofp_version OVS_UNUSED,
1116                              struct ofpbuf *out)
1117 {
1118     return decode_bundle(true, nab, out);
1119 }
1120
1121 static void
1122 encode_BUNDLE(const struct ofpact_bundle *bundle,
1123               enum ofp_version ofp_version OVS_UNUSED,
1124               struct ofpbuf *out)
1125 {
1126     int slaves_len = ROUND_UP(2 * bundle->n_slaves, OFP_ACTION_ALIGN);
1127     struct nx_action_bundle *nab;
1128     ovs_be16 *slaves;
1129     size_t i;
1130
1131     nab = (bundle->dst.field
1132            ? put_NXAST_BUNDLE_LOAD(out)
1133            : put_NXAST_BUNDLE(out));
1134     nab->len = htons(ntohs(nab->len) + slaves_len);
1135     nab->algorithm = htons(bundle->algorithm);
1136     nab->fields = htons(bundle->fields);
1137     nab->basis = htons(bundle->basis);
1138     nab->slave_type = htonl(mf_nxm_header(MFF_IN_PORT));
1139     nab->n_slaves = htons(bundle->n_slaves);
1140     if (bundle->dst.field) {
1141         nab->ofs_nbits = nxm_encode_ofs_nbits(bundle->dst.ofs,
1142                                               bundle->dst.n_bits);
1143         nab->dst = htonl(mf_nxm_header(bundle->dst.field->id));
1144     }
1145
1146     slaves = ofpbuf_put_zeros(out, slaves_len);
1147     for (i = 0; i < bundle->n_slaves; i++) {
1148         slaves[i] = htons(ofp_to_u16(bundle->slaves[i]));
1149     }
1150 }
1151
1152 static char * OVS_WARN_UNUSED_RESULT
1153 parse_BUNDLE(const char *arg, struct ofpbuf *ofpacts,
1154              enum ofputil_protocol *usable_protocols OVS_UNUSED)
1155 {
1156     return bundle_parse(arg, ofpacts);
1157 }
1158
1159 static char * OVS_WARN_UNUSED_RESULT
1160 parse_bundle_load(const char *arg, struct ofpbuf *ofpacts)
1161 {
1162     return bundle_parse_load(arg, ofpacts);
1163 }
1164
1165 static void
1166 format_BUNDLE(const struct ofpact_bundle *a, struct ds *s)
1167 {
1168     bundle_format(a, s);
1169 }
1170 \f
1171 /* Set VLAN actions. */
1172
1173 static enum ofperr
1174 decode_set_vlan_vid(uint16_t vid, bool push_vlan_if_needed, struct ofpbuf *out)
1175 {
1176     if (vid & ~0xfff) {
1177         return OFPERR_OFPBAC_BAD_ARGUMENT;
1178     } else {
1179         struct ofpact_vlan_vid *vlan_vid = ofpact_put_SET_VLAN_VID(out);
1180         vlan_vid->vlan_vid = vid;
1181         vlan_vid->push_vlan_if_needed = push_vlan_if_needed;
1182         return 0;
1183     }
1184 }
1185
1186 static enum ofperr
1187 decode_OFPAT_RAW10_SET_VLAN_VID(uint16_t vid,
1188                                 enum ofp_version ofp_version OVS_UNUSED,
1189                                 struct ofpbuf *out)
1190 {
1191     return decode_set_vlan_vid(vid, true, out);
1192 }
1193
1194 static enum ofperr
1195 decode_OFPAT_RAW11_SET_VLAN_VID(uint16_t vid,
1196                                 enum ofp_version ofp_version OVS_UNUSED,
1197                                 struct ofpbuf *out)
1198 {
1199     return decode_set_vlan_vid(vid, false, out);
1200 }
1201
1202 static void
1203 encode_SET_VLAN_VID(const struct ofpact_vlan_vid *vlan_vid,
1204                     enum ofp_version ofp_version, struct ofpbuf *out)
1205 {
1206     uint16_t vid = vlan_vid->vlan_vid;
1207
1208     /* Push a VLAN tag, if none is present and this form of the action calls
1209      * for such a feature. */
1210     if (ofp_version > OFP10_VERSION
1211         && vlan_vid->push_vlan_if_needed
1212         && !vlan_vid->flow_has_vlan) {
1213         put_OFPAT11_PUSH_VLAN(out, htons(ETH_TYPE_VLAN_8021Q));
1214     }
1215
1216     if (ofp_version == OFP10_VERSION) {
1217         put_OFPAT10_SET_VLAN_VID(out, vid);
1218     } else if (ofp_version == OFP11_VERSION) {
1219         put_OFPAT11_SET_VLAN_VID(out, vid);
1220     } else {
1221         ofpact_put_set_field(out, ofp_version,
1222                              MFF_VLAN_VID, vid | OFPVID12_PRESENT);
1223     }
1224 }
1225
1226 static char * OVS_WARN_UNUSED_RESULT
1227 parse_set_vlan_vid(char *arg, struct ofpbuf *ofpacts, bool push_vlan_if_needed)
1228 {
1229     struct ofpact_vlan_vid *vlan_vid;
1230     uint16_t vid;
1231     char *error;
1232
1233     error = str_to_u16(arg, "VLAN VID", &vid);
1234     if (error) {
1235         return error;
1236     }
1237
1238     if (vid & ~VLAN_VID_MASK) {
1239         return xasprintf("%s: not a valid VLAN VID", arg);
1240     }
1241     vlan_vid = ofpact_put_SET_VLAN_VID(ofpacts);
1242     vlan_vid->vlan_vid = vid;
1243     vlan_vid->push_vlan_if_needed = push_vlan_if_needed;
1244     return NULL;
1245 }
1246
1247 static char * OVS_WARN_UNUSED_RESULT
1248 parse_SET_VLAN_VID(char *arg, struct ofpbuf *ofpacts,
1249                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
1250 {
1251     return parse_set_vlan_vid(arg, ofpacts, false);
1252 }
1253
1254 static void
1255 format_SET_VLAN_VID(const struct ofpact_vlan_vid *a, struct ds *s)
1256 {
1257     ds_put_format(s, "%s:%"PRIu16,
1258                   a->push_vlan_if_needed ? "mod_vlan_vid" : "set_vlan_vid",
1259                   a->vlan_vid);
1260 }
1261 \f
1262 /* Set PCP actions. */
1263
1264 static enum ofperr
1265 decode_set_vlan_pcp(uint8_t pcp, bool push_vlan_if_needed, struct ofpbuf *out)
1266 {
1267     if (pcp & ~7) {
1268         return OFPERR_OFPBAC_BAD_ARGUMENT;
1269     } else {
1270         struct ofpact_vlan_pcp *vlan_pcp = ofpact_put_SET_VLAN_PCP(out);
1271         vlan_pcp->vlan_pcp = pcp;
1272         vlan_pcp->push_vlan_if_needed = push_vlan_if_needed;
1273         return 0;
1274     }
1275 }
1276
1277 static enum ofperr
1278 decode_OFPAT_RAW10_SET_VLAN_PCP(uint8_t pcp,
1279                                 enum ofp_version ofp_version OVS_UNUSED,
1280                                 struct ofpbuf *out)
1281 {
1282     return decode_set_vlan_pcp(pcp, true, out);
1283 }
1284
1285 static enum ofperr
1286 decode_OFPAT_RAW11_SET_VLAN_PCP(uint8_t pcp,
1287                                 enum ofp_version ofp_version OVS_UNUSED,
1288                                 struct ofpbuf *out)
1289 {
1290     return decode_set_vlan_pcp(pcp, false, out);
1291 }
1292
1293 static void
1294 encode_SET_VLAN_PCP(const struct ofpact_vlan_pcp *vlan_pcp,
1295                     enum ofp_version ofp_version, struct ofpbuf *out)
1296 {
1297     uint8_t pcp = vlan_pcp->vlan_pcp;
1298
1299     /* Push a VLAN tag, if none is present and this form of the action calls
1300      * for such a feature. */
1301     if (ofp_version > OFP10_VERSION
1302         && vlan_pcp->push_vlan_if_needed
1303         && !vlan_pcp->flow_has_vlan) {
1304         put_OFPAT11_PUSH_VLAN(out, htons(ETH_TYPE_VLAN_8021Q));
1305     }
1306
1307     if (ofp_version == OFP10_VERSION) {
1308         put_OFPAT10_SET_VLAN_PCP(out, pcp);
1309     } else if (ofp_version == OFP11_VERSION) {
1310         put_OFPAT11_SET_VLAN_PCP(out, pcp);
1311     } else {
1312         ofpact_put_set_field(out, ofp_version, MFF_VLAN_PCP, pcp);
1313     }
1314 }
1315
1316 static char * OVS_WARN_UNUSED_RESULT
1317 parse_set_vlan_pcp(char *arg, struct ofpbuf *ofpacts, bool push_vlan_if_needed)
1318 {
1319     struct ofpact_vlan_pcp *vlan_pcp;
1320     uint8_t pcp;
1321     char *error;
1322
1323     error = str_to_u8(arg, "VLAN PCP", &pcp);
1324     if (error) {
1325         return error;
1326     }
1327
1328     if (pcp & ~7) {
1329         return xasprintf("%s: not a valid VLAN PCP", arg);
1330     }
1331     vlan_pcp = ofpact_put_SET_VLAN_PCP(ofpacts);
1332     vlan_pcp->vlan_pcp = pcp;
1333     vlan_pcp->push_vlan_if_needed = push_vlan_if_needed;
1334     return NULL;
1335 }
1336
1337 static char * OVS_WARN_UNUSED_RESULT
1338 parse_SET_VLAN_PCP(char *arg, struct ofpbuf *ofpacts,
1339                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
1340 {
1341     return parse_set_vlan_pcp(arg, ofpacts, false);
1342 }
1343
1344 static void
1345 format_SET_VLAN_PCP(const struct ofpact_vlan_pcp *a, struct ds *s)
1346 {
1347     ds_put_format(s, "%s:%"PRIu8,
1348                   a->push_vlan_if_needed ? "mod_vlan_pcp" : "set_vlan_pcp",
1349                   a->vlan_pcp);
1350 }
1351 \f
1352 /* Strip VLAN actions. */
1353
1354 static enum ofperr
1355 decode_OFPAT_RAW10_STRIP_VLAN(struct ofpbuf *out)
1356 {
1357     ofpact_put_STRIP_VLAN(out)->ofpact.raw = OFPAT_RAW10_STRIP_VLAN;
1358     return 0;
1359 }
1360
1361 static enum ofperr
1362 decode_OFPAT_RAW11_POP_VLAN(struct ofpbuf *out)
1363 {
1364     ofpact_put_STRIP_VLAN(out)->ofpact.raw = OFPAT_RAW11_POP_VLAN;
1365     return 0;
1366 }
1367
1368 static void
1369 encode_STRIP_VLAN(const struct ofpact_null *null OVS_UNUSED,
1370                   enum ofp_version ofp_version, struct ofpbuf *out)
1371 {
1372     if (ofp_version == OFP10_VERSION) {
1373         put_OFPAT10_STRIP_VLAN(out);
1374     } else {
1375         put_OFPAT11_POP_VLAN(out);
1376     }
1377 }
1378
1379 static char * OVS_WARN_UNUSED_RESULT
1380 parse_STRIP_VLAN(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
1381                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
1382 {
1383     ofpact_put_STRIP_VLAN(ofpacts)->ofpact.raw = OFPAT_RAW10_STRIP_VLAN;
1384     return NULL;
1385 }
1386
1387 static char * OVS_WARN_UNUSED_RESULT
1388 parse_pop_vlan(struct ofpbuf *ofpacts)
1389 {
1390     ofpact_put_STRIP_VLAN(ofpacts)->ofpact.raw = OFPAT_RAW11_POP_VLAN;
1391     return NULL;
1392 }
1393
1394 static void
1395 format_STRIP_VLAN(const struct ofpact_null *a, struct ds *s)
1396 {
1397     ds_put_cstr(s, (a->ofpact.raw == OFPAT_RAW11_POP_VLAN
1398                     ? "pop_vlan"
1399                     : "strip_vlan"));
1400 }
1401 \f
1402 /* Push VLAN action. */
1403
1404 static enum ofperr
1405 decode_OFPAT_RAW11_PUSH_VLAN(ovs_be16 eth_type,
1406                              enum ofp_version ofp_version OVS_UNUSED,
1407                              struct ofpbuf *out)
1408 {
1409     if (eth_type != htons(ETH_TYPE_VLAN_8021Q)) {
1410         /* XXX 802.1AD(QinQ) isn't supported at the moment */
1411         return OFPERR_OFPBAC_BAD_ARGUMENT;
1412     }
1413     ofpact_put_PUSH_VLAN(out);
1414     return 0;
1415 }
1416
1417 static void
1418 encode_PUSH_VLAN(const struct ofpact_null *null OVS_UNUSED,
1419                  enum ofp_version ofp_version, struct ofpbuf *out)
1420 {
1421     if (ofp_version == OFP10_VERSION) {
1422         /* PUSH is a side effect of a SET_VLAN_VID/PCP, which should
1423          * follow this action. */
1424     } else {
1425         /* XXX ETH_TYPE_VLAN_8021AD case */
1426         put_OFPAT11_PUSH_VLAN(out, htons(ETH_TYPE_VLAN_8021Q));
1427     }
1428 }
1429
1430 static char * OVS_WARN_UNUSED_RESULT
1431 parse_PUSH_VLAN(char *arg, struct ofpbuf *ofpacts,
1432                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
1433 {
1434     uint16_t ethertype;
1435     char *error;
1436
1437     *usable_protocols &= OFPUTIL_P_OF11_UP;
1438     error = str_to_u16(arg, "ethertype", &ethertype);
1439     if (error) {
1440         return error;
1441     }
1442
1443     if (ethertype != ETH_TYPE_VLAN_8021Q) {
1444         /* XXX ETH_TYPE_VLAN_8021AD case isn't supported */
1445         return xasprintf("%s: not a valid VLAN ethertype", arg);
1446     }
1447
1448     ofpact_put_PUSH_VLAN(ofpacts);
1449     return NULL;
1450 }
1451
1452 static void
1453 format_PUSH_VLAN(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
1454 {
1455     /* XXX 802.1AD case*/
1456     ds_put_format(s, "push_vlan:%#"PRIx16, ETH_TYPE_VLAN_8021Q);
1457 }
1458 \f
1459 /* Action structure for OFPAT10_SET_DL_SRC/DST and OFPAT11_SET_DL_SRC/DST. */
1460 struct ofp_action_dl_addr {
1461     ovs_be16 type;                  /* Type. */
1462     ovs_be16 len;                   /* Length is 16. */
1463     struct eth_addr dl_addr;        /* Ethernet address. */
1464     uint8_t pad[6];
1465 };
1466 OFP_ASSERT(sizeof(struct ofp_action_dl_addr) == 16);
1467
1468 static enum ofperr
1469 decode_OFPAT_RAW_SET_DL_SRC(const struct ofp_action_dl_addr *a,
1470                             enum ofp_version ofp_version OVS_UNUSED,
1471                             struct ofpbuf *out)
1472 {
1473     ofpact_put_SET_ETH_SRC(out)->mac = a->dl_addr;
1474     return 0;
1475 }
1476
1477 static enum ofperr
1478 decode_OFPAT_RAW_SET_DL_DST(const struct ofp_action_dl_addr *a,
1479                             enum ofp_version ofp_version OVS_UNUSED,
1480                             struct ofpbuf *out)
1481 {
1482     ofpact_put_SET_ETH_DST(out)->mac = a->dl_addr;
1483     return 0;
1484 }
1485
1486 static void
1487 encode_SET_ETH_addr(const struct ofpact_mac *mac, enum ofp_version ofp_version,
1488                     enum ofp_raw_action_type raw, enum mf_field_id field,
1489                     struct ofpbuf *out)
1490 {
1491     if (ofp_version < OFP12_VERSION) {
1492         struct ofp_action_dl_addr *oada;
1493
1494         oada = ofpact_put_raw(out, ofp_version, raw, 0);
1495         oada->dl_addr = mac->mac;
1496     } else {
1497         ofpact_put_set_field(out, ofp_version, field,
1498                              eth_addr_to_uint64(mac->mac));
1499     }
1500 }
1501
1502 static void
1503 encode_SET_ETH_SRC(const struct ofpact_mac *mac, enum ofp_version ofp_version,
1504                    struct ofpbuf *out)
1505 {
1506     encode_SET_ETH_addr(mac, ofp_version, OFPAT_RAW_SET_DL_SRC, MFF_ETH_SRC,
1507                         out);
1508
1509 }
1510
1511 static void
1512 encode_SET_ETH_DST(const struct ofpact_mac *mac,
1513                                enum ofp_version ofp_version,
1514                                struct ofpbuf *out)
1515 {
1516     encode_SET_ETH_addr(mac, ofp_version, OFPAT_RAW_SET_DL_DST, MFF_ETH_DST,
1517                         out);
1518
1519 }
1520
1521 static char * OVS_WARN_UNUSED_RESULT
1522 parse_SET_ETH_SRC(char *arg, struct ofpbuf *ofpacts,
1523                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
1524 {
1525     return str_to_mac(arg, &ofpact_put_SET_ETH_SRC(ofpacts)->mac);
1526 }
1527
1528 static char * OVS_WARN_UNUSED_RESULT
1529 parse_SET_ETH_DST(char *arg, struct ofpbuf *ofpacts,
1530                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
1531 {
1532     return str_to_mac(arg, &ofpact_put_SET_ETH_DST(ofpacts)->mac);
1533 }
1534
1535 static void
1536 format_SET_ETH_SRC(const struct ofpact_mac *a, struct ds *s)
1537 {
1538     ds_put_format(s, "mod_dl_src:"ETH_ADDR_FMT, ETH_ADDR_ARGS(a->mac));
1539 }
1540
1541 static void
1542 format_SET_ETH_DST(const struct ofpact_mac *a, struct ds *s)
1543 {
1544     ds_put_format(s, "mod_dl_dst:"ETH_ADDR_FMT, ETH_ADDR_ARGS(a->mac));
1545 }
1546 \f
1547 /* Set IPv4 address actions. */
1548
1549 static enum ofperr
1550 decode_OFPAT_RAW_SET_NW_SRC(ovs_be32 ipv4,
1551                             enum ofp_version ofp_version OVS_UNUSED,
1552                             struct ofpbuf *out)
1553 {
1554     ofpact_put_SET_IPV4_SRC(out)->ipv4 = ipv4;
1555     return 0;
1556 }
1557
1558 static enum ofperr
1559 decode_OFPAT_RAW_SET_NW_DST(ovs_be32 ipv4,
1560                             enum ofp_version ofp_version OVS_UNUSED,
1561                             struct ofpbuf *out)
1562 {
1563     ofpact_put_SET_IPV4_DST(out)->ipv4 = ipv4;
1564     return 0;
1565 }
1566
1567 static void
1568 encode_SET_IPV4_addr(const struct ofpact_ipv4 *ipv4,
1569                      enum ofp_version ofp_version,
1570                      enum ofp_raw_action_type raw, enum mf_field_id field,
1571                      struct ofpbuf *out)
1572 {
1573     ovs_be32 addr = ipv4->ipv4;
1574     if (ofp_version < OFP12_VERSION) {
1575         ofpact_put_raw(out, ofp_version, raw, ntohl(addr));
1576     } else {
1577         ofpact_put_set_field(out, ofp_version, field, ntohl(addr));
1578     }
1579 }
1580
1581 static void
1582 encode_SET_IPV4_SRC(const struct ofpact_ipv4 *ipv4,
1583                     enum ofp_version ofp_version, struct ofpbuf *out)
1584 {
1585     encode_SET_IPV4_addr(ipv4, ofp_version, OFPAT_RAW_SET_NW_SRC, MFF_IPV4_SRC,
1586                          out);
1587 }
1588
1589 static void
1590 encode_SET_IPV4_DST(const struct ofpact_ipv4 *ipv4,
1591                     enum ofp_version ofp_version, struct ofpbuf *out)
1592 {
1593     encode_SET_IPV4_addr(ipv4, ofp_version, OFPAT_RAW_SET_NW_DST, MFF_IPV4_DST,
1594                          out);
1595 }
1596
1597 static char * OVS_WARN_UNUSED_RESULT
1598 parse_SET_IPV4_SRC(char *arg, struct ofpbuf *ofpacts,
1599                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
1600 {
1601     return str_to_ip(arg, &ofpact_put_SET_IPV4_SRC(ofpacts)->ipv4);
1602 }
1603
1604 static char * OVS_WARN_UNUSED_RESULT
1605 parse_SET_IPV4_DST(char *arg, struct ofpbuf *ofpacts,
1606                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
1607 {
1608     return str_to_ip(arg, &ofpact_put_SET_IPV4_DST(ofpacts)->ipv4);
1609 }
1610
1611 static void
1612 format_SET_IPV4_SRC(const struct ofpact_ipv4 *a, struct ds *s)
1613 {
1614     ds_put_format(s, "mod_nw_src:"IP_FMT, IP_ARGS(a->ipv4));
1615 }
1616
1617 static void
1618 format_SET_IPV4_DST(const struct ofpact_ipv4 *a, struct ds *s)
1619 {
1620     ds_put_format(s, "mod_nw_dst:"IP_FMT, IP_ARGS(a->ipv4));
1621 }
1622 \f
1623 /* Set IPv4/v6 TOS actions. */
1624
1625 static enum ofperr
1626 decode_OFPAT_RAW_SET_NW_TOS(uint8_t dscp,
1627                             enum ofp_version ofp_version OVS_UNUSED,
1628                             struct ofpbuf *out)
1629 {
1630     if (dscp & ~IP_DSCP_MASK) {
1631         return OFPERR_OFPBAC_BAD_ARGUMENT;
1632     } else {
1633         ofpact_put_SET_IP_DSCP(out)->dscp = dscp;
1634         return 0;
1635     }
1636 }
1637
1638 static void
1639 encode_SET_IP_DSCP(const struct ofpact_dscp *dscp,
1640                    enum ofp_version ofp_version, struct ofpbuf *out)
1641 {
1642     if (ofp_version < OFP12_VERSION) {
1643         put_OFPAT_SET_NW_TOS(out, ofp_version, dscp->dscp);
1644     } else {
1645         ofpact_put_set_field(out, ofp_version,
1646                              MFF_IP_DSCP_SHIFTED, dscp->dscp >> 2);
1647     }
1648 }
1649
1650 static char * OVS_WARN_UNUSED_RESULT
1651 parse_SET_IP_DSCP(char *arg, struct ofpbuf *ofpacts,
1652                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
1653 {
1654     uint8_t tos;
1655     char *error;
1656
1657     error = str_to_u8(arg, "TOS", &tos);
1658     if (error) {
1659         return error;
1660     }
1661
1662     if (tos & ~IP_DSCP_MASK) {
1663         return xasprintf("%s: not a valid TOS", arg);
1664     }
1665     ofpact_put_SET_IP_DSCP(ofpacts)->dscp = tos;
1666     return NULL;
1667 }
1668
1669 static void
1670 format_SET_IP_DSCP(const struct ofpact_dscp *a, struct ds *s)
1671 {
1672     ds_put_format(s, "mod_nw_tos:%d", a->dscp);
1673 }
1674 \f
1675 /* Set IPv4/v6 ECN actions. */
1676
1677 static enum ofperr
1678 decode_OFPAT_RAW11_SET_NW_ECN(uint8_t ecn,
1679                               enum ofp_version ofp_version OVS_UNUSED,
1680                               struct ofpbuf *out)
1681 {
1682     if (ecn & ~IP_ECN_MASK) {
1683         return OFPERR_OFPBAC_BAD_ARGUMENT;
1684     } else {
1685         ofpact_put_SET_IP_ECN(out)->ecn = ecn;
1686         return 0;
1687     }
1688 }
1689
1690 static void
1691 encode_SET_IP_ECN(const struct ofpact_ecn *ip_ecn,
1692                   enum ofp_version ofp_version, struct ofpbuf *out)
1693 {
1694     uint8_t ecn = ip_ecn->ecn;
1695     if (ofp_version == OFP10_VERSION) {
1696         /* XXX */
1697     } else if (ofp_version == OFP11_VERSION) {
1698         put_OFPAT11_SET_NW_ECN(out, ecn);
1699     } else {
1700         ofpact_put_set_field(out, ofp_version, MFF_IP_ECN, ecn);
1701     }
1702 }
1703
1704 static char * OVS_WARN_UNUSED_RESULT
1705 parse_SET_IP_ECN(char *arg, struct ofpbuf *ofpacts,
1706                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
1707 {
1708     uint8_t ecn;
1709     char *error;
1710
1711     error = str_to_u8(arg, "ECN", &ecn);
1712     if (error) {
1713         return error;
1714     }
1715
1716     if (ecn & ~IP_ECN_MASK) {
1717         return xasprintf("%s: not a valid ECN", arg);
1718     }
1719     ofpact_put_SET_IP_ECN(ofpacts)->ecn = ecn;
1720     return NULL;
1721 }
1722
1723 static void
1724 format_SET_IP_ECN(const struct ofpact_ecn *a, struct ds *s)
1725 {
1726     ds_put_format(s, "mod_nw_ecn:%d", a->ecn);
1727 }
1728 \f
1729 /* Set IPv4/v6 TTL actions. */
1730
1731 static enum ofperr
1732 decode_OFPAT_RAW11_SET_NW_TTL(uint8_t ttl,
1733                               enum ofp_version ofp_version OVS_UNUSED,
1734                               struct ofpbuf *out)
1735 {
1736     ofpact_put_SET_IP_TTL(out)->ttl = ttl;
1737     return 0;
1738 }
1739
1740 static void
1741 encode_SET_IP_TTL(const struct ofpact_ip_ttl *ttl,
1742                   enum ofp_version ofp_version, struct ofpbuf *out)
1743 {
1744     if (ofp_version >= OFP11_VERSION) {
1745         put_OFPAT11_SET_NW_TTL(out, ttl->ttl);
1746     } else {
1747         /* XXX */
1748     }
1749 }
1750
1751 static char * OVS_WARN_UNUSED_RESULT
1752 parse_SET_IP_TTL(char *arg, struct ofpbuf *ofpacts,
1753                   enum ofputil_protocol *usable_protocols OVS_UNUSED)
1754 {
1755     uint8_t ttl;
1756     char *error;
1757
1758     error = str_to_u8(arg, "TTL", &ttl);
1759     if (error) {
1760         return error;
1761     }
1762
1763     ofpact_put_SET_IP_TTL(ofpacts)->ttl = ttl;
1764     return NULL;
1765 }
1766
1767 static void
1768 format_SET_IP_TTL(const struct ofpact_ip_ttl *a, struct ds *s)
1769 {
1770     ds_put_format(s, "mod_nw_ttl:%d", a->ttl);
1771 }
1772 \f
1773 /* Set TCP/UDP/SCTP port actions. */
1774
1775 static enum ofperr
1776 decode_OFPAT_RAW_SET_TP_SRC(ovs_be16 port,
1777                             enum ofp_version ofp_version OVS_UNUSED,
1778                             struct ofpbuf *out)
1779 {
1780     ofpact_put_SET_L4_SRC_PORT(out)->port = ntohs(port);
1781     return 0;
1782 }
1783
1784 static enum ofperr
1785 decode_OFPAT_RAW_SET_TP_DST(ovs_be16 port,
1786                             enum ofp_version ofp_version OVS_UNUSED,
1787                             struct ofpbuf *out)
1788 {
1789     ofpact_put_SET_L4_DST_PORT(out)->port = ntohs(port);
1790     return 0;
1791 }
1792
1793 static void
1794 encode_SET_L4_port(const struct ofpact_l4_port *l4_port,
1795                    enum ofp_version ofp_version, enum ofp_raw_action_type raw,
1796                    enum mf_field_id field, struct ofpbuf *out)
1797 {
1798     uint16_t port = l4_port->port;
1799
1800     if (ofp_version >= OFP12_VERSION && field != MFF_N_IDS) {
1801         ofpact_put_set_field(out, ofp_version, field, port);
1802     } else {
1803         ofpact_put_raw(out, ofp_version, raw, port);
1804     }
1805 }
1806
1807 static void
1808 encode_SET_L4_SRC_PORT(const struct ofpact_l4_port *l4_port,
1809                        enum ofp_version ofp_version, struct ofpbuf *out)
1810 {
1811     uint8_t proto = l4_port->flow_ip_proto;
1812     enum mf_field_id field = (proto == IPPROTO_TCP ? MFF_TCP_SRC
1813                               : proto == IPPROTO_UDP ? MFF_UDP_SRC
1814                               : proto == IPPROTO_SCTP ? MFF_SCTP_SRC
1815                               : MFF_N_IDS);
1816
1817     encode_SET_L4_port(l4_port, ofp_version, OFPAT_RAW_SET_TP_SRC, field, out);
1818 }
1819
1820 static void
1821 encode_SET_L4_DST_PORT(const struct ofpact_l4_port *l4_port,
1822                        enum ofp_version ofp_version,
1823                        struct ofpbuf *out)
1824 {
1825     uint8_t proto = l4_port->flow_ip_proto;
1826     enum mf_field_id field = (proto == IPPROTO_TCP ? MFF_TCP_DST
1827                               : proto == IPPROTO_UDP ? MFF_UDP_DST
1828                               : proto == IPPROTO_SCTP ? MFF_SCTP_DST
1829                               : MFF_N_IDS);
1830
1831     encode_SET_L4_port(l4_port, ofp_version, OFPAT_RAW_SET_TP_DST, field, out);
1832 }
1833
1834 static char * OVS_WARN_UNUSED_RESULT
1835 parse_SET_L4_SRC_PORT(char *arg, struct ofpbuf *ofpacts,
1836                       enum ofputil_protocol *usable_protocols OVS_UNUSED)
1837 {
1838     return str_to_u16(arg, "source port",
1839                       &ofpact_put_SET_L4_SRC_PORT(ofpacts)->port);
1840 }
1841
1842 static char * OVS_WARN_UNUSED_RESULT
1843 parse_SET_L4_DST_PORT(char *arg, struct ofpbuf *ofpacts,
1844                       enum ofputil_protocol *usable_protocols OVS_UNUSED)
1845 {
1846     return str_to_u16(arg, "destination port",
1847                       &ofpact_put_SET_L4_DST_PORT(ofpacts)->port);
1848 }
1849
1850 static void
1851 format_SET_L4_SRC_PORT(const struct ofpact_l4_port *a, struct ds *s)
1852 {
1853     ds_put_format(s, "mod_tp_src:%d", a->port);
1854 }
1855
1856 static void
1857 format_SET_L4_DST_PORT(const struct ofpact_l4_port *a, struct ds *s)
1858 {
1859     ds_put_format(s, "mod_tp_dst:%d", a->port);
1860 }
1861 \f
1862 /* Action structure for OFPAT_COPY_FIELD. */
1863 struct ofp15_action_copy_field {
1864     ovs_be16 type;              /* OFPAT_COPY_FIELD. */
1865     ovs_be16 len;               /* Length is padded to 64 bits. */
1866     ovs_be16 n_bits;            /* Number of bits to copy. */
1867     ovs_be16 src_offset;        /* Starting bit offset in source. */
1868     ovs_be16 dst_offset;        /* Starting bit offset in destination. */
1869     uint8_t pad[2];
1870     /* Followed by:
1871      * - OXM header for source field.
1872      * - OXM header for destination field.
1873      * - Padding with 0-bytes to a multiple of 8 bytes.
1874      * The "pad2" member is the beginning of the above. */
1875     uint8_t pad2[4];
1876 };
1877 OFP_ASSERT(sizeof(struct ofp15_action_copy_field) == 16);
1878
1879 /* Action structure for OpenFlow 1.3 extension copy-field action.. */
1880 struct onf_action_copy_field {
1881     ovs_be16 type;              /* OFPAT_EXPERIMENTER. */
1882     ovs_be16 len;               /* Length is padded to 64 bits. */
1883     ovs_be32 experimenter;      /* ONF_VENDOR_ID. */
1884     ovs_be16 exp_type;          /* 3200. */
1885     uint8_t pad[2];             /* Not used. */
1886     ovs_be16 n_bits;            /* Number of bits to copy. */
1887     ovs_be16 src_offset;        /* Starting bit offset in source. */
1888     ovs_be16 dst_offset;        /* Starting bit offset in destination. */
1889     uint8_t pad2[2];            /* Not used. */
1890     /* Followed by:
1891      * - OXM header for source field.
1892      * - OXM header for destination field.
1893      * - Padding with 0-bytes (either 0 or 4 of them) to a multiple of 8 bytes.
1894      * The "pad3" member is the beginning of the above. */
1895     uint8_t pad3[4];            /* Not used. */
1896 };
1897 OFP_ASSERT(sizeof(struct onf_action_copy_field) == 24);
1898
1899 /* Action structure for NXAST_REG_MOVE.
1900  *
1901  * Copies src[src_ofs:src_ofs+n_bits] to dst[dst_ofs:dst_ofs+n_bits], where
1902  * a[b:c] denotes the bits within 'a' numbered 'b' through 'c' (not including
1903  * bit 'c').  Bit numbering starts at 0 for the least-significant bit, 1 for
1904  * the next most significant bit, and so on.
1905  *
1906  * 'src' and 'dst' are nxm_header values with nxm_hasmask=0.  (It doesn't make
1907  * sense to use nxm_hasmask=1 because the action does not do any kind of
1908  * matching; it uses the actual value of a field.)
1909  *
1910  * The following nxm_header values are potentially acceptable as 'src':
1911  *
1912  *   - NXM_OF_IN_PORT
1913  *   - NXM_OF_ETH_DST
1914  *   - NXM_OF_ETH_SRC
1915  *   - NXM_OF_ETH_TYPE
1916  *   - NXM_OF_VLAN_TCI
1917  *   - NXM_OF_IP_TOS
1918  *   - NXM_OF_IP_PROTO
1919  *   - NXM_OF_IP_SRC
1920  *   - NXM_OF_IP_DST
1921  *   - NXM_OF_TCP_SRC
1922  *   - NXM_OF_TCP_DST
1923  *   - NXM_OF_UDP_SRC
1924  *   - NXM_OF_UDP_DST
1925  *   - NXM_OF_ICMP_TYPE
1926  *   - NXM_OF_ICMP_CODE
1927  *   - NXM_OF_ARP_OP
1928  *   - NXM_OF_ARP_SPA
1929  *   - NXM_OF_ARP_TPA
1930  *   - NXM_NX_TUN_ID
1931  *   - NXM_NX_ARP_SHA
1932  *   - NXM_NX_ARP_THA
1933  *   - NXM_NX_ICMPV6_TYPE
1934  *   - NXM_NX_ICMPV6_CODE
1935  *   - NXM_NX_ND_SLL
1936  *   - NXM_NX_ND_TLL
1937  *   - NXM_NX_REG(idx) for idx in the switch's accepted range.
1938  *   - NXM_NX_PKT_MARK
1939  *   - NXM_NX_TUN_IPV4_SRC
1940  *   - NXM_NX_TUN_IPV4_DST
1941  *
1942  * The following nxm_header values are potentially acceptable as 'dst':
1943  *
1944  *   - NXM_OF_ETH_DST
1945  *   - NXM_OF_ETH_SRC
1946  *   - NXM_OF_IP_TOS
1947  *   - NXM_OF_IP_SRC
1948  *   - NXM_OF_IP_DST
1949  *   - NXM_OF_TCP_SRC
1950  *   - NXM_OF_TCP_DST
1951  *   - NXM_OF_UDP_SRC
1952  *   - NXM_OF_UDP_DST
1953  *   - NXM_OF_ICMP_TYPE
1954  *   - NXM_OF_ICMP_CODE
1955  *   - NXM_NX_ICMPV6_TYPE
1956  *   - NXM_NX_ICMPV6_CODE
1957  *   - NXM_NX_ARP_SHA
1958  *   - NXM_NX_ARP_THA
1959  *   - NXM_OF_ARP_OP
1960  *   - NXM_OF_ARP_SPA
1961  *   - NXM_OF_ARP_TPA
1962  *     Modifying any of the above fields changes the corresponding packet
1963  *     header.
1964  *
1965  *   - NXM_OF_IN_PORT
1966  *
1967  *   - NXM_NX_REG(idx) for idx in the switch's accepted range.
1968  *
1969  *   - NXM_NX_PKT_MARK
1970  *
1971  *   - NXM_OF_VLAN_TCI.  Modifying this field's value has side effects on the
1972  *     packet's 802.1Q header.  Setting a value with CFI=0 removes the 802.1Q
1973  *     header (if any), ignoring the other bits.  Setting a value with CFI=1
1974  *     adds or modifies the 802.1Q header appropriately, setting the TCI field
1975  *     to the field's new value (with the CFI bit masked out).
1976  *
1977  *   - NXM_NX_TUN_ID, NXM_NX_TUN_IPV4_SRC, NXM_NX_TUN_IPV4_DST.  Modifying
1978  *     any of these values modifies the corresponding tunnel header field used
1979  *     for the packet's next tunnel encapsulation, if allowed by the
1980  *     configuration of the output tunnel port.
1981  *
1982  * A given nxm_header value may be used as 'src' or 'dst' only on a flow whose
1983  * nx_match satisfies its prerequisites.  For example, NXM_OF_IP_TOS may be
1984  * used only if the flow's nx_match includes an nxm_entry that specifies
1985  * nxm_type=NXM_OF_ETH_TYPE, nxm_hasmask=0, and nxm_value=0x0800.
1986  *
1987  * The switch will reject actions for which src_ofs+n_bits is greater than the
1988  * width of 'src' or dst_ofs+n_bits is greater than the width of 'dst' with
1989  * error type OFPET_BAD_ACTION, code OFPBAC_BAD_ARGUMENT.
1990  *
1991  * This action behaves properly when 'src' overlaps with 'dst', that is, it
1992  * behaves as if 'src' were copied out to a temporary buffer, then the
1993  * temporary buffer copied to 'dst'.
1994  */
1995 struct nx_action_reg_move {
1996     ovs_be16 type;                  /* OFPAT_VENDOR. */
1997     ovs_be16 len;                   /* Length is 24. */
1998     ovs_be32 vendor;                /* NX_VENDOR_ID. */
1999     ovs_be16 subtype;               /* NXAST_REG_MOVE. */
2000     ovs_be16 n_bits;                /* Number of bits. */
2001     ovs_be16 src_ofs;               /* Starting bit offset in source. */
2002     ovs_be16 dst_ofs;               /* Starting bit offset in destination. */
2003     /* Followed by:
2004      * - OXM/NXM header for source field (4 or 8 bytes).
2005      * - OXM/NXM header for destination field (4 or 8 bytes).
2006      * - Padding with 0-bytes to a multiple of 8 bytes, if necessary. */
2007 };
2008 OFP_ASSERT(sizeof(struct nx_action_reg_move) == 16);
2009
2010 static enum ofperr
2011 decode_copy_field__(ovs_be16 src_offset, ovs_be16 dst_offset, ovs_be16 n_bits,
2012                     const void *action, ovs_be16 action_len, size_t oxm_offset,
2013                     struct ofpbuf *ofpacts)
2014 {
2015     struct ofpact_reg_move *move;
2016     enum ofperr error;
2017     struct ofpbuf b;
2018
2019     move = ofpact_put_REG_MOVE(ofpacts);
2020     move->ofpact.raw = ONFACT_RAW13_COPY_FIELD;
2021     move->src.ofs = ntohs(src_offset);
2022     move->src.n_bits = ntohs(n_bits);
2023     move->dst.ofs = ntohs(dst_offset);
2024     move->dst.n_bits = ntohs(n_bits);
2025
2026     ofpbuf_use_const(&b, action, ntohs(action_len));
2027     ofpbuf_pull(&b, oxm_offset);
2028     error = nx_pull_header(&b, &move->src.field, NULL);
2029     if (error) {
2030         return error;
2031     }
2032     error = nx_pull_header(&b, &move->dst.field, NULL);
2033     if (error) {
2034         return error;
2035     }
2036
2037     if (!is_all_zeros(b.data, b.size)) {
2038         return OFPERR_NXBRC_MUST_BE_ZERO;
2039     }
2040
2041     return nxm_reg_move_check(move, NULL);
2042 }
2043
2044 static enum ofperr
2045 decode_OFPAT_RAW15_COPY_FIELD(const struct ofp15_action_copy_field *oacf,
2046                               enum ofp_version ofp_version OVS_UNUSED,
2047                               struct ofpbuf *ofpacts)
2048 {
2049     return decode_copy_field__(oacf->src_offset, oacf->dst_offset,
2050                                oacf->n_bits, oacf, oacf->len,
2051                                OBJECT_OFFSETOF(oacf, pad2), ofpacts);
2052 }
2053
2054 static enum ofperr
2055 decode_ONFACT_RAW13_COPY_FIELD(const struct onf_action_copy_field *oacf,
2056                                enum ofp_version ofp_version OVS_UNUSED,
2057                                struct ofpbuf *ofpacts)
2058 {
2059     return decode_copy_field__(oacf->src_offset, oacf->dst_offset,
2060                                oacf->n_bits, oacf, oacf->len,
2061                                OBJECT_OFFSETOF(oacf, pad3), ofpacts);
2062 }
2063
2064 static enum ofperr
2065 decode_NXAST_RAW_REG_MOVE(const struct nx_action_reg_move *narm,
2066                           enum ofp_version ofp_version OVS_UNUSED,
2067                           struct ofpbuf *ofpacts)
2068 {
2069     struct ofpact_reg_move *move;
2070     enum ofperr error;
2071     struct ofpbuf b;
2072
2073     move = ofpact_put_REG_MOVE(ofpacts);
2074     move->ofpact.raw = NXAST_RAW_REG_MOVE;
2075     move->src.ofs = ntohs(narm->src_ofs);
2076     move->src.n_bits = ntohs(narm->n_bits);
2077     move->dst.ofs = ntohs(narm->dst_ofs);
2078     move->dst.n_bits = ntohs(narm->n_bits);
2079
2080     ofpbuf_use_const(&b, narm, ntohs(narm->len));
2081     ofpbuf_pull(&b, sizeof *narm);
2082     error = nx_pull_header(&b, &move->src.field, NULL);
2083     if (error) {
2084         return error;
2085     }
2086     error = nx_pull_header(&b, &move->dst.field, NULL);
2087     if (error) {
2088         return error;
2089     }
2090     if (!is_all_zeros(b.data, b.size)) {
2091         return OFPERR_NXBRC_MUST_BE_ZERO;
2092     }
2093
2094     return nxm_reg_move_check(move, NULL);
2095 }
2096
2097 static void
2098 encode_REG_MOVE(const struct ofpact_reg_move *move,
2099                 enum ofp_version ofp_version, struct ofpbuf *out)
2100 {
2101     /* For OpenFlow 1.3, the choice of ONFACT_RAW13_COPY_FIELD versus
2102      * NXAST_RAW_REG_MOVE is somewhat difficult.  Neither one is guaranteed to
2103      * be supported by every OpenFlow 1.3 implementation.  It would be ideal to
2104      * probe for support.  Until we have that ability, we currently prefer
2105      * NXAST_RAW_REG_MOVE for backward compatibility with older Open vSwitch
2106      * versions.  */
2107     size_t start_ofs = out->size;
2108     if (ofp_version >= OFP15_VERSION) {
2109         struct ofp15_action_copy_field *copy = put_OFPAT15_COPY_FIELD(out);
2110         copy->n_bits = htons(move->dst.n_bits);
2111         copy->src_offset = htons(move->src.ofs);
2112         copy->dst_offset = htons(move->dst.ofs);
2113         out->size = out->size - sizeof copy->pad2;
2114         nx_put_header(out, move->src.field->id, ofp_version, false);
2115         nx_put_header(out, move->dst.field->id, ofp_version, false);
2116     } else if (ofp_version == OFP13_VERSION
2117                && move->ofpact.raw == ONFACT_RAW13_COPY_FIELD) {
2118         struct onf_action_copy_field *copy = put_ONFACT13_COPY_FIELD(out);
2119         copy->n_bits = htons(move->dst.n_bits);
2120         copy->src_offset = htons(move->src.ofs);
2121         copy->dst_offset = htons(move->dst.ofs);
2122         out->size = out->size - sizeof copy->pad3;
2123         nx_put_header(out, move->src.field->id, ofp_version, false);
2124         nx_put_header(out, move->dst.field->id, ofp_version, false);
2125     } else {
2126         struct nx_action_reg_move *narm = put_NXAST_REG_MOVE(out);
2127         narm->n_bits = htons(move->dst.n_bits);
2128         narm->src_ofs = htons(move->src.ofs);
2129         narm->dst_ofs = htons(move->dst.ofs);
2130         nx_put_header(out, move->src.field->id, 0, false);
2131         nx_put_header(out, move->dst.field->id, 0, false);
2132     }
2133     pad_ofpat(out, start_ofs);
2134 }
2135
2136 static char * OVS_WARN_UNUSED_RESULT
2137 parse_REG_MOVE(const char *arg, struct ofpbuf *ofpacts,
2138                enum ofputil_protocol *usable_protocols OVS_UNUSED)
2139 {
2140     struct ofpact_reg_move *move = ofpact_put_REG_MOVE(ofpacts);
2141     const char *full_arg = arg;
2142     char *error;
2143
2144     error = mf_parse_subfield__(&move->src, &arg);
2145     if (error) {
2146         return error;
2147     }
2148     if (strncmp(arg, "->", 2)) {
2149         return xasprintf("%s: missing `->' following source", full_arg);
2150     }
2151     arg += 2;
2152     error = mf_parse_subfield(&move->dst, arg);
2153     if (error) {
2154         return error;
2155     }
2156
2157     if (move->src.n_bits != move->dst.n_bits) {
2158         return xasprintf("%s: source field is %d bits wide but destination is "
2159                          "%d bits wide", full_arg,
2160                          move->src.n_bits, move->dst.n_bits);
2161     }
2162     return NULL;
2163 }
2164
2165 static void
2166 format_REG_MOVE(const struct ofpact_reg_move *a, struct ds *s)
2167 {
2168     nxm_format_reg_move(a, s);
2169 }
2170 \f
2171 /* Action structure for OFPAT12_SET_FIELD. */
2172 struct ofp12_action_set_field {
2173     ovs_be16 type;                  /* OFPAT12_SET_FIELD. */
2174     ovs_be16 len;                   /* Length is padded to 64 bits. */
2175
2176     /* Followed by:
2177      * - An OXM header, value, and (in OpenFlow 1.5+) optionally a mask.
2178      * - Enough 0-bytes to pad out to a multiple of 64 bits.
2179      *
2180      * The "pad" member is the beginning of the above. */
2181     uint8_t pad[4];
2182 };
2183 OFP_ASSERT(sizeof(struct ofp12_action_set_field) == 8);
2184
2185 /* Action structure for NXAST_REG_LOAD.
2186  *
2187  * Copies value[0:n_bits] to dst[ofs:ofs+n_bits], where a[b:c] denotes the bits
2188  * within 'a' numbered 'b' through 'c' (not including bit 'c').  Bit numbering
2189  * starts at 0 for the least-significant bit, 1 for the next most significant
2190  * bit, and so on.
2191  *
2192  * 'dst' is an nxm_header with nxm_hasmask=0.  See the documentation for
2193  * NXAST_REG_MOVE, above, for the permitted fields and for the side effects of
2194  * loading them.
2195  *
2196  * The 'ofs' and 'n_bits' fields are combined into a single 'ofs_nbits' field
2197  * to avoid enlarging the structure by another 8 bytes.  To allow 'n_bits' to
2198  * take a value between 1 and 64 (inclusive) while taking up only 6 bits, it is
2199  * also stored as one less than its true value:
2200  *
2201  *  15                           6 5                0
2202  * +------------------------------+------------------+
2203  * |              ofs             |    n_bits - 1    |
2204  * +------------------------------+------------------+
2205  *
2206  * The switch will reject actions for which ofs+n_bits is greater than the
2207  * width of 'dst', or in which any bits in 'value' with value 2**n_bits or
2208  * greater are set to 1, with error type OFPET_BAD_ACTION, code
2209  * OFPBAC_BAD_ARGUMENT.
2210  */
2211 struct nx_action_reg_load {
2212     ovs_be16 type;                  /* OFPAT_VENDOR. */
2213     ovs_be16 len;                   /* Length is 24. */
2214     ovs_be32 vendor;                /* NX_VENDOR_ID. */
2215     ovs_be16 subtype;               /* NXAST_REG_LOAD. */
2216     ovs_be16 ofs_nbits;             /* (ofs << 6) | (n_bits - 1). */
2217     ovs_be32 dst;                   /* Destination register. */
2218     ovs_be64 value;                 /* Immediate value. */
2219 };
2220 OFP_ASSERT(sizeof(struct nx_action_reg_load) == 24);
2221
2222 /* Action structure for NXAST_REG_LOAD2.
2223  *
2224  * Compared to OFPAT_SET_FIELD, we can use this to set whole or partial fields
2225  * in any OpenFlow version.  Compared to NXAST_REG_LOAD, we can use this to set
2226  * OXM experimenter fields. */
2227 struct nx_action_reg_load2 {
2228     ovs_be16 type;                  /* OFPAT_VENDOR. */
2229     ovs_be16 len;                   /* At least 16. */
2230     ovs_be32 vendor;                /* NX_VENDOR_ID. */
2231     ovs_be16 subtype;               /* NXAST_SET_FIELD. */
2232
2233     /* Followed by:
2234      * - An NXM/OXM header, value, and optionally a mask.
2235      * - Enough 0-bytes to pad out to a multiple of 64 bits.
2236      *
2237      * The "pad" member is the beginning of the above. */
2238     uint8_t pad[6];
2239 };
2240 OFP_ASSERT(sizeof(struct nx_action_reg_load2) == 16);
2241
2242 static enum ofperr
2243 decode_ofpat_set_field(const struct ofp12_action_set_field *oasf,
2244                        bool may_mask, struct ofpbuf *ofpacts)
2245 {
2246     struct ofpact_set_field *sf;
2247     enum ofperr error;
2248     struct ofpbuf b;
2249
2250     sf = ofpact_put_SET_FIELD(ofpacts);
2251
2252     ofpbuf_use_const(&b, oasf, ntohs(oasf->len));
2253     ofpbuf_pull(&b, OBJECT_OFFSETOF(oasf, pad));
2254     error = nx_pull_entry(&b, &sf->field, &sf->value,
2255                           may_mask ? &sf->mask : NULL);
2256     if (error) {
2257         return (error == OFPERR_OFPBMC_BAD_MASK
2258                 ? OFPERR_OFPBAC_BAD_SET_MASK
2259                 : error);
2260     }
2261     if (!may_mask) {
2262         memset(&sf->mask, 0xff, sf->field->n_bytes);
2263     }
2264
2265     if (!is_all_zeros(b.data, b.size)) {
2266         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2267     }
2268
2269     /* OpenFlow says specifically that one may not set OXM_OF_IN_PORT via
2270      * Set-Field. */
2271     if (sf->field->id == MFF_IN_PORT_OXM) {
2272         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2273     }
2274
2275     /* oxm_length is now validated to be compatible with mf_value. */
2276     if (!sf->field->writable) {
2277         VLOG_WARN_RL(&rl, "destination field %s is not writable",
2278                      sf->field->name);
2279         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2280     }
2281
2282     /* The value must be valid for match.  OpenFlow 1.5 also says,
2283      * "In an OXM_OF_VLAN_VID set-field action, the OFPVID_PRESENT bit must be
2284      * a 1-bit in oxm_value and in oxm_mask." */
2285     if (!mf_is_value_valid(sf->field, &sf->value)
2286         || (sf->field->id == MFF_VLAN_VID
2287             && (!(sf->mask.be16 & htons(OFPVID12_PRESENT))
2288                 || !(sf->value.be16 & htons(OFPVID12_PRESENT))))) {
2289         struct ds ds = DS_EMPTY_INITIALIZER;
2290         mf_format(sf->field, &sf->value, NULL, &ds);
2291         VLOG_WARN_RL(&rl, "Invalid value for set field %s: %s",
2292                      sf->field->name, ds_cstr(&ds));
2293         ds_destroy(&ds);
2294
2295         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2296     }
2297     return 0;
2298 }
2299
2300 static enum ofperr
2301 decode_OFPAT_RAW12_SET_FIELD(const struct ofp12_action_set_field *oasf,
2302                              enum ofp_version ofp_version OVS_UNUSED,
2303                              struct ofpbuf *ofpacts)
2304 {
2305     return decode_ofpat_set_field(oasf, false, ofpacts);
2306 }
2307
2308 static enum ofperr
2309 decode_OFPAT_RAW15_SET_FIELD(const struct ofp12_action_set_field *oasf,
2310                              enum ofp_version ofp_version OVS_UNUSED,
2311                              struct ofpbuf *ofpacts)
2312 {
2313     return decode_ofpat_set_field(oasf, true, ofpacts);
2314 }
2315
2316 static enum ofperr
2317 decode_NXAST_RAW_REG_LOAD(const struct nx_action_reg_load *narl,
2318                           enum ofp_version ofp_version OVS_UNUSED,
2319                           struct ofpbuf *out)
2320 {
2321     struct ofpact_set_field *sf = ofpact_put_reg_load(out);
2322     struct mf_subfield dst;
2323     enum ofperr error;
2324
2325     sf->ofpact.raw = NXAST_RAW_REG_LOAD;
2326
2327     dst.field = mf_from_nxm_header(ntohl(narl->dst));
2328     dst.ofs = nxm_decode_ofs(narl->ofs_nbits);
2329     dst.n_bits = nxm_decode_n_bits(narl->ofs_nbits);
2330     error = mf_check_dst(&dst, NULL);
2331     if (error) {
2332         return error;
2333     }
2334
2335     /* Reject 'narl' if a bit numbered 'n_bits' or higher is set to 1 in
2336      * narl->value. */
2337     if (dst.n_bits < 64 && ntohll(narl->value) >> dst.n_bits) {
2338         return OFPERR_OFPBAC_BAD_ARGUMENT;
2339     }
2340
2341     sf->field = dst.field;
2342     bitwise_put(ntohll(narl->value),
2343                 &sf->value, dst.field->n_bytes, dst.ofs,
2344                 dst.n_bits);
2345     bitwise_put(UINT64_MAX,
2346                 &sf->mask, dst.field->n_bytes, dst.ofs,
2347                 dst.n_bits);
2348
2349     return 0;
2350 }
2351
2352 static enum ofperr
2353 decode_NXAST_RAW_REG_LOAD2(const struct nx_action_reg_load2 *narl,
2354                            enum ofp_version ofp_version OVS_UNUSED,
2355                            struct ofpbuf *out)
2356 {
2357     struct ofpact_set_field *sf;
2358     enum ofperr error;
2359     struct ofpbuf b;
2360
2361     sf = ofpact_put_SET_FIELD(out);
2362     sf->ofpact.raw = NXAST_RAW_REG_LOAD2;
2363
2364     ofpbuf_use_const(&b, narl, ntohs(narl->len));
2365     ofpbuf_pull(&b, OBJECT_OFFSETOF(narl, pad));
2366     error = nx_pull_entry(&b, &sf->field, &sf->value, &sf->mask);
2367     if (error) {
2368         return error;
2369     }
2370     if (!is_all_zeros(b.data, b.size)) {
2371         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2372     }
2373
2374     if (!sf->field->writable) {
2375         VLOG_WARN_RL(&rl, "destination field %s is not writable",
2376                      sf->field->name);
2377         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2378     }
2379     return 0;
2380 }
2381
2382 static void
2383 ofpact_put_set_field(struct ofpbuf *openflow, enum ofp_version ofp_version,
2384                      enum mf_field_id field, uint64_t value_)
2385 {
2386     struct ofp12_action_set_field *oasf OVS_UNUSED;
2387     int n_bytes = mf_from_id(field)->n_bytes;
2388     size_t start_ofs = openflow->size;
2389     union mf_value value;
2390
2391     value.be64 = htonll(value_ << (8 * (8 - n_bytes)));
2392
2393     oasf = put_OFPAT12_SET_FIELD(openflow);
2394     openflow->size = openflow->size - sizeof oasf->pad;
2395     nx_put_entry(openflow, field, ofp_version, &value, NULL);
2396     pad_ofpat(openflow, start_ofs);
2397 }
2398
2399 static bool
2400 next_load_segment(const struct ofpact_set_field *sf,
2401                   struct mf_subfield *dst, uint64_t *value)
2402 {
2403     int n_bits = sf->field->n_bits;
2404     int n_bytes = sf->field->n_bytes;
2405     int start = dst->ofs + dst->n_bits;
2406
2407     if (start < n_bits) {
2408         dst->field = sf->field;
2409         dst->ofs = bitwise_scan(&sf->mask, n_bytes, 1, start, n_bits);
2410         if (dst->ofs < n_bits) {
2411             dst->n_bits = bitwise_scan(&sf->mask, n_bytes, 0, dst->ofs + 1,
2412                                        MIN(dst->ofs + 64, n_bits)) - dst->ofs;
2413             *value = bitwise_get(&sf->value, n_bytes, dst->ofs, dst->n_bits);
2414             return true;
2415         }
2416     }
2417     return false;
2418 }
2419
2420 /* Convert 'sf' to a series of REG_LOADs. */
2421 static void
2422 set_field_to_nxast(const struct ofpact_set_field *sf, struct ofpbuf *openflow)
2423 {
2424     /* If 'sf' cannot be encoded as NXAST_REG_LOAD because it requires an
2425      * experimenter OXM or is variable length (or if it came in as
2426      * NXAST_REG_LOAD2), encode as NXAST_REG_LOAD2.  Otherwise use
2427      * NXAST_REG_LOAD, which is backward compatible. */
2428     if (sf->ofpact.raw == NXAST_RAW_REG_LOAD2
2429         || !mf_nxm_header(sf->field->id) || sf->field->variable_len) {
2430         struct nx_action_reg_load2 *narl OVS_UNUSED;
2431         size_t start_ofs = openflow->size;
2432
2433         narl = put_NXAST_REG_LOAD2(openflow);
2434         openflow->size = openflow->size - sizeof narl->pad;
2435         nx_put_entry(openflow, sf->field->id, 0, &sf->value, &sf->mask);
2436         pad_ofpat(openflow, start_ofs);
2437     } else {
2438         struct mf_subfield dst;
2439         uint64_t value;
2440
2441         dst.ofs = dst.n_bits = 0;
2442         while (next_load_segment(sf, &dst, &value)) {
2443             struct nx_action_reg_load *narl = put_NXAST_REG_LOAD(openflow);
2444             narl->ofs_nbits = nxm_encode_ofs_nbits(dst.ofs, dst.n_bits);
2445             narl->dst = htonl(mf_nxm_header(dst.field->id));
2446             narl->value = htonll(value);
2447         }
2448     }
2449 }
2450
2451 /* Convert 'sf', which must set an entire field, to standard OpenFlow 1.0/1.1
2452  * actions, if we can, falling back to Nicira extensions if we must.
2453  *
2454  * We check only meta-flow types that can appear within set field actions and
2455  * that have a mapping to compatible action types.  These struct mf_field
2456  * definitions have a defined OXM or NXM header value and specify the field as
2457  * writable. */
2458 static void
2459 set_field_to_legacy_openflow(const struct ofpact_set_field *sf,
2460                              enum ofp_version ofp_version,
2461                              struct ofpbuf *out)
2462 {
2463     switch ((int) sf->field->id) {
2464     case MFF_VLAN_TCI: {
2465         ovs_be16 tci = sf->value.be16;
2466         bool cfi = (tci & htons(VLAN_CFI)) != 0;
2467         uint16_t vid = vlan_tci_to_vid(tci);
2468         uint8_t pcp = vlan_tci_to_pcp(tci);
2469
2470         if (ofp_version < OFP11_VERSION) {
2471             /* NXM_OF_VLAN_TCI to OpenFlow 1.0 mapping:
2472              *
2473              * If CFI=1, Add or modify VLAN VID & PCP.
2474              * If CFI=0, strip VLAN header, if any.
2475              */
2476             if (cfi) {
2477                 put_OFPAT10_SET_VLAN_VID(out, vid);
2478                 put_OFPAT10_SET_VLAN_PCP(out, pcp);
2479             } else {
2480                 put_OFPAT10_STRIP_VLAN(out);
2481             }
2482         } else {
2483             /* NXM_OF_VLAN_TCI to OpenFlow 1.1 mapping:
2484              *
2485              * If CFI=1, Add or modify VLAN VID & PCP.
2486              *    OpenFlow 1.1 set actions only apply if the packet
2487              *    already has VLAN tags.  To be sure that is the case
2488              *    we have to push a VLAN header.  As we do not support
2489              *    multiple layers of VLANs, this is a no-op, if a VLAN
2490              *    header already exists.  This may backfire, however,
2491              *    when we start supporting multiple layers of VLANs.
2492              * If CFI=0, strip VLAN header, if any.
2493              */
2494             if (cfi) {
2495                 /* Push a VLAN tag, if one was not seen at action validation
2496                  * time. */
2497                 if (!sf->flow_has_vlan) {
2498                     put_OFPAT11_PUSH_VLAN(out, htons(ETH_TYPE_VLAN_8021Q));
2499                 }
2500                 put_OFPAT11_SET_VLAN_VID(out, vid);
2501                 put_OFPAT11_SET_VLAN_PCP(out, pcp);
2502             } else {
2503                 /* If the flow did not match on vlan, we have no way of
2504                  * knowing if the vlan tag exists, so we must POP just to be
2505                  * sure. */
2506                 put_OFPAT11_POP_VLAN(out);
2507             }
2508         }
2509         break;
2510     }
2511
2512     case MFF_VLAN_VID: {
2513         uint16_t vid = ntohs(sf->value.be16) & VLAN_VID_MASK;
2514         if (ofp_version == OFP10_VERSION) {
2515             put_OFPAT10_SET_VLAN_VID(out, vid);
2516         } else {
2517             put_OFPAT11_SET_VLAN_VID(out, vid);
2518         }
2519         break;
2520     }
2521
2522     case MFF_VLAN_PCP:
2523         if (ofp_version == OFP10_VERSION) {
2524             put_OFPAT10_SET_VLAN_PCP(out, sf->value.u8);
2525         } else {
2526             put_OFPAT11_SET_VLAN_PCP(out, sf->value.u8);
2527         }
2528         break;
2529
2530     case MFF_ETH_SRC:
2531         put_OFPAT_SET_DL_SRC(out, ofp_version)->dl_addr = sf->value.mac;
2532         break;
2533
2534     case MFF_ETH_DST:
2535         put_OFPAT_SET_DL_DST(out, ofp_version)->dl_addr = sf->value.mac;
2536         break;
2537
2538     case MFF_IPV4_SRC:
2539         put_OFPAT_SET_NW_SRC(out, ofp_version, sf->value.be32);
2540         break;
2541
2542     case MFF_IPV4_DST:
2543         put_OFPAT_SET_NW_DST(out, ofp_version, sf->value.be32);
2544         break;
2545
2546     case MFF_IP_DSCP:
2547         put_OFPAT_SET_NW_TOS(out, ofp_version, sf->value.u8);
2548         break;
2549
2550     case MFF_IP_DSCP_SHIFTED:
2551         put_OFPAT_SET_NW_TOS(out, ofp_version, sf->value.u8 << 2);
2552         break;
2553
2554     case MFF_TCP_SRC:
2555     case MFF_UDP_SRC:
2556         put_OFPAT_SET_TP_SRC(out, sf->value.be16);
2557         break;
2558
2559     case MFF_TCP_DST:
2560     case MFF_UDP_DST:
2561         put_OFPAT_SET_TP_DST(out, sf->value.be16);
2562         break;
2563
2564     default:
2565         set_field_to_nxast(sf, out);
2566         break;
2567     }
2568 }
2569
2570 static void
2571 set_field_to_set_field(const struct ofpact_set_field *sf,
2572                        enum ofp_version ofp_version, struct ofpbuf *out)
2573 {
2574     struct ofp12_action_set_field *oasf OVS_UNUSED;
2575     size_t start_ofs = out->size;
2576
2577     oasf = put_OFPAT12_SET_FIELD(out);
2578     out->size = out->size - sizeof oasf->pad;
2579     nx_put_entry(out, sf->field->id, ofp_version, &sf->value, &sf->mask);
2580     pad_ofpat(out, start_ofs);
2581 }
2582
2583 static void
2584 encode_SET_FIELD(const struct ofpact_set_field *sf,
2585                  enum ofp_version ofp_version, struct ofpbuf *out)
2586 {
2587     if (ofp_version >= OFP15_VERSION) {
2588         /* OF1.5+ only has Set-Field (reg_load is redundant so we drop it
2589          * entirely). */
2590         set_field_to_set_field(sf, ofp_version, out);
2591     } else if (sf->ofpact.raw == NXAST_RAW_REG_LOAD ||
2592                sf->ofpact.raw == NXAST_RAW_REG_LOAD2) {
2593         /* It came in as reg_load, send it out the same way. */
2594         set_field_to_nxast(sf, out);
2595     } else if (ofp_version < OFP12_VERSION) {
2596         /* OpenFlow 1.0 and 1.1 don't have Set-Field. */
2597         set_field_to_legacy_openflow(sf, ofp_version, out);
2598     } else if (is_all_ones((const uint8_t *) &sf->mask, sf->field->n_bytes)) {
2599         /* We're encoding to OpenFlow 1.2, 1.3, or 1.4.  The action sets an
2600          * entire field, so encode it as OFPAT_SET_FIELD. */
2601         set_field_to_set_field(sf, ofp_version, out);
2602     } else {
2603         /* We're encoding to OpenFlow 1.2, 1.3, or 1.4.  The action cannot be
2604          * encoded as OFPAT_SET_FIELD because it does not set an entire field,
2605          * so encode it as reg_load. */
2606         set_field_to_nxast(sf, out);
2607     }
2608 }
2609
2610 /* Parses the input argument 'arg' into the key, value, and delimiter
2611  * components that are common across the reg_load and set_field action format.
2612  *
2613  * With an argument like "1->metadata", sets the following pointers to
2614  * point within 'arg':
2615  * key: "metadata"
2616  * value: "1"
2617  * delim: "->"
2618  *
2619  * Returns NULL if successful, otherwise a malloc()'d string describing the
2620  * error.  The caller is responsible for freeing the returned string. */
2621 static char * OVS_WARN_UNUSED_RESULT
2622 set_field_split_str(char *arg, char **key, char **value, char **delim)
2623 {
2624     char *value_end;
2625
2626     *value = arg;
2627     value_end = strstr(arg, "->");
2628     *key = value_end + strlen("->");
2629     if (delim) {
2630         *delim = value_end;
2631     }
2632
2633     if (!value_end) {
2634         return xasprintf("%s: missing `->'", arg);
2635     }
2636     if (strlen(value_end) <= strlen("->")) {
2637         return xasprintf("%s: missing field name following `->'", arg);
2638     }
2639
2640     return NULL;
2641 }
2642
2643 /* Parses a "set_field" action with argument 'arg', appending the parsed
2644  * action to 'ofpacts'.
2645  *
2646  * Returns NULL if successful, otherwise a malloc()'d string describing the
2647  * error.  The caller is responsible for freeing the returned string. */
2648 static char * OVS_WARN_UNUSED_RESULT
2649 set_field_parse__(char *arg, struct ofpbuf *ofpacts,
2650                   enum ofputil_protocol *usable_protocols)
2651 {
2652     struct ofpact_set_field *sf = ofpact_put_SET_FIELD(ofpacts);
2653     char *value;
2654     char *delim;
2655     char *key;
2656     const struct mf_field *mf;
2657     char *error;
2658
2659     error = set_field_split_str(arg, &key, &value, &delim);
2660     if (error) {
2661         return error;
2662     }
2663
2664     mf = mf_from_name(key);
2665     if (!mf) {
2666         return xasprintf("%s is not a valid OXM field name", key);
2667     }
2668     if (!mf->writable) {
2669         return xasprintf("%s is read-only", key);
2670     }
2671     sf->field = mf;
2672     delim[0] = '\0';
2673     error = mf_parse(mf, value, &sf->value, &sf->mask);
2674     if (error) {
2675         return error;
2676     }
2677
2678     if (!mf_is_value_valid(mf, &sf->value)) {
2679         return xasprintf("%s is not a valid value for field %s", value, key);
2680     }
2681
2682     *usable_protocols &= mf->usable_protocols_exact;
2683     return NULL;
2684 }
2685
2686 /* Parses 'arg' as the argument to a "set_field" action, and appends such an
2687  * action to 'ofpacts'.
2688  *
2689  * Returns NULL if successful, otherwise a malloc()'d string describing the
2690  * error.  The caller is responsible for freeing the returned string. */
2691 static char * OVS_WARN_UNUSED_RESULT
2692 parse_SET_FIELD(const char *arg, struct ofpbuf *ofpacts,
2693                 enum ofputil_protocol *usable_protocols)
2694 {
2695     char *copy = xstrdup(arg);
2696     char *error = set_field_parse__(copy, ofpacts, usable_protocols);
2697     free(copy);
2698     return error;
2699 }
2700
2701 static char * OVS_WARN_UNUSED_RESULT
2702 parse_reg_load(char *arg, struct ofpbuf *ofpacts)
2703 {
2704     struct ofpact_set_field *sf = ofpact_put_reg_load(ofpacts);
2705     struct mf_subfield dst;
2706     char *key, *value_str;
2707     union mf_value value;
2708     char *error;
2709
2710     error = set_field_split_str(arg, &key, &value_str, NULL);
2711     if (error) {
2712         return error;
2713     }
2714
2715     error = mf_parse_subfield(&dst, key);
2716     if (error) {
2717         return error;
2718     }
2719
2720     if (parse_int_string(value_str, (uint8_t *)&value, dst.field->n_bytes,
2721                          &key)) {
2722         return xasprintf("%s: cannot parse integer value", arg);
2723     }
2724
2725     if (!bitwise_is_all_zeros(&value, dst.field->n_bytes, dst.n_bits,
2726                               dst.field->n_bytes * 8 - dst.n_bits)) {
2727         struct ds ds;
2728
2729         ds_init(&ds);
2730         mf_format(dst.field, &value, NULL, &ds);
2731         error = xasprintf("%s: value %s does not fit into %d bits",
2732                           arg, ds_cstr(&ds), dst.n_bits);
2733         ds_destroy(&ds);
2734         return error;
2735     }
2736
2737     sf->field = dst.field;
2738     memset(&sf->value, 0, sizeof sf->value);
2739     bitwise_copy(&value, dst.field->n_bytes, 0, &sf->value,
2740                  dst.field->n_bytes, dst.ofs, dst.n_bits);
2741     bitwise_one(&sf->mask, dst.field->n_bytes, dst.ofs, dst.n_bits);
2742
2743     return NULL;
2744 }
2745
2746 static void
2747 format_SET_FIELD(const struct ofpact_set_field *a, struct ds *s)
2748 {
2749     if (a->ofpact.raw == NXAST_RAW_REG_LOAD) {
2750         struct mf_subfield dst;
2751         uint64_t value;
2752
2753         dst.ofs = dst.n_bits = 0;
2754         while (next_load_segment(a, &dst, &value)) {
2755             ds_put_format(s, "load:%#"PRIx64"->", value);
2756             mf_format_subfield(&dst, s);
2757             ds_put_char(s, ',');
2758         }
2759         ds_chomp(s, ',');
2760     } else {
2761         ds_put_cstr(s, "set_field:");
2762         mf_format(a->field, &a->value, &a->mask, s);
2763         ds_put_format(s, "->%s", a->field->name);
2764     }
2765 }
2766
2767 /* Appends an OFPACT_SET_FIELD ofpact to 'ofpacts' and returns it.  The ofpact
2768  * is marked such that, if possible, it will be translated to OpenFlow as
2769  * NXAST_REG_LOAD extension actions rather than OFPAT_SET_FIELD, either because
2770  * that was the way that the action was expressed when it came into OVS or for
2771  * backward compatibility. */
2772 struct ofpact_set_field *
2773 ofpact_put_reg_load(struct ofpbuf *ofpacts)
2774 {
2775     struct ofpact_set_field *sf = ofpact_put_SET_FIELD(ofpacts);
2776     sf->ofpact.raw = NXAST_RAW_REG_LOAD;
2777     return sf;
2778 }
2779 \f
2780 /* Action structure for NXAST_STACK_PUSH and NXAST_STACK_POP.
2781  *
2782  * Pushes (or pops) field[offset: offset + n_bits] to (or from)
2783  * top of the stack.
2784  */
2785 struct nx_action_stack {
2786     ovs_be16 type;                  /* OFPAT_VENDOR. */
2787     ovs_be16 len;                   /* Length is 16. */
2788     ovs_be32 vendor;                /* NX_VENDOR_ID. */
2789     ovs_be16 subtype;               /* NXAST_STACK_PUSH or NXAST_STACK_POP. */
2790     ovs_be16 offset;                /* Bit offset into the field. */
2791     /* Followed by:
2792      * - OXM/NXM header for field to push or pop (4 or 8 bytes).
2793      * - ovs_be16 'n_bits', the number of bits to extract from the field.
2794      * - Enough 0-bytes to pad out the action to 24 bytes. */
2795     uint8_t pad[12];                /* See above. */
2796 };
2797 OFP_ASSERT(sizeof(struct nx_action_stack) == 24);
2798
2799 static enum ofperr
2800 decode_stack_action(const struct nx_action_stack *nasp,
2801                     struct ofpact_stack *stack_action)
2802 {
2803     enum ofperr error;
2804     struct ofpbuf b;
2805
2806     stack_action->subfield.ofs = ntohs(nasp->offset);
2807
2808     ofpbuf_use_const(&b, nasp, sizeof *nasp);
2809     ofpbuf_pull(&b, OBJECT_OFFSETOF(nasp, pad));
2810     error = nx_pull_header(&b, &stack_action->subfield.field, NULL);
2811     if (error) {
2812         return error;
2813     }
2814     stack_action->subfield.n_bits = ntohs(*(const ovs_be16 *) b.data);
2815     ofpbuf_pull(&b, 2);
2816     if (!is_all_zeros(b.data, b.size)) {
2817         return OFPERR_NXBRC_MUST_BE_ZERO;
2818     }
2819
2820     return 0;
2821 }
2822
2823 static enum ofperr
2824 decode_NXAST_RAW_STACK_PUSH(const struct nx_action_stack *nasp,
2825                             enum ofp_version ofp_version OVS_UNUSED,
2826                             struct ofpbuf *ofpacts)
2827 {
2828     struct ofpact_stack *push = ofpact_put_STACK_PUSH(ofpacts);
2829     enum ofperr error = decode_stack_action(nasp, push);
2830     return error ? error : nxm_stack_push_check(push, NULL);
2831 }
2832
2833 static enum ofperr
2834 decode_NXAST_RAW_STACK_POP(const struct nx_action_stack *nasp,
2835                            enum ofp_version ofp_version OVS_UNUSED,
2836                            struct ofpbuf *ofpacts)
2837 {
2838     struct ofpact_stack *pop = ofpact_put_STACK_POP(ofpacts);
2839     enum ofperr error = decode_stack_action(nasp, pop);
2840     return error ? error : nxm_stack_pop_check(pop, NULL);
2841 }
2842
2843 static void
2844 encode_STACK_op(const struct ofpact_stack *stack_action,
2845                 struct nx_action_stack *nasp)
2846 {
2847     struct ofpbuf b;
2848     ovs_be16 n_bits;
2849
2850     nasp->offset = htons(stack_action->subfield.ofs);
2851
2852     ofpbuf_use_stack(&b, nasp, ntohs(nasp->len));
2853     ofpbuf_put_uninit(&b, OBJECT_OFFSETOF(nasp, pad));
2854     nx_put_header(&b, stack_action->subfield.field->id, 0, false);
2855     n_bits = htons(stack_action->subfield.n_bits);
2856     ofpbuf_put(&b, &n_bits, sizeof n_bits);
2857 }
2858
2859 static void
2860 encode_STACK_PUSH(const struct ofpact_stack *stack,
2861                   enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
2862 {
2863     encode_STACK_op(stack, put_NXAST_STACK_PUSH(out));
2864 }
2865
2866 static void
2867 encode_STACK_POP(const struct ofpact_stack *stack,
2868                  enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
2869 {
2870     encode_STACK_op(stack, put_NXAST_STACK_POP(out));
2871 }
2872
2873 static char * OVS_WARN_UNUSED_RESULT
2874 parse_STACK_PUSH(char *arg, struct ofpbuf *ofpacts,
2875                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
2876 {
2877     return nxm_parse_stack_action(ofpact_put_STACK_PUSH(ofpacts), arg);
2878 }
2879
2880 static char * OVS_WARN_UNUSED_RESULT
2881 parse_STACK_POP(char *arg, struct ofpbuf *ofpacts,
2882                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
2883 {
2884     return nxm_parse_stack_action(ofpact_put_STACK_POP(ofpacts), arg);
2885 }
2886
2887 static void
2888 format_STACK_PUSH(const struct ofpact_stack *a, struct ds *s)
2889 {
2890     nxm_format_stack_push(a, s);
2891 }
2892
2893 static void
2894 format_STACK_POP(const struct ofpact_stack *a, struct ds *s)
2895 {
2896     nxm_format_stack_pop(a, s);
2897 }
2898 \f
2899 /* Action structure for NXAST_DEC_TTL_CNT_IDS.
2900  *
2901  * If the packet is not IPv4 or IPv6, does nothing.  For IPv4 or IPv6, if the
2902  * TTL or hop limit is at least 2, decrements it by 1.  Otherwise, if TTL or
2903  * hop limit is 0 or 1, sends a packet-in to the controllers with each of the
2904  * 'n_controllers' controller IDs specified in 'cnt_ids'.
2905  *
2906  * (This differs from NXAST_DEC_TTL in that for NXAST_DEC_TTL the packet-in is
2907  * sent only to controllers with id 0.)
2908  */
2909 struct nx_action_cnt_ids {
2910     ovs_be16 type;              /* OFPAT_VENDOR. */
2911     ovs_be16 len;               /* Length including slaves. */
2912     ovs_be32 vendor;            /* NX_VENDOR_ID. */
2913     ovs_be16 subtype;           /* NXAST_DEC_TTL_CNT_IDS. */
2914
2915     ovs_be16 n_controllers;     /* Number of controllers. */
2916     uint8_t zeros[4];           /* Must be zero. */
2917
2918     /* Followed by 1 or more controller ids.
2919      *
2920      * uint16_t cnt_ids[];        // Controller ids.
2921      * uint8_t pad[];           // Must be 0 to 8-byte align cnt_ids[].
2922      */
2923 };
2924 OFP_ASSERT(sizeof(struct nx_action_cnt_ids) == 16);
2925
2926 static enum ofperr
2927 decode_OFPAT_RAW_DEC_NW_TTL(struct ofpbuf *out)
2928 {
2929     uint16_t id = 0;
2930     struct ofpact_cnt_ids *ids;
2931     enum ofperr error = 0;
2932
2933     ids = ofpact_put_DEC_TTL(out);
2934     ids->n_controllers = 1;
2935     ofpbuf_put(out, &id, sizeof id);
2936     ids = out->header;
2937     ofpact_update_len(out, &ids->ofpact);
2938     return error;
2939 }
2940
2941 static enum ofperr
2942 decode_NXAST_RAW_DEC_TTL_CNT_IDS(const struct nx_action_cnt_ids *nac_ids,
2943                                  enum ofp_version ofp_version OVS_UNUSED,
2944                                  struct ofpbuf *out)
2945 {
2946     struct ofpact_cnt_ids *ids;
2947     size_t ids_size;
2948     int i;
2949
2950     ids = ofpact_put_DEC_TTL(out);
2951     ids->ofpact.raw = NXAST_RAW_DEC_TTL_CNT_IDS;
2952     ids->n_controllers = ntohs(nac_ids->n_controllers);
2953     ids_size = ntohs(nac_ids->len) - sizeof *nac_ids;
2954
2955     if (!is_all_zeros(nac_ids->zeros, sizeof nac_ids->zeros)) {
2956         return OFPERR_NXBRC_MUST_BE_ZERO;
2957     }
2958
2959     if (ids_size < ids->n_controllers * sizeof(ovs_be16)) {
2960         VLOG_WARN_RL(&rl, "Nicira action dec_ttl_cnt_ids only has %"PRIuSIZE" "
2961                      "bytes allocated for controller ids.  %"PRIuSIZE" bytes "
2962                      "are required for %"PRIu16" controllers.",
2963                      ids_size, ids->n_controllers * sizeof(ovs_be16),
2964                      ids->n_controllers);
2965         return OFPERR_OFPBAC_BAD_LEN;
2966     }
2967
2968     for (i = 0; i < ids->n_controllers; i++) {
2969         uint16_t id = ntohs(((ovs_be16 *)(nac_ids + 1))[i]);
2970         ofpbuf_put(out, &id, sizeof id);
2971         ids = out->header;
2972     }
2973
2974     ofpact_update_len(out, &ids->ofpact);
2975
2976     return 0;
2977 }
2978
2979 static void
2980 encode_DEC_TTL(const struct ofpact_cnt_ids *dec_ttl,
2981                enum ofp_version ofp_version, struct ofpbuf *out)
2982 {
2983     if (dec_ttl->ofpact.raw == NXAST_RAW_DEC_TTL_CNT_IDS
2984         || dec_ttl->n_controllers != 1
2985         || dec_ttl->cnt_ids[0] != 0) {
2986         struct nx_action_cnt_ids *nac_ids = put_NXAST_DEC_TTL_CNT_IDS(out);
2987         int ids_len = ROUND_UP(2 * dec_ttl->n_controllers, OFP_ACTION_ALIGN);
2988         ovs_be16 *ids;
2989         size_t i;
2990
2991         nac_ids->len = htons(ntohs(nac_ids->len) + ids_len);
2992         nac_ids->n_controllers = htons(dec_ttl->n_controllers);
2993
2994         ids = ofpbuf_put_zeros(out, ids_len);
2995         for (i = 0; i < dec_ttl->n_controllers; i++) {
2996             ids[i] = htons(dec_ttl->cnt_ids[i]);
2997         }
2998     } else {
2999         put_OFPAT_DEC_NW_TTL(out, ofp_version);
3000     }
3001 }
3002
3003 static void
3004 parse_noargs_dec_ttl(struct ofpbuf *ofpacts)
3005 {
3006     struct ofpact_cnt_ids *ids;
3007     uint16_t id = 0;
3008
3009     ofpact_put_DEC_TTL(ofpacts);
3010     ofpbuf_put(ofpacts, &id, sizeof id);
3011     ids = ofpacts->header;
3012     ids->n_controllers++;
3013     ofpact_update_len(ofpacts, &ids->ofpact);
3014 }
3015
3016 static char * OVS_WARN_UNUSED_RESULT
3017 parse_DEC_TTL(char *arg, struct ofpbuf *ofpacts,
3018               enum ofputil_protocol *usable_protocols OVS_UNUSED)
3019 {
3020     if (*arg == '\0') {
3021         parse_noargs_dec_ttl(ofpacts);
3022     } else {
3023         struct ofpact_cnt_ids *ids;
3024         char *cntr;
3025
3026         ids = ofpact_put_DEC_TTL(ofpacts);
3027         ids->ofpact.raw = NXAST_RAW_DEC_TTL_CNT_IDS;
3028         for (cntr = strtok_r(arg, ", ", &arg); cntr != NULL;
3029              cntr = strtok_r(NULL, ", ", &arg)) {
3030             uint16_t id = atoi(cntr);
3031
3032             ofpbuf_put(ofpacts, &id, sizeof id);
3033             ids = ofpacts->header;
3034             ids->n_controllers++;
3035         }
3036         if (!ids->n_controllers) {
3037             return xstrdup("dec_ttl_cnt_ids: expected at least one controller "
3038                            "id.");
3039         }
3040         ofpact_update_len(ofpacts, &ids->ofpact);
3041     }
3042     return NULL;
3043 }
3044
3045 static void
3046 format_DEC_TTL(const struct ofpact_cnt_ids *a, struct ds *s)
3047 {
3048     size_t i;
3049
3050     ds_put_cstr(s, "dec_ttl");
3051     if (a->ofpact.raw == NXAST_RAW_DEC_TTL_CNT_IDS) {
3052         ds_put_cstr(s, "(");
3053         for (i = 0; i < a->n_controllers; i++) {
3054             if (i) {
3055                 ds_put_cstr(s, ",");
3056             }
3057             ds_put_format(s, "%"PRIu16, a->cnt_ids[i]);
3058         }
3059         ds_put_cstr(s, ")");
3060     }
3061 }
3062 \f
3063 /* Set MPLS label actions. */
3064
3065 static enum ofperr
3066 decode_OFPAT_RAW_SET_MPLS_LABEL(ovs_be32 label,
3067                                 enum ofp_version ofp_version OVS_UNUSED,
3068                                 struct ofpbuf *out)
3069 {
3070     ofpact_put_SET_MPLS_LABEL(out)->label = label;
3071     return 0;
3072 }
3073
3074 static void
3075 encode_SET_MPLS_LABEL(const struct ofpact_mpls_label *label,
3076                       enum ofp_version ofp_version,
3077                                   struct ofpbuf *out)
3078 {
3079     if (ofp_version < OFP12_VERSION) {
3080         put_OFPAT_SET_MPLS_LABEL(out, ofp_version, label->label);
3081     } else {
3082         ofpact_put_set_field(out, ofp_version, MFF_MPLS_LABEL,
3083                              ntohl(label->label));
3084     }
3085 }
3086
3087 static char * OVS_WARN_UNUSED_RESULT
3088 parse_SET_MPLS_LABEL(char *arg, struct ofpbuf *ofpacts,
3089                      enum ofputil_protocol *usable_protocols OVS_UNUSED)
3090 {
3091     struct ofpact_mpls_label *mpls_label = ofpact_put_SET_MPLS_LABEL(ofpacts);
3092     if (*arg == '\0') {
3093         return xstrdup("set_mpls_label: expected label.");
3094     }
3095
3096     mpls_label->label = htonl(atoi(arg));
3097     return NULL;
3098 }
3099
3100 static void
3101 format_SET_MPLS_LABEL(const struct ofpact_mpls_label *a, struct ds *s)
3102 {
3103     ds_put_format(s, "set_mpls_label(%"PRIu32")", ntohl(a->label));
3104 }
3105 \f
3106 /* Set MPLS TC actions. */
3107
3108 static enum ofperr
3109 decode_OFPAT_RAW_SET_MPLS_TC(uint8_t tc,
3110                              enum ofp_version ofp_version OVS_UNUSED,
3111                              struct ofpbuf *out)
3112 {
3113     ofpact_put_SET_MPLS_TC(out)->tc = tc;
3114     return 0;
3115 }
3116
3117 static void
3118 encode_SET_MPLS_TC(const struct ofpact_mpls_tc *tc,
3119                    enum ofp_version ofp_version, struct ofpbuf *out)
3120 {
3121     if (ofp_version < OFP12_VERSION) {
3122         put_OFPAT_SET_MPLS_TC(out, ofp_version, tc->tc);
3123     } else {
3124         ofpact_put_set_field(out, ofp_version, MFF_MPLS_TC, tc->tc);
3125     }
3126 }
3127
3128 static char * OVS_WARN_UNUSED_RESULT
3129 parse_SET_MPLS_TC(char *arg, struct ofpbuf *ofpacts,
3130                   enum ofputil_protocol *usable_protocols OVS_UNUSED)
3131 {
3132     struct ofpact_mpls_tc *mpls_tc = ofpact_put_SET_MPLS_TC(ofpacts);
3133
3134     if (*arg == '\0') {
3135         return xstrdup("set_mpls_tc: expected tc.");
3136     }
3137
3138     mpls_tc->tc = atoi(arg);
3139     return NULL;
3140 }
3141
3142 static void
3143 format_SET_MPLS_TC(const struct ofpact_mpls_tc *a, struct ds *s)
3144 {
3145     ds_put_format(s, "set_mpls_ttl(%"PRIu8")", a->tc);
3146 }
3147 \f
3148 /* Set MPLS TTL actions. */
3149
3150 static enum ofperr
3151 decode_OFPAT_RAW_SET_MPLS_TTL(uint8_t ttl,
3152                               enum ofp_version ofp_version OVS_UNUSED,
3153                               struct ofpbuf *out)
3154 {
3155     ofpact_put_SET_MPLS_TTL(out)->ttl = ttl;
3156     return 0;
3157 }
3158
3159 static void
3160 encode_SET_MPLS_TTL(const struct ofpact_mpls_ttl *ttl,
3161                     enum ofp_version ofp_version, struct ofpbuf *out)
3162 {
3163     put_OFPAT_SET_MPLS_TTL(out, ofp_version, ttl->ttl);
3164 }
3165
3166 /* Parses 'arg' as the argument to a "set_mpls_ttl" action, and appends such an
3167  * action to 'ofpacts'.
3168  *
3169  * Returns NULL if successful, otherwise a malloc()'d string describing the
3170  * error.  The caller is responsible for freeing the returned string. */
3171 static char * OVS_WARN_UNUSED_RESULT
3172 parse_SET_MPLS_TTL(char *arg, struct ofpbuf *ofpacts,
3173                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
3174 {
3175     struct ofpact_mpls_ttl *mpls_ttl = ofpact_put_SET_MPLS_TTL(ofpacts);
3176
3177     if (*arg == '\0') {
3178         return xstrdup("set_mpls_ttl: expected ttl.");
3179     }
3180
3181     mpls_ttl->ttl = atoi(arg);
3182     return NULL;
3183 }
3184
3185 static void
3186 format_SET_MPLS_TTL(const struct ofpact_mpls_ttl *a, struct ds *s)
3187 {
3188     ds_put_format(s, "set_mpls_ttl(%"PRIu8")", a->ttl);
3189 }
3190 \f
3191 /* Decrement MPLS TTL actions. */
3192
3193 static enum ofperr
3194 decode_OFPAT_RAW_DEC_MPLS_TTL(struct ofpbuf *out)
3195 {
3196     ofpact_put_DEC_MPLS_TTL(out);
3197     return 0;
3198 }
3199
3200 static void
3201 encode_DEC_MPLS_TTL(const struct ofpact_null *null OVS_UNUSED,
3202                     enum ofp_version ofp_version, struct ofpbuf *out)
3203 {
3204     put_OFPAT_DEC_MPLS_TTL(out, ofp_version);
3205 }
3206
3207 static char * OVS_WARN_UNUSED_RESULT
3208 parse_DEC_MPLS_TTL(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
3209                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
3210 {
3211     ofpact_put_DEC_MPLS_TTL(ofpacts);
3212     return NULL;
3213 }
3214
3215 static void
3216 format_DEC_MPLS_TTL(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
3217 {
3218     ds_put_cstr(s, "dec_mpls_ttl");
3219 }
3220 \f
3221 /* Push MPLS label action. */
3222
3223 static enum ofperr
3224 decode_OFPAT_RAW_PUSH_MPLS(ovs_be16 ethertype,
3225                            enum ofp_version ofp_version OVS_UNUSED,
3226                            struct ofpbuf *out)
3227 {
3228     struct ofpact_push_mpls *oam;
3229
3230     if (!eth_type_mpls(ethertype)) {
3231         return OFPERR_OFPBAC_BAD_ARGUMENT;
3232     }
3233     oam = ofpact_put_PUSH_MPLS(out);
3234     oam->ethertype = ethertype;
3235
3236     return 0;
3237 }
3238
3239 static void
3240 encode_PUSH_MPLS(const struct ofpact_push_mpls *push_mpls,
3241                  enum ofp_version ofp_version, struct ofpbuf *out)
3242 {
3243     put_OFPAT_PUSH_MPLS(out, ofp_version, push_mpls->ethertype);
3244 }
3245
3246 static char * OVS_WARN_UNUSED_RESULT
3247 parse_PUSH_MPLS(char *arg, struct ofpbuf *ofpacts,
3248                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
3249 {
3250     uint16_t ethertype;
3251     char *error;
3252
3253     error = str_to_u16(arg, "push_mpls", &ethertype);
3254     if (!error) {
3255         ofpact_put_PUSH_MPLS(ofpacts)->ethertype = htons(ethertype);
3256     }
3257     return error;
3258 }
3259
3260 static void
3261 format_PUSH_MPLS(const struct ofpact_push_mpls *a, struct ds *s)
3262 {
3263     ds_put_format(s, "push_mpls:0x%04"PRIx16, ntohs(a->ethertype));
3264 }
3265 \f
3266 /* Pop MPLS label action. */
3267
3268 static enum ofperr
3269 decode_OFPAT_RAW_POP_MPLS(ovs_be16 ethertype,
3270                           enum ofp_version ofp_version OVS_UNUSED,
3271                           struct ofpbuf *out)
3272 {
3273     ofpact_put_POP_MPLS(out)->ethertype = ethertype;
3274     return 0;
3275 }
3276
3277 static void
3278 encode_POP_MPLS(const struct ofpact_pop_mpls *pop_mpls,
3279                 enum ofp_version ofp_version, struct ofpbuf *out)
3280 {
3281     put_OFPAT_POP_MPLS(out, ofp_version, pop_mpls->ethertype);
3282 }
3283
3284 static char * OVS_WARN_UNUSED_RESULT
3285 parse_POP_MPLS(char *arg, struct ofpbuf *ofpacts,
3286                     enum ofputil_protocol *usable_protocols OVS_UNUSED)
3287 {
3288     uint16_t ethertype;
3289     char *error;
3290
3291     error = str_to_u16(arg, "pop_mpls", &ethertype);
3292     if (!error) {
3293         ofpact_put_POP_MPLS(ofpacts)->ethertype = htons(ethertype);
3294     }
3295     return error;
3296 }
3297
3298 static void
3299 format_POP_MPLS(const struct ofpact_pop_mpls *a, struct ds *s)
3300 {
3301     ds_put_format(s, "pop_mpls:0x%04"PRIx16, ntohs(a->ethertype));
3302 }
3303 \f
3304 /* Set tunnel ID actions. */
3305
3306 static enum ofperr
3307 decode_NXAST_RAW_SET_TUNNEL(uint32_t tun_id,
3308                             enum ofp_version ofp_version OVS_UNUSED,
3309                             struct ofpbuf *out)
3310 {
3311     struct ofpact_tunnel *tunnel = ofpact_put_SET_TUNNEL(out);
3312     tunnel->ofpact.raw = NXAST_RAW_SET_TUNNEL;
3313     tunnel->tun_id = tun_id;
3314     return 0;
3315 }
3316
3317 static enum ofperr
3318 decode_NXAST_RAW_SET_TUNNEL64(uint64_t tun_id,
3319                               enum ofp_version ofp_version OVS_UNUSED,
3320                               struct ofpbuf *out)
3321 {
3322     struct ofpact_tunnel *tunnel = ofpact_put_SET_TUNNEL(out);
3323     tunnel->ofpact.raw = NXAST_RAW_SET_TUNNEL64;
3324     tunnel->tun_id = tun_id;
3325     return 0;
3326 }
3327
3328 static void
3329 encode_SET_TUNNEL(const struct ofpact_tunnel *tunnel,
3330                   enum ofp_version ofp_version, struct ofpbuf *out)
3331 {
3332     uint64_t tun_id = tunnel->tun_id;
3333
3334     if (ofp_version < OFP12_VERSION) {
3335         if (tun_id <= UINT32_MAX
3336             && tunnel->ofpact.raw != NXAST_RAW_SET_TUNNEL64) {
3337             put_NXAST_SET_TUNNEL(out, tun_id);
3338         } else {
3339             put_NXAST_SET_TUNNEL64(out, tun_id);
3340         }
3341     } else {
3342         ofpact_put_set_field(out, ofp_version, MFF_TUN_ID, tun_id);
3343     }
3344 }
3345
3346 static char * OVS_WARN_UNUSED_RESULT
3347 parse_set_tunnel(char *arg, struct ofpbuf *ofpacts,
3348                  enum ofp_raw_action_type raw)
3349 {
3350     struct ofpact_tunnel *tunnel;
3351
3352     tunnel = ofpact_put_SET_TUNNEL(ofpacts);
3353     tunnel->ofpact.raw = raw;
3354     return str_to_u64(arg, &tunnel->tun_id);
3355 }
3356
3357 static char * OVS_WARN_UNUSED_RESULT
3358 parse_SET_TUNNEL(char *arg, struct ofpbuf *ofpacts,
3359                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
3360 {
3361     return parse_set_tunnel(arg, ofpacts, NXAST_RAW_SET_TUNNEL);
3362 }
3363
3364 static void
3365 format_SET_TUNNEL(const struct ofpact_tunnel *a, struct ds *s)
3366 {
3367     ds_put_format(s, "set_tunnel%s:%#"PRIx64,
3368                   (a->tun_id > UINT32_MAX
3369                    || a->ofpact.raw == NXAST_RAW_SET_TUNNEL64 ? "64" : ""),
3370                   a->tun_id);
3371 }
3372 \f
3373 /* Set queue action. */
3374
3375 static enum ofperr
3376 decode_OFPAT_RAW_SET_QUEUE(uint32_t queue_id,
3377                            enum ofp_version ofp_version OVS_UNUSED,
3378                            struct ofpbuf *out)
3379 {
3380     ofpact_put_SET_QUEUE(out)->queue_id = queue_id;
3381     return 0;
3382 }
3383
3384 static void
3385 encode_SET_QUEUE(const struct ofpact_queue *queue,
3386                  enum ofp_version ofp_version, struct ofpbuf *out)
3387 {
3388     put_OFPAT_SET_QUEUE(out, ofp_version, queue->queue_id);
3389 }
3390
3391 static char * OVS_WARN_UNUSED_RESULT
3392 parse_SET_QUEUE(char *arg, struct ofpbuf *ofpacts,
3393                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
3394 {
3395     return str_to_u32(arg, &ofpact_put_SET_QUEUE(ofpacts)->queue_id);
3396 }
3397
3398 static void
3399 format_SET_QUEUE(const struct ofpact_queue *a, struct ds *s)
3400 {
3401     ds_put_format(s, "set_queue:%"PRIu32, a->queue_id);
3402 }
3403 \f
3404 /* Pop queue action. */
3405
3406 static enum ofperr
3407 decode_NXAST_RAW_POP_QUEUE(struct ofpbuf *out)
3408 {
3409     ofpact_put_POP_QUEUE(out);
3410     return 0;
3411 }
3412
3413 static void
3414 encode_POP_QUEUE(const struct ofpact_null *null OVS_UNUSED,
3415                  enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
3416 {
3417     put_NXAST_POP_QUEUE(out);
3418 }
3419
3420 static char * OVS_WARN_UNUSED_RESULT
3421 parse_POP_QUEUE(const char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
3422                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
3423 {
3424     ofpact_put_POP_QUEUE(ofpacts);
3425     return NULL;
3426 }
3427
3428 static void
3429 format_POP_QUEUE(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
3430 {
3431     ds_put_cstr(s, "pop_queue");
3432 }
3433 \f
3434 /* Action structure for NXAST_FIN_TIMEOUT.
3435  *
3436  * This action changes the idle timeout or hard timeout, or both, of this
3437  * OpenFlow rule when the rule matches a TCP packet with the FIN or RST flag.
3438  * When such a packet is observed, the action reduces the rule's idle timeout
3439  * to 'fin_idle_timeout' and its hard timeout to 'fin_hard_timeout'.  This
3440  * action has no effect on an existing timeout that is already shorter than the
3441  * one that the action specifies.  A 'fin_idle_timeout' or 'fin_hard_timeout'
3442  * of zero has no effect on the respective timeout.
3443  *
3444  * 'fin_idle_timeout' and 'fin_hard_timeout' are measured in seconds.
3445  * 'fin_hard_timeout' specifies time since the flow's creation, not since the
3446  * receipt of the FIN or RST.
3447  *
3448  * This is useful for quickly discarding learned TCP flows that otherwise will
3449  * take a long time to expire.
3450  *
3451  * This action is intended for use with an OpenFlow rule that matches only a
3452  * single TCP flow.  If the rule matches multiple TCP flows (e.g. it wildcards
3453  * all TCP traffic, or all TCP traffic to a particular port), then any FIN or
3454  * RST in any of those flows will cause the entire OpenFlow rule to expire
3455  * early, which is not normally desirable.
3456  */
3457 struct nx_action_fin_timeout {
3458     ovs_be16 type;              /* OFPAT_VENDOR. */
3459     ovs_be16 len;               /* 16. */
3460     ovs_be32 vendor;            /* NX_VENDOR_ID. */
3461     ovs_be16 subtype;           /* NXAST_FIN_TIMEOUT. */
3462     ovs_be16 fin_idle_timeout;  /* New idle timeout, if nonzero. */
3463     ovs_be16 fin_hard_timeout;  /* New hard timeout, if nonzero. */
3464     ovs_be16 pad;               /* Must be zero. */
3465 };
3466 OFP_ASSERT(sizeof(struct nx_action_fin_timeout) == 16);
3467
3468 static enum ofperr
3469 decode_NXAST_RAW_FIN_TIMEOUT(const struct nx_action_fin_timeout *naft,
3470                              enum ofp_version ofp_version OVS_UNUSED,
3471                              struct ofpbuf *out)
3472 {
3473     struct ofpact_fin_timeout *oft;
3474
3475     oft = ofpact_put_FIN_TIMEOUT(out);
3476     oft->fin_idle_timeout = ntohs(naft->fin_idle_timeout);
3477     oft->fin_hard_timeout = ntohs(naft->fin_hard_timeout);
3478     return 0;
3479 }
3480
3481 static void
3482 encode_FIN_TIMEOUT(const struct ofpact_fin_timeout *fin_timeout,
3483                    enum ofp_version ofp_version OVS_UNUSED,
3484                    struct ofpbuf *out)
3485 {
3486     struct nx_action_fin_timeout *naft = put_NXAST_FIN_TIMEOUT(out);
3487     naft->fin_idle_timeout = htons(fin_timeout->fin_idle_timeout);
3488     naft->fin_hard_timeout = htons(fin_timeout->fin_hard_timeout);
3489 }
3490
3491 static char * OVS_WARN_UNUSED_RESULT
3492 parse_FIN_TIMEOUT(char *arg, struct ofpbuf *ofpacts,
3493                   enum ofputil_protocol *usable_protocols OVS_UNUSED)
3494 {
3495     struct ofpact_fin_timeout *oft = ofpact_put_FIN_TIMEOUT(ofpacts);
3496     char *key, *value;
3497
3498     while (ofputil_parse_key_value(&arg, &key, &value)) {
3499         char *error;
3500
3501         if (!strcmp(key, "idle_timeout")) {
3502             error =  str_to_u16(value, key, &oft->fin_idle_timeout);
3503         } else if (!strcmp(key, "hard_timeout")) {
3504             error = str_to_u16(value, key, &oft->fin_hard_timeout);
3505         } else {
3506             error = xasprintf("invalid key '%s' in 'fin_timeout' argument",
3507                               key);
3508         }
3509
3510         if (error) {
3511             return error;
3512         }
3513     }
3514     return NULL;
3515 }
3516
3517 static void
3518 format_FIN_TIMEOUT(const struct ofpact_fin_timeout *a, struct ds *s)
3519 {
3520     ds_put_cstr(s, "fin_timeout(");
3521     if (a->fin_idle_timeout) {
3522         ds_put_format(s, "idle_timeout=%"PRIu16",", a->fin_idle_timeout);
3523     }
3524     if (a->fin_hard_timeout) {
3525         ds_put_format(s, "hard_timeout=%"PRIu16",", a->fin_hard_timeout);
3526     }
3527     ds_chomp(s, ',');
3528     ds_put_char(s, ')');
3529 }
3530 \f
3531 /* Action structures for NXAST_RESUBMIT and NXAST_RESUBMIT_TABLE.
3532  *
3533  * These actions search one of the switch's flow tables:
3534  *
3535  *    - For NXAST_RESUBMIT_TABLE only, if the 'table' member is not 255, then
3536  *      it specifies the table to search.
3537  *
3538  *    - Otherwise (for NXAST_RESUBMIT_TABLE with a 'table' of 255, or for
3539  *      NXAST_RESUBMIT regardless of 'table'), it searches the current flow
3540  *      table, that is, the OpenFlow flow table that contains the flow from
3541  *      which this action was obtained.  If this action did not come from a
3542  *      flow table (e.g. it came from an OFPT_PACKET_OUT message), then table 0
3543  *      is the current table.
3544  *
3545  * The flow table lookup uses a flow that may be slightly modified from the
3546  * original lookup:
3547  *
3548  *    - For NXAST_RESUBMIT, the 'in_port' member of struct nx_action_resubmit
3549  *      is used as the flow's in_port.
3550  *
3551  *    - For NXAST_RESUBMIT_TABLE, if the 'in_port' member is not OFPP_IN_PORT,
3552  *      then its value is used as the flow's in_port.  Otherwise, the original
3553  *      in_port is used.
3554  *
3555  *    - If actions that modify the flow (e.g. OFPAT_SET_VLAN_VID) precede the
3556  *      resubmit action, then the flow is updated with the new values.
3557  *
3558  * Following the lookup, the original in_port is restored.
3559  *
3560  * If the modified flow matched in the flow table, then the corresponding
3561  * actions are executed.  Afterward, actions following the resubmit in the
3562  * original set of actions, if any, are executed; any changes made to the
3563  * packet (e.g. changes to VLAN) by secondary actions persist when those
3564  * actions are executed, although the original in_port is restored.
3565  *
3566  * Resubmit actions may be used any number of times within a set of actions.
3567  *
3568  * Resubmit actions may nest to an implementation-defined depth.  Beyond this
3569  * implementation-defined depth, further resubmit actions are simply ignored.
3570  *
3571  * NXAST_RESUBMIT ignores 'table' and 'pad'.  NXAST_RESUBMIT_TABLE requires
3572  * 'pad' to be all-bits-zero.
3573  *
3574  * Open vSwitch 1.0.1 and earlier did not support recursion.  Open vSwitch
3575  * before 1.2.90 did not support NXAST_RESUBMIT_TABLE.
3576  */
3577 struct nx_action_resubmit {
3578     ovs_be16 type;                  /* OFPAT_VENDOR. */
3579     ovs_be16 len;                   /* Length is 16. */
3580     ovs_be32 vendor;                /* NX_VENDOR_ID. */
3581     ovs_be16 subtype;               /* NXAST_RESUBMIT. */
3582     ovs_be16 in_port;               /* New in_port for checking flow table. */
3583     uint8_t table;                  /* NXAST_RESUBMIT_TABLE: table to use. */
3584     uint8_t pad[3];
3585 };
3586 OFP_ASSERT(sizeof(struct nx_action_resubmit) == 16);
3587
3588 static enum ofperr
3589 decode_NXAST_RAW_RESUBMIT(uint16_t port,
3590                           enum ofp_version ofp_version OVS_UNUSED,
3591                           struct ofpbuf *out)
3592 {
3593     struct ofpact_resubmit *resubmit;
3594
3595     resubmit = ofpact_put_RESUBMIT(out);
3596     resubmit->ofpact.raw = NXAST_RAW_RESUBMIT;
3597     resubmit->in_port = u16_to_ofp(port);
3598     resubmit->table_id = 0xff;
3599     return 0;
3600 }
3601
3602 static enum ofperr
3603 decode_NXAST_RAW_RESUBMIT_TABLE(const struct nx_action_resubmit *nar,
3604                                 enum ofp_version ofp_version OVS_UNUSED,
3605                                 struct ofpbuf *out)
3606 {
3607     struct ofpact_resubmit *resubmit;
3608
3609     if (nar->pad[0] || nar->pad[1] || nar->pad[2]) {
3610         return OFPERR_OFPBAC_BAD_ARGUMENT;
3611     }
3612
3613     resubmit = ofpact_put_RESUBMIT(out);
3614     resubmit->ofpact.raw = NXAST_RAW_RESUBMIT_TABLE;
3615     resubmit->in_port = u16_to_ofp(ntohs(nar->in_port));
3616     resubmit->table_id = nar->table;
3617     return 0;
3618 }
3619
3620 static void
3621 encode_RESUBMIT(const struct ofpact_resubmit *resubmit,
3622                 enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
3623 {
3624     uint16_t in_port = ofp_to_u16(resubmit->in_port);
3625
3626     if (resubmit->table_id == 0xff
3627         && resubmit->ofpact.raw != NXAST_RAW_RESUBMIT_TABLE) {
3628         put_NXAST_RESUBMIT(out, in_port);
3629     } else {
3630         struct nx_action_resubmit *nar = put_NXAST_RESUBMIT_TABLE(out);
3631         nar->table = resubmit->table_id;
3632         nar->in_port = htons(in_port);
3633     }
3634 }
3635
3636 static char * OVS_WARN_UNUSED_RESULT
3637 parse_RESUBMIT(char *arg, struct ofpbuf *ofpacts,
3638                enum ofputil_protocol *usable_protocols OVS_UNUSED)
3639 {
3640     struct ofpact_resubmit *resubmit;
3641     char *in_port_s, *table_s;
3642
3643     resubmit = ofpact_put_RESUBMIT(ofpacts);
3644
3645     in_port_s = strsep(&arg, ",");
3646     if (in_port_s && in_port_s[0]) {
3647         if (!ofputil_port_from_string(in_port_s, &resubmit->in_port)) {
3648             return xasprintf("%s: resubmit to unknown port", in_port_s);
3649         }
3650     } else {
3651         resubmit->in_port = OFPP_IN_PORT;
3652     }
3653
3654     table_s = strsep(&arg, ",");
3655     if (table_s && table_s[0]) {
3656         uint32_t table_id = 0;
3657         char *error;
3658
3659         error = str_to_u32(table_s, &table_id);
3660         if (error) {
3661             return error;
3662         }
3663         resubmit->table_id = table_id;
3664     } else {
3665         resubmit->table_id = 255;
3666     }
3667
3668     if (resubmit->in_port == OFPP_IN_PORT && resubmit->table_id == 255) {
3669         return xstrdup("at least one \"in_port\" or \"table\" must be "
3670                        "specified  on resubmit");
3671     }
3672     return NULL;
3673 }
3674
3675 static void
3676 format_RESUBMIT(const struct ofpact_resubmit *a, struct ds *s)
3677 {
3678     if (a->in_port != OFPP_IN_PORT && a->table_id == 255) {
3679         ds_put_cstr(s, "resubmit:");
3680         ofputil_format_port(a->in_port, s);
3681     } else {
3682         ds_put_format(s, "resubmit(");
3683         if (a->in_port != OFPP_IN_PORT) {
3684             ofputil_format_port(a->in_port, s);
3685         }
3686         ds_put_char(s, ',');
3687         if (a->table_id != 255) {
3688             ds_put_format(s, "%"PRIu8, a->table_id);
3689         }
3690         ds_put_char(s, ')');
3691     }
3692 }
3693 \f
3694 /* Action structure for NXAST_LEARN.
3695  *
3696  * This action adds or modifies a flow in an OpenFlow table, similar to
3697  * OFPT_FLOW_MOD with OFPFC_MODIFY_STRICT as 'command'.  The new flow has the
3698  * specified idle timeout, hard timeout, priority, cookie, and flags.  The new
3699  * flow's match criteria and actions are built by applying each of the series
3700  * of flow_mod_spec elements included as part of the action.
3701  *
3702  * A flow_mod_spec starts with a 16-bit header.  A header that is all-bits-0 is
3703  * a no-op used for padding the action as a whole to a multiple of 8 bytes in
3704  * length.  Otherwise, the flow_mod_spec can be thought of as copying 'n_bits'
3705  * bits from a source to a destination.  In this case, the header contains
3706  * multiple fields:
3707  *
3708  *  15  14  13 12  11 10                              0
3709  * +------+---+------+---------------------------------+
3710  * |   0  |src|  dst |             n_bits              |
3711  * +------+---+------+---------------------------------+
3712  *
3713  * The meaning and format of a flow_mod_spec depends on 'src' and 'dst'.  The
3714  * following table summarizes the meaning of each possible combination.
3715  * Details follow the table:
3716  *
3717  *   src dst  meaning
3718  *   --- ---  ----------------------------------------------------------
3719  *    0   0   Add match criteria based on value in a field.
3720  *    1   0   Add match criteria based on an immediate value.
3721  *    0   1   Add NXAST_REG_LOAD action to copy field into a different field.
3722  *    1   1   Add NXAST_REG_LOAD action to load immediate value into a field.
3723  *    0   2   Add OFPAT_OUTPUT action to output to port from specified field.
3724  *   All other combinations are undefined and not allowed.
3725  *
3726  * The flow_mod_spec header is followed by a source specification and a
3727  * destination specification.  The format and meaning of the source
3728  * specification depends on 'src':
3729  *
3730  *   - If 'src' is 0, the source bits are taken from a field in the flow to
3731  *     which this action is attached.  (This should be a wildcarded field.  If
3732  *     its value is fully specified then the source bits being copied have
3733  *     constant values.)
3734  *
3735  *     The source specification is an ovs_be32 'field' and an ovs_be16 'ofs'.
3736  *     'field' is an nxm_header with nxm_hasmask=0, and 'ofs' the starting bit
3737  *     offset within that field.  The source bits are field[ofs:ofs+n_bits-1].
3738  *     'field' and 'ofs' are subject to the same restrictions as the source
3739  *     field in NXAST_REG_MOVE.
3740  *
3741  *   - If 'src' is 1, the source bits are a constant value.  The source
3742  *     specification is (n_bits+15)/16*2 bytes long.  Taking those bytes as a
3743  *     number in network order, the source bits are the 'n_bits'
3744  *     least-significant bits.  The switch will report an error if other bits
3745  *     in the constant are nonzero.
3746  *
3747  * The flow_mod_spec destination specification, for 'dst' of 0 or 1, is an
3748  * ovs_be32 'field' and an ovs_be16 'ofs'.  'field' is an nxm_header with
3749  * nxm_hasmask=0 and 'ofs' is a starting bit offset within that field.  The
3750  * meaning of the flow_mod_spec depends on 'dst':
3751  *
3752  *   - If 'dst' is 0, the flow_mod_spec specifies match criteria for the new
3753  *     flow.  The new flow matches only if bits field[ofs:ofs+n_bits-1] in a
3754  *     packet equal the source bits.  'field' may be any nxm_header with
3755  *     nxm_hasmask=0 that is allowed in NXT_FLOW_MOD.
3756  *
3757  *     Order is significant.  Earlier flow_mod_specs must satisfy any
3758  *     prerequisites for matching fields specified later, by copying constant
3759  *     values into prerequisite fields.
3760  *
3761  *     The switch will reject flow_mod_specs that do not satisfy NXM masking
3762  *     restrictions.
3763  *
3764  *   - If 'dst' is 1, the flow_mod_spec specifies an NXAST_REG_LOAD action for
3765  *     the new flow.  The new flow copies the source bits into
3766  *     field[ofs:ofs+n_bits-1].  Actions are executed in the same order as the
3767  *     flow_mod_specs.
3768  *
3769  *     A single NXAST_REG_LOAD action writes no more than 64 bits, so n_bits
3770  *     greater than 64 yields multiple NXAST_REG_LOAD actions.
3771  *
3772  * The flow_mod_spec destination spec for 'dst' of 2 (when 'src' is 0) is
3773  * empty.  It has the following meaning:
3774  *
3775  *   - The flow_mod_spec specifies an OFPAT_OUTPUT action for the new flow.
3776  *     The new flow outputs to the OpenFlow port specified by the source field.
3777  *     Of the special output ports with value OFPP_MAX or larger, OFPP_IN_PORT,
3778  *     OFPP_FLOOD, OFPP_LOCAL, and OFPP_ALL are supported.  Other special ports
3779  *     may not be used.
3780  *
3781  * Resource Management
3782  * -------------------
3783  *
3784  * A switch has a finite amount of flow table space available for learning.
3785  * When this space is exhausted, no new learning table entries will be learned
3786  * until some existing flow table entries expire.  The controller should be
3787  * prepared to handle this by flooding (which can be implemented as a
3788  * low-priority flow).
3789  *
3790  * If a learned flow matches a single TCP stream with a relatively long
3791  * timeout, one may make the best of resource constraints by setting
3792  * 'fin_idle_timeout' or 'fin_hard_timeout' (both measured in seconds), or
3793  * both, to shorter timeouts.  When either of these is specified as a nonzero
3794  * value, OVS adds a NXAST_FIN_TIMEOUT action, with the specified timeouts, to
3795  * the learned flow.
3796  *
3797  * Examples
3798  * --------
3799  *
3800  * The following examples give a prose description of the flow_mod_specs along
3801  * with informal notation for how those would be represented and a hex dump of
3802  * the bytes that would be required.
3803  *
3804  * These examples could work with various nx_action_learn parameters.  Typical
3805  * values would be idle_timeout=OFP_FLOW_PERMANENT, hard_timeout=60,
3806  * priority=OFP_DEFAULT_PRIORITY, flags=0, table_id=10.
3807  *
3808  * 1. Learn input port based on the source MAC, with lookup into
3809  *    NXM_NX_REG1[16:31] by resubmit to in_port=99:
3810  *
3811  *    Match on in_port=99:
3812  *       ovs_be16(src=1, dst=0, n_bits=16),               20 10
3813  *       ovs_be16(99),                                    00 63
3814  *       ovs_be32(NXM_OF_IN_PORT), ovs_be16(0)            00 00 00 02 00 00
3815  *
3816  *    Match Ethernet destination on Ethernet source from packet:
3817  *       ovs_be16(src=0, dst=0, n_bits=48),               00 30
3818  *       ovs_be32(NXM_OF_ETH_SRC), ovs_be16(0)            00 00 04 06 00 00
3819  *       ovs_be32(NXM_OF_ETH_DST), ovs_be16(0)            00 00 02 06 00 00
3820  *
3821  *    Set NXM_NX_REG1[16:31] to the packet's input port:
3822  *       ovs_be16(src=0, dst=1, n_bits=16),               08 10
3823  *       ovs_be32(NXM_OF_IN_PORT), ovs_be16(0)            00 00 00 02 00 00
3824  *       ovs_be32(NXM_NX_REG1), ovs_be16(16)              00 01 02 04 00 10
3825  *
3826  *    Given a packet that arrived on port A with Ethernet source address B,
3827  *    this would set up the flow "in_port=99, dl_dst=B,
3828  *    actions=load:A->NXM_NX_REG1[16..31]".
3829  *
3830  *    In syntax accepted by ovs-ofctl, this action is: learn(in_port=99,
3831  *    NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[],
3832  *    load:NXM_OF_IN_PORT[]->NXM_NX_REG1[16..31])
3833  *
3834  * 2. Output to input port based on the source MAC and VLAN VID, with lookup
3835  *    into NXM_NX_REG1[16:31]:
3836  *
3837  *    Match on same VLAN ID as packet:
3838  *       ovs_be16(src=0, dst=0, n_bits=12),               00 0c
3839  *       ovs_be32(NXM_OF_VLAN_TCI), ovs_be16(0)           00 00 08 02 00 00
3840  *       ovs_be32(NXM_OF_VLAN_TCI), ovs_be16(0)           00 00 08 02 00 00
3841  *
3842  *    Match Ethernet destination on Ethernet source from packet:
3843  *       ovs_be16(src=0, dst=0, n_bits=48),               00 30
3844  *       ovs_be32(NXM_OF_ETH_SRC), ovs_be16(0)            00 00 04 06 00 00
3845  *       ovs_be32(NXM_OF_ETH_DST), ovs_be16(0)            00 00 02 06 00 00
3846  *
3847  *    Output to the packet's input port:
3848  *       ovs_be16(src=0, dst=2, n_bits=16),               10 10
3849  *       ovs_be32(NXM_OF_IN_PORT), ovs_be16(0)            00 00 00 02 00 00
3850  *
3851  *    Given a packet that arrived on port A with Ethernet source address B in
3852  *    VLAN C, this would set up the flow "dl_dst=B, vlan_vid=C,
3853  *    actions=output:A".
3854  *
3855  *    In syntax accepted by ovs-ofctl, this action is:
3856  *    learn(NXM_OF_VLAN_TCI[0..11], NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[],
3857  *    output:NXM_OF_IN_PORT[])
3858  *
3859  * 3. Here's a recipe for a very simple-minded MAC learning switch.  It uses a
3860  *    10-second MAC expiration time to make it easier to see what's going on
3861  *
3862  *      ovs-vsctl del-controller br0
3863  *      ovs-ofctl del-flows br0
3864  *      ovs-ofctl add-flow br0 "table=0 actions=learn(table=1, \
3865           hard_timeout=10, NXM_OF_VLAN_TCI[0..11],             \
3866           NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[],                   \
3867           output:NXM_OF_IN_PORT[]), resubmit(,1)"
3868  *      ovs-ofctl add-flow br0 "table=1 priority=0 actions=flood"
3869  *
3870  *    You can then dump the MAC learning table with:
3871  *
3872  *      ovs-ofctl dump-flows br0 table=1
3873  *
3874  * Usage Advice
3875  * ------------
3876  *
3877  * For best performance, segregate learned flows into a table that is not used
3878  * for any other flows except possibly for a lowest-priority "catch-all" flow
3879  * (a flow with no match criteria).  If different learning actions specify
3880  * different match criteria, use different tables for the learned flows.
3881  *
3882  * The meaning of 'hard_timeout' and 'idle_timeout' can be counterintuitive.
3883  * These timeouts apply to the flow that is added, which means that a flow with
3884  * an idle timeout will expire when no traffic has been sent *to* the learned
3885  * address.  This is not usually the intent in MAC learning; instead, we want
3886  * the MAC learn entry to expire when no traffic has been sent *from* the
3887  * learned address.  Use a hard timeout for that.
3888  *
3889  *
3890  * Visibility of Changes
3891  * ---------------------
3892  *
3893  * Prior to Open vSwitch 2.4, any changes made by a "learn" action in a given
3894  * flow translation are visible to flow table lookups made later in the flow
3895  * translation.  This means that, in the example above, a MAC learned by the
3896  * learn action in table 0 would be found in table 1 (if the packet being
3897  * processed had the same source and destination MAC address).
3898  *
3899  * In Open vSwitch 2.4 and later, changes to a flow table (whether to add or
3900  * modify a flow) by a "learn" action are visible only for later flow
3901  * translations, not for later lookups within the same flow translation.  In
3902  * the MAC learning example, a MAC learned by the learn action in table 0 would
3903  * not be found in table 1 if the flow translation would resubmit to table 1
3904  * after the processing of the learn action, meaning that if this MAC had not
3905  * been learned before then the packet would be flooded. */
3906 struct nx_action_learn {
3907     ovs_be16 type;              /* OFPAT_VENDOR. */
3908     ovs_be16 len;               /* At least 24. */
3909     ovs_be32 vendor;            /* NX_VENDOR_ID. */
3910     ovs_be16 subtype;           /* NXAST_LEARN. */
3911     ovs_be16 idle_timeout;      /* Idle time before discarding (seconds). */
3912     ovs_be16 hard_timeout;      /* Max time before discarding (seconds). */
3913     ovs_be16 priority;          /* Priority level of flow entry. */
3914     ovs_be64 cookie;            /* Cookie for new flow. */
3915     ovs_be16 flags;             /* NX_LEARN_F_*. */
3916     uint8_t table_id;           /* Table to insert flow entry. */
3917     uint8_t pad;                /* Must be zero. */
3918     ovs_be16 fin_idle_timeout;  /* Idle timeout after FIN, if nonzero. */
3919     ovs_be16 fin_hard_timeout;  /* Hard timeout after FIN, if nonzero. */
3920     /* Followed by a sequence of flow_mod_spec elements, as described above,
3921      * until the end of the action is reached. */
3922 };
3923 OFP_ASSERT(sizeof(struct nx_action_learn) == 32);
3924
3925 static ovs_be16
3926 get_be16(const void **pp)
3927 {
3928     const ovs_be16 *p = *pp;
3929     ovs_be16 value = *p;
3930     *pp = p + 1;
3931     return value;
3932 }
3933
3934 static ovs_be32
3935 get_be32(const void **pp)
3936 {
3937     const ovs_be32 *p = *pp;
3938     ovs_be32 value = get_unaligned_be32(p);
3939     *pp = p + 1;
3940     return value;
3941 }
3942
3943 static void
3944 get_subfield(int n_bits, const void **p, struct mf_subfield *sf)
3945 {
3946     sf->field = mf_from_nxm_header(ntohl(get_be32(p)));
3947     sf->ofs = ntohs(get_be16(p));
3948     sf->n_bits = n_bits;
3949 }
3950
3951 static unsigned int
3952 learn_min_len(uint16_t header)
3953 {
3954     int n_bits = header & NX_LEARN_N_BITS_MASK;
3955     int src_type = header & NX_LEARN_SRC_MASK;
3956     int dst_type = header & NX_LEARN_DST_MASK;
3957     unsigned int min_len;
3958
3959     min_len = 0;
3960     if (src_type == NX_LEARN_SRC_FIELD) {
3961         min_len += sizeof(ovs_be32); /* src_field */
3962         min_len += sizeof(ovs_be16); /* src_ofs */
3963     } else {
3964         min_len += DIV_ROUND_UP(n_bits, 16);
3965     }
3966     if (dst_type == NX_LEARN_DST_MATCH ||
3967         dst_type == NX_LEARN_DST_LOAD) {
3968         min_len += sizeof(ovs_be32); /* dst_field */
3969         min_len += sizeof(ovs_be16); /* dst_ofs */
3970     }
3971     return min_len;
3972 }
3973
3974 /* Converts 'nal' into a "struct ofpact_learn" and appends that struct to
3975  * 'ofpacts'.  Returns 0 if successful, otherwise an OFPERR_*. */
3976 static enum ofperr
3977 decode_NXAST_RAW_LEARN(const struct nx_action_learn *nal,
3978                        enum ofp_version ofp_version OVS_UNUSED,
3979                        struct ofpbuf *ofpacts)
3980 {
3981     struct ofpact_learn *learn;
3982     const void *p, *end;
3983
3984     if (nal->pad) {
3985         return OFPERR_OFPBAC_BAD_ARGUMENT;
3986     }
3987
3988     learn = ofpact_put_LEARN(ofpacts);
3989
3990     learn->idle_timeout = ntohs(nal->idle_timeout);
3991     learn->hard_timeout = ntohs(nal->hard_timeout);
3992     learn->priority = ntohs(nal->priority);
3993     learn->cookie = nal->cookie;
3994     learn->table_id = nal->table_id;
3995     learn->fin_idle_timeout = ntohs(nal->fin_idle_timeout);
3996     learn->fin_hard_timeout = ntohs(nal->fin_hard_timeout);
3997
3998     learn->flags = ntohs(nal->flags);
3999     if (learn->flags & ~(NX_LEARN_F_SEND_FLOW_REM |
4000                          NX_LEARN_F_DELETE_LEARNED)) {
4001         return OFPERR_OFPBAC_BAD_ARGUMENT;
4002     }
4003
4004     if (learn->table_id == 0xff) {
4005         return OFPERR_OFPBAC_BAD_ARGUMENT;
4006     }
4007
4008     end = (char *) nal + ntohs(nal->len);
4009     for (p = nal + 1; p != end; ) {
4010         struct ofpact_learn_spec *spec;
4011         uint16_t header = ntohs(get_be16(&p));
4012
4013         if (!header) {
4014             break;
4015         }
4016
4017         spec = ofpbuf_put_zeros(ofpacts, sizeof *spec);
4018         learn = ofpacts->header;
4019         learn->n_specs++;
4020
4021         spec->src_type = header & NX_LEARN_SRC_MASK;
4022         spec->dst_type = header & NX_LEARN_DST_MASK;
4023         spec->n_bits = header & NX_LEARN_N_BITS_MASK;
4024
4025         /* Check for valid src and dst type combination. */
4026         if (spec->dst_type == NX_LEARN_DST_MATCH ||
4027             spec->dst_type == NX_LEARN_DST_LOAD ||
4028             (spec->dst_type == NX_LEARN_DST_OUTPUT &&
4029              spec->src_type == NX_LEARN_SRC_FIELD)) {
4030             /* OK. */
4031         } else {
4032             return OFPERR_OFPBAC_BAD_ARGUMENT;
4033         }
4034
4035         /* Check that the arguments don't overrun the end of the action. */
4036         if ((char *) end - (char *) p < learn_min_len(header)) {
4037             return OFPERR_OFPBAC_BAD_LEN;
4038         }
4039
4040         /* Get the source. */
4041         if (spec->src_type == NX_LEARN_SRC_FIELD) {
4042             get_subfield(spec->n_bits, &p, &spec->src);
4043         } else {
4044             int p_bytes = 2 * DIV_ROUND_UP(spec->n_bits, 16);
4045
4046             bitwise_copy(p, p_bytes, 0,
4047                          &spec->src_imm, sizeof spec->src_imm, 0,
4048                          spec->n_bits);
4049             p = (const uint8_t *) p + p_bytes;
4050         }
4051
4052         /* Get the destination. */
4053         if (spec->dst_type == NX_LEARN_DST_MATCH ||
4054             spec->dst_type == NX_LEARN_DST_LOAD) {
4055             get_subfield(spec->n_bits, &p, &spec->dst);
4056         }
4057     }
4058     ofpact_update_len(ofpacts, &learn->ofpact);
4059
4060     if (!is_all_zeros(p, (char *) end - (char *) p)) {
4061         return OFPERR_OFPBAC_BAD_ARGUMENT;
4062     }
4063
4064     return 0;
4065 }
4066
4067 static void
4068 put_be16(struct ofpbuf *b, ovs_be16 x)
4069 {
4070     ofpbuf_put(b, &x, sizeof x);
4071 }
4072
4073 static void
4074 put_be32(struct ofpbuf *b, ovs_be32 x)
4075 {
4076     ofpbuf_put(b, &x, sizeof x);
4077 }
4078
4079 static void
4080 put_u16(struct ofpbuf *b, uint16_t x)
4081 {
4082     put_be16(b, htons(x));
4083 }
4084
4085 static void
4086 put_u32(struct ofpbuf *b, uint32_t x)
4087 {
4088     put_be32(b, htonl(x));
4089 }
4090
4091 static void
4092 encode_LEARN(const struct ofpact_learn *learn,
4093              enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4094 {
4095     const struct ofpact_learn_spec *spec;
4096     struct nx_action_learn *nal;
4097     size_t start_ofs;
4098
4099     start_ofs = out->size;
4100     nal = put_NXAST_LEARN(out);
4101     nal->idle_timeout = htons(learn->idle_timeout);
4102     nal->hard_timeout = htons(learn->hard_timeout);
4103     nal->fin_idle_timeout = htons(learn->fin_idle_timeout);
4104     nal->fin_hard_timeout = htons(learn->fin_hard_timeout);
4105     nal->priority = htons(learn->priority);
4106     nal->cookie = learn->cookie;
4107     nal->flags = htons(learn->flags);
4108     nal->table_id = learn->table_id;
4109
4110     for (spec = learn->specs; spec < &learn->specs[learn->n_specs]; spec++) {
4111         put_u16(out, spec->n_bits | spec->dst_type | spec->src_type);
4112
4113         if (spec->src_type == NX_LEARN_SRC_FIELD) {
4114             put_u32(out, mf_nxm_header(spec->src.field->id));
4115             put_u16(out, spec->src.ofs);
4116         } else {
4117             size_t n_dst_bytes = 2 * DIV_ROUND_UP(spec->n_bits, 16);
4118             uint8_t *bits = ofpbuf_put_zeros(out, n_dst_bytes);
4119             bitwise_copy(&spec->src_imm, sizeof spec->src_imm, 0,
4120                          bits, n_dst_bytes, 0,
4121                          spec->n_bits);
4122         }
4123
4124         if (spec->dst_type == NX_LEARN_DST_MATCH ||
4125             spec->dst_type == NX_LEARN_DST_LOAD) {
4126             put_u32(out, mf_nxm_header(spec->dst.field->id));
4127             put_u16(out, spec->dst.ofs);
4128         }
4129     }
4130
4131     pad_ofpat(out, start_ofs);
4132 }
4133
4134 static char * OVS_WARN_UNUSED_RESULT
4135 parse_LEARN(char *arg, struct ofpbuf *ofpacts,
4136             enum ofputil_protocol *usable_protocols OVS_UNUSED)
4137 {
4138     return learn_parse(arg, ofpacts);
4139 }
4140
4141 static void
4142 format_LEARN(const struct ofpact_learn *a, struct ds *s)
4143 {
4144     learn_format(a, s);
4145 }
4146 \f
4147 /* Action structure for NXAST_CONJUNCTION. */
4148 struct nx_action_conjunction {
4149     ovs_be16 type;                  /* OFPAT_VENDOR. */
4150     ovs_be16 len;                   /* At least 16. */
4151     ovs_be32 vendor;                /* NX_VENDOR_ID. */
4152     ovs_be16 subtype;               /* See enum ofp_raw_action_type. */
4153     uint8_t clause;
4154     uint8_t n_clauses;
4155     ovs_be32 id;
4156 };
4157 OFP_ASSERT(sizeof(struct nx_action_conjunction) == 16);
4158
4159 static void
4160 add_conjunction(struct ofpbuf *out,
4161                 uint32_t id, uint8_t clause, uint8_t n_clauses)
4162 {
4163     struct ofpact_conjunction *oc;
4164
4165     oc = ofpact_put_CONJUNCTION(out);
4166     oc->id = id;
4167     oc->clause = clause;
4168     oc->n_clauses = n_clauses;
4169 }
4170
4171 static enum ofperr
4172 decode_NXAST_RAW_CONJUNCTION(const struct nx_action_conjunction *nac,
4173                              enum ofp_version ofp_version OVS_UNUSED,
4174                              struct ofpbuf *out)
4175 {
4176     if (nac->n_clauses < 2 || nac->n_clauses > 64
4177         || nac->clause >= nac->n_clauses) {
4178         return OFPERR_NXBAC_BAD_CONJUNCTION;
4179     } else {
4180         add_conjunction(out, ntohl(nac->id), nac->clause, nac->n_clauses);
4181         return 0;
4182     }
4183 }
4184
4185 static void
4186 encode_CONJUNCTION(const struct ofpact_conjunction *oc,
4187                    enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4188 {
4189     struct nx_action_conjunction *nac = put_NXAST_CONJUNCTION(out);
4190     nac->clause = oc->clause;
4191     nac->n_clauses = oc->n_clauses;
4192     nac->id = htonl(oc->id);
4193 }
4194
4195 static void
4196 format_CONJUNCTION(const struct ofpact_conjunction *oc, struct ds *s)
4197 {
4198     ds_put_format(s, "conjunction(%"PRIu32",%"PRIu8"/%"PRIu8")",
4199                   oc->id, oc->clause + 1, oc->n_clauses);
4200 }
4201
4202 static char * OVS_WARN_UNUSED_RESULT
4203 parse_CONJUNCTION(const char *arg, struct ofpbuf *ofpacts,
4204                   enum ofputil_protocol *usable_protocols OVS_UNUSED)
4205 {
4206     uint8_t n_clauses;
4207     uint8_t clause;
4208     uint32_t id;
4209     int n;
4210
4211     if (!ovs_scan(arg, "%"SCNi32" , %"SCNu8" / %"SCNu8" %n",
4212                   &id, &clause, &n_clauses, &n) || n != strlen(arg)) {
4213         return xstrdup("\"conjunction\" syntax is \"conjunction(id,i/n)\"");
4214     }
4215
4216     if (n_clauses < 2) {
4217         return xstrdup("conjunction must have at least 2 clauses");
4218     } else if (n_clauses > 64) {
4219         return xstrdup("conjunction must have at most 64 clauses");
4220     } else if (clause < 1) {
4221         return xstrdup("clause index must be positive");
4222     } else if (clause > n_clauses) {
4223         return xstrdup("clause index must be less than or equal to "
4224                        "number of clauses");
4225     }
4226
4227     add_conjunction(ofpacts, id, clause - 1, n_clauses);
4228     return NULL;
4229 }
4230 \f
4231 /* Action structure for NXAST_MULTIPATH.
4232  *
4233  * This action performs the following steps in sequence:
4234  *
4235  *    1. Hashes the fields designated by 'fields', one of NX_HASH_FIELDS_*.
4236  *       Refer to the definition of "enum nx_mp_fields" for details.
4237  *
4238  *       The 'basis' value is used as a universal hash parameter, that is,
4239  *       different values of 'basis' yield different hash functions.  The
4240  *       particular universal hash function used is implementation-defined.
4241  *
4242  *       The hashed fields' values are drawn from the current state of the
4243  *       flow, including all modifications that have been made by actions up to
4244  *       this point.
4245  *
4246  *    2. Applies the multipath link choice algorithm specified by 'algorithm',
4247  *       one of NX_MP_ALG_*.  Refer to the definition of "enum nx_mp_algorithm"
4248  *       for details.
4249  *
4250  *       The output of the algorithm is 'link', an unsigned integer less than
4251  *       or equal to 'max_link'.
4252  *
4253  *       Some algorithms use 'arg' as an additional argument.
4254  *
4255  *    3. Stores 'link' in dst[ofs:ofs+n_bits].  The format and semantics of
4256  *       'dst' and 'ofs_nbits' are similar to those for the NXAST_REG_LOAD
4257  *       action.
4258  *
4259  * The switch will reject actions that have an unknown 'fields', or an unknown
4260  * 'algorithm', or in which ofs+n_bits is greater than the width of 'dst', or
4261  * in which 'max_link' is greater than or equal to 2**n_bits, with error type
4262  * OFPET_BAD_ACTION, code OFPBAC_BAD_ARGUMENT.
4263  */
4264 struct nx_action_multipath {
4265     ovs_be16 type;              /* OFPAT_VENDOR. */
4266     ovs_be16 len;               /* Length is 32. */
4267     ovs_be32 vendor;            /* NX_VENDOR_ID. */
4268     ovs_be16 subtype;           /* NXAST_MULTIPATH. */
4269
4270     /* What fields to hash and how. */
4271     ovs_be16 fields;            /* One of NX_HASH_FIELDS_*. */
4272     ovs_be16 basis;             /* Universal hash parameter. */
4273     ovs_be16 pad0;
4274
4275     /* Multipath link choice algorithm to apply to hash value. */
4276     ovs_be16 algorithm;         /* One of NX_MP_ALG_*. */
4277     ovs_be16 max_link;          /* Number of output links, minus 1. */
4278     ovs_be32 arg;               /* Algorithm-specific argument. */
4279     ovs_be16 pad1;
4280
4281     /* Where to store the result. */
4282     ovs_be16 ofs_nbits;         /* (ofs << 6) | (n_bits - 1). */
4283     ovs_be32 dst;               /* Destination. */
4284 };
4285 OFP_ASSERT(sizeof(struct nx_action_multipath) == 32);
4286
4287 static enum ofperr
4288 decode_NXAST_RAW_MULTIPATH(const struct nx_action_multipath *nam,
4289                            enum ofp_version ofp_version OVS_UNUSED,
4290                            struct ofpbuf *out)
4291 {
4292     uint32_t n_links = ntohs(nam->max_link) + 1;
4293     size_t min_n_bits = log_2_ceil(n_links);
4294     struct ofpact_multipath *mp;
4295
4296     mp = ofpact_put_MULTIPATH(out);
4297     mp->fields = ntohs(nam->fields);
4298     mp->basis = ntohs(nam->basis);
4299     mp->algorithm = ntohs(nam->algorithm);
4300     mp->max_link = ntohs(nam->max_link);
4301     mp->arg = ntohl(nam->arg);
4302     mp->dst.field = mf_from_nxm_header(ntohl(nam->dst));
4303     mp->dst.ofs = nxm_decode_ofs(nam->ofs_nbits);
4304     mp->dst.n_bits = nxm_decode_n_bits(nam->ofs_nbits);
4305
4306     if (!flow_hash_fields_valid(mp->fields)) {
4307         VLOG_WARN_RL(&rl, "unsupported fields %d", (int) mp->fields);
4308         return OFPERR_OFPBAC_BAD_ARGUMENT;
4309     } else if (mp->algorithm != NX_MP_ALG_MODULO_N
4310                && mp->algorithm != NX_MP_ALG_HASH_THRESHOLD
4311                && mp->algorithm != NX_MP_ALG_HRW
4312                && mp->algorithm != NX_MP_ALG_ITER_HASH) {
4313         VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) mp->algorithm);
4314         return OFPERR_OFPBAC_BAD_ARGUMENT;
4315     } else if (mp->dst.n_bits < min_n_bits) {
4316         VLOG_WARN_RL(&rl, "multipath action requires at least %"PRIuSIZE" bits for "
4317                      "%"PRIu32" links", min_n_bits, n_links);
4318         return OFPERR_OFPBAC_BAD_ARGUMENT;
4319     }
4320
4321     return multipath_check(mp, NULL);
4322 }
4323
4324 static void
4325 encode_MULTIPATH(const struct ofpact_multipath *mp,
4326                  enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4327 {
4328     struct nx_action_multipath *nam = put_NXAST_MULTIPATH(out);
4329
4330     nam->fields = htons(mp->fields);
4331     nam->basis = htons(mp->basis);
4332     nam->algorithm = htons(mp->algorithm);
4333     nam->max_link = htons(mp->max_link);
4334     nam->arg = htonl(mp->arg);
4335     nam->ofs_nbits = nxm_encode_ofs_nbits(mp->dst.ofs, mp->dst.n_bits);
4336     nam->dst = htonl(mf_nxm_header(mp->dst.field->id));
4337 }
4338
4339 static char * OVS_WARN_UNUSED_RESULT
4340 parse_MULTIPATH(const char *arg, struct ofpbuf *ofpacts,
4341                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
4342 {
4343     return multipath_parse(ofpact_put_MULTIPATH(ofpacts), arg);
4344 }
4345
4346 static void
4347 format_MULTIPATH(const struct ofpact_multipath *a, struct ds *s)
4348 {
4349     multipath_format(a, s);
4350 }
4351 \f
4352 /* Action structure for NXAST_NOTE.
4353  *
4354  * This action has no effect.  It is variable length.  The switch does not
4355  * attempt to interpret the user-defined 'note' data in any way.  A controller
4356  * can use this action to attach arbitrary metadata to a flow.
4357  *
4358  * This action might go away in the future.
4359  */
4360 struct nx_action_note {
4361     ovs_be16 type;                  /* OFPAT_VENDOR. */
4362     ovs_be16 len;                   /* A multiple of 8, but at least 16. */
4363     ovs_be32 vendor;                /* NX_VENDOR_ID. */
4364     ovs_be16 subtype;               /* NXAST_NOTE. */
4365     uint8_t note[6];                /* Start of user-defined data. */
4366     /* Possibly followed by additional user-defined data. */
4367 };
4368 OFP_ASSERT(sizeof(struct nx_action_note) == 16);
4369
4370 static enum ofperr
4371 decode_NXAST_RAW_NOTE(const struct nx_action_note *nan,
4372                       enum ofp_version ofp_version OVS_UNUSED,
4373                       struct ofpbuf *out)
4374 {
4375     struct ofpact_note *note;
4376     unsigned int length;
4377
4378     length = ntohs(nan->len) - offsetof(struct nx_action_note, note);
4379     note = ofpact_put(out, OFPACT_NOTE,
4380                       offsetof(struct ofpact_note, data) + length);
4381     note->length = length;
4382     memcpy(note->data, nan->note, length);
4383
4384     return 0;
4385 }
4386
4387 static void
4388 encode_NOTE(const struct ofpact_note *note,
4389             enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4390 {
4391     size_t start_ofs = out->size;
4392     struct nx_action_note *nan;
4393
4394     put_NXAST_NOTE(out);
4395     out->size = out->size - sizeof nan->note;
4396
4397     ofpbuf_put(out, note->data, note->length);
4398     pad_ofpat(out, start_ofs);
4399 }
4400
4401 static char * OVS_WARN_UNUSED_RESULT
4402 parse_NOTE(const char *arg, struct ofpbuf *ofpacts,
4403            enum ofputil_protocol *usable_protocols OVS_UNUSED)
4404 {
4405     struct ofpact_note *note;
4406
4407     note = ofpact_put_NOTE(ofpacts);
4408     while (*arg != '\0') {
4409         uint8_t byte;
4410         bool ok;
4411
4412         if (*arg == '.') {
4413             arg++;
4414         }
4415         if (*arg == '\0') {
4416             break;
4417         }
4418
4419         byte = hexits_value(arg, 2, &ok);
4420         if (!ok) {
4421             return xstrdup("bad hex digit in `note' argument");
4422         }
4423         ofpbuf_put(ofpacts, &byte, 1);
4424
4425         note = ofpacts->header;
4426         note->length++;
4427
4428         arg += 2;
4429     }
4430     ofpact_update_len(ofpacts, &note->ofpact);
4431     return NULL;
4432 }
4433
4434 static void
4435 format_NOTE(const struct ofpact_note *a, struct ds *s)
4436 {
4437     size_t i;
4438
4439     ds_put_cstr(s, "note:");
4440     for (i = 0; i < a->length; i++) {
4441         if (i) {
4442             ds_put_char(s, '.');
4443         }
4444         ds_put_format(s, "%02"PRIx8, a->data[i]);
4445     }
4446 }
4447 \f
4448 /* Exit action. */
4449
4450 static enum ofperr
4451 decode_NXAST_RAW_EXIT(struct ofpbuf *out)
4452 {
4453     ofpact_put_EXIT(out);
4454     return 0;
4455 }
4456
4457 static void
4458 encode_EXIT(const struct ofpact_null *null OVS_UNUSED,
4459             enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4460 {
4461     put_NXAST_EXIT(out);
4462 }
4463
4464 static char * OVS_WARN_UNUSED_RESULT
4465 parse_EXIT(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
4466            enum ofputil_protocol *usable_protocols OVS_UNUSED)
4467 {
4468     ofpact_put_EXIT(ofpacts);
4469     return NULL;
4470 }
4471
4472 static void
4473 format_EXIT(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
4474 {
4475     ds_put_cstr(s, "exit");
4476 }
4477 \f
4478 /* Unroll xlate action. */
4479
4480 static void
4481 encode_UNROLL_XLATE(const struct ofpact_unroll_xlate *unroll OVS_UNUSED,
4482                     enum ofp_version ofp_version OVS_UNUSED,
4483                     struct ofpbuf *out OVS_UNUSED)
4484 {
4485     OVS_NOT_REACHED();
4486 }
4487
4488 static char * OVS_WARN_UNUSED_RESULT
4489 parse_UNROLL_XLATE(char *arg OVS_UNUSED, struct ofpbuf *ofpacts OVS_UNUSED,
4490                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
4491 {
4492     OVS_NOT_REACHED();
4493     return NULL;
4494 }
4495
4496 static void
4497 format_UNROLL_XLATE(const struct ofpact_unroll_xlate *a OVS_UNUSED,
4498                     struct ds *s)
4499 {
4500     ds_put_cstr(s, "unroll_xlate");
4501 }
4502 \f
4503 /* Action structure for NXAST_SAMPLE.
4504  *
4505  * Samples matching packets with the given probability and sends them
4506  * each to the set of collectors identified with the given ID.  The
4507  * probability is expressed as a number of packets to be sampled out
4508  * of USHRT_MAX packets, and must be >0.
4509  *
4510  * When sending packet samples to IPFIX collectors, the IPFIX flow
4511  * record sent for each sampled packet is associated with the given
4512  * observation domain ID and observation point ID.  Each IPFIX flow
4513  * record contain the sampled packet's headers when executing this
4514  * rule.  If a sampled packet's headers are modified by previous
4515  * actions in the flow, those modified headers are sent. */
4516 struct nx_action_sample {
4517     ovs_be16 type;                  /* OFPAT_VENDOR. */
4518     ovs_be16 len;                   /* Length is 24. */
4519     ovs_be32 vendor;                /* NX_VENDOR_ID. */
4520     ovs_be16 subtype;               /* NXAST_SAMPLE. */
4521     ovs_be16 probability;           /* Fraction of packets to sample. */
4522     ovs_be32 collector_set_id;      /* ID of collector set in OVSDB. */
4523     ovs_be32 obs_domain_id;         /* ID of sampling observation domain. */
4524     ovs_be32 obs_point_id;          /* ID of sampling observation point. */
4525 };
4526 OFP_ASSERT(sizeof(struct nx_action_sample) == 24);
4527
4528 static enum ofperr
4529 decode_NXAST_RAW_SAMPLE(const struct nx_action_sample *nas,
4530                         enum ofp_version ofp_version OVS_UNUSED,
4531                         struct ofpbuf *out)
4532 {
4533     struct ofpact_sample *sample;
4534
4535     sample = ofpact_put_SAMPLE(out);
4536     sample->probability = ntohs(nas->probability);
4537     sample->collector_set_id = ntohl(nas->collector_set_id);
4538     sample->obs_domain_id = ntohl(nas->obs_domain_id);
4539     sample->obs_point_id = ntohl(nas->obs_point_id);
4540
4541     if (sample->probability == 0) {
4542         return OFPERR_OFPBAC_BAD_ARGUMENT;
4543     }
4544
4545     return 0;
4546 }
4547
4548 static void
4549 encode_SAMPLE(const struct ofpact_sample *sample,
4550               enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4551 {
4552     struct nx_action_sample *nas;
4553
4554     nas = put_NXAST_SAMPLE(out);
4555     nas->probability = htons(sample->probability);
4556     nas->collector_set_id = htonl(sample->collector_set_id);
4557     nas->obs_domain_id = htonl(sample->obs_domain_id);
4558     nas->obs_point_id = htonl(sample->obs_point_id);
4559 }
4560
4561 /* Parses 'arg' as the argument to a "sample" action, and appends such an
4562  * action to 'ofpacts'.
4563  *
4564  * Returns NULL if successful, otherwise a malloc()'d string describing the
4565  * error.  The caller is responsible for freeing the returned string. */
4566 static char * OVS_WARN_UNUSED_RESULT
4567 parse_SAMPLE(char *arg, struct ofpbuf *ofpacts,
4568              enum ofputil_protocol *usable_protocols OVS_UNUSED)
4569 {
4570     struct ofpact_sample *os = ofpact_put_SAMPLE(ofpacts);
4571     char *key, *value;
4572
4573     while (ofputil_parse_key_value(&arg, &key, &value)) {
4574         char *error = NULL;
4575
4576         if (!strcmp(key, "probability")) {
4577             error = str_to_u16(value, "probability", &os->probability);
4578             if (!error && os->probability == 0) {
4579                 error = xasprintf("invalid probability value \"%s\"", value);
4580             }
4581         } else if (!strcmp(key, "collector_set_id")) {
4582             error = str_to_u32(value, &os->collector_set_id);
4583         } else if (!strcmp(key, "obs_domain_id")) {
4584             error = str_to_u32(value, &os->obs_domain_id);
4585         } else if (!strcmp(key, "obs_point_id")) {
4586             error = str_to_u32(value, &os->obs_point_id);
4587         } else {
4588             error = xasprintf("invalid key \"%s\" in \"sample\" argument",
4589                               key);
4590         }
4591         if (error) {
4592             return error;
4593         }
4594     }
4595     if (os->probability == 0) {
4596         return xstrdup("non-zero \"probability\" must be specified on sample");
4597     }
4598     return NULL;
4599 }
4600
4601 static void
4602 format_SAMPLE(const struct ofpact_sample *a, struct ds *s)
4603 {
4604     ds_put_format(s, "sample(probability=%"PRIu16",collector_set_id=%"PRIu32
4605                   ",obs_domain_id=%"PRIu32",obs_point_id=%"PRIu32")",
4606                   a->probability, a->collector_set_id,
4607                   a->obs_domain_id, a->obs_point_id);
4608 }
4609 \f
4610 /* debug_recirc instruction. */
4611
4612 static bool enable_debug;
4613
4614 void
4615 ofpact_dummy_enable(void)
4616 {
4617     enable_debug = true;
4618 }
4619
4620 static enum ofperr
4621 decode_NXAST_RAW_DEBUG_RECIRC(struct ofpbuf *out)
4622 {
4623     if (!enable_debug) {
4624         return OFPERR_OFPBAC_BAD_VENDOR_TYPE;
4625     }
4626
4627     ofpact_put_DEBUG_RECIRC(out);
4628     return 0;
4629 }
4630
4631 static void
4632 encode_DEBUG_RECIRC(const struct ofpact_null *n OVS_UNUSED,
4633                     enum ofp_version ofp_version OVS_UNUSED,
4634                     struct ofpbuf *out)
4635 {
4636     put_NXAST_DEBUG_RECIRC(out);
4637 }
4638
4639 static char * OVS_WARN_UNUSED_RESULT
4640 parse_DEBUG_RECIRC(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
4641                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
4642 {
4643     ofpact_put_DEBUG_RECIRC(ofpacts);
4644     return NULL;
4645 }
4646
4647 static void
4648 format_DEBUG_RECIRC(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
4649 {
4650     ds_put_cstr(s, "debug_recirc");
4651 }
4652
4653 /* Action structure for NXAST_CT.
4654  *
4655  * Pass traffic to the connection tracker.
4656  *
4657  * There are two important concepts to understanding the connection tracking
4658  * interface: Packet state and Connection state. Packets may be "Untracked" or
4659  * "Tracked". Connections may be "Uncommitted" or "Committed".
4660  *
4661  *   - Packet State:
4662  *
4663  *      Untracked packets have not yet passed through the connection tracker,
4664  *      and the connection state for such packets is unknown. In most cases,
4665  *      packets entering the OpenFlow pipeline will initially be in the
4666  *      untracked state. Untracked packets may become tracked by executing
4667  *      NXAST_CT with a "recirc_table" specified. This makes various aspects
4668  *      about the connection available, in particular the connection state.
4669  *
4670  *      Tracked packets have previously passed through the connection tracker.
4671  *      These packets will remain tracked through until the end of the OpenFlow
4672  *      pipeline. Tracked packets which have NXAST_CT executed with a
4673  *      "recirc_table" specified will return to the tracked state.
4674  *
4675  *      The packet state is only significant for the duration of packet
4676  *      processing within the OpenFlow pipeline.
4677  *
4678  *   - Connection State:
4679  *
4680  *      Multiple packets may be associated with a single connection. Initially,
4681  *      all connections are uncommitted. The connection state corresponding to
4682  *      a packet is available in the NXM_NX_CT_STATE field for tracked packets.
4683  *
4684  *      Uncommitted connections have no state stored about them. Uncommitted
4685  *      connections may transition into the committed state by executing
4686  *      NXAST_CT with the NX_CT_F_COMMIT flag.
4687  *
4688  *      Once a connection becomes committed, information may be gathered about
4689  *      the connection by passing subsequent packets through the connection
4690  *      tracker, and the state of the connection will be stored beyond the
4691  *      lifetime of packet processing.
4692  *
4693  *      Connections may transition back into the uncommitted state due to
4694  *      external timers, or due to the contents of packets that are sent to the
4695  *      connection tracker. This behaviour is outside of the scope of the
4696  *      OpenFlow interface.
4697  *
4698  * The "zone" specifies a context within which the tracking is done:
4699  *
4700  *      The connection tracking zone is a 16-bit number. Each zone is an
4701  *      independent connection tracking context. The connection state for each
4702  *      connection is completely separate for each zone, so if a connection
4703  *      is committed to zone A, then it will remain uncommitted in zone B.
4704  *      If NXAST_CT is executed with the same zone multiple times, later
4705  *      executions have no effect.
4706  *
4707  *      If 'zone_src' is nonzero, this specifies that the zone should be
4708  *      sourced from a field zone_src[ofs:ofs+nbits]. The format and semantics
4709  *      of 'zone_src' and 'zone_ofs_nbits' are similar to those for the
4710  *      NXAST_REG_LOAD action. The acceptable nxm_header values for 'zone_src'
4711  *      are the same as the acceptable nxm_header values for the 'src' field of
4712  *      NXAST_REG_MOVE.
4713  *
4714  *      If 'zone_src' is zero, then the value of 'zone_imm' will be used as the
4715  *      connection tracking zone.
4716  *
4717  * The "recirc_table" allows NXM_NX_CT_* fields to become available:
4718  *
4719  *      If "recirc_table" has a value other than NX_CT_RECIRC_NONE, then the
4720  *      packet will be logically cloned prior to executing this action. One
4721  *      copy will be sent to the connection tracker, then will be re-injected
4722  *      into the OpenFlow pipeline beginning at the OpenFlow table specified in
4723  *      this field. When the packet re-enters the pipeline, the NXM_NX_CT_*
4724  *      fields will be populated. The original instance of the packet will
4725  *      continue the current actions list. This can be thought of as similar to
4726  *      the effect of the "output" action: One copy is sent out (in this case,
4727  *      to the connection tracker), but the current copy continues processing.
4728  *
4729  *      It is strongly recommended that this table is later than the current
4730  *      table, to prevent loops.
4731  *
4732  * The "alg" attaches protocol-specific behaviour to this action:
4733  *
4734  *      The ALG is a 16-bit number which specifies that additional
4735  *      processing should be applied to this traffic.
4736  *
4737  *      Protocol | Value | Meaning
4738  *      --------------------------------------------------------------------
4739  *      None     |     0 | No protocol-specific behaviour.
4740  *      FTP      |    21 | Parse FTP control connections and observe the
4741  *               |       | negotiation of related data connections.
4742  *      Other    | Other | Unsupported protocols.
4743  *
4744  *      By way of example, if FTP control connections have this action applied
4745  *      with the ALG set to FTP (21), then the connection tracker will observe
4746  *      the negotiation of data connections. This allows the connection
4747  *      tracker to identify subsequent data connections as "related" to this
4748  *      existing connection. The "related" flag will be populated in the
4749  *      NXM_NX_CT_STATE field for such connections if the 'recirc_table' is
4750  *      specified.
4751  *
4752  * Zero or more actions may immediately follow this action. These actions will
4753  * be executed within the context of the connection tracker, and they require
4754  * the NX_CT_F_COMMIT flag to be set.
4755  */
4756 struct nx_action_conntrack {
4757     ovs_be16 type;              /* OFPAT_VENDOR. */
4758     ovs_be16 len;               /* At least 24. */
4759     ovs_be32 vendor;            /* NX_VENDOR_ID. */
4760     ovs_be16 subtype;           /* NXAST_CT. */
4761     ovs_be16 flags;             /* Zero or more NX_CT_F_* flags.
4762                                  * Unspecified flag bits must be zero. */
4763     ovs_be32 zone_src;          /* Connection tracking context. */
4764     union {
4765         ovs_be16 zone_ofs_nbits;/* Range to use from source field. */
4766         ovs_be16 zone_imm;      /* Immediate value for zone. */
4767     };
4768     uint8_t recirc_table;       /* Recirculate to a specific table, or
4769                                    NX_CT_RECIRC_NONE for no recirculation. */
4770     uint8_t pad[3];             /* Zeroes */
4771     ovs_be16 alg;               /* Well-known port number for the protocol.
4772                                  * 0 indicates no ALG is required. */
4773     /* Followed by a sequence of zero or more OpenFlow actions. The length of
4774      * these is included in 'len'. */
4775 };
4776 OFP_ASSERT(sizeof(struct nx_action_conntrack) == 24);
4777
4778 static enum ofperr
4779 decode_ct_zone(const struct nx_action_conntrack *nac,
4780                struct ofpact_conntrack *out)
4781 {
4782     if (nac->zone_src) {
4783         enum ofperr error;
4784
4785         out->zone_src.field = mf_from_nxm_header(ntohl(nac->zone_src));
4786         out->zone_src.ofs = nxm_decode_ofs(nac->zone_ofs_nbits);
4787         out->zone_src.n_bits = nxm_decode_n_bits(nac->zone_ofs_nbits);
4788         error = mf_check_src(&out->zone_src, NULL);
4789         if (error) {
4790             return error;
4791         }
4792
4793         if (out->zone_src.n_bits != 16) {
4794             VLOG_WARN_RL(&rl, "zone n_bits %d not within valid range [16..16]",
4795                          out->zone_src.n_bits);
4796             return OFPERR_OFPBAC_BAD_SET_LEN;
4797         }
4798     } else {
4799         out->zone_src.field = NULL;
4800         out->zone_imm = ntohs(nac->zone_imm);
4801     }
4802
4803     return 0;
4804 }
4805
4806 static enum ofperr
4807 decode_NXAST_RAW_CT(const struct nx_action_conntrack *nac,
4808                     enum ofp_version ofp_version, struct ofpbuf *out)
4809 {
4810     const size_t ct_offset = ofpacts_pull(out);
4811     struct ofpact_conntrack *conntrack;
4812     struct ofpbuf openflow;
4813     int error = 0;
4814
4815     conntrack = ofpact_put_CT(out);
4816     conntrack->flags = ntohs(nac->flags);
4817     error = decode_ct_zone(nac, conntrack);
4818     if (error) {
4819         goto out;
4820     }
4821     conntrack->recirc_table = nac->recirc_table;
4822     conntrack->alg = ntohs(nac->alg);
4823
4824     ofpbuf_pull(out, sizeof(*conntrack));
4825
4826     ofpbuf_use_const(&openflow, nac + 1, ntohs(nac->len) - sizeof(*nac));
4827     error = ofpacts_pull_openflow_actions__(&openflow, openflow.size,
4828                                             ofp_version,
4829                                             1u << OVSINST_OFPIT11_APPLY_ACTIONS,
4830                                             out, OFPACT_CT);
4831     if (error) {
4832         goto out;
4833     }
4834
4835     conntrack = ofpbuf_push_uninit(out, sizeof(*conntrack));
4836     out->header = &conntrack->ofpact;
4837     ofpact_update_len(out, &conntrack->ofpact);
4838
4839     if (conntrack->ofpact.len > sizeof(*conntrack)
4840         && !(conntrack->flags & NX_CT_F_COMMIT)) {
4841         const struct ofpact *a;
4842         size_t ofpacts_len = conntrack->ofpact.len - sizeof(*conntrack);
4843
4844         OFPACT_FOR_EACH (a, conntrack->actions, ofpacts_len) {
4845             if (a->type != OFPACT_NAT || ofpact_get_NAT(a)->flags
4846                 || ofpact_get_NAT(a)->range_af != AF_UNSPEC) {
4847                 VLOG_WARN_RL(&rl, "CT action requires commit flag if actions "
4848                              "other than NAT without arguments are specified.");
4849                 error = OFPERR_OFPBAC_BAD_ARGUMENT;
4850                 goto out;
4851             }
4852         }
4853     }
4854
4855 out:
4856     ofpbuf_push_uninit(out, ct_offset);
4857     return error;
4858 }
4859
4860 static void
4861 encode_CT(const struct ofpact_conntrack *conntrack,
4862           enum ofp_version ofp_version, struct ofpbuf *out)
4863 {
4864     struct nx_action_conntrack *nac;
4865     const size_t ofs = out->size;
4866     size_t len;
4867
4868     nac = put_NXAST_CT(out);
4869     nac->flags = htons(conntrack->flags);
4870     if (conntrack->zone_src.field) {
4871         nac->zone_src = htonl(mf_nxm_header(conntrack->zone_src.field->id));
4872         nac->zone_ofs_nbits = nxm_encode_ofs_nbits(conntrack->zone_src.ofs,
4873                                                    conntrack->zone_src.n_bits);
4874     } else {
4875         nac->zone_src = htonl(0);
4876         nac->zone_imm = htons(conntrack->zone_imm);
4877     }
4878     nac->recirc_table = conntrack->recirc_table;
4879     nac->alg = htons(conntrack->alg);
4880
4881     len = ofpacts_put_openflow_actions(conntrack->actions,
4882                                        ofpact_ct_get_action_len(conntrack),
4883                                        out, ofp_version);
4884     len += sizeof(*nac);
4885     nac = ofpbuf_at(out, ofs, sizeof(*nac));
4886     nac->len = htons(len);
4887 }
4888
4889 static char * OVS_WARN_UNUSED_RESULT parse_NAT(char *arg, struct ofpbuf *,
4890                                                enum ofputil_protocol * OVS_UNUSED);
4891
4892 /* Parses 'arg' as the argument to a "ct" action, and appends such an
4893  * action to 'ofpacts'.
4894  *
4895  * Returns NULL if successful, otherwise a malloc()'d string describing the
4896  * error.  The caller is responsible for freeing the returned string. */
4897 static char * OVS_WARN_UNUSED_RESULT
4898 parse_CT(char *arg, struct ofpbuf *ofpacts,
4899          enum ofputil_protocol *usable_protocols)
4900 {
4901     const size_t ct_offset = ofpacts_pull(ofpacts);
4902     struct ofpact_conntrack *oc;
4903     char *error = NULL;
4904     char *key, *value;
4905
4906     oc = ofpact_put_CT(ofpacts);
4907     oc->flags = 0;
4908     oc->recirc_table = NX_CT_RECIRC_NONE;
4909     while (ofputil_parse_key_value(&arg, &key, &value)) {
4910         if (!strcmp(key, "commit")) {
4911             oc->flags |= NX_CT_F_COMMIT;
4912         } else if (!strcmp(key, "table")) {
4913             error = str_to_u8(value, "recirc_table", &oc->recirc_table);
4914             if (!error && oc->recirc_table == NX_CT_RECIRC_NONE) {
4915                 error = xasprintf("invalid table %#"PRIx16, oc->recirc_table);
4916             }
4917         } else if (!strcmp(key, "zone")) {
4918             error = str_to_u16(value, "zone", &oc->zone_imm);
4919
4920             if (error) {
4921                 free(error);
4922                 error = mf_parse_subfield(&oc->zone_src, value);
4923                 if (error) {
4924                     return error;
4925                 }
4926             }
4927         } else if (!strcmp(key, "alg")) {
4928             error = str_to_connhelper(value, &oc->alg);
4929         } else if (!strcmp(key, "nat")) {
4930             const size_t nat_offset = ofpacts_pull(ofpacts);
4931
4932             error = parse_NAT(value, ofpacts, usable_protocols);
4933             ofpact_pad(ofpacts);
4934             /* Update CT action pointer and length. */
4935             ofpacts->header = ofpbuf_push_uninit(ofpacts, nat_offset);
4936             oc = ofpacts->header;
4937         } else if (!strcmp(key, "exec")) {
4938             /* Hide existing actions from ofpacts_parse_copy(), so the
4939              * nesting can be handled transparently. */
4940             enum ofputil_protocol usable_protocols2;
4941             const size_t exec_offset = ofpacts_pull(ofpacts);
4942
4943             /* Initializes 'usable_protocol2', fold it back to
4944              * '*usable_protocols' afterwards, so that we do not lose
4945              * restrictions already in there. */
4946             error = ofpacts_parse_copy(value, ofpacts, &usable_protocols2,
4947                                        false, OFPACT_CT);
4948             *usable_protocols &= usable_protocols2;
4949             ofpact_pad(ofpacts);
4950             ofpacts->header = ofpbuf_push_uninit(ofpacts, exec_offset);
4951             oc = ofpacts->header;
4952         } else {
4953             error = xasprintf("invalid argument to \"ct\" action: `%s'", key);
4954         }
4955         if (error) {
4956             break;
4957         }
4958     }
4959
4960     ofpact_update_len(ofpacts, &oc->ofpact);
4961     ofpbuf_push_uninit(ofpacts, ct_offset);
4962     return error;
4963 }
4964
4965 static void
4966 format_alg(int port, struct ds *s)
4967 {
4968     if (port == IPPORT_FTP) {
4969         ds_put_format(s, "alg=ftp,");
4970     } else if (port) {
4971         ds_put_format(s, "alg=%d,", port);
4972     }
4973 }
4974
4975 static void format_NAT(const struct ofpact_nat *a, struct ds *ds);
4976
4977 static void
4978 format_CT(const struct ofpact_conntrack *a, struct ds *s)
4979 {
4980     ds_put_cstr(s, "ct(");
4981     if (a->flags & NX_CT_F_COMMIT) {
4982         ds_put_cstr(s, "commit,");
4983     }
4984     if (a->recirc_table != NX_CT_RECIRC_NONE) {
4985         ds_put_format(s, "table=%"PRIu8",", a->recirc_table);
4986     }
4987     if (a->zone_src.field) {
4988         ds_put_format(s, "zone=");
4989         mf_format_subfield(&a->zone_src, s);
4990         ds_put_char(s, ',');
4991     } else if (a->zone_imm) {
4992         ds_put_format(s, "zone=%"PRIu16",", a->zone_imm);
4993     }
4994     /* If the first action is a NAT action, format it outside of the 'exec'
4995      * envelope. */
4996     const struct ofpact *action = a->actions;
4997     size_t actions_len = ofpact_ct_get_action_len(a);
4998     if (actions_len && action->type == OFPACT_NAT) {
4999         format_NAT(ofpact_get_NAT(action), s);
5000         ds_put_char(s, ',');
5001         actions_len -= OFPACT_ALIGN(action->len);
5002         action = ofpact_next(action);
5003     }
5004     if (actions_len) {
5005         ds_put_cstr(s, "exec(");
5006         ofpacts_format(action, actions_len, s);
5007         ds_put_cstr(s, "),");
5008     }
5009     format_alg(a->alg, s);
5010     ds_chomp(s, ',');
5011     ds_put_char(s, ')');
5012 }
5013 \f
5014 /* NAT action. */
5015
5016 /* Which optional fields are present? */
5017 enum nx_nat_range {
5018     NX_NAT_RANGE_IPV4_MIN  = 1 << 0, /* ovs_be32 */
5019     NX_NAT_RANGE_IPV4_MAX  = 1 << 1, /* ovs_be32 */
5020     NX_NAT_RANGE_IPV6_MIN  = 1 << 2, /* struct in6_addr */
5021     NX_NAT_RANGE_IPV6_MAX  = 1 << 3, /* struct in6_addr */
5022     NX_NAT_RANGE_PROTO_MIN = 1 << 4, /* ovs_be16 */
5023     NX_NAT_RANGE_PROTO_MAX = 1 << 5, /* ovs_be16 */
5024 };
5025
5026 /* Action structure for NXAST_NAT. */
5027 struct nx_action_nat {
5028     ovs_be16 type;              /* OFPAT_VENDOR. */
5029     ovs_be16 len;               /* At least 16. */
5030     ovs_be32 vendor;            /* NX_VENDOR_ID. */
5031     ovs_be16 subtype;           /* NXAST_NAT. */
5032     uint8_t  pad[2];            /* Must be zero. */
5033     ovs_be16 flags;             /* Zero or more NX_NAT_F_* flags.
5034                                  * Unspecified flag bits must be zero. */
5035     ovs_be16 range_present;     /* NX_NAT_RANGE_* */
5036     /* Followed by optional parameters as specified by 'range_present' */
5037 };
5038 OFP_ASSERT(sizeof(struct nx_action_nat) == 16);
5039
5040 static void
5041 encode_NAT(const struct ofpact_nat *nat,
5042            enum ofp_version ofp_version OVS_UNUSED,
5043            struct ofpbuf *out)
5044 {
5045     struct nx_action_nat *nan;
5046     const size_t ofs = out->size;
5047     uint16_t range_present = 0;
5048
5049     nan = put_NXAST_NAT(out);
5050     nan->flags = htons(nat->flags);
5051     if (nat->range_af == AF_INET) {
5052         if (nat->range.addr.ipv4.min) {
5053             ovs_be32 *min = ofpbuf_put_uninit(out, sizeof *min);
5054             *min = nat->range.addr.ipv4.min;
5055             range_present |= NX_NAT_RANGE_IPV4_MIN;
5056         }
5057         if (nat->range.addr.ipv4.max) {
5058             ovs_be32 *max = ofpbuf_put_uninit(out, sizeof *max);
5059             *max = nat->range.addr.ipv4.max;
5060             range_present |= NX_NAT_RANGE_IPV4_MAX;
5061         }
5062     } else if (nat->range_af == AF_INET6) {
5063         if (!ipv6_mask_is_any(&nat->range.addr.ipv6.min)) {
5064             struct in6_addr *min = ofpbuf_put_uninit(out, sizeof *min);
5065             *min = nat->range.addr.ipv6.min;
5066             range_present |= NX_NAT_RANGE_IPV6_MIN;
5067         }
5068         if (!ipv6_mask_is_any(&nat->range.addr.ipv6.max)) {
5069             struct in6_addr *max = ofpbuf_put_uninit(out, sizeof *max);
5070             *max = nat->range.addr.ipv6.max;
5071             range_present |= NX_NAT_RANGE_IPV6_MAX;
5072         }
5073     }
5074     if (nat->range_af != AF_UNSPEC) {
5075         if (nat->range.proto.min) {
5076             ovs_be16 *min = ofpbuf_put_uninit(out, sizeof *min);
5077             *min = htons(nat->range.proto.min);
5078             range_present |= NX_NAT_RANGE_PROTO_MIN;
5079         }
5080         if (nat->range.proto.max) {
5081             ovs_be16 *max = ofpbuf_put_uninit(out, sizeof *max);
5082             *max = htons(nat->range.proto.max);
5083             range_present |= NX_NAT_RANGE_PROTO_MAX;
5084         }
5085     }
5086     pad_ofpat(out, ofs);
5087     nan = ofpbuf_at(out, ofs, sizeof *nan);
5088     nan->range_present = htons(range_present);
5089 }
5090
5091 static enum ofperr
5092 decode_NXAST_RAW_NAT(const struct nx_action_nat *nan,
5093                      enum ofp_version ofp_version OVS_UNUSED,
5094                      struct ofpbuf *out)
5095 {
5096     struct ofpact_nat *nat;
5097     uint16_t range_present = ntohs(nan->range_present);
5098     const char *opts = (char *)(nan + 1);
5099     uint16_t len = ntohs(nan->len) - sizeof *nan;
5100
5101     nat = ofpact_put_NAT(out);
5102     nat->flags = ntohs(nan->flags);
5103
5104 #define NX_NAT_GET_OPT(DST, SRC, LEN, TYPE)                     \
5105     (LEN >= sizeof(TYPE)                                        \
5106      ? (memcpy(DST, SRC, sizeof(TYPE)), LEN -= sizeof(TYPE),    \
5107         SRC += sizeof(TYPE))                                    \
5108      : NULL)
5109
5110     nat->range_af = AF_UNSPEC;
5111     if (range_present & NX_NAT_RANGE_IPV4_MIN) {
5112         if (range_present & (NX_NAT_RANGE_IPV6_MIN | NX_NAT_RANGE_IPV6_MAX)) {
5113             return OFPERR_OFPBAC_BAD_ARGUMENT;
5114         }
5115
5116         if (!NX_NAT_GET_OPT(&nat->range.addr.ipv4.min, opts, len, ovs_be32)
5117             || !nat->range.addr.ipv4.min) {
5118             return OFPERR_OFPBAC_BAD_ARGUMENT;
5119         }
5120
5121         nat->range_af = AF_INET;
5122
5123         if (range_present & NX_NAT_RANGE_IPV4_MAX) {
5124             if (!NX_NAT_GET_OPT(&nat->range.addr.ipv4.max, opts, len,
5125                                 ovs_be32)) {
5126                 return OFPERR_OFPBAC_BAD_ARGUMENT;
5127             }
5128             if (ntohl(nat->range.addr.ipv4.max)
5129                 < ntohl(nat->range.addr.ipv4.min)) {
5130                 return OFPERR_OFPBAC_BAD_ARGUMENT;
5131             }
5132         }
5133     } else if (range_present & NX_NAT_RANGE_IPV4_MAX) {
5134         return OFPERR_OFPBAC_BAD_ARGUMENT;
5135     } else if (range_present & NX_NAT_RANGE_IPV6_MIN) {
5136         if (!NX_NAT_GET_OPT(&nat->range.addr.ipv6.min, opts, len,
5137                             struct in6_addr)
5138             || ipv6_mask_is_any(&nat->range.addr.ipv6.min)) {
5139             return OFPERR_OFPBAC_BAD_ARGUMENT;
5140         }
5141
5142         nat->range_af = AF_INET6;
5143
5144         if (range_present & NX_NAT_RANGE_IPV6_MAX) {
5145             if (!NX_NAT_GET_OPT(&nat->range.addr.ipv6.max, opts, len,
5146                                 struct in6_addr)) {
5147                 return OFPERR_OFPBAC_BAD_ARGUMENT;
5148             }
5149             if (memcmp(&nat->range.addr.ipv6.max, &nat->range.addr.ipv6.min,
5150                        sizeof(struct in6_addr)) < 0) {
5151                 return OFPERR_OFPBAC_BAD_ARGUMENT;
5152             }
5153         }
5154     } else if (range_present & NX_NAT_RANGE_IPV6_MAX) {
5155         return OFPERR_OFPBAC_BAD_ARGUMENT;
5156     }
5157
5158     if (range_present & NX_NAT_RANGE_PROTO_MIN) {
5159         ovs_be16 proto;
5160
5161         if (nat->range_af == AF_UNSPEC) {
5162             return OFPERR_OFPBAC_BAD_ARGUMENT;
5163         }
5164         if (!NX_NAT_GET_OPT(&proto, opts, len, ovs_be16) || proto == 0) {
5165             return OFPERR_OFPBAC_BAD_ARGUMENT;
5166         }
5167         nat->range.proto.min = ntohs(proto);
5168         if (range_present & NX_NAT_RANGE_PROTO_MAX) {
5169             if (!NX_NAT_GET_OPT(&proto, opts, len, ovs_be16)) {
5170                 return OFPERR_OFPBAC_BAD_ARGUMENT;
5171             }
5172             nat->range.proto.max = ntohs(proto);
5173             if (nat->range.proto.max < nat->range.proto.min) {
5174                 return OFPERR_OFPBAC_BAD_ARGUMENT;
5175             }
5176         }
5177     } else if (range_present & NX_NAT_RANGE_PROTO_MAX) {
5178         return OFPERR_OFPBAC_BAD_ARGUMENT;
5179     }
5180
5181     return 0;
5182 }
5183
5184 static void
5185 format_NAT(const struct ofpact_nat *a, struct ds *ds)
5186 {
5187     ds_put_cstr(ds, "nat");
5188
5189     if (a->flags & (NX_NAT_F_SRC | NX_NAT_F_DST)) {
5190         ds_put_char(ds, '(');
5191         ds_put_cstr(ds, a->flags & NX_NAT_F_SRC ? "src" : "dst");
5192
5193         if (a->range_af != AF_UNSPEC) {
5194             ds_put_cstr(ds, "=");
5195
5196             if (a->range_af == AF_INET) {
5197                 ds_put_format(ds, IP_FMT, IP_ARGS(a->range.addr.ipv4.min));
5198
5199                 if (a->range.addr.ipv4.max
5200                     && a->range.addr.ipv4.max != a->range.addr.ipv4.min) {
5201                     ds_put_format(ds, "-"IP_FMT,
5202                                   IP_ARGS(a->range.addr.ipv4.max));
5203                 }
5204             } else if (a->range_af == AF_INET6) {
5205                 ipv6_format_addr_bracket(&a->range.addr.ipv6.min, ds,
5206                                         a->range.proto.min);
5207
5208                 if (!ipv6_mask_is_any(&a->range.addr.ipv6.max)
5209                     && memcmp(&a->range.addr.ipv6.max, &a->range.addr.ipv6.min,
5210                               sizeof(struct in6_addr)) != 0) {
5211                     ds_put_char(ds, '-');
5212                     ipv6_format_addr_bracket(&a->range.addr.ipv6.max, ds,
5213                                             a->range.proto.min);
5214                 }
5215             }
5216             if (a->range.proto.min) {
5217                 ds_put_char(ds, ':');
5218                 ds_put_format(ds, "%"PRIu16, a->range.proto.min);
5219
5220                 if (a->range.proto.max
5221                     && a->range.proto.max != a->range.proto.min) {
5222                     ds_put_format(ds, "-%"PRIu16, a->range.proto.max);
5223                 }
5224             }
5225             ds_put_char(ds, ',');
5226
5227             if (a->flags & NX_NAT_F_PERSISTENT) {
5228                 ds_put_cstr(ds, "persistent,");
5229             }
5230             if (a->flags & NX_NAT_F_PROTO_HASH) {
5231                 ds_put_cstr(ds, "hash,");
5232             }
5233             if (a->flags & NX_NAT_F_PROTO_RANDOM) {
5234                 ds_put_cstr(ds, "random,");
5235             }
5236         }
5237         ds_chomp(ds, ',');
5238         ds_put_char(ds, ')');
5239     }
5240 }
5241
5242 static char * OVS_WARN_UNUSED_RESULT
5243 str_to_nat_range(const char *s, struct ofpact_nat *on)
5244 {
5245     char ipv6_s[IPV6_SCAN_LEN + 1];
5246     int n = 0;
5247
5248     on->range_af = AF_UNSPEC;
5249     if (ovs_scan_len(s, &n, IP_SCAN_FMT,
5250                      IP_SCAN_ARGS(&on->range.addr.ipv4.min))) {
5251         on->range_af = AF_INET;
5252
5253         if (s[n] == '-') {
5254             n++;
5255             if (!ovs_scan_len(s, &n, IP_SCAN_FMT,
5256                               IP_SCAN_ARGS(&on->range.addr.ipv4.max))
5257                 || (ntohl(on->range.addr.ipv4.max)
5258                     < ntohl(on->range.addr.ipv4.min))) {
5259                 goto error;
5260             }
5261         }
5262     } else if ((ovs_scan_len(s, &n, IPV6_SCAN_FMT, ipv6_s)
5263                 || ovs_scan_len(s, &n, "["IPV6_SCAN_FMT"]", ipv6_s))
5264                && inet_pton(AF_INET6, ipv6_s, &on->range.addr.ipv6.min) == 1) {
5265         on->range_af = AF_INET6;
5266
5267         if (s[n] == '-') {
5268             n++;
5269             if (!(ovs_scan_len(s, &n, IPV6_SCAN_FMT, ipv6_s)
5270                   || ovs_scan_len(s, &n, "["IPV6_SCAN_FMT"]", ipv6_s))
5271                 || inet_pton(AF_INET6, ipv6_s, &on->range.addr.ipv6.max) != 1
5272                 || memcmp(&on->range.addr.ipv6.max, &on->range.addr.ipv6.min,
5273                           sizeof on->range.addr.ipv6.max) < 0) {
5274                 goto error;
5275             }
5276         }
5277     }
5278     if (on->range_af != AF_UNSPEC && s[n] == ':') {
5279         n++;
5280         if (!ovs_scan_len(s, &n, "%"SCNu16, &on->range.proto.min)) {
5281             goto error;
5282         }
5283         if (s[n] == '-') {
5284             n++;
5285             if (!ovs_scan_len(s, &n, "%"SCNu16, &on->range.proto.max)
5286                 || on->range.proto.max < on->range.proto.min) {
5287                 goto error;
5288             }
5289         }
5290     }
5291     if (strlen(s) != n) {
5292         return xasprintf("garbage (%s) after nat range \"%s\" (pos: %d)",
5293                          &s[n], s, n);
5294     }
5295     return NULL;
5296 error:
5297     return xasprintf("invalid nat range \"%s\"", s);
5298 }
5299
5300
5301 /* Parses 'arg' as the argument to a "nat" action, and appends such an
5302  * action to 'ofpacts'.
5303  *
5304  * Returns NULL if successful, otherwise a malloc()'d string describing the
5305  * error.  The caller is responsible for freeing the returned string. */
5306 static char * OVS_WARN_UNUSED_RESULT
5307 parse_NAT(char *arg, struct ofpbuf *ofpacts,
5308           enum ofputil_protocol *usable_protocols OVS_UNUSED)
5309 {
5310     struct ofpact_nat *on = ofpact_put_NAT(ofpacts);
5311     char *key, *value;
5312
5313     on->flags = 0;
5314     on->range_af = AF_UNSPEC;
5315
5316     while (ofputil_parse_key_value(&arg, &key, &value)) {
5317         char *error = NULL;
5318
5319         if (!strcmp(key, "src")) {
5320             on->flags |= NX_NAT_F_SRC;
5321             error = str_to_nat_range(value, on);
5322         } else if (!strcmp(key, "dst")) {
5323             on->flags |= NX_NAT_F_DST;
5324             error = str_to_nat_range(value, on);
5325         } else if (!strcmp(key, "persistent")) {
5326             on->flags |= NX_NAT_F_PERSISTENT;
5327         } else if (!strcmp(key, "hash")) {
5328             on->flags |= NX_NAT_F_PROTO_HASH;
5329         } else if (!strcmp(key, "random")) {
5330             on->flags |= NX_NAT_F_PROTO_RANDOM;
5331         } else {
5332             error = xasprintf("invalid key \"%s\" in \"nat\" argument",
5333                               key);
5334         }
5335         if (error) {
5336             return error;
5337         }
5338     }
5339     if (on->flags & NX_NAT_F_SRC && on->flags & NX_NAT_F_DST) {
5340         return xasprintf("May only specify one of \"snat\" or \"dnat\".");
5341     }
5342     if (!(on->flags & NX_NAT_F_SRC || on->flags & NX_NAT_F_DST)) {
5343         if (on->flags) {
5344             return xasprintf("Flags allowed only with \"snat\" or \"dnat\".");
5345         }
5346         if (on->range_af != AF_UNSPEC) {
5347             return xasprintf("Range allowed only with \"snat\" or \"dnat\".");
5348         }
5349     }
5350     return NULL;
5351 }
5352
5353 \f
5354 /* Meter instruction. */
5355
5356 static void
5357 encode_METER(const struct ofpact_meter *meter,
5358              enum ofp_version ofp_version, struct ofpbuf *out)
5359 {
5360     if (ofp_version >= OFP13_VERSION) {
5361         instruction_put_OFPIT13_METER(out)->meter_id = htonl(meter->meter_id);
5362     }
5363 }
5364
5365 static char * OVS_WARN_UNUSED_RESULT
5366 parse_METER(char *arg, struct ofpbuf *ofpacts,
5367             enum ofputil_protocol *usable_protocols)
5368 {
5369     *usable_protocols &= OFPUTIL_P_OF13_UP;
5370     return str_to_u32(arg, &ofpact_put_METER(ofpacts)->meter_id);
5371 }
5372
5373 static void
5374 format_METER(const struct ofpact_meter *a, struct ds *s)
5375 {
5376     ds_put_format(s, "meter:%"PRIu32, a->meter_id);
5377 }
5378 \f
5379 /* Clear-Actions instruction. */
5380
5381 static void
5382 encode_CLEAR_ACTIONS(const struct ofpact_null *null OVS_UNUSED,
5383                      enum ofp_version ofp_version OVS_UNUSED,
5384                      struct ofpbuf *out OVS_UNUSED)
5385 {
5386     if (ofp_version > OFP10_VERSION) {
5387         instruction_put_OFPIT11_CLEAR_ACTIONS(out);
5388     }
5389 }
5390
5391 static char * OVS_WARN_UNUSED_RESULT
5392 parse_CLEAR_ACTIONS(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
5393                     enum ofputil_protocol *usable_protocols OVS_UNUSED)
5394 {
5395     ofpact_put_CLEAR_ACTIONS(ofpacts);
5396     return NULL;
5397 }
5398
5399 static void
5400 format_CLEAR_ACTIONS(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
5401 {
5402     ds_put_cstr(s, "clear_actions");
5403 }
5404 \f
5405 /* Write-Actions instruction. */
5406
5407 static void
5408 encode_WRITE_ACTIONS(const struct ofpact_nest *actions,
5409                      enum ofp_version ofp_version, struct ofpbuf *out)
5410 {
5411     if (ofp_version > OFP10_VERSION) {
5412         const size_t ofs = out->size;
5413
5414         instruction_put_OFPIT11_WRITE_ACTIONS(out);
5415         ofpacts_put_openflow_actions(actions->actions,
5416                                      ofpact_nest_get_action_len(actions),
5417                                      out, ofp_version);
5418         ofpacts_update_instruction_actions(out, ofs);
5419     }
5420 }
5421
5422 static char * OVS_WARN_UNUSED_RESULT
5423 parse_WRITE_ACTIONS(char *arg, struct ofpbuf *ofpacts,
5424                     enum ofputil_protocol *usable_protocols)
5425 {
5426     size_t ofs = ofpacts_pull(ofpacts);
5427     struct ofpact_nest *on;
5428     char *error;
5429
5430     /* Add a Write-Actions instruction and then pull it off. */
5431     ofpact_put(ofpacts, OFPACT_WRITE_ACTIONS, sizeof *on);
5432     ofpbuf_pull(ofpacts, sizeof *on);
5433
5434     /* Parse nested actions.
5435      *
5436      * We pulled off "write-actions" and the previous actions because the
5437      * OFPACT_WRITE_ACTIONS is only partially constructed: its length is such
5438      * that it doesn't actually include the nested actions.  That means that
5439      * ofpacts_parse() would reject them as being part of an Apply-Actions that
5440      * follows a Write-Actions, which is an invalid order.  */
5441     error = ofpacts_parse(arg, ofpacts, usable_protocols, false,
5442                           OFPACT_WRITE_ACTIONS);
5443
5444     /* Put the Write-Actions back on and update its length. */
5445     on = ofpbuf_push_uninit(ofpacts, sizeof *on);
5446     on->ofpact.len = ofpacts->size;
5447
5448     /* Put any previous actions or instructions back on. */
5449     ofpbuf_push_uninit(ofpacts, ofs);
5450
5451     return error;
5452 }
5453
5454 static void
5455 format_WRITE_ACTIONS(const struct ofpact_nest *a, struct ds *s)
5456 {
5457     ds_put_cstr(s, "write_actions(");
5458     ofpacts_format(a->actions, ofpact_nest_get_action_len(a), s);
5459     ds_put_char(s, ')');
5460 }
5461 \f
5462 /* Action structure for NXAST_WRITE_METADATA.
5463  *
5464  * Modifies the 'mask' bits of the metadata value. */
5465 struct nx_action_write_metadata {
5466     ovs_be16 type;                  /* OFPAT_VENDOR. */
5467     ovs_be16 len;                   /* Length is 32. */
5468     ovs_be32 vendor;                /* NX_VENDOR_ID. */
5469     ovs_be16 subtype;               /* NXAST_WRITE_METADATA. */
5470     uint8_t zeros[6];               /* Must be zero. */
5471     ovs_be64 metadata;              /* Metadata register. */
5472     ovs_be64 mask;                  /* Metadata mask. */
5473 };
5474 OFP_ASSERT(sizeof(struct nx_action_write_metadata) == 32);
5475
5476 static enum ofperr
5477 decode_NXAST_RAW_WRITE_METADATA(const struct nx_action_write_metadata *nawm,
5478                                 enum ofp_version ofp_version OVS_UNUSED,
5479                                 struct ofpbuf *out)
5480 {
5481     struct ofpact_metadata *om;
5482
5483     if (!is_all_zeros(nawm->zeros, sizeof nawm->zeros)) {
5484         return OFPERR_NXBRC_MUST_BE_ZERO;
5485     }
5486
5487     om = ofpact_put_WRITE_METADATA(out);
5488     om->metadata = nawm->metadata;
5489     om->mask = nawm->mask;
5490
5491     return 0;
5492 }
5493
5494 static void
5495 encode_WRITE_METADATA(const struct ofpact_metadata *metadata,
5496                       enum ofp_version ofp_version, struct ofpbuf *out)
5497 {
5498     if (ofp_version == OFP10_VERSION) {
5499         struct nx_action_write_metadata *nawm;
5500
5501         nawm = put_NXAST_WRITE_METADATA(out);
5502         nawm->metadata = metadata->metadata;
5503         nawm->mask = metadata->mask;
5504     } else {
5505         struct ofp11_instruction_write_metadata *oiwm;
5506
5507         oiwm = instruction_put_OFPIT11_WRITE_METADATA(out);
5508         oiwm->metadata = metadata->metadata;
5509         oiwm->metadata_mask = metadata->mask;
5510     }
5511 }
5512
5513 static char * OVS_WARN_UNUSED_RESULT
5514 parse_WRITE_METADATA(char *arg, struct ofpbuf *ofpacts,
5515                      enum ofputil_protocol *usable_protocols)
5516 {
5517     struct ofpact_metadata *om;
5518     char *mask = strchr(arg, '/');
5519
5520     *usable_protocols &= OFPUTIL_P_NXM_OF11_UP;
5521
5522     om = ofpact_put_WRITE_METADATA(ofpacts);
5523     if (mask) {
5524         char *error;
5525
5526         *mask = '\0';
5527         error = str_to_be64(mask + 1, &om->mask);
5528         if (error) {
5529             return error;
5530         }
5531     } else {
5532         om->mask = OVS_BE64_MAX;
5533     }
5534
5535     return str_to_be64(arg, &om->metadata);
5536 }
5537
5538 static void
5539 format_WRITE_METADATA(const struct ofpact_metadata *a, struct ds *s)
5540 {
5541     ds_put_format(s, "write_metadata:%#"PRIx64, ntohll(a->metadata));
5542     if (a->mask != OVS_BE64_MAX) {
5543         ds_put_format(s, "/%#"PRIx64, ntohll(a->mask));
5544     }
5545 }
5546 \f
5547 /* Goto-Table instruction. */
5548
5549 static void
5550 encode_GOTO_TABLE(const struct ofpact_goto_table *goto_table,
5551                   enum ofp_version ofp_version, struct ofpbuf *out)
5552 {
5553     if (ofp_version == OFP10_VERSION) {
5554         struct nx_action_resubmit *nar;
5555
5556         nar = put_NXAST_RESUBMIT_TABLE(out);
5557         nar->table = goto_table->table_id;
5558         nar->in_port = htons(ofp_to_u16(OFPP_IN_PORT));
5559     } else {
5560         struct ofp11_instruction_goto_table *oigt;
5561
5562         oigt = instruction_put_OFPIT11_GOTO_TABLE(out);
5563         oigt->table_id = goto_table->table_id;
5564         memset(oigt->pad, 0, sizeof oigt->pad);
5565     }
5566 }
5567
5568 static char * OVS_WARN_UNUSED_RESULT
5569 parse_GOTO_TABLE(char *arg, struct ofpbuf *ofpacts,
5570                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
5571 {
5572     struct ofpact_goto_table *ogt = ofpact_put_GOTO_TABLE(ofpacts);
5573     char *table_s = strsep(&arg, ",");
5574     if (!table_s || !table_s[0]) {
5575         return xstrdup("instruction goto-table needs table id");
5576     }
5577     return str_to_u8(table_s, "table", &ogt->table_id);
5578 }
5579
5580 static void
5581 format_GOTO_TABLE(const struct ofpact_goto_table *a, struct ds *s)
5582 {
5583     ds_put_format(s, "goto_table:%"PRIu8, a->table_id);
5584 }
5585 \f
5586 static void
5587 log_bad_action(const struct ofp_action_header *actions, size_t actions_len,
5588                const struct ofp_action_header *bad_action, enum ofperr error)
5589 {
5590     if (!VLOG_DROP_WARN(&rl)) {
5591         struct ds s;
5592
5593         ds_init(&s);
5594         ds_put_hex_dump(&s, actions, actions_len, 0, false);
5595         VLOG_WARN("bad action at offset %#"PRIxPTR" (%s):\n%s",
5596                   (char *)bad_action - (char *)actions,
5597                   ofperr_get_name(error), ds_cstr(&s));
5598         ds_destroy(&s);
5599     }
5600 }
5601
5602 static enum ofperr
5603 ofpacts_decode(const void *actions, size_t actions_len,
5604                enum ofp_version ofp_version, struct ofpbuf *ofpacts)
5605 {
5606     struct ofpbuf openflow;
5607
5608     ofpbuf_use_const(&openflow, actions, actions_len);
5609     while (openflow.size) {
5610         const struct ofp_action_header *action = openflow.data;
5611         enum ofp_raw_action_type raw;
5612         enum ofperr error;
5613         uint64_t arg;
5614
5615         error = ofpact_pull_raw(&openflow, ofp_version, &raw, &arg);
5616         if (!error) {
5617             error = ofpact_decode(action, raw, ofp_version, arg, ofpacts);
5618         }
5619
5620         if (error) {
5621             log_bad_action(actions, actions_len, action, error);
5622             return error;
5623         }
5624     }
5625
5626     ofpact_pad(ofpacts);
5627     return 0;
5628 }
5629
5630 static enum ofperr
5631 ofpacts_pull_openflow_actions__(struct ofpbuf *openflow,
5632                                 unsigned int actions_len,
5633                                 enum ofp_version version,
5634                                 uint32_t allowed_ovsinsts,
5635                                 struct ofpbuf *ofpacts,
5636                                 enum ofpact_type outer_action)
5637 {
5638     const struct ofp_action_header *actions;
5639     enum ofperr error;
5640
5641     if (!outer_action) {
5642         ofpbuf_clear(ofpacts);
5643     }
5644
5645     if (actions_len % OFP_ACTION_ALIGN != 0) {
5646         VLOG_WARN_RL(&rl, "OpenFlow message actions length %u is not a "
5647                      "multiple of %d", actions_len, OFP_ACTION_ALIGN);
5648         return OFPERR_OFPBRC_BAD_LEN;
5649     }
5650
5651     actions = ofpbuf_try_pull(openflow, actions_len);
5652     if (actions == NULL) {
5653         VLOG_WARN_RL(&rl, "OpenFlow message actions length %u exceeds "
5654                      "remaining message length (%"PRIu32")",
5655                      actions_len, openflow->size);
5656         return OFPERR_OFPBRC_BAD_LEN;
5657     }
5658
5659     error = ofpacts_decode(actions, actions_len, version, ofpacts);
5660     if (error) {
5661         ofpbuf_clear(ofpacts);
5662         return error;
5663     }
5664
5665     error = ofpacts_verify(ofpacts->data, ofpacts->size, allowed_ovsinsts,
5666                            outer_action);
5667     if (error) {
5668         ofpbuf_clear(ofpacts);
5669     }
5670     return error;
5671 }
5672
5673 /* Attempts to convert 'actions_len' bytes of OpenFlow actions from the
5674  * front of 'openflow' into ofpacts.  On success, replaces any existing content
5675  * in 'ofpacts' by the converted ofpacts; on failure, clears 'ofpacts'.
5676  * Returns 0 if successful, otherwise an OpenFlow error.
5677  *
5678  * Actions are processed according to their OpenFlow version which
5679  * is provided in the 'version' parameter.
5680  *
5681  * In most places in OpenFlow, actions appear encapsulated in instructions, so
5682  * you should call ofpacts_pull_openflow_instructions() instead of this
5683  * function.
5684  *
5685  * The parsed actions are valid generically, but they may not be valid in a
5686  * specific context.  For example, port numbers up to OFPP_MAX are valid
5687  * generically, but specific datapaths may only support port numbers in a
5688  * smaller range.  Use ofpacts_check() to additional check whether actions are
5689  * valid in a specific context. */
5690 enum ofperr
5691 ofpacts_pull_openflow_actions(struct ofpbuf *openflow,
5692                               unsigned int actions_len,
5693                               enum ofp_version version,
5694                               struct ofpbuf *ofpacts)
5695 {
5696     return ofpacts_pull_openflow_actions__(openflow, actions_len, version,
5697                                            1u << OVSINST_OFPIT11_APPLY_ACTIONS,
5698                                            ofpacts, 0);
5699 }
5700 \f
5701 /* OpenFlow 1.1 actions. */
5702
5703
5704 /* True if an action sets the value of a field
5705  * in a way that is compatibile with the action set.
5706  * The field can be set via either a set or a move action.
5707  * False otherwise. */
5708 static bool
5709 ofpact_is_set_or_move_action(const struct ofpact *a)
5710 {
5711     switch (a->type) {
5712     case OFPACT_SET_FIELD:
5713     case OFPACT_REG_MOVE:
5714     case OFPACT_SET_ETH_DST:
5715     case OFPACT_SET_ETH_SRC:
5716     case OFPACT_SET_IP_DSCP:
5717     case OFPACT_SET_IP_ECN:
5718     case OFPACT_SET_IP_TTL:
5719     case OFPACT_SET_IPV4_DST:
5720     case OFPACT_SET_IPV4_SRC:
5721     case OFPACT_SET_L4_DST_PORT:
5722     case OFPACT_SET_L4_SRC_PORT:
5723     case OFPACT_SET_MPLS_LABEL:
5724     case OFPACT_SET_MPLS_TC:
5725     case OFPACT_SET_MPLS_TTL:
5726     case OFPACT_SET_QUEUE:
5727     case OFPACT_SET_TUNNEL:
5728     case OFPACT_SET_VLAN_PCP:
5729     case OFPACT_SET_VLAN_VID:
5730         return true;
5731     case OFPACT_BUNDLE:
5732     case OFPACT_CLEAR_ACTIONS:
5733     case OFPACT_CT:
5734     case OFPACT_NAT:
5735     case OFPACT_CONTROLLER:
5736     case OFPACT_DEC_MPLS_TTL:
5737     case OFPACT_DEC_TTL:
5738     case OFPACT_ENQUEUE:
5739     case OFPACT_EXIT:
5740     case OFPACT_UNROLL_XLATE:
5741     case OFPACT_FIN_TIMEOUT:
5742     case OFPACT_GOTO_TABLE:
5743     case OFPACT_GROUP:
5744     case OFPACT_LEARN:
5745     case OFPACT_CONJUNCTION:
5746     case OFPACT_METER:
5747     case OFPACT_MULTIPATH:
5748     case OFPACT_NOTE:
5749     case OFPACT_OUTPUT:
5750     case OFPACT_OUTPUT_REG:
5751     case OFPACT_POP_MPLS:
5752     case OFPACT_POP_QUEUE:
5753     case OFPACT_PUSH_MPLS:
5754     case OFPACT_PUSH_VLAN:
5755     case OFPACT_RESUBMIT:
5756     case OFPACT_SAMPLE:
5757     case OFPACT_STACK_POP:
5758     case OFPACT_STACK_PUSH:
5759     case OFPACT_STRIP_VLAN:
5760     case OFPACT_WRITE_ACTIONS:
5761     case OFPACT_WRITE_METADATA:
5762     case OFPACT_DEBUG_RECIRC:
5763         return false;
5764     default:
5765         OVS_NOT_REACHED();
5766     }
5767 }
5768
5769 /* True if an action is allowed in the action set.
5770  * False otherwise. */
5771 static bool
5772 ofpact_is_allowed_in_actions_set(const struct ofpact *a)
5773 {
5774     switch (a->type) {
5775     case OFPACT_DEC_MPLS_TTL:
5776     case OFPACT_DEC_TTL:
5777     case OFPACT_GROUP:
5778     case OFPACT_OUTPUT:
5779     case OFPACT_POP_MPLS:
5780     case OFPACT_PUSH_MPLS:
5781     case OFPACT_PUSH_VLAN:
5782     case OFPACT_REG_MOVE:
5783     case OFPACT_SET_FIELD:
5784     case OFPACT_SET_ETH_DST:
5785     case OFPACT_SET_ETH_SRC:
5786     case OFPACT_SET_IP_DSCP:
5787     case OFPACT_SET_IP_ECN:
5788     case OFPACT_SET_IP_TTL:
5789     case OFPACT_SET_IPV4_DST:
5790     case OFPACT_SET_IPV4_SRC:
5791     case OFPACT_SET_L4_DST_PORT:
5792     case OFPACT_SET_L4_SRC_PORT:
5793     case OFPACT_SET_MPLS_LABEL:
5794     case OFPACT_SET_MPLS_TC:
5795     case OFPACT_SET_MPLS_TTL:
5796     case OFPACT_SET_QUEUE:
5797     case OFPACT_SET_TUNNEL:
5798     case OFPACT_SET_VLAN_PCP:
5799     case OFPACT_SET_VLAN_VID:
5800     case OFPACT_STRIP_VLAN:
5801         return true;
5802
5803     /* In general these actions are excluded because they are not part of
5804      * the OpenFlow specification nor map to actions that are defined in
5805      * the specification.  Thus the order in which they should be applied
5806      * in the action set is undefined. */
5807     case OFPACT_BUNDLE:
5808     case OFPACT_CONTROLLER:
5809     case OFPACT_CT:
5810     case OFPACT_NAT:
5811     case OFPACT_ENQUEUE:
5812     case OFPACT_EXIT:
5813     case OFPACT_UNROLL_XLATE:
5814     case OFPACT_FIN_TIMEOUT:
5815     case OFPACT_LEARN:
5816     case OFPACT_CONJUNCTION:
5817     case OFPACT_MULTIPATH:
5818     case OFPACT_NOTE:
5819     case OFPACT_OUTPUT_REG:
5820     case OFPACT_POP_QUEUE:
5821     case OFPACT_RESUBMIT:
5822     case OFPACT_SAMPLE:
5823     case OFPACT_STACK_POP:
5824     case OFPACT_STACK_PUSH:
5825     case OFPACT_DEBUG_RECIRC:
5826
5827     /* The action set may only include actions and thus
5828      * may not include any instructions */
5829     case OFPACT_CLEAR_ACTIONS:
5830     case OFPACT_GOTO_TABLE:
5831     case OFPACT_METER:
5832     case OFPACT_WRITE_ACTIONS:
5833     case OFPACT_WRITE_METADATA:
5834         return false;
5835     default:
5836         OVS_NOT_REACHED();
5837     }
5838 }
5839
5840 /* Append ofpact 'a' onto the tail of 'out' */
5841 static void
5842 ofpact_copy(struct ofpbuf *out, const struct ofpact *a)
5843 {
5844     ofpbuf_put(out, a, OFPACT_ALIGN(a->len));
5845 }
5846
5847 /* Copies the last ofpact whose type is 'filter' from 'in' to 'out'. */
5848 static bool
5849 ofpacts_copy_last(struct ofpbuf *out, const struct ofpbuf *in,
5850                   enum ofpact_type filter)
5851 {
5852     const struct ofpact *target;
5853     const struct ofpact *a;
5854
5855     target = NULL;
5856     OFPACT_FOR_EACH (a, in->data, in->size) {
5857         if (a->type == filter) {
5858             target = a;
5859         }
5860     }
5861     if (target) {
5862         ofpact_copy(out, target);
5863     }
5864     return target != NULL;
5865 }
5866
5867 /* Append all ofpacts, for which 'filter' returns true, from 'in' to 'out'.
5868  * The order of appended ofpacts is preserved between 'in' and 'out' */
5869 static void
5870 ofpacts_copy_all(struct ofpbuf *out, const struct ofpbuf *in,
5871                  bool (*filter)(const struct ofpact *))
5872 {
5873     const struct ofpact *a;
5874
5875     OFPACT_FOR_EACH (a, in->data, in->size) {
5876         if (filter(a)) {
5877             ofpact_copy(out, a);
5878         }
5879     }
5880 }
5881
5882 /* Reads 'action_set', which contains ofpacts accumulated by
5883  * OFPACT_WRITE_ACTIONS instructions, and writes equivalent actions to be
5884  * executed directly into 'action_list'.  (These names correspond to the
5885  * "Action Set" and "Action List" terms used in OpenFlow 1.1+.)
5886  *
5887  * In general this involves appending the last instance of each action that is
5888  * admissible in the action set in the order described in the OpenFlow
5889  * specification.
5890  *
5891  * Exceptions:
5892  * + output action is only appended if no group action was present in 'in'.
5893  * + As a simplification all set actions are copied in the order the are
5894  *   provided in 'in' as many set actions applied to a field has the same
5895  *   affect as only applying the last action that sets a field and
5896  *   duplicates are removed by do_xlate_actions().
5897  *   This has an unwanted side-effect of compsoting multiple
5898  *   LOAD_REG actions that touch different regions of the same field. */
5899 void
5900 ofpacts_execute_action_set(struct ofpbuf *action_list,
5901                            const struct ofpbuf *action_set)
5902 {
5903     /* The OpenFlow spec "Action Set" section specifies this order. */
5904     ofpacts_copy_last(action_list, action_set, OFPACT_STRIP_VLAN);
5905     ofpacts_copy_last(action_list, action_set, OFPACT_POP_MPLS);
5906     ofpacts_copy_last(action_list, action_set, OFPACT_PUSH_MPLS);
5907     ofpacts_copy_last(action_list, action_set, OFPACT_PUSH_VLAN);
5908     ofpacts_copy_last(action_list, action_set, OFPACT_DEC_TTL);
5909     ofpacts_copy_last(action_list, action_set, OFPACT_DEC_MPLS_TTL);
5910     ofpacts_copy_all(action_list, action_set, ofpact_is_set_or_move_action);
5911     ofpacts_copy_last(action_list, action_set, OFPACT_SET_QUEUE);
5912
5913     /* If both OFPACT_GROUP and OFPACT_OUTPUT are present, OpenFlow says that
5914      * we should execute only OFPACT_GROUP.
5915      *
5916      * If neither OFPACT_GROUP nor OFPACT_OUTPUT is present, then we can drop
5917      * all the actions because there's no point in modifying a packet that will
5918      * not be sent anywhere. */
5919     if (!ofpacts_copy_last(action_list, action_set, OFPACT_GROUP) &&
5920         !ofpacts_copy_last(action_list, action_set, OFPACT_OUTPUT) &&
5921         !ofpacts_copy_last(action_list, action_set, OFPACT_RESUBMIT)) {
5922         ofpbuf_clear(action_list);
5923     }
5924 }
5925
5926
5927 static enum ofperr
5928 ofpacts_decode_for_action_set(const struct ofp_action_header *in,
5929                               size_t n_in, enum ofp_version version,
5930                               struct ofpbuf *out)
5931 {
5932     enum ofperr error;
5933     struct ofpact *a;
5934     size_t start = out->size;
5935
5936     error = ofpacts_decode(in, n_in, version, out);
5937
5938     if (error) {
5939         return error;
5940     }
5941
5942     OFPACT_FOR_EACH (a, ofpact_end(out->data, start), out->size - start) {
5943         if (!ofpact_is_allowed_in_actions_set(a)) {
5944             VLOG_WARN_RL(&rl, "disallowed action in action set");
5945             return OFPERR_OFPBAC_BAD_TYPE;
5946         }
5947     }
5948
5949     return 0;
5950 }
5951 \f
5952 /* OpenFlow 1.1 instructions. */
5953
5954 struct instruction_type_info {
5955     enum ovs_instruction_type type;
5956     const char *name;
5957 };
5958
5959 static const struct instruction_type_info inst_info[] = {
5960 #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME)    {OVSINST_##ENUM, NAME},
5961 OVS_INSTRUCTIONS
5962 #undef DEFINE_INST
5963 };
5964
5965 const char *
5966 ovs_instruction_name_from_type(enum ovs_instruction_type type)
5967 {
5968     return inst_info[type].name;
5969 }
5970
5971 int
5972 ovs_instruction_type_from_name(const char *name)
5973 {
5974     const struct instruction_type_info *p;
5975     for (p = inst_info; p < &inst_info[ARRAY_SIZE(inst_info)]; p++) {
5976         if (!strcasecmp(name, p->name)) {
5977             return p->type;
5978         }
5979     }
5980     return -1;
5981 }
5982
5983 enum ovs_instruction_type
5984 ovs_instruction_type_from_ofpact_type(enum ofpact_type type)
5985 {
5986     switch (type) {
5987     case OFPACT_METER:
5988         return OVSINST_OFPIT13_METER;
5989     case OFPACT_CLEAR_ACTIONS:
5990         return OVSINST_OFPIT11_CLEAR_ACTIONS;
5991     case OFPACT_WRITE_ACTIONS:
5992         return OVSINST_OFPIT11_WRITE_ACTIONS;
5993     case OFPACT_WRITE_METADATA:
5994         return OVSINST_OFPIT11_WRITE_METADATA;
5995     case OFPACT_GOTO_TABLE:
5996         return OVSINST_OFPIT11_GOTO_TABLE;
5997     case OFPACT_OUTPUT:
5998     case OFPACT_GROUP:
5999     case OFPACT_CONTROLLER:
6000     case OFPACT_ENQUEUE:
6001     case OFPACT_OUTPUT_REG:
6002     case OFPACT_BUNDLE:
6003     case OFPACT_SET_VLAN_VID:
6004     case OFPACT_SET_VLAN_PCP:
6005     case OFPACT_STRIP_VLAN:
6006     case OFPACT_PUSH_VLAN:
6007     case OFPACT_SET_ETH_SRC:
6008     case OFPACT_SET_ETH_DST:
6009     case OFPACT_SET_IPV4_SRC:
6010     case OFPACT_SET_IPV4_DST:
6011     case OFPACT_SET_IP_DSCP:
6012     case OFPACT_SET_IP_ECN:
6013     case OFPACT_SET_IP_TTL:
6014     case OFPACT_SET_L4_SRC_PORT:
6015     case OFPACT_SET_L4_DST_PORT:
6016     case OFPACT_REG_MOVE:
6017     case OFPACT_SET_FIELD:
6018     case OFPACT_STACK_PUSH:
6019     case OFPACT_STACK_POP:
6020     case OFPACT_DEC_TTL:
6021     case OFPACT_SET_MPLS_LABEL:
6022     case OFPACT_SET_MPLS_TC:
6023     case OFPACT_SET_MPLS_TTL:
6024     case OFPACT_DEC_MPLS_TTL:
6025     case OFPACT_PUSH_MPLS:
6026     case OFPACT_POP_MPLS:
6027     case OFPACT_SET_TUNNEL:
6028     case OFPACT_SET_QUEUE:
6029     case OFPACT_POP_QUEUE:
6030     case OFPACT_FIN_TIMEOUT:
6031     case OFPACT_RESUBMIT:
6032     case OFPACT_LEARN:
6033     case OFPACT_CONJUNCTION:
6034     case OFPACT_MULTIPATH:
6035     case OFPACT_NOTE:
6036     case OFPACT_EXIT:
6037     case OFPACT_UNROLL_XLATE:
6038     case OFPACT_SAMPLE:
6039     case OFPACT_DEBUG_RECIRC:
6040     case OFPACT_CT:
6041     case OFPACT_NAT:
6042     default:
6043         return OVSINST_OFPIT11_APPLY_ACTIONS;
6044     }
6045 }
6046
6047 enum ofperr
6048 ovs_instruction_type_from_inst_type(enum ovs_instruction_type *instruction_type,
6049                                     const uint16_t inst_type)
6050 {
6051     switch (inst_type) {
6052
6053 #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME) \
6054     case ENUM:                                      \
6055         *instruction_type = OVSINST_##ENUM;         \
6056         return 0;
6057 OVS_INSTRUCTIONS
6058 #undef DEFINE_INST
6059
6060     default:
6061         return OFPERR_OFPBIC_UNKNOWN_INST;
6062     }
6063 }
6064
6065 /* Two-way translation between OVS's internal "OVSINST_*" representation of
6066  * instructions and the "OFPIT_*" representation used in OpenFlow. */
6067 struct ovsinst_map {
6068     enum ovs_instruction_type ovsinst; /* Internal name for instruction. */
6069     int ofpit;                         /* OFPIT_* number from OpenFlow spec. */
6070 };
6071
6072 static const struct ovsinst_map *
6073 get_ovsinst_map(enum ofp_version version)
6074 {
6075     /* OpenFlow 1.1 and 1.2 instructions. */
6076     static const struct ovsinst_map of11[] = {
6077         { OVSINST_OFPIT11_GOTO_TABLE, 1 },
6078         { OVSINST_OFPIT11_WRITE_METADATA, 2 },
6079         { OVSINST_OFPIT11_WRITE_ACTIONS, 3 },
6080         { OVSINST_OFPIT11_APPLY_ACTIONS, 4 },
6081         { OVSINST_OFPIT11_CLEAR_ACTIONS, 5 },
6082         { 0, -1 },
6083     };
6084
6085     /* OpenFlow 1.3+ instructions. */
6086     static const struct ovsinst_map of13[] = {
6087         { OVSINST_OFPIT11_GOTO_TABLE, 1 },
6088         { OVSINST_OFPIT11_WRITE_METADATA, 2 },
6089         { OVSINST_OFPIT11_WRITE_ACTIONS, 3 },
6090         { OVSINST_OFPIT11_APPLY_ACTIONS, 4 },
6091         { OVSINST_OFPIT11_CLEAR_ACTIONS, 5 },
6092         { OVSINST_OFPIT13_METER, 6 },
6093         { 0, -1 },
6094     };
6095
6096     return version < OFP13_VERSION ? of11 : of13;
6097 }
6098
6099 /* Converts 'ovsinst_bitmap', a bitmap whose bits correspond to OVSINST_*
6100  * values, into a bitmap of instructions suitable for OpenFlow 'version'
6101  * (OFP11_VERSION or later), and returns the result. */
6102 ovs_be32
6103 ovsinst_bitmap_to_openflow(uint32_t ovsinst_bitmap, enum ofp_version version)
6104 {
6105     uint32_t ofpit_bitmap = 0;
6106     const struct ovsinst_map *x;
6107
6108     for (x = get_ovsinst_map(version); x->ofpit >= 0; x++) {
6109         if (ovsinst_bitmap & (1u << x->ovsinst)) {
6110             ofpit_bitmap |= 1u << x->ofpit;
6111         }
6112     }
6113     return htonl(ofpit_bitmap);
6114 }
6115
6116 /* Converts 'ofpit_bitmap', a bitmap of instructions from an OpenFlow message
6117  * with the given 'version' (OFP11_VERSION or later) into a bitmap whose bits
6118  * correspond to OVSINST_* values, and returns the result. */
6119 uint32_t
6120 ovsinst_bitmap_from_openflow(ovs_be32 ofpit_bitmap, enum ofp_version version)
6121 {
6122     uint32_t ovsinst_bitmap = 0;
6123     const struct ovsinst_map *x;
6124
6125     for (x = get_ovsinst_map(version); x->ofpit >= 0; x++) {
6126         if (ofpit_bitmap & htonl(1u << x->ofpit)) {
6127             ovsinst_bitmap |= 1u << x->ovsinst;
6128         }
6129     }
6130     return ovsinst_bitmap;
6131 }
6132
6133 static inline struct ofp11_instruction *
6134 instruction_next(const struct ofp11_instruction *inst)
6135 {
6136     return ((struct ofp11_instruction *) (void *)
6137             ((uint8_t *) inst + ntohs(inst->len)));
6138 }
6139
6140 static inline bool
6141 instruction_is_valid(const struct ofp11_instruction *inst,
6142                      size_t n_instructions)
6143 {
6144     uint16_t len = ntohs(inst->len);
6145     return (!(len % OFP11_INSTRUCTION_ALIGN)
6146             && len >= sizeof *inst
6147             && len / sizeof *inst <= n_instructions);
6148 }
6149
6150 /* This macro is careful to check for instructions with bad lengths. */
6151 #define INSTRUCTION_FOR_EACH(ITER, LEFT, INSTRUCTIONS, N_INSTRUCTIONS)  \
6152     for ((ITER) = (INSTRUCTIONS), (LEFT) = (N_INSTRUCTIONS);            \
6153          (LEFT) > 0 && instruction_is_valid(ITER, LEFT);                \
6154          ((LEFT) -= (ntohs((ITER)->len)                                 \
6155                      / sizeof(struct ofp11_instruction)),               \
6156           (ITER) = instruction_next(ITER)))
6157
6158 static enum ofperr
6159 decode_openflow11_instruction(const struct ofp11_instruction *inst,
6160                               enum ovs_instruction_type *type)
6161 {
6162     uint16_t len = ntohs(inst->len);
6163
6164     switch (inst->type) {
6165     case CONSTANT_HTONS(OFPIT11_EXPERIMENTER):
6166         return OFPERR_OFPBIC_BAD_EXPERIMENTER;
6167
6168 #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME)     \
6169         case CONSTANT_HTONS(ENUM):                      \
6170             if (EXTENSIBLE                              \
6171                 ? len >= sizeof(struct STRUCT)          \
6172                 : len == sizeof(struct STRUCT)) {       \
6173                 *type = OVSINST_##ENUM;                 \
6174                 return 0;                               \
6175             } else {                                    \
6176                 return OFPERR_OFPBIC_BAD_LEN;           \
6177             }
6178 OVS_INSTRUCTIONS
6179 #undef DEFINE_INST
6180
6181     default:
6182         return OFPERR_OFPBIC_UNKNOWN_INST;
6183     }
6184 }
6185
6186 static enum ofperr
6187 decode_openflow11_instructions(const struct ofp11_instruction insts[],
6188                                size_t n_insts,
6189                                const struct ofp11_instruction *out[])
6190 {
6191     const struct ofp11_instruction *inst;
6192     size_t left;
6193
6194     memset(out, 0, N_OVS_INSTRUCTIONS * sizeof *out);
6195     INSTRUCTION_FOR_EACH (inst, left, insts, n_insts) {
6196         enum ovs_instruction_type type;
6197         enum ofperr error;
6198
6199         error = decode_openflow11_instruction(inst, &type);
6200         if (error) {
6201             return error;
6202         }
6203
6204         if (out[type]) {
6205             return OFPERR_OFPBIC_DUP_INST;
6206         }
6207         out[type] = inst;
6208     }
6209
6210     if (left) {
6211         VLOG_WARN_RL(&rl, "bad instruction format at offset %"PRIuSIZE,
6212                      (n_insts - left) * sizeof *inst);
6213         return OFPERR_OFPBIC_BAD_LEN;
6214     }
6215     return 0;
6216 }
6217
6218 static void
6219 get_actions_from_instruction(const struct ofp11_instruction *inst,
6220                              const struct ofp_action_header **actions,
6221                              size_t *actions_len)
6222 {
6223     *actions = ALIGNED_CAST(const struct ofp_action_header *, inst + 1);
6224     *actions_len = ntohs(inst->len) - sizeof *inst;
6225 }
6226
6227 enum ofperr
6228 ofpacts_pull_openflow_instructions(struct ofpbuf *openflow,
6229                                    unsigned int instructions_len,
6230                                    enum ofp_version version,
6231                                    struct ofpbuf *ofpacts)
6232 {
6233     const struct ofp11_instruction *instructions;
6234     const struct ofp11_instruction *insts[N_OVS_INSTRUCTIONS];
6235     enum ofperr error;
6236
6237     if (version == OFP10_VERSION) {
6238         return ofpacts_pull_openflow_actions__(openflow, instructions_len,
6239                                                version,
6240                                                (1u << N_OVS_INSTRUCTIONS) - 1,
6241                                                ofpacts, 0);
6242     }
6243
6244     ofpbuf_clear(ofpacts);
6245
6246     if (instructions_len % OFP11_INSTRUCTION_ALIGN != 0) {
6247         VLOG_WARN_RL(&rl, "OpenFlow message instructions length %u is not a "
6248                      "multiple of %d",
6249                      instructions_len, OFP11_INSTRUCTION_ALIGN);
6250         error = OFPERR_OFPBIC_BAD_LEN;
6251         goto exit;
6252     }
6253
6254     instructions = ofpbuf_try_pull(openflow, instructions_len);
6255     if (instructions == NULL) {
6256         VLOG_WARN_RL(&rl, "OpenFlow message instructions length %u exceeds "
6257                      "remaining message length (%"PRIu32")",
6258                      instructions_len, openflow->size);
6259         error = OFPERR_OFPBIC_BAD_LEN;
6260         goto exit;
6261     }
6262
6263     error = decode_openflow11_instructions(
6264         instructions, instructions_len / OFP11_INSTRUCTION_ALIGN,
6265         insts);
6266     if (error) {
6267         goto exit;
6268     }
6269
6270     if (insts[OVSINST_OFPIT13_METER]) {
6271         const struct ofp13_instruction_meter *oim;
6272         struct ofpact_meter *om;
6273
6274         oim = ALIGNED_CAST(const struct ofp13_instruction_meter *,
6275                            insts[OVSINST_OFPIT13_METER]);
6276
6277         om = ofpact_put_METER(ofpacts);
6278         om->meter_id = ntohl(oim->meter_id);
6279     }
6280     if (insts[OVSINST_OFPIT11_APPLY_ACTIONS]) {
6281         const struct ofp_action_header *actions;
6282         size_t actions_len;
6283
6284         get_actions_from_instruction(insts[OVSINST_OFPIT11_APPLY_ACTIONS],
6285                                      &actions, &actions_len);
6286         error = ofpacts_decode(actions, actions_len, version, ofpacts);
6287         if (error) {
6288             goto exit;
6289         }
6290     }
6291     if (insts[OVSINST_OFPIT11_CLEAR_ACTIONS]) {
6292         instruction_get_OFPIT11_CLEAR_ACTIONS(
6293             insts[OVSINST_OFPIT11_CLEAR_ACTIONS]);
6294         ofpact_put_CLEAR_ACTIONS(ofpacts);
6295     }
6296     if (insts[OVSINST_OFPIT11_WRITE_ACTIONS]) {
6297         struct ofpact_nest *on;
6298         const struct ofp_action_header *actions;
6299         size_t actions_len;
6300         size_t start;
6301
6302         ofpact_pad(ofpacts);
6303         start = ofpacts->size;
6304         ofpact_put(ofpacts, OFPACT_WRITE_ACTIONS,
6305                    offsetof(struct ofpact_nest, actions));
6306         get_actions_from_instruction(insts[OVSINST_OFPIT11_WRITE_ACTIONS],
6307                                      &actions, &actions_len);
6308         error = ofpacts_decode_for_action_set(actions, actions_len,
6309                                               version, ofpacts);
6310         if (error) {
6311             goto exit;
6312         }
6313         on = ofpbuf_at_assert(ofpacts, start, sizeof *on);
6314         on->ofpact.len = ofpacts->size - start;
6315     }
6316     if (insts[OVSINST_OFPIT11_WRITE_METADATA]) {
6317         const struct ofp11_instruction_write_metadata *oiwm;
6318         struct ofpact_metadata *om;
6319
6320         oiwm = ALIGNED_CAST(const struct ofp11_instruction_write_metadata *,
6321                             insts[OVSINST_OFPIT11_WRITE_METADATA]);
6322
6323         om = ofpact_put_WRITE_METADATA(ofpacts);
6324         om->metadata = oiwm->metadata;
6325         om->mask = oiwm->metadata_mask;
6326     }
6327     if (insts[OVSINST_OFPIT11_GOTO_TABLE]) {
6328         const struct ofp11_instruction_goto_table *oigt;
6329         struct ofpact_goto_table *ogt;
6330
6331         oigt = instruction_get_OFPIT11_GOTO_TABLE(
6332             insts[OVSINST_OFPIT11_GOTO_TABLE]);
6333         ogt = ofpact_put_GOTO_TABLE(ofpacts);
6334         ogt->table_id = oigt->table_id;
6335     }
6336
6337     error = ofpacts_verify(ofpacts->data, ofpacts->size,
6338                            (1u << N_OVS_INSTRUCTIONS) - 1, 0);
6339 exit:
6340     if (error) {
6341         ofpbuf_clear(ofpacts);
6342     }
6343     return error;
6344 }
6345
6346 /* Update the length of the instruction that begins at offset 'ofs' within
6347  * 'openflow' and contains nested actions that extend to the end of 'openflow'.
6348  * If the instruction contains no nested actions, deletes it entirely. */
6349 static void
6350 ofpacts_update_instruction_actions(struct ofpbuf *openflow, size_t ofs)
6351 {
6352     struct ofp11_instruction_actions *oia;
6353
6354     oia = ofpbuf_at_assert(openflow, ofs, sizeof *oia);
6355     if (openflow->size > ofs + sizeof *oia) {
6356         oia->len = htons(openflow->size - ofs);
6357     } else {
6358         openflow->size = ofs;
6359     }
6360 }
6361 \f
6362 /* Checks that 'port' is a valid output port for OFPACT_OUTPUT, given that the
6363  * switch will never have more than 'max_ports' ports.  Returns 0 if 'port' is
6364  * valid, otherwise an OpenFlow error code. */
6365 enum ofperr
6366 ofpact_check_output_port(ofp_port_t port, ofp_port_t max_ports)
6367 {
6368     switch (port) {
6369     case OFPP_IN_PORT:
6370     case OFPP_TABLE:
6371     case OFPP_NORMAL:
6372     case OFPP_FLOOD:
6373     case OFPP_ALL:
6374     case OFPP_CONTROLLER:
6375     case OFPP_LOCAL:
6376         return 0;
6377
6378     case OFPP_NONE:
6379         return OFPERR_OFPBAC_BAD_OUT_PORT;
6380
6381     default:
6382         if (ofp_to_u16(port) < ofp_to_u16(max_ports)) {
6383             return 0;
6384         }
6385         return OFPERR_OFPBAC_BAD_OUT_PORT;
6386     }
6387 }
6388
6389 /* Removes the protocols that require consistency between match and actions
6390  * (that's everything but OpenFlow 1.0) from '*usable_protocols'.
6391  *
6392  * (An example of an inconsistency between match and actions is a flow that
6393  * does not match on an MPLS Ethertype but has an action that pops an MPLS
6394  * label.) */
6395 static void
6396 inconsistent_match(enum ofputil_protocol *usable_protocols)
6397 {
6398     *usable_protocols &= OFPUTIL_P_OF10_ANY;
6399 }
6400
6401 /* May modify flow->dl_type, flow->nw_proto and flow->vlan_tci,
6402  * caller must restore them.
6403  *
6404  * Modifies some actions, filling in fields that could not be properly set
6405  * without context. */
6406 static enum ofperr
6407 ofpact_check__(enum ofputil_protocol *usable_protocols, struct ofpact *a,
6408                struct flow *flow, ofp_port_t max_ports,
6409                uint8_t table_id, uint8_t n_tables)
6410 {
6411     const struct ofpact_enqueue *enqueue;
6412     const struct mf_field *mf;
6413
6414     switch (a->type) {
6415     case OFPACT_OUTPUT:
6416         return ofpact_check_output_port(ofpact_get_OUTPUT(a)->port,
6417                                         max_ports);
6418
6419     case OFPACT_CONTROLLER:
6420         return 0;
6421
6422     case OFPACT_ENQUEUE:
6423         enqueue = ofpact_get_ENQUEUE(a);
6424         if (ofp_to_u16(enqueue->port) >= ofp_to_u16(max_ports)
6425             && enqueue->port != OFPP_IN_PORT
6426             && enqueue->port != OFPP_LOCAL) {
6427             return OFPERR_OFPBAC_BAD_OUT_PORT;
6428         }
6429         return 0;
6430
6431     case OFPACT_OUTPUT_REG:
6432         return mf_check_src(&ofpact_get_OUTPUT_REG(a)->src, flow);
6433
6434     case OFPACT_BUNDLE:
6435         return bundle_check(ofpact_get_BUNDLE(a), max_ports, flow);
6436
6437     case OFPACT_SET_VLAN_VID:
6438         /* Remember if we saw a vlan tag in the flow to aid translating to
6439          * OpenFlow 1.1+ if need be. */
6440         ofpact_get_SET_VLAN_VID(a)->flow_has_vlan =
6441             (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI);
6442         if (!(flow->vlan_tci & htons(VLAN_CFI)) &&
6443             !ofpact_get_SET_VLAN_VID(a)->push_vlan_if_needed) {
6444             inconsistent_match(usable_protocols);
6445         }
6446         /* Temporary mark that we have a vlan tag. */
6447         flow->vlan_tci |= htons(VLAN_CFI);
6448         return 0;
6449
6450     case OFPACT_SET_VLAN_PCP:
6451         /* Remember if we saw a vlan tag in the flow to aid translating to
6452          * OpenFlow 1.1+ if need be. */
6453         ofpact_get_SET_VLAN_PCP(a)->flow_has_vlan =
6454             (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI);
6455         if (!(flow->vlan_tci & htons(VLAN_CFI)) &&
6456             !ofpact_get_SET_VLAN_PCP(a)->push_vlan_if_needed) {
6457             inconsistent_match(usable_protocols);
6458         }
6459         /* Temporary mark that we have a vlan tag. */
6460         flow->vlan_tci |= htons(VLAN_CFI);
6461         return 0;
6462
6463     case OFPACT_STRIP_VLAN:
6464         if (!(flow->vlan_tci & htons(VLAN_CFI))) {
6465             inconsistent_match(usable_protocols);
6466         }
6467         /* Temporary mark that we have no vlan tag. */
6468         flow->vlan_tci = htons(0);
6469         return 0;
6470
6471     case OFPACT_PUSH_VLAN:
6472         if (flow->vlan_tci & htons(VLAN_CFI)) {
6473             /* Multiple VLAN headers not supported. */
6474             return OFPERR_OFPBAC_BAD_TAG;
6475         }
6476         /* Temporary mark that we have a vlan tag. */
6477         flow->vlan_tci |= htons(VLAN_CFI);
6478         return 0;
6479
6480     case OFPACT_SET_ETH_SRC:
6481     case OFPACT_SET_ETH_DST:
6482         return 0;
6483
6484     case OFPACT_SET_IPV4_SRC:
6485     case OFPACT_SET_IPV4_DST:
6486         if (flow->dl_type != htons(ETH_TYPE_IP)) {
6487             inconsistent_match(usable_protocols);
6488         }
6489         return 0;
6490
6491     case OFPACT_SET_IP_DSCP:
6492     case OFPACT_SET_IP_ECN:
6493     case OFPACT_SET_IP_TTL:
6494     case OFPACT_DEC_TTL:
6495         if (!is_ip_any(flow)) {
6496             inconsistent_match(usable_protocols);
6497         }
6498         return 0;
6499
6500     case OFPACT_SET_L4_SRC_PORT:
6501     case OFPACT_SET_L4_DST_PORT:
6502         if (!is_ip_any(flow) || (flow->nw_frag & FLOW_NW_FRAG_LATER) ||
6503             (flow->nw_proto != IPPROTO_TCP && flow->nw_proto != IPPROTO_UDP
6504              && flow->nw_proto != IPPROTO_SCTP)) {
6505             inconsistent_match(usable_protocols);
6506         }
6507         /* Note on which transport protocol the port numbers are set.
6508          * This allows this set action to be converted to an OF1.2 set field
6509          * action. */
6510         if (a->type == OFPACT_SET_L4_SRC_PORT) {
6511             ofpact_get_SET_L4_SRC_PORT(a)->flow_ip_proto = flow->nw_proto;
6512         } else {
6513             ofpact_get_SET_L4_DST_PORT(a)->flow_ip_proto = flow->nw_proto;
6514         }
6515         return 0;
6516
6517     case OFPACT_REG_MOVE:
6518         return nxm_reg_move_check(ofpact_get_REG_MOVE(a), flow);
6519
6520     case OFPACT_SET_FIELD:
6521         mf = ofpact_get_SET_FIELD(a)->field;
6522         /* Require OXM_OF_VLAN_VID to have an existing VLAN header. */
6523         if (!mf_are_prereqs_ok(mf, flow) ||
6524             (mf->id == MFF_VLAN_VID && !(flow->vlan_tci & htons(VLAN_CFI)))) {
6525             VLOG_WARN_RL(&rl, "set_field %s lacks correct prerequisities",
6526                          mf->name);
6527             return OFPERR_OFPBAC_MATCH_INCONSISTENT;
6528         }
6529         /* Remember if we saw a vlan tag in the flow to aid translating to
6530          * OpenFlow 1.1 if need be. */
6531         ofpact_get_SET_FIELD(a)->flow_has_vlan =
6532             (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI);
6533         if (mf->id == MFF_VLAN_TCI) {
6534             /* The set field may add or remove the vlan tag,
6535              * Mark the status temporarily. */
6536             flow->vlan_tci = ofpact_get_SET_FIELD(a)->value.be16;
6537         }
6538         return 0;
6539
6540     case OFPACT_STACK_PUSH:
6541         return nxm_stack_push_check(ofpact_get_STACK_PUSH(a), flow);
6542
6543     case OFPACT_STACK_POP:
6544         return nxm_stack_pop_check(ofpact_get_STACK_POP(a), flow);
6545
6546     case OFPACT_SET_MPLS_LABEL:
6547     case OFPACT_SET_MPLS_TC:
6548     case OFPACT_SET_MPLS_TTL:
6549     case OFPACT_DEC_MPLS_TTL:
6550         if (!eth_type_mpls(flow->dl_type)) {
6551             inconsistent_match(usable_protocols);
6552         }
6553         return 0;
6554
6555     case OFPACT_SET_TUNNEL:
6556     case OFPACT_SET_QUEUE:
6557     case OFPACT_POP_QUEUE:
6558     case OFPACT_RESUBMIT:
6559         return 0;
6560
6561     case OFPACT_FIN_TIMEOUT:
6562         if (flow->nw_proto != IPPROTO_TCP) {
6563             inconsistent_match(usable_protocols);
6564         }
6565         return 0;
6566
6567     case OFPACT_LEARN:
6568         return learn_check(ofpact_get_LEARN(a), flow);
6569
6570     case OFPACT_CONJUNCTION:
6571         return 0;
6572
6573     case OFPACT_MULTIPATH:
6574         return multipath_check(ofpact_get_MULTIPATH(a), flow);
6575
6576     case OFPACT_NOTE:
6577     case OFPACT_EXIT:
6578         return 0;
6579
6580     case OFPACT_PUSH_MPLS:
6581         flow->dl_type = ofpact_get_PUSH_MPLS(a)->ethertype;
6582         /* The packet is now MPLS and the MPLS payload is opaque.
6583          * Thus nothing can be assumed about the network protocol.
6584          * Temporarily mark that we have no nw_proto. */
6585         flow->nw_proto = 0;
6586         return 0;
6587
6588     case OFPACT_POP_MPLS:
6589         if (!eth_type_mpls(flow->dl_type)) {
6590             inconsistent_match(usable_protocols);
6591         }
6592         flow->dl_type = ofpact_get_POP_MPLS(a)->ethertype;
6593         return 0;
6594
6595     case OFPACT_SAMPLE:
6596         return 0;
6597
6598     case OFPACT_CT: {
6599         struct ofpact_conntrack *oc = ofpact_get_CT(a);
6600         enum ofperr err;
6601
6602         if (!dl_type_is_ip_any(flow->dl_type)
6603             || (flow->ct_state & CS_INVALID && oc->flags & NX_CT_F_COMMIT)) {
6604             inconsistent_match(usable_protocols);
6605         }
6606
6607         if (oc->zone_src.field) {
6608             return mf_check_src(&oc->zone_src, flow);
6609         }
6610
6611         err = ofpacts_check(oc->actions, ofpact_ct_get_action_len(oc),
6612                             flow, max_ports, table_id, n_tables,
6613                             usable_protocols);
6614         return err;
6615     }
6616
6617     case OFPACT_NAT: {
6618         struct ofpact_nat *on = ofpact_get_NAT(a);
6619
6620         if (!dl_type_is_ip_any(flow->dl_type) ||
6621             (on->range_af == AF_INET && flow->dl_type != htons(ETH_TYPE_IP)) ||
6622             (on->range_af == AF_INET6
6623              && flow->dl_type != htons(ETH_TYPE_IPV6))) {
6624             inconsistent_match(usable_protocols);
6625         }
6626         return 0;
6627     }
6628
6629     case OFPACT_CLEAR_ACTIONS:
6630         return 0;
6631
6632     case OFPACT_WRITE_ACTIONS: {
6633         /* Use a temporary copy of 'usable_protocols' because we can't check
6634          * consistency of an action set. */
6635         struct ofpact_nest *on = ofpact_get_WRITE_ACTIONS(a);
6636         enum ofputil_protocol p = *usable_protocols;
6637         return ofpacts_check(on->actions, ofpact_nest_get_action_len(on),
6638                              flow, max_ports, table_id, n_tables, &p);
6639     }
6640
6641     case OFPACT_WRITE_METADATA:
6642         return 0;
6643
6644     case OFPACT_METER: {
6645         uint32_t mid = ofpact_get_METER(a)->meter_id;
6646         if (mid == 0 || mid > OFPM13_MAX) {
6647             return OFPERR_OFPMMFC_INVALID_METER;
6648         }
6649         return 0;
6650     }
6651
6652     case OFPACT_GOTO_TABLE: {
6653         uint8_t goto_table = ofpact_get_GOTO_TABLE(a)->table_id;
6654         if ((table_id != 255 && goto_table <= table_id)
6655             || (n_tables != 255 && goto_table >= n_tables)) {
6656             return OFPERR_OFPBIC_BAD_TABLE_ID;
6657         }
6658         return 0;
6659     }
6660
6661     case OFPACT_GROUP:
6662         return 0;
6663
6664     case OFPACT_UNROLL_XLATE:
6665         /* UNROLL is an internal action that should never be seen via
6666          * OpenFlow. */
6667         return OFPERR_OFPBAC_BAD_TYPE;
6668
6669     case OFPACT_DEBUG_RECIRC:
6670         return 0;
6671
6672     default:
6673         OVS_NOT_REACHED();
6674     }
6675 }
6676
6677 /* Checks that the 'ofpacts_len' bytes of actions in 'ofpacts' are
6678  * appropriate for a packet with the prerequisites satisfied by 'flow' in a
6679  * switch with no more than 'max_ports' ports.
6680  *
6681  * If 'ofpacts' and 'flow' are inconsistent with one another, un-sets in
6682  * '*usable_protocols' the protocols that forbid the inconsistency.  (An
6683  * example of an inconsistency between match and actions is a flow that does
6684  * not match on an MPLS Ethertype but has an action that pops an MPLS label.)
6685  *
6686  * May annotate ofpacts with information gathered from the 'flow'.
6687  *
6688  * May temporarily modify 'flow', but restores the changes before returning. */
6689 enum ofperr
6690 ofpacts_check(struct ofpact ofpacts[], size_t ofpacts_len,
6691               struct flow *flow, ofp_port_t max_ports,
6692               uint8_t table_id, uint8_t n_tables,
6693               enum ofputil_protocol *usable_protocols)
6694 {
6695     struct ofpact *a;
6696     ovs_be16 dl_type = flow->dl_type;
6697     ovs_be16 vlan_tci = flow->vlan_tci;
6698     uint8_t nw_proto = flow->nw_proto;
6699     enum ofperr error = 0;
6700
6701     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6702         error = ofpact_check__(usable_protocols, a, flow,
6703                                max_ports, table_id, n_tables);
6704         if (error) {
6705             break;
6706         }
6707     }
6708     /* Restore fields that may have been modified. */
6709     flow->dl_type = dl_type;
6710     flow->vlan_tci = vlan_tci;
6711     flow->nw_proto = nw_proto;
6712     return error;
6713 }
6714
6715 /* Like ofpacts_check(), but reports inconsistencies as
6716  * OFPERR_OFPBAC_MATCH_INCONSISTENT rather than clearing bits. */
6717 enum ofperr
6718 ofpacts_check_consistency(struct ofpact ofpacts[], size_t ofpacts_len,
6719                           struct flow *flow, ofp_port_t max_ports,
6720                           uint8_t table_id, uint8_t n_tables,
6721                           enum ofputil_protocol usable_protocols)
6722 {
6723     enum ofputil_protocol p = usable_protocols;
6724     enum ofperr error;
6725
6726     error = ofpacts_check(ofpacts, ofpacts_len, flow, max_ports,
6727                           table_id, n_tables, &p);
6728     return (error ? error
6729             : p != usable_protocols ? OFPERR_OFPBAC_MATCH_INCONSISTENT
6730             : 0);
6731 }
6732
6733 /* Returns the destination field that 'ofpact' would write to, or NULL
6734  * if the action would not write to an mf_field. */
6735 const struct mf_field *
6736 ofpact_get_mf_dst(const struct ofpact *ofpact)
6737 {
6738     if (ofpact->type == OFPACT_SET_FIELD) {
6739         const struct ofpact_set_field *orl;
6740
6741         orl = CONTAINER_OF(ofpact, struct ofpact_set_field, ofpact);
6742         return orl->field;
6743     } else if (ofpact->type == OFPACT_REG_MOVE) {
6744         const struct ofpact_reg_move *orm;
6745
6746         orm = CONTAINER_OF(ofpact, struct ofpact_reg_move, ofpact);
6747         return orm->dst.field;
6748     }
6749
6750     return NULL;
6751 }
6752
6753 static enum ofperr
6754 unsupported_nesting(enum ofpact_type action, enum ofpact_type outer_action)
6755 {
6756     VLOG_WARN("%s action doesn't support nested action %s",
6757               ofpact_name(outer_action), ofpact_name(action));
6758     return OFPERR_OFPBAC_BAD_ARGUMENT;
6759 }
6760
6761 static bool
6762 field_requires_ct(enum mf_field_id field)
6763 {
6764     return field == MFF_CT_MARK || field == MFF_CT_LABEL;
6765 }
6766
6767 /* Apply nesting constraints for actions */
6768 static enum ofperr
6769 ofpacts_verify_nested(const struct ofpact *a, enum ofpact_type outer_action)
6770 {
6771     const struct mf_field *field = ofpact_get_mf_dst(a);
6772
6773     if (field && field_requires_ct(field->id) && outer_action != OFPACT_CT) {
6774         VLOG_WARN("cannot set CT fields outside of ct action");
6775         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
6776     }
6777     if (a->type == OFPACT_NAT) {
6778         if (outer_action != OFPACT_CT) {
6779             VLOG_WARN("Cannot have NAT action outside of \"ct\" action");
6780             return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
6781         }
6782         return 0;
6783     }
6784
6785     if (outer_action) {
6786         ovs_assert(outer_action == OFPACT_WRITE_ACTIONS
6787                    || outer_action == OFPACT_CT);
6788
6789         if (outer_action == OFPACT_CT) {
6790             if (!field) {
6791                 return unsupported_nesting(a->type, outer_action);
6792             } else if (!field_requires_ct(field->id)) {
6793                 VLOG_WARN("%s action doesn't support nested modification "
6794                           "of %s", ofpact_name(outer_action), field->name);
6795                 return OFPERR_OFPBAC_BAD_ARGUMENT;
6796             }
6797         }
6798     }
6799
6800     return 0;
6801 }
6802
6803 /* Verifies that the 'ofpacts_len' bytes of actions in 'ofpacts' are in the
6804  * appropriate order as defined by the OpenFlow spec and as required by Open
6805  * vSwitch.
6806  *
6807  * 'allowed_ovsinsts' is a bitmap of OVSINST_* values, in which 1-bits indicate
6808  * instructions that are allowed within 'ofpacts[]'.
6809  *
6810  * If 'outer_action' is not zero, it specifies that the actions are nested
6811  * within another action of type 'outer_action'. */
6812 static enum ofperr
6813 ofpacts_verify(const struct ofpact ofpacts[], size_t ofpacts_len,
6814                uint32_t allowed_ovsinsts, enum ofpact_type outer_action)
6815 {
6816     const struct ofpact *a;
6817     enum ovs_instruction_type inst;
6818
6819     inst = OVSINST_OFPIT13_METER;
6820     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6821         enum ovs_instruction_type next;
6822         enum ofperr error;
6823
6824         if (a->type == OFPACT_CONJUNCTION) {
6825             OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6826                 if (a->type != OFPACT_CONJUNCTION && a->type != OFPACT_NOTE) {
6827                     VLOG_WARN("\"conjunction\" actions may be used along with "
6828                               "\"note\" but not any other kind of action "
6829                               "(such as the \"%s\" action used here)",
6830                               ofpact_name(a->type));
6831                     return OFPERR_NXBAC_BAD_CONJUNCTION;
6832                 }
6833             }
6834             return 0;
6835         }
6836
6837         error = ofpacts_verify_nested(a, outer_action);
6838         if (error) {
6839             return error;
6840         }
6841
6842         next = ovs_instruction_type_from_ofpact_type(a->type);
6843         if (a > ofpacts
6844             && (inst == OVSINST_OFPIT11_APPLY_ACTIONS
6845                 ? next < inst
6846                 : next <= inst)) {
6847             const char *name = ovs_instruction_name_from_type(inst);
6848             const char *next_name = ovs_instruction_name_from_type(next);
6849
6850             if (next == inst) {
6851                 VLOG_WARN("duplicate %s instruction not allowed, for OpenFlow "
6852                           "1.1+ compatibility", name);
6853             } else {
6854                 VLOG_WARN("invalid instruction ordering: %s must appear "
6855                           "before %s, for OpenFlow 1.1+ compatibility",
6856                           next_name, name);
6857             }
6858             return OFPERR_OFPBAC_UNSUPPORTED_ORDER;
6859         }
6860         if (!((1u << next) & allowed_ovsinsts)) {
6861             const char *name = ovs_instruction_name_from_type(next);
6862
6863             VLOG_WARN("%s instruction not allowed here", name);
6864             return OFPERR_OFPBIC_UNSUP_INST;
6865         }
6866
6867         inst = next;
6868     }
6869
6870     return 0;
6871 }
6872 \f
6873 /* Converting ofpacts to OpenFlow. */
6874
6875 static void
6876 encode_ofpact(const struct ofpact *a, enum ofp_version ofp_version,
6877               struct ofpbuf *out)
6878 {
6879     switch (a->type) {
6880 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                              \
6881         case OFPACT_##ENUM:                                             \
6882             encode_##ENUM(ofpact_get_##ENUM(a), ofp_version, out);      \
6883             return;
6884         OFPACTS
6885 #undef OFPACT
6886     default:
6887         OVS_NOT_REACHED();
6888     }
6889 }
6890
6891 /* Converts the 'ofpacts_len' bytes of ofpacts in 'ofpacts' into OpenFlow
6892  * actions in 'openflow', appending the actions to any existing data in
6893  * 'openflow'. */
6894 size_t
6895 ofpacts_put_openflow_actions(const struct ofpact ofpacts[], size_t ofpacts_len,
6896                              struct ofpbuf *openflow,
6897                              enum ofp_version ofp_version)
6898 {
6899     const struct ofpact *a;
6900     size_t start_size = openflow->size;
6901
6902     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6903         encode_ofpact(a, ofp_version, openflow);
6904     }
6905     return openflow->size - start_size;
6906 }
6907
6908 static enum ovs_instruction_type
6909 ofpact_is_apply_actions(const struct ofpact *a)
6910 {
6911     return (ovs_instruction_type_from_ofpact_type(a->type)
6912             == OVSINST_OFPIT11_APPLY_ACTIONS);
6913 }
6914
6915 void
6916 ofpacts_put_openflow_instructions(const struct ofpact ofpacts[],
6917                                   size_t ofpacts_len,
6918                                   struct ofpbuf *openflow,
6919                                   enum ofp_version ofp_version)
6920 {
6921     const struct ofpact *end = ofpact_end(ofpacts, ofpacts_len);
6922     const struct ofpact *a;
6923
6924     if (ofp_version == OFP10_VERSION) {
6925         ofpacts_put_openflow_actions(ofpacts, ofpacts_len, openflow,
6926                                      ofp_version);
6927         return;
6928     }
6929
6930     a = ofpacts;
6931     while (a < end) {
6932         if (ofpact_is_apply_actions(a)) {
6933             size_t ofs = openflow->size;
6934
6935             instruction_put_OFPIT11_APPLY_ACTIONS(openflow);
6936             do {
6937                 encode_ofpact(a, ofp_version, openflow);
6938                 a = ofpact_next(a);
6939             } while (a < end && ofpact_is_apply_actions(a));
6940             ofpacts_update_instruction_actions(openflow, ofs);
6941         } else {
6942             encode_ofpact(a, ofp_version, openflow);
6943             a = ofpact_next(a);
6944         }
6945     }
6946 }
6947 \f
6948 /* Sets of supported actions. */
6949
6950 /* Two-way translation between OVS's internal "OFPACT_*" representation of
6951  * actions and the "OFPAT_*" representation used in some OpenFlow version.
6952  * (OFPAT_* numbering varies from one OpenFlow version to another, so a given
6953  * instance is specific to one OpenFlow version.) */
6954 struct ofpact_map {
6955     enum ofpact_type ofpact;    /* Internal name for action type. */
6956     int ofpat;                  /* OFPAT_* number from OpenFlow spec. */
6957 };
6958
6959 static const struct ofpact_map *
6960 get_ofpact_map(enum ofp_version version)
6961 {
6962     /* OpenFlow 1.0 actions. */
6963     static const struct ofpact_map of10[] = {
6964         { OFPACT_OUTPUT, 0 },
6965         { OFPACT_SET_VLAN_VID, 1 },
6966         { OFPACT_SET_VLAN_PCP, 2 },
6967         { OFPACT_STRIP_VLAN, 3 },
6968         { OFPACT_SET_ETH_SRC, 4 },
6969         { OFPACT_SET_ETH_DST, 5 },
6970         { OFPACT_SET_IPV4_SRC, 6 },
6971         { OFPACT_SET_IPV4_DST, 7 },
6972         { OFPACT_SET_IP_DSCP, 8 },
6973         { OFPACT_SET_L4_SRC_PORT, 9 },
6974         { OFPACT_SET_L4_DST_PORT, 10 },
6975         { OFPACT_ENQUEUE, 11 },
6976         { 0, -1 },
6977     };
6978
6979     /* OpenFlow 1.1 actions. */
6980     static const struct ofpact_map of11[] = {
6981         { OFPACT_OUTPUT, 0 },
6982         { OFPACT_SET_VLAN_VID, 1 },
6983         { OFPACT_SET_VLAN_PCP, 2 },
6984         { OFPACT_SET_ETH_SRC, 3 },
6985         { OFPACT_SET_ETH_DST, 4 },
6986         { OFPACT_SET_IPV4_SRC, 5 },
6987         { OFPACT_SET_IPV4_DST, 6 },
6988         { OFPACT_SET_IP_DSCP, 7 },
6989         { OFPACT_SET_IP_ECN, 8 },
6990         { OFPACT_SET_L4_SRC_PORT, 9 },
6991         { OFPACT_SET_L4_DST_PORT, 10 },
6992         /* OFPAT_COPY_TTL_OUT (11) not supported. */
6993         /* OFPAT_COPY_TTL_IN (12) not supported. */
6994         { OFPACT_SET_MPLS_LABEL, 13 },
6995         { OFPACT_SET_MPLS_TC, 14 },
6996         { OFPACT_SET_MPLS_TTL, 15 },
6997         { OFPACT_DEC_MPLS_TTL, 16 },
6998         { OFPACT_PUSH_VLAN, 17 },
6999         { OFPACT_STRIP_VLAN, 18 },
7000         { OFPACT_PUSH_MPLS, 19 },
7001         { OFPACT_POP_MPLS, 20 },
7002         { OFPACT_SET_QUEUE, 21 },
7003         { OFPACT_GROUP, 22 },
7004         { OFPACT_SET_IP_TTL, 23 },
7005         { OFPACT_DEC_TTL, 24 },
7006         { 0, -1 },
7007     };
7008
7009     /* OpenFlow 1.2, 1.3, and 1.4 actions. */
7010     static const struct ofpact_map of12[] = {
7011         { OFPACT_OUTPUT, 0 },
7012         /* OFPAT_COPY_TTL_OUT (11) not supported. */
7013         /* OFPAT_COPY_TTL_IN (12) not supported. */
7014         { OFPACT_SET_MPLS_TTL, 15 },
7015         { OFPACT_DEC_MPLS_TTL, 16 },
7016         { OFPACT_PUSH_VLAN, 17 },
7017         { OFPACT_STRIP_VLAN, 18 },
7018         { OFPACT_PUSH_MPLS, 19 },
7019         { OFPACT_POP_MPLS, 20 },
7020         { OFPACT_SET_QUEUE, 21 },
7021         { OFPACT_GROUP, 22 },
7022         { OFPACT_SET_IP_TTL, 23 },
7023         { OFPACT_DEC_TTL, 24 },
7024         { OFPACT_SET_FIELD, 25 },
7025         /* OF1.3+ OFPAT_PUSH_PBB (26) not supported. */
7026         /* OF1.3+ OFPAT_POP_PBB (27) not supported. */
7027         { 0, -1 },
7028     };
7029
7030     switch (version) {
7031     case OFP10_VERSION:
7032         return of10;
7033
7034     case OFP11_VERSION:
7035         return of11;
7036
7037     case OFP12_VERSION:
7038     case OFP13_VERSION:
7039     case OFP14_VERSION:
7040     case OFP15_VERSION:
7041     default:
7042         return of12;
7043     }
7044 }
7045
7046 /* Converts 'ofpacts_bitmap', a bitmap whose bits correspond to OFPACT_*
7047  * values, into a bitmap of actions suitable for OpenFlow 'version', and
7048  * returns the result. */
7049 ovs_be32
7050 ofpact_bitmap_to_openflow(uint64_t ofpacts_bitmap, enum ofp_version version)
7051 {
7052     uint32_t openflow_bitmap = 0;
7053     const struct ofpact_map *x;
7054
7055     for (x = get_ofpact_map(version); x->ofpat >= 0; x++) {
7056         if (ofpacts_bitmap & (UINT64_C(1) << x->ofpact)) {
7057             openflow_bitmap |= 1u << x->ofpat;
7058         }
7059     }
7060     return htonl(openflow_bitmap);
7061 }
7062
7063 /* Converts 'ofpat_bitmap', a bitmap of actions from an OpenFlow message with
7064  * the given 'version' into a bitmap whose bits correspond to OFPACT_* values,
7065  * and returns the result. */
7066 uint64_t
7067 ofpact_bitmap_from_openflow(ovs_be32 ofpat_bitmap, enum ofp_version version)
7068 {
7069     uint64_t ofpact_bitmap = 0;
7070     const struct ofpact_map *x;
7071
7072     for (x = get_ofpact_map(version); x->ofpat >= 0; x++) {
7073         if (ofpat_bitmap & htonl(1u << x->ofpat)) {
7074             ofpact_bitmap |= UINT64_C(1) << x->ofpact;
7075         }
7076     }
7077     return ofpact_bitmap;
7078 }
7079
7080 /* Appends to 's' a string representation of the set of OFPACT_* represented
7081  * by 'ofpacts_bitmap'. */
7082 void
7083 ofpact_bitmap_format(uint64_t ofpacts_bitmap, struct ds *s)
7084 {
7085     if (!ofpacts_bitmap) {
7086         ds_put_cstr(s, "<none>");
7087     } else {
7088         while (ofpacts_bitmap) {
7089             ds_put_format(s, "%s ",
7090                           ofpact_name(rightmost_1bit_idx(ofpacts_bitmap)));
7091             ofpacts_bitmap = zero_rightmost_1bit(ofpacts_bitmap);
7092         }
7093         ds_chomp(s, ' ');
7094     }
7095 }
7096 \f
7097 /* Returns true if 'action' outputs to 'port', false otherwise. */
7098 static bool
7099 ofpact_outputs_to_port(const struct ofpact *ofpact, ofp_port_t port)
7100 {
7101     switch (ofpact->type) {
7102     case OFPACT_OUTPUT:
7103         return ofpact_get_OUTPUT(ofpact)->port == port;
7104     case OFPACT_ENQUEUE:
7105         return ofpact_get_ENQUEUE(ofpact)->port == port;
7106     case OFPACT_CONTROLLER:
7107         return port == OFPP_CONTROLLER;
7108
7109     case OFPACT_OUTPUT_REG:
7110     case OFPACT_BUNDLE:
7111     case OFPACT_SET_VLAN_VID:
7112     case OFPACT_SET_VLAN_PCP:
7113     case OFPACT_STRIP_VLAN:
7114     case OFPACT_PUSH_VLAN:
7115     case OFPACT_SET_ETH_SRC:
7116     case OFPACT_SET_ETH_DST:
7117     case OFPACT_SET_IPV4_SRC:
7118     case OFPACT_SET_IPV4_DST:
7119     case OFPACT_SET_IP_DSCP:
7120     case OFPACT_SET_IP_ECN:
7121     case OFPACT_SET_IP_TTL:
7122     case OFPACT_SET_L4_SRC_PORT:
7123     case OFPACT_SET_L4_DST_PORT:
7124     case OFPACT_REG_MOVE:
7125     case OFPACT_SET_FIELD:
7126     case OFPACT_STACK_PUSH:
7127     case OFPACT_STACK_POP:
7128     case OFPACT_DEC_TTL:
7129     case OFPACT_SET_MPLS_LABEL:
7130     case OFPACT_SET_MPLS_TC:
7131     case OFPACT_SET_MPLS_TTL:
7132     case OFPACT_DEC_MPLS_TTL:
7133     case OFPACT_SET_TUNNEL:
7134     case OFPACT_WRITE_METADATA:
7135     case OFPACT_SET_QUEUE:
7136     case OFPACT_POP_QUEUE:
7137     case OFPACT_FIN_TIMEOUT:
7138     case OFPACT_RESUBMIT:
7139     case OFPACT_LEARN:
7140     case OFPACT_CONJUNCTION:
7141     case OFPACT_MULTIPATH:
7142     case OFPACT_NOTE:
7143     case OFPACT_EXIT:
7144     case OFPACT_UNROLL_XLATE:
7145     case OFPACT_PUSH_MPLS:
7146     case OFPACT_POP_MPLS:
7147     case OFPACT_SAMPLE:
7148     case OFPACT_CLEAR_ACTIONS:
7149     case OFPACT_WRITE_ACTIONS:
7150     case OFPACT_GOTO_TABLE:
7151     case OFPACT_METER:
7152     case OFPACT_GROUP:
7153     case OFPACT_DEBUG_RECIRC:
7154     case OFPACT_CT:
7155     case OFPACT_NAT:
7156     default:
7157         return false;
7158     }
7159 }
7160
7161 /* Returns true if any action in the 'ofpacts_len' bytes of 'ofpacts' outputs
7162  * to 'port', false otherwise. */
7163 bool
7164 ofpacts_output_to_port(const struct ofpact *ofpacts, size_t ofpacts_len,
7165                        ofp_port_t port)
7166 {
7167     const struct ofpact *a;
7168
7169     OFPACT_FOR_EACH_FLATTENED (a, ofpacts, ofpacts_len) {
7170         if (ofpact_outputs_to_port(a, port)) {
7171             return true;
7172         }
7173     }
7174
7175     return false;
7176 }
7177
7178 /* Returns true if any action in the 'ofpacts_len' bytes of 'ofpacts' outputs
7179  * to 'group', false otherwise. */
7180 bool
7181 ofpacts_output_to_group(const struct ofpact *ofpacts, size_t ofpacts_len,
7182                         uint32_t group_id)
7183 {
7184     const struct ofpact *a;
7185
7186     OFPACT_FOR_EACH_FLATTENED (a, ofpacts, ofpacts_len) {
7187         if (a->type == OFPACT_GROUP
7188             && ofpact_get_GROUP(a)->group_id == group_id) {
7189             return true;
7190         }
7191     }
7192
7193     return false;
7194 }
7195
7196 bool
7197 ofpacts_equal(const struct ofpact *a, size_t a_len,
7198               const struct ofpact *b, size_t b_len)
7199 {
7200     return a_len == b_len && !memcmp(a, b, a_len);
7201 }
7202
7203 /* Finds the OFPACT_METER action, if any, in the 'ofpacts_len' bytes of
7204  * 'ofpacts'.  If found, returns its meter ID; if not, returns 0.
7205  *
7206  * This function relies on the order of 'ofpacts' being correct (as checked by
7207  * ofpacts_verify()). */
7208 uint32_t
7209 ofpacts_get_meter(const struct ofpact ofpacts[], size_t ofpacts_len)
7210 {
7211     const struct ofpact *a;
7212
7213     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
7214         enum ovs_instruction_type inst;
7215
7216         inst = ovs_instruction_type_from_ofpact_type(a->type);
7217         if (a->type == OFPACT_METER) {
7218             return ofpact_get_METER(a)->meter_id;
7219         } else if (inst > OVSINST_OFPIT13_METER) {
7220             break;
7221         }
7222     }
7223
7224     return 0;
7225 }
7226 \f
7227 /* Formatting ofpacts. */
7228
7229 static void
7230 ofpact_format(const struct ofpact *a, struct ds *s)
7231 {
7232     switch (a->type) {
7233 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                              \
7234         case OFPACT_##ENUM:                                             \
7235             format_##ENUM(ALIGNED_CAST(const struct STRUCT *, a), s);   \
7236             break;
7237         OFPACTS
7238 #undef OFPACT
7239     default:
7240         OVS_NOT_REACHED();
7241     }
7242 }
7243
7244 /* Appends a string representing the 'ofpacts_len' bytes of ofpacts in
7245  * 'ofpacts' to 'string'. */
7246 void
7247 ofpacts_format(const struct ofpact *ofpacts, size_t ofpacts_len,
7248                struct ds *string)
7249 {
7250     if (!ofpacts_len) {
7251         ds_put_cstr(string, "drop");
7252     } else {
7253         const struct ofpact *a;
7254
7255         OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
7256             if (a != ofpacts) {
7257                 ds_put_cstr(string, ",");
7258             }
7259
7260             /* XXX write-actions */
7261             ofpact_format(a, string);
7262         }
7263     }
7264 }
7265 \f
7266 /* Internal use by helpers. */
7267
7268 void *
7269 ofpact_put(struct ofpbuf *ofpacts, enum ofpact_type type, size_t len)
7270 {
7271     struct ofpact *ofpact;
7272
7273     ofpact_pad(ofpacts);
7274     ofpacts->header = ofpbuf_put_uninit(ofpacts, len);
7275     ofpact = ofpacts->header;
7276     ofpact_init(ofpact, type, len);
7277     return ofpact;
7278 }
7279
7280 void
7281 ofpact_init(struct ofpact *ofpact, enum ofpact_type type, size_t len)
7282 {
7283     memset(ofpact, 0, len);
7284     ofpact->type = type;
7285     ofpact->raw = -1;
7286     ofpact->len = len;
7287 }
7288 \f
7289 /* Updates 'ofpact->len' to the number of bytes in the tail of 'ofpacts'
7290  * starting at 'ofpact'.
7291  *
7292  * This is the correct way to update a variable-length ofpact's length after
7293  * adding the variable-length part of the payload.  (See the large comment
7294  * near the end of ofp-actions.h for more information.) */
7295 void
7296 ofpact_update_len(struct ofpbuf *ofpacts, struct ofpact *ofpact)
7297 {
7298     ovs_assert(ofpact == ofpacts->header);
7299     ofpact->len = (char *) ofpbuf_tail(ofpacts) - (char *) ofpact;
7300 }
7301
7302 /* Pads out 'ofpacts' to a multiple of OFPACT_ALIGNTO bytes in length.  Each
7303  * ofpact_put_<ENUM>() calls this function automatically beforehand, but the
7304  * client must call this itself after adding the final ofpact to an array of
7305  * them.
7306  *
7307  * (The consequences of failing to call this function are probably not dire.
7308  * OFPACT_FOR_EACH will calculate a pointer beyond the end of the ofpacts, but
7309  * not dereference it.  That's undefined behavior, technically, but it will not
7310  * cause a real problem on common systems.  Still, it seems better to call
7311  * it.) */
7312 void
7313 ofpact_pad(struct ofpbuf *ofpacts)
7314 {
7315     unsigned int pad = PAD_SIZE(ofpacts->size, OFPACT_ALIGNTO);
7316     if (pad) {
7317         ofpbuf_put_zeros(ofpacts, pad);
7318     }
7319 }
7320 \f
7321
7322
7323
7324 static char * OVS_WARN_UNUSED_RESULT
7325 ofpact_parse(enum ofpact_type type, char *value, struct ofpbuf *ofpacts,
7326              enum ofputil_protocol *usable_protocols)
7327 {
7328     switch (type) {
7329 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                            \
7330         case OFPACT_##ENUM:                                             \
7331             return parse_##ENUM(value, ofpacts, usable_protocols);
7332         OFPACTS
7333 #undef OFPACT
7334     default:
7335         OVS_NOT_REACHED();
7336     }
7337 }
7338
7339 static bool
7340 ofpact_type_from_name(const char *name, enum ofpact_type *type)
7341 {
7342 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                            \
7343     if (!strcasecmp(name, NAME)) {                                    \
7344         *type = OFPACT_##ENUM;                                          \
7345         return true;                                                    \
7346     }
7347     OFPACTS
7348 #undef OFPACT
7349
7350     return false;
7351 }
7352
7353 /* Parses 'str' as a series of instructions, and appends them to 'ofpacts'.
7354  *
7355  * Returns NULL if successful, otherwise a malloc()'d string describing the
7356  * error.  The caller is responsible for freeing the returned string.
7357  *
7358  * If 'outer_action' is specified, indicates that the actions being parsed
7359  * are nested within another action of the type specified in 'outer_action'. */
7360 static char * OVS_WARN_UNUSED_RESULT
7361 ofpacts_parse__(char *str, struct ofpbuf *ofpacts,
7362                 enum ofputil_protocol *usable_protocols,
7363                 bool allow_instructions, enum ofpact_type outer_action)
7364 {
7365     int prev_inst = -1;
7366     enum ofperr retval;
7367     char *key, *value;
7368     bool drop = false;
7369     char *pos;
7370
7371     pos = str;
7372     while (ofputil_parse_key_value(&pos, &key, &value)) {
7373         enum ovs_instruction_type inst = OVSINST_OFPIT11_APPLY_ACTIONS;
7374         enum ofpact_type type;
7375         char *error = NULL;
7376         ofp_port_t port;
7377
7378         if (ofpact_type_from_name(key, &type)) {
7379             error = ofpact_parse(type, value, ofpacts, usable_protocols);
7380             inst = ovs_instruction_type_from_ofpact_type(type);
7381         } else if (!strcasecmp(key, "mod_vlan_vid")) {
7382             error = parse_set_vlan_vid(value, ofpacts, true);
7383         } else if (!strcasecmp(key, "mod_vlan_pcp")) {
7384             error = parse_set_vlan_pcp(value, ofpacts, true);
7385         } else if (!strcasecmp(key, "set_nw_ttl")) {
7386             error = parse_SET_IP_TTL(value, ofpacts, usable_protocols);
7387         } else if (!strcasecmp(key, "pop_vlan")) {
7388             error = parse_pop_vlan(ofpacts);
7389         } else if (!strcasecmp(key, "set_tunnel64")) {
7390             error = parse_set_tunnel(value, ofpacts,
7391                                      NXAST_RAW_SET_TUNNEL64);
7392         } else if (!strcasecmp(key, "load")) {
7393             error = parse_reg_load(value, ofpacts);
7394         } else if (!strcasecmp(key, "bundle_load")) {
7395             error = parse_bundle_load(value, ofpacts);
7396         } else if (!strcasecmp(key, "drop")) {
7397             drop = true;
7398         } else if (!strcasecmp(key, "apply_actions")) {
7399             return xstrdup("apply_actions is the default instruction");
7400         } else if (ofputil_port_from_string(key, &port)) {
7401             ofpact_put_OUTPUT(ofpacts)->port = port;
7402         } else {
7403             return xasprintf("unknown action %s", key);
7404         }
7405         if (error) {
7406             return error;
7407         }
7408
7409         if (inst != OVSINST_OFPIT11_APPLY_ACTIONS) {
7410             if (!allow_instructions) {
7411                 return xasprintf("only actions are allowed here (not "
7412                                  "instruction %s)",
7413                                  ovs_instruction_name_from_type(inst));
7414             }
7415             if (inst == prev_inst) {
7416                 return xasprintf("instruction %s may be specified only once",
7417                                  ovs_instruction_name_from_type(inst));
7418             }
7419         }
7420         if (prev_inst != -1 && inst < prev_inst) {
7421             return xasprintf("instruction %s must be specified before %s",
7422                              ovs_instruction_name_from_type(inst),
7423                              ovs_instruction_name_from_type(prev_inst));
7424         }
7425         prev_inst = inst;
7426     }
7427     ofpact_pad(ofpacts);
7428
7429     if (drop && ofpacts->size) {
7430         return xstrdup("\"drop\" must not be accompanied by any other action "
7431                        "or instruction");
7432     }
7433
7434     retval = ofpacts_verify(ofpacts->data, ofpacts->size,
7435                             (allow_instructions
7436                              ? (1u << N_OVS_INSTRUCTIONS) - 1
7437                              : 1u << OVSINST_OFPIT11_APPLY_ACTIONS),
7438                             outer_action);
7439     if (retval) {
7440         return xstrdup("Incorrect instruction ordering");
7441     }
7442
7443     return NULL;
7444 }
7445
7446 static char * OVS_WARN_UNUSED_RESULT
7447 ofpacts_parse(char *str, struct ofpbuf *ofpacts,
7448               enum ofputil_protocol *usable_protocols, bool allow_instructions,
7449               enum ofpact_type outer_action)
7450 {
7451     uint32_t orig_size = ofpacts->size;
7452     char *error = ofpacts_parse__(str, ofpacts, usable_protocols,
7453                                   allow_instructions, outer_action);
7454     if (error) {
7455         ofpacts->size = orig_size;
7456     }
7457     return error;
7458 }
7459
7460 static char * OVS_WARN_UNUSED_RESULT
7461 ofpacts_parse_copy(const char *s_, struct ofpbuf *ofpacts,
7462                    enum ofputil_protocol *usable_protocols,
7463                    bool allow_instructions, enum ofpact_type outer_action)
7464 {
7465     char *error, *s;
7466
7467     *usable_protocols = OFPUTIL_P_ANY;
7468
7469     s = xstrdup(s_);
7470     error = ofpacts_parse(s, ofpacts, usable_protocols, allow_instructions,
7471                           outer_action);
7472     free(s);
7473
7474     return error;
7475 }
7476
7477 /* Parses 's' as a set of OpenFlow actions and appends the actions to
7478  * 'ofpacts'. 'outer_action', if nonzero, specifies that 's' contains actions
7479  * that are nested within the action of type 'outer_action'.
7480  *
7481  * Returns NULL if successful, otherwise a malloc()'d string describing the
7482  * error.  The caller is responsible for freeing the returned string. */
7483 char * OVS_WARN_UNUSED_RESULT
7484 ofpacts_parse_actions(const char *s, struct ofpbuf *ofpacts,
7485                       enum ofputil_protocol *usable_protocols)
7486 {
7487     return ofpacts_parse_copy(s, ofpacts, usable_protocols, false, 0);
7488 }
7489
7490 /* Parses 's' as a set of OpenFlow instructions and appends the instructions to
7491  * 'ofpacts'.
7492  *
7493  * Returns NULL if successful, otherwise a malloc()'d string describing the
7494  * error.  The caller is responsible for freeing the returned string. */
7495 char * OVS_WARN_UNUSED_RESULT
7496 ofpacts_parse_instructions(const char *s, struct ofpbuf *ofpacts,
7497                            enum ofputil_protocol *usable_protocols)
7498 {
7499     return ofpacts_parse_copy(s, ofpacts, usable_protocols, true, 0);
7500 }
7501
7502 const char *
7503 ofpact_name(enum ofpact_type type)
7504 {
7505     switch (type) {
7506 #define OFPACT(ENUM, STRUCT, MEMBER, NAME) case OFPACT_##ENUM: return NAME;
7507         OFPACTS
7508 #undef OFPACT
7509     }
7510     return "<unknown>";
7511 }
7512 \f
7513 /* Low-level action decoding and encoding functions. */
7514
7515 /* Everything needed to identify a particular OpenFlow action. */
7516 struct ofpact_hdrs {
7517     uint32_t vendor;              /* 0 if standard, otherwise a vendor code. */
7518     uint16_t type;                /* Type if standard, otherwise subtype. */
7519     uint8_t ofp_version;          /* From ofp_header. */
7520 };
7521
7522 /* Information about a particular OpenFlow action. */
7523 struct ofpact_raw_instance {
7524     /* The action's identity. */
7525     struct ofpact_hdrs hdrs;
7526     enum ofp_raw_action_type raw;
7527
7528     /* Looking up the action. */
7529     struct hmap_node decode_node; /* Based on 'hdrs'. */
7530     struct hmap_node encode_node; /* Based on 'raw' + 'hdrs.ofp_version'. */
7531
7532     /* The action's encoded size.
7533      *
7534      * If this action is fixed-length, 'min_length' == 'max_length'.
7535      * If it is variable length, then 'max_length' is ROUND_DOWN(UINT16_MAX,
7536      * OFP_ACTION_ALIGN) == 65528. */
7537     unsigned short int min_length;
7538     unsigned short int max_length;
7539
7540     /* For actions with a simple integer numeric argument, 'arg_ofs' is the
7541      * offset of that argument from the beginning of the action and 'arg_len'
7542      * its length, both in bytes.
7543      *
7544      * For actions that take other forms, these are both zero. */
7545     unsigned short int arg_ofs;
7546     unsigned short int arg_len;
7547
7548     /* The name of the action, e.g. "OFPAT_OUTPUT" or "NXAST_RESUBMIT". */
7549     const char *name;
7550
7551     /* If this action is deprecated, a human-readable string with a brief
7552      * explanation. */
7553     const char *deprecation;
7554 };
7555
7556 /* Action header. */
7557 struct ofp_action_header {
7558     /* The meaning of other values of 'type' generally depends on the OpenFlow
7559      * version (see enum ofp_raw_action_type).
7560      *
7561      * Across all OpenFlow versions, OFPAT_VENDOR indicates that 'vendor'
7562      * designates an OpenFlow vendor ID and that the remainder of the action
7563      * structure has a vendor-defined meaning.
7564      */
7565 #define OFPAT_VENDOR 0xffff
7566     ovs_be16 type;
7567
7568     /* Always a multiple of 8. */
7569     ovs_be16 len;
7570
7571     /* For type == OFPAT_VENDOR only, this is a vendor ID, e.g. NX_VENDOR_ID or
7572      * ONF_VENDOR_ID.  Other 'type's use this space for some other purpose. */
7573     ovs_be32 vendor;
7574 };
7575 OFP_ASSERT(sizeof(struct ofp_action_header) == 8);
7576
7577 /* Header for Nicira-defined actions and for ONF vendor extensions.
7578  *
7579  * This cannot be used as an entirely generic vendor extension action header,
7580  * because OpenFlow does not specify the location or size of the action
7581  * subtype; it just happens that ONF extensions and Nicira extensions share
7582  * this format. */
7583 struct ext_action_header {
7584     ovs_be16 type;                  /* OFPAT_VENDOR. */
7585     ovs_be16 len;                   /* At least 16. */
7586     ovs_be32 vendor;                /* NX_VENDOR_ID or ONF_VENDOR_ID. */
7587     ovs_be16 subtype;               /* See enum ofp_raw_action_type. */
7588     uint8_t pad[6];
7589 };
7590 OFP_ASSERT(sizeof(struct ext_action_header) == 16);
7591
7592 static bool
7593 ofpact_hdrs_equal(const struct ofpact_hdrs *a,
7594                   const struct ofpact_hdrs *b)
7595 {
7596     return (a->vendor == b->vendor
7597             && a->type == b->type
7598             && a->ofp_version == b->ofp_version);
7599 }
7600
7601 static uint32_t
7602 ofpact_hdrs_hash(const struct ofpact_hdrs *hdrs)
7603 {
7604     return hash_2words(hdrs->vendor, (hdrs->type << 16) | hdrs->ofp_version);
7605 }
7606
7607 #include "ofp-actions.inc2"
7608
7609 static struct hmap *
7610 ofpact_decode_hmap(void)
7611 {
7612     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
7613     static struct hmap hmap;
7614
7615     if (ovsthread_once_start(&once)) {
7616         struct ofpact_raw_instance *inst;
7617
7618         hmap_init(&hmap);
7619         for (inst = all_raw_instances;
7620              inst < &all_raw_instances[ARRAY_SIZE(all_raw_instances)];
7621              inst++) {
7622             hmap_insert(&hmap, &inst->decode_node,
7623                         ofpact_hdrs_hash(&inst->hdrs));
7624         }
7625         ovsthread_once_done(&once);
7626     }
7627     return &hmap;
7628 }
7629
7630 static struct hmap *
7631 ofpact_encode_hmap(void)
7632 {
7633     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
7634     static struct hmap hmap;
7635
7636     if (ovsthread_once_start(&once)) {
7637         struct ofpact_raw_instance *inst;
7638
7639         hmap_init(&hmap);
7640         for (inst = all_raw_instances;
7641              inst < &all_raw_instances[ARRAY_SIZE(all_raw_instances)];
7642              inst++) {
7643             hmap_insert(&hmap, &inst->encode_node,
7644                         hash_2words(inst->raw, inst->hdrs.ofp_version));
7645         }
7646         ovsthread_once_done(&once);
7647     }
7648     return &hmap;
7649 }
7650
7651 static enum ofperr
7652 ofpact_decode_raw(enum ofp_version ofp_version,
7653                   const struct ofp_action_header *oah, size_t length,
7654                   const struct ofpact_raw_instance **instp)
7655 {
7656     const struct ofpact_raw_instance *inst;
7657     struct ofpact_hdrs hdrs;
7658
7659     *instp = NULL;
7660     if (length < sizeof *oah) {
7661         return OFPERR_OFPBAC_BAD_LEN;
7662     }
7663
7664     /* Get base action type. */
7665     if (oah->type == htons(OFPAT_VENDOR)) {
7666         /* Get vendor. */
7667         hdrs.vendor = ntohl(oah->vendor);
7668         if (hdrs.vendor == NX_VENDOR_ID || hdrs.vendor == ONF_VENDOR_ID) {
7669             /* Get extension subtype. */
7670             const struct ext_action_header *nah;
7671
7672             nah = ALIGNED_CAST(const struct ext_action_header *, oah);
7673             if (length < sizeof *nah) {
7674                 return OFPERR_OFPBAC_BAD_LEN;
7675             }
7676             hdrs.type = ntohs(nah->subtype);
7677         } else {
7678             VLOG_WARN_RL(&rl, "OpenFlow action has unknown vendor %#"PRIx32,
7679                          hdrs.vendor);
7680             return OFPERR_OFPBAC_BAD_VENDOR;
7681         }
7682     } else {
7683         hdrs.vendor = 0;
7684         hdrs.type = ntohs(oah->type);
7685     }
7686
7687     hdrs.ofp_version = ofp_version;
7688     HMAP_FOR_EACH_WITH_HASH (inst, decode_node, ofpact_hdrs_hash(&hdrs),
7689                              ofpact_decode_hmap()) {
7690         if (ofpact_hdrs_equal(&hdrs, &inst->hdrs)) {
7691             *instp = inst;
7692             return 0;
7693         }
7694     }
7695
7696     return (hdrs.vendor
7697             ? OFPERR_OFPBAC_BAD_VENDOR_TYPE
7698             : OFPERR_OFPBAC_BAD_TYPE);
7699 }
7700
7701 static enum ofperr
7702 ofpact_pull_raw(struct ofpbuf *buf, enum ofp_version ofp_version,
7703                 enum ofp_raw_action_type *raw, uint64_t *arg)
7704 {
7705     const struct ofp_action_header *oah = buf->data;
7706     const struct ofpact_raw_instance *action;
7707     unsigned int length;
7708     enum ofperr error;
7709
7710     *raw = *arg = 0;
7711     error = ofpact_decode_raw(ofp_version, oah, buf->size, &action);
7712     if (error) {
7713         return error;
7714     }
7715
7716     if (action->deprecation) {
7717         VLOG_INFO_RL(&rl, "%s is deprecated in %s (%s)",
7718                      action->name, ofputil_version_to_string(ofp_version),
7719                      action->deprecation);
7720     }
7721
7722     length = ntohs(oah->len);
7723     if (length > buf->size) {
7724         VLOG_WARN_RL(&rl, "OpenFlow action %s length %u exceeds action buffer "
7725                      "length %"PRIu32, action->name, length, buf->size);
7726         return OFPERR_OFPBAC_BAD_LEN;
7727     }
7728     if (length < action->min_length || length > action->max_length) {
7729         VLOG_WARN_RL(&rl, "OpenFlow action %s length %u not in valid range "
7730                      "[%hu,%hu]", action->name, length,
7731                      action->min_length, action->max_length);
7732         return OFPERR_OFPBAC_BAD_LEN;
7733     }
7734     if (length % 8) {
7735         VLOG_WARN_RL(&rl, "OpenFlow action %s length %u is not a multiple "
7736                      "of 8", action->name, length);
7737         return OFPERR_OFPBAC_BAD_LEN;
7738     }
7739
7740     *raw = action->raw;
7741     *arg = 0;
7742     if (action->arg_len) {
7743         const uint8_t *p;
7744         int i;
7745
7746         p = ofpbuf_at_assert(buf, action->arg_ofs, action->arg_len);
7747         for (i = 0; i < action->arg_len; i++) {
7748             *arg = (*arg << 8) | p[i];
7749         }
7750     }
7751
7752     ofpbuf_pull(buf, length);
7753
7754     return 0;
7755 }
7756
7757 static const struct ofpact_raw_instance *
7758 ofpact_raw_lookup(enum ofp_version ofp_version, enum ofp_raw_action_type raw)
7759 {
7760     const struct ofpact_raw_instance *inst;
7761
7762     HMAP_FOR_EACH_WITH_HASH (inst, encode_node, hash_2words(raw, ofp_version),
7763                              ofpact_encode_hmap()) {
7764         if (inst->raw == raw && inst->hdrs.ofp_version == ofp_version) {
7765             return inst;
7766         }
7767     }
7768     OVS_NOT_REACHED();
7769 }
7770
7771 static void *
7772 ofpact_put_raw(struct ofpbuf *buf, enum ofp_version ofp_version,
7773                enum ofp_raw_action_type raw, uint64_t arg)
7774 {
7775     const struct ofpact_raw_instance *inst;
7776     struct ofp_action_header *oah;
7777     const struct ofpact_hdrs *hdrs;
7778
7779     inst = ofpact_raw_lookup(ofp_version, raw);
7780     hdrs = &inst->hdrs;
7781
7782     oah = ofpbuf_put_zeros(buf, inst->min_length);
7783     oah->type = htons(hdrs->vendor ? OFPAT_VENDOR : hdrs->type);
7784     oah->len = htons(inst->min_length);
7785     oah->vendor = htonl(hdrs->vendor);
7786
7787     switch (hdrs->vendor) {
7788     case 0:
7789         break;
7790
7791     case NX_VENDOR_ID:
7792     case ONF_VENDOR_ID: {
7793         struct ext_action_header *nah = (struct ext_action_header *) oah;
7794         nah->subtype = htons(hdrs->type);
7795         break;
7796     }
7797
7798     default:
7799         OVS_NOT_REACHED();
7800     }
7801
7802     if (inst->arg_len) {
7803         uint8_t *p = (uint8_t *) oah + inst->arg_ofs + inst->arg_len;
7804         int i;
7805
7806         for (i = 0; i < inst->arg_len; i++) {
7807             *--p = arg;
7808             arg >>= 8;
7809         }
7810     } else {
7811         ovs_assert(!arg);
7812     }
7813
7814     return oah;
7815 }
7816
7817 static void
7818 pad_ofpat(struct ofpbuf *openflow, size_t start_ofs)
7819 {
7820     struct ofp_action_header *oah;
7821
7822     ofpbuf_put_zeros(openflow, PAD_SIZE(openflow->size - start_ofs,
7823                                         OFP_ACTION_ALIGN));
7824
7825     oah = ofpbuf_at_assert(openflow, start_ofs, sizeof *oah);
7826     oah->len = htons(openflow->size - start_ofs);
7827 }
7828