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