static int check_object(struct kmem_cache *s, struct page *page,
					void *object, u8 val)
{
	u8 *p = object;
	u8 *endobject = object + s->object_size;

	if (s->flags & SLAB_RED_ZONE) {
		if (!check_bytes_and_report(s, page, object, "Redzone",
			object - s->red_left_pad, val, s->red_left_pad))
			return 0;

		if (!check_bytes_and_report(s, page, object, "Redzone",
			endobject, val, s->inuse - s->object_size))
			return 0;
	} else {
		if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
			check_bytes_and_report(s, page, p, "Alignment padding",
				endobject, POISON_INUSE,
				s->inuse - s->object_size);
		}
	}

	if (s->flags & SLAB_POISON) {
		if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
			(!check_bytes_and_report(s, page, p, "Poison", p,
					POISON_FREE, s->object_size - 1) ||
			 !check_bytes_and_report(s, page, p, "Poison",
				p + s->object_size - 1, POISON_END, 1)))
			return 0;
		/*
		 * check_pad_bytes cleans up on its own.
		 */
		check_pad_bytes(s, page, p);
	}

	if (!s->offset && val == SLUB_RED_ACTIVE)
		/*
		 * Object and freepointer overlap. Cannot check
		 * freepointer while object is allocated.
		 */
		return 1;

	/* Check free pointer validity */
	if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
		object_err(s, page, p, "Freepointer corrupt");
		/*
		 * No choice but to zap it and thus lose the remainder
		 * of the free objects in this slab. May cause
		 * another error because the object count is now wrong.
		 */
		set_freepointer(s, p, NULL);
		return 0;
	}
	return 1;
}


mm: slub: add missing TID bump in kmem_cache_alloc_bulk()

When kmem_cache_alloc_bulk() attempts to allocate N objects from a percpu
freelist of length M, and N > M > 0, it will first remove the M elements
from the percpu freelist, then call ___slab_alloc() to allocate the next
element and repopulate the percpu freelist. ___slab_alloc() can re-enable
IRQs via allocate_slab(), so the TID must be bumped before ___slab_alloc()
to properly commit the freelist head change.

Fix it by unconditionally bumping c->tid when entering the slowpath.

Cc: stable@vger.kernel.org
Fixes: ebe909e0fdb3 ("slub: improve bulk alloc strategy")
Signed-off-by: Jann Horn <jannh@google.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>

static inline int free_consistency_checks(struct kmem_cache *s,
		struct page *page, void *object, unsigned long addr)
{
	if (!check_valid_pointer(s, page, object)) {
		slab_err(s, page, "Invalid object pointer 0x%p", object);
		return 0;
	}

	if (on_freelist(s, page, object)) {
		object_err(s, page, object, "Object already free");
		return 0;
	}

	if (!check_object(s, page, object, SLUB_RED_ACTIVE))
		return 0;

	if (unlikely(s != page->slab_cache)) {
		if (!PageSlab(page)) {
			slab_err(s, page, "Attempt to free object(0x%p) outside of slab",
				 object);
		} else if (!page->slab_cache) {
			pr_err("SLUB <none>: no slab for object 0x%p.\n",
			       object);
			dump_stack();
		} else
			object_err(s, page, object,
					"page slab pointer corrupt.");
		return 0;
	}
	return 1;
}


static ssize_t store_user_store(struct kmem_cache *s,
				const char *buf, size_t length)
{
	if (any_slab_objects(s))
		return -EBUSY;

	s->flags &= ~SLAB_STORE_USER;
	if (buf[0] == '1') {
		s->flags &= ~__CMPXCHG_DOUBLE;
		s->flags |= SLAB_STORE_USER;
	}
	calculate_sizes(s, -1);
	return length;
}


static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
{
	return sprintf(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
}


static inline void metadata_access_enable(void)
{
	kasan_disable_current();
}


init_kmem_cache_node(struct kmem_cache_node *n)
{
	n->nr_partial = 0;
	spin_lock_init(&n->list_lock);
	INIT_LIST_HEAD(&n->partial);
#ifdef CONFIG_SLUB_DEBUG
	atomic_long_set(&n->nr_slabs, 0);
	atomic_long_set(&n->total_objects, 0);
	INIT_LIST_HEAD(&n->full);
#endif
}


void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
					int node, unsigned long caller)
{
	struct kmem_cache *s;
	void *ret;

	if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
		ret = kmalloc_large_node(size, gfpflags, node);

		trace_kmalloc_node(caller, ret,
				   size, PAGE_SIZE << get_order(size),
				   gfpflags, node);

		return ret;
	}

	s = kmalloc_slab(size, gfpflags);

	if (unlikely(ZERO_OR_NULL_PTR(s)))
		return s;

	ret = slab_alloc_node(s, gfpflags, node, caller);

	/* Honor the call site pointer we received. */
	trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);

	return ret;
}


static ssize_t slab_attr_store(struct kobject *kobj,
				struct attribute *attr,
				const char *buf, size_t len)
{
	struct slab_attribute *attribute;
	struct kmem_cache *s;
	int err;

	attribute = to_slab_attr(attr);
	s = to_slab(kobj);

	if (!attribute->store)
		return -EIO;

	err = attribute->store(s, buf, len);
#ifdef CONFIG_MEMCG
	if (slab_state >= FULL && err >= 0 && is_root_cache(s)) {
		struct kmem_cache *c;

		mutex_lock(&slab_mutex);
		if (s->max_attr_size < len)
			s->max_attr_size = len;

		/*
		 * This is a best effort propagation, so this function's return
		 * value will be determined by the parent cache only. This is
		 * basically because not all attributes will have a well
		 * defined semantics for rollbacks - most of the actions will
		 * have permanent effects.
		 *
		 * Returning the error value of any of the children that fail
		 * is not 100 % defined, in the sense that users seeing the
		 * error code won't be able to know anything about the state of
		 * the cache.
		 *
		 * Only returning the error code for the parent cache at least
		 * has well defined semantics. The cache being written to
		 * directly either failed or succeeded, in which case we loop
		 * through the descendants with best-effort propagation.
		 */
		for_each_memcg_cache(c, s)
			attribute->store(c, buf, len);
		mutex_unlock(&slab_mutex);
	}
#endif
	return err;


static void add_full(struct kmem_cache *s,
	struct kmem_cache_node *n, struct page *page)
{
	if (!(s->flags & SLAB_STORE_USER))
		return;

	lockdep_assert_held(&n->list_lock);
	list_add(&page->slab_list, &n->full);
}


static inline struct page *alloc_slab_page(struct kmem_cache *s,
		gfp_t flags, int node, struct kmem_cache_order_objects oo)
{
	struct page *page;
	unsigned int order = oo_order(oo);

	if (node == NUMA_NO_NODE)
		page = alloc_pages(flags, order);
	else
		page = __alloc_pages_node(node, flags, order);

	if (page && charge_slab_page(page, flags, order, s)) {
		__free_pages(page, order);
		page = NULL;
	}

	return page;
}


int __kmem_cache_shutdown(struct kmem_cache *s)
{
	int node;
	struct kmem_cache_node *n;

	flush_all(s);
	/* Attempt to free all objects */
	for_each_kmem_cache_node(s, node, n) {
		free_partial(s, n);
		if (n->nr_partial || slabs_node(s, node))
			return 1;
	}
	sysfs_slab_remove(s);
	return 0;
}


static int __init setup_slub_debug(char *str)
{
	slub_debug = DEBUG_DEFAULT_FLAGS;
	if (*str++ != '=' || !*str)
		/*
		 * No options specified. Switch on full debugging.
		 */
		goto out;

	if (*str == ',')
		/*
		 * No options but restriction on slabs. This means full
		 * debugging for slabs matching a pattern.
		 */
		goto check_slabs;

	slub_debug = 0;
	if (*str == '-')
		/*
		 * Switch off all debugging measures.
		 */
		goto out;

	/*
	 * Determine which debug features should be switched on
	 */
	for (; *str && *str != ','; str++) {
		switch (tolower(*str)) {
		case 'f':
			slub_debug |= SLAB_CONSISTENCY_CHECKS;
			break;
		case 'z':
			slub_debug |= SLAB_RED_ZONE;
			break;
		case 'p':
			slub_debug |= SLAB_POISON;
			break;
		case 'u':
			slub_debug |= SLAB_STORE_USER;
			break;
		case 't':
			slub_debug |= SLAB_TRACE;
			break;
		case 'a':
			slub_debug |= SLAB_FAILSLAB;
			break;
		case 'o':
			/*
			 * Avoid enabling debugging on caches if its minimum
			 * order would increase as a result.
			 */
			disable_higher_order_debug = 1;
			break;
		default:
			pr_err("slub_debug option '%c' unknown. skipped\n",
			       *str);
		}
	}

check_slabs:
	if (*str == ',')
		slub_debug_slabs = str + 1;
out:
	if ((static_branch_unlikely(&init_on_alloc) ||
	     static_branch_unlikely(&init_on_free)) &&
	    (slub_debug & SLAB_POISON))
		pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
	return 1;
}


static inline int calculate_order(unsigned int size)
{
	unsigned int order;
	unsigned int min_objects;
	unsigned int max_objects;

	/*
	 * Attempt to find best configuration for a slab. This
	 * works by first attempting to generate a layout with
	 * the best configuration and backing off gradually.
	 *
	 * First we increase the acceptable waste in a slab. Then
	 * we reduce the minimum objects required in a slab.
	 */
	min_objects = slub_min_objects;
	if (!min_objects)
		min_objects = 4 * (fls(nr_cpu_ids) + 1);
	max_objects = order_objects(slub_max_order, size);
	min_objects = min(min_objects, max_objects);

	while (min_objects > 1) {
		unsigned int fraction;

		fraction = 16;
		while (fraction >= 4) {
			order = slab_order(size, min_objects,
					slub_max_order, fraction);
			if (order <= slub_max_order)
				return order;
			fraction /= 2;
		}
		min_objects--;
	}

	/*
	 * We were unable to place multiple objects in a slab. Now
	 * lets see if we can place a single object there.
	 */
	order = slab_order(size, 1, slub_max_order, 1);
	if (order <= slub_max_order)
		return order;

	/*
	 * Doh this slab cannot be placed using slub_max_order.
	 */
	order = slab_order(size, 1, MAX_ORDER, 1);
	if (order < MAX_ORDER)
		return order;
	return -ENOSYS;
}


static void slab_mem_offline_callback(void *arg)
{
	struct kmem_cache_node *n;
	struct kmem_cache *s;
	struct memory_notify *marg = arg;
	int offline_node;

	offline_node = marg->status_change_nid_normal;

	/*
	 * If the node still has available memory. we need kmem_cache_node
	 * for it yet.
	 */
	if (offline_node < 0)
		return;

	mutex_lock(&slab_mutex);
	list_for_each_entry(s, &slab_caches, list) {
		n = get_node(s, offline_node);
		if (n) {
			/*
			 * if n->nr_slabs > 0, slabs still exist on the node
			 * that is going down. We were unable to free them,
			 * and offline_pages() function shouldn't call this
			 * callback. So, we must fail.
			 */
			BUG_ON(slabs_node(s, offline_node));

			s->node[offline_node] = NULL;
			kmem_cache_free(kmem_cache_node, n);
		}
	}
	mutex_unlock(&slab_mutex);
}


static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
				 size_t length)
{
	unsigned int objects;
	int err;

	err = kstrtouint(buf, 10, &objects);
	if (err)
		return err;
	if (objects && !kmem_cache_has_cpu_partial(s))
		return -EINVAL;

	slub_set_cpu_partial(s, objects);
	flush_all(s);
	return length;
}


static inline int check_object(struct kmem_cache *s, struct page *page,
			void *object, u8 val) { return 1; }


void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr) {}


static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
{
	unsigned long freeptr_addr = (unsigned long)object + s->offset;

#ifdef CONFIG_SLAB_FREELIST_HARDENED
	BUG_ON(object == fp); /* naive detection of double free or corruption */
#endif

	*(void **)freeptr_addr = freelist_ptr(s, fp, freeptr_addr);
}


static inline unsigned int tid_to_cpu(unsigned long tid)
{
	return tid % TID_STEP;
}


