/* SPDX-License-Identifier: GPL-2.0 */
#include <linux/kernel.h>
#include <linux/slab.h>
#include <net/flow_offload.h>
#include <net/pkt_cls.h>

#define FLOW_DISSECTOR_MATCH(__rule, __type, __out)				\
	const struct flow_match *__m = &(__rule)->match;			\
	struct flow_dissector *__d = (__m)->dissector;				\
										\
	(__out)->key = skb_flow_dissector_target(__d, __type, (__m)->key);	\
	(__out)->mask = skb_flow_dissector_target(__d, __type, (__m)->mask);	\


#ifndef HAVE_TC_SETUP_FLOW_ACTION
static void build_rule_match(struct tc_cls_flower_offload *f,
			     struct flow_match *match)
{
	match->dissector = f->dissector;
	match->mask = f->mask;
	match->key = f->key;
}

static int build_rule_action(struct tcf_exts *exts,
			     struct flow_rule *rule)
{
	return tc_setup_flow_action(&rule->action, exts);
}

struct flow_rule *__alloc_flow_rule(struct tcf_exts *exts,
				    void *priv, int size)
{
	struct flow_rule *rule;
	int num_ent;
	void *ret;
	int err;

	if (!exts) {
		pr_err_once("mlx5_core: %s: no exts\n", __func__);
		return ERR_PTR(-EINVAL);
	}

	num_ent = tcf_exts_num_actions(exts);
	ret = kzalloc(size + sizeof(*rule) +
		      num_ent * sizeof(rule->action.entries[0]),
		      GFP_KERNEL);
	if (!ret)
		return ERR_PTR(-ENOMEM);

	rule = (struct flow_rule *)((uintptr_t)ret + size);
	rule->action.num_entries = num_ent;
	err = build_rule_action(exts, rule);
	if (err)
		goto out;

	if (priv)
		memcpy(ret, priv, size);
	rule->buff = ret;
	rule->priv = priv;
	rule->priv_size = size;

	return rule;

out:
	kfree(ret);
	return ERR_PTR(err);
}
EXPORT_SYMBOL(__alloc_flow_rule);

struct flow_rule *alloc_flow_rule(struct tc_cls_flower_offload **f)
{
	struct flow_rule *rule;

	rule = __alloc_flow_rule((*f)->exts, *f, sizeof(**f));
	if (IS_ERR(rule))
		return rule;

	build_rule_match(*f, &rule->match);

	*f = (struct tc_cls_flower_offload *)rule->buff;

	return rule;
}
EXPORT_SYMBOL(alloc_flow_rule);

void free_flow_rule(struct flow_rule *rule)
{
	if (rule->priv)
		memcpy(rule->priv, rule->buff, rule->priv_size);

	kfree(rule->buff);
}
EXPORT_SYMBOL(free_flow_rule);
#endif /* HAVE_TC_SETUP_FLOW_ACTION */
