[v4,3/3] mm: Batch-zap large anonymous folio PTE mappings

Message ID 20230727141837.3386072-4-ryan.roberts@arm.com
State New
Headers
Series Optimize large folio interaction with deferred split |

Commit Message

Ryan Roberts July 27, 2023, 2:18 p.m. UTC
  This allows batching the rmap removal with folio_remove_rmap_range(),
which means we avoid spuriously adding a partially unmapped folio to the
deferred split queue in the common case, which reduces split queue lock
contention.

Previously each page was removed from the rmap individually with
page_remove_rmap(). If the first page belonged to a large folio, this
would cause page_remove_rmap() to conclude that the folio was now
partially mapped and add the folio to the deferred split queue. But
subsequent calls would cause the folio to become fully unmapped, meaning
there is no value to adding it to the split queue.

A complicating factor is that for platforms where MMU_GATHER_NO_GATHER
is enabled (e.g. s390), __tlb_remove_page() drops a reference to the
page. This means that the folio reference count could drop to zero while
still in use (i.e. before folio_remove_rmap_range() is called). This
does not happen on other platforms because the actual page freeing is
deferred.

Solve this by appropriately getting/putting the folio to guarrantee it
does not get freed early. Given the need to get/put the folio in the
batch path, we stick to the non-batched path if the folio is not large.
While the batched path is functionally correct for a folio with 1 page,
it is unlikely to be as efficient as the existing non-batched path in
this case.

Signed-off-by: Ryan Roberts <ryan.roberts@arm.com>
---
 mm/memory.c | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 132 insertions(+)
  

Comments

Yu Zhao July 27, 2023, 5:22 p.m. UTC | #1
On Thu, Jul 27, 2023 at 8:18 AM Ryan Roberts <ryan.roberts@arm.com> wrote:
>
> This allows batching the rmap removal with folio_remove_rmap_range(),
> which means we avoid spuriously adding a partially unmapped folio to the
> deferred split queue in the common case, which reduces split queue lock
> contention.
>
> Previously each page was removed from the rmap individually with
> page_remove_rmap(). If the first page belonged to a large folio, this
> would cause page_remove_rmap() to conclude that the folio was now
> partially mapped and add the folio to the deferred split queue. But
> subsequent calls would cause the folio to become fully unmapped, meaning
> there is no value to adding it to the split queue.
>
> A complicating factor is that for platforms where MMU_GATHER_NO_GATHER
> is enabled (e.g. s390), __tlb_remove_page() drops a reference to the
> page. This means that the folio reference count could drop to zero while
> still in use (i.e. before folio_remove_rmap_range() is called). This
> does not happen on other platforms because the actual page freeing is
> deferred.
>
> Solve this by appropriately getting/putting the folio to guarrantee it
> does not get freed early. Given the need to get/put the folio in the
> batch path, we stick to the non-batched path if the folio is not large.
> While the batched path is functionally correct for a folio with 1 page,
> it is unlikely to be as efficient as the existing non-batched path in
> this case.
>
> Signed-off-by: Ryan Roberts <ryan.roberts@arm.com>

This ad hoc patch looks unacceptable to me: we can't afford to keep
adding special cases.

I vote for completely converting zap_pte_range() to use
folio_remove_rmap_range(), and that includes tlb_flush_rmap_batch()
and other types of large folios, not just anon. Otherwise I'll leave
it to Matthew and David.
  
Ryan Roberts July 28, 2023, 9:16 a.m. UTC | #2
On 27/07/2023 18:22, Yu Zhao wrote:
> On Thu, Jul 27, 2023 at 8:18 AM Ryan Roberts <ryan.roberts@arm.com> wrote:
>>
>> This allows batching the rmap removal with folio_remove_rmap_range(),
>> which means we avoid spuriously adding a partially unmapped folio to the
>> deferred split queue in the common case, which reduces split queue lock
>> contention.
>>
>> Previously each page was removed from the rmap individually with
>> page_remove_rmap(). If the first page belonged to a large folio, this
>> would cause page_remove_rmap() to conclude that the folio was now
>> partially mapped and add the folio to the deferred split queue. But
>> subsequent calls would cause the folio to become fully unmapped, meaning
>> there is no value to adding it to the split queue.
>>
>> A complicating factor is that for platforms where MMU_GATHER_NO_GATHER
>> is enabled (e.g. s390), __tlb_remove_page() drops a reference to the
>> page. This means that the folio reference count could drop to zero while
>> still in use (i.e. before folio_remove_rmap_range() is called). This
>> does not happen on other platforms because the actual page freeing is
>> deferred.
>>
>> Solve this by appropriately getting/putting the folio to guarrantee it
>> does not get freed early. Given the need to get/put the folio in the
>> batch path, we stick to the non-batched path if the folio is not large.
>> While the batched path is functionally correct for a folio with 1 page,
>> it is unlikely to be as efficient as the existing non-batched path in
>> this case.
>>
>> Signed-off-by: Ryan Roberts <ryan.roberts@arm.com>
> 
> This ad hoc patch looks unacceptable to me: we can't afford to keep
> adding special cases.
> 
> I vote for completely converting zap_pte_range() to use
> folio_remove_rmap_range(), and that includes tlb_flush_rmap_batch()
> and other types of large folios, not just anon. 