static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
{
	return sprintf(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
}


static ssize_t red_zone_store(struct kmem_cache *s,
				const char *buf, size_t length)
{
	if (any_slab_objects(s))
		return -EBUSY;

	s->flags &= ~SLAB_RED_ZONE;
	if (buf[0] == '1') {
		s->flags |= SLAB_RED_ZONE;
	}
	calculate_sizes(s, -1);
	return length;
}


static void init_kmem_cache_cpus(struct kmem_cache *s)
{
	int cpu;

	for_each_possible_cpu(cpu)
		per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
}


static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
{
	return x.x & OO_MASK;
}


static int __init setup_slub_min_objects(char *str)
{
	get_option(&str, (int *)&slub_min_objects);

	return 1;
}


ssize_t slabinfo_write(struct file *file, const char __user *buffer,
		       size_t count, loff_t *ppos)
{
	return -EIO;


static inline void add_partial(struct kmem_cache_node *n,
				struct page *page, int tail)
{
	lockdep_assert_held(&n->list_lock);
	__add_partial(n, page, tail);
}


static int calculate_sizes(struct kmem_cache *s, int forced_order)
{
	slab_flags_t flags = s->flags;
	unsigned int size = s->object_size;
	unsigned int order;

	/*
	 * Round up object size to the next word boundary. We can only
	 * place the free pointer at word boundaries and this determines
	 * the possible location of the free pointer.
	 */
	size = ALIGN(size, sizeof(void *));

#ifdef CONFIG_SLUB_DEBUG
	/*
	 * Determine if we can poison the object itself. If the user of
	 * the slab may touch the object after free or before allocation
	 * then we should never poison the object itself.
	 */
	if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
			!s->ctor)
		s->flags |= __OBJECT_POISON;
	else
		s->flags &= ~__OBJECT_POISON;

	/*
	 * If we are Redzoning then check if there is some space between the
	 * end of the object and the free pointer. If not then add an
	 * additional word to have some bytes to store Redzone information.
	 */
	if ((flags & SLAB_RED_ZONE) && size == s->object_size)
		size += sizeof(void *);
#endif

	/*
	 * With that we have determined the number of bytes in actual use
	 * by the object. This is the potential offset to the free pointer.
	 */
	s->inuse = size;

	if (((flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) ||
		s->ctor)) {
		/*
		 * Relocate free pointer after the object if it is not
		 * permitted to overwrite the first word of the object on
		 * kmem_cache_free.
		 *
		 * This is the case if we do RCU, have a constructor or
		 * destructor or are poisoning the objects.
		 */
		s->offset = size;
		size += sizeof(void *);
	}

#ifdef CONFIG_SLUB_DEBUG
	if (flags & SLAB_STORE_USER)
		/*
		 * Need to store information about allocs and frees after
		 * the object.
		 */
		size += 2 * sizeof(struct track);
#endif

	kasan_cache_create(s, &size, &s->flags);
#ifdef CONFIG_SLUB_DEBUG
	if (flags & SLAB_RED_ZONE) {
		/*
		 * Add some empty padding so that we can catch
		 * overwrites from earlier objects rather than let
		 * tracking information or the free pointer be
		 * corrupted if a user writes before the start
		 * of the object.
		 */
		size += sizeof(void *);

		s->red_left_pad = sizeof(void *);
		s->red_left_pad = ALIGN(s->red_left_pad, s->align);
		size += s->red_left_pad;
	}
#endif

	/*
	 * SLUB stores one object immediately after another beginning from
	 * offset 0. In order to align the objects we have to simply size
	 * each object to conform to the alignment.
	 */
	size = ALIGN(size, s->align);
	s->size = size;
	if (forced_order >= 0)
		order = forced_order;
	else
		order = calculate_order(size);

	if ((int)order < 0)
		return 0;

	s->allocflags = 0;
	if (order)
		s->allocflags |= __GFP_COMP;

	if (s->flags & SLAB_CACHE_DMA)
		s->allocflags |= GFP_DMA;

	if (s->flags & SLAB_CACHE_DMA32)
		s->allocflags |= GFP_DMA32;

	if (s->flags & SLAB_RECLAIM_ACCOUNT)
		s->allocflags |= __GFP_RECLAIMABLE;

	/*
	 * Determine the number of objects per slab
	 */
	s->oo = oo_make(order, size);
	s->min = oo_make(get_order(size), size);
	if (oo_objects(s->oo) > oo_objects(s->max))
		s->max = s->oo;

	return !!oo_objects(s->oo);
}


static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
{
#ifdef CONFIG_SLUB_CPU_PARTIAL
	return !kmem_cache_debug(s);
#else
	return false;
#endif
}


static void set_track(struct kmem_cache *s, void *object,
			enum track_item alloc, unsigned long addr)
{
	struct track *p = get_track(s, object, alloc);

	if (addr) {
#ifdef CONFIG_STACKTRACE
		unsigned int nr_entries;

		metadata_access_enable();
		nr_entries = stack_trace_save(p->addrs, TRACK_ADDRS_COUNT, 3);
		metadata_access_disable();

		if (nr_entries < TRACK_ADDRS_COUNT)
			p->addrs[nr_entries] = 0;
#endif
		p->addr = addr;
		p->cpu = smp_processor_id();
		p->pid = current->pid;
		p->when = jiffies;
	} else {
		memset(p, 0, sizeof(struct track));
	}
}


static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
{
	unsigned long off = s->inuse;	/* The end of info */

	if (s->offset)
		/* Freepointer is placed after the object. */
		off += sizeof(void *);

	if (s->flags & SLAB_STORE_USER)
		/* We also have user information there */
		off += 2 * sizeof(struct track);

	off += kasan_metadata_size(s);

	if (size_from_object(s) == off)
		return 1;

	return check_bytes_and_report(s, page, p, "Object padding",
			p + off, POISON_INUSE, size_from_object(s) - off);
}


static int validate_slab_node(struct kmem_cache *s,
		struct kmem_cache_node *n)
{
	unsigned long count = 0;
	struct page *page;
	unsigned long flags;

	spin_lock_irqsave(&n->list_lock, flags);

	list_for_each_entry(page, &n->partial, slab_list) {
		validate_slab(s, page);
		count++;
	}
	if (count != n->nr_partial)
		pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
		       s->name, count, n->nr_partial);

	if (!(s->flags & SLAB_STORE_USER))
		goto out;

	list_for_each_entry(page, &n->full, slab_list) {
		validate_slab(s, page);
		count++;
	}
	if (count != atomic_long_read(&n->nr_slabs))
		pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
		       s->name, count, atomic_long_read(&n->nr_slabs));

out:
	spin_unlock_irqrestore(&n->list_lock, flags);
	return count;
}


ofp-actions: Fix use-after-free while decoding RAW_ENCAP.

While decoding RAW_ENCAP action, decode_ed_prop() might re-allocate
ofpbuf if there is no enough space left.  However, function
'decode_NXAST_RAW_ENCAP' continues to use old pointer to 'encap'
structure leading to write-after-free and incorrect decoding.

  ==3549105==ERROR: AddressSanitizer: heap-use-after-free on address
  0x60600000011a at pc 0x0000005f6cc6 bp 0x7ffc3a2d4410 sp 0x7ffc3a2d4408
  WRITE of size 2 at 0x60600000011a thread T0
    #0 0x5f6cc5 in decode_NXAST_RAW_ENCAP lib/ofp-actions.c:4461:20
    #1 0x5f0551 in ofpact_decode ./lib/ofp-actions.inc2:4777:16
    #2 0x5ed17c in ofpacts_decode lib/ofp-actions.c:7752:21
    #3 0x5eba9a in ofpacts_pull_openflow_actions__ lib/ofp-actions.c:7791:13
    #4 0x5eb9fc in ofpacts_pull_openflow_actions lib/ofp-actions.c:7835:12
    #5 0x64bb8b in ofputil_decode_packet_out lib/ofp-packet.c:1113:17
    #6 0x65b6f4 in ofp_print_packet_out lib/ofp-print.c:148:13
    #7 0x659e3f in ofp_to_string__ lib/ofp-print.c:1029:16
    #8 0x659b24 in ofp_to_string lib/ofp-print.c:1244:21
    #9 0x65a28c in ofp_print lib/ofp-print.c:1288:28
    #10 0x540d11 in ofctl_ofp_parse utilities/ovs-ofctl.c:2814:9
    #11 0x564228 in ovs_cmdl_run_command__ lib/command-line.c:247:17
    #12 0x56408a in ovs_cmdl_run_command lib/command-line.c:278:5
    #13 0x5391ae in main utilities/ovs-ofctl.c:179:9
    #14 0x7f6911ce9081 in __libc_start_main (/lib64/libc.so.6+0x27081)
    #15 0x461fed in _start (utilities/ovs-ofctl+0x461fed)

Fix that by getting a new pointer before using.

Credit to OSS-Fuzz.

Fuzzer regression test will fail only with AddressSanitizer enabled.

Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=27851
Fixes: f839892a206a ("OF support and translation of generic encap and decap")
Acked-by: William Tu <u9012063@gmail.com>
Signed-off-by: Ilya Maximets <i.maximets@ovn.org>

format_SET_MPLS_LABEL(const struct ofpact_mpls_label *a,
                      const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sset_mpls_label(%s%"PRIu32"%s)%s",
                  colors.paren, colors.end, ntohl(a->label),
                  colors.paren, colors.end);
}

Open vSwitch (aka openvswitch) 2.11.0 through 2.15.0 has a use-after-free in decode_NXAST_RAW_ENCAP (called from ofpact_decode and ofpacts_decode) during the decoding of a RAW_ENCAP action.


parse_GOTO_TABLE(char *arg, const struct ofpact_parse_params *pp)
{
    struct ofpact_goto_table *ogt = ofpact_put_GOTO_TABLE(pp->ofpacts);
    if (!ofputil_table_from_string(arg, pp->table_map, &ogt->table_id)) {
        return xasprintf("unknown table \"%s\"", arg);
    }
    return NULL;
}


