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