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