Skip to contentSkip to conversation

mm: thp: deny THP for files on anonymous inodes

PATCH Applied Deepanshu Kartikey 7 participants 11 messages Feb 14 – Feb 22

Subsystems (5)
lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 mm: thp: deny THP for files on anonymous inodes

file_thp_enabled() incorrectly allows THP for files on anonymous inodes (e.g. guest_memfd and secretmem). These files are created via alloc_file_pseudo(), which does not call get_write_access() and leaves inode->i_writecount at 0. Combined with S_ISREG(inode->i_mode) being true, they appear as read-only regular files when CONFIG_READ_ONLY_THP_FOR_FS is enabled, making them eligible for THP collapse.

Anonymous inodes can never pass the inode_is_open_for_write() check since their i_writecount is never incremented through the normal VFS open path. The right thing to do is to exclude them from THP eligibility altogether, since CONFIG_READ_ONLY_THP_FOR_FS was designed for real filesystem files (e.g. shared libraries), not for pseudo-filesystem inodes.

For guest_memfd, this allows khugepaged and MADV_COLLAPSE to create large folios in the page cache via the collapse path, but the guest_memfd fault handler does not support large folios. This triggers WARN_ON_ONCE(folio_test_large(folio)) in kvm_gmem_fault_user_mapping().

For secretmem, collapse_file() tries to copy page contents through the direct map, but secretmem pages are removed from the direct map. This can result in a kernel crash:

    BUG: unable to handle page fault for address: ffff88810284d000
    RIP: 0010:memcpy_orig+0x16/0x130
    Call Trace:
     collapse_file
     hpage_collapse_scan_file
     madvise_collapse

Secretmem is not affected by the crash on upstream as the memory failure recovery handles the failed copy gracefully, but it still triggers confusing false memory failure reports:

Memory failure: 0x106d96f: recovery action for clean unevictable LRU page: Recovered

Check IS_ANON_FILE(inode) in file_thp_enabled() to deny THP for all anonymous inode files.

---
v2:
- Use IS_ANON_FILE(inode) to deny THP for all anonymous inode files instead of checking for specific subsystems (David Hildenbrand)
- Updated Fixes tag to 7fbb5e188248 which removed the VM_EXEC requirement that accidentally protected secretmem
- Expanded commit message with implications for both guest_memfd and secretmem

---
 mm/huge_memory.c | 3 +++
 1 file changed, 3 insertions(+)
mm/huge_memory.c +3 -0
index 40cf59301c21..d3beddd8cc30 100644
@@ -94,6 +94,9 @@ static inline bool file_thp_enabled(struct vm_area_struct *vma)
 
 	inode = file_inode(vma->vm_file);
 
+	if (IS_ANON_FILE(inode))
+		return false;
+
 	return !inode_is_open_for_write(inode) && S_ISREG(inode->i_mode);
 }
 
Signature · 1 line
2.43.0
reviewer Tested-by on v2 1/1
#1 lore raw
Quoted 15 lines · Deepanshu Kartikey

file_thp_enabled() incorrectly allows THP for files on anonymous inodes (e.g. guest_memfd and secretmem). These files are created via alloc_file_pseudo(), which does not call get_write_access() and leaves inode->i_writecount at 0. Combined with S_ISREG(inode->i_mode) being true, they appear as read-only regular files when CONFIG_READ_ONLY_THP_FOR_FS is enabled, making them eligible for THP collapse.

Anonymous inodes can never pass the inode_is_open_for_write() check since their i_writecount is never incremented through the normal VFS open path. The right thing to do is to exclude them from THP eligibility altogether, since CONFIG_READ_ONLY_THP_FOR_FS was designed for real filesystem files (e.g. shared libraries), not for pseudo-filesystem inodes.

Quoted 8 lines

For guest_memfd, this allows khugepaged and MADV_COLLAPSE to create large folios in the page cache via the collapse path, but the guest_memfd fault handler does not support large folios. This triggers WARN_ON_ONCE(folio_test_large(folio)) in kvm_gmem_fault_user_mapping().

For secretmem, collapse_file() tries to copy page contents through the direct map, but secretmem pages are removed from the direct map. This can result in a kernel crash:

Good catch, thanks!

For secretmem, file_thp_enabled() can incorrectly return true (i_writecount=0, S_ISREG=1), so the mapping becomes eligible for file THP collapse ...

However, if any folio is dirty, collapse bails out early with SCAN_PAGE_DIRTY_OR_WRITEBACK, as secretmem doesn't support normal writeback, IIUC.

