2023-07-27 14:26:53

by Ryan Roberts

[permalink] [raw]
Subject: [PATCH v4 0/3] Optimize large folio interaction with deferred split

Hi All,

This is v4 of a small series in support of my work to enable the use of large
folios for anonymous memory (known as "FLEXIBLE_THP" or "LARGE_ANON_FOLIO") [5].
It first makes it possible to add large, non-pmd-mappable folios to the deferred
split queue. Then it modifies zap_pte_range() to batch-remove spans of
physically contiguous pages from the rmap, which means that in the common case,
we elide the need to ever put the folio on the deferred split queue, thus
reducing lock contention and improving performance.

This becomes more visible once we have lots of large anonymous folios in the
system, and Huang Ying has suggested solving this needs to be a prerequisit for
merging the main FLEXIBLE_THP/LARGE_ANON_FOLIO work.

The series applies on top of v6.5-rc3 and a branch is available at [4].

NOTE: v3 is currently in mm-unstable and has a bug that affects s390, which this
version fixes.


Changes since v3 [3]
--------------------

- Fixed bug reported on s390 [6]
- Since s390 enables MMU_GATHER_NO_GATHER, __tlb_remove_page() causes a ref
to be dropped on the page, but we were still using the page after that
function call.
- Fix by using folio_get()/folio_put() to guarrantee lifetime of page
- Thanks to Nathan Chancellor for the bug report and helping me get set up
with s390!
- Don't use batch path if folio is not large


Changes since v2 [2]
--------------------

- patch 2: Reworked at Yu Zhou's request to reduce duplicated code.
- page_remove_rmap() now forwards to folio_remove_rmap_range() for the
!compound (PMD mapped) case.
- Both page_remove_rmap() and folio_remove_rmap_range() share common
epilogue via new helper function __remove_rmap_finish().
- As a result of the changes, I've removed the previous Reviewed-bys.
- other 2 patches are unchanged.


Changes since v1 [1]
--------------------

- patch 2: Modified doc comment for folio_remove_rmap_range()
- patch 2: Hoisted _nr_pages_mapped manipulation out of page loop so its now
modified once per folio_remove_rmap_range() call.
- patch 2: Added check that page range is fully contained by folio in
folio_remove_rmap_range()
- patch 2: Fixed some nits raised by Huang, Ying for folio_remove_rmap_range()
- patch 3: Support batch-zap of all anon pages, not just those in anon vmas
- patch 3: Renamed various functions to make their use clear
- patch 3: Various minor refactoring/cleanups
- Added Reviewed-By tags - thanks!


[1] https://lore.kernel.org/linux-mm/[email protected]/
[2] https://lore.kernel.org/linux-mm/[email protected]/
[3] https://lore.kernel.org/linux-mm/[email protected]/
[4] https://gitlab.arm.com/linux-arm/linux-rr/-/tree/features/granule_perf/deferredsplit-lkml_v4
[5] https://lore.kernel.org/linux-mm/[email protected]/
[6] https://lore.kernel.org/linux-mm/[email protected]/

Thanks,
Ryan


Ryan Roberts (3):
mm: Allow deferred splitting of arbitrary large anon folios
mm: Implement folio_remove_rmap_range()
mm: Batch-zap large anonymous folio PTE mappings

include/linux/rmap.h | 2 +
mm/memory.c | 132 +++++++++++++++++++++++++++++++++++++++++++
mm/rmap.c | 125 ++++++++++++++++++++++++++++++----------
3 files changed, 229 insertions(+), 30 deletions(-)

--
2.25.1



2023-07-27 14:31:56

by Ryan Roberts

[permalink] [raw]
Subject: [PATCH v4 1/3] mm: Allow deferred splitting of arbitrary large anon folios

In preparation for the introduction of large folios for anonymous
memory, we would like to be able to split them when they have unmapped
subpages, in order to free those unused pages under memory pressure. So
remove the artificial requirement that the large folio needed to be at
least PMD-sized.

