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