Quoted 8 lines
     BUG: unable to handle page fault for address: ffff88810284d000
     RIP: 0010:memcpy_orig+0x16/0x130
     Call Trace:
      collapse_file
      hpage_collapse_scan_file
      madvise_collapse
Quoted 6 lines

Secretmem is not affected by the crash on upstream as the memory failure recovery handles the failed copy gracefully, but it still triggers confusing false memory failure reports:

Memory failure: 0x106d96f: recovery action for clean unevictable LRU page: Recovered

Right. On my setup, that would hit SCAN_COPY_MC in hpage_collapse_scan_file() rather than a hard crash.

Quoted 12 lines

Check IS_ANON_FILE(inode) in file_thp_enabled() to deny THP for all anonymous inode files.

Quoted 1 line

---

Confirmed that file_thp_enabled() is working as expected now with this fix.

Cheers,
Lance

#2 lore raw
Quoted 27 lines · Lance Yang
Quoted 15 lines · Deepanshu Kartikey

file_thp_enabled() incorrectly allows THP for files on anonymous inodes (e.g. guest_memfd and secretmem). These files are created via alloc_file_pseudo(), which does not call get_write_access() and leaves inode->i_writecount at 0. Combined with S_ISREG(inode->i_mode) being true, they appear as read-only regular files when CONFIG_READ_ONLY_THP_FOR_FS is enabled, making them eligible for THP collapse.

Anonymous inodes can never pass the inode_is_open_for_write() check since their i_writecount is never incremented through the normal VFS open path. The right thing to do is to exclude them from THP eligibility altogether, since CONFIG_READ_ONLY_THP_FOR_FS was designed for real filesystem files (e.g. shared libraries), not for pseudo-filesystem inodes.

Quoted 8 lines

For guest_memfd, this allows khugepaged and MADV_COLLAPSE to create large folios in the page cache via the collapse path, but the guest_memfd fault handler does not support large folios. This triggers WARN_ON_ONCE(folio_test_large(folio)) in kvm_gmem_fault_user_mapping().

For secretmem, collapse_file() tries to copy page contents through the direct map, but secretmem pages are removed from the direct map. This can result in a kernel crash:

Good catch, thanks!

Quoted 8 lines

For secretmem, file_thp_enabled() can incorrectly return true (i_writecount=0, S_ISREG=1), so the mapping becomes eligible for file THP collapse ...

However, if any folio is dirty, collapse bails out early with SCAN_PAGE_DIRTY_OR_WRITEBACK, as secretmem doesn't support normal writeback, IIUC.

Yup! In the reproducers [1] I had to try to avoid setting the dirty flag on the pages.

[1] https://lore.kernel.org/linux-mm/CAEvNRgHegcz3ro35ixkDw39ES8=U6rs6S7iP0gkR9enr7HoGtA@mail.gmail.com

Quoted 12 lines
Quoted 12 lines
     BUG: unable to handle page fault for address: ffff88810284d000
     RIP: 0010:memcpy_orig+0x16/0x130
     Call Trace:
      collapse_file
      hpage_collapse_scan_file
      madvise_collapse

Secretmem is not affected by the crash on upstream as the memory failure recovery handles the failed copy gracefully, but it still triggers confusing false memory failure reports:

Quoted 7 lines
Quoted 2 lines

Memory failure: 0x106d96f: recovery action for clean unevictable LRU page: Recovered

Right. On my setup, that would hit SCAN_COPY_MC in hpage_collapse_scan_file()
rather than a hard crash.

Deepanshu, were you able to trigger a hard crash on some earlier kernel? I only saw this false memory failure log.

Quoted 21 lines
Quoted 12 lines

Check IS_ANON_FILE(inode) in file_thp_enabled() to deny THP for all anonymous inode files.

Quoted 1 line

---

Confirmed that file_thp_enabled() is working as expected now with this fix.

Cheers,
Lance

reviewer
#3 lore raw
Quoted 58 lines · Ackerley Tng
Quoted 27 lines · Lance Yang
Quoted 15 lines · Deepanshu Kartikey

file_thp_enabled() incorrectly allows THP for files on anonymous inodes (e.g. guest_memfd and secretmem). These files are created via alloc_file_pseudo(), which does not call get_write_access() and leaves inode->i_writecount at 0. Combined with S_ISREG(inode->i_mode) being true, they appear as read-only regular files when CONFIG_READ_ONLY_THP_FOR_FS is enabled, making them eligible for THP collapse.

Anonymous inodes can never pass the inode_is_open_for_write() check since their i_writecount is never incremented through the normal VFS open path. The right thing to do is to exclude them from THP eligibility altogether, since CONFIG_READ_ONLY_THP_FOR_FS was designed for real filesystem files (e.g. shared libraries), not for pseudo-filesystem inodes.