The intent of the change is to avoid the deferred split queue lock contention,
and this is only a problem for anon folios; page cache folios are never split in
this way. My intention was to do the smallest change to solve the problem. I
don't see the value in reworking a much bigger piece of the code, making it more
complex, when its not going to give any clear perf benefits.


Otherwise I'll leave
> it to Matthew and David.

If there is concensus that this is _required_ in order to merge this series,
then I guess I'll bite the bullet and do it. But my preference is to leave it
for if/when a reason is found that it is actually bringing benefit.
  
Yu Zhao Aug. 1, 2023, 7:12 a.m. UTC | #3
On Fri, Jul 28, 2023 at 3:16 AM Ryan Roberts <ryan.roberts@arm.com> wrote:
>
> On 27/07/2023 18:22, Yu Zhao wrote:
> > On Thu, Jul 27, 2023 at 8:18 AM Ryan Roberts <ryan.roberts@arm.com> wrote:
> >>
> >> This allows batching the rmap removal with folio_remove_rmap_range(),
> >> which means we avoid spuriously adding a partially unmapped folio to the
> >> deferred split queue in the common case, which reduces split queue lock
> >> contention.
> >>
> >> Previously each page was removed from the rmap individually with
> >> page_remove_rmap(). If the first page belonged to a large folio, this
> >> would cause page_remove_rmap() to conclude that the folio was now
> >> partially mapped and add the folio to the deferred split queue. But
> >> subsequent calls would cause the folio to become fully unmapped, meaning
> >> there is no value to adding it to the split queue.
> >>
> >> A complicating factor is that for platforms where MMU_GATHER_NO_GATHER
> >> is enabled (e.g. s390), __tlb_remove_page() drops a reference to the
> >> page. This means that the folio reference count could drop to zero while
> >> still in use (i.e. before folio_remove_rmap_range() is called). This
> >> does not happen on other platforms because the actual page freeing is
> >> deferred.
> >>
> >> Solve this by appropriately getting/putting the folio to guarrantee it
> >> does not get freed early. Given the need to get/put the folio in the
> >> batch path, we stick to the non-batched path if the folio is not large.
> >> While the batched path is functionally correct for a folio with 1 page,
> >> it is unlikely to be as efficient as the existing non-batched path in
> >> this case.
> >>
> >> Signed-off-by: Ryan Roberts <ryan.roberts@arm.com>
> >
> > This ad hoc patch looks unacceptable to me: we can't afford to keep
> > adding special cases.
> >
> > I vote for completely converting zap_pte_range() to use
> > folio_remove_rmap_range(), and that includes tlb_flush_rmap_batch()
> > and other types of large folios, not just anon.
>
> The intent of the change is to avoid the deferred split queue lock contention
> and this is only a problem for anon folios;

This reasoning seems wrong to me: if the goal was to fix the lock
contention, the fix should have been in deferred_split_folio().

> page cache folios are never split in
> this way.

The goal I see here is to enlighten zap_pte_range() with batch
operations on folios.

> My intention was to do the smallest change to solve the problem.

I understand the desire. But we can't do this at the cost of making
the codebase harder to maintain.

> I
> don't see the value in reworking a much bigger piece of the code, making it more
> complex, when its not going to give any clear perf benefits.

"Much bigger ... more complex": I'm not sure how you get this
impression. Have you tried to do it already or is it just a gut
feeling?

Supporting other types of large folios, not just anon, actually makes
it simpler!

> Otherwise I'll leave
> > it to Matthew and David.
>
> If there is concensus that this is _required_ in order to merge this series,
> then I guess I'll bite the bullet and do it. But my preference is to leave it
> for if/when a reason is found that it is actually bringing benefit.

There is a clear reason here: this patch is *half-baked* because it
doesn't handle tlb_flush_rmap_batch().
  
