xref: /linux/kernel/trace/bpf_trace.c (revision 55fbedcec622a943cb09a969aef1ddcba87ee40a)
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 	/* Similar to bpf_probe_write_user, task needs to be
871 	 * in a sound condition and kernel memory access be
872 	 * permitted in order to send signal to the current
873 	 * task.
874 	 */
875 	if (unlikely(task->flags & (PF_KTHREAD | PF_EXITING)))
876 		return -EPERM;
877 	if (unlikely(!nmi_uaccess_okay()))
878 		return -EPERM;
879 	/* Task should not be pid=1 to avoid kernel panic. */
880 	if (unlikely(is_global_init(task)))
881 		return -EPERM;
882 
883 	if (preempt_count() != 0 || irqs_disabled()) {
884 		/* Do an early check on signal validity. Otherwise,
885 		 * the error is lost in deferred irq_work.
886 		 */
887 		if (unlikely(!valid_signal(sig)))
888 			return -EINVAL;
889 
890 		work = this_cpu_ptr(&send_signal_work);
891 		if (cmpxchg(&work->task, NULL, task))
892 			return -EBUSY;
893 
894 		/* Add the current task, which is the target of sending signal,
895 		 * to the irq_work. The current task may change when queued
896 		 * irq works get executed.
897 		 */
898 		get_task_struct(task);
899 		work->has_siginfo = siginfo == &info;
900 		if (work->has_siginfo)
901 			copy_siginfo(&work->info, &info);
902 		work->sig = sig;
903 		work->type = type;
904 		irq_work_queue(&work->irq_work);
905 		return 0;
906 	}
907 
908 	return group_send_sig_info(sig, siginfo, task, type);
909 }
910 
911 BPF_CALL_1(bpf_send_signal, u32, sig)
912 {
913 	return bpf_send_signal_common(sig, PIDTYPE_TGID, NULL, 0);
914 }
915 
916 const struct bpf_func_proto bpf_send_signal_proto = {
917 	.func		= bpf_send_signal,
918 	.gpl_only	= false,
919 	.ret_type	= RET_INTEGER,
920 	.arg1_type	= ARG_ANYTHING,
921 };
922 
923 BPF_CALL_1(bpf_send_signal_thread, u32, sig)
924 {
925 	return bpf_send_signal_common(sig, PIDTYPE_PID, NULL, 0);
926 }
927 
928 const struct bpf_func_proto bpf_send_signal_thread_proto = {
929 	.func		= bpf_send_signal_thread,
930 	.gpl_only	= false,
931 	.ret_type	= RET_INTEGER,
932 	.arg1_type	= ARG_ANYTHING,
933 };
934 
935 BPF_CALL_3(bpf_d_path, const struct path *, path, char *, buf, u32, sz)
936 {
937 	struct path copy;
938 	long len;
939 	char *p;
940 
941 	if (!sz)
942 		return 0;
943 
944 	/*
945 	 * The path pointer is verified as trusted and safe to use,
946 	 * but let's double check it's valid anyway to workaround
947 	 * potentially broken verifier.
948 	 */
949 	len = copy_from_kernel_nofault(&copy, path, sizeof(*path));
950 	if (len < 0)
951 		return len;
952 
953 	p = d_path(&copy, buf, sz);
954 	if (IS_ERR(p)) {
955 		len = PTR_ERR(p);
956 	} else {
957 		len = buf + sz - p;
958 		memmove(buf, p, len);
959 	}
960 
961 	return len;
962 }
963 
964 BTF_SET_START(btf_allowlist_d_path)
965 #ifdef CONFIG_SECURITY
966 BTF_ID(func, security_file_permission)
967 BTF_ID(func, security_inode_getattr)
968 BTF_ID(func, security_file_open)
969 #endif
970 #ifdef CONFIG_SECURITY_PATH
971 BTF_ID(func, security_path_truncate)
972 #endif
973 BTF_ID(func, vfs_truncate)
974 BTF_ID(func, vfs_fallocate)
975 BTF_ID(func, dentry_open)
976 BTF_ID(func, vfs_getattr)
977 BTF_ID(func, filp_close)
978 BTF_SET_END(btf_allowlist_d_path)
979 
980 static bool bpf_d_path_allowed(const struct bpf_prog *prog)
981 {
982 	if (prog->type == BPF_PROG_TYPE_TRACING &&
983 	    prog->expected_attach_type == BPF_TRACE_ITER)
984 		return true;
985 
986 	if (prog->type == BPF_PROG_TYPE_LSM)
987 		return bpf_lsm_is_sleepable_hook(prog->aux->attach_btf_id);
988 
989 	return btf_id_set_contains(&btf_allowlist_d_path,
990 				   prog->aux->attach_btf_id);
991 }
992 
993 BTF_ID_LIST_SINGLE(bpf_d_path_btf_ids, struct, path)
994 
995 static const struct bpf_func_proto bpf_d_path_proto = {
996 	.func		= bpf_d_path,
997 	.gpl_only	= false,
998 	.ret_type	= RET_INTEGER,
999 	.arg1_type	= ARG_PTR_TO_BTF_ID,
1000 	.arg1_btf_id	= &bpf_d_path_btf_ids[0],
1001 	.arg2_type	= ARG_PTR_TO_MEM | MEM_UNINIT | MEM_WRITE,
1002 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
1003 	.allowed	= bpf_d_path_allowed,
1004 };
1005 
1006 #define BTF_F_ALL	(BTF_F_COMPACT  | BTF_F_NONAME | \
1007 			 BTF_F_PTR_RAW | BTF_F_ZERO)
1008 
1009 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
1010 				  u64 flags, const struct btf **btf,
1011 				  s32 *btf_id)
1012 {
1013 	const struct btf_type *t;
1014 
1015 	if (unlikely(flags & ~(BTF_F_ALL)))
1016 		return -EINVAL;
1017 
1018 	if (btf_ptr_size != sizeof(struct btf_ptr))
1019 		return -EINVAL;
1020 
1021 	*btf = bpf_get_btf_vmlinux();
1022 
1023 	if (IS_ERR_OR_NULL(*btf))
1024 		return IS_ERR(*btf) ? PTR_ERR(*btf) : -EINVAL;
1025 
1026 	if (ptr->type_id > 0)
1027 		*btf_id = ptr->type_id;
1028 	else
1029 		return -EINVAL;
1030 
1031 	if (*btf_id > 0)
1032 		t = btf_type_by_id(*btf, *btf_id);
1033 	if (*btf_id <= 0 || !t)
1034 		return -ENOENT;
1035 
1036 	return 0;
1037 }
1038 
1039 BPF_CALL_5(bpf_snprintf_btf, char *, str, u32, str_size, struct btf_ptr *, ptr,
1040 	   u32, btf_ptr_size, u64, flags)
1041 {
1042 	const struct btf *btf;
1043 	s32 btf_id;
1044 	int ret;
1045 
1046 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
1047 	if (ret)
1048 		return ret;
1049 
1050 	return btf_type_snprintf_show(btf, btf_id, ptr->ptr, str, str_size,
1051 				      flags);
1052 }
1053 
1054 const struct bpf_func_proto bpf_snprintf_btf_proto = {
1055 	.func		= bpf_snprintf_btf,
1056 	.gpl_only	= false,
1057 	.ret_type	= RET_INTEGER,
1058 	.arg1_type	= ARG_PTR_TO_MEM | MEM_UNINIT | MEM_WRITE,
1059 	.arg2_type	= ARG_MEM_SIZE,
1060 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1061 	.arg4_type	= ARG_MEM_SIZE,
1062 	.arg5_type	= ARG_ANYTHING,
1063 };
1064 
1065 BPF_CALL_1(bpf_get_func_ip_tracing, void *, ctx)
1066 {
1067 	/* This helper call is inlined by verifier. */
1068 	return ((u64 *)ctx)[-2];
1069 }
1070 
1071 static const struct bpf_func_proto bpf_get_func_ip_proto_tracing = {
1072 	.func		= bpf_get_func_ip_tracing,
1073 	.gpl_only	= true,
1074 	.ret_type	= RET_INTEGER,
1075 	.arg1_type	= ARG_PTR_TO_CTX,
1076 };
1077 
1078 static inline unsigned long get_entry_ip(unsigned long fentry_ip)
1079 {
1080 #ifdef CONFIG_X86_KERNEL_IBT
1081 	if (is_endbr((void *)(fentry_ip - ENDBR_INSN_SIZE)))
1082 		fentry_ip -= ENDBR_INSN_SIZE;
1083 #endif
1084 	return fentry_ip;
1085 }
1086 
1087 BPF_CALL_1(bpf_get_func_ip_kprobe, struct pt_regs *, regs)
1088 {
1089 	struct bpf_trace_run_ctx *run_ctx __maybe_unused;
1090 	struct kprobe *kp;
1091 
1092 #ifdef CONFIG_UPROBES
1093 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1094 	if (run_ctx->is_uprobe)
1095 		return ((struct uprobe_dispatch_data *)current->utask->vaddr)->bp_addr;
1096 #endif
1097 
1098 	kp = kprobe_running();
1099 
1100 	if (!kp || !(kp->flags & KPROBE_FLAG_ON_FUNC_ENTRY))
1101 		return 0;
1102 
1103 	return get_entry_ip((uintptr_t)kp->addr);
1104 }
1105 
1106 static const struct bpf_func_proto bpf_get_func_ip_proto_kprobe = {
1107 	.func		= bpf_get_func_ip_kprobe,
1108 	.gpl_only	= true,
1109 	.ret_type	= RET_INTEGER,
1110 	.arg1_type	= ARG_PTR_TO_CTX,
1111 };
1112 
1113 BPF_CALL_1(bpf_get_func_ip_kprobe_multi, struct pt_regs *, regs)
1114 {
1115 	return bpf_kprobe_multi_entry_ip(current->bpf_ctx);
1116 }
1117 
1118 static const struct bpf_func_proto bpf_get_func_ip_proto_kprobe_multi = {
1119 	.func		= bpf_get_func_ip_kprobe_multi,
1120 	.gpl_only	= false,
1121 	.ret_type	= RET_INTEGER,
1122 	.arg1_type	= ARG_PTR_TO_CTX,
1123 };
1124 
1125 BPF_CALL_1(bpf_get_attach_cookie_kprobe_multi, struct pt_regs *, regs)
1126 {
1127 	return bpf_kprobe_multi_cookie(current->bpf_ctx);
1128 }
1129 
1130 static const struct bpf_func_proto bpf_get_attach_cookie_proto_kmulti = {
1131 	.func		= bpf_get_attach_cookie_kprobe_multi,
1132 	.gpl_only	= false,
1133 	.ret_type	= RET_INTEGER,
1134 	.arg1_type	= ARG_PTR_TO_CTX,
1135 };
1136 
1137 BPF_CALL_1(bpf_get_func_ip_uprobe_multi, struct pt_regs *, regs)
1138 {
1139 	return bpf_uprobe_multi_entry_ip(current->bpf_ctx);
1140 }
1141 
1142 static const struct bpf_func_proto bpf_get_func_ip_proto_uprobe_multi = {
1143 	.func		= bpf_get_func_ip_uprobe_multi,
1144 	.gpl_only	= false,
1145 	.ret_type	= RET_INTEGER,
1146 	.arg1_type	= ARG_PTR_TO_CTX,
1147 };
1148 
1149 BPF_CALL_1(bpf_get_attach_cookie_uprobe_multi, struct pt_regs *, regs)
1150 {
1151 	return bpf_uprobe_multi_cookie(current->bpf_ctx);
1152 }
1153 
1154 static const struct bpf_func_proto bpf_get_attach_cookie_proto_umulti = {
1155 	.func		= bpf_get_attach_cookie_uprobe_multi,
1156 	.gpl_only	= false,
1157 	.ret_type	= RET_INTEGER,
1158 	.arg1_type	= ARG_PTR_TO_CTX,
1159 };
1160 
1161 BPF_CALL_1(bpf_get_attach_cookie_trace, void *, ctx)
1162 {
1163 	struct bpf_trace_run_ctx *run_ctx;
1164 
1165 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1166 	return run_ctx->bpf_cookie;
1167 }
1168 
1169 static const struct bpf_func_proto bpf_get_attach_cookie_proto_trace = {
1170 	.func		= bpf_get_attach_cookie_trace,
1171 	.gpl_only	= false,
1172 	.ret_type	= RET_INTEGER,
1173 	.arg1_type	= ARG_PTR_TO_CTX,
1174 };
1175 
1176 BPF_CALL_1(bpf_get_attach_cookie_pe, struct bpf_perf_event_data_kern *, ctx)
1177 {
1178 	return ctx->event->bpf_cookie;
1179 }
1180 
1181 static const struct bpf_func_proto bpf_get_attach_cookie_proto_pe = {
1182 	.func		= bpf_get_attach_cookie_pe,
1183 	.gpl_only	= false,
1184 	.ret_type	= RET_INTEGER,
1185 	.arg1_type	= ARG_PTR_TO_CTX,
1186 };
1187 
1188 BPF_CALL_1(bpf_get_attach_cookie_tracing, void *, ctx)
1189 {
1190 	struct bpf_trace_run_ctx *run_ctx;
1191 
1192 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1193 	return run_ctx->bpf_cookie;
1194 }
1195 
1196 static const struct bpf_func_proto bpf_get_attach_cookie_proto_tracing = {
1197 	.func		= bpf_get_attach_cookie_tracing,
1198 	.gpl_only	= false,
1199 	.ret_type	= RET_INTEGER,
1200 	.arg1_type	= ARG_PTR_TO_CTX,
1201 };
1202 
1203 BPF_CALL_3(bpf_get_branch_snapshot, void *, buf, u32, size, u64, flags)
1204 {
1205 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1206 	u32 entry_cnt = size / br_entry_size;
1207 
1208 	entry_cnt = static_call(perf_snapshot_branch_stack)(buf, entry_cnt);
1209 
1210 	if (unlikely(flags))
1211 		return -EINVAL;
1212 
1213 	if (!entry_cnt)
1214 		return -ENOENT;
1215 
1216 	return entry_cnt * br_entry_size;
1217 }
1218 
1219 const struct bpf_func_proto bpf_get_branch_snapshot_proto = {
1220 	.func		= bpf_get_branch_snapshot,
1221 	.gpl_only	= true,
1222 	.ret_type	= RET_INTEGER,
1223 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1224 	.arg2_type	= ARG_MEM_SIZE_OR_ZERO,
1225 };
1226 
1227 BPF_CALL_3(get_func_arg, void *, ctx, u32, n, u64 *, value)
1228 {
1229 	/* This helper call is inlined by verifier. */
1230 	u64 nr_args = ((u64 *)ctx)[-1] & 0xFF;
1231 
1232 	if ((u64) n >= nr_args)
1233 		return -EINVAL;
1234 	*value = ((u64 *)ctx)[n];
1235 	return 0;
1236 }
1237 
1238 static const struct bpf_func_proto bpf_get_func_arg_proto = {
1239 	.func		= get_func_arg,
1240 	.ret_type	= RET_INTEGER,
1241 	.arg1_type	= ARG_PTR_TO_CTX,
1242 	.arg2_type	= ARG_ANYTHING,
1243 	.arg3_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
1244 	.arg3_size	= sizeof(u64),
1245 };
1246 
1247 BPF_CALL_2(get_func_ret, void *, ctx, u64 *, value)
1248 {
1249 	/* This helper call is inlined by verifier. */
1250 	u64 nr_args = ((u64 *)ctx)[-1] & 0xFF;
1251 
1252 	*value = ((u64 *)ctx)[nr_args];
1253 	return 0;
1254 }
1255 
1256 static const struct bpf_func_proto bpf_get_func_ret_proto = {
1257 	.func		= get_func_ret,
1258 	.ret_type	= RET_INTEGER,
1259 	.arg1_type	= ARG_PTR_TO_CTX,
1260 	.arg2_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
1261 	.arg2_size	= sizeof(u64),
1262 };
1263 
1264 BPF_CALL_1(get_func_arg_cnt, void *, ctx)
1265 {
1266 	/* This helper call is inlined by verifier. */
1267 	return ((u64 *)ctx)[-1] & 0xFF;
1268 }
1269 
1270 static const struct bpf_func_proto bpf_get_func_arg_cnt_proto = {
1271 	.func		= get_func_arg_cnt,
1272 	.ret_type	= RET_INTEGER,
1273 	.arg1_type	= ARG_PTR_TO_CTX,
1274 };
1275 
1276 static const struct bpf_func_proto *
1277 bpf_tracing_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1278 {
1279 	const struct bpf_func_proto *func_proto;
1280 
1281 	switch (func_id) {
1282 	case BPF_FUNC_get_smp_processor_id:
1283 		return &bpf_get_smp_processor_id_proto;
1284 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
1285 	case BPF_FUNC_probe_read:
1286 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1287 		       NULL : &bpf_probe_read_compat_proto;
1288 	case BPF_FUNC_probe_read_str:
1289 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1290 		       NULL : &bpf_probe_read_compat_str_proto;
1291 #endif
1292 	case BPF_FUNC_get_func_ip:
1293 		return &bpf_get_func_ip_proto_tracing;
1294 	default:
1295 		break;
1296 	}
1297 
1298 	func_proto = bpf_base_func_proto(func_id, prog);
1299 	if (func_proto)
1300 		return func_proto;
1301 
1302 	if (!bpf_token_capable(prog->aux->token, CAP_SYS_ADMIN))
1303 		return NULL;
1304 
1305 	switch (func_id) {
1306 	case BPF_FUNC_probe_write_user:
1307 		return security_locked_down(LOCKDOWN_BPF_WRITE_USER) < 0 ?
1308 		       NULL : &bpf_probe_write_user_proto;
1309 	default:
1310 		return NULL;
1311 	}
1312 }
1313 
1314 static bool is_kprobe_multi(const struct bpf_prog *prog)
1315 {
1316 	return prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI ||
1317 	       prog->expected_attach_type == BPF_TRACE_KPROBE_SESSION;
1318 }
1319 
1320 static inline bool is_kprobe_session(const struct bpf_prog *prog)
1321 {
1322 	return prog->type == BPF_PROG_TYPE_KPROBE &&
1323 	       prog->expected_attach_type == BPF_TRACE_KPROBE_SESSION;
1324 }
1325 
1326 static inline bool is_uprobe_multi(const struct bpf_prog *prog)
1327 {
1328 	return prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI ||
1329 	       prog->expected_attach_type == BPF_TRACE_UPROBE_SESSION;
1330 }
1331 
1332 static inline bool is_uprobe_session(const struct bpf_prog *prog)
1333 {
1334 	return prog->type == BPF_PROG_TYPE_KPROBE &&
1335 	       prog->expected_attach_type == BPF_TRACE_UPROBE_SESSION;
1336 }
1337 
1338 static inline bool is_trace_fsession(const struct bpf_prog *prog)
1339 {
1340 	return prog->type == BPF_PROG_TYPE_TRACING &&
1341 	       (prog->expected_attach_type == BPF_TRACE_FSESSION ||
1342 		prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI);
1343 }
1344 
1345 static const struct bpf_func_proto *
1346 kprobe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1347 {
1348 	switch (func_id) {
1349 	case BPF_FUNC_perf_event_output:
1350 		return &bpf_perf_event_output_proto;
1351 	case BPF_FUNC_get_stackid:
1352 		return &bpf_get_stackid_proto;
1353 	case BPF_FUNC_get_stack:
1354 		return prog->sleepable ? &bpf_get_stack_sleepable_proto : &bpf_get_stack_proto;
1355 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
1356 	case BPF_FUNC_override_return:
1357 		return &bpf_override_return_proto;
1358 #endif
1359 	case BPF_FUNC_get_func_ip:
1360 		if (is_kprobe_multi(prog))
1361 			return &bpf_get_func_ip_proto_kprobe_multi;
1362 		if (is_uprobe_multi(prog))
1363 			return &bpf_get_func_ip_proto_uprobe_multi;
1364 		return &bpf_get_func_ip_proto_kprobe;
1365 	case BPF_FUNC_get_attach_cookie:
1366 		if (is_kprobe_multi(prog))
1367 			return &bpf_get_attach_cookie_proto_kmulti;
1368 		if (is_uprobe_multi(prog))
1369 			return &bpf_get_attach_cookie_proto_umulti;
1370 		return &bpf_get_attach_cookie_proto_trace;
1371 	default:
1372 		return bpf_tracing_func_proto(func_id, prog);
1373 	}
1374 }
1375 
1376 /* bpf+kprobe programs can access fields of 'struct pt_regs' */
1377 static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1378 					const struct bpf_prog *prog,
1379 					struct bpf_insn_access_aux *info)
1380 {
1381 	if (off < 0 || off >= sizeof(struct pt_regs))
1382 		return false;
1383 	if (off % size != 0)
1384 		return false;
1385 	/*
1386 	 * Assertion for 32 bit to make sure last 8 byte access
1387 	 * (BPF_DW) to the last 4 byte member is disallowed.
1388 	 */
1389 	if (off + size > sizeof(struct pt_regs))
1390 		return false;
1391 
1392 	if (type == BPF_WRITE)
1393 		prog->aux->kprobe_write_ctx = true;
1394 
1395 	return true;
1396 }
1397 
1398 const struct bpf_verifier_ops kprobe_verifier_ops = {
1399 	.get_func_proto  = kprobe_prog_func_proto,
1400 	.is_valid_access = kprobe_prog_is_valid_access,
1401 };
1402 
1403 const struct bpf_prog_ops kprobe_prog_ops = {
1404 };
1405 
1406 BPF_CALL_5(bpf_perf_event_output_tp, void *, tp_buff, struct bpf_map *, map,
1407 	   u64, flags, void *, data, u64, size)
1408 {
1409 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1410 
1411 	/*
1412 	 * r1 points to perf tracepoint buffer where first 8 bytes are hidden
1413 	 * from bpf program and contain a pointer to 'struct pt_regs'. Fetch it
1414 	 * from there and call the same bpf_perf_event_output() helper inline.
1415 	 */
1416 	return ____bpf_perf_event_output(regs, map, flags, data, size);
1417 }
1418 
1419 static const struct bpf_func_proto bpf_perf_event_output_proto_tp = {
1420 	.func		= bpf_perf_event_output_tp,
1421 	.gpl_only	= true,
1422 	.ret_type	= RET_INTEGER,
1423 	.arg1_type	= ARG_PTR_TO_CTX,
1424 	.arg2_type	= ARG_CONST_MAP_PTR,
1425 	.arg3_type	= ARG_ANYTHING,
1426 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1427 	.arg5_type	= ARG_MEM_SIZE_OR_ZERO,
1428 };
1429 
1430 BPF_CALL_3(bpf_get_stackid_tp, void *, tp_buff, struct bpf_map *, map,
1431 	   u64, flags)
1432 {
1433 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1434 
1435 	/*
1436 	 * Same comment as in bpf_perf_event_output_tp(), only that this time
1437 	 * the other helper's function body cannot be inlined due to being
1438 	 * external, thus we need to call raw helper function.
1439 	 */
1440 	return bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1441 			       flags, 0, 0);
1442 }
1443 
1444 static const struct bpf_func_proto bpf_get_stackid_proto_tp = {
1445 	.func		= bpf_get_stackid_tp,
1446 	.gpl_only	= true,
1447 	.ret_type	= RET_INTEGER,
1448 	.arg1_type	= ARG_PTR_TO_CTX,
1449 	.arg2_type	= ARG_CONST_MAP_PTR,
1450 	.arg3_type	= ARG_ANYTHING,
1451 };
1452 
1453 BPF_CALL_4(bpf_get_stack_tp, void *, tp_buff, void *, buf, u32, size,
1454 	   u64, flags)
1455 {
1456 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1457 
1458 	return bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1459 			     (unsigned long) size, flags, 0);
1460 }
1461 
1462 static const struct bpf_func_proto bpf_get_stack_proto_tp = {
1463 	.func		= bpf_get_stack_tp,
1464 	.gpl_only	= true,
1465 	.ret_type	= RET_INTEGER,
1466 	.arg1_type	= ARG_PTR_TO_CTX,
1467 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
1468 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
1469 	.arg4_type	= ARG_ANYTHING,
1470 };
1471 
1472 static const struct bpf_func_proto *
1473 tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1474 {
1475 	switch (func_id) {
1476 	case BPF_FUNC_perf_event_output:
1477 		return &bpf_perf_event_output_proto_tp;
1478 	case BPF_FUNC_get_stackid:
1479 		return &bpf_get_stackid_proto_tp;
1480 	case BPF_FUNC_get_stack:
1481 		return &bpf_get_stack_proto_tp;
1482 	case BPF_FUNC_get_attach_cookie:
1483 		return &bpf_get_attach_cookie_proto_trace;
1484 	default:
1485 		return bpf_tracing_func_proto(func_id, prog);
1486 	}
1487 }
1488 
1489 static bool tp_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1490 				    const struct bpf_prog *prog,
1491 				    struct bpf_insn_access_aux *info)
1492 {
1493 	if (off < sizeof(void *) || off >= PERF_MAX_TRACE_SIZE)
1494 		return false;
1495 	if (type != BPF_READ)
1496 		return false;
1497 	if (off % size != 0)
1498 		return false;
1499 
1500 	BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(__u64));
1501 	return true;
1502 }
1503 
1504 const struct bpf_verifier_ops tracepoint_verifier_ops = {
1505 	.get_func_proto  = tp_prog_func_proto,
1506 	.is_valid_access = tp_prog_is_valid_access,
1507 };
1508 
1509 const struct bpf_prog_ops tracepoint_prog_ops = {
1510 };
1511 
1512 BPF_CALL_3(bpf_perf_prog_read_value, struct bpf_perf_event_data_kern *, ctx,
1513 	   struct bpf_perf_event_value *, buf, u32, size)
1514 {
1515 	int err = -EINVAL;
1516 
1517 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
1518 		goto clear;
1519 	err = perf_event_read_local(ctx->event, &buf->counter, &buf->enabled,
1520 				    &buf->running);
1521 	if (unlikely(err))
1522 		goto clear;
1523 	return 0;
1524 clear:
1525 	memset(buf, 0, size);
1526 	return err;
1527 }
1528 
1529 static const struct bpf_func_proto bpf_perf_prog_read_value_proto = {
1530 	.func           = bpf_perf_prog_read_value,
1531 	.gpl_only       = true,
1532 	.ret_type       = RET_INTEGER,
1533 	.arg1_type      = ARG_PTR_TO_CTX,
1534 	.arg2_type      = ARG_PTR_TO_UNINIT_MEM,
1535 	.arg3_type      = ARG_MEM_SIZE,
1536 };
1537 
1538 BPF_CALL_4(bpf_read_branch_records, struct bpf_perf_event_data_kern *, ctx,
1539 	   void *, buf, u32, size, u64, flags)
1540 {
1541 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1542 	struct perf_branch_stack *br_stack = ctx->data->br_stack;
1543 	u32 to_copy;
1544 
1545 	if (unlikely(flags & ~BPF_F_GET_BRANCH_RECORDS_SIZE))
1546 		return -EINVAL;
1547 
1548 	if (unlikely(!(ctx->data->sample_flags & PERF_SAMPLE_BRANCH_STACK)))
1549 		return -ENOENT;
1550 
1551 	if (unlikely(!br_stack))
1552 		return -ENOENT;
1553 
1554 	if (flags & BPF_F_GET_BRANCH_RECORDS_SIZE)
1555 		return br_stack->nr * br_entry_size;
1556 
1557 	if (!buf || (size % br_entry_size != 0))
1558 		return -EINVAL;
1559 
1560 	to_copy = min_t(u32, br_stack->nr * br_entry_size, size);
1561 	memcpy(buf, br_stack->entries, to_copy);
1562 
1563 	return to_copy;
1564 }
1565 
1566 static const struct bpf_func_proto bpf_read_branch_records_proto = {
1567 	.func           = bpf_read_branch_records,
1568 	.gpl_only       = true,
1569 	.ret_type       = RET_INTEGER,
1570 	.arg1_type      = ARG_PTR_TO_CTX,
1571 	.arg2_type      = ARG_PTR_TO_MEM_OR_NULL | MEM_UNINIT | MEM_WRITE,
1572 	.arg3_type      = ARG_MEM_SIZE_OR_ZERO,
1573 	.arg4_type      = ARG_ANYTHING,
1574 };
1575 
1576 static const struct bpf_func_proto *
1577 pe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1578 {
1579 	switch (func_id) {
1580 	case BPF_FUNC_perf_event_output:
1581 		return &bpf_perf_event_output_proto_tp;
1582 	case BPF_FUNC_get_stackid:
1583 		return &bpf_get_stackid_proto_pe;
1584 	case BPF_FUNC_get_stack:
1585 		return &bpf_get_stack_proto_pe;
1586 	case BPF_FUNC_perf_prog_read_value:
1587 		return &bpf_perf_prog_read_value_proto;
1588 	case BPF_FUNC_read_branch_records:
1589 		return &bpf_read_branch_records_proto;
1590 	case BPF_FUNC_get_attach_cookie:
1591 		return &bpf_get_attach_cookie_proto_pe;
1592 	default:
1593 		return bpf_tracing_func_proto(func_id, prog);
1594 	}
1595 }
1596 
1597 /*
1598  * bpf_raw_tp_regs are separate from bpf_pt_regs used from skb/xdp
1599  * to avoid potential recursive reuse issue when/if tracepoints are added
1600  * inside bpf_*_event_output, bpf_get_stackid and/or bpf_get_stack.
1601  *
1602  * Since raw tracepoints run despite bpf_prog_active, support concurrent usage
1603  * in normal, irq, and nmi context.
1604  */
1605 struct bpf_raw_tp_regs {
1606 	struct pt_regs regs[3];
1607 };
1608 static DEFINE_PER_CPU(struct bpf_raw_tp_regs, bpf_raw_tp_regs);
1609 static DEFINE_PER_CPU(int, bpf_raw_tp_nest_level);
1610 static struct pt_regs *get_bpf_raw_tp_regs(void)
1611 {
1612 	struct bpf_raw_tp_regs *tp_regs = this_cpu_ptr(&bpf_raw_tp_regs);
1613 	int nest_level = this_cpu_inc_return(bpf_raw_tp_nest_level);
1614 
1615 	if (nest_level > ARRAY_SIZE(tp_regs->regs)) {
1616 		this_cpu_dec(bpf_raw_tp_nest_level);
1617 		return ERR_PTR(-EBUSY);
1618 	}
1619 
1620 	return &tp_regs->regs[nest_level - 1];
1621 }
1622 
1623 static void put_bpf_raw_tp_regs(void)
1624 {
1625 	this_cpu_dec(bpf_raw_tp_nest_level);
1626 }
1627 
1628 BPF_CALL_5(bpf_perf_event_output_raw_tp, struct bpf_raw_tracepoint_args *, args,
1629 	   struct bpf_map *, map, u64, flags, void *, data, u64, size)
1630 {
1631 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1632 	int ret;
1633 
1634 	if (IS_ERR(regs))
1635 		return PTR_ERR(regs);
1636 
1637 	perf_fetch_caller_regs(regs);
1638 	ret = ____bpf_perf_event_output(regs, map, flags, data, size);
1639 
1640 	put_bpf_raw_tp_regs();
1641 	return ret;
1642 }
1643 
1644 static const struct bpf_func_proto bpf_perf_event_output_proto_raw_tp = {
1645 	.func		= bpf_perf_event_output_raw_tp,
1646 	.gpl_only	= true,
1647 	.ret_type	= RET_INTEGER,
1648 	.arg1_type	= ARG_PTR_TO_CTX,
1649 	.arg2_type	= ARG_CONST_MAP_PTR,
1650 	.arg3_type	= ARG_ANYTHING,
1651 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1652 	.arg5_type	= ARG_MEM_SIZE_OR_ZERO,
1653 };
1654 
1655 extern const struct bpf_func_proto bpf_skb_output_proto;
1656 extern const struct bpf_func_proto bpf_xdp_output_proto;
1657 extern const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto;
1658 
1659 BPF_CALL_3(bpf_get_stackid_raw_tp, struct bpf_raw_tracepoint_args *, args,
1660 	   struct bpf_map *, map, u64, flags)
1661 {
1662 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1663 	int ret;
1664 
1665 	if (IS_ERR(regs))
1666 		return PTR_ERR(regs);
1667 
1668 	perf_fetch_caller_regs(regs);
1669 	/* similar to bpf_perf_event_output_tp, but pt_regs fetched differently */
1670 	ret = bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1671 			      flags, 0, 0);
1672 	put_bpf_raw_tp_regs();
1673 	return ret;
1674 }
1675 
1676 static const struct bpf_func_proto bpf_get_stackid_proto_raw_tp = {
1677 	.func		= bpf_get_stackid_raw_tp,
1678 	.gpl_only	= true,
1679 	.ret_type	= RET_INTEGER,
1680 	.arg1_type	= ARG_PTR_TO_CTX,
1681 	.arg2_type	= ARG_CONST_MAP_PTR,
1682 	.arg3_type	= ARG_ANYTHING,
1683 };
1684 
1685 BPF_CALL_4(bpf_get_stack_raw_tp, struct bpf_raw_tracepoint_args *, args,
1686 	   void *, buf, u32, size, u64, flags)
1687 {
1688 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1689 	int ret;
1690 
1691 	if (IS_ERR(regs))
1692 		return PTR_ERR(regs);
1693 
1694 	perf_fetch_caller_regs(regs);
1695 	ret = bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1696 			    (unsigned long) size, flags, 0);
1697 	put_bpf_raw_tp_regs();
1698 	return ret;
1699 }
1700 
1701 static const struct bpf_func_proto bpf_get_stack_proto_raw_tp = {
1702 	.func		= bpf_get_stack_raw_tp,
1703 	.gpl_only	= true,
1704 	.ret_type	= RET_INTEGER,
1705 	.arg1_type	= ARG_PTR_TO_CTX,
1706 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
1707 	.arg3_type	= ARG_MEM_SIZE_OR_ZERO,
1708 	.arg4_type	= ARG_ANYTHING,
1709 };
1710 
1711 static const struct bpf_func_proto *
1712 raw_tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1713 {
1714 	switch (func_id) {
1715 	case BPF_FUNC_perf_event_output:
1716 		return &bpf_perf_event_output_proto_raw_tp;
1717 	case BPF_FUNC_get_stackid:
1718 		return &bpf_get_stackid_proto_raw_tp;
1719 	case BPF_FUNC_get_stack:
1720 		return &bpf_get_stack_proto_raw_tp;
1721 	case BPF_FUNC_get_attach_cookie:
1722 		return &bpf_get_attach_cookie_proto_tracing;
1723 	default:
1724 		return bpf_tracing_func_proto(func_id, prog);
1725 	}
1726 }
1727 
1728 const struct bpf_func_proto *
1729 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1730 {
1731 	const struct bpf_func_proto *fn;
1732 
1733 	switch (func_id) {
1734 #ifdef CONFIG_NET
1735 	case BPF_FUNC_skb_output:
1736 		return &bpf_skb_output_proto;
1737 	case BPF_FUNC_xdp_output:
1738 		return &bpf_xdp_output_proto;
1739 	case BPF_FUNC_skc_to_tcp6_sock:
1740 		return &bpf_skc_to_tcp6_sock_proto;
1741 	case BPF_FUNC_skc_to_tcp_sock:
1742 		return &bpf_skc_to_tcp_sock_proto;
1743 	case BPF_FUNC_skc_to_tcp_timewait_sock:
1744 		return &bpf_skc_to_tcp_timewait_sock_proto;
1745 	case BPF_FUNC_skc_to_tcp_request_sock:
1746 		return &bpf_skc_to_tcp_request_sock_proto;
1747 	case BPF_FUNC_skc_to_udp6_sock:
1748 		return &bpf_skc_to_udp6_sock_proto;
1749 	case BPF_FUNC_skc_to_unix_sock:
1750 		return &bpf_skc_to_unix_sock_proto;
1751 	case BPF_FUNC_skc_to_mptcp_sock:
1752 		return &bpf_skc_to_mptcp_sock_proto;
1753 	case BPF_FUNC_sk_storage_get:
1754 		return &bpf_sk_storage_get_tracing_proto;
1755 	case BPF_FUNC_sk_storage_delete:
1756 		return &bpf_sk_storage_delete_tracing_proto;
1757 	case BPF_FUNC_sock_from_file:
1758 		return &bpf_sock_from_file_proto;
1759 	case BPF_FUNC_get_socket_cookie:
1760 		return &bpf_get_socket_ptr_cookie_proto;
1761 	case BPF_FUNC_xdp_get_buff_len:
1762 		return &bpf_xdp_get_buff_len_trace_proto;
1763 #endif
1764 	case BPF_FUNC_seq_printf:
1765 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1766 		       &bpf_seq_printf_proto :
1767 		       NULL;
1768 	case BPF_FUNC_seq_write:
1769 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1770 		       &bpf_seq_write_proto :
1771 		       NULL;
1772 	case BPF_FUNC_seq_printf_btf:
1773 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1774 		       &bpf_seq_printf_btf_proto :
1775 		       NULL;
1776 	case BPF_FUNC_d_path:
1777 		return &bpf_d_path_proto;
1778 	case BPF_FUNC_get_func_arg:
1779 		if (bpf_prog_has_trampoline(prog) ||
1780 		    prog->expected_attach_type == BPF_TRACE_RAW_TP)
1781 			return &bpf_get_func_arg_proto;
1782 		return NULL;
1783 	case BPF_FUNC_get_func_ret:
1784 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_ret_proto : NULL;
1785 	case BPF_FUNC_get_func_arg_cnt:
1786 		if (bpf_prog_has_trampoline(prog) ||
1787 		    prog->expected_attach_type == BPF_TRACE_RAW_TP)
1788 			return &bpf_get_func_arg_cnt_proto;
1789 		return NULL;
1790 	case BPF_FUNC_get_attach_cookie:
1791 		if (prog->type == BPF_PROG_TYPE_TRACING &&
1792 		    prog->expected_attach_type == BPF_TRACE_RAW_TP)
1793 			return &bpf_get_attach_cookie_proto_tracing;
1794 		return bpf_prog_has_trampoline(prog) ? &bpf_get_attach_cookie_proto_tracing : NULL;
1795 	default:
1796 		fn = raw_tp_prog_func_proto(func_id, prog);
1797 		if (!fn && prog->expected_attach_type == BPF_TRACE_ITER)
1798 			fn = bpf_iter_get_func_proto(func_id, prog);
1799 		return fn;
1800 	}
1801 }
1802 
1803 static bool raw_tp_prog_is_valid_access(int off, int size,
1804 					enum bpf_access_type type,
1805 					const struct bpf_prog *prog,
1806 					struct bpf_insn_access_aux *info)
1807 {
1808 	return bpf_tracing_ctx_access(off, size, type);
1809 }
1810 
1811 static bool tracing_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_btf_ctx_access(off, size, type, prog, info);
1817 }
1818 
1819 int __weak bpf_prog_test_run_tracing(struct bpf_prog *prog,
1820 				     const union bpf_attr *kattr,
1821 				     union bpf_attr __user *uattr)
1822 {
1823 	return -ENOTSUPP;
1824 }
1825 
1826 const struct bpf_verifier_ops raw_tracepoint_verifier_ops = {
1827 	.get_func_proto  = raw_tp_prog_func_proto,
1828 	.is_valid_access = raw_tp_prog_is_valid_access,
1829 };
1830 
1831 const struct bpf_prog_ops raw_tracepoint_prog_ops = {
1832 #ifdef CONFIG_NET
1833 	.test_run = bpf_prog_test_run_raw_tp,
1834 #endif
1835 };
1836 
1837 const struct bpf_verifier_ops tracing_verifier_ops = {
1838 	.get_func_proto  = tracing_prog_func_proto,
1839 	.is_valid_access = tracing_prog_is_valid_access,
1840 };
1841 
1842 const struct bpf_prog_ops tracing_prog_ops = {
1843 	.test_run = bpf_prog_test_run_tracing,
1844 };
1845 
1846 static bool raw_tp_writable_prog_is_valid_access(int off, int size,
1847 						 enum bpf_access_type type,
1848 						 const struct bpf_prog *prog,
1849 						 struct bpf_insn_access_aux *info)
1850 {
1851 	if (off == 0) {
1852 		if (size != sizeof(u64) || type != BPF_READ)
1853 			return false;
1854 		info->reg_type = PTR_TO_TP_BUFFER;
1855 	}
1856 	return raw_tp_prog_is_valid_access(off, size, type, prog, info);
1857 }
1858 
1859 const struct bpf_verifier_ops raw_tracepoint_writable_verifier_ops = {
1860 	.get_func_proto  = raw_tp_prog_func_proto,
1861 	.is_valid_access = raw_tp_writable_prog_is_valid_access,
1862 };
1863 
1864 const struct bpf_prog_ops raw_tracepoint_writable_prog_ops = {
1865 };
1866 
1867 static bool pe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1868 				    const struct bpf_prog *prog,
1869 				    struct bpf_insn_access_aux *info)
1870 {
1871 	const int size_u64 = sizeof(u64);
1872 
1873 	if (off < 0 || off >= sizeof(struct bpf_perf_event_data))
1874 		return false;
1875 	if (type != BPF_READ)
1876 		return false;
1877 	if (off % size != 0) {
1878 		if (sizeof(unsigned long) != 4)
1879 			return false;
1880 		if (size != 8)
1881 			return false;
1882 		if (off % size != 4)
1883 			return false;
1884 	}
1885 
1886 	switch (off) {
1887 	case bpf_ctx_range(struct bpf_perf_event_data, sample_period):
1888 		bpf_ctx_record_field_size(info, size_u64);
1889 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
1890 			return false;
1891 		break;
1892 	case bpf_ctx_range(struct bpf_perf_event_data, addr):
1893 		bpf_ctx_record_field_size(info, size_u64);
1894 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
1895 			return false;
1896 		break;
1897 	default:
1898 		if (size != sizeof(long))
1899 			return false;
1900 	}
1901 
1902 	return true;
1903 }
1904 
1905 static u32 pe_prog_convert_ctx_access(enum bpf_access_type type,
1906 				      const struct bpf_insn *si,
1907 				      struct bpf_insn *insn_buf,
1908 				      struct bpf_prog *prog, u32 *target_size)
1909 {
1910 	struct bpf_insn *insn = insn_buf;
1911 
1912 	switch (si->off) {
1913 	case offsetof(struct bpf_perf_event_data, sample_period):
1914 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1915 						       data), si->dst_reg, si->src_reg,
1916 				      offsetof(struct bpf_perf_event_data_kern, data));
1917 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
1918 				      bpf_target_off(struct perf_sample_data, period, 8,
1919 						     target_size));
1920 		break;
1921 	case offsetof(struct bpf_perf_event_data, addr):
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, addr, 8,
1927 						     target_size));
1928 		break;
1929 	default:
1930 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1931 						       regs), si->dst_reg, si->src_reg,
1932 				      offsetof(struct bpf_perf_event_data_kern, regs));
1933 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(long), si->dst_reg, si->dst_reg,
1934 				      si->off);
1935 		break;
1936 	}
1937 
1938 	return insn - insn_buf;
1939 }
1940 
1941 const struct bpf_verifier_ops perf_event_verifier_ops = {
1942 	.get_func_proto		= pe_prog_func_proto,
1943 	.is_valid_access	= pe_prog_is_valid_access,
1944 	.convert_ctx_access	= pe_prog_convert_ctx_access,
1945 };
1946 
1947 const struct bpf_prog_ops perf_event_prog_ops = {
1948 };
1949 
1950 static DEFINE_MUTEX(bpf_event_mutex);
1951 
1952 #define BPF_TRACE_MAX_PROGS 64
1953 
1954 int perf_event_attach_bpf_prog(struct perf_event *event,
1955 			       struct bpf_prog *prog,
1956 			       u64 bpf_cookie)
1957 {
1958 	struct bpf_prog_array *old_array;
1959 	struct bpf_prog_array *new_array;
1960 	int ret = -EEXIST;
1961 
1962 	/*
1963 	 * Kprobe override only works if they are on the function entry,
1964 	 * and only if they are on the opt-in list.
1965 	 */
1966 	if (prog->kprobe_override &&
1967 	    (!trace_kprobe_on_func_entry(event->tp_event) ||
1968 	     !trace_kprobe_error_injectable(event->tp_event)))
1969 		return -EINVAL;
1970 
1971 	mutex_lock(&bpf_event_mutex);
1972 
1973 	if (event->prog)
1974 		goto unlock;
1975 
1976 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
1977 	if (old_array &&
1978 	    bpf_prog_array_length(old_array) >= BPF_TRACE_MAX_PROGS) {
1979 		ret = -E2BIG;
1980 		goto unlock;
1981 	}
1982 
1983 	ret = bpf_prog_array_copy(old_array, NULL, prog, bpf_cookie, &new_array);
1984 	if (ret < 0)
1985 		goto unlock;
1986 
1987 	/* set the new array to event->tp_event and set event->prog */
1988 	event->prog = prog;
1989 	event->bpf_cookie = bpf_cookie;
1990 	rcu_assign_pointer(event->tp_event->prog_array, new_array);
1991 	bpf_prog_array_free_sleepable(old_array);
1992 
1993 unlock:
1994 	mutex_unlock(&bpf_event_mutex);
1995 	return ret;
1996 }
1997 
1998 void perf_event_detach_bpf_prog(struct perf_event *event)
1999 {
2000 	struct bpf_prog_array *old_array;
2001 	struct bpf_prog_array *new_array;
2002 	struct bpf_prog *prog = NULL;
2003 	int ret;
2004 
2005 	mutex_lock(&bpf_event_mutex);
2006 
2007 	if (!event->prog)
2008 		goto unlock;
2009 
2010 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
2011 	if (!old_array)
2012 		goto put;
2013 
2014 	ret = bpf_prog_array_copy(old_array, event->prog, NULL, 0, &new_array);
2015 	if (ret < 0) {
2016 		bpf_prog_array_delete_safe(old_array, event->prog);
2017 	} else {
2018 		rcu_assign_pointer(event->tp_event->prog_array, new_array);
2019 		bpf_prog_array_free_sleepable(old_array);
2020 	}
2021 
2022 put:
2023 	prog = event->prog;
2024 	event->prog = NULL;
2025 
2026 unlock:
2027 	mutex_unlock(&bpf_event_mutex);
2028 
2029 	if (prog) {
2030 		/*
2031 		 * It could be that the bpf_prog is not sleepable (and will be freed
2032 		 * via normal RCU), but is called from a point that supports sleepable
2033 		 * programs and uses tasks-trace-RCU.
2034 		 */
2035 		synchronize_rcu_tasks_trace();
2036 
2037 		bpf_prog_put(prog);
2038 	}
2039 }
2040 
2041 int perf_event_query_prog_array(struct perf_event *event, void __user *info)
2042 {
2043 	struct perf_event_query_bpf __user *uquery = info;
2044 	struct perf_event_query_bpf query = {};
2045 	struct bpf_prog_array *progs;
2046 	u32 *ids, prog_cnt, ids_len;
2047 	int ret;
2048 
2049 	if (!perfmon_capable())
2050 		return -EPERM;
2051 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
2052 		return -EINVAL;
2053 	if (copy_from_user(&query, uquery, sizeof(query)))
2054 		return -EFAULT;
2055 
2056 	ids_len = query.ids_len;
2057 	if (ids_len > BPF_TRACE_MAX_PROGS)
2058 		return -E2BIG;
2059 	ids = kcalloc(ids_len, sizeof(u32), GFP_USER | __GFP_NOWARN);
2060 	if (!ids)
2061 		return -ENOMEM;
2062 	/*
2063 	 * The above kcalloc returns ZERO_SIZE_PTR when ids_len = 0, which
2064 	 * is required when user only wants to check for uquery->prog_cnt.
2065 	 * There is no need to check for it since the case is handled
2066 	 * gracefully in bpf_prog_array_copy_info.
2067 	 */
2068 
2069 	mutex_lock(&bpf_event_mutex);
2070 	progs = bpf_event_rcu_dereference(event->tp_event->prog_array);
2071 	ret = bpf_prog_array_copy_info(progs, ids, ids_len, &prog_cnt);
2072 	mutex_unlock(&bpf_event_mutex);
2073 
2074 	if (copy_to_user(&uquery->prog_cnt, &prog_cnt, sizeof(prog_cnt)) ||
2075 	    copy_to_user(uquery->ids, ids, ids_len * sizeof(u32)))
2076 		ret = -EFAULT;
2077 
2078 	kfree(ids);
2079 	return ret;
2080 }
2081 
2082 extern struct bpf_raw_event_map __start__bpf_raw_tp[];
2083 extern struct bpf_raw_event_map __stop__bpf_raw_tp[];
2084 
2085 struct bpf_raw_event_map *bpf_get_raw_tracepoint(const char *name)
2086 {
2087 	struct bpf_raw_event_map *btp = __start__bpf_raw_tp;
2088 
2089 	for (; btp < __stop__bpf_raw_tp; btp++) {
2090 		if (!strcmp(btp->tp->name, name))
2091 			return btp;
2092 	}
2093 
2094 	return bpf_get_raw_tracepoint_module(name);
2095 }
2096 
2097 void bpf_put_raw_tracepoint(struct bpf_raw_event_map *btp)
2098 {
2099 	struct module *mod;
2100 
2101 	guard(rcu)();
2102 	mod = __module_address((unsigned long)btp);
2103 	module_put(mod);
2104 }
2105 
2106 static __always_inline
2107 void __bpf_trace_run(struct bpf_raw_tp_link *link, u64 *args)
2108 {
2109 	struct srcu_ctr __percpu *scp = NULL;
2110 	struct bpf_prog *prog = link->link.prog;
2111 	bool sleepable = prog->sleepable;
2112 	struct bpf_run_ctx *old_run_ctx;
2113 	struct bpf_trace_run_ctx run_ctx;
2114 
2115 	if (sleepable) {
2116 		scp = rcu_read_lock_tasks_trace();
2117 		migrate_disable();
2118 	} else {
2119 		rcu_read_lock_dont_migrate();
2120 	}
2121 
2122 	if (unlikely(!bpf_prog_get_recursion_context(prog))) {
2123 		bpf_prog_inc_misses_counter(prog);
2124 		goto out;
2125 	}
2126 
2127 	run_ctx.bpf_cookie = link->cookie;
2128 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
2129 
2130 	(void)bpf_prog_run(prog, args);
2131 
2132 	bpf_reset_run_ctx(old_run_ctx);
2133 out:
2134 	bpf_prog_put_recursion_context(prog);
2135 
2136 	if (sleepable) {
2137 		migrate_enable();
2138 		rcu_read_unlock_tasks_trace(scp);
2139 	} else {
2140 		rcu_read_unlock_migrate();
2141 	}
2142 }
2143 
2144 #define UNPACK(...)			__VA_ARGS__
2145 #define REPEAT_1(FN, DL, X, ...)	FN(X)
2146 #define REPEAT_2(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_1(FN, DL, __VA_ARGS__)
2147 #define REPEAT_3(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_2(FN, DL, __VA_ARGS__)
2148 #define REPEAT_4(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_3(FN, DL, __VA_ARGS__)
2149 #define REPEAT_5(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_4(FN, DL, __VA_ARGS__)
2150 #define REPEAT_6(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_5(FN, DL, __VA_ARGS__)
2151 #define REPEAT_7(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_6(FN, DL, __VA_ARGS__)
2152 #define REPEAT_8(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_7(FN, DL, __VA_ARGS__)
2153 #define REPEAT_9(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_8(FN, DL, __VA_ARGS__)
2154 #define REPEAT_10(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_9(FN, DL, __VA_ARGS__)
2155 #define REPEAT_11(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_10(FN, DL, __VA_ARGS__)
2156 #define REPEAT_12(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_11(FN, DL, __VA_ARGS__)
2157 #define REPEAT(X, FN, DL, ...)		REPEAT_##X(FN, DL, __VA_ARGS__)
2158 
2159 #define SARG(X)		u64 arg##X
2160 #define COPY(X)		args[X] = arg##X
2161 
2162 #define __DL_COM	(,)
2163 #define __DL_SEM	(;)
2164 
2165 #define __SEQ_0_11	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
2166 
2167 #define BPF_TRACE_DEFN_x(x)						\
2168 	void bpf_trace_run##x(struct bpf_raw_tp_link *link,		\
2169 			      REPEAT(x, SARG, __DL_COM, __SEQ_0_11))	\
2170 	{								\
2171 		u64 args[x];						\
2172 		REPEAT(x, COPY, __DL_SEM, __SEQ_0_11);			\
2173 		__bpf_trace_run(link, args);				\
2174 	}								\
2175 	EXPORT_SYMBOL_GPL(bpf_trace_run##x)
2176 BPF_TRACE_DEFN_x(1);
2177 BPF_TRACE_DEFN_x(2);
2178 BPF_TRACE_DEFN_x(3);
2179 BPF_TRACE_DEFN_x(4);
2180 BPF_TRACE_DEFN_x(5);
2181 BPF_TRACE_DEFN_x(6);
2182 BPF_TRACE_DEFN_x(7);
2183 BPF_TRACE_DEFN_x(8);
2184 BPF_TRACE_DEFN_x(9);
2185 BPF_TRACE_DEFN_x(10);
2186 BPF_TRACE_DEFN_x(11);
2187 BPF_TRACE_DEFN_x(12);
2188 
2189 int bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_raw_tp_link *link)
2190 {
2191 	struct tracepoint *tp = btp->tp;
2192 	struct bpf_prog *prog = link->link.prog;
2193 
2194 	/*
2195 	 * check that program doesn't access arguments beyond what's
2196 	 * available in this tracepoint
2197 	 */
2198 	if (prog->aux->max_ctx_offset > btp->num_args * sizeof(u64))
2199 		return -EINVAL;
2200 
2201 	if (prog->aux->max_tp_access > btp->writable_size)
2202 		return -EINVAL;
2203 
2204 	return tracepoint_probe_register_may_exist(tp, (void *)btp->bpf_func, link);
2205 }
2206 
2207 int bpf_probe_unregister(struct bpf_raw_event_map *btp, struct bpf_raw_tp_link *link)
2208 {
2209 	return tracepoint_probe_unregister(btp->tp, (void *)btp->bpf_func, link);
2210 }
2211 
2212 /* On success the caller releases *buf with kfree_const() */
2213 int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id,
2214 			    u32 *fd_type, const char **buf,
2215 			    u64 *probe_offset, u64 *probe_addr,
2216 			    unsigned long *missed)
2217 {
2218 	bool is_tracepoint, is_syscall_tp;
2219 	struct bpf_prog *prog;
2220 	int flags, err = 0;
2221 
2222 	/*
2223 	 * The list of dynamic events is walked, and a probe which has siblings
2224 	 * can be deleted, with its strings, while its event is in use.
2225 	 */
2226 	guard(mutex)(&event_mutex);
2227 
2228 	prog = event->prog;
2229 	if (!prog)
2230 		return -ENOENT;
2231 
2232 	/* not supporting BPF_PROG_TYPE_PERF_EVENT yet */
2233 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT)
2234 		return -EOPNOTSUPP;
2235 
2236 	*prog_id = prog->aux->id;
2237 	flags = event->tp_event->flags;
2238 	is_tracepoint = flags & TRACE_EVENT_FL_TRACEPOINT;
2239 	is_syscall_tp = is_syscall_trace_event(event->tp_event);
2240 
2241 	if (is_tracepoint || is_syscall_tp) {
2242 		*buf = is_tracepoint ? event->tp_event->tp->name
2243 				     : event->tp_event->name;
2244 		/* We allow NULL pointer for tracepoint */
2245 		if (fd_type)
2246 			*fd_type = BPF_FD_TYPE_TRACEPOINT;
2247 		if (probe_offset)
2248 			*probe_offset = 0x0;
2249 		if (probe_addr)
2250 			*probe_addr = 0x0;
2251 	} else {
2252 		/* kprobe/uprobe */
2253 		err = -EOPNOTSUPP;
2254 #ifdef CONFIG_KPROBE_EVENTS
2255 		if (flags & TRACE_EVENT_FL_KPROBE)
2256 			err = bpf_get_kprobe_info(event, fd_type, buf,
2257 						  probe_offset, probe_addr, missed,
2258 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2259 #endif
2260 #ifdef CONFIG_UPROBE_EVENTS
2261 		if (flags & TRACE_EVENT_FL_UPROBE)
2262 			err = bpf_get_uprobe_info(event, fd_type, buf,
2263 						  probe_offset, probe_addr,
2264 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2265 #endif
2266 	}
2267 
2268 	if (!err && *buf) {
2269 		*buf = kstrdup_const(*buf, GFP_KERNEL);
2270 		if (!*buf)
2271 			err = -ENOMEM;
2272 	}
2273 
2274 	return err;
2275 }
2276 
2277 static int __init send_signal_irq_work_init(void)
2278 {
2279 	int cpu;
2280 	struct send_signal_irq_work *work;
2281 
2282 	for_each_possible_cpu(cpu) {
2283 		work = per_cpu_ptr(&send_signal_work, cpu);
2284 		init_irq_work(&work->irq_work, do_bpf_send_signal);
2285 	}
2286 	return 0;
2287 }
2288 
2289 subsys_initcall(send_signal_irq_work_init);
2290 
2291 #ifdef CONFIG_MODULES
2292 static int bpf_event_notify(struct notifier_block *nb, unsigned long op,
2293 			    void *module)
2294 {
2295 	struct bpf_trace_module *btm, *tmp;
2296 	struct module *mod = module;
2297 	int ret = 0;
2298 
2299 	if (mod->num_bpf_raw_events == 0 ||
2300 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
2301 		goto out;
2302 
2303 	mutex_lock(&bpf_module_mutex);
2304 
2305 	switch (op) {
2306 	case MODULE_STATE_COMING:
2307 		btm = kzalloc_obj(*btm);
2308 		if (btm) {
2309 			btm->module = module;
2310 			list_add(&btm->list, &bpf_trace_modules);
2311 		} else {
2312 			ret = -ENOMEM;
2313 		}
2314 		break;
2315 	case MODULE_STATE_GOING:
2316 		list_for_each_entry_safe(btm, tmp, &bpf_trace_modules, list) {
2317 			if (btm->module == module) {
2318 				list_del(&btm->list);
2319 				kfree(btm);
2320 				break;
2321 			}
2322 		}
2323 		break;
2324 	}
2325 
2326 	mutex_unlock(&bpf_module_mutex);
2327 
2328 out:
2329 	return notifier_from_errno(ret);
2330 }
2331 
2332 static struct notifier_block bpf_module_nb = {
2333 	.notifier_call = bpf_event_notify,
2334 };
2335 
2336 static int __init bpf_event_init(void)
2337 {
2338 	register_module_notifier(&bpf_module_nb);
2339 	return 0;
2340 }
2341 
2342 fs_initcall(bpf_event_init);
2343 #endif /* CONFIG_MODULES */
2344 
2345 struct bpf_session_run_ctx {
2346 	struct bpf_run_ctx run_ctx;
2347 	bool is_return;
2348 	void *data;
2349 };
2350 
2351 #ifdef CONFIG_FPROBE
2352 struct bpf_kprobe_multi_link {
2353 	struct bpf_link link;
2354 	struct fprobe fp;
2355 	unsigned long *addrs;
2356 	u64 *cookies;
2357 	u32 cnt;
2358 	u32 mods_cnt;
2359 	struct module **mods;
2360 };
2361 
2362 struct bpf_kprobe_multi_run_ctx {
2363 	struct bpf_session_run_ctx session_ctx;
2364 	struct bpf_kprobe_multi_link *link;
2365 	unsigned long entry_ip;
2366 };
2367 
2368 struct user_syms {
2369 	const char **syms;
2370 	char *buf;
2371 };
2372 
2373 #ifndef CONFIG_HAVE_FTRACE_REGS_HAVING_PT_REGS
2374 static DEFINE_PER_CPU(struct pt_regs, bpf_kprobe_multi_pt_regs);
2375 #define bpf_kprobe_multi_pt_regs_ptr()	this_cpu_ptr(&bpf_kprobe_multi_pt_regs)
2376 #else
2377 #define bpf_kprobe_multi_pt_regs_ptr()	(NULL)
2378 #endif
2379 
2380 static unsigned long ftrace_get_entry_ip(unsigned long fentry_ip)
2381 {
2382 	unsigned long ip = ftrace_get_symaddr(fentry_ip);
2383 
2384 	return ip ? : fentry_ip;
2385 }
2386 
2387 static int copy_user_syms(struct user_syms *us, unsigned long __user *usyms, u32 cnt)
2388 {
2389 	unsigned long __user usymbol;
2390 	const char **syms = NULL;
2391 	char *buf = NULL, *p;
2392 	int err = -ENOMEM;
2393 	unsigned int i;
2394 
2395 	if (!access_ok(usyms, cnt * sizeof(*usyms)))
2396 		return -EFAULT;
2397 
2398 	syms = kvmalloc_array(cnt, sizeof(*syms), GFP_KERNEL);
2399 	if (!syms)
2400 		return -ENOMEM;
2401 
2402 	buf = kvmalloc_array(cnt, KSYM_NAME_LEN, GFP_KERNEL);
2403 	if (!buf)
2404 		goto error;
2405 
2406 	for (p = buf, i = 0; i < cnt; i++) {
2407 		if (get_user(usymbol, usyms + i)) {
2408 			err = -EFAULT;
2409 			goto error;
2410 		}
2411 		err = strncpy_from_user(p, (const char __user *) usymbol, KSYM_NAME_LEN);
2412 		if (err == KSYM_NAME_LEN)
2413 			err = -E2BIG;
2414 		if (err < 0)
2415 			goto error;
2416 		syms[i] = p;
2417 		p += err + 1;
2418 	}
2419 
2420 	us->syms = syms;
2421 	us->buf = buf;
2422 	return 0;
2423 
2424 error:
2425 	kvfree(syms);
2426 	kvfree(buf);
2427 	return err;
2428 }
2429 
2430 static void kprobe_multi_put_modules(struct module **mods, u32 cnt)
2431 {
2432 	u32 i;
2433 
2434 	for (i = 0; i < cnt; i++)
2435 		module_put(mods[i]);
2436 }
2437 
2438 static void free_user_syms(struct user_syms *us)
2439 {
2440 	kvfree(us->syms);
2441 	kvfree(us->buf);
2442 }
2443 
2444 static void bpf_kprobe_multi_link_release(struct bpf_link *link)
2445 {
2446 	struct bpf_kprobe_multi_link *kmulti_link;
2447 
2448 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2449 	/* Don't wait for RCU GP here. */
2450 	unregister_fprobe_async(&kmulti_link->fp);
2451 	kprobe_multi_put_modules(kmulti_link->mods, kmulti_link->mods_cnt);
2452 }
2453 
2454 static void bpf_kprobe_multi_link_dealloc(struct bpf_link *link)
2455 {
2456 	struct bpf_kprobe_multi_link *kmulti_link;
2457 
2458 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2459 	kvfree(kmulti_link->addrs);
2460 	kvfree(kmulti_link->cookies);
2461 	kfree(kmulti_link->mods);
2462 	kfree(kmulti_link);
2463 }
2464 
2465 static int bpf_kprobe_multi_link_fill_link_info(const struct bpf_link *link,
2466 						struct bpf_link_info *info)
2467 {
2468 	u64 __user *ucookies = u64_to_user_ptr(info->kprobe_multi.cookies);
2469 	u64 __user *uaddrs = u64_to_user_ptr(info->kprobe_multi.addrs);
2470 	struct bpf_kprobe_multi_link *kmulti_link;
2471 	u32 ucount = info->kprobe_multi.count;
2472 	int err = 0, i;
2473 
2474 	if (!uaddrs ^ !ucount)
2475 		return -EINVAL;
2476 	if (ucookies && !ucount)
2477 		return -EINVAL;
2478 
2479 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2480 	info->kprobe_multi.count = kmulti_link->cnt;
2481 	info->kprobe_multi.flags = kmulti_link->link.flags;
2482 	info->kprobe_multi.missed = kmulti_link->fp.nmissed;
2483 
2484 	if (!uaddrs)
2485 		return 0;
2486 	if (ucount < kmulti_link->cnt)
2487 		err = -ENOSPC;
2488 	else
2489 		ucount = kmulti_link->cnt;
2490 
2491 	if (ucookies) {
2492 		if (kmulti_link->cookies) {
2493 			if (copy_to_user(ucookies, kmulti_link->cookies, ucount * sizeof(u64)))
2494 				return -EFAULT;
2495 		} else {
2496 			for (i = 0; i < ucount; i++) {
2497 				if (put_user(0, ucookies + i))
2498 					return -EFAULT;
2499 			}
2500 		}
2501 	}
2502 
2503 	if (kallsyms_show_value(current_cred())) {
2504 		if (copy_to_user(uaddrs, kmulti_link->addrs, ucount * sizeof(u64)))
2505 			return -EFAULT;
2506 	} else {
2507 		for (i = 0; i < ucount; i++) {
2508 			if (put_user(0, uaddrs + i))
2509 				return -EFAULT;
2510 		}
2511 	}
2512 	return err;
2513 }
2514 
2515 #ifdef CONFIG_PROC_FS
2516 static void bpf_kprobe_multi_show_fdinfo(const struct bpf_link *link,
2517 					 struct seq_file *seq)
2518 {
2519 	struct bpf_kprobe_multi_link *kmulti_link;
2520 	bool has_cookies;
2521 
2522 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2523 	has_cookies = !!kmulti_link->cookies;
2524 
2525 	seq_printf(seq,
2526 		   "kprobe_cnt:\t%u\n"
2527 		   "missed:\t%lu\n",
2528 		   kmulti_link->cnt,
2529 		   kmulti_link->fp.nmissed);
2530 
2531 	seq_printf(seq, "%s\t %s\n", "cookie", "func");
2532 	for (int i = 0; i < kmulti_link->cnt; i++) {
2533 		seq_printf(seq,
2534 			   "%llu\t %pS\n",
2535 			   has_cookies ? kmulti_link->cookies[i] : 0,
2536 			   (void *)kmulti_link->addrs[i]);
2537 	}
2538 }
2539 #endif
2540 
2541 static const struct bpf_link_ops bpf_kprobe_multi_link_lops = {
2542 	.release = bpf_kprobe_multi_link_release,
2543 	.dealloc_deferred = bpf_kprobe_multi_link_dealloc,
2544 	.fill_link_info = bpf_kprobe_multi_link_fill_link_info,
2545 #ifdef CONFIG_PROC_FS
2546 	.show_fdinfo = bpf_kprobe_multi_show_fdinfo,
2547 #endif
2548 };
2549 
2550 static void bpf_kprobe_multi_cookie_swap(void *a, void *b, int size, const void *priv)
2551 {
2552 	const struct bpf_kprobe_multi_link *link = priv;
2553 	unsigned long *addr_a = a, *addr_b = b;
2554 	u64 *cookie_a, *cookie_b;
2555 
2556 	cookie_a = link->cookies + (addr_a - link->addrs);
2557 	cookie_b = link->cookies + (addr_b - link->addrs);
2558 
2559 	/* swap addr_a/addr_b and cookie_a/cookie_b values */
2560 	swap(*addr_a, *addr_b);
2561 	swap(*cookie_a, *cookie_b);
2562 }
2563 
2564 static int bpf_kprobe_multi_addrs_cmp(const void *a, const void *b)
2565 {
2566 	const unsigned long *addr_a = a, *addr_b = b;
2567 
2568 	if (*addr_a == *addr_b)
2569 		return 0;
2570 	return *addr_a < *addr_b ? -1 : 1;
2571 }
2572 
2573 static int bpf_kprobe_multi_cookie_cmp(const void *a, const void *b, const void *priv)
2574 {
2575 	return bpf_kprobe_multi_addrs_cmp(a, b);
2576 }
2577 
2578 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx)
2579 {
2580 	struct bpf_kprobe_multi_run_ctx *run_ctx;
2581 	struct bpf_kprobe_multi_link *link;
2582 	u64 *cookie, entry_ip;
2583 	unsigned long *addr;
2584 
2585 	if (WARN_ON_ONCE(!ctx))
2586 		return 0;
2587 	run_ctx = container_of(current->bpf_ctx, struct bpf_kprobe_multi_run_ctx,
2588 			       session_ctx.run_ctx);
2589 	link = run_ctx->link;
2590 	if (!link->cookies)
2591 		return 0;
2592 	entry_ip = run_ctx->entry_ip;
2593 	addr = bsearch(&entry_ip, link->addrs, link->cnt, sizeof(entry_ip),
2594 		       bpf_kprobe_multi_addrs_cmp);
2595 	if (!addr)
2596 		return 0;
2597 	cookie = link->cookies + (addr - link->addrs);
2598 	return *cookie;
2599 }
2600 
2601 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
2602 {
2603 	struct bpf_kprobe_multi_run_ctx *run_ctx;
2604 
2605 	run_ctx = container_of(current->bpf_ctx, struct bpf_kprobe_multi_run_ctx,
2606 			       session_ctx.run_ctx);
2607 	return run_ctx->entry_ip;
2608 }
2609 
2610 static __always_inline int
2611 kprobe_multi_link_prog_run(struct bpf_kprobe_multi_link *link,
2612 			   unsigned long entry_ip, struct ftrace_regs *fregs,
2613 			   bool is_return, void *data)
2614 {
2615 	struct bpf_kprobe_multi_run_ctx run_ctx = {
2616 		.session_ctx = {
2617 			.is_return = is_return,
2618 			.data = data,
2619 		},
2620 		.link = link,
2621 		.entry_ip = entry_ip,
2622 	};
2623 	struct bpf_run_ctx *old_run_ctx;
2624 	struct pt_regs *regs;
2625 	int err;
2626 
2627 	/*
2628 	 * graph tracer framework ensures we won't migrate, so there is no need
2629 	 * to use migrate_disable for bpf_prog_run again. The check here just for
2630 	 * __this_cpu_inc_return.
2631 	 */
2632 	cant_sleep();
2633 
2634 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
2635 		bpf_prog_inc_misses_counter(link->link.prog);
2636 		err = 1;
2637 		goto out;
2638 	}
2639 
2640 	rcu_read_lock();
2641 	regs = ftrace_partial_regs(fregs, bpf_kprobe_multi_pt_regs_ptr());
2642 	old_run_ctx = bpf_set_run_ctx(&run_ctx.session_ctx.run_ctx);
2643 	err = bpf_prog_run(link->link.prog, regs);
2644 	bpf_reset_run_ctx(old_run_ctx);
2645 	ftrace_partial_regs_update(fregs, bpf_kprobe_multi_pt_regs_ptr());
2646 	rcu_read_unlock();
2647 
2648  out:
2649 	__this_cpu_dec(bpf_prog_active);
2650 	return err;
2651 }
2652 
2653 static int
2654 kprobe_multi_link_handler(struct fprobe *fp, unsigned long fentry_ip,
2655 			  unsigned long ret_ip, struct ftrace_regs *fregs,
2656 			  void *data)
2657 {
2658 	struct bpf_kprobe_multi_link *link;
2659 	int err;
2660 
2661 	link = container_of(fp, struct bpf_kprobe_multi_link, fp);
2662 	err = kprobe_multi_link_prog_run(link, ftrace_get_entry_ip(fentry_ip),
2663 					 fregs, false, data);
2664 	return is_kprobe_session(link->link.prog) ? err : 0;
2665 }
2666 
2667 static void
2668 kprobe_multi_link_exit_handler(struct fprobe *fp, unsigned long fentry_ip,
2669 			       unsigned long ret_ip, struct ftrace_regs *fregs,
2670 			       void *data)
2671 {
2672 	struct bpf_kprobe_multi_link *link;
2673 
2674 	link = container_of(fp, struct bpf_kprobe_multi_link, fp);
2675 	kprobe_multi_link_prog_run(link, ftrace_get_entry_ip(fentry_ip),
2676 				   fregs, true, data);
2677 }
2678 
2679 static int symbols_cmp_r(const void *a, const void *b, const void *priv)
2680 {
2681 	const char **str_a = (const char **) a;
2682 	const char **str_b = (const char **) b;
2683 
2684 	return strcmp(*str_a, *str_b);
2685 }
2686 
2687 struct multi_symbols_sort {
2688 	const char **funcs;
2689 	u64 *cookies;
2690 };
2691 
2692 static void symbols_swap_r(void *a, void *b, int size, const void *priv)
2693 {
2694 	const struct multi_symbols_sort *data = priv;
2695 	const char **name_a = a, **name_b = b;
2696 
2697 	swap(*name_a, *name_b);
2698 
2699 	/* If defined, swap also related cookies. */
2700 	if (data->cookies) {
2701 		u64 *cookie_a, *cookie_b;
2702 
2703 		cookie_a = data->cookies + (name_a - data->funcs);
2704 		cookie_b = data->cookies + (name_b - data->funcs);
2705 		swap(*cookie_a, *cookie_b);
2706 	}
2707 }
2708 
2709 struct modules_array {
2710 	struct module **mods;
2711 	int mods_cnt;
2712 	int mods_cap;
2713 };
2714 
2715 static int add_module(struct modules_array *arr, struct module *mod)
2716 {
2717 	struct module **mods;
2718 
2719 	if (arr->mods_cnt == arr->mods_cap) {
2720 		arr->mods_cap = max(16, arr->mods_cap * 3 / 2);
2721 		mods = krealloc_array(arr->mods, arr->mods_cap, sizeof(*mods), GFP_KERNEL);
2722 		if (!mods)
2723 			return -ENOMEM;
2724 		arr->mods = mods;
2725 	}
2726 
2727 	arr->mods[arr->mods_cnt] = mod;
2728 	arr->mods_cnt++;
2729 	return 0;
2730 }
2731 
2732 static bool has_module(struct modules_array *arr, struct module *mod)
2733 {
2734 	int i;
2735 
2736 	for (i = arr->mods_cnt - 1; i >= 0; i--) {
2737 		if (arr->mods[i] == mod)
2738 			return true;
2739 	}
2740 	return false;
2741 }
2742 
2743 static int get_modules_for_addrs(struct module ***mods, unsigned long *addrs, u32 addrs_cnt)
2744 {
2745 	struct modules_array arr = {};
2746 	u32 i, err = 0;
2747 
2748 	for (i = 0; i < addrs_cnt; i++) {
2749 		bool skip_add = false;
2750 		struct module *mod;
2751 
2752 		scoped_guard(rcu) {
2753 			mod = __module_address(addrs[i]);
2754 			/* Either no module or it's already stored  */
2755 			if (!mod || has_module(&arr, mod)) {
2756 				skip_add = true;
2757 				break; /* scoped_guard */
2758 			}
2759 			if (!try_module_get(mod))
2760 				err = -EINVAL;
2761 		}
2762 		if (skip_add)
2763 			continue;
2764 		if (err)
2765 			break;
2766 		err = add_module(&arr, mod);
2767 		if (err) {
2768 			module_put(mod);
2769 			break;
2770 		}
2771 	}
2772 
2773 	/* We return either err < 0 in case of error, ... */
2774 	if (err) {
2775 		kprobe_multi_put_modules(arr.mods, arr.mods_cnt);
2776 		kfree(arr.mods);
2777 		return err;
2778 	}
2779 
2780 	/* or number of modules found if everything is ok. */
2781 	*mods = arr.mods;
2782 	return arr.mods_cnt;
2783 }
2784 
2785 static int addrs_check_error_injection_list(unsigned long *addrs, u32 cnt)
2786 {
2787 	u32 i;
2788 
2789 	for (i = 0; i < cnt; i++) {
2790 		if (!within_error_injection_list(addrs[i]))
2791 			return -EINVAL;
2792 	}
2793 	return 0;
2794 }
2795 
2796 int bpf_kprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
2797 {
2798 	struct bpf_kprobe_multi_link *link = NULL;
2799 	struct bpf_link_primer link_primer;
2800 	void __user *ucookies;
2801 	unsigned long *addrs;
2802 	u32 flags, cnt, size;
2803 	void __user *uaddrs;
2804 	u64 *cookies = NULL;
2805 	void __user *usyms;
2806 	int err;
2807 
2808 	/* no support for 32bit archs yet */
2809 	if (sizeof(u64) != sizeof(void *))
2810 		return -EOPNOTSUPP;
2811 
2812 	if (attr->link_create.flags)
2813 		return -EINVAL;
2814 
2815 	if (!is_kprobe_multi(prog))
2816 		return -EINVAL;
2817 
2818 	/* kprobe_multi is not allowed to be sleepable. */
2819 	if (prog->sleepable)
2820 		return -EINVAL;
2821 
2822 	/* Writing to context is not allowed for kprobes. */
2823 	if (prog->aux->kprobe_write_ctx)
2824 		return -EINVAL;
2825 
2826 	flags = attr->link_create.kprobe_multi.flags;
2827 	if (flags & ~BPF_F_KPROBE_MULTI_RETURN)
2828 		return -EINVAL;
2829 
2830 	uaddrs = u64_to_user_ptr(attr->link_create.kprobe_multi.addrs);
2831 	usyms = u64_to_user_ptr(attr->link_create.kprobe_multi.syms);
2832 	if (!!uaddrs == !!usyms)
2833 		return -EINVAL;
2834 
2835 	cnt = attr->link_create.kprobe_multi.cnt;
2836 	if (!cnt)
2837 		return -EINVAL;
2838 	if (cnt > MAX_KPROBE_MULTI_CNT)
2839 		return -E2BIG;
2840 
2841 	size = cnt * sizeof(*addrs);
2842 	addrs = kvmalloc_array(cnt, sizeof(*addrs), GFP_KERNEL);
2843 	if (!addrs)
2844 		return -ENOMEM;
2845 
2846 	ucookies = u64_to_user_ptr(attr->link_create.kprobe_multi.cookies);
2847 	if (ucookies) {
2848 		cookies = kvmalloc_array(cnt, sizeof(*addrs), GFP_KERNEL);
2849 		if (!cookies) {
2850 			err = -ENOMEM;
2851 			goto error;
2852 		}
2853 		if (copy_from_user(cookies, ucookies, size)) {
2854 			err = -EFAULT;
2855 			goto error;
2856 		}
2857 	}
2858 
2859 	if (uaddrs) {
2860 		if (copy_from_user(addrs, uaddrs, size)) {
2861 			err = -EFAULT;
2862 			goto error;
2863 		}
2864 	} else {
2865 		struct multi_symbols_sort data = {
2866 			.cookies = cookies,
2867 		};
2868 		struct user_syms us;
2869 
2870 		err = copy_user_syms(&us, usyms, cnt);
2871 		if (err)
2872 			goto error;
2873 
2874 		if (cookies)
2875 			data.funcs = us.syms;
2876 
2877 		sort_r(us.syms, cnt, sizeof(*us.syms), symbols_cmp_r,
2878 		       symbols_swap_r, &data);
2879 
2880 		err = ftrace_lookup_symbols(us.syms, cnt, addrs);
2881 		free_user_syms(&us);
2882 		if (err)
2883 			goto error;
2884 	}
2885 
2886 	if (prog->kprobe_override && addrs_check_error_injection_list(addrs, cnt)) {
2887 		err = -EINVAL;
2888 		goto error;
2889 	}
2890 
2891 	link = kzalloc_obj(*link);
2892 	if (!link) {
2893 		err = -ENOMEM;
2894 		goto error;
2895 	}
2896 
2897 	bpf_link_init(&link->link, BPF_LINK_TYPE_KPROBE_MULTI,
2898 		      &bpf_kprobe_multi_link_lops, prog, attr->link_create.attach_type);
2899 
2900 	err = bpf_link_prime(&link->link, &link_primer);
2901 	if (err)
2902 		goto error;
2903 
2904 	if (!(flags & BPF_F_KPROBE_MULTI_RETURN))
2905 		link->fp.entry_handler = kprobe_multi_link_handler;
2906 	if ((flags & BPF_F_KPROBE_MULTI_RETURN) || is_kprobe_session(prog))
2907 		link->fp.exit_handler = kprobe_multi_link_exit_handler;
2908 	if (is_kprobe_session(prog))
2909 		link->fp.entry_data_size = sizeof(u64);
2910 
2911 	link->addrs = addrs;
2912 	link->cookies = cookies;
2913 	link->cnt = cnt;
2914 	link->link.flags = flags;
2915 
2916 	if (cookies) {
2917 		/*
2918 		 * Sorting addresses will trigger sorting cookies as well
2919 		 * (check bpf_kprobe_multi_cookie_swap). This way we can
2920 		 * find cookie based on the address in bpf_get_attach_cookie
2921 		 * helper.
2922 		 */
2923 		sort_r(addrs, cnt, sizeof(*addrs),
2924 		       bpf_kprobe_multi_cookie_cmp,
2925 		       bpf_kprobe_multi_cookie_swap,
2926 		       link);
2927 	}
2928 
2929 	err = get_modules_for_addrs(&link->mods, addrs, cnt);
2930 	if (err < 0) {
2931 		bpf_link_cleanup(&link_primer);
2932 		return err;
2933 	}
2934 	link->mods_cnt = err;
2935 
2936 	err = register_fprobe_ips(&link->fp, addrs, cnt);
2937 	if (err) {
2938 		kprobe_multi_put_modules(link->mods, link->mods_cnt);
2939 		bpf_link_cleanup(&link_primer);
2940 		return err;
2941 	}
2942 
2943 	return bpf_link_settle(&link_primer);
2944 
2945 error:
2946 	kfree(link);
2947 	kvfree(addrs);
2948 	kvfree(cookies);
2949 	return err;
2950 }
2951 #else /* !CONFIG_FPROBE */
2952 int bpf_kprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
2953 {
2954 	return -EOPNOTSUPP;
2955 }
2956 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx)
2957 {
2958 	return 0;
2959 }
2960 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
2961 {
2962 	return 0;
2963 }
2964 #endif
2965 
2966 #ifdef CONFIG_UPROBES
2967 struct bpf_uprobe_multi_link;
2968 
2969 struct bpf_uprobe {
2970 	struct bpf_uprobe_multi_link *link;
2971 	loff_t offset;
2972 	unsigned long ref_ctr_offset;
2973 	u64 cookie;
2974 	struct uprobe *uprobe;
2975 	struct uprobe_consumer consumer;
2976 	bool session;
2977 };
2978 
2979 struct bpf_uprobe_multi_link {
2980 	struct path path;
2981 	struct bpf_link link;
2982 	u32 cnt;
2983 	struct bpf_uprobe *uprobes;
2984 	struct task_struct *task;
2985 };
2986 
2987 struct bpf_uprobe_multi_run_ctx {
2988 	struct bpf_session_run_ctx session_ctx;
2989 	unsigned long entry_ip;
2990 	struct bpf_uprobe *uprobe;
2991 };
2992 
2993 static void bpf_uprobe_unregister(struct bpf_uprobe *uprobes, u32 cnt)
2994 {
2995 	u32 i;
2996 
2997 	for (i = 0; i < cnt; i++)
2998 		uprobe_unregister_nosync(uprobes[i].uprobe, &uprobes[i].consumer);
2999 
3000 	if (cnt)
3001 		uprobe_unregister_sync();
3002 }
3003 
3004 static void bpf_uprobe_multi_link_release(struct bpf_link *link)
3005 {
3006 	struct bpf_uprobe_multi_link *umulti_link;
3007 
3008 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3009 	bpf_uprobe_unregister(umulti_link->uprobes, umulti_link->cnt);
3010 	if (umulti_link->task)
3011 		put_task_struct(umulti_link->task);
3012 	path_put(&umulti_link->path);
3013 }
3014 
3015 static void bpf_uprobe_multi_link_dealloc(struct bpf_link *link)
3016 {
3017 	struct bpf_uprobe_multi_link *umulti_link;
3018 
3019 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3020 	kvfree(umulti_link->uprobes);
3021 	kfree(umulti_link);
3022 }
3023 
3024 static int bpf_uprobe_multi_link_fill_link_info(const struct bpf_link *link,
3025 						struct bpf_link_info *info)
3026 {
3027 	u64 __user *uref_ctr_offsets = u64_to_user_ptr(info->uprobe_multi.ref_ctr_offsets);
3028 	u64 __user *ucookies = u64_to_user_ptr(info->uprobe_multi.cookies);
3029 	u64 __user *uoffsets = u64_to_user_ptr(info->uprobe_multi.offsets);
3030 	u64 __user *upath = u64_to_user_ptr(info->uprobe_multi.path);
3031 	u32 upath_size = info->uprobe_multi.path_size;
3032 	struct bpf_uprobe_multi_link *umulti_link;
3033 	u32 ucount = info->uprobe_multi.count;
3034 	int err = 0, i;
3035 	char *p, *buf;
3036 	long left = 0;
3037 
3038 	if (!upath ^ !upath_size)
3039 		return -EINVAL;
3040 
3041 	if ((uoffsets || uref_ctr_offsets || ucookies) && !ucount)
3042 		return -EINVAL;
3043 
3044 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3045 	info->uprobe_multi.count = umulti_link->cnt;
3046 	info->uprobe_multi.flags = umulti_link->link.flags;
3047 	info->uprobe_multi.pid = umulti_link->task ?
3048 				 task_pid_nr_ns(umulti_link->task, task_active_pid_ns(current)) : 0;
3049 
3050 	upath_size = upath_size ? min_t(u32, upath_size, PATH_MAX) : PATH_MAX;
3051 	buf = kmalloc(upath_size, GFP_KERNEL);
3052 	if (!buf)
3053 		return -ENOMEM;
3054 	p = d_path(&umulti_link->path, buf, upath_size);
3055 	if (IS_ERR(p)) {
3056 		kfree(buf);
3057 		return PTR_ERR(p);
3058 	}
3059 	upath_size = buf + upath_size - p;
3060 
3061 	if (upath)
3062 		left = copy_to_user(upath, p, upath_size);
3063 	kfree(buf);
3064 	if (left)
3065 		return -EFAULT;
3066 	info->uprobe_multi.path_size = upath_size;
3067 
3068 	if (!uoffsets && !ucookies && !uref_ctr_offsets)
3069 		return 0;
3070 
3071 	if (ucount < umulti_link->cnt)
3072 		err = -ENOSPC;
3073 	else
3074 		ucount = umulti_link->cnt;
3075 
3076 	for (i = 0; i < ucount; i++) {
3077 		if (uoffsets &&
3078 		    put_user(umulti_link->uprobes[i].offset, uoffsets + i))
3079 			return -EFAULT;
3080 		if (uref_ctr_offsets &&
3081 		    put_user(umulti_link->uprobes[i].ref_ctr_offset, uref_ctr_offsets + i))
3082 			return -EFAULT;
3083 		if (ucookies &&
3084 		    put_user(umulti_link->uprobes[i].cookie, ucookies + i))
3085 			return -EFAULT;
3086 	}
3087 
3088 	return err;
3089 }
3090 
3091 #ifdef CONFIG_PROC_FS
3092 static void bpf_uprobe_multi_show_fdinfo(const struct bpf_link *link,
3093 					 struct seq_file *seq)
3094 {
3095 	struct bpf_uprobe_multi_link *umulti_link;
3096 	char *p, *buf;
3097 	pid_t pid;
3098 
3099 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3100 
3101 	buf = kmalloc(PATH_MAX, GFP_KERNEL);
3102 	if (!buf)
3103 		return;
3104 
3105 	p = d_path(&umulti_link->path, buf, PATH_MAX);
3106 	if (IS_ERR(p)) {
3107 		kfree(buf);
3108 		return;
3109 	}
3110 
3111 	pid = umulti_link->task ?
3112 	      task_pid_nr_ns(umulti_link->task, task_active_pid_ns(current)) : 0;
3113 	seq_printf(seq,
3114 		   "uprobe_cnt:\t%u\n"
3115 		   "pid:\t%u\n"
3116 		   "path:\t%s\n",
3117 		   umulti_link->cnt, pid, p);
3118 
3119 	seq_printf(seq, "%s\t %s\t %s\n", "cookie", "offset", "ref_ctr_offset");
3120 	for (int i = 0; i < umulti_link->cnt; i++) {
3121 		seq_printf(seq,
3122 			   "%llu\t %#llx\t %#lx\n",
3123 			   umulti_link->uprobes[i].cookie,
3124 			   umulti_link->uprobes[i].offset,
3125 			   umulti_link->uprobes[i].ref_ctr_offset);
3126 	}
3127 
3128 	kfree(buf);
3129 }
3130 #endif
3131 
3132 static const struct bpf_link_ops bpf_uprobe_multi_link_lops = {
3133 	.release = bpf_uprobe_multi_link_release,
3134 	.dealloc_deferred = bpf_uprobe_multi_link_dealloc,
3135 	.fill_link_info = bpf_uprobe_multi_link_fill_link_info,
3136 #ifdef CONFIG_PROC_FS
3137 	.show_fdinfo = bpf_uprobe_multi_show_fdinfo,
3138 #endif
3139 };
3140 
3141 static int uprobe_prog_run(struct bpf_uprobe *uprobe,
3142 			   unsigned long entry_ip,
3143 			   struct pt_regs *regs,
3144 			   bool is_return, void *data)
3145 {
3146 	struct bpf_uprobe_multi_link *link = uprobe->link;
3147 	struct bpf_uprobe_multi_run_ctx run_ctx = {
3148 		.session_ctx = {
3149 			.is_return = is_return,
3150 			.data = data,
3151 		},
3152 		.entry_ip = entry_ip,
3153 		.uprobe = uprobe,
3154 	};
3155 	struct bpf_prog *prog = link->link.prog;
3156 	bool sleepable = prog->sleepable;
3157 	struct bpf_run_ctx *old_run_ctx;
3158 	int err;
3159 
3160 	if (link->task && !same_thread_group(current, link->task))
3161 		return 0;
3162 
3163 	if (sleepable)
3164 		rcu_read_lock_trace();
3165 	else
3166 		rcu_read_lock();
3167 
3168 	migrate_disable();
3169 
3170 	old_run_ctx = bpf_set_run_ctx(&run_ctx.session_ctx.run_ctx);
3171 	err = bpf_prog_run(link->link.prog, regs);
3172 	bpf_reset_run_ctx(old_run_ctx);
3173 
3174 	migrate_enable();
3175 
3176 	if (sleepable)
3177 		rcu_read_unlock_trace();
3178 	else
3179 		rcu_read_unlock();
3180 	return err;
3181 }
3182 
3183 static bool
3184 uprobe_multi_link_filter(struct uprobe_consumer *con, struct mm_struct *mm)
3185 {
3186 	struct bpf_uprobe *uprobe;
3187 
3188 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3189 	return uprobe->link->task->mm == mm;
3190 }
3191 
3192 static int
3193 uprobe_multi_link_handler(struct uprobe_consumer *con, struct pt_regs *regs,
3194 			  __u64 *data)
3195 {
3196 	struct bpf_uprobe *uprobe;
3197 	int ret;
3198 
3199 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3200 	ret = uprobe_prog_run(uprobe, instruction_pointer(regs), regs, false, data);
3201 	if (uprobe->session)
3202 		return ret ? UPROBE_HANDLER_IGNORE : 0;
3203 	return 0;
3204 }
3205 
3206 static int
3207 uprobe_multi_link_ret_handler(struct uprobe_consumer *con, unsigned long func, struct pt_regs *regs,
3208 			      __u64 *data)
3209 {
3210 	struct bpf_uprobe *uprobe;
3211 
3212 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3213 	uprobe_prog_run(uprobe, func, regs, true, data);
3214 	return 0;
3215 }
3216 
3217 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
3218 {
3219 	struct bpf_uprobe_multi_run_ctx *run_ctx;
3220 
3221 	run_ctx = container_of(current->bpf_ctx, struct bpf_uprobe_multi_run_ctx,
3222 			       session_ctx.run_ctx);
3223 	return run_ctx->entry_ip;
3224 }
3225 
3226 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx)
3227 {
3228 	struct bpf_uprobe_multi_run_ctx *run_ctx;
3229 
3230 	run_ctx = container_of(current->bpf_ctx, struct bpf_uprobe_multi_run_ctx,
3231 			       session_ctx.run_ctx);
3232 	return run_ctx->uprobe->cookie;
3233 }
3234 
3235 static int bpf_uprobe_multi_get_path(const union bpf_attr *attr, struct path *path)
3236 {
3237 	void __user *upath = u64_to_user_ptr(attr->link_create.uprobe_multi.path);
3238 	u32 path_fd = attr->link_create.uprobe_multi.path_fd;
3239 	u32 flags = attr->link_create.uprobe_multi.flags;
3240 
3241 	if (flags & BPF_F_UPROBE_MULTI_PATH_FD) {
3242 		/*
3243 		 * When BPF_F_UPROBE_MULTI_PATH_FD is set, the executable is
3244 		 * identified by path_fd, upath must be NULL.
3245 		 */
3246 		if (upath)
3247 			return -EINVAL;
3248 
3249 		CLASS(fd, f)(path_fd);
3250 		if (fd_empty(f))
3251 			return -EBADF;
3252 		*path = fd_file(f)->f_path;
3253 		path_get(path);
3254 		return 0;
3255 	}
3256 
3257 	/*
3258 	 * When BPF_F_UPROBE_MULTI_PATH_FD is not set, the path is resolved
3259 	 * relative to the cwd (AT_FDCWD) or absolute using the upath string.
3260 	 */
3261 	if (!upath || path_fd)
3262 		return -EINVAL;
3263 
3264 	return user_path_at(AT_FDCWD, upath, LOOKUP_FOLLOW, path);
3265 }
3266 
3267 int bpf_uprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3268 {
3269 	struct bpf_uprobe_multi_link *link = NULL;
3270 	unsigned long __user *uref_ctr_offsets;
3271 	struct bpf_link_primer link_primer;
3272 	struct bpf_uprobe *uprobes = NULL;
3273 	struct task_struct *task = NULL;
3274 	unsigned long __user *uoffsets;
3275 	u64 __user *ucookies;
3276 	unsigned long size;
3277 	u32 flags, cnt, i;
3278 	struct path path;
3279 	pid_t pid;
3280 	int err;
3281 
3282 	/* no support for 32bit archs yet */
3283 	if (sizeof(u64) != sizeof(void *))
3284 		return -EOPNOTSUPP;
3285 
3286 	if (attr->link_create.flags)
3287 		return -EINVAL;
3288 
3289 	if (!is_uprobe_multi(prog))
3290 		return -EINVAL;
3291 
3292 	flags = attr->link_create.uprobe_multi.flags;
3293 	if (flags & ~(BPF_F_UPROBE_MULTI_RETURN | BPF_F_UPROBE_MULTI_PATH_FD))
3294 		return -EINVAL;
3295 
3296 	/*
3297 	 * offsets and cnt are mandatory,
3298 	 * ref_ctr_offsets and cookies are optional
3299 	 */
3300 	uoffsets = u64_to_user_ptr(attr->link_create.uprobe_multi.offsets);
3301 	cnt = attr->link_create.uprobe_multi.cnt;
3302 	pid = attr->link_create.uprobe_multi.pid;
3303 
3304 	if (!uoffsets || !cnt || pid < 0)
3305 		return -EINVAL;
3306 	if (cnt > MAX_UPROBE_MULTI_CNT)
3307 		return -E2BIG;
3308 
3309 	uref_ctr_offsets = u64_to_user_ptr(attr->link_create.uprobe_multi.ref_ctr_offsets);
3310 	ucookies = u64_to_user_ptr(attr->link_create.uprobe_multi.cookies);
3311 
3312 	/*
3313 	 * All uoffsets/uref_ctr_offsets/ucookies arrays have the same value
3314 	 * size.  Check their address ranges up front, so that a bad pointer
3315 	 * fails before anything is looked up or allocated.
3316 	 */
3317 	size = sizeof(*uoffsets) * cnt;
3318 	if (!access_ok(uoffsets, size) || !access_ok(uref_ctr_offsets, size) ||
3319 	    !access_ok(ucookies, size))
3320 		return -EFAULT;
3321 
3322 	err = bpf_uprobe_multi_get_path(attr, &path);
3323 	if (err)
3324 		return err;
3325 
3326 	if (!d_is_reg(path.dentry)) {
3327 		err = -EBADF;
3328 		goto error_path_put;
3329 	}
3330 
3331 	if (pid) {
3332 		rcu_read_lock();
3333 		task = get_pid_task(find_vpid(pid), PIDTYPE_TGID);
3334 		rcu_read_unlock();
3335 		if (!task) {
3336 			err = -ESRCH;
3337 			goto error_path_put;
3338 		}
3339 	}
3340 
3341 	err = -ENOMEM;
3342 
3343 	link = kzalloc_obj(*link);
3344 	uprobes = kvzalloc_objs(*uprobes, cnt);
3345 
3346 	if (!uprobes || !link)
3347 		goto error_free;
3348 
3349 	for (i = 0; i < cnt; i++) {
3350 		if (get_user(uprobes[i].offset, uoffsets + i)) {
3351 			err = -EFAULT;
3352 			goto error_free;
3353 		}
3354 		if (uprobes[i].offset < 0) {
3355 			err = -EINVAL;
3356 			goto error_free;
3357 		}
3358 		if (uref_ctr_offsets && get_user(uprobes[i].ref_ctr_offset, uref_ctr_offsets + i)) {
3359 			err = -EFAULT;
3360 			goto error_free;
3361 		}
3362 		if (ucookies && get_user(uprobes[i].cookie, ucookies + i)) {
3363 			err = -EFAULT;
3364 			goto error_free;
3365 		}
3366 
3367 		uprobes[i].link = link;
3368 
3369 		if (!(flags & BPF_F_UPROBE_MULTI_RETURN))
3370 			uprobes[i].consumer.handler = uprobe_multi_link_handler;
3371 		if (flags & BPF_F_UPROBE_MULTI_RETURN || is_uprobe_session(prog))
3372 			uprobes[i].consumer.ret_handler = uprobe_multi_link_ret_handler;
3373 		if (is_uprobe_session(prog))
3374 			uprobes[i].session = true;
3375 		if (pid)
3376 			uprobes[i].consumer.filter = uprobe_multi_link_filter;
3377 	}
3378 
3379 	link->cnt = cnt;
3380 	link->uprobes = uprobes;
3381 	link->path = path;
3382 	link->task = task;
3383 	link->link.flags = flags;
3384 
3385 	bpf_link_init(&link->link, BPF_LINK_TYPE_UPROBE_MULTI,
3386 		      &bpf_uprobe_multi_link_lops, prog, attr->link_create.attach_type);
3387 
3388 	for (i = 0; i < cnt; i++) {
3389 		uprobes[i].uprobe = uprobe_register(d_real_inode(link->path.dentry),
3390 						    uprobes[i].offset,
3391 						    uprobes[i].ref_ctr_offset,
3392 						    &uprobes[i].consumer);
3393 		if (IS_ERR(uprobes[i].uprobe)) {
3394 			err = PTR_ERR(uprobes[i].uprobe);
3395 			link->cnt = i;
3396 			goto error_unregister;
3397 		}
3398 	}
3399 
3400 	err = bpf_link_prime(&link->link, &link_primer);
3401 	if (err)
3402 		goto error_unregister;
3403 
3404 	return bpf_link_settle(&link_primer);
3405 
3406 error_unregister:
3407 	bpf_uprobe_unregister(uprobes, link->cnt);
3408 
3409 error_free:
3410 	kvfree(uprobes);
3411 	kfree(link);
3412 	if (task)
3413 		put_task_struct(task);
3414 error_path_put:
3415 	path_put(&path);
3416 	return err;
3417 }
3418 #else /* !CONFIG_UPROBES */
3419 int bpf_uprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3420 {
3421 	return -EOPNOTSUPP;
3422 }
3423 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx)
3424 {
3425 	return 0;
3426 }
3427 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
3428 {
3429 	return 0;
3430 }
3431 #endif /* CONFIG_UPROBES */
3432 
3433 __bpf_kfunc_start_defs();
3434 
3435 __bpf_kfunc bool bpf_session_is_return(void *ctx)
3436 {
3437 	struct bpf_session_run_ctx *session_ctx;
3438 
3439 	session_ctx = container_of(current->bpf_ctx, struct bpf_session_run_ctx, run_ctx);
3440 	return session_ctx->is_return;
3441 }
3442 
3443 __bpf_kfunc __u64 *bpf_session_cookie(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->data;
3449 }
3450 
3451 __bpf_kfunc_end_defs();
3452 
3453 BTF_KFUNCS_START(session_kfunc_set_ids)
3454 BTF_ID_FLAGS(func, bpf_session_is_return)
3455 BTF_ID_FLAGS(func, bpf_session_cookie)
3456 BTF_KFUNCS_END(session_kfunc_set_ids)
3457 
3458 static int bpf_session_filter(const struct bpf_prog *prog, u32 kfunc_id)
3459 {
3460 	if (!btf_id_set8_contains(&session_kfunc_set_ids, kfunc_id))
3461 		return 0;
3462 
3463 	if (!is_kprobe_session(prog) && !is_uprobe_session(prog) && !is_trace_fsession(prog))
3464 		return -EACCES;
3465 
3466 	return 0;
3467 }
3468 
3469 static const struct btf_kfunc_id_set bpf_session_kfunc_set = {
3470 	.owner = THIS_MODULE,
3471 	.set = &session_kfunc_set_ids,
3472 	.filter = bpf_session_filter,
3473 };
3474 
3475 static int __init bpf_trace_kfuncs_init(void)
3476 {
3477 	int err = 0;
3478 
3479 	err = err ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_KPROBE, &bpf_session_kfunc_set);
3480 	err = err ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_session_kfunc_set);
3481 
3482 	return err;
3483 }
3484 
3485 late_initcall(bpf_trace_kfuncs_init);
3486 
3487 typedef int (*copy_fn_t)(void *dst, const void *src, u32 size, struct task_struct *tsk);
3488 
3489 /*
3490  * The __always_inline is to make sure the compiler doesn't
3491  * generate indirect calls into callbacks, which is expensive,
3492  * on some kernel configurations. This allows compiler to put
3493  * direct calls into all the specific callback implementations
3494  * (copy_user_data_sleepable, copy_user_data_nofault, and so on)
3495  */
3496 static __always_inline int __bpf_dynptr_copy_str(const struct bpf_dynptr *dptr, u64 doff, u64 size,
3497 						 const void *unsafe_src,
3498 						 copy_fn_t str_copy_fn,
3499 						 struct task_struct *tsk)
3500 {
3501 	const struct bpf_dynptr_kern *dst;
3502 	u64 chunk_sz, off;
3503 	void *dst_slice;
3504 	int cnt, err;
3505 	char buf[256];
3506 
3507 	dst_slice = bpf_dynptr_slice_rdwr(dptr, doff, NULL, size);
3508 	if (likely(dst_slice))
3509 		return str_copy_fn(dst_slice, unsafe_src, size, tsk);
3510 
3511 	dst = (struct bpf_dynptr_kern *)dptr;
3512 	if (bpf_dynptr_check_off_len(dst, doff, size))
3513 		return -E2BIG;
3514 
3515 	for (off = 0; off < size; off += chunk_sz - 1) {
3516 		chunk_sz = min_t(u64, sizeof(buf), size - off);
3517 		/* Expect str_copy_fn to return count of copied bytes, including
3518 		 * zero terminator. Next iteration increment off by chunk_sz - 1 to
3519 		 * overwrite NUL.
3520 		 */
3521 		cnt = str_copy_fn(buf, unsafe_src + off, chunk_sz, tsk);
3522 		if (cnt < 0)
3523 			return cnt;
3524 		err = __bpf_dynptr_write(dst, doff + off, buf, cnt, 0);
3525 		if (err)
3526 			return err;
3527 		if (cnt < chunk_sz || chunk_sz == 1) /* we are done */
3528 			return off + cnt;
3529 	}
3530 	return off;
3531 }
3532 
3533 static __always_inline int __bpf_dynptr_copy(const struct bpf_dynptr *dptr, u64 doff,
3534 					     u64 size, const void *unsafe_src,
3535 					     copy_fn_t copy_fn, struct task_struct *tsk)
3536 {
3537 	const struct bpf_dynptr_kern *dst;
3538 	void *dst_slice;
3539 	char buf[256];
3540 	u64 off, chunk_sz;
3541 	int err;
3542 
3543 	dst_slice = bpf_dynptr_slice_rdwr(dptr, doff, NULL, size);
3544 	if (likely(dst_slice))
3545 		return copy_fn(dst_slice, unsafe_src, size, tsk);
3546 
3547 	dst = (struct bpf_dynptr_kern *)dptr;
3548 	if (bpf_dynptr_check_off_len(dst, doff, size))
3549 		return -E2BIG;
3550 
3551 	for (off = 0; off < size; off += chunk_sz) {
3552 		chunk_sz = min_t(u64, sizeof(buf), size - off);
3553 		err = copy_fn(buf, unsafe_src + off, chunk_sz, tsk);
3554 		if (err)
3555 			return err;
3556 		err = __bpf_dynptr_write(dst, doff + off, buf, chunk_sz, 0);
3557 		if (err)
3558 			return err;
3559 	}
3560 	return 0;
3561 }
3562 
3563 static __always_inline int copy_user_data_nofault(void *dst, const void *unsafe_src,
3564 						  u32 size, struct task_struct *tsk)
3565 {
3566 	return copy_from_user_nofault(dst, (const void __user *)unsafe_src, size);
3567 }
3568 
3569 static __always_inline int copy_user_data_sleepable(void *dst, const void *unsafe_src,
3570 						    u32 size, struct task_struct *tsk)
3571 {
3572 	int ret;
3573 
3574 	if (!tsk) { /* Read from the current task */
3575 		ret = copy_from_user(dst, (const void __user *)unsafe_src, size);
3576 		if (ret)
3577 			return -EFAULT;
3578 		return 0;
3579 	}
3580 
3581 	ret = access_process_vm(tsk, (unsigned long)unsafe_src, dst, size, 0);
3582 	if (ret != size)
3583 		return -EFAULT;
3584 	return 0;
3585 }
3586 
3587 static __always_inline int copy_kernel_data_nofault(void *dst, const void *unsafe_src,
3588 						    u32 size, struct task_struct *tsk)
3589 {
3590 	return copy_from_kernel_nofault(dst, unsafe_src, size);
3591 }
3592 
3593 static __always_inline int copy_user_str_nofault(void *dst, const void *unsafe_src,
3594 						 u32 size, struct task_struct *tsk)
3595 {
3596 	return strncpy_from_user_nofault(dst, (const void __user *)unsafe_src, size);
3597 }
3598 
3599 static __always_inline int copy_user_str_sleepable(void *dst, const void *unsafe_src,
3600 						   u32 size, struct task_struct *tsk)
3601 {
3602 	int ret;
3603 
3604 	if (unlikely(size == 0))
3605 		return 0;
3606 
3607 	if (tsk) {
3608 		ret = copy_remote_vm_str(tsk, (unsigned long)unsafe_src, dst, size, 0);
3609 	} else {
3610 		ret = strncpy_from_user(dst, (const void __user *)unsafe_src, size - 1);
3611 		/* strncpy_from_user does not guarantee NUL termination */
3612 		if (ret >= 0)
3613 			((char *)dst)[ret] = '\0';
3614 	}
3615 
3616 	if (ret < 0)
3617 		return ret;
3618 	return ret + 1;
3619 }
3620 
3621 static __always_inline int copy_kernel_str_nofault(void *dst, const void *unsafe_src,
3622 						   u32 size, struct task_struct *tsk)
3623 {
3624 	return strncpy_from_kernel_nofault(dst, unsafe_src, size);
3625 }
3626 
3627 __bpf_kfunc_start_defs();
3628 
3629 __bpf_kfunc int bpf_send_signal_task(struct task_struct *task, int sig, enum pid_type type,
3630 				     u64 value)
3631 {
3632 	if (type != PIDTYPE_PID && type != PIDTYPE_TGID)
3633 		return -EINVAL;
3634 
3635 	return bpf_send_signal_common(sig, type, task, value);
3636 }
3637 
3638 __bpf_kfunc int bpf_probe_read_user_dynptr(const struct bpf_dynptr *dptr, u64 off,
3639 					   u64 size, const void __user *unsafe_ptr__ign)
3640 {
3641 	return __bpf_dynptr_copy(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3642 				 copy_user_data_nofault, NULL);
3643 }
3644 
3645 __bpf_kfunc int bpf_probe_read_kernel_dynptr(const struct bpf_dynptr *dptr, u64 off,
3646 					     u64 size, const void *unsafe_ptr__ign)
3647 {
3648 	return __bpf_dynptr_copy(dptr, off, size, unsafe_ptr__ign,
3649 				 copy_kernel_data_nofault, NULL);
3650 }
3651 
3652 __bpf_kfunc int bpf_probe_read_user_str_dynptr(const struct bpf_dynptr *dptr, u64 off,
3653 					       u64 size, const void __user *unsafe_ptr__ign)
3654 {
3655 	return __bpf_dynptr_copy_str(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3656 				     copy_user_str_nofault, NULL);
3657 }
3658 
3659 __bpf_kfunc int bpf_probe_read_kernel_str_dynptr(const struct bpf_dynptr *dptr, u64 off,
3660 						 u64 size, const void *unsafe_ptr__ign)
3661 {
3662 	return __bpf_dynptr_copy_str(dptr, off, size, unsafe_ptr__ign,
3663 				     copy_kernel_str_nofault, NULL);
3664 }
3665 
3666 __bpf_kfunc int bpf_copy_from_user_dynptr(const struct bpf_dynptr *dptr, u64 off,
3667 					  u64 size, const void __user *unsafe_ptr__ign)
3668 {
3669 	return __bpf_dynptr_copy(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3670 				 copy_user_data_sleepable, NULL);
3671 }
3672 
3673 __bpf_kfunc int bpf_copy_from_user_str_dynptr(const struct bpf_dynptr *dptr, u64 off,
3674 					      u64 size, const void __user *unsafe_ptr__ign)
3675 {
3676 	return __bpf_dynptr_copy_str(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3677 				     copy_user_str_sleepable, NULL);
3678 }
3679 
3680 __bpf_kfunc int bpf_copy_from_user_task_dynptr(const struct bpf_dynptr *dptr, u64 off,
3681 					       u64 size, const void __user *unsafe_ptr__ign,
3682 					       struct task_struct *tsk)
3683 {
3684 	return __bpf_dynptr_copy(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3685 				 copy_user_data_sleepable, tsk);
3686 }
3687 
3688 __bpf_kfunc int bpf_copy_from_user_task_str_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_str(dptr, off, size, (const void __force *)unsafe_ptr__ign,
3693 				     copy_user_str_sleepable, tsk);
3694 }
3695 
3696 __bpf_kfunc_end_defs();
3697 
3698 #if defined(CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS) && \
3699     defined(CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS)
3700 
3701 static void bpf_tracing_multi_link_release(struct bpf_link *link)
3702 {
3703 	struct bpf_tracing_multi_link *tr_link =
3704 		container_of(link, struct bpf_tracing_multi_link, link);
3705 
3706 	bpf_trampoline_multi_detach(link->prog, tr_link);
3707 }
3708 
3709 static void bpf_tracing_multi_link_dealloc(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 	kvfree(tr_link->fexits);
3715 	kvfree(tr_link->cookies);
3716 	kvfree(tr_link);
3717 }
3718 
3719 static int bpf_tracing_multi_link_fill_link_info(const struct bpf_link *link,
3720 						 struct bpf_link_info *info)
3721 {
3722 	u64 __user *ucookies = u64_to_user_ptr(info->tracing_multi.cookies);
3723 	u64 __user *uaddrs = u64_to_user_ptr(info->tracing_multi.addrs);
3724 	u32 __user *uids = u64_to_user_ptr(info->tracing_multi.ids);
3725 	struct bpf_tracing_multi_link *tr_link;
3726 	u32 ucount = info->tracing_multi.count;
3727 	bool has_cookies, show_addrs;
3728 	int err = 0;
3729 
3730 	if ((uids || ucookies || uaddrs) && !ucount)
3731 		return -EINVAL;
3732 
3733 	tr_link = container_of(link, struct bpf_tracing_multi_link, link);
3734 
3735 	info->tracing_multi.attach_type = tr_link->link.attach_type;
3736 	info->tracing_multi.count = tr_link->nodes_cnt;
3737 	info->tracing_multi.btf_obj_id = btf_obj_id(tr_link->link.prog->aux->attach_btf);
3738 
3739 	if (!uids && !ucookies && !uaddrs)
3740 		return 0;
3741 
3742 	if (ucount < tr_link->nodes_cnt)
3743 		err = -ENOSPC;
3744 	else
3745 		ucount = tr_link->nodes_cnt;
3746 
3747 	has_cookies = !!tr_link->cookies;
3748 	show_addrs = kallsyms_show_value(current_cred());
3749 
3750 	for (int i = 0; i < ucount; i++) {
3751 		struct bpf_tracing_multi_node *mnode = &tr_link->nodes[i];
3752 		u64 addr, cookie;
3753 		u32 id;
3754 
3755 		bpf_trampoline_unpack_key(mnode->trampoline->key, NULL, &id);
3756 
3757 		addr = show_addrs ? mnode->trampoline->ip : 0;
3758 		cookie = has_cookies ? tr_link->cookies[i] : 0;
3759 
3760 		if (uids && put_user(id, uids + i))
3761 			return -EFAULT;
3762 		if (uaddrs && put_user(addr, uaddrs + i))
3763 			return -EFAULT;
3764 		if (ucookies && put_user(cookie, ucookies + i))
3765 			return -EFAULT;
3766 
3767 		cond_resched();
3768 	}
3769 
3770 	return err;
3771 }
3772 
3773 #ifdef CONFIG_PROC_FS
3774 static void bpf_tracing_multi_show_fdinfo(const struct bpf_link *link,
3775 					  struct seq_file *seq)
3776 {
3777 	struct bpf_tracing_multi_link *tr_link =
3778 		container_of(link, struct bpf_tracing_multi_link, link);
3779 	bool has_cookies = !!tr_link->cookies;
3780 
3781 	seq_printf(seq, "attach_type:\t%u\n", tr_link->link.attach_type);
3782 	seq_printf(seq, "cnt:\t%u\n", tr_link->nodes_cnt);
3783 
3784 	seq_printf(seq, "%s\t %s\t %s\t %s\n", "obj-id", "btf-id", "cookie", "func");
3785 	for (int i = 0; i < tr_link->nodes_cnt; i++) {
3786 		struct bpf_tracing_multi_node *mnode = &tr_link->nodes[i];
3787 		u32 btf_id, obj_id;
3788 
3789 		bpf_trampoline_unpack_key(mnode->trampoline->key, &obj_id, &btf_id);
3790 		seq_printf(seq, "%u\t %u\t %llu\t %pS\n",
3791 			   obj_id, btf_id,
3792 			   has_cookies ? tr_link->cookies[i] : 0,
3793 			   (void *) mnode->trampoline->ip);
3794 
3795 		cond_resched();
3796 	}
3797 }
3798 #endif
3799 
3800 static const struct bpf_link_ops bpf_tracing_multi_link_lops = {
3801 	.release = bpf_tracing_multi_link_release,
3802 	.dealloc_deferred = bpf_tracing_multi_link_dealloc,
3803 	.fill_link_info = bpf_tracing_multi_link_fill_link_info,
3804 #ifdef CONFIG_PROC_FS
3805 	.show_fdinfo = bpf_tracing_multi_show_fdinfo,
3806 #endif
3807 };
3808 
3809 static int ids_cmp_r(const void *pa, const void *pb, const void *priv __maybe_unused)
3810 {
3811 	u32 a = *(u32 *) pa;
3812 	u32 b = *(u32 *) pb;
3813 
3814 	return (a > b) - (a < b);
3815 }
3816 
3817 static void ids_swap_r(void *a, void *b, int size __maybe_unused,
3818 		       const void *priv __maybe_unused)
3819 {
3820 	u64 *cookie_a, *cookie_b, *cookies;
3821 	u32 *id_a = a, *id_b = b, *ids;
3822 	void **data = (void **) priv;
3823 
3824 	ids     = data[0];
3825 	cookies = data[1];
3826 
3827 	if (cookies) {
3828 		cookie_a = cookies + (id_a - ids);
3829 		cookie_b = cookies + (id_b - ids);
3830 		swap(*cookie_a, *cookie_b);
3831 	}
3832 	swap(*id_a, *id_b);
3833 }
3834 
3835 static int check_dup_ids(u32 *ids, u64 *cookies, u32 cnt)
3836 {
3837 	void *data[2] = { ids, cookies };
3838 	int err = 0;
3839 
3840 	/*
3841 	 * Sort ids array (together with cookies array if defined)
3842 	 * and check it for duplicates. The ids and cookies arrays
3843 	 * are left sorted.
3844 	 */
3845 	sort_r_nonatomic(ids, cnt, sizeof(ids[0]), ids_cmp_r, ids_swap_r, data);
3846 
3847 	for (int i = 1; i < cnt; i++) {
3848 		if (ids[i] == ids[i - 1]) {
3849 			err = -EINVAL;
3850 			break;
3851 		}
3852 	}
3853 	return err;
3854 }
3855 
3856 int bpf_tracing_multi_attach(struct bpf_prog *prog, const union bpf_attr *attr)
3857 {
3858 	struct bpf_tracing_multi_link *link = NULL;
3859 	struct bpf_tramp_node *fexits = NULL;
3860 	struct bpf_link_primer link_primer;
3861 	u32 cnt, *ids = NULL;
3862 	u64 __user *ucookies;
3863 	u64 *cookies = NULL;
3864 	u32 __user *uids;
3865 	int err;
3866 
3867 	uids = u64_to_user_ptr(attr->link_create.tracing_multi.ids);
3868 	cnt = attr->link_create.tracing_multi.cnt;
3869 
3870 	if (!cnt || !uids)
3871 		return -EINVAL;
3872 	if (cnt > MAX_TRACING_MULTI_CNT)
3873 		return -E2BIG;
3874 	if (attr->link_create.flags || attr->link_create.target_fd)
3875 		return -EINVAL;
3876 
3877 	ids = kvmalloc_objs(*ids, cnt);
3878 	if (!ids)
3879 		return -ENOMEM;
3880 
3881 	if (copy_from_user(ids, uids, cnt * sizeof(*ids))) {
3882 		err = -EFAULT;
3883 		goto error;
3884 	}
3885 
3886 	ucookies = u64_to_user_ptr(attr->link_create.tracing_multi.cookies);
3887 	if (ucookies) {
3888 		cookies = kvmalloc_objs(*cookies, cnt);
3889 		if (!cookies) {
3890 			err = -ENOMEM;
3891 			goto error;
3892 		}
3893 		if (copy_from_user(cookies, ucookies, cnt * sizeof(*cookies))) {
3894 			err = -EFAULT;
3895 			goto error;
3896 		}
3897 	}
3898 
3899 	err = check_dup_ids(ids, cookies, cnt);
3900 	if (err)
3901 		goto error;
3902 
3903 	if (prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) {
3904 		fexits = kvmalloc_objs(*fexits, cnt);
3905 		if (!fexits) {
3906 			err = -ENOMEM;
3907 			goto error;
3908 		}
3909 	}
3910 
3911 	link = kvzalloc_flex(*link, nodes, cnt);
3912 	if (!link) {
3913 		err = -ENOMEM;
3914 		goto error;
3915 	}
3916 
3917 	bpf_link_init(&link->link, BPF_LINK_TYPE_TRACING_MULTI,
3918 		      &bpf_tracing_multi_link_lops, prog, prog->expected_attach_type);
3919 
3920 	err = bpf_link_prime(&link->link, &link_primer);
3921 	if (err)
3922 		goto error;
3923 
3924 	link->nodes_cnt = cnt;
3925 	link->cookies = cookies;
3926 	link->fexits = fexits;
3927 
3928 	err = bpf_trampoline_multi_attach(prog, ids, link);
3929 	kvfree(ids);
3930 	if (err) {
3931 		bpf_link_cleanup(&link_primer);
3932 		return err;
3933 	}
3934 	return bpf_link_settle(&link_primer);
3935 
3936 error:
3937 	kvfree(fexits);
3938 	kvfree(cookies);
3939 	kvfree(ids);
3940 	kvfree(link);
3941 	return err;
3942 }
3943 
3944 #else
3945 
3946 int bpf_tracing_multi_attach(struct bpf_prog *prog, const union bpf_attr *attr)
3947 {
3948 	return -EOPNOTSUPP;
3949 }
3950 
3951 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS && CONFIG_HAVE_SINGLE_FTRACE_DIRECT_OPS */
3952