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