bpf-loader.c 39.8 KB
Newer Older
W
Wang Nan 已提交
1 2 3 4 5 6 7
/*
 * bpf-loader.c
 *
 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
 * Copyright (C) 2015 Huawei Inc.
 */

8
#include <linux/bpf.h>
W
Wang Nan 已提交
9
#include <bpf/libbpf.h>
10
#include <bpf/bpf.h>
W
Wang Nan 已提交
11
#include <linux/err.h>
12
#include <linux/string.h>
W
Wang Nan 已提交
13 14 15
#include "perf.h"
#include "debug.h"
#include "bpf-loader.h"
16
#include "bpf-prologue.h"
17 18
#include "probe-event.h"
#include "probe-finder.h" // for MAX_PROBES
19
#include "parse-events.h"
20
#include "llvm-utils.h"
21
#include "c++/clang-c.h"
W
Wang Nan 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34

#define DEFINE_PRINT_FN(name, level) \
static int libbpf_##name(const char *fmt, ...)	\
{						\
	va_list args;				\
	int ret;				\
						\
	va_start(args, fmt);			\
	ret = veprintf(level, verbose, pr_fmt(fmt), args);\
	va_end(args);				\
	return ret;				\
}

W
Wang Nan 已提交
35 36
DEFINE_PRINT_FN(warning, 1)
DEFINE_PRINT_FN(info, 1)
W
Wang Nan 已提交
37 38
DEFINE_PRINT_FN(debug, 1)

39
struct bpf_prog_priv {
40 41 42
	bool is_tp;
	char *sys_name;
	char *evt_name;
43
	struct perf_probe_event pev;
44 45
	bool need_prologue;
	struct bpf_insn *insns_buf;
46 47
	int nr_types;
	int *type_mapping;
48 49
};

W
Wang Nan 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
static bool libbpf_initialized;

struct bpf_object *
bpf__prepare_load_buffer(void *obj_buf, size_t obj_buf_sz, const char *name)
{
	struct bpf_object *obj;

	if (!libbpf_initialized) {
		libbpf_set_print(libbpf_warning,
				 libbpf_info,
				 libbpf_debug);
		libbpf_initialized = true;
	}

	obj = bpf_object__open_buffer(obj_buf, obj_buf_sz, name);
	if (IS_ERR(obj)) {
		pr_debug("bpf: failed to load buffer\n");
		return ERR_PTR(-EINVAL);
	}

	return obj;
}

73
struct bpf_object *bpf__prepare_load(const char *filename, bool source)
W
Wang Nan 已提交
74 75 76 77 78 79 80 81 82 83
{
	struct bpf_object *obj;

	if (!libbpf_initialized) {
		libbpf_set_print(libbpf_warning,
				 libbpf_info,
				 libbpf_debug);
		libbpf_initialized = true;
	}

84 85 86 87 88
	if (source) {
		int err;
		void *obj_buf;
		size_t obj_buf_sz;

89 90 91 92 93 94 95 96 97 98
		perf_clang__init();
		err = perf_clang__compile_bpf(filename, &obj_buf, &obj_buf_sz);
		perf_clang__cleanup();
		if (err) {
			pr_warning("bpf: builtin compilation failed: %d, try external compiler\n", err);
			err = llvm__compile_bpf(filename, &obj_buf, &obj_buf_sz);
			if (err)
				return ERR_PTR(-BPF_LOADER_ERRNO__COMPILE);
		} else
			pr_debug("bpf: successfull builtin compilation\n");
99
		obj = bpf_object__open_buffer(obj_buf, obj_buf_sz, filename);
100 101 102 103

		if (!IS_ERR(obj) && llvm_param.dump_obj)
			llvm__dump_obj(filename, obj_buf, obj_buf_sz);

104 105 106 107
		free(obj_buf);
	} else
		obj = bpf_object__open(filename);

108
	if (IS_ERR(obj)) {
W
Wang Nan 已提交
109
		pr_debug("bpf: failed to load %s\n", filename);
110
		return obj;
W
Wang Nan 已提交
111 112 113 114 115 116 117 118 119
	}

	return obj;
}

void bpf__clear(void)
{
	struct bpf_object *obj, *tmp;

120 121
	bpf_object__for_each_safe(obj, tmp) {
		bpf__unprobe(obj);
W
Wang Nan 已提交
122
		bpf_object__close(obj);
123 124 125 126
	}
}

static void
127 128
clear_prog_priv(struct bpf_program *prog __maybe_unused,
		void *_priv)
129 130 131 132
{
	struct bpf_prog_priv *priv = _priv;

	cleanup_perf_probe_events(&priv->pev, 1);
133
	zfree(&priv->insns_buf);
134
	zfree(&priv->type_mapping);
135 136
	zfree(&priv->sys_name);
	zfree(&priv->evt_name);
137 138 139
	free(priv);
}

140
static int
141
prog_config__exec(const char *value, struct perf_probe_event *pev)
142 143 144 145 146 147 148 149
{
	pev->uprobes = true;
	pev->target = strdup(value);
	if (!pev->target)
		return -ENOMEM;
	return 0;
}

150
static int
151
prog_config__module(const char *value, struct perf_probe_event *pev)
152 153 154 155 156 157 158 159
{
	pev->uprobes = false;
	pev->target = strdup(value);
	if (!pev->target)
		return -ENOMEM;
	return 0;
}

160
static int
161
prog_config__bool(const char *value, bool *pbool, bool invert)
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
{
	int err;
	bool bool_value;

	if (!pbool)
		return -EINVAL;

	err = strtobool(value, &bool_value);
	if (err)
		return err;

	*pbool = invert ? !bool_value : bool_value;
	return 0;
}

static int
178 179
prog_config__inlines(const char *value,
		     struct perf_probe_event *pev __maybe_unused)
180
{
181
	return prog_config__bool(value, &probe_conf.no_inlines, true);
182 183 184
}

static int
185 186
prog_config__force(const char *value,
		   struct perf_probe_event *pev __maybe_unused)
187
{
188
	return prog_config__bool(value, &probe_conf.force_add, false);
189 190
}

191 192 193 194 195
static struct {
	const char *key;
	const char *usage;
	const char *desc;
	int (*func)(const char *, struct perf_probe_event *);
196
} bpf_prog_config_terms[] = {
197 198 199 200
	{
		.key	= "exec",
		.usage	= "exec=<full path of file>",
		.desc	= "Set uprobe target",
201
		.func	= prog_config__exec,
202
	},
203 204 205 206
	{
		.key	= "module",
		.usage	= "module=<module name>    ",
		.desc	= "Set kprobe module",
207
		.func	= prog_config__module,
208 209 210 211 212
	},
	{
		.key	= "inlines",
		.usage	= "inlines=[yes|no]        ",
		.desc	= "Probe at inline symbol",
213
		.func	= prog_config__inlines,
214 215 216 217 218
	},
	{
		.key	= "force",
		.usage	= "force=[yes|no]          ",
		.desc	= "Forcibly add events with existing name",
219
		.func	= prog_config__force,
220
	},
221 222 223
};

static int
224 225
do_prog_config(const char *key, const char *value,
	       struct perf_probe_event *pev)
