mm: honour compact_unevictable_allowed in mlock and CMA paths
Subsystems (7)
v2 cover mm: honour compact_unevictable_allowed in mlock and CMA paths
From: Wandun Chen <[email protected]>
vm.compact_unevictable_allowed=0 (the default on RT) is meant to keep compaction from touching unevictable folios. Several paths still migrate folios that are about to become unevictable, or in CMA regions, installing migration entries that a later access must wait on, then causing latency spikes on RT kernels.
This series fixes those paths and adds a tracepoint for diagnosis. It is a rework of the RFC [1] per review feedback, mainly from Vlastimil.
RFC --> v2:
1. On top of the isolate-path filtering, also filter by VM_LOCKED during the migration unmap step.
2. Make mlock/mlockall wait for in-flight migration entries, ensuring the folio is on the unevictable LRU before mlock[all] returns.
3. Dropped letting CMA migration take unevictable folios; instead migrate CMA folios out during mlock[all], avoiding migration at cma_alloc time.
4. Moved the tracepoint to the migration unmap path.
[1] https://lore.kernel.org/lkml/[email protected]/
Wandun Chen (4):
mm/migrate: do not migrate folios mapped into VM_LOCKED VMAs under
compaction
mm/mlock: wait for migration to finish when mlocking a folio mm/migrate: add tracepoint for folios unmapped during migration mm/mlock: migrate folios out of CMA when mlocking a range
include/linux/compaction.h | 6 ++ include/linux/rmap.h | 3 + include/trace/events/migrate.h | 29 +++++++ mm/compaction.c | 8 +- mm/migrate.c | 23 +++++- mm/mlock.c | 142 ++++++++++++++++++++++++++++++++- mm/rmap.c | 16 +++- 7 files changed, 216 insertions(+), 11 deletions(-)
Signature · 1 line
2.43.0
PATCH v2 1/4 mm/migrate: do not migrate folios mapped into VM_LOCKED VMAs under compaction
From: Wandun Chen <[email protected]>
When compact_unevictable_allowed=0, unevictable pages should not be migrated. However, mlock_folio_batch in the mlock[all] syscall introduces a race, mlock_folio() sets PG_mlocked immediately but defers PG_unevictable to mlock_folio_batch(), causing pages that are about to become unevictable to be migrated, which violates the intent of compact_unevictable_allowed, and causes spike latency in RT kernels [1].
In order to fix this, migration is forbidden for pages mapped into VMAs marked with VM_LOCKED. In addition, two early-return paths are introduced, filter out mlocked pages, return early to avoid unnecessary operations.
--- include/linux/compaction.h | 6 ++++++ include/linux/rmap.h | 3 +++ mm/compaction.c | 8 +++++++- mm/migrate.c | 23 +++++++++++++++++++---- mm/rmap.c | 12 +++++++++--- 5 files changed, 44 insertions(+), 8 deletions(-)
include/linux/compaction.h +6 -0
@@ -106,6 +106,7 @@ bool compaction_zonelist_suitable(struct alloc_context *ac, int order,extern void __meminit kcompactd_run (int nid);extern void __meminit kcompactd_stop (int nid);extern void wakeup_kcompactd (pg_data_t *pgdat,int order,int highest_zoneidx); +extern bool compaction_allow_unevictable (void );#else static inline void reset_isolation_suitable (pg_data_t *pgdat)
@@ -131,6 +132,11 @@ static inline void wakeup_kcompactd(pg_data_t *pgdat, { } +static inline bool compaction_allow_unevictable (void ) +{ +return true; +} +#endif /* CONFIG_COMPACTION */ struct node ;
include/linux/rmap.h +3 -0
@@ -102,6 +102,9 @@ enum ttu_flags {* do a final flush if necessary */ TTU_RMAP_LOCKED =0x80 ,/* do not grab rmap lock: * caller holds it */ +TTU_RESPECT_MLOCK =0x100 ,/* leave VM_LOCKED vmas mapped instead +* of installing a migration entry +*/ }; #ifdef CONFIG_MMU
mm/compaction.c +7 -1
@@ -1116,7 +1116,8 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, is_unevictable =folio_test_unevictable (folio);/* Compaction might skip unevictable pages but CMA takes them */ -if (!(mode &ISOLATE_UNEVICTABLE ) && is_unevictable) +if (!(mode &ISOLATE_UNEVICTABLE ) && + (is_unevictable ||folio_test_mlocked (folio))) goto isolate_fail_put;/*
@@ -1898,6 +1899,11 @@ typedef enum {* compactable pages. */ static int sysctl_compact_unevictable_allowed__read_mostly =CONFIG_COMPACT_UNEVICTABLE_DEFAULT ; + +bool compaction_allow_unevictable (void ) +{ +return sysctl_compact_unevictable_allowed; +}/* * Tunable for proactive compaction. It determines how * aggressively the kernel should compact memory in the
mm/migrate.c +19 -4
@@ -1202,7 +1202,7 @@ static void migrate_folio_done(struct folio *src,static int migrate_folio_unmap (new_folio_t get_new_folio,free_folio_t put_new_folio,unsigned long private,struct folio *src,struct folio **dstp,enum migrate_mode mode, -struct list_head *ret) +struct list_head *ret,enum migrate_reason reason) {struct folio *dst;int rc = -EAGAIN ;
@@ -1210,6 +1210,7 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,struct anon_vma *anon_vma =NULL ;bool locked = false;bool dst_locked = false; +enum ttu_flags ttu =0 ; dst =get_new_folio (src, private);if (!dst)
@@ -1249,9 +1250,15 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,folio_lock (src); } locked = true; -if (folio_test_mlocked (src)) +if (folio_test_mlocked (src)) { old_folio_state |=FOLIO_WAS_MLOCKED ; +if (reason ==MR_COMPACTION && !compaction_allow_unevictable ()) { + rc = -EBUSY ; + goto out; + } + } +if (folio_test_writeback (src)) {/* * Only in the case of a full synchronous migration is it
@@ -1324,7 +1331,14 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,/* Establish migration ptes */ VM_BUG_ON_FOLIO (folio_test_anon (src) && !folio_test_ksm (src) && !anon_vma, src); -try_to_migrate (src, mode ==MIGRATE_ASYNC ?TTU_BATCH_FLUSH :0 ); + +if (mode ==MIGRATE_ASYNC ) + ttu |=TTU_BATCH_FLUSH ; + +if (reason ==MR_COMPACTION && !compaction_allow_unevictable ()) + ttu |=TTU_RESPECT_MLOCK ; + +try_to_migrate (src, ttu); old_folio_state |=FOLIO_WAS_MAPPED ; }
@@ -1905,7 +1919,8 @@ static int migrate_pages_batch(struct list_head *from, } rc =migrate_folio_unmap (get_new_folio, put_new_folio, - private, folio, &dst, mode, ret_folios); + private, folio, &dst, mode, ret_folios, + reason);/* * The rules are: * 0: folio will be put on unmap_folios list,
mm/rmap.c +9 -3
@@ -2420,6 +2420,9 @@ static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,unsigned long pfn;unsigned long hsz =0 ; +if ((flags &TTU_RESPECT_MLOCK ) && (vma->vm_flags &VM_LOCKED )) +return false; +/* * When racing against e.g. zap_pte_range() on another cpu, * in between its ptep_get_and_clear_full() and folio_remove_rmap_*(),
@@ -2741,11 +2744,14 @@ void try_to_migrate(struct folio *folio, enum ttu_flags flags) };/* -* Migration always ignores mlock and only supports TTU_RMAP_LOCKED and -* TTU_SPLIT_HUGE_PMD, TTU_SYNC, and TTU_BATCH_FLUSH flags. +* Migration normally ignores mlock, but TTU_RESPECT_MLOCK asks it to +* leave folios mapped into VM_LOCKED vmas alone. Only TTU_RMAP_LOCKED, +* TTU_SPLIT_HUGE_PMD, TTU_SYNC, TTU_BATCH_FLUSH and TTU_RESPECT_MLOCK +* are supported. */ if (WARN_ON_ONCE (flags & ~(TTU_RMAP_LOCKED |TTU_SPLIT_HUGE_PMD | -TTU_SYNC |TTU_BATCH_FLUSH ))) +TTU_SYNC |TTU_BATCH_FLUSH | +TTU_RESPECT_MLOCK )))return ; if (folio_is_zone_device(folio) &&
Signature · 1 line
2.43.0
Lorenzo Stoakes
maintainerRe: [PATCH v2 1/4] mm/migrate: do not migrate folios mapped into VM_LOCKED VMAs under compaction
(Being really nitty, your subject line is too long)
Please don't reference legacy VMA flags for newer patches 'do not migrate folios mapped into mlocked VMAs...' works just as well.
Quoted 11 lines · Wandun Chen
From: Wandun Chen <[email protected]>
When compact_unevictable_allowed=0, unevictable pages should not be migrated. However,
mlock_folio_batchin the mlock[all] syscall introduces a race,mlock_folio()setsPG_mlockedimmediately but defersPG_unevictabletomlock_folio_batch(), causing pages that are about to become unevictable to be migrated, which violates the intent ofcompact_unevictable_allowed, and causes spike latency in RT kernels [1].In order to fix this, migration is forbidden for pages mapped into VMAs marked with
VM_LOCKED. In addition, two early-return paths are introduced,
Please don't reference legacy VMA flags. -> VMA_LOCKED_BIT.
Quoted 3 lines
filter out mlocked pages, return early to avoid unnecessary operations.
Fixes 90d07210ab55 ("mm: mlock: use folios and a folio batch internally")
Hmmmm why do you think my patch caused this? That was just a folio conversion?
Also I didn't think we liked having fixes spotted about a series with non-fixes tags?
Quoted 18 lines
Reported-by Alexander Krabler <[email protected]>Closes https://lore.kernel.org/all/DU0PR01MB10385345F7153F334100981888259A@DU0PR01MB10385.eurprd01.prod.exchangelabs.com/ [1] open hereSuggested-by Vlastimil Babka <[email protected]>Signed-off-by Wandun Chen <[email protected]>--- include/linux/compaction.h | 6 ++++++ include/linux/rmap.h | 3 +++ mm/compaction.c | 8 +++++++- mm/migrate.c | 23 +++++++++++++++++++---- mm/rmap.c | 12 +++++++++--- 5 files changed, 44 insertions(+), 8 deletions(-)include/linux/compaction.h +0
-0
include/linux/compaction.h bool compaction_zonelist_suitable(struct alloc_context *ac, int order, · line 109
Quoted 4 lines
include/linux/compaction.h +1
-0@@ -106,6 +106,7 @@ bool compaction_zonelist_suitable(struct alloc_context *ac, int order,extern void __meminit kcompactd_run (int nid);extern void __meminit kcompactd_stop (int nid);extern void wakeup_kcompactd (pg_data_t *pgdat,int order,int highest_zoneidx); +extern bool compaction_allow_unevictable (void );
Don't use extern. We remove extern as we go it's not needed.
Quoted 20 lines
include/linux/compaction.h +5
-0#else static inline void reset_isolation_suitable (pg_data_t *pgdat)@@ -131,6 +132,11 @@ static inline void wakeup_kcompactd(pg_data_t *pgdat, { } +static inline bool compaction_allow_unevictable (void ) +{ +return true; +} +#endif /* CONFIG_COMPACTION */ struct node ;include/linux/rmap.h +0
-0
include/linux/rmap.h enum ttu_flags { · line 105
Quoted 4 lines
include/linux/rmap.h +1
-0@@ -102,6 +102,9 @@ enum ttu_flags {* do a final flush if necessary */ TTU_RMAP_LOCKED =0x80 ,/* do not grab rmap lock: * caller holds it */ + TTU_RESPECT_MLOCK = 0x100,/* leave VM_LOCKED vmas mapped instead
-> VMA_LOCKED_BIT please. Also maybe just say mlock'd?
Quoted 10 lines
include/linux/rmap.h +2
-0+* of installing a migration entry +*/ };#ifdef CONFIG_MMU mm/compaction.c +0
-0
mm/compaction.c isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, · line 1120
Quoted 6 lines
mm/compaction.c +2
-1@@ -1116,7 +1116,8 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, is_unevictable =folio_test_unevictable (folio);/* Compaction might skip unevictable pages but CMA takes them */ -if (!(mode &ISOLATE_UNEVICTABLE ) && is_unevictable) +if (!(mode &ISOLATE_UNEVICTABLE ) && + (is_unevictable ||folio_test_mlocked (folio)))
Maybe just change is_unevictable to include this check?
Like:
is_unevictable = folio_test_unevictable(folio) || folio_test_mlocked(folio);
?
Also later you have:
if (((mode & ISOLATE_ASYNC_MIGRATE) && is_dirty) ||
(mapping && is_unevictable)) {
...Which doesn't account for mlock as-is? Is that correct?
mm/compaction.c typedef enum { · line 1906
Quoted 12 lines
mm/compaction.c +5
-0goto isolate_fail_put;/* @@ -1898,6 +1899,11 @@ typedef enum {* compactable pages. */ static int sysctl_compact_unevictable_allowed__read_mostly =CONFIG_COMPACT_UNEVICTABLE_DEFAULT ; + +bool compaction_allow_unevictable (void ) +{ +return sysctl_compact_unevictable_allowed; +}
You add this helper but isolate_migratepages() still references sysctl_compact_unevictable_allowed directly?
Quoted 17 lines
mm/compaction.c +0
-0/* * Tunable for proactive compaction. It determines how * aggressively the kernel should compact memory in the mm/migrate.c +1
-1@@ -1202,7 +1202,7 @@ static void migrate_folio_done(struct folio *src,static int migrate_folio_unmap (new_folio_t get_new_folio,free_folio_t put_new_folio,unsigned long private,struct folio *src,struct folio **dstp,enum migrate_mode mode, -struct list_head *ret) +struct list_head *ret,enum migrate_reason reason) {struct folio *dst;int rc = -EAGAIN ;
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1213
Quoted 4 lines
mm/migrate.c +1
-0@@ -1210,6 +1210,7 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,struct anon_vma *anon_vma =NULL ;bool locked = false;bool dst_locked = false; +enum ttu_flags ttu =0 ;
You reference ttu only in an if-block below no? So why are you declaring this here? Move it to the if-block.
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1256
Quoted 12 lines
mm/migrate.c +2
-1dst =get_new_folio (src, private);if (!dst)@@ -1249,9 +1250,15 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,folio_lock (src); } locked = true; -if (folio_test_mlocked (src)) +if (folio_test_mlocked (src)) { old_folio_state |=FOLIO_WAS_MLOCKED ; +if (reason ==MR_COMPACTION && !compaction_allow_unevictable ()) {
This should really be a helper since you repeat yourself and it's not obvious what this is checking.
Like:
static migrate_mlock_allowed(enum migrate_reason reason)
{
/* Only compaction is disallowed. */
if (reason != MR_COMPACTION)
return true;
/* If we can compact unevictable folios, we are ok. */
if (compaction_allow_unevictable())
return true;
/* Conservative: if any folio could be mlock()'d, disallow. */
return false;
}Then you could self-document what you're checking and avoid code duplication below.
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1333
Quoted 12 lines
mm/migrate.c +5
-0+ rc = -EBUSY ; + goto out; + } + } +if (folio_test_writeback (src)) {/* * Only in the case of a full synchronous migration is it @@ -1324,7 +1331,14 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,/* Establish migration ptes */ VM_BUG_ON_FOLIO (folio_test_anon (src) && !folio_test_ksm (src) && !anon_vma, src);
Useful to convert VM_BUG_*() -> VM_WARN_*() (possibly _ONCE() here also) as we go!
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1338
Quoted 6 lines
mm/migrate.c +5
-1-try_to_migrate (src, mode ==MIGRATE_ASYNC ?TTU_BATCH_FLUSH :0 ); + +if (mode ==MIGRATE_ASYNC ) + ttu |=TTU_BATCH_FLUSH ; + +if (reason ==MR_COMPACTION && !compaction_allow_unevictable ())
See above about deduplicating.
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1339
Quoted 1 line
mm/migrate.c +1
-0+ ttu |=TTU_RESPECT_MLOCK ;
Hmm. I don't love 'respect mlock'. I guess we only know about the reason being compaction here.
But I'm confused anyway. We have the folio, why aren't we just checking for PG_mlocked() here instead of getting the rmap to see if it's mapped anywhere with VMA_LOCKED_BIT?
Quoted 20 lines
mm/migrate.c +4
-1+ +try_to_migrate (src, ttu); old_folio_state |=FOLIO_WAS_MAPPED ; }@@ -1905,7 +1919,8 @@ static int migrate_pages_batch(struct list_head *from, } rc =migrate_folio_unmap (get_new_folio, put_new_folio, - private, folio, &dst, mode, ret_folios); + private, folio, &dst, mode, ret_folios, + reason);/* * The rules are: * 0: folio will be put on unmap_folios list, mm/rmap.c +0
-0
mm/rmap.c static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma, · line 2423
Quoted 4 lines
mm/rmap.c +1
-0@@ -2420,6 +2420,9 @@ static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,unsigned long pfn;unsigned long hsz =0 ; +if ((flags &TTU_RESPECT_MLOCK ) && (vma->vm_flags &VM_LOCKED ))
Please use the modern API for VMA flags. So:
if ((flags & TTU_RESPECT_MLOCK) && vma_test(VMA_LOCKED_BIT))
mm/rmap.c void try_to_migrate(struct folio *folio, enum ttu_flags flags) · line 2748
Quoted 13 lines
mm/rmap.c +4
-2+return false; +/* * When racing against e.g. zap_pte_range() on another cpu, * in between its ptep_get_and_clear_full() and folio_remove_rmap_*(), @@ -2741,11 +2744,14 @@ void try_to_migrate(struct folio *folio, enum ttu_flags flags) };/* -* Migration always ignores mlock and only supports TTU_RMAP_LOCKED and -* TTU_SPLIT_HUGE_PMD, TTU_SYNC, and TTU_BATCH_FLUSH flags. +* Migration normally ignores mlock, but TTU_RESPECT_MLOCK asks it to +* leave folios mapped into VM_LOCKED vmas alone. Only TTU_RMAP_LOCKED,
Again -> VMA_LOCKED_BIT.
Quoted 11 lines
mm/rmap.c +4
-2+* TTU_SPLIT_HUGE_PMD, TTU_SYNC, TTU_BATCH_FLUSH and TTU_RESPECT_MLOCK +* are supported. */ if (WARN_ON_ONCE (flags & ~(TTU_RMAP_LOCKED |TTU_SPLIT_HUGE_PMD | -TTU_SYNC |TTU_BATCH_FLUSH ))) +TTU_SYNC |TTU_BATCH_FLUSH | +TTU_RESPECT_MLOCK )))return ; if (folio_is_zone_device(folio) && --
Quoted 2 lines
2.43.0
Thanks, Lorenzo
Lorenzo Stoakes
maintainerRe: [PATCH v2 1/4] mm/migrate: do not migrate folios mapped into VM_LOCKED VMAs under compaction
Quoted 10 lines · Lorenzo Stoakes
See above about deduplicating.
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1339
Quoted 1 line
mm/migrate.c +1
-0+ ttu |=TTU_RESPECT_MLOCK ;Hmm. I don't love 'respect mlock'. I guess we only know about the reason being compaction here.
But I'm confused anyway. We have the folio, why aren't we just checking for
PG_mlocked()here instead of getting the rmap to see if it's mapped anywhere withVMA_LOCKED_BIT?
Also, since compaction_allow_unevictable() is a function that is accessible elsewhere, you could literally just have a TTU_MIGRATION here instead and have the rmap logic call compaction_allow_unevictable() instead rather than this.
And then you could adapt the function I suggested before not to take a reason parameter but rather a 'is_migration' one instead possibly and then pass (ttu & TTU_MIGRATION) in.
BUT. I still question whether this is at all needed since you have the folio you can check for PG_mlocked...
Cheers, Lorenzo
Re: [PATCH v2 1/4] mm/migrate: do not migrate folios mapped into VM_LOCKED VMAs under compaction
Quoted 8 lines · Lorenzo Stoakes
Quoted 7 lines · Lorenzo Stoakes
See above about deduplicating.
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1339
Quoted 1 line
mm/migrate.c +1
-0+ ttu |=TTU_RESPECT_MLOCK ;Hmm. I don't love 'respect mlock'. I guess we only know about the reason being compaction here.
Quoted 7 lines
Quoted 3 lines
But I'm confused anyway. We have the folio, why aren't we just checking for
PG_mlocked()here instead of getting the rmap to see if it's mapped anywhere withVMA_LOCKED_BIT?Also, since
compaction_allow_unevictable()is a function that is accessible elsewhere, you could literally just have aTTU_MIGRATIONhere instead and have the rmap logic callcompaction_allow_unevictable()instead rather than this.
Do you mean:
1. change TTU_RESPECT_MLOCK to TTU_MIGRATION, that'is OK.
2. move call compaction_allow_unevictable() to try_to_migrate_one? but as you suggested migrate_mlock_allowed function, it already called compaction_allow_unevictable() in order to determine whether TTU_MIGRATION needs to be added. Did I misunderstand something somewhere?
Quoted 7 lines
And then you could adapt the function I suggested before not to take a reason parameter but rather a '
is_migration' one instead possibly and then pass (ttu &TTU_MIGRATION) in.BUT. I still question whether this is at all needed since you have the folio you can check for
PG_mlocked...
I described a race scenario at this link:
https://lore.kernel.org/lkml/[email protected]/
Quoted 2 lines
Cheers, Lorenzo
Lorenzo Stoakes
maintainerRe: [PATCH v2 1/4] mm/migrate: do not migrate folios mapped into VM_LOCKED VMAs under compaction
Quoted 18 lines · Wandun
Quoted 8 lines · Lorenzo Stoakes
Quoted 7 lines · Lorenzo Stoakes
See above about deduplicating.
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1339
Quoted 1 line
mm/migrate.c +1
-0+ ttu |=TTU_RESPECT_MLOCK ;Hmm. I don't love 'respect mlock'. I guess we only know about the reason being compaction here.
Quoted 7 lines
Quoted 3 lines
But I'm confused anyway. We have the folio, why aren't we just checking for
PG_mlocked()here instead of getting the rmap to see if it's mapped anywhere withVMA_LOCKED_BIT?Also, since
compaction_allow_unevictable()is a function that is accessible elsewhere, you could literally just have aTTU_MIGRATIONhere instead and have the rmap logic callcompaction_allow_unevictable()instead rather than this.
Quoted 6 lines
Do you mean:
1. changeTTU_RESPECT_MLOCKtoTTU_MIGRATION, that'is OK.
2. move callcompaction_allow_unevictable()totry_to_migrate_one? but as you suggestedmigrate_mlock_allowedfunction, it already calledcompaction_allow_unevictable()in order to determine whetherTTU_MIGRATIONneeds to be added. Did I misunderstand something somewhere?
The next paragraph addresses this.
Quoted 8 lines
Quoted 8 lines
And then you could adapt the function I suggested before not to take a reason parameter but rather a '
is_migration' one instead possibly and then pass (ttu &TTU_MIGRATION) in.
Quoted 5 lines
Quoted 2 lines
BUT. I still question whether this is at all needed since you have the folio you can check for
PG_mlocked...I described a race scenario at this link:
https://lore.kernel.org/lkml/[email protected]/
OK thanks. You really have to spell this out in the code in a comment, this is really non-obvious.
I will try to look at your reply in due course (am between jobs atm).
Quoted 5 lines
Quoted 4 lines
Cheers, Lorenzo
Thanks, Lorenzo
Re: [PATCH v2 1/4] mm/migrate: do not migrate folios mapped into VM_LOCKED VMAs under compaction
Quoted 36 lines · Lorenzo Stoakes
Quoted 18 lines · Wandun
Quoted 8 lines · Lorenzo Stoakes
Quoted 7 lines · Lorenzo Stoakes
See above about deduplicating.
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1339
Quoted 1 line
mm/migrate.c +1
-0+ ttu |=TTU_RESPECT_MLOCK ;Hmm. I don't love 'respect mlock'. I guess we only know about the reason being compaction here.
Quoted 7 lines
Quoted 3 lines
But I'm confused anyway. We have the folio, why aren't we just checking for
PG_mlocked()here instead of getting the rmap to see if it's mapped anywhere withVMA_LOCKED_BIT?Also, since
compaction_allow_unevictable()is a function that is accessible elsewhere, you could literally just have aTTU_MIGRATIONhere instead and have the rmap logic callcompaction_allow_unevictable()instead rather than this.Quoted 6 lines
Do you mean:
1. changeTTU_RESPECT_MLOCKtoTTU_MIGRATION, that'is OK.
2. move callcompaction_allow_unevictable()totry_to_migrate_one? but as you suggestedmigrate_mlock_allowedfunction, it already calledcompaction_allow_unevictable()in order to determine whetherTTU_MIGRATIONneeds to be added. Did I misunderstand something somewhere?The next paragraph addresses this.
Quoted 8 lines
Quoted 8 lines
And then you could adapt the function I suggested before not to take a reason parameter but rather a '
is_migration' one instead possibly and then pass (ttu &TTU_MIGRATION) in.
Quoted 8 lines
Quoted 5 lines
Quoted 2 lines
BUT. I still question whether this is at all needed since you have the folio you can check for
PG_mlocked...I described a race scenario at this link:
https://lore.kernel.org/lkml/[email protected]/OK thanks. You really have to spell this out in the code in a comment, this is really non-obvious.
I will address these in the next version.
Thanks,
Wandun
Quoted 10 lines
I will try to look at your reply in due course (am between jobs atm).
Quoted 5 lines
Quoted 4 lines
Cheers, Lorenzo
Thanks, Lorenzo
Re: [PATCH v2 1/4] mm/migrate: do not migrate folios mapped into VM_LOCKED VMAs under compaction
In reply to Lorenzo StoakesQuoted 4 lines · Lorenzo Stoakes
(Being really nitty, your subject line is too long)
Please don't reference legacy VMA flags for newer patches 'do not migrate folios mapped into mlocked VMAs...' works just as well.
Got it.
Quoted 11 lines · Wandun Chen
Quoted 9 lines
From: Wandun Chen <[email protected]>
When compact_unevictable_allowed=0, unevictable pages should not be migrated. However,
mlock_folio_batchin the mlock[all] syscall introduces a race,mlock_folio()setsPG_mlockedimmediately but defersPG_unevictabletomlock_folio_batch(), causing pages that are about to become unevictable to be migrated, which violates the intent ofcompact_unevictable_allowed, and causes spike latency in RT kernels [1].
Quoted 4 lines
Quoted 2 lines
In order to fix this, migration is forbidden for pages mapped into VMAs marked with
VM_LOCKED. In addition, two early-return paths are introduced,Please don't reference legacy VMA flags. ->
VMA_LOCKED_BIT.
Got it.
Quoted 6 lines
Quoted 4 lines
filter out mlocked pages, return early to avoid unnecessary operations.
Fixes 90d07210ab55 ("mm: mlock: use folios and a folio batch internally")Hmmmm why do you think my patch caused this? That was just a folio conversion?
Oh, I made a mistake, your patch was just a folio conversion.
Batching mlocked page was introduced in v5.18 by:
commit 2fbb0c10d1e8 ("mm/munlock: mlock_page() munlock_page() batch by pagevec")
Setting sysctl_compact_unevictable_allowed to zero was introduced in v5.7 by:
commit 6923aa0d8c62 ("mm/compaction: Disable compact_unevictable_allowed on RT")
So this issue exist after v5.18.
Quoted 3 lines
Also I didn't think we liked having fixes spotted about a series with non-fixes tags?
Got it, will split this series in next version.
Quoted 14 lines
Quoted 14 lines
Reported-by Alexander Krabler <[email protected]>Closes https://lore.kernel.org/all/DU0PR01MB10385345F7153F334100981888259A@DU0PR01MB10385.eurprd01.prod.exchangelabs.com/ [1] open hereSuggested-by Vlastimil Babka <[email protected]>Signed-off-by Wandun Chen <[email protected]>--- include/linux/compaction.h | 6 ++++++ include/linux/rmap.h | 3 +++ mm/compaction.c | 8 +++++++- mm/migrate.c | 23 +++++++++++++++++++---- mm/rmap.c | 12 +++++++++--- 5 files changed, 44 insertions(+), 8 deletions(-)
Quoted 11 lines
include/linux/compaction.h bool compaction_zonelist_suitable(struct alloc_context *ac, int order, · line 109
Quoted 9 lines
include/linux/compaction.h +1
-0@@ -106,6 +106,7 @@ bool compaction_zonelist_suitable(struct alloc_context *ac, int order,extern void __meminit kcompactd_run (int nid);extern void __meminit kcompactd_stop (int nid);extern void wakeup_kcompactd (pg_data_t *pgdat,int order,int highest_zoneidx); +extern bool compaction_allow_unevictable (void );Don't use extern. We remove extern as we go it's not needed.
Got it.
Quoted 15 lines
Quoted 15 lines
include/linux/compaction.h +5
-0#else static inline void reset_isolation_suitable (pg_data_t *pgdat)@@ -131,6 +132,11 @@ static inline void wakeup_kcompactd(pg_data_t *pgdat, { } +static inline bool compaction_allow_unevictable (void ) +{ +return true; +} +#endif /* CONFIG_COMPACTION */
Quoted 12 lines
include/linux/rmap.h enum ttu_flags { · line 105
Quoted 10 lines
include/linux/compaction.h +0
-0struct node ;include/linux/rmap.h +1
-0@@ -102,6 +102,9 @@ enum ttu_flags {* do a final flush if necessary */ TTU_RMAP_LOCKED =0x80 ,/* do not grab rmap lock: * caller holds it */ + TTU_RESPECT_MLOCK = 0x100,/* leave VM_LOCKED vmas mapped instead->
VMA_LOCKED_BITplease. Also maybe just say mlock'd?
Got it.
Quoted 20 lines
Quoted 11 lines
include/linux/rmap.h +2
-0+* of installing a migration entry +*/ };#ifdef CONFIG_MMU mm/compaction.c +0
-0mm/compaction.c isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, · line 1120
Quoted 6 lines
mm/compaction.c +2
-1@@ -1116,7 +1116,8 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, is_unevictable =folio_test_unevictable (folio);/* Compaction might skip unevictable pages but CMA takes them */ -if (!(mode &ISOLATE_UNEVICTABLE ) && is_unevictable) +if (!(mode &ISOLATE_UNEVICTABLE ) && + (is_unevictable ||folio_test_mlocked (folio)))Maybe just change
is_unevictableto include this check?
Quoted 6 lines
Like:
is_unevictable = folio_test_unevictable(folio) || folio_test_mlocked(folio);?
Sounds good, I'll fold mlock into is_unevictable so both checks stay consistent.
Quoted 8 lines
Also later you have:
if (((mode & ISOLATE_ASYNC_MIGRATE) && is_dirty) || (mapping && is_unevictable)) { ...Which doesn't account for mlock as-is? Is that correct?
IIUC, The is_unevictable check here mainly serves as a cheap pre-filter for inaccessible mappings (which are always unevictable folio). It's unrelated to the mlock.
Quoted 5 lines
Quoted 5 lines
mm/compaction.c +0
-0goto isolate_fail_put;
Quoted 13 lines
mm/compaction.c typedef enum { · line 1906
Quoted 10 lines
mm/compaction.c +5
-0/* @@ -1898,6 +1899,11 @@ typedef enum {* compactable pages. */ static int sysctl_compact_unevictable_allowed__read_mostly =CONFIG_COMPACT_UNEVICTABLE_DEFAULT ; + +bool compaction_allow_unevictable (void ) +{ +return sysctl_compact_unevictable_allowed; +}You add this helper but
isolate_migratepages()still referencessysctl_compact_unevictable_alloweddirectly?
I'll route that reference through compaction_allow_unevictable() in next version.
Quoted 17 lines
Quoted 17 lines
mm/compaction.c +0
-0/* * Tunable for proactive compaction. It determines how * aggressively the kernel should compact memory in the mm/migrate.c +1
-1@@ -1202,7 +1202,7 @@ static void migrate_folio_done(struct folio *src,static int migrate_folio_unmap (new_folio_t get_new_folio,free_folio_t put_new_folio,unsigned long private,struct folio *src,struct folio **dstp,enum migrate_mode mode, -struct list_head *ret) +struct list_head *ret,enum migrate_reason reason) {struct folio *dst;int rc = -EAGAIN ;
Quoted 8 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1213
Quoted 5 lines
mm/migrate.c +1
-0@@ -1210,6 +1210,7 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,struct anon_vma *anon_vma =NULL ;bool locked = false;bool dst_locked = false; +enum ttu_flags ttu =0 ;You reference ttu only in an if-block below no? So why are you declaring this here? Move it to the if-block.
Got it. I'll move it to the if-block in next version.
Quoted 33 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1256
Quoted 13 lines
mm/migrate.c +2
-1dst =get_new_folio (src, private);if (!dst)@@ -1249,9 +1250,15 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,folio_lock (src); } locked = true; -if (folio_test_mlocked (src)) +if (folio_test_mlocked (src)) { old_folio_state |=FOLIO_WAS_MLOCKED ; +if (reason ==MR_COMPACTION && !compaction_allow_unevictable ()) {This should really be a helper since you repeat yourself and it's not obvious what this is checking.
Like:
static migrate_mlock_allowed(enum migrate_reason reason) { /* Only compaction is disallowed. */ if (reason != MR_COMPACTION) return true; /* If we can compact unevictable folios, we are ok. */ if (compaction_allow_unevictable()) return true; /* Conservative: if any folio could be mlock()'d, disallow. */ return false; }
Quoted 1 line
Then you could self-document what you're checking and avoid code duplication below.
Got it, it is more clear, thanks.
Quoted 15 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1333
Quoted 13 lines
mm/migrate.c +5
-0+ rc = -EBUSY ; + goto out; + } + } +if (folio_test_writeback (src)) {/* * Only in the case of a full synchronous migration is it @@ -1324,7 +1331,14 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,/* Establish migration ptes */ VM_BUG_ON_FOLIO (folio_test_anon (src) && !folio_test_ksm (src) && !anon_vma, src);Useful to convert VM_BUG_*() -> VM_WARN_*() (possibly
_ONCE()here also) as we go!
Got it.
Quoted 10 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1338
Quoted 7 lines
mm/migrate.c +5
-1-try_to_migrate (src, mode ==MIGRATE_ASYNC ?TTU_BATCH_FLUSH :0 ); + +if (mode ==MIGRATE_ASYNC ) + ttu |=TTU_BATCH_FLUSH ; + +if (reason ==MR_COMPACTION && !compaction_allow_unevictable ())See above about deduplicating.
Quoted 4 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1339
Quoted 1 line
mm/migrate.c +1
-0+ ttu |=TTU_RESPECT_MLOCK ;Hmm. I don't love 'respect mlock'. I guess we only know about the reason being compaction here.
Right, we only know about the reason.
Quoted 4 lines
But I'm confused anyway. We have the folio, why aren't we just checking for
PG_mlocked()here instead of getting the rmap to see if it's mapped anywhere withVMA_LOCKED_BIT?
There was a race scenario without patch 02, vma may already marked with VMA_LOCKED_BIT but folio has't marked with mlocked, such as below:
CPUA: mlock() CPUB: compaction / migration
mmap_write_lock()
mlock_fixup set VM_CLOKED
mlock_pte_range
mlock_folio(page N)
isolate page N+50 (mlock hasn't reached it) migrate_folio_unmap folio_test_mlocked() --> false, but VMA:VM_LOCKED try_to_migrate()
rmap_walk(P) [anon_vma rwsem / i_mmap_rwsem, read] try_to_migrate_one -->install migration entry
...reaches page N+50
skip migration entry (without patch 02)mmap_write_unlock()
access page N + 50 --> wait for migration complete
migrate_folios_move
....
migrate completeIf apply patch 02, mlock itself will wait migration complete, so checking VMA_LOCKED_BIT in the rmap path is no longer necessary, but this logic is retained to avoid unnecessary migration operations.
Quoted 24 lines
Quoted 24 lines
mm/migrate.c +4
-1+ +try_to_migrate (src, ttu); old_folio_state |=FOLIO_WAS_MAPPED ; }@@ -1905,7 +1919,8 @@ static int migrate_pages_batch(struct list_head *from, } rc =migrate_folio_unmap (get_new_folio, put_new_folio, - private, folio, &dst, mode, ret_folios); + private, folio, &dst, mode, ret_folios, + reason);/* * The rules are: * 0: folio will be put on unmap_folios list, mm/rmap.c +0
-0@@ -2420,6 +2420,9 @@ static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,unsigned long pfn;unsigned long hsz =0 ;
Quoted 5 lines
mm/rmap.c static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma, · line 2423
Quoted 1 line
mm/rmap.c +1
-0+if ((flags &TTU_RESPECT_MLOCK ) && (vma->vm_flags &VM_LOCKED ))Please use the modern API for VMA flags. So:
if ((flags & TTU_RESPECT_MLOCK) && vma_test(VMA_LOCKED_BIT))
Got it.
Quoted 26 lines
Quoted 7 lines
mm/rmap.c +2
-0+return false; +/* * When racing against e.g. zap_pte_range() on another cpu, * in between its ptep_get_and_clear_full() and folio_remove_rmap_*(), mm/rmap.c void try_to_migrate(struct folio *folio, enum ttu_flags flags) · line 2748
Quoted 7 lines
mm/rmap.c +2
-2@@ -2741,11 +2744,14 @@ void try_to_migrate(struct folio *folio, enum ttu_flags flags) };/* -* Migration always ignores mlock and only supports TTU_RMAP_LOCKED and -* TTU_SPLIT_HUGE_PMD, TTU_SYNC, and TTU_BATCH_FLUSH flags. +* Migration normally ignores mlock, but TTU_RESPECT_MLOCK asks it to +* leave folios mapped into VM_LOCKED vmas alone. Only TTU_RMAP_LOCKED, Again ->
VMA_LOCKED_BIT.Quoted 9 lines
mm/rmap.c +4
-1+* TTU_SPLIT_HUGE_PMD, TTU_SYNC, TTU_BATCH_FLUSH and TTU_RESPECT_MLOCK +* are supported. */ if (WARN_ON_ONCE (flags & ~(TTU_RMAP_LOCKED |TTU_SPLIT_HUGE_PMD | -TTU_SYNC |TTU_BATCH_FLUSH ))) +TTU_SYNC |TTU_BATCH_FLUSH | +TTU_RESPECT_MLOCK )))return ;
Quoted 6 lines
Quoted 4 lines
mm/rmap.c +0
-1if (folio_is_zone_device(folio) && --2.43.0
Thanks, Lorenzo
Thank you for the detailed review, Lorenzo.
many of the comments are very meaningful :)
Best regards
Wandun
Zi Yan
reviewerRe: [PATCH v2 1/4] mm/migrate: do not migrate folios mapped into VM_LOCKED VMAs under compaction
Quoted 284 lines · Wandun
Quoted 4 lines · Lorenzo Stoakes
(Being really nitty, your subject line is too long)
Please don't reference legacy VMA flags for newer patches 'do not migrate folios mapped into mlocked VMAs...' works just as well.
Got it.
Quoted 11 lines · Wandun Chen
Quoted 9 lines
From: Wandun Chen <[email protected]>
When compact_unevictable_allowed=0, unevictable pages should not be migrated. However,
mlock_folio_batchin the mlock[all] syscall introduces a race,mlock_folio()setsPG_mlockedimmediately but defersPG_unevictabletomlock_folio_batch(), causing pages that are about to become unevictable to be migrated, which violates the intent ofcompact_unevictable_allowed, and causes spike latency in RT kernels [1].Quoted 4 lines
Quoted 2 lines
In order to fix this, migration is forbidden for pages mapped into VMAs marked with
VM_LOCKED. In addition, two early-return paths are introduced,Please don't reference legacy VMA flags. ->
VMA_LOCKED_BIT.Got it.
Quoted 6 lines
Quoted 4 lines
filter out mlocked pages, return early to avoid unnecessary operations.
Fixes 90d07210ab55 ("mm: mlock: use folios and a folio batch internally")Hmmmm why do you think my patch caused this? That was just a folio conversion?
Oh, I made a mistake, your patch was just a folio conversion.
Batching mlocked page was introduced in v5.18 by:
commit2fbb0c10d1e8("mm/munlock:mlock_page()munlock_page()batch by pagevec")Setting
sysctl_compact_unevictable_allowedto zero was introduced in v5.7 by:
commit6923aa0d8c62("mm/compaction: Disablecompact_unevictable_allowedon RT")So this issue exist after v5.18.
Quoted 3 lines
Also I didn't think we liked having fixes spotted about a series with non-fixes tags?
Got it, will split this series in next version.
Quoted 14 lines
Quoted 14 lines
Reported-by Alexander Krabler <[email protected]>Closes https://lore.kernel.org/all/DU0PR01MB10385345F7153F334100981888259A@DU0PR01MB10385.eurprd01.prod.exchangelabs.com/ [1] open hereSuggested-by Vlastimil Babka <[email protected]>Signed-off-by Wandun Chen <[email protected]>--- include/linux/compaction.h | 6 ++++++ include/linux/rmap.h | 3 +++ mm/compaction.c | 8 +++++++- mm/migrate.c | 23 +++++++++++++++++++---- mm/rmap.c | 12 +++++++++--- 5 files changed, 44 insertions(+), 8 deletions(-)Quoted 11 lines
include/linux/compaction.h bool compaction_zonelist_suitable(struct alloc_context *ac, int order, · line 109
Quoted 9 lines
include/linux/compaction.h +1
-0@@ -106,6 +106,7 @@ bool compaction_zonelist_suitable(struct alloc_context *ac, int order,extern void __meminit kcompactd_run (int nid);extern void __meminit kcompactd_stop (int nid);extern void wakeup_kcompactd (pg_data_t *pgdat,int order,int highest_zoneidx); +extern bool compaction_allow_unevictable (void );Don't use extern. We remove extern as we go it's not needed.
Got it.
Quoted 15 lines
Quoted 15 lines
include/linux/compaction.h +5
-0#else static inline void reset_isolation_suitable (pg_data_t *pgdat)@@ -131,6 +132,11 @@ static inline void wakeup_kcompactd(pg_data_t *pgdat, { } +static inline bool compaction_allow_unevictable (void ) +{ +return true; +} +#endif /* CONFIG_COMPACTION */ Quoted 12 lines
include/linux/rmap.h enum ttu_flags { · line 105
Quoted 10 lines
include/linux/compaction.h +0
-0struct node ;include/linux/rmap.h +1
-0@@ -102,6 +102,9 @@ enum ttu_flags {* do a final flush if necessary */ TTU_RMAP_LOCKED =0x80 ,/* do not grab rmap lock: * caller holds it */ + TTU_RESPECT_MLOCK = 0x100,/* leave VM_LOCKED vmas mapped instead->
VMA_LOCKED_BITplease. Also maybe just say mlock'd?Got it.
Quoted 20 lines
Quoted 11 lines
include/linux/rmap.h +2
-0+* of installing a migration entry +*/ };#ifdef CONFIG_MMU mm/compaction.c +0
-0mm/compaction.c isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, · line 1120
Quoted 6 lines
mm/compaction.c +2
-1@@ -1116,7 +1116,8 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, is_unevictable =folio_test_unevictable (folio);/* Compaction might skip unevictable pages but CMA takes them */ -if (!(mode &ISOLATE_UNEVICTABLE ) && is_unevictable) +if (!(mode &ISOLATE_UNEVICTABLE ) && + (is_unevictable ||folio_test_mlocked (folio)))Maybe just change
is_unevictableto include this check?Quoted 6 lines
Like:
is_unevictable = folio_test_unevictable(folio) || folio_test_mlocked(folio);?
Sounds good, I'll fold mlock into
is_unevictableso both checks stay consistent.Quoted 8 lines
Also later you have:
if (((mode & ISOLATE_ASYNC_MIGRATE) && is_dirty) || (mapping && is_unevictable)) { ...Which doesn't account for mlock as-is? Is that correct?
IIUC, The
is_unevictablecheck here mainly serves as a cheap pre-filter for inaccessible mappings (which are always unevictable folio). It's unrelated to the mlock.Quoted 5 lines
Quoted 5 lines
mm/compaction.c +0
-0goto isolate_fail_put;Quoted 13 lines
mm/compaction.c typedef enum { · line 1906
Quoted 10 lines
mm/compaction.c +5
-0/* @@ -1898,6 +1899,11 @@ typedef enum {* compactable pages. */ static int sysctl_compact_unevictable_allowed__read_mostly =CONFIG_COMPACT_UNEVICTABLE_DEFAULT ; + +bool compaction_allow_unevictable (void ) +{ +return sysctl_compact_unevictable_allowed; +}You add this helper but
isolate_migratepages()still referencessysctl_compact_unevictable_alloweddirectly?I'll route that reference through
compaction_allow_unevictable()in next version.Quoted 17 lines
Quoted 17 lines
mm/compaction.c +0
-0/* * Tunable for proactive compaction. It determines how * aggressively the kernel should compact memory in the mm/migrate.c +1
-1@@ -1202,7 +1202,7 @@ static void migrate_folio_done(struct folio *src,static int migrate_folio_unmap (new_folio_t get_new_folio,free_folio_t put_new_folio,unsigned long private,struct folio *src,struct folio **dstp,enum migrate_mode mode, -struct list_head *ret) +struct list_head *ret,enum migrate_reason reason) {struct folio *dst;int rc = -EAGAIN ;Quoted 8 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1213
Quoted 5 lines
mm/migrate.c +1
-0@@ -1210,6 +1210,7 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,struct anon_vma *anon_vma =NULL ;bool locked = false;bool dst_locked = false; +enum ttu_flags ttu =0 ;You reference ttu only in an if-block below no? So why are you declaring this here? Move it to the if-block.
Got it. I'll move it to the if-block in next version.
Quoted 33 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1256
Quoted 13 lines
mm/migrate.c +2
-1dst =get_new_folio (src, private);if (!dst)@@ -1249,9 +1250,15 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,folio_lock (src); } locked = true; -if (folio_test_mlocked (src)) +if (folio_test_mlocked (src)) { old_folio_state |=FOLIO_WAS_MLOCKED ; +if (reason ==MR_COMPACTION && !compaction_allow_unevictable ()) {This should really be a helper since you repeat yourself and it's not obvious what this is checking.
Like:
static migrate_mlock_allowed(enum migrate_reason reason) { /* Only compaction is disallowed. */ if (reason != MR_COMPACTION) return true; /* If we can compact unevictable folios, we are ok. */ if (compaction_allow_unevictable()) return true; /* Conservative: if any folio could be mlock()'d, disallow. */ return false; }Quoted 1 line
Then you could self-document what you're checking and avoid code duplication below.
Got it, it is more clear, thanks.
Quoted 15 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1333
Quoted 13 lines
mm/migrate.c +5
-0+ rc = -EBUSY ; + goto out; + } + } +if (folio_test_writeback (src)) {/* * Only in the case of a full synchronous migration is it @@ -1324,7 +1331,14 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,/* Establish migration ptes */ VM_BUG_ON_FOLIO (folio_test_anon (src) && !folio_test_ksm (src) && !anon_vma, src);Useful to convert VM_BUG_*() -> VM_WARN_*() (possibly
_ONCE()here also) as we go!Got it.
Quoted 10 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1338
Quoted 7 lines
mm/migrate.c +5
-1-try_to_migrate (src, mode ==MIGRATE_ASYNC ?TTU_BATCH_FLUSH :0 ); + +if (mode ==MIGRATE_ASYNC ) + ttu |=TTU_BATCH_FLUSH ; + +if (reason ==MR_COMPACTION && !compaction_allow_unevictable ())See above about deduplicating.
Quoted 4 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1339
Quoted 1 line
mm/migrate.c +1
-0+ ttu |=TTU_RESPECT_MLOCK ;Hmm. I don't love 'respect mlock'. I guess we only know about the reason being compaction here.
Right, we only know about the reason.
Quoted 4 lines
But I'm confused anyway. We have the folio, why aren't we just checking for
PG_mlocked()here instead of getting the rmap to see if it's mapped anywhere withVMA_LOCKED_BIT?There was a race scenario without patch 02, vma may already marked with
VMA_LOCKED_BITbut folio has't marked with mlocked, such as below:CPUA:
mlock()CPUB: compaction / migration
mmap_write_lock()
mlock_fixupsetVM_CLOKED
mlock_pte_range
mlock_folio(page N)isolate page N+50 (mlock hasn't reached it)
migrate_folio_unmapfolio_test_mlocked()--> false, but VMA:VM_LOCKEDtry_to_migrate()
rmap_walk(P)[anon_vmarwsem /i_mmap_rwsem, read]try_to_migrate_one-->install migration entry
...reaches page N+50
skip migration entry (without patch 02)mmap_write_unlock()access page N + 50 --> wait for migration complete
migrate_folios_move .... migrate complete
Quoted 4 lines
If apply patch 02, mlock itself will wait migration complete, so checking
VMA_LOCKED_BITin the rmap path is no longer necessary, but this logic is retained to avoid unnecessary migration operations.
For this race condition, since VMA has VM_LOCKED_BIT set, maybe you can extend rwc->invalid_vma semantics to return 1:SKIP, 0:OK, -1:STOP. Then install an invalid_vma function when !compaction_allow_unevictable(). The invalid_vma function returns -1:STOP for any vma with VM_LOCKED_BIT set. __rmap_walk_file() and rmap_walk_anon() will need to break when -1:STOP is returned.
This approach will not require a new TTU flag, although it requires more code changes.
Best Regards,
Yan, Zi
Re: [PATCH v2 1/4] mm/migrate: do not migrate folios mapped into VM_LOCKED VMAs under compaction
Quoted 291 lines · Zi Yan
Quoted 284 lines · Wandun
Quoted 4 lines · Lorenzo Stoakes
(Being really nitty, your subject line is too long)
Please don't reference legacy VMA flags for newer patches 'do not migrate folios mapped into mlocked VMAs...' works just as well.
Got it.
Quoted 11 lines · Wandun Chen
Quoted 9 lines
From: Wandun Chen <[email protected]>
When compact_unevictable_allowed=0, unevictable pages should not be migrated. However,
mlock_folio_batchin the mlock[all] syscall introduces a race,mlock_folio()setsPG_mlockedimmediately but defersPG_unevictabletomlock_folio_batch(), causing pages that are about to become unevictable to be migrated, which violates the intent ofcompact_unevictable_allowed, and causes spike latency in RT kernels [1].Quoted 4 lines
Quoted 2 lines
In order to fix this, migration is forbidden for pages mapped into VMAs marked with
VM_LOCKED. In addition, two early-return paths are introduced,Please don't reference legacy VMA flags. ->
VMA_LOCKED_BIT.Got it.
Quoted 6 lines
Quoted 4 lines
filter out mlocked pages, return early to avoid unnecessary operations.
Fixes 90d07210ab55 ("mm: mlock: use folios and a folio batch internally")Hmmmm why do you think my patch caused this? That was just a folio conversion?
Oh, I made a mistake, your patch was just a folio conversion.
Batching mlocked page was introduced in v5.18 by:
commit2fbb0c10d1e8("mm/munlock:mlock_page()munlock_page()batch by pagevec")Setting
sysctl_compact_unevictable_allowedto zero was introduced in v5.7 by:
commit6923aa0d8c62("mm/compaction: Disablecompact_unevictable_allowedon RT")So this issue exist after v5.18.
Quoted 3 lines
Also I didn't think we liked having fixes spotted about a series with non-fixes tags?
Got it, will split this series in next version.
Quoted 14 lines
Quoted 14 lines
Reported-by Alexander Krabler <[email protected]>Closes https://lore.kernel.org/all/DU0PR01MB10385345F7153F334100981888259A@DU0PR01MB10385.eurprd01.prod.exchangelabs.com/ [1] open hereSuggested-by Vlastimil Babka <[email protected]>Signed-off-by Wandun Chen <[email protected]>--- include/linux/compaction.h | 6 ++++++ include/linux/rmap.h | 3 +++ mm/compaction.c | 8 +++++++- mm/migrate.c | 23 +++++++++++++++++++---- mm/rmap.c | 12 +++++++++--- 5 files changed, 44 insertions(+), 8 deletions(-)Quoted 11 lines
include/linux/compaction.h bool compaction_zonelist_suitable(struct alloc_context *ac, int order, · line 109
Quoted 9 lines
include/linux/compaction.h +1
-0@@ -106,6 +106,7 @@ bool compaction_zonelist_suitable(struct alloc_context *ac, int order,extern void __meminit kcompactd_run (int nid);extern void __meminit kcompactd_stop (int nid);extern void wakeup_kcompactd (pg_data_t *pgdat,int order,int highest_zoneidx); +extern bool compaction_allow_unevictable (void );Don't use extern. We remove extern as we go it's not needed.
Got it.
Quoted 15 lines
Quoted 15 lines
include/linux/compaction.h +5
-0#else static inline void reset_isolation_suitable (pg_data_t *pgdat)@@ -131,6 +132,11 @@ static inline void wakeup_kcompactd(pg_data_t *pgdat, { } +static inline bool compaction_allow_unevictable (void ) +{ +return true; +} +#endif /* CONFIG_COMPACTION */ Quoted 12 lines
include/linux/rmap.h enum ttu_flags { · line 105
Quoted 10 lines
include/linux/compaction.h +0
-0struct node ;include/linux/rmap.h +1
-0@@ -102,6 +102,9 @@ enum ttu_flags {* do a final flush if necessary */ TTU_RMAP_LOCKED =0x80 ,/* do not grab rmap lock: * caller holds it */ + TTU_RESPECT_MLOCK = 0x100,/* leave VM_LOCKED vmas mapped instead->
VMA_LOCKED_BITplease. Also maybe just say mlock'd?Got it.
Quoted 20 lines
Quoted 11 lines
include/linux/rmap.h +2
-0+* of installing a migration entry +*/ };#ifdef CONFIG_MMU mm/compaction.c +0
-0mm/compaction.c isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, · line 1120
Quoted 6 lines
mm/compaction.c +2
-1@@ -1116,7 +1116,8 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, is_unevictable =folio_test_unevictable (folio);/* Compaction might skip unevictable pages but CMA takes them */ -if (!(mode &ISOLATE_UNEVICTABLE ) && is_unevictable) +if (!(mode &ISOLATE_UNEVICTABLE ) && + (is_unevictable ||folio_test_mlocked (folio)))Maybe just change
is_unevictableto include this check?Quoted 6 lines
Like:
is_unevictable = folio_test_unevictable(folio) || folio_test_mlocked(folio);?
Sounds good, I'll fold mlock into
is_unevictableso both checks stay consistent.Quoted 8 lines
Also later you have:
if (((mode & ISOLATE_ASYNC_MIGRATE) && is_dirty) || (mapping && is_unevictable)) { ...Which doesn't account for mlock as-is? Is that correct?
IIUC, The
is_unevictablecheck here mainly serves as a cheap pre-filter for inaccessible mappings (which are always unevictable folio). It's unrelated to the mlock.Quoted 5 lines
Quoted 5 lines
mm/compaction.c +0
-0goto isolate_fail_put;Quoted 13 lines
mm/compaction.c typedef enum { · line 1906
Quoted 10 lines
mm/compaction.c +5
-0/* @@ -1898,6 +1899,11 @@ typedef enum {* compactable pages. */ static int sysctl_compact_unevictable_allowed__read_mostly =CONFIG_COMPACT_UNEVICTABLE_DEFAULT ; + +bool compaction_allow_unevictable (void ) +{ +return sysctl_compact_unevictable_allowed; +}You add this helper but
isolate_migratepages()still referencessysctl_compact_unevictable_alloweddirectly?I'll route that reference through
compaction_allow_unevictable()in next version.Quoted 17 lines
Quoted 17 lines
mm/compaction.c +0
-0/* * Tunable for proactive compaction. It determines how * aggressively the kernel should compact memory in the mm/migrate.c +1
-1@@ -1202,7 +1202,7 @@ static void migrate_folio_done(struct folio *src,static int migrate_folio_unmap (new_folio_t get_new_folio,free_folio_t put_new_folio,unsigned long private,struct folio *src,struct folio **dstp,enum migrate_mode mode, -struct list_head *ret) +struct list_head *ret,enum migrate_reason reason) {struct folio *dst;int rc = -EAGAIN ;Quoted 8 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1213
Quoted 5 lines
mm/migrate.c +1
-0@@ -1210,6 +1210,7 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,struct anon_vma *anon_vma =NULL ;bool locked = false;bool dst_locked = false; +enum ttu_flags ttu =0 ;You reference ttu only in an if-block below no? So why are you declaring this here? Move it to the if-block.
Got it. I'll move it to the if-block in next version.
Quoted 33 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1256
Quoted 13 lines
mm/migrate.c +2
-1dst =get_new_folio (src, private);if (!dst)@@ -1249,9 +1250,15 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,folio_lock (src); } locked = true; -if (folio_test_mlocked (src)) +if (folio_test_mlocked (src)) { old_folio_state |=FOLIO_WAS_MLOCKED ; +if (reason ==MR_COMPACTION && !compaction_allow_unevictable ()) {This should really be a helper since you repeat yourself and it's not obvious what this is checking.
Like:
static migrate_mlock_allowed(enum migrate_reason reason) { /* Only compaction is disallowed. */ if (reason != MR_COMPACTION) return true; /* If we can compact unevictable folios, we are ok. */ if (compaction_allow_unevictable()) return true; /* Conservative: if any folio could be mlock()'d, disallow. */ return false; }Quoted 1 line
Then you could self-document what you're checking and avoid code duplication below.
Got it, it is more clear, thanks.
Quoted 15 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1333
Quoted 13 lines
mm/migrate.c +5
-0+ rc = -EBUSY ; + goto out; + } + } +if (folio_test_writeback (src)) {/* * Only in the case of a full synchronous migration is it @@ -1324,7 +1331,14 @@ static int migrate_folio_unmap(new_folio_t get_new_folio,/* Establish migration ptes */ VM_BUG_ON_FOLIO (folio_test_anon (src) && !folio_test_ksm (src) && !anon_vma, src);Useful to convert VM_BUG_*() -> VM_WARN_*() (possibly
_ONCE()here also) as we go!Got it.
Quoted 10 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1338
Quoted 7 lines
mm/migrate.c +5
-1-try_to_migrate (src, mode ==MIGRATE_ASYNC ?TTU_BATCH_FLUSH :0 ); + +if (mode ==MIGRATE_ASYNC ) + ttu |=TTU_BATCH_FLUSH ; + +if (reason ==MR_COMPACTION && !compaction_allow_unevictable ())See above about deduplicating.
Quoted 4 lines
mm/migrate.c static int migrate_folio_unmap(new_folio_t get_new_folio, · line 1339
Quoted 1 line
mm/migrate.c +1
-0+ ttu |=TTU_RESPECT_MLOCK ;Hmm. I don't love 'respect mlock'. I guess we only know about the reason being compaction here.
Right, we only know about the reason.
Quoted 4 lines
But I'm confused anyway. We have the folio, why aren't we just checking for
PG_mlocked()here instead of getting the rmap to see if it's mapped anywhere withVMA_LOCKED_BIT?There was a race scenario without patch 02, vma may already marked with
VMA_LOCKED_BITbut folio has't marked with mlocked, such as below:CPUA:
mlock()CPUB: compaction / migration
mmap_write_lock()
mlock_fixupsetVM_CLOKED
mlock_pte_range
mlock_folio(page N)isolate page N+50 (mlock hasn't reached it)
migrate_folio_unmapfolio_test_mlocked()--> false, but VMA:VM_LOCKEDtry_to_migrate()
rmap_walk(P)[anon_vmarwsem /i_mmap_rwsem, read]try_to_migrate_one-->install migration entry
...reaches page N+50
skip migration entry (without patch 02)mmap_write_unlock()access page N + 50 --> wait for migration complete
migrate_folios_move .... migrate completeQuoted 4 lines
If apply patch 02, mlock itself will wait migration complete, so checking
VMA_LOCKED_BITin the rmap path is no longer necessary, but this logic is retained to avoid unnecessary migration operations.
Quoted 6 lines
For this race condition, since VMA has
VM_LOCKED_BITset, maybe you can extendrwc->invalid_vmasemantics to return 1:SKIP, 0:OK, -1:STOP. Then install aninvalid_vmafunction when !compaction_allow_unevictable(). Theinvalid_vmafunction returns -1:STOP for any vma withVM_LOCKED_BITset.__rmap_walk_file()andrmap_walk_anon()will need to break when -1:STOP is returned.
Hi Zi Yan,
Thanks for the suggestion, I really like this approach. Adding a TTU flag and the corresponding check in the rmap logic does make the code more complex. With the addition of STOP logic, the entire patch becomes very clear and readable.
Hi, Lorenzo, would you be happy with Yan's invalid_vma STOP extension? I'm inclined toward the this since it removes the new flag and reads more clearly.
Best regards,
Wandun
Quoted 6 lines
This approach will not require a new TTU flag, although it requires more code changes.
Best Regards,
Yan, Zi
PATCH v2 2/4 mm/mlock: wait for migration to finish when mlocking a folio
In reply to Wandun ChenFrom: Wandun Chen <[email protected]>
In RT kernels, sysctl_compact_unevictable_allowed is false by default, when the mlock/mlockall system call try to lock all the present page, the mlock_pte_range function skips non-present entries. If these non-present entries are migration entries, and the migration is not guaranteed to have completed before the mlock/mlockall, it may result in a page fault on subsequent access, which then waits for the migration to finish, causing spike latency in RT kernels.
Fix it by waiting for the migration to complete during the mlock/mlockall syscall when sysctl_compact_unevictable_allowed is false.
--- mm/mlock.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-)
mm/mlock.c +21 -2
@@ -25,6 +25,7 @@#include <linux/memcontrol.h> #include <linux/mm_inline.h> #include <linux/secretmem.h> +#include <linux/compaction.h> #include "internal.h"
@@ -361,8 +362,17 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr, ptl =pmd_trans_huge_lock (pmd, vma);if (ptl) { -if (!pmd_present (*pmd)) +if (!pmd_present (*pmd)) { +if (unlikely ((vma->vm_flags &VM_LOCKED ) && + !compaction_allow_unevictable () && +softleaf_is_migration (softleaf_from_pmd (*pmd)))) { +spin_unlock (ptl); +pmd_migration_entry_wait (vma->vm_mm, pmd); + walk->action =ACTION_AGAIN ; +return 0 ; + } goto out; + }if (is_huge_zero_pmd (*pmd)) goto out; folio =pmd_folio (*pmd);
@@ -383,8 +393,17 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr,for (pte = start_pte; addr != end; pte++, addr +=PAGE_SIZE ) { ptent =ptep_get (pte); -if (!pte_present (ptent)) +if (!pte_present (ptent)) { +if (unlikely ((vma->vm_flags &VM_LOCKED ) && + !compaction_allow_unevictable () && +softleaf_is_migration (softleaf_from_pte (ptent)))) { +pte_unmap_unlock (start_pte, ptl); +migration_entry_wait (vma->vm_mm, pmd, addr); + walk->action =ACTION_AGAIN ; +return 0 ; + }continue ; + } folio =vm_normal_folio (vma, addr, ptent);if (!folio ||folio_is_zone_device (folio))continue ;
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v2 2/4] mm/mlock: wait for migration to finish when mlocking a folio
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Returning ACTION_AGAIN from the PTE loop causes double-counting of folio mlock_count, permanently…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Returning ACTION_AGAIN from the PTE loop causes double-counting of folio mlock_count, permanently stranding folios on the unevictable list. --
--- Patch [2]: [PATCH v2 2/4] mm/mlock: wait for migration to finish when mlocking a folio --- commit 5e064939ab68367720d5bb81c64aebdb067992b6
Author: Wandun Chen <[email protected]>
mm/mlock: wait for migration to finish when mlocking a folio
This commit modifies mlock to wait for migration entries when compaction_allow_unevictable is false. This prevents spike latency in RT kernels caused by page faults waiting on migration after mlocking.
Quoted 4 lines
mm/mlock.c +0
-0
[ ... ]
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 403
Quoted 13 lines
mm/mlock.c +8
-1@@ -383,8 +393,17 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr,for (pte = start_pte; addr != end; pte++, addr +=PAGE_SIZE ) { ptent =ptep_get (pte); -if (!pte_present (ptent)) +if (!pte_present (ptent)) { +if (unlikely ((vma->vm_flags &VM_LOCKED ) && + !compaction_allow_unevictable () && +softleaf_is_migration (softleaf_from_pte (ptent)))) { +pte_unmap_unlock (start_pte, ptl); +migration_entry_wait (vma->vm_mm, pmd, addr); + walk->action =ACTION_AGAIN ; +return 0 ;
[Severity: High]
Does returning ACTION_AGAIN from within the PTE loop cause mlock_count to be inflated for previously processed PTEs?
If the loop processes some present PTEs (calling mlock_folio() on them) and then encounters a migration entry, it returns ACTION_AGAIN. This causes the generic page table walker to restart the callback from the original PMD start address:
mm/pagewalk.c:walk_pmd_range() {
again:
... if (ops->pmd_entry) err = ops->pmd_entry(pmd, addr, next, walk); if (err) break; if (walk->action == ACTION_AGAIN) goto again; ... }
Because addr was not advanced in walk_pmd_range(), mlock_pte_range() will process the earlier PTEs a second time, incrementing folio->mlock_count again. When the VMA is later unmapped, mlock_count will never reach zero, permanently stranding these folios on the unevictable list and leaking memory.
Quoted 6 lines
mm/mlock.c +2
-0+ }continue ; + } folio =vm_normal_folio (vma, addr, ptent);if (!folio ||folio_is_zone_device (folio))continue ;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Lorenzo Stoakes
maintainerRe: [PATCH v2 2/4] mm/mlock: wait for migration to finish when mlocking a folio
In reply to Wandun ChenQuoted 9 lines · Wandun Chen
From: Wandun Chen <[email protected]>
In RT kernels,
sysctl_compact_unevictable_allowedis false by default, when the mlock/mlockall system call try to lock all the present page, themlock_pte_rangefunction skips non-present entries. If these non-present entries are migration entries, and the migration is not guaranteed to have completed before the mlock/mlockall, it may result in a page fault on subsequent access, which then waits for the migration to finish, causing spike latency in RT kernels.
Is this really noticable and measurable?
I suppose not too many ranges should be mock
Quoted 3 lines
Fix it by waiting for the migration to complete during the mlock/mlockall syscall when
sysctl_compact_unevictable_allowedis false.
Probably better to reference the sysctl itself rather than an arbitrary varible name.
Quoted 2 lines
Fixes 90d07210ab55 ("mm: mlock: use folios and a folio batch internally")
Again I have no idea why you chose this as the fixes target, especially for this?
But in any case, why is this separate from the previous commit? I sthis an entirely separate fix?
Quoted 3 lines
Suggested-by Vlastimil Babka <[email protected]>Signed-off-by Wandun Chen <[email protected]>
A nit but please strip that #t.
Quoted 17 lines
--- mm/mlock.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-)mm/mlock.c +1
-0@@ -25,6 +25,7 @@#include <linux/memcontrol.h> #include <linux/mm_inline.h> #include <linux/secretmem.h> +#include <linux/compaction.h> #include "internal.h"
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 366
Quoted 6 lines
mm/mlock.c +2
-1@@ -361,8 +362,17 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr, ptl =pmd_trans_huge_lock (pmd, vma);if (ptl) { -if (!pmd_present (*pmd)) +if (!pmd_present (*pmd)) { + if (unlikely((vma->vm_flags & VM_LOCKED) &&
-> vma_test(vma, VMA_LOCKED_BIT)...
What is the basis for your unlikely()? Don't use likely()/unlikely() just because it feels right. Leave them out unless you have actual profiling data to prove it.
Remove it please.
But I'm also confused here - why are you checking for VMAs that already had VMA_LOCKED_BIT set when you are about to set it?
Surely this shouldn't be predicated on VMA_LOCKED_BIT?
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 367
Quoted 1 line
mm/mlock.c +1
-0+ !compaction_allow_unevictable() &&
Why do we care about compaction here? Are we assuming the softleaf migration entry is present only for compaction reasons?
So these migration entries could be there for any reason? Does it matter? Is it such a big deal, on mlock, to wait for migration entries? I think probably not.
But then maybe some weird workload gets affected... hmm.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 368
Quoted 1 line
mm/mlock.c +1
-0+ softleaf_is_migration(softleaf_from_pmd(*pmd)))) {
Use pmd_is_migration_entry()? :)
And technically you should use pmdp_get() I think? Maybe a situation where we don't care/need the READ_ONCE() though.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 373
Quoted 5 lines
mm/mlock.c +5
-0+spin_unlock (ptl); +pmd_migration_entry_wait (vma->vm_mm, pmd); + walk->action =ACTION_AGAIN ; +return 0 ; + }
This code is really disgusting, let's please not just copy/paste open-coded nested horror shows like this.
A good rule of thumb is if you see a bunch of code 'poking out' like this and certainly if you copy/paste it or something very much like it, break it out into a function.
So:
static bool wait_for_migration(const struct vm_area_struct *vma, softleaf_t entry) {
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
As above I'm not sure should even be checking this?
if (!vma_test(vma, VMA_LOCKED_BIT)) return false;
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
As above I'm not sure this makes sense?
if (compaction_allowed_unevictable()) return false; return softleaf_is_migration(entry); }
Then call it like:
if (ptl) {
const pmd_t pmd = pmdp_get(pmd);
if (!pmd_present(pmd)) {
const softleaf_t entry = softleaf_from_pmd(pmd);
if (!wait_for_migration(vma, entry))
goto out;
spin_unlock(ptl);
pmd_migration_entry_wait(vma->vm_mm, pmd);
walk->action = ACTION_AGAIN;
return 0;
}
if (is_huge_zero_pmd(pmd))
goto out;(etc. going *pmd -> pmd)
But we could probably do even better than that, and assuming your dubious checks above aren't needed, we don't even need a helper then:
if (ptl) {
const pmd_t pmd = pmdp_get(pmd); // possibly just *pmd?
const softleaf_t entry = softleaf_from_pmd(pmd);
if (softleaf_is_migration(entry)) {
/* Wait for migration entries. */
spin_unlock(ptl);
pmd_migration_entry_wait(vma->vm_mm, pmd);
walk->action = ACTION_AGAIN;
return 0;
}
if (!pmd_present(pmd))
goto out;
etc.And similar for the PTE stuff below.
This works because softleaf_from_pmd() (and pte) will give you a 'none' softleaf if the entry is not a softlaf entry. So you can unconditionally call it on a PMD.
Quoted 25 lines
mm/mlock.c +11
-2goto out; + }if (is_huge_zero_pmd (*pmd)) goto out; folio =pmd_folio (*pmd);@@ -383,8 +393,17 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr,for (pte = start_pte; addr != end; pte++, addr +=PAGE_SIZE ) { ptent =ptep_get (pte); -if (!pte_present (ptent)) +if (!pte_present (ptent)) { +if (unlikely ((vma->vm_flags &VM_LOCKED ) && + !compaction_allow_unevictable () && +softleaf_is_migration (softleaf_from_pte (ptent)))) { +pte_unmap_unlock (start_pte, ptl); +migration_entry_wait (vma->vm_mm, pmd, addr); + walk->action =ACTION_AGAIN ; +return 0 ; + }continue ; + } folio =vm_normal_folio (vma, addr, ptent);if (!folio ||folio_is_zone_device (folio))continue ; --
Quoted 2 lines
2.43.0
Thanks, Lorenzo
Sebastian Andrzej Siewior
maintainerRe: [PATCH v2 2/4] mm/mlock: wait for migration to finish when mlocking a folio
Quoted 11 lines · Lorenzo Stoakes
Quoted 9 lines · Wandun Chen
From: Wandun Chen <[email protected]>
In RT kernels,
sysctl_compact_unevictable_allowedis false by default, when the mlock/mlockall system call try to lock all the present page, themlock_pte_rangefunction skips non-present entries. If these non-present entries are migration entries, and the migration is not guaranteed to have completed before the mlock/mlockall, it may result in a page fault on subsequent access, which then waits for the migration to finish, causing spike latency in RT kernels.
Quoted 1 line
Is this really noticable and measurable?
You want to avoid page faults like this which is why you do mlock in the first place.
If the thread has a RT priority and it blocks here then other RT threads will be scheduled and your migration thread, which will resolve this, is SCHED_OTHER and the last one in the line. Assuming that thread has a 1ms cycle/ deadline then it will likely miss it.
Quoted 1 line
I suppose not too many ranges should be mock
Sebastian
Re: [PATCH v2 2/4] mm/mlock: wait for migration to finish when mlocking a folio
In reply to Lorenzo StoakesQuoted 11 lines · Lorenzo Stoakes
Quoted 9 lines · Wandun Chen
From: Wandun Chen <[email protected]>
In RT kernels,
sysctl_compact_unevictable_allowedis false by default, when the mlock/mlockall system call try to lock all the present page, themlock_pte_rangefunction skips non-present entries. If these non-present entries are migration entries, and the migration is not guaranteed to have completed before the mlock/mlockall, it may result in a page fault on subsequent access, which then waits for the migration to finish, causing spike latency in RT kernels.
Quoted 1 line
Is this really noticable and measurable?
Alexander Krabler reported a 1.1ms latency in [1]
Quoted 9 lines
I suppose not too many ranges should be mock
Quoted 3 lines
Fix it by waiting for the migration to complete during the mlock/mlockall syscall when
sysctl_compact_unevictable_allowedis false.Probably better to reference the sysctl itself rather than an arbitrary varible name.
Got it.
Quoted 6 lines
Quoted 3 lines
Fixes 90d07210ab55 ("mm: mlock: use folios and a folio batch internally")Again I have no idea why you chose this as the fixes target, especially for this?
You're right, the Fixes tag was wrong.
Setting sysctl_compact_unevictable_allowed to zero was introduced in v5.7 by:
commit 6923aa0d8c62 ("mm/compaction: Disable compact_unevictable_allowed on RT")
Before this commit, mlocked page can be migrated, and dont need to wait for migration complete.
After this commit, if don't wait for migration complete, this may result in latency spikes.
(The batch mlock feature increases the probability of hitting migration entries.)
Will update Fixes tag in next version.
Quoted 3 lines
But in any case, why is this separate from the previous commit? I sthis an entirely separate fix?
These two patches address two aspects of the same problem, and I split them into separate patches mainly to make review easier.
Patch 1 mainly prevents pages to be migrated due to batch mlock; patch 2 mainly ensures that pages undergoing migration have finished migrating once the mlock system call completes.
Quoted 6 lines
Quoted 4 lines
Suggested-by Vlastimil Babka <[email protected]>Signed-off-by Wandun Chen <[email protected]>A nit but please strip that #t.
Got it.
Quoted 27 lines
Quoted 18 lines
--- mm/mlock.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-)mm/mlock.c +1
-0@@ -25,6 +25,7 @@#include <linux/memcontrol.h> #include <linux/mm_inline.h> #include <linux/secretmem.h> +#include <linux/compaction.h> #include "internal.h" mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 366
Quoted 6 lines
mm/mlock.c +2
-1@@ -361,8 +362,17 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr, ptl =pmd_trans_huge_lock (pmd, vma);if (ptl) { -if (!pmd_present (*pmd)) +if (!pmd_present (*pmd)) { + if (unlikely((vma->vm_flags & VM_LOCKED) &&->
vma_test(vma, VMA_LOCKED_BIT)...
Quoted 5 lines
What is the basis for your
unlikely()? Don't use likely()/unlikely() just because it feels right. Leave them out unless you have actual profiling data to prove it.Remove it please.
Got it.
Quoted 5 lines
But I'm also confused here - why are you checking for VMAs that already had
VMA_LOCKED_BITset when you are about to set it?Surely this shouldn't be predicated on
VMA_LOCKED_BIT?
munlock also would call mlock_pte_range, if page is under undergoing migration, munlock dont need to wait migration complete.
Quoted 11 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 367
Quoted 3 lines
mm/mlock.c +1
-0+ !compaction_allow_unevictable() &&Why do we care about compaction here? Are we assuming the softleaf migration entry is present only for compaction reasons?
So these migration entries could be there for any reason? Does it matter? Is it such a big deal, on mlock, to wait for migration entries? I think probably not.
But then maybe some weird workload gets affected... hmm.
Indeed, there are workloads that are affected by this.
In RT kernels, RT processes typically use mlock to prevent their memory from being swapped out, and sysctl_compact_unevictable_is set to default 0 in the RT kernels, so mlocked memory won't be migrated and won't encounter migration entries on access.
Using compaction_allow_unevictable here is mainly to check whether the system is latency-sensitive. In RT kernels, sysctl_compact_unevictable_is set to 0 by default.
If there is no waiting, the migration may won't have completed by the time of the subsequent memory access, and then we would have to wait for migration to finish in the page fault path. Since pmd_migration_entry_wait/migration_entry_wait has no priority-propagation mechanism, if the process executing mlock is an RT process, this can lead to priority inversion and latency spike occurs.
Quoted 4 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 368
Quoted 2 lines
mm/mlock.c +1
-0+ softleaf_is_migration(softleaf_from_pmd(*pmd)))) {Use
pmd_is_migration_entry()? :)
Got it.
Quoted 13 lines
And technically you should use
pmdp_get()I think? Maybe a situation where we don't care/need theREAD_ONCE()though.mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 373
Quoted 5 lines
mm/mlock.c +5
-0+spin_unlock (ptl); +pmd_migration_entry_wait (vma->vm_mm, pmd); + walk->action =ACTION_AGAIN ; +return 0 ; + }This code is really disgusting, let's please not just copy/paste open-coded nested horror shows like this.
Quoted 3 lines
A good rule of thumb is if you see a bunch of code 'poking out' like this and certainly if you copy/paste it or something very much like it, break it out into a function.
Got it, will do in next version.
Quoted 54 lines
So:
static bool
wait_for_migration(const struct vm_area_struct *vma, softleaf_t entry){Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
As above I'm not sure should even be checking this?
if (!vma_test(vma, VMA_LOCKED_BIT)) return false;Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
As above I'm not sure this makes sense?
if (compaction_allowed_unevictable()) return false; return softleaf_is_migration(entry); }Then call it like:
if (ptl) { const pmd_t pmd = pmdp_get(pmd); if (!pmd_present(pmd)) { const softleaf_t entry = softleaf_from_pmd(pmd); if (!wait_for_migration(vma, entry)) goto out; spin_unlock(ptl); pmd_migration_entry_wait(vma->vm_mm, pmd); walk->action = ACTION_AGAIN; return 0; } if (is_huge_zero_pmd(pmd)) goto out;(etc. going *pmd -> pmd)
But we could probably do even better than that, and assuming your dubious checks above aren't needed, we don't even need a helper then:
if (ptl) { const pmd_t pmd = pmdp_get(pmd); // possibly just *pmd? const softleaf_t entry = softleaf_from_pmd(pmd); if (softleaf_is_migration(entry)) { /* Wait for migration entries. */ spin_unlock(ptl); pmd_migration_entry_wait(vma->vm_mm, pmd); walk->action = ACTION_AGAIN; return 0; } if (!pmd_present(pmd)) goto out; etc.
Quoted 5 lines
And similar for the PTE stuff below.
This works because
softleaf_from_pmd()(and pte) will give you a 'none' softleaf if the entry is not a softlaf entry. So you can unconditionally call it on a PMD.
Got it.
Quoted 22 lines
Quoted 22 lines
mm/mlock.c +11
-1goto out; + }if (is_huge_zero_pmd (*pmd)) goto out; folio =pmd_folio (*pmd);@@ -383,8 +393,17 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr,for (pte = start_pte; addr != end; pte++, addr +=PAGE_SIZE ) { ptent =ptep_get (pte); -if (!pte_present (ptent)) +if (!pte_present (ptent)) { +if (unlikely ((vma->vm_flags &VM_LOCKED ) && + !compaction_allow_unevictable () && +softleaf_is_migration (softleaf_from_pte (ptent)))) { +pte_unmap_unlock (start_pte, ptl); +migration_entry_wait (vma->vm_mm, pmd, addr); + walk->action =ACTION_AGAIN ; +return 0 ; + }continue ; + }
Quoted 8 lines
Quoted 6 lines
mm/mlock.c +0
-1folio =vm_normal_folio (vma, addr, ptent);if (!folio ||folio_is_zone_device (folio))continue ; --2.43.0
Thanks, Lorenzo
Thanks again.
Wandun
PATCH v2 3/4 mm/migrate: add tracepoint for folios unmapped during migration
In reply to Wandun ChenFrom: Wandun Chen <[email protected]>
Add mm_migrate_unmap_folio tracepoint, fired in try_to_migrate_one() after a folio's mapping has been replaced by a migration entry. It records the pfn, address, folio flags and vm_flags, making mlocked folios under migration easy to observe.
--- include/trace/events/migrate.h | 29 +++++++++++++++++++++++++++++ mm/rmap.c | 4 ++++ 2 files changed, 33 insertions(+)
include/trace/events/migrate.h +29 -0
@@ -6,6 +6,7 @@#define _TRACE_MIGRATE_H#include <linux/tracepoint.h> +#include <trace/events/mmflags.h> #define MIGRATE_MODE \ EM( MIGRATE_ASYNC, "MIGRATE_ASYNC") \
@@ -137,6 +138,34 @@ DEFINE_EVENT(migration_pte, set_migration_pte,TP_ARGS (addr, pte, order) ); +TRACE_EVENT (mm_migrate_unmap_folio, + + TP_PROTO(unsigned long pfn, unsigned long addr, + unsigned long page_flags, unsigned long vm_flags), + +TP_ARGS (pfn, addr, page_flags, vm_flags), + +TP_STRUCT__entry ( + __field(unsigned long, pfn) + __field(unsigned long, addr) + __field(unsigned long, page_flags) + __field(unsigned long, vm_flags) + ), + +TP_fast_assign ( + __entry->pfn = pfn; + __entry->addr = addr; + __entry->page_flags = page_flags; + __entry->vm_flags = vm_flags; + ), + +TP_printk ("pfn=0x%lx addr=0x%lx page_flags=%s vm_flags=%s" , + __entry->pfn, + __entry->addr, +show_page_flags (__entry->page_flags &PAGEFLAGS_MASK ), +show_vma_flags (__entry->vm_flags)) +); +DEFINE_EVENT (migration_pte, remove_migration_pte, TP_PROTO(unsigned long addr, unsigned long pte, int order), TP_ARGS(addr, pte, order)
mm/rmap.c +4 -0
@@ -2716,6 +2716,10 @@ static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,hugetlb_remove_rmap (folio); elsefolio_remove_rmap_pte (folio ,subpage ,vma ); + +trace_mm_migrate_unmap_folio (folio_pfn (folio), address, + folio->flags.f, vma->vm_flags); +if (vma->vm_flags &VM_LOCKED )mlock_drain_local ();folio_put (folio);
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v2 3/4] mm/migrate: add tracepoint for folios unmapped during migration
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Returning ACTION_AGAIN from inside the PTE loop in `mlock_pte_range` causes double-counting of…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Returning ACTION_AGAIN from inside the PTE loop in mlock_pte_range causes double-counting of mlock_count for folios processed earlier in the same PMD. --
--- Patch [3]: [PATCH v2 3/4] mm/migrate: add tracepoint for folios unmapped during migration --- commit 66d2b427e02176d2cc56e534e84b38ba838aacba
Author: Wandun Chen <[email protected]>
mm/migrate: add tracepoint for folios unmapped during migration
This commit adds the mm_migrate_unmap_folio tracepoint to try_to_migrate_one(). The tracepoint records the PFN, address, and flags when a folio's mapping is replaced by a migration entry, aiding observation of mlocked folios under migration.
mm/rmap.c static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma, · line 2729
Quoted 12 lines
mm/rmap.c +4
-0@@ -2723,6 +2723,10 @@ static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,hugetlb_remove_rmap (folio); elsefolio_remove_rmap_pte (folio ,subpage ,vma ); + +trace_mm_migrate_unmap_folio (folio_pfn (folio), address, + folio->flags.f, vma->vm_flags); +
[Severity: High]
When try_to_migrate_one() replaces a mapping with a migration entry here, can this cause a double-counting issue during concurrent mlock() calls?
If mlock_pte_range() encounters this migration entry midway through a PMD range, it sets walk->action = ACTION_AGAIN and returns 0:
mm/mlock.c:mlock_pte_range() {
...
for (pte = start_pte; addr != end; pte++, addr += PAGE_SIZE) {
ptent = ptep_get(pte);
if (!pte_present(ptent)) {
if (unlikely((vma->vm_flags & VM_LOCKED) &&
!compaction_allow_unevictable() &&
softleaf_is_migration(softleaf_from_pte(ptent)))) {
pte_unmap_unlock(start_pte, ptl);
migration_entry_wait(vma->vm_mm, pmd, addr);
walk->action = ACTION_AGAIN;
return 0;
}
continue;
}
...
if (vma->vm_flags & VM_LOCKED)
mlock_folio(folio);
...
}Because the page walker handles ACTION_AGAIN by restarting from the beginning of the PMD without advancing addr, will the folios processed earlier in this PMD be processed again?
Could this cause mlock_folio() to artificially inflate their mlock_count for each duplicate pass, permanently stranding the memory in the unevictable LRU?
Quoted 3 lines
mm/rmap.c +0
-0if (vma->vm_flags &VM_LOCKED )mlock_drain_local ();folio_put (folio);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
PATCH v2 4/4 mm/mlock: migrate folios out of CMA when mlocking a range
In reply to Wandun ChenFrom: Wandun Chen <[email protected]>
The region covered by mlock[all] may contain CMA pages. cma_alloc installs migration entries in the page table, if a memory access occurs at this point, it must wait for the migration to complete, which may cause latency spikes on the RT kernels.
Try to move the migration cost into the mlock[all] caller, which is typically a setup path. So reduce the chance of latency spikes on RT kernels by migrating the currently mapped CMA pages out of CMA region.
--- mm/mlock.c | 119 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 118 insertions(+), 1 deletion(-)
mm/mlock.c +118 -1
@@ -25,6 +25,7 @@#include <linux/memcontrol.h> #include <linux/mm_inline.h> #include <linux/secretmem.h> +#include <linux/migrate.h> #include <linux/compaction.h> #include "internal.h"
@@ -428,6 +429,119 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr,return 0 ; } +#ifdef CONFIG_CMA +static int mlock_collect_migratable_pte_range (pmd_t *pmd,unsigned long addr, +unsigned long end,struct mm_walk *walk) +{ +struct vm_area_struct *vma = walk->vma; +struct list_head *folio_list = walk->private; +spinlock_t *ptl; +pte_t *start_pte, *pte; +pte_t ptent; +struct folio *folio; +unsigned int step =1 ; + +if (!(vma->vm_flags &VM_LOCKED )) +return 0 ; + + ptl =pmd_trans_huge_lock (pmd, vma); +if (ptl) { +if (!pmd_present (*pmd)) { +if (unlikely (softleaf_is_migration (softleaf_from_pmd (*pmd)))) { +spin_unlock (ptl); +pmd_migration_entry_wait (vma->vm_mm, pmd); + walk->action =ACTION_AGAIN ; +return 0 ; + } + goto out; + } +if (is_huge_zero_pmd (*pmd)) + goto out; + folio =pmd_folio (*pmd); +if (folio_is_zone_device (folio)) + goto out; +if (is_migrate_cma_page (&folio->page)) +isolate_folio_to_list (folio, folio_list); + goto out; + } + + start_pte =pte_offset_map_lock (vma->vm_mm, pmd, addr, &ptl); +if (!start_pte) { + walk->action =ACTION_AGAIN ; +return 0 ; + } + +for (pte = start_pte; addr != end; pte += step, addr += step *PAGE_SIZE ) { + step =1 ; + ptent =ptep_get (pte); +if (!pte_present (ptent)) { +if (unlikely (softleaf_is_migration (softleaf_from_pte (ptent)))) { +pte_unmap_unlock (start_pte, ptl); +migration_entry_wait (vma->vm_mm, pmd, addr); + walk->action =ACTION_AGAIN ; +return 0 ; + } +continue ; + } + folio =vm_normal_folio (vma, addr, ptent); +if (!folio ||folio_is_zone_device (folio)) +continue ; + step =folio_mlock_step (folio, pte, addr, end); +if (is_migrate_cma_page (&folio->page)) +continue ; +isolate_folio_to_list (folio, folio_list); + } +pte_unmap (start_pte); +out: +spin_unlock (ptl); +cond_resched (); +return 0 ; +} + +static const struct mm_walk_ops mlock_collect_migratable_ops = { + .pmd_entry = mlock_collect_migratable_pte_range, + .walk_lock =PGWALK_RDLOCK , +}; + +static void mlock_migrate_cma_range (unsigned long start,unsigned long len) +{ +struct mm_struct *mm = current->mm; +unsigned long end = start + len; +LIST_HEAD (folio_list); +struct migration_target_control mtc = { + .nid =NUMA_NO_NODE , + .gfp_mask =GFP_HIGHUSER | __GFP_NOWARN, + .reason =MR_SYSCALL , + }; + +if (compaction_allow_unevictable ()) +return ; + +lru_cache_disable (); + +if (mmap_read_lock_killable (mm)) + goto out; + +walk_page_range (mm, start, end, &mlock_collect_migratable_ops, + &folio_list); +mmap_read_unlock (mm); + +if (list_empty (&folio_list)) + goto out; + +if (migrate_pages (&folio_list, alloc_migration_target,NULL , + (unsigned long )&mtc,MIGRATE_SYNC ,MR_SYSCALL ,NULL )) +putback_movable_pages (&folio_list); +out: +lru_cache_enable (); +} +#else +static inline void mlock_migrate_cma_range (unsigned long start, +unsigned long len) +{ +} +#endif /* CONFIG_CMA */ +/* * mlock_vma_pages_range() - mlock any pages already in the range, * or munlock all pages in the range.
@@ -678,6 +792,7 @@ static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t fla error =__mm_populate (start, len,0 );if (error)return __mlock_posix_error_return (error); +mlock_migrate_cma_range (start, len);return 0 ; }
@@ -790,8 +905,10 @@ SYSCALL_DEFINE1(mlockall, int, flags) capable(CAP_IPC_LOCK)) ret =apply_mlockall_flags (flags);mmap_write_unlock (current->mm); -if (!ret && (flags &MCL_CURRENT )) +if (!ret && (flags &MCL_CURRENT )) {mm_populate (0 ,TASK_SIZE ); +mlock_migrate_cma_range (0 ,TASK_SIZE ); + }return ret; }
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider: - [High] The `is_migrate_cma_page` condition is inverted in the PTE loop, isolating non-CMA pages instead…
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider:
- [High] The is_migrate_cma_page condition is inverted in the PTE loop, isolating non-CMA pages instead of CMA pages.
- [High] Setting ACTION_AGAIN on pte_offset_map_lock() failure creates an infinite loop.
- [High] Folios are isolated and added to a list without elevating their refcount, causing Use-After-Free.
- [High] Recursive mmap_read_lock acquisition creates an ABBA self-deadlock risk.
- [High] Locking order inversion between pte_unmap and spin_unlock causes a Use-After-Free of the spinlock.
- [Medium] Unbounded folio isolation aggregates too many pages off the LRU, leading to resource exhaustion. --
--- Patch [4]: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range --- commit 95a15b2b2b9bbf36b5f4e3a9dd716ec837e02900
Author: Wandun Chen <[email protected]>
mm/mlock: migrate folios out of CMA when mlocking a range
This commit attempts to reduce latency spikes on RT kernels by migrating CMA pages out of mlocked regions during the mlock setup path. It introduces a page walker to collect migratable CMA pages and migrates them using migrate_pages().
Quoted 4 lines
mm/mlock.c +0
-0
[ ... ]
Quoted 3 lines
mm/mlock.c +3
-0+static int mlock_collect_migratable_pte_range (pmd_t *pmd,unsigned long addr, +unsigned long end,struct mm_walk *walk) +{
[ ... ]
Quoted 2 lines
mm/mlock.c +2
-0+ ptl =pmd_trans_huge_lock (pmd, vma); +if (ptl) {
[ ... ]
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 464
Quoted 5 lines
mm/mlock.c +5
-0+ folio =pmd_folio (*pmd); +if (folio_is_zone_device (folio)) + goto out; +if (is_migrate_cma_page (&folio->page)) +isolate_folio_to_list (folio, folio_list);
[Severity: High]
Does this code risk a Use-After-Free on the folio? In the PMD path of mlock_collect_migratable_pte_range(), isolate_folio_to_list() is called without first obtaining a reference via folio_get(). Once the page table lock is dropped at the end of the function, a concurrent thread could unmap the region, dropping the mapcount and freeing the folio while it is still on folio_list. When migrate_pages() iterates over the list later, it might access freed memory.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 472
Quoted 8 lines
mm/mlock.c +8
-0+ goto out; + } + + start_pte =pte_offset_map_lock (vma->vm_mm, pmd, addr, &ptl); +if (!start_pte) { + walk->action =ACTION_AGAIN ; +return 0 ; + }
[Severity: High]
Could this create an infinite loop? When pte_offset_map_lock() returns NULL, which happens non-transiently for migration entries or empty PMDs, setting ACTION_AGAIN unconditionally tells the page walker to retry the exact same PMD forever. This could hang the kernel thread if mlock() races with another operation that installs migration entries or zaps the PMD.
Quoted 2 lines
mm/mlock.c +2
-0+ +for (pte = start_pte; addr != end; pte += step, addr += step *PAGE_SIZE ) {
[ ... ]
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 492
Quoted 7 lines
mm/mlock.c +7
-0+ folio =vm_normal_folio (vma, addr, ptent); +if (!folio ||folio_is_zone_device (folio)) +continue ; + step =folio_mlock_step (folio, pte, addr, end); +if (is_migrate_cma_page (&folio->page)) +continue ; +isolate_folio_to_list (folio, folio_list);
[Severity: High]
Is the logic inverted here? The condition causes CMA pages to be skipped while erroneously isolating non-CMA pages for migration. Any mlock() call touching regular memory might isolate and migrate those pages unnecessarily, while skipping the CMA pages this patch was intended to target.
[Severity: High]
Can this lead to a Use-After-Free? Just like in the PMD path, the folio here is isolated without a preceding folio_get() to ensure it survives outside the page table lock.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 496
Quoted 4 lines
mm/mlock.c +4
-0+ } +pte_unmap (start_pte); +out: +spin_unlock (ptl);
[Severity: High]
Is there a lock ordering inversion here? Calling pte_unmap() drops the RCU read lock, which means the page table page could immediately be freed by concurrent teardown like tlb_remove_table_rcu(). The subsequent spin_unlock(ptl) might then access the spinlock residing within the freed page table page on architectures with split PMD/PTE locks.
Quoted 11 lines
mm/mlock.c +11
-0+cond_resched (); +return 0 ; +} + +static const struct mm_walk_ops mlock_collect_migratable_ops = { + .pmd_entry = mlock_collect_migratable_pte_range, + .walk_lock =PGWALK_RDLOCK , +}; + +static void mlock_migrate_cma_range (unsigned long start,unsigned long len) +{
[ ... ]
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 526
Quoted 5 lines
mm/mlock.c +5
-0+if (mmap_read_lock_killable (mm)) + goto out; + +walk_page_range (mm, start, end, &mlock_collect_migratable_ops, + &folio_list);
[Severity: High]
Does this introduce a recursive mmap_read_lock acquisition that could result in a deadlock? mlock_migrate_cma_range() explicitly acquires the mmap_read_lock. It then calls walk_page_range() using the mlock_collect_migratable_ops, which specifies PGWALK_RDLOCK. The walker will internally attempt to acquire the mmap_read_lock again. If a concurrent writer attempts to acquire mmap_write_lock between these two read-lock acquisitions, it will block waiting for the first read lock to be released, and the second read lock will block waiting for the writer, creating an ABBA self-deadlock.
[Severity: Medium]
Is it safe to accumulate an unbounded number of folios into a single list during this page walk? For example, mlockall() invokes this for the entire TASK_SIZE range. Millions of folios could be isolated into folio_list, removing them from the LRU and hiding them from memory reclaim, potentially leading to soft lockups or OOM situations.
Quoted 4 lines
mm/mlock.c +4
-0+mmap_read_unlock (mm); + +if (list_empty (&folio_list)) + goto out;
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Re: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range
In reply to Wandun ChenQuoted 83 lines · Wandun Chen
From: Wandun Chen <[email protected]>
The region covered by mlock[all] may contain CMA pages.
cma_allocinstalls migration entries in the page table, if a memory access occurs at this point, it must wait for the migration to complete, which may cause latency spikes on the RT kernels.Try to move the migration cost into the mlock[all] caller, which is typically a setup path. So reduce the chance of latency spikes on RT kernels by migrating the currently mapped CMA pages out of CMA region.
Suggested-by Frank van der Linden <[email protected]>Signed-off-by Wandun Chen <[email protected]>--- mm/mlock.c | 119 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 118 insertions(+), 1 deletion(-)mm/mlock.c +50
-0@@ -25,6 +25,7 @@#include <linux/memcontrol.h> #include <linux/mm_inline.h> #include <linux/secretmem.h> +#include <linux/migrate.h> #include <linux/compaction.h> #include "internal.h" @@ -428,6 +429,119 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr,return 0 ; } +#ifdef CONFIG_CMA +static int mlock_collect_migratable_pte_range (pmd_t *pmd,unsigned long addr, +unsigned long end,struct mm_walk *walk) +{ +struct vm_area_struct *vma = walk->vma; +struct list_head *folio_list = walk->private; +spinlock_t *ptl; +pte_t *start_pte, *pte; +pte_t ptent; +struct folio *folio; +unsigned int step =1 ; + +if (!(vma->vm_flags &VM_LOCKED )) +return 0 ; + + ptl =pmd_trans_huge_lock (pmd, vma); +if (ptl) { +if (!pmd_present (*pmd)) { +if (unlikely (softleaf_is_migration (softleaf_from_pmd (*pmd)))) { +spin_unlock (ptl); +pmd_migration_entry_wait (vma->vm_mm, pmd); + walk->action =ACTION_AGAIN ; +return 0 ; + } + goto out; + } +if (is_huge_zero_pmd (*pmd)) + goto out; + folio =pmd_folio (*pmd); +if (folio_is_zone_device (folio)) + goto out; +if (is_migrate_cma_page (&folio->page)) +isolate_folio_to_list (folio, folio_list); + goto out; + } + + start_pte =pte_offset_map_lock (vma->vm_mm, pmd, addr, &ptl); +if (!start_pte) { + walk->action =ACTION_AGAIN ; +return 0 ; + } + +for (pte = start_pte; addr != end; pte += step, addr += step *PAGE_SIZE ) { + step =1 ; + ptent =ptep_get (pte); +if (!pte_present (ptent)) { +if (unlikely (softleaf_is_migration (softleaf_from_pte (ptent)))) { +pte_unmap_unlock (start_pte, ptl); +migration_entry_wait (vma->vm_mm, pmd, addr);
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 490
Quoted 10 lines
mm/mlock.c +10
-0+ walk->action =ACTION_AGAIN ; +return 0 ; + } +continue ; + } + folio =vm_normal_folio (vma, addr, ptent); +if (!folio ||folio_is_zone_device (folio)) +continue ; + step =folio_mlock_step (folio, pte, addr, end); +if (is_migrate_cma_page (&folio->page))
Here should be, sorry about this.
if (!is_migrate_cma_page(&folio->page)) continue;
Best regards
Wandun
Quoted 77 lines
mm/mlock.c +58
-1+continue ; + isolate_folio_to_list(folio, folio_list); + } +pte_unmap (start_pte); +out: +spin_unlock (ptl); +cond_resched (); +return 0 ; +} + +static const struct mm_walk_ops mlock_collect_migratable_ops = { + .pmd_entry = mlock_collect_migratable_pte_range, + .walk_lock =PGWALK_RDLOCK , +}; + +static void mlock_migrate_cma_range (unsigned long start,unsigned long len) +{ +struct mm_struct *mm = current->mm; +unsigned long end = start + len; +LIST_HEAD (folio_list); +struct migration_target_control mtc = { + .nid =NUMA_NO_NODE , + .gfp_mask =GFP_HIGHUSER | __GFP_NOWARN, + .reason =MR_SYSCALL , + }; + +if (compaction_allow_unevictable ()) +return ; + +lru_cache_disable (); + +if (mmap_read_lock_killable (mm)) + goto out; + +walk_page_range (mm, start, end, &mlock_collect_migratable_ops, + &folio_list); +mmap_read_unlock (mm); + +if (list_empty (&folio_list)) + goto out; + +if (migrate_pages (&folio_list, alloc_migration_target,NULL , + (unsigned long )&mtc,MIGRATE_SYNC ,MR_SYSCALL ,NULL )) +putback_movable_pages (&folio_list); +out: +lru_cache_enable (); +} +#else +static inline void mlock_migrate_cma_range (unsigned long start, +unsigned long len) +{ +} +#endif /* CONFIG_CMA */ +/* * mlock_vma_pages_range() - mlock any pages already in the range, * or munlock all pages in the range. @@ -678,6 +792,7 @@ static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t fla error =__mm_populate (start, len,0 );if (error)return __mlock_posix_error_return (error); +mlock_migrate_cma_range (start, len);return 0 ; }@@ -790,8 +905,10 @@ SYSCALL_DEFINE1(mlockall, int, flags) capable(CAP_IPC_LOCK)) ret =apply_mlockall_flags (flags);mmap_write_unlock (current->mm); -if (!ret && (flags &MCL_CURRENT )) +if (!ret && (flags &MCL_CURRENT )) {mm_populate (0 ,TASK_SIZE ); +mlock_migrate_cma_range (0 ,TASK_SIZE ); + }return ret; }
Lorenzo Stoakes
maintainerRe: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range
On Tue, Jul 07, 2026 at 09:36:17PM +0800, Wandun wrote:
<snip>
Quoted 4 lines
Quoted 4 lines
mm/mlock.c +0
-0
<snip>
Quoted 59 lines
Quoted 48 lines
mm/mlock.c +48
-0+static int mlock_collect_migratable_pte_range (pmd_t *pmd,unsigned long addr, +unsigned long end,struct mm_walk *walk) +{ +struct vm_area_struct *vma = walk->vma; +struct list_head *folio_list = walk->private; +spinlock_t *ptl; +pte_t *start_pte, *pte; +pte_t ptent; +struct folio *folio; +unsigned int step =1 ; + +if (!(vma->vm_flags &VM_LOCKED )) +return 0 ; + + ptl =pmd_trans_huge_lock (pmd, vma); +if (ptl) { +if (!pmd_present (*pmd)) { +if (unlikely (softleaf_is_migration (softleaf_from_pmd (*pmd)))) { +spin_unlock (ptl); +pmd_migration_entry_wait (vma->vm_mm, pmd); + walk->action =ACTION_AGAIN ; +return 0 ; + } + goto out; + } +if (is_huge_zero_pmd (*pmd)) + goto out; + folio =pmd_folio (*pmd); +if (folio_is_zone_device (folio)) + goto out; +if (is_migrate_cma_page (&folio->page)) +isolate_folio_to_list (folio, folio_list); + goto out; + } + + start_pte =pte_offset_map_lock (vma->vm_mm, pmd, addr, &ptl); +if (!start_pte) { + walk->action =ACTION_AGAIN ; +return 0 ; + } + +for (pte = start_pte; addr != end; pte += step, addr += step *PAGE_SIZE ) { + step =1 ; + ptent =ptep_get (pte); +if (!pte_present (ptent)) { +if (unlikely (softleaf_is_migration (softleaf_from_pte (ptent)))) { +pte_unmap_unlock (start_pte, ptl); +migration_entry_wait (vma->vm_mm, pmd, addr);mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 490
Quoted 10 lines
mm/mlock.c +10
-0+ walk->action =ACTION_AGAIN ; +return 0 ; + } +continue ; + } + folio =vm_normal_folio (vma, addr, ptent); +if (!folio ||folio_is_zone_device (folio)) +continue ; + step =folio_mlock_step (folio, pte, addr, end); +if (is_migrate_cma_page (&folio->page))Here should be, sorry about this.
Quoted 2 lines
if (!is_migrate_cma_page(&folio->page)) continue;
But above you do the:
if (is_migrate_cma_page(&folio->page)) isolate_folio_to_list(folio, folio_list);
Pattern :) so these should be consistent. But you're copy/pasting and need to not do that so it's kind of by the by.
Anyway, yes I assumed you meant this. But see the main review, I am not really a fan of the implementation, overall.
Quoted 3 lines
Best regards
Wandun
Thanks, Lorenzo
Lorenzo Stoakes
maintainerRe: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range
In reply to Wandun ChenQuoted 10 lines · Wandun Chen
From: Wandun Chen <[email protected]>
The region covered by mlock[all] may contain CMA pages.
cma_allocinstalls migration entries in the page table, if a memory access occurs at this point, it must wait for the migration to complete, which may cause latency spikes on the RT kernels.Try to move the migration cost into the mlock[all] caller, which is typically a setup path. So reduce the chance of latency spikes on RT kernels by migrating the currently mapped CMA pages out of CMA region.
'reduce the chances of latency' so do you have any data to back this invasive change or not?
And for RT, but nothing in here at all checks for RT? You're using this compaction sysctl as an RT check somehow? That's gross.
This doesn't feel like the right solution.
Quoted 21 lines
Suggested-by Frank van der Linden <[email protected]>Signed-off-by Wandun Chen <[email protected]>--- mm/mlock.c | 119 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 118 insertions(+), 1 deletion(-)mm/mlock.c +1
-0@@ -25,6 +25,7 @@#include <linux/memcontrol.h> #include <linux/mm_inline.h> #include <linux/secretmem.h> +#include <linux/migrate.h> #include <linux/compaction.h> #include "internal.h"
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 432
Quoted 4 lines
mm/mlock.c +1
-0@@ -428,6 +429,119 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr,return 0 ; } +#ifdef CONFIG_CMA
Ugh yuck. This is horrible. Why are we polluting mlock.c with CMA stuff?
Also no comment?
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 435
Quoted 3 lines
mm/mlock.c +3
-0+static int mlock_collect_migratable_pte_range (pmd_t *pmd,unsigned long addr, +unsigned long end,struct mm_walk *walk) +{
You've literally copy/pasted mlock_pte_range(), this is disgusting.
Please don't copy/paste code like this, this isn't PHP, it's the kernel, it's completely unacceptable.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 444
Quoted 9 lines
mm/mlock.c +9
-0+struct vm_area_struct *vma = walk->vma; +struct list_head *folio_list = walk->private; +spinlock_t *ptl; +pte_t *start_pte, *pte; +pte_t ptent; +struct folio *folio; +unsigned int step =1 ; + +if (!(vma->vm_flags &VM_LOCKED ))
Once again vma_test(vma, VMA_LOCKED_BIT) please.
But also, again (since you copy/pasted), why? You're literally mlocking here...
You going for that 'mlocking already mlocked ranges' sweet spot or am I missing something?
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 450
Quoted 6 lines
mm/mlock.c +6
-0+return 0 ; + + ptl =pmd_trans_huge_lock (pmd, vma); +if (ptl) { +if (!pmd_present (*pmd)) { +if (unlikely (softleaf_is_migration (softleaf_from_pmd (*pmd)))) {
OK so you're not actually checking for CMA here at all, you're just doing the migration wait stuff... again here? What?
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 463
Quoted 13 lines
mm/mlock.c +13
-0+spin_unlock (ptl); +pmd_migration_entry_wait (vma->vm_mm, pmd); + walk->action =ACTION_AGAIN ; +return 0 ; + } + goto out; + } +if (is_huge_zero_pmd (*pmd)) + goto out; + folio =pmd_folio (*pmd); +if (folio_is_zone_device (folio)) + goto out; +if (is_migrate_cma_page (&folio->page))
Err isn't this per-page, and you just checked that this is a huge folio, and you're only checking the first page? That seems wrong?
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 464
Quoted 1 line
mm/mlock.c +1
-0+isolate_folio_to_list (folio, folio_list);
Then you just take the whole folio?
It's really horrible that you're burying this in copy/pasted code from the rest.
Quoted 6 lines
mm/mlock.c +6
-0+ goto out; + } + + start_pte =pte_offset_map_lock (vma->vm_mm, pmd, addr, &ptl); +if (!start_pte) { + walk->action =ACTION_AGAIN ;
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 480
Quoted 10 lines
mm/mlock.c +10
-0+return 0 ; + } + +for (pte = start_pte; addr != end; pte += step, addr += step *PAGE_SIZE ) { + step =1 ; + ptent =ptep_get (pte); +if (!pte_present (ptent)) { +if (unlikely (softleaf_is_migration (softleaf_from_pte (ptent)))) { +pte_unmap_unlock (start_pte, ptl); +migration_entry_wait (vma->vm_mm, pmd, addr);
BTW I also wonder if we have guaranteed forward progress here if say a migration happened to migrate back and forth again across a range...?
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 455
Quoted 3 lines
mm/mlock.c +3
-0+ walk->action =ACTION_AGAIN ; +return 0 ; + }
Again, since you copy/pasted, same comment - this is disgusting.
And again I'm confused why you're waiting here again after you did it previously due to the previous commit that already does it?
And why for a non-CMA range, if somebody happens to set CONFIG_CMA they now get this done twice?
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 491
Quoted 8 lines
mm/mlock.c +8
-0+continue ; + } + folio =vm_normal_folio (vma, addr, ptent); +if (!folio ||folio_is_zone_device (folio)) +continue ; + step =folio_mlock_step (folio, pte, addr, end); +if (is_migrate_cma_page (&folio->page)) +continue ;
You mean ! surely?
Why are you inverting this vs. the above? you replied to the patch so maybe you correct this there.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 492
Quoted 1 line
mm/mlock.c +1
-0+isolate_folio_to_list (folio, folio_list);
And again you bury the actual point of this in one easily missed line and zero comments.
No.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 499
Quoted 7 lines
mm/mlock.c +7
-0+ } +pte_unmap (start_pte); +out: +spin_unlock (ptl); +cond_resched (); +return 0 ; +}
Yeah this is just completely unacceptable. You have to find a way to deduplicate code. Copy/paste code dumps are not ok.
But at the same time, you're dumping CMA crap in core mm mlock code which is horrible, you've also dumped some migration code so you're really mixing things up here horribly, and it doesn't seem justified?
Quoted 9 lines
mm/mlock.c +9
-0+ +static const struct mm_walk_ops mlock_collect_migratable_ops = { + .pmd_entry = mlock_collect_migratable_pte_range, + .walk_lock =PGWALK_RDLOCK , +}; + +static void mlock_migrate_cma_range (unsigned long start,unsigned long len) +{ +struct mm_struct *mm = current->mm;
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 518
Quoted 10 lines
mm/mlock.c +10
-0+unsigned long end = start + len; +LIST_HEAD (folio_list); +struct migration_target_control mtc = { + .nid =NUMA_NO_NODE , + .gfp_mask =GFP_HIGHUSER | __GFP_NOWARN, + .reason =MR_SYSCALL , + }; + +if (compaction_allow_unevictable ()) +return ;
Again you're assuming compaction for some reason. Why?
It feels like you're just gating specific behaviour for your workload on this flag and assuming that's ok.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 520
Quoted 2 lines
mm/mlock.c +2
-0+ +lru_cache_disable ();
What, why?
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 523
Quoted 3 lines
mm/mlock.c +3
-0+ +if (mmap_read_lock_killable (mm)) + goto out;
OK so you got a fatal signal and you don't bother telling anybody about it and just skip migration?...
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 524
Quoted 1 line
mm/mlock.c +1
-0+
Weird whitespace...
Quoted 5 lines
mm/mlock.c +5
-0+walk_page_range (mm, start, end, &mlock_collect_migratable_ops, + &folio_list); +mmap_read_unlock (mm); + +if (list_empty (&folio_list))
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 539
Quoted 10 lines
mm/mlock.c +10
-0+ goto out; + +if (migrate_pages (&folio_list, alloc_migration_target,NULL , + (unsigned long )&mtc,MIGRATE_SYNC ,MR_SYSCALL ,NULL )) +putback_movable_pages (&folio_list); +out: +lru_cache_enable (); +} +#else +static inline void mlock_migrate_cma_range(unsigned long start,
inline in a .c file? Why? Drop it.
mm/mlock.c static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t fla · line 795
Quoted 13 lines
mm/mlock.c +6
-0+ unsigned long len) +{ +} +#endif /* CONFIG_CMA */ +/* * mlock_vma_pages_range() - mlock any pages already in the range, * or munlock all pages in the range. @@ -678,6 +792,7 @@ static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t fla error =__mm_populate (start, len,0 );if (error)return __mlock_posix_error_return (error); +mlock_migrate_cma_range (start, len);
Err, unconditionally?
mm/mlock.c SYSCALL_DEFINE1(mlockall, int, flags) · line 910
Quoted 11 lines
mm/mlock.c +2
-1return 0 ; }@@ -790,8 +905,10 @@ SYSCALL_DEFINE1(mlockall, int, flags) capable(CAP_IPC_LOCK)) ret =apply_mlockall_flags (flags);mmap_write_unlock (current->mm); -if (!ret && (flags &MCL_CURRENT )) +if (!ret && (flags &MCL_CURRENT )) {mm_populate (0 ,TASK_SIZE ); +mlock_migrate_cma_range (0 ,TASK_SIZE );
Err what? Why are you doing this? You're forcing a wait on migration of literally everything across the whole of the process whether or not they're CMA ranges, but as a one time thing?
Quoted 7 lines
mm/mlock.c +1
-1+ }return ret; } --2.43.0
In general this feels like the wrong solution for a specific workload that sticks horrible stuff in core mm and I don't really love it :)
Thanks, Lorenzo
Sebastian Andrzej Siewior
maintainerRe: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range
Quoted 8 lines · Lorenzo Stoakes
Quoted 7 lines · Wandun Chen
From: Wandun Chen <[email protected]>
The region covered by mlock[all] may contain CMA pages.
cma_allocinstalls migration entries in the page table, if a memory access occurs at this point, it must wait for the migration to complete, which may cause latency spikes on the RT kernels.
Quoted 6 lines
Quoted 3 lines
Try to move the migration cost into the mlock[all] caller, which is typically a setup path. So reduce the chance of latency spikes on RT kernels by migrating the currently mapped CMA pages out of CMA region.
'reduce the chances of latency' so do you have any data to back this invasive change or not?
The application gets pages assigned which belong a CMA area. If the pages are in need by the CMA then those pages are replaced with other pages during a migration phase. Since there is no guarantee how long this will take and is also subject to general scheduling in the system it will be measurable and painful once hit.
Quoted 2 lines
And for RT, but nothing in here at all checks for RT? You're using this compaction sysctl as an RT check somehow? That's gross.
The man-page for mlock says that it guarantees to stay in RAM and/ or preventing to be moved to swap area. I would however argue that replacing physical pages in the background should fall under this since the application can't access them and is blocked while trying. The notes section (in the man-page) lists "real-time applications" and "deterministic timing". Therefore I think it makes sense to do this unconditionally for mlock areas regardless of the sysctl knob. Security related application probably only care that their memory does not hit the swap area and probably wouldn't mind 10ms delay.
Quoted 1 line
This doesn't feel like the right solution.
Sebastian
Re: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range
Quoted 25 lines · Sebastian Andrzej Siewior
Quoted 8 lines · Lorenzo Stoakes
Quoted 7 lines · Wandun Chen
From: Wandun Chen <[email protected]>
The region covered by mlock[all] may contain CMA pages.
cma_allocinstalls migration entries in the page table, if a memory access occurs at this point, it must wait for the migration to complete, which may cause latency spikes on the RT kernels.Quoted 6 lines
Quoted 3 lines
Try to move the migration cost into the mlock[all] caller, which is typically a setup path. So reduce the chance of latency spikes on RT kernels by migrating the currently mapped CMA pages out of CMA region.
'reduce the chances of latency' so do you have any data to back this invasive change or not?
The application gets pages assigned which belong a CMA area. If the pages are in need by the CMA then those pages are replaced with other pages during a migration phase. Since there is no guarantee how long this will take and is also subject to general scheduling in the system it will be measurable and painful once hit.
Quoted 2 lines
And for RT, but nothing in here at all checks for RT? You're using this compaction sysctl as an RT check somehow? That's gross.
Quoted 9 lines
The man-page for mlock says that it guarantees to stay in RAM and/ or preventing to be moved to swap area. I would however argue that replacing physical pages in the background should fall under this since the application can't access them and is blocked while trying. The notes section (in the man-page) lists "real-time applications" and "deterministic timing". Therefore I think it makes sense to do this unconditionally for mlock areas regardless of the sysctl knob. Security related application probably only care that their memory does not hit the swap area and probably wouldn't mind 10ms delay.
Thanks for helping to explain, that helps a lot, Sebastian. Wandun
Quoted 4 lines
Quoted 2 lines
This doesn't feel like the right solution.
Sebastian
Re: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range
In reply to Lorenzo StoakesQuoted 12 lines · Lorenzo Stoakes
Quoted 10 lines · Wandun Chen
From: Wandun Chen <[email protected]>
The region covered by mlock[all] may contain CMA pages.
cma_allocinstalls migration entries in the page table, if a memory access occurs at this point, it must wait for the migration to complete, which may cause latency spikes on the RT kernels.Try to move the migration cost into the mlock[all] caller, which is typically a setup path. So reduce the chance of latency spikes on RT kernels by migrating the currently mapped CMA pages out of CMA region.
Quoted 5 lines
'reduce the chances of latency' so do you have any data to back this invasive change or not?
And for RT, but nothing in here at all checks for RT? You're using this compaction sysctl as an RT check somehow? That's gross.
sysctl_compact_unevictable_allowed is set to zero by default in RT kernels. Also, sysctl_compact_unevictable_allowed can also be set to 1 in the RT kernel, though this will produce a warning.
When sysctl_compact_unevictable_allowed is set to 1, my understanding is that the mlock region should not contain CMA pages; otherwise, migration entries will appear during CMA migration, and have to wait for the migration to complete.
Quoted 22 lines
This doesn't feel like the right solution.
Quoted 19 lines
Suggested-by Frank van der Linden <[email protected]>Signed-off-by Wandun Chen <[email protected]>--- mm/mlock.c | 119 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 118 insertions(+), 1 deletion(-)mm/mlock.c +1
-0@@ -25,6 +25,7 @@#include <linux/memcontrol.h> #include <linux/mm_inline.h> #include <linux/secretmem.h> +#include <linux/migrate.h> #include <linux/compaction.h>
Quoted 8 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 432
Quoted 6 lines
mm/mlock.c +1
-0#include "internal.h" @@ -428,6 +429,119 @@ static int mlock_pte_range(pmd_t *pmd, unsigned long addr,return 0 ; } +#ifdef CONFIG_CMA Ugh yuck. This is horrible. Why are we polluting
mlock.cwith CMA stuff?
Will move to the relevant CMA file, if the CMA migration approach is acceptable.
Quoted 24 lines
Also no comment?
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 435
Quoted 3 lines
mm/mlock.c +3
-0+static int mlock_collect_migratable_pte_range (pmd_t *pmd,unsigned long addr, +unsigned long end,struct mm_walk *walk) +{You've literally copy/pasted
mlock_pte_range(), this is disgusting.Please don't copy/paste code like this, this isn't PHP, it's the kernel, it's completely unacceptable.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 444
Quoted 9 lines
mm/mlock.c +9
-0+struct vm_area_struct *vma = walk->vma; +struct list_head *folio_list = walk->private; +spinlock_t *ptl; +pte_t *start_pte, *pte; +pte_t ptent; +struct folio *folio; +unsigned int step =1 ; + +if (!(vma->vm_flags &VM_LOCKED ))Once again
vma_test(vma, VMA_LOCKED_BIT)please.
Quoted 4 lines
But also, again (since you copy/pasted), why? You're literally mlocking here...
You going for that 'mlocking already mlocked ranges' sweet spot or am I missing something?
Will remove this check in next version.
Quoted 10 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 450
Quoted 7 lines
mm/mlock.c +6
-0+return 0 ; + + ptl =pmd_trans_huge_lock (pmd, vma); +if (ptl) { +if (!pmd_present (*pmd)) { +if (unlikely (softleaf_is_migration (softleaf_from_pmd (*pmd)))) {OK so you're not actually checking for CMA here at all, you're just doing the migration wait stuff... again here? What?
This is to prevent CMA pages from being migrated by cma_alloc at this point, with migration entries already installed. If there are multiple CMA regions in the system, after the wait completes the page could still be a CMA page, so wait and recheck again.
Quoted 17 lines
Quoted 4 lines
mm/mlock.c +3
-0+spin_unlock (ptl); +pmd_migration_entry_wait (vma->vm_mm, pmd); + walk->action =ACTION_AGAIN ;mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 463
Quoted 10 lines
mm/mlock.c +10
-0+return 0 ; + } + goto out; + } +if (is_huge_zero_pmd (*pmd)) + goto out; + folio =pmd_folio (*pmd); +if (folio_is_zone_device (folio)) + goto out; +if (is_migrate_cma_page (&folio->page))Err isn't this per-page, and you just checked that this is a huge folio, and you're only checking the first page? That seems wrong?
Not wrong. IIUC there are two cases:
If folio_order(folio) < pageblock_order, the folio fits entirely within a single pageblock, so the first page is sufficient.
If folio_order(folio) >= pageblock_order, __free_one_page() prevents any buddy merge across a CMA/non-CMA boundary.
Quoted 18 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 464
Quoted 2 lines
mm/mlock.c +1
-0+isolate_folio_to_list (folio, folio_list);Then you just take the whole folio?
It's really horrible that you're burying this in copy/pasted code from the rest.
Quoted 11 lines
mm/mlock.c +11
-0+ goto out; + } + + start_pte =pte_offset_map_lock (vma->vm_mm, pmd, addr, &ptl); +if (!start_pte) { + walk->action =ACTION_AGAIN ; +return 0 ; + } + +for (pte = start_pte; addr != end; pte += step, addr += step *PAGE_SIZE ) { + step =1 ;
Quoted 8 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 480
Quoted 5 lines
mm/mlock.c +5
-0+ ptent =ptep_get (pte); +if (!pte_present (ptent)) { +if (unlikely (softleaf_is_migration (softleaf_from_pte (ptent)))) { +pte_unmap_unlock (start_pte, ptl); +migration_entry_wait (vma->vm_mm, pmd, addr);BTW I also wonder if we have guaranteed forward progress here if say a migration happened to migrate back and forth again across a range...?
In theory, it is possible to keep waiting here repeatedly:
if there are multiple CMA regions, a cma_alloc() from CMA region A installs a migration entry; once that migration completes, the page lands in CMA region B; then a cma_alloc() from CMA region B installs another migration entry, and so on, this function keep seeing a migration entry indefinitely. I suspect this is an extremely rare scenario in practice, but I will add a retry limit in a follow-up to guard against it.
Pages migrated out by mlock_migrate_cma_range() itself will not land in CMA (allocated via alloc_migration_target with GFP_HIGHUSER which avoids CMA), so this function always make forward progress.
Quoted 7 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 455
Quoted 4 lines
mm/mlock.c +3
-0+ walk->action =ACTION_AGAIN ; +return 0 ; + }Again, since you copy/pasted, same comment - this is disgusting.
Quoted 5 lines
And again I'm confused why you're waiting here again after you did it previously due to the previous commit that already does it?
And why for a non-CMA range, if somebody happens to set
CONFIG_CMAthey now get this done twice?
The previous commit prevents page migration triggered by kcompactd, but cannot prevent page migration triggered by cma_alloc().
compact_unevictable_allowed only prevents kcompactd-driven migration. For an RT application, migration triggered by kcompactd is outside the application's own behavior and can impact real-time latency. However, cma_alloc() does not check compact_unevictable_allowed, so CMA-driven migration will still migrate pages in the mlocked range, even if the RT application has already called mlock().
The idea of this patch is to migrate CMA pages out of the locked range at mlock() time. After that, even if cma_alloc() is called later, it will no longer affect the mlocked range.
Perhaps I should describe this more thoroughly in the commit message, will add this info in next version.
Quoted 12 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 491
Quoted 9 lines
mm/mlock.c +8
-0+continue ; + } + folio =vm_normal_folio (vma, addr, ptent); +if (!folio ||folio_is_zone_device (folio)) +continue ; + step =folio_mlock_step (folio, pte, addr, end); +if (is_migrate_cma_page (&folio->page)) +continue ;You mean ! surely?
Quoted 7 lines
Why are you inverting this vs. the above? you replied to the patch so maybe you correct this there.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 492
Quoted 1 line
mm/mlock.c +1
-0+isolate_folio_to_list (folio, folio_list);And again you bury the actual point of this in one easily missed line and zero comments.
I will add some comments in the next version.
Quoted 13 lines
No.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 499
Quoted 7 lines
mm/mlock.c +7
-0+ } +pte_unmap (start_pte); +out: +spin_unlock (ptl); +cond_resched (); +return 0 ; +}Yeah this is just completely unacceptable. You have to find a way to deduplicate code. Copy/paste code dumps are not ok.
Will refactor it in the next version to share the logic with mlock_pte_range().
Quoted 5 lines
But at the same time, you're dumping CMA crap in core mm mlock code which is horrible, you've also dumped some migration code so you're really mixing things up here horribly, and it doesn't seem justified?
As mentioned earlier, the migration entry handling here is intentional, we need to wait for any in-flight migration to complete before checking whether the page is CMA, otherwise we might miss CMA pages that are temporarily hidden behind a migration entry.
Quoted 13 lines
Quoted 13 lines
mm/mlock.c +13
-0+ +static const struct mm_walk_ops mlock_collect_migratable_ops = { + .pmd_entry = mlock_collect_migratable_pte_range, + .walk_lock =PGWALK_RDLOCK , +}; + +static void mlock_migrate_cma_range (unsigned long start,unsigned long len) +{ +struct mm_struct *mm = current->mm; +unsigned long end = start + len; +LIST_HEAD (folio_list); +struct migration_target_control mtc = { + .nid =NUMA_NO_NODE ,
Quoted 8 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 518
Quoted 6 lines
mm/mlock.c +6
-0+ .gfp_mask = GFP_HIGHUSER | __GFP_NOWARN, + .reason = MR_SYSCALL, + }; + +if (compaction_allow_unevictable ()) +return ;Again you're assuming compaction for some reason. Why?
If compact_unevictable_allowed is true, it means the system allows kcompactd to migrate pages in mlocked ranges, implying that the latency impact of such migration is acceptable. In that case, there is no need to proactively migrate CMA pages out of the mlocked range either.
Quoted 8 lines
It feels like you're just gating specific behaviour for your workload on this flag and assuming that's ok.
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 520
Quoted 2 lines
mm/mlock.c +2
-0+ +lru_cache_disable ();What, why?
IIUC if folios have not been drained to the LRU, the isolation will fail.
Quoted 7 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 523
Quoted 4 lines
mm/mlock.c +3
-0+ +if (mmap_read_lock_killable (mm)) + goto out;OK so you got a fatal signal and you don't bother telling anybody about it and just skip migration?...
Oh, here should return -EINTR, will fix in next version.
Quoted 14 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 524
Quoted 2 lines
mm/mlock.c +1
-0+Weird whitespace...
Quoted 9 lines
mm/mlock.c +9
-0+walk_page_range (mm, start, end, &mlock_collect_migratable_ops, + &folio_list); +mmap_read_unlock (mm); + +if (list_empty (&folio_list)) + goto out; + +if (migrate_pages (&folio_list, alloc_migration_target,NULL , + (unsigned long )&mtc,MIGRATE_SYNC ,MR_SYSCALL ,NULL ))
Quoted 8 lines
mm/mlock.c static int mlock_pte_range(pmd_t *pmd, unsigned long addr, · line 539
Quoted 6 lines
mm/mlock.c +6
-0+putback_movable_pages (&folio_list); +out: +lru_cache_enable (); +} +#else +static inline void mlock_migrate_cma_range(unsigned long start,inline in a .c file? Why? Drop it.
Got it.
Quoted 16 lines
Quoted 10 lines
mm/mlock.c +5
-0+ unsigned long len) +{ +} +#endif /* CONFIG_CMA */ +/* * mlock_vma_pages_range() - mlock any pages already in the range, * or munlock all pages in the range. mm/mlock.c static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t fla · line 795
Quoted 4 lines
mm/mlock.c +1
-0@@ -678,6 +792,7 @@ static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t fla error =__mm_populate (start, len,0 );if (error)return __mlock_posix_error_return (error); +mlock_migrate_cma_range (start, len);Err, unconditionally?
In mlock_migrate_cma_range(), the decision of whether to actually perform the migration is gated by compact_unevictable_allowed.
Quoted 4 lines
Quoted 4 lines
mm/mlock.c +0
-0return 0 ; }
Quoted 12 lines
mm/mlock.c SYSCALL_DEFINE1(mlockall, int, flags) · line 910
Quoted 8 lines
mm/mlock.c +2
-1@@ -790,8 +905,10 @@ SYSCALL_DEFINE1(mlockall, int, flags) capable(CAP_IPC_LOCK)) ret =apply_mlockall_flags (flags);mmap_write_unlock (current->mm); -if (!ret && (flags &MCL_CURRENT )) +if (!ret && (flags &MCL_CURRENT )) {mm_populate (0 ,TASK_SIZE ); +mlock_migrate_cma_range (0 ,TASK_SIZE );Err what? Why are you doing this? You're forcing a wait on migration of literally everything across the whole of the process whether or not they're CMA ranges, but as a one time thing?
mm_populate(0, TASK_SIZE) operates on the entire process address space, so mlock_migrate_cma_range() needs to scan the same range to find and migrate any CMA pages.
We are aware that this operation can be time-consuming. On RT systems, mlockall() is typically called during the application's initialization phase, so the cost is paid upfront at setup time rather than at runtime. The goal is to ensure that there are no latency spikes during the real-time execution phase.
Quoted 13 lines
Quoted 9 lines
mm/mlock.c +1
-1+ }return ret; } --2.43.0
In general this feels like the wrong solution for a specific workload that sticks horrible stuff in core mm and I don't really love it :)
Quoted 1 line
Thanks, Lorenzo
Thanks,
Wandun
David Hildenbrand (Arm)
maintainerRe: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range
In reply to Wandun ChenQuoted 3 lines · Wandun Chen
From: Wandun Chen <[email protected]>
The region covered by mlock[all] may contain CMA pages.
cma_allocinstalls
What about ZONE_MOVABLE where memory is supposed to be migratable?
Also, what about drivers that mmap() CMA memory to user space, and __mm_populate()->populate_vma_page_range() would actually try mlocking them, and they actually must remain on CMA areas?
Signature · 3 lines
Cheers, David
Sebastian Andrzej Siewior
maintainerRe: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range
Quoted 6 lines · David Hildenbrand (Arm)
Quoted 3 lines · Wandun Chen
From: Wandun Chen <[email protected]>
The region covered by mlock[all] may contain CMA pages.
cma_allocinstallsWhat about
ZONE_MOVABLEwhere memory is supposed to be migratable?
Would it be bad if the pages would not be movable anymore? Does this effect just memory-hotplug or something else, too?
Quoted 3 lines
Also, what about drivers that
mmap()CMA memory to user space, and __mm_populate()->populate_vma_page_range() would actually try mlocking them, and they actually must remain on CMA areas?
It should be safe to skip those. They belong to device and they shouldn't be affected by anything including getting swapped out.
Sebastian
Re: [PATCH v2 4/4] mm/mlock: migrate folios out of CMA when mlocking a range
Hi Sebastian, David,
Sorry for the long delay in getting back to this, and thanks a lot for the review.
Quoted 10 lines · Sebastian Andrzej Siewior
Quoted 6 lines · David Hildenbrand (Arm)
Quoted 3 lines · Wandun Chen
From: Wandun Chen <[email protected]>
The region covered by mlock[all] may contain CMA pages.
cma_allocinstallsWhat about
ZONE_MOVABLEwhere memory is supposed to be migratable?Would it be bad if the pages would not be movable anymore? Does this effect just memory-hotplug or something else, too?
ZONE_MOVABLE does not need the same treatment as CMA.
1. On RT compact_unevictable_allowed is 0 by default, pages in ZONE_MOVABLE are never migrated by compaction, so no latency spike, no problem.
2. For the scenario of memory offlining within ZONE_MOVABLE, because of offline is an explicit administrator action. Any jitter/latency is expected and acceptable, the operator chose to offline memory and would not do so during an RT-critical phase.
3. cma_alloc() runs at runtime, triggered by drivers as part of normal operation, and isolation path hardcodes ISOLATE_UNEVICTABLE, so it migrates the mlocked pages and installs migration entries. The fault-and-wait latency hits the RT task unpredictably during normal operation, which is not expected, and is exactly the spike this patch targets.
Quoted 7 lines
Quoted 4 lines
Also, what about drivers that
mmap()CMA memory to user space, and __mm_populate()->populate_vma_page_range() would actually try mlocking them, and they actually must remain on CMA areas?It should be safe to skip those. They belong to device and they shouldn't be affected by anything including getting swapped out.
Agreed. Only LRU folios are ever isolated for migration here (isolate_folio_to_list() -> folio_isolate_lru()), and device-owned CMA buffers are not on the LRU, so they are left in place. I'll double-check the mmap paths and make sure this holds, and state it explicitly in v3.
Best regards,
Wandun
Quoted 2 lines
Sebastian