check_SET_TUNNEL(const struct ofpact_tunnel *a OVS_UNUSED,
                 const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


check_SET_ETH_DST(const struct ofpact_mac *a OVS_UNUSED,
                  const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


check_WRITE_ACTIONS(struct ofpact_nest *a,
                    const struct ofpact_check_params *cp)
{
    /* Use a temporary copy of 'cp' to avoid updating 'cp->usable_protocols',
     * since we can't check consistency of an action set. */
    struct ofpact_check_params tmp = *cp;
    return ofpacts_check(a->actions, ofpact_nest_get_action_len(a), &tmp);
}


format_SET_QUEUE(const struct ofpact_queue *a,
                 const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sset_queue:%s%"PRIu32,
                  colors.param, colors.end, a->queue_id);
}


check_SET_IPV4_SRC(const struct ofpact_ipv4 *a OVS_UNUSED,
                   struct ofpact_check_params *cp)
{
    return check_set_ipv4(cp);
}


check_SET_IP_DSCP(const struct ofpact_dscp *a OVS_UNUSED,
                  struct ofpact_check_params *cp)
{
    return check_set_ip(cp);
}


parse_SET_IPV4_SRC(char *arg, const struct ofpact_parse_params *pp)
{
    return str_to_ip(arg, &ofpact_put_SET_IPV4_SRC(pp->ofpacts)->ipv4);
}


check_SET_ETH_SRC(const struct ofpact_mac *a OVS_UNUSED,
                  const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


decode_OFPAT_RAW11_SET_NW_TTL(uint8_t ttl,
                              enum ofp_version ofp_version OVS_UNUSED,
                              struct ofpbuf *out)
{
    ofpact_put_SET_IP_TTL(out)->ttl = ttl;
    return 0;
}


parse_PUSH_MPLS(char *arg, const struct ofpact_parse_params *pp)
{
    uint16_t ethertype;
    char *error;

    error = str_to_u16(arg, "push_mpls", &ethertype);
    if (!error) {
        ofpact_put_PUSH_MPLS(pp->ofpacts)->ethertype = htons(ethertype);
    }
    return error;
}


check_SET_MPLS_LABEL(const struct ofpact_mpls_label *a OVS_UNUSED,
                     struct ofpact_check_params *cp)
{
    return check_set_mpls(cp);
}


format_SET_IPV4_SRC(const struct ofpact_ipv4 *a,
                    const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%smod_nw_src:%s"IP_FMT,
                  colors.param, colors.end, IP_ARGS(a->ipv4));
}


decode_LEARN_specs(const void *p, const void *end,
                   const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap,
                   struct ofpbuf *ofpacts)
{
    struct ofpact_learn *learn = ofpacts->header;

    while (p != end) {
        struct ofpact_learn_spec *spec;
        uint16_t header = ntohs(get_be16(&p));

        if (!header) {
            break;
        }

        spec = ofpbuf_put_zeros(ofpacts, sizeof *spec);
        learn = ofpacts->header;

        spec->src_type = header & NX_LEARN_SRC_MASK;
        spec->dst_type = header & NX_LEARN_DST_MASK;
        spec->n_bits = header & NX_LEARN_N_BITS_MASK;

        /* Check for valid src and dst type combination. */
        if (spec->dst_type == NX_LEARN_DST_MATCH ||
            spec->dst_type == NX_LEARN_DST_LOAD ||
            (spec->dst_type == NX_LEARN_DST_OUTPUT &&
             spec->src_type == NX_LEARN_SRC_FIELD)) {
            /* OK. */
        } else {
            return OFPERR_OFPBAC_BAD_ARGUMENT;
        }

        /* Check that the arguments don't overrun the end of the action. */
        if ((char *) end - (char *) p < learn_min_len(header)) {
            return OFPERR_OFPBAC_BAD_LEN;
        }

        /* Get the source. */
        const uint8_t *imm = NULL;
        unsigned int imm_bytes = 0;
        enum ofperr error;
        if (spec->src_type == NX_LEARN_SRC_FIELD) {
            error = get_subfield(spec->n_bits, &p, &spec->src, vl_mff_map,
                                 tlv_bitmap);
            if (error) {
                return error;
            }
        } else {
            int p_bytes = 2 * DIV_ROUND_UP(spec->n_bits, 16);
            p = (const uint8_t *) p + p_bytes;

            imm_bytes = DIV_ROUND_UP(spec->n_bits, 8);
            imm = (const uint8_t *) p - imm_bytes;
        }

        /* Get the destination. */
        if (spec->dst_type == NX_LEARN_DST_MATCH ||
            spec->dst_type == NX_LEARN_DST_LOAD) {
            error = get_subfield(spec->n_bits, &p, &spec->dst, vl_mff_map,
                                 tlv_bitmap);
            if (error) {
                return error;
            }
        }

        if (imm) {
            uint8_t *src_imm = ofpbuf_put_zeros(ofpacts,
                                                OFPACT_ALIGN(imm_bytes));
            memcpy(src_imm, imm, imm_bytes);

            learn = ofpacts->header;
        }
    }
    ofpact_finish_LEARN(ofpacts, &learn);

    if (!is_all_zeros(p, (char *) end - (char *) p)) {
        return OFPERR_OFPBAC_BAD_ARGUMENT;
    }

    return 0;
}


check_GROUP(const struct ofpact_group *a OVS_UNUSED,
            const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


format_SET_IP_DSCP(const struct ofpact_dscp *a,
                   const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%smod_nw_tos:%s%d",
                  colors.param, colors.end, a->dscp);
}


parse_DEC_NSH_TTL(char *arg OVS_UNUSED, const struct ofpact_parse_params *pp)
{
    ofpact_put_DEC_NSH_TTL(pp->ofpacts);
    return NULL;
}


format_CLEAR_ACTIONS(const struct ofpact_null *a OVS_UNUSED,
                     const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sclear_actions%s", colors.value, colors.end);
}


parse_RESUBMIT(char *arg, const struct ofpact_parse_params *pp)
{
    struct ofpact_resubmit *resubmit;
    char *in_port_s, *table_s, *ct_s;

    resubmit = ofpact_put_RESUBMIT(pp->ofpacts);

    in_port_s = strsep(&arg, ",");
    if (in_port_s && in_port_s[0]) {
        if (!ofputil_port_from_string(in_port_s, pp->port_map,
                                      &resubmit->in_port)) {
            return xasprintf("%s: resubmit to unknown port", in_port_s);
        }
    } else {
        resubmit->in_port = OFPP_IN_PORT;
    }

    table_s = strsep(&arg, ",");
    if (table_s && table_s[0]) {
        if (!ofputil_table_from_string(table_s, pp->table_map,
                                       &resubmit->table_id)) {
            return xasprintf("%s: resubmit to unknown table", table_s);
        }
    } else {
        resubmit->table_id = 255;
    }

    ct_s = strsep(&arg, ",");
    if (ct_s && ct_s[0]) {
        if (strcmp(ct_s, "ct")) {
            return xasprintf("%s: unknown parameter", ct_s);
        }
        resubmit->with_ct_orig = true;
    } else {
        resubmit->with_ct_orig = false;
    }

    if (resubmit->in_port == OFPP_IN_PORT && resubmit->table_id == 255) {
        return xstrdup("at least one \"in_port\" or \"table\" must be "
                       "specified  on resubmit");
    }
    return NULL;
}


check_NOTE(const struct ofpact_note *a OVS_UNUSED,
           const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


parse_SET_FIELD(const char *arg, const struct ofpact_parse_params *pp)
{
    char *copy = xstrdup(arg);
    char *error = set_field_parse__(copy, pp);
    free(copy);
    return error;
}


format_CLONE(const struct ofpact_nest *a,
             const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sclone(%s", colors.paren, colors.end);
    ofpacts_format(a->actions, ofpact_nest_get_action_len(a), fp);
    ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
}


decode_NXAST_RAW_REG_LOAD2(const struct ext_action_header *eah,
                           enum ofp_version ofp_version OVS_UNUSED,
                           const struct vl_mff_map *vl_mff_map,
                           uint64_t *tlv_bitmap, struct ofpbuf *out)
{
    struct ofpbuf b = ofpbuf_const_initializer(eah, ntohs(eah->len));
    ofpbuf_pull(&b, OBJECT_OFFSETOF(eah, pad));

    union mf_value value, mask;
    const struct mf_field *field;
    enum ofperr error;
    error = mf_vl_mff_nx_pull_entry(&b, vl_mff_map, &field, &value, &mask,
                                    tlv_bitmap);
    if (error) {
        return error;
    }

    if (!is_all_zeros(b.data, b.size)) {
        return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
    }

    if (!field->writable) {
        VLOG_WARN_RL(&rl, "destination field %s is not writable", field->name);
        return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
    }

    /* Put value and mask. */
    ofpact_put_reg_load2(out, field, &value, &mask);
    return 0;
}


parse_bundle_load(const char *arg, const struct ofpact_parse_params *pp)
{
    return bundle_parse_load(arg, pp->port_map, pp->ofpacts);
}


format_PUSH_VLAN(const struct ofpact_push_vlan *push_vlan,
                 const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%spush_vlan:%s%#"PRIx16,
                  colors.param, colors.end, ntohs(push_vlan->ethertype));
}


parse_SET_ETH_SRC(char *arg, const struct ofpact_parse_params *pp)
{
    return str_to_mac(arg, &ofpact_put_SET_ETH_SRC(pp->ofpacts)->mac);
}


encode_ENCAP(const struct ofpact_encap *encap,
             enum ofp_version ofp_version OVS_UNUSED,
             struct ofpbuf *out)
{
    size_t start_ofs = out->size;
    struct nx_action_encap *nae = put_NXAST_ENCAP(out);
    int i;

    nae->new_pkt_type = encap->new_pkt_type;
    nae->hdr_size = htons(encap->hdr_size);
    const struct ofpact_ed_prop *prop = encap->props;
    for (i = 0; i < encap->n_props; i++) {
        encode_ed_prop(&prop, out);
    }
    pad_ofpat(out, start_ofs);
}


decode_OFPAT_RAW11_PUSH_VLAN(ovs_be16 eth_type,
                             enum ofp_version ofp_version OVS_UNUSED,
                             struct ofpbuf *out)
{
    struct ofpact_push_vlan *push_vlan;
    if (!eth_type_vlan(eth_type)) {
        return OFPERR_OFPBAC_BAD_ARGUMENT;
    }
    push_vlan = ofpact_put_PUSH_VLAN(out);
    push_vlan->ethertype = eth_type;
    return 0;
}


encode_CLONE(const struct ofpact_nest *clone,
              enum ofp_version ofp_version, struct ofpbuf *out)
{
    size_t len;
    const size_t ofs = out->size;
    struct ext_action_header *eah;

    put_NXAST_CLONE(out);
    len = ofpacts_put_openflow_actions(clone->actions,
                                       ofpact_nest_get_action_len(clone),
                                       out, ofp_version);
    len += sizeof *eah;
    eah = ofpbuf_at(out, ofs, sizeof *eah);
    eah->len = htons(len);
}


parse_SET_VLAN_PCP(char *arg, const struct ofpact_parse_params *pp)
{
    return parse_set_vlan_pcp(arg, false, pp);
}


format_METER(const struct ofpact_meter *a,
             const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%smeter:%s%"PRIu32,
                  colors.param, colors.end, a->meter_id);
}


format_DECAP(const struct ofpact_decap *a,
             const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sdecap(%s", colors.paren, colors.end);
    if (a->new_pkt_type != htonl(PT_USE_NEXT_PROTO)) {
        ds_put_format(fp->s, "packet_type(ns=%"PRIu16",id=%#"PRIx16")",
                      pt_ns(a->new_pkt_type),
                      pt_ns_type(a->new_pkt_type));
    }
    ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
}


check_CT_CLEAR(const struct ofpact_null *a OVS_UNUSED,
               const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


parse_NAT(char *arg, const struct ofpact_parse_params *pp)
{
    struct ofpact_nat *on = ofpact_put_NAT(pp->ofpacts);
    char *key, *value;

    on->flags = 0;
    on->range_af = AF_UNSPEC;

    while (ofputil_parse_key_value(&arg, &key, &value)) {
        char *error = NULL;

        if (!strcmp(key, "src")) {
            on->flags |= NX_NAT_F_SRC;
            error = str_to_nat_range(value, on);
        } else if (!strcmp(key, "dst")) {
            on->flags |= NX_NAT_F_DST;
            error = str_to_nat_range(value, on);
        } else if (!strcmp(key, "persistent")) {
            on->flags |= NX_NAT_F_PERSISTENT;
        } else if (!strcmp(key, "hash")) {
            on->flags |= NX_NAT_F_PROTO_HASH;
        } else if (!strcmp(key, "random")) {
            on->flags |= NX_NAT_F_PROTO_RANDOM;
        } else {
            error = xasprintf("invalid key \"%s\" in \"nat\" argument",
                              key);
        }
        if (error) {
            return error;
        }
    }
    if (on->flags & NX_NAT_F_SRC && on->flags & NX_NAT_F_DST) {
        return xasprintf("May only specify one of \"src\" or \"dst\".");
    }
    if (!(on->flags & NX_NAT_F_SRC || on->flags & NX_NAT_F_DST)) {
        if (on->flags) {
            return xasprintf("Flags allowed only with \"src\" or \"dst\".");
        }
        if (on->range_af != AF_UNSPEC) {
            return xasprintf("Range allowed only with \"src\" or \"dst\".");
        }
    }
    if (on->flags & NX_NAT_F_PROTO_HASH && on->flags & NX_NAT_F_PROTO_RANDOM) {
        return xasprintf("Both \"hash\" and \"random\" are not allowed.");
    }

    return NULL;
}


check_OUTPUT(const struct ofpact_output *a,
             const struct ofpact_check_params *cp)
{
    return ofpact_check_output_port(a->port, cp->max_ports);
}


parse_WRITE_ACTIONS(char *arg, const struct ofpact_parse_params *pp)
{
    size_t ofs = ofpacts_pull(pp->ofpacts);
    struct ofpact_nest *on;
    char *error;

    /* Add a Write-Actions instruction and then pull it off. */
    ofpact_put(pp->ofpacts, OFPACT_WRITE_ACTIONS, sizeof *on);
    ofpbuf_pull(pp->ofpacts, sizeof *on);

    /* Parse nested actions.
     *
     * We pulled off "write-actions" and the previous actions because the
     * OFPACT_WRITE_ACTIONS is only partially constructed: its length is such
     * that it doesn't actually include the nested actions.  That means that
     * ofpacts_parse() would reject them as being part of an Apply-Actions that
     * follows a Write-Actions, which is an invalid order.  */
    error = ofpacts_parse(arg, pp, false, OFPACT_WRITE_ACTIONS);

    /* Put the Write-Actions back on and update its length. */
    on = ofpbuf_push_uninit(pp->ofpacts, sizeof *on);
    on->ofpact.len = pp->ofpacts->size;

    /* Put any previous actions or instructions back on. */
    ofpbuf_push_uninit(pp->ofpacts, ofs);

    return error;
}


encode_NOTE(const struct ofpact_note *note,
            enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
{
    size_t start_ofs = out->size;
    struct nx_action_note *nan;

    put_NXAST_NOTE(out);
    out->size = out->size - sizeof nan->note;

    ofpbuf_put(out, note->data, note->length);
    pad_ofpat(out, start_ofs);
}


format_SET_IP_TTL(const struct ofpact_ip_ttl *a,
                  const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%smod_nw_ttl:%s%d",
                  colors.param, colors.end, a->ttl);
}


format_WRITE_ACTIONS(const struct ofpact_nest *a,
                     const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%swrite_actions(%s", colors.paren, colors.end);
    ofpacts_format(a->actions, ofpact_nest_get_action_len(a), fp);
    ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
}


check_SET_VLAN_PCP(struct ofpact_vlan_pcp *a, struct ofpact_check_params *cp)
{
    /* Remember if we saw a vlan tag in the flow to aid translating to OpenFlow
     * 1.1+ if need be. */
    ovs_be16 *tci = &cp->match->flow.vlans[0].tci;
    a->flow_has_vlan = (*tci & htons(VLAN_CFI)) != 0;
    if (!a->flow_has_vlan && !a->push_vlan_if_needed) {
        inconsistent_match(&cp->usable_protocols);
    }

    /* Temporarily mark that we have a vlan tag. */
    *tci |= htons(VLAN_CFI);

    return 0;
}


format_POP_QUEUE(const struct ofpact_null *a OVS_UNUSED,
                 const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%spop_queue%s", colors.value, colors.end);
}


format_BUNDLE(const struct ofpact_bundle *a,
              const struct ofpact_format_params *fp)
{
    bundle_format(a, fp->port_map, fp->s);
}


format_STACK_POP(const struct ofpact_stack *a,
                 const struct ofpact_format_params *fp)
{
    nxm_format_stack_pop(a, fp->s);
}


check_SET_IPV4_DST(const struct ofpact_ipv4 *a OVS_UNUSED,
                   struct ofpact_check_params *cp)
{
    return check_set_ipv4(cp);
}


parse_OUTPUT_TRUNC(const char *arg,
                   const struct ofpact_parse_params *pp OVS_UNUSED)
{
    /* Disable output_trunc parsing.  Expose as output(port=N,max_len=M) and
     * reuse parse_OUTPUT to parse output_trunc action. */
    return xasprintf("unknown action %s", arg);
}


parse_SET_MPLS_TC(char *arg, const struct ofpact_parse_params *pp)
{
    struct ofpact_mpls_tc *mpls_tc = ofpact_put_SET_MPLS_TC(pp->ofpacts);

    if (*arg == '\0') {
        return xstrdup("set_mpls_tc: expected tc.");
    }

    mpls_tc->tc = atoi(arg);
    return NULL;
}


ofpact_parse(enum ofpact_type type, char *value,
             const struct ofpact_parse_params *pp)
{
    switch (type) {
#define OFPACT(ENUM, STRUCT, MEMBER, NAME)                              \
        case OFPACT_##ENUM:                                             \
            return parse_##ENUM(value, pp);
        OFPACTS
#undef OFPACT
    default:
        OVS_NOT_REACHED();
    }
}


check_DEC_NSH_TTL(const struct ofpact_null *a OVS_UNUSED,
                  struct ofpact_check_params *cp)
{
    struct flow *flow = &cp->match->flow;
    if (flow->packet_type != htonl(PT_NSH) &&
        flow->dl_type != htons(ETH_TYPE_NSH)) {
        inconsistent_match(&cp->usable_protocols);
    }
    return 0;
}


check_CONTROLLER(const struct ofpact_controller *a OVS_UNUSED,
                 const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


decode_ofpat_set_field(const struct ofp12_action_set_field *oasf,
                       bool may_mask, const struct vl_mff_map *vl_mff_map,
                       uint64_t *tlv_bitmap, struct ofpbuf *ofpacts)
{
    struct ofpbuf b = ofpbuf_const_initializer(oasf, ntohs(oasf->len));
    ofpbuf_pull(&b, OBJECT_OFFSETOF(oasf, pad));

    union mf_value value, mask;
    const struct mf_field *field;
    enum ofperr error;
    error  = mf_vl_mff_nx_pull_entry(&b, vl_mff_map, &field, &value,
                                     may_mask ? &mask : NULL, tlv_bitmap);
    if (error) {
        return (error == OFPERR_OFPBMC_BAD_MASK
                ? OFPERR_OFPBAC_BAD_SET_MASK
                : error);
    }

    if (!may_mask) {
        memset(&mask, 0xff, field->n_bytes);
    }

    if (!is_all_zeros(b.data, b.size)) {
        return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
    }

    /* OpenFlow says specifically that one may not set OXM_OF_IN_PORT via
     * Set-Field. */
    if (field->id == MFF_IN_PORT_OXM) {
        return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
    }

    /* oxm_length is now validated to be compatible with mf_value. */
    if (!field->writable) {
        VLOG_WARN_RL(&rl, "destination field %s is not writable",
                     field->name);
        return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
    }

    /* The value must be valid for match.  OpenFlow 1.5 also says,
     * "In an OXM_OF_VLAN_VID set-field action, the OFPVID_PRESENT bit must be
     * a 1-bit in oxm_value and in oxm_mask." */
    if (!mf_is_value_valid(field, &value)
        || (field->id == MFF_VLAN_VID
            && (!(mask.be16 & htons(OFPVID12_PRESENT))
                || !(value.be16 & htons(OFPVID12_PRESENT))))) {
        struct ds ds = DS_EMPTY_INITIALIZER;
        mf_format(field, &value, NULL, NULL, &ds);
        VLOG_WARN_RL(&rl, "Invalid value for set field %s: %s",
                     field->name, ds_cstr(&ds));
        ds_destroy(&ds);

        return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
    }

    ofpact_put_set_field(ofpacts, field, &value, &mask);
    return 0;
}


decode_NXAST_RAW_DEBUG_SLOW(struct ofpbuf *out)
{
    if (!enable_debug) {
        return OFPERR_OFPBAC_BAD_VENDOR_TYPE;
    }

    ofpact_put_DEBUG_SLOW(out);
    return 0;
}


format_OUTPUT_REG(const struct ofpact_output_reg *a,
                  const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%soutput:%s", colors.special, colors.end);
    mf_format_subfield(&a->src, fp->s);
}


check_SET_IP_TTL(const struct ofpact_ip_ttl *a OVS_UNUSED,
                 struct ofpact_check_params *cp)
{
    return check_set_ip(cp);
}


parse_SET_IP_ECN(char *arg, const struct ofpact_parse_params *pp)
{
    uint8_t ecn;
    char *error;

    error = str_to_u8(arg, "ECN", &ecn);
    if (error) {
        return error;
    }

    if (ecn & ~IP_ECN_MASK) {
        return xasprintf("%s: not a valid ECN", arg);
    }
    ofpact_put_SET_IP_ECN(pp->ofpacts)->ecn = ecn;
    return NULL;
}


check_SET_IP_ECN(const struct ofpact_ecn *a OVS_UNUSED,
                 struct ofpact_check_params *cp)
{
    return check_set_ip(cp);
}


parse_SET_IP_TTL(char *arg, const struct ofpact_parse_params *pp)

{
    uint8_t ttl;
    char *error;

    error = str_to_u8(arg, "TTL", &ttl);
    if (error) {
        return error;
    }

    ofpact_put_SET_IP_TTL(pp->ofpacts)->ttl = ttl;
    return NULL;
}


check_SET_L4_DST_PORT(struct ofpact_l4_port *a, struct ofpact_check_params *cp)
{
    return check_set_l4_port(a, cp);
}


format_WRITE_METADATA(const struct ofpact_metadata *a,
                      const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%swrite_metadata:%s%#"PRIx64,
                  colors.param, colors.end, ntohll(a->metadata));
    if (a->mask != OVS_BE64_MAX) {
        ds_put_format(fp->s, "/%#"PRIx64, ntohll(a->mask));
    }
}


format_FIN_TIMEOUT(const struct ofpact_fin_timeout *a,
                   const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sfin_timeout(%s", colors.paren, colors.end);
    if (a->fin_idle_timeout) {
        ds_put_format(fp->s, "%sidle_timeout=%s%"PRIu16",",
                      colors.param, colors.end, a->fin_idle_timeout);
    }
    if (a->fin_hard_timeout) {
        ds_put_format(fp->s, "%shard_timeout=%s%"PRIu16",",
                      colors.param, colors.end, a->fin_hard_timeout);
    }
    ds_chomp(fp->s, ',');
    ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
}


check_ENQUEUE(const struct ofpact_enqueue *a,
              const struct ofpact_check_params *cp)
{
    if (ofp_to_u16(a->port) >= ofp_to_u16(cp->max_ports)
        && a->port != OFPP_IN_PORT
        && a->port != OFPP_LOCAL) {
        return OFPERR_OFPBAC_BAD_OUT_PORT;
    }
    return 0;
}


parse_truncate_subfield(const char *arg_,
                        const struct ofpact_parse_params *pp,
                        struct ofpact_output_trunc *output_trunc)
{
    char *key, *value;
    char *arg = CONST_CAST(char *, arg_);

    while (ofputil_parse_key_value(&arg, &key, &value)) {
        if (!strcmp(key, "port")) {
            if (!ofputil_port_from_string(value, pp->port_map,
                                          &output_trunc->port)) {
                return xasprintf("output to unknown truncate port: %s",
                                  value);
            }
            if (ofp_to_u16(output_trunc->port) > ofp_to_u16(OFPP_MAX)) {
                if (output_trunc->port != OFPP_LOCAL &&
                    output_trunc->port != OFPP_IN_PORT)
                return xasprintf("output to unsupported truncate port: %s",
                                 value);
            }
        } else if (!strcmp(key, "max_len")) {
            char *err;

            err = str_to_u32(value, &output_trunc->max_len);
            if (err) {
                return err;
            }
        } else {
            return xasprintf("invalid key '%s' in output_trunc argument",
                                key);
        }
    }
    return NULL;
}


decode_LEARN_common(const struct nx_action_learn *nal,
                    enum ofp_raw_action_type raw,
                    struct ofpact_learn *learn)
{
    if (nal->pad) {
        return OFPERR_OFPBAC_BAD_ARGUMENT;
    }

    learn->ofpact.raw = raw;
    learn->idle_timeout = ntohs(nal->idle_timeout);
    learn->hard_timeout = ntohs(nal->hard_timeout);
    learn->priority = ntohs(nal->priority);
    learn->cookie = nal->cookie;
    learn->table_id = nal->table_id;
    learn->fin_idle_timeout = ntohs(nal->fin_idle_timeout);
    learn->fin_hard_timeout = ntohs(nal->fin_hard_timeout);
    learn->flags = ntohs(nal->flags);

    if (learn->table_id == 0xff) {
        return OFPERR_OFPBAC_BAD_ARGUMENT;
    }

    return 0;
}


ofpacts_pull_openflow_actions__(struct ofpbuf *openflow,
                                unsigned int actions_len,
                                enum ofp_version version,
                                uint32_t allowed_ovsinsts,
                                struct ofpbuf *ofpacts,
                                enum ofpact_type outer_action,
                                const struct vl_mff_map *vl_mff_map,
                                uint64_t *ofpacts_tlv_bitmap)
{
    const struct ofp_action_header *actions;
    enum ofperr error;

    if (actions_len % OFP_ACTION_ALIGN != 0) {
        VLOG_WARN_RL(&rl, "OpenFlow message actions length %u is not a "
                     "multiple of %d", actions_len, OFP_ACTION_ALIGN);
        return OFPERR_OFPBRC_BAD_LEN;
    }

    actions = ofpbuf_try_pull(openflow, actions_len);
    if (actions == NULL) {
        VLOG_WARN_RL(&rl, "OpenFlow message actions length %u exceeds "
                     "remaining message length (%"PRIu32")",
                     actions_len, openflow->size);
        return OFPERR_OFPBRC_BAD_LEN;
    }

    error = ofpacts_decode(actions, actions_len, version, vl_mff_map,
                           ofpacts_tlv_bitmap, ofpacts);
    if (!error) {
        error = ofpacts_verify(ofpacts->data, ofpacts->size, allowed_ovsinsts,
                               outer_action);
    }
    if (error) {
        ofpbuf_clear(ofpacts);
    }
    return error;
}


encode_RESUBMIT(const struct ofpact_resubmit *resubmit,
                enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
{
    uint16_t in_port = ofp_to_u16(resubmit->in_port);

    if (resubmit->table_id == 0xff
        && resubmit->ofpact.raw == NXAST_RAW_RESUBMIT) {
        put_NXAST_RESUBMIT(out, in_port);
    } else {
        struct nx_action_resubmit *nar;
        nar = resubmit->with_ct_orig
            ? put_NXAST_RESUBMIT_TABLE_CT(out) : put_NXAST_RESUBMIT_TABLE(out);
        nar->table = resubmit->table_id;
        nar->in_port = htons(in_port);
    }
}


format_ENCAP(const struct ofpact_encap *a,
             const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sencap(%s", colors.paren, colors.end);
    ds_put_format(fp->s, "%s", format_encap_pkt_type(a->new_pkt_type));
    if (a->n_props > 0) {
        ds_put_format(fp->s, "%s(%s", colors.paren, colors.end);
        format_ed_props(fp->s, a->n_props, a->props);
        ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
    }
    ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
}


ofpact_is_allowed_in_actions_set(const struct ofpact *a)
{
    return action_set_classify(a) != ACTION_SLOT_INVALID;
}


ofpact_check_output_port(ofp_port_t port, ofp_port_t max_ports)
{
    switch (port) {
    case OFPP_IN_PORT:
    case OFPP_TABLE:
    case OFPP_NORMAL:
    case OFPP_FLOOD:
    case OFPP_ALL:
    case OFPP_CONTROLLER:
    case OFPP_LOCAL:
        return 0;

    case OFPP_NONE:
        return OFPERR_OFPBAC_BAD_OUT_PORT;

    default:
        if (ofp_to_u16(port) < ofp_to_u16(max_ports)) {
            return 0;
        }
        return OFPERR_OFPBAC_BAD_OUT_PORT;
    }
}


format_DEC_TTL(const struct ofpact_cnt_ids *a,
               const struct ofpact_format_params *fp)
{
    size_t i;

    ds_put_format(fp->s, "%sdec_ttl%s", colors.paren, colors.end);
    if (a->ofpact.raw == NXAST_RAW_DEC_TTL_CNT_IDS) {
        ds_put_format(fp->s, "%s(%s", colors.paren, colors.end);
        for (i = 0; i < a->n_controllers; i++) {
            if (i) {
                ds_put_cstr(fp->s, ",");
            }
            ds_put_format(fp->s, "%"PRIu16, a->cnt_ids[i]);
        }
        ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
    }
}


encode_DEBUG_SLOW(const struct ofpact_null *n OVS_UNUSED,
                  enum ofp_version ofp_version OVS_UNUSED,
                  struct ofpbuf *out)
{
    put_NXAST_DEBUG_SLOW(out);
}


check_WRITE_METADATA(const struct ofpact_metadata *a OVS_UNUSED,
                     const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


parse_ed_props(const uint16_t prop_class, char **arg, int *n_props, struct ofpbuf *out)
{
    char *key, *value, *err;
    uint8_t prop_type;

    while (ofputil_parse_key_value(arg, &key, &value)) {
        if (!parse_ed_prop_type(prop_class, key, &prop_type)) {
            return xasprintf("Invalid property: %s", key);
        }
        if (value == NULL) {
            return xasprintf("Missing the value for property: %s", key);
        }
        err = parse_ed_prop_value(prop_class, prop_type, value, out);
        if (err != NULL) {
            return err;
        }
        (*n_props)++;
    }
    return NULL;
}


check_STACK_PUSH(const struct ofpact_stack *a,
                 const struct ofpact_check_params *cp)
{
    return nxm_stack_push_check(a, cp->match);
}


format_CONTROLLER(const struct ofpact_controller *a,
                  const struct ofpact_format_params *fp)
{
    if (a->reason == OFPR_ACTION && !a->controller_id && !a->userdata_len
        && !a->pause && a->meter_id == NX_CTLR_NO_METER) {
        ds_put_format(fp->s, "%sCONTROLLER:%s%"PRIu16,
                      colors.special, colors.end, a->max_len);
    } else {
        enum ofp_packet_in_reason reason = a->reason;

        ds_put_format(fp->s, "%scontroller(%s", colors.paren, colors.end);
        if (reason != OFPR_ACTION) {
            char reasonbuf[OFPUTIL_PACKET_IN_REASON_BUFSIZE];

            ds_put_format(fp->s, "%sreason=%s%s,", colors.param, colors.end,
                          ofputil_packet_in_reason_to_string(
                              reason, reasonbuf, sizeof reasonbuf));
        }
        if (a->max_len != UINT16_MAX) {
            ds_put_format(fp->s, "%smax_len=%s%"PRIu16",",
                          colors.param, colors.end, a->max_len);
        }
        if (a->controller_id != 0) {
            ds_put_format(fp->s, "%sid=%s%"PRIu16",",
                          colors.param, colors.end, a->controller_id);
        }
        if (a->userdata_len) {
            ds_put_format(fp->s, "%suserdata=%s", colors.param, colors.end);
            format_hex_arg(fp->s, a->userdata, a->userdata_len);
            ds_put_char(fp->s, ',');
        }
        if (a->pause) {
            ds_put_format(fp->s, "%spause%s,", colors.value, colors.end);
        }
        if (a->meter_id != NX_CTLR_NO_METER) {
            ds_put_format(fp->s, "%smeter_id=%s%"PRIu32",",
                          colors.param, colors.end, a->meter_id);
        }
        ds_chomp(fp->s, ',');
        ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
    }
}


check_SET_MPLS_TC(const struct ofpact_mpls_tc *a OVS_UNUSED,
                  struct ofpact_check_params *cp)
{
    return check_set_mpls(cp);
}


set_field_parse__(char *arg, const struct ofpact_parse_params *pp)
{
    char *value;
    char *delim;
    char *key;
    const struct mf_field *mf;
    union mf_value sf_value, sf_mask;
    char *error;

    error = set_field_split_str(arg, &key, &value, &delim);
    if (error) {
        return error;
    }

    mf = mf_from_name(key);
    if (!mf) {
        return xasprintf("%s is not a valid OXM field name", key);
    }
    if (!mf->writable) {
        return xasprintf("%s is read-only", key);
    }

    delim[0] = '\0';
    error = mf_parse(mf, value, pp->port_map, &sf_value, &sf_mask);
    if (error) {
        return error;
    }

    if (!mf_is_value_valid(mf, &sf_value)) {
        return xasprintf("%s is not a valid value for field %s", value, key);
    }

    *pp->usable_protocols &= mf->usable_protocols_exact;

    ofpact_put_set_field(pp->ofpacts, mf, &sf_value, &sf_mask);
    return NULL;
}


parse_LEARN(char *arg, const struct ofpact_parse_params *pp)
{
    return learn_parse(arg, pp->port_map, pp->table_map, pp->ofpacts);
}


decode_NXAST_RAW_LEARN2(const struct nx_action_learn2 *nal,
                        enum ofp_version ofp_version OVS_UNUSED,
                        const struct vl_mff_map *vl_mff_map,
                        uint64_t *tlv_bitmap, struct ofpbuf *ofpacts)
{
    struct ofpbuf b = ofpbuf_const_initializer(nal, ntohs(nal->up.len));
    struct ofpact_learn *learn;
    enum ofperr error;

    if (nal->pad2) {
        return OFPERR_NXBAC_MUST_BE_ZERO;
    }

    learn = ofpact_put_LEARN(ofpacts);
    error = decode_LEARN_common(&nal->up, NXAST_RAW_LEARN2, learn);
    if (error) {
        return error;
    }

    learn->limit = ntohl(nal->limit);

    if (learn->flags & ~(NX_LEARN_F_SEND_FLOW_REM |
                         NX_LEARN_F_DELETE_LEARNED |
                         NX_LEARN_F_WRITE_RESULT)) {
        return OFPERR_OFPBAC_BAD_ARGUMENT;
    }

    ofpbuf_pull(&b, sizeof *nal);

    if (learn->flags & NX_LEARN_F_WRITE_RESULT) {
        error = nx_pull_header(&b, vl_mff_map, &learn->result_dst.field, NULL);
        if (error) {
            return error;
        }
        if (!learn->result_dst.field->writable) {
            return OFPERR_OFPBAC_BAD_SET_ARGUMENT;
        }
        learn->result_dst.ofs = ntohs(nal->result_dst_ofs);
        learn->result_dst.n_bits = 1;
    } else if (nal->result_dst_ofs) {
        return OFPERR_OFPBAC_BAD_ARGUMENT;
    }

    return decode_LEARN_specs(b.data, (char *) nal + ntohs(nal->up.len),
                              vl_mff_map, tlv_bitmap, ofpacts);
}


check_set_ip(struct ofpact_check_params *cp)
{
    if (!is_ip_any(&cp->match->flow)) {
        inconsistent_match(&cp->usable_protocols);
    }
    return 0;
}


format_CT(const struct ofpact_conntrack *a,
          const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sct(%s", colors.paren, colors.end);
    if (a->flags & NX_CT_F_COMMIT) {
        ds_put_format(fp->s, "%scommit%s,", colors.value, colors.end);
    }
    if (a->flags & NX_CT_F_FORCE) {
        ds_put_format(fp->s, "%sforce%s,", colors.value, colors.end);
    }
    if (a->recirc_table != NX_CT_RECIRC_NONE) {
        ds_put_format(fp->s, "%stable=%s", colors.special, colors.end);
        ofputil_format_table(a->recirc_table, fp->table_map, fp->s);
        ds_put_char(fp->s, ',');
    }
    if (a->zone_src.field) {
        ds_put_format(fp->s, "%szone=%s", colors.param, colors.end);
        mf_format_subfield(&a->zone_src, fp->s);
        ds_put_char(fp->s, ',');
    } else if (a->zone_imm) {
        ds_put_format(fp->s, "%szone=%s%"PRIu16",",
                      colors.param, colors.end, a->zone_imm);
    }
    /* If the first action is a NAT action, format it outside of the 'exec'
     * envelope. */
    const struct ofpact *action = a->actions;
    size_t actions_len = ofpact_ct_get_action_len(a);
    if (actions_len && action->type == OFPACT_NAT) {
        format_NAT(ofpact_get_NAT(action), fp);
        ds_put_char(fp->s, ',');
        actions_len -= OFPACT_ALIGN(action->len);
        action = ofpact_next(action);
    }
    if (actions_len) {
        ds_put_format(fp->s, "%sexec(%s", colors.paren, colors.end);
        ofpacts_format(action, actions_len, fp);
        ds_put_format(fp->s, "%s),%s", colors.paren, colors.end);
    }
    format_alg(a->alg, fp->s);
    ds_chomp(fp->s, ',');
    ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
}


format_GROUP(const struct ofpact_group *a,
             const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sgroup:%s%"PRIu32,
                  colors.special, colors.end, a->group_id);
}


decode_NXAST_RAW_CLONE(const struct ext_action_header *eah,
                       enum ofp_version ofp_version,
                       const struct vl_mff_map *vl_mff_map,
                       uint64_t *tlv_bitmap, struct ofpbuf *out)
{
    int error;
    struct ofpbuf openflow;
    const size_t clone_offset = ofpacts_pull(out);
    struct ofpact_nest *clone = ofpact_put_CLONE(out);

    /* decode action list */
    ofpbuf_pull(out, sizeof(*clone));
    openflow = ofpbuf_const_initializer(
                    eah + 1, ntohs(eah->len) - sizeof *eah);
    error = ofpacts_pull_openflow_actions__(&openflow, openflow.size,
                                            ofp_version,
                                            1u << OVSINST_OFPIT11_APPLY_ACTIONS,
                                            out, 0, vl_mff_map, tlv_bitmap);
    if (error) {
        return error;
    }
    clone = ofpbuf_push_uninit(out, sizeof *clone);
    out->header = &clone->ofpact;
    ofpact_finish_CLONE(out, &clone);
    ofpbuf_push_uninit(out, clone_offset);
    return error;
}


check_PUSH_MPLS(const struct ofpact_push_mpls *a,
                struct ofpact_check_params *cp)
{
    struct flow *flow = &cp->match->flow;

    if (flow->packet_type != htonl(PT_ETH)) {
        inconsistent_match(&cp->usable_protocols);
    }
    flow->dl_type = a->ethertype;

    /* The packet is now MPLS and the MPLS payload is opaque.
     * Thus nothing can be assumed about the network protocol.
     * Temporarily mark that we have no nw_proto. */
    flow->nw_proto = 0;

    return 0;
}


parse_DEBUG_RECIRC(char *arg OVS_UNUSED, const struct ofpact_parse_params *pp)
{
    ofpact_put_DEBUG_RECIRC(pp->ofpacts);
    return NULL;
}


parse_SET_L4_DST_PORT(char *arg, const struct ofpact_parse_params *pp)
{
    return str_to_u16(arg, "destination port",
                      &ofpact_put_SET_L4_DST_PORT(pp->ofpacts)->port);
}


decode_copy_field__(ovs_be16 src_offset, ovs_be16 dst_offset, ovs_be16 n_bits,
                    const void *action, ovs_be16 action_len, size_t oxm_offset,
                    const struct vl_mff_map *vl_mff_map,
                    uint64_t *tlv_bitmap, struct ofpbuf *ofpacts)
{
    struct ofpact_reg_move *move = ofpact_put_REG_MOVE(ofpacts);
    enum ofperr error;

    move->ofpact.raw = ONFACT_RAW13_COPY_FIELD;
    move->src.ofs = ntohs(src_offset);
    move->src.n_bits = ntohs(n_bits);
    move->dst.ofs = ntohs(dst_offset);
    move->dst.n_bits = ntohs(n_bits);

    struct ofpbuf b = ofpbuf_const_initializer(action, ntohs(action_len));
    ofpbuf_pull(&b, oxm_offset);

    error = mf_vl_mff_nx_pull_header(&b, vl_mff_map, &move->src.field, NULL,
                                     tlv_bitmap);
    if (error) {
        return error;
    }
    error = mf_vl_mff_nx_pull_header(&b, vl_mff_map, &move->dst.field, NULL,
                                     tlv_bitmap);
    if (error) {
        return error;
    }

    if (!is_all_zeros(b.data, b.size)) {
        return OFPERR_NXBRC_MUST_BE_ZERO;
    }

    return nxm_reg_move_check(move, NULL);
}


check_BUNDLE(const struct ofpact_bundle *a,
             const struct ofpact_check_params *cp)
{
    return bundle_check(a, cp->max_ports, cp->match);
}


ofpacts_check_consistency(struct ofpact ofpacts[], size_t ofpacts_len,
                          enum ofputil_protocol needed_protocols,
                          struct ofpact_check_params *cp)
{
    enum ofperr error = ofpacts_check(ofpacts, ofpacts_len, cp);
    if (!error && needed_protocols & ~cp->usable_protocols) {
        return OFPERR_OFPBAC_MATCH_INCONSISTENT;
    }
    return error;
}


parse_REG_MOVE(const char *arg, const struct ofpact_parse_params *pp)
{
    struct ofpact_reg_move *move = ofpact_put_REG_MOVE(pp->ofpacts);
    return nxm_parse_reg_move(move, arg);
}


check_GOTO_TABLE(const struct ofpact_goto_table *a,
                 const struct ofpact_check_params *cp)
{
    if ((cp->table_id != 255 && a->table_id <= cp->table_id)
        || (cp->n_tables != 255 && a->table_id >= cp->n_tables)) {
        return OFPERR_OFPBIC_BAD_TABLE_ID;
    }
    return 0;
}


parse_ENQUEUE(char *arg, const struct ofpact_parse_params *pp)
{
    char *sp = NULL;
    char *port = strtok_r(arg, ":q,", &sp);
    char *queue = strtok_r(NULL, "", &sp);
    struct ofpact_enqueue *enqueue;

    if (port == NULL || queue == NULL) {
        return xstrdup("\"enqueue\" syntax is \"enqueue:PORT:QUEUE\" or "
                       "\"enqueue(PORT,QUEUE)\"");
    }

    enqueue = ofpact_put_ENQUEUE(pp->ofpacts);
    if (!ofputil_port_from_string(port, pp->port_map, &enqueue->port)) {
        return xasprintf("%s: enqueue to unknown port", port);
    }
    return str_to_u32(queue, &enqueue->queue);
}


format_EXIT(const struct ofpact_null *a OVS_UNUSED,
            const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sexit%s", colors.special, colors.end);
}


check_subactions(struct ofpact *ofpacts, size_t ofpacts_len,
                 struct ofpact_check_params *cp)
{
    struct ofpact_check_params sub = *cp;
    enum ofperr error = ofpacts_check(ofpacts, ofpacts_len, &sub);
    cp->usable_protocols &= sub.usable_protocols;
    return error;
}


format_STACK_PUSH(const struct ofpact_stack *a,
                  const struct ofpact_format_params *fp)
{
    nxm_format_stack_push(a, fp->s);
}


decode_NXAST_RAW_RESUBMIT_TABLE_CT(const struct nx_action_resubmit *nar,
                                   enum ofp_version ofp_version OVS_UNUSED,
                                   struct ofpbuf *out)
{
    enum ofperr error = decode_NXAST_RAW_RESUBMIT_TABLE(nar, ofp_version, out);
    if (error) {
        return error;
    }
    struct ofpact_resubmit *resubmit = out->header;
    resubmit->ofpact.raw = NXAST_RAW_RESUBMIT_TABLE_CT;
    resubmit->with_ct_orig = true;
    return 0;
}


decode_NXAST_RAW_DEC_TTL_CNT_IDS(const struct nx_action_cnt_ids *nac_ids,
                                 enum ofp_version ofp_version OVS_UNUSED,
                                 struct ofpbuf *out)
{
    struct ofpact_cnt_ids *ids;
    size_t ids_size;
    int i;

    ids = ofpact_put_DEC_TTL(out);
    ids->ofpact.raw = NXAST_RAW_DEC_TTL_CNT_IDS;
    ids->n_controllers = ntohs(nac_ids->n_controllers);
    ids_size = ntohs(nac_ids->len) - sizeof *nac_ids;

    if (!is_all_zeros(nac_ids->zeros, sizeof nac_ids->zeros)) {
        return OFPERR_NXBRC_MUST_BE_ZERO;
    }

    if (ids_size < ids->n_controllers * sizeof(ovs_be16)) {
        VLOG_WARN_RL(&rl, "Nicira action dec_ttl_cnt_ids only has %"PRIuSIZE" "
                     "bytes allocated for controller ids.  %"PRIuSIZE" bytes "
                     "are required for %u controllers.",
                     ids_size, ids->n_controllers * sizeof(ovs_be16),
                     ids->n_controllers);
        return OFPERR_OFPBAC_BAD_LEN;
    }

    for (i = 0; i < ids->n_controllers; i++) {
        uint16_t id = ntohs(((ovs_be16 *)(nac_ids + 1))[i]);
        ofpbuf_put(out, &id, sizeof id);
        ids = out->header;
    }

    ofpact_finish_DEC_TTL(out, &ids);

    return 0;
}


check_SET_MPLS_TTL(const struct ofpact_mpls_ttl *a OVS_UNUSED,
                   struct ofpact_check_params *cp)
{
    return check_set_mpls(cp);
}


encode_DEC_NSH_TTL(const struct ofpact_null *null OVS_UNUSED,
            enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
{
    put_NXAST_DEC_NSH_TTL(out);
}


check_DEC_MPLS_TTL(const struct ofpact_null *a OVS_UNUSED,
                   struct ofpact_check_params *cp)
{
    return check_set_mpls(cp);
}


check_UNROLL_XLATE(const struct ofpact_unroll_xlate *a OVS_UNUSED,
                   const struct ofpact_check_params *cp OVS_UNUSED)
{
    /* UNROLL is an internal action that should never be seen via OpenFlow. */
    return OFPERR_OFPBAC_BAD_TYPE;
}


check_CLONE(struct ofpact_nest *a, struct ofpact_check_params *cp)
{
    return check_subactions(a->actions, ofpact_nest_get_action_len(a), cp);
}


decode_NXAST_RAW_DECAP(const struct nx_action_decap *nad,
                       enum ofp_version ofp_version OVS_UNUSED,
                       struct ofpbuf *ofpacts)
{
    struct ofpact_decap * decap;

    if (ntohs(nad->len) > sizeof *nad) {
        /* No properties supported yet. */
        return OFPERR_NXBAC_UNKNOWN_ED_PROP;
    }

    decap = ofpact_put_DECAP(ofpacts);
    decap->ofpact.raw = NXAST_RAW_DECAP;
    decap->new_pkt_type = nad->new_pkt_type;
    return 0;
}


parse_SET_IP_DSCP(char *arg, const struct ofpact_parse_params *pp)

{
    uint8_t tos;
    char *error;

    error = str_to_u8(arg, "TOS", &tos);
    if (error) {
        return error;
    }

    if (tos & ~IP_DSCP_MASK) {
        return xasprintf("%s: not a valid TOS", arg);
    }
    ofpact_put_SET_IP_DSCP(pp->ofpacts)->dscp = tos;
    return NULL;
}


check_SET_L4_SRC_PORT(struct ofpact_l4_port *a, struct ofpact_check_params *cp)
{
    return check_set_l4_port(a, cp);
}


parse_SET_MPLS_LABEL(char *arg, const struct ofpact_parse_params *pp)
{
    struct ofpact_mpls_label *mpls_label
        = ofpact_put_SET_MPLS_LABEL(pp->ofpacts);
    if (*arg == '\0') {
        return xstrdup("set_mpls_label: expected label.");
    }

    mpls_label->label = htonl(atoi(arg));
    return NULL;
}


encode_PUSH_VLAN(const struct ofpact_push_vlan *push_vlan,
                 enum ofp_version ofp_version, struct ofpbuf *out)
{
    if (ofp_version == OFP10_VERSION) {
        /* PUSH is a side effect of a SET_VLAN_VID/PCP, which should
         * follow this action. */
    } else {
        put_OFPAT11_PUSH_VLAN(out, push_vlan->ethertype);
    }
}


format_SET_L4_SRC_PORT(const struct ofpact_l4_port *a,
                       const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%smod_tp_src:%s%d",
                  colors.param, colors.end, a->port);
}


parse_NOTE(const char *arg, const struct ofpact_parse_params *pp)
{
    size_t start_ofs = pp->ofpacts->size;
    ofpact_put_NOTE(pp->ofpacts);
    arg = ofpbuf_put_hex(pp->ofpacts, arg, NULL);
    if (arg[0]) {
        return xstrdup("bad hex digit in `note' argument");
    }
    struct ofpact_note *note = ofpbuf_at_assert(pp->ofpacts, start_ofs,
                                                sizeof *note);
    note->length = pp->ofpacts->size - (start_ofs + sizeof *note);
    ofpact_finish_NOTE(pp->ofpacts, &note);
    return NULL;
}


check_LEARN(const struct ofpact_learn *a,
            const struct ofpact_check_params *cp)
{
    return learn_check(a, cp->match);
}


parse_OUTPUT(const char *arg, const struct ofpact_parse_params *pp)
{
    if (strstr(arg, "port") && strstr(arg, "max_len")) {
        struct ofpact_output_trunc *output_trunc;

        output_trunc = ofpact_put_OUTPUT_TRUNC(pp->ofpacts);
        return parse_truncate_subfield(arg, pp, output_trunc);
    }

    ofp_port_t port;
    if (ofputil_port_from_string(arg, pp->port_map, &port)) {
        struct ofpact_output *output = ofpact_put_OUTPUT(pp->ofpacts);
        output->port = port;
        output->max_len = output->port == OFPP_CONTROLLER ? UINT16_MAX : 0;
        return NULL;
    }

    struct mf_subfield src;
    char *error = mf_parse_subfield(&src, arg);
    if (!error) {
        struct ofpact_output_reg *output_reg;

        output_reg = ofpact_put_OUTPUT_REG(pp->ofpacts);
        output_reg->max_len = UINT16_MAX;
        output_reg->src = src;
        return NULL;
    }
    free(error);

    return xasprintf("%s: output to unknown port", arg);
}


check_OUTPUT_REG(const struct ofpact_output_reg *a,
                 const struct ofpact_check_params *cp)
{
    return mf_check_src(&a->src, cp->match);
}


check_POP_QUEUE(const struct ofpact_null *a OVS_UNUSED,
                const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


check_POP_MPLS(const struct ofpact_pop_mpls *a, struct ofpact_check_params *cp)
{
    struct flow *flow = &cp->match->flow;
    ovs_be16 dl_type = get_dl_type(flow);

    if (flow->packet_type != htonl(PT_ETH) || !eth_type_mpls(dl_type)) {
        inconsistent_match(&cp->usable_protocols);
    }
    flow->dl_type = a->ethertype;
    return 0;
}


check_RESUBMIT(const struct ofpact_resubmit *a,
               const struct ofpact_check_params *cp)
{
    if (a->with_ct_orig && !is_ct_valid(&cp->match->flow, &cp->match->wc,
                                        NULL)) {
        return OFPERR_OFPBAC_MATCH_INCONSISTENT;
    }
    return 0;
}


parse_DEC_MPLS_TTL(char *arg OVS_UNUSED, const struct ofpact_parse_params *pp)
{
    ofpact_put_DEC_MPLS_TTL(pp->ofpacts);
    return NULL;
}


format_UNROLL_XLATE(const struct ofpact_unroll_xlate *a,
                    const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sunroll_xlate(%s%stable=%s",
                  colors.paren,   colors.end,
                  colors.special, colors.end);
    ofputil_format_table(a->rule_table_id, fp->table_map, fp->s);
    ds_put_format(fp->s, ", %scookie=%s%"PRIu64"%s)%s",
                  colors.param,   colors.end, ntohll(a->rule_cookie),
                  colors.paren,   colors.end);
}


check_STACK_POP(const struct ofpact_stack *a,
                const struct ofpact_check_params *cp)
{
    return nxm_stack_pop_check(a, cp->match);
}


parse_CLONE(char *arg, const struct ofpact_parse_params *pp)
{
    const size_t clone_offset = ofpacts_pull(pp->ofpacts);
    struct ofpact_nest *clone = ofpact_put_CLONE(pp->ofpacts);
    char *error;

    ofpbuf_pull(pp->ofpacts, sizeof *clone);
    error = ofpacts_parse_copy(arg, pp, false, 0);
    /* header points to the action list */
    pp->ofpacts->header = ofpbuf_push_uninit(pp->ofpacts, sizeof *clone);
    clone = pp->ofpacts->header;

    ofpact_finish_CLONE(pp->ofpacts, &clone);
    ofpbuf_push_uninit(pp->ofpacts, clone_offset);
    return error;
}


parse_METER(char *arg, const struct ofpact_parse_params *pp)
{
    *pp->usable_protocols &= OFPUTIL_P_OF13_UP;
    return str_to_u32(arg, &ofpact_put_METER(pp->ofpacts)->meter_id);
}


parse_WRITE_METADATA(char *arg, const struct ofpact_parse_params *pp)
{
    struct ofpact_metadata *om;
    char *mask = strchr(arg, '/');

    *pp->usable_protocols &= OFPUTIL_P_NXM_OF11_UP;

    om = ofpact_put_WRITE_METADATA(pp->ofpacts);
    if (mask) {
        char *error;

        *mask = '\0';
        error = str_to_be64(mask + 1, &om->mask);
        if (error) {
            return error;
        }
    } else {
        om->mask = OVS_BE64_MAX;
    }

    return str_to_be64(arg, &om->metadata);
}


format_ENQUEUE(const struct ofpact_enqueue *a,
               const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%senqueue:%s", colors.param, colors.end);
    ofputil_format_port(a->port, fp->port_map, fp->s);
    ds_put_format(fp->s, ":%"PRIu32, a->queue);
}


check_SAMPLE(const struct ofpact_sample *a OVS_UNUSED,
             const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


ofpacts_parse_instructions(const char *s, const struct ofpact_parse_params *pp)
{
    return ofpacts_parse_copy(s, pp, true, 0);
}


format_SET_IP_ECN(const struct ofpact_ecn *a,
                  const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%smod_nw_ecn:%s%d",
                  colors.param, colors.end, a->ecn);
}


format_MULTIPATH(const struct ofpact_multipath *a,
                 const struct ofpact_format_params *fp)
{
    multipath_format(a, fp->s);
}


ofpact_check__(struct ofpact *a, struct ofpact_check_params *cp)
{
    switch (a->type) {
#define OFPACT(ENUM, STRUCT, MEMBER, NAME)                  \
        case OFPACT_##ENUM:                                 \
            return check_##ENUM(ofpact_get_##ENUM(a), cp);
        OFPACTS
#undef OFPACT
    default:
        OVS_NOT_REACHED();
    }
}


format_SET_VLAN_PCP(const struct ofpact_vlan_pcp *a,
                    const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%s%s:%s%"PRIu8, colors.param,
                  a->push_vlan_if_needed ? "mod_vlan_pcp" : "set_vlan_pcp",
                  colors.end, a->vlan_pcp);
}


format_SET_FIELD(const struct ofpact_set_field *a,
                 const struct ofpact_format_params *fp)
{
    if (a->ofpact.raw == NXAST_RAW_REG_LOAD) {
        struct mf_subfield dst;
        uint64_t value;

        dst.ofs = dst.n_bits = 0;
        while (next_load_segment(a, &dst, &value)) {
            ds_put_format(fp->s, "%sload:%s%#"PRIx64"%s->%s",
                          colors.special, colors.end, value,
                          colors.special, colors.end);
            mf_format_subfield(&dst, fp->s);
            ds_put_char(fp->s, ',');
        }
        ds_chomp(fp->s, ',');
    } else {
        ds_put_format(fp->s, "%sset_field:%s", colors.special, colors.end);
        mf_format(a->field, a->value, ofpact_set_field_mask(a),
                  fp->port_map, fp->s);
        ds_put_format(fp->s, "%s->%s%s",
                      colors.special, colors.end, a->field->name);
    }
}


check_EXIT(const struct ofpact_null *a OVS_UNUSED,
           const struct ofpact_check_params *cp OVS_UNUSED)
{
    return 0;
}


check_set_l4_port(struct ofpact_l4_port *a, struct ofpact_check_params *cp)
{
    const struct flow *flow = &cp->match->flow;
    if (!is_ip_any(flow)
        || flow->nw_frag & FLOW_NW_FRAG_LATER
        || (flow->nw_proto != IPPROTO_TCP &&
            flow->nw_proto != IPPROTO_UDP &&
            flow->nw_proto != IPPROTO_SCTP)) {
        inconsistent_match(&cp->usable_protocols);
    }

    /* Note the transport protocol in use, to allow this action to be converted
     * to an OF1.2 set_field action later if necessary. */
    a->flow_ip_proto = flow->nw_proto;

    return 0;
}


parse_SET_IPV4_DST(char *arg, const struct ofpact_parse_params *pp)
{
    return str_to_ip(arg, &ofpact_put_SET_IPV4_DST(pp->ofpacts)->ipv4);
}


format_REG_MOVE(const struct ofpact_reg_move *a,
                const struct ofpact_format_params *fp)
{
    nxm_format_reg_move(a, fp->s);
}


check_set_ipv4(struct ofpact_check_params *cp)
{
    ovs_be16 dl_type = get_dl_type(&cp->match->flow);
    if (dl_type != htons(ETH_TYPE_IP)) {
        inconsistent_match(&cp->usable_protocols);
    }
    return 0;
}


check_ENCAP(const struct ofpact_encap *a, struct ofpact_check_params *cp)
{
    struct flow *flow = &cp->match->flow;
    flow->packet_type = a->new_pkt_type;
    if (pt_ns(flow->packet_type) == OFPHTN_ETHERTYPE) {
        flow->dl_type = htons(pt_ns_type(flow->packet_type));
    }
    if (!is_ip_any(flow)) {
        flow->nw_proto = 0;
    }
    return 0;
}


parse_DECAP(char *arg, const struct ofpact_parse_params *pp)
{
    struct ofpact_decap *decap;
    char *key, *value, *pos;
    char *error = NULL;
    uint16_t ns, type;

    decap = ofpact_put_DECAP(pp->ofpacts);
    /* Default next packet_type is PT_USE_NEXT_PROTO. */
    decap->new_pkt_type = htonl(PT_USE_NEXT_PROTO);

    /* Parse decap packet_type if given. */
    if (ofputil_parse_key_value(&arg, &key, &value)) {
        if (strcmp(key, "packet_type") == 0) {
            pos = value;
            if (!ofputil_parse_key_value(&pos, &key, &value)
                || strcmp(key, "ns") != 0) {
                return xstrdup("Missing packet_type attribute ns");
            }
            error = str_to_u16(value, "ns", &ns);
            if (error) {
                return error;
            }
            if (ns >= OFPHTN_N_TYPES) {
                return xasprintf("Unsupported ns value: %"PRIu16, ns);
            }
            if (!ofputil_parse_key_value(&pos, &key, &value)
                || strcmp(key, "type") != 0) {
                return xstrdup("Missing packet_type attribute type");
            }
            error = str_to_u16(value, "type", &type);
            if (error) {
                return error;
            }
            decap->new_pkt_type = htonl(PACKET_TYPE(ns, type));
        } else {
            return xasprintf("Invalid decap argument: %s", key);
        }
    }
    return NULL;
}


format_OUTPUT(const struct ofpact_output *a,
              const struct ofpact_format_params *fp)
{
    if (ofp_to_u16(a->port) < ofp_to_u16(OFPP_MAX)) {
        ds_put_format(fp->s, "%soutput:%s", colors.special, colors.end);
    }
    ofputil_format_port(a->port, fp->port_map, fp->s);
    if (a->port == OFPP_CONTROLLER) {
        ds_put_format(fp->s, ":%"PRIu16, a->max_len);
    }
}


parse_DEBUG_SLOW(char *arg OVS_UNUSED, const struct ofpact_parse_params *pp)
{
    ofpact_put_DEBUG_SLOW(pp->ofpacts);
    return NULL;
}


ovs_instruction_type_from_ofpact_type(enum ofpact_type type)
{
    switch (type) {
    case OFPACT_METER:
        return OVSINST_OFPIT13_METER;
    case OFPACT_CLEAR_ACTIONS:
        return OVSINST_OFPIT11_CLEAR_ACTIONS;
    case OFPACT_WRITE_ACTIONS:
        return OVSINST_OFPIT11_WRITE_ACTIONS;
    case OFPACT_WRITE_METADATA:
        return OVSINST_OFPIT11_WRITE_METADATA;
    case OFPACT_GOTO_TABLE:
        return OVSINST_OFPIT11_GOTO_TABLE;
    case OFPACT_OUTPUT:
    case OFPACT_GROUP:
    case OFPACT_CLONE:
    case OFPACT_CONTROLLER:
    case OFPACT_ENQUEUE:
    case OFPACT_OUTPUT_REG:
    case OFPACT_OUTPUT_TRUNC:
    case OFPACT_BUNDLE:
    case OFPACT_SET_VLAN_VID:
    case OFPACT_SET_VLAN_PCP:
    case OFPACT_STRIP_VLAN:
    case OFPACT_PUSH_VLAN:
    case OFPACT_SET_ETH_SRC:
    case OFPACT_SET_ETH_DST:
    case OFPACT_SET_IPV4_SRC:
    case OFPACT_SET_IPV4_DST:
    case OFPACT_SET_IP_DSCP:
    case OFPACT_SET_IP_ECN:
    case OFPACT_SET_IP_TTL:
    case OFPACT_SET_L4_SRC_PORT:
    case OFPACT_SET_L4_DST_PORT:
    case OFPACT_REG_MOVE:
    case OFPACT_SET_FIELD:
    case OFPACT_STACK_PUSH:
    case OFPACT_STACK_POP:
    case OFPACT_DEC_TTL:
    case OFPACT_SET_MPLS_LABEL:
    case OFPACT_SET_MPLS_TC:
    case OFPACT_SET_MPLS_TTL:
    case OFPACT_DEC_MPLS_TTL:
    case OFPACT_PUSH_MPLS:
    case OFPACT_POP_MPLS:
    case OFPACT_SET_TUNNEL:
    case OFPACT_SET_QUEUE:
    case OFPACT_POP_QUEUE:
    case OFPACT_FIN_TIMEOUT:
    case OFPACT_RESUBMIT:
    case OFPACT_LEARN:
    case OFPACT_CONJUNCTION:
    case OFPACT_MULTIPATH:
    case OFPACT_NOTE:
    case OFPACT_EXIT:
    case OFPACT_UNROLL_XLATE:
    case OFPACT_SAMPLE:
    case OFPACT_DEBUG_RECIRC:
    case OFPACT_DEBUG_SLOW:
    case OFPACT_CT:
    case OFPACT_CT_CLEAR:
    case OFPACT_NAT:
    case OFPACT_ENCAP:
    case OFPACT_DECAP:
    case OFPACT_DEC_NSH_TTL:
    default:
        return OVSINST_OFPIT11_APPLY_ACTIONS;
    }
}


parse_OUTPUT_REG(const char *arg, const struct ofpact_parse_params *pp)
{
    return parse_OUTPUT(arg, pp);
}


decode_bundle(bool load, const struct nx_action_bundle *nab,
              const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap,
              struct ofpbuf *ofpacts)
{
    static struct vlog_rate_limit rll = VLOG_RATE_LIMIT_INIT(1, 5);
    struct ofpact_bundle *bundle;
    uint32_t slave_type;
    size_t slaves_size, i;
    enum ofperr error;

    bundle = ofpact_put_BUNDLE(ofpacts);

    bundle->n_slaves = ntohs(nab->n_slaves);
    bundle->basis = ntohs(nab->basis);
    bundle->fields = ntohs(nab->fields);
    bundle->algorithm = ntohs(nab->algorithm);
    slave_type = ntohl(nab->slave_type);
    slaves_size = ntohs(nab->len) - sizeof *nab;

    error = OFPERR_OFPBAC_BAD_ARGUMENT;
    if (!flow_hash_fields_valid(bundle->fields)) {
        VLOG_WARN_RL(&rll, "unsupported fields %d", (int) bundle->fields);
    } else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) {
        VLOG_WARN_RL(&rll, "too many slaves");
    } else if (bundle->algorithm != NX_BD_ALG_HRW
               && bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) {
        VLOG_WARN_RL(&rll, "unsupported algorithm %d", (int) bundle->algorithm);
    } else if (slave_type != mf_nxm_header(MFF_IN_PORT)) {
        VLOG_WARN_RL(&rll, "unsupported slave type %"PRIu32, slave_type);
    } else {
        error = 0;
    }

    if (!is_all_zeros(nab->zero, sizeof nab->zero)) {
        VLOG_WARN_RL(&rll, "reserved field is nonzero");
        error = OFPERR_OFPBAC_BAD_ARGUMENT;
    }

    if (load) {
        bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits);
        bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits);
        error = mf_vl_mff_mf_from_nxm_header(ntohl(nab->dst), vl_mff_map,
                                             &bundle->dst.field, tlv_bitmap);
        if (error) {
            return error;
        }

        if (bundle->dst.n_bits < 16) {
            VLOG_WARN_RL(&rll, "bundle_load action requires at least 16 bit "
                         "destination.");
            error = OFPERR_OFPBAC_BAD_ARGUMENT;
        }
    } else {
        if (nab->ofs_nbits || nab->dst) {
            VLOG_WARN_RL(&rll, "bundle action has nonzero reserved fields");
            error = OFPERR_OFPBAC_BAD_ARGUMENT;
        }
    }

    if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) {
        VLOG_WARN_RL(&rll, "Nicira action %s only has %"PRIuSIZE" bytes "
                     "allocated for slaves.  %"PRIuSIZE" bytes are required "
                     "for %u slaves.",
                     load ? "bundle_load" : "bundle", slaves_size,
                     bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves);
        error = OFPERR_OFPBAC_BAD_LEN;
    } else {
        for (i = 0; i < bundle->n_slaves; i++) {
            ofp_port_t ofp_port
                = u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));
            ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);
            bundle = ofpacts->header;
        }
    }

    ofpact_finish_BUNDLE(ofpacts, &bundle);
    if (!error) {
        error = bundle_check(bundle, OFPP_MAX, NULL);
    }
    return error;
}


parse_SET_VLAN_VID(char *arg, const struct ofpact_parse_params *pp)
{
    return parse_set_vlan_vid(arg, false, pp);
}


learn_min_len(uint16_t header)
{
    int n_bits = header & NX_LEARN_N_BITS_MASK;
    int src_type = header & NX_LEARN_SRC_MASK;
    int dst_type = header & NX_LEARN_DST_MASK;
    unsigned int min_len;

    min_len = 0;
    if (src_type == NX_LEARN_SRC_FIELD) {
        min_len += sizeof(ovs_be32); /* src_field */
        min_len += sizeof(ovs_be16); /* src_ofs */
    } else {
        min_len += 2 * DIV_ROUND_UP(n_bits, 16);
    }
    if (dst_type == NX_LEARN_DST_MATCH ||
        dst_type == NX_LEARN_DST_LOAD) {
        min_len += sizeof(ovs_be32); /* dst_field */
        min_len += sizeof(ovs_be16); /* dst_ofs */
    }
    return min_len;
}


ofpacts_parse__(char *str, const struct ofpact_parse_params *pp,
                bool allow_instructions, enum ofpact_type outer_action)
{
    int prev_inst = -1;
    enum ofperr retval;
    char *key, *value;
    bool drop = false;
    char *pos;

    pos = str;
    while (ofputil_parse_key_value(&pos, &key, &value)) {
        enum ovs_instruction_type inst = OVSINST_OFPIT11_APPLY_ACTIONS;
        enum ofpact_type type;
        char *error = NULL;
        ofp_port_t port;

        if (ofpact_type_from_name(key, &type)) {
            error = ofpact_parse(type, value, pp);
            inst = ovs_instruction_type_from_ofpact_type(type);
        } else if (!strcasecmp(key, "mod_vlan_vid")) {
            error = parse_set_vlan_vid(value, true, pp);
        } else if (!strcasecmp(key, "mod_vlan_pcp")) {
            error = parse_set_vlan_pcp(value, true, pp);
        } else if (!strcasecmp(key, "set_nw_ttl")) {
            error = parse_SET_IP_TTL(value, pp);
        } else if (!strcasecmp(key, "pop_vlan")) {
            error = parse_pop_vlan(pp);
        } else if (!strcasecmp(key, "set_tunnel64")) {
            error = parse_set_tunnel(value, NXAST_RAW_SET_TUNNEL64, pp);
        } else if (!strcasecmp(key, "load")) {
            error = parse_reg_load(value, pp);
        } else if (!strcasecmp(key, "bundle_load")) {
            error = parse_bundle_load(value, pp);
        } else if (!strcasecmp(key, "drop")) {
            drop = true;
        } else if (!strcasecmp(key, "apply_actions")) {
            return xstrdup("apply_actions is the default instruction");
        } else if (ofputil_port_from_string(key, pp->port_map, &port)) {
            ofpact_put_OUTPUT(pp->ofpacts)->port = port;
        } else {
            return xasprintf("unknown action %s", key);
        }
        if (error) {
            return error;
        }

        if (inst != OVSINST_OFPIT11_APPLY_ACTIONS) {
            if (!allow_instructions) {
                return xasprintf("only actions are allowed here (not "
                                 "instruction %s)",
                                 ovs_instruction_name_from_type(inst));
            }
            if (inst == prev_inst) {
                return xasprintf("instruction %s may be specified only once",
                                 ovs_instruction_name_from_type(inst));
            }
        }
        if (prev_inst != -1 && inst < prev_inst) {
            return xasprintf("instruction %s must be specified before %s",
                             ovs_instruction_name_from_type(inst),
                             ovs_instruction_name_from_type(prev_inst));
        }
        prev_inst = inst;
    }

    if (drop && pp->ofpacts->size) {
        return xstrdup("\"drop\" must not be accompanied by any other action "
                       "or instruction");
    }

    retval = ofpacts_verify(pp->ofpacts->data, pp->ofpacts->size,
                            (allow_instructions
                             ? (1u << N_OVS_INSTRUCTIONS) - 1
                             : 1u << OVSINST_OFPIT11_APPLY_ACTIONS),
                            outer_action);
    if (retval) {
        return xstrdup("Incorrect instruction ordering");
    }

    return NULL;
}


parse_FIN_TIMEOUT(char *arg, const struct ofpact_parse_params *pp)
{
    struct ofpact_fin_timeout *oft = ofpact_put_FIN_TIMEOUT(pp->ofpacts);
    char *key, *value;

    while (ofputil_parse_key_value(&arg, &key, &value)) {
        char *error;

        if (!strcmp(key, "idle_timeout")) {
            error =  str_to_u16(value, key, &oft->fin_idle_timeout);
        } else if (!strcmp(key, "hard_timeout")) {
            error = str_to_u16(value, key, &oft->fin_hard_timeout);
        } else {
            error = xasprintf("invalid key '%s' in 'fin_timeout' argument",
                              key);
        }

        if (error) {
            return error;
        }
    }
    return NULL;
}


parse_DEC_TTL(char *arg, const struct ofpact_parse_params *pp)
{
    if (*arg == '\0') {
        parse_noargs_dec_ttl(pp);
    } else {
        struct ofpact_cnt_ids *ids;
        char *cntr;

        ids = ofpact_put_DEC_TTL(pp->ofpacts);
        ids->ofpact.raw = NXAST_RAW_DEC_TTL_CNT_IDS;
        for (cntr = strtok_r(arg, ", ", &arg); cntr != NULL;
             cntr = strtok_r(NULL, ", ", &arg)) {
            uint16_t id = atoi(cntr);

            ofpbuf_put(pp->ofpacts, &id, sizeof id);
            ids = pp->ofpacts->header;
            ids->n_controllers++;
        }
        if (!ids->n_controllers) {
            return xstrdup("dec_ttl_cnt_ids: expected at least one controller "
                           "id.");
        }
        ofpact_finish_DEC_TTL(pp->ofpacts, &ids);
    }
    return NULL;
}


check_METER(const struct ofpact_meter *a,
            const struct ofpact_check_params *cp OVS_UNUSED)
{
    uint32_t mid = a->meter_id;
    return mid == 0 || mid > OFPM13_MAX ? OFPERR_OFPMMFC_INVALID_METER : 0;
}


encode_CONTROLLER(const struct ofpact_controller *controller,
                  enum ofp_version ofp_version OVS_UNUSED,
                  struct ofpbuf *out)
{
    if (controller->userdata_len
        || controller->pause
        || controller->meter_id != NX_CTLR_NO_METER
        || controller->ofpact.raw == NXAST_RAW_CONTROLLER2) {
        size_t start_ofs = out->size;
        put_NXAST_CONTROLLER2(out);
        if (controller->max_len != UINT16_MAX) {
            ofpprop_put_u16(out, NXAC2PT_MAX_LEN, controller->max_len);
        }
        if (controller->controller_id != 0) {
            ofpprop_put_u16(out, NXAC2PT_CONTROLLER_ID,
                            controller->controller_id);
        }
        if (controller->reason != OFPR_ACTION) {
            ofpprop_put_u8(out, NXAC2PT_REASON, controller->reason);
        }
        if (controller->userdata_len != 0) {
            ofpprop_put(out, NXAC2PT_USERDATA, controller->userdata,
                        controller->userdata_len);
        }
        if (controller->pause) {
            ofpprop_put_flag(out, NXAC2PT_PAUSE);
        }
        if (controller->meter_id != NX_CTLR_NO_METER) {
            ofpprop_put_u32(out, NXAC2PT_METER_ID, controller->meter_id);
        }
        pad_ofpat(out, start_ofs);
    } else {
        struct nx_action_controller *nac;

        nac = put_NXAST_CONTROLLER(out);
        nac->max_len = htons(controller->max_len);
        nac->controller_id = htons(controller->controller_id);
        nac->reason = controller->reason;
    }
}


format_DEBUG_SLOW(const struct ofpact_null *a OVS_UNUSED,
                  const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sdebug_slow%s", colors.value, colors.end);
}


format_SET_ETH_DST(const struct ofpact_mac *a,
                   const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%smod_dl_dst:%s"ETH_ADDR_FMT,
                  colors.param, colors.end, ETH_ADDR_ARGS(a->mac));
}