Reviewed-by: Yu Zhao <[email protected]>
Reviewed-by: Yin Fengwei <[email protected]>
Reviewed-by: Matthew Wilcox (Oracle) <[email protected]>
Reviewed-by: David Hildenbrand <[email protected]>
Signed-off-by: Ryan Roberts <[email protected]>
---
mm/rmap.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/mm/rmap.c b/mm/rmap.c
index 0c0d8857dfce..eb0bb00dae34 100644
--- a/mm/rmap.c
+++ b/mm/rmap.c
@@ -1426,11 +1426,11 @@ void page_remove_rmap(struct page *page, struct vm_area_struct *vma,
__lruvec_stat_mod_folio(folio, idx, -nr);

/*
- * Queue anon THP for deferred split if at least one
+ * Queue anon large folio for deferred split if at least one
* page of the folio is unmapped and at least one page
* is still mapped.
*/
- if (folio_test_pmd_mappable(folio) && folio_test_anon(folio))
+ if (folio_test_large(folio) && folio_test_anon(folio))
if (!compound || nr < nr_pmdmapped)
deferred_split_folio(folio);
}
--
2.25.1


2023-07-27 14:43:09

by Ryan Roberts

[permalink] [raw]
Subject: [PATCH v4 2/3] mm: Implement folio_remove_rmap_range()

Like page_remove_rmap() but batch-removes the rmap for a range of pages
belonging to a folio. This can provide a small speedup due to less
manipuation of the various counters. But more crucially, if removing the
rmap for all pages of a folio in a batch, there is no need to
(spuriously) add it to the deferred split list, which saves significant
cost when there is contention for the split queue lock.

All contained pages are accounted using the order-0 folio (or base page)
scheme.

page_remove_rmap() is refactored so that it forwards to
folio_remove_rmap_range() for !compound cases, and both functions now
share a common epilogue function. The intention here is to avoid
duplication of code.

Signed-off-by: Ryan Roberts <[email protected]>
---
include/linux/rmap.h | 2 +
mm/rmap.c | 125 ++++++++++++++++++++++++++++++++-----------
2 files changed, 97 insertions(+), 30 deletions(-)

diff --git a/include/linux/rmap.h b/include/linux/rmap.h
index b87d01660412..f578975c12c0 100644
--- a/include/linux/rmap.h
+++ b/include/linux/rmap.h
@@ -200,6 +200,8 @@ void page_add_file_rmap(struct page *, struct vm_area_struct *,
bool compound);
void page_remove_rmap(struct page *, struct vm_area_struct *,
bool compound);
+void folio_remove_rmap_range(struct folio *folio, struct page *page,
+ int nr, struct vm_area_struct *vma);

void hugepage_add_anon_rmap(struct page *, struct vm_area_struct *,
unsigned long address, rmap_t flags);
diff --git a/mm/rmap.c b/mm/rmap.c
index eb0bb00dae34..c3ef56f7ec15 100644
--- a/mm/rmap.c
+++ b/mm/rmap.c
@@ -1359,6 +1359,94 @@ void page_add_file_rmap(struct page *page, struct vm_area_struct *vma,
mlock_vma_folio(folio, vma, compound);
}

