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