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