Quoted 8 lines

For guest_memfd, this allows khugepaged and MADV_COLLAPSE to create large folios in the page cache via the collapse path, but the guest_memfd fault handler does not support large folios. This triggers WARN_ON_ONCE(folio_test_large(folio)) in kvm_gmem_fault_user_mapping().

For secretmem, collapse_file() tries to copy page contents through the direct map, but secretmem pages are removed from the direct map. This can result in a kernel crash:

Good catch, thanks!

Quoted 8 lines

For secretmem, file_thp_enabled() can incorrectly return true (i_writecount=0, S_ISREG=1), so the mapping becomes eligible for file THP collapse ...

However, if any folio is dirty, collapse bails out early with SCAN_PAGE_DIRTY_OR_WRITEBACK, as secretmem doesn't support normal writeback, IIUC.

Yup! In the reproducers [1] I had to try to avoid setting the dirty flag on the pages.

[1] https://lore.kernel.org/linux-mm/CAEvNRgHegcz3ro35ixkDw39ES8=U6rs6S7iP0gkR9enr7HoGtA@mail.gmail.com

Quoted 15 lines
Quoted 14 lines
      BUG: unable to handle page fault for address: ffff88810284d000
      RIP: 0010:memcpy_orig+0x16/0x130
      Call Trace:
       collapse_file
       hpage_collapse_scan_file
       madvise_collapse

Secretmem is not affected by the crash on upstream as the memory failure recovery handles the failed copy gracefully, but it still triggers confusing false memory failure reports:

Memory failure: 0x106d96f: recovery action for clean unevictable LRU page: Recovered

Quoted 7 lines
Quoted 4 lines

Right. On my setup, that would hit SCAN_COPY_MC in hpage_collapse_scan_file()
rather than a hard crash.

Deepanshu, were you able to trigger a hard crash on some earlier kernel? I only saw this false memory failure log.

On a setup where memory failure recovery works, we can trigger a panic by disabling recovery:

echo 0 > /proc/sys/vm/memory_failure_recovery

Then we would hit the following panic:

[  117.608411] Kernel panic - not syncing: Memory failure on page 1024d6
[  117.609490] CPU: 4 UID: 0 PID: 168 Comm: kworker/4:1 Not tainted 6.19.0 #83 PREEMPT(full)
[  117.610817] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 0.5.1 01/01/2011
[  117.612121] Workqueue: events memory_failure_work_func
[  117.612978] Call Trace:
[  117.613401]  <TASK>
[  117.613766]  dump_stack_lvl+0x60/0x90
[  117.614382]  dump_stack+0x14/0x1a
[  117.614940]  vpanic+0x1a6/0x470
[  117.615476]  panic+0xc0/0xc0
[  117.615967]  ? __pfx_panic+0x10/0x10
[  117.616571]  ? update_cfs_rq_load_avg+0x5f/0x5a0
[  117.617336]  ? dequeue_entities+0x250/0x1e30
[  117.618043]  memory_failure.cold+0x2d/0x2d
[  117.618725]  ? __pfx_memory_failure+0x10/0x10
[  117.619451]  ? __raw_spin_lock_irqsave+0x8d/0xf0
[  117.620215]  ? __switch_to+0x3e9/0xb60
[  117.620841]  memory_failure_work_func+0x150/0x200
[  117.621621]  process_one_work+0x63d/0xf50
[  117.622292]  worker_thread+0x517/0xd90
[  117.622915]  ? __pfx_worker_thread+0x10/0x10
[  117.623629]  kthread+0x369/0x460
[  117.624169]  ? __pfx_kthread+0x10/0x10
[  117.624796]  ret_from_fork+0x33a/0x660
[  117.625422]  ? __pfx_ret_from_fork+0x10/0x10
[  117.626126]  ? switch_fpu+0x19/0x1f0
[  117.626728]  ? __switch_to+0x3e9/0xb60
[  117.627354]  ? __pfx_kthread+0x10/0x10
[  117.627978]  ret_from_fork_asm+0x1a/0x30
[  117.628633]  </TASK>
[  117.629316] Kernel Offset: disabled
[  117.629902] ---[ end Kernel panic - not syncing: Memory failure on page 1024d6 ]---
maintainer Acked-by on v2 1/1
#4 lore raw
In reply to Deepanshu Kartikey
Quoted 41 lines · Deepanshu Kartikey

file_thp_enabled() incorrectly allows THP for files on anonymous inodes (e.g. guest_memfd and secretmem). These files are created via alloc_file_pseudo(), which does not call get_write_access() and leaves inode->i_writecount at 0. Combined with S_ISREG(inode->i_mode) being true, they appear as read-only regular files when CONFIG_READ_ONLY_THP_FOR_FS is enabled, making them eligible for THP collapse.

