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