David Hildenbrand Aug. 3, 2023, 1:38 p.m. UTC | #4
On 27.07.23 16:18, Ryan Roberts wrote:
> This allows batching the rmap removal with folio_remove_rmap_range(),
> which means we avoid spuriously adding a partially unmapped folio to the
> deferred split queue in the common case, which reduces split queue lock
> contention.
> 
> Previously each page was removed from the rmap individually with
> page_remove_rmap(). If the first page belonged to a large folio, this
> would cause page_remove_rmap() to conclude that the folio was now
> partially mapped and add the folio to the deferred split queue. But
> subsequent calls would cause the folio to become fully unmapped, meaning
> there is no value to adding it to the split queue.
> 
> A complicating factor is that for platforms where MMU_GATHER_NO_GATHER
> is enabled (e.g. s390), __tlb_remove_page() drops a reference to the
> page. This means that the folio reference count could drop to zero while
> still in use (i.e. before folio_remove_rmap_range() is called). This
> does not happen on other platforms because the actual page freeing is
> deferred.
> 
> Solve this by appropriately getting/putting the folio to guarrantee it
> does not get freed early. Given the need to get/put the folio in the
> batch path, we stick to the non-batched path if the folio is not large.
> While the batched path is functionally correct for a folio with 1 page,
> it is unlikely to be as efficient as the existing non-batched path in
> this case.
> 
> Signed-off-by: Ryan Roberts <ryan.roberts@arm.com>
> ---
>   mm/memory.c | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++
>   1 file changed, 132 insertions(+)
> 
> diff --git a/mm/memory.c b/mm/memory.c
> index 01f39e8144ef..d35bd8d2b855 100644
> --- a/mm/memory.c
> +++ b/mm/memory.c
> @@ -1391,6 +1391,99 @@ zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,
>   	pte_install_uffd_wp_if_needed(vma, addr, pte, pteval);
>   }
>   
> +static inline unsigned long page_cont_mapped_vaddr(struct page *page,
> +				struct page *anchor, unsigned long anchor_vaddr)
> +{
> +	unsigned long offset;
> +	unsigned long vaddr;
> +
> +	offset = (page_to_pfn(page) - page_to_pfn(anchor)) << PAGE_SHIFT;
> +	vaddr = anchor_vaddr + offset;
> +
> +	if (anchor > page) {
> +		if (vaddr > anchor_vaddr)
> +			return 0;
> +	} else {
> +		if (vaddr < anchor_vaddr)
> +			return ULONG_MAX;
> +	}
> +
> +	return vaddr;
> +}
> +
> +static int folio_nr_pages_cont_mapped(struct folio *folio,
> +				      struct page *page, pte_t *pte,
> +				      unsigned long addr, unsigned long end)
> +{
> +	pte_t ptent;
> +	int floops;
> +	int i;
> +	unsigned long pfn;
> +	struct page *folio_end;
> +
> +	if (!folio_test_large(folio))
> +		return 1;
> +
> +	folio_end = &folio->page + folio_nr_pages(folio);
> +	end = min(page_cont_mapped_vaddr(folio_end, page, addr), end);
> +	floops = (end - addr) >> PAGE_SHIFT;
> +	pfn = page_to_pfn(page);
> +	pfn++;
> +	pte++;
> +
> +	for (i = 1; i < floops; i++) {
> +		ptent = ptep_get(pte);
> +
> +		if (!pte_present(ptent) || pte_pfn(ptent) != pfn)
> +			break;
> +
> +		pfn++;
> +		pte++;
> +	}
> +
> +	return i;
> +}
> +
> +static unsigned long try_zap_anon_pte_range(struct mmu_gather *tlb,
> +					    struct vm_area_struct *vma,
> +					    struct folio *folio,
> +					    struct page *page, pte_t *pte,
> +					    unsigned long addr, int nr_pages,
> +					    struct zap_details *details)
> +{
> +	struct mm_struct *mm = tlb->mm;
> +	pte_t ptent;
> +	bool full;
> +	int i;
> +
> +	/* __tlb_remove_page may drop a ref; prevent going to 0 while in use. */
> +	folio_get(folio);

Is there no way around that? It feels wrong and IMHO a bit ugly.

With this patch, you'll might suddenly have mapcount > refcount for a 
folio, or am I wrong?

> +
> +	for (i = 0; i < nr_pages;) {
> +		ptent = ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm);
> +		tlb_remove_tlb_entry(tlb, pte, addr);
> +		zap_install_uffd_wp_if_needed(vma, addr, pte, details, ptent);
> +		full = __tlb_remove_page(tlb, page, 0);
> +
> +		if (unlikely(page_mapcount(page) < 1))
> +			print_bad_pte(vma, addr, ptent, page);

Can we avoid new users of page_mapcount() outside rmap code, please? :)
  
