mm: MM owner tracking for large folios (!hugetlb) + CONFIG_NO_PAGE_MAPCOUNT
Subsystems (16)
cover mm: MM owner tracking for large folios (!hugetlb) + CONFIG_NO_PAGE_MAPCOUNT
RMAP overhaul and optimizations, PTE batching, large mapcount, folio_likely_mapped_shared() introduction and optimizations, page_mapcount cleanups and preparations ... it's been quite some work to get to this point.
Next up is being able to identify -- without false positives, without page-mapcounts and without page table/rmap scanning -- whether a large folio is "mapped exclusively" into a single MM, and using that information to implement Copy-on-Write reuse and to improve folio_likely_mapped_shared() for large folios.
... and based on that, finally introducing a kernel config option that let's us not use+maintain per-page mapcounts in large folios, improving performance of (un)map operations today, taking one step towards supporting large folios > PMD_SIZE, and preparing for the bright future where we might no longer have a mapcount per page at all.
The bigger picture was presented at LSF/MM [1].
This series is effectively a follow-up on my early work from last year [2], which proposed a precise way to identify whether a large folio is "mapped shared" into multiple MMs or "mapped exclusively" into a single MM.
While that advanced approach has been simplified and optimized in the meantime, let's start with something simpler first -- "certainly mapped exclusive" vs. ""maybe mapped shared" -- so we can start learning about the effects and TODOs that some of the implied changes of losing per-page mapcounts has.
I have plans to exchange the simple approach used in this series at some point by the advanced approach, but one important thing to learn if the imprecision in the simple approach is relevant in practice.
64BIT only, and unless enabled in kconfig, this series should for now not have any impact.
1) Patch Organization
=====================
Patch #1 -> #4: make more room on 64BIT in order-1 folios
Patch #5 -> #7: prepare for MM owner tracking of large folios
Patch #8: implement a simple MM owner tracking approach for large folios
patch #9: simple optimization
Patch #10: COW reuse for PTE-mapped anon THP
Patch #11 -> #17: introduce and implement CONFIG_NO_PAGE_MAPCOUNT
2) MM owner tracking
====================
Similar to my advanced approach [2], we assign each MM a unique 20-bit ID ("MM ID"), to be able to squeeze more information in our folios.
Each large folios can store two MM-ID+mapcount combination:
* mm0_id + mm0_mapcount
* mm1_id + mm1_mapcount
Combined with the large mapcount, we can reliably identify whether one of these MMs is the current owner (-> owns all mappings) or even holds all folio references (-> owns all mappings, and all references are from mappings).
Stored MM IDs can only change if the corresponding mapcount is logically 0, and if the folio is currently "mapped exclusively".
As long as only two MMs map folio pages at a time, we can reliably identify whether a large folio is "mapped shared" or "mapped exclusively". The approach is precise.
Any MM mapping the folio while two other MMs are already mapping the folio, will lead to a "mapped shared" detection even after all other MMs stopped mapping the folio and it is actually "mapped exclusively": we can have false positives but never false negatives when detecting "mapped shared".
So that's where the approach gets imprecise.
For now, we use a bit-spinlock to sync the large mapcount + MM IDs + MM mapcounts, and make sure we do keep the machinery fast, to not degrade (un)map performance too much: for example, we make sure to only use a single atomic (when grabbing the bit-spinlock), like we would already perform when updating the large mapcount.
In the future, we might be able to use an arch_spin_lock(), but that's future work.
3) CONFIG_NO_PAGE_MAPCOUNT
==========================
patch #11 -> #17 spell out and document what exactly is affected when not maintaining the per-page mapcounts in large folios anymore.
For example, as we cannot maintain folio->_nr_pages_mapped anymore when (un)mapping pages, we'll account a complete folio as mapped if a single page is mapped.
As another example, we might now under-estimate the USS (Unique Set Size) of a process, but never over-estimate it.
With a more elaborate approach for MM-owner tracking like #1, some things could be improved (e.g., USS to some degree), but somethings just cannot be handled like we used to without these per-page mapcounts (e.g., folio->_nr_pages_mapped).
4) Performance
==============
The following kernel config combinations are possible:
* Base: CONFIG_PAGE_MAPCOUNT
-> (existing) page-mapcount tracking
* MM-ID: CONFIG_MM_ID && CONFIG_PAGE_MAPCOUNT -> page-mapcount + MM-ID tracking
* No-Mapcount: CONFIG_MM_ID && CONFIG_NO_PAGE_MAPCOUNT -> MM-ID tracking
I run my PTE-mapped-THP microbenchmarks [3] and vm-scalability on a machine with two NUMA nodes, with a 10-core Intel(R) Xeon(R) Silver 4210R CPU @ 2.40GHz and 16 GiB of memory each.
4.1) PTE-mapped-THP microbenchmarks
-----------------------------------
All benchmarks allocate 1 GiB of THPs of a given size, to then fork()/ munmap/... PMD-sized THPs are mapped by PTEs first.
Numbers are increase (+) / reduction (-) in runtime. Reduction (-) is good. "Base" is the baseline.
munmap: munmap() the allocated memory.
Folio Size | MM-ID | No-Mapcount
--------------------------------
16 KiB | 2 % | -8 %
32 KiB | 3 % | -9 %
64 KiB | 4 % | -16 %
128 KiB | 3 % | -17 %
256 KiB | 1 % | -23 %
512 KiB | 1 % | -26 %
1024 KiB | 0 % | -29 %
2048 KiB | 0 % | -31 %-> 32-128 with MM-ID are a bit unexpected: we would expect to see the worst
case with the smallest size (16 KiB). But for these sizes also the STDEV is between 1% and 2%, in contrast to the others (< 1 %). Maybe some weird interaction with PCP/buddy.
fork: fork()
Folio Size | MM-ID | No-Mapcount
--------------------------------
16 KiB | 4 % | -9 %
32 KiB | 1 % | -12 %
64 KiB | 0 % | -15 %
128 KiB | 0 % | -15 %
256 KiB | 0 % | -16 %
512 KiB | 0 % | -16 %
1024 KiB | 0 % | -17 %
2048 KiB | -1 % | -21 %-> Slight slowdown with MM-ID for the smallest folio size (more what we expect in contrast to munmap()).
cow-byte: fork() and keep the child running. write one byte to each
individual page, measuring the duration of all writes.
Folio Size | MM-ID | No-Mapcount
--------------------------------
16 KiB | 0 % | 0 %
32 KiB | 0 % | 0 %
64 KiB | 0 % | 0 %
128 KiB | 0 % | 0 %
256 KiB | 0 % | 0 %
512 KiB | 0 % | 0 %
1024 KiB | 0 % | 0 %
2048 KiB | 0 % | 0 %-> All other overhead dominates even when effectively unmapping
single pages of large folios when replacing them by a copy during write faults. No change, which is great!
reuse-byte: fork() and wait until the child quit. write one byte to each
individual page, measuring the duration of all writes.
Folio Size | MM-ID | No-Mapcount
--------------------------------
16 KiB | -66 % | -66 %
32 KiB | -65 % | -65 %
64 KiB | -64 % | -64 %
128 KiB | -64 % | -64 %
256 KiB | -64 % | -64 %
512 KiB | -64 % | -64 %
1024 KiB | -64 % | -64 %
2048 KiB | -64 % | -64 %-> No surprise, we reuse all pages instead of copying them.
child-reuse-bye: fork() and unmap the memory in the parent. write one byte
to each individual page in the child, measuring the duration of all writes.
Folio Size | MM-ID | No-Mapcount
--------------------------------
16 KiB | -66 % | -66 %
32 KiB | -65 % | -65 %
64 KiB | -64 % | -64 %
128 KiB | -64 % | -64 %
256 KiB | -64 % | -64 %
512 KiB | -64 % | -64 %
1024 KiB | -64 % | -64 %
2048 KiB | -64 % | -64 %-> Same thing, we reuse all pages instead of copying them.
For 4 KiB, there is no change in any benchmark, as expected.
4.2) vm-scalability
-------------------
For now I only ran anon COW tests. I use 1 GiB per child process and use one child per core (-> 20).
case-anon-cow-rand: random writes
There is effectively no change (<0.6% throughput difference).
case-anon-cow-seq: sequential writes
MM-ID has up to 2% *lower* throughout than Base, not really correlating to folio size. The difference is almost as large as the STDEV (1% - 2%), though. It looks like there is a very slight effective slowdown.
No-Mapcount has up to 3% *higher* throughput than Base, not really correlating to the folio size. However, also here the difference is almost as large as the STDEV (up to 2%). It looks like there is a very slight effective speedup.
In summary, no earth-shattering slowdown with MM-ID (and we just recently optimized folio->_nr_pages_mapped to give us some speedup :) ), and another nice improvement with No-Mapcount.
I did a bunch of cross-compiles and the build bots turned out very helpful over the last months. I did quite some testing with LTP and selftests, but x86-64 only.
To keep the CC list short, adding only relevant maintainers (CCed on all patches, sorry ;) ).
Related things on my long TODO list:
* Replace the "entire mapcount" by a "pmd mapcount" and a "pud mapcount", to prepare for handling folios > PMD size. Maybe we'll have to keep it for hugetlb, we'll see.
* Make hugetlb play along, and possibly use the same mapcount scheme. PMD page table sharing doesn't play along and needs some thought. There might be ways, but it's a bit more involved.
* Make AnonExclusive a per-folio flag. It's complicated.
[1] https://lwn.net/Articles/974223/
[2] https://lore.kernel.org/linux-mm/[email protected]/T/
[3] https://gitlab.com/davidhildenbrand/scratchspace/-/raw/main/pte-mapped-folio-benchmarks.c
David Hildenbrand (17):
mm: factor out large folio handling from folio_order() into
folio_large_order()
mm: factor out large folio handling from folio_nr_pages() into
folio_large_nr_pages()
mm/rmap: use folio_large_nr_pages() in add/remove functions
mm: let _folio_nr_pages overlay memcg_data in first tail page mm/rmap: pass dst_vma to page_try_dup_anon_rmap() and
page_dup_file_rmap()
mm/rmap: pass vma to __folio_add_rmap()
mm/rmap: abstract large mapcount operations for large folios
(!hugetlb)
mm/rmap: initial MM owner tracking for large folios (!hugetlb)
bit_spinlock: __always_inline (un)lock functions
mm: COW reuse support for PTE-mapped THP with CONFIG_MM_ID
mm: CONFIG_NO_PAGE_MAPCOUNT to prepare for not maintain per-page
mapcounts in large folios
mm: remove per-page mapcount dependency in
folio_likely_mapped_shared() (CONFIG_NO_PAGE_MAPCOUNT)
fs/proc/page: remove per-page mapcount dependency for /proc/kpagecount
(CONFIG_NO_PAGE_MAPCOUNT)
fs/proc/task_mmu: remove per-page mapcount dependency for
PM_MMAP_EXCLUSIVE (CONFIG_NO_PAGE_MAPCOUNT)
fs/proc/task_mmu: remove per-page mapcount dependency for "mapmax"
(CONFIG_NO_PAGE_MAPCOUNT)
fs/proc/task_mmu: remove per-page mapcount dependency for
smaps/smaps_rollup (CONFIG_NO_PAGE_MAPCOUNT)
mm: stop maintaining the per-page mapcount of large folios
(CONFIG_NO_PAGE_MAPCOUNT)
.../admin-guide/cgroup-v1/memory.rst | 4 + Documentation/admin-guide/cgroup-v2.rst | 10 +- Documentation/admin-guide/mm/pagemap.rst | 16 +- Documentation/filesystems/proc.rst | 28 ++- Documentation/mm/transhuge.rst | 39 +++- arch/x86/entry/vdso/vdso32/fake_32bit_build.h | 1 + fs/proc/internal.h | 33 +++ fs/proc/page.c | 18 +- fs/proc/task_mmu.c | 41 +++- include/linux/bit_spinlock.h | 8 +- include/linux/mm.h | 60 +++-- include/linux/mm_types.h | 57 ++++- include/linux/page-flags.h | 41 ++++ include/linux/rmap.h | 213 ++++++++++++++++-- kernel/fork.c | 36 +++ mm/Kconfig | 31 +++ mm/huge_memory.c | 16 +- mm/internal.h | 33 ++- mm/memory.c | 97 ++++++-- mm/page_alloc.c | 18 +- mm/page_owner.c | 2 +- mm/rmap.c | 97 ++++++-- 22 files changed, 781 insertions(+), 118 deletions(-)
Signature · 1 line
2.46.0
PATCH 1/17 mm: factor out large folio handling from folio_order() into folio_large_order()
Let's factor it out into a simple helper function. This helper will also come in handy when working with code where we know that our folio is large.
--- include/linux/mm.h | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-)
include/linux/mm.h +9 -4
@@ -1071,6 +1071,11 @@ int vma_is_stack_for_current(struct vm_area_struct *vma);struct mmu_gather ;struct inode ; +static inline unsigned int folio_large_order (const struct folio *folio) +{ +return folio->_flags_1 &0xff ; +} +/* * compound_order() can be called without holding a reference, which means * that niceties like page_folio() don't work. These callers should be
@@ -1084,7 +1089,7 @@ static inline unsigned int compound_order(struct page *page)if (!test_bit (PG_head, &folio->flags))return 0 ; -return folio->_flags_1 &0xff ; +return folio_large_order (folio); }/**
@@ -1100,7 +1105,7 @@ static inline unsigned int folio_order(const struct folio *folio) {if (!folio_test_large (folio))return 0 ; -return folio->_flags_1 &0xff ; +return folio_large_order (folio); }#include <linux/huge_mm.h>
@@ -2035,7 +2040,7 @@ static inline long folio_nr_pages(const struct folio *folio)#ifdef CONFIG_64BIT return folio->_folio_nr_pages;#else -return 1L << (folio->_flags_1 &0xff ); +return 1L <<folio_large_order (folio);#endif }
@@ -2060,7 +2065,7 @@ static inline unsigned long compound_nr(struct page *page)#ifdef CONFIG_64BIT return folio->_folio_nr_pages;#else -return 1L << (folio->_flags_1 &0xff ); +return 1L <<folio_large_order (folio);#endif }
Signature · 1 line
2.46.0
PATCH 2/17 mm: factor out large folio handling from folio_nr_pages() into folio_large_nr_pages()
In reply to David HildenbrandLet's factor it out into a simple helper function. This helper will also come in handy when working with code where we know that our folio is large.
Make use of it in internal.h and mm.h, where applicable.
While at it, let's consistently return a "long" value from all these similar functions. Note that we cannot use "unsigned int" (even though _folio_nr_pages is of that type), because it would break some callers that do stuff like "-folio_nr_pages()". Both "int" or "unsigned long" would work as well.
--- include/linux/mm.h | 27 ++++++++++++++------------- mm/internal.h | 2 +- 2 files changed, 15 insertions(+), 14 deletions(-)
include/linux/mm.h +14 -13
@@ -1076,6 +1076,15 @@ static inline unsigned int folio_large_order(const struct folio *folio)return folio->_flags_1 &0xff ; } +static inline long folio_large_nr_pages (const struct folio *folio) +{ +#ifdef CONFIG_64BIT +return folio->_folio_nr_pages; +#else +return 1L <<folio_large_order (folio); +#endif +} +/* * compound_order() can be called without holding a reference, which means * that niceties like page_folio() don't work. These callers should be
@@ -2037,11 +2046,7 @@ static inline long folio_nr_pages(const struct folio *folio) {if (!folio_test_large (folio))return 1 ; -#ifdef CONFIG_64BIT -return folio->_folio_nr_pages; -#else -return 1L <<folio_large_order (folio); -#endif +return folio_large_nr_pages (folio); }/* Only hugetlbfs can allocate folios larger than MAX_ORDER */
@@ -2056,24 +2061,20 @@ static inline long folio_nr_pages(const struct folio *folio)* page. compound_nr() can be called on a tail page, and is defined to * return 1 in that case. */ -static inline unsigned long compound_nr (struct page *page) +static inline long compound_nr (struct page *page) {struct folio *folio = (struct folio *)page;if (!test_bit (PG_head, &folio->flags))return 1 ; -#ifdef CONFIG_64BIT -return folio->_folio_nr_pages; -#else -return 1L <<folio_large_order (folio); -#endif +return folio_large_nr_pages (folio); }/** * thp_nr_pages - The number of regular pages in this huge page. * @page: The head page of a huge page. */ -static inline int thp_nr_pages (struct page *page) +static inline long thp_nr_pages (struct page *page) {return folio_nr_pages ((struct folio *)page); }
@@ -2183,7 +2184,7 @@ static inline bool folio_likely_mapped_shared(struct folio *folio)return false;/* If any page is mapped more than once we treat it "mapped shared". */ -if (folio_entire_mapcount (folio) || mapcount >folio_nr_pages (folio)) +if (folio_entire_mapcount (folio) || mapcount >folio_large_nr_pages (folio))return true;/* Let's guess based on the first subpage. */
mm/internal.h +1 -1
@@ -159,7 +159,7 @@ static inline int folio_pte_batch(struct folio *folio, unsigned long addr, pte_t *start_ptep, pte_t pte, int max_nr, fpb_t flags, bool *any_writable, bool *any_young, bool *any_dirty) { - unsigned long folio_end_pfn = folio_pfn(folio) + folio_nr_pages(folio); + unsigned long folio_end_pfn = folio_pfn(folio) + folio_large_nr_pages(folio);const pte_t *end_ptep = start_ptep + max_nr;pte_t expected_pte, *ptep;bool writable, young, dirty;
Signature · 1 line
2.46.0
PATCH 3/17 mm/rmap: use folio_large_nr_pages() in add/remove functions
In reply to David HildenbrandLet's just use the "large" variant in code where we are sure that we have a large folio in our hands: this way we are sure that we don't perform any unnecessary "large" checks.
While at it, convert the VM_BUG_ON_VMA to a VM_WARN_ON_ONCE.
--- mm/rmap.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-)
mm/rmap.c +8 -6
@@ -1184,7 +1184,7 @@ static __always_inline unsigned int __folio_add_rmap(struct folio *folio,if (first) { nr =atomic_add_return_relaxed (ENTIRELY_MAPPED , mapped);if (likely (nr <ENTIRELY_MAPPED +ENTIRELY_MAPPED )) { - *nr_pmdmapped =folio_nr_pages (folio); + *nr_pmdmapped =folio_large_nr_pages (folio); nr = *nr_pmdmapped - (nr &FOLIO_PAGES_MAPPED );/* Raced ahead of a remove and another add? */ if (unlikely (nr <0 ))
@@ -1418,14 +1418,11 @@ void folio_add_anon_rmap_pmd(struct folio *folio, struct page *page,void folio_add_new_anon_rmap (struct folio *folio,struct vm_area_struct *vma,unsigned long address,rmap_t flags) { -const int nr =folio_nr_pages (folio);const bool exclusive = flags &RMAP_EXCLUSIVE ; -int nr_pmdmapped =0 ; +int nr =1 , nr_pmdmapped =0 ;VM_WARN_ON_FOLIO (folio_test_hugetlb (folio), folio);VM_WARN_ON_FOLIO (!exclusive && !folio_test_locked (folio), folio); -VM_BUG_ON_VMA (address < vma->vm_start || - address + (nr <<PAGE_SHIFT ) > vma->vm_end, vma);/* * VM_DROPPABLE mappings don't swap; instead they're just dropped when
@@ -1443,6 +1440,7 @@ void folio_add_new_anon_rmap(struct folio *folio, struct vm_area_struct *vma, }else if (!folio_test_pmd_mappable (folio)) {int i; + nr =folio_large_nr_pages (folio);for (i =0 ; i < nr; i++) {struct page *page =folio_page (folio, i);
@@ -1456,6 +1454,7 @@ void folio_add_new_anon_rmap(struct folio *folio, struct vm_area_struct *vma,atomic_set (&folio->_large_mapcount, nr -1 );atomic_set (&folio->_nr_pages_mapped, nr); }else { + nr =folio_large_nr_pages (folio);/* increment count (starts at -1) */ atomic_set (&folio->_entire_mapcount,0 );/* increment count (starts at -1) */
@@ -1466,6 +1465,9 @@ void folio_add_new_anon_rmap(struct folio *folio, struct vm_area_struct *vma, nr_pmdmapped = nr; } +VM_WARN_ON_ONCE (address < vma->vm_start || + address + (nr <<PAGE_SHIFT ) > vma->vm_end); +__folio_mod_stat (folio, nr, nr_pmdmapped);mod_mthp_stat (folio_order (folio),MTHP_STAT_NR_ANON ,1 ); }
@@ -1557,7 +1559,7 @@ static __always_inline void __folio_remove_rmap(struct folio *folio,if (last) { nr =atomic_sub_return_relaxed (ENTIRELY_MAPPED , mapped);if (likely (nr <ENTIRELY_MAPPED )) { - nr_pmdmapped =folio_nr_pages (folio); + nr_pmdmapped =folio_large_nr_pages (folio); nr = nr_pmdmapped - (nr &FOLIO_PAGES_MAPPED );/* Raced ahead of another remove and an add? */ if (unlikely (nr <0 ))
Signature · 1 line
2.46.0
PATCH 4/17 mm: let _folio_nr_pages overlay memcg_data in first tail page
In reply to David HildenbrandLet's free up some more of the "unconditionally available on 64BIT" space in order-1 folios by letting _folio_nr_pages overlay memcg_data in the first tail page (second folio page). Consequently, we have the optimization now whenever we have CONFIG_MEMCG, independent of 64BIT.
We have to make sure that page->memcg on tail pages does not return "surprises". page_memcg_check() already properly refuses PageTail(). Let's do that earlier in print_page_owner_memcg() to avoid printing wrong "Slab cache page" information. No other code should touch that field on tail pages of compound pages.
Reset the "_nr_pages" to 0 when splitting folios, or when freeing them back to the buddy (to avoid false page->memcg_data "bad page" reports).
Note that in __split_huge_page(), folio_nr_pages() would stop working already as soon as we start messing with the subpages.
Most kernel configs should have at least CONFIG_MEMCG enabled, even if disabled at runtime. 64byte "struct memmap" is what we usually have on 64BIT.
While at it, rename "_folio_nr_pages" to "_nr_pages".
--- include/linux/mm.h | 4 ++-- include/linux/mm_types.h | 30 ++++++++++++++++++++++-------- mm/huge_memory.c | 8 ++++++++ mm/internal.h | 4 ++-- mm/page_alloc.c | 6 +++++- mm/page_owner.c | 2 +- 6 files changed, 40 insertions(+), 14 deletions(-)
include/linux/mm.h +2 -2
@@ -1078,8 +1078,8 @@ static inline unsigned int folio_large_order(const struct folio *folio)static inline long folio_large_nr_pages (const struct folio *folio) { -#ifdef CONFIG_64BIT -return folio->_folio_nr_pages; +#ifdef NR_PAGES_IN_LARGE_FOLIO +return folio->_nr_pages;#else return 1L <<folio_large_order (folio);#endif
include/linux/mm_types.h +22 -8
@@ -283,6 +283,11 @@ typedef struct {unsigned long val; } swp_entry_t; +#if defined(CONFIG_MEMCG ) || defined(CONFIG_SLAB_OBJ_EXT ) +/* We have some extra room after the refcount in tail pages. */ +#define NR_PAGES_IN_LARGE_FOLIO +#endif +/** * struct folio - Represents a contiguous set of bytes. * @flags: Identical to the page flags.
@@ -305,7 +310,7 @@ typedef struct {* @_large_mapcount: Do not use directly, call folio_mapcount(). * @_nr_pages_mapped: Do not use outside of rmap and debug code. * @_pincount: Do not use directly, call folio_maybe_dma_pinned(). -* @_folio_nr_pages: Do not use directly, call folio_nr_pages(). +* @_nr_pages: Do not use directly, call folio_nr_pages(). * @_hugetlb_subpool: Do not use directly, use accessor in hugetlb.h. * @_hugetlb_cgroup: Do not use directly, use accessor in hugetlb_cgroup.h. * @_hugetlb_cgroup_rsvd: Do not use directly, use accessor in hugetlb_cgroup.h.
@@ -366,13 +371,20 @@ struct folio {unsigned long _flags_1;unsigned long _head_1;/* public: */ -atomic_t _large_mapcount; -atomic_t _entire_mapcount; -atomic_t _nr_pages_mapped; -atomic_t _pincount; -#ifdef CONFIG_64BIT -unsigned int _folio_nr_pages; -#endif +union { +struct { +atomic_t _large_mapcount; +atomic_t _entire_mapcount; +atomic_t _nr_pages_mapped; +atomic_t _pincount; + }; +unsigned long _usable_1[4 ]; + }; +atomic_t _mapcount_1; +atomic_t _refcount_1; +#ifdef NR_PAGES_IN_LARGE_FOLIO +unsigned int _nr_pages; +#endif /* NR_PAGES_IN_LARGE_FOLIO */ /* private: the union with struct page is transitional */ };struct page __page_1;
@@ -424,6 +436,8 @@ FOLIO_MATCH(_last_cpupid, _last_cpupid); offsetof(struct page, pg) + sizeof(struct page))FOLIO_MATCH (flags, _flags_1);FOLIO_MATCH (compound_head, _head_1); +FOLIO_MATCH (_mapcount, _mapcount_1); +FOLIO_MATCH (_refcount, _refcount_1);#undef FOLIO_MATCH#define FOLIO_MATCH (pg, fl) \ static_assert(offsetof(struct folio, fl) == \
mm/huge_memory.c +8 -0
@@ -3171,6 +3171,14 @@ static void __split_huge_page(struct page *page, struct list_head *list,int order =folio_order (folio);unsigned int nr =1 << order; +/* +* Reset any memcg data overlay in the tail pages. folio_nr_pages() +* is unreliable after this point. +*/ +#ifdef NR_PAGES_IN_LARGE_FOLIO + folio->_nr_pages =0 ; +#endif +/* complete memcg works before add pages to LRU */ split_page_memcg (head, order, new_order);
mm/internal.h +2 -2
@@ -625,8 +625,8 @@ static inline void folio_set_order(struct folio *folio, unsigned int order)return ; folio->_flags_1 = (folio->_flags_1 & ~0xffUL ) | order; -#ifdef CONFIG_64BIT - folio->_folio_nr_pages =1U << order; +#ifdef NR_PAGES_IN_LARGE_FOLIO + folio->_nr_pages =1U << order;#endif }
mm/page_alloc.c +5 -1
@@ -1077,8 +1077,12 @@ __always_inline bool free_pages_prepare(struct page *page,if (unlikely (order)) {int i; -if (compound) +if (compound) { page[1 ].flags &= ~PAGE_FLAGS_SECOND ; +#ifdef NR_PAGES_IN_LARGE_FOLIO + ((struct folio *)page)->_nr_pages =0 ; +#endif + }for (i =1 ; i < (1 << order); i++) {if (compound) bad +=free_tail_page_prepare (page, page + i);
mm/page_owner.c +1 -1
@@ -507,7 +507,7 @@ static inline int print_page_owner_memcg(char *kbuf, size_t count, int ret,rcu_read_lock (); memcg_data =READ_ONCE (page->memcg_data); -if (!memcg_data) +if (!memcg_data ||PageTail (page)) goto out_unlock;if (memcg_data &MEMCG_DATA_OBJEXTS )
Signature · 1 line
2.46.0
PATCH 5/17 mm/rmap: pass dst_vma to page_try_dup_anon_rmap() and page_dup_file_rmap()
In reply to David HildenbrandWe'll need access to the destination MM when modifying the total mapcount of a non-hugetlb large folios next. So pass in the destination VMA.
--- include/linux/rmap.h | 42 +++++++++++++++++++++++++----------------- mm/huge_memory.c | 2 +- mm/memory.c | 10 +++++----- 3 files changed, 31 insertions(+), 23 deletions(-)
include/linux/rmap.h +25 -17
@@ -322,7 +322,8 @@ static inline void hugetlb_remove_rmap(struct folio *folio) } static __always_inline void __folio_dup_file_rmap(struct folio *folio, -struct page *page,int nr_pages,enum rmap_level level) +struct page *page,int nr_pages,struct vm_area_struct *dst_vma, +enum rmap_level level) {const int orig_nr_pages = nr_pages;
@@ -352,45 +353,47 @@ static __always_inline void __folio_dup_file_rmap(struct folio *folio,* @folio: The folio to duplicate the mappings of * @page: The first page to duplicate the mappings of * @nr_pages: The number of pages of which the mapping will be duplicated +* @dst_vma: The destination vm area * * The page range of the folio is defined by [page, page + nr_pages) * * The caller needs to hold the page table lock. */ static inline void folio_dup_file_rmap_ptes (struct folio *folio, -struct page *page,int nr_pages) +struct page *page,int nr_pages,struct vm_area_struct *dst_vma) { -__folio_dup_file_rmap (folio, page, nr_pages,RMAP_LEVEL_PTE ); +__folio_dup_file_rmap (folio, page, nr_pages, dst_vma,RMAP_LEVEL_PTE ); } static __always_inline void folio_dup_file_rmap_pte(struct folio *folio, -struct page *page) +struct page *page,struct vm_area_struct *dst_vma) { -__folio_dup_file_rmap (folio, page,1 ,RMAP_LEVEL_PTE ); +__folio_dup_file_rmap (folio, page,1 , dst_vma,RMAP_LEVEL_PTE ); }/** * folio_dup_file_rmap_pmd - duplicate a PMD mapping of a page range of a folio * @folio: The folio to duplicate the mapping of * @page: The first page to duplicate the mapping of +* @dst_vma: The destination vm area * * The page range of the folio is defined by [page, page + HPAGE_PMD_NR) * * The caller needs to hold the page table lock. */ static inline void folio_dup_file_rmap_pmd (struct folio *folio, -struct page *page) +struct page *page,struct vm_area_struct *dst_vma) {#ifdef CONFIG_TRANSPARENT_HUGEPAGE -__folio_dup_file_rmap (folio, page,HPAGE_PMD_NR ,RMAP_LEVEL_PTE ); +__folio_dup_file_rmap (folio, page,HPAGE_PMD_NR , dst_vma,RMAP_LEVEL_PTE );#else WARN_ON_ONCE (true);#endif } static __always_inline int __folio_try_dup_anon_rmap(struct folio *folio, -struct page *page,int nr_pages,struct vm_area_struct *src_vma, -enum rmap_level level) +struct page *page,int nr_pages,struct vm_area_struct *dst_vma, +struct vm_area_struct *src_vma,enum rmap_level level) {const int orig_nr_pages = nr_pages;bool maybe_pinned;
@@ -455,6 +458,7 @@ static __always_inline int __folio_try_dup_anon_rmap(struct folio *folio,* @folio: The folio to duplicate the mappings of * @page: The first page to duplicate the mappings of * @nr_pages: The number of pages of which the mapping will be duplicated +* @dst_vma: The destination vm area * @src_vma: The vm area from which the mappings are duplicated * * The page range of the folio is defined by [page, page + nr_pages)
@@ -473,16 +477,18 @@ static __always_inline int __folio_try_dup_anon_rmap(struct folio *folio,* Returns 0 if duplicating the mappings succeeded. Returns -EBUSY otherwise. */ static inline int folio_try_dup_anon_rmap_ptes (struct folio *folio, -struct page *page,int nr_pages,struct vm_area_struct *src_vma) +struct page *page,int nr_pages,struct vm_area_struct *dst_vma, +struct vm_area_struct *src_vma) { -return __folio_try_dup_anon_rmap (folio, page, nr_pages, src_vma, -RMAP_LEVEL_PTE ); +return __folio_try_dup_anon_rmap (folio, page, nr_pages, dst_vma, + src_vma,RMAP_LEVEL_PTE ); } static __always_inline int folio_try_dup_anon_rmap_pte(struct folio *folio, -struct page *page,struct vm_area_struct *src_vma) +struct page *page,struct vm_area_struct *dst_vma, +struct vm_area_struct *src_vma) { -return __folio_try_dup_anon_rmap (folio, page,1 , src_vma, +return __folio_try_dup_anon_rmap (folio, page,1 , dst_vma, src_vma,RMAP_LEVEL_PTE ); }
@@ -491,6 +497,7 @@ static __always_inline int folio_try_dup_anon_rmap_pte(struct folio *folio,* of a folio * @folio: The folio to duplicate the mapping of * @page: The first page to duplicate the mapping of +* @dst_vma: The destination vm area * @src_vma: The vm area from which the mapping is duplicated * * The page range of the folio is defined by [page, page + HPAGE_PMD_NR)
@@ -509,11 +516,12 @@ static __always_inline int folio_try_dup_anon_rmap_pte(struct folio *folio,* Returns 0 if duplicating the mapping succeeded. Returns -EBUSY otherwise. */ static inline int folio_try_dup_anon_rmap_pmd (struct folio *folio, -struct page *page,struct vm_area_struct *src_vma) +struct page *page,struct vm_area_struct *dst_vma, +struct vm_area_struct *src_vma) {#ifdef CONFIG_TRANSPARENT_HUGEPAGE -return __folio_try_dup_anon_rmap (folio, page,HPAGE_PMD_NR , src_vma, -RMAP_LEVEL_PMD ); +return __folio_try_dup_anon_rmap (folio, page,HPAGE_PMD_NR , dst_vma, + src_vma,RMAP_LEVEL_PMD );#else WARN_ON_ONCE (true);return -EBUSY ;
mm/huge_memory.c +1 -1
@@ -1642,7 +1642,7 @@ int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm, src_folio =page_folio (src_page);folio_get (src_folio); -if (unlikely (folio_try_dup_anon_rmap_pmd (src_folio, src_page, src_vma))) { +if (unlikely (folio_try_dup_anon_rmap_pmd (src_folio, src_page, dst_vma, src_vma))) {/* Page maybe pinned: split and retry the fault on PTEs. */ folio_put (src_folio);pte_free (dst_mm, pgtable);
mm/memory.c +5 -5
@@ -856,7 +856,7 @@ copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,folio_get (folio); rss[mm_counter (folio)]++;/* Cannot fail as these pages cannot get pinned. */ -folio_try_dup_anon_rmap_pte (folio, page, src_vma); +folio_try_dup_anon_rmap_pte (folio, page, dst_vma, src_vma);/* * We do not preserve soft-dirty information, because so
@@ -1007,14 +1007,14 @@ copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vmafolio_ref_add (folio, nr);if (folio_test_anon (folio)) {if (unlikely (folio_try_dup_anon_rmap_ptes (folio, page, - nr, src_vma))) { + nr, dst_vma, src_vma))) {folio_ref_sub (folio, nr);return -EAGAIN ; } rss[MM_ANONPAGES ] += nr;VM_WARN_ON_FOLIO (PageAnonExclusive (page), folio); }else { -folio_dup_file_rmap_ptes (folio, page, nr); +folio_dup_file_rmap_ptes (folio, page, nr, dst_vma); rss[mm_counter_file (folio)] += nr; }if (any_writable)
@@ -1032,7 +1032,7 @@ copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma* guarantee the pinned page won't be randomly replaced in the * future. */ -if (unlikely (folio_try_dup_anon_rmap_pte (folio, page, src_vma))) { +if (unlikely (folio_try_dup_anon_rmap_pte (folio, page, dst_vma, src_vma))) {/* Page may be pinned, we have to copy. */ folio_put (folio); err = copy_present_page(dst_vma, src_vma, dst_pte, src_pte,
@@ -1042,7 +1042,7 @@ copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma rss[MM_ANONPAGES ]++;VM_WARN_ON_FOLIO (PageAnonExclusive (page), folio); }else { -folio_dup_file_rmap_pte (folio, page); +folio_dup_file_rmap_pte (folio, page, dst_vma); rss[mm_counter_file (folio)]++; }
Signature · 1 line
2.46.0
PATCH 6/17 mm/rmap: pass vma to __folio_add_rmap()
In reply to David HildenbrandWe'll need access to the destination MM when modifying the total mapcount of a non-hugetlb large folios next. So pass in the VMA.
--- mm/rmap.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
mm/rmap.c +4 -4
@@ -1153,8 +1153,8 @@ int pfn_mkclean_range(unsigned long pfn, unsigned long nr_pages, pgoff_t pgoff, } static __always_inline unsigned int __folio_add_rmap(struct folio *folio, -struct page *page,int nr_pages,enum rmap_level level, -int *nr_pmdmapped) +struct page *page,int nr_pages,struct vm_area_struct *vma, +enum rmap_level level,int *nr_pmdmapped) {atomic_t *mapped = &folio->_nr_pages_mapped;const int orig_nr_pages = nr_pages;
@@ -1314,7 +1314,7 @@ static __always_inline void __folio_add_anon_rmap(struct folio *folio,VM_WARN_ON_FOLIO (!folio_test_anon (folio), folio); - nr =__folio_add_rmap (folio, page, nr_pages, level, &nr_pmdmapped); + nr =__folio_add_rmap (folio, page, nr_pages, vma, level, &nr_pmdmapped);if (likely (!folio_test_ksm (folio)))__page_check_anon_rmap (folio, page, vma, address);
@@ -1480,7 +1480,7 @@ static __always_inline void __folio_add_file_rmap(struct folio *folio,VM_WARN_ON_FOLIO (folio_test_anon (folio), folio); - nr =__folio_add_rmap (folio, page, nr_pages, level, &nr_pmdmapped); + nr =__folio_add_rmap (folio, page, nr_pages, vma, level, &nr_pmdmapped);__folio_mod_stat (folio, nr, nr_pmdmapped);/* See comments in folio_add_anon_rmap_*() */
Signature · 1 line
2.46.0
PATCH 7/17 mm/rmap: abstract large mapcount operations for large folios (!hugetlb)
In reply to David HildenbrandLet's abstract the operations so we can extend these operations easily.
--- include/linux/rmap.h | 39 +++++++++++++++++++++++++++++++++++---- mm/rmap.c | 14 ++++++-------- 2 files changed, 41 insertions(+), 12 deletions(-)
include/linux/rmap.h +35 -4
@@ -173,6 +173,37 @@ static inline void anon_vma_merge(struct vm_area_struct *vma,struct anon_vma *folio_get_anon_vma (struct folio *folio); +static inline void folio_set_large_mapcount (struct folio *folio,int mapcount, +struct vm_area_struct *vma) +{ +/* Note: mapcounts start at -1. */ +atomic_set (&folio->_large_mapcount, mapcount -1 ); +} + +static inline void folio_add_large_mapcount (struct folio *folio, +int diff,struct vm_area_struct *vma) +{ +atomic_add (diff, &folio->_large_mapcount); +} + +static inline void folio_inc_large_mapcount (struct folio *folio, +struct vm_area_struct *vma) +{ +atomic_inc (&folio->_large_mapcount); +} + +static inline void folio_sub_large_mapcount (struct folio *folio, +int diff,struct vm_area_struct *vma) +{ +atomic_sub (diff, &folio->_large_mapcount); +} + +static inline void folio_dec_large_mapcount (struct folio *folio, +struct vm_area_struct *vma) +{ +atomic_dec (&folio->_large_mapcount); +} +/* RMAP flags, currently only relevant for some anon rmap operations. */ typedef int __bitwise rmap_t ;
@@ -339,11 +370,11 @@ static __always_inline void __folio_dup_file_rmap(struct folio *folio,do {atomic_inc (&page->_mapcount); }while (page++, --nr_pages >0 ); -atomic_add (orig_nr_pages, &folio->_large_mapcount); +folio_add_large_mapcount (folio, orig_nr_pages, dst_vma);break ;case RMAP_LEVEL_PMD :atomic_inc (&folio->_entire_mapcount); -atomic_inc (&folio->_large_mapcount); +folio_inc_large_mapcount (folio, dst_vma);break ; } }
@@ -437,7 +468,7 @@ static __always_inline int __folio_try_dup_anon_rmap(struct folio *folio,ClearPageAnonExclusive (page);atomic_inc (&page->_mapcount); }while (page++, --nr_pages >0 ); -atomic_add (orig_nr_pages, &folio->_large_mapcount); +folio_add_large_mapcount (folio, orig_nr_pages, dst_vma);break ;case RMAP_LEVEL_PMD :if (PageAnonExclusive (page)) {
@@ -446,7 +477,7 @@ static __always_inline int __folio_try_dup_anon_rmap(struct folio *folio,ClearPageAnonExclusive (page); }atomic_inc (&folio->_entire_mapcount); -atomic_inc (&folio->_large_mapcount); +folio_inc_large_mapcount (folio, dst_vma);break ; }return 0 ;
mm/rmap.c +6 -8
@@ -1177,7 +1177,7 @@ static __always_inline unsigned int __folio_add_rmap(struct folio *folio, atomic_add_return_relaxed(first, mapped) < ENTIRELY_MAPPED) nr = first; -atomic_add (orig_nr_pages, &folio->_large_mapcount); +folio_add_large_mapcount (folio, orig_nr_pages, vma);break ;case RMAP_LEVEL_PMD : first =atomic_inc_and_test (&folio->_entire_mapcount);
@@ -1194,7 +1194,7 @@ static __always_inline unsigned int __folio_add_rmap(struct folio *folio, nr =0 ; } } -atomic_inc (&folio->_large_mapcount); +folio_inc_large_mapcount (folio, vma);break ; }return nr;
@@ -1450,15 +1450,13 @@ void folio_add_new_anon_rmap(struct folio *folio, struct vm_area_struct *vma,SetPageAnonExclusive (page); } -/* increment count (starts at -1) */ -atomic_set (&folio->_large_mapcount, nr -1 ); +folio_set_large_mapcount (folio, nr, vma);atomic_set (&folio->_nr_pages_mapped, nr); }else { nr =folio_large_nr_pages (folio);/* increment count (starts at -1) */ atomic_set (&folio->_entire_mapcount,0 ); -/* increment count (starts at -1) */ -atomic_set (&folio->_large_mapcount,0 ); +folio_set_large_mapcount (folio,1 , vma);atomic_set (&folio->_nr_pages_mapped,ENTIRELY_MAPPED );if (exclusive)SetPageAnonExclusive (&folio->page);
@@ -1542,7 +1540,7 @@ static __always_inline void __folio_remove_rmap(struct folio *folio,break ; } -atomic_sub (nr_pages, &folio->_large_mapcount); +folio_sub_large_mapcount (folio, nr_pages, vma);do { last +=atomic_add_negative (-1 , &page->_mapcount); }while (page++, --nr_pages >0 );
@@ -1554,7 +1552,7 @@ static __always_inline void __folio_remove_rmap(struct folio *folio, partially_mapped = nr &&atomic_read (mapped);break ;case RMAP_LEVEL_PMD : -atomic_dec (&folio->_large_mapcount); +folio_dec_large_mapcount (folio, vma); last =atomic_add_negative (-1 , &folio->_entire_mapcount);if (last) { nr =atomic_sub_return_relaxed (ENTIRELY_MAPPED , mapped);
Signature · 1 line
2.46.0
PATCH 8/17 mm/rmap: initial MM owner tracking for large folios (!hugetlb)
In reply to David HildenbrandLet's track for each large folio (excluding hugetlb for now) whether it is certainly mapped exclusively (mapped by a single MM), or whether it may be mapped shared (mapped by multiple MMs).
In an ideal world, we'd have a more precise "mapped exclusively" vs. "mapped shared" tracking -- avoiding the "maybe" part -- but the approaches to achieve that are a bit more involve, and we are going to start with something simple so we can also make progress on per-page mapcount removal. We can later easily exchange the tracking mechanism.
We'll use this information next to optimize COW reuse for PTE-mapped anonymous THP, and implement folio_likely_mapped_shared() in kernel configuration where the per-page mapcounts in large folios are no longer maintained. We could start doing the MM owner tracking for anonymous folios initially (COW reuse only applies to anon folios), but we'll keep it simple and just do it also for pagecache folios: the new tracking must be manually enabled via a kconfig option for now.
64bit only, because we cannot easily squeeze more stuff into the "struct folio" of order-1 folios. 32bit might be possible in the future, for example when limiting order-1 folios to 64bit only.
We'll remember for each large folio for two MMs that currently map this folio, how often they are mapping folio pages (mapcount). As long as a folio is unmapped or exclusively mapped, another MM can take a free spot. We won't allow to take a free spot if the folio is not mapped
exclusively: primarily to avoid some corner cases where some mappings of a MM are tracked via the slot, and others not (identified while working on this).
In addition, we'll remember the current state (exclusive/shared) and use a bit spinlock to sync on updates, and to require only a single atomic operation for our updates. Using a bit spinlock is not ideal, but there are not that many easy alternatives. We might be able to squeeze an arch_spin_lock into the "struct folio" later, for now keep it simple. RT is out of the picture with THP, and we can always optimize this later.
As we have to squeeze this information into the "struct folio" of even folios of order-1 (2 pages), and we generally want to reduce the required metadata, we'll assign each MM a unique ID that consumes less than 32 bit. We'll limit the IDs to 20bit / 1M for now: we could allow for up to 30bit, but getting even 1M IDs is unlikely in practice. If required, we could raise the limit later, and the 1M limit might come in handy in the future with other tracking approaches.
There won't be any false "mapped shared" detection as long as only two MMs map pages of a folio at one point in time -- for example with fork() and short-lived child processes, or with apps that hand over state from one instance to another, like live-migrating VMs on the same host, effectively migrating guest RAM via a mmap'ed files.
As soon as three MMs are involved at the same time, we might detect "mapped shared" although the folio is now "mapped exclusively". Example:
(1) App1 faults in a (shmem/file-backed) folio -> Tracked as MM0
(2) App2 faults in the same folio -> Tracked as MM1
(3) App3 faults in the same folio -> Cannot be tracked separately
(4) App1 and App2 unmap the folio.
(5) We'll still detect "shared" even though only App3 maps the folio.
With multiple processes, this might have the potential to result in unexpected owner changes, when migrating pages or when faulting them in:
assume a parent process fork()'s two short-lived child processes. We would expect that the parent always remains tracked under MM0, but it could be that at some point both child processes are tracked instead. For file-backed memory, reclaim+refault can trigger something similar.
Keep compilation for the vdso32 hack working by un-defining CONFIG_MM_ID like we for CONFIG_64BIT.
Make use of __always_inline to keep possible performance degradation when (un)mapping large folios to a minimum.
--- Documentation/mm/transhuge.rst | 8 ++ arch/x86/entry/vdso/vdso32/fake_32bit_build.h | 1 + include/linux/mm_types.h | 23 ++++ include/linux/page-flags.h | 41 ++++++ include/linux/rmap.h | 126 ++++++++++++++++++ kernel/fork.c | 36 +++++ mm/Kconfig | 11 ++ mm/huge_memory.c | 6 + mm/internal.h | 6 + mm/page_alloc.c | 10 ++ 10 files changed, 268 insertions(+)
Documentation/mm/transhuge.rst +8 -0
@@ -120,11 +120,19 @@ pages: and also increment/decrement folio->_nr_pages_mapped by ENTIRELY_MAPPED when _entire_mapcount goes from -1 to 0 or 0 to -1. + With CONFIG_MM_ID, we also maintain the two slots for tracking MM + owners (MM ID and corresponding mapcount), and the current status + ("mapped shared" vs. "mapped exclusively"). + - map/unmap of individual pages with PTE entry increment/decrement page->_mapcount, increment/decrement folio->_large_mapcount and also increment/decrement folio->_nr_pages_mapped when page->_mapcount goes from -1 to 0 or 0 to -1 as this counts the number of pages mapped by PTE. + With CONFIG_MM_ID, we also maintain the two slots for tracking MM + owners (MM ID and corresponding mapcount), and the current status + ("mapped shared" vs. "mapped exclusively"). + split_huge_page internally has to distribute the refcounts in the head page to the tail pages before clearing all PG_head/tail bits from the page structures. It can be done easily for refcounts taken by page table
arch/x86/entry/vdso/vdso32/fake_32bit_build.h +1 -0
@@ -13,6 +13,7 @@#undef CONFIG_SPARSEMEM_VMEMMAP#undef CONFIG_NR_CPUS#undef CONFIG_PARAVIRT_XXL +#undef CONFIG_MM_ID#define CONFIG_X86_32 1#define CONFIG_PGTABLE_LEVELS 2
include/linux/mm_types.h +23 -0
@@ -311,6 +311,9 @@ typedef struct {* @_nr_pages_mapped: Do not use outside of rmap and debug code. * @_pincount: Do not use directly, call folio_maybe_dma_pinned(). * @_nr_pages: Do not use directly, call folio_nr_pages(). +* @_mm0_mapcount: Do not use outside of rmap code. +* @_mm1_mapcount: Do not use outside of rmap code. +* @_mm_ids: Do not use outside of rmap code. * @_hugetlb_subpool: Do not use directly, use accessor in hugetlb.h. * @_hugetlb_cgroup: Do not use directly, use accessor in hugetlb_cgroup.h. * @_hugetlb_cgroup_rsvd: Do not use directly, use accessor in hugetlb_cgroup.h.
@@ -377,6 +380,11 @@ struct folio {atomic_t _entire_mapcount;atomic_t _nr_pages_mapped;atomic_t _pincount; +#ifdef CONFIG_MM_ID +int _mm0_mapcount; +int _mm1_mapcount; +unsigned long _mm_ids; +#endif /* CONFIG_MM_ID */ };unsigned long _usable_1[4 ]; };
@@ -1044,6 +1052,9 @@ struct mm_struct { #endif } lru_gen;#endif /* CONFIG_LRU_GEN_WALKS_MMU */ +#ifdef CONFIG_MM_ID +unsigned int mm_id; +#endif } __randomize_layout;/*
@@ -1053,6 +1064,18 @@ struct mm_struct {unsigned long cpu_bitmap[]; }; +#ifdef CONFIG_MM_ID +/* +* For init_mm and friends, we don't allocate an ID and use the dummy value +* instead. Limit ourselves to 1M MMs for now: even though we might support +* up to 4M PIDs, having more than 1M MM instances is highly unlikely. +*/ +#define MM_ID_DUMMY 0 +#define MM_ID_NR_BITS 20 +#define MM_ID_MIN (MM_ID_DUMMY + 1) +#define MM_ID_MAX ((1U << MM_ID_NR_BITS) - 1) +#endif /* CONFIG_MM_ID */ +#define MM_MT_FLAGS (MT_FLAGS_ALLOC_RANGE | MT_FLAGS_LOCK_EXTERN | \ MT_FLAGS_USE_RCU)extern struct mm_struct init_mm;
include/linux/page-flags.h +41 -0
53 lines not on this page · raw message
include/linux/rmap.h +126 -0
138 lines not on this page · raw message
kernel/fork.c +36 -0
@@ -813,6 +813,36 @@ static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)#define mm_free_pgd (mm)#endif /* CONFIG_MMU */ +#ifdef CONFIG_MM_ID +static DEFINE_IDA (mm_ida); + +static inline int mm_alloc_id (struct mm_struct *mm) +{ +int ret; + + ret =ida_alloc_range (&mm_ida,MM_ID_MIN ,MM_ID_MAX ,GFP_KERNEL ); +if (ret <0 ) +return ret; + mm->mm_id = ret; +return 0 ; +} + +static inline void mm_free_id (struct mm_struct *mm) +{ +const int id = mm->mm_id; + + mm->mm_id =MM_ID_DUMMY ; +if (id ==MM_ID_DUMMY ) +return ; +if (WARN_ON_ONCE (id <MM_ID_MIN || id >MM_ID_MAX )) +return ; +ida_free (&mm_ida, id); +} +#else +static inline int mm_alloc_id (struct mm_struct *mm) {return 0 ; } +static inline void mm_free_id (struct mm_struct *mm) {} +#endif +static void check_mm (struct mm_struct *mm) {int i;
@@ -916,6 +946,7 @@ void __mmdrop(struct mm_struct *mm)WARN_ON_ONCE (mm == current->active_mm);mm_free_pgd (mm); +mm_free_id (mm);destroy_context (mm);mmu_notifier_subscriptions_destroy (mm);check_mm (mm);
@@ -1293,6 +1324,9 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,if (mm_alloc_pgd (mm)) goto fail_nopgd; +if (mm_alloc_id (mm)) + goto fail_noid; +if (init_new_context (p, mm)) goto fail_nocontext;
@@ -1312,6 +1346,8 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p, fail_cid:destroy_context (mm); fail_nocontext: +mm_free_id (mm); +fail_noid:mm_free_pgd (mm); fail_nopgd:free_mm (mm);
mm/Kconfig +11 -0
@@ -846,6 +846,17 @@ choice enabled at runtime via sysfs. endchoice +config MM_ID + bool "MM ID tracking" + depends on TRANSPARENT_HUGEPAGE && 64BIT + help + Use unique per-MM IDs to track whether large allocations, such + as transparent huge pages, that span multiple physical pages + are "mapped shared" or "mapped exclusively" into user page tables. + This information is useful to determine the current owner of such a + large allocation, for example, helpful for the Copy-On-Write reuse + optimization. + config THP_SWAP def_bool y depends on TRANSPARENT_HUGEPAGE && ARCH_WANTS_THP_SWAP && SWAP && 64BIT
mm/huge_memory.c +6 -0
@@ -3193,6 +3193,12 @@ static void __split_huge_page(struct page *page, struct list_head *list,ClearPageHasHWPoisoned (head); +#ifdef CONFIG_MM_ID +if (!new_order) +/* Make sure page->private on the second page is 0. */ + folio->_mm_ids =0 ; +#endif +for (i = nr - new_nr; i >= new_nr; i -= new_nr) {__split_huge_page_tail (folio, i, lruvec, list, new_order);/* Some pages can be beyond EOF: drop them from page cache */
mm/internal.h +6 -0
@@ -665,6 +665,12 @@ static inline void prep_compound_head(struct page *page, unsigned int order)atomic_set (&folio->_entire_mapcount,-1 );atomic_set (&folio->_nr_pages_mapped,0 );atomic_set (&folio->_pincount,0 ); +#ifdef CONFIG_MM_ID + folio->_mm0_mapcount =-1 ; + folio->_mm1_mapcount =-1 ; + folio->_mm_ids =0 ; +folio_set_large_mapped_exclusively (folio); +#endif if (order >1 )INIT_LIST_HEAD (&folio->_deferred_list); }
mm/page_alloc.c +10 -0
@@ -959,6 +959,16 @@ static int free_tail_page_prepare(struct page *head_page, struct page *page)bad_page (page,"nonzero pincount" ); goto out; } +#ifdef CONFIG_MM_ID +if (unlikely (folio->_mm0_mapcount +1 )) { +bad_page (page,"nonzero _mm0_mapcount" ); + goto out; + } +if (unlikely (folio->_mm1_mapcount +1 )) { +bad_page (page,"nonzero _mm1_mapcount" ); + goto out; + } +#endif break ;case 2 :/* the second tail page: deferred_list overlaps ->mapping */
Signature · 1 line
2.46.0
PATCH 9/17 bit_spinlock: __always_inline (un)lock functions
In reply to David HildenbrandThe compiler might decide that it is a smart idea to not inline bit_spin_lock(), primarily when a couple of functions in the same file end up calling it. Especially when used in RMAP context, this can negatively affect fork() performance, where each additional function call is noticeable.
Let's simply flag all lock/unlock functions as __always_inline; arch_test_and_set_bit_lock() and friends are already tagged like that (but not test_and_set_bit_lock() for some reason).
If ever a problem, we could split it into a fast and a slow path, and only force the fast path to be inlined. But there is nothing particularly "big" here.
--- include/linux/bit_spinlock.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
include/linux/bit_spinlock.h +4 -4
@@ -13,7 +13,7 @@* Don't use this unless you really need to: spin_lock() and spin_unlock() * are significantly faster. */ -static inline void bit_spin_lock (int bitnum,unsigned long *addr) +static __always_inline void bit_spin_lock(int bitnum, unsigned long *addr) {/* * Assuming the lock is uncontended, this never enters
@@ -38,7 +38,7 @@ static inline void bit_spin_lock(int bitnum, unsigned long *addr)/* * Return true if it was acquired */ -static inline int bit_spin_trylock (int bitnum,unsigned long *addr) +static __always_inline int bit_spin_trylock(int bitnum, unsigned long *addr) {preempt_disable ();#if defined(CONFIG_SMP ) || defined(CONFIG_DEBUG_SPINLOCK )
@@ -54,7 +54,7 @@ static inline int bit_spin_trylock(int bitnum, unsigned long *addr)/* * bit-based spin_unlock() */ -static inline void bit_spin_unlock (int bitnum,unsigned long *addr) +static __always_inline void bit_spin_unlock(int bitnum, unsigned long *addr) {#ifdef CONFIG_DEBUG_SPINLOCK BUG_ON (!test_bit (bitnum, addr));
@@ -71,7 +71,7 @@ static inline void bit_spin_unlock(int bitnum, unsigned long *addr)* non-atomic version, which can be used eg. if the bit lock itself is * protecting the rest of the flags in the word. */ -static inline void __bit_spin_unlock (int bitnum,unsigned long *addr) +static __always_inline void __bit_spin_unlock(int bitnum, unsigned long *addr) {#ifdef CONFIG_DEBUG_SPINLOCK BUG_ON (!test_bit (bitnum, addr));
Signature · 1 line
2.46.0
PATCH 10/17 mm: COW reuse support for PTE-mapped THP with CONFIG_MM_ID
In reply to David HildenbrandLet's add support for CONFIG_MM_ID. The implementation is fairly straight forward: if exclusively mapped, make sure that all references are from mappings.
There are plenty of things we can optimize in the future: For example, we could remember that the folio is fully exclusive so we could speedup the next fault further. Also, we could try "faulting around", turning surrounding PTEs that map the same folio writable. But especially the latter might increase COW latency, so it would need further investigation.
--- mm/memory.c | 87 ++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 79 insertions(+), 8 deletions(-)
mm/memory.c +79 -8
@@ -3564,19 +3564,90 @@ static vm_fault_t wp_page_shared(struct vm_fault *vmf, struct folio *folio)return ret; } -static bool wp_can_reuse_anon_folio (struct folio *folio, -struct vm_area_struct *vma) +#ifdef CONFIG_MM_ID +static bool __wp_can_reuse_large_anon_folio (struct folio *folio, +struct vm_area_struct *vma) { +bool exclusive = false; + +/* Let's just free up a large folio if only a single page is mapped. */ +if (folio_large_mapcount (folio) <=1 ) +return false; +/* -* We could currently only reuse a subpage of a large folio if no -* other subpages of the large folios are still mapped. However, -* let's just consistently not reuse subpages even if we could -* reuse in that scenario, and give back a large folio a bit -* sooner. +* The assumption for anonymous folios is that each page can only get +* mapped once into each MM. The only exception are KSM folios, which +* are always small. +* +* Each taken mapcount must be paired with exactly one taken reference, +* whereby the refcount must be incremented before the mapcount when +* mapping a page, and the refcount must be decremented after the +* mapcount when unmapping a page. +* +* If all folio references are from mappings, and all mappings are in +* the page tables of this MM, then this folio is exclusive to this MM. */ -if (folio_test_large (folio)) +if (!folio_test_large_mapped_exclusively (folio)) +return false; + +VM_WARN_ON_ONCE (folio_test_ksm (folio)); +VM_WARN_ON_ONCE (folio_mapcount (folio) >folio_nr_pages (folio)); +VM_WARN_ON_ONCE (folio_entire_mapcount (folio)); + +if (unlikely (folio_test_swapcache (folio))) { +/* +* Note: freeing up the swapcache will fail if some PTEs are +* still swap entries. +*/ +if (!folio_trylock (folio)) +return false; +folio_free_swap (folio); +folio_unlock (folio); + } + +if (folio_large_mapcount (folio) !=folio_ref_count (folio))return false; +/* Stabilize the mapcount vs. refcount and recheck. */ +folio_lock_large_mapcount_data (folio); +VM_WARN_ON_ONCE (folio_large_mapcount (folio) <folio_ref_count (folio)); + +if (!folio_test_large_mapped_exclusively (folio)) + goto unlock; +if (folio_large_mapcount (folio) !=folio_ref_count (folio)) + goto unlock; + +VM_WARN_ON_ONCE (folio_mm0_id (folio) != vma->vm_mm->mm_id && +folio_mm1_id (folio) != vma->vm_mm->mm_id); + +/* +* Do we need the folio lock? Likely not. If there would have been +* references from page migration/swapout, we would have detected +* an additional folio reference and never ended up here. +*/ + exclusive = true; +unlock: +folio_unlock_large_mapcount_data (folio); +return exclusive; +} +#else /* !CONFIG_MM_ID */ +static bool __wp_can_reuse_large_anon_folio (struct folio *folio, +struct vm_area_struct *vma) +{ +/* +* We could reuse the last mapped page of a large folio, but let's +* just free up this large folio. +*/ +return false; +} +#endif /* !CONFIG_MM_ID */ + +static bool wp_can_reuse_anon_folio (struct folio *folio, +struct vm_area_struct *vma) +{ +if (folio_test_large (folio)) +return __wp_can_reuse_large_anon_folio (folio, vma); +/* * We have to verify under folio lock: these early checks are * just an optimization to avoid locking the folio and freeing
Signature · 1 line
2.46.0
PATCH 11/17 mm: CONFIG_NO_PAGE_MAPCOUNT to prepare for not maintain per-page mapcounts in large folios
In reply to David HildenbrandWe're close to the finishing line: let's introduce a new CONFIG_NO_PAGE_MAPCOUNT config option where we will incrementally remove any dependencies on per-page mapcounts in large folios. Once that's done, we'll stop maintaining the per-page mapcounts with this config option enabled.
CONFIG_NO_PAGE_MAPCOUNT will be EXPERIMENTAL for now, as we'll have to learn about some of the real world impact of some of the implications.
As writing "!CONFIG_NO_PAGE_MAPCOUNT" is really nasty, let's introduce a helper config option "CONFIG_PAGE_MAPCOUNT" that expresses the negation.
--- mm/Kconfig | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+)
mm/Kconfig +20 -0
@@ -878,8 +878,28 @@ config READ_ONLY_THP_FOR_FS support of file THPs will be developed in the next few release cycles. +config NO_PAGE_MAPCOUNT + bool "No per-page mapcount (EXPERIMENTAL)" + depends on TRANSPARENT_HUGEPAGE && MM_ID + help + Do not maintain per-page mapcounts for pages part of larger + allocations, such as transparent huge pages. + + When this config option is enabled, some interfaces that relied on + this information will rely on less-precise per-folio information + instead: for example, using the average per-page mapcount in such + a large allocation instead of the per-page mapcount. + + EXPERIMENTAL because the severity of some of the implications first + have to be understood properly. + endif # TRANSPARENT_HUGEPAGE +# simple helper to make the code a bit easier to read +config PAGE_MAPCOUNT + def_bool y + depends on !NO_PAGE_MAPCOUNT + # # The architecture supports pgtable leaves that is larger than PAGE_SIZE #
Signature · 1 line
2.46.0
PATCH 12/17 mm: remove per-page mapcount dependency in folio_likely_mapped_shared() (CONFIG_NO_PAGE_MAPCOUNT)
In reply to David HildenbrandLet's remove the dependency on the mapcount of the first folio page in large folios and consequently any "false negatives" from folio_likely_mapped_shared().
In theory, we could implement this change only with CONFIG_MM_ID, without gluing it to another config option. But we'll be a bit careful for the time being, because folio_likely_mapped_shared() can now return "false positives" more frequently. Glue it to CONFIG_NO_PAGE_MAPCOUNT, which expresses the "EXPERIMENTAL" character for now.
Let's reuse our new MM ownership tracking infrastructure for large folios. Thoroughly document the changed semantics. We might now detect that a folio as "mapped shared" although it no longer is -- this can only happen if more than two MMs mapped a folio at the same time, and neither of the first two is the last one mapping the folio.
"false positives" in this context are certainly better than "false negatives" when it comes to enforcing policies (e.g., is process 1 allowed to migrate a folio that might also be used by another process?), but in an ideal world we wouldn't have these "false positives" either.
It's worth noting that there will not be a change for small folios and hugetlb folios. In general, for PMD-mapped THP we don't expect a change, only for PTE-mapped THP.
This will affect various users of folio_likely_mapped_shared():
(1) khugepaged counts PTEs that target shared folios towards the max_ptes_shared. With false positives we might collapse too little, with false negatives too much.
(2) NUMA hinting: PROT_NONE NUMA protection will be skipped for shared folios in COW mappings. With false positives we skip too many, with false negatives we don't skip some we should be skipping.
During NUMA hinting faults, we will set TNF_SHARED with shared folios in shared mappings. With false positives we set it too often, with false negatives not often enough.
During NUMA hinting faults, we will reject to migrate shared folios in mappings with execute permissions (expectation: shared libraries). With false positives we reject to migrate some, with false negatives we migrate too many.
(3) MADV_COLD / MADV_PAGEOUT / MADV_FREE will not try splitting PTE-mapped THPs that are considered shared but not fully covered by the requested range, consequently not processing them. With false positives we will not split+process some we could have processed, with false negatives we split some folios we probably shouldn't have split.
(4) mbind() / migrate_pages() / move_pages() will refuse to migrate shared folios unless MPOL_MF_MOVE_ALL is effective (requires CAP_SYS_NICE). With false positives we reject to migrate some folios that could be migrated, with false negatives we migrate some folios that shouldn't have been migrated.
(5) folio_referenced_one() will skip exclusive swapbacked folios in dying processes. Shared folios will not be skipped. With false positives we might skip this optimization, with false negatives we might apply this optimization wrongly.
Likely (3) and (4) are not really used a lot on folios that are heavily shared among processes -- rather on anonymous memory (mostly from a single parent process) or almost-exclusively mmap'ed files.
Similarly (1) is not expected to matter much in practice, and if so, only for long-running child processes after fork(). But even here, it's unlikely that it matters in practice.
(5) is not expected to matter much at all, it's a new optimization either way.
(2) is interesting: the expectation here is that for anon folios it might not make a big difference. For file-backed pages it might, we'll have to learn about that.
Long story short: this paves the way for a complete CONFIG_NO_PAGE_MAPCOUNT implementation, but maybe we'll have to switch to another MM ownership tracking later.
--- include/linux/mm.h | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-)
include/linux/mm.h +18 -6
@@ -2142,9 +2142,9 @@ static inline size_t folio_size(const struct folio *folio)* are independent. * * As precise information is not easily available for all folios, this function -* estimates the number of MMs ("sharers") that are currently mapping a folio -* using the number of times the first page of the folio is currently mapped -* into page tables. +* must sometimes estimate the number of MMs ("sharers") that are currently +* mapping a folio using the number of times the first page of the folio is +* currently mapped into page tables. * * For small anonymous folios and anonymous hugetlb folios, the return * value will be exactly correct: non-KSM folios can only be mapped at most once
@@ -2152,13 +2152,21 @@ static inline size_t folio_size(const struct folio *folio)* considered shared even if mapped multiple times into the same MM. * * For other folios, the result can be fuzzy: -* #. For partially-mappable large folios (THP), the return value can wrongly -* indicate "mapped exclusively" (false negative) when the folio is -* only partially mapped into at least one MM. +* #. With CONFIG_PAGE_MAPCOUNT: For partially-mappable large folios (THP), +* the return value can wrongly indicate "mapped exclusively" (false +* negative) when the folio is only partially mapped into at least one MM. +* #. With CONFIG_NO_PAGE_MAPCOUNT: For partially-mappable large folios +* (THP), the return value can wrongly indicate "mapped shared" (false +* positive) in some scenarios. This can only happen if two MMs are +* already mapping a folio and a more MM starts mapping the folio. We +* would still the detect the folio as "mapped shared" after the first +* two MMs no longer map the folio. * #. For pagecache folios (including hugetlb), the return value can wrongly * indicate "mapped shared" (false positive) when two VMAs in the same MM * cover the same file range. * +* With CONFIG_MM_ID, this function will never return "false negatives". +* * Further, this function only considers current page table mappings that * are tracked using the folio mapcount(s). *
@@ -2183,12 +2191,16 @@ static inline bool folio_likely_mapped_shared(struct folio *folio)if (mapcount <=1 )return false; +#ifdef CONFIG_PAGE_MAPCOUNT /* If any page is mapped more than once we treat it "mapped shared". */ if (folio_entire_mapcount (folio) || mapcount >folio_large_nr_pages (folio))return true;/* Let's guess based on the first subpage. */ return atomic_read (&folio->_mapcount) >0 ; +#else /* !CONFIG_PAGE_MAPCOUNT */ +return !folio_test_large_mapped_exclusively (folio); +#endif /* !CONFIG_PAGE_MAPCOUNT */ }#ifndef HAVE_ARCH_MAKE_FOLIO_ACCESSIBLE
Signature · 1 line
2.46.0
PATCH 13/17 fs/proc/page: remove per-page mapcount dependency for /proc/kpagecount (CONFIG_NO_PAGE_MAPCOUNT)
In reply to David HildenbrandLet's implement an alternative when per-page mapcounts in large folios are no longer maintained -- soon with CONFIG_NO_PAGE_MAPCOUNT.
For large folios, we'll return the per-page average mapcount within the folio, except when the average is 0 but the folio is mapped: then we return 1.
For hugetlb folios and for large folios that are fully mapped into all address spaces, there is no change.
As an alternative, we could simply return 0 for non-hugetlb large folios, or disable this legacy interface with CONFIG_NO_PAGE_MAPCOUNT.
But the information exposed by this interface can still be valuable, and frequently we deal with fully-mapped large folios where the average corresponds to the actual page mapcount. So we'll leave it like this for now and document the new behavior.
--- Documentation/admin-guide/mm/pagemap.rst | 7 +++++- fs/proc/internal.h | 31 ++++++++++++++++++++++++ fs/proc/page.c | 18 +++++++++++--- 3 files changed, 52 insertions(+), 4 deletions(-)
Documentation/admin-guide/mm/pagemap.rst +6 -1
@@ -42,7 +42,12 @@ There are four components to pagemap: skip over unmapped regions. * ``/proc/kpagecount``. This file contains a 64-bit count of the number of - times each page is mapped, indexed by PFN. + times each page is mapped, indexed by PFN. Some kernel configurations do + not track the precise number of times a page part of a larger allocation + (e.g., THP) is mapped. In these configurations, the average number of + mappings per page in this larger allocation is returned instead. However, + if any page of the large allocation is mapped, the returned value will + be at least 1. The page-types tool in the tools/mm directory can be used to query the number of times a page is mapped.
fs/proc/internal.h +31 -0
@@ -174,6 +174,37 @@ static inline int folio_precise_page_mapcount(struct folio *folio,return mapcount; } +/** +* folio_average_page_mapcount() - Average number of mappings per page in this +* folio +* @folio: The folio. +* +* The average number of present user page table entries that reference each +* page in this folio as tracked via the RMAP: either referenced directly +* (PTE) or as part of a larger area that covers this page (e.g., PMD). +* +* Returns: The average number of mappings per page in this folio. 0 for +* folios that are not mapped to user space or are not tracked via the RMAP +* (e.g., shared zeropage). +*/ +static inline int folio_average_page_mapcount (struct folio *folio) +{ +int mapcount, entire_mapcount; +unsigned int adjust; + +if (!folio_test_large (folio)) +return atomic_read (&folio->_mapcount) +1 ; + + mapcount =folio_large_mapcount (folio); + entire_mapcount =folio_entire_mapcount (folio); +if (mapcount <= entire_mapcount) +return entire_mapcount; + mapcount -= entire_mapcount; + + adjust =folio_large_nr_pages (folio) /2 ; +return ((mapcount + adjust) >>folio_large_order (folio)) + + entire_mapcount; +}/* * array.c */
fs/proc/page.c +15 -3
@@ -67,9 +67,21 @@ static ssize_t kpagecount_read(struct file *file, char __user *buf,* memmaps that were actually initialized. */ page =pfn_to_online_page (pfn); -if (page) - mapcount =folio_precise_page_mapcount (page_folio (page), - page); +if (page) { +struct folio *folio =page_folio (page); + +#ifdef CONFIG_PAGE_MAPCOUNT + mapcount =folio_precise_page_mapcount (folio, page); +#else /* !CONFIG_PAGE_MAPCOUNT */ +/* +* Indicate the per-page average, but at least "1" for +* mapped folios. +*/ + mapcount =folio_average_page_mapcount (folio); +if (!mapcount &&folio_test_large (folio) &&folio_mapped (folio)) + mapcount =1 ; +#endif /* !CONFIG_PAGE_MAPCOUNT */ + }if (put_user (mapcount, out)) { ret = -EFAULT ;
Signature · 1 line
2.46.0
PATCH 14/17 fs/proc/task_mmu: remove per-page mapcount dependency for PM_MMAP_EXCLUSIVE (CONFIG_NO_PAGE_MAPCOUNT)
In reply to David HildenbrandLet's implement an alternative when per-page mapcounts in large folios are no longer maintained -- soon with CONFIG_NO_PAGE_MAPCOUNT.
PM_MMAP_EXCLUSIVE will now be set if folio_likely_mapped_shared() is true -- when the folio is considered "mapped shared", including when it once was "mapped shared" but no longer is, as documented.
This might result in and under-indication of "exclusively mapped", which is considered better than over-indicating it: under-estimating the USS (Unique Set Size) is better than over-estimating it.
As an alternative, we could simply remove that flag with CONFIG_NO_PAGE_MAPCOUNT completely, but there might be value to it. So, let's keep it like that and document the behavior.
--- Documentation/admin-guide/mm/pagemap.rst | 9 +++++++++ fs/proc/task_mmu.c | 16 ++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-)
Documentation/admin-guide/mm/pagemap.rst +9 -0
@@ -37,6 +37,15 @@ There are four components to pagemap: precisely which pages are mapped (or in swap) and comparing mapped pages between processes. + Note that in some kernel configurations, all pages part of a larger + allocation (e.g., THP) might be considered "mapped shared" if the large + allocation is considered "mapped shared": if not all pages are exclusive to + the same process. Further, some kernel configurations might consider larger + allocations "mapped shared", if they were at one point considered + "mapped shared", even if they would now be considered "exclusively mapped". + Consequently, in these kernel configurations, bit 56 might be set although + the page is actually "exclusively mapped" + Efficient users of this interface will use ``/proc/pid/maps`` to determine which areas of memory are actually mapped and llseek to skip over unmapped regions.
fs/proc/task_mmu.c +14 -2
@@ -29,6 +29,18 @@#include <asm/tlbflush.h> #include "internal.h" +#ifdef CONFIG_PAGE_MAPCOUNT +static bool __folio_page_mapped_exclusively (struct folio *folio,struct page *page) +{ +return folio_precise_page_mapcount (folio, page) ==1 ; +} +#else /* !CONFIG_PAGE_MAPCOUNT */ +static bool __folio_page_mapped_exclusively (struct folio *folio,struct page *page) +{ +return !folio_likely_mapped_shared (folio); +} +#endif /* CONFIG_PAGE_MAPCOUNT */ +#define SEQ_PUT_DEC (str, val) \ seq_put_decimal_ull_width(m, str, (val) << (PAGE_SHIFT-10), 8)void task_mem (struct seq_file *m,struct mm_struct *mm)
@@ -1746,7 +1758,7 @@ static pagemap_entry_t pte_to_pagemap_entry(struct pagemapread *pm,if (!folio_test_anon (folio)) flags |=PM_FILE ;if ((flags &PM_PRESENT ) && -folio_precise_page_mapcount (folio, page) ==1 ) +__folio_page_mapped_exclusively (folio, page)) flags |=PM_MMAP_EXCLUSIVE ; }if (vma->vm_flags &VM_SOFTDIRTY )
@@ -1821,7 +1833,7 @@ static int pagemap_pmd_range(pmd_t *pmdp, unsigned long addr, unsigned long end,pagemap_entry_t pme;if (folio && (flags &PM_PRESENT ) && -folio_precise_page_mapcount (folio, page + idx) ==1 ) +__folio_page_mapped_exclusively (folio, page)) cur_flags |=PM_MMAP_EXCLUSIVE ; pme =make_pme (frame, cur_flags);
Signature · 1 line
2.46.0
PATCH 15/17 fs/proc/task_mmu: remove per-page mapcount dependency for "mapmax" (CONFIG_NO_PAGE_MAPCOUNT)
In reply to David HildenbrandLet's implement an alternative when per-page mapcounts in large folios are no longer maintained -- soon with CONFIG_NO_PAGE_MAPCOUNT.
For calculating "mapmax", we now use the average per-page mapcount in a large folio instead of the per-page mapcount.
For hugetlb folios and folios that are not partially mapped into MMs, there is no change.
Likely, this change will not matter much in practice, and an alternative might be to simple remove this stat with CONFIG_NO_PAGE_MAPCOUNT. However, there might be value to it, so let's keep it like that and document the behavior.
--- Documentation/filesystems/proc.rst | 5 +++++ fs/proc/task_mmu.c | 8 +++++++- 2 files changed, 12 insertions(+), 1 deletion(-)
Documentation/filesystems/proc.rst +5 -0
@@ -684,6 +684,11 @@ Where: node locality page counters (N0 == node0, N1 == node1, ...) and the kernel page size, in KB, that is backing the mapping up. +Note that some kernel configurations do not track the precise number of times +a page part of a larger allocation (e.g., THP) is mapped. In these +configurations, "mapmax" might corresponds to the average number of mappings +per page in such a larger allocation instead. + 1.2 Kernel data ---------------
fs/proc/task_mmu.c +7 -1
@@ -2872,7 +2872,13 @@ static void gather_stats(struct page *page, struct numa_maps *md, int pte_dirty, unsigned long nr_pages) {struct folio *folio =page_folio (page); -int count =folio_precise_page_mapcount (folio, page); +int count; + +#ifdef CONFIG_PAGE_MAPCOUNT + count =folio_precise_page_mapcount (folio, page); +#else + count =min_t (int,folio_average_page_mapcount (folio),1 ); +#endif md->pages += nr_pages;if (pte_dirty ||folio_test_dirty (folio))
Signature · 1 line
2.46.0
PATCH 16/17 fs/proc/task_mmu: remove per-page mapcount dependency for smaps/smaps_rollup (CONFIG_NO_PAGE_MAPCOUNT)
In reply to David HildenbrandLet's implement an alternative when per-page mapcounts in large folios are no longer maintained -- soon with CONFIG_NO_PAGE_MAPCOUNT.
When computing the output for smaps / smaps_rollups, in particular when calculating the USS (Unique Set Size) and the PSS (Proportional Set Size), we still rely on per-page mapcounts.
To determine private vs. shared, we'll use folio_likely_mapped_shared(), similar to how we handle PM_MMAP_EXCLUSIVE. Similarly, we might now under-estimate the USS and count pages towards "shared" that are actually "private" ("exclusively mapped").
When calculating the PSS, we'll now also use the average per-page mapcount for large folios: this can result in both, an over-estimation and an under-estimation of the PSS. The difference is not expected to matter much in practice, but we'll have to learn as we go.
We can now provide folio_precise_page_mapcount() only with CONFIG_PAGE_MAPCOUNT, and remove one of the last users of per-page mapcounts when CONFIG_NO_PAGE_MAPCOUNT is enabled.
Document the new behavior.
--- Documentation/filesystems/proc.rst | 13 +++++++++++++ fs/proc/internal.h | 2 ++ fs/proc/task_mmu.c | 17 +++++++++++++++-- 3 files changed, 30 insertions(+), 2 deletions(-)
Documentation/filesystems/proc.rst +13 -0
@@ -504,6 +504,19 @@ Note that even a page which is part of a MAP_SHARED mapping, but has only a single pte mapped, i.e. is currently used by only one process, is accounted as private and not as shared. +Note that in some kernel configurations, all pages part of a larger allocation +(e.g., THP) might be considered "shared" if the large allocation is +considered "shared": if not all pages are exclusive to the same process. +Further, some kernel configurations might consider larger allocations "shared", +if they were at one point considered "shared", even if they would now be +considered "exclusive". + +Some kernel configurations do not track the precise number of times a page part +of a larger allocation is mapped. In this case, when calculating the PSS, the +average number of mappings per page in this larger allocation might be used +as an approximation for the number of mappings of a page. The PSS calculation +will be imprecise in this case. + "Referenced" indicates the amount of memory currently marked as referenced or accessed.
fs/proc/internal.h +2 -0
@@ -143,6 +143,7 @@ unsigned name_to_int(const struct qstr *qstr);/* Worst case buffer size needed for holding an integer. */ #define PROC_NUMBUF 13 +#ifdef CONFIG_PAGE_MAPCOUNT /** * folio_precise_page_mapcount() - Number of mappings of this folio page. * @folio: The folio.
@@ -173,6 +174,7 @@ static inline int folio_precise_page_mapcount(struct folio *folio, return mapcount; } +#endif /* CONFIG_PAGE_MAPCOUNT */ /** * folio_average_page_mapcount() - Average number of mappings per page in this
fs/proc/task_mmu.c +15 -2
@@ -734,6 +734,8 @@ static void smaps_account(struct mem_size_stats *mss, struct page *page,struct folio *folio =page_folio (page);int i, nr = compound ?compound_nr (page) :1 ;unsigned long size = nr *PAGE_SIZE ; +bool exclusive; +int mapcount;/* * First accumulate quantities that depend only on |size| and the type
@@ -774,18 +776,29 @@ static void smaps_account(struct mem_size_stats *mss, struct page *page, dirty, locked, present);return ; } + +#ifndef CONFIG_PAGE_MAPCOUNT + mapcount =folio_average_page_mapcount (folio); + exclusive = !folio_likely_mapped_shared (folio); +#endif +/* * We obtain a snapshot of the mapcount. Without holding the folio lock * this snapshot can be slightly wrong as we cannot always read the * mapcount atomically. */ for (i =0 ; i < nr; i++, page++) { -int mapcount =folio_precise_page_mapcount (folio, page);unsigned long pss =PAGE_SIZE <<PSS_SHIFT ; + +#ifdef CONFIG_PAGE_MAPCOUNT + mapcount =folio_precise_page_mapcount (folio, page); + exclusive = mapcount <2 ; +#endif +if (mapcount >=2 ) pss /= mapcount;smaps_page_accumulate (mss, folio,PAGE_SIZE , pss, - dirty, locked, mapcount <2 ); + dirty, locked, exclusive); } }
Signature · 1 line
2.46.0
PATCH 17/17 mm: stop maintaining the per-page mapcount of large folios (CONFIG_NO_PAGE_MAPCOUNT)
In reply to David HildenbrandEverything is in place to stop using the per-page mapcounts in large folios with CONFIG_NO_PAGE_MAPCOUNT: the mapcount of tail pages will always be logically 0 (-1 value), just like it currently is for hugetlb folios already, and the page mapcount of the head page is either 0 (-1 value) or contains a page type (e.g., hugetlb).
Maintaining _nr_pages_mapped without per-page mapcounts is impossible, so that one also has to go with CONFIG_NO_PAGE_MAPCOUNT.
There are two remaining implications:
(1) Per-node, per-cgroup and per-lruvec stats of "NR_ANON_MAPPED" ("mapped anonymous memory") and "NR_FILE_MAPPED" ("mapped file memory"):
As soon as any page of the folio is mapped -- folio_mapped() -- we now account the complete folio as mapped. Once the last page is unmapped -- !folio_mapped() -- we account the complete folio as unmapped.
This implies that ...
* "AnonPages" and "Mapped" in /proc/meminfo and /sys/devices/system/node/*/meminfo
* cgroup v2: "anon" and "file_mapped" in "memory.stat" and "memory.numa_stat"
* cgroup v1: "rss" and "mapped_file" in "memory.stat" and "memory.numa_stat
... can now appear higher than before. But note that these folios do consume that memory, simply not all pages are actually currently mapped.
It's worth nothing that other accounting in the kernel (esp. cgroup charging on allocation) is not affected by this change.
[why oh why is "anon" called "rss" in cgroup v1]
(2) Detecting partial mappings
Detecting whether anon THP are partially mapped gets a bit more unreliable. As long as a single MM maps such a large folio ("exclusively mapped"), we can reliably detect it. Especially before fork() / after a short-lived child process quit, we will detect partial mappings reliably, which is the common case.
In essence, if the average per-page mapcount in an anon THP is < 1, we know for sure that we have a partial mapping.
However, as soon as multiple MMs are involved, we might miss detecting partial mappings: this might be relevant with long-lived child processes. If we have a fully-mapped anon folio before fork(), once our child processes and our parent all unmap (zap/COW) the same pages (but not the complete folio), we might not detect the partial mapping. However, once the child processes quit we would detect the partial mapping.
How relevant this case is in practice remains to be seen. Swapout/migration will likely mitigate this.
In the future, RMAP walkers should check for that for "mapped shared" anon folios, and flag them for deferred-splitting.
There are a couple of remaining per-page mapcount users we won't touch for now:
(1) __dump_folio(): we'll tackle that separately later. For now, it will always read effective mapcount of "0" for pages in large folios.
(2) include/trace/events/page_ref.h: we should rework the whole handling to be folio-aware and simply trace folio_mapcount(). Let's leave it around for now, might still be helpful to trace the raw page mapcount value (e.g., including the page type).
(3) mm/mm_init.c: to initialize the mapcount/type field to -1. Will be required until we decoupled type+mapcount (e.g., moving it into "struct folio"), and until we initialize the type+mapcount when allocating a folio.
(4) mm/page_alloc.c: to sanity-check that the mapcount/type field is -1 when a page gets freed. We could probably remove at least the tail page mapcount check in non-debug environments.
Some added ifdefery seems unavoidable for now: at least it's mostly limited to the rmap add/remove core primitives.
Extend documentation.
--- .../admin-guide/cgroup-v1/memory.rst | 4 ++ Documentation/admin-guide/cgroup-v2.rst | 10 ++- Documentation/filesystems/proc.rst | 10 ++- Documentation/mm/transhuge.rst | 31 +++++++--- include/linux/mm_types.h | 4 ++ include/linux/rmap.h | 10 ++- mm/internal.h | 21 +++++-- mm/page_alloc.c | 2 + mm/rmap.c | 61 +++++++++++++++++++ 9 files changed, 133 insertions(+), 20 deletions(-)
Documentation/admin-guide/cgroup-v1/memory.rst +4 -0
@@ -615,6 +615,10 @@ memory.stat file includes following statistics: 'rss + mapped_file" will give you resident set size of cgroup. + Note that some kernel configurations might account complete larger + allocations (e.g., THP) towards 'rss' and 'mapped_file', even if + only some, but not all that memory is mapped. + (Note: file and shmem may be shared among other cgroups. In that case, mapped_file is accounted only when the memory cgroup is owner of page cache.)
Documentation/admin-guide/cgroup-v2.rst +8 -2
@@ -1429,7 +1429,10 @@ The following nested keys are defined. anon Amount of memory used in anonymous mappings such as - brk(), sbrk(), and mmap(MAP_ANONYMOUS) + brk(), sbrk(), and mmap(MAP_ANONYMOUS). Note that + some kernel configurations might account complete larger + allocations (e.g., THP) if only some, but not all the + memory of such an allocation is mapped anymore. file Amount of memory used to cache filesystem data,
@@ -1472,7 +1475,10 @@ The following nested keys are defined. Amount of application memory swapped out to zswap. file_mapped - Amount of cached filesystem data mapped with mmap() + Amount of cached filesystem data mapped with mmap(). Note + that some kernel configurations might account complete + larger allocations (e.g., THP) if only some, but not + not all the memory of such an allocation is mapped. file_dirty Amount of cached filesystem data that was modified but
Documentation/filesystems/proc.rst +8 -2
@@ -1148,9 +1148,15 @@ Dirty Writeback Memory which is actively being written back to the disk AnonPages - Non-file backed pages mapped into userspace page tables + Non-file backed pages mapped into userspace page tables. Note that + some kernel configurations might consider all pages part of a + larger allocation (e.g., THP) as "mapped", as soon as a single + page is mapped. Mapped - files which have been mmapped, such as libraries + files which have been mmapped, such as libraries. Note that some + kernel configurations might consider all pages part of a larger + allocation (e.g., THP) as "mapped", as soon as a single page is + mapped. Shmem Total memory used by shared memory (shmem) and tmpfs KReclaimable
Documentation/mm/transhuge.rst +23 -8
@@ -116,23 +116,28 @@ pages: succeeds on tail pages. - map/unmap of a PMD entry for the whole THP increment/decrement - folio->_entire_mapcount, increment/decrement folio->_large_mapcount - and also increment/decrement folio->_nr_pages_mapped by ENTIRELY_MAPPED - when _entire_mapcount goes from -1 to 0 or 0 to -1. + folio->_entire_mapcount and folio->_large_mapcount. With CONFIG_MM_ID, we also maintain the two slots for tracking MM owners (MM ID and corresponding mapcount), and the current status ("mapped shared" vs. "mapped exclusively"). + With CONFIG_PAGE_MAPCOUNT, we also increment/decrement + folio->_nr_pages_mapped by ENTIRELY_MAPPED when _entire_mapcount goes + from -1 to 0 or 0 to -1. + - map/unmap of individual pages with PTE entry increment/decrement - page->_mapcount, increment/decrement folio->_large_mapcount and also - increment/decrement folio->_nr_pages_mapped when page->_mapcount goes - from -1 to 0 or 0 to -1 as this counts the number of pages mapped by PTE. + folio->_large_mapcount. With CONFIG_MM_ID, we also maintain the two slots for tracking MM owners (MM ID and corresponding mapcount), and the current status ("mapped shared" vs. "mapped exclusively"). + With CONFIG_PAGE_MAPCOUNT, we also increment/decrement + page->_mapcount and increment/decrement folio->_nr_pages_mapped when + page->_mapcount goes from -1 to 0 or 0 to -1 as this counts the number + of pages mapped by PTE. + split_huge_page internally has to distribute the refcounts in the head page to the tail pages before clearing all PG_head/tail bits from the page structures. It can be done easily for refcounts taken by page table
@@ -159,8 +164,8 @@ clear where references should go after split: it will stay on the head page. Note that split_huge_pmd() doesn't have any limitations on refcounting: pmd can be split at any point and never fails. -Partial unmap and deferred_split_folio() -======================================== +Partial unmap and deferred_split_folio() (anon THP only) +======================================================== Unmapping part of THP (with munmap() or other way) is not going to free memory immediately. Instead, we detect that a subpage of THP is not in use
@@ -175,3 +180,13 @@ a THP crosses a VMA boundary. The function deferred_split_folio() is used to queue a folio for splitting. The splitting itself will happen when we get memory pressure via shrinker interface. + +With CONFIG_PAGE_MAPCOUNT, we reliably detect partial mappings based on +folio->_nr_pages_mapped. + +With CONFIG_NO_PAGE_MAPCOUNT, we detect partial mappings based on the +average per-page mapcount in a THP: if the average is < 1, an anon THP is +certainly partially mapped. As long as only a single process maps a THP, +this detection is reliable. With long-running child processes, there can +be scenarios where partial mappings can currently not be detected, and +might need asynchronous detection during memory reclaim in the future.
include/linux/mm_types.h +4 -0
@@ -378,7 +378,11 @@ struct folio {struct {atomic_t _large_mapcount;atomic_t _entire_mapcount; +#ifdef CONFIG_PAGE_MAPCOUNT atomic_t _nr_pages_mapped; +#else /* !CONFIG_PAGE_MAPCOUNT */ +int _unused_1; +#endif /* !CONFIG_PAGE_MAPCOUNT */ atomic_t _pincount;#ifdef CONFIG_MM_ID int _mm0_mapcount;
include/linux/rmap.h +8 -2
@@ -219,7 +219,7 @@ static __always_inline void folio_set_large_mapcount(struct folio *folio,VM_WARN_ON_ONCE (folio->_mm1_mapcount >=0 ); } -static __always_inline void folio_add_large_mapcount(struct folio *folio, +static __always_inline int folio_add_large_mapcount(struct folio *folio,int diff,struct vm_area_struct *vma) {const unsigned int mm_id = vma->vm_mm->mm_id;
@@ -264,11 +264,12 @@ static __always_inline void folio_add_large_mapcount(struct folio *folio,folio_clear_large_mapped_exclusively (folio); }folio_unlock_large_mapcount_data (folio); +return mapcount_val +1 ; }#define folio_inc_large_mapcount (folio, vma) \ folio_add_large_mapcount(folio, 1, vma) -static __always_inline void folio_sub_large_mapcount(struct folio *folio, +static __always_inline int folio_sub_large_mapcount(struct folio *folio,int diff,struct vm_area_struct *vma) {const unsigned int mm_id = vma->vm_mm->mm_id;
@@ -294,6 +295,7 @@ static __always_inline void folio_sub_large_mapcount(struct folio *folio, folio->_mm1_mapcount == mapcount_val)folio_set_large_mapped_exclusively (folio);folio_unlock_large_mapcount_data (folio); +return mapcount_val +1 ; }#define folio_dec_large_mapcount (folio, vma) \ folio_sub_large_mapcount(folio, 1, vma)
@@ -493,9 +495,11 @@ static __always_inline void __folio_dup_file_rmap(struct folio *folio,break ; } +#ifdef CONFIG_PAGE_MAPCOUNT do {atomic_inc (&page->_mapcount); }while (page++, --nr_pages >0 ); +#endif folio_add_large_mapcount (folio, orig_nr_pages, dst_vma);break ;case RMAP_LEVEL_PMD :
@@ -592,7 +596,9 @@ static __always_inline int __folio_try_dup_anon_rmap(struct folio *folio,do {if (PageAnonExclusive (page))ClearPageAnonExclusive (page); +#ifdef CONFIG_PAGE_MAPCOUNT atomic_inc (&page->_mapcount); +#endif }while (page++, --nr_pages >0 );folio_add_large_mapcount (folio, orig_nr_pages, dst_vma);break ;
mm/internal.h +15 -6
@@ -60,6 +60,13 @@ struct folio_batch;void page_writeback_init (void ); +/* +* Flags passed to __show_mem() and show_free_areas() to suppress output in +* various contexts. +*/ +#define SHOW_MEM_FILTER_NODES (0x0001u)/* disallowed nodes */ + +#ifdef CONFIG_PAGE_MAPCOUNT /* * If a 16GB hugetlb folio were mapped by PTEs of all of its 4kB pages, * its nr_pages_mapped would be 0x400000: choose the ENTIRELY_MAPPED bit
@@ -69,12 +76,6 @@ void page_writeback_init(void);#define ENTIRELY_MAPPED 0x800000#define FOLIO_PAGES_MAPPED (ENTIRELY_MAPPED - 1) -/* -* Flags passed to __show_mem() and show_free_areas() to suppress output in -* various contexts. -*/ -#define SHOW_MEM_FILTER_NODES (0x0001u)/* disallowed nodes */ -/* * How many individual pages have an elevated _mapcount. Excludes * the folio's entire_mapcount.
@@ -85,6 +86,12 @@ static inline int folio_nr_pages_mapped(const struct folio *folio) {return atomic_read (&folio->_nr_pages_mapped) &FOLIO_PAGES_MAPPED ; } +#else /* !CONFIG_PAGE_MAPCOUNT */ +static inline int folio_nr_pages_mapped (const struct folio *folio) +{ +return -1 ; +} +#endif /* !CONFIG_PAGE_MAPCOUNT */ /* * Retrieve the first entry of a folio based on a provided entry within the
@@ -663,7 +670,9 @@ static inline void prep_compound_head(struct page *page, unsigned int order)folio_set_order (folio, order);atomic_set (&folio->_large_mapcount,-1 );atomic_set (&folio->_entire_mapcount,-1 ); +#ifdef CONFIG_PAGE_MAPCOUNT atomic_set (&folio->_nr_pages_mapped,0 ); +#endif /* CONFIG_PAGE_MAPCOUNT */ atomic_set (&folio->_pincount,0 );#ifdef CONFIG_MM_ID folio->_mm0_mapcount =-1 ;
mm/page_alloc.c +2 -0
@@ -951,10 +951,12 @@ static int free_tail_page_prepare(struct page *head_page, struct page *page)bad_page (page,"nonzero large_mapcount" ); goto out; } +#ifdef CONFIG_PAGE_MAPCOUNT if (unlikely (atomic_read (&folio->_nr_pages_mapped))) {bad_page (page,"nonzero nr_pages_mapped" ); goto out; } +#endif if (unlikely (atomic_read (&folio->_pincount))) {bad_page (page,"nonzero pincount" ); goto out;
mm/rmap.c +61 -0
147 lines not on this page · raw message
Signature · 1 line
2.46.0
Re: [PATCH v1 01/17] mm: factor out large folio handling from folio_order() into folio_large_order()
In reply to David HildenbrandQuoted 6 lines · David Hildenbrand
Let's factor it out into a simple helper function. This helper will also come in handy when working with code where we know that our folio is large.
Signed-off-by David Hildenbrand <[email protected]>
LGTM. Feel feel to add:
Thanks,
Lance
Quoted 60 lines
--- include/linux/mm.h | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-)include/linux/mm.h +9
-5@@ -1071,6 +1071,11 @@ int vma_is_stack_for_current(struct vm_area_struct *vma);struct mmu_gather ;struct inode ; +static inline unsigned int folio_large_order (const struct folio *folio) +{ +return folio->_flags_1 &0xff ; +} +/* * compound_order() can be called without holding a reference, which means * that niceties like page_folio() don't work. These callers should be @@ -1084,7 +1089,7 @@ static inline unsigned int compound_order(struct page *page)if (!test_bit (PG_head, &folio->flags))return 0 ; -return folio->_flags_1 &0xff ; +return folio_large_order (folio); }/** @@ -1100,7 +1105,7 @@ static inline unsigned int folio_order(const struct folio *folio) {if (!folio_test_large (folio))return 0 ; -return folio->_flags_1 &0xff ; +return folio_large_order (folio); }#include <linux/huge_mm.h> @@ -2035,7 +2040,7 @@ static inline long folio_nr_pages(const struct folio *folio)#ifdef CONFIG_64BIT return folio->_folio_nr_pages;#else -return 1L << (folio->_flags_1 &0xff ); +return 1L <<folio_large_order (folio);#endif }@@ -2060,7 +2065,7 @@ static inline unsigned long compound_nr(struct page *page)#ifdef CONFIG_64BIT return folio->_folio_nr_pages;#else -return 1L << (folio->_flags_1 &0xff ); +return 1L <<folio_large_order (folio);#endif } --2.46.0
Quoted 246 lines · David Hildenbrand
RMAP overhaul and optimizations, PTE batching, large mapcount,
folio_likely_mapped_shared()introduction and optimizations,page_mapcountcleanups and preparations ... it's been quite some work to get to this point.Next up is being able to identify -- without false positives, without page-mapcounts and without page table/rmap scanning -- whether a large folio is "mapped exclusively" into a single MM, and using that information to implement Copy-on-Write reuse and to improve
folio_likely_mapped_shared()for large folios.... and based on that, finally introducing a kernel config option that let's us not use+maintain per-page mapcounts in large folios, improving performance of (un)map operations today, taking one step towards supporting large folios >
PMD_SIZE, and preparing for the bright future where we might no longer have a mapcount per page at all.The bigger picture was presented at LSF/MM [1].
This series is effectively a follow-up on my early work from last year [2], which proposed a precise way to identify whether a large folio is "mapped shared" into multiple MMs or "mapped exclusively" into a single MM.
While that advanced approach has been simplified and optimized in the meantime, let's start with something simpler first -- "certainly mapped exclusive" vs. ""maybe mapped shared" -- so we can start learning about the effects and TODOs that some of the implied changes of losing per-page mapcounts has.
I have plans to exchange the simple approach used in this series at some point by the advanced approach, but one important thing to learn if the imprecision in the simple approach is relevant in practice.
64BIT only, and unless enabled in kconfig, this series should for now not have any impact.
1) Patch Organization
=====================Patch #1 -> #4: make more room on 64BIT in order-1 folios
Patch #5 -> #7: prepare for MM owner tracking of large folios
Patch #8: implement a simple MM owner tracking approach for large folios
patch #9: simple optimization
Patch #10: COW reuse for PTE-mapped anon THP
Patch #11 -> #17: introduce and implement
CONFIG_NO_PAGE_MAPCOUNT2) MM owner tracking
====================Similar to my advanced approach [2], we assign each MM a unique 20-bit ID ("MM ID"), to be able to squeeze more information in our folios.
Each large folios can store two MM-ID+mapcount combination:
*mm0_id+mm0_mapcount
*mm1_id+mm1_mapcountCombined with the large mapcount, we can reliably identify whether one of these MMs is the current owner (-> owns all mappings) or even holds all folio references (-> owns all mappings, and all references are from mappings).
Stored MM IDs can only change if the corresponding mapcount is logically 0, and if the folio is currently "mapped exclusively".
As long as only two MMs map folio pages at a time, we can reliably identify whether a large folio is "mapped shared" or "mapped exclusively". The approach is precise.
Any MM mapping the folio while two other MMs are already mapping the folio, will lead to a "mapped shared" detection even after all other MMs stopped mapping the folio and it is actually "mapped exclusively": we can have false positives but never false negatives when detecting "mapped shared".
So that's where the approach gets imprecise.
For now, we use a bit-spinlock to sync the large mapcount + MM IDs + MM mapcounts, and make sure we do keep the machinery fast, to not degrade (un)map performance too much: for example, we make sure to only use a single atomic (when grabbing the bit-spinlock), like we would already perform when updating the large mapcount.
In the future, we might be able to use an
arch_spin_lock(), but that's future work.3)
CONFIG_NO_PAGE_MAPCOUNT
==========================patch #11 -> #17 spell out and document what exactly is affected when not maintaining the per-page mapcounts in large folios anymore.
For example, as we cannot maintain
folio->_nr_pages_mappedanymore when (un)mapping pages, we'll account a complete folio as mapped if a single page is mapped.As another example, we might now under-estimate the USS (Unique Set Size) of a process, but never over-estimate it.
With a more elaborate approach for MM-owner tracking like #1, some things could be improved (e.g., USS to some degree), but somethings just cannot be handled like we used to without these per-page mapcounts (e.g.,
folio->_nr_pages_mapped).4) Performance
==============The following kernel config combinations are possible:
* Base:
CONFIG_PAGE_MAPCOUNT
-> (existing) page-mapcount tracking
* MM-ID:CONFIG_MM_ID&&CONFIG_PAGE_MAPCOUNT-> page-mapcount + MM-ID tracking
* No-Mapcount:CONFIG_MM_ID&&CONFIG_NO_PAGE_MAPCOUNT-> MM-ID trackingI run my PTE-mapped-THP microbenchmarks [3] and vm-scalability on a machine with two NUMA nodes, with a 10-core Intel(R) Xeon(R) Silver 4210R CPU @ 2.40GHz and 16 GiB of memory each.
4.1) PTE-mapped-THP microbenchmarks
-----------------------------------All benchmarks allocate 1 GiB of THPs of a given size, to then fork()/ munmap/... PMD-sized THPs are mapped by PTEs first.
Numbers are increase (+) / reduction (-) in runtime. Reduction (-) is good. "Base" is the baseline.
munmap:
munmap()the allocated memory.Folio Size | MM-ID | No-Mapcount
--------------------------------16 KiB | 2 % | -8 % 32 KiB | 3 % | -9 % 64 KiB | 4 % | -16 % 128 KiB | 3 % | -17 % 256 KiB | 1 % | -23 % 512 KiB | 1 % | -26 % 1024 KiB | 0 % | -29 % 2048 KiB | 0 % | -31 %-> 32-128 with MM-ID are a bit unexpected: we would expect to see the worst
case with the smallest size (16 KiB). But for these sizes also the STDEV is between 1% and 2%, in contrast to the others (< 1 %). Maybe some weird interaction with PCP/buddy.fork:
fork()Folio Size | MM-ID | No-Mapcount
--------------------------------16 KiB | 4 % | -9 % 32 KiB | 1 % | -12 % 64 KiB | 0 % | -15 % 128 KiB | 0 % | -15 % 256 KiB | 0 % | -16 % 512 KiB | 0 % | -16 % 1024 KiB | 0 % | -17 % 2048 KiB | -1 % | -21 %-> Slight slowdown with MM-ID for the smallest folio size (more what we expect in contrast to
munmap()).cow-byte:
fork()and keep the child running. write one byte to each
individual page, measuring the duration of all writes.Folio Size | MM-ID | No-Mapcount
--------------------------------16 KiB | 0 % | 0 % 32 KiB | 0 % | 0 % 64 KiB | 0 % | 0 % 128 KiB | 0 % | 0 % 256 KiB | 0 % | 0 % 512 KiB | 0 % | 0 % 1024 KiB | 0 % | 0 % 2048 KiB | 0 % | 0 %-> All other overhead dominates even when effectively unmapping
single pages of large folios when replacing them by a copy during write faults. No change, which is great!reuse-byte:
fork()and wait until the child quit. write one byte to each
individual page, measuring the duration of all writes.Folio Size | MM-ID | No-Mapcount
--------------------------------16 KiB | -66 % | -66 % 32 KiB | -65 % | -65 % 64 KiB | -64 % | -64 % 128 KiB | -64 % | -64 % 256 KiB | -64 % | -64 % 512 KiB | -64 % | -64 % 1024 KiB | -64 % | -64 % 2048 KiB | -64 % | -64 %-> No surprise, we reuse all pages instead of copying them.
child-reuse-bye:
fork()and unmap the memory in the parent. write one byte
to each individual page in the child, measuring the duration of all writes.Folio Size | MM-ID | No-Mapcount
--------------------------------16 KiB | -66 % | -66 % 32 KiB | -65 % | -65 % 64 KiB | -64 % | -64 % 128 KiB | -64 % | -64 % 256 KiB | -64 % | -64 % 512 KiB | -64 % | -64 % 1024 KiB | -64 % | -64 % 2048 KiB | -64 % | -64 %-> Same thing, we reuse all pages instead of copying them.
For 4 KiB, there is no change in any benchmark, as expected.
4.2) vm-scalability
-------------------For now I only ran anon COW tests. I use 1 GiB per child process and use one child per core (-> 20).
case-anon-cow-rand: random writes
There is effectively no change (<0.6% throughput difference).
case-anon-cow-seq: sequential writes
MM-ID has up to 2% *lower* throughout than Base, not really correlating to folio size. The difference is almost as large as the STDEV (1% - 2%), though. It looks like there is a very slight effective slowdown.
No-Mapcount has up to 3% *higher* throughput than Base, not really correlating to the folio size. However, also here the difference is almost as large as the STDEV (up to 2%). It looks like there is a very slight effective speedup.
Quoted 8 lines
In summary, no earth-shattering slowdown with MM-ID (and we just recently optimized
folio->_nr_pages_mappedto give us some speedup :) ), and another nice improvement with No-Mapcount.I did a bunch of cross-compiles and the build bots turned out very helpful over the last months. I did quite some testing with LTP and selftests, but x86-64 only.
Gentle ping. I might soon have capacity to continue working on this. If there is no further feedback I'll rebase and resend.
Signature · 3 lines
Cheers, David / dhildenb
Re: [PATCH v1 01/17] mm: factor out large folio handling from folio_order() into folio_large_order()
In reply to David HildenbrandQuoted 5 lines · David Hildenbrand
Let's factor it out into a simple helper function. This helper will also come in handy when working with code where we know that our folio is large.
Signed-off-by David Hildenbrand <[email protected]>
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Re: [PATCH v1 02/17] mm: factor out large folio handling from folio_nr_pages() into folio_large_nr_pages()
In reply to David HildenbrandQuoted 25 lines · David Hildenbrand
Let's factor it out into a simple helper function. This helper will also come in handy when working with code where we know that our folio is large.
Make use of it in
internal.handmm.h, where applicable.While at it, let's consistently return a "long" value from all these similar functions. Note that we cannot use "unsigned int" (even though
_folio_nr_pagesis of that type), because it would break some callers that do stuff like "-folio_nr_pages()". Both "int" or "unsigned long" would work as well.Signed-off-by David Hildenbrand <[email protected]>--- include/linux/mm.h | 27 ++++++++++++++------------- mm/internal.h | 2 +- 2 files changed, 15 insertions(+), 14 deletions(-)include/linux/mm.h +0
-0@@ -1076,6 +1076,15 @@ static inline unsigned int folio_large_order(const struct folio *folio)return folio->_flags_1 &0xff ; }
include/linux/mm.h static inline unsigned int folio_large_order(const struct folio *folio) · line 1087
Quoted 10 lines
include/linux/mm.h +9
-0+static inline long folio_large_nr_pages (const struct folio *folio) +{ +#ifdef CONFIG_64BIT +return folio->_folio_nr_pages; +#else +return 1L <<folio_large_order (folio); +#endif +} +
Maybe it would be cleaner to move #ifdef outside of the function?
Otherwise:
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Re: [PATCH v1 03/17] mm/rmap: use folio_large_nr_pages() in add/remove functions
In reply to David HildenbrandQuoted 7 lines · David Hildenbrand
Let's just use the "large" variant in code where we are sure that we have a large folio in our hands: this way we are sure that we don't perform any unnecessary "large" checks.
While at it, convert the
VM_BUG_ON_VMAto aVM_WARN_ON_ONCE.Signed-off-by David Hildenbrand <[email protected]>
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Re: [PATCH v1 04/17] mm: let _folio_nr_pages overlay memcg_data in first tail page
In reply to David HildenbrandQuoted 17 lines · David Hildenbrand
Let's free up some more of the "unconditionally available on 64BIT" space in order-1 folios by letting
_folio_nr_pagesoverlaymemcg_datain the first tail page (second folio page). Consequently, we have the optimization now whenever we haveCONFIG_MEMCG, independent of 64BIT.We have to make sure that
page->memcgon tail pages does not return "surprises".page_memcg_check()already properly refusesPageTail(). Let's do that earlier inprint_page_owner_memcg()to avoid printing wrong "Slab cache page" information. No other code should touch that field on tail pages of compound pages.Reset the "
_nr_pages" to 0 when splitting folios, or when freeing them back to the buddy (to avoid falsepage->memcg_data"bad page" reports).Note that in
__split_huge_page(),folio_nr_pages()would stop working already as soon as we start messing with the subpages.
Quoted 7 lines
Most kernel configs should have at least
CONFIG_MEMCGenabled, even if disabled at runtime. 64byte "struct memmap" is what we usually have on 64BIT.While at it, rename "
_folio_nr_pages" to "_nr_pages".Signed-off-by David Hildenbrand <[email protected]>
BTW, have anybody evaluated how much (if anything) do we gain we a separate _nr_pages field in struct folio comparing to calculating it based on the order in _flags_1? Mask+shift should be pretty cheap.
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Re: [PATCH v1 04/17] mm: let _folio_nr_pages overlay memcg_data in first tail page
Quoted 24 lines · Kirill A. Shutemov
Quoted 23 lines · David Hildenbrand
Let's free up some more of the "unconditionally available on 64BIT" space in order-1 folios by letting
_folio_nr_pagesoverlaymemcg_datain the first tail page (second folio page). Consequently, we have the optimization now whenever we haveCONFIG_MEMCG, independent of 64BIT.We have to make sure that
page->memcgon tail pages does not return "surprises".page_memcg_check()already properly refusesPageTail(). Let's do that earlier inprint_page_owner_memcg()to avoid printing wrong "Slab cache page" information. No other code should touch that field on tail pages of compound pages.Reset the "
_nr_pages" to 0 when splitting folios, or when freeing them back to the buddy (to avoid falsepage->memcg_data"bad page" reports).Note that in
__split_huge_page(),folio_nr_pages()would stop working already as soon as we start messing with the subpages.Most kernel configs should have at least
CONFIG_MEMCGenabled, even if disabled at runtime. 64byte "struct memmap" is what we usually have on 64BIT.While at it, rename "
_folio_nr_pages" to "_nr_pages".
Quoted 7 lines
Quoted 1 line
Signed-off-by David Hildenbrand <[email protected]>Reviewed-by Kirill A. Shutemov <[email protected]>BTW, have anybody evaluated how much (if anything) do we gain we a separate
_nr_pagesfield in struct folio comparing to calculating it based on the order in_flags_1? Mask+shift should be pretty cheap.
I recall that Willy did, and it's mostly getting rid of a single instruction in loads of places.
$ git grep folio_nr_pages | wc -l 254
[my first intuition was also to just remove it, but this way seems easy to just maintain it for now]
Signature · 3 lines
Cheers, David / dhildenb
Re: [PATCH v1 08/17] mm/rmap: initial MM owner tracking for large folios (!hugetlb)
In reply to David Hildenbrandinclude/linux/mm_types.h struct mm_struct { · line 1072
Quoted 6 lines · David Hildenbrand
include/linux/mm_types.h +6
-0+#ifdef CONFIG_MM_ID +/* +* For init_mm and friends, we don't allocate an ID and use the dummy value +* instead. Limit ourselves to 1M MMs for now: even though we might support +* up to 4M PIDs, having more than 1M MM instances is highly unlikely. +*/
Hm. Should we lower PID_MAX_LIMIT limit then?
Also, do we really need IDA? Can't we derive the ID from mm_struct address?
Quoted 9 lines
include/linux/mm_types.h +6
-0+#define MM_ID_DUMMY 0 +#define MM_ID_NR_BITS 20 +#define MM_ID_MIN (MM_ID_DUMMY + 1) +#define MM_ID_MAX ((1U << MM_ID_NR_BITS) - 1) +#endif /* CONFIG_MM_ID */ +#define MM_MT_FLAGS (MT_FLAGS_ALLOC_RANGE | MT_FLAGS_LOCK_EXTERN | \ MT_FLAGS_USE_RCU)extern struct mm_struct init_mm;
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Re: [PATCH v1 08/17] mm/rmap: initial MM owner tracking for large folios (!hugetlb)
Quoted 9 lines · Kirill A. Shutemov
include/linux/mm_types.h struct mm_struct { · line 1072
Quoted 6 lines · David Hildenbrand
include/linux/mm_types.h +6
-0+#ifdef CONFIG_MM_ID +/* +* For init_mm and friends, we don't allocate an ID and use the dummy value +* instead. Limit ourselves to 1M MMs for now: even though we might support +* up to 4M PIDs, having more than 1M MM instances is highly unlikely. +*/ Hm. Should we lower
PID_MAX_LIMITlimit then?
Note that each thread gets a PID, but all threads share a MM struct. Also we are concerned about PID reuse, but not for MM IDs.
So I don't think we should be touching PID_MAX_LIMIT.
Quoted 3 lines
Also, do we really need IDA? Can't we derive the ID from
mm_structaddress?
Yes, that's the whole purpose of it. We need something < 30bit to save space in struct page.
The description touches on that:
"As we have to squeeze this information into the "struct folio" of even
folios of order-1 (2 pages), and we generally want to reduce the required metadata, we'll assign each MM a unique ID that consumes less than 32 bit. We'll limit the IDs to 20bit / 1M for now: we could allow for up to 30bit, but getting even 1M IDs is unlikely in practice. If required, we could raise the limit later, and the 1M limit might come in handy in the future with other tracking approaches."
Signature · 3 lines
Cheers, David / dhildenb
Re: [PATCH v1 02/17] mm: factor out large folio handling from folio_nr_pages() into folio_large_nr_pages()
In reply to Kirill A. ShutemovQuoted 27 lines · Kirill A. Shutemov
Quoted 26 lines · David Hildenbrand
Let's factor it out into a simple helper function. This helper will also come in handy when working with code where we know that our folio is large.
Make use of it in
internal.handmm.h, where applicable.While at it, let's consistently return a "long" value from all these similar functions. Note that we cannot use "unsigned int" (even though
_folio_nr_pagesis of that type), because it would break some callers that do stuff like "-folio_nr_pages()". Both "int" or "unsigned long" would work as well.Signed-off-by David Hildenbrand <[email protected]>--- include/linux/mm.h | 27 ++++++++++++++------------- mm/internal.h | 2 +- 2 files changed, 15 insertions(+), 14 deletions(-)include/linux/mm.h +0
-0@@ -1076,6 +1076,15 @@ static inline unsigned int folio_large_order(const struct folio *folio)return folio->_flags_1 &0xff ; }
Quoted 11 lines
include/linux/mm.h static inline unsigned int folio_large_order(const struct folio *folio) · line 1087
Quoted 9 lines
include/linux/mm.h +9
-0+static inline long folio_large_nr_pages (const struct folio *folio) +{ +#ifdef CONFIG_64BIT +return folio->_folio_nr_pages; +#else +return 1L <<folio_large_order (folio); +#endif +} +Maybe it would be cleaner to move #ifdef outside of the function?
Yes, can do that.
Signature · 3 lines
Cheers, David / dhildenb