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