+/**
+ * __remove_rmap_finish - common operations when taking down a mapping.
+ * @folio: Folio containing all pages taken down.
+ * @vma: The VM area containing the range.
+ * @compound: True if pages were taken down from PMD or false if from PTE(s).
+ * @nr_unmapped: Number of pages within folio that are now unmapped.
+ * @nr_mapped: Number of pages within folio that are still mapped.
+ */
+static void __remove_rmap_finish(struct folio *folio,
+ struct vm_area_struct *vma, bool compound,
+ int nr_unmapped, int nr_mapped)
+{
+ enum node_stat_item idx;
+
+ if (nr_unmapped) {
+ idx = folio_test_anon(folio) ? NR_ANON_MAPPED : NR_FILE_MAPPED;
+ __lruvec_stat_mod_folio(folio, idx, -nr_unmapped);
+
+ /*
+ * Queue large anon folio for deferred split if at least one
+ * page of the folio is unmapped and at least one page is still
+ * mapped.
+ */
+ if (folio_test_large(folio) &&
+ folio_test_anon(folio) && nr_mapped)
+ deferred_split_folio(folio);
+ }
+
+ /*
+ * It would be tidy to reset folio_test_anon mapping when fully
+ * unmapped, but that might overwrite a racing page_add_anon_rmap
+ * which increments mapcount after us but sets mapping before us:
+ * so leave the reset to free_pages_prepare, and remember that
+ * it's only reliable while mapped.
+ */
+
+ munlock_vma_folio(folio, vma, compound);
+}
+
+/**
+ * folio_remove_rmap_range - Take down PTE mappings from a range of pages.
+ * @folio: Folio containing all pages in range.
+ * @page: First page in range to unmap.
+ * @nr: Number of pages to unmap.
+ * @vma: The VM area containing the range.
+ *
+ * All pages in the range must belong to the same VMA & folio. They must be
+ * mapped with PTEs, not a PMD.
+ *
+ * Context: Caller holds the pte lock.
+ */
+void folio_remove_rmap_range(struct folio *folio, struct page *page,
+ int nr, struct vm_area_struct *vma)
+{
+ atomic_t *mapped = &folio->_nr_pages_mapped;
+ int nr_unmapped = 0;
+ int nr_mapped = 0;
+ bool last;
+
+ if (unlikely(folio_test_hugetlb(folio))) {
+ VM_WARN_ON_FOLIO(1, folio);
+ return;
+ }
+
+ VM_WARN_ON_ONCE(page < &folio->page ||
+ page + nr > (&folio->page + folio_nr_pages(folio)));
+
+ if (!folio_test_large(folio)) {
+ /* Is this the page's last map to be removed? */
+ last = atomic_add_negative(-1, &page->_mapcount);
+ nr_unmapped = last;
+ } else {
+ for (; nr != 0; nr--, page++) {
+ /* Is this the page's last map to be removed? */
+ last = atomic_add_negative(-1, &page->_mapcount);
+ if (last)
+ nr_unmapped++;
+ }
+
+ /* Pages still mapped if folio mapped entirely */
+ nr_mapped = atomic_sub_return_relaxed(nr_unmapped, mapped);
+ if (nr_mapped >= COMPOUND_MAPPED)
+ nr_unmapped = 0;
+ }
+
+ __remove_rmap_finish(folio, vma, false, nr_unmapped, nr_mapped);
+}
+
/**
* page_remove_rmap - take down pte mapping from a page
* @page: page to remove mapping from
@@ -1385,15 +1473,13 @@ void page_remove_rmap(struct page *page, struct vm_area_struct *vma,
return;
}

- /* Is page being unmapped by PTE? Is this its last map to be removed? */
+ /* Is page being unmapped by PTE? */
if (likely(!compound)) {
- last = atomic_add_negative(-1, &page->_mapcount);
- nr = last;
- if (last && folio_test_large(folio)) {
- nr = atomic_dec_return_relaxed(mapped);
- nr = (nr < COMPOUND_MAPPED);
- }
- } else if (folio_test_pmd_mappable(folio)) {
+ folio_remove_rmap_range(folio, page, 1, vma);
+ return;
+ }
+
+ if (folio_test_pmd_mappable(folio)) {
/* That test is redundant: it's for safety or to optimize out */

last = atomic_add_negative(-1, &folio->_entire_mapcount);
@@ -1421,29 +1507,8 @@ void page_remove_rmap(struct page *page, struct vm_area_struct *vma,
idx = NR_FILE_PMDMAPPED;
__lruvec_stat_mod_folio(folio, idx, -nr_pmdmapped);
}
- if (nr) {
- idx = folio_test_anon(folio) ? NR_ANON_MAPPED : NR_FILE_MAPPED;
- __lruvec_stat_mod_folio(folio, idx, -nr);
-
- /*
- * Queue anon large folio for deferred split if at least one
- * page of the folio is unmapped and at least one page
- * is still mapped.
- */
- if (folio_test_large(folio) && folio_test_anon(folio))
- if (!compound || nr < nr_pmdmapped)
- deferred_split_folio(folio);
- }
-
- /*
- * It would be tidy to reset folio_test_anon mapping when fully
- * unmapped, but that might overwrite a racing page_add_anon_rmap
- * which increments mapcount after us but sets mapping before us:
- * so leave the reset to free_pages_prepare, and remember that
- * it's only reliable while mapped.
- */

- munlock_vma_folio(folio, vma, compound);
+ __remove_rmap_finish(folio, vma, compound, nr, nr_pmdmapped - nr);
}