Anonymous inodes can never pass the inode_is_open_for_write() check since their i_writecount is never incremented through the normal VFS open path. The right thing to do is to exclude them from THP eligibility altogether, since CONFIG_READ_ONLY_THP_FOR_FS was designed for real filesystem files (e.g. shared libraries), not for pseudo-filesystem inodes.

For guest_memfd, this allows khugepaged and MADV_COLLAPSE to create large folios in the page cache via the collapse path, but the guest_memfd fault handler does not support large folios. This triggers WARN_ON_ONCE(folio_test_large(folio)) in kvm_gmem_fault_user_mapping().

For secretmem, collapse_file() tries to copy page contents through the direct map, but secretmem pages are removed from the direct map. This can result in a kernel crash:

     BUG: unable to handle page fault for address: ffff88810284d000
     RIP: 0010:memcpy_orig+0x16/0x130
     Call Trace:
      collapse_file
      hpage_collapse_scan_file
      madvise_collapse

Secretmem is not affected by the crash on upstream as the memory failure recovery handles the failed copy gracefully, but it still triggers confusing false memory failure reports:

Memory failure: 0x106d96f: recovery action for clean unevictable LRU page: Recovered

Check IS_ANON_FILE(inode) in file_thp_enabled() to deny THP for all anonymous inode files.

Quoted 8 lines
Signature · 3 lines
Cheers,

David
Reviewed-by on v2 1/1
#5 lore raw
In reply to Deepanshu Kartikey
Quoted 42 lines · Deepanshu Kartikey

file_thp_enabled() incorrectly allows THP for files on anonymous inodes (e.g. guest_memfd and secretmem). These files are created via alloc_file_pseudo(), which does not call get_write_access() and leaves inode->i_writecount at 0. Combined with S_ISREG(inode->i_mode) being true, they appear as read-only regular files when CONFIG_READ_ONLY_THP_FOR_FS is enabled, making them eligible for THP collapse.

Anonymous inodes can never pass the inode_is_open_for_write() check since their i_writecount is never incremented through the normal VFS open path. The right thing to do is to exclude them from THP eligibility altogether, since CONFIG_READ_ONLY_THP_FOR_FS was designed for real filesystem files (e.g. shared libraries), not for pseudo-filesystem inodes.

For guest_memfd, this allows khugepaged and MADV_COLLAPSE to create large folios in the page cache via the collapse path, but the guest_memfd fault handler does not support large folios. This triggers WARN_ON_ONCE(folio_test_large(folio)) in kvm_gmem_fault_user_mapping().

For secretmem, collapse_file() tries to copy page contents through the direct map, but secretmem pages are removed from the direct map. This can result in a kernel crash:

    BUG: unable to handle page fault for address: ffff88810284d000
    RIP: 0010:memcpy_orig+0x16/0x130
    Call Trace:
     collapse_file
     hpage_collapse_scan_file
     madvise_collapse

Secretmem is not affected by the crash on upstream as the memory failure recovery handles the failed copy gracefully, but it still triggers confusing false memory failure reports:

Memory failure: 0x106d96f: recovery action for clean unevictable LRU page: Recovered

Check IS_ANON_FILE(inode) in file_thp_enabled() to deny THP for all anonymous inode files.

Quoted 8 lines

LGTM,

Reviewed-by Tested-by on v2 1/1
#6 lore raw
In reply to Deepanshu Kartikey
Quoted 24 lines · Deepanshu Kartikey

file_thp_enabled() incorrectly allows THP for files on anonymous inodes (e.g. guest_memfd and secretmem). These files are created via alloc_file_pseudo(), which does not call get_write_access() and leaves inode->i_writecount at 0. Combined with S_ISREG(inode->i_mode) being true, they appear as read-only regular files when CONFIG_READ_ONLY_THP_FOR_FS is enabled, making them eligible for THP collapse.

Anonymous inodes can never pass the inode_is_open_for_write() check since their i_writecount is never incremented through the normal VFS open path. The right thing to do is to exclude them from THP eligibility altogether, since CONFIG_READ_ONLY_THP_FOR_FS was designed for real filesystem files (e.g. shared libraries), not for pseudo-filesystem inodes.

For guest_memfd, this allows khugepaged and MADV_COLLAPSE to create large folios in the page cache via the collapse path, but the guest_memfd fault handler does not support large folios. This triggers WARN_ON_ONCE(folio_test_large(folio)) in kvm_gmem_fault_user_mapping().