226 227 228 229
{
	unsigned int i;

	pr_debug("config bpf program: %s=%s\n", key, value);
230 231 232
	for (i = 0; i < ARRAY_SIZE(bpf_prog_config_terms); i++)
		if (strcmp(key, bpf_prog_config_terms[i].key) == 0)
			return bpf_prog_config_terms[i].func(value, pev);
233

234
	pr_debug("BPF: ERROR: invalid program config option: %s=%s\n",
235 236
		 key, value);

237 238 239 240
	pr_debug("\nHint: Valid options are:\n");
	for (i = 0; i < ARRAY_SIZE(bpf_prog_config_terms); i++)
		pr_debug("\t%s:\t%s\n", bpf_prog_config_terms[i].usage,
			 bpf_prog_config_terms[i].desc);
241 242
	pr_debug("\n");

243
	return -BPF_LOADER_ERRNO__PROGCONF_TERM;
244 245 246
}

static const char *
247
parse_prog_config_kvpair(const char *config_str, struct perf_probe_event *pev)
248 249 250 251 252 253 254
{
	char *text = strdup(config_str);
	char *sep, *line;
	const char *main_str = NULL;
	int err = 0;

	if (!text) {
255
		pr_debug("Not enough memory: dup config_str failed\n");
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
		return ERR_PTR(-ENOMEM);
	}

	line = text;
	while ((sep = strchr(line, ';'))) {
		char *equ;

		*sep = '\0';
		equ = strchr(line, '=');
		if (!equ) {
			pr_warning("WARNING: invalid config in BPF object: %s\n",
				   line);
			pr_warning("\tShould be 'key=value'.\n");
			goto nextline;
		}
		*equ = '\0';

273
		err = do_prog_config(line, equ + 1, pev);
274 275 276 277 278 279 280 281 282 283 284 285 286 287
		if (err)
			break;
nextline:
		line = sep + 1;
	}

	if (!err)
		main_str = config_str + (line - text);
	free(text);

	return err ? ERR_PTR(err) : main_str;
}

static int
288 289
parse_prog_config(const char *config_str, const char **p_main_str,
		  bool *is_tp, struct perf_probe_event *pev)
290 291
{
	int err;
292
	const char *main_str = parse_prog_config_kvpair(config_str, pev);
293 294 295 296

	if (IS_ERR(main_str))
		return PTR_ERR(main_str);

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
	*p_main_str = main_str;
	if (!strchr(main_str, '=')) {
		/* Is a tracepoint event? */
		const char *s = strchr(main_str, ':');

		if (!s) {
			pr_debug("bpf: '%s' is not a valid tracepoint\n",
				 config_str);
			return -BPF_LOADER_ERRNO__CONFIG;
		}

		*is_tp = true;
		return 0;
	}

	*is_tp = false;
313 314 315 316 317 318 319 320 321 322
	err = parse_perf_probe_command(main_str, pev);
	if (err < 0) {
		pr_debug("bpf: '%s' is not a valid config string\n",
			 config_str);
		/* parse failed, don't need clear pev. */
		return -BPF_LOADER_ERRNO__CONFIG;
	}
	return 0;
}

323 324 325 326 327
static int
config_bpf_program(struct bpf_program *prog)
{
	struct perf_probe_event *pev = NULL;
	struct bpf_prog_priv *priv = NULL;
328 329
	const char *config_str, *main_str;
	bool is_tp = false;
330 331
	int err;

332 333 334 335
	/* Initialize per-program probing setting */
	probe_conf.no_inlines = false;
	probe_conf.force_add = false;

336
	config_str = bpf_program__title(prog, false);
337
	if (IS_ERR(config_str)) {
338
		pr_debug("bpf: unable to get title for program\n");
339
		return PTR_ERR(config_str);
340 341 342 343 344 345 346 347 348 349
	}

	priv = calloc(sizeof(*priv), 1);
	if (!priv) {
		pr_debug("bpf: failed to alloc priv\n");
		return -ENOMEM;
	}
	pev = &priv->pev;

	pr_debug("bpf: config program '%s'\n", config_str);
350
	err = parse_prog_config(config_str, &main_str, &is_tp, pev);
351
	if (err)
352 353
		goto errout;

354 355 356 357 358 359 360 361 362
	if (is_tp) {
		char *s = strchr(main_str, ':');

		priv->is_tp = true;
		priv->sys_name = strndup(main_str, s - main_str);
		priv->evt_name = strdup(s + 1);
		goto set_priv;
	}

363 364 365
	if (pev->group && strcmp(pev->group, PERF_BPF_PROBE_GROUP)) {
		pr_debug("bpf: '%s': group for event is set and not '%s'.\n",
			 config_str, PERF_BPF_PROBE_GROUP);
366
		err = -BPF_LOADER_ERRNO__GROUP;
367 368 369 370 371 372 373 374 375 376 377
		goto errout;
	} else if (!pev->group)
		pev->group = strdup(PERF_BPF_PROBE_GROUP);

	if (!pev->group) {
		pr_debug("bpf: strdup failed\n");
		err = -ENOMEM;
		goto errout;
	}

	if (!pev->event) {
378
		pr_debug("bpf: '%s': event name is missing. Section name should be 'key=value'\n",
379
			 config_str);
380
		err = -BPF_LOADER_ERRNO__EVENTNAME;
381 382 383 384
		goto errout;
	}
	pr_debug("bpf: config '%s' is ok\n", config_str);

385
set_priv:
386
	err = bpf_program__set_priv(prog, priv, clear_prog_priv);
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
	if (err) {
		pr_debug("Failed to set priv for program '%s'\n", config_str);
		goto errout;
	}

	return 0;

errout:
	if (pev)
		clear_perf_probe_event(pev);
	free(priv);
	return err;
}

static int bpf__prepare_probe(void)
{
	static int err = 0;
	static bool initialized = false;

	/*
	 * Make err static, so if init failed the first, bpf__prepare_probe()
	 * fails each time without calling init_probe_symbol_maps multiple
	 * times.
	 */
	if (initialized)
		return err;

	initialized = true;
	err = init_probe_symbol_maps(false);
	if (err < 0)
		pr_debug("Failed to init_probe_symbol_maps\n");
	probe_conf.max_probes = MAX_PROBES;
	return err;
}

422 423 424 425 426
static int
preproc_gen_prologue(struct bpf_program *prog, int n,
		     struct bpf_insn *orig_insns, int orig_insns_cnt,
		     struct bpf_prog_prep_result *res)
{
427
	struct bpf_prog_priv *priv = bpf_program__priv(prog);
428 429 430 431
	struct probe_trace_event *tev;
	struct perf_probe_event *pev;
	struct bpf_insn *buf;
	size_t prologue_cnt = 0;
432
	int i, err;
433

434
	if (IS_ERR(priv) || !priv || priv->is_tp)
435 436 437 438
		goto errout;

	pev = &priv->pev;

439
	if (n < 0 || n >= priv->nr_types)
440 441
		goto errout;

442 443 444 445 446 447 448 449 450 451 452 453
	/* Find a tev belongs to that type */
	for (i = 0; i < pev->ntevs; i++) {
		if (priv->type_mapping[i] == n)
			break;
	}

	if (i >= pev->ntevs) {
		pr_debug("Internal error: prologue type %d not found\n", n);
		return -BPF_LOADER_ERRNO__PROLOGUE;
	}

	tev = &pev->tevs[i];
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483

