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