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