parse_SET_QUEUE(char *arg, const struct ofpact_parse_params *pp)
{
    return str_to_u32(arg, &ofpact_put_SET_QUEUE(pp->ofpacts)->queue_id);
}


parse_set_vlan_vid(char *arg, bool push_vlan_if_needed,
                   const struct ofpact_parse_params *pp)
{
    struct ofpact_vlan_vid *vlan_vid;
    uint16_t vid;
    char *error;

    error = str_to_u16(arg, "VLAN VID", &vid);
    if (error) {
        return error;
    }

    if (vid & ~VLAN_VID_MASK) {
        return xasprintf("%s: not a valid VLAN VID", arg);
    }
    vlan_vid = ofpact_put_SET_VLAN_VID(pp->ofpacts);
    vlan_vid->vlan_vid = vid;
    vlan_vid->push_vlan_if_needed = push_vlan_if_needed;
    return NULL;
}


encode_SET_ETH_SRC(const struct ofpact_mac *mac, enum ofp_version ofp_version,
                   struct ofpbuf *out)
{
    encode_SET_ETH_addr(mac, ofp_version, OFPAT_RAW_SET_DL_SRC, MFF_ETH_SRC,
                        out);

}


format_STRIP_VLAN(const struct ofpact_null *a,
                  const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, (a->ofpact.raw == OFPAT_RAW11_POP_VLAN
                    ? "%spop_vlan%s"
                    : "%sstrip_vlan%s"),
                  colors.value, colors.end);
}


