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