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