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