For secretmem, collapse_file() tries to copy page contents through the direct map, but secretmem pages are removed from the direct map. This can result in a kernel crash:

Quoted 7 lines
    BUG: unable to handle page fault for address: ffff88810284d000
    RIP: 0010:memcpy_orig+0x16/0x130
    Call Trace:
     collapse_file
     hpage_collapse_scan_file
     madvise_collapse

I couldn't reproduce this crash, I could only reproduce the false memory failure report below.

Quoted 35 lines

Secretmem is not affected by the crash on upstream as the memory failure recovery handles the failed copy gracefully, but it still triggers confusing false memory failure reports:

Memory failure: 0x106d96f: recovery action for clean unevictable LRU page: Recovered

Check IS_ANON_FILE(inode) in file_thp_enabled() to deny THP for all anonymous inode files.

---
v2:
- Use IS_ANON_FILE(inode) to deny THP for all anonymous inode files instead of checking for specific subsystems (David Hildenbrand)
- Updated Fixes tag to 7fbb5e188248 which removed the VM_EXEC requirement that accidentally protected secretmem
- Expanded commit message with implications for both guest_memfd and secretmem

---
 mm/huge_memory.c | 3 +++
 1 file changed, 3 insertions(+)
mm/huge_memory.c +0 -0
index 40cf59301c21..d3beddd8cc30 100644

mm/huge_memory.c static inline bool file_thp_enabled(struct vm_area_struct *vma) · line 99

Quoted 6 lines
mm/huge_memory.c +3 -0
@@ -94,6 +94,9 @@ static inline bool file_thp_enabled(struct vm_area_struct *vma)
 
 	inode = file_inode(vma->vm_file);
 
+	if (IS_ANON_FILE(inode))
+		return false;
+
Quoted 5 lines
mm/huge_memory.c +0 -1
 	return !inode_is_open_for_write(inode) && S_ISREG(inode->i_mode);
 }
 
--

2.43.0

Reviewed-by on v2 1/1
#7 lore raw
In reply to Deepanshu Kartikey
Quoted 35 lines · Deepanshu Kartikey

file_thp_enabled() incorrectly allows THP for files on anonymous inodes (e.g. guest_memfd and secretmem). These files are created via alloc_file_pseudo(), which does not call get_write_access() and leaves inode->i_writecount at 0. Combined with S_ISREG(inode->i_mode) being true, they appear as read-only regular files when CONFIG_READ_ONLY_THP_FOR_FS is enabled, making them eligible for THP collapse.

Anonymous inodes can never pass the inode_is_open_for_write() check since their i_writecount is never incremented through the normal VFS open path. The right thing to do is to exclude them from THP eligibility altogether, since CONFIG_READ_ONLY_THP_FOR_FS was designed for real filesystem files (e.g. shared libraries), not for pseudo-filesystem inodes.

For guest_memfd, this allows khugepaged and MADV_COLLAPSE to create large folios in the page cache via the collapse path, but the guest_memfd fault handler does not support large folios. This triggers WARN_ON_ONCE(folio_test_large(folio)) in kvm_gmem_fault_user_mapping().

For secretmem, collapse_file() tries to copy page contents through the direct map, but secretmem pages are removed from the direct map. This can result in a kernel crash:

    BUG: unable to handle page fault for address: ffff88810284d000
    RIP: 0010:memcpy_orig+0x16/0x130
    Call Trace:
     collapse_file
     hpage_collapse_scan_file
     madvise_collapse

Secretmem is not affected by the crash on upstream as the memory failure recovery handles the failed copy gracefully, but it still triggers confusing false memory failure reports:

Quoted 5 lines

Memory failure: 0x106d96f: recovery action for clean unevictable LRU page: Recovered

Check IS_ANON_FILE(inode) in file_thp_enabled() to deny THP for all anonymous inode files.

Great commit msg!

Quoted 9 lines

LGTM, so:

Quoted 29 lines

---
v2:
- Use IS_ANON_FILE(inode) to deny THP for all anonymous inode files instead of checking for specific subsystems (David Hildenbrand)
- Updated Fixes tag to 7fbb5e188248 which removed the VM_EXEC requirement that accidentally protected secretmem
- Expanded commit message with implications for both guest_memfd and secretmem

---
 mm/huge_memory.c | 3 +++
 1 file changed, 3 insertions(+)
mm/huge_memory.c +3 -1
index 40cf59301c21..d3beddd8cc30 100644
@@ -94,6 +94,9 @@ static inline bool file_thp_enabled(struct vm_area_struct *vma)
 
 	inode = file_inode(vma->vm_file);
 