David Hildenbrand Aug. 3, 2023, 1:50 p.m. UTC | #5
On 03.08.23 15:38, David Hildenbrand wrote:
> On 27.07.23 16:18, Ryan Roberts wrote:
>> This allows batching the rmap removal with folio_remove_rmap_range(),
>> which means we avoid spuriously adding a partially unmapped folio to the
>> deferred split queue in the common case, which reduces split queue lock
>> contention.
>>
>> Previously each page was removed from the rmap individually with
>> page_remove_rmap(). If the first page belonged to a large folio, this
>> would cause page_remove_rmap() to conclude that the folio was now
>> partially mapped and add the folio to the deferred split queue. But
>> subsequent calls would cause the folio to become fully unmapped, meaning
>> there is no value to adding it to the split queue.
>>
>> A complicating factor is that for platforms where MMU_GATHER_NO_GATHER
>> is enabled (e.g. s390), __tlb_remove_page() drops a reference to the
>> page. This means that the folio reference count could drop to zero while
>> still in use (i.e. before folio_remove_rmap_range() is called). This
>> does not happen on other platforms because the actual page freeing is
>> deferred.
>>
>> Solve this by appropriately getting/putting the folio to guarrantee it
>> does not get freed early. Given the need to get/put the folio in the
>> batch path, we stick to the non-batched path if the folio is not large.
>> While the batched path is functionally correct for a folio with 1 page,
>> it is unlikely to be as efficient as the existing non-batched path in
>> this case.
>>
>> Signed-off-by: Ryan Roberts <ryan.roberts@arm.com>
>> ---
>>    mm/memory.c | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++
>>    1 file changed, 132 insertions(+)
>>
>> diff --git a/mm/memory.c b/mm/memory.c
>> index 01f39e8144ef..d35bd8d2b855 100644
>> --- a/mm/memory.c
>> +++ b/mm/memory.c
>> @@ -1391,6 +1391,99 @@ zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,
>>    	pte_install_uffd_wp_if_needed(vma, addr, pte, pteval);
>>    }
>>    
>> +static inline unsigned long page_cont_mapped_vaddr(struct page *page,
>> +				struct page *anchor, unsigned long anchor_vaddr)
>> +{
>> +	unsigned long offset;
>> +	unsigned long vaddr;
>> +
>> +	offset = (page_to_pfn(page) - page_to_pfn(anchor)) << PAGE_SHIFT;
>> +	vaddr = anchor_vaddr + offset;
>> +
>> +	if (anchor > page) {
>> +		if (vaddr > anchor_vaddr)
>> +			return 0;
>> +	} else {
>> +		if (vaddr < anchor_vaddr)
>> +			return ULONG_MAX;
>> +	}
>> +
>> +	return vaddr;
>> +}
>> +
>> +static int folio_nr_pages_cont_mapped(struct folio *folio,
>> +				      struct page *page, pte_t *pte,
>> +				      unsigned long addr, unsigned long end)
>> +{
>> +	pte_t ptent;
>> +	int floops;
>> +	int i;
>> +	unsigned long pfn;
>> +	struct page *folio_end;
>> +
>> +	if (!folio_test_large(folio))
>> +		return 1;
>> +
>> +	folio_end = &folio->page + folio_nr_pages(folio);
>> +	end = min(page_cont_mapped_vaddr(folio_end, page, addr), end);
>> +	floops = (end - addr) >> PAGE_SHIFT;
>> +	pfn = page_to_pfn(page);
>> +	pfn++;
>> +	pte++;
>> +
>> +	for (i = 1; i < floops; i++) {
>> +		ptent = ptep_get(pte);
>> +
>> +		if (!pte_present(ptent) || pte_pfn(ptent) != pfn)
>> +			break;
>> +
>> +		pfn++;
>> +		pte++;
>> +	}
>> +
>> +	return i;
>> +}
>> +
>> +static unsigned long try_zap_anon_pte_range(struct mmu_gather *tlb,
>> +					    struct vm_area_struct *vma,
>> +					    struct folio *folio,
>> +					    struct page *page, pte_t *pte,
>> +					    unsigned long addr, int nr_pages,
>> +					    struct zap_details *details)
>> +{
>> +	struct mm_struct *mm = tlb->mm;
>> +	pte_t ptent;
>> +	bool full;
>> +	int i;
>> +
>> +	/* __tlb_remove_page may drop a ref; prevent going to 0 while in use. */
>> +	folio_get(folio);
> 
> Is there no way around that? It feels wrong and IMHO a bit ugly.
> 
> With this patch, you'll might suddenly have mapcount > refcount for a
> folio, or am I wrong?

Thinking about it, Maybe we should really find a way to keep the current 
logic flow unmodified:

1) ptep_get_and_clear_full()
2) tlb_remove_tlb_entry()
3) page_remove_rmap()
4) __tlb_remove_page()

For example, one loop to handle 1) and 2); and another one to handle 4).

This will need a way to query for the first loop how often we can call 
__tlb_remove_page() before we need a flush.

The simple answer would be "batch->max - batch->nr". tlb_next_batch() 
makes exceeding that a bit harder, maybe it's not really required.
  
Ryan Roberts Aug. 3, 2023, 1:56 p.m. UTC | #6
As per yesterday's discussion, I'm going to rework this series into a more
generic version that covers pagecache folios too. But your comments will still
be relevent there so answers below.


