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