	buf = priv->insns_buf;
	err = bpf__gen_prologue(tev->args, tev->nargs,
				buf, &prologue_cnt,
				BPF_MAXINSNS - orig_insns_cnt);
	if (err) {
		const char *title;

		title = bpf_program__title(prog, false);
		if (!title)
			title = "[unknown]";

		pr_debug("Failed to generate prologue for program %s\n",
			 title);
		return err;
	}

	memcpy(&buf[prologue_cnt], orig_insns,
	       sizeof(struct bpf_insn) * orig_insns_cnt);

	res->new_insn_ptr = buf;
	res->new_insn_cnt = prologue_cnt + orig_insns_cnt;
	res->pfd = NULL;
	return 0;

errout:
	pr_debug("Internal error in preproc_gen_prologue\n");
	return -BPF_LOADER_ERRNO__PROLOGUE;
}

484 485 486 487 488 489 490 491 492 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 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
/*
 * compare_tev_args is reflexive, transitive and antisymmetric.
 * I can proof it but this margin is too narrow to contain.
 */
static int compare_tev_args(const void *ptev1, const void *ptev2)
{
	int i, ret;
	const struct probe_trace_event *tev1 =
		*(const struct probe_trace_event **)ptev1;
	const struct probe_trace_event *tev2 =
		*(const struct probe_trace_event **)ptev2;

	ret = tev2->nargs - tev1->nargs;
	if (ret)
		return ret;

	for (i = 0; i < tev1->nargs; i++) {
		struct probe_trace_arg *arg1, *arg2;
		struct probe_trace_arg_ref *ref1, *ref2;

		arg1 = &tev1->args[i];
		arg2 = &tev2->args[i];

		ret = strcmp(arg1->value, arg2->value);
		if (ret)
			return ret;

		ref1 = arg1->ref;
		ref2 = arg2->ref;

		while (ref1 && ref2) {
			ret = ref2->offset - ref1->offset;
			if (ret)
				return ret;

			ref1 = ref1->next;
			ref2 = ref2->next;
		}

		if (ref1 || ref2)
			return ref2 ? 1 : -1;
	}

	return 0;
}

/*
 * Assign a type number to each tevs in a pev.
 * mapping is an array with same slots as tevs in that pev.
 * nr_types will be set to number of types.
 */
static int map_prologue(struct perf_probe_event *pev, int *mapping,
			int *nr_types)
{
	int i, type = 0;
	struct probe_trace_event **ptevs;

	size_t array_sz = sizeof(*ptevs) * pev->ntevs;

	ptevs = malloc(array_sz);
	if (!ptevs) {
545
		pr_debug("Not enough memory: alloc ptevs failed\n");
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
		return -ENOMEM;
	}

	pr_debug("In map_prologue, ntevs=%d\n", pev->ntevs);
	for (i = 0; i < pev->ntevs; i++)
		ptevs[i] = &pev->tevs[i];

	qsort(ptevs, pev->ntevs, sizeof(*ptevs),
	      compare_tev_args);

	for (i = 0; i < pev->ntevs; i++) {
		int n;

		n = ptevs[i] - pev->tevs;
		if (i == 0) {
			mapping[n] = type;
			pr_debug("mapping[%d]=%d\n", n, type);
			continue;
		}

		if (compare_tev_args(ptevs + i, ptevs + i - 1) == 0)
			mapping[n] = type;
		else
			mapping[n] = ++type;

		pr_debug("mapping[%d]=%d\n", n, mapping[n]);
	}
	free(ptevs);
	*nr_types = type + 1;

	return 0;
}

579 580
static int hook_load_preprocessor(struct bpf_program *prog)
{
581
	struct bpf_prog_priv *priv = bpf_program__priv(prog);
582 583 584 585
	struct perf_probe_event *pev;
	bool need_prologue = false;
	int err, i;

586
	if (IS_ERR(priv) || !priv) {
587 588 589 590
		pr_debug("Internal error when hook preprocessor\n");
		return -BPF_LOADER_ERRNO__INTERNAL;
	}

591 592 593 594 595
	if (priv->is_tp) {
		priv->need_prologue = false;
		return 0;
	}

596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
	pev = &priv->pev;
	for (i = 0; i < pev->ntevs; i++) {
		struct probe_trace_event *tev = &pev->tevs[i];

		if (tev->nargs > 0) {
			need_prologue = true;
			break;
		}
	}

	/*
	 * Since all tevs don't have argument, we don't need generate
	 * prologue.
	 */
	if (!need_prologue) {
		priv->need_prologue = false;
		return 0;
	}

	priv->need_prologue = true;
	priv->insns_buf = malloc(sizeof(struct bpf_insn) * BPF_MAXINSNS);
	if (!priv->insns_buf) {
618
		pr_debug("Not enough memory: alloc insns_buf failed\n");
619 620 621
		return -ENOMEM;
	}

622 623
	priv->type_mapping = malloc(sizeof(int) * pev->ntevs);
	if (!priv->type_mapping) {
624
		pr_debug("Not enough memory: alloc type_mapping failed\n");
625 626 627 628 629 630 631 632 633 634
		return -ENOMEM;
	}
	memset(priv->type_mapping, -1,
	       sizeof(int) * pev->ntevs);

	err = map_prologue(pev, priv->type_mapping, &priv->nr_types);
	if (err)
		return err;

	err = bpf_program__set_prep(prog, priv->nr_types,
635 636 637 638
				    preproc_gen_prologue);
	return err;
}

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
int bpf__probe(struct bpf_object *obj)
{
	int err = 0;
	struct bpf_program *prog;
	struct bpf_prog_priv *priv;
	struct perf_probe_event *pev;

	err = bpf__prepare_probe();
	if (err) {
		pr_debug("bpf__prepare_probe failed\n");
		return err;
	}

	bpf_object__for_each_program(prog, obj) {
		err = config_bpf_program(prog);
		if (err)
			goto out;

657 658 659
		priv = bpf_program__priv(prog);
		if (IS_ERR(priv) || !priv) {
			err = PTR_ERR(priv);
660
			goto out;
661
		}
662 663 664 665 666 667 668

		if (priv->is_tp) {
			bpf_program__set_tracepoint(prog);
			continue;
		}

		bpf_program__set_kprobe(prog);
669 670 671 672
		pev = &priv->pev;

		err = convert_perf_probe_events(pev, 1);
		if (err < 0) {
673
			pr_debug("bpf_probe: failed to convert perf probe events\n");
674 675 676 677 678
			goto out;
		}

		err = apply_perf_probe_events(pev, 1);
		if (err < 0) {
679
			pr_debug("bpf_probe: failed to apply perf probe events\n");
680 681
			goto out;
		}
682 683 684 685 686 687 688 689 690 691 692 693

		/*
		 * After probing, let's consider prologue, which
		 * adds program fetcher to BPF programs.
		 *
		 * hook_load_preprocessorr() hooks pre-processor
		 * to bpf_program, let it generate prologue
		 * dynamically during loading.
		 */
		err = hook_load_preprocessor(prog);
		if (err)
			goto out;
694 695 696 697 698 699 700 701 702 703 704 705
	}
out:
	return err < 0 ? err : 0;
}