On 03/08/2023 14:38, David Hildenbrand wrote:
> On 27.07.23 16:18, Ryan Roberts wrote:
>> This allows batching the rmap removal with folio_remove_rmap_range(),
>> which means we avoid spuriously adding a partially unmapped folio to the
>> deferred split queue in the common case, which reduces split queue lock
>> contention.
>>
>> Previously each page was removed from the rmap individually with
>> page_remove_rmap(). If the first page belonged to a large folio, this
>> would cause page_remove_rmap() to conclude that the folio was now
>> partially mapped and add the folio to the deferred split queue. But
>> subsequent calls would cause the folio to become fully unmapped, meaning
>> there is no value to adding it to the split queue.
>>
>> A complicating factor is that for platforms where MMU_GATHER_NO_GATHER
>> is enabled (e.g. s390), __tlb_remove_page() drops a reference to the
>> page. This means that the folio reference count could drop to zero while
>> still in use (i.e. before folio_remove_rmap_range() is called). This
>> does not happen on other platforms because the actual page freeing is
>> deferred.
>>
>> Solve this by appropriately getting/putting the folio to guarrantee it
>> does not get freed early. Given the need to get/put the folio in the
>> batch path, we stick to the non-batched path if the folio is not large.
>> While the batched path is functionally correct for a folio with 1 page,
>> it is unlikely to be as efficient as the existing non-batched path in
>> this case.
>>
>> Signed-off-by: Ryan Roberts <ryan.roberts@arm.com>
>> ---
>>   mm/memory.c | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++
>>   1 file changed, 132 insertions(+)
>>
>> diff --git a/mm/memory.c b/mm/memory.c
>> index 01f39e8144ef..d35bd8d2b855 100644
>> --- a/mm/memory.c
>> +++ b/mm/memory.c
>> @@ -1391,6 +1391,99 @@ zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,
>>       pte_install_uffd_wp_if_needed(vma, addr, pte, pteval);
>>   }
>>   +static inline unsigned long page_cont_mapped_vaddr(struct page *page,
>> +                struct page *anchor, unsigned long anchor_vaddr)
>> +{
>> +    unsigned long offset;
>> +    unsigned long vaddr;
>> +
>> +    offset = (page_to_pfn(page) - page_to_pfn(anchor)) << PAGE_SHIFT;
>> +    vaddr = anchor_vaddr + offset;
>> +
>> +    if (anchor > page) {
>> +        if (vaddr > anchor_vaddr)
>> +            return 0;
>> +    } else {
>> +        if (vaddr < anchor_vaddr)
>> +            return ULONG_MAX;
>> +    }
>> +
>> +    return vaddr;
>> +}
>> +
>> +static int folio_nr_pages_cont_mapped(struct folio *folio,
>> +                      struct page *page, pte_t *pte,
>> +                      unsigned long addr, unsigned long end)
>> +{
>> +    pte_t ptent;
>> +    int floops;
>> +    int i;
>> +    unsigned long pfn;
>> +    struct page *folio_end;
>> +
>> +    if (!folio_test_large(folio))
>> +        return 1;
>> +
>> +    folio_end = &folio->page + folio_nr_pages(folio);
>> +    end = min(page_cont_mapped_vaddr(folio_end, page, addr), end);
>> +    floops = (end - addr) >> PAGE_SHIFT;
>> +    pfn = page_to_pfn(page);
>> +    pfn++;
>> +    pte++;
>> +
>> +    for (i = 1; i < floops; i++) {
>> +        ptent = ptep_get(pte);
>> +
>> +        if (!pte_present(ptent) || pte_pfn(ptent) != pfn)
>> +            break;
>> +
>> +        pfn++;
>> +        pte++;
>> +    }
>> +
>> +    return i;
>> +}
>> +
>> +static unsigned long try_zap_anon_pte_range(struct mmu_gather *tlb,
>> +                        struct vm_area_struct *vma,
>> +                        struct folio *folio,
>> +                        struct page *page, pte_t *pte,
>> +                        unsigned long addr, int nr_pages,
>> +                        struct zap_details *details)
>> +{
>> +    struct mm_struct *mm = tlb->mm;
>> +    pte_t ptent;
>> +    bool full;
>> +    int i;
>> +
>> +    /* __tlb_remove_page may drop a ref; prevent going to 0 while in use. */
>> +    folio_get(folio);
> 
> Is there no way around that? It feels wrong and IMHO a bit ugly.

I haven't found a good one, but I'm all ears. On the non-batched path,
__tlb_remove_page() is called before page_remove_rmap(). On this path, the whole
point is that we just call folio_remove_rmap_range() for the whole batch. If I'm
right, we must only remove from the rmap *after* doing the pte clear to avoid
races. And we need to do call __tlb_remove_page() as we go, because it might run
out of space at any time.

If I knew how many pages the tlb could accept ahead of time, I could defer the
__tlb_remove_page() calls to after folio_remove_rmap_range(). But there is no
accessor for that as far as I can see. It looks fairly complicated to calculate
it too.

> 
> With this patch, you'll might suddenly have mapcount > refcount for a folio, or
> am I wrong?

Yes you would. Does that break things?

> 
>> +
>> +    for (i = 0; i < nr_pages;) {
>> +        ptent = ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm);
>> +        tlb_remove_tlb_entry(tlb, pte, addr);
>> +        zap_install_uffd_wp_if_needed(vma, addr, pte, details, ptent);
>> +        full = __tlb_remove_page(tlb, page, 0);
>> +
>> +        if (unlikely(page_mapcount(page) < 1))
>> +            print_bad_pte(vma, addr, ptent, page);
> 
> Can we avoid new users of page_mapcount() outside rmap code, please? :)

Sure. This is just trying to replicate the same diagnstics that's done on the
non-batched path. I'm happy to remove it.

>
  
