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