xref: /linux/net/core/filter.c (revision ab08863c58b1a96ff8378e373cb3d277cbe65b68)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Linux Socket Filter - Kernel level socket filtering
4  *
5  * Based on the design of the Berkeley Packet Filter. The new
6  * internal format has been designed by PLUMgrid:
7  *
8  *	Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
9  *
10  * Authors:
11  *
12  *	Jay Schulist <jschlst@samba.org>
13  *	Alexei Starovoitov <ast@plumgrid.com>
14  *	Daniel Borkmann <dborkman@redhat.com>
15  *
16  * Andi Kleen - Fix a few bad bugs and races.
17  * Kris Katterjohn - Added many additional checks in bpf_check_classic()
18  */
19 
20 #include <linux/atomic.h>
21 #include <linux/bpf_verifier.h>
22 #include <linux/module.h>
23 #include <linux/types.h>
24 #include <linux/mm.h>
25 #include <linux/fcntl.h>
26 #include <linux/socket.h>
27 #include <linux/sock_diag.h>
28 #include <linux/in.h>
29 #include <linux/inet.h>
30 #include <linux/netdevice.h>
31 #include <linux/if_packet.h>
32 #include <linux/if_arp.h>
33 #include <linux/gfp.h>
34 #include <net/inet_common.h>
35 #include <net/ip.h>
36 #include <net/protocol.h>
37 #include <net/netlink.h>
38 #include <linux/skbuff.h>
39 #include <linux/skmsg.h>
40 #include <net/sock.h>
41 #include <net/flow_dissector.h>
42 #include <linux/errno.h>
43 #include <linux/timer.h>
44 #include <linux/uaccess.h>
45 #include <linux/unaligned.h>
46 #include <linux/filter.h>
47 #include <linux/ratelimit.h>
48 #include <linux/seccomp.h>
49 #include <linux/if_vlan.h>
50 #include <linux/bpf.h>
51 #include <linux/btf.h>
52 #include <net/sch_generic.h>
53 #include <net/cls_cgroup.h>
54 #include <net/dst_metadata.h>
55 #include <net/dst.h>
56 #include <net/sock_reuseport.h>
57 #include <net/busy_poll.h>
58 #include <net/tcp.h>
59 #include <net/gre.h>
60 #include <net/xfrm.h>
61 #include <net/udp.h>
62 #include <linux/bpf_trace.h>
63 #include <net/xdp_sock.h>
64 #include <linux/inetdevice.h>
65 #include <net/inet_hashtables.h>
66 #include <net/inet6_hashtables.h>
67 #include <net/ip_fib.h>
68 #include <net/nexthop.h>
69 #include <net/flow.h>
70 #include <net/arp.h>
71 #include <net/ipv6.h>
72 #include <net/net_namespace.h>
73 #include <linux/seg6_local.h>
74 #include <net/seg6.h>
75 #include <net/seg6_local.h>
76 #include <net/lwtunnel.h>
77 #include <net/bpf_sk_storage.h>
78 #include <net/transp_v6.h>
79 #include <linux/btf_ids.h>
80 #include <net/tls.h>
81 #include <net/xdp.h>
82 #include <net/mptcp.h>
83 #include <net/netfilter/nf_conntrack_bpf.h>
84 #include <net/netkit.h>
85 #include <linux/un.h>
86 #include <net/xdp_sock_drv.h>
87 #include <net/inet_dscp.h>
88 #include <linux/icmpv6.h>
89 #include <net/icmp.h>
90 #include <net/ip6_route.h>
91 
92 #include "dev.h"
93 
94 /* Keep the struct bpf_fib_lookup small so that it fits into a cacheline */
95 static_assert(sizeof(struct bpf_fib_lookup) == 64, "struct bpf_fib_lookup size check");
96 
97 static const struct bpf_func_proto *
98 bpf_sk_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog);
99 
100 int copy_bpf_fprog_from_user(struct sock_fprog *dst, sockptr_t src, int len)
101 {
102 	if (in_compat_syscall()) {
103 		struct compat_sock_fprog f32;
104 
105 		if (len != sizeof(f32))
106 			return -EINVAL;
107 		if (copy_from_sockptr(&f32, src, sizeof(f32)))
108 			return -EFAULT;
109 		memset(dst, 0, sizeof(*dst));
110 		dst->len = f32.len;
111 		dst->filter = compat_ptr(f32.filter);
112 	} else {
113 		if (len != sizeof(*dst))
114 			return -EINVAL;
115 		if (copy_from_sockptr(dst, src, sizeof(*dst)))
116 			return -EFAULT;
117 	}
118 
119 	return 0;
120 }
121 EXPORT_SYMBOL_GPL(copy_bpf_fprog_from_user);
122 
123 /**
124  *	sk_filter_trim_cap - run a packet through a socket filter
125  *	@sk: sock associated with &sk_buff
126  *	@skb: buffer to filter
127  *	@cap: limit on how short the eBPF program may trim the packet
128  *
129  * Run the eBPF program and then cut skb->data to correct size returned by
130  * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
131  * than pkt_len we keep whole skb->data. This is the socket level
132  * wrapper to bpf_prog_run. It returns 0 if the packet should
133  * be accepted or a drop_reason if the packet should be tossed.
134  *
135  */
136 enum skb_drop_reason
137 sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
138 {
139 	enum skb_drop_reason drop_reason;
140 	struct sk_filter *filter;
141 	int err;
142 
143 	/*
144 	 * If the skb was allocated from pfmemalloc reserves, only
145 	 * allow SOCK_MEMALLOC sockets to use it as this socket is
146 	 * helping free memory
147 	 */
148 	if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
149 		NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
150 		return SKB_DROP_REASON_PFMEMALLOC;
151 	}
152 	err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
153 	if (err)
154 		return SKB_DROP_REASON_SOCKET_FILTER;
155 
156 	err = security_sock_rcv_skb(sk, skb);
157 	if (err)
158 		return SKB_DROP_REASON_SECURITY_HOOK;
159 
160 	drop_reason = 0;
161 	rcu_read_lock();
162 	filter = rcu_dereference(sk->sk_filter);
163 	if (filter) {
164 		struct sock *save_sk = skb->sk;
165 		unsigned int pkt_len;
166 
167 		skb->sk = sk;
168 		pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
169 		skb->sk = save_sk;
170 		err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
171 		if (err)
172 			drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
173 	}
174 	rcu_read_unlock();
175 
176 	return drop_reason;
177 }
178 EXPORT_SYMBOL(sk_filter_trim_cap);
179 
180 BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb)
181 {
182 	return skb_get_poff(skb);
183 }
184 
185 BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
186 {
187 	struct nlattr *nla;
188 
189 	if (skb_is_nonlinear(skb))
190 		return 0;
191 
192 	if (skb->len < sizeof(struct nlattr))
193 		return 0;
194 
195 	if (a > skb->len - sizeof(struct nlattr))
196 		return 0;
197 
198 	nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
199 	if (nla)
200 		return (void *) nla - (void *) skb->data;
201 
202 	return 0;
203 }
204 
205 BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
206 {
207 	struct nlattr *nla;
208 
209 	if (skb_is_nonlinear(skb))
210 		return 0;
211 
212 	if (skb->len < sizeof(struct nlattr))
213 		return 0;
214 
215 	if (a > skb->len - sizeof(struct nlattr))
216 		return 0;
217 
218 	nla = (struct nlattr *) &skb->data[a];
219 	if (!nla_ok(nla, skb->len - a))
220 		return 0;
221 
222 	nla = nla_find_nested(nla, x);
223 	if (nla)
224 		return (void *) nla - (void *) skb->data;
225 
226 	return 0;
227 }
228 
229 static int bpf_skb_load_helper_convert_offset(const struct sk_buff *skb, int offset)
230 {
231 	if (likely(offset >= 0))
232 		return offset;
233 
234 	if (offset >= SKF_NET_OFF)
235 		return offset - SKF_NET_OFF + skb_network_offset(skb);
236 
237 	if (offset >= SKF_LL_OFF && skb_mac_header_was_set(skb))
238 		return offset - SKF_LL_OFF + skb_mac_offset(skb);
239 
240 	return INT_MIN;
241 }
242 
243 BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *,
244 	   data, int, headlen, int, offset)
245 {
246 	u8 tmp;
247 	const int len = sizeof(tmp);
248 
249 	offset = bpf_skb_load_helper_convert_offset(skb, offset);
250 	if (offset == INT_MIN)
251 		return -EFAULT;
252 
253 	if (headlen - offset >= len)
254 		return *(u8 *)(data + offset);
255 	if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
256 		return tmp;
257 	else
258 		return -EFAULT;
259 }
260 
261 BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb,
262 	   int, offset)
263 {
264 	return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len,
265 					 offset);
266 }
267 
268 BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *,
269 	   data, int, headlen, int, offset)
270 {
271 	__be16 tmp;
272 	const int len = sizeof(tmp);
273 
274 	offset = bpf_skb_load_helper_convert_offset(skb, offset);
275 	if (offset == INT_MIN)
276 		return -EFAULT;
277 
278 	if (headlen - offset >= len)
279 		return get_unaligned_be16(data + offset);
280 	if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
281 		return be16_to_cpu(tmp);
282 	else
283 		return -EFAULT;
284 }
285 
286 BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb,
287 	   int, offset)
288 {
289 	return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len,
290 					  offset);
291 }
292 
293 BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *,
294 	   data, int, headlen, int, offset)
295 {
296 	__be32 tmp;
297 	const int len = sizeof(tmp);
298 
299 	offset = bpf_skb_load_helper_convert_offset(skb, offset);
300 	if (offset == INT_MIN)
301 		return -EFAULT;
302 
303 	if (headlen - offset >= len)
304 		return get_unaligned_be32(data + offset);
305 	if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
306 		return be32_to_cpu(tmp);
307 	else
308 		return -EFAULT;
309 }
310 
311 BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb,
312 	   int, offset)
313 {
314 	return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len,
315 					  offset);
316 }
317 
318 static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
319 			      struct bpf_insn *insn_buf)
320 {
321 	struct bpf_insn *insn = insn_buf;
322 
323 	switch (skb_field) {
324 	case SKF_AD_MARK:
325 		BUILD_BUG_ON(sizeof_field(struct sk_buff, mark) != 4);
326 
327 		*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
328 				      offsetof(struct sk_buff, mark));
329 		break;
330 
331 	case SKF_AD_PKTTYPE:
332 		*insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET);
333 		*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
334 #ifdef __BIG_ENDIAN_BITFIELD
335 		*insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
336 #endif
337 		break;
338 
339 	case SKF_AD_QUEUE:
340 		BUILD_BUG_ON(sizeof_field(struct sk_buff, queue_mapping) != 2);
341 
342 		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
343 				      offsetof(struct sk_buff, queue_mapping));
344 		break;
345 
346 	case SKF_AD_VLAN_TAG:
347 		BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_tci) != 2);
348 
349 		/* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
350 		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
351 				      offsetof(struct sk_buff, vlan_tci));
352 		break;
353 	case SKF_AD_VLAN_TAG_PRESENT:
354 		BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_all) != 4);
355 		*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
356 				      offsetof(struct sk_buff, vlan_all));
357 		*insn++ = BPF_JMP_IMM(BPF_JEQ, dst_reg, 0, 1);
358 		*insn++ = BPF_ALU32_IMM(BPF_MOV, dst_reg, 1);
359 		break;
360 	}
361 
362 	return insn - insn_buf;
363 }
364 
365 static bool convert_bpf_extensions(struct sock_filter *fp,
366 				   struct bpf_insn **insnp)
367 {
368 	struct bpf_insn *insn = *insnp;
369 	u32 cnt;
370 
371 	switch (fp->k) {
372 	case SKF_AD_OFF + SKF_AD_PROTOCOL:
373 		BUILD_BUG_ON(sizeof_field(struct sk_buff, protocol) != 2);
374 
375 		/* A = *(u16 *) (CTX + offsetof(protocol)) */
376 		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
377 				      offsetof(struct sk_buff, protocol));
378 		/* A = ntohs(A) [emitting a nop or swap16] */
379 		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
380 		break;
381 
382 	case SKF_AD_OFF + SKF_AD_PKTTYPE:
383 		cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
384 		insn += cnt - 1;
385 		break;
386 
387 	case SKF_AD_OFF + SKF_AD_IFINDEX:
388 	case SKF_AD_OFF + SKF_AD_HATYPE:
389 		BUILD_BUG_ON(sizeof_field(struct net_device, ifindex) != 4);
390 		BUILD_BUG_ON(sizeof_field(struct net_device, type) != 2);
391 
392 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
393 				      BPF_REG_TMP, BPF_REG_CTX,
394 				      offsetof(struct sk_buff, dev));
395 		/* if (tmp != 0) goto pc + 1 */
396 		*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
397 		*insn++ = BPF_EXIT_INSN();
398 		if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
399 			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
400 					    offsetof(struct net_device, ifindex));
401 		else
402 			*insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
403 					    offsetof(struct net_device, type));
404 		break;
405 
406 	case SKF_AD_OFF + SKF_AD_MARK:
407 		cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
408 		insn += cnt - 1;
409 		break;
410 
411 	case SKF_AD_OFF + SKF_AD_RXHASH:
412 		BUILD_BUG_ON(sizeof_field(struct sk_buff, hash) != 4);
413 
414 		*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
415 				    offsetof(struct sk_buff, hash));
416 		break;
417 
418 	case SKF_AD_OFF + SKF_AD_QUEUE:
419 		cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
420 		insn += cnt - 1;
421 		break;
422 
423 	case SKF_AD_OFF + SKF_AD_VLAN_TAG:
424 		cnt = convert_skb_access(SKF_AD_VLAN_TAG,
425 					 BPF_REG_A, BPF_REG_CTX, insn);
426 		insn += cnt - 1;
427 		break;
428 
429 	case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
430 		cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
431 					 BPF_REG_A, BPF_REG_CTX, insn);
432 		insn += cnt - 1;
433 		break;
434 
435 	case SKF_AD_OFF + SKF_AD_VLAN_TPID:
436 		BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_proto) != 2);
437 
438 		/* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
439 		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
440 				      offsetof(struct sk_buff, vlan_proto));
441 		/* A = ntohs(A) [emitting a nop or swap16] */
442 		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
443 		break;
444 
445 	case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
446 	case SKF_AD_OFF + SKF_AD_NLATTR:
447 	case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
448 	case SKF_AD_OFF + SKF_AD_CPU:
449 	case SKF_AD_OFF + SKF_AD_RANDOM:
450 		/* arg1 = CTX */
451 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
452 		/* arg2 = A */
453 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
454 		/* arg3 = X */
455 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
456 		/* Emit call(arg1=CTX, arg2=A, arg3=X) */
457 		switch (fp->k) {
458 		case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
459 			*insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset);
460 			break;
461 		case SKF_AD_OFF + SKF_AD_NLATTR:
462 			*insn = BPF_EMIT_CALL(bpf_skb_get_nlattr);
463 			break;
464 		case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
465 			*insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest);
466 			break;
467 		case SKF_AD_OFF + SKF_AD_CPU:
468 			*insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id);
469 			break;
470 		case SKF_AD_OFF + SKF_AD_RANDOM:
471 			*insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
472 			bpf_user_rnd_init_once();
473 			break;
474 		}
475 		break;
476 
477 	case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
478 		/* A ^= X */
479 		*insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
480 		break;
481 
482 	default:
483 		/* This is just a dummy call to avoid letting the compiler
484 		 * evict __bpf_call_base() as an optimization. Placed here
485 		 * where no-one bothers.
486 		 */
487 		BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
488 		return false;
489 	}
490 
491 	*insnp = insn;
492 	return true;
493 }
494 
495 static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp)
496 {
497 	const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS);
498 	int size = bpf_size_to_bytes(BPF_SIZE(fp->code));
499 	bool endian = BPF_SIZE(fp->code) == BPF_H ||
500 		      BPF_SIZE(fp->code) == BPF_W;
501 	bool indirect = BPF_MODE(fp->code) == BPF_IND;
502 	const int ip_align = NET_IP_ALIGN;
503 	struct bpf_insn *insn = *insnp;
504 	int offset = fp->k;
505 
506 	if (!indirect &&
507 	    ((unaligned_ok && offset >= 0) ||
508 	     (!unaligned_ok && offset >= 0 &&
509 	      offset + ip_align >= 0 &&
510 	      (offset + ip_align) % size == 0))) {
511 		bool ldx_off_ok = offset <= S16_MAX;
512 
513 		*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H);
514 		if (offset)
515 			*insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset);
516 		*insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP,
517 				      size, 2 + endian + (!ldx_off_ok * 2));
518 		if (ldx_off_ok) {
519 			*insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
520 					      BPF_REG_D, offset);
521 		} else {
522 			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D);
523 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset);
524 			*insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
525 					      BPF_REG_TMP, 0);
526 		}
527 		if (endian)
528 			*insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8);
529 		*insn++ = BPF_JMP_A(8);
530 	}
531 
532 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
533 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D);
534 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H);
535 	if (!indirect) {
536 		*insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset);
537 	} else {
538 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X);
539 		if (fp->k)
540 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset);
541 	}
542 
543 	switch (BPF_SIZE(fp->code)) {
544 	case BPF_B:
545 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8);
546 		break;
547 	case BPF_H:
548 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16);
549 		break;
550 	case BPF_W:
551 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32);
552 		break;
553 	default:
554 		return false;
555 	}
556 
557 	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2);
558 	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
559 	*insn   = BPF_EXIT_INSN();
560 
561 	*insnp = insn;
562 	return true;
563 }
564 
565 /**
566  *	bpf_convert_filter - convert filter program
567  *	@prog: the user passed filter program
568  *	@len: the length of the user passed filter program
569  *	@new_prog: allocated 'struct bpf_prog' or NULL
570  *	@new_len: pointer to store length of converted program
571  *	@seen_ld_abs: bool whether we've seen ld_abs/ind
572  *
573  * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
574  * style extended BPF (eBPF).
575  * Conversion workflow:
576  *
577  * 1) First pass for calculating the new program length:
578  *   bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs)
579  *
580  * 2) 2nd pass to remap in two passes: 1st pass finds new
581  *    jump offsets, 2nd pass remapping:
582  *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs)
583  */
584 static int bpf_convert_filter(struct sock_filter *prog, int len,
585 			      struct bpf_prog *new_prog, int *new_len,
586 			      bool *seen_ld_abs)
587 {
588 	int new_flen = 0, pass = 0, target, i, stack_off;
589 	struct bpf_insn *new_insn, *first_insn = NULL;
590 	struct sock_filter *fp;
591 	int *addrs = NULL;
592 	u8 bpf_src;
593 
594 	BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
595 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
596 
597 	if (len <= 0 || len > BPF_MAXINSNS)
598 		return -EINVAL;
599 
600 	if (new_prog) {
601 		first_insn = new_prog->insnsi;
602 		addrs = kzalloc_objs(*addrs, len, GFP_KERNEL | __GFP_NOWARN);
603 		if (!addrs)
604 			return -ENOMEM;
605 	}
606 
607 do_pass:
608 	new_insn = first_insn;
609 	fp = prog;
610 
611 	/* Classic BPF related prologue emission. */
612 	if (new_prog) {
613 		/* Classic BPF expects A and X to be reset first. These need
614 		 * to be guaranteed to be the first two instructions.
615 		 */
616 		*new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
617 		*new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
618 
619 		/* All programs must keep CTX in callee saved BPF_REG_CTX.
620 		 * In eBPF case it's done by the compiler, here we need to
621 		 * do this ourself. Initial CTX is present in BPF_REG_ARG1.
622 		 */
623 		*new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
624 		if (*seen_ld_abs) {
625 			/* For packet access in classic BPF, cache skb->data
626 			 * in callee-saved BPF R8 and skb->len - skb->data_len
627 			 * (headlen) in BPF R9. Since classic BPF is read-only
628 			 * on CTX, we only need to cache it once.
629 			 */
630 			*new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
631 						  BPF_REG_D, BPF_REG_CTX,
632 						  offsetof(struct sk_buff, data));
633 			*new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX,
634 						  offsetof(struct sk_buff, len));
635 			*new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX,
636 						  offsetof(struct sk_buff, data_len));
637 			*new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP);
638 		}
639 	} else {
640 		new_insn += 3;
641 	}
642 
643 	for (i = 0; i < len; fp++, i++) {
644 		struct bpf_insn tmp_insns[32] = { };
645 		struct bpf_insn *insn = tmp_insns;
646 
647 		if (addrs)
648 			addrs[i] = new_insn - first_insn;
649 
650 		switch (fp->code) {
651 		/* All arithmetic insns and skb loads map as-is. */
652 		case BPF_ALU | BPF_ADD | BPF_X:
653 		case BPF_ALU | BPF_ADD | BPF_K:
654 		case BPF_ALU | BPF_SUB | BPF_X:
655 		case BPF_ALU | BPF_SUB | BPF_K:
656 		case BPF_ALU | BPF_AND | BPF_X:
657 		case BPF_ALU | BPF_AND | BPF_K:
658 		case BPF_ALU | BPF_OR | BPF_X:
659 		case BPF_ALU | BPF_OR | BPF_K:
660 		case BPF_ALU | BPF_LSH | BPF_X:
661 		case BPF_ALU | BPF_LSH | BPF_K:
662 		case BPF_ALU | BPF_RSH | BPF_X:
663 		case BPF_ALU | BPF_RSH | BPF_K:
664 		case BPF_ALU | BPF_XOR | BPF_X:
665 		case BPF_ALU | BPF_XOR | BPF_K:
666 		case BPF_ALU | BPF_MUL | BPF_X:
667 		case BPF_ALU | BPF_MUL | BPF_K:
668 		case BPF_ALU | BPF_DIV | BPF_X:
669 		case BPF_ALU | BPF_DIV | BPF_K:
670 		case BPF_ALU | BPF_MOD | BPF_X:
671 		case BPF_ALU | BPF_MOD | BPF_K:
672 		case BPF_ALU | BPF_NEG:
673 		case BPF_LD | BPF_ABS | BPF_W:
674 		case BPF_LD | BPF_ABS | BPF_H:
675 		case BPF_LD | BPF_ABS | BPF_B:
676 		case BPF_LD | BPF_IND | BPF_W:
677 		case BPF_LD | BPF_IND | BPF_H:
678 		case BPF_LD | BPF_IND | BPF_B:
679 			/* Check for overloaded BPF extension and
680 			 * directly convert it if found, otherwise
681 			 * just move on with mapping.
682 			 */
683 			if (BPF_CLASS(fp->code) == BPF_LD &&
684 			    BPF_MODE(fp->code) == BPF_ABS &&
685 			    convert_bpf_extensions(fp, &insn))
686 				break;
687 			if (BPF_CLASS(fp->code) == BPF_LD &&
688 			    convert_bpf_ld_abs(fp, &insn)) {
689 				*seen_ld_abs = true;
690 				break;
691 			}
692 
693 			if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) ||
694 			    fp->code == (BPF_ALU | BPF_MOD | BPF_X)) {
695 				*insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X);
696 				/* Error with exception code on div/mod by 0.
697 				 * For cBPF programs, this was always return 0.
698 				 */
699 				*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2);
700 				*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
701 				*insn++ = BPF_EXIT_INSN();
702 			}
703 
704 			*insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
705 			break;
706 
707 		/* Jump transformation cannot use BPF block macros
708 		 * everywhere as offset calculation and target updates
709 		 * require a bit more work than the rest, i.e. jump
710 		 * opcodes map as-is, but offsets need adjustment.
711 		 */
712 
713 #define BPF_EMIT_JMP							\
714 	do {								\
715 		const s32 off_min = S16_MIN, off_max = S16_MAX;		\
716 		s32 off;						\
717 									\
718 		if (target >= len || target < 0)			\
719 			goto err;					\
720 		off = addrs ? addrs[target] - addrs[i] - 1 : 0;		\
721 		/* Adjust pc relative offset for 2nd or 3rd insn. */	\
722 		off -= insn - tmp_insns;				\
723 		/* Reject anything not fitting into insn->off. */	\
724 		if (off < off_min || off > off_max)			\
725 			goto err;					\
726 		insn->off = off;					\
727 	} while (0)
728 
729 		case BPF_JMP | BPF_JA:
730 			target = i + fp->k + 1;
731 			insn->code = fp->code;
732 			BPF_EMIT_JMP;
733 			break;
734 
735 		case BPF_JMP | BPF_JEQ | BPF_K:
736 		case BPF_JMP | BPF_JEQ | BPF_X:
737 		case BPF_JMP | BPF_JSET | BPF_K:
738 		case BPF_JMP | BPF_JSET | BPF_X:
739 		case BPF_JMP | BPF_JGT | BPF_K:
740 		case BPF_JMP | BPF_JGT | BPF_X:
741 		case BPF_JMP | BPF_JGE | BPF_K:
742 		case BPF_JMP | BPF_JGE | BPF_X:
743 			if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
744 				/* BPF immediates are signed, zero extend
745 				 * immediate into tmp register and use it
746 				 * in compare insn.
747 				 */
748 				*insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
749 
750 				insn->dst_reg = BPF_REG_A;
751 				insn->src_reg = BPF_REG_TMP;
752 				bpf_src = BPF_X;
753 			} else {
754 				insn->dst_reg = BPF_REG_A;
755 				insn->imm = fp->k;
756 				bpf_src = BPF_SRC(fp->code);
757 				insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
758 			}
759 
760 			/* Common case where 'jump_false' is next insn. */
761 			if (fp->jf == 0) {
762 				insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
763 				target = i + fp->jt + 1;
764 				BPF_EMIT_JMP;
765 				break;
766 			}
767 
768 			/* Convert some jumps when 'jump_true' is next insn. */
769 			if (fp->jt == 0) {
770 				switch (BPF_OP(fp->code)) {
771 				case BPF_JEQ:
772 					insn->code = BPF_JMP | BPF_JNE | bpf_src;
773 					break;
774 				case BPF_JGT:
775 					insn->code = BPF_JMP | BPF_JLE | bpf_src;
776 					break;
777 				case BPF_JGE:
778 					insn->code = BPF_JMP | BPF_JLT | bpf_src;
779 					break;
780 				default:
781 					goto jmp_rest;
782 				}
783 
784 				target = i + fp->jf + 1;
785 				BPF_EMIT_JMP;
786 				break;
787 			}
788 jmp_rest:
789 			/* Other jumps are mapped into two insns: Jxx and JA. */
790 			target = i + fp->jt + 1;
791 			insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
792 			BPF_EMIT_JMP;
793 			insn++;
794 
795 			insn->code = BPF_JMP | BPF_JA;
796 			target = i + fp->jf + 1;
797 			BPF_EMIT_JMP;
798 			break;
799 
800 		/* ldxb 4 * ([14] & 0xf) is remapped into 6 insns. */
801 		case BPF_LDX | BPF_MSH | BPF_B: {
802 			struct sock_filter tmp = {
803 				.code	= BPF_LD | BPF_ABS | BPF_B,
804 				.k	= fp->k,
805 			};
806 
807 			*seen_ld_abs = true;
808 
809 			/* X = A */
810 			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
811 			/* A = BPF_R0 = *(u8 *) (skb->data + K) */
812 			convert_bpf_ld_abs(&tmp, &insn);
813 			insn++;
814 			/* A &= 0xf */
815 			*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
816 			/* A <<= 2 */
817 			*insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
818 			/* tmp = X */
819 			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X);
820 			/* X = A */
821 			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
822 			/* A = tmp */
823 			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
824 			break;
825 		}
826 		/* RET_K is remapped into 2 insns. RET_A case doesn't need an
827 		 * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
828 		 */
829 		case BPF_RET | BPF_A:
830 		case BPF_RET | BPF_K:
831 			if (BPF_RVAL(fp->code) == BPF_K)
832 				*insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
833 							0, fp->k);
834 			*insn = BPF_EXIT_INSN();
835 			break;
836 
837 		/* Store to stack. */
838 		case BPF_ST:
839 		case BPF_STX:
840 			stack_off = fp->k * 4  + 4;
841 			*insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
842 					    BPF_ST ? BPF_REG_A : BPF_REG_X,
843 					    -stack_off);
844 			/* check_load_and_stores() verifies that classic BPF can
845 			 * load from stack only after write, so tracking
846 			 * stack_depth for ST|STX insns is enough
847 			 */
848 			if (new_prog && new_prog->aux->stack_depth < stack_off)
849 				new_prog->aux->stack_depth = stack_off;
850 			break;
851 
852 		/* Load from stack. */
853 		case BPF_LD | BPF_MEM:
854 		case BPF_LDX | BPF_MEM:
855 			stack_off = fp->k * 4  + 4;
856 			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
857 					    BPF_REG_A : BPF_REG_X, BPF_REG_FP,
858 					    -stack_off);
859 			break;
860 
861 		/* A = K or X = K */
862 		case BPF_LD | BPF_IMM:
863 		case BPF_LDX | BPF_IMM:
864 			*insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
865 					      BPF_REG_A : BPF_REG_X, fp->k);
866 			break;
867 
868 		/* X = A */
869 		case BPF_MISC | BPF_TAX:
870 			*insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
871 			break;
872 
873 		/* A = X */
874 		case BPF_MISC | BPF_TXA:
875 			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
876 			break;
877 
878 		/* A = skb->len or X = skb->len */
879 		case BPF_LD | BPF_W | BPF_LEN:
880 		case BPF_LDX | BPF_W | BPF_LEN:
881 			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
882 					    BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
883 					    offsetof(struct sk_buff, len));
884 			break;
885 
886 		/* Access seccomp_data fields. */
887 		case BPF_LDX | BPF_ABS | BPF_W:
888 			/* A = *(u32 *) (ctx + K) */
889 			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
890 			break;
891 
892 		/* Unknown instruction. */
893 		default:
894 			goto err;
895 		}
896 
897 		insn++;
898 		if (new_prog)
899 			memcpy(new_insn, tmp_insns,
900 			       sizeof(*insn) * (insn - tmp_insns));
901 		new_insn += insn - tmp_insns;
902 	}
903 
904 	if (!new_prog) {
905 		/* Only calculating new length. */
906 		*new_len = new_insn - first_insn;
907 		if (*seen_ld_abs)
908 			*new_len += 4; /* Prologue bits. */
909 		return 0;
910 	}
911 
912 	pass++;
913 	if (new_flen != new_insn - first_insn) {
914 		new_flen = new_insn - first_insn;
915 		if (pass > 2)
916 			goto err;
917 		goto do_pass;
918 	}
919 
920 	kfree(addrs);
921 	BUG_ON(*new_len != new_flen);
922 	return 0;
923 err:
924 	kfree(addrs);
925 	return -EINVAL;
926 }
927 
928 /* Security:
929  *
930  * As we dont want to clear mem[] array for each packet going through
931  * __bpf_prog_run(), we check that filter loaded by user never try to read
932  * a cell if not previously written, and we check all branches to be sure
933  * a malicious user doesn't try to abuse us.
934  */
935 static int check_load_and_stores(const struct sock_filter *filter, int flen)
936 {
937 	u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
938 	int pc, ret = 0;
939 
940 	BUILD_BUG_ON(BPF_MEMWORDS > 16);
941 
942 	masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
943 	if (!masks)
944 		return -ENOMEM;
945 
946 	memset(masks, 0xff, flen * sizeof(*masks));
947 
948 	for (pc = 0; pc < flen; pc++) {
949 		memvalid &= masks[pc];
950 
951 		switch (filter[pc].code) {
952 		case BPF_ST:
953 		case BPF_STX:
954 			memvalid |= (1 << filter[pc].k);
955 			break;
956 		case BPF_LD | BPF_MEM:
957 		case BPF_LDX | BPF_MEM:
958 			if (!(memvalid & (1 << filter[pc].k))) {
959 				ret = -EINVAL;
960 				goto error;
961 			}
962 			break;
963 		case BPF_JMP | BPF_JA:
964 			/* A jump must set masks on target */
965 			masks[pc + 1 + filter[pc].k] &= memvalid;
966 			memvalid = ~0;
967 			break;
968 		case BPF_JMP | BPF_JEQ | BPF_K:
969 		case BPF_JMP | BPF_JEQ | BPF_X:
970 		case BPF_JMP | BPF_JGE | BPF_K:
971 		case BPF_JMP | BPF_JGE | BPF_X:
972 		case BPF_JMP | BPF_JGT | BPF_K:
973 		case BPF_JMP | BPF_JGT | BPF_X:
974 		case BPF_JMP | BPF_JSET | BPF_K:
975 		case BPF_JMP | BPF_JSET | BPF_X:
976 			/* A jump must set masks on targets */
977 			masks[pc + 1 + filter[pc].jt] &= memvalid;
978 			masks[pc + 1 + filter[pc].jf] &= memvalid;
979 			memvalid = ~0;
980 			break;
981 		}
982 	}
983 error:
984 	kfree(masks);
985 	return ret;
986 }
987 
988 static bool chk_code_allowed(u16 code_to_probe)
989 {
990 	static const bool codes[] = {
991 		/* 32 bit ALU operations */
992 		[BPF_ALU | BPF_ADD | BPF_K] = true,
993 		[BPF_ALU | BPF_ADD | BPF_X] = true,
994 		[BPF_ALU | BPF_SUB | BPF_K] = true,
995 		[BPF_ALU | BPF_SUB | BPF_X] = true,
996 		[BPF_ALU | BPF_MUL | BPF_K] = true,
997 		[BPF_ALU | BPF_MUL | BPF_X] = true,
998 		[BPF_ALU | BPF_DIV | BPF_K] = true,
999 		[BPF_ALU | BPF_DIV | BPF_X] = true,
1000 		[BPF_ALU | BPF_MOD | BPF_K] = true,
1001 		[BPF_ALU | BPF_MOD | BPF_X] = true,
1002 		[BPF_ALU | BPF_AND | BPF_K] = true,
1003 		[BPF_ALU | BPF_AND | BPF_X] = true,
1004 		[BPF_ALU | BPF_OR | BPF_K] = true,
1005 		[BPF_ALU | BPF_OR | BPF_X] = true,
1006 		[BPF_ALU | BPF_XOR | BPF_K] = true,
1007 		[BPF_ALU | BPF_XOR | BPF_X] = true,
1008 		[BPF_ALU | BPF_LSH | BPF_K] = true,
1009 		[BPF_ALU | BPF_LSH | BPF_X] = true,
1010 		[BPF_ALU | BPF_RSH | BPF_K] = true,
1011 		[BPF_ALU | BPF_RSH | BPF_X] = true,
1012 		[BPF_ALU | BPF_NEG] = true,
1013 		/* Load instructions */
1014 		[BPF_LD | BPF_W | BPF_ABS] = true,
1015 		[BPF_LD | BPF_H | BPF_ABS] = true,
1016 		[BPF_LD | BPF_B | BPF_ABS] = true,
1017 		[BPF_LD | BPF_W | BPF_LEN] = true,
1018 		[BPF_LD | BPF_W | BPF_IND] = true,
1019 		[BPF_LD | BPF_H | BPF_IND] = true,
1020 		[BPF_LD | BPF_B | BPF_IND] = true,
1021 		[BPF_LD | BPF_IMM] = true,
1022 		[BPF_LD | BPF_MEM] = true,
1023 		[BPF_LDX | BPF_W | BPF_LEN] = true,
1024 		[BPF_LDX | BPF_B | BPF_MSH] = true,
1025 		[BPF_LDX | BPF_IMM] = true,
1026 		[BPF_LDX | BPF_MEM] = true,
1027 		/* Store instructions */
1028 		[BPF_ST] = true,
1029 		[BPF_STX] = true,
1030 		/* Misc instructions */
1031 		[BPF_MISC | BPF_TAX] = true,
1032 		[BPF_MISC | BPF_TXA] = true,
1033 		/* Return instructions */
1034 		[BPF_RET | BPF_K] = true,
1035 		[BPF_RET | BPF_A] = true,
1036 		/* Jump instructions */
1037 		[BPF_JMP | BPF_JA] = true,
1038 		[BPF_JMP | BPF_JEQ | BPF_K] = true,
1039 		[BPF_JMP | BPF_JEQ | BPF_X] = true,
1040 		[BPF_JMP | BPF_JGE | BPF_K] = true,
1041 		[BPF_JMP | BPF_JGE | BPF_X] = true,
1042 		[BPF_JMP | BPF_JGT | BPF_K] = true,
1043 		[BPF_JMP | BPF_JGT | BPF_X] = true,
1044 		[BPF_JMP | BPF_JSET | BPF_K] = true,
1045 		[BPF_JMP | BPF_JSET | BPF_X] = true,
1046 	};
1047 
1048 	if (code_to_probe >= ARRAY_SIZE(codes))
1049 		return false;
1050 
1051 	return codes[code_to_probe];
1052 }
1053 
1054 static bool bpf_check_basics_ok(const struct sock_filter *filter,
1055 				unsigned int flen)
1056 {
1057 	if (filter == NULL)
1058 		return false;
1059 	if (flen == 0 || flen > BPF_MAXINSNS)
1060 		return false;
1061 
1062 	return true;
1063 }
1064 
1065 /**
1066  *	bpf_check_classic - verify socket filter code
1067  *	@filter: filter to verify
1068  *	@flen: length of filter
1069  *
1070  * Check the user's filter code. If we let some ugly
1071  * filter code slip through kaboom! The filter must contain
1072  * no references or jumps that are out of range, no illegal
1073  * instructions, and must end with a RET instruction.
1074  *
1075  * All jumps are forward as they are not signed.
1076  *
1077  * Returns 0 if the rule set is legal or -EINVAL if not.
1078  */
1079 static int bpf_check_classic(const struct sock_filter *filter,
1080 			     unsigned int flen)
1081 {
1082 	bool anc_found;
1083 	int pc;
1084 
1085 	/* Check the filter code now */
1086 	for (pc = 0; pc < flen; pc++) {
1087 		const struct sock_filter *ftest = &filter[pc];
1088 
1089 		/* May we actually operate on this code? */
1090 		if (!chk_code_allowed(ftest->code))
1091 			return -EINVAL;
1092 
1093 		/* Some instructions need special checks */
1094 		switch (ftest->code) {
1095 		case BPF_ALU | BPF_DIV | BPF_K:
1096 		case BPF_ALU | BPF_MOD | BPF_K:
1097 			/* Check for division by zero */
1098 			if (ftest->k == 0)
1099 				return -EINVAL;
1100 			break;
1101 		case BPF_ALU | BPF_LSH | BPF_K:
1102 		case BPF_ALU | BPF_RSH | BPF_K:
1103 			if (ftest->k >= 32)
1104 				return -EINVAL;
1105 			break;
1106 		case BPF_LD | BPF_MEM:
1107 		case BPF_LDX | BPF_MEM:
1108 		case BPF_ST:
1109 		case BPF_STX:
1110 			/* Check for invalid memory addresses */
1111 			if (ftest->k >= BPF_MEMWORDS)
1112 				return -EINVAL;
1113 			break;
1114 		case BPF_JMP | BPF_JA:
1115 			/* Note, the large ftest->k might cause loops.
1116 			 * Compare this with conditional jumps below,
1117 			 * where offsets are limited. --ANK (981016)
1118 			 */
1119 			if (ftest->k >= (unsigned int)(flen - pc - 1))
1120 				return -EINVAL;
1121 			break;
1122 		case BPF_JMP | BPF_JEQ | BPF_K:
1123 		case BPF_JMP | BPF_JEQ | BPF_X:
1124 		case BPF_JMP | BPF_JGE | BPF_K:
1125 		case BPF_JMP | BPF_JGE | BPF_X:
1126 		case BPF_JMP | BPF_JGT | BPF_K:
1127 		case BPF_JMP | BPF_JGT | BPF_X:
1128 		case BPF_JMP | BPF_JSET | BPF_K:
1129 		case BPF_JMP | BPF_JSET | BPF_X:
1130 			/* Both conditionals must be safe */
1131 			if (pc + ftest->jt + 1 >= flen ||
1132 			    pc + ftest->jf + 1 >= flen)
1133 				return -EINVAL;
1134 			break;
1135 		case BPF_LD | BPF_W | BPF_ABS:
1136 		case BPF_LD | BPF_H | BPF_ABS:
1137 		case BPF_LD | BPF_B | BPF_ABS:
1138 			anc_found = false;
1139 			if (bpf_anc_helper(ftest) & BPF_ANC)
1140 				anc_found = true;
1141 			/* Ancillary operation unknown or unsupported */
1142 			if (anc_found == false && ftest->k >= SKF_AD_OFF)
1143 				return -EINVAL;
1144 		}
1145 	}
1146 
1147 	/* Last instruction must be a RET code */
1148 	switch (filter[flen - 1].code) {
1149 	case BPF_RET | BPF_K:
1150 	case BPF_RET | BPF_A:
1151 		return check_load_and_stores(filter, flen);
1152 	}
1153 
1154 	return -EINVAL;
1155 }
1156 
1157 static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
1158 				      const struct sock_fprog *fprog)
1159 {
1160 	unsigned int fsize = bpf_classic_proglen(fprog);
1161 	struct sock_fprog_kern *fkprog;
1162 
1163 	fp->orig_prog = kmalloc_obj(*fkprog);
1164 	if (!fp->orig_prog)
1165 		return -ENOMEM;
1166 
1167 	fkprog = fp->orig_prog;
1168 	fkprog->len = fprog->len;
1169 
1170 	fkprog->filter = kmemdup(fp->insns, fsize,
1171 				 GFP_KERNEL | __GFP_NOWARN);
1172 	if (!fkprog->filter) {
1173 		kfree(fp->orig_prog);
1174 		return -ENOMEM;
1175 	}
1176 
1177 	return 0;
1178 }
1179 
1180 static void bpf_release_orig_filter(struct bpf_prog *fp)
1181 {
1182 	struct sock_fprog_kern *fprog = fp->orig_prog;
1183 
1184 	if (fprog) {
1185 		kfree(fprog->filter);
1186 		kfree(fprog);
1187 	}
1188 }
1189 
1190 static void __bpf_prog_release(struct bpf_prog *prog)
1191 {
1192 	if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
1193 		bpf_prog_put(prog);
1194 	} else {
1195 		bpf_release_orig_filter(prog);
1196 		bpf_prog_free(prog);
1197 	}
1198 }
1199 
1200 static void __sk_filter_release(struct sk_filter *fp)
1201 {
1202 	__bpf_prog_release(fp->prog);
1203 	kfree(fp);
1204 }
1205 
1206 /**
1207  * 	sk_filter_release_rcu - Release a socket filter by rcu_head
1208  *	@rcu: rcu_head that contains the sk_filter to free
1209  */
1210 static void sk_filter_release_rcu(struct rcu_head *rcu)
1211 {
1212 	struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
1213 
1214 	__sk_filter_release(fp);
1215 }
1216 
1217 /**
1218  *	sk_filter_release - release a socket filter
1219  *	@fp: filter to remove
1220  *
1221  *	Remove a filter from a socket and release its resources.
1222  */
1223 static void sk_filter_release(struct sk_filter *fp)
1224 {
1225 	if (refcount_dec_and_test(&fp->refcnt))
1226 		call_rcu(&fp->rcu, sk_filter_release_rcu);
1227 }
1228 
1229 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
1230 {
1231 	u32 filter_size = bpf_prog_size(fp->prog->len);
1232 
1233 	atomic_sub(filter_size, &sk->sk_omem_alloc);
1234 	sk_filter_release(fp);
1235 }
1236 
1237 /* try to charge the socket memory if there is space available
1238  * return true on success
1239  */
1240 static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1241 {
1242 	int optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
1243 	u32 filter_size = bpf_prog_size(fp->prog->len);
1244 
1245 	/* same check as in sock_kmalloc() */
1246 	if (filter_size <= optmem_max &&
1247 	    atomic_read(&sk->sk_omem_alloc) + filter_size < optmem_max) {
1248 		atomic_add(filter_size, &sk->sk_omem_alloc);
1249 		return true;
1250 	}
1251 	return false;
1252 }
1253 
1254 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1255 {
1256 	if (!refcount_inc_not_zero(&fp->refcnt))
1257 		return false;
1258 
1259 	if (!__sk_filter_charge(sk, fp)) {
1260 		sk_filter_release(fp);
1261 		return false;
1262 	}
1263 	return true;
1264 }
1265 
1266 static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
1267 {
1268 	struct sock_filter *old_prog;
1269 	struct bpf_prog *old_fp;
1270 	int err, new_len, old_len = fp->len;
1271 	bool seen_ld_abs = false;
1272 
1273 	/* We are free to overwrite insns et al right here as it won't be used at
1274 	 * this point in time anymore internally after the migration to the eBPF
1275 	 * instruction representation.
1276 	 */
1277 	BUILD_BUG_ON(sizeof(struct sock_filter) !=
1278 		     sizeof(struct bpf_insn));
1279 
1280 	/* Conversion cannot happen on overlapping memory areas,
1281 	 * so we need to keep the user BPF around until the 2nd
1282 	 * pass. At this time, the user BPF is stored in fp->insns.
1283 	 */
1284 	old_prog = kmemdup_array(fp->insns, old_len, sizeof(struct sock_filter),
1285 				 GFP_KERNEL | __GFP_NOWARN);
1286 	if (!old_prog) {
1287 		err = -ENOMEM;
1288 		goto out_err;
1289 	}
1290 
1291 	/* 1st pass: calculate the new program length. */
1292 	err = bpf_convert_filter(old_prog, old_len, NULL, &new_len,
1293 				 &seen_ld_abs);
1294 	if (err)
1295 		goto out_err_free;
1296 
1297 	/* Expand fp for appending the new filter representation. */
1298 	old_fp = fp;
1299 	fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1300 	if (!fp) {
1301 		/* The old_fp is still around in case we couldn't
1302 		 * allocate new memory, so uncharge on that one.
1303 		 */
1304 		fp = old_fp;
1305 		err = -ENOMEM;
1306 		goto out_err_free;
1307 	}
1308 
1309 	fp->len = new_len;
1310 
1311 	/* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1312 	err = bpf_convert_filter(old_prog, old_len, fp, &new_len,
1313 				 &seen_ld_abs);
1314 	if (err)
1315 		/* 2nd bpf_convert_filter() can fail only if it fails
1316 		 * to allocate memory, remapping must succeed. Note,
1317 		 * that at this time old_fp has already been released
1318 		 * by krealloc().
1319 		 */
1320 		goto out_err_free;
1321 
1322 	fp = bpf_prog_select_runtime(fp, &err);
1323 	if (err)
1324 		goto out_err_free;
1325 
1326 	kfree(old_prog);
1327 	return fp;
1328 
1329 out_err_free:
1330 	kfree(old_prog);
1331 out_err:
1332 	__bpf_prog_release(fp);
1333 	return ERR_PTR(err);
1334 }
1335 
1336 static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1337 					   bpf_aux_classic_check_t trans)
1338 {
1339 	int err;
1340 
1341 	fp->bpf_func = NULL;
1342 	fp->jited = 0;
1343 
1344 	err = bpf_check_classic(fp->insns, fp->len);
1345 	if (err) {
1346 		__bpf_prog_release(fp);
1347 		return ERR_PTR(err);
1348 	}
1349 
1350 	/* There might be additional checks and transformations
1351 	 * needed on classic filters, f.e. in case of seccomp.
1352 	 */
1353 	if (trans) {
1354 		err = trans(fp->insns, fp->len);
1355 		if (err) {
1356 			__bpf_prog_release(fp);
1357 			return ERR_PTR(err);
1358 		}
1359 	}
1360 
1361 	/* Probe if we can JIT compile the filter and if so, do
1362 	 * the compilation of the filter.
1363 	 */
1364 	bpf_jit_compile(fp);
1365 
1366 	/* JIT compiler couldn't process this filter, so do the eBPF translation
1367 	 * for the optimized interpreter.
1368 	 */
1369 	if (!fp->jited)
1370 		fp = bpf_migrate_filter(fp);
1371 
1372 	return fp;
1373 }
1374 
1375 /**
1376  *	bpf_prog_create - create an unattached filter
1377  *	@pfp: the unattached filter that is created
1378  *	@fprog: the filter program
1379  *
1380  * Create a filter independent of any socket. We first run some
1381  * sanity checks on it to make sure it does not explode on us later.
1382  * If an error occurs or there is insufficient memory for the filter
1383  * a negative errno code is returned. On success the return is zero.
1384  */
1385 int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1386 {
1387 	unsigned int fsize = bpf_classic_proglen(fprog);
1388 	struct bpf_prog *fp;
1389 
1390 	/* Make sure new filter is there and in the right amounts. */
1391 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1392 		return -EINVAL;
1393 
1394 	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1395 	if (!fp)
1396 		return -ENOMEM;
1397 
1398 	memcpy(fp->insns, fprog->filter, fsize);
1399 
1400 	fp->len = fprog->len;
1401 	/* Since unattached filters are not copied back to user
1402 	 * space through sk_get_filter(), we do not need to hold
1403 	 * a copy here, and can spare us the work.
1404 	 */
1405 	fp->orig_prog = NULL;
1406 
1407 	/* bpf_prepare_filter() already takes care of freeing
1408 	 * memory in case something goes wrong.
1409 	 */
1410 	fp = bpf_prepare_filter(fp, NULL);
1411 	if (IS_ERR(fp))
1412 		return PTR_ERR(fp);
1413 
1414 	*pfp = fp;
1415 	return 0;
1416 }
1417 EXPORT_SYMBOL_GPL(bpf_prog_create);
1418 
1419 /**
1420  *	bpf_prog_create_from_user - create an unattached filter from user buffer
1421  *	@pfp: the unattached filter that is created
1422  *	@fprog: the filter program
1423  *	@trans: post-classic verifier transformation handler
1424  *	@save_orig: save classic BPF program
1425  *
1426  * This function effectively does the same as bpf_prog_create(), only
1427  * that it builds up its insns buffer from user space provided buffer.
1428  * It also allows for passing a bpf_aux_classic_check_t handler.
1429  */
1430 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1431 			      bpf_aux_classic_check_t trans, bool save_orig)
1432 {
1433 	unsigned int fsize = bpf_classic_proglen(fprog);
1434 	struct bpf_prog *fp;
1435 	int err;
1436 
1437 	/* Make sure new filter is there and in the right amounts. */
1438 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1439 		return -EINVAL;
1440 
1441 	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1442 	if (!fp)
1443 		return -ENOMEM;
1444 
1445 	if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1446 		__bpf_prog_free(fp);
1447 		return -EFAULT;
1448 	}
1449 
1450 	fp->len = fprog->len;
1451 	fp->orig_prog = NULL;
1452 
1453 	if (save_orig) {
1454 		err = bpf_prog_store_orig_filter(fp, fprog);
1455 		if (err) {
1456 			__bpf_prog_free(fp);
1457 			return -ENOMEM;
1458 		}
1459 	}
1460 
1461 	/* bpf_prepare_filter() already takes care of freeing
1462 	 * memory in case something goes wrong.
1463 	 */
1464 	fp = bpf_prepare_filter(fp, trans);
1465 	if (IS_ERR(fp))
1466 		return PTR_ERR(fp);
1467 
1468 	*pfp = fp;
1469 	return 0;
1470 }
1471 EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1472 
1473 void bpf_prog_destroy(struct bpf_prog *fp)
1474 {
1475 	__bpf_prog_release(fp);
1476 }
1477 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1478 
1479 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1480 {
1481 	struct sk_filter *fp, *old_fp;
1482 
1483 	fp = kmalloc_obj(*fp);
1484 	if (!fp)
1485 		return -ENOMEM;
1486 
1487 	fp->prog = prog;
1488 
1489 	if (!__sk_filter_charge(sk, fp)) {
1490 		kfree(fp);
1491 		return -ENOMEM;
1492 	}
1493 	refcount_set(&fp->refcnt, 1);
1494 
1495 	old_fp = rcu_dereference_protected(sk->sk_filter,
1496 					   lockdep_sock_is_held(sk));
1497 	rcu_assign_pointer(sk->sk_filter, fp);
1498 
1499 	if (old_fp)
1500 		sk_filter_uncharge(sk, old_fp);
1501 
1502 	return 0;
1503 }
1504 
1505 static
1506 struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1507 {
1508 	unsigned int fsize = bpf_classic_proglen(fprog);
1509 	struct bpf_prog *prog;
1510 	int err;
1511 
1512 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1513 		return ERR_PTR(-EPERM);
1514 
1515 	/* Make sure new filter is there and in the right amounts. */
1516 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1517 		return ERR_PTR(-EINVAL);
1518 
1519 	prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1520 	if (!prog)
1521 		return ERR_PTR(-ENOMEM);
1522 
1523 	if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1524 		__bpf_prog_free(prog);
1525 		return ERR_PTR(-EFAULT);
1526 	}
1527 
1528 	prog->len = fprog->len;
1529 
1530 	err = bpf_prog_store_orig_filter(prog, fprog);
1531 	if (err) {
1532 		__bpf_prog_free(prog);
1533 		return ERR_PTR(-ENOMEM);
1534 	}
1535 
1536 	/* bpf_prepare_filter() already takes care of freeing
1537 	 * memory in case something goes wrong.
1538 	 */
1539 	return bpf_prepare_filter(prog, NULL);
1540 }
1541 
1542 /**
1543  *	sk_attach_filter - attach a socket filter
1544  *	@fprog: the filter program
1545  *	@sk: the socket to use
1546  *
1547  * Attach the user's filter code. We first run some sanity checks on
1548  * it to make sure it does not explode on us later. If an error
1549  * occurs or there is insufficient memory for the filter a negative
1550  * errno code is returned. On success the return is zero.
1551  */
1552 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1553 {
1554 	struct bpf_prog *prog = __get_filter(fprog, sk);
1555 	int err;
1556 
1557 	if (IS_ERR(prog))
1558 		return PTR_ERR(prog);
1559 
1560 	err = __sk_attach_prog(prog, sk);
1561 	if (err < 0) {
1562 		__bpf_prog_release(prog);
1563 		return err;
1564 	}
1565 
1566 	return 0;
1567 }
1568 EXPORT_SYMBOL_GPL(sk_attach_filter);
1569 
1570 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1571 {
1572 	struct bpf_prog *prog = __get_filter(fprog, sk);
1573 	int err, optmem_max;
1574 
1575 	if (IS_ERR(prog))
1576 		return PTR_ERR(prog);
1577 
1578 	optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
1579 	if (bpf_prog_size(prog->len) > optmem_max)
1580 		err = -ENOMEM;
1581 	else
1582 		err = reuseport_attach_prog(sk, prog);
1583 
1584 	if (err)
1585 		__bpf_prog_release(prog);
1586 
1587 	return err;
1588 }
1589 
1590 static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1591 {
1592 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1593 		return ERR_PTR(-EPERM);
1594 
1595 	return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1596 }
1597 
1598 int sk_attach_bpf(u32 ufd, struct sock *sk)
1599 {
1600 	struct bpf_prog *prog = __get_bpf(ufd, sk);
1601 	int err;
1602 
1603 	if (IS_ERR(prog))
1604 		return PTR_ERR(prog);
1605 
1606 	err = __sk_attach_prog(prog, sk);
1607 	if (err < 0) {
1608 		bpf_prog_put(prog);
1609 		return err;
1610 	}
1611 
1612 	return 0;
1613 }
1614 
1615 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1616 {
1617 	struct bpf_prog *prog;
1618 	int err, optmem_max;
1619 
1620 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1621 		return -EPERM;
1622 
1623 	prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1624 	if (PTR_ERR(prog) == -EINVAL)
1625 		prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT);
1626 	if (IS_ERR(prog))
1627 		return PTR_ERR(prog);
1628 
1629 	if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) {
1630 		/* Like other non BPF_PROG_TYPE_SOCKET_FILTER
1631 		 * bpf prog (e.g. sockmap).  It depends on the
1632 		 * limitation imposed by bpf_prog_load().
1633 		 * Hence, sysctl_optmem_max is not checked.
1634 		 */
1635 		if ((sk->sk_type != SOCK_STREAM &&
1636 		     sk->sk_type != SOCK_DGRAM) ||
1637 		    (sk->sk_protocol != IPPROTO_UDP &&
1638 		     sk->sk_protocol != IPPROTO_TCP) ||
1639 		    (sk->sk_family != AF_INET &&
1640 		     sk->sk_family != AF_INET6)) {
1641 			err = -ENOTSUPP;
1642 			goto err_prog_put;
1643 		}
1644 	} else {
1645 		/* BPF_PROG_TYPE_SOCKET_FILTER */
1646 		optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
1647 		if (bpf_prog_size(prog->len) > optmem_max) {
1648 			err = -ENOMEM;
1649 			goto err_prog_put;
1650 		}
1651 	}
1652 
1653 	err = reuseport_attach_prog(sk, prog);
1654 err_prog_put:
1655 	if (err)
1656 		bpf_prog_put(prog);
1657 
1658 	return err;
1659 }
1660 
1661 static void sk_reuseport_prog_free_rcu(struct rcu_head *rcu)
1662 {
1663 	struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
1664 	struct bpf_prog *prog = aux->prog;
1665 
1666 	bpf_release_orig_filter(prog);
1667 	bpf_prog_free(prog);
1668 }
1669 
1670 void sk_reuseport_prog_free(struct bpf_prog *prog)
1671 {
1672 	if (!prog)
1673 		return;
1674 
1675 	if (bpf_prog_was_classic(prog))
1676 		call_rcu(&prog->aux->rcu, sk_reuseport_prog_free_rcu);
1677 	else
1678 		bpf_prog_put(prog);
1679 }
1680 
1681 static inline int __bpf_try_make_writable(struct sk_buff *skb,
1682 					  unsigned int write_len)
1683 {
1684 #ifdef CONFIG_DEBUG_NET
1685 	/* Avoid a splat in pskb_may_pull_reason() */
1686 	if (write_len > INT_MAX)
1687 		return -EINVAL;
1688 #endif
1689 	return skb_ensure_writable(skb, write_len);
1690 }
1691 
1692 static inline int bpf_try_make_writable(struct sk_buff *skb,
1693 					unsigned int write_len)
1694 {
1695 	int err = __bpf_try_make_writable(skb, write_len);
1696 
1697 	bpf_compute_data_pointers(skb);
1698 	return err;
1699 }
1700 
1701 static int bpf_try_make_head_writable(struct sk_buff *skb)
1702 {
1703 	return bpf_try_make_writable(skb, skb_headlen(skb));
1704 }
1705 
1706 static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1707 {
1708 	if (skb_at_tc_ingress(skb))
1709 		skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1710 }
1711 
1712 static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1713 {
1714 	if (skb_at_tc_ingress(skb))
1715 		skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1716 }
1717 
1718 /*
1719  * The source of a write through a dynptr may be a slice of the same skb.
1720  * Making the skb writable can move its head: follow the move.
1721  */
1722 static int bpf_try_make_writable_from(struct sk_buff *skb, u32 write_len,
1723 				      const void **from)
1724 {
1725 	const void *head = skb->head;
1726 	bool in_head = *from >= head &&
1727 		       *from < (const void *)skb_end_pointer(skb);
1728 	int err;
1729 
1730 	err = bpf_try_make_writable(skb, write_len);
1731 	if (!err && in_head)
1732 		*from = skb->head + (*from - head);
1733 	return err;
1734 }
1735 
1736 BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1737 	   const void *, from, u32, len, u64, flags)
1738 {
1739 	void *ptr;
1740 
1741 	if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1742 		return -EINVAL;
1743 	if (unlikely(offset > INT_MAX))
1744 		return -EFAULT;
1745 	if (unlikely(bpf_try_make_writable_from(skb, offset + len, &from)))
1746 		return -EFAULT;
1747 
1748 	ptr = skb->data + offset;
1749 	if (flags & BPF_F_RECOMPUTE_CSUM)
1750 		__skb_postpull_rcsum(skb, ptr, len, offset);
1751 
1752 	/* through a dynptr the source may be an overlapping slice of the skb */
1753 	memmove(ptr, from, len);
1754 
1755 	if (flags & BPF_F_RECOMPUTE_CSUM)
1756 		__skb_postpush_rcsum(skb, ptr, len, offset);
1757 	if (flags & BPF_F_INVALIDATE_HASH)
1758 		skb_clear_hash(skb);
1759 
1760 	return 0;
1761 }
1762 
1763 static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1764 	.func		= bpf_skb_store_bytes,
1765 	.gpl_only	= false,
1766 	.ret_type	= RET_INTEGER,
1767 	.arg1_type	= ARG_PTR_TO_CTX,
1768 	.arg2_type	= ARG_ANYTHING,
1769 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1770 	.arg4_type	= ARG_MEM_SIZE,
1771 	.arg5_type	= ARG_ANYTHING,
1772 };
1773 
1774 int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from,
1775 			  u32 len, u64 flags)
1776 {
1777 	return ____bpf_skb_store_bytes(skb, offset, from, len, flags);
1778 }
1779 
1780 BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1781 	   void *, to, u32, len)
1782 {
1783 	void *ptr;
1784 
1785 	if (unlikely(offset > INT_MAX))
1786 		goto err_clear;
1787 
1788 	ptr = skb_header_pointer(skb, offset, len, to);
1789 	if (unlikely(!ptr))
1790 		goto err_clear;
1791 	if (ptr != to)
1792 		memcpy(to, ptr, len);
1793 
1794 	return 0;
1795 err_clear:
1796 	memset(to, 0, len);
1797 	return -EFAULT;
1798 }
1799 
1800 static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1801 	.func		= bpf_skb_load_bytes,
1802 	.gpl_only	= false,
1803 	.ret_type	= RET_INTEGER,
1804 	.arg1_type	= ARG_PTR_TO_CTX,
1805 	.arg2_type	= ARG_ANYTHING,
1806 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1807 	.arg4_type	= ARG_MEM_SIZE,
1808 };
1809 
1810 int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset, void *to, u32 len)
1811 {
1812 	return ____bpf_skb_load_bytes(skb, offset, to, len);
1813 }
1814 
1815 BPF_CALL_4(bpf_flow_dissector_load_bytes,
1816 	   const struct bpf_flow_dissector *, ctx, u32, offset,
1817 	   void *, to, u32, len)
1818 {
1819 	void *ptr;
1820 
1821 	if (unlikely(offset > 0xffff))
1822 		goto err_clear;
1823 
1824 	if (unlikely(!ctx->skb))
1825 		goto err_clear;
1826 
1827 	ptr = skb_header_pointer(ctx->skb, offset, len, to);
1828 	if (unlikely(!ptr))
1829 		goto err_clear;
1830 	if (ptr != to)
1831 		memcpy(to, ptr, len);
1832 
1833 	return 0;
1834 err_clear:
1835 	memset(to, 0, len);
1836 	return -EFAULT;
1837 }
1838 
1839 static const struct bpf_func_proto bpf_flow_dissector_load_bytes_proto = {
1840 	.func		= bpf_flow_dissector_load_bytes,
1841 	.gpl_only	= false,
1842 	.ret_type	= RET_INTEGER,
1843 	.arg1_type	= ARG_PTR_TO_CTX,
1844 	.arg2_type	= ARG_ANYTHING,
1845 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1846 	.arg4_type	= ARG_MEM_SIZE,
1847 };
1848 
1849 BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
1850 	   u32, offset, void *, to, u32, len, u32, start_header)
1851 {
1852 	u8 *end = skb_tail_pointer(skb);
1853 	u8 *start, *ptr;
1854 
1855 	if (unlikely(offset > 0xffff))
1856 		goto err_clear;
1857 
1858 	switch (start_header) {
1859 	case BPF_HDR_START_MAC:
1860 		if (unlikely(!skb_mac_header_was_set(skb)))
1861 			goto err_clear;
1862 		start = skb_mac_header(skb);
1863 		break;
1864 	case BPF_HDR_START_NET:
1865 		start = skb_network_header(skb);
1866 		break;
1867 	default:
1868 		goto err_clear;
1869 	}
1870 
1871 	ptr = start + offset;
1872 
1873 	if (likely(ptr + len <= end)) {
1874 		memcpy(to, ptr, len);
1875 		return 0;
1876 	}
1877 
1878 err_clear:
1879 	memset(to, 0, len);
1880 	return -EFAULT;
1881 }
1882 
1883 static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = {
1884 	.func		= bpf_skb_load_bytes_relative,
1885 	.gpl_only	= false,
1886 	.ret_type	= RET_INTEGER,
1887 	.arg1_type	= ARG_PTR_TO_CTX,
1888 	.arg2_type	= ARG_ANYTHING,
1889 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1890 	.arg4_type	= ARG_MEM_SIZE,
1891 	.arg5_type	= ARG_ANYTHING,
1892 };
1893 
1894 BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
1895 {
1896 	/* Idea is the following: should the needed direct read/write
1897 	 * test fail during runtime, we can pull in more data and redo
1898 	 * again, since implicitly, we invalidate previous checks here.
1899 	 *
1900 	 * Or, since we know how much we need to make read/writeable,
1901 	 * this can be done once at the program beginning for direct
1902 	 * access case. By this we overcome limitations of only current
1903 	 * headroom being accessible.
1904 	 */
1905 	return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
1906 }
1907 
1908 static const struct bpf_func_proto bpf_skb_pull_data_proto = {
1909 	.func		= bpf_skb_pull_data,
1910 	.gpl_only	= false,
1911 	.ret_type	= RET_INTEGER,
1912 	.arg1_type	= ARG_PTR_TO_CTX,
1913 	.arg2_type	= ARG_ANYTHING,
1914 };
1915 
1916 BPF_CALL_1(bpf_sk_fullsock, struct sock *, sk)
1917 {
1918 	return sk_fullsock(sk) ? (unsigned long)sk : (unsigned long)NULL;
1919 }
1920 
1921 static const struct bpf_func_proto bpf_sk_fullsock_proto = {
1922 	.func		= bpf_sk_fullsock,
1923 	.gpl_only	= false,
1924 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
1925 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
1926 };
1927 
1928 static inline int sk_skb_try_make_writable(struct sk_buff *skb,
1929 					   unsigned int write_len)
1930 {
1931 	return __bpf_try_make_writable(skb, write_len);
1932 }
1933 
1934 BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len)
1935 {
1936 	/* Idea is the following: should the needed direct read/write
1937 	 * test fail during runtime, we can pull in more data and redo
1938 	 * again, since implicitly, we invalidate previous checks here.
1939 	 *
1940 	 * Or, since we know how much we need to make read/writeable,
1941 	 * this can be done once at the program beginning for direct
1942 	 * access case. By this we overcome limitations of only current
1943 	 * headroom being accessible.
1944 	 */
1945 	return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb));
1946 }
1947 
1948 static const struct bpf_func_proto sk_skb_pull_data_proto = {
1949 	.func		= sk_skb_pull_data,
1950 	.gpl_only	= false,
1951 	.ret_type	= RET_INTEGER,
1952 	.arg1_type	= ARG_PTR_TO_CTX,
1953 	.arg2_type	= ARG_ANYTHING,
1954 };
1955 
1956 BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1957 	   u64, from, u64, to, u64, flags)
1958 {
1959 	__sum16 *ptr;
1960 
1961 	if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1962 		return -EINVAL;
1963 	if (unlikely(offset > 0xffff || offset & 1))
1964 		return -EFAULT;
1965 	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1966 		return -EFAULT;
1967 
1968 	ptr = (__sum16 *)(skb->data + offset);
1969 	switch (flags & BPF_F_HDR_FIELD_MASK) {
1970 	case 0:
1971 		if (unlikely(from != 0))
1972 			return -EINVAL;
1973 
1974 		csum_replace_by_diff(ptr, to);
1975 		break;
1976 	case 2:
1977 		csum_replace2(ptr, from, to);
1978 		break;
1979 	case 4:
1980 		csum_replace4(ptr, from, to);
1981 		break;
1982 	default:
1983 		return -EINVAL;
1984 	}
1985 
1986 	return 0;
1987 }
1988 
1989 static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1990 	.func		= bpf_l3_csum_replace,
1991 	.gpl_only	= false,
1992 	.ret_type	= RET_INTEGER,
1993 	.arg1_type	= ARG_PTR_TO_CTX,
1994 	.arg2_type	= ARG_ANYTHING,
1995 	.arg3_type	= ARG_ANYTHING,
1996 	.arg4_type	= ARG_ANYTHING,
1997 	.arg5_type	= ARG_ANYTHING,
1998 };
1999 
2000 BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
2001 	   u64, from, u64, to, u64, flags)
2002 {
2003 	bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
2004 	bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
2005 	bool do_mforce = flags & BPF_F_MARK_ENFORCE;
2006 	bool is_ipv6   = flags & BPF_F_IPV6;
2007 	__sum16 *ptr;
2008 
2009 	if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
2010 			       BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK | BPF_F_IPV6)))
2011 		return -EINVAL;
2012 	if (unlikely(offset > 0xffff || offset & 1))
2013 		return -EFAULT;
2014 	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
2015 		return -EFAULT;
2016 
2017 	ptr = (__sum16 *)(skb->data + offset);
2018 	if (is_mmzero && !do_mforce && !*ptr)
2019 		return 0;
2020 
2021 	switch (flags & BPF_F_HDR_FIELD_MASK) {
2022 	case 0:
2023 		if (unlikely(from != 0))
2024 			return -EINVAL;
2025 
2026 		inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo, is_ipv6);
2027 		break;
2028 	case 2:
2029 		inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
2030 		break;
2031 	case 4:
2032 		inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
2033 		break;
2034 	default:
2035 		return -EINVAL;
2036 	}
2037 
2038 	if (is_mmzero && !*ptr)
2039 		*ptr = CSUM_MANGLED_0;
2040 	return 0;
2041 }
2042 
2043 static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
2044 	.func		= bpf_l4_csum_replace,
2045 	.gpl_only	= false,
2046 	.ret_type	= RET_INTEGER,
2047 	.arg1_type	= ARG_PTR_TO_CTX,
2048 	.arg2_type	= ARG_ANYTHING,
2049 	.arg3_type	= ARG_ANYTHING,
2050 	.arg4_type	= ARG_ANYTHING,
2051 	.arg5_type	= ARG_ANYTHING,
2052 };
2053 
2054 BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
2055 	   __be32 *, to, u32, to_size, __wsum, seed)
2056 {
2057 	/* This is quite flexible, some examples:
2058 	 *
2059 	 * from_size == 0, to_size > 0,  seed := csum --> pushing data
2060 	 * from_size > 0,  to_size == 0, seed := csum --> pulling data
2061 	 * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
2062 	 *
2063 	 * Even for diffing, from_size and to_size don't need to be equal.
2064 	 */
2065 
2066 	__wsum ret = seed;
2067 
2068 	if (from_size && to_size)
2069 		ret = csum_sub(csum_partial(to, to_size, ret),
2070 			       csum_partial(from, from_size, 0));
2071 	else if (to_size)
2072 		ret = csum_partial(to, to_size, ret);
2073 
2074 	else if (from_size)
2075 		ret = ~csum_partial(from, from_size, ~ret);
2076 
2077 	return csum_from32to16((__force unsigned int)ret);
2078 }
2079 
2080 static const struct bpf_func_proto bpf_csum_diff_proto = {
2081 	.func		= bpf_csum_diff,
2082 	.gpl_only	= false,
2083 	.pkt_access	= true,
2084 	.ret_type	= RET_INTEGER,
2085 	.arg1_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
2086 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
2087 	.arg3_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
2088 	.arg4_type	= ARG_MEM_SIZE_OR_ZERO,
2089 	.arg5_type	= ARG_ANYTHING,
2090 };
2091 
2092 BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
2093 {
2094 	/* The interface is to be used in combination with bpf_csum_diff()
2095 	 * for direct packet writes. csum rotation for alignment as well
2096 	 * as emulating csum_sub() can be done from the eBPF program.
2097 	 */
2098 	if (skb->ip_summed == CHECKSUM_COMPLETE)
2099 		return (skb->csum = csum_add(skb->csum, csum));
2100 
2101 	return -ENOTSUPP;
2102 }
2103 
2104 static const struct bpf_func_proto bpf_csum_update_proto = {
2105 	.func		= bpf_csum_update,
2106 	.gpl_only	= false,
2107 	.ret_type	= RET_INTEGER,
2108 	.arg1_type	= ARG_PTR_TO_CTX,
2109 	.arg2_type	= ARG_ANYTHING,
2110 };
2111 
2112 BPF_CALL_2(bpf_csum_level, struct sk_buff *, skb, u64, level)
2113 {
2114 	/* The interface is to be used in combination with bpf_skb_adjust_room()
2115 	 * for encap/decap of packet headers when BPF_F_ADJ_ROOM_NO_CSUM_RESET
2116 	 * is passed as flags, for example.
2117 	 */
2118 	switch (level) {
2119 	case BPF_CSUM_LEVEL_INC:
2120 		__skb_incr_checksum_unnecessary(skb);
2121 		break;
2122 	case BPF_CSUM_LEVEL_DEC:
2123 		__skb_decr_checksum_unnecessary(skb);
2124 		break;
2125 	case BPF_CSUM_LEVEL_RESET:
2126 		__skb_reset_checksum_unnecessary(skb);
2127 		break;
2128 	case BPF_CSUM_LEVEL_QUERY:
2129 		return skb->ip_summed == CHECKSUM_UNNECESSARY ?
2130 		       skb->csum_level : -EACCES;
2131 	default:
2132 		return -EINVAL;
2133 	}
2134 
2135 	return 0;
2136 }
2137 
2138 static const struct bpf_func_proto bpf_csum_level_proto = {
2139 	.func		= bpf_csum_level,
2140 	.gpl_only	= false,
2141 	.ret_type	= RET_INTEGER,
2142 	.arg1_type	= ARG_PTR_TO_CTX,
2143 	.arg2_type	= ARG_ANYTHING,
2144 };
2145 
2146 static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
2147 {
2148 	return dev_forward_skb_nomtu(dev, skb);
2149 }
2150 
2151 static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
2152 				      struct sk_buff *skb)
2153 {
2154 	int ret = ____dev_forward_skb(dev, skb, false);
2155 
2156 	if (likely(!ret)) {
2157 		skb->dev = dev;
2158 		ret = netif_rx(skb);
2159 	}
2160 
2161 	return ret;
2162 }
2163 
2164 static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
2165 {
2166 	int ret;
2167 
2168 	if (dev_xmit_recursion()) {
2169 		net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2170 		kfree_skb(skb);
2171 		return -ENETDOWN;
2172 	}
2173 
2174 	skb->dev = dev;
2175 	skb_set_redirected_noclear(skb, skb_at_tc_ingress(skb));
2176 	skb_clear_tstamp(skb);
2177 
2178 	dev_xmit_recursion_inc();
2179 	ret = dev_queue_xmit(skb);
2180 	dev_xmit_recursion_dec();
2181 
2182 	return ret;
2183 }
2184 
2185 static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
2186 				 u32 flags)
2187 {
2188 	unsigned int mlen = skb_network_offset(skb);
2189 
2190 	if (unlikely(skb->len <= mlen)) {
2191 		kfree_skb(skb);
2192 		return -ERANGE;
2193 	}
2194 
2195 	if (mlen) {
2196 		__skb_pull(skb, mlen);
2197 
2198 		/* At ingress, the mac header has already been pulled once.
2199 		 * At egress, skb_pospull_rcsum has to be done in case that
2200 		 * the skb is originated from ingress (i.e. a forwarded skb)
2201 		 * to ensure that rcsum starts at net header.
2202 		 */
2203 		if (!skb_at_tc_ingress(skb))
2204 			skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
2205 	}
2206 	skb_pop_mac_header(skb);
2207 	skb_reset_mac_len(skb);
2208 	return flags & BPF_F_INGRESS ?
2209 	       __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
2210 }
2211 
2212 static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
2213 				 u32 flags)
2214 {
2215 	/* Verify that a link layer header is carried */
2216 	if (unlikely(skb->mac_header >= skb->network_header || skb->len == 0)) {
2217 		kfree_skb(skb);
2218 		return -ERANGE;
2219 	}
2220 
2221 	bpf_push_mac_rcsum(skb);
2222 	return flags & BPF_F_INGRESS ?
2223 	       __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
2224 }
2225 
2226 static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
2227 			  u32 flags)
2228 {
2229 	if (dev_is_mac_header_xmit(dev))
2230 		return __bpf_redirect_common(skb, dev, flags);
2231 	else
2232 		return __bpf_redirect_no_mac(skb, dev, flags);
2233 }
2234 
2235 #if IS_ENABLED(CONFIG_IPV6)
2236 static int bpf_out_neigh_v6(struct net *net, struct sk_buff *skb,
2237 			    struct net_device *dev, struct bpf_nh_params *nh)
2238 {
2239 	u32 hh_len = LL_RESERVED_SPACE(dev);
2240 	const struct in6_addr *nexthop;
2241 	struct dst_entry *dst = NULL;
2242 	struct neighbour *neigh;
2243 
2244 	if (dev_xmit_recursion()) {
2245 		net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2246 		goto out_drop;
2247 	}
2248 
2249 	skb->dev = dev;
2250 	skb_clear_tstamp(skb);
2251 
2252 	if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) {
2253 		skb = skb_expand_head(skb, hh_len);
2254 		if (!skb)
2255 			return -ENOMEM;
2256 	}
2257 
2258 	if (unlikely(!ipv6_mod_enabled()))
2259 		goto out_drop;
2260 
2261 	rcu_read_lock();
2262 	if (!nh) {
2263 		dst = skb_dst(skb);
2264 		nexthop = rt6_nexthop(dst_rt6_info(dst),
2265 				      &ipv6_hdr(skb)->daddr);
2266 	} else {
2267 		nexthop = &nh->ipv6_nh;
2268 	}
2269 	neigh = ip_neigh_gw6(dev, nexthop);
2270 	if (likely(!IS_ERR(neigh))) {
2271 		int ret;
2272 
2273 		sock_confirm_neigh(skb, neigh);
2274 		local_bh_disable();
2275 		dev_xmit_recursion_inc();
2276 		ret = neigh_output(neigh, skb, false);
2277 		dev_xmit_recursion_dec();
2278 		local_bh_enable();
2279 		rcu_read_unlock();
2280 		return ret;
2281 	}
2282 	rcu_read_unlock();
2283 	if (dst)
2284 		IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES);
2285 out_drop:
2286 	kfree_skb(skb);
2287 	return -ENETDOWN;
2288 }
2289 
2290 static int __bpf_redirect_neigh_v6(struct sk_buff *skb, struct net_device *dev,
2291 				   struct bpf_nh_params *nh)
2292 {
2293 	const struct ipv6hdr *ip6h = ipv6_hdr(skb);
2294 	struct net *net = dev_net(dev);
2295 	int err, ret = NET_XMIT_DROP;
2296 
2297 	if (!nh) {
2298 		struct dst_entry *dst;
2299 		struct flowi6 fl6 = {
2300 			.flowi6_flags = FLOWI_FLAG_ANYSRC,
2301 			.flowi6_mark  = skb->mark,
2302 			.flowlabel    = ip6_flowinfo(ip6h),
2303 			.flowi6_oif   = dev->ifindex,
2304 			.flowi6_proto = ip6h->nexthdr,
2305 			.daddr	      = ip6h->daddr,
2306 			.saddr	      = ip6h->saddr,
2307 		};
2308 
2309 		dst = ip6_dst_lookup_flow(net, NULL, &fl6, NULL);
2310 		if (IS_ERR(dst))
2311 			goto out_drop;
2312 
2313 		skb_dst_drop(skb);
2314 		skb_dst_set(skb, dst);
2315 	} else if (nh->nh_family != AF_INET6) {
2316 		goto out_drop;
2317 	}
2318 
2319 	err = bpf_out_neigh_v6(net, skb, dev, nh);
2320 	if (unlikely(net_xmit_eval(err)))
2321 		dev_core_stats_tx_dropped_inc(dev);
2322 	else
2323 		ret = NET_XMIT_SUCCESS;
2324 	goto out_xmit;
2325 out_drop:
2326 	dev_core_stats_tx_dropped_inc(dev);
2327 	kfree_skb(skb);
2328 out_xmit:
2329 	return ret;
2330 }
2331 #else
2332 static int __bpf_redirect_neigh_v6(struct sk_buff *skb, struct net_device *dev,
2333 				   struct bpf_nh_params *nh)
2334 {
2335 	kfree_skb(skb);
2336 	return NET_XMIT_DROP;
2337 }
2338 #endif /* CONFIG_IPV6 */
2339 
2340 #if IS_ENABLED(CONFIG_INET)
2341 static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb,
2342 			    struct net_device *dev, struct bpf_nh_params *nh)
2343 {
2344 	u32 hh_len = LL_RESERVED_SPACE(dev);
2345 	struct neighbour *neigh;
2346 	bool is_v6gw = false;
2347 
2348 	if (dev_xmit_recursion()) {
2349 		net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2350 		goto out_drop;
2351 	}
2352 
2353 	skb->dev = dev;
2354 	skb_clear_tstamp(skb);
2355 
2356 	if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) {
2357 		skb = skb_expand_head(skb, hh_len);
2358 		if (!skb)
2359 			return -ENOMEM;
2360 	}
2361 
2362 	rcu_read_lock();
2363 	if (!nh) {
2364 		struct rtable *rt = skb_rtable(skb);
2365 
2366 		neigh = ip_neigh_for_gw(rt, skb, &is_v6gw);
2367 	} else if (nh->nh_family == AF_INET6) {
2368 		if (unlikely(!ipv6_mod_enabled())) {
2369 			rcu_read_unlock();
2370 			goto out_drop;
2371 		}
2372 		neigh = ip_neigh_gw6(dev, &nh->ipv6_nh);
2373 		is_v6gw = true;
2374 	} else if (nh->nh_family == AF_INET) {
2375 		neigh = ip_neigh_gw4(dev, nh->ipv4_nh);
2376 	} else {
2377 		rcu_read_unlock();
2378 		goto out_drop;
2379 	}
2380 
2381 	if (likely(!IS_ERR(neigh))) {
2382 		int ret;
2383 
2384 		sock_confirm_neigh(skb, neigh);
2385 		local_bh_disable();
2386 		dev_xmit_recursion_inc();
2387 		ret = neigh_output(neigh, skb, is_v6gw);
2388 		dev_xmit_recursion_dec();
2389 		local_bh_enable();
2390 		rcu_read_unlock();
2391 		return ret;
2392 	}
2393 	rcu_read_unlock();
2394 out_drop:
2395 	kfree_skb(skb);
2396 	return -ENETDOWN;
2397 }
2398 
2399 static int __bpf_redirect_neigh_v4(struct sk_buff *skb, struct net_device *dev,
2400 				   struct bpf_nh_params *nh)
2401 {
2402 	const struct iphdr *ip4h = ip_hdr(skb);
2403 	struct net *net = dev_net(dev);
2404 	int err, ret = NET_XMIT_DROP;
2405 
2406 	if (!nh) {
2407 		struct flowi4 fl4 = {
2408 			.flowi4_flags = FLOWI_FLAG_ANYSRC,
2409 			.flowi4_mark  = skb->mark,
2410 			.flowi4_dscp  = ip4h_dscp(ip4h),
2411 			.flowi4_oif   = dev->ifindex,
2412 			.flowi4_proto = ip4h->protocol,
2413 			.daddr	      = ip4h->daddr,
2414 			.saddr	      = ip4h->saddr,
2415 		};
2416 		struct rtable *rt;
2417 
2418 		rt = ip_route_output_flow(net, &fl4, NULL);
2419 		if (IS_ERR(rt))
2420 			goto out_drop;
2421 		if (rt->rt_type != RTN_UNICAST && rt->rt_type != RTN_LOCAL) {
2422 			ip_rt_put(rt);
2423 			goto out_drop;
2424 		}
2425 
2426 		skb_dst_drop(skb);
2427 		skb_dst_set(skb, &rt->dst);
2428 	}
2429 
2430 	err = bpf_out_neigh_v4(net, skb, dev, nh);
2431 	if (unlikely(net_xmit_eval(err)))
2432 		dev_core_stats_tx_dropped_inc(dev);
2433 	else
2434 		ret = NET_XMIT_SUCCESS;
2435 	goto out_xmit;
2436 out_drop:
2437 	dev_core_stats_tx_dropped_inc(dev);
2438 	kfree_skb(skb);
2439 out_xmit:
2440 	return ret;
2441 }
2442 #else
2443 static int __bpf_redirect_neigh_v4(struct sk_buff *skb, struct net_device *dev,
2444 				   struct bpf_nh_params *nh)
2445 {
2446 	kfree_skb(skb);
2447 	return NET_XMIT_DROP;
2448 }
2449 #endif /* CONFIG_INET */
2450 
2451 static int __bpf_redirect_neigh(struct sk_buff *skb, struct net_device *dev,
2452 				struct bpf_nh_params *nh)
2453 {
2454 	struct ethhdr *ethh = eth_hdr(skb);
2455 
2456 	if (unlikely(skb->mac_header >= skb->network_header))
2457 		goto out;
2458 	bpf_push_mac_rcsum(skb);
2459 	if (is_multicast_ether_addr(ethh->h_dest))
2460 		goto out;
2461 
2462 	skb_pull(skb, sizeof(*ethh));
2463 	skb_unset_mac_header(skb);
2464 	skb_reset_network_header(skb);
2465 
2466 	if (skb->protocol == htons(ETH_P_IP))
2467 		return __bpf_redirect_neigh_v4(skb, dev, nh);
2468 	else if (skb->protocol == htons(ETH_P_IPV6))
2469 		return __bpf_redirect_neigh_v6(skb, dev, nh);
2470 out:
2471 	kfree_skb(skb);
2472 	return -ENOTSUPP;
2473 }
2474 
2475 /* Internal, non-exposed redirect flags. */
2476 enum {
2477 	BPF_F_NEIGH	= (1ULL << 16),
2478 	BPF_F_PEER	= (1ULL << 17),
2479 	BPF_F_NEXTHOP	= (1ULL << 18),
2480 #define BPF_F_REDIRECT_INTERNAL	(BPF_F_NEIGH | BPF_F_PEER | BPF_F_NEXTHOP)
2481 };
2482 
2483 BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
2484 {
2485 	struct net_device *dev;
2486 	struct sk_buff *clone;
2487 	int ret;
2488 
2489 	BUILD_BUG_ON(BPF_F_REDIRECT_INTERNAL & BPF_F_REDIRECT_FLAGS);
2490 
2491 	if (unlikely(flags & (~(BPF_F_INGRESS) | BPF_F_REDIRECT_INTERNAL)))
2492 		return -EINVAL;
2493 
2494 	/* BPF test infra's convert___skb_to_skb() can create type-less
2495 	 * GSO packets. gso_features_check() will detect this as a bad
2496 	 * offload. However, lets not leak them out in the first place.
2497 	 */
2498 	if (unlikely(skb_is_gso(skb) && !skb_shinfo(skb)->gso_type))
2499 		return -EBADMSG;
2500 
2501 	dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
2502 	if (unlikely(!dev))
2503 		return -EINVAL;
2504 
2505 	clone = skb_clone(skb, GFP_ATOMIC);
2506 	if (unlikely(!clone))
2507 		return -ENOMEM;
2508 
2509 	/* For direct write, we need to keep the invariant that the skbs
2510 	 * we're dealing with need to be uncloned. Should uncloning fail
2511 	 * here, we need to free the just generated clone to unclone once
2512 	 * again.
2513 	 */
2514 	ret = bpf_try_make_head_writable(skb);
2515 	if (unlikely(ret)) {
2516 		kfree_skb(clone);
2517 		return -ENOMEM;
2518 	}
2519 
2520 	return __bpf_redirect(clone, dev, flags);
2521 }
2522 
2523 static const struct bpf_func_proto bpf_clone_redirect_proto = {
2524 	.func           = bpf_clone_redirect,
2525 	.gpl_only       = false,
2526 	.ret_type       = RET_INTEGER,
2527 	.arg1_type      = ARG_PTR_TO_CTX,
2528 	.arg2_type      = ARG_ANYTHING,
2529 	.arg3_type      = ARG_ANYTHING,
2530 };
2531 
2532 static struct net_device *skb_get_peer_dev(struct net_device *dev)
2533 {
2534 	const struct net_device_ops *ops = dev->netdev_ops;
2535 
2536 	if (likely(ops->ndo_get_peer_dev))
2537 		return INDIRECT_CALL_1(ops->ndo_get_peer_dev,
2538 				       netkit_peer_dev, dev);
2539 	return NULL;
2540 }
2541 
2542 int skb_do_redirect(struct sk_buff *skb)
2543 {
2544 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
2545 	struct net *net = dev_net(skb->dev);
2546 	struct net_device *dev;
2547 	u32 flags = ri->flags;
2548 
2549 	dev = dev_get_by_index_rcu(net, ri->tgt_index);
2550 	ri->tgt_index = 0;
2551 	ri->flags = 0;
2552 	if (unlikely(!dev))
2553 		goto out_drop;
2554 	if (flags & BPF_F_PEER) {
2555 		dev = skb_get_peer_dev(dev);
2556 		if (unlikely(!dev ||
2557 			     !(dev->flags & IFF_UP) ||
2558 			     net_eq(net, dev_net(dev))))
2559 			goto out_drop;
2560 		skb_scrub_packet(skb, false);
2561 		if (flags & BPF_F_EGRESS)
2562 			return __bpf_redirect(skb, dev, 0);
2563 		if (unlikely(!skb_at_tc_ingress(skb)))
2564 			goto out_drop;
2565 		skb->dev = dev;
2566 		dev_sw_netstats_rx_add(dev, skb->len);
2567 		return -EAGAIN;
2568 	}
2569 	return flags & BPF_F_NEIGH ?
2570 	       __bpf_redirect_neigh(skb, dev, flags & BPF_F_NEXTHOP ?
2571 				    &ri->nh : NULL) :
2572 	       __bpf_redirect(skb, dev, flags);
2573 out_drop:
2574 	kfree_skb(skb);
2575 	return -EINVAL;
2576 }
2577 
2578 BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
2579 {
2580 	struct bpf_redirect_info *ri;
2581 
2582 	if (unlikely(!bpf_net_ctx_get() ||
2583 		     (flags & (~(BPF_F_INGRESS) | BPF_F_REDIRECT_INTERNAL))))
2584 		return TC_ACT_SHOT;
2585 
2586 	ri = bpf_net_ctx_get_ri();
2587 	ri->flags = flags;
2588 	ri->tgt_index = ifindex;
2589 
2590 	return TC_ACT_REDIRECT;
2591 }
2592 
2593 static const struct bpf_func_proto bpf_redirect_proto = {
2594 	.func           = bpf_redirect,
2595 	.gpl_only       = false,
2596 	.ret_type       = RET_INTEGER,
2597 	.arg1_type      = ARG_ANYTHING,
2598 	.arg2_type      = ARG_ANYTHING,
2599 };
2600 
2601 BPF_CALL_2(bpf_redirect_peer, u32, ifindex, u64, flags)
2602 {
2603 	struct bpf_redirect_info *ri;
2604 
2605 	if (unlikely(!bpf_net_ctx_get() || (flags & ~BPF_F_EGRESS)))
2606 		return TC_ACT_SHOT;
2607 
2608 	ri = bpf_net_ctx_get_ri();
2609 	ri->flags = BPF_F_PEER | flags;
2610 	ri->tgt_index = ifindex;
2611 
2612 	return TC_ACT_REDIRECT;
2613 }
2614 
2615 static const struct bpf_func_proto bpf_redirect_peer_proto = {
2616 	.func           = bpf_redirect_peer,
2617 	.gpl_only       = false,
2618 	.ret_type       = RET_INTEGER,
2619 	.arg1_type      = ARG_ANYTHING,
2620 	.arg2_type      = ARG_ANYTHING,
2621 };
2622 
2623 BPF_CALL_4(bpf_redirect_neigh, u32, ifindex, struct bpf_redir_neigh *, params,
2624 	   int, plen, u64, flags)
2625 {
2626 	struct bpf_redirect_info *ri;
2627 
2628 	if (unlikely((plen && plen < sizeof(*params)) ||
2629 		     !bpf_net_ctx_get() || flags))
2630 		return TC_ACT_SHOT;
2631 
2632 	ri = bpf_net_ctx_get_ri();
2633 	ri->flags = BPF_F_NEIGH | (plen ? BPF_F_NEXTHOP : 0);
2634 	ri->tgt_index = ifindex;
2635 
2636 	BUILD_BUG_ON(sizeof(struct bpf_redir_neigh) != sizeof(struct bpf_nh_params));
2637 	if (plen)
2638 		memcpy(&ri->nh, params, sizeof(ri->nh));
2639 
2640 	return TC_ACT_REDIRECT;
2641 }
2642 
2643 static const struct bpf_func_proto bpf_redirect_neigh_proto = {
2644 	.func		= bpf_redirect_neigh,
2645 	.gpl_only	= false,
2646 	.ret_type	= RET_INTEGER,
2647 	.arg1_type	= ARG_ANYTHING,
2648 	.arg2_type      = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
2649 	.arg3_type      = ARG_MEM_SIZE_OR_ZERO,
2650 	.arg4_type	= ARG_ANYTHING,
2651 };
2652 
2653 BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg *, msg, u32, bytes)
2654 {
2655 	msg->apply_bytes = bytes;
2656 	return 0;
2657 }
2658 
2659 static const struct bpf_func_proto bpf_msg_apply_bytes_proto = {
2660 	.func           = bpf_msg_apply_bytes,
2661 	.gpl_only       = false,
2662 	.ret_type       = RET_INTEGER,
2663 	.arg1_type	= ARG_PTR_TO_CTX,
2664 	.arg2_type      = ARG_ANYTHING,
2665 };
2666 
2667 BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes)
2668 {
2669 	msg->cork_bytes = bytes;
2670 	return 0;
2671 }
2672 
2673 static void sk_msg_reset_curr(struct sk_msg *msg)
2674 {
2675 	if (!msg->sg.size) {
2676 		msg->sg.curr = msg->sg.start;
2677 		msg->sg.copybreak = 0;
2678 	} else {
2679 		u32 i = msg->sg.end;
2680 
2681 		sk_msg_iter_var_prev(i);
2682 		msg->sg.curr = i;
2683 		msg->sg.copybreak = msg->sg.data[i].length;
2684 	}
2685 }
2686 
2687 static bool sk_msg_elem_is_copy(const struct sk_msg *msg, u32 i)
2688 {
2689 	return test_bit(i, msg->sg.copy);
2690 }
2691 
2692 static void sk_msg_clear_elem_copy(struct sk_msg *msg, u32 i)
2693 {
2694 	__clear_bit(i, msg->sg.copy);
2695 }
2696 
2697 static void sk_msg_set_elem_copy(struct sk_msg *msg, u32 i, bool sg_copy)
2698 {
2699 	__assign_bit(i, msg->sg.copy, sg_copy);
2700 }
2701 
2702 static void sk_msg_clear_copy_range(struct sk_msg *msg, u32 start, u32 end)
2703 {
2704 	while (start != end) {
2705 		sk_msg_clear_elem_copy(msg, start);
2706 		sk_msg_iter_var_next(start);
2707 	}
2708 }
2709 
2710 static void sk_msg_sg_move(struct sk_msg *msg, u32 dst, u32 src)
2711 {
2712 	msg->sg.data[dst] = msg->sg.data[src];
2713 
2714 	sk_msg_set_elem_copy(msg, dst,
2715 		sk_msg_elem_is_copy(msg, src));
2716 }
2717 
2718 static const struct bpf_func_proto bpf_msg_cork_bytes_proto = {
2719 	.func           = bpf_msg_cork_bytes,
2720 	.gpl_only       = false,
2721 	.ret_type       = RET_INTEGER,
2722 	.arg1_type	= ARG_PTR_TO_CTX,
2723 	.arg2_type      = ARG_ANYTHING,
2724 };
2725 
2726 BPF_CALL_4(bpf_msg_pull_data, struct sk_msg *, msg, u32, start,
2727 	   u32, end, u64, flags)
2728 {
2729 	u32 len = 0, offset = 0, copy = 0, poffset = 0, bytes = end - start;
2730 	u32 first_sge, last_sge, i, shift, bytes_sg_total;
2731 	struct scatterlist *sge;
2732 	u8 *raw, *to, *from;
2733 	struct page *page;
2734 
2735 	if (unlikely(flags || end <= start))
2736 		return -EINVAL;
2737 
2738 	/* First find the starting scatterlist element */
2739 	i = msg->sg.start;
2740 	do {
2741 		offset += len;
2742 		len = sk_msg_elem(msg, i)->length;
2743 		if (start < offset + len)
2744 			break;
2745 		sk_msg_iter_var_next(i);
2746 	} while (i != msg->sg.end);
2747 
2748 	if (unlikely(start >= offset + len))
2749 		return -EINVAL;
2750 
2751 	first_sge = i;
2752 	/* The start may point into the sg element so we need to also
2753 	 * account for the headroom.
2754 	 */
2755 	bytes_sg_total = start - offset + bytes;
2756 	if (!sk_msg_elem_is_copy(msg, i) && bytes_sg_total <= len)
2757 		goto out;
2758 
2759 	/* At this point we need to linearize multiple scatterlist
2760 	 * elements or a single shared page. Either way we need to
2761 	 * copy into a linear buffer exclusively owned by BPF. Then
2762 	 * place the buffer in the scatterlist and fixup the original
2763 	 * entries by removing the entries now in the linear buffer
2764 	 * and shifting the remaining entries. For now we do not try
2765 	 * to copy partial entries to avoid complexity of running out
2766 	 * of sg_entry slots. The downside is reading a single byte
2767 	 * will copy the entire sg entry.
2768 	 */
2769 	do {
2770 		copy += sk_msg_elem(msg, i)->length;
2771 		sk_msg_iter_var_next(i);
2772 		if (bytes_sg_total <= copy)
2773 			break;
2774 	} while (i != msg->sg.end);
2775 	last_sge = i;
2776 
2777 	if (unlikely(bytes_sg_total > copy))
2778 		return -EINVAL;
2779 
2780 	page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2781 			   get_order(copy));
2782 	if (unlikely(!page))
2783 		return -ENOMEM;
2784 
2785 	raw = page_address(page);
2786 	i = first_sge;
2787 	do {
2788 		sge = sk_msg_elem(msg, i);
2789 		from = sg_virt(sge);
2790 		len = sge->length;
2791 		to = raw + poffset;
2792 
2793 		memcpy(to, from, len);
2794 		poffset += len;
2795 		sge->length = 0;
2796 		put_page(sg_page(sge));
2797 		sk_msg_clear_elem_copy(msg, i);
2798 
2799 		sk_msg_iter_var_next(i);
2800 	} while (i != last_sge);
2801 
2802 	sg_set_page(&msg->sg.data[first_sge], page, copy, 0);
2803 	sk_msg_clear_elem_copy(msg, first_sge);
2804 
2805 	/* To repair sg ring we need to shift entries. If we only
2806 	 * had a single entry though we can just replace it and
2807 	 * be done. Otherwise walk the ring and shift the entries.
2808 	 */
2809 	WARN_ON_ONCE(last_sge == first_sge);
2810 	shift = last_sge > first_sge ?
2811 		last_sge - first_sge - 1 :
2812 		NR_MSG_FRAG_IDS - first_sge + last_sge - 1;
2813 	if (!shift) {
2814 		sk_msg_clear_elem_copy(msg, msg->sg.end);
2815 		goto out;
2816 	}
2817 
2818 	i = first_sge;
2819 	sk_msg_iter_var_next(i);
2820 	sk_msg_clear_copy_range(msg, i, last_sge);
2821 
2822 	i = first_sge;
2823 	sk_msg_iter_var_next(i);
2824 	do {
2825 		u32 move_from;
2826 
2827 		if (i + shift >= NR_MSG_FRAG_IDS)
2828 			move_from = i + shift - NR_MSG_FRAG_IDS;
2829 		else
2830 			move_from = i + shift;
2831 		if (move_from == msg->sg.end)
2832 			break;
2833 
2834 		sk_msg_sg_move(msg, i, move_from);
2835 		msg->sg.data[move_from].length = 0;
2836 		msg->sg.data[move_from].page_link = 0;
2837 		msg->sg.data[move_from].offset = 0;
2838 		sk_msg_clear_elem_copy(msg, move_from);
2839 		sk_msg_iter_var_next(i);
2840 	} while (1);
2841 
2842 	msg->sg.end = msg->sg.end - shift > msg->sg.end ?
2843 		      msg->sg.end - shift + NR_MSG_FRAG_IDS :
2844 		      msg->sg.end - shift;
2845 	sk_msg_clear_elem_copy(msg, msg->sg.end);
2846 out:
2847 	sk_msg_reset_curr(msg);
2848 	msg->data = sg_virt(&msg->sg.data[first_sge]) + start - offset;
2849 	msg->data_end = msg->data + bytes;
2850 	return 0;
2851 }
2852 
2853 static const struct bpf_func_proto bpf_msg_pull_data_proto = {
2854 	.func		= bpf_msg_pull_data,
2855 	.gpl_only	= false,
2856 	.ret_type	= RET_INTEGER,
2857 	.arg1_type	= ARG_PTR_TO_CTX,
2858 	.arg2_type	= ARG_ANYTHING,
2859 	.arg3_type	= ARG_ANYTHING,
2860 	.arg4_type	= ARG_ANYTHING,
2861 };
2862 
2863 BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start,
2864 	   u32, len, u64, flags)
2865 {
2866 	bool sge_copy = false, nsge_copy = false, nnsge_copy = false;
2867 	struct scatterlist sge, nsge, nnsge, rsge = {0}, *psge;
2868 	u32 new, i = 0, l = 0, space, copy = 0, offset = 0;
2869 	bool rsge_copy = false;
2870 	u8 *raw, *to, *from;
2871 	struct page *page;
2872 
2873 	if (unlikely(flags))
2874 		return -EINVAL;
2875 
2876 	if (unlikely(len == 0))
2877 		return 0;
2878 
2879 	/* First find the starting scatterlist element */
2880 	i = msg->sg.start;
2881 	do {
2882 		offset += l;
2883 		l = sk_msg_elem(msg, i)->length;
2884 
2885 		if (start < offset + l)
2886 			break;
2887 		sk_msg_iter_var_next(i);
2888 	} while (i != msg->sg.end);
2889 
2890 	if (start > offset + l)
2891 		return -EINVAL;
2892 
2893 	space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2894 
2895 	/* If no space available will fallback to copy, we need at
2896 	 * least one scatterlist elem available to push data into
2897 	 * when start aligns to the beginning of an element or two
2898 	 * when it falls inside an element. We handle the start equals
2899 	 * offset case because its the common case for inserting a
2900 	 * header.
2901 	 */
2902 	if (!space || (space == 1 && start != offset))
2903 		copy = msg->sg.data[i].length;
2904 
2905 	if (unlikely(copy + len < copy))
2906 		return -EINVAL;
2907 
2908 	page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2909 			   get_order(copy + len));
2910 	if (unlikely(!page))
2911 		return -ENOMEM;
2912 
2913 	if (copy) {
2914 		int front, back;
2915 
2916 		raw = page_address(page);
2917 
2918 		if (i == msg->sg.end)
2919 			sk_msg_iter_var_prev(i);
2920 		psge = sk_msg_elem(msg, i);
2921 		front = start - offset;
2922 		back = psge->length - front;
2923 		from = sg_virt(psge);
2924 
2925 		if (front)
2926 			memcpy(raw, from, front);
2927 
2928 		if (back) {
2929 			from += front;
2930 			to = raw + front + len;
2931 
2932 			memcpy(to, from, back);
2933 		}
2934 
2935 		put_page(sg_page(psge));
2936 		new = i;
2937 		goto place_new;
2938 	}
2939 
2940 	if (start - offset) {
2941 		if (i == msg->sg.end)
2942 			sk_msg_iter_var_prev(i);
2943 		psge = sk_msg_elem(msg, i);
2944 		rsge = sk_msg_elem_cpy(msg, i);
2945 		rsge_copy = sk_msg_elem_is_copy(msg, i);
2946 
2947 		psge->length = start - offset;
2948 		rsge.length -= psge->length;
2949 		rsge.offset += start - offset;
2950 
2951 		sk_msg_iter_var_next(i);
2952 		sg_unmark_end(psge);
2953 		sg_unmark_end(&rsge);
2954 	}
2955 
2956 	/* Slot(s) to place newly allocated data */
2957 	sk_msg_iter_next(msg, end);
2958 	new = i;
2959 	sk_msg_iter_var_next(i);
2960 
2961 	if (i == msg->sg.end) {
2962 		if (!rsge.length)
2963 			goto place_new;
2964 		sk_msg_iter_next(msg, end);
2965 		goto place_new;
2966 	}
2967 
2968 	/* Shift one or two slots as needed */
2969 	sge = sk_msg_elem_cpy(msg, new);
2970 	sg_unmark_end(&sge);
2971 	sge_copy = sk_msg_elem_is_copy(msg, new);
2972 
2973 	nsge = sk_msg_elem_cpy(msg, i);
2974 	nsge_copy = sk_msg_elem_is_copy(msg, i);
2975 	if (rsge.length) {
2976 		sk_msg_iter_var_next(i);
2977 		nnsge = sk_msg_elem_cpy(msg, i);
2978 		nnsge_copy = sk_msg_elem_is_copy(msg, i);
2979 		sk_msg_iter_next(msg, end);
2980 	}
2981 
2982 	while (i != msg->sg.end) {
2983 		msg->sg.data[i] = sge;
2984 		sk_msg_set_elem_copy(msg, i, sge_copy);
2985 		sge = nsge;
2986 		sge_copy = nsge_copy;
2987 		sk_msg_iter_var_next(i);
2988 		if (rsge.length) {
2989 			nsge = nnsge;
2990 			nsge_copy = nnsge_copy;
2991 			nnsge = sk_msg_elem_cpy(msg, i);
2992 			nnsge_copy = sk_msg_elem_is_copy(msg, i);
2993 		} else {
2994 			nsge = sk_msg_elem_cpy(msg, i);
2995 			nsge_copy = sk_msg_elem_is_copy(msg, i);
2996 		}
2997 	}
2998 
2999 place_new:
3000 	/* Place newly allocated data buffer */
3001 	sk_mem_charge(msg->sk, len);
3002 	msg->sg.size += len;
3003 	sk_msg_clear_elem_copy(msg, new);
3004 	sg_set_page(&msg->sg.data[new], page, len + copy, 0);
3005 	if (rsge.length) {
3006 		get_page(sg_page(&rsge));
3007 		sk_msg_iter_var_next(new);
3008 		msg->sg.data[new] = rsge;
3009 		sk_msg_set_elem_copy(msg, new, rsge_copy);
3010 	}
3011 	sk_msg_clear_elem_copy(msg, msg->sg.end);
3012 
3013 	sk_msg_reset_curr(msg);
3014 	sk_msg_compute_data_pointers(msg);
3015 	return 0;
3016 }
3017 
3018 static const struct bpf_func_proto bpf_msg_push_data_proto = {
3019 	.func		= bpf_msg_push_data,
3020 	.gpl_only	= false,
3021 	.ret_type	= RET_INTEGER,
3022 	.arg1_type	= ARG_PTR_TO_CTX,
3023 	.arg2_type	= ARG_ANYTHING,
3024 	.arg3_type	= ARG_ANYTHING,
3025 	.arg4_type	= ARG_ANYTHING,
3026 };
3027 
3028 static void sk_msg_shift_left(struct sk_msg *msg, int i)
3029 {
3030 	struct scatterlist *sge = sk_msg_elem(msg, i);
3031 	int prev;
3032 
3033 	put_page(sg_page(sge));
3034 	do {
3035 		prev = i;
3036 		sk_msg_iter_var_next(i);
3037 		sk_msg_sg_move(msg, prev, i);
3038 	} while (i != msg->sg.end);
3039 
3040 	sk_msg_iter_prev(msg, end);
3041 	sk_msg_clear_elem_copy(msg, msg->sg.end);
3042 }
3043 
3044 static void sk_msg_shift_right(struct sk_msg *msg, int i)
3045 {
3046 	struct scatterlist tmp, sge;
3047 	bool tmp_copy, sge_copy;
3048 
3049 	sk_msg_iter_next(msg, end);
3050 	sge = sk_msg_elem_cpy(msg, i);
3051 	sge_copy = sk_msg_elem_is_copy(msg, i);
3052 	sk_msg_iter_var_next(i);
3053 	tmp = sk_msg_elem_cpy(msg, i);
3054 	tmp_copy = sk_msg_elem_is_copy(msg, i);
3055 
3056 	while (i != msg->sg.end) {
3057 		msg->sg.data[i] = sge;
3058 		sk_msg_set_elem_copy(msg, i, sge_copy);
3059 		sk_msg_iter_var_next(i);
3060 		sge = tmp;
3061 		sge_copy = tmp_copy;
3062 		tmp = sk_msg_elem_cpy(msg, i);
3063 		tmp_copy = sk_msg_elem_is_copy(msg, i);
3064 	}
3065 	sk_msg_clear_elem_copy(msg, msg->sg.end);
3066 }
3067 
3068 BPF_CALL_4(bpf_msg_pop_data, struct sk_msg *, msg, u32, start,
3069 	   u32, len, u64, flags)
3070 {
3071 	u32 i = 0, l = 0, space, offset = 0;
3072 	u64 last = (u64)start + len;
3073 	u32 pop;
3074 
3075 	if (unlikely(flags))
3076 		return -EINVAL;
3077 
3078 	if (unlikely(len == 0))
3079 		return 0;
3080 
3081 	/* First find the starting scatterlist element */
3082 	i = msg->sg.start;
3083 	do {
3084 		offset += l;
3085 		l = sk_msg_elem(msg, i)->length;
3086 
3087 		if (start < offset + l)
3088 			break;
3089 		sk_msg_iter_var_next(i);
3090 	} while (i != msg->sg.end);
3091 
3092 	/* Bounds checks: start and pop must be inside message */
3093 	if (start >= offset + l || last > msg->sg.size)
3094 		return -EINVAL;
3095 
3096 	space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
3097 
3098 	pop = len;
3099 	/* --------------| offset
3100 	 * -| start      |-------- len -------|
3101 	 *
3102 	 *  |----- a ----|-------- pop -------|----- b ----|
3103 	 *  |______________________________________________| length
3104 	 *
3105 	 *
3106 	 * a:   region at front of scatter element to save
3107 	 * b:   region at back of scatter element to save when length > A + pop
3108 	 * pop: region to pop from element, same as input 'pop' here will be
3109 	 *      decremented below per iteration.
3110 	 *
3111 	 * Two top-level cases to handle when start != offset, first B is non
3112 	 * zero and second B is zero corresponding to when a pop includes more
3113 	 * than one element.
3114 	 *
3115 	 * Then if B is non-zero AND there is no space allocate space and
3116 	 * compact A, B regions into page. If there is space shift ring to
3117 	 * the right free'ing the next element in ring to place B, leaving
3118 	 * A untouched except to reduce length.
3119 	 */
3120 	if (start != offset) {
3121 		struct scatterlist *nsge, *sge = sk_msg_elem(msg, i);
3122 		bool sge_copy = sk_msg_elem_is_copy(msg, i);
3123 		int a = start - offset;
3124 		int b = sge->length - pop - a;
3125 		u32 sge_idx = i;
3126 
3127 		sk_msg_iter_var_next(i);
3128 
3129 		if (b > 0) {
3130 			if (space) {
3131 				sge->length = a;
3132 				sk_msg_shift_right(msg, i);
3133 				nsge = sk_msg_elem(msg, i);
3134 				get_page(sg_page(sge));
3135 				sg_set_page(nsge,
3136 					    sg_page(sge),
3137 					    b, sge->offset + pop + a);
3138 				sk_msg_set_elem_copy(msg, i, sge_copy);
3139 			} else {
3140 				struct page *page, *orig;
3141 				u8 *to, *from;
3142 
3143 				page = alloc_pages(__GFP_NOWARN |
3144 						   __GFP_COMP   | GFP_ATOMIC,
3145 						   get_order(a + b));
3146 				if (unlikely(!page))
3147 					return -ENOMEM;
3148 
3149 				orig = sg_page(sge);
3150 				from = sg_virt(sge);
3151 				to = page_address(page);
3152 				memcpy(to, from, a);
3153 				memcpy(to + a, from + a + pop, b);
3154 				sg_set_page(sge, page, a + b, 0);
3155 				sk_msg_clear_elem_copy(msg, sge_idx);
3156 				put_page(orig);
3157 			}
3158 			pop = 0;
3159 		} else {
3160 			pop -= (sge->length - a);
3161 			sge->length = a;
3162 		}
3163 	}
3164 
3165 	/* From above the current layout _must_ be as follows,
3166 	 *
3167 	 * -| offset
3168 	 * -| start
3169 	 *
3170 	 *  |---- pop ---|---------------- b ------------|
3171 	 *  |____________________________________________| length
3172 	 *
3173 	 * Offset and start of the current msg elem are equal because in the
3174 	 * previous case we handled offset != start and either consumed the
3175 	 * entire element and advanced to the next element OR pop == 0.
3176 	 *
3177 	 * Two cases to handle here are first pop is less than the length
3178 	 * leaving some remainder b above. Simply adjust the element's layout
3179 	 * in this case. Or pop >= length of the element so that b = 0. In this
3180 	 * case advance to next element decrementing pop.
3181 	 */
3182 	while (pop) {
3183 		struct scatterlist *sge = sk_msg_elem(msg, i);
3184 
3185 		if (pop < sge->length) {
3186 			sge->length -= pop;
3187 			sge->offset += pop;
3188 			pop = 0;
3189 		} else {
3190 			pop -= sge->length;
3191 			sk_msg_shift_left(msg, i);
3192 		}
3193 	}
3194 
3195 	sk_mem_uncharge(msg->sk, len - pop);
3196 	msg->sg.size -= (len - pop);
3197 	sk_msg_reset_curr(msg);
3198 	sk_msg_compute_data_pointers(msg);
3199 	return 0;
3200 }
3201 
3202 static const struct bpf_func_proto bpf_msg_pop_data_proto = {
3203 	.func		= bpf_msg_pop_data,
3204 	.gpl_only	= false,
3205 	.ret_type	= RET_INTEGER,
3206 	.arg1_type	= ARG_PTR_TO_CTX,
3207 	.arg2_type	= ARG_ANYTHING,
3208 	.arg3_type	= ARG_ANYTHING,
3209 	.arg4_type	= ARG_ANYTHING,
3210 };
3211 
3212 #ifdef CONFIG_CGROUP_NET_CLASSID
3213 BPF_CALL_0(bpf_get_cgroup_classid_curr)
3214 {
3215 	return __task_get_classid(current);
3216 }
3217 
3218 const struct bpf_func_proto bpf_get_cgroup_classid_curr_proto = {
3219 	.func		= bpf_get_cgroup_classid_curr,
3220 	.gpl_only	= false,
3221 	.ret_type	= RET_INTEGER,
3222 };
3223 
3224 BPF_CALL_1(bpf_skb_cgroup_classid, const struct sk_buff *, skb)
3225 {
3226 	struct sock *sk = skb_to_full_sk(skb);
3227 
3228 	if (!sk || !sk_fullsock(sk))
3229 		return 0;
3230 
3231 	return sock_cgroup_classid(&sk->sk_cgrp_data);
3232 }
3233 
3234 static const struct bpf_func_proto bpf_skb_cgroup_classid_proto = {
3235 	.func		= bpf_skb_cgroup_classid,
3236 	.gpl_only	= false,
3237 	.ret_type	= RET_INTEGER,
3238 	.arg1_type	= ARG_PTR_TO_CTX,
3239 };
3240 #endif
3241 
3242 BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
3243 {
3244 	return task_get_classid(skb);
3245 }
3246 
3247 static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
3248 	.func           = bpf_get_cgroup_classid,
3249 	.gpl_only       = false,
3250 	.ret_type       = RET_INTEGER,
3251 	.arg1_type      = ARG_PTR_TO_CTX,
3252 };
3253 
3254 BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
3255 {
3256 	return dst_tclassid(skb);
3257 }
3258 
3259 static const struct bpf_func_proto bpf_get_route_realm_proto = {
3260 	.func           = bpf_get_route_realm,
3261 	.gpl_only       = false,
3262 	.ret_type       = RET_INTEGER,
3263 	.arg1_type      = ARG_PTR_TO_CTX,
3264 };
3265 
3266 BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
3267 {
3268 	/* If skb_clear_hash() was called due to mangling, we can
3269 	 * trigger SW recalculation here. Later access to hash
3270 	 * can then use the inline skb->hash via context directly
3271 	 * instead of calling this helper again.
3272 	 */
3273 	return skb_get_hash(skb);
3274 }
3275 
3276 static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
3277 	.func		= bpf_get_hash_recalc,
3278 	.gpl_only	= false,
3279 	.ret_type	= RET_INTEGER,
3280 	.arg1_type	= ARG_PTR_TO_CTX,
3281 };
3282 
3283 BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
3284 {
3285 	/* After all direct packet write, this can be used once for
3286 	 * triggering a lazy recalc on next skb_get_hash() invocation.
3287 	 */
3288 	skb_clear_hash(skb);
3289 	return 0;
3290 }
3291 
3292 static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
3293 	.func		= bpf_set_hash_invalid,
3294 	.gpl_only	= false,
3295 	.ret_type	= RET_INTEGER,
3296 	.arg1_type	= ARG_PTR_TO_CTX,
3297 };
3298 
3299 BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
3300 {
3301 	/* Set user specified hash as L4(+), so that it gets returned
3302 	 * on skb_get_hash() call unless BPF prog later on triggers a
3303 	 * skb_clear_hash().
3304 	 */
3305 	__skb_set_sw_hash(skb, hash, true);
3306 	return 0;
3307 }
3308 
3309 static const struct bpf_func_proto bpf_set_hash_proto = {
3310 	.func		= bpf_set_hash,
3311 	.gpl_only	= false,
3312 	.ret_type	= RET_INTEGER,
3313 	.arg1_type	= ARG_PTR_TO_CTX,
3314 	.arg2_type	= ARG_ANYTHING,
3315 };
3316 
3317 BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
3318 	   u16, vlan_tci)
3319 {
3320 	int ret;
3321 
3322 	if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
3323 		     vlan_proto != htons(ETH_P_8021AD)))
3324 		vlan_proto = htons(ETH_P_8021Q);
3325 
3326 	bpf_push_mac_rcsum(skb);
3327 	ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
3328 	bpf_pull_mac_rcsum(skb);
3329 	skb_reset_mac_len(skb);
3330 
3331 	bpf_compute_data_pointers(skb);
3332 	return ret;
3333 }
3334 
3335 static const struct bpf_func_proto bpf_skb_vlan_push_proto = {
3336 	.func           = bpf_skb_vlan_push,
3337 	.gpl_only       = false,
3338 	.ret_type       = RET_INTEGER,
3339 	.arg1_type      = ARG_PTR_TO_CTX,
3340 	.arg2_type      = ARG_ANYTHING,
3341 	.arg3_type      = ARG_ANYTHING,
3342 };
3343 
3344 BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
3345 {
3346 	int ret;
3347 
3348 	bpf_push_mac_rcsum(skb);
3349 	ret = skb_vlan_pop(skb);
3350 	bpf_pull_mac_rcsum(skb);
3351 
3352 	bpf_compute_data_pointers(skb);
3353 	return ret;
3354 }
3355 
3356 static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
3357 	.func           = bpf_skb_vlan_pop,
3358 	.gpl_only       = false,
3359 	.ret_type       = RET_INTEGER,
3360 	.arg1_type      = ARG_PTR_TO_CTX,
3361 };
3362 
3363 static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
3364 {
3365 	/* Caller already did skb_cow() with meta_len+len as headroom,
3366 	 * so no need to do it here.
3367 	 */
3368 	skb_push(skb, len);
3369 	skb_postpush_data_move(skb, len, off);
3370 	memset(skb->data + off, 0, len);
3371 
3372 	/* No skb_postpush_rcsum(skb, skb->data + off, len)
3373 	 * needed here as it does not change the skb->csum
3374 	 * result for checksum complete when summing over
3375 	 * zeroed blocks.
3376 	 */
3377 	return 0;
3378 }
3379 
3380 static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
3381 {
3382 	void *old_data;
3383 
3384 	/* skb_ensure_writable() is not needed here, as we're
3385 	 * already working on an uncloned skb.
3386 	 */
3387 	if (unlikely(!pskb_may_pull(skb, off + len)))
3388 		return -ENOMEM;
3389 
3390 	old_data = skb->data;
3391 	__skb_pull(skb, len);
3392 	skb_postpull_rcsum(skb, old_data + off, len);
3393 	skb_postpull_data_move(skb, len, off);
3394 
3395 	return 0;
3396 }
3397 
3398 static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
3399 {
3400 	bool trans_same = skb->transport_header == skb->network_header;
3401 	int ret;
3402 
3403 	/* There's no need for __skb_push()/__skb_pull() pair to
3404 	 * get to the start of the mac header as we're guaranteed
3405 	 * to always start from here under eBPF.
3406 	 */
3407 	ret = bpf_skb_generic_push(skb, off, len);
3408 	if (likely(!ret)) {
3409 		skb->mac_header -= len;
3410 		skb->network_header -= len;
3411 		if (trans_same)
3412 			skb->transport_header = skb->network_header;
3413 	}
3414 
3415 	return ret;
3416 }
3417 
3418 static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
3419 {
3420 	bool trans_same = skb->transport_header == skb->network_header;
3421 	int ret;
3422 
3423 	/* Same here, __skb_push()/__skb_pull() pair not needed. */
3424 	ret = bpf_skb_generic_pop(skb, off, len);
3425 	if (likely(!ret)) {
3426 		skb->mac_header += len;
3427 		skb->network_header += len;
3428 		if (trans_same)
3429 			skb->transport_header = skb->network_header;
3430 	}
3431 
3432 	return ret;
3433 }
3434 
3435 static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
3436 {
3437 	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
3438 	const u8 meta_len = skb_metadata_len(skb);
3439 	u32 off = skb_mac_header_len(skb);
3440 	int ret;
3441 
3442 	ret = skb_cow(skb, meta_len + len_diff);
3443 	if (unlikely(ret < 0))
3444 		return ret;
3445 
3446 	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
3447 	if (unlikely(ret < 0))
3448 		return ret;
3449 
3450 	if (skb_is_gso(skb)) {
3451 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3452 
3453 		/* SKB_GSO_TCPV4 needs to be changed into SKB_GSO_TCPV6. */
3454 		if (shinfo->gso_type & SKB_GSO_TCPV4) {
3455 			shinfo->gso_type &= ~SKB_GSO_TCPV4;
3456 			shinfo->gso_type |=  SKB_GSO_TCPV6;
3457 		}
3458 		shinfo->gso_type |=  SKB_GSO_DODGY;
3459 	}
3460 
3461 	skb->protocol = htons(ETH_P_IPV6);
3462 	skb_clear_hash(skb);
3463 
3464 	return 0;
3465 }
3466 
3467 static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
3468 {
3469 	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
3470 	u32 off = skb_mac_header_len(skb);
3471 	int ret;
3472 
3473 	ret = skb_unclone(skb, GFP_ATOMIC);
3474 	if (unlikely(ret < 0))
3475 		return ret;
3476 
3477 	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3478 	if (unlikely(ret < 0))
3479 		return ret;
3480 
3481 	if (skb_is_gso(skb)) {
3482 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3483 
3484 		/* SKB_GSO_TCPV6 needs to be changed into SKB_GSO_TCPV4. */
3485 		if (shinfo->gso_type & SKB_GSO_TCPV6) {
3486 			shinfo->gso_type &= ~SKB_GSO_TCPV6;
3487 			shinfo->gso_type |=  SKB_GSO_TCPV4;
3488 		}
3489 		shinfo->gso_type |=  SKB_GSO_DODGY;
3490 	}
3491 
3492 	skb->protocol = htons(ETH_P_IP);
3493 	skb_clear_hash(skb);
3494 
3495 	return 0;
3496 }
3497 
3498 static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
3499 {
3500 	__be16 from_proto = skb->protocol;
3501 
3502 	if (from_proto == htons(ETH_P_IP) &&
3503 	      to_proto == htons(ETH_P_IPV6))
3504 		return bpf_skb_proto_4_to_6(skb);
3505 
3506 	if (from_proto == htons(ETH_P_IPV6) &&
3507 	      to_proto == htons(ETH_P_IP))
3508 		return bpf_skb_proto_6_to_4(skb);
3509 
3510 	return -ENOTSUPP;
3511 }
3512 
3513 BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
3514 	   u64, flags)
3515 {
3516 	int ret;
3517 
3518 	if (unlikely(flags))
3519 		return -EINVAL;
3520 
3521 	/* General idea is that this helper does the basic groundwork
3522 	 * needed for changing the protocol, and eBPF program fills the
3523 	 * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
3524 	 * and other helpers, rather than passing a raw buffer here.
3525 	 *
3526 	 * The rationale is to keep this minimal and without a need to
3527 	 * deal with raw packet data. F.e. even if we would pass buffers
3528 	 * here, the program still needs to call the bpf_lX_csum_replace()
3529 	 * helpers anyway. Plus, this way we keep also separation of
3530 	 * concerns, since f.e. bpf_skb_store_bytes() should only take
3531 	 * care of stores.
3532 	 *
3533 	 * Currently, additional options and extension header space are
3534 	 * not supported, but flags register is reserved so we can adapt
3535 	 * that. For offloads, we mark packet as dodgy, so that headers
3536 	 * need to be verified first.
3537 	 */
3538 	ret = bpf_skb_proto_xlat(skb, proto);
3539 	bpf_compute_data_pointers(skb);
3540 	if (ret)
3541 		return ret;
3542 
3543 	if (skb_valid_dst(skb))
3544 		skb_dst_drop(skb);
3545 
3546 	return 0;
3547 }
3548 
3549 static const struct bpf_func_proto bpf_skb_change_proto_proto = {
3550 	.func		= bpf_skb_change_proto,
3551 	.gpl_only	= false,
3552 	.ret_type	= RET_INTEGER,
3553 	.arg1_type	= ARG_PTR_TO_CTX,
3554 	.arg2_type	= ARG_ANYTHING,
3555 	.arg3_type	= ARG_ANYTHING,
3556 };
3557 
3558 BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
3559 {
3560 	/* We only allow a restricted subset to be changed for now. */
3561 	if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
3562 		     !skb_pkt_type_ok(pkt_type)))
3563 		return -EINVAL;
3564 
3565 	skb->pkt_type = pkt_type;
3566 	return 0;
3567 }
3568 
3569 static const struct bpf_func_proto bpf_skb_change_type_proto = {
3570 	.func		= bpf_skb_change_type,
3571 	.gpl_only	= false,
3572 	.ret_type	= RET_INTEGER,
3573 	.arg1_type	= ARG_PTR_TO_CTX,
3574 	.arg2_type	= ARG_ANYTHING,
3575 };
3576 
3577 static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
3578 {
3579 	switch (skb->protocol) {
3580 	case htons(ETH_P_IP):
3581 		return sizeof(struct iphdr);
3582 	case htons(ETH_P_IPV6):
3583 		return sizeof(struct ipv6hdr);
3584 	default:
3585 		return ~0U;
3586 	}
3587 }
3588 
3589 #define BPF_F_ADJ_ROOM_ENCAP_L3_MASK	(BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 | \
3590 					 BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3591 
3592 #define BPF_F_ADJ_ROOM_DECAP_L3_MASK	(BPF_F_ADJ_ROOM_DECAP_L3_IPV4 | \
3593 					 BPF_F_ADJ_ROOM_DECAP_L3_IPV6)
3594 
3595 #define BPF_F_ADJ_ROOM_DECAP_L4_MASK	(BPF_F_ADJ_ROOM_DECAP_L4_UDP | \
3596 					 BPF_F_ADJ_ROOM_DECAP_L4_GRE)
3597 
3598 #define BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK	(BPF_F_ADJ_ROOM_DECAP_IPXIP4 | \
3599 					 BPF_F_ADJ_ROOM_DECAP_IPXIP6)
3600 
3601 #define BPF_F_ADJ_ROOM_ENCAP_MASK	(BPF_F_ADJ_ROOM_ENCAP_L3_MASK | \
3602 					 BPF_F_ADJ_ROOM_ENCAP_L4_GRE | \
3603 					 BPF_F_ADJ_ROOM_ENCAP_L4_UDP | \
3604 					 BPF_F_ADJ_ROOM_ENCAP_L2_ETH | \
3605 					 BPF_F_ADJ_ROOM_ENCAP_L2( \
3606 					  BPF_ADJ_ROOM_ENCAP_L2_MASK))
3607 
3608 #define BPF_F_ADJ_ROOM_DECAP_MASK	(BPF_F_ADJ_ROOM_DECAP_L3_MASK | \
3609 					 BPF_F_ADJ_ROOM_DECAP_L4_MASK | \
3610 					 BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK)
3611 
3612 #define BPF_F_ADJ_ROOM_MASK		(BPF_F_ADJ_ROOM_FIXED_GSO | \
3613 					 BPF_F_ADJ_ROOM_ENCAP_MASK | \
3614 					 BPF_F_ADJ_ROOM_DECAP_MASK | \
3615 					 BPF_F_ADJ_ROOM_NO_CSUM_RESET)
3616 
3617 static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff,
3618 			    u64 flags)
3619 {
3620 	u8 inner_mac_len = flags >> BPF_ADJ_ROOM_ENCAP_L2_SHIFT;
3621 	bool encap = flags & BPF_F_ADJ_ROOM_ENCAP_L3_MASK;
3622 	u16 mac_len = 0, inner_net = 0, inner_trans = 0;
3623 	const u8 meta_len = skb_metadata_len(skb);
3624 	unsigned int gso_type = SKB_GSO_DODGY;
3625 	int ret;
3626 
3627 	if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3628 		/* udp gso_size delineates datagrams, only allow if fixed */
3629 		if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3630 		    !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3631 			return -ENOTSUPP;
3632 	}
3633 
3634 	/*
3635 	 * The MSS is lowered by len_diff. Leave the least that the stack lets a
3636 	 * TCP GSO packet have, or gso_segs can overflow.
3637 	 */
3638 	if (skb_is_gso(skb) && !(flags & BPF_F_ADJ_ROOM_FIXED_GSO) &&
3639 	    skb_shinfo(skb)->gso_size < len_diff + TCP_MIN_GSO_SIZE)
3640 		return -ENOTSUPP;
3641 
3642 	ret = skb_cow_head(skb, meta_len + len_diff);
3643 	if (unlikely(ret < 0))
3644 		return ret;
3645 
3646 	if (encap) {
3647 		if (skb->protocol != htons(ETH_P_IP) &&
3648 		    skb->protocol != htons(ETH_P_IPV6))
3649 			return -ENOTSUPP;
3650 
3651 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 &&
3652 		    flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3653 			return -EINVAL;
3654 
3655 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE &&
3656 		    flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3657 			return -EINVAL;
3658 
3659 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L2_ETH &&
3660 		    inner_mac_len < ETH_HLEN)
3661 			return -EINVAL;
3662 
3663 		if (skb->encapsulation)
3664 			return -EALREADY;
3665 
3666 		mac_len = skb->network_header - skb->mac_header;
3667 		inner_net = skb->network_header;
3668 		if (inner_mac_len > len_diff)
3669 			return -EINVAL;
3670 		inner_trans = skb->transport_header;
3671 	}
3672 
3673 	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
3674 	if (unlikely(ret < 0))
3675 		return ret;
3676 
3677 	if (encap) {
3678 		skb->inner_mac_header = inner_net - inner_mac_len;
3679 		skb->inner_network_header = inner_net;
3680 		skb->inner_transport_header = inner_trans;
3681 
3682 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L2_ETH)
3683 			skb_set_inner_protocol(skb, htons(ETH_P_TEB));
3684 		else
3685 			skb_set_inner_protocol(skb, skb->protocol);
3686 
3687 		skb->encapsulation = 1;
3688 		skb_set_network_header(skb, mac_len);
3689 
3690 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3691 			gso_type |= SKB_GSO_UDP_TUNNEL;
3692 		else if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE)
3693 			gso_type |= SKB_GSO_GRE;
3694 		else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3695 			gso_type |= SKB_GSO_IPXIP6;
3696 		else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3697 			gso_type |= SKB_GSO_IPXIP4;
3698 
3699 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE ||
3700 		    flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP) {
3701 			int nh_len = flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 ?
3702 					sizeof(struct ipv6hdr) :
3703 					sizeof(struct iphdr);
3704 
3705 			skb_set_transport_header(skb, mac_len + nh_len);
3706 		}
3707 
3708 		/* Match skb->protocol to new outer l3 protocol */
3709 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3710 			skb->protocol = htons(ETH_P_IPV6);
3711 		else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3712 			skb->protocol = htons(ETH_P_IP);
3713 
3714 		if (skb_valid_dst(skb))
3715 			skb_dst_drop(skb);
3716 	}
3717 
3718 	if (skb_is_gso(skb)) {
3719 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3720 
3721 		/* Header must be checked, and gso_segs recomputed. */
3722 		shinfo->gso_type |= gso_type;
3723 		shinfo->gso_segs = 0;
3724 
3725 		/* Due to header growth, MSS needs to be downgraded.
3726 		 * There is a BUG_ON() when segmenting the frag_list with
3727 		 * head_frag true, so linearize the skb after downgrading
3728 		 * the MSS.
3729 		 */
3730 		if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO)) {
3731 			skb_decrease_gso_size(shinfo, len_diff);
3732 			if (shinfo->frag_list)
3733 				return skb_linearize(skb);
3734 		}
3735 	}
3736 
3737 	return 0;
3738 }
3739 
3740 static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff,
3741 			      u64 flags)
3742 {
3743 	bool decap = flags & BPF_F_ADJ_ROOM_DECAP_L3_MASK;
3744 	int ret;
3745 
3746 	if (unlikely(flags & ~(BPF_F_ADJ_ROOM_DECAP_MASK |
3747 			       BPF_F_ADJ_ROOM_FIXED_GSO |
3748 			       BPF_F_ADJ_ROOM_NO_CSUM_RESET)))
3749 		return -EINVAL;
3750 
3751 	if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3752 		/* udp gso_size delineates datagrams, only allow if fixed */
3753 		if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3754 		    !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3755 			return -ENOTSUPP;
3756 	}
3757 
3758 	ret = skb_unclone(skb, GFP_ATOMIC);
3759 	if (unlikely(ret < 0))
3760 		return ret;
3761 
3762 	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3763 	if (unlikely(ret < 0))
3764 		return ret;
3765 
3766 	if (decap) {
3767 		/* Match skb->protocol to new outer l3 protocol */
3768 		if (flags & BPF_F_ADJ_ROOM_DECAP_L3_IPV6)
3769 			skb->protocol = htons(ETH_P_IPV6);
3770 		else if (flags & BPF_F_ADJ_ROOM_DECAP_L3_IPV4)
3771 			skb->protocol = htons(ETH_P_IP);
3772 
3773 		if (skb_valid_dst(skb))
3774 			skb_dst_drop(skb);
3775 	}
3776 
3777 	if (skb_is_gso(skb)) {
3778 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3779 
3780 		/* Due to header shrink, MSS can be upgraded. */
3781 		if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3782 			skb_increase_gso_size(shinfo, len_diff);
3783 
3784 		/* Selective GSO flag clearing based on decap type.
3785 		 * Only clear the flags for the tunnel layer being removed.
3786 		 */
3787 		if ((flags & BPF_F_ADJ_ROOM_DECAP_L4_UDP) &&
3788 		    (shinfo->gso_type & (SKB_GSO_UDP_TUNNEL |
3789 					 SKB_GSO_UDP_TUNNEL_CSUM)))
3790 			shinfo->gso_type &= ~(SKB_GSO_UDP_TUNNEL |
3791 					      SKB_GSO_UDP_TUNNEL_CSUM);
3792 		if ((flags & BPF_F_ADJ_ROOM_DECAP_L4_GRE) &&
3793 		    (shinfo->gso_type & (SKB_GSO_GRE | SKB_GSO_GRE_CSUM)))
3794 			shinfo->gso_type &= ~(SKB_GSO_GRE |
3795 					      SKB_GSO_GRE_CSUM);
3796 		if ((flags & BPF_F_ADJ_ROOM_DECAP_IPXIP4) &&
3797 		    (shinfo->gso_type & SKB_GSO_IPXIP4))
3798 			shinfo->gso_type &= ~SKB_GSO_IPXIP4;
3799 		if ((flags & BPF_F_ADJ_ROOM_DECAP_IPXIP6) &&
3800 		    (shinfo->gso_type & SKB_GSO_IPXIP6))
3801 			shinfo->gso_type &= ~SKB_GSO_IPXIP6;
3802 
3803 		/* Clear encapsulation flag only when no tunnel GSO flags remain */
3804 		if (flags & (BPF_F_ADJ_ROOM_DECAP_L4_MASK |
3805 			     BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK)) {
3806 			if (!(shinfo->gso_type & (SKB_GSO_UDP_TUNNEL |
3807 						  SKB_GSO_UDP_TUNNEL_CSUM |
3808 						  SKB_GSO_GRE |
3809 						  SKB_GSO_GRE_CSUM |
3810 						  SKB_GSO_IPXIP4 |
3811 						  SKB_GSO_IPXIP6 |
3812 						  SKB_GSO_ESP)))
3813 				if (skb->encapsulation)
3814 					skb->encapsulation = 0;
3815 		}
3816 
3817 		/* Header must be checked, and gso_segs recomputed. */
3818 		shinfo->gso_type |= SKB_GSO_DODGY;
3819 		shinfo->gso_segs = 0;
3820 	} else {
3821 		/* For non-GSO packets, clear encapsulation if decap flags are set */
3822 		if ((flags & (BPF_F_ADJ_ROOM_DECAP_L4_MASK |
3823 			      BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK)) &&
3824 		    skb->encapsulation)
3825 			skb->encapsulation = 0;
3826 	}
3827 
3828 	return 0;
3829 }
3830 
3831 #define BPF_SKB_MAX_LEN SKB_MAX_ALLOC
3832 
3833 BPF_CALL_4(sk_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3834 	   u32, mode, u64, flags)
3835 {
3836 	u32 len_diff_abs = abs(len_diff);
3837 	bool shrink = len_diff < 0;
3838 	int ret = 0;
3839 
3840 	if (unlikely(flags || mode))
3841 		return -EINVAL;
3842 	if (unlikely(len_diff_abs > 0xfffU))
3843 		return -EFAULT;
3844 
3845 	if (!shrink) {
3846 		ret = skb_cow(skb, len_diff);
3847 		if (unlikely(ret < 0))
3848 			return ret;
3849 		__skb_push(skb, len_diff_abs);
3850 		memset(skb->data, 0, len_diff_abs);
3851 	} else {
3852 		if (unlikely(!pskb_may_pull(skb, len_diff_abs)))
3853 			return -ENOMEM;
3854 		__skb_pull(skb, len_diff_abs);
3855 	}
3856 	if (tls_sw_has_ctx_rx(skb->sk)) {
3857 		struct strp_msg *rxm = strp_msg(skb);
3858 
3859 		rxm->full_len += len_diff;
3860 	}
3861 	return ret;
3862 }
3863 
3864 static const struct bpf_func_proto sk_skb_adjust_room_proto = {
3865 	.func		= sk_skb_adjust_room,
3866 	.gpl_only	= false,
3867 	.ret_type	= RET_INTEGER,
3868 	.arg1_type	= ARG_PTR_TO_CTX,
3869 	.arg2_type	= ARG_ANYTHING,
3870 	.arg3_type	= ARG_ANYTHING,
3871 	.arg4_type	= ARG_ANYTHING,
3872 };
3873 
3874 BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3875 	   u32, mode, u64, flags)
3876 {
3877 	u32 len_cur, len_diff_abs = abs(len_diff);
3878 	u32 len_min = bpf_skb_net_base_len(skb);
3879 	u32 len_max = BPF_SKB_MAX_LEN;
3880 	__be16 proto = skb->protocol;
3881 	bool shrink = len_diff < 0;
3882 	u32 off;
3883 	int ret;
3884 
3885 	if (unlikely(flags & ~BPF_F_ADJ_ROOM_MASK))
3886 		return -EINVAL;
3887 	if (unlikely(len_diff_abs > 0xfffU))
3888 		return -EFAULT;
3889 	if (unlikely(proto != htons(ETH_P_IP) &&
3890 		     proto != htons(ETH_P_IPV6)))
3891 		return -ENOTSUPP;
3892 
3893 	off = skb_mac_header_len(skb);
3894 	switch (mode) {
3895 	case BPF_ADJ_ROOM_NET:
3896 		off += bpf_skb_net_base_len(skb);
3897 		break;
3898 	case BPF_ADJ_ROOM_MAC:
3899 		break;
3900 	default:
3901 		return -ENOTSUPP;
3902 	}
3903 
3904 	if (flags & BPF_F_ADJ_ROOM_DECAP_MASK) {
3905 		u32 len_decap_min = 0;
3906 
3907 		if (!shrink)
3908 			return -EINVAL;
3909 
3910 		/* Reject mutually exclusive decap flag pairs. */
3911 		if ((flags & BPF_F_ADJ_ROOM_DECAP_L3_MASK) ==
3912 		    BPF_F_ADJ_ROOM_DECAP_L3_MASK)
3913 			return -EINVAL;
3914 
3915 		if ((flags & BPF_F_ADJ_ROOM_DECAP_L4_MASK) ==
3916 		    BPF_F_ADJ_ROOM_DECAP_L4_MASK)
3917 			return -EINVAL;
3918 
3919 		if ((flags & BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK) ==
3920 		    BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK)
3921 			return -EINVAL;
3922 
3923 		/* Reject mutually exclusive decap tunnel type flags. */
3924 		if ((flags & BPF_F_ADJ_ROOM_DECAP_L4_MASK) &&
3925 		    (flags & BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK))
3926 			return -EINVAL;
3927 
3928 		if (flags & BPF_F_ADJ_ROOM_DECAP_L4_MASK)
3929 			len_decap_min += bpf_skb_net_base_len(skb);
3930 
3931 		if (flags & BPF_F_ADJ_ROOM_DECAP_L4_UDP)
3932 			len_decap_min += sizeof(struct udphdr);
3933 
3934 		if (flags & BPF_F_ADJ_ROOM_DECAP_L4_GRE)
3935 			len_decap_min += sizeof(struct gre_base_hdr);
3936 
3937 		if (flags & BPF_F_ADJ_ROOM_DECAP_IPXIP4)
3938 			len_decap_min += sizeof(struct iphdr);
3939 
3940 		if (flags & BPF_F_ADJ_ROOM_DECAP_IPXIP6)
3941 			len_decap_min += sizeof(struct ipv6hdr);
3942 
3943 		if (len_diff_abs < len_decap_min)
3944 			return -EINVAL;
3945 
3946 		if (flags & BPF_F_ADJ_ROOM_DECAP_L3_IPV4)
3947 			len_min = sizeof(struct iphdr);
3948 
3949 		if (flags & BPF_F_ADJ_ROOM_DECAP_L3_IPV6)
3950 			len_min = sizeof(struct ipv6hdr);
3951 	}
3952 
3953 	len_cur = skb->len - skb_network_offset(skb);
3954 	if ((shrink && (len_diff_abs >= len_cur ||
3955 			len_cur - len_diff_abs < len_min)) ||
3956 	    (!shrink && (skb->len + len_diff_abs > len_max &&
3957 			 !skb_is_gso(skb))))
3958 		return -ENOTSUPP;
3959 
3960 	ret = shrink ? bpf_skb_net_shrink(skb, off, len_diff_abs, flags) :
3961 		       bpf_skb_net_grow(skb, off, len_diff_abs, flags);
3962 	if (!ret && !(flags & BPF_F_ADJ_ROOM_NO_CSUM_RESET))
3963 		__skb_reset_checksum_unnecessary(skb);
3964 
3965 	bpf_compute_data_pointers(skb);
3966 	return ret;
3967 }
3968 
3969 static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
3970 	.func		= bpf_skb_adjust_room,
3971 	.gpl_only	= false,
3972 	.ret_type	= RET_INTEGER,
3973 	.arg1_type	= ARG_PTR_TO_CTX,
3974 	.arg2_type	= ARG_ANYTHING,
3975 	.arg3_type	= ARG_ANYTHING,
3976 	.arg4_type	= ARG_ANYTHING,
3977 };
3978 
3979 static u32 __bpf_skb_min_len(const struct sk_buff *skb)
3980 {
3981 	int offset = skb_network_offset(skb);
3982 	u32 min_len = 0;
3983 
3984 	if (offset > 0)
3985 		min_len = offset;
3986 	if (skb_transport_header_was_set(skb)) {
3987 		offset = skb_transport_offset(skb);
3988 		if (offset > 0)
3989 			min_len = offset;
3990 	}
3991 	return min_len;
3992 }
3993 
3994 static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
3995 {
3996 	unsigned int old_len = skb->len;
3997 	int ret;
3998 
3999 	ret = __skb_grow_rcsum(skb, new_len);
4000 	if (!ret)
4001 		memset(skb->data + old_len, 0, new_len - old_len);
4002 	return ret;
4003 }
4004 
4005 static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
4006 {
4007 	if (skb->ip_summed == CHECKSUM_PARTIAL &&
4008 	    new_len < skb_checksum_start_offset(skb) + skb->csum_offset +
4009 		      sizeof(__sum16))
4010 		skb->ip_summed = CHECKSUM_NONE;
4011 
4012 	return __skb_trim_rcsum(skb, new_len);
4013 }
4014 
4015 static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
4016 					u64 flags)
4017 {
4018 	u32 max_len = BPF_SKB_MAX_LEN;
4019 	u32 min_len = __bpf_skb_min_len(skb);
4020 	int ret;
4021 
4022 	if (unlikely(flags || new_len > max_len || new_len < min_len))
4023 		return -EINVAL;
4024 	if (skb->encapsulation)
4025 		return -ENOTSUPP;
4026 
4027 	/* The basic idea of this helper is that it's performing the
4028 	 * needed work to either grow or trim an skb, and eBPF program
4029 	 * rewrites the rest via helpers like bpf_skb_store_bytes(),
4030 	 * bpf_lX_csum_replace() and others rather than passing a raw
4031 	 * buffer here. This one is a slow path helper and intended
4032 	 * for replies with control messages.
4033 	 *
4034 	 * Like in bpf_skb_change_proto(), we want to keep this rather
4035 	 * minimal and without protocol specifics so that we are able
4036 	 * to separate concerns as in bpf_skb_store_bytes() should only
4037 	 * be the one responsible for writing buffers.
4038 	 *
4039 	 * It's really expected to be a slow path operation here for
4040 	 * control message replies, so we're implicitly linearizing,
4041 	 * uncloning and drop offloads from the skb by this.
4042 	 */
4043 	ret = __bpf_try_make_writable(skb, skb->len);
4044 	if (!ret) {
4045 		if (new_len > skb->len)
4046 			ret = bpf_skb_grow_rcsum(skb, new_len);
4047 		else if (new_len < skb->len)
4048 			ret = bpf_skb_trim_rcsum(skb, new_len);
4049 		if (!ret && skb_is_gso(skb))
4050 			skb_gso_reset(skb);
4051 	}
4052 	return ret;
4053 }
4054 
4055 BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
4056 	   u64, flags)
4057 {
4058 	int ret = __bpf_skb_change_tail(skb, new_len, flags);
4059 
4060 	bpf_compute_data_pointers(skb);
4061 	return ret;
4062 }
4063 
4064 static const struct bpf_func_proto bpf_skb_change_tail_proto = {
4065 	.func		= bpf_skb_change_tail,
4066 	.gpl_only	= false,
4067 	.ret_type	= RET_INTEGER,
4068 	.arg1_type	= ARG_PTR_TO_CTX,
4069 	.arg2_type	= ARG_ANYTHING,
4070 	.arg3_type	= ARG_ANYTHING,
4071 };
4072 
4073 BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
4074 	   u64, flags)
4075 {
4076 	return __bpf_skb_change_tail(skb, new_len, flags);
4077 }
4078 
4079 static const struct bpf_func_proto sk_skb_change_tail_proto = {
4080 	.func		= sk_skb_change_tail,
4081 	.gpl_only	= false,
4082 	.ret_type	= RET_INTEGER,
4083 	.arg1_type	= ARG_PTR_TO_CTX,
4084 	.arg2_type	= ARG_ANYTHING,
4085 	.arg3_type	= ARG_ANYTHING,
4086 };
4087 
4088 static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
4089 					u64 flags)
4090 {
4091 	const u8 meta_len = skb_metadata_len(skb);
4092 	u32 max_len = BPF_SKB_MAX_LEN;
4093 	u32 new_len = skb->len + head_room;
4094 	int ret;
4095 
4096 	if (unlikely(flags || (int)head_room < 0 ||
4097 		     (!skb_is_gso(skb) && new_len > max_len) ||
4098 		     new_len < skb->len))
4099 		return -EINVAL;
4100 
4101 	ret = skb_cow(skb, meta_len + head_room);
4102 	if (likely(!ret)) {
4103 		/* Idea for this helper is that we currently only
4104 		 * allow to expand on mac header. This means that
4105 		 * skb->protocol network header, etc, stay as is.
4106 		 * Compared to bpf_skb_change_tail(), we're more
4107 		 * flexible due to not needing to linearize or
4108 		 * reset GSO. Intention for this helper is to be
4109 		 * used by an L3 skb that needs to push mac header
4110 		 * for redirection into L2 device.
4111 		 */
4112 		__skb_push(skb, head_room);
4113 		skb_postpush_data_move(skb, head_room, 0);
4114 		memset(skb->data, 0, head_room);
4115 		skb_reset_mac_header(skb);
4116 		skb_reset_mac_len(skb);
4117 	}
4118 
4119 	return ret;
4120 }
4121 
4122 BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
4123 	   u64, flags)
4124 {
4125 	int ret = __bpf_skb_change_head(skb, head_room, flags);
4126 
4127 	bpf_compute_data_pointers(skb);
4128 	return ret;
4129 }
4130 
4131 static const struct bpf_func_proto bpf_skb_change_head_proto = {
4132 	.func		= bpf_skb_change_head,
4133 	.gpl_only	= false,
4134 	.ret_type	= RET_INTEGER,
4135 	.arg1_type	= ARG_PTR_TO_CTX,
4136 	.arg2_type	= ARG_ANYTHING,
4137 	.arg3_type	= ARG_ANYTHING,
4138 };
4139 
4140 BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
4141 	   u64, flags)
4142 {
4143 	return __bpf_skb_change_head(skb, head_room, flags);
4144 }
4145 
4146 static const struct bpf_func_proto sk_skb_change_head_proto = {
4147 	.func		= sk_skb_change_head,
4148 	.gpl_only	= false,
4149 	.ret_type	= RET_INTEGER,
4150 	.arg1_type	= ARG_PTR_TO_CTX,
4151 	.arg2_type	= ARG_ANYTHING,
4152 	.arg3_type	= ARG_ANYTHING,
4153 };
4154 
4155 BPF_CALL_1(bpf_xdp_get_buff_len, struct xdp_buff*, xdp)
4156 {
4157 	return xdp_get_buff_len(xdp);
4158 }
4159 
4160 static const struct bpf_func_proto bpf_xdp_get_buff_len_proto = {
4161 	.func		= bpf_xdp_get_buff_len,
4162 	.gpl_only	= false,
4163 	.ret_type	= RET_INTEGER,
4164 	.arg1_type	= ARG_PTR_TO_CTX,
4165 };
4166 
4167 BTF_ID_LIST_SINGLE(bpf_xdp_get_buff_len_bpf_ids, struct, xdp_buff)
4168 
4169 const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto = {
4170 	.func		= bpf_xdp_get_buff_len,
4171 	.gpl_only	= false,
4172 	.arg1_type	= ARG_PTR_TO_BTF_ID,
4173 	.arg1_btf_id	= &bpf_xdp_get_buff_len_bpf_ids[0],
4174 };
4175 
4176 static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
4177 {
4178 	return xdp_data_meta_unsupported(xdp) ? 0 :
4179 	       xdp->data - xdp->data_meta;
4180 }
4181 
4182 BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
4183 {
4184 	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
4185 	unsigned long metalen = xdp_get_metalen(xdp);
4186 	void *data_start = xdp_frame_end + metalen;
4187 	void *data = xdp->data + offset;
4188 
4189 	if (unlikely(data < data_start ||
4190 		     data > xdp->data_end - ETH_HLEN))
4191 		return -EINVAL;
4192 
4193 	if (metalen)
4194 		memmove(xdp->data_meta + offset,
4195 			xdp->data_meta, metalen);
4196 	xdp->data_meta += offset;
4197 	xdp->data = data;
4198 
4199 	return 0;
4200 }
4201 
4202 static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
4203 	.func		= bpf_xdp_adjust_head,
4204 	.gpl_only	= false,
4205 	.ret_type	= RET_INTEGER,
4206 	.arg1_type	= ARG_PTR_TO_CTX,
4207 	.arg2_type	= ARG_ANYTHING,
4208 };
4209 
4210 void bpf_xdp_copy_buf(struct xdp_buff *xdp, unsigned long off,
4211 		      void *buf, unsigned long len, bool flush)
4212 {
4213 	unsigned long ptr_len, ptr_off = 0;
4214 	skb_frag_t *next_frag, *end_frag;
4215 	struct skb_shared_info *sinfo;
4216 	void *src, *dst;
4217 	u8 *ptr_buf;
4218 
4219 	if (likely(xdp->data_end - xdp->data >= off + len)) {
4220 		src = flush ? buf : xdp->data + off;
4221 		dst = flush ? xdp->data + off : buf;
4222 		memcpy(dst, src, len);
4223 		return;
4224 	}
4225 
4226 	sinfo = xdp_get_shared_info_from_buff(xdp);
4227 	end_frag = &sinfo->frags[sinfo->nr_frags];
4228 	next_frag = &sinfo->frags[0];
4229 
4230 	ptr_len = xdp->data_end - xdp->data;
4231 	ptr_buf = xdp->data;
4232 
4233 	while (true) {
4234 		if (off < ptr_off + ptr_len) {
4235 			unsigned long copy_off = off - ptr_off;
4236 			unsigned long copy_len = min(len, ptr_len - copy_off);
4237 
4238 			src = flush ? buf : ptr_buf + copy_off;
4239 			dst = flush ? ptr_buf + copy_off : buf;
4240 			memcpy(dst, src, copy_len);
4241 
4242 			off += copy_len;
4243 			len -= copy_len;
4244 			buf += copy_len;
4245 		}
4246 
4247 		if (!len || next_frag == end_frag)
4248 			break;
4249 
4250 		ptr_off += ptr_len;
4251 		ptr_buf = skb_frag_address(next_frag);
4252 		ptr_len = skb_frag_size(next_frag);
4253 		next_frag++;
4254 	}
4255 }
4256 
4257 void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len)
4258 {
4259 	u32 size = xdp->data_end - xdp->data;
4260 	struct skb_shared_info *sinfo;
4261 	void *addr = xdp->data;
4262 	int i;
4263 
4264 	if (unlikely(offset > 0xffff || len > 0xffff))
4265 		return ERR_PTR(-EFAULT);
4266 
4267 	if (unlikely(offset + len > xdp_get_buff_len(xdp)))
4268 		return ERR_PTR(-EINVAL);
4269 
4270 	if (likely(offset < size)) /* linear area */
4271 		goto out;
4272 
4273 	sinfo = xdp_get_shared_info_from_buff(xdp);
4274 	offset -= size;
4275 	for (i = 0; i < sinfo->nr_frags; i++) { /* paged area */
4276 		u32 frag_size = skb_frag_size(&sinfo->frags[i]);
4277 
4278 		if  (offset < frag_size) {
4279 			addr = skb_frag_address(&sinfo->frags[i]);
4280 			size = frag_size;
4281 			break;
4282 		}
4283 		offset -= frag_size;
4284 	}
4285 out:
4286 	return offset + len <= size ? addr + offset : NULL;
4287 }
4288 
4289 BPF_CALL_4(bpf_xdp_load_bytes, struct xdp_buff *, xdp, u32, offset,
4290 	   void *, buf, u32, len)
4291 {
4292 	void *ptr;
4293 
4294 	ptr = bpf_xdp_pointer(xdp, offset, len);
4295 	if (IS_ERR(ptr))
4296 		return PTR_ERR(ptr);
4297 
4298 	if (!ptr)
4299 		bpf_xdp_copy_buf(xdp, offset, buf, len, false);
4300 	else
4301 		memcpy(buf, ptr, len);
4302 
4303 	return 0;
4304 }
4305 
4306 static const struct bpf_func_proto bpf_xdp_load_bytes_proto = {
4307 	.func		= bpf_xdp_load_bytes,
4308 	.gpl_only	= false,
4309 	.ret_type	= RET_INTEGER,
4310 	.arg1_type	= ARG_PTR_TO_CTX,
4311 	.arg2_type	= ARG_ANYTHING,
4312 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
4313 	.arg4_type	= ARG_MEM_SIZE,
4314 };
4315 
4316 int __bpf_xdp_load_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len)
4317 {
4318 	return ____bpf_xdp_load_bytes(xdp, offset, buf, len);
4319 }
4320 
4321 BPF_CALL_4(bpf_xdp_store_bytes, struct xdp_buff *, xdp, u32, offset,
4322 	   void *, buf, u32, len)
4323 {
4324 	void *ptr;
4325 
4326 	ptr = bpf_xdp_pointer(xdp, offset, len);
4327 	if (IS_ERR(ptr))
4328 		return PTR_ERR(ptr);
4329 
4330 	if (!ptr)
4331 		bpf_xdp_copy_buf(xdp, offset, buf, len, true);
4332 	else
4333 		/* through a dynptr the source may be an overlapping slice */
4334 		memmove(ptr, buf, len);
4335 
4336 	return 0;
4337 }
4338 
4339 static const struct bpf_func_proto bpf_xdp_store_bytes_proto = {
4340 	.func		= bpf_xdp_store_bytes,
4341 	.gpl_only	= false,
4342 	.ret_type	= RET_INTEGER,
4343 	.arg1_type	= ARG_PTR_TO_CTX,
4344 	.arg2_type	= ARG_ANYTHING,
4345 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4346 	.arg4_type	= ARG_MEM_SIZE,
4347 };
4348 
4349 int __bpf_xdp_store_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len)
4350 {
4351 	return ____bpf_xdp_store_bytes(xdp, offset, buf, len);
4352 }
4353 
4354 static int bpf_xdp_frags_increase_tail(struct xdp_buff *xdp, int offset)
4355 {
4356 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
4357 	skb_frag_t *frag = &sinfo->frags[sinfo->nr_frags - 1];
4358 	struct xdp_rxq_info *rxq = xdp->rxq;
4359 	int tailroom;
4360 
4361 	if (!rxq->frag_size || rxq->frag_size > xdp->frame_sz)
4362 		return -EOPNOTSUPP;
4363 
4364 	tailroom = rxq->frag_size - skb_frag_size(frag) -
4365 		   skb_frag_off(frag) % rxq->frag_size;
4366 	WARN_ON_ONCE(tailroom < 0);
4367 	if (unlikely(offset > tailroom))
4368 		return -EINVAL;
4369 
4370 	memset(skb_frag_address(frag) + skb_frag_size(frag), 0, offset);
4371 	skb_frag_size_add(frag, offset);
4372 	sinfo->xdp_frags_size += offset;
4373 	if (rxq->mem.type == MEM_TYPE_XSK_BUFF_POOL)
4374 		xsk_buff_get_tail(xdp)->data_end += offset;
4375 
4376 	return 0;
4377 }
4378 
4379 static struct xdp_buff *bpf_xdp_shrink_data_zc(struct xdp_buff *xdp, int shrink,
4380 					       bool tail, bool release)
4381 {
4382 	struct xdp_buff *zc_frag = tail ? xsk_buff_get_tail(xdp) :
4383 					  xsk_buff_get_head(xdp);
4384 
4385 	if (release) {
4386 		xsk_buff_del_frag(zc_frag);
4387 	} else {
4388 		if (tail)
4389 			zc_frag->data_end -= shrink;
4390 		else
4391 			zc_frag->data += shrink;
4392 	}
4393 
4394 	return zc_frag;
4395 }
4396 
4397 static bool bpf_xdp_shrink_data(struct xdp_buff *xdp, skb_frag_t *frag,
4398 				int shrink, bool tail)
4399 {
4400 	enum xdp_mem_type mem_type = xdp->rxq->mem.type;
4401 	bool release = skb_frag_size(frag) == shrink;
4402 	netmem_ref netmem = skb_frag_netmem(frag);
4403 	struct xdp_buff *zc_frag = NULL;
4404 
4405 	if (mem_type == MEM_TYPE_XSK_BUFF_POOL) {
4406 		netmem = 0;
4407 		zc_frag = bpf_xdp_shrink_data_zc(xdp, shrink, tail, release);
4408 	}
4409 
4410 	if (release) {
4411 		__xdp_return(netmem, mem_type, false, zc_frag);
4412 	} else {
4413 		if (!tail)
4414 			skb_frag_off_add(frag, shrink);
4415 		skb_frag_size_sub(frag, shrink);
4416 	}
4417 
4418 	return release;
4419 }
4420 
4421 static int bpf_xdp_frags_shrink_tail(struct xdp_buff *xdp, int offset)
4422 {
4423 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
4424 	int i, n_frags_free = 0, len_free = 0;
4425 
4426 	if (unlikely(offset > (int)xdp_get_buff_len(xdp) - ETH_HLEN))
4427 		return -EINVAL;
4428 
4429 	for (i = sinfo->nr_frags - 1; i >= 0 && offset > 0; i--) {
4430 		skb_frag_t *frag = &sinfo->frags[i];
4431 		int shrink = min_t(int, offset, skb_frag_size(frag));
4432 
4433 		len_free += shrink;
4434 		offset -= shrink;
4435 		if (bpf_xdp_shrink_data(xdp, frag, shrink, true))
4436 			n_frags_free++;
4437 	}
4438 	sinfo->nr_frags -= n_frags_free;
4439 	sinfo->xdp_frags_size -= len_free;
4440 
4441 	if (unlikely(!sinfo->nr_frags)) {
4442 		xdp_buff_clear_frags_flag(xdp);
4443 		xdp_buff_clear_frag_pfmemalloc(xdp);
4444 		xdp->data_end -= offset;
4445 	}
4446 
4447 	return 0;
4448 }
4449 
4450 BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
4451 {
4452 	void *data_hard_end = xdp_data_hard_end(xdp); /* use xdp->frame_sz */
4453 	void *data_end = xdp->data_end + offset;
4454 
4455 	if (unlikely(xdp_buff_has_frags(xdp))) { /* non-linear xdp buff */
4456 		if (offset < 0)
4457 			return bpf_xdp_frags_shrink_tail(xdp, -offset);
4458 
4459 		return bpf_xdp_frags_increase_tail(xdp, offset);
4460 	}
4461 
4462 	/* Notice that xdp_data_hard_end have reserved some tailroom */
4463 	if (unlikely(data_end > data_hard_end))
4464 		return -EINVAL;
4465 
4466 	if (unlikely(data_end < xdp->data + ETH_HLEN))
4467 		return -EINVAL;
4468 
4469 	/* Clear memory area on grow, can contain uninit kernel memory */
4470 	if (offset > 0)
4471 		memset(xdp->data_end, 0, offset);
4472 
4473 	xdp->data_end = data_end;
4474 
4475 	return 0;
4476 }
4477 
4478 static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
4479 	.func		= bpf_xdp_adjust_tail,
4480 	.gpl_only	= false,
4481 	.ret_type	= RET_INTEGER,
4482 	.arg1_type	= ARG_PTR_TO_CTX,
4483 	.arg2_type	= ARG_ANYTHING,
4484 };
4485 
4486 BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
4487 {
4488 	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
4489 	void *meta = xdp->data_meta + offset;
4490 	unsigned long metalen = xdp->data - meta;
4491 
4492 	if (xdp_data_meta_unsupported(xdp))
4493 		return -ENOTSUPP;
4494 	if (unlikely(meta < xdp_frame_end ||
4495 		     meta > xdp->data))
4496 		return -EINVAL;
4497 	if (unlikely(xdp_metalen_invalid(metalen)))
4498 		return -EACCES;
4499 
4500 	xdp->data_meta = meta;
4501 
4502 	return 0;
4503 }
4504 
4505 static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
4506 	.func		= bpf_xdp_adjust_meta,
4507 	.gpl_only	= false,
4508 	.ret_type	= RET_INTEGER,
4509 	.arg1_type	= ARG_PTR_TO_CTX,
4510 	.arg2_type	= ARG_ANYTHING,
4511 };
4512 
4513 /**
4514  * DOC: xdp redirect
4515  *
4516  * XDP_REDIRECT works by a three-step process, implemented in the functions
4517  * below:
4518  *
4519  * 1. The bpf_redirect() and bpf_redirect_map() helpers will lookup the target
4520  *    of the redirect and store it (along with some other metadata) in a per-CPU
4521  *    struct bpf_redirect_info.
4522  *
4523  * 2. When the program returns the XDP_REDIRECT return code, the driver will
4524  *    call xdp_do_redirect() which will use the information in struct
4525  *    bpf_redirect_info to actually enqueue the frame into a map type-specific
4526  *    bulk queue structure.
4527  *
4528  * 3. Before exiting its NAPI poll loop, the driver will call
4529  *    xdp_do_flush(), which will flush all the different bulk queues,
4530  *    thus completing the redirect. Note that xdp_do_flush() must be
4531  *    called before napi_complete_done() in the driver, as the
4532  *    XDP_REDIRECT logic relies on being inside a single NAPI instance
4533  *    through to the xdp_do_flush() call for RCU protection of all
4534  *    in-kernel data structures.
4535  */
4536 /*
4537  * Pointers to the map entries will be kept around for this whole sequence of
4538  * steps, protected by RCU. However, there is no top-level rcu_read_lock() in
4539  * the core code; instead, the RCU protection relies on everything happening
4540  * inside a single NAPI poll sequence, which means it's between a pair of calls
4541  * to local_bh_disable()/local_bh_enable().
4542  *
4543  * The map entries are marked as __rcu and the map code makes sure to
4544  * dereference those pointers with rcu_dereference_check() in a way that works
4545  * for both sections that to hold an rcu_read_lock() and sections that are
4546  * called from NAPI without a separate rcu_read_lock(). The code below does not
4547  * use RCU annotations, but relies on those in the map code.
4548  */
4549 void xdp_do_flush(void)
4550 {
4551 	struct list_head *lh_map, *lh_dev, *lh_xsk;
4552 
4553 	bpf_net_ctx_get_all_used_flush_lists(&lh_map, &lh_dev, &lh_xsk);
4554 	if (lh_dev)
4555 		__dev_flush(lh_dev);
4556 	if (lh_map)
4557 		__cpu_map_flush(lh_map);
4558 	if (lh_xsk)
4559 		__xsk_map_flush(lh_xsk);
4560 }
4561 EXPORT_SYMBOL_GPL(xdp_do_flush);
4562 
4563 #if defined(CONFIG_DEBUG_NET) && defined(CONFIG_BPF_SYSCALL)
4564 void xdp_do_check_flushed(struct napi_struct *napi)
4565 {
4566 	struct list_head *lh_map, *lh_dev, *lh_xsk;
4567 	bool missed = false;
4568 
4569 	bpf_net_ctx_get_all_used_flush_lists(&lh_map, &lh_dev, &lh_xsk);
4570 	if (lh_dev) {
4571 		__dev_flush(lh_dev);
4572 		missed = true;
4573 	}
4574 	if (lh_map) {
4575 		__cpu_map_flush(lh_map);
4576 		missed = true;
4577 	}
4578 	if (lh_xsk) {
4579 		__xsk_map_flush(lh_xsk);
4580 		missed = true;
4581 	}
4582 
4583 	WARN_ONCE(missed, "Missing xdp_do_flush() invocation after NAPI by %ps\n",
4584 		  napi->poll);
4585 }
4586 #endif
4587 
4588 DEFINE_STATIC_KEY_FALSE(bpf_master_redirect_enabled_key);
4589 EXPORT_SYMBOL_GPL(bpf_master_redirect_enabled_key);
4590 
4591 u32 xdp_master_redirect(struct xdp_buff *xdp)
4592 {
4593 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4594 	struct net_device *master, *slave;
4595 
4596 	master = netdev_master_upper_dev_get_rcu(xdp->rxq->dev);
4597 	if (unlikely(!master || !(master->flags & IFF_UP)))
4598 		return XDP_ABORTED;
4599 	slave = master->netdev_ops->ndo_xdp_get_xmit_slave(master, xdp);
4600 	if (slave && slave != xdp->rxq->dev) {
4601 		/* The target device is different from the receiving device, so
4602 		 * redirect it to the new device.
4603 		 * Using XDP_REDIRECT gets the correct behaviour from XDP enabled
4604 		 * drivers to unmap the packet from their rx ring.
4605 		 */
4606 		ri->tgt_index = slave->ifindex;
4607 		ri->map_id = INT_MAX;
4608 		ri->map_type = BPF_MAP_TYPE_UNSPEC;
4609 		return XDP_REDIRECT;
4610 	}
4611 	return XDP_TX;
4612 }
4613 EXPORT_SYMBOL_GPL(xdp_master_redirect);
4614 
4615 static inline int __xdp_do_redirect_xsk(struct bpf_redirect_info *ri,
4616 					const struct net_device *dev,
4617 					struct xdp_buff *xdp,
4618 					const struct bpf_prog *xdp_prog)
4619 {
4620 	enum bpf_map_type map_type = ri->map_type;
4621 	void *fwd = ri->tgt_value;
4622 	u32 map_id = ri->map_id;
4623 	int err;
4624 
4625 	ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4626 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4627 
4628 	err = __xsk_map_redirect(fwd, xdp);
4629 	if (unlikely(err))
4630 		goto err;
4631 
4632 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4633 	return 0;
4634 err:
4635 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4636 	return err;
4637 }
4638 
4639 static __always_inline int
4640 __xdp_do_redirect_frame(struct bpf_redirect_info *ri, struct net_device *dev,
4641 			struct xdp_frame *xdpf,
4642 			const struct bpf_prog *xdp_prog)
4643 {
4644 	enum bpf_map_type map_type = ri->map_type;
4645 	void *fwd = ri->tgt_value;
4646 	u32 map_id = ri->map_id;
4647 	u32 flags = ri->flags;
4648 	struct bpf_map *map;
4649 	int err;
4650 
4651 	ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4652 	ri->flags = 0;
4653 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4654 
4655 	if (unlikely(!xdpf)) {
4656 		err = -EOVERFLOW;
4657 		goto err;
4658 	}
4659 
4660 	switch (map_type) {
4661 	case BPF_MAP_TYPE_DEVMAP:
4662 		fallthrough;
4663 	case BPF_MAP_TYPE_DEVMAP_HASH:
4664 		if (unlikely(flags & BPF_F_BROADCAST)) {
4665 			map = READ_ONCE(ri->map);
4666 
4667 			/* The map pointer is cleared when the map is being torn
4668 			 * down by dev_map_free()
4669 			 */
4670 			if (unlikely(!map)) {
4671 				err = -ENOENT;
4672 				break;
4673 			}
4674 
4675 			WRITE_ONCE(ri->map, NULL);
4676 			err = dev_map_enqueue_multi(xdpf, dev, map,
4677 						    flags & BPF_F_EXCLUDE_INGRESS);
4678 		} else {
4679 			err = dev_map_enqueue(fwd, xdpf, dev);
4680 		}
4681 		break;
4682 	case BPF_MAP_TYPE_CPUMAP:
4683 		err = cpu_map_enqueue(fwd, xdpf, dev);
4684 		break;
4685 	case BPF_MAP_TYPE_UNSPEC:
4686 		if (map_id == INT_MAX) {
4687 			fwd = dev_get_by_index_rcu(dev_net(dev), ri->tgt_index);
4688 			if (unlikely(!fwd)) {
4689 				err = -EINVAL;
4690 				break;
4691 			}
4692 			err = dev_xdp_enqueue(fwd, xdpf, dev);
4693 			break;
4694 		}
4695 		fallthrough;
4696 	default:
4697 		err = -EBADRQC;
4698 	}
4699 
4700 	if (unlikely(err))
4701 		goto err;
4702 
4703 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4704 	return 0;
4705 err:
4706 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4707 	return err;
4708 }
4709 
4710 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
4711 		    const struct bpf_prog *xdp_prog)
4712 {
4713 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4714 	enum bpf_map_type map_type = ri->map_type;
4715 
4716 	if (map_type == BPF_MAP_TYPE_XSKMAP)
4717 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
4718 
4719 	return __xdp_do_redirect_frame(ri, dev, xdp_convert_buff_to_frame(xdp),
4720 				       xdp_prog);
4721 }
4722 EXPORT_SYMBOL_GPL(xdp_do_redirect);
4723 
4724 int xdp_do_redirect_frame(struct net_device *dev, struct xdp_buff *xdp,
4725 			  struct xdp_frame *xdpf,
4726 			  const struct bpf_prog *xdp_prog)
4727 {
4728 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4729 	enum bpf_map_type map_type = ri->map_type;
4730 
4731 	if (map_type == BPF_MAP_TYPE_XSKMAP)
4732 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
4733 
4734 	return __xdp_do_redirect_frame(ri, dev, xdpf, xdp_prog);
4735 }
4736 EXPORT_SYMBOL_GPL(xdp_do_redirect_frame);
4737 
4738 static int xdp_do_generic_redirect_map(struct net_device *dev,
4739 				       struct sk_buff *skb,
4740 				       struct xdp_buff *xdp,
4741 				       const struct bpf_prog *xdp_prog,
4742 				       void *fwd, enum bpf_map_type map_type,
4743 				       u32 map_id, u32 flags)
4744 {
4745 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4746 	struct bpf_map *map;
4747 	int err;
4748 
4749 	switch (map_type) {
4750 	case BPF_MAP_TYPE_DEVMAP:
4751 		fallthrough;
4752 	case BPF_MAP_TYPE_DEVMAP_HASH:
4753 		if (unlikely(flags & BPF_F_BROADCAST)) {
4754 			map = READ_ONCE(ri->map);
4755 
4756 			/* The map pointer is cleared when the map is being torn
4757 			 * down by dev_map_free()
4758 			 */
4759 			if (unlikely(!map)) {
4760 				err = -ENOENT;
4761 				break;
4762 			}
4763 
4764 			WRITE_ONCE(ri->map, NULL);
4765 			err = dev_map_redirect_multi(dev, skb, xdp_prog, map,
4766 						     flags & BPF_F_EXCLUDE_INGRESS);
4767 		} else {
4768 			err = dev_map_generic_redirect(fwd, skb, xdp_prog);
4769 		}
4770 		if (unlikely(err))
4771 			goto err;
4772 		break;
4773 	case BPF_MAP_TYPE_XSKMAP:
4774 		err = xsk_generic_rcv(fwd, xdp);
4775 		if (err)
4776 			goto err;
4777 		consume_skb(skb);
4778 		break;
4779 	case BPF_MAP_TYPE_CPUMAP:
4780 		err = cpu_map_generic_redirect(fwd, skb);
4781 		if (unlikely(err))
4782 			goto err;
4783 		break;
4784 	default:
4785 		err = -EBADRQC;
4786 		goto err;
4787 	}
4788 
4789 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4790 	return 0;
4791 err:
4792 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4793 	return err;
4794 }
4795 
4796 int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
4797 			    struct xdp_buff *xdp,
4798 			    const struct bpf_prog *xdp_prog)
4799 {
4800 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4801 	enum bpf_map_type map_type = ri->map_type;
4802 	void *fwd = ri->tgt_value;
4803 	u32 map_id = ri->map_id;
4804 	u32 flags = ri->flags;
4805 	int err;
4806 
4807 	ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4808 	ri->flags = 0;
4809 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4810 
4811 	if (map_type == BPF_MAP_TYPE_UNSPEC && map_id == INT_MAX) {
4812 		fwd = dev_get_by_index_rcu(dev_net(dev), ri->tgt_index);
4813 		if (unlikely(!fwd)) {
4814 			err = -EINVAL;
4815 			goto err;
4816 		}
4817 
4818 		err = xdp_ok_fwd_dev(fwd, skb->len);
4819 		if (unlikely(err))
4820 			goto err;
4821 
4822 		skb->dev = fwd;
4823 		_trace_xdp_redirect(dev, xdp_prog, ri->tgt_index);
4824 		generic_xdp_tx(skb, xdp_prog);
4825 		return 0;
4826 	}
4827 
4828 	return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog, fwd, map_type, map_id, flags);
4829 err:
4830 	_trace_xdp_redirect_err(dev, xdp_prog, ri->tgt_index, err);
4831 	return err;
4832 }
4833 
4834 BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
4835 {
4836 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4837 
4838 	if (unlikely(flags))
4839 		return XDP_ABORTED;
4840 
4841 	/* NB! Map type UNSPEC and map_id == INT_MAX (never generated
4842 	 * by map_idr) is used for ifindex based XDP redirect.
4843 	 */
4844 	ri->tgt_index = ifindex;
4845 	ri->map_id = INT_MAX;
4846 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4847 
4848 	return XDP_REDIRECT;
4849 }
4850 
4851 static const struct bpf_func_proto bpf_xdp_redirect_proto = {
4852 	.func           = bpf_xdp_redirect,
4853 	.gpl_only       = false,
4854 	.ret_type       = RET_INTEGER,
4855 	.arg1_type      = ARG_ANYTHING,
4856 	.arg2_type      = ARG_ANYTHING,
4857 };
4858 
4859 BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u64, key,
4860 	   u64, flags)
4861 {
4862 	return map->ops->map_redirect(map, key, flags);
4863 }
4864 
4865 static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
4866 	.func           = bpf_xdp_redirect_map,
4867 	.gpl_only       = false,
4868 	.ret_type       = RET_INTEGER,
4869 	.arg1_type      = ARG_CONST_MAP_PTR,
4870 	.arg2_type      = ARG_ANYTHING,
4871 	.arg3_type      = ARG_ANYTHING,
4872 };
4873 
4874 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
4875 				  unsigned long off, unsigned long len)
4876 {
4877 	void *ptr = skb_header_pointer(skb, off, len, dst_buff);
4878 
4879 	if (unlikely(!ptr))
4880 		return len;
4881 	if (ptr != dst_buff)
4882 		memcpy(dst_buff, ptr, len);
4883 
4884 	return 0;
4885 }
4886 
4887 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
4888 	   u64, flags, void *, meta, u64, meta_size)
4889 {
4890 	u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
4891 
4892 	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
4893 		return -EINVAL;
4894 	if (unlikely(!skb || skb_size > skb->len))
4895 		return -EFAULT;
4896 
4897 	return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
4898 				bpf_skb_copy);
4899 }
4900 
4901 static const struct bpf_func_proto bpf_skb_event_output_proto = {
4902 	.func		= bpf_skb_event_output,
4903 	.gpl_only	= true,
4904 	.ret_type	= RET_INTEGER,
4905 	.arg1_type	= ARG_PTR_TO_CTX,
4906 	.arg2_type	= ARG_CONST_MAP_PTR,
4907 	.arg3_type	= ARG_ANYTHING,
4908 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4909 	.arg5_type	= ARG_MEM_SIZE_OR_ZERO,
4910 };
4911 
4912 BTF_ID_LIST_SINGLE(bpf_skb_output_btf_ids, struct, sk_buff)
4913 
4914 const struct bpf_func_proto bpf_skb_output_proto = {
4915 	.func		= bpf_skb_event_output,
4916 	.gpl_only	= true,
4917 	.ret_type	= RET_INTEGER,
4918 	.arg1_type	= ARG_PTR_TO_BTF_ID,
4919 	.arg1_btf_id	= &bpf_skb_output_btf_ids[0],
4920 	.arg2_type	= ARG_CONST_MAP_PTR,
4921 	.arg3_type	= ARG_ANYTHING,
4922 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4923 	.arg5_type	= ARG_MEM_SIZE_OR_ZERO,
4924 };
4925 
4926 static unsigned short bpf_tunnel_key_af(u64 flags)
4927 {
4928 	return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
4929 }
4930 
4931 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
4932 	   u32, size, u64, flags)
4933 {
4934 	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
4935 	u8 compat[sizeof(struct bpf_tunnel_key)];
4936 	void *to_orig = to;
4937 	int err;
4938 
4939 	if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6 |
4940 					 BPF_F_TUNINFO_FLAGS)))) {
4941 		err = -EINVAL;
4942 		goto err_clear;
4943 	}
4944 	if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
4945 		err = -EPROTO;
4946 		goto err_clear;
4947 	}
4948 	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
4949 		err = -EINVAL;
4950 		switch (size) {
4951 		case offsetof(struct bpf_tunnel_key, local_ipv6[0]):
4952 		case offsetof(struct bpf_tunnel_key, tunnel_label):
4953 		case offsetof(struct bpf_tunnel_key, tunnel_ext):
4954 			goto set_compat;
4955 		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
4956 			/* Fixup deprecated structure layouts here, so we have
4957 			 * a common path later on.
4958 			 */
4959 			if (ip_tunnel_info_af(info) != AF_INET)
4960 				goto err_clear;
4961 set_compat:
4962 			to = (struct bpf_tunnel_key *)compat;
4963 			break;
4964 		default:
4965 			goto err_clear;
4966 		}
4967 	}
4968 
4969 	to->tunnel_id = be64_to_cpu(info->key.tun_id);
4970 	to->tunnel_tos = info->key.tos;
4971 	to->tunnel_ttl = info->key.ttl;
4972 	if (flags & BPF_F_TUNINFO_FLAGS)
4973 		to->tunnel_flags = ip_tunnel_flags_to_be16(info->key.tun_flags);
4974 	else
4975 		to->tunnel_ext = 0;
4976 
4977 	if (flags & BPF_F_TUNINFO_IPV6) {
4978 		memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
4979 		       sizeof(to->remote_ipv6));
4980 		memcpy(to->local_ipv6, &info->key.u.ipv6.dst,
4981 		       sizeof(to->local_ipv6));
4982 		to->tunnel_label = be32_to_cpu(info->key.label);
4983 	} else {
4984 		to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
4985 		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4986 		to->local_ipv4 = be32_to_cpu(info->key.u.ipv4.dst);
4987 		memset(&to->local_ipv6[1], 0, sizeof(__u32) * 3);
4988 		to->tunnel_label = 0;
4989 	}
4990 
4991 	if (unlikely(size != sizeof(struct bpf_tunnel_key)))
4992 		memcpy(to_orig, to, size);
4993 
4994 	return 0;
4995 err_clear:
4996 	memset(to_orig, 0, size);
4997 	return err;
4998 }
4999 
5000 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
5001 	.func		= bpf_skb_get_tunnel_key,
5002 	.gpl_only	= false,
5003 	.ret_type	= RET_INTEGER,
5004 	.arg1_type	= ARG_PTR_TO_CTX,
5005 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
5006 	.arg3_type	= ARG_MEM_SIZE,
5007 	.arg4_type	= ARG_ANYTHING,
5008 };
5009 
5010 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
5011 {
5012 	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
5013 	int err;
5014 
5015 	if (unlikely(!info ||
5016 		     !ip_tunnel_is_options_present(info->key.tun_flags))) {
5017 		err = -ENOENT;
5018 		goto err_clear;
5019 	}
5020 	if (unlikely(size < info->options_len)) {
5021 		err = -ENOMEM;
5022 		goto err_clear;
5023 	}
5024 
5025 	ip_tunnel_info_opts_get(to, info);
5026 	if (size > info->options_len)
5027 		memset(to + info->options_len, 0, size - info->options_len);
5028 
5029 	return info->options_len;
5030 err_clear:
5031 	memset(to, 0, size);
5032 	return err;
5033 }
5034 
5035 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
5036 	.func		= bpf_skb_get_tunnel_opt,
5037 	.gpl_only	= false,
5038 	.ret_type	= RET_INTEGER,
5039 	.arg1_type	= ARG_PTR_TO_CTX,
5040 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
5041 	.arg3_type	= ARG_MEM_SIZE,
5042 };
5043 
5044 static struct metadata_dst __percpu *md_dst;
5045 
5046 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
5047 	   const struct bpf_tunnel_key *, from, u32, size, u64, flags)
5048 {
5049 	struct metadata_dst *md = this_cpu_ptr(md_dst);
5050 	u8 compat[sizeof(struct bpf_tunnel_key)];
5051 	struct ip_tunnel_info *info;
5052 
5053 	if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
5054 			       BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER |
5055 			       BPF_F_NO_TUNNEL_KEY)))
5056 		return -EINVAL;
5057 	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
5058 		switch (size) {
5059 		case offsetof(struct bpf_tunnel_key, local_ipv6[0]):
5060 		case offsetof(struct bpf_tunnel_key, tunnel_label):
5061 		case offsetof(struct bpf_tunnel_key, tunnel_ext):
5062 		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
5063 			/* Fixup deprecated structure layouts here, so we have
5064 			 * a common path later on.
5065 			 */
5066 			memcpy(compat, from, size);
5067 			memset(compat + size, 0, sizeof(compat) - size);
5068 			from = (const struct bpf_tunnel_key *) compat;
5069 			break;
5070 		default:
5071 			return -EINVAL;
5072 		}
5073 	}
5074 	if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
5075 		     from->tunnel_ext))
5076 		return -EINVAL;
5077 
5078 	skb_dst_drop(skb);
5079 	dst_hold((struct dst_entry *) md);
5080 	skb_dst_set(skb, (struct dst_entry *) md);
5081 
5082 	info = &md->u.tun_info;
5083 	memset(info, 0, sizeof(*info));
5084 	info->mode = IP_TUNNEL_INFO_TX;
5085 
5086 	__set_bit(IP_TUNNEL_NOCACHE_BIT, info->key.tun_flags);
5087 	__assign_bit(IP_TUNNEL_DONT_FRAGMENT_BIT, info->key.tun_flags,
5088 		     flags & BPF_F_DONT_FRAGMENT);
5089 	__assign_bit(IP_TUNNEL_CSUM_BIT, info->key.tun_flags,
5090 		     !(flags & BPF_F_ZERO_CSUM_TX));
5091 	__assign_bit(IP_TUNNEL_SEQ_BIT, info->key.tun_flags,
5092 		     flags & BPF_F_SEQ_NUMBER);
5093 	__assign_bit(IP_TUNNEL_KEY_BIT, info->key.tun_flags,
5094 		     !(flags & BPF_F_NO_TUNNEL_KEY));
5095 
5096 	info->key.tun_id = cpu_to_be64(from->tunnel_id);
5097 	info->key.tos = from->tunnel_tos;
5098 	info->key.ttl = from->tunnel_ttl;
5099 
5100 	if (flags & BPF_F_TUNINFO_IPV6) {
5101 		info->mode |= IP_TUNNEL_INFO_IPV6;
5102 		memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
5103 		       sizeof(from->remote_ipv6));
5104 		memcpy(&info->key.u.ipv6.src, from->local_ipv6,
5105 		       sizeof(from->local_ipv6));
5106 		info->key.label = cpu_to_be32(from->tunnel_label) &
5107 				  IPV6_FLOWLABEL_MASK;
5108 	} else {
5109 		info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
5110 		info->key.u.ipv4.src = cpu_to_be32(from->local_ipv4);
5111 		info->key.flow_flags = FLOWI_FLAG_ANYSRC;
5112 	}
5113 
5114 	return 0;
5115 }
5116 
5117 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
5118 	.func		= bpf_skb_set_tunnel_key,
5119 	.gpl_only	= false,
5120 	.ret_type	= RET_INTEGER,
5121 	.arg1_type	= ARG_PTR_TO_CTX,
5122 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5123 	.arg3_type	= ARG_MEM_SIZE,
5124 	.arg4_type	= ARG_ANYTHING,
5125 };
5126 
5127 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
5128 	   const u8 *, from, u32, size)
5129 {
5130 	struct ip_tunnel_info *info = skb_tunnel_info(skb);
5131 	const struct metadata_dst *md = this_cpu_ptr(md_dst);
5132 	IP_TUNNEL_DECLARE_FLAGS(present) = { };
5133 
5134 	if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
5135 		return -EINVAL;
5136 	if (unlikely(size > IP_TUNNEL_OPTS_MAX))
5137 		return -ENOMEM;
5138 
5139 	ip_tunnel_set_options_present(present);
5140 	ip_tunnel_info_opts_set(info, from, size, present);
5141 
5142 	return 0;
5143 }
5144 
5145 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
5146 	.func		= bpf_skb_set_tunnel_opt,
5147 	.gpl_only	= false,
5148 	.ret_type	= RET_INTEGER,
5149 	.arg1_type	= ARG_PTR_TO_CTX,
5150 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5151 	.arg3_type	= ARG_MEM_SIZE,
5152 };
5153 
5154 static const struct bpf_func_proto *
5155 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
5156 {
5157 	if (!md_dst) {
5158 		struct metadata_dst __percpu *tmp;
5159 
5160 		tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
5161 						METADATA_IP_TUNNEL,
5162 						GFP_KERNEL);
5163 		if (!tmp)
5164 			return NULL;
5165 		if (cmpxchg(&md_dst, NULL, tmp))
5166 			metadata_dst_free_percpu(tmp);
5167 	}
5168 
5169 	switch (which) {
5170 	case BPF_FUNC_skb_set_tunnel_key:
5171 		return &bpf_skb_set_tunnel_key_proto;
5172 	case BPF_FUNC_skb_set_tunnel_opt:
5173 		return &bpf_skb_set_tunnel_opt_proto;
5174 	default:
5175 		return NULL;
5176 	}
5177 }
5178 
5179 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
5180 	   u32, idx)
5181 {
5182 	struct bpf_array *array = container_of(map, struct bpf_array, map);
5183 	struct cgroup *cgrp;
5184 	struct sock *sk;
5185 
5186 	sk = skb_to_full_sk(skb);
5187 	if (!sk || !sk_fullsock(sk))
5188 		return -ENOENT;
5189 	if (unlikely(idx >= array->map.max_entries))
5190 		return -E2BIG;
5191 
5192 	cgrp = READ_ONCE(array->ptrs[idx]);
5193 	if (unlikely(!cgrp))
5194 		return -EAGAIN;
5195 
5196 	return sk_under_cgroup_hierarchy(sk, cgrp);
5197 }
5198 
5199 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
5200 	.func		= bpf_skb_under_cgroup,
5201 	.gpl_only	= false,
5202 	.ret_type	= RET_INTEGER,
5203 	.arg1_type	= ARG_PTR_TO_CTX,
5204 	.arg2_type	= ARG_CONST_MAP_PTR,
5205 	.arg3_type	= ARG_ANYTHING,
5206 };
5207 
5208 #ifdef CONFIG_SOCK_CGROUP_DATA
5209 static inline u64 __bpf_sk_cgroup_id(struct sock *sk)
5210 {
5211 	struct cgroup *cgrp;
5212 
5213 	sk = sk_to_full_sk(sk);
5214 	if (!sk || !sk_fullsock(sk))
5215 		return 0;
5216 
5217 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
5218 	return cgroup_id(cgrp);
5219 }
5220 
5221 BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
5222 {
5223 	return __bpf_sk_cgroup_id(skb->sk);
5224 }
5225 
5226 static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
5227 	.func           = bpf_skb_cgroup_id,
5228 	.gpl_only       = false,
5229 	.ret_type       = RET_INTEGER,
5230 	.arg1_type      = ARG_PTR_TO_CTX,
5231 };
5232 
5233 static inline u64 __bpf_sk_ancestor_cgroup_id(struct sock *sk,
5234 					      int ancestor_level)
5235 {
5236 	struct cgroup *ancestor;
5237 	struct cgroup *cgrp;
5238 
5239 	sk = sk_to_full_sk(sk);
5240 	if (!sk || !sk_fullsock(sk))
5241 		return 0;
5242 
5243 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
5244 	ancestor = cgroup_ancestor(cgrp, ancestor_level);
5245 	if (!ancestor)
5246 		return 0;
5247 
5248 	return cgroup_id(ancestor);
5249 }
5250 
5251 BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
5252 	   ancestor_level)
5253 {
5254 	return __bpf_sk_ancestor_cgroup_id(skb->sk, ancestor_level);
5255 }
5256 
5257 static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
5258 	.func           = bpf_skb_ancestor_cgroup_id,
5259 	.gpl_only       = false,
5260 	.ret_type       = RET_INTEGER,
5261 	.arg1_type      = ARG_PTR_TO_CTX,
5262 	.arg2_type      = ARG_ANYTHING,
5263 };
5264 
5265 BPF_CALL_1(bpf_sk_cgroup_id, struct sock *, sk)
5266 {
5267 	return __bpf_sk_cgroup_id(sk);
5268 }
5269 
5270 static const struct bpf_func_proto bpf_sk_cgroup_id_proto = {
5271 	.func           = bpf_sk_cgroup_id,
5272 	.gpl_only       = false,
5273 	.ret_type       = RET_INTEGER,
5274 	.arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5275 };
5276 
5277 BPF_CALL_2(bpf_sk_ancestor_cgroup_id, struct sock *, sk, int, ancestor_level)
5278 {
5279 	return __bpf_sk_ancestor_cgroup_id(sk, ancestor_level);
5280 }
5281 
5282 static const struct bpf_func_proto bpf_sk_ancestor_cgroup_id_proto = {
5283 	.func           = bpf_sk_ancestor_cgroup_id,
5284 	.gpl_only       = false,
5285 	.ret_type       = RET_INTEGER,
5286 	.arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5287 	.arg2_type      = ARG_ANYTHING,
5288 };
5289 #endif
5290 
5291 static unsigned long bpf_xdp_copy(void *dst, const void *ctx,
5292 				  unsigned long off, unsigned long len)
5293 {
5294 	struct xdp_buff *xdp = (struct xdp_buff *)ctx;
5295 
5296 	bpf_xdp_copy_buf(xdp, off, dst, len, false);
5297 	return 0;
5298 }
5299 
5300 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
5301 	   u64, flags, void *, meta, u64, meta_size)
5302 {
5303 	u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
5304 
5305 	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
5306 		return -EINVAL;
5307 
5308 	if (unlikely(!xdp || xdp_size > xdp_get_buff_len(xdp)))
5309 		return -EFAULT;
5310 
5311 	return bpf_event_output(map, flags, meta, meta_size, xdp,
5312 				xdp_size, bpf_xdp_copy);
5313 }
5314 
5315 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
5316 	.func		= bpf_xdp_event_output,
5317 	.gpl_only	= true,
5318 	.ret_type	= RET_INTEGER,
5319 	.arg1_type	= ARG_PTR_TO_CTX,
5320 	.arg2_type	= ARG_CONST_MAP_PTR,
5321 	.arg3_type	= ARG_ANYTHING,
5322 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5323 	.arg5_type	= ARG_MEM_SIZE_OR_ZERO,
5324 };
5325 
5326 BTF_ID_LIST_SINGLE(bpf_xdp_output_btf_ids, struct, xdp_buff)
5327 
5328 const struct bpf_func_proto bpf_xdp_output_proto = {
5329 	.func		= bpf_xdp_event_output,
5330 	.gpl_only	= true,
5331 	.ret_type	= RET_INTEGER,
5332 	.arg1_type	= ARG_PTR_TO_BTF_ID,
5333 	.arg1_btf_id	= &bpf_xdp_output_btf_ids[0],
5334 	.arg2_type	= ARG_CONST_MAP_PTR,
5335 	.arg3_type	= ARG_ANYTHING,
5336 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5337 	.arg5_type	= ARG_MEM_SIZE_OR_ZERO,
5338 };
5339 
5340 BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
5341 {
5342 	return skb->sk ? __sock_gen_cookie(skb->sk) : 0;
5343 }
5344 
5345 static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
5346 	.func           = bpf_get_socket_cookie,
5347 	.gpl_only       = false,
5348 	.ret_type       = RET_INTEGER,
5349 	.arg1_type      = ARG_PTR_TO_CTX,
5350 };
5351 
5352 BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
5353 {
5354 	return __sock_gen_cookie(ctx->sk);
5355 }
5356 
5357 static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
5358 	.func		= bpf_get_socket_cookie_sock_addr,
5359 	.gpl_only	= false,
5360 	.ret_type	= RET_INTEGER,
5361 	.arg1_type	= ARG_PTR_TO_CTX,
5362 };
5363 
5364 BPF_CALL_1(bpf_get_socket_cookie_sock, struct sock *, ctx)
5365 {
5366 	return __sock_gen_cookie(ctx);
5367 }
5368 
5369 static const struct bpf_func_proto bpf_get_socket_cookie_sock_proto = {
5370 	.func		= bpf_get_socket_cookie_sock,
5371 	.gpl_only	= false,
5372 	.ret_type	= RET_INTEGER,
5373 	.arg1_type	= ARG_PTR_TO_CTX,
5374 };
5375 
5376 BPF_CALL_1(bpf_get_socket_ptr_cookie, struct sock *, sk)
5377 {
5378 	return sk ? sock_gen_cookie(sk) : 0;
5379 }
5380 
5381 const struct bpf_func_proto bpf_get_socket_ptr_cookie_proto = {
5382 	.func		= bpf_get_socket_ptr_cookie,
5383 	.gpl_only	= false,
5384 	.ret_type	= RET_INTEGER,
5385 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON | PTR_MAYBE_NULL,
5386 };
5387 
5388 BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
5389 {
5390 	return __sock_gen_cookie(ctx->sk);
5391 }
5392 
5393 static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
5394 	.func		= bpf_get_socket_cookie_sock_ops,
5395 	.gpl_only	= false,
5396 	.ret_type	= RET_INTEGER,
5397 	.arg1_type	= ARG_PTR_TO_CTX,
5398 };
5399 
5400 static u64 __bpf_get_netns_cookie(struct sock *sk)
5401 {
5402 	const struct net *net = sk ? sock_net(sk) : &init_net;
5403 
5404 	return net->net_cookie;
5405 }
5406 
5407 BPF_CALL_1(bpf_get_netns_cookie, struct sk_buff *, skb)
5408 {
5409 	return __bpf_get_netns_cookie(skb && skb->sk ? skb->sk : NULL);
5410 }
5411 
5412 static const struct bpf_func_proto bpf_get_netns_cookie_proto = {
5413 	.func           = bpf_get_netns_cookie,
5414 	.ret_type       = RET_INTEGER,
5415 	.arg1_type      = ARG_PTR_TO_CTX_OR_NULL,
5416 };
5417 
5418 BPF_CALL_1(bpf_get_netns_cookie_sock, struct sock *, ctx)
5419 {
5420 	return __bpf_get_netns_cookie(ctx);
5421 }
5422 
5423 static const struct bpf_func_proto bpf_get_netns_cookie_sock_proto = {
5424 	.func		= bpf_get_netns_cookie_sock,
5425 	.gpl_only	= false,
5426 	.ret_type	= RET_INTEGER,
5427 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5428 };
5429 
5430 BPF_CALL_1(bpf_get_netns_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
5431 {
5432 	return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5433 }
5434 
5435 static const struct bpf_func_proto bpf_get_netns_cookie_sock_addr_proto = {
5436 	.func		= bpf_get_netns_cookie_sock_addr,
5437 	.gpl_only	= false,
5438 	.ret_type	= RET_INTEGER,
5439 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5440 };
5441 
5442 BPF_CALL_1(bpf_get_netns_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
5443 {
5444 	return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5445 }
5446 
5447 static const struct bpf_func_proto bpf_get_netns_cookie_sock_ops_proto = {
5448 	.func		= bpf_get_netns_cookie_sock_ops,
5449 	.gpl_only	= false,
5450 	.ret_type	= RET_INTEGER,
5451 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5452 };
5453 
5454 BPF_CALL_1(bpf_get_netns_cookie_sk_msg, struct sk_msg *, ctx)
5455 {
5456 	return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5457 }
5458 
5459 static const struct bpf_func_proto bpf_get_netns_cookie_sk_msg_proto = {
5460 	.func		= bpf_get_netns_cookie_sk_msg,
5461 	.gpl_only	= false,
5462 	.ret_type	= RET_INTEGER,
5463 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5464 };
5465 
5466 BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
5467 {
5468 	struct sock *sk = sk_to_full_sk(skb->sk);
5469 	kuid_t kuid;
5470 
5471 	if (!sk || !sk_fullsock(sk))
5472 		return overflowuid;
5473 	kuid = sock_net_uid(sock_net(sk), sk);
5474 	return from_kuid_munged(sock_net(sk)->user_ns, kuid);
5475 }
5476 
5477 static const struct bpf_func_proto bpf_get_socket_uid_proto = {
5478 	.func           = bpf_get_socket_uid,
5479 	.gpl_only       = false,
5480 	.ret_type       = RET_INTEGER,
5481 	.arg1_type      = ARG_PTR_TO_CTX,
5482 };
5483 
5484 static int sk_bpf_set_get_cb_flags(struct sock *sk, char *optval, bool getopt)
5485 {
5486 	u32 sk_bpf_cb_flags;
5487 
5488 	if (getopt) {
5489 		*(u32 *)optval = sk->sk_bpf_cb_flags;
5490 		return 0;
5491 	}
5492 
5493 	sk_bpf_cb_flags = *(u32 *)optval;
5494 
5495 	if (sk_bpf_cb_flags & ~SK_BPF_CB_MASK)
5496 		return -EINVAL;
5497 
5498 	sk->sk_bpf_cb_flags = sk_bpf_cb_flags;
5499 
5500 	return 0;
5501 }
5502 
5503 static int sol_socket_sockopt(struct sock *sk, int optname,
5504 			      char *optval, int *optlen,
5505 			      bool getopt)
5506 {
5507 	switch (optname) {
5508 	case SO_REUSEADDR:
5509 	case SO_SNDBUF:
5510 	case SO_RCVBUF:
5511 	case SO_KEEPALIVE:
5512 	case SO_PRIORITY:
5513 	case SO_REUSEPORT:
5514 	case SO_RCVLOWAT:
5515 	case SO_MARK:
5516 	case SO_MAX_PACING_RATE:
5517 	case SO_BINDTOIFINDEX:
5518 	case SO_TXREHASH:
5519 	case SK_BPF_CB_FLAGS:
5520 		if (*optlen != sizeof(int))
5521 			return -EINVAL;
5522 		break;
5523 	case SO_BINDTODEVICE:
5524 		break;
5525 	default:
5526 		return -EINVAL;
5527 	}
5528 
5529 	if (optname == SK_BPF_CB_FLAGS)
5530 		return sk_bpf_set_get_cb_flags(sk, optval, getopt);
5531 
5532 	if (getopt) {
5533 		if (optname == SO_BINDTODEVICE)
5534 			return -EINVAL;
5535 		return sk_getsockopt(sk, SOL_SOCKET, optname,
5536 				     KERNEL_SOCKPTR(optval),
5537 				     KERNEL_SOCKPTR(optlen));
5538 	}
5539 
5540 	return sk_setsockopt(sk, SOL_SOCKET, optname,
5541 			     KERNEL_SOCKPTR(optval), *optlen);
5542 }
5543 
5544 static int bpf_sol_tcp_getsockopt(struct sock *sk, int optname,
5545 				  char *optval, int optlen)
5546 {
5547 	if (optlen != sizeof(int))
5548 		return -EINVAL;
5549 
5550 	switch (optname) {
5551 	case TCP_BPF_SOCK_OPS_CB_FLAGS: {
5552 		int cb_flags = tcp_sk(sk)->bpf_sock_ops_cb_flags;
5553 
5554 		memcpy(optval, &cb_flags, optlen);
5555 		break;
5556 	}
5557 	case TCP_BPF_RTO_MIN: {
5558 		int rto_min_us = jiffies_to_usecs(inet_csk(sk)->icsk_rto_min);
5559 
5560 		memcpy(optval, &rto_min_us, optlen);
5561 		break;
5562 	}
5563 	case TCP_BPF_DELACK_MAX: {
5564 		int delack_max_us = jiffies_to_usecs(inet_csk(sk)->icsk_delack_max);
5565 
5566 		memcpy(optval, &delack_max_us, optlen);
5567 		break;
5568 	}
5569 	default:
5570 		return -EINVAL;
5571 	}
5572 
5573 	return 0;
5574 }
5575 
5576 static int bpf_sol_tcp_setsockopt(struct sock *sk, int optname,
5577 				  char *optval, int optlen)
5578 {
5579 	struct tcp_sock *tp = tcp_sk(sk);
5580 	unsigned long timeout;
5581 	int val;
5582 
5583 	if (optlen != sizeof(int))
5584 		return -EINVAL;
5585 
5586 	val = *(int *)optval;
5587 
5588 	/* Only some options are supported */
5589 	switch (optname) {
5590 	case TCP_BPF_IW:
5591 		if (val <= 0 || tp->data_segs_out > tp->syn_data)
5592 			return -EINVAL;
5593 		tcp_snd_cwnd_set(tp, val);
5594 		break;
5595 	case TCP_BPF_SNDCWND_CLAMP:
5596 		if (val <= 0)
5597 			return -EINVAL;
5598 		tp->snd_cwnd_clamp = val;
5599 		WRITE_ONCE(tp->snd_ssthresh, val);
5600 		break;
5601 	case TCP_BPF_DELACK_MAX:
5602 		timeout = usecs_to_jiffies(val);
5603 		if (timeout > TCP_DELACK_MAX ||
5604 		    timeout < TCP_TIMEOUT_MIN)
5605 			return -EINVAL;
5606 		inet_csk(sk)->icsk_delack_max = timeout;
5607 		break;
5608 	case TCP_BPF_RTO_MIN:
5609 		timeout = usecs_to_jiffies(val);
5610 		if (timeout > TCP_RTO_MIN ||
5611 		    timeout < TCP_TIMEOUT_MIN)
5612 			return -EINVAL;
5613 		inet_csk(sk)->icsk_rto_min = timeout;
5614 		break;
5615 	case TCP_BPF_SOCK_OPS_CB_FLAGS:
5616 		if (val & ~(BPF_SOCK_OPS_ALL_CB_FLAGS))
5617 			return -EINVAL;
5618 		tp->bpf_sock_ops_cb_flags = val;
5619 		break;
5620 	default:
5621 		return -EINVAL;
5622 	}
5623 
5624 	return 0;
5625 }
5626 
5627 static int sol_tcp_sockopt_congestion(struct sock *sk, char *optval,
5628 				      int *optlen, bool getopt)
5629 {
5630 	struct tcp_sock *tp;
5631 	int ret;
5632 
5633 	if (*optlen < 2)
5634 		return -EINVAL;
5635 
5636 	if (getopt) {
5637 		if (!inet_csk(sk)->icsk_ca_ops)
5638 			return -EINVAL;
5639 		/* BPF expects NULL-terminated tcp-cc string */
5640 		optval[--(*optlen)] = '\0';
5641 		return do_tcp_getsockopt(sk, SOL_TCP, TCP_CONGESTION,
5642 					 KERNEL_SOCKPTR(optval),
5643 					 KERNEL_SOCKPTR(optlen));
5644 	}
5645 
5646 	/* "cdg" is the only cc that alloc a ptr
5647 	 * in inet_csk_ca area.  The bpf-tcp-cc may
5648 	 * overwrite this ptr after switching to cdg.
5649 	 */
5650 	if (*optlen >= sizeof("cdg") - 1 && !strncmp("cdg", optval, *optlen))
5651 		return -ENOTSUPP;
5652 
5653 	/* It stops this looping
5654 	 *
5655 	 * .init => bpf_setsockopt(tcp_cc) => .init =>
5656 	 * bpf_setsockopt(tcp_cc)" => .init => ....
5657 	 *
5658 	 * The second bpf_setsockopt(tcp_cc) is not allowed
5659 	 * in order to break the loop when both .init
5660 	 * are the same bpf prog.
5661 	 *
5662 	 * This applies even the second bpf_setsockopt(tcp_cc)
5663 	 * does not cause a loop.  This limits only the first
5664 	 * '.init' can call bpf_setsockopt(TCP_CONGESTION) to
5665 	 * pick a fallback cc (eg. peer does not support ECN)
5666 	 * and the second '.init' cannot fallback to
5667 	 * another.
5668 	 */
5669 	tp = tcp_sk(sk);
5670 	if (tp->bpf_chg_cc_inprogress)
5671 		return -EBUSY;
5672 
5673 	tp->bpf_chg_cc_inprogress = 1;
5674 	ret = do_tcp_setsockopt(sk, SOL_TCP, TCP_CONGESTION,
5675 				KERNEL_SOCKPTR(optval), *optlen);
5676 	tp->bpf_chg_cc_inprogress = 0;
5677 	return ret;
5678 }
5679 
5680 static int sol_tcp_sockopt(struct sock *sk, int optname,
5681 			   char *optval, int *optlen,
5682 			   bool getopt)
5683 {
5684 	if (!sk_is_tcp(sk))
5685 		return -EINVAL;
5686 
5687 	switch (optname) {
5688 	case TCP_NODELAY:
5689 	case TCP_MAXSEG:
5690 	case TCP_KEEPIDLE:
5691 	case TCP_KEEPINTVL:
5692 	case TCP_KEEPCNT:
5693 	case TCP_SYNCNT:
5694 	case TCP_WINDOW_CLAMP:
5695 	case TCP_THIN_LINEAR_TIMEOUTS:
5696 	case TCP_USER_TIMEOUT:
5697 	case TCP_NOTSENT_LOWAT:
5698 	case TCP_SAVE_SYN:
5699 	case TCP_RTO_MAX_MS:
5700 		if (*optlen != sizeof(int))
5701 			return -EINVAL;
5702 		break;
5703 	case TCP_CONGESTION:
5704 		return sol_tcp_sockopt_congestion(sk, optval, optlen, getopt);
5705 	case TCP_SAVED_SYN:
5706 		if (*optlen < 1)
5707 			return -EINVAL;
5708 		break;
5709 	default:
5710 		if (getopt)
5711 			return bpf_sol_tcp_getsockopt(sk, optname, optval, *optlen);
5712 		return bpf_sol_tcp_setsockopt(sk, optname, optval, *optlen);
5713 	}
5714 
5715 	if (getopt) {
5716 		if (optname == TCP_SAVED_SYN) {
5717 			struct tcp_sock *tp = tcp_sk(sk);
5718 
5719 			if (!tp->saved_syn ||
5720 			    *optlen > tcp_saved_syn_len(tp->saved_syn))
5721 				return -EINVAL;
5722 			memcpy(optval, tp->saved_syn->data, *optlen);
5723 			/* It cannot free tp->saved_syn here because it
5724 			 * does not know if the user space still needs it.
5725 			 */
5726 			return 0;
5727 		}
5728 
5729 		return do_tcp_getsockopt(sk, SOL_TCP, optname,
5730 					 KERNEL_SOCKPTR(optval),
5731 					 KERNEL_SOCKPTR(optlen));
5732 	}
5733 
5734 	return do_tcp_setsockopt(sk, SOL_TCP, optname,
5735 				 KERNEL_SOCKPTR(optval), *optlen);
5736 }
5737 
5738 static bool sk_allows_sol_ip_sockopt(struct sock *sk)
5739 {
5740 	switch (sk->sk_family) {
5741 	case AF_INET:
5742 		return true;
5743 	case AF_INET6:
5744 		/* Allow getting/setting sockopt for possible ipv4-mapped ipv6 socket. */
5745 		return sk->sk_type != SOCK_RAW && !ipv6_only_sock(sk);
5746 	default:
5747 		return false;
5748 	}
5749 }
5750 
5751 static int sol_ip_sockopt(struct sock *sk, int optname,
5752 			  char *optval, int *optlen,
5753 			  bool getopt)
5754 {
5755 	if (!sk_allows_sol_ip_sockopt(sk))
5756 		return -EINVAL;
5757 
5758 	switch (optname) {
5759 	case IP_TOS:
5760 	case IP_TRANSPARENT:
5761 		if (*optlen != sizeof(int))
5762 			return -EINVAL;
5763 		break;
5764 	default:
5765 		return -EINVAL;
5766 	}
5767 
5768 	if (getopt)
5769 		return do_ip_getsockopt(sk, SOL_IP, optname,
5770 					KERNEL_SOCKPTR(optval),
5771 					KERNEL_SOCKPTR(optlen));
5772 
5773 	return do_ip_setsockopt(sk, SOL_IP, optname,
5774 				KERNEL_SOCKPTR(optval), *optlen);
5775 }
5776 
5777 static int sol_ipv6_sockopt(struct sock *sk, int optname,
5778 			    char *optval, int *optlen,
5779 			    bool getopt)
5780 {
5781 	if (sk->sk_family != AF_INET6)
5782 		return -EINVAL;
5783 
5784 	switch (optname) {
5785 	case IPV6_TCLASS:
5786 	case IPV6_AUTOFLOWLABEL:
5787 	case IPV6_TRANSPARENT:
5788 		if (*optlen != sizeof(int))
5789 			return -EINVAL;
5790 		break;
5791 	default:
5792 		return -EINVAL;
5793 	}
5794 
5795 	if (getopt)
5796 		return do_ipv6_getsockopt(sk, SOL_IPV6, optname,
5797 					  KERNEL_SOCKPTR(optval),
5798 					  KERNEL_SOCKPTR(optlen));
5799 
5800 	return do_ipv6_setsockopt(sk, SOL_IPV6, optname,
5801 				  KERNEL_SOCKPTR(optval), *optlen);
5802 }
5803 
5804 static int __bpf_setsockopt(struct sock *sk, int level, int optname,
5805 			    char *optval, int optlen)
5806 {
5807 	if (!sk_fullsock(sk))
5808 		return -EINVAL;
5809 
5810 	if (level == SOL_SOCKET)
5811 		return sol_socket_sockopt(sk, optname, optval, &optlen, false);
5812 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_IP)
5813 		return sol_ip_sockopt(sk, optname, optval, &optlen, false);
5814 	else if (IS_ENABLED(CONFIG_IPV6) && level == SOL_IPV6)
5815 		return sol_ipv6_sockopt(sk, optname, optval, &optlen, false);
5816 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP)
5817 		return sol_tcp_sockopt(sk, optname, optval, &optlen, false);
5818 
5819 	return -EINVAL;
5820 }
5821 
5822 static bool is_locked_tcp_sock_ops(struct bpf_sock_ops_kern *bpf_sock)
5823 {
5824 	return bpf_sock->op <= BPF_SOCK_OPS_WRITE_HDR_OPT_CB;
5825 }
5826 
5827 static int _bpf_setsockopt(struct sock *sk, int level, int optname,
5828 			   char *optval, int optlen)
5829 {
5830 	if (sk_fullsock(sk))
5831 		sock_owned_by_me(sk);
5832 	return __bpf_setsockopt(sk, level, optname, optval, optlen);
5833 }
5834 
5835 static int __bpf_getsockopt(struct sock *sk, int level, int optname,
5836 			    char *optval, int optlen)
5837 {
5838 	int err, saved_optlen = optlen;
5839 
5840 	if (!sk_fullsock(sk)) {
5841 		err = -EINVAL;
5842 		goto done;
5843 	}
5844 
5845 	if (level == SOL_SOCKET)
5846 		err = sol_socket_sockopt(sk, optname, optval, &optlen, true);
5847 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP)
5848 		err = sol_tcp_sockopt(sk, optname, optval, &optlen, true);
5849 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_IP)
5850 		err = sol_ip_sockopt(sk, optname, optval, &optlen, true);
5851 	else if (IS_ENABLED(CONFIG_IPV6) && level == SOL_IPV6)
5852 		err = sol_ipv6_sockopt(sk, optname, optval, &optlen, true);
5853 	else
5854 		err = -EINVAL;
5855 
5856 done:
5857 	if (err)
5858 		optlen = 0;
5859 	if (optlen < saved_optlen)
5860 		memset(optval + optlen, 0, saved_optlen - optlen);
5861 	return err;
5862 }
5863 
5864 static int _bpf_getsockopt(struct sock *sk, int level, int optname,
5865 			   char *optval, int optlen)
5866 {
5867 	if (sk_fullsock(sk))
5868 		sock_owned_by_me(sk);
5869 	return __bpf_getsockopt(sk, level, optname, optval, optlen);
5870 }
5871 
5872 BPF_CALL_5(bpf_sk_setsockopt, struct sock *, sk, int, level,
5873 	   int, optname, char *, optval, int, optlen)
5874 {
5875 	return _bpf_setsockopt(sk, level, optname, optval, optlen);
5876 }
5877 
5878 const struct bpf_func_proto bpf_sk_setsockopt_proto = {
5879 	.func		= bpf_sk_setsockopt,
5880 	.gpl_only	= false,
5881 	.ret_type	= RET_INTEGER,
5882 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5883 	.arg2_type	= ARG_ANYTHING,
5884 	.arg3_type	= ARG_ANYTHING,
5885 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5886 	.arg5_type	= ARG_MEM_SIZE,
5887 };
5888 
5889 BPF_CALL_5(bpf_sk_getsockopt, struct sock *, sk, int, level,
5890 	   int, optname, char *, optval, int, optlen)
5891 {
5892 	return _bpf_getsockopt(sk, level, optname, optval, optlen);
5893 }
5894 
5895 const struct bpf_func_proto bpf_sk_getsockopt_proto = {
5896 	.func		= bpf_sk_getsockopt,
5897 	.gpl_only	= false,
5898 	.ret_type	= RET_INTEGER,
5899 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5900 	.arg2_type	= ARG_ANYTHING,
5901 	.arg3_type	= ARG_ANYTHING,
5902 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5903 	.arg5_type	= ARG_MEM_SIZE,
5904 };
5905 
5906 BPF_CALL_5(bpf_sk_setsockopt_nodelay, struct sock *, sk, int, level,
5907 	   int, optname, char *, optval, int, optlen)
5908 {
5909 	/*
5910 	 * TCP_NODELAY triggers tcp_push_pending_frames() and re-enters
5911 	 * CA_EVENT_TX_START in bpf_tcp_cc.
5912 	 */
5913 	if (level == SOL_TCP && optname == TCP_NODELAY)
5914 		return -EOPNOTSUPP;
5915 
5916 	return _bpf_setsockopt(sk, level, optname, optval, optlen);
5917 }
5918 
5919 const struct bpf_func_proto bpf_sk_setsockopt_nodelay_proto = {
5920 	.func		= bpf_sk_setsockopt_nodelay,
5921 	.gpl_only	= false,
5922 	.ret_type	= RET_INTEGER,
5923 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5924 	.arg2_type	= ARG_ANYTHING,
5925 	.arg3_type	= ARG_ANYTHING,
5926 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5927 	.arg5_type	= ARG_MEM_SIZE,
5928 };
5929 
5930 BPF_CALL_5(bpf_unlocked_sk_setsockopt, struct sock *, sk, int, level,
5931 	   int, optname, char *, optval, int, optlen)
5932 {
5933 	return __bpf_setsockopt(sk, level, optname, optval, optlen);
5934 }
5935 
5936 const struct bpf_func_proto bpf_unlocked_sk_setsockopt_proto = {
5937 	.func		= bpf_unlocked_sk_setsockopt,
5938 	.gpl_only	= false,
5939 	.ret_type	= RET_INTEGER,
5940 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5941 	.arg2_type	= ARG_ANYTHING,
5942 	.arg3_type	= ARG_ANYTHING,
5943 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5944 	.arg5_type	= ARG_MEM_SIZE,
5945 };
5946 
5947 BPF_CALL_5(bpf_unlocked_sk_getsockopt, struct sock *, sk, int, level,
5948 	   int, optname, char *, optval, int, optlen)
5949 {
5950 	return __bpf_getsockopt(sk, level, optname, optval, optlen);
5951 }
5952 
5953 const struct bpf_func_proto bpf_unlocked_sk_getsockopt_proto = {
5954 	.func		= bpf_unlocked_sk_getsockopt,
5955 	.gpl_only	= false,
5956 	.ret_type	= RET_INTEGER,
5957 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5958 	.arg2_type	= ARG_ANYTHING,
5959 	.arg3_type	= ARG_ANYTHING,
5960 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5961 	.arg5_type	= ARG_MEM_SIZE,
5962 };
5963 
5964 BPF_CALL_5(bpf_sock_addr_setsockopt, struct bpf_sock_addr_kern *, ctx,
5965 	   int, level, int, optname, char *, optval, int, optlen)
5966 {
5967 	return _bpf_setsockopt(ctx->sk, level, optname, optval, optlen);
5968 }
5969 
5970 static const struct bpf_func_proto bpf_sock_addr_setsockopt_proto = {
5971 	.func		= bpf_sock_addr_setsockopt,
5972 	.gpl_only	= false,
5973 	.ret_type	= RET_INTEGER,
5974 	.arg1_type	= ARG_PTR_TO_CTX,
5975 	.arg2_type	= ARG_ANYTHING,
5976 	.arg3_type	= ARG_ANYTHING,
5977 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5978 	.arg5_type	= ARG_MEM_SIZE,
5979 };
5980 
5981 BPF_CALL_5(bpf_sock_addr_getsockopt, struct bpf_sock_addr_kern *, ctx,
5982 	   int, level, int, optname, char *, optval, int, optlen)
5983 {
5984 	return _bpf_getsockopt(ctx->sk, level, optname, optval, optlen);
5985 }
5986 
5987 static const struct bpf_func_proto bpf_sock_addr_getsockopt_proto = {
5988 	.func		= bpf_sock_addr_getsockopt,
5989 	.gpl_only	= false,
5990 	.ret_type	= RET_INTEGER,
5991 	.arg1_type	= ARG_PTR_TO_CTX,
5992 	.arg2_type	= ARG_ANYTHING,
5993 	.arg3_type	= ARG_ANYTHING,
5994 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5995 	.arg5_type	= ARG_MEM_SIZE,
5996 };
5997 
5998 static int sk_bpf_set_get_bypass_prot_mem(struct sock *sk,
5999 					  char *optval, int optlen,
6000 					  bool getopt)
6001 {
6002 	int val;
6003 
6004 	if (optlen != sizeof(int))
6005 		return -EINVAL;
6006 
6007 	if (!sk_has_account(sk))
6008 		return -EOPNOTSUPP;
6009 
6010 	if (getopt) {
6011 		*(int *)optval = sk->sk_bypass_prot_mem;
6012 		return 0;
6013 	}
6014 
6015 	val = *(int *)optval;
6016 	if (val < 0 || val > 1)
6017 		return -EINVAL;
6018 
6019 	sk->sk_bypass_prot_mem = val;
6020 	return 0;
6021 }
6022 
6023 BPF_CALL_5(bpf_sock_create_setsockopt, struct sock *, sk, int, level,
6024 	   int, optname, char *, optval, int, optlen)
6025 {
6026 	if (level == SOL_SOCKET && optname == SK_BPF_BYPASS_PROT_MEM)
6027 		return sk_bpf_set_get_bypass_prot_mem(sk, optval, optlen, false);
6028 
6029 	return __bpf_setsockopt(sk, level, optname, optval, optlen);
6030 }
6031 
6032 static const struct bpf_func_proto bpf_sock_create_setsockopt_proto = {
6033 	.func		= bpf_sock_create_setsockopt,
6034 	.gpl_only	= false,
6035 	.ret_type	= RET_INTEGER,
6036 	.arg1_type	= ARG_PTR_TO_CTX,
6037 	.arg2_type	= ARG_ANYTHING,
6038 	.arg3_type	= ARG_ANYTHING,
6039 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6040 	.arg5_type	= ARG_MEM_SIZE,
6041 };
6042 
6043 BPF_CALL_5(bpf_sock_create_getsockopt, struct sock *, sk, int, level,
6044 	   int, optname, char *, optval, int, optlen)
6045 {
6046 	if (level == SOL_SOCKET && optname == SK_BPF_BYPASS_PROT_MEM) {
6047 		int err = sk_bpf_set_get_bypass_prot_mem(sk, optval, optlen, true);
6048 
6049 		if (err)
6050 			memset(optval, 0, optlen);
6051 
6052 		return err;
6053 	}
6054 
6055 	return __bpf_getsockopt(sk, level, optname, optval, optlen);
6056 }
6057 
6058 static const struct bpf_func_proto bpf_sock_create_getsockopt_proto = {
6059 	.func		= bpf_sock_create_getsockopt,
6060 	.gpl_only	= false,
6061 	.ret_type	= RET_INTEGER,
6062 	.arg1_type	= ARG_PTR_TO_CTX,
6063 	.arg2_type	= ARG_ANYTHING,
6064 	.arg3_type	= ARG_ANYTHING,
6065 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
6066 	.arg5_type	= ARG_MEM_SIZE,
6067 };
6068 
6069 BPF_CALL_5(bpf_sock_ops_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
6070 	   int, level, int, optname, char *, optval, int, optlen)
6071 {
6072 	if (!is_locked_tcp_sock_ops(bpf_sock))
6073 		return -EOPNOTSUPP;
6074 
6075 	/* TCP_NODELAY triggers tcp_push_pending_frames() and re-enters these callbacks. */
6076 	if ((bpf_sock->op == BPF_SOCK_OPS_HDR_OPT_LEN_CB ||
6077 	     bpf_sock->op == BPF_SOCK_OPS_WRITE_HDR_OPT_CB) &&
6078 	    level == SOL_TCP && optname == TCP_NODELAY)
6079 		return -EOPNOTSUPP;
6080 
6081 	return _bpf_setsockopt(bpf_sock->sk, level, optname, optval, optlen);
6082 }
6083 
6084 static const struct bpf_func_proto bpf_sock_ops_setsockopt_proto = {
6085 	.func		= bpf_sock_ops_setsockopt,
6086 	.gpl_only	= false,
6087 	.ret_type	= RET_INTEGER,
6088 	.arg1_type	= ARG_PTR_TO_CTX,
6089 	.arg2_type	= ARG_ANYTHING,
6090 	.arg3_type	= ARG_ANYTHING,
6091 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6092 	.arg5_type	= ARG_MEM_SIZE,
6093 };
6094 
6095 static int bpf_sock_ops_get_syn(struct bpf_sock_ops_kern *bpf_sock,
6096 				int optname, const u8 **start)
6097 {
6098 	struct sk_buff *syn_skb = bpf_sock->syn_skb;
6099 	const u8 *hdr_start;
6100 	int ret;
6101 
6102 	if (syn_skb) {
6103 		/* sk is a request_sock here */
6104 
6105 		if (optname == TCP_BPF_SYN) {
6106 			hdr_start = syn_skb->data;
6107 			ret = tcp_hdrlen(syn_skb);
6108 		} else if (optname == TCP_BPF_SYN_IP) {
6109 			hdr_start = skb_network_header(syn_skb);
6110 			ret = skb_network_header_len(syn_skb) +
6111 				tcp_hdrlen(syn_skb);
6112 		} else {
6113 			/* optname == TCP_BPF_SYN_MAC */
6114 			hdr_start = skb_mac_header(syn_skb);
6115 			ret = skb_mac_header_len(syn_skb) +
6116 				skb_network_header_len(syn_skb) +
6117 				tcp_hdrlen(syn_skb);
6118 		}
6119 	} else {
6120 		struct sock *sk = bpf_sock->sk;
6121 		struct saved_syn *saved_syn;
6122 
6123 		if (sk->sk_state == TCP_NEW_SYN_RECV)
6124 			/* synack retransmit. bpf_sock->syn_skb will
6125 			 * not be available.  It has to resort to
6126 			 * saved_syn (if it is saved).
6127 			 */
6128 			saved_syn = inet_reqsk(sk)->saved_syn;
6129 		else
6130 			saved_syn = tcp_sk(sk)->saved_syn;
6131 
6132 		if (!saved_syn)
6133 			return -ENOENT;
6134 
6135 		if (optname == TCP_BPF_SYN) {
6136 			hdr_start = saved_syn->data +
6137 				saved_syn->mac_hdrlen +
6138 				saved_syn->network_hdrlen;
6139 			ret = saved_syn->tcp_hdrlen;
6140 		} else if (optname == TCP_BPF_SYN_IP) {
6141 			hdr_start = saved_syn->data +
6142 				saved_syn->mac_hdrlen;
6143 			ret = saved_syn->network_hdrlen +
6144 				saved_syn->tcp_hdrlen;
6145 		} else {
6146 			/* optname == TCP_BPF_SYN_MAC */
6147 
6148 			/* TCP_SAVE_SYN may not have saved the mac hdr */
6149 			if (!saved_syn->mac_hdrlen)
6150 				return -ENOENT;
6151 
6152 			hdr_start = saved_syn->data;
6153 			ret = saved_syn->mac_hdrlen +
6154 				saved_syn->network_hdrlen +
6155 				saved_syn->tcp_hdrlen;
6156 		}
6157 	}
6158 
6159 	*start = hdr_start;
6160 	return ret;
6161 }
6162 
6163 BPF_CALL_5(bpf_sock_ops_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
6164 	   int, level, int, optname, char *, optval, int, optlen)
6165 {
6166 	if (!is_locked_tcp_sock_ops(bpf_sock))
6167 		return -EOPNOTSUPP;
6168 
6169 	if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP &&
6170 	    optname >= TCP_BPF_SYN && optname <= TCP_BPF_SYN_MAC) {
6171 		int ret, copy_len = 0;
6172 		const u8 *start;
6173 
6174 		ret = bpf_sock_ops_get_syn(bpf_sock, optname, &start);
6175 		if (ret > 0) {
6176 			copy_len = ret;
6177 			if (optlen < copy_len) {
6178 				copy_len = optlen;
6179 				ret = -ENOSPC;
6180 			}
6181 
6182 			memcpy(optval, start, copy_len);
6183 		}
6184 
6185 		/* Zero out unused buffer at the end */
6186 		memset(optval + copy_len, 0, optlen - copy_len);
6187 
6188 		return ret;
6189 	}
6190 
6191 	return _bpf_getsockopt(bpf_sock->sk, level, optname, optval, optlen);
6192 }
6193 
6194 static const struct bpf_func_proto bpf_sock_ops_getsockopt_proto = {
6195 	.func		= bpf_sock_ops_getsockopt,
6196 	.gpl_only	= false,
6197 	.ret_type	= RET_INTEGER,
6198 	.arg1_type	= ARG_PTR_TO_CTX,
6199 	.arg2_type	= ARG_ANYTHING,
6200 	.arg3_type	= ARG_ANYTHING,
6201 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
6202 	.arg5_type	= ARG_MEM_SIZE,
6203 };
6204 
6205 BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
6206 	   int, argval)
6207 {
6208 	struct sock *sk = bpf_sock->sk;
6209 	int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
6210 
6211 	if (!is_locked_tcp_sock_ops(bpf_sock))
6212 		return -EOPNOTSUPP;
6213 
6214 	if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
6215 		return -EINVAL;
6216 
6217 	tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
6218 
6219 	return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
6220 }
6221 
6222 static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
6223 	.func		= bpf_sock_ops_cb_flags_set,
6224 	.gpl_only	= false,
6225 	.ret_type	= RET_INTEGER,
6226 	.arg1_type	= ARG_PTR_TO_CTX,
6227 	.arg2_type	= ARG_ANYTHING,
6228 };
6229 
6230 BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
6231 	   int, addr_len)
6232 {
6233 #ifdef CONFIG_INET
6234 	struct sock *sk = ctx->sk;
6235 	u32 flags = BIND_FROM_BPF;
6236 	int err;
6237 
6238 	err = -EINVAL;
6239 	if (addr_len < offsetofend(struct sockaddr, sa_family))
6240 		return err;
6241 	if (addr->sa_family == AF_INET) {
6242 		if (addr_len < sizeof(struct sockaddr_in))
6243 			return err;
6244 		if (((struct sockaddr_in *)addr)->sin_port == htons(0))
6245 			flags |= BIND_FORCE_ADDRESS_NO_PORT;
6246 		return __inet_bind(sk, (struct sockaddr_unsized *)addr, addr_len, flags);
6247 #if IS_ENABLED(CONFIG_IPV6)
6248 	} else if (addr->sa_family == AF_INET6) {
6249 		if (addr_len < SIN6_LEN_RFC2133)
6250 			return err;
6251 		if (((struct sockaddr_in6 *)addr)->sin6_port == htons(0))
6252 			flags |= BIND_FORCE_ADDRESS_NO_PORT;
6253 
6254 		return __inet6_bind(sk, (struct sockaddr_unsized *)addr,
6255 				    addr_len, flags);
6256 #endif /* CONFIG_IPV6 */
6257 	}
6258 #endif /* CONFIG_INET */
6259 
6260 	return -EAFNOSUPPORT;
6261 }
6262 
6263 static const struct bpf_func_proto bpf_bind_proto = {
6264 	.func		= bpf_bind,
6265 	.gpl_only	= false,
6266 	.ret_type	= RET_INTEGER,
6267 	.arg1_type	= ARG_PTR_TO_CTX,
6268 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6269 	.arg3_type	= ARG_MEM_SIZE,
6270 };
6271 
6272 #ifdef CONFIG_XFRM
6273 
6274 #if (IS_BUILTIN(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) || \
6275     (IS_MODULE(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
6276 
6277 struct metadata_dst __percpu *xfrm_bpf_md_dst;
6278 EXPORT_SYMBOL_GPL(xfrm_bpf_md_dst);
6279 
6280 #endif
6281 
6282 BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
6283 	   struct bpf_xfrm_state *, to, u32, size, u64, flags)
6284 {
6285 	const struct sec_path *sp = skb_sec_path(skb);
6286 	const struct xfrm_state *x;
6287 
6288 	if (!sp || unlikely(index >= sp->len || flags))
6289 		goto err_clear;
6290 
6291 	x = sp->xvec[index];
6292 
6293 	if (unlikely(size != sizeof(struct bpf_xfrm_state)))
6294 		goto err_clear;
6295 
6296 	to->reqid = x->props.reqid;
6297 	to->spi = x->id.spi;
6298 	to->family = x->props.family;
6299 	to->ext = 0;
6300 
6301 	if (to->family == AF_INET6) {
6302 		memcpy(to->remote_ipv6, x->props.saddr.a6,
6303 		       sizeof(to->remote_ipv6));
6304 	} else {
6305 		to->remote_ipv4 = x->props.saddr.a4;
6306 		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
6307 	}
6308 
6309 	return 0;
6310 err_clear:
6311 	memset(to, 0, size);
6312 	return -EINVAL;
6313 }
6314 
6315 static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
6316 	.func		= bpf_skb_get_xfrm_state,
6317 	.gpl_only	= false,
6318 	.ret_type	= RET_INTEGER,
6319 	.arg1_type	= ARG_PTR_TO_CTX,
6320 	.arg2_type	= ARG_ANYTHING,
6321 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
6322 	.arg4_type	= ARG_MEM_SIZE,
6323 	.arg5_type	= ARG_ANYTHING,
6324 };
6325 #endif
6326 
6327 #if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
6328 static int bpf_fib_set_fwd_params(struct net_device *dev,
6329 				  struct bpf_fib_lookup *params,
6330 				  u32 flags, u32 mtu, u32 in_ifindex)
6331 {
6332 	params->h_vlan_TCI = 0;
6333 	params->h_vlan_proto = 0;
6334 
6335 #if IS_ENABLED(CONFIG_VLAN_8021Q)
6336 	if ((flags & BPF_FIB_LOOKUP_VLAN) && is_vlan_dev(dev)) {
6337 		struct net_device *real_dev = vlan_dev_priv(dev)->real_dev;
6338 
6339 		if (!is_vlan_dev(real_dev) &&
6340 		    net_eq(dev_net(real_dev), dev_net(dev))) {
6341 			params->h_vlan_proto = vlan_dev_vlan_proto(dev);
6342 			params->h_vlan_TCI = htons(vlan_dev_vlan_id(dev));
6343 			params->ifindex = real_dev->ifindex;
6344 		} else {
6345 			params->ifindex = in_ifindex;
6346 			return BPF_FIB_LKUP_RET_VLAN_FAILURE;
6347 		}
6348 	}
6349 #endif
6350 
6351 	if (mtu)
6352 		params->mtu_result = mtu; /* union with tot_len */
6353 
6354 	return 0;
6355 }
6356 
6357 static struct net_device *bpf_fib_vlan_input_dev(struct net_device *dev,
6358 						 const struct bpf_fib_lookup *params)
6359 {
6360 	__be16 proto = params->h_vlan_proto;
6361 	struct net_device *vlan_dev;
6362 	u16 vid;
6363 
6364 	if (proto != htons(ETH_P_8021Q) && proto != htons(ETH_P_8021AD))
6365 		return ERR_PTR(-EINVAL);
6366 
6367 	vid = ntohs(params->h_vlan_TCI) & VLAN_VID_MASK;
6368 	vlan_dev = __vlan_find_dev_deep_rcu(dev, proto, vid);
6369 	if (!vlan_dev || !(vlan_dev->flags & IFF_UP) ||
6370 	    !net_eq(dev_net(vlan_dev), dev_net(dev)))
6371 		return NULL;
6372 
6373 	return vlan_dev;
6374 }
6375 #endif
6376 
6377 #if IS_ENABLED(CONFIG_INET)
6378 static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
6379 			       u32 flags, bool check_mtu)
6380 {
6381 	u32 in_ifindex = params->ifindex;
6382 	struct neighbour *neigh = NULL;
6383 	struct fib_nh_common *nhc;
6384 	struct in_device *in_dev;
6385 	struct net_device *dev;
6386 	struct fib_result res;
6387 	struct flowi4 fl4 = {};
6388 	u32 mtu = 0;
6389 	int err;
6390 
6391 	dev = dev_get_by_index_rcu(net, params->ifindex);
6392 	if (unlikely(!dev))
6393 		return -ENODEV;
6394 
6395 	if (flags & BPF_FIB_LOOKUP_VLAN_INPUT) {
6396 		dev = bpf_fib_vlan_input_dev(dev, params);
6397 		if (IS_ERR(dev))
6398 			return PTR_ERR(dev);
6399 		if (!dev)
6400 			return BPF_FIB_LKUP_RET_NOT_FWDED;
6401 	}
6402 
6403 	/* verify forwarding is enabled on this interface */
6404 	in_dev = __in_dev_get_rcu(dev);
6405 	if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
6406 		return BPF_FIB_LKUP_RET_FWD_DISABLED;
6407 
6408 	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
6409 		fl4.flowi4_iif = 1;
6410 		fl4.flowi4_oif = params->ifindex;
6411 	} else {
6412 		/*
6413 		 * dev->ifindex, not params->ifindex: VLAN_INPUT may have
6414 		 * resolved dev to a subinterface above.
6415 		 */
6416 		fl4.flowi4_iif = dev->ifindex;
6417 		fl4.flowi4_oif = 0;
6418 	}
6419 	fl4.flowi4_dscp = inet_dsfield_to_dscp(params->tos);
6420 	fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
6421 	fl4.flowi4_flags = 0;
6422 
6423 	fl4.flowi4_proto = params->l4_protocol;
6424 	fl4.daddr = params->ipv4_dst;
6425 	fl4.saddr = params->ipv4_src;
6426 	fl4.fl4_sport = params->sport;
6427 	fl4.fl4_dport = params->dport;
6428 	fl4.flowi4_multipath_hash = 0;
6429 
6430 	if (flags & BPF_FIB_LOOKUP_DIRECT) {
6431 		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
6432 		struct fib_table *tb;
6433 
6434 		if (flags & BPF_FIB_LOOKUP_TBID) {
6435 			tbid = params->tbid;
6436 			/* zero out for vlan output */
6437 			params->tbid = 0;
6438 		}
6439 
6440 		tb = fib_get_table(net, tbid);
6441 		if (unlikely(!tb))
6442 			return BPF_FIB_LKUP_RET_NOT_FWDED;
6443 
6444 		err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
6445 	} else {
6446 		if (flags & BPF_FIB_LOOKUP_MARK)
6447 			fl4.flowi4_mark = params->mark;
6448 		else
6449 			fl4.flowi4_mark = 0;
6450 		fl4.flowi4_secid = 0;
6451 		fl4.flowi4_tun_key.tun_id = 0;
6452 		fl4.flowi4_uid = sock_net_uid(net, NULL);
6453 
6454 		err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
6455 	}
6456 
6457 	if (err) {
6458 		/* map fib lookup errors to RTN_ type */
6459 		if (err == -EINVAL)
6460 			return BPF_FIB_LKUP_RET_BLACKHOLE;
6461 		if (err == -EHOSTUNREACH)
6462 			return BPF_FIB_LKUP_RET_UNREACHABLE;
6463 		if (err == -EACCES)
6464 			return BPF_FIB_LKUP_RET_PROHIBIT;
6465 
6466 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6467 	}
6468 
6469 	if (res.type != RTN_UNICAST)
6470 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6471 
6472 	if (fib_info_num_path(res.fi) > 1)
6473 		fib_select_path(net, &res, &fl4, NULL);
6474 
6475 	if (check_mtu) {
6476 		mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
6477 		if (params->tot_len > mtu) {
6478 			params->mtu_result = mtu; /* union with tot_len */
6479 			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
6480 		}
6481 	}
6482 
6483 	nhc = res.nhc;
6484 
6485 	/* do not handle lwt encaps right now */
6486 	if (nhc->nhc_lwtstate)
6487 		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
6488 
6489 	dev = nhc->nhc_dev;
6490 
6491 	params->rt_metric = res.fi->fib_priority;
6492 	params->ifindex = dev->ifindex;
6493 
6494 	if (flags & BPF_FIB_LOOKUP_SRC)
6495 		params->ipv4_src = fib_result_prefsrc(net, &res);
6496 
6497 	/* xdp and cls_bpf programs are run in RCU-bh so
6498 	 * rcu_read_lock_bh is not needed here
6499 	 */
6500 	if (likely(nhc->nhc_gw_family != AF_INET6)) {
6501 		if (nhc->nhc_gw_family)
6502 			params->ipv4_dst = nhc->nhc_gw.ipv4;
6503 	} else {
6504 		struct in6_addr *dst = (struct in6_addr *)params->ipv6_dst;
6505 
6506 		params->family = AF_INET6;
6507 		*dst = nhc->nhc_gw.ipv6;
6508 	}
6509 
6510 	if (flags & BPF_FIB_LOOKUP_SKIP_NEIGH)
6511 		goto set_fwd_params;
6512 
6513 	if (likely(nhc->nhc_gw_family != AF_INET6))
6514 		neigh = __ipv4_neigh_lookup_noref(dev,
6515 						  (__force u32)params->ipv4_dst);
6516 	else if (IS_ENABLED(CONFIG_IPV6))
6517 		neigh = __ipv6_neigh_lookup_noref(dev, params->ipv6_dst);
6518 
6519 	if (!neigh || !(READ_ONCE(neigh->nud_state) & NUD_VALID))
6520 		return BPF_FIB_LKUP_RET_NO_NEIGH;
6521 	memcpy(params->dmac, neigh->ha, ETH_ALEN);
6522 	memcpy(params->smac, dev->dev_addr, ETH_ALEN);
6523 
6524 set_fwd_params:
6525 	return bpf_fib_set_fwd_params(dev, params, flags, mtu, in_ifindex);
6526 }
6527 #endif
6528 
6529 #if IS_ENABLED(CONFIG_IPV6)
6530 static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
6531 			       u32 flags, bool check_mtu)
6532 {
6533 	struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
6534 	struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
6535 	u32 in_ifindex = params->ifindex;
6536 	struct fib6_result res = {};
6537 	struct neighbour *neigh;
6538 	struct net_device *dev;
6539 	struct inet6_dev *idev;
6540 	struct flowi6 fl6 = {};
6541 	int strict = 0;
6542 	int oif, err;
6543 	u32 mtu = 0;
6544 
6545 	/* link local addresses are never forwarded */
6546 	if (rt6_need_strict(dst) || rt6_need_strict(src))
6547 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6548 
6549 	dev = dev_get_by_index_rcu(net, params->ifindex);
6550 	if (unlikely(!dev))
6551 		return -ENODEV;
6552 
6553 	if (flags & BPF_FIB_LOOKUP_VLAN_INPUT) {
6554 		dev = bpf_fib_vlan_input_dev(dev, params);
6555 		if (IS_ERR(dev))
6556 			return PTR_ERR(dev);
6557 		if (!dev)
6558 			return BPF_FIB_LKUP_RET_NOT_FWDED;
6559 	}
6560 
6561 	idev = __in6_dev_get_safely(dev);
6562 	if (unlikely(!idev || !READ_ONCE(idev->cnf.forwarding)))
6563 		return BPF_FIB_LKUP_RET_FWD_DISABLED;
6564 
6565 	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
6566 		fl6.flowi6_iif = 1;
6567 		oif = fl6.flowi6_oif = params->ifindex;
6568 	} else {
6569 		/*
6570 		 * dev->ifindex, not params->ifindex: VLAN_INPUT may have
6571 		 * resolved dev to a subinterface above.
6572 		 */
6573 		oif = dev->ifindex;
6574 		fl6.flowi6_iif = oif;
6575 		fl6.flowi6_oif = 0;
6576 		strict = RT6_LOOKUP_F_HAS_SADDR;
6577 	}
6578 	fl6.flowlabel = params->flowinfo;
6579 	fl6.flowi6_scope = 0;
6580 	fl6.flowi6_flags = 0;
6581 	fl6.mp_hash = 0;
6582 
6583 	fl6.flowi6_proto = params->l4_protocol;
6584 	fl6.daddr = *dst;
6585 	fl6.saddr = *src;
6586 	fl6.fl6_sport = params->sport;
6587 	fl6.fl6_dport = params->dport;
6588 
6589 	if (flags & BPF_FIB_LOOKUP_DIRECT) {
6590 		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
6591 		struct fib6_table *tb;
6592 
6593 		if (flags & BPF_FIB_LOOKUP_TBID) {
6594 			tbid = params->tbid;
6595 			/* zero out for vlan output */
6596 			params->tbid = 0;
6597 		}
6598 
6599 		tb = fib6_get_table(net, tbid);
6600 		if (unlikely(!tb))
6601 			return BPF_FIB_LKUP_RET_NOT_FWDED;
6602 
6603 		err = fib6_table_lookup(net, tb, oif, &fl6, &res, strict);
6604 	} else {
6605 		if (flags & BPF_FIB_LOOKUP_MARK)
6606 			fl6.flowi6_mark = params->mark;
6607 		else
6608 			fl6.flowi6_mark = 0;
6609 		fl6.flowi6_secid = 0;
6610 		fl6.flowi6_tun_key.tun_id = 0;
6611 		fl6.flowi6_uid = sock_net_uid(net, NULL);
6612 
6613 		err = fib6_lookup(net, oif, &fl6, &res, strict);
6614 	}
6615 
6616 	if (unlikely(err || IS_ERR_OR_NULL(res.f6i) ||
6617 		     res.f6i == net->ipv6.fib6_null_entry))
6618 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6619 
6620 	switch (res.fib6_type) {
6621 	/* only unicast is forwarded */
6622 	case RTN_UNICAST:
6623 		break;
6624 	case RTN_BLACKHOLE:
6625 		return BPF_FIB_LKUP_RET_BLACKHOLE;
6626 	case RTN_UNREACHABLE:
6627 		return BPF_FIB_LKUP_RET_UNREACHABLE;
6628 	case RTN_PROHIBIT:
6629 		return BPF_FIB_LKUP_RET_PROHIBIT;
6630 	default:
6631 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6632 	}
6633 
6634 	fib6_select_path(net, &res, &fl6, fl6.flowi6_oif,
6635 			 fl6.flowi6_oif != 0, NULL, strict);
6636 
6637 	if (check_mtu) {
6638 		mtu = ip6_mtu_from_fib6(&res, dst, src);
6639 		if (params->tot_len > mtu) {
6640 			params->mtu_result = mtu; /* union with tot_len */
6641 			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
6642 		}
6643 	}
6644 
6645 	if (res.nh->fib_nh_lws)
6646 		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
6647 
6648 	if (res.nh->fib_nh_gw_family)
6649 		*dst = res.nh->fib_nh_gw6;
6650 
6651 	dev = res.nh->fib_nh_dev;
6652 	params->rt_metric = res.f6i->fib6_metric;
6653 	params->ifindex = dev->ifindex;
6654 
6655 	if (flags & BPF_FIB_LOOKUP_SRC) {
6656 		if (res.f6i->fib6_prefsrc.plen) {
6657 			*src = res.f6i->fib6_prefsrc.addr;
6658 		} else {
6659 			err = ipv6_dev_get_saddr(net, dev, &fl6.daddr, 0, src);
6660 			if (err)
6661 				return BPF_FIB_LKUP_RET_NO_SRC_ADDR;
6662 		}
6663 	}
6664 
6665 	if (flags & BPF_FIB_LOOKUP_SKIP_NEIGH)
6666 		goto set_fwd_params;
6667 
6668 	/* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
6669 	 * not needed here.
6670 	 */
6671 	neigh = __ipv6_neigh_lookup_noref(dev, dst);
6672 	if (!neigh || !(READ_ONCE(neigh->nud_state) & NUD_VALID))
6673 		return BPF_FIB_LKUP_RET_NO_NEIGH;
6674 	memcpy(params->dmac, neigh->ha, ETH_ALEN);
6675 	memcpy(params->smac, dev->dev_addr, ETH_ALEN);
6676 
6677 set_fwd_params:
6678 	return bpf_fib_set_fwd_params(dev, params, flags, mtu, in_ifindex);
6679 }
6680 #endif
6681 
6682 #define BPF_FIB_LOOKUP_MASK (BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT | \
6683 			     BPF_FIB_LOOKUP_SKIP_NEIGH | BPF_FIB_LOOKUP_TBID | \
6684 			     BPF_FIB_LOOKUP_SRC | BPF_FIB_LOOKUP_MARK | \
6685 			     BPF_FIB_LOOKUP_VLAN | BPF_FIB_LOOKUP_VLAN_INPUT)
6686 
6687 static bool bpf_fib_lookup_flags_ok(u32 flags)
6688 {
6689 	if (flags & ~BPF_FIB_LOOKUP_MASK)
6690 		return false;
6691 
6692 	if ((flags & BPF_FIB_LOOKUP_VLAN_INPUT) &&
6693 	    (flags & (BPF_FIB_LOOKUP_TBID | BPF_FIB_LOOKUP_OUTPUT)))
6694 		return false;
6695 
6696 	return true;
6697 }
6698 
6699 BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
6700 	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
6701 {
6702 	if (plen < sizeof(*params))
6703 		return -EINVAL;
6704 
6705 	if (!bpf_fib_lookup_flags_ok(flags))
6706 		return -EINVAL;
6707 
6708 	switch (params->family) {
6709 #if IS_ENABLED(CONFIG_INET)
6710 	case AF_INET:
6711 		return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
6712 					   flags, true);
6713 #endif
6714 #if IS_ENABLED(CONFIG_IPV6)
6715 	case AF_INET6:
6716 		return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
6717 					   flags, true);
6718 #endif
6719 	}
6720 	return -EAFNOSUPPORT;
6721 }
6722 
6723 static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
6724 	.func		= bpf_xdp_fib_lookup,
6725 	.gpl_only	= true,
6726 	.ret_type	= RET_INTEGER,
6727 	.arg1_type      = ARG_PTR_TO_CTX,
6728 	.arg2_type      = ARG_PTR_TO_MEM | MEM_WRITE,
6729 	.arg3_type      = ARG_MEM_SIZE,
6730 	.arg4_type	= ARG_ANYTHING,
6731 };
6732 
6733 BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
6734 	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
6735 {
6736 	struct net *net = dev_net(skb->dev);
6737 	int rc = -EAFNOSUPPORT;
6738 	bool check_mtu = false;
6739 
6740 	if (plen < sizeof(*params))
6741 		return -EINVAL;
6742 
6743 	if (!bpf_fib_lookup_flags_ok(flags))
6744 		return -EINVAL;
6745 
6746 	if (flags & BPF_FIB_LOOKUP_VLAN)
6747 		return -EINVAL;
6748 
6749 	if (params->tot_len)
6750 		check_mtu = true;
6751 
6752 	switch (params->family) {
6753 #if IS_ENABLED(CONFIG_INET)
6754 	case AF_INET:
6755 		rc = bpf_ipv4_fib_lookup(net, params, flags, check_mtu);
6756 		break;
6757 #endif
6758 #if IS_ENABLED(CONFIG_IPV6)
6759 	case AF_INET6:
6760 		rc = bpf_ipv6_fib_lookup(net, params, flags, check_mtu);
6761 		break;
6762 #endif
6763 	}
6764 
6765 	if (rc == BPF_FIB_LKUP_RET_SUCCESS && !check_mtu) {
6766 		struct net_device *dev;
6767 
6768 		/* When tot_len isn't provided by user, check skb
6769 		 * against MTU of FIB lookup resulting net_device
6770 		 */
6771 		dev = dev_get_by_index_rcu(net, params->ifindex);
6772 		if (unlikely(!dev))
6773 			return -ENODEV;
6774 		if (!is_skb_forwardable(dev, skb))
6775 			rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
6776 
6777 		params->mtu_result = dev->mtu; /* union with tot_len */
6778 	}
6779 
6780 	return rc;
6781 }
6782 
6783 static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
6784 	.func		= bpf_skb_fib_lookup,
6785 	.gpl_only	= true,
6786 	.ret_type	= RET_INTEGER,
6787 	.arg1_type      = ARG_PTR_TO_CTX,
6788 	.arg2_type      = ARG_PTR_TO_MEM | MEM_WRITE,
6789 	.arg3_type      = ARG_MEM_SIZE,
6790 	.arg4_type	= ARG_ANYTHING,
6791 };
6792 
6793 static struct net_device *__dev_via_ifindex(struct net_device *dev_curr,
6794 					    u32 ifindex)
6795 {
6796 	struct net *netns = dev_net(dev_curr);
6797 
6798 	/* Non-redirect use-cases can use ifindex=0 and save ifindex lookup */
6799 	if (ifindex == 0)
6800 		return dev_curr;
6801 
6802 	return dev_get_by_index_rcu(netns, ifindex);
6803 }
6804 
6805 BPF_CALL_5(bpf_skb_check_mtu, struct sk_buff *, skb,
6806 	   u32, ifindex, u32 *, mtu_len, s32, len_diff, u64, flags)
6807 {
6808 	int ret = BPF_MTU_CHK_RET_FRAG_NEEDED;
6809 	struct net_device *dev = skb->dev;
6810 	int mtu, dev_len, skb_len;
6811 
6812 	if (unlikely(flags & ~(BPF_MTU_CHK_SEGS)))
6813 		return -EINVAL;
6814 	if (unlikely(flags & BPF_MTU_CHK_SEGS && (len_diff || *mtu_len)))
6815 		return -EINVAL;
6816 
6817 	dev = __dev_via_ifindex(dev, ifindex);
6818 	if (unlikely(!dev))
6819 		return -ENODEV;
6820 
6821 	mtu = READ_ONCE(dev->mtu);
6822 	dev_len = mtu + dev->hard_header_len;
6823 
6824 	/* If set use *mtu_len as input, L3 as iph->tot_len (like fib_lookup) */
6825 	skb_len = *mtu_len ? *mtu_len + dev->hard_header_len : skb->len;
6826 
6827 	skb_len += len_diff; /* minus result pass check */
6828 	if (skb_len <= dev_len) {
6829 		ret = BPF_MTU_CHK_RET_SUCCESS;
6830 		goto out;
6831 	}
6832 	/* At this point, skb->len exceed MTU, but as it include length of all
6833 	 * segments, it can still be below MTU.  The SKB can possibly get
6834 	 * re-segmented in transmit path (see validate_xmit_skb).  Thus, user
6835 	 * must choose if segs are to be MTU checked.
6836 	 */
6837 	if (skb_is_gso(skb)) {
6838 		ret = BPF_MTU_CHK_RET_SUCCESS;
6839 		if (flags & BPF_MTU_CHK_SEGS) {
6840 			if (!skb_transport_header_was_set(skb))
6841 				return -EINVAL;
6842 			if (!skb_gso_validate_network_len(skb, mtu))
6843 				ret = BPF_MTU_CHK_RET_SEGS_TOOBIG;
6844 		}
6845 	}
6846 out:
6847 	*mtu_len = mtu;
6848 	return ret;
6849 }
6850 
6851 BPF_CALL_5(bpf_xdp_check_mtu, struct xdp_buff *, xdp,
6852 	   u32, ifindex, u32 *, mtu_len, s32, len_diff, u64, flags)
6853 {
6854 	struct net_device *dev = xdp->rxq->dev;
6855 	int xdp_len = xdp->data_end - xdp->data;
6856 	int ret = BPF_MTU_CHK_RET_SUCCESS;
6857 	int mtu, dev_len;
6858 
6859 	/* XDP variant doesn't support multi-buffer segment check (yet) */
6860 	if (unlikely(flags))
6861 		return -EINVAL;
6862 
6863 	dev = __dev_via_ifindex(dev, ifindex);
6864 	if (unlikely(!dev))
6865 		return -ENODEV;
6866 
6867 	mtu = READ_ONCE(dev->mtu);
6868 	dev_len = mtu + dev->hard_header_len;
6869 
6870 	/* Use *mtu_len as input, L3 as iph->tot_len (like fib_lookup) */
6871 	if (*mtu_len)
6872 		xdp_len = *mtu_len + dev->hard_header_len;
6873 
6874 	xdp_len += len_diff; /* minus result pass check */
6875 	if (xdp_len > dev_len)
6876 		ret = BPF_MTU_CHK_RET_FRAG_NEEDED;
6877 
6878 	*mtu_len = mtu;
6879 	return ret;
6880 }
6881 
6882 static const struct bpf_func_proto bpf_skb_check_mtu_proto = {
6883 	.func		= bpf_skb_check_mtu,
6884 	.gpl_only	= true,
6885 	.ret_type	= RET_INTEGER,
6886 	.arg1_type      = ARG_PTR_TO_CTX,
6887 	.arg2_type      = ARG_ANYTHING,
6888 	.arg3_type      = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_WRITE | MEM_ALIGNED,
6889 	.arg3_size	= sizeof(u32),
6890 	.arg4_type      = ARG_ANYTHING,
6891 	.arg5_type      = ARG_ANYTHING,
6892 };
6893 
6894 static const struct bpf_func_proto bpf_xdp_check_mtu_proto = {
6895 	.func		= bpf_xdp_check_mtu,
6896 	.gpl_only	= true,
6897 	.ret_type	= RET_INTEGER,
6898 	.arg1_type      = ARG_PTR_TO_CTX,
6899 	.arg2_type      = ARG_ANYTHING,
6900 	.arg3_type      = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_WRITE | MEM_ALIGNED,
6901 	.arg3_size	= sizeof(u32),
6902 	.arg4_type      = ARG_ANYTHING,
6903 	.arg5_type      = ARG_ANYTHING,
6904 };
6905 
6906 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6907 static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
6908 {
6909 	int err;
6910 	struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
6911 
6912 	if (!seg6_validate_srh(srh, len, false))
6913 		return -EINVAL;
6914 
6915 	switch (type) {
6916 	case BPF_LWT_ENCAP_SEG6_INLINE:
6917 		if (skb->protocol != htons(ETH_P_IPV6))
6918 			return -EBADMSG;
6919 
6920 		err = seg6_do_srh_inline(skb, srh);
6921 		break;
6922 	case BPF_LWT_ENCAP_SEG6:
6923 		skb_reset_inner_headers(skb);
6924 		skb->encapsulation = 1;
6925 		err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
6926 		break;
6927 	default:
6928 		return -EINVAL;
6929 	}
6930 
6931 	bpf_compute_data_pointers(skb);
6932 	if (err)
6933 		return err;
6934 
6935 	skb_set_transport_header(skb, sizeof(struct ipv6hdr));
6936 
6937 	return seg6_lookup_nexthop(skb, NULL, 0);
6938 }
6939 #endif /* CONFIG_IPV6_SEG6_BPF */
6940 
6941 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
6942 static int bpf_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len,
6943 			     bool ingress)
6944 {
6945 	return bpf_lwt_push_ip_encap(skb, hdr, len, ingress);
6946 }
6947 #endif
6948 
6949 BPF_CALL_4(bpf_lwt_in_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
6950 	   u32, len)
6951 {
6952 	switch (type) {
6953 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6954 	case BPF_LWT_ENCAP_SEG6:
6955 	case BPF_LWT_ENCAP_SEG6_INLINE:
6956 		return bpf_push_seg6_encap(skb, type, hdr, len);
6957 #endif
6958 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
6959 	case BPF_LWT_ENCAP_IP:
6960 		return bpf_push_ip_encap(skb, hdr, len, true /* ingress */);
6961 #endif
6962 	default:
6963 		return -EINVAL;
6964 	}
6965 }
6966 
6967 BPF_CALL_4(bpf_lwt_xmit_push_encap, struct sk_buff *, skb, u32, type,
6968 	   void *, hdr, u32, len)
6969 {
6970 	switch (type) {
6971 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
6972 	case BPF_LWT_ENCAP_IP:
6973 		return bpf_push_ip_encap(skb, hdr, len, false /* egress */);
6974 #endif
6975 	default:
6976 		return -EINVAL;
6977 	}
6978 }
6979 
6980 static const struct bpf_func_proto bpf_lwt_in_push_encap_proto = {
6981 	.func		= bpf_lwt_in_push_encap,
6982 	.gpl_only	= false,
6983 	.ret_type	= RET_INTEGER,
6984 	.arg1_type	= ARG_PTR_TO_CTX,
6985 	.arg2_type	= ARG_ANYTHING,
6986 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6987 	.arg4_type	= ARG_MEM_SIZE
6988 };
6989 
6990 static const struct bpf_func_proto bpf_lwt_xmit_push_encap_proto = {
6991 	.func		= bpf_lwt_xmit_push_encap,
6992 	.gpl_only	= false,
6993 	.ret_type	= RET_INTEGER,
6994 	.arg1_type	= ARG_PTR_TO_CTX,
6995 	.arg2_type	= ARG_ANYTHING,
6996 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6997 	.arg4_type	= ARG_MEM_SIZE
6998 };
6999 
7000 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
7001 BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
7002 	   const void *, from, u32, len)
7003 {
7004 	struct seg6_bpf_srh_state *srh_state =
7005 		this_cpu_ptr(&seg6_bpf_srh_states);
7006 	struct ipv6_sr_hdr *srh = srh_state->srh;
7007 	void *srh_tlvs, *srh_end, *ptr;
7008 	int srhoff = 0;
7009 
7010 	lockdep_assert_held(&srh_state->bh_lock);
7011 	if (srh == NULL)
7012 		return -EINVAL;
7013 
7014 	srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
7015 	srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
7016 
7017 	ptr = skb->data + offset;
7018 	if (ptr >= srh_tlvs && ptr + len <= srh_end)
7019 		srh_state->valid = false;
7020 	else if (ptr < (void *)&srh->flags ||
7021 		 ptr + len > (void *)&srh->segments)
7022 		return -EFAULT;
7023 
7024 	if (unlikely(bpf_try_make_writable(skb, offset + len)))
7025 		return -EFAULT;
7026 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
7027 		return -EINVAL;
7028 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
7029 
7030 	memcpy(skb->data + offset, from, len);
7031 	return 0;
7032 }
7033 
7034 static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
7035 	.func		= bpf_lwt_seg6_store_bytes,
7036 	.gpl_only	= false,
7037 	.ret_type	= RET_INTEGER,
7038 	.arg1_type	= ARG_PTR_TO_CTX,
7039 	.arg2_type	= ARG_ANYTHING,
7040 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7041 	.arg4_type	= ARG_MEM_SIZE
7042 };
7043 
7044 static void bpf_update_srh_state(struct sk_buff *skb)
7045 {
7046 	struct seg6_bpf_srh_state *srh_state =
7047 		this_cpu_ptr(&seg6_bpf_srh_states);
7048 
7049 	/* Behind a decapsulation this is a header that nobody has looked at */
7050 	srh_state->srh = seg6_get_srh(skb, 0);
7051 	if (srh_state->srh) {
7052 		srh_state->hdrlen = srh_state->srh->hdrlen << 3;
7053 		srh_state->valid = true;
7054 	}
7055 	/* it may have been pulled into the head */
7056 	bpf_compute_data_pointers(skb);
7057 }
7058 
7059 BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
7060 	   u32, action, void *, param, u32, param_len)
7061 {
7062 	struct seg6_bpf_srh_state *srh_state =
7063 		this_cpu_ptr(&seg6_bpf_srh_states);
7064 	int hdroff = 0;
7065 	int err;
7066 
7067 	lockdep_assert_held(&srh_state->bh_lock);
7068 	switch (action) {
7069 	case SEG6_LOCAL_ACTION_END_X:
7070 		if (!seg6_bpf_has_valid_srh(skb))
7071 			return -EBADMSG;
7072 		if (param_len != sizeof(struct in6_addr))
7073 			return -EINVAL;
7074 		return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
7075 	case SEG6_LOCAL_ACTION_END_T:
7076 		if (!seg6_bpf_has_valid_srh(skb))
7077 			return -EBADMSG;
7078 		if (param_len != sizeof(int))
7079 			return -EINVAL;
7080 		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
7081 	case SEG6_LOCAL_ACTION_END_DT6:
7082 		if (!seg6_bpf_has_valid_srh(skb))
7083 			return -EBADMSG;
7084 		if (param_len != sizeof(int))
7085 			return -EINVAL;
7086 
7087 		if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
7088 			return -EBADMSG;
7089 		/* As long as nothing has been changed, the program goes on */
7090 		if (!pskb_may_pull(skb, hdroff + sizeof(struct ipv6hdr))) {
7091 			/* but the head may have moved */
7092 			bpf_update_srh_state(skb);
7093 			return -EBADMSG;
7094 		}
7095 
7096 		__skb_pull(skb, hdroff);
7097 		skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
7098 		skb_reset_network_header(skb);
7099 		skb_reset_transport_header(skb);
7100 		skb->encapsulation = 0;
7101 
7102 		bpf_compute_data_pointers(skb);
7103 		bpf_update_srh_state(skb);
7104 		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
7105 	case SEG6_LOCAL_ACTION_END_B6:
7106 		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
7107 			return -EBADMSG;
7108 		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
7109 					  param, param_len);
7110 		/* The header can be in place although err says otherwise */
7111 		bpf_update_srh_state(skb);
7112 
7113 		return err;
7114 	case SEG6_LOCAL_ACTION_END_B6_ENCAP:
7115 		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
7116 			return -EBADMSG;
7117 		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
7118 					  param, param_len);
7119 		/* The header can be in place although err says otherwise */
7120 		bpf_update_srh_state(skb);
7121 
7122 		return err;
7123 	default:
7124 		return -EINVAL;
7125 	}
7126 }
7127 
7128 static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
7129 	.func		= bpf_lwt_seg6_action,
7130 	.gpl_only	= false,
7131 	.ret_type	= RET_INTEGER,
7132 	.arg1_type	= ARG_PTR_TO_CTX,
7133 	.arg2_type	= ARG_ANYTHING,
7134 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7135 	.arg4_type	= ARG_MEM_SIZE
7136 };
7137 
7138 BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
7139 	   s32, len)
7140 {
7141 	struct seg6_bpf_srh_state *srh_state =
7142 		this_cpu_ptr(&seg6_bpf_srh_states);
7143 	struct ipv6_sr_hdr *srh = srh_state->srh;
7144 	void *srh_end, *srh_tlvs, *ptr;
7145 	struct ipv6hdr *hdr;
7146 	int srhoff = 0;
7147 	int ret;
7148 
7149 	lockdep_assert_held(&srh_state->bh_lock);
7150 	if (unlikely(srh == NULL))
7151 		return -EINVAL;
7152 
7153 	srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
7154 			((srh->first_segment + 1) << 4));
7155 	srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
7156 			srh_state->hdrlen);
7157 	ptr = skb->data + offset;
7158 
7159 	if (unlikely(ptr < srh_tlvs || ptr > srh_end))
7160 		return -EFAULT;
7161 	if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
7162 		return -EFAULT;
7163 
7164 	if (len > 0) {
7165 		ret = skb_cow_head(skb, len);
7166 		if (unlikely(ret < 0))
7167 			return ret;
7168 
7169 		ret = bpf_skb_net_hdr_push(skb, offset, len);
7170 	} else {
7171 		ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
7172 	}
7173 
7174 	bpf_compute_data_pointers(skb);
7175 	if (unlikely(ret < 0))
7176 		return ret;
7177 
7178 	hdr = (struct ipv6hdr *)skb->data;
7179 	hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
7180 
7181 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
7182 		return -EINVAL;
7183 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
7184 	srh_state->hdrlen += len;
7185 	srh_state->valid = false;
7186 	return 0;
7187 }
7188 
7189 static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
7190 	.func		= bpf_lwt_seg6_adjust_srh,
7191 	.gpl_only	= false,
7192 	.ret_type	= RET_INTEGER,
7193 	.arg1_type	= ARG_PTR_TO_CTX,
7194 	.arg2_type	= ARG_ANYTHING,
7195 	.arg3_type	= ARG_ANYTHING,
7196 };
7197 #endif /* CONFIG_IPV6_SEG6_BPF */
7198 
7199 #ifdef CONFIG_INET
7200 static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple,
7201 			      int dif, int sdif, u8 family, u8 proto)
7202 {
7203 	bool refcounted = false;
7204 	struct sock *sk = NULL;
7205 
7206 	if (family == AF_INET) {
7207 		__be32 src4 = tuple->ipv4.saddr;
7208 		__be32 dst4 = tuple->ipv4.daddr;
7209 
7210 		if (proto == IPPROTO_TCP)
7211 			sk = __inet_lookup(net, NULL, 0,
7212 					   src4, tuple->ipv4.sport,
7213 					   dst4, tuple->ipv4.dport,
7214 					   dif, sdif, &refcounted);
7215 		else
7216 			sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport,
7217 					       dst4, tuple->ipv4.dport,
7218 					       dif, sdif, NULL);
7219 #if IS_ENABLED(CONFIG_IPV6)
7220 	} else {
7221 		struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
7222 		struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
7223 
7224 		if (proto == IPPROTO_TCP)
7225 			sk = __inet6_lookup(net, NULL, 0,
7226 					    src6, tuple->ipv6.sport,
7227 					    dst6, ntohs(tuple->ipv6.dport),
7228 					    dif, sdif, &refcounted);
7229 		else if (likely(ipv6_mod_enabled()))
7230 			sk = __udp6_lib_lookup(net, src6, tuple->ipv6.sport,
7231 					       dst6, tuple->ipv6.dport,
7232 					       dif, sdif, NULL);
7233 #endif
7234 	}
7235 
7236 	if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) {
7237 		WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
7238 		sk = NULL;
7239 	}
7240 	return sk;
7241 }
7242 
7243 /* bpf_skc_lookup performs the core lookup for different types of sockets,
7244  * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE.
7245  */
7246 static struct sock *
7247 __bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
7248 		 struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
7249 		 u64 flags, int sdif)
7250 {
7251 	struct sock *sk = NULL;
7252 	struct net *net;
7253 	u8 family;
7254 
7255 	if (len == sizeof(tuple->ipv4))
7256 		family = AF_INET;
7257 	else if (len == sizeof(tuple->ipv6))
7258 		family = AF_INET6;
7259 	else
7260 		return NULL;
7261 
7262 	if (unlikely(flags || !((s32)netns_id < 0 || netns_id <= S32_MAX)))
7263 		goto out;
7264 
7265 	if (sdif < 0) {
7266 		if (family == AF_INET)
7267 			sdif = inet_sdif(skb);
7268 		else
7269 			sdif = inet6_sdif(skb);
7270 	}
7271 
7272 	if ((s32)netns_id < 0) {
7273 		net = caller_net;
7274 		sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
7275 	} else {
7276 		net = get_net_ns_by_id(caller_net, netns_id);
7277 		if (unlikely(!net))
7278 			goto out;
7279 		sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
7280 		put_net(net);
7281 	}
7282 
7283 out:
7284 	return sk;
7285 }
7286 
7287 static struct sock *
7288 bpf_sk_lookup_full_sk(struct sock *sk)
7289 {
7290 	struct sock *sk2 = sk_to_full_sk(sk);
7291 
7292 	/*
7293 	 * sk_to_full_sk() may return sk->rsk_listener, make sure the original
7294 	 * sk sock refcnt is decremented to prevent a request_sock leak.
7295 	 */
7296 	if (sk2 != sk) {
7297 		sock_gen_put(sk);
7298 		/* Ensure there is no need to bump sk2 refcnt. */
7299 		if (unlikely(sk2 && !sock_flag(sk2, SOCK_RCU_FREE))) {
7300 			WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
7301 			return NULL;
7302 		}
7303 		sk = sk2;
7304 	}
7305 
7306 	return sk;
7307 }
7308 
7309 static struct sock *
7310 __bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
7311 		struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
7312 		u64 flags, int sdif)
7313 {
7314 	struct sock *sk = __bpf_skc_lookup(skb, tuple, len, caller_net,
7315 					   ifindex, proto, netns_id, flags,
7316 					   sdif);
7317 	if (sk)
7318 		sk = bpf_sk_lookup_full_sk(sk);
7319 	return sk;
7320 }
7321 
7322 static struct sock *
7323 bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
7324 	       u8 proto, u64 netns_id, u64 flags)
7325 {
7326 	struct net *caller_net;
7327 	int ifindex;
7328 
7329 	if (skb->dev) {
7330 		caller_net = dev_net(skb->dev);
7331 		ifindex = skb->dev->ifindex;
7332 	} else {
7333 		caller_net = sock_net(skb->sk);
7334 		ifindex = 0;
7335 	}
7336 
7337 	return __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto,
7338 				netns_id, flags, -1);
7339 }
7340 
7341 static struct sock *
7342 bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
7343 	      u8 proto, u64 netns_id, u64 flags)
7344 {
7345 	struct sock *sk = bpf_skc_lookup(skb, tuple, len, proto, netns_id,
7346 					 flags);
7347 	if (sk)
7348 		sk = bpf_sk_lookup_full_sk(sk);
7349 	return sk;
7350 }
7351 
7352 BPF_CALL_5(bpf_skc_lookup_tcp, struct sk_buff *, skb,
7353 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7354 {
7355 	return (unsigned long)bpf_skc_lookup(skb, tuple, len, IPPROTO_TCP,
7356 					     netns_id, flags);
7357 }
7358 
7359 static const struct bpf_func_proto bpf_skc_lookup_tcp_proto = {
7360 	.func		= bpf_skc_lookup_tcp,
7361 	.gpl_only	= false,
7362 	.pkt_access	= true,
7363 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
7364 	.arg1_type	= ARG_PTR_TO_CTX,
7365 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7366 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
7367 	.arg4_type	= ARG_ANYTHING,
7368 	.arg5_type	= ARG_ANYTHING,
7369 };
7370 
7371 BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb,
7372 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7373 {
7374 	return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP,
7375 					    netns_id, flags);
7376 }
7377 
7378 static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = {
7379 	.func		= bpf_sk_lookup_tcp,
7380 	.gpl_only	= false,
7381 	.pkt_access	= true,
7382 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7383 	.arg1_type	= ARG_PTR_TO_CTX,
7384 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7385 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
7386 	.arg4_type	= ARG_ANYTHING,
7387 	.arg5_type	= ARG_ANYTHING,
7388 };
7389 
7390 BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb,
7391 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7392 {
7393 	return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP,
7394 					    netns_id, flags);
7395 }
7396 
7397 static const struct bpf_func_proto bpf_sk_lookup_udp_proto = {
7398 	.func		= bpf_sk_lookup_udp,
7399 	.gpl_only	= false,
7400 	.pkt_access	= true,
7401 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7402 	.arg1_type	= ARG_PTR_TO_CTX,
7403 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7404 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
7405 	.arg4_type	= ARG_ANYTHING,
7406 	.arg5_type	= ARG_ANYTHING,
7407 };
7408 
7409 BPF_CALL_5(bpf_tc_skc_lookup_tcp, struct sk_buff *, skb,
7410 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7411 {
7412 	struct net_device *dev = skb->dev;
7413 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7414 	struct net *caller_net = dev_net(dev);
7415 
7416 	return (unsigned long)__bpf_skc_lookup(skb, tuple, len, caller_net,
7417 					       ifindex, IPPROTO_TCP, netns_id,
7418 					       flags, sdif);
7419 }
7420 
7421 static const struct bpf_func_proto bpf_tc_skc_lookup_tcp_proto = {
7422 	.func		= bpf_tc_skc_lookup_tcp,
7423 	.gpl_only	= false,
7424 	.pkt_access	= true,
7425 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
7426 	.arg1_type	= ARG_PTR_TO_CTX,
7427 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7428 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
7429 	.arg4_type	= ARG_ANYTHING,
7430 	.arg5_type	= ARG_ANYTHING,
7431 };
7432 
7433 BPF_CALL_5(bpf_tc_sk_lookup_tcp, struct sk_buff *, skb,
7434 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7435 {
7436 	struct net_device *dev = skb->dev;
7437 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7438 	struct net *caller_net = dev_net(dev);
7439 
7440 	return (unsigned long)__bpf_sk_lookup(skb, tuple, len, caller_net,
7441 					      ifindex, IPPROTO_TCP, netns_id,
7442 					      flags, sdif);
7443 }
7444 
7445 static const struct bpf_func_proto bpf_tc_sk_lookup_tcp_proto = {
7446 	.func		= bpf_tc_sk_lookup_tcp,
7447 	.gpl_only	= false,
7448 	.pkt_access	= true,
7449 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7450 	.arg1_type	= ARG_PTR_TO_CTX,
7451 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7452 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
7453 	.arg4_type	= ARG_ANYTHING,
7454 	.arg5_type	= ARG_ANYTHING,
7455 };
7456 
7457 BPF_CALL_5(bpf_tc_sk_lookup_udp, struct sk_buff *, skb,
7458 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7459 {
7460 	struct net_device *dev = skb->dev;
7461 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7462 	struct net *caller_net = dev_net(dev);
7463 
7464 	return (unsigned long)__bpf_sk_lookup(skb, tuple, len, caller_net,
7465 					      ifindex, IPPROTO_UDP, netns_id,
7466 					      flags, sdif);
7467 }
7468 
7469 static const struct bpf_func_proto bpf_tc_sk_lookup_udp_proto = {
7470 	.func		= bpf_tc_sk_lookup_udp,
7471 	.gpl_only	= false,
7472 	.pkt_access	= true,
7473 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7474 	.arg1_type	= ARG_PTR_TO_CTX,
7475 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7476 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
7477 	.arg4_type	= ARG_ANYTHING,
7478 	.arg5_type	= ARG_ANYTHING,
7479 };
7480 
7481 BPF_CALL_1(bpf_sk_release, struct sock *, sk)
7482 {
7483 	if (sk && sk_is_refcounted(sk))
7484 		sock_gen_put(sk);
7485 	return 0;
7486 }
7487 
7488 static const struct bpf_func_proto bpf_sk_release_proto = {
7489 	.func		= bpf_sk_release,
7490 	.gpl_only	= false,
7491 	.ret_type	= RET_INTEGER,
7492 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON | OBJ_RELEASE,
7493 };
7494 
7495 BPF_CALL_5(bpf_xdp_sk_lookup_udp, struct xdp_buff *, ctx,
7496 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
7497 {
7498 	struct net_device *dev = ctx->rxq->dev;
7499 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7500 	struct net *caller_net = dev_net(dev);
7501 
7502 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
7503 					      ifindex, IPPROTO_UDP, netns_id,
7504 					      flags, sdif);
7505 }
7506 
7507 static const struct bpf_func_proto bpf_xdp_sk_lookup_udp_proto = {
7508 	.func           = bpf_xdp_sk_lookup_udp,
7509 	.gpl_only       = false,
7510 	.pkt_access     = true,
7511 	.ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
7512 	.arg1_type      = ARG_PTR_TO_CTX,
7513 	.arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7514 	.arg3_type      = ARG_MEM_SIZE_OR_ZERO,
7515 	.arg4_type      = ARG_ANYTHING,
7516 	.arg5_type      = ARG_ANYTHING,
7517 };
7518 
7519 BPF_CALL_5(bpf_xdp_skc_lookup_tcp, struct xdp_buff *, ctx,
7520 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
7521 {
7522 	struct net_device *dev = ctx->rxq->dev;
7523 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7524 	struct net *caller_net = dev_net(dev);
7525 
7526 	return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, caller_net,
7527 					       ifindex, IPPROTO_TCP, netns_id,
7528 					       flags, sdif);
7529 }
7530 
7531 static const struct bpf_func_proto bpf_xdp_skc_lookup_tcp_proto = {
7532 	.func           = bpf_xdp_skc_lookup_tcp,
7533 	.gpl_only       = false,
7534 	.pkt_access     = true,
7535 	.ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
7536 	.arg1_type      = ARG_PTR_TO_CTX,
7537 	.arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7538 	.arg3_type      = ARG_MEM_SIZE_OR_ZERO,
7539 	.arg4_type      = ARG_ANYTHING,
7540 	.arg5_type      = ARG_ANYTHING,
7541 };
7542 
7543 BPF_CALL_5(bpf_xdp_sk_lookup_tcp, struct xdp_buff *, ctx,
7544 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
7545 {
7546 	struct net_device *dev = ctx->rxq->dev;
7547 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7548 	struct net *caller_net = dev_net(dev);
7549 
7550 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
7551 					      ifindex, IPPROTO_TCP, netns_id,
7552 					      flags, sdif);
7553 }
7554 
7555 static const struct bpf_func_proto bpf_xdp_sk_lookup_tcp_proto = {
7556 	.func           = bpf_xdp_sk_lookup_tcp,
7557 	.gpl_only       = false,
7558 	.pkt_access     = true,
7559 	.ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
7560 	.arg1_type      = ARG_PTR_TO_CTX,
7561 	.arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7562 	.arg3_type      = ARG_MEM_SIZE_OR_ZERO,
7563 	.arg4_type      = ARG_ANYTHING,
7564 	.arg5_type      = ARG_ANYTHING,
7565 };
7566 
7567 BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
7568 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7569 {
7570 	return (unsigned long)__bpf_skc_lookup(NULL, tuple, len,
7571 					       sock_net(ctx->sk), 0,
7572 					       IPPROTO_TCP, netns_id, flags,
7573 					       -1);
7574 }
7575 
7576 static const struct bpf_func_proto bpf_sock_addr_skc_lookup_tcp_proto = {
7577 	.func		= bpf_sock_addr_skc_lookup_tcp,
7578 	.gpl_only	= false,
7579 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
7580 	.arg1_type	= ARG_PTR_TO_CTX,
7581 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7582 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
7583 	.arg4_type	= ARG_ANYTHING,
7584 	.arg5_type	= ARG_ANYTHING,
7585 };
7586 
7587 BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
7588 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7589 {
7590 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
7591 					      sock_net(ctx->sk), 0, IPPROTO_TCP,
7592 					      netns_id, flags, -1);
7593 }
7594 
7595 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_tcp_proto = {
7596 	.func		= bpf_sock_addr_sk_lookup_tcp,
7597 	.gpl_only	= false,
7598 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7599 	.arg1_type	= ARG_PTR_TO_CTX,
7600 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7601 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
7602 	.arg4_type	= ARG_ANYTHING,
7603 	.arg5_type	= ARG_ANYTHING,
7604 };
7605 
7606 BPF_CALL_5(bpf_sock_addr_sk_lookup_udp, struct bpf_sock_addr_kern *, ctx,
7607 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7608 {
7609 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
7610 					      sock_net(ctx->sk), 0, IPPROTO_UDP,
7611 					      netns_id, flags, -1);
7612 }
7613 
7614 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_udp_proto = {
7615 	.func		= bpf_sock_addr_sk_lookup_udp,
7616 	.gpl_only	= false,
7617 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7618 	.arg1_type	= ARG_PTR_TO_CTX,
7619 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7620 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
7621 	.arg4_type	= ARG_ANYTHING,
7622 	.arg5_type	= ARG_ANYTHING,
7623 };
7624 
7625 bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
7626 				  struct bpf_insn_access_aux *info)
7627 {
7628 	if (off < 0 || off >= offsetofend(struct bpf_tcp_sock,
7629 					  icsk_retransmits))
7630 		return false;
7631 
7632 	if (off % size != 0)
7633 		return false;
7634 
7635 	switch (off) {
7636 	case bpf_ctx_range(struct bpf_tcp_sock, bytes_received):
7637 	case bpf_ctx_range(struct bpf_tcp_sock, bytes_acked):
7638 		return size == sizeof(__u64);
7639 	default:
7640 		return size == sizeof(__u32);
7641 	}
7642 }
7643 
7644 u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
7645 				    const struct bpf_insn *si,
7646 				    struct bpf_insn *insn_buf,
7647 				    struct bpf_prog *prog, u32 *target_size)
7648 {
7649 	struct bpf_insn *insn = insn_buf;
7650 
7651 #define BPF_TCP_SOCK_GET_COMMON(FIELD)					\
7652 	do {								\
7653 		BUILD_BUG_ON(sizeof_field(struct tcp_sock, FIELD) >	\
7654 			     sizeof_field(struct bpf_tcp_sock, FIELD));	\
7655 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_sock, FIELD),\
7656 				      si->dst_reg, si->src_reg,		\
7657 				      offsetof(struct tcp_sock, FIELD)); \
7658 	} while (0)
7659 
7660 #define BPF_INET_SOCK_GET_COMMON(FIELD)					\
7661 	do {								\
7662 		BUILD_BUG_ON(sizeof_field(struct inet_connection_sock,	\
7663 					  FIELD) >			\
7664 			     sizeof_field(struct bpf_tcp_sock, FIELD));	\
7665 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			\
7666 					struct inet_connection_sock,	\
7667 					FIELD),				\
7668 				      si->dst_reg, si->src_reg,		\
7669 				      offsetof(				\
7670 					struct inet_connection_sock,	\
7671 					FIELD));			\
7672 	} while (0)
7673 
7674 	BTF_TYPE_EMIT(struct bpf_tcp_sock);
7675 
7676 	switch (si->off) {
7677 	case offsetof(struct bpf_tcp_sock, rtt_min):
7678 		BUILD_BUG_ON(sizeof_field(struct tcp_sock, rtt_min) !=
7679 			     sizeof(struct minmax));
7680 		BUILD_BUG_ON(sizeof(struct minmax) <
7681 			     sizeof(struct minmax_sample));
7682 
7683 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7684 				      offsetof(struct tcp_sock, rtt_min) +
7685 				      offsetof(struct minmax_sample, v));
7686 		break;
7687 	case offsetof(struct bpf_tcp_sock, snd_cwnd):
7688 		BPF_TCP_SOCK_GET_COMMON(snd_cwnd);
7689 		break;
7690 	case offsetof(struct bpf_tcp_sock, srtt_us):
7691 		BPF_TCP_SOCK_GET_COMMON(srtt_us);
7692 		break;
7693 	case offsetof(struct bpf_tcp_sock, snd_ssthresh):
7694 		BPF_TCP_SOCK_GET_COMMON(snd_ssthresh);
7695 		break;
7696 	case offsetof(struct bpf_tcp_sock, rcv_nxt):
7697 		BPF_TCP_SOCK_GET_COMMON(rcv_nxt);
7698 		break;
7699 	case offsetof(struct bpf_tcp_sock, snd_nxt):
7700 		BPF_TCP_SOCK_GET_COMMON(snd_nxt);
7701 		break;
7702 	case offsetof(struct bpf_tcp_sock, snd_una):
7703 		BPF_TCP_SOCK_GET_COMMON(snd_una);
7704 		break;
7705 	case offsetof(struct bpf_tcp_sock, mss_cache):
7706 		BPF_TCP_SOCK_GET_COMMON(mss_cache);
7707 		break;
7708 	case offsetof(struct bpf_tcp_sock, ecn_flags):
7709 		BPF_TCP_SOCK_GET_COMMON(ecn_flags);
7710 		break;
7711 	case offsetof(struct bpf_tcp_sock, rate_delivered):
7712 		BPF_TCP_SOCK_GET_COMMON(rate_delivered);
7713 		break;
7714 	case offsetof(struct bpf_tcp_sock, rate_interval_us):
7715 		BPF_TCP_SOCK_GET_COMMON(rate_interval_us);
7716 		break;
7717 	case offsetof(struct bpf_tcp_sock, packets_out):
7718 		BPF_TCP_SOCK_GET_COMMON(packets_out);
7719 		break;
7720 	case offsetof(struct bpf_tcp_sock, retrans_out):
7721 		BPF_TCP_SOCK_GET_COMMON(retrans_out);
7722 		break;
7723 	case offsetof(struct bpf_tcp_sock, total_retrans):
7724 		BPF_TCP_SOCK_GET_COMMON(total_retrans);
7725 		break;
7726 	case offsetof(struct bpf_tcp_sock, segs_in):
7727 		BPF_TCP_SOCK_GET_COMMON(segs_in);
7728 		break;
7729 	case offsetof(struct bpf_tcp_sock, data_segs_in):
7730 		BPF_TCP_SOCK_GET_COMMON(data_segs_in);
7731 		break;
7732 	case offsetof(struct bpf_tcp_sock, segs_out):
7733 		BPF_TCP_SOCK_GET_COMMON(segs_out);
7734 		break;
7735 	case offsetof(struct bpf_tcp_sock, data_segs_out):
7736 		BPF_TCP_SOCK_GET_COMMON(data_segs_out);
7737 		break;
7738 	case offsetof(struct bpf_tcp_sock, lost_out):
7739 		BPF_TCP_SOCK_GET_COMMON(lost_out);
7740 		break;
7741 	case offsetof(struct bpf_tcp_sock, sacked_out):
7742 		BPF_TCP_SOCK_GET_COMMON(sacked_out);
7743 		break;
7744 	case offsetof(struct bpf_tcp_sock, bytes_received):
7745 		BPF_TCP_SOCK_GET_COMMON(bytes_received);
7746 		break;
7747 	case offsetof(struct bpf_tcp_sock, bytes_acked):
7748 		BPF_TCP_SOCK_GET_COMMON(bytes_acked);
7749 		break;
7750 	case offsetof(struct bpf_tcp_sock, dsack_dups):
7751 		BPF_TCP_SOCK_GET_COMMON(dsack_dups);
7752 		break;
7753 	case offsetof(struct bpf_tcp_sock, delivered):
7754 		BPF_TCP_SOCK_GET_COMMON(delivered);
7755 		break;
7756 	case offsetof(struct bpf_tcp_sock, delivered_ce):
7757 		BPF_TCP_SOCK_GET_COMMON(delivered_ce);
7758 		break;
7759 	case offsetof(struct bpf_tcp_sock, icsk_retransmits):
7760 		BPF_INET_SOCK_GET_COMMON(icsk_retransmits);
7761 		break;
7762 	}
7763 
7764 	return insn - insn_buf;
7765 }
7766 
7767 BPF_CALL_1(bpf_tcp_sock, struct sock *, sk)
7768 {
7769 	if (sk_fullsock(sk) && sk_is_tcp(sk))
7770 		return (unsigned long)sk;
7771 
7772 	return (unsigned long)NULL;
7773 }
7774 
7775 const struct bpf_func_proto bpf_tcp_sock_proto = {
7776 	.func		= bpf_tcp_sock,
7777 	.gpl_only	= false,
7778 	.ret_type	= RET_PTR_TO_TCP_SOCK_OR_NULL,
7779 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
7780 };
7781 
7782 BPF_CALL_1(bpf_get_listener_sock, struct sock *, sk)
7783 {
7784 	sk = sk_to_full_sk(sk);
7785 
7786 	if (sk && sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_RCU_FREE))
7787 		return (unsigned long)sk;
7788 
7789 	return (unsigned long)NULL;
7790 }
7791 
7792 static const struct bpf_func_proto bpf_get_listener_sock_proto = {
7793 	.func		= bpf_get_listener_sock,
7794 	.gpl_only	= false,
7795 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7796 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
7797 };
7798 
7799 BPF_CALL_1(bpf_skb_ecn_set_ce, struct sk_buff *, skb)
7800 {
7801 	unsigned int iphdr_len;
7802 
7803 	switch (skb_protocol(skb, true)) {
7804 	case cpu_to_be16(ETH_P_IP):
7805 		iphdr_len = sizeof(struct iphdr);
7806 		break;
7807 	case cpu_to_be16(ETH_P_IPV6):
7808 		iphdr_len = sizeof(struct ipv6hdr);
7809 		break;
7810 	default:
7811 		return 0;
7812 	}
7813 
7814 	if (skb_headlen(skb) < iphdr_len)
7815 		return 0;
7816 
7817 	if (skb_cloned(skb) && !skb_clone_writable(skb, iphdr_len))
7818 		return 0;
7819 
7820 	return INET_ECN_set_ce(skb);
7821 }
7822 
7823 bool bpf_xdp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
7824 				  struct bpf_insn_access_aux *info)
7825 {
7826 	if (off < 0 || off >= offsetofend(struct bpf_xdp_sock, queue_id))
7827 		return false;
7828 
7829 	if (off % size != 0)
7830 		return false;
7831 
7832 	switch (off) {
7833 	default:
7834 		return size == sizeof(__u32);
7835 	}
7836 }
7837 
7838 u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
7839 				    const struct bpf_insn *si,
7840 				    struct bpf_insn *insn_buf,
7841 				    struct bpf_prog *prog, u32 *target_size)
7842 {
7843 	struct bpf_insn *insn = insn_buf;
7844 
7845 #define BPF_XDP_SOCK_GET(FIELD)						\
7846 	do {								\
7847 		BUILD_BUG_ON(sizeof_field(struct xdp_sock, FIELD) >	\
7848 			     sizeof_field(struct bpf_xdp_sock, FIELD));	\
7849 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_sock, FIELD),\
7850 				      si->dst_reg, si->src_reg,		\
7851 				      offsetof(struct xdp_sock, FIELD)); \
7852 	} while (0)
7853 
7854 	BTF_TYPE_EMIT(struct bpf_xdp_sock);
7855 
7856 	switch (si->off) {
7857 	case offsetof(struct bpf_xdp_sock, queue_id):
7858 		BPF_XDP_SOCK_GET(queue_id);
7859 		break;
7860 	}
7861 
7862 	return insn - insn_buf;
7863 }
7864 
7865 static const struct bpf_func_proto bpf_skb_ecn_set_ce_proto = {
7866 	.func           = bpf_skb_ecn_set_ce,
7867 	.gpl_only       = false,
7868 	.ret_type       = RET_INTEGER,
7869 	.arg1_type      = ARG_PTR_TO_CTX,
7870 };
7871 
7872 BPF_CALL_5(bpf_tcp_check_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
7873 	   struct tcphdr *, th, u32, th_len)
7874 {
7875 #ifdef CONFIG_SYN_COOKIES
7876 	int ret;
7877 
7878 	if (unlikely(!sk || th_len < sizeof(*th)))
7879 		return -EINVAL;
7880 
7881 	/* sk_listener() allows TCP_NEW_SYN_RECV, which makes no sense here. */
7882 	if (sk->sk_state != TCP_LISTEN || sk->sk_protocol != IPPROTO_TCP)
7883 		return -EINVAL;
7884 
7885 	if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies))
7886 		return -EINVAL;
7887 
7888 	if (!th->ack || th->rst || th->syn)
7889 		return -ENOENT;
7890 
7891 	if (unlikely(iph_len < sizeof(struct iphdr)))
7892 		return -EINVAL;
7893 
7894 	if (tcp_synq_no_recent_overflow(sk))
7895 		return -ENOENT;
7896 
7897 	/* Both struct iphdr and struct ipv6hdr have the version field at the
7898 	 * same offset so we can cast to the shorter header (struct iphdr).
7899 	 */
7900 	switch (((struct iphdr *)iph)->version) {
7901 	case 4:
7902 		if (sk->sk_family == AF_INET6 && ipv6_only_sock(sk))
7903 			return -EINVAL;
7904 
7905 		ret = __cookie_v4_check((struct iphdr *)iph, th);
7906 		break;
7907 
7908 #if IS_ENABLED(CONFIG_IPV6)
7909 	case 6:
7910 		if (unlikely(iph_len < sizeof(struct ipv6hdr)))
7911 			return -EINVAL;
7912 
7913 		if (sk->sk_family != AF_INET6)
7914 			return -EINVAL;
7915 
7916 		ret = __cookie_v6_check((struct ipv6hdr *)iph, th);
7917 		break;
7918 #endif /* CONFIG_IPV6 */
7919 
7920 	default:
7921 		return -EPROTONOSUPPORT;
7922 	}
7923 
7924 	if (ret > 0)
7925 		return 0;
7926 
7927 	return -ENOENT;
7928 #else
7929 	return -ENOTSUPP;
7930 #endif
7931 }
7932 
7933 static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = {
7934 	.func		= bpf_tcp_check_syncookie,
7935 	.gpl_only	= true,
7936 	.pkt_access	= true,
7937 	.ret_type	= RET_INTEGER,
7938 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
7939 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7940 	.arg3_type	= ARG_MEM_SIZE,
7941 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7942 	.arg5_type	= ARG_MEM_SIZE,
7943 };
7944 
7945 BPF_CALL_5(bpf_tcp_gen_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
7946 	   struct tcphdr *, th, u32, th_len)
7947 {
7948 #ifdef CONFIG_SYN_COOKIES
7949 	u32 cookie;
7950 	u16 mss;
7951 
7952 	if (unlikely(!sk || th_len < sizeof(*th) || th_len != th->doff * 4))
7953 		return -EINVAL;
7954 
7955 	if (sk->sk_state != TCP_LISTEN || sk->sk_protocol != IPPROTO_TCP)
7956 		return -EINVAL;
7957 
7958 	if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies))
7959 		return -ENOENT;
7960 
7961 	if (!th->syn || th->ack || th->fin || th->rst)
7962 		return -EINVAL;
7963 
7964 	if (unlikely(iph_len < sizeof(struct iphdr)))
7965 		return -EINVAL;
7966 
7967 	/* Both struct iphdr and struct ipv6hdr have the version field at the
7968 	 * same offset so we can cast to the shorter header (struct iphdr).
7969 	 */
7970 	switch (((struct iphdr *)iph)->version) {
7971 	case 4:
7972 		if (sk->sk_family == AF_INET6 && ipv6_only_sock(sk))
7973 			return -EINVAL;
7974 
7975 		mss = tcp_v4_get_syncookie(sk, iph, th, &cookie);
7976 		break;
7977 
7978 #if IS_ENABLED(CONFIG_IPV6)
7979 	case 6:
7980 		if (unlikely(iph_len < sizeof(struct ipv6hdr)))
7981 			return -EINVAL;
7982 
7983 		if (sk->sk_family != AF_INET6)
7984 			return -EINVAL;
7985 
7986 		mss = tcp_v6_get_syncookie(sk, iph, th, &cookie);
7987 		break;
7988 #endif /* CONFIG_IPV6 */
7989 
7990 	default:
7991 		return -EPROTONOSUPPORT;
7992 	}
7993 	if (mss == 0)
7994 		return -ENOENT;
7995 
7996 	return cookie | ((u64)mss << 32);
7997 #else
7998 	return -EOPNOTSUPP;
7999 #endif /* CONFIG_SYN_COOKIES */
8000 }
8001 
8002 static const struct bpf_func_proto bpf_tcp_gen_syncookie_proto = {
8003 	.func		= bpf_tcp_gen_syncookie,
8004 	.gpl_only	= true, /* __cookie_v*_init_sequence() is GPL */
8005 	.pkt_access	= true,
8006 	.ret_type	= RET_INTEGER,
8007 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
8008 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
8009 	.arg3_type	= ARG_MEM_SIZE,
8010 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
8011 	.arg5_type	= ARG_MEM_SIZE,
8012 };
8013 
8014 BPF_CALL_3(bpf_sk_assign, struct sk_buff *, skb, struct sock *, sk, u64, flags)
8015 {
8016 	if (!sk || flags != 0)
8017 		return -EINVAL;
8018 	if (!skb_at_tc_ingress(skb))
8019 		return -EOPNOTSUPP;
8020 	if (unlikely(dev_net(skb->dev) != sock_net(sk)))
8021 		return -ENETUNREACH;
8022 	if (sk_unhashed(sk))
8023 		return -EOPNOTSUPP;
8024 	if (sk_is_refcounted(sk) &&
8025 	    unlikely(!refcount_inc_not_zero(&sk->sk_refcnt)))
8026 		return -ENOENT;
8027 
8028 	skb_orphan(skb);
8029 	skb->sk = sk;
8030 	skb->destructor = sock_pfree;
8031 
8032 	return 0;
8033 }
8034 
8035 static const struct bpf_func_proto bpf_sk_assign_proto = {
8036 	.func		= bpf_sk_assign,
8037 	.gpl_only	= false,
8038 	.ret_type	= RET_INTEGER,
8039 	.arg1_type      = ARG_PTR_TO_CTX,
8040 	.arg2_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
8041 	.arg3_type	= ARG_ANYTHING,
8042 };
8043 
8044 static const u8 *bpf_search_tcp_opt(const u8 *op, const u8 *opend,
8045 				    u8 search_kind, const u8 *magic,
8046 				    u8 magic_len, bool *eol)
8047 {
8048 	u8 kind, kind_len;
8049 
8050 	*eol = false;
8051 
8052 	while (op < opend) {
8053 		kind = op[0];
8054 
8055 		if (kind == TCPOPT_EOL) {
8056 			*eol = true;
8057 			return ERR_PTR(-ENOMSG);
8058 		} else if (kind == TCPOPT_NOP) {
8059 			op++;
8060 			continue;
8061 		}
8062 
8063 		if (opend - op < 2 || opend - op < op[1] || op[1] < 2)
8064 			/* Something is wrong in the received header.
8065 			 * Follow the TCP stack's tcp_parse_options()
8066 			 * and just bail here.
8067 			 */
8068 			return ERR_PTR(-EFAULT);
8069 
8070 		kind_len = op[1];
8071 		if (search_kind == kind) {
8072 			if (!magic_len)
8073 				return op;
8074 
8075 			if (magic_len > kind_len - 2)
8076 				return ERR_PTR(-ENOMSG);
8077 
8078 			if (!memcmp(&op[2], magic, magic_len))
8079 				return op;
8080 		}
8081 
8082 		op += kind_len;
8083 	}
8084 
8085 	return ERR_PTR(-ENOMSG);
8086 }
8087 
8088 int __bpf_sock_ops_load_hdr_opt(struct bpf_sock_ops_kern *bpf_sock,
8089 				void *search_res, u32 len, u64 flags)
8090 {
8091 	bool eol, load_syn = flags & BPF_LOAD_HDR_OPT_TCP_SYN;
8092 	const u8 *op, *opend, *magic, *search = search_res;
8093 	u8 search_kind, search_len, copy_len, magic_len;
8094 	int ret;
8095 
8096 	/* 2 byte is the minimal option len except TCPOPT_NOP and
8097 	 * TCPOPT_EOL which are useless for the bpf prog to learn
8098 	 * and this helper disallow loading them also.
8099 	 */
8100 	if (len < 2 || flags & ~BPF_LOAD_HDR_OPT_TCP_SYN)
8101 		return -EINVAL;
8102 
8103 	search_kind = search[0];
8104 	search_len = search[1];
8105 
8106 	if (search_len > len || search_kind == TCPOPT_NOP ||
8107 	    search_kind == TCPOPT_EOL)
8108 		return -EINVAL;
8109 
8110 	if (search_kind == TCPOPT_EXP || search_kind == 253) {
8111 		/* 16 or 32 bit magic.  +2 for kind and kind length */
8112 		if (search_len != 4 && search_len != 6)
8113 			return -EINVAL;
8114 		magic = &search[2];
8115 		magic_len = search_len - 2;
8116 	} else {
8117 		if (search_len)
8118 			return -EINVAL;
8119 		magic = NULL;
8120 		magic_len = 0;
8121 	}
8122 
8123 	if (load_syn) {
8124 		ret = bpf_sock_ops_get_syn(bpf_sock, TCP_BPF_SYN, &op);
8125 		if (ret < 0)
8126 			return ret;
8127 
8128 		opend = op + ret;
8129 		op += sizeof(struct tcphdr);
8130 	} else {
8131 		if (!bpf_sock->skb ||
8132 		    bpf_sock->op == BPF_SOCK_OPS_HDR_OPT_LEN_CB)
8133 			/* This bpf_sock->op cannot call this helper */
8134 			return -EPERM;
8135 
8136 		opend = bpf_sock->skb_data_end;
8137 		op = bpf_sock->skb->data + sizeof(struct tcphdr);
8138 	}
8139 
8140 	op = bpf_search_tcp_opt(op, opend, search_kind, magic, magic_len,
8141 				&eol);
8142 	if (IS_ERR(op))
8143 		return PTR_ERR(op);
8144 
8145 	copy_len = op[1];
8146 	ret = copy_len;
8147 	if (copy_len > len) {
8148 		ret = -ENOSPC;
8149 		copy_len = len;
8150 	}
8151 
8152 	memcpy(search_res, op, copy_len);
8153 	return ret;
8154 }
8155 
8156 BPF_CALL_4(bpf_sock_ops_load_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
8157 	   void *, search_res, u32, len, u64, flags)
8158 {
8159 	if (!is_locked_tcp_sock_ops(bpf_sock))
8160 		return -EOPNOTSUPP;
8161 
8162 	return __bpf_sock_ops_load_hdr_opt(bpf_sock, search_res, len, flags);
8163 }
8164 
8165 static const struct bpf_func_proto bpf_sock_ops_load_hdr_opt_proto = {
8166 	.func		= bpf_sock_ops_load_hdr_opt,
8167 	.gpl_only	= false,
8168 	.ret_type	= RET_INTEGER,
8169 	.arg1_type	= ARG_PTR_TO_CTX,
8170 	.arg2_type	= ARG_PTR_TO_MEM | MEM_WRITE,
8171 	.arg3_type	= ARG_MEM_SIZE,
8172 	.arg4_type	= ARG_ANYTHING,
8173 };
8174 
8175 int __bpf_sock_ops_store_hdr_opt(struct bpf_sock_ops_kern *bpf_sock,
8176 				 const void *from, u32 len, u64 flags)
8177 {
8178 	u8 new_kind, new_kind_len, magic_len = 0, *opend;
8179 	const u8 *op, *new_op, *magic = NULL;
8180 	struct sk_buff *skb;
8181 	bool eol;
8182 
8183 	if (len < 2 || flags)
8184 		return -EINVAL;
8185 
8186 	new_op = from;
8187 	new_kind = new_op[0];
8188 	new_kind_len = new_op[1];
8189 
8190 	if (new_kind_len > len || new_kind == TCPOPT_NOP ||
8191 	    new_kind == TCPOPT_EOL)
8192 		return -EINVAL;
8193 
8194 	if (new_kind_len > bpf_sock->remaining_opt_len)
8195 		return -ENOSPC;
8196 
8197 	/* 253 is another experimental kind */
8198 	if (new_kind == TCPOPT_EXP || new_kind == 253)  {
8199 		if (new_kind_len < 4)
8200 			return -EINVAL;
8201 		/* Match for the 2 byte magic also.
8202 		 * RFC 6994: the magic could be 2 or 4 bytes.
8203 		 * Hence, matching by 2 byte only is on the
8204 		 * conservative side but it is the right
8205 		 * thing to do for the 'search-for-duplication'
8206 		 * purpose.
8207 		 */
8208 		magic = &new_op[2];
8209 		magic_len = 2;
8210 	}
8211 
8212 	/* Check for duplication */
8213 	skb = bpf_sock->skb;
8214 	op = skb->data + sizeof(struct tcphdr);
8215 	opend = bpf_sock->skb_data_end;
8216 
8217 	op = bpf_search_tcp_opt(op, opend, new_kind, magic, magic_len,
8218 				&eol);
8219 	if (!IS_ERR(op))
8220 		return -EEXIST;
8221 
8222 	if (PTR_ERR(op) != -ENOMSG)
8223 		return PTR_ERR(op);
8224 
8225 	if (eol)
8226 		/* The option has been ended.  Treat it as no more
8227 		 * header option can be written.
8228 		 */
8229 		return -ENOSPC;
8230 
8231 	/* No duplication found.  Store the header option. */
8232 	memcpy(opend, from, new_kind_len);
8233 
8234 	bpf_sock->remaining_opt_len -= new_kind_len;
8235 	bpf_sock->skb_data_end += new_kind_len;
8236 
8237 	return 0;
8238 }
8239 
8240 BPF_CALL_4(bpf_sock_ops_store_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
8241 	   const void *, from, u32, len, u64, flags)
8242 {
8243 	if (bpf_sock->op != BPF_SOCK_OPS_WRITE_HDR_OPT_CB)
8244 		return -EPERM;
8245 
8246 	return __bpf_sock_ops_store_hdr_opt(bpf_sock, from, len, flags);
8247 }
8248 
8249 static const struct bpf_func_proto bpf_sock_ops_store_hdr_opt_proto = {
8250 	.func		= bpf_sock_ops_store_hdr_opt,
8251 	.gpl_only	= false,
8252 	.ret_type	= RET_INTEGER,
8253 	.arg1_type	= ARG_PTR_TO_CTX,
8254 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
8255 	.arg3_type	= ARG_MEM_SIZE,
8256 	.arg4_type	= ARG_ANYTHING,
8257 };
8258 
8259 BPF_CALL_3(bpf_sock_ops_reserve_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
8260 	   u32, len, u64, flags)
8261 {
8262 	if (bpf_sock->op != BPF_SOCK_OPS_HDR_OPT_LEN_CB)
8263 		return -EPERM;
8264 
8265 	if (flags || len < 2)
8266 		return -EINVAL;
8267 
8268 	if (len > bpf_sock->remaining_opt_len)
8269 		return -ENOSPC;
8270 
8271 	bpf_sock->remaining_opt_len -= len;
8272 
8273 	return 0;
8274 }
8275 
8276 static const struct bpf_func_proto bpf_sock_ops_reserve_hdr_opt_proto = {
8277 	.func		= bpf_sock_ops_reserve_hdr_opt,
8278 	.gpl_only	= false,
8279 	.ret_type	= RET_INTEGER,
8280 	.arg1_type	= ARG_PTR_TO_CTX,
8281 	.arg2_type	= ARG_ANYTHING,
8282 	.arg3_type	= ARG_ANYTHING,
8283 };
8284 
8285 BPF_CALL_3(bpf_skb_set_tstamp, struct sk_buff *, skb,
8286 	   u64, tstamp, u32, tstamp_type)
8287 {
8288 	/* skb_clear_delivery_time() is done for inet protocol */
8289 	if (skb->protocol != htons(ETH_P_IP) &&
8290 	    skb->protocol != htons(ETH_P_IPV6))
8291 		return -EOPNOTSUPP;
8292 
8293 	switch (tstamp_type) {
8294 	case BPF_SKB_CLOCK_REALTIME:
8295 		skb->tstamp = tstamp;
8296 		skb->tstamp_type = SKB_CLOCK_REALTIME;
8297 		break;
8298 	case BPF_SKB_CLOCK_MONOTONIC:
8299 		if (!tstamp)
8300 			return -EINVAL;
8301 		skb->tstamp = tstamp;
8302 		skb->tstamp_type = SKB_CLOCK_MONOTONIC;
8303 		break;
8304 	case BPF_SKB_CLOCK_TAI:
8305 		if (!tstamp)
8306 			return -EINVAL;
8307 		skb->tstamp = tstamp;
8308 		skb->tstamp_type = SKB_CLOCK_TAI;
8309 		break;
8310 	default:
8311 		return -EINVAL;
8312 	}
8313 
8314 	return 0;
8315 }
8316 
8317 static const struct bpf_func_proto bpf_skb_set_tstamp_proto = {
8318 	.func           = bpf_skb_set_tstamp,
8319 	.gpl_only       = false,
8320 	.ret_type       = RET_INTEGER,
8321 	.arg1_type      = ARG_PTR_TO_CTX,
8322 	.arg2_type      = ARG_ANYTHING,
8323 	.arg3_type      = ARG_ANYTHING,
8324 };
8325 
8326 #ifdef CONFIG_SYN_COOKIES
8327 BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv4, struct iphdr *, iph,
8328 	   struct tcphdr *, th, u32, th_len)
8329 {
8330 	u32 cookie;
8331 	u16 mss;
8332 
8333 	if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
8334 		return -EINVAL;
8335 
8336 	mss = tcp_parse_mss_option(th, 0) ?: TCP_MSS_DEFAULT;
8337 	cookie = __cookie_v4_init_sequence(iph, th, &mss);
8338 
8339 	return cookie | ((u64)mss << 32);
8340 }
8341 
8342 static const struct bpf_func_proto bpf_tcp_raw_gen_syncookie_ipv4_proto = {
8343 	.func		= bpf_tcp_raw_gen_syncookie_ipv4,
8344 	.gpl_only	= true, /* __cookie_v4_init_sequence() is GPL */
8345 	.pkt_access	= true,
8346 	.ret_type	= RET_INTEGER,
8347 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_RDONLY,
8348 	.arg1_size	= sizeof(struct iphdr),
8349 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
8350 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
8351 };
8352 
8353 BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv6, struct ipv6hdr *, iph,
8354 	   struct tcphdr *, th, u32, th_len)
8355 {
8356 #if IS_ENABLED(CONFIG_IPV6)
8357 	const u16 mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) -
8358 		sizeof(struct ipv6hdr);
8359 	u32 cookie;
8360 	u16 mss;
8361 
8362 	if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
8363 		return -EINVAL;
8364 
8365 	mss = tcp_parse_mss_option(th, 0) ?: mss_clamp;
8366 	cookie = __cookie_v6_init_sequence(iph, th, &mss);
8367 
8368 	return cookie | ((u64)mss << 32);
8369 #else
8370 	return -EPROTONOSUPPORT;
8371 #endif
8372 }
8373 
8374 static const struct bpf_func_proto bpf_tcp_raw_gen_syncookie_ipv6_proto = {
8375 	.func		= bpf_tcp_raw_gen_syncookie_ipv6,
8376 	.gpl_only	= true, /* __cookie_v6_init_sequence() is GPL */
8377 	.pkt_access	= true,
8378 	.ret_type	= RET_INTEGER,
8379 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_RDONLY,
8380 	.arg1_size	= sizeof(struct ipv6hdr),
8381 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
8382 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
8383 };
8384 
8385 BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv4, struct iphdr *, iph,
8386 	   struct tcphdr *, th)
8387 {
8388 	if (__cookie_v4_check(iph, th) > 0)
8389 		return 0;
8390 
8391 	return -EACCES;
8392 }
8393 
8394 static const struct bpf_func_proto bpf_tcp_raw_check_syncookie_ipv4_proto = {
8395 	.func		= bpf_tcp_raw_check_syncookie_ipv4,
8396 	.gpl_only	= true, /* __cookie_v4_check is GPL */
8397 	.pkt_access	= true,
8398 	.ret_type	= RET_INTEGER,
8399 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_RDONLY,
8400 	.arg1_size	= sizeof(struct iphdr),
8401 	.arg2_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_RDONLY,
8402 	.arg2_size	= sizeof(struct tcphdr),
8403 };
8404 
8405 BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv6, struct ipv6hdr *, iph,
8406 	   struct tcphdr *, th)
8407 {
8408 #if IS_ENABLED(CONFIG_IPV6)
8409 	if (__cookie_v6_check(iph, th) > 0)
8410 		return 0;
8411 
8412 	return -EACCES;
8413 #else
8414 	return -EPROTONOSUPPORT;
8415 #endif
8416 }
8417 
8418 static const struct bpf_func_proto bpf_tcp_raw_check_syncookie_ipv6_proto = {
8419 	.func		= bpf_tcp_raw_check_syncookie_ipv6,
8420 	.gpl_only	= true, /* __cookie_v6_check is GPL */
8421 	.pkt_access	= true,
8422 	.ret_type	= RET_INTEGER,
8423 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_RDONLY,
8424 	.arg1_size	= sizeof(struct ipv6hdr),
8425 	.arg2_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_RDONLY,
8426 	.arg2_size	= sizeof(struct tcphdr),
8427 };
8428 #endif /* CONFIG_SYN_COOKIES */
8429 
8430 #endif /* CONFIG_INET */
8431 
8432 bool bpf_helper_changes_pkt_data(enum bpf_func_id func_id)
8433 {
8434 	switch (func_id) {
8435 	case BPF_FUNC_clone_redirect:
8436 	case BPF_FUNC_l3_csum_replace:
8437 	case BPF_FUNC_l4_csum_replace:
8438 	case BPF_FUNC_lwt_push_encap:
8439 	case BPF_FUNC_lwt_seg6_action:
8440 	case BPF_FUNC_lwt_seg6_adjust_srh:
8441 	case BPF_FUNC_lwt_seg6_store_bytes:
8442 	case BPF_FUNC_msg_pop_data:
8443 	case BPF_FUNC_msg_pull_data:
8444 	case BPF_FUNC_msg_push_data:
8445 	case BPF_FUNC_skb_adjust_room:
8446 	case BPF_FUNC_skb_change_head:
8447 	case BPF_FUNC_skb_change_proto:
8448 	case BPF_FUNC_skb_change_tail:
8449 	case BPF_FUNC_skb_pull_data:
8450 	case BPF_FUNC_skb_store_bytes:
8451 	case BPF_FUNC_skb_vlan_pop:
8452 	case BPF_FUNC_skb_vlan_push:
8453 	case BPF_FUNC_store_hdr_opt:
8454 	case BPF_FUNC_xdp_adjust_head:
8455 	case BPF_FUNC_xdp_adjust_meta:
8456 	case BPF_FUNC_xdp_adjust_tail:
8457 	/* tail-called program could call any of the above */
8458 	case BPF_FUNC_tail_call:
8459 		return true;
8460 	default:
8461 		return false;
8462 	}
8463 }
8464 
8465 const struct bpf_func_proto bpf_event_output_data_proto __weak;
8466 const struct bpf_func_proto bpf_sk_storage_get_cg_sock_proto __weak;
8467 
8468 static const struct bpf_func_proto *
8469 sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8470 {
8471 	const struct bpf_func_proto *func_proto;
8472 
8473 	func_proto = cgroup_common_func_proto(func_id, prog);
8474 	if (func_proto)
8475 		return func_proto;
8476 
8477 	switch (func_id) {
8478 	case BPF_FUNC_get_socket_cookie:
8479 		return &bpf_get_socket_cookie_sock_proto;
8480 	case BPF_FUNC_get_netns_cookie:
8481 		return &bpf_get_netns_cookie_sock_proto;
8482 	case BPF_FUNC_perf_event_output:
8483 		return &bpf_event_output_data_proto;
8484 	case BPF_FUNC_sk_storage_get:
8485 		return &bpf_sk_storage_get_cg_sock_proto;
8486 	case BPF_FUNC_ktime_get_coarse_ns:
8487 		return &bpf_ktime_get_coarse_ns_proto;
8488 	case BPF_FUNC_setsockopt:
8489 		switch (prog->expected_attach_type) {
8490 		case BPF_CGROUP_INET_SOCK_CREATE:
8491 			return &bpf_sock_create_setsockopt_proto;
8492 		default:
8493 			return NULL;
8494 		}
8495 	case BPF_FUNC_getsockopt:
8496 		switch (prog->expected_attach_type) {
8497 		case BPF_CGROUP_INET_SOCK_CREATE:
8498 			return &bpf_sock_create_getsockopt_proto;
8499 		default:
8500 			return NULL;
8501 		}
8502 	default:
8503 		return bpf_base_func_proto(func_id, prog);
8504 	}
8505 }
8506 
8507 static const struct bpf_func_proto *
8508 sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8509 {
8510 	const struct bpf_func_proto *func_proto;
8511 
8512 	func_proto = cgroup_common_func_proto(func_id, prog);
8513 	if (func_proto)
8514 		return func_proto;
8515 
8516 	switch (func_id) {
8517 	case BPF_FUNC_bind:
8518 		switch (prog->expected_attach_type) {
8519 		case BPF_CGROUP_INET4_CONNECT:
8520 		case BPF_CGROUP_INET6_CONNECT:
8521 			return &bpf_bind_proto;
8522 		default:
8523 			return NULL;
8524 		}
8525 	case BPF_FUNC_get_socket_cookie:
8526 		return &bpf_get_socket_cookie_sock_addr_proto;
8527 	case BPF_FUNC_get_netns_cookie:
8528 		return &bpf_get_netns_cookie_sock_addr_proto;
8529 	case BPF_FUNC_perf_event_output:
8530 		return &bpf_event_output_data_proto;
8531 #ifdef CONFIG_INET
8532 	case BPF_FUNC_sk_lookup_tcp:
8533 		return &bpf_sock_addr_sk_lookup_tcp_proto;
8534 	case BPF_FUNC_sk_lookup_udp:
8535 		return &bpf_sock_addr_sk_lookup_udp_proto;
8536 	case BPF_FUNC_sk_release:
8537 		return &bpf_sk_release_proto;
8538 	case BPF_FUNC_skc_lookup_tcp:
8539 		return &bpf_sock_addr_skc_lookup_tcp_proto;
8540 #endif /* CONFIG_INET */
8541 	case BPF_FUNC_sk_storage_get:
8542 		return &bpf_sk_storage_get_proto;
8543 	case BPF_FUNC_sk_storage_delete:
8544 		return &bpf_sk_storage_delete_proto;
8545 	case BPF_FUNC_setsockopt:
8546 		switch (prog->expected_attach_type) {
8547 		case BPF_CGROUP_INET4_BIND:
8548 		case BPF_CGROUP_INET6_BIND:
8549 		case BPF_CGROUP_INET4_CONNECT:
8550 		case BPF_CGROUP_INET6_CONNECT:
8551 		case BPF_CGROUP_UNIX_CONNECT:
8552 		case BPF_CGROUP_UDP4_RECVMSG:
8553 		case BPF_CGROUP_UDP6_RECVMSG:
8554 		case BPF_CGROUP_UNIX_RECVMSG:
8555 		case BPF_CGROUP_UDP4_SENDMSG:
8556 		case BPF_CGROUP_UDP6_SENDMSG:
8557 		case BPF_CGROUP_UNIX_SENDMSG:
8558 		case BPF_CGROUP_INET4_GETPEERNAME:
8559 		case BPF_CGROUP_INET6_GETPEERNAME:
8560 		case BPF_CGROUP_INET4_GETSOCKNAME:
8561 		case BPF_CGROUP_INET6_GETSOCKNAME:
8562 			return &bpf_sock_addr_setsockopt_proto;
8563 		default:
8564 			return NULL;
8565 		}
8566 	case BPF_FUNC_getsockopt:
8567 		switch (prog->expected_attach_type) {
8568 		case BPF_CGROUP_INET4_BIND:
8569 		case BPF_CGROUP_INET6_BIND:
8570 		case BPF_CGROUP_INET4_CONNECT:
8571 		case BPF_CGROUP_INET6_CONNECT:
8572 		case BPF_CGROUP_UNIX_CONNECT:
8573 		case BPF_CGROUP_UDP4_RECVMSG:
8574 		case BPF_CGROUP_UDP6_RECVMSG:
8575 		case BPF_CGROUP_UNIX_RECVMSG:
8576 		case BPF_CGROUP_UDP4_SENDMSG:
8577 		case BPF_CGROUP_UDP6_SENDMSG:
8578 		case BPF_CGROUP_UNIX_SENDMSG:
8579 		case BPF_CGROUP_INET4_GETPEERNAME:
8580 		case BPF_CGROUP_INET6_GETPEERNAME:
8581 		case BPF_CGROUP_INET4_GETSOCKNAME:
8582 		case BPF_CGROUP_INET6_GETSOCKNAME:
8583 			return &bpf_sock_addr_getsockopt_proto;
8584 		default:
8585 			return NULL;
8586 		}
8587 	default:
8588 		return bpf_sk_base_func_proto(func_id, prog);
8589 	}
8590 }
8591 
8592 static const struct bpf_func_proto *
8593 sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8594 {
8595 	switch (func_id) {
8596 	case BPF_FUNC_skb_load_bytes:
8597 		return &bpf_skb_load_bytes_proto;
8598 	case BPF_FUNC_skb_load_bytes_relative:
8599 		return &bpf_skb_load_bytes_relative_proto;
8600 	case BPF_FUNC_get_socket_cookie:
8601 		return &bpf_get_socket_cookie_proto;
8602 	case BPF_FUNC_get_netns_cookie:
8603 		return &bpf_get_netns_cookie_proto;
8604 	case BPF_FUNC_get_socket_uid:
8605 		return &bpf_get_socket_uid_proto;
8606 	case BPF_FUNC_perf_event_output:
8607 		return &bpf_skb_event_output_proto;
8608 	default:
8609 		return bpf_sk_base_func_proto(func_id, prog);
8610 	}
8611 }
8612 
8613 const struct bpf_func_proto bpf_sk_storage_get_proto __weak;
8614 const struct bpf_func_proto bpf_sk_storage_delete_proto __weak;
8615 
8616 static const struct bpf_func_proto *
8617 cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8618 {
8619 	const struct bpf_func_proto *func_proto;
8620 
8621 	func_proto = cgroup_common_func_proto(func_id, prog);
8622 	if (func_proto)
8623 		return func_proto;
8624 
8625 	switch (func_id) {
8626 	case BPF_FUNC_sk_fullsock:
8627 		return &bpf_sk_fullsock_proto;
8628 	case BPF_FUNC_sk_storage_get:
8629 		return &bpf_sk_storage_get_proto;
8630 	case BPF_FUNC_sk_storage_delete:
8631 		return &bpf_sk_storage_delete_proto;
8632 	case BPF_FUNC_perf_event_output:
8633 		return &bpf_skb_event_output_proto;
8634 #ifdef CONFIG_SOCK_CGROUP_DATA
8635 	case BPF_FUNC_skb_cgroup_id:
8636 		return &bpf_skb_cgroup_id_proto;
8637 	case BPF_FUNC_skb_ancestor_cgroup_id:
8638 		return &bpf_skb_ancestor_cgroup_id_proto;
8639 	case BPF_FUNC_sk_cgroup_id:
8640 		return &bpf_sk_cgroup_id_proto;
8641 	case BPF_FUNC_sk_ancestor_cgroup_id:
8642 		return &bpf_sk_ancestor_cgroup_id_proto;
8643 #endif
8644 #ifdef CONFIG_INET
8645 	case BPF_FUNC_sk_lookup_tcp:
8646 		return &bpf_sk_lookup_tcp_proto;
8647 	case BPF_FUNC_sk_lookup_udp:
8648 		return &bpf_sk_lookup_udp_proto;
8649 	case BPF_FUNC_sk_release:
8650 		return &bpf_sk_release_proto;
8651 	case BPF_FUNC_skc_lookup_tcp:
8652 		return &bpf_skc_lookup_tcp_proto;
8653 	case BPF_FUNC_tcp_sock:
8654 		return &bpf_tcp_sock_proto;
8655 	case BPF_FUNC_get_listener_sock:
8656 		return &bpf_get_listener_sock_proto;
8657 	case BPF_FUNC_skb_ecn_set_ce:
8658 		return &bpf_skb_ecn_set_ce_proto;
8659 #endif
8660 	default:
8661 		return sk_filter_func_proto(func_id, prog);
8662 	}
8663 }
8664 
8665 static const struct bpf_func_proto *
8666 tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8667 {
8668 	switch (func_id) {
8669 	case BPF_FUNC_skb_store_bytes:
8670 		return &bpf_skb_store_bytes_proto;
8671 	case BPF_FUNC_skb_load_bytes:
8672 		return &bpf_skb_load_bytes_proto;
8673 	case BPF_FUNC_skb_load_bytes_relative:
8674 		return &bpf_skb_load_bytes_relative_proto;
8675 	case BPF_FUNC_skb_pull_data:
8676 		return &bpf_skb_pull_data_proto;
8677 	case BPF_FUNC_csum_diff:
8678 		return &bpf_csum_diff_proto;
8679 	case BPF_FUNC_csum_update:
8680 		return &bpf_csum_update_proto;
8681 	case BPF_FUNC_csum_level:
8682 		return &bpf_csum_level_proto;
8683 	case BPF_FUNC_l3_csum_replace:
8684 		return &bpf_l3_csum_replace_proto;
8685 	case BPF_FUNC_l4_csum_replace:
8686 		return &bpf_l4_csum_replace_proto;
8687 	case BPF_FUNC_clone_redirect:
8688 		return &bpf_clone_redirect_proto;
8689 	case BPF_FUNC_get_cgroup_classid:
8690 		return &bpf_get_cgroup_classid_proto;
8691 	case BPF_FUNC_skb_vlan_push:
8692 		return &bpf_skb_vlan_push_proto;
8693 	case BPF_FUNC_skb_vlan_pop:
8694 		return &bpf_skb_vlan_pop_proto;
8695 	case BPF_FUNC_skb_change_proto:
8696 		return &bpf_skb_change_proto_proto;
8697 	case BPF_FUNC_skb_change_type:
8698 		return &bpf_skb_change_type_proto;
8699 	case BPF_FUNC_skb_adjust_room:
8700 		return &bpf_skb_adjust_room_proto;
8701 	case BPF_FUNC_skb_change_tail:
8702 		return &bpf_skb_change_tail_proto;
8703 	case BPF_FUNC_skb_change_head:
8704 		return &bpf_skb_change_head_proto;
8705 	case BPF_FUNC_skb_get_tunnel_key:
8706 		return &bpf_skb_get_tunnel_key_proto;
8707 	case BPF_FUNC_skb_set_tunnel_key:
8708 		return bpf_get_skb_set_tunnel_proto(func_id);
8709 	case BPF_FUNC_skb_get_tunnel_opt:
8710 		return &bpf_skb_get_tunnel_opt_proto;
8711 	case BPF_FUNC_skb_set_tunnel_opt:
8712 		return bpf_get_skb_set_tunnel_proto(func_id);
8713 	case BPF_FUNC_redirect:
8714 		return &bpf_redirect_proto;
8715 	case BPF_FUNC_redirect_neigh:
8716 		return &bpf_redirect_neigh_proto;
8717 	case BPF_FUNC_redirect_peer:
8718 		return &bpf_redirect_peer_proto;
8719 	case BPF_FUNC_get_route_realm:
8720 		return &bpf_get_route_realm_proto;
8721 	case BPF_FUNC_get_hash_recalc:
8722 		return &bpf_get_hash_recalc_proto;
8723 	case BPF_FUNC_set_hash_invalid:
8724 		return &bpf_set_hash_invalid_proto;
8725 	case BPF_FUNC_set_hash:
8726 		return &bpf_set_hash_proto;
8727 	case BPF_FUNC_perf_event_output:
8728 		return &bpf_skb_event_output_proto;
8729 	case BPF_FUNC_get_smp_processor_id:
8730 		return &bpf_get_smp_processor_id_proto;
8731 	case BPF_FUNC_skb_under_cgroup:
8732 		return &bpf_skb_under_cgroup_proto;
8733 	case BPF_FUNC_get_socket_cookie:
8734 		return &bpf_get_socket_cookie_proto;
8735 	case BPF_FUNC_get_netns_cookie:
8736 		return &bpf_get_netns_cookie_proto;
8737 	case BPF_FUNC_get_socket_uid:
8738 		return &bpf_get_socket_uid_proto;
8739 	case BPF_FUNC_fib_lookup:
8740 		return &bpf_skb_fib_lookup_proto;
8741 	case BPF_FUNC_check_mtu:
8742 		return &bpf_skb_check_mtu_proto;
8743 	case BPF_FUNC_sk_fullsock:
8744 		return &bpf_sk_fullsock_proto;
8745 	case BPF_FUNC_sk_storage_get:
8746 		return &bpf_sk_storage_get_proto;
8747 	case BPF_FUNC_sk_storage_delete:
8748 		return &bpf_sk_storage_delete_proto;
8749 #ifdef CONFIG_XFRM
8750 	case BPF_FUNC_skb_get_xfrm_state:
8751 		return &bpf_skb_get_xfrm_state_proto;
8752 #endif
8753 #ifdef CONFIG_CGROUP_NET_CLASSID
8754 	case BPF_FUNC_skb_cgroup_classid:
8755 		return &bpf_skb_cgroup_classid_proto;
8756 #endif
8757 #ifdef CONFIG_SOCK_CGROUP_DATA
8758 	case BPF_FUNC_skb_cgroup_id:
8759 		return &bpf_skb_cgroup_id_proto;
8760 	case BPF_FUNC_skb_ancestor_cgroup_id:
8761 		return &bpf_skb_ancestor_cgroup_id_proto;
8762 #endif
8763 #ifdef CONFIG_INET
8764 	case BPF_FUNC_sk_lookup_tcp:
8765 		return &bpf_tc_sk_lookup_tcp_proto;
8766 	case BPF_FUNC_sk_lookup_udp:
8767 		return &bpf_tc_sk_lookup_udp_proto;
8768 	case BPF_FUNC_sk_release:
8769 		return &bpf_sk_release_proto;
8770 	case BPF_FUNC_tcp_sock:
8771 		return &bpf_tcp_sock_proto;
8772 	case BPF_FUNC_get_listener_sock:
8773 		return &bpf_get_listener_sock_proto;
8774 	case BPF_FUNC_skc_lookup_tcp:
8775 		return &bpf_tc_skc_lookup_tcp_proto;
8776 	case BPF_FUNC_tcp_check_syncookie:
8777 		return &bpf_tcp_check_syncookie_proto;
8778 	case BPF_FUNC_skb_ecn_set_ce:
8779 		return &bpf_skb_ecn_set_ce_proto;
8780 	case BPF_FUNC_tcp_gen_syncookie:
8781 		return &bpf_tcp_gen_syncookie_proto;
8782 	case BPF_FUNC_sk_assign:
8783 		return &bpf_sk_assign_proto;
8784 	case BPF_FUNC_skb_set_tstamp:
8785 		return &bpf_skb_set_tstamp_proto;
8786 #ifdef CONFIG_SYN_COOKIES
8787 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv4:
8788 		return &bpf_tcp_raw_gen_syncookie_ipv4_proto;
8789 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv6:
8790 		return &bpf_tcp_raw_gen_syncookie_ipv6_proto;
8791 	case BPF_FUNC_tcp_raw_check_syncookie_ipv4:
8792 		return &bpf_tcp_raw_check_syncookie_ipv4_proto;
8793 	case BPF_FUNC_tcp_raw_check_syncookie_ipv6:
8794 		return &bpf_tcp_raw_check_syncookie_ipv6_proto;
8795 #endif
8796 #endif
8797 	default:
8798 		return bpf_sk_base_func_proto(func_id, prog);
8799 	}
8800 }
8801 
8802 static const struct bpf_func_proto *
8803 xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8804 {
8805 	switch (func_id) {
8806 	case BPF_FUNC_perf_event_output:
8807 		return &bpf_xdp_event_output_proto;
8808 	case BPF_FUNC_get_smp_processor_id:
8809 		return &bpf_get_smp_processor_id_proto;
8810 	case BPF_FUNC_csum_diff:
8811 		return &bpf_csum_diff_proto;
8812 	case BPF_FUNC_xdp_adjust_head:
8813 		return &bpf_xdp_adjust_head_proto;
8814 	case BPF_FUNC_xdp_adjust_meta:
8815 		return &bpf_xdp_adjust_meta_proto;
8816 	case BPF_FUNC_redirect:
8817 		return &bpf_xdp_redirect_proto;
8818 	case BPF_FUNC_redirect_map:
8819 		return &bpf_xdp_redirect_map_proto;
8820 	case BPF_FUNC_xdp_adjust_tail:
8821 		return &bpf_xdp_adjust_tail_proto;
8822 	case BPF_FUNC_xdp_get_buff_len:
8823 		return &bpf_xdp_get_buff_len_proto;
8824 	case BPF_FUNC_xdp_load_bytes:
8825 		return &bpf_xdp_load_bytes_proto;
8826 	case BPF_FUNC_xdp_store_bytes:
8827 		return &bpf_xdp_store_bytes_proto;
8828 	case BPF_FUNC_fib_lookup:
8829 		return &bpf_xdp_fib_lookup_proto;
8830 	case BPF_FUNC_check_mtu:
8831 		return &bpf_xdp_check_mtu_proto;
8832 #ifdef CONFIG_INET
8833 	case BPF_FUNC_sk_lookup_udp:
8834 		return &bpf_xdp_sk_lookup_udp_proto;
8835 	case BPF_FUNC_sk_lookup_tcp:
8836 		return &bpf_xdp_sk_lookup_tcp_proto;
8837 	case BPF_FUNC_sk_release:
8838 		return &bpf_sk_release_proto;
8839 	case BPF_FUNC_skc_lookup_tcp:
8840 		return &bpf_xdp_skc_lookup_tcp_proto;
8841 	case BPF_FUNC_tcp_check_syncookie:
8842 		return &bpf_tcp_check_syncookie_proto;
8843 	case BPF_FUNC_tcp_gen_syncookie:
8844 		return &bpf_tcp_gen_syncookie_proto;
8845 #ifdef CONFIG_SYN_COOKIES
8846 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv4:
8847 		return &bpf_tcp_raw_gen_syncookie_ipv4_proto;
8848 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv6:
8849 		return &bpf_tcp_raw_gen_syncookie_ipv6_proto;
8850 	case BPF_FUNC_tcp_raw_check_syncookie_ipv4:
8851 		return &bpf_tcp_raw_check_syncookie_ipv4_proto;
8852 	case BPF_FUNC_tcp_raw_check_syncookie_ipv6:
8853 		return &bpf_tcp_raw_check_syncookie_ipv6_proto;
8854 #endif
8855 #endif
8856 	default:
8857 		return bpf_sk_base_func_proto(func_id, prog);
8858 	}
8859 
8860 #if IS_MODULE(CONFIG_NF_CONNTRACK) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)
8861 	/* The nf_conn___init type is used in the NF_CONNTRACK kfuncs. The
8862 	 * kfuncs are defined in two different modules, and we want to be able
8863 	 * to use them interchangeably with the same BTF type ID. Because modules
8864 	 * can't de-duplicate BTF IDs between each other, we need the type to be
8865 	 * referenced in the vmlinux BTF or the verifier will get confused about
8866 	 * the different types. So we add this dummy type reference which will
8867 	 * be included in vmlinux BTF, allowing both modules to refer to the
8868 	 * same type ID.
8869 	 */
8870 	BTF_TYPE_EMIT(struct nf_conn___init);
8871 #endif
8872 }
8873 
8874 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
8875 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
8876 
8877 static const struct bpf_func_proto *
8878 sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8879 {
8880 	const struct bpf_func_proto *func_proto;
8881 
8882 	func_proto = cgroup_common_func_proto(func_id, prog);
8883 	if (func_proto)
8884 		return func_proto;
8885 
8886 	switch (func_id) {
8887 	case BPF_FUNC_setsockopt:
8888 		return &bpf_sock_ops_setsockopt_proto;
8889 	case BPF_FUNC_getsockopt:
8890 		return &bpf_sock_ops_getsockopt_proto;
8891 	case BPF_FUNC_sock_ops_cb_flags_set:
8892 		return &bpf_sock_ops_cb_flags_set_proto;
8893 	case BPF_FUNC_sock_map_update:
8894 		return &bpf_sock_map_update_proto;
8895 	case BPF_FUNC_sock_hash_update:
8896 		return &bpf_sock_hash_update_proto;
8897 	case BPF_FUNC_get_socket_cookie:
8898 		return &bpf_get_socket_cookie_sock_ops_proto;
8899 	case BPF_FUNC_perf_event_output:
8900 		return &bpf_event_output_data_proto;
8901 	case BPF_FUNC_sk_storage_get:
8902 		return &bpf_sk_storage_get_proto;
8903 	case BPF_FUNC_sk_storage_delete:
8904 		return &bpf_sk_storage_delete_proto;
8905 	case BPF_FUNC_get_netns_cookie:
8906 		return &bpf_get_netns_cookie_sock_ops_proto;
8907 #ifdef CONFIG_INET
8908 	case BPF_FUNC_load_hdr_opt:
8909 		return &bpf_sock_ops_load_hdr_opt_proto;
8910 	case BPF_FUNC_store_hdr_opt:
8911 		return &bpf_sock_ops_store_hdr_opt_proto;
8912 	case BPF_FUNC_reserve_hdr_opt:
8913 		return &bpf_sock_ops_reserve_hdr_opt_proto;
8914 	case BPF_FUNC_tcp_sock:
8915 		return &bpf_tcp_sock_proto;
8916 #endif /* CONFIG_INET */
8917 	default:
8918 		return bpf_sk_base_func_proto(func_id, prog);
8919 	}
8920 }
8921 
8922 const struct bpf_func_proto bpf_msg_redirect_map_proto __weak;
8923 const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak;
8924 
8925 static const struct bpf_func_proto *
8926 sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8927 {
8928 	switch (func_id) {
8929 	case BPF_FUNC_msg_redirect_map:
8930 		return &bpf_msg_redirect_map_proto;
8931 	case BPF_FUNC_msg_redirect_hash:
8932 		return &bpf_msg_redirect_hash_proto;
8933 	case BPF_FUNC_msg_apply_bytes:
8934 		return &bpf_msg_apply_bytes_proto;
8935 	case BPF_FUNC_msg_cork_bytes:
8936 		return &bpf_msg_cork_bytes_proto;
8937 	case BPF_FUNC_msg_pull_data:
8938 		return &bpf_msg_pull_data_proto;
8939 	case BPF_FUNC_msg_push_data:
8940 		return &bpf_msg_push_data_proto;
8941 	case BPF_FUNC_msg_pop_data:
8942 		return &bpf_msg_pop_data_proto;
8943 	case BPF_FUNC_perf_event_output:
8944 		return &bpf_event_output_data_proto;
8945 	case BPF_FUNC_sk_storage_get:
8946 		return &bpf_sk_storage_get_proto;
8947 	case BPF_FUNC_sk_storage_delete:
8948 		return &bpf_sk_storage_delete_proto;
8949 	case BPF_FUNC_get_netns_cookie:
8950 		return &bpf_get_netns_cookie_sk_msg_proto;
8951 	default:
8952 		return bpf_sk_base_func_proto(func_id, prog);
8953 	}
8954 }
8955 
8956 const struct bpf_func_proto bpf_sk_redirect_map_proto __weak;
8957 const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak;
8958 
8959 static const struct bpf_func_proto *
8960 sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8961 {
8962 	switch (func_id) {
8963 	case BPF_FUNC_skb_store_bytes:
8964 		return &bpf_skb_store_bytes_proto;
8965 	case BPF_FUNC_skb_load_bytes:
8966 		return &bpf_skb_load_bytes_proto;
8967 	case BPF_FUNC_skb_pull_data:
8968 		return &sk_skb_pull_data_proto;
8969 	case BPF_FUNC_skb_change_tail:
8970 		return &sk_skb_change_tail_proto;
8971 	case BPF_FUNC_skb_change_head:
8972 		return &sk_skb_change_head_proto;
8973 	case BPF_FUNC_skb_adjust_room:
8974 		return &sk_skb_adjust_room_proto;
8975 	case BPF_FUNC_get_socket_cookie:
8976 		return &bpf_get_socket_cookie_proto;
8977 	case BPF_FUNC_get_socket_uid:
8978 		return &bpf_get_socket_uid_proto;
8979 	case BPF_FUNC_sk_redirect_map:
8980 		return &bpf_sk_redirect_map_proto;
8981 	case BPF_FUNC_sk_redirect_hash:
8982 		return &bpf_sk_redirect_hash_proto;
8983 	case BPF_FUNC_perf_event_output:
8984 		return &bpf_skb_event_output_proto;
8985 #ifdef CONFIG_INET
8986 	case BPF_FUNC_sk_lookup_tcp:
8987 		return &bpf_sk_lookup_tcp_proto;
8988 	case BPF_FUNC_sk_lookup_udp:
8989 		return &bpf_sk_lookup_udp_proto;
8990 	case BPF_FUNC_sk_release:
8991 		return &bpf_sk_release_proto;
8992 	case BPF_FUNC_skc_lookup_tcp:
8993 		return &bpf_skc_lookup_tcp_proto;
8994 #endif
8995 	default:
8996 		return bpf_sk_base_func_proto(func_id, prog);
8997 	}
8998 }
8999 
9000 static const struct bpf_func_proto *
9001 flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
9002 {
9003 	switch (func_id) {
9004 	case BPF_FUNC_skb_load_bytes:
9005 		return &bpf_flow_dissector_load_bytes_proto;
9006 	default:
9007 		return bpf_sk_base_func_proto(func_id, prog);
9008 	}
9009 }
9010 
9011 static const struct bpf_func_proto *
9012 lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
9013 {
9014 	switch (func_id) {
9015 	case BPF_FUNC_skb_load_bytes:
9016 		return &bpf_skb_load_bytes_proto;
9017 	case BPF_FUNC_skb_pull_data:
9018 		return &bpf_skb_pull_data_proto;
9019 	case BPF_FUNC_csum_diff:
9020 		return &bpf_csum_diff_proto;
9021 	case BPF_FUNC_get_cgroup_classid:
9022 		return &bpf_get_cgroup_classid_proto;
9023 	case BPF_FUNC_get_route_realm:
9024 		return &bpf_get_route_realm_proto;
9025 	case BPF_FUNC_get_hash_recalc:
9026 		return &bpf_get_hash_recalc_proto;
9027 	case BPF_FUNC_perf_event_output:
9028 		return &bpf_skb_event_output_proto;
9029 	case BPF_FUNC_get_smp_processor_id:
9030 		return &bpf_get_smp_processor_id_proto;
9031 	case BPF_FUNC_skb_under_cgroup:
9032 		return &bpf_skb_under_cgroup_proto;
9033 	default:
9034 		return bpf_sk_base_func_proto(func_id, prog);
9035 	}
9036 }
9037 
9038 static const struct bpf_func_proto *
9039 lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
9040 {
9041 	switch (func_id) {
9042 	case BPF_FUNC_lwt_push_encap:
9043 		return &bpf_lwt_in_push_encap_proto;
9044 	default:
9045 		return lwt_out_func_proto(func_id, prog);
9046 	}
9047 }
9048 
9049 static const struct bpf_func_proto *
9050 lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
9051 {
9052 	switch (func_id) {
9053 	case BPF_FUNC_skb_get_tunnel_key:
9054 		return &bpf_skb_get_tunnel_key_proto;
9055 	case BPF_FUNC_skb_set_tunnel_key:
9056 		return bpf_get_skb_set_tunnel_proto(func_id);
9057 	case BPF_FUNC_skb_get_tunnel_opt:
9058 		return &bpf_skb_get_tunnel_opt_proto;
9059 	case BPF_FUNC_skb_set_tunnel_opt:
9060 		return bpf_get_skb_set_tunnel_proto(func_id);
9061 	case BPF_FUNC_redirect:
9062 		return &bpf_redirect_proto;
9063 	case BPF_FUNC_clone_redirect:
9064 		return &bpf_clone_redirect_proto;
9065 	case BPF_FUNC_skb_change_tail:
9066 		return &bpf_skb_change_tail_proto;
9067 	case BPF_FUNC_skb_change_head:
9068 		return &bpf_skb_change_head_proto;
9069 	case BPF_FUNC_skb_store_bytes:
9070 		return &bpf_skb_store_bytes_proto;
9071 	case BPF_FUNC_csum_update:
9072 		return &bpf_csum_update_proto;
9073 	case BPF_FUNC_csum_level:
9074 		return &bpf_csum_level_proto;
9075 	case BPF_FUNC_l3_csum_replace:
9076 		return &bpf_l3_csum_replace_proto;
9077 	case BPF_FUNC_l4_csum_replace:
9078 		return &bpf_l4_csum_replace_proto;
9079 	case BPF_FUNC_set_hash_invalid:
9080 		return &bpf_set_hash_invalid_proto;
9081 	case BPF_FUNC_lwt_push_encap:
9082 		return &bpf_lwt_xmit_push_encap_proto;
9083 	default:
9084 		return lwt_out_func_proto(func_id, prog);
9085 	}
9086 }
9087 
9088 static const struct bpf_func_proto *
9089 lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
9090 {
9091 	switch (func_id) {
9092 	case BPF_FUNC_skb_pull_data:
9093 		return NULL;
9094 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
9095 	case BPF_FUNC_lwt_seg6_store_bytes:
9096 		return &bpf_lwt_seg6_store_bytes_proto;
9097 	case BPF_FUNC_lwt_seg6_action:
9098 		return &bpf_lwt_seg6_action_proto;
9099 	case BPF_FUNC_lwt_seg6_adjust_srh:
9100 		return &bpf_lwt_seg6_adjust_srh_proto;
9101 #endif
9102 	default:
9103 		return lwt_out_func_proto(func_id, prog);
9104 	}
9105 }
9106 
9107 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
9108 				    const struct bpf_prog *prog,
9109 				    struct bpf_insn_access_aux *info)
9110 {
9111 	const int size_default = sizeof(__u32);
9112 
9113 	if (off < 0 || off >= sizeof(struct __sk_buff))
9114 		return false;
9115 
9116 	/* The verifier guarantees that size > 0. */
9117 	if (off % size != 0)
9118 		return false;
9119 
9120 	switch (off) {
9121 	case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
9122 		if (off + size > offsetofend(struct __sk_buff, cb[4]))
9123 			return false;
9124 		break;
9125 	case bpf_ctx_range(struct __sk_buff, data):
9126 	case bpf_ctx_range(struct __sk_buff, data_meta):
9127 	case bpf_ctx_range(struct __sk_buff, data_end):
9128 		if (info->is_ldsx || size != size_default)
9129 			return false;
9130 		break;
9131 	case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
9132 	case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
9133 	case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
9134 	case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
9135 		if (size != size_default)
9136 			return false;
9137 		break;
9138 	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
9139 		return false;
9140 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
9141 		if (type == BPF_WRITE || size != sizeof(__u64))
9142 			return false;
9143 		break;
9144 	case bpf_ctx_range(struct __sk_buff, tstamp):
9145 		if (size != sizeof(__u64))
9146 			return false;
9147 		break;
9148 	case bpf_ctx_range_ptr(struct __sk_buff, sk):
9149 		if (type == BPF_WRITE || size != sizeof(__u64))
9150 			return false;
9151 		info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
9152 		break;
9153 	case offsetof(struct __sk_buff, tstamp_type):
9154 		return false;
9155 	case offsetofend(struct __sk_buff, tstamp_type) ... offsetof(struct __sk_buff, hwtstamp) - 1:
9156 		/* Explicitly prohibit access to padding in __sk_buff. */
9157 		return false;
9158 	default:
9159 		/* Only narrow read access allowed for now. */
9160 		if (type == BPF_WRITE) {
9161 			if (size != size_default)
9162 				return false;
9163 		} else {
9164 			bpf_ctx_record_field_size(info, size_default);
9165 			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
9166 				return false;
9167 		}
9168 	}
9169 
9170 	return true;
9171 }
9172 
9173 static bool sk_filter_is_valid_access(int off, int size,
9174 				      enum bpf_access_type type,
9175 				      const struct bpf_prog *prog,
9176 				      struct bpf_insn_access_aux *info)
9177 {
9178 	switch (off) {
9179 	case bpf_ctx_range(struct __sk_buff, tc_classid):
9180 	case bpf_ctx_range(struct __sk_buff, data):
9181 	case bpf_ctx_range(struct __sk_buff, data_meta):
9182 	case bpf_ctx_range(struct __sk_buff, data_end):
9183 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
9184 	case bpf_ctx_range(struct __sk_buff, tstamp):
9185 	case bpf_ctx_range(struct __sk_buff, wire_len):
9186 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
9187 		return false;
9188 	}
9189 
9190 	if (type == BPF_WRITE) {
9191 		switch (off) {
9192 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
9193 			break;
9194 		default:
9195 			return false;
9196 		}
9197 	}
9198 
9199 	return bpf_skb_is_valid_access(off, size, type, prog, info);
9200 }
9201 
9202 static bool cg_skb_is_valid_access(int off, int size,
9203 				   enum bpf_access_type type,
9204 				   const struct bpf_prog *prog,
9205 				   struct bpf_insn_access_aux *info)
9206 {
9207 	switch (off) {
9208 	case bpf_ctx_range(struct __sk_buff, tc_classid):
9209 	case bpf_ctx_range(struct __sk_buff, data_meta):
9210 	case bpf_ctx_range(struct __sk_buff, wire_len):
9211 		return false;
9212 	case bpf_ctx_range(struct __sk_buff, data):
9213 	case bpf_ctx_range(struct __sk_buff, data_end):
9214 		if (!bpf_token_capable(prog->aux->token, CAP_BPF))
9215 			return false;
9216 		break;
9217 	}
9218 
9219 	if (type == BPF_WRITE) {
9220 		switch (off) {
9221 		case bpf_ctx_range(struct __sk_buff, mark):
9222 		case bpf_ctx_range(struct __sk_buff, priority):
9223 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
9224 			break;
9225 		case bpf_ctx_range(struct __sk_buff, tstamp):
9226 			if (!bpf_token_capable(prog->aux->token, CAP_BPF))
9227 				return false;
9228 			break;
9229 		default:
9230 			return false;
9231 		}
9232 	}
9233 
9234 	switch (off) {
9235 	case bpf_ctx_range(struct __sk_buff, data):
9236 		info->reg_type = PTR_TO_PACKET;
9237 		break;
9238 	case bpf_ctx_range(struct __sk_buff, data_end):
9239 		info->reg_type = PTR_TO_PACKET_END;
9240 		break;
9241 	}
9242 
9243 	return bpf_skb_is_valid_access(off, size, type, prog, info);
9244 }
9245 
9246 static bool lwt_is_valid_access(int off, int size,
9247 				enum bpf_access_type type,
9248 				const struct bpf_prog *prog,
9249 				struct bpf_insn_access_aux *info)
9250 {
9251 	switch (off) {
9252 	case bpf_ctx_range(struct __sk_buff, tc_classid):
9253 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
9254 	case bpf_ctx_range(struct __sk_buff, data_meta):
9255 	case bpf_ctx_range(struct __sk_buff, tstamp):
9256 	case bpf_ctx_range(struct __sk_buff, wire_len):
9257 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
9258 		return false;
9259 	}
9260 
9261 	if (type == BPF_WRITE) {
9262 		switch (off) {
9263 		case bpf_ctx_range(struct __sk_buff, mark):
9264 		case bpf_ctx_range(struct __sk_buff, priority):
9265 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
9266 			break;
9267 		default:
9268 			return false;
9269 		}
9270 	}
9271 
9272 	switch (off) {
9273 	case bpf_ctx_range(struct __sk_buff, data):
9274 		info->reg_type = PTR_TO_PACKET;
9275 		break;
9276 	case bpf_ctx_range(struct __sk_buff, data_end):
9277 		info->reg_type = PTR_TO_PACKET_END;
9278 		break;
9279 	}
9280 
9281 	return bpf_skb_is_valid_access(off, size, type, prog, info);
9282 }
9283 
9284 /* Attach type specific accesses */
9285 static bool __sock_filter_check_attach_type(int off,
9286 					    enum bpf_access_type access_type,
9287 					    enum bpf_attach_type attach_type)
9288 {
9289 	switch (off) {
9290 	case offsetof(struct bpf_sock, bound_dev_if):
9291 	case offsetof(struct bpf_sock, mark):
9292 	case offsetof(struct bpf_sock, priority):
9293 		switch (attach_type) {
9294 		case BPF_CGROUP_INET_SOCK_CREATE:
9295 		case BPF_CGROUP_INET_SOCK_RELEASE:
9296 			goto full_access;
9297 		default:
9298 			return false;
9299 		}
9300 	case bpf_ctx_range(struct bpf_sock, src_ip4):
9301 		switch (attach_type) {
9302 		case BPF_CGROUP_INET4_POST_BIND:
9303 			goto read_only;
9304 		default:
9305 			return false;
9306 		}
9307 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
9308 		switch (attach_type) {
9309 		case BPF_CGROUP_INET6_POST_BIND:
9310 			goto read_only;
9311 		default:
9312 			return false;
9313 		}
9314 	case bpf_ctx_range(struct bpf_sock, src_port):
9315 		switch (attach_type) {
9316 		case BPF_CGROUP_INET4_POST_BIND:
9317 		case BPF_CGROUP_INET6_POST_BIND:
9318 			goto read_only;
9319 		default:
9320 			return false;
9321 		}
9322 	}
9323 read_only:
9324 	return access_type == BPF_READ;
9325 full_access:
9326 	return true;
9327 }
9328 
9329 bool bpf_sock_common_is_valid_access(int off, int size,
9330 				     enum bpf_access_type type,
9331 				     struct bpf_insn_access_aux *info)
9332 {
9333 	switch (off) {
9334 	case bpf_ctx_range_till(struct bpf_sock, type, priority):
9335 		return false;
9336 	default:
9337 		return bpf_sock_is_valid_access(off, size, type, info);
9338 	}
9339 }
9340 
9341 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
9342 			      struct bpf_insn_access_aux *info)
9343 {
9344 	const int size_default = sizeof(__u32);
9345 	int field_size;
9346 
9347 	if (off < 0 || off >= sizeof(struct bpf_sock))
9348 		return false;
9349 	if (off % size != 0)
9350 		return false;
9351 
9352 	switch (off) {
9353 	case offsetof(struct bpf_sock, state):
9354 	case offsetof(struct bpf_sock, family):
9355 	case offsetof(struct bpf_sock, type):
9356 	case offsetof(struct bpf_sock, protocol):
9357 	case offsetof(struct bpf_sock, src_port):
9358 	case offsetof(struct bpf_sock, rx_queue_mapping):
9359 	case bpf_ctx_range(struct bpf_sock, src_ip4):
9360 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
9361 	case bpf_ctx_range(struct bpf_sock, dst_ip4):
9362 	case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
9363 		bpf_ctx_record_field_size(info, size_default);
9364 		return bpf_ctx_narrow_access_ok(off, size, size_default);
9365 	case bpf_ctx_range(struct bpf_sock, dst_port):
9366 		field_size = size == size_default ?
9367 			size_default : sizeof_field(struct bpf_sock, dst_port);
9368 		bpf_ctx_record_field_size(info, field_size);
9369 		return bpf_ctx_narrow_access_ok(off, size, field_size);
9370 	case offsetofend(struct bpf_sock, dst_port) ...
9371 	     offsetof(struct bpf_sock, dst_ip4) - 1:
9372 		return false;
9373 	}
9374 
9375 	return size == size_default;
9376 }
9377 
9378 static bool sock_filter_is_valid_access(int off, int size,
9379 					enum bpf_access_type type,
9380 					const struct bpf_prog *prog,
9381 					struct bpf_insn_access_aux *info)
9382 {
9383 	if (!bpf_sock_is_valid_access(off, size, type, info))
9384 		return false;
9385 	return __sock_filter_check_attach_type(off, type,
9386 					       prog->expected_attach_type);
9387 }
9388 
9389 static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write,
9390 			     const struct bpf_prog *prog)
9391 {
9392 	/* Neither direct read nor direct write requires any preliminary
9393 	 * action.
9394 	 */
9395 	return 0;
9396 }
9397 
9398 static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
9399 				const struct bpf_prog *prog, int drop_verdict)
9400 {
9401 	struct bpf_insn *insn = insn_buf;
9402 
9403 	if (!direct_write)
9404 		return 0;
9405 
9406 	/* if (!skb->cloned)
9407 	 *       goto start;
9408 	 *
9409 	 * (Fast-path, otherwise approximation that we might be
9410 	 *  a clone, do the rest in helper.)
9411 	 */
9412 	*insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET);
9413 	*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
9414 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
9415 
9416 	/* ret = bpf_skb_pull_data(skb, 0); */
9417 	*insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
9418 	*insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
9419 	*insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
9420 			       BPF_FUNC_skb_pull_data);
9421 	/* if (!ret)
9422 	 *      goto restore;
9423 	 * return TC_ACT_SHOT;
9424 	 */
9425 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
9426 	*insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
9427 	*insn++ = BPF_EXIT_INSN();
9428 
9429 	/* restore: */
9430 	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
9431 	/* start: */
9432 	*insn++ = prog->insnsi[0];
9433 
9434 	return insn - insn_buf;
9435 }
9436 
9437 static int bpf_gen_ld_abs(const struct bpf_insn *orig,
9438 			  struct bpf_insn *insn_buf)
9439 {
9440 	bool indirect = BPF_MODE(orig->code) == BPF_IND;
9441 	struct bpf_insn *insn = insn_buf;
9442 
9443 	if (!indirect) {
9444 		*insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
9445 	} else {
9446 		*insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
9447 		if (orig->imm)
9448 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
9449 	}
9450 	/* We're guaranteed here that CTX is in R6. */
9451 	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
9452 
9453 	switch (BPF_SIZE(orig->code)) {
9454 	case BPF_B:
9455 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
9456 		break;
9457 	case BPF_H:
9458 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
9459 		break;
9460 	case BPF_W:
9461 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
9462 		break;
9463 	}
9464 
9465 	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
9466 	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
9467 	*insn++ = BPF_EXIT_INSN();
9468 
9469 	return insn - insn_buf;
9470 }
9471 
9472 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
9473 			       const struct bpf_prog *prog)
9474 {
9475 	return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
9476 }
9477 
9478 static bool tc_cls_act_is_valid_access(int off, int size,
9479 				       enum bpf_access_type type,
9480 				       const struct bpf_prog *prog,
9481 				       struct bpf_insn_access_aux *info)
9482 {
9483 	if (type == BPF_WRITE) {
9484 		switch (off) {
9485 		case bpf_ctx_range(struct __sk_buff, mark):
9486 		case bpf_ctx_range(struct __sk_buff, tc_index):
9487 		case bpf_ctx_range(struct __sk_buff, priority):
9488 		case bpf_ctx_range(struct __sk_buff, tc_classid):
9489 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
9490 		case bpf_ctx_range(struct __sk_buff, tstamp):
9491 		case bpf_ctx_range(struct __sk_buff, queue_mapping):
9492 			break;
9493 		default:
9494 			return false;
9495 		}
9496 	}
9497 
9498 	switch (off) {
9499 	case bpf_ctx_range(struct __sk_buff, data):
9500 		info->reg_type = PTR_TO_PACKET;
9501 		break;
9502 	case bpf_ctx_range(struct __sk_buff, data_meta):
9503 		info->reg_type = PTR_TO_PACKET_META;
9504 		break;
9505 	case bpf_ctx_range(struct __sk_buff, data_end):
9506 		info->reg_type = PTR_TO_PACKET_END;
9507 		break;
9508 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
9509 		return false;
9510 	case offsetof(struct __sk_buff, tstamp_type):
9511 		/* The convert_ctx_access() on reading and writing
9512 		 * __sk_buff->tstamp depends on whether the bpf prog
9513 		 * has used __sk_buff->tstamp_type or not.
9514 		 * Thus, we need to set prog->tstamp_type_access
9515 		 * earlier during is_valid_access() here.
9516 		 */
9517 		((struct bpf_prog *)prog)->tstamp_type_access = 1;
9518 		return size == sizeof(__u8);
9519 	}
9520 
9521 	return bpf_skb_is_valid_access(off, size, type, prog, info);
9522 }
9523 
9524 DEFINE_MUTEX(nf_conn_btf_access_lock);
9525 EXPORT_SYMBOL_GPL(nf_conn_btf_access_lock);
9526 
9527 int (*nfct_btf_struct_access)(struct bpf_verifier_log *log,
9528 			      const struct bpf_reg_state *reg,
9529 			      int off, int size);
9530 EXPORT_SYMBOL_GPL(nfct_btf_struct_access);
9531 
9532 static int tc_cls_act_btf_struct_access(struct bpf_verifier_log *log,
9533 					const struct bpf_reg_state *reg,
9534 					int off, int size)
9535 {
9536 	int ret = -EACCES;
9537 
9538 	mutex_lock(&nf_conn_btf_access_lock);
9539 	if (nfct_btf_struct_access)
9540 		ret = nfct_btf_struct_access(log, reg, off, size);
9541 	mutex_unlock(&nf_conn_btf_access_lock);
9542 
9543 	return ret;
9544 }
9545 
9546 static bool __is_valid_xdp_access(int off, int size)
9547 {
9548 	if (off < 0 || off >= sizeof(struct xdp_md))
9549 		return false;
9550 	if (off % size != 0)
9551 		return false;
9552 	if (size != sizeof(__u32))
9553 		return false;
9554 
9555 	return true;
9556 }
9557 
9558 static bool xdp_is_valid_access(int off, int size,
9559 				enum bpf_access_type type,
9560 				const struct bpf_prog *prog,
9561 				struct bpf_insn_access_aux *info)
9562 {
9563 	if (prog->expected_attach_type != BPF_XDP_DEVMAP) {
9564 		switch (off) {
9565 		case offsetof(struct xdp_md, egress_ifindex):
9566 			return false;
9567 		}
9568 	}
9569 
9570 	if (type == BPF_WRITE) {
9571 		if (bpf_prog_is_offloaded(prog->aux)) {
9572 			switch (off) {
9573 			case offsetof(struct xdp_md, rx_queue_index):
9574 				return __is_valid_xdp_access(off, size);
9575 			}
9576 		}
9577 		return false;
9578 	} else {
9579 		switch (off) {
9580 		case offsetof(struct xdp_md, data_meta):
9581 		case offsetof(struct xdp_md, data):
9582 		case offsetof(struct xdp_md, data_end):
9583 			if (info->is_ldsx)
9584 				return false;
9585 		}
9586 	}
9587 
9588 	switch (off) {
9589 	case offsetof(struct xdp_md, data):
9590 		info->reg_type = PTR_TO_PACKET;
9591 		break;
9592 	case offsetof(struct xdp_md, data_meta):
9593 		info->reg_type = PTR_TO_PACKET_META;
9594 		break;
9595 	case offsetof(struct xdp_md, data_end):
9596 		info->reg_type = PTR_TO_PACKET_END;
9597 		break;
9598 	}
9599 
9600 	return __is_valid_xdp_access(off, size);
9601 }
9602 
9603 void bpf_warn_invalid_xdp_action(const struct net_device *dev,
9604 				 const struct bpf_prog *prog, u32 act)
9605 {
9606 	const u32 act_max = XDP_REDIRECT;
9607 
9608 	pr_warn_once("%s XDP return value %u on prog %s (id %d) dev %s, expect packet loss!\n",
9609 		     act > act_max ? "Illegal" : "Driver unsupported",
9610 		     act, prog->aux->name, prog->aux->id, dev ? dev->name : "N/A");
9611 }
9612 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
9613 
9614 static int xdp_btf_struct_access(struct bpf_verifier_log *log,
9615 				 const struct bpf_reg_state *reg,
9616 				 int off, int size)
9617 {
9618 	int ret = -EACCES;
9619 
9620 	mutex_lock(&nf_conn_btf_access_lock);
9621 	if (nfct_btf_struct_access)
9622 		ret = nfct_btf_struct_access(log, reg, off, size);
9623 	mutex_unlock(&nf_conn_btf_access_lock);
9624 
9625 	return ret;
9626 }
9627 
9628 static bool sock_addr_is_valid_access(int off, int size,
9629 				      enum bpf_access_type type,
9630 				      const struct bpf_prog *prog,
9631 				      struct bpf_insn_access_aux *info)
9632 {
9633 	const int size_default = sizeof(__u32);
9634 
9635 	if (off < 0 || off >= sizeof(struct bpf_sock_addr))
9636 		return false;
9637 	if (off % size != 0)
9638 		return false;
9639 
9640 	/* Disallow access to fields not belonging to the attach type's address
9641 	 * family.
9642 	 */
9643 	switch (off) {
9644 	case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
9645 		switch (prog->expected_attach_type) {
9646 		case BPF_CGROUP_INET4_BIND:
9647 		case BPF_CGROUP_INET4_CONNECT:
9648 		case BPF_CGROUP_INET4_GETPEERNAME:
9649 		case BPF_CGROUP_INET4_GETSOCKNAME:
9650 		case BPF_CGROUP_UDP4_SENDMSG:
9651 		case BPF_CGROUP_UDP4_RECVMSG:
9652 			break;
9653 		default:
9654 			return false;
9655 		}
9656 		break;
9657 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
9658 		switch (prog->expected_attach_type) {
9659 		case BPF_CGROUP_INET6_BIND:
9660 		case BPF_CGROUP_INET6_CONNECT:
9661 		case BPF_CGROUP_INET6_GETPEERNAME:
9662 		case BPF_CGROUP_INET6_GETSOCKNAME:
9663 		case BPF_CGROUP_UDP6_SENDMSG:
9664 		case BPF_CGROUP_UDP6_RECVMSG:
9665 			break;
9666 		default:
9667 			return false;
9668 		}
9669 		break;
9670 	case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
9671 		switch (prog->expected_attach_type) {
9672 		case BPF_CGROUP_UDP4_SENDMSG:
9673 			break;
9674 		default:
9675 			return false;
9676 		}
9677 		break;
9678 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
9679 				msg_src_ip6[3]):
9680 		switch (prog->expected_attach_type) {
9681 		case BPF_CGROUP_UDP6_SENDMSG:
9682 			break;
9683 		default:
9684 			return false;
9685 		}
9686 		break;
9687 	}
9688 
9689 	switch (off) {
9690 	case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
9691 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
9692 	case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
9693 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
9694 				msg_src_ip6[3]):
9695 	case bpf_ctx_range(struct bpf_sock_addr, user_port):
9696 		if (type == BPF_READ) {
9697 			bpf_ctx_record_field_size(info, size_default);
9698 
9699 			if (bpf_ctx_wide_access_ok(off, size,
9700 						   struct bpf_sock_addr,
9701 						   user_ip6))
9702 				return true;
9703 
9704 			if (bpf_ctx_wide_access_ok(off, size,
9705 						   struct bpf_sock_addr,
9706 						   msg_src_ip6))
9707 				return true;
9708 
9709 			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
9710 				return false;
9711 		} else {
9712 			if (bpf_ctx_wide_access_ok(off, size,
9713 						   struct bpf_sock_addr,
9714 						   user_ip6))
9715 				return true;
9716 
9717 			if (bpf_ctx_wide_access_ok(off, size,
9718 						   struct bpf_sock_addr,
9719 						   msg_src_ip6))
9720 				return true;
9721 
9722 			if (size != size_default)
9723 				return false;
9724 		}
9725 		break;
9726 	case bpf_ctx_range_ptr(struct bpf_sock_addr, sk):
9727 		if (type != BPF_READ)
9728 			return false;
9729 		if (size != sizeof(__u64))
9730 			return false;
9731 		info->reg_type = PTR_TO_SOCKET;
9732 		break;
9733 	case bpf_ctx_range(struct bpf_sock_addr, user_family):
9734 	case bpf_ctx_range(struct bpf_sock_addr, family):
9735 	case bpf_ctx_range(struct bpf_sock_addr, type):
9736 	case bpf_ctx_range(struct bpf_sock_addr, protocol):
9737 		if (type != BPF_READ)
9738 			return false;
9739 		if (size != size_default)
9740 			return false;
9741 		break;
9742 	default:
9743 		return false;
9744 	}
9745 
9746 	return true;
9747 }
9748 
9749 static bool sock_ops_is_valid_access(int off, int size,
9750 				     enum bpf_access_type type,
9751 				     const struct bpf_prog *prog,
9752 				     struct bpf_insn_access_aux *info)
9753 {
9754 	const int size_default = sizeof(__u32);
9755 
9756 	if (off < 0 || off >= sizeof(struct bpf_sock_ops))
9757 		return false;
9758 
9759 	/* The verifier guarantees that size > 0. */
9760 	if (off % size != 0)
9761 		return false;
9762 
9763 	if (type == BPF_WRITE) {
9764 		switch (off) {
9765 		case offsetof(struct bpf_sock_ops, reply):
9766 		case offsetof(struct bpf_sock_ops, sk_txhash):
9767 			if (size != size_default)
9768 				return false;
9769 			break;
9770 		default:
9771 			return false;
9772 		}
9773 	} else {
9774 		switch (off) {
9775 		case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
9776 					bytes_acked):
9777 			if (size != sizeof(__u64))
9778 				return false;
9779 			break;
9780 		case bpf_ctx_range_ptr(struct bpf_sock_ops, sk):
9781 			if (size != sizeof(__u64))
9782 				return false;
9783 			info->reg_type = PTR_TO_SOCKET_OR_NULL;
9784 			break;
9785 		case bpf_ctx_range_ptr(struct bpf_sock_ops, skb_data):
9786 			if (size != sizeof(__u64))
9787 				return false;
9788 			info->reg_type = PTR_TO_PACKET;
9789 			break;
9790 		case bpf_ctx_range_ptr(struct bpf_sock_ops, skb_data_end):
9791 			if (size != sizeof(__u64))
9792 				return false;
9793 			info->reg_type = PTR_TO_PACKET_END;
9794 			break;
9795 		case offsetof(struct bpf_sock_ops, skb_tcp_flags):
9796 			bpf_ctx_record_field_size(info, size_default);
9797 			return bpf_ctx_narrow_access_ok(off, size,
9798 							size_default);
9799 		case bpf_ctx_range(struct bpf_sock_ops, skb_hwtstamp):
9800 			if (size != sizeof(__u64))
9801 				return false;
9802 			break;
9803 		default:
9804 			if (size != size_default)
9805 				return false;
9806 			break;
9807 		}
9808 	}
9809 
9810 	return true;
9811 }
9812 
9813 static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
9814 			   const struct bpf_prog *prog)
9815 {
9816 	return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
9817 }
9818 
9819 static bool sk_skb_is_valid_access(int off, int size,
9820 				   enum bpf_access_type type,
9821 				   const struct bpf_prog *prog,
9822 				   struct bpf_insn_access_aux *info)
9823 {
9824 	switch (off) {
9825 	case bpf_ctx_range(struct __sk_buff, tc_classid):
9826 	case bpf_ctx_range(struct __sk_buff, data_meta):
9827 	case bpf_ctx_range(struct __sk_buff, tstamp):
9828 	case bpf_ctx_range(struct __sk_buff, wire_len):
9829 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
9830 		return false;
9831 	}
9832 
9833 	if (type == BPF_WRITE) {
9834 		switch (off) {
9835 		case bpf_ctx_range(struct __sk_buff, tc_index):
9836 		case bpf_ctx_range(struct __sk_buff, priority):
9837 			break;
9838 		default:
9839 			return false;
9840 		}
9841 	}
9842 
9843 	switch (off) {
9844 	case bpf_ctx_range(struct __sk_buff, mark):
9845 		return false;
9846 	case bpf_ctx_range(struct __sk_buff, data):
9847 		info->reg_type = PTR_TO_PACKET;
9848 		break;
9849 	case bpf_ctx_range(struct __sk_buff, data_end):
9850 		info->reg_type = PTR_TO_PACKET_END;
9851 		break;
9852 	}
9853 
9854 	return bpf_skb_is_valid_access(off, size, type, prog, info);
9855 }
9856 
9857 static bool sk_msg_is_valid_access(int off, int size,
9858 				   enum bpf_access_type type,
9859 				   const struct bpf_prog *prog,
9860 				   struct bpf_insn_access_aux *info)
9861 {
9862 	if (type == BPF_WRITE)
9863 		return false;
9864 
9865 	if (off % size != 0)
9866 		return false;
9867 
9868 	switch (off) {
9869 	case bpf_ctx_range_ptr(struct sk_msg_md, data):
9870 		info->reg_type = PTR_TO_PACKET;
9871 		if (size != sizeof(__u64))
9872 			return false;
9873 		break;
9874 	case bpf_ctx_range_ptr(struct sk_msg_md, data_end):
9875 		info->reg_type = PTR_TO_PACKET_END;
9876 		if (size != sizeof(__u64))
9877 			return false;
9878 		break;
9879 	case bpf_ctx_range_ptr(struct sk_msg_md, sk):
9880 		if (size != sizeof(__u64))
9881 			return false;
9882 		info->reg_type = PTR_TO_SOCKET;
9883 		break;
9884 	case bpf_ctx_range(struct sk_msg_md, family):
9885 	case bpf_ctx_range(struct sk_msg_md, remote_ip4):
9886 	case bpf_ctx_range(struct sk_msg_md, local_ip4):
9887 	case bpf_ctx_range_till(struct sk_msg_md, remote_ip6[0], remote_ip6[3]):
9888 	case bpf_ctx_range_till(struct sk_msg_md, local_ip6[0], local_ip6[3]):
9889 	case bpf_ctx_range(struct sk_msg_md, remote_port):
9890 	case bpf_ctx_range(struct sk_msg_md, local_port):
9891 	case bpf_ctx_range(struct sk_msg_md, size):
9892 		if (size != sizeof(__u32))
9893 			return false;
9894 		break;
9895 	default:
9896 		return false;
9897 	}
9898 	return true;
9899 }
9900 
9901 static bool flow_dissector_is_valid_access(int off, int size,
9902 					   enum bpf_access_type type,
9903 					   const struct bpf_prog *prog,
9904 					   struct bpf_insn_access_aux *info)
9905 {
9906 	const int size_default = sizeof(__u32);
9907 
9908 	if (off < 0 || off >= sizeof(struct __sk_buff))
9909 		return false;
9910 
9911 	if (off % size != 0)
9912 		return false;
9913 
9914 	if (type == BPF_WRITE)
9915 		return false;
9916 
9917 	switch (off) {
9918 	case bpf_ctx_range(struct __sk_buff, data):
9919 		if (info->is_ldsx || size != size_default)
9920 			return false;
9921 		info->reg_type = PTR_TO_PACKET;
9922 		return true;
9923 	case bpf_ctx_range(struct __sk_buff, data_end):
9924 		if (info->is_ldsx || size != size_default)
9925 			return false;
9926 		info->reg_type = PTR_TO_PACKET_END;
9927 		return true;
9928 	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
9929 		if (size != sizeof(__u64))
9930 			return false;
9931 		info->reg_type = PTR_TO_FLOW_KEYS;
9932 		return true;
9933 	default:
9934 		return false;
9935 	}
9936 }
9937 
9938 static u32 flow_dissector_convert_ctx_access(enum bpf_access_type type,
9939 					     const struct bpf_insn *si,
9940 					     struct bpf_insn *insn_buf,
9941 					     struct bpf_prog *prog,
9942 					     u32 *target_size)
9943 
9944 {
9945 	struct bpf_insn *insn = insn_buf;
9946 
9947 	switch (si->off) {
9948 	case offsetof(struct __sk_buff, data):
9949 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data),
9950 				      si->dst_reg, si->src_reg,
9951 				      offsetof(struct bpf_flow_dissector, data));
9952 		break;
9953 
9954 	case offsetof(struct __sk_buff, data_end):
9955 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data_end),
9956 				      si->dst_reg, si->src_reg,
9957 				      offsetof(struct bpf_flow_dissector, data_end));
9958 		break;
9959 
9960 	case offsetof(struct __sk_buff, flow_keys):
9961 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, flow_keys),
9962 				      si->dst_reg, si->src_reg,
9963 				      offsetof(struct bpf_flow_dissector, flow_keys));
9964 		break;
9965 	}
9966 
9967 	return insn - insn_buf;
9968 }
9969 
9970 static struct bpf_insn *bpf_convert_tstamp_type_read(const struct bpf_insn *si,
9971 						     struct bpf_insn *insn)
9972 {
9973 	__u8 value_reg = si->dst_reg;
9974 	__u8 skb_reg = si->src_reg;
9975 	BUILD_BUG_ON(__SKB_CLOCK_MAX != (int)BPF_SKB_CLOCK_TAI);
9976 	BUILD_BUG_ON(SKB_CLOCK_REALTIME != (int)BPF_SKB_CLOCK_REALTIME);
9977 	BUILD_BUG_ON(SKB_CLOCK_MONOTONIC != (int)BPF_SKB_CLOCK_MONOTONIC);
9978 	BUILD_BUG_ON(SKB_CLOCK_TAI != (int)BPF_SKB_CLOCK_TAI);
9979 	*insn++ = BPF_LDX_MEM(BPF_B, value_reg, skb_reg, SKB_BF_MONO_TC_OFFSET);
9980 	*insn++ = BPF_ALU32_IMM(BPF_AND, value_reg, SKB_TSTAMP_TYPE_MASK);
9981 #ifdef __BIG_ENDIAN_BITFIELD
9982 	*insn++ = BPF_ALU32_IMM(BPF_RSH, value_reg, SKB_TSTAMP_TYPE_RSHIFT);
9983 #else
9984 	BUILD_BUG_ON(!(SKB_TSTAMP_TYPE_MASK & 0x1));
9985 #endif
9986 
9987 	return insn;
9988 }
9989 
9990 static struct bpf_insn *bpf_convert_shinfo_access(__u8 dst_reg, __u8 skb_reg,
9991 						  struct bpf_insn *insn)
9992 {
9993 	/* si->dst_reg = skb_shinfo(SKB); */
9994 #ifdef NET_SKBUFF_DATA_USES_OFFSET
9995 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
9996 			      BPF_REG_AX, skb_reg,
9997 			      offsetof(struct sk_buff, end));
9998 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, head),
9999 			      dst_reg, skb_reg,
10000 			      offsetof(struct sk_buff, head));
10001 	*insn++ = BPF_ALU64_REG(BPF_ADD, dst_reg, BPF_REG_AX);
10002 #else
10003 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
10004 			      dst_reg, skb_reg,
10005 			      offsetof(struct sk_buff, end));
10006 #endif
10007 
10008 	return insn;
10009 }
10010 
10011 static struct bpf_insn *bpf_convert_tstamp_read(const struct bpf_prog *prog,
10012 						const struct bpf_insn *si,
10013 						struct bpf_insn *insn)
10014 {
10015 	__u8 value_reg = si->dst_reg;
10016 	__u8 skb_reg = si->src_reg;
10017 
10018 #ifdef CONFIG_NET_XGRESS
10019 	/* If the tstamp_type is read,
10020 	 * the bpf prog is aware the tstamp could have delivery time.
10021 	 * Thus, read skb->tstamp as is if tstamp_type_access is true.
10022 	 */
10023 	if (!prog->tstamp_type_access) {
10024 		/* AX is needed because src_reg and dst_reg could be the same */
10025 		__u8 tmp_reg = BPF_REG_AX;
10026 
10027 		*insn++ = BPF_LDX_MEM(BPF_B, tmp_reg, skb_reg, SKB_BF_MONO_TC_OFFSET);
10028 		/* check if ingress mask bits is set */
10029 		*insn++ = BPF_JMP32_IMM(BPF_JSET, tmp_reg, TC_AT_INGRESS_MASK, 1);
10030 		*insn++ = BPF_JMP_A(4);
10031 		*insn++ = BPF_JMP32_IMM(BPF_JSET, tmp_reg, SKB_TSTAMP_TYPE_MASK, 1);
10032 		*insn++ = BPF_JMP_A(2);
10033 		/* skb->tc_at_ingress && skb->tstamp_type,
10034 		 * read 0 as the (rcv) timestamp.
10035 		 */
10036 		*insn++ = BPF_MOV64_IMM(value_reg, 0);
10037 		*insn++ = BPF_JMP_A(1);
10038 	}
10039 #endif
10040 
10041 	*insn++ = BPF_LDX_MEM(BPF_DW, value_reg, skb_reg,
10042 			      offsetof(struct sk_buff, tstamp));
10043 	return insn;
10044 }
10045 
10046 static struct bpf_insn *bpf_convert_tstamp_write(const struct bpf_prog *prog,
10047 						 const struct bpf_insn *si,
10048 						 struct bpf_insn *insn)
10049 {
10050 	__u8 value_reg = si->src_reg;
10051 	__u8 skb_reg = si->dst_reg;
10052 
10053 #ifdef CONFIG_NET_XGRESS
10054 	/* If the tstamp_type is read,
10055 	 * the bpf prog is aware the tstamp could have delivery time.
10056 	 * Thus, write skb->tstamp as is if tstamp_type_access is true.
10057 	 * Otherwise, writing at ingress will have to clear the
10058 	 * skb->tstamp_type bit also.
10059 	 */
10060 	if (!prog->tstamp_type_access) {
10061 		__u8 tmp_reg = BPF_REG_AX;
10062 
10063 		*insn++ = BPF_LDX_MEM(BPF_B, tmp_reg, skb_reg, SKB_BF_MONO_TC_OFFSET);
10064 		/* Writing __sk_buff->tstamp as ingress, goto <clear> */
10065 		*insn++ = BPF_JMP32_IMM(BPF_JSET, tmp_reg, TC_AT_INGRESS_MASK, 1);
10066 		/* goto <store> */
10067 		*insn++ = BPF_JMP_A(2);
10068 		/* <clear>: skb->tstamp_type */
10069 		*insn++ = BPF_ALU32_IMM(BPF_AND, tmp_reg, ~SKB_TSTAMP_TYPE_MASK);
10070 		*insn++ = BPF_STX_MEM(BPF_B, skb_reg, tmp_reg, SKB_BF_MONO_TC_OFFSET);
10071 	}
10072 #endif
10073 
10074 	/* <store>: skb->tstamp = tstamp */
10075 	*insn++ = BPF_RAW_INSN(BPF_CLASS(si->code) | BPF_DW | BPF_MEM,
10076 			       skb_reg, value_reg, offsetof(struct sk_buff, tstamp), si->imm);
10077 	return insn;
10078 }
10079 
10080 #define BPF_EMIT_STORE(size, si, off)					\
10081 	BPF_RAW_INSN(BPF_CLASS((si)->code) | (size) | BPF_MEM,		\
10082 		     (si)->dst_reg, (si)->src_reg, (off), (si)->imm)
10083 
10084 static u32 bpf_convert_ctx_access(enum bpf_access_type type,
10085 				  const struct bpf_insn *si,
10086 				  struct bpf_insn *insn_buf,
10087 				  struct bpf_prog *prog, u32 *target_size)
10088 {
10089 	struct bpf_insn *insn = insn_buf;
10090 	int off;
10091 
10092 	switch (si->off) {
10093 	case offsetof(struct __sk_buff, len):
10094 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10095 				      bpf_target_off(struct sk_buff, len, 4,
10096 						     target_size));
10097 		break;
10098 
10099 	case offsetof(struct __sk_buff, protocol):
10100 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
10101 				      bpf_target_off(struct sk_buff, protocol, 2,
10102 						     target_size));
10103 		break;
10104 
10105 	case offsetof(struct __sk_buff, vlan_proto):
10106 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
10107 				      bpf_target_off(struct sk_buff, vlan_proto, 2,
10108 						     target_size));
10109 		break;
10110 
10111 	case offsetof(struct __sk_buff, priority):
10112 		if (type == BPF_WRITE)
10113 			*insn++ = BPF_EMIT_STORE(BPF_W, si,
10114 						 bpf_target_off(struct sk_buff, priority, 4,
10115 								target_size));
10116 		else
10117 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10118 					      bpf_target_off(struct sk_buff, priority, 4,
10119 							     target_size));
10120 		break;
10121 
10122 	case offsetof(struct __sk_buff, ingress_ifindex):
10123 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10124 				      bpf_target_off(struct sk_buff, skb_iif, 4,
10125 						     target_size));
10126 		break;
10127 
10128 	case offsetof(struct __sk_buff, ifindex):
10129 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
10130 				      si->dst_reg, si->src_reg,
10131 				      offsetof(struct sk_buff, dev));
10132 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
10133 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10134 				      bpf_target_off(struct net_device, ifindex, 4,
10135 						     target_size));
10136 		break;
10137 
10138 	case offsetof(struct __sk_buff, hash):
10139 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10140 				      bpf_target_off(struct sk_buff, hash, 4,
10141 						     target_size));
10142 		break;
10143 
10144 	case offsetof(struct __sk_buff, mark):
10145 		if (type == BPF_WRITE)
10146 			*insn++ = BPF_EMIT_STORE(BPF_W, si,
10147 						 bpf_target_off(struct sk_buff, mark, 4,
10148 								target_size));
10149 		else
10150 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10151 					      bpf_target_off(struct sk_buff, mark, 4,
10152 							     target_size));
10153 		break;
10154 
10155 	case offsetof(struct __sk_buff, pkt_type):
10156 		*target_size = 1;
10157 		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
10158 				      PKT_TYPE_OFFSET);
10159 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
10160 #ifdef __BIG_ENDIAN_BITFIELD
10161 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
10162 #endif
10163 		break;
10164 
10165 	case offsetof(struct __sk_buff, queue_mapping):
10166 		if (type == BPF_WRITE) {
10167 			u32 offset = bpf_target_off(struct sk_buff, queue_mapping, 2, target_size);
10168 
10169 			if (BPF_CLASS(si->code) == BPF_ST && si->imm >= NO_QUEUE_MAPPING) {
10170 				*insn++ = BPF_JMP_A(0); /* noop */
10171 				break;
10172 			}
10173 
10174 			if (BPF_CLASS(si->code) == BPF_STX)
10175 				*insn++ = BPF_JMP_IMM(BPF_JGE, si->src_reg, NO_QUEUE_MAPPING, 1);
10176 			*insn++ = BPF_EMIT_STORE(BPF_H, si, offset);
10177 		} else {
10178 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
10179 					      bpf_target_off(struct sk_buff,
10180 							     queue_mapping,
10181 							     2, target_size));
10182 		}
10183 		break;
10184 
10185 	case offsetof(struct __sk_buff, vlan_present):
10186 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10187 				      bpf_target_off(struct sk_buff,
10188 						     vlan_all, 4, target_size));
10189 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
10190 		*insn++ = BPF_ALU32_IMM(BPF_MOV, si->dst_reg, 1);
10191 		break;
10192 
10193 	case offsetof(struct __sk_buff, vlan_tci):
10194 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
10195 				      bpf_target_off(struct sk_buff, vlan_tci, 2,
10196 						     target_size));
10197 		break;
10198 
10199 	case offsetof(struct __sk_buff, cb[0]) ...
10200 	     offsetofend(struct __sk_buff, cb[4]) - 1:
10201 		BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, data) < 20);
10202 		BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
10203 			      offsetof(struct qdisc_skb_cb, data)) %
10204 			     sizeof(__u64));
10205 
10206 		prog->cb_access = 1;
10207 		off  = si->off;
10208 		off -= offsetof(struct __sk_buff, cb[0]);
10209 		off += offsetof(struct sk_buff, cb);
10210 		off += offsetof(struct qdisc_skb_cb, data);
10211 		if (type == BPF_WRITE)
10212 			*insn++ = BPF_EMIT_STORE(BPF_SIZE(si->code), si, off);
10213 		else
10214 			*insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
10215 					      si->src_reg, off);
10216 		break;
10217 
10218 	case offsetof(struct __sk_buff, tc_classid):
10219 		BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, tc_classid) != 2);
10220 
10221 		off  = si->off;
10222 		off -= offsetof(struct __sk_buff, tc_classid);
10223 		off += offsetof(struct sk_buff, cb);
10224 		off += offsetof(struct qdisc_skb_cb, tc_classid);
10225 		*target_size = 2;
10226 		if (type == BPF_WRITE)
10227 			*insn++ = BPF_EMIT_STORE(BPF_H, si, off);
10228 		else
10229 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
10230 					      si->src_reg, off);
10231 		break;
10232 
10233 	case offsetof(struct __sk_buff, data):
10234 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
10235 				      si->dst_reg, si->src_reg,
10236 				      offsetof(struct sk_buff, data));
10237 		break;
10238 
10239 	case offsetof(struct __sk_buff, data_meta):
10240 		off  = si->off;
10241 		off -= offsetof(struct __sk_buff, data_meta);
10242 		off += offsetof(struct sk_buff, cb);
10243 		off += offsetof(struct bpf_skb_data_end, data_meta);
10244 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
10245 				      si->src_reg, off);
10246 		break;
10247 
10248 	case offsetof(struct __sk_buff, data_end):
10249 		off  = si->off;
10250 		off -= offsetof(struct __sk_buff, data_end);
10251 		off += offsetof(struct sk_buff, cb);
10252 		off += offsetof(struct bpf_skb_data_end, data_end);
10253 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
10254 				      si->src_reg, off);
10255 		break;
10256 
10257 	case offsetof(struct __sk_buff, tc_index):
10258 #ifdef CONFIG_NET_SCHED
10259 		if (type == BPF_WRITE)
10260 			*insn++ = BPF_EMIT_STORE(BPF_H, si,
10261 						 bpf_target_off(struct sk_buff, tc_index, 2,
10262 								target_size));
10263 		else
10264 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
10265 					      bpf_target_off(struct sk_buff, tc_index, 2,
10266 							     target_size));
10267 #else
10268 		*target_size = 2;
10269 		if (type == BPF_WRITE)
10270 			*insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
10271 		else
10272 			*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
10273 #endif
10274 		break;
10275 
10276 	case offsetof(struct __sk_buff, napi_id):
10277 #if defined(CONFIG_NET_RX_BUSY_POLL)
10278 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10279 				      bpf_target_off(struct sk_buff, napi_id, 4,
10280 						     target_size));
10281 		*insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
10282 		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
10283 #else
10284 		*target_size = 4;
10285 		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
10286 #endif
10287 		break;
10288 	case offsetof(struct __sk_buff, family):
10289 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
10290 
10291 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
10292 				      si->dst_reg, si->src_reg,
10293 				      offsetof(struct sk_buff, sk));
10294 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10295 				      bpf_target_off(struct sock_common,
10296 						     skc_family,
10297 						     2, target_size));
10298 		break;
10299 	case offsetof(struct __sk_buff, remote_ip4):
10300 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
10301 
10302 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
10303 				      si->dst_reg, si->src_reg,
10304 				      offsetof(struct sk_buff, sk));
10305 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10306 				      bpf_target_off(struct sock_common,
10307 						     skc_daddr,
10308 						     4, target_size));
10309 		break;
10310 	case offsetof(struct __sk_buff, local_ip4):
10311 		BUILD_BUG_ON(sizeof_field(struct sock_common,
10312 					  skc_rcv_saddr) != 4);
10313 
10314 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
10315 				      si->dst_reg, si->src_reg,
10316 				      offsetof(struct sk_buff, sk));
10317 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10318 				      bpf_target_off(struct sock_common,
10319 						     skc_rcv_saddr,
10320 						     4, target_size));
10321 		break;
10322 	case offsetof(struct __sk_buff, remote_ip6[0]) ...
10323 	     offsetof(struct __sk_buff, remote_ip6[3]):
10324 #if IS_ENABLED(CONFIG_IPV6)
10325 		BUILD_BUG_ON(sizeof_field(struct sock_common,
10326 					  skc_v6_daddr.s6_addr32[0]) != 4);
10327 
10328 		off = si->off;
10329 		off -= offsetof(struct __sk_buff, remote_ip6[0]);
10330 
10331 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
10332 				      si->dst_reg, si->src_reg,
10333 				      offsetof(struct sk_buff, sk));
10334 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10335 				      offsetof(struct sock_common,
10336 					       skc_v6_daddr.s6_addr32[0]) +
10337 				      off);
10338 #else
10339 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10340 #endif
10341 		break;
10342 	case offsetof(struct __sk_buff, local_ip6[0]) ...
10343 	     offsetof(struct __sk_buff, local_ip6[3]):
10344 #if IS_ENABLED(CONFIG_IPV6)
10345 		BUILD_BUG_ON(sizeof_field(struct sock_common,
10346 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
10347 
10348 		off = si->off;
10349 		off -= offsetof(struct __sk_buff, local_ip6[0]);
10350 
10351 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
10352 				      si->dst_reg, si->src_reg,
10353 				      offsetof(struct sk_buff, sk));
10354 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10355 				      offsetof(struct sock_common,
10356 					       skc_v6_rcv_saddr.s6_addr32[0]) +
10357 				      off);
10358 #else
10359 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10360 #endif
10361 		break;
10362 
10363 	case offsetof(struct __sk_buff, remote_port):
10364 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
10365 
10366 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
10367 				      si->dst_reg, si->src_reg,
10368 				      offsetof(struct sk_buff, sk));
10369 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10370 				      bpf_target_off(struct sock_common,
10371 						     skc_dport,
10372 						     2, target_size));
10373 #ifndef __BIG_ENDIAN_BITFIELD
10374 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
10375 #endif
10376 		break;
10377 
10378 	case offsetof(struct __sk_buff, local_port):
10379 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
10380 
10381 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
10382 				      si->dst_reg, si->src_reg,
10383 				      offsetof(struct sk_buff, sk));
10384 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10385 				      bpf_target_off(struct sock_common,
10386 						     skc_num, 2, target_size));
10387 		break;
10388 
10389 	case offsetof(struct __sk_buff, tstamp):
10390 		BUILD_BUG_ON(sizeof_field(struct sk_buff, tstamp) != 8);
10391 
10392 		if (type == BPF_WRITE)
10393 			insn = bpf_convert_tstamp_write(prog, si, insn);
10394 		else
10395 			insn = bpf_convert_tstamp_read(prog, si, insn);
10396 		break;
10397 
10398 	case offsetof(struct __sk_buff, tstamp_type):
10399 		insn = bpf_convert_tstamp_type_read(si, insn);
10400 		break;
10401 
10402 	case offsetof(struct __sk_buff, gso_segs):
10403 		insn = bpf_convert_shinfo_access(si->dst_reg, si->src_reg, insn);
10404 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_segs),
10405 				      si->dst_reg, si->dst_reg,
10406 				      bpf_target_off(struct skb_shared_info,
10407 						     gso_segs, 2,
10408 						     target_size));
10409 		break;
10410 	case offsetof(struct __sk_buff, gso_size):
10411 		insn = bpf_convert_shinfo_access(si->dst_reg, si->src_reg, insn);
10412 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_size),
10413 				      si->dst_reg, si->dst_reg,
10414 				      bpf_target_off(struct skb_shared_info,
10415 						     gso_size, 2,
10416 						     target_size));
10417 		break;
10418 	case offsetof(struct __sk_buff, wire_len):
10419 		BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, pkt_len) != 4);
10420 
10421 		off = si->off;
10422 		off -= offsetof(struct __sk_buff, wire_len);
10423 		off += offsetof(struct sk_buff, cb);
10424 		off += offsetof(struct qdisc_skb_cb, pkt_len);
10425 		*target_size = 4;
10426 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off);
10427 		break;
10428 
10429 	case offsetof(struct __sk_buff, sk):
10430 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
10431 				      si->dst_reg, si->src_reg,
10432 				      offsetof(struct sk_buff, sk));
10433 		break;
10434 	case offsetof(struct __sk_buff, hwtstamp):
10435 		BUILD_BUG_ON(sizeof_field(struct skb_shared_hwtstamps, hwtstamp) != 8);
10436 		BUILD_BUG_ON(offsetof(struct skb_shared_hwtstamps, hwtstamp) != 0);
10437 
10438 		insn = bpf_convert_shinfo_access(si->dst_reg, si->src_reg, insn);
10439 		*insn++ = BPF_LDX_MEM(BPF_DW,
10440 				      si->dst_reg, si->dst_reg,
10441 				      bpf_target_off(struct skb_shared_info,
10442 						     hwtstamps, 8,
10443 						     target_size));
10444 		break;
10445 	}
10446 
10447 	return insn - insn_buf;
10448 }
10449 
10450 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
10451 				const struct bpf_insn *si,
10452 				struct bpf_insn *insn_buf,
10453 				struct bpf_prog *prog, u32 *target_size)
10454 {
10455 	struct bpf_insn *insn = insn_buf;
10456 	int off;
10457 
10458 	switch (si->off) {
10459 	case offsetof(struct bpf_sock, bound_dev_if):
10460 		BUILD_BUG_ON(sizeof_field(struct sock, sk_bound_dev_if) != 4);
10461 
10462 		if (type == BPF_WRITE)
10463 			*insn++ = BPF_EMIT_STORE(BPF_W, si,
10464 						 offsetof(struct sock, sk_bound_dev_if));
10465 		else
10466 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10467 				      offsetof(struct sock, sk_bound_dev_if));
10468 		break;
10469 
10470 	case offsetof(struct bpf_sock, mark):
10471 		BUILD_BUG_ON(sizeof_field(struct sock, sk_mark) != 4);
10472 
10473 		if (type == BPF_WRITE)
10474 			*insn++ = BPF_EMIT_STORE(BPF_W, si,
10475 						 offsetof(struct sock, sk_mark));
10476 		else
10477 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10478 				      offsetof(struct sock, sk_mark));
10479 		break;
10480 
10481 	case offsetof(struct bpf_sock, priority):
10482 		BUILD_BUG_ON(sizeof_field(struct sock, sk_priority) != 4);
10483 
10484 		if (type == BPF_WRITE)
10485 			*insn++ = BPF_EMIT_STORE(BPF_W, si,
10486 						 offsetof(struct sock, sk_priority));
10487 		else
10488 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10489 				      offsetof(struct sock, sk_priority));
10490 		break;
10491 
10492 	case offsetof(struct bpf_sock, family):
10493 		*insn++ = BPF_LDX_MEM(
10494 			BPF_FIELD_SIZEOF(struct sock_common, skc_family),
10495 			si->dst_reg, si->src_reg,
10496 			bpf_target_off(struct sock_common,
10497 				       skc_family,
10498 				       sizeof_field(struct sock_common,
10499 						    skc_family),
10500 				       target_size));
10501 		break;
10502 
10503 	case offsetof(struct bpf_sock, type):
10504 		*insn++ = BPF_LDX_MEM(
10505 			BPF_FIELD_SIZEOF(struct sock, sk_type),
10506 			si->dst_reg, si->src_reg,
10507 			bpf_target_off(struct sock, sk_type,
10508 				       sizeof_field(struct sock, sk_type),
10509 				       target_size));
10510 		break;
10511 
10512 	case offsetof(struct bpf_sock, protocol):
10513 		*insn++ = BPF_LDX_MEM(
10514 			BPF_FIELD_SIZEOF(struct sock, sk_protocol),
10515 			si->dst_reg, si->src_reg,
10516 			bpf_target_off(struct sock, sk_protocol,
10517 				       sizeof_field(struct sock, sk_protocol),
10518 				       target_size));
10519 		break;
10520 
10521 	case offsetof(struct bpf_sock, src_ip4):
10522 		*insn++ = BPF_LDX_MEM(
10523 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
10524 			bpf_target_off(struct sock_common, skc_rcv_saddr,
10525 				       sizeof_field(struct sock_common,
10526 						    skc_rcv_saddr),
10527 				       target_size));
10528 		break;
10529 
10530 	case offsetof(struct bpf_sock, dst_ip4):
10531 		*insn++ = BPF_LDX_MEM(
10532 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
10533 			bpf_target_off(struct sock_common, skc_daddr,
10534 				       sizeof_field(struct sock_common,
10535 						    skc_daddr),
10536 				       target_size));
10537 		break;
10538 
10539 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
10540 #if IS_ENABLED(CONFIG_IPV6)
10541 		off = si->off;
10542 		off -= offsetof(struct bpf_sock, src_ip6[0]);
10543 		*insn++ = BPF_LDX_MEM(
10544 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
10545 			bpf_target_off(
10546 				struct sock_common,
10547 				skc_v6_rcv_saddr.s6_addr32[0],
10548 				sizeof_field(struct sock_common,
10549 					     skc_v6_rcv_saddr.s6_addr32[0]),
10550 				target_size) + off);
10551 #else
10552 		(void)off;
10553 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10554 #endif
10555 		break;
10556 
10557 	case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
10558 #if IS_ENABLED(CONFIG_IPV6)
10559 		off = si->off;
10560 		off -= offsetof(struct bpf_sock, dst_ip6[0]);
10561 		*insn++ = BPF_LDX_MEM(
10562 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
10563 			bpf_target_off(struct sock_common,
10564 				       skc_v6_daddr.s6_addr32[0],
10565 				       sizeof_field(struct sock_common,
10566 						    skc_v6_daddr.s6_addr32[0]),
10567 				       target_size) + off);
10568 #else
10569 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10570 		*target_size = 4;
10571 #endif
10572 		break;
10573 
10574 	case offsetof(struct bpf_sock, src_port):
10575 		*insn++ = BPF_LDX_MEM(
10576 			BPF_FIELD_SIZEOF(struct sock_common, skc_num),
10577 			si->dst_reg, si->src_reg,
10578 			bpf_target_off(struct sock_common, skc_num,
10579 				       sizeof_field(struct sock_common,
10580 						    skc_num),
10581 				       target_size));
10582 		break;
10583 
10584 	case offsetof(struct bpf_sock, dst_port):
10585 		*insn++ = BPF_LDX_MEM(
10586 			BPF_FIELD_SIZEOF(struct sock_common, skc_dport),
10587 			si->dst_reg, si->src_reg,
10588 			bpf_target_off(struct sock_common, skc_dport,
10589 				       sizeof_field(struct sock_common,
10590 						    skc_dport),
10591 				       target_size));
10592 		break;
10593 
10594 	case offsetof(struct bpf_sock, state):
10595 		*insn++ = BPF_LDX_MEM(
10596 			BPF_FIELD_SIZEOF(struct sock_common, skc_state),
10597 			si->dst_reg, si->src_reg,
10598 			bpf_target_off(struct sock_common, skc_state,
10599 				       sizeof_field(struct sock_common,
10600 						    skc_state),
10601 				       target_size));
10602 		break;
10603 	case offsetof(struct bpf_sock, rx_queue_mapping):
10604 #ifdef CONFIG_SOCK_RX_QUEUE_MAPPING
10605 		*insn++ = BPF_LDX_MEM(
10606 			BPF_FIELD_SIZEOF(struct sock, sk_rx_queue_mapping),
10607 			si->dst_reg, si->src_reg,
10608 			bpf_target_off(struct sock, sk_rx_queue_mapping,
10609 				       sizeof_field(struct sock,
10610 						    sk_rx_queue_mapping),
10611 				       target_size));
10612 		*insn++ = BPF_JMP_IMM(BPF_JNE, si->dst_reg, NO_QUEUE_MAPPING,
10613 				      1);
10614 		*insn++ = BPF_MOV32_IMM(si->dst_reg, -1);
10615 #else
10616 		*insn++ = BPF_MOV32_IMM(si->dst_reg, -1);
10617 #endif
10618 		*target_size = sizeof_field(struct bpf_sock, rx_queue_mapping);
10619 
10620 		break;
10621 	}
10622 
10623 	return insn - insn_buf;
10624 }
10625 
10626 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
10627 					 const struct bpf_insn *si,
10628 					 struct bpf_insn *insn_buf,
10629 					 struct bpf_prog *prog, u32 *target_size)
10630 {
10631 	struct bpf_insn *insn = insn_buf;
10632 
10633 	switch (si->off) {
10634 	case offsetof(struct __sk_buff, ifindex):
10635 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
10636 				      si->dst_reg, si->src_reg,
10637 				      offsetof(struct sk_buff, dev));
10638 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10639 				      bpf_target_off(struct net_device, ifindex, 4,
10640 						     target_size));
10641 		break;
10642 	default:
10643 		return bpf_convert_ctx_access(type, si, insn_buf, prog,
10644 					      target_size);
10645 	}
10646 
10647 	return insn - insn_buf;
10648 }
10649 
10650 static u32 xdp_convert_ctx_access(enum bpf_access_type type,
10651 				  const struct bpf_insn *si,
10652 				  struct bpf_insn *insn_buf,
10653 				  struct bpf_prog *prog, u32 *target_size)
10654 {
10655 	struct bpf_insn *insn = insn_buf;
10656 
10657 	switch (si->off) {
10658 	case offsetof(struct xdp_md, data):
10659 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
10660 				      si->dst_reg, si->src_reg,
10661 				      offsetof(struct xdp_buff, data));
10662 		break;
10663 	case offsetof(struct xdp_md, data_meta):
10664 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
10665 				      si->dst_reg, si->src_reg,
10666 				      offsetof(struct xdp_buff, data_meta));
10667 		break;
10668 	case offsetof(struct xdp_md, data_end):
10669 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
10670 				      si->dst_reg, si->src_reg,
10671 				      offsetof(struct xdp_buff, data_end));
10672 		break;
10673 	case offsetof(struct xdp_md, ingress_ifindex):
10674 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
10675 				      si->dst_reg, si->src_reg,
10676 				      offsetof(struct xdp_buff, rxq));
10677 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
10678 				      si->dst_reg, si->dst_reg,
10679 				      offsetof(struct xdp_rxq_info, dev));
10680 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10681 				      offsetof(struct net_device, ifindex));
10682 		break;
10683 	case offsetof(struct xdp_md, rx_queue_index):
10684 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
10685 				      si->dst_reg, si->src_reg,
10686 				      offsetof(struct xdp_buff, rxq));
10687 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10688 				      offsetof(struct xdp_rxq_info,
10689 					       queue_index));
10690 		break;
10691 	case offsetof(struct xdp_md, egress_ifindex):
10692 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, txq),
10693 				      si->dst_reg, si->src_reg,
10694 				      offsetof(struct xdp_buff, txq));
10695 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_txq_info, dev),
10696 				      si->dst_reg, si->dst_reg,
10697 				      offsetof(struct xdp_txq_info, dev));
10698 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10699 				      offsetof(struct net_device, ifindex));
10700 		break;
10701 	}
10702 
10703 	return insn - insn_buf;
10704 }
10705 
10706 /* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
10707  * context Structure, F is Field in context structure that contains a pointer
10708  * to Nested Structure of type NS that has the field NF.
10709  *
10710  * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
10711  * sure that SIZE is not greater than actual size of S.F.NF.
10712  *
10713  * If offset OFF is provided, the load happens from that offset relative to
10714  * offset of NF.
10715  */
10716 #define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)	       \
10717 	do {								       \
10718 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
10719 				      si->src_reg, offsetof(S, F));	       \
10720 		*insn++ = BPF_LDX_MEM(					       \
10721 			SIZE, si->dst_reg, si->dst_reg,			       \
10722 			bpf_target_off(NS, NF, sizeof_field(NS, NF),	       \
10723 				       target_size)			       \
10724 				+ OFF);					       \
10725 	} while (0)
10726 
10727 #define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)			       \
10728 	SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,		       \
10729 					     BPF_FIELD_SIZEOF(NS, NF), 0)
10730 
10731 /* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
10732  * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
10733  *
10734  * In addition it uses Temporary Field TF (member of struct S) as the 3rd
10735  * "register" since two registers available in convert_ctx_access are not
10736  * enough: we can't override neither SRC, since it contains value to store, nor
10737  * DST since it contains pointer to context that may be used by later
10738  * instructions. But we need a temporary place to save pointer to nested
10739  * structure whose field we want to store to.
10740  */
10741 #define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE, OFF, TF)	       \
10742 	do {								       \
10743 		int tmp_reg = BPF_REG_9;				       \
10744 		if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)	       \
10745 			--tmp_reg;					       \
10746 		if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)	       \
10747 			--tmp_reg;					       \
10748 		*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,	       \
10749 				      offsetof(S, TF));			       \
10750 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,	       \
10751 				      si->dst_reg, offsetof(S, F));	       \
10752 		*insn++ = BPF_RAW_INSN(SIZE | BPF_MEM | BPF_CLASS(si->code),   \
10753 				       tmp_reg, si->src_reg,		       \
10754 			bpf_target_off(NS, NF, sizeof_field(NS, NF),	       \
10755 				       target_size)			       \
10756 				       + OFF,				       \
10757 				       si->imm);			       \
10758 		*insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,	       \
10759 				      offsetof(S, TF));			       \
10760 	} while (0)
10761 
10762 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
10763 						      TF)		       \
10764 	do {								       \
10765 		if (type == BPF_WRITE) {				       \
10766 			SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE,   \
10767 							 OFF, TF);	       \
10768 		} else {						       \
10769 			SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(		       \
10770 				S, NS, F, NF, SIZE, OFF);  \
10771 		}							       \
10772 	} while (0)
10773 
10774 static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
10775 					const struct bpf_insn *si,
10776 					struct bpf_insn *insn_buf,
10777 					struct bpf_prog *prog, u32 *target_size)
10778 {
10779 	int off, port_size = sizeof_field(struct sockaddr_in6, sin6_port);
10780 	struct bpf_insn *insn = insn_buf;
10781 
10782 	switch (si->off) {
10783 	case offsetof(struct bpf_sock_addr, user_family):
10784 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10785 					    struct sockaddr, uaddr, sa_family);
10786 		break;
10787 
10788 	case offsetof(struct bpf_sock_addr, user_ip4):
10789 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10790 			struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
10791 			sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
10792 		break;
10793 
10794 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
10795 		off = si->off;
10796 		off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
10797 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10798 			struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
10799 			sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
10800 			tmp_reg);
10801 		break;
10802 
10803 	case offsetof(struct bpf_sock_addr, user_port):
10804 		/* To get port we need to know sa_family first and then treat
10805 		 * sockaddr as either sockaddr_in or sockaddr_in6.
10806 		 * Though we can simplify since port field has same offset and
10807 		 * size in both structures.
10808 		 * Here we check this invariant and use just one of the
10809 		 * structures if it's true.
10810 		 */
10811 		BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
10812 			     offsetof(struct sockaddr_in6, sin6_port));
10813 		BUILD_BUG_ON(sizeof_field(struct sockaddr_in, sin_port) !=
10814 			     sizeof_field(struct sockaddr_in6, sin6_port));
10815 		/* Account for sin6_port being smaller than user_port. */
10816 		port_size = min(port_size, BPF_LDST_BYTES(si));
10817 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10818 			struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
10819 			sin6_port, bytes_to_bpf_size(port_size), 0, tmp_reg);
10820 		break;
10821 
10822 	case offsetof(struct bpf_sock_addr, family):
10823 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10824 					    struct sock, sk, sk_family);
10825 		break;
10826 
10827 	case offsetof(struct bpf_sock_addr, type):
10828 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10829 					    struct sock, sk, sk_type);
10830 		break;
10831 
10832 	case offsetof(struct bpf_sock_addr, protocol):
10833 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10834 					    struct sock, sk, sk_protocol);
10835 		break;
10836 
10837 	case offsetof(struct bpf_sock_addr, msg_src_ip4):
10838 		/* Treat t_ctx as struct in_addr for msg_src_ip4. */
10839 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10840 			struct bpf_sock_addr_kern, struct in_addr, t_ctx,
10841 			s_addr, BPF_SIZE(si->code), 0, tmp_reg);
10842 		break;
10843 
10844 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
10845 				msg_src_ip6[3]):
10846 		off = si->off;
10847 		off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
10848 		/* Treat t_ctx as struct in6_addr for msg_src_ip6. */
10849 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10850 			struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
10851 			s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
10852 		break;
10853 	case offsetof(struct bpf_sock_addr, sk):
10854 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_addr_kern, sk),
10855 				      si->dst_reg, si->src_reg,
10856 				      offsetof(struct bpf_sock_addr_kern, sk));
10857 		break;
10858 	}
10859 
10860 	return insn - insn_buf;
10861 }
10862 
10863 static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
10864 				       const struct bpf_insn *si,
10865 				       struct bpf_insn *insn_buf,
10866 				       struct bpf_prog *prog,
10867 				       u32 *target_size)
10868 {
10869 	struct bpf_insn *insn = insn_buf;
10870 	int off;
10871 
10872 /* Helper macro for adding read access to tcp_sock or sock fields. */
10873 #define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)			      \
10874 	do {								      \
10875 		int fullsock_reg = si->dst_reg, reg = BPF_REG_9, jmp = 2;     \
10876 		BUILD_BUG_ON(sizeof_field(OBJ, OBJ_FIELD) >		      \
10877 			     sizeof_field(struct bpf_sock_ops, BPF_FIELD));   \
10878 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10879 			reg--;						      \
10880 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10881 			reg--;						      \
10882 		if (si->dst_reg == si->src_reg) {			      \
10883 			*insn++ = BPF_STX_MEM(BPF_DW, si->src_reg, reg,	      \
10884 					  offsetof(struct bpf_sock_ops_kern,  \
10885 					  temp));			      \
10886 			fullsock_reg = reg;				      \
10887 			jmp += 2;					      \
10888 		}							      \
10889 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10890 						struct bpf_sock_ops_kern,     \
10891 						is_locked_tcp_sock),	      \
10892 				      fullsock_reg, si->src_reg,	      \
10893 				      offsetof(struct bpf_sock_ops_kern,      \
10894 					       is_locked_tcp_sock));	      \
10895 		*insn++ = BPF_JMP_IMM(BPF_JEQ, fullsock_reg, 0, jmp);	      \
10896 		if (si->dst_reg == si->src_reg)				      \
10897 			*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,	      \
10898 				      offsetof(struct bpf_sock_ops_kern,      \
10899 				      temp));				      \
10900 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10901 						struct bpf_sock_ops_kern, sk),\
10902 				      si->dst_reg, si->src_reg,		      \
10903 				      offsetof(struct bpf_sock_ops_kern, sk));\
10904 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,		      \
10905 						       OBJ_FIELD),	      \
10906 				      si->dst_reg, si->dst_reg,		      \
10907 				      offsetof(OBJ, OBJ_FIELD));	      \
10908 		if (si->dst_reg == si->src_reg)	{			      \
10909 			*insn++ = BPF_JMP_A(2);				      \
10910 			*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,	      \
10911 				      offsetof(struct bpf_sock_ops_kern,      \
10912 				      temp));				      \
10913 			*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);	      \
10914 		}							      \
10915 	} while (0)
10916 
10917 #define SOCK_OPS_GET_SK()							      \
10918 	do {								      \
10919 		int fullsock_reg = si->dst_reg, reg = BPF_REG_9, jmp = 1;     \
10920 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10921 			reg--;						      \
10922 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10923 			reg--;						      \
10924 		if (si->dst_reg == si->src_reg) {			      \
10925 			*insn++ = BPF_STX_MEM(BPF_DW, si->src_reg, reg,	      \
10926 					  offsetof(struct bpf_sock_ops_kern,  \
10927 					  temp));			      \
10928 			fullsock_reg = reg;				      \
10929 			jmp += 2;					      \
10930 		}							      \
10931 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10932 						struct bpf_sock_ops_kern,     \
10933 						is_fullsock),		      \
10934 				      fullsock_reg, si->src_reg,	      \
10935 				      offsetof(struct bpf_sock_ops_kern,      \
10936 					       is_fullsock));		      \
10937 		*insn++ = BPF_JMP_IMM(BPF_JEQ, fullsock_reg, 0, jmp);	      \
10938 		if (si->dst_reg == si->src_reg)				      \
10939 			*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,	      \
10940 				      offsetof(struct bpf_sock_ops_kern,      \
10941 				      temp));				      \
10942 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10943 						struct bpf_sock_ops_kern, sk),\
10944 				      si->dst_reg, si->src_reg,		      \
10945 				      offsetof(struct bpf_sock_ops_kern, sk));\
10946 		if (si->dst_reg == si->src_reg)	{			      \
10947 			*insn++ = BPF_JMP_A(2);				      \
10948 			*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,	      \
10949 				      offsetof(struct bpf_sock_ops_kern,      \
10950 				      temp));				      \
10951 			*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);	      \
10952 		}							      \
10953 	} while (0)
10954 
10955 #define SOCK_OPS_GET_TCP_SOCK_FIELD(FIELD) \
10956 		SOCK_OPS_GET_FIELD(FIELD, FIELD, struct tcp_sock)
10957 
10958 /* Helper macro for adding write access to tcp_sock or sock fields.
10959  * The macro is called with two registers, dst_reg which contains a pointer
10960  * to ctx (context) and src_reg which contains the value that should be
10961  * stored. However, we need an additional register since we cannot overwrite
10962  * dst_reg because it may be used later in the program.
10963  * Instead we "borrow" one of the other register. We first save its value
10964  * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
10965  * it at the end of the macro.
10966  */
10967 #define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)			      \
10968 	do {								      \
10969 		int reg = BPF_REG_9;					      \
10970 		BUILD_BUG_ON(sizeof_field(OBJ, OBJ_FIELD) >		      \
10971 			     sizeof_field(struct bpf_sock_ops, BPF_FIELD));   \
10972 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10973 			reg--;						      \
10974 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10975 			reg--;						      \
10976 		*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,		      \
10977 				      offsetof(struct bpf_sock_ops_kern,      \
10978 					       temp));			      \
10979 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10980 						struct bpf_sock_ops_kern,     \
10981 						is_locked_tcp_sock),	      \
10982 				      reg, si->dst_reg,			      \
10983 				      offsetof(struct bpf_sock_ops_kern,      \
10984 					       is_locked_tcp_sock));	      \
10985 		*insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);		      \
10986 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10987 						struct bpf_sock_ops_kern, sk),\
10988 				      reg, si->dst_reg,			      \
10989 				      offsetof(struct bpf_sock_ops_kern, sk));\
10990 		*insn++ = BPF_RAW_INSN(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD) |     \
10991 				       BPF_MEM | BPF_CLASS(si->code),	      \
10992 				       reg, si->src_reg,		      \
10993 				       offsetof(OBJ, OBJ_FIELD),	      \
10994 				       si->imm);			      \
10995 		*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,		      \
10996 				      offsetof(struct bpf_sock_ops_kern,      \
10997 					       temp));			      \
10998 	} while (0)
10999 
11000 #define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)	      \
11001 	do {								      \
11002 		if (TYPE == BPF_WRITE)					      \
11003 			SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);	      \
11004 		else							      \
11005 			SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);	      \
11006 	} while (0)
11007 
11008 	switch (si->off) {
11009 	case offsetof(struct bpf_sock_ops, op):
11010 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
11011 						       op),
11012 				      si->dst_reg, si->src_reg,
11013 				      offsetof(struct bpf_sock_ops_kern, op));
11014 		break;
11015 
11016 	case offsetof(struct bpf_sock_ops, replylong[0]) ...
11017 	     offsetof(struct bpf_sock_ops, replylong[3]):
11018 		BUILD_BUG_ON(sizeof_field(struct bpf_sock_ops, reply) !=
11019 			     sizeof_field(struct bpf_sock_ops_kern, reply));
11020 		BUILD_BUG_ON(sizeof_field(struct bpf_sock_ops, replylong) !=
11021 			     sizeof_field(struct bpf_sock_ops_kern, replylong));
11022 		off = si->off;
11023 		off -= offsetof(struct bpf_sock_ops, replylong[0]);
11024 		off += offsetof(struct bpf_sock_ops_kern, replylong[0]);
11025 		if (type == BPF_WRITE)
11026 			*insn++ = BPF_EMIT_STORE(BPF_W, si, off);
11027 		else
11028 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
11029 					      off);
11030 		break;
11031 
11032 	case offsetof(struct bpf_sock_ops, family):
11033 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
11034 
11035 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11036 					      struct bpf_sock_ops_kern, sk),
11037 				      si->dst_reg, si->src_reg,
11038 				      offsetof(struct bpf_sock_ops_kern, sk));
11039 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
11040 				      offsetof(struct sock_common, skc_family));
11041 		break;
11042 
11043 	case offsetof(struct bpf_sock_ops, remote_ip4):
11044 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
11045 
11046 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11047 						struct bpf_sock_ops_kern, sk),
11048 				      si->dst_reg, si->src_reg,
11049 				      offsetof(struct bpf_sock_ops_kern, sk));
11050 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
11051 				      offsetof(struct sock_common, skc_daddr));
11052 		break;
11053 
11054 	case offsetof(struct bpf_sock_ops, local_ip4):
11055 		BUILD_BUG_ON(sizeof_field(struct sock_common,
11056 					  skc_rcv_saddr) != 4);
11057 
11058 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11059 					      struct bpf_sock_ops_kern, sk),
11060 				      si->dst_reg, si->src_reg,
11061 				      offsetof(struct bpf_sock_ops_kern, sk));
11062 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
11063 				      offsetof(struct sock_common,
11064 					       skc_rcv_saddr));
11065 		break;
11066 
11067 	case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
11068 	     offsetof(struct bpf_sock_ops, remote_ip6[3]):
11069 #if IS_ENABLED(CONFIG_IPV6)
11070 		BUILD_BUG_ON(sizeof_field(struct sock_common,
11071 					  skc_v6_daddr.s6_addr32[0]) != 4);
11072 
11073 		off = si->off;
11074 		off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
11075 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11076 						struct bpf_sock_ops_kern, sk),
11077 				      si->dst_reg, si->src_reg,
11078 				      offsetof(struct bpf_sock_ops_kern, sk));
11079 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
11080 				      offsetof(struct sock_common,
11081 					       skc_v6_daddr.s6_addr32[0]) +
11082 				      off);
11083 #else
11084 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11085 #endif
11086 		break;
11087 
11088 	case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
11089 	     offsetof(struct bpf_sock_ops, local_ip6[3]):
11090 #if IS_ENABLED(CONFIG_IPV6)
11091 		BUILD_BUG_ON(sizeof_field(struct sock_common,
11092 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
11093 
11094 		off = si->off;
11095 		off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
11096 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11097 						struct bpf_sock_ops_kern, sk),
11098 				      si->dst_reg, si->src_reg,
11099 				      offsetof(struct bpf_sock_ops_kern, sk));
11100 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
11101 				      offsetof(struct sock_common,
11102 					       skc_v6_rcv_saddr.s6_addr32[0]) +
11103 				      off);
11104 #else
11105 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11106 #endif
11107 		break;
11108 
11109 	case offsetof(struct bpf_sock_ops, remote_port):
11110 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
11111 
11112 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11113 						struct bpf_sock_ops_kern, sk),
11114 				      si->dst_reg, si->src_reg,
11115 				      offsetof(struct bpf_sock_ops_kern, sk));
11116 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
11117 				      offsetof(struct sock_common, skc_dport));
11118 #ifndef __BIG_ENDIAN_BITFIELD
11119 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
11120 #endif
11121 		break;
11122 
11123 	case offsetof(struct bpf_sock_ops, local_port):
11124 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
11125 
11126 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11127 						struct bpf_sock_ops_kern, sk),
11128 				      si->dst_reg, si->src_reg,
11129 				      offsetof(struct bpf_sock_ops_kern, sk));
11130 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
11131 				      offsetof(struct sock_common, skc_num));
11132 		break;
11133 
11134 	case offsetof(struct bpf_sock_ops, is_fullsock):
11135 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11136 						struct bpf_sock_ops_kern,
11137 						is_fullsock),
11138 				      si->dst_reg, si->src_reg,
11139 				      offsetof(struct bpf_sock_ops_kern,
11140 					       is_fullsock));
11141 		break;
11142 
11143 	case offsetof(struct bpf_sock_ops, state):
11144 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_state) != 1);
11145 
11146 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11147 						struct bpf_sock_ops_kern, sk),
11148 				      si->dst_reg, si->src_reg,
11149 				      offsetof(struct bpf_sock_ops_kern, sk));
11150 		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
11151 				      offsetof(struct sock_common, skc_state));
11152 		break;
11153 
11154 	case offsetof(struct bpf_sock_ops, rtt_min):
11155 		SOCK_OPS_GET_FIELD(rtt_min, rtt_min.s[0].v, struct tcp_sock);
11156 		break;
11157 
11158 	case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
11159 		SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
11160 				   struct tcp_sock);
11161 		break;
11162 
11163 	case offsetof(struct bpf_sock_ops, sk_txhash):
11164 		SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
11165 					  struct sock, type);
11166 		break;
11167 	case offsetof(struct bpf_sock_ops, snd_cwnd):
11168 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_cwnd);
11169 		break;
11170 	case offsetof(struct bpf_sock_ops, srtt_us):
11171 		SOCK_OPS_GET_TCP_SOCK_FIELD(srtt_us);
11172 		break;
11173 	case offsetof(struct bpf_sock_ops, snd_ssthresh):
11174 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_ssthresh);
11175 		break;
11176 	case offsetof(struct bpf_sock_ops, rcv_nxt):
11177 		SOCK_OPS_GET_TCP_SOCK_FIELD(rcv_nxt);
11178 		break;
11179 	case offsetof(struct bpf_sock_ops, snd_nxt):
11180 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_nxt);
11181 		break;
11182 	case offsetof(struct bpf_sock_ops, snd_una):
11183 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_una);
11184 		break;
11185 	case offsetof(struct bpf_sock_ops, mss_cache):
11186 		SOCK_OPS_GET_TCP_SOCK_FIELD(mss_cache);
11187 		break;
11188 	case offsetof(struct bpf_sock_ops, ecn_flags):
11189 		SOCK_OPS_GET_TCP_SOCK_FIELD(ecn_flags);
11190 		break;
11191 	case offsetof(struct bpf_sock_ops, rate_delivered):
11192 		SOCK_OPS_GET_TCP_SOCK_FIELD(rate_delivered);
11193 		break;
11194 	case offsetof(struct bpf_sock_ops, rate_interval_us):
11195 		SOCK_OPS_GET_TCP_SOCK_FIELD(rate_interval_us);
11196 		break;
11197 	case offsetof(struct bpf_sock_ops, packets_out):
11198 		SOCK_OPS_GET_TCP_SOCK_FIELD(packets_out);
11199 		break;
11200 	case offsetof(struct bpf_sock_ops, retrans_out):
11201 		SOCK_OPS_GET_TCP_SOCK_FIELD(retrans_out);
11202 		break;
11203 	case offsetof(struct bpf_sock_ops, total_retrans):
11204 		SOCK_OPS_GET_TCP_SOCK_FIELD(total_retrans);
11205 		break;
11206 	case offsetof(struct bpf_sock_ops, segs_in):
11207 		SOCK_OPS_GET_TCP_SOCK_FIELD(segs_in);
11208 		break;
11209 	case offsetof(struct bpf_sock_ops, data_segs_in):
11210 		SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_in);
11211 		break;
11212 	case offsetof(struct bpf_sock_ops, segs_out):
11213 		SOCK_OPS_GET_TCP_SOCK_FIELD(segs_out);
11214 		break;
11215 	case offsetof(struct bpf_sock_ops, data_segs_out):
11216 		SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_out);
11217 		break;
11218 	case offsetof(struct bpf_sock_ops, lost_out):
11219 		SOCK_OPS_GET_TCP_SOCK_FIELD(lost_out);
11220 		break;
11221 	case offsetof(struct bpf_sock_ops, sacked_out):
11222 		SOCK_OPS_GET_TCP_SOCK_FIELD(sacked_out);
11223 		break;
11224 	case offsetof(struct bpf_sock_ops, bytes_received):
11225 		SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_received);
11226 		break;
11227 	case offsetof(struct bpf_sock_ops, bytes_acked):
11228 		SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_acked);
11229 		break;
11230 	case offsetof(struct bpf_sock_ops, sk):
11231 		SOCK_OPS_GET_SK();
11232 		break;
11233 	case offsetof(struct bpf_sock_ops, skb_data_end):
11234 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
11235 						       skb_data_end),
11236 				      si->dst_reg, si->src_reg,
11237 				      offsetof(struct bpf_sock_ops_kern,
11238 					       skb_data_end));
11239 		break;
11240 	case offsetof(struct bpf_sock_ops, skb_data):
11241 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
11242 						       skb),
11243 				      si->dst_reg, si->src_reg,
11244 				      offsetof(struct bpf_sock_ops_kern,
11245 					       skb));
11246 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
11247 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
11248 				      si->dst_reg, si->dst_reg,
11249 				      offsetof(struct sk_buff, data));
11250 		break;
11251 	case offsetof(struct bpf_sock_ops, skb_len):
11252 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
11253 						       skb),
11254 				      si->dst_reg, si->src_reg,
11255 				      offsetof(struct bpf_sock_ops_kern,
11256 					       skb));
11257 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
11258 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, len),
11259 				      si->dst_reg, si->dst_reg,
11260 				      offsetof(struct sk_buff, len));
11261 		break;
11262 	case offsetof(struct bpf_sock_ops, skb_tcp_flags):
11263 		off = offsetof(struct sk_buff, cb);
11264 		off += offsetof(struct tcp_skb_cb, tcp_flags);
11265 		*target_size = sizeof_field(struct tcp_skb_cb, tcp_flags);
11266 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
11267 						       skb),
11268 				      si->dst_reg, si->src_reg,
11269 				      offsetof(struct bpf_sock_ops_kern,
11270 					       skb));
11271 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
11272 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_skb_cb,
11273 						       tcp_flags),
11274 				      si->dst_reg, si->dst_reg, off);
11275 		break;
11276 	case offsetof(struct bpf_sock_ops, skb_hwtstamp): {
11277 		struct bpf_insn *jmp_on_null_skb;
11278 
11279 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
11280 						       skb),
11281 				      si->dst_reg, si->src_reg,
11282 				      offsetof(struct bpf_sock_ops_kern,
11283 					       skb));
11284 		/* Reserve one insn to test skb == NULL */
11285 		jmp_on_null_skb = insn++;
11286 		insn = bpf_convert_shinfo_access(si->dst_reg, si->dst_reg, insn);
11287 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
11288 				      bpf_target_off(struct skb_shared_info,
11289 						     hwtstamps, 8,
11290 						     target_size));
11291 		*jmp_on_null_skb = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0,
11292 					       insn - jmp_on_null_skb - 1);
11293 		break;
11294 	}
11295 	}
11296 	return insn - insn_buf;
11297 }
11298 
11299 /* data_end = skb->data + skb_headlen() */
11300 static struct bpf_insn *bpf_convert_data_end_access(const struct bpf_insn *si,
11301 						    struct bpf_insn *insn)
11302 {
11303 	int reg;
11304 	int temp_reg_off = offsetof(struct sk_buff, cb) +
11305 			   offsetof(struct sk_skb_cb, temp_reg);
11306 
11307 	if (si->src_reg == si->dst_reg) {
11308 		/* We need an extra register, choose and save a register. */
11309 		reg = BPF_REG_9;
11310 		if (si->src_reg == reg || si->dst_reg == reg)
11311 			reg--;
11312 		if (si->src_reg == reg || si->dst_reg == reg)
11313 			reg--;
11314 		*insn++ = BPF_STX_MEM(BPF_DW, si->src_reg, reg, temp_reg_off);
11315 	} else {
11316 		reg = si->dst_reg;
11317 	}
11318 
11319 	/* reg = skb->data */
11320 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
11321 			      reg, si->src_reg,
11322 			      offsetof(struct sk_buff, data));
11323 	/* AX = skb->len */
11324 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, len),
11325 			      BPF_REG_AX, si->src_reg,
11326 			      offsetof(struct sk_buff, len));
11327 	/* reg = skb->data + skb->len */
11328 	*insn++ = BPF_ALU64_REG(BPF_ADD, reg, BPF_REG_AX);
11329 	/* AX = skb->data_len */
11330 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data_len),
11331 			      BPF_REG_AX, si->src_reg,
11332 			      offsetof(struct sk_buff, data_len));
11333 
11334 	/* reg = skb->data + skb->len - skb->data_len */
11335 	*insn++ = BPF_ALU64_REG(BPF_SUB, reg, BPF_REG_AX);
11336 
11337 	if (si->src_reg == si->dst_reg) {
11338 		/* Restore the saved register */
11339 		*insn++ = BPF_MOV64_REG(BPF_REG_AX, si->src_reg);
11340 		*insn++ = BPF_MOV64_REG(si->dst_reg, reg);
11341 		*insn++ = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_AX, temp_reg_off);
11342 	}
11343 
11344 	return insn;
11345 }
11346 
11347 static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
11348 				     const struct bpf_insn *si,
11349 				     struct bpf_insn *insn_buf,
11350 				     struct bpf_prog *prog, u32 *target_size)
11351 {
11352 	struct bpf_insn *insn = insn_buf;
11353 	int off;
11354 
11355 	switch (si->off) {
11356 	case offsetof(struct __sk_buff, data_end):
11357 		insn = bpf_convert_data_end_access(si, insn);
11358 		break;
11359 	case offsetof(struct __sk_buff, cb[0]) ...
11360 	     offsetofend(struct __sk_buff, cb[4]) - 1:
11361 		BUILD_BUG_ON(sizeof_field(struct sk_skb_cb, data) < 20);
11362 		BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
11363 			      offsetof(struct sk_skb_cb, data)) %
11364 			     sizeof(__u64));
11365 
11366 		prog->cb_access = 1;
11367 		off  = si->off;
11368 		off -= offsetof(struct __sk_buff, cb[0]);
11369 		off += offsetof(struct sk_buff, cb);
11370 		off += offsetof(struct sk_skb_cb, data);
11371 		if (type == BPF_WRITE)
11372 			*insn++ = BPF_EMIT_STORE(BPF_SIZE(si->code), si, off);
11373 		else
11374 			*insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
11375 					      si->src_reg, off);
11376 		break;
11377 
11378 
11379 	default:
11380 		return bpf_convert_ctx_access(type, si, insn_buf, prog,
11381 					      target_size);
11382 	}
11383 
11384 	return insn - insn_buf;
11385 }
11386 
11387 static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
11388 				     const struct bpf_insn *si,
11389 				     struct bpf_insn *insn_buf,
11390 				     struct bpf_prog *prog, u32 *target_size)
11391 {
11392 	struct bpf_insn *insn = insn_buf;
11393 #if IS_ENABLED(CONFIG_IPV6)
11394 	int off;
11395 #endif
11396 
11397 	/* convert ctx uses the fact sg element is first in struct */
11398 	BUILD_BUG_ON(offsetof(struct sk_msg, sg) != 0);
11399 
11400 	switch (si->off) {
11401 	case offsetof(struct sk_msg_md, data):
11402 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data),
11403 				      si->dst_reg, si->src_reg,
11404 				      offsetof(struct sk_msg, data));
11405 		break;
11406 	case offsetof(struct sk_msg_md, data_end):
11407 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data_end),
11408 				      si->dst_reg, si->src_reg,
11409 				      offsetof(struct sk_msg, data_end));
11410 		break;
11411 	case offsetof(struct sk_msg_md, family):
11412 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
11413 
11414 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11415 					      struct sk_msg, sk),
11416 				      si->dst_reg, si->src_reg,
11417 				      offsetof(struct sk_msg, sk));
11418 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
11419 				      offsetof(struct sock_common, skc_family));
11420 		break;
11421 
11422 	case offsetof(struct sk_msg_md, remote_ip4):
11423 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
11424 
11425 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11426 						struct sk_msg, sk),
11427 				      si->dst_reg, si->src_reg,
11428 				      offsetof(struct sk_msg, sk));
11429 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
11430 				      offsetof(struct sock_common, skc_daddr));
11431 		break;
11432 
11433 	case offsetof(struct sk_msg_md, local_ip4):
11434 		BUILD_BUG_ON(sizeof_field(struct sock_common,
11435 					  skc_rcv_saddr) != 4);
11436 
11437 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11438 					      struct sk_msg, sk),
11439 				      si->dst_reg, si->src_reg,
11440 				      offsetof(struct sk_msg, sk));
11441 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
11442 				      offsetof(struct sock_common,
11443 					       skc_rcv_saddr));
11444 		break;
11445 
11446 	case offsetof(struct sk_msg_md, remote_ip6[0]) ...
11447 	     offsetof(struct sk_msg_md, remote_ip6[3]):
11448 #if IS_ENABLED(CONFIG_IPV6)
11449 		BUILD_BUG_ON(sizeof_field(struct sock_common,
11450 					  skc_v6_daddr.s6_addr32[0]) != 4);
11451 
11452 		off = si->off;
11453 		off -= offsetof(struct sk_msg_md, remote_ip6[0]);
11454 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11455 						struct sk_msg, sk),
11456 				      si->dst_reg, si->src_reg,
11457 				      offsetof(struct sk_msg, sk));
11458 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
11459 				      offsetof(struct sock_common,
11460 					       skc_v6_daddr.s6_addr32[0]) +
11461 				      off);
11462 #else
11463 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11464 #endif
11465 		break;
11466 
11467 	case offsetof(struct sk_msg_md, local_ip6[0]) ...
11468 	     offsetof(struct sk_msg_md, local_ip6[3]):
11469 #if IS_ENABLED(CONFIG_IPV6)
11470 		BUILD_BUG_ON(sizeof_field(struct sock_common,
11471 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
11472 
11473 		off = si->off;
11474 		off -= offsetof(struct sk_msg_md, local_ip6[0]);
11475 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11476 						struct sk_msg, sk),
11477 				      si->dst_reg, si->src_reg,
11478 				      offsetof(struct sk_msg, sk));
11479 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
11480 				      offsetof(struct sock_common,
11481 					       skc_v6_rcv_saddr.s6_addr32[0]) +
11482 				      off);
11483 #else
11484 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11485 #endif
11486 		break;
11487 
11488 	case offsetof(struct sk_msg_md, remote_port):
11489 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
11490 
11491 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11492 						struct sk_msg, sk),
11493 				      si->dst_reg, si->src_reg,
11494 				      offsetof(struct sk_msg, sk));
11495 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
11496 				      offsetof(struct sock_common, skc_dport));
11497 #ifndef __BIG_ENDIAN_BITFIELD
11498 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
11499 #endif
11500 		break;
11501 
11502 	case offsetof(struct sk_msg_md, local_port):
11503 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
11504 
11505 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11506 						struct sk_msg, sk),
11507 				      si->dst_reg, si->src_reg,
11508 				      offsetof(struct sk_msg, sk));
11509 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
11510 				      offsetof(struct sock_common, skc_num));
11511 		break;
11512 
11513 	case offsetof(struct sk_msg_md, size):
11514 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_sg, size),
11515 				      si->dst_reg, si->src_reg,
11516 				      offsetof(struct sk_msg_sg, size));
11517 		break;
11518 
11519 	case offsetof(struct sk_msg_md, sk):
11520 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, sk),
11521 				      si->dst_reg, si->src_reg,
11522 				      offsetof(struct sk_msg, sk));
11523 		break;
11524 	}
11525 
11526 	return insn - insn_buf;
11527 }
11528 
11529 const struct bpf_verifier_ops sk_filter_verifier_ops = {
11530 	.get_func_proto		= sk_filter_func_proto,
11531 	.is_valid_access	= sk_filter_is_valid_access,
11532 	.convert_ctx_access	= bpf_convert_ctx_access,
11533 	.gen_ld_abs		= bpf_gen_ld_abs,
11534 };
11535 
11536 const struct bpf_prog_ops sk_filter_prog_ops = {
11537 	.test_run		= bpf_prog_test_run_skb,
11538 };
11539 
11540 const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
11541 	.get_func_proto		= tc_cls_act_func_proto,
11542 	.is_valid_access	= tc_cls_act_is_valid_access,
11543 	.convert_ctx_access	= tc_cls_act_convert_ctx_access,
11544 	.gen_prologue		= tc_cls_act_prologue,
11545 	.gen_ld_abs		= bpf_gen_ld_abs,
11546 	.btf_struct_access	= tc_cls_act_btf_struct_access,
11547 };
11548 
11549 const struct bpf_prog_ops tc_cls_act_prog_ops = {
11550 	.test_run		= bpf_prog_test_run_skb,
11551 };
11552 
11553 const struct bpf_verifier_ops xdp_verifier_ops = {
11554 	.get_func_proto		= xdp_func_proto,
11555 	.is_valid_access	= xdp_is_valid_access,
11556 	.convert_ctx_access	= xdp_convert_ctx_access,
11557 	.gen_prologue		= bpf_noop_prologue,
11558 	.btf_struct_access	= xdp_btf_struct_access,
11559 };
11560 
11561 const struct bpf_prog_ops xdp_prog_ops = {
11562 	.test_run		= bpf_prog_test_run_xdp,
11563 };
11564 
11565 const struct bpf_verifier_ops cg_skb_verifier_ops = {
11566 	.get_func_proto		= cg_skb_func_proto,
11567 	.is_valid_access	= cg_skb_is_valid_access,
11568 	.convert_ctx_access	= bpf_convert_ctx_access,
11569 };
11570 
11571 const struct bpf_prog_ops cg_skb_prog_ops = {
11572 	.test_run		= bpf_prog_test_run_skb,
11573 };
11574 
11575 const struct bpf_verifier_ops lwt_in_verifier_ops = {
11576 	.get_func_proto		= lwt_in_func_proto,
11577 	.is_valid_access	= lwt_is_valid_access,
11578 	.convert_ctx_access	= bpf_convert_ctx_access,
11579 };
11580 
11581 const struct bpf_prog_ops lwt_in_prog_ops = {
11582 	.test_run		= bpf_prog_test_run_skb,
11583 };
11584 
11585 const struct bpf_verifier_ops lwt_out_verifier_ops = {
11586 	.get_func_proto		= lwt_out_func_proto,
11587 	.is_valid_access	= lwt_is_valid_access,
11588 	.convert_ctx_access	= bpf_convert_ctx_access,
11589 };
11590 
11591 const struct bpf_prog_ops lwt_out_prog_ops = {
11592 	.test_run		= bpf_prog_test_run_skb,
11593 };
11594 
11595 const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
11596 	.get_func_proto		= lwt_xmit_func_proto,
11597 	.is_valid_access	= lwt_is_valid_access,
11598 	.convert_ctx_access	= bpf_convert_ctx_access,
11599 	.gen_prologue		= tc_cls_act_prologue,
11600 };
11601 
11602 const struct bpf_prog_ops lwt_xmit_prog_ops = {
11603 	.test_run		= bpf_prog_test_run_skb,
11604 };
11605 
11606 const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
11607 	.get_func_proto		= lwt_seg6local_func_proto,
11608 	.is_valid_access	= lwt_is_valid_access,
11609 	.convert_ctx_access	= bpf_convert_ctx_access,
11610 };
11611 
11612 const struct bpf_prog_ops lwt_seg6local_prog_ops = {
11613 };
11614 
11615 const struct bpf_verifier_ops cg_sock_verifier_ops = {
11616 	.get_func_proto		= sock_filter_func_proto,
11617 	.is_valid_access	= sock_filter_is_valid_access,
11618 	.convert_ctx_access	= bpf_sock_convert_ctx_access,
11619 };
11620 
11621 const struct bpf_prog_ops cg_sock_prog_ops = {
11622 };
11623 
11624 const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
11625 	.get_func_proto		= sock_addr_func_proto,
11626 	.is_valid_access	= sock_addr_is_valid_access,
11627 	.convert_ctx_access	= sock_addr_convert_ctx_access,
11628 };
11629 
11630 const struct bpf_prog_ops cg_sock_addr_prog_ops = {
11631 };
11632 
11633 const struct bpf_verifier_ops sock_ops_verifier_ops = {
11634 	.get_func_proto		= sock_ops_func_proto,
11635 	.is_valid_access	= sock_ops_is_valid_access,
11636 	.convert_ctx_access	= sock_ops_convert_ctx_access,
11637 };
11638 
11639 const struct bpf_prog_ops sock_ops_prog_ops = {
11640 };
11641 
11642 const struct bpf_verifier_ops sk_skb_verifier_ops = {
11643 	.get_func_proto		= sk_skb_func_proto,
11644 	.is_valid_access	= sk_skb_is_valid_access,
11645 	.convert_ctx_access	= sk_skb_convert_ctx_access,
11646 	.gen_prologue		= sk_skb_prologue,
11647 };
11648 
11649 const struct bpf_prog_ops sk_skb_prog_ops = {
11650 };
11651 
11652 const struct bpf_verifier_ops sk_msg_verifier_ops = {
11653 	.get_func_proto		= sk_msg_func_proto,
11654 	.is_valid_access	= sk_msg_is_valid_access,
11655 	.convert_ctx_access	= sk_msg_convert_ctx_access,
11656 	.gen_prologue		= bpf_noop_prologue,
11657 };
11658 
11659 const struct bpf_prog_ops sk_msg_prog_ops = {
11660 };
11661 
11662 const struct bpf_verifier_ops flow_dissector_verifier_ops = {
11663 	.get_func_proto		= flow_dissector_func_proto,
11664 	.is_valid_access	= flow_dissector_is_valid_access,
11665 	.convert_ctx_access	= flow_dissector_convert_ctx_access,
11666 };
11667 
11668 const struct bpf_prog_ops flow_dissector_prog_ops = {
11669 	.test_run		= bpf_prog_test_run_flow_dissector,
11670 };
11671 
11672 int sk_detach_filter(struct sock *sk)
11673 {
11674 	int ret = -ENOENT;
11675 	struct sk_filter *filter;
11676 
11677 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
11678 		return -EPERM;
11679 
11680 	filter = rcu_dereference_protected(sk->sk_filter,
11681 					   lockdep_sock_is_held(sk));
11682 	if (filter) {
11683 		RCU_INIT_POINTER(sk->sk_filter, NULL);
11684 		sk_filter_uncharge(sk, filter);
11685 		ret = 0;
11686 	}
11687 
11688 	return ret;
11689 }
11690 EXPORT_SYMBOL_GPL(sk_detach_filter);
11691 
11692 int sk_get_filter(struct sock *sk, sockptr_t optval, unsigned int len)
11693 {
11694 	struct sock_fprog_kern *fprog;
11695 	struct sk_filter *filter;
11696 	int ret = 0;
11697 
11698 	sockopt_lock_sock(sk);
11699 	filter = rcu_dereference_protected(sk->sk_filter,
11700 					   lockdep_sock_is_held(sk));
11701 	if (!filter)
11702 		goto out;
11703 
11704 	/* We're copying the filter that has been originally attached,
11705 	 * so no conversion/decode needed anymore. eBPF programs that
11706 	 * have no original program cannot be dumped through this.
11707 	 */
11708 	ret = -EACCES;
11709 	fprog = filter->prog->orig_prog;
11710 	if (!fprog)
11711 		goto out;
11712 
11713 	ret = fprog->len;
11714 	if (!len)
11715 		/* User space only enquires number of filter blocks. */
11716 		goto out;
11717 
11718 	ret = -EINVAL;
11719 	if (len < fprog->len)
11720 		goto out;
11721 
11722 	ret = -EFAULT;
11723 	if (copy_to_sockptr(optval, fprog->filter, bpf_classic_proglen(fprog)))
11724 		goto out;
11725 
11726 	/* Instead of bytes, the API requests to return the number
11727 	 * of filter blocks.
11728 	 */
11729 	ret = fprog->len;
11730 out:
11731 	sockopt_release_sock(sk);
11732 	return ret;
11733 }
11734 
11735 #ifdef CONFIG_INET
11736 static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
11737 				    struct sock_reuseport *reuse,
11738 				    struct sock *sk, struct sk_buff *skb,
11739 				    struct sock *migrating_sk,
11740 				    u32 hash)
11741 {
11742 	reuse_kern->skb = skb;
11743 	reuse_kern->sk = sk;
11744 	reuse_kern->selected_sk = NULL;
11745 	reuse_kern->migrating_sk = migrating_sk;
11746 	reuse_kern->data_end = skb->data + skb_headlen(skb);
11747 	reuse_kern->hash = hash;
11748 	reuse_kern->reuseport_id = reuse->reuseport_id;
11749 	reuse_kern->bind_inany = reuse->bind_inany;
11750 }
11751 
11752 struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
11753 				  struct bpf_prog *prog, struct sk_buff *skb,
11754 				  struct sock *migrating_sk,
11755 				  u32 hash)
11756 {
11757 	struct sk_reuseport_kern reuse_kern;
11758 	enum sk_action action;
11759 
11760 	bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, migrating_sk, hash);
11761 	action = bpf_prog_run(prog, &reuse_kern);
11762 
11763 	if (action == SK_PASS)
11764 		return reuse_kern.selected_sk;
11765 	else
11766 		return ERR_PTR(-ECONNREFUSED);
11767 }
11768 
11769 BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
11770 	   struct bpf_map *, map, void *, key, u32, flags)
11771 {
11772 	bool is_sockarray = map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY;
11773 	struct sock_reuseport *reuse;
11774 	struct sock *selected_sk;
11775 	int err;
11776 
11777 	selected_sk = map->ops->map_lookup_elem(map, key);
11778 	if (!selected_sk)
11779 		return -ENOENT;
11780 
11781 	reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
11782 	if (!reuse) {
11783 		/* reuseport_array has only sk with non NULL sk_reuseport_cb.
11784 		 * The only (!reuse) case here is - the sk has already been
11785 		 * unhashed (e.g. by close()), so treat it as -ENOENT.
11786 		 *
11787 		 * Other maps (e.g. sock_map) do not provide this guarantee and
11788 		 * the sk may never be in the reuseport group to begin with.
11789 		 */
11790 		err = is_sockarray ? -ENOENT : -EINVAL;
11791 		goto error;
11792 	}
11793 
11794 	if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
11795 		struct sock *sk = reuse_kern->sk;
11796 
11797 		if (sk->sk_protocol != selected_sk->sk_protocol) {
11798 			err = -EPROTOTYPE;
11799 		} else if (sk->sk_family != selected_sk->sk_family) {
11800 			err = -EAFNOSUPPORT;
11801 		} else {
11802 			/* Catch all. Likely bound to a different sockaddr. */
11803 			err = -EBADFD;
11804 		}
11805 		goto error;
11806 	}
11807 
11808 	reuse_kern->selected_sk = selected_sk;
11809 
11810 	return 0;
11811 error:
11812 	/* Lookup in sock_map can return TCP ESTABLISHED sockets. */
11813 	if (sk_is_refcounted(selected_sk))
11814 		sock_put(selected_sk);
11815 
11816 	return err;
11817 }
11818 
11819 static const struct bpf_func_proto sk_select_reuseport_proto = {
11820 	.func           = sk_select_reuseport,
11821 	.gpl_only       = false,
11822 	.ret_type       = RET_INTEGER,
11823 	.arg1_type	= ARG_PTR_TO_CTX,
11824 	.arg2_type      = ARG_CONST_MAP_PTR,
11825 	.arg3_type      = ARG_PTR_TO_MAP_KEY,
11826 	.arg4_type	= ARG_ANYTHING,
11827 };
11828 
11829 BPF_CALL_4(sk_reuseport_load_bytes,
11830 	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
11831 	   void *, to, u32, len)
11832 {
11833 	return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
11834 }
11835 
11836 static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
11837 	.func		= sk_reuseport_load_bytes,
11838 	.gpl_only	= false,
11839 	.ret_type	= RET_INTEGER,
11840 	.arg1_type	= ARG_PTR_TO_CTX,
11841 	.arg2_type	= ARG_ANYTHING,
11842 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
11843 	.arg4_type	= ARG_MEM_SIZE,
11844 };
11845 
11846 BPF_CALL_5(sk_reuseport_load_bytes_relative,
11847 	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
11848 	   void *, to, u32, len, u32, start_header)
11849 {
11850 	return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
11851 					       len, start_header);
11852 }
11853 
11854 static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
11855 	.func		= sk_reuseport_load_bytes_relative,
11856 	.gpl_only	= false,
11857 	.ret_type	= RET_INTEGER,
11858 	.arg1_type	= ARG_PTR_TO_CTX,
11859 	.arg2_type	= ARG_ANYTHING,
11860 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
11861 	.arg4_type	= ARG_MEM_SIZE,
11862 	.arg5_type	= ARG_ANYTHING,
11863 };
11864 
11865 static const struct bpf_func_proto *
11866 sk_reuseport_func_proto(enum bpf_func_id func_id,
11867 			const struct bpf_prog *prog)
11868 {
11869 	switch (func_id) {
11870 	case BPF_FUNC_sk_select_reuseport:
11871 		return &sk_select_reuseport_proto;
11872 	case BPF_FUNC_skb_load_bytes:
11873 		return &sk_reuseport_load_bytes_proto;
11874 	case BPF_FUNC_skb_load_bytes_relative:
11875 		return &sk_reuseport_load_bytes_relative_proto;
11876 	case BPF_FUNC_get_socket_cookie:
11877 		return &bpf_get_socket_ptr_cookie_proto;
11878 	case BPF_FUNC_ktime_get_coarse_ns:
11879 		return &bpf_ktime_get_coarse_ns_proto;
11880 	default:
11881 		return bpf_base_func_proto(func_id, prog);
11882 	}
11883 }
11884 
11885 static bool
11886 sk_reuseport_is_valid_access(int off, int size,
11887 			     enum bpf_access_type type,
11888 			     const struct bpf_prog *prog,
11889 			     struct bpf_insn_access_aux *info)
11890 {
11891 	const u32 size_default = sizeof(__u32);
11892 
11893 	if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
11894 	    off % size || type != BPF_READ)
11895 		return false;
11896 
11897 	switch (off) {
11898 	case offsetof(struct sk_reuseport_md, data):
11899 		info->reg_type = PTR_TO_PACKET;
11900 		return size == sizeof(__u64);
11901 
11902 	case offsetof(struct sk_reuseport_md, data_end):
11903 		info->reg_type = PTR_TO_PACKET_END;
11904 		return size == sizeof(__u64);
11905 
11906 	case offsetof(struct sk_reuseport_md, hash):
11907 		return size == size_default;
11908 
11909 	case offsetof(struct sk_reuseport_md, sk):
11910 		info->reg_type = PTR_TO_SOCKET;
11911 		return size == sizeof(__u64);
11912 
11913 	case offsetof(struct sk_reuseport_md, migrating_sk):
11914 		info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
11915 		return size == sizeof(__u64);
11916 
11917 	/* Fields that allow narrowing */
11918 	case bpf_ctx_range(struct sk_reuseport_md, eth_protocol):
11919 		if (size < sizeof_field(struct sk_buff, protocol))
11920 			return false;
11921 		fallthrough;
11922 	case bpf_ctx_range(struct sk_reuseport_md, ip_protocol):
11923 	case bpf_ctx_range(struct sk_reuseport_md, bind_inany):
11924 	case bpf_ctx_range(struct sk_reuseport_md, len):
11925 		bpf_ctx_record_field_size(info, size_default);
11926 		return bpf_ctx_narrow_access_ok(off, size, size_default);
11927 
11928 	default:
11929 		return false;
11930 	}
11931 }
11932 
11933 #define SK_REUSEPORT_LOAD_FIELD(F) ({					\
11934 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
11935 			      si->dst_reg, si->src_reg,			\
11936 			      bpf_target_off(struct sk_reuseport_kern, F, \
11937 					     sizeof_field(struct sk_reuseport_kern, F), \
11938 					     target_size));		\
11939 	})
11940 
11941 #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)				\
11942 	SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,		\
11943 				    struct sk_buff,			\
11944 				    skb,				\
11945 				    SKB_FIELD)
11946 
11947 #define SK_REUSEPORT_LOAD_SK_FIELD(SK_FIELD)				\
11948 	SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,		\
11949 				    struct sock,			\
11950 				    sk,					\
11951 				    SK_FIELD)
11952 
11953 static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
11954 					   const struct bpf_insn *si,
11955 					   struct bpf_insn *insn_buf,
11956 					   struct bpf_prog *prog,
11957 					   u32 *target_size)
11958 {
11959 	struct bpf_insn *insn = insn_buf;
11960 
11961 	switch (si->off) {
11962 	case offsetof(struct sk_reuseport_md, data):
11963 		SK_REUSEPORT_LOAD_SKB_FIELD(data);
11964 		break;
11965 
11966 	case offsetof(struct sk_reuseport_md, len):
11967 		SK_REUSEPORT_LOAD_SKB_FIELD(len);
11968 		break;
11969 
11970 	case offsetof(struct sk_reuseport_md, eth_protocol):
11971 		SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
11972 		break;
11973 
11974 	case offsetof(struct sk_reuseport_md, ip_protocol):
11975 		SK_REUSEPORT_LOAD_SK_FIELD(sk_protocol);
11976 		break;
11977 
11978 	case offsetof(struct sk_reuseport_md, data_end):
11979 		SK_REUSEPORT_LOAD_FIELD(data_end);
11980 		break;
11981 
11982 	case offsetof(struct sk_reuseport_md, hash):
11983 		SK_REUSEPORT_LOAD_FIELD(hash);
11984 		break;
11985 
11986 	case offsetof(struct sk_reuseport_md, bind_inany):
11987 		SK_REUSEPORT_LOAD_FIELD(bind_inany);
11988 		break;
11989 
11990 	case offsetof(struct sk_reuseport_md, sk):
11991 		SK_REUSEPORT_LOAD_FIELD(sk);
11992 		break;
11993 
11994 	case offsetof(struct sk_reuseport_md, migrating_sk):
11995 		SK_REUSEPORT_LOAD_FIELD(migrating_sk);
11996 		break;
11997 	}
11998 
11999 	return insn - insn_buf;
12000 }
12001 
12002 const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
12003 	.get_func_proto		= sk_reuseport_func_proto,
12004 	.is_valid_access	= sk_reuseport_is_valid_access,
12005 	.convert_ctx_access	= sk_reuseport_convert_ctx_access,
12006 };
12007 
12008 const struct bpf_prog_ops sk_reuseport_prog_ops = {
12009 };
12010 
12011 DEFINE_STATIC_KEY_FALSE(bpf_sk_lookup_enabled);
12012 EXPORT_SYMBOL(bpf_sk_lookup_enabled);
12013 
12014 BPF_CALL_3(bpf_sk_lookup_assign, struct bpf_sk_lookup_kern *, ctx,
12015 	   struct sock *, sk, u64, flags)
12016 {
12017 	if (unlikely(flags & ~(BPF_SK_LOOKUP_F_REPLACE |
12018 			       BPF_SK_LOOKUP_F_NO_REUSEPORT)))
12019 		return -EINVAL;
12020 	if (unlikely(sk && sk_is_refcounted(sk)))
12021 		return -ESOCKTNOSUPPORT; /* reject non-RCU freed sockets */
12022 	if (unlikely(sk && sk_is_tcp(sk) && sk->sk_state != TCP_LISTEN))
12023 		return -ESOCKTNOSUPPORT; /* only accept TCP socket in LISTEN */
12024 	if (unlikely(sk && sk_is_udp(sk) && sk->sk_state != TCP_CLOSE))
12025 		return -ESOCKTNOSUPPORT; /* only accept UDP socket in CLOSE */
12026 
12027 	/* Check if socket is suitable for packet L3/L4 protocol */
12028 	if (sk && sk->sk_protocol != ctx->protocol)
12029 		return -EPROTOTYPE;
12030 	if (sk && sk->sk_family != ctx->family &&
12031 	    (sk->sk_family == AF_INET || ipv6_only_sock(sk)))
12032 		return -EAFNOSUPPORT;
12033 
12034 	if (ctx->selected_sk && !(flags & BPF_SK_LOOKUP_F_REPLACE))
12035 		return -EEXIST;
12036 
12037 	/* Select socket as lookup result */
12038 	ctx->selected_sk = sk;
12039 	ctx->no_reuseport = flags & BPF_SK_LOOKUP_F_NO_REUSEPORT;
12040 	return 0;
12041 }
12042 
12043 static const struct bpf_func_proto bpf_sk_lookup_assign_proto = {
12044 	.func		= bpf_sk_lookup_assign,
12045 	.gpl_only	= false,
12046 	.ret_type	= RET_INTEGER,
12047 	.arg1_type	= ARG_PTR_TO_CTX,
12048 	.arg2_type	= ARG_PTR_TO_SOCKET_OR_NULL,
12049 	.arg3_type	= ARG_ANYTHING,
12050 };
12051 
12052 static const struct bpf_func_proto *
12053 sk_lookup_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
12054 {
12055 	switch (func_id) {
12056 	case BPF_FUNC_perf_event_output:
12057 		return &bpf_event_output_data_proto;
12058 	case BPF_FUNC_sk_assign:
12059 		return &bpf_sk_lookup_assign_proto;
12060 	case BPF_FUNC_sk_release:
12061 		return &bpf_sk_release_proto;
12062 	default:
12063 		return bpf_sk_base_func_proto(func_id, prog);
12064 	}
12065 }
12066 
12067 static bool sk_lookup_is_valid_access(int off, int size,
12068 				      enum bpf_access_type type,
12069 				      const struct bpf_prog *prog,
12070 				      struct bpf_insn_access_aux *info)
12071 {
12072 	if (off < 0 || off >= sizeof(struct bpf_sk_lookup))
12073 		return false;
12074 	if (off % size != 0)
12075 		return false;
12076 	if (type != BPF_READ)
12077 		return false;
12078 
12079 	switch (off) {
12080 	case bpf_ctx_range_ptr(struct bpf_sk_lookup, sk):
12081 		info->reg_type = PTR_TO_SOCKET_OR_NULL;
12082 		return size == sizeof(__u64);
12083 
12084 	case bpf_ctx_range(struct bpf_sk_lookup, family):
12085 	case bpf_ctx_range(struct bpf_sk_lookup, protocol):
12086 	case bpf_ctx_range(struct bpf_sk_lookup, remote_ip4):
12087 	case bpf_ctx_range(struct bpf_sk_lookup, local_ip4):
12088 	case bpf_ctx_range_till(struct bpf_sk_lookup, remote_ip6[0], remote_ip6[3]):
12089 	case bpf_ctx_range_till(struct bpf_sk_lookup, local_ip6[0], local_ip6[3]):
12090 	case bpf_ctx_range(struct bpf_sk_lookup, local_port):
12091 	case bpf_ctx_range(struct bpf_sk_lookup, ingress_ifindex):
12092 		bpf_ctx_record_field_size(info, sizeof(__u32));
12093 		return bpf_ctx_narrow_access_ok(off, size, sizeof(__u32));
12094 
12095 	case bpf_ctx_range(struct bpf_sk_lookup, remote_port):
12096 		/* Allow 4-byte access to 2-byte field for backward compatibility */
12097 		if (size == sizeof(__u32))
12098 			return true;
12099 		bpf_ctx_record_field_size(info, sizeof(__be16));
12100 		return bpf_ctx_narrow_access_ok(off, size, sizeof(__be16));
12101 
12102 	case offsetofend(struct bpf_sk_lookup, remote_port) ...
12103 	     offsetof(struct bpf_sk_lookup, local_ip4) - 1:
12104 		/* Allow access to zero padding for backward compatibility */
12105 		bpf_ctx_record_field_size(info, sizeof(__u16));
12106 		return bpf_ctx_narrow_access_ok(off, size, sizeof(__u16));
12107 
12108 	default:
12109 		return false;
12110 	}
12111 }
12112 
12113 static u32 sk_lookup_convert_ctx_access(enum bpf_access_type type,
12114 					const struct bpf_insn *si,
12115 					struct bpf_insn *insn_buf,
12116 					struct bpf_prog *prog,
12117 					u32 *target_size)
12118 {
12119 	struct bpf_insn *insn = insn_buf;
12120 
12121 	switch (si->off) {
12122 	case offsetof(struct bpf_sk_lookup, sk):
12123 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
12124 				      offsetof(struct bpf_sk_lookup_kern, selected_sk));
12125 		break;
12126 
12127 	case offsetof(struct bpf_sk_lookup, family):
12128 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
12129 				      bpf_target_off(struct bpf_sk_lookup_kern,
12130 						     family, 2, target_size));
12131 		break;
12132 
12133 	case offsetof(struct bpf_sk_lookup, protocol):
12134 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
12135 				      bpf_target_off(struct bpf_sk_lookup_kern,
12136 						     protocol, 2, target_size));
12137 		break;
12138 
12139 	case offsetof(struct bpf_sk_lookup, remote_ip4):
12140 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
12141 				      bpf_target_off(struct bpf_sk_lookup_kern,
12142 						     v4.saddr, 4, target_size));
12143 		break;
12144 
12145 	case offsetof(struct bpf_sk_lookup, local_ip4):
12146 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
12147 				      bpf_target_off(struct bpf_sk_lookup_kern,
12148 						     v4.daddr, 4, target_size));
12149 		break;
12150 
12151 	case bpf_ctx_range_till(struct bpf_sk_lookup,
12152 				remote_ip6[0], remote_ip6[3]): {
12153 #if IS_ENABLED(CONFIG_IPV6)
12154 		int off = si->off;
12155 
12156 		off -= offsetof(struct bpf_sk_lookup, remote_ip6[0]);
12157 		off += bpf_target_off(struct in6_addr, s6_addr32[0], 4, target_size);
12158 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
12159 				      offsetof(struct bpf_sk_lookup_kern, v6.saddr));
12160 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
12161 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, off);
12162 #else
12163 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
12164 #endif
12165 		break;
12166 	}
12167 	case bpf_ctx_range_till(struct bpf_sk_lookup,
12168 				local_ip6[0], local_ip6[3]): {
12169 #if IS_ENABLED(CONFIG_IPV6)
12170 		int off = si->off;
12171 
12172 		off -= offsetof(struct bpf_sk_lookup, local_ip6[0]);
12173 		off += bpf_target_off(struct in6_addr, s6_addr32[0], 4, target_size);
12174 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
12175 				      offsetof(struct bpf_sk_lookup_kern, v6.daddr));
12176 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
12177 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, off);
12178 #else
12179 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
12180 #endif
12181 		break;
12182 	}
12183 	case offsetof(struct bpf_sk_lookup, remote_port):
12184 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
12185 				      bpf_target_off(struct bpf_sk_lookup_kern,
12186 						     sport, 2, target_size));
12187 		break;
12188 
12189 	case offsetofend(struct bpf_sk_lookup, remote_port):
12190 		*target_size = 2;
12191 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
12192 		break;
12193 
12194 	case offsetof(struct bpf_sk_lookup, local_port):
12195 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
12196 				      bpf_target_off(struct bpf_sk_lookup_kern,
12197 						     dport, 2, target_size));
12198 		break;
12199 
12200 	case offsetof(struct bpf_sk_lookup, ingress_ifindex):
12201 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
12202 				      bpf_target_off(struct bpf_sk_lookup_kern,
12203 						     ingress_ifindex, 4, target_size));
12204 		break;
12205 	}
12206 
12207 	return insn - insn_buf;
12208 }
12209 
12210 const struct bpf_prog_ops sk_lookup_prog_ops = {
12211 	.test_run = bpf_prog_test_run_sk_lookup,
12212 };
12213 
12214 const struct bpf_verifier_ops sk_lookup_verifier_ops = {
12215 	.get_func_proto		= sk_lookup_func_proto,
12216 	.is_valid_access	= sk_lookup_is_valid_access,
12217 	.convert_ctx_access	= sk_lookup_convert_ctx_access,
12218 };
12219 
12220 #endif /* CONFIG_INET */
12221 
12222 DEFINE_BPF_DISPATCHER(xdp)
12223 
12224 void bpf_prog_change_xdp(struct bpf_prog *prev_prog, struct bpf_prog *prog)
12225 {
12226 	bpf_dispatcher_change_prog(BPF_DISPATCHER_PTR(xdp), prev_prog, prog);
12227 }
12228 
12229 BTF_ID_LIST_GLOBAL(btf_sock_ids, MAX_BTF_SOCK_TYPE)
12230 #define BTF_SOCK_TYPE(name, type) BTF_ID(struct, type)
12231 BTF_SOCK_TYPE_xxx
12232 #undef BTF_SOCK_TYPE
12233 
12234 BPF_CALL_1(bpf_skc_to_tcp6_sock, struct sock *, sk)
12235 {
12236 	/* tcp6_sock type is not generated in dwarf and hence btf,
12237 	 * trigger an explicit type generation here.
12238 	 */
12239 	BTF_TYPE_EMIT(struct tcp6_sock);
12240 	if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP &&
12241 	    sk->sk_type == SOCK_STREAM && sk->sk_family == AF_INET6)
12242 		return (unsigned long)sk;
12243 
12244 	return (unsigned long)NULL;
12245 }
12246 
12247 const struct bpf_func_proto bpf_skc_to_tcp6_sock_proto = {
12248 	.func			= bpf_skc_to_tcp6_sock,
12249 	.gpl_only		= false,
12250 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
12251 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
12252 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP6],
12253 };
12254 
12255 BPF_CALL_1(bpf_skc_to_tcp_sock, struct sock *, sk)
12256 {
12257 	if (sk && sk_fullsock(sk) && sk_is_tcp(sk))
12258 		return (unsigned long)sk;
12259 
12260 	return (unsigned long)NULL;
12261 }
12262 
12263 const struct bpf_func_proto bpf_skc_to_tcp_sock_proto = {
12264 	.func			= bpf_skc_to_tcp_sock,
12265 	.gpl_only		= false,
12266 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
12267 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
12268 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP],
12269 };
12270 
12271 BPF_CALL_1(bpf_skc_to_tcp_timewait_sock, struct sock *, sk)
12272 {
12273 	/* BTF types for tcp_timewait_sock and inet_timewait_sock are not
12274 	 * generated if CONFIG_INET=n. Trigger an explicit generation here.
12275 	 */
12276 	BTF_TYPE_EMIT(struct inet_timewait_sock);
12277 	BTF_TYPE_EMIT(struct tcp_timewait_sock);
12278 
12279 #ifdef CONFIG_INET
12280 	if (sk && sk->sk_prot == &tcp_prot && sk->sk_state == TCP_TIME_WAIT)
12281 		return (unsigned long)sk;
12282 #endif
12283 
12284 #if IS_ENABLED(CONFIG_IPV6)
12285 	if (sk && sk->sk_prot == &tcpv6_prot && sk->sk_state == TCP_TIME_WAIT)
12286 		return (unsigned long)sk;
12287 #endif
12288 
12289 	return (unsigned long)NULL;
12290 }
12291 
12292 const struct bpf_func_proto bpf_skc_to_tcp_timewait_sock_proto = {
12293 	.func			= bpf_skc_to_tcp_timewait_sock,
12294 	.gpl_only		= false,
12295 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
12296 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
12297 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP_TW],
12298 };
12299 
12300 BPF_CALL_1(bpf_skc_to_tcp_request_sock, struct sock *, sk)
12301 {
12302 #ifdef CONFIG_INET
12303 	if (sk && sk->sk_prot == &tcp_prot && sk->sk_state == TCP_NEW_SYN_RECV)
12304 		return (unsigned long)sk;
12305 #endif
12306 
12307 #if IS_ENABLED(CONFIG_IPV6)
12308 	if (sk && sk->sk_prot == &tcpv6_prot && sk->sk_state == TCP_NEW_SYN_RECV)
12309 		return (unsigned long)sk;
12310 #endif
12311 
12312 	return (unsigned long)NULL;
12313 }
12314 
12315 const struct bpf_func_proto bpf_skc_to_tcp_request_sock_proto = {
12316 	.func			= bpf_skc_to_tcp_request_sock,
12317 	.gpl_only		= false,
12318 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
12319 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
12320 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP_REQ],
12321 };
12322 
12323 BPF_CALL_1(bpf_skc_to_udp6_sock, struct sock *, sk)
12324 {
12325 	/* udp6_sock type is not generated in dwarf and hence btf,
12326 	 * trigger an explicit type generation here.
12327 	 */
12328 	BTF_TYPE_EMIT(struct udp6_sock);
12329 	if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_UDP &&
12330 	    sk->sk_type == SOCK_DGRAM && sk->sk_family == AF_INET6)
12331 		return (unsigned long)sk;
12332 
12333 	return (unsigned long)NULL;
12334 }
12335 
12336 const struct bpf_func_proto bpf_skc_to_udp6_sock_proto = {
12337 	.func			= bpf_skc_to_udp6_sock,
12338 	.gpl_only		= false,
12339 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
12340 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
12341 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_UDP6],
12342 };
12343 
12344 BPF_CALL_1(bpf_skc_to_unix_sock, struct sock *, sk)
12345 {
12346 	/* unix_sock type is not generated in dwarf and hence btf,
12347 	 * trigger an explicit type generation here.
12348 	 */
12349 	BTF_TYPE_EMIT(struct unix_sock);
12350 	if (sk && sk_is_unix(sk))
12351 		return (unsigned long)sk;
12352 
12353 	return (unsigned long)NULL;
12354 }
12355 
12356 const struct bpf_func_proto bpf_skc_to_unix_sock_proto = {
12357 	.func			= bpf_skc_to_unix_sock,
12358 	.gpl_only		= false,
12359 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
12360 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
12361 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_UNIX],
12362 };
12363 
12364 BPF_CALL_1(bpf_skc_to_mptcp_sock, struct sock *, sk)
12365 {
12366 	BTF_TYPE_EMIT(struct mptcp_sock);
12367 	return (unsigned long)bpf_mptcp_sock_from_subflow(sk);
12368 }
12369 
12370 const struct bpf_func_proto bpf_skc_to_mptcp_sock_proto = {
12371 	.func		= bpf_skc_to_mptcp_sock,
12372 	.gpl_only	= false,
12373 	.ret_type	= RET_PTR_TO_BTF_ID_OR_NULL,
12374 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
12375 	.ret_btf_id	= &btf_sock_ids[BTF_SOCK_TYPE_MPTCP],
12376 };
12377 
12378 BPF_CALL_1(bpf_sock_from_file, struct file *, file)
12379 {
12380 	return (unsigned long)sock_from_file(file);
12381 }
12382 
12383 BTF_ID_LIST(bpf_sock_from_file_btf_ids)
12384 BTF_ID(struct, socket)
12385 BTF_ID(struct, file)
12386 
12387 const struct bpf_func_proto bpf_sock_from_file_proto = {
12388 	.func		= bpf_sock_from_file,
12389 	.gpl_only	= false,
12390 	.ret_type	= RET_PTR_TO_BTF_ID_OR_NULL,
12391 	.ret_btf_id	= &bpf_sock_from_file_btf_ids[0],
12392 	.arg1_type	= ARG_PTR_TO_BTF_ID,
12393 	.arg1_btf_id	= &bpf_sock_from_file_btf_ids[1],
12394 };
12395 
12396 static const struct bpf_func_proto *
12397 bpf_sk_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
12398 {
12399 	const struct bpf_func_proto *func;
12400 
12401 	switch (func_id) {
12402 	case BPF_FUNC_skc_to_tcp6_sock:
12403 		func = &bpf_skc_to_tcp6_sock_proto;
12404 		break;
12405 	case BPF_FUNC_skc_to_tcp_sock:
12406 		func = &bpf_skc_to_tcp_sock_proto;
12407 		break;
12408 	case BPF_FUNC_skc_to_tcp_timewait_sock:
12409 		func = &bpf_skc_to_tcp_timewait_sock_proto;
12410 		break;
12411 	case BPF_FUNC_skc_to_tcp_request_sock:
12412 		func = &bpf_skc_to_tcp_request_sock_proto;
12413 		break;
12414 	case BPF_FUNC_skc_to_udp6_sock:
12415 		func = &bpf_skc_to_udp6_sock_proto;
12416 		break;
12417 	case BPF_FUNC_skc_to_unix_sock:
12418 		func = &bpf_skc_to_unix_sock_proto;
12419 		break;
12420 	case BPF_FUNC_skc_to_mptcp_sock:
12421 		func = &bpf_skc_to_mptcp_sock_proto;
12422 		break;
12423 	case BPF_FUNC_ktime_get_coarse_ns:
12424 		return &bpf_ktime_get_coarse_ns_proto;
12425 	default:
12426 		return bpf_base_func_proto(func_id, prog);
12427 	}
12428 
12429 	if (!bpf_token_capable(prog->aux->token, CAP_PERFMON))
12430 		return NULL;
12431 
12432 	return func;
12433 }
12434 
12435 /**
12436  * bpf_skb_meta_pointer() - Gets a mutable pointer within the skb metadata area.
12437  * @skb: socket buffer carrying the metadata
12438  * @offset: offset into the metadata area, must be <= skb_metadata_len()
12439  */
12440 void *bpf_skb_meta_pointer(struct sk_buff *skb, u32 offset)
12441 {
12442 	return skb_metadata_end(skb) - skb_metadata_len(skb) + offset;
12443 }
12444 
12445 int __bpf_skb_meta_store_bytes(struct sk_buff *skb, u32 offset,
12446 			       const void *from, u32 len, u64 flags)
12447 {
12448 	if (unlikely(flags))
12449 		return -EINVAL;
12450 	if (unlikely(bpf_try_make_writable_from(skb, 0, &from)))
12451 		return -EFAULT;
12452 
12453 	memmove(bpf_skb_meta_pointer(skb, offset), from, len);
12454 	return 0;
12455 }
12456 
12457 __bpf_kfunc_start_defs();
12458 __bpf_kfunc int bpf_dynptr_from_skb(struct __sk_buff *s, u64 flags,
12459 				    struct bpf_dynptr *ptr__uninit)
12460 {
12461 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)ptr__uninit;
12462 	struct sk_buff *skb = (struct sk_buff *)s;
12463 
12464 	if (flags) {
12465 		bpf_dynptr_set_null(ptr);
12466 		return -EINVAL;
12467 	}
12468 
12469 	bpf_dynptr_init(ptr, skb, BPF_DYNPTR_TYPE_SKB, 0, skb->len);
12470 
12471 	return 0;
12472 }
12473 
12474 /**
12475  * bpf_dynptr_from_skb_meta() - Initialize a dynptr to the skb metadata area.
12476  * @skb_: socket buffer carrying the metadata
12477  * @flags: future use, must be zero
12478  * @ptr__uninit: dynptr to initialize
12479  *
12480  * Set up a dynptr for access to the metadata area earlier allocated from the
12481  * XDP context with bpf_xdp_adjust_meta(). Serves as an alternative to
12482  * &__sk_buff->data_meta.
12483  *
12484  * Return:
12485  * * %0         - dynptr ready to use
12486  * * %-EINVAL   - invalid flags, dynptr set to null
12487  */
12488 __bpf_kfunc int bpf_dynptr_from_skb_meta(struct __sk_buff *skb_, u64 flags,
12489 					 struct bpf_dynptr *ptr__uninit)
12490 {
12491 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)ptr__uninit;
12492 	struct sk_buff *skb = (struct sk_buff *)skb_;
12493 
12494 	if (flags) {
12495 		bpf_dynptr_set_null(ptr);
12496 		return -EINVAL;
12497 	}
12498 
12499 	bpf_dynptr_init(ptr, skb, BPF_DYNPTR_TYPE_SKB_META, 0, skb_metadata_len(skb));
12500 
12501 	return 0;
12502 }
12503 
12504 __bpf_kfunc int bpf_dynptr_from_xdp(struct xdp_md *x, u64 flags,
12505 				    struct bpf_dynptr *ptr__uninit)
12506 {
12507 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)ptr__uninit;
12508 	struct xdp_buff *xdp = (struct xdp_buff *)x;
12509 
12510 	if (flags) {
12511 		bpf_dynptr_set_null(ptr);
12512 		return -EINVAL;
12513 	}
12514 
12515 	bpf_dynptr_init(ptr, xdp, BPF_DYNPTR_TYPE_XDP, 0, xdp_get_buff_len(xdp));
12516 
12517 	return 0;
12518 }
12519 
12520 __bpf_kfunc int bpf_sock_addr_set_sun_path(struct bpf_sock_addr_kern *sa_kern,
12521 					   const u8 *sun_path, u32 sun_path__sz)
12522 {
12523 	struct sockaddr_un *un;
12524 
12525 	if (sa_kern->sk->sk_family != AF_UNIX)
12526 		return -EINVAL;
12527 
12528 	/* We do not allow changing the address to unnamed or larger than the
12529 	 * maximum allowed address size for a unix sockaddr.
12530 	 */
12531 	if (sun_path__sz == 0 || sun_path__sz > UNIX_PATH_MAX)
12532 		return -EINVAL;
12533 
12534 	un = (struct sockaddr_un *)sa_kern->uaddr;
12535 	memcpy(un->sun_path, sun_path, sun_path__sz);
12536 	sa_kern->uaddrlen = offsetof(struct sockaddr_un, sun_path) + sun_path__sz;
12537 
12538 	return 0;
12539 }
12540 
12541 __bpf_kfunc int bpf_sk_assign_tcp_reqsk(struct __sk_buff *s, struct sock *sk,
12542 					struct bpf_tcp_req_attrs *attrs, int attrs__sz)
12543 {
12544 #if IS_ENABLED(CONFIG_SYN_COOKIES)
12545 	struct sk_buff *skb = (struct sk_buff *)s;
12546 	const struct request_sock_ops *ops;
12547 	struct inet_request_sock *ireq;
12548 	struct tcp_request_sock *treq;
12549 	struct request_sock *req;
12550 	struct net *net;
12551 	__u16 min_mss;
12552 	u32 tsoff = 0;
12553 
12554 	if (attrs__sz != sizeof(*attrs) ||
12555 	    attrs->reserved[0] || attrs->reserved[1] || attrs->reserved[2])
12556 		return -EINVAL;
12557 
12558 	if (!skb_at_tc_ingress(skb))
12559 		return -EINVAL;
12560 
12561 	net = dev_net(skb->dev);
12562 	if (net != sock_net(sk))
12563 		return -ENETUNREACH;
12564 
12565 	switch (skb->protocol) {
12566 	case htons(ETH_P_IP):
12567 		ops = &tcp_request_sock_ops;
12568 		min_mss = 536;
12569 		break;
12570 #if IS_ENABLED(CONFIG_IPV6)
12571 	case htons(ETH_P_IPV6):
12572 		ops = &tcp6_request_sock_ops;
12573 		min_mss = IPV6_MIN_MTU - 60;
12574 		break;
12575 #endif
12576 	default:
12577 		return -EINVAL;
12578 	}
12579 
12580 	if (sk->sk_type != SOCK_STREAM || sk->sk_state != TCP_LISTEN ||
12581 	    sk_is_mptcp(sk))
12582 		return -EINVAL;
12583 
12584 	if (attrs->mss < min_mss)
12585 		return -EINVAL;
12586 
12587 	if (attrs->wscale_ok) {
12588 		if (!READ_ONCE(net->ipv4.sysctl_tcp_window_scaling))
12589 			return -EINVAL;
12590 
12591 		if (attrs->snd_wscale > TCP_MAX_WSCALE ||
12592 		    attrs->rcv_wscale > TCP_MAX_WSCALE)
12593 			return -EINVAL;
12594 	}
12595 
12596 	if (attrs->sack_ok && !READ_ONCE(net->ipv4.sysctl_tcp_sack))
12597 		return -EINVAL;
12598 
12599 	if (attrs->tstamp_ok) {
12600 		if (!READ_ONCE(net->ipv4.sysctl_tcp_timestamps))
12601 			return -EINVAL;
12602 
12603 		tsoff = attrs->rcv_tsecr - tcp_ns_to_ts(attrs->usec_ts_ok, tcp_clock_ns());
12604 	}
12605 
12606 	req = inet_reqsk_alloc(ops, sk, false);
12607 	if (!req)
12608 		return -ENOMEM;
12609 
12610 	ireq = inet_rsk(req);
12611 	treq = tcp_rsk(req);
12612 
12613 	req->rsk_listener = sk;
12614 	req->syncookie = 1;
12615 	req->mss = attrs->mss;
12616 	req->ts_recent = attrs->rcv_tsval;
12617 
12618 	ireq->snd_wscale = attrs->snd_wscale;
12619 	ireq->rcv_wscale = attrs->rcv_wscale;
12620 	ireq->tstamp_ok	= !!attrs->tstamp_ok;
12621 	ireq->sack_ok = !!attrs->sack_ok;
12622 	ireq->wscale_ok = !!attrs->wscale_ok;
12623 	ireq->ecn_ok = !!attrs->ecn_ok;
12624 
12625 	treq->req_usec_ts = !!attrs->usec_ts_ok;
12626 	treq->ts_off = tsoff;
12627 
12628 	skb_orphan(skb);
12629 	skb->sk = req_to_sk(req);
12630 	skb->destructor = sock_pfree;
12631 
12632 	return 0;
12633 #else
12634 	return -EOPNOTSUPP;
12635 #endif
12636 }
12637 
12638 __bpf_kfunc int bpf_sock_ops_enable_tx_tstamp(struct bpf_sock_ops_kern *skops,
12639 					      u64 flags)
12640 {
12641 	struct sk_buff *skb;
12642 
12643 	if (skops->op != BPF_SOCK_OPS_TSTAMP_SENDMSG_CB)
12644 		return -EOPNOTSUPP;
12645 
12646 	if (flags)
12647 		return -EINVAL;
12648 
12649 	skb = skops->skb;
12650 	skb_shinfo(skb)->tx_flags |= SKBTX_BPF;
12651 	TCP_SKB_CB(skb)->txstamp_ack |= TSTAMP_ACK_BPF;
12652 	skb_shinfo(skb)->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1;
12653 
12654 	return 0;
12655 }
12656 
12657 /**
12658  * bpf_xdp_pull_data() - Pull in non-linear xdp data.
12659  * @x: &xdp_md associated with the XDP buffer
12660  * @len: length of data to be made directly accessible in the linear part
12661  *
12662  * Pull in data in case the XDP buffer associated with @x is non-linear and
12663  * not all @len are in the linear data area.
12664  *
12665  * Direct packet access allows reading and writing linear XDP data through
12666  * packet pointers (i.e., &xdp_md->data + offsets). The amount of data which
12667  * ends up in the linear part of the xdp_buff depends on the NIC and its
12668  * configuration. When a frag-capable XDP program wants to directly access
12669  * headers that may be in the non-linear area, call this kfunc to make sure
12670  * the data is available in the linear area. Alternatively, use dynptr or
12671  * bpf_xdp_{load,store}_bytes() to access data without pulling.
12672  *
12673  * This kfunc can also be used with bpf_xdp_adjust_head() to decapsulate
12674  * headers in the non-linear data area.
12675  *
12676  * A call to this kfunc may reduce headroom. If there is not enough tailroom
12677  * in the linear data area, metadata and data will be shifted down.
12678  *
12679  * A call to this kfunc is susceptible to change the buffer geometry.
12680  * Therefore, at load time, all checks on pointers previously done by the
12681  * verifier are invalidated and must be performed again, if the kfunc is used
12682  * in combination with direct packet access.
12683  *
12684  * Return:
12685  * * %0         - success
12686  * * %-EINVAL   - invalid len
12687  */
12688 __bpf_kfunc int bpf_xdp_pull_data(struct xdp_md *x, u32 len)
12689 {
12690 	struct xdp_buff *xdp = (struct xdp_buff *)x;
12691 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
12692 	int i, delta, shift, headroom, tailroom, n_frags_free = 0;
12693 	void *data_hard_end = xdp_data_hard_end(xdp);
12694 	int data_len = xdp->data_end - xdp->data;
12695 	void *start;
12696 
12697 	if (len <= data_len)
12698 		return 0;
12699 
12700 	if (unlikely(len > xdp_get_buff_len(xdp)))
12701 		return -EINVAL;
12702 
12703 	start = xdp_data_meta_unsupported(xdp) ? xdp->data : xdp->data_meta;
12704 
12705 	headroom = start - xdp->data_hard_start - sizeof(struct xdp_frame);
12706 	tailroom = data_hard_end - xdp->data_end;
12707 
12708 	delta = len - data_len;
12709 	if (unlikely(delta > tailroom + headroom))
12710 		return -EINVAL;
12711 
12712 	shift = delta - tailroom;
12713 	if (shift > 0) {
12714 		memmove(start - shift, start, xdp->data_end - start);
12715 
12716 		xdp->data_meta -= shift;
12717 		xdp->data -= shift;
12718 		xdp->data_end -= shift;
12719 	}
12720 
12721 	for (i = 0; i < sinfo->nr_frags && delta; i++) {
12722 		skb_frag_t *frag = &sinfo->frags[i];
12723 		u32 shrink = min_t(u32, delta, skb_frag_size(frag));
12724 
12725 		memcpy(xdp->data_end, skb_frag_address(frag), shrink);
12726 
12727 		xdp->data_end += shrink;
12728 		sinfo->xdp_frags_size -= shrink;
12729 		delta -= shrink;
12730 		if (bpf_xdp_shrink_data(xdp, frag, shrink, false))
12731 			n_frags_free++;
12732 	}
12733 
12734 	if (unlikely(n_frags_free)) {
12735 		memmove(sinfo->frags, sinfo->frags + n_frags_free,
12736 			(sinfo->nr_frags - n_frags_free) * sizeof(skb_frag_t));
12737 
12738 		sinfo->nr_frags -= n_frags_free;
12739 
12740 		if (!sinfo->nr_frags) {
12741 			xdp_buff_clear_frags_flag(xdp);
12742 			xdp_buff_clear_frag_pfmemalloc(xdp);
12743 		}
12744 	}
12745 
12746 	return 0;
12747 }
12748 
12749 /**
12750  * bpf_icmp_send - Send an ICMP control message
12751  * @skb_ctx: Packet that triggered the control message
12752  * @type: ICMP type (only ICMP_DEST_UNREACH/ICMPV6_DEST_UNREACH supported)
12753  * @code: ICMP code (0-15 except ICMP_FRAG_NEEDED for IPv4, 0-6 for IPv6)
12754  *
12755  * Sends an ICMP control message in response to the packet. The original packet
12756  * is cloned before sending the ICMP message, so the BPF program can still let
12757  * the packet pass if desired.
12758  *
12759  * Currently only ICMP_DEST_UNREACH (IPv4) and ICMPV6_DEST_UNREACH (IPv6) are
12760  * supported.
12761  *
12762  * Return: 0 on success (send attempt), negative error code on failure:
12763  *         -EBUSY: Recursion detected
12764  *         -EPROTONOSUPPORT: Non-IP protocol
12765  *         -EOPNOTSUPP: Unsupported ICMP type
12766  *         -EINVAL: Invalid code parameter
12767  *         -ENETUNREACH: No usable route/dst for the ICMP reply
12768  *         -ENOMEM: Memory allocation failed
12769  */
12770 __bpf_kfunc int bpf_icmp_send(struct __sk_buff *skb_ctx, int type, int code)
12771 {
12772 	struct sk_buff *skb = (struct sk_buff *)skb_ctx;
12773 	struct sock *sk;
12774 
12775 	sk = skb_to_full_sk(skb);
12776 	if (sk && sk->sk_kern_sock &&
12777 	    (sk->sk_protocol == IPPROTO_ICMP || sk->sk_protocol == IPPROTO_ICMPV6))
12778 		return -EBUSY;
12779 
12780 	if (!skb_valid_dst(skb))
12781 		return -ENETUNREACH;
12782 
12783 	switch (skb->protocol) {
12784 #if IS_ENABLED(CONFIG_INET)
12785 	case htons(ETH_P_IP): {
12786 		struct sk_buff *nskb;
12787 
12788 		if (type != ICMP_DEST_UNREACH)
12789 			return -EOPNOTSUPP;
12790 		if (code < 0 || code > NR_ICMP_UNREACH ||
12791 		    code == ICMP_FRAG_NEEDED) /* needs a valid next-hop MTU */
12792 			return -EINVAL;
12793 
12794 		nskb = skb_clone(skb, GFP_ATOMIC);
12795 		if (!nskb)
12796 			return -ENOMEM;
12797 
12798 		memset(IPCB(nskb), 0, sizeof(*IPCB(nskb)));
12799 		icmp_send(nskb, type, code, 0);
12800 		consume_skb(nskb);
12801 		break;
12802 	}
12803 #endif
12804 #if IS_ENABLED(CONFIG_IPV6)
12805 	case htons(ETH_P_IPV6): {
12806 		struct sk_buff *nskb;
12807 
12808 		if (type != ICMPV6_DEST_UNREACH)
12809 			return -EOPNOTSUPP;
12810 		if (code < 0 || code > ICMPV6_REJECT_ROUTE)
12811 			return -EINVAL;
12812 
12813 		nskb = skb_clone(skb, GFP_ATOMIC);
12814 		if (!nskb)
12815 			return -ENOMEM;
12816 
12817 		memset(IP6CB(nskb), 0, sizeof(*IP6CB(nskb)));
12818 		icmpv6_send(nskb, type, code, 0);
12819 		consume_skb(nskb);
12820 		break;
12821 	}
12822 #endif
12823 	default:
12824 		return -EPROTONOSUPPORT;
12825 	}
12826 
12827 	return 0;
12828 }
12829 
12830 __bpf_kfunc_end_defs();
12831 
12832 int bpf_dynptr_from_skb_rdonly(struct __sk_buff *skb, u64 flags,
12833 			       struct bpf_dynptr *ptr__uninit)
12834 {
12835 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)ptr__uninit;
12836 	int err;
12837 
12838 	err = bpf_dynptr_from_skb(skb, flags, ptr__uninit);
12839 	if (err)
12840 		return err;
12841 
12842 	bpf_dynptr_set_rdonly(ptr);
12843 
12844 	return 0;
12845 }
12846 
12847 BTF_KFUNCS_START(bpf_kfunc_check_set_skb)
12848 BTF_ID_FLAGS(func, bpf_dynptr_from_skb)
12849 BTF_KFUNCS_END(bpf_kfunc_check_set_skb)
12850 
12851 BTF_KFUNCS_START(bpf_kfunc_check_set_skb_meta)
12852 BTF_ID_FLAGS(func, bpf_dynptr_from_skb_meta)
12853 BTF_KFUNCS_END(bpf_kfunc_check_set_skb_meta)
12854 
12855 BTF_KFUNCS_START(bpf_kfunc_check_set_xdp)
12856 BTF_ID_FLAGS(func, bpf_dynptr_from_xdp)
12857 BTF_ID_FLAGS(func, bpf_xdp_pull_data)
12858 BTF_KFUNCS_END(bpf_kfunc_check_set_xdp)
12859 
12860 BTF_KFUNCS_START(bpf_kfunc_check_set_sock_addr)
12861 BTF_ID_FLAGS(func, bpf_sock_addr_set_sun_path)
12862 BTF_KFUNCS_END(bpf_kfunc_check_set_sock_addr)
12863 
12864 BTF_KFUNCS_START(bpf_kfunc_check_set_tcp_reqsk)
12865 BTF_ID_FLAGS(func, bpf_sk_assign_tcp_reqsk)
12866 BTF_KFUNCS_END(bpf_kfunc_check_set_tcp_reqsk)
12867 
12868 BTF_KFUNCS_START(bpf_kfunc_check_set_sock_ops)
12869 BTF_ID_FLAGS(func, bpf_sock_ops_enable_tx_tstamp)
12870 BTF_KFUNCS_END(bpf_kfunc_check_set_sock_ops)
12871 
12872 BTF_KFUNCS_START(bpf_kfunc_check_set_icmp_send)
12873 BTF_ID_FLAGS(func, bpf_icmp_send)
12874 BTF_KFUNCS_END(bpf_kfunc_check_set_icmp_send)
12875 
12876 static const struct btf_kfunc_id_set bpf_kfunc_set_skb = {
12877 	.owner = THIS_MODULE,
12878 	.set = &bpf_kfunc_check_set_skb,
12879 };
12880 
12881 static const struct btf_kfunc_id_set bpf_kfunc_set_skb_meta = {
12882 	.owner = THIS_MODULE,
12883 	.set = &bpf_kfunc_check_set_skb_meta,
12884 };
12885 
12886 static const struct btf_kfunc_id_set bpf_kfunc_set_xdp = {
12887 	.owner = THIS_MODULE,
12888 	.set = &bpf_kfunc_check_set_xdp,
12889 };
12890 
12891 static const struct btf_kfunc_id_set bpf_kfunc_set_sock_addr = {
12892 	.owner = THIS_MODULE,
12893 	.set = &bpf_kfunc_check_set_sock_addr,
12894 };
12895 
12896 static const struct btf_kfunc_id_set bpf_kfunc_set_tcp_reqsk = {
12897 	.owner = THIS_MODULE,
12898 	.set = &bpf_kfunc_check_set_tcp_reqsk,
12899 };
12900 
12901 static const struct btf_kfunc_id_set bpf_kfunc_set_sock_ops = {
12902 	.owner = THIS_MODULE,
12903 	.set = &bpf_kfunc_check_set_sock_ops,
12904 };
12905 
12906 static const struct btf_kfunc_id_set bpf_kfunc_set_icmp_send = {
12907 	.owner = THIS_MODULE,
12908 	.set = &bpf_kfunc_check_set_icmp_send,
12909 };
12910 
12911 static int __init bpf_kfunc_init(void)
12912 {
12913 	int ret;
12914 
12915 	ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &bpf_kfunc_set_skb);
12916 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_ACT, &bpf_kfunc_set_skb);
12917 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SK_SKB, &bpf_kfunc_set_skb);
12918 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SOCKET_FILTER, &bpf_kfunc_set_skb);
12919 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, &bpf_kfunc_set_skb);
12920 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_OUT, &bpf_kfunc_set_skb);
12921 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_IN, &bpf_kfunc_set_skb);
12922 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_XMIT, &bpf_kfunc_set_skb);
12923 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_SEG6LOCAL, &bpf_kfunc_set_skb);
12924 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_NETFILTER, &bpf_kfunc_set_skb);
12925 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_kfunc_set_skb);
12926 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &bpf_kfunc_set_skb);
12927 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &bpf_kfunc_set_skb_meta);
12928 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_ACT, &bpf_kfunc_set_skb_meta);
12929 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &bpf_kfunc_set_xdp);
12930 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
12931 					       &bpf_kfunc_set_sock_addr);
12932 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &bpf_kfunc_set_tcp_reqsk);
12933 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, &bpf_kfunc_set_icmp_send);
12934 	return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SOCK_OPS, &bpf_kfunc_set_sock_ops);
12935 }
12936 late_initcall(bpf_kfunc_init);
12937 
12938 __bpf_kfunc_start_defs();
12939 
12940 /* bpf_sock_destroy: Destroy the given socket with ECONNABORTED error code.
12941  *
12942  * The function expects a non-NULL pointer to a socket, and invokes the
12943  * protocol specific socket destroy handlers.
12944  *
12945  * The helper can only be called from BPF contexts that have acquired the socket
12946  * locks.
12947  *
12948  * Parameters:
12949  * @sock: Pointer to socket to be destroyed
12950  *
12951  * Return:
12952  * On error, may return EOPNOTSUPP, or whatever the protocol specific
12953  * destroy handler returns.
12954  * EOPNOTSUPP if protocol specific destroy handler is not supported.
12955  * 0 otherwise
12956  */
12957 __bpf_kfunc int bpf_sock_destroy(struct sock_common *sock)
12958 {
12959 	struct sock *sk = (struct sock *)sock;
12960 
12961 	/* The locking semantics that allow for synchronous execution of the
12962 	 * destroy handlers are only supported for TCP and UDP.
12963 	 * Supporting protocols will need to acquire sock lock in the BPF context
12964 	 * prior to invoking this kfunc.
12965 	 */
12966 	if (!sk->sk_prot->diag_destroy)
12967 		return -EOPNOTSUPP;
12968 
12969 	if (sk_fullsock(sk) &&
12970 	    sk->sk_protocol != IPPROTO_TCP &&
12971 	    sk->sk_protocol != IPPROTO_UDP)
12972 		return -EOPNOTSUPP;
12973 
12974 	return sk->sk_prot->diag_destroy(sk, ECONNABORTED);
12975 }
12976 
12977 __bpf_kfunc_end_defs();
12978 
12979 BTF_KFUNCS_START(bpf_sk_iter_kfunc_ids)
12980 BTF_ID_FLAGS(func, bpf_sock_destroy)
12981 BTF_KFUNCS_END(bpf_sk_iter_kfunc_ids)
12982 
12983 static int tracing_iter_filter(const struct bpf_prog *prog, u32 kfunc_id)
12984 {
12985 	if (btf_id_set8_contains(&bpf_sk_iter_kfunc_ids, kfunc_id) &&
12986 	    prog->expected_attach_type != BPF_TRACE_ITER)
12987 		return -EACCES;
12988 	return 0;
12989 }
12990 
12991 static const struct btf_kfunc_id_set bpf_sk_iter_kfunc_set = {
12992 	.owner = THIS_MODULE,
12993 	.set   = &bpf_sk_iter_kfunc_ids,
12994 	.filter = tracing_iter_filter,
12995 };
12996 
12997 static int init_subsystem(void)
12998 {
12999 	return register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_sk_iter_kfunc_set);
13000 }
13001 late_initcall(init_subsystem);
13002