bpf_trace.c 23.1 KB
Newer Older
1
/* Copyright (c) 2011-2015 PLUMgrid, http://plumgrid.com
2
 * Copyright (c) 2016 Facebook
3 4 5 6 7 8 9 10 11
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General Public
 * License as published by the Free Software Foundation.
 */
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/bpf.h>
12
#include <linux/bpf_perf_event.h>
13 14
#include <linux/filter.h>
#include <linux/uaccess.h>
15
#include <linux/ctype.h>
16 17 18 19
#include <linux/kprobes.h>
#include <asm/kprobes.h>

#include "trace_probe.h"
20 21
#include "trace.h"

22 23
u64 bpf_get_stackid(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);

24 25
/**
 * trace_call_bpf - invoke BPF program
26
 * @call: tracepoint event
27 28 29 30 31 32 33 34 35 36 37
 * @ctx: opaque context pointer
 *
 * kprobe handlers execute BPF programs via this helper.
 * Can be used from static tracepoints in the future.
 *
 * Return: BPF programs always return an integer which is interpreted by
 * kprobe handler as:
 * 0 - return from kprobe (event is filtered out)
 * 1 - store kprobe event into ring buffer
 * Other values are reserved and currently alias to 1
 */
38
unsigned int trace_call_bpf(struct trace_event_call *call, void *ctx)
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
{
	unsigned int ret;

	if (in_nmi()) /* not supported yet */
		return 1;

	preempt_disable();

	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) {
		/*
		 * since some bpf program is already running on this cpu,
		 * don't call into another bpf program (same or different)
		 * and don't send kprobe event into ring-buffer,
		 * so return zero here
		 */
		ret = 0;
		goto out;
	}

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
	/*
	 * Instead of moving rcu_read_lock/rcu_dereference/rcu_read_unlock
	 * to all call sites, we did a bpf_prog_array_valid() there to check
	 * whether call->prog_array is empty or not, which is
	 * a heurisitc to speed up execution.
	 *
	 * If bpf_prog_array_valid() fetched prog_array was
	 * non-NULL, we go into trace_call_bpf() and do the actual
	 * proper rcu_dereference() under RCU lock.
	 * If it turns out that prog_array is NULL then, we bail out.
	 * For the opposite, if the bpf_prog_array_valid() fetched pointer
	 * was NULL, you'll skip the prog_array with the risk of missing
	 * out of events when it was updated in between this and the
	 * rcu_dereference() which is accepted risk.
	 */
	ret = BPF_PROG_RUN_ARRAY_CHECK(call->prog_array, ctx, BPF_PROG_RUN);
74 75 76 77 78 79 80 81 82

 out:
	__this_cpu_dec(bpf_prog_active);
	preempt_enable();

	return ret;
}
EXPORT_SYMBOL_GPL(trace_call_bpf);

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
#ifdef CONFIG_BPF_KPROBE_OVERRIDE
BPF_CALL_2(bpf_override_return, struct pt_regs *, regs, unsigned long, rc)
{
	__this_cpu_write(bpf_kprobe_override, 1);
	regs_set_return_value(regs, rc);
	arch_ftrace_kprobe_override_function(regs);
	return 0;
}

static const struct bpf_func_proto bpf_override_return_proto = {
	.func		= bpf_override_return,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};
#endif

101
BPF_CALL_3(bpf_probe_read, void *, dst, u32, size, const void *, unsafe_ptr)
102
{
103
	int ret;
104

105 106 107 108 109
	ret = probe_kernel_read(dst, unsafe_ptr, size);
	if (unlikely(ret < 0))
		memset(dst, 0, size);

	return ret;
110 111 112 113 114 115
}

static const struct bpf_func_proto bpf_probe_read_proto = {
	.func		= bpf_probe_read,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
116
	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
117
	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
118 119 120
	.arg3_type	= ARG_ANYTHING,
};

