[PATCH bpf-next 1/2] bpf: account for local storage map elements memory
From: Mahe Tardy
Date: Thu Nov 26 2026 - 08:13:35 EST
Commit 7490b7f1c02e ("bpf, net: bpf_local_storage memory usage")
introduced bpf_local_storage_map_mem_usage() to compute the memory usage
of local storage related maps but left the accounting of the allocated
element aside. For users of these maps, the elements can quickly make up
the majority of the memory usage and make the reported memory usage
quite wrong.
Walk the bucket's list to count the number of elements in the map, note
that concurrent insertions and deletions can make the count imprecise.
Signed-off-by: Mahe Tardy <mahe.tardy@xxxxxxxxx>
---
kernel/bpf/bpf_local_storage.c | 16 ++++++++++++----
1 file changed, 12 insertions(+), 4 deletions(-)
diff --git a/kernel/bpf/bpf_local_storage.c b/kernel/bpf/bpf_local_storage.c
index b12fcec47ffa..6fb95503441e 100644
--- a/kernel/bpf/bpf_local_storage.c
+++ b/kernel/bpf/bpf_local_storage.c
@@ -792,11 +792,19 @@ u32 bpf_local_storage_destroy(struct bpf_local_storage *local_storage)
u64 bpf_local_storage_map_mem_usage(const struct bpf_map *map)
{
struct bpf_local_storage_map *smap = (struct bpf_local_storage_map *)map;
- u64 usage = sizeof(*smap);
+ struct bpf_local_storage_elem *selem;
+ u64 nbuckets = 1ULL << smap->bucket_log;
+ u64 nr_elem = 0;
+ u64 i;
+
+ for (i = 0; i < nbuckets; i++) {
+ rcu_read_lock();
+ hlist_for_each_entry_rcu(selem, &smap->buckets[i].list, map_node)
+ nr_elem++;
+ rcu_read_unlock();
+ }
- /* The dynamically callocated selems are not counted currently. */
- usage += sizeof(*smap->buckets) * (1ULL << smap->bucket_log);
- return usage;
+ return sizeof(*smap) + nbuckets * sizeof(*smap->buckets) + nr_elem * smap->elem_size;
}
struct bpf_map *
--
2.43.0