mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH 0/6] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis
@ 2026-12-04  1:04 Ian Rogers
  2026-12-04  1:04 ` [PATCH 1/6] perf machine: Fix leak when creating host kernel maps fails Ian Rogers
                   ` (5 more replies)
  0 siblings, 6 replies; 7+ messages in thread
From: Ian Rogers @ 2026-12-04  1:04 UTC (permalink / raw)
  To: linux-perf-users, acme, namhyung
  Cc: linux-kernel, peterz, mingo, jolsa, adrian.hunter, james.clark,
	dsahern, andrii, Ian Rogers

Today perf parses the text of /proc/<pid>/task/<pid>/maps and, for
each file backed mapping missing from the DSO cache, opens and parses
the ELF file, within the process' mount namespace, for its build ID.
PROCMAP_QUERY (Linux 6.11+) returns each VMA in binary form, can
filter VMAs by permission in the kernel, and returns the build ID read
by the kernel from the mapped file. This works for deleted binaries
and binaries in other mount namespaces, where perf currently gets no
build ID.

While PROCMAP_QUERY was being developed, Andrii Nakryiko prototyped
using it for perf's mmap synthesis and measured it with 'perf bench
internals synthesize', finding it slightly faster than parsing the
text, but the perf change wasn't posted for inclusion [1][2]. This
series differs in letting the kernel filter VMAs, in getting build IDs
from the kernel, as build IDs in synthesized MMAP2 events have since
become the default, and in fixing the benchmark, which was failing to
read build IDs (patch 3).

[1] https://lore.kernel.org/all/CAEf4BzbdGJzMuRgGJE72VFquXL37rS9Ti__wx4f_+kt3yetkEg@mail.gmail.com/
[2] https://github.com/anakryiko/linux/commit/0841fe675ed30f5605c5b228e18f5612ea253b35

The series is based on perf-tools-next.

Patches 1 and 2 fix pre-existing bugs found by the Sashiko AI review
tool when reviewing an earlier version of this series. Patch 1 fixes a
leak in __machine__new_host() when creating the kernel maps fails.
Patch 2 fixes a data race on DSO build IDs when several threads
synthesize events, by reading and setting the build ID with the dsos
lock held, as lookups that compare DSO ids already do. ThreadSanitizer
reported 8 races on the build ID in 'perf bench internals synthesize
-t -m 8 -M 8' before the fix and none after it.

Patch 3 fixes 'perf bench internals synthesize', which never called
symbol__init() so every build ID read failed and the DSO cache never
worked, making the benchmark ~15x slower than real synthesis.

Patch 4 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.

Patch 5 adds a 'perf bench internals synthesize --[no-]procmap-query'
option and a core.procmap-query config option to allow comparison.

Patch 6 adds a perf test that synthesizes the test process' mmaps both
ways and checks the MMAP2 events are byte for byte identical, with and
without build IDs and data mmaps, including an execute-only mapping.

Results on an Intel Core i7-14700, 7.1 kernel (usec, lower is better).

 Single threaded, perf process, warm DSO cache, pinned to a CPU,
 min / median of 10 interleaved runs:
                        text              PROCMAP_QUERY
   exec mmaps only    249.2 /  258.8      172.2 /  177.2   (-32%)
   with data mmaps   1458.3 / 1621.8     1631.5 / 1726.2   (+6%)

 System wide ('-t -m 1 -M 4', ~32,000 events, unprivileged), cold
 DSO cache as at the start of 'perf record -a', min / median of 3
 runs:
   threads              text              PROCMAP_QUERY
     1               301943 / 302766     161624 / 164009   (-46%)
     2               184631 / 187061     112002 / 115959   (-38%)
     3               240013 / 240291     136163 / 215740
     4               133571 / 139586      92270 /  95234   (-32%)

The 3 thread PROCMAP_QUERY median is skewed by two noisy runs; by the
minimum it is 43% faster.

PROCMAP_QUERY is not a win everywhere: with data mmaps and a warm DSO
cache, one ioctl per readable VMA is slightly slower than formatting
and parsing the text. Splitting data mmap synthesis into the readable
and execute-only passes avoids querying the ~22% of VMAs that are
inaccessible guards, cutting the ioctls when walking every process on
the test machine by 13%, but the time only improved by about 1% as
those VMAs have no name and are cheap to query. The benefit for
executable mmaps, the default for 'perf record', comes from the kernel
filtering VMAs and from not opening ELF files.

Recording with and without core.procmap-query on 'sleep' and a
python3 process with many libraries, with and without -d, gave
identical mmap events in 'perf script --show-mmap-events'. For a
process running a deleted binary, PROCMAP_QUERY gave the build ID
where the text path only had the device/inode.

