summaryrefslogtreecommitdiffstats
path: root/tools/perf/util/bpf_map.c
blob: eb853ca67cf4213904ae877df00c6a93083bc491 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)

#include "util/bpf_map.h"
#include <bpf/bpf.h>
#include <bpf/libbpf.h>
#include <linux/err.h>
#include <linux/kernel.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>

static bool bpf_map_def__is_per_cpu(const struct bpf_map_def *def)
{
	return def->type == BPF_MAP_TYPE_PERCPU_HASH ||
	       def->type == BPF_MAP_TYPE_PERCPU_ARRAY ||
	       def->type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
	       def->type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE;
}

static void *bpf_map_def__alloc_value(const struct bpf_map_def *def)
{
	if (bpf_map_def__is_per_cpu(def))
		return malloc(round_up(def->value_size, 8) * sysconf(_SC_NPROCESSORS_CONF));

	return malloc(def->value_size);
}

int bpf_map__fprintf(struct bpf_map *map, FILE *fp)
{
	const struct bpf_map_def *def = bpf_map__def(map);
	void *prev_key = NULL, *key, *value;
	int fd = bpf_map__fd(map), err;
	int printed = 0;

	if (fd < 0)
		return fd;

	if (IS_ERR(def))
		return PTR_ERR(def);

	err = -ENOMEM;
	key = malloc(def->key_size);
	if (key == NULL)
		goto out;

	value = bpf_map_def__alloc_value(def);
	if (value == NULL)
		goto out_free_key;

	while ((err = bpf_map_get_next_key(fd, prev_key, key) == 0)) {
		int intkey = *(int *)key;

		if (!bpf_map_lookup_elem(fd, key, value)) {
			bool boolval = *(bool *)value;
			if (boolval)
				printed += fprintf(fp, "[%d] = %d,\n", intkey, boolval);
		} else {
			printed += fprintf(fp, "[%d] = ERROR,\n", intkey);
		}

		prev_key = key;
	}

	if (err == ENOENT)
		err = printed;

	free(value);
out_free_key:
	free(key);
out:
	return err;
}