[PATCH] libperf: Grant write permission for user page

Leo Yan posted 1 patch 7 months, 3 weeks ago
tools/lib/perf/mmap.c | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
[PATCH] libperf: Grant write permission for user page
Posted by Leo Yan 7 months, 3 weeks ago
When perf runs in overwrite mode, the ring buffer is mapped read-only.

On the other hand, the first page in the ring buffer is for user page,
which is used for exchanging parameters between the kernel and the
userspace.  The read-only permission causes Segmentation fault with
command:

  $ perf record --overwrite -a -e cs_etm//
    perf: Segmentation fault

This patch grants write permission for the mapped user page so the
userspace tool can update info properly.

Fixes: d1a177595b3a ("libperf: Adopt perf_evlist__mmap()/munmap() from tools/perf")
Reported-by: Tomas Glozar <tglozar@redhat.com>
Closes: https://lore.kernel.org/linux-perf-users/20250428124727.GE551819@e132581.arm.com/T/#t
Signed-off-by: Leo Yan <leo.yan@arm.com>
---
 tools/lib/perf/mmap.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/tools/lib/perf/mmap.c b/tools/lib/perf/mmap.c
index c1a51d925e0e..7c0748a9d79f 100644
--- a/tools/lib/perf/mmap.c
+++ b/tools/lib/perf/mmap.c
@@ -4,6 +4,7 @@
 #include <asm/bug.h>
 #include <errno.h>
 #include <string.h>
+#include <unistd.h>
 #include <linux/ring_buffer.h>
 #include <linux/perf_event.h>
 #include <perf/mmap.h>
@@ -45,6 +46,21 @@ int perf_mmap__mmap(struct perf_mmap *map, struct perf_mmap_param *mp,
 		return -1;
 	}
 
+	/*
+	 * In overwrite mode, pages are mapped as read-only.  Fix the permission
+	 * to make the user page writable, as the tool needs to update
+	 * information (e.g., aux_offset/aux_size) into it.
+	 */
+	if (mp->prot == PROT_READ) {
+		const long page_sz = sysconf(_SC_PAGE_SIZE);
+
+		if (mprotect(map->base, page_sz, mp->prot | PROT_WRITE) < 0) {
+			munmap(map->base, perf_mmap__mmap_len(map));
+			map->base = NULL;
+			return -1;
+		}
+	}
+
 	map->fd  = fd;
 	map->cpu = cpu;
 	return 0;
-- 
2.34.1