+	if (IS_ANON_FILE(inode))
+		return false;
+
 	return !inode_is_open_for_write(inode) && S_ISREG(inode->i_mode);
 }
 
--

2.43.0

#8 lore raw

PATCH 1/1 KVM: selftests: Test MADV_COLLAPSE on GUEST_MEMFD

In reply to Deepanshu Kartikey

guest_memfd only supports PAGE_SIZE pages, and khugepaged or MADV_COLLAPSE collapsing pages may result in private memory regions being mapped into host page tables.

Add test to verify that MADV_COLLAPSE fails on guest_memfd folios, and any subsequent usage of guest_memfd memory faults in PAGE_SIZE folios. Running this test should not result in any memory failure logs or kernel WARNings.

This selftest was added as a result of a syzbot-reported issue where khugepaged operating on guest_memfd memory with MADV_HUGEPAGE caused the collapse of folios, which then subsequently resulted in a WARNing.

---
 .../testing/selftests/kvm/guest_memfd_test.c  | 72 +++++++++++++++++++
 1 file changed, 72 insertions(+)
tools/testing/selftests/kvm/guest_memfd_test.c +72 -0
index 618c937f3c90f..d16341a4a315d 100644
@@ -171,6 +171,77 @@ static void test_numa_allocation(int fd, size_t total_size)
 	kvm_munmap(mem, total_size);
 }
 
+static size_t getpmdsize(void)
+{
+	const char *path = "/sys/kernel/mm/transparent_hugepage/hpage_pmd_size";
+	static size_t pmd_size = -1;
+	FILE *fp;
+
+	if (pmd_size != -1)
+		return pmd_size;
+
+	fp = fopen(path, "r");
+	TEST_ASSERT(fp, "Couldn't open %s to read PMD size.", path);
+
+	TEST_ASSERT_EQ(fscanf(fp, "%lu", &pmd_size), 1);
+
+	TEST_ASSERT_EQ(fclose(fp), 0);
+
+	return pmd_size;
+}
+
+static void test_collapse(struct kvm_vm *vm, uint64_t flags)
+{
+	const size_t pmd_size = getpmdsize();
+	char *mem;
+	off_t i;
+	int fd;
+
+	fd = vm_create_guest_memfd(vm, pmd_size * 2,
+				   GUEST_MEMFD_FLAG_MMAP |
+				   GUEST_MEMFD_FLAG_INIT_SHARED);
+
+	/*
+	 * Use aligned address so that MADV_COLLAPSE will not be
+	 * filtered out early in the collapsing routine.
+	 */
+#define ALIGNED_ADDRESS ((void *)0x4000000000UL)
+	mem = mmap(ALIGNED_ADDRESS, pmd_size, PROT_READ | PROT_WRITE,
+		   MAP_FIXED | MAP_SHARED, fd, 0);
+	TEST_ASSERT_EQ(mem, ALIGNED_ADDRESS);
+
+	/*
+	 * Use reads to populate page table to avoid setting dirty
+	 * flag on page.
+	 */
+	for (i = 0; i < pmd_size; i += getpagesize())
+		READ_ONCE(mem[i]);
+
+	/*
+	 * Advising the use of huge pages in guest_memfd should be
+	 * fine...
+	 */
+	TEST_ASSERT_EQ(madvise(mem, pmd_size, MADV_HUGEPAGE), 0);
+
+	/*
+	 * ... but collapsing folios must not be supported to avoid
+	 * mapping beyond shared ranges into host userspace page
+	 * tables.
+	 */
+	TEST_ASSERT_EQ(madvise(mem, pmd_size, MADV_COLLAPSE), -1);
+	TEST_ASSERT_EQ(errno, EINVAL);
+
+	/*
+	 * Removing from host page tables and re-faulting should be
+	 * fine; should not end up faulting in a collapsed/huge folio.
+	 */
+	TEST_ASSERT_EQ(madvise(mem, pmd_size, MADV_DONTNEED), 0);
+	READ_ONCE(mem[0]);
+
+	kvm_munmap(mem, pmd_size);
+	kvm_close(fd);
+}
+
 static void test_fault_sigbus(int fd, size_t accessible_size, size_t map_size)
 {
 	const char val = 0xaa;
@@ -370,6 +441,7 @@ static void __test_guest_memfd(struct kvm_vm *vm, uint64_t flags)
 			gmem_test(mmap_supported, vm, flags);
 			gmem_test(fault_overflow, vm, flags);
 			gmem_test(numa_allocation, vm, flags);
+			test_collapse(vm, flags);
 		} else {
 			gmem_test(fault_private, vm, flags);
 		}
