* [PATCH v3 1/7] perf machine: Fix leak when creating host kernel maps fails
2026-12-04 6:23 [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
@ 2026-12-04 6:23 ` Ian Rogers
2026-12-04 6:23 ` [PATCH v3 2/7] perf synthetic-events: Fix race on DSO build IDs when synthesizing Ian Rogers
` (7 subsequent siblings)
8 siblings, 0 replies; 11+ messages in thread
From: Ian Rogers @ 2026-12-04 6:23 UTC (permalink / raw)
To: linux-perf-users
Cc: linux-kernel, peterz, mingo, acme, namhyung, jolsa, adrian.hunter,
james.clark, dsahern, andrii, Ian Rogers
If machine__create_kernel_maps() fails in __machine__new_host() the
machine is freed with free(), leaking what machine__init() and the
partially created kernel maps allocated, such as the kmaps, root_dir,
mmap_name, kernel DSO and threads. Use machine__delete() to release
them.
Fixes: 8fb598e5a3b0 ("perf trace: Fix comm resolution when reading events from file")
Signed-off-by: Ian Rogers <irogers@google.com>
---
Notes:
The leak was found by the Sashiko AI review tool when reviewing an
earlier version of this series.
This change was developed with the help of an AI coding assistant
(Gemini in Jetski), which wrote the initial code, tests and
changelog; it was reviewed, built and tested by the author.
tools/perf/util/machine.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/tools/perf/util/machine.c b/tools/perf/util/machine.c
index 2750d507aecc..5fbc5941a2bc 100644
--- a/tools/perf/util/machine.c
+++ b/tools/perf/util/machine.c
@@ -144,7 +144,7 @@ static struct machine *__machine__new_host(struct perf_env *host_env, bool kerne
}
if (kernel_maps && machine__create_kernel_maps(machine) < 0) {
- free(machine);
+ machine__delete(machine);
return NULL;
}
machine->env = host_env;
--
2.56.1.915.g69d5ec7298-goog
^ permalink raw reply related [flat|nested] 11+ messages in thread* [PATCH v3 2/7] perf synthetic-events: Fix race on DSO build IDs when synthesizing
2026-12-04 6:23 [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
2026-12-04 6:23 ` [PATCH v3 1/7] perf machine: Fix leak when creating host kernel maps fails Ian Rogers
@ 2026-12-04 6:23 ` Ian Rogers
2026-12-04 6:23 ` [PATCH v3 3/7] perf bench synthesize: Initialize symbols so build IDs can be read Ian Rogers
` (6 subsequent siblings)
8 siblings, 0 replies; 11+ messages in thread
From: Ian Rogers @ 2026-12-04 6:23 UTC (permalink / raw)
To: linux-perf-users
Cc: linux-kernel, peterz, mingo, acme, namhyung, jolsa, adrian.hunter,
james.clark, dsahern, andrii, Ian Rogers
perf_event__synthesize_threads() may use several threads that share the
machine's dsos. perf_record_mmap2__read_build_id() reads a DSO's build
ID, to avoid reading the file again, and sets it after reading the
file, without any locking. Threads synthesizing processes that map the
same file, such as libc, can race reading and writing the same build
ID, and the build ID is also read by dsos__findnew_id() when comparing
DSO ids and checking if an id needs improving.
Those lookups hold the dsos lock, and DSO ids are already updated by
__dso__improve_id() with the dsos write lock held. Add
dsos__findnew_id_build_id(), which also copies the DSO's build ID
while the lookup holds the dsos lock, and dsos__set_dso_build_id() to
set the build ID, if unset, holding the dsos write lock, and use them
when synthesizing. The writer then excludes both the synthesis readers
and the lookups, and reading the build ID needs no extra locking. As
before, setting the build ID doesn't re-sort dsos; DSOs created when
synthesizing are keyed by device and inode, which are compared before
the build ID.
ThreadSanitizer reported 8 data races on the build ID, between
dso__set_build_id() and dso__has_build_id()/dso__needs_improve_id(), in
'perf bench internals synthesize -t -m 8 -M 8' (with the benchmark
fixed to initialize libelf so build IDs are read) and none with this
change.
Fixes: fd643afc8f60 ("perf record: Save DSO build-ID for synthesizing")
Signed-off-by: Ian Rogers <irogers@google.com>
---
Notes:
The race was found by the Sashiko AI review tool when reviewing an
earlier version of this series.
This change was developed with the help of an AI coding assistant
(Gemini in Jetski), which wrote the initial code, tests and
changelog; it was reviewed, built and tested by the author.
tools/perf/util/dsos.c | 38 +++++++++++++++++++++++++++++-
tools/perf/util/dsos.h | 4 ++++
tools/perf/util/synthetic-events.c | 12 ++++++----
3 files changed, 48 insertions(+), 6 deletions(-)
diff --git a/tools/perf/util/dsos.c b/tools/perf/util/dsos.c
index 9ae27ee93413..e095eb59ae7b 100644
--- a/tools/perf/util/dsos.c
+++ b/tools/perf/util/dsos.c
@@ -340,13 +340,34 @@ static struct dso *__dsos__findnew_id(struct dsos *dsos, const char *name, const
return dso ? dso : __dsos__addnew_id(dsos, name, id);
}
-struct dso *dsos__findnew_id(struct dsos *dsos, const char *name, const struct dso_id *id)
+/* Copy the build ID of dso, size 0 if it has none, with dsos->lock held. */
+static void dso__copy_build_id(const struct dso *dso, struct build_id *bid)
+{
+ if (!bid)
+ return;
+
+ if (dso && dso__has_build_id(dso))
+ *bid = *dso__bid(dso);
+ else
+ bid->size = 0;
+}
+
+/*
+ * Like dsos__findnew_id() but, if bid isn't NULL, also copies the DSO's build
+ * ID to bid, with size 0 if there is none, while holding the dsos lock. A
+ * DSO's build ID is part of the id compared by lookups holding the lock, and
+ * it may be set by threads synthesizing events in parallel, see
+ * dsos__set_dso_build_id(), so it must not be read without the lock.
+ */
+struct dso *dsos__findnew_id_build_id(struct dsos *dsos, const char *name,
+ const struct dso_id *id, struct build_id *bid)
{
struct dso *dso;
down_read(&dsos->lock);
dso = __dsos__find_id(dsos, name, id, false, /*write_locked=*/false);
if (dso && !dso__needs_improve_id(dso, id)) {
+ dso__copy_build_id(dso, bid);
up_read(&dsos->lock);
return dso;
}
@@ -355,10 +376,25 @@ struct dso *dsos__findnew_id(struct dsos *dsos, const char *name, const struct d
down_write(&dsos->lock);
dso = __dsos__findnew_id(dsos, name, id);
+ dso__copy_build_id(dso, bid);
up_write(&dsos->lock);
return dso;
}
+struct dso *dsos__findnew_id(struct dsos *dsos, const char *name, const struct dso_id *id)
+{
+ return dsos__findnew_id_build_id(dsos, name, id, /*bid=*/NULL);
+}
+
+/* Set the build ID of a DSO in dsos, if it has none, holding the dsos lock. */
+void dsos__set_dso_build_id(struct dsos *dsos, struct dso *dso, const struct build_id *bid)
+{
+ down_write(&dsos->lock);
+ if (!dso__has_build_id(dso))
+ dso__set_build_id(dso, bid);
+ up_write(&dsos->lock);
+}
+
struct dsos__fprintf_buildid_cb_args {
FILE *fp;
bool (*skip)(struct dso *dso, int parm);
diff --git a/tools/perf/util/dsos.h b/tools/perf/util/dsos.h
index cc7e3a42f9cb..b3c6a6e9ced5 100644
--- a/tools/perf/util/dsos.h
+++ b/tools/perf/util/dsos.h
@@ -8,6 +8,7 @@
#include <linux/rbtree.h>
#include "rwsem.h"
+struct build_id;
struct dso;
struct dso_id;
struct kmod_path;
@@ -35,6 +36,9 @@ struct dso *__dsos__find(struct dsos *dsos, const char *name, bool cmp_short, bo
struct dso *dsos__find(struct dsos *dsos, const char *name, bool cmp_short);
struct dso *dsos__findnew_id(struct dsos *dsos, const char *name, const struct dso_id *id);
+struct dso *dsos__findnew_id_build_id(struct dsos *dsos, const char *name,
+ const struct dso_id *id, struct build_id *bid);
+void dsos__set_dso_build_id(struct dsos *dsos, struct dso *dso, const struct build_id *bid);
bool dsos__read_build_ids(struct dsos *dsos, bool with_hits);
diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c
index 3c8d29f27fd9..445199d7bbd4 100644
--- a/tools/perf/util/synthetic-events.c
+++ b/tools/perf/util/synthetic-events.c
@@ -4,6 +4,7 @@
#include "util/data.h"
#include "util/debug.h"
#include "util/dso.h"
+#include "util/dsos.h"
#include "util/event.h"
#include "util/evlist.h"
#include "util/machine.h"
@@ -462,9 +463,10 @@ static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event,
dso_id.mmap2_ino_generation_valid = true;
}
- dso = dsos__findnew_id(&machine->dsos, event->filename, &dso_id);
- if (dso && dso__has_build_id(dso)) {
- bid = *dso__bid(dso);
+ dso = dsos__findnew_id_build_id(&machine->dsos, event->filename, &dso_id, &bid);
+ if (dso && bid.size) {
+ /* The DSO already has the build ID, don't set it again. */
+ dso__zput(dso);
rc = 0;
goto out;
}
@@ -485,8 +487,8 @@ static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event,
event->__reserved_1 = 0;
event->__reserved_2 = 0;
- if (dso && !dso__has_build_id(dso))
- dso__set_build_id(dso, &bid);
+ if (dso)
+ dsos__set_dso_build_id(&machine->dsos, dso, &bid);
} else {
if (event->filename[0] == '/') {
pr_debug2("Failed to read build ID for %s\n",
--
2.56.1.915.g69d5ec7298-goog
^ permalink raw reply related [flat|nested] 11+ messages in thread* [PATCH v3 3/7] perf bench synthesize: Initialize symbols so build IDs can be read
2026-12-04 6:23 [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
2026-12-04 6:23 ` [PATCH v3 1/7] perf machine: Fix leak when creating host kernel maps fails Ian Rogers
2026-12-04 6:23 ` [PATCH v3 2/7] perf synthetic-events: Fix race on DSO build IDs when synthesizing Ian Rogers
@ 2026-12-04 6:23 ` Ian Rogers
2026-12-04 6:23 ` [PATCH v3 4/7] tools headers UAPI: Synchronize linux/fs.h with the kernel sources Ian Rogers
` (5 subsequent siblings)
8 siblings, 0 replies; 11+ messages in thread
From: Ian Rogers @ 2026-12-04 6:23 UTC (permalink / raw)
To: linux-perf-users
Cc: linux-kernel, peterz, mingo, acme, namhyung, jolsa, adrian.hunter,
james.clark, dsahern, andrii, Ian Rogers
Since build IDs became the default in synthesized MMAP2 events, the
synthesize benchmark reads the build ID of every mapped file. The
benchmark never called symbol__init(), so elf_version() was never
called, elf_begin() fails and every build ID read fails. As no build ID
is found the DSO build ID cache is never populated, and so every mapping
re-opens its file and enters the mount namespace again on every
iteration. This made the benchmark measure a failure path that doesn't
occur in 'perf record', for example on an Intel Core i7-14700:
Before:
Average synthesis took: 3876.387 usec (+- 13.053 usec)
Average data synthesis took: 24886.623 usec (+- 1238.682 usec)
After (median of 10 runs):
Average synthesis took: 258.8 usec
Average data synthesis took: 1621.8 usec
Create a single host perf_env in bench_synthesize(), pass it to
symbol__init() so libelf is initialized and vmlinux paths match the
host, and share it with the sessions the single and multi-threaded
benchmarks create rather than each creating their own.
Fixes: 53b00ff358dc ("perf record: Make --buildid-mmap the default")
Signed-off-by: Ian Rogers <irogers@google.com>
---
Notes:
This change was developed with the help of an AI coding assistant
(Gemini in Jetski), which wrote the initial code, tests and
changelog; it was reviewed, built and tested by the author.
tools/perf/bench/synthesize.c | 52 +++++++++++++++++++----------------
1 file changed, 29 insertions(+), 23 deletions(-)
diff --git a/tools/perf/bench/synthesize.c b/tools/perf/bench/synthesize.c
index 265d49a913d9..fdc5465db3f0 100644
--- a/tools/perf/bench/synthesize.c
+++ b/tools/perf/bench/synthesize.c
@@ -12,6 +12,7 @@
#include "../util/debug.h"
#include "../util/session.h"
#include "../util/stat.h"
+#include "../util/symbol.h"
#include "../util/synthetic-events.h"
#include "../util/target.h"
#include "../util/thread_map.h"
@@ -108,23 +109,20 @@ static int do_run_single_threaded(struct perf_session *session,
return 0;
}
-static int run_single_threaded(void)
+static int run_single_threaded(struct perf_env *host_env)
{
struct perf_session *session;
struct target target = {
.pid = "self",
};
struct perf_thread_map *threads;
- struct perf_env host_env;
int err;
perf_set_singlethreaded();
- perf_env__init(&host_env);
session = __perf_session__new(/*data=*/NULL, /*tool=*/NULL,
- /*trace_event_repipe=*/false, &host_env);
+ /*trace_event_repipe=*/false, host_env);
if (IS_ERR(session)) {
pr_err("Session creation failed.\n");
- perf_env__exit(&host_env);
return PTR_ERR(session);
}
threads = thread_map__new_by_pid(getpid());
@@ -149,12 +147,12 @@ static int run_single_threaded(void)
perf_thread_map__put(threads);
perf_session__delete(session);
- perf_env__exit(&host_env);
return err;
}
-static int do_run_multi_threaded(struct target *target,
- unsigned int nr_threads_synthesize)
+static int do_run_multi_threaded(struct perf_env *host_env,
+ struct target *target,
+ unsigned int nr_threads_synthesize)
{
struct timeval start, end, diff;
u64 runtime_us;
@@ -163,18 +161,14 @@ static int do_run_multi_threaded(struct target *target,
int err = 0;
struct stats time_stats, event_stats;
struct perf_session *session;
- struct perf_env host_env;
- perf_env__init(&host_env);
init_stats(&time_stats);
init_stats(&event_stats);
for (i = 0; i < multi_iterations; i++) {
session = __perf_session__new(/*data=*/NULL, /*tool=*/NULL,
- /*trace_event_repipe=*/false, &host_env);
- if (IS_ERR(session)) {
- err = PTR_ERR(session);
- goto err_out;
- }
+ /*trace_event_repipe=*/false, host_env);
+ if (IS_ERR(session))
+ return PTR_ERR(session);
atomic_set(&event_count, 0);
gettimeofday(&start, NULL);
err = __machine__synthesize_threads(&session->machines.host,
@@ -185,7 +179,7 @@ static int do_run_multi_threaded(struct target *target,
nr_threads_synthesize);
if (err) {
perf_session__delete(session);
- goto err_out;
+ return err;
}
gettimeofday(&end, NULL);
@@ -208,12 +202,10 @@ static int do_run_multi_threaded(struct target *target,
printf(" Average time per event %.3f usec\n",
time_average / event_average);
-err_out:
- perf_env__exit(&host_env);
- return err;
+ return 0;
}
-static int run_multi_threaded(void)
+static int run_multi_threaded(struct perf_env *host_env)
{
struct target target = {
.cpu_list = "0"
@@ -239,7 +231,7 @@ static int run_multi_threaded(void)
printf(" Number of synthesis threads: %u\n",
nr_threads_synthesize);
- err = do_run_multi_threaded(&target, nr_threads_synthesize);
+ err = do_run_multi_threaded(host_env, &target, nr_threads_synthesize);
if (err)
return err;
}
@@ -249,6 +241,7 @@ static int run_multi_threaded(void)
int bench_synthesize(int argc, const char **argv)
{
+ struct perf_env host_env;
int err = 0;
argc = parse_options(argc, argv, options, bench_usage, 0);
@@ -264,11 +257,24 @@ int bench_synthesize(int argc, const char **argv)
if (!run_st && !run_mt)
run_st = true;
+ /*
+ * Initialize libelf, otherwise reading build IDs fails and the DSO
+ * build ID cache is never populated.
+ */
+ perf_env__init(&host_env);
+ err = symbol__init(&host_env);
+ if (err < 0) {
+ perf_env__exit(&host_env);
+ return err;
+ }
+
if (run_st)
- err = run_single_threaded();
+ err = run_single_threaded(&host_env);
if (!err && run_mt)
- err = run_multi_threaded();
+ err = run_multi_threaded(&host_env);
+ symbol__exit();
+ perf_env__exit(&host_env);
return err;
}
--
2.56.1.915.g69d5ec7298-goog
^ permalink raw reply related [flat|nested] 11+ messages in thread* [PATCH v3 4/7] tools headers UAPI: Synchronize linux/fs.h with the kernel sources
2026-12-04 6:23 [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
` (2 preceding siblings ...)
2026-12-04 6:23 ` [PATCH v3 3/7] perf bench synthesize: Initialize symbols so build IDs can be read Ian Rogers
@ 2026-12-04 6:23 ` Ian Rogers
2026-12-04 6:23 ` [PATCH v3 5/7] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events Ian Rogers
` (4 subsequent siblings)
8 siblings, 0 replies; 11+ messages in thread
From: Ian Rogers @ 2026-12-04 6:23 UTC (permalink / raw)
To: linux-perf-users
Cc: linux-kernel, peterz, mingo, acme, namhyung, jolsa, adrian.hunter,
james.clark, dsahern, andrii, Ian Rogers
Synchronize tools/include/uapi/linux/fs.h with include/uapi/linux/fs.h
and add it to FILES in tools/perf/check-headers.sh so future changes
are tracked alongside the trace beauty copy. Upcoming perf
PROCMAP_QUERY synthesis code compiles directly against
tools/include/uapi/linux/fs.h.
Signed-off-by: Ian Rogers <irogers@google.com>
---
Notes:
This change was developed with the help of an AI coding assistant
(Gemini in Jetski), which wrote the initial code, tests and
changelog; it was reviewed, built and tested by the author.
tools/include/uapi/linux/fs.h | 137 +++++++++++++++++++++++++++++++---
| 1 +
2 files changed, 129 insertions(+), 9 deletions(-)
diff --git a/tools/include/uapi/linux/fs.h b/tools/include/uapi/linux/fs.h
index f0a26309b6d5..a46c33692aa2 100644
--- a/tools/include/uapi/linux/fs.h
+++ b/tools/include/uapi/linux/fs.h
@@ -28,8 +28,8 @@
* nr_file rlimit, so it's safe to set up a ridiculously high absolute
* upper limit on files-per-process.
*
- * Some programs (notably those using select()) may have to be
- * recompiled to take full advantage of the new limits..
+ * Some programs (notably those using select()) may have to be
+ * recompiled to take full advantage of the new limits..
*/
/* Fixed constants first: */
@@ -60,6 +60,17 @@
#define RENAME_EXCHANGE (1 << 1) /* Exchange source and dest */
#define RENAME_WHITEOUT (1 << 2) /* Whiteout source */
+/*
+ * The root inode of procfs is guaranteed to always have the same inode number.
+ * For programs that make heavy use of procfs, verifying that the root is a
+ * real procfs root and using openat2(RESOLVE_{NO_{XDEV,MAGICLINKS},BENEATH})
+ * will allow you to make sure you are never tricked into operating on the
+ * wrong procfs file.
+ */
+enum procfs_ino {
+ PROCFS_ROOT_INO = 1,
+};
+
struct file_clone_range {
__s64 src_fd;
__u64 src_offset;
@@ -77,7 +88,7 @@ struct fstrim_range {
* We include a length field because some filesystems (vfat) have an identifier
* that we do want to expose as a UUID, but doesn't have the standard length.
*
- * We use a fixed size buffer beacuse this interface will, by fiat, never
+ * We use a fixed size buffer because this interface will, by fiat, never
* support "UUIDs" longer than 16 bytes; we don't want to force all downstream
* users to have to deal with that.
*/
@@ -91,6 +102,63 @@ struct fs_sysfs_path {
__u8 name[128];
};
+/* Protection info capability flags */
+#define LBMD_PI_CAP_INTEGRITY (1 << 0)
+#define LBMD_PI_CAP_REFTAG (1 << 1)
+
+/* Checksum types for Protection Information */
+#define LBMD_PI_CSUM_NONE 0
+#define LBMD_PI_CSUM_IP 1
+#define LBMD_PI_CSUM_CRC16_T10DIF 2
+#define LBMD_PI_CSUM_CRC64_NVME 4
+
+/* sizeof first published struct */
+#define LBMD_SIZE_VER0 16
+
+/*
+ * Logical block metadata capability descriptor
+ * If the device does not support metadata, all the fields will be zero.
+ * Applications must check lbmd_flags to determine whether metadata is
+ * supported or not.
+ */
+struct logical_block_metadata_cap {
+ /* Bitmask of logical block metadata capability flags */
+ __u32 lbmd_flags;
+ /*
+ * The amount of data described by each unit of logical block
+ * metadata
+ */
+ __u16 lbmd_interval;
+ /*
+ * Size in bytes of the logical block metadata associated with each
+ * interval
+ */
+ __u8 lbmd_size;
+ /*
+ * Size in bytes of the opaque block tag associated with each
+ * interval
+ */
+ __u8 lbmd_opaque_size;
+ /*
+ * Offset in bytes of the opaque block tag within the logical block
+ * metadata
+ */
+ __u8 lbmd_opaque_offset;
+ /* Size in bytes of the T10 PI tuple associated with each interval */
+ __u8 lbmd_pi_size;
+ /* Offset in bytes of T10 PI tuple within the logical block metadata */
+ __u8 lbmd_pi_offset;
+ /* T10 PI guard tag type */
+ __u8 lbmd_guard_tag_type;
+ /* Size in bytes of the T10 PI application tag */
+ __u8 lbmd_app_tag_size;
+ /* Size in bytes of the T10 PI reference tag */
+ __u8 lbmd_ref_tag_size;
+ /* Size in bytes of the T10 PI storage tag */
+ __u8 lbmd_storage_tag_size;
+ __u8 pad;
+};
+
/* extent-same (dedupe) ioctls; these MUST match the btrfs ioctl definitions */
#define FILE_DEDUPE_RANGE_SAME 0
#define FILE_DEDUPE_RANGE_DIFFERS 1
@@ -148,6 +216,24 @@ struct fsxattr {
unsigned char fsx_pad[8];
};
+/*
+ * Variable size structure for file_[sg]et_attr().
+ *
+ * Note. This is alternative to the structure 'struct file_kattr'/'struct fsxattr'.
+ * As this structure is passed to/from userspace with its size, this can
+ * be versioned based on the size.
+ */
+struct file_attr {
+ __u64 fa_xflags; /* xflags field value (get/set) */
+ __u32 fa_extsize; /* extsize field value (get/set)*/
+ __u32 fa_nextents; /* nextents field value (get) */
+ __u32 fa_projid; /* project identifier (get/set) */
+ __u32 fa_cowextsize; /* CoW extsize field value (get/set) */
+};
+
+#define FILE_ATTR_SIZE_VER0 24
+#define FILE_ATTR_SIZE_LATEST FILE_ATTR_SIZE_VER0
+
/*
* Flags for the fsx_xflags field
*/
@@ -167,6 +253,14 @@ struct fsxattr {
#define FS_XFLAG_FILESTREAM 0x00004000 /* use filestream allocator */
#define FS_XFLAG_DAX 0x00008000 /* use DAX for IO */
#define FS_XFLAG_COWEXTSIZE 0x00010000 /* CoW extent size allocator hint */
+#define FS_XFLAG_VERITY 0x00020000 /* fs-verity enabled */
+/*
+ * Case handling flags (read-only, cannot be set via ioctl).
+ * Default (neither set) indicates POSIX semantics: case-sensitive
+ * lookups and case-preserving storage.
+ */
+#define FS_XFLAG_CASEFOLD 0x00040000 /* case-insensitive lookups */
+#define FS_XFLAG_CASENONPRESERVING 0x00080000 /* case not preserved */
#define FS_XFLAG_HASATTR 0x80000000 /* no DIFLAG for this */
/* the read-only stuff doesn't really belong here, but any other place is
@@ -212,10 +306,9 @@ struct fsxattr {
#define BLKROTATIONAL _IO(0x12,126)
#define BLKZEROOUT _IO(0x12,127)
#define BLKGETDISKSEQ _IOR(0x12,128,__u64)
-/*
- * A jump here: 130-136 are reserved for zoned block devices
- * (see uapi/linux/blkzoned.h)
- */
+/* 130-136 and 142 are used by zoned block device ioctls (uapi/linux/blkzoned.h) */
+/* 137-141 are used by blk-crypto ioctls (uapi/linux/blk-crypto.h) */
+#define BLKTRACESETUP2 _IOWR(0x12, 142, struct blk_user_trace_setup2)
#define BMAP_IOCTL 1 /* obsolete - kept for compatibility */
#define FIBMAP _IO(0x00,1) /* bmap access */
@@ -249,6 +342,8 @@ struct fsxattr {
* also /sys/kernel/debug/ for filesystems with debugfs exports
*/
#define FS_IOC_GETFSSYSFSPATH _IOR(0x15, 1, struct fs_sysfs_path)
+/* Get logical block metadata capability details */
+#define FS_IOC_GETLBMD_CAP _IOWR(0x15, 2, struct logical_block_metadata_cap)
/*
* Inode flags (FS_IOC_GETFLAGS / FS_IOC_SETFLAGS)
@@ -300,7 +395,16 @@ struct fsxattr {
#define FS_DAX_FL 0x02000000 /* Inode is DAX */
#define FS_INLINE_DATA_FL 0x10000000 /* Reserved for ext4 */
#define FS_PROJINHERIT_FL 0x20000000 /* Create with parents projid */
-#define FS_CASEFOLD_FL 0x40000000 /* Folder is case insensitive */
+/*
+ * FS_CASEFOLD_FL indicates case-insensitive name lookup. The
+ * bit is most often reported on directories, where it controls
+ * lookups of entries within. Filesystems that derive
+ * case-insensitivity from mount or volume state may also report
+ * it on non-directory inodes; userspace must not assume the bit
+ * is directory-only. FS_XFLAG_CASEFOLD reports the same
+ * information read-only via FS_IOC_FSGETXATTR.
+ */
+#define FS_CASEFOLD_FL 0x40000000
#define FS_RESERVED_FL 0x80000000 /* reserved for ext2 lib */
#define FS_FL_USER_VISIBLE 0x0003DFFF /* User visible flags */
@@ -344,10 +448,13 @@ typedef int __bitwise __kernel_rwf_t;
/* buffered IO that drops the cache after reading or writing data */
#define RWF_DONTCACHE ((__force __kernel_rwf_t)0x00000080)
+/* prevent pipe and socket writes from raising SIGPIPE */
+#define RWF_NOSIGNAL ((__force __kernel_rwf_t)0x00000100)
+
/* mask of flags supported by the kernel */
#define RWF_SUPPORTED (RWF_HIPRI | RWF_DSYNC | RWF_SYNC | RWF_NOWAIT |\
RWF_APPEND | RWF_NOAPPEND | RWF_ATOMIC |\
- RWF_DONTCACHE)
+ RWF_DONTCACHE | RWF_NOSIGNAL)
#define PROCFS_IOCTL_MAGIC 'f'
@@ -567,4 +674,16 @@ struct procmap_query {
__u64 build_id_addr; /* in */
};
+/*
+ * Shutdown the filesystem.
+ */
+#define FS_IOC_SHUTDOWN _IOR('X', 125, __u32)
+
+/*
+ * Flags for FS_IOC_SHUTDOWN
+ */
+#define FS_SHUTDOWN_FLAGS_DEFAULT 0x0
+#define FS_SHUTDOWN_FLAGS_LOGFLUSH 0x1 /* flush log but not data*/
+#define FS_SHUTDOWN_FLAGS_NOLOGFLUSH 0x2 /* don't flush log nor data */
+
#endif /* _UAPI_LINUX_FS_H */
--git a/tools/perf/check-headers.sh b/tools/perf/check-headers.sh
index caa7ab26968c..790abfe9f929 100755
--- a/tools/perf/check-headers.sh
+++ b/tools/perf/check-headers.sh
@@ -7,6 +7,7 @@ NC='\033[0m' # No Color
declare -a FILES=(
"include/uapi/linux/const.h"
"include/uapi/linux/bits.h"
+ "include/uapi/linux/fs.h"
"include/uapi/linux/fscrypt.h"
"include/uapi/linux/genetlink.h"
"include/uapi/linux/if_addr.h"
--
2.56.1.915.g69d5ec7298-goog
^ permalink raw reply related [flat|nested] 11+ messages in thread* [PATCH v3 5/7] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events
2026-12-04 6:23 [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
` (3 preceding siblings ...)
2026-12-04 6:23 ` [PATCH v3 4/7] tools headers UAPI: Synchronize linux/fs.h with the kernel sources Ian Rogers
@ 2026-12-04 6:23 ` Ian Rogers
2026-12-04 6:46 ` sashiko-bot
2026-12-04 6:23 ` [PATCH v3 6/7] perf bench synthesize: Add --procmap-query option Ian Rogers
` (3 subsequent siblings)
8 siblings, 1 reply; 11+ messages in thread
From: Ian Rogers @ 2026-12-04 6:23 UTC (permalink / raw)
To: linux-perf-users
Cc: linux-kernel, peterz, mingo, acme, namhyung, jolsa, adrian.hunter,
james.clark, dsahern, andrii, Ian Rogers
When synthesizing MMAP2 events for existing processes perf parses the
text of /proc/<pid>/task/<pid>/maps and then, for each file backed
mapping not already in the DSO cache, opens and parses the ELF file,
within the process' mount namespace, to find its build ID.
Since Linux 6.11 the PROCMAP_QUERY ioctl on the maps file returns the
details of a VMA in binary form and can return the build ID of the
backing file, read by the kernel from the mapped file. As suggested by
Peter Zijlstra, use it to synthesize the mmap events:
- The kernel skips unwanted VMAs, rather than perf parsing and
discarding them.
- Build IDs come from the kernel, avoiding perf opening ELF files and
switching mount namespace.
- Build IDs are found for files perf can't open by path, such as
deleted binaries or those in other mount namespaces.
Without data mmaps a single pass asks the kernel for executable VMAs.
Data mmaps want VMAs that are readable or executable, but query flags
can only require permissions, so a first pass gets the readable VMAs,
skipping inaccessible ones like guard pages, and a second pass gets the
executable VMAs that aren't readable, such as execute-only memory. The
second pass only requests the name of the VMAs it emits. The events for
execute-only VMAs therefore follow the others rather than being in
address order.
The DSO cache is still checked first, keyed by device and inode as
before, with the build ID copied during the lookup, and the kernel is
only asked to read the build ID on a miss, so the build ID of a file is
read once. If the kernel can't provide the build ID then the file is
read as before. As before, files without a build ID aren't remembered,
so each mapping of them misses the cache, costing an extra query to
the kernel before the file is read. Kernel build ID queries via
PROCMAP_QUERY are only enabled on Linux 6.19+ (checked via uname() in
the probe), avoiding a kernel NULL pointer dereference in
filemap_read_folio() on 6.11-6.18 kernels lacking commit 777a8560fd29
("lib/buildid: use __kernel_read() for sleepable context") for
mappings without ->read_folio such as tmpfs, shmem, hugetlbfs,
dma-buf, or devices. On 6.19+, device nodes, kernel
pseudo-filesystems/paths, and other visible non-regular files are also
skipped before asking the kernel for a build ID. Names too long for
the event become "//toolong" as with the text parser. The text parser
remains as a fallback for kernels lacking PROCMAP_QUERY, which is
probed once on /proc/self/maps using pthread_once(), and for other
errors on the first query. The VMA handling shared by both paths is
moved into a helper so both produce identical events.
A difference is that the gate VMA, [vsyscall] on x86-64 and [vectors]
on 32-bit ARM, isn't in the VMA tree and so isn't reported by
PROCMAP_QUERY, while it is shown in the maps file. The kernel never
emits an MMAP2 event for it either, so processes started while
recording already lack it, and as it has no backing file no symbols
were resolved for it.
PROCMAP_QUERY is provided by tools/include/uapi/linux/fs.h.
Using 'perf bench internals synthesize' on an Intel Core i7-14700 with
a 7.1 kernel, pinned to a CPU, with the DSO cache warm after the first
iteration (usec, min / median of 10 interleaved runs):
/proc/pid/maps text PROCMAP_QUERY
exec mmaps only 249.2 / 258.8 172.2 / 177.2
with data mmaps 1458.3 / 1621.8 1631.5 / 1726.2
With data mmaps every readable VMA needs an ioctl and, with a warm DSO
cache, this is about 6% slower than reading the text. With a cold DSO
cache, as at the start of 'perf record -a', the system wide benchmark
('-t -m 1 -M 4', about 32,000 events, unprivileged, min / median of 3
runs) shows the benefit of not opening ELF files:
Threads /proc/pid/maps text PROCMAP_QUERY
1 301943 / 302766 161624 / 164009
2 184631 / 187061 112002 / 115959
3 240013 / 240291 136163 / 215740
4 133571 / 139586 92270 / 95234
The 3 thread PROCMAP_QUERY median is skewed by two noisy runs.
Link: https://lore.kernel.org/lkml/20261202124341.GA677025@noisy.programming.kicks-ass.net/
Suggested-by: Peter Zijlstra <peterz@infradead.org>
Signed-off-by: Ian Rogers <irogers@google.com>
---
Notes:
This change was developed with the help of an AI coding assistant
(Gemini in Jetski), which wrote the initial code, tests and
changelog; it was reviewed, built and tested by the author.
tools/perf/util/synthetic-events.c | 600 ++++++++++++++++++++++++-----
1 file changed, 500 insertions(+), 100 deletions(-)
diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c
index 445199d7bbd4..fe2c36962d1d 100644
--- a/tools/perf/util/synthetic-events.c
+++ b/tools/perf/util/synthetic-events.c
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-2.0-only
#include "util/cgroup.h"
+#include "util/build-id.h"
#include "util/data.h"
#include "util/debug.h"
#include "util/dso.h"
@@ -20,6 +21,8 @@
#include "util/target.h"
#include "util/time-utils.h"
#include <linux/bitops.h>
+#include <linux/compiler.h>
+#include <linux/fs.h> /* PROCMAP_QUERY */
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/zalloc.h>
@@ -34,14 +37,17 @@
#include <dirent.h>
#include <errno.h>
#include <inttypes.h>
+#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <uapi/linux/mman.h> /* To get things like MAP_HUGETLB even on older libc headers */
#include <api/fs/fs.h>
#include <api/io.h>
#include <api/io_dir.h>
+#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
+#include <sys/utsname.h>
#include <fcntl.h>
#include <unistd.h>
@@ -436,9 +442,19 @@ static bool read_proc_maps_line(struct io *io, __u64 *start, __u64 *end,
return true;
}
+/*
+ * Add a build ID to the MMAP2 event. If the build ID is already known, for
+ * example because the PROCMAP_QUERY ioctl returned it, it is passed as
+ * known_bid and the file isn't read. Otherwise the build ID comes from the DSO
+ * cache or by reading the file within the process' mount namespace. If the
+ * DSO for the event's filename and device/inode was already found it may be
+ * passed to avoid looking it up again.
+ */
static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event,
struct machine *machine,
- bool is_kernel)
+ bool is_kernel,
+ struct dso *known_dso,
+ const struct build_id *known_bid)
{
struct build_id bid = { .size = 0, };
struct nsinfo *nsi;
@@ -463,7 +479,17 @@ static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event,
dso_id.mmap2_ino_generation_valid = true;
}
- dso = dsos__findnew_id_build_id(&machine->dsos, event->filename, &dso_id, &bid);
+ if (known_bid && known_bid->size) {
+ /* Set the build ID in the known DSO, if there is one, below. */
+ dso = known_dso ? dso__get(known_dso) : NULL;
+ bid = *known_bid;
+ rc = 0;
+ goto out;
+ }
+ if (known_dso)
+ dso = dso__get(known_dso);
+ else
+ dso = dsos__findnew_id_build_id(&machine->dsos, event->filename, &dso_id, &bid);
if (dso && bid.size) {
/* The DSO already has the build ID, don't set it again. */
dso__zput(dso);
@@ -498,134 +524,506 @@ static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event,
dso__put(dso);
}
-int perf_event__synthesize_mmap_events(const struct perf_tool *tool,
- union perf_event *event,
- pid_t pid, pid_t tgid,
- perf_event__handler_t process,
- struct machine *machine,
- bool mmap_data)
-{
+/* A VMA read from /proc/<pid>/maps or with the PROCMAP_QUERY ioctl. */
+struct synth_mmap2_vma {
+ __u64 start, end, pgoff, ino;
+ u32 prot, flags, maj, min;
+ /* The build ID if provided by the kernel, otherwise size is 0. */
+ struct build_id bid;
+ /* Optional DSO, holding a reference, already found for the VMA. */
+ struct dso *dso;
+};
+
+/* State when synthesizing the MMAP2 events of a process. */
+struct synth_mmap2_state {
+ const struct perf_tool *tool;
+ union perf_event *event;
+ perf_event__handler_t process;
+ struct machine *machine;
+ const char *hugetlbfs_mnt;
+ size_t hugetlbfs_mnt_len;
unsigned long long t;
- char bf[BUFSIZ];
- struct io io;
- bool truncation = false;
- unsigned long long timeout = proc_map_timeout * 1000000ULL;
- int rc = 0;
- const char *hugetlbfs_mnt = hugetlbfs__mountpoint();
- int hugetlbfs_mnt_len = hugetlbfs_mnt ? strlen(hugetlbfs_mnt) : 0;
+ unsigned long long timeout;
+ pid_t pid;
+ pid_t tgid;
+ bool mmap_data;
+ /* Set when the timeout is exceeded, no more events should follow. */
+ bool truncation;
+};
- if (machine__is_default_guest(machine))
- return 0;
+/*
+ * Complete and process the MMAP2 event for a VMA whose name has already been
+ * written to event->mmap2.filename. Unwanted VMAs are skipped. Returns 0 on
+ * success, or -1 if processing the event failed.
+ */
+static int synth_mmap2_state__process_vma(struct synth_mmap2_state *state,
+ struct synth_mmap2_vma *vma)
+{
+ static const char anonstr[] = "//anon";
+ union perf_event *event = state->event;
+ struct machine *machine = state->machine;
+ size_t size, aligned_size;
- snprintf(bf, sizeof(bf), "%s/proc/%d/task/%d/maps",
- machine->root_dir, pid, pid);
+ if (!strcmp(event->mmap2.filename, ""))
+ strcpy(event->mmap2.filename, anonstr);
- io.fd = open(bf, O_RDONLY, 0);
- if (io.fd < 0) {
- /*
- * We raced with a task exiting - just return:
- */
- pr_debug("couldn't open %s\n", bf);
- return -1;
+ if (state->hugetlbfs_mnt_len &&
+ !strncmp(event->mmap2.filename, state->hugetlbfs_mnt, state->hugetlbfs_mnt_len)) {
+ strcpy(event->mmap2.filename, anonstr);
+ vma->flags |= MAP_HUGETLB;
+ /* No build ID for "//anon", as when reading the file. */
+ vma->bid.size = 0;
+ dso__zput(vma->dso);
}
- io__init(&io, io.fd, bf, sizeof(bf));
- event->header.type = PERF_RECORD_MMAP2;
- t = rdclock();
+ size = strlen(event->mmap2.filename) + 1;
+ aligned_size = PERF_ALIGN(size, sizeof(u64));
+
+ event->mmap2.header.type = PERF_RECORD_MMAP2;
+
+ /*
+ * Just like the kernel, see perf_misc_flags() in
+ * kernel/events/core.c
+ */
+ if (machine__is_host(machine))
+ event->header.misc = PERF_RECORD_MISC_USER;
+ else
+ event->header.misc = PERF_RECORD_MISC_GUEST_USER;
+
+ if ((rdclock() - state->t) > state->timeout) {
+ pr_warning("Reading %s/proc/%d/task/%d/maps time out. You may want to increase the time limit by --proc-map-timeout\n",
+ machine->root_dir, state->pid, state->pid);
+ state->truncation = true;
+ goto out;
+ }
+
+ if ((vma->prot & PROT_EXEC) == 0) {
+ if (!state->mmap_data || (vma->prot & PROT_READ) == 0)
+ return 0;
+
+ event->header.misc |= PERF_RECORD_MISC_MMAP_DATA;
+ }
+
+out:
+ if (state->truncation)
+ event->header.misc |= PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT;
+
+ event->mmap2.header.size =
+ offsetof(struct perf_record_mmap2, filename) +
+ aligned_size;
+
+ /* Zero the padding and ID header trailer safely! */
+ memset((char *)event + offsetof(struct perf_record_mmap2, filename) + size, 0,
+ (aligned_size - size) + machine->id_hdr_size);
+
+ event->mmap2.header.size += machine->id_hdr_size;
+ event->mmap2.start = vma->start;
+ event->mmap2.len = vma->end - vma->start;
+ event->mmap2.pgoff = vma->pgoff;
+ event->mmap2.maj = vma->maj;
+ event->mmap2.min = vma->min;
+ event->mmap2.ino = vma->ino;
+ event->mmap2.ino_generation = 0;
+ event->mmap2.pid = state->tgid;
+ event->mmap2.tid = state->pid;
+ event->mmap2.prot = vma->prot;
+ event->mmap2.flags = vma->flags;
+
+ if (!symbol_conf.no_buildid_mmap2)
+ perf_record_mmap2__read_build_id(&event->mmap2, machine, false,
+ vma->dso, &vma->bid);
+
+ if (perf_tool__process_synth_event(state->tool, event, machine, state->process) != 0)
+ return -1;
+
+ return 0;
+}
+
+/* Synthesize MMAP2 events by parsing the text of the maps file. */
+static int synth_mmap2_state__read_maps_text(struct synth_mmap2_state *state, int fd,
+ char *bf, size_t bf_size)
+{
+ union perf_event *event = state->event;
+ const size_t name_size = sizeof(event->mmap2.filename) - state->machine->id_hdr_size;
+ struct io io;
+
+ io__init(&io, fd, bf, bf_size);
while (!io.eof) {
- static const char anonstr[] = "//anon";
- size_t size, aligned_size;
- __u64 start, end, pgoff, ino;
- u32 prot, flags, maj, min;
+ struct synth_mmap2_vma vma = { .bid = { .size = 0, }, };
/* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
/* Read directly into event->mmap2.filename, clamping for id_hdr_size! */
- if (!read_proc_maps_line(&io, &start, &end,
- &prot, &flags, &pgoff,
- &maj, &min, &ino,
- sizeof(event->mmap2.filename) - machine->id_hdr_size,
- event->mmap2.filename)) {
+ if (!read_proc_maps_line(&io, &vma.start, &vma.end,
+ &vma.prot, &vma.flags, &vma.pgoff,
+ &vma.maj, &vma.min, &vma.ino,
+ name_size, event->mmap2.filename)) {
if (io.eof)
break;
continue;
}
- if (!strcmp(event->mmap2.filename, ""))
- strcpy(event->mmap2.filename, anonstr);
+ if (synth_mmap2_state__process_vma(state, &vma))
+ return -1;
- if (hugetlbfs_mnt_len &&
- !strncmp(event->mmap2.filename, hugetlbfs_mnt, hugetlbfs_mnt_len)) {
- strcpy(event->mmap2.filename, anonstr);
- flags |= MAP_HUGETLB;
- }
+ if (state->truncation)
+ break;
+ }
+ return 0;
+}
- size = strlen(event->mmap2.filename) + 1;
- aligned_size = PERF_ALIGN(size, sizeof(u64));
+/*
+ * Set once by procmap_query__probe(): whether the running kernel supports
+ * PROCMAP_QUERY, and whether it is safe to ask PROCMAP_QUERY for build IDs
+ * (Linux 6.19+, containing commit 777a8560fd29 "lib/buildid: use
+ * __kernel_read() for sleepable context").
+ */
+static bool procmap_query_supported;
+static bool procmap_query_build_id_supported;
- event->mmap2.header.type = PERF_RECORD_MMAP2;
+static void procmap_query__probe(void)
+{
+ struct procmap_query q = {
+ .size = sizeof(q),
+ .query_flags = PROCMAP_QUERY_COVERING_OR_NEXT_VMA,
+ };
+ struct utsname uts;
+ unsigned int major, minor;
+ int fd = open("/proc/self/maps", O_RDONLY);
- /*
- * Just like the kernel, see perf_misc_flags() in
- * kernel/events/core.c
- */
- if (machine__is_host(machine))
- event->header.misc = PERF_RECORD_MISC_USER;
- else
- event->header.misc = PERF_RECORD_MISC_GUEST_USER;
+ if (fd < 0)
+ return;
+
+ procmap_query_supported = ioctl(fd, PROCMAP_QUERY, &q) == 0 || errno == ENOENT;
+ close(fd);
+ if (!procmap_query_supported) {
+ pr_debug("PROCMAP_QUERY not supported, reading maps files as text\n");
+ return;
+ }
+
+ /*
+ * On 6.11-6.18 kernels lacking commit 777a8560fd29, querying a build ID
+ * on a VMA backed by a filesystem without ->read_folio (such as tmpfs,
+ * shmem, hugetlbfs, dma-buf, or device files) can trigger a kernel NULL
+ * pointer dereference in filemap_read_folio(). Only request build IDs
+ * from PROCMAP_QUERY on Linux 6.19+.
+ */
+ if (uname(&uts) == 0 &&
+ sscanf(uts.release, "%u.%u", &major, &minor) == 2 &&
+ (major > 6 || (major == 6 && minor >= 19))) {
+ procmap_query_build_id_supported = true;
+ } else {
+ pr_debug("PROCMAP_QUERY build ID queries disabled on kernel < 6.19\n");
+ }
+}
+
+static bool procmap_query__supported(void)
+{
+ static pthread_once_t once = PTHREAD_ONCE_INIT;
+
+ pthread_once(&once, procmap_query__probe);
+ return procmap_query_supported;
+}
+
+static bool procmap_query__skip_build_id(struct machine *machine, const char *name)
+{
+ struct stat st;
- if ((rdclock() - t) > timeout) {
- pr_warning("Reading %s/proc/%d/task/%d/maps time out. You may want to increase the time limit by --proc-map-timeout\n",
- machine->root_dir, pid, pid);
- truncation = true;
- goto out;
+ /*
+ * Skip device nodes and kernel pseudo-filesystems/paths before asking
+ * the kernel for a build ID: do_procmap_query() passes vma->vm_file
+ * straight to build_id_parse_file() -> __kernel_read(), which warns on
+ * device files without ->read_iter and wastes a query on non-ELF
+ * pseudo-paths.
+ */
+ if (strstarts(name, "/dev/") || strstarts(name, "/sys/") ||
+ strstarts(name, "/proc/") || strstarts(name, "/memfd:") ||
+ strstarts(name, "/dmabuf:") || strstarts(name, "/anon_hugepage") ||
+ strstarts(name, "/SYSV") || strstarts(name, "/["))
+ return true;
+
+ /*
+ * Skip any other non-regular file visible in this mount namespace.
+ * If stat() fails (e.g. a deleted binary or a file only in the
+ * target's mount namespace), still let the kernel try.
+ */
+ if (machine__is_host(machine) && stat(name, &st) == 0 && !S_ISREG(st.st_mode))
+ return true;
+
+ return false;
+}
+
+/*
+ * Find the DSO and build ID of the file backing a VMA found by PROCMAP_QUERY.
+ * The DSO cache is checked first, so that the kernel only reads the build ID
+ * once per file. On a hit the cached build ID is used and the DSO isn't kept.
+ * On a miss the DSO is kept, so the build ID can be added to it, and the VMA
+ * is queried again asking the kernel for the build ID. If the kernel can't
+ * provide it, the build ID is left empty and perf_record_mmap2__read_build_id()
+ * will try to read it from the file.
+ */
+static void synth_mmap2_state__vma_build_id(struct synth_mmap2_state *state, int fd,
+ const struct procmap_query *found,
+ const char *name, struct synth_mmap2_vma *vma)
+{
+ struct dso_id dso_id = dso_id_empty;
+ struct procmap_query q = {
+ .size = sizeof(q),
+ .query_addr = found->vma_start,
+ };
+ u8 build_id[BUILD_ID_SIZE];
+
+ dso_id.maj = found->dev_major;
+ dso_id.min = found->dev_minor;
+ dso_id.ino = found->inode;
+ dso_id.ino_generation = 0;
+ dso_id.mmap2_valid = true;
+ dso_id.mmap2_ino_generation_valid = true;
+
+ vma->dso = dsos__findnew_id_build_id(&state->machine->dsos, name, &dso_id, &vma->bid);
+ if (vma->bid.size) {
+ dso__zput(vma->dso);
+ return;
+ }
+ if (procmap_query__skip_build_id(state->machine, name))
+ return;
+
+ q.build_id_addr = (uintptr_t)build_id;
+ q.build_id_size = sizeof(build_id);
+ if (ioctl(fd, PROCMAP_QUERY, &q) < 0 || q.build_id_size == 0)
+ return;
+
+ /* Ignore the build ID if the VMA was changed. */
+ if (q.vma_start != found->vma_start || q.inode != found->inode ||
+ q.dev_major != found->dev_major || q.dev_minor != found->dev_minor)
+ return;
+
+ build_id__init(&vma->bid, build_id, q.build_id_size);
+}
+
+/*
+ * Synthesize MMAP2 events for the VMAs found by PROCMAP_QUERY with the given
+ * query flags. When skip_readable is true readable VMAs are skipped, as an
+ * earlier pass handled them, and their names aren't requested. first is true
+ * until a query succeeds and is shared by passes. Returns 0 on success, -1 if
+ * processing an event failed or 1 if the first query failed and the maps file
+ * should be read as text instead.
+ */
+static int synth_mmap2_state__procmap_query_pass(struct synth_mmap2_state *state, int fd,
+ __u64 query_flags, bool skip_readable,
+ bool *first)
+{
+ union perf_event *event = state->event;
+ char *name = event->mmap2.filename;
+ const u32 name_size = sizeof(event->mmap2.filename) - state->machine->id_hdr_size;
+ __u64 addr = 0;
+
+ while (true) {
+ struct synth_mmap2_vma vma = { .bid = { .size = 0, }, };
+ struct procmap_query q;
+ bool want_name = !skip_readable;
+ bool name_too_long = false;
+ int ret;
+retry:
+ q = (struct procmap_query){
+ .size = sizeof(q),
+ .query_flags = query_flags,
+ .query_addr = addr,
+ };
+ if (want_name) {
+ q.vma_name_addr = (uintptr_t)name;
+ q.vma_name_size = name_size;
}
- if ((prot & PROT_EXEC) == 0) {
- if (!mmap_data || (prot & PROT_READ) == 0)
+ while (ioctl(fd, PROCMAP_QUERY, &q) < 0) {
+ int err = errno;
+
+ /* No more VMAs. */
+ if (err == ENOENT)
+ return 0;
+
+ /* The name doesn't fit, retry without it. */
+ if (err == ENAMETOOLONG && q.vma_name_size) {
+ name_too_long = true;
+ q.vma_name_addr = 0;
+ q.vma_name_size = 0;
continue;
+ }
- event->header.misc |= PERF_RECORD_MISC_MMAP_DATA;
+ if (*first) {
+ /*
+ * Read the text for just this process, for
+ * example if its maps file is in another
+ * machine's root_dir without PROCMAP_QUERY.
+ */
+ pr_debug("PROCMAP_QUERY failed for pid %d (errno %d), reading maps file\n",
+ state->pid, err);
+ return 1;
+ }
+
+ /* Likely the process exited, stop as reading text would. */
+ pr_debug("PROCMAP_QUERY failed for pid %d at %#llx (errno %d)\n",
+ state->pid, (unsigned long long)addr, err);
+ return 0;
}
+ *first = false;
-out:
- if (truncation)
- event->header.misc |= PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT;
+ if (skip_readable && (q.vma_flags & PROCMAP_QUERY_VMA_READABLE)) {
+ if ((rdclock() - state->t) <= state->timeout) {
+ if (q.vma_end <= addr)
+ return 0;
+ addr = q.vma_end;
+ continue;
+ }
+ /*
+ * Timed out while skipping readable VMAs. Proceed to
+ * want_name to fetch the VMA's name so that
+ * synth_mmap2_state__process_vma() warns and emits the
+ * real VMA with PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT.
+ */
+ }
+ if (!want_name) {
+ /*
+ * A wanted VMA (or a timeout), query it again to get
+ * its name without moving addr backwards (a covering
+ * VMA can start below addr, and moving backwards could
+ * loop if a concurrent mprotect() flips its prefix).
+ */
+ want_name = true;
+ if (q.vma_start > addr)
+ addr = q.vma_start;
+ goto retry;
+ }
- event->mmap2.header.size =
- offsetof(struct perf_record_mmap2, filename) +
- aligned_size;
+ vma.start = q.vma_start;
+ vma.end = q.vma_end;
+ vma.pgoff = q.vma_offset;
+ vma.maj = q.dev_major;
+ vma.min = q.dev_minor;
+ vma.ino = q.inode;
+ vma.prot = 0;
+ if (q.vma_flags & PROCMAP_QUERY_VMA_READABLE)
+ vma.prot |= PROT_READ;
+ if (q.vma_flags & PROCMAP_QUERY_VMA_WRITABLE)
+ vma.prot |= PROT_WRITE;
+ if (q.vma_flags & PROCMAP_QUERY_VMA_EXECUTABLE)
+ vma.prot |= PROT_EXEC;
+ vma.flags = (q.vma_flags & PROCMAP_QUERY_VMA_SHARED) ? MAP_SHARED : MAP_PRIVATE;
+
+ if (name_too_long)
+ strlcpy(name, "//toolong", name_size);
+ else if (q.vma_name_size == 0)
+ name[0] = '\0';
- /* Zero the padding and ID header trailer safely! */
- memset((char *)event + offsetof(struct perf_record_mmap2, filename) + size, 0,
- (aligned_size - size) + machine->id_hdr_size);
-
- event->mmap2.header.size += machine->id_hdr_size;
- event->mmap2.start = start;
- event->mmap2.len = end - start;
- event->mmap2.pgoff = pgoff;
- event->mmap2.maj = maj;
- event->mmap2.min = min;
- event->mmap2.ino = ino;
- event->mmap2.ino_generation = 0;
- event->mmap2.pid = tgid;
- event->mmap2.tid = pid;
- event->mmap2.prot = prot;
- event->mmap2.flags = flags;
-
- if (!symbol_conf.no_buildid_mmap2)
- perf_record_mmap2__read_build_id(&event->mmap2, machine, false);
-
- if (perf_tool__process_synth_event(tool, event, machine, process) != 0) {
- rc = -1;
- break;
- }
+ /*
+ * Get the build ID of wanted file backed VMAs. Other VMAs
+ * have no build ID, or are unwanted and skipped.
+ */
+ if (procmap_query_build_id_supported && !symbol_conf.no_buildid_mmap2 &&
+ q.inode && name[0] == '/' && name[1] != '/' &&
+ ((vma.prot & PROT_EXEC) || (state->mmap_data && (vma.prot & PROT_READ))) &&
+ (!state->hugetlbfs_mnt_len ||
+ strncmp(name, state->hugetlbfs_mnt, state->hugetlbfs_mnt_len)))
+ synth_mmap2_state__vma_build_id(state, fd, &q, name, &vma);
+
+ ret = synth_mmap2_state__process_vma(state, &vma);
+ dso__put(vma.dso);
+ if (ret)
+ return -1;
- if (truncation)
- break;
+ if (state->truncation || q.vma_end <= addr)
+ return 0;
+ addr = q.vma_end;
}
+}
- close(io.fd);
+/*
+ * Synthesize MMAP2 events using the PROCMAP_QUERY ioctl on the maps file. The
+ * kernel skips unwanted VMAs and provides the build ID, avoiding perf opening
+ * the ELF file within the process' mount namespace. Returns 0 on success, -1
+ * if processing an event failed or 1 if the maps file should be read as text
+ * instead.
+ */
+static int synth_mmap2_state__procmap_query(struct synth_mmap2_state *state, int fd)
+{
+ bool first = true;
+ int ret;
+
+ /* Without data mmaps only executable VMAs are wanted. */
+ if (!state->mmap_data) {
+ return synth_mmap2_state__procmap_query_pass(state, fd,
+ PROCMAP_QUERY_COVERING_OR_NEXT_VMA |
+ PROCMAP_QUERY_VMA_EXECUTABLE,
+ /*skip_readable=*/false, &first);
+ }
+
+ /*
+ * Data mmaps want VMAs that are readable or executable, but query
+ * flags can only require permissions. First get the readable VMAs,
+ * skipping inaccessible ones like guard pages, then the executable
+ * VMAs that aren't readable, such as execute-only memory.
+ */
+ ret = synth_mmap2_state__procmap_query_pass(state, fd,
+ PROCMAP_QUERY_COVERING_OR_NEXT_VMA |
+ PROCMAP_QUERY_VMA_READABLE,
+ /*skip_readable=*/false, &first);
+ if (ret || state->truncation)
+ return ret;
+
+ return synth_mmap2_state__procmap_query_pass(state, fd,
+ PROCMAP_QUERY_COVERING_OR_NEXT_VMA |
+ PROCMAP_QUERY_VMA_EXECUTABLE,
+ /*skip_readable=*/true, &first);
+}
+
+int perf_event__synthesize_mmap_events(const struct perf_tool *tool,
+ union perf_event *event,
+ pid_t pid, pid_t tgid,
+ perf_event__handler_t process,
+ struct machine *machine,
+ bool mmap_data)
+{
+ char bf[BUFSIZ];
+ const char *hugetlbfs_mnt = hugetlbfs__mountpoint();
+ struct synth_mmap2_state state = {
+ .tool = tool,
+ .event = event,
+ .process = process,
+ .machine = machine,
+ .hugetlbfs_mnt = hugetlbfs_mnt,
+ .hugetlbfs_mnt_len = hugetlbfs_mnt ? strlen(hugetlbfs_mnt) : 0,
+ .timeout = proc_map_timeout * 1000000ULL,
+ .pid = pid,
+ .tgid = tgid,
+ .mmap_data = mmap_data,
+ };
+ int fd, rc = 1;
+
+ if (machine__is_default_guest(machine))
+ return 0;
+
+ snprintf(bf, sizeof(bf), "%s/proc/%d/task/%d/maps",
+ machine->root_dir, pid, pid);
+
+ fd = open(bf, O_RDONLY, 0);
+ if (fd < 0) {
+ /*
+ * We raced with a task exiting - just return:
+ */
+ pr_debug("couldn't open %s\n", bf);
+ return -1;
+ }
+
+ event->header.type = PERF_RECORD_MMAP2;
+ state.t = rdclock();
+
+ if (procmap_query__supported())
+ rc = synth_mmap2_state__procmap_query(&state, fd);
+
+ if (rc > 0)
+ rc = synth_mmap2_state__read_maps_text(&state, fd, bf, sizeof(bf));
+
+ close(fd);
return rc;
}
@@ -814,7 +1212,8 @@ static int perf_event__synthesize_modules_maps_cb(struct map *map, void *data)
event->mmap2.__reserved_1 = 0;
event->mmap2.__reserved_2 = 0;
- perf_record_mmap2__read_build_id(&event->mmap2, args->machine, false);
+ perf_record_mmap2__read_build_id(&event->mmap2, args->machine, false,
+ /*known_dso=*/NULL, /*known_bid=*/NULL);
} else {
const char *long_name = dso__long_name(dso);
@@ -1301,7 +1700,8 @@ static int __perf_event__synthesize_kernel_mmap(const struct perf_tool *tool,
event->mmap2.len = map__end(map) - event->mmap.start;
event->mmap2.pid = machine->pid;
- perf_record_mmap2__read_build_id(&event->mmap2, machine, true);
+ perf_record_mmap2__read_build_id(&event->mmap2, machine, true,
+ /*known_dso=*/NULL, /*known_bid=*/NULL);
} else {
size = snprintf(event->mmap.filename, sizeof(event->mmap.filename),
"%s%s", machine->mmap_name, kmap->ref_reloc_sym->name) + 1;
--
2.56.1.915.g69d5ec7298-goog
^ permalink raw reply related [flat|nested] 11+ messages in thread* Re: [PATCH v3 5/7] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events
2026-12-04 6:23 ` [PATCH v3 5/7] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events Ian Rogers
@ 2026-12-04 6:46 ` sashiko-bot
0 siblings, 0 replies; 11+ messages in thread
From: sashiko-bot @ 2026-12-04 6:46 UTC (permalink / raw)
To: Ian Rogers, linux-perf-users
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] perf: PROCMAP_QUERY enabled on 6.11-6.18 without build ID or
VMA locks
--
commit 22c6077b6804349c8a83a045b52a96cac3269331
Author: Ian Rogers <irogers@google.com>
perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events
This commit uses the PROCMAP_QUERY ioctl on /proc/<pid>/task/<pid>/maps
to synthesize MMAP2 events and fetch kernel-provided build IDs on Linux
6.19+, falling back to reading the maps file as text when PROCMAP_QUERY
is unavailable.
Link: https://lore.kernel.org/lkml/20261202124341.GA677025@noisy.programming.kicks-ass.net/
> diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c
> index 445199d7bbd46..fe2c36962d1d0 100644
> --- a/tools/perf/util/synthetic-events.c
> +++ b/tools/perf/util/synthetic-events.c
> @@ -498,134 +524,506 @@ static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event,
[ ... ]
> + if (procmap_query__supported())
> + rc = synth_mmap2_state__procmap_query(&state, fd);
> +
> + if (rc > 0)
> + rc = synth_mmap2_state__read_maps_text(&state, fd, bf, sizeof(bf));
[Severity: Medium]
Should synth_mmap2_state__procmap_query() be skipped when mmap_data is
true on Linux 6.11-6.18?
On those kernels, procmap_query__probe() leaves
procmap_query_build_id_supported false, so data-mmap synthesis (such as
perf record --call-graph dwarf) pays the per-VMA ioctl and two-pass scan
cost with no build-ID speedup, regressing both warm and cold DSO caches.
On Linux 6.17, PROCMAP_QUERY also regresses target mm->mmap_lock
contention for both exec-only and data-mmap synthesis.
Text /proc/<pid>/maps uses per-VMA locks since 5631da56c9a8
("fs/proc/task_mmu: read proc/pid/maps under per-vma lock"), whereas
PROCMAP_QUERY gained them in 6.18 via d9d1c2d81797 ("fs/proc/task_mmu:
execute PROCMAP_QUERY ioctl under per-vma locks").
Falling back to synth_mmap2_state__read_maps_text() when mmap_data is
true without procmap_query_build_id_supported (and on Linux 6.17) would
avoid these regressions while keeping the exec-only speedup on 6.11-6.16
and 6.18.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261204062328.2508164-1-irogers@google.com?part=5
^ permalink raw reply [flat|nested] 11+ messages in thread
* [PATCH v3 6/7] perf bench synthesize: Add --procmap-query option
2026-12-04 6:23 [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
` (4 preceding siblings ...)
2026-12-04 6:23 ` [PATCH v3 5/7] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events Ian Rogers
@ 2026-12-04 6:23 ` Ian Rogers
2026-12-04 6:23 ` [PATCH v3 7/7] perf test: Add test comparing PROCMAP_QUERY and /proc/pid/maps synthesis Ian Rogers
` (2 subsequent siblings)
8 siblings, 0 replies; 11+ messages in thread
From: Ian Rogers @ 2026-12-04 6:23 UTC (permalink / raw)
To: linux-perf-users
Cc: linux-kernel, peterz, mingo, acme, namhyung, jolsa, adrian.hunter,
james.clark, dsahern, andrii, Ian Rogers
Add a --[no-]procmap-query option to 'perf bench internals synthesize'
so that synthesizing mmap events using the PROCMAP_QUERY ioctl can be
compared with parsing the text of /proc/<pid>/maps. The mode used is
printed at the start of the benchmark. As the text parser may be
wanted for debugging or comparison when recording, also add a
core.procmap-query perf config option that, when false, disables the
use of PROCMAP_QUERY.
$ perf bench internals synthesize --no-procmap-query
# Running 'internals/synthesize' benchmark:
Reading mmaps using /proc/pid/maps text
Computing performance of single threaded perf event synthesis by
synthesizing events on the perf process itself:
Average synthesis took: 273.436 usec (+- 2.084 usec)
Average num. events: 62.000 (+- 0.000)
Average time per event 4.410 usec
Average data synthesis took: 1680.164 usec (+- 12.119 usec)
Average num. events: 333.000 (+- 0.000)
Average time per event 5.046 usec
Signed-off-by: Ian Rogers <irogers@google.com>
---
Notes:
This change was developed with the help of an AI coding assistant
(Gemini in Jetski), which wrote the initial code, tests and
changelog; it was reviewed, built and tested by the author.
tools/perf/Documentation/perf-bench.txt | 4 +++-
tools/perf/Documentation/perf-config.txt | 5 +++++
tools/perf/bench/synthesize.c | 6 ++++++
tools/perf/util/config.c | 4 ++++
tools/perf/util/synthetic-events.c | 3 ++-
tools/perf/util/synthetic-events.h | 6 ++++++
6 files changed, 26 insertions(+), 2 deletions(-)
diff --git a/tools/perf/Documentation/perf-bench.txt b/tools/perf/Documentation/perf-bench.txt
index c65dd8f4131f..ca53d6de2851 100644
--- a/tools/perf/Documentation/perf-bench.txt
+++ b/tools/perf/Documentation/perf-bench.txt
@@ -349,7 +349,9 @@ Suite for evaluating multiple epoll_ctl calls.
SUITES FOR 'internals'
~~~~~~~~~~~~~~~~~~~~~~
*synthesize*::
-Suite for evaluating perf's event synthesis performance.
+Suite for evaluating perf's event synthesis performance. The
+--no-procmap-query option reads mmaps by parsing the text of
+/proc/<pid>/maps rather than with the PROCMAP_QUERY ioctl.
*symbols*::
Suite for evaluating ELF symbol loading, sorting, and lookup performance.
diff --git a/tools/perf/Documentation/perf-config.txt b/tools/perf/Documentation/perf-config.txt
index 6cff6f26af8d..aad31a33ce56 100644
--- a/tools/perf/Documentation/perf-config.txt
+++ b/tools/perf/Documentation/perf-config.txt
@@ -210,6 +210,11 @@ core.*::
Sets a timeout (in milliseconds) for parsing /proc/<pid>/maps files.
Can be overridden by the --proc-map-timeout option on supported
subcommands. The default timeout is 500ms.
+ procmap-query::
+ When 'true' (the default) mmap events for existing processes
+ are synthesized using the PROCMAP_QUERY ioctl, if supported by
+ the kernel, which also provides the build ID of the mapped
+ file. When 'false' the text of /proc/<pid>/maps is parsed.
addr2line-disable-warn::
When set to 'true' disable all warnings from 'addr2line' output.
Default setting is 'false' to show these warnings.
diff --git a/tools/perf/bench/synthesize.c b/tools/perf/bench/synthesize.c
index fdc5465db3f0..c1217f5c1fb3 100644
--- a/tools/perf/bench/synthesize.c
+++ b/tools/perf/bench/synthesize.c
@@ -41,6 +41,8 @@ static const struct option options[] = {
"Number of iterations used to compute single-threaded average"),
OPT_UINTEGER('I', "multi-iterations", &multi_iterations,
"Number of iterations used to compute multi-threaded average"),
+ OPT_BOOLEAN(0, "procmap-query", &synthesize_procmap_query,
+ "Use PROCMAP_QUERY, if supported, rather than /proc/pid/maps text"),
OPT_END()
};
@@ -268,6 +270,10 @@ int bench_synthesize(int argc, const char **argv)
return err;
}
+ printf("Reading mmaps using %s\n",
+ synthesize_procmap_query ? "the PROCMAP_QUERY ioctl, if supported"
+ : "/proc/pid/maps text");
+
if (run_st)
err = run_single_threaded(&host_env);
diff --git a/tools/perf/util/config.c b/tools/perf/util/config.c
index 0e6b77a0a5e7..83963e607506 100644
--- a/tools/perf/util/config.c
+++ b/tools/perf/util/config.c
@@ -39,6 +39,7 @@
#include "util/evsel.h" /* evsel__hw_names, evsel__use_bpf_counters */
#include "util/hist.h" /* perf_hist_config */
#include "util/stat.h" /* perf_stat__set_big_num */
+#include "util/synthetic-events.h" /* synthesize_procmap_query */
#define MAXNAME (256)
@@ -483,6 +484,9 @@ static int perf_default_core_config(const char *var, const char *value)
if (!strcmp(var, "core.proc-map-timeout"))
proc_map_timeout = strtoul(value, NULL, 10);
+ if (!strcmp(var, "core.procmap-query"))
+ synthesize_procmap_query = perf_config_bool(var, value);
+
if (!strcmp(var, "core.addr2line-timeout"))
symbol_conf.addr2line_timeout_ms = strtoul(value, NULL, 10);
diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c
index fe2c36962d1d..d84449c7e98c 100644
--- a/tools/perf/util/synthetic-events.c
+++ b/tools/perf/util/synthetic-events.c
@@ -54,6 +54,7 @@
#define DEFAULT_PROC_MAP_PARSE_TIMEOUT 500
unsigned int proc_map_timeout = DEFAULT_PROC_MAP_PARSE_TIMEOUT;
+bool synthesize_procmap_query = true;
int perf_tool__process_synth_event(const struct perf_tool *tool,
union perf_event *event,
@@ -1017,7 +1018,7 @@ int perf_event__synthesize_mmap_events(const struct perf_tool *tool,
event->header.type = PERF_RECORD_MMAP2;
state.t = rdclock();
- if (procmap_query__supported())
+ if (synthesize_procmap_query && procmap_query__supported())
rc = synth_mmap2_state__procmap_query(&state, fd);
if (rc > 0)
diff --git a/tools/perf/util/synthetic-events.h b/tools/perf/util/synthetic-events.h
index 243115ea61ae..2f018c51b98e 100644
--- a/tools/perf/util/synthetic-events.h
+++ b/tools/perf/util/synthetic-events.h
@@ -41,6 +41,12 @@ enum perf_record_synth {
int parse_synth_opt(char *str);
+/*
+ * Synthesize mmap events using the PROCMAP_QUERY ioctl, when supported by the
+ * kernel, rather than parsing the text of /proc/<pid>/maps. Defaults to true.
+ */
+extern bool synthesize_procmap_query;
+
typedef int (*perf_event__handler_t)(const struct perf_tool *tool, union perf_event *event,
struct perf_sample *sample, struct machine *machine);
--
2.56.1.915.g69d5ec7298-goog
^ permalink raw reply related [flat|nested] 11+ messages in thread* [PATCH v3 7/7] perf test: Add test comparing PROCMAP_QUERY and /proc/pid/maps synthesis
2026-12-04 6:23 [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
` (5 preceding siblings ...)
2026-12-04 6:23 ` [PATCH v3 6/7] perf bench synthesize: Add --procmap-query option Ian Rogers
@ 2026-12-04 6:23 ` Ian Rogers
2026-12-04 6:46 ` [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis sashiko-bot
2026-12-04 11:11 ` Peter Zijlstra
8 siblings, 0 replies; 11+ messages in thread
From: Ian Rogers @ 2026-12-04 6:23 UTC (permalink / raw)
To: linux-perf-users
Cc: linux-kernel, peterz, mingo, acme, namhyung, jolsa, adrian.hunter,
james.clark, dsahern, andrii, Ian Rogers
Synthesize the MMAP2 events of the perf test process both by parsing
/proc/<pid>/maps and with the PROCMAP_QUERY ioctl, and check the events
are byte for byte identical, including the build ID or device/inode
fields, the filename padding and a 3 u64 id header trailer. The event
buffer is filled with a different byte pattern for each synthesis, so
any byte not written by synthesis causes a mismatch. Each synthesis uses
a new machine so that the DSO build ID cache isn't shared. The
comparison is done with and without build IDs and with and without data
mmaps. The events are sorted by address before being compared, as with
data mmaps PROCMAP_QUERY finds execute-only VMAs after the readable
ones. With data mmaps only file backed mappings are compared, not
"//anon" ones, as anonymous mappings like the heap may change between
the two synthesis runs. The gate VMA, such as [vsyscall], is only in
the maps file and so it is ignored. To cover the execute-only case, a
page of the perf binary is mapped with only PROT_EXEC and the test
checks both paths have an event for it. The test is skipped if the
kernel doesn't support PROCMAP_QUERY.
$ perf test -vv PROCMAP 2>&1 | grep -E 'Compared|PROCMAP'
30: Synthesize MMAP2 events with PROCMAP_QUERY:
Compared 62 MMAP2 events (mmap_data=0, build IDs=1)
Compared 300 MMAP2 events (mmap_data=1, build IDs=1)
Compared 62 MMAP2 events (mmap_data=0, build IDs=0)
Compared 300 MMAP2 events (mmap_data=1, build IDs=0)
30: Synthesize MMAP2 events with PROCMAP_QUERY : Ok
Signed-off-by: Ian Rogers <irogers@google.com>
---
Notes:
This change was developed with the help of an AI coding assistant
(Gemini in Jetski), which wrote the initial code, tests and
changelog; it was reviewed, built and tested by the author.
tools/perf/tests/Build | 1 +
tools/perf/tests/builtin-test.c | 1 +
tools/perf/tests/synthesize-mmap.c | 275 +++++++++++++++++++++++++++++
tools/perf/tests/tests.h | 1 +
4 files changed, 278 insertions(+)
create mode 100644 tools/perf/tests/synthesize-mmap.c
diff --git a/tools/perf/tests/Build b/tools/perf/tests/Build
index a95ca6cbcb6d..ce36ee23a5e9 100644
--- a/tools/perf/tests/Build
+++ b/tools/perf/tests/Build
@@ -29,6 +29,7 @@ perf-test-y += wp.o
perf-test-y += task-exit.o
perf-test-y += sw-clock.o
perf-test-y += mmap-thread-lookup.o
+perf-test-y += synthesize-mmap.o
perf-test-y += thread-maps-share.o
perf-test-y += thread-stack.o
perf-test-$(CONFIG_LIBTRACEEVENT) += switch-tracking.o
diff --git a/tools/perf/tests/builtin-test.c b/tools/perf/tests/builtin-test.c
index f88e4ad8a319..859b2b70b768 100644
--- a/tools/perf/tests/builtin-test.c
+++ b/tools/perf/tests/builtin-test.c
@@ -145,6 +145,7 @@ static struct test_suite *generic_tests[] = {
&suite__parse_no_sample_id_all,
&suite__hists_filter,
&suite__mmap_thread_lookup,
+ &suite__synthesize_procmap_query,
&suite__thread_maps_share,
&suite__thread_stack,
&suite__hists_output,
diff --git a/tools/perf/tests/synthesize-mmap.c b/tools/perf/tests/synthesize-mmap.c
new file mode 100644
index 000000000000..53c6f2b0eeb4
--- /dev/null
+++ b/tools/perf/tests/synthesize-mmap.c
@@ -0,0 +1,275 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Check that synthesizing MMAP2 events using the PROCMAP_QUERY ioctl gives the
+ * same events as parsing the text of /proc/<pid>/maps.
+ */
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#include <linux/fs.h>
+#include <linux/kernel.h>
+#include <linux/string.h>
+#include <linux/zalloc.h>
+#include "debug.h"
+#include "env.h"
+#include "event.h"
+#include "machine.h"
+#include "symbol_conf.h"
+#include "synthetic-events.h"
+#include "tests.h"
+#include "tool.h"
+
+struct synth_events {
+ struct perf_tool tool;
+ union perf_event **events;
+ size_t nr;
+ size_t alloc;
+};
+
+static int process_event(const struct perf_tool *tool, union perf_event *event,
+ struct perf_sample *sample __maybe_unused,
+ struct machine *machine __maybe_unused)
+{
+ struct synth_events *se = container_of(tool, struct synth_events, tool);
+ union perf_event *copy;
+
+ if (se->nr == se->alloc) {
+ size_t alloc = se->alloc ? se->alloc * 2 : 64;
+ union perf_event **events = realloc(se->events, alloc * sizeof(*events));
+
+ if (!events)
+ return -ENOMEM;
+ se->events = events;
+ se->alloc = alloc;
+ }
+ copy = memdup(event, event->header.size);
+ if (!copy)
+ return -ENOMEM;
+ se->events[se->nr++] = copy;
+ return 0;
+}
+
+static void synth_events__exit(struct synth_events *se)
+{
+ for (size_t i = 0; i < se->nr; i++)
+ free(se->events[i]);
+ zfree(&se->events);
+ se->nr = 0;
+ se->alloc = 0;
+}
+
+/*
+ * An id header trailer as when sample_id_all is set, so that its zeroing is
+ * compared too.
+ */
+#define TEST_ID_HDR_SIZE (3 * sizeof(u64))
+
+/*
+ * Synthesize the process' MMAP2 events. The event buffer is filled with fill
+ * first so that any byte of an event not written by synthesis, such as
+ * padding, differs between the two synthesis runs and fails the comparison.
+ */
+static int synthesize(struct synth_events *se, bool procmap_query, bool mmap_data,
+ int fill)
+{
+ bool saved_procmap_query = synthesize_procmap_query;
+ struct perf_env host_env;
+ struct machine *machine;
+ union perf_event *event;
+ int err = -1;
+
+ perf_tool__init(&se->tool, /*ordered_events=*/false);
+ /* Use a new machine so DSO build ID caches aren't shared. */
+ perf_env__init(&host_env);
+ machine = machine__new_host(&host_env);
+ if (!machine)
+ goto out_env;
+ machine->id_hdr_size = TEST_ID_HDR_SIZE;
+
+ event = malloc(sizeof(event->mmap2) + machine->id_hdr_size);
+ if (!event)
+ goto out_machine;
+ memset(event, fill, sizeof(event->mmap2) + machine->id_hdr_size);
+
+ synthesize_procmap_query = procmap_query;
+ err = perf_event__synthesize_mmap_events(&se->tool, event, getpid(), getpid(),
+ process_event, machine, mmap_data);
+ synthesize_procmap_query = saved_procmap_query;
+
+ free(event);
+out_machine:
+ machine__delete(machine);
+out_env:
+ perf_env__exit(&host_env);
+ return err;
+}
+
+static void print_event(const char *prefix, union perf_event *event)
+{
+ pr_debug("%s: ", prefix);
+ if (verbose > 0)
+ perf_event__fprintf_mmap2(event, debug_file());
+}
+
+/*
+ * When synthesizing data mmaps, anonymous memory like the heap may change
+ * between the two synthesis runs due to allocations. Only compare file backed
+ * mappings that should be stable, not "//anon" ones. The gate VMA, such as
+ * [vsyscall] on x86-64, isn't in the process' VMA tree, it is shown in
+ * /proc/<pid>/maps but not reported by PROCMAP_QUERY, so it is ignored.
+ */
+static bool is_stable(union perf_event *event, bool mmap_data)
+{
+ const char *name = event->mmap2.filename;
+
+ if (!strcmp(name, "[vsyscall]") || !strcmp(name, "[vectors]"))
+ return false;
+
+ return !mmap_data || (name[0] == '/' && name[1] != '/');
+}
+
+static int cmp_event(const void *a, const void *b)
+{
+ const union perf_event *ea = *(const union perf_event * const *)a;
+ const union perf_event *eb = *(const union perf_event * const *)b;
+
+ if (ea->mmap2.start != eb->mmap2.start)
+ return ea->mmap2.start < eb->mmap2.start ? -1 : 1;
+ if (ea->header.size != eb->header.size)
+ return ea->header.size < eb->header.size ? -1 : 1;
+ return memcmp(ea, eb, ea->header.size);
+}
+
+/* Is there an event for a mapping at addr? */
+static bool has_mapping(const struct synth_events *se, u64 addr)
+{
+ for (size_t i = 0; i < se->nr; i++) {
+ if (se->events[i]->mmap2.start == addr)
+ return true;
+ }
+ return false;
+}
+
+static int compare(struct synth_events *text, struct synth_events *query, bool mmap_data)
+{
+ size_t i = 0, j = 0, compared = 0;
+ int ret = TEST_OK;
+
+ /*
+ * With data mmaps PROCMAP_QUERY finds the readable VMAs before the
+ * execute-only ones, so order the events by address.
+ */
+ qsort(text->events, text->nr, sizeof(*text->events), cmp_event);
+ qsort(query->events, query->nr, sizeof(*query->events), cmp_event);
+
+ while (true) {
+ while (i < text->nr && !is_stable(text->events[i], mmap_data))
+ i++;
+ while (j < query->nr && !is_stable(query->events[j], mmap_data))
+ j++;
+ if (i == text->nr || j == query->nr)
+ break;
+
+ if (text->events[i]->header.size != query->events[j]->header.size ||
+ memcmp(text->events[i], query->events[j], text->events[i]->header.size)) {
+ pr_debug("MMAP2 event mismatch\n");
+ print_event("text", text->events[i]);
+ print_event("procmap_query", query->events[j]);
+ ret = TEST_FAIL;
+ }
+ compared++;
+ i++;
+ j++;
+ }
+ if (i != text->nr || j != query->nr) {
+ pr_debug("Number of MMAP2 events differs: text %zu procmap_query %zu\n",
+ text->nr, query->nr);
+ ret = TEST_FAIL;
+ }
+ if (compared == 0) {
+ pr_debug("No MMAP2 events compared\n");
+ ret = TEST_FAIL;
+ }
+ pr_debug("Compared %zu MMAP2 events (mmap_data=%d, build IDs=%d)\n",
+ compared, mmap_data, !symbol_conf.no_buildid_mmap2);
+ return ret;
+}
+
+static bool procmap_query_supported(void)
+{
+ struct procmap_query q = {
+ .size = sizeof(q),
+ .query_flags = PROCMAP_QUERY_COVERING_OR_NEXT_VMA,
+ };
+ int fd = open("/proc/self/maps", O_RDONLY);
+ bool ret;
+
+ if (fd < 0)
+ return false;
+ ret = ioctl(fd, PROCMAP_QUERY, &q) == 0;
+ close(fd);
+ return ret;
+}
+
+static int test__synthesize_procmap_query(struct test_suite *test __maybe_unused,
+ int subtest __maybe_unused)
+{
+ bool saved_no_buildid_mmap2 = symbol_conf.no_buildid_mmap2;
+ long page_size = sysconf(_SC_PAGESIZE);
+ int ret = TEST_OK;
+ void *xonly;
+ int fd;
+
+ if (!procmap_query_supported()) {
+ pr_debug("PROCMAP_QUERY not supported\n");
+ return TEST_SKIP;
+ }
+
+ /*
+ * Add an execute-only file mapping, that is found by a second
+ * PROCMAP_QUERY pass when synthesizing data mmaps. Some
+ * architectures may still report it as readable.
+ */
+ fd = open("/proc/self/exe", O_RDONLY);
+ if (fd < 0) {
+ pr_debug("Failed to open /proc/self/exe\n");
+ return TEST_FAIL;
+ }
+ xonly = mmap(NULL, page_size, PROT_EXEC, MAP_PRIVATE, fd, 0);
+ close(fd);
+ if (xonly == MAP_FAILED) {
+ pr_debug("Failed to mmap an execute-only page\n");
+ return TEST_FAIL;
+ }
+
+ for (int i = 0; i < 4 && ret == TEST_OK; i++) {
+ bool mmap_data = i & 1;
+ struct synth_events text = {}, query = {};
+
+ symbol_conf.no_buildid_mmap2 = i & 2;
+ if (synthesize(&text, /*procmap_query=*/false, mmap_data, /*fill=*/0xaa) ||
+ synthesize(&query, /*procmap_query=*/true, mmap_data, /*fill=*/0x55)) {
+ pr_debug("Synthesizing MMAP2 events failed\n");
+ ret = TEST_FAIL;
+ } else if (!has_mapping(&text, (u64)(uintptr_t)xonly) ||
+ !has_mapping(&query, (u64)(uintptr_t)xonly)) {
+ pr_debug("Missing execute-only mapping at %p\n", xonly);
+ ret = TEST_FAIL;
+ } else {
+ ret = compare(&text, &query, mmap_data);
+ }
+ synth_events__exit(&text);
+ synth_events__exit(&query);
+ }
+ symbol_conf.no_buildid_mmap2 = saved_no_buildid_mmap2;
+ munmap(xonly, page_size);
+ return ret;
+}
+
+DEFINE_SUITE("Synthesize MMAP2 events with PROCMAP_QUERY", synthesize_procmap_query);
diff --git a/tools/perf/tests/tests.h b/tools/perf/tests/tests.h
index c0fb260d3f2f..7d259c24a917 100644
--- a/tools/perf/tests/tests.h
+++ b/tools/perf/tests/tests.h
@@ -156,6 +156,7 @@ DECLARE_SUITE(dwarf_unwind);
DECLARE_SUITE(expr);
DECLARE_SUITE(hists_filter);
DECLARE_SUITE(mmap_thread_lookup);
+DECLARE_SUITE(synthesize_procmap_query);
DECLARE_SUITE(thread_maps_share);
DECLARE_SUITE(thread_stack);
DECLARE_SUITE(hists_output);
--
2.56.1.915.g69d5ec7298-goog
^ permalink raw reply related [flat|nested] 11+ messages in thread* Re: [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis
2026-12-04 6:23 [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
` (6 preceding siblings ...)
2026-12-04 6:23 ` [PATCH v3 7/7] perf test: Add test comparing PROCMAP_QUERY and /proc/pid/maps synthesis Ian Rogers
@ 2026-12-04 6:46 ` sashiko-bot
2026-12-04 11:11 ` Peter Zijlstra
8 siblings, 0 replies; 11+ messages in thread
From: sashiko-bot @ 2026-12-04 6:46 UTC (permalink / raw)
To: Ian Rogers, linux-perf-users
Sashiko has finished reviewing this 7-patch series:
- Patches 1-4, 6, and 7: no issues found.
- Patch 5 ("perf synthetic-events: Use PROCMAP_QUERY to synthesi..."): 1
potential issue (1 Medium)
A detailed review has been sent as a separate reply to patch 5.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261204062328.2508164-1-irogers@google.com
^ permalink raw reply [flat|nested] 11+ messages in thread* Re: [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis
2026-12-04 6:23 [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
` (7 preceding siblings ...)
2026-12-04 6:46 ` [PATCH v3 0/7] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis sashiko-bot
@ 2026-12-04 11:11 ` Peter Zijlstra
8 siblings, 0 replies; 11+ messages in thread
From: Peter Zijlstra @ 2026-12-04 11:11 UTC (permalink / raw)
To: Ian Rogers
Cc: linux-perf-users, linux-kernel, mingo, acme, namhyung, jolsa,
adrian.hunter, james.clark, dsahern, andrii
On Thu, Dec 03, 2026 at 10:23:21PM -0800, Ian Rogers wrote:
> Patch 5 adds the PROCMAP_QUERY path. Without data mmaps the kernel
> returns only executable VMAs. With data mmaps (readable or executable
> VMAs are wanted) a first pass gets readable VMAs, skipping guard pages,
> and a second pass gets executable VMAs that aren't readable, such as
> execute-only memory. The DSO cache is consulted first (keyed by
> device/inode as before), and only on a miss is the VMA queried again
> for the kernel to read the build ID, so each file's build ID is read
> once. If the kernel can't give a build ID, the file is read as before,
> with the existing nsinfo handling; no nsinfo or mount namespace work
> is done when the kernel or DSO cache provides the build ID. The text
> parser remains as a fallback when the ioctl isn't supported (probed
> once with pthread_once()) or the first query fails. Shared code is in
> a helper so both paths emit identical events.
> The 3 thread PROCMAP_QUERY median is skewed by two noisy runs; by the
> minimum it is 43% faster.
Nice :-)
^ permalink raw reply [flat|nested] 11+ messages in thread