xref: /linux-6.15/kernel/trace/bpf_trace.c (revision c8a950d0)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2011-2015 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  */
5 #include <linux/kernel.h>
6 #include <linux/types.h>
7 #include <linux/slab.h>
8 #include <linux/bpf.h>
9 #include <linux/bpf_perf_event.h>
10 #include <linux/btf.h>
11 #include <linux/filter.h>
12 #include <linux/uaccess.h>
13 #include <linux/ctype.h>
14 #include <linux/kprobes.h>
15 #include <linux/spinlock.h>
16 #include <linux/syscalls.h>
17 #include <linux/error-injection.h>
18 #include <linux/btf_ids.h>
19 
20 #include <uapi/linux/bpf.h>
21 #include <uapi/linux/btf.h>
22 
23 #include <asm/tlb.h>
24 
25 #include "trace_probe.h"
26 #include "trace.h"
27 
28 #define CREATE_TRACE_POINTS
29 #include "bpf_trace.h"
30 
31 #define bpf_event_rcu_dereference(p)					\
32 	rcu_dereference_protected(p, lockdep_is_held(&bpf_event_mutex))
33 
34 #ifdef CONFIG_MODULES
35 struct bpf_trace_module {
36 	struct module *module;
37 	struct list_head list;
38 };
39 
40 static LIST_HEAD(bpf_trace_modules);
41 static DEFINE_MUTEX(bpf_module_mutex);
42 
43 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
44 {
45 	struct bpf_raw_event_map *btp, *ret = NULL;
46 	struct bpf_trace_module *btm;
47 	unsigned int i;
48 
49 	mutex_lock(&bpf_module_mutex);
50 	list_for_each_entry(btm, &bpf_trace_modules, list) {
51 		for (i = 0; i < btm->module->num_bpf_raw_events; ++i) {
52 			btp = &btm->module->bpf_raw_events[i];
53 			if (!strcmp(btp->tp->name, name)) {
54 				if (try_module_get(btm->module))
55 					ret = btp;
56 				goto out;
57 			}
58 		}
59 	}
60 out:
61 	mutex_unlock(&bpf_module_mutex);
62 	return ret;
63 }
64 #else
65 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
66 {
67 	return NULL;
68 }
69 #endif /* CONFIG_MODULES */
70 
71 u64 bpf_get_stackid(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
72 u64 bpf_get_stack(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
73 
74 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
75 				  u64 flags, const struct btf **btf,
76 				  s32 *btf_id);
77 
78 /**
79  * trace_call_bpf - invoke BPF program
80  * @call: tracepoint event
81  * @ctx: opaque context pointer
82  *
83  * kprobe handlers execute BPF programs via this helper.
84  * Can be used from static tracepoints in the future.
85  *
86  * Return: BPF programs always return an integer which is interpreted by
87  * kprobe handler as:
88  * 0 - return from kprobe (event is filtered out)
89  * 1 - store kprobe event into ring buffer
90  * Other values are reserved and currently alias to 1
91  */
92 unsigned int trace_call_bpf(struct trace_event_call *call, void *ctx)
93 {
94 	unsigned int ret;
95 
96 	if (in_nmi()) /* not supported yet */
97 		return 1;
98 
99 	cant_sleep();
100 
101 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
102 		/*
103 		 * since some bpf program is already running on this cpu,
104 		 * don't call into another bpf program (same or different)
105 		 * and don't send kprobe event into ring-buffer,
106 		 * so return zero here
107 		 */
108 		ret = 0;
109 		goto out;
110 	}
111 
112 	/*
113 	 * Instead of moving rcu_read_lock/rcu_dereference/rcu_read_unlock
114 	 * to all call sites, we did a bpf_prog_array_valid() there to check
115 	 * whether call->prog_array is empty or not, which is
116 	 * a heurisitc to speed up execution.
117 	 *
118 	 * If bpf_prog_array_valid() fetched prog_array was
119 	 * non-NULL, we go into trace_call_bpf() and do the actual
120 	 * proper rcu_dereference() under RCU lock.
121 	 * If it turns out that prog_array is NULL then, we bail out.
122 	 * For the opposite, if the bpf_prog_array_valid() fetched pointer
123 	 * was NULL, you'll skip the prog_array with the risk of missing
124 	 * out of events when it was updated in between this and the
125 	 * rcu_dereference() which is accepted risk.
126 	 */
127 	ret = BPF_PROG_RUN_ARRAY_CHECK(call->prog_array, ctx, BPF_PROG_RUN);
128 
129  out:
130 	__this_cpu_dec(bpf_prog_active);
131 
132 	return ret;
133 }
134 
135 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
136 BPF_CALL_2(bpf_override_return, struct pt_regs *, regs, unsigned long, rc)
137 {
138 	regs_set_return_value(regs, rc);
139 	override_function_with_return(regs);
140 	return 0;
141 }
142 
143 static const struct bpf_func_proto bpf_override_return_proto = {
144 	.func		= bpf_override_return,
145 	.gpl_only	= true,
146 	.ret_type	= RET_INTEGER,
147 	.arg1_type	= ARG_PTR_TO_CTX,
148 	.arg2_type	= ARG_ANYTHING,
149 };
150 #endif
151 
152 static __always_inline int
153 bpf_probe_read_user_common(void *dst, u32 size, const void __user *unsafe_ptr)
154 {
155 	int ret;
156 
157 	ret = copy_from_user_nofault(dst, unsafe_ptr, size);
158 	if (unlikely(ret < 0))
159 		memset(dst, 0, size);
160 	return ret;
161 }
162 
163 BPF_CALL_3(bpf_probe_read_user, void *, dst, u32, size,
164 	   const void __user *, unsafe_ptr)
165 {
166 	return bpf_probe_read_user_common(dst, size, unsafe_ptr);
167 }
168 
169 const struct bpf_func_proto bpf_probe_read_user_proto = {
170 	.func		= bpf_probe_read_user,
171 	.gpl_only	= true,
172 	.ret_type	= RET_INTEGER,
173 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
174 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
175 	.arg3_type	= ARG_ANYTHING,
176 };
177 
178 static __always_inline int
179 bpf_probe_read_user_str_common(void *dst, u32 size,
180 			       const void __user *unsafe_ptr)
181 {
182 	int ret;
183 
184 	ret = strncpy_from_user_nofault(dst, unsafe_ptr, size);
185 	if (unlikely(ret < 0))
186 		memset(dst, 0, size);
187 	return ret;
188 }
189 
190 BPF_CALL_3(bpf_probe_read_user_str, void *, dst, u32, size,
191 	   const void __user *, unsafe_ptr)
192 {
193 	return bpf_probe_read_user_str_common(dst, size, unsafe_ptr);
194 }
195 
196 const struct bpf_func_proto bpf_probe_read_user_str_proto = {
197 	.func		= bpf_probe_read_user_str,
198 	.gpl_only	= true,
199 	.ret_type	= RET_INTEGER,
200 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
201 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
202 	.arg3_type	= ARG_ANYTHING,
203 };
204 
205 static __always_inline int
206 bpf_probe_read_kernel_common(void *dst, u32 size, const void *unsafe_ptr)
207 {
208 	int ret = security_locked_down(LOCKDOWN_BPF_READ);
209 
210 	if (unlikely(ret < 0))
211 		goto fail;
212 	ret = copy_from_kernel_nofault(dst, unsafe_ptr, size);
213 	if (unlikely(ret < 0))
214 		goto fail;
215 	return ret;
216 fail:
217 	memset(dst, 0, size);
218 	return ret;
219 }
220 
221 BPF_CALL_3(bpf_probe_read_kernel, void *, dst, u32, size,
222 	   const void *, unsafe_ptr)
223 {
224 	return bpf_probe_read_kernel_common(dst, size, unsafe_ptr);
225 }
226 
227 const struct bpf_func_proto bpf_probe_read_kernel_proto = {
228 	.func		= bpf_probe_read_kernel,
229 	.gpl_only	= true,
230 	.ret_type	= RET_INTEGER,
231 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
232 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
233 	.arg3_type	= ARG_ANYTHING,
234 };
235 
236 static __always_inline int
237 bpf_probe_read_kernel_str_common(void *dst, u32 size, const void *unsafe_ptr)
238 {
239 	int ret = security_locked_down(LOCKDOWN_BPF_READ);
240 
241 	if (unlikely(ret < 0))
242 		goto fail;
243 
244 	/*
245 	 * The strncpy_from_kernel_nofault() call will likely not fill the
246 	 * entire buffer, but that's okay in this circumstance as we're probing
247 	 * arbitrary memory anyway similar to bpf_probe_read_*() and might
248 	 * as well probe the stack. Thus, memory is explicitly cleared
249 	 * only in error case, so that improper users ignoring return
250 	 * code altogether don't copy garbage; otherwise length of string
251 	 * is returned that can be used for bpf_perf_event_output() et al.
252 	 */
253 	ret = strncpy_from_kernel_nofault(dst, unsafe_ptr, size);
254 	if (unlikely(ret < 0))
255 		goto fail;
256 
257 	return ret;
258 fail:
259 	memset(dst, 0, size);
260 	return ret;
261 }
262 
263 BPF_CALL_3(bpf_probe_read_kernel_str, void *, dst, u32, size,
264 	   const void *, unsafe_ptr)
265 {
266 	return bpf_probe_read_kernel_str_common(dst, size, unsafe_ptr);
267 }
268 
269 const struct bpf_func_proto bpf_probe_read_kernel_str_proto = {
270 	.func		= bpf_probe_read_kernel_str,
271 	.gpl_only	= true,
272 	.ret_type	= RET_INTEGER,
273 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
274 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
275 	.arg3_type	= ARG_ANYTHING,
276 };
277 
278 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
279 BPF_CALL_3(bpf_probe_read_compat, void *, dst, u32, size,
280 	   const void *, unsafe_ptr)
281 {
282 	if ((unsigned long)unsafe_ptr < TASK_SIZE) {
283 		return bpf_probe_read_user_common(dst, size,
284 				(__force void __user *)unsafe_ptr);
285 	}
286 	return bpf_probe_read_kernel_common(dst, size, unsafe_ptr);
287 }
288 
289 static const struct bpf_func_proto bpf_probe_read_compat_proto = {
290 	.func		= bpf_probe_read_compat,
291 	.gpl_only	= true,
292 	.ret_type	= RET_INTEGER,
293 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
294 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
295 	.arg3_type	= ARG_ANYTHING,
296 };
297 
298 BPF_CALL_3(bpf_probe_read_compat_str, void *, dst, u32, size,
299 	   const void *, unsafe_ptr)
300 {
301 	if ((unsigned long)unsafe_ptr < TASK_SIZE) {
302 		return bpf_probe_read_user_str_common(dst, size,
303 				(__force void __user *)unsafe_ptr);
304 	}
305 	return bpf_probe_read_kernel_str_common(dst, size, unsafe_ptr);
306 }
307 
308 static const struct bpf_func_proto bpf_probe_read_compat_str_proto = {
309 	.func		= bpf_probe_read_compat_str,
310 	.gpl_only	= true,
311 	.ret_type	= RET_INTEGER,
312 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
313 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
314 	.arg3_type	= ARG_ANYTHING,
315 };
316 #endif /* CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE */
317 
318 BPF_CALL_3(bpf_probe_write_user, void __user *, unsafe_ptr, const void *, src,
319 	   u32, size)
320 {
321 	/*
322 	 * Ensure we're in user context which is safe for the helper to
323 	 * run. This helper has no business in a kthread.
324 	 *
325 	 * access_ok() should prevent writing to non-user memory, but in
326 	 * some situations (nommu, temporary switch, etc) access_ok() does
327 	 * not provide enough validation, hence the check on KERNEL_DS.
328 	 *
329 	 * nmi_uaccess_okay() ensures the probe is not run in an interim
330 	 * state, when the task or mm are switched. This is specifically
331 	 * required to prevent the use of temporary mm.
332 	 */
333 
334 	if (unlikely(in_interrupt() ||
335 		     current->flags & (PF_KTHREAD | PF_EXITING)))
336 		return -EPERM;
337 	if (unlikely(uaccess_kernel()))
338 		return -EPERM;
339 	if (unlikely(!nmi_uaccess_okay()))
340 		return -EPERM;
341 
342 	return copy_to_user_nofault(unsafe_ptr, src, size);
343 }
344 
345 static const struct bpf_func_proto bpf_probe_write_user_proto = {
346 	.func		= bpf_probe_write_user,
347 	.gpl_only	= true,
348 	.ret_type	= RET_INTEGER,
349 	.arg1_type	= ARG_ANYTHING,
350 	.arg2_type	= ARG_PTR_TO_MEM,
351 	.arg3_type	= ARG_CONST_SIZE,
352 };
353 
354 static const struct bpf_func_proto *bpf_get_probe_write_proto(void)
355 {
356 	if (!capable(CAP_SYS_ADMIN))
357 		return NULL;
358 
359 	pr_warn_ratelimited("%s[%d] is installing a program with bpf_probe_write_user helper that may corrupt user memory!",
360 			    current->comm, task_pid_nr(current));
361 
362 	return &bpf_probe_write_user_proto;
363 }
364 
365 static void bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype,
366 		size_t bufsz)
367 {
368 	void __user *user_ptr = (__force void __user *)unsafe_ptr;
369 
370 	buf[0] = 0;
371 
372 	switch (fmt_ptype) {
373 	case 's':
374 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
375 		if ((unsigned long)unsafe_ptr < TASK_SIZE) {
376 			strncpy_from_user_nofault(buf, user_ptr, bufsz);
377 			break;
378 		}
379 		fallthrough;
380 #endif
381 	case 'k':
382 		strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz);
383 		break;
384 	case 'u':
385 		strncpy_from_user_nofault(buf, user_ptr, bufsz);
386 		break;
387 	}
388 }
389 
390 static DEFINE_RAW_SPINLOCK(trace_printk_lock);
391 
392 #define BPF_TRACE_PRINTK_SIZE   1024
393 
394 static __printf(1, 0) int bpf_do_trace_printk(const char *fmt, ...)
395 {
396 	static char buf[BPF_TRACE_PRINTK_SIZE];
397 	unsigned long flags;
398 	va_list ap;
399 	int ret;
400 
401 	raw_spin_lock_irqsave(&trace_printk_lock, flags);
402 	va_start(ap, fmt);
403 	ret = vsnprintf(buf, sizeof(buf), fmt, ap);
404 	va_end(ap);
405 	/* vsnprintf() will not append null for zero-length strings */
406 	if (ret == 0)
407 		buf[0] = '\0';
408 	trace_bpf_trace_printk(buf);
409 	raw_spin_unlock_irqrestore(&trace_printk_lock, flags);
410 
411 	return ret;
412 }
413 
414 /*
415  * Only limited trace_printk() conversion specifiers allowed:
416  * %d %i %u %x %ld %li %lu %lx %lld %lli %llu %llx %p %pB %pks %pus %s
417  */
418 BPF_CALL_5(bpf_trace_printk, char *, fmt, u32, fmt_size, u64, arg1,
419 	   u64, arg2, u64, arg3)
420 {
421 	int i, mod[3] = {}, fmt_cnt = 0;
422 	char buf[64], fmt_ptype;
423 	void *unsafe_ptr = NULL;
424 	bool str_seen = false;
425 
426 	/*
427 	 * bpf_check()->check_func_arg()->check_stack_boundary()
428 	 * guarantees that fmt points to bpf program stack,
429 	 * fmt_size bytes of it were initialized and fmt_size > 0
430 	 */
431 	if (fmt[--fmt_size] != 0)
432 		return -EINVAL;
433 
434 	/* check format string for allowed specifiers */
435 	for (i = 0; i < fmt_size; i++) {
436 		if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i]))
437 			return -EINVAL;
438 
439 		if (fmt[i] != '%')
440 			continue;
441 
442 		if (fmt_cnt >= 3)
443 			return -EINVAL;
444 
445 		/* fmt[i] != 0 && fmt[last] == 0, so we can access fmt[i + 1] */
446 		i++;
447 		if (fmt[i] == 'l') {
448 			mod[fmt_cnt]++;
449 			i++;
450 		} else if (fmt[i] == 'p') {
451 			mod[fmt_cnt]++;
452 			if ((fmt[i + 1] == 'k' ||
453 			     fmt[i + 1] == 'u') &&
454 			    fmt[i + 2] == 's') {
455 				fmt_ptype = fmt[i + 1];
456 				i += 2;
457 				goto fmt_str;
458 			}
459 
460 			if (fmt[i + 1] == 'B') {
461 				i++;
462 				goto fmt_next;
463 			}
464 
465 			/* disallow any further format extensions */
466 			if (fmt[i + 1] != 0 &&
467 			    !isspace(fmt[i + 1]) &&
468 			    !ispunct(fmt[i + 1]))
469 				return -EINVAL;
470 
471 			goto fmt_next;
472 		} else if (fmt[i] == 's') {
473 			mod[fmt_cnt]++;
474 			fmt_ptype = fmt[i];
475 fmt_str:
476 			if (str_seen)
477 				/* allow only one '%s' per fmt string */
478 				return -EINVAL;
479 			str_seen = true;
480 
481 			if (fmt[i + 1] != 0 &&
482 			    !isspace(fmt[i + 1]) &&
483 			    !ispunct(fmt[i + 1]))
484 				return -EINVAL;
485 
486 			switch (fmt_cnt) {
487 			case 0:
488 				unsafe_ptr = (void *)(long)arg1;
489 				arg1 = (long)buf;
490 				break;
491 			case 1:
492 				unsafe_ptr = (void *)(long)arg2;
493 				arg2 = (long)buf;
494 				break;
495 			case 2:
496 				unsafe_ptr = (void *)(long)arg3;
497 				arg3 = (long)buf;
498 				break;
499 			}
500 
501 			bpf_trace_copy_string(buf, unsafe_ptr, fmt_ptype,
502 					sizeof(buf));
503 			goto fmt_next;
504 		}
505 
506 		if (fmt[i] == 'l') {
507 			mod[fmt_cnt]++;
508 			i++;
509 		}
510 
511 		if (fmt[i] != 'i' && fmt[i] != 'd' &&
512 		    fmt[i] != 'u' && fmt[i] != 'x')
513 			return -EINVAL;
514 fmt_next:
515 		fmt_cnt++;
516 	}
517 
518 /* Horrid workaround for getting va_list handling working with different
519  * argument type combinations generically for 32 and 64 bit archs.
520  */
521 #define __BPF_TP_EMIT()	__BPF_ARG3_TP()
522 #define __BPF_TP(...)							\
523 	bpf_do_trace_printk(fmt, ##__VA_ARGS__)
524 
525 #define __BPF_ARG1_TP(...)						\
526 	((mod[0] == 2 || (mod[0] == 1 && __BITS_PER_LONG == 64))	\
527 	  ? __BPF_TP(arg1, ##__VA_ARGS__)				\
528 	  : ((mod[0] == 1 || (mod[0] == 0 && __BITS_PER_LONG == 32))	\
529 	      ? __BPF_TP((long)arg1, ##__VA_ARGS__)			\
530 	      : __BPF_TP((u32)arg1, ##__VA_ARGS__)))
531 
532 #define __BPF_ARG2_TP(...)						\
533 	((mod[1] == 2 || (mod[1] == 1 && __BITS_PER_LONG == 64))	\
534 	  ? __BPF_ARG1_TP(arg2, ##__VA_ARGS__)				\
535 	  : ((mod[1] == 1 || (mod[1] == 0 && __BITS_PER_LONG == 32))	\
536 	      ? __BPF_ARG1_TP((long)arg2, ##__VA_ARGS__)		\
537 	      : __BPF_ARG1_TP((u32)arg2, ##__VA_ARGS__)))
538 
539 #define __BPF_ARG3_TP(...)						\
540 	((mod[2] == 2 || (mod[2] == 1 && __BITS_PER_LONG == 64))	\
541 	  ? __BPF_ARG2_TP(arg3, ##__VA_ARGS__)				\
542 	  : ((mod[2] == 1 || (mod[2] == 0 && __BITS_PER_LONG == 32))	\
543 	      ? __BPF_ARG2_TP((long)arg3, ##__VA_ARGS__)		\
544 	      : __BPF_ARG2_TP((u32)arg3, ##__VA_ARGS__)))
545 
546 	return __BPF_TP_EMIT();
547 }
548 
549 static const struct bpf_func_proto bpf_trace_printk_proto = {
550 	.func		= bpf_trace_printk,
551 	.gpl_only	= true,
552 	.ret_type	= RET_INTEGER,
553 	.arg1_type	= ARG_PTR_TO_MEM,
554 	.arg2_type	= ARG_CONST_SIZE,
555 };
556 
557 const struct bpf_func_proto *bpf_get_trace_printk_proto(void)
558 {
559 	/*
560 	 * This program might be calling bpf_trace_printk,
561 	 * so enable the associated bpf_trace/bpf_trace_printk event.
562 	 * Repeat this each time as it is possible a user has
563 	 * disabled bpf_trace_printk events.  By loading a program
564 	 * calling bpf_trace_printk() however the user has expressed
565 	 * the intent to see such events.
566 	 */
567 	if (trace_set_clr_event("bpf_trace", "bpf_trace_printk", 1))
568 		pr_warn_ratelimited("could not enable bpf_trace_printk events");
569 
570 	return &bpf_trace_printk_proto;
571 }
572 
573 #define MAX_SEQ_PRINTF_VARARGS		12
574 #define MAX_SEQ_PRINTF_MAX_MEMCPY	6
575 #define MAX_SEQ_PRINTF_STR_LEN		128
576 
577 struct bpf_seq_printf_buf {
578 	char buf[MAX_SEQ_PRINTF_MAX_MEMCPY][MAX_SEQ_PRINTF_STR_LEN];
579 };
580 static DEFINE_PER_CPU(struct bpf_seq_printf_buf, bpf_seq_printf_buf);
581 static DEFINE_PER_CPU(int, bpf_seq_printf_buf_used);
582 
583 BPF_CALL_5(bpf_seq_printf, struct seq_file *, m, char *, fmt, u32, fmt_size,
584 	   const void *, data, u32, data_len)
585 {
586 	int err = -EINVAL, fmt_cnt = 0, memcpy_cnt = 0;
587 	int i, buf_used, copy_size, num_args;
588 	u64 params[MAX_SEQ_PRINTF_VARARGS];
589 	struct bpf_seq_printf_buf *bufs;
590 	const u64 *args = data;
591 
592 	buf_used = this_cpu_inc_return(bpf_seq_printf_buf_used);
593 	if (WARN_ON_ONCE(buf_used > 1)) {
594 		err = -EBUSY;
595 		goto out;
596 	}
597 
598 	bufs = this_cpu_ptr(&bpf_seq_printf_buf);
599 
600 	/*
601 	 * bpf_check()->check_func_arg()->check_stack_boundary()
602 	 * guarantees that fmt points to bpf program stack,
603 	 * fmt_size bytes of it were initialized and fmt_size > 0
604 	 */
605 	if (fmt[--fmt_size] != 0)
606 		goto out;
607 
608 	if (data_len & 7)
609 		goto out;
610 
611 	for (i = 0; i < fmt_size; i++) {
612 		if (fmt[i] == '%') {
613 			if (fmt[i + 1] == '%')
614 				i++;
615 			else if (!data || !data_len)
616 				goto out;
617 		}
618 	}
619 
620 	num_args = data_len / 8;
621 
622 	/* check format string for allowed specifiers */
623 	for (i = 0; i < fmt_size; i++) {
624 		/* only printable ascii for now. */
625 		if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i])) {
626 			err = -EINVAL;
627 			goto out;
628 		}
629 
630 		if (fmt[i] != '%')
631 			continue;
632 
633 		if (fmt[i + 1] == '%') {
634 			i++;
635 			continue;
636 		}
637 
638 		if (fmt_cnt >= MAX_SEQ_PRINTF_VARARGS) {
639 			err = -E2BIG;
640 			goto out;
641 		}
642 
643 		if (fmt_cnt >= num_args) {
644 			err = -EINVAL;
645 			goto out;
646 		}
647 
648 		/* fmt[i] != 0 && fmt[last] == 0, so we can access fmt[i + 1] */
649 		i++;
650 
651 		/* skip optional "[0 +-][num]" width formating field */
652 		while (fmt[i] == '0' || fmt[i] == '+'  || fmt[i] == '-' ||
653 		       fmt[i] == ' ')
654 			i++;
655 		if (fmt[i] >= '1' && fmt[i] <= '9') {
656 			i++;
657 			while (fmt[i] >= '0' && fmt[i] <= '9')
658 				i++;
659 		}
660 
661 		if (fmt[i] == 's') {
662 			void *unsafe_ptr;
663 
664 			/* try our best to copy */
665 			if (memcpy_cnt >= MAX_SEQ_PRINTF_MAX_MEMCPY) {
666 				err = -E2BIG;
667 				goto out;
668 			}
669 
670 			unsafe_ptr = (void *)(long)args[fmt_cnt];
671 			err = strncpy_from_kernel_nofault(bufs->buf[memcpy_cnt],
672 					unsafe_ptr, MAX_SEQ_PRINTF_STR_LEN);
673 			if (err < 0)
674 				bufs->buf[memcpy_cnt][0] = '\0';
675 			params[fmt_cnt] = (u64)(long)bufs->buf[memcpy_cnt];
676 
677 			fmt_cnt++;
678 			memcpy_cnt++;
679 			continue;
680 		}
681 
682 		if (fmt[i] == 'p') {
683 			if (fmt[i + 1] == 0 ||
684 			    fmt[i + 1] == 'K' ||
685 			    fmt[i + 1] == 'x' ||
686 			    fmt[i + 1] == 'B') {
687 				/* just kernel pointers */
688 				params[fmt_cnt] = args[fmt_cnt];
689 				fmt_cnt++;
690 				continue;
691 			}
692 
693 			/* only support "%pI4", "%pi4", "%pI6" and "%pi6". */
694 			if (fmt[i + 1] != 'i' && fmt[i + 1] != 'I') {
695 				err = -EINVAL;
696 				goto out;
697 			}
698 			if (fmt[i + 2] != '4' && fmt[i + 2] != '6') {
699 				err = -EINVAL;
700 				goto out;
701 			}
702 
703 			if (memcpy_cnt >= MAX_SEQ_PRINTF_MAX_MEMCPY) {
704 				err = -E2BIG;
705 				goto out;
706 			}
707 
708 
709 			copy_size = (fmt[i + 2] == '4') ? 4 : 16;
710 
711 			err = copy_from_kernel_nofault(bufs->buf[memcpy_cnt],
712 						(void *) (long) args[fmt_cnt],
713 						copy_size);
714 			if (err < 0)
715 				memset(bufs->buf[memcpy_cnt], 0, copy_size);
716 			params[fmt_cnt] = (u64)(long)bufs->buf[memcpy_cnt];
717 
718 			i += 2;
719 			fmt_cnt++;
720 			memcpy_cnt++;
721 			continue;
722 		}
723 
724 		if (fmt[i] == 'l') {
725 			i++;
726 			if (fmt[i] == 'l')
727 				i++;
728 		}
729 
730 		if (fmt[i] != 'i' && fmt[i] != 'd' &&
731 		    fmt[i] != 'u' && fmt[i] != 'x' &&
732 		    fmt[i] != 'X') {
733 			err = -EINVAL;
734 			goto out;
735 		}
736 
737 		params[fmt_cnt] = args[fmt_cnt];
738 		fmt_cnt++;
739 	}
740 
741 	/* Maximumly we can have MAX_SEQ_PRINTF_VARARGS parameter, just give
742 	 * all of them to seq_printf().
743 	 */
744 	seq_printf(m, fmt, params[0], params[1], params[2], params[3],
745 		   params[4], params[5], params[6], params[7], params[8],
746 		   params[9], params[10], params[11]);
747 
748 	err = seq_has_overflowed(m) ? -EOVERFLOW : 0;
749 out:
750 	this_cpu_dec(bpf_seq_printf_buf_used);
751 	return err;
752 }
753 
754 BTF_ID_LIST_SINGLE(btf_seq_file_ids, struct, seq_file)
755 
756 static const struct bpf_func_proto bpf_seq_printf_proto = {
757 	.func		= bpf_seq_printf,
758 	.gpl_only	= true,
759 	.ret_type	= RET_INTEGER,
760 	.arg1_type	= ARG_PTR_TO_BTF_ID,
761 	.arg1_btf_id	= &btf_seq_file_ids[0],
762 	.arg2_type	= ARG_PTR_TO_MEM,
763 	.arg3_type	= ARG_CONST_SIZE,
764 	.arg4_type      = ARG_PTR_TO_MEM_OR_NULL,
765 	.arg5_type      = ARG_CONST_SIZE_OR_ZERO,
766 };
767 
768 BPF_CALL_3(bpf_seq_write, struct seq_file *, m, const void *, data, u32, len)
769 {
770 	return seq_write(m, data, len) ? -EOVERFLOW : 0;
771 }
772 
773 static const struct bpf_func_proto bpf_seq_write_proto = {
774 	.func		= bpf_seq_write,
775 	.gpl_only	= true,
776 	.ret_type	= RET_INTEGER,
777 	.arg1_type	= ARG_PTR_TO_BTF_ID,
778 	.arg1_btf_id	= &btf_seq_file_ids[0],
779 	.arg2_type	= ARG_PTR_TO_MEM,
780 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
781 };
782 
783 BPF_CALL_4(bpf_seq_printf_btf, struct seq_file *, m, struct btf_ptr *, ptr,
784 	   u32, btf_ptr_size, u64, flags)
785 {
786 	const struct btf *btf;
787 	s32 btf_id;
788 	int ret;
789 
790 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
791 	if (ret)
792 		return ret;
793 
794 	return btf_type_seq_show_flags(btf, btf_id, ptr->ptr, m, flags);
795 }
796 
797 static const struct bpf_func_proto bpf_seq_printf_btf_proto = {
798 	.func		= bpf_seq_printf_btf,
799 	.gpl_only	= true,
800 	.ret_type	= RET_INTEGER,
801 	.arg1_type	= ARG_PTR_TO_BTF_ID,
802 	.arg1_btf_id	= &btf_seq_file_ids[0],
803 	.arg2_type	= ARG_PTR_TO_MEM,
804 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
805 	.arg4_type	= ARG_ANYTHING,
806 };
807 
808 static __always_inline int
809 get_map_perf_counter(struct bpf_map *map, u64 flags,
810 		     u64 *value, u64 *enabled, u64 *running)
811 {
812 	struct bpf_array *array = container_of(map, struct bpf_array, map);
813 	unsigned int cpu = smp_processor_id();
814 	u64 index = flags & BPF_F_INDEX_MASK;
815 	struct bpf_event_entry *ee;
816 
817 	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
818 		return -EINVAL;
819 	if (index == BPF_F_CURRENT_CPU)
820 		index = cpu;
821 	if (unlikely(index >= array->map.max_entries))
822 		return -E2BIG;
823 
824 	ee = READ_ONCE(array->ptrs[index]);
825 	if (!ee)
826 		return -ENOENT;
827 
828 	return perf_event_read_local(ee->event, value, enabled, running);
829 }
830 
831 BPF_CALL_2(bpf_perf_event_read, struct bpf_map *, map, u64, flags)
832 {
833 	u64 value = 0;
834 	int err;
835 
836 	err = get_map_perf_counter(map, flags, &value, NULL, NULL);
837 	/*
838 	 * this api is ugly since we miss [-22..-2] range of valid
839 	 * counter values, but that's uapi
840 	 */
841 	if (err)
842 		return err;
843 	return value;
844 }
845 
846 static const struct bpf_func_proto bpf_perf_event_read_proto = {
847 	.func		= bpf_perf_event_read,
848 	.gpl_only	= true,
849 	.ret_type	= RET_INTEGER,
850 	.arg1_type	= ARG_CONST_MAP_PTR,
851 	.arg2_type	= ARG_ANYTHING,
852 };
853 
854 BPF_CALL_4(bpf_perf_event_read_value, struct bpf_map *, map, u64, flags,
855 	   struct bpf_perf_event_value *, buf, u32, size)
856 {
857 	int err = -EINVAL;
858 
859 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
860 		goto clear;
861 	err = get_map_perf_counter(map, flags, &buf->counter, &buf->enabled,
862 				   &buf->running);
863 	if (unlikely(err))
864 		goto clear;
865 	return 0;
866 clear:
867 	memset(buf, 0, size);
868 	return err;
869 }
870 
871 static const struct bpf_func_proto bpf_perf_event_read_value_proto = {
872 	.func		= bpf_perf_event_read_value,
873 	.gpl_only	= true,
874 	.ret_type	= RET_INTEGER,
875 	.arg1_type	= ARG_CONST_MAP_PTR,
876 	.arg2_type	= ARG_ANYTHING,
877 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
878 	.arg4_type	= ARG_CONST_SIZE,
879 };
880 
881 static __always_inline u64
882 __bpf_perf_event_output(struct pt_regs *regs, struct bpf_map *map,
883 			u64 flags, struct perf_sample_data *sd)
884 {
885 	struct bpf_array *array = container_of(map, struct bpf_array, map);
886 	unsigned int cpu = smp_processor_id();
887 	u64 index = flags & BPF_F_INDEX_MASK;
888 	struct bpf_event_entry *ee;
889 	struct perf_event *event;
890 
891 	if (index == BPF_F_CURRENT_CPU)
892 		index = cpu;
893 	if (unlikely(index >= array->map.max_entries))
894 		return -E2BIG;
895 
896 	ee = READ_ONCE(array->ptrs[index]);
897 	if (!ee)
898 		return -ENOENT;
899 
900 	event = ee->event;
901 	if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
902 		     event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
903 		return -EINVAL;
904 
905 	if (unlikely(event->oncpu != cpu))
906 		return -EOPNOTSUPP;
907 
908 	return perf_event_output(event, sd, regs);
909 }
910 
911 /*
912  * Support executing tracepoints in normal, irq, and nmi context that each call
913  * bpf_perf_event_output
914  */
915 struct bpf_trace_sample_data {
916 	struct perf_sample_data sds[3];
917 };
918 
919 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_trace_sds);
920 static DEFINE_PER_CPU(int, bpf_trace_nest_level);
921 BPF_CALL_5(bpf_perf_event_output, struct pt_regs *, regs, struct bpf_map *, map,
922 	   u64, flags, void *, data, u64, size)
923 {
924 	struct bpf_trace_sample_data *sds = this_cpu_ptr(&bpf_trace_sds);
925 	int nest_level = this_cpu_inc_return(bpf_trace_nest_level);
926 	struct perf_raw_record raw = {
927 		.frag = {
928 			.size = size,
929 			.data = data,
930 		},
931 	};
932 	struct perf_sample_data *sd;
933 	int err;
934 
935 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(sds->sds))) {
936 		err = -EBUSY;
937 		goto out;
938 	}
939 
940 	sd = &sds->sds[nest_level - 1];
941 
942 	if (unlikely(flags & ~(BPF_F_INDEX_MASK))) {
943 		err = -EINVAL;
944 		goto out;
945 	}
946 
947 	perf_sample_data_init(sd, 0, 0);
948 	sd->raw = &raw;
949 
950 	err = __bpf_perf_event_output(regs, map, flags, sd);
951 
952 out:
953 	this_cpu_dec(bpf_trace_nest_level);
954 	return err;
955 }
956 
957 static const struct bpf_func_proto bpf_perf_event_output_proto = {
958 	.func		= bpf_perf_event_output,
959 	.gpl_only	= true,
960 	.ret_type	= RET_INTEGER,
961 	.arg1_type	= ARG_PTR_TO_CTX,
962 	.arg2_type	= ARG_CONST_MAP_PTR,
963 	.arg3_type	= ARG_ANYTHING,
964 	.arg4_type	= ARG_PTR_TO_MEM,
965 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
966 };
967 
968 static DEFINE_PER_CPU(int, bpf_event_output_nest_level);
969 struct bpf_nested_pt_regs {
970 	struct pt_regs regs[3];
971 };
972 static DEFINE_PER_CPU(struct bpf_nested_pt_regs, bpf_pt_regs);
973 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_misc_sds);
974 
975 u64 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
976 		     void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
977 {
978 	int nest_level = this_cpu_inc_return(bpf_event_output_nest_level);
979 	struct perf_raw_frag frag = {
980 		.copy		= ctx_copy,
981 		.size		= ctx_size,
982 		.data		= ctx,
983 	};
984 	struct perf_raw_record raw = {
985 		.frag = {
986 			{
987 				.next	= ctx_size ? &frag : NULL,
988 			},
989 			.size	= meta_size,
990 			.data	= meta,
991 		},
992 	};
993 	struct perf_sample_data *sd;
994 	struct pt_regs *regs;
995 	u64 ret;
996 
997 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(bpf_misc_sds.sds))) {
998 		ret = -EBUSY;
999 		goto out;
1000 	}
1001 	sd = this_cpu_ptr(&bpf_misc_sds.sds[nest_level - 1]);
1002 	regs = this_cpu_ptr(&bpf_pt_regs.regs[nest_level - 1]);
1003 
1004 	perf_fetch_caller_regs(regs);
1005 	perf_sample_data_init(sd, 0, 0);
1006 	sd->raw = &raw;
1007 
1008 	ret = __bpf_perf_event_output(regs, map, flags, sd);
1009 out:
1010 	this_cpu_dec(bpf_event_output_nest_level);
1011 	return ret;
1012 }
1013 
1014 BPF_CALL_0(bpf_get_current_task)
1015 {
1016 	return (long) current;
1017 }
1018 
1019 const struct bpf_func_proto bpf_get_current_task_proto = {
1020 	.func		= bpf_get_current_task,
1021 	.gpl_only	= true,
1022 	.ret_type	= RET_INTEGER,
1023 };
1024 
1025 BPF_CALL_0(bpf_get_current_task_btf)
1026 {
1027 	return (unsigned long) current;
1028 }
1029 
1030 BTF_ID_LIST_SINGLE(bpf_get_current_btf_ids, struct, task_struct)
1031 
1032 static const struct bpf_func_proto bpf_get_current_task_btf_proto = {
1033 	.func		= bpf_get_current_task_btf,
1034 	.gpl_only	= true,
1035 	.ret_type	= RET_PTR_TO_BTF_ID,
1036 	.ret_btf_id	= &bpf_get_current_btf_ids[0],
1037 };
1038 
1039 BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
1040 {
1041 	struct bpf_array *array = container_of(map, struct bpf_array, map);
1042 	struct cgroup *cgrp;
1043 
1044 	if (unlikely(idx >= array->map.max_entries))
1045 		return -E2BIG;
1046 
1047 	cgrp = READ_ONCE(array->ptrs[idx]);
1048 	if (unlikely(!cgrp))
1049 		return -EAGAIN;
1050 
1051 	return task_under_cgroup_hierarchy(current, cgrp);
1052 }
1053 
1054 static const struct bpf_func_proto bpf_current_task_under_cgroup_proto = {
1055 	.func           = bpf_current_task_under_cgroup,
1056 	.gpl_only       = false,
1057 	.ret_type       = RET_INTEGER,
1058 	.arg1_type      = ARG_CONST_MAP_PTR,
1059 	.arg2_type      = ARG_ANYTHING,
1060 };
1061 
1062 struct send_signal_irq_work {
1063 	struct irq_work irq_work;
1064 	struct task_struct *task;
1065 	u32 sig;
1066 	enum pid_type type;
1067 };
1068 
1069 static DEFINE_PER_CPU(struct send_signal_irq_work, send_signal_work);
1070 
1071 static void do_bpf_send_signal(struct irq_work *entry)
1072 {
1073 	struct send_signal_irq_work *work;
1074 
1075 	work = container_of(entry, struct send_signal_irq_work, irq_work);
1076 	group_send_sig_info(work->sig, SEND_SIG_PRIV, work->task, work->type);
1077 }
1078 
1079 static int bpf_send_signal_common(u32 sig, enum pid_type type)
1080 {
1081 	struct send_signal_irq_work *work = NULL;
1082 
1083 	/* Similar to bpf_probe_write_user, task needs to be
1084 	 * in a sound condition and kernel memory access be
1085 	 * permitted in order to send signal to the current
1086 	 * task.
1087 	 */
1088 	if (unlikely(current->flags & (PF_KTHREAD | PF_EXITING)))
1089 		return -EPERM;
1090 	if (unlikely(uaccess_kernel()))
1091 		return -EPERM;
1092 	if (unlikely(!nmi_uaccess_okay()))
1093 		return -EPERM;
1094 
1095 	if (irqs_disabled()) {
1096 		/* Do an early check on signal validity. Otherwise,
1097 		 * the error is lost in deferred irq_work.
1098 		 */
1099 		if (unlikely(!valid_signal(sig)))
1100 			return -EINVAL;
1101 
1102 		work = this_cpu_ptr(&send_signal_work);
1103 		if (atomic_read(&work->irq_work.flags) & IRQ_WORK_BUSY)
1104 			return -EBUSY;
1105 
1106 		/* Add the current task, which is the target of sending signal,
1107 		 * to the irq_work. The current task may change when queued
1108 		 * irq works get executed.
1109 		 */
1110 		work->task = current;
1111 		work->sig = sig;
1112 		work->type = type;
1113 		irq_work_queue(&work->irq_work);
1114 		return 0;
1115 	}
1116 
1117 	return group_send_sig_info(sig, SEND_SIG_PRIV, current, type);
1118 }
1119 
1120 BPF_CALL_1(bpf_send_signal, u32, sig)
1121 {
1122 	return bpf_send_signal_common(sig, PIDTYPE_TGID);
1123 }
1124 
1125 static const struct bpf_func_proto bpf_send_signal_proto = {
1126 	.func		= bpf_send_signal,
1127 	.gpl_only	= false,
1128 	.ret_type	= RET_INTEGER,
1129 	.arg1_type	= ARG_ANYTHING,
1130 };
1131 
1132 BPF_CALL_1(bpf_send_signal_thread, u32, sig)
1133 {
1134 	return bpf_send_signal_common(sig, PIDTYPE_PID);
1135 }
1136 
1137 static const struct bpf_func_proto bpf_send_signal_thread_proto = {
1138 	.func		= bpf_send_signal_thread,
1139 	.gpl_only	= false,
1140 	.ret_type	= RET_INTEGER,
1141 	.arg1_type	= ARG_ANYTHING,
1142 };
1143 
1144 BPF_CALL_3(bpf_d_path, struct path *, path, char *, buf, u32, sz)
1145 {
1146 	long len;
1147 	char *p;
1148 
1149 	if (!sz)
1150 		return 0;
1151 
1152 	p = d_path(path, buf, sz);
1153 	if (IS_ERR(p)) {
1154 		len = PTR_ERR(p);
1155 	} else {
1156 		len = buf + sz - p;
1157 		memmove(buf, p, len);
1158 	}
1159 
1160 	return len;
1161 }
1162 
1163 BTF_SET_START(btf_allowlist_d_path)
1164 #ifdef CONFIG_SECURITY
1165 BTF_ID(func, security_file_permission)
1166 BTF_ID(func, security_inode_getattr)
1167 BTF_ID(func, security_file_open)
1168 #endif
1169 #ifdef CONFIG_SECURITY_PATH
1170 BTF_ID(func, security_path_truncate)
1171 #endif
1172 BTF_ID(func, vfs_truncate)
1173 BTF_ID(func, vfs_fallocate)
1174 BTF_ID(func, dentry_open)
1175 BTF_ID(func, vfs_getattr)
1176 BTF_ID(func, filp_close)
1177 BTF_SET_END(btf_allowlist_d_path)
1178 
1179 static bool bpf_d_path_allowed(const struct bpf_prog *prog)
1180 {
1181 	return btf_id_set_contains(&btf_allowlist_d_path, prog->aux->attach_btf_id);
1182 }
1183 
1184 BTF_ID_LIST_SINGLE(bpf_d_path_btf_ids, struct, path)
1185 
1186 static const struct bpf_func_proto bpf_d_path_proto = {
1187 	.func		= bpf_d_path,
1188 	.gpl_only	= false,
1189 	.ret_type	= RET_INTEGER,
1190 	.arg1_type	= ARG_PTR_TO_BTF_ID,
1191 	.arg1_btf_id	= &bpf_d_path_btf_ids[0],
1192 	.arg2_type	= ARG_PTR_TO_MEM,
1193 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
1194 	.allowed	= bpf_d_path_allowed,
1195 };
1196 
1197 #define BTF_F_ALL	(BTF_F_COMPACT  | BTF_F_NONAME | \
1198 			 BTF_F_PTR_RAW | BTF_F_ZERO)
1199 
1200 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
1201 				  u64 flags, const struct btf **btf,
1202 				  s32 *btf_id)
1203 {
1204 	const struct btf_type *t;
1205 
1206 	if (unlikely(flags & ~(BTF_F_ALL)))
1207 		return -EINVAL;
1208 
1209 	if (btf_ptr_size != sizeof(struct btf_ptr))
1210 		return -EINVAL;
1211 
1212 	*btf = bpf_get_btf_vmlinux();
1213 
1214 	if (IS_ERR_OR_NULL(*btf))
1215 		return PTR_ERR(*btf);
1216 
1217 	if (ptr->type_id > 0)
1218 		*btf_id = ptr->type_id;
1219 	else
1220 		return -EINVAL;
1221 
1222 	if (*btf_id > 0)
1223 		t = btf_type_by_id(*btf, *btf_id);
1224 	if (*btf_id <= 0 || !t)
1225 		return -ENOENT;
1226 
1227 	return 0;
1228 }
1229 
1230 BPF_CALL_5(bpf_snprintf_btf, char *, str, u32, str_size, struct btf_ptr *, ptr,
1231 	   u32, btf_ptr_size, u64, flags)
1232 {
1233 	const struct btf *btf;
1234 	s32 btf_id;
1235 	int ret;
1236 
1237 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
1238 	if (ret)
1239 		return ret;
1240 
1241 	return btf_type_snprintf_show(btf, btf_id, ptr->ptr, str, str_size,
1242 				      flags);
1243 }
1244 
1245 const struct bpf_func_proto bpf_snprintf_btf_proto = {
1246 	.func		= bpf_snprintf_btf,
1247 	.gpl_only	= false,
1248 	.ret_type	= RET_INTEGER,
1249 	.arg1_type	= ARG_PTR_TO_MEM,
1250 	.arg2_type	= ARG_CONST_SIZE,
1251 	.arg3_type	= ARG_PTR_TO_MEM,
1252 	.arg4_type	= ARG_CONST_SIZE,
1253 	.arg5_type	= ARG_ANYTHING,
1254 };
1255 
1256 const struct bpf_func_proto *
1257 bpf_tracing_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1258 {
1259 	switch (func_id) {
1260 	case BPF_FUNC_map_lookup_elem:
1261 		return &bpf_map_lookup_elem_proto;
1262 	case BPF_FUNC_map_update_elem:
1263 		return &bpf_map_update_elem_proto;
1264 	case BPF_FUNC_map_delete_elem:
1265 		return &bpf_map_delete_elem_proto;
1266 	case BPF_FUNC_map_push_elem:
1267 		return &bpf_map_push_elem_proto;
1268 	case BPF_FUNC_map_pop_elem:
1269 		return &bpf_map_pop_elem_proto;
1270 	case BPF_FUNC_map_peek_elem:
1271 		return &bpf_map_peek_elem_proto;
1272 	case BPF_FUNC_ktime_get_ns:
1273 		return &bpf_ktime_get_ns_proto;
1274 	case BPF_FUNC_ktime_get_boot_ns:
1275 		return &bpf_ktime_get_boot_ns_proto;
1276 	case BPF_FUNC_tail_call:
1277 		return &bpf_tail_call_proto;
1278 	case BPF_FUNC_get_current_pid_tgid:
1279 		return &bpf_get_current_pid_tgid_proto;
1280 	case BPF_FUNC_get_current_task:
1281 		return &bpf_get_current_task_proto;
1282 	case BPF_FUNC_get_current_task_btf:
1283 		return &bpf_get_current_task_btf_proto;
1284 	case BPF_FUNC_get_current_uid_gid:
1285 		return &bpf_get_current_uid_gid_proto;
1286 	case BPF_FUNC_get_current_comm:
1287 		return &bpf_get_current_comm_proto;
1288 	case BPF_FUNC_trace_printk:
1289 		return bpf_get_trace_printk_proto();
1290 	case BPF_FUNC_get_smp_processor_id:
1291 		return &bpf_get_smp_processor_id_proto;
1292 	case BPF_FUNC_get_numa_node_id:
1293 		return &bpf_get_numa_node_id_proto;
1294 	case BPF_FUNC_perf_event_read:
1295 		return &bpf_perf_event_read_proto;
1296 	case BPF_FUNC_probe_write_user:
1297 		return bpf_get_probe_write_proto();
1298 	case BPF_FUNC_current_task_under_cgroup:
1299 		return &bpf_current_task_under_cgroup_proto;
1300 	case BPF_FUNC_get_prandom_u32:
1301 		return &bpf_get_prandom_u32_proto;
1302 	case BPF_FUNC_probe_read_user:
1303 		return &bpf_probe_read_user_proto;
1304 	case BPF_FUNC_probe_read_kernel:
1305 		return &bpf_probe_read_kernel_proto;
1306 	case BPF_FUNC_probe_read_user_str:
1307 		return &bpf_probe_read_user_str_proto;
1308 	case BPF_FUNC_probe_read_kernel_str:
1309 		return &bpf_probe_read_kernel_str_proto;
1310 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
1311 	case BPF_FUNC_probe_read:
1312 		return &bpf_probe_read_compat_proto;
1313 	case BPF_FUNC_probe_read_str:
1314 		return &bpf_probe_read_compat_str_proto;
1315 #endif
1316 #ifdef CONFIG_CGROUPS
1317 	case BPF_FUNC_get_current_cgroup_id:
1318 		return &bpf_get_current_cgroup_id_proto;
1319 #endif
1320 	case BPF_FUNC_send_signal:
1321 		return &bpf_send_signal_proto;
1322 	case BPF_FUNC_send_signal_thread:
1323 		return &bpf_send_signal_thread_proto;
1324 	case BPF_FUNC_perf_event_read_value:
1325 		return &bpf_perf_event_read_value_proto;
1326 	case BPF_FUNC_get_ns_current_pid_tgid:
1327 		return &bpf_get_ns_current_pid_tgid_proto;
1328 	case BPF_FUNC_ringbuf_output:
1329 		return &bpf_ringbuf_output_proto;
1330 	case BPF_FUNC_ringbuf_reserve:
1331 		return &bpf_ringbuf_reserve_proto;
1332 	case BPF_FUNC_ringbuf_submit:
1333 		return &bpf_ringbuf_submit_proto;
1334 	case BPF_FUNC_ringbuf_discard:
1335 		return &bpf_ringbuf_discard_proto;
1336 	case BPF_FUNC_ringbuf_query:
1337 		return &bpf_ringbuf_query_proto;
1338 	case BPF_FUNC_jiffies64:
1339 		return &bpf_jiffies64_proto;
1340 	case BPF_FUNC_get_task_stack:
1341 		return &bpf_get_task_stack_proto;
1342 	case BPF_FUNC_copy_from_user:
1343 		return prog->aux->sleepable ? &bpf_copy_from_user_proto : NULL;
1344 	case BPF_FUNC_snprintf_btf:
1345 		return &bpf_snprintf_btf_proto;
1346 	case BPF_FUNC_bpf_per_cpu_ptr:
1347 		return &bpf_per_cpu_ptr_proto;
1348 	case BPF_FUNC_bpf_this_cpu_ptr:
1349 		return &bpf_this_cpu_ptr_proto;
1350 	default:
1351 		return NULL;
1352 	}
1353 }
1354 
1355 static const struct bpf_func_proto *
1356 kprobe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1357 {
1358 	switch (func_id) {
1359 	case BPF_FUNC_perf_event_output:
1360 		return &bpf_perf_event_output_proto;
1361 	case BPF_FUNC_get_stackid:
1362 		return &bpf_get_stackid_proto;
1363 	case BPF_FUNC_get_stack:
1364 		return &bpf_get_stack_proto;
1365 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
1366 	case BPF_FUNC_override_return:
1367 		return &bpf_override_return_proto;
1368 #endif
1369 	default:
1370 		return bpf_tracing_func_proto(func_id, prog);
1371 	}
1372 }
1373 
1374 /* bpf+kprobe programs can access fields of 'struct pt_regs' */
1375 static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1376 					const struct bpf_prog *prog,
1377 					struct bpf_insn_access_aux *info)
1378 {
1379 	if (off < 0 || off >= sizeof(struct pt_regs))
1380 		return false;
1381 	if (type != BPF_READ)
1382 		return false;
1383 	if (off % size != 0)
1384 		return false;
1385 	/*
1386 	 * Assertion for 32 bit to make sure last 8 byte access
1387 	 * (BPF_DW) to the last 4 byte member is disallowed.
1388 	 */
1389 	if (off + size > sizeof(struct pt_regs))
1390 		return false;
1391 
1392 	return true;
1393 }
1394 
1395 const struct bpf_verifier_ops kprobe_verifier_ops = {
1396 	.get_func_proto  = kprobe_prog_func_proto,
1397 	.is_valid_access = kprobe_prog_is_valid_access,
1398 };
1399 
1400 const struct bpf_prog_ops kprobe_prog_ops = {
1401 };
1402 
1403 BPF_CALL_5(bpf_perf_event_output_tp, void *, tp_buff, struct bpf_map *, map,
1404 	   u64, flags, void *, data, u64, size)
1405 {
1406 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1407 
1408 	/*
1409 	 * r1 points to perf tracepoint buffer where first 8 bytes are hidden
1410 	 * from bpf program and contain a pointer to 'struct pt_regs'. Fetch it
1411 	 * from there and call the same bpf_perf_event_output() helper inline.
1412 	 */
1413 	return ____bpf_perf_event_output(regs, map, flags, data, size);
1414 }
1415 
1416 static const struct bpf_func_proto bpf_perf_event_output_proto_tp = {
1417 	.func		= bpf_perf_event_output_tp,
1418 	.gpl_only	= true,
1419 	.ret_type	= RET_INTEGER,
1420 	.arg1_type	= ARG_PTR_TO_CTX,
1421 	.arg2_type	= ARG_CONST_MAP_PTR,
1422 	.arg3_type	= ARG_ANYTHING,
1423 	.arg4_type	= ARG_PTR_TO_MEM,
1424 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1425 };
1426 
1427 BPF_CALL_3(bpf_get_stackid_tp, void *, tp_buff, struct bpf_map *, map,
1428 	   u64, flags)
1429 {
1430 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1431 
1432 	/*
1433 	 * Same comment as in bpf_perf_event_output_tp(), only that this time
1434 	 * the other helper's function body cannot be inlined due to being
1435 	 * external, thus we need to call raw helper function.
1436 	 */
1437 	return bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1438 			       flags, 0, 0);
1439 }
1440 
1441 static const struct bpf_func_proto bpf_get_stackid_proto_tp = {
1442 	.func		= bpf_get_stackid_tp,
1443 	.gpl_only	= true,
1444 	.ret_type	= RET_INTEGER,
1445 	.arg1_type	= ARG_PTR_TO_CTX,
1446 	.arg2_type	= ARG_CONST_MAP_PTR,
1447 	.arg3_type	= ARG_ANYTHING,
1448 };
1449 
1450 BPF_CALL_4(bpf_get_stack_tp, void *, tp_buff, void *, buf, u32, size,
1451 	   u64, flags)
1452 {
1453 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1454 
1455 	return bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1456 			     (unsigned long) size, flags, 0);
1457 }
1458 
1459 static const struct bpf_func_proto bpf_get_stack_proto_tp = {
1460 	.func		= bpf_get_stack_tp,
1461 	.gpl_only	= true,
1462 	.ret_type	= RET_INTEGER,
1463 	.arg1_type	= ARG_PTR_TO_CTX,
1464 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
1465 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
1466 	.arg4_type	= ARG_ANYTHING,
1467 };
1468 
1469 static const struct bpf_func_proto *
1470 tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1471 {
1472 	switch (func_id) {
1473 	case BPF_FUNC_perf_event_output:
1474 		return &bpf_perf_event_output_proto_tp;
1475 	case BPF_FUNC_get_stackid:
1476 		return &bpf_get_stackid_proto_tp;
1477 	case BPF_FUNC_get_stack:
1478 		return &bpf_get_stack_proto_tp;
1479 	default:
1480 		return bpf_tracing_func_proto(func_id, prog);
1481 	}
1482 }
1483 
1484 static bool tp_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1485 				    const struct bpf_prog *prog,
1486 				    struct bpf_insn_access_aux *info)
1487 {
1488 	if (off < sizeof(void *) || off >= PERF_MAX_TRACE_SIZE)
1489 		return false;
1490 	if (type != BPF_READ)
1491 		return false;
1492 	if (off % size != 0)
1493 		return false;
1494 
1495 	BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(__u64));
1496 	return true;
1497 }
1498 
1499 const struct bpf_verifier_ops tracepoint_verifier_ops = {
1500 	.get_func_proto  = tp_prog_func_proto,
1501 	.is_valid_access = tp_prog_is_valid_access,
1502 };
1503 
1504 const struct bpf_prog_ops tracepoint_prog_ops = {
1505 };
1506 
1507 BPF_CALL_3(bpf_perf_prog_read_value, struct bpf_perf_event_data_kern *, ctx,
1508 	   struct bpf_perf_event_value *, buf, u32, size)
1509 {
1510 	int err = -EINVAL;
1511 
1512 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
1513 		goto clear;
1514 	err = perf_event_read_local(ctx->event, &buf->counter, &buf->enabled,
1515 				    &buf->running);
1516 	if (unlikely(err))
1517 		goto clear;
1518 	return 0;
1519 clear:
1520 	memset(buf, 0, size);
1521 	return err;
1522 }
1523 
1524 static const struct bpf_func_proto bpf_perf_prog_read_value_proto = {
1525          .func           = bpf_perf_prog_read_value,
1526          .gpl_only       = true,
1527          .ret_type       = RET_INTEGER,
1528          .arg1_type      = ARG_PTR_TO_CTX,
1529          .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
1530          .arg3_type      = ARG_CONST_SIZE,
1531 };
1532 
1533 BPF_CALL_4(bpf_read_branch_records, struct bpf_perf_event_data_kern *, ctx,
1534 	   void *, buf, u32, size, u64, flags)
1535 {
1536 #ifndef CONFIG_X86
1537 	return -ENOENT;
1538 #else
1539 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1540 	struct perf_branch_stack *br_stack = ctx->data->br_stack;
1541 	u32 to_copy;
1542 
1543 	if (unlikely(flags & ~BPF_F_GET_BRANCH_RECORDS_SIZE))
1544 		return -EINVAL;
1545 
1546 	if (unlikely(!br_stack))
1547 		return -EINVAL;
1548 
1549 	if (flags & BPF_F_GET_BRANCH_RECORDS_SIZE)
1550 		return br_stack->nr * br_entry_size;
1551 
1552 	if (!buf || (size % br_entry_size != 0))
1553 		return -EINVAL;
1554 
1555 	to_copy = min_t(u32, br_stack->nr * br_entry_size, size);
1556 	memcpy(buf, br_stack->entries, to_copy);
1557 
1558 	return to_copy;
1559 #endif
1560 }
1561 
1562 static const struct bpf_func_proto bpf_read_branch_records_proto = {
1563 	.func           = bpf_read_branch_records,
1564 	.gpl_only       = true,
1565 	.ret_type       = RET_INTEGER,
1566 	.arg1_type      = ARG_PTR_TO_CTX,
1567 	.arg2_type      = ARG_PTR_TO_MEM_OR_NULL,
1568 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
1569 	.arg4_type      = ARG_ANYTHING,
1570 };
1571 
1572 static const struct bpf_func_proto *
1573 pe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1574 {
1575 	switch (func_id) {
1576 	case BPF_FUNC_perf_event_output:
1577 		return &bpf_perf_event_output_proto_tp;
1578 	case BPF_FUNC_get_stackid:
1579 		return &bpf_get_stackid_proto_pe;
1580 	case BPF_FUNC_get_stack:
1581 		return &bpf_get_stack_proto_pe;
1582 	case BPF_FUNC_perf_prog_read_value:
1583 		return &bpf_perf_prog_read_value_proto;
1584 	case BPF_FUNC_read_branch_records:
1585 		return &bpf_read_branch_records_proto;
1586 	default:
1587 		return bpf_tracing_func_proto(func_id, prog);
1588 	}
1589 }
1590 
1591 /*
1592  * bpf_raw_tp_regs are separate from bpf_pt_regs used from skb/xdp
1593  * to avoid potential recursive reuse issue when/if tracepoints are added
1594  * inside bpf_*_event_output, bpf_get_stackid and/or bpf_get_stack.
1595  *
1596  * Since raw tracepoints run despite bpf_prog_active, support concurrent usage
1597  * in normal, irq, and nmi context.
1598  */
1599 struct bpf_raw_tp_regs {
1600 	struct pt_regs regs[3];
1601 };
1602 static DEFINE_PER_CPU(struct bpf_raw_tp_regs, bpf_raw_tp_regs);
1603 static DEFINE_PER_CPU(int, bpf_raw_tp_nest_level);
1604 static struct pt_regs *get_bpf_raw_tp_regs(void)
1605 {
1606 	struct bpf_raw_tp_regs *tp_regs = this_cpu_ptr(&bpf_raw_tp_regs);
1607 	int nest_level = this_cpu_inc_return(bpf_raw_tp_nest_level);
1608 
1609 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(tp_regs->regs))) {
1610 		this_cpu_dec(bpf_raw_tp_nest_level);
1611 		return ERR_PTR(-EBUSY);
1612 	}
1613 
1614 	return &tp_regs->regs[nest_level - 1];
1615 }
1616 
1617 static void put_bpf_raw_tp_regs(void)
1618 {
1619 	this_cpu_dec(bpf_raw_tp_nest_level);
1620 }
1621 
1622 BPF_CALL_5(bpf_perf_event_output_raw_tp, struct bpf_raw_tracepoint_args *, args,
1623 	   struct bpf_map *, map, u64, flags, void *, data, u64, size)
1624 {
1625 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1626 	int ret;
1627 
1628 	if (IS_ERR(regs))
1629 		return PTR_ERR(regs);
1630 
1631 	perf_fetch_caller_regs(regs);
1632 	ret = ____bpf_perf_event_output(regs, map, flags, data, size);
1633 
1634 	put_bpf_raw_tp_regs();
1635 	return ret;
1636 }
1637 
1638 static const struct bpf_func_proto bpf_perf_event_output_proto_raw_tp = {
1639 	.func		= bpf_perf_event_output_raw_tp,
1640 	.gpl_only	= true,
1641 	.ret_type	= RET_INTEGER,
1642 	.arg1_type	= ARG_PTR_TO_CTX,
1643 	.arg2_type	= ARG_CONST_MAP_PTR,
1644 	.arg3_type	= ARG_ANYTHING,
1645 	.arg4_type	= ARG_PTR_TO_MEM,
1646 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1647 };
1648 
1649 extern const struct bpf_func_proto bpf_skb_output_proto;
1650 extern const struct bpf_func_proto bpf_xdp_output_proto;
1651 
1652 BPF_CALL_3(bpf_get_stackid_raw_tp, struct bpf_raw_tracepoint_args *, args,
1653 	   struct bpf_map *, map, u64, flags)
1654 {
1655 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1656 	int ret;
1657 
1658 	if (IS_ERR(regs))
1659 		return PTR_ERR(regs);
1660 
1661 	perf_fetch_caller_regs(regs);
1662 	/* similar to bpf_perf_event_output_tp, but pt_regs fetched differently */
1663 	ret = bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1664 			      flags, 0, 0);
1665 	put_bpf_raw_tp_regs();
1666 	return ret;
1667 }
1668 
1669 static const struct bpf_func_proto bpf_get_stackid_proto_raw_tp = {
1670 	.func		= bpf_get_stackid_raw_tp,
1671 	.gpl_only	= true,
1672 	.ret_type	= RET_INTEGER,
1673 	.arg1_type	= ARG_PTR_TO_CTX,
1674 	.arg2_type	= ARG_CONST_MAP_PTR,
1675 	.arg3_type	= ARG_ANYTHING,
1676 };
1677 
1678 BPF_CALL_4(bpf_get_stack_raw_tp, struct bpf_raw_tracepoint_args *, args,
1679 	   void *, buf, u32, size, u64, flags)
1680 {
1681 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1682 	int ret;
1683 
1684 	if (IS_ERR(regs))
1685 		return PTR_ERR(regs);
1686 
1687 	perf_fetch_caller_regs(regs);
1688 	ret = bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1689 			    (unsigned long) size, flags, 0);
1690 	put_bpf_raw_tp_regs();
1691 	return ret;
1692 }
1693 
1694 static const struct bpf_func_proto bpf_get_stack_proto_raw_tp = {
1695 	.func		= bpf_get_stack_raw_tp,
1696 	.gpl_only	= true,
1697 	.ret_type	= RET_INTEGER,
1698 	.arg1_type	= ARG_PTR_TO_CTX,
1699 	.arg2_type	= ARG_PTR_TO_MEM,
1700 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
1701 	.arg4_type	= ARG_ANYTHING,
1702 };
1703 
1704 static const struct bpf_func_proto *
1705 raw_tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1706 {
1707 	switch (func_id) {
1708 	case BPF_FUNC_perf_event_output:
1709 		return &bpf_perf_event_output_proto_raw_tp;
1710 	case BPF_FUNC_get_stackid:
1711 		return &bpf_get_stackid_proto_raw_tp;
1712 	case BPF_FUNC_get_stack:
1713 		return &bpf_get_stack_proto_raw_tp;
1714 	default:
1715 		return bpf_tracing_func_proto(func_id, prog);
1716 	}
1717 }
1718 
1719 const struct bpf_func_proto *
1720 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1721 {
1722 	switch (func_id) {
1723 #ifdef CONFIG_NET
1724 	case BPF_FUNC_skb_output:
1725 		return &bpf_skb_output_proto;
1726 	case BPF_FUNC_xdp_output:
1727 		return &bpf_xdp_output_proto;
1728 	case BPF_FUNC_skc_to_tcp6_sock:
1729 		return &bpf_skc_to_tcp6_sock_proto;
1730 	case BPF_FUNC_skc_to_tcp_sock:
1731 		return &bpf_skc_to_tcp_sock_proto;
1732 	case BPF_FUNC_skc_to_tcp_timewait_sock:
1733 		return &bpf_skc_to_tcp_timewait_sock_proto;
1734 	case BPF_FUNC_skc_to_tcp_request_sock:
1735 		return &bpf_skc_to_tcp_request_sock_proto;
1736 	case BPF_FUNC_skc_to_udp6_sock:
1737 		return &bpf_skc_to_udp6_sock_proto;
1738 #endif
1739 	case BPF_FUNC_seq_printf:
1740 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1741 		       &bpf_seq_printf_proto :
1742 		       NULL;
1743 	case BPF_FUNC_seq_write:
1744 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1745 		       &bpf_seq_write_proto :
1746 		       NULL;
1747 	case BPF_FUNC_seq_printf_btf:
1748 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1749 		       &bpf_seq_printf_btf_proto :
1750 		       NULL;
1751 	case BPF_FUNC_d_path:
1752 		return &bpf_d_path_proto;
1753 	default:
1754 		return raw_tp_prog_func_proto(func_id, prog);
1755 	}
1756 }
1757 
1758 static bool raw_tp_prog_is_valid_access(int off, int size,
1759 					enum bpf_access_type type,
1760 					const struct bpf_prog *prog,
1761 					struct bpf_insn_access_aux *info)
1762 {
1763 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
1764 		return false;
1765 	if (type != BPF_READ)
1766 		return false;
1767 	if (off % size != 0)
1768 		return false;
1769 	return true;
1770 }
1771 
1772 static bool tracing_prog_is_valid_access(int off, int size,
1773 					 enum bpf_access_type type,
1774 					 const struct bpf_prog *prog,
1775 					 struct bpf_insn_access_aux *info)
1776 {
1777 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
1778 		return false;
1779 	if (type != BPF_READ)
1780 		return false;
1781 	if (off % size != 0)
1782 		return false;
1783 	return btf_ctx_access(off, size, type, prog, info);
1784 }
1785 
1786 int __weak bpf_prog_test_run_tracing(struct bpf_prog *prog,
1787 				     const union bpf_attr *kattr,
1788 				     union bpf_attr __user *uattr)
1789 {
1790 	return -ENOTSUPP;
1791 }
1792 
1793 const struct bpf_verifier_ops raw_tracepoint_verifier_ops = {
1794 	.get_func_proto  = raw_tp_prog_func_proto,
1795 	.is_valid_access = raw_tp_prog_is_valid_access,
1796 };
1797 
1798 const struct bpf_prog_ops raw_tracepoint_prog_ops = {
1799 #ifdef CONFIG_NET
1800 	.test_run = bpf_prog_test_run_raw_tp,
1801 #endif
1802 };
1803 
1804 const struct bpf_verifier_ops tracing_verifier_ops = {
1805 	.get_func_proto  = tracing_prog_func_proto,
1806 	.is_valid_access = tracing_prog_is_valid_access,
1807 };
1808 
1809 const struct bpf_prog_ops tracing_prog_ops = {
1810 	.test_run = bpf_prog_test_run_tracing,
1811 };
1812 
1813 static bool raw_tp_writable_prog_is_valid_access(int off, int size,
1814 						 enum bpf_access_type type,
1815 						 const struct bpf_prog *prog,
1816 						 struct bpf_insn_access_aux *info)
1817 {
1818 	if (off == 0) {
1819 		if (size != sizeof(u64) || type != BPF_READ)
1820 			return false;
1821 		info->reg_type = PTR_TO_TP_BUFFER;
1822 	}
1823 	return raw_tp_prog_is_valid_access(off, size, type, prog, info);
1824 }
1825 
1826 const struct bpf_verifier_ops raw_tracepoint_writable_verifier_ops = {
1827 	.get_func_proto  = raw_tp_prog_func_proto,
1828 	.is_valid_access = raw_tp_writable_prog_is_valid_access,
1829 };
1830 
1831 const struct bpf_prog_ops raw_tracepoint_writable_prog_ops = {
1832 };
1833 
1834 static bool pe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1835 				    const struct bpf_prog *prog,
1836 				    struct bpf_insn_access_aux *info)
1837 {
1838 	const int size_u64 = sizeof(u64);
1839 
1840 	if (off < 0 || off >= sizeof(struct bpf_perf_event_data))
1841 		return false;
1842 	if (type != BPF_READ)
1843 		return false;
1844 	if (off % size != 0) {
1845 		if (sizeof(unsigned long) != 4)
1846 			return false;
1847 		if (size != 8)
1848 			return false;
1849 		if (off % size != 4)
1850 			return false;
1851 	}
1852 
1853 	switch (off) {
1854 	case bpf_ctx_range(struct bpf_perf_event_data, sample_period):
1855 		bpf_ctx_record_field_size(info, size_u64);
1856 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
1857 			return false;
1858 		break;
1859 	case bpf_ctx_range(struct bpf_perf_event_data, addr):
1860 		bpf_ctx_record_field_size(info, size_u64);
1861 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
1862 			return false;
1863 		break;
1864 	default:
1865 		if (size != sizeof(long))
1866 			return false;
1867 	}
1868 
1869 	return true;
1870 }
1871 
1872 static u32 pe_prog_convert_ctx_access(enum bpf_access_type type,
1873 				      const struct bpf_insn *si,
1874 				      struct bpf_insn *insn_buf,
1875 				      struct bpf_prog *prog, u32 *target_size)
1876 {
1877 	struct bpf_insn *insn = insn_buf;
1878 
1879 	switch (si->off) {
1880 	case offsetof(struct bpf_perf_event_data, sample_period):
1881 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1882 						       data), si->dst_reg, si->src_reg,
1883 				      offsetof(struct bpf_perf_event_data_kern, data));
1884 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
1885 				      bpf_target_off(struct perf_sample_data, period, 8,
1886 						     target_size));
1887 		break;
1888 	case offsetof(struct bpf_perf_event_data, addr):
1889 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1890 						       data), si->dst_reg, si->src_reg,
1891 				      offsetof(struct bpf_perf_event_data_kern, data));
1892 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
1893 				      bpf_target_off(struct perf_sample_data, addr, 8,
1894 						     target_size));
1895 		break;
1896 	default:
1897 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1898 						       regs), si->dst_reg, si->src_reg,
1899 				      offsetof(struct bpf_perf_event_data_kern, regs));
1900 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(long), si->dst_reg, si->dst_reg,
1901 				      si->off);
1902 		break;
1903 	}
1904 
1905 	return insn - insn_buf;
1906 }
1907 
1908 const struct bpf_verifier_ops perf_event_verifier_ops = {
1909 	.get_func_proto		= pe_prog_func_proto,
1910 	.is_valid_access	= pe_prog_is_valid_access,
1911 	.convert_ctx_access	= pe_prog_convert_ctx_access,
1912 };
1913 
1914 const struct bpf_prog_ops perf_event_prog_ops = {
1915 };
1916 
1917 static DEFINE_MUTEX(bpf_event_mutex);
1918 
1919 #define BPF_TRACE_MAX_PROGS 64
1920 
1921 int perf_event_attach_bpf_prog(struct perf_event *event,
1922 			       struct bpf_prog *prog)
1923 {
1924 	struct bpf_prog_array *old_array;
1925 	struct bpf_prog_array *new_array;
1926 	int ret = -EEXIST;
1927 
1928 	/*
1929 	 * Kprobe override only works if they are on the function entry,
1930 	 * and only if they are on the opt-in list.
1931 	 */
1932 	if (prog->kprobe_override &&
1933 	    (!trace_kprobe_on_func_entry(event->tp_event) ||
1934 	     !trace_kprobe_error_injectable(event->tp_event)))
1935 		return -EINVAL;
1936 
1937 	mutex_lock(&bpf_event_mutex);
1938 
1939 	if (event->prog)
1940 		goto unlock;
1941 
1942 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
1943 	if (old_array &&
1944 	    bpf_prog_array_length(old_array) >= BPF_TRACE_MAX_PROGS) {
1945 		ret = -E2BIG;
1946 		goto unlock;
1947 	}
1948 
1949 	ret = bpf_prog_array_copy(old_array, NULL, prog, &new_array);
1950 	if (ret < 0)
1951 		goto unlock;
1952 
1953 	/* set the new array to event->tp_event and set event->prog */
1954 	event->prog = prog;
1955 	rcu_assign_pointer(event->tp_event->prog_array, new_array);
1956 	bpf_prog_array_free(old_array);
1957 
1958 unlock:
1959 	mutex_unlock(&bpf_event_mutex);
1960 	return ret;
1961 }
1962 
1963 void perf_event_detach_bpf_prog(struct perf_event *event)
1964 {
1965 	struct bpf_prog_array *old_array;
1966 	struct bpf_prog_array *new_array;
1967 	int ret;
1968 
1969 	mutex_lock(&bpf_event_mutex);
1970 
1971 	if (!event->prog)
1972 		goto unlock;
1973 
1974 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
1975 	ret = bpf_prog_array_copy(old_array, event->prog, NULL, &new_array);
1976 	if (ret == -ENOENT)
1977 		goto unlock;
1978 	if (ret < 0) {
1979 		bpf_prog_array_delete_safe(old_array, event->prog);
1980 	} else {
1981 		rcu_assign_pointer(event->tp_event->prog_array, new_array);
1982 		bpf_prog_array_free(old_array);
1983 	}
1984 
1985 	bpf_prog_put(event->prog);
1986 	event->prog = NULL;
1987 
1988 unlock:
1989 	mutex_unlock(&bpf_event_mutex);
1990 }
1991 
1992 int perf_event_query_prog_array(struct perf_event *event, void __user *info)
1993 {
1994 	struct perf_event_query_bpf __user *uquery = info;
1995 	struct perf_event_query_bpf query = {};
1996 	struct bpf_prog_array *progs;
1997 	u32 *ids, prog_cnt, ids_len;
1998 	int ret;
1999 
2000 	if (!perfmon_capable())
2001 		return -EPERM;
2002 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
2003 		return -EINVAL;
2004 	if (copy_from_user(&query, uquery, sizeof(query)))
2005 		return -EFAULT;
2006 
2007 	ids_len = query.ids_len;
2008 	if (ids_len > BPF_TRACE_MAX_PROGS)
2009 		return -E2BIG;
2010 	ids = kcalloc(ids_len, sizeof(u32), GFP_USER | __GFP_NOWARN);
2011 	if (!ids)
2012 		return -ENOMEM;
2013 	/*
2014 	 * The above kcalloc returns ZERO_SIZE_PTR when ids_len = 0, which
2015 	 * is required when user only wants to check for uquery->prog_cnt.
2016 	 * There is no need to check for it since the case is handled
2017 	 * gracefully in bpf_prog_array_copy_info.
2018 	 */
2019 
2020 	mutex_lock(&bpf_event_mutex);
2021 	progs = bpf_event_rcu_dereference(event->tp_event->prog_array);
2022 	ret = bpf_prog_array_copy_info(progs, ids, ids_len, &prog_cnt);
2023 	mutex_unlock(&bpf_event_mutex);
2024 
2025 	if (copy_to_user(&uquery->prog_cnt, &prog_cnt, sizeof(prog_cnt)) ||
2026 	    copy_to_user(uquery->ids, ids, ids_len * sizeof(u32)))
2027 		ret = -EFAULT;
2028 
2029 	kfree(ids);
2030 	return ret;
2031 }
2032 
2033 extern struct bpf_raw_event_map __start__bpf_raw_tp[];
2034 extern struct bpf_raw_event_map __stop__bpf_raw_tp[];
2035 
2036 struct bpf_raw_event_map *bpf_get_raw_tracepoint(const char *name)
2037 {
2038 	struct bpf_raw_event_map *btp = __start__bpf_raw_tp;
2039 
2040 	for (; btp < __stop__bpf_raw_tp; btp++) {
2041 		if (!strcmp(btp->tp->name, name))
2042 			return btp;
2043 	}
2044 
2045 	return bpf_get_raw_tracepoint_module(name);
2046 }
2047 
2048 void bpf_put_raw_tracepoint(struct bpf_raw_event_map *btp)
2049 {
2050 	struct module *mod = __module_address((unsigned long)btp);
2051 
2052 	if (mod)
2053 		module_put(mod);
2054 }
2055 
2056 static __always_inline
2057 void __bpf_trace_run(struct bpf_prog *prog, u64 *args)
2058 {
2059 	cant_sleep();
2060 	rcu_read_lock();
2061 	(void) BPF_PROG_RUN(prog, args);
2062 	rcu_read_unlock();
2063 }
2064 
2065 #define UNPACK(...)			__VA_ARGS__
2066 #define REPEAT_1(FN, DL, X, ...)	FN(X)
2067 #define REPEAT_2(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_1(FN, DL, __VA_ARGS__)
2068 #define REPEAT_3(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_2(FN, DL, __VA_ARGS__)
2069 #define REPEAT_4(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_3(FN, DL, __VA_ARGS__)
2070 #define REPEAT_5(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_4(FN, DL, __VA_ARGS__)
2071 #define REPEAT_6(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_5(FN, DL, __VA_ARGS__)
2072 #define REPEAT_7(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_6(FN, DL, __VA_ARGS__)
2073 #define REPEAT_8(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_7(FN, DL, __VA_ARGS__)
2074 #define REPEAT_9(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_8(FN, DL, __VA_ARGS__)
2075 #define REPEAT_10(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_9(FN, DL, __VA_ARGS__)
2076 #define REPEAT_11(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_10(FN, DL, __VA_ARGS__)
2077 #define REPEAT_12(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_11(FN, DL, __VA_ARGS__)
2078 #define REPEAT(X, FN, DL, ...)		REPEAT_##X(FN, DL, __VA_ARGS__)
2079 
2080 #define SARG(X)		u64 arg##X
2081 #define COPY(X)		args[X] = arg##X
2082 
2083 #define __DL_COM	(,)
2084 #define __DL_SEM	(;)
2085 
2086 #define __SEQ_0_11	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
2087 
2088 #define BPF_TRACE_DEFN_x(x)						\
2089 	void bpf_trace_run##x(struct bpf_prog *prog,			\
2090 			      REPEAT(x, SARG, __DL_COM, __SEQ_0_11))	\
2091 	{								\
2092 		u64 args[x];						\
2093 		REPEAT(x, COPY, __DL_SEM, __SEQ_0_11);			\
2094 		__bpf_trace_run(prog, args);				\
2095 	}								\
2096 	EXPORT_SYMBOL_GPL(bpf_trace_run##x)
2097 BPF_TRACE_DEFN_x(1);
2098 BPF_TRACE_DEFN_x(2);
2099 BPF_TRACE_DEFN_x(3);
2100 BPF_TRACE_DEFN_x(4);
2101 BPF_TRACE_DEFN_x(5);
2102 BPF_TRACE_DEFN_x(6);
2103 BPF_TRACE_DEFN_x(7);
2104 BPF_TRACE_DEFN_x(8);
2105 BPF_TRACE_DEFN_x(9);
2106 BPF_TRACE_DEFN_x(10);
2107 BPF_TRACE_DEFN_x(11);
2108 BPF_TRACE_DEFN_x(12);
2109 
2110 static int __bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
2111 {
2112 	struct tracepoint *tp = btp->tp;
2113 
2114 	/*
2115 	 * check that program doesn't access arguments beyond what's
2116 	 * available in this tracepoint
2117 	 */
2118 	if (prog->aux->max_ctx_offset > btp->num_args * sizeof(u64))
2119 		return -EINVAL;
2120 
2121 	if (prog->aux->max_tp_access > btp->writable_size)
2122 		return -EINVAL;
2123 
2124 	return tracepoint_probe_register(tp, (void *)btp->bpf_func, prog);
2125 }
2126 
2127 int bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
2128 {
2129 	return __bpf_probe_register(btp, prog);
2130 }
2131 
2132 int bpf_probe_unregister(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
2133 {
2134 	return tracepoint_probe_unregister(btp->tp, (void *)btp->bpf_func, prog);
2135 }
2136 
2137 int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id,
2138 			    u32 *fd_type, const char **buf,
2139 			    u64 *probe_offset, u64 *probe_addr)
2140 {
2141 	bool is_tracepoint, is_syscall_tp;
2142 	struct bpf_prog *prog;
2143 	int flags, err = 0;
2144 
2145 	prog = event->prog;
2146 	if (!prog)
2147 		return -ENOENT;
2148 
2149 	/* not supporting BPF_PROG_TYPE_PERF_EVENT yet */
2150 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT)
2151 		return -EOPNOTSUPP;
2152 
2153 	*prog_id = prog->aux->id;
2154 	flags = event->tp_event->flags;
2155 	is_tracepoint = flags & TRACE_EVENT_FL_TRACEPOINT;
2156 	is_syscall_tp = is_syscall_trace_event(event->tp_event);
2157 
2158 	if (is_tracepoint || is_syscall_tp) {
2159 		*buf = is_tracepoint ? event->tp_event->tp->name
2160 				     : event->tp_event->name;
2161 		*fd_type = BPF_FD_TYPE_TRACEPOINT;
2162 		*probe_offset = 0x0;
2163 		*probe_addr = 0x0;
2164 	} else {
2165 		/* kprobe/uprobe */
2166 		err = -EOPNOTSUPP;
2167 #ifdef CONFIG_KPROBE_EVENTS
2168 		if (flags & TRACE_EVENT_FL_KPROBE)
2169 			err = bpf_get_kprobe_info(event, fd_type, buf,
2170 						  probe_offset, probe_addr,
2171 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2172 #endif
2173 #ifdef CONFIG_UPROBE_EVENTS
2174 		if (flags & TRACE_EVENT_FL_UPROBE)
2175 			err = bpf_get_uprobe_info(event, fd_type, buf,
2176 						  probe_offset,
2177 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2178 #endif
2179 	}
2180 
2181 	return err;
2182 }
2183 
2184 static int __init send_signal_irq_work_init(void)
2185 {
2186 	int cpu;
2187 	struct send_signal_irq_work *work;
2188 
2189 	for_each_possible_cpu(cpu) {
2190 		work = per_cpu_ptr(&send_signal_work, cpu);
2191 		init_irq_work(&work->irq_work, do_bpf_send_signal);
2192 	}
2193 	return 0;
2194 }
2195 
2196 subsys_initcall(send_signal_irq_work_init);
2197 
2198 #ifdef CONFIG_MODULES
2199 static int bpf_event_notify(struct notifier_block *nb, unsigned long op,
2200 			    void *module)
2201 {
2202 	struct bpf_trace_module *btm, *tmp;
2203 	struct module *mod = module;
2204 	int ret = 0;
2205 
2206 	if (mod->num_bpf_raw_events == 0 ||
2207 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
2208 		goto out;
2209 
2210 	mutex_lock(&bpf_module_mutex);
2211 
2212 	switch (op) {
2213 	case MODULE_STATE_COMING:
2214 		btm = kzalloc(sizeof(*btm), GFP_KERNEL);
2215 		if (btm) {
2216 			btm->module = module;
2217 			list_add(&btm->list, &bpf_trace_modules);
2218 		} else {
2219 			ret = -ENOMEM;
2220 		}
2221 		break;
2222 	case MODULE_STATE_GOING:
2223 		list_for_each_entry_safe(btm, tmp, &bpf_trace_modules, list) {
2224 			if (btm->module == module) {
2225 				list_del(&btm->list);
2226 				kfree(btm);
2227 				break;
2228 			}
2229 		}
2230 		break;
2231 	}
2232 
2233 	mutex_unlock(&bpf_module_mutex);
2234 
2235 out:
2236 	return notifier_from_errno(ret);
2237 }
2238 
2239 static struct notifier_block bpf_module_nb = {
2240 	.notifier_call = bpf_event_notify,
2241 };
2242 
2243 static int __init bpf_event_init(void)
2244 {
2245 	register_module_notifier(&bpf_module_nb);
2246 	return 0;
2247 }
2248 
2249 fs_initcall(bpf_event_init);
2250 #endif /* CONFIG_MODULES */
2251