Skip to contentSkip to conversation

Allow storage of flexible metadata information for eBPF programs

PATCH Superseded Stanislav Fomichev 5 participants 31 messages Aug 28, 2020 – Sep 9, 2020

Subsystems (10)

v3 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v3 cover Allow storage of flexible metadata information for eBPF programs

Currently, if a user wants to store arbitrary metadata for an eBPF program, for example, the program build commit hash or version, they could store it in a map, and conveniently libbpf uses .data section to populate an internal map. However, if the program does not actually reference the map, then the map would be de-refcounted and freed.

This patch set introduces a new syscall BPF_PROG_BIND_MAP to add a map to a program's used_maps, even if the program instructions does not reference the map. libbpf is extended to recognize the .metadata section and load it as an internal map, and use the new syscall to ensure the map is bound. bpftool is also extended to have a new flag to prog subcommand, "--metadata" to dump the contents of the metadata section without a separate map dump call.

An example use of this would be BPF C file declaring:

  char commit_hash[] SEC(".metadata") = "abcdef123456";

and bpftool would emit:

  $ bpftool prog --metadata
  [...]
        metadata:
                commit_hash = "abcdef123456"

Patch 1 protects the used_maps array and count with a mutex.

Patch 2 implements the new syscall.

Patch 3 extends libbpf to have a wrapper around the syscall, probe the kernel for support of this new syscall, and use it on .metadata section if supported and the section exists.

Patch 4 extends bpftool so that it is able to dump metadata from prog show.

Patch 5 extends bpftool gen skeleton to treat the metadata section like an rodata section so that it mmaps the map read-only at load time.

Patch 6 adds a test to check the metadata loading and dumping.

Changes since RFC:
* Fixed a few missing unlocks, and missing close while iterating map fds.
* Move mutex initialization to right after prog aux allocation, and mutex destroy to right after prog aux free.
* s/ADD_MAP/BIND_MAP/
* Use mutex only instead of RCU to protect the used_map array & count.

Changes since v1:
* Made struct bpf_prog_bind_opts in libbpf so flags is optional.
* Deduped probe_kern_global_data and probe_prog_bind_map into a common helper.
* Added comment regarding why EEXIST is ignored in libbpf bind map.
* Froze all LIBBPF_MAP_METADATA internal maps.
* Moved bpf_prog_bind_map into new LIBBPF_0.1.1 in libbpf.map.
* Added p_err() calls on error cases in bpftool show_prog_metadata.
* Reverse christmas tree coding style in bpftool show_prog_metadata.
* Made bpftool gen skeleton recognize .metadata as an internal map and generate datasec definition in skeleton.
* Added C test using skeleton to see asset that the metadata is what we expect and rebinding causes EEXIST.

Cc YiFei Zhu <[email protected]>

Stanislav Fomichev (2):
libbpf: implement bpf_prog_find_metadata
bpftool: mention --metadata in the documentation

YiFei Zhu (6):
bpf: Mutex protect used_maps array and count
bpf: Add BPF_PROG_BIND_MAP syscall
libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section
bpftool: support dumping metadata
bpftool: support metadata internal map in gen skeleton selftests/bpf: Test load and dump metadata with btftool and skel

 .../net/ethernet/netronome/nfp/bpf/offload.c  |  18 ++-
 include/linux/bpf.h                           |   1 +
 include/uapi/linux/bpf.h                      |   7 +
 kernel/bpf/core.c                             |  15 +-
 kernel/bpf/syscall.c                          |  81 ++++++++++-
 net/core/dev.c                                |  11 +-
 .../bpftool/Documentation/bpftool-prog.rst    |   5 +-
 tools/bpf/bpftool/gen.c                       |   5 +
 tools/bpf/bpftool/json_writer.c               |   6 +
 tools/bpf/bpftool/json_writer.h               |   3 +
 tools/bpf/bpftool/main.c                      |  10 ++
 tools/bpf/bpftool/main.h                      |   1 +
 tools/bpf/bpftool/prog.c                      | 132 +++++++++++++++++-
 tools/include/uapi/linux/bpf.h                |   7 +
 tools/lib/bpf/bpf.c                           |  87 ++++++++++++
 tools/lib/bpf/bpf.h                           |   9 ++
 tools/lib/bpf/libbpf.c                        | 130 ++++++++++++++---
 tools/lib/bpf/libbpf.map                      |   2 +
 tools/testing/selftests/bpf/Makefile          |   3 +-
 .../selftests/bpf/prog_tests/metadata.c       |  83 +++++++++++
 .../selftests/bpf/progs/metadata_unused.c     |  15 ++
 .../selftests/bpf/progs/metadata_used.c       |  15 ++
 .../selftests/bpf/test_bpftool_metadata.sh    |  82 +++++++++++
 23 files changed, 687 insertions(+), 41 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/metadata.c
 create mode 100644 tools/testing/selftests/bpf/progs/metadata_unused.c
 create mode 100644 tools/testing/selftests/bpf/progs/metadata_used.c
 create mode 100755 tools/testing/selftests/bpf/test_bpftool_metadata.sh
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
#1 lore raw

PATCH v3 1/8 bpf: Mutex protect used_maps array and count

From: YiFei Zhu <[email protected]>

To support modifying the used_maps array, we use a mutex to protect the use of the counter and the array. The mutex is initialized right after the prog aux is allocated, and destroyed right before prog aux is freed. This way we guarantee it's initialized for both cBPF and eBPF.

---
 .../net/ethernet/netronome/nfp/bpf/offload.c   | 18 ++++++++++++------
 include/linux/bpf.h                            |  1 +
 kernel/bpf/core.c                              | 15 +++++++++++----
 kernel/bpf/syscall.c                           | 16 ++++++++++++----
 net/core/dev.c                                 | 11 ++++++++---
 5 files changed, 44 insertions(+), 17 deletions(-)
drivers/net/ethernet/netronome/nfp/bpf/offload.c +12 -6
index ac02369174a9..53851853562c 100644
@@ -111,7 +111,9 @@ static int
 nfp_map_ptrs_record(struct nfp_app_bpf *bpf, struct nfp_prog *nfp_prog,
 		    struct bpf_prog *prog)
 {
-	int i, cnt, err;
+	int i, cnt, err = 0;
+
+	mutex_lock(&prog->aux->used_maps_mutex);
 
 	/* Quickly count the maps we will have to remember */
 	cnt = 0;
@@ -119,13 +121,15 @@ nfp_map_ptrs_record(struct nfp_app_bpf *bpf, struct nfp_prog *nfp_prog,
 		if (bpf_map_offload_neutral(prog->aux->used_maps[i]))
 			cnt++;
 	if (!cnt)
-		return 0;
+		goto out;
 
 	nfp_prog->map_records = kmalloc_array(cnt,
 					      sizeof(nfp_prog->map_records[0]),
 					      GFP_KERNEL);
-	if (!nfp_prog->map_records)
-		return -ENOMEM;
+	if (!nfp_prog->map_records) {
+		err = -ENOMEM;
+		goto out;
+	}
 
 	for (i = 0; i < prog->aux->used_map_cnt; i++)
 		if (bpf_map_offload_neutral(prog->aux->used_maps[i])) {
@@ -133,12 +137,14 @@ nfp_map_ptrs_record(struct nfp_app_bpf *bpf, struct nfp_prog *nfp_prog,
 						 prog->aux->used_maps[i]);
 			if (err) {
 				nfp_map_ptrs_forget(bpf, nfp_prog);
-				return err;
+				goto out;
 			}
 		}
 	WARN_ON(cnt != nfp_prog->map_records_cnt);
 
-	return 0;
+out:
+	mutex_unlock(&prog->aux->used_maps_mutex);
+	return err;
 }
 
 static int
include/linux/bpf.h +1 -0
index dbba82a80087..1b404b034775 100644
@@ -748,6 +748,7 @@ struct bpf_prog_aux {
 	struct bpf_ksym ksym;
 	const struct bpf_prog_ops *ops;
 	struct bpf_map **used_maps;
+	struct mutex used_maps_mutex; /* mutex for used_maps and used_map_cnt */
 	struct bpf_prog *prog;
 	struct user_struct *user;
 	u64 load_time; /* ns since boottime */
kernel/bpf/core.c +11 -4
index ed0b3578867c..2a20c2833996 100644
@@ -98,6 +98,7 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
 	fp->jit_requested = ebpf_jit_enabled();
 
 	INIT_LIST_HEAD_RCU(&fp->aux->ksym.lnode);
+	mutex_init(&fp->aux->used_maps_mutex);
 
 	return fp;
 }
@@ -253,6 +254,7 @@ struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
 void __bpf_prog_free(struct bpf_prog *fp)
 {
 	if (fp->aux) {
+		mutex_destroy(&fp->aux->used_maps_mutex);
 		free_percpu(fp->aux->stats);
 		kfree(fp->aux->poke_tab);
 		kfree(fp->aux);
@@ -1747,8 +1749,9 @@ bool bpf_prog_array_compatible(struct bpf_array *array,
 static int bpf_check_tail_call(const struct bpf_prog *fp)
 {
 	struct bpf_prog_aux *aux = fp->aux;
-	int i;
+	int i, ret = 0;
 
+	mutex_lock(&aux->used_maps_mutex);
 	for (i = 0; i < aux->used_map_cnt; i++) {
 		struct bpf_map *map = aux->used_maps[i];
 		struct bpf_array *array;
@@ -1757,11 +1760,15 @@ static int bpf_check_tail_call(const struct bpf_prog *fp)
 			continue;
 
 		array = container_of(map, struct bpf_array, map);
-		if (!bpf_prog_array_compatible(array, fp))
-			return -EINVAL;
+		if (!bpf_prog_array_compatible(array, fp)) {
+			ret = -EINVAL;
+			goto out;
+		}
 	}
 
-	return 0;
+out:
+	mutex_unlock(&aux->used_maps_mutex);
+	return ret;
 }
 
 static void bpf_prog_select_func(struct bpf_prog *fp)
kernel/bpf/syscall.c +12 -4
index b86b1155b748..c9b8a97fbbdf 100644
@@ -3155,21 +3155,25 @@ static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
 	const struct bpf_map *map;
 	int i;
 
+	mutex_lock(&prog->aux->used_maps_mutex);
 	for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
 		map = prog->aux->used_maps[i];
 		if (map == (void *)addr) {
 			*type = BPF_PSEUDO_MAP_FD;
-			return map;
+			goto out;
 		}
 		if (!map->ops->map_direct_value_meta)
 			continue;
 		if (!map->ops->map_direct_value_meta(map, addr, off)) {
 			*type = BPF_PSEUDO_MAP_VALUE;
-			return map;
+			goto out;
 		}
 	}
+	map = NULL;
 
-	return NULL;
+out:
+	mutex_unlock(&prog->aux->used_maps_mutex);
+	return map;
 }
 
 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
@@ -3287,6 +3291,7 @@ static int bpf_prog_get_info_by_fd(struct file *file,
 	memcpy(info.tag, prog->tag, sizeof(prog->tag));
 	memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
 
+	mutex_lock(&prog->aux->used_maps_mutex);
 	ulen = info.nr_map_ids;
 	info.nr_map_ids = prog->aux->used_map_cnt;
 	ulen = min_t(u32, info.nr_map_ids, ulen);
@@ -3296,9 +3301,12 @@ static int bpf_prog_get_info_by_fd(struct file *file,
 
 		for (i = 0; i < ulen; i++)
 			if (put_user(prog->aux->used_maps[i]->id,
-				     &user_map_ids[i]))
+				     &user_map_ids[i])) {
+				mutex_unlock(&prog->aux->used_maps_mutex);
 				return -EFAULT;
+			}
 	}
+	mutex_unlock(&prog->aux->used_maps_mutex);
 
 	err = set_info_rec_size(&info);
 	if (err)
net/core/dev.c +8 -3
index b5d1129d8310..6957b31127d9 100644
@@ -5441,15 +5441,20 @@ static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
 	if (new) {
 		u32 i;
 
+		mutex_lock(&new->aux->used_maps_mutex);
+
 		/* generic XDP does not work with DEVMAPs that can
 		 * have a bpf_prog installed on an entry
 		 */
 		for (i = 0; i < new->aux->used_map_cnt; i++) {
-			if (dev_map_can_have_prog(new->aux->used_maps[i]))
-				return -EINVAL;
-			if (cpu_map_prog_allowed(new->aux->used_maps[i]))
+			if (dev_map_can_have_prog(new->aux->used_maps[i]) ||
+			    cpu_map_prog_allowed(new->aux->used_maps[i])) {
+				mutex_unlock(&new->aux->used_maps_mutex);
 				return -EINVAL;
+			}
 		}
+
+		mutex_unlock(&new->aux->used_maps_mutex);
 	}
 
 	switch (xdp->command) {
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
#2 lore raw

PATCH v3 2/8 bpf: Add BPF_PROG_BIND_MAP syscall

In reply to Stanislav Fomichev

From: YiFei Zhu <[email protected]>

This syscall binds a map to a program. -EEXIST if the map is already bound to the program.

---
 include/uapi/linux/bpf.h       |  7 ++++
 kernel/bpf/syscall.c           | 65 ++++++++++++++++++++++++++++++++++
 tools/include/uapi/linux/bpf.h |  7 ++++
 3 files changed, 79 insertions(+)
include/uapi/linux/bpf.h +7 -0
index ef7af384f5ee..d232c71c4560 100644
@@ -124,6 +124,7 @@ enum bpf_cmd {
 	BPF_ENABLE_STATS,
 	BPF_ITER_CREATE,
 	BPF_LINK_DETACH,
+	BPF_PROG_BIND_MAP,
 };
 
 enum bpf_map_type {
@@ -650,6 +651,12 @@ union bpf_attr {
 		__u32		flags;
 	} iter_create;
 
+	struct { /* struct used by BPF_PROG_BIND_MAP command */
+		__u32		prog_fd;
+		__u32		map_fd;
+		__u32		flags;		/* extra flags */
+	} prog_bind_map;
+
 } __attribute__((aligned(8)));
 
 /* The description below is an attempt at providing documentation to eBPF
kernel/bpf/syscall.c +65 -0

77 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +7 -0
index ef7af384f5ee..d232c71c4560 100644
@@ -124,6 +124,7 @@ enum bpf_cmd {
 	BPF_ENABLE_STATS,
 	BPF_ITER_CREATE,
 	BPF_LINK_DETACH,
+	BPF_PROG_BIND_MAP,
 };
 
 enum bpf_map_type {
@@ -650,6 +651,12 @@ union bpf_attr {
 		__u32		flags;
 	} iter_create;
 
+	struct { /* struct used by BPF_PROG_BIND_MAP command */
+		__u32		prog_fd;
+		__u32		map_fd;
+		__u32		flags;		/* extra flags */
+	} prog_bind_map;
+
 } __attribute__((aligned(8)));
 
 /* The description below is an attempt at providing documentation to eBPF
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
#3 lore raw

Re: [PATCH bpf-next v3 2/8] bpf: Add BPF_PROG_BIND_MAP syscall

Quoted 15 lines · Stanislav Fomichev

From: YiFei Zhu <[email protected]>

This syscall binds a map to a program. -EEXIST if the map is already bound to the program.

---
 include/uapi/linux/bpf.h       |  7 ++++
 kernel/bpf/syscall.c           | 65 ++++++++++++++++++++++++++++++++++
 tools/include/uapi/linux/bpf.h |  7 ++++
 3 files changed, 79 insertions(+)

[...]

kernel/bpf/syscall.c static int bpf_iter_create(union bpf_attr *attr) · line 4189

Quoted 9 lines
kernel/bpf/syscall.c +9 -0
+
+       mutex_lock(&prog->aux->used_maps_mutex);
+
+       used_maps_old = prog->aux->used_maps;
+
+       for (i = 0; i < prog->aux->used_map_cnt; i++)
+               if (used_maps_old[i] == map) {
+                       ret = -EEXIST;
+                       goto out_unlock;

Do we need to return any error in this case? The intent of this command is to make sure the map is bound to the prog, right? If it's already bound, good, it's a success, just no extra steps were performed internally. What's the use for this EEXIST if it's always going to be ignored?

Quoted 10 lines
kernel/bpf/syscall.c +10 -0
+               }
+
+       used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
+                                     sizeof(used_maps_new[0]),
+                                     GFP_KERNEL);
+       if (!used_maps_new) {
+               ret = -ENOMEM;
+               goto out_unlock;
+       }
+

[...]

#4 lore raw

PATCH v3 3/8 libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

In reply to Stanislav Fomichev

From: YiFei Zhu <[email protected]>

The patch adds a simple wrapper bpf_prog_bind_map around the syscall. And when using libbpf to load a program, it will probe the kernel for the support of this syscall, and scan for the .metadata ELF section and load it as an internal map like a .data section.

In the case that kernel supports the BPF_PROG_BIND_MAP syscall and a .metadata section exists, the map will be explicitly bound to the program via the syscall immediately after program is loaded. -EEXIST is ignored for this syscall.

---
 tools/lib/bpf/bpf.c      |  13 ++++
 tools/lib/bpf/bpf.h      |   8 +++
 tools/lib/bpf/libbpf.c   | 130 ++++++++++++++++++++++++++++++++-------
 tools/lib/bpf/libbpf.map |   1 +
 4 files changed, 131 insertions(+), 21 deletions(-)
tools/lib/bpf/bpf.c +13 -0
index 82b983ff6569..5f6c5676cc45 100644
@@ -872,3 +872,16 @@ int bpf_enable_stats(enum bpf_stats_type type)
 
 	return sys_bpf(BPF_ENABLE_STATS, &attr, sizeof(attr));
 }
+
+int bpf_prog_bind_map(int prog_fd, int map_fd,
+		      const struct bpf_prog_bind_opts *opts)
+{
+	union bpf_attr attr;
+
+	memset(&attr, 0, sizeof(attr));
+	attr.prog_bind_map.prog_fd = prog_fd;
+	attr.prog_bind_map.map_fd = map_fd;
+	attr.prog_bind_map.flags = OPTS_GET(opts, flags, 0);
+
+	return sys_bpf(BPF_PROG_BIND_MAP, &attr, sizeof(attr));
+}
tools/lib/bpf/bpf.h +8 -0
index 015d13f25fcc..8c1ac4b42f90 100644
@@ -243,6 +243,14 @@ LIBBPF_API int bpf_task_fd_query(int pid, int fd, __u32 flags, char *buf,
 enum bpf_stats_type; /* defined in up-to-date linux/bpf.h */
 LIBBPF_API int bpf_enable_stats(enum bpf_stats_type type);
 
