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