[PATCH bpf-next v1 2/4] bpftool: Add tools support to show BPF htab map's used size

From: Ho-Ren (Jack) Chuang
Date: Fri Nov 04 2022 - 22:52:42 EST


Add bpftool support for reporting the number of used entries of
htab maps by leveraging the newly added "used_entries" field in
struct bpf_map_info. It works with JSON as well.

To better understand actual used memory size of a htab map,
pre-allocated maps are now marked with "*" behind the "max_entries" size.

Signed-off-by: Ho-Ren (Jack) Chuang <horenchuang@xxxxxxxxxxxxx>
---
tools/bpf/bpftool/map.c | 9 +++++++--
tools/include/uapi/linux/bpf.h | 1 +
2 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/tools/bpf/bpftool/map.c b/tools/bpf/bpftool/map.c
index 9a6ca9f31133..0b07abae7309 100644
--- a/tools/bpf/bpftool/map.c
+++ b/tools/bpf/bpftool/map.c
@@ -475,6 +475,8 @@ static int show_map_close_json(int fd, struct bpf_map_info *info)
jsonw_uint_field(json_wtr, "bytes_key", info->key_size);
jsonw_uint_field(json_wtr, "bytes_value", info->value_size);
jsonw_uint_field(json_wtr, "max_entries", info->max_entries);
+ if (info->type == BPF_MAP_TYPE_HASH)
+ jsonw_uint_field(json_wtr, "used_entries", info->used_entries);

if (memlock)
jsonw_int_field(json_wtr, "bytes_memlock", atoll(memlock));
@@ -561,8 +563,11 @@ static int show_map_close_plain(int fd, struct bpf_map_info *info)
frozen_str = get_fdinfo(fd, "frozen");

show_map_header_plain(info);
- printf("\tkey %uB value %uB max_entries %u",
- info->key_size, info->value_size, info->max_entries);
+ printf("\tkey %uB value %uB max_entries %u%1s",
+ info->key_size, info->value_size, info->max_entries,
+ !(info->map_flags & BPF_F_NO_PREALLOC) ? "*" : "");
+ if (info->type == BPF_MAP_TYPE_HASH)
+ printf(" used_entries %u", info->used_entries);

if (memlock)
printf(" memlock %sB", memlock);
diff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h
index 17f61338f8f8..63659368cf0e 100644
--- a/tools/include/uapi/linux/bpf.h
+++ b/tools/include/uapi/linux/bpf.h
@@ -6215,6 +6215,7 @@ struct bpf_map_info {
__u32 id;
__u32 key_size;
__u32 value_size;
+ __u32 used_entries;
__u32 max_entries;
__u32 map_flags;
char name[BPF_OBJ_NAME_LEN];
--
Ho-Ren (Jack) Chuang