gobpf icon indicating copy to clipboard operation
gobpf copied to clipboard

support per-cpu maps in bcc

Open jwhited opened this issue 7 years ago • 1 comments

bcc.Table/TableIterator API can only operate on elements for one map. Could these be extended to support per-cpu maps?

kernel sample: https://github.com/torvalds/linux/commit/3059303f59cf90a84e7fdef154ff0b215bcfaa97

jwhited avatar Sep 14 '18 17:09 jwhited

from bcc import BPF

# Load and compile the eBPF program
bpf_prog = """
#include <linux/sched.h>
BPF_PERCPU_ARRAY(cpu_data, struct data_t, NR_CPUS);

struct data_t {
    u64 timestamp;
    u32 value;
};

int my_prog(struct __sk_buff *skb)
{
    int cpu = bpf_get_smp_processor_id();
    struct data_t *data = cpu_data.lookup(&cpu);
    if (!data) {
        struct data_t zero_data = {};
        cpu_data.update(&cpu, &zero_data);
        data = cpu_data.lookup(&cpu);
    }

    // Access and update the per-cpu data
    data->timestamp = bpf_ktime_get_ns();
    data->value++;

    return 0;
}
"""

# Create the BPF module and attach the program
b = BPF(text=bpf_prog)
fn = b.load_func("my_prog", BPF.SCHED_CLS)

# Retrieve the per-cpu map and iterate over its elements
cpu_data_map = b["cpu_data"]
for key, value in cpu_data_map.items():
    cpu = key.value
    data = value.value
    print(f"CPU {cpu}: timestamp={data.timestamp}, value={data.value}")

ljluestc avatar Jul 05 '23 03:07 ljluestc