xref: /openbmc/linux/kernel/trace/bpf_trace.c (revision 133f9794)
1 /* Copyright (c) 2011-2015 PLUMgrid, http://plumgrid.com
2  * Copyright (c) 2016 Facebook
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of version 2 of the GNU General Public
6  * License as published by the Free Software Foundation.
7  */
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/bpf_perf_event.h>
13 #include <linux/filter.h>
14 #include <linux/uaccess.h>
15 #include <linux/ctype.h>
16 #include <linux/kprobes.h>
17 #include <linux/error-injection.h>
18 
19 #include "trace_probe.h"
20 #include "trace.h"
21 
22 u64 bpf_get_stackid(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
23 
24 /**
25  * trace_call_bpf - invoke BPF program
26  * @call: tracepoint event
27  * @ctx: opaque context pointer
28  *
29  * kprobe handlers execute BPF programs via this helper.
30  * Can be used from static tracepoints in the future.
31  *
32  * Return: BPF programs always return an integer which is interpreted by
33  * kprobe handler as:
34  * 0 - return from kprobe (event is filtered out)
35  * 1 - store kprobe event into ring buffer
36  * Other values are reserved and currently alias to 1
37  */
38 unsigned int trace_call_bpf(struct trace_event_call *call, void *ctx)
39 {
40 	unsigned int ret;
41 
42 	if (in_nmi()) /* not supported yet */
43 		return 1;
44 
45 	preempt_disable();
46 
47 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
48 		/*
49 		 * since some bpf program is already running on this cpu,
50 		 * don't call into another bpf program (same or different)
51 		 * and don't send kprobe event into ring-buffer,
52 		 * so return zero here
53 		 */
54 		ret = 0;
55 		goto out;
56 	}
57 
58 	/*
59 	 * Instead of moving rcu_read_lock/rcu_dereference/rcu_read_unlock
60 	 * to all call sites, we did a bpf_prog_array_valid() there to check
61 	 * whether call->prog_array is empty or not, which is
62 	 * a heurisitc to speed up execution.
63 	 *
64 	 * If bpf_prog_array_valid() fetched prog_array was
65 	 * non-NULL, we go into trace_call_bpf() and do the actual
66 	 * proper rcu_dereference() under RCU lock.
67 	 * If it turns out that prog_array is NULL then, we bail out.
68 	 * For the opposite, if the bpf_prog_array_valid() fetched pointer
69 	 * was NULL, you'll skip the prog_array with the risk of missing
70 	 * out of events when it was updated in between this and the
71 	 * rcu_dereference() which is accepted risk.
72 	 */
73 	ret = BPF_PROG_RUN_ARRAY_CHECK(call->prog_array, ctx, BPF_PROG_RUN);
74 
75  out:
76 	__this_cpu_dec(bpf_prog_active);
77 	preempt_enable();
78 
79 	return ret;
80 }
81 EXPORT_SYMBOL_GPL(trace_call_bpf);
82 
83 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
84 BPF_CALL_2(bpf_override_return, struct pt_regs *, regs, unsigned long, rc)
85 {
86 	regs_set_return_value(regs, rc);
87 	override_function_with_return(regs);
88 	return 0;
89 }
90 
91 static const struct bpf_func_proto bpf_override_return_proto = {
92 	.func		= bpf_override_return,
93 	.gpl_only	= true,
94 	.ret_type	= RET_INTEGER,
95 	.arg1_type	= ARG_PTR_TO_CTX,
96 	.arg2_type	= ARG_ANYTHING,
97 };
98 #endif
99 
100 BPF_CALL_3(bpf_probe_read, void *, dst, u32, size, const void *, unsafe_ptr)
101 {
102 	int ret;
103 
104 	ret = probe_kernel_read(dst, unsafe_ptr, size);
105 	if (unlikely(ret < 0))
106 		memset(dst, 0, size);
107 
108 	return ret;
109 }
110 
111 static const struct bpf_func_proto bpf_probe_read_proto = {
112 	.func		= bpf_probe_read,
113 	.gpl_only	= true,
114 	.ret_type	= RET_INTEGER,
115 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
116 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
117 	.arg3_type	= ARG_ANYTHING,
118 };
119 
120 BPF_CALL_3(bpf_probe_write_user, void *, unsafe_ptr, const void *, src,
121 	   u32, size)
122 {
123 	/*
124 	 * Ensure we're in user context which is safe for the helper to
125 	 * run. This helper has no business in a kthread.
126 	 *
127 	 * access_ok() should prevent writing to non-user memory, but in
128 	 * some situations (nommu, temporary switch, etc) access_ok() does
129 	 * not provide enough validation, hence the check on KERNEL_DS.
130 	 */
131 
132 	if (unlikely(in_interrupt() ||
133 		     current->flags & (PF_KTHREAD | PF_EXITING)))
134 		return -EPERM;
135 	if (unlikely(uaccess_kernel()))
136 		return -EPERM;
137 	if (!access_ok(VERIFY_WRITE, unsafe_ptr, size))
138 		return -EPERM;
139 
140 	return probe_kernel_write(unsafe_ptr, src, size);
141 }
142 
143 static const struct bpf_func_proto bpf_probe_write_user_proto = {
144 	.func		= bpf_probe_write_user,
145 	.gpl_only	= true,
146 	.ret_type	= RET_INTEGER,
147 	.arg1_type	= ARG_ANYTHING,
148 	.arg2_type	= ARG_PTR_TO_MEM,
149 	.arg3_type	= ARG_CONST_SIZE,
150 };
151 
152 static const struct bpf_func_proto *bpf_get_probe_write_proto(void)
153 {
154 	pr_warn_ratelimited("%s[%d] is installing a program with bpf_probe_write_user helper that may corrupt user memory!",
155 			    current->comm, task_pid_nr(current));
156 
157 	return &bpf_probe_write_user_proto;
158 }
159 
160 /*
161  * Only limited trace_printk() conversion specifiers allowed:
162  * %d %i %u %x %ld %li %lu %lx %lld %lli %llu %llx %p %s
163  */
164 BPF_CALL_5(bpf_trace_printk, char *, fmt, u32, fmt_size, u64, arg1,
165 	   u64, arg2, u64, arg3)
166 {
167 	bool str_seen = false;
168 	int mod[3] = {};
169 	int fmt_cnt = 0;
170 	u64 unsafe_addr;
171 	char buf[64];
172 	int i;
173 
174 	/*
175 	 * bpf_check()->check_func_arg()->check_stack_boundary()
176 	 * guarantees that fmt points to bpf program stack,
177 	 * fmt_size bytes of it were initialized and fmt_size > 0
178 	 */
179 	if (fmt[--fmt_size] != 0)
180 		return -EINVAL;
181 
182 	/* check format string for allowed specifiers */
183 	for (i = 0; i < fmt_size; i++) {
184 		if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i]))
185 			return -EINVAL;
186 
187 		if (fmt[i] != '%')
188 			continue;
189 
190 		if (fmt_cnt >= 3)
191 			return -EINVAL;
192 
193 		/* fmt[i] != 0 && fmt[last] == 0, so we can access fmt[i + 1] */
194 		i++;
195 		if (fmt[i] == 'l') {
196 			mod[fmt_cnt]++;
197 			i++;
198 		} else if (fmt[i] == 'p' || fmt[i] == 's') {
199 			mod[fmt_cnt]++;
200 			i++;
201 			if (!isspace(fmt[i]) && !ispunct(fmt[i]) && fmt[i] != 0)
202 				return -EINVAL;
203 			fmt_cnt++;
204 			if (fmt[i - 1] == 's') {
205 				if (str_seen)
206 					/* allow only one '%s' per fmt string */
207 					return -EINVAL;
208 				str_seen = true;
209 
210 				switch (fmt_cnt) {
211 				case 1:
212 					unsafe_addr = arg1;
213 					arg1 = (long) buf;
214 					break;
215 				case 2:
216 					unsafe_addr = arg2;
217 					arg2 = (long) buf;
218 					break;
219 				case 3:
220 					unsafe_addr = arg3;
221 					arg3 = (long) buf;
222 					break;
223 				}
224 				buf[0] = 0;
225 				strncpy_from_unsafe(buf,
226 						    (void *) (long) unsafe_addr,
227 						    sizeof(buf));
228 			}
229 			continue;
230 		}
231 
232 		if (fmt[i] == 'l') {
233 			mod[fmt_cnt]++;
234 			i++;
235 		}
236 
237 		if (fmt[i] != 'i' && fmt[i] != 'd' &&
238 		    fmt[i] != 'u' && fmt[i] != 'x')
239 			return -EINVAL;
240 		fmt_cnt++;
241 	}
242 
243 /* Horrid workaround for getting va_list handling working with different
244  * argument type combinations generically for 32 and 64 bit archs.
245  */
246 #define __BPF_TP_EMIT()	__BPF_ARG3_TP()
247 #define __BPF_TP(...)							\
248 	__trace_printk(0 /* Fake ip */,					\
249 		       fmt, ##__VA_ARGS__)
250 
251 #define __BPF_ARG1_TP(...)						\
252 	((mod[0] == 2 || (mod[0] == 1 && __BITS_PER_LONG == 64))	\
253 	  ? __BPF_TP(arg1, ##__VA_ARGS__)				\
254 	  : ((mod[0] == 1 || (mod[0] == 0 && __BITS_PER_LONG == 32))	\
255 	      ? __BPF_TP((long)arg1, ##__VA_ARGS__)			\
256 	      : __BPF_TP((u32)arg1, ##__VA_ARGS__)))
257 
258 #define __BPF_ARG2_TP(...)						\
259 	((mod[1] == 2 || (mod[1] == 1 && __BITS_PER_LONG == 64))	\
260 	  ? __BPF_ARG1_TP(arg2, ##__VA_ARGS__)				\
261 	  : ((mod[1] == 1 || (mod[1] == 0 && __BITS_PER_LONG == 32))	\
262 	      ? __BPF_ARG1_TP((long)arg2, ##__VA_ARGS__)		\
263 	      : __BPF_ARG1_TP((u32)arg2, ##__VA_ARGS__)))
264 
265 #define __BPF_ARG3_TP(...)						\
266 	((mod[2] == 2 || (mod[2] == 1 && __BITS_PER_LONG == 64))	\
267 	  ? __BPF_ARG2_TP(arg3, ##__VA_ARGS__)				\
268 	  : ((mod[2] == 1 || (mod[2] == 0 && __BITS_PER_LONG == 32))	\
269 	      ? __BPF_ARG2_TP((long)arg3, ##__VA_ARGS__)		\
270 	      : __BPF_ARG2_TP((u32)arg3, ##__VA_ARGS__)))
271 
272 	return __BPF_TP_EMIT();
273 }
274 
275 static const struct bpf_func_proto bpf_trace_printk_proto = {
276 	.func		= bpf_trace_printk,
277 	.gpl_only	= true,
278 	.ret_type	= RET_INTEGER,
279 	.arg1_type	= ARG_PTR_TO_MEM,
280 	.arg2_type	= ARG_CONST_SIZE,
281 };
282 
283 const struct bpf_func_proto *bpf_get_trace_printk_proto(void)
284 {
285 	/*
286 	 * this program might be calling bpf_trace_printk,
287 	 * so allocate per-cpu printk buffers
288 	 */
289 	trace_printk_init_buffers();
290 
291 	return &bpf_trace_printk_proto;
292 }
293 
294 static __always_inline int
295 get_map_perf_counter(struct bpf_map *map, u64 flags,
296 		     u64 *value, u64 *enabled, u64 *running)
297 {
298 	struct bpf_array *array = container_of(map, struct bpf_array, map);
299 	unsigned int cpu = smp_processor_id();
300 	u64 index = flags & BPF_F_INDEX_MASK;
301 	struct bpf_event_entry *ee;
302 
303 	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
304 		return -EINVAL;
305 	if (index == BPF_F_CURRENT_CPU)
306 		index = cpu;
307 	if (unlikely(index >= array->map.max_entries))
308 		return -E2BIG;
309 
310 	ee = READ_ONCE(array->ptrs[index]);
311 	if (!ee)
312 		return -ENOENT;
313 
314 	return perf_event_read_local(ee->event, value, enabled, running);
315 }
316 
317 BPF_CALL_2(bpf_perf_event_read, struct bpf_map *, map, u64, flags)
318 {
319 	u64 value = 0;
320 	int err;
321 
322 	err = get_map_perf_counter(map, flags, &value, NULL, NULL);
323 	/*
324 	 * this api is ugly since we miss [-22..-2] range of valid
325 	 * counter values, but that's uapi
326 	 */
327 	if (err)
328 		return err;
329 	return value;
330 }
331 
332 static const struct bpf_func_proto bpf_perf_event_read_proto = {
333 	.func		= bpf_perf_event_read,
334 	.gpl_only	= true,
335 	.ret_type	= RET_INTEGER,
336 	.arg1_type	= ARG_CONST_MAP_PTR,
337 	.arg2_type	= ARG_ANYTHING,
338 };
339 
340 BPF_CALL_4(bpf_perf_event_read_value, struct bpf_map *, map, u64, flags,
341 	   struct bpf_perf_event_value *, buf, u32, size)
342 {
343 	int err = -EINVAL;
344 
345 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
346 		goto clear;
347 	err = get_map_perf_counter(map, flags, &buf->counter, &buf->enabled,
348 				   &buf->running);
349 	if (unlikely(err))
350 		goto clear;
351 	return 0;
352 clear:
353 	memset(buf, 0, size);
354 	return err;
355 }
356 
357 static const struct bpf_func_proto bpf_perf_event_read_value_proto = {
358 	.func		= bpf_perf_event_read_value,
359 	.gpl_only	= true,
360 	.ret_type	= RET_INTEGER,
361 	.arg1_type	= ARG_CONST_MAP_PTR,
362 	.arg2_type	= ARG_ANYTHING,
363 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
364 	.arg4_type	= ARG_CONST_SIZE,
365 };
366 
367 static DEFINE_PER_CPU(struct perf_sample_data, bpf_trace_sd);
368 
369 static __always_inline u64
370 __bpf_perf_event_output(struct pt_regs *regs, struct bpf_map *map,
371 			u64 flags, struct perf_sample_data *sd)
372 {
373 	struct bpf_array *array = container_of(map, struct bpf_array, map);
374 	unsigned int cpu = smp_processor_id();
375 	u64 index = flags & BPF_F_INDEX_MASK;
376 	struct bpf_event_entry *ee;
377 	struct perf_event *event;
378 
379 	if (index == BPF_F_CURRENT_CPU)
380 		index = cpu;
381 	if (unlikely(index >= array->map.max_entries))
382 		return -E2BIG;
383 
384 	ee = READ_ONCE(array->ptrs[index]);
385 	if (!ee)
386 		return -ENOENT;
387 
388 	event = ee->event;
389 	if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
390 		     event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
391 		return -EINVAL;
392 
393 	if (unlikely(event->oncpu != cpu))
394 		return -EOPNOTSUPP;
395 
396 	perf_event_output(event, sd, regs);
397 	return 0;
398 }
399 
400 BPF_CALL_5(bpf_perf_event_output, struct pt_regs *, regs, struct bpf_map *, map,
401 	   u64, flags, void *, data, u64, size)
402 {
403 	struct perf_sample_data *sd = this_cpu_ptr(&bpf_trace_sd);
404 	struct perf_raw_record raw = {
405 		.frag = {
406 			.size = size,
407 			.data = data,
408 		},
409 	};
410 
411 	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
412 		return -EINVAL;
413 
414 	perf_sample_data_init(sd, 0, 0);
415 	sd->raw = &raw;
416 
417 	return __bpf_perf_event_output(regs, map, flags, sd);
418 }
419 
420 static const struct bpf_func_proto bpf_perf_event_output_proto = {
421 	.func		= bpf_perf_event_output,
422 	.gpl_only	= true,
423 	.ret_type	= RET_INTEGER,
424 	.arg1_type	= ARG_PTR_TO_CTX,
425 	.arg2_type	= ARG_CONST_MAP_PTR,
426 	.arg3_type	= ARG_ANYTHING,
427 	.arg4_type	= ARG_PTR_TO_MEM,
428 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
429 };
430 
431 static DEFINE_PER_CPU(struct pt_regs, bpf_pt_regs);
432 static DEFINE_PER_CPU(struct perf_sample_data, bpf_misc_sd);
433 
434 u64 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
435 		     void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
436 {
437 	struct perf_sample_data *sd = this_cpu_ptr(&bpf_misc_sd);
438 	struct pt_regs *regs = this_cpu_ptr(&bpf_pt_regs);
439 	struct perf_raw_frag frag = {
440 		.copy		= ctx_copy,
441 		.size		= ctx_size,
442 		.data		= ctx,
443 	};
444 	struct perf_raw_record raw = {
445 		.frag = {
446 			{
447 				.next	= ctx_size ? &frag : NULL,
448 			},
449 			.size	= meta_size,
450 			.data	= meta,
451 		},
452 	};
453 
454 	perf_fetch_caller_regs(regs);
455 	perf_sample_data_init(sd, 0, 0);
456 	sd->raw = &raw;
457 
458 	return __bpf_perf_event_output(regs, map, flags, sd);
459 }
460 
461 BPF_CALL_0(bpf_get_current_task)
462 {
463 	return (long) current;
464 }
465 
466 static const struct bpf_func_proto bpf_get_current_task_proto = {
467 	.func		= bpf_get_current_task,
468 	.gpl_only	= true,
469 	.ret_type	= RET_INTEGER,
470 };
471 
472 BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
473 {
474 	struct bpf_array *array = container_of(map, struct bpf_array, map);
475 	struct cgroup *cgrp;
476 
477 	if (unlikely(in_interrupt()))
478 		return -EINVAL;
479 	if (unlikely(idx >= array->map.max_entries))
480 		return -E2BIG;
481 
482 	cgrp = READ_ONCE(array->ptrs[idx]);
483 	if (unlikely(!cgrp))
484 		return -EAGAIN;
485 
486 	return task_under_cgroup_hierarchy(current, cgrp);
487 }
488 
489 static const struct bpf_func_proto bpf_current_task_under_cgroup_proto = {
490 	.func           = bpf_current_task_under_cgroup,
491 	.gpl_only       = false,
492 	.ret_type       = RET_INTEGER,
493 	.arg1_type      = ARG_CONST_MAP_PTR,
494 	.arg2_type      = ARG_ANYTHING,
495 };
496 
497 BPF_CALL_3(bpf_probe_read_str, void *, dst, u32, size,
498 	   const void *, unsafe_ptr)
499 {
500 	int ret;
501 
502 	/*
503 	 * The strncpy_from_unsafe() call will likely not fill the entire
504 	 * buffer, but that's okay in this circumstance as we're probing
505 	 * arbitrary memory anyway similar to bpf_probe_read() and might
506 	 * as well probe the stack. Thus, memory is explicitly cleared
507 	 * only in error case, so that improper users ignoring return
508 	 * code altogether don't copy garbage; otherwise length of string
509 	 * is returned that can be used for bpf_perf_event_output() et al.
510 	 */
511 	ret = strncpy_from_unsafe(dst, unsafe_ptr, size);
512 	if (unlikely(ret < 0))
513 		memset(dst, 0, size);
514 
515 	return ret;
516 }
517 
518 static const struct bpf_func_proto bpf_probe_read_str_proto = {
519 	.func		= bpf_probe_read_str,
520 	.gpl_only	= true,
521 	.ret_type	= RET_INTEGER,
522 	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
523 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
524 	.arg3_type	= ARG_ANYTHING,
525 };
526 
527 static const struct bpf_func_proto *tracing_func_proto(enum bpf_func_id func_id)
528 {
529 	switch (func_id) {
530 	case BPF_FUNC_map_lookup_elem:
531 		return &bpf_map_lookup_elem_proto;
532 	case BPF_FUNC_map_update_elem:
533 		return &bpf_map_update_elem_proto;
534 	case BPF_FUNC_map_delete_elem:
535 		return &bpf_map_delete_elem_proto;
536 	case BPF_FUNC_probe_read:
537 		return &bpf_probe_read_proto;
538 	case BPF_FUNC_ktime_get_ns:
539 		return &bpf_ktime_get_ns_proto;
540 	case BPF_FUNC_tail_call:
541 		return &bpf_tail_call_proto;
542 	case BPF_FUNC_get_current_pid_tgid:
543 		return &bpf_get_current_pid_tgid_proto;
544 	case BPF_FUNC_get_current_task:
545 		return &bpf_get_current_task_proto;
546 	case BPF_FUNC_get_current_uid_gid:
547 		return &bpf_get_current_uid_gid_proto;
548 	case BPF_FUNC_get_current_comm:
549 		return &bpf_get_current_comm_proto;
550 	case BPF_FUNC_trace_printk:
551 		return bpf_get_trace_printk_proto();
552 	case BPF_FUNC_get_smp_processor_id:
553 		return &bpf_get_smp_processor_id_proto;
554 	case BPF_FUNC_get_numa_node_id:
555 		return &bpf_get_numa_node_id_proto;
556 	case BPF_FUNC_perf_event_read:
557 		return &bpf_perf_event_read_proto;
558 	case BPF_FUNC_probe_write_user:
559 		return bpf_get_probe_write_proto();
560 	case BPF_FUNC_current_task_under_cgroup:
561 		return &bpf_current_task_under_cgroup_proto;
562 	case BPF_FUNC_get_prandom_u32:
563 		return &bpf_get_prandom_u32_proto;
564 	case BPF_FUNC_probe_read_str:
565 		return &bpf_probe_read_str_proto;
566 	default:
567 		return NULL;
568 	}
569 }
570 
571 static const struct bpf_func_proto *kprobe_prog_func_proto(enum bpf_func_id func_id)
572 {
573 	switch (func_id) {
574 	case BPF_FUNC_perf_event_output:
575 		return &bpf_perf_event_output_proto;
576 	case BPF_FUNC_get_stackid:
577 		return &bpf_get_stackid_proto;
578 	case BPF_FUNC_perf_event_read_value:
579 		return &bpf_perf_event_read_value_proto;
580 #ifdef CONFIG_BPF_KPROBE_OVERRIDE
581 	case BPF_FUNC_override_return:
582 		return &bpf_override_return_proto;
583 #endif
584 	default:
585 		return tracing_func_proto(func_id);
586 	}
587 }
588 
589 /* bpf+kprobe programs can access fields of 'struct pt_regs' */
590 static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
591 					struct bpf_insn_access_aux *info)
592 {
593 	if (off < 0 || off >= sizeof(struct pt_regs))
594 		return false;
595 	if (type != BPF_READ)
596 		return false;
597 	if (off % size != 0)
598 		return false;
599 	/*
600 	 * Assertion for 32 bit to make sure last 8 byte access
601 	 * (BPF_DW) to the last 4 byte member is disallowed.
602 	 */
603 	if (off + size > sizeof(struct pt_regs))
604 		return false;
605 
606 	return true;
607 }
608 
609 const struct bpf_verifier_ops kprobe_verifier_ops = {
610 	.get_func_proto  = kprobe_prog_func_proto,
611 	.is_valid_access = kprobe_prog_is_valid_access,
612 };
613 
614 const struct bpf_prog_ops kprobe_prog_ops = {
615 };
616 
617 BPF_CALL_5(bpf_perf_event_output_tp, void *, tp_buff, struct bpf_map *, map,
618 	   u64, flags, void *, data, u64, size)
619 {
620 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
621 
622 	/*
623 	 * r1 points to perf tracepoint buffer where first 8 bytes are hidden
624 	 * from bpf program and contain a pointer to 'struct pt_regs'. Fetch it
625 	 * from there and call the same bpf_perf_event_output() helper inline.
626 	 */
627 	return ____bpf_perf_event_output(regs, map, flags, data, size);
628 }
629 
630 static const struct bpf_func_proto bpf_perf_event_output_proto_tp = {
631 	.func		= bpf_perf_event_output_tp,
632 	.gpl_only	= true,
633 	.ret_type	= RET_INTEGER,
634 	.arg1_type	= ARG_PTR_TO_CTX,
635 	.arg2_type	= ARG_CONST_MAP_PTR,
636 	.arg3_type	= ARG_ANYTHING,
637 	.arg4_type	= ARG_PTR_TO_MEM,
638 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
639 };
640 
641 BPF_CALL_3(bpf_get_stackid_tp, void *, tp_buff, struct bpf_map *, map,
642 	   u64, flags)
643 {
644 	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
645 
646 	/*
647 	 * Same comment as in bpf_perf_event_output_tp(), only that this time
648 	 * the other helper's function body cannot be inlined due to being
649 	 * external, thus we need to call raw helper function.
650 	 */
651 	return bpf_get_stackid((unsigned long) regs, (unsigned long) map,
652 			       flags, 0, 0);
653 }
654 
655 static const struct bpf_func_proto bpf_get_stackid_proto_tp = {
656 	.func		= bpf_get_stackid_tp,
657 	.gpl_only	= true,
658 	.ret_type	= RET_INTEGER,
659 	.arg1_type	= ARG_PTR_TO_CTX,
660 	.arg2_type	= ARG_CONST_MAP_PTR,
661 	.arg3_type	= ARG_ANYTHING,
662 };
663 
664 BPF_CALL_3(bpf_perf_prog_read_value_tp, struct bpf_perf_event_data_kern *, ctx,
665 	   struct bpf_perf_event_value *, buf, u32, size)
666 {
667 	int err = -EINVAL;
668 
669 	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
670 		goto clear;
671 	err = perf_event_read_local(ctx->event, &buf->counter, &buf->enabled,
672 				    &buf->running);
673 	if (unlikely(err))
674 		goto clear;
675 	return 0;
676 clear:
677 	memset(buf, 0, size);
678 	return err;
679 }
680 
681 static const struct bpf_func_proto bpf_perf_prog_read_value_proto_tp = {
682          .func           = bpf_perf_prog_read_value_tp,
683          .gpl_only       = true,
684          .ret_type       = RET_INTEGER,
685          .arg1_type      = ARG_PTR_TO_CTX,
686          .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
687          .arg3_type      = ARG_CONST_SIZE,
688 };
689 
690 static const struct bpf_func_proto *tp_prog_func_proto(enum bpf_func_id func_id)
691 {
692 	switch (func_id) {
693 	case BPF_FUNC_perf_event_output:
694 		return &bpf_perf_event_output_proto_tp;
695 	case BPF_FUNC_get_stackid:
696 		return &bpf_get_stackid_proto_tp;
697 	case BPF_FUNC_perf_prog_read_value:
698 		return &bpf_perf_prog_read_value_proto_tp;
699 	default:
700 		return tracing_func_proto(func_id);
701 	}
702 }
703 
704 static bool tp_prog_is_valid_access(int off, int size, enum bpf_access_type type,
705 				    struct bpf_insn_access_aux *info)
706 {
707 	if (off < sizeof(void *) || off >= PERF_MAX_TRACE_SIZE)
708 		return false;
709 	if (type != BPF_READ)
710 		return false;
711 	if (off % size != 0)
712 		return false;
713 
714 	BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(__u64));
715 	return true;
716 }
717 
718 const struct bpf_verifier_ops tracepoint_verifier_ops = {
719 	.get_func_proto  = tp_prog_func_proto,
720 	.is_valid_access = tp_prog_is_valid_access,
721 };
722 
723 const struct bpf_prog_ops tracepoint_prog_ops = {
724 };
725 
726 static bool pe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
727 				    struct bpf_insn_access_aux *info)
728 {
729 	const int size_sp = FIELD_SIZEOF(struct bpf_perf_event_data,
730 					 sample_period);
731 
732 	if (off < 0 || off >= sizeof(struct bpf_perf_event_data))
733 		return false;
734 	if (type != BPF_READ)
735 		return false;
736 	if (off % size != 0)
737 		return false;
738 
739 	switch (off) {
740 	case bpf_ctx_range(struct bpf_perf_event_data, sample_period):
741 		bpf_ctx_record_field_size(info, size_sp);
742 		if (!bpf_ctx_narrow_access_ok(off, size, size_sp))
743 			return false;
744 		break;
745 	default:
746 		if (size != sizeof(long))
747 			return false;
748 	}
749 
750 	return true;
751 }
752 
753 static u32 pe_prog_convert_ctx_access(enum bpf_access_type type,
754 				      const struct bpf_insn *si,
755 				      struct bpf_insn *insn_buf,
756 				      struct bpf_prog *prog, u32 *target_size)
757 {
758 	struct bpf_insn *insn = insn_buf;
759 
760 	switch (si->off) {
761 	case offsetof(struct bpf_perf_event_data, sample_period):
762 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
763 						       data), si->dst_reg, si->src_reg,
764 				      offsetof(struct bpf_perf_event_data_kern, data));
765 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
766 				      bpf_target_off(struct perf_sample_data, period, 8,
767 						     target_size));
768 		break;
769 	default:
770 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
771 						       regs), si->dst_reg, si->src_reg,
772 				      offsetof(struct bpf_perf_event_data_kern, regs));
773 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(long), si->dst_reg, si->dst_reg,
774 				      si->off);
775 		break;
776 	}
777 
778 	return insn - insn_buf;
779 }
780 
781 const struct bpf_verifier_ops perf_event_verifier_ops = {
782 	.get_func_proto		= tp_prog_func_proto,
783 	.is_valid_access	= pe_prog_is_valid_access,
784 	.convert_ctx_access	= pe_prog_convert_ctx_access,
785 };
786 
787 const struct bpf_prog_ops perf_event_prog_ops = {
788 };
789 
790 static DEFINE_MUTEX(bpf_event_mutex);
791 
792 #define BPF_TRACE_MAX_PROGS 64
793 
794 int perf_event_attach_bpf_prog(struct perf_event *event,
795 			       struct bpf_prog *prog)
796 {
797 	struct bpf_prog_array __rcu *old_array;
798 	struct bpf_prog_array *new_array;
799 	int ret = -EEXIST;
800 
801 	/*
802 	 * Kprobe override only works if they are on the function entry,
803 	 * and only if they are on the opt-in list.
804 	 */
805 	if (prog->kprobe_override &&
806 	    (!trace_kprobe_on_func_entry(event->tp_event) ||
807 	     !trace_kprobe_error_injectable(event->tp_event)))
808 		return -EINVAL;
809 
810 	mutex_lock(&bpf_event_mutex);
811 
812 	if (event->prog)
813 		goto unlock;
814 
815 	old_array = event->tp_event->prog_array;
816 	if (old_array &&
817 	    bpf_prog_array_length(old_array) >= BPF_TRACE_MAX_PROGS) {
818 		ret = -E2BIG;
819 		goto unlock;
820 	}
821 
822 	ret = bpf_prog_array_copy(old_array, NULL, prog, &new_array);
823 	if (ret < 0)
824 		goto unlock;
825 
826 	/* set the new array to event->tp_event and set event->prog */
827 	event->prog = prog;
828 	rcu_assign_pointer(event->tp_event->prog_array, new_array);
829 	bpf_prog_array_free(old_array);
830 
831 unlock:
832 	mutex_unlock(&bpf_event_mutex);
833 	return ret;
834 }
835 
836 void perf_event_detach_bpf_prog(struct perf_event *event)
837 {
838 	struct bpf_prog_array __rcu *old_array;
839 	struct bpf_prog_array *new_array;
840 	int ret;
841 
842 	mutex_lock(&bpf_event_mutex);
843 
844 	if (!event->prog)
845 		goto unlock;
846 
847 	old_array = event->tp_event->prog_array;
848 	ret = bpf_prog_array_copy(old_array, event->prog, NULL, &new_array);
849 	if (ret < 0) {
850 		bpf_prog_array_delete_safe(old_array, event->prog);
851 	} else {
852 		rcu_assign_pointer(event->tp_event->prog_array, new_array);
853 		bpf_prog_array_free(old_array);
854 	}
855 
856 	bpf_prog_put(event->prog);
857 	event->prog = NULL;
858 
859 unlock:
860 	mutex_unlock(&bpf_event_mutex);
861 }
862 
863 int perf_event_query_prog_array(struct perf_event *event, void __user *info)
864 {
865 	struct perf_event_query_bpf __user *uquery = info;
866 	struct perf_event_query_bpf query = {};
867 	int ret;
868 
869 	if (!capable(CAP_SYS_ADMIN))
870 		return -EPERM;
871 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
872 		return -EINVAL;
873 	if (copy_from_user(&query, uquery, sizeof(query)))
874 		return -EFAULT;
875 
876 	mutex_lock(&bpf_event_mutex);
877 	ret = bpf_prog_array_copy_info(event->tp_event->prog_array,
878 				       uquery->ids,
879 				       query.ids_len,
880 				       &uquery->prog_cnt);
881 	mutex_unlock(&bpf_event_mutex);
882 
883 	return ret;
884 }
885