Known difference: the gate VMA ([vsyscall] on x86-64, [vectors] on
32-bit ARM) isn't in the VMA tree, so no map is synthesized for it.
No symbols were ever resolved for it, as it has no backing file, and
samples there are now shown as [unknown] rather than [vsyscall] or
[vectors]. The kernel never emits an MMAP2 event for the gate VMA, so
processes started during recording already lacked it; PROCMAP_QUERY
makes pre-existing processes consistent with them.

Tools used: the code, tests and changelogs in this series were
initially written by an AI coding assistant (Gemini in Jetski)
from prompts describing the goal above, and were then reviewed,
built (GCC and clang), tested ('perf test', the new equivalence
test, 'perf record'/'perf script' comparisons) and benchmarked by
me.

Ian Rogers (6):
  perf machine: Fix leak when creating host kernel maps fails
  perf synthetic-events: Fix race on DSO build IDs when synthesizing
  perf bench synthesize: Initialize symbols so build IDs can be read
  perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events
  perf bench synthesize: Add --procmap-query option
  perf test: Add test comparing PROCMAP_QUERY and /proc/pid/maps
    synthesis

 tools/perf/Documentation/perf-bench.txt  |   4 +-
 tools/perf/Documentation/perf-config.txt |   5 +
 tools/perf/bench/synthesize.c            |  58 ++-
 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 +
 tools/perf/util/config.c                 |   4 +
 tools/perf/util/dsos.c                   |  38 +-
 tools/perf/util/dsos.h                   |   4 +
 tools/perf/util/machine.c                |   2 +-
 tools/perf/util/synthetic-events.c       | 539 ++++++++++++++++++-----
 tools/perf/util/synthetic-events.h       |   6 +
 13 files changed, 808 insertions(+), 130 deletions(-)
 create mode 100644 tools/perf/tests/synthesize-mmap.c


base-commit: 22f7d78dc87e43ff4f7c03d23f46f49692c41ad0
-- 
2.56.1.915.g69d5ec7298-goog


^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH 1/6] perf machine: Fix leak when creating host kernel maps fails
  2026-12-04  1:04 [PATCH 0/6] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
@ 2026-12-04  1:04 ` Ian Rogers
  2026-12-04  1:04 ` [PATCH 2/6] perf synthetic-events: Fix race on DSO build IDs when synthesizing Ian Rogers
                   ` (4 subsequent siblings)
  5 siblings, 0 replies; 7+ messages in thread
From: Ian Rogers @ 2026-12-04  1:04 UTC (permalink / raw)
  To: linux-perf-users, acme, namhyung
  Cc: linux-kernel, peterz, mingo, 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;

base-commit: 22f7d78dc87e43ff4f7c03d23f46f49692c41ad0
-- 
2.56.1.915.g69d5ec7298-goog


^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH 2/6] perf synthetic-events: Fix race on DSO build IDs when synthesizing
  2026-12-04  1:04 [PATCH 0/6] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
  2026-12-04  1:04 ` [PATCH 1/6] perf machine: Fix leak when creating host kernel maps fails Ian Rogers
@ 2026-12-04  1:04 ` Ian Rogers
  2026-12-04  1:04 ` [PATCH 3/6] perf bench synthesize: Initialize symbols so build IDs can be read Ian Rogers
                   ` (3 subsequent siblings)
  5 siblings, 0 replies; 7+ messages in thread
From: Ian Rogers @ 2026-12-04  1:04 UTC (permalink / raw)
  To: linux-perf-users, acme, namhyung
  Cc: linux-kernel, peterz, mingo, 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	[flat|nested] 7+ messages in thread

* [PATCH 3/6] perf bench synthesize: Initialize symbols so build IDs can be read
  2026-12-04  1:04 [PATCH 0/6] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
  2026-12-04  1:04 ` [PATCH 1/6] perf machine: Fix leak when creating host kernel maps fails Ian Rogers
  2026-12-04  1:04 ` [PATCH 2/6] perf synthetic-events: Fix race on DSO build IDs when synthesizing Ian Rogers
@ 2026-12-04  1:04 ` Ian Rogers
  2026-12-04  1:04 ` [PATCH 4/6] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events Ian Rogers
                   ` (2 subsequent siblings)
  5 siblings, 0 replies; 7+ messages in thread
From: Ian Rogers @ 2026-12-04  1:04 UTC (permalink / raw)
  To: linux-perf-users, acme, namhyung
  Cc: linux-kernel, peterz, mingo, 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	[flat|nested] 7+ messages in thread

* [PATCH 4/6] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events
  2026-12-04  1:04 [PATCH 0/6] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
                   ` (2 preceding siblings ...)
  2026-12-04  1:04 ` [PATCH 3/6] perf bench synthesize: Initialize symbols so build IDs can be read Ian Rogers
