Re: [PATCH v2] mm/memory: mark unshare copies dirty to fix MADV_FREE data loss

From: David Hildenbrand (Arm)

Date: Tue Nov 17 2026 - 05:16:17 EST


On 11/17/26 11:06, Daniel Wade wrote:

Please don't send out stuff that fast, especially when the discussion is not
over yet.

> wp_page_copy() only calls pte_mkdirty() for write faults, so the copy it
> makes for FAULT_FLAG_UNSHARE comes out clean. Nothing marks the folio
> dirty either and there is no swap entry.
>
> Unshare faults come from R/O GUP pins, like process_vm_readv() on a page
> shared with a child. If the process forks after the pin is gone,
> MADV_FREE in one of them marks the folio lazyfree and reclaim frees it.
> The other process then reads zeroes.
>
> Mark the copy's PTE dirty. pte_mkdirty() also sets soft-dirty on x86, so
> take soft-dirty from the old PTE in both directions.
>
> Side effect: smaps and numa_maps count an unshare copy as Private_Dirty
> or Shared_Dirty rather than _Clean.

numa_maps still doesn't expose Private_Dirty or Shared_Dirty. So this should
probably be be

Side effect: smaps counts an unshare copy as Private_Dirty
or Shared_Dirty, and numa_maps indicates it as dirty.

>
> Fixes: c89357e27f20 ("mm: support GUP-triggered unsharing of anonymous pages")
> Suggested-by: David Hildenbrand (Arm) <david@xxxxxxxxxx>
> Cc: stable@xxxxxxxxxxxxxxx
> Signed-off-by: Daniel Wade <danjwade95@xxxxxxxxx>
> ---
> v2: set the PTE dirty instead of the folio, as David suggested. No atomic,
> and the dirty bit then also survives in the other mappings.
> v1: https://lore.kernel.org/all/20261116111245.28871-1-danjwade95@xxxxxxxxx/
>
> Tested on mainline b3dfbde62cf1, x86-64 with KASAN and PROVE_LOCKING, as
> uid 65534. The test gives an unshare copy to a child, has the parent
> MADV_FREE it and a control page it alone maps, then waits for reclaim.
> Without the patch all 4096 bytes come back wrong in the child; with it the
> child's page is intact and the control page is still discarded. Same on
> v6.12.117.
>
> mm/memory.c | 3 +++
> 1 file changed, 3 insertions(+)
>
> diff --git a/mm/memory.c b/mm/memory.c
> index ec3d9d99ccee..113b305854d5 100644
> --- a/mm/memory.c
> +++ b/mm/memory.c
> @@ -4130,8 +4130,11 @@ static vm_fault_t wp_page_copy(struct vm_fault *vmf)
> entry = folio_mk_pte(new_folio, vma->vm_page_prot);
> entry = pte_sw_mkyoung(entry);
> if (unlikely(unshare)) {
> + entry = pte_mkdirty(entry);
> if (pte_soft_dirty(vmf->orig_pte))
> entry = pte_mksoft_dirty(entry);
> + else
> + entry = pte_clear_soft_dirty(entry);
> if (pte_uffd(vmf->orig_pte)) {
> entry = pte_mkuffd(entry);
> if (userfaultfd_rwp(vma))

Apart from that LGTM

Reviewed-by: David Hildenbrand (Arm) <david@xxxxxxxxxx>


I'll wait for more review before picking this up.

--
Cheers,

David