encode_DECAP(const struct ofpact_decap *decap,
                enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out)
{
    struct nx_action_decap *nad = put_NXAST_DECAP(out);

    nad->len = htons(sizeof(struct nx_action_decap));
    nad->new_pkt_type = decap->new_pkt_type;
}


check_OUTPUT_TRUNC(const struct ofpact_output_trunc *a,
                   const struct ofpact_check_params *cp)
{
    return ofpact_check_output_port(a->port, cp->max_ports);
}


parse_POP_QUEUE(const char *arg OVS_UNUSED,
                const struct ofpact_parse_params *pp)
{
    ofpact_put_POP_QUEUE(pp->ofpacts);
    return NULL;
}


check_CT(struct ofpact_conntrack *a, struct ofpact_check_params *cp)
{
    struct flow *flow = &cp->match->flow;

    if (!dl_type_is_ip_any(get_dl_type(flow))
        || (flow->ct_state & CS_INVALID && a->flags & NX_CT_F_COMMIT)
        || (a->alg == IPPORT_FTP && flow->nw_proto != IPPROTO_TCP)
        || (a->alg == IPPORT_TFTP && flow->nw_proto != IPPROTO_UDP)) {
        /* We can't downgrade to OF1.0 and expect inconsistent CT actions
         * be silently discarded.  Instead, datapath flow install fails, so
         * it is better to flag inconsistent CT actions as hard errors. */
        return OFPERR_OFPBAC_MATCH_INCONSISTENT;
    }

    if (a->zone_src.field) {
        return mf_check_src(&a->zone_src, cp->match);
    }

    return check_subactions(a->actions, ofpact_ct_get_action_len(a), cp);
}