#define EVENTS_WRITE_BUFSIZE  4096
int bpf__unprobe(struct bpf_object *obj)
{
	int err, ret = 0;
	struct bpf_program *prog;

	bpf_object__for_each_program(prog, obj) {
706
		struct bpf_prog_priv *priv = bpf_program__priv(prog);
707 708
		int i;

709
		if (IS_ERR(priv) || !priv || priv->is_tp)
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
			continue;

		for (i = 0; i < priv->pev.ntevs; i++) {
			struct probe_trace_event *tev = &priv->pev.tevs[i];
			char name_buf[EVENTS_WRITE_BUFSIZE];
			struct strfilter *delfilter;

			snprintf(name_buf, EVENTS_WRITE_BUFSIZE,
				 "%s:%s", tev->group, tev->event);
			name_buf[EVENTS_WRITE_BUFSIZE - 1] = '\0';

			delfilter = strfilter__new(name_buf, NULL);
			if (!delfilter) {
				pr_debug("Failed to create filter for unprobing\n");
				ret = -ENOMEM;
				continue;
			}

			err = del_perf_probe_events(delfilter);
			strfilter__delete(delfilter);
			if (err) {
				pr_debug("Failed to delete %s\n", name_buf);
				ret = err;
				continue;
			}
		}
	}
	return ret;
}

740 741 742 743 744 745 746 747 748 749 750 751
int bpf__load(struct bpf_object *obj)
{
	int err;

	err = bpf_object__load(obj);
	if (err) {
		pr_debug("bpf: load objects failed\n");
		return err;
	}
	return 0;
}

752 753 754
int bpf__foreach_event(struct bpf_object *obj,
		       bpf_prog_iter_callback_t func,
		       void *arg)
755 756 757 758 759
{
	struct bpf_program *prog;
	int err;

	bpf_object__for_each_program(prog, obj) {
760
		struct bpf_prog_priv *priv = bpf_program__priv(prog);
761 762 763 764
		struct probe_trace_event *tev;
		struct perf_probe_event *pev;
		int i, fd;

765
		if (IS_ERR(priv) || !priv) {
766
			pr_debug("bpf: failed to get private field\n");
767
			return -BPF_LOADER_ERRNO__INTERNAL;
768 769
		}

770 771 772 773 774 775 776 777 778 779
		if (priv->is_tp) {
			fd = bpf_program__fd(prog);
			err = (*func)(priv->sys_name, priv->evt_name, fd, arg);
			if (err) {
				pr_debug("bpf: tracepoint call back failed, stop iterate\n");
				return err;
			}
			continue;
		}

780 781 782 783
		pev = &priv->pev;
		for (i = 0; i < pev->ntevs; i++) {
			tev = &pev->tevs[i];

784 785 786 787 788
			if (priv->need_prologue) {
				int type = priv->type_mapping[i];

				fd = bpf_program__nth_fd(prog, type);
			} else {
789
				fd = bpf_program__fd(prog);
790
			}
791

792 793 794 795 796
			if (fd < 0) {
				pr_debug("bpf: failed to get file descriptor\n");
				return fd;
			}

797
			err = (*func)(tev->group, tev->event, fd, arg);
798 799 800 801 802 803 804 805 806
			if (err) {
				pr_debug("bpf: call back failed, stop iterate\n");
				return err;
			}
		}
	}
	return 0;
}

807 808
enum bpf_map_op_type {
	BPF_MAP_OP_SET_VALUE,
809
	BPF_MAP_OP_SET_EVSEL,
810 811 812 813
};

enum bpf_map_key_type {
	BPF_MAP_KEY_ALL,
814
	BPF_MAP_KEY_RANGES,
815 816 817 818 819 820
};

struct bpf_map_op {
	struct list_head list;
	enum bpf_map_op_type op_type;
	enum bpf_map_key_type key_type;
821 822 823
	union {
		struct parse_events_array array;
	} k;
824 825
	union {
		u64 value;
826
		struct perf_evsel *evsel;
827 828 829 830 831 832 833 834 835 836 837 838
	} v;
};

struct bpf_map_priv {
	struct list_head ops_list;
};

static void
bpf_map_op__delete(struct bpf_map_op *op)
{
	if (!list_empty(&op->list))
		list_del(&op->list);
839 840
	if (op->key_type == BPF_MAP_KEY_RANGES)
		parse_events__clear_array(&op->k.array);
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
	free(op);
}

static void
bpf_map_priv__purge(struct bpf_map_priv *priv)
{
	struct bpf_map_op *pos, *n;

	list_for_each_entry_safe(pos, n, &priv->ops_list, list) {
		list_del_init(&pos->list);
		bpf_map_op__delete(pos);
	}
}

static void
bpf_map_priv__clear(struct bpf_map *map __maybe_unused,
		    void *_priv)
{
	struct bpf_map_priv *priv = _priv;

	bpf_map_priv__purge(priv);
	free(priv);
}

865 866 867 868 869 870 871 872 873 874 875 876 877
static int
bpf_map_op_setkey(struct bpf_map_op *op, struct parse_events_term *term)
{
	op->key_type = BPF_MAP_KEY_ALL;
	if (!term)
		return 0;

	if (term->array.nr_ranges) {
		size_t memsz = term->array.nr_ranges *
				sizeof(op->k.array.ranges[0]);

		op->k.array.ranges = memdup(term->array.ranges, memsz);
		if (!op->k.array.ranges) {
878
			pr_debug("Not enough memory to alloc indices for map\n");
879 880 881 882 883 884 885 886
			return -ENOMEM;
		}
		op->key_type = BPF_MAP_KEY_RANGES;
		op->k.array.nr_ranges = term->array.nr_ranges;
	}
	return 0;
}

887
static struct bpf_map_op *
888
bpf_map_op__new(struct parse_events_term *term)
889 890
{
	struct bpf_map_op *op;
891
	int err;
892 893 894 895 896 897 898 899

	op = zalloc(sizeof(*op));
	if (!op) {
		pr_debug("Failed to alloc bpf_map_op\n");
		return ERR_PTR(-ENOMEM);
	}
	INIT_LIST_HEAD(&op->list);

900 901 902 903 904
	err = bpf_map_op_setkey(op, term);
	if (err) {
		free(op);
		return ERR_PTR(err);
	}
905 906 907
	return op;
}

908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
static struct bpf_map_op *
bpf_map_op__clone(struct bpf_map_op *op)
{
	struct bpf_map_op *newop;

	newop = memdup(op, sizeof(*op));
	if (!newop) {
		pr_debug("Failed to alloc bpf_map_op\n");
		return NULL;
	}

	INIT_LIST_HEAD(&newop->list);
	if (op->key_type == BPF_MAP_KEY_RANGES) {
		size_t memsz = op->k.array.nr_ranges *
			       sizeof(op->k.array.ranges[0]);

		newop->k.array.ranges = memdup(op->k.array.ranges, memsz);
		if (!newop->k.array.ranges) {
			pr_debug("Failed to alloc indices for map\n");
			free(newop);
			return NULL;
		}
	}

	return newop;
}

static struct bpf_map_priv *
bpf_map_priv__clone(struct bpf_map_priv *priv)
{
	struct bpf_map_priv *newpriv;
	struct bpf_map_op *pos, *newop;

	newpriv = zalloc(sizeof(*newpriv));
	if (!newpriv) {
943
		pr_debug("Not enough memory to alloc map private\n");
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
		return NULL;
	}
	INIT_LIST_HEAD(&newpriv->ops_list);

	list_for_each_entry(pos, &priv->ops_list, list) {
		newop = bpf_map_op__clone(pos);
		if (!newop) {
			bpf_map_priv__purge(newpriv);
			return NULL;
		}
		list_add_tail(&newop->list, &newpriv->ops_list);
	}

	return newpriv;
}

