linux 关键字为结构时,bpf_map_lookup_elem不工作

gkl3eglg  于 2022-11-02  发布在  Linux
关注(0)|答案(1)|浏览(122)

我在程序的一个SEC中创建了一个BPF_MAP_TYPE_HASH类型的Map条目,并试图在另一个SEC中访问该条目。

struct map_key
{
    __u16 key_1;
    __u16 key_2;
}

struct map_value
{
    __u16 value_1;
    __u16 value_2;
}

struct
{
    __uint(type, BPF_MAP_TYPE_HASH);
    __type(key, struct map_key);
    __type(value, struct map_value);
    __uint(max_entries, 1024);
} bpf_map SEC(".maps");

SEC("sec1")
int sec1_func(struct __sk_buff *skb)
{
    struct map_key key = {0}
    key.key1 = 10;
    key.key2 = 20;
    check = bpf_map_lookup_elem(&bpf_map, &key);
    if (check == NULL) {
        bpf_trace_printk("Trouble.", sizeof("Trouble"));
    }
}

SEC("sec2")
{
    struct map_key key = {0}
    key.key1 = 10;
    key.key2 = 20;

    struct map_value value = {0}
    value.value1 = 15
    value.value2 = 25

    bpf_map_update_elem(&map_key, &key, &value, BPF_NOEXIST);
}

sec2是在sec1之前执行的,所以Map肯定是在bpf_map_lookup_elem被调用之前创建的,但是当我在sec1中调用这个函数时,仍然会从它返回空值。

qxgroojn

qxgroojn1#

所以解决办法是

struct map_key
{
    __u16 key_1;
    __u16 key_2;
}

struct map_value
{
    __u16 value_1;
    __u16 value_2;
}

struct
{
    __uint(type, BPF_MAP_TYPE_HASH);
    __type(key, struct map_key);
    __type(value, struct map_value);
    __uint(max_entries, 1024);
    __uint(pinning, 1);
} bpf_map SEC(".maps");

SEC("sec1")
int sec1_func(struct __sk_buff *skb)
{
    struct map_key key = {0}
    key.key1 = 10;
    key.key2 = 20;
    check = bpf_map_lookup_elem(&bpf_map, &key);
    if (check == NULL) {
        bpf_trace_printk("Trouble.", sizeof("Trouble"));
    }
}

SEC("sec2")
{
    struct map_key key = {0}
    key.key1 = 10;
    key.key2 = 20;

    struct map_value value = {0}
    value.value1 = 15
    value.value2 = 25

    bpf_map_update_elem(&map_key, &key, &value, BPF_NOEXIST);
}

附加的pin字段允许我在同一个对象文件中的不同elf部分使用该Map。

相关问题