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