@ 2026-12-04  1:04 ` Ian Rogers
  2026-12-04  1:04 ` [PATCH 5/6] perf bench synthesize: Add --procmap-query option Ian Rogers
  2026-12-04  1:04 ` [PATCH 6/6] perf test: Add test comparing PROCMAP_QUERY and /proc/pid/maps synthesis Ian Rogers
  5 siblings, 0 replies; 7+ messages in thread
From: Ian Rogers @ 2026-12-04  1:04 UTC (permalink / raw)
  To: linux-perf-users, acme, namhyung
  Cc: linux-kernel, peterz, mingo, 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. 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.

The tools/include copy of linux/fs.h provides PROCMAP_QUERY when the
system headers lack it.

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 | 528 +++++++++++++++++++++++------
 1 file changed, 428 insertions(+), 100 deletions(-)

diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c
index 445199d7bbd4..3ad482f9115a 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, from tools/include/uapi if not in system headers */
 #include <linux/kernel.h>
 #include <linux/string.h>
 #include <linux/zalloc.h>
@@ -34,12 +37,14 @@
 #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 <fcntl.h>
@@ -436,9 +441,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 +478,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 +523,435 @@ 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));
+/* Does the running kernel support PROCMAP_QUERY? Set by procmap_query__probe(). */
+static bool procmap_query_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,
+	};
+	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");
+}
+
+static bool procmap_query__supported(void)
+{
+	static pthread_once_t once = PTHREAD_ONCE_INIT;
+
+	pthread_once(&once, procmap_query__probe);
+	return procmap_query_supported;
+}
+
+/*
+ * 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;
+	}
+
+	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;
 
-		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;
+	/* 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;
+			}
+
+			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;
+			}
 
-			event->header.misc |= PERF_RECORD_MISC_MMAP_DATA;
+			/* 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)) {
+			addr = q.vma_end;
+			continue;
+		}
+		if (!want_name) {
+			/* A wanted VMA, query it again to get its name. */
+			want_name = true;
+			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 (!symbol_conf.no_buildid_mmap2 && q.inode && name[0] == '/' &&
+		    ((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);
 
-		if (truncation)
-			break;
+		addr = q.vma_end;
+
+		ret = synth_mmap2_state__process_vma(state, &vma);
+		dso__put(vma.dso);
+		if (ret)
+			return -1;
+
+		if (state->truncation)
+			return 0;
 	}
+}
 
-	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 +1140,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 +1628,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	[flat|nested] 7+ messages in thread

* [PATCH 5/6] perf bench synthesize: Add --procmap-query option
  2026-12-04  1:04 [PATCH 0/6] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
                   ` (3 preceding siblings ...)
  2026-12-04  1:04 ` [PATCH 4/6] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events Ian Rogers
@ 2026-12-04  1:04 ` Ian Rogers
  2026-12-04  1:04 ` [PATCH 6/6] perf test: Add test comparing PROCMAP_QUERY and /proc/pid/maps synthesis Ian Rogers
  5 siblings, 0 replies; 7+ messages in thread
From: Ian Rogers @ 2026-12-04  1:04 UTC (permalink / raw)
  To: linux-perf-users, acme, namhyung
  Cc: linux-kernel, peterz, mingo, 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 3ad482f9115a..9db1084f25b0 100644
--- a/tools/perf/util/synthetic-events.c
+++ b/tools/perf/util/synthetic-events.c
@@ -53,6 +53,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,
@@ -945,7 +946,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	[flat|nested] 7+ messages in thread

* [PATCH 6/6] perf test: Add test comparing PROCMAP_QUERY and /proc/pid/maps synthesis
  2026-12-04  1:04 [PATCH 0/6] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
                   ` (4 preceding siblings ...)
  2026-12-04  1:04 ` [PATCH 5/6] perf bench synthesize: Add --procmap-query option Ian Rogers
@ 2026-12-04  1:04 ` Ian Rogers
  5 siblings, 0 replies; 7+ messages in thread
From: Ian Rogers @ 2026-12-04  1:04 UTC (permalink / raw)
  To: linux-perf-users, acme, namhyung
  Cc: linux-kernel, peterz, mingo, 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	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2026-12-04  1:05 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-12-04  1:04 [PATCH 0/6] perf synthetic-events: Use PROCMAP_QUERY for mmap synthesis Ian Rogers
2026-12-04  1:04 ` [PATCH 1/6] perf machine: Fix leak when creating host kernel maps fails Ian Rogers
2026-12-04  1:04 ` [PATCH 2/6] perf synthetic-events: Fix race on DSO build IDs when synthesizing Ian Rogers
2026-12-04  1:04 ` [PATCH 3/6] perf bench synthesize: Initialize symbols so build IDs can be read Ian Rogers
2026-12-04  1:04 ` [PATCH 4/6] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events Ian Rogers
2026-12-04  1:04 ` [PATCH 5/6] perf bench synthesize: Add --procmap-query option Ian Rogers
2026-12-04  1:04 ` [PATCH 6/6] perf test: Add test comparing PROCMAP_QUERY and /proc/pid/maps synthesis Ian Rogers

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®