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