David Hildenbrand Aug. 3, 2023, 1:57 p.m. UTC | #7
On 27.07.23 19:22, Yu Zhao wrote:
> On Thu, Jul 27, 2023 at 8:18 AM Ryan Roberts <ryan.roberts@arm.com> wrote:
>>
>> This allows batching the rmap removal with folio_remove_rmap_range(),
>> which means we avoid spuriously adding a partially unmapped folio to the
>> deferred split queue in the common case, which reduces split queue lock
>> contention.
>>
>> Previously each page was removed from the rmap individually with
>> page_remove_rmap(). If the first page belonged to a large folio, this
>> would cause page_remove_rmap() to conclude that the folio was now
>> partially mapped and add the folio to the deferred split queue. But
>> subsequent calls would cause the folio to become fully unmapped, meaning
>> there is no value to adding it to the split queue.
>>
>> A complicating factor is that for platforms where MMU_GATHER_NO_GATHER
>> is enabled (e.g. s390), __tlb_remove_page() drops a reference to the
>> page. This means that the folio reference count could drop to zero while
>> still in use (i.e. before folio_remove_rmap_range() is called). This
>> does not happen on other platforms because the actual page freeing is
>> deferred.
>>
>> Solve this by appropriately getting/putting the folio to guarrantee it
>> does not get freed early. Given the need to get/put the folio in the
>> batch path, we stick to the non-batched path if the folio is not large.
>> While the batched path is functionally correct for a folio with 1 page,
>> it is unlikely to be as efficient as the existing non-batched path in
>> this case.
>>
>> Signed-off-by: Ryan Roberts <ryan.roberts@arm.com>
> 
> This ad hoc patch looks unacceptable to me: we can't afford to keep
> adding special cases.
> 
> I vote for completely converting zap_pte_range() to use
> folio_remove_rmap_range(), and that includes tlb_flush_rmap_batch()
> and other types of large folios, not just anon. Otherwise I'll leave
> it to Matthew and David.

The !anon case with tlb_delay_rmap() really hurts my brain (again).

We're already special-casing on !anon ... so splitting anon and !anon 
also doesn't sound completely off to me.

But yes, we should find ways to just avoid any special casing here, or 
at least minimize them.

(The bigger problem I have with this patch, as raised in my replies, is 
that it messes up the order in which we adjust mapcount+refcount, and I 
am *really* not a friend of that :) )
  
David Hildenbrand Aug. 3, 2023, 2:10 p.m. UTC | #8
>>
>> With this patch, you'll might suddenly have mapcount > refcount for a folio, or
>> am I wrong?
> 
> Yes you would. Does that break things?
> 

It is problematic whenever you want to check for additional page 
references that are not from mappings (i.e., GUP refs/pins or anything else)

One example lives in KSM code (!compound only):

page_mapcount(page) + 1 + swapped != page_count(page)

Another one in compaction code:

if (!mapping && (folio_ref_count(folio) - 1) > folio_mapcount(folio))

And another one in khugepaged (is_refcount_suitable)

... and in THP split can_split_folio() (although that can deal with 
false positives and false negatives).


We want to avoid detecting "no other references" if there *are* other 
references. Detecting "there are other references" although there are 
not is usually better.


Assume you have mapcount > refcount for some time due to concurrent 
unmapping, AND some unrelated reference. You would suddenly pass these 
checks (mapcount == refcount) and might not detect other references.

>>
>>> +
>>> +    for (i = 0; i < nr_pages;) {
>>> +        ptent = ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm);
>>> +        tlb_remove_tlb_entry(tlb, pte, addr);
>>> +        zap_install_uffd_wp_if_needed(vma, addr, pte, details, ptent);
>>> +        full = __tlb_remove_page(tlb, page, 0);
>>> +
>>> +        if (unlikely(page_mapcount(page) < 1))
>>> +            print_bad_pte(vma, addr, ptent, page);
>>
>> Can we avoid new users of page_mapcount() outside rmap code, please? :)
> 
> Sure. This is just trying to replicate the same diagnstics that's done on the
> non-batched path. I'm happy to remove it.

Spotted it afterwards in the existing code already, so you're effetively 
not adding new ones.
  
Ryan Roberts Aug. 3, 2023, 2:15 p.m. UTC | #9
On 03/08/2023 15:10, David Hildenbrand wrote:
>>>
>>> With this patch, you'll might suddenly have mapcount > refcount for a folio, or
>>> am I wrong?
>>
>> Yes you would. Does that break things?
>>
> 
> It is problematic whenever you want to check for additional page references that
> are not from mappings (i.e., GUP refs/pins or anything else)
> 
> One example lives in KSM code (!compound only):
> 
> page_mapcount(page) + 1 + swapped != page_count(page)
> 
> Another one in compaction code:
> 
> if (!mapping && (folio_ref_count(folio) - 1) > folio_mapcount(folio))
> 
> And another one in khugepaged (is_refcount_suitable)
> 
> ... and in THP split can_split_folio() (although that can deal with false
> positives and false negatives).
> 
> 
> We want to avoid detecting "no other references" if there *are* other
> references. Detecting "there are other references" although there are not is
> usually better.
> 
> 
> Assume you have mapcount > refcount for some time due to concurrent unmapping,
> AND some unrelated reference. You would suddenly pass these checks (mapcount ==
> refcount) and might not detect other references.

OK. I'll rework with the 2 loop approach, assuming I can calculate the number of
free slots in the mmu_gather ahead of time.


