The tracefs path helpers look up /sys/kernel/debug/tracing first, even when tracefs is already mounted at /sys/kernel/tracing. This can trigger an unnecessary legacy tracefs mount and selects a path beneath debugfs, which is commonly restricted. Prefer the direct tracefs mount when statfs() reports TRACEFS_MAGIC. Checking the filesystem type avoids selecting an existing but unmounted sysfs mountpoint. Preserve the existing debugfs fallback and the default tracefs path when neither location is available. Fixes: a1ac9fd6c650 ("libbpf: fallback to tracefs mount point if debugfs is not mounted") Closes: https://github.com/libbpf/libbpf/issues/966 Assisted-by: LLM Signed-off-by: Eduard Zateev --- Validation on Fedora 44 (aarch64): - Built static and shared libbpf with the default warning settings. - Exercised all five path helpers using wrapped syscalls for both mounts, tracefs only, debugfs only, an unmounted tracefs directory, and neither path available. The original code fails the both-mounts scenario. - Confirmed the direct tracefs paths on the host's mounted tracefs. Privileged BPF attach/mount tests were not run. tools/lib/bpf/libbpf.c | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c index cb09ded90..9db0a8bde 100644 --- a/tools/lib/bpf/libbpf.c +++ b/tools/lib/bpf/libbpf.c @@ -59,6 +59,10 @@ #define BPF_FS_MAGIC 0xcafe4a11 #endif +#ifndef TRACEFS_MAGIC +#define TRACEFS_MAGIC 0x74726163 +#endif + #define MAX_EVENT_NAME_LEN 64 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf" @@ -12713,12 +12717,17 @@ static int append_to_file(const char *file, const char *fmt, ...) static bool use_debugfs(void) { - static int has_debugfs = -1; + static int needs_debugfs = -1; + struct statfs st_fs; - if (has_debugfs < 0) - has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0; + if (needs_debugfs < 0) { + if (statfs(TRACEFS, &st_fs) == 0 && st_fs.f_type == TRACEFS_MAGIC) + needs_debugfs = 0; + else + needs_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0; + } - return has_debugfs == 1; + return needs_debugfs == 1; } static const char *tracefs_path(void) base-commit: a6303535c2ad9d49598d52556183911f02287791 -- 2.55.0