Skip to content

Commit

Permalink
libbpf-tools/profile: Batch lookup support for hash map
Browse files Browse the repository at this point in the history
Use bpf_map_lookup_batch() instead of bpf_map_get_next_key() to read
the hash map, if available.
  • Loading branch information
ekyooo committed May 8, 2024
1 parent 77c0591 commit 3a6dc1a
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions libbpf-tools/profile.c
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ struct ksyms *ksyms;
struct syms_cache *syms_cache;
struct syms *syms;

static bool batch_map_ops = true; /* hope for the best */

static error_t parse_arg(int key, char *arg, struct argp_state *state)
{
static int pos_args;
Expand Down Expand Up @@ -268,13 +270,61 @@ static int cmp_counts(const void *a, const void *b)
return y - x;
}

static int read_batch_counts_map(int fd, struct key_ext_t *items, __u32 *count)
{
struct key_t keys[*count];
__u64 vals[*count];
void *in = NULL, *out;
__u32 i, n, n_read = 0;
int err = 0;

while (n_read < *count && !err) {
n = *count - n_read;
err = bpf_map_lookup_batch(fd, &in, &out, keys + n_read,
vals + n_read, &n, NULL);
if (err < 0 && err != -ENOENT) {
/* we want to propagate EINVAL upper, so that
* the batch_map_ops flag is set to false */
if (err != -EINVAL)
fprintf(stderr, "bpf_map_lookup_batch: %s\n",
strerror(-err));

return err;
}

n_read += n;
in = out;
}

for (i = 0; i < n_read; i++) {
items[i].k.pid = keys[i].pid;
items[i].k.user_stack_id = keys[i].user_stack_id;
items[i].k.kern_stack_id = keys[i].kern_stack_id;
strncpy(items[i].k.name, keys[i].name, TASK_COMM_LEN);
items[i].v = vals[i];
}

*count = n_read;
return 0;
}

static int read_counts_map(int fd, struct key_ext_t *items, __u32 *count)
{
struct key_t empty = {};
struct key_t *lookup_key = &empty;
int i = 0;
int err;

if (batch_map_ops) {
err = read_batch_counts_map(fd, items, count);
if (err < 0 && err == -EINVAL) {
/* fall back to a racy variant */
batch_map_ops = false;
} else {
return err;
}
}

while (bpf_map_get_next_key(fd, lookup_key, &items[i].k) == 0) {
err = bpf_map_lookup_elem(fd, &items[i].k, &items[i].v);
if (err < 0) {
Expand Down

0 comments on commit 3a6dc1a

Please sign in to comment.