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