xref: /openbmc/linux/net/sched/act_ct.c (revision 545094d9)
1 // SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB
2 /* -
3  * net/sched/act_ct.c  Connection Tracking action
4  *
5  * Authors:   Paul Blakey <paulb@mellanox.com>
6  *            Yossi Kuperman <yossiku@mellanox.com>
7  *            Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>
8  */
9 
10 #include <linux/module.h>
11 #include <linux/init.h>
12 #include <linux/kernel.h>
13 #include <linux/skbuff.h>
14 #include <linux/rtnetlink.h>
15 #include <linux/pkt_cls.h>
16 #include <linux/ip.h>
17 #include <linux/ipv6.h>
18 #include <linux/rhashtable.h>
19 #include <net/netlink.h>
20 #include <net/pkt_sched.h>
21 #include <net/pkt_cls.h>
22 #include <net/act_api.h>
23 #include <net/ip.h>
24 #include <net/ipv6_frag.h>
25 #include <uapi/linux/tc_act/tc_ct.h>
26 #include <net/tc_act/tc_ct.h>
27 
28 #include <net/netfilter/nf_flow_table.h>
29 #include <net/netfilter/nf_conntrack.h>
30 #include <net/netfilter/nf_conntrack_core.h>
31 #include <net/netfilter/nf_conntrack_zones.h>
32 #include <net/netfilter/nf_conntrack_helper.h>
33 #include <net/netfilter/nf_conntrack_acct.h>
34 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
35 #include <net/netfilter/nf_conntrack_act_ct.h>
36 #include <uapi/linux/netfilter/nf_nat.h>
37 
38 static struct workqueue_struct *act_ct_wq;
39 static struct rhashtable zones_ht;
40 static DEFINE_MUTEX(zones_mutex);
41 
42 struct tcf_ct_flow_table {
43 	struct rhash_head node; /* In zones tables */
44 
45 	struct rcu_work rwork;
46 	struct nf_flowtable nf_ft;
47 	refcount_t ref;
48 	u16 zone;
49 
50 	bool dying;
51 };
52 
53 static const struct rhashtable_params zones_params = {
54 	.head_offset = offsetof(struct tcf_ct_flow_table, node),
55 	.key_offset = offsetof(struct tcf_ct_flow_table, zone),
56 	.key_len = sizeof_field(struct tcf_ct_flow_table, zone),
57 	.automatic_shrinking = true,
58 };
59 
60 static struct flow_action_entry *
61 tcf_ct_flow_table_flow_action_get_next(struct flow_action *flow_action)
62 {
63 	int i = flow_action->num_entries++;
64 
65 	return &flow_action->entries[i];
66 }
67 
68 static void tcf_ct_add_mangle_action(struct flow_action *action,
69 				     enum flow_action_mangle_base htype,
70 				     u32 offset,
71 				     u32 mask,
72 				     u32 val)
73 {
74 	struct flow_action_entry *entry;
75 
76 	entry = tcf_ct_flow_table_flow_action_get_next(action);
77 	entry->id = FLOW_ACTION_MANGLE;
78 	entry->mangle.htype = htype;
79 	entry->mangle.mask = ~mask;
80 	entry->mangle.offset = offset;
81 	entry->mangle.val = val;
82 }
83 
84 /* The following nat helper functions check if the inverted reverse tuple
85  * (target) is different then the current dir tuple - meaning nat for ports
86  * and/or ip is needed, and add the relevant mangle actions.
87  */
88 static void
89 tcf_ct_flow_table_add_action_nat_ipv4(const struct nf_conntrack_tuple *tuple,
90 				      struct nf_conntrack_tuple target,
91 				      struct flow_action *action)
92 {
93 	if (memcmp(&target.src.u3, &tuple->src.u3, sizeof(target.src.u3)))
94 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_IP4,
95 					 offsetof(struct iphdr, saddr),
96 					 0xFFFFFFFF,
97 					 be32_to_cpu(target.src.u3.ip));
98 	if (memcmp(&target.dst.u3, &tuple->dst.u3, sizeof(target.dst.u3)))
99 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_IP4,
100 					 offsetof(struct iphdr, daddr),
101 					 0xFFFFFFFF,
102 					 be32_to_cpu(target.dst.u3.ip));
103 }
104 
105 static void
106 tcf_ct_add_ipv6_addr_mangle_action(struct flow_action *action,
107 				   union nf_inet_addr *addr,
108 				   u32 offset)
109 {
110 	int i;
111 
112 	for (i = 0; i < sizeof(struct in6_addr) / sizeof(u32); i++)
113 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_IP6,
114 					 i * sizeof(u32) + offset,
115 					 0xFFFFFFFF, be32_to_cpu(addr->ip6[i]));
116 }
117 
118 static void
119 tcf_ct_flow_table_add_action_nat_ipv6(const struct nf_conntrack_tuple *tuple,
120 				      struct nf_conntrack_tuple target,
121 				      struct flow_action *action)
122 {
123 	if (memcmp(&target.src.u3, &tuple->src.u3, sizeof(target.src.u3)))
124 		tcf_ct_add_ipv6_addr_mangle_action(action, &target.src.u3,
125 						   offsetof(struct ipv6hdr,
126 							    saddr));
127 	if (memcmp(&target.dst.u3, &tuple->dst.u3, sizeof(target.dst.u3)))
128 		tcf_ct_add_ipv6_addr_mangle_action(action, &target.dst.u3,
129 						   offsetof(struct ipv6hdr,
130 							    daddr));
131 }
132 
133 static void
134 tcf_ct_flow_table_add_action_nat_tcp(const struct nf_conntrack_tuple *tuple,
135 				     struct nf_conntrack_tuple target,
136 				     struct flow_action *action)
137 {
138 	__be16 target_src = target.src.u.tcp.port;
139 	__be16 target_dst = target.dst.u.tcp.port;
140 
141 	if (target_src != tuple->src.u.tcp.port)
142 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_TCP,
143 					 offsetof(struct tcphdr, source),
144 					 0xFFFF, be16_to_cpu(target_src));
145 	if (target_dst != tuple->dst.u.tcp.port)
146 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_TCP,
147 					 offsetof(struct tcphdr, dest),
148 					 0xFFFF, be16_to_cpu(target_dst));
149 }
150 
151 static void
152 tcf_ct_flow_table_add_action_nat_udp(const struct nf_conntrack_tuple *tuple,
153 				     struct nf_conntrack_tuple target,
154 				     struct flow_action *action)
155 {
156 	__be16 target_src = target.src.u.udp.port;
157 	__be16 target_dst = target.dst.u.udp.port;
158 
159 	if (target_src != tuple->src.u.udp.port)
160 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_UDP,
161 					 offsetof(struct udphdr, source),
162 					 0xFFFF, be16_to_cpu(target_src));
163 	if (target_dst != tuple->dst.u.udp.port)
164 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_UDP,
165 					 offsetof(struct udphdr, dest),
166 					 0xFFFF, be16_to_cpu(target_dst));
167 }
168 
169 static void tcf_ct_flow_table_add_action_meta(struct nf_conn *ct,
170 					      enum ip_conntrack_dir dir,
171 					      struct flow_action *action)
172 {
173 	struct nf_conn_labels *ct_labels;
174 	struct flow_action_entry *entry;
175 	enum ip_conntrack_info ctinfo;
176 	u32 *act_ct_labels;
177 
178 	entry = tcf_ct_flow_table_flow_action_get_next(action);
179 	entry->id = FLOW_ACTION_CT_METADATA;
180 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
181 	entry->ct_metadata.mark = ct->mark;
182 #endif
183 	ctinfo = dir == IP_CT_DIR_ORIGINAL ? IP_CT_ESTABLISHED :
184 					     IP_CT_ESTABLISHED_REPLY;
185 	/* aligns with the CT reference on the SKB nf_ct_set */
186 	entry->ct_metadata.cookie = (unsigned long)ct | ctinfo;
187 	entry->ct_metadata.orig_dir = dir == IP_CT_DIR_ORIGINAL;
188 
189 	act_ct_labels = entry->ct_metadata.labels;
190 	ct_labels = nf_ct_labels_find(ct);
191 	if (ct_labels)
192 		memcpy(act_ct_labels, ct_labels->bits, NF_CT_LABELS_MAX_SIZE);
193 	else
194 		memset(act_ct_labels, 0, NF_CT_LABELS_MAX_SIZE);
195 }
196 
197 static int tcf_ct_flow_table_add_action_nat(struct net *net,
198 					    struct nf_conn *ct,
199 					    enum ip_conntrack_dir dir,
200 					    struct flow_action *action)
201 {
202 	const struct nf_conntrack_tuple *tuple = &ct->tuplehash[dir].tuple;
203 	struct nf_conntrack_tuple target;
204 
205 	if (!(ct->status & IPS_NAT_MASK))
206 		return 0;
207 
208 	nf_ct_invert_tuple(&target, &ct->tuplehash[!dir].tuple);
209 
210 	switch (tuple->src.l3num) {
211 	case NFPROTO_IPV4:
212 		tcf_ct_flow_table_add_action_nat_ipv4(tuple, target,
213 						      action);
214 		break;
215 	case NFPROTO_IPV6:
216 		tcf_ct_flow_table_add_action_nat_ipv6(tuple, target,
217 						      action);
218 		break;
219 	default:
220 		return -EOPNOTSUPP;
221 	}
222 
223 	switch (nf_ct_protonum(ct)) {
224 	case IPPROTO_TCP:
225 		tcf_ct_flow_table_add_action_nat_tcp(tuple, target, action);
226 		break;
227 	case IPPROTO_UDP:
228 		tcf_ct_flow_table_add_action_nat_udp(tuple, target, action);
229 		break;
230 	default:
231 		return -EOPNOTSUPP;
232 	}
233 
234 	return 0;
235 }
236 
237 static int tcf_ct_flow_table_fill_actions(struct net *net,
238 					  const struct flow_offload *flow,
239 					  enum flow_offload_tuple_dir tdir,
240 					  struct nf_flow_rule *flow_rule)
241 {
242 	struct flow_action *action = &flow_rule->rule->action;
243 	int num_entries = action->num_entries;
244 	struct nf_conn *ct = flow->ct;
245 	enum ip_conntrack_dir dir;
246 	int i, err;
247 
248 	switch (tdir) {
249 	case FLOW_OFFLOAD_DIR_ORIGINAL:
250 		dir = IP_CT_DIR_ORIGINAL;
251 		break;
252 	case FLOW_OFFLOAD_DIR_REPLY:
253 		dir = IP_CT_DIR_REPLY;
254 		break;
255 	default:
256 		return -EOPNOTSUPP;
257 	}
258 
259 	err = tcf_ct_flow_table_add_action_nat(net, ct, dir, action);
260 	if (err)
261 		goto err_nat;
262 
263 	tcf_ct_flow_table_add_action_meta(ct, dir, action);
264 	return 0;
265 
266 err_nat:
267 	/* Clear filled actions */
268 	for (i = num_entries; i < action->num_entries; i++)
269 		memset(&action->entries[i], 0, sizeof(action->entries[i]));
270 	action->num_entries = num_entries;
271 
272 	return err;
273 }
274 
275 static struct nf_flowtable_type flowtable_ct = {
276 	.action		= tcf_ct_flow_table_fill_actions,
277 	.owner		= THIS_MODULE,
278 };
279 
280 static int tcf_ct_flow_table_get(struct net *net, struct tcf_ct_params *params)
281 {
282 	struct tcf_ct_flow_table *ct_ft;
283 	int err = -ENOMEM;
284 
285 	mutex_lock(&zones_mutex);
286 	ct_ft = rhashtable_lookup_fast(&zones_ht, &params->zone, zones_params);
287 	if (ct_ft && refcount_inc_not_zero(&ct_ft->ref))
288 		goto out_unlock;
289 
290 	ct_ft = kzalloc(sizeof(*ct_ft), GFP_KERNEL);
291 	if (!ct_ft)
292 		goto err_alloc;
293 	refcount_set(&ct_ft->ref, 1);
294 
295 	ct_ft->zone = params->zone;
296 	err = rhashtable_insert_fast(&zones_ht, &ct_ft->node, zones_params);
297 	if (err)
298 		goto err_insert;
299 
300 	ct_ft->nf_ft.type = &flowtable_ct;
301 	ct_ft->nf_ft.flags |= NF_FLOWTABLE_HW_OFFLOAD |
302 			      NF_FLOWTABLE_COUNTER;
303 	err = nf_flow_table_init(&ct_ft->nf_ft);
304 	if (err)
305 		goto err_init;
306 	write_pnet(&ct_ft->nf_ft.net, net);
307 
308 	__module_get(THIS_MODULE);
309 out_unlock:
310 	params->ct_ft = ct_ft;
311 	params->nf_ft = &ct_ft->nf_ft;
312 	mutex_unlock(&zones_mutex);
313 
314 	return 0;
315 
316 err_init:
317 	rhashtable_remove_fast(&zones_ht, &ct_ft->node, zones_params);
318 err_insert:
319 	kfree(ct_ft);
320 err_alloc:
321 	mutex_unlock(&zones_mutex);
322 	return err;
323 }
324 
325 static void tcf_ct_flow_table_cleanup_work(struct work_struct *work)
326 {
327 	struct flow_block_cb *block_cb, *tmp_cb;
328 	struct tcf_ct_flow_table *ct_ft;
329 	struct flow_block *block;
330 
331 	ct_ft = container_of(to_rcu_work(work), struct tcf_ct_flow_table,
332 			     rwork);
333 	nf_flow_table_free(&ct_ft->nf_ft);
334 
335 	/* Remove any remaining callbacks before cleanup */
336 	block = &ct_ft->nf_ft.flow_block;
337 	down_write(&ct_ft->nf_ft.flow_block_lock);
338 	list_for_each_entry_safe(block_cb, tmp_cb, &block->cb_list, list) {
339 		list_del(&block_cb->list);
340 		flow_block_cb_free(block_cb);
341 	}
342 	up_write(&ct_ft->nf_ft.flow_block_lock);
343 	kfree(ct_ft);
344 
345 	module_put(THIS_MODULE);
346 }
347 
348 static void tcf_ct_flow_table_put(struct tcf_ct_params *params)
349 {
350 	struct tcf_ct_flow_table *ct_ft = params->ct_ft;
351 
352 	if (refcount_dec_and_test(&params->ct_ft->ref)) {
353 		rhashtable_remove_fast(&zones_ht, &ct_ft->node, zones_params);
354 		INIT_RCU_WORK(&ct_ft->rwork, tcf_ct_flow_table_cleanup_work);
355 		queue_rcu_work(act_ct_wq, &ct_ft->rwork);
356 	}
357 }
358 
359 static void tcf_ct_flow_tc_ifidx(struct flow_offload *entry,
360 				 struct nf_conn_act_ct_ext *act_ct_ext, u8 dir)
361 {
362 	entry->tuplehash[dir].tuple.xmit_type = FLOW_OFFLOAD_XMIT_TC;
363 	entry->tuplehash[dir].tuple.tc.iifidx = act_ct_ext->ifindex[dir];
364 }
365 
366 static void tcf_ct_flow_table_add(struct tcf_ct_flow_table *ct_ft,
367 				  struct nf_conn *ct,
368 				  bool tcp)
369 {
370 	struct nf_conn_act_ct_ext *act_ct_ext;
371 	struct flow_offload *entry;
372 	int err;
373 
374 	if (test_and_set_bit(IPS_OFFLOAD_BIT, &ct->status))
375 		return;
376 
377 	entry = flow_offload_alloc(ct);
378 	if (!entry) {
379 		WARN_ON_ONCE(1);
380 		goto err_alloc;
381 	}
382 
383 	if (tcp) {
384 		ct->proto.tcp.seen[0].flags |= IP_CT_TCP_FLAG_BE_LIBERAL;
385 		ct->proto.tcp.seen[1].flags |= IP_CT_TCP_FLAG_BE_LIBERAL;
386 	}
387 
388 	act_ct_ext = nf_conn_act_ct_ext_find(ct);
389 	if (act_ct_ext) {
390 		tcf_ct_flow_tc_ifidx(entry, act_ct_ext, FLOW_OFFLOAD_DIR_ORIGINAL);
391 		tcf_ct_flow_tc_ifidx(entry, act_ct_ext, FLOW_OFFLOAD_DIR_REPLY);
392 	}
393 
394 	err = flow_offload_add(&ct_ft->nf_ft, entry);
395 	if (err)
396 		goto err_add;
397 
398 	return;
399 
400 err_add:
401 	flow_offload_free(entry);
402 err_alloc:
403 	clear_bit(IPS_OFFLOAD_BIT, &ct->status);
404 }
405 
406 static void tcf_ct_flow_table_process_conn(struct tcf_ct_flow_table *ct_ft,
407 					   struct nf_conn *ct,
408 					   enum ip_conntrack_info ctinfo)
409 {
410 	bool tcp = false;
411 
412 	if ((ctinfo != IP_CT_ESTABLISHED && ctinfo != IP_CT_ESTABLISHED_REPLY) ||
413 	    !test_bit(IPS_ASSURED_BIT, &ct->status))
414 		return;
415 
416 	switch (nf_ct_protonum(ct)) {
417 	case IPPROTO_TCP:
418 		tcp = true;
419 		if (ct->proto.tcp.state != TCP_CONNTRACK_ESTABLISHED)
420 			return;
421 		break;
422 	case IPPROTO_UDP:
423 		break;
424 #ifdef CONFIG_NF_CT_PROTO_GRE
425 	case IPPROTO_GRE: {
426 		struct nf_conntrack_tuple *tuple;
427 
428 		if (ct->status & IPS_NAT_MASK)
429 			return;
430 		tuple = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
431 		/* No support for GRE v1 */
432 		if (tuple->src.u.gre.key || tuple->dst.u.gre.key)
433 			return;
434 		break;
435 	}
436 #endif
437 	default:
438 		return;
439 	}
440 
441 	if (nf_ct_ext_exist(ct, NF_CT_EXT_HELPER) ||
442 	    ct->status & IPS_SEQ_ADJUST)
443 		return;
444 
445 	tcf_ct_flow_table_add(ct_ft, ct, tcp);
446 }
447 
448 static bool
449 tcf_ct_flow_table_fill_tuple_ipv4(struct sk_buff *skb,
450 				  struct flow_offload_tuple *tuple,
451 				  struct tcphdr **tcph)
452 {
453 	struct flow_ports *ports;
454 	unsigned int thoff;
455 	struct iphdr *iph;
456 	size_t hdrsize;
457 	u8 ipproto;
458 
459 	if (!pskb_network_may_pull(skb, sizeof(*iph)))
460 		return false;
461 
462 	iph = ip_hdr(skb);
463 	thoff = iph->ihl * 4;
464 
465 	if (ip_is_fragment(iph) ||
466 	    unlikely(thoff != sizeof(struct iphdr)))
467 		return false;
468 
469 	ipproto = iph->protocol;
470 	switch (ipproto) {
471 	case IPPROTO_TCP:
472 		hdrsize = sizeof(struct tcphdr);
473 		break;
474 	case IPPROTO_UDP:
475 		hdrsize = sizeof(*ports);
476 		break;
477 #ifdef CONFIG_NF_CT_PROTO_GRE
478 	case IPPROTO_GRE:
479 		hdrsize = sizeof(struct gre_base_hdr);
480 		break;
481 #endif
482 	default:
483 		return false;
484 	}
485 
486 	if (iph->ttl <= 1)
487 		return false;
488 
489 	if (!pskb_network_may_pull(skb, thoff + hdrsize))
490 		return false;
491 
492 	switch (ipproto) {
493 	case IPPROTO_TCP:
494 		*tcph = (void *)(skb_network_header(skb) + thoff);
495 		fallthrough;
496 	case IPPROTO_UDP:
497 		ports = (struct flow_ports *)(skb_network_header(skb) + thoff);
498 		tuple->src_port = ports->source;
499 		tuple->dst_port = ports->dest;
500 		break;
501 	case IPPROTO_GRE: {
502 		struct gre_base_hdr *greh;
503 
504 		greh = (struct gre_base_hdr *)(skb_network_header(skb) + thoff);
505 		if ((greh->flags & GRE_VERSION) != GRE_VERSION_0)
506 			return false;
507 		break;
508 	}
509 	}
510 
511 	iph = ip_hdr(skb);
512 
513 	tuple->src_v4.s_addr = iph->saddr;
514 	tuple->dst_v4.s_addr = iph->daddr;
515 	tuple->l3proto = AF_INET;
516 	tuple->l4proto = ipproto;
517 
518 	return true;
519 }
520 
521 static bool
522 tcf_ct_flow_table_fill_tuple_ipv6(struct sk_buff *skb,
523 				  struct flow_offload_tuple *tuple,
524 				  struct tcphdr **tcph)
525 {
526 	struct flow_ports *ports;
527 	struct ipv6hdr *ip6h;
528 	unsigned int thoff;
529 	size_t hdrsize;
530 	u8 nexthdr;
531 
532 	if (!pskb_network_may_pull(skb, sizeof(*ip6h)))
533 		return false;
534 
535 	ip6h = ipv6_hdr(skb);
536 	thoff = sizeof(*ip6h);
537 
538 	nexthdr = ip6h->nexthdr;
539 	switch (nexthdr) {
540 	case IPPROTO_TCP:
541 		hdrsize = sizeof(struct tcphdr);
542 		break;
543 	case IPPROTO_UDP:
544 		hdrsize = sizeof(*ports);
545 		break;
546 #ifdef CONFIG_NF_CT_PROTO_GRE
547 	case IPPROTO_GRE:
548 		hdrsize = sizeof(struct gre_base_hdr);
549 		break;
550 #endif
551 	default:
552 		return false;
553 	}
554 
555 	if (ip6h->hop_limit <= 1)
556 		return false;
557 
558 	if (!pskb_network_may_pull(skb, thoff + hdrsize))
559 		return false;
560 
561 	switch (nexthdr) {
562 	case IPPROTO_TCP:
563 		*tcph = (void *)(skb_network_header(skb) + thoff);
564 		fallthrough;
565 	case IPPROTO_UDP:
566 		ports = (struct flow_ports *)(skb_network_header(skb) + thoff);
567 		tuple->src_port = ports->source;
568 		tuple->dst_port = ports->dest;
569 		break;
570 	case IPPROTO_GRE: {
571 		struct gre_base_hdr *greh;
572 
573 		greh = (struct gre_base_hdr *)(skb_network_header(skb) + thoff);
574 		if ((greh->flags & GRE_VERSION) != GRE_VERSION_0)
575 			return false;
576 		break;
577 	}
578 	}
579 
580 	ip6h = ipv6_hdr(skb);
581 
582 	tuple->src_v6 = ip6h->saddr;
583 	tuple->dst_v6 = ip6h->daddr;
584 	tuple->l3proto = AF_INET6;
585 	tuple->l4proto = nexthdr;
586 
587 	return true;
588 }
589 
590 static bool tcf_ct_flow_table_lookup(struct tcf_ct_params *p,
591 				     struct sk_buff *skb,
592 				     u8 family)
593 {
594 	struct nf_flowtable *nf_ft = &p->ct_ft->nf_ft;
595 	struct flow_offload_tuple_rhash *tuplehash;
596 	struct flow_offload_tuple tuple = {};
597 	enum ip_conntrack_info ctinfo;
598 	struct tcphdr *tcph = NULL;
599 	struct flow_offload *flow;
600 	struct nf_conn *ct;
601 	u8 dir;
602 
603 	switch (family) {
604 	case NFPROTO_IPV4:
605 		if (!tcf_ct_flow_table_fill_tuple_ipv4(skb, &tuple, &tcph))
606 			return false;
607 		break;
608 	case NFPROTO_IPV6:
609 		if (!tcf_ct_flow_table_fill_tuple_ipv6(skb, &tuple, &tcph))
610 			return false;
611 		break;
612 	default:
613 		return false;
614 	}
615 
616 	tuplehash = flow_offload_lookup(nf_ft, &tuple);
617 	if (!tuplehash)
618 		return false;
619 
620 	dir = tuplehash->tuple.dir;
621 	flow = container_of(tuplehash, struct flow_offload, tuplehash[dir]);
622 	ct = flow->ct;
623 
624 	if (tcph && (unlikely(tcph->fin || tcph->rst))) {
625 		flow_offload_teardown(flow);
626 		return false;
627 	}
628 
629 	ctinfo = dir == FLOW_OFFLOAD_DIR_ORIGINAL ? IP_CT_ESTABLISHED :
630 						    IP_CT_ESTABLISHED_REPLY;
631 
632 	flow_offload_refresh(nf_ft, flow);
633 	nf_conntrack_get(&ct->ct_general);
634 	nf_ct_set(skb, ct, ctinfo);
635 	if (nf_ft->flags & NF_FLOWTABLE_COUNTER)
636 		nf_ct_acct_update(ct, dir, skb->len);
637 
638 	return true;
639 }
640 
641 static int tcf_ct_flow_tables_init(void)
642 {
643 	return rhashtable_init(&zones_ht, &zones_params);
644 }
645 
646 static void tcf_ct_flow_tables_uninit(void)
647 {
648 	rhashtable_destroy(&zones_ht);
649 }
650 
651 static struct tc_action_ops act_ct_ops;
652 
653 struct tc_ct_action_net {
654 	struct tc_action_net tn; /* Must be first */
655 	bool labels;
656 };
657 
658 /* Determine whether skb->_nfct is equal to the result of conntrack lookup. */
659 static bool tcf_ct_skb_nfct_cached(struct net *net, struct sk_buff *skb,
660 				   u16 zone_id, bool force)
661 {
662 	enum ip_conntrack_info ctinfo;
663 	struct nf_conn *ct;
664 
665 	ct = nf_ct_get(skb, &ctinfo);
666 	if (!ct)
667 		return false;
668 	if (!net_eq(net, read_pnet(&ct->ct_net)))
669 		goto drop_ct;
670 	if (nf_ct_zone(ct)->id != zone_id)
671 		goto drop_ct;
672 
673 	/* Force conntrack entry direction. */
674 	if (force && CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL) {
675 		if (nf_ct_is_confirmed(ct))
676 			nf_ct_kill(ct);
677 
678 		goto drop_ct;
679 	}
680 
681 	return true;
682 
683 drop_ct:
684 	nf_ct_put(ct);
685 	nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
686 
687 	return false;
688 }
689 
690 /* Trim the skb to the length specified by the IP/IPv6 header,
691  * removing any trailing lower-layer padding. This prepares the skb
692  * for higher-layer processing that assumes skb->len excludes padding
693  * (such as nf_ip_checksum). The caller needs to pull the skb to the
694  * network header, and ensure ip_hdr/ipv6_hdr points to valid data.
695  */
696 static int tcf_ct_skb_network_trim(struct sk_buff *skb, int family)
697 {
698 	unsigned int len;
699 
700 	switch (family) {
701 	case NFPROTO_IPV4:
702 		len = ntohs(ip_hdr(skb)->tot_len);
703 		break;
704 	case NFPROTO_IPV6:
705 		len = sizeof(struct ipv6hdr)
706 			+ ntohs(ipv6_hdr(skb)->payload_len);
707 		break;
708 	default:
709 		len = skb->len;
710 	}
711 
712 	return pskb_trim_rcsum(skb, len);
713 }
714 
715 static u8 tcf_ct_skb_nf_family(struct sk_buff *skb)
716 {
717 	u8 family = NFPROTO_UNSPEC;
718 
719 	switch (skb_protocol(skb, true)) {
720 	case htons(ETH_P_IP):
721 		family = NFPROTO_IPV4;
722 		break;
723 	case htons(ETH_P_IPV6):
724 		family = NFPROTO_IPV6;
725 		break;
726 	default:
727 		break;
728 	}
729 
730 	return family;
731 }
732 
733 static int tcf_ct_ipv4_is_fragment(struct sk_buff *skb, bool *frag)
734 {
735 	unsigned int len;
736 
737 	len =  skb_network_offset(skb) + sizeof(struct iphdr);
738 	if (unlikely(skb->len < len))
739 		return -EINVAL;
740 	if (unlikely(!pskb_may_pull(skb, len)))
741 		return -ENOMEM;
742 
743 	*frag = ip_is_fragment(ip_hdr(skb));
744 	return 0;
745 }
746 
747 static int tcf_ct_ipv6_is_fragment(struct sk_buff *skb, bool *frag)
748 {
749 	unsigned int flags = 0, len, payload_ofs = 0;
750 	unsigned short frag_off;
751 	int nexthdr;
752 
753 	len =  skb_network_offset(skb) + sizeof(struct ipv6hdr);
754 	if (unlikely(skb->len < len))
755 		return -EINVAL;
756 	if (unlikely(!pskb_may_pull(skb, len)))
757 		return -ENOMEM;
758 
759 	nexthdr = ipv6_find_hdr(skb, &payload_ofs, -1, &frag_off, &flags);
760 	if (unlikely(nexthdr < 0))
761 		return -EPROTO;
762 
763 	*frag = flags & IP6_FH_F_FRAG;
764 	return 0;
765 }
766 
767 static int tcf_ct_handle_fragments(struct net *net, struct sk_buff *skb,
768 				   u8 family, u16 zone, bool *defrag)
769 {
770 	enum ip_conntrack_info ctinfo;
771 	struct nf_conn *ct;
772 	int err = 0;
773 	bool frag;
774 	u16 mru;
775 
776 	/* Previously seen (loopback)? Ignore. */
777 	ct = nf_ct_get(skb, &ctinfo);
778 	if ((ct && !nf_ct_is_template(ct)) || ctinfo == IP_CT_UNTRACKED)
779 		return 0;
780 
781 	if (family == NFPROTO_IPV4)
782 		err = tcf_ct_ipv4_is_fragment(skb, &frag);
783 	else
784 		err = tcf_ct_ipv6_is_fragment(skb, &frag);
785 	if (err || !frag)
786 		return err;
787 
788 	skb_get(skb);
789 	mru = tc_skb_cb(skb)->mru;
790 
791 	if (family == NFPROTO_IPV4) {
792 		enum ip_defrag_users user = IP_DEFRAG_CONNTRACK_IN + zone;
793 
794 		memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
795 		local_bh_disable();
796 		err = ip_defrag(net, skb, user);
797 		local_bh_enable();
798 		if (err && err != -EINPROGRESS)
799 			return err;
800 
801 		if (!err) {
802 			*defrag = true;
803 			mru = IPCB(skb)->frag_max_size;
804 		}
805 	} else { /* NFPROTO_IPV6 */
806 #if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6)
807 		enum ip6_defrag_users user = IP6_DEFRAG_CONNTRACK_IN + zone;
808 
809 		memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
810 		err = nf_ct_frag6_gather(net, skb, user);
811 		if (err && err != -EINPROGRESS)
812 			goto out_free;
813 
814 		if (!err) {
815 			*defrag = true;
816 			mru = IP6CB(skb)->frag_max_size;
817 		}
818 #else
819 		err = -EOPNOTSUPP;
820 		goto out_free;
821 #endif
822 	}
823 
824 	if (err != -EINPROGRESS)
825 		tc_skb_cb(skb)->mru = mru;
826 	skb_clear_hash(skb);
827 	skb->ignore_df = 1;
828 	return err;
829 
830 out_free:
831 	kfree_skb(skb);
832 	return err;
833 }
834 
835 static void tcf_ct_params_free(struct rcu_head *head)
836 {
837 	struct tcf_ct_params *params = container_of(head,
838 						    struct tcf_ct_params, rcu);
839 
840 	tcf_ct_flow_table_put(params);
841 
842 	if (params->tmpl)
843 		nf_ct_put(params->tmpl);
844 	kfree(params);
845 }
846 
847 #if IS_ENABLED(CONFIG_NF_NAT)
848 /* Modelled after nf_nat_ipv[46]_fn().
849  * range is only used for new, uninitialized NAT state.
850  * Returns either NF_ACCEPT or NF_DROP.
851  */
852 static int ct_nat_execute(struct sk_buff *skb, struct nf_conn *ct,
853 			  enum ip_conntrack_info ctinfo,
854 			  const struct nf_nat_range2 *range,
855 			  enum nf_nat_manip_type maniptype)
856 {
857 	__be16 proto = skb_protocol(skb, true);
858 	int hooknum, err = NF_ACCEPT;
859 
860 	/* See HOOK2MANIP(). */
861 	if (maniptype == NF_NAT_MANIP_SRC)
862 		hooknum = NF_INET_LOCAL_IN; /* Source NAT */
863 	else
864 		hooknum = NF_INET_LOCAL_OUT; /* Destination NAT */
865 
866 	switch (ctinfo) {
867 	case IP_CT_RELATED:
868 	case IP_CT_RELATED_REPLY:
869 		if (proto == htons(ETH_P_IP) &&
870 		    ip_hdr(skb)->protocol == IPPROTO_ICMP) {
871 			if (!nf_nat_icmp_reply_translation(skb, ct, ctinfo,
872 							   hooknum))
873 				err = NF_DROP;
874 			goto out;
875 		} else if (IS_ENABLED(CONFIG_IPV6) && proto == htons(ETH_P_IPV6)) {
876 			__be16 frag_off;
877 			u8 nexthdr = ipv6_hdr(skb)->nexthdr;
878 			int hdrlen = ipv6_skip_exthdr(skb,
879 						      sizeof(struct ipv6hdr),
880 						      &nexthdr, &frag_off);
881 
882 			if (hdrlen >= 0 && nexthdr == IPPROTO_ICMPV6) {
883 				if (!nf_nat_icmpv6_reply_translation(skb, ct,
884 								     ctinfo,
885 								     hooknum,
886 								     hdrlen))
887 					err = NF_DROP;
888 				goto out;
889 			}
890 		}
891 		/* Non-ICMP, fall thru to initialize if needed. */
892 		fallthrough;
893 	case IP_CT_NEW:
894 		/* Seen it before?  This can happen for loopback, retrans,
895 		 * or local packets.
896 		 */
897 		if (!nf_nat_initialized(ct, maniptype)) {
898 			/* Initialize according to the NAT action. */
899 			err = (range && range->flags & NF_NAT_RANGE_MAP_IPS)
900 				/* Action is set up to establish a new
901 				 * mapping.
902 				 */
903 				? nf_nat_setup_info(ct, range, maniptype)
904 				: nf_nat_alloc_null_binding(ct, hooknum);
905 			if (err != NF_ACCEPT)
906 				goto out;
907 		}
908 		break;
909 
910 	case IP_CT_ESTABLISHED:
911 	case IP_CT_ESTABLISHED_REPLY:
912 		break;
913 
914 	default:
915 		err = NF_DROP;
916 		goto out;
917 	}
918 
919 	err = nf_nat_packet(ct, ctinfo, hooknum, skb);
920 	if (err == NF_ACCEPT) {
921 		if (maniptype == NF_NAT_MANIP_SRC)
922 			tc_skb_cb(skb)->post_ct_snat = 1;
923 		if (maniptype == NF_NAT_MANIP_DST)
924 			tc_skb_cb(skb)->post_ct_dnat = 1;
925 	}
926 out:
927 	return err;
928 }
929 #endif /* CONFIG_NF_NAT */
930 
931 static void tcf_ct_act_set_mark(struct nf_conn *ct, u32 mark, u32 mask)
932 {
933 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
934 	u32 new_mark;
935 
936 	if (!mask)
937 		return;
938 
939 	new_mark = mark | (ct->mark & ~(mask));
940 	if (ct->mark != new_mark) {
941 		ct->mark = new_mark;
942 		if (nf_ct_is_confirmed(ct))
943 			nf_conntrack_event_cache(IPCT_MARK, ct);
944 	}
945 #endif
946 }
947 
948 static void tcf_ct_act_set_labels(struct nf_conn *ct,
949 				  u32 *labels,
950 				  u32 *labels_m)
951 {
952 #if IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS)
953 	size_t labels_sz = sizeof_field(struct tcf_ct_params, labels);
954 
955 	if (!memchr_inv(labels_m, 0, labels_sz))
956 		return;
957 
958 	nf_connlabels_replace(ct, labels, labels_m, 4);
959 #endif
960 }
961 
962 static int tcf_ct_act_nat(struct sk_buff *skb,
963 			  struct nf_conn *ct,
964 			  enum ip_conntrack_info ctinfo,
965 			  int ct_action,
966 			  struct nf_nat_range2 *range,
967 			  bool commit)
968 {
969 #if IS_ENABLED(CONFIG_NF_NAT)
970 	int err;
971 	enum nf_nat_manip_type maniptype;
972 
973 	if (!(ct_action & TCA_CT_ACT_NAT))
974 		return NF_ACCEPT;
975 
976 	/* Add NAT extension if not confirmed yet. */
977 	if (!nf_ct_is_confirmed(ct) && !nf_ct_nat_ext_add(ct))
978 		return NF_DROP;   /* Can't NAT. */
979 
980 	if (ctinfo != IP_CT_NEW && (ct->status & IPS_NAT_MASK) &&
981 	    (ctinfo != IP_CT_RELATED || commit)) {
982 		/* NAT an established or related connection like before. */
983 		if (CTINFO2DIR(ctinfo) == IP_CT_DIR_REPLY)
984 			/* This is the REPLY direction for a connection
985 			 * for which NAT was applied in the forward
986 			 * direction.  Do the reverse NAT.
987 			 */
988 			maniptype = ct->status & IPS_SRC_NAT
989 				? NF_NAT_MANIP_DST : NF_NAT_MANIP_SRC;
990 		else
991 			maniptype = ct->status & IPS_SRC_NAT
992 				? NF_NAT_MANIP_SRC : NF_NAT_MANIP_DST;
993 	} else if (ct_action & TCA_CT_ACT_NAT_SRC) {
994 		maniptype = NF_NAT_MANIP_SRC;
995 	} else if (ct_action & TCA_CT_ACT_NAT_DST) {
996 		maniptype = NF_NAT_MANIP_DST;
997 	} else {
998 		return NF_ACCEPT;
999 	}
1000 
1001 	err = ct_nat_execute(skb, ct, ctinfo, range, maniptype);
1002 	if (err == NF_ACCEPT && ct->status & IPS_DST_NAT) {
1003 		if (ct->status & IPS_SRC_NAT) {
1004 			if (maniptype == NF_NAT_MANIP_SRC)
1005 				maniptype = NF_NAT_MANIP_DST;
1006 			else
1007 				maniptype = NF_NAT_MANIP_SRC;
1008 
1009 			err = ct_nat_execute(skb, ct, ctinfo, range,
1010 					     maniptype);
1011 		} else if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL) {
1012 			err = ct_nat_execute(skb, ct, ctinfo, NULL,
1013 					     NF_NAT_MANIP_SRC);
1014 		}
1015 	}
1016 	return err;
1017 #else
1018 	return NF_ACCEPT;
1019 #endif
1020 }
1021 
1022 static int tcf_ct_act(struct sk_buff *skb, const struct tc_action *a,
1023 		      struct tcf_result *res)
1024 {
1025 	struct net *net = dev_net(skb->dev);
1026 	bool cached, commit, clear, force;
1027 	enum ip_conntrack_info ctinfo;
1028 	struct tcf_ct *c = to_ct(a);
1029 	struct nf_conn *tmpl = NULL;
1030 	struct nf_hook_state state;
1031 	int nh_ofs, err, retval;
1032 	struct tcf_ct_params *p;
1033 	bool skip_add = false;
1034 	bool defrag = false;
1035 	struct nf_conn *ct;
1036 	u8 family;
1037 
1038 	p = rcu_dereference_bh(c->params);
1039 
1040 	retval = READ_ONCE(c->tcf_action);
1041 	commit = p->ct_action & TCA_CT_ACT_COMMIT;
1042 	clear = p->ct_action & TCA_CT_ACT_CLEAR;
1043 	force = p->ct_action & TCA_CT_ACT_FORCE;
1044 	tmpl = p->tmpl;
1045 
1046 	tcf_lastuse_update(&c->tcf_tm);
1047 	tcf_action_update_bstats(&c->common, skb);
1048 
1049 	if (clear) {
1050 		tc_skb_cb(skb)->post_ct = false;
1051 		ct = nf_ct_get(skb, &ctinfo);
1052 		if (ct) {
1053 			nf_ct_put(ct);
1054 			nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
1055 		}
1056 
1057 		goto out_clear;
1058 	}
1059 
1060 	family = tcf_ct_skb_nf_family(skb);
1061 	if (family == NFPROTO_UNSPEC)
1062 		goto drop;
1063 
1064 	/* The conntrack module expects to be working at L3.
1065 	 * We also try to pull the IPv4/6 header to linear area
1066 	 */
1067 	nh_ofs = skb_network_offset(skb);
1068 	skb_pull_rcsum(skb, nh_ofs);
1069 	err = tcf_ct_handle_fragments(net, skb, family, p->zone, &defrag);
1070 	if (err == -EINPROGRESS) {
1071 		retval = TC_ACT_STOLEN;
1072 		goto out_clear;
1073 	}
1074 	if (err)
1075 		goto drop;
1076 
1077 	err = tcf_ct_skb_network_trim(skb, family);
1078 	if (err)
1079 		goto drop;
1080 
1081 	/* If we are recirculating packets to match on ct fields and
1082 	 * committing with a separate ct action, then we don't need to
1083 	 * actually run the packet through conntrack twice unless it's for a
1084 	 * different zone.
1085 	 */
1086 	cached = tcf_ct_skb_nfct_cached(net, skb, p->zone, force);
1087 	if (!cached) {
1088 		if (tcf_ct_flow_table_lookup(p, skb, family)) {
1089 			skip_add = true;
1090 			goto do_nat;
1091 		}
1092 
1093 		/* Associate skb with specified zone. */
1094 		if (tmpl) {
1095 			nf_conntrack_put(skb_nfct(skb));
1096 			nf_conntrack_get(&tmpl->ct_general);
1097 			nf_ct_set(skb, tmpl, IP_CT_NEW);
1098 		}
1099 
1100 		state.hook = NF_INET_PRE_ROUTING;
1101 		state.net = net;
1102 		state.pf = family;
1103 		err = nf_conntrack_in(skb, &state);
1104 		if (err != NF_ACCEPT)
1105 			goto out_push;
1106 	}
1107 
1108 do_nat:
1109 	ct = nf_ct_get(skb, &ctinfo);
1110 	if (!ct)
1111 		goto out_push;
1112 	nf_ct_deliver_cached_events(ct);
1113 	nf_conn_act_ct_ext_fill(skb, ct, ctinfo);
1114 
1115 	err = tcf_ct_act_nat(skb, ct, ctinfo, p->ct_action, &p->range, commit);
1116 	if (err != NF_ACCEPT)
1117 		goto drop;
1118 
1119 	if (commit) {
1120 		tcf_ct_act_set_mark(ct, p->mark, p->mark_mask);
1121 		tcf_ct_act_set_labels(ct, p->labels, p->labels_mask);
1122 
1123 		if (!nf_ct_is_confirmed(ct))
1124 			nf_conn_act_ct_ext_add(ct);
1125 
1126 		/* This will take care of sending queued events
1127 		 * even if the connection is already confirmed.
1128 		 */
1129 		if (nf_conntrack_confirm(skb) != NF_ACCEPT)
1130 			goto drop;
1131 	}
1132 
1133 	if (!skip_add)
1134 		tcf_ct_flow_table_process_conn(p->ct_ft, ct, ctinfo);
1135 
1136 out_push:
1137 	skb_push_rcsum(skb, nh_ofs);
1138 
1139 	tc_skb_cb(skb)->post_ct = true;
1140 	tc_skb_cb(skb)->zone = p->zone;
1141 out_clear:
1142 	if (defrag)
1143 		qdisc_skb_cb(skb)->pkt_len = skb->len;
1144 	return retval;
1145 
1146 drop:
1147 	tcf_action_inc_drop_qstats(&c->common);
1148 	return TC_ACT_SHOT;
1149 }
1150 
1151 static const struct nla_policy ct_policy[TCA_CT_MAX + 1] = {
1152 	[TCA_CT_ACTION] = { .type = NLA_U16 },
1153 	[TCA_CT_PARMS] = NLA_POLICY_EXACT_LEN(sizeof(struct tc_ct)),
1154 	[TCA_CT_ZONE] = { .type = NLA_U16 },
1155 	[TCA_CT_MARK] = { .type = NLA_U32 },
1156 	[TCA_CT_MARK_MASK] = { .type = NLA_U32 },
1157 	[TCA_CT_LABELS] = { .type = NLA_BINARY,
1158 			    .len = 128 / BITS_PER_BYTE },
1159 	[TCA_CT_LABELS_MASK] = { .type = NLA_BINARY,
1160 				 .len = 128 / BITS_PER_BYTE },
1161 	[TCA_CT_NAT_IPV4_MIN] = { .type = NLA_U32 },
1162 	[TCA_CT_NAT_IPV4_MAX] = { .type = NLA_U32 },
1163 	[TCA_CT_NAT_IPV6_MIN] = NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
1164 	[TCA_CT_NAT_IPV6_MAX] = NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
1165 	[TCA_CT_NAT_PORT_MIN] = { .type = NLA_U16 },
1166 	[TCA_CT_NAT_PORT_MAX] = { .type = NLA_U16 },
1167 };
1168 
1169 static int tcf_ct_fill_params_nat(struct tcf_ct_params *p,
1170 				  struct tc_ct *parm,
1171 				  struct nlattr **tb,
1172 				  struct netlink_ext_ack *extack)
1173 {
1174 	struct nf_nat_range2 *range;
1175 
1176 	if (!(p->ct_action & TCA_CT_ACT_NAT))
1177 		return 0;
1178 
1179 	if (!IS_ENABLED(CONFIG_NF_NAT)) {
1180 		NL_SET_ERR_MSG_MOD(extack, "Netfilter nat isn't enabled in kernel");
1181 		return -EOPNOTSUPP;
1182 	}
1183 
1184 	if (!(p->ct_action & (TCA_CT_ACT_NAT_SRC | TCA_CT_ACT_NAT_DST)))
1185 		return 0;
1186 
1187 	if ((p->ct_action & TCA_CT_ACT_NAT_SRC) &&
1188 	    (p->ct_action & TCA_CT_ACT_NAT_DST)) {
1189 		NL_SET_ERR_MSG_MOD(extack, "dnat and snat can't be enabled at the same time");
1190 		return -EOPNOTSUPP;
1191 	}
1192 
1193 	range = &p->range;
1194 	if (tb[TCA_CT_NAT_IPV4_MIN]) {
1195 		struct nlattr *max_attr = tb[TCA_CT_NAT_IPV4_MAX];
1196 
1197 		p->ipv4_range = true;
1198 		range->flags |= NF_NAT_RANGE_MAP_IPS;
1199 		range->min_addr.ip =
1200 			nla_get_in_addr(tb[TCA_CT_NAT_IPV4_MIN]);
1201 
1202 		range->max_addr.ip = max_attr ?
1203 				     nla_get_in_addr(max_attr) :
1204 				     range->min_addr.ip;
1205 	} else if (tb[TCA_CT_NAT_IPV6_MIN]) {
1206 		struct nlattr *max_attr = tb[TCA_CT_NAT_IPV6_MAX];
1207 
1208 		p->ipv4_range = false;
1209 		range->flags |= NF_NAT_RANGE_MAP_IPS;
1210 		range->min_addr.in6 =
1211 			nla_get_in6_addr(tb[TCA_CT_NAT_IPV6_MIN]);
1212 
1213 		range->max_addr.in6 = max_attr ?
1214 				      nla_get_in6_addr(max_attr) :
1215 				      range->min_addr.in6;
1216 	}
1217 
1218 	if (tb[TCA_CT_NAT_PORT_MIN]) {
1219 		range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1220 		range->min_proto.all = nla_get_be16(tb[TCA_CT_NAT_PORT_MIN]);
1221 
1222 		range->max_proto.all = tb[TCA_CT_NAT_PORT_MAX] ?
1223 				       nla_get_be16(tb[TCA_CT_NAT_PORT_MAX]) :
1224 				       range->min_proto.all;
1225 	}
1226 
1227 	return 0;
1228 }
1229 
1230 static void tcf_ct_set_key_val(struct nlattr **tb,
1231 			       void *val, int val_type,
1232 			       void *mask, int mask_type,
1233 			       int len)
1234 {
1235 	if (!tb[val_type])
1236 		return;
1237 	nla_memcpy(val, tb[val_type], len);
1238 
1239 	if (!mask)
1240 		return;
1241 
1242 	if (mask_type == TCA_CT_UNSPEC || !tb[mask_type])
1243 		memset(mask, 0xff, len);
1244 	else
1245 		nla_memcpy(mask, tb[mask_type], len);
1246 }
1247 
1248 static int tcf_ct_fill_params(struct net *net,
1249 			      struct tcf_ct_params *p,
1250 			      struct tc_ct *parm,
1251 			      struct nlattr **tb,
1252 			      struct netlink_ext_ack *extack)
1253 {
1254 	struct tc_ct_action_net *tn = net_generic(net, act_ct_ops.net_id);
1255 	struct nf_conntrack_zone zone;
1256 	struct nf_conn *tmpl;
1257 	int err;
1258 
1259 	p->zone = NF_CT_DEFAULT_ZONE_ID;
1260 
1261 	tcf_ct_set_key_val(tb,
1262 			   &p->ct_action, TCA_CT_ACTION,
1263 			   NULL, TCA_CT_UNSPEC,
1264 			   sizeof(p->ct_action));
1265 
1266 	if (p->ct_action & TCA_CT_ACT_CLEAR)
1267 		return 0;
1268 
1269 	err = tcf_ct_fill_params_nat(p, parm, tb, extack);
1270 	if (err)
1271 		return err;
1272 
1273 	if (tb[TCA_CT_MARK]) {
1274 		if (!IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)) {
1275 			NL_SET_ERR_MSG_MOD(extack, "Conntrack mark isn't enabled.");
1276 			return -EOPNOTSUPP;
1277 		}
1278 		tcf_ct_set_key_val(tb,
1279 				   &p->mark, TCA_CT_MARK,
1280 				   &p->mark_mask, TCA_CT_MARK_MASK,
1281 				   sizeof(p->mark));
1282 	}
1283 
1284 	if (tb[TCA_CT_LABELS]) {
1285 		if (!IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS)) {
1286 			NL_SET_ERR_MSG_MOD(extack, "Conntrack labels isn't enabled.");
1287 			return -EOPNOTSUPP;
1288 		}
1289 
1290 		if (!tn->labels) {
1291 			NL_SET_ERR_MSG_MOD(extack, "Failed to set connlabel length");
1292 			return -EOPNOTSUPP;
1293 		}
1294 		tcf_ct_set_key_val(tb,
1295 				   p->labels, TCA_CT_LABELS,
1296 				   p->labels_mask, TCA_CT_LABELS_MASK,
1297 				   sizeof(p->labels));
1298 	}
1299 
1300 	if (tb[TCA_CT_ZONE]) {
1301 		if (!IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES)) {
1302 			NL_SET_ERR_MSG_MOD(extack, "Conntrack zones isn't enabled.");
1303 			return -EOPNOTSUPP;
1304 		}
1305 
1306 		tcf_ct_set_key_val(tb,
1307 				   &p->zone, TCA_CT_ZONE,
1308 				   NULL, TCA_CT_UNSPEC,
1309 				   sizeof(p->zone));
1310 	}
1311 
1312 	nf_ct_zone_init(&zone, p->zone, NF_CT_DEFAULT_ZONE_DIR, 0);
1313 	tmpl = nf_ct_tmpl_alloc(net, &zone, GFP_KERNEL);
1314 	if (!tmpl) {
1315 		NL_SET_ERR_MSG_MOD(extack, "Failed to allocate conntrack template");
1316 		return -ENOMEM;
1317 	}
1318 	__set_bit(IPS_CONFIRMED_BIT, &tmpl->status);
1319 	p->tmpl = tmpl;
1320 
1321 	return 0;
1322 }
1323 
1324 static int tcf_ct_init(struct net *net, struct nlattr *nla,
1325 		       struct nlattr *est, struct tc_action **a,
1326 		       struct tcf_proto *tp, u32 flags,
1327 		       struct netlink_ext_ack *extack)
1328 {
1329 	struct tc_action_net *tn = net_generic(net, act_ct_ops.net_id);
1330 	bool bind = flags & TCA_ACT_FLAGS_BIND;
1331 	struct tcf_ct_params *params = NULL;
1332 	struct nlattr *tb[TCA_CT_MAX + 1];
1333 	struct tcf_chain *goto_ch = NULL;
1334 	struct tc_ct *parm;
1335 	struct tcf_ct *c;
1336 	int err, res = 0;
1337 	u32 index;
1338 
1339 	if (!nla) {
1340 		NL_SET_ERR_MSG_MOD(extack, "Ct requires attributes to be passed");
1341 		return -EINVAL;
1342 	}
1343 
1344 	err = nla_parse_nested(tb, TCA_CT_MAX, nla, ct_policy, extack);
1345 	if (err < 0)
1346 		return err;
1347 
1348 	if (!tb[TCA_CT_PARMS]) {
1349 		NL_SET_ERR_MSG_MOD(extack, "Missing required ct parameters");
1350 		return -EINVAL;
1351 	}
1352 	parm = nla_data(tb[TCA_CT_PARMS]);
1353 	index = parm->index;
1354 	err = tcf_idr_check_alloc(tn, &index, a, bind);
1355 	if (err < 0)
1356 		return err;
1357 
1358 	if (!err) {
1359 		err = tcf_idr_create_from_flags(tn, index, est, a,
1360 						&act_ct_ops, bind, flags);
1361 		if (err) {
1362 			tcf_idr_cleanup(tn, index);
1363 			return err;
1364 		}
1365 		res = ACT_P_CREATED;
1366 	} else {
1367 		if (bind)
1368 			return 0;
1369 
1370 		if (!(flags & TCA_ACT_FLAGS_REPLACE)) {
1371 			tcf_idr_release(*a, bind);
1372 			return -EEXIST;
1373 		}
1374 	}
1375 	err = tcf_action_check_ctrlact(parm->action, tp, &goto_ch, extack);
1376 	if (err < 0)
1377 		goto cleanup;
1378 
1379 	c = to_ct(*a);
1380 
1381 	params = kzalloc(sizeof(*params), GFP_KERNEL);
1382 	if (unlikely(!params)) {
1383 		err = -ENOMEM;
1384 		goto cleanup;
1385 	}
1386 
1387 	err = tcf_ct_fill_params(net, params, parm, tb, extack);
1388 	if (err)
1389 		goto cleanup;
1390 
1391 	err = tcf_ct_flow_table_get(net, params);
1392 	if (err)
1393 		goto cleanup_params;
1394 
1395 	spin_lock_bh(&c->tcf_lock);
1396 	goto_ch = tcf_action_set_ctrlact(*a, parm->action, goto_ch);
1397 	params = rcu_replace_pointer(c->params, params,
1398 				     lockdep_is_held(&c->tcf_lock));
1399 	spin_unlock_bh(&c->tcf_lock);
1400 
1401 	if (goto_ch)
1402 		tcf_chain_put_by_act(goto_ch);
1403 	if (params)
1404 		call_rcu(&params->rcu, tcf_ct_params_free);
1405 
1406 	return res;
1407 
1408 cleanup_params:
1409 	if (params->tmpl)
1410 		nf_ct_put(params->tmpl);
1411 cleanup:
1412 	if (goto_ch)
1413 		tcf_chain_put_by_act(goto_ch);
1414 	kfree(params);
1415 	tcf_idr_release(*a, bind);
1416 	return err;
1417 }
1418 
1419 static void tcf_ct_cleanup(struct tc_action *a)
1420 {
1421 	struct tcf_ct_params *params;
1422 	struct tcf_ct *c = to_ct(a);
1423 
1424 	params = rcu_dereference_protected(c->params, 1);
1425 	if (params)
1426 		call_rcu(&params->rcu, tcf_ct_params_free);
1427 }
1428 
1429 static int tcf_ct_dump_key_val(struct sk_buff *skb,
1430 			       void *val, int val_type,
1431 			       void *mask, int mask_type,
1432 			       int len)
1433 {
1434 	int err;
1435 
1436 	if (mask && !memchr_inv(mask, 0, len))
1437 		return 0;
1438 
1439 	err = nla_put(skb, val_type, len, val);
1440 	if (err)
1441 		return err;
1442 
1443 	if (mask_type != TCA_CT_UNSPEC) {
1444 		err = nla_put(skb, mask_type, len, mask);
1445 		if (err)
1446 			return err;
1447 	}
1448 
1449 	return 0;
1450 }
1451 
1452 static int tcf_ct_dump_nat(struct sk_buff *skb, struct tcf_ct_params *p)
1453 {
1454 	struct nf_nat_range2 *range = &p->range;
1455 
1456 	if (!(p->ct_action & TCA_CT_ACT_NAT))
1457 		return 0;
1458 
1459 	if (!(p->ct_action & (TCA_CT_ACT_NAT_SRC | TCA_CT_ACT_NAT_DST)))
1460 		return 0;
1461 
1462 	if (range->flags & NF_NAT_RANGE_MAP_IPS) {
1463 		if (p->ipv4_range) {
1464 			if (nla_put_in_addr(skb, TCA_CT_NAT_IPV4_MIN,
1465 					    range->min_addr.ip))
1466 				return -1;
1467 			if (nla_put_in_addr(skb, TCA_CT_NAT_IPV4_MAX,
1468 					    range->max_addr.ip))
1469 				return -1;
1470 		} else {
1471 			if (nla_put_in6_addr(skb, TCA_CT_NAT_IPV6_MIN,
1472 					     &range->min_addr.in6))
1473 				return -1;
1474 			if (nla_put_in6_addr(skb, TCA_CT_NAT_IPV6_MAX,
1475 					     &range->max_addr.in6))
1476 				return -1;
1477 		}
1478 	}
1479 
1480 	if (range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) {
1481 		if (nla_put_be16(skb, TCA_CT_NAT_PORT_MIN,
1482 				 range->min_proto.all))
1483 			return -1;
1484 		if (nla_put_be16(skb, TCA_CT_NAT_PORT_MAX,
1485 				 range->max_proto.all))
1486 			return -1;
1487 	}
1488 
1489 	return 0;
1490 }
1491 
1492 static inline int tcf_ct_dump(struct sk_buff *skb, struct tc_action *a,
1493 			      int bind, int ref)
1494 {
1495 	unsigned char *b = skb_tail_pointer(skb);
1496 	struct tcf_ct *c = to_ct(a);
1497 	struct tcf_ct_params *p;
1498 
1499 	struct tc_ct opt = {
1500 		.index   = c->tcf_index,
1501 		.refcnt  = refcount_read(&c->tcf_refcnt) - ref,
1502 		.bindcnt = atomic_read(&c->tcf_bindcnt) - bind,
1503 	};
1504 	struct tcf_t t;
1505 
1506 	spin_lock_bh(&c->tcf_lock);
1507 	p = rcu_dereference_protected(c->params,
1508 				      lockdep_is_held(&c->tcf_lock));
1509 	opt.action = c->tcf_action;
1510 
1511 	if (tcf_ct_dump_key_val(skb,
1512 				&p->ct_action, TCA_CT_ACTION,
1513 				NULL, TCA_CT_UNSPEC,
1514 				sizeof(p->ct_action)))
1515 		goto nla_put_failure;
1516 
1517 	if (p->ct_action & TCA_CT_ACT_CLEAR)
1518 		goto skip_dump;
1519 
1520 	if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
1521 	    tcf_ct_dump_key_val(skb,
1522 				&p->mark, TCA_CT_MARK,
1523 				&p->mark_mask, TCA_CT_MARK_MASK,
1524 				sizeof(p->mark)))
1525 		goto nla_put_failure;
1526 
1527 	if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1528 	    tcf_ct_dump_key_val(skb,
1529 				p->labels, TCA_CT_LABELS,
1530 				p->labels_mask, TCA_CT_LABELS_MASK,
1531 				sizeof(p->labels)))
1532 		goto nla_put_failure;
1533 
1534 	if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1535 	    tcf_ct_dump_key_val(skb,
1536 				&p->zone, TCA_CT_ZONE,
1537 				NULL, TCA_CT_UNSPEC,
1538 				sizeof(p->zone)))
1539 		goto nla_put_failure;
1540 
1541 	if (tcf_ct_dump_nat(skb, p))
1542 		goto nla_put_failure;
1543 
1544 skip_dump:
1545 	if (nla_put(skb, TCA_CT_PARMS, sizeof(opt), &opt))
1546 		goto nla_put_failure;
1547 
1548 	tcf_tm_dump(&t, &c->tcf_tm);
1549 	if (nla_put_64bit(skb, TCA_CT_TM, sizeof(t), &t, TCA_CT_PAD))
1550 		goto nla_put_failure;
1551 	spin_unlock_bh(&c->tcf_lock);
1552 
1553 	return skb->len;
1554 nla_put_failure:
1555 	spin_unlock_bh(&c->tcf_lock);
1556 	nlmsg_trim(skb, b);
1557 	return -1;
1558 }
1559 
1560 static void tcf_stats_update(struct tc_action *a, u64 bytes, u64 packets,
1561 			     u64 drops, u64 lastuse, bool hw)
1562 {
1563 	struct tcf_ct *c = to_ct(a);
1564 
1565 	tcf_action_update_stats(a, bytes, packets, drops, hw);
1566 	c->tcf_tm.lastuse = max_t(u64, c->tcf_tm.lastuse, lastuse);
1567 }
1568 
1569 static int tcf_ct_offload_act_setup(struct tc_action *act, void *entry_data,
1570 				    u32 *index_inc, bool bind,
1571 				    struct netlink_ext_ack *extack)
1572 {
1573 	if (bind) {
1574 		struct flow_action_entry *entry = entry_data;
1575 
1576 		entry->id = FLOW_ACTION_CT;
1577 		entry->ct.action = tcf_ct_action(act);
1578 		entry->ct.zone = tcf_ct_zone(act);
1579 		entry->ct.flow_table = tcf_ct_ft(act);
1580 		*index_inc = 1;
1581 	} else {
1582 		struct flow_offload_action *fl_action = entry_data;
1583 
1584 		fl_action->id = FLOW_ACTION_CT;
1585 	}
1586 
1587 	return 0;
1588 }
1589 
1590 static struct tc_action_ops act_ct_ops = {
1591 	.kind		=	"ct",
1592 	.id		=	TCA_ID_CT,
1593 	.owner		=	THIS_MODULE,
1594 	.act		=	tcf_ct_act,
1595 	.dump		=	tcf_ct_dump,
1596 	.init		=	tcf_ct_init,
1597 	.cleanup	=	tcf_ct_cleanup,
1598 	.stats_update	=	tcf_stats_update,
1599 	.offload_act_setup =	tcf_ct_offload_act_setup,
1600 	.size		=	sizeof(struct tcf_ct),
1601 };
1602 
1603 static __net_init int ct_init_net(struct net *net)
1604 {
1605 	unsigned int n_bits = sizeof_field(struct tcf_ct_params, labels) * 8;
1606 	struct tc_ct_action_net *tn = net_generic(net, act_ct_ops.net_id);
1607 
1608 	if (nf_connlabels_get(net, n_bits - 1)) {
1609 		tn->labels = false;
1610 		pr_err("act_ct: Failed to set connlabels length");
1611 	} else {
1612 		tn->labels = true;
1613 	}
1614 
1615 	return tc_action_net_init(net, &tn->tn, &act_ct_ops);
1616 }
1617 
1618 static void __net_exit ct_exit_net(struct list_head *net_list)
1619 {
1620 	struct net *net;
1621 
1622 	rtnl_lock();
1623 	list_for_each_entry(net, net_list, exit_list) {
1624 		struct tc_ct_action_net *tn = net_generic(net, act_ct_ops.net_id);
1625 
1626 		if (tn->labels)
1627 			nf_connlabels_put(net);
1628 	}
1629 	rtnl_unlock();
1630 
1631 	tc_action_net_exit(net_list, act_ct_ops.net_id);
1632 }
1633 
1634 static struct pernet_operations ct_net_ops = {
1635 	.init = ct_init_net,
1636 	.exit_batch = ct_exit_net,
1637 	.id   = &act_ct_ops.net_id,
1638 	.size = sizeof(struct tc_ct_action_net),
1639 };
1640 
1641 static int __init ct_init_module(void)
1642 {
1643 	int err;
1644 
1645 	act_ct_wq = alloc_ordered_workqueue("act_ct_workqueue", 0);
1646 	if (!act_ct_wq)
1647 		return -ENOMEM;
1648 
1649 	err = tcf_ct_flow_tables_init();
1650 	if (err)
1651 		goto err_tbl_init;
1652 
1653 	err = tcf_register_action(&act_ct_ops, &ct_net_ops);
1654 	if (err)
1655 		goto err_register;
1656 
1657 	static_branch_inc(&tcf_frag_xmit_count);
1658 
1659 	return 0;
1660 
1661 err_register:
1662 	tcf_ct_flow_tables_uninit();
1663 err_tbl_init:
1664 	destroy_workqueue(act_ct_wq);
1665 	return err;
1666 }
1667 
1668 static void __exit ct_cleanup_module(void)
1669 {
1670 	static_branch_dec(&tcf_frag_xmit_count);
1671 	tcf_unregister_action(&act_ct_ops, &ct_net_ops);
1672 	tcf_ct_flow_tables_uninit();
1673 	destroy_workqueue(act_ct_wq);
1674 }
1675 
1676 module_init(ct_init_module);
1677 module_exit(ct_cleanup_module);
1678 MODULE_AUTHOR("Paul Blakey <paulb@mellanox.com>");
1679 MODULE_AUTHOR("Yossi Kuperman <yossiku@mellanox.com>");
1680 MODULE_AUTHOR("Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>");
1681 MODULE_DESCRIPTION("Connection tracking action");
1682 MODULE_LICENSE("GPL v2");
1683