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