[PATCH] mm/khugepaged: reject shmem collapse ranges beyond i_size

From: Jérémy Jean

Date: Thu Nov 12 2026 - 09:39:52 EST


MADV_COLLAPSE lets collapse_file() treat absent shmem pages as holes
filled with zeros. It does not check i_size, which allows one present
page to become a huge mapping that covers the whole collapse range,
including pages beyond EOF. This makes those pages writable. A later
file extension can expose their contents after F_SEAL_WRITE.

Hold inode i_rwsem in read mode while collapsing shmem so i_size
cannot change. Reject a collapse if its page range extends past
i_size rounded up to PAGE_SIZE. Keep i_size_read() outside the
page-cache XArray lock because its 32-bit SMP reader is not IRQ
safe.

Fixes: 34488399fa08 ("mm/madvise: add file and shmem support to MADV_COLLAPSE")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Jérémy Jean <Jeremy.Jean@xxxxxxxxxxxxxxxxx>
---
mm/khugepaged.c | 9 +++++++++
1 file changed, 9 insertions(+)

diff --git a/mm/khugepaged.c b/mm/khugepaged.c
index 4bbe319..e20416a 100644
--- a/mm/khugepaged.c
+++ b/mm/khugepaged.c
@@ -2251,6 +2251,13 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
*/
VM_WARN_ON_ONCE(!is_shmem && !mapping_pmd_folio_support(mapping));
VM_WARN_ON_ONCE(start & (HPAGE_PMD_NR - 1));
+ if (is_shmem)
+ inode_lock_shared(mapping->host);
+ if (is_shmem &&
+ end > DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE)) {
+ result = SCAN_TRUNCATED;
+ goto out;
+ }

result = alloc_charge_folio(&new_folio, mm, cc, HPAGE_PMD_ORDER);
if (result != SCAN_SUCCEED)
@@ -2682,6 +2689,8 @@ rollback:
out_put:
folio_put(new_folio);
out:
+ if (is_shmem)
+ inode_unlock_shared(mapping->host);
VM_BUG_ON(!list_empty(&pagelist));
trace_mm_khugepaged_collapse_file(mm, new_pfn, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
return result;
--
2.47.3