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