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