mm/truncate: fix data loss when truncating straddling large folios
Subsystems (5)
v3 cover mm/truncate: fix data loss when truncating straddling large folios
From: Zhang Yi <[email protected]>
Hello,
This is the third version fixing data loss when truncating straddling large folios caught on the upcomming ext4 + iomap buffered I/O conversion[1]. I've clarify the split logic as Joanne and Brian suggested, also slove the concurrent issue pointed out by sashiko and split the patch into 3 small ones as Zi Yan suggested.
Patch 1: Add pstart and pend parameters to
truncate_inode_partial_folio() and fix the data loss issue when the second splitting straddling large folios fails.
Patch 2: Fix the similar data loss issue also could encountered on the
filesystem with min_order > 0.
Patch 3: Clarify the existing confusing return value of
truncate_inode_partial_folio().
Thanks,
Yi.
[1] https://lore.kernel.org/linux-fsdevel/[email protected]/
v2->v3:
- Rework the folio2 validity check logic to fix the invalid folio->index issue. (sashiko)
- Clarify the pstart and pend setting logic and the corresponding comments to make it more readable. (Brian, Joanne)
- Split the patch into 3 small patches. (Zi Yan)v1->v2:
- Export pstart as a new parameter so that the generic and shmem truncate paths don't need to recompute the start value from the return value. (Brian)
- When min_order is nonzero, align [pstart, pend] to the inner boundaries of the folio to ensure they do not point into the middle of a large folio, which could otherwise cause valid data within the folio to be incorrectly cleared. (Joanne)
v2: https://lore.kernel.org/linux-mm/[email protected]/
v1: https://lore.kernel.org/linux-mm/[email protected]/
Zhang Yi (3):
mm/truncate: fix data loss when splitting straddling large folios
fails
mm/truncate: align truncation boundaries to mapping minimum folio
order
mm/truncate: clarify return value of truncate_inode_partial_folio()
mm/internal.h | 4 +- mm/shmem.c | 13 +++---- mm/truncate.c | 105 ++++++++++++++++++++++++++++++++++---------------- 3 files changed, 79 insertions(+), 43 deletions(-)
Signature · 1 line
2.52.0
PATCH v3 1/3 mm/truncate: fix data loss when splitting straddling large folios fails
From: Zhang Yi <[email protected]>
truncate_inode_partial_folio() splits a large folio so that the caller's truncate loop can drop the in-range sub-folios while keeping the out-of-range tail. The first split at the punch start edge is non-uniform, which leaves the sub-folio at the truncation end edge as large as possible, this means it may still straddle the range, holding both zeroed in-range and valid out-of-range data. The function then attempts a second split at offset + length to isolate that tail.
If the second split fails the straddling sub-folio stays merged. The function returned true unconditionally on all exit paths of the success block, telling the caller it was fully handled. The caller kept its default end and the truncate loop truncated every sub-folio below it, including the merged straddler, discarding the valid out-of-range tail.
For example, a 4-page order-2 folio punched from offset 0 to the middle of the last page:
truncate_inode_pages_range()
truncate_inode_partial_folio() # same_folio == true
1st split at page0 -> [p0, p1, p2-3] # non-uniform, success
folio2 = p2-3 # straddles: p2 zeroed, p3 tail valid 2nd split of folio2 fails / cannot lock
return true # BUG: caller keeps default end
end = 3
loop truncates p0, p1, p2-3 # p3's valid tail is lost
This became reachable after commit 7460b470a131 ("mm/truncate: use folio_split() in truncate operation") replaced the atomic split_folio() with folio_split(), whose non-uniform split can partially split a folio and leave the end edge merged.
It has gone unnoticed because a dirty large folio normally carries the filesystem's private data, for example buffer_head, so filemap_release_folio() -> iomap_release_folio() returns false on a dirty folio and folio_split() aborts with -EBUSY before any split, leaving the straddler safely unsplit. The bug is only reachable on paths that produce dirty large folios without filesystem private data, and it was caught on the upcoming ext4 iomap buffered I/O path when no ifs is attached.
Rework the contract so the caller is told the page range to discard:
- Add pgoff_t *pstart and *pend out-parameters that receive the page range fully covered by [lstart, lend] after any split (or none), i.e. the pages wholly within the range and safe to discard.
- Adjust the ordering of the validate check when splitting folio2. folio2->index is only reliable after the reference count and lock have been successfully acquired, since it may have been split concurrently, or freed and recycled to an unrelated mapping. On any failure to obtain a reliable end position, fall back to folio->index, which is safe but leaves the sub-folios split off at the offset edge in the page cache.
- Rename the byte-range parameters start/end to lstart/lend to better express their semantics.
Callers in truncate_inode_pages_range() and shmem_undo_range() pass &pstart for the folio at the start edge and &pend for the folio at the end edge, so the truncate loop drops exactly the fully covered pages and never touches a straddling folio that still holds valid out-of-range data.
--- mm/internal.h | 4 +-- mm/shmem.c | 13 +++----- mm/truncate.c | 89 ++++++++++++++++++++++++++++++++++++--------------- 3 files changed, 71 insertions(+), 35 deletions(-)
mm/internal.h +2 -2
@@ -627,8 +627,8 @@ unsigned find_lock_entries(struct address_space *mapping, pgoff_t *start,unsigned find_get_entries (struct address_space *mapping,pgoff_t *start,pgoff_t end,struct folio_batch *fbatch,pgoff_t *indices);int truncate_inode_folio (struct address_space *mapping,struct folio *folio); -bool truncate_inode_partial_folio (struct folio *folio,loff_t start, -loff_t end); +bool truncate_inode_partial_folio (struct folio *folio,loff_t lstart, +loff_t lend,pgoff_t *pstart,pgoff_t *pend);long mapping_evict_folio (struct address_space *mapping,struct folio *folio);unsigned long mapping_try_invalidate (struct address_space *mapping,pgoff_t start,pgoff_t end,unsigned long *nr_failed);
mm/shmem.c +5 -8
@@ -1175,11 +1175,8 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,if (folio) { same_folio = lend <folio_next_pos (folio);folio_mark_dirty (folio); -if (!truncate_inode_partial_folio (folio, lstart, lend)) { - start =folio_next_index (folio); -if (same_folio) - end = folio->index; - } +truncate_inode_partial_folio (folio, lstart, lend, &start, + same_folio ? &end :NULL );folio_unlock (folio);folio_put (folio); folio =NULL ;
@@ -1189,8 +1186,7 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend, folio =shmem_get_partial_folio (inode, lend >>PAGE_SHIFT );if (folio) {folio_mark_dirty (folio); -if (!truncate_inode_partial_folio (folio, lstart, lend)) - end = folio->index; +truncate_inode_partial_folio (folio, lstart, lend,NULL , &end);folio_unlock (folio);folio_put (folio); }
@@ -1258,7 +1254,8 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,if (!folio_test_large (folio)) {truncate_inode_folio (mapping, folio); - }else if (truncate_inode_partial_folio (folio, lstart, lend)) { + }else if (truncate_inode_partial_folio (folio, + lstart, lend,NULL ,NULL )) {/* * If we split a page, reset the loop so * that we pick up the new sub pages.
mm/truncate.c +64 -25
144 lines not on this page · raw message
Signature · 1 line
2.52.0
[email protected]
AI reviewRe: [PATCH v3 1/3] mm/truncate: fix data loss when splitting straddling large folios fails
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Critical] mm: data loss in hole punch due to ABA in speculative folio lookup - [High] mm: memory leak in…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] mm: data loss in hole punch due to ABA in speculative folio lookup
- [High] mm: memory leak in hole punch due to skipped successfully split order-0 folios --
commit 2e1b0dbca7f3fd72aa6840729db47e2498ff1268
Author: Zhang Yi <[email protected]>
mm/truncate: fix data loss when splitting straddling large folios fails
This commit modifies truncate_inode_partial_folio to return out-parameters pstart and pend indicating the fully covered page range safe to discard after any split. This is intended to fix a data loss issue when splitting a straddling large folio fails.
Quoted 36 lines
mm/truncate.c +17
-2@@ -259,32 +271,62 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end)* for shmem truncate */ struct folio *folio2; +pgoff_t end, aligned_end = (pos + offset + length) >> +PAGE_SHIFT ; -if (offset + length == size) - goto no_split; +if (pstart) + *pstart =round_up (pos + offset,PAGE_SIZE ) >> +PAGE_SHIFT ; + +if (offset + length == size) { + end = aligned_end; + goto out; + } split_at2 =folio_page (folio,PAGE_ALIGN_DOWN (offset + length) /PAGE_SIZE ); folio2 =page_folio (split_at2); +/* +* folio2 may become stale due to a concurrent split or +* freeing, so validate it before and after taking its lock. +* If it fails, we can't get an accurate end position and fall +* back to folio->index, which may leave sub-folios split off +* at the offset edge in the page cache this round. +*/
mm/truncate.c bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end) · line 303
Quoted 10 lines
mm/truncate.c +4
-3+ end = folio->index;if (!folio_try_get (folio2)) - goto no_split; - -if (!folio_test_large (folio2)) goto out; +if (folio2->mapping != folio->mapping || + !folio_test_large (folio2)) + goto out_put;
[Severity: High]
Could this lead to a memory leak if the first split successfully shatters the folio to order-0 pages?
If the hole punch starts in the middle of a large folio and the first split successfully shatters it into order-0 folios (which happens when min_order is 0), the tail page folio2 becomes an order-0 folio.
The speculative pre-lock check validates folio2 here:
if (folio2->mapping != folio->mapping ||
!folio_test_large(folio2))
goto out_put;Because folio2 is order-0, !folio_test_large(folio2) evaluates to true. Execution jumps to out_put without updating end to aligned_end, leaving end initialized to folio->index.
When pend is returned as folio->index to the caller (truncate_inode_pages_range), it is used as the upper bound for the truncation loop. Because end is less than or equal to start, the loop terminates immediately, skipping the pages within the hole punch range and leaving them permanently leaked in the page cache.
Quoted 14 lines
mm/truncate.c +13
-1+ +if (!folio_trylock (folio2)) - goto out; + goto out_put; + +if (page_folio (split_at2) != folio2) { +folio_unlock (folio2); + goto out_put; + } +if (!folio_test_large (folio2)) { + end = aligned_end; +folio_unlock (folio2); + goto out_put; + }
mm/truncate.c bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end)
Quoted 10 lines
mm/truncate.c +5
-4-/* make sure folio2 is large and does not change its mapping */ -if (folio_test_large (folio2) && - folio2->mapping == folio->mapping) -folio_split_or_unmap (folio2, split_at2, min_order); +/* Split failed: back off to the head of the straddler */ +if (folio_split_or_unmap (folio2, split_at2, min_order)) + end = folio2->index; +else + end = aligned_end;
[Severity: Critical]
Does this speculative lookup handle the reallocation race correctly if the folio is reallocated to a different file offset?
After the first split, the tail pages are added to the page cache and unlocked. During speculative lookup, the tail page could be concurrently reclaimed, freed, and reallocated as a new large folio in the same mapping but at a completely different file offset.
The validation checks earlier and the page_folio check here will all pass because the physical page split_at2 is part of the new allocation.
However, the file index of the folio is not verified. If this unrelated large folio fails to split, the fallback path assigns its index to end here:
if (folio_split_or_unmap(folio2, split_at2, min_order))
end = folio2->index;
This unrelated file offset is then returned to the caller via pend, which can cause the hole punch loop to truncate an unrelated segment of the file.
Should we verify that the file index of folio2 matches the expected index (e.g. folio2->index + folio_page_idx(folio2, split_at2) == expected_index) before using it?
Quoted 12 lines
mm/truncate.c +4
-2folio_unlock (folio2); -out: +out_put:folio_put (folio2); -no_split: +out: +if (pend) + *pend = end;return true; }if (folio_test_dirty (folio))
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Jan Kara
maintainerRe: [PATCH v3 1/3] mm/truncate: fix data loss when splitting straddling large folios fails
In reply to Zhang YiQuoted 65 lines · Zhang Yi
From: Zhang Yi <[email protected]>
truncate_inode_partial_folio()splits a large folio so that the caller's truncate loop can drop the in-range sub-folios while keeping the out-of-range tail. The first split at the punch start edge is non-uniform, which leaves the sub-folio at the truncation end edge as large as possible, this means it may still straddle the range, holding both zeroed in-range and valid out-of-range data. The function then attempts a second split at offset + length to isolate that tail.If the second split fails the straddling sub-folio stays merged. The function returned true unconditionally on all exit paths of the success block, telling the caller it was fully handled. The caller kept its default end and the truncate loop truncated every sub-folio below it, including the merged straddler, discarding the valid out-of-range tail.
For example, a 4-page order-2 folio punched from offset 0 to the middle of the last page:
truncate_inode_pages_range()
truncate_inode_partial_folio()#same_folio== true
1st split at page0 -> [p0, p1, p2-3] # non-uniform, success
folio2 = p2-3 # straddles: p2 zeroed, p3 tail valid 2nd split of folio2 fails / cannot lock
return true # BUG: caller keeps default end
end = 3
loop truncates p0, p1, p2-3 # p3's valid tail is lostThis became reachable after commit
7460b470a131("mm/truncate: usefolio_split()in truncate operation") replaced the atomicsplit_folio()withfolio_split(), whose non-uniform split can partially split a folio and leave the end edge merged.It has gone unnoticed because a dirty large folio normally carries the filesystem's private data, for example
buffer_head, sofilemap_release_folio()->iomap_release_folio()returns false on a dirty folio andfolio_split()aborts with-EBUSYbefore any split, leaving the straddler safely unsplit. The bug is only reachable on paths that produce dirty large folios without filesystem private data, and it was caught on the upcoming ext4 iomap buffered I/O path when no ifs is attached.Rework the contract so the caller is told the page range to discard:
- Add
pgoff_t*pstart and *pend out-parameters that receive the page range fully covered by [lstart, lend] after any split (or none), i.e. the pages wholly within the range and safe to discard.- Adjust the ordering of the validate check when splitting folio2.
folio2->indexis only reliable after the reference count and lock have been successfully acquired, since it may have been split concurrently, or freed and recycled to an unrelated mapping. On any failure to obtain a reliable end position, fall back tofolio->index, which is safe but leaves the sub-folios split off at the offset edge in the page cache.- Rename the byte-range parameters start/end to lstart/lend to better express their semantics.
Callers in
truncate_inode_pages_range()andshmem_undo_range()pass &pstart for the folio at the start edge and &pend for the folio at the end edge, so the truncate loop drops exactly the fully covered pages and never touches a straddling folio that still holds valid out-of-range data.
Quoted 4 lines
Suggested-by Brian Foster <[email protected]>Fixes 7460b470a131 ("mm/truncate: use folio_split() in truncate operation")Signed-off-by Zhang Yi <[email protected]>
The changes mostly look good to me but I have some confusion around the folio2 splitting below.
Quoted 47 lines
mm/truncate.c +23
-9@@ -259,32 +271,62 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end)* for shmem truncate */ struct folio *folio2; +pgoff_t end, aligned_end = (pos + offset + length) >> +PAGE_SHIFT ; -if (offset + length == size) - goto no_split; +if (pstart) + *pstart =round_up (pos + offset,PAGE_SIZE ) >> +PAGE_SHIFT ; + +if (offset + length == size) { + end = aligned_end; + goto out; + } split_at2 =folio_page (folio,PAGE_ALIGN_DOWN (offset + length) /PAGE_SIZE ); folio2 =page_folio (split_at2); +/* +* folio2 may become stale due to a concurrent split or +* freeing, so validate it before and after taking its lock. +* If it fails, we can't get an accurate end position and fall +* back to folio->index, which may leave sub-folios split off +* at the offset edge in the page cache this round. +*/ + end = folio->index;if (!folio_try_get (folio2)) - goto no_split; - -if (!folio_test_large (folio2)) goto out; +if (folio2->mapping != folio->mapping || + !folio_test_large (folio2)) + goto out_put; +if (!folio_trylock (folio2)) - goto out; + goto out_put; -/* make sure folio2 is large and does not change its mapping */ -if (folio_test_large (folio2) && - folio2->mapping == folio->mapping)
mm/truncate.c bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end) · line 316
Quoted 10 lines
mm/truncate.c +9
-1-folio_split_or_unmap (folio2, split_at2, min_order); +if (page_folio (split_at2) != folio2) { +folio_unlock (folio2); + goto out_put; + } +if (!folio_test_large (folio2)) { + end = aligned_end; +folio_unlock (folio2); + goto out_put; + }
So I always found this folio2 lookup and revalidation somewhat suspicious and now that we're digging into it I'll ask: As you note in the changelog, by the time we compute split_at2 the page can be already freed and reused because it was split off from the original 'folio'. It can be for example a slab page or anything else. So is it guaranteed that page_folio() actually returns something sensible? What guarantees we properly detect the "reuse for something else" case in all possible cases for which the page can be reused? I understand this is mostly a preexisting issue so maybe these questions are more for MM guys than you...
So for me as an filesystem guy I'd appreciate some comment in this code explaining why grabbing folio2 this way is actually safe. The really safe way of getting to folio2 would be to use
__filemap_get_folio(mapping, (offset+length) >> PAGE_SHIFT, FGP_LOCK, 0)
but I suppose we don't use the mapping lookup as it is more expensive?
Honza
Quoted 46 lines
mm/truncate.c +14
-9+ +/* Split failed: back off to the head of the straddler */ +if (folio_split_or_unmap (folio2, split_at2, min_order)) + end = folio2->index; +else + end = aligned_end;folio_unlock (folio2); -out: +out_put:folio_put (folio2); -no_split: +out: +if (pend) + *pend = end;return true; }if (folio_test_dirty (folio))@@ -413,11 +455,8 @@ void truncate_inode_pages_range(struct address_space *mapping, folio =__filemap_get_folio (mapping, lstart >>PAGE_SHIFT ,FGP_LOCK ,0 );if (!IS_ERR (folio)) { same_folio = lend <folio_next_pos (folio); -if (!truncate_inode_partial_folio (folio, lstart, lend)) { - start =folio_next_index (folio); -if (same_folio) - end = folio->index; - } +truncate_inode_partial_folio (folio, lstart, lend, &start, + same_folio ? &end :NULL );folio_unlock (folio);folio_put (folio); folio =NULL ;@@ -427,8 +466,8 @@ void truncate_inode_pages_range(struct address_space *mapping, folio =__filemap_get_folio (mapping, lend >>PAGE_SHIFT ,FGP_LOCK ,0 );if (!IS_ERR (folio)) { -if (!truncate_inode_partial_folio (folio, lstart, lend)) - end = folio->index; +truncate_inode_partial_folio (folio, lstart, lend, +NULL , &end);folio_unlock (folio);folio_put (folio); }Signature · 1 line
2.52.0
Signature · 2 lines
Jan Kara <[email protected]> SUSE Labs, CR
Re: [PATCH v3 1/3] mm/truncate: fix data loss when splitting straddling large folios fails
Quoted 129 lines · Jan Kara
Quoted 65 lines · Zhang Yi
From: Zhang Yi <[email protected]>
truncate_inode_partial_folio()splits a large folio so that the caller's truncate loop can drop the in-range sub-folios while keeping the out-of-range tail. The first split at the punch start edge is non-uniform, which leaves the sub-folio at the truncation end edge as large as possible, this means it may still straddle the range, holding both zeroed in-range and valid out-of-range data. The function then attempts a second split at offset + length to isolate that tail.If the second split fails the straddling sub-folio stays merged. The function returned true unconditionally on all exit paths of the success block, telling the caller it was fully handled. The caller kept its default end and the truncate loop truncated every sub-folio below it, including the merged straddler, discarding the valid out-of-range tail.
For example, a 4-page order-2 folio punched from offset 0 to the middle of the last page:
truncate_inode_pages_range()
truncate_inode_partial_folio()#same_folio== true
1st split at page0 -> [p0, p1, p2-3] # non-uniform, success
folio2 = p2-3 # straddles: p2 zeroed, p3 tail valid 2nd split of folio2 fails / cannot lock
return true # BUG: caller keeps default end
end = 3
loop truncates p0, p1, p2-3 # p3's valid tail is lostThis became reachable after commit
7460b470a131("mm/truncate: usefolio_split()in truncate operation") replaced the atomicsplit_folio()withfolio_split(), whose non-uniform split can partially split a folio and leave the end edge merged.It has gone unnoticed because a dirty large folio normally carries the filesystem's private data, for example
buffer_head, sofilemap_release_folio()->iomap_release_folio()returns false on a dirty folio andfolio_split()aborts with-EBUSYbefore any split, leaving the straddler safely unsplit. The bug is only reachable on paths that produce dirty large folios without filesystem private data, and it was caught on the upcoming ext4 iomap buffered I/O path when no ifs is attached.Rework the contract so the caller is told the page range to discard:
- Add
pgoff_t*pstart and *pend out-parameters that receive the page range fully covered by [lstart, lend] after any split (or none), i.e. the pages wholly within the range and safe to discard.- Adjust the ordering of the validate check when splitting folio2.
folio2->indexis only reliable after the reference count and lock have been successfully acquired, since it may have been split concurrently, or freed and recycled to an unrelated mapping. On any failure to obtain a reliable end position, fall back tofolio->index, which is safe but leaves the sub-folios split off at the offset edge in the page cache.- Rename the byte-range parameters start/end to lstart/lend to better express their semantics.
Callers in
truncate_inode_pages_range()andshmem_undo_range()pass &pstart for the folio at the start edge and &pend for the folio at the end edge, so the truncate loop drops exactly the fully covered pages and never touches a straddling folio that still holds valid out-of-range data.Quoted 4 lines
Suggested-by Brian Foster <[email protected]>Fixes 7460b470a131 ("mm/truncate: use folio_split() in truncate operation")Signed-off-by Zhang Yi <[email protected]>The changes mostly look good to me but I have some confusion around the folio2 splitting below.
Quoted 55 lines
mm/truncate.c +30
-10@@ -259,32 +271,62 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end)* for shmem truncate */ struct folio *folio2; +pgoff_t end, aligned_end = (pos + offset + length) >> +PAGE_SHIFT ; -if (offset + length == size) - goto no_split; +if (pstart) + *pstart =round_up (pos + offset,PAGE_SIZE ) >> +PAGE_SHIFT ; + +if (offset + length == size) { + end = aligned_end; + goto out; + } split_at2 =folio_page (folio,PAGE_ALIGN_DOWN (offset + length) /PAGE_SIZE ); folio2 =page_folio (split_at2); +/* +* folio2 may become stale due to a concurrent split or +* freeing, so validate it before and after taking its lock. +* If it fails, we can't get an accurate end position and fall +* back to folio->index, which may leave sub-folios split off +* at the offset edge in the page cache this round. +*/ + end = folio->index;if (!folio_try_get (folio2)) - goto no_split; - -if (!folio_test_large (folio2)) goto out; +if (folio2->mapping != folio->mapping || + !folio_test_large (folio2)) + goto out_put; +if (!folio_trylock (folio2)) - goto out; + goto out_put; -/* make sure folio2 is large and does not change its mapping */ -if (folio_test_large (folio2) && - folio2->mapping == folio->mapping) -folio_split_or_unmap (folio2, split_at2, min_order); +if (page_folio (split_at2) != folio2) { +folio_unlock (folio2); + goto out_put; + } +if (!folio_test_large (folio2)) { + end = aligned_end; +folio_unlock (folio2);
Quoted 8 lines
Review bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end) · line 316
Quoted 2 lines
(quoted diff) +2
-0+ goto out_put; + }So I always found this folio2 lookup and revalidation somewhat suspicious and now that we're digging into it I'll ask: As you note in the changelog, by the time we compute
split_at2the page can be already freed and reused because it was split off from the original 'folio'. It can be for example a slab page or anything else. So is it guaranteed thatpage_folio()actually
For a slab or unrelated page, folio->mapping check rejects them.
Quoted 1 line
returns something sensible? What guarantees we properly detect the "reuse
No, but folio_try_get() prevents non ref'd folios.
Quoted 3 lines
for something else" case in all possible cases for which the page can be reused? I understand this is mostly a preexisting issue so maybe these questions are more for MM guys than you...
I agree with you that trying to split a unlocked and not ref'd folio2 is flaky. And it almost does a __filemap_get_folio() like you proposed below.
Quoted 6 lines
So for me as an filesystem guy I'd appreciate some comment in this code explaining why grabbing folio2 this way is actually safe. The really safe way of getting to folio2 would be to use
__filemap_get_folio(mapping, (offset+length) >> PAGE_SHIFT, FGP_LOCK, 0)
but I suppose we don't use the mapping lookup as it is more expensive?
__filemap_get_folio() is a better version of the existing folio2 finding code. When I wrote the code, I never thought about using __filemap_get_folio(), but I probably should have done it.
BTW,
__filemap_get_folio(mapping, folio->index + (offset+length) >> PAGE_SHIFT,
FGP_LOCK | FGP_NOWAIT, 0)
might be better:
1. folio->index is needed to get the right folio2,
2. nowait can us nonblocking.
Quoted 46 lines
Quoted 46 lines
mm/truncate.c +14
-9+ +/* Split failed: back off to the head of the straddler */ +if (folio_split_or_unmap (folio2, split_at2, min_order)) + end = folio2->index; +else + end = aligned_end;folio_unlock (folio2); -out: +out_put:folio_put (folio2); -no_split: +out: +if (pend) + *pend = end;return true; }if (folio_test_dirty (folio))@@ -413,11 +455,8 @@ void truncate_inode_pages_range(struct address_space *mapping, folio =__filemap_get_folio (mapping, lstart >>PAGE_SHIFT ,FGP_LOCK ,0 );if (!IS_ERR (folio)) { same_folio = lend <folio_next_pos (folio); -if (!truncate_inode_partial_folio (folio, lstart, lend)) { - start =folio_next_index (folio); -if (same_folio) - end = folio->index; - } +truncate_inode_partial_folio (folio, lstart, lend, &start, + same_folio ? &end :NULL );folio_unlock (folio);folio_put (folio); folio =NULL ;@@ -427,8 +466,8 @@ void truncate_inode_pages_range(struct address_space *mapping, folio =__filemap_get_folio (mapping, lend >>PAGE_SHIFT ,FGP_LOCK ,0 );if (!IS_ERR (folio)) { -if (!truncate_inode_partial_folio (folio, lstart, lend)) - end = folio->index; +truncate_inode_partial_folio (folio, lstart, lend, +NULL , &end);folio_unlock (folio);folio_put (folio); }Signature · 1 line
2.52.0
Signature · 2 lines
Best Regards, Yan, Zi
Re: [PATCH v3 1/3] mm/truncate: fix data loss when splitting straddling large folios fails
Quoted 145 lines · Zi Yan
Quoted 129 lines · Jan Kara
Quoted 65 lines · Zhang Yi
From: Zhang Yi <[email protected]>
truncate_inode_partial_folio()splits a large folio so that the caller's truncate loop can drop the in-range sub-folios while keeping the out-of-range tail. The first split at the punch start edge is non-uniform, which leaves the sub-folio at the truncation end edge as large as possible, this means it may still straddle the range, holding both zeroed in-range and valid out-of-range data. The function then attempts a second split at offset + length to isolate that tail.If the second split fails the straddling sub-folio stays merged. The function returned true unconditionally on all exit paths of the success block, telling the caller it was fully handled. The caller kept its default end and the truncate loop truncated every sub-folio below it, including the merged straddler, discarding the valid out-of-range tail.
For example, a 4-page order-2 folio punched from offset 0 to the middle of the last page:
truncate_inode_pages_range()
truncate_inode_partial_folio()#same_folio== true
1st split at page0 -> [p0, p1, p2-3] # non-uniform, success
folio2 = p2-3 # straddles: p2 zeroed, p3 tail valid 2nd split of folio2 fails / cannot lock
return true # BUG: caller keeps default end
end = 3
loop truncates p0, p1, p2-3 # p3's valid tail is lostThis became reachable after commit
7460b470a131("mm/truncate: usefolio_split()in truncate operation") replaced the atomicsplit_folio()withfolio_split(), whose non-uniform split can partially split a folio and leave the end edge merged.It has gone unnoticed because a dirty large folio normally carries the filesystem's private data, for example
buffer_head, sofilemap_release_folio()->iomap_release_folio()returns false on a dirty folio andfolio_split()aborts with-EBUSYbefore any split, leaving the straddler safely unsplit. The bug is only reachable on paths that produce dirty large folios without filesystem private data, and it was caught on the upcoming ext4 iomap buffered I/O path when no ifs is attached.Rework the contract so the caller is told the page range to discard:
- Add
pgoff_t*pstart and *pend out-parameters that receive the page range fully covered by [lstart, lend] after any split (or none), i.e. the pages wholly within the range and safe to discard.- Adjust the ordering of the validate check when splitting folio2.
folio2->indexis only reliable after the reference count and lock have been successfully acquired, since it may have been split concurrently, or freed and recycled to an unrelated mapping. On any failure to obtain a reliable end position, fall back tofolio->index, which is safe but leaves the sub-folios split off at the offset edge in the page cache.- Rename the byte-range parameters start/end to lstart/lend to better express their semantics.
Callers in
truncate_inode_pages_range()andshmem_undo_range()pass &pstart for the folio at the start edge and &pend for the folio at the end edge, so the truncate loop drops exactly the fully covered pages and never touches a straddling folio that still holds valid out-of-range data.Quoted 4 lines
Suggested-by Brian Foster <[email protected]>Fixes 7460b470a131 ("mm/truncate: use folio_split() in truncate operation")Signed-off-by Zhang Yi <[email protected]>The changes mostly look good to me but I have some confusion around the folio2 splitting below.
Quoted 55 lines
(quoted diff) +30
-10@@ -259,32 +271,62 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end) * for shmem truncate */ struct folio *folio2; + pgoff_t end, aligned_end = (pos + offset + length) >> + PAGE_SHIFT; - if (offset + length == size) - goto no_split; + if (pstart) + *pstart = round_up(pos + offset, PAGE_SIZE) >> + PAGE_SHIFT; + + if (offset + length == size) { + end = aligned_end; + goto out; + } split_at2 = folio_page(folio, PAGE_ALIGN_DOWN(offset + length) / PAGE_SIZE); folio2 = page_folio(split_at2); + /* + * folio2 may become stale due to a concurrent split or + * freeing, so validate it before and after taking its lock. + * If it fails, we can't get an accurate end position and fall + * back to folio->index, which may leave sub-folios split off + * at the offset edge in the page cache this round. + */ + end = folio->index; if (!folio_try_get(folio2)) - goto no_split; - - if (!folio_test_large(folio2)) goto out; + if (folio2->mapping != folio->mapping || + !folio_test_large(folio2)) + goto out_put; + if (!folio_trylock(folio2)) - goto out; + goto out_put; - /* make sure folio2 is large and does not change its mapping */ - if (folio_test_large(folio2) && - folio2->mapping == folio->mapping) - folio_split_or_unmap(folio2, split_at2, min_order); + if (page_folio(split_at2) != folio2) { + folio_unlock(folio2); + goto out_put; + } + if (!folio_test_large(folio2)) { + end = aligned_end; + folio_unlock(folio2);Quoted 8 lines
Review bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end) · line 316
Quoted 2 lines
(quoted diff) +2
-0+ goto out_put; + }So I always found this folio2 lookup and revalidation somewhat suspicious and now that we're digging into it I'll ask: As you note in the changelog, by the time we compute
split_at2the page can be already freed and reused because it was split off from the original 'folio'. It can be for example a slab page or anything else. So is it guaranteed thatpage_folio()actuallyFor a slab or unrelated page,
folio->mappingcheck rejects them.Quoted 1 line
returns something sensible? What guarantees we properly detect the "reuse
No, but
folio_try_get()prevents non ref'd folios.
Quoted 8 lines
Quoted 3 lines
for something else" case in all possible cases for which the page can be reused? I understand this is mostly a preexisting issue so maybe these questions are more for MM guys than you...
I agree with you that trying to split a unlocked and not ref'd folio2 is flaky. And it almost does a
__filemap_get_folio()like you proposed below.
I think this is indeed a pre-existing issue, as Sashiko pointed out:
Quoted 18 lines
[Severity: Critical]
Does this speculative lookup handle the reallocation race correctly if the folio is reallocated to a different file offset?After the first split, the tail pages are added to the page cache and unlocked. During speculative lookup, the tail page could be concurrently reclaimed, freed, and reallocated as a new large folio in the same mapping but at a completely different file offset.
The validation checks earlier and the
page_foliocheck here will all pass because the physical pagesplit_at2is part of the new allocation.However, the file index of the folio is not verified. If this unrelated large folio fails to split, the fallback path assigns its index to end here:
if (
folio_split_or_unmap(folio2, split_at2, min_order))
end =folio2->index;
Quoted 6 lines
This unrelated file offset is then returned to the caller via pend, which can cause the hole punch loop to truncate an unrelated segment of the file.
Should we verify that the file index of folio2 matches the expected index (e.g.
folio2->index+folio_page_idx(folio2, split_at2)==expected_index) before using it?
the current mapping check on the folio2 and the folio != page_folio(split_at) check in __folio_split() are not able to catch this problem, which could then cause folio2 to be split at the wrong position. Does that sound right?
Quoted 11 lines
Quoted 6 lines
So for me as an filesystem guy I'd appreciate some comment in this code explaining why grabbing folio2 this way is actually safe. The really safe way of getting to folio2 would be to use
__filemap_get_folio(mapping, (offset+length) >> PAGE_SHIFT, FGP_LOCK, 0)
but I suppose we don't use the mapping lookup as it is more expensive?
__filemap_get_folio()is a better version of the existing folio2 finding code. When I wrote the code, I never thought about using__filemap_get_folio(), but I probably should have done it.
Quoted 8 lines
BTW,
__filemap_get_folio(mapping,folio->index+ (offset+length) >>PAGE_SHIFT,
FGP_LOCK|FGP_NOWAIT, 0)
might be better:
1.folio->indexis needed to get the right folio2,
2. nowait can us nonblocking.
Following your suggestion, I reworked my existing patch to use __filemap_get_folio(), and it ends up looking roughly like the following(not tested yet). What do you think?
Besides, if the issue Sashiko pointed out does indeed exist, I can extract the __filemap_get_folio() change into a separate patch to fix it on its own.
Thanks,
Yi.
mm/truncate.c +29 -34
@@ -279,51 +279,46 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart, *pstart =round_up (pos + offset, min_nrbytes) >>PAGE_SHIFT ; -if (offset + length == size) { - end = aligned_end; + end = aligned_end; +if (offset + length == size) goto out; - } - - split_at2 =folio_page (folio, -PAGE_ALIGN_DOWN (offset + length) /PAGE_SIZE ); - folio2 =page_folio (split_at2);/* -* folio2 may become stale due to a concurrent split or -* freeing, so validate it before and after taking its lock. -* If it fails, we can't get an accurate end position and fall -* back to folio->index, which may leave sub-folios split off -* at the offset edge in the page cache this round. +* After the first split at the start edge, the folio at the +* end edge may be freed and reused concurrently. +* __filemap_get_folio() looks up the straddler at +* aligned_end and returns it locked and ref'd with the +* mapping validated. */ - end = folio->index; -if (!folio_try_get (folio2)) + folio2 =__filemap_get_folio (folio->mapping, aligned_end, +FGP_LOCK |FGP_NOWAIT ,0 ); +if (IS_ERR (folio2)) { +/* +* No sub-folio straddles the boundary when aligned_end +* is empty so discarding up to it is safe. Otherwise +* the straddler is locked by someone else and we +* cannot obtain a reliable end position, so we fall +* back to folio->index. This is safe but may leave +* pages split off at the offset edge lingering in the +* page cache this round. +*/ +if (PTR_ERR (folio2) != -ENOENT ) + end = folio->index; goto out; - -if (folio2->mapping != folio->mapping || - !folio_test_large (folio2)) - goto out_put; - -if (!folio_trylock (folio2)) - goto out_put; - -if (page_folio (split_at2) != folio2) { -folio_unlock (folio2); - goto out_put; - } -if (!folio_test_large (folio2)) { - end = aligned_end; -folio_unlock (folio2); - goto out_put; } -/* Split failed: back off to the head of the straddler */ +/* Already at the minimum order, nothing to split */ +if (folio_order (folio2) == min_order) + goto out_put; + + split_at2 =folio_page (folio2, (aligned_end - folio2->index)); + +/* Split failed, keep the straddler intact */ if (folio_split_or_unmap (folio2, split_at2, min_order)) end = folio2->index; -else - end = aligned_end; -folio_unlock (folio2); out_put: +folio_unlock (folio2);folio_put (folio2); out:if (pend)
Re: [PATCH v3 1/3] mm/truncate: fix data loss when splitting straddling large folios fails
Quoted 206 lines · Zhang Yi
Quoted 140 lines · Zi Yan
Quoted 124 lines · Jan Kara
Quoted 65 lines · Zhang Yi
From: Zhang Yi <[email protected]>
truncate_inode_partial_folio()splits a large folio so that the caller's truncate loop can drop the in-range sub-folios while keeping the out-of-range tail. The first split at the punch start edge is non-uniform, which leaves the sub-folio at the truncation end edge as large as possible, this means it may still straddle the range, holding both zeroed in-range and valid out-of-range data. The function then attempts a second split at offset + length to isolate that tail.If the second split fails the straddling sub-folio stays merged. The function returned true unconditionally on all exit paths of the success block, telling the caller it was fully handled. The caller kept its default end and the truncate loop truncated every sub-folio below it, including the merged straddler, discarding the valid out-of-range tail.
For example, a 4-page order-2 folio punched from offset 0 to the middle of the last page:
truncate_inode_pages_range()truncate_inode_partial_folio() #same_folio== true 1st split at page0 -> [p0, p1, p2-3] # non-uniform, success folio2 = p2-3 # straddles: p2 zeroed, p3 tail valid 2nd split of folio2 fails / cannot lock
return true # BUG: caller keeps default end end = 3
loop truncates p0, p1, p2-3 # p3's valid tail is lostThis became reachable after commit
7460b470a131("mm/truncate: usefolio_split()in truncate operation") replaced the atomicsplit_folio()withfolio_split(), whose non-uniform split can partially split a folio and leave the end edge merged.It has gone unnoticed because a dirty large folio normally carries the filesystem's private data, for example
buffer_head, sofilemap_release_folio()->iomap_release_folio()returns false on a dirty folio andfolio_split()aborts with-EBUSYbefore any split, leaving the straddler safely unsplit. The bug is only reachable on paths that produce dirty large folios without filesystem private data, and it was caught on the upcoming ext4 iomap buffered I/O path when no ifs is attached.Rework the contract so the caller is told the page range to discard:
- Add
pgoff_t*pstart and *pend out-parameters that receive the page range fully covered by [lstart, lend] after any split (or none), i.e. the pages wholly within the range and safe to discard.- Adjust the ordering of the validate check when splitting folio2.
folio2->indexis only reliable after the reference count and lock have been successfully acquired, since it may have been split concurrently, or freed and recycled to an unrelated mapping. On any failure to obtain a reliable end position, fall back tofolio->index, which is safe but leaves the sub-folios split off at the offset edge in the page cache.- Rename the byte-range parameters start/end to lstart/lend to better express their semantics.
Callers in
truncate_inode_pages_range()andshmem_undo_range()pass &pstart for the folio at the start edge and &pend for the folio at the end edge, so the truncate loop drops exactly the fully covered pages and never touches a straddling folio that still holds valid out-of-range data.Quoted 4 lines
Suggested-by Brian Foster <[email protected]>Fixes 7460b470a131 ("mm/truncate: use folio_split() in truncate operation")Signed-off-by Zhang Yi <[email protected]>The changes mostly look good to me but I have some confusion around the folio2 splitting below.
Quoted 50 lines
(quoted diff) +10
-1@@ -259,32 +271,62 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end) * for shmem truncate */ struct folio *folio2; + pgoff_t end, aligned_end = (pos + offset + length) >> + PAGE_SHIFT; - if (offset + length == size) - goto no_split; + if (pstart) + *pstart = round_up(pos + offset, PAGE_SIZE) >> + PAGE_SHIFT; + + if (offset + length == size) { + end = aligned_end; + goto out; + } split_at2 = folio_page(folio, PAGE_ALIGN_DOWN(offset + length) / PAGE_SIZE); folio2 = page_folio(split_at2);+ /*
+ * folio2 may become stale due to a concurrent split or + * freeing, so validate it before and after taking its lock. + * If it fails, we can't get an accurate end position and fall + * back tofolio->index, which may leave sub-folios split off + * at the offset edge in the page cache this round.
+ */
+ end =folio->index;
if (!folio_try_get(folio2))
- gotono_split;
-
- if (!folio_test_large(folio2))
goto out;
+ if (folio2->mapping!=folio->mapping||
+ !folio_test_large(folio2))
+ gotoout_put;
+
if (!folio_trylock(folio2))
- goto out;
+ gotoout_put;
- /* make sure folio2 is large and does not change its mapping */ - if (folio_test_large(folio2)&&
-folio2->mapping==folio->mapping)
-folio_split_or_unmap(folio2, split_at2, min_order); + if (page_folio(split_at2)!= folio2) {
+folio_unlock(folio2);
+ gotoout_put;
+ }
+ if (!folio_test_large(folio2)) {
+ end =aligned_end;
+folio_unlock(folio2);Quoted 8 lines
Quoted 2 lines
+ goto
out_put;
+ }So I always found this folio2 lookup and revalidation somewhat suspicious and now that we're digging into it I'll ask: As you note in the changelog, by the time we compute
split_at2the page can be already freed and reused because it was split off from the original 'folio'. It can be for example a slab page or anything else. So is it guaranteed thatpage_folio()actuallyFor a slab or unrelated page,
folio->mappingcheck rejects them.Quoted 1 line
returns something sensible? What guarantees we properly detect the "reuse
No, but
folio_try_get()prevents non ref'd folios.Quoted 8 lines
Quoted 3 lines
for something else" case in all possible cases for which the page can be reused? I understand this is mostly a preexisting issue so maybe these questions are more for MM guys than you...
I agree with you that trying to split a unlocked and not ref'd folio2 is flaky. And it almost does a
__filemap_get_folio()like you proposed below.I think this is indeed a pre-existing issue, as Sashiko pointed out:
Quoted 18 lines
[Severity: Critical]
Does this speculative lookup handle the reallocation race correctly if the folio is reallocated to a different file offset?After the first split, the tail pages are added to the page cache and unlocked. During speculative lookup, the tail page could be concurrently reclaimed, freed, and reallocated as a new large folio in the same mapping but at a completely different file offset.
The validation checks earlier and the
page_foliocheck here will all pass because the physical pagesplit_at2is part of the new allocation.However, the file index of the folio is not verified. If this unrelated large folio fails to split, the fallback path assigns its index to end here:
if (
folio_split_or_unmap(folio2, split_at2, min_order)) end =folio2->index;Quoted 6 lines
This unrelated file offset is then returned to the caller via pend, which can cause the hole punch loop to truncate an unrelated segment of the file.
Should we verify that the file index of folio2 matches the expected index (e.g.
folio2->index+folio_page_idx(folio2, split_at2)==expected_index) before using it?the current mapping check on the folio2 and the folio !=
page_folio(split_at)check in__folio_split()are not able to catch this problem, which could then cause folio2 to be split at the wrong position. Does that sound right?Quoted 11 lines
Quoted 6 lines
So for me as an filesystem guy I'd appreciate some comment in this code explaining why grabbing folio2 this way is actually safe. The really safe way of getting to folio2 would be to use
__filemap_get_folio(mapping, (offset+length) >> PAGE_SHIFT, FGP_LOCK, 0)but I suppose we don't use the mapping lookup as it is more expensive?
__filemap_get_folio()is a better version of the existing folio2 finding code. When I wrote the code, I never thought about using__filemap_get_folio(), but I probably should have done it.Quoted 8 lines
BTW,
__filemap_get_folio(mapping, folio->index + (offset+length) >> PAGE_SHIFT, FGP_LOCK | FGP_NOWAIT, 0)
might be better:
1.folio->indexis needed to get the right folio2,
2. nowait can us nonblocking.Following your suggestion, I reworked my existing patch to use
__filemap_get_folio(), and it ends up looking roughly like the following(not tested yet). What do you think?
Quoted 7 lines
Besides, if the issue Sashiko pointed out does indeed exist, I can extract the
__filemap_get_folio()change into a separate patch to fix it on its own.Thanks,
Yi.
Sorry, the previous diff format was incorrect, reposting it.
mm/truncate.c +29 -34
@@ -279,51 +279,46 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart, *pstart =round_up (pos + offset, min_nrbytes) >>PAGE_SHIFT ; -if (offset + length == size) { - end = aligned_end; + end = aligned_end; +if (offset + length == size) goto out; - } - - split_at2 =folio_page (folio, -PAGE_ALIGN_DOWN (offset + length) /PAGE_SIZE ); - folio2 =page_folio (split_at2);/* -* folio2 may become stale due to a concurrent split or -* freeing, so validate it before and after taking its lock. -* If it fails, we can't get an accurate end position and fall -* back to folio->index, which may leave sub-folios split off -* at the offset edge in the page cache this round. +* After the first split at the start edge, the folio at the +* end edge may be freed and reused concurrently. +* __filemap_get_folio() looks up the straddler at +* aligned_end and returns it locked and ref'd with the +* mapping validated. */ - end = folio->index; -if (!folio_try_get (folio2)) + folio2 =__filemap_get_folio (folio->mapping, aligned_end, +FGP_LOCK |FGP_NOWAIT ,0 ); +if (IS_ERR (folio2)) { +/* +* No sub-folio straddles the boundary when aligned_end +* is empty so discarding up to it is safe. Otherwise +* the straddler is locked by someone else and we +* cannot obtain a reliable end position, so we fall +* back to folio->index. This is safe but may leave +* pages split off at the offset edge lingering in the +* page cache this round. +*/ +if (PTR_ERR (folio2) != -ENOENT ) + end = folio->index; goto out; - -if (folio2->mapping != folio->mapping || - !folio_test_large (folio2)) - goto out_put; - -if (!folio_trylock (folio2)) - goto out_put; - -if (page_folio (split_at2) != folio2) { -folio_unlock (folio2); - goto out_put; - } -if (!folio_test_large (folio2)) { - end = aligned_end; -folio_unlock (folio2); - goto out_put; } -/* Split failed: back off to the head of the straddler */ +/* Already at the minimum order, nothing to split */ +if (folio_order (folio2) == min_order) + goto out_put; + + split_at2 =folio_page (folio2, (aligned_end - folio2->index)); + +/* Split failed, keep the straddler intact */ if (folio_split_or_unmap (folio2, split_at2, min_order)) end = folio2->index; -else - end = aligned_end; -folio_unlock (folio2); out_put: +folio_unlock (folio2);folio_put (folio2); out:if (pend)
Jan Kara
maintainerRe: [PATCH v3 1/3] mm/truncate: fix data loss when splitting straddling large folios fails
Quoted 77 lines · Zhang Yi
Sorry, the previous diff format was incorrect, reposting it.
mm/truncate.c +28
-31@@ -279,51 +279,46 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart, *pstart =round_up (pos + offset, min_nrbytes) >>PAGE_SHIFT ; -if (offset + length == size) { - end = aligned_end; + end = aligned_end; +if (offset + length == size) goto out; - } - - split_at2 =folio_page (folio, -PAGE_ALIGN_DOWN (offset + length) /PAGE_SIZE ); - folio2 =page_folio (split_at2);/* -* folio2 may become stale due to a concurrent split or -* freeing, so validate it before and after taking its lock. -* If it fails, we can't get an accurate end position and fall -* back to folio->index, which may leave sub-folios split off -* at the offset edge in the page cache this round. +* After the first split at the start edge, the folio at the +* end edge may be freed and reused concurrently. +* __filemap_get_folio() looks up the straddler at +* aligned_end and returns it locked and ref'd with the +* mapping validated. */ - end = folio->index; -if (!folio_try_get (folio2)) + folio2 =__filemap_get_folio (folio->mapping, aligned_end, +FGP_LOCK |FGP_NOWAIT ,0 ); +if (IS_ERR (folio2)) { +/* +* No sub-folio straddles the boundary when aligned_end +* is empty so discarding up to it is safe. Otherwise +* the straddler is locked by someone else and we +* cannot obtain a reliable end position, so we fall +* back to folio->index. This is safe but may leave +* pages split off at the offset edge lingering in the +* page cache this round. +*/ +if (PTR_ERR (folio2) != -ENOENT ) + end = folio->index; goto out; - -if (folio2->mapping != folio->mapping || - !folio_test_large (folio2)) - goto out_put; - -if (!folio_trylock (folio2)) - goto out_put; - -if (page_folio (split_at2) != folio2) { -folio_unlock (folio2); - goto out_put; - } -if (!folio_test_large (folio2)) { - end = aligned_end; -folio_unlock (folio2); - goto out_put; } -/* Split failed: back off to the head of the straddler */ +/* Already at the minimum order, nothing to split */ +if (folio_order (folio2) == min_order) + goto out_put; + + split_at2 =folio_page (folio2, (aligned_end - folio2->index)); + +/* Split failed, keep the straddler intact */ if (folio_split_or_unmap (folio2, split_at2, min_order))
mm/truncate.c bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart, · line 324
Quoted 10 lines
mm/truncate.c +1
-3end = folio2->index; - else - end = aligned_end; -folio_unlock (folio2); out_put: +folio_unlock (folio2);folio_put (folio2); out:if (pend)
FWIW this looks much more understandable to me. And since this is a preexisting issue I agree this should be a separate patch.
Honza
Signature · 2 lines
Jan Kara <[email protected]> SUSE Labs, CR
Re: [PATCH v3 1/3] mm/truncate: fix data loss when splitting straddling large folios fails
Quoted 92 lines · Jan Kara
Quoted 77 lines · Zhang Yi
Sorry, the previous diff format was incorrect, reposting it.
mm/truncate.c +28
-31@@ -279,51 +279,46 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart, *pstart =round_up (pos + offset, min_nrbytes) >>PAGE_SHIFT ; -if (offset + length == size) { - end = aligned_end; + end = aligned_end; +if (offset + length == size) goto out; - } - - split_at2 =folio_page (folio, -PAGE_ALIGN_DOWN (offset + length) /PAGE_SIZE ); - folio2 =page_folio (split_at2);/* -* folio2 may become stale due to a concurrent split or -* freeing, so validate it before and after taking its lock. -* If it fails, we can't get an accurate end position and fall -* back to folio->index, which may leave sub-folios split off -* at the offset edge in the page cache this round. +* After the first split at the start edge, the folio at the +* end edge may be freed and reused concurrently. +* __filemap_get_folio() looks up the straddler at +* aligned_end and returns it locked and ref'd with the +* mapping validated. */ - end = folio->index; -if (!folio_try_get (folio2)) + folio2 =__filemap_get_folio (folio->mapping, aligned_end, +FGP_LOCK |FGP_NOWAIT ,0 ); +if (IS_ERR (folio2)) { +/* +* No sub-folio straddles the boundary when aligned_end +* is empty so discarding up to it is safe. Otherwise +* the straddler is locked by someone else and we +* cannot obtain a reliable end position, so we fall +* back to folio->index. This is safe but may leave +* pages split off at the offset edge lingering in the +* page cache this round. +*/ +if (PTR_ERR (folio2) != -ENOENT ) + end = folio->index; goto out; - -if (folio2->mapping != folio->mapping || - !folio_test_large (folio2)) - goto out_put; - -if (!folio_trylock (folio2)) - goto out_put; - -if (page_folio (split_at2) != folio2) { -folio_unlock (folio2); - goto out_put; - } -if (!folio_test_large (folio2)) { - end = aligned_end; -folio_unlock (folio2); - goto out_put; } -/* Split failed: back off to the head of the straddler */ +/* Already at the minimum order, nothing to split */ +if (folio_order (folio2) == min_order) + goto out_put; + + split_at2 =folio_page (folio2, (aligned_end - folio2->index)); + +/* Split failed, keep the straddler intact */ if (folio_split_or_unmap (folio2, split_at2, min_order))mm/truncate.c bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart, · line 324
Quoted 10 lines
mm/truncate.c +1
-3end = folio2->index; - else - end = aligned_end; -folio_unlock (folio2); out_put: +folio_unlock (folio2);folio_put (folio2); out:if (pend)FWIW this looks much more understandable to me. And since this is a preexisting issue I agree this should be a separate patch.
Quoted 1 line
Honza
Thank you for confirming. I will send out the next iteration after testing.
Thanks,
Yi.
Re: [PATCH v3 1/3] mm/truncate: fix data loss when splitting straddling large folios fails
In reply to Zhang YiQuoted 75 lines · Zhang Yi
From: Zhang Yi <[email protected]>
truncate_inode_partial_folio()splits a large folio so that the caller's truncate loop can drop the in-range sub-folios while keeping the out-of-range tail. The first split at the punch start edge is non-uniform, which leaves the sub-folio at the truncation end edge as large as possible, this means it may still straddle the range, holding both zeroed in-range and valid out-of-range data. The function then attempts a second split at offset + length to isolate that tail.If the second split fails the straddling sub-folio stays merged. The function returned true unconditionally on all exit paths of the success block, telling the caller it was fully handled. The caller kept its default end and the truncate loop truncated every sub-folio below it, including the merged straddler, discarding the valid out-of-range tail.
For example, a 4-page order-2 folio punched from offset 0 to the middle of the last page:
truncate_inode_pages_range()
truncate_inode_partial_folio()#same_folio== true
1st split at page0 -> [p0, p1, p2-3] # non-uniform, success
folio2 = p2-3 # straddles: p2 zeroed, p3 tail valid 2nd split of folio2 fails / cannot lock
return true # BUG: caller keeps default end
end = 3
loop truncates p0, p1, p2-3 # p3's valid tail is lostThis became reachable after commit
7460b470a131("mm/truncate: usefolio_split()in truncate operation") replaced the atomicsplit_folio()withfolio_split(), whose non-uniform split can partially split a folio and leave the end edge merged.It has gone unnoticed because a dirty large folio normally carries the filesystem's private data, for example
buffer_head, sofilemap_release_folio()->iomap_release_folio()returns false on a dirty folio andfolio_split()aborts with-EBUSYbefore any split, leaving the straddler safely unsplit. The bug is only reachable on paths that produce dirty large folios without filesystem private data, and it was caught on the upcoming ext4 iomap buffered I/O path when no ifs is attached.Rework the contract so the caller is told the page range to discard:
- Add
pgoff_t*pstart and *pend out-parameters that receive the page range fully covered by [lstart, lend] after any split (or none), i.e. the pages wholly within the range and safe to discard.- Adjust the ordering of the validate check when splitting folio2.
folio2->indexis only reliable after the reference count and lock have been successfully acquired, since it may have been split concurrently, or freed and recycled to an unrelated mapping. On any failure to obtain a reliable end position, fall back tofolio->index, which is safe but leaves the sub-folios split off at the offset edge in the page cache.- Rename the byte-range parameters start/end to lstart/lend to better express their semantics.
Callers in
truncate_inode_pages_range()andshmem_undo_range()pass &pstart for the folio at the start edge and &pend for the folio at the end edge, so the truncate loop drops exactly the fully covered pages and never touches a straddling folio that still holds valid out-of-range data.Suggested-by Brian Foster <[email protected]>Fixes 7460b470a131 ("mm/truncate: use folio_split() in truncate operation")Signed-off-by Zhang Yi <[email protected]>--- mm/internal.h | 4 +-- mm/shmem.c | 13 +++----- mm/truncate.c | 89 ++++++++++++++++++++++++++++++++++++--------------- 3 files changed, 71 insertions(+), 35 deletions(-)
...
Quoted 4 lines
mm/truncate.c +0
-0
...
Quoted 30 lines
mm/truncate.c +18
-2@@ -259,32 +271,62 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end)* for shmem truncate */ struct folio *folio2; +pgoff_t end, aligned_end = (pos + offset + length) >> +PAGE_SHIFT ; -if (offset + length == size) - goto no_split; +if (pstart) + *pstart =round_up (pos + offset,PAGE_SIZE ) >> +PAGE_SHIFT ; + +if (offset + length == size) { + end = aligned_end; + goto out; + } split_at2 =folio_page (folio,PAGE_ALIGN_DOWN (offset + length) /PAGE_SIZE ); folio2 =page_folio (split_at2); +/* +* folio2 may become stale due to a concurrent split or +* freeing, so validate it before and after taking its lock. +* If it fails, we can't get an accurate end position and fall +* back to folio->index, which may leave sub-folios split off +* at the offset edge in the page cache this round. +*/ + end = folio->index;
mm/truncate.c bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end) · line 304
Quoted 10 lines
mm/truncate.c +4
-3if (!folio_try_get (folio2)) - goto no_split; - -if (!folio_test_large (folio2)) goto out; +if (folio2->mapping != folio->mapping || + !folio_test_large (folio2)) + goto out_put; +
Hi Zhang,
The only thing that sticks out to me in this version is the !folio_test_large() check above. If we split (or something happens) such that folio2 is no longer large, wouldn't it be more likely to catch it here and fail to update end like we do in the same check a bit further down after the folio lock? Maybe I'm missing something here, but it seems a little odd for the same condition to return two possible states like this. Otherwise I like the changes you've made and the rest of the patch LGTM.
Brian
Quoted 63 lines
mm/truncate.c +24
-14if (!folio_trylock (folio2)) - goto out; + goto out_put; -/* make sure folio2 is large and does not change its mapping */ -if (folio_test_large (folio2) && - folio2->mapping == folio->mapping) -folio_split_or_unmap (folio2, split_at2, min_order); +if (page_folio (split_at2) != folio2) { +folio_unlock (folio2); + goto out_put; + } +if (!folio_test_large (folio2)) { + end = aligned_end; +folio_unlock (folio2); + goto out_put; + } + +/* Split failed: back off to the head of the straddler */ +if (folio_split_or_unmap (folio2, split_at2, min_order)) + end = folio2->index; +else + end = aligned_end;folio_unlock (folio2); -out: +out_put:folio_put (folio2); -no_split: +out: +if (pend) + *pend = end;return true; }if (folio_test_dirty (folio))@@ -413,11 +455,8 @@ void truncate_inode_pages_range(struct address_space *mapping, folio =__filemap_get_folio (mapping, lstart >>PAGE_SHIFT ,FGP_LOCK ,0 );if (!IS_ERR (folio)) { same_folio = lend <folio_next_pos (folio); -if (!truncate_inode_partial_folio (folio, lstart, lend)) { - start =folio_next_index (folio); -if (same_folio) - end = folio->index; - } +truncate_inode_partial_folio (folio, lstart, lend, &start, + same_folio ? &end :NULL );folio_unlock (folio);folio_put (folio); folio =NULL ;@@ -427,8 +466,8 @@ void truncate_inode_pages_range(struct address_space *mapping, folio =__filemap_get_folio (mapping, lend >>PAGE_SHIFT ,FGP_LOCK ,0 );if (!IS_ERR (folio)) { -if (!truncate_inode_partial_folio (folio, lstart, lend)) - end = folio->index; +truncate_inode_partial_folio (folio, lstart, lend, +NULL , &end);folio_unlock (folio);folio_put (folio); }Signature · 1 line
2.52.0
Re: [PATCH v3 1/3] mm/truncate: fix data loss when splitting straddling large folios fails
Quoted 134 lines · Brian Foster
Quoted 75 lines · Zhang Yi
From: Zhang Yi <[email protected]>
truncate_inode_partial_folio()splits a large folio so that the caller's truncate loop can drop the in-range sub-folios while keeping the out-of-range tail. The first split at the punch start edge is non-uniform, which leaves the sub-folio at the truncation end edge as large as possible, this means it may still straddle the range, holding both zeroed in-range and valid out-of-range data. The function then attempts a second split at offset + length to isolate that tail.If the second split fails the straddling sub-folio stays merged. The function returned true unconditionally on all exit paths of the success block, telling the caller it was fully handled. The caller kept its default end and the truncate loop truncated every sub-folio below it, including the merged straddler, discarding the valid out-of-range tail.
For example, a 4-page order-2 folio punched from offset 0 to the middle of the last page:
truncate_inode_pages_range()
truncate_inode_partial_folio()#same_folio== true
1st split at page0 -> [p0, p1, p2-3] # non-uniform, success
folio2 = p2-3 # straddles: p2 zeroed, p3 tail valid 2nd split of folio2 fails / cannot lock
return true # BUG: caller keeps default end
end = 3
loop truncates p0, p1, p2-3 # p3's valid tail is lostThis became reachable after commit
7460b470a131("mm/truncate: usefolio_split()in truncate operation") replaced the atomicsplit_folio()withfolio_split(), whose non-uniform split can partially split a folio and leave the end edge merged.It has gone unnoticed because a dirty large folio normally carries the filesystem's private data, for example
buffer_head, sofilemap_release_folio()->iomap_release_folio()returns false on a dirty folio andfolio_split()aborts with-EBUSYbefore any split, leaving the straddler safely unsplit. The bug is only reachable on paths that produce dirty large folios without filesystem private data, and it was caught on the upcoming ext4 iomap buffered I/O path when no ifs is attached.Rework the contract so the caller is told the page range to discard:
- Add
pgoff_t*pstart and *pend out-parameters that receive the page range fully covered by [lstart, lend] after any split (or none), i.e. the pages wholly within the range and safe to discard.- Adjust the ordering of the validate check when splitting folio2.
folio2->indexis only reliable after the reference count and lock have been successfully acquired, since it may have been split concurrently, or freed and recycled to an unrelated mapping. On any failure to obtain a reliable end position, fall back tofolio->index, which is safe but leaves the sub-folios split off at the offset edge in the page cache.- Rename the byte-range parameters start/end to lstart/lend to better express their semantics.
Callers in
truncate_inode_pages_range()andshmem_undo_range()pass &pstart for the folio at the start edge and &pend for the folio at the end edge, so the truncate loop drops exactly the fully covered pages and never touches a straddling folio that still holds valid out-of-range data.Suggested-by Brian Foster <[email protected]>Fixes 7460b470a131 ("mm/truncate: use folio_split() in truncate operation")Signed-off-by Zhang Yi <[email protected]>--- mm/internal.h | 4 +-- mm/shmem.c | 13 +++----- mm/truncate.c | 89 ++++++++++++++++++++++++++++++++++++--------------- 3 files changed, 71 insertions(+), 35 deletions(-)...
Quoted 4 lines
mm/truncate.c +0
-0...
Quoted 30 lines
mm/truncate.c +18
-2@@ -259,32 +271,62 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end)* for shmem truncate */ struct folio *folio2; +pgoff_t end, aligned_end = (pos + offset + length) >> +PAGE_SHIFT ; -if (offset + length == size) - goto no_split; +if (pstart) + *pstart =round_up (pos + offset,PAGE_SIZE ) >> +PAGE_SHIFT ; + +if (offset + length == size) { + end = aligned_end; + goto out; + } split_at2 =folio_page (folio,PAGE_ALIGN_DOWN (offset + length) /PAGE_SIZE ); folio2 =page_folio (split_at2); +/* +* folio2 may become stale due to a concurrent split or +* freeing, so validate it before and after taking its lock. +* If it fails, we can't get an accurate end position and fall +* back to folio->index, which may leave sub-folios split off +* at the offset edge in the page cache this round. +*/ + end = folio->index;mm/truncate.c bool truncate_inode_partial_folio(struct folio *folio, loff_t start, loff_t end) · line 304
Quoted 10 lines
mm/truncate.c +4
-3if (!folio_try_get (folio2)) - goto no_split; - -if (!folio_test_large (folio2)) goto out; +if (folio2->mapping != folio->mapping || + !folio_test_large (folio2)) + goto out_put; +Hi Zhang,
The only thing that sticks out to me in this version is the !folio_test_large() check above. If we split (or something happens) such that folio2 is no longer large, wouldn't it be more likely to catch it here and fail to update end like we do in the same check a bit further down after the folio lock? Maybe I'm missing something here, but it seems a little odd for the same condition to return two possible states like this. Otherwise I like the changes you've made and the rest of the patch LGTM.
Quoted 1 line
Brian
Yes, you're right! That check should be dropped, I got myself confused with all these complicated checks. Fortunately Jan and Zi Yan suggested using __filemap_get_folio(), and with that I think we can get rid of all these convoluted checks.
Thanks,
Yi.
Quoted 65 lines
Quoted 64 lines
mm/truncate.c +24
-14if (!folio_trylock (folio2)) - goto out; + goto out_put; -/* make sure folio2 is large and does not change its mapping */ -if (folio_test_large (folio2) && - folio2->mapping == folio->mapping) -folio_split_or_unmap (folio2, split_at2, min_order); +if (page_folio (split_at2) != folio2) { +folio_unlock (folio2); + goto out_put; + } +if (!folio_test_large (folio2)) { + end = aligned_end; +folio_unlock (folio2); + goto out_put; + } + +/* Split failed: back off to the head of the straddler */ +if (folio_split_or_unmap (folio2, split_at2, min_order)) + end = folio2->index; +else + end = aligned_end;folio_unlock (folio2); -out: +out_put:folio_put (folio2); -no_split: +out: +if (pend) + *pend = end;return true; }if (folio_test_dirty (folio))@@ -413,11 +455,8 @@ void truncate_inode_pages_range(struct address_space *mapping, folio =__filemap_get_folio (mapping, lstart >>PAGE_SHIFT ,FGP_LOCK ,0 );if (!IS_ERR (folio)) { same_folio = lend <folio_next_pos (folio); -if (!truncate_inode_partial_folio (folio, lstart, lend)) { - start =folio_next_index (folio); -if (same_folio) - end = folio->index; - } +truncate_inode_partial_folio (folio, lstart, lend, &start, + same_folio ? &end :NULL );folio_unlock (folio);folio_put (folio); folio =NULL ;@@ -427,8 +466,8 @@ void truncate_inode_pages_range(struct address_space *mapping, folio =__filemap_get_folio (mapping, lend >>PAGE_SHIFT ,FGP_LOCK ,0 );if (!IS_ERR (folio)) { -if (!truncate_inode_partial_folio (folio, lstart, lend)) - end = folio->index; +truncate_inode_partial_folio (folio, lstart, lend, +NULL , &end);folio_unlock (folio);folio_put (folio); }Signature · 1 line
2.52.0
PATCH v3 2/3 mm/truncate: align truncation boundaries to mapping minimum folio order
In reply to Zhang YiFrom: Zhang Yi <[email protected]>
When the mapping has a non-zero minimum folio order (min_order), folio_split() stops at min_order instead of order 0, so the sub-folio containing a split point stays aligned to 1 << min_order rather than to a single page. The original boundaries were based on page granularity, so either boundary could land inside the min_order chunk at its edge, and the truncation loop would drop that whole chunk, valid out-of-range tail included.
For example, a 64K (order-4) folio with min_order = 2 (16K) punched from offset 0 to 36K:
split @p0 -> [p0-p3, p4-p7, p8-p15] # non-uniform, min_order
folio2 = p8-p15 # straddles: p8 in range, p9-p15 tail valid
2nd split of folio2 -> [p8-p11, p12-p15] # success
end(old) = p9 # BUG: p9 inside [p8-p11]
loop truncates ... p8-p11 # p9-p11's valid tail is lost
It has gone unnoticed so far for two reasons. A non-zero min_order is only used by filesystems with a block or sector size larger than the page size, and those either always write back the affected range before punching a hole or truncating, or they carry filesystem private data on dirty folios (e.g. buffer_head), which makes filemap_release_folio() fail and folio_split() abort with -EBUSY, so the folio is never split and the old start/end boundaries remain valid. The bug only becomes reachable on paths that truncate dirty large folios without prior writeback and without filesystem private data, such as the upcoming ext4 iomap buffered I/O path.
Align both start (rounded up) and end (rounded down) to the mapping minimum folio order so they always fall on a folio boundary.
--- mm/truncate.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-)
mm/truncate.c +8 -6
@@ -213,8 +213,8 @@ static int folio_split_or_unmap(struct folio *folio, struct page *split_at,* * When @pstart and/or @pend are non-NULL they receive the indexes of the * page range fully covered by [lstart, lend] after any split (or none), -* i.e. the range of pages wholly within [lstart, lend] and so safe to -* discard. +* aligned inwards to min_order, i.e. the range of folios wholly within +* [lstart, lend] and so safe to discard. * * Returns false if splitting failed so the caller can avoid * discarding the entire folio which is stubbornly unsplit.
@@ -226,6 +226,7 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart,size_t size =folio_size (folio);unsigned int offset, length;struct page *split_at, *split_at2; +unsigned long min_nrbytes;unsigned int min_order;if (pos < lstart)
@@ -263,6 +264,7 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart,return true; min_order =mapping_min_folio_order (folio->mapping); + min_nrbytes =mapping_min_folio_nrbytes (folio->mapping); split_at =folio_page (folio,PAGE_ALIGN_DOWN (offset) /PAGE_SIZE );if (!folio_split_or_unmap (folio, split_at, min_order)) {/*
@@ -271,12 +273,12 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart,* for shmem truncate */ struct folio *folio2; -pgoff_t end, aligned_end = (pos + offset + length) >> -PAGE_SHIFT ; +pgoff_t end, aligned_end =round_down (pos + offset + length, + min_nrbytes) >>PAGE_SHIFT ;if (pstart) - *pstart =round_up (pos + offset,PAGE_SIZE ) >> -PAGE_SHIFT ; + *pstart =round_up (pos + offset, + min_nrbytes) >>PAGE_SHIFT ;if (offset + length == size) { end = aligned_end;
Signature · 1 line
2.52.0
[email protected]
AI reviewRe: [PATCH v3 2/3] mm/truncate: align truncation boundaries to mapping minimum folio order
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 13 lines
From: Zhang Yi <[email protected]>
When the mapping has a non-zero minimum folio order (
min_order),folio_split()stops atmin_orderinstead of order 0, so the sub-folio containing a split point stays aligned to 1 <<min_orderrather than to a single page. The original boundaries were based on page granularity, so either boundary could land inside themin_orderchunk at its edge, and the truncation loop would drop that whole chunk, valid out-of-range tail included.For example, a 64K (order-4) folio with
min_order= 2 (16K) punched from offset 0 to 36K:
Quoted 8 lines
split @p0 -> [p0-p3, p4-p7, p8-p15] # non-uniform,
min_order
folio2 = p8-p15 # straddles: p8 in range, p9-p15 tail valid
[ ... ]Reported-by Joanne Koong <[email protected]>Link https://lore.kernel.org/linux-mm/CAJnrk1bQYUe6+1ryyJur5EEnZYrC+_5AYsy=OWzVRgD4202y1g@mail.gmail.com/ open hereFixes e220917fa5077 ("mm: split a folio in minimum folio order chunks")Signed-off-by Zhang Yi <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Re: [PATCH v3 2/3] mm/truncate: align truncation boundaries to mapping minimum folio order
In reply to Zhang YiQuoted 33 lines · Zhang Yi
From: Zhang Yi <[email protected]>
When the mapping has a non-zero minimum folio order (
min_order),folio_split()stops atmin_orderinstead of order 0, so the sub-folio containing a split point stays aligned to 1 <<min_orderrather than to a single page. The original boundaries were based on page granularity, so either boundary could land inside themin_orderchunk at its edge, and the truncation loop would drop that whole chunk, valid out-of-range tail included.For example, a 64K (order-4) folio with
min_order= 2 (16K) punched from offset 0 to 36K:split @p0 -> [p0-p3, p4-p7, p8-p15] # non-uniform,
min_order
folio2 = p8-p15 # straddles: p8 in range, p9-p15 tail valid
2nd split of folio2 -> [p8-p11, p12-p15] # success
end(old) = p9 # BUG: p9 inside [p8-p11]
loop truncates ... p8-p11 # p9-p11's valid tail is lostIt has gone unnoticed so far for two reasons. A non-zero
min_orderis only used by filesystems with a block or sector size larger than the page size, and those either always write back the affected range before punching a hole or truncating, or they carry filesystem private data on dirty folios (e.g.buffer_head), which makesfilemap_release_folio()fail andfolio_split()abort with-EBUSY, so the folio is never split and the old start/end boundaries remain valid. The bug only becomes reachable on paths that truncate dirty large folios without prior writeback and without filesystem private data, such as the upcoming ext4 iomap buffered I/O path.Align both start (rounded up) and end (rounded down) to the mapping minimum folio order so they always fall on a folio boundary.
Quoted 8 lines
Reported-by Joanne Koong <[email protected]>Link https://lore.kernel.org/linux-mm/CAJnrk1bQYUe6+1ryyJur5EEnZYrC+_5AYsy=OWzVRgD4202y1g@mail.gmail.com/ open hereFixes e220917fa5077 ("mm: split a folio in minimum folio order chunks")Signed-off-by Zhang Yi <[email protected]>--- mm/truncate.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-)
This should be the first patch, since Fixes is older than the one in patch 1.
It can adjust start and end in truncate_inode_pages_range() instead, since shmem's min_order is always 0.
Something like below.
Am I missing anything? Thanks.
mm/truncate.c +5 -0
@@ -374,6 +374,7 @@ void truncate_inode_pages_range(struct address_space *mapping,int i;struct folio *folio;bool same_folio; +pgoff_t min_nrpages =mapping_min_folio_nrpages (mapping);if (mapping_empty (mapping))return ;
@@ -395,6 +396,10 @@ void truncate_inode_pages_range(struct address_space *mapping, else end = (lend +1 ) >>PAGE_SHIFT ; + start =round_up (start, min_nrpages); +if (end != (pgoff_t)-1 ) + end =round_down (end, min_nrpages); +folio_batch_init (&fbatch); index = start; while (index < end && find_lock_entries(mapping, &index, end - 1,
Signature · 2 lines
Best Regards, Yan, Zi
Re: [PATCH v3 2/3] mm/truncate: align truncation boundaries to mapping minimum folio order
Quoted 46 lines · Zi Yan
Quoted 33 lines · Zhang Yi
From: Zhang Yi <[email protected]>
When the mapping has a non-zero minimum folio order (
min_order),folio_split()stops atmin_orderinstead of order 0, so the sub-folio containing a split point stays aligned to 1 <<min_orderrather than to a single page. The original boundaries were based on page granularity, so either boundary could land inside themin_orderchunk at its edge, and the truncation loop would drop that whole chunk, valid out-of-range tail included.For example, a 64K (order-4) folio with
min_order= 2 (16K) punched from offset 0 to 36K:split @p0 -> [p0-p3, p4-p7, p8-p15] # non-uniform,
min_order
folio2 = p8-p15 # straddles: p8 in range, p9-p15 tail valid
2nd split of folio2 -> [p8-p11, p12-p15] # success
end(old) = p9 # BUG: p9 inside [p8-p11]
loop truncates ... p8-p11 # p9-p11's valid tail is lostIt has gone unnoticed so far for two reasons. A non-zero
min_orderis only used by filesystems with a block or sector size larger than the page size, and those either always write back the affected range before punching a hole or truncating, or they carry filesystem private data on dirty folios (e.g.buffer_head), which makesfilemap_release_folio()fail andfolio_split()abort with-EBUSY, so the folio is never split and the old start/end boundaries remain valid. The bug only becomes reachable on paths that truncate dirty large folios without prior writeback and without filesystem private data, such as the upcoming ext4 iomap buffered I/O path.Align both start (rounded up) and end (rounded down) to the mapping minimum folio order so they always fall on a folio boundary.
Quoted 8 lines
Reported-by Joanne Koong <[email protected]>Link https://lore.kernel.org/linux-mm/CAJnrk1bQYUe6+1ryyJur5EEnZYrC+_5AYsy=OWzVRgD4202y1g@mail.gmail.com/ open hereFixes e220917fa5077 ("mm: split a folio in minimum folio order chunks")Signed-off-by Zhang Yi <[email protected]>--- mm/truncate.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-)This should be the first patch, since Fixes is older than the one in patch 1.
Quoted 6 lines
It can adjust start and end in
truncate_inode_pages_range()instead, since shmem'smin_orderis always 0.Something like below.
Am I missing anything? Thanks.
Yeah, this makes sense to me, thanks for your suggestion.
Yi.
Quoted 25 lines
mm/truncate.c +5
-0@@ -374,6 +374,7 @@ void truncate_inode_pages_range(struct address_space *mapping,int i;struct folio *folio;bool same_folio; +pgoff_t min_nrpages =mapping_min_folio_nrpages (mapping);if (mapping_empty (mapping))return ;@@ -395,6 +396,10 @@ void truncate_inode_pages_range(struct address_space *mapping, else end = (lend +1 ) >>PAGE_SHIFT ; + start =round_up (start, min_nrpages); +if (end != (pgoff_t)-1 ) + end =round_down (end, min_nrpages); +folio_batch_init (&fbatch); index = start; while (index < end && find_lock_entries(mapping, &index, end - 1,
PATCH v3 3/3 mm/truncate: clarify return value of truncate_inode_partial_folio()
In reply to Zhang YiFrom: Zhang Yi <[email protected]>
With the earlier rework the callers no longer rely on the return value of truncate_inode_partial_folio() to decide whether to adjust the truncation range. The pstart/pend out-parameters carry that information instead. The callers now only use the return value as a flag indicating whether the loop should be reset to pick up newly split sub-folios on the shmem path.
Return true if at least one split succeeded, and false otherwise. This clarifies the existing confusing return value semantics.
--- mm/truncate.c | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-)
mm/truncate.c +6 -8
@@ -216,8 +216,7 @@ static int folio_split_or_unmap(struct folio *folio, struct page *split_at,* aligned inwards to min_order, i.e. the range of folios wholly within * [lstart, lend] and so safe to discard. * -* Returns false if splitting failed so the caller can avoid -* discarding the entire folio which is stubbornly unsplit. +* Return %true if at least one split succeeded, %false otherwise. */ bool truncate_inode_partial_folio (struct folio *folio,loff_t lstart,loff_t lend,pgoff_t *pstart,pgoff_t *pend)
@@ -247,7 +246,7 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart,folio_wait_writeback (folio);if (length == size) {truncate_inode_folio (folio->mapping, folio); -return true; +return false; }/*
@@ -261,7 +260,7 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart,if (folio_needs_release (folio))folio_invalidate (folio, offset, length);if (!folio_test_large (folio)) -return true; +return false; min_order =mapping_min_folio_order (folio->mapping); min_nrbytes =mapping_min_folio_nrbytes (folio->mapping);
@@ -331,10 +330,9 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart, *pend = end;return true; } -if (folio_test_dirty (folio)) -return false; -truncate_inode_folio (folio->mapping, folio); -return true; +if (!folio_test_dirty (folio)) +truncate_inode_folio (folio->mapping, folio); +return false; }/*
Signature · 1 line
2.52.0
[email protected]
AI reviewRe: [PATCH v3 3/3] mm/truncate: clarify return value of truncate_inode_partial_folio()
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] mm: sub-folio page cache leak due to incorrect end boundary on split failure --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] mm: sub-folio page cache leak due to incorrect end boundary on split failure --
commit 4bfa9d8fcd26bcd7a9625b0b4e4d07b1e0a6b145
Author: Zhang Yi <[email protected]>
mm/truncate: clarify return value of truncate_inode_partial_folio()
This commit updates truncate_inode_partial_folio() to clarify its return value semantics. Callers now use the return value strictly as a flag for loop resetting, and rely instead on the pstart and pend out-parameters to decide whether to adjust the truncation range.
Quoted 4 lines
mm/truncate.c +0
-0
[ ... ]
mm/truncate.c bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart, · line 332
Quoted 4 lines
mm/truncate.c +0
-0@@ -331,10 +330,9 @@ bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart, *pend = end;return true; }
[Severity: High]
With the new caller dependency on pstart and pend instead of the return value, can this error path cause a sub-folio page cache leak?
If truncate_inode_partial_folio() is called for a range within a single large folio, and the first split succeeds, *pstart is advanced. If the second split attempt fails early during folio2 validation, the code behaves as follows:
mm/truncate.c:truncate_inode_partial_folio() {
...
end = folio->index;
if (!folio_try_get(folio2))
goto out;
...
out:
if (pend)
*pend = end;
return true;
}Does this set *pend backward to the start of the original large folio?
If this results in a situation where *pstart is greater than *pend, will the caller bypass its discard loop entirely? This seems like it could permanently leak all successfully split sub-folios in the range within the page cache. For hole punches, could this result in reading stale data instead of zeros?
Quoted 10 lines
mm/truncate.c +3
-4-if (folio_test_dirty (folio)) -return false; -truncate_inode_folio (folio->mapping, folio); -return true; +if (!folio_test_dirty (folio)) +truncate_inode_folio (folio->mapping, folio); +return false; }/*
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3