xref: /linux/net/core/filter.c (revision d0d106a2bd21499901299160744e5fe9f4c83ddb)
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,enum xdp_mem_type mem_type,bool release)4130 static void bpf_xdp_shrink_data_zc(struct xdp_buff *xdp, int shrink,
4131 				   enum xdp_mem_type mem_type, 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(0, mem_type, 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 	enum xdp_mem_type mem_type = xdp->rxq->mem.type;
4147 	bool release = skb_frag_size(frag) == shrink;
4148 
4149 	if (mem_type == MEM_TYPE_XSK_BUFF_POOL) {
4150 		bpf_xdp_shrink_data_zc(xdp, shrink, mem_type, release);
4151 		goto out;
4152 	}
4153 
4154 	if (release)
4155 		__xdp_return(skb_frag_netmem(frag), mem_type, false, NULL);
4156 
4157 out:
4158 	return release;
4159 }
4160 
bpf_xdp_frags_shrink_tail(struct xdp_buff * xdp,int offset)4161 static int bpf_xdp_frags_shrink_tail(struct xdp_buff *xdp, int offset)
4162 {
4163 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
4164 	int i, n_frags_free = 0, len_free = 0;
4165 
4166 	if (unlikely(offset > (int)xdp_get_buff_len(xdp) - ETH_HLEN))
4167 		return -EINVAL;
4168 
4169 	for (i = sinfo->nr_frags - 1; i >= 0 && offset > 0; i--) {
4170 		skb_frag_t *frag = &sinfo->frags[i];
4171 		int shrink = min_t(int, offset, skb_frag_size(frag));
4172 
4173 		len_free += shrink;
4174 		offset -= shrink;
4175 		if (bpf_xdp_shrink_data(xdp, frag, shrink)) {
4176 			n_frags_free++;
4177 		} else {
4178 			skb_frag_size_sub(frag, shrink);
4179 			break;
4180 		}
4181 	}
4182 	sinfo->nr_frags -= n_frags_free;
4183 	sinfo->xdp_frags_size -= len_free;
4184 
4185 	if (unlikely(!sinfo->nr_frags)) {
4186 		xdp_buff_clear_frags_flag(xdp);
4187 		xdp->data_end -= offset;
4188 	}
4189 
4190 	return 0;
4191 }
4192 
BPF_CALL_2(bpf_xdp_adjust_tail,struct xdp_buff *,xdp,int,offset)4193 BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
4194 {
4195 	void *data_hard_end = xdp_data_hard_end(xdp); /* use xdp->frame_sz */
4196 	void *data_end = xdp->data_end + offset;
4197 
4198 	if (unlikely(xdp_buff_has_frags(xdp))) { /* non-linear xdp buff */
4199 		if (offset < 0)
4200 			return bpf_xdp_frags_shrink_tail(xdp, -offset);
4201 
4202 		return bpf_xdp_frags_increase_tail(xdp, offset);
4203 	}
4204 
4205 	/* Notice that xdp_data_hard_end have reserved some tailroom */
4206 	if (unlikely(data_end > data_hard_end))
4207 		return -EINVAL;
4208 
4209 	if (unlikely(data_end < xdp->data + ETH_HLEN))
4210 		return -EINVAL;
4211 
4212 	/* Clear memory area on grow, can contain uninit kernel memory */
4213 	if (offset > 0)
4214 		memset(xdp->data_end, 0, offset);
4215 
4216 	xdp->data_end = data_end;
4217 
4218 	return 0;
4219 }
4220 
4221 static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
4222 	.func		= bpf_xdp_adjust_tail,
4223 	.gpl_only	= false,
4224 	.ret_type	= RET_INTEGER,
4225 	.arg1_type	= ARG_PTR_TO_CTX,
4226 	.arg2_type	= ARG_ANYTHING,
4227 };
4228 
BPF_CALL_2(bpf_xdp_adjust_meta,struct xdp_buff *,xdp,int,offset)4229 BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
4230 {
4231 	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
4232 	void *meta = xdp->data_meta + offset;
4233 	unsigned long metalen = xdp->data - meta;
4234 
4235 	if (xdp_data_meta_unsupported(xdp))
4236 		return -ENOTSUPP;
4237 	if (unlikely(meta < xdp_frame_end ||
4238 		     meta > xdp->data))
4239 		return -EINVAL;
4240 	if (unlikely(xdp_metalen_invalid(metalen)))
4241 		return -EACCES;
4242 
4243 	xdp->data_meta = meta;
4244 
4245 	return 0;
4246 }
4247 
4248 static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
4249 	.func		= bpf_xdp_adjust_meta,
4250 	.gpl_only	= false,
4251 	.ret_type	= RET_INTEGER,
4252 	.arg1_type	= ARG_PTR_TO_CTX,
4253 	.arg2_type	= ARG_ANYTHING,
4254 };
4255 
4256 /**
4257  * DOC: xdp redirect
4258  *
4259  * XDP_REDIRECT works by a three-step process, implemented in the functions
4260  * below:
4261  *
4262  * 1. The bpf_redirect() and bpf_redirect_map() helpers will lookup the target
4263  *    of the redirect and store it (along with some other metadata) in a per-CPU
4264  *    struct bpf_redirect_info.
4265  *
4266  * 2. When the program returns the XDP_REDIRECT return code, the driver will
4267  *    call xdp_do_redirect() which will use the information in struct
4268  *    bpf_redirect_info to actually enqueue the frame into a map type-specific
4269  *    bulk queue structure.
4270  *
4271  * 3. Before exiting its NAPI poll loop, the driver will call
4272  *    xdp_do_flush(), which will flush all the different bulk queues,
4273  *    thus completing the redirect. Note that xdp_do_flush() must be
4274  *    called before napi_complete_done() in the driver, as the
4275  *    XDP_REDIRECT logic relies on being inside a single NAPI instance
4276  *    through to the xdp_do_flush() call for RCU protection of all
4277  *    in-kernel data structures.
4278  */
4279 /*
4280  * Pointers to the map entries will be kept around for this whole sequence of
4281  * steps, protected by RCU. However, there is no top-level rcu_read_lock() in
4282  * the core code; instead, the RCU protection relies on everything happening
4283  * inside a single NAPI poll sequence, which means it's between a pair of calls
4284  * to local_bh_disable()/local_bh_enable().
4285  *
4286  * The map entries are marked as __rcu and the map code makes sure to
4287  * dereference those pointers with rcu_dereference_check() in a way that works
4288  * for both sections that to hold an rcu_read_lock() and sections that are
4289  * called from NAPI without a separate rcu_read_lock(). The code below does not
4290  * use RCU annotations, but relies on those in the map code.
4291  */
xdp_do_flush(void)4292 void xdp_do_flush(void)
4293 {
4294 	struct list_head *lh_map, *lh_dev, *lh_xsk;
4295 
4296 	bpf_net_ctx_get_all_used_flush_lists(&lh_map, &lh_dev, &lh_xsk);
4297 	if (lh_dev)
4298 		__dev_flush(lh_dev);
4299 	if (lh_map)
4300 		__cpu_map_flush(lh_map);
4301 	if (lh_xsk)
4302 		__xsk_map_flush(lh_xsk);
4303 }
4304 EXPORT_SYMBOL_GPL(xdp_do_flush);
4305 
4306 #if defined(CONFIG_DEBUG_NET) && defined(CONFIG_BPF_SYSCALL)
xdp_do_check_flushed(struct napi_struct * napi)4307 void xdp_do_check_flushed(struct napi_struct *napi)
4308 {
4309 	struct list_head *lh_map, *lh_dev, *lh_xsk;
4310 	bool missed = false;
4311 
4312 	bpf_net_ctx_get_all_used_flush_lists(&lh_map, &lh_dev, &lh_xsk);
4313 	if (lh_dev) {
4314 		__dev_flush(lh_dev);
4315 		missed = true;
4316 	}
4317 	if (lh_map) {
4318 		__cpu_map_flush(lh_map);
4319 		missed = true;
4320 	}
4321 	if (lh_xsk) {
4322 		__xsk_map_flush(lh_xsk);
4323 		missed = true;
4324 	}
4325 
4326 	WARN_ONCE(missed, "Missing xdp_do_flush() invocation after NAPI by %ps\n",
4327 		  napi->poll);
4328 }
4329 #endif
4330 
4331 DEFINE_STATIC_KEY_FALSE(bpf_master_redirect_enabled_key);
4332 EXPORT_SYMBOL_GPL(bpf_master_redirect_enabled_key);
4333 
xdp_master_redirect(struct xdp_buff * xdp)4334 u32 xdp_master_redirect(struct xdp_buff *xdp)
4335 {
4336 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4337 	struct net_device *master, *slave;
4338 
4339 	master = netdev_master_upper_dev_get_rcu(xdp->rxq->dev);
4340 	slave = master->netdev_ops->ndo_xdp_get_xmit_slave(master, xdp);
4341 	if (slave && slave != xdp->rxq->dev) {
4342 		/* The target device is different from the receiving device, so
4343 		 * redirect it to the new device.
4344 		 * Using XDP_REDIRECT gets the correct behaviour from XDP enabled
4345 		 * drivers to unmap the packet from their rx ring.
4346 		 */
4347 		ri->tgt_index = slave->ifindex;
4348 		ri->map_id = INT_MAX;
4349 		ri->map_type = BPF_MAP_TYPE_UNSPEC;
4350 		return XDP_REDIRECT;
4351 	}
4352 	return XDP_TX;
4353 }
4354 EXPORT_SYMBOL_GPL(xdp_master_redirect);
4355 
__xdp_do_redirect_xsk(struct bpf_redirect_info * ri,const struct net_device * dev,struct xdp_buff * xdp,const struct bpf_prog * xdp_prog)4356 static inline int __xdp_do_redirect_xsk(struct bpf_redirect_info *ri,
4357 					const struct net_device *dev,
4358 					struct xdp_buff *xdp,
4359 					const struct bpf_prog *xdp_prog)
4360 {
4361 	enum bpf_map_type map_type = ri->map_type;
4362 	void *fwd = ri->tgt_value;
4363 	u32 map_id = ri->map_id;
4364 	int err;
4365 
4366 	ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4367 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4368 
4369 	err = __xsk_map_redirect(fwd, xdp);
4370 	if (unlikely(err))
4371 		goto err;
4372 
4373 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4374 	return 0;
4375 err:
4376 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4377 	return err;
4378 }
4379 
4380 static __always_inline int
__xdp_do_redirect_frame(struct bpf_redirect_info * ri,struct net_device * dev,struct xdp_frame * xdpf,const struct bpf_prog * xdp_prog)4381 __xdp_do_redirect_frame(struct bpf_redirect_info *ri, struct net_device *dev,
4382 			struct xdp_frame *xdpf,
4383 			const struct bpf_prog *xdp_prog)
4384 {
4385 	enum bpf_map_type map_type = ri->map_type;
4386 	void *fwd = ri->tgt_value;
4387 	u32 map_id = ri->map_id;
4388 	u32 flags = ri->flags;
4389 	struct bpf_map *map;
4390 	int err;
4391 
4392 	ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4393 	ri->flags = 0;
4394 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4395 
4396 	if (unlikely(!xdpf)) {
4397 		err = -EOVERFLOW;
4398 		goto err;
4399 	}
4400 
4401 	switch (map_type) {
4402 	case BPF_MAP_TYPE_DEVMAP:
4403 		fallthrough;
4404 	case BPF_MAP_TYPE_DEVMAP_HASH:
4405 		if (unlikely(flags & BPF_F_BROADCAST)) {
4406 			map = READ_ONCE(ri->map);
4407 
4408 			/* The map pointer is cleared when the map is being torn
4409 			 * down by dev_map_free()
4410 			 */
4411 			if (unlikely(!map)) {
4412 				err = -ENOENT;
4413 				break;
4414 			}
4415 
4416 			WRITE_ONCE(ri->map, NULL);
4417 			err = dev_map_enqueue_multi(xdpf, dev, map,
4418 						    flags & BPF_F_EXCLUDE_INGRESS);
4419 		} else {
4420 			err = dev_map_enqueue(fwd, xdpf, dev);
4421 		}
4422 		break;
4423 	case BPF_MAP_TYPE_CPUMAP:
4424 		err = cpu_map_enqueue(fwd, xdpf, dev);
4425 		break;
4426 	case BPF_MAP_TYPE_UNSPEC:
4427 		if (map_id == INT_MAX) {
4428 			fwd = dev_get_by_index_rcu(dev_net(dev), ri->tgt_index);
4429 			if (unlikely(!fwd)) {
4430 				err = -EINVAL;
4431 				break;
4432 			}
4433 			err = dev_xdp_enqueue(fwd, xdpf, dev);
4434 			break;
4435 		}
4436 		fallthrough;
4437 	default:
4438 		err = -EBADRQC;
4439 	}
4440 
4441 	if (unlikely(err))
4442 		goto err;
4443 
4444 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4445 	return 0;
4446 err:
4447 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4448 	return err;
4449 }
4450 
xdp_do_redirect(struct net_device * dev,struct xdp_buff * xdp,const struct bpf_prog * xdp_prog)4451 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
4452 		    const struct bpf_prog *xdp_prog)
4453 {
4454 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4455 	enum bpf_map_type map_type = ri->map_type;
4456 
4457 	if (map_type == BPF_MAP_TYPE_XSKMAP)
4458 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
4459 
4460 	return __xdp_do_redirect_frame(ri, dev, xdp_convert_buff_to_frame(xdp),
4461 				       xdp_prog);
4462 }
4463 EXPORT_SYMBOL_GPL(xdp_do_redirect);
4464 
xdp_do_redirect_frame(struct net_device * dev,struct xdp_buff * xdp,struct xdp_frame * xdpf,const struct bpf_prog * xdp_prog)4465 int xdp_do_redirect_frame(struct net_device *dev, struct xdp_buff *xdp,
4466 			  struct xdp_frame *xdpf,
4467 			  const struct bpf_prog *xdp_prog)
4468 {
4469 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4470 	enum bpf_map_type map_type = ri->map_type;
4471 
4472 	if (map_type == BPF_MAP_TYPE_XSKMAP)
4473 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
4474 
4475 	return __xdp_do_redirect_frame(ri, dev, xdpf, xdp_prog);
4476 }
4477 EXPORT_SYMBOL_GPL(xdp_do_redirect_frame);
4478 
xdp_do_generic_redirect_map(struct net_device * dev,struct sk_buff * skb,struct xdp_buff * xdp,const struct bpf_prog * xdp_prog,void * fwd,enum bpf_map_type map_type,u32 map_id,u32 flags)4479 static int xdp_do_generic_redirect_map(struct net_device *dev,
4480 				       struct sk_buff *skb,
4481 				       struct xdp_buff *xdp,
4482 				       const struct bpf_prog *xdp_prog,
4483 				       void *fwd, enum bpf_map_type map_type,
4484 				       u32 map_id, u32 flags)
4485 {
4486 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4487 	struct bpf_map *map;
4488 	int err;
4489 
4490 	switch (map_type) {
4491 	case BPF_MAP_TYPE_DEVMAP:
4492 		fallthrough;
4493 	case BPF_MAP_TYPE_DEVMAP_HASH:
4494 		if (unlikely(flags & BPF_F_BROADCAST)) {
4495 			map = READ_ONCE(ri->map);
4496 
4497 			/* The map pointer is cleared when the map is being torn
4498 			 * down by dev_map_free()
4499 			 */
4500 			if (unlikely(!map)) {
4501 				err = -ENOENT;
4502 				break;
4503 			}
4504 
4505 			WRITE_ONCE(ri->map, NULL);
4506 			err = dev_map_redirect_multi(dev, skb, xdp_prog, map,
4507 						     flags & BPF_F_EXCLUDE_INGRESS);
4508 		} else {
4509 			err = dev_map_generic_redirect(fwd, skb, xdp_prog);
4510 		}
4511 		if (unlikely(err))
4512 			goto err;
4513 		break;
4514 	case BPF_MAP_TYPE_XSKMAP:
4515 		err = xsk_generic_rcv(fwd, xdp);
4516 		if (err)
4517 			goto err;
4518 		consume_skb(skb);
4519 		break;
4520 	case BPF_MAP_TYPE_CPUMAP:
4521 		err = cpu_map_generic_redirect(fwd, skb);
4522 		if (unlikely(err))
4523 			goto err;
4524 		break;
4525 	default:
4526 		err = -EBADRQC;
4527 		goto err;
4528 	}
4529 
4530 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4531 	return 0;
4532 err:
4533 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4534 	return err;
4535 }
4536 
xdp_do_generic_redirect(struct net_device * dev,struct sk_buff * skb,struct xdp_buff * xdp,const struct bpf_prog * xdp_prog)4537 int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
4538 			    struct xdp_buff *xdp,
4539 			    const struct bpf_prog *xdp_prog)
4540 {
4541 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4542 	enum bpf_map_type map_type = ri->map_type;
4543 	void *fwd = ri->tgt_value;
4544 	u32 map_id = ri->map_id;
4545 	u32 flags = ri->flags;
4546 	int err;
4547 
4548 	ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4549 	ri->flags = 0;
4550 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4551 
4552 	if (map_type == BPF_MAP_TYPE_UNSPEC && map_id == INT_MAX) {
4553 		fwd = dev_get_by_index_rcu(dev_net(dev), ri->tgt_index);
4554 		if (unlikely(!fwd)) {
4555 			err = -EINVAL;
4556 			goto err;
4557 		}
4558 
4559 		err = xdp_ok_fwd_dev(fwd, skb->len);
4560 		if (unlikely(err))
4561 			goto err;
4562 
4563 		skb->dev = fwd;
4564 		_trace_xdp_redirect(dev, xdp_prog, ri->tgt_index);
4565 		generic_xdp_tx(skb, xdp_prog);
4566 		return 0;
4567 	}
4568 
4569 	return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog, fwd, map_type, map_id, flags);
4570 err:
4571 	_trace_xdp_redirect_err(dev, xdp_prog, ri->tgt_index, err);
4572 	return err;
4573 }
4574 
BPF_CALL_2(bpf_xdp_redirect,u32,ifindex,u64,flags)4575 BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
4576 {
4577 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4578 
4579 	if (unlikely(flags))
4580 		return XDP_ABORTED;
4581 
4582 	/* NB! Map type UNSPEC and map_id == INT_MAX (never generated
4583 	 * by map_idr) is used for ifindex based XDP redirect.
4584 	 */
4585 	ri->tgt_index = ifindex;
4586 	ri->map_id = INT_MAX;
4587 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4588 
4589 	return XDP_REDIRECT;
4590 }
4591 
4592 static const struct bpf_func_proto bpf_xdp_redirect_proto = {
4593 	.func           = bpf_xdp_redirect,
4594 	.gpl_only       = false,
4595 	.ret_type       = RET_INTEGER,
4596 	.arg1_type      = ARG_ANYTHING,
4597 	.arg2_type      = ARG_ANYTHING,
4598 };
4599 
BPF_CALL_3(bpf_xdp_redirect_map,struct bpf_map *,map,u64,key,u64,flags)4600 BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u64, key,
4601 	   u64, flags)
4602 {
4603 	return map->ops->map_redirect(map, key, flags);
4604 }
4605 
4606 static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
4607 	.func           = bpf_xdp_redirect_map,
4608 	.gpl_only       = false,
4609 	.ret_type       = RET_INTEGER,
4610 	.arg1_type      = ARG_CONST_MAP_PTR,
4611 	.arg2_type      = ARG_ANYTHING,
4612 	.arg3_type      = ARG_ANYTHING,
4613 };
4614 
bpf_skb_copy(void * dst_buff,const void * skb,unsigned long off,unsigned long len)4615 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
4616 				  unsigned long off, unsigned long len)
4617 {
4618 	void *ptr = skb_header_pointer(skb, off, len, dst_buff);
4619 
4620 	if (unlikely(!ptr))
4621 		return len;
4622 	if (ptr != dst_buff)
4623 		memcpy(dst_buff, ptr, len);
4624 
4625 	return 0;
4626 }
4627 
BPF_CALL_5(bpf_skb_event_output,struct sk_buff *,skb,struct bpf_map *,map,u64,flags,void *,meta,u64,meta_size)4628 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
4629 	   u64, flags, void *, meta, u64, meta_size)
4630 {
4631 	u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
4632 
4633 	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
4634 		return -EINVAL;
4635 	if (unlikely(!skb || skb_size > skb->len))
4636 		return -EFAULT;
4637 
4638 	return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
4639 				bpf_skb_copy);
4640 }
4641 
4642 static const struct bpf_func_proto bpf_skb_event_output_proto = {
4643 	.func		= bpf_skb_event_output,
4644 	.gpl_only	= true,
4645 	.ret_type	= RET_INTEGER,
4646 	.arg1_type	= ARG_PTR_TO_CTX,
4647 	.arg2_type	= ARG_CONST_MAP_PTR,
4648 	.arg3_type	= ARG_ANYTHING,
4649 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4650 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
4651 };
4652 
4653 BTF_ID_LIST_SINGLE(bpf_skb_output_btf_ids, struct, sk_buff)
4654 
4655 const struct bpf_func_proto bpf_skb_output_proto = {
4656 	.func		= bpf_skb_event_output,
4657 	.gpl_only	= true,
4658 	.ret_type	= RET_INTEGER,
4659 	.arg1_type	= ARG_PTR_TO_BTF_ID,
4660 	.arg1_btf_id	= &bpf_skb_output_btf_ids[0],
4661 	.arg2_type	= ARG_CONST_MAP_PTR,
4662 	.arg3_type	= ARG_ANYTHING,
4663 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4664 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
4665 };
4666 
bpf_tunnel_key_af(u64 flags)4667 static unsigned short bpf_tunnel_key_af(u64 flags)
4668 {
4669 	return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
4670 }
4671 
BPF_CALL_4(bpf_skb_get_tunnel_key,struct sk_buff *,skb,struct bpf_tunnel_key *,to,u32,size,u64,flags)4672 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
4673 	   u32, size, u64, flags)
4674 {
4675 	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
4676 	u8 compat[sizeof(struct bpf_tunnel_key)];
4677 	void *to_orig = to;
4678 	int err;
4679 
4680 	if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6 |
4681 					 BPF_F_TUNINFO_FLAGS)))) {
4682 		err = -EINVAL;
4683 		goto err_clear;
4684 	}
4685 	if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
4686 		err = -EPROTO;
4687 		goto err_clear;
4688 	}
4689 	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
4690 		err = -EINVAL;
4691 		switch (size) {
4692 		case offsetof(struct bpf_tunnel_key, local_ipv6[0]):
4693 		case offsetof(struct bpf_tunnel_key, tunnel_label):
4694 		case offsetof(struct bpf_tunnel_key, tunnel_ext):
4695 			goto set_compat;
4696 		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
4697 			/* Fixup deprecated structure layouts here, so we have
4698 			 * a common path later on.
4699 			 */
4700 			if (ip_tunnel_info_af(info) != AF_INET)
4701 				goto err_clear;
4702 set_compat:
4703 			to = (struct bpf_tunnel_key *)compat;
4704 			break;
4705 		default:
4706 			goto err_clear;
4707 		}
4708 	}
4709 
4710 	to->tunnel_id = be64_to_cpu(info->key.tun_id);
4711 	to->tunnel_tos = info->key.tos;
4712 	to->tunnel_ttl = info->key.ttl;
4713 	if (flags & BPF_F_TUNINFO_FLAGS)
4714 		to->tunnel_flags = ip_tunnel_flags_to_be16(info->key.tun_flags);
4715 	else
4716 		to->tunnel_ext = 0;
4717 
4718 	if (flags & BPF_F_TUNINFO_IPV6) {
4719 		memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
4720 		       sizeof(to->remote_ipv6));
4721 		memcpy(to->local_ipv6, &info->key.u.ipv6.dst,
4722 		       sizeof(to->local_ipv6));
4723 		to->tunnel_label = be32_to_cpu(info->key.label);
4724 	} else {
4725 		to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
4726 		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4727 		to->local_ipv4 = be32_to_cpu(info->key.u.ipv4.dst);
4728 		memset(&to->local_ipv6[1], 0, sizeof(__u32) * 3);
4729 		to->tunnel_label = 0;
4730 	}
4731 
4732 	if (unlikely(size != sizeof(struct bpf_tunnel_key)))
4733 		memcpy(to_orig, to, size);
4734 
4735 	return 0;
4736 err_clear:
4737 	memset(to_orig, 0, size);
4738 	return err;
4739 }
4740 
4741 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
4742 	.func		= bpf_skb_get_tunnel_key,
4743 	.gpl_only	= false,
4744 	.ret_type	= RET_INTEGER,
4745 	.arg1_type	= ARG_PTR_TO_CTX,
4746 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
4747 	.arg3_type	= ARG_CONST_SIZE,
4748 	.arg4_type	= ARG_ANYTHING,
4749 };
4750 
BPF_CALL_3(bpf_skb_get_tunnel_opt,struct sk_buff *,skb,u8 *,to,u32,size)4751 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
4752 {
4753 	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
4754 	int err;
4755 
4756 	if (unlikely(!info ||
4757 		     !ip_tunnel_is_options_present(info->key.tun_flags))) {
4758 		err = -ENOENT;
4759 		goto err_clear;
4760 	}
4761 	if (unlikely(size < info->options_len)) {
4762 		err = -ENOMEM;
4763 		goto err_clear;
4764 	}
4765 
4766 	ip_tunnel_info_opts_get(to, info);
4767 	if (size > info->options_len)
4768 		memset(to + info->options_len, 0, size - info->options_len);
4769 
4770 	return info->options_len;
4771 err_clear:
4772 	memset(to, 0, size);
4773 	return err;
4774 }
4775 
4776 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
4777 	.func		= bpf_skb_get_tunnel_opt,
4778 	.gpl_only	= false,
4779 	.ret_type	= RET_INTEGER,
4780 	.arg1_type	= ARG_PTR_TO_CTX,
4781 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
4782 	.arg3_type	= ARG_CONST_SIZE,
4783 };
4784 
4785 static struct metadata_dst __percpu *md_dst;
4786 
BPF_CALL_4(bpf_skb_set_tunnel_key,struct sk_buff *,skb,const struct bpf_tunnel_key *,from,u32,size,u64,flags)4787 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
4788 	   const struct bpf_tunnel_key *, from, u32, size, u64, flags)
4789 {
4790 	struct metadata_dst *md = this_cpu_ptr(md_dst);
4791 	u8 compat[sizeof(struct bpf_tunnel_key)];
4792 	struct ip_tunnel_info *info;
4793 
4794 	if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
4795 			       BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER |
4796 			       BPF_F_NO_TUNNEL_KEY)))
4797 		return -EINVAL;
4798 	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
4799 		switch (size) {
4800 		case offsetof(struct bpf_tunnel_key, local_ipv6[0]):
4801 		case offsetof(struct bpf_tunnel_key, tunnel_label):
4802 		case offsetof(struct bpf_tunnel_key, tunnel_ext):
4803 		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
4804 			/* Fixup deprecated structure layouts here, so we have
4805 			 * a common path later on.
4806 			 */
4807 			memcpy(compat, from, size);
4808 			memset(compat + size, 0, sizeof(compat) - size);
4809 			from = (const struct bpf_tunnel_key *) compat;
4810 			break;
4811 		default:
4812 			return -EINVAL;
4813 		}
4814 	}
4815 	if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
4816 		     from->tunnel_ext))
4817 		return -EINVAL;
4818 
4819 	skb_dst_drop(skb);
4820 	dst_hold((struct dst_entry *) md);
4821 	skb_dst_set(skb, (struct dst_entry *) md);
4822 
4823 	info = &md->u.tun_info;
4824 	memset(info, 0, sizeof(*info));
4825 	info->mode = IP_TUNNEL_INFO_TX;
4826 
4827 	__set_bit(IP_TUNNEL_NOCACHE_BIT, info->key.tun_flags);
4828 	__assign_bit(IP_TUNNEL_DONT_FRAGMENT_BIT, info->key.tun_flags,
4829 		     flags & BPF_F_DONT_FRAGMENT);
4830 	__assign_bit(IP_TUNNEL_CSUM_BIT, info->key.tun_flags,
4831 		     !(flags & BPF_F_ZERO_CSUM_TX));
4832 	__assign_bit(IP_TUNNEL_SEQ_BIT, info->key.tun_flags,
4833 		     flags & BPF_F_SEQ_NUMBER);
4834 	__assign_bit(IP_TUNNEL_KEY_BIT, info->key.tun_flags,
4835 		     !(flags & BPF_F_NO_TUNNEL_KEY));
4836 
4837 	info->key.tun_id = cpu_to_be64(from->tunnel_id);
4838 	info->key.tos = from->tunnel_tos;
4839 	info->key.ttl = from->tunnel_ttl;
4840 
4841 	if (flags & BPF_F_TUNINFO_IPV6) {
4842 		info->mode |= IP_TUNNEL_INFO_IPV6;
4843 		memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
4844 		       sizeof(from->remote_ipv6));
4845 		memcpy(&info->key.u.ipv6.src, from->local_ipv6,
4846 		       sizeof(from->local_ipv6));
4847 		info->key.label = cpu_to_be32(from->tunnel_label) &
4848 				  IPV6_FLOWLABEL_MASK;
4849 	} else {
4850 		info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
4851 		info->key.u.ipv4.src = cpu_to_be32(from->local_ipv4);
4852 		info->key.flow_flags = FLOWI_FLAG_ANYSRC;
4853 	}
4854 
4855 	return 0;
4856 }
4857 
4858 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
4859 	.func		= bpf_skb_set_tunnel_key,
4860 	.gpl_only	= false,
4861 	.ret_type	= RET_INTEGER,
4862 	.arg1_type	= ARG_PTR_TO_CTX,
4863 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4864 	.arg3_type	= ARG_CONST_SIZE,
4865 	.arg4_type	= ARG_ANYTHING,
4866 };
4867 
BPF_CALL_3(bpf_skb_set_tunnel_opt,struct sk_buff *,skb,const u8 *,from,u32,size)4868 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
4869 	   const u8 *, from, u32, size)
4870 {
4871 	struct ip_tunnel_info *info = skb_tunnel_info(skb);
4872 	const struct metadata_dst *md = this_cpu_ptr(md_dst);
4873 	IP_TUNNEL_DECLARE_FLAGS(present) = { };
4874 
4875 	if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
4876 		return -EINVAL;
4877 	if (unlikely(size > IP_TUNNEL_OPTS_MAX))
4878 		return -ENOMEM;
4879 
4880 	ip_tunnel_set_options_present(present);
4881 	ip_tunnel_info_opts_set(info, from, size, present);
4882 
4883 	return 0;
4884 }
4885 
4886 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
4887 	.func		= bpf_skb_set_tunnel_opt,
4888 	.gpl_only	= false,
4889 	.ret_type	= RET_INTEGER,
4890 	.arg1_type	= ARG_PTR_TO_CTX,
4891 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4892 	.arg3_type	= ARG_CONST_SIZE,
4893 };
4894 
4895 static const struct bpf_func_proto *
bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)4896 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
4897 {
4898 	if (!md_dst) {
4899 		struct metadata_dst __percpu *tmp;
4900 
4901 		tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
4902 						METADATA_IP_TUNNEL,
4903 						GFP_KERNEL);
4904 		if (!tmp)
4905 			return NULL;
4906 		if (cmpxchg(&md_dst, NULL, tmp))
4907 			metadata_dst_free_percpu(tmp);
4908 	}
4909 
4910 	switch (which) {
4911 	case BPF_FUNC_skb_set_tunnel_key:
4912 		return &bpf_skb_set_tunnel_key_proto;
4913 	case BPF_FUNC_skb_set_tunnel_opt:
4914 		return &bpf_skb_set_tunnel_opt_proto;
4915 	default:
4916 		return NULL;
4917 	}
4918 }
4919 
BPF_CALL_3(bpf_skb_under_cgroup,struct sk_buff *,skb,struct bpf_map *,map,u32,idx)4920 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
4921 	   u32, idx)
4922 {
4923 	struct bpf_array *array = container_of(map, struct bpf_array, map);
4924 	struct cgroup *cgrp;
4925 	struct sock *sk;
4926 
4927 	sk = skb_to_full_sk(skb);
4928 	if (!sk || !sk_fullsock(sk))
4929 		return -ENOENT;
4930 	if (unlikely(idx >= array->map.max_entries))
4931 		return -E2BIG;
4932 
4933 	cgrp = READ_ONCE(array->ptrs[idx]);
4934 	if (unlikely(!cgrp))
4935 		return -EAGAIN;
4936 
4937 	return sk_under_cgroup_hierarchy(sk, cgrp);
4938 }
4939 
4940 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
4941 	.func		= bpf_skb_under_cgroup,
4942 	.gpl_only	= false,
4943 	.ret_type	= RET_INTEGER,
4944 	.arg1_type	= ARG_PTR_TO_CTX,
4945 	.arg2_type	= ARG_CONST_MAP_PTR,
4946 	.arg3_type	= ARG_ANYTHING,
4947 };
4948 
4949 #ifdef CONFIG_SOCK_CGROUP_DATA
__bpf_sk_cgroup_id(struct sock * sk)4950 static inline u64 __bpf_sk_cgroup_id(struct sock *sk)
4951 {
4952 	struct cgroup *cgrp;
4953 
4954 	sk = sk_to_full_sk(sk);
4955 	if (!sk || !sk_fullsock(sk))
4956 		return 0;
4957 
4958 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4959 	return cgroup_id(cgrp);
4960 }
4961 
BPF_CALL_1(bpf_skb_cgroup_id,const struct sk_buff *,skb)4962 BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
4963 {
4964 	return __bpf_sk_cgroup_id(skb->sk);
4965 }
4966 
4967 static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
4968 	.func           = bpf_skb_cgroup_id,
4969 	.gpl_only       = false,
4970 	.ret_type       = RET_INTEGER,
4971 	.arg1_type      = ARG_PTR_TO_CTX,
4972 };
4973 
__bpf_sk_ancestor_cgroup_id(struct sock * sk,int ancestor_level)4974 static inline u64 __bpf_sk_ancestor_cgroup_id(struct sock *sk,
4975 					      int ancestor_level)
4976 {
4977 	struct cgroup *ancestor;
4978 	struct cgroup *cgrp;
4979 
4980 	sk = sk_to_full_sk(sk);
4981 	if (!sk || !sk_fullsock(sk))
4982 		return 0;
4983 
4984 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4985 	ancestor = cgroup_ancestor(cgrp, ancestor_level);
4986 	if (!ancestor)
4987 		return 0;
4988 
4989 	return cgroup_id(ancestor);
4990 }
4991 
BPF_CALL_2(bpf_skb_ancestor_cgroup_id,const struct sk_buff *,skb,int,ancestor_level)4992 BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
4993 	   ancestor_level)
4994 {
4995 	return __bpf_sk_ancestor_cgroup_id(skb->sk, ancestor_level);
4996 }
4997 
4998 static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
4999 	.func           = bpf_skb_ancestor_cgroup_id,
5000 	.gpl_only       = false,
5001 	.ret_type       = RET_INTEGER,
5002 	.arg1_type      = ARG_PTR_TO_CTX,
5003 	.arg2_type      = ARG_ANYTHING,
5004 };
5005 
BPF_CALL_1(bpf_sk_cgroup_id,struct sock *,sk)5006 BPF_CALL_1(bpf_sk_cgroup_id, struct sock *, sk)
5007 {
5008 	return __bpf_sk_cgroup_id(sk);
5009 }
5010 
5011 static const struct bpf_func_proto bpf_sk_cgroup_id_proto = {
5012 	.func           = bpf_sk_cgroup_id,
5013 	.gpl_only       = false,
5014 	.ret_type       = RET_INTEGER,
5015 	.arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5016 };
5017 
BPF_CALL_2(bpf_sk_ancestor_cgroup_id,struct sock *,sk,int,ancestor_level)5018 BPF_CALL_2(bpf_sk_ancestor_cgroup_id, struct sock *, sk, int, ancestor_level)
5019 {
5020 	return __bpf_sk_ancestor_cgroup_id(sk, ancestor_level);
5021 }
5022 
5023 static const struct bpf_func_proto bpf_sk_ancestor_cgroup_id_proto = {
5024 	.func           = bpf_sk_ancestor_cgroup_id,
5025 	.gpl_only       = false,
5026 	.ret_type       = RET_INTEGER,
5027 	.arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5028 	.arg2_type      = ARG_ANYTHING,
5029 };
5030 #endif
5031 
bpf_xdp_copy(void * dst,const void * ctx,unsigned long off,unsigned long len)5032 static unsigned long bpf_xdp_copy(void *dst, const void *ctx,
5033 				  unsigned long off, unsigned long len)
5034 {
5035 	struct xdp_buff *xdp = (struct xdp_buff *)ctx;
5036 
5037 	bpf_xdp_copy_buf(xdp, off, dst, len, false);
5038 	return 0;
5039 }
5040 
BPF_CALL_5(bpf_xdp_event_output,struct xdp_buff *,xdp,struct bpf_map *,map,u64,flags,void *,meta,u64,meta_size)5041 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
5042 	   u64, flags, void *, meta, u64, meta_size)
5043 {
5044 	u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
5045 
5046 	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
5047 		return -EINVAL;
5048 
5049 	if (unlikely(!xdp || xdp_size > xdp_get_buff_len(xdp)))
5050 		return -EFAULT;
5051 
5052 	return bpf_event_output(map, flags, meta, meta_size, xdp,
5053 				xdp_size, bpf_xdp_copy);
5054 }
5055 
5056 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
5057 	.func		= bpf_xdp_event_output,
5058 	.gpl_only	= true,
5059 	.ret_type	= RET_INTEGER,
5060 	.arg1_type	= ARG_PTR_TO_CTX,
5061 	.arg2_type	= ARG_CONST_MAP_PTR,
5062 	.arg3_type	= ARG_ANYTHING,
5063 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5064 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
5065 };
5066 
5067 BTF_ID_LIST_SINGLE(bpf_xdp_output_btf_ids, struct, xdp_buff)
5068 
5069 const struct bpf_func_proto bpf_xdp_output_proto = {
5070 	.func		= bpf_xdp_event_output,
5071 	.gpl_only	= true,
5072 	.ret_type	= RET_INTEGER,
5073 	.arg1_type	= ARG_PTR_TO_BTF_ID,
5074 	.arg1_btf_id	= &bpf_xdp_output_btf_ids[0],
5075 	.arg2_type	= ARG_CONST_MAP_PTR,
5076 	.arg3_type	= ARG_ANYTHING,
5077 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5078 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
5079 };
5080 
BPF_CALL_1(bpf_get_socket_cookie,struct sk_buff *,skb)5081 BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
5082 {
5083 	return skb->sk ? __sock_gen_cookie(skb->sk) : 0;
5084 }
5085 
5086 static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
5087 	.func           = bpf_get_socket_cookie,
5088 	.gpl_only       = false,
5089 	.ret_type       = RET_INTEGER,
5090 	.arg1_type      = ARG_PTR_TO_CTX,
5091 };
5092 
BPF_CALL_1(bpf_get_socket_cookie_sock_addr,struct bpf_sock_addr_kern *,ctx)5093 BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
5094 {
5095 	return __sock_gen_cookie(ctx->sk);
5096 }
5097 
5098 static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
5099 	.func		= bpf_get_socket_cookie_sock_addr,
5100 	.gpl_only	= false,
5101 	.ret_type	= RET_INTEGER,
5102 	.arg1_type	= ARG_PTR_TO_CTX,
5103 };
5104 
BPF_CALL_1(bpf_get_socket_cookie_sock,struct sock *,ctx)5105 BPF_CALL_1(bpf_get_socket_cookie_sock, struct sock *, ctx)
5106 {
5107 	return __sock_gen_cookie(ctx);
5108 }
5109 
5110 static const struct bpf_func_proto bpf_get_socket_cookie_sock_proto = {
5111 	.func		= bpf_get_socket_cookie_sock,
5112 	.gpl_only	= false,
5113 	.ret_type	= RET_INTEGER,
5114 	.arg1_type	= ARG_PTR_TO_CTX,
5115 };
5116 
BPF_CALL_1(bpf_get_socket_ptr_cookie,struct sock *,sk)5117 BPF_CALL_1(bpf_get_socket_ptr_cookie, struct sock *, sk)
5118 {
5119 	return sk ? sock_gen_cookie(sk) : 0;
5120 }
5121 
5122 const struct bpf_func_proto bpf_get_socket_ptr_cookie_proto = {
5123 	.func		= bpf_get_socket_ptr_cookie,
5124 	.gpl_only	= false,
5125 	.ret_type	= RET_INTEGER,
5126 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON | PTR_MAYBE_NULL,
5127 };
5128 
BPF_CALL_1(bpf_get_socket_cookie_sock_ops,struct bpf_sock_ops_kern *,ctx)5129 BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
5130 {
5131 	return __sock_gen_cookie(ctx->sk);
5132 }
5133 
5134 static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
5135 	.func		= bpf_get_socket_cookie_sock_ops,
5136 	.gpl_only	= false,
5137 	.ret_type	= RET_INTEGER,
5138 	.arg1_type	= ARG_PTR_TO_CTX,
5139 };
5140 
__bpf_get_netns_cookie(struct sock * sk)5141 static u64 __bpf_get_netns_cookie(struct sock *sk)
5142 {
5143 	const struct net *net = sk ? sock_net(sk) : &init_net;
5144 
5145 	return net->net_cookie;
5146 }
5147 
BPF_CALL_1(bpf_get_netns_cookie,struct sk_buff *,skb)5148 BPF_CALL_1(bpf_get_netns_cookie, struct sk_buff *, skb)
5149 {
5150 	return __bpf_get_netns_cookie(skb && skb->sk ? skb->sk : NULL);
5151 }
5152 
5153 static const struct bpf_func_proto bpf_get_netns_cookie_proto = {
5154 	.func           = bpf_get_netns_cookie,
5155 	.ret_type       = RET_INTEGER,
5156 	.arg1_type      = ARG_PTR_TO_CTX_OR_NULL,
5157 };
5158 
BPF_CALL_1(bpf_get_netns_cookie_sock,struct sock *,ctx)5159 BPF_CALL_1(bpf_get_netns_cookie_sock, struct sock *, ctx)
5160 {
5161 	return __bpf_get_netns_cookie(ctx);
5162 }
5163 
5164 static const struct bpf_func_proto bpf_get_netns_cookie_sock_proto = {
5165 	.func		= bpf_get_netns_cookie_sock,
5166 	.gpl_only	= false,
5167 	.ret_type	= RET_INTEGER,
5168 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5169 };
5170 
BPF_CALL_1(bpf_get_netns_cookie_sock_addr,struct bpf_sock_addr_kern *,ctx)5171 BPF_CALL_1(bpf_get_netns_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
5172 {
5173 	return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5174 }
5175 
5176 static const struct bpf_func_proto bpf_get_netns_cookie_sock_addr_proto = {
5177 	.func		= bpf_get_netns_cookie_sock_addr,
5178 	.gpl_only	= false,
5179 	.ret_type	= RET_INTEGER,
5180 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5181 };
5182 
BPF_CALL_1(bpf_get_netns_cookie_sock_ops,struct bpf_sock_ops_kern *,ctx)5183 BPF_CALL_1(bpf_get_netns_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
5184 {
5185 	return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5186 }
5187 
5188 static const struct bpf_func_proto bpf_get_netns_cookie_sock_ops_proto = {
5189 	.func		= bpf_get_netns_cookie_sock_ops,
5190 	.gpl_only	= false,
5191 	.ret_type	= RET_INTEGER,
5192 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5193 };
5194 
BPF_CALL_1(bpf_get_netns_cookie_sk_msg,struct sk_msg *,ctx)5195 BPF_CALL_1(bpf_get_netns_cookie_sk_msg, struct sk_msg *, ctx)
5196 {
5197 	return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5198 }
5199 
5200 static const struct bpf_func_proto bpf_get_netns_cookie_sk_msg_proto = {
5201 	.func		= bpf_get_netns_cookie_sk_msg,
5202 	.gpl_only	= false,
5203 	.ret_type	= RET_INTEGER,
5204 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5205 };
5206 
BPF_CALL_1(bpf_get_socket_uid,struct sk_buff *,skb)5207 BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
5208 {
5209 	struct sock *sk = sk_to_full_sk(skb->sk);
5210 	kuid_t kuid;
5211 
5212 	if (!sk || !sk_fullsock(sk))
5213 		return overflowuid;
5214 	kuid = sock_net_uid(sock_net(sk), sk);
5215 	return from_kuid_munged(sock_net(sk)->user_ns, kuid);
5216 }
5217 
5218 static const struct bpf_func_proto bpf_get_socket_uid_proto = {
5219 	.func           = bpf_get_socket_uid,
5220 	.gpl_only       = false,
5221 	.ret_type       = RET_INTEGER,
5222 	.arg1_type      = ARG_PTR_TO_CTX,
5223 };
5224 
sol_socket_sockopt(struct sock * sk,int optname,char * optval,int * optlen,bool getopt)5225 static int sol_socket_sockopt(struct sock *sk, int optname,
5226 			      char *optval, int *optlen,
5227 			      bool getopt)
5228 {
5229 	switch (optname) {
5230 	case SO_REUSEADDR:
5231 	case SO_SNDBUF:
5232 	case SO_RCVBUF:
5233 	case SO_KEEPALIVE:
5234 	case SO_PRIORITY:
5235 	case SO_REUSEPORT:
5236 	case SO_RCVLOWAT:
5237 	case SO_MARK:
5238 	case SO_MAX_PACING_RATE:
5239 	case SO_BINDTOIFINDEX:
5240 	case SO_TXREHASH:
5241 		if (*optlen != sizeof(int))
5242 			return -EINVAL;
5243 		break;
5244 	case SO_BINDTODEVICE:
5245 		break;
5246 	default:
5247 		return -EINVAL;
5248 	}
5249 
5250 	if (getopt) {
5251 		if (optname == SO_BINDTODEVICE)
5252 			return -EINVAL;
5253 		return sk_getsockopt(sk, SOL_SOCKET, optname,
5254 				     KERNEL_SOCKPTR(optval),
5255 				     KERNEL_SOCKPTR(optlen));
5256 	}
5257 
5258 	return sk_setsockopt(sk, SOL_SOCKET, optname,
5259 			     KERNEL_SOCKPTR(optval), *optlen);
5260 }
5261 
bpf_sol_tcp_setsockopt(struct sock * sk,int optname,char * optval,int optlen)5262 static int bpf_sol_tcp_setsockopt(struct sock *sk, int optname,
5263 				  char *optval, int optlen)
5264 {
5265 	struct tcp_sock *tp = tcp_sk(sk);
5266 	unsigned long timeout;
5267 	int val;
5268 
5269 	if (optlen != sizeof(int))
5270 		return -EINVAL;
5271 
5272 	val = *(int *)optval;
5273 
5274 	/* Only some options are supported */
5275 	switch (optname) {
5276 	case TCP_BPF_IW:
5277 		if (val <= 0 || tp->data_segs_out > tp->syn_data)
5278 			return -EINVAL;
5279 		tcp_snd_cwnd_set(tp, val);
5280 		break;
5281 	case TCP_BPF_SNDCWND_CLAMP:
5282 		if (val <= 0)
5283 			return -EINVAL;
5284 		tp->snd_cwnd_clamp = val;
5285 		tp->snd_ssthresh = val;
5286 		break;
5287 	case TCP_BPF_DELACK_MAX:
5288 		timeout = usecs_to_jiffies(val);
5289 		if (timeout > TCP_DELACK_MAX ||
5290 		    timeout < TCP_TIMEOUT_MIN)
5291 			return -EINVAL;
5292 		inet_csk(sk)->icsk_delack_max = timeout;
5293 		break;
5294 	case TCP_BPF_RTO_MIN:
5295 		timeout = usecs_to_jiffies(val);
5296 		if (timeout > TCP_RTO_MIN ||
5297 		    timeout < TCP_TIMEOUT_MIN)
5298 			return -EINVAL;
5299 		inet_csk(sk)->icsk_rto_min = timeout;
5300 		break;
5301 	case TCP_BPF_SOCK_OPS_CB_FLAGS:
5302 		if (val & ~(BPF_SOCK_OPS_ALL_CB_FLAGS))
5303 			return -EINVAL;
5304 		tp->bpf_sock_ops_cb_flags = val;
5305 		break;
5306 	default:
5307 		return -EINVAL;
5308 	}
5309 
5310 	return 0;
5311 }
5312 
sol_tcp_sockopt_congestion(struct sock * sk,char * optval,int * optlen,bool getopt)5313 static int sol_tcp_sockopt_congestion(struct sock *sk, char *optval,
5314 				      int *optlen, bool getopt)
5315 {
5316 	struct tcp_sock *tp;
5317 	int ret;
5318 
5319 	if (*optlen < 2)
5320 		return -EINVAL;
5321 
5322 	if (getopt) {
5323 		if (!inet_csk(sk)->icsk_ca_ops)
5324 			return -EINVAL;
5325 		/* BPF expects NULL-terminated tcp-cc string */
5326 		optval[--(*optlen)] = '\0';
5327 		return do_tcp_getsockopt(sk, SOL_TCP, TCP_CONGESTION,
5328 					 KERNEL_SOCKPTR(optval),
5329 					 KERNEL_SOCKPTR(optlen));
5330 	}
5331 
5332 	/* "cdg" is the only cc that alloc a ptr
5333 	 * in inet_csk_ca area.  The bpf-tcp-cc may
5334 	 * overwrite this ptr after switching to cdg.
5335 	 */
5336 	if (*optlen >= sizeof("cdg") - 1 && !strncmp("cdg", optval, *optlen))
5337 		return -ENOTSUPP;
5338 
5339 	/* It stops this looping
5340 	 *
5341 	 * .init => bpf_setsockopt(tcp_cc) => .init =>
5342 	 * bpf_setsockopt(tcp_cc)" => .init => ....
5343 	 *
5344 	 * The second bpf_setsockopt(tcp_cc) is not allowed
5345 	 * in order to break the loop when both .init
5346 	 * are the same bpf prog.
5347 	 *
5348 	 * This applies even the second bpf_setsockopt(tcp_cc)
5349 	 * does not cause a loop.  This limits only the first
5350 	 * '.init' can call bpf_setsockopt(TCP_CONGESTION) to
5351 	 * pick a fallback cc (eg. peer does not support ECN)
5352 	 * and the second '.init' cannot fallback to
5353 	 * another.
5354 	 */
5355 	tp = tcp_sk(sk);
5356 	if (tp->bpf_chg_cc_inprogress)
5357 		return -EBUSY;
5358 
5359 	tp->bpf_chg_cc_inprogress = 1;
5360 	ret = do_tcp_setsockopt(sk, SOL_TCP, TCP_CONGESTION,
5361 				KERNEL_SOCKPTR(optval), *optlen);
5362 	tp->bpf_chg_cc_inprogress = 0;
5363 	return ret;
5364 }
5365 
sol_tcp_sockopt(struct sock * sk,int optname,char * optval,int * optlen,bool getopt)5366 static int sol_tcp_sockopt(struct sock *sk, int optname,
5367 			   char *optval, int *optlen,
5368 			   bool getopt)
5369 {
5370 	if (sk->sk_protocol != IPPROTO_TCP)
5371 		return -EINVAL;
5372 
5373 	switch (optname) {
5374 	case TCP_NODELAY:
5375 	case TCP_MAXSEG:
5376 	case TCP_KEEPIDLE:
5377 	case TCP_KEEPINTVL:
5378 	case TCP_KEEPCNT:
5379 	case TCP_SYNCNT:
5380 	case TCP_WINDOW_CLAMP:
5381 	case TCP_THIN_LINEAR_TIMEOUTS:
5382 	case TCP_USER_TIMEOUT:
5383 	case TCP_NOTSENT_LOWAT:
5384 	case TCP_SAVE_SYN:
5385 		if (*optlen != sizeof(int))
5386 			return -EINVAL;
5387 		break;
5388 	case TCP_CONGESTION:
5389 		return sol_tcp_sockopt_congestion(sk, optval, optlen, getopt);
5390 	case TCP_SAVED_SYN:
5391 		if (*optlen < 1)
5392 			return -EINVAL;
5393 		break;
5394 	case TCP_BPF_SOCK_OPS_CB_FLAGS:
5395 		if (*optlen != sizeof(int))
5396 			return -EINVAL;
5397 		if (getopt) {
5398 			struct tcp_sock *tp = tcp_sk(sk);
5399 			int cb_flags = tp->bpf_sock_ops_cb_flags;
5400 
5401 			memcpy(optval, &cb_flags, *optlen);
5402 			return 0;
5403 		}
5404 		return bpf_sol_tcp_setsockopt(sk, optname, optval, *optlen);
5405 	default:
5406 		if (getopt)
5407 			return -EINVAL;
5408 		return bpf_sol_tcp_setsockopt(sk, optname, optval, *optlen);
5409 	}
5410 
5411 	if (getopt) {
5412 		if (optname == TCP_SAVED_SYN) {
5413 			struct tcp_sock *tp = tcp_sk(sk);
5414 
5415 			if (!tp->saved_syn ||
5416 			    *optlen > tcp_saved_syn_len(tp->saved_syn))
5417 				return -EINVAL;
5418 			memcpy(optval, tp->saved_syn->data, *optlen);
5419 			/* It cannot free tp->saved_syn here because it
5420 			 * does not know if the user space still needs it.
5421 			 */
5422 			return 0;
5423 		}
5424 
5425 		return do_tcp_getsockopt(sk, SOL_TCP, optname,
5426 					 KERNEL_SOCKPTR(optval),
5427 					 KERNEL_SOCKPTR(optlen));
5428 	}
5429 
5430 	return do_tcp_setsockopt(sk, SOL_TCP, optname,
5431 				 KERNEL_SOCKPTR(optval), *optlen);
5432 }
5433 
sol_ip_sockopt(struct sock * sk,int optname,char * optval,int * optlen,bool getopt)5434 static int sol_ip_sockopt(struct sock *sk, int optname,
5435 			  char *optval, int *optlen,
5436 			  bool getopt)
5437 {
5438 	if (sk->sk_family != AF_INET)
5439 		return -EINVAL;
5440 
5441 	switch (optname) {
5442 	case IP_TOS:
5443 		if (*optlen != sizeof(int))
5444 			return -EINVAL;
5445 		break;
5446 	default:
5447 		return -EINVAL;
5448 	}
5449 
5450 	if (getopt)
5451 		return do_ip_getsockopt(sk, SOL_IP, optname,
5452 					KERNEL_SOCKPTR(optval),
5453 					KERNEL_SOCKPTR(optlen));
5454 
5455 	return do_ip_setsockopt(sk, SOL_IP, optname,
5456 				KERNEL_SOCKPTR(optval), *optlen);
5457 }
5458 
sol_ipv6_sockopt(struct sock * sk,int optname,char * optval,int * optlen,bool getopt)5459 static int sol_ipv6_sockopt(struct sock *sk, int optname,
5460 			    char *optval, int *optlen,
5461 			    bool getopt)
5462 {
5463 	if (sk->sk_family != AF_INET6)
5464 		return -EINVAL;
5465 
5466 	switch (optname) {
5467 	case IPV6_TCLASS:
5468 	case IPV6_AUTOFLOWLABEL:
5469 		if (*optlen != sizeof(int))
5470 			return -EINVAL;
5471 		break;
5472 	default:
5473 		return -EINVAL;
5474 	}
5475 
5476 	if (getopt)
5477 		return ipv6_bpf_stub->ipv6_getsockopt(sk, SOL_IPV6, optname,
5478 						      KERNEL_SOCKPTR(optval),
5479 						      KERNEL_SOCKPTR(optlen));
5480 
5481 	return ipv6_bpf_stub->ipv6_setsockopt(sk, SOL_IPV6, optname,
5482 					      KERNEL_SOCKPTR(optval), *optlen);
5483 }
5484 
__bpf_setsockopt(struct sock * sk,int level,int optname,char * optval,int optlen)5485 static int __bpf_setsockopt(struct sock *sk, int level, int optname,
5486 			    char *optval, int optlen)
5487 {
5488 	if (!sk_fullsock(sk))
5489 		return -EINVAL;
5490 
5491 	if (level == SOL_SOCKET)
5492 		return sol_socket_sockopt(sk, optname, optval, &optlen, false);
5493 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_IP)
5494 		return sol_ip_sockopt(sk, optname, optval, &optlen, false);
5495 	else if (IS_ENABLED(CONFIG_IPV6) && level == SOL_IPV6)
5496 		return sol_ipv6_sockopt(sk, optname, optval, &optlen, false);
5497 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP)
5498 		return sol_tcp_sockopt(sk, optname, optval, &optlen, false);
5499 
5500 	return -EINVAL;
5501 }
5502 
_bpf_setsockopt(struct sock * sk,int level,int optname,char * optval,int optlen)5503 static int _bpf_setsockopt(struct sock *sk, int level, int optname,
5504 			   char *optval, int optlen)
5505 {
5506 	if (sk_fullsock(sk))
5507 		sock_owned_by_me(sk);
5508 	return __bpf_setsockopt(sk, level, optname, optval, optlen);
5509 }
5510 
__bpf_getsockopt(struct sock * sk,int level,int optname,char * optval,int optlen)5511 static int __bpf_getsockopt(struct sock *sk, int level, int optname,
5512 			    char *optval, int optlen)
5513 {
5514 	int err, saved_optlen = optlen;
5515 
5516 	if (!sk_fullsock(sk)) {
5517 		err = -EINVAL;
5518 		goto done;
5519 	}
5520 
5521 	if (level == SOL_SOCKET)
5522 		err = sol_socket_sockopt(sk, optname, optval, &optlen, true);
5523 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP)
5524 		err = sol_tcp_sockopt(sk, optname, optval, &optlen, true);
5525 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_IP)
5526 		err = sol_ip_sockopt(sk, optname, optval, &optlen, true);
5527 	else if (IS_ENABLED(CONFIG_IPV6) && level == SOL_IPV6)
5528 		err = sol_ipv6_sockopt(sk, optname, optval, &optlen, true);
5529 	else
5530 		err = -EINVAL;
5531 
5532 done:
5533 	if (err)
5534 		optlen = 0;
5535 	if (optlen < saved_optlen)
5536 		memset(optval + optlen, 0, saved_optlen - optlen);
5537 	return err;
5538 }
5539 
_bpf_getsockopt(struct sock * sk,int level,int optname,char * optval,int optlen)5540 static int _bpf_getsockopt(struct sock *sk, int level, int optname,
5541 			   char *optval, int optlen)
5542 {
5543 	if (sk_fullsock(sk))
5544 		sock_owned_by_me(sk);
5545 	return __bpf_getsockopt(sk, level, optname, optval, optlen);
5546 }
5547 
BPF_CALL_5(bpf_sk_setsockopt,struct sock *,sk,int,level,int,optname,char *,optval,int,optlen)5548 BPF_CALL_5(bpf_sk_setsockopt, struct sock *, sk, int, level,
5549 	   int, optname, char *, optval, int, optlen)
5550 {
5551 	return _bpf_setsockopt(sk, level, optname, optval, optlen);
5552 }
5553 
5554 const struct bpf_func_proto bpf_sk_setsockopt_proto = {
5555 	.func		= bpf_sk_setsockopt,
5556 	.gpl_only	= false,
5557 	.ret_type	= RET_INTEGER,
5558 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5559 	.arg2_type	= ARG_ANYTHING,
5560 	.arg3_type	= ARG_ANYTHING,
5561 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5562 	.arg5_type	= ARG_CONST_SIZE,
5563 };
5564 
BPF_CALL_5(bpf_sk_getsockopt,struct sock *,sk,int,level,int,optname,char *,optval,int,optlen)5565 BPF_CALL_5(bpf_sk_getsockopt, struct sock *, sk, int, level,
5566 	   int, optname, char *, optval, int, optlen)
5567 {
5568 	return _bpf_getsockopt(sk, level, optname, optval, optlen);
5569 }
5570 
5571 const struct bpf_func_proto bpf_sk_getsockopt_proto = {
5572 	.func		= bpf_sk_getsockopt,
5573 	.gpl_only	= false,
5574 	.ret_type	= RET_INTEGER,
5575 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5576 	.arg2_type	= ARG_ANYTHING,
5577 	.arg3_type	= ARG_ANYTHING,
5578 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5579 	.arg5_type	= ARG_CONST_SIZE,
5580 };
5581 
BPF_CALL_5(bpf_unlocked_sk_setsockopt,struct sock *,sk,int,level,int,optname,char *,optval,int,optlen)5582 BPF_CALL_5(bpf_unlocked_sk_setsockopt, struct sock *, sk, int, level,
5583 	   int, optname, char *, optval, int, optlen)
5584 {
5585 	return __bpf_setsockopt(sk, level, optname, optval, optlen);
5586 }
5587 
5588 const struct bpf_func_proto bpf_unlocked_sk_setsockopt_proto = {
5589 	.func		= bpf_unlocked_sk_setsockopt,
5590 	.gpl_only	= false,
5591 	.ret_type	= RET_INTEGER,
5592 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5593 	.arg2_type	= ARG_ANYTHING,
5594 	.arg3_type	= ARG_ANYTHING,
5595 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5596 	.arg5_type	= ARG_CONST_SIZE,
5597 };
5598 
BPF_CALL_5(bpf_unlocked_sk_getsockopt,struct sock *,sk,int,level,int,optname,char *,optval,int,optlen)5599 BPF_CALL_5(bpf_unlocked_sk_getsockopt, struct sock *, sk, int, level,
5600 	   int, optname, char *, optval, int, optlen)
5601 {
5602 	return __bpf_getsockopt(sk, level, optname, optval, optlen);
5603 }
5604 
5605 const struct bpf_func_proto bpf_unlocked_sk_getsockopt_proto = {
5606 	.func		= bpf_unlocked_sk_getsockopt,
5607 	.gpl_only	= false,
5608 	.ret_type	= RET_INTEGER,
5609 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5610 	.arg2_type	= ARG_ANYTHING,
5611 	.arg3_type	= ARG_ANYTHING,
5612 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5613 	.arg5_type	= ARG_CONST_SIZE,
5614 };
5615 
BPF_CALL_5(bpf_sock_addr_setsockopt,struct bpf_sock_addr_kern *,ctx,int,level,int,optname,char *,optval,int,optlen)5616 BPF_CALL_5(bpf_sock_addr_setsockopt, struct bpf_sock_addr_kern *, ctx,
5617 	   int, level, int, optname, char *, optval, int, optlen)
5618 {
5619 	return _bpf_setsockopt(ctx->sk, level, optname, optval, optlen);
5620 }
5621 
5622 static const struct bpf_func_proto bpf_sock_addr_setsockopt_proto = {
5623 	.func		= bpf_sock_addr_setsockopt,
5624 	.gpl_only	= false,
5625 	.ret_type	= RET_INTEGER,
5626 	.arg1_type	= ARG_PTR_TO_CTX,
5627 	.arg2_type	= ARG_ANYTHING,
5628 	.arg3_type	= ARG_ANYTHING,
5629 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5630 	.arg5_type	= ARG_CONST_SIZE,
5631 };
5632 
BPF_CALL_5(bpf_sock_addr_getsockopt,struct bpf_sock_addr_kern *,ctx,int,level,int,optname,char *,optval,int,optlen)5633 BPF_CALL_5(bpf_sock_addr_getsockopt, struct bpf_sock_addr_kern *, ctx,
5634 	   int, level, int, optname, char *, optval, int, optlen)
5635 {
5636 	return _bpf_getsockopt(ctx->sk, level, optname, optval, optlen);
5637 }
5638 
5639 static const struct bpf_func_proto bpf_sock_addr_getsockopt_proto = {
5640 	.func		= bpf_sock_addr_getsockopt,
5641 	.gpl_only	= false,
5642 	.ret_type	= RET_INTEGER,
5643 	.arg1_type	= ARG_PTR_TO_CTX,
5644 	.arg2_type	= ARG_ANYTHING,
5645 	.arg3_type	= ARG_ANYTHING,
5646 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5647 	.arg5_type	= ARG_CONST_SIZE,
5648 };
5649 
BPF_CALL_5(bpf_sock_ops_setsockopt,struct bpf_sock_ops_kern *,bpf_sock,int,level,int,optname,char *,optval,int,optlen)5650 BPF_CALL_5(bpf_sock_ops_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
5651 	   int, level, int, optname, char *, optval, int, optlen)
5652 {
5653 	return _bpf_setsockopt(bpf_sock->sk, level, optname, optval, optlen);
5654 }
5655 
5656 static const struct bpf_func_proto bpf_sock_ops_setsockopt_proto = {
5657 	.func		= bpf_sock_ops_setsockopt,
5658 	.gpl_only	= false,
5659 	.ret_type	= RET_INTEGER,
5660 	.arg1_type	= ARG_PTR_TO_CTX,
5661 	.arg2_type	= ARG_ANYTHING,
5662 	.arg3_type	= ARG_ANYTHING,
5663 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5664 	.arg5_type	= ARG_CONST_SIZE,
5665 };
5666 
bpf_sock_ops_get_syn(struct bpf_sock_ops_kern * bpf_sock,int optname,const u8 ** start)5667 static int bpf_sock_ops_get_syn(struct bpf_sock_ops_kern *bpf_sock,
5668 				int optname, const u8 **start)
5669 {
5670 	struct sk_buff *syn_skb = bpf_sock->syn_skb;
5671 	const u8 *hdr_start;
5672 	int ret;
5673 
5674 	if (syn_skb) {
5675 		/* sk is a request_sock here */
5676 
5677 		if (optname == TCP_BPF_SYN) {
5678 			hdr_start = syn_skb->data;
5679 			ret = tcp_hdrlen(syn_skb);
5680 		} else if (optname == TCP_BPF_SYN_IP) {
5681 			hdr_start = skb_network_header(syn_skb);
5682 			ret = skb_network_header_len(syn_skb) +
5683 				tcp_hdrlen(syn_skb);
5684 		} else {
5685 			/* optname == TCP_BPF_SYN_MAC */
5686 			hdr_start = skb_mac_header(syn_skb);
5687 			ret = skb_mac_header_len(syn_skb) +
5688 				skb_network_header_len(syn_skb) +
5689 				tcp_hdrlen(syn_skb);
5690 		}
5691 	} else {
5692 		struct sock *sk = bpf_sock->sk;
5693 		struct saved_syn *saved_syn;
5694 
5695 		if (sk->sk_state == TCP_NEW_SYN_RECV)
5696 			/* synack retransmit. bpf_sock->syn_skb will
5697 			 * not be available.  It has to resort to
5698 			 * saved_syn (if it is saved).
5699 			 */
5700 			saved_syn = inet_reqsk(sk)->saved_syn;
5701 		else
5702 			saved_syn = tcp_sk(sk)->saved_syn;
5703 
5704 		if (!saved_syn)
5705 			return -ENOENT;
5706 
5707 		if (optname == TCP_BPF_SYN) {
5708 			hdr_start = saved_syn->data +
5709 				saved_syn->mac_hdrlen +
5710 				saved_syn->network_hdrlen;
5711 			ret = saved_syn->tcp_hdrlen;
5712 		} else if (optname == TCP_BPF_SYN_IP) {
5713 			hdr_start = saved_syn->data +
5714 				saved_syn->mac_hdrlen;
5715 			ret = saved_syn->network_hdrlen +
5716 				saved_syn->tcp_hdrlen;
5717 		} else {
5718 			/* optname == TCP_BPF_SYN_MAC */
5719 
5720 			/* TCP_SAVE_SYN may not have saved the mac hdr */
5721 			if (!saved_syn->mac_hdrlen)
5722 				return -ENOENT;
5723 
5724 			hdr_start = saved_syn->data;
5725 			ret = saved_syn->mac_hdrlen +
5726 				saved_syn->network_hdrlen +
5727 				saved_syn->tcp_hdrlen;
5728 		}
5729 	}
5730 
5731 	*start = hdr_start;
5732 	return ret;
5733 }
5734 
BPF_CALL_5(bpf_sock_ops_getsockopt,struct bpf_sock_ops_kern *,bpf_sock,int,level,int,optname,char *,optval,int,optlen)5735 BPF_CALL_5(bpf_sock_ops_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
5736 	   int, level, int, optname, char *, optval, int, optlen)
5737 {
5738 	if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP &&
5739 	    optname >= TCP_BPF_SYN && optname <= TCP_BPF_SYN_MAC) {
5740 		int ret, copy_len = 0;
5741 		const u8 *start;
5742 
5743 		ret = bpf_sock_ops_get_syn(bpf_sock, optname, &start);
5744 		if (ret > 0) {
5745 			copy_len = ret;
5746 			if (optlen < copy_len) {
5747 				copy_len = optlen;
5748 				ret = -ENOSPC;
5749 			}
5750 
5751 			memcpy(optval, start, copy_len);
5752 		}
5753 
5754 		/* Zero out unused buffer at the end */
5755 		memset(optval + copy_len, 0, optlen - copy_len);
5756 
5757 		return ret;
5758 	}
5759 
5760 	return _bpf_getsockopt(bpf_sock->sk, level, optname, optval, optlen);
5761 }
5762 
5763 static const struct bpf_func_proto bpf_sock_ops_getsockopt_proto = {
5764 	.func		= bpf_sock_ops_getsockopt,
5765 	.gpl_only	= false,
5766 	.ret_type	= RET_INTEGER,
5767 	.arg1_type	= ARG_PTR_TO_CTX,
5768 	.arg2_type	= ARG_ANYTHING,
5769 	.arg3_type	= ARG_ANYTHING,
5770 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5771 	.arg5_type	= ARG_CONST_SIZE,
5772 };
5773 
BPF_CALL_2(bpf_sock_ops_cb_flags_set,struct bpf_sock_ops_kern *,bpf_sock,int,argval)5774 BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
5775 	   int, argval)
5776 {
5777 	struct sock *sk = bpf_sock->sk;
5778 	int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
5779 
5780 	if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
5781 		return -EINVAL;
5782 
5783 	tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
5784 
5785 	return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
5786 }
5787 
5788 static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
5789 	.func		= bpf_sock_ops_cb_flags_set,
5790 	.gpl_only	= false,
5791 	.ret_type	= RET_INTEGER,
5792 	.arg1_type	= ARG_PTR_TO_CTX,
5793 	.arg2_type	= ARG_ANYTHING,
5794 };
5795 
5796 const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
5797 EXPORT_SYMBOL_GPL(ipv6_bpf_stub);
5798 
BPF_CALL_3(bpf_bind,struct bpf_sock_addr_kern *,ctx,struct sockaddr *,addr,int,addr_len)5799 BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
5800 	   int, addr_len)
5801 {
5802 #ifdef CONFIG_INET
5803 	struct sock *sk = ctx->sk;
5804 	u32 flags = BIND_FROM_BPF;
5805 	int err;
5806 
5807 	err = -EINVAL;
5808 	if (addr_len < offsetofend(struct sockaddr, sa_family))
5809 		return err;
5810 	if (addr->sa_family == AF_INET) {
5811 		if (addr_len < sizeof(struct sockaddr_in))
5812 			return err;
5813 		if (((struct sockaddr_in *)addr)->sin_port == htons(0))
5814 			flags |= BIND_FORCE_ADDRESS_NO_PORT;
5815 		return __inet_bind(sk, addr, addr_len, flags);
5816 #if IS_ENABLED(CONFIG_IPV6)
5817 	} else if (addr->sa_family == AF_INET6) {
5818 		if (addr_len < SIN6_LEN_RFC2133)
5819 			return err;
5820 		if (((struct sockaddr_in6 *)addr)->sin6_port == htons(0))
5821 			flags |= BIND_FORCE_ADDRESS_NO_PORT;
5822 		/* ipv6_bpf_stub cannot be NULL, since it's called from
5823 		 * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
5824 		 */
5825 		return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, flags);
5826 #endif /* CONFIG_IPV6 */
5827 	}
5828 #endif /* CONFIG_INET */
5829 
5830 	return -EAFNOSUPPORT;
5831 }
5832 
5833 static const struct bpf_func_proto bpf_bind_proto = {
5834 	.func		= bpf_bind,
5835 	.gpl_only	= false,
5836 	.ret_type	= RET_INTEGER,
5837 	.arg1_type	= ARG_PTR_TO_CTX,
5838 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5839 	.arg3_type	= ARG_CONST_SIZE,
5840 };
5841 
5842 #ifdef CONFIG_XFRM
5843 
5844 #if (IS_BUILTIN(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) || \
5845     (IS_MODULE(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
5846 
5847 struct metadata_dst __percpu *xfrm_bpf_md_dst;
5848 EXPORT_SYMBOL_GPL(xfrm_bpf_md_dst);
5849 
5850 #endif
5851 
BPF_CALL_5(bpf_skb_get_xfrm_state,struct sk_buff *,skb,u32,index,struct bpf_xfrm_state *,to,u32,size,u64,flags)5852 BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
5853 	   struct bpf_xfrm_state *, to, u32, size, u64, flags)
5854 {
5855 	const struct sec_path *sp = skb_sec_path(skb);
5856 	const struct xfrm_state *x;
5857 
5858 	if (!sp || unlikely(index >= sp->len || flags))
5859 		goto err_clear;
5860 
5861 	x = sp->xvec[index];
5862 
5863 	if (unlikely(size != sizeof(struct bpf_xfrm_state)))
5864 		goto err_clear;
5865 
5866 	to->reqid = x->props.reqid;
5867 	to->spi = x->id.spi;
5868 	to->family = x->props.family;
5869 	to->ext = 0;
5870 
5871 	if (to->family == AF_INET6) {
5872 		memcpy(to->remote_ipv6, x->props.saddr.a6,
5873 		       sizeof(to->remote_ipv6));
5874 	} else {
5875 		to->remote_ipv4 = x->props.saddr.a4;
5876 		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
5877 	}
5878 
5879 	return 0;
5880 err_clear:
5881 	memset(to, 0, size);
5882 	return -EINVAL;
5883 }
5884 
5885 static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
5886 	.func		= bpf_skb_get_xfrm_state,
5887 	.gpl_only	= false,
5888 	.ret_type	= RET_INTEGER,
5889 	.arg1_type	= ARG_PTR_TO_CTX,
5890 	.arg2_type	= ARG_ANYTHING,
5891 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
5892 	.arg4_type	= ARG_CONST_SIZE,
5893 	.arg5_type	= ARG_ANYTHING,
5894 };
5895 #endif
5896 
5897 #if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
bpf_fib_set_fwd_params(struct bpf_fib_lookup * params,u32 mtu)5898 static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params, u32 mtu)
5899 {
5900 	params->h_vlan_TCI = 0;
5901 	params->h_vlan_proto = 0;
5902 	if (mtu)
5903 		params->mtu_result = mtu; /* union with tot_len */
5904 
5905 	return 0;
5906 }
5907 #endif
5908 
5909 #if IS_ENABLED(CONFIG_INET)
bpf_ipv4_fib_lookup(struct net * net,struct bpf_fib_lookup * params,u32 flags,bool check_mtu)5910 static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
5911 			       u32 flags, bool check_mtu)
5912 {
5913 	struct fib_nh_common *nhc;
5914 	struct in_device *in_dev;
5915 	struct neighbour *neigh;
5916 	struct net_device *dev;
5917 	struct fib_result res;
5918 	struct flowi4 fl4;
5919 	u32 mtu = 0;
5920 	int err;
5921 
5922 	dev = dev_get_by_index_rcu(net, params->ifindex);
5923 	if (unlikely(!dev))
5924 		return -ENODEV;
5925 
5926 	/* verify forwarding is enabled on this interface */
5927 	in_dev = __in_dev_get_rcu(dev);
5928 	if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
5929 		return BPF_FIB_LKUP_RET_FWD_DISABLED;
5930 
5931 	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
5932 		fl4.flowi4_iif = 1;
5933 		fl4.flowi4_oif = params->ifindex;
5934 	} else {
5935 		fl4.flowi4_iif = params->ifindex;
5936 		fl4.flowi4_oif = 0;
5937 	}
5938 	fl4.flowi4_tos = params->tos & INET_DSCP_MASK;
5939 	fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
5940 	fl4.flowi4_flags = 0;
5941 
5942 	fl4.flowi4_proto = params->l4_protocol;
5943 	fl4.daddr = params->ipv4_dst;
5944 	fl4.saddr = params->ipv4_src;
5945 	fl4.fl4_sport = params->sport;
5946 	fl4.fl4_dport = params->dport;
5947 	fl4.flowi4_multipath_hash = 0;
5948 
5949 	if (flags & BPF_FIB_LOOKUP_DIRECT) {
5950 		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
5951 		struct fib_table *tb;
5952 
5953 		if (flags & BPF_FIB_LOOKUP_TBID) {
5954 			tbid = params->tbid;
5955 			/* zero out for vlan output */
5956 			params->tbid = 0;
5957 		}
5958 
5959 		tb = fib_get_table(net, tbid);
5960 		if (unlikely(!tb))
5961 			return BPF_FIB_LKUP_RET_NOT_FWDED;
5962 
5963 		err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
5964 	} else {
5965 		if (flags & BPF_FIB_LOOKUP_MARK)
5966 			fl4.flowi4_mark = params->mark;
5967 		else
5968 			fl4.flowi4_mark = 0;
5969 		fl4.flowi4_secid = 0;
5970 		fl4.flowi4_tun_key.tun_id = 0;
5971 		fl4.flowi4_uid = sock_net_uid(net, NULL);
5972 
5973 		err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
5974 	}
5975 
5976 	if (err) {
5977 		/* map fib lookup errors to RTN_ type */
5978 		if (err == -EINVAL)
5979 			return BPF_FIB_LKUP_RET_BLACKHOLE;
5980 		if (err == -EHOSTUNREACH)
5981 			return BPF_FIB_LKUP_RET_UNREACHABLE;
5982 		if (err == -EACCES)
5983 			return BPF_FIB_LKUP_RET_PROHIBIT;
5984 
5985 		return BPF_FIB_LKUP_RET_NOT_FWDED;
5986 	}
5987 
5988 	if (res.type != RTN_UNICAST)
5989 		return BPF_FIB_LKUP_RET_NOT_FWDED;
5990 
5991 	if (fib_info_num_path(res.fi) > 1)
5992 		fib_select_path(net, &res, &fl4, NULL);
5993 
5994 	if (check_mtu) {
5995 		mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
5996 		if (params->tot_len > mtu) {
5997 			params->mtu_result = mtu; /* union with tot_len */
5998 			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
5999 		}
6000 	}
6001 
6002 	nhc = res.nhc;
6003 
6004 	/* do not handle lwt encaps right now */
6005 	if (nhc->nhc_lwtstate)
6006 		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
6007 
6008 	dev = nhc->nhc_dev;
6009 
6010 	params->rt_metric = res.fi->fib_priority;
6011 	params->ifindex = dev->ifindex;
6012 
6013 	if (flags & BPF_FIB_LOOKUP_SRC)
6014 		params->ipv4_src = fib_result_prefsrc(net, &res);
6015 
6016 	/* xdp and cls_bpf programs are run in RCU-bh so
6017 	 * rcu_read_lock_bh is not needed here
6018 	 */
6019 	if (likely(nhc->nhc_gw_family != AF_INET6)) {
6020 		if (nhc->nhc_gw_family)
6021 			params->ipv4_dst = nhc->nhc_gw.ipv4;
6022 	} else {
6023 		struct in6_addr *dst = (struct in6_addr *)params->ipv6_dst;
6024 
6025 		params->family = AF_INET6;
6026 		*dst = nhc->nhc_gw.ipv6;
6027 	}
6028 
6029 	if (flags & BPF_FIB_LOOKUP_SKIP_NEIGH)
6030 		goto set_fwd_params;
6031 
6032 	if (likely(nhc->nhc_gw_family != AF_INET6))
6033 		neigh = __ipv4_neigh_lookup_noref(dev,
6034 						  (__force u32)params->ipv4_dst);
6035 	else
6036 		neigh = __ipv6_neigh_lookup_noref_stub(dev, params->ipv6_dst);
6037 
6038 	if (!neigh || !(READ_ONCE(neigh->nud_state) & NUD_VALID))
6039 		return BPF_FIB_LKUP_RET_NO_NEIGH;
6040 	memcpy(params->dmac, neigh->ha, ETH_ALEN);
6041 	memcpy(params->smac, dev->dev_addr, ETH_ALEN);
6042 
6043 set_fwd_params:
6044 	return bpf_fib_set_fwd_params(params, mtu);
6045 }
6046 #endif
6047 
6048 #if IS_ENABLED(CONFIG_IPV6)
bpf_ipv6_fib_lookup(struct net * net,struct bpf_fib_lookup * params,u32 flags,bool check_mtu)6049 static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
6050 			       u32 flags, bool check_mtu)
6051 {
6052 	struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
6053 	struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
6054 	struct fib6_result res = {};
6055 	struct neighbour *neigh;
6056 	struct net_device *dev;
6057 	struct inet6_dev *idev;
6058 	struct flowi6 fl6;
6059 	int strict = 0;
6060 	int oif, err;
6061 	u32 mtu = 0;
6062 
6063 	/* link local addresses are never forwarded */
6064 	if (rt6_need_strict(dst) || rt6_need_strict(src))
6065 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6066 
6067 	dev = dev_get_by_index_rcu(net, params->ifindex);
6068 	if (unlikely(!dev))
6069 		return -ENODEV;
6070 
6071 	idev = __in6_dev_get_safely(dev);
6072 	if (unlikely(!idev || !READ_ONCE(idev->cnf.forwarding)))
6073 		return BPF_FIB_LKUP_RET_FWD_DISABLED;
6074 
6075 	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
6076 		fl6.flowi6_iif = 1;
6077 		oif = fl6.flowi6_oif = params->ifindex;
6078 	} else {
6079 		oif = fl6.flowi6_iif = params->ifindex;
6080 		fl6.flowi6_oif = 0;
6081 		strict = RT6_LOOKUP_F_HAS_SADDR;
6082 	}
6083 	fl6.flowlabel = params->flowinfo;
6084 	fl6.flowi6_scope = 0;
6085 	fl6.flowi6_flags = 0;
6086 	fl6.mp_hash = 0;
6087 
6088 	fl6.flowi6_proto = params->l4_protocol;
6089 	fl6.daddr = *dst;
6090 	fl6.saddr = *src;
6091 	fl6.fl6_sport = params->sport;
6092 	fl6.fl6_dport = params->dport;
6093 
6094 	if (flags & BPF_FIB_LOOKUP_DIRECT) {
6095 		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
6096 		struct fib6_table *tb;
6097 
6098 		if (flags & BPF_FIB_LOOKUP_TBID) {
6099 			tbid = params->tbid;
6100 			/* zero out for vlan output */
6101 			params->tbid = 0;
6102 		}
6103 
6104 		tb = ipv6_stub->fib6_get_table(net, tbid);
6105 		if (unlikely(!tb))
6106 			return BPF_FIB_LKUP_RET_NOT_FWDED;
6107 
6108 		err = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, &res,
6109 						   strict);
6110 	} else {
6111 		if (flags & BPF_FIB_LOOKUP_MARK)
6112 			fl6.flowi6_mark = params->mark;
6113 		else
6114 			fl6.flowi6_mark = 0;
6115 		fl6.flowi6_secid = 0;
6116 		fl6.flowi6_tun_key.tun_id = 0;
6117 		fl6.flowi6_uid = sock_net_uid(net, NULL);
6118 
6119 		err = ipv6_stub->fib6_lookup(net, oif, &fl6, &res, strict);
6120 	}
6121 
6122 	if (unlikely(err || IS_ERR_OR_NULL(res.f6i) ||
6123 		     res.f6i == net->ipv6.fib6_null_entry))
6124 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6125 
6126 	switch (res.fib6_type) {
6127 	/* only unicast is forwarded */
6128 	case RTN_UNICAST:
6129 		break;
6130 	case RTN_BLACKHOLE:
6131 		return BPF_FIB_LKUP_RET_BLACKHOLE;
6132 	case RTN_UNREACHABLE:
6133 		return BPF_FIB_LKUP_RET_UNREACHABLE;
6134 	case RTN_PROHIBIT:
6135 		return BPF_FIB_LKUP_RET_PROHIBIT;
6136 	default:
6137 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6138 	}
6139 
6140 	ipv6_stub->fib6_select_path(net, &res, &fl6, fl6.flowi6_oif,
6141 				    fl6.flowi6_oif != 0, NULL, strict);
6142 
6143 	if (check_mtu) {
6144 		mtu = ipv6_stub->ip6_mtu_from_fib6(&res, dst, src);
6145 		if (params->tot_len > mtu) {
6146 			params->mtu_result = mtu; /* union with tot_len */
6147 			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
6148 		}
6149 	}
6150 
6151 	if (res.nh->fib_nh_lws)
6152 		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
6153 
6154 	if (res.nh->fib_nh_gw_family)
6155 		*dst = res.nh->fib_nh_gw6;
6156 
6157 	dev = res.nh->fib_nh_dev;
6158 	params->rt_metric = res.f6i->fib6_metric;
6159 	params->ifindex = dev->ifindex;
6160 
6161 	if (flags & BPF_FIB_LOOKUP_SRC) {
6162 		if (res.f6i->fib6_prefsrc.plen) {
6163 			*src = res.f6i->fib6_prefsrc.addr;
6164 		} else {
6165 			err = ipv6_bpf_stub->ipv6_dev_get_saddr(net, dev,
6166 								&fl6.daddr, 0,
6167 								src);
6168 			if (err)
6169 				return BPF_FIB_LKUP_RET_NO_SRC_ADDR;
6170 		}
6171 	}
6172 
6173 	if (flags & BPF_FIB_LOOKUP_SKIP_NEIGH)
6174 		goto set_fwd_params;
6175 
6176 	/* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
6177 	 * not needed here.
6178 	 */
6179 	neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
6180 	if (!neigh || !(READ_ONCE(neigh->nud_state) & NUD_VALID))
6181 		return BPF_FIB_LKUP_RET_NO_NEIGH;
6182 	memcpy(params->dmac, neigh->ha, ETH_ALEN);
6183 	memcpy(params->smac, dev->dev_addr, ETH_ALEN);
6184 
6185 set_fwd_params:
6186 	return bpf_fib_set_fwd_params(params, mtu);
6187 }
6188 #endif
6189 
6190 #define BPF_FIB_LOOKUP_MASK (BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT | \
6191 			     BPF_FIB_LOOKUP_SKIP_NEIGH | BPF_FIB_LOOKUP_TBID | \
6192 			     BPF_FIB_LOOKUP_SRC | BPF_FIB_LOOKUP_MARK)
6193 
BPF_CALL_4(bpf_xdp_fib_lookup,struct xdp_buff *,ctx,struct bpf_fib_lookup *,params,int,plen,u32,flags)6194 BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
6195 	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
6196 {
6197 	if (plen < sizeof(*params))
6198 		return -EINVAL;
6199 
6200 	if (flags & ~BPF_FIB_LOOKUP_MASK)
6201 		return -EINVAL;
6202 
6203 	switch (params->family) {
6204 #if IS_ENABLED(CONFIG_INET)
6205 	case AF_INET:
6206 		return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
6207 					   flags, true);
6208 #endif
6209 #if IS_ENABLED(CONFIG_IPV6)
6210 	case AF_INET6:
6211 		return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
6212 					   flags, true);
6213 #endif
6214 	}
6215 	return -EAFNOSUPPORT;
6216 }
6217 
6218 static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
6219 	.func		= bpf_xdp_fib_lookup,
6220 	.gpl_only	= true,
6221 	.ret_type	= RET_INTEGER,
6222 	.arg1_type      = ARG_PTR_TO_CTX,
6223 	.arg2_type      = ARG_PTR_TO_MEM,
6224 	.arg3_type      = ARG_CONST_SIZE,
6225 	.arg4_type	= ARG_ANYTHING,
6226 };
6227 
BPF_CALL_4(bpf_skb_fib_lookup,struct sk_buff *,skb,struct bpf_fib_lookup *,params,int,plen,u32,flags)6228 BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
6229 	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
6230 {
6231 	struct net *net = dev_net(skb->dev);
6232 	int rc = -EAFNOSUPPORT;
6233 	bool check_mtu = false;
6234 
6235 	if (plen < sizeof(*params))
6236 		return -EINVAL;
6237 
6238 	if (flags & ~BPF_FIB_LOOKUP_MASK)
6239 		return -EINVAL;
6240 
6241 	if (params->tot_len)
6242 		check_mtu = true;
6243 
6244 	switch (params->family) {
6245 #if IS_ENABLED(CONFIG_INET)
6246 	case AF_INET:
6247 		rc = bpf_ipv4_fib_lookup(net, params, flags, check_mtu);
6248 		break;
6249 #endif
6250 #if IS_ENABLED(CONFIG_IPV6)
6251 	case AF_INET6:
6252 		rc = bpf_ipv6_fib_lookup(net, params, flags, check_mtu);
6253 		break;
6254 #endif
6255 	}
6256 
6257 	if (rc == BPF_FIB_LKUP_RET_SUCCESS && !check_mtu) {
6258 		struct net_device *dev;
6259 
6260 		/* When tot_len isn't provided by user, check skb
6261 		 * against MTU of FIB lookup resulting net_device
6262 		 */
6263 		dev = dev_get_by_index_rcu(net, params->ifindex);
6264 		if (!is_skb_forwardable(dev, skb))
6265 			rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
6266 
6267 		params->mtu_result = dev->mtu; /* union with tot_len */
6268 	}
6269 
6270 	return rc;
6271 }
6272 
6273 static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
6274 	.func		= bpf_skb_fib_lookup,
6275 	.gpl_only	= true,
6276 	.ret_type	= RET_INTEGER,
6277 	.arg1_type      = ARG_PTR_TO_CTX,
6278 	.arg2_type      = ARG_PTR_TO_MEM,
6279 	.arg3_type      = ARG_CONST_SIZE,
6280 	.arg4_type	= ARG_ANYTHING,
6281 };
6282 
__dev_via_ifindex(struct net_device * dev_curr,u32 ifindex)6283 static struct net_device *__dev_via_ifindex(struct net_device *dev_curr,
6284 					    u32 ifindex)
6285 {
6286 	struct net *netns = dev_net(dev_curr);
6287 
6288 	/* Non-redirect use-cases can use ifindex=0 and save ifindex lookup */
6289 	if (ifindex == 0)
6290 		return dev_curr;
6291 
6292 	return dev_get_by_index_rcu(netns, ifindex);
6293 }
6294 
BPF_CALL_5(bpf_skb_check_mtu,struct sk_buff *,skb,u32,ifindex,u32 *,mtu_len,s32,len_diff,u64,flags)6295 BPF_CALL_5(bpf_skb_check_mtu, struct sk_buff *, skb,
6296 	   u32, ifindex, u32 *, mtu_len, s32, len_diff, u64, flags)
6297 {
6298 	int ret = BPF_MTU_CHK_RET_FRAG_NEEDED;
6299 	struct net_device *dev = skb->dev;
6300 	int mtu, dev_len, skb_len;
6301 
6302 	if (unlikely(flags & ~(BPF_MTU_CHK_SEGS)))
6303 		return -EINVAL;
6304 	if (unlikely(flags & BPF_MTU_CHK_SEGS && (len_diff || *mtu_len)))
6305 		return -EINVAL;
6306 
6307 	dev = __dev_via_ifindex(dev, ifindex);
6308 	if (unlikely(!dev))
6309 		return -ENODEV;
6310 
6311 	mtu = READ_ONCE(dev->mtu);
6312 	dev_len = mtu + dev->hard_header_len;
6313 
6314 	/* If set use *mtu_len as input, L3 as iph->tot_len (like fib_lookup) */
6315 	skb_len = *mtu_len ? *mtu_len + dev->hard_header_len : skb->len;
6316 
6317 	skb_len += len_diff; /* minus result pass check */
6318 	if (skb_len <= dev_len) {
6319 		ret = BPF_MTU_CHK_RET_SUCCESS;
6320 		goto out;
6321 	}
6322 	/* At this point, skb->len exceed MTU, but as it include length of all
6323 	 * segments, it can still be below MTU.  The SKB can possibly get
6324 	 * re-segmented in transmit path (see validate_xmit_skb).  Thus, user
6325 	 * must choose if segs are to be MTU checked.
6326 	 */
6327 	if (skb_is_gso(skb)) {
6328 		ret = BPF_MTU_CHK_RET_SUCCESS;
6329 		if (flags & BPF_MTU_CHK_SEGS &&
6330 		    !skb_gso_validate_network_len(skb, mtu))
6331 			ret = BPF_MTU_CHK_RET_SEGS_TOOBIG;
6332 	}
6333 out:
6334 	*mtu_len = mtu;
6335 	return ret;
6336 }
6337 
BPF_CALL_5(bpf_xdp_check_mtu,struct xdp_buff *,xdp,u32,ifindex,u32 *,mtu_len,s32,len_diff,u64,flags)6338 BPF_CALL_5(bpf_xdp_check_mtu, struct xdp_buff *, xdp,
6339 	   u32, ifindex, u32 *, mtu_len, s32, len_diff, u64, flags)
6340 {
6341 	struct net_device *dev = xdp->rxq->dev;
6342 	int xdp_len = xdp->data_end - xdp->data;
6343 	int ret = BPF_MTU_CHK_RET_SUCCESS;
6344 	int mtu, dev_len;
6345 
6346 	/* XDP variant doesn't support multi-buffer segment check (yet) */
6347 	if (unlikely(flags))
6348 		return -EINVAL;
6349 
6350 	dev = __dev_via_ifindex(dev, ifindex);
6351 	if (unlikely(!dev))
6352 		return -ENODEV;
6353 
6354 	mtu = READ_ONCE(dev->mtu);
6355 	dev_len = mtu + dev->hard_header_len;
6356 
6357 	/* Use *mtu_len as input, L3 as iph->tot_len (like fib_lookup) */
6358 	if (*mtu_len)
6359 		xdp_len = *mtu_len + dev->hard_header_len;
6360 
6361 	xdp_len += len_diff; /* minus result pass check */
6362 	if (xdp_len > dev_len)
6363 		ret = BPF_MTU_CHK_RET_FRAG_NEEDED;
6364 
6365 	*mtu_len = mtu;
6366 	return ret;
6367 }
6368 
6369 static const struct bpf_func_proto bpf_skb_check_mtu_proto = {
6370 	.func		= bpf_skb_check_mtu,
6371 	.gpl_only	= true,
6372 	.ret_type	= RET_INTEGER,
6373 	.arg1_type      = ARG_PTR_TO_CTX,
6374 	.arg2_type      = ARG_ANYTHING,
6375 	.arg3_type      = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_WRITE | MEM_ALIGNED,
6376 	.arg3_size	= sizeof(u32),
6377 	.arg4_type      = ARG_ANYTHING,
6378 	.arg5_type      = ARG_ANYTHING,
6379 };
6380 
6381 static const struct bpf_func_proto bpf_xdp_check_mtu_proto = {
6382 	.func		= bpf_xdp_check_mtu,
6383 	.gpl_only	= true,
6384 	.ret_type	= RET_INTEGER,
6385 	.arg1_type      = ARG_PTR_TO_CTX,
6386 	.arg2_type      = ARG_ANYTHING,
6387 	.arg3_type      = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_WRITE | MEM_ALIGNED,
6388 	.arg3_size	= sizeof(u32),
6389 	.arg4_type      = ARG_ANYTHING,
6390 	.arg5_type      = ARG_ANYTHING,
6391 };
6392 
6393 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
bpf_push_seg6_encap(struct sk_buff * skb,u32 type,void * hdr,u32 len)6394 static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
6395 {
6396 	int err;
6397 	struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
6398 
6399 	if (!seg6_validate_srh(srh, len, false))
6400 		return -EINVAL;
6401 
6402 	switch (type) {
6403 	case BPF_LWT_ENCAP_SEG6_INLINE:
6404 		if (skb->protocol != htons(ETH_P_IPV6))
6405 			return -EBADMSG;
6406 
6407 		err = seg6_do_srh_inline(skb, srh);
6408 		break;
6409 	case BPF_LWT_ENCAP_SEG6:
6410 		skb_reset_inner_headers(skb);
6411 		skb->encapsulation = 1;
6412 		err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
6413 		break;
6414 	default:
6415 		return -EINVAL;
6416 	}
6417 
6418 	bpf_compute_data_pointers(skb);
6419 	if (err)
6420 		return err;
6421 
6422 	skb_set_transport_header(skb, sizeof(struct ipv6hdr));
6423 
6424 	return seg6_lookup_nexthop(skb, NULL, 0);
6425 }
6426 #endif /* CONFIG_IPV6_SEG6_BPF */
6427 
6428 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
bpf_push_ip_encap(struct sk_buff * skb,void * hdr,u32 len,bool ingress)6429 static int bpf_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len,
6430 			     bool ingress)
6431 {
6432 	return bpf_lwt_push_ip_encap(skb, hdr, len, ingress);
6433 }
6434 #endif
6435 
BPF_CALL_4(bpf_lwt_in_push_encap,struct sk_buff *,skb,u32,type,void *,hdr,u32,len)6436 BPF_CALL_4(bpf_lwt_in_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
6437 	   u32, len)
6438 {
6439 	switch (type) {
6440 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6441 	case BPF_LWT_ENCAP_SEG6:
6442 	case BPF_LWT_ENCAP_SEG6_INLINE:
6443 		return bpf_push_seg6_encap(skb, type, hdr, len);
6444 #endif
6445 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
6446 	case BPF_LWT_ENCAP_IP:
6447 		return bpf_push_ip_encap(skb, hdr, len, true /* ingress */);
6448 #endif
6449 	default:
6450 		return -EINVAL;
6451 	}
6452 }
6453 
BPF_CALL_4(bpf_lwt_xmit_push_encap,struct sk_buff *,skb,u32,type,void *,hdr,u32,len)6454 BPF_CALL_4(bpf_lwt_xmit_push_encap, struct sk_buff *, skb, u32, type,
6455 	   void *, hdr, u32, len)
6456 {
6457 	switch (type) {
6458 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
6459 	case BPF_LWT_ENCAP_IP:
6460 		return bpf_push_ip_encap(skb, hdr, len, false /* egress */);
6461 #endif
6462 	default:
6463 		return -EINVAL;
6464 	}
6465 }
6466 
6467 static const struct bpf_func_proto bpf_lwt_in_push_encap_proto = {
6468 	.func		= bpf_lwt_in_push_encap,
6469 	.gpl_only	= false,
6470 	.ret_type	= RET_INTEGER,
6471 	.arg1_type	= ARG_PTR_TO_CTX,
6472 	.arg2_type	= ARG_ANYTHING,
6473 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6474 	.arg4_type	= ARG_CONST_SIZE
6475 };
6476 
6477 static const struct bpf_func_proto bpf_lwt_xmit_push_encap_proto = {
6478 	.func		= bpf_lwt_xmit_push_encap,
6479 	.gpl_only	= false,
6480 	.ret_type	= RET_INTEGER,
6481 	.arg1_type	= ARG_PTR_TO_CTX,
6482 	.arg2_type	= ARG_ANYTHING,
6483 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6484 	.arg4_type	= ARG_CONST_SIZE
6485 };
6486 
6487 #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)6488 BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
6489 	   const void *, from, u32, len)
6490 {
6491 	struct seg6_bpf_srh_state *srh_state =
6492 		this_cpu_ptr(&seg6_bpf_srh_states);
6493 	struct ipv6_sr_hdr *srh = srh_state->srh;
6494 	void *srh_tlvs, *srh_end, *ptr;
6495 	int srhoff = 0;
6496 
6497 	lockdep_assert_held(&srh_state->bh_lock);
6498 	if (srh == NULL)
6499 		return -EINVAL;
6500 
6501 	srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
6502 	srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
6503 
6504 	ptr = skb->data + offset;
6505 	if (ptr >= srh_tlvs && ptr + len <= srh_end)
6506 		srh_state->valid = false;
6507 	else if (ptr < (void *)&srh->flags ||
6508 		 ptr + len > (void *)&srh->segments)
6509 		return -EFAULT;
6510 
6511 	if (unlikely(bpf_try_make_writable(skb, offset + len)))
6512 		return -EFAULT;
6513 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
6514 		return -EINVAL;
6515 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
6516 
6517 	memcpy(skb->data + offset, from, len);
6518 	return 0;
6519 }
6520 
6521 static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
6522 	.func		= bpf_lwt_seg6_store_bytes,
6523 	.gpl_only	= false,
6524 	.ret_type	= RET_INTEGER,
6525 	.arg1_type	= ARG_PTR_TO_CTX,
6526 	.arg2_type	= ARG_ANYTHING,
6527 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6528 	.arg4_type	= ARG_CONST_SIZE
6529 };
6530 
bpf_update_srh_state(struct sk_buff * skb)6531 static void bpf_update_srh_state(struct sk_buff *skb)
6532 {
6533 	struct seg6_bpf_srh_state *srh_state =
6534 		this_cpu_ptr(&seg6_bpf_srh_states);
6535 	int srhoff = 0;
6536 
6537 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
6538 		srh_state->srh = NULL;
6539 	} else {
6540 		srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
6541 		srh_state->hdrlen = srh_state->srh->hdrlen << 3;
6542 		srh_state->valid = true;
6543 	}
6544 }
6545 
BPF_CALL_4(bpf_lwt_seg6_action,struct sk_buff *,skb,u32,action,void *,param,u32,param_len)6546 BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
6547 	   u32, action, void *, param, u32, param_len)
6548 {
6549 	struct seg6_bpf_srh_state *srh_state =
6550 		this_cpu_ptr(&seg6_bpf_srh_states);
6551 	int hdroff = 0;
6552 	int err;
6553 
6554 	lockdep_assert_held(&srh_state->bh_lock);
6555 	switch (action) {
6556 	case SEG6_LOCAL_ACTION_END_X:
6557 		if (!seg6_bpf_has_valid_srh(skb))
6558 			return -EBADMSG;
6559 		if (param_len != sizeof(struct in6_addr))
6560 			return -EINVAL;
6561 		return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
6562 	case SEG6_LOCAL_ACTION_END_T:
6563 		if (!seg6_bpf_has_valid_srh(skb))
6564 			return -EBADMSG;
6565 		if (param_len != sizeof(int))
6566 			return -EINVAL;
6567 		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
6568 	case SEG6_LOCAL_ACTION_END_DT6:
6569 		if (!seg6_bpf_has_valid_srh(skb))
6570 			return -EBADMSG;
6571 		if (param_len != sizeof(int))
6572 			return -EINVAL;
6573 
6574 		if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
6575 			return -EBADMSG;
6576 		if (!pskb_pull(skb, hdroff))
6577 			return -EBADMSG;
6578 
6579 		skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
6580 		skb_reset_network_header(skb);
6581 		skb_reset_transport_header(skb);
6582 		skb->encapsulation = 0;
6583 
6584 		bpf_compute_data_pointers(skb);
6585 		bpf_update_srh_state(skb);
6586 		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
6587 	case SEG6_LOCAL_ACTION_END_B6:
6588 		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
6589 			return -EBADMSG;
6590 		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
6591 					  param, param_len);
6592 		if (!err)
6593 			bpf_update_srh_state(skb);
6594 
6595 		return err;
6596 	case SEG6_LOCAL_ACTION_END_B6_ENCAP:
6597 		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
6598 			return -EBADMSG;
6599 		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
6600 					  param, param_len);
6601 		if (!err)
6602 			bpf_update_srh_state(skb);
6603 
6604 		return err;
6605 	default:
6606 		return -EINVAL;
6607 	}
6608 }
6609 
6610 static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
6611 	.func		= bpf_lwt_seg6_action,
6612 	.gpl_only	= false,
6613 	.ret_type	= RET_INTEGER,
6614 	.arg1_type	= ARG_PTR_TO_CTX,
6615 	.arg2_type	= ARG_ANYTHING,
6616 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6617 	.arg4_type	= ARG_CONST_SIZE
6618 };
6619 
BPF_CALL_3(bpf_lwt_seg6_adjust_srh,struct sk_buff *,skb,u32,offset,s32,len)6620 BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
6621 	   s32, len)
6622 {
6623 	struct seg6_bpf_srh_state *srh_state =
6624 		this_cpu_ptr(&seg6_bpf_srh_states);
6625 	struct ipv6_sr_hdr *srh = srh_state->srh;
6626 	void *srh_end, *srh_tlvs, *ptr;
6627 	struct ipv6hdr *hdr;
6628 	int srhoff = 0;
6629 	int ret;
6630 
6631 	lockdep_assert_held(&srh_state->bh_lock);
6632 	if (unlikely(srh == NULL))
6633 		return -EINVAL;
6634 
6635 	srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
6636 			((srh->first_segment + 1) << 4));
6637 	srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
6638 			srh_state->hdrlen);
6639 	ptr = skb->data + offset;
6640 
6641 	if (unlikely(ptr < srh_tlvs || ptr > srh_end))
6642 		return -EFAULT;
6643 	if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
6644 		return -EFAULT;
6645 
6646 	if (len > 0) {
6647 		ret = skb_cow_head(skb, len);
6648 		if (unlikely(ret < 0))
6649 			return ret;
6650 
6651 		ret = bpf_skb_net_hdr_push(skb, offset, len);
6652 	} else {
6653 		ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
6654 	}
6655 
6656 	bpf_compute_data_pointers(skb);
6657 	if (unlikely(ret < 0))
6658 		return ret;
6659 
6660 	hdr = (struct ipv6hdr *)skb->data;
6661 	hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
6662 
6663 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
6664 		return -EINVAL;
6665 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
6666 	srh_state->hdrlen += len;
6667 	srh_state->valid = false;
6668 	return 0;
6669 }
6670 
6671 static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
6672 	.func		= bpf_lwt_seg6_adjust_srh,
6673 	.gpl_only	= false,
6674 	.ret_type	= RET_INTEGER,
6675 	.arg1_type	= ARG_PTR_TO_CTX,
6676 	.arg2_type	= ARG_ANYTHING,
6677 	.arg3_type	= ARG_ANYTHING,
6678 };
6679 #endif /* CONFIG_IPV6_SEG6_BPF */
6680 
6681 #ifdef CONFIG_INET
sk_lookup(struct net * net,struct bpf_sock_tuple * tuple,int dif,int sdif,u8 family,u8 proto)6682 static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple,
6683 			      int dif, int sdif, u8 family, u8 proto)
6684 {
6685 	struct inet_hashinfo *hinfo = net->ipv4.tcp_death_row.hashinfo;
6686 	bool refcounted = false;
6687 	struct sock *sk = NULL;
6688 
6689 	if (family == AF_INET) {
6690 		__be32 src4 = tuple->ipv4.saddr;
6691 		__be32 dst4 = tuple->ipv4.daddr;
6692 
6693 		if (proto == IPPROTO_TCP)
6694 			sk = __inet_lookup(net, hinfo, NULL, 0,
6695 					   src4, tuple->ipv4.sport,
6696 					   dst4, tuple->ipv4.dport,
6697 					   dif, sdif, &refcounted);
6698 		else
6699 			sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport,
6700 					       dst4, tuple->ipv4.dport,
6701 					       dif, sdif, net->ipv4.udp_table, NULL);
6702 #if IS_ENABLED(CONFIG_IPV6)
6703 	} else {
6704 		struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
6705 		struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
6706 
6707 		if (proto == IPPROTO_TCP)
6708 			sk = __inet6_lookup(net, hinfo, NULL, 0,
6709 					    src6, tuple->ipv6.sport,
6710 					    dst6, ntohs(tuple->ipv6.dport),
6711 					    dif, sdif, &refcounted);
6712 		else if (likely(ipv6_bpf_stub))
6713 			sk = ipv6_bpf_stub->udp6_lib_lookup(net,
6714 							    src6, tuple->ipv6.sport,
6715 							    dst6, tuple->ipv6.dport,
6716 							    dif, sdif,
6717 							    net->ipv4.udp_table, NULL);
6718 #endif
6719 	}
6720 
6721 	if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) {
6722 		WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
6723 		sk = NULL;
6724 	}
6725 	return sk;
6726 }
6727 
6728 /* bpf_skc_lookup performs the core lookup for different types of sockets,
6729  * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE.
6730  */
6731 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)6732 __bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6733 		 struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
6734 		 u64 flags, int sdif)
6735 {
6736 	struct sock *sk = NULL;
6737 	struct net *net;
6738 	u8 family;
6739 
6740 	if (len == sizeof(tuple->ipv4))
6741 		family = AF_INET;
6742 	else if (len == sizeof(tuple->ipv6))
6743 		family = AF_INET6;
6744 	else
6745 		return NULL;
6746 
6747 	if (unlikely(flags || !((s32)netns_id < 0 || netns_id <= S32_MAX)))
6748 		goto out;
6749 
6750 	if (sdif < 0) {
6751 		if (family == AF_INET)
6752 			sdif = inet_sdif(skb);
6753 		else
6754 			sdif = inet6_sdif(skb);
6755 	}
6756 
6757 	if ((s32)netns_id < 0) {
6758 		net = caller_net;
6759 		sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
6760 	} else {
6761 		net = get_net_ns_by_id(caller_net, netns_id);
6762 		if (unlikely(!net))
6763 			goto out;
6764 		sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
6765 		put_net(net);
6766 	}
6767 
6768 out:
6769 	return sk;
6770 }
6771 
6772 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)6773 __bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6774 		struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
6775 		u64 flags, int sdif)
6776 {
6777 	struct sock *sk = __bpf_skc_lookup(skb, tuple, len, caller_net,
6778 					   ifindex, proto, netns_id, flags,
6779 					   sdif);
6780 
6781 	if (sk) {
6782 		struct sock *sk2 = sk_to_full_sk(sk);
6783 
6784 		/* sk_to_full_sk() may return (sk)->rsk_listener, so make sure the original sk
6785 		 * sock refcnt is decremented to prevent a request_sock leak.
6786 		 */
6787 		if (sk2 != sk) {
6788 			sock_gen_put(sk);
6789 			/* Ensure there is no need to bump sk2 refcnt */
6790 			if (unlikely(sk2 && !sock_flag(sk2, SOCK_RCU_FREE))) {
6791 				WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
6792 				return NULL;
6793 			}
6794 			sk = sk2;
6795 		}
6796 	}
6797 
6798 	return sk;
6799 }
6800 
6801 static struct sock *
bpf_skc_lookup(struct sk_buff * skb,struct bpf_sock_tuple * tuple,u32 len,u8 proto,u64 netns_id,u64 flags)6802 bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6803 	       u8 proto, u64 netns_id, u64 flags)
6804 {
6805 	struct net *caller_net;
6806 	int ifindex;
6807 
6808 	if (skb->dev) {
6809 		caller_net = dev_net(skb->dev);
6810 		ifindex = skb->dev->ifindex;
6811 	} else {
6812 		caller_net = sock_net(skb->sk);
6813 		ifindex = 0;
6814 	}
6815 
6816 	return __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto,
6817 				netns_id, flags, -1);
6818 }
6819 
6820 static struct sock *
bpf_sk_lookup(struct sk_buff * skb,struct bpf_sock_tuple * tuple,u32 len,u8 proto,u64 netns_id,u64 flags)6821 bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6822 	      u8 proto, u64 netns_id, u64 flags)
6823 {
6824 	struct sock *sk = bpf_skc_lookup(skb, tuple, len, proto, netns_id,
6825 					 flags);
6826 
6827 	if (sk) {
6828 		struct sock *sk2 = sk_to_full_sk(sk);
6829 
6830 		/* sk_to_full_sk() may return (sk)->rsk_listener, so make sure the original sk
6831 		 * sock refcnt is decremented to prevent a request_sock leak.
6832 		 */
6833 		if (sk2 != sk) {
6834 			sock_gen_put(sk);
6835 			/* Ensure there is no need to bump sk2 refcnt */
6836 			if (unlikely(sk2 && !sock_flag(sk2, SOCK_RCU_FREE))) {
6837 				WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
6838 				return NULL;
6839 			}
6840 			sk = sk2;
6841 		}
6842 	}
6843 
6844 	return sk;
6845 }
6846 
BPF_CALL_5(bpf_skc_lookup_tcp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6847 BPF_CALL_5(bpf_skc_lookup_tcp, struct sk_buff *, skb,
6848 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6849 {
6850 	return (unsigned long)bpf_skc_lookup(skb, tuple, len, IPPROTO_TCP,
6851 					     netns_id, flags);
6852 }
6853 
6854 static const struct bpf_func_proto bpf_skc_lookup_tcp_proto = {
6855 	.func		= bpf_skc_lookup_tcp,
6856 	.gpl_only	= false,
6857 	.pkt_access	= true,
6858 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
6859 	.arg1_type	= ARG_PTR_TO_CTX,
6860 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6861 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
6862 	.arg4_type	= ARG_ANYTHING,
6863 	.arg5_type	= ARG_ANYTHING,
6864 };
6865 
BPF_CALL_5(bpf_sk_lookup_tcp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6866 BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb,
6867 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6868 {
6869 	return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP,
6870 					    netns_id, flags);
6871 }
6872 
6873 static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = {
6874 	.func		= bpf_sk_lookup_tcp,
6875 	.gpl_only	= false,
6876 	.pkt_access	= true,
6877 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
6878 	.arg1_type	= ARG_PTR_TO_CTX,
6879 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6880 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
6881 	.arg4_type	= ARG_ANYTHING,
6882 	.arg5_type	= ARG_ANYTHING,
6883 };
6884 
BPF_CALL_5(bpf_sk_lookup_udp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6885 BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb,
6886 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6887 {
6888 	return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP,
6889 					    netns_id, flags);
6890 }
6891 
6892 static const struct bpf_func_proto bpf_sk_lookup_udp_proto = {
6893 	.func		= bpf_sk_lookup_udp,
6894 	.gpl_only	= false,
6895 	.pkt_access	= true,
6896 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
6897 	.arg1_type	= ARG_PTR_TO_CTX,
6898 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6899 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
6900 	.arg4_type	= ARG_ANYTHING,
6901 	.arg5_type	= ARG_ANYTHING,
6902 };
6903 
BPF_CALL_5(bpf_tc_skc_lookup_tcp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6904 BPF_CALL_5(bpf_tc_skc_lookup_tcp, struct sk_buff *, skb,
6905 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6906 {
6907 	struct net_device *dev = skb->dev;
6908 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6909 	struct net *caller_net = dev_net(dev);
6910 
6911 	return (unsigned long)__bpf_skc_lookup(skb, tuple, len, caller_net,
6912 					       ifindex, IPPROTO_TCP, netns_id,
6913 					       flags, sdif);
6914 }
6915 
6916 static const struct bpf_func_proto bpf_tc_skc_lookup_tcp_proto = {
6917 	.func		= bpf_tc_skc_lookup_tcp,
6918 	.gpl_only	= false,
6919 	.pkt_access	= true,
6920 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
6921 	.arg1_type	= ARG_PTR_TO_CTX,
6922 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6923 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
6924 	.arg4_type	= ARG_ANYTHING,
6925 	.arg5_type	= ARG_ANYTHING,
6926 };
6927 
BPF_CALL_5(bpf_tc_sk_lookup_tcp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6928 BPF_CALL_5(bpf_tc_sk_lookup_tcp, struct sk_buff *, skb,
6929 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6930 {
6931 	struct net_device *dev = skb->dev;
6932 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6933 	struct net *caller_net = dev_net(dev);
6934 
6935 	return (unsigned long)__bpf_sk_lookup(skb, tuple, len, caller_net,
6936 					      ifindex, IPPROTO_TCP, netns_id,
6937 					      flags, sdif);
6938 }
6939 
6940 static const struct bpf_func_proto bpf_tc_sk_lookup_tcp_proto = {
6941 	.func		= bpf_tc_sk_lookup_tcp,
6942 	.gpl_only	= false,
6943 	.pkt_access	= true,
6944 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
6945 	.arg1_type	= ARG_PTR_TO_CTX,
6946 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6947 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
6948 	.arg4_type	= ARG_ANYTHING,
6949 	.arg5_type	= ARG_ANYTHING,
6950 };
6951 
BPF_CALL_5(bpf_tc_sk_lookup_udp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6952 BPF_CALL_5(bpf_tc_sk_lookup_udp, struct sk_buff *, skb,
6953 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6954 {
6955 	struct net_device *dev = skb->dev;
6956 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6957 	struct net *caller_net = dev_net(dev);
6958 
6959 	return (unsigned long)__bpf_sk_lookup(skb, tuple, len, caller_net,
6960 					      ifindex, IPPROTO_UDP, netns_id,
6961 					      flags, sdif);
6962 }
6963 
6964 static const struct bpf_func_proto bpf_tc_sk_lookup_udp_proto = {
6965 	.func		= bpf_tc_sk_lookup_udp,
6966 	.gpl_only	= false,
6967 	.pkt_access	= true,
6968 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
6969 	.arg1_type	= ARG_PTR_TO_CTX,
6970 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6971 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
6972 	.arg4_type	= ARG_ANYTHING,
6973 	.arg5_type	= ARG_ANYTHING,
6974 };
6975 
BPF_CALL_1(bpf_sk_release,struct sock *,sk)6976 BPF_CALL_1(bpf_sk_release, struct sock *, sk)
6977 {
6978 	if (sk && sk_is_refcounted(sk))
6979 		sock_gen_put(sk);
6980 	return 0;
6981 }
6982 
6983 static const struct bpf_func_proto bpf_sk_release_proto = {
6984 	.func		= bpf_sk_release,
6985 	.gpl_only	= false,
6986 	.ret_type	= RET_INTEGER,
6987 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON | OBJ_RELEASE,
6988 };
6989 
BPF_CALL_5(bpf_xdp_sk_lookup_udp,struct xdp_buff *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u32,netns_id,u64,flags)6990 BPF_CALL_5(bpf_xdp_sk_lookup_udp, struct xdp_buff *, ctx,
6991 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
6992 {
6993 	struct net_device *dev = ctx->rxq->dev;
6994 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6995 	struct net *caller_net = dev_net(dev);
6996 
6997 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
6998 					      ifindex, IPPROTO_UDP, netns_id,
6999 					      flags, sdif);
7000 }
7001 
7002 static const struct bpf_func_proto bpf_xdp_sk_lookup_udp_proto = {
7003 	.func           = bpf_xdp_sk_lookup_udp,
7004 	.gpl_only       = false,
7005 	.pkt_access     = true,
7006 	.ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
7007 	.arg1_type      = ARG_PTR_TO_CTX,
7008 	.arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7009 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
7010 	.arg4_type      = ARG_ANYTHING,
7011 	.arg5_type      = ARG_ANYTHING,
7012 };
7013 
BPF_CALL_5(bpf_xdp_skc_lookup_tcp,struct xdp_buff *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u32,netns_id,u64,flags)7014 BPF_CALL_5(bpf_xdp_skc_lookup_tcp, struct xdp_buff *, ctx,
7015 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
7016 {
7017 	struct net_device *dev = ctx->rxq->dev;
7018 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7019 	struct net *caller_net = dev_net(dev);
7020 
7021 	return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, caller_net,
7022 					       ifindex, IPPROTO_TCP, netns_id,
7023 					       flags, sdif);
7024 }
7025 
7026 static const struct bpf_func_proto bpf_xdp_skc_lookup_tcp_proto = {
7027 	.func           = bpf_xdp_skc_lookup_tcp,
7028 	.gpl_only       = false,
7029 	.pkt_access     = true,
7030 	.ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
7031 	.arg1_type      = ARG_PTR_TO_CTX,
7032 	.arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7033 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
7034 	.arg4_type      = ARG_ANYTHING,
7035 	.arg5_type      = ARG_ANYTHING,
7036 };
7037 
BPF_CALL_5(bpf_xdp_sk_lookup_tcp,struct xdp_buff *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u32,netns_id,u64,flags)7038 BPF_CALL_5(bpf_xdp_sk_lookup_tcp, struct xdp_buff *, ctx,
7039 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
7040 {
7041 	struct net_device *dev = ctx->rxq->dev;
7042 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7043 	struct net *caller_net = dev_net(dev);
7044 
7045 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
7046 					      ifindex, IPPROTO_TCP, netns_id,
7047 					      flags, sdif);
7048 }
7049 
7050 static const struct bpf_func_proto bpf_xdp_sk_lookup_tcp_proto = {
7051 	.func           = bpf_xdp_sk_lookup_tcp,
7052 	.gpl_only       = false,
7053 	.pkt_access     = true,
7054 	.ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
7055 	.arg1_type      = ARG_PTR_TO_CTX,
7056 	.arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7057 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
7058 	.arg4_type      = ARG_ANYTHING,
7059 	.arg5_type      = ARG_ANYTHING,
7060 };
7061 
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)7062 BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
7063 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7064 {
7065 	return (unsigned long)__bpf_skc_lookup(NULL, tuple, len,
7066 					       sock_net(ctx->sk), 0,
7067 					       IPPROTO_TCP, netns_id, flags,
7068 					       -1);
7069 }
7070 
7071 static const struct bpf_func_proto bpf_sock_addr_skc_lookup_tcp_proto = {
7072 	.func		= bpf_sock_addr_skc_lookup_tcp,
7073 	.gpl_only	= false,
7074 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
7075 	.arg1_type	= ARG_PTR_TO_CTX,
7076 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7077 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7078 	.arg4_type	= ARG_ANYTHING,
7079 	.arg5_type	= ARG_ANYTHING,
7080 };
7081 
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)7082 BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
7083 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7084 {
7085 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
7086 					      sock_net(ctx->sk), 0, IPPROTO_TCP,
7087 					      netns_id, flags, -1);
7088 }
7089 
7090 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_tcp_proto = {
7091 	.func		= bpf_sock_addr_sk_lookup_tcp,
7092 	.gpl_only	= false,
7093 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7094 	.arg1_type	= ARG_PTR_TO_CTX,
7095 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7096 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7097 	.arg4_type	= ARG_ANYTHING,
7098 	.arg5_type	= ARG_ANYTHING,
7099 };
7100 
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)7101 BPF_CALL_5(bpf_sock_addr_sk_lookup_udp, struct bpf_sock_addr_kern *, ctx,
7102 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7103 {
7104 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
7105 					      sock_net(ctx->sk), 0, IPPROTO_UDP,
7106 					      netns_id, flags, -1);
7107 }
7108 
7109 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_udp_proto = {
7110 	.func		= bpf_sock_addr_sk_lookup_udp,
7111 	.gpl_only	= false,
7112 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7113 	.arg1_type	= ARG_PTR_TO_CTX,
7114 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7115 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7116 	.arg4_type	= ARG_ANYTHING,
7117 	.arg5_type	= ARG_ANYTHING,
7118 };
7119 
bpf_tcp_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)7120 bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
7121 				  struct bpf_insn_access_aux *info)
7122 {
7123 	if (off < 0 || off >= offsetofend(struct bpf_tcp_sock,
7124 					  icsk_retransmits))
7125 		return false;
7126 
7127 	if (off % size != 0)
7128 		return false;
7129 
7130 	switch (off) {
7131 	case offsetof(struct bpf_tcp_sock, bytes_received):
7132 	case offsetof(struct bpf_tcp_sock, bytes_acked):
7133 		return size == sizeof(__u64);
7134 	default:
7135 		return size == sizeof(__u32);
7136 	}
7137 }
7138 
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)7139 u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
7140 				    const struct bpf_insn *si,
7141 				    struct bpf_insn *insn_buf,
7142 				    struct bpf_prog *prog, u32 *target_size)
7143 {
7144 	struct bpf_insn *insn = insn_buf;
7145 
7146 #define BPF_TCP_SOCK_GET_COMMON(FIELD)					\
7147 	do {								\
7148 		BUILD_BUG_ON(sizeof_field(struct tcp_sock, FIELD) >	\
7149 			     sizeof_field(struct bpf_tcp_sock, FIELD));	\
7150 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_sock, FIELD),\
7151 				      si->dst_reg, si->src_reg,		\
7152 				      offsetof(struct tcp_sock, FIELD)); \
7153 	} while (0)
7154 
7155 #define BPF_INET_SOCK_GET_COMMON(FIELD)					\
7156 	do {								\
7157 		BUILD_BUG_ON(sizeof_field(struct inet_connection_sock,	\
7158 					  FIELD) >			\
7159 			     sizeof_field(struct bpf_tcp_sock, FIELD));	\
7160 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			\
7161 					struct inet_connection_sock,	\
7162 					FIELD),				\
7163 				      si->dst_reg, si->src_reg,		\
7164 				      offsetof(				\
7165 					struct inet_connection_sock,	\
7166 					FIELD));			\
7167 	} while (0)
7168 
7169 	BTF_TYPE_EMIT(struct bpf_tcp_sock);
7170 
7171 	switch (si->off) {
7172 	case offsetof(struct bpf_tcp_sock, rtt_min):
7173 		BUILD_BUG_ON(sizeof_field(struct tcp_sock, rtt_min) !=
7174 			     sizeof(struct minmax));
7175 		BUILD_BUG_ON(sizeof(struct minmax) <
7176 			     sizeof(struct minmax_sample));
7177 
7178 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7179 				      offsetof(struct tcp_sock, rtt_min) +
7180 				      offsetof(struct minmax_sample, v));
7181 		break;
7182 	case offsetof(struct bpf_tcp_sock, snd_cwnd):
7183 		BPF_TCP_SOCK_GET_COMMON(snd_cwnd);
7184 		break;
7185 	case offsetof(struct bpf_tcp_sock, srtt_us):
7186 		BPF_TCP_SOCK_GET_COMMON(srtt_us);
7187 		break;
7188 	case offsetof(struct bpf_tcp_sock, snd_ssthresh):
7189 		BPF_TCP_SOCK_GET_COMMON(snd_ssthresh);
7190 		break;
7191 	case offsetof(struct bpf_tcp_sock, rcv_nxt):
7192 		BPF_TCP_SOCK_GET_COMMON(rcv_nxt);
7193 		break;
7194 	case offsetof(struct bpf_tcp_sock, snd_nxt):
7195 		BPF_TCP_SOCK_GET_COMMON(snd_nxt);
7196 		break;
7197 	case offsetof(struct bpf_tcp_sock, snd_una):
7198 		BPF_TCP_SOCK_GET_COMMON(snd_una);
7199 		break;
7200 	case offsetof(struct bpf_tcp_sock, mss_cache):
7201 		BPF_TCP_SOCK_GET_COMMON(mss_cache);
7202 		break;
7203 	case offsetof(struct bpf_tcp_sock, ecn_flags):
7204 		BPF_TCP_SOCK_GET_COMMON(ecn_flags);
7205 		break;
7206 	case offsetof(struct bpf_tcp_sock, rate_delivered):
7207 		BPF_TCP_SOCK_GET_COMMON(rate_delivered);
7208 		break;
7209 	case offsetof(struct bpf_tcp_sock, rate_interval_us):
7210 		BPF_TCP_SOCK_GET_COMMON(rate_interval_us);
7211 		break;
7212 	case offsetof(struct bpf_tcp_sock, packets_out):
7213 		BPF_TCP_SOCK_GET_COMMON(packets_out);
7214 		break;
7215 	case offsetof(struct bpf_tcp_sock, retrans_out):
7216 		BPF_TCP_SOCK_GET_COMMON(retrans_out);
7217 		break;
7218 	case offsetof(struct bpf_tcp_sock, total_retrans):
7219 		BPF_TCP_SOCK_GET_COMMON(total_retrans);
7220 		break;
7221 	case offsetof(struct bpf_tcp_sock, segs_in):
7222 		BPF_TCP_SOCK_GET_COMMON(segs_in);
7223 		break;
7224 	case offsetof(struct bpf_tcp_sock, data_segs_in):
7225 		BPF_TCP_SOCK_GET_COMMON(data_segs_in);
7226 		break;
7227 	case offsetof(struct bpf_tcp_sock, segs_out):
7228 		BPF_TCP_SOCK_GET_COMMON(segs_out);
7229 		break;
7230 	case offsetof(struct bpf_tcp_sock, data_segs_out):
7231 		BPF_TCP_SOCK_GET_COMMON(data_segs_out);
7232 		break;
7233 	case offsetof(struct bpf_tcp_sock, lost_out):
7234 		BPF_TCP_SOCK_GET_COMMON(lost_out);
7235 		break;
7236 	case offsetof(struct bpf_tcp_sock, sacked_out):
7237 		BPF_TCP_SOCK_GET_COMMON(sacked_out);
7238 		break;
7239 	case offsetof(struct bpf_tcp_sock, bytes_received):
7240 		BPF_TCP_SOCK_GET_COMMON(bytes_received);
7241 		break;
7242 	case offsetof(struct bpf_tcp_sock, bytes_acked):
7243 		BPF_TCP_SOCK_GET_COMMON(bytes_acked);
7244 		break;
7245 	case offsetof(struct bpf_tcp_sock, dsack_dups):
7246 		BPF_TCP_SOCK_GET_COMMON(dsack_dups);
7247 		break;
7248 	case offsetof(struct bpf_tcp_sock, delivered):
7249 		BPF_TCP_SOCK_GET_COMMON(delivered);
7250 		break;
7251 	case offsetof(struct bpf_tcp_sock, delivered_ce):
7252 		BPF_TCP_SOCK_GET_COMMON(delivered_ce);
7253 		break;
7254 	case offsetof(struct bpf_tcp_sock, icsk_retransmits):
7255 		BPF_INET_SOCK_GET_COMMON(icsk_retransmits);
7256 		break;
7257 	}
7258 
7259 	return insn - insn_buf;
7260 }
7261 
BPF_CALL_1(bpf_tcp_sock,struct sock *,sk)7262 BPF_CALL_1(bpf_tcp_sock, struct sock *, sk)
7263 {
7264 	if (sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP)
7265 		return (unsigned long)sk;
7266 
7267 	return (unsigned long)NULL;
7268 }
7269 
7270 const struct bpf_func_proto bpf_tcp_sock_proto = {
7271 	.func		= bpf_tcp_sock,
7272 	.gpl_only	= false,
7273 	.ret_type	= RET_PTR_TO_TCP_SOCK_OR_NULL,
7274 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
7275 };
7276 
BPF_CALL_1(bpf_get_listener_sock,struct sock *,sk)7277 BPF_CALL_1(bpf_get_listener_sock, struct sock *, sk)
7278 {
7279 	sk = sk_to_full_sk(sk);
7280 
7281 	if (sk && sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_RCU_FREE))
7282 		return (unsigned long)sk;
7283 
7284 	return (unsigned long)NULL;
7285 }
7286 
7287 static const struct bpf_func_proto bpf_get_listener_sock_proto = {
7288 	.func		= bpf_get_listener_sock,
7289 	.gpl_only	= false,
7290 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7291 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
7292 };
7293 
BPF_CALL_1(bpf_skb_ecn_set_ce,struct sk_buff *,skb)7294 BPF_CALL_1(bpf_skb_ecn_set_ce, struct sk_buff *, skb)
7295 {
7296 	unsigned int iphdr_len;
7297 
7298 	switch (skb_protocol(skb, true)) {
7299 	case cpu_to_be16(ETH_P_IP):
7300 		iphdr_len = sizeof(struct iphdr);
7301 		break;
7302 	case cpu_to_be16(ETH_P_IPV6):
7303 		iphdr_len = sizeof(struct ipv6hdr);
7304 		break;
7305 	default:
7306 		return 0;
7307 	}
7308 
7309 	if (skb_headlen(skb) < iphdr_len)
7310 		return 0;
7311 
7312 	if (skb_cloned(skb) && !skb_clone_writable(skb, iphdr_len))
7313 		return 0;
7314 
7315 	return INET_ECN_set_ce(skb);
7316 }
7317 
bpf_xdp_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)7318 bool bpf_xdp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
7319 				  struct bpf_insn_access_aux *info)
7320 {
7321 	if (off < 0 || off >= offsetofend(struct bpf_xdp_sock, queue_id))
7322 		return false;
7323 
7324 	if (off % size != 0)
7325 		return false;
7326 
7327 	switch (off) {
7328 	default:
7329 		return size == sizeof(__u32);
7330 	}
7331 }
7332 
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)7333 u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
7334 				    const struct bpf_insn *si,
7335 				    struct bpf_insn *insn_buf,
7336 				    struct bpf_prog *prog, u32 *target_size)
7337 {
7338 	struct bpf_insn *insn = insn_buf;
7339 
7340 #define BPF_XDP_SOCK_GET(FIELD)						\
7341 	do {								\
7342 		BUILD_BUG_ON(sizeof_field(struct xdp_sock, FIELD) >	\
7343 			     sizeof_field(struct bpf_xdp_sock, FIELD));	\
7344 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_sock, FIELD),\
7345 				      si->dst_reg, si->src_reg,		\
7346 				      offsetof(struct xdp_sock, FIELD)); \
7347 	} while (0)
7348 
7349 	switch (si->off) {
7350 	case offsetof(struct bpf_xdp_sock, queue_id):
7351 		BPF_XDP_SOCK_GET(queue_id);
7352 		break;
7353 	}
7354 
7355 	return insn - insn_buf;
7356 }
7357 
7358 static const struct bpf_func_proto bpf_skb_ecn_set_ce_proto = {
7359 	.func           = bpf_skb_ecn_set_ce,
7360 	.gpl_only       = false,
7361 	.ret_type       = RET_INTEGER,
7362 	.arg1_type      = ARG_PTR_TO_CTX,
7363 };
7364 
BPF_CALL_5(bpf_tcp_check_syncookie,struct sock *,sk,void *,iph,u32,iph_len,struct tcphdr *,th,u32,th_len)7365 BPF_CALL_5(bpf_tcp_check_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
7366 	   struct tcphdr *, th, u32, th_len)
7367 {
7368 #ifdef CONFIG_SYN_COOKIES
7369 	int ret;
7370 
7371 	if (unlikely(!sk || th_len < sizeof(*th)))
7372 		return -EINVAL;
7373 
7374 	/* sk_listener() allows TCP_NEW_SYN_RECV, which makes no sense here. */
7375 	if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
7376 		return -EINVAL;
7377 
7378 	if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies))
7379 		return -EINVAL;
7380 
7381 	if (!th->ack || th->rst || th->syn)
7382 		return -ENOENT;
7383 
7384 	if (unlikely(iph_len < sizeof(struct iphdr)))
7385 		return -EINVAL;
7386 
7387 	if (tcp_synq_no_recent_overflow(sk))
7388 		return -ENOENT;
7389 
7390 	/* Both struct iphdr and struct ipv6hdr have the version field at the
7391 	 * same offset so we can cast to the shorter header (struct iphdr).
7392 	 */
7393 	switch (((struct iphdr *)iph)->version) {
7394 	case 4:
7395 		if (sk->sk_family == AF_INET6 && ipv6_only_sock(sk))
7396 			return -EINVAL;
7397 
7398 		ret = __cookie_v4_check((struct iphdr *)iph, th);
7399 		break;
7400 
7401 #if IS_BUILTIN(CONFIG_IPV6)
7402 	case 6:
7403 		if (unlikely(iph_len < sizeof(struct ipv6hdr)))
7404 			return -EINVAL;
7405 
7406 		if (sk->sk_family != AF_INET6)
7407 			return -EINVAL;
7408 
7409 		ret = __cookie_v6_check((struct ipv6hdr *)iph, th);
7410 		break;
7411 #endif /* CONFIG_IPV6 */
7412 
7413 	default:
7414 		return -EPROTONOSUPPORT;
7415 	}
7416 
7417 	if (ret > 0)
7418 		return 0;
7419 
7420 	return -ENOENT;
7421 #else
7422 	return -ENOTSUPP;
7423 #endif
7424 }
7425 
7426 static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = {
7427 	.func		= bpf_tcp_check_syncookie,
7428 	.gpl_only	= true,
7429 	.pkt_access	= true,
7430 	.ret_type	= RET_INTEGER,
7431 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
7432 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7433 	.arg3_type	= ARG_CONST_SIZE,
7434 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7435 	.arg5_type	= ARG_CONST_SIZE,
7436 };
7437 
BPF_CALL_5(bpf_tcp_gen_syncookie,struct sock *,sk,void *,iph,u32,iph_len,struct tcphdr *,th,u32,th_len)7438 BPF_CALL_5(bpf_tcp_gen_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
7439 	   struct tcphdr *, th, u32, th_len)
7440 {
7441 #ifdef CONFIG_SYN_COOKIES
7442 	u32 cookie;
7443 	u16 mss;
7444 
7445 	if (unlikely(!sk || th_len < sizeof(*th) || th_len != th->doff * 4))
7446 		return -EINVAL;
7447 
7448 	if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
7449 		return -EINVAL;
7450 
7451 	if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies))
7452 		return -ENOENT;
7453 
7454 	if (!th->syn || th->ack || th->fin || th->rst)
7455 		return -EINVAL;
7456 
7457 	if (unlikely(iph_len < sizeof(struct iphdr)))
7458 		return -EINVAL;
7459 
7460 	/* Both struct iphdr and struct ipv6hdr have the version field at the
7461 	 * same offset so we can cast to the shorter header (struct iphdr).
7462 	 */
7463 	switch (((struct iphdr *)iph)->version) {
7464 	case 4:
7465 		if (sk->sk_family == AF_INET6 && ipv6_only_sock(sk))
7466 			return -EINVAL;
7467 
7468 		mss = tcp_v4_get_syncookie(sk, iph, th, &cookie);
7469 		break;
7470 
7471 #if IS_BUILTIN(CONFIG_IPV6)
7472 	case 6:
7473 		if (unlikely(iph_len < sizeof(struct ipv6hdr)))
7474 			return -EINVAL;
7475 
7476 		if (sk->sk_family != AF_INET6)
7477 			return -EINVAL;
7478 
7479 		mss = tcp_v6_get_syncookie(sk, iph, th, &cookie);
7480 		break;
7481 #endif /* CONFIG_IPV6 */
7482 
7483 	default:
7484 		return -EPROTONOSUPPORT;
7485 	}
7486 	if (mss == 0)
7487 		return -ENOENT;
7488 
7489 	return cookie | ((u64)mss << 32);
7490 #else
7491 	return -EOPNOTSUPP;
7492 #endif /* CONFIG_SYN_COOKIES */
7493 }
7494 
7495 static const struct bpf_func_proto bpf_tcp_gen_syncookie_proto = {
7496 	.func		= bpf_tcp_gen_syncookie,
7497 	.gpl_only	= true, /* __cookie_v*_init_sequence() is GPL */
7498 	.pkt_access	= true,
7499 	.ret_type	= RET_INTEGER,
7500 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
7501 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7502 	.arg3_type	= ARG_CONST_SIZE,
7503 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7504 	.arg5_type	= ARG_CONST_SIZE,
7505 };
7506 
BPF_CALL_3(bpf_sk_assign,struct sk_buff *,skb,struct sock *,sk,u64,flags)7507 BPF_CALL_3(bpf_sk_assign, struct sk_buff *, skb, struct sock *, sk, u64, flags)
7508 {
7509 	if (!sk || flags != 0)
7510 		return -EINVAL;
7511 	if (!skb_at_tc_ingress(skb))
7512 		return -EOPNOTSUPP;
7513 	if (unlikely(dev_net(skb->dev) != sock_net(sk)))
7514 		return -ENETUNREACH;
7515 	if (sk_unhashed(sk))
7516 		return -EOPNOTSUPP;
7517 	if (sk_is_refcounted(sk) &&
7518 	    unlikely(!refcount_inc_not_zero(&sk->sk_refcnt)))
7519 		return -ENOENT;
7520 
7521 	skb_orphan(skb);
7522 	skb->sk = sk;
7523 	skb->destructor = sock_pfree;
7524 
7525 	return 0;
7526 }
7527 
7528 static const struct bpf_func_proto bpf_sk_assign_proto = {
7529 	.func		= bpf_sk_assign,
7530 	.gpl_only	= false,
7531 	.ret_type	= RET_INTEGER,
7532 	.arg1_type      = ARG_PTR_TO_CTX,
7533 	.arg2_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
7534 	.arg3_type	= ARG_ANYTHING,
7535 };
7536 
bpf_search_tcp_opt(const u8 * op,const u8 * opend,u8 search_kind,const u8 * magic,u8 magic_len,bool * eol)7537 static const u8 *bpf_search_tcp_opt(const u8 *op, const u8 *opend,
7538 				    u8 search_kind, const u8 *magic,
7539 				    u8 magic_len, bool *eol)
7540 {
7541 	u8 kind, kind_len;
7542 
7543 	*eol = false;
7544 
7545 	while (op < opend) {
7546 		kind = op[0];
7547 
7548 		if (kind == TCPOPT_EOL) {
7549 			*eol = true;
7550 			return ERR_PTR(-ENOMSG);
7551 		} else if (kind == TCPOPT_NOP) {
7552 			op++;
7553 			continue;
7554 		}
7555 
7556 		if (opend - op < 2 || opend - op < op[1] || op[1] < 2)
7557 			/* Something is wrong in the received header.
7558 			 * Follow the TCP stack's tcp_parse_options()
7559 			 * and just bail here.
7560 			 */
7561 			return ERR_PTR(-EFAULT);
7562 
7563 		kind_len = op[1];
7564 		if (search_kind == kind) {
7565 			if (!magic_len)
7566 				return op;
7567 
7568 			if (magic_len > kind_len - 2)
7569 				return ERR_PTR(-ENOMSG);
7570 
7571 			if (!memcmp(&op[2], magic, magic_len))
7572 				return op;
7573 		}
7574 
7575 		op += kind_len;
7576 	}
7577 
7578 	return ERR_PTR(-ENOMSG);
7579 }
7580 
BPF_CALL_4(bpf_sock_ops_load_hdr_opt,struct bpf_sock_ops_kern *,bpf_sock,void *,search_res,u32,len,u64,flags)7581 BPF_CALL_4(bpf_sock_ops_load_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
7582 	   void *, search_res, u32, len, u64, flags)
7583 {
7584 	bool eol, load_syn = flags & BPF_LOAD_HDR_OPT_TCP_SYN;
7585 	const u8 *op, *opend, *magic, *search = search_res;
7586 	u8 search_kind, search_len, copy_len, magic_len;
7587 	int ret;
7588 
7589 	/* 2 byte is the minimal option len except TCPOPT_NOP and
7590 	 * TCPOPT_EOL which are useless for the bpf prog to learn
7591 	 * and this helper disallow loading them also.
7592 	 */
7593 	if (len < 2 || flags & ~BPF_LOAD_HDR_OPT_TCP_SYN)
7594 		return -EINVAL;
7595 
7596 	search_kind = search[0];
7597 	search_len = search[1];
7598 
7599 	if (search_len > len || search_kind == TCPOPT_NOP ||
7600 	    search_kind == TCPOPT_EOL)
7601 		return -EINVAL;
7602 
7603 	if (search_kind == TCPOPT_EXP || search_kind == 253) {
7604 		/* 16 or 32 bit magic.  +2 for kind and kind length */
7605 		if (search_len != 4 && search_len != 6)
7606 			return -EINVAL;
7607 		magic = &search[2];
7608 		magic_len = search_len - 2;
7609 	} else {
7610 		if (search_len)
7611 			return -EINVAL;
7612 		magic = NULL;
7613 		magic_len = 0;
7614 	}
7615 
7616 	if (load_syn) {
7617 		ret = bpf_sock_ops_get_syn(bpf_sock, TCP_BPF_SYN, &op);
7618 		if (ret < 0)
7619 			return ret;
7620 
7621 		opend = op + ret;
7622 		op += sizeof(struct tcphdr);
7623 	} else {
7624 		if (!bpf_sock->skb ||
7625 		    bpf_sock->op == BPF_SOCK_OPS_HDR_OPT_LEN_CB)
7626 			/* This bpf_sock->op cannot call this helper */
7627 			return -EPERM;
7628 
7629 		opend = bpf_sock->skb_data_end;
7630 		op = bpf_sock->skb->data + sizeof(struct tcphdr);
7631 	}
7632 
7633 	op = bpf_search_tcp_opt(op, opend, search_kind, magic, magic_len,
7634 				&eol);
7635 	if (IS_ERR(op))
7636 		return PTR_ERR(op);
7637 
7638 	copy_len = op[1];
7639 	ret = copy_len;
7640 	if (copy_len > len) {
7641 		ret = -ENOSPC;
7642 		copy_len = len;
7643 	}
7644 
7645 	memcpy(search_res, op, copy_len);
7646 	return ret;
7647 }
7648 
7649 static const struct bpf_func_proto bpf_sock_ops_load_hdr_opt_proto = {
7650 	.func		= bpf_sock_ops_load_hdr_opt,
7651 	.gpl_only	= false,
7652 	.ret_type	= RET_INTEGER,
7653 	.arg1_type	= ARG_PTR_TO_CTX,
7654 	.arg2_type	= ARG_PTR_TO_MEM | MEM_WRITE,
7655 	.arg3_type	= ARG_CONST_SIZE,
7656 	.arg4_type	= ARG_ANYTHING,
7657 };
7658 
BPF_CALL_4(bpf_sock_ops_store_hdr_opt,struct bpf_sock_ops_kern *,bpf_sock,const void *,from,u32,len,u64,flags)7659 BPF_CALL_4(bpf_sock_ops_store_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
7660 	   const void *, from, u32, len, u64, flags)
7661 {
7662 	u8 new_kind, new_kind_len, magic_len = 0, *opend;
7663 	const u8 *op, *new_op, *magic = NULL;
7664 	struct sk_buff *skb;
7665 	bool eol;
7666 
7667 	if (bpf_sock->op != BPF_SOCK_OPS_WRITE_HDR_OPT_CB)
7668 		return -EPERM;
7669 
7670 	if (len < 2 || flags)
7671 		return -EINVAL;
7672 
7673 	new_op = from;
7674 	new_kind = new_op[0];
7675 	new_kind_len = new_op[1];
7676 
7677 	if (new_kind_len > len || new_kind == TCPOPT_NOP ||
7678 	    new_kind == TCPOPT_EOL)
7679 		return -EINVAL;
7680 
7681 	if (new_kind_len > bpf_sock->remaining_opt_len)
7682 		return -ENOSPC;
7683 
7684 	/* 253 is another experimental kind */
7685 	if (new_kind == TCPOPT_EXP || new_kind == 253)  {
7686 		if (new_kind_len < 4)
7687 			return -EINVAL;
7688 		/* Match for the 2 byte magic also.
7689 		 * RFC 6994: the magic could be 2 or 4 bytes.
7690 		 * Hence, matching by 2 byte only is on the
7691 		 * conservative side but it is the right
7692 		 * thing to do for the 'search-for-duplication'
7693 		 * purpose.
7694 		 */
7695 		magic = &new_op[2];
7696 		magic_len = 2;
7697 	}
7698 
7699 	/* Check for duplication */
7700 	skb = bpf_sock->skb;
7701 	op = skb->data + sizeof(struct tcphdr);
7702 	opend = bpf_sock->skb_data_end;
7703 
7704 	op = bpf_search_tcp_opt(op, opend, new_kind, magic, magic_len,
7705 				&eol);
7706 	if (!IS_ERR(op))
7707 		return -EEXIST;
7708 
7709 	if (PTR_ERR(op) != -ENOMSG)
7710 		return PTR_ERR(op);
7711 
7712 	if (eol)
7713 		/* The option has been ended.  Treat it as no more
7714 		 * header option can be written.
7715 		 */
7716 		return -ENOSPC;
7717 
7718 	/* No duplication found.  Store the header option. */
7719 	memcpy(opend, from, new_kind_len);
7720 
7721 	bpf_sock->remaining_opt_len -= new_kind_len;
7722 	bpf_sock->skb_data_end += new_kind_len;
7723 
7724 	return 0;
7725 }
7726 
7727 static const struct bpf_func_proto bpf_sock_ops_store_hdr_opt_proto = {
7728 	.func		= bpf_sock_ops_store_hdr_opt,
7729 	.gpl_only	= false,
7730 	.ret_type	= RET_INTEGER,
7731 	.arg1_type	= ARG_PTR_TO_CTX,
7732 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7733 	.arg3_type	= ARG_CONST_SIZE,
7734 	.arg4_type	= ARG_ANYTHING,
7735 };
7736 
BPF_CALL_3(bpf_sock_ops_reserve_hdr_opt,struct bpf_sock_ops_kern *,bpf_sock,u32,len,u64,flags)7737 BPF_CALL_3(bpf_sock_ops_reserve_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
7738 	   u32, len, u64, flags)
7739 {
7740 	if (bpf_sock->op != BPF_SOCK_OPS_HDR_OPT_LEN_CB)
7741 		return -EPERM;
7742 
7743 	if (flags || len < 2)
7744 		return -EINVAL;
7745 
7746 	if (len > bpf_sock->remaining_opt_len)
7747 		return -ENOSPC;
7748 
7749 	bpf_sock->remaining_opt_len -= len;
7750 
7751 	return 0;
7752 }
7753 
7754 static const struct bpf_func_proto bpf_sock_ops_reserve_hdr_opt_proto = {
7755 	.func		= bpf_sock_ops_reserve_hdr_opt,
7756 	.gpl_only	= false,
7757 	.ret_type	= RET_INTEGER,
7758 	.arg1_type	= ARG_PTR_TO_CTX,
7759 	.arg2_type	= ARG_ANYTHING,
7760 	.arg3_type	= ARG_ANYTHING,
7761 };
7762 
BPF_CALL_3(bpf_skb_set_tstamp,struct sk_buff *,skb,u64,tstamp,u32,tstamp_type)7763 BPF_CALL_3(bpf_skb_set_tstamp, struct sk_buff *, skb,
7764 	   u64, tstamp, u32, tstamp_type)
7765 {
7766 	/* skb_clear_delivery_time() is done for inet protocol */
7767 	if (skb->protocol != htons(ETH_P_IP) &&
7768 	    skb->protocol != htons(ETH_P_IPV6))
7769 		return -EOPNOTSUPP;
7770 
7771 	switch (tstamp_type) {
7772 	case BPF_SKB_CLOCK_REALTIME:
7773 		skb->tstamp = tstamp;
7774 		skb->tstamp_type = SKB_CLOCK_REALTIME;
7775 		break;
7776 	case BPF_SKB_CLOCK_MONOTONIC:
7777 		if (!tstamp)
7778 			return -EINVAL;
7779 		skb->tstamp = tstamp;
7780 		skb->tstamp_type = SKB_CLOCK_MONOTONIC;
7781 		break;
7782 	case BPF_SKB_CLOCK_TAI:
7783 		if (!tstamp)
7784 			return -EINVAL;
7785 		skb->tstamp = tstamp;
7786 		skb->tstamp_type = SKB_CLOCK_TAI;
7787 		break;
7788 	default:
7789 		return -EINVAL;
7790 	}
7791 
7792 	return 0;
7793 }
7794 
7795 static const struct bpf_func_proto bpf_skb_set_tstamp_proto = {
7796 	.func           = bpf_skb_set_tstamp,
7797 	.gpl_only       = false,
7798 	.ret_type       = RET_INTEGER,
7799 	.arg1_type      = ARG_PTR_TO_CTX,
7800 	.arg2_type      = ARG_ANYTHING,
7801 	.arg3_type      = ARG_ANYTHING,
7802 };
7803 
7804 #ifdef CONFIG_SYN_COOKIES
BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv4,struct iphdr *,iph,struct tcphdr *,th,u32,th_len)7805 BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv4, struct iphdr *, iph,
7806 	   struct tcphdr *, th, u32, th_len)
7807 {
7808 	u32 cookie;
7809 	u16 mss;
7810 
7811 	if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
7812 		return -EINVAL;
7813 
7814 	mss = tcp_parse_mss_option(th, 0) ?: TCP_MSS_DEFAULT;
7815 	cookie = __cookie_v4_init_sequence(iph, th, &mss);
7816 
7817 	return cookie | ((u64)mss << 32);
7818 }
7819 
7820 static const struct bpf_func_proto bpf_tcp_raw_gen_syncookie_ipv4_proto = {
7821 	.func		= bpf_tcp_raw_gen_syncookie_ipv4,
7822 	.gpl_only	= true, /* __cookie_v4_init_sequence() is GPL */
7823 	.pkt_access	= true,
7824 	.ret_type	= RET_INTEGER,
7825 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7826 	.arg1_size	= sizeof(struct iphdr),
7827 	.arg2_type	= ARG_PTR_TO_MEM,
7828 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7829 };
7830 
BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv6,struct ipv6hdr *,iph,struct tcphdr *,th,u32,th_len)7831 BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv6, struct ipv6hdr *, iph,
7832 	   struct tcphdr *, th, u32, th_len)
7833 {
7834 #if IS_BUILTIN(CONFIG_IPV6)
7835 	const u16 mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) -
7836 		sizeof(struct ipv6hdr);
7837 	u32 cookie;
7838 	u16 mss;
7839 
7840 	if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
7841 		return -EINVAL;
7842 
7843 	mss = tcp_parse_mss_option(th, 0) ?: mss_clamp;
7844 	cookie = __cookie_v6_init_sequence(iph, th, &mss);
7845 
7846 	return cookie | ((u64)mss << 32);
7847 #else
7848 	return -EPROTONOSUPPORT;
7849 #endif
7850 }
7851 
7852 static const struct bpf_func_proto bpf_tcp_raw_gen_syncookie_ipv6_proto = {
7853 	.func		= bpf_tcp_raw_gen_syncookie_ipv6,
7854 	.gpl_only	= true, /* __cookie_v6_init_sequence() is GPL */
7855 	.pkt_access	= true,
7856 	.ret_type	= RET_INTEGER,
7857 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7858 	.arg1_size	= sizeof(struct ipv6hdr),
7859 	.arg2_type	= ARG_PTR_TO_MEM,
7860 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7861 };
7862 
BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv4,struct iphdr *,iph,struct tcphdr *,th)7863 BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv4, struct iphdr *, iph,
7864 	   struct tcphdr *, th)
7865 {
7866 	if (__cookie_v4_check(iph, th) > 0)
7867 		return 0;
7868 
7869 	return -EACCES;
7870 }
7871 
7872 static const struct bpf_func_proto bpf_tcp_raw_check_syncookie_ipv4_proto = {
7873 	.func		= bpf_tcp_raw_check_syncookie_ipv4,
7874 	.gpl_only	= true, /* __cookie_v4_check is GPL */
7875 	.pkt_access	= true,
7876 	.ret_type	= RET_INTEGER,
7877 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7878 	.arg1_size	= sizeof(struct iphdr),
7879 	.arg2_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7880 	.arg2_size	= sizeof(struct tcphdr),
7881 };
7882 
BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv6,struct ipv6hdr *,iph,struct tcphdr *,th)7883 BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv6, struct ipv6hdr *, iph,
7884 	   struct tcphdr *, th)
7885 {
7886 #if IS_BUILTIN(CONFIG_IPV6)
7887 	if (__cookie_v6_check(iph, th) > 0)
7888 		return 0;
7889 
7890 	return -EACCES;
7891 #else
7892 	return -EPROTONOSUPPORT;
7893 #endif
7894 }
7895 
7896 static const struct bpf_func_proto bpf_tcp_raw_check_syncookie_ipv6_proto = {
7897 	.func		= bpf_tcp_raw_check_syncookie_ipv6,
7898 	.gpl_only	= true, /* __cookie_v6_check is GPL */
7899 	.pkt_access	= true,
7900 	.ret_type	= RET_INTEGER,
7901 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7902 	.arg1_size	= sizeof(struct ipv6hdr),
7903 	.arg2_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7904 	.arg2_size	= sizeof(struct tcphdr),
7905 };
7906 #endif /* CONFIG_SYN_COOKIES */
7907 
7908 #endif /* CONFIG_INET */
7909 
bpf_helper_changes_pkt_data(enum bpf_func_id func_id)7910 bool bpf_helper_changes_pkt_data(enum bpf_func_id func_id)
7911 {
7912 	switch (func_id) {
7913 	case BPF_FUNC_clone_redirect:
7914 	case BPF_FUNC_l3_csum_replace:
7915 	case BPF_FUNC_l4_csum_replace:
7916 	case BPF_FUNC_lwt_push_encap:
7917 	case BPF_FUNC_lwt_seg6_action:
7918 	case BPF_FUNC_lwt_seg6_adjust_srh:
7919 	case BPF_FUNC_lwt_seg6_store_bytes:
7920 	case BPF_FUNC_msg_pop_data:
7921 	case BPF_FUNC_msg_pull_data:
7922 	case BPF_FUNC_msg_push_data:
7923 	case BPF_FUNC_skb_adjust_room:
7924 	case BPF_FUNC_skb_change_head:
7925 	case BPF_FUNC_skb_change_proto:
7926 	case BPF_FUNC_skb_change_tail:
7927 	case BPF_FUNC_skb_pull_data:
7928 	case BPF_FUNC_skb_store_bytes:
7929 	case BPF_FUNC_skb_vlan_pop:
7930 	case BPF_FUNC_skb_vlan_push:
7931 	case BPF_FUNC_store_hdr_opt:
7932 	case BPF_FUNC_xdp_adjust_head:
7933 	case BPF_FUNC_xdp_adjust_meta:
7934 	case BPF_FUNC_xdp_adjust_tail:
7935 	/* tail-called program could call any of the above */
7936 	case BPF_FUNC_tail_call:
7937 		return true;
7938 	default:
7939 		return false;
7940 	}
7941 }
7942 
7943 const struct bpf_func_proto bpf_event_output_data_proto __weak;
7944 const struct bpf_func_proto bpf_sk_storage_get_cg_sock_proto __weak;
7945 
7946 static const struct bpf_func_proto *
sock_filter_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)7947 sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
7948 {
7949 	const struct bpf_func_proto *func_proto;
7950 
7951 	func_proto = cgroup_common_func_proto(func_id, prog);
7952 	if (func_proto)
7953 		return func_proto;
7954 
7955 	func_proto = cgroup_current_func_proto(func_id, prog);
7956 	if (func_proto)
7957 		return func_proto;
7958 
7959 	switch (func_id) {
7960 	case BPF_FUNC_get_socket_cookie:
7961 		return &bpf_get_socket_cookie_sock_proto;
7962 	case BPF_FUNC_get_netns_cookie:
7963 		return &bpf_get_netns_cookie_sock_proto;
7964 	case BPF_FUNC_perf_event_output:
7965 		return &bpf_event_output_data_proto;
7966 	case BPF_FUNC_sk_storage_get:
7967 		return &bpf_sk_storage_get_cg_sock_proto;
7968 	case BPF_FUNC_ktime_get_coarse_ns:
7969 		return &bpf_ktime_get_coarse_ns_proto;
7970 	default:
7971 		return bpf_base_func_proto(func_id, prog);
7972 	}
7973 }
7974 
7975 static const struct bpf_func_proto *
sock_addr_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)7976 sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
7977 {
7978 	const struct bpf_func_proto *func_proto;
7979 
7980 	func_proto = cgroup_common_func_proto(func_id, prog);
7981 	if (func_proto)
7982 		return func_proto;
7983 
7984 	func_proto = cgroup_current_func_proto(func_id, prog);
7985 	if (func_proto)
7986 		return func_proto;
7987 
7988 	switch (func_id) {
7989 	case BPF_FUNC_bind:
7990 		switch (prog->expected_attach_type) {
7991 		case BPF_CGROUP_INET4_CONNECT:
7992 		case BPF_CGROUP_INET6_CONNECT:
7993 			return &bpf_bind_proto;
7994 		default:
7995 			return NULL;
7996 		}
7997 	case BPF_FUNC_get_socket_cookie:
7998 		return &bpf_get_socket_cookie_sock_addr_proto;
7999 	case BPF_FUNC_get_netns_cookie:
8000 		return &bpf_get_netns_cookie_sock_addr_proto;
8001 	case BPF_FUNC_perf_event_output:
8002 		return &bpf_event_output_data_proto;
8003 #ifdef CONFIG_INET
8004 	case BPF_FUNC_sk_lookup_tcp:
8005 		return &bpf_sock_addr_sk_lookup_tcp_proto;
8006 	case BPF_FUNC_sk_lookup_udp:
8007 		return &bpf_sock_addr_sk_lookup_udp_proto;
8008 	case BPF_FUNC_sk_release:
8009 		return &bpf_sk_release_proto;
8010 	case BPF_FUNC_skc_lookup_tcp:
8011 		return &bpf_sock_addr_skc_lookup_tcp_proto;
8012 #endif /* CONFIG_INET */
8013 	case BPF_FUNC_sk_storage_get:
8014 		return &bpf_sk_storage_get_proto;
8015 	case BPF_FUNC_sk_storage_delete:
8016 		return &bpf_sk_storage_delete_proto;
8017 	case BPF_FUNC_setsockopt:
8018 		switch (prog->expected_attach_type) {
8019 		case BPF_CGROUP_INET4_BIND:
8020 		case BPF_CGROUP_INET6_BIND:
8021 		case BPF_CGROUP_INET4_CONNECT:
8022 		case BPF_CGROUP_INET6_CONNECT:
8023 		case BPF_CGROUP_UNIX_CONNECT:
8024 		case BPF_CGROUP_UDP4_RECVMSG:
8025 		case BPF_CGROUP_UDP6_RECVMSG:
8026 		case BPF_CGROUP_UNIX_RECVMSG:
8027 		case BPF_CGROUP_UDP4_SENDMSG:
8028 		case BPF_CGROUP_UDP6_SENDMSG:
8029 		case BPF_CGROUP_UNIX_SENDMSG:
8030 		case BPF_CGROUP_INET4_GETPEERNAME:
8031 		case BPF_CGROUP_INET6_GETPEERNAME:
8032 		case BPF_CGROUP_UNIX_GETPEERNAME:
8033 		case BPF_CGROUP_INET4_GETSOCKNAME:
8034 		case BPF_CGROUP_INET6_GETSOCKNAME:
8035 		case BPF_CGROUP_UNIX_GETSOCKNAME:
8036 			return &bpf_sock_addr_setsockopt_proto;
8037 		default:
8038 			return NULL;
8039 		}
8040 	case BPF_FUNC_getsockopt:
8041 		switch (prog->expected_attach_type) {
8042 		case BPF_CGROUP_INET4_BIND:
8043 		case BPF_CGROUP_INET6_BIND:
8044 		case BPF_CGROUP_INET4_CONNECT:
8045 		case BPF_CGROUP_INET6_CONNECT:
8046 		case BPF_CGROUP_UNIX_CONNECT:
8047 		case BPF_CGROUP_UDP4_RECVMSG:
8048 		case BPF_CGROUP_UDP6_RECVMSG:
8049 		case BPF_CGROUP_UNIX_RECVMSG:
8050 		case BPF_CGROUP_UDP4_SENDMSG:
8051 		case BPF_CGROUP_UDP6_SENDMSG:
8052 		case BPF_CGROUP_UNIX_SENDMSG:
8053 		case BPF_CGROUP_INET4_GETPEERNAME:
8054 		case BPF_CGROUP_INET6_GETPEERNAME:
8055 		case BPF_CGROUP_UNIX_GETPEERNAME:
8056 		case BPF_CGROUP_INET4_GETSOCKNAME:
8057 		case BPF_CGROUP_INET6_GETSOCKNAME:
8058 		case BPF_CGROUP_UNIX_GETSOCKNAME:
8059 			return &bpf_sock_addr_getsockopt_proto;
8060 		default:
8061 			return NULL;
8062 		}
8063 	default:
8064 		return bpf_sk_base_func_proto(func_id, prog);
8065 	}
8066 }
8067 
8068 static const struct bpf_func_proto *
sk_filter_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8069 sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8070 {
8071 	switch (func_id) {
8072 	case BPF_FUNC_skb_load_bytes:
8073 		return &bpf_skb_load_bytes_proto;
8074 	case BPF_FUNC_skb_load_bytes_relative:
8075 		return &bpf_skb_load_bytes_relative_proto;
8076 	case BPF_FUNC_get_socket_cookie:
8077 		return &bpf_get_socket_cookie_proto;
8078 	case BPF_FUNC_get_socket_uid:
8079 		return &bpf_get_socket_uid_proto;
8080 	case BPF_FUNC_perf_event_output:
8081 		return &bpf_skb_event_output_proto;
8082 	default:
8083 		return bpf_sk_base_func_proto(func_id, prog);
8084 	}
8085 }
8086 
8087 const struct bpf_func_proto bpf_sk_storage_get_proto __weak;
8088 const struct bpf_func_proto bpf_sk_storage_delete_proto __weak;
8089 
8090 static const struct bpf_func_proto *
cg_skb_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8091 cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8092 {
8093 	const struct bpf_func_proto *func_proto;
8094 
8095 	func_proto = cgroup_common_func_proto(func_id, prog);
8096 	if (func_proto)
8097 		return func_proto;
8098 
8099 	switch (func_id) {
8100 	case BPF_FUNC_sk_fullsock:
8101 		return &bpf_sk_fullsock_proto;
8102 	case BPF_FUNC_sk_storage_get:
8103 		return &bpf_sk_storage_get_proto;
8104 	case BPF_FUNC_sk_storage_delete:
8105 		return &bpf_sk_storage_delete_proto;
8106 	case BPF_FUNC_perf_event_output:
8107 		return &bpf_skb_event_output_proto;
8108 #ifdef CONFIG_SOCK_CGROUP_DATA
8109 	case BPF_FUNC_skb_cgroup_id:
8110 		return &bpf_skb_cgroup_id_proto;
8111 	case BPF_FUNC_skb_ancestor_cgroup_id:
8112 		return &bpf_skb_ancestor_cgroup_id_proto;
8113 	case BPF_FUNC_sk_cgroup_id:
8114 		return &bpf_sk_cgroup_id_proto;
8115 	case BPF_FUNC_sk_ancestor_cgroup_id:
8116 		return &bpf_sk_ancestor_cgroup_id_proto;
8117 #endif
8118 #ifdef CONFIG_INET
8119 	case BPF_FUNC_sk_lookup_tcp:
8120 		return &bpf_sk_lookup_tcp_proto;
8121 	case BPF_FUNC_sk_lookup_udp:
8122 		return &bpf_sk_lookup_udp_proto;
8123 	case BPF_FUNC_sk_release:
8124 		return &bpf_sk_release_proto;
8125 	case BPF_FUNC_skc_lookup_tcp:
8126 		return &bpf_skc_lookup_tcp_proto;
8127 	case BPF_FUNC_tcp_sock:
8128 		return &bpf_tcp_sock_proto;
8129 	case BPF_FUNC_get_listener_sock:
8130 		return &bpf_get_listener_sock_proto;
8131 	case BPF_FUNC_skb_ecn_set_ce:
8132 		return &bpf_skb_ecn_set_ce_proto;
8133 #endif
8134 	default:
8135 		return sk_filter_func_proto(func_id, prog);
8136 	}
8137 }
8138 
8139 static const struct bpf_func_proto *
tc_cls_act_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8140 tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8141 {
8142 	switch (func_id) {
8143 	case BPF_FUNC_skb_store_bytes:
8144 		return &bpf_skb_store_bytes_proto;
8145 	case BPF_FUNC_skb_load_bytes:
8146 		return &bpf_skb_load_bytes_proto;
8147 	case BPF_FUNC_skb_load_bytes_relative:
8148 		return &bpf_skb_load_bytes_relative_proto;
8149 	case BPF_FUNC_skb_pull_data:
8150 		return &bpf_skb_pull_data_proto;
8151 	case BPF_FUNC_csum_diff:
8152 		return &bpf_csum_diff_proto;
8153 	case BPF_FUNC_csum_update:
8154 		return &bpf_csum_update_proto;
8155 	case BPF_FUNC_csum_level:
8156 		return &bpf_csum_level_proto;
8157 	case BPF_FUNC_l3_csum_replace:
8158 		return &bpf_l3_csum_replace_proto;
8159 	case BPF_FUNC_l4_csum_replace:
8160 		return &bpf_l4_csum_replace_proto;
8161 	case BPF_FUNC_clone_redirect:
8162 		return &bpf_clone_redirect_proto;
8163 	case BPF_FUNC_get_cgroup_classid:
8164 		return &bpf_get_cgroup_classid_proto;
8165 	case BPF_FUNC_skb_vlan_push:
8166 		return &bpf_skb_vlan_push_proto;
8167 	case BPF_FUNC_skb_vlan_pop:
8168 		return &bpf_skb_vlan_pop_proto;
8169 	case BPF_FUNC_skb_change_proto:
8170 		return &bpf_skb_change_proto_proto;
8171 	case BPF_FUNC_skb_change_type:
8172 		return &bpf_skb_change_type_proto;
8173 	case BPF_FUNC_skb_adjust_room:
8174 		return &bpf_skb_adjust_room_proto;
8175 	case BPF_FUNC_skb_change_tail:
8176 		return &bpf_skb_change_tail_proto;
8177 	case BPF_FUNC_skb_change_head:
8178 		return &bpf_skb_change_head_proto;
8179 	case BPF_FUNC_skb_get_tunnel_key:
8180 		return &bpf_skb_get_tunnel_key_proto;
8181 	case BPF_FUNC_skb_set_tunnel_key:
8182 		return bpf_get_skb_set_tunnel_proto(func_id);
8183 	case BPF_FUNC_skb_get_tunnel_opt:
8184 		return &bpf_skb_get_tunnel_opt_proto;
8185 	case BPF_FUNC_skb_set_tunnel_opt:
8186 		return bpf_get_skb_set_tunnel_proto(func_id);
8187 	case BPF_FUNC_redirect:
8188 		return &bpf_redirect_proto;
8189 	case BPF_FUNC_redirect_neigh:
8190 		return &bpf_redirect_neigh_proto;
8191 	case BPF_FUNC_redirect_peer:
8192 		return &bpf_redirect_peer_proto;
8193 	case BPF_FUNC_get_route_realm:
8194 		return &bpf_get_route_realm_proto;
8195 	case BPF_FUNC_get_hash_recalc:
8196 		return &bpf_get_hash_recalc_proto;
8197 	case BPF_FUNC_set_hash_invalid:
8198 		return &bpf_set_hash_invalid_proto;
8199 	case BPF_FUNC_set_hash:
8200 		return &bpf_set_hash_proto;
8201 	case BPF_FUNC_perf_event_output:
8202 		return &bpf_skb_event_output_proto;
8203 	case BPF_FUNC_get_smp_processor_id:
8204 		return &bpf_get_smp_processor_id_proto;
8205 	case BPF_FUNC_skb_under_cgroup:
8206 		return &bpf_skb_under_cgroup_proto;
8207 	case BPF_FUNC_get_socket_cookie:
8208 		return &bpf_get_socket_cookie_proto;
8209 	case BPF_FUNC_get_netns_cookie:
8210 		return &bpf_get_netns_cookie_proto;
8211 	case BPF_FUNC_get_socket_uid:
8212 		return &bpf_get_socket_uid_proto;
8213 	case BPF_FUNC_fib_lookup:
8214 		return &bpf_skb_fib_lookup_proto;
8215 	case BPF_FUNC_check_mtu:
8216 		return &bpf_skb_check_mtu_proto;
8217 	case BPF_FUNC_sk_fullsock:
8218 		return &bpf_sk_fullsock_proto;
8219 	case BPF_FUNC_sk_storage_get:
8220 		return &bpf_sk_storage_get_proto;
8221 	case BPF_FUNC_sk_storage_delete:
8222 		return &bpf_sk_storage_delete_proto;
8223 #ifdef CONFIG_XFRM
8224 	case BPF_FUNC_skb_get_xfrm_state:
8225 		return &bpf_skb_get_xfrm_state_proto;
8226 #endif
8227 #ifdef CONFIG_CGROUP_NET_CLASSID
8228 	case BPF_FUNC_skb_cgroup_classid:
8229 		return &bpf_skb_cgroup_classid_proto;
8230 #endif
8231 #ifdef CONFIG_SOCK_CGROUP_DATA
8232 	case BPF_FUNC_skb_cgroup_id:
8233 		return &bpf_skb_cgroup_id_proto;
8234 	case BPF_FUNC_skb_ancestor_cgroup_id:
8235 		return &bpf_skb_ancestor_cgroup_id_proto;
8236 #endif
8237 #ifdef CONFIG_INET
8238 	case BPF_FUNC_sk_lookup_tcp:
8239 		return &bpf_tc_sk_lookup_tcp_proto;
8240 	case BPF_FUNC_sk_lookup_udp:
8241 		return &bpf_tc_sk_lookup_udp_proto;
8242 	case BPF_FUNC_sk_release:
8243 		return &bpf_sk_release_proto;
8244 	case BPF_FUNC_tcp_sock:
8245 		return &bpf_tcp_sock_proto;
8246 	case BPF_FUNC_get_listener_sock:
8247 		return &bpf_get_listener_sock_proto;
8248 	case BPF_FUNC_skc_lookup_tcp:
8249 		return &bpf_tc_skc_lookup_tcp_proto;
8250 	case BPF_FUNC_tcp_check_syncookie:
8251 		return &bpf_tcp_check_syncookie_proto;
8252 	case BPF_FUNC_skb_ecn_set_ce:
8253 		return &bpf_skb_ecn_set_ce_proto;
8254 	case BPF_FUNC_tcp_gen_syncookie:
8255 		return &bpf_tcp_gen_syncookie_proto;
8256 	case BPF_FUNC_sk_assign:
8257 		return &bpf_sk_assign_proto;
8258 	case BPF_FUNC_skb_set_tstamp:
8259 		return &bpf_skb_set_tstamp_proto;
8260 #ifdef CONFIG_SYN_COOKIES
8261 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv4:
8262 		return &bpf_tcp_raw_gen_syncookie_ipv4_proto;
8263 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv6:
8264 		return &bpf_tcp_raw_gen_syncookie_ipv6_proto;
8265 	case BPF_FUNC_tcp_raw_check_syncookie_ipv4:
8266 		return &bpf_tcp_raw_check_syncookie_ipv4_proto;
8267 	case BPF_FUNC_tcp_raw_check_syncookie_ipv6:
8268 		return &bpf_tcp_raw_check_syncookie_ipv6_proto;
8269 #endif
8270 #endif
8271 	default:
8272 		return bpf_sk_base_func_proto(func_id, prog);
8273 	}
8274 }
8275 
8276 static const struct bpf_func_proto *
xdp_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8277 xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8278 {
8279 	switch (func_id) {
8280 	case BPF_FUNC_perf_event_output:
8281 		return &bpf_xdp_event_output_proto;
8282 	case BPF_FUNC_get_smp_processor_id:
8283 		return &bpf_get_smp_processor_id_proto;
8284 	case BPF_FUNC_csum_diff:
8285 		return &bpf_csum_diff_proto;
8286 	case BPF_FUNC_xdp_adjust_head:
8287 		return &bpf_xdp_adjust_head_proto;
8288 	case BPF_FUNC_xdp_adjust_meta:
8289 		return &bpf_xdp_adjust_meta_proto;
8290 	case BPF_FUNC_redirect:
8291 		return &bpf_xdp_redirect_proto;
8292 	case BPF_FUNC_redirect_map:
8293 		return &bpf_xdp_redirect_map_proto;
8294 	case BPF_FUNC_xdp_adjust_tail:
8295 		return &bpf_xdp_adjust_tail_proto;
8296 	case BPF_FUNC_xdp_get_buff_len:
8297 		return &bpf_xdp_get_buff_len_proto;
8298 	case BPF_FUNC_xdp_load_bytes:
8299 		return &bpf_xdp_load_bytes_proto;
8300 	case BPF_FUNC_xdp_store_bytes:
8301 		return &bpf_xdp_store_bytes_proto;
8302 	case BPF_FUNC_fib_lookup:
8303 		return &bpf_xdp_fib_lookup_proto;
8304 	case BPF_FUNC_check_mtu:
8305 		return &bpf_xdp_check_mtu_proto;
8306 #ifdef CONFIG_INET
8307 	case BPF_FUNC_sk_lookup_udp:
8308 		return &bpf_xdp_sk_lookup_udp_proto;
8309 	case BPF_FUNC_sk_lookup_tcp:
8310 		return &bpf_xdp_sk_lookup_tcp_proto;
8311 	case BPF_FUNC_sk_release:
8312 		return &bpf_sk_release_proto;
8313 	case BPF_FUNC_skc_lookup_tcp:
8314 		return &bpf_xdp_skc_lookup_tcp_proto;
8315 	case BPF_FUNC_tcp_check_syncookie:
8316 		return &bpf_tcp_check_syncookie_proto;
8317 	case BPF_FUNC_tcp_gen_syncookie:
8318 		return &bpf_tcp_gen_syncookie_proto;
8319 #ifdef CONFIG_SYN_COOKIES
8320 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv4:
8321 		return &bpf_tcp_raw_gen_syncookie_ipv4_proto;
8322 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv6:
8323 		return &bpf_tcp_raw_gen_syncookie_ipv6_proto;
8324 	case BPF_FUNC_tcp_raw_check_syncookie_ipv4:
8325 		return &bpf_tcp_raw_check_syncookie_ipv4_proto;
8326 	case BPF_FUNC_tcp_raw_check_syncookie_ipv6:
8327 		return &bpf_tcp_raw_check_syncookie_ipv6_proto;
8328 #endif
8329 #endif
8330 	default:
8331 		return bpf_sk_base_func_proto(func_id, prog);
8332 	}
8333 
8334 #if IS_MODULE(CONFIG_NF_CONNTRACK) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)
8335 	/* The nf_conn___init type is used in the NF_CONNTRACK kfuncs. The
8336 	 * kfuncs are defined in two different modules, and we want to be able
8337 	 * to use them interchangeably with the same BTF type ID. Because modules
8338 	 * can't de-duplicate BTF IDs between each other, we need the type to be
8339 	 * referenced in the vmlinux BTF or the verifier will get confused about
8340 	 * the different types. So we add this dummy type reference which will
8341 	 * be included in vmlinux BTF, allowing both modules to refer to the
8342 	 * same type ID.
8343 	 */
8344 	BTF_TYPE_EMIT(struct nf_conn___init);
8345 #endif
8346 }
8347 
8348 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
8349 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
8350 
8351 static const struct bpf_func_proto *
sock_ops_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8352 sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8353 {
8354 	const struct bpf_func_proto *func_proto;
8355 
8356 	func_proto = cgroup_common_func_proto(func_id, prog);
8357 	if (func_proto)
8358 		return func_proto;
8359 
8360 	switch (func_id) {
8361 	case BPF_FUNC_setsockopt:
8362 		return &bpf_sock_ops_setsockopt_proto;
8363 	case BPF_FUNC_getsockopt:
8364 		return &bpf_sock_ops_getsockopt_proto;
8365 	case BPF_FUNC_sock_ops_cb_flags_set:
8366 		return &bpf_sock_ops_cb_flags_set_proto;
8367 	case BPF_FUNC_sock_map_update:
8368 		return &bpf_sock_map_update_proto;
8369 	case BPF_FUNC_sock_hash_update:
8370 		return &bpf_sock_hash_update_proto;
8371 	case BPF_FUNC_get_socket_cookie:
8372 		return &bpf_get_socket_cookie_sock_ops_proto;
8373 	case BPF_FUNC_perf_event_output:
8374 		return &bpf_event_output_data_proto;
8375 	case BPF_FUNC_sk_storage_get:
8376 		return &bpf_sk_storage_get_proto;
8377 	case BPF_FUNC_sk_storage_delete:
8378 		return &bpf_sk_storage_delete_proto;
8379 	case BPF_FUNC_get_netns_cookie:
8380 		return &bpf_get_netns_cookie_sock_ops_proto;
8381 #ifdef CONFIG_INET
8382 	case BPF_FUNC_load_hdr_opt:
8383 		return &bpf_sock_ops_load_hdr_opt_proto;
8384 	case BPF_FUNC_store_hdr_opt:
8385 		return &bpf_sock_ops_store_hdr_opt_proto;
8386 	case BPF_FUNC_reserve_hdr_opt:
8387 		return &bpf_sock_ops_reserve_hdr_opt_proto;
8388 	case BPF_FUNC_tcp_sock:
8389 		return &bpf_tcp_sock_proto;
8390 #endif /* CONFIG_INET */
8391 	default:
8392 		return bpf_sk_base_func_proto(func_id, prog);
8393 	}
8394 }
8395 
8396 const struct bpf_func_proto bpf_msg_redirect_map_proto __weak;
8397 const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak;
8398 
8399 static const struct bpf_func_proto *
sk_msg_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8400 sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8401 {
8402 	switch (func_id) {
8403 	case BPF_FUNC_msg_redirect_map:
8404 		return &bpf_msg_redirect_map_proto;
8405 	case BPF_FUNC_msg_redirect_hash:
8406 		return &bpf_msg_redirect_hash_proto;
8407 	case BPF_FUNC_msg_apply_bytes:
8408 		return &bpf_msg_apply_bytes_proto;
8409 	case BPF_FUNC_msg_cork_bytes:
8410 		return &bpf_msg_cork_bytes_proto;
8411 	case BPF_FUNC_msg_pull_data:
8412 		return &bpf_msg_pull_data_proto;
8413 	case BPF_FUNC_msg_push_data:
8414 		return &bpf_msg_push_data_proto;
8415 	case BPF_FUNC_msg_pop_data:
8416 		return &bpf_msg_pop_data_proto;
8417 	case BPF_FUNC_perf_event_output:
8418 		return &bpf_event_output_data_proto;
8419 	case BPF_FUNC_get_current_uid_gid:
8420 		return &bpf_get_current_uid_gid_proto;
8421 	case BPF_FUNC_sk_storage_get:
8422 		return &bpf_sk_storage_get_proto;
8423 	case BPF_FUNC_sk_storage_delete:
8424 		return &bpf_sk_storage_delete_proto;
8425 	case BPF_FUNC_get_netns_cookie:
8426 		return &bpf_get_netns_cookie_sk_msg_proto;
8427 #ifdef CONFIG_CGROUP_NET_CLASSID
8428 	case BPF_FUNC_get_cgroup_classid:
8429 		return &bpf_get_cgroup_classid_curr_proto;
8430 #endif
8431 	default:
8432 		return bpf_sk_base_func_proto(func_id, prog);
8433 	}
8434 }
8435 
8436 const struct bpf_func_proto bpf_sk_redirect_map_proto __weak;
8437 const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak;
8438 
8439 static const struct bpf_func_proto *
sk_skb_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8440 sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8441 {
8442 	switch (func_id) {
8443 	case BPF_FUNC_skb_store_bytes:
8444 		return &bpf_skb_store_bytes_proto;
8445 	case BPF_FUNC_skb_load_bytes:
8446 		return &bpf_skb_load_bytes_proto;
8447 	case BPF_FUNC_skb_pull_data:
8448 		return &sk_skb_pull_data_proto;
8449 	case BPF_FUNC_skb_change_tail:
8450 		return &sk_skb_change_tail_proto;
8451 	case BPF_FUNC_skb_change_head:
8452 		return &sk_skb_change_head_proto;
8453 	case BPF_FUNC_skb_adjust_room:
8454 		return &sk_skb_adjust_room_proto;
8455 	case BPF_FUNC_get_socket_cookie:
8456 		return &bpf_get_socket_cookie_proto;
8457 	case BPF_FUNC_get_socket_uid:
8458 		return &bpf_get_socket_uid_proto;
8459 	case BPF_FUNC_sk_redirect_map:
8460 		return &bpf_sk_redirect_map_proto;
8461 	case BPF_FUNC_sk_redirect_hash:
8462 		return &bpf_sk_redirect_hash_proto;
8463 	case BPF_FUNC_perf_event_output:
8464 		return &bpf_skb_event_output_proto;
8465 #ifdef CONFIG_INET
8466 	case BPF_FUNC_sk_lookup_tcp:
8467 		return &bpf_sk_lookup_tcp_proto;
8468 	case BPF_FUNC_sk_lookup_udp:
8469 		return &bpf_sk_lookup_udp_proto;
8470 	case BPF_FUNC_sk_release:
8471 		return &bpf_sk_release_proto;
8472 	case BPF_FUNC_skc_lookup_tcp:
8473 		return &bpf_skc_lookup_tcp_proto;
8474 #endif
8475 	default:
8476 		return bpf_sk_base_func_proto(func_id, prog);
8477 	}
8478 }
8479 
8480 static const struct bpf_func_proto *
flow_dissector_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8481 flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8482 {
8483 	switch (func_id) {
8484 	case BPF_FUNC_skb_load_bytes:
8485 		return &bpf_flow_dissector_load_bytes_proto;
8486 	default:
8487 		return bpf_sk_base_func_proto(func_id, prog);
8488 	}
8489 }
8490 
8491 static const struct bpf_func_proto *
lwt_out_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8492 lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8493 {
8494 	switch (func_id) {
8495 	case BPF_FUNC_skb_load_bytes:
8496 		return &bpf_skb_load_bytes_proto;
8497 	case BPF_FUNC_skb_pull_data:
8498 		return &bpf_skb_pull_data_proto;
8499 	case BPF_FUNC_csum_diff:
8500 		return &bpf_csum_diff_proto;
8501 	case BPF_FUNC_get_cgroup_classid:
8502 		return &bpf_get_cgroup_classid_proto;
8503 	case BPF_FUNC_get_route_realm:
8504 		return &bpf_get_route_realm_proto;
8505 	case BPF_FUNC_get_hash_recalc:
8506 		return &bpf_get_hash_recalc_proto;
8507 	case BPF_FUNC_perf_event_output:
8508 		return &bpf_skb_event_output_proto;
8509 	case BPF_FUNC_get_smp_processor_id:
8510 		return &bpf_get_smp_processor_id_proto;
8511 	case BPF_FUNC_skb_under_cgroup:
8512 		return &bpf_skb_under_cgroup_proto;
8513 	default:
8514 		return bpf_sk_base_func_proto(func_id, prog);
8515 	}
8516 }
8517 
8518 static const struct bpf_func_proto *
lwt_in_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8519 lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8520 {
8521 	switch (func_id) {
8522 	case BPF_FUNC_lwt_push_encap:
8523 		return &bpf_lwt_in_push_encap_proto;
8524 	default:
8525 		return lwt_out_func_proto(func_id, prog);
8526 	}
8527 }
8528 
8529 static const struct bpf_func_proto *
lwt_xmit_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8530 lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8531 {
8532 	switch (func_id) {
8533 	case BPF_FUNC_skb_get_tunnel_key:
8534 		return &bpf_skb_get_tunnel_key_proto;
8535 	case BPF_FUNC_skb_set_tunnel_key:
8536 		return bpf_get_skb_set_tunnel_proto(func_id);
8537 	case BPF_FUNC_skb_get_tunnel_opt:
8538 		return &bpf_skb_get_tunnel_opt_proto;
8539 	case BPF_FUNC_skb_set_tunnel_opt:
8540 		return bpf_get_skb_set_tunnel_proto(func_id);
8541 	case BPF_FUNC_redirect:
8542 		return &bpf_redirect_proto;
8543 	case BPF_FUNC_clone_redirect:
8544 		return &bpf_clone_redirect_proto;
8545 	case BPF_FUNC_skb_change_tail:
8546 		return &bpf_skb_change_tail_proto;
8547 	case BPF_FUNC_skb_change_head:
8548 		return &bpf_skb_change_head_proto;
8549 	case BPF_FUNC_skb_store_bytes:
8550 		return &bpf_skb_store_bytes_proto;
8551 	case BPF_FUNC_csum_update:
8552 		return &bpf_csum_update_proto;
8553 	case BPF_FUNC_csum_level:
8554 		return &bpf_csum_level_proto;
8555 	case BPF_FUNC_l3_csum_replace:
8556 		return &bpf_l3_csum_replace_proto;
8557 	case BPF_FUNC_l4_csum_replace:
8558 		return &bpf_l4_csum_replace_proto;
8559 	case BPF_FUNC_set_hash_invalid:
8560 		return &bpf_set_hash_invalid_proto;
8561 	case BPF_FUNC_lwt_push_encap:
8562 		return &bpf_lwt_xmit_push_encap_proto;
8563 	default:
8564 		return lwt_out_func_proto(func_id, prog);
8565 	}
8566 }
8567 
8568 static const struct bpf_func_proto *
lwt_seg6local_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8569 lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8570 {
8571 	switch (func_id) {
8572 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
8573 	case BPF_FUNC_lwt_seg6_store_bytes:
8574 		return &bpf_lwt_seg6_store_bytes_proto;
8575 	case BPF_FUNC_lwt_seg6_action:
8576 		return &bpf_lwt_seg6_action_proto;
8577 	case BPF_FUNC_lwt_seg6_adjust_srh:
8578 		return &bpf_lwt_seg6_adjust_srh_proto;
8579 #endif
8580 	default:
8581 		return lwt_out_func_proto(func_id, prog);
8582 	}
8583 }
8584 
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)8585 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
8586 				    const struct bpf_prog *prog,
8587 				    struct bpf_insn_access_aux *info)
8588 {
8589 	const int size_default = sizeof(__u32);
8590 
8591 	if (off < 0 || off >= sizeof(struct __sk_buff))
8592 		return false;
8593 
8594 	/* The verifier guarantees that size > 0. */
8595 	if (off % size != 0)
8596 		return false;
8597 
8598 	switch (off) {
8599 	case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8600 		if (off + size > offsetofend(struct __sk_buff, cb[4]))
8601 			return false;
8602 		break;
8603 	case bpf_ctx_range(struct __sk_buff, data):
8604 	case bpf_ctx_range(struct __sk_buff, data_meta):
8605 	case bpf_ctx_range(struct __sk_buff, data_end):
8606 		if (info->is_ldsx || size != size_default)
8607 			return false;
8608 		break;
8609 	case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
8610 	case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
8611 	case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
8612 	case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
8613 		if (size != size_default)
8614 			return false;
8615 		break;
8616 	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
8617 		return false;
8618 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
8619 		if (type == BPF_WRITE || size != sizeof(__u64))
8620 			return false;
8621 		break;
8622 	case bpf_ctx_range(struct __sk_buff, tstamp):
8623 		if (size != sizeof(__u64))
8624 			return false;
8625 		break;
8626 	case offsetof(struct __sk_buff, sk):
8627 		if (type == BPF_WRITE || size != sizeof(__u64))
8628 			return false;
8629 		info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
8630 		break;
8631 	case offsetof(struct __sk_buff, tstamp_type):
8632 		return false;
8633 	case offsetofend(struct __sk_buff, tstamp_type) ... offsetof(struct __sk_buff, hwtstamp) - 1:
8634 		/* Explicitly prohibit access to padding in __sk_buff. */
8635 		return false;
8636 	default:
8637 		/* Only narrow read access allowed for now. */
8638 		if (type == BPF_WRITE) {
8639 			if (size != size_default)
8640 				return false;
8641 		} else {
8642 			bpf_ctx_record_field_size(info, size_default);
8643 			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
8644 				return false;
8645 		}
8646 	}
8647 
8648 	return true;
8649 }
8650 
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)8651 static bool sk_filter_is_valid_access(int off, int size,
8652 				      enum bpf_access_type type,
8653 				      const struct bpf_prog *prog,
8654 				      struct bpf_insn_access_aux *info)
8655 {
8656 	switch (off) {
8657 	case bpf_ctx_range(struct __sk_buff, tc_classid):
8658 	case bpf_ctx_range(struct __sk_buff, data):
8659 	case bpf_ctx_range(struct __sk_buff, data_meta):
8660 	case bpf_ctx_range(struct __sk_buff, data_end):
8661 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
8662 	case bpf_ctx_range(struct __sk_buff, tstamp):
8663 	case bpf_ctx_range(struct __sk_buff, wire_len):
8664 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
8665 		return false;
8666 	}
8667 
8668 	if (type == BPF_WRITE) {
8669 		switch (off) {
8670 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8671 			break;
8672 		default:
8673 			return false;
8674 		}
8675 	}
8676 
8677 	return bpf_skb_is_valid_access(off, size, type, prog, info);
8678 }
8679 
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)8680 static bool cg_skb_is_valid_access(int off, int size,
8681 				   enum bpf_access_type type,
8682 				   const struct bpf_prog *prog,
8683 				   struct bpf_insn_access_aux *info)
8684 {
8685 	switch (off) {
8686 	case bpf_ctx_range(struct __sk_buff, tc_classid):
8687 	case bpf_ctx_range(struct __sk_buff, data_meta):
8688 	case bpf_ctx_range(struct __sk_buff, wire_len):
8689 		return false;
8690 	case bpf_ctx_range(struct __sk_buff, data):
8691 	case bpf_ctx_range(struct __sk_buff, data_end):
8692 		if (!bpf_token_capable(prog->aux->token, CAP_BPF))
8693 			return false;
8694 		break;
8695 	}
8696 
8697 	if (type == BPF_WRITE) {
8698 		switch (off) {
8699 		case bpf_ctx_range(struct __sk_buff, mark):
8700 		case bpf_ctx_range(struct __sk_buff, priority):
8701 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8702 			break;
8703 		case bpf_ctx_range(struct __sk_buff, tstamp):
8704 			if (!bpf_token_capable(prog->aux->token, CAP_BPF))
8705 				return false;
8706 			break;
8707 		default:
8708 			return false;
8709 		}
8710 	}
8711 
8712 	switch (off) {
8713 	case bpf_ctx_range(struct __sk_buff, data):
8714 		info->reg_type = PTR_TO_PACKET;
8715 		break;
8716 	case bpf_ctx_range(struct __sk_buff, data_end):
8717 		info->reg_type = PTR_TO_PACKET_END;
8718 		break;
8719 	}
8720 
8721 	return bpf_skb_is_valid_access(off, size, type, prog, info);
8722 }
8723 
lwt_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)8724 static bool lwt_is_valid_access(int off, int size,
8725 				enum bpf_access_type type,
8726 				const struct bpf_prog *prog,
8727 				struct bpf_insn_access_aux *info)
8728 {
8729 	switch (off) {
8730 	case bpf_ctx_range(struct __sk_buff, tc_classid):
8731 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
8732 	case bpf_ctx_range(struct __sk_buff, data_meta):
8733 	case bpf_ctx_range(struct __sk_buff, tstamp):
8734 	case bpf_ctx_range(struct __sk_buff, wire_len):
8735 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
8736 		return false;
8737 	}
8738 
8739 	if (type == BPF_WRITE) {
8740 		switch (off) {
8741 		case bpf_ctx_range(struct __sk_buff, mark):
8742 		case bpf_ctx_range(struct __sk_buff, priority):
8743 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8744 			break;
8745 		default:
8746 			return false;
8747 		}
8748 	}
8749 
8750 	switch (off) {
8751 	case bpf_ctx_range(struct __sk_buff, data):
8752 		info->reg_type = PTR_TO_PACKET;
8753 		break;
8754 	case bpf_ctx_range(struct __sk_buff, data_end):
8755 		info->reg_type = PTR_TO_PACKET_END;
8756 		break;
8757 	}
8758 
8759 	return bpf_skb_is_valid_access(off, size, type, prog, info);
8760 }
8761 
8762 /* Attach type specific accesses */
__sock_filter_check_attach_type(int off,enum bpf_access_type access_type,enum bpf_attach_type attach_type)8763 static bool __sock_filter_check_attach_type(int off,
8764 					    enum bpf_access_type access_type,
8765 					    enum bpf_attach_type attach_type)
8766 {
8767 	switch (off) {
8768 	case offsetof(struct bpf_sock, bound_dev_if):
8769 	case offsetof(struct bpf_sock, mark):
8770 	case offsetof(struct bpf_sock, priority):
8771 		switch (attach_type) {
8772 		case BPF_CGROUP_INET_SOCK_CREATE:
8773 		case BPF_CGROUP_INET_SOCK_RELEASE:
8774 			goto full_access;
8775 		default:
8776 			return false;
8777 		}
8778 	case bpf_ctx_range(struct bpf_sock, src_ip4):
8779 		switch (attach_type) {
8780 		case BPF_CGROUP_INET4_POST_BIND:
8781 			goto read_only;
8782 		default:
8783 			return false;
8784 		}
8785 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
8786 		switch (attach_type) {
8787 		case BPF_CGROUP_INET6_POST_BIND:
8788 			goto read_only;
8789 		default:
8790 			return false;
8791 		}
8792 	case bpf_ctx_range(struct bpf_sock, src_port):
8793 		switch (attach_type) {
8794 		case BPF_CGROUP_INET4_POST_BIND:
8795 		case BPF_CGROUP_INET6_POST_BIND:
8796 			goto read_only;
8797 		default:
8798 			return false;
8799 		}
8800 	}
8801 read_only:
8802 	return access_type == BPF_READ;
8803 full_access:
8804 	return true;
8805 }
8806 
bpf_sock_common_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)8807 bool bpf_sock_common_is_valid_access(int off, int size,
8808 				     enum bpf_access_type type,
8809 				     struct bpf_insn_access_aux *info)
8810 {
8811 	switch (off) {
8812 	case bpf_ctx_range_till(struct bpf_sock, type, priority):
8813 		return false;
8814 	default:
8815 		return bpf_sock_is_valid_access(off, size, type, info);
8816 	}
8817 }
8818 
bpf_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)8819 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
8820 			      struct bpf_insn_access_aux *info)
8821 {
8822 	const int size_default = sizeof(__u32);
8823 	int field_size;
8824 
8825 	if (off < 0 || off >= sizeof(struct bpf_sock))
8826 		return false;
8827 	if (off % size != 0)
8828 		return false;
8829 
8830 	switch (off) {
8831 	case offsetof(struct bpf_sock, state):
8832 	case offsetof(struct bpf_sock, family):
8833 	case offsetof(struct bpf_sock, type):
8834 	case offsetof(struct bpf_sock, protocol):
8835 	case offsetof(struct bpf_sock, src_port):
8836 	case offsetof(struct bpf_sock, rx_queue_mapping):
8837 	case bpf_ctx_range(struct bpf_sock, src_ip4):
8838 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
8839 	case bpf_ctx_range(struct bpf_sock, dst_ip4):
8840 	case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
8841 		bpf_ctx_record_field_size(info, size_default);
8842 		return bpf_ctx_narrow_access_ok(off, size, size_default);
8843 	case bpf_ctx_range(struct bpf_sock, dst_port):
8844 		field_size = size == size_default ?
8845 			size_default : sizeof_field(struct bpf_sock, dst_port);
8846 		bpf_ctx_record_field_size(info, field_size);
8847 		return bpf_ctx_narrow_access_ok(off, size, field_size);
8848 	case offsetofend(struct bpf_sock, dst_port) ...
8849 	     offsetof(struct bpf_sock, dst_ip4) - 1:
8850 		return false;
8851 	}
8852 
8853 	return size == size_default;
8854 }
8855 
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)8856 static bool sock_filter_is_valid_access(int off, int size,
8857 					enum bpf_access_type type,
8858 					const struct bpf_prog *prog,
8859 					struct bpf_insn_access_aux *info)
8860 {
8861 	if (!bpf_sock_is_valid_access(off, size, type, info))
8862 		return false;
8863 	return __sock_filter_check_attach_type(off, type,
8864 					       prog->expected_attach_type);
8865 }
8866 
bpf_noop_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog)8867 static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write,
8868 			     const struct bpf_prog *prog)
8869 {
8870 	/* Neither direct read nor direct write requires any preliminary
8871 	 * action.
8872 	 */
8873 	return 0;
8874 }
8875 
bpf_unclone_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog,int drop_verdict)8876 static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
8877 				const struct bpf_prog *prog, int drop_verdict)
8878 {
8879 	struct bpf_insn *insn = insn_buf;
8880 
8881 	if (!direct_write)
8882 		return 0;
8883 
8884 	/* if (!skb->cloned)
8885 	 *       goto start;
8886 	 *
8887 	 * (Fast-path, otherwise approximation that we might be
8888 	 *  a clone, do the rest in helper.)
8889 	 */
8890 	*insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET);
8891 	*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
8892 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
8893 
8894 	/* ret = bpf_skb_pull_data(skb, 0); */
8895 	*insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
8896 	*insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
8897 	*insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
8898 			       BPF_FUNC_skb_pull_data);
8899 	/* if (!ret)
8900 	 *      goto restore;
8901 	 * return TC_ACT_SHOT;
8902 	 */
8903 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
8904 	*insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
8905 	*insn++ = BPF_EXIT_INSN();
8906 
8907 	/* restore: */
8908 	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
8909 	/* start: */
8910 	*insn++ = prog->insnsi[0];
8911 
8912 	return insn - insn_buf;
8913 }
8914 
bpf_gen_ld_abs(const struct bpf_insn * orig,struct bpf_insn * insn_buf)8915 static int bpf_gen_ld_abs(const struct bpf_insn *orig,
8916 			  struct bpf_insn *insn_buf)
8917 {
8918 	bool indirect = BPF_MODE(orig->code) == BPF_IND;
8919 	struct bpf_insn *insn = insn_buf;
8920 
8921 	if (!indirect) {
8922 		*insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
8923 	} else {
8924 		*insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
8925 		if (orig->imm)
8926 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
8927 	}
8928 	/* We're guaranteed here that CTX is in R6. */
8929 	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
8930 
8931 	switch (BPF_SIZE(orig->code)) {
8932 	case BPF_B:
8933 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
8934 		break;
8935 	case BPF_H:
8936 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
8937 		break;
8938 	case BPF_W:
8939 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
8940 		break;
8941 	}
8942 
8943 	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
8944 	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
8945 	*insn++ = BPF_EXIT_INSN();
8946 
8947 	return insn - insn_buf;
8948 }
8949 
tc_cls_act_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog)8950 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
8951 			       const struct bpf_prog *prog)
8952 {
8953 	return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
8954 }
8955 
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)8956 static bool tc_cls_act_is_valid_access(int off, int size,
8957 				       enum bpf_access_type type,
8958 				       const struct bpf_prog *prog,
8959 				       struct bpf_insn_access_aux *info)
8960 {
8961 	if (type == BPF_WRITE) {
8962 		switch (off) {
8963 		case bpf_ctx_range(struct __sk_buff, mark):
8964 		case bpf_ctx_range(struct __sk_buff, tc_index):
8965 		case bpf_ctx_range(struct __sk_buff, priority):
8966 		case bpf_ctx_range(struct __sk_buff, tc_classid):
8967 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8968 		case bpf_ctx_range(struct __sk_buff, tstamp):
8969 		case bpf_ctx_range(struct __sk_buff, queue_mapping):
8970 			break;
8971 		default:
8972 			return false;
8973 		}
8974 	}
8975 
8976 	switch (off) {
8977 	case bpf_ctx_range(struct __sk_buff, data):
8978 		info->reg_type = PTR_TO_PACKET;
8979 		break;
8980 	case bpf_ctx_range(struct __sk_buff, data_meta):
8981 		info->reg_type = PTR_TO_PACKET_META;
8982 		break;
8983 	case bpf_ctx_range(struct __sk_buff, data_end):
8984 		info->reg_type = PTR_TO_PACKET_END;
8985 		break;
8986 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
8987 		return false;
8988 	case offsetof(struct __sk_buff, tstamp_type):
8989 		/* The convert_ctx_access() on reading and writing
8990 		 * __sk_buff->tstamp depends on whether the bpf prog
8991 		 * has used __sk_buff->tstamp_type or not.
8992 		 * Thus, we need to set prog->tstamp_type_access
8993 		 * earlier during is_valid_access() here.
8994 		 */
8995 		((struct bpf_prog *)prog)->tstamp_type_access = 1;
8996 		return size == sizeof(__u8);
8997 	}
8998 
8999 	return bpf_skb_is_valid_access(off, size, type, prog, info);
9000 }
9001 
9002 DEFINE_MUTEX(nf_conn_btf_access_lock);
9003 EXPORT_SYMBOL_GPL(nf_conn_btf_access_lock);
9004 
9005 int (*nfct_btf_struct_access)(struct bpf_verifier_log *log,
9006 			      const struct bpf_reg_state *reg,
9007 			      int off, int size);
9008 EXPORT_SYMBOL_GPL(nfct_btf_struct_access);
9009 
tc_cls_act_btf_struct_access(struct bpf_verifier_log * log,const struct bpf_reg_state * reg,int off,int size)9010 static int tc_cls_act_btf_struct_access(struct bpf_verifier_log *log,
9011 					const struct bpf_reg_state *reg,
9012 					int off, int size)
9013 {
9014 	int ret = -EACCES;
9015 
9016 	mutex_lock(&nf_conn_btf_access_lock);
9017 	if (nfct_btf_struct_access)
9018 		ret = nfct_btf_struct_access(log, reg, off, size);
9019 	mutex_unlock(&nf_conn_btf_access_lock);
9020 
9021 	return ret;
9022 }
9023 
__is_valid_xdp_access(int off,int size)9024 static bool __is_valid_xdp_access(int off, int size)
9025 {
9026 	if (off < 0 || off >= sizeof(struct xdp_md))
9027 		return false;
9028 	if (off % size != 0)
9029 		return false;
9030 	if (size != sizeof(__u32))
9031 		return false;
9032 
9033 	return true;
9034 }
9035 
xdp_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)9036 static bool xdp_is_valid_access(int off, int size,
9037 				enum bpf_access_type type,
9038 				const struct bpf_prog *prog,
9039 				struct bpf_insn_access_aux *info)
9040 {
9041 	if (prog->expected_attach_type != BPF_XDP_DEVMAP) {
9042 		switch (off) {
9043 		case offsetof(struct xdp_md, egress_ifindex):
9044 			return false;
9045 		}
9046 	}
9047 
9048 	if (type == BPF_WRITE) {
9049 		if (bpf_prog_is_offloaded(prog->aux)) {
9050 			switch (off) {
9051 			case offsetof(struct xdp_md, rx_queue_index):
9052 				return __is_valid_xdp_access(off, size);
9053 			}
9054 		}
9055 		return false;
9056 	} else {
9057 		switch (off) {
9058 		case offsetof(struct xdp_md, data_meta):
9059 		case offsetof(struct xdp_md, data):
9060 		case offsetof(struct xdp_md, data_end):
9061 			if (info->is_ldsx)
9062 				return false;
9063 		}
9064 	}
9065 
9066 	switch (off) {
9067 	case offsetof(struct xdp_md, data):
9068 		info->reg_type = PTR_TO_PACKET;
9069 		break;
9070 	case offsetof(struct xdp_md, data_meta):
9071 		info->reg_type = PTR_TO_PACKET_META;
9072 		break;
9073 	case offsetof(struct xdp_md, data_end):
9074 		info->reg_type = PTR_TO_PACKET_END;
9075 		break;
9076 	}
9077 
9078 	return __is_valid_xdp_access(off, size);
9079 }
9080 
bpf_warn_invalid_xdp_action(const struct net_device * dev,const struct bpf_prog * prog,u32 act)9081 void bpf_warn_invalid_xdp_action(const struct net_device *dev,
9082 				 const 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 	int err;
11255 
11256 	selected_sk = map->ops->map_lookup_elem(map, key);
11257 	if (!selected_sk)
11258 		return -ENOENT;
11259 
11260 	reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
11261 	if (!reuse) {
11262 		/* reuseport_array has only sk with non NULL sk_reuseport_cb.
11263 		 * The only (!reuse) case here is - the sk has already been
11264 		 * unhashed (e.g. by close()), so treat it as -ENOENT.
11265 		 *
11266 		 * Other maps (e.g. sock_map) do not provide this guarantee and
11267 		 * the sk may never be in the reuseport group to begin with.
11268 		 */
11269 		err = is_sockarray ? -ENOENT : -EINVAL;
11270 		goto error;
11271 	}
11272 
11273 	if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
11274 		struct sock *sk = reuse_kern->sk;
11275 
11276 		if (sk->sk_protocol != selected_sk->sk_protocol) {
11277 			err = -EPROTOTYPE;
11278 		} else if (sk->sk_family != selected_sk->sk_family) {
11279 			err = -EAFNOSUPPORT;
11280 		} else {
11281 			/* Catch all. Likely bound to a different sockaddr. */
11282 			err = -EBADFD;
11283 		}
11284 		goto error;
11285 	}
11286 
11287 	reuse_kern->selected_sk = selected_sk;
11288 
11289 	return 0;
11290 error:
11291 	/* Lookup in sock_map can return TCP ESTABLISHED sockets. */
11292 	if (sk_is_refcounted(selected_sk))
11293 		sock_put(selected_sk);
11294 
11295 	return err;
11296 }
11297 
11298 static const struct bpf_func_proto sk_select_reuseport_proto = {
11299 	.func           = sk_select_reuseport,
11300 	.gpl_only       = false,
11301 	.ret_type       = RET_INTEGER,
11302 	.arg1_type	= ARG_PTR_TO_CTX,
11303 	.arg2_type      = ARG_CONST_MAP_PTR,
11304 	.arg3_type      = ARG_PTR_TO_MAP_KEY,
11305 	.arg4_type	= ARG_ANYTHING,
11306 };
11307 
BPF_CALL_4(sk_reuseport_load_bytes,const struct sk_reuseport_kern *,reuse_kern,u32,offset,void *,to,u32,len)11308 BPF_CALL_4(sk_reuseport_load_bytes,
11309 	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
11310 	   void *, to, u32, len)
11311 {
11312 	return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
11313 }
11314 
11315 static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
11316 	.func		= sk_reuseport_load_bytes,
11317 	.gpl_only	= false,
11318 	.ret_type	= RET_INTEGER,
11319 	.arg1_type	= ARG_PTR_TO_CTX,
11320 	.arg2_type	= ARG_ANYTHING,
11321 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
11322 	.arg4_type	= ARG_CONST_SIZE,
11323 };
11324 
BPF_CALL_5(sk_reuseport_load_bytes_relative,const struct sk_reuseport_kern *,reuse_kern,u32,offset,void *,to,u32,len,u32,start_header)11325 BPF_CALL_5(sk_reuseport_load_bytes_relative,
11326 	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
11327 	   void *, to, u32, len, u32, start_header)
11328 {
11329 	return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
11330 					       len, start_header);
11331 }
11332 
11333 static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
11334 	.func		= sk_reuseport_load_bytes_relative,
11335 	.gpl_only	= false,
11336 	.ret_type	= RET_INTEGER,
11337 	.arg1_type	= ARG_PTR_TO_CTX,
11338 	.arg2_type	= ARG_ANYTHING,
11339 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
11340 	.arg4_type	= ARG_CONST_SIZE,
11341 	.arg5_type	= ARG_ANYTHING,
11342 };
11343 
11344 static const struct bpf_func_proto *
sk_reuseport_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)11345 sk_reuseport_func_proto(enum bpf_func_id func_id,
11346 			const struct bpf_prog *prog)
11347 {
11348 	switch (func_id) {
11349 	case BPF_FUNC_sk_select_reuseport:
11350 		return &sk_select_reuseport_proto;
11351 	case BPF_FUNC_skb_load_bytes:
11352 		return &sk_reuseport_load_bytes_proto;
11353 	case BPF_FUNC_skb_load_bytes_relative:
11354 		return &sk_reuseport_load_bytes_relative_proto;
11355 	case BPF_FUNC_get_socket_cookie:
11356 		return &bpf_get_socket_ptr_cookie_proto;
11357 	case BPF_FUNC_ktime_get_coarse_ns:
11358 		return &bpf_ktime_get_coarse_ns_proto;
11359 	default:
11360 		return bpf_base_func_proto(func_id, prog);
11361 	}
11362 }
11363 
11364 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)11365 sk_reuseport_is_valid_access(int off, int size,
11366 			     enum bpf_access_type type,
11367 			     const struct bpf_prog *prog,
11368 			     struct bpf_insn_access_aux *info)
11369 {
11370 	const u32 size_default = sizeof(__u32);
11371 
11372 	if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
11373 	    off % size || type != BPF_READ)
11374 		return false;
11375 
11376 	switch (off) {
11377 	case offsetof(struct sk_reuseport_md, data):
11378 		info->reg_type = PTR_TO_PACKET;
11379 		return size == sizeof(__u64);
11380 
11381 	case offsetof(struct sk_reuseport_md, data_end):
11382 		info->reg_type = PTR_TO_PACKET_END;
11383 		return size == sizeof(__u64);
11384 
11385 	case offsetof(struct sk_reuseport_md, hash):
11386 		return size == size_default;
11387 
11388 	case offsetof(struct sk_reuseport_md, sk):
11389 		info->reg_type = PTR_TO_SOCKET;
11390 		return size == sizeof(__u64);
11391 
11392 	case offsetof(struct sk_reuseport_md, migrating_sk):
11393 		info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
11394 		return size == sizeof(__u64);
11395 
11396 	/* Fields that allow narrowing */
11397 	case bpf_ctx_range(struct sk_reuseport_md, eth_protocol):
11398 		if (size < sizeof_field(struct sk_buff, protocol))
11399 			return false;
11400 		fallthrough;
11401 	case bpf_ctx_range(struct sk_reuseport_md, ip_protocol):
11402 	case bpf_ctx_range(struct sk_reuseport_md, bind_inany):
11403 	case bpf_ctx_range(struct sk_reuseport_md, len):
11404 		bpf_ctx_record_field_size(info, size_default);
11405 		return bpf_ctx_narrow_access_ok(off, size, size_default);
11406 
11407 	default:
11408 		return false;
11409 	}
11410 }
11411 
11412 #define SK_REUSEPORT_LOAD_FIELD(F) ({					\
11413 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
11414 			      si->dst_reg, si->src_reg,			\
11415 			      bpf_target_off(struct sk_reuseport_kern, F, \
11416 					     sizeof_field(struct sk_reuseport_kern, F), \
11417 					     target_size));		\
11418 	})
11419 
11420 #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)				\
11421 	SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,		\
11422 				    struct sk_buff,			\
11423 				    skb,				\
11424 				    SKB_FIELD)
11425 
11426 #define SK_REUSEPORT_LOAD_SK_FIELD(SK_FIELD)				\
11427 	SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,		\
11428 				    struct sock,			\
11429 				    sk,					\
11430 				    SK_FIELD)
11431 
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)11432 static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
11433 					   const struct bpf_insn *si,
11434 					   struct bpf_insn *insn_buf,
11435 					   struct bpf_prog *prog,
11436 					   u32 *target_size)
11437 {
11438 	struct bpf_insn *insn = insn_buf;
11439 
11440 	switch (si->off) {
11441 	case offsetof(struct sk_reuseport_md, data):
11442 		SK_REUSEPORT_LOAD_SKB_FIELD(data);
11443 		break;
11444 
11445 	case offsetof(struct sk_reuseport_md, len):
11446 		SK_REUSEPORT_LOAD_SKB_FIELD(len);
11447 		break;
11448 
11449 	case offsetof(struct sk_reuseport_md, eth_protocol):
11450 		SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
11451 		break;
11452 
11453 	case offsetof(struct sk_reuseport_md, ip_protocol):
11454 		SK_REUSEPORT_LOAD_SK_FIELD(sk_protocol);
11455 		break;
11456 
11457 	case offsetof(struct sk_reuseport_md, data_end):
11458 		SK_REUSEPORT_LOAD_FIELD(data_end);
11459 		break;
11460 
11461 	case offsetof(struct sk_reuseport_md, hash):
11462 		SK_REUSEPORT_LOAD_FIELD(hash);
11463 		break;
11464 
11465 	case offsetof(struct sk_reuseport_md, bind_inany):
11466 		SK_REUSEPORT_LOAD_FIELD(bind_inany);
11467 		break;
11468 
11469 	case offsetof(struct sk_reuseport_md, sk):
11470 		SK_REUSEPORT_LOAD_FIELD(sk);
11471 		break;
11472 
11473 	case offsetof(struct sk_reuseport_md, migrating_sk):
11474 		SK_REUSEPORT_LOAD_FIELD(migrating_sk);
11475 		break;
11476 	}
11477 
11478 	return insn - insn_buf;
11479 }
11480 
11481 const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
11482 	.get_func_proto		= sk_reuseport_func_proto,
11483 	.is_valid_access	= sk_reuseport_is_valid_access,
11484 	.convert_ctx_access	= sk_reuseport_convert_ctx_access,
11485 };
11486 
11487 const struct bpf_prog_ops sk_reuseport_prog_ops = {
11488 };
11489 
11490 DEFINE_STATIC_KEY_FALSE(bpf_sk_lookup_enabled);
11491 EXPORT_SYMBOL(bpf_sk_lookup_enabled);
11492 
BPF_CALL_3(bpf_sk_lookup_assign,struct bpf_sk_lookup_kern *,ctx,struct sock *,sk,u64,flags)11493 BPF_CALL_3(bpf_sk_lookup_assign, struct bpf_sk_lookup_kern *, ctx,
11494 	   struct sock *, sk, u64, flags)
11495 {
11496 	if (unlikely(flags & ~(BPF_SK_LOOKUP_F_REPLACE |
11497 			       BPF_SK_LOOKUP_F_NO_REUSEPORT)))
11498 		return -EINVAL;
11499 	if (unlikely(sk && sk_is_refcounted(sk)))
11500 		return -ESOCKTNOSUPPORT; /* reject non-RCU freed sockets */
11501 	if (unlikely(sk && sk_is_tcp(sk) && sk->sk_state != TCP_LISTEN))
11502 		return -ESOCKTNOSUPPORT; /* only accept TCP socket in LISTEN */
11503 	if (unlikely(sk && sk_is_udp(sk) && sk->sk_state != TCP_CLOSE))
11504 		return -ESOCKTNOSUPPORT; /* only accept UDP socket in CLOSE */
11505 
11506 	/* Check if socket is suitable for packet L3/L4 protocol */
11507 	if (sk && sk->sk_protocol != ctx->protocol)
11508 		return -EPROTOTYPE;
11509 	if (sk && sk->sk_family != ctx->family &&
11510 	    (sk->sk_family == AF_INET || ipv6_only_sock(sk)))
11511 		return -EAFNOSUPPORT;
11512 
11513 	if (ctx->selected_sk && !(flags & BPF_SK_LOOKUP_F_REPLACE))
11514 		return -EEXIST;
11515 
11516 	/* Select socket as lookup result */
11517 	ctx->selected_sk = sk;
11518 	ctx->no_reuseport = flags & BPF_SK_LOOKUP_F_NO_REUSEPORT;
11519 	return 0;
11520 }
11521 
11522 static const struct bpf_func_proto bpf_sk_lookup_assign_proto = {
11523 	.func		= bpf_sk_lookup_assign,
11524 	.gpl_only	= false,
11525 	.ret_type	= RET_INTEGER,
11526 	.arg1_type	= ARG_PTR_TO_CTX,
11527 	.arg2_type	= ARG_PTR_TO_SOCKET_OR_NULL,
11528 	.arg3_type	= ARG_ANYTHING,
11529 };
11530 
11531 static const struct bpf_func_proto *
sk_lookup_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)11532 sk_lookup_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
11533 {
11534 	switch (func_id) {
11535 	case BPF_FUNC_perf_event_output:
11536 		return &bpf_event_output_data_proto;
11537 	case BPF_FUNC_sk_assign:
11538 		return &bpf_sk_lookup_assign_proto;
11539 	case BPF_FUNC_sk_release:
11540 		return &bpf_sk_release_proto;
11541 	default:
11542 		return bpf_sk_base_func_proto(func_id, prog);
11543 	}
11544 }
11545 
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)11546 static bool sk_lookup_is_valid_access(int off, int size,
11547 				      enum bpf_access_type type,
11548 				      const struct bpf_prog *prog,
11549 				      struct bpf_insn_access_aux *info)
11550 {
11551 	if (off < 0 || off >= sizeof(struct bpf_sk_lookup))
11552 		return false;
11553 	if (off % size != 0)
11554 		return false;
11555 	if (type != BPF_READ)
11556 		return false;
11557 
11558 	switch (off) {
11559 	case offsetof(struct bpf_sk_lookup, sk):
11560 		info->reg_type = PTR_TO_SOCKET_OR_NULL;
11561 		return size == sizeof(__u64);
11562 
11563 	case bpf_ctx_range(struct bpf_sk_lookup, family):
11564 	case bpf_ctx_range(struct bpf_sk_lookup, protocol):
11565 	case bpf_ctx_range(struct bpf_sk_lookup, remote_ip4):
11566 	case bpf_ctx_range(struct bpf_sk_lookup, local_ip4):
11567 	case bpf_ctx_range_till(struct bpf_sk_lookup, remote_ip6[0], remote_ip6[3]):
11568 	case bpf_ctx_range_till(struct bpf_sk_lookup, local_ip6[0], local_ip6[3]):
11569 	case bpf_ctx_range(struct bpf_sk_lookup, local_port):
11570 	case bpf_ctx_range(struct bpf_sk_lookup, ingress_ifindex):
11571 		bpf_ctx_record_field_size(info, sizeof(__u32));
11572 		return bpf_ctx_narrow_access_ok(off, size, sizeof(__u32));
11573 
11574 	case bpf_ctx_range(struct bpf_sk_lookup, remote_port):
11575 		/* Allow 4-byte access to 2-byte field for backward compatibility */
11576 		if (size == sizeof(__u32))
11577 			return true;
11578 		bpf_ctx_record_field_size(info, sizeof(__be16));
11579 		return bpf_ctx_narrow_access_ok(off, size, sizeof(__be16));
11580 
11581 	case offsetofend(struct bpf_sk_lookup, remote_port) ...
11582 	     offsetof(struct bpf_sk_lookup, local_ip4) - 1:
11583 		/* Allow access to zero padding for backward compatibility */
11584 		bpf_ctx_record_field_size(info, sizeof(__u16));
11585 		return bpf_ctx_narrow_access_ok(off, size, sizeof(__u16));
11586 
11587 	default:
11588 		return false;
11589 	}
11590 }
11591 
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)11592 static u32 sk_lookup_convert_ctx_access(enum bpf_access_type type,
11593 					const struct bpf_insn *si,
11594 					struct bpf_insn *insn_buf,
11595 					struct bpf_prog *prog,
11596 					u32 *target_size)
11597 {
11598 	struct bpf_insn *insn = insn_buf;
11599 
11600 	switch (si->off) {
11601 	case offsetof(struct bpf_sk_lookup, sk):
11602 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
11603 				      offsetof(struct bpf_sk_lookup_kern, selected_sk));
11604 		break;
11605 
11606 	case offsetof(struct bpf_sk_lookup, family):
11607 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11608 				      bpf_target_off(struct bpf_sk_lookup_kern,
11609 						     family, 2, target_size));
11610 		break;
11611 
11612 	case offsetof(struct bpf_sk_lookup, protocol):
11613 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11614 				      bpf_target_off(struct bpf_sk_lookup_kern,
11615 						     protocol, 2, target_size));
11616 		break;
11617 
11618 	case offsetof(struct bpf_sk_lookup, remote_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.saddr, 4, target_size));
11622 		break;
11623 
11624 	case offsetof(struct bpf_sk_lookup, local_ip4):
11625 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
11626 				      bpf_target_off(struct bpf_sk_lookup_kern,
11627 						     v4.daddr, 4, target_size));
11628 		break;
11629 
11630 	case bpf_ctx_range_till(struct bpf_sk_lookup,
11631 				remote_ip6[0], remote_ip6[3]): {
11632 #if IS_ENABLED(CONFIG_IPV6)
11633 		int off = si->off;
11634 
11635 		off -= offsetof(struct bpf_sk_lookup, remote_ip6[0]);
11636 		off += bpf_target_off(struct in6_addr, s6_addr32[0], 4, target_size);
11637 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
11638 				      offsetof(struct bpf_sk_lookup_kern, v6.saddr));
11639 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
11640 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, off);
11641 #else
11642 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11643 #endif
11644 		break;
11645 	}
11646 	case bpf_ctx_range_till(struct bpf_sk_lookup,
11647 				local_ip6[0], local_ip6[3]): {
11648 #if IS_ENABLED(CONFIG_IPV6)
11649 		int off = si->off;
11650 
11651 		off -= offsetof(struct bpf_sk_lookup, local_ip6[0]);
11652 		off += bpf_target_off(struct in6_addr, s6_addr32[0], 4, target_size);
11653 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
11654 				      offsetof(struct bpf_sk_lookup_kern, v6.daddr));
11655 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
11656 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, off);
11657 #else
11658 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11659 #endif
11660 		break;
11661 	}
11662 	case offsetof(struct bpf_sk_lookup, remote_port):
11663 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11664 				      bpf_target_off(struct bpf_sk_lookup_kern,
11665 						     sport, 2, target_size));
11666 		break;
11667 
11668 	case offsetofend(struct bpf_sk_lookup, remote_port):
11669 		*target_size = 2;
11670 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11671 		break;
11672 
11673 	case offsetof(struct bpf_sk_lookup, local_port):
11674 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11675 				      bpf_target_off(struct bpf_sk_lookup_kern,
11676 						     dport, 2, target_size));
11677 		break;
11678 
11679 	case offsetof(struct bpf_sk_lookup, ingress_ifindex):
11680 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
11681 				      bpf_target_off(struct bpf_sk_lookup_kern,
11682 						     ingress_ifindex, 4, target_size));
11683 		break;
11684 	}
11685 
11686 	return insn - insn_buf;
11687 }
11688 
11689 const struct bpf_prog_ops sk_lookup_prog_ops = {
11690 	.test_run = bpf_prog_test_run_sk_lookup,
11691 };
11692 
11693 const struct bpf_verifier_ops sk_lookup_verifier_ops = {
11694 	.get_func_proto		= sk_lookup_func_proto,
11695 	.is_valid_access	= sk_lookup_is_valid_access,
11696 	.convert_ctx_access	= sk_lookup_convert_ctx_access,
11697 };
11698 
11699 #endif /* CONFIG_INET */
11700 
DEFINE_BPF_DISPATCHER(xdp)11701 DEFINE_BPF_DISPATCHER(xdp)
11702 
11703 void bpf_prog_change_xdp(struct bpf_prog *prev_prog, struct bpf_prog *prog)
11704 {
11705 	bpf_dispatcher_change_prog(BPF_DISPATCHER_PTR(xdp), prev_prog, prog);
11706 }
11707 
BTF_ID_LIST_GLOBAL(btf_sock_ids,MAX_BTF_SOCK_TYPE)11708 BTF_ID_LIST_GLOBAL(btf_sock_ids, MAX_BTF_SOCK_TYPE)
11709 #define BTF_SOCK_TYPE(name, type) BTF_ID(struct, type)
11710 BTF_SOCK_TYPE_xxx
11711 #undef BTF_SOCK_TYPE
11712 
11713 BPF_CALL_1(bpf_skc_to_tcp6_sock, struct sock *, sk)
11714 {
11715 	/* tcp6_sock type is not generated in dwarf and hence btf,
11716 	 * trigger an explicit type generation here.
11717 	 */
11718 	BTF_TYPE_EMIT(struct tcp6_sock);
11719 	if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP &&
11720 	    sk->sk_family == AF_INET6)
11721 		return (unsigned long)sk;
11722 
11723 	return (unsigned long)NULL;
11724 }
11725 
11726 const struct bpf_func_proto bpf_skc_to_tcp6_sock_proto = {
11727 	.func			= bpf_skc_to_tcp6_sock,
11728 	.gpl_only		= false,
11729 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11730 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11731 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP6],
11732 };
11733 
BPF_CALL_1(bpf_skc_to_tcp_sock,struct sock *,sk)11734 BPF_CALL_1(bpf_skc_to_tcp_sock, struct sock *, sk)
11735 {
11736 	if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP)
11737 		return (unsigned long)sk;
11738 
11739 	return (unsigned long)NULL;
11740 }
11741 
11742 const struct bpf_func_proto bpf_skc_to_tcp_sock_proto = {
11743 	.func			= bpf_skc_to_tcp_sock,
11744 	.gpl_only		= false,
11745 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11746 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11747 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP],
11748 };
11749 
BPF_CALL_1(bpf_skc_to_tcp_timewait_sock,struct sock *,sk)11750 BPF_CALL_1(bpf_skc_to_tcp_timewait_sock, struct sock *, sk)
11751 {
11752 	/* BTF types for tcp_timewait_sock and inet_timewait_sock are not
11753 	 * generated if CONFIG_INET=n. Trigger an explicit generation here.
11754 	 */
11755 	BTF_TYPE_EMIT(struct inet_timewait_sock);
11756 	BTF_TYPE_EMIT(struct tcp_timewait_sock);
11757 
11758 #ifdef CONFIG_INET
11759 	if (sk && sk->sk_prot == &tcp_prot && sk->sk_state == TCP_TIME_WAIT)
11760 		return (unsigned long)sk;
11761 #endif
11762 
11763 #if IS_BUILTIN(CONFIG_IPV6)
11764 	if (sk && sk->sk_prot == &tcpv6_prot && sk->sk_state == TCP_TIME_WAIT)
11765 		return (unsigned long)sk;
11766 #endif
11767 
11768 	return (unsigned long)NULL;
11769 }
11770 
11771 const struct bpf_func_proto bpf_skc_to_tcp_timewait_sock_proto = {
11772 	.func			= bpf_skc_to_tcp_timewait_sock,
11773 	.gpl_only		= false,
11774 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11775 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11776 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP_TW],
11777 };
11778 
BPF_CALL_1(bpf_skc_to_tcp_request_sock,struct sock *,sk)11779 BPF_CALL_1(bpf_skc_to_tcp_request_sock, struct sock *, sk)
11780 {
11781 #ifdef CONFIG_INET
11782 	if (sk && sk->sk_prot == &tcp_prot && sk->sk_state == TCP_NEW_SYN_RECV)
11783 		return (unsigned long)sk;
11784 #endif
11785 
11786 #if IS_BUILTIN(CONFIG_IPV6)
11787 	if (sk && sk->sk_prot == &tcpv6_prot && sk->sk_state == TCP_NEW_SYN_RECV)
11788 		return (unsigned long)sk;
11789 #endif
11790 
11791 	return (unsigned long)NULL;
11792 }
11793 
11794 const struct bpf_func_proto bpf_skc_to_tcp_request_sock_proto = {
11795 	.func			= bpf_skc_to_tcp_request_sock,
11796 	.gpl_only		= false,
11797 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11798 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11799 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP_REQ],
11800 };
11801 
BPF_CALL_1(bpf_skc_to_udp6_sock,struct sock *,sk)11802 BPF_CALL_1(bpf_skc_to_udp6_sock, struct sock *, sk)
11803 {
11804 	/* udp6_sock type is not generated in dwarf and hence btf,
11805 	 * trigger an explicit type generation here.
11806 	 */
11807 	BTF_TYPE_EMIT(struct udp6_sock);
11808 	if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_UDP &&
11809 	    sk->sk_type == SOCK_DGRAM && sk->sk_family == AF_INET6)
11810 		return (unsigned long)sk;
11811 
11812 	return (unsigned long)NULL;
11813 }
11814 
11815 const struct bpf_func_proto bpf_skc_to_udp6_sock_proto = {
11816 	.func			= bpf_skc_to_udp6_sock,
11817 	.gpl_only		= false,
11818 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11819 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11820 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_UDP6],
11821 };
11822 
BPF_CALL_1(bpf_skc_to_unix_sock,struct sock *,sk)11823 BPF_CALL_1(bpf_skc_to_unix_sock, struct sock *, sk)
11824 {
11825 	/* unix_sock type is not generated in dwarf and hence btf,
11826 	 * trigger an explicit type generation here.
11827 	 */
11828 	BTF_TYPE_EMIT(struct unix_sock);
11829 	if (sk && sk_fullsock(sk) && sk->sk_family == AF_UNIX)
11830 		return (unsigned long)sk;
11831 
11832 	return (unsigned long)NULL;
11833 }
11834 
11835 const struct bpf_func_proto bpf_skc_to_unix_sock_proto = {
11836 	.func			= bpf_skc_to_unix_sock,
11837 	.gpl_only		= false,
11838 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11839 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11840 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_UNIX],
11841 };
11842 
BPF_CALL_1(bpf_skc_to_mptcp_sock,struct sock *,sk)11843 BPF_CALL_1(bpf_skc_to_mptcp_sock, struct sock *, sk)
11844 {
11845 	BTF_TYPE_EMIT(struct mptcp_sock);
11846 	return (unsigned long)bpf_mptcp_sock_from_subflow(sk);
11847 }
11848 
11849 const struct bpf_func_proto bpf_skc_to_mptcp_sock_proto = {
11850 	.func		= bpf_skc_to_mptcp_sock,
11851 	.gpl_only	= false,
11852 	.ret_type	= RET_PTR_TO_BTF_ID_OR_NULL,
11853 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
11854 	.ret_btf_id	= &btf_sock_ids[BTF_SOCK_TYPE_MPTCP],
11855 };
11856 
BPF_CALL_1(bpf_sock_from_file,struct file *,file)11857 BPF_CALL_1(bpf_sock_from_file, struct file *, file)
11858 {
11859 	return (unsigned long)sock_from_file(file);
11860 }
11861 
11862 BTF_ID_LIST(bpf_sock_from_file_btf_ids)
11863 BTF_ID(struct, socket)
11864 BTF_ID(struct, file)
11865 
11866 const struct bpf_func_proto bpf_sock_from_file_proto = {
11867 	.func		= bpf_sock_from_file,
11868 	.gpl_only	= false,
11869 	.ret_type	= RET_PTR_TO_BTF_ID_OR_NULL,
11870 	.ret_btf_id	= &bpf_sock_from_file_btf_ids[0],
11871 	.arg1_type	= ARG_PTR_TO_BTF_ID,
11872 	.arg1_btf_id	= &bpf_sock_from_file_btf_ids[1],
11873 };
11874 
11875 static const struct bpf_func_proto *
bpf_sk_base_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)11876 bpf_sk_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
11877 {
11878 	const struct bpf_func_proto *func;
11879 
11880 	switch (func_id) {
11881 	case BPF_FUNC_skc_to_tcp6_sock:
11882 		func = &bpf_skc_to_tcp6_sock_proto;
11883 		break;
11884 	case BPF_FUNC_skc_to_tcp_sock:
11885 		func = &bpf_skc_to_tcp_sock_proto;
11886 		break;
11887 	case BPF_FUNC_skc_to_tcp_timewait_sock:
11888 		func = &bpf_skc_to_tcp_timewait_sock_proto;
11889 		break;
11890 	case BPF_FUNC_skc_to_tcp_request_sock:
11891 		func = &bpf_skc_to_tcp_request_sock_proto;
11892 		break;
11893 	case BPF_FUNC_skc_to_udp6_sock:
11894 		func = &bpf_skc_to_udp6_sock_proto;
11895 		break;
11896 	case BPF_FUNC_skc_to_unix_sock:
11897 		func = &bpf_skc_to_unix_sock_proto;
11898 		break;
11899 	case BPF_FUNC_skc_to_mptcp_sock:
11900 		func = &bpf_skc_to_mptcp_sock_proto;
11901 		break;
11902 	case BPF_FUNC_ktime_get_coarse_ns:
11903 		return &bpf_ktime_get_coarse_ns_proto;
11904 	default:
11905 		return bpf_base_func_proto(func_id, prog);
11906 	}
11907 
11908 	if (!bpf_token_capable(prog->aux->token, CAP_PERFMON))
11909 		return NULL;
11910 
11911 	return func;
11912 }
11913 
11914 __bpf_kfunc_start_defs();
bpf_dynptr_from_skb(struct __sk_buff * s,u64 flags,struct bpf_dynptr * ptr__uninit)11915 __bpf_kfunc int bpf_dynptr_from_skb(struct __sk_buff *s, u64 flags,
11916 				    struct bpf_dynptr *ptr__uninit)
11917 {
11918 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)ptr__uninit;
11919 	struct sk_buff *skb = (struct sk_buff *)s;
11920 
11921 	if (flags) {
11922 		bpf_dynptr_set_null(ptr);
11923 		return -EINVAL;
11924 	}
11925 
11926 	bpf_dynptr_init(ptr, skb, BPF_DYNPTR_TYPE_SKB, 0, skb->len);
11927 
11928 	return 0;
11929 }
11930 
bpf_dynptr_from_xdp(struct xdp_md * x,u64 flags,struct bpf_dynptr * ptr__uninit)11931 __bpf_kfunc int bpf_dynptr_from_xdp(struct xdp_md *x, u64 flags,
11932 				    struct bpf_dynptr *ptr__uninit)
11933 {
11934 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)ptr__uninit;
11935 	struct xdp_buff *xdp = (struct xdp_buff *)x;
11936 
11937 	if (flags) {
11938 		bpf_dynptr_set_null(ptr);
11939 		return -EINVAL;
11940 	}
11941 
11942 	bpf_dynptr_init(ptr, xdp, BPF_DYNPTR_TYPE_XDP, 0, xdp_get_buff_len(xdp));
11943 
11944 	return 0;
11945 }
11946 
bpf_sock_addr_set_sun_path(struct bpf_sock_addr_kern * sa_kern,const u8 * sun_path,u32 sun_path__sz)11947 __bpf_kfunc int bpf_sock_addr_set_sun_path(struct bpf_sock_addr_kern *sa_kern,
11948 					   const u8 *sun_path, u32 sun_path__sz)
11949 {
11950 	struct sockaddr_un *un;
11951 
11952 	if (sa_kern->sk->sk_family != AF_UNIX)
11953 		return -EINVAL;
11954 
11955 	/* We do not allow changing the address to unnamed or larger than the
11956 	 * maximum allowed address size for a unix sockaddr.
11957 	 */
11958 	if (sun_path__sz == 0 || sun_path__sz > UNIX_PATH_MAX)
11959 		return -EINVAL;
11960 
11961 	un = (struct sockaddr_un *)sa_kern->uaddr;
11962 	memcpy(un->sun_path, sun_path, sun_path__sz);
11963 	sa_kern->uaddrlen = offsetof(struct sockaddr_un, sun_path) + sun_path__sz;
11964 
11965 	return 0;
11966 }
11967 
bpf_sk_assign_tcp_reqsk(struct __sk_buff * s,struct sock * sk,struct bpf_tcp_req_attrs * attrs,int attrs__sz)11968 __bpf_kfunc int bpf_sk_assign_tcp_reqsk(struct __sk_buff *s, struct sock *sk,
11969 					struct bpf_tcp_req_attrs *attrs, int attrs__sz)
11970 {
11971 #if IS_ENABLED(CONFIG_SYN_COOKIES)
11972 	struct sk_buff *skb = (struct sk_buff *)s;
11973 	const struct request_sock_ops *ops;
11974 	struct inet_request_sock *ireq;
11975 	struct tcp_request_sock *treq;
11976 	struct request_sock *req;
11977 	struct net *net;
11978 	__u16 min_mss;
11979 	u32 tsoff = 0;
11980 
11981 	if (attrs__sz != sizeof(*attrs) ||
11982 	    attrs->reserved[0] || attrs->reserved[1] || attrs->reserved[2])
11983 		return -EINVAL;
11984 
11985 	if (!skb_at_tc_ingress(skb))
11986 		return -EINVAL;
11987 
11988 	net = dev_net(skb->dev);
11989 	if (net != sock_net(sk))
11990 		return -ENETUNREACH;
11991 
11992 	switch (skb->protocol) {
11993 	case htons(ETH_P_IP):
11994 		ops = &tcp_request_sock_ops;
11995 		min_mss = 536;
11996 		break;
11997 #if IS_BUILTIN(CONFIG_IPV6)
11998 	case htons(ETH_P_IPV6):
11999 		ops = &tcp6_request_sock_ops;
12000 		min_mss = IPV6_MIN_MTU - 60;
12001 		break;
12002 #endif
12003 	default:
12004 		return -EINVAL;
12005 	}
12006 
12007 	if (sk->sk_type != SOCK_STREAM || sk->sk_state != TCP_LISTEN ||
12008 	    sk_is_mptcp(sk))
12009 		return -EINVAL;
12010 
12011 	if (attrs->mss < min_mss)
12012 		return -EINVAL;
12013 
12014 	if (attrs->wscale_ok) {
12015 		if (!READ_ONCE(net->ipv4.sysctl_tcp_window_scaling))
12016 			return -EINVAL;
12017 
12018 		if (attrs->snd_wscale > TCP_MAX_WSCALE ||
12019 		    attrs->rcv_wscale > TCP_MAX_WSCALE)
12020 			return -EINVAL;
12021 	}
12022 
12023 	if (attrs->sack_ok && !READ_ONCE(net->ipv4.sysctl_tcp_sack))
12024 		return -EINVAL;
12025 
12026 	if (attrs->tstamp_ok) {
12027 		if (!READ_ONCE(net->ipv4.sysctl_tcp_timestamps))
12028 			return -EINVAL;
12029 
12030 		tsoff = attrs->rcv_tsecr - tcp_ns_to_ts(attrs->usec_ts_ok, tcp_clock_ns());
12031 	}
12032 
12033 	req = inet_reqsk_alloc(ops, sk, false);
12034 	if (!req)
12035 		return -ENOMEM;
12036 
12037 	ireq = inet_rsk(req);
12038 	treq = tcp_rsk(req);
12039 
12040 	req->rsk_listener = sk;
12041 	req->syncookie = 1;
12042 	req->mss = attrs->mss;
12043 	req->ts_recent = attrs->rcv_tsval;
12044 
12045 	ireq->snd_wscale = attrs->snd_wscale;
12046 	ireq->rcv_wscale = attrs->rcv_wscale;
12047 	ireq->tstamp_ok	= !!attrs->tstamp_ok;
12048 	ireq->sack_ok = !!attrs->sack_ok;
12049 	ireq->wscale_ok = !!attrs->wscale_ok;
12050 	ireq->ecn_ok = !!attrs->ecn_ok;
12051 
12052 	treq->req_usec_ts = !!attrs->usec_ts_ok;
12053 	treq->ts_off = tsoff;
12054 
12055 	skb_orphan(skb);
12056 	skb->sk = req_to_sk(req);
12057 	skb->destructor = sock_pfree;
12058 
12059 	return 0;
12060 #else
12061 	return -EOPNOTSUPP;
12062 #endif
12063 }
12064 
12065 __bpf_kfunc_end_defs();
12066 
bpf_dynptr_from_skb_rdonly(struct __sk_buff * skb,u64 flags,struct bpf_dynptr * ptr__uninit)12067 int bpf_dynptr_from_skb_rdonly(struct __sk_buff *skb, u64 flags,
12068 			       struct bpf_dynptr *ptr__uninit)
12069 {
12070 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)ptr__uninit;
12071 	int err;
12072 
12073 	err = bpf_dynptr_from_skb(skb, flags, ptr__uninit);
12074 	if (err)
12075 		return err;
12076 
12077 	bpf_dynptr_set_rdonly(ptr);
12078 
12079 	return 0;
12080 }
12081 
12082 BTF_KFUNCS_START(bpf_kfunc_check_set_skb)
12083 BTF_ID_FLAGS(func, bpf_dynptr_from_skb, KF_TRUSTED_ARGS)
12084 BTF_KFUNCS_END(bpf_kfunc_check_set_skb)
12085 
12086 BTF_KFUNCS_START(bpf_kfunc_check_set_xdp)
12087 BTF_ID_FLAGS(func, bpf_dynptr_from_xdp)
12088 BTF_KFUNCS_END(bpf_kfunc_check_set_xdp)
12089 
12090 BTF_KFUNCS_START(bpf_kfunc_check_set_sock_addr)
12091 BTF_ID_FLAGS(func, bpf_sock_addr_set_sun_path)
12092 BTF_KFUNCS_END(bpf_kfunc_check_set_sock_addr)
12093 
12094 BTF_KFUNCS_START(bpf_kfunc_check_set_tcp_reqsk)
12095 BTF_ID_FLAGS(func, bpf_sk_assign_tcp_reqsk, KF_TRUSTED_ARGS)
12096 BTF_KFUNCS_END(bpf_kfunc_check_set_tcp_reqsk)
12097 
12098 static const struct btf_kfunc_id_set bpf_kfunc_set_skb = {
12099 	.owner = THIS_MODULE,
12100 	.set = &bpf_kfunc_check_set_skb,
12101 };
12102 
12103 static const struct btf_kfunc_id_set bpf_kfunc_set_xdp = {
12104 	.owner = THIS_MODULE,
12105 	.set = &bpf_kfunc_check_set_xdp,
12106 };
12107 
12108 static const struct btf_kfunc_id_set bpf_kfunc_set_sock_addr = {
12109 	.owner = THIS_MODULE,
12110 	.set = &bpf_kfunc_check_set_sock_addr,
12111 };
12112 
12113 static const struct btf_kfunc_id_set bpf_kfunc_set_tcp_reqsk = {
12114 	.owner = THIS_MODULE,
12115 	.set = &bpf_kfunc_check_set_tcp_reqsk,
12116 };
12117 
bpf_kfunc_init(void)12118 static int __init bpf_kfunc_init(void)
12119 {
12120 	int ret;
12121 
12122 	ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &bpf_kfunc_set_skb);
12123 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_ACT, &bpf_kfunc_set_skb);
12124 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SK_SKB, &bpf_kfunc_set_skb);
12125 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SOCKET_FILTER, &bpf_kfunc_set_skb);
12126 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, &bpf_kfunc_set_skb);
12127 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_OUT, &bpf_kfunc_set_skb);
12128 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_IN, &bpf_kfunc_set_skb);
12129 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_XMIT, &bpf_kfunc_set_skb);
12130 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_SEG6LOCAL, &bpf_kfunc_set_skb);
12131 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_NETFILTER, &bpf_kfunc_set_skb);
12132 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_kfunc_set_skb);
12133 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &bpf_kfunc_set_xdp);
12134 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
12135 					       &bpf_kfunc_set_sock_addr);
12136 	return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &bpf_kfunc_set_tcp_reqsk);
12137 }
12138 late_initcall(bpf_kfunc_init);
12139 
12140 __bpf_kfunc_start_defs();
12141 
12142 /* bpf_sock_destroy: Destroy the given socket with ECONNABORTED error code.
12143  *
12144  * The function expects a non-NULL pointer to a socket, and invokes the
12145  * protocol specific socket destroy handlers.
12146  *
12147  * The helper can only be called from BPF contexts that have acquired the socket
12148  * locks.
12149  *
12150  * Parameters:
12151  * @sock: Pointer to socket to be destroyed
12152  *
12153  * Return:
12154  * On error, may return EPROTONOSUPPORT, EINVAL.
12155  * EPROTONOSUPPORT if protocol specific destroy handler is not supported.
12156  * 0 otherwise
12157  */
bpf_sock_destroy(struct sock_common * sock)12158 __bpf_kfunc int bpf_sock_destroy(struct sock_common *sock)
12159 {
12160 	struct sock *sk = (struct sock *)sock;
12161 
12162 	/* The locking semantics that allow for synchronous execution of the
12163 	 * destroy handlers are only supported for TCP and UDP.
12164 	 * Supporting protocols will need to acquire sock lock in the BPF context
12165 	 * prior to invoking this kfunc.
12166 	 */
12167 	if (!sk->sk_prot->diag_destroy || (sk->sk_protocol != IPPROTO_TCP &&
12168 					   sk->sk_protocol != IPPROTO_UDP))
12169 		return -EOPNOTSUPP;
12170 
12171 	return sk->sk_prot->diag_destroy(sk, ECONNABORTED);
12172 }
12173 
12174 __bpf_kfunc_end_defs();
12175 
12176 BTF_KFUNCS_START(bpf_sk_iter_kfunc_ids)
BTF_ID_FLAGS(func,bpf_sock_destroy,KF_TRUSTED_ARGS)12177 BTF_ID_FLAGS(func, bpf_sock_destroy, KF_TRUSTED_ARGS)
12178 BTF_KFUNCS_END(bpf_sk_iter_kfunc_ids)
12179 
12180 static int tracing_iter_filter(const struct bpf_prog *prog, u32 kfunc_id)
12181 {
12182 	if (btf_id_set8_contains(&bpf_sk_iter_kfunc_ids, kfunc_id) &&
12183 	    prog->expected_attach_type != BPF_TRACE_ITER)
12184 		return -EACCES;
12185 	return 0;
12186 }
12187 
12188 static const struct btf_kfunc_id_set bpf_sk_iter_kfunc_set = {
12189 	.owner = THIS_MODULE,
12190 	.set   = &bpf_sk_iter_kfunc_ids,
12191 	.filter = tracing_iter_filter,
12192 };
12193 
init_subsystem(void)12194 static int init_subsystem(void)
12195 {
12196 	return register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_sk_iter_kfunc_set);
12197 }
12198 late_initcall(init_subsystem);
12199