3

I have encountered an interesting issue where a PERCPU_ARRAY created on one system with 2 processors creates an array with 2 per-CPU elements and on another system with 2 processors, an array with 128 per-CPU elements. The latter was rather unexpected to me!

The way I discovered this behavior is that a program that allocated an array for the number of CPUs (using get_nprocs_conf(3)) and then read in the PERCPU_ARRAY into it (using bpf_map_lookup_elem()) ended up writing past the end of the array and crashing.

I would like to find out what is the proper way to determine in a program that reads BPF maps the number of elements in a PERCPU_ARRAY used on a system.

Failing that, I think the second best approach is to pick a buffer for reading in that is "large enough." Here, the problem is similar: what is that number and is there way to learn it at runtime?

Dmitri
  • 479
  • 3
  • 10

1 Answers1

2

The question comes from reading the source of bpftool, which figures this out:

unsigned int get_possible_cpus(void)
{
        int cpus = libbpf_num_possible_cpus();
        
        if (cpus < 0) {
                p_err("Can't get # of possible cpus: %s", strerror(-cpus));
                exit(-1);
        }
        return cpus;
}

int libbpf_num_possible_cpus(void)
{       
        static const char *fcpu = "/sys/devices/system/cpu/possible";
        static int cpus;
        int err, n, i, tmp_cpus;
        bool *mask;

/* ---8<--- snip */

}

So that's how they do it!

Dmitri
  • 479
  • 3
  • 10