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