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