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