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