+struct bpf_prog_bind_opts {
+	size_t sz; /* size of this struct for forward/backward compatibility */
+	__u32 flags;
+};
+#define bpf_prog_bind_opts__last_field flags
+
+LIBBPF_API int bpf_prog_bind_map(int prog_fd, int map_fd,
+				 const struct bpf_prog_bind_opts *opts);
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
tools/lib/bpf/libbpf.c +109 -21

263 lines not on this page · raw message

tools/lib/bpf/libbpf.map +1 -0
index 66a6286d0716..529b99c0c2c3 100644
@@ -302,6 +302,7 @@ LIBBPF_0.1.0 {
 
 LIBBPF_0.2.0 {
 	global:
+		bpf_prog_bind_map;
 		perf_buffer__buffer_cnt;
 		perf_buffer__buffer_fd;
 		perf_buffer__epoll_fd;
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
#5 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

Quoted 8 lines · Stanislav Fomichev

From: YiFei Zhu <[email protected]>

The patch adds a simple wrapper bpf_prog_bind_map around the syscall. And when using libbpf to load a program, it will probe the kernel for the support of this syscall, and scan for the .metadata ELF section and load it as an internal map like a .data section.

Quoted 4 lines

In the case that kernel supports the BPF_PROG_BIND_MAP syscall and a .metadata section exists, the map will be explicitly bound to the program via the syscall immediately after program is loaded. -EEXIST is ignored for this syscall.

Here is the question I have. How important is it that all this metadata is in a separate map? What if libbpf just PROG_BIND_MAP all the maps inside a single BPF .o file to all BPF programs in that file? Including ARRAY maps created for .data, .rodata and .bss, even if the BPF program doesn't use any of the global variables? If it's too extreme, we could do it only for global data maps, leaving explicit map definitions in SEC(".maps") alone. Would that be terrible? Conceptually it makes sense, because when you program in user-space, you expect global variables to be there, even if you don't reference it directly, right? The only downside is that you won't have a special ".metadata" map, rather it will be part of ".rodata" one.

Quoted 11 lines
---
 tools/lib/bpf/bpf.c      |  13 ++++
 tools/lib/bpf/bpf.h      |   8 +++
 tools/lib/bpf/libbpf.c   | 130 ++++++++++++++++++++++++++++++++-------
 tools/lib/bpf/libbpf.map |   1 +
 4 files changed, 131 insertions(+), 21 deletions(-)

[...]

tools/lib/bpf/libbpf.c static int probe_kern_prog_name(void) · line 3623

Quoted 7 lines
tools/lib/bpf/libbpf.c +2 -1
@@ -3592,18 +3619,13 @@ static int probe_kern_prog_name(void)
        return probe_fd(ret);
 }
 
-static int probe_kern_global_data(void)
+static void __probe_create_global_data(int *prog, int *map,
+                                      struct bpf_insn *insns, size_t insns_cnt)

all those static functions are internal, no need for double underscore in names

Quoted 26 lines
tools/lib/bpf/libbpf.c +4 -11
 {
        struct bpf_load_program_attr prg_attr;
        struct bpf_create_map_attr map_attr;
        char *cp, errmsg[STRERR_BUFSIZE];
-       struct bpf_insn insns[] = {
-               BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
-               BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
-               BPF_MOV64_IMM(BPF_REG_0, 0),
-               BPF_EXIT_INSN(),
-       };
-       int ret, map;
+       int err;
 
        memset(&map_attr, 0, sizeof(map_attr));
        map_attr.map_type = BPF_MAP_TYPE_ARRAY;
@@ -3611,26 +3633,40 @@ static int probe_kern_global_data(void)
        map_attr.value_size = 32;
        map_attr.max_entries = 1;
 
-       map = bpf_create_map_xattr(&map_attr);
-       if (map < 0) {
-               ret = -errno;
-               cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
+       *map = bpf_create_map_xattr(&map_attr);
+       if (*map < 0) {
+               err = errno;

tools/lib/bpf/libbpf.c static int probe_kern_global_data(void) · line 3645

Quoted 10 lines
tools/lib/bpf/libbpf.c +4 -3
+               cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
                pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
-                       __func__, cp, -ret);
-               return ret;
+                       __func__, cp, -err);
+               return;
        }
 
-       insns[0].imm = map;
+       insns[0].imm = *map;

you are making confusing and error prone assumptions about the first instruction passed in, I really-really don't like this, super easy to miss and super easy to screw up.

Quoted 12 lines
tools/lib/bpf/libbpf.c +4 -2
        memset(&prg_attr, 0, sizeof(prg_attr));
        prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
        prg_attr.insns = insns;
-       prg_attr.insns_cnt = ARRAY_SIZE(insns);
+       prg_attr.insns_cnt = insns_cnt;
        prg_attr.license = "GPL";
 
-       ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
+       *prog = bpf_load_program_xattr(&prg_attr, NULL, 0);
+}
+

[...]

#6 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

Quoted 14 lines · Andrii Nakryiko
Quoted 8 lines · Stanislav Fomichev

From: YiFei Zhu <[email protected]>

The patch adds a simple wrapper bpf_prog_bind_map around the syscall. And when using libbpf to load a program, it will probe the kernel for the support of this syscall, and scan for the .metadata ELF section and load it as an internal map like a .data section.

Quoted 4 lines

In the case that kernel supports the BPF_PROG_BIND_MAP syscall and a .metadata section exists, the map will be explicitly bound to the program via the syscall immediately after program is loaded. -EEXIST is ignored for this syscall.

Quoted 11 lines

Here is the question I have. How important is it that all this metadata is in a separate map? What if libbpf just PROG_BIND_MAP all the maps inside a single BPF .o file to all BPF programs in that file? Including ARRAY maps created for .data, .rodata and .bss, even if the BPF program doesn't use any of the global variables? If it's too extreme, we could do it only for global data maps, leaving explicit map definitions in SEC(".maps") alone. Would that be terrible? Conceptually it makes sense, because when you program in user-space, you expect global variables to be there, even if you don't reference it directly, right? The only downside is that you won't have a special ".metadata" map, rather it will be part of ".rodata" one.

That's an interesting idea.
Indeed. If we have BPF_PROG_BIND_MAP command why do we need to create another map that behaves exactly like .rodata but has a different name? Wouldn't it be better to identify metadata elements some other way? Like by common prefix/suffix name of the variables or
via grouping them under one structure with standard prefix? Like:
struct bpf_prog_metadata_blahblah {
char compiler_name[];
int my_internal_prog_version;
} = { .compiler_name[] = "clang v.12", ...};

In the past we did this hack for 'version' and for 'license',
but we did it because we didn't have BTF and there was no other way to determine the boundaries.
I think libbpf can and should support multiple rodata sections with arbitrary names, but hardcoding one specific ".metadata" name? Hmm. Let's think through the implications.
Multiple .o support and static linking is coming soon.
When two .o-s with multiple bpf progs are statically linked libbpf won't have any choice but to merge them together under single ".metadata" section and single map that will be BPF_PROG_BIND_MAP-ed to different progs. Meaning that metadata applies to final elf file after linking. It's _not_ per program metadata.
May be we should talk about problem statement and goals.
Do we actually need metadata per program or metadata per single .o or metadata per final .o with multiple .o linked together?
What is this metadata?
If it's just unreferenced by program read only data then no special names or prefixes are needed. We can introduce BPF_PROG_BIND_MAP to bind any map to any program and it would be up to tooling to decide the meaning of the data in the map. For example, bpftool can choose to print all variables from all read only maps that match "bpf_metadata_" prefix, but it will be bpftool convention only and not hard coded in libbpf.

