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