xref: /openbmc/linux/kernel/trace/bpf_trace.c (revision 6ec62dba)
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/verification.h>
26 #include <linux/namei.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 
47 #ifdef CONFIG_MODULES
48 struct bpf_trace_module {
49 	struct module *module;
50 	struct list_head list;
51 };
52 
53 static LIST_HEAD(bpf_trace_modules);
54 static DEFINE_MUTEX(bpf_module_mutex);
55 
56 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
57 {
58 	struct bpf_raw_event_map *btp, *ret = NULL;
59 	struct bpf_trace_module *btm;
60 	unsigned int i;
61 
62 	mutex_lock(&bpf_module_mutex);
63 	list_for_each_entry(btm, &bpf_trace_modules, list) {
64 		for (i = 0; i < btm->module->num_bpf_raw_events; ++i) {
65 			btp = &btm->module->bpf_raw_events[i];
66 			if (!strcmp(btp->tp->name, name)) {
67 				if (try_module_get(btm->module))
68 					ret = btp;
69 				goto out;
70 			}
71 		}
72 	}
73 out:
74 	mutex_unlock(&bpf_module_mutex);
75 	return ret;
76 }
77 #else
78 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
79 {
80 	return NULL;
81 }
82 #endif /* CONFIG_MODULES */
83 
84 u64 bpf_get_stackid(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
85 u64 bpf_get_stack(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
86 
87 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
88 				  u64 flags, const struct btf **btf,
89 				  s32 *btf_id);
90 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx);
91 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx);
92 
93 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx);
94 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx);
95 
96 /**
97  * trace_call_bpf - invoke BPF program
98  * @call: tracepoint event
99  * @ctx: opaque context pointer
100  *
101  * kprobe handlers execute BPF programs via this helper.
102  * Can be used from static tracepoints in the future.
103  *
104  * Return: BPF programs always return an integer which is interpreted by
105  * kprobe handler as:
106  * 0 - return from kprobe (event is filtered out)
107  * 1 - store kprobe event into ring buffer
108  * Other values are reserved and currently alias to 1
109  */
110 unsigned int trace_call_bpf(struct trace_event_call *call, void *ctx)
111 {
112 	unsigned int ret;
113 
114 	cant_sleep();
115 
116 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
117 		/*
118 		 * since some bpf program is already running on this cpu,
119 		 * don't call into another bpf program (same or different)
120 		 * and don't send kprobe event into ring-buffer,
121 		 * so return zero here
122 		 */
123 		ret = 0;
124 		goto out;
125 	}
126 
127 	/*
128 	 * Instead of moving rcu_read_lock/rcu_dereference/rcu_read_unlock
129 	 * to all call sites, we did a bpf_prog_array_valid() there to check
130 	 * whether call->prog_array is empty or not, which is
131 	 * a heuristic to speed up execution.
132 	 *
133 	 * If bpf_prog_array_valid() fetched prog_array was
134 	 * non-NULL, we go into trace_call_bpf() and do the actual
135 	 * proper rcu_dereference() under RCU lock.
136 	 * If it turns out that prog_array is NULL then, we bail out.
137 	 * For the opposite, if the bpf_prog_array_valid() fetched pointer
138 	 * was NULL, you'll skip the prog_array with the risk of missing
139 	 * out of events when it was updated in between this and the
140 	 * rcu_dereference() which is accepted risk.
141 	 */
142 	rcu_read_lock();
143 	ret = bpf_prog_run_array(rcu_dereference(call->prog_array),
144 				 ctx, bpf_prog_run);
145 	rcu_read_unlock();
146 
147  out:
148 	__this_cpu_dec(bpf_prog_active);
149 
150 	return ret;
151 }
152 
153 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
154 BPF_CALL_2(bpf_override_return, struct pt_regs *, regs, unsigned long, rc)
155 {
156 	regs_set_return_value(regs, rc);
157 	override_function_with_return(regs);
158 	return 0;
159 }
160 
161 static const struct bpf_func_proto bpf_override_return_proto = {
162 	.func		= bpf_override_return,
163 	.gpl_only	= true,
164 	.ret_type	= RET_INTEGER,
165 	.arg1_type	= ARG_PTR_TO_CTX,
166 	.arg2_type	= ARG_ANYTHING,
167 };
168 #endif
169 
170 static __always_inline int
171 bpf_probe_read_user_common(void *dst, u32 size, const void __user *unsafe_ptr)
172 {
173 	int ret;
174 
175 	ret = copy_from_user_nofault(dst, unsafe_ptr, size);
176 	if (unlikely(ret < 0))
177 		memset(dst, 0, size);
178 	return ret;
179 }
180 
181 BPF_CALL_3(bpf_probe_read_user, void *, dst, u32, size,
182 	   const void __user *, unsafe_ptr)
183 {
184 	return bpf_probe_read_user_common(dst, size, unsafe_ptr);
185 }
186 
187 const struct bpf_func_proto bpf_probe_read_user_proto = {
188 	.func		= bpf_probe_read_user,
189 	.gpl_only	= true,
190 	.ret_type	= RET_INTEGER,
191 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
192 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
193 	.arg3_type	= ARG_ANYTHING,
194 };
195 
196 static __always_inline int
197 bpf_probe_read_user_str_common(void *dst, u32 size,
198 			       const void __user *unsafe_ptr)
199 {
200 	int ret;
201 
202 	/*
203 	 * NB: We rely on strncpy_from_user() not copying junk past the NUL
204 	 * terminator into `dst`.
205 	 *
206 	 * strncpy_from_user() does long-sized strides in the fast path. If the
207 	 * strncpy does not mask out the bytes after the NUL in `unsafe_ptr`,
208 	 * then there could be junk after the NUL in `dst`. If user takes `dst`
209 	 * and keys a hash map with it, then semantically identical strings can
210 	 * occupy multiple entries in the map.
211 	 */
212 	ret = strncpy_from_user_nofault(dst, unsafe_ptr, size);
213 	if (unlikely(ret < 0))
214 		memset(dst, 0, size);
215 	return ret;
216 }
217 
218 BPF_CALL_3(bpf_probe_read_user_str, void *, dst, u32, size,
219 	   const void __user *, unsafe_ptr)
220 {
221 	return bpf_probe_read_user_str_common(dst, size, unsafe_ptr);
222 }
223 
224 const struct bpf_func_proto bpf_probe_read_user_str_proto = {
225 	.func		= bpf_probe_read_user_str,
226 	.gpl_only	= true,
227 	.ret_type	= RET_INTEGER,
228 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
229 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
230 	.arg3_type	= ARG_ANYTHING,
231 };
232 
233 BPF_CALL_3(bpf_probe_read_kernel, void *, dst, u32, size,
234 	   const void *, unsafe_ptr)
235 {
236 	return bpf_probe_read_kernel_common(dst, size, unsafe_ptr);
237 }
238 
239 const struct bpf_func_proto bpf_probe_read_kernel_proto = {
240 	.func		= bpf_probe_read_kernel,
241 	.gpl_only	= true,
242 	.ret_type	= RET_INTEGER,
243 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
244 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
245 	.arg3_type	= ARG_ANYTHING,
246 };
247 
248 static __always_inline int
249 bpf_probe_read_kernel_str_common(void *dst, u32 size, const void *unsafe_ptr)
250 {
251 	int ret;
252 
253 	/*
254 	 * The strncpy_from_kernel_nofault() call will likely not fill the
255 	 * entire buffer, but that's okay in this circumstance as we're probing
256 	 * arbitrary memory anyway similar to bpf_probe_read_*() and might
257 	 * as well probe the stack. Thus, memory is explicitly cleared
258 	 * only in error case, so that improper users ignoring return
259 	 * code altogether don't copy garbage; otherwise length of string
260 	 * is returned that can be used for bpf_perf_event_output() et al.
261 	 */
262 	ret = strncpy_from_kernel_nofault(dst, unsafe_ptr, size);
263 	if (unlikely(ret < 0))
264 		memset(dst, 0, size);
265 	return ret;
266 }
267 
268 BPF_CALL_3(bpf_probe_read_kernel_str, void *, dst, u32, size,
269 	   const void *, unsafe_ptr)
270 {
271 	return bpf_probe_read_kernel_str_common(dst, size, unsafe_ptr);
272 }
273 
274 const struct bpf_func_proto bpf_probe_read_kernel_str_proto = {
275 	.func		= bpf_probe_read_kernel_str,
276 	.gpl_only	= true,
277 	.ret_type	= RET_INTEGER,
278 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
279 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
280 	.arg3_type	= ARG_ANYTHING,
281 };
282 
283 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
284 BPF_CALL_3(bpf_probe_read_compat, void *, dst, u32, size,
285 	   const void *, unsafe_ptr)
286 {
287 	if ((unsigned long)unsafe_ptr < TASK_SIZE) {
288 		return bpf_probe_read_user_common(dst, size,
289 				(__force void __user *)unsafe_ptr);
290 	}
291 	return bpf_probe_read_kernel_common(dst, size, unsafe_ptr);
292 }
293 
294 static const struct bpf_func_proto bpf_probe_read_compat_proto = {
295 	.func		= bpf_probe_read_compat,
296 	.gpl_only	= true,
297 	.ret_type	= RET_INTEGER,
298 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
299 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
300 	.arg3_type	= ARG_ANYTHING,
301 };
302 
303 BPF_CALL_3(bpf_probe_read_compat_str, void *, dst, u32, size,
304 	   const void *, unsafe_ptr)
305 {
306 	if ((unsigned long)unsafe_ptr < TASK_SIZE) {
307 		return bpf_probe_read_user_str_common(dst, size,
308 				(__force void __user *)unsafe_ptr);
309 	}
310 	return bpf_probe_read_kernel_str_common(dst, size, unsafe_ptr);
311 }
312 
313 static const struct bpf_func_proto bpf_probe_read_compat_str_proto = {
314 	.func		= bpf_probe_read_compat_str,
315 	.gpl_only	= true,
316 	.ret_type	= RET_INTEGER,
317 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
318 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
319 	.arg3_type	= ARG_ANYTHING,
320 };
321 #endif /* CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE */
322 
323 BPF_CALL_3(bpf_probe_write_user, void __user *, unsafe_ptr, const void *, src,
324 	   u32, size)
325 {
326 	/*
327 	 * Ensure we're in user context which is safe for the helper to
328 	 * run. This helper has no business in a kthread.
329 	 *
330 	 * access_ok() should prevent writing to non-user memory, but in
331 	 * some situations (nommu, temporary switch, etc) access_ok() does
332 	 * not provide enough validation, hence the check on KERNEL_DS.
333 	 *
334 	 * nmi_uaccess_okay() ensures the probe is not run in an interim
335 	 * state, when the task or mm are switched. This is specifically
336 	 * required to prevent the use of temporary mm.
337 	 */
338 
339 	if (unlikely(in_interrupt() ||
340 		     current->flags & (PF_KTHREAD | PF_EXITING)))
341 		return -EPERM;
342 	if (unlikely(!nmi_uaccess_okay()))
343 		return -EPERM;
344 
345 	return copy_to_user_nofault(unsafe_ptr, src, size);
346 }
347 
348 static const struct bpf_func_proto bpf_probe_write_user_proto = {
349 	.func		= bpf_probe_write_user,
350 	.gpl_only	= true,
351 	.ret_type	= RET_INTEGER,
352 	.arg1_type	= ARG_ANYTHING,
353 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
354 	.arg3_type	= ARG_CONST_SIZE,
355 };
356 
357 static const struct bpf_func_proto *bpf_get_probe_write_proto(void)
358 {
359 	if (!capable(CAP_SYS_ADMIN))
360 		return NULL;
361 
362 	pr_warn_ratelimited("%s[%d] is installing a program with bpf_probe_write_user helper that may corrupt user memory!",
363 			    current->comm, task_pid_nr(current));
364 
365 	return &bpf_probe_write_user_proto;
366 }
367 
368 #define MAX_TRACE_PRINTK_VARARGS	3
369 #define BPF_TRACE_PRINTK_SIZE		1024
370 
371 BPF_CALL_5(bpf_trace_printk, char *, fmt, u32, fmt_size, u64, arg1,
372 	   u64, arg2, u64, arg3)
373 {
374 	u64 args[MAX_TRACE_PRINTK_VARARGS] = { arg1, arg2, arg3 };
375 	struct bpf_bprintf_data data = {
376 		.get_bin_args	= true,
377 		.get_buf	= true,
378 	};
379 	int ret;
380 
381 	ret = bpf_bprintf_prepare(fmt, fmt_size, args,
382 				  MAX_TRACE_PRINTK_VARARGS, &data);
383 	if (ret < 0)
384 		return ret;
385 
386 	ret = bstr_printf(data.buf, MAX_BPRINTF_BUF, fmt, data.bin_args);
387 
388 	trace_bpf_trace_printk(data.buf);
389 
390 	bpf_bprintf_cleanup(&data);
391 
392 	return ret;
393 }
394 
395 static const struct bpf_func_proto bpf_trace_printk_proto = {
396 	.func		= bpf_trace_printk,
397 	.gpl_only	= true,
398 	.ret_type	= RET_INTEGER,
399 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
400 	.arg2_type	= ARG_CONST_SIZE,
401 };
402 
403 static void __set_printk_clr_event(void)
404 {
405 	/*
406 	 * This program might be calling bpf_trace_printk,
407 	 * so enable the associated bpf_trace/bpf_trace_printk event.
408 	 * Repeat this each time as it is possible a user has
409 	 * disabled bpf_trace_printk events.  By loading a program
410 	 * calling bpf_trace_printk() however the user has expressed
411 	 * the intent to see such events.
412 	 */
413 	if (trace_set_clr_event("bpf_trace", "bpf_trace_printk", 1))
414 		pr_warn_ratelimited("could not enable bpf_trace_printk events");
415 }
416 
417 const struct bpf_func_proto *bpf_get_trace_printk_proto(void)
418 {
419 	__set_printk_clr_event();
420 	return &bpf_trace_printk_proto;
421 }
422 
423 BPF_CALL_4(bpf_trace_vprintk, char *, fmt, u32, fmt_size, const void *, args,
424 	   u32, data_len)
425 {
426 	struct bpf_bprintf_data data = {
427 		.get_bin_args	= true,
428 		.get_buf	= true,
429 	};
430 	int ret, num_args;
431 
432 	if (data_len & 7 || data_len > MAX_BPRINTF_VARARGS * 8 ||
433 	    (data_len && !args))
434 		return -EINVAL;
435 	num_args = data_len / 8;
436 
437 	ret = bpf_bprintf_prepare(fmt, fmt_size, args, num_args, &data);
438 	if (ret < 0)
439 		return ret;
440 
441 	ret = bstr_printf(data.buf, MAX_BPRINTF_BUF, fmt, data.bin_args);
442 
443 	trace_bpf_trace_printk(data.buf);
444 
445 	bpf_bprintf_cleanup(&data);
446 
447 	return ret;
448 }
449 
450 static const struct bpf_func_proto bpf_trace_vprintk_proto = {
451 	.func		= bpf_trace_vprintk,
452 	.gpl_only	= true,
453 	.ret_type	= RET_INTEGER,
454 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
455 	.arg2_type	= ARG_CONST_SIZE,
456 	.arg3_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
457 	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
458 };
459 
460 const struct bpf_func_proto *bpf_get_trace_vprintk_proto(void)
461 {
462 	__set_printk_clr_event();
463 	return &bpf_trace_vprintk_proto;
464 }
465 
466 BPF_CALL_5(bpf_seq_printf, struct seq_file *, m, char *, fmt, u32, fmt_size,
467 	   const void *, args, u32, data_len)
468 {
469 	struct bpf_bprintf_data data = {
470 		.get_bin_args	= true,
471 	};
472 	int err, num_args;
473 
474 	if (data_len & 7 || data_len > MAX_BPRINTF_VARARGS * 8 ||
475 	    (data_len && !args))
476 		return -EINVAL;
477 	num_args = data_len / 8;
478 
479 	err = bpf_bprintf_prepare(fmt, fmt_size, args, num_args, &data);
480 	if (err < 0)
481 		return err;
482 
483 	seq_bprintf(m, fmt, data.bin_args);
484 
485 	bpf_bprintf_cleanup(&data);
486 
487 	return seq_has_overflowed(m) ? -EOVERFLOW : 0;
488 }
489 
490 BTF_ID_LIST_SINGLE(btf_seq_file_ids, struct, seq_file)
491 
492 static const struct bpf_func_proto bpf_seq_printf_proto = {
493 	.func		= bpf_seq_printf,
494 	.gpl_only	= true,
495 	.ret_type	= RET_INTEGER,
496 	.arg1_type	= ARG_PTR_TO_BTF_ID,
497 	.arg1_btf_id	= &btf_seq_file_ids[0],
498 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
499 	.arg3_type	= ARG_CONST_SIZE,
500 	.arg4_type      = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
501 	.arg5_type      = ARG_CONST_SIZE_OR_ZERO,
502 };
503 
504 BPF_CALL_3(bpf_seq_write, struct seq_file *, m, const void *, data, u32, len)
505 {
506 	return seq_write(m, data, len) ? -EOVERFLOW : 0;
507 }
508 
509 static const struct bpf_func_proto bpf_seq_write_proto = {
510 	.func		= bpf_seq_write,
511 	.gpl_only	= true,
512 	.ret_type	= RET_INTEGER,
513 	.arg1_type	= ARG_PTR_TO_BTF_ID,
514 	.arg1_btf_id	= &btf_seq_file_ids[0],
515 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
516 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
517 };
518 
519 BPF_CALL_4(bpf_seq_printf_btf, struct seq_file *, m, struct btf_ptr *, ptr,
520 	   u32, btf_ptr_size, u64, flags)
521 {
522 	const struct btf *btf;
523 	s32 btf_id;
524 	int ret;
525 
526 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
527 	if (ret)
528 		return ret;
529 
530 	return btf_type_seq_show_flags(btf, btf_id, ptr->ptr, m, flags);
531 }
532 
533 static const struct bpf_func_proto bpf_seq_printf_btf_proto = {
534 	.func		= bpf_seq_printf_btf,
535 	.gpl_only	= true,
536 	.ret_type	= RET_INTEGER,
537 	.arg1_type	= ARG_PTR_TO_BTF_ID,
538 	.arg1_btf_id	= &btf_seq_file_ids[0],
539 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
540 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
541 	.arg4_type	= ARG_ANYTHING,
542 };
543 
544 static __always_inline int
545 get_map_perf_counter(struct bpf_map *map, u64 flags,
546 		     u64 *value, u64 *enabled, u64 *running)
547 {
548 	struct bpf_array *array = container_of(map, struct bpf_array, map);
549 	unsigned int cpu = smp_processor_id();
550 	u64 index = flags & BPF_F_INDEX_MASK;
551 	struct bpf_event_entry *ee;
552 
553 	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
554 		return -EINVAL;
555 	if (index == BPF_F_CURRENT_CPU)
556 		index = cpu;
557 	if (unlikely(index >= array->map.max_entries))
558 		return -E2BIG;
559 
560 	ee = READ_ONCE(array->ptrs[index]);
561 	if (!ee)
562 		return -ENOENT;
563 
564 	return perf_event_read_local(ee->event, value, enabled, running);
565 }
566 
567 BPF_CALL_2(bpf_perf_event_read, struct bpf_map *, map, u64, flags)
568 {
569 	u64 value = 0;
570 	int err;
571 
572 	err = get_map_perf_counter(map, flags, &value, NULL, NULL);
573 	/*
574 	 * this api is ugly since we miss [-22..-2] range of valid
575 	 * counter values, but that's uapi
576 	 */
577 	if (err)
578 		return err;
579 	return value;
580 }
581 
582 static const struct bpf_func_proto bpf_perf_event_read_proto = {
583 	.func		= bpf_perf_event_read,
584 	.gpl_only	= true,
585 	.ret_type	= RET_INTEGER,
586 	.arg1_type	= ARG_CONST_MAP_PTR,
587 	.arg2_type	= ARG_ANYTHING,
588 };
589 
590 BPF_CALL_4(bpf_perf_event_read_value, struct bpf_map *, map, u64, flags,
591 	   struct bpf_perf_event_value *, buf, u32, size)
592 {
593 	int err = -EINVAL;
594 
595 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
596 		goto clear;
597 	err = get_map_perf_counter(map, flags, &buf->counter, &buf->enabled,
598 				   &buf->running);
599 	if (unlikely(err))
600 		goto clear;
601 	return 0;
602 clear:
603 	memset(buf, 0, size);
604 	return err;
605 }
606 
607 static const struct bpf_func_proto bpf_perf_event_read_value_proto = {
608 	.func		= bpf_perf_event_read_value,
609 	.gpl_only	= true,
610 	.ret_type	= RET_INTEGER,
611 	.arg1_type	= ARG_CONST_MAP_PTR,
612 	.arg2_type	= ARG_ANYTHING,
613 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
614 	.arg4_type	= ARG_CONST_SIZE,
615 };
616 
617 static __always_inline u64
618 __bpf_perf_event_output(struct pt_regs *regs, struct bpf_map *map,
619 			u64 flags, struct perf_sample_data *sd)
620 {
621 	struct bpf_array *array = container_of(map, struct bpf_array, map);
622 	unsigned int cpu = smp_processor_id();
623 	u64 index = flags & BPF_F_INDEX_MASK;
624 	struct bpf_event_entry *ee;
625 	struct perf_event *event;
626 
627 	if (index == BPF_F_CURRENT_CPU)
628 		index = cpu;
629 	if (unlikely(index >= array->map.max_entries))
630 		return -E2BIG;
631 
632 	ee = READ_ONCE(array->ptrs[index]);
633 	if (!ee)
634 		return -ENOENT;
635 
636 	event = ee->event;
637 	if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
638 		     event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
639 		return -EINVAL;
640 
641 	if (unlikely(event->oncpu != cpu))
642 		return -EOPNOTSUPP;
643 
644 	return perf_event_output(event, sd, regs);
645 }
646 
647 /*
648  * Support executing tracepoints in normal, irq, and nmi context that each call
649  * bpf_perf_event_output
650  */
651 struct bpf_trace_sample_data {
652 	struct perf_sample_data sds[3];
653 };
654 
655 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_trace_sds);
656 static DEFINE_PER_CPU(int, bpf_trace_nest_level);
657 BPF_CALL_5(bpf_perf_event_output, struct pt_regs *, regs, struct bpf_map *, map,
658 	   u64, flags, void *, data, u64, size)
659 {
660 	struct bpf_trace_sample_data *sds;
661 	struct perf_raw_record raw = {
662 		.frag = {
663 			.size = size,
664 			.data = data,
665 		},
666 	};
667 	struct perf_sample_data *sd;
668 	int nest_level, err;
669 
670 	preempt_disable();
671 	sds = this_cpu_ptr(&bpf_trace_sds);
672 	nest_level = this_cpu_inc_return(bpf_trace_nest_level);
673 
674 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(sds->sds))) {
675 		err = -EBUSY;
676 		goto out;
677 	}
678 
679 	sd = &sds->sds[nest_level - 1];
680 
681 	if (unlikely(flags & ~(BPF_F_INDEX_MASK))) {
682 		err = -EINVAL;
683 		goto out;
684 	}
685 
686 	perf_sample_data_init(sd, 0, 0);
687 	perf_sample_save_raw_data(sd, &raw);
688 
689 	err = __bpf_perf_event_output(regs, map, flags, sd);
690 out:
691 	this_cpu_dec(bpf_trace_nest_level);
692 	preempt_enable();
693 	return err;
694 }
695 
696 static const struct bpf_func_proto bpf_perf_event_output_proto = {
697 	.func		= bpf_perf_event_output,
698 	.gpl_only	= true,
699 	.ret_type	= RET_INTEGER,
700 	.arg1_type	= ARG_PTR_TO_CTX,
701 	.arg2_type	= ARG_CONST_MAP_PTR,
702 	.arg3_type	= ARG_ANYTHING,
703 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
704 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
705 };
706 
707 static DEFINE_PER_CPU(int, bpf_event_output_nest_level);
708 struct bpf_nested_pt_regs {
709 	struct pt_regs regs[3];
710 };
711 static DEFINE_PER_CPU(struct bpf_nested_pt_regs, bpf_pt_regs);
712 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_misc_sds);
713 
714 u64 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
715 		     void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
716 {
717 	struct perf_raw_frag frag = {
718 		.copy		= ctx_copy,
719 		.size		= ctx_size,
720 		.data		= ctx,
721 	};
722 	struct perf_raw_record raw = {
723 		.frag = {
724 			{
725 				.next	= ctx_size ? &frag : NULL,
726 			},
727 			.size	= meta_size,
728 			.data	= meta,
729 		},
730 	};
731 	struct perf_sample_data *sd;
732 	struct pt_regs *regs;
733 	int nest_level;
734 	u64 ret;
735 
736 	preempt_disable();
737 	nest_level = this_cpu_inc_return(bpf_event_output_nest_level);
738 
739 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(bpf_misc_sds.sds))) {
740 		ret = -EBUSY;
741 		goto out;
742 	}
743 	sd = this_cpu_ptr(&bpf_misc_sds.sds[nest_level - 1]);
744 	regs = this_cpu_ptr(&bpf_pt_regs.regs[nest_level - 1]);
745 
746 	perf_fetch_caller_regs(regs);
747 	perf_sample_data_init(sd, 0, 0);
748 	perf_sample_save_raw_data(sd, &raw);
749 
750 	ret = __bpf_perf_event_output(regs, map, flags, sd);
751 out:
752 	this_cpu_dec(bpf_event_output_nest_level);
753 	preempt_enable();
754 	return ret;
755 }
756 
757 BPF_CALL_0(bpf_get_current_task)
758 {
759 	return (long) current;
760 }
761 
762 const struct bpf_func_proto bpf_get_current_task_proto = {
763 	.func		= bpf_get_current_task,
764 	.gpl_only	= true,
765 	.ret_type	= RET_INTEGER,
766 };
767 
768 BPF_CALL_0(bpf_get_current_task_btf)
769 {
770 	return (unsigned long) current;
771 }
772 
773 const struct bpf_func_proto bpf_get_current_task_btf_proto = {
774 	.func		= bpf_get_current_task_btf,
775 	.gpl_only	= true,
776 	.ret_type	= RET_PTR_TO_BTF_ID_TRUSTED,
777 	.ret_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
778 };
779 
780 BPF_CALL_1(bpf_task_pt_regs, struct task_struct *, task)
781 {
782 	return (unsigned long) task_pt_regs(task);
783 }
784 
785 BTF_ID_LIST(bpf_task_pt_regs_ids)
786 BTF_ID(struct, pt_regs)
787 
788 const struct bpf_func_proto bpf_task_pt_regs_proto = {
789 	.func		= bpf_task_pt_regs,
790 	.gpl_only	= true,
791 	.arg1_type	= ARG_PTR_TO_BTF_ID,
792 	.arg1_btf_id	= &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
793 	.ret_type	= RET_PTR_TO_BTF_ID,
794 	.ret_btf_id	= &bpf_task_pt_regs_ids[0],
795 };
796 
797 BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
798 {
799 	struct bpf_array *array = container_of(map, struct bpf_array, map);
800 	struct cgroup *cgrp;
801 
802 	if (unlikely(idx >= array->map.max_entries))
803 		return -E2BIG;
804 
805 	cgrp = READ_ONCE(array->ptrs[idx]);
806 	if (unlikely(!cgrp))
807 		return -EAGAIN;
808 
809 	return task_under_cgroup_hierarchy(current, cgrp);
810 }
811 
812 static const struct bpf_func_proto bpf_current_task_under_cgroup_proto = {
813 	.func           = bpf_current_task_under_cgroup,
814 	.gpl_only       = false,
815 	.ret_type       = RET_INTEGER,
816 	.arg1_type      = ARG_CONST_MAP_PTR,
817 	.arg2_type      = ARG_ANYTHING,
818 };
819 
820 struct send_signal_irq_work {
821 	struct irq_work irq_work;
822 	struct task_struct *task;
823 	u32 sig;
824 	enum pid_type type;
825 };
826 
827 static DEFINE_PER_CPU(struct send_signal_irq_work, send_signal_work);
828 
829 static void do_bpf_send_signal(struct irq_work *entry)
830 {
831 	struct send_signal_irq_work *work;
832 
833 	work = container_of(entry, struct send_signal_irq_work, irq_work);
834 	group_send_sig_info(work->sig, SEND_SIG_PRIV, work->task, work->type);
835 	put_task_struct(work->task);
836 }
837 
838 static int bpf_send_signal_common(u32 sig, enum pid_type type)
839 {
840 	struct send_signal_irq_work *work = NULL;
841 
842 	/* Similar to bpf_probe_write_user, task needs to be
843 	 * in a sound condition and kernel memory access be
844 	 * permitted in order to send signal to the current
845 	 * task.
846 	 */
847 	if (unlikely(current->flags & (PF_KTHREAD | PF_EXITING)))
848 		return -EPERM;
849 	if (unlikely(!nmi_uaccess_okay()))
850 		return -EPERM;
851 	/* Task should not be pid=1 to avoid kernel panic. */
852 	if (unlikely(is_global_init(current)))
853 		return -EPERM;
854 
855 	if (irqs_disabled()) {
856 		/* Do an early check on signal validity. Otherwise,
857 		 * the error is lost in deferred irq_work.
858 		 */
859 		if (unlikely(!valid_signal(sig)))
860 			return -EINVAL;
861 
862 		work = this_cpu_ptr(&send_signal_work);
863 		if (irq_work_is_busy(&work->irq_work))
864 			return -EBUSY;
865 
866 		/* Add the current task, which is the target of sending signal,
867 		 * to the irq_work. The current task may change when queued
868 		 * irq works get executed.
869 		 */
870 		work->task = get_task_struct(current);
871 		work->sig = sig;
872 		work->type = type;
873 		irq_work_queue(&work->irq_work);
874 		return 0;
875 	}
876 
877 	return group_send_sig_info(sig, SEND_SIG_PRIV, current, type);
878 }
879 
880 BPF_CALL_1(bpf_send_signal, u32, sig)
881 {
882 	return bpf_send_signal_common(sig, PIDTYPE_TGID);
883 }
884 
885 static const struct bpf_func_proto bpf_send_signal_proto = {
886 	.func		= bpf_send_signal,
887 	.gpl_only	= false,
888 	.ret_type	= RET_INTEGER,
889 	.arg1_type	= ARG_ANYTHING,
890 };
891 
892 BPF_CALL_1(bpf_send_signal_thread, u32, sig)
893 {
894 	return bpf_send_signal_common(sig, PIDTYPE_PID);
895 }
896 
897 static const struct bpf_func_proto bpf_send_signal_thread_proto = {
898 	.func		= bpf_send_signal_thread,
899 	.gpl_only	= false,
900 	.ret_type	= RET_INTEGER,
901 	.arg1_type	= ARG_ANYTHING,
902 };
903 
904 BPF_CALL_3(bpf_d_path, struct path *, path, char *, buf, u32, sz)
905 {
906 	struct path copy;
907 	long len;
908 	char *p;
909 
910 	if (!sz)
911 		return 0;
912 
913 	/*
914 	 * The path pointer is verified as trusted and safe to use,
915 	 * but let's double check it's valid anyway to workaround
916 	 * potentially broken verifier.
917 	 */
918 	len = copy_from_kernel_nofault(&copy, path, sizeof(*path));
919 	if (len < 0)
920 		return len;
921 
922 	p = d_path(&copy, buf, sz);
923 	if (IS_ERR(p)) {
924 		len = PTR_ERR(p);
925 	} else {
926 		len = buf + sz - p;
927 		memmove(buf, p, len);
928 	}
929 
930 	return len;
931 }
932 
933 BTF_SET_START(btf_allowlist_d_path)
934 #ifdef CONFIG_SECURITY
935 BTF_ID(func, security_file_permission)
936 BTF_ID(func, security_inode_getattr)
937 BTF_ID(func, security_file_open)
938 #endif
939 #ifdef CONFIG_SECURITY_PATH
940 BTF_ID(func, security_path_truncate)
941 #endif
942 BTF_ID(func, vfs_truncate)
943 BTF_ID(func, vfs_fallocate)
944 BTF_ID(func, dentry_open)
945 BTF_ID(func, vfs_getattr)
946 BTF_ID(func, filp_close)
947 BTF_SET_END(btf_allowlist_d_path)
948 
949 static bool bpf_d_path_allowed(const struct bpf_prog *prog)
950 {
951 	if (prog->type == BPF_PROG_TYPE_TRACING &&
952 	    prog->expected_attach_type == BPF_TRACE_ITER)
953 		return true;
954 
955 	if (prog->type == BPF_PROG_TYPE_LSM)
956 		return bpf_lsm_is_sleepable_hook(prog->aux->attach_btf_id);
957 
958 	return btf_id_set_contains(&btf_allowlist_d_path,
959 				   prog->aux->attach_btf_id);
960 }
961 
962 BTF_ID_LIST_SINGLE(bpf_d_path_btf_ids, struct, path)
963 
964 static const struct bpf_func_proto bpf_d_path_proto = {
965 	.func		= bpf_d_path,
966 	.gpl_only	= false,
967 	.ret_type	= RET_INTEGER,
968 	.arg1_type	= ARG_PTR_TO_BTF_ID,
969 	.arg1_btf_id	= &bpf_d_path_btf_ids[0],
970 	.arg2_type	= ARG_PTR_TO_MEM,
971 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
972 	.allowed	= bpf_d_path_allowed,
973 };
974 
975 #define BTF_F_ALL	(BTF_F_COMPACT  | BTF_F_NONAME | \
976 			 BTF_F_PTR_RAW | BTF_F_ZERO)
977 
978 static int bpf_btf_printf_prepare(struct btf_ptr *ptr, u32 btf_ptr_size,
979 				  u64 flags, const struct btf **btf,
980 				  s32 *btf_id)
981 {
982 	const struct btf_type *t;
983 
984 	if (unlikely(flags & ~(BTF_F_ALL)))
985 		return -EINVAL;
986 
987 	if (btf_ptr_size != sizeof(struct btf_ptr))
988 		return -EINVAL;
989 
990 	*btf = bpf_get_btf_vmlinux();
991 
992 	if (IS_ERR_OR_NULL(*btf))
993 		return IS_ERR(*btf) ? PTR_ERR(*btf) : -EINVAL;
994 
995 	if (ptr->type_id > 0)
996 		*btf_id = ptr->type_id;
997 	else
998 		return -EINVAL;
999 
1000 	if (*btf_id > 0)
1001 		t = btf_type_by_id(*btf, *btf_id);
1002 	if (*btf_id <= 0 || !t)
1003 		return -ENOENT;
1004 
1005 	return 0;
1006 }
1007 
1008 BPF_CALL_5(bpf_snprintf_btf, char *, str, u32, str_size, struct btf_ptr *, ptr,
1009 	   u32, btf_ptr_size, u64, flags)
1010 {
1011 	const struct btf *btf;
1012 	s32 btf_id;
1013 	int ret;
1014 
1015 	ret = bpf_btf_printf_prepare(ptr, btf_ptr_size, flags, &btf, &btf_id);
1016 	if (ret)
1017 		return ret;
1018 
1019 	return btf_type_snprintf_show(btf, btf_id, ptr->ptr, str, str_size,
1020 				      flags);
1021 }
1022 
1023 const struct bpf_func_proto bpf_snprintf_btf_proto = {
1024 	.func		= bpf_snprintf_btf,
1025 	.gpl_only	= false,
1026 	.ret_type	= RET_INTEGER,
1027 	.arg1_type	= ARG_PTR_TO_MEM,
1028 	.arg2_type	= ARG_CONST_SIZE,
1029 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1030 	.arg4_type	= ARG_CONST_SIZE,
1031 	.arg5_type	= ARG_ANYTHING,
1032 };
1033 
1034 BPF_CALL_1(bpf_get_func_ip_tracing, void *, ctx)
1035 {
1036 	/* This helper call is inlined by verifier. */
1037 	return ((u64 *)ctx)[-2];
1038 }
1039 
1040 static const struct bpf_func_proto bpf_get_func_ip_proto_tracing = {
1041 	.func		= bpf_get_func_ip_tracing,
1042 	.gpl_only	= true,
1043 	.ret_type	= RET_INTEGER,
1044 	.arg1_type	= ARG_PTR_TO_CTX,
1045 };
1046 
1047 #ifdef CONFIG_X86_KERNEL_IBT
1048 static unsigned long get_entry_ip(unsigned long fentry_ip)
1049 {
1050 	u32 instr;
1051 
1052 	/* Being extra safe in here in case entry ip is on the page-edge. */
1053 	if (get_kernel_nofault(instr, (u32 *) fentry_ip - 1))
1054 		return fentry_ip;
1055 	if (is_endbr(instr))
1056 		fentry_ip -= ENDBR_INSN_SIZE;
1057 	return fentry_ip;
1058 }
1059 #else
1060 #define get_entry_ip(fentry_ip) fentry_ip
1061 #endif
1062 
1063 BPF_CALL_1(bpf_get_func_ip_kprobe, struct pt_regs *, regs)
1064 {
1065 	struct bpf_trace_run_ctx *run_ctx __maybe_unused;
1066 	struct kprobe *kp;
1067 
1068 #ifdef CONFIG_UPROBES
1069 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1070 	if (run_ctx->is_uprobe)
1071 		return ((struct uprobe_dispatch_data *)current->utask->vaddr)->bp_addr;
1072 #endif
1073 
1074 	kp = kprobe_running();
1075 
1076 	if (!kp || !(kp->flags & KPROBE_FLAG_ON_FUNC_ENTRY))
1077 		return 0;
1078 
1079 	return get_entry_ip((uintptr_t)kp->addr);
1080 }
1081 
1082 static const struct bpf_func_proto bpf_get_func_ip_proto_kprobe = {
1083 	.func		= bpf_get_func_ip_kprobe,
1084 	.gpl_only	= true,
1085 	.ret_type	= RET_INTEGER,
1086 	.arg1_type	= ARG_PTR_TO_CTX,
1087 };
1088 
1089 BPF_CALL_1(bpf_get_func_ip_kprobe_multi, struct pt_regs *, regs)
1090 {
1091 	return bpf_kprobe_multi_entry_ip(current->bpf_ctx);
1092 }
1093 
1094 static const struct bpf_func_proto bpf_get_func_ip_proto_kprobe_multi = {
1095 	.func		= bpf_get_func_ip_kprobe_multi,
1096 	.gpl_only	= false,
1097 	.ret_type	= RET_INTEGER,
1098 	.arg1_type	= ARG_PTR_TO_CTX,
1099 };
1100 
1101 BPF_CALL_1(bpf_get_attach_cookie_kprobe_multi, struct pt_regs *, regs)
1102 {
1103 	return bpf_kprobe_multi_cookie(current->bpf_ctx);
1104 }
1105 
1106 static const struct bpf_func_proto bpf_get_attach_cookie_proto_kmulti = {
1107 	.func		= bpf_get_attach_cookie_kprobe_multi,
1108 	.gpl_only	= false,
1109 	.ret_type	= RET_INTEGER,
1110 	.arg1_type	= ARG_PTR_TO_CTX,
1111 };
1112 
1113 BPF_CALL_1(bpf_get_func_ip_uprobe_multi, struct pt_regs *, regs)
1114 {
1115 	return bpf_uprobe_multi_entry_ip(current->bpf_ctx);
1116 }
1117 
1118 static const struct bpf_func_proto bpf_get_func_ip_proto_uprobe_multi = {
1119 	.func		= bpf_get_func_ip_uprobe_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_uprobe_multi, struct pt_regs *, regs)
1126 {
1127 	return bpf_uprobe_multi_cookie(current->bpf_ctx);
1128 }
1129 
1130 static const struct bpf_func_proto bpf_get_attach_cookie_proto_umulti = {
1131 	.func		= bpf_get_attach_cookie_uprobe_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_attach_cookie_trace, void *, ctx)
1138 {
1139 	struct bpf_trace_run_ctx *run_ctx;
1140 
1141 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1142 	return run_ctx->bpf_cookie;
1143 }
1144 
1145 static const struct bpf_func_proto bpf_get_attach_cookie_proto_trace = {
1146 	.func		= bpf_get_attach_cookie_trace,
1147 	.gpl_only	= false,
1148 	.ret_type	= RET_INTEGER,
1149 	.arg1_type	= ARG_PTR_TO_CTX,
1150 };
1151 
1152 BPF_CALL_1(bpf_get_attach_cookie_pe, struct bpf_perf_event_data_kern *, ctx)
1153 {
1154 	return ctx->event->bpf_cookie;
1155 }
1156 
1157 static const struct bpf_func_proto bpf_get_attach_cookie_proto_pe = {
1158 	.func		= bpf_get_attach_cookie_pe,
1159 	.gpl_only	= false,
1160 	.ret_type	= RET_INTEGER,
1161 	.arg1_type	= ARG_PTR_TO_CTX,
1162 };
1163 
1164 BPF_CALL_1(bpf_get_attach_cookie_tracing, void *, ctx)
1165 {
1166 	struct bpf_trace_run_ctx *run_ctx;
1167 
1168 	run_ctx = container_of(current->bpf_ctx, struct bpf_trace_run_ctx, run_ctx);
1169 	return run_ctx->bpf_cookie;
1170 }
1171 
1172 static const struct bpf_func_proto bpf_get_attach_cookie_proto_tracing = {
1173 	.func		= bpf_get_attach_cookie_tracing,
1174 	.gpl_only	= false,
1175 	.ret_type	= RET_INTEGER,
1176 	.arg1_type	= ARG_PTR_TO_CTX,
1177 };
1178 
1179 BPF_CALL_3(bpf_get_branch_snapshot, void *, buf, u32, size, u64, flags)
1180 {
1181 #ifndef CONFIG_X86
1182 	return -ENOENT;
1183 #else
1184 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1185 	u32 entry_cnt = size / br_entry_size;
1186 
1187 	entry_cnt = static_call(perf_snapshot_branch_stack)(buf, entry_cnt);
1188 
1189 	if (unlikely(flags))
1190 		return -EINVAL;
1191 
1192 	if (!entry_cnt)
1193 		return -ENOENT;
1194 
1195 	return entry_cnt * br_entry_size;
1196 #endif
1197 }
1198 
1199 static const struct bpf_func_proto bpf_get_branch_snapshot_proto = {
1200 	.func		= bpf_get_branch_snapshot,
1201 	.gpl_only	= true,
1202 	.ret_type	= RET_INTEGER,
1203 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
1204 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1205 };
1206 
1207 BPF_CALL_3(get_func_arg, void *, ctx, u32, n, u64 *, value)
1208 {
1209 	/* This helper call is inlined by verifier. */
1210 	u64 nr_args = ((u64 *)ctx)[-1];
1211 
1212 	if ((u64) n >= nr_args)
1213 		return -EINVAL;
1214 	*value = ((u64 *)ctx)[n];
1215 	return 0;
1216 }
1217 
1218 static const struct bpf_func_proto bpf_get_func_arg_proto = {
1219 	.func		= get_func_arg,
1220 	.ret_type	= RET_INTEGER,
1221 	.arg1_type	= ARG_PTR_TO_CTX,
1222 	.arg2_type	= ARG_ANYTHING,
1223 	.arg3_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_ALIGNED,
1224 	.arg3_size	= sizeof(u64),
1225 };
1226 
1227 BPF_CALL_2(get_func_ret, void *, ctx, u64 *, value)
1228 {
1229 	/* This helper call is inlined by verifier. */
1230 	u64 nr_args = ((u64 *)ctx)[-1];
1231 
1232 	*value = ((u64 *)ctx)[nr_args];
1233 	return 0;
1234 }
1235 
1236 static const struct bpf_func_proto bpf_get_func_ret_proto = {
1237 	.func		= get_func_ret,
1238 	.ret_type	= RET_INTEGER,
1239 	.arg1_type	= ARG_PTR_TO_CTX,
1240 	.arg2_type	= ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_ALIGNED,
1241 	.arg2_size	= sizeof(u64),
1242 };
1243 
1244 BPF_CALL_1(get_func_arg_cnt, void *, ctx)
1245 {
1246 	/* This helper call is inlined by verifier. */
1247 	return ((u64 *)ctx)[-1];
1248 }
1249 
1250 static const struct bpf_func_proto bpf_get_func_arg_cnt_proto = {
1251 	.func		= get_func_arg_cnt,
1252 	.ret_type	= RET_INTEGER,
1253 	.arg1_type	= ARG_PTR_TO_CTX,
1254 };
1255 
1256 #ifdef CONFIG_KEYS
1257 __diag_push();
1258 __diag_ignore_all("-Wmissing-prototypes",
1259 		  "kfuncs which will be used in BPF programs");
1260 
1261 /**
1262  * bpf_lookup_user_key - lookup a key by its serial
1263  * @serial: key handle serial number
1264  * @flags: lookup-specific flags
1265  *
1266  * Search a key with a given *serial* and the provided *flags*.
1267  * If found, increment the reference count of the key by one, and
1268  * return it in the bpf_key structure.
1269  *
1270  * The bpf_key structure must be passed to bpf_key_put() when done
1271  * with it, so that the key reference count is decremented and the
1272  * bpf_key structure is freed.
1273  *
1274  * Permission checks are deferred to the time the key is used by
1275  * one of the available key-specific kfuncs.
1276  *
1277  * Set *flags* with KEY_LOOKUP_CREATE, to attempt creating a requested
1278  * special keyring (e.g. session keyring), if it doesn't yet exist.
1279  * Set *flags* with KEY_LOOKUP_PARTIAL, to lookup a key without waiting
1280  * for the key construction, and to retrieve uninstantiated keys (keys
1281  * without data attached to them).
1282  *
1283  * Return: a bpf_key pointer with a valid key pointer if the key is found, a
1284  *         NULL pointer otherwise.
1285  */
1286 __bpf_kfunc struct bpf_key *bpf_lookup_user_key(u32 serial, u64 flags)
1287 {
1288 	key_ref_t key_ref;
1289 	struct bpf_key *bkey;
1290 
1291 	if (flags & ~KEY_LOOKUP_ALL)
1292 		return NULL;
1293 
1294 	/*
1295 	 * Permission check is deferred until the key is used, as the
1296 	 * intent of the caller is unknown here.
1297 	 */
1298 	key_ref = lookup_user_key(serial, flags, KEY_DEFER_PERM_CHECK);
1299 	if (IS_ERR(key_ref))
1300 		return NULL;
1301 
1302 	bkey = kmalloc(sizeof(*bkey), GFP_KERNEL);
1303 	if (!bkey) {
1304 		key_put(key_ref_to_ptr(key_ref));
1305 		return NULL;
1306 	}
1307 
1308 	bkey->key = key_ref_to_ptr(key_ref);
1309 	bkey->has_ref = true;
1310 
1311 	return bkey;
1312 }
1313 
1314 /**
1315  * bpf_lookup_system_key - lookup a key by a system-defined ID
1316  * @id: key ID
1317  *
1318  * Obtain a bpf_key structure with a key pointer set to the passed key ID.
1319  * The key pointer is marked as invalid, to prevent bpf_key_put() from
1320  * attempting to decrement the key reference count on that pointer. The key
1321  * pointer set in such way is currently understood only by
1322  * verify_pkcs7_signature().
1323  *
1324  * Set *id* to one of the values defined in include/linux/verification.h:
1325  * 0 for the primary keyring (immutable keyring of system keys);
1326  * VERIFY_USE_SECONDARY_KEYRING for both the primary and secondary keyring
1327  * (where keys can be added only if they are vouched for by existing keys
1328  * in those keyrings); VERIFY_USE_PLATFORM_KEYRING for the platform
1329  * keyring (primarily used by the integrity subsystem to verify a kexec'ed
1330  * kerned image and, possibly, the initramfs signature).
1331  *
1332  * Return: a bpf_key pointer with an invalid key pointer set from the
1333  *         pre-determined ID on success, a NULL pointer otherwise
1334  */
1335 __bpf_kfunc struct bpf_key *bpf_lookup_system_key(u64 id)
1336 {
1337 	struct bpf_key *bkey;
1338 
1339 	if (system_keyring_id_check(id) < 0)
1340 		return NULL;
1341 
1342 	bkey = kmalloc(sizeof(*bkey), GFP_ATOMIC);
1343 	if (!bkey)
1344 		return NULL;
1345 
1346 	bkey->key = (struct key *)(unsigned long)id;
1347 	bkey->has_ref = false;
1348 
1349 	return bkey;
1350 }
1351 
1352 /**
1353  * bpf_key_put - decrement key reference count if key is valid and free bpf_key
1354  * @bkey: bpf_key structure
1355  *
1356  * Decrement the reference count of the key inside *bkey*, if the pointer
1357  * is valid, and free *bkey*.
1358  */
1359 __bpf_kfunc void bpf_key_put(struct bpf_key *bkey)
1360 {
1361 	if (bkey->has_ref)
1362 		key_put(bkey->key);
1363 
1364 	kfree(bkey);
1365 }
1366 
1367 #ifdef CONFIG_SYSTEM_DATA_VERIFICATION
1368 /**
1369  * bpf_verify_pkcs7_signature - verify a PKCS#7 signature
1370  * @data_ptr: data to verify
1371  * @sig_ptr: signature of the data
1372  * @trusted_keyring: keyring with keys trusted for signature verification
1373  *
1374  * Verify the PKCS#7 signature *sig_ptr* against the supplied *data_ptr*
1375  * with keys in a keyring referenced by *trusted_keyring*.
1376  *
1377  * Return: 0 on success, a negative value on error.
1378  */
1379 __bpf_kfunc int bpf_verify_pkcs7_signature(struct bpf_dynptr_kern *data_ptr,
1380 			       struct bpf_dynptr_kern *sig_ptr,
1381 			       struct bpf_key *trusted_keyring)
1382 {
1383 	int ret;
1384 
1385 	if (trusted_keyring->has_ref) {
1386 		/*
1387 		 * Do the permission check deferred in bpf_lookup_user_key().
1388 		 * See bpf_lookup_user_key() for more details.
1389 		 *
1390 		 * A call to key_task_permission() here would be redundant, as
1391 		 * it is already done by keyring_search() called by
1392 		 * find_asymmetric_key().
1393 		 */
1394 		ret = key_validate(trusted_keyring->key);
1395 		if (ret < 0)
1396 			return ret;
1397 	}
1398 
1399 	return verify_pkcs7_signature(data_ptr->data,
1400 				      __bpf_dynptr_size(data_ptr),
1401 				      sig_ptr->data,
1402 				      __bpf_dynptr_size(sig_ptr),
1403 				      trusted_keyring->key,
1404 				      VERIFYING_UNSPECIFIED_SIGNATURE, NULL,
1405 				      NULL);
1406 }
1407 #endif /* CONFIG_SYSTEM_DATA_VERIFICATION */
1408 
1409 __diag_pop();
1410 
1411 BTF_SET8_START(key_sig_kfunc_set)
1412 BTF_ID_FLAGS(func, bpf_lookup_user_key, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
1413 BTF_ID_FLAGS(func, bpf_lookup_system_key, KF_ACQUIRE | KF_RET_NULL)
1414 BTF_ID_FLAGS(func, bpf_key_put, KF_RELEASE)
1415 #ifdef CONFIG_SYSTEM_DATA_VERIFICATION
1416 BTF_ID_FLAGS(func, bpf_verify_pkcs7_signature, KF_SLEEPABLE)
1417 #endif
1418 BTF_SET8_END(key_sig_kfunc_set)
1419 
1420 static const struct btf_kfunc_id_set bpf_key_sig_kfunc_set = {
1421 	.owner = THIS_MODULE,
1422 	.set = &key_sig_kfunc_set,
1423 };
1424 
1425 static int __init bpf_key_sig_kfuncs_init(void)
1426 {
1427 	return register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
1428 					 &bpf_key_sig_kfunc_set);
1429 }
1430 
1431 late_initcall(bpf_key_sig_kfuncs_init);
1432 #endif /* CONFIG_KEYS */
1433 
1434 static const struct bpf_func_proto *
1435 bpf_tracing_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1436 {
1437 	switch (func_id) {
1438 	case BPF_FUNC_map_lookup_elem:
1439 		return &bpf_map_lookup_elem_proto;
1440 	case BPF_FUNC_map_update_elem:
1441 		return &bpf_map_update_elem_proto;
1442 	case BPF_FUNC_map_delete_elem:
1443 		return &bpf_map_delete_elem_proto;
1444 	case BPF_FUNC_map_push_elem:
1445 		return &bpf_map_push_elem_proto;
1446 	case BPF_FUNC_map_pop_elem:
1447 		return &bpf_map_pop_elem_proto;
1448 	case BPF_FUNC_map_peek_elem:
1449 		return &bpf_map_peek_elem_proto;
1450 	case BPF_FUNC_map_lookup_percpu_elem:
1451 		return &bpf_map_lookup_percpu_elem_proto;
1452 	case BPF_FUNC_ktime_get_ns:
1453 		return &bpf_ktime_get_ns_proto;
1454 	case BPF_FUNC_ktime_get_boot_ns:
1455 		return &bpf_ktime_get_boot_ns_proto;
1456 	case BPF_FUNC_tail_call:
1457 		return &bpf_tail_call_proto;
1458 	case BPF_FUNC_get_current_pid_tgid:
1459 		return &bpf_get_current_pid_tgid_proto;
1460 	case BPF_FUNC_get_current_task:
1461 		return &bpf_get_current_task_proto;
1462 	case BPF_FUNC_get_current_task_btf:
1463 		return &bpf_get_current_task_btf_proto;
1464 	case BPF_FUNC_task_pt_regs:
1465 		return &bpf_task_pt_regs_proto;
1466 	case BPF_FUNC_get_current_uid_gid:
1467 		return &bpf_get_current_uid_gid_proto;
1468 	case BPF_FUNC_get_current_comm:
1469 		return &bpf_get_current_comm_proto;
1470 	case BPF_FUNC_trace_printk:
1471 		return bpf_get_trace_printk_proto();
1472 	case BPF_FUNC_get_smp_processor_id:
1473 		return &bpf_get_smp_processor_id_proto;
1474 	case BPF_FUNC_get_numa_node_id:
1475 		return &bpf_get_numa_node_id_proto;
1476 	case BPF_FUNC_perf_event_read:
1477 		return &bpf_perf_event_read_proto;
1478 	case BPF_FUNC_current_task_under_cgroup:
1479 		return &bpf_current_task_under_cgroup_proto;
1480 	case BPF_FUNC_get_prandom_u32:
1481 		return &bpf_get_prandom_u32_proto;
1482 	case BPF_FUNC_probe_write_user:
1483 		return security_locked_down(LOCKDOWN_BPF_WRITE_USER) < 0 ?
1484 		       NULL : bpf_get_probe_write_proto();
1485 	case BPF_FUNC_probe_read_user:
1486 		return &bpf_probe_read_user_proto;
1487 	case BPF_FUNC_probe_read_kernel:
1488 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1489 		       NULL : &bpf_probe_read_kernel_proto;
1490 	case BPF_FUNC_probe_read_user_str:
1491 		return &bpf_probe_read_user_str_proto;
1492 	case BPF_FUNC_probe_read_kernel_str:
1493 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1494 		       NULL : &bpf_probe_read_kernel_str_proto;
1495 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
1496 	case BPF_FUNC_probe_read:
1497 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1498 		       NULL : &bpf_probe_read_compat_proto;
1499 	case BPF_FUNC_probe_read_str:
1500 		return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
1501 		       NULL : &bpf_probe_read_compat_str_proto;
1502 #endif
1503 #ifdef CONFIG_CGROUPS
1504 	case BPF_FUNC_cgrp_storage_get:
1505 		return &bpf_cgrp_storage_get_proto;
1506 	case BPF_FUNC_cgrp_storage_delete:
1507 		return &bpf_cgrp_storage_delete_proto;
1508 #endif
1509 	case BPF_FUNC_send_signal:
1510 		return &bpf_send_signal_proto;
1511 	case BPF_FUNC_send_signal_thread:
1512 		return &bpf_send_signal_thread_proto;
1513 	case BPF_FUNC_perf_event_read_value:
1514 		return &bpf_perf_event_read_value_proto;
1515 	case BPF_FUNC_get_ns_current_pid_tgid:
1516 		return &bpf_get_ns_current_pid_tgid_proto;
1517 	case BPF_FUNC_ringbuf_output:
1518 		return &bpf_ringbuf_output_proto;
1519 	case BPF_FUNC_ringbuf_reserve:
1520 		return &bpf_ringbuf_reserve_proto;
1521 	case BPF_FUNC_ringbuf_submit:
1522 		return &bpf_ringbuf_submit_proto;
1523 	case BPF_FUNC_ringbuf_discard:
1524 		return &bpf_ringbuf_discard_proto;
1525 	case BPF_FUNC_ringbuf_query:
1526 		return &bpf_ringbuf_query_proto;
1527 	case BPF_FUNC_jiffies64:
1528 		return &bpf_jiffies64_proto;
1529 	case BPF_FUNC_get_task_stack:
1530 		return &bpf_get_task_stack_proto;
1531 	case BPF_FUNC_copy_from_user:
1532 		return &bpf_copy_from_user_proto;
1533 	case BPF_FUNC_copy_from_user_task:
1534 		return &bpf_copy_from_user_task_proto;
1535 	case BPF_FUNC_snprintf_btf:
1536 		return &bpf_snprintf_btf_proto;
1537 	case BPF_FUNC_per_cpu_ptr:
1538 		return &bpf_per_cpu_ptr_proto;
1539 	case BPF_FUNC_this_cpu_ptr:
1540 		return &bpf_this_cpu_ptr_proto;
1541 	case BPF_FUNC_task_storage_get:
1542 		if (bpf_prog_check_recur(prog))
1543 			return &bpf_task_storage_get_recur_proto;
1544 		return &bpf_task_storage_get_proto;
1545 	case BPF_FUNC_task_storage_delete:
1546 		if (bpf_prog_check_recur(prog))
1547 			return &bpf_task_storage_delete_recur_proto;
1548 		return &bpf_task_storage_delete_proto;
1549 	case BPF_FUNC_for_each_map_elem:
1550 		return &bpf_for_each_map_elem_proto;
1551 	case BPF_FUNC_snprintf:
1552 		return &bpf_snprintf_proto;
1553 	case BPF_FUNC_get_func_ip:
1554 		return &bpf_get_func_ip_proto_tracing;
1555 	case BPF_FUNC_get_branch_snapshot:
1556 		return &bpf_get_branch_snapshot_proto;
1557 	case BPF_FUNC_find_vma:
1558 		return &bpf_find_vma_proto;
1559 	case BPF_FUNC_trace_vprintk:
1560 		return bpf_get_trace_vprintk_proto();
1561 	default:
1562 		return bpf_base_func_proto(func_id);
1563 	}
1564 }
1565 
1566 static const struct bpf_func_proto *
1567 kprobe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1568 {
1569 	switch (func_id) {
1570 	case BPF_FUNC_perf_event_output:
1571 		return &bpf_perf_event_output_proto;
1572 	case BPF_FUNC_get_stackid:
1573 		return &bpf_get_stackid_proto;
1574 	case BPF_FUNC_get_stack:
1575 		return &bpf_get_stack_proto;
1576 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
1577 	case BPF_FUNC_override_return:
1578 		return &bpf_override_return_proto;
1579 #endif
1580 	case BPF_FUNC_get_func_ip:
1581 		if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI)
1582 			return &bpf_get_func_ip_proto_kprobe_multi;
1583 		if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI)
1584 			return &bpf_get_func_ip_proto_uprobe_multi;
1585 		return &bpf_get_func_ip_proto_kprobe;
1586 	case BPF_FUNC_get_attach_cookie:
1587 		if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI)
1588 			return &bpf_get_attach_cookie_proto_kmulti;
1589 		if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI)
1590 			return &bpf_get_attach_cookie_proto_umulti;
1591 		return &bpf_get_attach_cookie_proto_trace;
1592 	default:
1593 		return bpf_tracing_func_proto(func_id, prog);
1594 	}
1595 }
1596 
1597 /* bpf+kprobe programs can access fields of 'struct pt_regs' */
1598 static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1599 					const struct bpf_prog *prog,
1600 					struct bpf_insn_access_aux *info)
1601 {
1602 	if (off < 0 || off >= sizeof(struct pt_regs))
1603 		return false;
1604 	if (type != BPF_READ)
1605 		return false;
1606 	if (off % size != 0)
1607 		return false;
1608 	/*
1609 	 * Assertion for 32 bit to make sure last 8 byte access
1610 	 * (BPF_DW) to the last 4 byte member is disallowed.
1611 	 */
1612 	if (off + size > sizeof(struct pt_regs))
1613 		return false;
1614 
1615 	return true;
1616 }
1617 
1618 const struct bpf_verifier_ops kprobe_verifier_ops = {
1619 	.get_func_proto  = kprobe_prog_func_proto,
1620 	.is_valid_access = kprobe_prog_is_valid_access,
1621 };
1622 
1623 const struct bpf_prog_ops kprobe_prog_ops = {
1624 };
1625 
1626 BPF_CALL_5(bpf_perf_event_output_tp, void *, tp_buff, struct bpf_map *, map,
1627 	   u64, flags, void *, data, u64, size)
1628 {
1629 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1630 
1631 	/*
1632 	 * r1 points to perf tracepoint buffer where first 8 bytes are hidden
1633 	 * from bpf program and contain a pointer to 'struct pt_regs'. Fetch it
1634 	 * from there and call the same bpf_perf_event_output() helper inline.
1635 	 */
1636 	return ____bpf_perf_event_output(regs, map, flags, data, size);
1637 }
1638 
1639 static const struct bpf_func_proto bpf_perf_event_output_proto_tp = {
1640 	.func		= bpf_perf_event_output_tp,
1641 	.gpl_only	= true,
1642 	.ret_type	= RET_INTEGER,
1643 	.arg1_type	= ARG_PTR_TO_CTX,
1644 	.arg2_type	= ARG_CONST_MAP_PTR,
1645 	.arg3_type	= ARG_ANYTHING,
1646 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1647 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1648 };
1649 
1650 BPF_CALL_3(bpf_get_stackid_tp, void *, tp_buff, struct bpf_map *, map,
1651 	   u64, flags)
1652 {
1653 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1654 
1655 	/*
1656 	 * Same comment as in bpf_perf_event_output_tp(), only that this time
1657 	 * the other helper's function body cannot be inlined due to being
1658 	 * external, thus we need to call raw helper function.
1659 	 */
1660 	return bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1661 			       flags, 0, 0);
1662 }
1663 
1664 static const struct bpf_func_proto bpf_get_stackid_proto_tp = {
1665 	.func		= bpf_get_stackid_tp,
1666 	.gpl_only	= true,
1667 	.ret_type	= RET_INTEGER,
1668 	.arg1_type	= ARG_PTR_TO_CTX,
1669 	.arg2_type	= ARG_CONST_MAP_PTR,
1670 	.arg3_type	= ARG_ANYTHING,
1671 };
1672 
1673 BPF_CALL_4(bpf_get_stack_tp, void *, tp_buff, void *, buf, u32, size,
1674 	   u64, flags)
1675 {
1676 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
1677 
1678 	return bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1679 			     (unsigned long) size, flags, 0);
1680 }
1681 
1682 static const struct bpf_func_proto bpf_get_stack_proto_tp = {
1683 	.func		= bpf_get_stack_tp,
1684 	.gpl_only	= true,
1685 	.ret_type	= RET_INTEGER,
1686 	.arg1_type	= ARG_PTR_TO_CTX,
1687 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
1688 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
1689 	.arg4_type	= ARG_ANYTHING,
1690 };
1691 
1692 static const struct bpf_func_proto *
1693 tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1694 {
1695 	switch (func_id) {
1696 	case BPF_FUNC_perf_event_output:
1697 		return &bpf_perf_event_output_proto_tp;
1698 	case BPF_FUNC_get_stackid:
1699 		return &bpf_get_stackid_proto_tp;
1700 	case BPF_FUNC_get_stack:
1701 		return &bpf_get_stack_proto_tp;
1702 	case BPF_FUNC_get_attach_cookie:
1703 		return &bpf_get_attach_cookie_proto_trace;
1704 	default:
1705 		return bpf_tracing_func_proto(func_id, prog);
1706 	}
1707 }
1708 
1709 static bool tp_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1710 				    const struct bpf_prog *prog,
1711 				    struct bpf_insn_access_aux *info)
1712 {
1713 	if (off < sizeof(void *) || off >= PERF_MAX_TRACE_SIZE)
1714 		return false;
1715 	if (type != BPF_READ)
1716 		return false;
1717 	if (off % size != 0)
1718 		return false;
1719 
1720 	BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(__u64));
1721 	return true;
1722 }
1723 
1724 const struct bpf_verifier_ops tracepoint_verifier_ops = {
1725 	.get_func_proto  = tp_prog_func_proto,
1726 	.is_valid_access = tp_prog_is_valid_access,
1727 };
1728 
1729 const struct bpf_prog_ops tracepoint_prog_ops = {
1730 };
1731 
1732 BPF_CALL_3(bpf_perf_prog_read_value, struct bpf_perf_event_data_kern *, ctx,
1733 	   struct bpf_perf_event_value *, buf, u32, size)
1734 {
1735 	int err = -EINVAL;
1736 
1737 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
1738 		goto clear;
1739 	err = perf_event_read_local(ctx->event, &buf->counter, &buf->enabled,
1740 				    &buf->running);
1741 	if (unlikely(err))
1742 		goto clear;
1743 	return 0;
1744 clear:
1745 	memset(buf, 0, size);
1746 	return err;
1747 }
1748 
1749 static const struct bpf_func_proto bpf_perf_prog_read_value_proto = {
1750          .func           = bpf_perf_prog_read_value,
1751          .gpl_only       = true,
1752          .ret_type       = RET_INTEGER,
1753          .arg1_type      = ARG_PTR_TO_CTX,
1754          .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
1755          .arg3_type      = ARG_CONST_SIZE,
1756 };
1757 
1758 BPF_CALL_4(bpf_read_branch_records, struct bpf_perf_event_data_kern *, ctx,
1759 	   void *, buf, u32, size, u64, flags)
1760 {
1761 	static const u32 br_entry_size = sizeof(struct perf_branch_entry);
1762 	struct perf_branch_stack *br_stack = ctx->data->br_stack;
1763 	u32 to_copy;
1764 
1765 	if (unlikely(flags & ~BPF_F_GET_BRANCH_RECORDS_SIZE))
1766 		return -EINVAL;
1767 
1768 	if (unlikely(!(ctx->data->sample_flags & PERF_SAMPLE_BRANCH_STACK)))
1769 		return -ENOENT;
1770 
1771 	if (unlikely(!br_stack))
1772 		return -ENOENT;
1773 
1774 	if (flags & BPF_F_GET_BRANCH_RECORDS_SIZE)
1775 		return br_stack->nr * br_entry_size;
1776 
1777 	if (!buf || (size % br_entry_size != 0))
1778 		return -EINVAL;
1779 
1780 	to_copy = min_t(u32, br_stack->nr * br_entry_size, size);
1781 	memcpy(buf, br_stack->entries, to_copy);
1782 
1783 	return to_copy;
1784 }
1785 
1786 static const struct bpf_func_proto bpf_read_branch_records_proto = {
1787 	.func           = bpf_read_branch_records,
1788 	.gpl_only       = true,
1789 	.ret_type       = RET_INTEGER,
1790 	.arg1_type      = ARG_PTR_TO_CTX,
1791 	.arg2_type      = ARG_PTR_TO_MEM_OR_NULL,
1792 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
1793 	.arg4_type      = ARG_ANYTHING,
1794 };
1795 
1796 static const struct bpf_func_proto *
1797 pe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1798 {
1799 	switch (func_id) {
1800 	case BPF_FUNC_perf_event_output:
1801 		return &bpf_perf_event_output_proto_tp;
1802 	case BPF_FUNC_get_stackid:
1803 		return &bpf_get_stackid_proto_pe;
1804 	case BPF_FUNC_get_stack:
1805 		return &bpf_get_stack_proto_pe;
1806 	case BPF_FUNC_perf_prog_read_value:
1807 		return &bpf_perf_prog_read_value_proto;
1808 	case BPF_FUNC_read_branch_records:
1809 		return &bpf_read_branch_records_proto;
1810 	case BPF_FUNC_get_attach_cookie:
1811 		return &bpf_get_attach_cookie_proto_pe;
1812 	default:
1813 		return bpf_tracing_func_proto(func_id, prog);
1814 	}
1815 }
1816 
1817 /*
1818  * bpf_raw_tp_regs are separate from bpf_pt_regs used from skb/xdp
1819  * to avoid potential recursive reuse issue when/if tracepoints are added
1820  * inside bpf_*_event_output, bpf_get_stackid and/or bpf_get_stack.
1821  *
1822  * Since raw tracepoints run despite bpf_prog_active, support concurrent usage
1823  * in normal, irq, and nmi context.
1824  */
1825 struct bpf_raw_tp_regs {
1826 	struct pt_regs regs[3];
1827 };
1828 static DEFINE_PER_CPU(struct bpf_raw_tp_regs, bpf_raw_tp_regs);
1829 static DEFINE_PER_CPU(int, bpf_raw_tp_nest_level);
1830 static struct pt_regs *get_bpf_raw_tp_regs(void)
1831 {
1832 	struct bpf_raw_tp_regs *tp_regs = this_cpu_ptr(&bpf_raw_tp_regs);
1833 	int nest_level = this_cpu_inc_return(bpf_raw_tp_nest_level);
1834 
1835 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(tp_regs->regs))) {
1836 		this_cpu_dec(bpf_raw_tp_nest_level);
1837 		return ERR_PTR(-EBUSY);
1838 	}
1839 
1840 	return &tp_regs->regs[nest_level - 1];
1841 }
1842 
1843 static void put_bpf_raw_tp_regs(void)
1844 {
1845 	this_cpu_dec(bpf_raw_tp_nest_level);
1846 }
1847 
1848 BPF_CALL_5(bpf_perf_event_output_raw_tp, struct bpf_raw_tracepoint_args *, args,
1849 	   struct bpf_map *, map, u64, flags, void *, data, u64, size)
1850 {
1851 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1852 	int ret;
1853 
1854 	if (IS_ERR(regs))
1855 		return PTR_ERR(regs);
1856 
1857 	perf_fetch_caller_regs(regs);
1858 	ret = ____bpf_perf_event_output(regs, map, flags, data, size);
1859 
1860 	put_bpf_raw_tp_regs();
1861 	return ret;
1862 }
1863 
1864 static const struct bpf_func_proto bpf_perf_event_output_proto_raw_tp = {
1865 	.func		= bpf_perf_event_output_raw_tp,
1866 	.gpl_only	= true,
1867 	.ret_type	= RET_INTEGER,
1868 	.arg1_type	= ARG_PTR_TO_CTX,
1869 	.arg2_type	= ARG_CONST_MAP_PTR,
1870 	.arg3_type	= ARG_ANYTHING,
1871 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1872 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
1873 };
1874 
1875 extern const struct bpf_func_proto bpf_skb_output_proto;
1876 extern const struct bpf_func_proto bpf_xdp_output_proto;
1877 extern const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto;
1878 
1879 BPF_CALL_3(bpf_get_stackid_raw_tp, struct bpf_raw_tracepoint_args *, args,
1880 	   struct bpf_map *, map, u64, flags)
1881 {
1882 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1883 	int ret;
1884 
1885 	if (IS_ERR(regs))
1886 		return PTR_ERR(regs);
1887 
1888 	perf_fetch_caller_regs(regs);
1889 	/* similar to bpf_perf_event_output_tp, but pt_regs fetched differently */
1890 	ret = bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1891 			      flags, 0, 0);
1892 	put_bpf_raw_tp_regs();
1893 	return ret;
1894 }
1895 
1896 static const struct bpf_func_proto bpf_get_stackid_proto_raw_tp = {
1897 	.func		= bpf_get_stackid_raw_tp,
1898 	.gpl_only	= true,
1899 	.ret_type	= RET_INTEGER,
1900 	.arg1_type	= ARG_PTR_TO_CTX,
1901 	.arg2_type	= ARG_CONST_MAP_PTR,
1902 	.arg3_type	= ARG_ANYTHING,
1903 };
1904 
1905 BPF_CALL_4(bpf_get_stack_raw_tp, struct bpf_raw_tracepoint_args *, args,
1906 	   void *, buf, u32, size, u64, flags)
1907 {
1908 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1909 	int ret;
1910 
1911 	if (IS_ERR(regs))
1912 		return PTR_ERR(regs);
1913 
1914 	perf_fetch_caller_regs(regs);
1915 	ret = bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1916 			    (unsigned long) size, flags, 0);
1917 	put_bpf_raw_tp_regs();
1918 	return ret;
1919 }
1920 
1921 static const struct bpf_func_proto bpf_get_stack_proto_raw_tp = {
1922 	.func		= bpf_get_stack_raw_tp,
1923 	.gpl_only	= true,
1924 	.ret_type	= RET_INTEGER,
1925 	.arg1_type	= ARG_PTR_TO_CTX,
1926 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1927 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
1928 	.arg4_type	= ARG_ANYTHING,
1929 };
1930 
1931 static const struct bpf_func_proto *
1932 raw_tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1933 {
1934 	switch (func_id) {
1935 	case BPF_FUNC_perf_event_output:
1936 		return &bpf_perf_event_output_proto_raw_tp;
1937 	case BPF_FUNC_get_stackid:
1938 		return &bpf_get_stackid_proto_raw_tp;
1939 	case BPF_FUNC_get_stack:
1940 		return &bpf_get_stack_proto_raw_tp;
1941 	default:
1942 		return bpf_tracing_func_proto(func_id, prog);
1943 	}
1944 }
1945 
1946 const struct bpf_func_proto *
1947 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1948 {
1949 	const struct bpf_func_proto *fn;
1950 
1951 	switch (func_id) {
1952 #ifdef CONFIG_NET
1953 	case BPF_FUNC_skb_output:
1954 		return &bpf_skb_output_proto;
1955 	case BPF_FUNC_xdp_output:
1956 		return &bpf_xdp_output_proto;
1957 	case BPF_FUNC_skc_to_tcp6_sock:
1958 		return &bpf_skc_to_tcp6_sock_proto;
1959 	case BPF_FUNC_skc_to_tcp_sock:
1960 		return &bpf_skc_to_tcp_sock_proto;
1961 	case BPF_FUNC_skc_to_tcp_timewait_sock:
1962 		return &bpf_skc_to_tcp_timewait_sock_proto;
1963 	case BPF_FUNC_skc_to_tcp_request_sock:
1964 		return &bpf_skc_to_tcp_request_sock_proto;
1965 	case BPF_FUNC_skc_to_udp6_sock:
1966 		return &bpf_skc_to_udp6_sock_proto;
1967 	case BPF_FUNC_skc_to_unix_sock:
1968 		return &bpf_skc_to_unix_sock_proto;
1969 	case BPF_FUNC_skc_to_mptcp_sock:
1970 		return &bpf_skc_to_mptcp_sock_proto;
1971 	case BPF_FUNC_sk_storage_get:
1972 		return &bpf_sk_storage_get_tracing_proto;
1973 	case BPF_FUNC_sk_storage_delete:
1974 		return &bpf_sk_storage_delete_tracing_proto;
1975 	case BPF_FUNC_sock_from_file:
1976 		return &bpf_sock_from_file_proto;
1977 	case BPF_FUNC_get_socket_cookie:
1978 		return &bpf_get_socket_ptr_cookie_proto;
1979 	case BPF_FUNC_xdp_get_buff_len:
1980 		return &bpf_xdp_get_buff_len_trace_proto;
1981 #endif
1982 	case BPF_FUNC_seq_printf:
1983 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1984 		       &bpf_seq_printf_proto :
1985 		       NULL;
1986 	case BPF_FUNC_seq_write:
1987 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1988 		       &bpf_seq_write_proto :
1989 		       NULL;
1990 	case BPF_FUNC_seq_printf_btf:
1991 		return prog->expected_attach_type == BPF_TRACE_ITER ?
1992 		       &bpf_seq_printf_btf_proto :
1993 		       NULL;
1994 	case BPF_FUNC_d_path:
1995 		return &bpf_d_path_proto;
1996 	case BPF_FUNC_get_func_arg:
1997 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_arg_proto : NULL;
1998 	case BPF_FUNC_get_func_ret:
1999 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_ret_proto : NULL;
2000 	case BPF_FUNC_get_func_arg_cnt:
2001 		return bpf_prog_has_trampoline(prog) ? &bpf_get_func_arg_cnt_proto : NULL;
2002 	case BPF_FUNC_get_attach_cookie:
2003 		return bpf_prog_has_trampoline(prog) ? &bpf_get_attach_cookie_proto_tracing : NULL;
2004 	default:
2005 		fn = raw_tp_prog_func_proto(func_id, prog);
2006 		if (!fn && prog->expected_attach_type == BPF_TRACE_ITER)
2007 			fn = bpf_iter_get_func_proto(func_id, prog);
2008 		return fn;
2009 	}
2010 }
2011 
2012 static bool raw_tp_prog_is_valid_access(int off, int size,
2013 					enum bpf_access_type type,
2014 					const struct bpf_prog *prog,
2015 					struct bpf_insn_access_aux *info)
2016 {
2017 	return bpf_tracing_ctx_access(off, size, type);
2018 }
2019 
2020 static bool tracing_prog_is_valid_access(int off, int size,
2021 					 enum bpf_access_type type,
2022 					 const struct bpf_prog *prog,
2023 					 struct bpf_insn_access_aux *info)
2024 {
2025 	return bpf_tracing_btf_ctx_access(off, size, type, prog, info);
2026 }
2027 
2028 int __weak bpf_prog_test_run_tracing(struct bpf_prog *prog,
2029 				     const union bpf_attr *kattr,
2030 				     union bpf_attr __user *uattr)
2031 {
2032 	return -ENOTSUPP;
2033 }
2034 
2035 const struct bpf_verifier_ops raw_tracepoint_verifier_ops = {
2036 	.get_func_proto  = raw_tp_prog_func_proto,
2037 	.is_valid_access = raw_tp_prog_is_valid_access,
2038 };
2039 
2040 const struct bpf_prog_ops raw_tracepoint_prog_ops = {
2041 #ifdef CONFIG_NET
2042 	.test_run = bpf_prog_test_run_raw_tp,
2043 #endif
2044 };
2045 
2046 const struct bpf_verifier_ops tracing_verifier_ops = {
2047 	.get_func_proto  = tracing_prog_func_proto,
2048 	.is_valid_access = tracing_prog_is_valid_access,
2049 };
2050 
2051 const struct bpf_prog_ops tracing_prog_ops = {
2052 	.test_run = bpf_prog_test_run_tracing,
2053 };
2054 
2055 static bool raw_tp_writable_prog_is_valid_access(int off, int size,
2056 						 enum bpf_access_type type,
2057 						 const struct bpf_prog *prog,
2058 						 struct bpf_insn_access_aux *info)
2059 {
2060 	if (off == 0) {
2061 		if (size != sizeof(u64) || type != BPF_READ)
2062 			return false;
2063 		info->reg_type = PTR_TO_TP_BUFFER;
2064 	}
2065 	return raw_tp_prog_is_valid_access(off, size, type, prog, info);
2066 }
2067 
2068 const struct bpf_verifier_ops raw_tracepoint_writable_verifier_ops = {
2069 	.get_func_proto  = raw_tp_prog_func_proto,
2070 	.is_valid_access = raw_tp_writable_prog_is_valid_access,
2071 };
2072 
2073 const struct bpf_prog_ops raw_tracepoint_writable_prog_ops = {
2074 };
2075 
2076 static bool pe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
2077 				    const struct bpf_prog *prog,
2078 				    struct bpf_insn_access_aux *info)
2079 {
2080 	const int size_u64 = sizeof(u64);
2081 
2082 	if (off < 0 || off >= sizeof(struct bpf_perf_event_data))
2083 		return false;
2084 	if (type != BPF_READ)
2085 		return false;
2086 	if (off % size != 0) {
2087 		if (sizeof(unsigned long) != 4)
2088 			return false;
2089 		if (size != 8)
2090 			return false;
2091 		if (off % size != 4)
2092 			return false;
2093 	}
2094 
2095 	switch (off) {
2096 	case bpf_ctx_range(struct bpf_perf_event_data, sample_period):
2097 		bpf_ctx_record_field_size(info, size_u64);
2098 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
2099 			return false;
2100 		break;
2101 	case bpf_ctx_range(struct bpf_perf_event_data, addr):
2102 		bpf_ctx_record_field_size(info, size_u64);
2103 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
2104 			return false;
2105 		break;
2106 	default:
2107 		if (size != sizeof(long))
2108 			return false;
2109 	}
2110 
2111 	return true;
2112 }
2113 
2114 static u32 pe_prog_convert_ctx_access(enum bpf_access_type type,
2115 				      const struct bpf_insn *si,
2116 				      struct bpf_insn *insn_buf,
2117 				      struct bpf_prog *prog, u32 *target_size)
2118 {
2119 	struct bpf_insn *insn = insn_buf;
2120 
2121 	switch (si->off) {
2122 	case offsetof(struct bpf_perf_event_data, sample_period):
2123 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
2124 						       data), si->dst_reg, si->src_reg,
2125 				      offsetof(struct bpf_perf_event_data_kern, data));
2126 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
2127 				      bpf_target_off(struct perf_sample_data, period, 8,
2128 						     target_size));
2129 		break;
2130 	case offsetof(struct bpf_perf_event_data, addr):
2131 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
2132 						       data), si->dst_reg, si->src_reg,
2133 				      offsetof(struct bpf_perf_event_data_kern, data));
2134 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
2135 				      bpf_target_off(struct perf_sample_data, addr, 8,
2136 						     target_size));
2137 		break;
2138 	default:
2139 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
2140 						       regs), si->dst_reg, si->src_reg,
2141 				      offsetof(struct bpf_perf_event_data_kern, regs));
2142 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(long), si->dst_reg, si->dst_reg,
2143 				      si->off);
2144 		break;
2145 	}
2146 
2147 	return insn - insn_buf;
2148 }
2149 
2150 const struct bpf_verifier_ops perf_event_verifier_ops = {
2151 	.get_func_proto		= pe_prog_func_proto,
2152 	.is_valid_access	= pe_prog_is_valid_access,
2153 	.convert_ctx_access	= pe_prog_convert_ctx_access,
2154 };
2155 
2156 const struct bpf_prog_ops perf_event_prog_ops = {
2157 };
2158 
2159 static DEFINE_MUTEX(bpf_event_mutex);
2160 
2161 #define BPF_TRACE_MAX_PROGS 64
2162 
2163 int perf_event_attach_bpf_prog(struct perf_event *event,
2164 			       struct bpf_prog *prog,
2165 			       u64 bpf_cookie)
2166 {
2167 	struct bpf_prog_array *old_array;
2168 	struct bpf_prog_array *new_array;
2169 	int ret = -EEXIST;
2170 
2171 	/*
2172 	 * Kprobe override only works if they are on the function entry,
2173 	 * and only if they are on the opt-in list.
2174 	 */
2175 	if (prog->kprobe_override &&
2176 	    (!trace_kprobe_on_func_entry(event->tp_event) ||
2177 	     !trace_kprobe_error_injectable(event->tp_event)))
2178 		return -EINVAL;
2179 
2180 	mutex_lock(&bpf_event_mutex);
2181 
2182 	if (event->prog)
2183 		goto unlock;
2184 
2185 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
2186 	if (old_array &&
2187 	    bpf_prog_array_length(old_array) >= BPF_TRACE_MAX_PROGS) {
2188 		ret = -E2BIG;
2189 		goto unlock;
2190 	}
2191 
2192 	ret = bpf_prog_array_copy(old_array, NULL, prog, bpf_cookie, &new_array);
2193 	if (ret < 0)
2194 		goto unlock;
2195 
2196 	/* set the new array to event->tp_event and set event->prog */
2197 	event->prog = prog;
2198 	event->bpf_cookie = bpf_cookie;
2199 	rcu_assign_pointer(event->tp_event->prog_array, new_array);
2200 	bpf_prog_array_free_sleepable(old_array);
2201 
2202 unlock:
2203 	mutex_unlock(&bpf_event_mutex);
2204 	return ret;
2205 }
2206 
2207 void perf_event_detach_bpf_prog(struct perf_event *event)
2208 {
2209 	struct bpf_prog_array *old_array;
2210 	struct bpf_prog_array *new_array;
2211 	int ret;
2212 
2213 	mutex_lock(&bpf_event_mutex);
2214 
2215 	if (!event->prog)
2216 		goto unlock;
2217 
2218 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
2219 	ret = bpf_prog_array_copy(old_array, event->prog, NULL, 0, &new_array);
2220 	if (ret == -ENOENT)
2221 		goto unlock;
2222 	if (ret < 0) {
2223 		bpf_prog_array_delete_safe(old_array, event->prog);
2224 	} else {
2225 		rcu_assign_pointer(event->tp_event->prog_array, new_array);
2226 		bpf_prog_array_free_sleepable(old_array);
2227 	}
2228 
2229 	bpf_prog_put(event->prog);
2230 	event->prog = NULL;
2231 
2232 unlock:
2233 	mutex_unlock(&bpf_event_mutex);
2234 }
2235 
2236 int perf_event_query_prog_array(struct perf_event *event, void __user *info)
2237 {
2238 	struct perf_event_query_bpf __user *uquery = info;
2239 	struct perf_event_query_bpf query = {};
2240 	struct bpf_prog_array *progs;
2241 	u32 *ids, prog_cnt, ids_len;
2242 	int ret;
2243 
2244 	if (!perfmon_capable())
2245 		return -EPERM;
2246 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
2247 		return -EINVAL;
2248 	if (copy_from_user(&query, uquery, sizeof(query)))
2249 		return -EFAULT;
2250 
2251 	ids_len = query.ids_len;
2252 	if (ids_len > BPF_TRACE_MAX_PROGS)
2253 		return -E2BIG;
2254 	ids = kcalloc(ids_len, sizeof(u32), GFP_USER | __GFP_NOWARN);
2255 	if (!ids)
2256 		return -ENOMEM;
2257 	/*
2258 	 * The above kcalloc returns ZERO_SIZE_PTR when ids_len = 0, which
2259 	 * is required when user only wants to check for uquery->prog_cnt.
2260 	 * There is no need to check for it since the case is handled
2261 	 * gracefully in bpf_prog_array_copy_info.
2262 	 */
2263 
2264 	mutex_lock(&bpf_event_mutex);
2265 	progs = bpf_event_rcu_dereference(event->tp_event->prog_array);
2266 	ret = bpf_prog_array_copy_info(progs, ids, ids_len, &prog_cnt);
2267 	mutex_unlock(&bpf_event_mutex);
2268 
2269 	if (copy_to_user(&uquery->prog_cnt, &prog_cnt, sizeof(prog_cnt)) ||
2270 	    copy_to_user(uquery->ids, ids, ids_len * sizeof(u32)))
2271 		ret = -EFAULT;
2272 
2273 	kfree(ids);
2274 	return ret;
2275 }
2276 
2277 extern struct bpf_raw_event_map __start__bpf_raw_tp[];
2278 extern struct bpf_raw_event_map __stop__bpf_raw_tp[];
2279 
2280 struct bpf_raw_event_map *bpf_get_raw_tracepoint(const char *name)
2281 {
2282 	struct bpf_raw_event_map *btp = __start__bpf_raw_tp;
2283 
2284 	for (; btp < __stop__bpf_raw_tp; btp++) {
2285 		if (!strcmp(btp->tp->name, name))
2286 			return btp;
2287 	}
2288 
2289 	return bpf_get_raw_tracepoint_module(name);
2290 }
2291 
2292 void bpf_put_raw_tracepoint(struct bpf_raw_event_map *btp)
2293 {
2294 	struct module *mod;
2295 
2296 	preempt_disable();
2297 	mod = __module_address((unsigned long)btp);
2298 	module_put(mod);
2299 	preempt_enable();
2300 }
2301 
2302 static __always_inline
2303 void __bpf_trace_run(struct bpf_prog *prog, u64 *args)
2304 {
2305 	cant_sleep();
2306 	if (unlikely(this_cpu_inc_return(*(prog->active)) != 1)) {
2307 		bpf_prog_inc_misses_counter(prog);
2308 		goto out;
2309 	}
2310 	rcu_read_lock();
2311 	(void) bpf_prog_run(prog, args);
2312 	rcu_read_unlock();
2313 out:
2314 	this_cpu_dec(*(prog->active));
2315 }
2316 
2317 #define UNPACK(...)			__VA_ARGS__
2318 #define REPEAT_1(FN, DL, X, ...)	FN(X)
2319 #define REPEAT_2(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_1(FN, DL, __VA_ARGS__)
2320 #define REPEAT_3(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_2(FN, DL, __VA_ARGS__)
2321 #define REPEAT_4(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_3(FN, DL, __VA_ARGS__)
2322 #define REPEAT_5(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_4(FN, DL, __VA_ARGS__)
2323 #define REPEAT_6(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_5(FN, DL, __VA_ARGS__)
2324 #define REPEAT_7(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_6(FN, DL, __VA_ARGS__)
2325 #define REPEAT_8(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_7(FN, DL, __VA_ARGS__)
2326 #define REPEAT_9(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_8(FN, DL, __VA_ARGS__)
2327 #define REPEAT_10(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_9(FN, DL, __VA_ARGS__)
2328 #define REPEAT_11(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_10(FN, DL, __VA_ARGS__)
2329 #define REPEAT_12(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_11(FN, DL, __VA_ARGS__)
2330 #define REPEAT(X, FN, DL, ...)		REPEAT_##X(FN, DL, __VA_ARGS__)
2331 
2332 #define SARG(X)		u64 arg##X
2333 #define COPY(X)		args[X] = arg##X
2334 
2335 #define __DL_COM	(,)
2336 #define __DL_SEM	(;)
2337 
2338 #define __SEQ_0_11	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
2339 
2340 #define BPF_TRACE_DEFN_x(x)						\
2341 	void bpf_trace_run##x(struct bpf_prog *prog,			\
2342 			      REPEAT(x, SARG, __DL_COM, __SEQ_0_11))	\
2343 	{								\
2344 		u64 args[x];						\
2345 		REPEAT(x, COPY, __DL_SEM, __SEQ_0_11);			\
2346 		__bpf_trace_run(prog, args);				\
2347 	}								\
2348 	EXPORT_SYMBOL_GPL(bpf_trace_run##x)
2349 BPF_TRACE_DEFN_x(1);
2350 BPF_TRACE_DEFN_x(2);
2351 BPF_TRACE_DEFN_x(3);
2352 BPF_TRACE_DEFN_x(4);
2353 BPF_TRACE_DEFN_x(5);
2354 BPF_TRACE_DEFN_x(6);
2355 BPF_TRACE_DEFN_x(7);
2356 BPF_TRACE_DEFN_x(8);
2357 BPF_TRACE_DEFN_x(9);
2358 BPF_TRACE_DEFN_x(10);
2359 BPF_TRACE_DEFN_x(11);
2360 BPF_TRACE_DEFN_x(12);
2361 
2362 static int __bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
2363 {
2364 	struct tracepoint *tp = btp->tp;
2365 
2366 	/*
2367 	 * check that program doesn't access arguments beyond what's
2368 	 * available in this tracepoint
2369 	 */
2370 	if (prog->aux->max_ctx_offset > btp->num_args * sizeof(u64))
2371 		return -EINVAL;
2372 
2373 	if (prog->aux->max_tp_access > btp->writable_size)
2374 		return -EINVAL;
2375 
2376 	return tracepoint_probe_register_may_exist(tp, (void *)btp->bpf_func,
2377 						   prog);
2378 }
2379 
2380 int bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
2381 {
2382 	return __bpf_probe_register(btp, prog);
2383 }
2384 
2385 int bpf_probe_unregister(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
2386 {
2387 	return tracepoint_probe_unregister(btp->tp, (void *)btp->bpf_func, prog);
2388 }
2389 
2390 int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id,
2391 			    u32 *fd_type, const char **buf,
2392 			    u64 *probe_offset, u64 *probe_addr)
2393 {
2394 	bool is_tracepoint, is_syscall_tp;
2395 	struct bpf_prog *prog;
2396 	int flags, err = 0;
2397 
2398 	prog = event->prog;
2399 	if (!prog)
2400 		return -ENOENT;
2401 
2402 	/* not supporting BPF_PROG_TYPE_PERF_EVENT yet */
2403 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT)
2404 		return -EOPNOTSUPP;
2405 
2406 	*prog_id = prog->aux->id;
2407 	flags = event->tp_event->flags;
2408 	is_tracepoint = flags & TRACE_EVENT_FL_TRACEPOINT;
2409 	is_syscall_tp = is_syscall_trace_event(event->tp_event);
2410 
2411 	if (is_tracepoint || is_syscall_tp) {
2412 		*buf = is_tracepoint ? event->tp_event->tp->name
2413 				     : event->tp_event->name;
2414 		/* We allow NULL pointer for tracepoint */
2415 		if (fd_type)
2416 			*fd_type = BPF_FD_TYPE_TRACEPOINT;
2417 		if (probe_offset)
2418 			*probe_offset = 0x0;
2419 		if (probe_addr)
2420 			*probe_addr = 0x0;
2421 	} else {
2422 		/* kprobe/uprobe */
2423 		err = -EOPNOTSUPP;
2424 #ifdef CONFIG_KPROBE_EVENTS
2425 		if (flags & TRACE_EVENT_FL_KPROBE)
2426 			err = bpf_get_kprobe_info(event, fd_type, buf,
2427 						  probe_offset, probe_addr,
2428 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2429 #endif
2430 #ifdef CONFIG_UPROBE_EVENTS
2431 		if (flags & TRACE_EVENT_FL_UPROBE)
2432 			err = bpf_get_uprobe_info(event, fd_type, buf,
2433 						  probe_offset, probe_addr,
2434 						  event->attr.type == PERF_TYPE_TRACEPOINT);
2435 #endif
2436 	}
2437 
2438 	return err;
2439 }
2440 
2441 static int __init send_signal_irq_work_init(void)
2442 {
2443 	int cpu;
2444 	struct send_signal_irq_work *work;
2445 
2446 	for_each_possible_cpu(cpu) {
2447 		work = per_cpu_ptr(&send_signal_work, cpu);
2448 		init_irq_work(&work->irq_work, do_bpf_send_signal);
2449 	}
2450 	return 0;
2451 }
2452 
2453 subsys_initcall(send_signal_irq_work_init);
2454 
2455 #ifdef CONFIG_MODULES
2456 static int bpf_event_notify(struct notifier_block *nb, unsigned long op,
2457 			    void *module)
2458 {
2459 	struct bpf_trace_module *btm, *tmp;
2460 	struct module *mod = module;
2461 	int ret = 0;
2462 
2463 	if (mod->num_bpf_raw_events == 0 ||
2464 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
2465 		goto out;
2466 
2467 	mutex_lock(&bpf_module_mutex);
2468 
2469 	switch (op) {
2470 	case MODULE_STATE_COMING:
2471 		btm = kzalloc(sizeof(*btm), GFP_KERNEL);
2472 		if (btm) {
2473 			btm->module = module;
2474 			list_add(&btm->list, &bpf_trace_modules);
2475 		} else {
2476 			ret = -ENOMEM;
2477 		}
2478 		break;
2479 	case MODULE_STATE_GOING:
2480 		list_for_each_entry_safe(btm, tmp, &bpf_trace_modules, list) {
2481 			if (btm->module == module) {
2482 				list_del(&btm->list);
2483 				kfree(btm);
2484 				break;
2485 			}
2486 		}
2487 		break;
2488 	}
2489 
2490 	mutex_unlock(&bpf_module_mutex);
2491 
2492 out:
2493 	return notifier_from_errno(ret);
2494 }
2495 
2496 static struct notifier_block bpf_module_nb = {
2497 	.notifier_call = bpf_event_notify,
2498 };
2499 
2500 static int __init bpf_event_init(void)
2501 {
2502 	register_module_notifier(&bpf_module_nb);
2503 	return 0;
2504 }
2505 
2506 fs_initcall(bpf_event_init);
2507 #endif /* CONFIG_MODULES */
2508 
2509 #ifdef CONFIG_FPROBE
2510 struct bpf_kprobe_multi_link {
2511 	struct bpf_link link;
2512 	struct fprobe fp;
2513 	unsigned long *addrs;
2514 	u64 *cookies;
2515 	u32 cnt;
2516 	u32 mods_cnt;
2517 	struct module **mods;
2518 	u32 flags;
2519 };
2520 
2521 struct bpf_kprobe_multi_run_ctx {
2522 	struct bpf_run_ctx run_ctx;
2523 	struct bpf_kprobe_multi_link *link;
2524 	unsigned long entry_ip;
2525 };
2526 
2527 struct user_syms {
2528 	const char **syms;
2529 	char *buf;
2530 };
2531 
2532 static int copy_user_syms(struct user_syms *us, unsigned long __user *usyms, u32 cnt)
2533 {
2534 	unsigned long __user usymbol;
2535 	const char **syms = NULL;
2536 	char *buf = NULL, *p;
2537 	int err = -ENOMEM;
2538 	unsigned int i;
2539 
2540 	syms = kvmalloc_array(cnt, sizeof(*syms), GFP_KERNEL);
2541 	if (!syms)
2542 		goto error;
2543 
2544 	buf = kvmalloc_array(cnt, KSYM_NAME_LEN, GFP_KERNEL);
2545 	if (!buf)
2546 		goto error;
2547 
2548 	for (p = buf, i = 0; i < cnt; i++) {
2549 		if (__get_user(usymbol, usyms + i)) {
2550 			err = -EFAULT;
2551 			goto error;
2552 		}
2553 		err = strncpy_from_user(p, (const char __user *) usymbol, KSYM_NAME_LEN);
2554 		if (err == KSYM_NAME_LEN)
2555 			err = -E2BIG;
2556 		if (err < 0)
2557 			goto error;
2558 		syms[i] = p;
2559 		p += err + 1;
2560 	}
2561 
2562 	us->syms = syms;
2563 	us->buf = buf;
2564 	return 0;
2565 
2566 error:
2567 	if (err) {
2568 		kvfree(syms);
2569 		kvfree(buf);
2570 	}
2571 	return err;
2572 }
2573 
2574 static void kprobe_multi_put_modules(struct module **mods, u32 cnt)
2575 {
2576 	u32 i;
2577 
2578 	for (i = 0; i < cnt; i++)
2579 		module_put(mods[i]);
2580 }
2581 
2582 static void free_user_syms(struct user_syms *us)
2583 {
2584 	kvfree(us->syms);
2585 	kvfree(us->buf);
2586 }
2587 
2588 static void bpf_kprobe_multi_link_release(struct bpf_link *link)
2589 {
2590 	struct bpf_kprobe_multi_link *kmulti_link;
2591 
2592 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2593 	unregister_fprobe(&kmulti_link->fp);
2594 	kprobe_multi_put_modules(kmulti_link->mods, kmulti_link->mods_cnt);
2595 }
2596 
2597 static void bpf_kprobe_multi_link_dealloc(struct bpf_link *link)
2598 {
2599 	struct bpf_kprobe_multi_link *kmulti_link;
2600 
2601 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2602 	kvfree(kmulti_link->addrs);
2603 	kvfree(kmulti_link->cookies);
2604 	kfree(kmulti_link->mods);
2605 	kfree(kmulti_link);
2606 }
2607 
2608 static int bpf_kprobe_multi_link_fill_link_info(const struct bpf_link *link,
2609 						struct bpf_link_info *info)
2610 {
2611 	u64 __user *uaddrs = u64_to_user_ptr(info->kprobe_multi.addrs);
2612 	struct bpf_kprobe_multi_link *kmulti_link;
2613 	u32 ucount = info->kprobe_multi.count;
2614 	int err = 0, i;
2615 
2616 	if (!uaddrs ^ !ucount)
2617 		return -EINVAL;
2618 
2619 	kmulti_link = container_of(link, struct bpf_kprobe_multi_link, link);
2620 	info->kprobe_multi.count = kmulti_link->cnt;
2621 	info->kprobe_multi.flags = kmulti_link->flags;
2622 
2623 	if (!uaddrs)
2624 		return 0;
2625 	if (ucount < kmulti_link->cnt)
2626 		err = -ENOSPC;
2627 	else
2628 		ucount = kmulti_link->cnt;
2629 
2630 	if (kallsyms_show_value(current_cred())) {
2631 		if (copy_to_user(uaddrs, kmulti_link->addrs, ucount * sizeof(u64)))
2632 			return -EFAULT;
2633 	} else {
2634 		for (i = 0; i < ucount; i++) {
2635 			if (put_user(0, uaddrs + i))
2636 				return -EFAULT;
2637 		}
2638 	}
2639 	return err;
2640 }
2641 
2642 static const struct bpf_link_ops bpf_kprobe_multi_link_lops = {
2643 	.release = bpf_kprobe_multi_link_release,
2644 	.dealloc_deferred = bpf_kprobe_multi_link_dealloc,
2645 	.fill_link_info = bpf_kprobe_multi_link_fill_link_info,
2646 };
2647 
2648 static void bpf_kprobe_multi_cookie_swap(void *a, void *b, int size, const void *priv)
2649 {
2650 	const struct bpf_kprobe_multi_link *link = priv;
2651 	unsigned long *addr_a = a, *addr_b = b;
2652 	u64 *cookie_a, *cookie_b;
2653 
2654 	cookie_a = link->cookies + (addr_a - link->addrs);
2655 	cookie_b = link->cookies + (addr_b - link->addrs);
2656 
2657 	/* swap addr_a/addr_b and cookie_a/cookie_b values */
2658 	swap(*addr_a, *addr_b);
2659 	swap(*cookie_a, *cookie_b);
2660 }
2661 
2662 static int bpf_kprobe_multi_addrs_cmp(const void *a, const void *b)
2663 {
2664 	const unsigned long *addr_a = a, *addr_b = b;
2665 
2666 	if (*addr_a == *addr_b)
2667 		return 0;
2668 	return *addr_a < *addr_b ? -1 : 1;
2669 }
2670 
2671 static int bpf_kprobe_multi_cookie_cmp(const void *a, const void *b, const void *priv)
2672 {
2673 	return bpf_kprobe_multi_addrs_cmp(a, b);
2674 }
2675 
2676 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx)
2677 {
2678 	struct bpf_kprobe_multi_run_ctx *run_ctx;
2679 	struct bpf_kprobe_multi_link *link;
2680 	u64 *cookie, entry_ip;
2681 	unsigned long *addr;
2682 
2683 	if (WARN_ON_ONCE(!ctx))
2684 		return 0;
2685 	run_ctx = container_of(current->bpf_ctx, struct bpf_kprobe_multi_run_ctx, run_ctx);
2686 	link = run_ctx->link;
2687 	if (!link->cookies)
2688 		return 0;
2689 	entry_ip = run_ctx->entry_ip;
2690 	addr = bsearch(&entry_ip, link->addrs, link->cnt, sizeof(entry_ip),
2691 		       bpf_kprobe_multi_addrs_cmp);
2692 	if (!addr)
2693 		return 0;
2694 	cookie = link->cookies + (addr - link->addrs);
2695 	return *cookie;
2696 }
2697 
2698 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
2699 {
2700 	struct bpf_kprobe_multi_run_ctx *run_ctx;
2701 
2702 	run_ctx = container_of(current->bpf_ctx, struct bpf_kprobe_multi_run_ctx, run_ctx);
2703 	return run_ctx->entry_ip;
2704 }
2705 
2706 static int
2707 kprobe_multi_link_prog_run(struct bpf_kprobe_multi_link *link,
2708 			   unsigned long entry_ip, struct pt_regs *regs)
2709 {
2710 	struct bpf_kprobe_multi_run_ctx run_ctx = {
2711 		.link = link,
2712 		.entry_ip = entry_ip,
2713 	};
2714 	struct bpf_run_ctx *old_run_ctx;
2715 	int err;
2716 
2717 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
2718 		err = 0;
2719 		goto out;
2720 	}
2721 
2722 	migrate_disable();
2723 	rcu_read_lock();
2724 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
2725 	err = bpf_prog_run(link->link.prog, regs);
2726 	bpf_reset_run_ctx(old_run_ctx);
2727 	rcu_read_unlock();
2728 	migrate_enable();
2729 
2730  out:
2731 	__this_cpu_dec(bpf_prog_active);
2732 	return err;
2733 }
2734 
2735 static int
2736 kprobe_multi_link_handler(struct fprobe *fp, unsigned long fentry_ip,
2737 			  unsigned long ret_ip, struct pt_regs *regs,
2738 			  void *data)
2739 {
2740 	struct bpf_kprobe_multi_link *link;
2741 
2742 	link = container_of(fp, struct bpf_kprobe_multi_link, fp);
2743 	kprobe_multi_link_prog_run(link, get_entry_ip(fentry_ip), regs);
2744 	return 0;
2745 }
2746 
2747 static void
2748 kprobe_multi_link_exit_handler(struct fprobe *fp, unsigned long fentry_ip,
2749 			       unsigned long ret_ip, struct pt_regs *regs,
2750 			       void *data)
2751 {
2752 	struct bpf_kprobe_multi_link *link;
2753 
2754 	link = container_of(fp, struct bpf_kprobe_multi_link, fp);
2755 	kprobe_multi_link_prog_run(link, get_entry_ip(fentry_ip), regs);
2756 }
2757 
2758 static int symbols_cmp_r(const void *a, const void *b, const void *priv)
2759 {
2760 	const char **str_a = (const char **) a;
2761 	const char **str_b = (const char **) b;
2762 
2763 	return strcmp(*str_a, *str_b);
2764 }
2765 
2766 struct multi_symbols_sort {
2767 	const char **funcs;
2768 	u64 *cookies;
2769 };
2770 
2771 static void symbols_swap_r(void *a, void *b, int size, const void *priv)
2772 {
2773 	const struct multi_symbols_sort *data = priv;
2774 	const char **name_a = a, **name_b = b;
2775 
2776 	swap(*name_a, *name_b);
2777 
2778 	/* If defined, swap also related cookies. */
2779 	if (data->cookies) {
2780 		u64 *cookie_a, *cookie_b;
2781 
2782 		cookie_a = data->cookies + (name_a - data->funcs);
2783 		cookie_b = data->cookies + (name_b - data->funcs);
2784 		swap(*cookie_a, *cookie_b);
2785 	}
2786 }
2787 
2788 struct modules_array {
2789 	struct module **mods;
2790 	int mods_cnt;
2791 	int mods_cap;
2792 };
2793 
2794 static int add_module(struct modules_array *arr, struct module *mod)
2795 {
2796 	struct module **mods;
2797 
2798 	if (arr->mods_cnt == arr->mods_cap) {
2799 		arr->mods_cap = max(16, arr->mods_cap * 3 / 2);
2800 		mods = krealloc_array(arr->mods, arr->mods_cap, sizeof(*mods), GFP_KERNEL);
2801 		if (!mods)
2802 			return -ENOMEM;
2803 		arr->mods = mods;
2804 	}
2805 
2806 	arr->mods[arr->mods_cnt] = mod;
2807 	arr->mods_cnt++;
2808 	return 0;
2809 }
2810 
2811 static bool has_module(struct modules_array *arr, struct module *mod)
2812 {
2813 	int i;
2814 
2815 	for (i = arr->mods_cnt - 1; i >= 0; i--) {
2816 		if (arr->mods[i] == mod)
2817 			return true;
2818 	}
2819 	return false;
2820 }
2821 
2822 static int get_modules_for_addrs(struct module ***mods, unsigned long *addrs, u32 addrs_cnt)
2823 {
2824 	struct modules_array arr = {};
2825 	u32 i, err = 0;
2826 
2827 	for (i = 0; i < addrs_cnt; i++) {
2828 		struct module *mod;
2829 
2830 		preempt_disable();
2831 		mod = __module_address(addrs[i]);
2832 		/* Either no module or we it's already stored  */
2833 		if (!mod || has_module(&arr, mod)) {
2834 			preempt_enable();
2835 			continue;
2836 		}
2837 		if (!try_module_get(mod))
2838 			err = -EINVAL;
2839 		preempt_enable();
2840 		if (err)
2841 			break;
2842 		err = add_module(&arr, mod);
2843 		if (err) {
2844 			module_put(mod);
2845 			break;
2846 		}
2847 	}
2848 
2849 	/* We return either err < 0 in case of error, ... */
2850 	if (err) {
2851 		kprobe_multi_put_modules(arr.mods, arr.mods_cnt);
2852 		kfree(arr.mods);
2853 		return err;
2854 	}
2855 
2856 	/* or number of modules found if everything is ok. */
2857 	*mods = arr.mods;
2858 	return arr.mods_cnt;
2859 }
2860 
2861 static int addrs_check_error_injection_list(unsigned long *addrs, u32 cnt)
2862 {
2863 	u32 i;
2864 
2865 	for (i = 0; i < cnt; i++) {
2866 		if (!within_error_injection_list(addrs[i]))
2867 			return -EINVAL;
2868 	}
2869 	return 0;
2870 }
2871 
2872 int bpf_kprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
2873 {
2874 	struct bpf_kprobe_multi_link *link = NULL;
2875 	struct bpf_link_primer link_primer;
2876 	void __user *ucookies;
2877 	unsigned long *addrs;
2878 	u32 flags, cnt, size;
2879 	void __user *uaddrs;
2880 	u64 *cookies = NULL;
2881 	void __user *usyms;
2882 	int err;
2883 
2884 	/* no support for 32bit archs yet */
2885 	if (sizeof(u64) != sizeof(void *))
2886 		return -EOPNOTSUPP;
2887 
2888 	if (prog->expected_attach_type != BPF_TRACE_KPROBE_MULTI)
2889 		return -EINVAL;
2890 
2891 	flags = attr->link_create.kprobe_multi.flags;
2892 	if (flags & ~BPF_F_KPROBE_MULTI_RETURN)
2893 		return -EINVAL;
2894 
2895 	uaddrs = u64_to_user_ptr(attr->link_create.kprobe_multi.addrs);
2896 	usyms = u64_to_user_ptr(attr->link_create.kprobe_multi.syms);
2897 	if (!!uaddrs == !!usyms)
2898 		return -EINVAL;
2899 
2900 	cnt = attr->link_create.kprobe_multi.cnt;
2901 	if (!cnt)
2902 		return -EINVAL;
2903 	if (cnt > MAX_KPROBE_MULTI_CNT)
2904 		return -E2BIG;
2905 
2906 	size = cnt * sizeof(*addrs);
2907 	addrs = kvmalloc_array(cnt, sizeof(*addrs), GFP_KERNEL);
2908 	if (!addrs)
2909 		return -ENOMEM;
2910 
2911 	ucookies = u64_to_user_ptr(attr->link_create.kprobe_multi.cookies);
2912 	if (ucookies) {
2913 		cookies = kvmalloc_array(cnt, sizeof(*addrs), GFP_KERNEL);
2914 		if (!cookies) {
2915 			err = -ENOMEM;
2916 			goto error;
2917 		}
2918 		if (copy_from_user(cookies, ucookies, size)) {
2919 			err = -EFAULT;
2920 			goto error;
2921 		}
2922 	}
2923 
2924 	if (uaddrs) {
2925 		if (copy_from_user(addrs, uaddrs, size)) {
2926 			err = -EFAULT;
2927 			goto error;
2928 		}
2929 	} else {
2930 		struct multi_symbols_sort data = {
2931 			.cookies = cookies,
2932 		};
2933 		struct user_syms us;
2934 
2935 		err = copy_user_syms(&us, usyms, cnt);
2936 		if (err)
2937 			goto error;
2938 
2939 		if (cookies)
2940 			data.funcs = us.syms;
2941 
2942 		sort_r(us.syms, cnt, sizeof(*us.syms), symbols_cmp_r,
2943 		       symbols_swap_r, &data);
2944 
2945 		err = ftrace_lookup_symbols(us.syms, cnt, addrs);
2946 		free_user_syms(&us);
2947 		if (err)
2948 			goto error;
2949 	}
2950 
2951 	if (prog->kprobe_override && addrs_check_error_injection_list(addrs, cnt)) {
2952 		err = -EINVAL;
2953 		goto error;
2954 	}
2955 
2956 	link = kzalloc(sizeof(*link), GFP_KERNEL);
2957 	if (!link) {
2958 		err = -ENOMEM;
2959 		goto error;
2960 	}
2961 
2962 	bpf_link_init(&link->link, BPF_LINK_TYPE_KPROBE_MULTI,
2963 		      &bpf_kprobe_multi_link_lops, prog);
2964 
2965 	err = bpf_link_prime(&link->link, &link_primer);
2966 	if (err)
2967 		goto error;
2968 
2969 	if (flags & BPF_F_KPROBE_MULTI_RETURN)
2970 		link->fp.exit_handler = kprobe_multi_link_exit_handler;
2971 	else
2972 		link->fp.entry_handler = kprobe_multi_link_handler;
2973 
2974 	link->addrs = addrs;
2975 	link->cookies = cookies;
2976 	link->cnt = cnt;
2977 	link->flags = flags;
2978 
2979 	if (cookies) {
2980 		/*
2981 		 * Sorting addresses will trigger sorting cookies as well
2982 		 * (check bpf_kprobe_multi_cookie_swap). This way we can
2983 		 * find cookie based on the address in bpf_get_attach_cookie
2984 		 * helper.
2985 		 */
2986 		sort_r(addrs, cnt, sizeof(*addrs),
2987 		       bpf_kprobe_multi_cookie_cmp,
2988 		       bpf_kprobe_multi_cookie_swap,
2989 		       link);
2990 	}
2991 
2992 	err = get_modules_for_addrs(&link->mods, addrs, cnt);
2993 	if (err < 0) {
2994 		bpf_link_cleanup(&link_primer);
2995 		return err;
2996 	}
2997 	link->mods_cnt = err;
2998 
2999 	err = register_fprobe_ips(&link->fp, addrs, cnt);
3000 	if (err) {
3001 		kprobe_multi_put_modules(link->mods, link->mods_cnt);
3002 		bpf_link_cleanup(&link_primer);
3003 		return err;
3004 	}
3005 
3006 	return bpf_link_settle(&link_primer);
3007 
3008 error:
3009 	kfree(link);
3010 	kvfree(addrs);
3011 	kvfree(cookies);
3012 	return err;
3013 }
3014 #else /* !CONFIG_FPROBE */
3015 int bpf_kprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3016 {
3017 	return -EOPNOTSUPP;
3018 }
3019 static u64 bpf_kprobe_multi_cookie(struct bpf_run_ctx *ctx)
3020 {
3021 	return 0;
3022 }
3023 static u64 bpf_kprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
3024 {
3025 	return 0;
3026 }
3027 #endif
3028 
3029 #ifdef CONFIG_UPROBES
3030 struct bpf_uprobe_multi_link;
3031 
3032 struct bpf_uprobe {
3033 	struct bpf_uprobe_multi_link *link;
3034 	loff_t offset;
3035 	unsigned long ref_ctr_offset;
3036 	u64 cookie;
3037 	struct uprobe_consumer consumer;
3038 };
3039 
3040 struct bpf_uprobe_multi_link {
3041 	struct path path;
3042 	struct bpf_link link;
3043 	u32 cnt;
3044 	struct bpf_uprobe *uprobes;
3045 	struct task_struct *task;
3046 };
3047 
3048 struct bpf_uprobe_multi_run_ctx {
3049 	struct bpf_run_ctx run_ctx;
3050 	unsigned long entry_ip;
3051 	struct bpf_uprobe *uprobe;
3052 };
3053 
3054 static void bpf_uprobe_unregister(struct path *path, struct bpf_uprobe *uprobes,
3055 				  u32 cnt)
3056 {
3057 	u32 i;
3058 
3059 	for (i = 0; i < cnt; i++) {
3060 		uprobe_unregister(d_real_inode(path->dentry), uprobes[i].offset,
3061 				  &uprobes[i].consumer);
3062 	}
3063 }
3064 
3065 static void bpf_uprobe_multi_link_release(struct bpf_link *link)
3066 {
3067 	struct bpf_uprobe_multi_link *umulti_link;
3068 
3069 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3070 	bpf_uprobe_unregister(&umulti_link->path, umulti_link->uprobes, umulti_link->cnt);
3071 	if (umulti_link->task)
3072 		put_task_struct(umulti_link->task);
3073 	path_put(&umulti_link->path);
3074 }
3075 
3076 static void bpf_uprobe_multi_link_dealloc(struct bpf_link *link)
3077 {
3078 	struct bpf_uprobe_multi_link *umulti_link;
3079 
3080 	umulti_link = container_of(link, struct bpf_uprobe_multi_link, link);
3081 	kvfree(umulti_link->uprobes);
3082 	kfree(umulti_link);
3083 }
3084 
3085 static const struct bpf_link_ops bpf_uprobe_multi_link_lops = {
3086 	.release = bpf_uprobe_multi_link_release,
3087 	.dealloc_deferred = bpf_uprobe_multi_link_dealloc,
3088 };
3089 
3090 static int uprobe_prog_run(struct bpf_uprobe *uprobe,
3091 			   unsigned long entry_ip,
3092 			   struct pt_regs *regs)
3093 {
3094 	struct bpf_uprobe_multi_link *link = uprobe->link;
3095 	struct bpf_uprobe_multi_run_ctx run_ctx = {
3096 		.entry_ip = entry_ip,
3097 		.uprobe = uprobe,
3098 	};
3099 	struct bpf_prog *prog = link->link.prog;
3100 	bool sleepable = prog->aux->sleepable;
3101 	struct bpf_run_ctx *old_run_ctx;
3102 	int err = 0;
3103 
3104 	if (link->task && current->mm != link->task->mm)
3105 		return 0;
3106 
3107 	if (sleepable)
3108 		rcu_read_lock_trace();
3109 	else
3110 		rcu_read_lock();
3111 
3112 	migrate_disable();
3113 
3114 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
3115 	err = bpf_prog_run(link->link.prog, regs);
3116 	bpf_reset_run_ctx(old_run_ctx);
3117 
3118 	migrate_enable();
3119 
3120 	if (sleepable)
3121 		rcu_read_unlock_trace();
3122 	else
3123 		rcu_read_unlock();
3124 	return err;
3125 }
3126 
3127 static bool
3128 uprobe_multi_link_filter(struct uprobe_consumer *con, enum uprobe_filter_ctx ctx,
3129 			 struct mm_struct *mm)
3130 {
3131 	struct bpf_uprobe *uprobe;
3132 
3133 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3134 	return uprobe->link->task->mm == mm;
3135 }
3136 
3137 static int
3138 uprobe_multi_link_handler(struct uprobe_consumer *con, struct pt_regs *regs)
3139 {
3140 	struct bpf_uprobe *uprobe;
3141 
3142 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3143 	return uprobe_prog_run(uprobe, instruction_pointer(regs), regs);
3144 }
3145 
3146 static int
3147 uprobe_multi_link_ret_handler(struct uprobe_consumer *con, unsigned long func, struct pt_regs *regs)
3148 {
3149 	struct bpf_uprobe *uprobe;
3150 
3151 	uprobe = container_of(con, struct bpf_uprobe, consumer);
3152 	return uprobe_prog_run(uprobe, func, regs);
3153 }
3154 
3155 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
3156 {
3157 	struct bpf_uprobe_multi_run_ctx *run_ctx;
3158 
3159 	run_ctx = container_of(current->bpf_ctx, struct bpf_uprobe_multi_run_ctx, run_ctx);
3160 	return run_ctx->entry_ip;
3161 }
3162 
3163 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx)
3164 {
3165 	struct bpf_uprobe_multi_run_ctx *run_ctx;
3166 
3167 	run_ctx = container_of(current->bpf_ctx, struct bpf_uprobe_multi_run_ctx, run_ctx);
3168 	return run_ctx->uprobe->cookie;
3169 }
3170 
3171 int bpf_uprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3172 {
3173 	struct bpf_uprobe_multi_link *link = NULL;
3174 	unsigned long __user *uref_ctr_offsets;
3175 	struct bpf_link_primer link_primer;
3176 	struct bpf_uprobe *uprobes = NULL;
3177 	struct task_struct *task = NULL;
3178 	unsigned long __user *uoffsets;
3179 	u64 __user *ucookies;
3180 	void __user *upath;
3181 	u32 flags, cnt, i;
3182 	struct path path;
3183 	char *name;
3184 	pid_t pid;
3185 	int err;
3186 
3187 	/* no support for 32bit archs yet */
3188 	if (sizeof(u64) != sizeof(void *))
3189 		return -EOPNOTSUPP;
3190 
3191 	if (prog->expected_attach_type != BPF_TRACE_UPROBE_MULTI)
3192 		return -EINVAL;
3193 
3194 	flags = attr->link_create.uprobe_multi.flags;
3195 	if (flags & ~BPF_F_UPROBE_MULTI_RETURN)
3196 		return -EINVAL;
3197 
3198 	/*
3199 	 * path, offsets and cnt are mandatory,
3200 	 * ref_ctr_offsets and cookies are optional
3201 	 */
3202 	upath = u64_to_user_ptr(attr->link_create.uprobe_multi.path);
3203 	uoffsets = u64_to_user_ptr(attr->link_create.uprobe_multi.offsets);
3204 	cnt = attr->link_create.uprobe_multi.cnt;
3205 	pid = attr->link_create.uprobe_multi.pid;
3206 
3207 	if (!upath || !uoffsets || !cnt || pid < 0)
3208 		return -EINVAL;
3209 	if (cnt > MAX_UPROBE_MULTI_CNT)
3210 		return -E2BIG;
3211 
3212 	uref_ctr_offsets = u64_to_user_ptr(attr->link_create.uprobe_multi.ref_ctr_offsets);
3213 	ucookies = u64_to_user_ptr(attr->link_create.uprobe_multi.cookies);
3214 
3215 	name = strndup_user(upath, PATH_MAX);
3216 	if (IS_ERR(name)) {
3217 		err = PTR_ERR(name);
3218 		return err;
3219 	}
3220 
3221 	err = kern_path(name, LOOKUP_FOLLOW, &path);
3222 	kfree(name);
3223 	if (err)
3224 		return err;
3225 
3226 	if (!d_is_reg(path.dentry)) {
3227 		err = -EBADF;
3228 		goto error_path_put;
3229 	}
3230 
3231 	if (pid) {
3232 		rcu_read_lock();
3233 		task = get_pid_task(find_vpid(pid), PIDTYPE_TGID);
3234 		rcu_read_unlock();
3235 		if (!task) {
3236 			err = -ESRCH;
3237 			goto error_path_put;
3238 		}
3239 	}
3240 
3241 	err = -ENOMEM;
3242 
3243 	link = kzalloc(sizeof(*link), GFP_KERNEL);
3244 	uprobes = kvcalloc(cnt, sizeof(*uprobes), GFP_KERNEL);
3245 
3246 	if (!uprobes || !link)
3247 		goto error_free;
3248 
3249 	for (i = 0; i < cnt; i++) {
3250 		if (ucookies && __get_user(uprobes[i].cookie, ucookies + i)) {
3251 			err = -EFAULT;
3252 			goto error_free;
3253 		}
3254 		if (uref_ctr_offsets && __get_user(uprobes[i].ref_ctr_offset, uref_ctr_offsets + i)) {
3255 			err = -EFAULT;
3256 			goto error_free;
3257 		}
3258 		if (__get_user(uprobes[i].offset, uoffsets + i)) {
3259 			err = -EFAULT;
3260 			goto error_free;
3261 		}
3262 
3263 		uprobes[i].link = link;
3264 
3265 		if (flags & BPF_F_UPROBE_MULTI_RETURN)
3266 			uprobes[i].consumer.ret_handler = uprobe_multi_link_ret_handler;
3267 		else
3268 			uprobes[i].consumer.handler = uprobe_multi_link_handler;
3269 
3270 		if (pid)
3271 			uprobes[i].consumer.filter = uprobe_multi_link_filter;
3272 	}
3273 
3274 	link->cnt = cnt;
3275 	link->uprobes = uprobes;
3276 	link->path = path;
3277 	link->task = task;
3278 
3279 	bpf_link_init(&link->link, BPF_LINK_TYPE_UPROBE_MULTI,
3280 		      &bpf_uprobe_multi_link_lops, prog);
3281 
3282 	for (i = 0; i < cnt; i++) {
3283 		err = uprobe_register_refctr(d_real_inode(link->path.dentry),
3284 					     uprobes[i].offset,
3285 					     uprobes[i].ref_ctr_offset,
3286 					     &uprobes[i].consumer);
3287 		if (err) {
3288 			bpf_uprobe_unregister(&path, uprobes, i);
3289 			goto error_free;
3290 		}
3291 	}
3292 
3293 	err = bpf_link_prime(&link->link, &link_primer);
3294 	if (err)
3295 		goto error_free;
3296 
3297 	return bpf_link_settle(&link_primer);
3298 
3299 error_free:
3300 	kvfree(uprobes);
3301 	kfree(link);
3302 	if (task)
3303 		put_task_struct(task);
3304 error_path_put:
3305 	path_put(&path);
3306 	return err;
3307 }
3308 #else /* !CONFIG_UPROBES */
3309 int bpf_uprobe_multi_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3310 {
3311 	return -EOPNOTSUPP;
3312 }
3313 static u64 bpf_uprobe_multi_cookie(struct bpf_run_ctx *ctx)
3314 {
3315 	return 0;
3316 }
3317 static u64 bpf_uprobe_multi_entry_ip(struct bpf_run_ctx *ctx)
3318 {
3319 	return 0;
3320 }
3321 #endif /* CONFIG_UPROBES */
3322