#7 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

Quoted 28 lines · Alexei Starovoitov
Quoted 14 lines · Andrii Nakryiko
Quoted 8 lines · Stanislav Fomichev

From: YiFei Zhu <[email protected]>

The patch adds a simple wrapper bpf_prog_bind_map around the syscall. And when using libbpf to load a program, it will probe the kernel for the support of this syscall, and scan for the .metadata ELF section and load it as an internal map like a .data section.

Quoted 4 lines

In the case that kernel supports the BPF_PROG_BIND_MAP syscall and a .metadata section exists, the map will be explicitly bound to the program via the syscall immediately after program is loaded. -EEXIST is ignored for this syscall.

Quoted 11 lines

Here is the question I have. How important is it that all this metadata is in a separate map? What if libbpf just PROG_BIND_MAP all the maps inside a single BPF .o file to all BPF programs in that file? Including ARRAY maps created for .data, .rodata and .bss, even if the BPF program doesn't use any of the global variables? If it's too extreme, we could do it only for global data maps, leaving explicit map definitions in SEC(".maps") alone. Would that be terrible? Conceptually it makes sense, because when you program in user-space, you expect global variables to be there, even if you don't reference it directly, right? The only downside is that you won't have a special ".metadata" map, rather it will be part of ".rodata" one.

Quoted 3 lines

That's an interesting idea.
Indeed. If we have BPF_PROG_BIND_MAP command why do we need to create another map that behaves exactly like .rodata but has a different name?

That was exactly my thought when I re-read this patch set :)

Quoted 9 lines

Wouldn't it be better to identify metadata elements some other way? Like by common prefix/suffix name of the variables or via grouping them under one structure with standard prefix? Like:
struct bpf_prog_metadata_blahblah {
char compiler_name[];
int my_internal_prog_version;
} = { .compiler_name[] = "clang v.12", ...};

Quoted 4 lines

In the past we did this hack for 'version' and for 'license', but we did it because we didn't have BTF and there was no other way to determine the boundaries.
I think libbpf can and should support multiple rodata sections with

Yep, that's coming, we already have a pretty common .rodata.str1.1 section emitted by Clang for some cases, which libbpf currently ignores, but that should change. Creating a separate map for all such small sections seems excessive, so my plan is to combine them and their BTFs into one, as you assumed below.

Quoted 8 lines

arbitrary names, but hardcoding one specific ".metadata" name? Hmm. Let's think through the implications.
Multiple .o support and static linking is coming soon. When two .o-s with multiple bpf progs are statically linked libbpf won't have any choice but to merge them together under single ".metadata" section and single map that will be BPF_PROG_BIND_MAP-ed to different progs. Meaning that metadata applies to final elf file after linking. It's _not_ per program metadata.

Right, exactly.

Quoted 4 lines

May be we should talk about problem statement and goals. Do we actually need metadata per program or metadata per single .o or metadata per final .o with multiple .o linked together? What is this metadata?

Yep, that's a very valid question. I've also CC'ed Andrey.

Quoted 6 lines

If it's just unreferenced by program read only data then no special names or prefixes are needed. We can introduce BPF_PROG_BIND_MAP to bind any map to any program and it would be up to tooling to decide the meaning of the data in the map. For example, bpftool can choose to print all variables from all read only maps that match "bpf_metadata_" prefix, but it will be bpftool convention only and not hard coded in libbpf.

Agree as well. It feels a bit odd for libbpf to handle ".metadata" specially, given libbpf itself doesn't care about its contents at all.

So thanks for bringing this up, I think this is an important discussion to have.

#8 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

Quoted 6 lines · Andrii Nakryiko
Quoted 4 lines

May be we should talk about problem statement and goals. Do we actually need metadata per program or metadata per single .o or metadata per final .o with multiple .o linked together? What is this metadata?

Yep, that's a very valid question. I've also CC'ed Andrey.

For the libxdp use case, I need metadata per program. But I'm already sticking that in a single section and disambiguating by struct name (just prefixing the function name with a _ ), so I think it's fine to have this kind of "concatenated metadata" per elf file and parse out the per-program information from that. This is similar to the BTF-encoded "metadata" we can do today.

Quoted 7 lines
Quoted 6 lines

If it's just unreferenced by program read only data then no special names or prefixes are needed. We can introduce BPF_PROG_BIND_MAP to bind any map to any program and it would be up to tooling to decide the meaning of the data in the map. For example, bpftool can choose to print all variables from all read only maps that match "bpf_metadata_" prefix, but it will be bpftool convention only and not hard coded in libbpf.

Quoted 5 lines

Agree as well. It feels a bit odd for libbpf to handle ".metadata" specially, given libbpf itself doesn't care about its contents at all.

So thanks for bringing this up, I think this is an important discussion to have.

I'm fine with having this be part of .rodata. One drawback, though, is that if any metadata is defined, it becomes a bit more complicated to use bpf_map__set_initial_value() because that now also has to include the metadata. Any way we can improve upon that?

-Toke

#9 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

Quoted 27 lines · Toke Høiland-Jørgensen
Quoted 6 lines · Andrii Nakryiko
Quoted 4 lines

May be we should talk about problem statement and goals. Do we actually need metadata per program or metadata per single .o or metadata per final .o with multiple .o linked together? What is this metadata?

Yep, that's a very valid question. I've also CC'ed Andrey.

For the libxdp use case, I need metadata per program. But I'm already sticking that in a single section and disambiguating by struct name (just prefixing the function name with a _ ), so I think it's fine to have this kind of "concatenated metadata" per elf file and parse out the per-program information from that. This is similar to the BTF-encoded "metadata" we can do today.

Quoted 10 lines
Quoted 6 lines

If it's just unreferenced by program read only data then no special names or prefixes are needed. We can introduce BPF_PROG_BIND_MAP to bind any map to any program and it would be up to tooling to decide the meaning of the data in the map. For example, bpftool can choose to print all variables from all read only maps that match "bpf_metadata_" prefix, but it will be bpftool convention only and not hard coded in libbpf.

Agree as well. It feels a bit odd for libbpf to handle ".metadata" specially, given libbpf itself doesn't care about its contents at all.

Quoted 7 lines
Quoted 2 lines

So thanks for bringing this up, I think this is an important discussion to have.

I'm fine with having this be part of .rodata. One drawback, though, is that if any metadata is defined, it becomes a bit more complicated to use bpf_map__set_initial_value() because that now also has to include the metadata. Any way we can improve upon that?

I know that skeleton is not an answer for you, so you'll have to find DATASEC and corresponding variable offset and size (libbpf provides APIs for all those operations, but you'll need to combine them together). Then mmap() map and then you can do partial updates. There is no other way to update only portions of an ARRAY map, except through memory-mapping.

Quoted 3 lines

-Toke

#10 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

Quoted 36 lines · Andrii Nakryiko
Quoted 27 lines · Toke Høiland-Jørgensen
Quoted 6 lines · Andrii Nakryiko
Quoted 4 lines

May be we should talk about problem statement and goals. Do we actually need metadata per program or metadata per single .o or metadata per final .o with multiple .o linked together? What is this metadata?

Yep, that's a very valid question. I've also CC'ed Andrey.

For the libxdp use case, I need metadata per program. But I'm already sticking that in a single section and disambiguating by struct name (just prefixing the function name with a _ ), so I think it's fine to have this kind of "concatenated metadata" per elf file and parse out the per-program information from that. This is similar to the BTF-encoded "metadata" we can do today.

Quoted 10 lines
Quoted 6 lines

If it's just unreferenced by program read only data then no special names or prefixes are needed. We can introduce BPF_PROG_BIND_MAP to bind any map to any program and it would be up to tooling to decide the meaning of the data in the map. For example, bpftool can choose to print all variables from all read only maps that match "bpf_metadata_" prefix, but it will be bpftool convention only and not hard coded in libbpf.

Agree as well. It feels a bit odd for libbpf to handle ".metadata" specially, given libbpf itself doesn't care about its contents at all.

Quoted 7 lines
Quoted 2 lines

So thanks for bringing this up, I think this is an important discussion to have.

I'm fine with having this be part of .rodata. One drawback, though, is that if any metadata is defined, it becomes a bit more complicated to use bpf_map__set_initial_value() because that now also has to include the metadata. Any way we can improve upon that?

Quoted 6 lines

I know that skeleton is not an answer for you, so you'll have to find DATASEC and corresponding variable offset and size (libbpf provides APIs for all those operations, but you'll need to combine them together). Then mmap() map and then you can do partial updates. There is no other way to update only portions of an ARRAY map, except through memory-mapping.

Well, I wouldn't mind having to go digging through the section. But is it really possible to pick out and modify parts of it my mmap() before the object is loaded (and the map frozen)? How? I seem to recall we added bpf_map__set_initial_value() because this was *not* possible with the public API?

Also, for this, a bpf_map__get_initial_value() could be a simple way to allow partial modifications. The caller could just get the whole map value, modify it, and set it again afterwards with __set_initial_value(). Any objections to adding that?

-Toke

#11 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

Quoted 46 lines · Toke Høiland-Jørgensen
Quoted 36 lines · Andrii Nakryiko
Quoted 27 lines · Toke Høiland-Jørgensen
Quoted 6 lines · Andrii Nakryiko
Quoted 4 lines

May be we should talk about problem statement and goals. Do we actually need metadata per program or metadata per single .o or metadata per final .o with multiple .o linked together? What is this metadata?

Yep, that's a very valid question. I've also CC'ed Andrey.

For the libxdp use case, I need metadata per program. But I'm already sticking that in a single section and disambiguating by struct name (just prefixing the function name with a _ ), so I think it's fine to have this kind of "concatenated metadata" per elf file and parse out the per-program information from that. This is similar to the BTF-encoded "metadata" we can do today.

Quoted 10 lines
Quoted 6 lines

If it's just unreferenced by program read only data then no special names or prefixes are needed. We can introduce BPF_PROG_BIND_MAP to bind any map to any program and it would be up to tooling to decide the meaning of the data in the map. For example, bpftool can choose to print all variables from all read only maps that match "bpf_metadata_" prefix, but it will be bpftool convention only and not hard coded in libbpf.

Agree as well. It feels a bit odd for libbpf to handle ".metadata" specially, given libbpf itself doesn't care about its contents at all.

Quoted 7 lines
Quoted 2 lines

So thanks for bringing this up, I think this is an important discussion to have.

I'm fine with having this be part of .rodata. One drawback, though, is that if any metadata is defined, it becomes a bit more complicated to use bpf_map__set_initial_value() because that now also has to include the metadata. Any way we can improve upon that?

Quoted 6 lines

I know that skeleton is not an answer for you, so you'll have to find DATASEC and corresponding variable offset and size (libbpf provides APIs for all those operations, but you'll need to combine them together). Then mmap() map and then you can do partial updates. There is no other way to update only portions of an ARRAY map, except through memory-mapping.

Quoted 6 lines

Well, I wouldn't mind having to go digging through the section. But is it really possible to pick out and modify parts of it my mmap() before the object is loaded (and the map frozen)? How? I seem to recall we added bpf_map__set_initial_value() because this was *not* possible with the public API?

Ah, right, .rodata is frozen on load, forgot we are talking about .rodata here.

Quoted 4 lines

Also, for this, a bpf_map__get_initial_value() could be a simple way to allow partial modifications. The caller could just get the whole map value, modify it, and set it again afterwards with __set_initial_value(). Any objections to adding that?

Yeah, I think having an API for getting initial map value makes sense. But please follow the naming convention for getters and call it bpf_map__initial_value().

Quoted 3 lines

-Toke

#12 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

In reply to Toke Høiland-Jørgensen
Quoted 8 lines · Toke Høiland-Jørgensen
Quoted 5 lines · Andrii Nakryiko
Quoted 4 lines

May be we should talk about problem statement and goals. Do we actually need metadata per program or metadata per single .o or metadata per final .o with multiple .o linked together? What is this metadata?

Quoted 8 lines
Quoted 1 line

Yep, that's a very valid question. I've also CC'ed Andrey.

For the libxdp use case, I need metadata per program. But I'm already sticking that in a single section and disambiguating by struct name (just prefixing the function name with a _ ), so I think it's fine to have this kind of "concatenated metadata" per elf file and parse out the per-program information from that. This is similar to the BTF-encoded "metadata" we can do today.

We've come full circle :-)
I think we discussed that approach originally - to stick everything into existing global .data/.rodata and use some variable prefix for the metadata. I'm fine with that approach. The only thing I don't understand is - why bother with the additional .rodata.metadata section and merging?
Can we unconditionally do BPF_PROG_BIND_MAP(.rodata) from libbpf (and ignore the error) and be done?

