[PATCH] selftests/mm: Fix memleak in migration benchmark

From: Hongfu Li

Date: Wed Jul 08 2026 - 06:43:17 EST


Several early return paths in run_migration_benchmark() skip
hmm_buffer_free(), leaking the buffer. Replace with a single cleanup
label.

Signed-off-by: Hongfu Li <lihongfu@xxxxxxxxxx>
---
tools/testing/selftests/mm/hmm-tests.c | 19 +++++++++++--------
1 file changed, 11 insertions(+), 8 deletions(-)

diff --git a/tools/testing/selftests/mm/hmm-tests.c b/tools/testing/selftests/mm/hmm-tests.c
index e4c49699f3f7..e8046675a0c3 100644
--- a/tools/testing/selftests/mm/hmm-tests.c
+++ b/tools/testing/selftests/mm/hmm-tests.c
@@ -2828,8 +2828,10 @@ static inline int run_migration_benchmark(int fd, int use_thp, size_t buffer_siz
buffer->ptr = mmap(NULL, buffer_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

- if (buffer->ptr == MAP_FAILED)
- return -1;
+ if (buffer->ptr == MAP_FAILED) {
+ ret = -1;
+ goto cleanup;
+ }

/* Apply THP hint if requested */
if (use_thp)
@@ -2838,7 +2840,7 @@ static inline int run_migration_benchmark(int fd, int use_thp, size_t buffer_siz
ret = madvise(buffer->ptr, buffer_size, MADV_NOHUGEPAGE);

if (ret)
- return ret;
+ goto cleanup;

/* Initialize memory to make sure pages are allocated */
ptr = (int *)buffer->ptr;
@@ -2848,11 +2850,11 @@ static inline int run_migration_benchmark(int fd, int use_thp, size_t buffer_siz
/* Warmup iteration */
ret = hmm_migrate_sys_to_dev(fd, buffer, npages);
if (ret)
- return ret;
+ goto cleanup;

ret = hmm_migrate_dev_to_sys(fd, buffer, npages);
if (ret)
- return ret;
+ goto cleanup;

/* Benchmark iterations */
for (i = 0; i < iterations; i++) {
@@ -2861,7 +2863,7 @@ static inline int run_migration_benchmark(int fd, int use_thp, size_t buffer_siz

ret = hmm_migrate_sys_to_dev(fd, buffer, npages);
if (ret)
- return ret;
+ goto cleanup;

end = get_time_ms();
s2d_total += (end - start);
@@ -2871,7 +2873,7 @@ static inline int run_migration_benchmark(int fd, int use_thp, size_t buffer_siz

ret = hmm_migrate_dev_to_sys(fd, buffer, npages);
if (ret)
- return ret;
+ goto cleanup;

end = get_time_ms();
d2s_total += (end - start);
@@ -2886,8 +2888,9 @@ static inline int run_migration_benchmark(int fd, int use_thp, size_t buffer_siz
(results->dev_to_sys_time / 1000.0);

/* Cleanup */
+cleanup:
hmm_buffer_free(buffer);
- return 0;
+ return ret;
}

/*
--
2.25.1