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