960 961 962
static int
bpf_map__add_op(struct bpf_map *map, struct bpf_map_op *op)
{
963
	const char *map_name = bpf_map__name(map);
964
	struct bpf_map_priv *priv = bpf_map__priv(map);
965

966
	if (IS_ERR(priv)) {
967
		pr_debug("Failed to get private from map %s\n", map_name);
968
		return PTR_ERR(priv);
969 970 971 972 973
	}

	if (!priv) {
		priv = zalloc(sizeof(*priv));
		if (!priv) {
974
			pr_debug("Not enough memory to alloc map private\n");
975 976 977 978
			return -ENOMEM;
		}
		INIT_LIST_HEAD(&priv->ops_list);

979
		if (bpf_map__set_priv(map, priv, bpf_map_priv__clear)) {
980 981 982 983 984 985 986 987 988
			free(priv);
			return -BPF_LOADER_ERRNO__INTERNAL;
		}
	}

	list_add_tail(&op->list, &priv->ops_list);
	return 0;
}

989
static struct bpf_map_op *
990
bpf_map__add_newop(struct bpf_map *map, struct parse_events_term *term)
991 992 993 994
{
	struct bpf_map_op *op;
	int err;

995
	op = bpf_map_op__new(term);
996 997 998 999 1000 1001 1002 1003 1004 1005 1006
	if (IS_ERR(op))
		return op;

	err = bpf_map__add_op(map, op);
	if (err) {
		bpf_map_op__delete(op);
		return ERR_PTR(err);
	}
	return op;
}

1007 1008 1009 1010 1011
static int
__bpf_map__config_value(struct bpf_map *map,
			struct parse_events_term *term)
{
	struct bpf_map_op *op;
1012
	const char *map_name = bpf_map__name(map);
1013
	const struct bpf_map_def *def = bpf_map__def(map);
1014

1015
	if (IS_ERR(def)) {
1016 1017 1018 1019 1020
		pr_debug("Unable to get map definition from '%s'\n",
			 map_name);
		return -BPF_LOADER_ERRNO__INTERNAL;
	}

1021
	if (def->type != BPF_MAP_TYPE_ARRAY) {
1022 1023 1024 1025
		pr_debug("Map %s type is not BPF_MAP_TYPE_ARRAY\n",
			 map_name);
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_TYPE;
	}
1026
	if (def->key_size < sizeof(unsigned int)) {
1027 1028 1029
		pr_debug("Map %s has incorrect key size\n", map_name);
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_KEYSIZE;
	}
1030
	switch (def->value_size) {
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
	case 1:
	case 2:
	case 4:
	case 8:
		break;
	default:
		pr_debug("Map %s has incorrect value size\n", map_name);
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUESIZE;
	}

1041
	op = bpf_map__add_newop(map, term);
1042 1043 1044 1045
	if (IS_ERR(op))
		return PTR_ERR(op);
	op->op_type = BPF_MAP_OP_SET_VALUE;
	op->v.value = term->val.num;
1046
	return 0;
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
}

static int
bpf_map__config_value(struct bpf_map *map,
		      struct parse_events_term *term,
		      struct perf_evlist *evlist __maybe_unused)
{
	if (!term->err_val) {
		pr_debug("Config value not set\n");
		return -BPF_LOADER_ERRNO__OBJCONF_CONF;
	}

	if (term->type_val != PARSE_EVENTS__TERM_TYPE_NUM) {
1060
		pr_debug("ERROR: wrong value type for 'value'\n");
1061 1062 1063 1064 1065 1066
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUE;
	}

	return __bpf_map__config_value(map, term);
}

1067 1068 1069 1070 1071 1072
static int
__bpf_map__config_event(struct bpf_map *map,
			struct parse_events_term *term,
			struct perf_evlist *evlist)
{
	struct perf_evsel *evsel;
1073
	const struct bpf_map_def *def;
1074
	struct bpf_map_op *op;
1075
	const char *map_name = bpf_map__name(map);
1076 1077 1078 1079 1080 1081 1082 1083

	evsel = perf_evlist__find_evsel_by_str(evlist, term->val.str);
	if (!evsel) {
		pr_debug("Event (for '%s') '%s' doesn't exist\n",
			 map_name, term->val.str);
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_NOEVT;
	}

1084 1085
	def = bpf_map__def(map);
	if (IS_ERR(def)) {
1086 1087
		pr_debug("Unable to get map definition from '%s'\n",
			 map_name);
1088
		return PTR_ERR(def);
1089 1090 1091 1092 1093 1094
	}

	/*
	 * No need to check key_size and value_size:
	 * kernel has already checked them.
	 */
1095
	if (def->type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
1096 1097 1098 1099 1100
		pr_debug("Map %s type is not BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
			 map_name);
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_TYPE;
	}

1101
	op = bpf_map__add_newop(map, term);
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
	if (IS_ERR(op))
		return PTR_ERR(op);
	op->op_type = BPF_MAP_OP_SET_EVSEL;
	op->v.evsel = evsel;
	return 0;
}

static int
bpf_map__config_event(struct bpf_map *map,
		      struct parse_events_term *term,
		      struct perf_evlist *evlist)
{
	if (!term->err_val) {
		pr_debug("Config value not set\n");
		return -BPF_LOADER_ERRNO__OBJCONF_CONF;
	}

	if (term->type_val != PARSE_EVENTS__TERM_TYPE_STR) {
		pr_debug("ERROR: wrong value type for 'event'\n");
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUE;
	}

	return __bpf_map__config_event(map, term, evlist);
}

1127 1128 1129 1130 1131 1132 1133 1134
struct bpf_obj_config__map_func {
	const char *config_opt;
	int (*config_func)(struct bpf_map *, struct parse_events_term *,
			   struct perf_evlist *);
};

struct bpf_obj_config__map_func bpf_obj_config__map_funcs[] = {
	{"value", bpf_map__config_value},
1135
	{"event", bpf_map__config_event},
1136 1137
};

