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