Skip to content

Helper function bpf_for_each_map_elem

v5.13

For each element in map, call callback_fn function with map, callback_ctx and other map-specific parameters.

Definition

Copyright (c) 2015 The Libbpf Authors. All rights reserved.

static long (* const bpf_for_each_map_elem)(void *map, void *callback_fn, void *callback_ctx, __u64 flags) = (void *) 164;

Usage

The callback_fn should be a static function with the following signature: long (*callback_fn)(struct bpf_map *map, const void *key, void *value, void *ctx);

callback_ctx should be a pointer to a variable on the stack, its type can be determined by the caller. The same context is shared between all calls and can so be used to get information back from the callback to the main program.

The flags is used to control certain aspects of the helper. Currently, the flags must be 0.

For per-CPU maps, the map_value is the value on the cpu where the bpf_prog is running.

If callback_fn return 0, the helper will continue to the next element. If return value is 1, the helper will skip the rest of elements and return. Other return values are not used now.

Returns The number of traversed map elements for success, -EINVAL for invalid flags.

Program types

This helper call can be used in the following program types:

Map types

This helper call can be used with the following map types:

Example

static long callback_fn(struct bpf_map *map, const void *key, void *value, void *ctx)
{
    bpf_printk("context value: %s\n", *(char **)ctx);
    // delete elements with an odd key
    if (*(__u32 *)key % 2)
        bpf_map_delete_elem(map, key);
    return 0;
}

int program(void *ctx)
{
    /*
        .
        .
        .
    */

    char *context = "This string will pass to every callback call";
    long (*cb_p)(struct bpf_map *, const void *, void *, void *) = &callback_fn;
    bpf_for_each_map_elem(&my_map, cb_p, &context, 0);
}