1138 1139 1140 1141 1142 1143
static int
config_map_indices_range_check(struct parse_events_term *term,
			       struct bpf_map *map,
			       const char *map_name)
{
	struct parse_events_array *array = &term->array;
1144
	const struct bpf_map_def *def;
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
	unsigned int i;

	if (!array->nr_ranges)
		return 0;
	if (!array->ranges) {
		pr_debug("ERROR: map %s: array->nr_ranges is %d but range array is NULL\n",
			 map_name, (int)array->nr_ranges);
		return -BPF_LOADER_ERRNO__INTERNAL;
	}

1155 1156
	def = bpf_map__def(map);
	if (IS_ERR(def)) {
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
		pr_debug("ERROR: Unable to get map definition from '%s'\n",
			 map_name);
		return -BPF_LOADER_ERRNO__INTERNAL;
	}

	for (i = 0; i < array->nr_ranges; i++) {
		unsigned int start = array->ranges[i].start;
		size_t length = array->ranges[i].length;
		unsigned int idx = start + length - 1;

1167
		if (idx >= def->max_entries) {
1168 1169 1170 1171 1172 1173 1174
			pr_debug("ERROR: index %d too large\n", idx);
			return -BPF_LOADER_ERRNO__OBJCONF_MAP_IDX2BIG;
		}
	}
	return 0;
}

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
static int
bpf__obj_config_map(struct bpf_object *obj,
		    struct parse_events_term *term,
		    struct perf_evlist *evlist,
		    int *key_scan_pos)
{
	/* key is "map:<mapname>.<config opt>" */
	char *map_name = strdup(term->config + sizeof("map:") - 1);
	struct bpf_map *map;
	int err = -BPF_LOADER_ERRNO__OBJCONF_OPT;
	char *map_opt;
	size_t i;

	if (!map_name)
		return -ENOMEM;

	map_opt = strchr(map_name, '.');
	if (!map_opt) {
		pr_debug("ERROR: Invalid map config: %s\n", map_name);
		goto out;
	}

	*map_opt++ = '\0';
	if (*map_opt == '\0') {
		pr_debug("ERROR: Invalid map option: %s\n", term->config);
		goto out;
	}

1203
	map = bpf_object__find_map_by_name(obj, map_name);
1204 1205 1206 1207 1208 1209
	if (!map) {
		pr_debug("ERROR: Map %s doesn't exist\n", map_name);
		err = -BPF_LOADER_ERRNO__OBJCONF_MAP_NOTEXIST;
		goto out;
	}

1210 1211 1212 1213 1214 1215
	*key_scan_pos += strlen(map_opt);
	err = config_map_indices_range_check(term, map, map_name);
	if (err)
		goto out;
	*key_scan_pos -= strlen(map_opt);

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
	for (i = 0; i < ARRAY_SIZE(bpf_obj_config__map_funcs); i++) {
		struct bpf_obj_config__map_func *func =
				&bpf_obj_config__map_funcs[i];

		if (strcmp(map_opt, func->config_opt) == 0) {
			err = func->config_func(map, term, evlist);
			goto out;
		}
	}

	pr_debug("ERROR: Invalid map config option '%s'\n", map_opt);
	err = -BPF_LOADER_ERRNO__OBJCONF_MAP_OPT;
out:
	free(map_name);
	if (!err)
		key_scan_pos += strlen(map_opt);
	return err;
}

int bpf__config_obj(struct bpf_object *obj,
		    struct parse_events_term *term,
		    struct perf_evlist *evlist,
		    int *error_pos)
{
	int key_scan_pos = 0;
	int err;

	if (!obj || !term || !term->config)
		return -EINVAL;

	if (!prefixcmp(term->config, "map:")) {
		key_scan_pos = sizeof("map:") - 1;
		err = bpf__obj_config_map(obj, term, evlist, &key_scan_pos);
		goto out;
	}
	err = -BPF_LOADER_ERRNO__OBJCONF_OPT;
out:
	if (error_pos)
		*error_pos = key_scan_pos;
	return err;

}

1259
typedef int (*map_config_func_t)(const char *name, int map_fd,
1260
				 const struct bpf_map_def *pdef,
1261 1262 1263 1264 1265 1266
				 struct bpf_map_op *op,
				 void *pkey, void *arg);

static int
foreach_key_array_all(map_config_func_t func,
		      void *arg, const char *name,
1267
		      int map_fd, const struct bpf_map_def *pdef,
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
		      struct bpf_map_op *op)
{
	unsigned int i;
	int err;

	for (i = 0; i < pdef->max_entries; i++) {
		err = func(name, map_fd, pdef, op, &i, arg);
		if (err) {
			pr_debug("ERROR: failed to insert value to %s[%u]\n",
				 name, i);
			return err;
		}
	}
	return 0;
}

1284 1285 1286
static int
foreach_key_array_ranges(map_config_func_t func, void *arg,
			 const char *name, int map_fd,
1287
			 const struct bpf_map_def *pdef,
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
			 struct bpf_map_op *op)
{
	unsigned int i, j;
	int err;

	for (i = 0; i < op->k.array.nr_ranges; i++) {
		unsigned int start = op->k.array.ranges[i].start;
		size_t length = op->k.array.ranges[i].length;

		for (j = 0; j < length; j++) {
			unsigned int idx = start + j;

			err = func(name, map_fd, pdef, op, &idx, arg);
			if (err) {
				pr_debug("ERROR: failed to insert value to %s[%u]\n",
					 name, idx);
				return err;
			}
		}
	}
	return 0;
}

1311 1312 1313 1314 1315 1316 1317
static int
bpf_map_config_foreach_key(struct bpf_map *map,
			   map_config_func_t func,
			   void *arg)
{
	int err, map_fd;
	struct bpf_map_op *op;
1318
	const struct bpf_map_def *def;
1319
	const char *name = bpf_map__name(map);
1320
	struct bpf_map_priv *priv = bpf_map__priv(map);
1321

1322
	if (IS_ERR(priv)) {
1323 1324 1325 1326 1327 1328 1329 1330
		pr_debug("ERROR: failed to get private from map %s\n", name);
		return -BPF_LOADER_ERRNO__INTERNAL;
	}
	if (!priv || list_empty(&priv->ops_list)) {
		pr_debug("INFO: nothing to config for map %s\n", name);
		return 0;
	}

1331 1332
	def = bpf_map__def(map);
	if (IS_ERR(def)) {
1333 1334 1335
		pr_debug("ERROR: failed to get definition from map %s\n", name);
		return -BPF_LOADER_ERRNO__INTERNAL;
	}
1336
	map_fd = bpf_map__fd(map);
1337 1338 1339 1340 1341 1342
	if (map_fd < 0) {
		pr_debug("ERROR: failed to get fd from map %s\n", name);
		return map_fd;
	}

	list_for_each_entry(op, &priv->ops_list, list) {
1343
		switch (def->type) {
1344
		case BPF_MAP_TYPE_ARRAY:
1345
		case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1346 1347 1348
			switch (op->key_type) {
			case BPF_MAP_KEY_ALL:
				err = foreach_key_array_all(func, arg, name,
1349
							    map_fd, def, op);
1350 1351 1352
				break;
			case BPF_MAP_KEY_RANGES:
				err = foreach_key_array_ranges(func, arg, name,
1353
							       map_fd, def,
1354
							       op);
1355 1356 1357 1358 1359 1360
				break;
			default:
				pr_debug("ERROR: keytype for map '%s' invalid\n",
					 name);
				return -BPF_LOADER_ERRNO__INTERNAL;
			}
1361 1362
			if (err)
				return err;
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
			break;
		default:
			pr_debug("ERROR: type of '%s' incorrect\n", name);
			return -BPF_LOADER_ERRNO__OBJCONF_MAP_TYPE;
		}
	}

	return 0;
}

static int
apply_config_value_for_key(int map_fd, void *pkey,
			   size_t val_size, u64 val)
{
	int err = 0;

	switch (val_size) {
	case 1: {
		u8 _val = (u8)(val);
		err = bpf_map_update_elem(map_fd, pkey, &_val, BPF_ANY);
		break;
	}
	case 2: {
		u16 _val = (u16)(val);
		err = bpf_map_update_elem(map_fd, pkey, &_val, BPF_ANY);
		break;
	}
	case 4: {
		u32 _val = (u32)(val);
		err = bpf_map_update_elem(map_fd, pkey, &_val, BPF_ANY);
		break;
	}
	case 8: {
		err = bpf_map_update_elem(map_fd, pkey, &val, BPF_ANY);
		break;
	}
	default:
		pr_debug("ERROR: invalid value size\n");
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUESIZE;
	}
	if (err && errno)
		err = -errno;
	return err;
}

