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