121 122
BPF_CALL_3(bpf_probe_write_user, void *, unsafe_ptr, const void *, src,
	   u32, size)
123 124 125 126 127 128 129 130 131 132 133 134 135
{
	/*
	 * Ensure we're in user context which is safe for the helper to
	 * run. This helper has no business in a kthread.
	 *
	 * access_ok() should prevent writing to non-user memory, but in
	 * some situations (nommu, temporary switch, etc) access_ok() does
	 * not provide enough validation, hence the check on KERNEL_DS.
	 */

	if (unlikely(in_interrupt() ||
		     current->flags & (PF_KTHREAD | PF_EXITING)))
		return -EPERM;
A
Al Viro 已提交
136
	if (unlikely(uaccess_kernel()))
137 138 139 140 141 142 143 144 145 146 147 148
		return -EPERM;
	if (!access_ok(VERIFY_WRITE, unsafe_ptr, size))
		return -EPERM;

	return probe_kernel_write(unsafe_ptr, src, size);
}

static const struct bpf_func_proto bpf_probe_write_user_proto = {
	.func		= bpf_probe_write_user,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_ANYTHING,
149 150
	.arg2_type	= ARG_PTR_TO_MEM,
	.arg3_type	= ARG_CONST_SIZE,
151 152 153 154 155 156 157 158 159 160
};

static const struct bpf_func_proto *bpf_get_probe_write_proto(void)
{
	pr_warn_ratelimited("%s[%d] is installing a program with bpf_probe_write_user helper that may corrupt user memory!",
			    current->comm, task_pid_nr(current));

	return &bpf_probe_write_user_proto;
}

161
/*
162 163
 * Only limited trace_printk() conversion specifiers allowed:
 * %d %i %u %x %ld %li %lu %lx %lld %lli %llu %llx %p %s
164
 */
165 166
BPF_CALL_5(bpf_trace_printk, char *, fmt, u32, fmt_size, u64, arg1,
	   u64, arg2, u64, arg3)
167
{
168
	bool str_seen = false;
169 170
	int mod[3] = {};
	int fmt_cnt = 0;
171 172
	u64 unsafe_addr;
	char buf[64];
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
	int i;

	/*
	 * bpf_check()->check_func_arg()->check_stack_boundary()
	 * guarantees that fmt points to bpf program stack,
	 * fmt_size bytes of it were initialized and fmt_size > 0
	 */
	if (fmt[--fmt_size] != 0)
		return -EINVAL;

	/* check format string for allowed specifiers */
	for (i = 0; i < fmt_size; i++) {
		if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i]))
			return -EINVAL;

		if (fmt[i] != '%')
			continue;

		if (fmt_cnt >= 3)
			return -EINVAL;

		/* fmt[i] != 0 && fmt[last] == 0, so we can access fmt[i + 1] */
		i++;
		if (fmt[i] == 'l') {
			mod[fmt_cnt]++;
			i++;
199
		} else if (fmt[i] == 'p' || fmt[i] == 's') {
200 201 202 203 204
			mod[fmt_cnt]++;
			i++;
			if (!isspace(fmt[i]) && !ispunct(fmt[i]) && fmt[i] != 0)
				return -EINVAL;
			fmt_cnt++;
205 206 207 208 209 210 211 212
			if (fmt[i - 1] == 's') {
				if (str_seen)
					/* allow only one '%s' per fmt string */
					return -EINVAL;
				str_seen = true;

				switch (fmt_cnt) {
				case 1:
213 214
					unsafe_addr = arg1;
					arg1 = (long) buf;
215 216
					break;
				case 2:
217 218
					unsafe_addr = arg2;
					arg2 = (long) buf;
219 220
					break;
				case 3:
221 222
					unsafe_addr = arg3;
					arg3 = (long) buf;
223 224 225 226 227 228 229
					break;
				}
				buf[0] = 0;
				strncpy_from_unsafe(buf,
						    (void *) (long) unsafe_addr,
						    sizeof(buf));
			}
230 231 232 233 234 235 236 237
			continue;
		}

		if (fmt[i] == 'l') {
			mod[fmt_cnt]++;
			i++;
		}