/*
--
2.25.1


2023-07-27 14:53:34

by Ryan Roberts

[permalink] [raw]
Subject: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

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 <[email protected]>
---
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);
+
+ 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);
--
2.25.1


2023-07-27 17:38:01

by Yu Zhao

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

On Thu, Jul 27, 2023 at 8:18 AM Ryan Roberts <[email protected]> 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 <[email protected]>

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.

2023-07-28 09:29:15

by Ryan Roberts

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

On 27/07/2023 18:22, Yu Zhao wrote:
> On Thu, Jul 27, 2023 at 8:18 AM Ryan Roberts <[email protected]> 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 <[email protected]>
>
> 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.


2023-08-01 07:36:01

by Yu Zhao

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

On Fri, Jul 28, 2023 at 3:16 AM Ryan Roberts <[email protected]> wrote:
>
> On 27/07/2023 18:22, Yu Zhao wrote:
> > On Thu, Jul 27, 2023 at 8:18 AM Ryan Roberts <[email protected]> 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 <[email protected]>
> >
> > 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().

2023-08-02 17:03:37

by Ryan Roberts

[permalink] [raw]
Subject: Re: [PATCH v4 0/3] Optimize large folio interaction with deferred split

Hi Andrew,

After discussion about this in Matthew's THP Cabal, we have decided to take a
different approach with this patch set. Could you therefore remove it from
mm-unstable, please? Sorry about the noise.

I'm going to try 2 different approaches:
- avoid the split lock contention by using mmu gather (suggested by Kirill)
- expand the zap pte batching to also cover file folios (as requested by Yu).

Thanks,
Ryan



On 27/07/2023 15:18, Ryan Roberts wrote:
> Hi All,
>
> This is v4 of a small series in support of my work to enable the use of large
> folios for anonymous memory (known as "FLEXIBLE_THP" or "LARGE_ANON_FOLIO") [5].
> It first makes it possible to add large, non-pmd-mappable folios to the deferred
> split queue. Then it modifies zap_pte_range() to batch-remove spans of
> physically contiguous pages from the rmap, which means that in the common case,
> we elide the need to ever put the folio on the deferred split queue, thus
> reducing lock contention and improving performance.
>
> This becomes more visible once we have lots of large anonymous folios in the
> system, and Huang Ying has suggested solving this needs to be a prerequisit for
> merging the main FLEXIBLE_THP/LARGE_ANON_FOLIO work.
>
> The series applies on top of v6.5-rc3 and a branch is available at [4].
>
> NOTE: v3 is currently in mm-unstable and has a bug that affects s390, which this
> version fixes.
>
>
> Changes since v3 [3]
> --------------------
>
> - Fixed bug reported on s390 [6]
> - Since s390 enables MMU_GATHER_NO_GATHER, __tlb_remove_page() causes a ref
> to be dropped on the page, but we were still using the page after that
> function call.
> - Fix by using folio_get()/folio_put() to guarrantee lifetime of page
> - Thanks to Nathan Chancellor for the bug report and helping me get set up
> with s390!
> - Don't use batch path if folio is not large
>
>
> Changes since v2 [2]
> --------------------
>
> - patch 2: Reworked at Yu Zhou's request to reduce duplicated code.
> - page_remove_rmap() now forwards to folio_remove_rmap_range() for the
> !compound (PMD mapped) case.
> - Both page_remove_rmap() and folio_remove_rmap_range() share common
> epilogue via new helper function __remove_rmap_finish().
> - As a result of the changes, I've removed the previous Reviewed-bys.
> - other 2 patches are unchanged.
>
>
> Changes since v1 [1]
> --------------------
>
> - patch 2: Modified doc comment for folio_remove_rmap_range()
> - patch 2: Hoisted _nr_pages_mapped manipulation out of page loop so its now
> modified once per folio_remove_rmap_range() call.
> - patch 2: Added check that page range is fully contained by folio in
> folio_remove_rmap_range()
> - patch 2: Fixed some nits raised by Huang, Ying for folio_remove_rmap_range()
> - patch 3: Support batch-zap of all anon pages, not just those in anon vmas
> - patch 3: Renamed various functions to make their use clear
> - patch 3: Various minor refactoring/cleanups
> - Added Reviewed-By tags - thanks!
>
>
> [1] https://lore.kernel.org/linux-mm/[email protected]/
> [2] https://lore.kernel.org/linux-mm/[email protected]/
> [3] https://lore.kernel.org/linux-mm/[email protected]/
> [4] https://gitlab.arm.com/linux-arm/linux-rr/-/tree/features/granule_perf/deferredsplit-lkml_v4
> [5] https://lore.kernel.org/linux-mm/[email protected]/
> [6] https://lore.kernel.org/linux-mm/[email protected]/
>
> Thanks,
> Ryan
>
>
> Ryan Roberts (3):
> mm: Allow deferred splitting of arbitrary large anon folios
> mm: Implement folio_remove_rmap_range()
> mm: Batch-zap large anonymous folio PTE mappings
>
> include/linux/rmap.h | 2 +
> mm/memory.c | 132 +++++++++++++++++++++++++++++++++++++++++++
> mm/rmap.c | 125 ++++++++++++++++++++++++++++++----------
> 3 files changed, 229 insertions(+), 30 deletions(-)
>
> --
> 2.25.1
>


2023-08-02 17:30:37

by Yu Zhao

[permalink] [raw]
Subject: Re: [PATCH v4 0/3] Optimize large folio interaction with deferred split

On Wed, Aug 2, 2023 at 10:42 AM Ryan Roberts <[email protected]> wrote:
>
> Hi Andrew,
>
> After discussion about this in Matthew's THP Cabal, we have decided to take a
> different approach with this patch set. Could you therefore remove it from
> mm-unstable, please? Sorry about the noise.
>
> I'm going to try 2 different approaches:
> - avoid the split lock contention by using mmu gather (suggested by Kirill)
> - expand the zap pte batching to also cover file folios (as requested by Yu).

Also we didn't have the chance to clarify before Ryan dropped out from
the meeting: I don't think this series is a prerequisite for the other
series ("variable-order, large folios for anonymous memory") at all.
They can move along in parallel: one is specific for anon and the
other (this series) is generic for all types of large folios.

2023-08-03 13:04:29

by Kirill A. Shutemov

[permalink] [raw]
Subject: Re: [PATCH v4 0/3] Optimize large folio interaction with deferred split

On Wed, Aug 02, 2023 at 05:42:23PM +0100, Ryan Roberts wrote:
> - avoid the split lock contention by using mmu gather (suggested by Kirill)

[Offlist]

So, my idea is to embed struct deferred_split into struct mmu_gather and
make zap path to use it instead of per-node/per-memcg deferred_split. This
would avoid lock contention. If the list is not empty after zap, move the
to the per-node/per-memcg deferred_split.

But it is only relevant if we see lock contention.

--
Kiryl Shutsemau / Kirill A. Shutemov

2023-08-03 13:29:26

by Ryan Roberts

[permalink] [raw]
Subject: Re: [PATCH v4 0/3] Optimize large folio interaction with deferred split

On 03/08/2023 13:01, Kirill A. Shutemov wrote:
> On Wed, Aug 02, 2023 at 05:42:23PM +0100, Ryan Roberts wrote:
>> - avoid the split lock contention by using mmu gather (suggested by Kirill)
>
> [Offlist]
>
> So, my idea is to embed struct deferred_split into struct mmu_gather and
> make zap path to use it instead of per-node/per-memcg deferred_split. This
> would avoid lock contention. If the list is not empty after zap, move the
> to the per-node/per-memcg deferred_split.
>
> But it is only relevant if we see lock contention.
>

Thanks Kiryl, I understand the proposal now. Having thought about this over
night, I'm thinking I'll just implement the full batch approach that Yu
proposed. In this case, we will get the benefits of batching rmap removal (for
all folio types) and as a side benefit we will get the lock contention reduction
(if there is lock contention) without the need for the new per-mmu_gather struct
deferred_split. Shout if you have issue with this.

2023-08-03 14:03:40

by David Hildenbrand

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

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 <[email protected]>
>> ---
>> 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.

--
Cheers,

David / dhildenb


2023-08-03 14:10:39

by David Hildenbrand

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

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 <[email protected]>
> ---
> 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? :)

--
Cheers,

David / dhildenb


2023-08-03 14:12:33

by Ryan Roberts

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

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 <[email protected]>
>> ---
>>   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.

>


2023-08-03 14:44:13

by Ryan Roberts

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

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.
>


2023-08-03 14:51:15

by David Hildenbrand

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

On 27.07.23 19:22, Yu Zhao wrote:
> On Thu, Jul 27, 2023 at 8:18 AM Ryan Roberts <[email protected]> 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 <[email protected]>
>
> 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 :) )

--
Cheers,

David / dhildenb


2023-08-03 14:57:30

by Zi Yan

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

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


Attachments:
signature.asc (871.00 B)
OpenPGP digital signature

2023-08-03 16:02:31

by David Hildenbrand

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

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.

--
Cheers,

David / dhildenb


2023-08-03 16:08:53

by David Hildenbrand

[permalink] [raw]
Subject: Re: [PATCH v4 3/3] mm: Batch-zap large anonymous folio PTE mappings

>>
>> 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.

--
Cheers,

David / dhildenb