1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
static int
apply_config_evsel_for_key(const char *name, int map_fd, void *pkey,
			   struct perf_evsel *evsel)
{
	struct xyarray *xy = evsel->fd;
	struct perf_event_attr *attr;
	unsigned int key, events;
	bool check_pass = false;
	int *evt_fd;
	int err;

	if (!xy) {
		pr_debug("ERROR: evsel not ready for map %s\n", name);
		return -BPF_LOADER_ERRNO__INTERNAL;
	}

	if (xy->row_size / xy->entry_size != 1) {
		pr_debug("ERROR: Dimension of target event is incorrect for map %s\n",
			 name);
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_EVTDIM;
	}

	attr = &evsel->attr;
	if (attr->inherit) {
		pr_debug("ERROR: Can't put inherit event into map %s\n", name);
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_EVTINH;
	}

1436 1437
	if (perf_evsel__is_bpf_output(evsel))
		check_pass = true;
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
	if (attr->type == PERF_TYPE_RAW)
		check_pass = true;
	if (attr->type == PERF_TYPE_HARDWARE)
		check_pass = true;
	if (!check_pass) {
		pr_debug("ERROR: Event type is wrong for map %s\n", name);
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_EVTTYPE;
	}

	events = xy->entries / (xy->row_size / xy->entry_size);
	key = *((unsigned int *)pkey);
	if (key >= events) {
		pr_debug("ERROR: there is no event %d for map %s\n",
			 key, name);
		return -BPF_LOADER_ERRNO__OBJCONF_MAP_MAPSIZE;
	}
	evt_fd = xyarray__entry(xy, key, 0);
	err = bpf_map_update_elem(map_fd, pkey, evt_fd, BPF_ANY);
	if (err && errno)
		err = -errno;
	return err;
}

1461 1462
static int
apply_obj_config_map_for_key(const char *name, int map_fd,
1463
			     const struct bpf_map_def *pdef,
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
			     struct bpf_map_op *op,
			     void *pkey, void *arg __maybe_unused)
{
	int err;

	switch (op->op_type) {
	case BPF_MAP_OP_SET_VALUE:
		err = apply_config_value_for_key(map_fd, pkey,
						 pdef->value_size,
						 op->v.value);
		break;
1475 1476 1477 1478
	case BPF_MAP_OP_SET_EVSEL:
		err = apply_config_evsel_for_key(name, map_fd, pkey,
						 op->v.evsel);
		break;
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
	default:
		pr_debug("ERROR: unknown value type for '%s'\n", name);
		err = -BPF_LOADER_ERRNO__INTERNAL;
	}
	return err;
}

static int
apply_obj_config_map(struct bpf_map *map)
{
	return bpf_map_config_foreach_key(map,
					  apply_obj_config_map_for_key,
					  NULL);
}

static int
apply_obj_config_object(struct bpf_object *obj)
{
	struct bpf_map *map;
	int err;

	bpf_map__for_each(map, obj) {
		err = apply_obj_config_map(map);
		if (err)
			return err;
	}
	return 0;
}

int bpf__apply_obj_config(void)
{
	struct bpf_object *obj, *tmp;
	int err;

	bpf_object__for_each_safe(obj, tmp) {
		err = apply_obj_config_object(obj);
		if (err)
			return err;
	}

	return 0;
}

1522 1523 1524 1525 1526 1527
#define bpf__for_each_map(pos, obj, objtmp)	\
	bpf_object__for_each_safe(obj, objtmp)	\
		bpf_map__for_each(pos, obj)

#define bpf__for_each_stdout_map(pos, obj, objtmp)	\
	bpf__for_each_map(pos, obj, objtmp) 		\
1528
		if (bpf_map__name(pos) && 		\
1529
			(strcmp("__bpf_stdout__", 	\
1530
				bpf_map__name(pos)) == 0))
1531 1532 1533 1534 1535

int bpf__setup_stdout(struct perf_evlist *evlist __maybe_unused)
{
	struct bpf_map_priv *tmpl_priv = NULL;
	struct bpf_object *obj, *tmp;
1536
	struct perf_evsel *evsel = NULL;
1537 1538 1539 1540 1541
	struct bpf_map *map;
	int err;
	bool need_init = false;

	bpf__for_each_stdout_map(map, obj, tmp) {
1542
		struct bpf_map_priv *priv = bpf_map__priv(map);
1543

1544
		if (IS_ERR(priv))
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
			return -BPF_LOADER_ERRNO__INTERNAL;

		/*
		 * No need to check map type: type should have been
		 * verified by kernel.
		 */
		if (!need_init && !priv)
			need_init = !priv;
		if (!tmpl_priv && priv)
			tmpl_priv = priv;
	}

	if (!need_init)
		return 0;

1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
	if (!tmpl_priv) {
		err = parse_events(evlist, "bpf-output/no-inherit=1,name=__bpf_stdout__/",
				   NULL);
		if (err) {
			pr_debug("ERROR: failed to create bpf-output event\n");
			return -err;
		}

		evsel = perf_evlist__last(evlist);
	}
1570 1571

	bpf__for_each_stdout_map(map, obj, tmp) {
1572
		struct bpf_map_priv *priv = bpf_map__priv(map);
1573

1574
		if (IS_ERR(priv))
1575 1576 1577 1578
			return -BPF_LOADER_ERRNO__INTERNAL;
		if (priv)
			continue;

1579 1580 1581 1582
		if (tmpl_priv) {
			priv = bpf_map_priv__clone(tmpl_priv);
			if (!priv)
				return -ENOMEM;
1583

1584
			err = bpf_map__set_priv(map, priv, bpf_map_priv__clear);
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
			if (err) {
				bpf_map_priv__clear(map, priv);
				return err;
			}
		} else if (evsel) {
			struct bpf_map_op *op;

			op = bpf_map__add_newop(map, NULL);
			if (IS_ERR(op))
				return PTR_ERR(op);
			op->op_type = BPF_MAP_OP_SET_EVSEL;
			op->v.evsel = evsel;
1597 1598 1599 1600 1601 1602
		}
	}

	return 0;
}

1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
#define ERRNO_OFFSET(e)		((e) - __BPF_LOADER_ERRNO__START)
#define ERRCODE_OFFSET(c)	ERRNO_OFFSET(BPF_LOADER_ERRNO__##c)
#define NR_ERRNO	(__BPF_LOADER_ERRNO__END - __BPF_LOADER_ERRNO__START)

