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