> 
>>>
>>>> +
>>>> +    for (i = 0; i < nr_pages;) {
>>>> +        ptent = ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm);
>>>> +        tlb_remove_tlb_entry(tlb, pte, addr);
>>>> +        zap_install_uffd_wp_if_needed(vma, addr, pte, details, ptent);
>>>> +        full = __tlb_remove_page(tlb, page, 0);
>>>> +
>>>> +        if (unlikely(page_mapcount(page) < 1))
>>>> +            print_bad_pte(vma, addr, ptent, page);
>>>
>>> Can we avoid new users of page_mapcount() outside rmap code, please? :)
>>
>> Sure. This is just trying to replicate the same diagnstics that's done on the
>> non-batched path. I'm happy to remove it.
> 
> Spotted it afterwards in the existing code already, so you're effetively not
> adding new ones.
>
  
David Hildenbrand Aug. 3, 2023, 2:21 p.m. UTC | #10
On 03.08.23 16:15, Ryan Roberts wrote:
> On 03/08/2023 15:10, David Hildenbrand wrote:
>>>>
>>>> With this patch, you'll might suddenly have mapcount > refcount for a folio, or
>>>> am I wrong?
>>>
>>> Yes you would. Does that break things?
>>>
>>
>> It is problematic whenever you want to check for additional page references that
>> are not from mappings (i.e., GUP refs/pins or anything else)
>>
>> One example lives in KSM code (!compound only):
>>
>> page_mapcount(page) + 1 + swapped != page_count(page)
>>
>> Another one in compaction code:
>>
>> if (!mapping && (folio_ref_count(folio) - 1) > folio_mapcount(folio))
>>
>> And another one in khugepaged (is_refcount_suitable)
>>
>> ... and in THP split can_split_folio() (although that can deal with false
>> positives and false negatives).
>>
>>
>> We want to avoid detecting "no other references" if there *are* other
>> references. Detecting "there are other references" although there are not is
>> usually better.
>>
>>
>> Assume you have mapcount > refcount for some time due to concurrent unmapping,
>> AND some unrelated reference. You would suddenly pass these checks (mapcount ==
>> refcount) and might not detect other references.
> 
> OK. I'll rework with the 2 loop approach, assuming I can calculate the number of
> free slots in the mmu_gather ahead of time.

Note that I think some of these checks might be racy in corner cases 
(and we should most probably make them more reliable by enforcing the 
memory order -- especially a single atomic total_mapcount might help).

But for now, at least the idea that seems to work is that

a) When you map the page, you first increment the refcount, then the 
mapcount

b) When you unmap a page, you first decrement the mapcount, then the 
refcount

So refcount >= mapcount should in theory always hold when taking a 
snapshot of both values. Although if the actual sides that check for 
these additional references might deserve some fine-tuning.
  
Zi Yan Aug. 3, 2023, 2:28 p.m. UTC | #11
On 3 Aug 2023, at 10:15, Ryan Roberts wrote:

> On 03/08/2023 15:10, David Hildenbrand wrote:
>>>>
>>>> With this patch, you'll might suddenly have mapcount > refcount for a folio, or
>>>> am I wrong?
>>>
>>> Yes you would. Does that break things?
>>>
>>
>> It is problematic whenever you want to check for additional page references that
>> are not from mappings (i.e., GUP refs/pins or anything else)
>>
>> One example lives in KSM code (!compound only):
>>
>> page_mapcount(page) + 1 + swapped != page_count(page)
>>
>> Another one in compaction code:
>>
>> if (!mapping && (folio_ref_count(folio) - 1) > folio_mapcount(folio))
>>
>> And another one in khugepaged (is_refcount_suitable)
>>
>> ... and in THP split can_split_folio() (although that can deal with false
>> positives and false negatives).
>>
>>
>> We want to avoid detecting "no other references" if there *are* other
>> references. Detecting "there are other references" although there are not is
>> usually better.
>>
>>
>> Assume you have mapcount > refcount for some time due to concurrent unmapping,
>> AND some unrelated reference. You would suddenly pass these checks (mapcount ==
>> refcount) and might not detect other references.
>
> OK. I'll rework with the 2 loop approach, assuming I can calculate the number of
> free slots in the mmu_gather ahead of time.
>
>
>>
>>>>
>>>>> +
>>>>> +    for (i = 0; i < nr_pages;) {
>>>>> +        ptent = ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm);
>>>>> +        tlb_remove_tlb_entry(tlb, pte, addr);
>>>>> +        zap_install_uffd_wp_if_needed(vma, addr, pte, details, ptent);
>>>>> +        full = __tlb_remove_page(tlb, page, 0);
>>>>> +
>>>>> +        if (unlikely(page_mapcount(page) < 1))
>>>>> +            print_bad_pte(vma, addr, ptent, page);
>>>>
>>>> Can we avoid new users of page_mapcount() outside rmap code, please? :)
>>>
>>> Sure. This is just trying to replicate the same diagnstics that's done on the
>>> non-batched path. I'm happy to remove it.
>>
>> Spotted it afterwards in the existing code already, so you're effetively not
>> adding new ones.

