[PATCH 08/32] mm/khugepaged: flush file after unlocking folios in collapse_file()
From: David Hildenbrand (Arm)
Date: Sun Nov 29 2026 - 05:09:39 EST
From: Chris Mason <mason@xxxxxxxxxx>
collapse_file() calls filemap_flush() when it encounters a dirty folio in
a file that is not open for writing. At that point, source folios earlier
in the range are still locked. The writable-open check is racy: a writer
can open the file after the check.
On ext4, the flush may need a journal handle, while EXT4_IOC_MOVE_EXT
takes a journal handle before locking folios, and a journal commit blocks
new handles while waiting for existing handles to be released.
Consequently, we can deadlock: collapse_file() waits for a handle, the
commit waits for extent movement to finish, and extent movement waits for
a source folio lock.
Let's fix it by deferring filemap_flush() until rollback has unlocked all
source folios.
This has medium urgency, as it can deadlock ext4 in some scenarios.
Fixes: 75f360696ce9 ("mm/thp: flush file for !is_shmem PageDirty() case in collapse_file()")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Chris Mason <mason@xxxxxxxxxx>
[ david: rework code; simplify comments and description ]
Signed-off-by: David Hildenbrand (Arm) <david@xxxxxxxxxx>
---
mm/khugepaged.c | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/mm/khugepaged.c b/mm/khugepaged.c
index b133c378dac72..7296673378c72 100644
--- a/mm/khugepaged.c
+++ b/mm/khugepaged.c
@@ -2272,6 +2272,7 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
int nr_none = 0;
bool do_readahead = false;
bool readahead_done = false;
+ bool any_non_shmem_dirty = false;
/*
* MADV_COLLAPSE ignores shmem huge config, so do not check shmem
@@ -2376,8 +2377,7 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
* forcing writeback in loop.
*/
xas_unlock_irq(&xas);
- if (!inode_is_open_for_write(mapping->host))
- filemap_flush(mapping);
+ any_non_shmem_dirty = true;
result = SCAN_PAGE_DIRTY_OR_WRITEBACK;
goto xa_unlocked;
} else if (folio_test_writeback(folio)) {
@@ -2711,6 +2711,10 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
}
out_put:
folio_put(new_folio);
+
+ /* Flush after unlocking all folios. */
+ if (any_non_shmem_dirty && !inode_is_open_for_write(mapping->host))
+ filemap_flush(mapping);
out:
VM_BUG_ON(!list_empty(&pagelist));
trace_mm_khugepaged_collapse_file(mm, new_pfn, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
--
2.56.1