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