6

In the kernel, eBPF maps can be defined as:

struct bpf_map_def SEC("maps") my_map = {
    .type = BPF_MAP_TYPE_HASH,
    .key_size = sizeof(uint32_t),
    .value_size = sizeof(struct task_prov_struct),
    .max_entries = 4096,
};

If I do not know ahead of time the maximum possible size of my_map (I also don't want to waste memory), is there a way to, say, pre-allocate a small size and dynamically increase the size as needed? I am aware of bpf_map__resize function but it seems to be a user space function and can only be called before a map is loaded. I'd appreciate any sample code snippet or reference.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
vanbastelaer
  • 368
  • 2
  • 15

1 Answers1

7

No, at the moment you cannot “resize” an eBPF map after it has been created.

However, the size of the map in the kernel may vary over time.

  • Some maps are pre-allocated, because their type requires so (e.g. arrays) or because this was required by the user at map creation time, by providing the relevant flag. These maps are allocated as soon as they are created, and occupy a space equal to (key_size + value_size) * max_entries.
  • Some other maps are not pre-allocated, and will grow over time. This is the case for hash maps for example: They will take more space in kernel space as new entries are added. However, they will only grow up to the maximum number of entries provided during their creation, and it is NOT possible to update this maximum number of entries after that.

Regarding the bpf_map__resize() function from libbpf, it is a user space function that can be used to update the number of entries for a map, before this map is created in the kernel:

int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
{
    if (map->fd >= 0)
        return -EBUSY;
    map->def.max_entries = max_entries;
    return 0;
}

int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
{
    if (!map || !max_entries)
        return -EINVAL;

    return bpf_map__set_max_entries(map, max_entries);
}

If we already created the map (if we have a file descriptor to that map), the operation fails.

Qeole
  • 8,284
  • 1
  • 24
  • 52