Add support for connection tracking helper/ALGs.
[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             ofpbuf_pull(ofpacts, sizeof(*oc));
4856             error = ofpacts_parse_copy(value, ofpacts, usable_protocols, false,
4857                                        OFPACT_CT);
4858             ofpact_pad(ofpacts);
4859             ofpacts->header = ofpbuf_push_uninit(ofpacts, sizeof(*oc));
4860             oc = ofpacts->header;
4861         } else {
4862             error = xasprintf("invalid argument to \"ct\" action: `%s'", key);
4863         }
4864         if (error) {
4865             break;
4866         }
4867     }
4868
4869     ofpact_update_len(ofpacts, &oc->ofpact);
4870     ofpbuf_push_uninit(ofpacts, ct_offset);
4871     return error;
4872 }
4873
4874 static void
4875 format_alg(int port, struct ds *s)
4876 {
4877     if (port == IPPORT_FTP) {
4878         ds_put_format(s, "alg=ftp,");
4879     } else if (port) {
4880         ds_put_format(s, "alg=%d,", port);
4881     }
4882 }
4883
4884 static void
4885 format_CT(const struct ofpact_conntrack *a, struct ds *s)
4886 {
4887     ds_put_cstr(s, "ct(");
4888     if (a->flags & NX_CT_F_COMMIT) {
4889         ds_put_cstr(s, "commit,");
4890     }
4891     if (a->recirc_table != NX_CT_RECIRC_NONE) {
4892         ds_put_format(s, "table=%"PRIu8",", a->recirc_table);
4893     }
4894     if (a->zone_src.field) {
4895         ds_put_format(s, "zone=");
4896         mf_format_subfield(&a->zone_src, s);
4897         ds_put_char(s, ',');
4898     } else if (a->zone_imm) {
4899         ds_put_format(s, "zone=%"PRIu16",", a->zone_imm);
4900     }
4901     if (ofpact_ct_get_action_len(a)) {
4902         ds_put_cstr(s, "exec(");
4903         ofpacts_format(a->actions, ofpact_ct_get_action_len(a), s);
4904         ds_put_format(s, "),");
4905     }
4906     format_alg(a->alg, s);
4907     ds_chomp(s, ',');
4908     ds_put_char(s, ')');
4909 }
4910 \f
4911 /* Meter instruction. */
4912
4913 static void
4914 encode_METER(const struct ofpact_meter *meter,
4915              enum ofp_version ofp_version, struct ofpbuf *out)
4916 {
4917     if (ofp_version >= OFP13_VERSION) {
4918         instruction_put_OFPIT13_METER(out)->meter_id = htonl(meter->meter_id);
4919     }
4920 }
4921
4922 static char * OVS_WARN_UNUSED_RESULT
4923 parse_METER(char *arg, struct ofpbuf *ofpacts,
4924             enum ofputil_protocol *usable_protocols)
4925 {
4926     *usable_protocols &= OFPUTIL_P_OF13_UP;
4927     return str_to_u32(arg, &ofpact_put_METER(ofpacts)->meter_id);
4928 }
4929
4930 static void
4931 format_METER(const struct ofpact_meter *a, struct ds *s)
4932 {
4933     ds_put_format(s, "meter:%"PRIu32, a->meter_id);
4934 }
4935 \f
4936 /* Clear-Actions instruction. */
4937
4938 static void
4939 encode_CLEAR_ACTIONS(const struct ofpact_null *null OVS_UNUSED,
4940                      enum ofp_version ofp_version OVS_UNUSED,
4941                      struct ofpbuf *out OVS_UNUSED)
4942 {
4943     if (ofp_version > OFP10_VERSION) {
4944         instruction_put_OFPIT11_CLEAR_ACTIONS(out);
4945     }
4946 }
4947
4948 static char * OVS_WARN_UNUSED_RESULT
4949 parse_CLEAR_ACTIONS(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
4950                     enum ofputil_protocol *usable_protocols OVS_UNUSED)
4951 {
4952     ofpact_put_CLEAR_ACTIONS(ofpacts);
4953     return NULL;
4954 }
4955
4956 static void
4957 format_CLEAR_ACTIONS(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
4958 {
4959     ds_put_cstr(s, "clear_actions");
4960 }
4961 \f
4962 /* Write-Actions instruction. */
4963
4964 static void
4965 encode_WRITE_ACTIONS(const struct ofpact_nest *actions,
4966                      enum ofp_version ofp_version, struct ofpbuf *out)
4967 {
4968     if (ofp_version > OFP10_VERSION) {
4969         const size_t ofs = out->size;
4970
4971         instruction_put_OFPIT11_WRITE_ACTIONS(out);
4972         ofpacts_put_openflow_actions(actions->actions,
4973                                      ofpact_nest_get_action_len(actions),
4974                                      out, ofp_version);
4975         ofpacts_update_instruction_actions(out, ofs);
4976     }
4977 }
4978
4979 static char * OVS_WARN_UNUSED_RESULT
4980 parse_WRITE_ACTIONS(char *arg, struct ofpbuf *ofpacts,
4981                     enum ofputil_protocol *usable_protocols)
4982 {
4983     size_t ofs = ofpacts_pull(ofpacts);
4984     struct ofpact_nest *on;
4985     char *error;
4986
4987     /* Add a Write-Actions instruction and then pull it off. */
4988     ofpact_put(ofpacts, OFPACT_WRITE_ACTIONS, sizeof *on);
4989     ofpbuf_pull(ofpacts, sizeof *on);
4990
4991     /* Parse nested actions.
4992      *
4993      * We pulled off "write-actions" and the previous actions because the
4994      * OFPACT_WRITE_ACTIONS is only partially constructed: its length is such
4995      * that it doesn't actually include the nested actions.  That means that
4996      * ofpacts_parse() would reject them as being part of an Apply-Actions that
4997      * follows a Write-Actions, which is an invalid order.  */
4998     error = ofpacts_parse(arg, ofpacts, usable_protocols, false,
4999                           OFPACT_WRITE_ACTIONS);
5000
5001     /* Put the Write-Actions back on and update its length. */
5002     on = ofpbuf_push_uninit(ofpacts, sizeof *on);
5003     on->ofpact.len = ofpacts->size;
5004
5005     /* Put any previous actions or instructions back on. */
5006     ofpbuf_push_uninit(ofpacts, ofs);
5007
5008     return error;
5009 }
5010
5011 static void
5012 format_WRITE_ACTIONS(const struct ofpact_nest *a, struct ds *s)
5013 {
5014     ds_put_cstr(s, "write_actions(");
5015     ofpacts_format(a->actions, ofpact_nest_get_action_len(a), s);
5016     ds_put_char(s, ')');
5017 }
5018 \f
5019 /* Action structure for NXAST_WRITE_METADATA.
5020  *
5021  * Modifies the 'mask' bits of the metadata value. */
5022 struct nx_action_write_metadata {
5023     ovs_be16 type;                  /* OFPAT_VENDOR. */
5024     ovs_be16 len;                   /* Length is 32. */
5025     ovs_be32 vendor;                /* NX_VENDOR_ID. */
5026     ovs_be16 subtype;               /* NXAST_WRITE_METADATA. */
5027     uint8_t zeros[6];               /* Must be zero. */
5028     ovs_be64 metadata;              /* Metadata register. */
5029     ovs_be64 mask;                  /* Metadata mask. */
5030 };
5031 OFP_ASSERT(sizeof(struct nx_action_write_metadata) == 32);
5032
5033 static enum ofperr
5034 decode_NXAST_RAW_WRITE_METADATA(const struct nx_action_write_metadata *nawm,
5035                                 enum ofp_version ofp_version OVS_UNUSED,
5036                                 struct ofpbuf *out)
5037 {
5038     struct ofpact_metadata *om;
5039
5040     if (!is_all_zeros(nawm->zeros, sizeof nawm->zeros)) {
5041         return OFPERR_NXBRC_MUST_BE_ZERO;
5042     }
5043
5044     om = ofpact_put_WRITE_METADATA(out);
5045     om->metadata = nawm->metadata;
5046     om->mask = nawm->mask;
5047
5048     return 0;
5049 }
5050
5051 static void
5052 encode_WRITE_METADATA(const struct ofpact_metadata *metadata,
5053                       enum ofp_version ofp_version, struct ofpbuf *out)
5054 {
5055     if (ofp_version == OFP10_VERSION) {
5056         struct nx_action_write_metadata *nawm;
5057
5058         nawm = put_NXAST_WRITE_METADATA(out);
5059         nawm->metadata = metadata->metadata;
5060         nawm->mask = metadata->mask;
5061     } else {
5062         struct ofp11_instruction_write_metadata *oiwm;
5063
5064         oiwm = instruction_put_OFPIT11_WRITE_METADATA(out);
5065         oiwm->metadata = metadata->metadata;
5066         oiwm->metadata_mask = metadata->mask;
5067     }
5068 }
5069
5070 static char * OVS_WARN_UNUSED_RESULT
5071 parse_WRITE_METADATA(char *arg, struct ofpbuf *ofpacts,
5072                      enum ofputil_protocol *usable_protocols)
5073 {
5074     struct ofpact_metadata *om;
5075     char *mask = strchr(arg, '/');
5076
5077     *usable_protocols &= OFPUTIL_P_NXM_OF11_UP;
5078
5079     om = ofpact_put_WRITE_METADATA(ofpacts);
5080     if (mask) {
5081         char *error;
5082
5083         *mask = '\0';
5084         error = str_to_be64(mask + 1, &om->mask);
5085         if (error) {
5086             return error;
5087         }
5088     } else {
5089         om->mask = OVS_BE64_MAX;
5090     }
5091
5092     return str_to_be64(arg, &om->metadata);
5093 }
5094
5095 static void
5096 format_WRITE_METADATA(const struct ofpact_metadata *a, struct ds *s)
5097 {
5098     ds_put_format(s, "write_metadata:%#"PRIx64, ntohll(a->metadata));
5099     if (a->mask != OVS_BE64_MAX) {
5100         ds_put_format(s, "/%#"PRIx64, ntohll(a->mask));
5101     }
5102 }
5103 \f
5104 /* Goto-Table instruction. */
5105
5106 static void
5107 encode_GOTO_TABLE(const struct ofpact_goto_table *goto_table,
5108                   enum ofp_version ofp_version, struct ofpbuf *out)
5109 {
5110     if (ofp_version == OFP10_VERSION) {
5111         struct nx_action_resubmit *nar;
5112
5113         nar = put_NXAST_RESUBMIT_TABLE(out);
5114         nar->table = goto_table->table_id;
5115         nar->in_port = htons(ofp_to_u16(OFPP_IN_PORT));
5116     } else {
5117         struct ofp11_instruction_goto_table *oigt;
5118
5119         oigt = instruction_put_OFPIT11_GOTO_TABLE(out);
5120         oigt->table_id = goto_table->table_id;
5121         memset(oigt->pad, 0, sizeof oigt->pad);
5122     }
5123 }
5124
5125 static char * OVS_WARN_UNUSED_RESULT
5126 parse_GOTO_TABLE(char *arg, struct ofpbuf *ofpacts,
5127                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
5128 {
5129     struct ofpact_goto_table *ogt = ofpact_put_GOTO_TABLE(ofpacts);
5130     char *table_s = strsep(&arg, ",");
5131     if (!table_s || !table_s[0]) {
5132         return xstrdup("instruction goto-table needs table id");
5133     }
5134     return str_to_u8(table_s, "table", &ogt->table_id);
5135 }
5136
5137 static void
5138 format_GOTO_TABLE(const struct ofpact_goto_table *a, struct ds *s)
5139 {
5140     ds_put_format(s, "goto_table:%"PRIu8, a->table_id);
5141 }
5142 \f
5143 static void
5144 log_bad_action(const struct ofp_action_header *actions, size_t actions_len,
5145                const struct ofp_action_header *bad_action, enum ofperr error)
5146 {
5147     if (!VLOG_DROP_WARN(&rl)) {
5148         struct ds s;
5149
5150         ds_init(&s);
5151         ds_put_hex_dump(&s, actions, actions_len, 0, false);
5152         VLOG_WARN("bad action at offset %#"PRIxPTR" (%s):\n%s",
5153                   (char *)bad_action - (char *)actions,
5154                   ofperr_get_name(error), ds_cstr(&s));
5155         ds_destroy(&s);
5156     }
5157 }
5158
5159 static enum ofperr
5160 ofpacts_decode(const void *actions, size_t actions_len,
5161                enum ofp_version ofp_version, struct ofpbuf *ofpacts)
5162 {
5163     struct ofpbuf openflow;
5164
5165     ofpbuf_use_const(&openflow, actions, actions_len);
5166     while (openflow.size) {
5167         const struct ofp_action_header *action = openflow.data;
5168         enum ofp_raw_action_type raw;
5169         enum ofperr error;
5170         uint64_t arg;
5171
5172         error = ofpact_pull_raw(&openflow, ofp_version, &raw, &arg);
5173         if (!error) {
5174             error = ofpact_decode(action, raw, ofp_version, arg, ofpacts);
5175         }
5176
5177         if (error) {
5178             log_bad_action(actions, actions_len, action, error);
5179             return error;
5180         }
5181     }
5182
5183     ofpact_pad(ofpacts);
5184     return 0;
5185 }
5186
5187 static enum ofperr
5188 ofpacts_pull_openflow_actions__(struct ofpbuf *openflow,
5189                                 unsigned int actions_len,
5190                                 enum ofp_version version,
5191                                 uint32_t allowed_ovsinsts,
5192                                 struct ofpbuf *ofpacts,
5193                                 enum ofpact_type outer_action)
5194 {
5195     const struct ofp_action_header *actions;
5196     enum ofperr error;
5197
5198     if (!outer_action) {
5199         ofpbuf_clear(ofpacts);
5200     }
5201
5202     if (actions_len % OFP_ACTION_ALIGN != 0) {
5203         VLOG_WARN_RL(&rl, "OpenFlow message actions length %u is not a "
5204                      "multiple of %d", actions_len, OFP_ACTION_ALIGN);
5205         return OFPERR_OFPBRC_BAD_LEN;
5206     }
5207
5208     actions = ofpbuf_try_pull(openflow, actions_len);
5209     if (actions == NULL) {
5210         VLOG_WARN_RL(&rl, "OpenFlow message actions length %u exceeds "
5211                      "remaining message length (%"PRIu32")",
5212                      actions_len, openflow->size);
5213         return OFPERR_OFPBRC_BAD_LEN;
5214     }
5215
5216     error = ofpacts_decode(actions, actions_len, version, ofpacts);
5217     if (error) {
5218         ofpbuf_clear(ofpacts);
5219         return error;
5220     }
5221
5222     error = ofpacts_verify(ofpacts->data, ofpacts->size, allowed_ovsinsts,
5223                            outer_action);
5224     if (error) {
5225         ofpbuf_clear(ofpacts);
5226     }
5227     return error;
5228 }
5229
5230 /* Attempts to convert 'actions_len' bytes of OpenFlow actions from the
5231  * front of 'openflow' into ofpacts.  On success, replaces any existing content
5232  * in 'ofpacts' by the converted ofpacts; on failure, clears 'ofpacts'.
5233  * Returns 0 if successful, otherwise an OpenFlow error.
5234  *
5235  * Actions are processed according to their OpenFlow version which
5236  * is provided in the 'version' parameter.
5237  *
5238  * In most places in OpenFlow, actions appear encapsulated in instructions, so
5239  * you should call ofpacts_pull_openflow_instructions() instead of this
5240  * function.
5241  *
5242  * The parsed actions are valid generically, but they may not be valid in a
5243  * specific context.  For example, port numbers up to OFPP_MAX are valid
5244  * generically, but specific datapaths may only support port numbers in a
5245  * smaller range.  Use ofpacts_check() to additional check whether actions are
5246  * valid in a specific context. */
5247 enum ofperr
5248 ofpacts_pull_openflow_actions(struct ofpbuf *openflow,
5249                               unsigned int actions_len,
5250                               enum ofp_version version,
5251                               struct ofpbuf *ofpacts)
5252 {
5253     return ofpacts_pull_openflow_actions__(openflow, actions_len, version,
5254                                            1u << OVSINST_OFPIT11_APPLY_ACTIONS,
5255                                            ofpacts, 0);
5256 }
5257 \f
5258 /* OpenFlow 1.1 actions. */
5259
5260
5261 /* True if an action sets the value of a field
5262  * in a way that is compatibile with the action set.
5263  * The field can be set via either a set or a move action.
5264  * False otherwise. */
5265 static bool
5266 ofpact_is_set_or_move_action(const struct ofpact *a)
5267 {
5268     switch (a->type) {
5269     case OFPACT_SET_FIELD:
5270     case OFPACT_REG_MOVE:
5271     case OFPACT_SET_ETH_DST:
5272     case OFPACT_SET_ETH_SRC:
5273     case OFPACT_SET_IP_DSCP:
5274     case OFPACT_SET_IP_ECN:
5275     case OFPACT_SET_IP_TTL:
5276     case OFPACT_SET_IPV4_DST:
5277     case OFPACT_SET_IPV4_SRC:
5278     case OFPACT_SET_L4_DST_PORT:
5279     case OFPACT_SET_L4_SRC_PORT:
5280     case OFPACT_SET_MPLS_LABEL:
5281     case OFPACT_SET_MPLS_TC:
5282     case OFPACT_SET_MPLS_TTL:
5283     case OFPACT_SET_QUEUE:
5284     case OFPACT_SET_TUNNEL:
5285     case OFPACT_SET_VLAN_PCP:
5286     case OFPACT_SET_VLAN_VID:
5287         return true;
5288     case OFPACT_BUNDLE:
5289     case OFPACT_CLEAR_ACTIONS:
5290     case OFPACT_CT:
5291     case OFPACT_CONTROLLER:
5292     case OFPACT_DEC_MPLS_TTL:
5293     case OFPACT_DEC_TTL:
5294     case OFPACT_ENQUEUE:
5295     case OFPACT_EXIT:
5296     case OFPACT_UNROLL_XLATE:
5297     case OFPACT_FIN_TIMEOUT:
5298     case OFPACT_GOTO_TABLE:
5299     case OFPACT_GROUP:
5300     case OFPACT_LEARN:
5301     case OFPACT_CONJUNCTION:
5302     case OFPACT_METER:
5303     case OFPACT_MULTIPATH:
5304     case OFPACT_NOTE:
5305     case OFPACT_OUTPUT:
5306     case OFPACT_OUTPUT_REG:
5307     case OFPACT_POP_MPLS:
5308     case OFPACT_POP_QUEUE:
5309     case OFPACT_PUSH_MPLS:
5310     case OFPACT_PUSH_VLAN:
5311     case OFPACT_RESUBMIT:
5312     case OFPACT_SAMPLE:
5313     case OFPACT_STACK_POP:
5314     case OFPACT_STACK_PUSH:
5315     case OFPACT_STRIP_VLAN:
5316     case OFPACT_WRITE_ACTIONS:
5317     case OFPACT_WRITE_METADATA:
5318     case OFPACT_DEBUG_RECIRC:
5319         return false;
5320     default:
5321         OVS_NOT_REACHED();
5322     }
5323 }
5324
5325 /* True if an action is allowed in the action set.
5326  * False otherwise. */
5327 static bool
5328 ofpact_is_allowed_in_actions_set(const struct ofpact *a)
5329 {
5330     switch (a->type) {
5331     case OFPACT_DEC_MPLS_TTL:
5332     case OFPACT_DEC_TTL:
5333     case OFPACT_GROUP:
5334     case OFPACT_OUTPUT:
5335     case OFPACT_POP_MPLS:
5336     case OFPACT_PUSH_MPLS:
5337     case OFPACT_PUSH_VLAN:
5338     case OFPACT_REG_MOVE:
5339     case OFPACT_SET_FIELD:
5340     case OFPACT_SET_ETH_DST:
5341     case OFPACT_SET_ETH_SRC:
5342     case OFPACT_SET_IP_DSCP:
5343     case OFPACT_SET_IP_ECN:
5344     case OFPACT_SET_IP_TTL:
5345     case OFPACT_SET_IPV4_DST:
5346     case OFPACT_SET_IPV4_SRC:
5347     case OFPACT_SET_L4_DST_PORT:
5348     case OFPACT_SET_L4_SRC_PORT:
5349     case OFPACT_SET_MPLS_LABEL:
5350     case OFPACT_SET_MPLS_TC:
5351     case OFPACT_SET_MPLS_TTL:
5352     case OFPACT_SET_QUEUE:
5353     case OFPACT_SET_TUNNEL:
5354     case OFPACT_SET_VLAN_PCP:
5355     case OFPACT_SET_VLAN_VID:
5356     case OFPACT_STRIP_VLAN:
5357         return true;
5358
5359     /* In general these actions are excluded because they are not part of
5360      * the OpenFlow specification nor map to actions that are defined in
5361      * the specification.  Thus the order in which they should be applied
5362      * in the action set is undefined. */
5363     case OFPACT_BUNDLE:
5364     case OFPACT_CONTROLLER:
5365     case OFPACT_CT:
5366     case OFPACT_ENQUEUE:
5367     case OFPACT_EXIT:
5368     case OFPACT_UNROLL_XLATE:
5369     case OFPACT_FIN_TIMEOUT:
5370     case OFPACT_LEARN:
5371     case OFPACT_CONJUNCTION:
5372     case OFPACT_MULTIPATH:
5373     case OFPACT_NOTE:
5374     case OFPACT_OUTPUT_REG:
5375     case OFPACT_POP_QUEUE:
5376     case OFPACT_RESUBMIT:
5377     case OFPACT_SAMPLE:
5378     case OFPACT_STACK_POP:
5379     case OFPACT_STACK_PUSH:
5380     case OFPACT_DEBUG_RECIRC:
5381
5382     /* The action set may only include actions and thus
5383      * may not include any instructions */
5384     case OFPACT_CLEAR_ACTIONS:
5385     case OFPACT_GOTO_TABLE:
5386     case OFPACT_METER:
5387     case OFPACT_WRITE_ACTIONS:
5388     case OFPACT_WRITE_METADATA:
5389         return false;
5390     default:
5391         OVS_NOT_REACHED();
5392     }
5393 }
5394
5395 /* Append ofpact 'a' onto the tail of 'out' */
5396 static void
5397 ofpact_copy(struct ofpbuf *out, const struct ofpact *a)
5398 {
5399     ofpbuf_put(out, a, OFPACT_ALIGN(a->len));
5400 }
5401
5402 /* Copies the last ofpact whose type is 'filter' from 'in' to 'out'. */
5403 static bool
5404 ofpacts_copy_last(struct ofpbuf *out, const struct ofpbuf *in,
5405                   enum ofpact_type filter)
5406 {
5407     const struct ofpact *target;
5408     const struct ofpact *a;
5409
5410     target = NULL;
5411     OFPACT_FOR_EACH (a, in->data, in->size) {
5412         if (a->type == filter) {
5413             target = a;
5414         }
5415     }
5416     if (target) {
5417         ofpact_copy(out, target);
5418     }
5419     return target != NULL;
5420 }
5421
5422 /* Append all ofpacts, for which 'filter' returns true, from 'in' to 'out'.
5423  * The order of appended ofpacts is preserved between 'in' and 'out' */
5424 static void
5425 ofpacts_copy_all(struct ofpbuf *out, const struct ofpbuf *in,
5426                  bool (*filter)(const struct ofpact *))
5427 {
5428     const struct ofpact *a;
5429
5430     OFPACT_FOR_EACH (a, in->data, in->size) {
5431         if (filter(a)) {
5432             ofpact_copy(out, a);
5433         }
5434     }
5435 }
5436
5437 /* Reads 'action_set', which contains ofpacts accumulated by
5438  * OFPACT_WRITE_ACTIONS instructions, and writes equivalent actions to be
5439  * executed directly into 'action_list'.  (These names correspond to the
5440  * "Action Set" and "Action List" terms used in OpenFlow 1.1+.)
5441  *
5442  * In general this involves appending the last instance of each action that is
5443  * admissible in the action set in the order described in the OpenFlow
5444  * specification.
5445  *
5446  * Exceptions:
5447  * + output action is only appended if no group action was present in 'in'.
5448  * + As a simplification all set actions are copied in the order the are
5449  *   provided in 'in' as many set actions applied to a field has the same
5450  *   affect as only applying the last action that sets a field and
5451  *   duplicates are removed by do_xlate_actions().
5452  *   This has an unwanted side-effect of compsoting multiple
5453  *   LOAD_REG actions that touch different regions of the same field. */
5454 void
5455 ofpacts_execute_action_set(struct ofpbuf *action_list,
5456                            const struct ofpbuf *action_set)
5457 {
5458     /* The OpenFlow spec "Action Set" section specifies this order. */
5459     ofpacts_copy_last(action_list, action_set, OFPACT_STRIP_VLAN);
5460     ofpacts_copy_last(action_list, action_set, OFPACT_POP_MPLS);
5461     ofpacts_copy_last(action_list, action_set, OFPACT_PUSH_MPLS);
5462     ofpacts_copy_last(action_list, action_set, OFPACT_PUSH_VLAN);
5463     ofpacts_copy_last(action_list, action_set, OFPACT_DEC_TTL);
5464     ofpacts_copy_last(action_list, action_set, OFPACT_DEC_MPLS_TTL);
5465     ofpacts_copy_all(action_list, action_set, ofpact_is_set_or_move_action);
5466     ofpacts_copy_last(action_list, action_set, OFPACT_SET_QUEUE);
5467
5468     /* If both OFPACT_GROUP and OFPACT_OUTPUT are present, OpenFlow says that
5469      * we should execute only OFPACT_GROUP.
5470      *
5471      * If neither OFPACT_GROUP nor OFPACT_OUTPUT is present, then we can drop
5472      * all the actions because there's no point in modifying a packet that will
5473      * not be sent anywhere. */
5474     if (!ofpacts_copy_last(action_list, action_set, OFPACT_GROUP) &&
5475         !ofpacts_copy_last(action_list, action_set, OFPACT_OUTPUT) &&
5476         !ofpacts_copy_last(action_list, action_set, OFPACT_RESUBMIT)) {
5477         ofpbuf_clear(action_list);
5478     }
5479 }
5480
5481
5482 static enum ofperr
5483 ofpacts_decode_for_action_set(const struct ofp_action_header *in,
5484                               size_t n_in, enum ofp_version version,
5485                               struct ofpbuf *out)
5486 {
5487     enum ofperr error;
5488     struct ofpact *a;
5489     size_t start = out->size;
5490
5491     error = ofpacts_decode(in, n_in, version, out);
5492
5493     if (error) {
5494         return error;
5495     }
5496
5497     OFPACT_FOR_EACH (a, ofpact_end(out->data, start), out->size - start) {
5498         if (!ofpact_is_allowed_in_actions_set(a)) {
5499             VLOG_WARN_RL(&rl, "disallowed action in action set");
5500             return OFPERR_OFPBAC_BAD_TYPE;
5501         }
5502     }
5503
5504     return 0;
5505 }
5506 \f
5507 /* OpenFlow 1.1 instructions. */
5508
5509 struct instruction_type_info {
5510     enum ovs_instruction_type type;
5511     const char *name;
5512 };
5513
5514 static const struct instruction_type_info inst_info[] = {
5515 #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME)    {OVSINST_##ENUM, NAME},
5516 OVS_INSTRUCTIONS
5517 #undef DEFINE_INST
5518 };
5519
5520 const char *
5521 ovs_instruction_name_from_type(enum ovs_instruction_type type)
5522 {
5523     return inst_info[type].name;
5524 }
5525
5526 int
5527 ovs_instruction_type_from_name(const char *name)
5528 {
5529     const struct instruction_type_info *p;
5530     for (p = inst_info; p < &inst_info[ARRAY_SIZE(inst_info)]; p++) {
5531         if (!strcasecmp(name, p->name)) {
5532             return p->type;
5533         }
5534     }
5535     return -1;
5536 }
5537
5538 enum ovs_instruction_type
5539 ovs_instruction_type_from_ofpact_type(enum ofpact_type type)
5540 {
5541     switch (type) {
5542     case OFPACT_METER:
5543         return OVSINST_OFPIT13_METER;
5544     case OFPACT_CLEAR_ACTIONS:
5545         return OVSINST_OFPIT11_CLEAR_ACTIONS;
5546     case OFPACT_WRITE_ACTIONS:
5547         return OVSINST_OFPIT11_WRITE_ACTIONS;
5548     case OFPACT_WRITE_METADATA:
5549         return OVSINST_OFPIT11_WRITE_METADATA;
5550     case OFPACT_GOTO_TABLE:
5551         return OVSINST_OFPIT11_GOTO_TABLE;
5552     case OFPACT_OUTPUT:
5553     case OFPACT_GROUP:
5554     case OFPACT_CONTROLLER:
5555     case OFPACT_ENQUEUE:
5556     case OFPACT_OUTPUT_REG:
5557     case OFPACT_BUNDLE:
5558     case OFPACT_SET_VLAN_VID:
5559     case OFPACT_SET_VLAN_PCP:
5560     case OFPACT_STRIP_VLAN:
5561     case OFPACT_PUSH_VLAN:
5562     case OFPACT_SET_ETH_SRC:
5563     case OFPACT_SET_ETH_DST:
5564     case OFPACT_SET_IPV4_SRC:
5565     case OFPACT_SET_IPV4_DST:
5566     case OFPACT_SET_IP_DSCP:
5567     case OFPACT_SET_IP_ECN:
5568     case OFPACT_SET_IP_TTL:
5569     case OFPACT_SET_L4_SRC_PORT:
5570     case OFPACT_SET_L4_DST_PORT:
5571     case OFPACT_REG_MOVE:
5572     case OFPACT_SET_FIELD:
5573     case OFPACT_STACK_PUSH:
5574     case OFPACT_STACK_POP:
5575     case OFPACT_DEC_TTL:
5576     case OFPACT_SET_MPLS_LABEL:
5577     case OFPACT_SET_MPLS_TC:
5578     case OFPACT_SET_MPLS_TTL:
5579     case OFPACT_DEC_MPLS_TTL:
5580     case OFPACT_PUSH_MPLS:
5581     case OFPACT_POP_MPLS:
5582     case OFPACT_SET_TUNNEL:
5583     case OFPACT_SET_QUEUE:
5584     case OFPACT_POP_QUEUE:
5585     case OFPACT_FIN_TIMEOUT:
5586     case OFPACT_RESUBMIT:
5587     case OFPACT_LEARN:
5588     case OFPACT_CONJUNCTION:
5589     case OFPACT_MULTIPATH:
5590     case OFPACT_NOTE:
5591     case OFPACT_EXIT:
5592     case OFPACT_UNROLL_XLATE:
5593     case OFPACT_SAMPLE:
5594     case OFPACT_DEBUG_RECIRC:
5595     case OFPACT_CT:
5596     default:
5597         return OVSINST_OFPIT11_APPLY_ACTIONS;
5598     }
5599 }
5600
5601 enum ofperr
5602 ovs_instruction_type_from_inst_type(enum ovs_instruction_type *instruction_type,
5603                                     const uint16_t inst_type)
5604 {
5605     switch (inst_type) {
5606
5607 #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME) \
5608     case ENUM:                                      \
5609         *instruction_type = OVSINST_##ENUM;         \
5610         return 0;
5611 OVS_INSTRUCTIONS
5612 #undef DEFINE_INST
5613
5614     default:
5615         return OFPERR_OFPBIC_UNKNOWN_INST;
5616     }
5617 }
5618
5619 /* Two-way translation between OVS's internal "OVSINST_*" representation of
5620  * instructions and the "OFPIT_*" representation used in OpenFlow. */
5621 struct ovsinst_map {
5622     enum ovs_instruction_type ovsinst; /* Internal name for instruction. */
5623     int ofpit;                         /* OFPIT_* number from OpenFlow spec. */
5624 };
5625
5626 static const struct ovsinst_map *
5627 get_ovsinst_map(enum ofp_version version)
5628 {
5629     /* OpenFlow 1.1 and 1.2 instructions. */
5630     static const struct ovsinst_map of11[] = {
5631         { OVSINST_OFPIT11_GOTO_TABLE, 1 },
5632         { OVSINST_OFPIT11_WRITE_METADATA, 2 },
5633         { OVSINST_OFPIT11_WRITE_ACTIONS, 3 },
5634         { OVSINST_OFPIT11_APPLY_ACTIONS, 4 },
5635         { OVSINST_OFPIT11_CLEAR_ACTIONS, 5 },
5636         { 0, -1 },
5637     };
5638
5639     /* OpenFlow 1.3+ instructions. */
5640     static const struct ovsinst_map of13[] = {
5641         { OVSINST_OFPIT11_GOTO_TABLE, 1 },
5642         { OVSINST_OFPIT11_WRITE_METADATA, 2 },
5643         { OVSINST_OFPIT11_WRITE_ACTIONS, 3 },
5644         { OVSINST_OFPIT11_APPLY_ACTIONS, 4 },
5645         { OVSINST_OFPIT11_CLEAR_ACTIONS, 5 },
5646         { OVSINST_OFPIT13_METER, 6 },
5647         { 0, -1 },
5648     };
5649
5650     return version < OFP13_VERSION ? of11 : of13;
5651 }
5652
5653 /* Converts 'ovsinst_bitmap', a bitmap whose bits correspond to OVSINST_*
5654  * values, into a bitmap of instructions suitable for OpenFlow 'version'
5655  * (OFP11_VERSION or later), and returns the result. */
5656 ovs_be32
5657 ovsinst_bitmap_to_openflow(uint32_t ovsinst_bitmap, enum ofp_version version)
5658 {
5659     uint32_t ofpit_bitmap = 0;
5660     const struct ovsinst_map *x;
5661
5662     for (x = get_ovsinst_map(version); x->ofpit >= 0; x++) {
5663         if (ovsinst_bitmap & (1u << x->ovsinst)) {
5664             ofpit_bitmap |= 1u << x->ofpit;
5665         }
5666     }
5667     return htonl(ofpit_bitmap);
5668 }
5669
5670 /* Converts 'ofpit_bitmap', a bitmap of instructions from an OpenFlow message
5671  * with the given 'version' (OFP11_VERSION or later) into a bitmap whose bits
5672  * correspond to OVSINST_* values, and returns the result. */
5673 uint32_t
5674 ovsinst_bitmap_from_openflow(ovs_be32 ofpit_bitmap, enum ofp_version version)
5675 {
5676     uint32_t ovsinst_bitmap = 0;
5677     const struct ovsinst_map *x;
5678
5679     for (x = get_ovsinst_map(version); x->ofpit >= 0; x++) {
5680         if (ofpit_bitmap & htonl(1u << x->ofpit)) {
5681             ovsinst_bitmap |= 1u << x->ovsinst;
5682         }
5683     }
5684     return ovsinst_bitmap;
5685 }
5686
5687 static inline struct ofp11_instruction *
5688 instruction_next(const struct ofp11_instruction *inst)
5689 {
5690     return ((struct ofp11_instruction *) (void *)
5691             ((uint8_t *) inst + ntohs(inst->len)));
5692 }
5693
5694 static inline bool
5695 instruction_is_valid(const struct ofp11_instruction *inst,
5696                      size_t n_instructions)
5697 {
5698     uint16_t len = ntohs(inst->len);
5699     return (!(len % OFP11_INSTRUCTION_ALIGN)
5700             && len >= sizeof *inst
5701             && len / sizeof *inst <= n_instructions);
5702 }
5703
5704 /* This macro is careful to check for instructions with bad lengths. */
5705 #define INSTRUCTION_FOR_EACH(ITER, LEFT, INSTRUCTIONS, N_INSTRUCTIONS)  \
5706     for ((ITER) = (INSTRUCTIONS), (LEFT) = (N_INSTRUCTIONS);            \
5707          (LEFT) > 0 && instruction_is_valid(ITER, LEFT);                \
5708          ((LEFT) -= (ntohs((ITER)->len)                                 \
5709                      / sizeof(struct ofp11_instruction)),               \
5710           (ITER) = instruction_next(ITER)))
5711
5712 static enum ofperr
5713 decode_openflow11_instruction(const struct ofp11_instruction *inst,
5714                               enum ovs_instruction_type *type)
5715 {
5716     uint16_t len = ntohs(inst->len);
5717
5718     switch (inst->type) {
5719     case CONSTANT_HTONS(OFPIT11_EXPERIMENTER):
5720         return OFPERR_OFPBIC_BAD_EXPERIMENTER;
5721
5722 #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME)     \
5723         case CONSTANT_HTONS(ENUM):                      \
5724             if (EXTENSIBLE                              \
5725                 ? len >= sizeof(struct STRUCT)          \
5726                 : len == sizeof(struct STRUCT)) {       \
5727                 *type = OVSINST_##ENUM;                 \
5728                 return 0;                               \
5729             } else {                                    \
5730                 return OFPERR_OFPBIC_BAD_LEN;           \
5731             }
5732 OVS_INSTRUCTIONS
5733 #undef DEFINE_INST
5734
5735     default:
5736         return OFPERR_OFPBIC_UNKNOWN_INST;
5737     }
5738 }
5739
5740 static enum ofperr
5741 decode_openflow11_instructions(const struct ofp11_instruction insts[],
5742                                size_t n_insts,
5743                                const struct ofp11_instruction *out[])
5744 {
5745     const struct ofp11_instruction *inst;
5746     size_t left;
5747
5748     memset(out, 0, N_OVS_INSTRUCTIONS * sizeof *out);
5749     INSTRUCTION_FOR_EACH (inst, left, insts, n_insts) {
5750         enum ovs_instruction_type type;
5751         enum ofperr error;
5752
5753         error = decode_openflow11_instruction(inst, &type);
5754         if (error) {
5755             return error;
5756         }
5757
5758         if (out[type]) {
5759             return OFPERR_OFPBIC_DUP_INST;
5760         }
5761         out[type] = inst;
5762     }
5763
5764     if (left) {
5765         VLOG_WARN_RL(&rl, "bad instruction format at offset %"PRIuSIZE,
5766                      (n_insts - left) * sizeof *inst);
5767         return OFPERR_OFPBIC_BAD_LEN;
5768     }
5769     return 0;
5770 }
5771
5772 static void
5773 get_actions_from_instruction(const struct ofp11_instruction *inst,
5774                              const struct ofp_action_header **actions,
5775                              size_t *actions_len)
5776 {
5777     *actions = ALIGNED_CAST(const struct ofp_action_header *, inst + 1);
5778     *actions_len = ntohs(inst->len) - sizeof *inst;
5779 }
5780
5781 enum ofperr
5782 ofpacts_pull_openflow_instructions(struct ofpbuf *openflow,
5783                                    unsigned int instructions_len,
5784                                    enum ofp_version version,
5785                                    struct ofpbuf *ofpacts)
5786 {
5787     const struct ofp11_instruction *instructions;
5788     const struct ofp11_instruction *insts[N_OVS_INSTRUCTIONS];
5789     enum ofperr error;
5790
5791     if (version == OFP10_VERSION) {
5792         return ofpacts_pull_openflow_actions__(openflow, instructions_len,
5793                                                version,
5794                                                (1u << N_OVS_INSTRUCTIONS) - 1,
5795                                                ofpacts, 0);
5796     }
5797
5798     ofpbuf_clear(ofpacts);
5799
5800     if (instructions_len % OFP11_INSTRUCTION_ALIGN != 0) {
5801         VLOG_WARN_RL(&rl, "OpenFlow message instructions length %u is not a "
5802                      "multiple of %d",
5803                      instructions_len, OFP11_INSTRUCTION_ALIGN);
5804         error = OFPERR_OFPBIC_BAD_LEN;
5805         goto exit;
5806     }
5807
5808     instructions = ofpbuf_try_pull(openflow, instructions_len);
5809     if (instructions == NULL) {
5810         VLOG_WARN_RL(&rl, "OpenFlow message instructions length %u exceeds "
5811                      "remaining message length (%"PRIu32")",
5812                      instructions_len, openflow->size);
5813         error = OFPERR_OFPBIC_BAD_LEN;
5814         goto exit;
5815     }
5816
5817     error = decode_openflow11_instructions(
5818         instructions, instructions_len / OFP11_INSTRUCTION_ALIGN,
5819         insts);
5820     if (error) {
5821         goto exit;
5822     }
5823
5824     if (insts[OVSINST_OFPIT13_METER]) {
5825         const struct ofp13_instruction_meter *oim;
5826         struct ofpact_meter *om;
5827
5828         oim = ALIGNED_CAST(const struct ofp13_instruction_meter *,
5829                            insts[OVSINST_OFPIT13_METER]);
5830
5831         om = ofpact_put_METER(ofpacts);
5832         om->meter_id = ntohl(oim->meter_id);
5833     }
5834     if (insts[OVSINST_OFPIT11_APPLY_ACTIONS]) {
5835         const struct ofp_action_header *actions;
5836         size_t actions_len;
5837
5838         get_actions_from_instruction(insts[OVSINST_OFPIT11_APPLY_ACTIONS],
5839                                      &actions, &actions_len);
5840         error = ofpacts_decode(actions, actions_len, version, ofpacts);
5841         if (error) {
5842             goto exit;
5843         }
5844     }
5845     if (insts[OVSINST_OFPIT11_CLEAR_ACTIONS]) {
5846         instruction_get_OFPIT11_CLEAR_ACTIONS(
5847             insts[OVSINST_OFPIT11_CLEAR_ACTIONS]);
5848         ofpact_put_CLEAR_ACTIONS(ofpacts);
5849     }
5850     if (insts[OVSINST_OFPIT11_WRITE_ACTIONS]) {
5851         struct ofpact_nest *on;
5852         const struct ofp_action_header *actions;
5853         size_t actions_len;
5854         size_t start;
5855
5856         ofpact_pad(ofpacts);
5857         start = ofpacts->size;
5858         ofpact_put(ofpacts, OFPACT_WRITE_ACTIONS,
5859                    offsetof(struct ofpact_nest, actions));
5860         get_actions_from_instruction(insts[OVSINST_OFPIT11_WRITE_ACTIONS],
5861                                      &actions, &actions_len);
5862         error = ofpacts_decode_for_action_set(actions, actions_len,
5863                                               version, ofpacts);
5864         if (error) {
5865             goto exit;
5866         }
5867         on = ofpbuf_at_assert(ofpacts, start, sizeof *on);
5868         on->ofpact.len = ofpacts->size - start;
5869     }
5870     if (insts[OVSINST_OFPIT11_WRITE_METADATA]) {
5871         const struct ofp11_instruction_write_metadata *oiwm;
5872         struct ofpact_metadata *om;
5873
5874         oiwm = ALIGNED_CAST(const struct ofp11_instruction_write_metadata *,
5875                             insts[OVSINST_OFPIT11_WRITE_METADATA]);
5876
5877         om = ofpact_put_WRITE_METADATA(ofpacts);
5878         om->metadata = oiwm->metadata;
5879         om->mask = oiwm->metadata_mask;
5880     }
5881     if (insts[OVSINST_OFPIT11_GOTO_TABLE]) {
5882         const struct ofp11_instruction_goto_table *oigt;
5883         struct ofpact_goto_table *ogt;
5884
5885         oigt = instruction_get_OFPIT11_GOTO_TABLE(
5886             insts[OVSINST_OFPIT11_GOTO_TABLE]);
5887         ogt = ofpact_put_GOTO_TABLE(ofpacts);
5888         ogt->table_id = oigt->table_id;
5889     }
5890
5891     error = ofpacts_verify(ofpacts->data, ofpacts->size,
5892                            (1u << N_OVS_INSTRUCTIONS) - 1, 0);
5893 exit:
5894     if (error) {
5895         ofpbuf_clear(ofpacts);
5896     }
5897     return error;
5898 }
5899
5900 /* Update the length of the instruction that begins at offset 'ofs' within
5901  * 'openflow' and contains nested actions that extend to the end of 'openflow'.
5902  * If the instruction contains no nested actions, deletes it entirely. */
5903 static void
5904 ofpacts_update_instruction_actions(struct ofpbuf *openflow, size_t ofs)
5905 {
5906     struct ofp11_instruction_actions *oia;
5907
5908     oia = ofpbuf_at_assert(openflow, ofs, sizeof *oia);
5909     if (openflow->size > ofs + sizeof *oia) {
5910         oia->len = htons(openflow->size - ofs);
5911     } else {
5912         openflow->size = ofs;
5913     }
5914 }
5915 \f
5916 /* Checks that 'port' is a valid output port for OFPACT_OUTPUT, given that the
5917  * switch will never have more than 'max_ports' ports.  Returns 0 if 'port' is
5918  * valid, otherwise an OpenFlow error code. */
5919 enum ofperr
5920 ofpact_check_output_port(ofp_port_t port, ofp_port_t max_ports)
5921 {
5922     switch (port) {
5923     case OFPP_IN_PORT:
5924     case OFPP_TABLE:
5925     case OFPP_NORMAL:
5926     case OFPP_FLOOD:
5927     case OFPP_ALL:
5928     case OFPP_CONTROLLER:
5929     case OFPP_LOCAL:
5930         return 0;
5931
5932     case OFPP_NONE:
5933         return OFPERR_OFPBAC_BAD_OUT_PORT;
5934
5935     default:
5936         if (ofp_to_u16(port) < ofp_to_u16(max_ports)) {
5937             return 0;
5938         }
5939         return OFPERR_OFPBAC_BAD_OUT_PORT;
5940     }
5941 }
5942
5943 /* Removes the protocols that require consistency between match and actions
5944  * (that's everything but OpenFlow 1.0) from '*usable_protocols'.
5945  *
5946  * (An example of an inconsistency between match and actions is a flow that
5947  * does not match on an MPLS Ethertype but has an action that pops an MPLS
5948  * label.) */
5949 static void
5950 inconsistent_match(enum ofputil_protocol *usable_protocols)
5951 {
5952     *usable_protocols &= OFPUTIL_P_OF10_ANY;
5953 }
5954
5955 /* May modify flow->dl_type, flow->nw_proto and flow->vlan_tci,
5956  * caller must restore them.
5957  *
5958  * Modifies some actions, filling in fields that could not be properly set
5959  * without context. */
5960 static enum ofperr
5961 ofpact_check__(enum ofputil_protocol *usable_protocols, struct ofpact *a,
5962                struct flow *flow, ofp_port_t max_ports,
5963                uint8_t table_id, uint8_t n_tables)
5964 {
5965     const struct ofpact_enqueue *enqueue;
5966     const struct mf_field *mf;
5967
5968     switch (a->type) {
5969     case OFPACT_OUTPUT:
5970         return ofpact_check_output_port(ofpact_get_OUTPUT(a)->port,
5971                                         max_ports);
5972
5973     case OFPACT_CONTROLLER:
5974         return 0;
5975
5976     case OFPACT_ENQUEUE:
5977         enqueue = ofpact_get_ENQUEUE(a);
5978         if (ofp_to_u16(enqueue->port) >= ofp_to_u16(max_ports)
5979             && enqueue->port != OFPP_IN_PORT
5980             && enqueue->port != OFPP_LOCAL) {
5981             return OFPERR_OFPBAC_BAD_OUT_PORT;
5982         }
5983         return 0;
5984
5985     case OFPACT_OUTPUT_REG:
5986         return mf_check_src(&ofpact_get_OUTPUT_REG(a)->src, flow);
5987
5988     case OFPACT_BUNDLE:
5989         return bundle_check(ofpact_get_BUNDLE(a), max_ports, flow);
5990
5991     case OFPACT_SET_VLAN_VID:
5992         /* Remember if we saw a vlan tag in the flow to aid translating to
5993          * OpenFlow 1.1+ if need be. */
5994         ofpact_get_SET_VLAN_VID(a)->flow_has_vlan =
5995             (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI);
5996         if (!(flow->vlan_tci & htons(VLAN_CFI)) &&
5997             !ofpact_get_SET_VLAN_VID(a)->push_vlan_if_needed) {
5998             inconsistent_match(usable_protocols);
5999         }
6000         /* Temporary mark that we have a vlan tag. */
6001         flow->vlan_tci |= htons(VLAN_CFI);
6002         return 0;
6003
6004     case OFPACT_SET_VLAN_PCP:
6005         /* Remember if we saw a vlan tag in the flow to aid translating to
6006          * OpenFlow 1.1+ if need be. */
6007         ofpact_get_SET_VLAN_PCP(a)->flow_has_vlan =
6008             (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI);
6009         if (!(flow->vlan_tci & htons(VLAN_CFI)) &&
6010             !ofpact_get_SET_VLAN_PCP(a)->push_vlan_if_needed) {
6011             inconsistent_match(usable_protocols);
6012         }
6013         /* Temporary mark that we have a vlan tag. */
6014         flow->vlan_tci |= htons(VLAN_CFI);
6015         return 0;
6016
6017     case OFPACT_STRIP_VLAN:
6018         if (!(flow->vlan_tci & htons(VLAN_CFI))) {
6019             inconsistent_match(usable_protocols);
6020         }
6021         /* Temporary mark that we have no vlan tag. */
6022         flow->vlan_tci = htons(0);
6023         return 0;
6024
6025     case OFPACT_PUSH_VLAN:
6026         if (flow->vlan_tci & htons(VLAN_CFI)) {
6027             /* Multiple VLAN headers not supported. */
6028             return OFPERR_OFPBAC_BAD_TAG;
6029         }
6030         /* Temporary mark that we have a vlan tag. */
6031         flow->vlan_tci |= htons(VLAN_CFI);
6032         return 0;
6033
6034     case OFPACT_SET_ETH_SRC:
6035     case OFPACT_SET_ETH_DST:
6036         return 0;
6037
6038     case OFPACT_SET_IPV4_SRC:
6039     case OFPACT_SET_IPV4_DST:
6040         if (flow->dl_type != htons(ETH_TYPE_IP)) {
6041             inconsistent_match(usable_protocols);
6042         }
6043         return 0;
6044
6045     case OFPACT_SET_IP_DSCP:
6046     case OFPACT_SET_IP_ECN:
6047     case OFPACT_SET_IP_TTL:
6048     case OFPACT_DEC_TTL:
6049         if (!is_ip_any(flow)) {
6050             inconsistent_match(usable_protocols);
6051         }
6052         return 0;
6053
6054     case OFPACT_SET_L4_SRC_PORT:
6055     case OFPACT_SET_L4_DST_PORT:
6056         if (!is_ip_any(flow) || (flow->nw_frag & FLOW_NW_FRAG_LATER) ||
6057             (flow->nw_proto != IPPROTO_TCP && flow->nw_proto != IPPROTO_UDP
6058              && flow->nw_proto != IPPROTO_SCTP)) {
6059             inconsistent_match(usable_protocols);
6060         }
6061         /* Note on which transport protocol the port numbers are set.
6062          * This allows this set action to be converted to an OF1.2 set field
6063          * action. */
6064         if (a->type == OFPACT_SET_L4_SRC_PORT) {
6065             ofpact_get_SET_L4_SRC_PORT(a)->flow_ip_proto = flow->nw_proto;
6066         } else {
6067             ofpact_get_SET_L4_DST_PORT(a)->flow_ip_proto = flow->nw_proto;
6068         }
6069         return 0;
6070
6071     case OFPACT_REG_MOVE:
6072         return nxm_reg_move_check(ofpact_get_REG_MOVE(a), flow);
6073
6074     case OFPACT_SET_FIELD:
6075         mf = ofpact_get_SET_FIELD(a)->field;
6076         /* Require OXM_OF_VLAN_VID to have an existing VLAN header. */
6077         if (!mf_are_prereqs_ok(mf, flow) ||
6078             (mf->id == MFF_VLAN_VID && !(flow->vlan_tci & htons(VLAN_CFI)))) {
6079             VLOG_WARN_RL(&rl, "set_field %s lacks correct prerequisities",
6080                          mf->name);
6081             return OFPERR_OFPBAC_MATCH_INCONSISTENT;
6082         }
6083         /* Remember if we saw a vlan tag in the flow to aid translating to
6084          * OpenFlow 1.1 if need be. */
6085         ofpact_get_SET_FIELD(a)->flow_has_vlan =
6086             (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI);
6087         if (mf->id == MFF_VLAN_TCI) {
6088             /* The set field may add or remove the vlan tag,
6089              * Mark the status temporarily. */
6090             flow->vlan_tci = ofpact_get_SET_FIELD(a)->value.be16;
6091         }
6092         return 0;
6093
6094     case OFPACT_STACK_PUSH:
6095         return nxm_stack_push_check(ofpact_get_STACK_PUSH(a), flow);
6096
6097     case OFPACT_STACK_POP:
6098         return nxm_stack_pop_check(ofpact_get_STACK_POP(a), flow);
6099
6100     case OFPACT_SET_MPLS_LABEL:
6101     case OFPACT_SET_MPLS_TC:
6102     case OFPACT_SET_MPLS_TTL:
6103     case OFPACT_DEC_MPLS_TTL:
6104         if (!eth_type_mpls(flow->dl_type)) {
6105             inconsistent_match(usable_protocols);
6106         }
6107         return 0;
6108
6109     case OFPACT_SET_TUNNEL:
6110     case OFPACT_SET_QUEUE:
6111     case OFPACT_POP_QUEUE:
6112     case OFPACT_RESUBMIT:
6113         return 0;
6114
6115     case OFPACT_FIN_TIMEOUT:
6116         if (flow->nw_proto != IPPROTO_TCP) {
6117             inconsistent_match(usable_protocols);
6118         }
6119         return 0;
6120
6121     case OFPACT_LEARN:
6122         return learn_check(ofpact_get_LEARN(a), flow);
6123
6124     case OFPACT_CONJUNCTION:
6125         return 0;
6126
6127     case OFPACT_MULTIPATH:
6128         return multipath_check(ofpact_get_MULTIPATH(a), flow);
6129
6130     case OFPACT_NOTE:
6131     case OFPACT_EXIT:
6132         return 0;
6133
6134     case OFPACT_PUSH_MPLS:
6135         flow->dl_type = ofpact_get_PUSH_MPLS(a)->ethertype;
6136         /* The packet is now MPLS and the MPLS payload is opaque.
6137          * Thus nothing can be assumed about the network protocol.
6138          * Temporarily mark that we have no nw_proto. */
6139         flow->nw_proto = 0;
6140         return 0;
6141
6142     case OFPACT_POP_MPLS:
6143         if (!eth_type_mpls(flow->dl_type)) {
6144             inconsistent_match(usable_protocols);
6145         }
6146         flow->dl_type = ofpact_get_POP_MPLS(a)->ethertype;
6147         return 0;
6148
6149     case OFPACT_SAMPLE:
6150         return 0;
6151
6152     case OFPACT_CT: {
6153         struct ofpact_conntrack *oc = ofpact_get_CT(a);
6154         enum ofputil_protocol p = *usable_protocols;
6155
6156         if (!dl_type_is_ip_any(flow->dl_type)
6157             || (flow->ct_state & CS_INVALID && oc->flags & NX_CT_F_COMMIT)) {
6158             inconsistent_match(usable_protocols);
6159         }
6160
6161         if (oc->zone_src.field) {
6162             return mf_check_src(&oc->zone_src, flow);
6163         }
6164
6165         return ofpacts_check(oc->actions, ofpact_ct_get_action_len(oc),
6166                              flow, max_ports, table_id, n_tables, &p);
6167     }
6168
6169     case OFPACT_CLEAR_ACTIONS:
6170         return 0;
6171
6172     case OFPACT_WRITE_ACTIONS: {
6173         /* Use a temporary copy of 'usable_protocols' because we can't check
6174          * consistency of an action set. */
6175         struct ofpact_nest *on = ofpact_get_WRITE_ACTIONS(a);
6176         enum ofputil_protocol p = *usable_protocols;
6177         return ofpacts_check(on->actions, ofpact_nest_get_action_len(on),
6178                              flow, max_ports, table_id, n_tables, &p);
6179     }
6180
6181     case OFPACT_WRITE_METADATA:
6182         return 0;
6183
6184     case OFPACT_METER: {
6185         uint32_t mid = ofpact_get_METER(a)->meter_id;
6186         if (mid == 0 || mid > OFPM13_MAX) {
6187             return OFPERR_OFPMMFC_INVALID_METER;
6188         }
6189         return 0;
6190     }
6191
6192     case OFPACT_GOTO_TABLE: {
6193         uint8_t goto_table = ofpact_get_GOTO_TABLE(a)->table_id;
6194         if ((table_id != 255 && goto_table <= table_id)
6195             || (n_tables != 255 && goto_table >= n_tables)) {
6196             return OFPERR_OFPBIC_BAD_TABLE_ID;
6197         }
6198         return 0;
6199     }
6200
6201     case OFPACT_GROUP:
6202         return 0;
6203
6204     case OFPACT_UNROLL_XLATE:
6205         /* UNROLL is an internal action that should never be seen via
6206          * OpenFlow. */
6207         return OFPERR_OFPBAC_BAD_TYPE;
6208
6209     case OFPACT_DEBUG_RECIRC:
6210         return 0;
6211
6212     default:
6213         OVS_NOT_REACHED();
6214     }
6215 }
6216
6217 /* Checks that the 'ofpacts_len' bytes of actions in 'ofpacts' are
6218  * appropriate for a packet with the prerequisites satisfied by 'flow' in a
6219  * switch with no more than 'max_ports' ports.
6220  *
6221  * If 'ofpacts' and 'flow' are inconsistent with one another, un-sets in
6222  * '*usable_protocols' the protocols that forbid the inconsistency.  (An
6223  * example of an inconsistency between match and actions is a flow that does
6224  * not match on an MPLS Ethertype but has an action that pops an MPLS label.)
6225  *
6226  * May annotate ofpacts with information gathered from the 'flow'.
6227  *
6228  * May temporarily modify 'flow', but restores the changes before returning. */
6229 enum ofperr
6230 ofpacts_check(struct ofpact ofpacts[], size_t ofpacts_len,
6231               struct flow *flow, ofp_port_t max_ports,
6232               uint8_t table_id, uint8_t n_tables,
6233               enum ofputil_protocol *usable_protocols)
6234 {
6235     struct ofpact *a;
6236     ovs_be16 dl_type = flow->dl_type;
6237     ovs_be16 vlan_tci = flow->vlan_tci;
6238     uint8_t nw_proto = flow->nw_proto;
6239     enum ofperr error = 0;
6240
6241     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6242         error = ofpact_check__(usable_protocols, a, flow,
6243                                max_ports, table_id, n_tables);
6244         if (error) {
6245             break;
6246         }
6247     }
6248     /* Restore fields that may have been modified. */
6249     flow->dl_type = dl_type;
6250     flow->vlan_tci = vlan_tci;
6251     flow->nw_proto = nw_proto;
6252     return error;
6253 }
6254
6255 /* Like ofpacts_check(), but reports inconsistencies as
6256  * OFPERR_OFPBAC_MATCH_INCONSISTENT rather than clearing bits. */
6257 enum ofperr
6258 ofpacts_check_consistency(struct ofpact ofpacts[], size_t ofpacts_len,
6259                           struct flow *flow, ofp_port_t max_ports,
6260                           uint8_t table_id, uint8_t n_tables,
6261                           enum ofputil_protocol usable_protocols)
6262 {
6263     enum ofputil_protocol p = usable_protocols;
6264     enum ofperr error;
6265
6266     error = ofpacts_check(ofpacts, ofpacts_len, flow, max_ports,
6267                           table_id, n_tables, &p);
6268     return (error ? error
6269             : p != usable_protocols ? OFPERR_OFPBAC_MATCH_INCONSISTENT
6270             : 0);
6271 }
6272
6273 static const struct mf_field *
6274 ofpact_get_mf_field(enum ofpact_type type, const void *ofpact)
6275 {
6276     if (type == OFPACT_SET_FIELD) {
6277         const struct ofpact_set_field *orl = ofpact;
6278
6279         return orl->field;
6280     } else if (type == OFPACT_REG_MOVE) {
6281         const struct ofpact_reg_move *orm = ofpact;
6282
6283         return orm->dst.field;
6284     }
6285
6286     return NULL;
6287 }
6288
6289 static enum ofperr
6290 unsupported_nesting(enum ofpact_type action, enum ofpact_type outer_action)
6291 {
6292     VLOG_WARN("%s action doesn't support nested action %s",
6293               ofpact_name(outer_action), ofpact_name(action));
6294     return OFPERR_OFPBAC_BAD_ARGUMENT;
6295 }
6296
6297 static bool
6298 field_requires_ct(enum mf_field_id field)
6299 {
6300     return field == MFF_CT_MARK || field == MFF_CT_LABEL;
6301 }
6302
6303 /* Apply nesting constraints for actions */
6304 static enum ofperr
6305 ofpacts_verify_nested(const struct ofpact *a, enum ofpact_type outer_action)
6306 {
6307     const struct mf_field *field = ofpact_get_mf_field(a->type, a);
6308
6309     if (field && field_requires_ct(field->id) && outer_action != OFPACT_CT) {
6310         VLOG_WARN("cannot set CT fields outside of ct action");
6311         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
6312     }
6313
6314     if (outer_action) {
6315         ovs_assert(outer_action == OFPACT_WRITE_ACTIONS
6316                    || outer_action == OFPACT_CT);
6317
6318         if (outer_action == OFPACT_CT) {
6319             if (!field) {
6320                 return unsupported_nesting(a->type, outer_action);
6321             } else if (!field_requires_ct(field->id)) {
6322                 VLOG_WARN("%s action doesn't support nested modification "
6323                           "of %s", ofpact_name(outer_action), field->name);
6324                 return OFPERR_OFPBAC_BAD_ARGUMENT;
6325             }
6326         }
6327     }
6328
6329     return 0;
6330 }
6331
6332 /* Verifies that the 'ofpacts_len' bytes of actions in 'ofpacts' are in the
6333  * appropriate order as defined by the OpenFlow spec and as required by Open
6334  * vSwitch.
6335  *
6336  * 'allowed_ovsinsts' is a bitmap of OVSINST_* values, in which 1-bits indicate
6337  * instructions that are allowed within 'ofpacts[]'.
6338  *
6339  * If 'outer_action' is not zero, it specifies that the actions are nested
6340  * within another action of type 'outer_action'. */
6341 static enum ofperr
6342 ofpacts_verify(const struct ofpact ofpacts[], size_t ofpacts_len,
6343                uint32_t allowed_ovsinsts, enum ofpact_type outer_action)
6344 {
6345     const struct ofpact *a;
6346     enum ovs_instruction_type inst;
6347
6348     inst = OVSINST_OFPIT13_METER;
6349     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6350         enum ovs_instruction_type next;
6351         enum ofperr error;
6352
6353         if (a->type == OFPACT_CONJUNCTION) {
6354             OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6355                 if (a->type != OFPACT_CONJUNCTION && a->type != OFPACT_NOTE) {
6356                     VLOG_WARN("\"conjunction\" actions may be used along with "
6357                               "\"note\" but not any other kind of action "
6358                               "(such as the \"%s\" action used here)",
6359                               ofpact_name(a->type));
6360                     return OFPERR_NXBAC_BAD_CONJUNCTION;
6361                 }
6362             }
6363             return 0;
6364         }
6365
6366         error = ofpacts_verify_nested(a, outer_action);
6367         if (error) {
6368             return error;
6369         }
6370
6371         next = ovs_instruction_type_from_ofpact_type(a->type);
6372         if (a > ofpacts
6373             && (inst == OVSINST_OFPIT11_APPLY_ACTIONS
6374                 ? next < inst
6375                 : next <= inst)) {
6376             const char *name = ovs_instruction_name_from_type(inst);
6377             const char *next_name = ovs_instruction_name_from_type(next);
6378
6379             if (next == inst) {
6380                 VLOG_WARN("duplicate %s instruction not allowed, for OpenFlow "
6381                           "1.1+ compatibility", name);
6382             } else {
6383                 VLOG_WARN("invalid instruction ordering: %s must appear "
6384                           "before %s, for OpenFlow 1.1+ compatibility",
6385                           next_name, name);
6386             }
6387             return OFPERR_OFPBAC_UNSUPPORTED_ORDER;
6388         }
6389         if (!((1u << next) & allowed_ovsinsts)) {
6390             const char *name = ovs_instruction_name_from_type(next);
6391
6392             VLOG_WARN("%s instruction not allowed here", name);
6393             return OFPERR_OFPBIC_UNSUP_INST;
6394         }
6395
6396         inst = next;
6397     }
6398
6399     return 0;
6400 }
6401 \f
6402 /* Converting ofpacts to OpenFlow. */
6403
6404 static void
6405 encode_ofpact(const struct ofpact *a, enum ofp_version ofp_version,
6406               struct ofpbuf *out)
6407 {
6408     switch (a->type) {
6409 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                              \
6410         case OFPACT_##ENUM:                                             \
6411             encode_##ENUM(ofpact_get_##ENUM(a), ofp_version, out);      \
6412             return;
6413         OFPACTS
6414 #undef OFPACT
6415     default:
6416         OVS_NOT_REACHED();
6417     }
6418 }
6419
6420 /* Converts the 'ofpacts_len' bytes of ofpacts in 'ofpacts' into OpenFlow
6421  * actions in 'openflow', appending the actions to any existing data in
6422  * 'openflow'. */
6423 size_t
6424 ofpacts_put_openflow_actions(const struct ofpact ofpacts[], size_t ofpacts_len,
6425                              struct ofpbuf *openflow,
6426                              enum ofp_version ofp_version)
6427 {
6428     const struct ofpact *a;
6429     size_t start_size = openflow->size;
6430
6431     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6432         encode_ofpact(a, ofp_version, openflow);
6433     }
6434     return openflow->size - start_size;
6435 }
6436
6437 static enum ovs_instruction_type
6438 ofpact_is_apply_actions(const struct ofpact *a)
6439 {
6440     return (ovs_instruction_type_from_ofpact_type(a->type)
6441             == OVSINST_OFPIT11_APPLY_ACTIONS);
6442 }
6443
6444 void
6445 ofpacts_put_openflow_instructions(const struct ofpact ofpacts[],
6446                                   size_t ofpacts_len,
6447                                   struct ofpbuf *openflow,
6448                                   enum ofp_version ofp_version)
6449 {
6450     const struct ofpact *end = ofpact_end(ofpacts, ofpacts_len);
6451     const struct ofpact *a;
6452
6453     if (ofp_version == OFP10_VERSION) {
6454         ofpacts_put_openflow_actions(ofpacts, ofpacts_len, openflow,
6455                                      ofp_version);
6456         return;
6457     }
6458
6459     a = ofpacts;
6460     while (a < end) {
6461         if (ofpact_is_apply_actions(a)) {
6462             size_t ofs = openflow->size;
6463
6464             instruction_put_OFPIT11_APPLY_ACTIONS(openflow);
6465             do {
6466                 encode_ofpact(a, ofp_version, openflow);
6467                 a = ofpact_next(a);
6468             } while (a < end && ofpact_is_apply_actions(a));
6469             ofpacts_update_instruction_actions(openflow, ofs);
6470         } else {
6471             encode_ofpact(a, ofp_version, openflow);
6472             a = ofpact_next(a);
6473         }
6474     }
6475 }
6476 \f
6477 /* Sets of supported actions. */
6478
6479 /* Two-way translation between OVS's internal "OFPACT_*" representation of
6480  * actions and the "OFPAT_*" representation used in some OpenFlow version.
6481  * (OFPAT_* numbering varies from one OpenFlow version to another, so a given
6482  * instance is specific to one OpenFlow version.) */
6483 struct ofpact_map {
6484     enum ofpact_type ofpact;    /* Internal name for action type. */
6485     int ofpat;                  /* OFPAT_* number from OpenFlow spec. */
6486 };
6487
6488 static const struct ofpact_map *
6489 get_ofpact_map(enum ofp_version version)
6490 {
6491     /* OpenFlow 1.0 actions. */
6492     static const struct ofpact_map of10[] = {
6493         { OFPACT_OUTPUT, 0 },
6494         { OFPACT_SET_VLAN_VID, 1 },
6495         { OFPACT_SET_VLAN_PCP, 2 },
6496         { OFPACT_STRIP_VLAN, 3 },
6497         { OFPACT_SET_ETH_SRC, 4 },
6498         { OFPACT_SET_ETH_DST, 5 },
6499         { OFPACT_SET_IPV4_SRC, 6 },
6500         { OFPACT_SET_IPV4_DST, 7 },
6501         { OFPACT_SET_IP_DSCP, 8 },
6502         { OFPACT_SET_L4_SRC_PORT, 9 },
6503         { OFPACT_SET_L4_DST_PORT, 10 },
6504         { OFPACT_ENQUEUE, 11 },
6505         { 0, -1 },
6506     };
6507
6508     /* OpenFlow 1.1 actions. */
6509     static const struct ofpact_map of11[] = {
6510         { OFPACT_OUTPUT, 0 },
6511         { OFPACT_SET_VLAN_VID, 1 },
6512         { OFPACT_SET_VLAN_PCP, 2 },
6513         { OFPACT_SET_ETH_SRC, 3 },
6514         { OFPACT_SET_ETH_DST, 4 },
6515         { OFPACT_SET_IPV4_SRC, 5 },
6516         { OFPACT_SET_IPV4_DST, 6 },
6517         { OFPACT_SET_IP_DSCP, 7 },
6518         { OFPACT_SET_IP_ECN, 8 },
6519         { OFPACT_SET_L4_SRC_PORT, 9 },
6520         { OFPACT_SET_L4_DST_PORT, 10 },
6521         /* OFPAT_COPY_TTL_OUT (11) not supported. */
6522         /* OFPAT_COPY_TTL_IN (12) not supported. */
6523         { OFPACT_SET_MPLS_LABEL, 13 },
6524         { OFPACT_SET_MPLS_TC, 14 },
6525         { OFPACT_SET_MPLS_TTL, 15 },
6526         { OFPACT_DEC_MPLS_TTL, 16 },
6527         { OFPACT_PUSH_VLAN, 17 },
6528         { OFPACT_STRIP_VLAN, 18 },
6529         { OFPACT_PUSH_MPLS, 19 },
6530         { OFPACT_POP_MPLS, 20 },
6531         { OFPACT_SET_QUEUE, 21 },
6532         { OFPACT_GROUP, 22 },
6533         { OFPACT_SET_IP_TTL, 23 },
6534         { OFPACT_DEC_TTL, 24 },
6535         { 0, -1 },
6536     };
6537
6538     /* OpenFlow 1.2, 1.3, and 1.4 actions. */
6539     static const struct ofpact_map of12[] = {
6540         { OFPACT_OUTPUT, 0 },
6541         /* OFPAT_COPY_TTL_OUT (11) not supported. */
6542         /* OFPAT_COPY_TTL_IN (12) not supported. */
6543         { OFPACT_SET_MPLS_TTL, 15 },
6544         { OFPACT_DEC_MPLS_TTL, 16 },
6545         { OFPACT_PUSH_VLAN, 17 },
6546         { OFPACT_STRIP_VLAN, 18 },
6547         { OFPACT_PUSH_MPLS, 19 },
6548         { OFPACT_POP_MPLS, 20 },
6549         { OFPACT_SET_QUEUE, 21 },
6550         { OFPACT_GROUP, 22 },
6551         { OFPACT_SET_IP_TTL, 23 },
6552         { OFPACT_DEC_TTL, 24 },
6553         { OFPACT_SET_FIELD, 25 },
6554         /* OF1.3+ OFPAT_PUSH_PBB (26) not supported. */
6555         /* OF1.3+ OFPAT_POP_PBB (27) not supported. */
6556         { 0, -1 },
6557     };
6558
6559     switch (version) {
6560     case OFP10_VERSION:
6561         return of10;
6562
6563     case OFP11_VERSION:
6564         return of11;
6565
6566     case OFP12_VERSION:
6567     case OFP13_VERSION:
6568     case OFP14_VERSION:
6569     case OFP15_VERSION:
6570     default:
6571         return of12;
6572     }
6573 }
6574
6575 /* Converts 'ofpacts_bitmap', a bitmap whose bits correspond to OFPACT_*
6576  * values, into a bitmap of actions suitable for OpenFlow 'version', and
6577  * returns the result. */
6578 ovs_be32
6579 ofpact_bitmap_to_openflow(uint64_t ofpacts_bitmap, enum ofp_version version)
6580 {
6581     uint32_t openflow_bitmap = 0;
6582     const struct ofpact_map *x;
6583
6584     for (x = get_ofpact_map(version); x->ofpat >= 0; x++) {
6585         if (ofpacts_bitmap & (UINT64_C(1) << x->ofpact)) {
6586             openflow_bitmap |= 1u << x->ofpat;
6587         }
6588     }
6589     return htonl(openflow_bitmap);
6590 }
6591
6592 /* Converts 'ofpat_bitmap', a bitmap of actions from an OpenFlow message with
6593  * the given 'version' into a bitmap whose bits correspond to OFPACT_* values,
6594  * and returns the result. */
6595 uint64_t
6596 ofpact_bitmap_from_openflow(ovs_be32 ofpat_bitmap, enum ofp_version version)
6597 {
6598     uint64_t ofpact_bitmap = 0;
6599     const struct ofpact_map *x;
6600
6601     for (x = get_ofpact_map(version); x->ofpat >= 0; x++) {
6602         if (ofpat_bitmap & htonl(1u << x->ofpat)) {
6603             ofpact_bitmap |= UINT64_C(1) << x->ofpact;
6604         }
6605     }
6606     return ofpact_bitmap;
6607 }
6608
6609 /* Appends to 's' a string representation of the set of OFPACT_* represented
6610  * by 'ofpacts_bitmap'. */
6611 void
6612 ofpact_bitmap_format(uint64_t ofpacts_bitmap, struct ds *s)
6613 {
6614     if (!ofpacts_bitmap) {
6615         ds_put_cstr(s, "<none>");
6616     } else {
6617         while (ofpacts_bitmap) {
6618             ds_put_format(s, "%s ",
6619                           ofpact_name(rightmost_1bit_idx(ofpacts_bitmap)));
6620             ofpacts_bitmap = zero_rightmost_1bit(ofpacts_bitmap);
6621         }
6622         ds_chomp(s, ' ');
6623     }
6624 }
6625 \f
6626 /* Returns true if 'action' outputs to 'port', false otherwise. */
6627 static bool
6628 ofpact_outputs_to_port(const struct ofpact *ofpact, ofp_port_t port)
6629 {
6630     switch (ofpact->type) {
6631     case OFPACT_OUTPUT:
6632         return ofpact_get_OUTPUT(ofpact)->port == port;
6633     case OFPACT_ENQUEUE:
6634         return ofpact_get_ENQUEUE(ofpact)->port == port;
6635     case OFPACT_CONTROLLER:
6636         return port == OFPP_CONTROLLER;
6637
6638     case OFPACT_OUTPUT_REG:
6639     case OFPACT_BUNDLE:
6640     case OFPACT_SET_VLAN_VID:
6641     case OFPACT_SET_VLAN_PCP:
6642     case OFPACT_STRIP_VLAN:
6643     case OFPACT_PUSH_VLAN:
6644     case OFPACT_SET_ETH_SRC:
6645     case OFPACT_SET_ETH_DST:
6646     case OFPACT_SET_IPV4_SRC:
6647     case OFPACT_SET_IPV4_DST:
6648     case OFPACT_SET_IP_DSCP:
6649     case OFPACT_SET_IP_ECN:
6650     case OFPACT_SET_IP_TTL:
6651     case OFPACT_SET_L4_SRC_PORT:
6652     case OFPACT_SET_L4_DST_PORT:
6653     case OFPACT_REG_MOVE:
6654     case OFPACT_SET_FIELD:
6655     case OFPACT_STACK_PUSH:
6656     case OFPACT_STACK_POP:
6657     case OFPACT_DEC_TTL:
6658     case OFPACT_SET_MPLS_LABEL:
6659     case OFPACT_SET_MPLS_TC:
6660     case OFPACT_SET_MPLS_TTL:
6661     case OFPACT_DEC_MPLS_TTL:
6662     case OFPACT_SET_TUNNEL:
6663     case OFPACT_WRITE_METADATA:
6664     case OFPACT_SET_QUEUE:
6665     case OFPACT_POP_QUEUE:
6666     case OFPACT_FIN_TIMEOUT:
6667     case OFPACT_RESUBMIT:
6668     case OFPACT_LEARN:
6669     case OFPACT_CONJUNCTION:
6670     case OFPACT_MULTIPATH:
6671     case OFPACT_NOTE:
6672     case OFPACT_EXIT:
6673     case OFPACT_UNROLL_XLATE:
6674     case OFPACT_PUSH_MPLS:
6675     case OFPACT_POP_MPLS:
6676     case OFPACT_SAMPLE:
6677     case OFPACT_CLEAR_ACTIONS:
6678     case OFPACT_WRITE_ACTIONS:
6679     case OFPACT_GOTO_TABLE:
6680     case OFPACT_METER:
6681     case OFPACT_GROUP:
6682     case OFPACT_DEBUG_RECIRC:
6683     case OFPACT_CT:
6684     default:
6685         return false;
6686     }
6687 }
6688
6689 /* Returns true if any action in the 'ofpacts_len' bytes of 'ofpacts' outputs
6690  * to 'port', false otherwise. */
6691 bool
6692 ofpacts_output_to_port(const struct ofpact *ofpacts, size_t ofpacts_len,
6693                        ofp_port_t port)
6694 {
6695     const struct ofpact *a;
6696
6697     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6698         if (ofpact_outputs_to_port(a, port)) {
6699             return true;
6700         }
6701     }
6702
6703     return false;
6704 }
6705
6706 /* Returns true if any action in the 'ofpacts_len' bytes of 'ofpacts' outputs
6707  * to 'group', false otherwise. */
6708 bool
6709 ofpacts_output_to_group(const struct ofpact *ofpacts, size_t ofpacts_len,
6710                         uint32_t group_id)
6711 {
6712     const struct ofpact *a;
6713
6714     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6715         if (a->type == OFPACT_GROUP
6716             && ofpact_get_GROUP(a)->group_id == group_id) {
6717             return true;
6718         }
6719     }
6720
6721     return false;
6722 }
6723
6724 bool
6725 ofpacts_equal(const struct ofpact *a, size_t a_len,
6726               const struct ofpact *b, size_t b_len)
6727 {
6728     return a_len == b_len && !memcmp(a, b, a_len);
6729 }
6730
6731 /* Finds the OFPACT_METER action, if any, in the 'ofpacts_len' bytes of
6732  * 'ofpacts'.  If found, returns its meter ID; if not, returns 0.
6733  *
6734  * This function relies on the order of 'ofpacts' being correct (as checked by
6735  * ofpacts_verify()). */
6736 uint32_t
6737 ofpacts_get_meter(const struct ofpact ofpacts[], size_t ofpacts_len)
6738 {
6739     const struct ofpact *a;
6740
6741     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6742         enum ovs_instruction_type inst;
6743
6744         inst = ovs_instruction_type_from_ofpact_type(a->type);
6745         if (a->type == OFPACT_METER) {
6746             return ofpact_get_METER(a)->meter_id;
6747         } else if (inst > OVSINST_OFPIT13_METER) {
6748             break;
6749         }
6750     }
6751
6752     return 0;
6753 }
6754 \f
6755 /* Formatting ofpacts. */
6756
6757 static void
6758 ofpact_format(const struct ofpact *a, struct ds *s)
6759 {
6760     switch (a->type) {
6761 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                              \
6762         case OFPACT_##ENUM:                                             \
6763             format_##ENUM(ALIGNED_CAST(const struct STRUCT *, a), s);   \
6764             break;
6765         OFPACTS
6766 #undef OFPACT
6767     default:
6768         OVS_NOT_REACHED();
6769     }
6770 }
6771
6772 /* Appends a string representing the 'ofpacts_len' bytes of ofpacts in
6773  * 'ofpacts' to 'string'. */
6774 void
6775 ofpacts_format(const struct ofpact *ofpacts, size_t ofpacts_len,
6776                struct ds *string)
6777 {
6778     if (!ofpacts_len) {
6779         ds_put_cstr(string, "drop");
6780     } else {
6781         const struct ofpact *a;
6782
6783         OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6784             if (a != ofpacts) {
6785                 ds_put_cstr(string, ",");
6786             }
6787
6788             /* XXX write-actions */
6789             ofpact_format(a, string);
6790         }
6791     }
6792 }
6793 \f
6794 /* Internal use by helpers. */
6795
6796 void *
6797 ofpact_put(struct ofpbuf *ofpacts, enum ofpact_type type, size_t len)
6798 {
6799     struct ofpact *ofpact;
6800
6801     ofpact_pad(ofpacts);
6802     ofpacts->header = ofpbuf_put_uninit(ofpacts, len);
6803     ofpact = ofpacts->header;
6804     ofpact_init(ofpact, type, len);
6805     return ofpact;
6806 }
6807
6808 void
6809 ofpact_init(struct ofpact *ofpact, enum ofpact_type type, size_t len)
6810 {
6811     memset(ofpact, 0, len);
6812     ofpact->type = type;
6813     ofpact->raw = -1;
6814     ofpact->len = len;
6815 }
6816 \f
6817 /* Updates 'ofpact->len' to the number of bytes in the tail of 'ofpacts'
6818  * starting at 'ofpact'.
6819  *
6820  * This is the correct way to update a variable-length ofpact's length after
6821  * adding the variable-length part of the payload.  (See the large comment
6822  * near the end of ofp-actions.h for more information.) */
6823 void
6824 ofpact_update_len(struct ofpbuf *ofpacts, struct ofpact *ofpact)
6825 {
6826     ovs_assert(ofpact == ofpacts->header);
6827     ofpact->len = (char *) ofpbuf_tail(ofpacts) - (char *) ofpact;
6828 }
6829
6830 /* Pads out 'ofpacts' to a multiple of OFPACT_ALIGNTO bytes in length.  Each
6831  * ofpact_put_<ENUM>() calls this function automatically beforehand, but the
6832  * client must call this itself after adding the final ofpact to an array of
6833  * them.
6834  *
6835  * (The consequences of failing to call this function are probably not dire.
6836  * OFPACT_FOR_EACH will calculate a pointer beyond the end of the ofpacts, but
6837  * not dereference it.  That's undefined behavior, technically, but it will not
6838  * cause a real problem on common systems.  Still, it seems better to call
6839  * it.) */
6840 void
6841 ofpact_pad(struct ofpbuf *ofpacts)
6842 {
6843     unsigned int pad = PAD_SIZE(ofpacts->size, OFPACT_ALIGNTO);
6844     if (pad) {
6845         ofpbuf_put_zeros(ofpacts, pad);
6846     }
6847 }
6848 \f
6849
6850
6851
6852 static char * OVS_WARN_UNUSED_RESULT
6853 ofpact_parse(enum ofpact_type type, char *value, struct ofpbuf *ofpacts,
6854              enum ofputil_protocol *usable_protocols)
6855 {
6856     switch (type) {
6857 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                            \
6858         case OFPACT_##ENUM:                                             \
6859             return parse_##ENUM(value, ofpacts, usable_protocols);
6860         OFPACTS
6861 #undef OFPACT
6862     default:
6863         OVS_NOT_REACHED();
6864     }
6865 }
6866
6867 static bool
6868 ofpact_type_from_name(const char *name, enum ofpact_type *type)
6869 {
6870 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                            \
6871     if (!strcasecmp(name, NAME)) {                                    \
6872         *type = OFPACT_##ENUM;                                          \
6873         return true;                                                    \
6874     }
6875     OFPACTS
6876 #undef OFPACT
6877
6878     return false;
6879 }
6880
6881 /* Parses 'str' as a series of instructions, and appends them to 'ofpacts'.
6882  *
6883  * Returns NULL if successful, otherwise a malloc()'d string describing the
6884  * error.  The caller is responsible for freeing the returned string.
6885  *
6886  * If 'outer_action' is specified, indicates that the actions being parsed
6887  * are nested within another action of the type specified in 'outer_action'. */
6888 static char * OVS_WARN_UNUSED_RESULT
6889 ofpacts_parse__(char *str, struct ofpbuf *ofpacts,
6890                 enum ofputil_protocol *usable_protocols,
6891                 bool allow_instructions, enum ofpact_type outer_action)
6892 {
6893     int prev_inst = -1;
6894     enum ofperr retval;
6895     char *key, *value;
6896     bool drop = false;
6897     char *pos;
6898
6899     pos = str;
6900     while (ofputil_parse_key_value(&pos, &key, &value)) {
6901         enum ovs_instruction_type inst = OVSINST_OFPIT11_APPLY_ACTIONS;
6902         enum ofpact_type type;
6903         char *error = NULL;
6904         ofp_port_t port;
6905
6906         if (ofpact_type_from_name(key, &type)) {
6907             error = ofpact_parse(type, value, ofpacts, usable_protocols);
6908             inst = ovs_instruction_type_from_ofpact_type(type);
6909         } else if (!strcasecmp(key, "mod_vlan_vid")) {
6910             error = parse_set_vlan_vid(value, ofpacts, true);
6911         } else if (!strcasecmp(key, "mod_vlan_pcp")) {
6912             error = parse_set_vlan_pcp(value, ofpacts, true);
6913         } else if (!strcasecmp(key, "set_nw_ttl")) {
6914             error = parse_SET_IP_TTL(value, ofpacts, usable_protocols);
6915         } else if (!strcasecmp(key, "pop_vlan")) {
6916             error = parse_pop_vlan(ofpacts);
6917         } else if (!strcasecmp(key, "set_tunnel64")) {
6918             error = parse_set_tunnel(value, ofpacts,
6919                                      NXAST_RAW_SET_TUNNEL64);
6920         } else if (!strcasecmp(key, "load")) {
6921             error = parse_reg_load(value, ofpacts);
6922         } else if (!strcasecmp(key, "bundle_load")) {
6923             error = parse_bundle_load(value, ofpacts);
6924         } else if (!strcasecmp(key, "drop")) {
6925             drop = true;
6926         } else if (!strcasecmp(key, "apply_actions")) {
6927             return xstrdup("apply_actions is the default instruction");
6928         } else if (ofputil_port_from_string(key, &port)) {
6929             ofpact_put_OUTPUT(ofpacts)->port = port;
6930         } else {
6931             return xasprintf("unknown action %s", key);
6932         }
6933         if (error) {
6934             return error;
6935         }
6936
6937         if (inst != OVSINST_OFPIT11_APPLY_ACTIONS) {
6938             if (!allow_instructions) {
6939                 return xasprintf("only actions are allowed here (not "
6940                                  "instruction %s)",
6941                                  ovs_instruction_name_from_type(inst));
6942             }
6943             if (inst == prev_inst) {
6944                 return xasprintf("instruction %s may be specified only once",
6945                                  ovs_instruction_name_from_type(inst));
6946             }
6947         }
6948         if (prev_inst != -1 && inst < prev_inst) {
6949             return xasprintf("instruction %s must be specified before %s",
6950                              ovs_instruction_name_from_type(inst),
6951                              ovs_instruction_name_from_type(prev_inst));
6952         }
6953         prev_inst = inst;
6954     }
6955     ofpact_pad(ofpacts);
6956
6957     if (drop && ofpacts->size) {
6958         return xstrdup("\"drop\" must not be accompanied by any other action "
6959                        "or instruction");
6960     }
6961
6962     retval = ofpacts_verify(ofpacts->data, ofpacts->size,
6963                             (allow_instructions
6964                              ? (1u << N_OVS_INSTRUCTIONS) - 1
6965                              : 1u << OVSINST_OFPIT11_APPLY_ACTIONS),
6966                             outer_action);
6967     if (retval) {
6968         return xstrdup("Incorrect instruction ordering");
6969     }
6970
6971     return NULL;
6972 }
6973
6974 static char * OVS_WARN_UNUSED_RESULT
6975 ofpacts_parse(char *str, struct ofpbuf *ofpacts,
6976               enum ofputil_protocol *usable_protocols, bool allow_instructions,
6977               enum ofpact_type outer_action)
6978 {
6979     uint32_t orig_size = ofpacts->size;
6980     char *error = ofpacts_parse__(str, ofpacts, usable_protocols,
6981                                   allow_instructions, outer_action);
6982     if (error) {
6983         ofpacts->size = orig_size;
6984     }
6985     return error;
6986 }
6987
6988 static char * OVS_WARN_UNUSED_RESULT
6989 ofpacts_parse_copy(const char *s_, struct ofpbuf *ofpacts,
6990                    enum ofputil_protocol *usable_protocols,
6991                    bool allow_instructions, enum ofpact_type outer_action)
6992 {
6993     char *error, *s;
6994
6995     *usable_protocols = OFPUTIL_P_ANY;
6996
6997     s = xstrdup(s_);
6998     error = ofpacts_parse(s, ofpacts, usable_protocols, allow_instructions,
6999                           outer_action);
7000     free(s);
7001
7002     return error;
7003 }
7004
7005 /* Parses 's' as a set of OpenFlow actions and appends the actions to
7006  * 'ofpacts'. 'outer_action', if nonzero, specifies that 's' contains actions
7007  * that are nested within the action of type 'outer_action'.
7008  *
7009  * Returns NULL if successful, otherwise a malloc()'d string describing the
7010  * error.  The caller is responsible for freeing the returned string. */
7011 char * OVS_WARN_UNUSED_RESULT
7012 ofpacts_parse_actions(const char *s, struct ofpbuf *ofpacts,
7013                       enum ofputil_protocol *usable_protocols)
7014 {
7015     return ofpacts_parse_copy(s, ofpacts, usable_protocols, false, 0);
7016 }
7017
7018 /* Parses 's' as a set of OpenFlow instructions and appends the instructions to
7019  * 'ofpacts'.
7020  *
7021  * Returns NULL if successful, otherwise a malloc()'d string describing the
7022  * error.  The caller is responsible for freeing the returned string. */
7023 char * OVS_WARN_UNUSED_RESULT
7024 ofpacts_parse_instructions(const char *s, struct ofpbuf *ofpacts,
7025                            enum ofputil_protocol *usable_protocols)
7026 {
7027     return ofpacts_parse_copy(s, ofpacts, usable_protocols, true, 0);
7028 }
7029
7030 const char *
7031 ofpact_name(enum ofpact_type type)
7032 {
7033     switch (type) {
7034 #define OFPACT(ENUM, STRUCT, MEMBER, NAME) case OFPACT_##ENUM: return NAME;
7035         OFPACTS
7036 #undef OFPACT
7037     }
7038     return "<unknown>";
7039 }
7040 \f
7041 /* Low-level action decoding and encoding functions. */
7042
7043 /* Everything needed to identify a particular OpenFlow action. */
7044 struct ofpact_hdrs {
7045     uint32_t vendor;              /* 0 if standard, otherwise a vendor code. */
7046     uint16_t type;                /* Type if standard, otherwise subtype. */
7047     uint8_t ofp_version;          /* From ofp_header. */
7048 };
7049
7050 /* Information about a particular OpenFlow action. */
7051 struct ofpact_raw_instance {
7052     /* The action's identity. */
7053     struct ofpact_hdrs hdrs;
7054     enum ofp_raw_action_type raw;
7055
7056     /* Looking up the action. */
7057     struct hmap_node decode_node; /* Based on 'hdrs'. */
7058     struct hmap_node encode_node; /* Based on 'raw' + 'hdrs.ofp_version'. */
7059
7060     /* The action's encoded size.
7061      *
7062      * If this action is fixed-length, 'min_length' == 'max_length'.
7063      * If it is variable length, then 'max_length' is ROUND_DOWN(UINT16_MAX,
7064      * OFP_ACTION_ALIGN) == 65528. */
7065     unsigned short int min_length;
7066     unsigned short int max_length;
7067
7068     /* For actions with a simple integer numeric argument, 'arg_ofs' is the
7069      * offset of that argument from the beginning of the action and 'arg_len'
7070      * its length, both in bytes.
7071      *
7072      * For actions that take other forms, these are both zero. */
7073     unsigned short int arg_ofs;
7074     unsigned short int arg_len;
7075
7076     /* The name of the action, e.g. "OFPAT_OUTPUT" or "NXAST_RESUBMIT". */
7077     const char *name;
7078
7079     /* If this action is deprecated, a human-readable string with a brief
7080      * explanation. */
7081     const char *deprecation;
7082 };
7083
7084 /* Action header. */
7085 struct ofp_action_header {
7086     /* The meaning of other values of 'type' generally depends on the OpenFlow
7087      * version (see enum ofp_raw_action_type).
7088      *
7089      * Across all OpenFlow versions, OFPAT_VENDOR indicates that 'vendor'
7090      * designates an OpenFlow vendor ID and that the remainder of the action
7091      * structure has a vendor-defined meaning.
7092      */
7093 #define OFPAT_VENDOR 0xffff
7094     ovs_be16 type;
7095
7096     /* Always a multiple of 8. */
7097     ovs_be16 len;
7098
7099     /* For type == OFPAT_VENDOR only, this is a vendor ID, e.g. NX_VENDOR_ID or
7100      * ONF_VENDOR_ID.  Other 'type's use this space for some other purpose. */
7101     ovs_be32 vendor;
7102 };
7103 OFP_ASSERT(sizeof(struct ofp_action_header) == 8);
7104
7105 /* Header for Nicira-defined actions and for ONF vendor extensions.
7106  *
7107  * This cannot be used as an entirely generic vendor extension action header,
7108  * because OpenFlow does not specify the location or size of the action
7109  * subtype; it just happens that ONF extensions and Nicira extensions share
7110  * this format. */
7111 struct ext_action_header {
7112     ovs_be16 type;                  /* OFPAT_VENDOR. */
7113     ovs_be16 len;                   /* At least 16. */
7114     ovs_be32 vendor;                /* NX_VENDOR_ID or ONF_VENDOR_ID. */
7115     ovs_be16 subtype;               /* See enum ofp_raw_action_type. */
7116     uint8_t pad[6];
7117 };
7118 OFP_ASSERT(sizeof(struct ext_action_header) == 16);
7119
7120 static bool
7121 ofpact_hdrs_equal(const struct ofpact_hdrs *a,
7122                   const struct ofpact_hdrs *b)
7123 {
7124     return (a->vendor == b->vendor
7125             && a->type == b->type
7126             && a->ofp_version == b->ofp_version);
7127 }
7128
7129 static uint32_t
7130 ofpact_hdrs_hash(const struct ofpact_hdrs *hdrs)
7131 {
7132     return hash_2words(hdrs->vendor, (hdrs->type << 16) | hdrs->ofp_version);
7133 }
7134
7135 #include "ofp-actions.inc2"
7136
7137 static struct hmap *
7138 ofpact_decode_hmap(void)
7139 {
7140     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
7141     static struct hmap hmap;
7142
7143     if (ovsthread_once_start(&once)) {
7144         struct ofpact_raw_instance *inst;
7145
7146         hmap_init(&hmap);
7147         for (inst = all_raw_instances;
7148              inst < &all_raw_instances[ARRAY_SIZE(all_raw_instances)];
7149              inst++) {
7150             hmap_insert(&hmap, &inst->decode_node,
7151                         ofpact_hdrs_hash(&inst->hdrs));
7152         }
7153         ovsthread_once_done(&once);
7154     }
7155     return &hmap;
7156 }
7157
7158 static struct hmap *
7159 ofpact_encode_hmap(void)
7160 {
7161     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
7162     static struct hmap hmap;
7163
7164     if (ovsthread_once_start(&once)) {
7165         struct ofpact_raw_instance *inst;
7166
7167         hmap_init(&hmap);
7168         for (inst = all_raw_instances;
7169              inst < &all_raw_instances[ARRAY_SIZE(all_raw_instances)];
7170              inst++) {
7171             hmap_insert(&hmap, &inst->encode_node,
7172                         hash_2words(inst->raw, inst->hdrs.ofp_version));
7173         }
7174         ovsthread_once_done(&once);
7175     }
7176     return &hmap;
7177 }
7178
7179 static enum ofperr
7180 ofpact_decode_raw(enum ofp_version ofp_version,
7181                   const struct ofp_action_header *oah, size_t length,
7182                   const struct ofpact_raw_instance **instp)
7183 {
7184     const struct ofpact_raw_instance *inst;
7185     struct ofpact_hdrs hdrs;
7186
7187     *instp = NULL;
7188     if (length < sizeof *oah) {
7189         return OFPERR_OFPBAC_BAD_LEN;
7190     }
7191
7192     /* Get base action type. */
7193     if (oah->type == htons(OFPAT_VENDOR)) {
7194         /* Get vendor. */
7195         hdrs.vendor = ntohl(oah->vendor);
7196         if (hdrs.vendor == NX_VENDOR_ID || hdrs.vendor == ONF_VENDOR_ID) {
7197             /* Get extension subtype. */
7198             const struct ext_action_header *nah;
7199
7200             nah = ALIGNED_CAST(const struct ext_action_header *, oah);
7201             if (length < sizeof *nah) {
7202                 return OFPERR_OFPBAC_BAD_LEN;
7203             }
7204             hdrs.type = ntohs(nah->subtype);
7205         } else {
7206             VLOG_WARN_RL(&rl, "OpenFlow action has unknown vendor %#"PRIx32,
7207                          hdrs.vendor);
7208             return OFPERR_OFPBAC_BAD_VENDOR;
7209         }
7210     } else {
7211         hdrs.vendor = 0;
7212         hdrs.type = ntohs(oah->type);
7213     }
7214
7215     hdrs.ofp_version = ofp_version;
7216     HMAP_FOR_EACH_WITH_HASH (inst, decode_node, ofpact_hdrs_hash(&hdrs),
7217                              ofpact_decode_hmap()) {
7218         if (ofpact_hdrs_equal(&hdrs, &inst->hdrs)) {
7219             *instp = inst;
7220             return 0;
7221         }
7222     }
7223
7224     return (hdrs.vendor
7225             ? OFPERR_OFPBAC_BAD_VENDOR_TYPE
7226             : OFPERR_OFPBAC_BAD_TYPE);
7227 }
7228
7229 static enum ofperr
7230 ofpact_pull_raw(struct ofpbuf *buf, enum ofp_version ofp_version,
7231                 enum ofp_raw_action_type *raw, uint64_t *arg)
7232 {
7233     const struct ofp_action_header *oah = buf->data;
7234     const struct ofpact_raw_instance *action;
7235     unsigned int length;
7236     enum ofperr error;
7237
7238     *raw = *arg = 0;
7239     error = ofpact_decode_raw(ofp_version, oah, buf->size, &action);
7240     if (error) {
7241         return error;
7242     }
7243
7244     if (action->deprecation) {
7245         VLOG_INFO_RL(&rl, "%s is deprecated in %s (%s)",
7246                      action->name, ofputil_version_to_string(ofp_version),
7247                      action->deprecation);
7248     }
7249
7250     length = ntohs(oah->len);
7251     if (length > buf->size) {
7252         VLOG_WARN_RL(&rl, "OpenFlow action %s length %u exceeds action buffer "
7253                      "length %"PRIu32, action->name, length, buf->size);
7254         return OFPERR_OFPBAC_BAD_LEN;
7255     }
7256     if (length < action->min_length || length > action->max_length) {
7257         VLOG_WARN_RL(&rl, "OpenFlow action %s length %u not in valid range "
7258                      "[%hu,%hu]", action->name, length,
7259                      action->min_length, action->max_length);
7260         return OFPERR_OFPBAC_BAD_LEN;
7261     }
7262     if (length % 8) {
7263         VLOG_WARN_RL(&rl, "OpenFlow action %s length %u is not a multiple "
7264                      "of 8", action->name, length);
7265         return OFPERR_OFPBAC_BAD_LEN;
7266     }
7267
7268     *raw = action->raw;
7269     *arg = 0;
7270     if (action->arg_len) {
7271         const uint8_t *p;
7272         int i;
7273
7274         p = ofpbuf_at_assert(buf, action->arg_ofs, action->arg_len);
7275         for (i = 0; i < action->arg_len; i++) {
7276             *arg = (*arg << 8) | p[i];
7277         }
7278     }
7279
7280     ofpbuf_pull(buf, length);
7281
7282     return 0;
7283 }
7284
7285 static const struct ofpact_raw_instance *
7286 ofpact_raw_lookup(enum ofp_version ofp_version, enum ofp_raw_action_type raw)
7287 {
7288     const struct ofpact_raw_instance *inst;
7289
7290     HMAP_FOR_EACH_WITH_HASH (inst, encode_node, hash_2words(raw, ofp_version),
7291                              ofpact_encode_hmap()) {
7292         if (inst->raw == raw && inst->hdrs.ofp_version == ofp_version) {
7293             return inst;
7294         }
7295     }
7296     OVS_NOT_REACHED();
7297 }
7298
7299 static void *
7300 ofpact_put_raw(struct ofpbuf *buf, enum ofp_version ofp_version,
7301                enum ofp_raw_action_type raw, uint64_t arg)
7302 {
7303     const struct ofpact_raw_instance *inst;
7304     struct ofp_action_header *oah;
7305     const struct ofpact_hdrs *hdrs;
7306
7307     inst = ofpact_raw_lookup(ofp_version, raw);
7308     hdrs = &inst->hdrs;
7309
7310     oah = ofpbuf_put_zeros(buf, inst->min_length);
7311     oah->type = htons(hdrs->vendor ? OFPAT_VENDOR : hdrs->type);
7312     oah->len = htons(inst->min_length);
7313     oah->vendor = htonl(hdrs->vendor);
7314
7315     switch (hdrs->vendor) {
7316     case 0:
7317         break;
7318
7319     case NX_VENDOR_ID:
7320     case ONF_VENDOR_ID: {
7321         struct ext_action_header *nah = (struct ext_action_header *) oah;
7322         nah->subtype = htons(hdrs->type);
7323         break;
7324     }
7325
7326     default:
7327         OVS_NOT_REACHED();
7328     }
7329
7330     if (inst->arg_len) {
7331         uint8_t *p = (uint8_t *) oah + inst->arg_ofs + inst->arg_len;
7332         int i;
7333
7334         for (i = 0; i < inst->arg_len; i++) {
7335             *--p = arg;
7336             arg >>= 8;
7337         }
7338     } else {
7339         ovs_assert(!arg);
7340     }
7341
7342     return oah;
7343 }
7344
7345 static void
7346 pad_ofpat(struct ofpbuf *openflow, size_t start_ofs)
7347 {
7348     struct ofp_action_header *oah;
7349
7350     ofpbuf_put_zeros(openflow, PAD_SIZE(openflow->size - start_ofs, 8));
7351
7352     oah = ofpbuf_at_assert(openflow, start_ofs, sizeof *oah);
7353     oah->len = htons(openflow->size - start_ofs);
7354 }
7355