check_SET_FIELD(struct ofpact_set_field *a,
                const struct ofpact_check_params *cp)
{
    const struct mf_field *mf = a->field;
    struct flow *flow = &cp->match->flow;
    ovs_be16 *tci = &flow->vlans[0].tci;

    /* Require OXM_OF_VLAN_VID to have an existing VLAN header. */
    if (!mf_are_prereqs_ok(mf, flow, NULL)
        || (mf->id == MFF_VLAN_VID && !(*tci & htons(VLAN_CFI)))) {
        VLOG_WARN_RL(&rl, "set_field %s lacks correct prerequisites",
                     mf->name);
        return OFPERR_OFPBAC_MATCH_INCONSISTENT;
    }

    /* Remember if we saw a VLAN tag in the flow, to aid translating to
     * OpenFlow 1.1 if need be. */
    a->flow_has_vlan = (*tci & htons(VLAN_CFI)) != 0;
    if (mf->id == MFF_VLAN_TCI) {
        /* The set field may add or remove the VLAN tag,
         * Mark the status temporarily. */
        *tci = a->value->be16;
    }

    return 0;
}


format_NAT(const struct ofpact_nat *a, const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%snat%s", colors.paren, colors.end);

    if (a->flags & (NX_NAT_F_SRC | NX_NAT_F_DST)) {
        ds_put_format(fp->s, "%s(%s", colors.paren, colors.end);
        ds_put_format(fp->s, a->flags & NX_NAT_F_SRC ? "%ssrc%s" : "%sdst%s",
                      colors.param, colors.end);

        if (a->range_af != AF_UNSPEC) {
            ds_put_format(fp->s, "%s=%s", colors.param, colors.end);

            if (a->range_af == AF_INET) {
                ds_put_format(fp->s, IP_FMT, IP_ARGS(a->range.addr.ipv4.min));

                if (a->range.addr.ipv4.max
                    && a->range.addr.ipv4.max != a->range.addr.ipv4.min) {
                    ds_put_format(fp->s, "-"IP_FMT,
                                  IP_ARGS(a->range.addr.ipv4.max));
                }
            } else if (a->range_af == AF_INET6) {
                ipv6_format_addr_bracket(&a->range.addr.ipv6.min, fp->s,
                                        a->range.proto.min);

                if (!ipv6_mask_is_any(&a->range.addr.ipv6.max)
                    && memcmp(&a->range.addr.ipv6.max, &a->range.addr.ipv6.min,
                              sizeof(struct in6_addr)) != 0) {
                    ds_put_char(fp->s, '-');
                    ipv6_format_addr_bracket(&a->range.addr.ipv6.max, fp->s,
                                            a->range.proto.min);
                }
            }
            if (a->range.proto.min) {
                ds_put_char(fp->s, ':');
                ds_put_format(fp->s, "%"PRIu16, a->range.proto.min);

                if (a->range.proto.max
                    && a->range.proto.max != a->range.proto.min) {
                    ds_put_format(fp->s, "-%"PRIu16, a->range.proto.max);
                }
            }
            ds_put_char(fp->s, ',');

            if (a->flags & NX_NAT_F_PERSISTENT) {
                ds_put_format(fp->s, "%spersistent%s,",
                              colors.value, colors.end);
            }
            if (a->flags & NX_NAT_F_PROTO_HASH) {
                ds_put_format(fp->s, "%shash%s,", colors.value, colors.end);
            }
            if (a->flags & NX_NAT_F_PROTO_RANDOM) {
                ds_put_format(fp->s, "%srandom%s,", colors.value, colors.end);
            }
        }
        ds_chomp(fp->s, ',');
        ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
    }
}


