xref: /openbmc/linux/kernel/trace/bpf_trace.c (revision 78beef62)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2011-2015 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  */
5 #include <linux/kernel.h>
6 #include <linux/types.h>
7 #include <linux/slab.h>
8 #include <linux/bpf.h>
9 #include <linux/bpf_perf_event.h>
10 #include <linux/filter.h>
11 #include <linux/uaccess.h>
12 #include <linux/ctype.h>
13 #include <linux/kprobes.h>
14 #include <linux/syscalls.h>
15 #include <linux/error-injection.h>
16 
17 #include <asm/tlb.h>
18 
19 #include "trace_probe.h"
20 #include "trace.h"
21 
22 #define bpf_event_rcu_dereference(p)					\
23 	rcu_dereference_protected(p, lockdep_is_held(&bpf_event_mutex))
24 
25 #ifdef CONFIG_MODULES
26 struct bpf_trace_module {
27 	struct module *module;
28 	struct list_head list;
29 };
30 
31 static LIST_HEAD(bpf_trace_modules);
32 static DEFINE_MUTEX(bpf_module_mutex);
33 
34 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
35 {
36 	struct bpf_raw_event_map *btp, *ret = NULL;
37 	struct bpf_trace_module *btm;
38 	unsigned int i;
39 
40 	mutex_lock(&bpf_module_mutex);
41 	list_for_each_entry(btm, &bpf_trace_modules, list) {
42 		for (i = 0; i < btm->module->num_bpf_raw_events; ++i) {
43 			btp = &btm->module->bpf_raw_events[i];
44 			if (!strcmp(btp->tp->name, name)) {
45 				if (try_module_get(btm->module))
46 					ret = btp;
47 				goto out;
48 			}
49 		}
50 	}
51 out:
52 	mutex_unlock(&bpf_module_mutex);
53 	return ret;
54 }
55 #else
56 static struct bpf_raw_event_map *bpf_get_raw_tracepoint_module(const char *name)
57 {
58 	return NULL;
59 }
60 #endif /* CONFIG_MODULES */
61 
62 u64 bpf_get_stackid(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
63 u64 bpf_get_stack(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
64 
65 /**
66  * trace_call_bpf - invoke BPF program
67  * @call: tracepoint event
68  * @ctx: opaque context pointer
69  *
70  * kprobe handlers execute BPF programs via this helper.
71  * Can be used from static tracepoints in the future.
72  *
73  * Return: BPF programs always return an integer which is interpreted by
74  * kprobe handler as:
75  * 0 - return from kprobe (event is filtered out)
76  * 1 - store kprobe event into ring buffer
77  * Other values are reserved and currently alias to 1
78  */
79 unsigned int trace_call_bpf(struct trace_event_call *call, void *ctx)
80 {
81 	unsigned int ret;
82 
83 	if (in_nmi()) /* not supported yet */
84 		return 1;
85 
86 	preempt_disable();
87 
88 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
89 		/*
90 		 * since some bpf program is already running on this cpu,
91 		 * don't call into another bpf program (same or different)
92 		 * and don't send kprobe event into ring-buffer,
93 		 * so return zero here
94 		 */
95 		ret = 0;
96 		goto out;
97 	}
98 
99 	/*
100 	 * Instead of moving rcu_read_lock/rcu_dereference/rcu_read_unlock
101 	 * to all call sites, we did a bpf_prog_array_valid() there to check
102 	 * whether call->prog_array is empty or not, which is
103 	 * a heurisitc to speed up execution.
104 	 *
105 	 * If bpf_prog_array_valid() fetched prog_array was
106 	 * non-NULL, we go into trace_call_bpf() and do the actual
107 	 * proper rcu_dereference() under RCU lock.
108 	 * If it turns out that prog_array is NULL then, we bail out.
109 	 * For the opposite, if the bpf_prog_array_valid() fetched pointer
110 	 * was NULL, you'll skip the prog_array with the risk of missing
111 	 * out of events when it was updated in between this and the
112 	 * rcu_dereference() which is accepted risk.
113 	 */
114 	ret = BPF_PROG_RUN_ARRAY_CHECK(call->prog_array, ctx, BPF_PROG_RUN);
115 
116  out:
117 	__this_cpu_dec(bpf_prog_active);
118 	preempt_enable();
119 
120 	return ret;
121 }
122 EXPORT_SYMBOL_GPL(trace_call_bpf);
123 
124 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
125 BPF_CALL_2(bpf_override_return, struct pt_regs *, regs, unsigned long, rc)
126 {
127 	regs_set_return_value(regs, rc);
128 	override_function_with_return(regs);
129 	return 0;
130 }
131 
132 static const struct bpf_func_proto bpf_override_return_proto = {
133 	.func		= bpf_override_return,
134 	.gpl_only	= true,
135 	.ret_type	= RET_INTEGER,
136 	.arg1_type	= ARG_PTR_TO_CTX,
137 	.arg2_type	= ARG_ANYTHING,
138 };
139 #endif
140 
141 BPF_CALL_3(bpf_probe_read, void *, dst, u32, size, const void *, unsafe_ptr)
142 {
143 	int ret;
144 
145 	ret = probe_kernel_read(dst, unsafe_ptr, size);
146 	if (unlikely(ret < 0))
147 		memset(dst, 0, size);
148 
149 	return ret;
150 }
151 
152 static const struct bpf_func_proto bpf_probe_read_proto = {
153 	.func		= bpf_probe_read,
154 	.gpl_only	= true,
155 	.ret_type	= RET_INTEGER,
156 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
157 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
158 	.arg3_type	= ARG_ANYTHING,
159 };
160 
161 BPF_CALL_3(bpf_probe_write_user, void *, unsafe_ptr, const void *, src,
162 	   u32, size)
163 {
164 	/*
165 	 * Ensure we're in user context which is safe for the helper to
166 	 * run. This helper has no business in a kthread.
167 	 *
168 	 * access_ok() should prevent writing to non-user memory, but in
169 	 * some situations (nommu, temporary switch, etc) access_ok() does
170 	 * not provide enough validation, hence the check on KERNEL_DS.
171 	 *
172 	 * nmi_uaccess_okay() ensures the probe is not run in an interim
173 	 * state, when the task or mm are switched. This is specifically
174 	 * required to prevent the use of temporary mm.
175 	 */
176 
177 	if (unlikely(in_interrupt() ||
178 		     current->flags & (PF_KTHREAD | PF_EXITING)))
179 		return -EPERM;
180 	if (unlikely(uaccess_kernel()))
181 		return -EPERM;
182 	if (unlikely(!nmi_uaccess_okay()))
183 		return -EPERM;
184 	if (!access_ok(unsafe_ptr, size))
185 		return -EPERM;
186 
187 	return probe_kernel_write(unsafe_ptr, src, size);
188 }
189 
190 static const struct bpf_func_proto bpf_probe_write_user_proto = {
191 	.func		= bpf_probe_write_user,
192 	.gpl_only	= true,
193 	.ret_type	= RET_INTEGER,
194 	.arg1_type	= ARG_ANYTHING,
195 	.arg2_type	= ARG_PTR_TO_MEM,
196 	.arg3_type	= ARG_CONST_SIZE,
197 };
198 
199 static const struct bpf_func_proto *bpf_get_probe_write_proto(void)
200 {
201 	pr_warn_ratelimited("%s[%d] is installing a program with bpf_probe_write_user helper that may corrupt user memory!",
202 			    current->comm, task_pid_nr(current));
203 
204 	return &bpf_probe_write_user_proto;
205 }
206 
207 /*
208  * Only limited trace_printk() conversion specifiers allowed:
209  * %d %i %u %x %ld %li %lu %lx %lld %lli %llu %llx %p %s
210  */
211 BPF_CALL_5(bpf_trace_printk, char *, fmt, u32, fmt_size, u64, arg1,
212 	   u64, arg2, u64, arg3)
213 {
214 	bool str_seen = false;
215 	int mod[3] = {};
216 	int fmt_cnt = 0;
217 	u64 unsafe_addr;
218 	char buf[64];
219 	int i;
220 
221 	/*
222 	 * bpf_check()->check_func_arg()->check_stack_boundary()
223 	 * guarantees that fmt points to bpf program stack,
224 	 * fmt_size bytes of it were initialized and fmt_size > 0
225 	 */
226 	if (fmt[--fmt_size] != 0)
227 		return -EINVAL;
228 
229 	/* check format string for allowed specifiers */
230 	for (i = 0; i < fmt_size; i++) {
231 		if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i]))
232 			return -EINVAL;
233 
234 		if (fmt[i] != '%')
235 			continue;
236 
237 		if (fmt_cnt >= 3)
238 			return -EINVAL;
239 
240 		/* fmt[i] != 0 && fmt[last] == 0, so we can access fmt[i + 1] */
241 		i++;
242 		if (fmt[i] == 'l') {
243 			mod[fmt_cnt]++;
244 			i++;
245 		} else if (fmt[i] == 'p' || fmt[i] == 's') {
246 			mod[fmt_cnt]++;
247 			/* disallow any further format extensions */
248 			if (fmt[i + 1] != 0 &&
249 			    !isspace(fmt[i + 1]) &&
250 			    !ispunct(fmt[i + 1]))
251 				return -EINVAL;
252 			fmt_cnt++;
253 			if (fmt[i] == 's') {
254 				if (str_seen)
255 					/* allow only one '%s' per fmt string */
256 					return -EINVAL;
257 				str_seen = true;
258 
259 				switch (fmt_cnt) {
260 				case 1:
261 					unsafe_addr = arg1;
262 					arg1 = (long) buf;
263 					break;
264 				case 2:
265 					unsafe_addr = arg2;
266 					arg2 = (long) buf;
267 					break;
268 				case 3:
269 					unsafe_addr = arg3;
270 					arg3 = (long) buf;
271 					break;
272 				}
273 				buf[0] = 0;
274 				strncpy_from_unsafe(buf,
275 						    (void *) (long) unsafe_addr,
276 						    sizeof(buf));
277 			}
278 			continue;
279 		}
280 
281 		if (fmt[i] == 'l') {
282 			mod[fmt_cnt]++;
283 			i++;
284 		}
285 
286 		if (fmt[i] != 'i' && fmt[i] != 'd' &&
287 		    fmt[i] != 'u' && fmt[i] != 'x')
288 			return -EINVAL;
289 		fmt_cnt++;
290 	}
291 
292 /* Horrid workaround for getting va_list handling working with different
293  * argument type combinations generically for 32 and 64 bit archs.
294  */
295 #define __BPF_TP_EMIT()	__BPF_ARG3_TP()
296 #define __BPF_TP(...)							\
297 	__trace_printk(0 /* Fake ip */,					\
298 		       fmt, ##__VA_ARGS__)
299 
300 #define __BPF_ARG1_TP(...)						\
301 	((mod[0] == 2 || (mod[0] == 1 && __BITS_PER_LONG == 64))	\
302 	  ? __BPF_TP(arg1, ##__VA_ARGS__)				\
303 	  : ((mod[0] == 1 || (mod[0] == 0 && __BITS_PER_LONG == 32))	\
304 	      ? __BPF_TP((long)arg1, ##__VA_ARGS__)			\
305 	      : __BPF_TP((u32)arg1, ##__VA_ARGS__)))
306 
307 #define __BPF_ARG2_TP(...)						\
308 	((mod[1] == 2 || (mod[1] == 1 && __BITS_PER_LONG == 64))	\
309 	  ? __BPF_ARG1_TP(arg2, ##__VA_ARGS__)				\
310 	  : ((mod[1] == 1 || (mod[1] == 0 && __BITS_PER_LONG == 32))	\
311 	      ? __BPF_ARG1_TP((long)arg2, ##__VA_ARGS__)		\
312 	      : __BPF_ARG1_TP((u32)arg2, ##__VA_ARGS__)))
313 
314 #define __BPF_ARG3_TP(...)						\
315 	((mod[2] == 2 || (mod[2] == 1 && __BITS_PER_LONG == 64))	\
316 	  ? __BPF_ARG2_TP(arg3, ##__VA_ARGS__)				\
317 	  : ((mod[2] == 1 || (mod[2] == 0 && __BITS_PER_LONG == 32))	\
318 	      ? __BPF_ARG2_TP((long)arg3, ##__VA_ARGS__)		\
319 	      : __BPF_ARG2_TP((u32)arg3, ##__VA_ARGS__)))
320 
321 	return __BPF_TP_EMIT();
322 }
323 
324 static const struct bpf_func_proto bpf_trace_printk_proto = {
325 	.func		= bpf_trace_printk,
326 	.gpl_only	= true,
327 	.ret_type	= RET_INTEGER,
328 	.arg1_type	= ARG_PTR_TO_MEM,
329 	.arg2_type	= ARG_CONST_SIZE,
330 };
331 
332 const struct bpf_func_proto *bpf_get_trace_printk_proto(void)
333 {
334 	/*
335 	 * this program might be calling bpf_trace_printk,
336 	 * so allocate per-cpu printk buffers
337 	 */
338 	trace_printk_init_buffers();
339 
340 	return &bpf_trace_printk_proto;
341 }
342 
343 static __always_inline int
344 get_map_perf_counter(struct bpf_map *map, u64 flags,
345 		     u64 *value, u64 *enabled, u64 *running)
346 {
347 	struct bpf_array *array = container_of(map, struct bpf_array, map);
348 	unsigned int cpu = smp_processor_id();
349 	u64 index = flags & BPF_F_INDEX_MASK;
350 	struct bpf_event_entry *ee;
351 
352 	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
353 		return -EINVAL;
354 	if (index == BPF_F_CURRENT_CPU)
355 		index = cpu;
356 	if (unlikely(index >= array->map.max_entries))
357 		return -E2BIG;
358 
359 	ee = READ_ONCE(array->ptrs[index]);
360 	if (!ee)
361 		return -ENOENT;
362 
363 	return perf_event_read_local(ee->event, value, enabled, running);
364 }
365 
366 BPF_CALL_2(bpf_perf_event_read, struct bpf_map *, map, u64, flags)
367 {
368 	u64 value = 0;
369 	int err;
370 
371 	err = get_map_perf_counter(map, flags, &value, NULL, NULL);
372 	/*
373 	 * this api is ugly since we miss [-22..-2] range of valid
374 	 * counter values, but that's uapi
375 	 */
376 	if (err)
377 		return err;
378 	return value;
379 }
380 
381 static const struct bpf_func_proto bpf_perf_event_read_proto = {
382 	.func		= bpf_perf_event_read,
383 	.gpl_only	= true,
384 	.ret_type	= RET_INTEGER,
385 	.arg1_type	= ARG_CONST_MAP_PTR,
386 	.arg2_type	= ARG_ANYTHING,
387 };
388 
389 BPF_CALL_4(bpf_perf_event_read_value, struct bpf_map *, map, u64, flags,
390 	   struct bpf_perf_event_value *, buf, u32, size)
391 {
392 	int err = -EINVAL;
393 
394 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
395 		goto clear;
396 	err = get_map_perf_counter(map, flags, &buf->counter, &buf->enabled,
397 				   &buf->running);
398 	if (unlikely(err))
399 		goto clear;
400 	return 0;
401 clear:
402 	memset(buf, 0, size);
403 	return err;
404 }
405 
406 static const struct bpf_func_proto bpf_perf_event_read_value_proto = {
407 	.func		= bpf_perf_event_read_value,
408 	.gpl_only	= true,
409 	.ret_type	= RET_INTEGER,
410 	.arg1_type	= ARG_CONST_MAP_PTR,
411 	.arg2_type	= ARG_ANYTHING,
412 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
413 	.arg4_type	= ARG_CONST_SIZE,
414 };
415 
416 static __always_inline u64
417 __bpf_perf_event_output(struct pt_regs *regs, struct bpf_map *map,
418 			u64 flags, struct perf_sample_data *sd)
419 {
420 	struct bpf_array *array = container_of(map, struct bpf_array, map);
421 	unsigned int cpu = smp_processor_id();
422 	u64 index = flags & BPF_F_INDEX_MASK;
423 	struct bpf_event_entry *ee;
424 	struct perf_event *event;
425 
426 	if (index == BPF_F_CURRENT_CPU)
427 		index = cpu;
428 	if (unlikely(index >= array->map.max_entries))
429 		return -E2BIG;
430 
431 	ee = READ_ONCE(array->ptrs[index]);
432 	if (!ee)
433 		return -ENOENT;
434 
435 	event = ee->event;
436 	if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
437 		     event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
438 		return -EINVAL;
439 
440 	if (unlikely(event->oncpu != cpu))
441 		return -EOPNOTSUPP;
442 
443 	return perf_event_output(event, sd, regs);
444 }
445 
446 /*
447  * Support executing tracepoints in normal, irq, and nmi context that each call
448  * bpf_perf_event_output
449  */
450 struct bpf_trace_sample_data {
451 	struct perf_sample_data sds[3];
452 };
453 
454 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_trace_sds);
455 static DEFINE_PER_CPU(int, bpf_trace_nest_level);
456 BPF_CALL_5(bpf_perf_event_output, struct pt_regs *, regs, struct bpf_map *, map,
457 	   u64, flags, void *, data, u64, size)
458 {
459 	struct bpf_trace_sample_data *sds = this_cpu_ptr(&bpf_trace_sds);
460 	int nest_level = this_cpu_inc_return(bpf_trace_nest_level);
461 	struct perf_raw_record raw = {
462 		.frag = {
463 			.size = size,
464 			.data = data,
465 		},
466 	};
467 	struct perf_sample_data *sd;
468 	int err;
469 
470 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(sds->sds))) {
471 		err = -EBUSY;
472 		goto out;
473 	}
474 
475 	sd = &sds->sds[nest_level - 1];
476 
477 	if (unlikely(flags & ~(BPF_F_INDEX_MASK))) {
478 		err = -EINVAL;
479 		goto out;
480 	}
481 
482 	perf_sample_data_init(sd, 0, 0);
483 	sd->raw = &raw;
484 
485 	err = __bpf_perf_event_output(regs, map, flags, sd);
486 
487 out:
488 	this_cpu_dec(bpf_trace_nest_level);
489 	return err;
490 }
491 
492 static const struct bpf_func_proto bpf_perf_event_output_proto = {
493 	.func		= bpf_perf_event_output,
494 	.gpl_only	= true,
495 	.ret_type	= RET_INTEGER,
496 	.arg1_type	= ARG_PTR_TO_CTX,
497 	.arg2_type	= ARG_CONST_MAP_PTR,
498 	.arg3_type	= ARG_ANYTHING,
499 	.arg4_type	= ARG_PTR_TO_MEM,
500 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
501 };
502 
503 static DEFINE_PER_CPU(int, bpf_event_output_nest_level);
504 struct bpf_nested_pt_regs {
505 	struct pt_regs regs[3];
506 };
507 static DEFINE_PER_CPU(struct bpf_nested_pt_regs, bpf_pt_regs);
508 static DEFINE_PER_CPU(struct bpf_trace_sample_data, bpf_misc_sds);
509 
510 u64 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
511 		     void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
512 {
513 	int nest_level = this_cpu_inc_return(bpf_event_output_nest_level);
514 	struct perf_raw_frag frag = {
515 		.copy		= ctx_copy,
516 		.size		= ctx_size,
517 		.data		= ctx,
518 	};
519 	struct perf_raw_record raw = {
520 		.frag = {
521 			{
522 				.next	= ctx_size ? &frag : NULL,
523 			},
524 			.size	= meta_size,
525 			.data	= meta,
526 		},
527 	};
528 	struct perf_sample_data *sd;
529 	struct pt_regs *regs;
530 	u64 ret;
531 
532 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(bpf_misc_sds.sds))) {
533 		ret = -EBUSY;
534 		goto out;
535 	}
536 	sd = this_cpu_ptr(&bpf_misc_sds.sds[nest_level - 1]);
537 	regs = this_cpu_ptr(&bpf_pt_regs.regs[nest_level - 1]);
538 
539 	perf_fetch_caller_regs(regs);
540 	perf_sample_data_init(sd, 0, 0);
541 	sd->raw = &raw;
542 
543 	ret = __bpf_perf_event_output(regs, map, flags, sd);
544 out:
545 	this_cpu_dec(bpf_event_output_nest_level);
546 	return ret;
547 }
548 
549 BPF_CALL_0(bpf_get_current_task)
550 {
551 	return (long) current;
552 }
553 
554 static const struct bpf_func_proto bpf_get_current_task_proto = {
555 	.func		= bpf_get_current_task,
556 	.gpl_only	= true,
557 	.ret_type	= RET_INTEGER,
558 };
559 
560 BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
561 {
562 	struct bpf_array *array = container_of(map, struct bpf_array, map);
563 	struct cgroup *cgrp;
564 
565 	if (unlikely(idx >= array->map.max_entries))
566 		return -E2BIG;
567 
568 	cgrp = READ_ONCE(array->ptrs[idx]);
569 	if (unlikely(!cgrp))
570 		return -EAGAIN;
571 
572 	return task_under_cgroup_hierarchy(current, cgrp);
573 }
574 
575 static const struct bpf_func_proto bpf_current_task_under_cgroup_proto = {
576 	.func           = bpf_current_task_under_cgroup,
577 	.gpl_only       = false,
578 	.ret_type       = RET_INTEGER,
579 	.arg1_type      = ARG_CONST_MAP_PTR,
580 	.arg2_type      = ARG_ANYTHING,
581 };
582 
583 BPF_CALL_3(bpf_probe_read_str, void *, dst, u32, size,
584 	   const void *, unsafe_ptr)
585 {
586 	int ret;
587 
588 	/*
589 	 * The strncpy_from_unsafe() call will likely not fill the entire
590 	 * buffer, but that's okay in this circumstance as we're probing
591 	 * arbitrary memory anyway similar to bpf_probe_read() and might
592 	 * as well probe the stack. Thus, memory is explicitly cleared
593 	 * only in error case, so that improper users ignoring return
594 	 * code altogether don't copy garbage; otherwise length of string
595 	 * is returned that can be used for bpf_perf_event_output() et al.
596 	 */
597 	ret = strncpy_from_unsafe(dst, unsafe_ptr, size);
598 	if (unlikely(ret < 0))
599 		memset(dst, 0, size);
600 
601 	return ret;
602 }
603 
604 static const struct bpf_func_proto bpf_probe_read_str_proto = {
605 	.func		= bpf_probe_read_str,
606 	.gpl_only	= true,
607 	.ret_type	= RET_INTEGER,
608 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
609 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
610 	.arg3_type	= ARG_ANYTHING,
611 };
612 
613 struct send_signal_irq_work {
614 	struct irq_work irq_work;
615 	struct task_struct *task;
616 	u32 sig;
617 };
618 
619 static DEFINE_PER_CPU(struct send_signal_irq_work, send_signal_work);
620 
621 static void do_bpf_send_signal(struct irq_work *entry)
622 {
623 	struct send_signal_irq_work *work;
624 
625 	work = container_of(entry, struct send_signal_irq_work, irq_work);
626 	group_send_sig_info(work->sig, SEND_SIG_PRIV, work->task, PIDTYPE_TGID);
627 }
628 
629 BPF_CALL_1(bpf_send_signal, u32, sig)
630 {
631 	struct send_signal_irq_work *work = NULL;
632 
633 	/* Similar to bpf_probe_write_user, task needs to be
634 	 * in a sound condition and kernel memory access be
635 	 * permitted in order to send signal to the current
636 	 * task.
637 	 */
638 	if (unlikely(current->flags & (PF_KTHREAD | PF_EXITING)))
639 		return -EPERM;
640 	if (unlikely(uaccess_kernel()))
641 		return -EPERM;
642 	if (unlikely(!nmi_uaccess_okay()))
643 		return -EPERM;
644 
645 	if (in_nmi()) {
646 		/* Do an early check on signal validity. Otherwise,
647 		 * the error is lost in deferred irq_work.
648 		 */
649 		if (unlikely(!valid_signal(sig)))
650 			return -EINVAL;
651 
652 		work = this_cpu_ptr(&send_signal_work);
653 		if (work->irq_work.flags & IRQ_WORK_BUSY)
654 			return -EBUSY;
655 
656 		/* Add the current task, which is the target of sending signal,
657 		 * to the irq_work. The current task may change when queued
658 		 * irq works get executed.
659 		 */
660 		work->task = current;
661 		work->sig = sig;
662 		irq_work_queue(&work->irq_work);
663 		return 0;
664 	}
665 
666 	return group_send_sig_info(sig, SEND_SIG_PRIV, current, PIDTYPE_TGID);
667 }
668 
669 static const struct bpf_func_proto bpf_send_signal_proto = {
670 	.func		= bpf_send_signal,
671 	.gpl_only	= false,
672 	.ret_type	= RET_INTEGER,
673 	.arg1_type	= ARG_ANYTHING,
674 };
675 
676 static const struct bpf_func_proto *
677 tracing_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
678 {
679 	switch (func_id) {
680 	case BPF_FUNC_map_lookup_elem:
681 		return &bpf_map_lookup_elem_proto;
682 	case BPF_FUNC_map_update_elem:
683 		return &bpf_map_update_elem_proto;
684 	case BPF_FUNC_map_delete_elem:
685 		return &bpf_map_delete_elem_proto;
686 	case BPF_FUNC_map_push_elem:
687 		return &bpf_map_push_elem_proto;
688 	case BPF_FUNC_map_pop_elem:
689 		return &bpf_map_pop_elem_proto;
690 	case BPF_FUNC_map_peek_elem:
691 		return &bpf_map_peek_elem_proto;
692 	case BPF_FUNC_probe_read:
693 		return &bpf_probe_read_proto;
694 	case BPF_FUNC_ktime_get_ns:
695 		return &bpf_ktime_get_ns_proto;
696 	case BPF_FUNC_tail_call:
697 		return &bpf_tail_call_proto;
698 	case BPF_FUNC_get_current_pid_tgid:
699 		return &bpf_get_current_pid_tgid_proto;
700 	case BPF_FUNC_get_current_task:
701 		return &bpf_get_current_task_proto;
702 	case BPF_FUNC_get_current_uid_gid:
703 		return &bpf_get_current_uid_gid_proto;
704 	case BPF_FUNC_get_current_comm:
705 		return &bpf_get_current_comm_proto;
706 	case BPF_FUNC_trace_printk:
707 		return bpf_get_trace_printk_proto();
708 	case BPF_FUNC_get_smp_processor_id:
709 		return &bpf_get_smp_processor_id_proto;
710 	case BPF_FUNC_get_numa_node_id:
711 		return &bpf_get_numa_node_id_proto;
712 	case BPF_FUNC_perf_event_read:
713 		return &bpf_perf_event_read_proto;
714 	case BPF_FUNC_probe_write_user:
715 		return bpf_get_probe_write_proto();
716 	case BPF_FUNC_current_task_under_cgroup:
717 		return &bpf_current_task_under_cgroup_proto;
718 	case BPF_FUNC_get_prandom_u32:
719 		return &bpf_get_prandom_u32_proto;
720 	case BPF_FUNC_probe_read_str:
721 		return &bpf_probe_read_str_proto;
722 #ifdef CONFIG_CGROUPS
723 	case BPF_FUNC_get_current_cgroup_id:
724 		return &bpf_get_current_cgroup_id_proto;
725 #endif
726 	case BPF_FUNC_send_signal:
727 		return &bpf_send_signal_proto;
728 	default:
729 		return NULL;
730 	}
731 }
732 
733 static const struct bpf_func_proto *
734 kprobe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
735 {
736 	switch (func_id) {
737 	case BPF_FUNC_perf_event_output:
738 		return &bpf_perf_event_output_proto;
739 	case BPF_FUNC_get_stackid:
740 		return &bpf_get_stackid_proto;
741 	case BPF_FUNC_get_stack:
742 		return &bpf_get_stack_proto;
743 	case BPF_FUNC_perf_event_read_value:
744 		return &bpf_perf_event_read_value_proto;
745 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
746 	case BPF_FUNC_override_return:
747 		return &bpf_override_return_proto;
748 #endif
749 	default:
750 		return tracing_func_proto(func_id, prog);
751 	}
752 }
753 
754 /* bpf+kprobe programs can access fields of 'struct pt_regs' */
755 static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
756 					const struct bpf_prog *prog,
757 					struct bpf_insn_access_aux *info)
758 {
759 	if (off < 0 || off >= sizeof(struct pt_regs))
760 		return false;
761 	if (type != BPF_READ)
762 		return false;
763 	if (off % size != 0)
764 		return false;
765 	/*
766 	 * Assertion for 32 bit to make sure last 8 byte access
767 	 * (BPF_DW) to the last 4 byte member is disallowed.
768 	 */
769 	if (off + size > sizeof(struct pt_regs))
770 		return false;
771 
772 	return true;
773 }
774 
775 const struct bpf_verifier_ops kprobe_verifier_ops = {
776 	.get_func_proto  = kprobe_prog_func_proto,
777 	.is_valid_access = kprobe_prog_is_valid_access,
778 };
779 
780 const struct bpf_prog_ops kprobe_prog_ops = {
781 };
782 
783 BPF_CALL_5(bpf_perf_event_output_tp, void *, tp_buff, struct bpf_map *, map,
784 	   u64, flags, void *, data, u64, size)
785 {
786 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
787 
788 	/*
789 	 * r1 points to perf tracepoint buffer where first 8 bytes are hidden
790 	 * from bpf program and contain a pointer to 'struct pt_regs'. Fetch it
791 	 * from there and call the same bpf_perf_event_output() helper inline.
792 	 */
793 	return ____bpf_perf_event_output(regs, map, flags, data, size);
794 }
795 
796 static const struct bpf_func_proto bpf_perf_event_output_proto_tp = {
797 	.func		= bpf_perf_event_output_tp,
798 	.gpl_only	= true,
799 	.ret_type	= RET_INTEGER,
800 	.arg1_type	= ARG_PTR_TO_CTX,
801 	.arg2_type	= ARG_CONST_MAP_PTR,
802 	.arg3_type	= ARG_ANYTHING,
803 	.arg4_type	= ARG_PTR_TO_MEM,
804 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
805 };
806 
807 BPF_CALL_3(bpf_get_stackid_tp, void *, tp_buff, struct bpf_map *, map,
808 	   u64, flags)
809 {
810 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
811 
812 	/*
813 	 * Same comment as in bpf_perf_event_output_tp(), only that this time
814 	 * the other helper's function body cannot be inlined due to being
815 	 * external, thus we need to call raw helper function.
816 	 */
817 	return bpf_get_stackid((unsigned long) regs, (unsigned long) map,
818 			       flags, 0, 0);
819 }
820 
821 static const struct bpf_func_proto bpf_get_stackid_proto_tp = {
822 	.func		= bpf_get_stackid_tp,
823 	.gpl_only	= true,
824 	.ret_type	= RET_INTEGER,
825 	.arg1_type	= ARG_PTR_TO_CTX,
826 	.arg2_type	= ARG_CONST_MAP_PTR,
827 	.arg3_type	= ARG_ANYTHING,
828 };
829 
830 BPF_CALL_4(bpf_get_stack_tp, void *, tp_buff, void *, buf, u32, size,
831 	   u64, flags)
832 {
833 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
834 
835 	return bpf_get_stack((unsigned long) regs, (unsigned long) buf,
836 			     (unsigned long) size, flags, 0);
837 }
838 
839 static const struct bpf_func_proto bpf_get_stack_proto_tp = {
840 	.func		= bpf_get_stack_tp,
841 	.gpl_only	= true,
842 	.ret_type	= RET_INTEGER,
843 	.arg1_type	= ARG_PTR_TO_CTX,
844 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
845 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
846 	.arg4_type	= ARG_ANYTHING,
847 };
848 
849 static const struct bpf_func_proto *
850 tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
851 {
852 	switch (func_id) {
853 	case BPF_FUNC_perf_event_output:
854 		return &bpf_perf_event_output_proto_tp;
855 	case BPF_FUNC_get_stackid:
856 		return &bpf_get_stackid_proto_tp;
857 	case BPF_FUNC_get_stack:
858 		return &bpf_get_stack_proto_tp;
859 	default:
860 		return tracing_func_proto(func_id, prog);
861 	}
862 }
863 
864 static bool tp_prog_is_valid_access(int off, int size, enum bpf_access_type type,
865 				    const struct bpf_prog *prog,
866 				    struct bpf_insn_access_aux *info)
867 {
868 	if (off < sizeof(void *) || off >= PERF_MAX_TRACE_SIZE)
869 		return false;
870 	if (type != BPF_READ)
871 		return false;
872 	if (off % size != 0)
873 		return false;
874 
875 	BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(__u64));
876 	return true;
877 }
878 
879 const struct bpf_verifier_ops tracepoint_verifier_ops = {
880 	.get_func_proto  = tp_prog_func_proto,
881 	.is_valid_access = tp_prog_is_valid_access,
882 };
883 
884 const struct bpf_prog_ops tracepoint_prog_ops = {
885 };
886 
887 BPF_CALL_3(bpf_perf_prog_read_value, struct bpf_perf_event_data_kern *, ctx,
888 	   struct bpf_perf_event_value *, buf, u32, size)
889 {
890 	int err = -EINVAL;
891 
892 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
893 		goto clear;
894 	err = perf_event_read_local(ctx->event, &buf->counter, &buf->enabled,
895 				    &buf->running);
896 	if (unlikely(err))
897 		goto clear;
898 	return 0;
899 clear:
900 	memset(buf, 0, size);
901 	return err;
902 }
903 
904 static const struct bpf_func_proto bpf_perf_prog_read_value_proto = {
905          .func           = bpf_perf_prog_read_value,
906          .gpl_only       = true,
907          .ret_type       = RET_INTEGER,
908          .arg1_type      = ARG_PTR_TO_CTX,
909          .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
910          .arg3_type      = ARG_CONST_SIZE,
911 };
912 
913 static const struct bpf_func_proto *
914 pe_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
915 {
916 	switch (func_id) {
917 	case BPF_FUNC_perf_event_output:
918 		return &bpf_perf_event_output_proto_tp;
919 	case BPF_FUNC_get_stackid:
920 		return &bpf_get_stackid_proto_tp;
921 	case BPF_FUNC_get_stack:
922 		return &bpf_get_stack_proto_tp;
923 	case BPF_FUNC_perf_prog_read_value:
924 		return &bpf_perf_prog_read_value_proto;
925 	default:
926 		return tracing_func_proto(func_id, prog);
927 	}
928 }
929 
930 /*
931  * bpf_raw_tp_regs are separate from bpf_pt_regs used from skb/xdp
932  * to avoid potential recursive reuse issue when/if tracepoints are added
933  * inside bpf_*_event_output, bpf_get_stackid and/or bpf_get_stack.
934  *
935  * Since raw tracepoints run despite bpf_prog_active, support concurrent usage
936  * in normal, irq, and nmi context.
937  */
938 struct bpf_raw_tp_regs {
939 	struct pt_regs regs[3];
940 };
941 static DEFINE_PER_CPU(struct bpf_raw_tp_regs, bpf_raw_tp_regs);
942 static DEFINE_PER_CPU(int, bpf_raw_tp_nest_level);
943 static struct pt_regs *get_bpf_raw_tp_regs(void)
944 {
945 	struct bpf_raw_tp_regs *tp_regs = this_cpu_ptr(&bpf_raw_tp_regs);
946 	int nest_level = this_cpu_inc_return(bpf_raw_tp_nest_level);
947 
948 	if (WARN_ON_ONCE(nest_level > ARRAY_SIZE(tp_regs->regs))) {
949 		this_cpu_dec(bpf_raw_tp_nest_level);
950 		return ERR_PTR(-EBUSY);
951 	}
952 
953 	return &tp_regs->regs[nest_level - 1];
954 }
955 
956 static void put_bpf_raw_tp_regs(void)
957 {
958 	this_cpu_dec(bpf_raw_tp_nest_level);
959 }
960 
961 BPF_CALL_5(bpf_perf_event_output_raw_tp, struct bpf_raw_tracepoint_args *, args,
962 	   struct bpf_map *, map, u64, flags, void *, data, u64, size)
963 {
964 	struct pt_regs *regs = get_bpf_raw_tp_regs();
965 	int ret;
966 
967 	if (IS_ERR(regs))
968 		return PTR_ERR(regs);
969 
970 	perf_fetch_caller_regs(regs);
971 	ret = ____bpf_perf_event_output(regs, map, flags, data, size);
972 
973 	put_bpf_raw_tp_regs();
974 	return ret;
975 }
976 
977 static const struct bpf_func_proto bpf_perf_event_output_proto_raw_tp = {
978 	.func		= bpf_perf_event_output_raw_tp,
979 	.gpl_only	= true,
980 	.ret_type	= RET_INTEGER,
981 	.arg1_type	= ARG_PTR_TO_CTX,
982 	.arg2_type	= ARG_CONST_MAP_PTR,
983 	.arg3_type	= ARG_ANYTHING,
984 	.arg4_type	= ARG_PTR_TO_MEM,
985 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
986 };
987 
988 BPF_CALL_3(bpf_get_stackid_raw_tp, struct bpf_raw_tracepoint_args *, args,
989 	   struct bpf_map *, map, u64, flags)
990 {
991 	struct pt_regs *regs = get_bpf_raw_tp_regs();
992 	int ret;
993 
994 	if (IS_ERR(regs))
995 		return PTR_ERR(regs);
996 
997 	perf_fetch_caller_regs(regs);
998 	/* similar to bpf_perf_event_output_tp, but pt_regs fetched differently */
999 	ret = bpf_get_stackid((unsigned long) regs, (unsigned long) map,
1000 			      flags, 0, 0);
1001 	put_bpf_raw_tp_regs();
1002 	return ret;
1003 }
1004 
1005 static const struct bpf_func_proto bpf_get_stackid_proto_raw_tp = {
1006 	.func		= bpf_get_stackid_raw_tp,
1007 	.gpl_only	= true,
1008 	.ret_type	= RET_INTEGER,
1009 	.arg1_type	= ARG_PTR_TO_CTX,
1010 	.arg2_type	= ARG_CONST_MAP_PTR,
1011 	.arg3_type	= ARG_ANYTHING,
1012 };
1013 
1014 BPF_CALL_4(bpf_get_stack_raw_tp, struct bpf_raw_tracepoint_args *, args,
1015 	   void *, buf, u32, size, u64, flags)
1016 {
1017 	struct pt_regs *regs = get_bpf_raw_tp_regs();
1018 	int ret;
1019 
1020 	if (IS_ERR(regs))
1021 		return PTR_ERR(regs);
1022 
1023 	perf_fetch_caller_regs(regs);
1024 	ret = bpf_get_stack((unsigned long) regs, (unsigned long) buf,
1025 			    (unsigned long) size, flags, 0);
1026 	put_bpf_raw_tp_regs();
1027 	return ret;
1028 }
1029 
1030 static const struct bpf_func_proto bpf_get_stack_proto_raw_tp = {
1031 	.func		= bpf_get_stack_raw_tp,
1032 	.gpl_only	= true,
1033 	.ret_type	= RET_INTEGER,
1034 	.arg1_type	= ARG_PTR_TO_CTX,
1035 	.arg2_type	= ARG_PTR_TO_MEM,
1036 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
1037 	.arg4_type	= ARG_ANYTHING,
1038 };
1039 
1040 static const struct bpf_func_proto *
1041 raw_tp_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1042 {
1043 	switch (func_id) {
1044 	case BPF_FUNC_perf_event_output:
1045 		return &bpf_perf_event_output_proto_raw_tp;
1046 	case BPF_FUNC_get_stackid:
1047 		return &bpf_get_stackid_proto_raw_tp;
1048 	case BPF_FUNC_get_stack:
1049 		return &bpf_get_stack_proto_raw_tp;
1050 	default:
1051 		return tracing_func_proto(func_id, prog);
1052 	}
1053 }
1054 
1055 static bool raw_tp_prog_is_valid_access(int off, int size,
1056 					enum bpf_access_type type,
1057 					const struct bpf_prog *prog,
1058 					struct bpf_insn_access_aux *info)
1059 {
1060 	/* largest tracepoint in the kernel has 12 args */
1061 	if (off < 0 || off >= sizeof(__u64) * 12)
1062 		return false;
1063 	if (type != BPF_READ)
1064 		return false;
1065 	if (off % size != 0)
1066 		return false;
1067 	return true;
1068 }
1069 
1070 const struct bpf_verifier_ops raw_tracepoint_verifier_ops = {
1071 	.get_func_proto  = raw_tp_prog_func_proto,
1072 	.is_valid_access = raw_tp_prog_is_valid_access,
1073 };
1074 
1075 const struct bpf_prog_ops raw_tracepoint_prog_ops = {
1076 };
1077 
1078 static bool raw_tp_writable_prog_is_valid_access(int off, int size,
1079 						 enum bpf_access_type type,
1080 						 const struct bpf_prog *prog,
1081 						 struct bpf_insn_access_aux *info)
1082 {
1083 	if (off == 0) {
1084 		if (size != sizeof(u64) || type != BPF_READ)
1085 			return false;
1086 		info->reg_type = PTR_TO_TP_BUFFER;
1087 	}
1088 	return raw_tp_prog_is_valid_access(off, size, type, prog, info);
1089 }
1090 
1091 const struct bpf_verifier_ops raw_tracepoint_writable_verifier_ops = {
1092 	.get_func_proto  = raw_tp_prog_func_proto,
1093 	.is_valid_access = raw_tp_writable_prog_is_valid_access,
1094 };
1095 
1096 const struct bpf_prog_ops raw_tracepoint_writable_prog_ops = {
1097 };
1098 
1099 static bool pe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
1100 				    const struct bpf_prog *prog,
1101 				    struct bpf_insn_access_aux *info)
1102 {
1103 	const int size_u64 = sizeof(u64);
1104 
1105 	if (off < 0 || off >= sizeof(struct bpf_perf_event_data))
1106 		return false;
1107 	if (type != BPF_READ)
1108 		return false;
1109 	if (off % size != 0) {
1110 		if (sizeof(unsigned long) != 4)
1111 			return false;
1112 		if (size != 8)
1113 			return false;
1114 		if (off % size != 4)
1115 			return false;
1116 	}
1117 
1118 	switch (off) {
1119 	case bpf_ctx_range(struct bpf_perf_event_data, sample_period):
1120 		bpf_ctx_record_field_size(info, size_u64);
1121 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
1122 			return false;
1123 		break;
1124 	case bpf_ctx_range(struct bpf_perf_event_data, addr):
1125 		bpf_ctx_record_field_size(info, size_u64);
1126 		if (!bpf_ctx_narrow_access_ok(off, size, size_u64))
1127 			return false;
1128 		break;
1129 	default:
1130 		if (size != sizeof(long))
1131 			return false;
1132 	}
1133 
1134 	return true;
1135 }
1136 
1137 static u32 pe_prog_convert_ctx_access(enum bpf_access_type type,
1138 				      const struct bpf_insn *si,
1139 				      struct bpf_insn *insn_buf,
1140 				      struct bpf_prog *prog, u32 *target_size)
1141 {
1142 	struct bpf_insn *insn = insn_buf;
1143 
1144 	switch (si->off) {
1145 	case offsetof(struct bpf_perf_event_data, sample_period):
1146 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1147 						       data), si->dst_reg, si->src_reg,
1148 				      offsetof(struct bpf_perf_event_data_kern, data));
1149 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
1150 				      bpf_target_off(struct perf_sample_data, period, 8,
1151 						     target_size));
1152 		break;
1153 	case offsetof(struct bpf_perf_event_data, addr):
1154 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1155 						       data), si->dst_reg, si->src_reg,
1156 				      offsetof(struct bpf_perf_event_data_kern, data));
1157 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
1158 				      bpf_target_off(struct perf_sample_data, addr, 8,
1159 						     target_size));
1160 		break;
1161 	default:
1162 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
1163 						       regs), si->dst_reg, si->src_reg,
1164 				      offsetof(struct bpf_perf_event_data_kern, regs));
1165 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(long), si->dst_reg, si->dst_reg,
1166 				      si->off);
1167 		break;
1168 	}
1169 
1170 	return insn - insn_buf;
1171 }
1172 
1173 const struct bpf_verifier_ops perf_event_verifier_ops = {
1174 	.get_func_proto		= pe_prog_func_proto,
1175 	.is_valid_access	= pe_prog_is_valid_access,
1176 	.convert_ctx_access	= pe_prog_convert_ctx_access,
1177 };
1178 
1179 const struct bpf_prog_ops perf_event_prog_ops = {
1180 };
1181 
1182 static DEFINE_MUTEX(bpf_event_mutex);
1183 
1184 #define BPF_TRACE_MAX_PROGS 64
1185 
1186 int perf_event_attach_bpf_prog(struct perf_event *event,
1187 			       struct bpf_prog *prog)
1188 {
1189 	struct bpf_prog_array *old_array;
1190 	struct bpf_prog_array *new_array;
1191 	int ret = -EEXIST;
1192 
1193 	/*
1194 	 * Kprobe override only works if they are on the function entry,
1195 	 * and only if they are on the opt-in list.
1196 	 */
1197 	if (prog->kprobe_override &&
1198 	    (!trace_kprobe_on_func_entry(event->tp_event) ||
1199 	     !trace_kprobe_error_injectable(event->tp_event)))
1200 		return -EINVAL;
1201 
1202 	mutex_lock(&bpf_event_mutex);
1203 
1204 	if (event->prog)
1205 		goto unlock;
1206 
1207 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
1208 	if (old_array &&
1209 	    bpf_prog_array_length(old_array) >= BPF_TRACE_MAX_PROGS) {
1210 		ret = -E2BIG;
1211 		goto unlock;
1212 	}
1213 
1214 	ret = bpf_prog_array_copy(old_array, NULL, prog, &new_array);
1215 	if (ret < 0)
1216 		goto unlock;
1217 
1218 	/* set the new array to event->tp_event and set event->prog */
1219 	event->prog = prog;
1220 	rcu_assign_pointer(event->tp_event->prog_array, new_array);
1221 	bpf_prog_array_free(old_array);
1222 
1223 unlock:
1224 	mutex_unlock(&bpf_event_mutex);
1225 	return ret;
1226 }
1227 
1228 void perf_event_detach_bpf_prog(struct perf_event *event)
1229 {
1230 	struct bpf_prog_array *old_array;
1231 	struct bpf_prog_array *new_array;
1232 	int ret;
1233 
1234 	mutex_lock(&bpf_event_mutex);
1235 
1236 	if (!event->prog)
1237 		goto unlock;
1238 
1239 	old_array = bpf_event_rcu_dereference(event->tp_event->prog_array);
1240 	ret = bpf_prog_array_copy(old_array, event->prog, NULL, &new_array);
1241 	if (ret == -ENOENT)
1242 		goto unlock;
1243 	if (ret < 0) {
1244 		bpf_prog_array_delete_safe(old_array, event->prog);
1245 	} else {
1246 		rcu_assign_pointer(event->tp_event->prog_array, new_array);
1247 		bpf_prog_array_free(old_array);
1248 	}
1249 
1250 	bpf_prog_put(event->prog);
1251 	event->prog = NULL;
1252 
1253 unlock:
1254 	mutex_unlock(&bpf_event_mutex);
1255 }
1256 
1257 int perf_event_query_prog_array(struct perf_event *event, void __user *info)
1258 {
1259 	struct perf_event_query_bpf __user *uquery = info;
1260 	struct perf_event_query_bpf query = {};
1261 	struct bpf_prog_array *progs;
1262 	u32 *ids, prog_cnt, ids_len;
1263 	int ret;
1264 
1265 	if (!capable(CAP_SYS_ADMIN))
1266 		return -EPERM;
1267 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
1268 		return -EINVAL;
1269 	if (copy_from_user(&query, uquery, sizeof(query)))
1270 		return -EFAULT;
1271 
1272 	ids_len = query.ids_len;
1273 	if (ids_len > BPF_TRACE_MAX_PROGS)
1274 		return -E2BIG;
1275 	ids = kcalloc(ids_len, sizeof(u32), GFP_USER | __GFP_NOWARN);
1276 	if (!ids)
1277 		return -ENOMEM;
1278 	/*
1279 	 * The above kcalloc returns ZERO_SIZE_PTR when ids_len = 0, which
1280 	 * is required when user only wants to check for uquery->prog_cnt.
1281 	 * There is no need to check for it since the case is handled
1282 	 * gracefully in bpf_prog_array_copy_info.
1283 	 */
1284 
1285 	mutex_lock(&bpf_event_mutex);
1286 	progs = bpf_event_rcu_dereference(event->tp_event->prog_array);
1287 	ret = bpf_prog_array_copy_info(progs, ids, ids_len, &prog_cnt);
1288 	mutex_unlock(&bpf_event_mutex);
1289 
1290 	if (copy_to_user(&uquery->prog_cnt, &prog_cnt, sizeof(prog_cnt)) ||
1291 	    copy_to_user(uquery->ids, ids, ids_len * sizeof(u32)))
1292 		ret = -EFAULT;
1293 
1294 	kfree(ids);
1295 	return ret;
1296 }
1297 
1298 extern struct bpf_raw_event_map __start__bpf_raw_tp[];
1299 extern struct bpf_raw_event_map __stop__bpf_raw_tp[];
1300 
1301 struct bpf_raw_event_map *bpf_get_raw_tracepoint(const char *name)
1302 {
1303 	struct bpf_raw_event_map *btp = __start__bpf_raw_tp;
1304 
1305 	for (; btp < __stop__bpf_raw_tp; btp++) {
1306 		if (!strcmp(btp->tp->name, name))
1307 			return btp;
1308 	}
1309 
1310 	return bpf_get_raw_tracepoint_module(name);
1311 }
1312 
1313 void bpf_put_raw_tracepoint(struct bpf_raw_event_map *btp)
1314 {
1315 	struct module *mod = __module_address((unsigned long)btp);
1316 
1317 	if (mod)
1318 		module_put(mod);
1319 }
1320 
1321 static __always_inline
1322 void __bpf_trace_run(struct bpf_prog *prog, u64 *args)
1323 {
1324 	rcu_read_lock();
1325 	preempt_disable();
1326 	(void) BPF_PROG_RUN(prog, args);
1327 	preempt_enable();
1328 	rcu_read_unlock();
1329 }
1330 
1331 #define UNPACK(...)			__VA_ARGS__
1332 #define REPEAT_1(FN, DL, X, ...)	FN(X)
1333 #define REPEAT_2(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_1(FN, DL, __VA_ARGS__)
1334 #define REPEAT_3(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_2(FN, DL, __VA_ARGS__)
1335 #define REPEAT_4(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_3(FN, DL, __VA_ARGS__)
1336 #define REPEAT_5(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_4(FN, DL, __VA_ARGS__)
1337 #define REPEAT_6(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_5(FN, DL, __VA_ARGS__)
1338 #define REPEAT_7(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_6(FN, DL, __VA_ARGS__)
1339 #define REPEAT_8(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_7(FN, DL, __VA_ARGS__)
1340 #define REPEAT_9(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_8(FN, DL, __VA_ARGS__)
1341 #define REPEAT_10(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_9(FN, DL, __VA_ARGS__)
1342 #define REPEAT_11(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_10(FN, DL, __VA_ARGS__)
1343 #define REPEAT_12(FN, DL, X, ...)	FN(X) UNPACK DL REPEAT_11(FN, DL, __VA_ARGS__)
1344 #define REPEAT(X, FN, DL, ...)		REPEAT_##X(FN, DL, __VA_ARGS__)
1345 
1346 #define SARG(X)		u64 arg##X
1347 #define COPY(X)		args[X] = arg##X
1348 
1349 #define __DL_COM	(,)
1350 #define __DL_SEM	(;)
1351 
1352 #define __SEQ_0_11	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
1353 
1354 #define BPF_TRACE_DEFN_x(x)						\
1355 	void bpf_trace_run##x(struct bpf_prog *prog,			\
1356 			      REPEAT(x, SARG, __DL_COM, __SEQ_0_11))	\
1357 	{								\
1358 		u64 args[x];						\
1359 		REPEAT(x, COPY, __DL_SEM, __SEQ_0_11);			\
1360 		__bpf_trace_run(prog, args);				\
1361 	}								\
1362 	EXPORT_SYMBOL_GPL(bpf_trace_run##x)
1363 BPF_TRACE_DEFN_x(1);
1364 BPF_TRACE_DEFN_x(2);
1365 BPF_TRACE_DEFN_x(3);
1366 BPF_TRACE_DEFN_x(4);
1367 BPF_TRACE_DEFN_x(5);
1368 BPF_TRACE_DEFN_x(6);
1369 BPF_TRACE_DEFN_x(7);
1370 BPF_TRACE_DEFN_x(8);
1371 BPF_TRACE_DEFN_x(9);
1372 BPF_TRACE_DEFN_x(10);
1373 BPF_TRACE_DEFN_x(11);
1374 BPF_TRACE_DEFN_x(12);
1375 
1376 static int __bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
1377 {
1378 	struct tracepoint *tp = btp->tp;
1379 
1380 	/*
1381 	 * check that program doesn't access arguments beyond what's
1382 	 * available in this tracepoint
1383 	 */
1384 	if (prog->aux->max_ctx_offset > btp->num_args * sizeof(u64))
1385 		return -EINVAL;
1386 
1387 	if (prog->aux->max_tp_access > btp->writable_size)
1388 		return -EINVAL;
1389 
1390 	return tracepoint_probe_register(tp, (void *)btp->bpf_func, prog);
1391 }
1392 
1393 int bpf_probe_register(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
1394 {
1395 	return __bpf_probe_register(btp, prog);
1396 }
1397 
1398 int bpf_probe_unregister(struct bpf_raw_event_map *btp, struct bpf_prog *prog)
1399 {
1400 	return tracepoint_probe_unregister(btp->tp, (void *)btp->bpf_func, prog);
1401 }
1402 
1403 int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id,
1404 			    u32 *fd_type, const char **buf,
1405 			    u64 *probe_offset, u64 *probe_addr)
1406 {
1407 	bool is_tracepoint, is_syscall_tp;
1408 	struct bpf_prog *prog;
1409 	int flags, err = 0;
1410 
1411 	prog = event->prog;
1412 	if (!prog)
1413 		return -ENOENT;
1414 
1415 	/* not supporting BPF_PROG_TYPE_PERF_EVENT yet */
1416 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT)
1417 		return -EOPNOTSUPP;
1418 
1419 	*prog_id = prog->aux->id;
1420 	flags = event->tp_event->flags;
1421 	is_tracepoint = flags & TRACE_EVENT_FL_TRACEPOINT;
1422 	is_syscall_tp = is_syscall_trace_event(event->tp_event);
1423 
1424 	if (is_tracepoint || is_syscall_tp) {
1425 		*buf = is_tracepoint ? event->tp_event->tp->name
1426 				     : event->tp_event->name;
1427 		*fd_type = BPF_FD_TYPE_TRACEPOINT;
1428 		*probe_offset = 0x0;
1429 		*probe_addr = 0x0;
1430 	} else {
1431 		/* kprobe/uprobe */
1432 		err = -EOPNOTSUPP;
1433 #ifdef CONFIG_KPROBE_EVENTS
1434 		if (flags & TRACE_EVENT_FL_KPROBE)
1435 			err = bpf_get_kprobe_info(event, fd_type, buf,
1436 						  probe_offset, probe_addr,
1437 						  event->attr.type == PERF_TYPE_TRACEPOINT);
1438 #endif
1439 #ifdef CONFIG_UPROBE_EVENTS
1440 		if (flags & TRACE_EVENT_FL_UPROBE)
1441 			err = bpf_get_uprobe_info(event, fd_type, buf,
1442 						  probe_offset,
1443 						  event->attr.type == PERF_TYPE_TRACEPOINT);
1444 #endif
1445 	}
1446 
1447 	return err;
1448 }
1449 
1450 static int __init send_signal_irq_work_init(void)
1451 {
1452 	int cpu;
1453 	struct send_signal_irq_work *work;
1454 
1455 	for_each_possible_cpu(cpu) {
1456 		work = per_cpu_ptr(&send_signal_work, cpu);
1457 		init_irq_work(&work->irq_work, do_bpf_send_signal);
1458 	}
1459 	return 0;
1460 }
1461 
1462 subsys_initcall(send_signal_irq_work_init);
1463 
1464 #ifdef CONFIG_MODULES
1465 static int bpf_event_notify(struct notifier_block *nb, unsigned long op,
1466 			    void *module)
1467 {
1468 	struct bpf_trace_module *btm, *tmp;
1469 	struct module *mod = module;
1470 
1471 	if (mod->num_bpf_raw_events == 0 ||
1472 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
1473 		return 0;
1474 
1475 	mutex_lock(&bpf_module_mutex);
1476 
1477 	switch (op) {
1478 	case MODULE_STATE_COMING:
1479 		btm = kzalloc(sizeof(*btm), GFP_KERNEL);
1480 		if (btm) {
1481 			btm->module = module;
1482 			list_add(&btm->list, &bpf_trace_modules);
1483 		}
1484 		break;
1485 	case MODULE_STATE_GOING:
1486 		list_for_each_entry_safe(btm, tmp, &bpf_trace_modules, list) {
1487 			if (btm->module == module) {
1488 				list_del(&btm->list);
1489 				kfree(btm);
1490 				break;
1491 			}
1492 		}
1493 		break;
1494 	}
1495 
1496 	mutex_unlock(&bpf_module_mutex);
1497 
1498 	return 0;
1499 }
1500 
1501 static struct notifier_block bpf_module_nb = {
1502 	.notifier_call = bpf_event_notify,
1503 };
1504 
1505 static int __init bpf_event_init(void)
1506 {
1507 	register_module_notifier(&bpf_module_nb);
1508 	return 0;
1509 }
1510 
1511 fs_initcall(bpf_event_init);
1512 #endif /* CONFIG_MODULES */
1513