Sticking to the original question: for our use-case, the metadata is per .o file. I'm not sure how it would work in the 'multiple .o linked together' use case. Ideally, we'd need to preserve all metadata?

Quoted 10 lines
Quoted 10 lines
Quoted 6 lines

If it's just unreferenced by program read only data then no special names or prefixes are needed. We can introduce BPF_PROG_BIND_MAP to bind any map to any program and it would be up to tooling to decide the meaning of the data in the map. For example, bpftool can choose to print all variables from all read only maps that match "bpf_metadata_" prefix, but it will be bpftool convention only and not hard coded in libbpf.

Agree as well. It feels a bit odd for libbpf to handle ".metadata" specially, given libbpf itself doesn't care about its contents at all.

Quoted 7 lines
Quoted 2 lines

So thanks for bringing this up, I think this is an important discussion to have.

I'm fine with having this be part of .rodata. One drawback, though, is that if any metadata is defined, it becomes a bit more complicated to use bpf_map__set_initial_value() because that now also has to include the metadata. Any way we can improve upon that?

Right. One additional thing we wanted this metadata to have is the comm of the process who loaded this bpf program (to be filled/added by libbpf).
I suppose .rodata.metadata section can help with that?

#13 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

Quoted 18 lines · Stanislav Fomichev
Quoted 8 lines · Toke Høiland-Jørgensen
Quoted 5 lines · Andrii Nakryiko
Quoted 4 lines

May be we should talk about problem statement and goals. Do we actually need metadata per program or metadata per single .o or metadata per final .o with multiple .o linked together? What is this metadata?

Quoted 8 lines
Quoted 1 line

Yep, that's a very valid question. I've also CC'ed Andrey.

For the libxdp use case, I need metadata per program. But I'm already sticking that in a single section and disambiguating by struct name (just prefixing the function name with a _ ), so I think it's fine to have this kind of "concatenated metadata" per elf file and parse out the per-program information from that. This is similar to the BTF-encoded "metadata" we can do today.

Quoted 4 lines

We've come full circle :-)
I think we discussed that approach originally - to stick everything into existing global .data/.rodata and use some variable prefix for the metadata. I'm fine with that approach. The only thing I don't

That's what we wanted all along, but the problem was with keeping reference to bpf_map from bpf_prog. We eventually gave up and concluded that extra BPF command is necessary. But somewhere along the road we somehow concluded we need an entire new special map/section, and I didn't realize at first (and it seems it wasn't just me) that the latter part is unnecessary.

Quoted 4 lines

understand is - why bother with the additional .rodata.metadata section and merging?
Can we unconditionally do BPF_PROG_BIND_MAP(.rodata) from libbpf (and ignore the error) and be done?

That's exactly what we are proposing, to stick to .rodata, instead of having extra .metadata section. Multiple .rodata/.data sections are orthogonal concerns, which we need to solve as well, because the compiler does emit many of them in some cases. So in that context, once we support multiple .rodata's, it would be possible to have metadata-only "sub-sections". But we don't have to do that, keeping everything simple and put into .rodata works just fine.

Quoted 4 lines

Sticking to the original question: for our use-case, the metadata is per .o file. I'm not sure how it would work in the 'multiple .o linked together' use case. Ideally, we'd need to preserve all metadata?

Just like in user-space, when you have multiple .c files compiled into .o files and later linked into a final library or binary, all the .data and .rodata sections are combined. That's what will happen with BPF .o files as well. So it will be automatically preserved, as you seem to want.

Quoted 14 lines
Quoted 14 lines
Quoted 13 lines
Quoted 7 lines

If it's just unreferenced by program read only data then no special names or prefixes are needed. We can introduce BPF_PROG_BIND_MAP to bind any map to any program and it would be up to tooling to decide the meaning of the data in the map. For example, bpftool can choose to print all variables from all read only maps that match "bpf_metadata_" prefix, but it will be bpftool convention only and not hard coded in libbpf.

Agree as well. It feels a bit odd for libbpf to handle ".metadata" specially, given libbpf itself doesn't care about its contents at all.

So thanks for bringing this up, I think this is an important discussion to have.

Quoted 8 lines
Quoted 4 lines

I'm fine with having this be part of .rodata. One drawback, though, is that if any metadata is defined, it becomes a bit more complicated to use bpf_map__set_initial_value() because that now also has to include the metadata. Any way we can improve upon that?

Right. One additional thing we wanted this metadata to have is the comm of the process who loaded this bpf program (to be filled/added by libbpf).
I suppose .rodata.metadata section can help with that?

.rodata.metadata has nothing to do with this. I'm also not sure whether it's a responsibility of libbpf to provide process's comm as a metadata, to be honest. Next thing it will be user name/user id, then cgroup name, then some other application-level concept and so on. I'd prefer to keep it simple and let applications handle that for themselves. Luckily, using a BPF skeleton this is **extremely** easy.

#14 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

In reply to Andrii Nakryiko

Andrii Nakryiko <[email protected]> [Fri, 2020-09-04 16:19 -0700]:

Quoted 65 lines
Quoted 28 lines · Alexei Starovoitov
Quoted 14 lines · Andrii Nakryiko
Quoted 8 lines · Stanislav Fomichev

From: YiFei Zhu <[email protected]>

The patch adds a simple wrapper bpf_prog_bind_map around the syscall. And when using libbpf to load a program, it will probe the kernel for the support of this syscall, and scan for the .metadata ELF section and load it as an internal map like a .data section.

Quoted 4 lines

In the case that kernel supports the BPF_PROG_BIND_MAP syscall and a .metadata section exists, the map will be explicitly bound to the program via the syscall immediately after program is loaded. -EEXIST is ignored for this syscall.

Quoted 11 lines

Here is the question I have. How important is it that all this metadata is in a separate map? What if libbpf just PROG_BIND_MAP all the maps inside a single BPF .o file to all BPF programs in that file? Including ARRAY maps created for .data, .rodata and .bss, even if the BPF program doesn't use any of the global variables? If it's too extreme, we could do it only for global data maps, leaving explicit map definitions in SEC(".maps") alone. Would that be terrible? Conceptually it makes sense, because when you program in user-space, you expect global variables to be there, even if you don't reference it directly, right? The only downside is that you won't have a special ".metadata" map, rather it will be part of ".rodata" one.

Quoted 3 lines

That's an interesting idea.
Indeed. If we have BPF_PROG_BIND_MAP command why do we need to create another map that behaves exactly like .rodata but has a different name?

That was exactly my thought when I re-read this patch set :)

Quoted 9 lines

Wouldn't it be better to identify metadata elements some other way? Like by common prefix/suffix name of the variables or via grouping them under one structure with standard prefix? Like:
struct bpf_prog_metadata_blahblah {
char compiler_name[];
int my_internal_prog_version;
} = { .compiler_name[] = "clang v.12", ...};

Quoted 4 lines

In the past we did this hack for 'version' and for 'license', but we did it because we didn't have BTF and there was no other way to determine the boundaries.
I think libbpf can and should support multiple rodata sections with

Yep, that's coming, we already have a pretty common .rodata.str1.1 section emitted by Clang for some cases, which libbpf currently ignores, but that should change. Creating a separate map for all such small sections seems excessive, so my plan is to combine them and their BTFs into one, as you assumed below.

Quoted 8 lines

arbitrary names, but hardcoding one specific ".metadata" name? Hmm. Let's think through the implications.
Multiple .o support and static linking is coming soon. When two .o-s with multiple bpf progs are statically linked libbpf won't have any choice but to merge them together under single ".metadata" section and single map that will be BPF_PROG_BIND_MAP-ed to different progs. Meaning that metadata applies to final elf file after linking. It's _not_ per program metadata.

Quoted 8 lines

Right, exactly.

Quoted 4 lines

May be we should talk about problem statement and goals. Do we actually need metadata per program or metadata per single .o or metadata per final .o with multiple .o linked together? What is this metadata?

Yep, that's a very valid question. I've also CC'ed Andrey.

From my side the problem statement is to be able to save a bunch of metadata fields per BPF object file (I don't distinguish "final .o" and "multiple .o linked together" since we have only the former in prod).

Specifically things like oncall team who owns the programs in the object (the most important info), build info (repository revision, build commit time, build time), etc. The plan is to integrate it with build system and be able to quickly identify source code and point of contact for any particular program.

All these things are always the same for all programs in one object. It may change in the future, but at the moment I'm not aware of any use-case where these things can be different for different programs in the same object.

I don't have strong preferences on the implementation side as long as it covers the use-case, e.g. the one in the patch set would work FWIW.

Quoted 11 lines
Quoted 6 lines

If it's just unreferenced by program read only data then no special names or prefixes are needed. We can introduce BPF_PROG_BIND_MAP to bind any map to any program and it would be up to tooling to decide the meaning of the data in the map. For example, bpftool can choose to print all variables from all read only maps that match "bpf_metadata_" prefix, but it will be bpftool convention only and not hard coded in libbpf.

Agree as well. It feels a bit odd for libbpf to handle ".metadata" specially, given libbpf itself doesn't care about its contents at all.

So thanks for bringing this up, I think this is an important discussion to have.

Signature · 1 line
Andrey Ignatov
#15 lore raw

Re: [PATCH bpf-next v3 3/8] libbpf: Add BPF_PROG_BIND_MAP syscall and use it on .metadata section

Quoted 74 lines · Andrey Ignatov

Andrii Nakryiko <[email protected]> [Fri, 2020-09-04 16:19 -0700]:

Quoted 72 lines
Quoted 28 lines · Alexei Starovoitov
Quoted 14 lines · Andrii Nakryiko
Quoted 8 lines · Stanislav Fomichev

From: YiFei Zhu <[email protected]>

The patch adds a simple wrapper bpf_prog_bind_map around the syscall. And when using libbpf to load a program, it will probe the kernel for the support of this syscall, and scan for the .metadata ELF section and load it as an internal map like a .data section.

Quoted 4 lines

In the case that kernel supports the BPF_PROG_BIND_MAP syscall and a .metadata section exists, the map will be explicitly bound to the program via the syscall immediately after program is loaded. -EEXIST is ignored for this syscall.

Quoted 11 lines

Here is the question I have. How important is it that all this metadata is in a separate map? What if libbpf just PROG_BIND_MAP all the maps inside a single BPF .o file to all BPF programs in that file? Including ARRAY maps created for .data, .rodata and .bss, even if the BPF program doesn't use any of the global variables? If it's too extreme, we could do it only for global data maps, leaving explicit map definitions in SEC(".maps") alone. Would that be terrible? Conceptually it makes sense, because when you program in user-space, you expect global variables to be there, even if you don't reference it directly, right? The only downside is that you won't have a special ".metadata" map, rather it will be part of ".rodata" one.

Quoted 3 lines

That's an interesting idea.
Indeed. If we have BPF_PROG_BIND_MAP command why do we need to create another map that behaves exactly like .rodata but has a different name?

That was exactly my thought when I re-read this patch set :)

Quoted 9 lines

Wouldn't it be better to identify metadata elements some other way? Like by common prefix/suffix name of the variables or via grouping them under one structure with standard prefix? Like:
struct bpf_prog_metadata_blahblah {
char compiler_name[];
int my_internal_prog_version;
} = { .compiler_name[] = "clang v.12", ...};

Quoted 4 lines

In the past we did this hack for 'version' and for 'license', but we did it because we didn't have BTF and there was no other way to determine the boundaries.
I think libbpf can and should support multiple rodata sections with

Yep, that's coming, we already have a pretty common .rodata.str1.1 section emitted by Clang for some cases, which libbpf currently ignores, but that should change. Creating a separate map for all such small sections seems excessive, so my plan is to combine them and their BTFs into one, as you assumed below.

Quoted 8 lines

arbitrary names, but hardcoding one specific ".metadata" name? Hmm. Let's think through the implications.
Multiple .o support and static linking is coming soon. When two .o-s with multiple bpf progs are statically linked libbpf won't have any choice but to merge them together under single ".metadata" section and single map that will be BPF_PROG_BIND_MAP-ed to different progs. Meaning that metadata applies to final elf file after linking. It's _not_ per program metadata.

Right, exactly.

Quoted 4 lines

May be we should talk about problem statement and goals. Do we actually need metadata per program or metadata per single .o or metadata per final .o with multiple .o linked together? What is this metadata?

Quoted 5 lines
Quoted 1 line

Yep, that's a very valid question. I've also CC'ed Andrey.