ofpact_copy(struct ofpbuf *out, const struct ofpact *a)
{
    ofpbuf_put(out, a, OFPACT_ALIGN(a->len));
}


parse_MULTIPATH(const char *arg, const struct ofpact_parse_params *pp)
{
    return multipath_parse(ofpact_put_MULTIPATH(pp->ofpacts), arg);
}


format_SAMPLE(const struct ofpact_sample *a,
              const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%ssample(%s%sprobability=%s%"PRIu16
                  ",%scollector_set_id=%s%"PRIu32
                  ",%sobs_domain_id=%s%"PRIu32
                  ",%sobs_point_id=%s%"PRIu32,
                  colors.paren, colors.end,
                  colors.param, colors.end, a->probability,
                  colors.param, colors.end, a->collector_set_id,
                  colors.param, colors.end, a->obs_domain_id,
                  colors.param, colors.end, a->obs_point_id);
    if (a->sampling_port != OFPP_NONE) {
        ds_put_format(fp->s, ",%ssampling_port=%s", colors.param, colors.end);
        ofputil_format_port(a->sampling_port, fp->port_map, fp->s);
    }
    if (a->direction == NX_ACTION_SAMPLE_INGRESS) {
        ds_put_format(fp->s, ",%singress%s", colors.param, colors.end);
    } else if (a->direction == NX_ACTION_SAMPLE_EGRESS) {
        ds_put_format(fp->s, ",%segress%s", colors.param, colors.end);
    }
    ds_put_format(fp->s, "%s)%s", colors.paren, colors.end);
}


