Re: [PATCH] btrfs: don't invalidate beyond-EOF folios without private in extent_writepage()
From: Qu Wenruo
Date: Tue Dec 01 2026 - 22:56:08 EST
在 2026/12/2 14:04, Brahmajit Das 写道:
On 2026/12/2 Qu Wenruo wrote:
Agreed, that's better. For v2 I'm thinking of making btrfs_release_folio()
refuse to release while folio_maybe_dma_pinned(),
Would that race? E.g. at the time of btrfs_release_folio(), the folio is
not yet pinned, but after the check, GUP pinned the folio, resulting the
same folio private cleared problem.
I don't think a new pin can cause it. btrfs_release_folio() only
releases a locked, clean folio. A clean folio of a shared mapping has
all its PTEs write-protected (folio_mkclean() at writeback), so a new
FOLL_WRITE pin, the only kind that re-dirties the folio when released,
has to take the write fault -> btrfs_page_mkwrite(), which locks the
folio and does set_folio_extent_mapped() before the pin completes.
GUP-fast doesn't bypass this either, since it requires
pte_access_permitted(pte, FOLL_WRITE).
The real gap is that folio_maybe_dma_pinned() only catches FOLL_PIN.
Legacy get_user_pages() + set_page_dirty_lock() users would still
re-dirty a folio after its private was released. So I agree the check
isn't enough on its own.
I'm wondering if we can re-attach the private structure during
btrfs_data_dirty_folio() to close the loop?
That looks more complete to me: it covers FOLL_GET users and the
beyond-EOF folio invalidated by extent_writepage(). Some constraints
I see:
- ->dirty_folio() can't fail and may be called in atomic context, so
the allocation has to be GFP_NOWAIT. (For the PTE lock caller the
folio is already dirty, so private should already be there.)
- btrfs_alloc_folio_state() returns zeroed bitmaps, so for an uptodate
folio we'd need to fill the uptodate bitmap before marking blocks
dirty/fixup.
If the folio has its private removed, can it still be uptodate?
That folio should be invalidated, thus I think it should not be uptodate either.
- If the allocation fails we still need a fallback. Writeback can
sleep, so I'd make extent_writepage() attach private with GFP_NOFS
before the beyond-EOF check, so btrfs_invalidate_folio() always sees
it there.
So for v2 I plan to:
1) attach private in btrfs_data_dirty_folio() if missing, including
for folios beyond EOF;
2) attach private in extent_writepage() before the EOF check as the
fallback, instead of skipping folio_invalidate() as v1 did.
If that only affects folio_invalidate() call, I think you can add do the attach inside that beyond EOF branch, so it won't affect the existing unexpected dirty folio check.
Sorry I'm not an expert in the GUP part, although it sounds fine to me, some review from others would definitely help.
Does that sound reasonable? For the in-EOF case with a failed
allocation, I'm not sure how best to record the fixup without the
bitmap. Treating the whole folio as needing fixup would be simplest,
if you're fine with that.
Thanks,
Brahmajit