From my side the problem statement is to be able to save a bunch of metadata fields per BPF object file (I don't distinguish "final .o" and "multiple .o linked together" since we have only the former in prod).

We don't *yet*. But reading below, you have the entire BPF application (i.e., a collection of maps, variables and programs) in mind, not specifically single .c file compiled into a single .o file. So everything works out, I think.

Quoted 29 lines

Specifically things like oncall team who owns the programs in the object (the most important info), build info (repository revision, build commit time, build time), etc. The plan is to integrate it with build system and be able to quickly identify source code and point of contact for any particular program.

All these things are always the same for all programs in one object. It may change in the future, but at the moment I'm not aware of any use-case where these things can be different for different programs in the same object.

I don't have strong preferences on the implementation side as long as it covers the use-case, e.g. the one in the patch set would work FWIW.

Quoted 11 lines
Quoted 6 lines

If it's just unreferenced by program read only data then no special names or prefixes are needed. We can introduce BPF_PROG_BIND_MAP to bind any map to any program and it would be up to tooling to decide the meaning of the data in the map. For example, bpftool can choose to print all variables from all read only maps that match "bpf_metadata_" prefix, but it will be bpftool convention only and not hard coded in libbpf.

Agree as well. It feels a bit odd for libbpf to handle ".metadata" specially, given libbpf itself doesn't care about its contents at all.

So thanks for bringing this up, I think this is an important discussion to have.

--
Andrey Ignatov

#16 lore raw

PATCH v3 4/8 libbpf: implement bpf_prog_find_metadata

In reply to Stanislav Fomichev

This is a low-level function (hence in bpf.c) to find out the metadata map id for the provided program fd.
It will be used in the next commits from bpftool.

Cc Toke Høiland-Jørgensen <[email protected]>
Cc YiFei Zhu <[email protected]>
---
 tools/lib/bpf/bpf.c      | 74 ++++++++++++++++++++++++++++++++++++++++
 tools/lib/bpf/bpf.h      |  1 +
 tools/lib/bpf/libbpf.map |  1 +
 3 files changed, 76 insertions(+)
tools/lib/bpf/bpf.c +74 -0
index 5f6c5676cc45..01c0ede1625d 100644
@@ -885,3 +885,77 @@ int bpf_prog_bind_map(int prog_fd, int map_fd,
 
 	return sys_bpf(BPF_PROG_BIND_MAP, &attr, sizeof(attr));
 }
+
+int bpf_prog_find_metadata(int prog_fd)
+{
+	struct bpf_prog_info prog_info = {};
+	struct bpf_map_info map_info;
+	__u32 prog_info_len;
+	__u32 map_info_len;
+	int saved_errno;
+	__u32 *map_ids;
+	int nr_maps;
+	int map_fd;
+	int ret;
+	int i;
+
+	prog_info_len = sizeof(prog_info);
+
+	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
+	if (ret)
+		return ret;
+
+	if (!prog_info.nr_map_ids)
+		return -1;
+
+	map_ids = calloc(prog_info.nr_map_ids, sizeof(__u32));
+	if (!map_ids)
+		return -1;
+
+	nr_maps = prog_info.nr_map_ids;
+	memset(&prog_info, 0, sizeof(prog_info));
+	prog_info.nr_map_ids = nr_maps;
+	prog_info.map_ids = ptr_to_u64(map_ids);
+	prog_info_len = sizeof(prog_info);
+
+	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
+	if (ret)
+		goto free_map_ids;
+
+	ret = -1;
+	for (i = 0; i < prog_info.nr_map_ids; i++) {
+		map_fd = bpf_map_get_fd_by_id(map_ids[i]);
+		if (map_fd < 0) {
+			ret = -1;
+			goto free_map_ids;
+		}
+
+		memset(&map_info, 0, sizeof(map_info));
+		map_info_len = sizeof(map_info);
+		ret = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
+		saved_errno = errno;
+		close(map_fd);
+		errno = saved_errno;
+		if (ret)
+			goto free_map_ids;
+
+		if (map_info.type != BPF_MAP_TYPE_ARRAY)
+			continue;
+		if (map_info.key_size != sizeof(int))
+			continue;
+		if (map_info.max_entries != 1)
+			continue;
+		if (!map_info.btf_value_type_id)
+			continue;
+		if (!strstr(map_info.name, ".metadata"))
+			continue;
+
+		ret = map_ids[i];
+		break;
+	}
+
+
+free_map_ids:
+	free(map_ids);
+	return ret;
+}
tools/lib/bpf/bpf.h +1 -0
index 8c1ac4b42f90..8982ffa7cfd2 100644
@@ -251,6 +251,7 @@ struct bpf_prog_bind_opts {
 
 LIBBPF_API int bpf_prog_bind_map(int prog_fd, int map_fd,
 				 const struct bpf_prog_bind_opts *opts);
+LIBBPF_API int bpf_prog_find_metadata(int prog_fd);
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
tools/lib/bpf/libbpf.map +1 -0
index 529b99c0c2c3..b7a40f543b2b 100644
@@ -307,4 +307,5 @@ LIBBPF_0.2.0 {
 		perf_buffer__buffer_fd;
 		perf_buffer__epoll_fd;
 		perf_buffer__consume_buffer;
+		bpf_prog_find_metadata;
 } LIBBPF_0.1.0;
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
#17 lore raw

Re: [PATCH bpf-next v3 4/8] libbpf: implement bpf_prog_find_metadata

Quoted 64 lines · Stanislav Fomichev

This is a low-level function (hence in bpf.c) to find out the metadata map id for the provided program fd.
It will be used in the next commits from bpftool.

Cc Toke Høiland-Jørgensen <[email protected]>
Cc YiFei Zhu <[email protected]>
---
 tools/lib/bpf/bpf.c      | 74 ++++++++++++++++++++++++++++++++++++++++
 tools/lib/bpf/bpf.h      |  1 +
 tools/lib/bpf/libbpf.map |  1 +
 3 files changed, 76 insertions(+)
tools/lib/bpf/bpf.c +43 -0
index 5f6c5676cc45..01c0ede1625d 100644
@@ -885,3 +885,77 @@ int bpf_prog_bind_map(int prog_fd, int map_fd,
 
 	return sys_bpf(BPF_PROG_BIND_MAP, &attr, sizeof(attr));
 }
+
+int bpf_prog_find_metadata(int prog_fd)
+{
+	struct bpf_prog_info prog_info = {};
+	struct bpf_map_info map_info;
+	__u32 prog_info_len;
+	__u32 map_info_len;
+	int saved_errno;
+	__u32 *map_ids;
+	int nr_maps;
+	int map_fd;
+	int ret;
+	int i;
+
+	prog_info_len = sizeof(prog_info);
+
+	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
+	if (ret)
+		return ret;
+
+	if (!prog_info.nr_map_ids)
+		return -1;
+
+	map_ids = calloc(prog_info.nr_map_ids, sizeof(__u32));
+	if (!map_ids)
+		return -1;
+
+	nr_maps = prog_info.nr_map_ids;
+	memset(&prog_info, 0, sizeof(prog_info));
+	prog_info.nr_map_ids = nr_maps;
+	prog_info.map_ids = ptr_to_u64(map_ids);
+	prog_info_len = sizeof(prog_info);
+
+	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
+	if (ret)
+		goto free_map_ids;
+
+	ret = -1;
+	for (i = 0; i < prog_info.nr_map_ids; i++) {
+		map_fd = bpf_map_get_fd_by_id(map_ids[i]);
+		if (map_fd < 0) {
+			ret = -1;
+			goto free_map_ids;

tools/lib/bpf/bpf.c int bpf_prog_bind_map(int prog_fd, int map_fd, · line 940

Quoted 10 lines
tools/lib/bpf/bpf.c +10 -0
+		}
+
+		memset(&map_info, 0, sizeof(map_info));
+		map_info_len = sizeof(map_info);
+		ret = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
+		saved_errno = errno;
+		close(map_fd);
+		errno = saved_errno;
+		if (ret)
+			goto free_map_ids;

If you get to this point on the last entry in the loop, ret will be 0, and any of the continue statements below will end the loop, causing the whole function to return 0. While this is not technically a valid ID, it still seems odd that the function returns -1 on all error conditions except this one.

Also, it would be good to be able to unambiguously distinguish between "this program has no metadata associated" and "something went wrong while querying the kernel for metadata (e.g., permission error)". So something that amounts to a -ENOENT return; I guess turning all return values into negative error codes would do that (and also do away with the need for the saved_errno dance above), but id does clash a bit with the convention in the rest of the file (where all the other functions just return -1 and set errno)...

-Toke

#18 lore raw

Re: [PATCH bpf-next v3 4/8] libbpf: implement bpf_prog_find_metadata

Quoted 83 lines · Toke H�iland-J�rgensen
Quoted 64 lines · Stanislav Fomichev

This is a low-level function (hence in bpf.c) to find out the metadata map id for the provided program fd.
It will be used in the next commits from bpftool.

Cc Toke H�iland-J�rgensen <[email protected]>
Cc YiFei Zhu <[email protected]>
---
 tools/lib/bpf/bpf.c      | 74 ++++++++++++++++++++++++++++++++++++++++
 tools/lib/bpf/bpf.h      |  1 +
 tools/lib/bpf/libbpf.map |  1 +
 3 files changed, 76 insertions(+)
tools/lib/bpf/bpf.c +43 -0
index 5f6c5676cc45..01c0ede1625d 100644
@@ -885,3 +885,77 @@ int bpf_prog_bind_map(int prog_fd, int map_fd,
 
 	return sys_bpf(BPF_PROG_BIND_MAP, &attr, sizeof(attr));
 }
+
+int bpf_prog_find_metadata(int prog_fd)
+{
+	struct bpf_prog_info prog_info = {};
+	struct bpf_map_info map_info;
+	__u32 prog_info_len;
+	__u32 map_info_len;
+	int saved_errno;
+	__u32 *map_ids;
+	int nr_maps;
+	int map_fd;
+	int ret;
+	int i;
+
+	prog_info_len = sizeof(prog_info);
+
+	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
+	if (ret)
+		return ret;
+
+	if (!prog_info.nr_map_ids)
+		return -1;
+
+	map_ids = calloc(prog_info.nr_map_ids, sizeof(__u32));
+	if (!map_ids)
+		return -1;
+
+	nr_maps = prog_info.nr_map_ids;
+	memset(&prog_info, 0, sizeof(prog_info));
+	prog_info.nr_map_ids = nr_maps;
+	prog_info.map_ids = ptr_to_u64(map_ids);
+	prog_info_len = sizeof(prog_info);
+
+	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
+	if (ret)
+		goto free_map_ids;
+
+	ret = -1;
+	for (i = 0; i < prog_info.nr_map_ids; i++) {
+		map_fd = bpf_map_get_fd_by_id(map_ids[i]);
+		if (map_fd < 0) {
+			ret = -1;
+			goto free_map_ids;

tools/lib/bpf/bpf.c int bpf_prog_bind_map(int prog_fd, int map_fd, · line 940

Quoted 10 lines
tools/lib/bpf/bpf.c +10 -0
+		}
+
+		memset(&map_info, 0, sizeof(map_info));
+		map_info_len = sizeof(map_info);
+		ret = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
+		saved_errno = errno;
+		close(map_fd);
+		errno = saved_errno;
+		if (ret)
+			goto free_map_ids;

If you get to this point on the last entry in the loop, ret will be 0, and any of the continue statements below will end the loop, causing the whole function to return 0. While this is not technically a valid ID, it still seems odd that the function returns -1 on all error conditions except this one.

Quoted 8 lines

Also, it would be good to be able to unambiguously distinguish between "this program has no metadata associated" and "something went wrong while querying the kernel for metadata (e.g., permission error)". So something that amounts to a -ENOENT return; I guess turning all return values into negative error codes would do that (and also do away with the need for the saved_errno dance above), but id does clash a bit with the convention in the rest of the file (where all the other functions just return -1 and set errno)...

Good point. I think I can change the function signature to:

int bpf_prog_find_metadata(int prog_fd, int *map_id)

And explicitly return map_id via argument. Then the ret can be used as -1/0 error and I can set errno appropriately where it makes sense. This will better match the convention we have in this file.

Will respin v4 later this week to give people opportunity to look at the other patches in the series. Thanks!

#19 lore raw

Re: [PATCH bpf-next v3 4/8] libbpf: implement bpf_prog_find_metadata

Quoted 92 lines · On Mon, Aug 31, 2020 at 08:40:01AM -0700, [email protected] wrote:
Quoted 83 lines · Toke H�iland-J�rgensen
Quoted 64 lines · Stanislav Fomichev

This is a low-level function (hence in bpf.c) to find out the metadata map id for the provided program fd.
It will be used in the next commits from bpftool.

Cc Toke H�iland-J�rgensen <[email protected]>
Cc YiFei Zhu <[email protected]>
---
 tools/lib/bpf/bpf.c      | 74 ++++++++++++++++++++++++++++++++++++++++
 tools/lib/bpf/bpf.h      |  1 +
 tools/lib/bpf/libbpf.map |  1 +
 3 files changed, 76 insertions(+)
tools/lib/bpf/bpf.c +43 -0
index 5f6c5676cc45..01c0ede1625d 100644
@@ -885,3 +885,77 @@ int bpf_prog_bind_map(int prog_fd, int map_fd,
 
 	return sys_bpf(BPF_PROG_BIND_MAP, &attr, sizeof(attr));
 }
+
+int bpf_prog_find_metadata(int prog_fd)
+{
+	struct bpf_prog_info prog_info = {};
+	struct bpf_map_info map_info;
+	__u32 prog_info_len;
+	__u32 map_info_len;
+	int saved_errno;
+	__u32 *map_ids;
+	int nr_maps;
+	int map_fd;
+	int ret;
+	int i;
+
+	prog_info_len = sizeof(prog_info);
+
+	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
+	if (ret)
+		return ret;
+
+	if (!prog_info.nr_map_ids)
+		return -1;
+
+	map_ids = calloc(prog_info.nr_map_ids, sizeof(__u32));
+	if (!map_ids)
+		return -1;
+
+	nr_maps = prog_info.nr_map_ids;
+	memset(&prog_info, 0, sizeof(prog_info));
+	prog_info.nr_map_ids = nr_maps;
+	prog_info.map_ids = ptr_to_u64(map_ids);
+	prog_info_len = sizeof(prog_info);
+
+	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
+	if (ret)
+		goto free_map_ids;
+
+	ret = -1;
+	for (i = 0; i < prog_info.nr_map_ids; i++) {
+		map_fd = bpf_map_get_fd_by_id(map_ids[i]);
+		if (map_fd < 0) {
+			ret = -1;
+			goto free_map_ids;

tools/lib/bpf/bpf.c int bpf_prog_bind_map(int prog_fd, int map_fd, · line 940

Quoted 10 lines
tools/lib/bpf/bpf.c +10 -0
+		}
+
+		memset(&map_info, 0, sizeof(map_info));
+		map_info_len = sizeof(map_info);
+		ret = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
+		saved_errno = errno;
+		close(map_fd);
+		errno = saved_errno;
+		if (ret)
+			goto free_map_ids;

If you get to this point on the last entry in the loop, ret will be 0, and any of the continue statements below will end the loop, causing the whole function to return 0. While this is not technically a valid ID, it still seems odd that the function returns -1 on all error conditions except this one.

Quoted 8 lines

Also, it would be good to be able to unambiguously distinguish between "this program has no metadata associated" and "something went wrong while querying the kernel for metadata (e.g., permission error)". So something that amounts to a -ENOENT return; I guess turning all return values into negative error codes would do that (and also do away with the need for the saved_errno dance above), but id does clash a bit with the convention in the rest of the file (where all the other functions just return -1 and set errno)...

Quoted 7 lines

Good point. I think I can change the function signature to:

int bpf_prog_find_metadata(int prog_fd, int *map_id)

And explicitly return map_id via argument. Then the ret can be used as -1/0 error and I can set errno appropriately where it makes sense. This will better match the convention we have in this file.

I don't feel great about this libbpf api. bpftool already does bpf_obj_get_info_by_fd() for progs and for maps. This extra step and extra set of syscalls is redundant work. I think it's better to be done as part of bpftool. It doesn't quite fit as generic api.

#20 lore raw

Re: [PATCH bpf-next v3 4/8] libbpf: implement bpf_prog_find_metadata

Quoted 101 lines · Alexei Starovoitov
Quoted 92 lines · On Mon, Aug 31, 2020 at 08:40:01AM -0700, [email protected] wrote:
Quoted 83 lines · Toke H�iland-J�rgensen
Quoted 64 lines · Stanislav Fomichev

This is a low-level function (hence in bpf.c) to find out the metadata map id for the provided program fd.
It will be used in the next commits from bpftool.

Cc Toke H�iland-J�rgensen <[email protected]>
Cc YiFei Zhu <[email protected]>
---
 tools/lib/bpf/bpf.c      | 74 ++++++++++++++++++++++++++++++++++++++++
 tools/lib/bpf/bpf.h      |  1 +
 tools/lib/bpf/libbpf.map |  1 +
 3 files changed, 76 insertions(+)
tools/lib/bpf/bpf.c +43 -0
index 5f6c5676cc45..01c0ede1625d 100644
@@ -885,3 +885,77 @@ int bpf_prog_bind_map(int prog_fd, int map_fd,
 
 	return sys_bpf(BPF_PROG_BIND_MAP, &attr, sizeof(attr));
 }
+
+int bpf_prog_find_metadata(int prog_fd)
+{
+	struct bpf_prog_info prog_info = {};
+	struct bpf_map_info map_info;
+	__u32 prog_info_len;
+	__u32 map_info_len;
+	int saved_errno;
+	__u32 *map_ids;
+	int nr_maps;
+	int map_fd;
+	int ret;
+	int i;
+
+	prog_info_len = sizeof(prog_info);
+
+	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
+	if (ret)
+		return ret;
+
+	if (!prog_info.nr_map_ids)
+		return -1;
+
+	map_ids = calloc(prog_info.nr_map_ids, sizeof(__u32));
+	if (!map_ids)
+		return -1;
+
+	nr_maps = prog_info.nr_map_ids;
+	memset(&prog_info, 0, sizeof(prog_info));
+	prog_info.nr_map_ids = nr_maps;
+	prog_info.map_ids = ptr_to_u64(map_ids);
+	prog_info_len = sizeof(prog_info);
+
+	ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
+	if (ret)
+		goto free_map_ids;
+
+	ret = -1;
+	for (i = 0; i < prog_info.nr_map_ids; i++) {
+		map_fd = bpf_map_get_fd_by_id(map_ids[i]);
+		if (map_fd < 0) {
+			ret = -1;
+			goto free_map_ids;

tools/lib/bpf/bpf.c int bpf_prog_bind_map(int prog_fd, int map_fd, · line 940

Quoted 10 lines
tools/lib/bpf/bpf.c +10 -0
+		}
+
+		memset(&map_info, 0, sizeof(map_info));
+		map_info_len = sizeof(map_info);
+		ret = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
+		saved_errno = errno;
+		close(map_fd);
+		errno = saved_errno;
+		if (ret)
+			goto free_map_ids;

If you get to this point on the last entry in the loop, ret will be 0, and any of the continue statements below will end the loop, causing the whole function to return 0. While this is not technically a valid ID, it still seems odd that the function returns -1 on all error conditions except this one.

Quoted 8 lines

Also, it would be good to be able to unambiguously distinguish between "this program has no metadata associated" and "something went wrong while querying the kernel for metadata (e.g., permission error)". So something that amounts to a -ENOENT return; I guess turning all return values into negative error codes would do that (and also do away with the need for the saved_errno dance above), but id does clash a bit with the convention in the rest of the file (where all the other functions just return -1 and set errno)...

Quoted 7 lines

Good point. I think I can change the function signature to:

int bpf_prog_find_metadata(int prog_fd, int *map_id)

And explicitly return map_id via argument. Then the ret can be used as -1/0 error and I can set errno appropriately where it makes sense. This will better match the convention we have in this file.

Quoted 5 lines

I don't feel great about this libbpf api. bpftool already does bpf_obj_get_info_by_fd() for progs and for maps. This extra step and extra set of syscalls is redundant work. I think it's better to be done as part of bpftool. It doesn't quite fit as generic api.

Why not? We are establishing a convention for how to store (and read) metadata from a program; by having an API to get this, we make sure that every application that wants to access this metadata agrees on how to do so. If we don't have it, people will have to go look at bpftool code, and we'll end up with copied code snippets, which seems less than ideal.

-Toke

#21 lore raw

Re: [PATCH bpf-next v3 4/8] libbpf: implement bpf_prog_find_metadata

Quoted 8 lines · Toke Høiland-Jørgensen
Quoted 6 lines

I don't feel great about this libbpf api. bpftool already does bpf_obj_get_info_by_fd() for progs and for maps. This extra step and extra set of syscalls is redundant work. I think it's better to be done as part of bpftool. It doesn't quite fit as generic api.

Why not?

It's a helper function on top of already provided api and implemented in the most brute force and inefficient way.
bpftool implementation of the same will be more efficient.

Quoted 2 lines

so. If we don't have it, people will have to go look at bpftool code, and we'll end up with copied code snippets, which seems less than ideal.

I'd like to see the real use case first before hypothesising.

#22 lore raw

Re: [PATCH bpf-next v3 4/8] libbpf: implement bpf_prog_find_metadata

Quoted 8 lines · Alexei Starovoitov
Quoted 7 lines · Toke Høiland-Jørgensen
Quoted 6 lines

I don't feel great about this libbpf api. bpftool already does bpf_obj_get_info_by_fd() for progs and for maps. This extra step and extra set of syscalls is redundant work. I think it's better to be done as part of bpftool. It doesn't quite fit as generic api.

Quoted 5 lines
Quoted 1 line

Why not?

It's a helper function on top of already provided api and implemented in the most brute force and inefficient way.
bpftool implementation of the same will be more efficient.

Right, certainly wouldn't mind something more efficient. But to me, the inefficiency is outweighed by convenience of having this canonical reference for 'this is the metadata map'.

Quoted 4 lines
Quoted 2 lines

so. If we don't have it, people will have to go look at bpftool code, and we'll end up with copied code snippets, which seems less than ideal.

I'd like to see the real use case first before hypothesising.

For me, that would be incorporating support for this into libxdp/xdp-tools; which was the reason I asked for this to be split into a separate API in the first place. But okay, not going to keep arguing about this, I can copy-paste code as well as the next person.

-Toke

#23 lore raw

PATCH v3 5/8 bpftool: support dumping metadata

In reply to Stanislav Fomichev

From: YiFei Zhu <[email protected]>

Added a flag "--metadata" to bpftool prog list to dump the metadata contents. For some formatting some BTF code is put directly in the metadata dumping. Sanity checks on the map and the kind of the btf_type to make sure we are actually dumping what we are expecting.

A helper jsonw_reset is added to json writer so we can reuse the same json writer without having extraneous commas.

Sample output:

  $ bpftool prog --metadata
  6: cgroup_skb  name prog  tag bcf7977d3b93787c  gpl
  [...]
  	btf_id 4
  	metadata:
  		metadata_a = "foo"
  		metadata_b = 1
  $ bpftool prog --metadata --json --pretty
  [{
          "id": 6,
  [...]
          "btf_id": 4,
          "metadata": {
              "metadata_a": "foo",
              "metadata_b": 1
          }
      }
  ]
---
 tools/bpf/bpftool/json_writer.c |   6 ++
 tools/bpf/bpftool/json_writer.h |   3 +
 tools/bpf/bpftool/main.c        |  10 +++
 tools/bpf/bpftool/main.h        |   1 +
 tools/bpf/bpftool/prog.c        | 130 ++++++++++++++++++++++++++++++++
 5 files changed, 150 insertions(+)
tools/bpf/bpftool/json_writer.c +6 -0
index 86501cd3c763..7fea83bedf48 100644
@@ -119,6 +119,12 @@ void jsonw_pretty(json_writer_t *self, bool on)
 	self->pretty = on;
 }
 
+void jsonw_reset(json_writer_t *self)
+{
+	assert(self->depth == 0);
+	self->sep = '\0';
+}
+
 /* Basic blocks */
 static void jsonw_begin(json_writer_t *self, int c)
 {
tools/bpf/bpftool/json_writer.h +3 -0
index 35cf1f00f96c..8ace65cdb92f 100644
@@ -27,6 +27,9 @@ void jsonw_destroy(json_writer_t **self_p);
 /* Cause output to have pretty whitespace */
 void jsonw_pretty(json_writer_t *self, bool on);
 
+/* Reset separator to create new JSON */
+void jsonw_reset(json_writer_t *self);
+
 /* Add property name */
 void jsonw_name(json_writer_t *self, const char *name);
 
tools/bpf/bpftool/main.c +10 -0
index 4a191fcbeb82..a681d568cfa7 100644
@@ -28,6 +28,7 @@ bool show_pinned;
 bool block_mount;
 bool verifier_logs;
 bool relaxed_maps;
+bool dump_metadata;
 struct pinned_obj_table prog_table;
 struct pinned_obj_table map_table;
 struct pinned_obj_table link_table;
@@ -351,6 +352,10 @@ static int do_batch(int argc, char **argv)
 	return err;
 }
 
+enum bpftool_longonly_opts {
+	OPT_METADATA = 256,
+};
+
 int main(int argc, char **argv)
 {
 	static const struct option options[] = {
@@ -362,6 +367,7 @@ int main(int argc, char **argv)
 		{ "mapcompat",	no_argument,	NULL,	'm' },
 		{ "nomount",	no_argument,	NULL,	'n' },
 		{ "debug",	no_argument,	NULL,	'd' },
+		{ "metadata",	no_argument,	NULL,	OPT_METADATA },
 		{ 0 }
 	};
 	int opt, ret;
@@ -371,6 +377,7 @@ int main(int argc, char **argv)
 	json_output = false;
 	show_pinned = false;
 	block_mount = false;
+	dump_metadata = false;
 	bin_name = argv[0];
 
 	hash_init(prog_table.table);
@@ -412,6 +419,9 @@ int main(int argc, char **argv)
 			libbpf_set_print(print_all_levels);
 			verifier_logs = true;
 			break;
+		case OPT_METADATA:
+			dump_metadata = true;
+			break;
 		default:
 			p_err("unrecognized option '%s'", argv[optind - 1]);
 			if (json_output)
tools/bpf/bpftool/main.h +1 -0
index c46e52137b87..8750758e9150 100644
@@ -90,6 +90,7 @@ extern bool show_pids;
 extern bool block_mount;
 extern bool verifier_logs;
 extern bool relaxed_maps;
+extern bool dump_metadata;
 extern struct pinned_obj_table prog_table;
 extern struct pinned_obj_table map_table;
 extern struct pinned_obj_table link_table;
tools/bpf/bpftool/prog.c +130 -0

148 lines not on this page · raw message

Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
#24 lore raw

Re: [PATCH bpf-next v3 5/8] bpftool: support dumping metadata

Quoted 44 lines · Stanislav Fomichev

From: YiFei Zhu <[email protected]>

Added a flag "--metadata" to bpftool prog list to dump the metadata contents. For some formatting some BTF code is put directly in the metadata dumping. Sanity checks on the map and the kind of the btf_type to make sure we are actually dumping what we are expecting.

A helper jsonw_reset is added to json writer so we can reuse the same json writer without having extraneous commas.

Sample output:

  $ bpftool prog --metadata
  6: cgroup_skb  name prog  tag bcf7977d3b93787c  gpl
  [...]
        btf_id 4
        metadata:
                metadata_a = "foo"
                metadata_b = 1
  $ bpftool prog --metadata --json --pretty
  [{
          "id": 6,
  [...]
          "btf_id": 4,
          "metadata": {
              "metadata_a": "foo",
              "metadata_b": 1
          }
      }
  ]
---
 tools/bpf/bpftool/json_writer.c |   6 ++
 tools/bpf/bpftool/json_writer.h |   3 +
 tools/bpf/bpftool/main.c        |  10 +++
 tools/bpf/bpftool/main.h        |   1 +
 tools/bpf/bpftool/prog.c        | 130 ++++++++++++++++++++++++++++++++
 5 files changed, 150 insertions(+)

[...]

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 200

Quoted 7 lines
tools/bpf/bpftool/prog.c +7 -0
+
+       if (bpf_map_lookup_elem(map_fd, &key, value)) {
+               p_err("metadata map lookup failed: %s", strerror(errno));
+               goto out_free;
+       }
+
+       err = btf__get_from_id(map_info.btf_id, &btf);

what if the map has no btf_id associated (e.g., because of an old kernel?); why fail in this case?

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 207

Quoted 7 lines
tools/bpf/bpftool/prog.c +7 -0
+       if (err || !btf) {
+               p_err("metadata BTF get failed: %s", strerror(-err));
+               goto out_free;
+       }
+
+       t_datasec = btf__type_by_id(btf, map_info.btf_value_type_id);
+       if (BTF_INFO_KIND(t_datasec->info) != BTF_KIND_DATASEC) {

btf_is_datasec(t_datasec)

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 212

Quoted 5 lines
tools/bpf/bpftool/prog.c +5 -0
+               p_err("bad metadata BTF");
+               goto out_free;
+       }
+
+       vlen = BTF_INFO_VLEN(t_datasec->info);

btf_vlen(t_datasec)

Quoted 1 line

+ vsi = (struct btf_var_secinfo *)(t_datasec + 1);

btf_var_secinfos(t_datasec)

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 216

Quoted 3 lines
tools/bpf/bpftool/prog.c +3 -0
+
+       /* We don't proceed to check the kinds of the elements of the DATASEC.
+        * The verifier enforce then to be BTF_KIND_VAR.

typo: then -> them

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 229

Quoted 13 lines
tools/bpf/bpftool/prog.c +13 -0
+        */
+
+       if (json_output) {
+               struct btf_dumper d = {
+                       .btf = btf,
+                       .jw = json_wtr,
+                       .is_plain_text = false,
+               };
+
+               jsonw_name(json_wtr, "metadata");
+
+               jsonw_start_object(json_wtr);
+               for (i = 0; i < vlen; i++) {

nit: doing ++vsi here

Quoted 1 line

+ t_var = btf__type_by_id(btf, vsi[i].type);

and vsi->type here and below would look a bit cleaner

Quoted 9 lines
tools/bpf/bpftool/prog.c +9 -0
+
+                       jsonw_name(json_wtr, btf__name_by_offset(btf, t_var->name_off));
+                       err = btf_dumper_type(&d, t_var->type, value + vsi[i].offset);
+                       if (err) {
+                               p_err("btf dump failed");
+                               break;
+                       }
+               }
+               jsonw_end_object(json_wtr);

[...]

#25 lore raw

Re: [PATCH bpf-next v3 5/8] bpftool: support dumping metadata

Quoted 49 lines · Andrii Nakryiko
Quoted 44 lines · Stanislav Fomichev

From: YiFei Zhu <[email protected]>

Added a flag "--metadata" to bpftool prog list to dump the metadata contents. For some formatting some BTF code is put directly in the metadata dumping. Sanity checks on the map and the kind of the btf_type to make sure we are actually dumping what we are expecting.

A helper jsonw_reset is added to json writer so we can reuse the same json writer without having extraneous commas.

Sample output:

  $ bpftool prog --metadata
  6: cgroup_skb  name prog  tag bcf7977d3b93787c  gpl
  [...]
        btf_id 4
        metadata:
                metadata_a = "foo"
                metadata_b = 1
  $ bpftool prog --metadata --json --pretty
  [{
          "id": 6,
  [...]
          "btf_id": 4,
          "metadata": {
              "metadata_a": "foo",
              "metadata_b": 1
          }
      }
  ]
---
 tools/bpf/bpftool/json_writer.c |   6 ++
 tools/bpf/bpftool/json_writer.h |   3 +
 tools/bpf/bpftool/main.c        |  10 +++
 tools/bpf/bpftool/main.h        |   1 +
 tools/bpf/bpftool/prog.c        | 130 ++++++++++++++++++++++++++++++++
 5 files changed, 150 insertions(+)

[...]

Quoted 10 lines

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 200

Quoted 7 lines
tools/bpf/bpftool/prog.c +7 -0
+
+       if (bpf_map_lookup_elem(map_fd, &key, value)) {
+               p_err("metadata map lookup failed: %s", strerror(errno));
+               goto out_free;
+       }
+
+       err = btf__get_from_id(map_info.btf_id, &btf);

what if the map has no btf_id associated (e.g., because of an old kernel?); why fail in this case?

Thank you for the review, coming back at it a bit late :-(

This functionality is guarded by --metadata bpftool flag (off by default). In case of no btf_id, it might be helpful to show why we don't have the metadata rather than just quietly failing.
WDYT?

Quoted 28 lines

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 207

Quoted 7 lines
tools/bpf/bpftool/prog.c +7 -0
+       if (err || !btf) {
+               p_err("metadata BTF get failed: %s", strerror(-err));
+               goto out_free;
+       }
+
+       t_datasec = btf__type_by_id(btf, map_info.btf_value_type_id);
+       if (BTF_INFO_KIND(t_datasec->info) != BTF_KIND_DATASEC) {

btf_is_datasec(t_datasec)

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 212

Quoted 5 lines
tools/bpf/bpftool/prog.c +5 -0
+               p_err("bad metadata BTF");
+               goto out_free;
+       }
+
+       vlen = BTF_INFO_VLEN(t_datasec->info);

btf_vlen(t_datasec)

Quoted 1 line

+ vsi = (struct btf_var_secinfo *)(t_datasec + 1);

btf_var_secinfos(t_datasec)

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 216

Quoted 3 lines
tools/bpf/bpftool/prog.c +3 -0
+
+       /* We don't proceed to check the kinds of the elements of the DATASEC.
+        * The verifier enforce then to be BTF_KIND_VAR.

typo: then -> them

Quoted 15 lines

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 229

Quoted 13 lines
tools/bpf/bpftool/prog.c +13 -0
+        */
+
+       if (json_output) {
+               struct btf_dumper d = {
+                       .btf = btf,
+                       .jw = json_wtr,
+                       .is_plain_text = false,
+               };
+
+               jsonw_name(json_wtr, "metadata");
+
+               jsonw_start_object(json_wtr);
+               for (i = 0; i < vlen; i++) {

nit: doing ++vsi here

Agreed with all the above, except this one.
It feels like it's safer to do [i] in case somebody adds a 'continue' clause later and we miss that '++vsi'.
Let me know if you feel strongly about it.

Quoted 15 lines
Quoted 1 line

+ t_var = btf__type_by_id(btf, vsi[i].type);

and vsi->type here and below would look a bit cleaner

Quoted 9 lines
tools/bpf/bpftool/prog.c +9 -0
+
+                       jsonw_name(json_wtr, btf__name_by_offset(btf, t_var->name_off));
+                       err = btf_dumper_type(&d, t_var->type, value + vsi[i].offset);
+                       if (err) {
+                               p_err("btf dump failed");
+                               break;
+                       }
+               }
+               jsonw_end_object(json_wtr);

[...]

#26 lore raw

Re: [PATCH bpf-next v3 5/8] bpftool: support dumping metadata

Quoted 62 lines · Stanislav Fomichev
Quoted 49 lines · Andrii Nakryiko
Quoted 44 lines · Stanislav Fomichev

From: YiFei Zhu <[email protected]>

Added a flag "--metadata" to bpftool prog list to dump the metadata contents. For some formatting some BTF code is put directly in the metadata dumping. Sanity checks on the map and the kind of the btf_type to make sure we are actually dumping what we are expecting.

A helper jsonw_reset is added to json writer so we can reuse the same json writer without having extraneous commas.

Sample output:

  $ bpftool prog --metadata
  6: cgroup_skb  name prog  tag bcf7977d3b93787c  gpl
  [...]
        btf_id 4
        metadata:
                metadata_a = "foo"
                metadata_b = 1
  $ bpftool prog --metadata --json --pretty
  [{
          "id": 6,
  [...]
          "btf_id": 4,
          "metadata": {
              "metadata_a": "foo",
              "metadata_b": 1
          }
      }
  ]
---
 tools/bpf/bpftool/json_writer.c |   6 ++
 tools/bpf/bpftool/json_writer.h |   3 +
 tools/bpf/bpftool/main.c        |  10 +++
 tools/bpf/bpftool/main.h        |   1 +
 tools/bpf/bpftool/prog.c        | 130 ++++++++++++++++++++++++++++++++
 5 files changed, 150 insertions(+)

[...]

Quoted 10 lines

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 200

Quoted 7 lines
tools/bpf/bpftool/prog.c +7 -0
+
+       if (bpf_map_lookup_elem(map_fd, &key, value)) {
+               p_err("metadata map lookup failed: %s", strerror(errno));
+               goto out_free;
+       }
+
+       err = btf__get_from_id(map_info.btf_id, &btf);

what if the map has no btf_id associated (e.g., because of an old kernel?); why fail in this case?

Quoted 6 lines

Thank you for the review, coming back at it a bit late :-(

This functionality is guarded by --metadata bpftool flag (off by default). In case of no btf_id, it might be helpful to show why we don't have the metadata rather than just quietly failing.
WDYT?

we might do it similarly to PID info I added with bpf_iter: if it's supported -- emit it, if not -- skip and still succeed. So maybe we don't really need extra --metadata flag and should do all this always?

Quoted 44 lines
Quoted 29 lines

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 207

Quoted 8 lines
tools/bpf/bpftool/prog.c +7 -0
+       if (err || !btf) {
+               p_err("metadata BTF get failed: %s", strerror(-err));
+               goto out_free;
+       }
+
+       t_datasec = btf__type_by_id(btf, map_info.btf_value_type_id);
+       if (BTF_INFO_KIND(t_datasec->info) != BTF_KIND_DATASEC) {

btf_is_datasec(t_datasec)

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 212

Quoted 5 lines
tools/bpf/bpftool/prog.c +5 -0
+               p_err("bad metadata BTF");
+               goto out_free;
+       }
+
+       vlen = BTF_INFO_VLEN(t_datasec->info);

btf_vlen(t_datasec)

Quoted 1 line

+ vsi = (struct btf_var_secinfo *)(t_datasec + 1);

btf_var_secinfos(t_datasec)

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 216

Quoted 3 lines
tools/bpf/bpftool/prog.c +3 -0
+
+       /* We don't proceed to check the kinds of the elements of the DATASEC.
+        * The verifier enforce then to be BTF_KIND_VAR.

typo: then -> them

Quoted 15 lines

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 229

Quoted 13 lines
tools/bpf/bpftool/prog.c +13 -0
+        */
+
+       if (json_output) {
+               struct btf_dumper d = {
+                       .btf = btf,
+                       .jw = json_wtr,
+                       .is_plain_text = false,
+               };
+
+               jsonw_name(json_wtr, "metadata");
+
+               jsonw_start_object(json_wtr);
+               for (i = 0; i < vlen; i++) {

nit: doing ++vsi here

Quoted 4 lines

Agreed with all the above, except this one.
It feels like it's safer to do [i] in case somebody adds a 'continue' clause later and we miss that '++vsi'.
Let me know if you feel strongly about it.

I meant to add vsi++ inside the for clause, no way to miss it:

for (i = 0; i < vlen, i++, vsi++) {
continue/break/whatever you want, except extra i++ or vsi++
}

it's the safest way, imo

Quoted 16 lines
Quoted 16 lines
Quoted 2 lines

+ t_var = btf__type_by_id(btf, vsi[i].type);

and vsi->type here and below would look a bit cleaner

Quoted 9 lines
tools/bpf/bpftool/prog.c +9 -0
+
+                       jsonw_name(json_wtr, btf__name_by_offset(btf, t_var->name_off));
+                       err = btf_dumper_type(&d, t_var->type, value + vsi[i].offset);
+                       if (err) {
+                               p_err("btf dump failed");
+                               break;
+                       }
+               }
+               jsonw_end_object(json_wtr);

[...]

#27 lore raw

Re: [PATCH bpf-next v3 5/8] bpftool: support dumping metadata

Quoted 66 lines · Andrii Nakryiko
Quoted 64 lines · Stanislav Fomichev
Quoted 49 lines · Andrii Nakryiko
Quoted 44 lines · Stanislav Fomichev

From: YiFei Zhu <[email protected]>

Added a flag "--metadata" to bpftool prog list to dump the metadata contents. For some formatting some BTF code is put directly in the metadata dumping. Sanity checks on the map and the kind of the btf_type to make sure we are actually dumping what we are expecting.

A helper jsonw_reset is added to json writer so we can reuse the same json writer without having extraneous commas.

Sample output:

  $ bpftool prog --metadata
  6: cgroup_skb  name prog  tag bcf7977d3b93787c  gpl
  [...]
        btf_id 4
        metadata:
                metadata_a = "foo"
                metadata_b = 1
  $ bpftool prog --metadata --json --pretty
  [{
          "id": 6,
  [...]
          "btf_id": 4,
          "metadata": {
              "metadata_a": "foo",
              "metadata_b": 1
          }
      }
  ]
---
 tools/bpf/bpftool/json_writer.c |   6 ++
 tools/bpf/bpftool/json_writer.h |   3 +
 tools/bpf/bpftool/main.c        |  10 +++
 tools/bpf/bpftool/main.h        |   1 +
 tools/bpf/bpftool/prog.c        | 130 ++++++++++++++++++++++++++++++++
 5 files changed, 150 insertions(+)

[...]

Quoted 10 lines

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 200

Quoted 7 lines
tools/bpf/bpftool/prog.c +7 -0
+
+       if (bpf_map_lookup_elem(map_fd, &key, value)) {
+               p_err("metadata map lookup failed: %s", strerror(errno));
+               goto out_free;
+       }
+
+       err = btf__get_from_id(map_info.btf_id, &btf);

what if the map has no btf_id associated (e.g., because of an old kernel?); why fail in this case?

Thank you for the review, coming back at it a bit late :-(

Quoted 8 lines
Quoted 4 lines

This functionality is guarded by --metadata bpftool flag (off by default). In case of no btf_id, it might be helpful to show why we don't have the metadata rather than just quietly failing.
WDYT?

we might do it similarly to PID info I added with bpf_iter: if it's supported -- emit it, if not -- skip and still succeed. So maybe we don't really need extra --metadata flag and should do all this always?

Sounds reasonable, especially if there is an existing precedent. Let me explore that option.

Quoted 48 lines
Quoted 43 lines
Quoted 28 lines

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 207

Quoted 7 lines
tools/bpf/bpftool/prog.c +7 -0
+       if (err || !btf) {
+               p_err("metadata BTF get failed: %s", strerror(-err));
+               goto out_free;
+       }
+
+       t_datasec = btf__type_by_id(btf, map_info.btf_value_type_id);
+       if (BTF_INFO_KIND(t_datasec->info) != BTF_KIND_DATASEC) {

btf_is_datasec(t_datasec)

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 212

Quoted 5 lines
tools/bpf/bpftool/prog.c +5 -0
+               p_err("bad metadata BTF");
+               goto out_free;
+       }
+
+       vlen = BTF_INFO_VLEN(t_datasec->info);

btf_vlen(t_datasec)

Quoted 1 line

+ vsi = (struct btf_var_secinfo *)(t_datasec + 1);

btf_var_secinfos(t_datasec)

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 216

Quoted 3 lines
tools/bpf/bpftool/prog.c +3 -0
+
+       /* We don't proceed to check the kinds of the elements of the DATASEC.
+        * The verifier enforce then to be BTF_KIND_VAR.

typo: then -> them

Quoted 15 lines

tools/bpf/bpftool/prog.c static void show_prog_maps(int fd, __u32 num_maps) · line 229

Quoted 13 lines
tools/bpf/bpftool/prog.c +13 -0
+        */
+
+       if (json_output) {
+               struct btf_dumper d = {
+                       .btf = btf,
+                       .jw = json_wtr,
+                       .is_plain_text = false,
+               };
+
+               jsonw_name(json_wtr, "metadata");
+
+               jsonw_start_object(json_wtr);
+               for (i = 0; i < vlen; i++) {

nit: doing ++vsi here

Quoted 4 lines

Agreed with all the above, except this one.
It feels like it's safer to do [i] in case somebody adds a 'continue' clause later and we miss that '++vsi'.
Let me know if you feel strongly about it.

Quoted 7 lines

I meant to add vsi++ inside the for clause, no way to miss it:

for (i = 0; i < vlen, i++, vsi++) {
continue/break/whatever you want, except extra i++ or vsi++
}

it's the safest way, imo

Ack, I can do that, thanks!

Quoted 15 lines
Quoted 15 lines
Quoted 15 lines
Quoted 1 line

+ t_var = btf__type_by_id(btf, vsi[i].type);

and vsi->type here and below would look a bit cleaner

Quoted 9 lines
tools/bpf/bpftool/prog.c +9 -0
+
+                       jsonw_name(json_wtr, btf__name_by_offset(btf, t_var->name_off));
+                       err = btf_dumper_type(&d, t_var->type, value + vsi[i].offset);
+                       if (err) {
+                               p_err("btf dump failed");
+                               break;
+                       }
+               }
+               jsonw_end_object(json_wtr);

[...]

#28 lore raw

PATCH v3 6/8 bpftool: support metadata internal map in gen skeleton

In reply to Stanislav Fomichev

From: YiFei Zhu <[email protected]>

The treatment of this section .metadata is exactly like .rodata, the type modifiers are stripped. The resulting skeleton looks like:

  struct skel_with_metadata {
  	struct bpf_object_skeleton *skeleton;
  	struct bpf_object *obj;
  	struct {
  		struct bpf_map *metadata;
  	} maps;
  	[...]
  	struct skel_with_metadata__metadata {
  		char metadata_a[4];
  		int metadata_b;
  	} *metadata;
  };
---
 tools/bpf/bpftool/gen.c | 5 +++++
 1 file changed, 5 insertions(+)
tools/bpf/bpftool/gen.c +5 -0
index 4033c46d83e7..9c316ea23ca1 100644
@@ -82,6 +82,8 @@ static const char *get_map_ident(const struct bpf_map *map)
 		return "bss";
 	else if (str_has_suffix(name, ".kconfig"))
 		return "kconfig";
+	else if (str_has_suffix(name, ".metadata"))
+		return "metadata";
 	else
 		return NULL;
 }
@@ -113,6 +115,9 @@ static int codegen_datasec_def(struct bpf_object *obj,
 		strip_mods = true;
 	} else if (strcmp(sec_name, ".kconfig") == 0) {
 		sec_ident = "kconfig";
+	} else if (strcmp(sec_name, ".metadata") == 0) {
+		sec_ident = "metadata";
+		strip_mods = true;
 	} else {
 		return 0;
 	}
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
#29 lore raw

PATCH v3 7/8 bpftool: mention --metadata in the documentation

In reply to Stanislav Fomichev

Mention --metadata in the rst documentation and in the prog.c help.

---
 tools/bpf/bpftool/Documentation/bpftool-prog.rst | 5 ++++-
 tools/bpf/bpftool/prog.c                         | 2 +-
 2 files changed, 5 insertions(+), 2 deletions(-)
tools/bpf/bpftool/Documentation/bpftool-prog.rst +4 -1
index 82e356b664e8..84dc47e18016 100644
@@ -12,7 +12,7 @@ SYNOPSIS
 
 	**bpftool** [*OPTIONS*] **prog** *COMMAND*
 
-	*OPTIONS* := { { **-j** | **--json** } [{ **-p** | **--pretty** }] | { **-f** | **--bpffs** } }
+	*OPTIONS* := { { **-j** | **--json** } [{ **-p** | **--pretty** }] | { **-f** | **--bpffs** } | {**--metadata**} }
 
 	*COMMANDS* :=
 	{ **show** | **list** | **dump xlated** | **dump jited** | **pin** | **load**
@@ -80,6 +80,9 @@ DESCRIPTION
 		  programs. On such kernels bpftool will automatically emit this
 		  information as well.
 
+		  You can specify **--metadata** option to pretty-print
+		  read-only data from the associated *.metadata* section.
+
 	**bpftool prog dump xlated** *PROG* [{ **file** *FILE* | **opcodes** | **visual** | **linum** }]
 		  Dump eBPF instructions of the programs from the kernel. By
 		  default, eBPF will be disassembled and printed to standard
tools/bpf/bpftool/prog.c +1 -1
index 5d626c134e7d..4c129d6d2a0c 100644
@@ -2005,7 +2005,7 @@ static int do_help(int argc, char **argv)
 	}
 
 	fprintf(stderr,
-		"Usage: %1$s %2$s { show | list } [PROG]\n"
+		"Usage: %1$s %2$s { show | list } [PROG] [--metadata]\n"
 		"       %1$s %2$s dump xlated PROG [{ file FILE | opcodes | visual | linum }]\n"
 		"       %1$s %2$s dump jited  PROG [{ file FILE | opcodes | linum }]\n"
 		"       %1$s %2$s pin   PROG FILE\n"
Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog
#30 lore raw

PATCH v3 8/8 selftests/bpf: Test load and dump metadata with btftool and skel

In reply to Stanislav Fomichev

From: YiFei Zhu <[email protected]>

This is a simple test to check that loading and dumping metadata in btftool works, whether or not metadata contents are used by the program.

A C test is also added to make sure the skeleton code can read the metadata values, and we also check that trying to re-bind the map causes EEXIST, so we are sure the map is already bound by libbpf when loading skeleton.

---
 tools/testing/selftests/bpf/Makefile          |  3 +-
 .../selftests/bpf/prog_tests/metadata.c       | 83 +++++++++++++++++++
 .../selftests/bpf/progs/metadata_unused.c     | 15 ++++
 .../selftests/bpf/progs/metadata_used.c       | 15 ++++
 .../selftests/bpf/test_bpftool_metadata.sh    | 82 ++++++++++++++++++
 5 files changed, 197 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/metadata.c
 create mode 100644 tools/testing/selftests/bpf/progs/metadata_unused.c
 create mode 100644 tools/testing/selftests/bpf/progs/metadata_used.c
 create mode 100755 tools/testing/selftests/bpf/test_bpftool_metadata.sh
tools/testing/selftests/bpf/Makefile +2 -1
index 09657d0afb5c..f7fd1503d210 100644
@@ -68,7 +68,8 @@ TEST_PROGS := test_kmod.sh \
 	test_tc_edt.sh \
 	test_xdping.sh \
 	test_bpftool_build.sh \
-	test_bpftool.sh
+	test_bpftool.sh \
+	test_bpftool_metadata.sh \
 
 TEST_PROGS_EXTENDED := with_addr.sh \
 	with_tunnels.sh \
tools/testing/selftests/bpf/prog_tests/metadata.c new file +83 -0

83 lines not on this page · raw message

tools/testing/selftests/bpf/progs/metadata_unused.c new file +15 -0
new file mode 100644
index 000000000000..523b3c332426
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: GPL-2.0-only
+
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+
+char metadata_a[] SEC(".metadata") = "foo";
+int metadata_b SEC(".metadata") = 1;
+
+SEC("cgroup_skb/egress")
+int prog(struct xdp_md *ctx)
+{
+	return 0;
+}
+
+char _license[] SEC("license") = "GPL";
tools/testing/selftests/bpf/progs/metadata_used.c new file +15 -0
new file mode 100644
index 000000000000..59785404f7bb
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: GPL-2.0-only
+
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+
+char metadata_a[] SEC(".metadata") = "bar";
+int metadata_b SEC(".metadata") = 2;
+
+SEC("cgroup_skb/egress")
+int prog(struct xdp_md *ctx)
+{
+	return metadata_b ? 1 : 0;
+}
+
+char _license[] SEC("license") = "GPL";
tools/testing/selftests/bpf/test_bpftool_metadata.sh new file +82 -0

82 lines not on this page · raw message

Signature · 1 line
2.28.0.402.g5ffc5be6b7-goog