decode_NXAST_RAW_ENCAP(const struct nx_action_encap *nae,
                       enum ofp_version ofp_version OVS_UNUSED,
                       struct ofpbuf *out)
{
    struct ofpact_encap *encap;
    const struct ofp_ed_prop_header *ofp_prop;
    const size_t encap_ofs = out->size;
    size_t props_len;
    uint16_t n_props = 0;
    int err;

    encap = ofpact_put_ENCAP(out);
    encap->ofpact.raw = NXAST_RAW_ENCAP;
    switch (ntohl(nae->new_pkt_type)) {
    case PT_ETH:
    case PT_NSH:
        /* Add supported encap header types here. */
        break;
    default:
        return OFPERR_NXBAC_BAD_HEADER_TYPE;
    }
    encap->new_pkt_type = nae->new_pkt_type;
    encap->hdr_size = ntohs(nae->hdr_size);

    ofp_prop = nae->props;
    props_len = ntohs(nae->len) - offsetof(struct nx_action_encap, props);
    n_props = 0;
    while (props_len > 0) {
        err = decode_ed_prop(&ofp_prop, out, &props_len);
        if (err) {
            return err;
        }
        n_props++;
    }
    encap = ofpbuf_at_assert(out, encap_ofs, sizeof *encap);
    encap->n_props = n_props;
    out->header = &encap->ofpact;
    ofpact_finish_ENCAP(out, &encap);

    return 0;
}


format_ed_props(struct ds *s, uint16_t n_props,
                const struct ofpact_ed_prop *prop)
{
    const uint8_t *p = (uint8_t *) prop;
    int i;

    if (n_props == 0) {
        return;
    }
    for (i = 0; i < n_props; i++) {
        format_ed_prop(s, prop);
        ds_put_char(s, ',');
        p += ROUND_UP(prop->len, 8);
        prop = ALIGNED_CAST(const struct ofpact_ed_prop *, p);
    }
    if (n_props > 0) {
        ds_chomp(s, ',');
    }
}


ofpact_hdrs_hash(const struct ofpact_hdrs *hdrs)
{
    return hash_2words(hdrs->vendor,
                       ((uint32_t) hdrs->type << 16) | hdrs->ofp_version);
}


check_DECAP(const struct ofpact_decap *a OVS_UNUSED,
            struct ofpact_check_params *cp)
{
    struct flow *flow = &cp->match->flow;
    if (flow->packet_type == htonl(PT_ETH)) {
        /* Adjust the packet_type to allow subsequent actions. */
        flow->packet_type = PACKET_TYPE_BE(OFPHTN_ETHERTYPE,
                                           ntohs(flow->dl_type));
    } else {
        /* The actual packet_type is only known after decapsulation.
         * Do not allow subsequent actions that depend on packet headers. */
        flow->packet_type = htonl(PT_UNKNOWN);
        flow->dl_type = OVS_BE16_MAX;
    }
    return 0;
}


format_GOTO_TABLE(const struct ofpact_goto_table *a,
                  const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%sgoto_table:%s", colors.param, colors.end);
    ofputil_format_table(a->table_id, fp->table_map, fp->s);
}