static const char *bpf_loader_strerror_table[NR_ERRNO] = {
	[ERRCODE_OFFSET(CONFIG)]	= "Invalid config string",
	[ERRCODE_OFFSET(GROUP)]		= "Invalid group name",
	[ERRCODE_OFFSET(EVENTNAME)]	= "No event name found in config string",
	[ERRCODE_OFFSET(INTERNAL)]	= "BPF loader internal error",
	[ERRCODE_OFFSET(COMPILE)]	= "Error when compiling BPF scriptlet",
1613
	[ERRCODE_OFFSET(PROGCONF_TERM)]	= "Invalid program config term in config string",
1614 1615 1616
	[ERRCODE_OFFSET(PROLOGUE)]	= "Failed to generate prologue",
	[ERRCODE_OFFSET(PROLOGUE2BIG)]	= "Prologue too big for program",
	[ERRCODE_OFFSET(PROLOGUEOOB)]	= "Offset out of bound for prologue",
1617 1618 1619 1620 1621 1622 1623 1624
	[ERRCODE_OFFSET(OBJCONF_OPT)]	= "Invalid object config option",
	[ERRCODE_OFFSET(OBJCONF_CONF)]	= "Config value not set (missing '=')",
	[ERRCODE_OFFSET(OBJCONF_MAP_OPT)]	= "Invalid object map config option",
	[ERRCODE_OFFSET(OBJCONF_MAP_NOTEXIST)]	= "Target map doesn't exist",
	[ERRCODE_OFFSET(OBJCONF_MAP_VALUE)]	= "Incorrect value type for map",
	[ERRCODE_OFFSET(OBJCONF_MAP_TYPE)]	= "Incorrect map type",
	[ERRCODE_OFFSET(OBJCONF_MAP_KEYSIZE)]	= "Incorrect map key size",
	[ERRCODE_OFFSET(OBJCONF_MAP_VALUESIZE)]	= "Incorrect map value size",
1625 1626 1627 1628 1629
	[ERRCODE_OFFSET(OBJCONF_MAP_NOEVT)]	= "Event not found for map setting",
	[ERRCODE_OFFSET(OBJCONF_MAP_MAPSIZE)]	= "Invalid map size for event setting",
	[ERRCODE_OFFSET(OBJCONF_MAP_EVTDIM)]	= "Event dimension too large",
	[ERRCODE_OFFSET(OBJCONF_MAP_EVTINH)]	= "Doesn't support inherit event",
	[ERRCODE_OFFSET(OBJCONF_MAP_EVTTYPE)]	= "Wrong event type for map",
1630
	[ERRCODE_OFFSET(OBJCONF_MAP_IDX2BIG)]	= "Index too large",
1631 1632
};

1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
static int
bpf_loader_strerror(int err, char *buf, size_t size)
{
	char sbuf[STRERR_BUFSIZE];
	const char *msg;

	if (!buf || !size)
		return -1;

	err = err > 0 ? err : -err;

	if (err >= __LIBBPF_ERRNO__START)
		return libbpf_strerror(err, buf, size);

1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
	if (err >= __BPF_LOADER_ERRNO__START && err < __BPF_LOADER_ERRNO__END) {
		msg = bpf_loader_strerror_table[ERRNO_OFFSET(err)];
		snprintf(buf, size, "%s", msg);
		buf[size - 1] = '\0';
		return 0;
	}

	if (err >= __BPF_LOADER_ERRNO__END)
		snprintf(buf, size, "Unknown bpf loader error %d", err);
	else
		snprintf(buf, size, "%s",
1658
			 str_error_r(err, sbuf, sizeof(sbuf)));
1659

1660
	buf[size - 1] = '\0';
1661
	return -1;
1662 1663
}

1664 1665 1666 1667 1668 1669
#define bpf__strerror_head(err, buf, size) \
	char sbuf[STRERR_BUFSIZE], *emsg;\
	if (!size)\
		return 0;\
	if (err < 0)\
		err = -err;\
1670 1671
	bpf_loader_strerror(err, sbuf, sizeof(sbuf));\
	emsg = sbuf;\
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
	switch (err) {\
	default:\
		scnprintf(buf, size, "%s", emsg);\
		break;

#define bpf__strerror_entry(val, fmt...)\
	case val: {\
		scnprintf(buf, size, fmt);\
		break;\
	}

#define bpf__strerror_end(buf, size)\
	}\
	buf[size - 1] = '\0';

1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
int bpf__strerror_prepare_load(const char *filename, bool source,
			       int err, char *buf, size_t size)
{
	size_t n;
	int ret;

	n = snprintf(buf, size, "Failed to load %s%s: ",
			 filename, source ? " from source" : "");
	if (n >= size) {
		buf[size - 1] = '\0';
		return 0;
	}
	buf += n;
	size -= n;

	ret = bpf_loader_strerror(err, buf, size);
	buf[size - 1] = '\0';
	return ret;
}

1707 1708 1709 1710
int bpf__strerror_probe(struct bpf_object *obj __maybe_unused,
			int err, char *buf, size_t size)
{
	bpf__strerror_head(err, buf, size);
1711
	case BPF_LOADER_ERRNO__PROGCONF_TERM: {
1712 1713 1714
		scnprintf(buf, size, "%s (add -v to see detail)", emsg);
		break;
	}
1715
	bpf__strerror_entry(EEXIST, "Probe point exist. Try 'perf probe -d \"*\"' and set 'force=yes'");
1716 1717 1718
	bpf__strerror_entry(EACCES, "You need to be root");
	bpf__strerror_entry(EPERM, "You need to be root, and /proc/sys/kernel/kptr_restrict should be 0");
	bpf__strerror_entry(ENOENT, "You need to check probing points in BPF file");
1719 1720
	bpf__strerror_end(buf, size);
	return 0;
W
Wang Nan 已提交
1721
}
1722

1723
int bpf__strerror_load(struct bpf_object *obj,
1724 1725 1726
		       int err, char *buf, size_t size)
{
	bpf__strerror_head(err, buf, size);
1727
	case LIBBPF_ERRNO__KVER: {
1728
		unsigned int obj_kver = bpf_object__kversion(obj);
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
		unsigned int real_kver;

		if (fetch_kernel_version(&real_kver, NULL, 0)) {
			scnprintf(buf, size, "Unable to fetch kernel version");
			break;
		}

		if (obj_kver != real_kver) {
			scnprintf(buf, size,
				  "'version' ("KVER_FMT") doesn't match running kernel ("KVER_FMT")",
				  KVER_PARAM(obj_kver),
				  KVER_PARAM(real_kver));
			break;
		}

		scnprintf(buf, size, "Failed to load program for unknown reason");
		break;
	}
1747 1748 1749
	bpf__strerror_end(buf, size);
	return 0;
}
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762

int bpf__strerror_config_obj(struct bpf_object *obj __maybe_unused,
			     struct parse_events_term *term __maybe_unused,
			     struct perf_evlist *evlist __maybe_unused,
			     int *error_pos __maybe_unused, int err,
			     char *buf, size_t size)
{
	bpf__strerror_head(err, buf, size);
	bpf__strerror_entry(BPF_LOADER_ERRNO__OBJCONF_MAP_TYPE,
			    "Can't use this config term with this map type");
	bpf__strerror_end(buf, size);
	return 0;
}
1763 1764 1765 1766

int bpf__strerror_apply_obj_config(int err, char *buf, size_t size)
{
	bpf__strerror_head(err, buf, size);
1767 1768 1769 1770 1771 1772
	bpf__strerror_entry(BPF_LOADER_ERRNO__OBJCONF_MAP_EVTDIM,
			    "Cannot set event to BPF map in multi-thread tracing");
	bpf__strerror_entry(BPF_LOADER_ERRNO__OBJCONF_MAP_EVTINH,
			    "%s (Hint: use -i to turn off inherit)", emsg);
	bpf__strerror_entry(BPF_LOADER_ERRNO__OBJCONF_MAP_EVTTYPE,
			    "Can only put raw, hardware and BPF output event into a BPF map");
1773 1774 1775
	bpf__strerror_end(buf, size);
	return 0;
}
1776 1777 1778 1779 1780 1781 1782 1783

int bpf__strerror_setup_stdout(struct perf_evlist *evlist __maybe_unused,
			       int err, char *buf, size_t size)
{
	bpf__strerror_head(err, buf, size);
	bpf__strerror_end(buf, size);
	return 0;
}