Signature · 1 line
2.53.0.273.g2a3d683680-goog
#9 lore raw

Re: [PATCH] KVM: selftests: Test MADV_COLLAPSE on GUEST_MEMFD

tools/testing/selftests/kvm/guest_memfd_test.c static void test_numa_allocation(int fd, size_t total_size) · line 174

Quoted 9 lines · Ackerley Tng
tools/testing/selftests/kvm/guest_memfd_test.c +1 -0
index 618c937f3c90f..d16341a4a315d 100644
@@ -171,6 +171,77 @@ static void test_numa_allocation(int fd, size_t total_size)
 	kvm_munmap(mem, total_size);
 }
 
+static size_t getpmdsize(void)

This absolutely belongs in library/utility code.

tools/testing/selftests/kvm/guest_memfd_test.c static void test_numa_allocation(int fd, size_t total_size) · line 184

Quoted 10 lines
tools/testing/selftests/kvm/guest_memfd_test.c +10 -0
+{
+	const char *path = "/sys/kernel/mm/transparent_hugepage/hpage_pmd_size";
+	static size_t pmd_size = -1;
+	FILE *fp;
+
+	if (pmd_size != -1)
+		return pmd_size;
+
+	fp = fopen(path, "r");
+	TEST_ASSERT(fp, "Couldn't open %s to read PMD size.", path);

This will likely assert on a kernel without THP support.

tools/testing/selftests/kvm/guest_memfd_test.c static void test_numa_allocation(int fd, size_t total_size) · line 187

Quoted 3 lines
tools/testing/selftests/kvm/guest_memfd_test.c +3 -0
+	TEST_ASSERT_EQ(fscanf(fp, "%lu", &pmd_size), 1);
+
+	TEST_ASSERT_EQ(fclose(fp), 0);

Please try to extend tools/testing/selftests/kvm/include/kvm_syscalls.h.

Quoted 8 lines
tools/testing/selftests/kvm/guest_memfd_test.c +8 -0
+
+	return pmd_size;
+}
+
+static void test_collapse(struct kvm_vm *vm, uint64_t flags)
+{
+	const size_t pmd_size = getpmdsize();
+	char *mem;

tools/testing/selftests/kvm/guest_memfd_test.c static void test_numa_allocation(int fd, size_t total_size) · line 205

Quoted 10 lines
tools/testing/selftests/kvm/guest_memfd_test.c +10 -0
+	off_t i;
+	int fd;
+
+	fd = vm_create_guest_memfd(vm, pmd_size * 2,
+				   GUEST_MEMFD_FLAG_MMAP |
+				   GUEST_MEMFD_FLAG_INIT_SHARED);
+
+	/*
+	 * Use aligned address so that MADV_COLLAPSE will not be
+	 * filtered out early in the collapsing routine.

Please elaborate, the value below is way more magical than just being aligned.

tools/testing/selftests/kvm/guest_memfd_test.c static void test_numa_allocation(int fd, size_t total_size) · line 207

Quoted 2 lines
tools/testing/selftests/kvm/guest_memfd_test.c +2 -0
+	 */
+#define ALIGNED_ADDRESS ((void *)0x4000000000UL)

Use a "const void *" instead of #define inside a function. And use one of the appropriate size macros, e.g.

	const void *ALIGNED_ADDRESS = (void *)(SZ_1G * <some magic value>);

But why hardcode a virtual address in the first place? If you a specific alignment, just allocate enough virtual memory to be able to meet those alignment requirements.

Quoted 40 lines
tools/testing/selftests/kvm/guest_memfd_test.c +36 -0
+	mem = mmap(ALIGNED_ADDRESS, pmd_size, PROT_READ | PROT_WRITE,
+		   MAP_FIXED | MAP_SHARED, fd, 0);
+	TEST_ASSERT_EQ(mem, ALIGNED_ADDRESS);
+
+	/*
+	 * Use reads to populate page table to avoid setting dirty
+	 * flag on page.
+	 */
+	for (i = 0; i < pmd_size; i += getpagesize())
+		READ_ONCE(mem[i]);
+
+	/*
+	 * Advising the use of huge pages in guest_memfd should be
+	 * fine...
+	 */
+	TEST_ASSERT_EQ(madvise(mem, pmd_size, MADV_HUGEPAGE), 0);
+
+	/*
+	 * ... but collapsing folios must not be supported to avoid
+	 * mapping beyond shared ranges into host userspace page
+	 * tables.
+	 */
+	TEST_ASSERT_EQ(madvise(mem, pmd_size, MADV_COLLAPSE), -1);
+	TEST_ASSERT_EQ(errno, EINVAL);
+
+	/*
+	 * Removing from host page tables and re-faulting should be
+	 * fine; should not end up faulting in a collapsed/huge folio.
+	 */
+	TEST_ASSERT_EQ(madvise(mem, pmd_size, MADV_DONTNEED), 0);
+	READ_ONCE(mem[0]);
+
+	kvm_munmap(mem, pmd_size);
+	kvm_close(fd);
+}
+
 static void test_fault_sigbus(int fd, size_t accessible_size, size_t map_size)
 {
 	const char val = 0xaa;

tools/testing/selftests/kvm/guest_memfd_test.c static void __test_guest_memfd(struct kvm_vm *vm, uint64_t flags) · line 444

Quoted 4 lines
tools/testing/selftests/kvm/guest_memfd_test.c +1 -0
@@ -370,6 +441,7 @@ static void __test_guest_memfd(struct kvm_vm *vm, uint64_t flags)
 			gmem_test(mmap_supported, vm, flags);
 			gmem_test(fault_overflow, vm, flags);
 			gmem_test(numa_allocation, vm, flags);
+			test_collapse(vm, flags);

Why diverge from everything else? Yeah, the size is different, but that's easy enough to handle. And presumably the THP query needs to be able to fail gracefully, so something like this?

tools/testing/selftests/kvm/guest_memfd_test.c +17 -3
index 618c937f3c90..e942adae1f59 100644
@@ -350,14 +350,28 @@ static void test_guest_memfd_flags(struct kvm_vm *vm)
        }
 }
 
