xref: /linux/kernel/trace/bpf_trace.c (revision 0c8bf38058e5ac0e42246acb13f623b7962a3922)
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_verifier.h>
10 #include <linux/bpf_perf_event.h>
11 #include <linux/btf.h>
12 #include <linux/filter.h>
13 #include <linux/uaccess.h>
14 #include <linux/ctype.h>
15 #include <linux/kprobes.h>
16 #include <linux/spinlock.h>
17 #include <linux/syscalls.h>
18 #include <linux/error-injection.h>
19 #include <linux/btf_ids.h>
20 #include <linux/bpf_lsm.h>
21 #include <linux/fprobe.h>
22 #include <linux/bsearch.h>
23 #include <linux/sort.h>
24 #include <linux/key.h>
25 #include <linux/namei.h>
26 #include <linux/file.h>
27 
28 #include <net/bpf_sk_storage.h>
29 
30 #include <uapi/linux/bpf.h>
31 #include <uapi/linux/btf.h>
32 
33 #include <asm/tlb.h>
34 
35 #include "trace_probe.h"
36 #include "trace.h"
37 
38 #define CREATE_TRACE_POINTS
39 #include "bpf_trace.h"
40 
41 #define bpf_event_rcu_dereference(p)					\
42 	rcu_dereference_protected(p, lockdep_is_held(&bpf_event_mutex))
43 
44 #define MAX_UPROBE_MULTI_CNT (1U << 20)
45 #define MAX_KPROBE_MULTI_CNT (1U << 20)
46 #define MAX_TRACING_MULTI_CNT (1U << 20)
47 
48 #ifdef CONFIG_MODULES
49 struct bpf_trace_module {
50 	struct module *module;
51 	struct list_head list;
52 };
53 
54 static LIST_HEAD(bpf_trace_modules);
55 static DEFINE_MUTEX(bpf_module_mutex);
56 
57 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
58 {
59 	struct bpf_raw_event_map *btp, *ret = NULL;
60 	struct bpf_trace_module *btm;
61 	unsigned int i;
62 
63 	mutex_lock(&bpf_module_mutex);
64 	list_for_each_entry(btm, &bpf_trace_modules, list) {
65 		for (i = 0; i < btm->module->num_bpf_raw_events; ++i) {
66 			btp = &btm->module->bpf_raw_events[i];
67 			if (!strcmp(btp->tp->name, name)) {
68 				if (try_module_get(btm->module))
69 					ret = btp;
70 				goto out;
71 			}
72 		}
73 	}
74 out:
75 	mutex_unlock(&bpf_module_mutex);
76 	return ret;
77 }
78 #else
79 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
80 {
81 	return NULL;
82 }
83 #endif /* CONFIG_MODULES */
84 
85 u64 bpf_get_stackid(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
86 u64 bpf_get_stack(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
87 
88 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
89 				  u64 flags, const struct btf **btf,
90 				  s32 *btf_id);
91 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx);
92 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx);
93 
94 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx);
95 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx);
96 
97 /**
98  * trace_call_bpf - invoke BPF program
99  * @call: tracepoint event
100  * @ctx: opaque context pointer
101  *
102  * kprobe handlers execute BPF programs via this helper.
103  * Can be used from static tracepoints in the future.
104  *
105  * Return: BPF programs always return an integer which is interpreted by
106  * kprobe handler as:
107  * 0 - return from kprobe (event is filtered out)
108  * 1 - store kprobe event into ring buffer
109  * Other values are reserved and currently alias to 1
110  */
111 unsigned int trace_call_bpf(struct trace_event_call *call, void *ctx)
112 {
113 	unsigned int ret;
114 
115 	cant_sleep();
116 
117 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
118 		/*
119 		 * since some bpf program is already running on this cpu,
120 		 * don't call into another bpf program (same or different)
121 		 * and don't send kprobe event into ring-buffer,
122 		 * so return zero here
123 		 */
124 		rcu_read_lock();
125 		bpf_prog_inc_misses_counters(rcu_dereference(call->prog_array));
126 		rcu_read_unlock();
127 		ret = 0;
128 		goto out;
129 	}
130 
131 	/*
132 	 * Instead of moving rcu_read_lock/rcu_dereference/rcu_read_unlock
133 	 * to all call sites, we did a bpf_prog_array_valid() there to check
134 	 * whether call->prog_array is empty or not, which is
135 	 * a heuristic to speed up execution.
136 	 *
137 	 * If bpf_prog_array_valid() fetched prog_array was
138 	 * non-NULL, we go into trace_call_bpf() and do the actual
139 	 * proper rcu_dereference() under RCU lock.
140 	 * If it turns out that prog_array is NULL then, we bail out.
141 	 * For the opposite, if the bpf_prog_array_valid() fetched pointer
142 	 * was NULL, you'll skip the prog_array with the risk of missing
143 	 * out of events when it was updated in between this and the
144 	 * rcu_dereference() which is accepted risk.
145 	 */
146 	rcu_read_lock();
147 	ret = bpf_prog_run_array(rcu_dereference(call->prog_array),
148 				 ctx, bpf_prog_run);
149 	rcu_read_unlock();
150 
151  out:
152 	__this_cpu_dec(bpf_prog_active);
153 
154 	return ret;
155 }
156 
157 /**
158  * trace_call_bpf_faultable - invoke BPF program in faultable context
159  * @call: tracepoint event
160  * @ctx: opaque context pointer
161  *
162  * Variant of trace_call_bpf() for faultable tracepoints (syscall
163  * tracepoints). Supports sleepable BPF programs by using rcu_tasks_trace
164  * for lifetime protection and bpf_prog_run_array_sleepable() for per-program
165  * RCU flavor selection, following the uprobe pattern.
166  *
167  * Per-program recursion protection is provided by
168  * bpf_prog_run_array_sleepable(). Global bpf_prog_active is not
169  * needed because syscall tracepoints cannot self-recurse.
170  *
171  * Must be called from a faultable/preemptible context.
172  */
173 unsigned int trace_call_bpf_faultable(struct trace_event_call *call, void *ctx)
174 {
175 	struct bpf_prog_array *prog_array;
176 
177 	might_fault();
178 	guard(rcu_tasks_trace)();
179 
180 	prog_array = rcu_dereference_check(call->prog_array,
181 					   rcu_read_lock_trace_held());
182 	return bpf_prog_run_array_sleepable(prog_array, ctx, bpf_prog_run);
183 }
184 
185 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
186 BPF_CALL_2(bpf_override_return, struct pt_regs *, regs, unsigned long, rc)
187 {
188 	regs_set_return_value(regs, rc);
189 	override_function_with_return(regs);
190 	return 0;
191 }
192 
193 static const struct bpf_func_proto bpf_override_return_proto = {
194 	.func		= bpf_override_return,
195 	.gpl_only	= true,
196 	.ret_type	= RET_INTEGER,
197 	.arg1_type	= ARG_PTR_TO_CTX,
198 	.arg2_type	= ARG_ANYTHING,
199 };
200 #endif
201 
202 static __always_inline int
203 bpf_probe_read_user_common(void *dst, u32 size, const void __user *unsafe_ptr)
204 {
205 	int ret;
206 
207 	ret = copy_from_user_nofault(dst, unsafe_ptr, size);
208 	if (unlikely(ret < 0))
209 		memset(dst, 0, size);
210 	return ret;
211 }
212 
213 BPF_CALL_3(bpf_probe_read_user, void *, dst, u32, size,
214 	   const void __user *, unsafe_ptr)
215 {
216 	return bpf_probe_read_user_common(dst, size, unsafe_ptr);
217 }
218 
219 const struct bpf_func_proto bpf_probe_read_user_proto = {
220 	.func		= bpf_probe_read_user,
221 	.gpl_only	= true,
222 	.ret_type	= RET_INTEGER,
223 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
224 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
225 	.arg3_type	= ARG_ANYTHING,
226 };
227 
228 static __always_inline int
229 bpf_probe_read_user_str_common(void *dst, u32 size,
230 			       const void __user *unsafe_ptr)
231 {
232 	int ret;
233 
234 	/*
235 	 * NB: We rely on strncpy_from_user() not copying junk past the NUL
236 	 * terminator into `dst`.
237 	 *
238 	 * strncpy_from_user() does long-sized strides in the fast path. If the
239 	 * strncpy does not mask out the bytes after the NUL in `unsafe_ptr`,
240 	 * then there could be junk after the NUL in `dst`. If user takes `dst`
241 	 * and keys a hash map with it, then semantically identical strings can
242 	 * occupy multiple entries in the map.
243 	 */
244 	ret = strncpy_from_user_nofault(dst, unsafe_ptr, size);
245 	if (unlikely(ret < 0))
246 		memset(dst, 0, size);
247 	return ret;
248 }
249 
250 BPF_CALL_3(bpf_probe_read_user_str, void *, dst, u32, size,
251 	   const void __user *, unsafe_ptr)
252 {
253 	return bpf_probe_read_user_str_common(dst, size, unsafe_ptr);
254 }
255 
256 const struct bpf_func_proto bpf_probe_read_user_str_proto = {
257 	.func		= bpf_probe_read_user_str,
258 	.gpl_only	= true,
259 	.ret_type	= RET_INTEGER,
260 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
261 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
262 	.arg3_type	= ARG_ANYTHING,
263 };
264 
265 BPF_CALL_3(bpf_probe_read_kernel, void *, dst, u32, size,
266 	   const void *, unsafe_ptr)
267 {
268 	return bpf_probe_read_kernel_common(dst, size, unsafe_ptr);
269 }
270 
271 const struct bpf_func_proto bpf_probe_read_kernel_proto = {
272 	.func		= bpf_probe_read_kernel,
273 	.gpl_only	= true,
274 	.ret_type	= RET_INTEGER,
275 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
276 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
277 	.arg3_type	= ARG_ANYTHING,
278 };
279 
280 static __always_inline int
281 bpf_probe_read_kernel_str_common(void *dst, u32 size, const void *unsafe_ptr)
282 {
283 	int ret;
284 
285 	/*
286 	 * The strncpy_from_kernel_nofault() call will likely not fill the
287 	 * entire buffer, but that's okay in this circumstance as we're probing
288 	 * arbitrary memory anyway similar to bpf_probe_read_*() and might
289 	 * as well probe the stack. Thus, memory is explicitly cleared
290 	 * only in error case, so that improper users ignoring return
291 	 * code altogether don't copy garbage; otherwise length of string
292 	 * is returned that can be used for bpf_perf_event_output() et al.
293 	 */
294 	ret = strncpy_from_kernel_nofault(dst, unsafe_ptr, size);
295 	if (unlikely(ret < 0))
296 		memset(dst, 0, size);
297 	return ret;
298 }
299 
300 BPF_CALL_3(bpf_probe_read_kernel_str, void *, dst, u32, size,
301 	   const void *, unsafe_ptr)
302 {
303 	return bpf_probe_read_kernel_str_common(dst, size, unsafe_ptr);
304 }
305 
306 const struct bpf_func_proto bpf_probe_read_kernel_str_proto = {
307 	.func		= bpf_probe_read_kernel_str,
308 	.gpl_only	= true,
309 	.ret_type	= RET_INTEGER,
310 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
311 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
312 	.arg3_type	= ARG_ANYTHING,
313 };
314 
315 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
316 BPF_CALL_3(bpf_probe_read_compat, void *, dst, u32, size,
317 	   const void *, unsafe_ptr)
318 {
319 	if ((unsigned long)unsafe_ptr < TASK_SIZE) {
320 		return bpf_probe_read_user_common(dst, size,
321 				(__force void __user *)unsafe_ptr);
322 	}
323 	return bpf_probe_read_kernel_common(dst, size, unsafe_ptr);
324 }
325 
326 static const struct bpf_func_proto bpf_probe_read_compat_proto = {
327 	.func		= bpf_probe_read_compat,
328 	.gpl_only	= true,
329 	.ret_type	= RET_INTEGER,
330 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
331 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
332 	.arg3_type	= ARG_ANYTHING,
333 };
334 
335 BPF_CALL_3(bpf_probe_read_compat_str, void *, dst, u32, size,
336 	   const void *, unsafe_ptr)
337 {
338 	if ((unsigned long)unsafe_ptr < TASK_SIZE) {
339 		return bpf_probe_read_user_str_common(dst, size,
340 				(__force void __user *)unsafe_ptr);
341 	}
342 	return bpf_probe_read_kernel_str_common(dst, size, unsafe_ptr);
343 }
344 
345 static const struct bpf_func_proto bpf_probe_read_compat_str_proto = {
346 	.func		= bpf_probe_read_compat_str,
347 	.gpl_only	= true,
348 	.ret_type	= RET_INTEGER,
349 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
350 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
351 	.arg3_type	= ARG_ANYTHING,
352 };
353 #endif /* CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE */
354 
355 BPF_CALL_3(bpf_probe_write_user, void __user *, unsafe_ptr, const void *, src,
356 	   u32, size)
357 {
358 	/*
359 	 * Ensure we're in user context which is safe for the helper to
360 	 * run. This helper has no business in a kthread.
361 	 *
362 	 * access_ok() should prevent writing to non-user memory, but in
363 	 * some situations (nommu, temporary switch, etc) access_ok() does
364 	 * not provide enough validation, hence the check on KERNEL_DS.
365 	 *
366 	 * nmi_uaccess_okay() ensures the probe is not run in an interim
367 	 * state, when the task or mm are switched. This is specifically
368 	 * required to prevent the use of temporary mm.
369 	 */
370 
371 	if (unlikely(in_interrupt() ||
372 		     current->flags & (PF_KTHREAD | PF_EXITING)))
373 		return -EPERM;
374 	if (unlikely(!nmi_uaccess_okay()))
375 		return -EPERM;
376 
377 	return copy_to_user_nofault(unsafe_ptr, src, size);
378 }
379 
380 static const struct bpf_func_proto bpf_probe_write_user_proto = {
381 	.func		= bpf_probe_write_user,
382 	.gpl_only	= true,
383 	.ret_type	= RET_INTEGER,
384 	.arg1_type	= ARG_ANYTHING,
385 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
386 	.arg3_type	= ARG_MEM_SIZE,
387 };
388 
389 #define MAX_TRACE_PRINTK_VARARGS	3
390 #define BPF_TRACE_PRINTK_SIZE		1024
391 
392 BPF_CALL_5(bpf_trace_printk, char *, fmt, u32, fmt_size, u64, arg1,
393 	   u64, arg2, u64, arg3)
394 {
395 	u64 args[MAX_TRACE_PRINTK_VARARGS] = { arg1, arg2, arg3 };
396 	struct bpf_bprintf_data data = {
397 		.get_bin_args	= true,
398 		.get_buf	= true,
399 	};
400 	int ret;
401 
402 	ret = bpf_bprintf_prepare(fmt, fmt_size, args,
403 				  MAX_TRACE_PRINTK_VARARGS, &data);
404 	if (ret < 0)
405 		return ret;
406 
407 	ret = bstr_printf(data.buf, MAX_BPRINTF_BUF, fmt, data.bin_args);
408 
409 	trace_bpf_trace_printk(data.buf);
410 
411 	bpf_bprintf_cleanup(&data);
412 
413 	return ret;
414 }
415 
416 static const struct bpf_func_proto bpf_trace_printk_proto = {
417 	.func		= bpf_trace_printk,
418 	.gpl_only	= true,
419 	.ret_type	= RET_INTEGER,
420 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
421 	.arg2_type	= ARG_MEM_SIZE,
422 };
423 
424 static void __set_printk_clr_event(struct work_struct *work)
425 {
426 	/*
427 	 * This program might be calling bpf_trace_printk,
428 	 * so enable the associated bpf_trace/bpf_trace_printk event.
429 	 * Repeat this each time as it is possible a user has
430 	 * disabled bpf_trace_printk events.  By loading a program
431 	 * calling bpf_trace_printk() however the user has expressed
432 	 * the intent to see such events.
433 	 */
434 	if (trace_set_clr_event("bpf_trace", "bpf_trace_printk", 1))
435 		pr_warn_ratelimited("could not enable bpf_trace_printk events");
436 }
437 static DECLARE_WORK(set_printk_work, __set_printk_clr_event);
438 
439 const struct bpf_func_proto *bpf_get_trace_printk_proto(void)
440 {
441 	schedule_work(&set_printk_work);
442 	return &bpf_trace_printk_proto;
443 }
444 
445 BPF_CALL_4(bpf_trace_vprintk, char *, fmt, u32, fmt_size, const void *, args,
446 	   u32, data_len)
447 {
448 	struct bpf_bprintf_data data = {
449 		.get_bin_args	= true,
450 		.get_buf	= true,
451 	};
452 	int ret, num_args;
453 
454 	if (data_len & 7 || data_len > MAX_BPRINTF_VARARGS * 8 ||
455 	    (data_len && !args))
456 		return -EINVAL;
457 	num_args = data_len / 8;
458 
459 	ret = bpf_bprintf_prepare(fmt, fmt_size, args, num_args, &data);
460 	if (ret < 0)
461 		return ret;
462 
463 	ret = bstr_printf(data.buf, MAX_BPRINTF_BUF, fmt, data.bin_args);
464 
465 	trace_bpf_trace_printk(data.buf);
466 
467 	bpf_bprintf_cleanup(&data);
468 
469 	return ret;
470 }
471 
472 static const struct bpf_func_proto bpf_trace_vprintk_proto = {
473 	.func		= bpf_trace_vprintk,
474 	.gpl_only	= true,
475 	.ret_type	= RET_INTEGER,
476 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
477 	.arg2_type	= ARG_MEM_SIZE,
478 	.arg3_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
479 	.arg4_type	= ARG_MEM_SIZE_OR_ZERO,
480 };
481 
482 const struct bpf_func_proto *bpf_get_trace_vprintk_proto(void)
483 {
484 	schedule_work(&set_printk_work);
485 	return &bpf_trace_vprintk_proto;
486 }
487 
488 BPF_CALL_5(bpf_seq_printf, struct seq_file *, m, char *, fmt, u32, fmt_size,
489 	   const void *, args, u32, data_len)
490 {
491 	struct bpf_bprintf_data data = {
492 		.get_bin_args	= true,
493 	};
494 	int err, num_args;
495 
496 	if (data_len & 7 || data_len > MAX_BPRINTF_VARARGS * 8 ||
497 	    (data_len && !args))
498 		return -EINVAL;
499 	num_args = data_len / 8;
500 
501 	err = bpf_bprintf_prepare(fmt, fmt_size, args, num_args, &data);
502 	if (err < 0)
503 		return err;
504 
505 	seq_bprintf(m, fmt, data.bin_args);
506 
507 	bpf_bprintf_cleanup(&data);
508 
509 	return seq_has_overflowed(m) ? -EOVERFLOW : 0;
510 }
511 
512 BTF_ID_LIST_SINGLE(btf_seq_file_ids, struct, seq_file)
513 
514 static const struct bpf_func_proto bpf_seq_printf_proto = {
515 	.func		= bpf_seq_printf,
516 	.gpl_only	= true,
517 	.ret_type	= RET_INTEGER,
518 	.arg1_type	= ARG_PTR_TO_BTF_ID,
519 	.arg1_btf_id	= &btf_seq_file_ids[0],
520 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
521 	.arg3_type	= ARG_MEM_SIZE,
522 	.arg4_type      = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
523 	.arg5_type      = ARG_MEM_SIZE_OR_ZERO,
524 };
525 
526 BPF_CALL_3(bpf_seq_write, struct seq_file *, m, const void *, data, u32, len)
527 {
528 	return seq_write(m, data, len) ? -EOVERFLOW : 0;
529 }
530 
531 static const struct bpf_func_proto bpf_seq_write_proto = {
532 	.func		= bpf_seq_write,
533 	.gpl_only	= true,
534 	.ret_type	= RET_INTEGER,
535 	.arg1_type	= ARG_PTR_TO_BTF_ID,
536 	.arg1_btf_id	= &btf_seq_file_ids[0],
537 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
538 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
539 };
540 
541 BPF_CALL_4(bpf_seq_printf_btf, struct seq_file *, m, struct btf_ptr *, ptr,
542 	   u32, btf_ptr_size, u64, flags)
543 {
544 	const struct btf *btf;
545 	s32 btf_id;
546 	int ret;
547 
548 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
549 	if (ret)
550 		return ret;
551 
552 	return btf_type_seq_show_flags(btf, btf_id, ptr->ptr, m, flags);
553 }
554 
555 static const struct bpf_func_proto bpf_seq_printf_btf_proto = {
556 	.func		= bpf_seq_printf_btf,
557 	.gpl_only	= true,
558 	.ret_type	= RET_INTEGER,
559 	.arg1_type	= ARG_PTR_TO_BTF_ID,
560 	.arg1_btf_id	= &btf_seq_file_ids[0],
561 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
562 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
563 	.arg4_type	= ARG_ANYTHING,
564 };
565 
566 static __always_inline int
567 get_map_perf_counter(struct bpf_map *map, u64 flags,
568 		     u64 *value, u64 *enabled, u64 *running)
569 {
570 	struct bpf_array *array = container_of(map, struct bpf_array, map);
571 	unsigned int cpu = smp_processor_id();
572 	u64 index = flags & BPF_F_INDEX_MASK;
573 	struct bpf_event_entry *ee;
574 
575 	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
576 		return -EINVAL;
577 	if (index == BPF_F_CURRENT_CPU)
578 		index = cpu;
579 	if (unlikely(index >= array->map.max_entries))
580 		return -E2BIG;
581 
582 	ee = READ_ONCE(array->ptrs[index]);
583 	if (!ee)
584 		return -ENOENT;
585 
586 	return perf_event_read_local(ee->event, value, enabled, running);
587 }
588 
589 BPF_CALL_2(bpf_perf_event_read, struct bpf_map *, map, u64, flags)
590 {
591 	u64 value = 0;
592 	int err;
593 
594 	err = get_map_perf_counter(map, flags, &value, NULL, NULL);
595 	/*
596 	 * this api is ugly since we miss [-22..-2] range of valid
597 	 * counter values, but that's uapi
598 	 */
599 	if (err)
600 		return err;
601 	return value;
602 }
603 
604 const struct bpf_func_proto bpf_perf_event_read_proto = {
605 	.func		= bpf_perf_event_read,
606 	.gpl_only	= true,
607 	.ret_type	= RET_INTEGER,
608 	.arg1_type	= ARG_CONST_MAP_PTR,
609 	.arg2_type	= ARG_ANYTHING,
610 };
611 
612 BPF_CALL_4(bpf_perf_event_read_value, struct bpf_map *, map, u64, flags,
613 	   struct bpf_perf_event_value *, buf, u32, size)
614 {
615 	int err = -EINVAL;
616 
617 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
618 		goto clear;
619 	err = get_map_perf_counter(map, flags, &buf->counter, &buf->enabled,
620 				   &buf->running);
621 	if (unlikely(err))
622 		goto clear;
623 	return 0;
624 clear:
625 	memset(buf, 0, size);
626 	return err;
627 }
628 
629 static const struct bpf_func_proto bpf_perf_event_read_value_proto = {
630 	.func		= bpf_perf_event_read_value,
631 	.gpl_only	= true,
632 	.ret_type	= RET_INTEGER,
633 	.arg1_type	= ARG_CONST_MAP_PTR,
634 	.arg2_type	= ARG_ANYTHING,
635 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
636 	.arg4_type	= ARG_MEM_SIZE,
637 };
638 
639 const struct bpf_func_proto *bpf_get_perf_event_read_value_proto(void)
640 {
641 	return &bpf_perf_event_read_value_proto;
642 }
643 
644 static __always_inline u64
645 __bpf_perf_event_output(struct pt_regs *regs, struct bpf_map *map,
646 			u64 flags, struct perf_raw_record *raw,
647 			struct perf_sample_data *sd)
648 {
649 	struct bpf_array *array = container_of(map, struct bpf_array, map);
650 	unsigned int cpu = smp_processor_id();
651 	u64 index = flags & BPF_F_INDEX_MASK;
652 	struct bpf_event_entry *ee;
653 	struct perf_event *event;
654 
655 	if (index == BPF_F_CURRENT_CPU)
656 		index = cpu;
657 	if (unlikely(index >= array->map.max_entries))
658 		return -E2BIG;
659 
660 	ee = READ_ONCE(array->ptrs[index]);
661 	if (!ee)
662 		return -ENOENT;
663 
664 	event = ee->event;
665 	if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
666 		     event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
667 		return -EINVAL;
668 
669 	if (unlikely(event->oncpu != cpu))
670 		return -EOPNOTSUPP;
671 
672 	perf_sample_save_raw_data(sd, event, raw);
673 
674 	return perf_event_output(event, sd, regs);
675 }
676 
677 /*
678  * Support executing tracepoints in normal, irq, and nmi context that each call
679  * bpf_perf_event_output
680  */
681 struct bpf_trace_sample_data {
682 	struct perf_sample_data sds[3];
683 };
684 
685 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_trace_sds);
686 static DEFINE_PER_CPU(int, bpf_trace_nest_level);
687 BPF_CALL_5(bpf_perf_event_output, struct pt_regs *, regs, struct bpf_map *, map,
688 	   u64, flags, void *, data, u64, size)
689 {
690 	struct bpf_trace_sample_data *sds;
691 	struct perf_raw_record raw = {
692 		.frag = {
693 			.size = size,
694 			.data = data,
695 		},
696 	};
697 	struct perf_sample_data *sd;
698 	int nest_level, err;
699 
700 	preempt_disable();
701 	sds = this_cpu_ptr(&bpf_trace_sds);
702 	nest_level = this_cpu_inc_return(bpf_trace_nest_level);
703 
704 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(sds->sds))) {
705 		err = -EBUSY;
706 		goto out;
707 	}
708 
709 	sd = &sds->sds[nest_level - 1];
710 
711 	if (unlikely(flags & ~(BPF_F_INDEX_MASK))) {
712 		err = -EINVAL;
713 		goto out;
714 	}
715 
716 	perf_sample_data_init(sd, 0, 0);
717 
718 	err = __bpf_perf_event_output(regs, map, flags, &raw, sd);
719 out:
720 	this_cpu_dec(bpf_trace_nest_level);
721 	preempt_enable();
722 	return err;
723 }
724 
725 static const struct bpf_func_proto bpf_perf_event_output_proto = {
726 	.func		= bpf_perf_event_output,
727 	.gpl_only	= true,
728 	.ret_type	= RET_INTEGER,
729 	.arg1_type	= ARG_PTR_TO_CTX,
730 	.arg2_type	= ARG_CONST_MAP_PTR,
731 	.arg3_type	= ARG_ANYTHING,
732 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
733 	.arg5_type	= ARG_MEM_SIZE_OR_ZERO,
734 };
735 
736 static DEFINE_PER_CPU(int, bpf_event_output_nest_level);
737 struct bpf_nested_pt_regs {
738 	struct pt_regs regs[3];
739 };
740 static DEFINE_PER_CPU(struct bpf_nested_pt_regs, bpf_pt_regs);
741 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_misc_sds);
742 
743 u64 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
744 		     void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
745 {
746 	struct perf_raw_frag frag = {
747 		.copy		= ctx_copy,
748 		.size		= ctx_size,
749 		.data		= ctx,
750 	};
751 	struct perf_raw_record raw = {
752 		.frag = {
753 			{
754 				.next	= ctx_size ? &frag : NULL,
755 			},
756 			.size	= meta_size,
757 			.data	= meta,
758 		},
759 	};
760 	struct perf_sample_data *sd;
761 	struct pt_regs *regs;
762 	int nest_level;
763 	u64 ret;
764 
765 	preempt_disable();
766 	nest_level = this_cpu_inc_return(bpf_event_output_nest_level);
767 
768 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(bpf_misc_sds.sds))) {
769 		ret = -EBUSY;
770 		goto out;
771 	}
772 	sd = this_cpu_ptr(&bpf_misc_sds.sds[nest_level - 1]);
773 	regs = this_cpu_ptr(&bpf_pt_regs.regs[nest_level - 1]);
774 
775 	perf_fetch_caller_regs(regs);
776 	perf_sample_data_init(sd, 0, 0);
777 
778 	ret = __bpf_perf_event_output(regs, map, flags, &raw, sd);
779 out:
780 	this_cpu_dec(bpf_event_output_nest_level);
781 	preempt_enable();
782 	return ret;
783 }
784 
785 BPF_CALL_0(bpf_get_current_task)
786 {
787 	return (long) current;
788 }
789 
790 const struct bpf_func_proto bpf_get_current_task_proto = {
791 	.func		= bpf_get_current_task,
792 	.gpl_only	= true,
793 	.ret_type	= RET_INTEGER,
794 };
795 
796 BPF_CALL_0(bpf_get_current_task_btf)
797 {
798 	return (unsigned long) current;
799 }
800 
801 const struct bpf_func_proto bpf_get_current_task_btf_proto = {
802 	.func		= bpf_get_current_task_btf,
803 	.gpl_only	= true,
804 	.ret_type	= RET_PTR_TO_BTF_ID_TRUSTED,
805 	.ret_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
806 };
807 
808 BPF_CALL_1(bpf_task_pt_regs, struct task_struct *, task)
809 {
810 	return (unsigned long) task_pt_regs(task);
811 }
812 
813 BTF_ID_LIST_SINGLE(bpf_task_pt_regs_ids, struct, pt_regs)
814 
815 const struct bpf_func_proto bpf_task_pt_regs_proto = {
816 	.func		= bpf_task_pt_regs,
817 	.gpl_only	= true,
818 	.arg1_type	= ARG_PTR_TO_BTF_ID,
819 	.arg1_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
820 	.ret_type	= RET_PTR_TO_BTF_ID,
821 	.ret_btf_id	= &bpf_task_pt_regs_ids[0],
822 };
823 
824 struct send_signal_irq_work {
825 	struct irq_work irq_work;
826 	/* The claim: NULL marks the slot free for the next caller. */
827 	struct task_struct *task;
828 	u32 sig;
829 	enum pid_type type;
830 	bool has_siginfo;
831 	struct kernel_siginfo info;
832 };
833 
834 static DEFINE_PER_CPU(struct send_signal_irq_work, send_signal_work);
835 
836 static void do_bpf_send_signal(struct irq_work *entry)
837 {
838 	struct send_signal_irq_work *work;
839 	struct kernel_siginfo *siginfo;
840 
841 	work = container_of(entry, struct send_signal_irq_work, irq_work);
842 	siginfo = work->has_siginfo ? &work->info : SEND_SIG_PRIV;
843 
844 	group_send_sig_info(work->sig, siginfo, work->task, work->type);
845 	put_task_struct(work->task);
846 	/* Release once the fields are consumed. */
847 	smp_store_release(&work->task, NULL);
848 }
849 
850 static int bpf_send_signal_common(u32 sig, enum pid_type type, struct task_struct *task, u64 value)
851 {
852 	struct send_signal_irq_work *work = NULL;
853 	struct kernel_siginfo info;
854 	struct kernel_siginfo *siginfo;
855 
856 	if (!task) {
857 		task = current;
858 		siginfo = SEND_SIG_PRIV;
859 	} else {
860 		clear_siginfo(&info);
861 		info.si_signo = sig;
862 		info.si_errno = 0;
863 		info.si_code = SI_KERNEL;
864 		info.si_pid = 0;
865 		info.si_uid = 0;
866 		info.si_value.sival_ptr = (void __user __force *)(unsigned long)value;
867 		siginfo = &info;
868 	}
869 
870 	/*
871 	 * Similar to bpf_probe_write_user, task needs to be
872 	 * in a sound condition.
873 	 */
874 	if (unlikely(task->flags & (PF_KTHREAD | PF_EXITING)))
875 		return -EPERM;
876 	/* Task should not be pid=1 to avoid kernel panic. */
877 	if (unlikely(is_global_init(task)))
878 		return -EPERM;
879 
880 	if (preempt_count() != 0 || irqs_disabled()) {
881 		/* Do an early check on signal validity. Otherwise,
882 		 * the error is lost in deferred irq_work.
883 		 */
884 		if (unlikely(!valid_signal(sig)))
885 			return -EINVAL;
886 
887 		work = this_cpu_ptr(&send_signal_work);
888 		if (cmpxchg(&work->task, NULL, task))
889 			return -EBUSY;
890 
891 		/* Add the current task, which is the target of sending signal,
892 		 * to the irq_work. The current task may change when queued
893 		 * irq works get executed.
894 		 */
895 		get_task_struct(task);
896 		work->has_siginfo = siginfo == &info;
897 		if (work->has_siginfo)
898 			copy_siginfo(&work->info, &info);
899 		work->sig = sig;
900 		work->type = type;
901 		irq_work_queue(&work->irq_work);
902 		return 0;
903 	}
904 
905 	return group_send_sig_info(sig, siginfo, task, type);
906 }
907 
908 BPF_CALL_1(bpf_send_signal, u32, sig)
909 {
910 	return bpf_send_signal_common(sig, PIDTYPE_TGID, NULL, 0);
911 }
912 
913 const struct bpf_func_proto bpf_send_signal_proto = {
914 	.func		= bpf_send_signal,
915 	.gpl_only	= false,
916 	.ret_type	= RET_INTEGER,
917 	.arg1_type	= ARG_ANYTHING,
918 };
919 
920 BPF_CALL_1(bpf_send_signal_thread, u32, sig)
921 {
922 	return bpf_send_signal_common(sig, PIDTYPE_PID, NULL, 0);
923 }
924 
925 const struct bpf_func_proto bpf_send_signal_thread_proto = {
926 	.func		= bpf_send_signal_thread,
927 	.gpl_only	= false,
928 	.ret_type	= RET_INTEGER,
929 	.arg1_type	= ARG_ANYTHING,
930 };
931 
932 BPF_CALL_3(bpf_d_path, const struct path *, path, char *, buf, u32, sz)
933 {
934 	struct path copy;
935 	long len;
936 	char *p;
937 
938 	if (!sz)
939 		return 0;
940 
941 	/*
942 	 * The path pointer is verified as trusted and safe to use,
943 	 * but let's double check it's valid anyway to workaround
944 	 * potentially broken verifier.
945 	 */
946 	len = copy_from_kernel_nofault(&copy, path, sizeof(*path));
947 	if (len < 0)
948 		return len;
949 
950 	p = d_path(&copy, buf, sz);
951 	if (IS_ERR(p)) {
952 		len = PTR_ERR(p);
953 	} else {
954 		len = buf + sz - p;
955 		memmove(buf, p, len);
956 	}
957 
958 	return len;
959 }
960 
961 BTF_SET_START(btf_allowlist_d_path)
962 #ifdef CONFIG_SECURITY
963 BTF_ID(func, security_file_permission)
964 BTF_ID(func, security_inode_getattr)
965 BTF_ID(func, security_file_open)
966 #endif
967 #ifdef CONFIG_SECURITY_PATH
968 BTF_ID(func, security_path_truncate)
969 #endif
970 BTF_ID(func, vfs_truncate)
971 BTF_ID(func, vfs_fallocate)
972 BTF_ID(func, dentry_open)
973 BTF_ID(func, vfs_getattr)
974 BTF_ID(func, filp_close)
975 BTF_SET_END(btf_allowlist_d_path)
976 
977 BTF_SET_START(btf_allowlist_d_path_fentry)
978 BTF_ID(func, filp_close_sync)
979 BTF_SET_END(btf_allowlist_d_path_fentry)
980 
981 static bool bpf_d_path_allowed(const struct bpf_prog *prog)
982 {
983 	if (prog->type == BPF_PROG_TYPE_TRACING &&
984 	    prog->expected_attach_type == BPF_TRACE_ITER)
985 		return true;
986 
987 	if (prog->type == BPF_PROG_TYPE_LSM)
988 		return bpf_lsm_is_sleepable_hook(prog->aux->attach_btf_id);
989 
990 	if (btf_id_set_contains(&btf_allowlist_d_path,
991 				prog->aux->attach_btf_id))
992 		return true;
993 
994 	if (btf_id_set_contains(&btf_allowlist_d_path_fentry,
995 				prog->aux->attach_btf_id))
996 		return prog->expected_attach_type == BPF_TRACE_FENTRY;
997 
998 	return false;
999 }
1000 
1001 BTF_ID_LIST_SINGLE(bpf_d_path_btf_ids, struct, path)
1002 
1003 static const struct bpf_func_proto bpf_d_path_proto = {
1004 	.func		= bpf_d_path,
1005 	.gpl_only	= false,
1006 	.ret_type	= RET_INTEGER,
1007 	.arg1_type	= ARG_PTR_TO_BTF_ID,
1008 	.arg1_btf_id	= &bpf_d_path_btf_ids[0],
1009 	.arg2_type	= ARG_PTR_TO_MEM | MEM_UNINIT | MEM_WRITE,
1010 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
1011 	.allowed	= bpf_d_path_allowed,
1012 };
1013 
1014 #define BTF_F_ALL	(BTF_F_COMPACT  | BTF_F_NONAME | \
1015 			 BTF_F_PTR_RAW | BTF_F_ZERO)
1016 
1017 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
1018 				  u64 flags, const struct btf **btf,
1019 				  s32 *btf_id)
1020 {
1021 	const struct btf_type *t;
1022 
1023 	if (unlikely(flags & ~(BTF_F_ALL)))
1024 		return -EINVAL;
1025 
1026 	if (btf_ptr_size != sizeof(struct btf_ptr))
1027 		return -EINVAL;
1028 
1029 	*btf = bpf_get_btf_vmlinux();
1030 
1031 	if (IS_ERR_OR_NULL(*btf))
1032 		return IS_ERR(*btf) ? PTR_ERR(*btf) : -EINVAL;
1033 
1034 	if (ptr->type_id > 0)
1035 		*btf_id = ptr->type_id;
1036 	else
1037 		return -EINVAL;
1038 
1039 	if (*btf_id > 0)
1040 		t = btf_type_by_id(*btf, *btf_id);
1041 	if (*btf_id <= 0 || !t)
1042 		return -ENOENT;
1043 
1044 	return 0;
1045 }
1046 
1047 BPF_CALL_5(bpf_snprintf_btf, char *, str, u32, str_size, struct btf_ptr *, ptr,
1048 	   u32, btf_ptr_size, u64, flags)
1049 {
1050 	const struct btf *btf;
1051 	s32 btf_id;
1052 	int ret;
1053 
1054 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
1055 	if (ret)
1056 		return ret;
1057 
1058 	return btf_type_snprintf_show(btf, btf_id, ptr->ptr, str, str_size,
1059 				      flags);
1060 }
1061 
1062 const struct bpf_func_proto bpf_snprintf_btf_proto = {
1063 	.func		= bpf_snprintf_btf,
1064 	.gpl_only	= false,
1065 	.ret_type	= RET_INTEGER,
1066 	.arg1_type	= ARG_PTR_TO_MEM | MEM_UNINIT | MEM_WRITE,
1067 	.arg2_type	= ARG_MEM_SIZE,
1068 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1069 	.arg4_type	= ARG_MEM_SIZE,
1070 	.arg5_type	= ARG_ANYTHING,
1071 };
1072 
1073 BPF_CALL_1(bpf_get_func_ip_tracing, void *, ctx)
1074 {
1075 	/* This helper call is inlined by verifier. */
1076 	return ((u64 *)ctx)[-2];
1077 }
1078 
1079 static const struct bpf_func_proto bpf_get_func_ip_proto_tracing = {
1080 	.func		= bpf_get_func_ip_tracing,
1081 	.gpl_only	= true,
1082 	.ret_type	= RET_INTEGER,
1083 	.arg1_type	= ARG_PTR_TO_CTX,
1084 };
1085 
1086 static inline unsigned long get_entry_ip(unsigned long fentry_ip)
1087 {
1088 #ifdef CONFIG_X86_KERNEL_IBT
1089 	if (is_endbr((void *)(fentry_ip - ENDBR_INSN_SIZE)))
1090 		fentry_ip -= ENDBR_INSN_SIZE;
1091 #endif
1092 	return fentry_ip;
1093 }
1094 
1095 BPF_CALL_1(bpf_get_func_ip_kprobe, struct pt_regs *, regs)
1096 {
1097 	struct bpf_trace_run_ctx *run_ctx __maybe_unused;
1098 	struct kprobe *kp;
1099 
1100 #ifdef CONFIG_UPROBES
1101 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1102 	if (run_ctx->is_uprobe)
1103 		return ((struct uprobe_dispatch_data *)current->utask->vaddr)->bp_addr;
1104 #endif
1105 
1106 	kp = kprobe_running();
1107 
1108 	if (!kp || !(kp->flags & KPROBE_FLAG_ON_FUNC_ENTRY))
1109 		return 0;
1110 
1111 	return get_entry_ip((uintptr_t)kp->addr);
1112 }
1113 
1114 static const struct bpf_func_proto bpf_get_func_ip_proto_kprobe = {
1115 	.func		= bpf_get_func_ip_kprobe,
1116 	.gpl_only	= true,
1117 	.ret_type	= RET_INTEGER,
1118 	.arg1_type	= ARG_PTR_TO_CTX,
1119 };
1120 
1121 BPF_CALL_1(bpf_get_func_ip_kprobe_multi, struct pt_regs *, regs)
1122 {
1123 	return bpf_kprobe_multi_entry_ip(current->bpf_ctx);
1124 }
1125 
1126 static const struct bpf_func_proto bpf_get_func_ip_proto_kprobe_multi = {
1127 	.func		= bpf_get_func_ip_kprobe_multi,
1128 	.gpl_only	= false,
1129 	.ret_type	= RET_INTEGER,
1130 	.arg1_type	= ARG_PTR_TO_CTX,
1131 };
1132 
1133 BPF_CALL_1(bpf_get_attach_cookie_kprobe_multi, struct pt_regs *, regs)
1134 {
1135 	return bpf_kprobe_multi_cookie(current->bpf_ctx);
1136 }
1137 
1138 static const struct bpf_func_proto bpf_get_attach_cookie_proto_kmulti = {
1139 	.func		= bpf_get_attach_cookie_kprobe_multi,
1140 	.gpl_only	= false,
1141 	.ret_type	= RET_INTEGER,
1142 	.arg1_type	= ARG_PTR_TO_CTX,
1143 };
1144 
1145 BPF_CALL_1(bpf_get_func_ip_uprobe_multi, struct pt_regs *, regs)
1146 {
1147 	return bpf_uprobe_multi_entry_ip(current->bpf_ctx);
1148 }
1149 
1150 static const struct bpf_func_proto bpf_get_func_ip_proto_uprobe_multi = {
1151 	.func		= bpf_get_func_ip_uprobe_multi,
1152 	.gpl_only	= false,
1153 	.ret_type	= RET_INTEGER,
1154 	.arg1_type	= ARG_PTR_TO_CTX,
1155 };
1156 
1157 BPF_CALL_1(bpf_get_attach_cookie_uprobe_multi, struct pt_regs *, regs)
1158 {
1159 	return bpf_uprobe_multi_cookie(current->bpf_ctx);
1160 }
1161 
1162 static const struct bpf_func_proto bpf_get_attach_cookie_proto_umulti = {
1163 	.func		= bpf_get_attach_cookie_uprobe_multi,
1164 	.gpl_only	= false,
1165 	.ret_type	= RET_INTEGER,
1166 	.arg1_type	= ARG_PTR_TO_CTX,
1167 };
1168 
1169 BPF_CALL_1(bpf_get_attach_cookie_trace, void *, ctx)
1170 {
1171 	struct bpf_trace_run_ctx *run_ctx;
1172 
1173 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1174 	return run_ctx->bpf_cookie;
1175 }
1176 
1177 static const struct bpf_func_proto bpf_get_attach_cookie_proto_trace = {
1178 	.func		= bpf_get_attach_cookie_trace,
1179 	.gpl_only	= false,
1180 	.ret_type	= RET_INTEGER,
1181 	.arg1_type	= ARG_PTR_TO_CTX,
1182 };
1183 
1184 BPF_CALL_1(bpf_get_attach_cookie_pe, struct bpf_perf_event_data_kern *, ctx)
1185 {
1186 	return ctx->event->bpf_cookie;
1187 }
1188 
1189 static const struct bpf_func_proto bpf_get_attach_cookie_proto_pe = {
1190 	.func		= bpf_get_attach_cookie_pe,
1191 	.gpl_only	= false,
1192 	.ret_type	= RET_INTEGER,
1193 	.arg1_type	= ARG_PTR_TO_CTX,
1194 };
1195 
1196 BPF_CALL_1(bpf_get_attach_cookie_tracing, void *, ctx)
1197 {
1198 	struct bpf_trace_run_ctx *run_ctx;
1199 
1200 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1201 	return run_ctx->bpf_cookie;
1202 }
1203 
1204 static const struct bpf_func_proto bpf_get_attach_cookie_proto_tracing = {
1205 	.func		= bpf_get_attach_cookie_tracing,
1206 	.gpl_only	= false,
1207 	.ret_type	= RET_INTEGER,
1208 	.arg1_type	= ARG_PTR_TO_CTX,
1209 };
1210 
1211 BPF_CALL_3(bpf_get_branch_snapshot, void *, buf, u32, size, u64, flags)
1212 {
1213 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1214 	u32 entry_cnt = size / br_entry_size;
1215 
1216 	entry_cnt = static_call(perf_snapshot_branch_stack)(buf, entry_cnt);
1217 
1218 	if (unlikely(flags))
1219 		return -EINVAL;
1220 
1221 	if (!entry_cnt)
1222 		return -ENOENT;
1223 
1224 	return entry_cnt * br_entry_size;
1225 }
1226 
1227 const struct bpf_func_proto bpf_get_branch_snapshot_proto = {
1228 	.func		= bpf_get_branch_snapshot,
1229 	.gpl_only	= true,
1230 	.ret_type	= RET_INTEGER,
1231 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1232 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
1233 };
1234 
1235 BPF_CALL_3(get_func_arg, void *, ctx, u32, n, u64 *, value)
1236 {
1237 	/* This helper call is inlined by verifier. */
1238 	u64 nr_args = ((u64 *)ctx)[-1] & 0xFF;
1239 
1240 	if ((u64) n >= nr_args)
1241 		return -EINVAL;
1242 	*value = ((u64 *)ctx)[n];
1243 	return 0;
1244 }
1245 
1246 static const struct bpf_func_proto bpf_get_func_arg_proto = {
1247 	.func		= get_func_arg,
1248 	.ret_type	= RET_INTEGER,
1249 	.arg1_type	= ARG_PTR_TO_CTX,
1250 	.arg2_type	= ARG_ANYTHING,
1251 	.arg3_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
1252 	.arg3_size	= sizeof(u64),
1253 };
1254 
1255 BPF_CALL_2(get_func_ret, void *, ctx, u64 *, value)
1256 {
1257 	/* This helper call is inlined by verifier. */
1258 	u64 nr_args = ((u64 *)ctx)[-1] & 0xFF;
1259 
1260 	*value = ((u64 *)ctx)[nr_args];
1261 	return 0;
1262 }
1263 
1264 static const struct bpf_func_proto bpf_get_func_ret_proto = {
1265 	.func		= get_func_ret,
1266 	.ret_type	= RET_INTEGER,
1267 	.arg1_type	= ARG_PTR_TO_CTX,
1268 	.arg2_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
1269 	.arg2_size	= sizeof(u64),
1270 };
1271 
1272 BPF_CALL_1(get_func_arg_cnt, void *, ctx)
1273 {
1274 	/* This helper call is inlined by verifier. */
1275 	return ((u64 *)ctx)[-1] & 0xFF;
1276 }
1277 
1278 static const struct bpf_func_proto bpf_get_func_arg_cnt_proto = {
1279 	.func		= get_func_arg_cnt,
1280 	.ret_type	= RET_INTEGER,
1281 	.arg1_type	= ARG_PTR_TO_CTX,
1282 };
1283 
1284 static const struct bpf_func_proto *
1285 bpf_tracing_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1286 {
1287 	const struct bpf_func_proto *func_proto;
1288 
1289 	switch (func_id) {
1290 	case BPF_FUNC_get_smp_processor_id:
1291 		return &bpf_get_smp_processor_id_proto;
1292 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
1293 	case BPF_FUNC_probe_read:
1294 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1295 		       NULL : &bpf_probe_read_compat_proto;
1296 	case BPF_FUNC_probe_read_str:
1297 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1298 		       NULL : &bpf_probe_read_compat_str_proto;
1299 #endif
1300 	case BPF_FUNC_get_func_ip:
1301 		return &bpf_get_func_ip_proto_tracing;
1302 	default:
1303 		break;
1304 	}
1305 
1306 	func_proto = bpf_base_func_proto(func_id, prog);
1307 	if (func_proto)
1308 		return func_proto;
1309 
1310 	if (!bpf_token_capable(prog->aux->token, CAP_SYS_ADMIN))
1311 		return NULL;
1312 
1313 	switch (func_id) {
1314 	case BPF_FUNC_probe_write_user:
1315 		return security_locked_down(LOCKDOWN_BPF_WRITE_USER) < 0 ?
1316 		       NULL : &bpf_probe_write_user_proto;
1317 	default:
1318 		return NULL;
1319 	}
1320 }
1321 
1322 static bool is_kprobe_multi(const struct bpf_prog *prog)
1323 {
1324 	return prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI ||
1325 	       prog->expected_attach_type == BPF_TRACE_KPROBE_SESSION;
1326 }
1327 
1328 static inline bool is_kprobe_session(const struct bpf_prog *prog)
1329 {
1330 	return prog->type == BPF_PROG_TYPE_KPROBE &&
1331 	       prog->expected_attach_type == BPF_TRACE_KPROBE_SESSION;
1332 }
1333 
1334 static inline bool is_uprobe_multi(const struct bpf_prog *prog)
1335 {
1336 	return prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI ||
1337 	       prog->expected_attach_type == BPF_TRACE_UPROBE_SESSION;
1338 }
1339 
1340 static inline bool is_uprobe_session(const struct bpf_prog *prog)
1341 {
1342 	return prog->type == BPF_PROG_TYPE_KPROBE &&
1343 	       prog->expected_attach_type == BPF_TRACE_UPROBE_SESSION;
1344 }
1345 
1346 static inline bool is_trace_fsession(const struct bpf_prog *prog)
1347 {
1348 	return prog->type == BPF_PROG_TYPE_TRACING &&
1349 	       (prog->expected_attach_type == BPF_TRACE_FSESSION ||
1350 		prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI);
1351 }
1352 
1353 static const struct bpf_func_proto *
1354 kprobe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1355 {
1356 	switch (func_id) {
1357 	case BPF_FUNC_perf_event_output:
1358 		return &bpf_perf_event_output_proto;
1359 	case BPF_FUNC_get_stackid:
1360 		return &bpf_get_stackid_proto;
1361 	case BPF_FUNC_get_stack:
1362 		return prog->sleepable ? &bpf_get_stack_sleepable_proto : &bpf_get_stack_proto;
1363 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
1364 	case BPF_FUNC_override_return:
1365 		return &bpf_override_return_proto;
1366 #endif
1367 	case BPF_FUNC_get_func_ip:
1368 		if (is_kprobe_multi(prog))
1369 			return &bpf_get_func_ip_proto_kprobe_multi;
1370 		if (is_uprobe_multi(prog))
1371 			return &bpf_get_func_ip_proto_uprobe_multi;
1372 		return &bpf_get_func_ip_proto_kprobe;
1373 	case BPF_FUNC_get_attach_cookie:
1374 		if (is_kprobe_multi(prog))
1375 			return &bpf_get_attach_cookie_proto_kmulti;
1376 		if (is_uprobe_multi(prog))
1377 			return &bpf_get_attach_cookie_proto_umulti;
1378 		return &bpf_get_attach_cookie_proto_trace;
1379 	default:
1380 		return bpf_tracing_func_proto(func_id, prog);
1381 	}
1382 }
1383 
1384 /* bpf+kprobe programs can access fields of 'struct pt_regs' */
1385 static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1386 					const struct bpf_prog *prog,
1387 					struct bpf_insn_access_aux *info)
1388 {
1389 	if (off < 0 || off >= sizeof(struct pt_regs))
1390 		return false;
1391 	if (off % size != 0)
1392 		return false;
1393 	/*
1394 	 * Assertion for 32 bit to make sure last 8 byte access
1395 	 * (BPF_DW) to the last 4 byte member is disallowed.
1396 	 */
1397 	if (off + size > sizeof(struct pt_regs))
1398 		return false;
1399 
1400 	if (type == BPF_WRITE)
1401 		prog->aux->kprobe_write_ctx = true;
1402 
1403 	return true;
1404 }
1405 
1406 const struct bpf_verifier_ops kprobe_verifier_ops = {
1407 	.get_func_proto  = kprobe_prog_func_proto,
1408 	.is_valid_access = kprobe_prog_is_valid_access,
1409 };
1410 
1411 const struct bpf_prog_ops kprobe_prog_ops = {
1412 };
1413 
1414 BPF_CALL_5(bpf_perf_event_output_tp, void *, tp_buff, struct bpf_map *, map,
1415 	   u64, flags, void *, data, u64, size)
1416 {
1417 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1418 
1419 	/*
1420 	 * r1 points to perf tracepoint buffer where first 8 bytes are hidden
1421 	 * from bpf program and contain a pointer to 'struct pt_regs'. Fetch it
1422 	 * from there and call the same bpf_perf_event_output() helper inline.
1423 	 */
1424 	return ____bpf_perf_event_output(regs, map, flags, data, size);
1425 }
1426 
1427 static const struct bpf_func_proto bpf_perf_event_output_proto_tp = {
1428 	.func		= bpf_perf_event_output_tp,
1429 	.gpl_only	= true,
1430 	.ret_type	= RET_INTEGER,
1431 	.arg1_type	= ARG_PTR_TO_CTX,
1432 	.arg2_type	= ARG_CONST_MAP_PTR,
1433 	.arg3_type	= ARG_ANYTHING,
1434 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1435 	.arg5_type	= ARG_MEM_SIZE_OR_ZERO,
1436 };
1437 
1438 BPF_CALL_3(bpf_get_stackid_tp, void *, tp_buff, struct bpf_map *, map,
1439 	   u64, flags)
1440 {
1441 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1442 
1443 	/*
1444 	 * Same comment as in bpf_perf_event_output_tp(), only that this time
1445 	 * the other helper's function body cannot be inlined due to being
1446 	 * external, thus we need to call raw helper function.
1447 	 */
1448 	return bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1449 			       flags, 0, 0);
1450 }
1451 
1452 static const struct bpf_func_proto bpf_get_stackid_proto_tp = {
1453 	.func		= bpf_get_stackid_tp,
1454 	.gpl_only	= true,
1455 	.ret_type	= RET_INTEGER,
1456 	.arg1_type	= ARG_PTR_TO_CTX,
1457 	.arg2_type	= ARG_CONST_MAP_PTR,
1458 	.arg3_type	= ARG_ANYTHING,
1459 };
1460 
1461 BPF_CALL_4(bpf_get_stack_tp, void *, tp_buff, void *, buf, u32, size,
1462 	   u64, flags)
1463 {
1464 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1465 
1466 	return bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1467 			     (unsigned long) size, flags, 0);
1468 }
1469 
1470 static const struct bpf_func_proto bpf_get_stack_proto_tp = {
1471 	.func		= bpf_get_stack_tp,
1472 	.gpl_only	= true,
1473 	.ret_type	= RET_INTEGER,
1474 	.arg1_type	= ARG_PTR_TO_CTX,
1475 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
1476 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
1477 	.arg4_type	= ARG_ANYTHING,
1478 };
1479 
1480 static const struct bpf_func_proto *
1481 tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1482 {
1483 	switch (func_id) {
1484 	case BPF_FUNC_perf_event_output:
1485 		return &bpf_perf_event_output_proto_tp;
1486 	case BPF_FUNC_get_stackid:
1487 		return &bpf_get_stackid_proto_tp;
1488 	case BPF_FUNC_get_stack:
1489 		return &bpf_get_stack_proto_tp;
1490 	case BPF_FUNC_get_attach_cookie:
1491 		return &bpf_get_attach_cookie_proto_trace;
1492 	default:
1493 		return bpf_tracing_func_proto(func_id, prog);
1494 	}
1495 }
1496 
1497 static bool tp_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1498 				    const struct bpf_prog *prog,
1499 				    struct bpf_insn_access_aux *info)
1500 {
1501 	if (off < sizeof(void *) || off >= PERF_MAX_TRACE_SIZE)
1502 		return false;
1503 	if (type != BPF_READ)
1504 		return false;
1505 	if (off % size != 0)
1506 		return false;
1507 
1508 	BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(__u64));
1509 	return true;
1510 }
1511 
1512 const struct bpf_verifier_ops tracepoint_verifier_ops = {
1513 	.get_func_proto  = tp_prog_func_proto,
1514 	.is_valid_access = tp_prog_is_valid_access,
1515 };
1516 
1517 const struct bpf_prog_ops tracepoint_prog_ops = {
1518 };
1519 
1520 BPF_CALL_3(bpf_perf_prog_read_value, struct bpf_perf_event_data_kern *, ctx,
1521 	   struct bpf_perf_event_value *, buf, u32, size)
1522 {
1523 	int err = -EINVAL;
1524 
1525 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
1526 		goto clear;
1527 	err = perf_event_read_local(ctx->event, &buf->counter, &buf->enabled,
1528 				    &buf->running);
1529 	if (unlikely(err))
1530 		goto clear;
1531 	return 0;
1532 clear:
1533 	memset(buf, 0, size);
1534 	return err;
1535 }
1536 
1537 static const struct bpf_func_proto bpf_perf_prog_read_value_proto = {
1538 	.func           = bpf_perf_prog_read_value,
1539 	.gpl_only       = true,
1540 	.ret_type       = RET_INTEGER,
1541 	.arg1_type      = ARG_PTR_TO_CTX,
1542 	.arg2_type      = ARG_PTR_TO_UNINIT_MEM,
1543 	.arg3_type      = ARG_MEM_SIZE,
1544 };
1545 
1546 BPF_CALL_4(bpf_read_branch_records, struct bpf_perf_event_data_kern *, ctx,
1547 	   void *, buf, u32, size, u64, flags)
1548 {
1549 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1550 	struct perf_branch_stack *br_stack = ctx->data->br_stack;
1551 	u32 to_copy;
1552 
1553 	if (unlikely(flags & ~BPF_F_GET_BRANCH_RECORDS_SIZE))
1554 		return -EINVAL;
1555 
1556 	if (unlikely(!(ctx->data->sample_flags & PERF_SAMPLE_BRANCH_STACK)))
1557 		return -ENOENT;
1558 
1559 	if (unlikely(!br_stack))
1560 		return -ENOENT;
1561 
1562 	if (flags & BPF_F_GET_BRANCH_RECORDS_SIZE)
1563 		return br_stack->nr * br_entry_size;
1564 
1565 	if (!buf || (size % br_entry_size != 0))
1566 		return -EINVAL;
1567 
1568 	to_copy = min_t(u32, br_stack->nr * br_entry_size, size);
1569 	memcpy(buf, br_stack->entries, to_copy);
1570 
1571 	return to_copy;
1572 }
1573 
1574 static const struct bpf_func_proto bpf_read_branch_records_proto = {
1575 	.func           = bpf_read_branch_records,
1576 	.gpl_only       = true,
1577 	.ret_type       = RET_INTEGER,
1578 	.arg1_type      = ARG_PTR_TO_CTX,
1579 	.arg2_type      = ARG_PTR_TO_MEM_OR_NULL | MEM_UNINIT | MEM_WRITE,
1580 	.arg3_type      = ARG_MEM_SIZE_OR_ZERO,
1581 	.arg4_type      = ARG_ANYTHING,
1582 };
1583 
1584 static const struct bpf_func_proto *
1585 pe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1586 {
1587 	switch (func_id) {
1588 	case BPF_FUNC_perf_event_output:
1589 		return &bpf_perf_event_output_proto_tp;
1590 	case BPF_FUNC_get_stackid:
1591 		return &bpf_get_stackid_proto_pe;
1592 	case BPF_FUNC_get_stack:
1593 		return &bpf_get_stack_proto_pe;
1594 	case BPF_FUNC_perf_prog_read_value:
1595 		return &bpf_perf_prog_read_value_proto;
1596 	case BPF_FUNC_read_branch_records:
1597 		return &bpf_read_branch_records_proto;
1598 	case BPF_FUNC_get_attach_cookie:
1599 		return &bpf_get_attach_cookie_proto_pe;
1600 	default:
1601 		return bpf_tracing_func_proto(func_id, prog);
1602 	}
1603 }
1604 
1605 /*
1606  * bpf_raw_tp_regs are separate from bpf_pt_regs used from skb/xdp
1607  * to avoid potential recursive reuse issue when/if tracepoints are added
1608  * inside bpf_*_event_output, bpf_get_stackid and/or bpf_get_stack.
1609  *
1610  * Since raw tracepoints run despite bpf_prog_active, support concurrent usage
1611  * in normal, irq, and nmi context.
1612  */
1613 struct bpf_raw_tp_regs {
1614 	struct pt_regs regs[3];
1615 };
1616 static DEFINE_PER_CPU(struct bpf_raw_tp_regs, bpf_raw_tp_regs);
1617 static DEFINE_PER_CPU(int, bpf_raw_tp_nest_level);
1618 static struct pt_regs *get_bpf_raw_tp_regs(void)
1619 {
1620 	struct bpf_raw_tp_regs *tp_regs = this_cpu_ptr(&bpf_raw_tp_regs);
1621 	int nest_level = this_cpu_inc_return(bpf_raw_tp_nest_level);
1622 
1623 	if (nest_level > ARRAY_SIZE(tp_regs->regs)) {
1624 		this_cpu_dec(bpf_raw_tp_nest_level);
1625 		return ERR_PTR(-EBUSY);
1626 	}
1627 
1628 	return &tp_regs->regs[nest_level - 1];
1629 }
1630 
1631 static void put_bpf_raw_tp_regs(void)
1632 {
1633 	this_cpu_dec(bpf_raw_tp_nest_level);
1634 }
1635 
1636 BPF_CALL_5(bpf_perf_event_output_raw_tp, struct bpf_raw_tracepoint_args *, args,
1637 	   struct bpf_map *, map, u64, flags, void *, data, u64, size)
1638 {
1639 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1640 	int ret;
1641 
1642 	if (IS_ERR(regs))
1643 		return PTR_ERR(regs);
1644 
1645 	perf_fetch_caller_regs(regs);
1646 	ret = ____bpf_perf_event_output(regs, map, flags, data, size);
1647 
1648 	put_bpf_raw_tp_regs();
1649 	return ret;
1650 }
1651 
1652 static const struct bpf_func_proto bpf_perf_event_output_proto_raw_tp = {
1653 	.func		= bpf_perf_event_output_raw_tp,
1654 	.gpl_only	= true,
1655 	.ret_type	= RET_INTEGER,
1656 	.arg1_type	= ARG_PTR_TO_CTX,
1657 	.arg2_type	= ARG_CONST_MAP_PTR,
1658 	.arg3_type	= ARG_ANYTHING,
1659 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1660 	.arg5_type	= ARG_MEM_SIZE_OR_ZERO,
1661 };
1662 
1663 extern const struct bpf_func_proto bpf_skb_output_proto;
1664 extern const struct bpf_func_proto bpf_xdp_output_proto;
1665 extern const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto;
1666 
1667 BPF_CALL_3(bpf_get_stackid_raw_tp, struct bpf_raw_tracepoint_args *, args,
1668 	   struct bpf_map *, map, u64, flags)
1669 {
1670 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1671 	int ret;
1672 
1673 	if (IS_ERR(regs))
1674 		return PTR_ERR(regs);
1675 
1676 	perf_fetch_caller_regs(regs);
1677 	/* similar to bpf_perf_event_output_tp, but pt_regs fetched differently */
1678 	ret = bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1679 			      flags, 0, 0);
1680 	put_bpf_raw_tp_regs();
1681 	return ret;
1682 }
1683 
1684 static const struct bpf_func_proto bpf_get_stackid_proto_raw_tp = {
1685 	.func		= bpf_get_stackid_raw_tp,
1686 	.gpl_only	= true,
1687 	.ret_type	= RET_INTEGER,
1688 	.arg1_type	= ARG_PTR_TO_CTX,
1689 	.arg2_type	= ARG_CONST_MAP_PTR,
1690 	.arg3_type	= ARG_ANYTHING,
1691 };
1692 
1693 BPF_CALL_4(bpf_get_stack_raw_tp, struct bpf_raw_tracepoint_args *, args,
1694 	   void *, buf, u32, size, u64, flags)
1695 {
1696 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1697 	int ret;
1698 
1699 	if (IS_ERR(regs))
1700 		return PTR_ERR(regs);
1701 
1702 	perf_fetch_caller_regs(regs);
1703 	ret = bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1704 			    (unsigned long) size, flags, 0);
1705 	put_bpf_raw_tp_regs();
1706 	return ret;
1707 }
1708 
1709 static const struct bpf_func_proto bpf_get_stack_proto_raw_tp = {
1710 	.func		= bpf_get_stack_raw_tp,
1711 	.gpl_only	= true,
1712 	.ret_type	= RET_INTEGER,
1713 	.arg1_type	= ARG_PTR_TO_CTX,
1714 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
1715 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
1716 	.arg4_type	= ARG_ANYTHING,
1717 };
1718 
1719 static const struct bpf_func_proto *
1720 raw_tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1721 {
1722 	switch (func_id) {
1723 	case BPF_FUNC_perf_event_output:
1724 		return &bpf_perf_event_output_proto_raw_tp;
1725 	case BPF_FUNC_get_stackid:
1726 		return &bpf_get_stackid_proto_raw_tp;
1727 	case BPF_FUNC_get_stack:
1728 		return &bpf_get_stack_proto_raw_tp;
1729 	case BPF_FUNC_get_attach_cookie:
1730 		return &bpf_get_attach_cookie_proto_tracing;
1731 	default:
1732 		return bpf_tracing_func_proto(func_id, prog);
1733 	}
1734 }
1735 
1736 const struct bpf_func_proto *
1737 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1738 {
1739 	const struct bpf_func_proto *fn;
1740 
1741 	switch (func_id) {
1742 #ifdef CONFIG_NET
1743 	case BPF_FUNC_skb_output:
1744 		return &bpf_skb_output_proto;
1745 	case BPF_FUNC_xdp_output:
1746 		return &bpf_xdp_output_proto;
1747 	case BPF_FUNC_skc_to_tcp6_sock:
1748 		return &bpf_skc_to_tcp6_sock_proto;
1749 	case BPF_FUNC_skc_to_tcp_sock:
1750 		return &bpf_skc_to_tcp_sock_proto;
1751 	case BPF_FUNC_skc_to_tcp_timewait_sock:
1752 		return &bpf_skc_to_tcp_timewait_sock_proto;
1753 	case BPF_FUNC_skc_to_tcp_request_sock:
1754 		return &bpf_skc_to_tcp_request_sock_proto;
1755 	case BPF_FUNC_skc_to_udp6_sock:
1756 		return &bpf_skc_to_udp6_sock_proto;
1757 	case BPF_FUNC_skc_to_unix_sock:
1758 		return &bpf_skc_to_unix_sock_proto;
1759 	case BPF_FUNC_skc_to_mptcp_sock:
1760 		return &bpf_skc_to_mptcp_sock_proto;
1761 	case BPF_FUNC_sk_storage_get:
1762 		return &bpf_sk_storage_get_tracing_proto;
1763 	case BPF_FUNC_sk_storage_delete:
1764 		return &bpf_sk_storage_delete_tracing_proto;
1765 	case BPF_FUNC_sock_from_file:
1766 		return &bpf_sock_from_file_proto;
1767 	case BPF_FUNC_get_socket_cookie:
1768 		return &bpf_get_socket_ptr_cookie_proto;
1769 	case BPF_FUNC_xdp_get_buff_len:
1770 		return &bpf_xdp_get_buff_len_trace_proto;
1771 #endif
1772 	case BPF_FUNC_seq_printf:
1773 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1774 		       &bpf_seq_printf_proto :
1775 		       NULL;
1776 	case BPF_FUNC_seq_write:
1777 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1778 		       &bpf_seq_write_proto :
1779 		       NULL;
1780 	case BPF_FUNC_seq_printf_btf:
1781 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1782 		       &bpf_seq_printf_btf_proto :
1783 		       NULL;
1784 	case BPF_FUNC_d_path:
1785 		return &bpf_d_path_proto;
1786 	case BPF_FUNC_get_func_arg:
1787 		if (bpf_prog_has_trampoline(prog) ||
1788 		    prog->expected_attach_type == BPF_TRACE_RAW_TP)
1789 			return &bpf_get_func_arg_proto;
1790 		return NULL;
1791 	case BPF_FUNC_get_func_ret:
1792 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_ret_proto : NULL;
1793 	case BPF_FUNC_get_func_arg_cnt:
1794 		if (bpf_prog_has_trampoline(prog) ||
1795 		    prog->expected_attach_type == BPF_TRACE_RAW_TP)
1796 			return &bpf_get_func_arg_cnt_proto;
1797 		return NULL;
1798 	case BPF_FUNC_get_attach_cookie:
1799 		if (prog->type == BPF_PROG_TYPE_TRACING &&
1800 		    prog->expected_attach_type == BPF_TRACE_RAW_TP)
1801 			return &bpf_get_attach_cookie_proto_tracing;
1802 		return bpf_prog_has_trampoline(prog) ? &bpf_get_attach_cookie_proto_tracing : NULL;
1803 	default:
1804 		fn = raw_tp_prog_func_proto(func_id, prog);
1805 		if (!fn && prog->expected_attach_type == BPF_TRACE_ITER)
1806 			fn = bpf_iter_get_func_proto(func_id, prog);
1807 		return fn;
1808 	}
1809 }
1810 
1811 static bool raw_tp_prog_is_valid_access(int off, int size,
1812 					enum bpf_access_type type,
1813 					const struct bpf_prog *prog,
1814 					struct bpf_insn_access_aux *info)
1815 {
1816 	return bpf_tracing_ctx_access(off, size, type);
1817 }
1818 
1819 static bool tracing_prog_is_valid_access(int off, int size,
1820 					 enum bpf_access_type type,
1821 					 const struct bpf_prog *prog,
1822 					 struct bpf_insn_access_aux *info)
1823 {
1824 	return bpf_tracing_btf_ctx_access(off, size, type, prog, info);
1825 }
1826 
1827 int __weak bpf_prog_test_run_tracing(struct bpf_prog *prog,
1828 				     const union bpf_attr *kattr,
1829 				     union bpf_attr __user *uattr)
1830 {
1831 	return -ENOTSUPP;
1832 }
1833 
1834 const struct bpf_verifier_ops raw_tracepoint_verifier_ops = {
1835 	.get_func_proto  = raw_tp_prog_func_proto,
1836 	.is_valid_access = raw_tp_prog_is_valid_access,
1837 };
1838 
1839 const struct bpf_prog_ops raw_tracepoint_prog_ops = {
1840 #ifdef CONFIG_NET
1841 	.test_run = bpf_prog_test_run_raw_tp,
1842 #endif
1843 };
1844 
1845 const struct bpf_verifier_ops tracing_verifier_ops = {
1846 	.get_func_proto  = tracing_prog_func_proto,
1847 	.is_valid_access = tracing_prog_is_valid_access,
1848 };
1849 
1850 const struct bpf_prog_ops tracing_prog_ops = {
1851 	.test_run = bpf_prog_test_run_tracing,
1852 };
1853 
1854 static bool raw_tp_writable_prog_is_valid_access(int off, int size,
1855 						 enum bpf_access_type type,
1856 						 const struct bpf_prog *prog,
1857 						 struct bpf_insn_access_aux *info)
1858 {
1859 	if (off == 0) {
1860 		if (size != sizeof(u64) || type != BPF_READ)
1861 			return false;
1862 		info->reg_type = PTR_TO_TP_BUFFER;
1863 	}
1864 	return raw_tp_prog_is_valid_access(off, size, type, prog, info);
1865 }
1866 
1867 const struct bpf_verifier_ops raw_tracepoint_writable_verifier_ops = {
1868 	.get_func_proto  = raw_tp_prog_func_proto,
1869 	.is_valid_access = raw_tp_writable_prog_is_valid_access,
1870 };
1871 
1872 const struct bpf_prog_ops raw_tracepoint_writable_prog_ops = {
1873 };
1874 
1875 static bool pe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1876 				    const struct bpf_prog *prog,
1877 				    struct bpf_insn_access_aux *info)
1878 {
1879 	const int size_u64 = sizeof(u64);
1880 
1881 	if (off < 0 || off >= sizeof(struct bpf_perf_event_data))
1882 		return false;
1883 	if (type != BPF_READ)
1884 		return false;
1885 	if (off % size != 0) {
1886 		if (sizeof(unsigned long) != 4)
1887 			return false;
1888 		if (size != 8)
1889 			return false;
1890 		if (off % size != 4)
1891 			return false;
1892 	}
1893 
1894 	switch (off) {
1895 	case bpf_ctx_range(struct bpf_perf_event_data, sample_period):
1896 		bpf_ctx_record_field_size(info, size_u64);
1897 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
1898 			return false;
1899 		break;
1900 	case bpf_ctx_range(struct bpf_perf_event_data, addr):
1901 		bpf_ctx_record_field_size(info, size_u64);
1902 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
1903 			return false;
1904 		break;
1905 	default:
1906 		if (size != sizeof(long))
1907 			return false;
1908 	}
1909 
1910 	return true;
1911 }
1912 
1913 static u32 pe_prog_convert_ctx_access(enum bpf_access_type type,
1914 				      const struct bpf_insn *si,
1915 				      struct bpf_insn *insn_buf,
1916 				      struct bpf_prog *prog, u32 *target_size)
1917 {
1918 	struct bpf_insn *insn = insn_buf;
1919 
1920 	switch (si->off) {
1921 	case offsetof(struct bpf_perf_event_data, sample_period):
1922 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1923 						       data), si->dst_reg, si->src_reg,
1924 				      offsetof(struct bpf_perf_event_data_kern, data));
1925 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
1926 				      bpf_target_off(struct perf_sample_data, period, 8,
1927 						     target_size));
1928 		break;
1929 	case offsetof(struct bpf_perf_event_data, addr):
1930 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1931 						       data), si->dst_reg, si->src_reg,
1932 				      offsetof(struct bpf_perf_event_data_kern, data));
1933 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
1934 				      bpf_target_off(struct perf_sample_data, addr, 8,
1935 						     target_size));
1936 		break;
1937 	default:
1938 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1939 						       regs), si->dst_reg, si->src_reg,
1940 				      offsetof(struct bpf_perf_event_data_kern, regs));
1941 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(long), si->dst_reg, si->dst_reg,
1942 				      si->off);
1943 		break;
1944 	}
1945 
1946 	return insn - insn_buf;
1947 }
1948 
1949 const struct bpf_verifier_ops perf_event_verifier_ops = {
1950 	.get_func_proto		= pe_prog_func_proto,
1951 	.is_valid_access	= pe_prog_is_valid_access,
1952 	.convert_ctx_access	= pe_prog_convert_ctx_access,
1953 };
1954 
1955 const struct bpf_prog_ops perf_event_prog_ops = {
1956 };
1957 
1958 static DEFINE_MUTEX(bpf_event_mutex);
1959 
1960 #define BPF_TRACE_MAX_PROGS 64
1961 
1962 int perf_event_attach_bpf_prog(struct perf_event *event,
1963 			       struct bpf_prog *prog,
1964 			       u64 bpf_cookie)
1965 {
1966 	struct bpf_prog_array *old_array;
1967 	struct bpf_prog_array *new_array;
1968 	int ret = -EEXIST;
1969 
1970 	/*
1971 	 * Kprobe override only works if they are on the function entry,
1972 	 * and only if they are on the opt-in list.
1973 	 */
1974 	if (prog->kprobe_override &&
1975 	    (!trace_kprobe_on_func_entry(event->tp_event) ||
1976 	     !trace_kprobe_error_injectable(event->tp_event)))
1977 		return -EINVAL;
1978 
1979 	mutex_lock(&bpf_event_mutex);
1980 
1981 	if (event->prog)
1982 		goto unlock;
1983 
1984 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
1985 	if (old_array &&
1986 	    bpf_prog_array_length(old_array) >= BPF_TRACE_MAX_PROGS) {
1987 		ret = -E2BIG;
1988 		goto unlock;
1989 	}
1990 
1991 	ret = bpf_prog_array_copy(old_array, NULL, prog, bpf_cookie, &new_array);
1992 	if (ret < 0)
1993 		goto unlock;
1994 
1995 	/* set the new array to event->tp_event and set event->prog */
1996 	event->prog = prog;
1997 	event->bpf_cookie = bpf_cookie;
1998 	rcu_assign_pointer(event->tp_event->prog_array, new_array);
1999 	bpf_prog_array_free_sleepable(old_array);
2000 
2001 unlock:
2002 	mutex_unlock(&bpf_event_mutex);
2003 	return ret;
2004 }
2005 
2006 void perf_event_detach_bpf_prog(struct perf_event *event)
2007 {
2008 	struct bpf_prog_array *old_array;
2009 	struct bpf_prog_array *new_array;
2010 	struct bpf_prog *prog = NULL;
2011 	int ret;
2012 
2013 	mutex_lock(&bpf_event_mutex);
2014 
2015 	if (!event->prog)
2016 		goto unlock;
2017 
2018 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
2019 	if (!old_array)
2020 		goto put;
2021 
2022 	ret = bpf_prog_array_copy(old_array, event->prog, NULL, 0, &new_array);
2023 	if (ret < 0) {
2024 		bpf_prog_array_delete_safe(old_array, event->prog);
2025 	} else {
2026 		rcu_assign_pointer(event->tp_event->prog_array, new_array);
2027 		bpf_prog_array_free_sleepable(old_array);
2028 	}
2029 
2030 put:
2031 	prog = event->prog;
2032 	event->prog = NULL;
2033 
2034 unlock:
2035 	mutex_unlock(&bpf_event_mutex);
2036 
2037 	if (prog) {
2038 		/*
2039 		 * It could be that the bpf_prog is not sleepable (and will be freed
2040 		 * via normal RCU), but is called from a point that supports sleepable
2041 		 * programs and uses tasks-trace-RCU.
2042 		 */
2043 		synchronize_rcu_tasks_trace();
2044 
2045 		bpf_prog_put(prog);
2046 	}
2047 }
2048 
2049 int perf_event_query_prog_array(struct perf_event *event, void __user *info)
2050 {
2051 	struct perf_event_query_bpf __user *uquery = info;
2052 	struct perf_event_query_bpf query = {};
2053 	struct bpf_prog_array *progs;
2054 	u32 *ids, prog_cnt, ids_len;
2055 	int ret;
2056 
2057 	if (!perfmon_capable())
2058 		return -EPERM;
2059 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
2060 		return -EINVAL;
2061 	if (copy_from_user(&query, uquery, sizeof(query)))
2062 		return -EFAULT;
2063 
2064 	ids_len = query.ids_len;
2065 	if (ids_len > BPF_TRACE_MAX_PROGS)
2066 		return -E2BIG;
2067 	ids = kcalloc(ids_len, sizeof(u32), GFP_USER | __GFP_NOWARN);
2068 	if (!ids)
2069 		return -ENOMEM;
2070 	/*
2071 	 * The above kcalloc returns ZERO_SIZE_PTR when ids_len = 0, which
2072 	 * is required when user only wants to check for uquery->prog_cnt.
2073 	 * There is no need to check for it since the case is handled
2074 	 * gracefully in bpf_prog_array_copy_info.
2075 	 */
2076 
2077 	mutex_lock(&bpf_event_mutex);
2078 	progs = bpf_event_rcu_dereference(event->tp_event->prog_array);
2079 	ret = bpf_prog_array_copy_info(progs, ids, ids_len, &prog_cnt);
2080 	mutex_unlock(&bpf_event_mutex);
2081 
2082 	if (copy_to_user(&uquery->prog_cnt, &prog_cnt, sizeof(prog_cnt)) ||
2083 	    copy_to_user(uquery->ids, ids, ids_len * sizeof(u32)))
2084 		ret = -EFAULT;
2085 
2086 	kfree(ids);
2087 	return ret;
2088 }
2089 
2090 extern struct bpf_raw_event_map __start__bpf_raw_tp[];
2091 extern struct bpf_raw_event_map __stop__bpf_raw_tp[];
2092 
2093 struct bpf_raw_event_map *bpf_get_raw_tracepoint(const char *name)
2094 {
2095 	struct bpf_raw_event_map *btp = __start__bpf_raw_tp;
2096 
2097 	for (; btp < __stop__bpf_raw_tp; btp++) {
2098 		if (!strcmp(btp->tp->name, name))
2099 			return btp;
2100 	}
2101 
2102 	return bpf_get_raw_tracepoint_module(name);
2103 }
2104 
2105 void bpf_put_raw_tracepoint(struct bpf_raw_event_map *btp)
2106 {
2107 	struct module *mod;
2108 
2109 	guard(rcu)();
2110 	mod = __module_address((unsigned long)btp);
2111 	module_put(mod);
2112 }
2113 
2114 static __always_inline
2115 void __bpf_trace_run(struct bpf_raw_tp_link *link, u64 *args)
2116 {
2117 	struct srcu_ctr __percpu *scp = NULL;
2118 	struct bpf_prog *prog = link->link.prog;
2119 	bool sleepable = prog->sleepable;
2120 	struct bpf_run_ctx *old_run_ctx;
2121 	struct bpf_trace_run_ctx run_ctx;
2122 
2123 	if (sleepable) {
2124 		scp = rcu_read_lock_tasks_trace();
2125 		migrate_disable();
2126 	} else {
2127 		rcu_read_lock_dont_migrate();
2128 	}
2129 
2130 	if (unlikely(!bpf_prog_get_recursion_context(prog))) {
2131 		bpf_prog_inc_misses_counter(prog);
2132 		goto out;
2133 	}
2134 
2135 	run_ctx.bpf_cookie = link->cookie;
2136 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
2137 
2138 	(void)bpf_prog_run(prog, args);
2139 
2140 	bpf_reset_run_ctx(old_run_ctx);
2141 out:
2142 	bpf_prog_put_recursion_context(prog);
2143 
2144 	if (sleepable) {
2145 		migrate_enable();
2146 		rcu_read_unlock_tasks_trace(scp);
2147 	} else {
2148 		rcu_read_unlock_migrate();
2149 	}
2150 }
2151 
2152 #define UNPACK(...)			__VA_ARGS__
2153 #define REPEAT_1(FN, DL, X, ...)	FN(X)
2154 #define REPEAT_2(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_1(FN, DL, __VA_ARGS__)
2155 #define REPEAT_3(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_2(FN, DL, __VA_ARGS__)
2156 #define REPEAT_4(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_3(FN, DL, __VA_ARGS__)
2157 #define REPEAT_5(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_4(FN, DL, __VA_ARGS__)
2158 #define REPEAT_6(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_5(FN, DL, __VA_ARGS__)
2159 #define REPEAT_7(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_6(FN, DL, __VA_ARGS__)
2160 #define REPEAT_8(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_7(FN, DL, __VA_ARGS__)
2161 #define REPEAT_9(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_8(FN, DL, __VA_ARGS__)
2162 #define REPEAT_10(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_9(FN, DL, __VA_ARGS__)
2163 #define REPEAT_11(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_10(FN, DL, __VA_ARGS__)
2164 #define REPEAT_12(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_11(FN, DL, __VA_ARGS__)
2165 #define REPEAT(X, FN, DL, ...)		REPEAT_##X(FN, DL, __VA_ARGS__)
2166 
2167 #define SARG(X)		u64 arg##X
2168 #define COPY(X)		args[X] = arg##X
2169 
2170 #define __DL_COM	(,)
2171 #define __DL_SEM	(;)
2172 
2173 #define __SEQ_0_11	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
2174 
2175 #define BPF_TRACE_DEFN_x(x)						\
2176 	void bpf_trace_run##x(struct bpf_raw_tp_link *link,		\
2177 			      REPEAT(x, SARG, __DL_COM, __SEQ_0_11))	\
2178 	{								\
2179 		u64 args[x];						\
2180 		REPEAT(x, COPY, __DL_SEM, __SEQ_0_11);			\
2181 		__bpf_trace_run(link, args);				\
2182 	}								\
2183 	EXPORT_SYMBOL_GPL(bpf_trace_run##x)
2184 BPF_TRACE_DEFN_x(1);
2185 BPF_TRACE_DEFN_x(2);
2186 BPF_TRACE_DEFN_x(3);
2187 BPF_TRACE_DEFN_x(4);
2188 BPF_TRACE_DEFN_x(5);
2189 BPF_TRACE_DEFN_x(6);
2190 BPF_TRACE_DEFN_x(7);
2191 BPF_TRACE_DEFN_x(8);
2192 BPF_TRACE_DEFN_x(9);
2193 BPF_TRACE_DEFN_x(10);
2194 BPF_TRACE_DEFN_x(11);
2195 BPF_TRACE_DEFN_x(12);
2196 
2197 int bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_raw_tp_link *link)
2198 {
2199 	struct tracepoint *tp = btp->tp;
2200 	struct bpf_prog *prog = link->link.prog;
2201 
2202 	/*
2203 	 * check that program doesn't access arguments beyond what's
2204 	 * available in this tracepoint
2205 	 */
2206 	if (prog->aux->max_ctx_offset > btp->num_args * sizeof(u64))
2207 		return -EINVAL;
2208 
2209 	if (prog->aux->max_tp_access > btp->writable_size)
2210 		return -EINVAL;
2211 
2212 	return tracepoint_probe_register_may_exist(tp, (void *)btp->bpf_func, link);
2213 }
2214 
2215 int bpf_probe_unregister(struct bpf_raw_event_map *btp, struct bpf_raw_tp_link *link)
2216 {
2217 	return tracepoint_probe_unregister(btp->tp, (void *)btp->bpf_func, link);
2218 }
2219 
2220 /* On success the caller releases *buf with kfree_const() */
2221 int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id,
2222 			    u32 *fd_type, const char **buf,
2223 			    u64 *probe_offset, u64 *probe_addr,
2224 			    unsigned long *missed)
2225 {
2226 	bool is_tracepoint, is_syscall_tp;
2227 	struct bpf_prog *prog;
2228 	int flags, err = 0;
2229 
2230 	/*
2231 	 * The list of dynamic events is walked, and a probe which has siblings
2232 	 * can be deleted, with its strings, while its event is in use.
2233 	 */
2234 	guard(mutex)(&event_mutex);
2235 
2236 	prog = event->prog;
2237 	if (!prog)
2238 		return -ENOENT;
2239 
2240 	/* not supporting BPF_PROG_TYPE_PERF_EVENT yet */
2241 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT)
2242 		return -EOPNOTSUPP;
2243 
2244 	*prog_id = prog->aux->id;
2245 	flags = event->tp_event->flags;
2246 	is_tracepoint = flags & TRACE_EVENT_FL_TRACEPOINT;
2247 	is_syscall_tp = is_syscall_trace_event(event->tp_event);
2248 
2249 	if (is_tracepoint || is_syscall_tp) {
2250 		*buf = is_tracepoint ? event->tp_event->tp->name
2251 				     : event->tp_event->name;
2252 		/* We allow NULL pointer for tracepoint */
2253 		if (fd_type)
2254 			*fd_type = BPF_FD_TYPE_TRACEPOINT;
2255 		if (probe_offset)
2256 			*probe_offset = 0x0;
2257 		if (probe_addr)
2258 			*probe_addr = 0x0;
2259 	} else {
2260 		/* kprobe/uprobe */
2261 		err = -EOPNOTSUPP;
2262 #ifdef CONFIG_KPROBE_EVENTS
2263 		if (flags & TRACE_EVENT_FL_KPROBE)
2264 			err = bpf_get_kprobe_info(event, fd_type, buf,
2265 						  probe_offset, probe_addr, missed,
2266 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2267 #endif
2268 #ifdef CONFIG_UPROBE_EVENTS
2269 		if (flags & TRACE_EVENT_FL_UPROBE)
2270 			err = bpf_get_uprobe_info(event, fd_type, buf,
2271 						  probe_offset, probe_addr,
2272 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2273 #endif
2274 	}
2275 
2276 	if (!err && *buf) {
2277 		*buf = kstrdup_const(*buf, GFP_KERNEL);
2278 		if (!*buf)
2279 			err = -ENOMEM;
2280 	}
2281 
2282 	return err;
2283 }
2284 
2285 static int __init send_signal_irq_work_init(void)
2286 {
2287 	int cpu;
2288 	struct send_signal_irq_work *work;
2289 
2290 	for_each_possible_cpu(cpu) {
2291 		work = per_cpu_ptr(&send_signal_work, cpu);
2292 		init_irq_work(&work->irq_work, do_bpf_send_signal);
2293 	}
2294 	return 0;
2295 }
2296 
2297 subsys_initcall(send_signal_irq_work_init);
2298 
2299 #ifdef CONFIG_MODULES
2300 static int bpf_event_notify(struct notifier_block *nb, unsigned long op,
2301 			    void *module)
2302 {
2303 	struct bpf_trace_module *btm, *tmp;
2304 	struct module *mod = module;
2305 	int ret = 0;
2306 
2307 	if (mod->num_bpf_raw_events == 0 ||
2308 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
2309 		goto out;
2310 
2311 	mutex_lock(&bpf_module_mutex);
2312 
2313 	switch (op) {
2314 	case MODULE_STATE_COMING:
2315 		btm = kzalloc_obj(*btm);
2316 		if (btm) {
2317 			btm->module = module;
2318 			list_add(&btm->list, &bpf_trace_modules);
2319 		} else {
2320 			ret = -ENOMEM;
2321 		}
2322 		break;
2323 	case MODULE_STATE_GOING:
2324 		list_for_each_entry_safe(btm, tmp, &bpf_trace_modules, list) {
2325 			if (btm->module == module) {
2326 				list_del(&btm->list);
2327 				kfree(btm);
2328 				break;
2329 			}
2330 		}
2331 		break;
2332 	}
2333 
2334 	mutex_unlock(&bpf_module_mutex);
2335 
2336 out:
2337 	return notifier_from_errno(ret);
2338 }
2339 
2340 static struct notifier_block bpf_module_nb = {
2341 	.notifier_call = bpf_event_notify,
2342 };
2343 
2344 static int __init bpf_event_init(void)
2345 {
2346 	register_module_notifier(&bpf_module_nb);
2347 	return 0;
2348 }
2349 
2350 fs_initcall(bpf_event_init);
2351 #endif /* CONFIG_MODULES */
2352 
2353 struct bpf_session_run_ctx {
2354 	struct bpf_run_ctx run_ctx;
2355 	bool is_return;
2356 	void *data;
2357 };
2358 
2359 #ifdef CONFIG_FPROBE
2360 struct bpf_kprobe_multi_link {
2361 	struct bpf_link link;
2362 	struct fprobe fp;
2363 	unsigned long *addrs;
2364 	u64 *cookies;
2365 	u32 cnt;
2366 	u32 mods_cnt;
2367 	struct module **mods;
2368 };
2369 
2370 struct bpf_kprobe_multi_run_ctx {
2371 	struct bpf_session_run_ctx session_ctx;
2372 	struct bpf_kprobe_multi_link *link;
2373 	unsigned long entry_ip;
2374 };
2375 
2376 struct user_syms {
2377 	const char **syms;
2378 	char *buf;
2379 };
2380 
2381 #ifndef CONFIG_HAVE_FTRACE_REGS_HAVING_PT_REGS
2382 static DEFINE_PER_CPU(struct pt_regs, bpf_kprobe_multi_pt_regs);
2383 #define bpf_kprobe_multi_pt_regs_ptr()	this_cpu_ptr(&bpf_kprobe_multi_pt_regs)
2384 #else
2385 #define bpf_kprobe_multi_pt_regs_ptr()	(NULL)
2386 #endif
2387 
2388 static unsigned long ftrace_get_entry_ip(unsigned long fentry_ip)
2389 {
2390 	unsigned long ip = ftrace_get_symaddr(fentry_ip);
2391 
2392 	return ip ? : fentry_ip;
2393 }
2394 
2395 static int copy_user_syms(struct user_syms *us, unsigned long __user *usyms, u32 cnt)
2396 {
2397 	unsigned long __user usymbol;
2398 	const char **syms = NULL;
2399 	char *buf = NULL, *p;
2400 	int err = -ENOMEM;
2401 	unsigned int i;
2402 
2403 	if (!access_ok(usyms, cnt * sizeof(*usyms)))
2404 		return -EFAULT;
2405 
2406 	syms = kvmalloc_array(cnt, sizeof(*syms), GFP_KERNEL);
2407 	if (!syms)
2408 		return -ENOMEM;
2409 
2410 	buf = kvmalloc_array(cnt, KSYM_NAME_LEN, GFP_KERNEL);
2411 	if (!buf)
2412 		goto error;
2413 
2414 	for (p = buf, i = 0; i < cnt; i++) {
2415 		if (get_user(usymbol, usyms + i)) {
2416 			err = -EFAULT;
2417 			goto error;
2418 		}
2419 		err = strncpy_from_user(p, (const char __user *) usymbol, KSYM_NAME_LEN);
2420 		if (err == KSYM_NAME_LEN)
2421 			err = -E2BIG;
2422 		if (err < 0)
2423 			goto error;
2424 		syms[i] = p;
2425 		p += err + 1;
2426 	}
2427 
2428 	us->syms = syms;
2429 	us->buf = buf;
2430 	return 0;
2431 
2432 error:
2433 	kvfree(syms);
2434 	kvfree(buf);
2435 	return err;
2436 }
2437 
2438 static void kprobe_multi_put_modules(struct module **mods, u32 cnt)
2439 {
2440 	u32 i;
2441 
2442 	for (i = 0; i < cnt; i++)
2443 		module_put(mods[i]);
2444 }
2445 
2446 static void free_user_syms(struct user_syms *us)
2447 {
2448 	kvfree(us->syms);
2449 	kvfree(us->buf);
2450 }
2451 
2452 static void bpf_kprobe_multi_link_release(struct bpf_link *link)
2453 {
2454 	struct bpf_kprobe_multi_link *kmulti_link;
2455 
2456 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2457 	/* Don't wait for RCU GP here. */
2458 	unregister_fprobe_async(&kmulti_link->fp);
2459 	kprobe_multi_put_modules(kmulti_link->mods, kmulti_link->mods_cnt);
2460 }
2461 
2462 static void bpf_kprobe_multi_link_dealloc(struct bpf_link *link)
2463 {
2464 	struct bpf_kprobe_multi_link *kmulti_link;
2465 
2466 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2467 	kvfree(kmulti_link->addrs);
2468 	kvfree(kmulti_link->cookies);
2469 	kfree(kmulti_link->mods);
2470 	kfree(kmulti_link);
2471 }
2472 
2473 static int bpf_kprobe_multi_link_fill_link_info(const struct bpf_link *link,
2474 						struct bpf_link_info *info)
2475 {
2476 	u64 __user *ucookies = u64_to_user_ptr(info->kprobe_multi.cookies);
2477 	u64 __user *uaddrs = u64_to_user_ptr(info->kprobe_multi.addrs);
2478 	struct bpf_kprobe_multi_link *kmulti_link;
2479 	u32 ucount = info->kprobe_multi.count;
2480 	int err = 0, i;
2481 
2482 	if (!uaddrs ^ !ucount)
2483 		return -EINVAL;
2484 	if (ucookies && !ucount)
2485 		return -EINVAL;
2486 
2487 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2488 	info->kprobe_multi.count = kmulti_link->cnt;
2489 	info->kprobe_multi.flags = kmulti_link->link.flags;
2490 	info->kprobe_multi.missed = kmulti_link->fp.nmissed;
2491 
2492 	if (!uaddrs)
2493 		return 0;
2494 	if (ucount < kmulti_link->cnt)
2495 		err = -ENOSPC;
2496 	else
2497 		ucount = kmulti_link->cnt;
2498 
2499 	if (ucookies) {
2500 		if (kmulti_link->cookies) {
2501 			if (copy_to_user(ucookies, kmulti_link->cookies, ucount * sizeof(u64)))
2502 				return -EFAULT;
2503 		} else {
2504 			for (i = 0; i < ucount; i++) {
2505 				if (put_user(0, ucookies + i))
2506 					return -EFAULT;
2507 			}
2508 		}
2509 	}
2510 
2511 	if (kallsyms_show_value(current_cred())) {
2512 		if (copy_to_user(uaddrs, kmulti_link->addrs, ucount * sizeof(u64)))
2513 			return -EFAULT;
2514 	} else {
2515 		for (i = 0; i < ucount; i++) {
2516 			if (put_user(0, uaddrs + i))
2517 				return -EFAULT;
2518 		}
2519 	}
2520 	return err;
2521 }
2522 
2523 #ifdef CONFIG_PROC_FS
2524 static void bpf_kprobe_multi_show_fdinfo(const struct bpf_link *link,
2525 					 struct seq_file *seq)
2526 {
2527 	struct bpf_kprobe_multi_link *kmulti_link;
2528 	bool has_cookies;
2529 
2530 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2531 	has_cookies = !!kmulti_link->cookies;
2532 
2533 	seq_printf(seq,
2534 		   "kprobe_cnt:\t%u\n"
2535 		   "missed:\t%lu\n",
2536 		   kmulti_link->cnt,
2537 		   kmulti_link->fp.nmissed);
2538 
2539 	seq_printf(seq, "%s\t %s\n", "cookie", "func");
2540 	for (int i = 0; i < kmulti_link->cnt; i++) {
2541 		seq_printf(seq,
2542 			   "%llu\t %pS\n",
2543 			   has_cookies ? kmulti_link->cookies[i] : 0,
2544 			   (void *)kmulti_link->addrs[i]);
2545 	}
2546 }
2547 #endif
2548 
2549 static const struct bpf_link_ops bpf_kprobe_multi_link_lops = {
2550 	.release = bpf_kprobe_multi_link_release,
2551 	.dealloc_deferred = bpf_kprobe_multi_link_dealloc,
2552 	.fill_link_info = bpf_kprobe_multi_link_fill_link_info,
2553 #ifdef CONFIG_PROC_FS
2554 	.show_fdinfo = bpf_kprobe_multi_show_fdinfo,
2555 #endif
2556 };
2557 
2558 static void bpf_kprobe_multi_cookie_swap(void *a, void *b, int size, const void *priv)
2559 {
2560 	const struct bpf_kprobe_multi_link *link = priv;
2561 	unsigned long *addr_a = a, *addr_b = b;
2562 	u64 *cookie_a, *cookie_b;
2563 
2564 	cookie_a = link->cookies + (addr_a - link->addrs);
2565 	cookie_b = link->cookies + (addr_b - link->addrs);
2566 
2567 	/* swap addr_a/addr_b and cookie_a/cookie_b values */
2568 	swap(*addr_a, *addr_b);
2569 	swap(*cookie_a, *cookie_b);
2570 }
2571 
2572 static int bpf_kprobe_multi_addrs_cmp(const void *a, const void *b)
2573 {
2574 	const unsigned long *addr_a = a, *addr_b = b;
2575 
2576 	if (*addr_a == *addr_b)
2577 		return 0;
2578 	return *addr_a < *addr_b ? -1 : 1;
2579 }
2580 
2581 static int bpf_kprobe_multi_cookie_cmp(const void *a, const void *b, const void *priv)
2582 {
2583 	return bpf_kprobe_multi_addrs_cmp(a, b);
2584 }
2585 
2586 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx)
2587 {
2588 	struct bpf_kprobe_multi_run_ctx *run_ctx;
2589 	struct bpf_kprobe_multi_link *link;
2590 	u64 *cookie, entry_ip;
2591 	unsigned long *addr;
2592 
2593 	if (WARN_ON_ONCE(!ctx))
2594 		return 0;
2595 	run_ctx = container_of(current->bpf_ctx, struct bpf_kprobe_multi_run_ctx,
2596 			       session_ctx.run_ctx);
2597 	link = run_ctx->link;
2598 	if (!link->cookies)
2599 		return 0;
2600 	entry_ip = run_ctx->entry_ip;
2601 	addr = bsearch(&entry_ip, link->addrs, link->cnt, sizeof(entry_ip),
2602 		       bpf_kprobe_multi_addrs_cmp);
2603 	if (!addr)
2604 		return 0;
2605 	cookie = link->cookies + (addr - link->addrs);
2606 	return *cookie;
2607 }
2608 
2609 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
2610 {
2611 	struct bpf_kprobe_multi_run_ctx *run_ctx;
2612 
2613 	run_ctx = container_of(current->bpf_ctx, struct bpf_kprobe_multi_run_ctx,
2614 			       session_ctx.run_ctx);
2615 	return run_ctx->entry_ip;
2616 }
2617 
2618 static __always_inline int
2619 kprobe_multi_link_prog_run(struct bpf_kprobe_multi_link *link,
2620 			   unsigned long entry_ip, struct ftrace_regs *fregs,
2621 			   bool is_return, void *data)
2622 {
2623 	struct bpf_kprobe_multi_run_ctx run_ctx = {
2624 		.session_ctx = {
2625 			.is_return = is_return,
2626 			.data = data,
2627 		},
2628 		.link = link,
2629 		.entry_ip = entry_ip,
2630 	};
2631 	struct bpf_run_ctx *old_run_ctx;
2632 	struct pt_regs *regs;
2633 	int err;
2634 
2635 	/*
2636 	 * graph tracer framework ensures we won't migrate, so there is no need
2637 	 * to use migrate_disable for bpf_prog_run again. The check here just for
2638 	 * __this_cpu_inc_return.
2639 	 */
2640 	cant_sleep();
2641 
2642 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
2643 		bpf_prog_inc_misses_counter(link->link.prog);
2644 		err = 1;
2645 		goto out;
2646 	}
2647 
2648 	rcu_read_lock();
2649 	regs = ftrace_partial_regs(fregs, bpf_kprobe_multi_pt_regs_ptr());
2650 	old_run_ctx = bpf_set_run_ctx(&run_ctx.session_ctx.run_ctx);
2651 	err = bpf_prog_run(link->link.prog, regs);
2652 	bpf_reset_run_ctx(old_run_ctx);
2653 	ftrace_partial_regs_update(fregs, bpf_kprobe_multi_pt_regs_ptr());
2654 	rcu_read_unlock();
2655 
2656  out:
2657 	__this_cpu_dec(bpf_prog_active);
2658 	return err;
2659 }
2660 
2661 static int
2662 kprobe_multi_link_handler(struct fprobe *fp, unsigned long fentry_ip,
2663 			  unsigned long ret_ip, struct ftrace_regs *fregs,
2664 			  void *data)
2665 {
2666 	struct bpf_kprobe_multi_link *link;
2667 	int err;
2668 
2669 	link = container_of(fp, struct bpf_kprobe_multi_link, fp);
2670 	err = kprobe_multi_link_prog_run(link, ftrace_get_entry_ip(fentry_ip),
2671 					 fregs, false, data);
2672 	return is_kprobe_session(link->link.prog) ? err : 0;
2673 }
2674 
2675 static void
2676 kprobe_multi_link_exit_handler(struct fprobe *fp, unsigned long fentry_ip,
2677 			       unsigned long ret_ip, struct ftrace_regs *fregs,
2678 			       void *data)
2679 {
2680 	struct bpf_kprobe_multi_link *link;
2681 
2682 	link = container_of(fp, struct bpf_kprobe_multi_link, fp);
2683 	kprobe_multi_link_prog_run(link, ftrace_get_entry_ip(fentry_ip),
2684 				   fregs, true, data);
2685 }
2686 
2687 static int symbols_cmp_r(const void *a, const void *b, const void *priv)
2688 {
2689 	const char **str_a = (const char **) a;
2690 	const char **str_b = (const char **) b;
2691 
2692 	return strcmp(*str_a, *str_b);
2693 }
2694 
2695 struct multi_symbols_sort {
2696 	const char **funcs;
2697 	u64 *cookies;
2698 };
2699 
2700 static void symbols_swap_r(void *a, void *b, int size, const void *priv)
2701 {
2702 	const struct multi_symbols_sort *data = priv;
2703 	const char **name_a = a, **name_b = b;
2704 
2705 	swap(*name_a, *name_b);
2706 
2707 	/* If defined, swap also related cookies. */
2708 	if (data->cookies) {
2709 		u64 *cookie_a, *cookie_b;
2710 
2711 		cookie_a = data->cookies + (name_a - data->funcs);
2712 		cookie_b = data->cookies + (name_b - data->funcs);
2713 		swap(*cookie_a, *cookie_b);
2714 	}
2715 }
2716 
2717 struct modules_array {
2718 	struct module **mods;
2719 	int mods_cnt;
2720 	int mods_cap;
2721 };
2722 
2723 static int add_module(struct modules_array *arr, struct module *mod)
2724 {
2725 	struct module **mods;
2726 
2727 	if (arr->mods_cnt == arr->mods_cap) {
2728 		arr->mods_cap = max(16, arr->mods_cap * 3 / 2);
2729 		mods = krealloc_array(arr->mods, arr->mods_cap, sizeof(*mods), GFP_KERNEL);
2730 		if (!mods)
2731 			return -ENOMEM;
2732 		arr->mods = mods;
2733 	}
2734 
2735 	arr->mods[arr->mods_cnt] = mod;
2736 	arr->mods_cnt++;
2737 	return 0;
2738 }
2739 
2740 static bool has_module(struct modules_array *arr, struct module *mod)
2741 {
2742 	int i;
2743 
2744 	for (i = arr->mods_cnt - 1; i >= 0; i--) {
2745 		if (arr->mods[i] == mod)
2746 			return true;
2747 	}
2748 	return false;
2749 }
2750 
2751 static int get_modules_for_addrs(struct module ***mods, unsigned long *addrs, u32 addrs_cnt)
2752 {
2753 	struct modules_array arr = {};
2754 	u32 i, err = 0;
2755 
2756 	for (i = 0; i < addrs_cnt; i++) {
2757 		bool skip_add = false;
2758 		struct module *mod;
2759 
2760 		scoped_guard(rcu) {
2761 			mod = __module_address(addrs[i]);
2762 			/* Either no module or it's already stored  */
2763 			if (!mod || has_module(&arr, mod)) {
2764 				skip_add = true;
2765 				break; /* scoped_guard */
2766 			}
2767 			if (!try_module_get(mod))
2768 				err = -EINVAL;
2769 		}
2770 		if (skip_add)
2771 			continue;
2772 		if (err)
2773 			break;
2774 		err = add_module(&arr, mod);
2775 		if (err) {
2776 			module_put(mod);
2777 			break;
2778 		}
2779 	}
2780 
2781 	/* We return either err < 0 in case of error, ... */
2782 	if (err) {
2783 		kprobe_multi_put_modules(arr.mods, arr.mods_cnt);
2784 		kfree(arr.mods);
2785 		return err;
2786 	}
2787 
2788 	/* or number of modules found if everything is ok. */
2789 	*mods = arr.mods;
2790 	return arr.mods_cnt;
2791 }
2792 
2793 static int addrs_check_error_injection_list(unsigned long *addrs, u32 cnt)
2794 {
2795 	u32 i;
2796 
2797 	for (i = 0; i < cnt; i++) {
2798 		if (!within_error_injection_list(addrs[i]))
2799 			return -EINVAL;
2800 	}
2801 	return 0;
2802 }
2803 
2804 int bpf_kprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
2805 {
2806 	struct bpf_kprobe_multi_link *link = NULL;
2807 	struct bpf_link_primer link_primer;
2808 	void __user *ucookies;
2809 	unsigned long *addrs;
2810 	u32 flags, cnt, size;
2811 	void __user *uaddrs;
2812 	u64 *cookies = NULL;
2813 	void __user *usyms;
2814 	int err;
2815 
2816 	/* no support for 32bit archs yet */
2817 	if (sizeof(u64) != sizeof(void *))
2818 		return -EOPNOTSUPP;
2819 
2820 	if (attr->link_create.flags)
2821 		return -EINVAL;
2822 
2823 	if (!is_kprobe_multi(prog))
2824 		return -EINVAL;
2825 
2826 	/* kprobe_multi is not allowed to be sleepable. */
2827 	if (prog->sleepable)
2828 		return -EINVAL;
2829 
2830 	/* Writing to context is not allowed for kprobes. */
2831 	if (prog->aux->kprobe_write_ctx)
2832 		return -EINVAL;
2833 
2834 	flags = attr->link_create.kprobe_multi.flags;
2835 	if (flags & ~BPF_F_KPROBE_MULTI_RETURN)
2836 		return -EINVAL;
2837 
2838 	uaddrs = u64_to_user_ptr(attr->link_create.kprobe_multi.addrs);
2839 	usyms = u64_to_user_ptr(attr->link_create.kprobe_multi.syms);
2840 	if (!!uaddrs == !!usyms)
2841 		return -EINVAL;
2842 
2843 	cnt = attr->link_create.kprobe_multi.cnt;
2844 	if (!cnt)
2845 		return -EINVAL;
2846 	if (cnt > MAX_KPROBE_MULTI_CNT)
2847 		return -E2BIG;
2848 
2849 	size = cnt * sizeof(*addrs);
2850 	addrs = kvmalloc_array(cnt, sizeof(*addrs), GFP_KERNEL);
2851 	if (!addrs)
2852 		return -ENOMEM;
2853 
2854 	ucookies = u64_to_user_ptr(attr->link_create.kprobe_multi.cookies);
2855 	if (ucookies) {
2856 		cookies = kvmalloc_array(cnt, sizeof(*addrs), GFP_KERNEL);
2857 		if (!cookies) {
2858 			err = -ENOMEM;
2859 			goto error;
2860 		}
2861 		if (copy_from_user(cookies, ucookies, size)) {
2862 			err = -EFAULT;
2863 			goto error;
2864 		}
2865 	}
2866 
2867 	if (uaddrs) {
2868 		if (copy_from_user(addrs, uaddrs, size)) {
2869 			err = -EFAULT;
2870 			goto error;
2871 		}
2872 	} else {
2873 		struct multi_symbols_sort data = {
2874 			.cookies = cookies,
2875 		};
2876 		struct user_syms us;
2877 
2878 		err = copy_user_syms(&us, usyms, cnt);
2879 		if (err)
2880 			goto error;
2881 
2882 		if (cookies)
2883 			data.funcs = us.syms;
2884 
2885 		sort_r(us.syms, cnt, sizeof(*us.syms), symbols_cmp_r,
2886 		       symbols_swap_r, &data);
2887 
2888 		err = ftrace_lookup_symbols(us.syms, cnt, addrs);
2889 		free_user_syms(&us);
2890 		if (err)
2891 			goto error;
2892 	}
2893 
2894 	if (prog->kprobe_override && addrs_check_error_injection_list(addrs, cnt)) {
2895 		err = -EINVAL;
2896 		goto error;
2897 	}
2898 
2899 	link = kzalloc_obj(*link);
2900 	if (!link) {
2901 		err = -ENOMEM;
2902 		goto error;
2903 	}
2904 
2905 	bpf_link_init(&link->link, BPF_LINK_TYPE_KPROBE_MULTI,
2906 		      &bpf_kprobe_multi_link_lops, prog, attr->link_create.attach_type);
2907 
2908 	err = bpf_link_prime(&link->link, &link_primer);
2909 	if (err)
2910 		goto error;
2911 
2912 	if (!(flags & BPF_F_KPROBE_MULTI_RETURN))
2913 		link->fp.entry_handler = kprobe_multi_link_handler;
2914 	if ((flags & BPF_F_KPROBE_MULTI_RETURN) || is_kprobe_session(prog))
2915 		link->fp.exit_handler = kprobe_multi_link_exit_handler;
2916 	if (is_kprobe_session(prog))
2917 		link->fp.entry_data_size = sizeof(u64);
2918 
2919 	link->addrs = addrs;
2920 	link->cookies = cookies;
2921 	link->cnt = cnt;
2922 	link->link.flags = flags;
2923 
2924 	if (cookies) {
2925 		/*
2926 		 * Sorting addresses will trigger sorting cookies as well
2927 		 * (check bpf_kprobe_multi_cookie_swap). This way we can
2928 		 * find cookie based on the address in bpf_get_attach_cookie
2929 		 * helper.
2930 		 */
2931 		sort_r(addrs, cnt, sizeof(*addrs),
2932 		       bpf_kprobe_multi_cookie_cmp,
2933 		       bpf_kprobe_multi_cookie_swap,
2934 		       link);
2935 	}
2936 
2937 	err = get_modules_for_addrs(&link->mods, addrs, cnt);
2938 	if (err < 0) {
2939 		bpf_link_cleanup(&link_primer);
2940 		return err;
2941 	}
2942 	link->mods_cnt = err;
2943 
2944 	err = register_fprobe_ips(&link->fp, addrs, cnt);
2945 	if (err) {
2946 		kprobe_multi_put_modules(link->mods, link->mods_cnt);
2947 		bpf_link_cleanup(&link_primer);
2948 		return err;
2949 	}
2950 
2951 	return bpf_link_settle(&link_primer);
2952 
2953 error:
2954 	kfree(link);
2955 	kvfree(addrs);
2956 	kvfree(cookies);
2957 	return err;
2958 }
2959 #else /* !CONFIG_FPROBE */
2960 int bpf_kprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
2961 {
2962 	return -EOPNOTSUPP;
2963 }
2964 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx)
2965 {
2966 	return 0;
2967 }
2968 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
2969 {
2970 	return 0;
2971 }
2972 #endif
2973 
2974 #ifdef CONFIG_UPROBES
2975 struct bpf_uprobe_multi_link;
2976 
2977 struct bpf_uprobe {
2978 	struct bpf_uprobe_multi_link *link;
2979 	loff_t offset;
2980 	unsigned long ref_ctr_offset;
2981 	u64 cookie;
2982 	struct uprobe *uprobe;
2983 	struct uprobe_consumer consumer;
2984 	bool session;
2985 };
2986 
2987 struct bpf_uprobe_multi_link {
2988 	struct path path;
2989 	struct bpf_link link;
2990 	u32 cnt;
2991 	struct bpf_uprobe *uprobes;
2992 	struct task_struct *task;
2993 };
2994 
2995 struct bpf_uprobe_multi_run_ctx {
2996 	struct bpf_session_run_ctx session_ctx;
2997 	unsigned long entry_ip;
2998 	struct bpf_uprobe *uprobe;
2999 };
3000 
3001 static void bpf_uprobe_unregister(struct bpf_uprobe *uprobes, u32 cnt)
3002 {
3003 	u32 i;
3004 
3005 	for (i = 0; i < cnt; i++)
3006 		uprobe_unregister_nosync(uprobes[i].uprobe, &uprobes[i].consumer);
3007 
3008 	if (cnt)
3009 		uprobe_unregister_sync();
3010 }
3011 
3012 static void bpf_uprobe_multi_link_release(struct bpf_link *link)
3013 {
3014 	struct bpf_uprobe_multi_link *umulti_link;
3015 
3016 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3017 	bpf_uprobe_unregister(umulti_link->uprobes, umulti_link->cnt);
3018 	if (umulti_link->task)
3019 		put_task_struct(umulti_link->task);
3020 	path_put(&umulti_link->path);
3021 }
3022 
3023 static void bpf_uprobe_multi_link_dealloc(struct bpf_link *link)
3024 {
3025 	struct bpf_uprobe_multi_link *umulti_link;
3026 
3027 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3028 	kvfree(umulti_link->uprobes);
3029 	kfree(umulti_link);
3030 }
3031 
3032 static int bpf_uprobe_multi_link_fill_link_info(const struct bpf_link *link,
3033 						struct bpf_link_info *info)
3034 {
3035 	u64 __user *uref_ctr_offsets = u64_to_user_ptr(info->uprobe_multi.ref_ctr_offsets);
3036 	u64 __user *ucookies = u64_to_user_ptr(info->uprobe_multi.cookies);
3037 	u64 __user *uoffsets = u64_to_user_ptr(info->uprobe_multi.offsets);
3038 	u64 __user *upath = u64_to_user_ptr(info->uprobe_multi.path);
3039 	u32 upath_size = info->uprobe_multi.path_size;
3040 	struct bpf_uprobe_multi_link *umulti_link;
3041 	u32 ucount = info->uprobe_multi.count;
3042 	int err = 0, i;
3043 	char *p, *buf;
3044 	long left = 0;
3045 
3046 	if (!upath ^ !upath_size)
3047 		return -EINVAL;
3048 
3049 	if ((uoffsets || uref_ctr_offsets || ucookies) && !ucount)
3050 		return -EINVAL;
3051 
3052 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3053 	info->uprobe_multi.count = umulti_link->cnt;
3054 	info->uprobe_multi.flags = umulti_link->link.flags;
3055 	info->uprobe_multi.pid = umulti_link->task ?
3056 				 task_pid_nr_ns(umulti_link->task, task_active_pid_ns(current)) : 0;
3057 
3058 	upath_size = upath_size ? min_t(u32, upath_size, PATH_MAX) : PATH_MAX;
3059 	buf = kmalloc(upath_size, GFP_KERNEL);
3060 	if (!buf)
3061 		return -ENOMEM;
3062 	p = d_path(&umulti_link->path, buf, upath_size);
3063 	if (IS_ERR(p)) {
3064 		kfree(buf);
3065 		return PTR_ERR(p);
3066 	}
3067 	upath_size = buf + upath_size - p;
3068 
3069 	if (upath)
3070 		left = copy_to_user(upath, p, upath_size);
3071 	kfree(buf);
3072 	if (left)
3073 		return -EFAULT;
3074 	info->uprobe_multi.path_size = upath_size;
3075 
3076 	if (!uoffsets && !ucookies && !uref_ctr_offsets)
3077 		return 0;
3078 
3079 	if (ucount < umulti_link->cnt)
3080 		err = -ENOSPC;
3081 	else
3082 		ucount = umulti_link->cnt;
3083 
3084 	for (i = 0; i < ucount; i++) {
3085 		if (uoffsets &&
3086 		    put_user(umulti_link->uprobes[i].offset, uoffsets + i))
3087 			return -EFAULT;
3088 		if (uref_ctr_offsets &&
3089 		    put_user(umulti_link->uprobes[i].ref_ctr_offset, uref_ctr_offsets + i))
3090 			return -EFAULT;
3091 		if (ucookies &&
3092 		    put_user(umulti_link->uprobes[i].cookie, ucookies + i))
3093 			return -EFAULT;
3094 	}
3095 
3096 	return err;
3097 }
3098 
3099 #ifdef CONFIG_PROC_FS
3100 static void bpf_uprobe_multi_show_fdinfo(const struct bpf_link *link,
3101 					 struct seq_file *seq)
3102 {
3103 	struct bpf_uprobe_multi_link *umulti_link;
3104 	char *p, *buf;
3105 	pid_t pid;
3106 
3107 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3108 
3109 	buf = kmalloc(PATH_MAX, GFP_KERNEL);
3110 	if (!buf)
3111 		return;
3112 
3113 	p = d_path(&umulti_link->path, buf, PATH_MAX);
3114 	if (IS_ERR(p)) {
3115 		kfree(buf);
3116 		return;
3117 	}
3118 
3119 	pid = umulti_link->task ?
3120 	      task_pid_nr_ns(umulti_link->task, task_active_pid_ns(current)) : 0;
3121 	seq_printf(seq,
3122 		   "uprobe_cnt:\t%u\n"
3123 		   "pid:\t%u\n"
3124 		   "path:\t%s\n",
3125 		   umulti_link->cnt, pid, p);
3126 
3127 	seq_printf(seq, "%s\t %s\t %s\n", "cookie", "offset", "ref_ctr_offset");
3128 	for (int i = 0; i < umulti_link->cnt; i++) {
3129 		seq_printf(seq,
3130 			   "%llu\t %#llx\t %#lx\n",
3131 			   umulti_link->uprobes[i].cookie,
3132 			   umulti_link->uprobes[i].offset,
3133 			   umulti_link->uprobes[i].ref_ctr_offset);
3134 	}
3135 
3136 	kfree(buf);
3137 }
3138 #endif
3139 
3140 static const struct bpf_link_ops bpf_uprobe_multi_link_lops = {
3141 	.release = bpf_uprobe_multi_link_release,
3142 	.dealloc_deferred = bpf_uprobe_multi_link_dealloc,
3143 	.fill_link_info = bpf_uprobe_multi_link_fill_link_info,
3144 #ifdef CONFIG_PROC_FS
3145 	.show_fdinfo = bpf_uprobe_multi_show_fdinfo,
3146 #endif
3147 };
3148 
3149 static int uprobe_prog_run(struct bpf_uprobe *uprobe,
3150 			   unsigned long entry_ip,
3151 			   struct pt_regs *regs,
3152 			   bool is_return, void *data)
3153 {
3154 	struct bpf_uprobe_multi_link *link = uprobe->link;
3155 	struct bpf_uprobe_multi_run_ctx run_ctx = {
3156 		.session_ctx = {
3157 			.is_return = is_return,
3158 			.data = data,
3159 		},
3160 		.entry_ip = entry_ip,
3161 		.uprobe = uprobe,
3162 	};
3163 	struct bpf_prog *prog = link->link.prog;
3164 	bool sleepable = prog->sleepable;
3165 	struct bpf_run_ctx *old_run_ctx;
3166 	int err;
3167 
3168 	if (link->task && !same_thread_group(current, link->task))
3169 		return 0;
3170 
3171 	if (sleepable)
3172 		rcu_read_lock_trace();
3173 	else
3174 		rcu_read_lock();
3175 
3176 	migrate_disable();
3177 
3178 	old_run_ctx = bpf_set_run_ctx(&run_ctx.session_ctx.run_ctx);
3179 	err = bpf_prog_run(link->link.prog, regs);
3180 	bpf_reset_run_ctx(old_run_ctx);
3181 
3182 	migrate_enable();
3183 
3184 	if (sleepable)
3185 		rcu_read_unlock_trace();
3186 	else
3187 		rcu_read_unlock();
3188 	return err;
3189 }
3190 
3191 static bool
3192 uprobe_multi_link_filter(struct uprobe_consumer *con, struct mm_struct *mm)
3193 {
3194 	struct bpf_uprobe *uprobe;
3195 
3196 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3197 	return uprobe->link->task->mm == mm;
3198 }
3199 
3200 static int
3201 uprobe_multi_link_handler(struct uprobe_consumer *con, struct pt_regs *regs,
3202 			  __u64 *data)
3203 {
3204 	struct bpf_uprobe *uprobe;
3205 	int ret;
3206 
3207 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3208 	ret = uprobe_prog_run(uprobe, instruction_pointer(regs), regs, false, data);
3209 	if (uprobe->session)
3210 		return ret ? UPROBE_HANDLER_IGNORE : 0;
3211 	return 0;
3212 }
3213 
3214 static int
3215 uprobe_multi_link_ret_handler(struct uprobe_consumer *con, unsigned long func, struct pt_regs *regs,
3216 			      __u64 *data)
3217 {
3218 	struct bpf_uprobe *uprobe;
3219 
3220 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3221 	uprobe_prog_run(uprobe, func, regs, true, data);
3222 	return 0;
3223 }
3224 
3225 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
3226 {
3227 	struct bpf_uprobe_multi_run_ctx *run_ctx;
3228 
3229 	run_ctx = container_of(current->bpf_ctx, struct bpf_uprobe_multi_run_ctx,
3230 			       session_ctx.run_ctx);
3231 	return run_ctx->entry_ip;
3232 }
3233 
3234 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx)
3235 {
3236 	struct bpf_uprobe_multi_run_ctx *run_ctx;
3237 
3238 	run_ctx = container_of(current->bpf_ctx, struct bpf_uprobe_multi_run_ctx,
3239 			       session_ctx.run_ctx);
3240 	return run_ctx->uprobe->cookie;
3241 }
3242 
3243 static int bpf_uprobe_multi_get_path(const union bpf_attr *attr, struct path *path)
3244 {
3245 	void __user *upath = u64_to_user_ptr(attr->link_create.uprobe_multi.path);
3246 	u32 path_fd = attr->link_create.uprobe_multi.path_fd;
3247 	u32 flags = attr->link_create.uprobe_multi.flags;
3248 
3249 	if (flags & BPF_F_UPROBE_MULTI_PATH_FD) {
3250 		/*
3251 		 * When BPF_F_UPROBE_MULTI_PATH_FD is set, the executable is
3252 		 * identified by path_fd, upath must be NULL.
3253 		 */
3254 		if (upath)
3255 			return -EINVAL;
3256 
3257 		CLASS(fd, f)(path_fd);
3258 		if (fd_empty(f))
3259 			return -EBADF;
3260 		*path = fd_file(f)->f_path;
3261 		path_get(path);
3262 		return 0;
3263 	}
3264 
3265 	/*
3266 	 * When BPF_F_UPROBE_MULTI_PATH_FD is not set, the path is resolved
3267 	 * relative to the cwd (AT_FDCWD) or absolute using the upath string.
3268 	 */
3269 	if (!upath || path_fd)
3270 		return -EINVAL;
3271 
3272 	return user_path_at(AT_FDCWD, upath, LOOKUP_FOLLOW, path);
3273 }
3274 
3275 int bpf_uprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3276 {
3277 	struct bpf_uprobe_multi_link *link = NULL;
3278 	unsigned long __user *uref_ctr_offsets;
3279 	struct bpf_link_primer link_primer;
3280 	struct bpf_uprobe *uprobes = NULL;
3281 	struct task_struct *task = NULL;
3282 	unsigned long __user *uoffsets;
3283 	u64 __user *ucookies;
3284 	unsigned long size;
3285 	u32 flags, cnt, i;
3286 	struct path path;
3287 	pid_t pid;
3288 	int err;
3289 
3290 	/* no support for 32bit archs yet */
3291 	if (sizeof(u64) != sizeof(void *))
3292 		return -EOPNOTSUPP;
3293 
3294 	if (attr->link_create.flags)
3295 		return -EINVAL;
3296 
3297 	if (!is_uprobe_multi(prog))
3298 		return -EINVAL;
3299 
3300 	flags = attr->link_create.uprobe_multi.flags;
3301 	if (flags & ~(BPF_F_UPROBE_MULTI_RETURN | BPF_F_UPROBE_MULTI_PATH_FD))
3302 		return -EINVAL;
3303 
3304 	/*
3305 	 * offsets and cnt are mandatory,
3306 	 * ref_ctr_offsets and cookies are optional
3307 	 */
3308 	uoffsets = u64_to_user_ptr(attr->link_create.uprobe_multi.offsets);
3309 	cnt = attr->link_create.uprobe_multi.cnt;
3310 	pid = attr->link_create.uprobe_multi.pid;
3311 
3312 	if (!uoffsets || !cnt || pid < 0)
3313 		return -EINVAL;
3314 	if (cnt > MAX_UPROBE_MULTI_CNT)
3315 		return -E2BIG;
3316 
3317 	uref_ctr_offsets = u64_to_user_ptr(attr->link_create.uprobe_multi.ref_ctr_offsets);
3318 	ucookies = u64_to_user_ptr(attr->link_create.uprobe_multi.cookies);
3319 
3320 	/*
3321 	 * All uoffsets/uref_ctr_offsets/ucookies arrays have the same value
3322 	 * size.  Check their address ranges up front, so that a bad pointer
3323 	 * fails before anything is looked up or allocated.
3324 	 */
3325 	size = sizeof(*uoffsets) * cnt;
3326 	if (!access_ok(uoffsets, size) || !access_ok(uref_ctr_offsets, size) ||
3327 	    !access_ok(ucookies, size))
3328 		return -EFAULT;
3329 
3330 	err = bpf_uprobe_multi_get_path(attr, &path);
3331 	if (err)
3332 		return err;
3333 
3334 	if (!d_is_reg(path.dentry)) {
3335 		err = -EBADF;
3336 		goto error_path_put;
3337 	}
3338 
3339 	if (pid) {
3340 		rcu_read_lock();
3341 		task = get_pid_task(find_vpid(pid), PIDTYPE_TGID);
3342 		rcu_read_unlock();
3343 		if (!task) {
3344 			err = -ESRCH;
3345 			goto error_path_put;
3346 		}
3347 	}
3348 
3349 	err = -ENOMEM;
3350 
3351 	link = kzalloc_obj(*link);
3352 	uprobes = kvzalloc_objs(*uprobes, cnt);
3353 
3354 	if (!uprobes || !link)
3355 		goto error_free;
3356 
3357 	for (i = 0; i < cnt; i++) {
3358 		if (get_user(uprobes[i].offset, uoffsets + i)) {
3359 			err = -EFAULT;
3360 			goto error_free;
3361 		}
3362 		if (uprobes[i].offset < 0) {
3363 			err = -EINVAL;
3364 			goto error_free;
3365 		}
3366 		if (uref_ctr_offsets && get_user(uprobes[i].ref_ctr_offset, uref_ctr_offsets + i)) {
3367 			err = -EFAULT;
3368 			goto error_free;
3369 		}
3370 		if (ucookies && get_user(uprobes[i].cookie, ucookies + i)) {
3371 			err = -EFAULT;
3372 			goto error_free;
3373 		}
3374 
3375 		uprobes[i].link = link;
3376 
3377 		if (!(flags & BPF_F_UPROBE_MULTI_RETURN))
3378 			uprobes[i].consumer.handler = uprobe_multi_link_handler;
3379 		if (flags & BPF_F_UPROBE_MULTI_RETURN || is_uprobe_session(prog))
3380 			uprobes[i].consumer.ret_handler = uprobe_multi_link_ret_handler;
3381 		if (is_uprobe_session(prog))
3382 			uprobes[i].session = true;
3383 		if (pid)
3384 			uprobes[i].consumer.filter = uprobe_multi_link_filter;
3385 	}
3386 
3387 	link->cnt = cnt;
3388 	link->uprobes = uprobes;
3389 	link->path = path;
3390 	link->task = task;
3391 	link->link.flags = flags;
3392 
3393 	bpf_link_init(&link->link, BPF_LINK_TYPE_UPROBE_MULTI,
3394 		      &bpf_uprobe_multi_link_lops, prog, attr->link_create.attach_type);
3395 
3396 	for (i = 0; i < cnt; i++) {
3397 		uprobes[i].uprobe = uprobe_register(d_real_inode(link->path.dentry),
3398 						    uprobes[i].offset,
3399 						    uprobes[i].ref_ctr_offset,
3400 						    &uprobes[i].consumer);
3401 		if (IS_ERR(uprobes[i].uprobe)) {
3402 			err = PTR_ERR(uprobes[i].uprobe);
3403 			link->cnt = i;
3404 			goto error_unregister;
3405 		}
3406 	}
3407 
3408 	err = bpf_link_prime(&link->link, &link_primer);
3409 	if (err)
3410 		goto error_unregister;
3411 
3412 	return bpf_link_settle(&link_primer);
3413 
3414 error_unregister:
3415 	bpf_uprobe_unregister(uprobes, link->cnt);
3416 
3417 error_free:
3418 	kvfree(uprobes);
3419 	kfree(link);
3420 	if (task)
3421 		put_task_struct(task);
3422 error_path_put:
3423 	path_put(&path);
3424 	return err;
3425 }
3426 #else /* !CONFIG_UPROBES */
3427 int bpf_uprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3428 {
3429 	return -EOPNOTSUPP;
3430 }
3431 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx)
3432 {
3433 	return 0;
3434 }
3435 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
3436 {
3437 	return 0;
3438 }
3439 #endif /* CONFIG_UPROBES */
3440 
3441 __bpf_kfunc_start_defs();
3442 
3443 __bpf_kfunc bool bpf_session_is_return(void *ctx)
3444 {
3445 	struct bpf_session_run_ctx *session_ctx;
3446 
3447 	session_ctx = container_of(current->bpf_ctx, struct bpf_session_run_ctx, run_ctx);
3448 	return session_ctx->is_return;
3449 }
3450 
3451 __bpf_kfunc __u64 *bpf_session_cookie(void *ctx)
3452 {
3453 	struct bpf_session_run_ctx *session_ctx;
3454 
3455 	session_ctx = container_of(current->bpf_ctx, struct bpf_session_run_ctx, run_ctx);
3456 	return session_ctx->data;
3457 }
3458 
3459 __bpf_kfunc_end_defs();
3460 
3461 BTF_KFUNCS_START(session_kfunc_set_ids)
3462 BTF_ID_FLAGS(func, bpf_session_is_return)
3463 BTF_ID_FLAGS(func, bpf_session_cookie)
3464 BTF_KFUNCS_END(session_kfunc_set_ids)
3465 
3466 static int bpf_session_filter(const struct bpf_prog *prog, u32 kfunc_id)
3467 {
3468 	if (!btf_id_set8_contains(&session_kfunc_set_ids, kfunc_id))
3469 		return 0;
3470 
3471 	if (!is_kprobe_session(prog) && !is_uprobe_session(prog) && !is_trace_fsession(prog))
3472 		return -EACCES;
3473 
3474 	return 0;
3475 }
3476 
3477 static const struct btf_kfunc_id_set bpf_session_kfunc_set = {
3478 	.owner = THIS_MODULE,
3479 	.set = &session_kfunc_set_ids,
3480 	.filter = bpf_session_filter,
3481 };
3482 
3483 static int __init bpf_trace_kfuncs_init(void)
3484 {
3485 	int err = 0;
3486 
3487 	err = err ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_KPROBE, &bpf_session_kfunc_set);
3488 	err = err ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_session_kfunc_set);
3489 
3490 	return err;
3491 }
3492 
3493 late_initcall(bpf_trace_kfuncs_init);
3494 
3495 typedef int (*copy_fn_t)(void *dst, const void *src, u32 size, struct task_struct *tsk);
3496 
3497 /*
3498  * The __always_inline is to make sure the compiler doesn't
3499  * generate indirect calls into callbacks, which is expensive,
3500  * on some kernel configurations. This allows compiler to put
3501  * direct calls into all the specific callback implementations
3502  * (copy_user_data_sleepable, copy_user_data_nofault, and so on)
3503  */
3504 static __always_inline int __bpf_dynptr_copy_str(const struct bpf_dynptr *dptr, u64 doff, u64 size,
3505 						 const void *unsafe_src,
3506 						 copy_fn_t str_copy_fn,
3507 						 struct task_struct *tsk)
3508 {
3509 	const struct bpf_dynptr_kern *dst;
3510 	u64 chunk_sz, off;
3511 	void *dst_slice;
3512 	int cnt, err;
3513 	char buf[256];
3514 
3515 	dst_slice = bpf_dynptr_slice_rdwr(dptr, doff, NULL, size);
3516 	if (likely(dst_slice))
3517 		return str_copy_fn(dst_slice, unsafe_src, size, tsk);
3518 
3519 	dst = (struct bpf_dynptr_kern *)dptr;
3520 	if (bpf_dynptr_check_off_len(dst, doff, size))
3521 		return -E2BIG;
3522 
3523 	for (off = 0; off < size; off += chunk_sz - 1) {
3524 		chunk_sz = min_t(u64, sizeof(buf), size - off);
3525 		/* Expect str_copy_fn to return count of copied bytes, including
3526 		 * zero terminator. Next iteration increment off by chunk_sz - 1 to
3527 		 * overwrite NUL.
3528 		 */
3529 		cnt = str_copy_fn(buf, unsafe_src + off, chunk_sz, tsk);
3530 		if (cnt < 0)
3531 			return cnt;
3532 		err = __bpf_dynptr_write(dst, doff + off, buf, cnt, 0);
3533 		if (err)
3534 			return err;
3535 		if (cnt < chunk_sz || chunk_sz == 1) /* we are done */
3536 			return off + cnt;
3537 	}
3538 	return off;
3539 }
3540 
3541 static __always_inline int __bpf_dynptr_copy(const struct bpf_dynptr *dptr, u64 doff,
3542 					     u64 size, const void *unsafe_src,
3543 					     copy_fn_t copy_fn, struct task_struct *tsk)
3544 {
3545 	const struct bpf_dynptr_kern *dst;
3546 	void *dst_slice;
3547 	char buf[256];
3548 	u64 off, chunk_sz;
3549 	int err;
3550 
3551 	dst_slice = bpf_dynptr_slice_rdwr(dptr, doff, NULL, size);
3552 	if (likely(dst_slice))
3553 		return copy_fn(dst_slice, unsafe_src, size, tsk);
3554 
3555 	dst = (struct bpf_dynptr_kern *)dptr;
3556 	if (bpf_dynptr_check_off_len(dst, doff, size))
3557 		return -E2BIG;
3558 
3559 	for (off = 0; off < size; off += chunk_sz) {
3560 		chunk_sz = min_t(u64, sizeof(buf), size - off);
3561 		err = copy_fn(buf, unsafe_src + off, chunk_sz, tsk);
3562 		if (err)
3563 			return err;
3564 		err = __bpf_dynptr_write(dst, doff + off, buf, chunk_sz, 0);
3565 		if (err)
3566 			return err;
3567 	}
3568 	return 0;
3569 }
3570 
3571 static __always_inline int copy_user_data_nofault(void *dst, const void *unsafe_src,
3572 						  u32 size, struct task_struct *tsk)
3573 {
3574 	return copy_from_user_nofault(dst, (const void __user *)unsafe_src, size);
3575 }
3576 
3577 static __always_inline int copy_user_data_sleepable(void *dst, const void *unsafe_src,
3578 						    u32 size, struct task_struct *tsk)
3579 {
3580 	int ret;
3581 
3582 	if (!tsk) { /* Read from the current task */
3583 		ret = copy_from_user(dst, (const void __user *)unsafe_src, size);
3584 		if (ret)
3585 			return -EFAULT;
3586 		return 0;
3587 	}
3588 
3589 	ret = access_process_vm(tsk, (unsigned long)unsafe_src, dst, size, 0);
3590 	if (ret != size)
3591 		return -EFAULT;
3592 	return 0;
3593 }
3594 
3595 static __always_inline int copy_kernel_data_nofault(void *dst, const void *unsafe_src,
3596 						    u32 size, struct task_struct *tsk)
3597 {
3598 	return copy_from_kernel_nofault(dst, unsafe_src, size);
3599 }
3600 
3601 static __always_inline int copy_user_str_nofault(void *dst, const void *unsafe_src,
3602 						 u32 size, struct task_struct *tsk)
3603 {
3604 	return strncpy_from_user_nofault(dst, (const void __user *)unsafe_src, size);
3605 }
3606 
3607 static __always_inline int copy_user_str_sleepable(void *dst, const void *unsafe_src,
3608 						   u32 size, struct task_struct *tsk)
3609 {
3610 	int ret;
3611 
3612 	if (unlikely(size == 0))
3613 		return 0;
3614 
3615 	if (tsk) {
3616 		ret = copy_remote_vm_str(tsk, (unsigned long)unsafe_src, dst, size, 0);
3617 	} else {
3618 		ret = strncpy_from_user(dst, (const void __user *)unsafe_src, size - 1);
3619 		/* strncpy_from_user does not guarantee NUL termination */
3620 		if (ret >= 0)
3621 			((char *)dst)[ret] = '\0';
3622 	}
3623 
3624 	if (ret < 0)
3625 		return ret;
3626 	return ret + 1;
3627 }
3628 
3629 static __always_inline int copy_kernel_str_nofault(void *dst, const void *unsafe_src,
3630 						   u32 size, struct task_struct *tsk)
3631 {
3632 	return strncpy_from_kernel_nofault(dst, unsafe_src, size);
3633 }
3634 
3635 __bpf_kfunc_start_defs();
3636 
3637 __bpf_kfunc int bpf_send_signal_task(struct task_struct *task, int sig, enum pid_type type,
3638 				     u64 value)
3639 {
3640 	if (type != PIDTYPE_PID && type != PIDTYPE_TGID)
3641 		return -EINVAL;
3642 
3643 	return bpf_send_signal_common(sig, type, task, value);
3644 }
3645 
3646 __bpf_kfunc int bpf_probe_read_user_dynptr(const struct bpf_dynptr *dptr, u64 off,
3647 					   u64 size, const void __user *unsafe_ptr__ign)
3648 {
3649 	return __bpf_dynptr_copy(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3650 				 copy_user_data_nofault, NULL);
3651 }
3652 
3653 __bpf_kfunc int bpf_probe_read_kernel_dynptr(const struct bpf_dynptr *dptr, u64 off,
3654 					     u64 size, const void *unsafe_ptr__ign)
3655 {
3656 	return __bpf_dynptr_copy(dptr, off, size, unsafe_ptr__ign,
3657 				 copy_kernel_data_nofault, NULL);
3658 }
3659 
3660 __bpf_kfunc int bpf_probe_read_user_str_dynptr(const struct bpf_dynptr *dptr, u64 off,
3661 					       u64 size, const void __user *unsafe_ptr__ign)
3662 {
3663 	return __bpf_dynptr_copy_str(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3664 				     copy_user_str_nofault, NULL);
3665 }
3666 
3667 __bpf_kfunc int bpf_probe_read_kernel_str_dynptr(const struct bpf_dynptr *dptr, u64 off,
3668 						 u64 size, const void *unsafe_ptr__ign)
3669 {
3670 	return __bpf_dynptr_copy_str(dptr, off, size, unsafe_ptr__ign,
3671 				     copy_kernel_str_nofault, NULL);
3672 }
3673 
3674 __bpf_kfunc int bpf_copy_from_user_dynptr(const struct bpf_dynptr *dptr, u64 off,
3675 					  u64 size, const void __user *unsafe_ptr__ign)
3676 {
3677 	return __bpf_dynptr_copy(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3678 				 copy_user_data_sleepable, NULL);
3679 }
3680 
3681 __bpf_kfunc int bpf_copy_from_user_str_dynptr(const struct bpf_dynptr *dptr, u64 off,
3682 					      u64 size, const void __user *unsafe_ptr__ign)
3683 {
3684 	return __bpf_dynptr_copy_str(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3685 				     copy_user_str_sleepable, NULL);
3686 }
3687 
3688 __bpf_kfunc int bpf_copy_from_user_task_dynptr(const struct bpf_dynptr *dptr, u64 off,
3689 					       u64 size, const void __user *unsafe_ptr__ign,
3690 					       struct task_struct *tsk)
3691 {
3692 	return __bpf_dynptr_copy(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3693 				 copy_user_data_sleepable, tsk);
3694 }
3695 
3696 __bpf_kfunc int bpf_copy_from_user_task_str_dynptr(const struct bpf_dynptr *dptr, u64 off,
3697 						   u64 size, const void __user *unsafe_ptr__ign,
3698 						   struct task_struct *tsk)
3699 {
3700 	return __bpf_dynptr_copy_str(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3701 				     copy_user_str_sleepable, tsk);
3702 }
3703 
3704 __bpf_kfunc_end_defs();
3705 
3706 #if defined(CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS) && \
3707     defined(CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS)
3708 
3709 static void bpf_tracing_multi_link_release(struct bpf_link *link)
3710 {
3711 	struct bpf_tracing_multi_link *tr_link =
3712 		container_of(link, struct bpf_tracing_multi_link, link);
3713 
3714 	bpf_trampoline_multi_detach(link->prog, tr_link);
3715 }
3716 
3717 static void bpf_tracing_multi_link_dealloc(struct bpf_link *link)
3718 {
3719 	struct bpf_tracing_multi_link *tr_link =
3720 		container_of(link, struct bpf_tracing_multi_link, link);
3721 
3722 	kvfree(tr_link->fexits);
3723 	kvfree(tr_link->cookies);
3724 	kvfree(tr_link);
3725 }
3726 
3727 static int bpf_tracing_multi_link_fill_link_info(const struct bpf_link *link,
3728 						 struct bpf_link_info *info)
3729 {
3730 	u64 __user *ucookies = u64_to_user_ptr(info->tracing_multi.cookies);
3731 	u64 __user *uaddrs = u64_to_user_ptr(info->tracing_multi.addrs);
3732 	u32 __user *uids = u64_to_user_ptr(info->tracing_multi.ids);
3733 	struct bpf_tracing_multi_link *tr_link;
3734 	u32 ucount = info->tracing_multi.count;
3735 	bool has_cookies, show_addrs;
3736 	int err = 0;
3737 
3738 	if ((uids || ucookies || uaddrs) && !ucount)
3739 		return -EINVAL;
3740 
3741 	tr_link = container_of(link, struct bpf_tracing_multi_link, link);
3742 
3743 	info->tracing_multi.attach_type = tr_link->link.attach_type;
3744 	info->tracing_multi.count = tr_link->nodes_cnt;
3745 	info->tracing_multi.btf_obj_id = btf_obj_id(tr_link->link.prog->aux->attach_btf);
3746 
3747 	if (!uids && !ucookies && !uaddrs)
3748 		return 0;
3749 
3750 	if (ucount < tr_link->nodes_cnt)
3751 		err = -ENOSPC;
3752 	else
3753 		ucount = tr_link->nodes_cnt;
3754 
3755 	has_cookies = !!tr_link->cookies;
3756 	show_addrs = kallsyms_show_value(current_cred());
3757 
3758 	for (int i = 0; i < ucount; i++) {
3759 		struct bpf_tracing_multi_node *mnode = &tr_link->nodes[i];
3760 		u64 addr, cookie;
3761 		u32 id;
3762 
3763 		bpf_trampoline_unpack_key(mnode->trampoline->key, NULL, &id);
3764 
3765 		addr = show_addrs ? mnode->trampoline->ip : 0;
3766 		cookie = has_cookies ? tr_link->cookies[i] : 0;
3767 
3768 		if (uids && put_user(id, uids + i))
3769 			return -EFAULT;
3770 		if (uaddrs && put_user(addr, uaddrs + i))
3771 			return -EFAULT;
3772 		if (ucookies && put_user(cookie, ucookies + i))
3773 			return -EFAULT;
3774 
3775 		cond_resched();
3776 	}
3777 
3778 	return err;
3779 }
3780 
3781 #ifdef CONFIG_PROC_FS
3782 static void bpf_tracing_multi_show_fdinfo(const struct bpf_link *link,
3783 					  struct seq_file *seq)
3784 {
3785 	struct bpf_tracing_multi_link *tr_link =
3786 		container_of(link, struct bpf_tracing_multi_link, link);
3787 	bool has_cookies = !!tr_link->cookies;
3788 
3789 	seq_printf(seq, "attach_type:\t%u\n", tr_link->link.attach_type);
3790 	seq_printf(seq, "cnt:\t%u\n", tr_link->nodes_cnt);
3791 
3792 	seq_printf(seq, "%s\t %s\t %s\t %s\n", "obj-id", "btf-id", "cookie", "func");
3793 	for (int i = 0; i < tr_link->nodes_cnt; i++) {
3794 		struct bpf_tracing_multi_node *mnode = &tr_link->nodes[i];
3795 		u32 btf_id, obj_id;
3796 
3797 		bpf_trampoline_unpack_key(mnode->trampoline->key, &obj_id, &btf_id);
3798 		seq_printf(seq, "%u\t %u\t %llu\t %pS\n",
3799 			   obj_id, btf_id,
3800 			   has_cookies ? tr_link->cookies[i] : 0,
3801 			   (void *) mnode->trampoline->ip);
3802 
3803 		cond_resched();
3804 	}
3805 }
3806 #endif
3807 
3808 static const struct bpf_link_ops bpf_tracing_multi_link_lops = {
3809 	.release = bpf_tracing_multi_link_release,
3810 	.dealloc_deferred = bpf_tracing_multi_link_dealloc,
3811 	.fill_link_info = bpf_tracing_multi_link_fill_link_info,
3812 #ifdef CONFIG_PROC_FS
3813 	.show_fdinfo = bpf_tracing_multi_show_fdinfo,
3814 #endif
3815 };
3816 
3817 static int ids_cmp_r(const void *pa, const void *pb, const void *priv __maybe_unused)
3818 {
3819 	u32 a = *(u32 *) pa;
3820 	u32 b = *(u32 *) pb;
3821 
3822 	return (a > b) - (a < b);
3823 }
3824 
3825 static void ids_swap_r(void *a, void *b, int size __maybe_unused,
3826 		       const void *priv __maybe_unused)
3827 {
3828 	u64 *cookie_a, *cookie_b, *cookies;
3829 	u32 *id_a = a, *id_b = b, *ids;
3830 	void **data = (void **) priv;
3831 
3832 	ids     = data[0];
3833 	cookies = data[1];
3834 
3835 	if (cookies) {
3836 		cookie_a = cookies + (id_a - ids);
3837 		cookie_b = cookies + (id_b - ids);
3838 		swap(*cookie_a, *cookie_b);
3839 	}
3840 	swap(*id_a, *id_b);
3841 }
3842 
3843 static int check_dup_ids(u32 *ids, u64 *cookies, u32 cnt)
3844 {
3845 	void *data[2] = { ids, cookies };
3846 	int err = 0;
3847 
3848 	/*
3849 	 * Sort ids array (together with cookies array if defined)
3850 	 * and check it for duplicates. The ids and cookies arrays
3851 	 * are left sorted.
3852 	 */
3853 	sort_r_nonatomic(ids, cnt, sizeof(ids[0]), ids_cmp_r, ids_swap_r, data);
3854 
3855 	for (int i = 1; i < cnt; i++) {
3856 		if (ids[i] == ids[i - 1]) {
3857 			err = -EINVAL;
3858 			break;
3859 		}
3860 	}
3861 	return err;
3862 }
3863 
3864 int bpf_tracing_multi_attach(struct bpf_prog *prog, const union bpf_attr *attr)
3865 {
3866 	struct bpf_tracing_multi_link *link = NULL;
3867 	struct bpf_tramp_node *fexits = NULL;
3868 	struct bpf_link_primer link_primer;
3869 	u32 cnt, *ids = NULL;
3870 	u64 __user *ucookies;
3871 	u64 *cookies = NULL;
3872 	u32 __user *uids;
3873 	int err;
3874 
3875 	uids = u64_to_user_ptr(attr->link_create.tracing_multi.ids);
3876 	cnt = attr->link_create.tracing_multi.cnt;
3877 
3878 	if (!cnt || !uids)
3879 		return -EINVAL;
3880 	if (cnt > MAX_TRACING_MULTI_CNT)
3881 		return -E2BIG;
3882 	if (attr->link_create.flags || attr->link_create.target_fd)
3883 		return -EINVAL;
3884 
3885 	ids = kvmalloc_objs(*ids, cnt);
3886 	if (!ids)
3887 		return -ENOMEM;
3888 
3889 	if (copy_from_user(ids, uids, cnt * sizeof(*ids))) {
3890 		err = -EFAULT;
3891 		goto error;
3892 	}
3893 
3894 	ucookies = u64_to_user_ptr(attr->link_create.tracing_multi.cookies);
3895 	if (ucookies) {
3896 		cookies = kvmalloc_objs(*cookies, cnt);
3897 		if (!cookies) {
3898 			err = -ENOMEM;
3899 			goto error;
3900 		}
3901 		if (copy_from_user(cookies, ucookies, cnt * sizeof(*cookies))) {
3902 			err = -EFAULT;
3903 			goto error;
3904 		}
3905 	}
3906 
3907 	err = check_dup_ids(ids, cookies, cnt);
3908 	if (err)
3909 		goto error;
3910 
3911 	if (prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) {
3912 		fexits = kvmalloc_objs(*fexits, cnt);
3913 		if (!fexits) {
3914 			err = -ENOMEM;
3915 			goto error;
3916 		}
3917 	}
3918 
3919 	link = kvzalloc_flex(*link, nodes, cnt);
3920 	if (!link) {
3921 		err = -ENOMEM;
3922 		goto error;
3923 	}
3924 
3925 	bpf_link_init(&link->link, BPF_LINK_TYPE_TRACING_MULTI,
3926 		      &bpf_tracing_multi_link_lops, prog, prog->expected_attach_type);
3927 
3928 	err = bpf_link_prime(&link->link, &link_primer);
3929 	if (err)
3930 		goto error;
3931 
3932 	link->nodes_cnt = cnt;
3933 	link->cookies = cookies;
3934 	link->fexits = fexits;
3935 
3936 	err = bpf_trampoline_multi_attach(prog, ids, link);
3937 	kvfree(ids);
3938 	if (err) {
3939 		bpf_link_cleanup(&link_primer);
3940 		return err;
3941 	}
3942 	return bpf_link_settle(&link_primer);
3943 
3944 error:
3945 	kvfree(fexits);
3946 	kvfree(cookies);
3947 	kvfree(ids);
3948 	kvfree(link);
3949 	return err;
3950 }
3951 
3952 #else
3953 
3954 int bpf_tracing_multi_attach(struct bpf_prog *prog, const union bpf_attr *attr)
3955 {
3956 	return -EOPNOTSUPP;
3957 }
3958 
3959 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS && CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS */
3960