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