-#define gmem_test(__test, __vm, __flags)                               \
+#define __gmem_test(__test, __vm, __flags, __size)                     \
 do {                                                                   \
-       int fd = vm_create_guest_memfd(__vm, page_size * 4, __flags);   \
+       int fd = vm_create_guest_memfd(__vm, __size, __flags);          \
                                                                        \
-       test_##__test(fd, page_size * 4);                               \
+       test_##__test(fd, __size);                                      \
        close(fd);                                                      \
 } while (0)
 
+#define gmem_test(__test, __vm, __flags)                               \
+       __gmem_test(__test, __vm, __flags, page_size * 4)
+
+#define gmem_test_huge_pmd(__test, __vm, __flags)                      \
+do {                                                                   \
+       size_t pmd_size = kvm_get_thp_pmd_size();                       \
+                                                                       \
+       if (!pmd_size)                                                  \
+               break;                                                  \
+                                                                       \
+       __gmem_test(__test, __vm, __flags, pmd_size * 2);               \
+} while (0)
+
+
 static void __test_guest_memfd(struct kvm_vm *vm, uint64_t flags)
 {
        test_create_guest_memfd_multiple(vm);
#10 lore raw

Re: [PATCH] KVM: selftests: Test MADV_COLLAPSE on GUEST_MEMFD

Quoted 39 lines · Sean Christopherson

Review

Quoted 7 lines · Ackerley Tng

[...snip...]

(quoted diff) +4 -0
+
+	/*
+	 * Use aligned address so that MADV_COLLAPSE will not be
+	 * filtered out early in the collapsing routine.

Please elaborate, the value below is way more magical than just being aligned.

Review

Quoted 2 lines
(quoted diff) +2 -0
+	 */
+#define ALIGNED_ADDRESS ((void *)0x4000000000UL)

Use a "const void *" instead of #define inside a function. And use one of the appropriate size macros, e.g.

	const void *ALIGNED_ADDRESS = (void *)(SZ_1G * <some magic value>);

But why hardcode a virtual address in the first place? If you a specific alignment, just allocate enough virtual memory to be able to meet those alignment requirements.

Review static void __test_guest_memfd(struct kvm_vm *vm, uint64_t flags) · line 444

Quoted 10 lines
(quoted diff) +3 -0
+	mem = mmap(ALIGNED_ADDRESS, pmd_size, PROT_READ | PROT_WRITE,
+		   MAP_FIXED | MAP_SHARED, fd, 0);
 
[...snip...]
@@ -370,6 +441,7 @@ static void __test_guest_memfd(struct kvm_vm *vm, uint64_t flags)
 			gmem_test(mmap_supported, vm, flags);
 			gmem_test(fault_overflow, vm, flags);
 			gmem_test(numa_allocation, vm, flags);
+			test_collapse(vm, flags);

Why diverge from everything else? Yeah, the size is different, but that's easy enough to handle. And presumably the THP query needs to be able to fail gracefully, so something like this?

Quoted 2 lines

[...snip...]

Addressed your comments in a v2 [*], thanks for reviewing!

[*] https://lore.kernel.org/all/[email protected]/T/