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