238 239
		if (fmt[i] != 'i' && fmt[i] != 'd' &&
		    fmt[i] != 'u' && fmt[i] != 'x')
240 241 242 243
			return -EINVAL;
		fmt_cnt++;
	}

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
/* Horrid workaround for getting va_list handling working with different
 * argument type combinations generically for 32 and 64 bit archs.
 */
#define __BPF_TP_EMIT()	__BPF_ARG3_TP()
#define __BPF_TP(...)							\
	__trace_printk(1 /* Fake ip will not be printed. */,		\
		       fmt, ##__VA_ARGS__)

#define __BPF_ARG1_TP(...)						\
	((mod[0] == 2 || (mod[0] == 1 && __BITS_PER_LONG == 64))	\
	  ? __BPF_TP(arg1, ##__VA_ARGS__)				\
	  : ((mod[0] == 1 || (mod[0] == 0 && __BITS_PER_LONG == 32))	\
	      ? __BPF_TP((long)arg1, ##__VA_ARGS__)			\
	      : __BPF_TP((u32)arg1, ##__VA_ARGS__)))

#define __BPF_ARG2_TP(...)						\
	((mod[1] == 2 || (mod[1] == 1 && __BITS_PER_LONG == 64))	\
	  ? __BPF_ARG1_TP(arg2, ##__VA_ARGS__)				\
	  : ((mod[1] == 1 || (mod[1] == 0 && __BITS_PER_LONG == 32))	\
	      ? __BPF_ARG1_TP((long)arg2, ##__VA_ARGS__)		\
	      : __BPF_ARG1_TP((u32)arg2, ##__VA_ARGS__)))

#define __BPF_ARG3_TP(...)						\
	((mod[2] == 2 || (mod[2] == 1 && __BITS_PER_LONG == 64))	\
	  ? __BPF_ARG2_TP(arg3, ##__VA_ARGS__)				\
	  : ((mod[2] == 1 || (mod[2] == 0 && __BITS_PER_LONG == 32))	\
	      ? __BPF_ARG2_TP((long)arg3, ##__VA_ARGS__)		\
	      : __BPF_ARG2_TP((u32)arg3, ##__VA_ARGS__)))

	return __BPF_TP_EMIT();
274 275 276 277 278 279
}

static const struct bpf_func_proto bpf_trace_printk_proto = {
	.func		= bpf_trace_printk,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
280 281
	.arg1_type	= ARG_PTR_TO_MEM,
	.arg2_type	= ARG_CONST_SIZE,
282 283
};

284 285 286 287 288 289 290 291 292 293 294
const struct bpf_func_proto *bpf_get_trace_printk_proto(void)
{
	/*
	 * this program might be calling bpf_trace_printk,
	 * so allocate per-cpu printk buffers
	 */
	trace_printk_init_buffers();

	return &bpf_trace_printk_proto;
}

295 296 297
static __always_inline int
get_map_perf_counter(struct bpf_map *map, u64 flags,
		     u64 *value, u64 *enabled, u64 *running)
298 299
{
	struct bpf_array *array = container_of(map, struct bpf_array, map);
300 301
	unsigned int cpu = smp_processor_id();
	u64 index = flags & BPF_F_INDEX_MASK;
302
	struct bpf_event_entry *ee;
303

304 305 306 307
	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
		return -EINVAL;
	if (index == BPF_F_CURRENT_CPU)
		index = cpu;
308 309 310
	if (unlikely(index >= array->map.max_entries))
		return -E2BIG;

311
	ee = READ_ONCE(array->ptrs[index]);
312
	if (!ee)
313 314
		return -ENOENT;

315 316 317 318 319 320 321 322 323
	return perf_event_read_local(ee->event, value, enabled, running);
}

BPF_CALL_2(bpf_perf_event_read, struct bpf_map *, map, u64, flags)
{
	u64 value = 0;
	int err;

	err = get_map_perf_counter(map, flags, &value, NULL, NULL);
324
	/*
325 326
	 * this api is ugly since we miss [-22..-2] range of valid
	 * counter values, but that's uapi
327
	 */
328 329 330
	if (err)
		return err;
	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 337 338 339 340
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_CONST_MAP_PTR,
	.arg2_type	= ARG_ANYTHING,
};

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
BPF_CALL_4(bpf_perf_event_read_value, struct bpf_map *, map, u64, flags,
	   struct bpf_perf_event_value *, buf, u32, size)
{
	int err = -EINVAL;

	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
		goto clear;
	err = get_map_perf_counter(map, flags, &buf->counter, &buf->enabled,
				   &buf->running);
	if (unlikely(err))
		goto clear;
	return 0;
clear:
	memset(buf, 0, size);
	return err;
}

static const struct bpf_func_proto bpf_perf_event_read_value_proto = {
	.func		= bpf_perf_event_read_value,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_CONST_MAP_PTR,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg4_type	= ARG_CONST_SIZE,
};

368 369
static DEFINE_PER_CPU(struct perf_sample_data, bpf_sd);

370 371 372
static __always_inline u64
__bpf_perf_event_output(struct pt_regs *regs, struct bpf_map *map,
			u64 flags, struct perf_raw_record *raw)
373 374
{
	struct bpf_array *array = container_of(map, struct bpf_array, map);
375
	struct perf_sample_data *sd = this_cpu_ptr(&bpf_sd);
376
	unsigned int cpu = smp_processor_id();
377
	u64 index = flags & BPF_F_INDEX_MASK;
378
	struct bpf_event_entry *ee;
379 380
	struct perf_event *event;

381
	if (index == BPF_F_CURRENT_CPU)
382
		index = cpu;
383 384 385
	if (unlikely(index >= array->map.max_entries))
		return -E2BIG;

386
	ee = READ_ONCE(array->ptrs[index]);
387
	if (!ee)
388 389
		return -ENOENT;

390
	event = ee->event;
391 392 393 394
	if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
		     event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
		return -EINVAL;

395
	if (unlikely(event->oncpu != cpu))
396 397
		return -EOPNOTSUPP;

398 399 400
	perf_sample_data_init(sd, 0, 0);
	sd->raw = raw;
	perf_event_output(event, sd, regs);
401 402 403
	return 0;
}

404 405
BPF_CALL_5(bpf_perf_event_output, struct pt_regs *, regs, struct bpf_map *, map,
	   u64, flags, void *, data, u64, size)
406 407 408 409 410 411 412 413 414 415 416 417 418 419
{
	struct perf_raw_record raw = {
		.frag = {
			.size = size,
			.data = data,
		},
	};

	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
		return -EINVAL;

	return __bpf_perf_event_output(regs, map, flags, &raw);
}

420 421
static const struct bpf_func_proto bpf_perf_event_output_proto = {
	.func		= bpf_perf_event_output,
422
	.gpl_only	= true,
423 424 425 426
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_ANYTHING,
427
	.arg4_type	= ARG_PTR_TO_MEM,
428
	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
429 430
};

431 432
static DEFINE_PER_CPU(struct pt_regs, bpf_pt_regs);

433 434
u64 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)
435 436
{
	struct pt_regs *regs = this_cpu_ptr(&bpf_pt_regs);
437 438 439 440 441 442 443
	struct perf_raw_frag frag = {
		.copy		= ctx_copy,
		.size		= ctx_size,
		.data		= ctx,
	};
	struct perf_raw_record raw = {
		.frag = {
444 445 446
			{
				.next	= ctx_size ? &frag : NULL,
			},
447 448 449 450
			.size	= meta_size,
			.data	= meta,
		},
	};
451 452 453

	perf_fetch_caller_regs(regs);

454
	return __bpf_perf_event_output(regs, map, flags, &raw);
455 456
}

457
BPF_CALL_0(bpf_get_current_task)
458 459 460 461 462 463 464 465 466 467
{
	return (long) current;
}

static const struct bpf_func_proto bpf_get_current_task_proto = {
	.func		= bpf_get_current_task,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
};

468
BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
{
	struct bpf_array *array = container_of(map, struct bpf_array, map);
	struct cgroup *cgrp;

	if (unlikely(in_interrupt()))
		return -EINVAL;
	if (unlikely(idx >= array->map.max_entries))
		return -E2BIG;

	cgrp = READ_ONCE(array->ptrs[idx]);
	if (unlikely(!cgrp))
		return -EAGAIN;

	return task_under_cgroup_hierarchy(current, cgrp);
}

static const struct bpf_func_proto bpf_current_task_under_cgroup_proto = {
	.func           = bpf_current_task_under_cgroup,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_CONST_MAP_PTR,
	.arg2_type      = ARG_ANYTHING,
};

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
BPF_CALL_3(bpf_probe_read_str, void *, dst, u32, size,
	   const void *, unsafe_ptr)
{
	int ret;

	/*
	 * The strncpy_from_unsafe() call will likely not fill the entire
	 * buffer, but that's okay in this circumstance as we're probing
	 * arbitrary memory anyway similar to bpf_probe_read() and might
	 * as well probe the stack. Thus, memory is explicitly cleared
	 * only in error case, so that improper users ignoring return
	 * code altogether don't copy garbage; otherwise length of string
	 * is returned that can be used for bpf_perf_event_output() et al.
	 */
	ret = strncpy_from_unsafe(dst, unsafe_ptr, size);
	if (unlikely(ret < 0))
		memset(dst, 0, size);

	return ret;
}

static const struct bpf_func_proto bpf_probe_read_str_proto = {
	.func		= bpf_probe_read_str,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_UNINIT_MEM,
519
	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
520 521 522
	.arg3_type	= ARG_ANYTHING,
};

523
static const struct bpf_func_proto *tracing_func_proto(enum bpf_func_id func_id)
524 525 526 527 528 529 530 531 532 533
{
	switch (func_id) {
	case BPF_FUNC_map_lookup_elem:
		return &bpf_map_lookup_elem_proto;
	case BPF_FUNC_map_update_elem:
		return &bpf_map_update_elem_proto;
	case BPF_FUNC_map_delete_elem:
		return &bpf_map_delete_elem_proto;
	case BPF_FUNC_probe_read:
		return &bpf_probe_read_proto;
534 535
	case BPF_FUNC_ktime_get_ns:
		return &bpf_ktime_get_ns_proto;
536 537
	case BPF_FUNC_tail_call:
		return &bpf_tail_call_proto;
538 539
	case BPF_FUNC_get_current_pid_tgid:
		return &bpf_get_current_pid_tgid_proto;
540 541
	case BPF_FUNC_get_current_task:
		return &bpf_get_current_task_proto;
542 543 544 545
	case BPF_FUNC_get_current_uid_gid:
		return &bpf_get_current_uid_gid_proto;
	case BPF_FUNC_get_current_comm:
		return &bpf_get_current_comm_proto;
546
	case BPF_FUNC_trace_printk:
547
		return bpf_get_trace_printk_proto();
548 549
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
550 551
	case BPF_FUNC_get_numa_node_id:
		return &bpf_get_numa_node_id_proto;
552 553
	case BPF_FUNC_perf_event_read:
		return &bpf_perf_event_read_proto;
554 555
	case BPF_FUNC_probe_write_user:
		return bpf_get_probe_write_proto();
556 557
	case BPF_FUNC_current_task_under_cgroup:
		return &bpf_current_task_under_cgroup_proto;
558 559
	case BPF_FUNC_get_prandom_u32:
		return &bpf_get_prandom_u32_proto;
560 561
	case BPF_FUNC_probe_read_str:
		return &bpf_probe_read_str_proto;
562 563 564 565 566 567 568 569
	default:
		return NULL;
	}
}

static const struct bpf_func_proto *kprobe_prog_func_proto(enum bpf_func_id func_id)
{
	switch (func_id) {
570 571
	case BPF_FUNC_perf_event_output:
		return &bpf_perf_event_output_proto;
572 573
	case BPF_FUNC_get_stackid:
		return &bpf_get_stackid_proto;
574 575
	case BPF_FUNC_perf_event_read_value:
		return &bpf_perf_event_read_value_proto;
576 577 578 579
#ifdef CONFIG_BPF_KPROBE_OVERRIDE
	case BPF_FUNC_override_return:
		return &bpf_override_return_proto;
#endif
580
	default:
581
		return tracing_func_proto(func_id);
582 583 584 585
	}
}

/* bpf+kprobe programs can access fields of 'struct pt_regs' */
586
static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
587
					struct bpf_insn_access_aux *info)
588 589 590 591 592 593 594
{
	if (off < 0 || off >= sizeof(struct pt_regs))
		return false;
	if (type != BPF_READ)
		return false;
	if (off % size != 0)
		return false;
595 596 597 598 599 600 601
	/*
	 * Assertion for 32 bit to make sure last 8 byte access
	 * (BPF_DW) to the last 4 byte member is disallowed.
	 */
	if (off + size > sizeof(struct pt_regs))
		return false;

602 603 604
	return true;
}

605
const struct bpf_verifier_ops kprobe_verifier_ops = {
606 607 608 609
	.get_func_proto  = kprobe_prog_func_proto,
	.is_valid_access = kprobe_prog_is_valid_access,
};

610 611 612
const struct bpf_prog_ops kprobe_prog_ops = {
};

613 614
BPF_CALL_5(bpf_perf_event_output_tp, void *, tp_buff, struct bpf_map *, map,
	   u64, flags, void *, data, u64, size)
615
{
616 617
	struct pt_regs *regs = *(struct pt_regs **)tp_buff;

618 619 620
	/*
	 * r1 points to perf tracepoint buffer where first 8 bytes are hidden
	 * from bpf program and contain a pointer to 'struct pt_regs'. Fetch it
621
	 * from there and call the same bpf_perf_event_output() helper inline.
622
	 */
623
	return ____bpf_perf_event_output(regs, map, flags, data, size);
624 625 626 627 628 629 630 631 632
}

static const struct bpf_func_proto bpf_perf_event_output_proto_tp = {
	.func		= bpf_perf_event_output_tp,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_ANYTHING,
633
	.arg4_type	= ARG_PTR_TO_MEM,
634
	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
635 636
};

637 638
BPF_CALL_3(bpf_get_stackid_tp, void *, tp_buff, struct bpf_map *, map,
	   u64, flags)
639
{
640
	struct pt_regs *regs = *(struct pt_regs **)tp_buff;
641

642 643 644 645 646 647 648
	/*
	 * Same comment as in bpf_perf_event_output_tp(), only that this time
	 * the other helper's function body cannot be inlined due to being
	 * external, thus we need to call raw helper function.
	 */
	return bpf_get_stackid((unsigned long) regs, (unsigned long) map,
			       flags, 0, 0);
649 650 651 652 653 654 655 656 657 658 659
}

static const struct bpf_func_proto bpf_get_stackid_proto_tp = {
	.func		= bpf_get_stackid_tp,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_ANYTHING,
};

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
BPF_CALL_3(bpf_perf_prog_read_value_tp, struct bpf_perf_event_data_kern *, ctx,
	   struct bpf_perf_event_value *, buf, u32, size)
{
	int err = -EINVAL;

	if (unlikely(size != sizeof(struct bpf_perf_event_value)))
		goto clear;
	err = perf_event_read_local(ctx->event, &buf->counter, &buf->enabled,
				    &buf->running);
	if (unlikely(err))
		goto clear;
	return 0;
clear:
	memset(buf, 0, size);
	return err;
}

static const struct bpf_func_proto bpf_perf_prog_read_value_proto_tp = {
         .func           = bpf_perf_prog_read_value_tp,
         .gpl_only       = true,
         .ret_type       = RET_INTEGER,
         .arg1_type      = ARG_PTR_TO_CTX,
         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
         .arg3_type      = ARG_CONST_SIZE,
};

686 687 688 689
static const struct bpf_func_proto *tp_prog_func_proto(enum bpf_func_id func_id)
{
	switch (func_id) {
	case BPF_FUNC_perf_event_output:
690
		return &bpf_perf_event_output_proto_tp;
691
	case BPF_FUNC_get_stackid:
692
		return &bpf_get_stackid_proto_tp;
693 694
	case BPF_FUNC_perf_prog_read_value:
		return &bpf_perf_prog_read_value_proto_tp;
695 696 697 698 699
	default:
		return tracing_func_proto(func_id);
	}
}

700
static bool tp_prog_is_valid_access(int off, int size, enum bpf_access_type type,
701
				    struct bpf_insn_access_aux *info)
702 703 704 705 706 707 708
{
	if (off < sizeof(void *) || off >= PERF_MAX_TRACE_SIZE)
		return false;
	if (type != BPF_READ)
		return false;
	if (off % size != 0)
		return false;
709 710

	BUILD_BUG_ON(PERF_MAX_TRACE_SIZE % sizeof(__u64));
711 712 713
	return true;
}

714
const struct bpf_verifier_ops tracepoint_verifier_ops = {
715 716 717 718
	.get_func_proto  = tp_prog_func_proto,
	.is_valid_access = tp_prog_is_valid_access,
};

719 720 721
const struct bpf_prog_ops tracepoint_prog_ops = {
};

722
static bool pe_prog_is_valid_access(int off, int size, enum bpf_access_type type,
723
				    struct bpf_insn_access_aux *info)
724
{
725 726
	const int size_sp = FIELD_SIZEOF(struct bpf_perf_event_data,
					 sample_period);
727

728 729 730 731 732 733
	if (off < 0 || off >= sizeof(struct bpf_perf_event_data))
		return false;
	if (type != BPF_READ)
		return false;
	if (off % size != 0)
		return false;
734

735 736 737 738
	switch (off) {
	case bpf_ctx_range(struct bpf_perf_event_data, sample_period):
		bpf_ctx_record_field_size(info, size_sp);
		if (!bpf_ctx_narrow_access_ok(off, size, size_sp))
739
			return false;
740 741
		break;
	default:
742 743 744
		if (size != sizeof(long))
			return false;
	}
745

746 747 748
	return true;
}

749 750
static u32 pe_prog_convert_ctx_access(enum bpf_access_type type,
				      const struct bpf_insn *si,
751
				      struct bpf_insn *insn_buf,
752
				      struct bpf_prog *prog, u32 *target_size)
753 754 755
{
	struct bpf_insn *insn = insn_buf;

756
	switch (si->off) {
757
	case offsetof(struct bpf_perf_event_data, sample_period):
758
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
759
						       data), si->dst_reg, si->src_reg,
760
				      offsetof(struct bpf_perf_event_data_kern, data));
761
		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
762 763
				      bpf_target_off(struct perf_sample_data, period, 8,
						     target_size));
764 765
		break;
	default:
766
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_perf_event_data_kern,
767
						       regs), si->dst_reg, si->src_reg,
768
				      offsetof(struct bpf_perf_event_data_kern, regs));
769 770
		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(long), si->dst_reg, si->dst_reg,
				      si->off);
771 772 773 774 775 776
		break;
	}

	return insn - insn_buf;
}

777
const struct bpf_verifier_ops perf_event_verifier_ops = {
778 779 780 781
	.get_func_proto		= tp_prog_func_proto,
	.is_valid_access	= pe_prog_is_valid_access,
	.convert_ctx_access	= pe_prog_convert_ctx_access,
};
782 783 784

const struct bpf_prog_ops perf_event_prog_ops = {
};
785 786 787

static DEFINE_MUTEX(bpf_event_mutex);

788 789
#define BPF_TRACE_MAX_PROGS 64

790 791 792 793 794 795 796
int perf_event_attach_bpf_prog(struct perf_event *event,
			       struct bpf_prog *prog)
{
	struct bpf_prog_array __rcu *old_array;
	struct bpf_prog_array *new_array;
	int ret = -EEXIST;

797 798 799 800 801 802 803 804 805
	/*
	 * Kprobe override only works for ftrace based kprobes, and only if they
	 * are on the opt-in list.
	 */
	if (prog->kprobe_override &&
	    (!trace_kprobe_ftrace(event->tp_event) ||
	     !trace_kprobe_error_injectable(event->tp_event)))
		return -EINVAL;

806 807 808
	mutex_lock(&bpf_event_mutex);

	if (event->prog)
809
		goto unlock;
810

811
	old_array = event->tp_event->prog_array;
812 813 814 815 816 817
	if (old_array &&
	    bpf_prog_array_length(old_array) >= BPF_TRACE_MAX_PROGS) {
		ret = -E2BIG;
		goto unlock;
	}

818 819
	ret = bpf_prog_array_copy(old_array, NULL, prog, &new_array);
	if (ret < 0)
820
		goto unlock;
821 822 823 824 825 826

	/* set the new array to event->tp_event and set event->prog */
	event->prog = prog;
	rcu_assign_pointer(event->tp_event->prog_array, new_array);
	bpf_prog_array_free(old_array);

827
unlock:
828 829 830 831 832 833 834 835 836 837 838 839 840
	mutex_unlock(&bpf_event_mutex);
	return ret;
}

void perf_event_detach_bpf_prog(struct perf_event *event)
{
	struct bpf_prog_array __rcu *old_array;
	struct bpf_prog_array *new_array;
	int ret;

	mutex_lock(&bpf_event_mutex);

	if (!event->prog)
841
		goto unlock;
842

843
	old_array = event->tp_event->prog_array;
844 845 846 847 848 849 850 851 852 853 854
	ret = bpf_prog_array_copy(old_array, event->prog, NULL, &new_array);
	if (ret < 0) {
		bpf_prog_array_delete_safe(old_array, event->prog);
	} else {
		rcu_assign_pointer(event->tp_event->prog_array, new_array);
		bpf_prog_array_free(old_array);
	}

	bpf_prog_put(event->prog);
	event->prog = NULL;

855
unlock:
856 857
	mutex_unlock(&bpf_event_mutex);
}
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880

int bpf_event_query_prog_array(struct perf_event *event, void __user *info)
{
	struct perf_event_query_bpf __user *uquery = info;
	struct perf_event_query_bpf query = {};
	int ret;

	if (!capable(CAP_SYS_ADMIN))
		return -EPERM;
	if (event->attr.type != PERF_TYPE_TRACEPOINT)
		return -EINVAL;
	if (copy_from_user(&query, uquery, sizeof(query)))
		return -EFAULT;

	mutex_lock(&bpf_event_mutex);
	ret = bpf_prog_array_copy_info(event->tp_event->prog_array,
				       uquery->ids,
				       query.ids_len,
				       &uquery->prog_cnt);
	mutex_unlock(&bpf_event_mutex);

	return ret;
}