I agree that we should keep the original logic flow and use the 2 loop approach.
Otherwise, the (unlikely(page_mapcount(page) < 1)) check might not work as
expected, since the page mapcount is decreased after this check in your code.


--
Best Regards,
Yan, Zi
  

Patch

diff --git a/mm/memory.c b/mm/memory.c
index 01f39e8144ef..d35bd8d2b855 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -1391,6 +1391,99 @@  zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,
 	pte_install_uffd_wp_if_needed(vma, addr, pte, pteval);
 }
 
+static inline unsigned long page_cont_mapped_vaddr(struct page *page,
+				struct page *anchor, unsigned long anchor_vaddr)
+{
+	unsigned long offset;
+	unsigned long vaddr;
+
+	offset = (page_to_pfn(page) - page_to_pfn(anchor)) << PAGE_SHIFT;
+	vaddr = anchor_vaddr + offset;
+
+	if (anchor > page) {
+		if (vaddr > anchor_vaddr)
+			return 0;
+	} else {
+		if (vaddr < anchor_vaddr)
+			return ULONG_MAX;
+	}
+
+	return vaddr;
+}
+
+static int folio_nr_pages_cont_mapped(struct folio *folio,
+				      struct page *page, pte_t *pte,
+				      unsigned long addr, unsigned long end)
+{
+	pte_t ptent;
+	int floops;
+	int i;
+	unsigned long pfn;
+	struct page *folio_end;
+
+	if (!folio_test_large(folio))
+		return 1;
+
+	folio_end = &folio->page + folio_nr_pages(folio);
+	end = min(page_cont_mapped_vaddr(folio_end, page, addr), end);
+	floops = (end - addr) >> PAGE_SHIFT;
+	pfn = page_to_pfn(page);
+	pfn++;
+	pte++;
+
+	for (i = 1; i < floops; i++) {
+		ptent = ptep_get(pte);
+
+		if (!pte_present(ptent) || pte_pfn(ptent) != pfn)
+			break;
+
+		pfn++;
+		pte++;
+	}
+
+	return i;
+}
+
+static unsigned long try_zap_anon_pte_range(struct mmu_gather *tlb,
+					    struct vm_area_struct *vma,
+					    struct folio *folio,
+					    struct page *page, pte_t *pte,
+					    unsigned long addr, int nr_pages,
+					    struct zap_details *details)
+{
+	struct mm_struct *mm = tlb->mm;
+	pte_t ptent;
+	bool full;
+	int i;
+
+	/* __tlb_remove_page may drop a ref; prevent going to 0 while in use. */
+	folio_get(folio);
+
+	for (i = 0; i < nr_pages;) {
+		ptent = ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm);
+		tlb_remove_tlb_entry(tlb, pte, addr);
+		zap_install_uffd_wp_if_needed(vma, addr, pte, details, ptent);
+		full = __tlb_remove_page(tlb, page, 0);
+
+		if (unlikely(page_mapcount(page) < 1))
+			print_bad_pte(vma, addr, ptent, page);
+
+		i++;
+		page++;
+		pte++;
+		addr += PAGE_SIZE;
+
+		if (unlikely(full))
+			break;
+	}
+
+	folio_remove_rmap_range(folio, page - i, i, vma);
+
+	folio_put(folio);
+
+	return i;
+}
+
 static unsigned long zap_pte_range(struct mmu_gather *tlb,
 				struct vm_area_struct *vma, pmd_t *pmd,
 				unsigned long addr, unsigned long end,
@@ -1428,6 +1521,45 @@  static unsigned long zap_pte_range(struct mmu_gather *tlb,
 			page = vm_normal_page(vma, addr, ptent);
 			if (unlikely(!should_zap_page(details, page)))
 				continue;
+
+			/*
+			 * Batch zap large anonymous folio mappings. This allows
+			 * batching the rmap removal, which means we avoid
+			 * spuriously adding a partially unmapped folio to the
+			 * deferrred split queue in the common case, which
+			 * reduces split queue lock contention.
+			 */
+			if (page && PageAnon(page)) {
+				struct folio *folio = page_folio(page);
+
+				if (folio_test_large(folio)) {
+					int nr_pages_req, nr_pages;
+					int counter = mm_counter(page);
+
+					nr_pages_req = folio_nr_pages_cont_mapped(
+							folio, page, pte, addr,
+							end);
+
+					/* folio may be freed on return. */
+					nr_pages = try_zap_anon_pte_range(
+							tlb, vma, folio, page,
+							pte, addr, nr_pages_req,
+							details);
+
+					rss[counter] -= nr_pages;
+					nr_pages--;
+					pte += nr_pages;
+					addr += nr_pages << PAGE_SHIFT;
+
+					if (unlikely(nr_pages < nr_pages_req)) {
+						force_flush = 1;
+						addr += PAGE_SIZE;
+						break;
+					}
+					continue;
+				}
+			}
+
 			ptent = ptep_get_and_clear_full(mm, addr, pte,
 							tlb->fullmm);
 			tlb_remove_tlb_entry(tlb, pte, addr);