vlog: change log file owner when switching user
[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_OF_ICMP_TYPE
1884  *   - NXM_OF_ICMP_CODE
1885  *   - NXM_NX_ICMPV6_TYPE
1886  *   - NXM_NX_ICMPV6_CODE
1887  *   - NXM_NX_ARP_SHA
1888  *   - NXM_NX_ARP_THA
1889  *   - NXM_OF_ARP_OP
1890  *   - NXM_OF_ARP_SPA
1891  *   - NXM_OF_ARP_TPA
1892  *     Modifying any of the above fields changes the corresponding packet
1893  *     header.
1894  *
1895  *   - NXM_OF_IN_PORT
1896  *
1897  *   - NXM_NX_REG(idx) for idx in the switch's accepted range.
1898  *
1899  *   - NXM_NX_PKT_MARK
1900  *
1901  *   - NXM_OF_VLAN_TCI.  Modifying this field's value has side effects on the
1902  *     packet's 802.1Q header.  Setting a value with CFI=0 removes the 802.1Q
1903  *     header (if any), ignoring the other bits.  Setting a value with CFI=1
1904  *     adds or modifies the 802.1Q header appropriately, setting the TCI field
1905  *     to the field's new value (with the CFI bit masked out).
1906  *
1907  *   - NXM_NX_TUN_ID, NXM_NX_TUN_IPV4_SRC, NXM_NX_TUN_IPV4_DST.  Modifying
1908  *     any of these values modifies the corresponding tunnel header field used
1909  *     for the packet's next tunnel encapsulation, if allowed by the
1910  *     configuration of the output tunnel port.
1911  *
1912  * A given nxm_header value may be used as 'src' or 'dst' only on a flow whose
1913  * nx_match satisfies its prerequisites.  For example, NXM_OF_IP_TOS may be
1914  * used only if the flow's nx_match includes an nxm_entry that specifies
1915  * nxm_type=NXM_OF_ETH_TYPE, nxm_hasmask=0, and nxm_value=0x0800.
1916  *
1917  * The switch will reject actions for which src_ofs+n_bits is greater than the
1918  * width of 'src' or dst_ofs+n_bits is greater than the width of 'dst' with
1919  * error type OFPET_BAD_ACTION, code OFPBAC_BAD_ARGUMENT.
1920  *
1921  * This action behaves properly when 'src' overlaps with 'dst', that is, it
1922  * behaves as if 'src' were copied out to a temporary buffer, then the
1923  * temporary buffer copied to 'dst'.
1924  */
1925 struct nx_action_reg_move {
1926     ovs_be16 type;                  /* OFPAT_VENDOR. */
1927     ovs_be16 len;                   /* Length is 24. */
1928     ovs_be32 vendor;                /* NX_VENDOR_ID. */
1929     ovs_be16 subtype;               /* NXAST_REG_MOVE. */
1930     ovs_be16 n_bits;                /* Number of bits. */
1931     ovs_be16 src_ofs;               /* Starting bit offset in source. */
1932     ovs_be16 dst_ofs;               /* Starting bit offset in destination. */
1933     /* Followed by:
1934      * - OXM/NXM header for source field (4 or 8 bytes).
1935      * - OXM/NXM header for destination field (4 or 8 bytes).
1936      * - Padding with 0-bytes to a multiple of 8 bytes, if necessary. */
1937 };
1938 OFP_ASSERT(sizeof(struct nx_action_reg_move) == 16);
1939
1940 static enum ofperr
1941 decode_copy_field__(ovs_be16 src_offset, ovs_be16 dst_offset, ovs_be16 n_bits,
1942                     const void *action, ovs_be16 action_len, size_t oxm_offset,
1943                     struct ofpbuf *ofpacts)
1944 {
1945     struct ofpact_reg_move *move;
1946     enum ofperr error;
1947     struct ofpbuf b;
1948
1949     move = ofpact_put_REG_MOVE(ofpacts);
1950     move->ofpact.raw = ONFACT_RAW13_COPY_FIELD;
1951     move->src.ofs = ntohs(src_offset);
1952     move->src.n_bits = ntohs(n_bits);
1953     move->dst.ofs = ntohs(dst_offset);
1954     move->dst.n_bits = ntohs(n_bits);
1955
1956     ofpbuf_use_const(&b, action, ntohs(action_len));
1957     ofpbuf_pull(&b, oxm_offset);
1958     error = nx_pull_header(&b, &move->src.field, NULL);
1959     if (error) {
1960         return error;
1961     }
1962     error = nx_pull_header(&b, &move->dst.field, NULL);
1963     if (error) {
1964         return error;
1965     }
1966
1967     if (!is_all_zeros(b.data, b.size)) {
1968         return OFPERR_NXBRC_MUST_BE_ZERO;
1969     }
1970
1971     return nxm_reg_move_check(move, NULL);
1972 }
1973
1974 static enum ofperr
1975 decode_OFPAT_RAW15_COPY_FIELD(const struct ofp15_action_copy_field *oacf,
1976                               enum ofp_version ofp_version OVS_UNUSED,
1977                               struct ofpbuf *ofpacts)
1978 {
1979     return decode_copy_field__(oacf->src_offset, oacf->dst_offset,
1980                                oacf->n_bits, oacf, oacf->len,
1981                                OBJECT_OFFSETOF(oacf, pad2), ofpacts);
1982 }
1983
1984 static enum ofperr
1985 decode_ONFACT_RAW13_COPY_FIELD(const struct onf_action_copy_field *oacf,
1986                                enum ofp_version ofp_version OVS_UNUSED,
1987                                struct ofpbuf *ofpacts)
1988 {
1989     return decode_copy_field__(oacf->src_offset, oacf->dst_offset,
1990                                oacf->n_bits, oacf, oacf->len,
1991                                OBJECT_OFFSETOF(oacf, pad3), ofpacts);
1992 }
1993
1994 static enum ofperr
1995 decode_NXAST_RAW_REG_MOVE(const struct nx_action_reg_move *narm,
1996                           enum ofp_version ofp_version OVS_UNUSED,
1997                           struct ofpbuf *ofpacts)
1998 {
1999     struct ofpact_reg_move *move;
2000     enum ofperr error;
2001     struct ofpbuf b;
2002
2003     move = ofpact_put_REG_MOVE(ofpacts);
2004     move->ofpact.raw = NXAST_RAW_REG_MOVE;
2005     move->src.ofs = ntohs(narm->src_ofs);
2006     move->src.n_bits = ntohs(narm->n_bits);
2007     move->dst.ofs = ntohs(narm->dst_ofs);
2008     move->dst.n_bits = ntohs(narm->n_bits);
2009
2010     ofpbuf_use_const(&b, narm, ntohs(narm->len));
2011     ofpbuf_pull(&b, sizeof *narm);
2012     error = nx_pull_header(&b, &move->src.field, NULL);
2013     if (error) {
2014         return error;
2015     }
2016     error = nx_pull_header(&b, &move->dst.field, NULL);
2017     if (error) {
2018         return error;
2019     }
2020     if (!is_all_zeros(b.data, b.size)) {
2021         return OFPERR_NXBRC_MUST_BE_ZERO;
2022     }
2023
2024     return nxm_reg_move_check(move, NULL);
2025 }
2026
2027 static void
2028 encode_REG_MOVE(const struct ofpact_reg_move *move,
2029                 enum ofp_version ofp_version, struct ofpbuf *out)
2030 {
2031     /* For OpenFlow 1.3, the choice of ONFACT_RAW13_COPY_FIELD versus
2032      * NXAST_RAW_REG_MOVE is somewhat difficult.  Neither one is guaranteed to
2033      * be supported by every OpenFlow 1.3 implementation.  It would be ideal to
2034      * probe for support.  Until we have that ability, we currently prefer
2035      * NXAST_RAW_REG_MOVE for backward compatibility with older Open vSwitch
2036      * versions.  */
2037     size_t start_ofs = out->size;
2038     if (ofp_version >= OFP15_VERSION) {
2039         struct ofp15_action_copy_field *copy = put_OFPAT15_COPY_FIELD(out);
2040         copy->n_bits = htons(move->dst.n_bits);
2041         copy->src_offset = htons(move->src.ofs);
2042         copy->dst_offset = htons(move->dst.ofs);
2043         out->size = out->size - sizeof copy->pad2;
2044         nx_put_header(out, move->src.field->id, ofp_version, false);
2045         nx_put_header(out, move->dst.field->id, ofp_version, false);
2046     } else if (ofp_version == OFP13_VERSION
2047                && move->ofpact.raw == ONFACT_RAW13_COPY_FIELD) {
2048         struct onf_action_copy_field *copy = put_ONFACT13_COPY_FIELD(out);
2049         copy->n_bits = htons(move->dst.n_bits);
2050         copy->src_offset = htons(move->src.ofs);
2051         copy->dst_offset = htons(move->dst.ofs);
2052         out->size = out->size - sizeof copy->pad3;
2053         nx_put_header(out, move->src.field->id, ofp_version, false);
2054         nx_put_header(out, move->dst.field->id, ofp_version, false);
2055     } else {
2056         struct nx_action_reg_move *narm = put_NXAST_REG_MOVE(out);
2057         narm->n_bits = htons(move->dst.n_bits);
2058         narm->src_ofs = htons(move->src.ofs);
2059         narm->dst_ofs = htons(move->dst.ofs);
2060         nx_put_header(out, move->src.field->id, 0, false);
2061         nx_put_header(out, move->dst.field->id, 0, false);
2062     }
2063     pad_ofpat(out, start_ofs);
2064 }
2065
2066 static char * OVS_WARN_UNUSED_RESULT
2067 parse_REG_MOVE(const char *arg, struct ofpbuf *ofpacts,
2068                enum ofputil_protocol *usable_protocols OVS_UNUSED)
2069 {
2070     struct ofpact_reg_move *move = ofpact_put_REG_MOVE(ofpacts);
2071     const char *full_arg = arg;
2072     char *error;
2073
2074     error = mf_parse_subfield__(&move->src, &arg);
2075     if (error) {
2076         return error;
2077     }
2078     if (strncmp(arg, "->", 2)) {
2079         return xasprintf("%s: missing `->' following source", full_arg);
2080     }
2081     arg += 2;
2082     error = mf_parse_subfield(&move->dst, arg);
2083     if (error) {
2084         return error;
2085     }
2086
2087     if (move->src.n_bits != move->dst.n_bits) {
2088         return xasprintf("%s: source field is %d bits wide but destination is "
2089                          "%d bits wide", full_arg,
2090                          move->src.n_bits, move->dst.n_bits);
2091     }
2092     return NULL;
2093 }
2094
2095 static void
2096 format_REG_MOVE(const struct ofpact_reg_move *a, struct ds *s)
2097 {
2098     nxm_format_reg_move(a, s);
2099 }
2100 \f
2101 /* Action structure for OFPAT12_SET_FIELD. */
2102 struct ofp12_action_set_field {
2103     ovs_be16 type;                  /* OFPAT12_SET_FIELD. */
2104     ovs_be16 len;                   /* Length is padded to 64 bits. */
2105
2106     /* Followed by:
2107      * - An OXM header, value, and (in OpenFlow 1.5+) optionally a mask.
2108      * - Enough 0-bytes to pad out to a multiple of 64 bits.
2109      *
2110      * The "pad" member is the beginning of the above. */
2111     uint8_t pad[4];
2112 };
2113 OFP_ASSERT(sizeof(struct ofp12_action_set_field) == 8);
2114
2115 /* Action structure for NXAST_REG_LOAD.
2116  *
2117  * Copies value[0:n_bits] to dst[ofs:ofs+n_bits], where a[b:c] denotes the bits
2118  * within 'a' numbered 'b' through 'c' (not including bit 'c').  Bit numbering
2119  * starts at 0 for the least-significant bit, 1 for the next most significant
2120  * bit, and so on.
2121  *
2122  * 'dst' is an nxm_header with nxm_hasmask=0.  See the documentation for
2123  * NXAST_REG_MOVE, above, for the permitted fields and for the side effects of
2124  * loading them.
2125  *
2126  * The 'ofs' and 'n_bits' fields are combined into a single 'ofs_nbits' field
2127  * to avoid enlarging the structure by another 8 bytes.  To allow 'n_bits' to
2128  * take a value between 1 and 64 (inclusive) while taking up only 6 bits, it is
2129  * also stored as one less than its true value:
2130  *
2131  *  15                           6 5                0
2132  * +------------------------------+------------------+
2133  * |              ofs             |    n_bits - 1    |
2134  * +------------------------------+------------------+
2135  *
2136  * The switch will reject actions for which ofs+n_bits is greater than the
2137  * width of 'dst', or in which any bits in 'value' with value 2**n_bits or
2138  * greater are set to 1, with error type OFPET_BAD_ACTION, code
2139  * OFPBAC_BAD_ARGUMENT.
2140  */
2141 struct nx_action_reg_load {
2142     ovs_be16 type;                  /* OFPAT_VENDOR. */
2143     ovs_be16 len;                   /* Length is 24. */
2144     ovs_be32 vendor;                /* NX_VENDOR_ID. */
2145     ovs_be16 subtype;               /* NXAST_REG_LOAD. */
2146     ovs_be16 ofs_nbits;             /* (ofs << 6) | (n_bits - 1). */
2147     ovs_be32 dst;                   /* Destination register. */
2148     ovs_be64 value;                 /* Immediate value. */
2149 };
2150 OFP_ASSERT(sizeof(struct nx_action_reg_load) == 24);
2151
2152 /* Action structure for NXAST_REG_LOAD2.
2153  *
2154  * Compared to OFPAT_SET_FIELD, we can use this to set whole or partial fields
2155  * in any OpenFlow version.  Compared to NXAST_REG_LOAD, we can use this to set
2156  * OXM experimenter fields. */
2157 struct nx_action_reg_load2 {
2158     ovs_be16 type;                  /* OFPAT_VENDOR. */
2159     ovs_be16 len;                   /* At least 16. */
2160     ovs_be32 vendor;                /* NX_VENDOR_ID. */
2161     ovs_be16 subtype;               /* NXAST_SET_FIELD. */
2162
2163     /* Followed by:
2164      * - An NXM/OXM header, value, and optionally a mask.
2165      * - Enough 0-bytes to pad out to a multiple of 64 bits.
2166      *
2167      * The "pad" member is the beginning of the above. */
2168     uint8_t pad[6];
2169 };
2170 OFP_ASSERT(sizeof(struct nx_action_reg_load2) == 16);
2171
2172 static enum ofperr
2173 decode_ofpat_set_field(const struct ofp12_action_set_field *oasf,
2174                        bool may_mask, struct ofpbuf *ofpacts)
2175 {
2176     struct ofpact_set_field *sf;
2177     enum ofperr error;
2178     struct ofpbuf b;
2179
2180     sf = ofpact_put_SET_FIELD(ofpacts);
2181
2182     ofpbuf_use_const(&b, oasf, ntohs(oasf->len));
2183     ofpbuf_pull(&b, OBJECT_OFFSETOF(oasf, pad));
2184     error = nx_pull_entry(&b, &sf->field, &sf->value,
2185                           may_mask ? &sf->mask : NULL);
2186     if (error) {
2187         return (error == OFPERR_OFPBMC_BAD_MASK
2188                 ? OFPERR_OFPBAC_BAD_SET_MASK
2189                 : error);
2190     }
2191     if (!may_mask) {
2192         memset(&sf->mask, 0xff, sf->field->n_bytes);
2193     }
2194
2195     if (!is_all_zeros(b.data, b.size)) {
2196         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2197     }
2198
2199     /* OpenFlow says specifically that one may not set OXM_OF_IN_PORT via
2200      * Set-Field. */
2201     if (sf->field->id == MFF_IN_PORT_OXM) {
2202         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2203     }
2204
2205     /* oxm_length is now validated to be compatible with mf_value. */
2206     if (!sf->field->writable) {
2207         VLOG_WARN_RL(&rl, "destination field %s is not writable",
2208                      sf->field->name);
2209         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2210     }
2211
2212     /* The value must be valid for match.  OpenFlow 1.5 also says,
2213      * "In an OXM_OF_VLAN_VID set-field action, the OFPVID_PRESENT bit must be
2214      * a 1-bit in oxm_value and in oxm_mask." */
2215     if (!mf_is_value_valid(sf->field, &sf->value)
2216         || (sf->field->id == MFF_VLAN_VID
2217             && (!(sf->mask.be16 & htons(OFPVID12_PRESENT))
2218                 || !(sf->value.be16 & htons(OFPVID12_PRESENT))))) {
2219         struct ds ds = DS_EMPTY_INITIALIZER;
2220         mf_format(sf->field, &sf->value, NULL, &ds);
2221         VLOG_WARN_RL(&rl, "Invalid value for set field %s: %s",
2222                      sf->field->name, ds_cstr(&ds));
2223         ds_destroy(&ds);
2224
2225         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2226     }
2227     return 0;
2228 }
2229
2230 static enum ofperr
2231 decode_OFPAT_RAW12_SET_FIELD(const struct ofp12_action_set_field *oasf,
2232                              enum ofp_version ofp_version OVS_UNUSED,
2233                              struct ofpbuf *ofpacts)
2234 {
2235     return decode_ofpat_set_field(oasf, false, ofpacts);
2236 }
2237
2238 static enum ofperr
2239 decode_OFPAT_RAW15_SET_FIELD(const struct ofp12_action_set_field *oasf,
2240                              enum ofp_version ofp_version OVS_UNUSED,
2241                              struct ofpbuf *ofpacts)
2242 {
2243     return decode_ofpat_set_field(oasf, true, ofpacts);
2244 }
2245
2246 static enum ofperr
2247 decode_NXAST_RAW_REG_LOAD(const struct nx_action_reg_load *narl,
2248                           enum ofp_version ofp_version OVS_UNUSED,
2249                           struct ofpbuf *out)
2250 {
2251     struct ofpact_set_field *sf = ofpact_put_reg_load(out);
2252     struct mf_subfield dst;
2253     enum ofperr error;
2254
2255     sf->ofpact.raw = NXAST_RAW_REG_LOAD;
2256
2257     dst.field = mf_from_nxm_header(ntohl(narl->dst));
2258     dst.ofs = nxm_decode_ofs(narl->ofs_nbits);
2259     dst.n_bits = nxm_decode_n_bits(narl->ofs_nbits);
2260     error = mf_check_dst(&dst, NULL);
2261     if (error) {
2262         return error;
2263     }
2264
2265     /* Reject 'narl' if a bit numbered 'n_bits' or higher is set to 1 in
2266      * narl->value. */
2267     if (dst.n_bits < 64 && ntohll(narl->value) >> dst.n_bits) {
2268         return OFPERR_OFPBAC_BAD_ARGUMENT;
2269     }
2270
2271     sf->field = dst.field;
2272     bitwise_put(ntohll(narl->value),
2273                 &sf->value, dst.field->n_bytes, dst.ofs,
2274                 dst.n_bits);
2275     bitwise_put(UINT64_MAX,
2276                 &sf->mask, dst.field->n_bytes, dst.ofs,
2277                 dst.n_bits);
2278
2279     return 0;
2280 }
2281
2282 static enum ofperr
2283 decode_NXAST_RAW_REG_LOAD2(const struct nx_action_reg_load2 *narl,
2284                            enum ofp_version ofp_version OVS_UNUSED,
2285                            struct ofpbuf *out)
2286 {
2287     struct ofpact_set_field *sf;
2288     enum ofperr error;
2289     struct ofpbuf b;
2290
2291     sf = ofpact_put_SET_FIELD(out);
2292     sf->ofpact.raw = NXAST_RAW_REG_LOAD2;
2293
2294     ofpbuf_use_const(&b, narl, ntohs(narl->len));
2295     ofpbuf_pull(&b, OBJECT_OFFSETOF(narl, pad));
2296     error = nx_pull_entry(&b, &sf->field, &sf->value, &sf->mask);
2297     if (error) {
2298         return error;
2299     }
2300     if (!is_all_zeros(b.data, b.size)) {
2301         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2302     }
2303
2304     if (!sf->field->writable) {
2305         VLOG_WARN_RL(&rl, "destination field %s is not writable",
2306                      sf->field->name);
2307         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
2308     }
2309     return 0;
2310 }
2311
2312 static void
2313 ofpact_put_set_field(struct ofpbuf *openflow, enum ofp_version ofp_version,
2314                      enum mf_field_id field, uint64_t value_)
2315 {
2316     struct ofp12_action_set_field *oasf OVS_UNUSED;
2317     int n_bytes = mf_from_id(field)->n_bytes;
2318     size_t start_ofs = openflow->size;
2319     union mf_value value;
2320
2321     value.be64 = htonll(value_ << (8 * (8 - n_bytes)));
2322
2323     oasf = put_OFPAT12_SET_FIELD(openflow);
2324     openflow->size = openflow->size - sizeof oasf->pad;
2325     nx_put_entry(openflow, field, ofp_version, &value, NULL);
2326     pad_ofpat(openflow, start_ofs);
2327 }
2328
2329 static bool
2330 next_load_segment(const struct ofpact_set_field *sf,
2331                   struct mf_subfield *dst, uint64_t *value)
2332 {
2333     int n_bits = sf->field->n_bits;
2334     int n_bytes = sf->field->n_bytes;
2335     int start = dst->ofs + dst->n_bits;
2336
2337     if (start < n_bits) {
2338         dst->field = sf->field;
2339         dst->ofs = bitwise_scan(&sf->mask, n_bytes, 1, start, n_bits);
2340         if (dst->ofs < n_bits) {
2341             dst->n_bits = bitwise_scan(&sf->mask, n_bytes, 0, dst->ofs + 1,
2342                                        MIN(dst->ofs + 64, n_bits)) - dst->ofs;
2343             *value = bitwise_get(&sf->value, n_bytes, dst->ofs, dst->n_bits);
2344             return true;
2345         }
2346     }
2347     return false;
2348 }
2349
2350 /* Convert 'sf' to a series of REG_LOADs. */
2351 static void
2352 set_field_to_nxast(const struct ofpact_set_field *sf, struct ofpbuf *openflow)
2353 {
2354     /* If 'sf' cannot be encoded as NXAST_REG_LOAD because it requires an
2355      * experimenter OXM or is variable length (or if it came in as
2356      * NXAST_REG_LOAD2), encode as NXAST_REG_LOAD2.  Otherwise use
2357      * NXAST_REG_LOAD, which is backward compatible. */
2358     if (sf->ofpact.raw == NXAST_RAW_REG_LOAD2
2359         || !mf_nxm_header(sf->field->id) || sf->field->variable_len) {
2360         struct nx_action_reg_load2 *narl OVS_UNUSED;
2361         size_t start_ofs = openflow->size;
2362
2363         narl = put_NXAST_REG_LOAD2(openflow);
2364         openflow->size = openflow->size - sizeof narl->pad;
2365         nx_put_entry(openflow, sf->field->id, 0, &sf->value, &sf->mask);
2366         pad_ofpat(openflow, start_ofs);
2367     } else {
2368         struct mf_subfield dst;
2369         uint64_t value;
2370
2371         dst.ofs = dst.n_bits = 0;
2372         while (next_load_segment(sf, &dst, &value)) {
2373             struct nx_action_reg_load *narl = put_NXAST_REG_LOAD(openflow);
2374             narl->ofs_nbits = nxm_encode_ofs_nbits(dst.ofs, dst.n_bits);
2375             narl->dst = htonl(mf_nxm_header(dst.field->id));
2376             narl->value = htonll(value);
2377         }
2378     }
2379 }
2380
2381 /* Convert 'sf', which must set an entire field, to standard OpenFlow 1.0/1.1
2382  * actions, if we can, falling back to Nicira extensions if we must.
2383  *
2384  * We check only meta-flow types that can appear within set field actions and
2385  * that have a mapping to compatible action types.  These struct mf_field
2386  * definitions have a defined OXM or NXM header value and specify the field as
2387  * writable. */
2388 static void
2389 set_field_to_legacy_openflow(const struct ofpact_set_field *sf,
2390                              enum ofp_version ofp_version,
2391                              struct ofpbuf *out)
2392 {
2393     switch ((int) sf->field->id) {
2394     case MFF_VLAN_TCI: {
2395         ovs_be16 tci = sf->value.be16;
2396         bool cfi = (tci & htons(VLAN_CFI)) != 0;
2397         uint16_t vid = vlan_tci_to_vid(tci);
2398         uint8_t pcp = vlan_tci_to_pcp(tci);
2399
2400         if (ofp_version < OFP11_VERSION) {
2401             /* NXM_OF_VLAN_TCI to OpenFlow 1.0 mapping:
2402              *
2403              * If CFI=1, Add or modify VLAN VID & PCP.
2404              * If CFI=0, strip VLAN header, if any.
2405              */
2406             if (cfi) {
2407                 put_OFPAT10_SET_VLAN_VID(out, vid);
2408                 put_OFPAT10_SET_VLAN_PCP(out, pcp);
2409             } else {
2410                 put_OFPAT10_STRIP_VLAN(out);
2411             }
2412         } else {
2413             /* NXM_OF_VLAN_TCI to OpenFlow 1.1 mapping:
2414              *
2415              * If CFI=1, Add or modify VLAN VID & PCP.
2416              *    OpenFlow 1.1 set actions only apply if the packet
2417              *    already has VLAN tags.  To be sure that is the case
2418              *    we have to push a VLAN header.  As we do not support
2419              *    multiple layers of VLANs, this is a no-op, if a VLAN
2420              *    header already exists.  This may backfire, however,
2421              *    when we start supporting multiple layers of VLANs.
2422              * If CFI=0, strip VLAN header, if any.
2423              */
2424             if (cfi) {
2425                 /* Push a VLAN tag, if one was not seen at action validation
2426                  * time. */
2427                 if (!sf->flow_has_vlan) {
2428                     put_OFPAT11_PUSH_VLAN(out, htons(ETH_TYPE_VLAN_8021Q));
2429                 }
2430                 put_OFPAT11_SET_VLAN_VID(out, vid);
2431                 put_OFPAT11_SET_VLAN_PCP(out, pcp);
2432             } else {
2433                 /* If the flow did not match on vlan, we have no way of
2434                  * knowing if the vlan tag exists, so we must POP just to be
2435                  * sure. */
2436                 put_OFPAT11_POP_VLAN(out);
2437             }
2438         }
2439         break;
2440     }
2441
2442     case MFF_VLAN_VID: {
2443         uint16_t vid = ntohs(sf->value.be16) & VLAN_VID_MASK;
2444         if (ofp_version == OFP10_VERSION) {
2445             put_OFPAT10_SET_VLAN_VID(out, vid);
2446         } else {
2447             put_OFPAT11_SET_VLAN_VID(out, vid);
2448         }
2449         break;
2450     }
2451
2452     case MFF_VLAN_PCP:
2453         if (ofp_version == OFP10_VERSION) {
2454             put_OFPAT10_SET_VLAN_PCP(out, sf->value.u8);
2455         } else {
2456             put_OFPAT11_SET_VLAN_PCP(out, sf->value.u8);
2457         }
2458         break;
2459
2460     case MFF_ETH_SRC:
2461         put_OFPAT_SET_DL_SRC(out, ofp_version)->dl_addr = sf->value.mac;
2462         break;
2463
2464     case MFF_ETH_DST:
2465         put_OFPAT_SET_DL_DST(out, ofp_version)->dl_addr = sf->value.mac;
2466         break;
2467
2468     case MFF_IPV4_SRC:
2469         put_OFPAT_SET_NW_SRC(out, ofp_version, sf->value.be32);
2470         break;
2471
2472     case MFF_IPV4_DST:
2473         put_OFPAT_SET_NW_DST(out, ofp_version, sf->value.be32);
2474         break;
2475
2476     case MFF_IP_DSCP:
2477         put_OFPAT_SET_NW_TOS(out, ofp_version, sf->value.u8);
2478         break;
2479
2480     case MFF_IP_DSCP_SHIFTED:
2481         put_OFPAT_SET_NW_TOS(out, ofp_version, sf->value.u8 << 2);
2482         break;
2483
2484     case MFF_TCP_SRC:
2485     case MFF_UDP_SRC:
2486         put_OFPAT_SET_TP_SRC(out, sf->value.be16);
2487         break;
2488
2489     case MFF_TCP_DST:
2490     case MFF_UDP_DST:
2491         put_OFPAT_SET_TP_DST(out, sf->value.be16);
2492         break;
2493
2494     default:
2495         set_field_to_nxast(sf, out);
2496         break;
2497     }
2498 }
2499
2500 static void
2501 set_field_to_set_field(const struct ofpact_set_field *sf,
2502                        enum ofp_version ofp_version, struct ofpbuf *out)
2503 {
2504     struct ofp12_action_set_field *oasf OVS_UNUSED;
2505     size_t start_ofs = out->size;
2506
2507     oasf = put_OFPAT12_SET_FIELD(out);
2508     out->size = out->size - sizeof oasf->pad;
2509     nx_put_entry(out, sf->field->id, ofp_version, &sf->value, &sf->mask);
2510     pad_ofpat(out, start_ofs);
2511 }
2512
2513 static void
2514 encode_SET_FIELD(const struct ofpact_set_field *sf,
2515                  enum ofp_version ofp_version, struct ofpbuf *out)
2516 {
2517     if (ofp_version >= OFP15_VERSION) {
2518         /* OF1.5+ only has Set-Field (reg_load is redundant so we drop it
2519          * entirely). */
2520         set_field_to_set_field(sf, ofp_version, out);
2521     } else if (sf->ofpact.raw == NXAST_RAW_REG_LOAD ||
2522                sf->ofpact.raw == NXAST_RAW_REG_LOAD2) {
2523         /* It came in as reg_load, send it out the same way. */
2524         set_field_to_nxast(sf, out);
2525     } else if (ofp_version < OFP12_VERSION) {
2526         /* OpenFlow 1.0 and 1.1 don't have Set-Field. */
2527         set_field_to_legacy_openflow(sf, ofp_version, out);
2528     } else if (is_all_ones((const uint8_t *) &sf->mask, sf->field->n_bytes)) {
2529         /* We're encoding to OpenFlow 1.2, 1.3, or 1.4.  The action sets an
2530          * entire field, so encode it as OFPAT_SET_FIELD. */
2531         set_field_to_set_field(sf, ofp_version, out);
2532     } else {
2533         /* We're encoding to OpenFlow 1.2, 1.3, or 1.4.  The action cannot be
2534          * encoded as OFPAT_SET_FIELD because it does not set an entire field,
2535          * so encode it as reg_load. */
2536         set_field_to_nxast(sf, out);
2537     }
2538 }
2539
2540 /* Parses the input argument 'arg' into the key, value, and delimiter
2541  * components that are common across the reg_load and set_field action format.
2542  *
2543  * With an argument like "1->metadata", sets the following pointers to
2544  * point within 'arg':
2545  * key: "metadata"
2546  * value: "1"
2547  * delim: "->"
2548  *
2549  * Returns NULL if successful, otherwise a malloc()'d string describing the
2550  * error.  The caller is responsible for freeing the returned string. */
2551 static char * OVS_WARN_UNUSED_RESULT
2552 set_field_split_str(char *arg, char **key, char **value, char **delim)
2553 {
2554     char *value_end;
2555
2556     *value = arg;
2557     value_end = strstr(arg, "->");
2558     *key = value_end + strlen("->");
2559     if (delim) {
2560         *delim = value_end;
2561     }
2562
2563     if (!value_end) {
2564         return xasprintf("%s: missing `->'", arg);
2565     }
2566     if (strlen(value_end) <= strlen("->")) {
2567         return xasprintf("%s: missing field name following `->'", arg);
2568     }
2569
2570     return NULL;
2571 }
2572
2573 /* Parses a "set_field" action with argument 'arg', appending the parsed
2574  * action to 'ofpacts'.
2575  *
2576  * Returns NULL if successful, otherwise a malloc()'d string describing the
2577  * error.  The caller is responsible for freeing the returned string. */
2578 static char * OVS_WARN_UNUSED_RESULT
2579 set_field_parse__(char *arg, struct ofpbuf *ofpacts,
2580                   enum ofputil_protocol *usable_protocols)
2581 {
2582     struct ofpact_set_field *sf = ofpact_put_SET_FIELD(ofpacts);
2583     char *value;
2584     char *delim;
2585     char *key;
2586     const struct mf_field *mf;
2587     char *error;
2588
2589     error = set_field_split_str(arg, &key, &value, &delim);
2590     if (error) {
2591         return error;
2592     }
2593
2594     mf = mf_from_name(key);
2595     if (!mf) {
2596         return xasprintf("%s is not a valid OXM field name", key);
2597     }
2598     if (!mf->writable) {
2599         return xasprintf("%s is read-only", key);
2600     }
2601     sf->field = mf;
2602     delim[0] = '\0';
2603     error = mf_parse(mf, value, &sf->value, &sf->mask);
2604     if (error) {
2605         return error;
2606     }
2607
2608     if (!mf_is_value_valid(mf, &sf->value)) {
2609         return xasprintf("%s is not a valid value for field %s", value, key);
2610     }
2611
2612     *usable_protocols &= mf->usable_protocols_exact;
2613     return NULL;
2614 }
2615
2616 /* Parses 'arg' as the argument to a "set_field" action, and appends such an
2617  * action to 'ofpacts'.
2618  *
2619  * Returns NULL if successful, otherwise a malloc()'d string describing the
2620  * error.  The caller is responsible for freeing the returned string. */
2621 static char * OVS_WARN_UNUSED_RESULT
2622 parse_SET_FIELD(const char *arg, struct ofpbuf *ofpacts,
2623                 enum ofputil_protocol *usable_protocols)
2624 {
2625     char *copy = xstrdup(arg);
2626     char *error = set_field_parse__(copy, ofpacts, usable_protocols);
2627     free(copy);
2628     return error;
2629 }
2630
2631 static char * OVS_WARN_UNUSED_RESULT
2632 parse_reg_load(char *arg, struct ofpbuf *ofpacts)
2633 {
2634     struct ofpact_set_field *sf = ofpact_put_reg_load(ofpacts);
2635     struct mf_subfield dst;
2636     char *key, *value_str;
2637     union mf_value value;
2638     char *error;
2639
2640     error = set_field_split_str(arg, &key, &value_str, NULL);
2641     if (error) {
2642         return error;
2643     }
2644
2645     error = mf_parse_subfield(&dst, key);
2646     if (error) {
2647         return error;
2648     }
2649
2650     if (parse_int_string(value_str, (uint8_t *)&value, dst.field->n_bytes,
2651                          &key)) {
2652         return xasprintf("%s: cannot parse integer value", arg);
2653     }
2654
2655     if (!bitwise_is_all_zeros(&value, dst.field->n_bytes, dst.n_bits,
2656                               dst.field->n_bytes * 8 - dst.n_bits)) {
2657         struct ds ds;
2658
2659         ds_init(&ds);
2660         mf_format(dst.field, &value, NULL, &ds);
2661         error = xasprintf("%s: value %s does not fit into %d bits",
2662                           arg, ds_cstr(&ds), dst.n_bits);
2663         ds_destroy(&ds);
2664         return error;
2665     }
2666
2667     sf->field = dst.field;
2668     memset(&sf->value, 0, sizeof sf->value);
2669     bitwise_copy(&value, dst.field->n_bytes, 0, &sf->value,
2670                  dst.field->n_bytes, dst.ofs, dst.n_bits);
2671     bitwise_one(&sf->mask, dst.field->n_bytes, dst.ofs, dst.n_bits);
2672
2673     return NULL;
2674 }
2675
2676 static void
2677 format_SET_FIELD(const struct ofpact_set_field *a, struct ds *s)
2678 {
2679     if (a->ofpact.raw == NXAST_RAW_REG_LOAD) {
2680         struct mf_subfield dst;
2681         uint64_t value;
2682
2683         dst.ofs = dst.n_bits = 0;
2684         while (next_load_segment(a, &dst, &value)) {
2685             ds_put_format(s, "load:%#"PRIx64"->", value);
2686             mf_format_subfield(&dst, s);
2687             ds_put_char(s, ',');
2688         }
2689         ds_chomp(s, ',');
2690     } else {
2691         ds_put_cstr(s, "set_field:");
2692         mf_format(a->field, &a->value, &a->mask, s);
2693         ds_put_format(s, "->%s", a->field->name);
2694     }
2695 }
2696
2697 /* Appends an OFPACT_SET_FIELD ofpact to 'ofpacts' and returns it.  The ofpact
2698  * is marked such that, if possible, it will be translated to OpenFlow as
2699  * NXAST_REG_LOAD extension actions rather than OFPAT_SET_FIELD, either because
2700  * that was the way that the action was expressed when it came into OVS or for
2701  * backward compatibility. */
2702 struct ofpact_set_field *
2703 ofpact_put_reg_load(struct ofpbuf *ofpacts)
2704 {
2705     struct ofpact_set_field *sf = ofpact_put_SET_FIELD(ofpacts);
2706     sf->ofpact.raw = NXAST_RAW_REG_LOAD;
2707     return sf;
2708 }
2709 \f
2710 /* Action structure for NXAST_STACK_PUSH and NXAST_STACK_POP.
2711  *
2712  * Pushes (or pops) field[offset: offset + n_bits] to (or from)
2713  * top of the stack.
2714  */
2715 struct nx_action_stack {
2716     ovs_be16 type;                  /* OFPAT_VENDOR. */
2717     ovs_be16 len;                   /* Length is 16. */
2718     ovs_be32 vendor;                /* NX_VENDOR_ID. */
2719     ovs_be16 subtype;               /* NXAST_STACK_PUSH or NXAST_STACK_POP. */
2720     ovs_be16 offset;                /* Bit offset into the field. */
2721     /* Followed by:
2722      * - OXM/NXM header for field to push or pop (4 or 8 bytes).
2723      * - ovs_be16 'n_bits', the number of bits to extract from the field.
2724      * - Enough 0-bytes to pad out the action to 24 bytes. */
2725     uint8_t pad[12];                /* See above. */
2726 };
2727 OFP_ASSERT(sizeof(struct nx_action_stack) == 24);
2728
2729 static enum ofperr
2730 decode_stack_action(const struct nx_action_stack *nasp,
2731                     struct ofpact_stack *stack_action)
2732 {
2733     enum ofperr error;
2734     struct ofpbuf b;
2735
2736     stack_action->subfield.ofs = ntohs(nasp->offset);
2737
2738     ofpbuf_use_const(&b, nasp, sizeof *nasp);
2739     ofpbuf_pull(&b, OBJECT_OFFSETOF(nasp, pad));
2740     error = nx_pull_header(&b, &stack_action->subfield.field, NULL);
2741     if (error) {
2742         return error;
2743     }
2744     stack_action->subfield.n_bits = ntohs(*(const ovs_be16 *) b.data);
2745     ofpbuf_pull(&b, 2);
2746     if (!is_all_zeros(b.data, b.size)) {
2747         return OFPERR_NXBRC_MUST_BE_ZERO;
2748     }
2749
2750     return 0;
2751 }
2752
2753 static enum ofperr
2754 decode_NXAST_RAW_STACK_PUSH(const struct nx_action_stack *nasp,
2755                             enum ofp_version ofp_version OVS_UNUSED,
2756                             struct ofpbuf *ofpacts)
2757 {
2758     struct ofpact_stack *push = ofpact_put_STACK_PUSH(ofpacts);
2759     enum ofperr error = decode_stack_action(nasp, push);
2760     return error ? error : nxm_stack_push_check(push, NULL);
2761 }
2762
2763 static enum ofperr
2764 decode_NXAST_RAW_STACK_POP(const struct nx_action_stack *nasp,
2765                            enum ofp_version ofp_version OVS_UNUSED,
2766                            struct ofpbuf *ofpacts)
2767 {
2768     struct ofpact_stack *pop = ofpact_put_STACK_POP(ofpacts);
2769     enum ofperr error = decode_stack_action(nasp, pop);
2770     return error ? error : nxm_stack_pop_check(pop, NULL);
2771 }
2772
2773 static void
2774 encode_STACK_op(const struct ofpact_stack *stack_action,
2775                 struct nx_action_stack *nasp)
2776 {
2777     struct ofpbuf b;
2778     ovs_be16 n_bits;
2779
2780     nasp->offset = htons(stack_action->subfield.ofs);
2781
2782     ofpbuf_use_stack(&b, nasp, ntohs(nasp->len));
2783     ofpbuf_put_uninit(&b, OBJECT_OFFSETOF(nasp, pad));
2784     nx_put_header(&b, stack_action->subfield.field->id, 0, false);
2785     n_bits = htons(stack_action->subfield.n_bits);
2786     ofpbuf_put(&b, &n_bits, sizeof n_bits);
2787 }
2788
2789 static void
2790 encode_STACK_PUSH(const struct ofpact_stack *stack,
2791                   enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
2792 {
2793     encode_STACK_op(stack, put_NXAST_STACK_PUSH(out));
2794 }
2795
2796 static void
2797 encode_STACK_POP(const struct ofpact_stack *stack,
2798                  enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
2799 {
2800     encode_STACK_op(stack, put_NXAST_STACK_POP(out));
2801 }
2802
2803 static char * OVS_WARN_UNUSED_RESULT
2804 parse_STACK_PUSH(char *arg, struct ofpbuf *ofpacts,
2805                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
2806 {
2807     return nxm_parse_stack_action(ofpact_put_STACK_PUSH(ofpacts), arg);
2808 }
2809
2810 static char * OVS_WARN_UNUSED_RESULT
2811 parse_STACK_POP(char *arg, struct ofpbuf *ofpacts,
2812                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
2813 {
2814     return nxm_parse_stack_action(ofpact_put_STACK_POP(ofpacts), arg);
2815 }
2816
2817 static void
2818 format_STACK_PUSH(const struct ofpact_stack *a, struct ds *s)
2819 {
2820     nxm_format_stack_push(a, s);
2821 }
2822
2823 static void
2824 format_STACK_POP(const struct ofpact_stack *a, struct ds *s)
2825 {
2826     nxm_format_stack_pop(a, s);
2827 }
2828 \f
2829 /* Action structure for NXAST_DEC_TTL_CNT_IDS.
2830  *
2831  * If the packet is not IPv4 or IPv6, does nothing.  For IPv4 or IPv6, if the
2832  * TTL or hop limit is at least 2, decrements it by 1.  Otherwise, if TTL or
2833  * hop limit is 0 or 1, sends a packet-in to the controllers with each of the
2834  * 'n_controllers' controller IDs specified in 'cnt_ids'.
2835  *
2836  * (This differs from NXAST_DEC_TTL in that for NXAST_DEC_TTL the packet-in is
2837  * sent only to controllers with id 0.)
2838  */
2839 struct nx_action_cnt_ids {
2840     ovs_be16 type;              /* OFPAT_VENDOR. */
2841     ovs_be16 len;               /* Length including slaves. */
2842     ovs_be32 vendor;            /* NX_VENDOR_ID. */
2843     ovs_be16 subtype;           /* NXAST_DEC_TTL_CNT_IDS. */
2844
2845     ovs_be16 n_controllers;     /* Number of controllers. */
2846     uint8_t zeros[4];           /* Must be zero. */
2847
2848     /* Followed by 1 or more controller ids.
2849      *
2850      * uint16_t cnt_ids[];        // Controller ids.
2851      * uint8_t pad[];           // Must be 0 to 8-byte align cnt_ids[].
2852      */
2853 };
2854 OFP_ASSERT(sizeof(struct nx_action_cnt_ids) == 16);
2855
2856 static enum ofperr
2857 decode_OFPAT_RAW_DEC_NW_TTL(struct ofpbuf *out)
2858 {
2859     uint16_t id = 0;
2860     struct ofpact_cnt_ids *ids;
2861     enum ofperr error = 0;
2862
2863     ids = ofpact_put_DEC_TTL(out);
2864     ids->n_controllers = 1;
2865     ofpbuf_put(out, &id, sizeof id);
2866     ids = out->header;
2867     ofpact_update_len(out, &ids->ofpact);
2868     return error;
2869 }
2870
2871 static enum ofperr
2872 decode_NXAST_RAW_DEC_TTL_CNT_IDS(const struct nx_action_cnt_ids *nac_ids,
2873                                  enum ofp_version ofp_version OVS_UNUSED,
2874                                  struct ofpbuf *out)
2875 {
2876     struct ofpact_cnt_ids *ids;
2877     size_t ids_size;
2878     int i;
2879
2880     ids = ofpact_put_DEC_TTL(out);
2881     ids->ofpact.raw = NXAST_RAW_DEC_TTL_CNT_IDS;
2882     ids->n_controllers = ntohs(nac_ids->n_controllers);
2883     ids_size = ntohs(nac_ids->len) - sizeof *nac_ids;
2884
2885     if (!is_all_zeros(nac_ids->zeros, sizeof nac_ids->zeros)) {
2886         return OFPERR_NXBRC_MUST_BE_ZERO;
2887     }
2888
2889     if (ids_size < ids->n_controllers * sizeof(ovs_be16)) {
2890         VLOG_WARN_RL(&rl, "Nicira action dec_ttl_cnt_ids only has %"PRIuSIZE" "
2891                      "bytes allocated for controller ids.  %"PRIuSIZE" bytes "
2892                      "are required for %"PRIu16" controllers.",
2893                      ids_size, ids->n_controllers * sizeof(ovs_be16),
2894                      ids->n_controllers);
2895         return OFPERR_OFPBAC_BAD_LEN;
2896     }
2897
2898     for (i = 0; i < ids->n_controllers; i++) {
2899         uint16_t id = ntohs(((ovs_be16 *)(nac_ids + 1))[i]);
2900         ofpbuf_put(out, &id, sizeof id);
2901         ids = out->header;
2902     }
2903
2904     ofpact_update_len(out, &ids->ofpact);
2905
2906     return 0;
2907 }
2908
2909 static void
2910 encode_DEC_TTL(const struct ofpact_cnt_ids *dec_ttl,
2911                enum ofp_version ofp_version, struct ofpbuf *out)
2912 {
2913     if (dec_ttl->ofpact.raw == NXAST_RAW_DEC_TTL_CNT_IDS
2914         || dec_ttl->n_controllers != 1
2915         || dec_ttl->cnt_ids[0] != 0) {
2916         struct nx_action_cnt_ids *nac_ids = put_NXAST_DEC_TTL_CNT_IDS(out);
2917         int ids_len = ROUND_UP(2 * dec_ttl->n_controllers, OFP_ACTION_ALIGN);
2918         ovs_be16 *ids;
2919         size_t i;
2920
2921         nac_ids->len = htons(ntohs(nac_ids->len) + ids_len);
2922         nac_ids->n_controllers = htons(dec_ttl->n_controllers);
2923
2924         ids = ofpbuf_put_zeros(out, ids_len);
2925         for (i = 0; i < dec_ttl->n_controllers; i++) {
2926             ids[i] = htons(dec_ttl->cnt_ids[i]);
2927         }
2928     } else {
2929         put_OFPAT_DEC_NW_TTL(out, ofp_version);
2930     }
2931 }
2932
2933 static void
2934 parse_noargs_dec_ttl(struct ofpbuf *ofpacts)
2935 {
2936     struct ofpact_cnt_ids *ids;
2937     uint16_t id = 0;
2938
2939     ofpact_put_DEC_TTL(ofpacts);
2940     ofpbuf_put(ofpacts, &id, sizeof id);
2941     ids = ofpacts->header;
2942     ids->n_controllers++;
2943     ofpact_update_len(ofpacts, &ids->ofpact);
2944 }
2945
2946 static char * OVS_WARN_UNUSED_RESULT
2947 parse_DEC_TTL(char *arg, struct ofpbuf *ofpacts,
2948               enum ofputil_protocol *usable_protocols OVS_UNUSED)
2949 {
2950     if (*arg == '\0') {
2951         parse_noargs_dec_ttl(ofpacts);
2952     } else {
2953         struct ofpact_cnt_ids *ids;
2954         char *cntr;
2955
2956         ids = ofpact_put_DEC_TTL(ofpacts);
2957         ids->ofpact.raw = NXAST_RAW_DEC_TTL_CNT_IDS;
2958         for (cntr = strtok_r(arg, ", ", &arg); cntr != NULL;
2959              cntr = strtok_r(NULL, ", ", &arg)) {
2960             uint16_t id = atoi(cntr);
2961
2962             ofpbuf_put(ofpacts, &id, sizeof id);
2963             ids = ofpacts->header;
2964             ids->n_controllers++;
2965         }
2966         if (!ids->n_controllers) {
2967             return xstrdup("dec_ttl_cnt_ids: expected at least one controller "
2968                            "id.");
2969         }
2970         ofpact_update_len(ofpacts, &ids->ofpact);
2971     }
2972     return NULL;
2973 }
2974
2975 static void
2976 format_DEC_TTL(const struct ofpact_cnt_ids *a, struct ds *s)
2977 {
2978     size_t i;
2979
2980     ds_put_cstr(s, "dec_ttl");
2981     if (a->ofpact.raw == NXAST_RAW_DEC_TTL_CNT_IDS) {
2982         ds_put_cstr(s, "(");
2983         for (i = 0; i < a->n_controllers; i++) {
2984             if (i) {
2985                 ds_put_cstr(s, ",");
2986             }
2987             ds_put_format(s, "%"PRIu16, a->cnt_ids[i]);
2988         }
2989         ds_put_cstr(s, ")");
2990     }
2991 }
2992 \f
2993 /* Set MPLS label actions. */
2994
2995 static enum ofperr
2996 decode_OFPAT_RAW_SET_MPLS_LABEL(ovs_be32 label,
2997                                 enum ofp_version ofp_version OVS_UNUSED,
2998                                 struct ofpbuf *out)
2999 {
3000     ofpact_put_SET_MPLS_LABEL(out)->label = label;
3001     return 0;
3002 }
3003
3004 static void
3005 encode_SET_MPLS_LABEL(const struct ofpact_mpls_label *label,
3006                       enum ofp_version ofp_version,
3007                                   struct ofpbuf *out)
3008 {
3009     if (ofp_version < OFP12_VERSION) {
3010         put_OFPAT_SET_MPLS_LABEL(out, ofp_version, label->label);
3011     } else {
3012         ofpact_put_set_field(out, ofp_version, MFF_MPLS_LABEL,
3013                              ntohl(label->label));
3014     }
3015 }
3016
3017 static char * OVS_WARN_UNUSED_RESULT
3018 parse_SET_MPLS_LABEL(char *arg, struct ofpbuf *ofpacts,
3019                      enum ofputil_protocol *usable_protocols OVS_UNUSED)
3020 {
3021     struct ofpact_mpls_label *mpls_label = ofpact_put_SET_MPLS_LABEL(ofpacts);
3022     if (*arg == '\0') {
3023         return xstrdup("set_mpls_label: expected label.");
3024     }
3025
3026     mpls_label->label = htonl(atoi(arg));
3027     return NULL;
3028 }
3029
3030 static void
3031 format_SET_MPLS_LABEL(const struct ofpact_mpls_label *a, struct ds *s)
3032 {
3033     ds_put_format(s, "set_mpls_label(%"PRIu32")", ntohl(a->label));
3034 }
3035 \f
3036 /* Set MPLS TC actions. */
3037
3038 static enum ofperr
3039 decode_OFPAT_RAW_SET_MPLS_TC(uint8_t tc,
3040                              enum ofp_version ofp_version OVS_UNUSED,
3041                              struct ofpbuf *out)
3042 {
3043     ofpact_put_SET_MPLS_TC(out)->tc = tc;
3044     return 0;
3045 }
3046
3047 static void
3048 encode_SET_MPLS_TC(const struct ofpact_mpls_tc *tc,
3049                    enum ofp_version ofp_version, struct ofpbuf *out)
3050 {
3051     if (ofp_version < OFP12_VERSION) {
3052         put_OFPAT_SET_MPLS_TC(out, ofp_version, tc->tc);
3053     } else {
3054         ofpact_put_set_field(out, ofp_version, MFF_MPLS_TC, tc->tc);
3055     }
3056 }
3057
3058 static char * OVS_WARN_UNUSED_RESULT
3059 parse_SET_MPLS_TC(char *arg, struct ofpbuf *ofpacts,
3060                   enum ofputil_protocol *usable_protocols OVS_UNUSED)
3061 {
3062     struct ofpact_mpls_tc *mpls_tc = ofpact_put_SET_MPLS_TC(ofpacts);
3063
3064     if (*arg == '\0') {
3065         return xstrdup("set_mpls_tc: expected tc.");
3066     }
3067
3068     mpls_tc->tc = atoi(arg);
3069     return NULL;
3070 }
3071
3072 static void
3073 format_SET_MPLS_TC(const struct ofpact_mpls_tc *a, struct ds *s)
3074 {
3075     ds_put_format(s, "set_mpls_ttl(%"PRIu8")", a->tc);
3076 }
3077 \f
3078 /* Set MPLS TTL actions. */
3079
3080 static enum ofperr
3081 decode_OFPAT_RAW_SET_MPLS_TTL(uint8_t ttl,
3082                               enum ofp_version ofp_version OVS_UNUSED,
3083                               struct ofpbuf *out)
3084 {
3085     ofpact_put_SET_MPLS_TTL(out)->ttl = ttl;
3086     return 0;
3087 }
3088
3089 static void
3090 encode_SET_MPLS_TTL(const struct ofpact_mpls_ttl *ttl,
3091                     enum ofp_version ofp_version, struct ofpbuf *out)
3092 {
3093     put_OFPAT_SET_MPLS_TTL(out, ofp_version, ttl->ttl);
3094 }
3095
3096 /* Parses 'arg' as the argument to a "set_mpls_ttl" action, and appends such an
3097  * action to 'ofpacts'.
3098  *
3099  * Returns NULL if successful, otherwise a malloc()'d string describing the
3100  * error.  The caller is responsible for freeing the returned string. */
3101 static char * OVS_WARN_UNUSED_RESULT
3102 parse_SET_MPLS_TTL(char *arg, struct ofpbuf *ofpacts,
3103                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
3104 {
3105     struct ofpact_mpls_ttl *mpls_ttl = ofpact_put_SET_MPLS_TTL(ofpacts);
3106
3107     if (*arg == '\0') {
3108         return xstrdup("set_mpls_ttl: expected ttl.");
3109     }
3110
3111     mpls_ttl->ttl = atoi(arg);
3112     return NULL;
3113 }
3114
3115 static void
3116 format_SET_MPLS_TTL(const struct ofpact_mpls_ttl *a, struct ds *s)
3117 {
3118     ds_put_format(s, "set_mpls_ttl(%"PRIu8")", a->ttl);
3119 }
3120 \f
3121 /* Decrement MPLS TTL actions. */
3122
3123 static enum ofperr
3124 decode_OFPAT_RAW_DEC_MPLS_TTL(struct ofpbuf *out)
3125 {
3126     ofpact_put_DEC_MPLS_TTL(out);
3127     return 0;
3128 }
3129
3130 static void
3131 encode_DEC_MPLS_TTL(const struct ofpact_null *null OVS_UNUSED,
3132                     enum ofp_version ofp_version, struct ofpbuf *out)
3133 {
3134     put_OFPAT_DEC_MPLS_TTL(out, ofp_version);
3135 }
3136
3137 static char * OVS_WARN_UNUSED_RESULT
3138 parse_DEC_MPLS_TTL(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
3139                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
3140 {
3141     ofpact_put_DEC_MPLS_TTL(ofpacts);
3142     return NULL;
3143 }
3144
3145 static void
3146 format_DEC_MPLS_TTL(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
3147 {
3148     ds_put_cstr(s, "dec_mpls_ttl");
3149 }
3150 \f
3151 /* Push MPLS label action. */
3152
3153 static enum ofperr
3154 decode_OFPAT_RAW_PUSH_MPLS(ovs_be16 ethertype,
3155                            enum ofp_version ofp_version OVS_UNUSED,
3156                            struct ofpbuf *out)
3157 {
3158     struct ofpact_push_mpls *oam;
3159
3160     if (!eth_type_mpls(ethertype)) {
3161         return OFPERR_OFPBAC_BAD_ARGUMENT;
3162     }
3163     oam = ofpact_put_PUSH_MPLS(out);
3164     oam->ethertype = ethertype;
3165
3166     return 0;
3167 }
3168
3169 static void
3170 encode_PUSH_MPLS(const struct ofpact_push_mpls *push_mpls,
3171                  enum ofp_version ofp_version, struct ofpbuf *out)
3172 {
3173     put_OFPAT_PUSH_MPLS(out, ofp_version, push_mpls->ethertype);
3174 }
3175
3176 static char * OVS_WARN_UNUSED_RESULT
3177 parse_PUSH_MPLS(char *arg, struct ofpbuf *ofpacts,
3178                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
3179 {
3180     uint16_t ethertype;
3181     char *error;
3182
3183     error = str_to_u16(arg, "push_mpls", &ethertype);
3184     if (!error) {
3185         ofpact_put_PUSH_MPLS(ofpacts)->ethertype = htons(ethertype);
3186     }
3187     return error;
3188 }
3189
3190 static void
3191 format_PUSH_MPLS(const struct ofpact_push_mpls *a, struct ds *s)
3192 {
3193     ds_put_format(s, "push_mpls:0x%04"PRIx16, ntohs(a->ethertype));
3194 }
3195 \f
3196 /* Pop MPLS label action. */
3197
3198 static enum ofperr
3199 decode_OFPAT_RAW_POP_MPLS(ovs_be16 ethertype,
3200                           enum ofp_version ofp_version OVS_UNUSED,
3201                           struct ofpbuf *out)
3202 {
3203     ofpact_put_POP_MPLS(out)->ethertype = ethertype;
3204     return 0;
3205 }
3206
3207 static void
3208 encode_POP_MPLS(const struct ofpact_pop_mpls *pop_mpls,
3209                 enum ofp_version ofp_version, struct ofpbuf *out)
3210 {
3211     put_OFPAT_POP_MPLS(out, ofp_version, pop_mpls->ethertype);
3212 }
3213
3214 static char * OVS_WARN_UNUSED_RESULT
3215 parse_POP_MPLS(char *arg, struct ofpbuf *ofpacts,
3216                     enum ofputil_protocol *usable_protocols OVS_UNUSED)
3217 {
3218     uint16_t ethertype;
3219     char *error;
3220
3221     error = str_to_u16(arg, "pop_mpls", &ethertype);
3222     if (!error) {
3223         ofpact_put_POP_MPLS(ofpacts)->ethertype = htons(ethertype);
3224     }
3225     return error;
3226 }
3227
3228 static void
3229 format_POP_MPLS(const struct ofpact_pop_mpls *a, struct ds *s)
3230 {
3231     ds_put_format(s, "pop_mpls:0x%04"PRIx16, ntohs(a->ethertype));
3232 }
3233 \f
3234 /* Set tunnel ID actions. */
3235
3236 static enum ofperr
3237 decode_NXAST_RAW_SET_TUNNEL(uint32_t tun_id,
3238                             enum ofp_version ofp_version OVS_UNUSED,
3239                             struct ofpbuf *out)
3240 {
3241     struct ofpact_tunnel *tunnel = ofpact_put_SET_TUNNEL(out);
3242     tunnel->ofpact.raw = NXAST_RAW_SET_TUNNEL;
3243     tunnel->tun_id = tun_id;
3244     return 0;
3245 }
3246
3247 static enum ofperr
3248 decode_NXAST_RAW_SET_TUNNEL64(uint64_t tun_id,
3249                               enum ofp_version ofp_version OVS_UNUSED,
3250                               struct ofpbuf *out)
3251 {
3252     struct ofpact_tunnel *tunnel = ofpact_put_SET_TUNNEL(out);
3253     tunnel->ofpact.raw = NXAST_RAW_SET_TUNNEL64;
3254     tunnel->tun_id = tun_id;
3255     return 0;
3256 }
3257
3258 static void
3259 encode_SET_TUNNEL(const struct ofpact_tunnel *tunnel,
3260                   enum ofp_version ofp_version, struct ofpbuf *out)
3261 {
3262     uint64_t tun_id = tunnel->tun_id;
3263
3264     if (ofp_version < OFP12_VERSION) {
3265         if (tun_id <= UINT32_MAX
3266             && tunnel->ofpact.raw != NXAST_RAW_SET_TUNNEL64) {
3267             put_NXAST_SET_TUNNEL(out, tun_id);
3268         } else {
3269             put_NXAST_SET_TUNNEL64(out, tun_id);
3270         }
3271     } else {
3272         ofpact_put_set_field(out, ofp_version, MFF_TUN_ID, tun_id);
3273     }
3274 }
3275
3276 static char * OVS_WARN_UNUSED_RESULT
3277 parse_set_tunnel(char *arg, struct ofpbuf *ofpacts,
3278                  enum ofp_raw_action_type raw)
3279 {
3280     struct ofpact_tunnel *tunnel;
3281
3282     tunnel = ofpact_put_SET_TUNNEL(ofpacts);
3283     tunnel->ofpact.raw = raw;
3284     return str_to_u64(arg, &tunnel->tun_id);
3285 }
3286
3287 static char * OVS_WARN_UNUSED_RESULT
3288 parse_SET_TUNNEL(char *arg, struct ofpbuf *ofpacts,
3289                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
3290 {
3291     return parse_set_tunnel(arg, ofpacts, NXAST_RAW_SET_TUNNEL);
3292 }
3293
3294 static void
3295 format_SET_TUNNEL(const struct ofpact_tunnel *a, struct ds *s)
3296 {
3297     ds_put_format(s, "set_tunnel%s:%#"PRIx64,
3298                   (a->tun_id > UINT32_MAX
3299                    || a->ofpact.raw == NXAST_RAW_SET_TUNNEL64 ? "64" : ""),
3300                   a->tun_id);
3301 }
3302 \f
3303 /* Set queue action. */
3304
3305 static enum ofperr
3306 decode_OFPAT_RAW_SET_QUEUE(uint32_t queue_id,
3307                            enum ofp_version ofp_version OVS_UNUSED,
3308                            struct ofpbuf *out)
3309 {
3310     ofpact_put_SET_QUEUE(out)->queue_id = queue_id;
3311     return 0;
3312 }
3313
3314 static void
3315 encode_SET_QUEUE(const struct ofpact_queue *queue,
3316                  enum ofp_version ofp_version, struct ofpbuf *out)
3317 {
3318     put_OFPAT_SET_QUEUE(out, ofp_version, queue->queue_id);
3319 }
3320
3321 static char * OVS_WARN_UNUSED_RESULT
3322 parse_SET_QUEUE(char *arg, struct ofpbuf *ofpacts,
3323                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
3324 {
3325     return str_to_u32(arg, &ofpact_put_SET_QUEUE(ofpacts)->queue_id);
3326 }
3327
3328 static void
3329 format_SET_QUEUE(const struct ofpact_queue *a, struct ds *s)
3330 {
3331     ds_put_format(s, "set_queue:%"PRIu32, a->queue_id);
3332 }
3333 \f
3334 /* Pop queue action. */
3335
3336 static enum ofperr
3337 decode_NXAST_RAW_POP_QUEUE(struct ofpbuf *out)
3338 {
3339     ofpact_put_POP_QUEUE(out);
3340     return 0;
3341 }
3342
3343 static void
3344 encode_POP_QUEUE(const struct ofpact_null *null OVS_UNUSED,
3345                  enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
3346 {
3347     put_NXAST_POP_QUEUE(out);
3348 }
3349
3350 static char * OVS_WARN_UNUSED_RESULT
3351 parse_POP_QUEUE(const char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
3352                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
3353 {
3354     ofpact_put_POP_QUEUE(ofpacts);
3355     return NULL;
3356 }
3357
3358 static void
3359 format_POP_QUEUE(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
3360 {
3361     ds_put_cstr(s, "pop_queue");
3362 }
3363 \f
3364 /* Action structure for NXAST_FIN_TIMEOUT.
3365  *
3366  * This action changes the idle timeout or hard timeout, or both, of this
3367  * OpenFlow rule when the rule matches a TCP packet with the FIN or RST flag.
3368  * When such a packet is observed, the action reduces the rule's idle timeout
3369  * to 'fin_idle_timeout' and its hard timeout to 'fin_hard_timeout'.  This
3370  * action has no effect on an existing timeout that is already shorter than the
3371  * one that the action specifies.  A 'fin_idle_timeout' or 'fin_hard_timeout'
3372  * of zero has no effect on the respective timeout.
3373  *
3374  * 'fin_idle_timeout' and 'fin_hard_timeout' are measured in seconds.
3375  * 'fin_hard_timeout' specifies time since the flow's creation, not since the
3376  * receipt of the FIN or RST.
3377  *
3378  * This is useful for quickly discarding learned TCP flows that otherwise will
3379  * take a long time to expire.
3380  *
3381  * This action is intended for use with an OpenFlow rule that matches only a
3382  * single TCP flow.  If the rule matches multiple TCP flows (e.g. it wildcards
3383  * all TCP traffic, or all TCP traffic to a particular port), then any FIN or
3384  * RST in any of those flows will cause the entire OpenFlow rule to expire
3385  * early, which is not normally desirable.
3386  */
3387 struct nx_action_fin_timeout {
3388     ovs_be16 type;              /* OFPAT_VENDOR. */
3389     ovs_be16 len;               /* 16. */
3390     ovs_be32 vendor;            /* NX_VENDOR_ID. */
3391     ovs_be16 subtype;           /* NXAST_FIN_TIMEOUT. */
3392     ovs_be16 fin_idle_timeout;  /* New idle timeout, if nonzero. */
3393     ovs_be16 fin_hard_timeout;  /* New hard timeout, if nonzero. */
3394     ovs_be16 pad;               /* Must be zero. */
3395 };
3396 OFP_ASSERT(sizeof(struct nx_action_fin_timeout) == 16);
3397
3398 static enum ofperr
3399 decode_NXAST_RAW_FIN_TIMEOUT(const struct nx_action_fin_timeout *naft,
3400                              enum ofp_version ofp_version OVS_UNUSED,
3401                              struct ofpbuf *out)
3402 {
3403     struct ofpact_fin_timeout *oft;
3404
3405     oft = ofpact_put_FIN_TIMEOUT(out);
3406     oft->fin_idle_timeout = ntohs(naft->fin_idle_timeout);
3407     oft->fin_hard_timeout = ntohs(naft->fin_hard_timeout);
3408     return 0;
3409 }
3410
3411 static void
3412 encode_FIN_TIMEOUT(const struct ofpact_fin_timeout *fin_timeout,
3413                    enum ofp_version ofp_version OVS_UNUSED,
3414                    struct ofpbuf *out)
3415 {
3416     struct nx_action_fin_timeout *naft = put_NXAST_FIN_TIMEOUT(out);
3417     naft->fin_idle_timeout = htons(fin_timeout->fin_idle_timeout);
3418     naft->fin_hard_timeout = htons(fin_timeout->fin_hard_timeout);
3419 }
3420
3421 static char * OVS_WARN_UNUSED_RESULT
3422 parse_FIN_TIMEOUT(char *arg, struct ofpbuf *ofpacts,
3423                   enum ofputil_protocol *usable_protocols OVS_UNUSED)
3424 {
3425     struct ofpact_fin_timeout *oft = ofpact_put_FIN_TIMEOUT(ofpacts);
3426     char *key, *value;
3427
3428     while (ofputil_parse_key_value(&arg, &key, &value)) {
3429         char *error;
3430
3431         if (!strcmp(key, "idle_timeout")) {
3432             error =  str_to_u16(value, key, &oft->fin_idle_timeout);
3433         } else if (!strcmp(key, "hard_timeout")) {
3434             error = str_to_u16(value, key, &oft->fin_hard_timeout);
3435         } else {
3436             error = xasprintf("invalid key '%s' in 'fin_timeout' argument",
3437                               key);
3438         }
3439
3440         if (error) {
3441             return error;
3442         }
3443     }
3444     return NULL;
3445 }
3446
3447 static void
3448 format_FIN_TIMEOUT(const struct ofpact_fin_timeout *a, struct ds *s)
3449 {
3450     ds_put_cstr(s, "fin_timeout(");
3451     if (a->fin_idle_timeout) {
3452         ds_put_format(s, "idle_timeout=%"PRIu16",", a->fin_idle_timeout);
3453     }
3454     if (a->fin_hard_timeout) {
3455         ds_put_format(s, "hard_timeout=%"PRIu16",", a->fin_hard_timeout);
3456     }
3457     ds_chomp(s, ',');
3458     ds_put_char(s, ')');
3459 }
3460 \f
3461 /* Action structures for NXAST_RESUBMIT and NXAST_RESUBMIT_TABLE.
3462  *
3463  * These actions search one of the switch's flow tables:
3464  *
3465  *    - For NXAST_RESUBMIT_TABLE only, if the 'table' member is not 255, then
3466  *      it specifies the table to search.
3467  *
3468  *    - Otherwise (for NXAST_RESUBMIT_TABLE with a 'table' of 255, or for
3469  *      NXAST_RESUBMIT regardless of 'table'), it searches the current flow
3470  *      table, that is, the OpenFlow flow table that contains the flow from
3471  *      which this action was obtained.  If this action did not come from a
3472  *      flow table (e.g. it came from an OFPT_PACKET_OUT message), then table 0
3473  *      is the current table.
3474  *
3475  * The flow table lookup uses a flow that may be slightly modified from the
3476  * original lookup:
3477  *
3478  *    - For NXAST_RESUBMIT, the 'in_port' member of struct nx_action_resubmit
3479  *      is used as the flow's in_port.
3480  *
3481  *    - For NXAST_RESUBMIT_TABLE, if the 'in_port' member is not OFPP_IN_PORT,
3482  *      then its value is used as the flow's in_port.  Otherwise, the original
3483  *      in_port is used.
3484  *
3485  *    - If actions that modify the flow (e.g. OFPAT_SET_VLAN_VID) precede the
3486  *      resubmit action, then the flow is updated with the new values.
3487  *
3488  * Following the lookup, the original in_port is restored.
3489  *
3490  * If the modified flow matched in the flow table, then the corresponding
3491  * actions are executed.  Afterward, actions following the resubmit in the
3492  * original set of actions, if any, are executed; any changes made to the
3493  * packet (e.g. changes to VLAN) by secondary actions persist when those
3494  * actions are executed, although the original in_port is restored.
3495  *
3496  * Resubmit actions may be used any number of times within a set of actions.
3497  *
3498  * Resubmit actions may nest to an implementation-defined depth.  Beyond this
3499  * implementation-defined depth, further resubmit actions are simply ignored.
3500  *
3501  * NXAST_RESUBMIT ignores 'table' and 'pad'.  NXAST_RESUBMIT_TABLE requires
3502  * 'pad' to be all-bits-zero.
3503  *
3504  * Open vSwitch 1.0.1 and earlier did not support recursion.  Open vSwitch
3505  * before 1.2.90 did not support NXAST_RESUBMIT_TABLE.
3506  */
3507 struct nx_action_resubmit {
3508     ovs_be16 type;                  /* OFPAT_VENDOR. */
3509     ovs_be16 len;                   /* Length is 16. */
3510     ovs_be32 vendor;                /* NX_VENDOR_ID. */
3511     ovs_be16 subtype;               /* NXAST_RESUBMIT. */
3512     ovs_be16 in_port;               /* New in_port for checking flow table. */
3513     uint8_t table;                  /* NXAST_RESUBMIT_TABLE: table to use. */
3514     uint8_t pad[3];
3515 };
3516 OFP_ASSERT(sizeof(struct nx_action_resubmit) == 16);
3517
3518 static enum ofperr
3519 decode_NXAST_RAW_RESUBMIT(uint16_t port,
3520                           enum ofp_version ofp_version OVS_UNUSED,
3521                           struct ofpbuf *out)
3522 {
3523     struct ofpact_resubmit *resubmit;
3524
3525     resubmit = ofpact_put_RESUBMIT(out);
3526     resubmit->ofpact.raw = NXAST_RAW_RESUBMIT;
3527     resubmit->in_port = u16_to_ofp(port);
3528     resubmit->table_id = 0xff;
3529     return 0;
3530 }
3531
3532 static enum ofperr
3533 decode_NXAST_RAW_RESUBMIT_TABLE(const struct nx_action_resubmit *nar,
3534                                 enum ofp_version ofp_version OVS_UNUSED,
3535                                 struct ofpbuf *out)
3536 {
3537     struct ofpact_resubmit *resubmit;
3538
3539     if (nar->pad[0] || nar->pad[1] || nar->pad[2]) {
3540         return OFPERR_OFPBAC_BAD_ARGUMENT;
3541     }
3542
3543     resubmit = ofpact_put_RESUBMIT(out);
3544     resubmit->ofpact.raw = NXAST_RAW_RESUBMIT_TABLE;
3545     resubmit->in_port = u16_to_ofp(ntohs(nar->in_port));
3546     resubmit->table_id = nar->table;
3547     return 0;
3548 }
3549
3550 static void
3551 encode_RESUBMIT(const struct ofpact_resubmit *resubmit,
3552                 enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
3553 {
3554     uint16_t in_port = ofp_to_u16(resubmit->in_port);
3555
3556     if (resubmit->table_id == 0xff
3557         && resubmit->ofpact.raw != NXAST_RAW_RESUBMIT_TABLE) {
3558         put_NXAST_RESUBMIT(out, in_port);
3559     } else {
3560         struct nx_action_resubmit *nar = put_NXAST_RESUBMIT_TABLE(out);
3561         nar->table = resubmit->table_id;
3562         nar->in_port = htons(in_port);
3563     }
3564 }
3565
3566 static char * OVS_WARN_UNUSED_RESULT
3567 parse_RESUBMIT(char *arg, struct ofpbuf *ofpacts,
3568                enum ofputil_protocol *usable_protocols OVS_UNUSED)
3569 {
3570     struct ofpact_resubmit *resubmit;
3571     char *in_port_s, *table_s;
3572
3573     resubmit = ofpact_put_RESUBMIT(ofpacts);
3574
3575     in_port_s = strsep(&arg, ",");
3576     if (in_port_s && in_port_s[0]) {
3577         if (!ofputil_port_from_string(in_port_s, &resubmit->in_port)) {
3578             return xasprintf("%s: resubmit to unknown port", in_port_s);
3579         }
3580     } else {
3581         resubmit->in_port = OFPP_IN_PORT;
3582     }
3583
3584     table_s = strsep(&arg, ",");
3585     if (table_s && table_s[0]) {
3586         uint32_t table_id = 0;
3587         char *error;
3588
3589         error = str_to_u32(table_s, &table_id);
3590         if (error) {
3591             return error;
3592         }
3593         resubmit->table_id = table_id;
3594     } else {
3595         resubmit->table_id = 255;
3596     }
3597
3598     if (resubmit->in_port == OFPP_IN_PORT && resubmit->table_id == 255) {
3599         return xstrdup("at least one \"in_port\" or \"table\" must be "
3600                        "specified  on resubmit");
3601     }
3602     return NULL;
3603 }
3604
3605 static void
3606 format_RESUBMIT(const struct ofpact_resubmit *a, struct ds *s)
3607 {
3608     if (a->in_port != OFPP_IN_PORT && a->table_id == 255) {
3609         ds_put_cstr(s, "resubmit:");
3610         ofputil_format_port(a->in_port, s);
3611     } else {
3612         ds_put_format(s, "resubmit(");
3613         if (a->in_port != OFPP_IN_PORT) {
3614             ofputil_format_port(a->in_port, s);
3615         }
3616         ds_put_char(s, ',');
3617         if (a->table_id != 255) {
3618             ds_put_format(s, "%"PRIu8, a->table_id);
3619         }
3620         ds_put_char(s, ')');
3621     }
3622 }
3623 \f
3624 /* Action structure for NXAST_LEARN.
3625  *
3626  * This action adds or modifies a flow in an OpenFlow table, similar to
3627  * OFPT_FLOW_MOD with OFPFC_MODIFY_STRICT as 'command'.  The new flow has the
3628  * specified idle timeout, hard timeout, priority, cookie, and flags.  The new
3629  * flow's match criteria and actions are built by applying each of the series
3630  * of flow_mod_spec elements included as part of the action.
3631  *
3632  * A flow_mod_spec starts with a 16-bit header.  A header that is all-bits-0 is
3633  * a no-op used for padding the action as a whole to a multiple of 8 bytes in
3634  * length.  Otherwise, the flow_mod_spec can be thought of as copying 'n_bits'
3635  * bits from a source to a destination.  In this case, the header contains
3636  * multiple fields:
3637  *
3638  *  15  14  13 12  11 10                              0
3639  * +------+---+------+---------------------------------+
3640  * |   0  |src|  dst |             n_bits              |
3641  * +------+---+------+---------------------------------+
3642  *
3643  * The meaning and format of a flow_mod_spec depends on 'src' and 'dst'.  The
3644  * following table summarizes the meaning of each possible combination.
3645  * Details follow the table:
3646  *
3647  *   src dst  meaning
3648  *   --- ---  ----------------------------------------------------------
3649  *    0   0   Add match criteria based on value in a field.
3650  *    1   0   Add match criteria based on an immediate value.
3651  *    0   1   Add NXAST_REG_LOAD action to copy field into a different field.
3652  *    1   1   Add NXAST_REG_LOAD action to load immediate value into a field.
3653  *    0   2   Add OFPAT_OUTPUT action to output to port from specified field.
3654  *   All other combinations are undefined and not allowed.
3655  *
3656  * The flow_mod_spec header is followed by a source specification and a
3657  * destination specification.  The format and meaning of the source
3658  * specification depends on 'src':
3659  *
3660  *   - If 'src' is 0, the source bits are taken from a field in the flow to
3661  *     which this action is attached.  (This should be a wildcarded field.  If
3662  *     its value is fully specified then the source bits being copied have
3663  *     constant values.)
3664  *
3665  *     The source specification is an ovs_be32 'field' and an ovs_be16 'ofs'.
3666  *     'field' is an nxm_header with nxm_hasmask=0, and 'ofs' the starting bit
3667  *     offset within that field.  The source bits are field[ofs:ofs+n_bits-1].
3668  *     'field' and 'ofs' are subject to the same restrictions as the source
3669  *     field in NXAST_REG_MOVE.
3670  *
3671  *   - If 'src' is 1, the source bits are a constant value.  The source
3672  *     specification is (n_bits+15)/16*2 bytes long.  Taking those bytes as a
3673  *     number in network order, the source bits are the 'n_bits'
3674  *     least-significant bits.  The switch will report an error if other bits
3675  *     in the constant are nonzero.
3676  *
3677  * The flow_mod_spec destination specification, for 'dst' of 0 or 1, is an
3678  * ovs_be32 'field' and an ovs_be16 'ofs'.  'field' is an nxm_header with
3679  * nxm_hasmask=0 and 'ofs' is a starting bit offset within that field.  The
3680  * meaning of the flow_mod_spec depends on 'dst':
3681  *
3682  *   - If 'dst' is 0, the flow_mod_spec specifies match criteria for the new
3683  *     flow.  The new flow matches only if bits field[ofs:ofs+n_bits-1] in a
3684  *     packet equal the source bits.  'field' may be any nxm_header with
3685  *     nxm_hasmask=0 that is allowed in NXT_FLOW_MOD.
3686  *
3687  *     Order is significant.  Earlier flow_mod_specs must satisfy any
3688  *     prerequisites for matching fields specified later, by copying constant
3689  *     values into prerequisite fields.
3690  *
3691  *     The switch will reject flow_mod_specs that do not satisfy NXM masking
3692  *     restrictions.
3693  *
3694  *   - If 'dst' is 1, the flow_mod_spec specifies an NXAST_REG_LOAD action for
3695  *     the new flow.  The new flow copies the source bits into
3696  *     field[ofs:ofs+n_bits-1].  Actions are executed in the same order as the
3697  *     flow_mod_specs.
3698  *
3699  *     A single NXAST_REG_LOAD action writes no more than 64 bits, so n_bits
3700  *     greater than 64 yields multiple NXAST_REG_LOAD actions.
3701  *
3702  * The flow_mod_spec destination spec for 'dst' of 2 (when 'src' is 0) is
3703  * empty.  It has the following meaning:
3704  *
3705  *   - The flow_mod_spec specifies an OFPAT_OUTPUT action for the new flow.
3706  *     The new flow outputs to the OpenFlow port specified by the source field.
3707  *     Of the special output ports with value OFPP_MAX or larger, OFPP_IN_PORT,
3708  *     OFPP_FLOOD, OFPP_LOCAL, and OFPP_ALL are supported.  Other special ports
3709  *     may not be used.
3710  *
3711  * Resource Management
3712  * -------------------
3713  *
3714  * A switch has a finite amount of flow table space available for learning.
3715  * When this space is exhausted, no new learning table entries will be learned
3716  * until some existing flow table entries expire.  The controller should be
3717  * prepared to handle this by flooding (which can be implemented as a
3718  * low-priority flow).
3719  *
3720  * If a learned flow matches a single TCP stream with a relatively long
3721  * timeout, one may make the best of resource constraints by setting
3722  * 'fin_idle_timeout' or 'fin_hard_timeout' (both measured in seconds), or
3723  * both, to shorter timeouts.  When either of these is specified as a nonzero
3724  * value, OVS adds a NXAST_FIN_TIMEOUT action, with the specified timeouts, to
3725  * the learned flow.
3726  *
3727  * Examples
3728  * --------
3729  *
3730  * The following examples give a prose description of the flow_mod_specs along
3731  * with informal notation for how those would be represented and a hex dump of
3732  * the bytes that would be required.
3733  *
3734  * These examples could work with various nx_action_learn parameters.  Typical
3735  * values would be idle_timeout=OFP_FLOW_PERMANENT, hard_timeout=60,
3736  * priority=OFP_DEFAULT_PRIORITY, flags=0, table_id=10.
3737  *
3738  * 1. Learn input port based on the source MAC, with lookup into
3739  *    NXM_NX_REG1[16:31] by resubmit to in_port=99:
3740  *
3741  *    Match on in_port=99:
3742  *       ovs_be16(src=1, dst=0, n_bits=16),               20 10
3743  *       ovs_be16(99),                                    00 63
3744  *       ovs_be32(NXM_OF_IN_PORT), ovs_be16(0)            00 00 00 02 00 00
3745  *
3746  *    Match Ethernet destination on Ethernet source from packet:
3747  *       ovs_be16(src=0, dst=0, n_bits=48),               00 30
3748  *       ovs_be32(NXM_OF_ETH_SRC), ovs_be16(0)            00 00 04 06 00 00
3749  *       ovs_be32(NXM_OF_ETH_DST), ovs_be16(0)            00 00 02 06 00 00
3750  *
3751  *    Set NXM_NX_REG1[16:31] to the packet's input port:
3752  *       ovs_be16(src=0, dst=1, n_bits=16),               08 10
3753  *       ovs_be32(NXM_OF_IN_PORT), ovs_be16(0)            00 00 00 02 00 00
3754  *       ovs_be32(NXM_NX_REG1), ovs_be16(16)              00 01 02 04 00 10
3755  *
3756  *    Given a packet that arrived on port A with Ethernet source address B,
3757  *    this would set up the flow "in_port=99, dl_dst=B,
3758  *    actions=load:A->NXM_NX_REG1[16..31]".
3759  *
3760  *    In syntax accepted by ovs-ofctl, this action is: learn(in_port=99,
3761  *    NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[],
3762  *    load:NXM_OF_IN_PORT[]->NXM_NX_REG1[16..31])
3763  *
3764  * 2. Output to input port based on the source MAC and VLAN VID, with lookup
3765  *    into NXM_NX_REG1[16:31]:
3766  *
3767  *    Match on same VLAN ID as packet:
3768  *       ovs_be16(src=0, dst=0, n_bits=12),               00 0c
3769  *       ovs_be32(NXM_OF_VLAN_TCI), ovs_be16(0)           00 00 08 02 00 00
3770  *       ovs_be32(NXM_OF_VLAN_TCI), ovs_be16(0)           00 00 08 02 00 00
3771  *
3772  *    Match Ethernet destination on Ethernet source from packet:
3773  *       ovs_be16(src=0, dst=0, n_bits=48),               00 30
3774  *       ovs_be32(NXM_OF_ETH_SRC), ovs_be16(0)            00 00 04 06 00 00
3775  *       ovs_be32(NXM_OF_ETH_DST), ovs_be16(0)            00 00 02 06 00 00
3776  *
3777  *    Output to the packet's input port:
3778  *       ovs_be16(src=0, dst=2, n_bits=16),               10 10
3779  *       ovs_be32(NXM_OF_IN_PORT), ovs_be16(0)            00 00 00 02 00 00
3780  *
3781  *    Given a packet that arrived on port A with Ethernet source address B in
3782  *    VLAN C, this would set up the flow "dl_dst=B, vlan_vid=C,
3783  *    actions=output:A".
3784  *
3785  *    In syntax accepted by ovs-ofctl, this action is:
3786  *    learn(NXM_OF_VLAN_TCI[0..11], NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[],
3787  *    output:NXM_OF_IN_PORT[])
3788  *
3789  * 3. Here's a recipe for a very simple-minded MAC learning switch.  It uses a
3790  *    10-second MAC expiration time to make it easier to see what's going on
3791  *
3792  *      ovs-vsctl del-controller br0
3793  *      ovs-ofctl del-flows br0
3794  *      ovs-ofctl add-flow br0 "table=0 actions=learn(table=1, \
3795           hard_timeout=10, NXM_OF_VLAN_TCI[0..11],             \
3796           NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[],                   \
3797           output:NXM_OF_IN_PORT[]), resubmit(,1)"
3798  *      ovs-ofctl add-flow br0 "table=1 priority=0 actions=flood"
3799  *
3800  *    You can then dump the MAC learning table with:
3801  *
3802  *      ovs-ofctl dump-flows br0 table=1
3803  *
3804  * Usage Advice
3805  * ------------
3806  *
3807  * For best performance, segregate learned flows into a table that is not used
3808  * for any other flows except possibly for a lowest-priority "catch-all" flow
3809  * (a flow with no match criteria).  If different learning actions specify
3810  * different match criteria, use different tables for the learned flows.
3811  *
3812  * The meaning of 'hard_timeout' and 'idle_timeout' can be counterintuitive.
3813  * These timeouts apply to the flow that is added, which means that a flow with
3814  * an idle timeout will expire when no traffic has been sent *to* the learned
3815  * address.  This is not usually the intent in MAC learning; instead, we want
3816  * the MAC learn entry to expire when no traffic has been sent *from* the
3817  * learned address.  Use a hard timeout for that.
3818  *
3819  *
3820  * Visibility of Changes
3821  * ---------------------
3822  *
3823  * Prior to Open vSwitch 2.4, any changes made by a "learn" action in a given
3824  * flow translation are visible to flow table lookups made later in the flow
3825  * translation.  This means that, in the example above, a MAC learned by the
3826  * learn action in table 0 would be found in table 1 (if the packet being
3827  * processed had the same source and destination MAC address).
3828  *
3829  * In Open vSwitch 2.4 and later, changes to a flow table (whether to add or
3830  * modify a flow) by a "learn" action are visible only for later flow
3831  * translations, not for later lookups within the same flow translation.  In
3832  * the MAC learning example, a MAC learned by the learn action in table 0 would
3833  * not be found in table 1 if the flow translation would resubmit to table 1
3834  * after the processing of the learn action, meaning that if this MAC had not
3835  * been learned before then the packet would be flooded. */
3836 struct nx_action_learn {
3837     ovs_be16 type;              /* OFPAT_VENDOR. */
3838     ovs_be16 len;               /* At least 24. */
3839     ovs_be32 vendor;            /* NX_VENDOR_ID. */
3840     ovs_be16 subtype;           /* NXAST_LEARN. */
3841     ovs_be16 idle_timeout;      /* Idle time before discarding (seconds). */
3842     ovs_be16 hard_timeout;      /* Max time before discarding (seconds). */
3843     ovs_be16 priority;          /* Priority level of flow entry. */
3844     ovs_be64 cookie;            /* Cookie for new flow. */
3845     ovs_be16 flags;             /* NX_LEARN_F_*. */
3846     uint8_t table_id;           /* Table to insert flow entry. */
3847     uint8_t pad;                /* Must be zero. */
3848     ovs_be16 fin_idle_timeout;  /* Idle timeout after FIN, if nonzero. */
3849     ovs_be16 fin_hard_timeout;  /* Hard timeout after FIN, if nonzero. */
3850     /* Followed by a sequence of flow_mod_spec elements, as described above,
3851      * until the end of the action is reached. */
3852 };
3853 OFP_ASSERT(sizeof(struct nx_action_learn) == 32);
3854
3855 static ovs_be16
3856 get_be16(const void **pp)
3857 {
3858     const ovs_be16 *p = *pp;
3859     ovs_be16 value = *p;
3860     *pp = p + 1;
3861     return value;
3862 }
3863
3864 static ovs_be32
3865 get_be32(const void **pp)
3866 {
3867     const ovs_be32 *p = *pp;
3868     ovs_be32 value = get_unaligned_be32(p);
3869     *pp = p + 1;
3870     return value;
3871 }
3872
3873 static void
3874 get_subfield(int n_bits, const void **p, struct mf_subfield *sf)
3875 {
3876     sf->field = mf_from_nxm_header(ntohl(get_be32(p)));
3877     sf->ofs = ntohs(get_be16(p));
3878     sf->n_bits = n_bits;
3879 }
3880
3881 static unsigned int
3882 learn_min_len(uint16_t header)
3883 {
3884     int n_bits = header & NX_LEARN_N_BITS_MASK;
3885     int src_type = header & NX_LEARN_SRC_MASK;
3886     int dst_type = header & NX_LEARN_DST_MASK;
3887     unsigned int min_len;
3888
3889     min_len = 0;
3890     if (src_type == NX_LEARN_SRC_FIELD) {
3891         min_len += sizeof(ovs_be32); /* src_field */
3892         min_len += sizeof(ovs_be16); /* src_ofs */
3893     } else {
3894         min_len += DIV_ROUND_UP(n_bits, 16);
3895     }
3896     if (dst_type == NX_LEARN_DST_MATCH ||
3897         dst_type == NX_LEARN_DST_LOAD) {
3898         min_len += sizeof(ovs_be32); /* dst_field */
3899         min_len += sizeof(ovs_be16); /* dst_ofs */
3900     }
3901     return min_len;
3902 }
3903
3904 /* Converts 'nal' into a "struct ofpact_learn" and appends that struct to
3905  * 'ofpacts'.  Returns 0 if successful, otherwise an OFPERR_*. */
3906 static enum ofperr
3907 decode_NXAST_RAW_LEARN(const struct nx_action_learn *nal,
3908                        enum ofp_version ofp_version OVS_UNUSED,
3909                        struct ofpbuf *ofpacts)
3910 {
3911     struct ofpact_learn *learn;
3912     const void *p, *end;
3913
3914     if (nal->pad) {
3915         return OFPERR_OFPBAC_BAD_ARGUMENT;
3916     }
3917
3918     learn = ofpact_put_LEARN(ofpacts);
3919
3920     learn->idle_timeout = ntohs(nal->idle_timeout);
3921     learn->hard_timeout = ntohs(nal->hard_timeout);
3922     learn->priority = ntohs(nal->priority);
3923     learn->cookie = nal->cookie;
3924     learn->table_id = nal->table_id;
3925     learn->fin_idle_timeout = ntohs(nal->fin_idle_timeout);
3926     learn->fin_hard_timeout = ntohs(nal->fin_hard_timeout);
3927
3928     learn->flags = ntohs(nal->flags);
3929     if (learn->flags & ~(NX_LEARN_F_SEND_FLOW_REM |
3930                          NX_LEARN_F_DELETE_LEARNED)) {
3931         return OFPERR_OFPBAC_BAD_ARGUMENT;
3932     }
3933
3934     if (learn->table_id == 0xff) {
3935         return OFPERR_OFPBAC_BAD_ARGUMENT;
3936     }
3937
3938     end = (char *) nal + ntohs(nal->len);
3939     for (p = nal + 1; p != end; ) {
3940         struct ofpact_learn_spec *spec;
3941         uint16_t header = ntohs(get_be16(&p));
3942
3943         if (!header) {
3944             break;
3945         }
3946
3947         spec = ofpbuf_put_zeros(ofpacts, sizeof *spec);
3948         learn = ofpacts->header;
3949         learn->n_specs++;
3950
3951         spec->src_type = header & NX_LEARN_SRC_MASK;
3952         spec->dst_type = header & NX_LEARN_DST_MASK;
3953         spec->n_bits = header & NX_LEARN_N_BITS_MASK;
3954
3955         /* Check for valid src and dst type combination. */
3956         if (spec->dst_type == NX_LEARN_DST_MATCH ||
3957             spec->dst_type == NX_LEARN_DST_LOAD ||
3958             (spec->dst_type == NX_LEARN_DST_OUTPUT &&
3959              spec->src_type == NX_LEARN_SRC_FIELD)) {
3960             /* OK. */
3961         } else {
3962             return OFPERR_OFPBAC_BAD_ARGUMENT;
3963         }
3964
3965         /* Check that the arguments don't overrun the end of the action. */
3966         if ((char *) end - (char *) p < learn_min_len(header)) {
3967             return OFPERR_OFPBAC_BAD_LEN;
3968         }
3969
3970         /* Get the source. */
3971         if (spec->src_type == NX_LEARN_SRC_FIELD) {
3972             get_subfield(spec->n_bits, &p, &spec->src);
3973         } else {
3974             int p_bytes = 2 * DIV_ROUND_UP(spec->n_bits, 16);
3975
3976             bitwise_copy(p, p_bytes, 0,
3977                          &spec->src_imm, sizeof spec->src_imm, 0,
3978                          spec->n_bits);
3979             p = (const uint8_t *) p + p_bytes;
3980         }
3981
3982         /* Get the destination. */
3983         if (spec->dst_type == NX_LEARN_DST_MATCH ||
3984             spec->dst_type == NX_LEARN_DST_LOAD) {
3985             get_subfield(spec->n_bits, &p, &spec->dst);
3986         }
3987     }
3988     ofpact_update_len(ofpacts, &learn->ofpact);
3989
3990     if (!is_all_zeros(p, (char *) end - (char *) p)) {
3991         return OFPERR_OFPBAC_BAD_ARGUMENT;
3992     }
3993
3994     return 0;
3995 }
3996
3997 static void
3998 put_be16(struct ofpbuf *b, ovs_be16 x)
3999 {
4000     ofpbuf_put(b, &x, sizeof x);
4001 }
4002
4003 static void
4004 put_be32(struct ofpbuf *b, ovs_be32 x)
4005 {
4006     ofpbuf_put(b, &x, sizeof x);
4007 }
4008
4009 static void
4010 put_u16(struct ofpbuf *b, uint16_t x)
4011 {
4012     put_be16(b, htons(x));
4013 }
4014
4015 static void
4016 put_u32(struct ofpbuf *b, uint32_t x)
4017 {
4018     put_be32(b, htonl(x));
4019 }
4020
4021 static void
4022 encode_LEARN(const struct ofpact_learn *learn,
4023              enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4024 {
4025     const struct ofpact_learn_spec *spec;
4026     struct nx_action_learn *nal;
4027     size_t start_ofs;
4028
4029     start_ofs = out->size;
4030     nal = put_NXAST_LEARN(out);
4031     nal->idle_timeout = htons(learn->idle_timeout);
4032     nal->hard_timeout = htons(learn->hard_timeout);
4033     nal->fin_idle_timeout = htons(learn->fin_idle_timeout);
4034     nal->fin_hard_timeout = htons(learn->fin_hard_timeout);
4035     nal->priority = htons(learn->priority);
4036     nal->cookie = learn->cookie;
4037     nal->flags = htons(learn->flags);
4038     nal->table_id = learn->table_id;
4039
4040     for (spec = learn->specs; spec < &learn->specs[learn->n_specs]; spec++) {
4041         put_u16(out, spec->n_bits | spec->dst_type | spec->src_type);
4042
4043         if (spec->src_type == NX_LEARN_SRC_FIELD) {
4044             put_u32(out, mf_nxm_header(spec->src.field->id));
4045             put_u16(out, spec->src.ofs);
4046         } else {
4047             size_t n_dst_bytes = 2 * DIV_ROUND_UP(spec->n_bits, 16);
4048             uint8_t *bits = ofpbuf_put_zeros(out, n_dst_bytes);
4049             bitwise_copy(&spec->src_imm, sizeof spec->src_imm, 0,
4050                          bits, n_dst_bytes, 0,
4051                          spec->n_bits);
4052         }
4053
4054         if (spec->dst_type == NX_LEARN_DST_MATCH ||
4055             spec->dst_type == NX_LEARN_DST_LOAD) {
4056             put_u32(out, mf_nxm_header(spec->dst.field->id));
4057             put_u16(out, spec->dst.ofs);
4058         }
4059     }
4060
4061     pad_ofpat(out, start_ofs);
4062 }
4063
4064 static char * OVS_WARN_UNUSED_RESULT
4065 parse_LEARN(char *arg, struct ofpbuf *ofpacts,
4066             enum ofputil_protocol *usable_protocols OVS_UNUSED)
4067 {
4068     return learn_parse(arg, ofpacts);
4069 }
4070
4071 static void
4072 format_LEARN(const struct ofpact_learn *a, struct ds *s)
4073 {
4074     learn_format(a, s);
4075 }
4076 \f
4077 /* Action structure for NXAST_CONJUNCTION. */
4078 struct nx_action_conjunction {
4079     ovs_be16 type;                  /* OFPAT_VENDOR. */
4080     ovs_be16 len;                   /* At least 16. */
4081     ovs_be32 vendor;                /* NX_VENDOR_ID. */
4082     ovs_be16 subtype;               /* See enum ofp_raw_action_type. */
4083     uint8_t clause;
4084     uint8_t n_clauses;
4085     ovs_be32 id;
4086 };
4087 OFP_ASSERT(sizeof(struct nx_action_conjunction) == 16);
4088
4089 static void
4090 add_conjunction(struct ofpbuf *out,
4091                 uint32_t id, uint8_t clause, uint8_t n_clauses)
4092 {
4093     struct ofpact_conjunction *oc;
4094
4095     oc = ofpact_put_CONJUNCTION(out);
4096     oc->id = id;
4097     oc->clause = clause;
4098     oc->n_clauses = n_clauses;
4099 }
4100
4101 static enum ofperr
4102 decode_NXAST_RAW_CONJUNCTION(const struct nx_action_conjunction *nac,
4103                              enum ofp_version ofp_version OVS_UNUSED,
4104                              struct ofpbuf *out)
4105 {
4106     if (nac->n_clauses < 2 || nac->n_clauses > 64
4107         || nac->clause >= nac->n_clauses) {
4108         return OFPERR_NXBAC_BAD_CONJUNCTION;
4109     } else {
4110         add_conjunction(out, ntohl(nac->id), nac->clause, nac->n_clauses);
4111         return 0;
4112     }
4113 }
4114
4115 static void
4116 encode_CONJUNCTION(const struct ofpact_conjunction *oc,
4117                    enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4118 {
4119     struct nx_action_conjunction *nac = put_NXAST_CONJUNCTION(out);
4120     nac->clause = oc->clause;
4121     nac->n_clauses = oc->n_clauses;
4122     nac->id = htonl(oc->id);
4123 }
4124
4125 static void
4126 format_CONJUNCTION(const struct ofpact_conjunction *oc, struct ds *s)
4127 {
4128     ds_put_format(s, "conjunction(%"PRIu32",%"PRIu8"/%"PRIu8")",
4129                   oc->id, oc->clause + 1, oc->n_clauses);
4130 }
4131
4132 static char * OVS_WARN_UNUSED_RESULT
4133 parse_CONJUNCTION(const char *arg, struct ofpbuf *ofpacts,
4134                   enum ofputil_protocol *usable_protocols OVS_UNUSED)
4135 {
4136     uint8_t n_clauses;
4137     uint8_t clause;
4138     uint32_t id;
4139     int n;
4140
4141     if (!ovs_scan(arg, "%"SCNi32" , %"SCNu8" / %"SCNu8" %n",
4142                   &id, &clause, &n_clauses, &n) || n != strlen(arg)) {
4143         return xstrdup("\"conjunction\" syntax is \"conjunction(id,i/n)\"");
4144     }
4145
4146     if (n_clauses < 2) {
4147         return xstrdup("conjunction must have at least 2 clauses");
4148     } else if (n_clauses > 64) {
4149         return xstrdup("conjunction must have at most 64 clauses");
4150     } else if (clause < 1) {
4151         return xstrdup("clause index must be positive");
4152     } else if (clause > n_clauses) {
4153         return xstrdup("clause index must be less than or equal to "
4154                        "number of clauses");
4155     }
4156
4157     add_conjunction(ofpacts, id, clause - 1, n_clauses);
4158     return NULL;
4159 }
4160 \f
4161 /* Action structure for NXAST_MULTIPATH.
4162  *
4163  * This action performs the following steps in sequence:
4164  *
4165  *    1. Hashes the fields designated by 'fields', one of NX_HASH_FIELDS_*.
4166  *       Refer to the definition of "enum nx_mp_fields" for details.
4167  *
4168  *       The 'basis' value is used as a universal hash parameter, that is,
4169  *       different values of 'basis' yield different hash functions.  The
4170  *       particular universal hash function used is implementation-defined.
4171  *
4172  *       The hashed fields' values are drawn from the current state of the
4173  *       flow, including all modifications that have been made by actions up to
4174  *       this point.
4175  *
4176  *    2. Applies the multipath link choice algorithm specified by 'algorithm',
4177  *       one of NX_MP_ALG_*.  Refer to the definition of "enum nx_mp_algorithm"
4178  *       for details.
4179  *
4180  *       The output of the algorithm is 'link', an unsigned integer less than
4181  *       or equal to 'max_link'.
4182  *
4183  *       Some algorithms use 'arg' as an additional argument.
4184  *
4185  *    3. Stores 'link' in dst[ofs:ofs+n_bits].  The format and semantics of
4186  *       'dst' and 'ofs_nbits' are similar to those for the NXAST_REG_LOAD
4187  *       action.
4188  *
4189  * The switch will reject actions that have an unknown 'fields', or an unknown
4190  * 'algorithm', or in which ofs+n_bits is greater than the width of 'dst', or
4191  * in which 'max_link' is greater than or equal to 2**n_bits, with error type
4192  * OFPET_BAD_ACTION, code OFPBAC_BAD_ARGUMENT.
4193  */
4194 struct nx_action_multipath {
4195     ovs_be16 type;              /* OFPAT_VENDOR. */
4196     ovs_be16 len;               /* Length is 32. */
4197     ovs_be32 vendor;            /* NX_VENDOR_ID. */
4198     ovs_be16 subtype;           /* NXAST_MULTIPATH. */
4199
4200     /* What fields to hash and how. */
4201     ovs_be16 fields;            /* One of NX_HASH_FIELDS_*. */
4202     ovs_be16 basis;             /* Universal hash parameter. */
4203     ovs_be16 pad0;
4204
4205     /* Multipath link choice algorithm to apply to hash value. */
4206     ovs_be16 algorithm;         /* One of NX_MP_ALG_*. */
4207     ovs_be16 max_link;          /* Number of output links, minus 1. */
4208     ovs_be32 arg;               /* Algorithm-specific argument. */
4209     ovs_be16 pad1;
4210
4211     /* Where to store the result. */
4212     ovs_be16 ofs_nbits;         /* (ofs << 6) | (n_bits - 1). */
4213     ovs_be32 dst;               /* Destination. */
4214 };
4215 OFP_ASSERT(sizeof(struct nx_action_multipath) == 32);
4216
4217 static enum ofperr
4218 decode_NXAST_RAW_MULTIPATH(const struct nx_action_multipath *nam,
4219                            enum ofp_version ofp_version OVS_UNUSED,
4220                            struct ofpbuf *out)
4221 {
4222     uint32_t n_links = ntohs(nam->max_link) + 1;
4223     size_t min_n_bits = log_2_ceil(n_links);
4224     struct ofpact_multipath *mp;
4225
4226     mp = ofpact_put_MULTIPATH(out);
4227     mp->fields = ntohs(nam->fields);
4228     mp->basis = ntohs(nam->basis);
4229     mp->algorithm = ntohs(nam->algorithm);
4230     mp->max_link = ntohs(nam->max_link);
4231     mp->arg = ntohl(nam->arg);
4232     mp->dst.field = mf_from_nxm_header(ntohl(nam->dst));
4233     mp->dst.ofs = nxm_decode_ofs(nam->ofs_nbits);
4234     mp->dst.n_bits = nxm_decode_n_bits(nam->ofs_nbits);
4235
4236     if (!flow_hash_fields_valid(mp->fields)) {
4237         VLOG_WARN_RL(&rl, "unsupported fields %d", (int) mp->fields);
4238         return OFPERR_OFPBAC_BAD_ARGUMENT;
4239     } else if (mp->algorithm != NX_MP_ALG_MODULO_N
4240                && mp->algorithm != NX_MP_ALG_HASH_THRESHOLD
4241                && mp->algorithm != NX_MP_ALG_HRW
4242                && mp->algorithm != NX_MP_ALG_ITER_HASH) {
4243         VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) mp->algorithm);
4244         return OFPERR_OFPBAC_BAD_ARGUMENT;
4245     } else if (mp->dst.n_bits < min_n_bits) {
4246         VLOG_WARN_RL(&rl, "multipath action requires at least %"PRIuSIZE" bits for "
4247                      "%"PRIu32" links", min_n_bits, n_links);
4248         return OFPERR_OFPBAC_BAD_ARGUMENT;
4249     }
4250
4251     return multipath_check(mp, NULL);
4252 }
4253
4254 static void
4255 encode_MULTIPATH(const struct ofpact_multipath *mp,
4256                  enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4257 {
4258     struct nx_action_multipath *nam = put_NXAST_MULTIPATH(out);
4259
4260     nam->fields = htons(mp->fields);
4261     nam->basis = htons(mp->basis);
4262     nam->algorithm = htons(mp->algorithm);
4263     nam->max_link = htons(mp->max_link);
4264     nam->arg = htonl(mp->arg);
4265     nam->ofs_nbits = nxm_encode_ofs_nbits(mp->dst.ofs, mp->dst.n_bits);
4266     nam->dst = htonl(mf_nxm_header(mp->dst.field->id));
4267 }
4268
4269 static char * OVS_WARN_UNUSED_RESULT
4270 parse_MULTIPATH(const char *arg, struct ofpbuf *ofpacts,
4271                 enum ofputil_protocol *usable_protocols OVS_UNUSED)
4272 {
4273     return multipath_parse(ofpact_put_MULTIPATH(ofpacts), arg);
4274 }
4275
4276 static void
4277 format_MULTIPATH(const struct ofpact_multipath *a, struct ds *s)
4278 {
4279     multipath_format(a, s);
4280 }
4281 \f
4282 /* Action structure for NXAST_NOTE.
4283  *
4284  * This action has no effect.  It is variable length.  The switch does not
4285  * attempt to interpret the user-defined 'note' data in any way.  A controller
4286  * can use this action to attach arbitrary metadata to a flow.
4287  *
4288  * This action might go away in the future.
4289  */
4290 struct nx_action_note {
4291     ovs_be16 type;                  /* OFPAT_VENDOR. */
4292     ovs_be16 len;                   /* A multiple of 8, but at least 16. */
4293     ovs_be32 vendor;                /* NX_VENDOR_ID. */
4294     ovs_be16 subtype;               /* NXAST_NOTE. */
4295     uint8_t note[6];                /* Start of user-defined data. */
4296     /* Possibly followed by additional user-defined data. */
4297 };
4298 OFP_ASSERT(sizeof(struct nx_action_note) == 16);
4299
4300 static enum ofperr
4301 decode_NXAST_RAW_NOTE(const struct nx_action_note *nan,
4302                       enum ofp_version ofp_version OVS_UNUSED,
4303                       struct ofpbuf *out)
4304 {
4305     struct ofpact_note *note;
4306     unsigned int length;
4307
4308     length = ntohs(nan->len) - offsetof(struct nx_action_note, note);
4309     note = ofpact_put(out, OFPACT_NOTE,
4310                       offsetof(struct ofpact_note, data) + length);
4311     note->length = length;
4312     memcpy(note->data, nan->note, length);
4313
4314     return 0;
4315 }
4316
4317 static void
4318 encode_NOTE(const struct ofpact_note *note,
4319             enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4320 {
4321     size_t start_ofs = out->size;
4322     struct nx_action_note *nan;
4323     unsigned int remainder;
4324     unsigned int len;
4325
4326     put_NXAST_NOTE(out);
4327     out->size = out->size - sizeof nan->note;
4328
4329     ofpbuf_put(out, note->data, note->length);
4330
4331     len = out->size - start_ofs;
4332     remainder = len % OFP_ACTION_ALIGN;
4333     if (remainder) {
4334         ofpbuf_put_zeros(out, OFP_ACTION_ALIGN - remainder);
4335     }
4336     nan = ofpbuf_at(out, start_ofs, sizeof *nan);
4337     nan->len = htons(out->size - start_ofs);
4338 }
4339
4340 static char * OVS_WARN_UNUSED_RESULT
4341 parse_NOTE(const char *arg, struct ofpbuf *ofpacts,
4342            enum ofputil_protocol *usable_protocols OVS_UNUSED)
4343 {
4344     struct ofpact_note *note;
4345
4346     note = ofpact_put_NOTE(ofpacts);
4347     while (*arg != '\0') {
4348         uint8_t byte;
4349         bool ok;
4350
4351         if (*arg == '.') {
4352             arg++;
4353         }
4354         if (*arg == '\0') {
4355             break;
4356         }
4357
4358         byte = hexits_value(arg, 2, &ok);
4359         if (!ok) {
4360             return xstrdup("bad hex digit in `note' argument");
4361         }
4362         ofpbuf_put(ofpacts, &byte, 1);
4363
4364         note = ofpacts->header;
4365         note->length++;
4366
4367         arg += 2;
4368     }
4369     ofpact_update_len(ofpacts, &note->ofpact);
4370     return NULL;
4371 }
4372
4373 static void
4374 format_NOTE(const struct ofpact_note *a, struct ds *s)
4375 {
4376     size_t i;
4377
4378     ds_put_cstr(s, "note:");
4379     for (i = 0; i < a->length; i++) {
4380         if (i) {
4381             ds_put_char(s, '.');
4382         }
4383         ds_put_format(s, "%02"PRIx8, a->data[i]);
4384     }
4385 }
4386 \f
4387 /* Exit action. */
4388
4389 static enum ofperr
4390 decode_NXAST_RAW_EXIT(struct ofpbuf *out)
4391 {
4392     ofpact_put_EXIT(out);
4393     return 0;
4394 }
4395
4396 static void
4397 encode_EXIT(const struct ofpact_null *null OVS_UNUSED,
4398             enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4399 {
4400     put_NXAST_EXIT(out);
4401 }
4402
4403 static char * OVS_WARN_UNUSED_RESULT
4404 parse_EXIT(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
4405            enum ofputil_protocol *usable_protocols OVS_UNUSED)
4406 {
4407     ofpact_put_EXIT(ofpacts);
4408     return NULL;
4409 }
4410
4411 static void
4412 format_EXIT(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
4413 {
4414     ds_put_cstr(s, "exit");
4415 }
4416 \f
4417 /* Unroll xlate action. */
4418
4419 static void
4420 encode_UNROLL_XLATE(const struct ofpact_unroll_xlate *unroll OVS_UNUSED,
4421                     enum ofp_version ofp_version OVS_UNUSED,
4422                     struct ofpbuf *out OVS_UNUSED)
4423 {
4424     OVS_NOT_REACHED();
4425 }
4426
4427 static char * OVS_WARN_UNUSED_RESULT
4428 parse_UNROLL_XLATE(char *arg OVS_UNUSED, struct ofpbuf *ofpacts OVS_UNUSED,
4429                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
4430 {
4431     OVS_NOT_REACHED();
4432     return NULL;
4433 }
4434
4435 static void
4436 format_UNROLL_XLATE(const struct ofpact_unroll_xlate *a OVS_UNUSED,
4437                     struct ds *s)
4438 {
4439     ds_put_cstr(s, "unroll_xlate");
4440 }
4441 \f
4442 /* Action structure for NXAST_SAMPLE.
4443  *
4444  * Samples matching packets with the given probability and sends them
4445  * each to the set of collectors identified with the given ID.  The
4446  * probability is expressed as a number of packets to be sampled out
4447  * of USHRT_MAX packets, and must be >0.
4448  *
4449  * When sending packet samples to IPFIX collectors, the IPFIX flow
4450  * record sent for each sampled packet is associated with the given
4451  * observation domain ID and observation point ID.  Each IPFIX flow
4452  * record contain the sampled packet's headers when executing this
4453  * rule.  If a sampled packet's headers are modified by previous
4454  * actions in the flow, those modified headers are sent. */
4455 struct nx_action_sample {
4456     ovs_be16 type;                  /* OFPAT_VENDOR. */
4457     ovs_be16 len;                   /* Length is 24. */
4458     ovs_be32 vendor;                /* NX_VENDOR_ID. */
4459     ovs_be16 subtype;               /* NXAST_SAMPLE. */
4460     ovs_be16 probability;           /* Fraction of packets to sample. */
4461     ovs_be32 collector_set_id;      /* ID of collector set in OVSDB. */
4462     ovs_be32 obs_domain_id;         /* ID of sampling observation domain. */
4463     ovs_be32 obs_point_id;          /* ID of sampling observation point. */
4464 };
4465 OFP_ASSERT(sizeof(struct nx_action_sample) == 24);
4466
4467 static enum ofperr
4468 decode_NXAST_RAW_SAMPLE(const struct nx_action_sample *nas,
4469                         enum ofp_version ofp_version OVS_UNUSED,
4470                         struct ofpbuf *out)
4471 {
4472     struct ofpact_sample *sample;
4473
4474     sample = ofpact_put_SAMPLE(out);
4475     sample->probability = ntohs(nas->probability);
4476     sample->collector_set_id = ntohl(nas->collector_set_id);
4477     sample->obs_domain_id = ntohl(nas->obs_domain_id);
4478     sample->obs_point_id = ntohl(nas->obs_point_id);
4479
4480     if (sample->probability == 0) {
4481         return OFPERR_OFPBAC_BAD_ARGUMENT;
4482     }
4483
4484     return 0;
4485 }
4486
4487 static void
4488 encode_SAMPLE(const struct ofpact_sample *sample,
4489               enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
4490 {
4491     struct nx_action_sample *nas;
4492
4493     nas = put_NXAST_SAMPLE(out);
4494     nas->probability = htons(sample->probability);
4495     nas->collector_set_id = htonl(sample->collector_set_id);
4496     nas->obs_domain_id = htonl(sample->obs_domain_id);
4497     nas->obs_point_id = htonl(sample->obs_point_id);
4498 }
4499
4500 /* Parses 'arg' as the argument to a "sample" action, and appends such an
4501  * action to 'ofpacts'.
4502  *
4503  * Returns NULL if successful, otherwise a malloc()'d string describing the
4504  * error.  The caller is responsible for freeing the returned string. */
4505 static char * OVS_WARN_UNUSED_RESULT
4506 parse_SAMPLE(char *arg, struct ofpbuf *ofpacts,
4507              enum ofputil_protocol *usable_protocols OVS_UNUSED)
4508 {
4509     struct ofpact_sample *os = ofpact_put_SAMPLE(ofpacts);
4510     char *key, *value;
4511
4512     while (ofputil_parse_key_value(&arg, &key, &value)) {
4513         char *error = NULL;
4514
4515         if (!strcmp(key, "probability")) {
4516             error = str_to_u16(value, "probability", &os->probability);
4517             if (!error && os->probability == 0) {
4518                 error = xasprintf("invalid probability value \"%s\"", value);
4519             }
4520         } else if (!strcmp(key, "collector_set_id")) {
4521             error = str_to_u32(value, &os->collector_set_id);
4522         } else if (!strcmp(key, "obs_domain_id")) {
4523             error = str_to_u32(value, &os->obs_domain_id);
4524         } else if (!strcmp(key, "obs_point_id")) {
4525             error = str_to_u32(value, &os->obs_point_id);
4526         } else {
4527             error = xasprintf("invalid key \"%s\" in \"sample\" argument",
4528                               key);
4529         }
4530         if (error) {
4531             return error;
4532         }
4533     }
4534     if (os->probability == 0) {
4535         return xstrdup("non-zero \"probability\" must be specified on sample");
4536     }
4537     return NULL;
4538 }
4539
4540 static void
4541 format_SAMPLE(const struct ofpact_sample *a, struct ds *s)
4542 {
4543     ds_put_format(s, "sample(probability=%"PRIu16",collector_set_id=%"PRIu32
4544                   ",obs_domain_id=%"PRIu32",obs_point_id=%"PRIu32")",
4545                   a->probability, a->collector_set_id,
4546                   a->obs_domain_id, a->obs_point_id);
4547 }
4548 \f
4549 /* debug_recirc instruction. */
4550
4551 static bool enable_debug;
4552
4553 void
4554 ofpact_dummy_enable(void)
4555 {
4556     enable_debug = true;
4557 }
4558
4559 static enum ofperr
4560 decode_NXAST_RAW_DEBUG_RECIRC(struct ofpbuf *out)
4561 {
4562     if (!enable_debug) {
4563         return OFPERR_OFPBAC_BAD_VENDOR_TYPE;
4564     }
4565
4566     ofpact_put_DEBUG_RECIRC(out);
4567     return 0;
4568 }
4569
4570 static void
4571 encode_DEBUG_RECIRC(const struct ofpact_null *n OVS_UNUSED,
4572                     enum ofp_version ofp_version OVS_UNUSED,
4573                     struct ofpbuf *out)
4574 {
4575     put_NXAST_DEBUG_RECIRC(out);
4576 }
4577
4578 static char * OVS_WARN_UNUSED_RESULT
4579 parse_DEBUG_RECIRC(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
4580                    enum ofputil_protocol *usable_protocols OVS_UNUSED)
4581 {
4582     ofpact_put_DEBUG_RECIRC(ofpacts);
4583     return NULL;
4584 }
4585
4586 static void
4587 format_DEBUG_RECIRC(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
4588 {
4589     ds_put_cstr(s, "debug_recirc");
4590 }
4591
4592 /* Action structure for NXAST_CT.
4593  *
4594  * Pass traffic to the connection tracker.
4595  *
4596  * There are two important concepts to understanding the connection tracking
4597  * interface: Packet state and Connection state. Packets may be "Untracked" or
4598  * "Tracked". Connections may be "Uncommitted" or "Committed".
4599  *
4600  *   - Packet State:
4601  *
4602  *      Untracked packets have not yet passed through the connection tracker,
4603  *      and the connection state for such packets is unknown. In most cases,
4604  *      packets entering the OpenFlow pipeline will initially be in the
4605  *      untracked state. Untracked packets may become tracked by executing
4606  *      NXAST_CT with a "recirc_table" specified. This makes various aspects
4607  *      about the connection available, in particular the connection state.
4608  *
4609  *      Tracked packets have previously passed through the connection tracker.
4610  *      These packets will remain tracked through until the end of the OpenFlow
4611  *      pipeline. Tracked packets which have NXAST_CT executed with a
4612  *      "recirc_table" specified will return to the tracked state.
4613  *
4614  *      The packet state is only significant for the duration of packet
4615  *      processing within the OpenFlow pipeline.
4616  *
4617  *   - Connection State:
4618  *
4619  *      Multiple packets may be associated with a single connection. Initially,
4620  *      all connections are uncommitted. The connection state corresponding to
4621  *      a packet is available in the NXM_NX_CT_STATE field for tracked packets.
4622  *
4623  *      Uncommitted connections have no state stored about them. Uncommitted
4624  *      connections may transition into the committed state by executing
4625  *      NXAST_CT with the NX_CT_F_COMMIT flag.
4626  *
4627  *      Once a connection becomes committed, information may be gathered about
4628  *      the connection by passing subsequent packets through the connection
4629  *      tracker, and the state of the connection will be stored beyond the
4630  *      lifetime of packet processing.
4631  *
4632  *      Connections may transition back into the uncommitted state due to
4633  *      external timers, or due to the contents of packets that are sent to the
4634  *      connection tracker. This behaviour is outside of the scope of the
4635  *      OpenFlow interface.
4636  *
4637  * The "zone" specifies a context within which the tracking is done:
4638  *
4639  *      The connection tracking zone is a 16-bit number. Each zone is an
4640  *      independent connection tracking context. The connection state for each
4641  *      connection is completely separate for each zone, so if a connection
4642  *      is committed to zone A, then it will remain uncommitted in zone B.
4643  *      If NXAST_CT is executed with the same zone multiple times, later
4644  *      executions have no effect.
4645  *
4646  *      If 'zone_src' is nonzero, this specifies that the zone should be
4647  *      sourced from a field zone_src[ofs:ofs+nbits]. The format and semantics
4648  *      of 'zone_src' and 'zone_ofs_nbits' are similar to those for the
4649  *      NXAST_REG_LOAD action. The acceptable nxm_header values for 'zone_src'
4650  *      are the same as the acceptable nxm_header values for the 'src' field of
4651  *      NXAST_REG_MOVE.
4652  *
4653  *      If 'zone_src' is zero, then the value of 'zone_imm' will be used as the
4654  *      connection tracking zone.
4655  *
4656  * The "recirc_table" allows NXM_NX_CT_* fields to become available:
4657  *
4658  *      If "recirc_table" has a value other than NX_CT_RECIRC_NONE, then the
4659  *      packet will be logically cloned prior to executing this action. One
4660  *      copy will be sent to the connection tracker, then will be re-injected
4661  *      into the OpenFlow pipeline beginning at the OpenFlow table specified in
4662  *      this field. When the packet re-enters the pipeline, the NXM_NX_CT_*
4663  *      fields will be populated. The original instance of the packet will
4664  *      continue the current actions list. This can be thought of as similar to
4665  *      the effect of the "output" action: One copy is sent out (in this case,
4666  *      to the connection tracker), but the current copy continues processing.
4667  *
4668  *      It is strongly recommended that this table is later than the current
4669  *      table, to prevent loops.
4670  *
4671  * The "alg" attaches protocol-specific behaviour to this action:
4672  *
4673  *      The ALG is a 16-bit number which specifies that additional
4674  *      processing should be applied to this traffic.
4675  *
4676  *      Protocol | Value | Meaning
4677  *      --------------------------------------------------------------------
4678  *      None     |     0 | No protocol-specific behaviour.
4679  *      FTP      |    21 | Parse FTP control connections and observe the
4680  *               |       | negotiation of related data connections.
4681  *      Other    | Other | Unsupported protocols.
4682  *
4683  *      By way of example, if FTP control connections have this action applied
4684  *      with the ALG set to FTP (21), then the connection tracker will observe
4685  *      the negotiation of data connections. This allows the connection
4686  *      tracker to identify subsequent data connections as "related" to this
4687  *      existing connection. The "related" flag will be populated in the
4688  *      NXM_NX_CT_STATE field for such connections if the 'recirc_table' is
4689  *      specified.
4690  *
4691  * Zero or more actions may immediately follow this action. These actions will
4692  * be executed within the context of the connection tracker, and they require
4693  * the NX_CT_F_COMMIT flag to be set.
4694  */
4695 struct nx_action_conntrack {
4696     ovs_be16 type;              /* OFPAT_VENDOR. */
4697     ovs_be16 len;               /* At least 24. */
4698     ovs_be32 vendor;            /* NX_VENDOR_ID. */
4699     ovs_be16 subtype;           /* NXAST_CT. */
4700     ovs_be16 flags;             /* Zero or more NX_CT_F_* flags.
4701                                  * Unspecified flag bits must be zero. */
4702     ovs_be32 zone_src;          /* Connection tracking context. */
4703     union {
4704         ovs_be16 zone_ofs_nbits;/* Range to use from source field. */
4705         ovs_be16 zone_imm;      /* Immediate value for zone. */
4706     };
4707     uint8_t recirc_table;       /* Recirculate to a specific table, or
4708                                    NX_CT_RECIRC_NONE for no recirculation. */
4709     uint8_t pad[3];             /* Zeroes */
4710     ovs_be16 alg;               /* Well-known port number for the protocol.
4711                                  * 0 indicates no ALG is required. */
4712     /* Followed by a sequence of zero or more OpenFlow actions. The length of
4713      * these is included in 'len'. */
4714 };
4715 OFP_ASSERT(sizeof(struct nx_action_conntrack) == 24);
4716
4717 static enum ofperr
4718 decode_ct_zone(const struct nx_action_conntrack *nac,
4719                struct ofpact_conntrack *out)
4720 {
4721     if (nac->zone_src) {
4722         enum ofperr error;
4723
4724         out->zone_src.field = mf_from_nxm_header(ntohl(nac->zone_src));
4725         out->zone_src.ofs = nxm_decode_ofs(nac->zone_ofs_nbits);
4726         out->zone_src.n_bits = nxm_decode_n_bits(nac->zone_ofs_nbits);
4727         error = mf_check_src(&out->zone_src, NULL);
4728         if (error) {
4729             return error;
4730         }
4731
4732         if (out->zone_src.n_bits != 16) {
4733             VLOG_WARN_RL(&rl, "zone n_bits %d not within valid range [16..16]",
4734                          out->zone_src.n_bits);
4735             return OFPERR_OFPBAC_BAD_SET_LEN;
4736         }
4737     } else {
4738         out->zone_src.field = NULL;
4739         out->zone_imm = ntohs(nac->zone_imm);
4740     }
4741
4742     return 0;
4743 }
4744
4745 static enum ofperr
4746 decode_NXAST_RAW_CT(const struct nx_action_conntrack *nac,
4747                     enum ofp_version ofp_version, struct ofpbuf *out)
4748 {
4749     const size_t ct_offset = ofpacts_pull(out);
4750     struct ofpact_conntrack *conntrack;
4751     struct ofpbuf openflow;
4752     int error = 0;
4753
4754     conntrack = ofpact_put_CT(out);
4755     conntrack->flags = ntohs(nac->flags);
4756     error = decode_ct_zone(nac, conntrack);
4757     if (error) {
4758         goto out;
4759     }
4760     conntrack->recirc_table = nac->recirc_table;
4761     conntrack->alg = ntohs(nac->alg);
4762
4763     ofpbuf_pull(out, sizeof(*conntrack));
4764
4765     ofpbuf_use_const(&openflow, nac + 1, ntohs(nac->len) - sizeof(*nac));
4766     error = ofpacts_pull_openflow_actions__(&openflow, openflow.size,
4767                                             ofp_version,
4768                                             1u << OVSINST_OFPIT11_APPLY_ACTIONS,
4769                                             out, OFPACT_CT);
4770     if (error) {
4771         goto out;
4772     }
4773
4774     conntrack = ofpbuf_push_uninit(out, sizeof(*conntrack));
4775     out->header = &conntrack->ofpact;
4776     ofpact_update_len(out, &conntrack->ofpact);
4777
4778     if (conntrack->ofpact.len > sizeof(*conntrack)
4779         && !(conntrack->flags & NX_CT_F_COMMIT)) {
4780         VLOG_WARN_RL(&rl, "CT action requires commit flag if actions are "
4781                      "specified.");
4782         error = OFPERR_OFPBAC_BAD_ARGUMENT;
4783     }
4784
4785 out:
4786     ofpbuf_push_uninit(out, ct_offset);
4787     return error;
4788 }
4789
4790 static void
4791 encode_CT(const struct ofpact_conntrack *conntrack,
4792           enum ofp_version ofp_version, struct ofpbuf *out)
4793 {
4794     struct nx_action_conntrack *nac;
4795     const size_t ofs = out->size;
4796     size_t len;
4797
4798     nac = put_NXAST_CT(out);
4799     nac->flags = htons(conntrack->flags);
4800     if (conntrack->zone_src.field) {
4801         nac->zone_src = htonl(mf_nxm_header(conntrack->zone_src.field->id));
4802         nac->zone_ofs_nbits = nxm_encode_ofs_nbits(conntrack->zone_src.ofs,
4803                                                    conntrack->zone_src.n_bits);
4804     } else {
4805         nac->zone_src = htonl(0);
4806         nac->zone_imm = htons(conntrack->zone_imm);
4807     }
4808     nac->recirc_table = conntrack->recirc_table;
4809     nac->alg = htons(conntrack->alg);
4810
4811     len = ofpacts_put_openflow_actions(conntrack->actions,
4812                                        ofpact_ct_get_action_len(conntrack),
4813                                        out, ofp_version);
4814     len += sizeof(*nac);
4815     nac = ofpbuf_at(out, ofs, sizeof(*nac));
4816     nac->len = htons(len);
4817 }
4818
4819 /* Parses 'arg' as the argument to a "ct" action, and appends such an
4820  * action to 'ofpacts'.
4821  *
4822  * Returns NULL if successful, otherwise a malloc()'d string describing the
4823  * error.  The caller is responsible for freeing the returned string. */
4824 static char * OVS_WARN_UNUSED_RESULT
4825 parse_CT(char *arg, struct ofpbuf *ofpacts,
4826          enum ofputil_protocol *usable_protocols)
4827 {
4828     const size_t ct_offset = ofpacts_pull(ofpacts);
4829     struct ofpact_conntrack *oc;
4830     char *error = NULL;
4831     char *key, *value;
4832
4833     oc = ofpact_put_CT(ofpacts);
4834     oc->flags = 0;
4835     oc->recirc_table = NX_CT_RECIRC_NONE;
4836     while (ofputil_parse_key_value(&arg, &key, &value)) {
4837         if (!strcmp(key, "commit")) {
4838             oc->flags |= NX_CT_F_COMMIT;
4839         } else if (!strcmp(key, "table")) {
4840             error = str_to_u8(value, "recirc_table", &oc->recirc_table);
4841             if (!error && oc->recirc_table == NX_CT_RECIRC_NONE) {
4842                 error = xasprintf("invalid table %#"PRIx16, oc->recirc_table);
4843             }
4844         } else if (!strcmp(key, "zone")) {
4845             error = str_to_u16(value, "zone", &oc->zone_imm);
4846
4847             if (error) {
4848                 free(error);
4849                 error = mf_parse_subfield(&oc->zone_src, value);
4850                 if (error) {
4851                     return error;
4852                 }
4853             }
4854         } else if (!strcmp(key, "alg")) {
4855             error = str_to_connhelper(value, &oc->alg);
4856         } else if (!strcmp(key, "exec")) {
4857             /* Hide existing actions from ofpacts_parse_copy(), so the
4858              * nesting can be handled transparently. */
4859             enum ofputil_protocol usable_protocols2;
4860
4861             ofpbuf_pull(ofpacts, sizeof(*oc));
4862             /* Initializes 'usable_protocol2', fold it back to
4863              * '*usable_protocols' afterwards, so that we do not lose
4864              * restrictions already in there. */
4865             error = ofpacts_parse_copy(value, ofpacts, &usable_protocols2,
4866                                        false, OFPACT_CT);
4867             *usable_protocols &= usable_protocols2;
4868             ofpact_pad(ofpacts);
4869             ofpacts->header = ofpbuf_push_uninit(ofpacts, sizeof(*oc));
4870             oc = ofpacts->header;
4871         } else {
4872             error = xasprintf("invalid argument to \"ct\" action: `%s'", key);
4873         }
4874         if (error) {
4875             break;
4876         }
4877     }
4878
4879     ofpact_update_len(ofpacts, &oc->ofpact);
4880     ofpbuf_push_uninit(ofpacts, ct_offset);
4881     return error;
4882 }
4883
4884 static void
4885 format_alg(int port, struct ds *s)
4886 {
4887     if (port == IPPORT_FTP) {
4888         ds_put_format(s, "alg=ftp,");
4889     } else if (port) {
4890         ds_put_format(s, "alg=%d,", port);
4891     }
4892 }
4893
4894 static void
4895 format_CT(const struct ofpact_conntrack *a, struct ds *s)
4896 {
4897     ds_put_cstr(s, "ct(");
4898     if (a->flags & NX_CT_F_COMMIT) {
4899         ds_put_cstr(s, "commit,");
4900     }
4901     if (a->recirc_table != NX_CT_RECIRC_NONE) {
4902         ds_put_format(s, "table=%"PRIu8",", a->recirc_table);
4903     }
4904     if (a->zone_src.field) {
4905         ds_put_format(s, "zone=");
4906         mf_format_subfield(&a->zone_src, s);
4907         ds_put_char(s, ',');
4908     } else if (a->zone_imm) {
4909         ds_put_format(s, "zone=%"PRIu16",", a->zone_imm);
4910     }
4911     if (ofpact_ct_get_action_len(a)) {
4912         ds_put_cstr(s, "exec(");
4913         ofpacts_format(a->actions, ofpact_ct_get_action_len(a), s);
4914         ds_put_format(s, "),");
4915     }
4916     format_alg(a->alg, s);
4917     ds_chomp(s, ',');
4918     ds_put_char(s, ')');
4919 }
4920 \f
4921 /* Meter instruction. */
4922
4923 static void
4924 encode_METER(const struct ofpact_meter *meter,
4925              enum ofp_version ofp_version, struct ofpbuf *out)
4926 {
4927     if (ofp_version >= OFP13_VERSION) {
4928         instruction_put_OFPIT13_METER(out)->meter_id = htonl(meter->meter_id);
4929     }
4930 }
4931
4932 static char * OVS_WARN_UNUSED_RESULT
4933 parse_METER(char *arg, struct ofpbuf *ofpacts,
4934             enum ofputil_protocol *usable_protocols)
4935 {
4936     *usable_protocols &= OFPUTIL_P_OF13_UP;
4937     return str_to_u32(arg, &ofpact_put_METER(ofpacts)->meter_id);
4938 }
4939
4940 static void
4941 format_METER(const struct ofpact_meter *a, struct ds *s)
4942 {
4943     ds_put_format(s, "meter:%"PRIu32, a->meter_id);
4944 }
4945 \f
4946 /* Clear-Actions instruction. */
4947
4948 static void
4949 encode_CLEAR_ACTIONS(const struct ofpact_null *null OVS_UNUSED,
4950                      enum ofp_version ofp_version OVS_UNUSED,
4951                      struct ofpbuf *out OVS_UNUSED)
4952 {
4953     if (ofp_version > OFP10_VERSION) {
4954         instruction_put_OFPIT11_CLEAR_ACTIONS(out);
4955     }
4956 }
4957
4958 static char * OVS_WARN_UNUSED_RESULT
4959 parse_CLEAR_ACTIONS(char *arg OVS_UNUSED, struct ofpbuf *ofpacts,
4960                     enum ofputil_protocol *usable_protocols OVS_UNUSED)
4961 {
4962     ofpact_put_CLEAR_ACTIONS(ofpacts);
4963     return NULL;
4964 }
4965
4966 static void
4967 format_CLEAR_ACTIONS(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
4968 {
4969     ds_put_cstr(s, "clear_actions");
4970 }
4971 \f
4972 /* Write-Actions instruction. */
4973
4974 static void
4975 encode_WRITE_ACTIONS(const struct ofpact_nest *actions,
4976                      enum ofp_version ofp_version, struct ofpbuf *out)
4977 {
4978     if (ofp_version > OFP10_VERSION) {
4979         const size_t ofs = out->size;
4980
4981         instruction_put_OFPIT11_WRITE_ACTIONS(out);
4982         ofpacts_put_openflow_actions(actions->actions,
4983                                      ofpact_nest_get_action_len(actions),
4984                                      out, ofp_version);
4985         ofpacts_update_instruction_actions(out, ofs);
4986     }
4987 }
4988
4989 static char * OVS_WARN_UNUSED_RESULT
4990 parse_WRITE_ACTIONS(char *arg, struct ofpbuf *ofpacts,
4991                     enum ofputil_protocol *usable_protocols)
4992 {
4993     size_t ofs = ofpacts_pull(ofpacts);
4994     struct ofpact_nest *on;
4995     char *error;
4996
4997     /* Add a Write-Actions instruction and then pull it off. */
4998     ofpact_put(ofpacts, OFPACT_WRITE_ACTIONS, sizeof *on);
4999     ofpbuf_pull(ofpacts, sizeof *on);
5000
5001     /* Parse nested actions.
5002      *
5003      * We pulled off "write-actions" and the previous actions because the
5004      * OFPACT_WRITE_ACTIONS is only partially constructed: its length is such
5005      * that it doesn't actually include the nested actions.  That means that
5006      * ofpacts_parse() would reject them as being part of an Apply-Actions that
5007      * follows a Write-Actions, which is an invalid order.  */
5008     error = ofpacts_parse(arg, ofpacts, usable_protocols, false,
5009                           OFPACT_WRITE_ACTIONS);
5010
5011     /* Put the Write-Actions back on and update its length. */
5012     on = ofpbuf_push_uninit(ofpacts, sizeof *on);
5013     on->ofpact.len = ofpacts->size;
5014
5015     /* Put any previous actions or instructions back on. */
5016     ofpbuf_push_uninit(ofpacts, ofs);
5017
5018     return error;
5019 }
5020
5021 static void
5022 format_WRITE_ACTIONS(const struct ofpact_nest *a, struct ds *s)
5023 {
5024     ds_put_cstr(s, "write_actions(");
5025     ofpacts_format(a->actions, ofpact_nest_get_action_len(a), s);
5026     ds_put_char(s, ')');
5027 }
5028 \f
5029 /* Action structure for NXAST_WRITE_METADATA.
5030  *
5031  * Modifies the 'mask' bits of the metadata value. */
5032 struct nx_action_write_metadata {
5033     ovs_be16 type;                  /* OFPAT_VENDOR. */
5034     ovs_be16 len;                   /* Length is 32. */
5035     ovs_be32 vendor;                /* NX_VENDOR_ID. */
5036     ovs_be16 subtype;               /* NXAST_WRITE_METADATA. */
5037     uint8_t zeros[6];               /* Must be zero. */
5038     ovs_be64 metadata;              /* Metadata register. */
5039     ovs_be64 mask;                  /* Metadata mask. */
5040 };
5041 OFP_ASSERT(sizeof(struct nx_action_write_metadata) == 32);
5042
5043 static enum ofperr
5044 decode_NXAST_RAW_WRITE_METADATA(const struct nx_action_write_metadata *nawm,
5045                                 enum ofp_version ofp_version OVS_UNUSED,
5046                                 struct ofpbuf *out)
5047 {
5048     struct ofpact_metadata *om;
5049
5050     if (!is_all_zeros(nawm->zeros, sizeof nawm->zeros)) {
5051         return OFPERR_NXBRC_MUST_BE_ZERO;
5052     }
5053
5054     om = ofpact_put_WRITE_METADATA(out);
5055     om->metadata = nawm->metadata;
5056     om->mask = nawm->mask;
5057
5058     return 0;
5059 }
5060
5061 static void
5062 encode_WRITE_METADATA(const struct ofpact_metadata *metadata,
5063                       enum ofp_version ofp_version, struct ofpbuf *out)
5064 {
5065     if (ofp_version == OFP10_VERSION) {
5066         struct nx_action_write_metadata *nawm;
5067
5068         nawm = put_NXAST_WRITE_METADATA(out);
5069         nawm->metadata = metadata->metadata;
5070         nawm->mask = metadata->mask;
5071     } else {
5072         struct ofp11_instruction_write_metadata *oiwm;
5073
5074         oiwm = instruction_put_OFPIT11_WRITE_METADATA(out);
5075         oiwm->metadata = metadata->metadata;
5076         oiwm->metadata_mask = metadata->mask;
5077     }
5078 }
5079
5080 static char * OVS_WARN_UNUSED_RESULT
5081 parse_WRITE_METADATA(char *arg, struct ofpbuf *ofpacts,
5082                      enum ofputil_protocol *usable_protocols)
5083 {
5084     struct ofpact_metadata *om;
5085     char *mask = strchr(arg, '/');
5086
5087     *usable_protocols &= OFPUTIL_P_NXM_OF11_UP;
5088
5089     om = ofpact_put_WRITE_METADATA(ofpacts);
5090     if (mask) {
5091         char *error;
5092
5093         *mask = '\0';
5094         error = str_to_be64(mask + 1, &om->mask);
5095         if (error) {
5096             return error;
5097         }
5098     } else {
5099         om->mask = OVS_BE64_MAX;
5100     }
5101
5102     return str_to_be64(arg, &om->metadata);
5103 }
5104
5105 static void
5106 format_WRITE_METADATA(const struct ofpact_metadata *a, struct ds *s)
5107 {
5108     ds_put_format(s, "write_metadata:%#"PRIx64, ntohll(a->metadata));
5109     if (a->mask != OVS_BE64_MAX) {
5110         ds_put_format(s, "/%#"PRIx64, ntohll(a->mask));
5111     }
5112 }
5113 \f
5114 /* Goto-Table instruction. */
5115
5116 static void
5117 encode_GOTO_TABLE(const struct ofpact_goto_table *goto_table,
5118                   enum ofp_version ofp_version, struct ofpbuf *out)
5119 {
5120     if (ofp_version == OFP10_VERSION) {
5121         struct nx_action_resubmit *nar;
5122
5123         nar = put_NXAST_RESUBMIT_TABLE(out);
5124         nar->table = goto_table->table_id;
5125         nar->in_port = htons(ofp_to_u16(OFPP_IN_PORT));
5126     } else {
5127         struct ofp11_instruction_goto_table *oigt;
5128
5129         oigt = instruction_put_OFPIT11_GOTO_TABLE(out);
5130         oigt->table_id = goto_table->table_id;
5131         memset(oigt->pad, 0, sizeof oigt->pad);
5132     }
5133 }
5134
5135 static char * OVS_WARN_UNUSED_RESULT
5136 parse_GOTO_TABLE(char *arg, struct ofpbuf *ofpacts,
5137                  enum ofputil_protocol *usable_protocols OVS_UNUSED)
5138 {
5139     struct ofpact_goto_table *ogt = ofpact_put_GOTO_TABLE(ofpacts);
5140     char *table_s = strsep(&arg, ",");
5141     if (!table_s || !table_s[0]) {
5142         return xstrdup("instruction goto-table needs table id");
5143     }
5144     return str_to_u8(table_s, "table", &ogt->table_id);
5145 }
5146
5147 static void
5148 format_GOTO_TABLE(const struct ofpact_goto_table *a, struct ds *s)
5149 {
5150     ds_put_format(s, "goto_table:%"PRIu8, a->table_id);
5151 }
5152 \f
5153 static void
5154 log_bad_action(const struct ofp_action_header *actions, size_t actions_len,
5155                const struct ofp_action_header *bad_action, enum ofperr error)
5156 {
5157     if (!VLOG_DROP_WARN(&rl)) {
5158         struct ds s;
5159
5160         ds_init(&s);
5161         ds_put_hex_dump(&s, actions, actions_len, 0, false);
5162         VLOG_WARN("bad action at offset %#"PRIxPTR" (%s):\n%s",
5163                   (char *)bad_action - (char *)actions,
5164                   ofperr_get_name(error), ds_cstr(&s));
5165         ds_destroy(&s);
5166     }
5167 }
5168
5169 static enum ofperr
5170 ofpacts_decode(const void *actions, size_t actions_len,
5171                enum ofp_version ofp_version, struct ofpbuf *ofpacts)
5172 {
5173     struct ofpbuf openflow;
5174
5175     ofpbuf_use_const(&openflow, actions, actions_len);
5176     while (openflow.size) {
5177         const struct ofp_action_header *action = openflow.data;
5178         enum ofp_raw_action_type raw;
5179         enum ofperr error;
5180         uint64_t arg;
5181
5182         error = ofpact_pull_raw(&openflow, ofp_version, &raw, &arg);
5183         if (!error) {
5184             error = ofpact_decode(action, raw, ofp_version, arg, ofpacts);
5185         }
5186
5187         if (error) {
5188             log_bad_action(actions, actions_len, action, error);
5189             return error;
5190         }
5191     }
5192
5193     ofpact_pad(ofpacts);
5194     return 0;
5195 }
5196
5197 static enum ofperr
5198 ofpacts_pull_openflow_actions__(struct ofpbuf *openflow,
5199                                 unsigned int actions_len,
5200                                 enum ofp_version version,
5201                                 uint32_t allowed_ovsinsts,
5202                                 struct ofpbuf *ofpacts,
5203                                 enum ofpact_type outer_action)
5204 {
5205     const struct ofp_action_header *actions;
5206     enum ofperr error;
5207
5208     if (!outer_action) {
5209         ofpbuf_clear(ofpacts);
5210     }
5211
5212     if (actions_len % OFP_ACTION_ALIGN != 0) {
5213         VLOG_WARN_RL(&rl, "OpenFlow message actions length %u is not a "
5214                      "multiple of %d", actions_len, OFP_ACTION_ALIGN);
5215         return OFPERR_OFPBRC_BAD_LEN;
5216     }
5217
5218     actions = ofpbuf_try_pull(openflow, actions_len);
5219     if (actions == NULL) {
5220         VLOG_WARN_RL(&rl, "OpenFlow message actions length %u exceeds "
5221                      "remaining message length (%"PRIu32")",
5222                      actions_len, openflow->size);
5223         return OFPERR_OFPBRC_BAD_LEN;
5224     }
5225
5226     error = ofpacts_decode(actions, actions_len, version, ofpacts);
5227     if (error) {
5228         ofpbuf_clear(ofpacts);
5229         return error;
5230     }
5231
5232     error = ofpacts_verify(ofpacts->data, ofpacts->size, allowed_ovsinsts,
5233                            outer_action);
5234     if (error) {
5235         ofpbuf_clear(ofpacts);
5236     }
5237     return error;
5238 }
5239
5240 /* Attempts to convert 'actions_len' bytes of OpenFlow actions from the
5241  * front of 'openflow' into ofpacts.  On success, replaces any existing content
5242  * in 'ofpacts' by the converted ofpacts; on failure, clears 'ofpacts'.
5243  * Returns 0 if successful, otherwise an OpenFlow error.
5244  *
5245  * Actions are processed according to their OpenFlow version which
5246  * is provided in the 'version' parameter.
5247  *
5248  * In most places in OpenFlow, actions appear encapsulated in instructions, so
5249  * you should call ofpacts_pull_openflow_instructions() instead of this
5250  * function.
5251  *
5252  * The parsed actions are valid generically, but they may not be valid in a
5253  * specific context.  For example, port numbers up to OFPP_MAX are valid
5254  * generically, but specific datapaths may only support port numbers in a
5255  * smaller range.  Use ofpacts_check() to additional check whether actions are
5256  * valid in a specific context. */
5257 enum ofperr
5258 ofpacts_pull_openflow_actions(struct ofpbuf *openflow,
5259                               unsigned int actions_len,
5260                               enum ofp_version version,
5261                               struct ofpbuf *ofpacts)
5262 {
5263     return ofpacts_pull_openflow_actions__(openflow, actions_len, version,
5264                                            1u << OVSINST_OFPIT11_APPLY_ACTIONS,
5265                                            ofpacts, 0);
5266 }
5267 \f
5268 /* OpenFlow 1.1 actions. */
5269
5270
5271 /* True if an action sets the value of a field
5272  * in a way that is compatibile with the action set.
5273  * The field can be set via either a set or a move action.
5274  * False otherwise. */
5275 static bool
5276 ofpact_is_set_or_move_action(const struct ofpact *a)
5277 {
5278     switch (a->type) {
5279     case OFPACT_SET_FIELD:
5280     case OFPACT_REG_MOVE:
5281     case OFPACT_SET_ETH_DST:
5282     case OFPACT_SET_ETH_SRC:
5283     case OFPACT_SET_IP_DSCP:
5284     case OFPACT_SET_IP_ECN:
5285     case OFPACT_SET_IP_TTL:
5286     case OFPACT_SET_IPV4_DST:
5287     case OFPACT_SET_IPV4_SRC:
5288     case OFPACT_SET_L4_DST_PORT:
5289     case OFPACT_SET_L4_SRC_PORT:
5290     case OFPACT_SET_MPLS_LABEL:
5291     case OFPACT_SET_MPLS_TC:
5292     case OFPACT_SET_MPLS_TTL:
5293     case OFPACT_SET_QUEUE:
5294     case OFPACT_SET_TUNNEL:
5295     case OFPACT_SET_VLAN_PCP:
5296     case OFPACT_SET_VLAN_VID:
5297         return true;
5298     case OFPACT_BUNDLE:
5299     case OFPACT_CLEAR_ACTIONS:
5300     case OFPACT_CT:
5301     case OFPACT_CONTROLLER:
5302     case OFPACT_DEC_MPLS_TTL:
5303     case OFPACT_DEC_TTL:
5304     case OFPACT_ENQUEUE:
5305     case OFPACT_EXIT:
5306     case OFPACT_UNROLL_XLATE:
5307     case OFPACT_FIN_TIMEOUT:
5308     case OFPACT_GOTO_TABLE:
5309     case OFPACT_GROUP:
5310     case OFPACT_LEARN:
5311     case OFPACT_CONJUNCTION:
5312     case OFPACT_METER:
5313     case OFPACT_MULTIPATH:
5314     case OFPACT_NOTE:
5315     case OFPACT_OUTPUT:
5316     case OFPACT_OUTPUT_REG:
5317     case OFPACT_POP_MPLS:
5318     case OFPACT_POP_QUEUE:
5319     case OFPACT_PUSH_MPLS:
5320     case OFPACT_PUSH_VLAN:
5321     case OFPACT_RESUBMIT:
5322     case OFPACT_SAMPLE:
5323     case OFPACT_STACK_POP:
5324     case OFPACT_STACK_PUSH:
5325     case OFPACT_STRIP_VLAN:
5326     case OFPACT_WRITE_ACTIONS:
5327     case OFPACT_WRITE_METADATA:
5328     case OFPACT_DEBUG_RECIRC:
5329         return false;
5330     default:
5331         OVS_NOT_REACHED();
5332     }
5333 }
5334
5335 /* True if an action is allowed in the action set.
5336  * False otherwise. */
5337 static bool
5338 ofpact_is_allowed_in_actions_set(const struct ofpact *a)
5339 {
5340     switch (a->type) {
5341     case OFPACT_DEC_MPLS_TTL:
5342     case OFPACT_DEC_TTL:
5343     case OFPACT_GROUP:
5344     case OFPACT_OUTPUT:
5345     case OFPACT_POP_MPLS:
5346     case OFPACT_PUSH_MPLS:
5347     case OFPACT_PUSH_VLAN:
5348     case OFPACT_REG_MOVE:
5349     case OFPACT_SET_FIELD:
5350     case OFPACT_SET_ETH_DST:
5351     case OFPACT_SET_ETH_SRC:
5352     case OFPACT_SET_IP_DSCP:
5353     case OFPACT_SET_IP_ECN:
5354     case OFPACT_SET_IP_TTL:
5355     case OFPACT_SET_IPV4_DST:
5356     case OFPACT_SET_IPV4_SRC:
5357     case OFPACT_SET_L4_DST_PORT:
5358     case OFPACT_SET_L4_SRC_PORT:
5359     case OFPACT_SET_MPLS_LABEL:
5360     case OFPACT_SET_MPLS_TC:
5361     case OFPACT_SET_MPLS_TTL:
5362     case OFPACT_SET_QUEUE:
5363     case OFPACT_SET_TUNNEL:
5364     case OFPACT_SET_VLAN_PCP:
5365     case OFPACT_SET_VLAN_VID:
5366     case OFPACT_STRIP_VLAN:
5367         return true;
5368
5369     /* In general these actions are excluded because they are not part of
5370      * the OpenFlow specification nor map to actions that are defined in
5371      * the specification.  Thus the order in which they should be applied
5372      * in the action set is undefined. */
5373     case OFPACT_BUNDLE:
5374     case OFPACT_CONTROLLER:
5375     case OFPACT_CT:
5376     case OFPACT_ENQUEUE:
5377     case OFPACT_EXIT:
5378     case OFPACT_UNROLL_XLATE:
5379     case OFPACT_FIN_TIMEOUT:
5380     case OFPACT_LEARN:
5381     case OFPACT_CONJUNCTION:
5382     case OFPACT_MULTIPATH:
5383     case OFPACT_NOTE:
5384     case OFPACT_OUTPUT_REG:
5385     case OFPACT_POP_QUEUE:
5386     case OFPACT_RESUBMIT:
5387     case OFPACT_SAMPLE:
5388     case OFPACT_STACK_POP:
5389     case OFPACT_STACK_PUSH:
5390     case OFPACT_DEBUG_RECIRC:
5391
5392     /* The action set may only include actions and thus
5393      * may not include any instructions */
5394     case OFPACT_CLEAR_ACTIONS:
5395     case OFPACT_GOTO_TABLE:
5396     case OFPACT_METER:
5397     case OFPACT_WRITE_ACTIONS:
5398     case OFPACT_WRITE_METADATA:
5399         return false;
5400     default:
5401         OVS_NOT_REACHED();
5402     }
5403 }
5404
5405 /* Append ofpact 'a' onto the tail of 'out' */
5406 static void
5407 ofpact_copy(struct ofpbuf *out, const struct ofpact *a)
5408 {
5409     ofpbuf_put(out, a, OFPACT_ALIGN(a->len));
5410 }
5411
5412 /* Copies the last ofpact whose type is 'filter' from 'in' to 'out'. */
5413 static bool
5414 ofpacts_copy_last(struct ofpbuf *out, const struct ofpbuf *in,
5415                   enum ofpact_type filter)
5416 {
5417     const struct ofpact *target;
5418     const struct ofpact *a;
5419
5420     target = NULL;
5421     OFPACT_FOR_EACH (a, in->data, in->size) {
5422         if (a->type == filter) {
5423             target = a;
5424         }
5425     }
5426     if (target) {
5427         ofpact_copy(out, target);
5428     }
5429     return target != NULL;
5430 }
5431
5432 /* Append all ofpacts, for which 'filter' returns true, from 'in' to 'out'.
5433  * The order of appended ofpacts is preserved between 'in' and 'out' */
5434 static void
5435 ofpacts_copy_all(struct ofpbuf *out, const struct ofpbuf *in,
5436                  bool (*filter)(const struct ofpact *))
5437 {
5438     const struct ofpact *a;
5439
5440     OFPACT_FOR_EACH (a, in->data, in->size) {
5441         if (filter(a)) {
5442             ofpact_copy(out, a);
5443         }
5444     }
5445 }
5446
5447 /* Reads 'action_set', which contains ofpacts accumulated by
5448  * OFPACT_WRITE_ACTIONS instructions, and writes equivalent actions to be
5449  * executed directly into 'action_list'.  (These names correspond to the
5450  * "Action Set" and "Action List" terms used in OpenFlow 1.1+.)
5451  *
5452  * In general this involves appending the last instance of each action that is
5453  * admissible in the action set in the order described in the OpenFlow
5454  * specification.
5455  *
5456  * Exceptions:
5457  * + output action is only appended if no group action was present in 'in'.
5458  * + As a simplification all set actions are copied in the order the are
5459  *   provided in 'in' as many set actions applied to a field has the same
5460  *   affect as only applying the last action that sets a field and
5461  *   duplicates are removed by do_xlate_actions().
5462  *   This has an unwanted side-effect of compsoting multiple
5463  *   LOAD_REG actions that touch different regions of the same field. */
5464 void
5465 ofpacts_execute_action_set(struct ofpbuf *action_list,
5466                            const struct ofpbuf *action_set)
5467 {
5468     /* The OpenFlow spec "Action Set" section specifies this order. */
5469     ofpacts_copy_last(action_list, action_set, OFPACT_STRIP_VLAN);
5470     ofpacts_copy_last(action_list, action_set, OFPACT_POP_MPLS);
5471     ofpacts_copy_last(action_list, action_set, OFPACT_PUSH_MPLS);
5472     ofpacts_copy_last(action_list, action_set, OFPACT_PUSH_VLAN);
5473     ofpacts_copy_last(action_list, action_set, OFPACT_DEC_TTL);
5474     ofpacts_copy_last(action_list, action_set, OFPACT_DEC_MPLS_TTL);
5475     ofpacts_copy_all(action_list, action_set, ofpact_is_set_or_move_action);
5476     ofpacts_copy_last(action_list, action_set, OFPACT_SET_QUEUE);
5477
5478     /* If both OFPACT_GROUP and OFPACT_OUTPUT are present, OpenFlow says that
5479      * we should execute only OFPACT_GROUP.
5480      *
5481      * If neither OFPACT_GROUP nor OFPACT_OUTPUT is present, then we can drop
5482      * all the actions because there's no point in modifying a packet that will
5483      * not be sent anywhere. */
5484     if (!ofpacts_copy_last(action_list, action_set, OFPACT_GROUP) &&
5485         !ofpacts_copy_last(action_list, action_set, OFPACT_OUTPUT) &&
5486         !ofpacts_copy_last(action_list, action_set, OFPACT_RESUBMIT)) {
5487         ofpbuf_clear(action_list);
5488     }
5489 }
5490
5491
5492 static enum ofperr
5493 ofpacts_decode_for_action_set(const struct ofp_action_header *in,
5494                               size_t n_in, enum ofp_version version,
5495                               struct ofpbuf *out)
5496 {
5497     enum ofperr error;
5498     struct ofpact *a;
5499     size_t start = out->size;
5500
5501     error = ofpacts_decode(in, n_in, version, out);
5502
5503     if (error) {
5504         return error;
5505     }
5506
5507     OFPACT_FOR_EACH (a, ofpact_end(out->data, start), out->size - start) {
5508         if (!ofpact_is_allowed_in_actions_set(a)) {
5509             VLOG_WARN_RL(&rl, "disallowed action in action set");
5510             return OFPERR_OFPBAC_BAD_TYPE;
5511         }
5512     }
5513
5514     return 0;
5515 }
5516 \f
5517 /* OpenFlow 1.1 instructions. */
5518
5519 struct instruction_type_info {
5520     enum ovs_instruction_type type;
5521     const char *name;
5522 };
5523
5524 static const struct instruction_type_info inst_info[] = {
5525 #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME)    {OVSINST_##ENUM, NAME},
5526 OVS_INSTRUCTIONS
5527 #undef DEFINE_INST
5528 };
5529
5530 const char *
5531 ovs_instruction_name_from_type(enum ovs_instruction_type type)
5532 {
5533     return inst_info[type].name;
5534 }
5535
5536 int
5537 ovs_instruction_type_from_name(const char *name)
5538 {
5539     const struct instruction_type_info *p;
5540     for (p = inst_info; p < &inst_info[ARRAY_SIZE(inst_info)]; p++) {
5541         if (!strcasecmp(name, p->name)) {
5542             return p->type;
5543         }
5544     }
5545     return -1;
5546 }
5547
5548 enum ovs_instruction_type
5549 ovs_instruction_type_from_ofpact_type(enum ofpact_type type)
5550 {
5551     switch (type) {
5552     case OFPACT_METER:
5553         return OVSINST_OFPIT13_METER;
5554     case OFPACT_CLEAR_ACTIONS:
5555         return OVSINST_OFPIT11_CLEAR_ACTIONS;
5556     case OFPACT_WRITE_ACTIONS:
5557         return OVSINST_OFPIT11_WRITE_ACTIONS;
5558     case OFPACT_WRITE_METADATA:
5559         return OVSINST_OFPIT11_WRITE_METADATA;
5560     case OFPACT_GOTO_TABLE:
5561         return OVSINST_OFPIT11_GOTO_TABLE;
5562     case OFPACT_OUTPUT:
5563     case OFPACT_GROUP:
5564     case OFPACT_CONTROLLER:
5565     case OFPACT_ENQUEUE:
5566     case OFPACT_OUTPUT_REG:
5567     case OFPACT_BUNDLE:
5568     case OFPACT_SET_VLAN_VID:
5569     case OFPACT_SET_VLAN_PCP:
5570     case OFPACT_STRIP_VLAN:
5571     case OFPACT_PUSH_VLAN:
5572     case OFPACT_SET_ETH_SRC:
5573     case OFPACT_SET_ETH_DST:
5574     case OFPACT_SET_IPV4_SRC:
5575     case OFPACT_SET_IPV4_DST:
5576     case OFPACT_SET_IP_DSCP:
5577     case OFPACT_SET_IP_ECN:
5578     case OFPACT_SET_IP_TTL:
5579     case OFPACT_SET_L4_SRC_PORT:
5580     case OFPACT_SET_L4_DST_PORT:
5581     case OFPACT_REG_MOVE:
5582     case OFPACT_SET_FIELD:
5583     case OFPACT_STACK_PUSH:
5584     case OFPACT_STACK_POP:
5585     case OFPACT_DEC_TTL:
5586     case OFPACT_SET_MPLS_LABEL:
5587     case OFPACT_SET_MPLS_TC:
5588     case OFPACT_SET_MPLS_TTL:
5589     case OFPACT_DEC_MPLS_TTL:
5590     case OFPACT_PUSH_MPLS:
5591     case OFPACT_POP_MPLS:
5592     case OFPACT_SET_TUNNEL:
5593     case OFPACT_SET_QUEUE:
5594     case OFPACT_POP_QUEUE:
5595     case OFPACT_FIN_TIMEOUT:
5596     case OFPACT_RESUBMIT:
5597     case OFPACT_LEARN:
5598     case OFPACT_CONJUNCTION:
5599     case OFPACT_MULTIPATH:
5600     case OFPACT_NOTE:
5601     case OFPACT_EXIT:
5602     case OFPACT_UNROLL_XLATE:
5603     case OFPACT_SAMPLE:
5604     case OFPACT_DEBUG_RECIRC:
5605     case OFPACT_CT:
5606     default:
5607         return OVSINST_OFPIT11_APPLY_ACTIONS;
5608     }
5609 }
5610
5611 enum ofperr
5612 ovs_instruction_type_from_inst_type(enum ovs_instruction_type *instruction_type,
5613                                     const uint16_t inst_type)
5614 {
5615     switch (inst_type) {
5616
5617 #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME) \
5618     case ENUM:                                      \
5619         *instruction_type = OVSINST_##ENUM;         \
5620         return 0;
5621 OVS_INSTRUCTIONS
5622 #undef DEFINE_INST
5623
5624     default:
5625         return OFPERR_OFPBIC_UNKNOWN_INST;
5626     }
5627 }
5628
5629 /* Two-way translation between OVS's internal "OVSINST_*" representation of
5630  * instructions and the "OFPIT_*" representation used in OpenFlow. */
5631 struct ovsinst_map {
5632     enum ovs_instruction_type ovsinst; /* Internal name for instruction. */
5633     int ofpit;                         /* OFPIT_* number from OpenFlow spec. */
5634 };
5635
5636 static const struct ovsinst_map *
5637 get_ovsinst_map(enum ofp_version version)
5638 {
5639     /* OpenFlow 1.1 and 1.2 instructions. */
5640     static const struct ovsinst_map of11[] = {
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         { 0, -1 },
5647     };
5648
5649     /* OpenFlow 1.3+ instructions. */
5650     static const struct ovsinst_map of13[] = {
5651         { OVSINST_OFPIT11_GOTO_TABLE, 1 },
5652         { OVSINST_OFPIT11_WRITE_METADATA, 2 },
5653         { OVSINST_OFPIT11_WRITE_ACTIONS, 3 },
5654         { OVSINST_OFPIT11_APPLY_ACTIONS, 4 },
5655         { OVSINST_OFPIT11_CLEAR_ACTIONS, 5 },
5656         { OVSINST_OFPIT13_METER, 6 },
5657         { 0, -1 },
5658     };
5659
5660     return version < OFP13_VERSION ? of11 : of13;
5661 }
5662
5663 /* Converts 'ovsinst_bitmap', a bitmap whose bits correspond to OVSINST_*
5664  * values, into a bitmap of instructions suitable for OpenFlow 'version'
5665  * (OFP11_VERSION or later), and returns the result. */
5666 ovs_be32
5667 ovsinst_bitmap_to_openflow(uint32_t ovsinst_bitmap, enum ofp_version version)
5668 {
5669     uint32_t ofpit_bitmap = 0;
5670     const struct ovsinst_map *x;
5671
5672     for (x = get_ovsinst_map(version); x->ofpit >= 0; x++) {
5673         if (ovsinst_bitmap & (1u << x->ovsinst)) {
5674             ofpit_bitmap |= 1u << x->ofpit;
5675         }
5676     }
5677     return htonl(ofpit_bitmap);
5678 }
5679
5680 /* Converts 'ofpit_bitmap', a bitmap of instructions from an OpenFlow message
5681  * with the given 'version' (OFP11_VERSION or later) into a bitmap whose bits
5682  * correspond to OVSINST_* values, and returns the result. */
5683 uint32_t
5684 ovsinst_bitmap_from_openflow(ovs_be32 ofpit_bitmap, enum ofp_version version)
5685 {
5686     uint32_t ovsinst_bitmap = 0;
5687     const struct ovsinst_map *x;
5688
5689     for (x = get_ovsinst_map(version); x->ofpit >= 0; x++) {
5690         if (ofpit_bitmap & htonl(1u << x->ofpit)) {
5691             ovsinst_bitmap |= 1u << x->ovsinst;
5692         }
5693     }
5694     return ovsinst_bitmap;
5695 }
5696
5697 static inline struct ofp11_instruction *
5698 instruction_next(const struct ofp11_instruction *inst)
5699 {
5700     return ((struct ofp11_instruction *) (void *)
5701             ((uint8_t *) inst + ntohs(inst->len)));
5702 }
5703
5704 static inline bool
5705 instruction_is_valid(const struct ofp11_instruction *inst,
5706                      size_t n_instructions)
5707 {
5708     uint16_t len = ntohs(inst->len);
5709     return (!(len % OFP11_INSTRUCTION_ALIGN)
5710             && len >= sizeof *inst
5711             && len / sizeof *inst <= n_instructions);
5712 }
5713
5714 /* This macro is careful to check for instructions with bad lengths. */
5715 #define INSTRUCTION_FOR_EACH(ITER, LEFT, INSTRUCTIONS, N_INSTRUCTIONS)  \
5716     for ((ITER) = (INSTRUCTIONS), (LEFT) = (N_INSTRUCTIONS);            \
5717          (LEFT) > 0 && instruction_is_valid(ITER, LEFT);                \
5718          ((LEFT) -= (ntohs((ITER)->len)                                 \
5719                      / sizeof(struct ofp11_instruction)),               \
5720           (ITER) = instruction_next(ITER)))
5721
5722 static enum ofperr
5723 decode_openflow11_instruction(const struct ofp11_instruction *inst,
5724                               enum ovs_instruction_type *type)
5725 {
5726     uint16_t len = ntohs(inst->len);
5727
5728     switch (inst->type) {
5729     case CONSTANT_HTONS(OFPIT11_EXPERIMENTER):
5730         return OFPERR_OFPBIC_BAD_EXPERIMENTER;
5731
5732 #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME)     \
5733         case CONSTANT_HTONS(ENUM):                      \
5734             if (EXTENSIBLE                              \
5735                 ? len >= sizeof(struct STRUCT)          \
5736                 : len == sizeof(struct STRUCT)) {       \
5737                 *type = OVSINST_##ENUM;                 \
5738                 return 0;                               \
5739             } else {                                    \
5740                 return OFPERR_OFPBIC_BAD_LEN;           \
5741             }
5742 OVS_INSTRUCTIONS
5743 #undef DEFINE_INST
5744
5745     default:
5746         return OFPERR_OFPBIC_UNKNOWN_INST;
5747     }
5748 }
5749
5750 static enum ofperr
5751 decode_openflow11_instructions(const struct ofp11_instruction insts[],
5752                                size_t n_insts,
5753                                const struct ofp11_instruction *out[])
5754 {
5755     const struct ofp11_instruction *inst;
5756     size_t left;
5757
5758     memset(out, 0, N_OVS_INSTRUCTIONS * sizeof *out);
5759     INSTRUCTION_FOR_EACH (inst, left, insts, n_insts) {
5760         enum ovs_instruction_type type;
5761         enum ofperr error;
5762
5763         error = decode_openflow11_instruction(inst, &type);
5764         if (error) {
5765             return error;
5766         }
5767
5768         if (out[type]) {
5769             return OFPERR_OFPBIC_DUP_INST;
5770         }
5771         out[type] = inst;
5772     }
5773
5774     if (left) {
5775         VLOG_WARN_RL(&rl, "bad instruction format at offset %"PRIuSIZE,
5776                      (n_insts - left) * sizeof *inst);
5777         return OFPERR_OFPBIC_BAD_LEN;
5778     }
5779     return 0;
5780 }
5781
5782 static void
5783 get_actions_from_instruction(const struct ofp11_instruction *inst,
5784                              const struct ofp_action_header **actions,
5785                              size_t *actions_len)
5786 {
5787     *actions = ALIGNED_CAST(const struct ofp_action_header *, inst + 1);
5788     *actions_len = ntohs(inst->len) - sizeof *inst;
5789 }
5790
5791 enum ofperr
5792 ofpacts_pull_openflow_instructions(struct ofpbuf *openflow,
5793                                    unsigned int instructions_len,
5794                                    enum ofp_version version,
5795                                    struct ofpbuf *ofpacts)
5796 {
5797     const struct ofp11_instruction *instructions;
5798     const struct ofp11_instruction *insts[N_OVS_INSTRUCTIONS];
5799     enum ofperr error;
5800
5801     if (version == OFP10_VERSION) {
5802         return ofpacts_pull_openflow_actions__(openflow, instructions_len,
5803                                                version,
5804                                                (1u << N_OVS_INSTRUCTIONS) - 1,
5805                                                ofpacts, 0);
5806     }
5807
5808     ofpbuf_clear(ofpacts);
5809
5810     if (instructions_len % OFP11_INSTRUCTION_ALIGN != 0) {
5811         VLOG_WARN_RL(&rl, "OpenFlow message instructions length %u is not a "
5812                      "multiple of %d",
5813                      instructions_len, OFP11_INSTRUCTION_ALIGN);
5814         error = OFPERR_OFPBIC_BAD_LEN;
5815         goto exit;
5816     }
5817
5818     instructions = ofpbuf_try_pull(openflow, instructions_len);
5819     if (instructions == NULL) {
5820         VLOG_WARN_RL(&rl, "OpenFlow message instructions length %u exceeds "
5821                      "remaining message length (%"PRIu32")",
5822                      instructions_len, openflow->size);
5823         error = OFPERR_OFPBIC_BAD_LEN;
5824         goto exit;
5825     }
5826
5827     error = decode_openflow11_instructions(
5828         instructions, instructions_len / OFP11_INSTRUCTION_ALIGN,
5829         insts);
5830     if (error) {
5831         goto exit;
5832     }
5833
5834     if (insts[OVSINST_OFPIT13_METER]) {
5835         const struct ofp13_instruction_meter *oim;
5836         struct ofpact_meter *om;
5837
5838         oim = ALIGNED_CAST(const struct ofp13_instruction_meter *,
5839                            insts[OVSINST_OFPIT13_METER]);
5840
5841         om = ofpact_put_METER(ofpacts);
5842         om->meter_id = ntohl(oim->meter_id);
5843     }
5844     if (insts[OVSINST_OFPIT11_APPLY_ACTIONS]) {
5845         const struct ofp_action_header *actions;
5846         size_t actions_len;
5847
5848         get_actions_from_instruction(insts[OVSINST_OFPIT11_APPLY_ACTIONS],
5849                                      &actions, &actions_len);
5850         error = ofpacts_decode(actions, actions_len, version, ofpacts);
5851         if (error) {
5852             goto exit;
5853         }
5854     }
5855     if (insts[OVSINST_OFPIT11_CLEAR_ACTIONS]) {
5856         instruction_get_OFPIT11_CLEAR_ACTIONS(
5857             insts[OVSINST_OFPIT11_CLEAR_ACTIONS]);
5858         ofpact_put_CLEAR_ACTIONS(ofpacts);
5859     }
5860     if (insts[OVSINST_OFPIT11_WRITE_ACTIONS]) {
5861         struct ofpact_nest *on;
5862         const struct ofp_action_header *actions;
5863         size_t actions_len;
5864         size_t start;
5865
5866         ofpact_pad(ofpacts);
5867         start = ofpacts->size;
5868         ofpact_put(ofpacts, OFPACT_WRITE_ACTIONS,
5869                    offsetof(struct ofpact_nest, actions));
5870         get_actions_from_instruction(insts[OVSINST_OFPIT11_WRITE_ACTIONS],
5871                                      &actions, &actions_len);
5872         error = ofpacts_decode_for_action_set(actions, actions_len,
5873                                               version, ofpacts);
5874         if (error) {
5875             goto exit;
5876         }
5877         on = ofpbuf_at_assert(ofpacts, start, sizeof *on);
5878         on->ofpact.len = ofpacts->size - start;
5879     }
5880     if (insts[OVSINST_OFPIT11_WRITE_METADATA]) {
5881         const struct ofp11_instruction_write_metadata *oiwm;
5882         struct ofpact_metadata *om;
5883
5884         oiwm = ALIGNED_CAST(const struct ofp11_instruction_write_metadata *,
5885                             insts[OVSINST_OFPIT11_WRITE_METADATA]);
5886
5887         om = ofpact_put_WRITE_METADATA(ofpacts);
5888         om->metadata = oiwm->metadata;
5889         om->mask = oiwm->metadata_mask;
5890     }
5891     if (insts[OVSINST_OFPIT11_GOTO_TABLE]) {
5892         const struct ofp11_instruction_goto_table *oigt;
5893         struct ofpact_goto_table *ogt;
5894
5895         oigt = instruction_get_OFPIT11_GOTO_TABLE(
5896             insts[OVSINST_OFPIT11_GOTO_TABLE]);
5897         ogt = ofpact_put_GOTO_TABLE(ofpacts);
5898         ogt->table_id = oigt->table_id;
5899     }
5900
5901     error = ofpacts_verify(ofpacts->data, ofpacts->size,
5902                            (1u << N_OVS_INSTRUCTIONS) - 1, 0);
5903 exit:
5904     if (error) {
5905         ofpbuf_clear(ofpacts);
5906     }
5907     return error;
5908 }
5909
5910 /* Update the length of the instruction that begins at offset 'ofs' within
5911  * 'openflow' and contains nested actions that extend to the end of 'openflow'.
5912  * If the instruction contains no nested actions, deletes it entirely. */
5913 static void
5914 ofpacts_update_instruction_actions(struct ofpbuf *openflow, size_t ofs)
5915 {
5916     struct ofp11_instruction_actions *oia;
5917
5918     oia = ofpbuf_at_assert(openflow, ofs, sizeof *oia);
5919     if (openflow->size > ofs + sizeof *oia) {
5920         oia->len = htons(openflow->size - ofs);
5921     } else {
5922         openflow->size = ofs;
5923     }
5924 }
5925 \f
5926 /* Checks that 'port' is a valid output port for OFPACT_OUTPUT, given that the
5927  * switch will never have more than 'max_ports' ports.  Returns 0 if 'port' is
5928  * valid, otherwise an OpenFlow error code. */
5929 enum ofperr
5930 ofpact_check_output_port(ofp_port_t port, ofp_port_t max_ports)
5931 {
5932     switch (port) {
5933     case OFPP_IN_PORT:
5934     case OFPP_TABLE:
5935     case OFPP_NORMAL:
5936     case OFPP_FLOOD:
5937     case OFPP_ALL:
5938     case OFPP_CONTROLLER:
5939     case OFPP_LOCAL:
5940         return 0;
5941
5942     case OFPP_NONE:
5943         return OFPERR_OFPBAC_BAD_OUT_PORT;
5944
5945     default:
5946         if (ofp_to_u16(port) < ofp_to_u16(max_ports)) {
5947             return 0;
5948         }
5949         return OFPERR_OFPBAC_BAD_OUT_PORT;
5950     }
5951 }
5952
5953 /* Removes the protocols that require consistency between match and actions
5954  * (that's everything but OpenFlow 1.0) from '*usable_protocols'.
5955  *
5956  * (An example of an inconsistency between match and actions is a flow that
5957  * does not match on an MPLS Ethertype but has an action that pops an MPLS
5958  * label.) */
5959 static void
5960 inconsistent_match(enum ofputil_protocol *usable_protocols)
5961 {
5962     *usable_protocols &= OFPUTIL_P_OF10_ANY;
5963 }
5964
5965 /* May modify flow->dl_type, flow->nw_proto and flow->vlan_tci,
5966  * caller must restore them.
5967  *
5968  * Modifies some actions, filling in fields that could not be properly set
5969  * without context. */
5970 static enum ofperr
5971 ofpact_check__(enum ofputil_protocol *usable_protocols, struct ofpact *a,
5972                struct flow *flow, ofp_port_t max_ports,
5973                uint8_t table_id, uint8_t n_tables)
5974 {
5975     const struct ofpact_enqueue *enqueue;
5976     const struct mf_field *mf;
5977
5978     switch (a->type) {
5979     case OFPACT_OUTPUT:
5980         return ofpact_check_output_port(ofpact_get_OUTPUT(a)->port,
5981                                         max_ports);
5982
5983     case OFPACT_CONTROLLER:
5984         return 0;
5985
5986     case OFPACT_ENQUEUE:
5987         enqueue = ofpact_get_ENQUEUE(a);
5988         if (ofp_to_u16(enqueue->port) >= ofp_to_u16(max_ports)
5989             && enqueue->port != OFPP_IN_PORT
5990             && enqueue->port != OFPP_LOCAL) {
5991             return OFPERR_OFPBAC_BAD_OUT_PORT;
5992         }
5993         return 0;
5994
5995     case OFPACT_OUTPUT_REG:
5996         return mf_check_src(&ofpact_get_OUTPUT_REG(a)->src, flow);
5997
5998     case OFPACT_BUNDLE:
5999         return bundle_check(ofpact_get_BUNDLE(a), max_ports, flow);
6000
6001     case OFPACT_SET_VLAN_VID:
6002         /* Remember if we saw a vlan tag in the flow to aid translating to
6003          * OpenFlow 1.1+ if need be. */
6004         ofpact_get_SET_VLAN_VID(a)->flow_has_vlan =
6005             (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI);
6006         if (!(flow->vlan_tci & htons(VLAN_CFI)) &&
6007             !ofpact_get_SET_VLAN_VID(a)->push_vlan_if_needed) {
6008             inconsistent_match(usable_protocols);
6009         }
6010         /* Temporary mark that we have a vlan tag. */
6011         flow->vlan_tci |= htons(VLAN_CFI);
6012         return 0;
6013
6014     case OFPACT_SET_VLAN_PCP:
6015         /* Remember if we saw a vlan tag in the flow to aid translating to
6016          * OpenFlow 1.1+ if need be. */
6017         ofpact_get_SET_VLAN_PCP(a)->flow_has_vlan =
6018             (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI);
6019         if (!(flow->vlan_tci & htons(VLAN_CFI)) &&
6020             !ofpact_get_SET_VLAN_PCP(a)->push_vlan_if_needed) {
6021             inconsistent_match(usable_protocols);
6022         }
6023         /* Temporary mark that we have a vlan tag. */
6024         flow->vlan_tci |= htons(VLAN_CFI);
6025         return 0;
6026
6027     case OFPACT_STRIP_VLAN:
6028         if (!(flow->vlan_tci & htons(VLAN_CFI))) {
6029             inconsistent_match(usable_protocols);
6030         }
6031         /* Temporary mark that we have no vlan tag. */
6032         flow->vlan_tci = htons(0);
6033         return 0;
6034
6035     case OFPACT_PUSH_VLAN:
6036         if (flow->vlan_tci & htons(VLAN_CFI)) {
6037             /* Multiple VLAN headers not supported. */
6038             return OFPERR_OFPBAC_BAD_TAG;
6039         }
6040         /* Temporary mark that we have a vlan tag. */
6041         flow->vlan_tci |= htons(VLAN_CFI);
6042         return 0;
6043
6044     case OFPACT_SET_ETH_SRC:
6045     case OFPACT_SET_ETH_DST:
6046         return 0;
6047
6048     case OFPACT_SET_IPV4_SRC:
6049     case OFPACT_SET_IPV4_DST:
6050         if (flow->dl_type != htons(ETH_TYPE_IP)) {
6051             inconsistent_match(usable_protocols);
6052         }
6053         return 0;
6054
6055     case OFPACT_SET_IP_DSCP:
6056     case OFPACT_SET_IP_ECN:
6057     case OFPACT_SET_IP_TTL:
6058     case OFPACT_DEC_TTL:
6059         if (!is_ip_any(flow)) {
6060             inconsistent_match(usable_protocols);
6061         }
6062         return 0;
6063
6064     case OFPACT_SET_L4_SRC_PORT:
6065     case OFPACT_SET_L4_DST_PORT:
6066         if (!is_ip_any(flow) || (flow->nw_frag & FLOW_NW_FRAG_LATER) ||
6067             (flow->nw_proto != IPPROTO_TCP && flow->nw_proto != IPPROTO_UDP
6068              && flow->nw_proto != IPPROTO_SCTP)) {
6069             inconsistent_match(usable_protocols);
6070         }
6071         /* Note on which transport protocol the port numbers are set.
6072          * This allows this set action to be converted to an OF1.2 set field
6073          * action. */
6074         if (a->type == OFPACT_SET_L4_SRC_PORT) {
6075             ofpact_get_SET_L4_SRC_PORT(a)->flow_ip_proto = flow->nw_proto;
6076         } else {
6077             ofpact_get_SET_L4_DST_PORT(a)->flow_ip_proto = flow->nw_proto;
6078         }
6079         return 0;
6080
6081     case OFPACT_REG_MOVE:
6082         return nxm_reg_move_check(ofpact_get_REG_MOVE(a), flow);
6083
6084     case OFPACT_SET_FIELD:
6085         mf = ofpact_get_SET_FIELD(a)->field;
6086         /* Require OXM_OF_VLAN_VID to have an existing VLAN header. */
6087         if (!mf_are_prereqs_ok(mf, flow) ||
6088             (mf->id == MFF_VLAN_VID && !(flow->vlan_tci & htons(VLAN_CFI)))) {
6089             VLOG_WARN_RL(&rl, "set_field %s lacks correct prerequisities",
6090                          mf->name);
6091             return OFPERR_OFPBAC_MATCH_INCONSISTENT;
6092         }
6093         /* Remember if we saw a vlan tag in the flow to aid translating to
6094          * OpenFlow 1.1 if need be. */
6095         ofpact_get_SET_FIELD(a)->flow_has_vlan =
6096             (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI);
6097         if (mf->id == MFF_VLAN_TCI) {
6098             /* The set field may add or remove the vlan tag,
6099              * Mark the status temporarily. */
6100             flow->vlan_tci = ofpact_get_SET_FIELD(a)->value.be16;
6101         }
6102         return 0;
6103
6104     case OFPACT_STACK_PUSH:
6105         return nxm_stack_push_check(ofpact_get_STACK_PUSH(a), flow);
6106
6107     case OFPACT_STACK_POP:
6108         return nxm_stack_pop_check(ofpact_get_STACK_POP(a), flow);
6109
6110     case OFPACT_SET_MPLS_LABEL:
6111     case OFPACT_SET_MPLS_TC:
6112     case OFPACT_SET_MPLS_TTL:
6113     case OFPACT_DEC_MPLS_TTL:
6114         if (!eth_type_mpls(flow->dl_type)) {
6115             inconsistent_match(usable_protocols);
6116         }
6117         return 0;
6118
6119     case OFPACT_SET_TUNNEL:
6120     case OFPACT_SET_QUEUE:
6121     case OFPACT_POP_QUEUE:
6122     case OFPACT_RESUBMIT:
6123         return 0;
6124
6125     case OFPACT_FIN_TIMEOUT:
6126         if (flow->nw_proto != IPPROTO_TCP) {
6127             inconsistent_match(usable_protocols);
6128         }
6129         return 0;
6130
6131     case OFPACT_LEARN:
6132         return learn_check(ofpact_get_LEARN(a), flow);
6133
6134     case OFPACT_CONJUNCTION:
6135         return 0;
6136
6137     case OFPACT_MULTIPATH:
6138         return multipath_check(ofpact_get_MULTIPATH(a), flow);
6139
6140     case OFPACT_NOTE:
6141     case OFPACT_EXIT:
6142         return 0;
6143
6144     case OFPACT_PUSH_MPLS:
6145         flow->dl_type = ofpact_get_PUSH_MPLS(a)->ethertype;
6146         /* The packet is now MPLS and the MPLS payload is opaque.
6147          * Thus nothing can be assumed about the network protocol.
6148          * Temporarily mark that we have no nw_proto. */
6149         flow->nw_proto = 0;
6150         return 0;
6151
6152     case OFPACT_POP_MPLS:
6153         if (!eth_type_mpls(flow->dl_type)) {
6154             inconsistent_match(usable_protocols);
6155         }
6156         flow->dl_type = ofpact_get_POP_MPLS(a)->ethertype;
6157         return 0;
6158
6159     case OFPACT_SAMPLE:
6160         return 0;
6161
6162     case OFPACT_CT: {
6163         struct ofpact_conntrack *oc = ofpact_get_CT(a);
6164         enum ofperr err;
6165
6166         if (!dl_type_is_ip_any(flow->dl_type)
6167             || (flow->ct_state & CS_INVALID && oc->flags & NX_CT_F_COMMIT)) {
6168             inconsistent_match(usable_protocols);
6169         }
6170
6171         if (oc->zone_src.field) {
6172             return mf_check_src(&oc->zone_src, flow);
6173         }
6174
6175         err = ofpacts_check(oc->actions, ofpact_ct_get_action_len(oc),
6176                             flow, max_ports, table_id, n_tables,
6177                             usable_protocols);
6178         return err;
6179     }
6180
6181     case OFPACT_CLEAR_ACTIONS:
6182         return 0;
6183
6184     case OFPACT_WRITE_ACTIONS: {
6185         /* Use a temporary copy of 'usable_protocols' because we can't check
6186          * consistency of an action set. */
6187         struct ofpact_nest *on = ofpact_get_WRITE_ACTIONS(a);
6188         enum ofputil_protocol p = *usable_protocols;
6189         return ofpacts_check(on->actions, ofpact_nest_get_action_len(on),
6190                              flow, max_ports, table_id, n_tables, &p);
6191     }
6192
6193     case OFPACT_WRITE_METADATA:
6194         return 0;
6195
6196     case OFPACT_METER: {
6197         uint32_t mid = ofpact_get_METER(a)->meter_id;
6198         if (mid == 0 || mid > OFPM13_MAX) {
6199             return OFPERR_OFPMMFC_INVALID_METER;
6200         }
6201         return 0;
6202     }
6203
6204     case OFPACT_GOTO_TABLE: {
6205         uint8_t goto_table = ofpact_get_GOTO_TABLE(a)->table_id;
6206         if ((table_id != 255 && goto_table <= table_id)
6207             || (n_tables != 255 && goto_table >= n_tables)) {
6208             return OFPERR_OFPBIC_BAD_TABLE_ID;
6209         }
6210         return 0;
6211     }
6212
6213     case OFPACT_GROUP:
6214         return 0;
6215
6216     case OFPACT_UNROLL_XLATE:
6217         /* UNROLL is an internal action that should never be seen via
6218          * OpenFlow. */
6219         return OFPERR_OFPBAC_BAD_TYPE;
6220
6221     case OFPACT_DEBUG_RECIRC:
6222         return 0;
6223
6224     default:
6225         OVS_NOT_REACHED();
6226     }
6227 }
6228
6229 /* Checks that the 'ofpacts_len' bytes of actions in 'ofpacts' are
6230  * appropriate for a packet with the prerequisites satisfied by 'flow' in a
6231  * switch with no more than 'max_ports' ports.
6232  *
6233  * If 'ofpacts' and 'flow' are inconsistent with one another, un-sets in
6234  * '*usable_protocols' the protocols that forbid the inconsistency.  (An
6235  * example of an inconsistency between match and actions is a flow that does
6236  * not match on an MPLS Ethertype but has an action that pops an MPLS label.)
6237  *
6238  * May annotate ofpacts with information gathered from the 'flow'.
6239  *
6240  * May temporarily modify 'flow', but restores the changes before returning. */
6241 enum ofperr
6242 ofpacts_check(struct ofpact ofpacts[], size_t ofpacts_len,
6243               struct flow *flow, ofp_port_t max_ports,
6244               uint8_t table_id, uint8_t n_tables,
6245               enum ofputil_protocol *usable_protocols)
6246 {
6247     struct ofpact *a;
6248     ovs_be16 dl_type = flow->dl_type;
6249     ovs_be16 vlan_tci = flow->vlan_tci;
6250     uint8_t nw_proto = flow->nw_proto;
6251     enum ofperr error = 0;
6252
6253     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6254         error = ofpact_check__(usable_protocols, a, flow,
6255                                max_ports, table_id, n_tables);
6256         if (error) {
6257             break;
6258         }
6259     }
6260     /* Restore fields that may have been modified. */
6261     flow->dl_type = dl_type;
6262     flow->vlan_tci = vlan_tci;
6263     flow->nw_proto = nw_proto;
6264     return error;
6265 }
6266
6267 /* Like ofpacts_check(), but reports inconsistencies as
6268  * OFPERR_OFPBAC_MATCH_INCONSISTENT rather than clearing bits. */
6269 enum ofperr
6270 ofpacts_check_consistency(struct ofpact ofpacts[], size_t ofpacts_len,
6271                           struct flow *flow, ofp_port_t max_ports,
6272                           uint8_t table_id, uint8_t n_tables,
6273                           enum ofputil_protocol usable_protocols)
6274 {
6275     enum ofputil_protocol p = usable_protocols;
6276     enum ofperr error;
6277
6278     error = ofpacts_check(ofpacts, ofpacts_len, flow, max_ports,
6279                           table_id, n_tables, &p);
6280     return (error ? error
6281             : p != usable_protocols ? OFPERR_OFPBAC_MATCH_INCONSISTENT
6282             : 0);
6283 }
6284
6285 static const struct mf_field *
6286 ofpact_get_mf_field(enum ofpact_type type, const void *ofpact)
6287 {
6288     if (type == OFPACT_SET_FIELD) {
6289         const struct ofpact_set_field *orl = ofpact;
6290
6291         return orl->field;
6292     } else if (type == OFPACT_REG_MOVE) {
6293         const struct ofpact_reg_move *orm = ofpact;
6294
6295         return orm->dst.field;
6296     }
6297
6298     return NULL;
6299 }
6300
6301 static enum ofperr
6302 unsupported_nesting(enum ofpact_type action, enum ofpact_type outer_action)
6303 {
6304     VLOG_WARN("%s action doesn't support nested action %s",
6305               ofpact_name(outer_action), ofpact_name(action));
6306     return OFPERR_OFPBAC_BAD_ARGUMENT;
6307 }
6308
6309 static bool
6310 field_requires_ct(enum mf_field_id field)
6311 {
6312     return field == MFF_CT_MARK || field == MFF_CT_LABEL;
6313 }
6314
6315 /* Apply nesting constraints for actions */
6316 static enum ofperr
6317 ofpacts_verify_nested(const struct ofpact *a, enum ofpact_type outer_action)
6318 {
6319     const struct mf_field *field = ofpact_get_mf_field(a->type, a);
6320
6321     if (field && field_requires_ct(field->id) && outer_action != OFPACT_CT) {
6322         VLOG_WARN("cannot set CT fields outside of ct action");
6323         return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
6324     }
6325
6326     if (outer_action) {
6327         ovs_assert(outer_action == OFPACT_WRITE_ACTIONS
6328                    || outer_action == OFPACT_CT);
6329
6330         if (outer_action == OFPACT_CT) {
6331             if (!field) {
6332                 return unsupported_nesting(a->type, outer_action);
6333             } else if (!field_requires_ct(field->id)) {
6334                 VLOG_WARN("%s action doesn't support nested modification "
6335                           "of %s", ofpact_name(outer_action), field->name);
6336                 return OFPERR_OFPBAC_BAD_ARGUMENT;
6337             }
6338         }
6339     }
6340
6341     return 0;
6342 }
6343
6344 /* Verifies that the 'ofpacts_len' bytes of actions in 'ofpacts' are in the
6345  * appropriate order as defined by the OpenFlow spec and as required by Open
6346  * vSwitch.
6347  *
6348  * 'allowed_ovsinsts' is a bitmap of OVSINST_* values, in which 1-bits indicate
6349  * instructions that are allowed within 'ofpacts[]'.
6350  *
6351  * If 'outer_action' is not zero, it specifies that the actions are nested
6352  * within another action of type 'outer_action'. */
6353 static enum ofperr
6354 ofpacts_verify(const struct ofpact ofpacts[], size_t ofpacts_len,
6355                uint32_t allowed_ovsinsts, enum ofpact_type outer_action)
6356 {
6357     const struct ofpact *a;
6358     enum ovs_instruction_type inst;
6359
6360     inst = OVSINST_OFPIT13_METER;
6361     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6362         enum ovs_instruction_type next;
6363         enum ofperr error;
6364
6365         if (a->type == OFPACT_CONJUNCTION) {
6366             OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6367                 if (a->type != OFPACT_CONJUNCTION && a->type != OFPACT_NOTE) {
6368                     VLOG_WARN("\"conjunction\" actions may be used along with "
6369                               "\"note\" but not any other kind of action "
6370                               "(such as the \"%s\" action used here)",
6371                               ofpact_name(a->type));
6372                     return OFPERR_NXBAC_BAD_CONJUNCTION;
6373                 }
6374             }
6375             return 0;
6376         }
6377
6378         error = ofpacts_verify_nested(a, outer_action);
6379         if (error) {
6380             return error;
6381         }
6382
6383         next = ovs_instruction_type_from_ofpact_type(a->type);
6384         if (a > ofpacts
6385             && (inst == OVSINST_OFPIT11_APPLY_ACTIONS
6386                 ? next < inst
6387                 : next <= inst)) {
6388             const char *name = ovs_instruction_name_from_type(inst);
6389             const char *next_name = ovs_instruction_name_from_type(next);
6390
6391             if (next == inst) {
6392                 VLOG_WARN("duplicate %s instruction not allowed, for OpenFlow "
6393                           "1.1+ compatibility", name);
6394             } else {
6395                 VLOG_WARN("invalid instruction ordering: %s must appear "
6396                           "before %s, for OpenFlow 1.1+ compatibility",
6397                           next_name, name);
6398             }
6399             return OFPERR_OFPBAC_UNSUPPORTED_ORDER;
6400         }
6401         if (!((1u << next) & allowed_ovsinsts)) {
6402             const char *name = ovs_instruction_name_from_type(next);
6403
6404             VLOG_WARN("%s instruction not allowed here", name);
6405             return OFPERR_OFPBIC_UNSUP_INST;
6406         }
6407
6408         inst = next;
6409     }
6410
6411     return 0;
6412 }
6413 \f
6414 /* Converting ofpacts to OpenFlow. */
6415
6416 static void
6417 encode_ofpact(const struct ofpact *a, enum ofp_version ofp_version,
6418               struct ofpbuf *out)
6419 {
6420     switch (a->type) {
6421 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                              \
6422         case OFPACT_##ENUM:                                             \
6423             encode_##ENUM(ofpact_get_##ENUM(a), ofp_version, out);      \
6424             return;
6425         OFPACTS
6426 #undef OFPACT
6427     default:
6428         OVS_NOT_REACHED();
6429     }
6430 }
6431
6432 /* Converts the 'ofpacts_len' bytes of ofpacts in 'ofpacts' into OpenFlow
6433  * actions in 'openflow', appending the actions to any existing data in
6434  * 'openflow'. */
6435 size_t
6436 ofpacts_put_openflow_actions(const struct ofpact ofpacts[], size_t ofpacts_len,
6437                              struct ofpbuf *openflow,
6438                              enum ofp_version ofp_version)
6439 {
6440     const struct ofpact *a;
6441     size_t start_size = openflow->size;
6442
6443     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6444         encode_ofpact(a, ofp_version, openflow);
6445     }
6446     return openflow->size - start_size;
6447 }
6448
6449 static enum ovs_instruction_type
6450 ofpact_is_apply_actions(const struct ofpact *a)
6451 {
6452     return (ovs_instruction_type_from_ofpact_type(a->type)
6453             == OVSINST_OFPIT11_APPLY_ACTIONS);
6454 }
6455
6456 void
6457 ofpacts_put_openflow_instructions(const struct ofpact ofpacts[],
6458                                   size_t ofpacts_len,
6459                                   struct ofpbuf *openflow,
6460                                   enum ofp_version ofp_version)
6461 {
6462     const struct ofpact *end = ofpact_end(ofpacts, ofpacts_len);
6463     const struct ofpact *a;
6464
6465     if (ofp_version == OFP10_VERSION) {
6466         ofpacts_put_openflow_actions(ofpacts, ofpacts_len, openflow,
6467                                      ofp_version);
6468         return;
6469     }
6470
6471     a = ofpacts;
6472     while (a < end) {
6473         if (ofpact_is_apply_actions(a)) {
6474             size_t ofs = openflow->size;
6475
6476             instruction_put_OFPIT11_APPLY_ACTIONS(openflow);
6477             do {
6478                 encode_ofpact(a, ofp_version, openflow);
6479                 a = ofpact_next(a);
6480             } while (a < end && ofpact_is_apply_actions(a));
6481             ofpacts_update_instruction_actions(openflow, ofs);
6482         } else {
6483             encode_ofpact(a, ofp_version, openflow);
6484             a = ofpact_next(a);
6485         }
6486     }
6487 }
6488 \f
6489 /* Sets of supported actions. */
6490
6491 /* Two-way translation between OVS's internal "OFPACT_*" representation of
6492  * actions and the "OFPAT_*" representation used in some OpenFlow version.
6493  * (OFPAT_* numbering varies from one OpenFlow version to another, so a given
6494  * instance is specific to one OpenFlow version.) */
6495 struct ofpact_map {
6496     enum ofpact_type ofpact;    /* Internal name for action type. */
6497     int ofpat;                  /* OFPAT_* number from OpenFlow spec. */
6498 };
6499
6500 static const struct ofpact_map *
6501 get_ofpact_map(enum ofp_version version)
6502 {
6503     /* OpenFlow 1.0 actions. */
6504     static const struct ofpact_map of10[] = {
6505         { OFPACT_OUTPUT, 0 },
6506         { OFPACT_SET_VLAN_VID, 1 },
6507         { OFPACT_SET_VLAN_PCP, 2 },
6508         { OFPACT_STRIP_VLAN, 3 },
6509         { OFPACT_SET_ETH_SRC, 4 },
6510         { OFPACT_SET_ETH_DST, 5 },
6511         { OFPACT_SET_IPV4_SRC, 6 },
6512         { OFPACT_SET_IPV4_DST, 7 },
6513         { OFPACT_SET_IP_DSCP, 8 },
6514         { OFPACT_SET_L4_SRC_PORT, 9 },
6515         { OFPACT_SET_L4_DST_PORT, 10 },
6516         { OFPACT_ENQUEUE, 11 },
6517         { 0, -1 },
6518     };
6519
6520     /* OpenFlow 1.1 actions. */
6521     static const struct ofpact_map of11[] = {
6522         { OFPACT_OUTPUT, 0 },
6523         { OFPACT_SET_VLAN_VID, 1 },
6524         { OFPACT_SET_VLAN_PCP, 2 },
6525         { OFPACT_SET_ETH_SRC, 3 },
6526         { OFPACT_SET_ETH_DST, 4 },
6527         { OFPACT_SET_IPV4_SRC, 5 },
6528         { OFPACT_SET_IPV4_DST, 6 },
6529         { OFPACT_SET_IP_DSCP, 7 },
6530         { OFPACT_SET_IP_ECN, 8 },
6531         { OFPACT_SET_L4_SRC_PORT, 9 },
6532         { OFPACT_SET_L4_DST_PORT, 10 },
6533         /* OFPAT_COPY_TTL_OUT (11) not supported. */
6534         /* OFPAT_COPY_TTL_IN (12) not supported. */
6535         { OFPACT_SET_MPLS_LABEL, 13 },
6536         { OFPACT_SET_MPLS_TC, 14 },
6537         { OFPACT_SET_MPLS_TTL, 15 },
6538         { OFPACT_DEC_MPLS_TTL, 16 },
6539         { OFPACT_PUSH_VLAN, 17 },
6540         { OFPACT_STRIP_VLAN, 18 },
6541         { OFPACT_PUSH_MPLS, 19 },
6542         { OFPACT_POP_MPLS, 20 },
6543         { OFPACT_SET_QUEUE, 21 },
6544         { OFPACT_GROUP, 22 },
6545         { OFPACT_SET_IP_TTL, 23 },
6546         { OFPACT_DEC_TTL, 24 },
6547         { 0, -1 },
6548     };
6549
6550     /* OpenFlow 1.2, 1.3, and 1.4 actions. */
6551     static const struct ofpact_map of12[] = {
6552         { OFPACT_OUTPUT, 0 },
6553         /* OFPAT_COPY_TTL_OUT (11) not supported. */
6554         /* OFPAT_COPY_TTL_IN (12) not supported. */
6555         { OFPACT_SET_MPLS_TTL, 15 },
6556         { OFPACT_DEC_MPLS_TTL, 16 },
6557         { OFPACT_PUSH_VLAN, 17 },
6558         { OFPACT_STRIP_VLAN, 18 },
6559         { OFPACT_PUSH_MPLS, 19 },
6560         { OFPACT_POP_MPLS, 20 },
6561         { OFPACT_SET_QUEUE, 21 },
6562         { OFPACT_GROUP, 22 },
6563         { OFPACT_SET_IP_TTL, 23 },
6564         { OFPACT_DEC_TTL, 24 },
6565         { OFPACT_SET_FIELD, 25 },
6566         /* OF1.3+ OFPAT_PUSH_PBB (26) not supported. */
6567         /* OF1.3+ OFPAT_POP_PBB (27) not supported. */
6568         { 0, -1 },
6569     };
6570
6571     switch (version) {
6572     case OFP10_VERSION:
6573         return of10;
6574
6575     case OFP11_VERSION:
6576         return of11;
6577
6578     case OFP12_VERSION:
6579     case OFP13_VERSION:
6580     case OFP14_VERSION:
6581     case OFP15_VERSION:
6582     default:
6583         return of12;
6584     }
6585 }
6586
6587 /* Converts 'ofpacts_bitmap', a bitmap whose bits correspond to OFPACT_*
6588  * values, into a bitmap of actions suitable for OpenFlow 'version', and
6589  * returns the result. */
6590 ovs_be32
6591 ofpact_bitmap_to_openflow(uint64_t ofpacts_bitmap, enum ofp_version version)
6592 {
6593     uint32_t openflow_bitmap = 0;
6594     const struct ofpact_map *x;
6595
6596     for (x = get_ofpact_map(version); x->ofpat >= 0; x++) {
6597         if (ofpacts_bitmap & (UINT64_C(1) << x->ofpact)) {
6598             openflow_bitmap |= 1u << x->ofpat;
6599         }
6600     }
6601     return htonl(openflow_bitmap);
6602 }
6603
6604 /* Converts 'ofpat_bitmap', a bitmap of actions from an OpenFlow message with
6605  * the given 'version' into a bitmap whose bits correspond to OFPACT_* values,
6606  * and returns the result. */
6607 uint64_t
6608 ofpact_bitmap_from_openflow(ovs_be32 ofpat_bitmap, enum ofp_version version)
6609 {
6610     uint64_t ofpact_bitmap = 0;
6611     const struct ofpact_map *x;
6612
6613     for (x = get_ofpact_map(version); x->ofpat >= 0; x++) {
6614         if (ofpat_bitmap & htonl(1u << x->ofpat)) {
6615             ofpact_bitmap |= UINT64_C(1) << x->ofpact;
6616         }
6617     }
6618     return ofpact_bitmap;
6619 }
6620
6621 /* Appends to 's' a string representation of the set of OFPACT_* represented
6622  * by 'ofpacts_bitmap'. */
6623 void
6624 ofpact_bitmap_format(uint64_t ofpacts_bitmap, struct ds *s)
6625 {
6626     if (!ofpacts_bitmap) {
6627         ds_put_cstr(s, "<none>");
6628     } else {
6629         while (ofpacts_bitmap) {
6630             ds_put_format(s, "%s ",
6631                           ofpact_name(rightmost_1bit_idx(ofpacts_bitmap)));
6632             ofpacts_bitmap = zero_rightmost_1bit(ofpacts_bitmap);
6633         }
6634         ds_chomp(s, ' ');
6635     }
6636 }
6637 \f
6638 /* Returns true if 'action' outputs to 'port', false otherwise. */
6639 static bool
6640 ofpact_outputs_to_port(const struct ofpact *ofpact, ofp_port_t port)
6641 {
6642     switch (ofpact->type) {
6643     case OFPACT_OUTPUT:
6644         return ofpact_get_OUTPUT(ofpact)->port == port;
6645     case OFPACT_ENQUEUE:
6646         return ofpact_get_ENQUEUE(ofpact)->port == port;
6647     case OFPACT_CONTROLLER:
6648         return port == OFPP_CONTROLLER;
6649
6650     case OFPACT_OUTPUT_REG:
6651     case OFPACT_BUNDLE:
6652     case OFPACT_SET_VLAN_VID:
6653     case OFPACT_SET_VLAN_PCP:
6654     case OFPACT_STRIP_VLAN:
6655     case OFPACT_PUSH_VLAN:
6656     case OFPACT_SET_ETH_SRC:
6657     case OFPACT_SET_ETH_DST:
6658     case OFPACT_SET_IPV4_SRC:
6659     case OFPACT_SET_IPV4_DST:
6660     case OFPACT_SET_IP_DSCP:
6661     case OFPACT_SET_IP_ECN:
6662     case OFPACT_SET_IP_TTL:
6663     case OFPACT_SET_L4_SRC_PORT:
6664     case OFPACT_SET_L4_DST_PORT:
6665     case OFPACT_REG_MOVE:
6666     case OFPACT_SET_FIELD:
6667     case OFPACT_STACK_PUSH:
6668     case OFPACT_STACK_POP:
6669     case OFPACT_DEC_TTL:
6670     case OFPACT_SET_MPLS_LABEL:
6671     case OFPACT_SET_MPLS_TC:
6672     case OFPACT_SET_MPLS_TTL:
6673     case OFPACT_DEC_MPLS_TTL:
6674     case OFPACT_SET_TUNNEL:
6675     case OFPACT_WRITE_METADATA:
6676     case OFPACT_SET_QUEUE:
6677     case OFPACT_POP_QUEUE:
6678     case OFPACT_FIN_TIMEOUT:
6679     case OFPACT_RESUBMIT:
6680     case OFPACT_LEARN:
6681     case OFPACT_CONJUNCTION:
6682     case OFPACT_MULTIPATH:
6683     case OFPACT_NOTE:
6684     case OFPACT_EXIT:
6685     case OFPACT_UNROLL_XLATE:
6686     case OFPACT_PUSH_MPLS:
6687     case OFPACT_POP_MPLS:
6688     case OFPACT_SAMPLE:
6689     case OFPACT_CLEAR_ACTIONS:
6690     case OFPACT_WRITE_ACTIONS:
6691     case OFPACT_GOTO_TABLE:
6692     case OFPACT_METER:
6693     case OFPACT_GROUP:
6694     case OFPACT_DEBUG_RECIRC:
6695     case OFPACT_CT:
6696     default:
6697         return false;
6698     }
6699 }
6700
6701 /* Returns true if any action in the 'ofpacts_len' bytes of 'ofpacts' outputs
6702  * to 'port', false otherwise. */
6703 bool
6704 ofpacts_output_to_port(const struct ofpact *ofpacts, size_t ofpacts_len,
6705                        ofp_port_t port)
6706 {
6707     const struct ofpact *a;
6708
6709     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6710         if (ofpact_outputs_to_port(a, port)) {
6711             return true;
6712         }
6713     }
6714
6715     return false;
6716 }
6717
6718 /* Returns true if any action in the 'ofpacts_len' bytes of 'ofpacts' outputs
6719  * to 'group', false otherwise. */
6720 bool
6721 ofpacts_output_to_group(const struct ofpact *ofpacts, size_t ofpacts_len,
6722                         uint32_t group_id)
6723 {
6724     const struct ofpact *a;
6725
6726     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6727         if (a->type == OFPACT_GROUP
6728             && ofpact_get_GROUP(a)->group_id == group_id) {
6729             return true;
6730         }
6731     }
6732
6733     return false;
6734 }
6735
6736 bool
6737 ofpacts_equal(const struct ofpact *a, size_t a_len,
6738               const struct ofpact *b, size_t b_len)
6739 {
6740     return a_len == b_len && !memcmp(a, b, a_len);
6741 }
6742
6743 /* Finds the OFPACT_METER action, if any, in the 'ofpacts_len' bytes of
6744  * 'ofpacts'.  If found, returns its meter ID; if not, returns 0.
6745  *
6746  * This function relies on the order of 'ofpacts' being correct (as checked by
6747  * ofpacts_verify()). */
6748 uint32_t
6749 ofpacts_get_meter(const struct ofpact ofpacts[], size_t ofpacts_len)
6750 {
6751     const struct ofpact *a;
6752
6753     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6754         enum ovs_instruction_type inst;
6755
6756         inst = ovs_instruction_type_from_ofpact_type(a->type);
6757         if (a->type == OFPACT_METER) {
6758             return ofpact_get_METER(a)->meter_id;
6759         } else if (inst > OVSINST_OFPIT13_METER) {
6760             break;
6761         }
6762     }
6763
6764     return 0;
6765 }
6766 \f
6767 /* Formatting ofpacts. */
6768
6769 static void
6770 ofpact_format(const struct ofpact *a, struct ds *s)
6771 {
6772     switch (a->type) {
6773 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                              \
6774         case OFPACT_##ENUM:                                             \
6775             format_##ENUM(ALIGNED_CAST(const struct STRUCT *, a), s);   \
6776             break;
6777         OFPACTS
6778 #undef OFPACT
6779     default:
6780         OVS_NOT_REACHED();
6781     }
6782 }
6783
6784 /* Appends a string representing the 'ofpacts_len' bytes of ofpacts in
6785  * 'ofpacts' to 'string'. */
6786 void
6787 ofpacts_format(const struct ofpact *ofpacts, size_t ofpacts_len,
6788                struct ds *string)
6789 {
6790     if (!ofpacts_len) {
6791         ds_put_cstr(string, "drop");
6792     } else {
6793         const struct ofpact *a;
6794
6795         OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6796             if (a != ofpacts) {
6797                 ds_put_cstr(string, ",");
6798             }
6799
6800             /* XXX write-actions */
6801             ofpact_format(a, string);
6802         }
6803     }
6804 }
6805 \f
6806 /* Internal use by helpers. */
6807
6808 void *
6809 ofpact_put(struct ofpbuf *ofpacts, enum ofpact_type type, size_t len)
6810 {
6811     struct ofpact *ofpact;
6812
6813     ofpact_pad(ofpacts);
6814     ofpacts->header = ofpbuf_put_uninit(ofpacts, len);
6815     ofpact = ofpacts->header;
6816     ofpact_init(ofpact, type, len);
6817     return ofpact;
6818 }
6819
6820 void
6821 ofpact_init(struct ofpact *ofpact, enum ofpact_type type, size_t len)
6822 {
6823     memset(ofpact, 0, len);
6824     ofpact->type = type;
6825     ofpact->raw = -1;
6826     ofpact->len = len;
6827 }
6828 \f
6829 /* Updates 'ofpact->len' to the number of bytes in the tail of 'ofpacts'
6830  * starting at 'ofpact'.
6831  *
6832  * This is the correct way to update a variable-length ofpact's length after
6833  * adding the variable-length part of the payload.  (See the large comment
6834  * near the end of ofp-actions.h for more information.) */
6835 void
6836 ofpact_update_len(struct ofpbuf *ofpacts, struct ofpact *ofpact)
6837 {
6838     ovs_assert(ofpact == ofpacts->header);
6839     ofpact->len = (char *) ofpbuf_tail(ofpacts) - (char *) ofpact;
6840 }
6841
6842 /* Pads out 'ofpacts' to a multiple of OFPACT_ALIGNTO bytes in length.  Each
6843  * ofpact_put_<ENUM>() calls this function automatically beforehand, but the
6844  * client must call this itself after adding the final ofpact to an array of
6845  * them.
6846  *
6847  * (The consequences of failing to call this function are probably not dire.
6848  * OFPACT_FOR_EACH will calculate a pointer beyond the end of the ofpacts, but
6849  * not dereference it.  That's undefined behavior, technically, but it will not
6850  * cause a real problem on common systems.  Still, it seems better to call
6851  * it.) */
6852 void
6853 ofpact_pad(struct ofpbuf *ofpacts)
6854 {
6855     unsigned int pad = PAD_SIZE(ofpacts->size, OFPACT_ALIGNTO);
6856     if (pad) {
6857         ofpbuf_put_zeros(ofpacts, pad);
6858     }
6859 }
6860 \f
6861
6862
6863
6864 static char * OVS_WARN_UNUSED_RESULT
6865 ofpact_parse(enum ofpact_type type, char *value, struct ofpbuf *ofpacts,
6866              enum ofputil_protocol *usable_protocols)
6867 {
6868     switch (type) {
6869 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                            \
6870         case OFPACT_##ENUM:                                             \
6871             return parse_##ENUM(value, ofpacts, usable_protocols);
6872         OFPACTS
6873 #undef OFPACT
6874     default:
6875         OVS_NOT_REACHED();
6876     }
6877 }
6878
6879 static bool
6880 ofpact_type_from_name(const char *name, enum ofpact_type *type)
6881 {
6882 #define OFPACT(ENUM, STRUCT, MEMBER, NAME)                            \
6883     if (!strcasecmp(name, NAME)) {                                    \
6884         *type = OFPACT_##ENUM;                                          \
6885         return true;                                                    \
6886     }
6887     OFPACTS
6888 #undef OFPACT
6889
6890     return false;
6891 }
6892
6893 /* Parses 'str' as a series of instructions, and appends them to 'ofpacts'.
6894  *
6895  * Returns NULL if successful, otherwise a malloc()'d string describing the
6896  * error.  The caller is responsible for freeing the returned string.
6897  *
6898  * If 'outer_action' is specified, indicates that the actions being parsed
6899  * are nested within another action of the type specified in 'outer_action'. */
6900 static char * OVS_WARN_UNUSED_RESULT
6901 ofpacts_parse__(char *str, struct ofpbuf *ofpacts,
6902                 enum ofputil_protocol *usable_protocols,
6903                 bool allow_instructions, enum ofpact_type outer_action)
6904 {
6905     int prev_inst = -1;
6906     enum ofperr retval;
6907     char *key, *value;
6908     bool drop = false;
6909     char *pos;
6910
6911     pos = str;
6912     while (ofputil_parse_key_value(&pos, &key, &value)) {
6913         enum ovs_instruction_type inst = OVSINST_OFPIT11_APPLY_ACTIONS;
6914         enum ofpact_type type;
6915         char *error = NULL;
6916         ofp_port_t port;
6917
6918         if (ofpact_type_from_name(key, &type)) {
6919             error = ofpact_parse(type, value, ofpacts, usable_protocols);
6920             inst = ovs_instruction_type_from_ofpact_type(type);
6921         } else if (!strcasecmp(key, "mod_vlan_vid")) {
6922             error = parse_set_vlan_vid(value, ofpacts, true);
6923         } else if (!strcasecmp(key, "mod_vlan_pcp")) {
6924             error = parse_set_vlan_pcp(value, ofpacts, true);
6925         } else if (!strcasecmp(key, "set_nw_ttl")) {
6926             error = parse_SET_IP_TTL(value, ofpacts, usable_protocols);
6927         } else if (!strcasecmp(key, "pop_vlan")) {
6928             error = parse_pop_vlan(ofpacts);
6929         } else if (!strcasecmp(key, "set_tunnel64")) {
6930             error = parse_set_tunnel(value, ofpacts,
6931                                      NXAST_RAW_SET_TUNNEL64);
6932         } else if (!strcasecmp(key, "load")) {
6933             error = parse_reg_load(value, ofpacts);
6934         } else if (!strcasecmp(key, "bundle_load")) {
6935             error = parse_bundle_load(value, ofpacts);
6936         } else if (!strcasecmp(key, "drop")) {
6937             drop = true;
6938         } else if (!strcasecmp(key, "apply_actions")) {
6939             return xstrdup("apply_actions is the default instruction");
6940         } else if (ofputil_port_from_string(key, &port)) {
6941             ofpact_put_OUTPUT(ofpacts)->port = port;
6942         } else {
6943             return xasprintf("unknown action %s", key);
6944         }
6945         if (error) {
6946             return error;
6947         }
6948
6949         if (inst != OVSINST_OFPIT11_APPLY_ACTIONS) {
6950             if (!allow_instructions) {
6951                 return xasprintf("only actions are allowed here (not "
6952                                  "instruction %s)",
6953                                  ovs_instruction_name_from_type(inst));
6954             }
6955             if (inst == prev_inst) {
6956                 return xasprintf("instruction %s may be specified only once",
6957                                  ovs_instruction_name_from_type(inst));
6958             }
6959         }
6960         if (prev_inst != -1 && inst < prev_inst) {
6961             return xasprintf("instruction %s must be specified before %s",
6962                              ovs_instruction_name_from_type(inst),
6963                              ovs_instruction_name_from_type(prev_inst));
6964         }
6965         prev_inst = inst;
6966     }
6967     ofpact_pad(ofpacts);
6968
6969     if (drop && ofpacts->size) {
6970         return xstrdup("\"drop\" must not be accompanied by any other action "
6971                        "or instruction");
6972     }
6973
6974     retval = ofpacts_verify(ofpacts->data, ofpacts->size,
6975                             (allow_instructions
6976                              ? (1u << N_OVS_INSTRUCTIONS) - 1
6977                              : 1u << OVSINST_OFPIT11_APPLY_ACTIONS),
6978                             outer_action);
6979     if (retval) {
6980         return xstrdup("Incorrect instruction ordering");
6981     }
6982
6983     return NULL;
6984 }
6985
6986 static char * OVS_WARN_UNUSED_RESULT
6987 ofpacts_parse(char *str, struct ofpbuf *ofpacts,
6988               enum ofputil_protocol *usable_protocols, bool allow_instructions,
6989               enum ofpact_type outer_action)
6990 {
6991     uint32_t orig_size = ofpacts->size;
6992     char *error = ofpacts_parse__(str, ofpacts, usable_protocols,
6993                                   allow_instructions, outer_action);
6994     if (error) {
6995         ofpacts->size = orig_size;
6996     }
6997     return error;
6998 }
6999
7000 static char * OVS_WARN_UNUSED_RESULT
7001 ofpacts_parse_copy(const char *s_, struct ofpbuf *ofpacts,
7002                    enum ofputil_protocol *usable_protocols,
7003                    bool allow_instructions, enum ofpact_type outer_action)
7004 {
7005     char *error, *s;
7006
7007     *usable_protocols = OFPUTIL_P_ANY;
7008
7009     s = xstrdup(s_);
7010     error = ofpacts_parse(s, ofpacts, usable_protocols, allow_instructions,
7011                           outer_action);
7012     free(s);
7013
7014     return error;
7015 }
7016
7017 /* Parses 's' as a set of OpenFlow actions and appends the actions to
7018  * 'ofpacts'. 'outer_action', if nonzero, specifies that 's' contains actions
7019  * that are nested within the action of type 'outer_action'.
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_actions(const char *s, struct ofpbuf *ofpacts,
7025                       enum ofputil_protocol *usable_protocols)
7026 {
7027     return ofpacts_parse_copy(s, ofpacts, usable_protocols, false, 0);
7028 }
7029
7030 /* Parses 's' as a set of OpenFlow instructions and appends the instructions to
7031  * 'ofpacts'.
7032  *
7033  * Returns NULL if successful, otherwise a malloc()'d string describing the
7034  * error.  The caller is responsible for freeing the returned string. */
7035 char * OVS_WARN_UNUSED_RESULT
7036 ofpacts_parse_instructions(const char *s, struct ofpbuf *ofpacts,
7037                            enum ofputil_protocol *usable_protocols)
7038 {
7039     return ofpacts_parse_copy(s, ofpacts, usable_protocols, true, 0);
7040 }
7041
7042 const char *
7043 ofpact_name(enum ofpact_type type)
7044 {
7045     switch (type) {
7046 #define OFPACT(ENUM, STRUCT, MEMBER, NAME) case OFPACT_##ENUM: return NAME;
7047         OFPACTS
7048 #undef OFPACT
7049     }
7050     return "<unknown>";
7051 }
7052 \f
7053 /* Low-level action decoding and encoding functions. */
7054
7055 /* Everything needed to identify a particular OpenFlow action. */
7056 struct ofpact_hdrs {
7057     uint32_t vendor;              /* 0 if standard, otherwise a vendor code. */
7058     uint16_t type;                /* Type if standard, otherwise subtype. */
7059     uint8_t ofp_version;          /* From ofp_header. */
7060 };
7061
7062 /* Information about a particular OpenFlow action. */
7063 struct ofpact_raw_instance {
7064     /* The action's identity. */
7065     struct ofpact_hdrs hdrs;
7066     enum ofp_raw_action_type raw;
7067
7068     /* Looking up the action. */
7069     struct hmap_node decode_node; /* Based on 'hdrs'. */
7070     struct hmap_node encode_node; /* Based on 'raw' + 'hdrs.ofp_version'. */
7071
7072     /* The action's encoded size.
7073      *
7074      * If this action is fixed-length, 'min_length' == 'max_length'.
7075      * If it is variable length, then 'max_length' is ROUND_DOWN(UINT16_MAX,
7076      * OFP_ACTION_ALIGN) == 65528. */
7077     unsigned short int min_length;
7078     unsigned short int max_length;
7079
7080     /* For actions with a simple integer numeric argument, 'arg_ofs' is the
7081      * offset of that argument from the beginning of the action and 'arg_len'
7082      * its length, both in bytes.
7083      *
7084      * For actions that take other forms, these are both zero. */
7085     unsigned short int arg_ofs;
7086     unsigned short int arg_len;
7087
7088     /* The name of the action, e.g. "OFPAT_OUTPUT" or "NXAST_RESUBMIT". */
7089     const char *name;
7090
7091     /* If this action is deprecated, a human-readable string with a brief
7092      * explanation. */
7093     const char *deprecation;
7094 };
7095
7096 /* Action header. */
7097 struct ofp_action_header {
7098     /* The meaning of other values of 'type' generally depends on the OpenFlow
7099      * version (see enum ofp_raw_action_type).
7100      *
7101      * Across all OpenFlow versions, OFPAT_VENDOR indicates that 'vendor'
7102      * designates an OpenFlow vendor ID and that the remainder of the action
7103      * structure has a vendor-defined meaning.
7104      */
7105 #define OFPAT_VENDOR 0xffff
7106     ovs_be16 type;
7107
7108     /* Always a multiple of 8. */
7109     ovs_be16 len;
7110
7111     /* For type == OFPAT_VENDOR only, this is a vendor ID, e.g. NX_VENDOR_ID or
7112      * ONF_VENDOR_ID.  Other 'type's use this space for some other purpose. */
7113     ovs_be32 vendor;
7114 };
7115 OFP_ASSERT(sizeof(struct ofp_action_header) == 8);
7116
7117 /* Header for Nicira-defined actions and for ONF vendor extensions.
7118  *
7119  * This cannot be used as an entirely generic vendor extension action header,
7120  * because OpenFlow does not specify the location or size of the action
7121  * subtype; it just happens that ONF extensions and Nicira extensions share
7122  * this format. */
7123 struct ext_action_header {
7124     ovs_be16 type;                  /* OFPAT_VENDOR. */
7125     ovs_be16 len;                   /* At least 16. */
7126     ovs_be32 vendor;                /* NX_VENDOR_ID or ONF_VENDOR_ID. */
7127     ovs_be16 subtype;               /* See enum ofp_raw_action_type. */
7128     uint8_t pad[6];
7129 };
7130 OFP_ASSERT(sizeof(struct ext_action_header) == 16);
7131
7132 static bool
7133 ofpact_hdrs_equal(const struct ofpact_hdrs *a,
7134                   const struct ofpact_hdrs *b)
7135 {
7136     return (a->vendor == b->vendor
7137             && a->type == b->type
7138             && a->ofp_version == b->ofp_version);
7139 }
7140
7141 static uint32_t
7142 ofpact_hdrs_hash(const struct ofpact_hdrs *hdrs)
7143 {
7144     return hash_2words(hdrs->vendor, (hdrs->type << 16) | hdrs->ofp_version);
7145 }
7146
7147 #include "ofp-actions.inc2"
7148
7149 static struct hmap *
7150 ofpact_decode_hmap(void)
7151 {
7152     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
7153     static struct hmap hmap;
7154
7155     if (ovsthread_once_start(&once)) {
7156         struct ofpact_raw_instance *inst;
7157
7158         hmap_init(&hmap);
7159         for (inst = all_raw_instances;
7160              inst < &all_raw_instances[ARRAY_SIZE(all_raw_instances)];
7161              inst++) {
7162             hmap_insert(&hmap, &inst->decode_node,
7163                         ofpact_hdrs_hash(&inst->hdrs));
7164         }
7165         ovsthread_once_done(&once);
7166     }
7167     return &hmap;
7168 }
7169
7170 static struct hmap *
7171 ofpact_encode_hmap(void)
7172 {
7173     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
7174     static struct hmap hmap;
7175
7176     if (ovsthread_once_start(&once)) {
7177         struct ofpact_raw_instance *inst;
7178
7179         hmap_init(&hmap);
7180         for (inst = all_raw_instances;
7181              inst < &all_raw_instances[ARRAY_SIZE(all_raw_instances)];
7182              inst++) {
7183             hmap_insert(&hmap, &inst->encode_node,
7184                         hash_2words(inst->raw, inst->hdrs.ofp_version));
7185         }
7186         ovsthread_once_done(&once);
7187     }
7188     return &hmap;
7189 }
7190
7191 static enum ofperr
7192 ofpact_decode_raw(enum ofp_version ofp_version,
7193                   const struct ofp_action_header *oah, size_t length,
7194                   const struct ofpact_raw_instance **instp)
7195 {
7196     const struct ofpact_raw_instance *inst;
7197     struct ofpact_hdrs hdrs;
7198
7199     *instp = NULL;
7200     if (length < sizeof *oah) {
7201         return OFPERR_OFPBAC_BAD_LEN;
7202     }
7203
7204     /* Get base action type. */
7205     if (oah->type == htons(OFPAT_VENDOR)) {
7206         /* Get vendor. */
7207         hdrs.vendor = ntohl(oah->vendor);
7208         if (hdrs.vendor == NX_VENDOR_ID || hdrs.vendor == ONF_VENDOR_ID) {
7209             /* Get extension subtype. */
7210             const struct ext_action_header *nah;
7211
7212             nah = ALIGNED_CAST(const struct ext_action_header *, oah);
7213             if (length < sizeof *nah) {
7214                 return OFPERR_OFPBAC_BAD_LEN;
7215             }
7216             hdrs.type = ntohs(nah->subtype);
7217         } else {
7218             VLOG_WARN_RL(&rl, "OpenFlow action has unknown vendor %#"PRIx32,
7219                          hdrs.vendor);
7220             return OFPERR_OFPBAC_BAD_VENDOR;
7221         }
7222     } else {
7223         hdrs.vendor = 0;
7224         hdrs.type = ntohs(oah->type);
7225     }
7226
7227     hdrs.ofp_version = ofp_version;
7228     HMAP_FOR_EACH_WITH_HASH (inst, decode_node, ofpact_hdrs_hash(&hdrs),
7229                              ofpact_decode_hmap()) {
7230         if (ofpact_hdrs_equal(&hdrs, &inst->hdrs)) {
7231             *instp = inst;
7232             return 0;
7233         }
7234     }
7235
7236     return (hdrs.vendor
7237             ? OFPERR_OFPBAC_BAD_VENDOR_TYPE
7238             : OFPERR_OFPBAC_BAD_TYPE);
7239 }
7240
7241 static enum ofperr
7242 ofpact_pull_raw(struct ofpbuf *buf, enum ofp_version ofp_version,
7243                 enum ofp_raw_action_type *raw, uint64_t *arg)
7244 {
7245     const struct ofp_action_header *oah = buf->data;
7246     const struct ofpact_raw_instance *action;
7247     unsigned int length;
7248     enum ofperr error;
7249
7250     *raw = *arg = 0;
7251     error = ofpact_decode_raw(ofp_version, oah, buf->size, &action);
7252     if (error) {
7253         return error;
7254     }
7255
7256     if (action->deprecation) {
7257         VLOG_INFO_RL(&rl, "%s is deprecated in %s (%s)",
7258                      action->name, ofputil_version_to_string(ofp_version),
7259                      action->deprecation);
7260     }
7261
7262     length = ntohs(oah->len);
7263     if (length > buf->size) {
7264         VLOG_WARN_RL(&rl, "OpenFlow action %s length %u exceeds action buffer "
7265                      "length %"PRIu32, action->name, length, buf->size);
7266         return OFPERR_OFPBAC_BAD_LEN;
7267     }
7268     if (length < action->min_length || length > action->max_length) {
7269         VLOG_WARN_RL(&rl, "OpenFlow action %s length %u not in valid range "
7270                      "[%hu,%hu]", action->name, length,
7271                      action->min_length, action->max_length);
7272         return OFPERR_OFPBAC_BAD_LEN;
7273     }
7274     if (length % 8) {
7275         VLOG_WARN_RL(&rl, "OpenFlow action %s length %u is not a multiple "
7276                      "of 8", action->name, length);
7277         return OFPERR_OFPBAC_BAD_LEN;
7278     }
7279
7280     *raw = action->raw;
7281     *arg = 0;
7282     if (action->arg_len) {
7283         const uint8_t *p;
7284         int i;
7285
7286         p = ofpbuf_at_assert(buf, action->arg_ofs, action->arg_len);
7287         for (i = 0; i < action->arg_len; i++) {
7288             *arg = (*arg << 8) | p[i];
7289         }
7290     }
7291
7292     ofpbuf_pull(buf, length);
7293
7294     return 0;
7295 }
7296
7297 static const struct ofpact_raw_instance *
7298 ofpact_raw_lookup(enum ofp_version ofp_version, enum ofp_raw_action_type raw)
7299 {
7300     const struct ofpact_raw_instance *inst;
7301
7302     HMAP_FOR_EACH_WITH_HASH (inst, encode_node, hash_2words(raw, ofp_version),
7303                              ofpact_encode_hmap()) {
7304         if (inst->raw == raw && inst->hdrs.ofp_version == ofp_version) {
7305             return inst;
7306         }
7307     }
7308     OVS_NOT_REACHED();
7309 }
7310
7311 static void *
7312 ofpact_put_raw(struct ofpbuf *buf, enum ofp_version ofp_version,
7313                enum ofp_raw_action_type raw, uint64_t arg)
7314 {
7315     const struct ofpact_raw_instance *inst;
7316     struct ofp_action_header *oah;
7317     const struct ofpact_hdrs *hdrs;
7318
7319     inst = ofpact_raw_lookup(ofp_version, raw);
7320     hdrs = &inst->hdrs;
7321
7322     oah = ofpbuf_put_zeros(buf, inst->min_length);
7323     oah->type = htons(hdrs->vendor ? OFPAT_VENDOR : hdrs->type);
7324     oah->len = htons(inst->min_length);
7325     oah->vendor = htonl(hdrs->vendor);
7326
7327     switch (hdrs->vendor) {
7328     case 0:
7329         break;
7330
7331     case NX_VENDOR_ID:
7332     case ONF_VENDOR_ID: {
7333         struct ext_action_header *nah = (struct ext_action_header *) oah;
7334         nah->subtype = htons(hdrs->type);
7335         break;
7336     }
7337
7338     default:
7339         OVS_NOT_REACHED();
7340     }
7341
7342     if (inst->arg_len) {
7343         uint8_t *p = (uint8_t *) oah + inst->arg_ofs + inst->arg_len;
7344         int i;
7345
7346         for (i = 0; i < inst->arg_len; i++) {
7347             *--p = arg;
7348             arg >>= 8;
7349         }
7350     } else {
7351         ovs_assert(!arg);
7352     }
7353
7354     return oah;
7355 }
7356
7357 static void
7358 pad_ofpat(struct ofpbuf *openflow, size_t start_ofs)
7359 {
7360     struct ofp_action_header *oah;
7361
7362     ofpbuf_put_zeros(openflow, PAD_SIZE(openflow->size - start_ofs, 8));
7363
7364     oah = ofpbuf_at_assert(openflow, start_ofs, sizeof *oah);
7365     oah->len = htons(openflow->size - start_ofs);
7366 }
7367