assorted oom fixes
Subsystems (6)
Michal Hocko
maintainercover assorted oom fixes
Hi David,
these are assorted oom related fixes. There is nothing super critical in there but the patch1 is using a potential UAF for oom_disabled (v1 only feature) situations so I've marked it for stable explicitly. All these are based on Chris Mason's reports so thanks for those!
Patch9 depends on
https://lore.kernel.org/all/[email protected]/
which should be already sitting in the Andrew's queue.
I would still appreciate second pair of eyes on these patches before merging so please take a look David Rientjes and Ben on those oom related and I would appreciate Johannes input especially on memcg specific and the reclaim specific ones.
Thanks a lot!
Michal Hocko
maintainerPATCH 1/10 memcg-v1, oom: do not sleep in worker contexts
From: Michal Hocko <[email protected]>
SVA device faults at the limit of a v1 memcg with the OOM killer disabled can leak a css reference, or cause a use-after-free of the memcg.
handle_mm_fault() enables the memcg OOM handling for FAULT_FLAG_USER, so a failed charge can leave a css reference in current->memcg_in_oom. On VM_FAULT_OOM the caller has to drop it in pagefault_out_of_memory(). But iommu_sva_handle_mm() sets the flag for faults that it handles in a kworker, and never makes that call. The pointer stays on the kworker, and fork copies it to usermode helpers without a reference:
kworker usermode helper
======= ===============
iommu_sva_handle_mm()
memcg1_oom_prepare()
css_get()
current->memcg_in_oom = memcg
call_usermodehelper_exec_work()
dup_task_struct()
handle_mm_fault()
css_put()
iommu_sva_handle_mm()
handle_mm_fault()
css_put()Fix this by explicitly avoid oom_disabled path for workers. This would simply fail the charge and bail out without triggering the oom killer same as if this happened outside of #PF handler.
--- mm/memcontrol-v1.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
mm/memcontrol-v1.c +2 -1
@@ -1100,7 +1100,8 @@ bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked)* victim and then we have to bail out from the charge path. */ if (READ_ONCE (memcg->oom_kill_disable)) { -if (current->in_user_fault) { +if (current->in_user_fault && + !(current->flags & (PF_WQ_WORKER |PF_IO_WORKER ))) {css_get (&memcg->css); current->memcg_in_oom = memcg; }
Signature · 1 line
2.56.1
Re: [PATCH 01/10] memcg-v1, oom: do not sleep in worker contexts
Quoted 27 lines · Michal Hocko
From: Michal Hocko <[email protected]>
SVA device faults at the limit of a v1 memcg with the OOM killer disabled can leak a css reference, or cause a use-after-free of the memcg.
handle_mm_fault()enables the memcg OOM handling forFAULT_FLAG_USER, so a failed charge can leave a css reference incurrent->memcg_in_oom. OnVM_FAULT_OOMthe caller has to drop it inpagefault_out_of_memory(). Butiommu_sva_handle_mm()sets the flag for faults that it handles in a kworker, and never makes that call. The pointer stays on the kworker, and fork copies it to usermode helpers without a reference:kworker usermode helper ======= =============== iommu_sva_handle_mm() memcg1_oom_prepare() css_get() current->memcg_in_oom = memcg call_usermodehelper_exec_work() dup_task_struct() handle_mm_fault() css_put() iommu_sva_handle_mm() handle_mm_fault() css_put()
Quoted 3 lines
Fix this by explicitly avoid
oom_disabledpath for workers. This would simply fail the charge and bail out without triggering the oom killer same as if this happened outside of #PF handler.
Hi Michal, I hope you are doing well. Thank you for the fix!
This was a fun fix to review because I wasn't entirely familiar with how v1 handles OOMs when the killer is disabled, so I got to learn about this mechanism.
The fix looks good to me, thanks!
And I also reproduced the issue and saw that I would get a KASAN slab-use-after-free before, but no such error with this patch applied. I don't have easy access to real IOMMU or SVA devices, so I wrote a module to exercise the path that you note in the commit. It just mimics iommu_sva_handle_mm().
Quoted 26 lines
Fixes fc36479db74e ("iommu: Add a page fault handler")Cc stableReported-by Chris Mason <[email protected]>Signed-off-by Michal Hocko <[email protected]>--- mm/memcontrol-v1.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)mm/memcontrol-v1.c +2
-1@@ -1100,7 +1100,8 @@ bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked)* victim and then we have to bail out from the charge path. */ if (READ_ONCE (memcg->oom_kill_disable)) { -if (current->in_user_fault) { +if (current->in_user_fault && + !(current->flags & (PF_WQ_WORKER |PF_IO_WORKER ))) {css_get (&memcg->css); current->memcg_in_oom = memcg; }Signature · 1 line
2.56.1
Michal Hocko
maintainerRe: [PATCH 01/10] memcg-v1, oom: do not sleep in worker contexts
Quoted 32 lines · Joshua Hahn
Quoted 27 lines · Michal Hocko
From: Michal Hocko <[email protected]>
SVA device faults at the limit of a v1 memcg with the OOM killer disabled can leak a css reference, or cause a use-after-free of the memcg.
handle_mm_fault()enables the memcg OOM handling forFAULT_FLAG_USER, so a failed charge can leave a css reference incurrent->memcg_in_oom. OnVM_FAULT_OOMthe caller has to drop it inpagefault_out_of_memory(). Butiommu_sva_handle_mm()sets the flag for faults that it handles in a kworker, and never makes that call. The pointer stays on the kworker, and fork copies it to usermode helpers without a reference:kworker usermode helper ======= =============== iommu_sva_handle_mm() memcg1_oom_prepare() css_get() current->memcg_in_oom = memcg call_usermodehelper_exec_work() dup_task_struct() handle_mm_fault() css_put() iommu_sva_handle_mm() handle_mm_fault() css_put()Quoted 3 lines
Fix this by explicitly avoid
oom_disabledpath for workers. This would simply fail the charge and bail out without triggering the oom killer same as if this happened outside of #PF handler.
Quoted 5 lines
Hi Michal, I hope you are doing well. Thank you for the fix!
This was a fun fix to review because I wasn't entirely familiar with how v1 handles OOMs when the killer is disabled, so I got to learn about this mechanism.
Thanks for the review. Yes, this feature is quite tricky because it has loose ends quite far away and a unusual worker context change while sleeping inside a worker makes this hard to spot.
Quoted 9 lines
The fix looks good to me, thanks!
Reviewed-by Joshua Hahn <[email protected]>And I also reproduced the issue and saw that I would get a KASAN slab-use-after-free before, but no such error with this patch applied. I don't have easy access to real IOMMU or SVA devices, so I wrote a module to exercise the path that you note in the commit. It just mimics
iommu_sva_handle_mm().Tested-by Joshua Hahn <[email protected]>
Yes, this is the most trivial way to trigger that. Thanks for trying.
Quoted 26 lines
Quoted 26 lines
Fixes fc36479db74e ("iommu: Add a page fault handler")Cc stableReported-by Chris Mason <[email protected]>Signed-off-by Michal Hocko <[email protected]>--- mm/memcontrol-v1.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)mm/memcontrol-v1.c +2
-1@@ -1100,7 +1100,8 @@ bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked)* victim and then we have to bail out from the charge path. */ if (READ_ONCE (memcg->oom_kill_disable)) { -if (current->in_user_fault) { +if (current->in_user_fault && + !(current->flags & (PF_WQ_WORKER |PF_IO_WORKER ))) {css_get (&memcg->css); current->memcg_in_oom = memcg; }Signature · 1 line
2.56.1
Signature · 2 lines
Michal Hocko SUSE Labs
Michal Hocko
maintainerPATCH 2/10 mm/oom_kill: keep the allocating mm eligible
In reply to Michal HockoFrom: Chris Mason <[email protected]>
On a NUMA machine, a process can exhaust nodes that its own task mempolicy or cpuset. The mempolicy can kill unrelated tasks one after the other, and then panic, while that process is never selected.
The OOM killer skips a task that oom_cpuset_eligible() rejects, on the assumption that killing it frees nothing on the nodes that ran out. But each of the two tests in that function can reject the process whose mm is filling those nodes:
- In a mempolicy OOM, the function checks the mempolicy of the task. But the nodemask of the allocation can come from the mempolicy of a VMA, so a task with MPOL_BIND to other nodes can still fill the exhausted nodes.
- In a cpuset OOM, the function compares the mems_allowed of the task with that of current. mems_allowed is per task, so a vfork() child can allocate in a different cpuset from its parent. oom_badness() skips the child because it is in vfork(). The parent shares the mm, but it is rejected because its cpuset has other nodes.
Tasks with no mempolicy, or in the root cpuset, pass these tests and are killed instead. When none is left, out_of_memory() panics.
The fix used here is to treat every process that shares the mm of current as eligible, since current is allocating on the exhausted nodes.
--- mm/oom_kill.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-)
mm/oom_kill.c +17 -3
@@ -82,7 +82,8 @@ static inline bool is_memcg_oom(struct oom_control *oc)* * Task eligibility is determined by whether or not a candidate task, @tsk, * shares the same mempolicy nodes as current if it is bound by such a policy -* and whether or not it has the same set of allowed cpuset nodes. +* and whether or not it has the same set of allowed cpuset nodes. A process +* that shares the mm of current is always eligible. * * This function is assuming oom-killer context and 'current' has triggered * the oom-killer.
@@ -90,11 +91,23 @@ static inline bool is_memcg_oom(struct oom_control *oc)static bool oom_cpuset_eligible (struct task_struct *start,struct oom_control *oc) { +struct mm_struct *mm = current->mm;struct task_struct *tsk;bool ret = false;const nodemask_t *mask = oc->nodemask;rcu_read_lock (); +/* +* current allocates on the nodes of this oom, so its mm may have memory +* there. The tests below can miss that: the nodemask can come from the +* mempolicy of a vma while that of the task binds it to other nodes, and +* a process that shares the mm can be in another cpuset. +*/ +if (mm &&process_shares_mm (start, mm)) { + ret = true; + goto unlock; + } +for_each_thread (start, tsk) {if (mask) {/*
@@ -114,6 +127,7 @@ static bool oom_cpuset_eligible(struct task_struct *start,if (ret)break ; } +unlock:rcu_read_unlock ();return ret;
@@ -407,8 +421,8 @@ static int dump_task(struct task_struct *p, void *arg)* @oc: pointer to struct oom_control * * Dumps the current memory state of all eligible tasks. Tasks not in the same -* memcg, not in the same cpuset, or bound to a disjoint set of mempolicy nodes -* are not shown. +* memcg are not shown. Nor are tasks not in the same cpuset or bound to a +* disjoint set of mempolicy nodes, unless they share the mm of current. * State information includes task's pid, uid, tgid, vm size, rss, * pgtables_bytes, swapents, oom_score_adj value, and name. */
Signature · 1 line
2.56.1
Michal Hocko
maintainerPATCH 3/10 mm, oom: do not panic on constrained OOMs
In reply to Michal HockoFrom: Michal Hocko <[email protected]>
domain (cpuset, mempolicy or memcg) OOMs represent a partial shortage of memory. There might still be memory available outside of the domain and therefore panicing at this stage might disrupt otherwise operational workloads. We already avoid panicing for memcg ooms. Node bound (by mempolicy or cpusets) ooms shouldn't be any different from that.
Do not panic on any fail to find an oom victim unless this is full system wide oom (CONSTRAINT_NONE) context.
--- mm/oom_kill.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
mm/oom_kill.c +4 -3
@@ -1168,10 +1168,11 @@ bool out_of_memory(struct oom_control *oc)pr_warn ("Out of memory and no killable processes...\n" );/* * If we got here due to an actual allocation at the -* system level, we cannot survive this and will enter -* an endless loop in the allocator. Bail out now. +* system level without any constrains, we cannot survive this +* and will enter an endless loop in the allocator. +* Bail out now. */ -if (!is_sysrq_oom (oc) && !is_memcg_oom (oc)) +if (!is_sysrq_oom (oc) && oc->constraint ==CONSTRAINT_NONE )panic ("System is deadlocked on memory\n" ); }if (oc->chosen && oc->chosen != (void *)-1UL )
Signature · 1 line
2.56.1
Michal Hocko
maintainerPATCH 4/10 mm/oom_kill: ratelimit memcg OOM reports with no victim
In reply to Michal HockoFrom: Chris Mason <[email protected]>
A memory cgroup that is at its limit and has no killable task can flood the kernel log with OOM reports, and delay the OOM killer for the rest of the system.
When a memcg OOM finds no victim, out_of_memory() prints the whole OOM report and returns false. Nothing was freed, so the next charge that invokes the OOM killer, or the next write that sets memory.max below the usage, prints the same report again. Each report is printed with oom_lock held, which every other OOM in the system needs as well.
The fix used here is to rate limit the report of a memcg OOM with no victim. All memory cgroups share that rate limit, so a cgroup that keeps running into such an OOM can suppress the report of another cgroup. If that turns out to be too limiting we can make this per memcg but there doesn't seem to be a strong reason to go that way for now
--- mm/oom_kill.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-)
mm/oom_kill.c +14 -2
@@ -1164,8 +1164,20 @@ bool out_of_memory(struct oom_control *oc)select_bad_process (oc);/* Found nothing?!?! */ if (!oc->chosen) { -dump_header (oc); -pr_warn ("Out of memory and no killable processes...\n" ); + static DEFINE_RATELIMIT_STATE(memcg_rs, DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + +/* +* A memcg oom does not panic, and its caller goes on. A memcg +* memcg with no killable task gets here with each charge that +* calls the oom killer, and with each write to memory.max, so do +* not dump each time. +*/ +if (!is_memcg_oom (oc) ||__ratelimit (&memcg_rs)) { +dump_header (oc); +pr_warn ("Out of memory and no killable processes...\n" ); + } +/* * If we got here due to an actual allocation at the * system level without any constrains, we cannot survive this
Signature · 1 line
2.56.1
Michal Hocko
maintainerPATCH 5/10 mm, oom: thaw tasks sharing the mm with the oom victim
In reply to Michal HockoFrom: Michal Hocko <[email protected]>
If an OOM victim shares its mm with another process, a global OOM can panic the kernel if no other process is killable. Otherwise it can needlessly kill further processes. Both need a victim with much memory that the OOM reaper cannot free, such as page tables. They can happen if the other process is frozen by the cgroup v1 freezer.
Thaw tasks that are killed because they are sharing mm with the oom victim to address that.
--- mm/oom_kill.c | 1 + 1 file changed, 1 insertion(+)
mm/oom_kill.c +1 -0
@@ -990,6 +990,7 @@ static void __oom_kill_process(struct task_struct *victim, const char *message)if (unlikely (p->flags &PF_KTHREAD ))continue ;do_send_sig_info (SIGKILL ,SEND_SIG_PRIV , p,PIDTYPE_TGID ); +thaw_process (p); }rcu_read_unlock ();
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 05/10] mm, oom: thaw tasks sharing the mm with the oom victim
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] mm, oom: thaw_process() fails to thaw shared-mm tasks in __oom_kill_process() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] mm, oom: thaw_process() fails to thaw shared-mm tasks in __oom_kill_process()
--
commit 342e5dd06461083fcf31f5a288fe32e31c789a6e
Author: Michal Hocko <[email protected]>
mm, oom: thaw tasks sharing the mm with the oom victim
This commit calls thaw_process() on processes in other thread groups that are killed because they share their mm with the OOM victim.
mm/oom_kill.c static void __oom_kill_process(struct task_struct *victim, const char *message) · line 993
Quoted 9 lines
mm/oom_kill.c +1
-0@@ -990,6 +990,7 @@ static void __oom_kill_process(struct task_struct *victim, const char *message)if (unlikely (p->flags &PF_KTHREAD ))continue ;do_send_sig_info (SIGKILL ,SEND_SIG_PRIV , p,PIDTYPE_TGID ); +thaw_process (p);
[Severity: High]
Can thaw_process(p) actually unfreeze p here when mark_oom_victim() was only called on victim?
Because this loop skips same_thread_group(p, victim), p has its own signal_struct where p->signal->oom_mm is still NULL, so tsk_is_oom_victim() returns false for p's threads:
kernel/freezer.c:freezing_slow_path() {
...
if (tsk_is_oom_victim(p))
return false;
if (pm_nosig_freezing || cgroup1_freezing(p))
return true;
...
}When thaw_process(p) wakes a thread in __refrigerator() (or a thread in a TASK_FREEZABLE sleep that enters get_signal() -> try_to_freeze() before checking SIGKILL), freezing(current) still returns true if its cgroup v1 freezer is frozen. The thread goes right back into TASK_FROZEN without exiting, leaving the shared mm pinned and failing to avoid the extra OOM kills or panic this patch aims to prevent.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Michal Hocko
maintainerRe: [PATCH 05/10] mm, oom: thaw tasks sharing the mm with the oom victim
Quoted 42 lines · On Wed 02-12-26 16:30:59, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] mm, oom:thaw_process()fails to thaw shared-mm tasks in__oom_kill_process()
--commit
342e5dd06461083fcf31f5a288fe32e31c789a6e
Author: Michal Hocko <[email protected]>mm, oom: thaw tasks sharing the mm with the oom victim
This commit calls
thaw_process()on processes in other thread groups that are killed because they share their mm with the OOM victim.mm/oom_kill.c static void __oom_kill_process(struct task_struct *victim, const char *message) · line 993
Quoted 9 lines
mm/oom_kill.c +1
-0@@ -990,6 +990,7 @@ static void __oom_kill_process(struct task_struct *victim, const char *message)if (unlikely (p->flags &PF_KTHREAD ))continue ;do_send_sig_info (SIGKILL ,SEND_SIG_PRIV , p,PIDTYPE_TGID ); +thaw_process (p);[Severity: High]
Canthaw_process(p)actually unfreeze p here whenmark_oom_victim()was only called on victim?Because this loop skips
same_thread_group(p, victim), p has its ownsignal_structwherep->signal->oom_mmis still NULL, sotsk_is_oom_victim()returns false for p's threads:kernel/freezer.c:freezing_slow_path() { ... if (tsk_is_oom_victim(p)) return false; if (pm_nosig_freezing || cgroup1_freezing(p)) return true; ... }
Quoted 6 lines
When
thaw_process(p)wakes a thread in__refrigerator()(or a thread in aTASK_FREEZABLEsleep that entersget_signal()->try_to_freeze()before checking SIGKILL), freezing(current) still returns true if its cgroup v1 freezer is frozen. The thread goes right back intoTASK_FROZENwithout exiting, leaving the shared mm pinned and failing to avoid the extra OOM kills or panic this patch aims to prevent.
Correct. I believe the following should address the issue. I will fold that into the patch. Thanks for pointing out. I always forget all these details about freezer. I thought thaw_task would act merely on grounds of pending SIGKILL. Mea culpa
kernel/freezer.c +3 -0
@@ -44,6 +44,9 @@ bool freezing_slow_path(struct task_struct *p)if (tsk_is_oom_victim (p))return false; +if (p->mm &&mm_is_oom_victim (p->mm)) +return false; +if (pm_nosig_freezing ||cgroup1_freezing (p))return true;
Signature · 2 lines
Michal Hocko SUSE Labs
Michal Hocko
maintainerPATCH 6/10 mm, oom: check oom victims prior to numa placement
In reply to Michal HockoFrom: Michal Hocko <[email protected]>
oom_evaluate_task checks oom_cpuset_eligible before potential inflight oom victims. This allows to have several oom victims on disjunct numa domains but it also allows to unnecessarily kill more tasks than necessary. But if we have tasks that consume memory in multiple numa nodes (e.g. via vma memory policy) then we can bail too early:
TaskA (nodemask=1, vma->mpol=0), TaskB (nodemask=1)
OOM1(nodemask=0): TaskA killed
OOM2(nodemask=1): TaskA invisble due to oom_cpuset_eligible but it will be freeing memopry from node=1 too.
Check for existing oom victims before numa placement and bail out if there is any oom victim even if it could be in a different oom domain. This is a slow path and postponed OOM killing is almost always a better choice than killing that is too eager.
--- mm/oom_kill.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
mm/oom_kill.c +4 -4
@@ -318,10 +318,6 @@ static int oom_evaluate_task(struct task_struct *task, void *arg)if (oom_unkillable_task (task)) goto next; -/* p may not have freeable memory in nodemask */ -if (!is_memcg_oom (oc) && !oom_cpuset_eligible (task, oc)) - goto next; -/* * This task already has access to memory reserves and is being killed. * Don't allow any other task to have access to the reserves unless
@@ -334,6 +330,10 @@ static int oom_evaluate_task(struct task_struct *task, void *arg) goto abort; } +/* p may not have freeable memory in nodemask */ +if (!is_memcg_oom (oc) && !oom_cpuset_eligible (task, oc)) + goto next; +/* * If task is allocating a lot of memory and has been marked to be * killed first if it triggers an oom, then select it.
Signature · 1 line
2.56.1
Michal Hocko
maintainerPATCH 7/10 memcg, oom: wait for rcu_call callbacks before retrying reclaim
In reply to Michal HockoFrom: Michal Hocko <[email protected]>
In a memory cgroup with a small limit, the OOM killer can kill a task while most of the limit is taken up by memory that is already queued to be freed after an RCU grace period.
Memory that was passed to call_rcu() stays charged until its callback frees it. The task_struct and the credentials of an exited child are freed that way. With MMU_GATHER_RCU_TABLE_FREE, so are its page tables. Reclaim cannot free such memory, and call_rcu() does not throttle its caller. So tasks that fork short-lived children can fill the limit with memory that only waits to be freed. When a charge then fails at the limit, try_charge_memcg() reclaims and drains the per-CPU stocks. It then calls mem_cgroup_oom() without waiting for a grace period.
Call rcu_barrier before retrying the charge after unsuccessful reclaim (slow path) to reduce this potential issue.
--- mm/memcontrol.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
mm/memcontrol.c +4 -1
@@ -2800,8 +2800,11 @@ static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,if (nr_reclaimed && nr_pages <= (1 <<PAGE_ALLOC_COSTLY_ORDER )) goto retry; -if (nr_retries--) +if (nr_retries--) { +/* Wait for any potential call_rcu memory freers */ +rcu_barrier (); goto retry; + }if (gfp_mask & __GFP_RETRY_MAYFAIL) goto nomem;
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 07/10] memcg, oom: wait for rcu_call callbacks before retrying reclaim
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] memcg: repeated rcu_barrier() on every retry loop in try_charge_memcg() - [Medium] memcg: per-CPU…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] memcg: repeated rcu_barrier() on every retry loop in try_charge_memcg()
- [Medium] memcg: per-CPU stocks not drained after rcu_barrier() in try_charge_memcg()
--
commit cdd0f5947203961fb686dca72c1e12849c882b50
Author: Michal Hocko <[email protected]>
memcg, oom: wait for rcu_call callbacks before retrying reclaim
This commit calls rcu_barrier() in try_charge_memcg() before retrying the charge after unsuccessful reclaim, so pending call_rcu() memory frees complete before invoking the memcg OOM killer.
Quoted 7 lines
mm/memcontrol.c +0
-0@@ -2921,8 +2921,11 @@ static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,if (nr_reclaimed && nr_pages <= (1 <<PAGE_ALLOC_COSTLY_ORDER )) goto retry;
mm/memcontrol.c static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask, · line 2931
Quoted 10 lines
mm/memcontrol.c +4
-1-if (nr_retries--) +if (nr_retries--) { +/* Wait for any potential call_rcu memory freers */ +rcu_barrier (); goto retry; + }if (gfp_mask & __GFP_RETRY_MAYFAIL) goto nomem;
[Severity: High]
Should rcu_barrier() be limited to run at most once per charge rather than on every nr_retries iteration?
nr_retries starts at MAX_RECLAIM_RETRIES (16) and is reset to 16 after mem_cgroup_oom(), while each rcu_barrier() serializes on the global rcu_state.barrier_mutex, sends cross-CPU IPIs, and waits for a full RCU callback drain. In addition to running 16 times before each OOM attempt, costly high-order charges (nr_pages > 1 << PAGE_ALLOC_COSTLY_ORDER), such as THP faults with GFP_TRANSHUGE on MADV_HUGEPAGE mappings near memory.max, fall through the nr_reclaimed check above and block for 16 consecutive rcu_barrier() calls before falling back to order-0 pages.
[Severity: Medium]
Can the charges freed by RCU callbacks during rcu_barrier() remain trapped in per-CPU stocks without drain_all_stock() running again?
On the first failed reclaim pass, drain_all_stock(mem_over_limit) runs and sets drained = true before jumping to retry, so rcu_barrier() is only reached on a later pass after drained is already set:
mm/memcontrol.c:try_charge_memcg() {
...
if (!drained) {
drain_all_stock(mem_over_limit);
drained = true;
goto retry;
}
...
if (nr_retries--) {
/* Wait for any potential call_rcu memory freers */
rcu_barrier();
goto retry;
}
}When RCU callbacks such as delayed_put_task_struct() or tlb_remove_table_rcu() free slab objects and page tables during rcu_barrier(), they uncharge via obj_cgroup_uncharge_pages() -> refill_stock(), which caches up to MEMCG_STOCK_HIGH (64 pages) in the callback CPU's memcg_stock (plus up to a page in obj_stock). Because drained is never reset after rcu_barrier(), consume_stock() on retry only sees the charging CPU's local stock, leaving charges freed on other CPUs cached in remote stocks and still triggering mem_cgroup_oom() in small cgroups.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Michal Hocko
maintainerRe: [PATCH 07/10] memcg, oom: wait for rcu_call callbacks before retrying reclaim
Quoted 8 lines · On Wed 02-12-26 16:31:01, [email protected] wrote:
[Severity: Medium]
Can the charges freed by RCU callbacks duringrcu_barrier()remain trapped in per-CPU stocks withoutdrain_all_stock()running again?On the first failed reclaim pass,
drain_all_stock(mem_over_limit)runs and sets drained = true before jumping to retry, sorcu_barrier()is only reached on a later pass after drained is already set:
Quoted 14 lines
mm/memcontrol.c:try_charge_memcg() {
...
if (!drained) {
drain_all_stock(mem_over_limit);
drained = true;
goto retry;
}
...
if (nr_retries--) {
/* Wait for any potential call_rcu memory freers */
rcu_barrier();
goto retry;
}
}Right and I do not see this to be a problem.
Quoted 8 lines
When RCU callbacks such as
delayed_put_task_struct()ortlb_remove_table_rcu()free slab objects and page tables duringrcu_barrier(), they uncharge viaobj_cgroup_uncharge_pages()->refill_stock(), which caches up toMEMCG_STOCK_HIGH(64 pages) in the callback CPU'smemcg_stock(plus up to a page inobj_stock). Because drained is never reset afterrcu_barrier(),consume_stock()on retry only sees the charging CPU's local stock, leaving charges freed on other CPUs cached in remote stocks and still triggeringmem_cgroup_oom()in small cgroups.
Right, maybe something worth looking into but in a separate patch. I believe we can manage caches more efficiently in general rather than chasing for few cpus. If anything I would base that on top of Joshua's work (that I still owe a review).
Quoted 2 lines
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Signature · 2 lines
Michal Hocko SUSE Labs
Re: [PATCH 07/10] memcg, oom: wait for rcu_call callbacks before retrying reclaim
In reply to Michal HockoQuoted 17 lines · Michal Hocko
From: Michal Hocko <[email protected]>
In a memory cgroup with a small limit, the OOM killer can kill a task while most of the limit is taken up by memory that is already queued to be freed after an RCU grace period.
Memory that was passed to
call_rcu()stays charged until its callback frees it. Thetask_structand the credentials of an exited child are freed that way. WithMMU_GATHER_RCU_TABLE_FREE, so are its page tables. Reclaim cannot free such memory, andcall_rcu()does not throttle its caller.So tasks that fork short-lived children can fill the limit with memory that only waits to be freed. When a charge then fails at the limit,
try_charge_memcg()reclaims and drains the per-CPU stocks. It then callsmem_cgroup_oom()without waiting for a grace period.
Quoted 6 lines
Call
rcu_barrierbefore retrying the charge after unsuccessful reclaim (slow path) to reduce this potential issue.Reported-by Chris Mason <[email protected]>Signed-off-by Michal Hocko <[email protected]>---
I was wondering why we have to call rcu_barrier() for every retry instead of just once before OOM. Retrying memory won't free page tables anyway.
Apparently sashiko wondered it too.
Quoted 22 lines
mm/memcontrol.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)mm/memcontrol.c +4
-1@@ -2800,8 +2800,11 @@ static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,if (nr_reclaimed && nr_pages <= (1 <<PAGE_ALLOC_COSTLY_ORDER )) goto retry; -if (nr_retries--) +if (nr_retries--) { +/* Wait for any potential call_rcu memory freers */ +rcu_barrier (); goto retry; + }if (gfp_mask & __GFP_RETRY_MAYFAIL) goto nomem;Signature · 1 line
2.56.1
Signature · 2 lines
Cheers, Harry / Hyeonggon
Michal Hocko
maintainerRe: [PATCH 07/10] memcg, oom: wait for rcu_call callbacks before retrying reclaim
Quoted 25 lines · Harry Yoo
Quoted 17 lines · Michal Hocko
From: Michal Hocko <[email protected]>
In a memory cgroup with a small limit, the OOM killer can kill a task while most of the limit is taken up by memory that is already queued to be freed after an RCU grace period.
Memory that was passed to
call_rcu()stays charged until its callback frees it. Thetask_structand the credentials of an exited child are freed that way. WithMMU_GATHER_RCU_TABLE_FREE, so are its page tables. Reclaim cannot free such memory, andcall_rcu()does not throttle its caller.So tasks that fork short-lived children can fill the limit with memory that only waits to be freed. When a charge then fails at the limit,
try_charge_memcg()reclaims and drains the per-CPU stocks. It then callsmem_cgroup_oom()without waiting for a grace period.Quoted 6 lines
Call
rcu_barrierbefore retrying the charge after unsuccessful reclaim (slow path) to reduce this potential issue.Reported-by Chris Mason <[email protected]>Signed-off-by Michal Hocko <[email protected]>---
Quoted 5 lines
I was wondering why we have to call
rcu_barrier()for every retry instead of just once before OOM. Retrying memory won't free page tables anyway.Apparently sashiko wondered it too.
I considered this to be a slow path (the full reclaim round to fail) so additional wait on rcu_barrier doesn't seem all that terrible. Yet we capture potential memory freers before retrying the charge. I could have done something like
mm/memcontrol.c +2 -1
@@ -2802,7 +2802,8 @@ static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,if (nr_retries--) {/* Wait for any potential call_rcu memory freers */ -rcu_barrier (); +if (!nr_retries) +rcu_barrier (); goto retry; }
to reduce that to the very last run. But this is a bit confusing and in the worst case we are going through more expensive reclaim rounds while there might be rcu callbacks sitting and waiting. I do not think we have a decent way of knowning and making that more directed. But if there is a general agreement that this is the right way, I can go with that of course. This would be really hard to measure without artificial workloads which I do not want to really optimize for.
Signature · 2 lines
Michal Hocko SUSE Labs
Michal Hocko
maintainerPATCH 8/10 mm, oom: wait for rcu_call callbacks before retrying reclaim
In reply to Michal HockoFrom: Michal Hocko <[email protected]>
Memory reclaim can miss quite a lot of pages freed through call_rcu because it itself doen't trigger RCU grace period. cond_resched() is not sufficient for that. Call rcu_barrier to wait for those callbacks to execute before retrying the reclaim loop again.
--- mm/page_alloc.c | 3 +++ 1 file changed, 3 insertions(+)
mm/page_alloc.c +3 -0
@@ -4701,6 +4701,9 @@ should_reclaim_retry(gfp_t gfp_mask, unsigned order,schedule_timeout_uninterruptible (1 ); elsecond_resched (); + +/* Wait for any potential call_rcu memory freers */ +rcu_barrier (); out:/* Before OOM, exhaust highatomic_reserve */ if (!ret)
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 08/10] mm, oom: wait for rcu_call callbacks before retrying reclaim
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] mm: rcu_barrier() in should_reclaim_retry() runs after zone watermark check - [High] mm…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] mm: rcu_barrier() in should_reclaim_retry() runs after zone watermark check
- [High] mm: should_reclaim_retry() calls rcu_barrier() even when reclaim progresses
--
commit 80d44083709f0dc6896c3ee8f1c5829f534bd7fa
Author: Michal Hocko <[email protected]>
mm, oom: wait for rcu_call callbacks before retrying reclaim
This commit adds an rcu_barrier() call in should_reclaim_retry() to wait for in-flight RCU callbacks to free memory before retrying reclaim.
Quoted 5 lines
mm/page_alloc.c +0
-0
mm/page_alloc.c should_reclaim_retry(gfp_t gfp_mask, unsigned order, · line 4721
Quoted 9 lines
mm/page_alloc.c +3
-0@@ -4713,6 +4713,9 @@ should_reclaim_retry(gfp_t gfp_mask, unsigned order,schedule_timeout_uninterruptible (1 ); elsecond_resched (); + +/* Wait for any potential call_rcu memory freers */ +rcu_barrier (); out:/* Before OOM, exhaust highatomic_reserve */ if (!ret)
[Severity: High]
Does running rcu_barrier() after the zone watermark loop cause should_reclaim_retry() to return false without re-checking the memory just freed by the RCU callbacks?
Pages waiting on call_rcu() are not counted in zone_reclaimable_pages() or NR_FREE_PAGES until their callbacks run. When remaining LRU and free pages are below min_wmark, the loop leaves ret as false before rcu_barrier() drains the pending callbacks, so should_reclaim_retry() still returns false and __alloc_pages_slowpath() proceeds straight to __alloc_pages_may_oom() instead of retrying the allocation.
[Severity: High]
Should rcu_barrier() be skipped when direct reclaim made progress (did_some_progress is true and *no_progress_loops is reset to 0), similar to how commit "memcg, oom: wait for rcu_call callbacks before retrying reclaim" only calls rcu_barrier() in try_charge_memcg() when nr_reclaimed is zero?
Calling rcu_barrier() unconditionally on every should_reclaim_retry() pass serializes all multi-pass direct-reclaim threads on rcu_state.barrier_mutex, sends cross-CPU IPIs, and waits for a full RCU grace period even while normal reclaim is actively freeing pages.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Michal Hocko
maintainerRe: [PATCH 08/10] mm, oom: wait for rcu_call callbacks before retrying reclaim
Quoted 50 lines · On Wed 02-12-26 16:31:02, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] mm:rcu_barrier()inshould_reclaim_retry()runs after zone watermark check
- [High] mm:should_reclaim_retry()callsrcu_barrier()even when reclaim progresses
--commit
80d44083709f0dc6896c3ee8f1c5829f534bd7fa
Author: Michal Hocko <[email protected]>mm, oom: wait for
rcu_callcallbacks before retrying reclaimThis commit adds an
rcu_barrier()call inshould_reclaim_retry()to wait for in-flight RCU callbacks to free memory before retrying reclaim.Quoted 5 lines
mm/page_alloc.c +0
-0mm/page_alloc.c should_reclaim_retry(gfp_t gfp_mask, unsigned order, · line 4721
Quoted 9 lines
mm/page_alloc.c +3
-0@@ -4713,6 +4713,9 @@ should_reclaim_retry(gfp_t gfp_mask, unsigned order,schedule_timeout_uninterruptible (1 ); elsecond_resched (); + +/* Wait for any potential call_rcu memory freers */ +rcu_barrier (); out:/* Before OOM, exhaust highatomic_reserve */ if (!ret)[Severity: High]
Does runningrcu_barrier()after the zone watermark loop causeshould_reclaim_retry()to return false without re-checking the memory just freed by the RCU callbacks?Pages waiting on
call_rcu()are not counted inzone_reclaimable_pages()orNR_FREE_PAGESuntil their callbacks run. When remaining LRU and free pages are belowmin_wmark, the loop leaves ret as false beforercu_barrier()drains the pending callbacks, soshould_reclaim_retry()still returns false and__alloc_pages_slowpath()proceeds straight to__alloc_pages_may_oom()instead of retrying the allocation.[Severity: High]
Shouldrcu_barrier()be skipped when direct reclaim made progress (did_some_progressis true and*no_progress_loopsis reset to 0), similar to how commit "memcg, oom: wait forrcu_callcallbacks before retrying reclaim" only callsrcu_barrier()intry_charge_memcg()whennr_reclaimedis zero?
Quoted 4 lines
Calling
rcu_barrier()unconditionally on everyshould_reclaim_retry()pass serializes all multi-pass direct-reclaim threads on rcu_state.barrier_mutex, sends cross-CPU IPIs, and waits for a full RCU grace period even while normal reclaim is actively freeing pages.
Fair point. I will think about some more. I have to admit I am not entirely convinced about this patch. I should have probably marked it RFC.
Quoted 2 lines
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Signature · 2 lines
Michal Hocko SUSE Labs
Michal Hocko
maintainerRe: [PATCH 08/10] mm, oom: wait for rcu_call callbacks before retrying reclaim
In reply to Michal HockoI am dropping this patch based on discussion with Paul and conclusion
reached in https://lore.kernel.org/all/ed6c5f64-7afe-45a2-8d18-e4e1c0052840@paulmck-laptop/T/#u
Quoted 29 lines · Michal Hocko
From: Michal Hocko <[email protected]>
Memory reclaim can miss quite a lot of pages freed through
call_rcubecause it itself doen't trigger RCU grace period.cond_resched()is not sufficient for that. Callrcu_barrierto wait for those callbacks to execute before retrying the reclaim loop again.Signed-off-by Michal Hocko <[email protected]>--- mm/page_alloc.c | 3 +++ 1 file changed, 3 insertions(+)mm/page_alloc.c +3
-0@@ -4701,6 +4701,9 @@ should_reclaim_retry(gfp_t gfp_mask, unsigned order,schedule_timeout_uninterruptible (1 ); elsecond_resched (); + +/* Wait for any potential call_rcu memory freers */ +rcu_barrier (); out:/* Before OOM, exhaust highatomic_reserve */ if (!ret)Signature · 1 line
2.56.1
Signature · 2 lines
Michal Hocko SUSE Labs
Michal Hocko
maintainerPATCH 9/10 mm, oom: add rcu_barrier before hiding victim from the oom killer
In reply to Michal HockoFrom: Michal Hocko <[email protected]>
OOM victim could have released quite a lot of memory through rcu_call path (e.g. page tables). Call rcu_barrier before setting MMF_OOM_SKIP on the victim to wait for those to execute before the oom killer is allowed to pick another victim.
Also move MMF_OOM_SKIP in exit_mmap path after page tables are freed to capture as much memory as possible to be freed. This is safe from the forward progress POV because oom_reaper will run concurrently in case the exit path gets stuck. We are going to see less memory freed by the oom reaper because it cannot tear down page tables directly but that should be acceptable.
--- mm/mmap.c | 21 +++++++++------------ mm/oom_kill.c | 7 +++++++ 2 files changed, 16 insertions(+), 12 deletions(-)
mm/mmap.c +9 -12
@@ -1313,20 +1313,8 @@ void exit_mmap(struct mm_struct *mm)/* update_hiwater_rss(mm) here? but nobody should be looking */ /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); - -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ -if (mm_is_oom_victim (mm)) -tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);
@@ -1334,6 +1322,15 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ +if (mm_is_oom_victim (mm)) { +rcu_barrier (); +mm_flags_set (MMF_OOM_SKIP , mm); + } +/* * Walk the list again, actually closing and freeing it, with preemption * enabled, without holding any MM locks besides the unreachable
mm/oom_kill.c +7 -0
@@ -628,6 +628,13 @@ static void oom_reap_task(struct task_struct *tsk) done: tsk->oom_reaper_list =NULL ; +/* +* Make sure that pre-exising call_rcu users will get a chance to +* free up memory. This might have been exiting task itself as well +* so call this before we hide the current victim from the oom killer. +*/ +rcu_barrier (); +/* * Hide this mm from OOM killer because it has been either reaped or * somebody can't call mmap_write_unlock(mm).
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 09/10] mm, oom: add rcu_barrier before hiding victim from the oom killer
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] mm: exit_mmap() delays tlb flush and MMF_OOM_SKIP across free_pgtables() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] mm: exit_mmap() delays tlb flush and MMF_OOM_SKIP across free_pgtables()
--
commit 1c8250a513b4c920254c3d354feba98a795ac23c
Author: Michal Hocko <[email protected]>
mm, oom: add rcu_barrier before hiding victim from the oom killer
This commit adds rcu_barrier() before setting MMF_OOM_SKIP in oom_reap_task() and exit_mmap(), and moves the MMF_OOM_SKIP update in exit_mmap() after free_pgtables() and tlb_finish_mmu().
Quoted 27 lines
mm/mmap.c +0
-12@@ -1317,20 +1317,8 @@ void exit_mmap(struct mm_struct *mm)/* update_hiwater_rss(mm) here? but nobody should be looking */ /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); - -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ -if (mm_is_oom_victim (mm)) -tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);@@ -1338,6 +1326,15 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);
mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1336
Quoted 10 lines
mm/mmap.c +8
-0tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ +if (mm_is_oom_victim (mm)) { +rcu_barrier (); +mm_flags_set (MMF_OOM_SKIP , mm); + }
[Severity: High]
Does removing tlb_flush_mmu(&tlb) after unmap_vmas() and delaying MMF_OOM_SKIP across free_pgtables() leave gathered data folios unfreed while blocking the OOM reaper on mmap_write_lock(mm)?
unmap_vmas() clears the PTEs and leaves up to MAX_GATHER_BATCH_COUNT batches of unmapped data pages queued in exit_mmap()'s on-stack struct mmu_gather tlb until tlb_finish_mmu(). Once the PTEs are cleared, a concurrent oom_reap_task_mm() cannot reclaim those pages from the page tables either.
free_pgtables() then runs under mmap_write_lock(mm) and takes sleeping VMA and rmap locks (vma_start_write(), anon_vma->root->rwsem in unlink_anon_vmas(), and mapping->i_mmap_rwsem in unlink_file_vma_batch_final()), followed by rcu_barrier() still under mmap_write_lock(mm).
While exit_mmap() is blocked in free_pgtables() or rcu_barrier() holding mmap_write_lock(mm), oom_reap_task_mm() fails mmap_read_trylock(mm). After MAX_OOM_REAP_RETRIES, oom_reap_task() sees MMF_OOM_SKIP still clear, emits false "oom_reaper: unable to reap pid" warnings and lock dumps (regressing 97b1255cb27c ("mm,oom_reaper: check for MMF_OOM_SKIP before complaining")), and sets MMF_OOM_SKIP while the gathered data pages in tlb are still unfreed (regressing a35b6312255d ("mm/mmap: free gathered pages before MMF_OOM_SKIP")).
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Michal Hocko
maintainerRe: [PATCH 09/10] mm, oom: add rcu_barrier before hiding victim from the oom killer
Forgot to CC Lorenzo, sorry about that.
Quoted 70 lines · On Wed 02-12-26 16:31:03, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] mm:exit_mmap()delays tlb flush andMMF_OOM_SKIPacrossfree_pgtables()
--commit
1c8250a513b4c920254c3d354feba98a795ac23c
Author: Michal Hocko <[email protected]>mm, oom: add
rcu_barrierbefore hiding victim from the oom killerThis commit adds
rcu_barrier()before settingMMF_OOM_SKIPinoom_reap_task()andexit_mmap(), and moves theMMF_OOM_SKIPupdate inexit_mmap()afterfree_pgtables()andtlb_finish_mmu().Quoted 27 lines
mm/mmap.c +0
-12@@ -1317,20 +1317,8 @@ void exit_mmap(struct mm_struct *mm)/* update_hiwater_rss(mm) here? but nobody should be looking */ /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); - -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ -if (mm_is_oom_victim (mm)) -tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);@@ -1338,6 +1326,15 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1336
Quoted 10 lines
mm/mmap.c +8
-0tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ +if (mm_is_oom_victim (mm)) { +rcu_barrier (); +mm_flags_set (MMF_OOM_SKIP , mm); + }[Severity: High]
Does removingtlb_flush_mmu(&tlb)afterunmap_vmas()and delayingMMF_OOM_SKIPacrossfree_pgtables()leave gathered data folios unfreed while blocking the OOM reaper onmmap_write_lock(mm)?
unmap_vmas()clears the PTEs and leaves up toMAX_GATHER_BATCH_COUNTbatches of unmapped data pages queued in exit_mmap()'s on-stack structmmu_gathertlb untiltlb_finish_mmu(). Once the PTEs are cleared, a concurrentoom_reap_task_mm()cannot reclaim those pages from the page tables either.
free_pgtables()then runs undermmap_write_lock(mm)and takes sleeping VMA and rmap locks (vma_start_write(),anon_vma->root->rwseminunlink_anon_vmas(), andmapping->i_mmap_rwseminunlink_file_vma_batch_final()), followed byrcu_barrier()still undermmap_write_lock(mm).
Quoted 8 lines
While
exit_mmap()is blocked infree_pgtables()orrcu_barrier()holdingmmap_write_lock(mm),oom_reap_task_mm()failsmmap_read_trylock(mm). AfterMAX_OOM_REAP_RETRIES,oom_reap_task()seesMMF_OOM_SKIPstill clear, emits false "oom_reaper: unable to reap pid" warnings and lock dumps (regressing97b1255cb27c("mm,oom_reaper: check forMMF_OOM_SKIPbefore complaining")), and setsMMF_OOM_SKIPwhile the gathered data pages in tlb are still unfreed (regressinga35b6312255d("mm/mmap: free gathered pages beforeMMF_OOM_SKIP")).
OK, my primary intention was to delay MMF_OOM_SKIP primarily. But dropping tlb_flush_mmu seems just pointless (well, just to save one branch in the exit hot path) and it can actually do more bad than good. I will fold this in
mm/mmap.c +4 -0
@@ -1313,6 +1313,10 @@ void exit_mmap(struct mm_struct *mm)/* update_hiwater_rss(mm) here? but nobody should be looking */ /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); + +/* Free batched pages during unmap_vmas ASAP for oom victims */ +if (mm_is_oom_victim (mm)) +tlb_flush_mmu (&tlb);mmap_read_unlock (mm);mmap_write_lock (mm);
Signature · 2 lines
Michal Hocko SUSE Labs
Lorenzo Stoakes (ARM)
maintainerRe: [PATCH 09/10] mm, oom: add rcu_barrier before hiding victim from the oom killer
Quoted 1 line · Michal Hocko
Forgot to CC Lorenzo, sorry about that.
Apology should be mine, sorry did mean to take a look at this off-list previously, just snowed under!
I guess you'll respin given the below? I can wait for that I guess?
Quoted 102 lines · On Wed 02-12-26 16:31:03, [email protected] wrote:
Quoted 70 lines
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] mm:exit_mmap()delays tlb flush andMMF_OOM_SKIPacrossfree_pgtables()
--commit
1c8250a513b4c920254c3d354feba98a795ac23c
Author: Michal Hocko <[email protected]>mm, oom: add
rcu_barrierbefore hiding victim from the oom killerThis commit adds
rcu_barrier()before settingMMF_OOM_SKIPinoom_reap_task()andexit_mmap(), and moves theMMF_OOM_SKIPupdate inexit_mmap()afterfree_pgtables()andtlb_finish_mmu().Quoted 27 lines
mm/mmap.c +0
-12@@ -1317,20 +1317,8 @@ void exit_mmap(struct mm_struct *mm)/* update_hiwater_rss(mm) here? but nobody should be looking */ /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); - -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ -if (mm_is_oom_victim (mm)) -tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);@@ -1338,6 +1326,15 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1336
Quoted 10 lines
mm/mmap.c +8
-0tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ +if (mm_is_oom_victim (mm)) { +rcu_barrier (); +mm_flags_set (MMF_OOM_SKIP , mm); + }[Severity: High]
Does removingtlb_flush_mmu(&tlb)afterunmap_vmas()and delayingMMF_OOM_SKIPacrossfree_pgtables()leave gathered data folios unfreed while blocking the OOM reaper onmmap_write_lock(mm)?
unmap_vmas()clears the PTEs and leaves up toMAX_GATHER_BATCH_COUNTbatches of unmapped data pages queued in exit_mmap()'s on-stack structmmu_gathertlb untiltlb_finish_mmu(). Once the PTEs are cleared, a concurrentoom_reap_task_mm()cannot reclaim those pages from the page tables either.
free_pgtables()then runs undermmap_write_lock(mm)and takes sleeping VMA and rmap locks (vma_start_write(),anon_vma->root->rwseminunlink_anon_vmas(), andmapping->i_mmap_rwseminunlink_file_vma_batch_final()), followed byrcu_barrier()still undermmap_write_lock(mm).Quoted 8 lines
While
exit_mmap()is blocked infree_pgtables()orrcu_barrier()holdingmmap_write_lock(mm),oom_reap_task_mm()failsmmap_read_trylock(mm). AfterMAX_OOM_REAP_RETRIES,oom_reap_task()seesMMF_OOM_SKIPstill clear, emits false "oom_reaper: unable to reap pid" warnings and lock dumps (regressing97b1255cb27c("mm,oom_reaper: check forMMF_OOM_SKIPbefore complaining")), and setsMMF_OOM_SKIPwhile the gathered data pages in tlb are still unfreed (regressinga35b6312255d("mm/mmap: free gathered pages beforeMMF_OOM_SKIP")).OK, my primary intention was to delay
MMF_OOM_SKIPprimarily. But droppingtlb_flush_mmuseems just pointless (well, just to save one branch in the exit hot path) and it can actually do more bad than good. I will fold this inmm/mmap.c +4
-1@@ -1313,6 +1313,10 @@ void exit_mmap(struct mm_struct *mm)/* update_hiwater_rss(mm) here? but nobody should be looking */ /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); + +/* Free batched pages during unmap_vmas ASAP for oom victims */ +if (mm_is_oom_victim (mm)) +tlb_flush_mmu (&tlb);mmap_read_unlock (mm);mmap_write_lock (mm); --
Quoted 2 lines
Michal Hocko
SUSE Labs
--
Cheers, Lorenzo
Michal Hocko
maintainerPATCH v2 1/1 mm, oom: add rcu_barrier before hiding victim from the oom killer
In reply to Michal HockoFrom: Michal Hocko <[email protected]>
OOM victim could have released quite a lot of memory through rcu_call path (e.g. page tables). Call rcu_barrier before setting MMF_OOM_SKIP on the victim to wait for those to execute before the oom killer is allowed to pick another victim.
Also move MMF_OOM_SKIP in exit_mmap path after page tables are freed to capture as much memory as possible to be freed. This is safe from the forward progress POV because oom_reaper will run concurrently in case the exit path gets stuck. We are going to see less memory freed by the oom reaper because it cannot tear down page tables directly but that should be acceptable.
--- mm/mmap.c | 19 ++++++++++--------- mm/oom_kill.c | 7 +++++++ 2 files changed, 17 insertions(+), 9 deletions(-)
mm/mmap.c +10 -9
@@ -1314,19 +1314,11 @@ void exit_mmap(struct mm_struct *mm)/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ +/* Free batched pages during unmap_vmas ASAP for oom victims */ if (mm_is_oom_victim (mm))tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);
@@ -1334,6 +1326,15 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ +if (mm_is_oom_victim (mm)) { +rcu_barrier (); +mm_flags_set (MMF_OOM_SKIP , mm); + } +/* * Walk the list again, actually closing and freeing it, with preemption * enabled, without holding any MM locks besides the unreachable
mm/oom_kill.c +7 -0
@@ -628,6 +628,13 @@ static void oom_reap_task(struct task_struct *tsk) done: tsk->oom_reaper_list =NULL ; +/* +* Make sure that pre-exising call_rcu users will get a chance to +* free up memory. This might have been exiting task itself as well +* so call this before we hide the current victim from the oom killer. +*/ +rcu_barrier (); +/* * Hide this mm from OOM killer because it has been either reaped or * somebody can't call mmap_write_unlock(mm).
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] mm: delaying MMF_OOM_SKIP in exit_mmap() breaks oom_reaper synchronization - [Medium] mm, oom…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] mm: delaying MMF_OOM_SKIP in exit_mmap() breaks oom_reaper synchronization
- [Medium] mm, oom: redundant rcu_barrier() in exit_mmap() and oom_reap_task()
--
commit d8b9a20b6dcaba9ce0a826a457c923a1fe4ea9c1
Author: Michal Hocko <[email protected]>
mm, oom: add rcu_barrier before hiding victim from the oom killer
This commit calls rcu_barrier() before setting MMF_OOM_SKIP in oom_reap_task() and exit_mmap(), and moves setting MMF_OOM_SKIP in exit_mmap() after free_pgtables() under mm_is_oom_victim(mm).
Quoted 27 lines
mm/mmap.c +1
-9@@ -1318,19 +1318,11 @@ void exit_mmap(struct mm_struct *mm)/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ +/* Free batched pages during unmap_vmas ASAP for oom victims */ if (mm_is_oom_victim (mm))tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);@@ -1338,6 +1330,15 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);
mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1340
Quoted 10 lines
mm/mmap.c +8
-0tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ +if (mm_is_oom_victim (mm)) { +rcu_barrier (); +mm_flags_set (MMF_OOM_SKIP , mm); + }
[Severity: Medium]
Does delaying MMF_OOM_SKIP until after free_pgtables() and rcu_barrier(), and gating it on mm_is_oom_victim(mm), break exit_mmap() synchronization with oom_reap_task() and process_mrelease()?
oom_reap_task_mm() and oom_reap_task() rely on exit_mmap() setting MMF_OOM_SKIP before acquiring mmap_write_lock(mm):
mm/oom_kill.c:oom_reap_task_mm() {
...
/*
* MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't
* work on the mm anymore. The check for MMF_OOM_SKIP must run
* under mmap_lock for reading because it serializes against the
* mmap_write_lock();mmap_write_unlock() cycle in exit_mmap().
*/
if (mm_flags_test(MMF_OOM_SKIP, mm)) {
trace_skip_task_reaping(tsk->pid);
goto out_unlock;
}
...
}With MMF_OOM_SKIP moved after free_pgtables() and rcu_barrier(), exit_mmap() holds mmap_write_lock(mm) across sleeping anon_vma, i_mmap and RCU barrier waits while MMF_OOM_SKIP is still clear, even though unmap_vmas() and tlb_flush_mmu() have already freed the victim's anonymous pages. If oom_reap_task() runs during this phase, mmap_read_trylock(mm) fails repeatedly and oom_reap_task() finds MMF_OOM_SKIP unset after MAX_OOM_REAP_RETRIES, emitting false "unable to reap" warnings, task dumps, and debug_show_all_locks() output.
Leaving MMF_OOM_SKIP unset between mmap_read_unlock(mm) and mmap_write_lock(mm) also lets oom_reap_task_mm() grab mmap_read_lock(mm) in that window, walk already-unmapped VMAs while blocking exit_mmap() from starting free_pgtables(), and set MMF_OOM_SKIP in oom_reap_task() before page tables are freed.
In addition, gating mm_flags_set(MMF_OOM_SKIP, mm) on mm_is_oom_victim(mm) means processes killed from userspace never set MMF_OOM_SKIP in exit_mmap(), breaking the MMF_OOM_SKIP checks in process_mrelease().
Quoted 8 lines
mm/oom_kill.c +0
-0@@ -614,6 +614,13 @@ static void oom_reap_task(struct task_struct *tsk) done: tsk->oom_reaper_list =NULL ;
mm/oom_kill.c static void oom_reap_task(struct task_struct *tsk) · line 626
Quoted 10 lines
mm/oom_kill.c +7
-0+/* +* Make sure that pre-exising call_rcu users will get a chance to +* free up memory. This might have been exiting task itself as well +* so call this before we hide the current victim from the oom killer. +*/ +rcu_barrier (); +/* * Hide this mm from OOM killer because it has been either reaped or * somebody can't call mmap_write_unlock(mm).
[Severity: Medium]
Can oom_reap_task() and exit_mmap() both run a redundant rcu_barrier() on the same victim when MMF_OOM_SKIP is already set?
When exit_mmap() finishes first and sets MMF_OOM_SKIP, oom_reap_task_mm() or oom_reap_task() sees MMF_OOM_SKIP and jumps to done:, where it still calls rcu_barrier() unconditionally and stalls the oom_reaper kthread before it can reap other victims on oom_reaper_list. Conversely, when oom_reap_task() finishes first and sets MMF_OOM_SKIP, the victim is already hidden from the OOM killer, yet exit_mmap() still runs rcu_barrier() under mmap_write_lock(mm) before tear_down_vmas() and __mt_destroy() can free the VMAs and maple tree nodes.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Michal Hocko
maintainerRe: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
Quoted 78 lines · On Wed 02-12-26 22:08:16, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] mm: delayingMMF_OOM_SKIPinexit_mmap()breaksoom_reapersynchronization
- [Medium] mm, oom: redundantrcu_barrier()inexit_mmap()andoom_reap_task()
--commit
d8b9a20b6dcaba9ce0a826a457c923a1fe4ea9c1
Author: Michal Hocko <[email protected]>mm, oom: add
rcu_barrierbefore hiding victim from the oom killerThis commit calls
rcu_barrier()before settingMMF_OOM_SKIPinoom_reap_task()andexit_mmap(), and moves settingMMF_OOM_SKIPinexit_mmap()afterfree_pgtables()undermm_is_oom_victim(mm).Quoted 27 lines
mm/mmap.c +1
-9@@ -1318,19 +1318,11 @@ void exit_mmap(struct mm_struct *mm)/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ +/* Free batched pages during unmap_vmas ASAP for oom victims */ if (mm_is_oom_victim (mm))tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);@@ -1338,6 +1330,15 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1340
Quoted 10 lines
mm/mmap.c +8
-0tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ +if (mm_is_oom_victim (mm)) { +rcu_barrier (); +mm_flags_set (MMF_OOM_SKIP , mm); + }[Severity: Medium]
Does delayingMMF_OOM_SKIPuntil afterfree_pgtables()andrcu_barrier(), and gating it onmm_is_oom_victim(mm), breakexit_mmap()synchronization withoom_reap_task()andprocess_mrelease()?
oom_reap_task_mm()andoom_reap_task()rely onexit_mmap()settingMMF_OOM_SKIPbefore acquiringmmap_write_lock(mm):mm/oom_kill.c:oom_reap_task_mm() { ... /* * MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't * work on the mm anymore. The check for MMF_OOM_SKIP must run * under mmap_lock for reading because it serializes against the * mmap_write_lock();mmap_write_unlock() cycle in exit_mmap(). */ if (mm_flags_test(MMF_OOM_SKIP, mm)) { trace_skip_task_reaping(tsk->pid); goto out_unlock; } ... }
Quoted 5 lines
With
MMF_OOM_SKIPmoved afterfree_pgtables()andrcu_barrier(),exit_mmap()holdsmmap_write_lock(mm)across sleepinganon_vma,i_mmapand RCU barrier waits whileMMF_OOM_SKIPis still clear, even thoughunmap_vmas()andtlb_flush_mmu()have already freed the victim's anonymous pages.
Correct
Quoted 4 lines
If
oom_reap_task()runs during this phase,mmap_read_trylock(mm)fails repeatedly andoom_reap_task()findsMMF_OOM_SKIPunset afterMAX_OOM_REAP_RETRIES, emitting false "unable to reap" warnings, task dumps, anddebug_show_all_locks()output.
Right. This is likely unnecessary but I would consider it mostly harmless. debug_show_all_locks is nop without CONFIG_LOCKDEP which is the case for most production workloads. Dumping the victims stack is more noisy than necessary but I would rather wait for this being a real problem than developing a specific solution for that.
Quoted 5 lines
Leaving
MMF_OOM_SKIPunset betweenmmap_read_unlock(mm)andmmap_write_lock(mm)also letsoom_reap_task_mm()grabmmap_read_lock(mm)in that window, walk already-unmapped VMAs while blockingexit_mmap()from startingfree_pgtables(), and setMMF_OOM_SKIPinoom_reap_task()before page tables are freed.
Yes. We cannot have both. oom_reaper is delayed to allow normal victim to finish properly before meddling with it.
Quoted 4 lines
In addition, gating
mm_flags_set(MMF_OOM_SKIP, mm)onmm_is_oom_victim(mm)means processes killed from userspace never setMMF_OOM_SKIPinexit_mmap(), breaking theMMF_OOM_SKIPchecks inprocess_mrelease().
mm/mmap.c +2 -3
@@ -1330,10 +1330,9 @@ void exit_mmap(struct mm_struct *mm)* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM * killer will only skip this mm if it's already freed all it can. */ -if (mm_is_oom_victim (mm)) { +if (mm_is_oom_victim (mm))rcu_barrier (); -mm_flags_set (MMF_OOM_SKIP , mm); - } +mm_flags_set (MMF_OOM_SKIP , mm);/* * Walk the list again, actually closing and freeing it, with preemption
Quoted 8 lines
Quoted 8 lines
mm/oom_kill.c +0
-0@@ -614,6 +614,13 @@ static void oom_reap_task(struct task_struct *tsk) done: tsk->oom_reaper_list =NULL ;
Quoted 14 lines
mm/oom_kill.c static void oom_reap_task(struct task_struct *tsk) · line 626
Quoted 10 lines
mm/oom_kill.c +7
-0+/* +* Make sure that pre-exising call_rcu users will get a chance to +* free up memory. This might have been exiting task itself as well +* so call this before we hide the current victim from the oom killer. +*/ +rcu_barrier (); +/* * Hide this mm from OOM killer because it has been either reaped or * somebody can't call mmap_write_unlock(mm). [Severity: Medium]
Canoom_reap_task()andexit_mmap()both run a redundantrcu_barrier()on the same victim whenMMF_OOM_SKIPis already set?
They can. Unless I miss something I do not see that as necessarily wrong thing to do. On the oom_reaper side of things this could slow down operation unnecessarily but this is not a fast path and it should provide a way to ensure we do not allow oom killer to go after another victim while there is memory being freed through rcu.
On the exit_mmap side we are flushing after the victims active contribution to the rcu freed data structures from the page table freeing.
So I would say prefer a simpler solution for now.
Let's see whether there is a general agreement with those decisions before I send v3.
Signature · 2 lines
Michal Hocko SUSE Labs
Liam R. Howlett
maintainerRe: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
Quoted 117 lines · Michal Hocko
Quoted 78 lines · On Wed 02-12-26 22:08:16, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] mm: delayingMMF_OOM_SKIPinexit_mmap()breaksoom_reapersynchronization
- [Medium] mm, oom: redundantrcu_barrier()inexit_mmap()andoom_reap_task()
--commit
d8b9a20b6dcaba9ce0a826a457c923a1fe4ea9c1
Author: Michal Hocko <[email protected]>mm, oom: add
rcu_barrierbefore hiding victim from the oom killerThis commit calls
rcu_barrier()before settingMMF_OOM_SKIPinoom_reap_task()andexit_mmap(), and moves settingMMF_OOM_SKIPinexit_mmap()afterfree_pgtables()undermm_is_oom_victim(mm).Quoted 27 lines
mm/mmap.c +1
-9@@ -1318,19 +1318,11 @@ void exit_mmap(struct mm_struct *mm)/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ +/* Free batched pages during unmap_vmas ASAP for oom victims */ if (mm_is_oom_victim (mm))tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);@@ -1338,6 +1330,15 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1340
Quoted 10 lines
mm/mmap.c +8
-0tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ +if (mm_is_oom_victim (mm)) { +rcu_barrier (); +mm_flags_set (MMF_OOM_SKIP , mm); + }[Severity: Medium]
Does delayingMMF_OOM_SKIPuntil afterfree_pgtables()andrcu_barrier(), and gating it onmm_is_oom_victim(mm), breakexit_mmap()synchronization withoom_reap_task()andprocess_mrelease()?
oom_reap_task_mm()andoom_reap_task()rely onexit_mmap()settingMMF_OOM_SKIPbefore acquiringmmap_write_lock(mm):mm/oom_kill.c:oom_reap_task_mm() { ... /* * MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't * work on the mm anymore. The check for MMF_OOM_SKIP must run * under mmap_lock for reading because it serializes against the * mmap_write_lock();mmap_write_unlock() cycle in exit_mmap(). */ if (mm_flags_test(MMF_OOM_SKIP, mm)) { trace_skip_task_reaping(tsk->pid); goto out_unlock; } ... }Quoted 5 lines
With
MMF_OOM_SKIPmoved afterfree_pgtables()andrcu_barrier(),exit_mmap()holdsmmap_write_lock(mm)across sleepinganon_vma,i_mmapand RCU barrier waits whileMMF_OOM_SKIPis still clear, even thoughunmap_vmas()andtlb_flush_mmu()have already freed the victim's anonymous pages.Correct
Quoted 4 lines
If
oom_reap_task()runs during this phase,mmap_read_trylock(mm)fails repeatedly andoom_reap_task()findsMMF_OOM_SKIPunset afterMAX_OOM_REAP_RETRIES, emitting false "unable to reap" warnings, task dumps, anddebug_show_all_locks()output.Right. This is likely unnecessary but I would consider it mostly harmless.
debug_show_all_locksis nop withoutCONFIG_LOCKDEPwhich is the case for most production workloads. Dumping the victims stack is more noisy than necessary but I would rather wait for this being a real problem than developing a specific solution for that.Quoted 5 lines
Leaving
MMF_OOM_SKIPunset betweenmmap_read_unlock(mm)andmmap_write_lock(mm)also letsoom_reap_task_mm()grabmmap_read_lock(mm)in that window, walk already-unmapped VMAs while blockingexit_mmap()from startingfree_pgtables(), and setMMF_OOM_SKIPinoom_reap_task()before page tables are freed.Yes. We cannot have both.
oom_reaperis delayed to allow normal victim to finish properly before meddling with it.Quoted 4 lines
In addition, gating
mm_flags_set(MMF_OOM_SKIP, mm)onmm_is_oom_victim(mm)means processes killed from userspace never setMMF_OOM_SKIPinexit_mmap(), breaking theMMF_OOM_SKIPchecks inprocess_mrelease().mm/mmap.c +0
-0
mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1335
Quoted 9 lines
mm/mmap.c +2
-3@@ -1330,10 +1330,9 @@ void exit_mmap(struct mm_struct *mm)* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM * killer will only skip this mm if it's already freed all it can. */ -if (mm_is_oom_victim (mm)) { +if (mm_is_oom_victim (mm))rcu_barrier (); -mm_flags_set (MMF_OOM_SKIP , mm); - } +mm_flags_set (MMF_OOM_SKIP , mm);
Since we don't set the MMF_OOM_SKIP first, doesn't that mean the reaper may continuously find this mm to try-lock, then fail while the rcu_barrier() is running with the mmap_write_lock() and rcu's barrier_mutex?
Quoted 44 lines
mm/mmap.c +0
-0/* * Walk the list again, actually closing and freeing it, with preemption Quoted 8 lines
Quoted 8 lines
mm/oom_kill.c +0
-0@@ -614,6 +614,13 @@ static void oom_reap_task(struct task_struct *tsk) done: tsk->oom_reaper_list =NULL ;Quoted 14 lines
mm/oom_kill.c static void oom_reap_task(struct task_struct *tsk) · line 626
Quoted 10 lines
mm/oom_kill.c +7
-0+/* +* Make sure that pre-exising call_rcu users will get a chance to +* free up memory. This might have been exiting task itself as well +* so call this before we hide the current victim from the oom killer. +*/ +rcu_barrier (); +/* * Hide this mm from OOM killer because it has been either reaped or * somebody can't call mmap_write_unlock(mm). [Severity: Medium]
Canoom_reap_task()andexit_mmap()both run a redundantrcu_barrier()on the same victim whenMMF_OOM_SKIPis already set?They can. Unless I miss something I do not see that as necessarily wrong thing to do. On the
oom_reaperside of things this could slow down operation unnecessarily but this is not a fast path and it should provide a way to ensure we do not allow oom killer to go after another victim while there is memory being freed through rcu.
On theexit_mmapside we are flushing after the victims active contribution to the rcu freed data structures from the page table freeing.So I would say prefer a simpler solution for now.
Let's see whether there is a general agreement with those decisions before I send v3.
Signature · 2 lines
Michal Hocko SUSE Labs
Michal Hocko
maintainerRe: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
On Thu 03-12-26 23:06:05, Liam R. Howlett wrote:
[...]
Quoted 11 lines
Quoted 11 lines
mm/mmap.c +1
-1@@ -1330,10 +1330,9 @@ void exit_mmap(struct mm_struct *mm)* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM * killer will only skip this mm if it's already freed all it can. */ -if (mm_is_oom_victim (mm)) { +if (mm_is_oom_victim (mm))rcu_barrier ();
Quoted 8 lines
mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1335
Quoted 3 lines
mm/mmap.c +1
-2-mm_flags_set (MMF_OOM_SKIP , mm); - } +mm_flags_set (MMF_OOM_SKIP , mm);Since we don't set the
MMF_OOM_SKIPfirst, doesn't that mean the reaper may continuously find this mm to try-lock, then fail while thercu_barrier()is running with themmap_write_lock()and rcu'sbarrier_mutex?
Yes it can but keep in mind that the main point of moving MMF_OOM_SKIP is to delay the next oom victim selection. So this is a desirable behavior. Even if the reaper wins the race manages to set MMF_OOM_SKIP on its own then we are not worse than before.
Signature · 2 lines
Michal Hocko SUSE Labs
Lorenzo Stoakes (ARM)
maintainerRe: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
In reply to Michal HockoOK so for this one I think worth bringing in the big guns, i.e. Paul :)
Quoted 11 lines · Michal Hocko
From: Michal Hocko <[email protected]>
OOM victim could have released quite a lot of memory through
rcu_callpath (e.g. page tables). Callrcu_barrierbefore settingMMF_OOM_SKIPon the victim to wait for those to execute before the oom killer is allowed to pick another victim.Also move
MMF_OOM_SKIPinexit_mmappath after page tables are freed to capture as much memory as possible to be freed. This is safe from the forward progress POV becauseoom_reaperwill run concurrently in case the exit path gets stuck. We are going to see less memory freed
Ah OK sorry I only just read this, but commented below.
How certain are we of this though?
Both calls have no timeout and both take rcu_state.barrier_mutex I think so I fear that actually we _might_ have a forward-progress issue here?
Have you been able to somehow pressure test this? I hate to say it but AI is pretty good at coming up with this kind of thing and iterating on it.
We should definitely tread carefully here anyway.
Quoted 36 lines
by the oom reaper because it cannot tear down page tables directly but that should be acceptable.
Reported-by Chris Mason <[email protected]>Signed-off-by Michal Hocko <[email protected]>--- mm/mmap.c | 19 ++++++++++--------- mm/oom_kill.c | 7 +++++++ 2 files changed, 17 insertions(+), 9 deletions(-)mm/mmap.c +1
-9@@ -1314,19 +1314,11 @@ void exit_mmap(struct mm_struct *mm)/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ +/* Free batched pages during unmap_vmas ASAP for oom victims */ if (mm_is_oom_victim (mm))tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);
mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1332
Quoted 7 lines
mm/mmap.c +4
-0@@ -1334,6 +1326,15 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/
Shouldn't we say this is paired with oom_reap_task(). Is it right to say that Paul? :)
mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1334
Quoted 2 lines
mm/mmap.c +2
-0+if (mm_is_oom_victim (mm)) { +rcu_barrier ();
So this is a fairly heavyweight barrier I think, it waits for _all_ in-flight call_rcu() callbacks to complete.
Reading the rcu_barrier() code briefly suggests it does a _lot_ there.
And this is a super sensitive point - will this always result in forward progress? Could it be significantly delayed?
Are there any lock dependencies that could be problematic?
Quoted 11 lines
mm/mmap.c +3
-0+mm_flags_set (MMF_OOM_SKIP , mm); + } +/* * Walk the list again, actually closing and freeing it, with preemption * enabled, without holding any MM locks besides the unreachable mm/oom_kill.c +0
-0
mm/oom_kill.c static void oom_reap_task(struct task_struct *tsk) · line 636
Quoted 9 lines
mm/oom_kill.c +6
-0@@ -628,6 +628,13 @@ static void oom_reap_task(struct task_struct *tsk) done: tsk->oom_reaper_list =NULL ; +/* +* Make sure that pre-exising call_rcu users will get a chance to +* free up memory. This might have been exiting task itself as well +* so call this before we hide the current victim from the oom killer. +*/ +rcu_barrier ();
Similar comments here. Paul what do you think?
Quoted 7 lines
mm/oom_kill.c +1
-1+/* * Hide this mm from OOM killer because it has been either reaped or * somebody can't call mmap_write_unlock(mm). -- 2.56.1
--
Cheers, Lorenzo
Re: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
Quoted 66 lines · Lorenzo Stoakes (ARM)
OK so for this one I think worth bringing in the big guns, i.e. Paul :)
Quoted 11 lines · Michal Hocko
From: Michal Hocko <[email protected]>
OOM victim could have released quite a lot of memory through
rcu_callpath (e.g. page tables). Callrcu_barrierbefore settingMMF_OOM_SKIPon the victim to wait for those to execute before the oom killer is allowed to pick another victim.Also move
MMF_OOM_SKIPinexit_mmappath after page tables are freed to capture as much memory as possible to be freed. This is safe from the forward progress POV becauseoom_reaperwill run concurrently in case the exit path gets stuck. We are going to see less memory freedAh OK sorry I only just read this, but commented below.
How certain are we of this though?
Both calls have no timeout and both take rcu_state.barrier_mutex I think so I fear that actually we _might_ have a forward-progress issue here?
Have you been able to somehow pressure test this? I hate to say it but AI is pretty good at coming up with this kind of thing and iterating on it.
We should definitely tread carefully here anyway.
Quoted 39 lines
by the oom reaper because it cannot tear down page tables directly but that should be acceptable.
Reported-by Chris Mason <[email protected]>Signed-off-by Michal Hocko <[email protected]>--- mm/mmap.c | 19 ++++++++++--------- mm/oom_kill.c | 7 +++++++ 2 files changed, 17 insertions(+), 9 deletions(-)mm/mmap.c +1
-9@@ -1314,19 +1314,11 @@ void exit_mmap(struct mm_struct *mm)/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ +/* Free batched pages during unmap_vmas ASAP for oom victims */ if (mm_is_oom_victim (mm))tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);@@ -1334,6 +1326,15 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);tlb_finish_mmu (&tlb);
Quoted 7 lines
mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1332
Quoted 4 lines
mm/mmap.c +4
-0+/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ Shouldn't we say this is paired with
oom_reap_task(). Is it right to say that Paul? :)
You could say that an rcu_barrier() is paired with every callback function that it waits for, and also with every call_rcu*() invocation that queued one of those callbacks. I hadn't really ever thought of it this way, but it might well be useful when documenting and analyzing the code.
Quoted 7 lines
mm/mmap.c void exit_mmap(struct mm_struct *mm) · line 1334
Quoted 2 lines
mm/mmap.c +2
-0+if (mm_is_oom_victim (mm)) { +rcu_barrier ();So this is a fairly heavyweight barrier I think, it waits for _all_ in-flight
call_rcu()callbacks to complete.Reading the
rcu_barrier()code briefly suggests it does a _lot_ there.
Oh yes! ;-)
For each and every normal-RCU call_rcu*() callback that has already been queued, it waits for that callback function to complete executing after having been invoked. Among other things, this waiting time might include up to (almost) two normal-RCU grace periods. This waiting time might also include the invocation of millions of RCU callback functions.
These are extremes, but they could happen.
Quoted 2 lines
And this is a super sensitive point - will this always result in forward progress? Could it be significantly delayed?
Normal grace period latencies tend to be in the tens or hundreds of milliseconds. And RCU CPU stall warnings happen when a given grace period extends for more than 21 *seconds*, so long RCU grace periods can happen. On the other hand, grace periods this long are (and should be) treated as bugs.
Quoted 1 line
Are there any lock dependencies that could be problematic?
Given that you are asking this, I am assuming that if this rcu_barrier() gets stuck, reclaim also gets stuck.
You are not allowed to acquire sleeplocks in RCU callback functions, and you are not allowed to hold spinlocks across an rcu_barrier(), so at a high level, no. One theoretical problem would be if RCU allocated memory while doing a grace period, and the call to rcu_barrier() blocked the grace period that its callback functions were in turn waiting on. And there might be something like this that could happen when a CPU was coming online for the very first time, especially if that CPU was a rcu_nocbs CPU, which needs kthreads to be created.
No locks involved, but self-deadlock nevertheless.
So maybe make that rcu_barrier() execute asynchronously? And/or do a synchronize_rcu_expedited(), also asynchronously?
Quoted 14 lines
Quoted 14 lines
mm/mmap.c +3
-0+mm_flags_set (MMF_OOM_SKIP , mm); + } +/* * Walk the list again, actually closing and freeing it, with preemption * enabled, without holding any MM locks besides the unreachable mm/oom_kill.c +0
-0@@ -628,6 +628,13 @@ static void oom_reap_task(struct task_struct *tsk) done: tsk->oom_reaper_list =NULL ;
Quoted 8 lines
mm/oom_kill.c static void oom_reap_task(struct task_struct *tsk) · line 636
Quoted 6 lines
mm/oom_kill.c +6
-0+/* +* Make sure that pre-exising call_rcu users will get a chance to +* free up memory. This might have been exiting task itself as well +* so call this before we hide the current victim from the oom killer. +*/ +rcu_barrier ();Similar comments here. Paul what do you think?
If this can block reclaim, same comments as above.
Thanx, Paul
Quoted 10 lines
Quoted 7 lines
mm/oom_kill.c +1
-1+/* * Hide this mm from OOM killer because it has been either reaped or * somebody can't call mmap_write_unlock(mm). -- 2.56.1
--
Cheers, Lorenzo
Michal Hocko
maintainerRe: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
On Thu 03-12-26 09:39:53, Paul E. McKenney wrote:
[...]
Quoted 8 lines
Quoted 2 lines
And this is a super sensitive point - will this always result in forward progress? Could it be significantly delayed?
Normal grace period latencies tend to be in the tens or hundreds of milliseconds. And RCU CPU stall warnings happen when a given grace period extends for more than 21 *seconds*, so long RCU grace periods can happen. On the other hand, grace periods this long are (and should be) treated as bugs.
Yes, I guess it is expected that this can take a long time. And this particular patch adds it to two places:
- exit_mmap for an oom_victim
- oom_reaper
The former is dying and if that takes longer while it is guaranteed to release its own memory from page tables which are freed through RCU then this is good. We do not even need a guarantee of a fwd progress here.
The latter is more sensitive as it needs the guarantee of fwd progress. Although it doesn't hold any locks explicitly it ensures that the currently selected oom victims will be torn down - either through them exiting or remotely through the reaper. In either case they are declared MMF_OOM_SKIP in the end.
If that takes longer then still not anything really earth shattering as long as this cannot block for unbound amount of time.
Quoted 8 lines
Quoted 1 line
Are there any lock dependencies that could be problematic?
Given that you are asking this, I am assuming that if this
rcu_barrier()gets stuck, reclaim also gets stuck.You are not allowed to acquire sleeplocks in RCU callback functions, and you are not allowed to hold spinlocks across an
rcu_barrier(), so at a high level, no.
Thanks for the confirmation. That was my understanding.
Quoted 8 lines
One theoretical problem would be if RCU allocated
memory while doing a grace period, and the call torcu_barrier()blocked the grace period that its callback functions were in turn waiting on. And there might be something like this that could happen when a CPU was coming online for the very first time, especially if that CPU was arcu_nocbsCPU, which needs kthreads to be created.No locks involved, but self-deadlock nevertheless.
Could you clarify a bit please? So this would be possible only during early boot while hitting OOM because RCU internals would be blocked on the memory allocation which cannot be resolved?
Quoted 1 line
So maybe make that
rcu_barrier()execute asynchronously?
Well the thing is that we need to use it to order MMF_OOM_SKIP setting in the oom_reaper case.
Quoted 2 lines
And/or do a
synchronize_rcu_expedited(), also asynchronously?
As this is mostly a best effort to ensure a lot of memory is not sitting to be freed in rcu callbacks then I would much rather just drop the rcu_barrier from oom_reap_task.
Signature · 2 lines
Michal Hocko SUSE Labs
Re: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
Quoted 20 lines · Michal Hocko
On Thu 03-12-26 09:39:53, Paul E. McKenney wrote:
[...]Quoted 8 lines
Quoted 2 lines
And this is a super sensitive point - will this always result in forward progress? Could it be significantly delayed?
Normal grace period latencies tend to be in the tens or hundreds of milliseconds. And RCU CPU stall warnings happen when a given grace period extends for more than 21 *seconds*, so long RCU grace periods can happen. On the other hand, grace periods this long are (and should be) treated as bugs.
Yes, I guess it is expected that this can take a long time. And this particular patch adds it to two places:
-exit_mmapfor anoom_victim
-oom_reaperThe former is dying and if that takes longer while it is guaranteed to release its own memory from page tables which are freed through RCU then this is good. We do not even need a guarantee of a fwd progress here.
Quoted 7 lines
The latter is more sensitive as it needs the guarantee of fwd progress. Although it doesn't hold any locks explicitly it ensures that the currently selected oom victims will be torn down - either through them exiting or remotely through the reaper. In either case they are declared
MMF_OOM_SKIPin the end.
If that takes longer then still not anything really earth shattering as long as this cannot block for unbound amount of time.
OK, good to know!
Quoted 18 lines
Quoted 8 lines
Quoted 1 line
Are there any lock dependencies that could be problematic?
Given that you are asking this, I am assuming that if this
rcu_barrier()gets stuck, reclaim also gets stuck.You are not allowed to acquire sleeplocks in RCU callback functions, and you are not allowed to hold spinlocks across an
rcu_barrier(), so at a high level, no.Thanks for the confirmation. That was my understanding.
Quoted 7 lines
One theoretical problem would be if RCU allocated
memory while doing a grace period, and the call torcu_barrier()blocked the grace period that its callback functions were in turn waiting on. And there might be something like this that could happen when a CPU was coming online for the very first time, especially if that CPU was arcu_nocbsCPU, which needs kthreads to be created.
Quoted 5 lines
Quoted 1 line
No locks involved, but self-deadlock nevertheless.
Could you clarify a bit please? So this would be possible only during early boot while hitting OOM because RCU internals would be blocked on the memory allocation which cannot be resolved?
Also when bringing a CPU online during runtime, potentially. There are some oddball configurations that bring up only some of the CPUs initially, and bring up the rest later. One way to do this is to have qemu and the kernel have different ideas about the number of CPUs that exist.
And yes, my concern is that RCU grace periods are blocked on reclaim while reclaim blocks on an RCU grace period. But maybe this code is guaranteed to run in its own kthreads or similar?
Either way, I freely confess that I have not traced out an actual failure scenario.
Quoted 4 lines
Quoted 1 line
So maybe make that
rcu_barrier()execute asynchronously?Well the thing is that we need to use it to order
MMF_OOM_SKIPsetting in theoom_reapercase.
OK, that would rule out asynchrony. ;-)
Quoted 6 lines
Quoted 2 lines
And/or do a
synchronize_rcu_expedited(), also asynchronously?As this is mostly a best effort to ensure a lot of memory is not sitting to be freed in rcu callbacks then I would much rather just drop the
rcu_barrierfromoom_reap_task.
The main advantage of doing an rcu_barrier() would be in kernels built with CONFIG_RCU_LAZY=y, in which case rcu_barrier() would "motivate" lazy callbacks, potentially large numbers of them.
On the other hand, RCU does a shrinker_register() in that case, so maybe those lazy callbacks are already covered.
Thanx, Paul
Michal Hocko
maintainerRe: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
Quoted 55 lines · Paul E. McKenney
Quoted 20 lines · Michal Hocko
On Thu 03-12-26 09:39:53, Paul E. McKenney wrote:
[...]Quoted 8 lines
Quoted 2 lines
And this is a super sensitive point - will this always result in forward progress? Could it be significantly delayed?
Normal grace period latencies tend to be in the tens or hundreds of milliseconds. And RCU CPU stall warnings happen when a given grace period extends for more than 21 *seconds*, so long RCU grace periods can happen. On the other hand, grace periods this long are (and should be) treated as bugs.
Yes, I guess it is expected that this can take a long time. And this particular patch adds it to two places:
-exit_mmapfor anoom_victim
-oom_reaperThe former is dying and if that takes longer while it is guaranteed to release its own memory from page tables which are freed through RCU then this is good. We do not even need a guarantee of a fwd progress here.
Quoted 7 lines
The latter is more sensitive as it needs the guarantee of fwd progress. Although it doesn't hold any locks explicitly it ensures that the currently selected oom victims will be torn down - either through them exiting or remotely through the reaper. In either case they are declared
MMF_OOM_SKIPin the end.
If that takes longer then still not anything really earth shattering as long as this cannot block for unbound amount of time.OK, good to know!
Quoted 18 lines
Quoted 8 lines
Quoted 1 line
Are there any lock dependencies that could be problematic?
Given that you are asking this, I am assuming that if this
rcu_barrier()gets stuck, reclaim also gets stuck.You are not allowed to acquire sleeplocks in RCU callback functions, and you are not allowed to hold spinlocks across an
rcu_barrier(), so at a high level, no.Thanks for the confirmation. That was my understanding.
Quoted 7 lines
One theoretical problem would be if RCU allocated
memory while doing a grace period, and the call torcu_barrier()blocked the grace period that its callback functions were in turn waiting on. And there might be something like this that could happen when a CPU was coming online for the very first time, especially if that CPU was arcu_nocbsCPU, which needs kthreads to be created.Quoted 5 lines
Quoted 1 line
No locks involved, but self-deadlock nevertheless.
Could you clarify a bit please? So this would be possible only during early boot while hitting OOM because RCU internals would be blocked on the memory allocation which cannot be resolved?
Quoted 8 lines
Also when bringing a CPU online during runtime, potentially. There are some oddball configurations that bring up only some of the CPUs initially, and bring up the rest later. One way to do this is to have qemu and the kernel have different ideas about the number of CPUs that exist.
And yes, my concern is that RCU grace periods are blocked on reclaim while reclaim blocks on an RCU grace period. But maybe this code is guaranteed to run in its own kthreads or similar?
Yes, oom_reaper itself is running in a dedicated kernel thread. Is that sufficient? I thought we could have an indirect dependency chain
RCU grace period oom_reaper oom_victim
allocates memory [blocked]
looping in reclaim rcu_barrier(); [blocked] MMF_OOM_SKIP
Quoted 17 lines
Either way, I freely confess that I have not traced out an actual failure scenario.
Quoted 4 lines
Quoted 1 line
So maybe make that
rcu_barrier()execute asynchronously?Well the thing is that we need to use it to order
MMF_OOM_SKIPsetting in theoom_reapercase.OK, that would rule out asynchrony. ;-)
Quoted 6 lines
Quoted 2 lines
And/or do a
synchronize_rcu_expedited(), also asynchronously?As this is mostly a best effort to ensure a lot of memory is not sitting to be freed in rcu callbacks then I would much rather just drop the
rcu_barrierfromoom_reap_task.
Quoted 6 lines
The main advantage of doing an
rcu_barrier()would be in kernels built withCONFIG_RCU_LAZY=y, in which casercu_barrier()would "motivate" lazy callbacks, potentially large numbers of them.On the other hand, RCU does a
shrinker_register()in that case, so maybe those lazy callbacks are already covered.
That only involves k[v]free_rcu ones right? So for example page tables wouldn't fall into that category.
Signature · 2 lines
Michal Hocko SUSE Labs
Re: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
Quoted 65 lines · Michal Hocko
Quoted 55 lines · Paul E. McKenney
Quoted 20 lines · Michal Hocko
On Thu 03-12-26 09:39:53, Paul E. McKenney wrote:
[...]Quoted 8 lines
Quoted 2 lines
And this is a super sensitive point - will this always result in forward progress? Could it be significantly delayed?
Normal grace period latencies tend to be in the tens or hundreds of milliseconds. And RCU CPU stall warnings happen when a given grace period extends for more than 21 *seconds*, so long RCU grace periods can happen. On the other hand, grace periods this long are (and should be) treated as bugs.
Yes, I guess it is expected that this can take a long time. And this particular patch adds it to two places:
-exit_mmapfor anoom_victim
-oom_reaperThe former is dying and if that takes longer while it is guaranteed to release its own memory from page tables which are freed through RCU then this is good. We do not even need a guarantee of a fwd progress here.
Quoted 7 lines
The latter is more sensitive as it needs the guarantee of fwd progress. Although it doesn't hold any locks explicitly it ensures that the currently selected oom victims will be torn down - either through them exiting or remotely through the reaper. In either case they are declared
MMF_OOM_SKIPin the end.
If that takes longer then still not anything really earth shattering as long as this cannot block for unbound amount of time.OK, good to know!
Quoted 18 lines
Quoted 8 lines
Quoted 1 line
Are there any lock dependencies that could be problematic?
Given that you are asking this, I am assuming that if this
rcu_barrier()gets stuck, reclaim also gets stuck.You are not allowed to acquire sleeplocks in RCU callback functions, and you are not allowed to hold spinlocks across an
rcu_barrier(), so at a high level, no.Thanks for the confirmation. That was my understanding.
Quoted 7 lines
One theoretical problem would be if RCU allocated
memory while doing a grace period, and the call torcu_barrier()blocked the grace period that its callback functions were in turn waiting on. And there might be something like this that could happen when a CPU was coming online for the very first time, especially if that CPU was arcu_nocbsCPU, which needs kthreads to be created.Quoted 5 lines
Quoted 1 line
No locks involved, but self-deadlock nevertheless.
Could you clarify a bit please? So this would be possible only during early boot while hitting OOM because RCU internals would be blocked on the memory allocation which cannot be resolved?
Quoted 8 lines
Also when bringing a CPU online during runtime, potentially. There are some oddball configurations that bring up only some of the CPUs initially, and bring up the rest later. One way to do this is to have qemu and the kernel have different ideas about the number of CPUs that exist.
And yes, my concern is that RCU grace periods are blocked on reclaim while reclaim blocks on an RCU grace period. But maybe this code is guaranteed to run in its own kthreads or similar?
Quoted 8 lines
Yes,
oom_reaperitself is running in a dedicated kernel thread. Is that sufficient? I thought we could have an indirect dependency chainRCU grace period
oom_reaperoom_victim
allocates memory [blocked]looping in reclaim rcu_barrier(); [blocked] MMF_OOM_SKIP
Good point, RCU would need to do non-blocking allocations to avoid that dependency chain.
Quoted 21 lines
Quoted 21 lines
Either way, I freely confess that I have not traced out an actual failure scenario.
Quoted 4 lines
Quoted 1 line
So maybe make that
rcu_barrier()execute asynchronously?Well the thing is that we need to use it to order
MMF_OOM_SKIPsetting in theoom_reapercase.OK, that would rule out asynchrony. ;-)
Quoted 6 lines
Quoted 2 lines
And/or do a
synchronize_rcu_expedited(), also asynchronously?As this is mostly a best effort to ensure a lot of memory is not sitting to be freed in rcu callbacks then I would much rather just drop the
rcu_barrierfromoom_reap_task.The main advantage of doing an
rcu_barrier()would be in kernels built withCONFIG_RCU_LAZY=y, in which casercu_barrier()would "motivate" lazy callbacks, potentially large numbers of them.
Quoted 5 lines
Quoted 2 lines
On the other hand, RCU does a
shrinker_register()in that case, so maybe those lazy callbacks are already covered.That only involves k[v]free_rcu ones right? So for example page tables wouldn't fall into that category.
This one registers lazy_rcu_shrink_count() and lazy_rcu_shrink_scan() in kernel/rcu/tree_nocb.h, which look to me like they are dealing with lazy callbacks.
Thanx, Paul
Michal Hocko
maintainerRe: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
Quoted 2 lines · Paul E. McKenney
Quoted 1 line · Michal Hocko
On Thu 03-12-26 12:02:00, Paul E. McKenney wrote:
[...]
Quoted 7 lines
Quoted 7 lines
Quoted 3 lines
And yes, my concern is that RCU grace periods are blocked on reclaim while reclaim blocks on an RCU grace period. But maybe this code is guaranteed to run in its own kthreads or similar?
Yes,
oom_reaperitself is running in a dedicated kernel thread. Is that sufficient? I thought we could have an indirect dependency chain
Quoted 8 lines
Quoted 5 lines
RCU grace period
oom_reaperoom_victim
allocates memory [blocked]looping in reclaim rcu_barrier(); [blocked] MMF_OOM_SKIPGood point, RCU would need to do non-blocking allocations to avoid that dependency chain.
Or pre-allocate so that it doesn't block from inside of the grace period.
Anyway, thanks for the insight. I will drop the barrier from the oom_reaper and also the global memory reclaim
https://lore.kernel.org/all/[email protected]/T/#u
Thanks!
Signature · 2 lines
Michal Hocko SUSE Labs
Re: [PATCH v2] mm, oom: add rcu_barrier before hiding victim from the oom killer
Quoted 17 lines · Michal Hocko
Quoted 2 lines · Paul E. McKenney
Quoted 1 line · Michal Hocko
On Thu 03-12-26 12:02:00, Paul E. McKenney wrote:
[...]
Quoted 13 lines
Quoted 12 lines
Quoted 3 lines
And yes, my concern is that RCU grace periods are blocked on reclaim while reclaim blocks on an RCU grace period. But maybe this code is guaranteed to run in its own kthreads or similar?
Yes,
oom_reaperitself is running in a dedicated kernel thread. Is that sufficient? I thought we could have an indirect dependency chainRCU grace period
oom_reaperoom_victim
allocates memory [blocked]looping in reclaim rcu_barrier(); [blocked] MMF_OOM_SKIP
Quoted 5 lines
Quoted 2 lines
Good point, RCU would need to do non-blocking allocations to avoid that dependency chain.
Or pre-allocate so that it doesn't block from inside of the grace period.
I used to do just that, until we encountered systems whose firmware claimed many more CPUs than actually existed, which caused people to complain about the resulting useless RCU kthreads. :-(
As a result, now many allocations happen when given CPU first comes online.
Quoted 3 lines
Anyway, thanks for the insight. I will drop the barrier from the
oom_reaperand also the global memory reclaim
https://lore.kernel.org/all/[email protected]/T/#u
Would another approach be to prevent CPU hotplug during reclaim? Or at least across the rcu_barrier() call? No, that just gets us more opportunities for deadlock between reclaim and CPU hotplug. :-(
Thanx, Paul
Michal Hocko
maintainerPATCH v3 1/1 mm, oom: move MMF_OOM_SKIP after page table releasing in exit_mmap
In reply to Michal HockoFrom: Michal Hocko <[email protected]>
OOM victim could have consumed quite a lot of memory through page tables and those are currently released after we set MMF_OOM_SKIP in the exit_mmap path. If the memory consumed through the address space is not sufficient to recover from the OOM (e.g. most of it is shared memory etc.) then we could go after another oom victim even though page tables could have released enough memory to prevent from that.
Move MMF_OOM_SKIP in exit_mmap path after page tables freeing to capture as much memory as possible to be released. We need to wait for RCU callbacks to see that memory freed.
In order to prevent oom reaper or process_mrelease to stumble over freed page tables they are checking MMF_OOM_SKIP under mmap_lock for read which is synchronized with MMF_OOM_SKIP set under exclusive lock after page tables are freed.
The move is safe from the forward progress POV too because oom_reaper will run concurrently in case the exit path gets stuck and also if RCU callbacks are not making forward progress for whatever reason and it will bail out by setting MMF_OOM_SKIP. Up until exit_mmap takes the exclusive mmap_lock they will cooperate in releasing the address space. We are going to see less memory freed by the oom reaper because it cannot tear down page tables directly but that should be acceptable. Please note that the reaper execution is delayed so the freeing should be typically done the exit path.
--- mm/mmap.c | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-)
Changes
since v1
- restore tlb_flush_mmu after unmap_vmas
since v2
- dropped rcu_barrier from the oom_reaper path as there might be an obscure case when RCU grace period might allocate
https://lore.kernel.org/all/ed6c5f64-7afe-45a2-8d18-e4e1c0052840@paulmck-laptop/T/#u
- set MMF_OOM_SKIP unconditionally in exit_mmap path
- reworded the changelog to better describe the actual problem and explain the coordination and synchronization between exit, process_mrelease and oom_reaper
mm/mmap.c +9 -9
@@ -1314,19 +1314,11 @@ void exit_mmap(struct mm_struct *mm)/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ +/* Free batched pages during unmap_vmas ASAP for oom victims */ if (mm_is_oom_victim (mm))tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);
@@ -1334,6 +1326,14 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ +if (mm_is_oom_victim (mm)) +rcu_barrier (); +mm_flags_set (MMF_OOM_SKIP , mm); +/* * Walk the list again, actually closing and freeing it, with preemption * enabled, without holding any MM locks besides the unreachable
Signature · 1 line
2.56.1
Re: [PATCH v3] mm, oom: move MMF_OOM_SKIP after page table releasing in exit_mmap
Quoted 28 lines · Michal Hocko
From: Michal Hocko <[email protected]>
OOM victim could have consumed quite a lot of memory through page tables and those are currently released after we set
MMF_OOM_SKIPin theexit_mmappath. If the memory consumed through the address space is not sufficient to recover from the OOM (e.g. most of it is shared memory etc.) then we could go after another oom victim even though page tables could have released enough memory to prevent from that.Move
MMF_OOM_SKIPinexit_mmappath after page tables freeing to capture as much memory as possible to be released. We need to wait for RCU callbacks to see that memory freed.In order to prevent oom reaper or
process_mreleaseto stumble over freed page tables they are checkingMMF_OOM_SKIPundermmap_lockfor read which is synchronized withMMF_OOM_SKIPset under exclusive lock after page tables are freed.The move is safe from the forward progress POV too because
oom_reaperwill run concurrently in case the exit path gets stuck and also if RCU callbacks are not making forward progress for whatever reason and it will bail out by settingMMF_OOM_SKIP. Up untilexit_mmaptakes the exclusivemmap_lockthey will cooperate in releasing the address space. We are going to see less memory freed by the oom reaper because it cannot tear down page tables directly but that should be acceptable. Please note that the reaper execution is delayed so the freeing should be typically done the exit path.
Quoted 2 lines
Reported-by Chris Mason <[email protected]>Signed-off-by Michal Hocko <[email protected]>
Nice, lovely to see my RCU page table work coming in useful here :))
Quoted 57 lines
--- mm/mmap.c | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-)Changes
since v1
- restoretlb_flush_mmuafterunmap_vmas
since v2
- droppedrcu_barrierfrom theoom_reaperpath as there might be an obscure case when RCU grace period might allocate
https://lore.kernel.org/all/ed6c5f64-7afe-45a2-8d18-e4e1c0052840@paulmck-laptop/T/#u
- setMMF_OOM_SKIPunconditionally inexit_mmappath
- reworded the changelog to better describe the actual problem and explain the coordination and synchronization between exit,process_mreleaseandoom_reapermm/mmap.c +9
-10@@ -1314,19 +1314,11 @@ void exit_mmap(struct mm_struct *mm)/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */ unmap_vmas (&tlb, &unmap); -/* -* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM -* killer will only skip this mm if it's already freed all it can. -*/ +/* Free batched pages during unmap_vmas ASAP for oom victims */ if (mm_is_oom_victim (mm))tlb_flush_mmu (&tlb);mmap_read_unlock (mm); -/* -* Set MMF_OOM_SKIP to hide this task from the oom killer/reaper -* because the memory has been already unmapped. -*/ -mm_flags_set (MMF_OOM_SKIP , mm);mmap_write_lock (mm); unmap.mm_wr_locked = true;mt_clear_in_rcu (&mm->mm_mt);@@ -1334,6 +1326,14 @@ void exit_mmap(struct mm_struct *mm)free_pgtables (&tlb, &unmap);tlb_finish_mmu (&tlb); +/* +* Free the memory before marking MMF_OOM_SKIP so a re-triggered OOM +* killer will only skip this mm if it's already freed all it can. +*/ +if (mm_is_oom_victim (mm)) +rcu_barrier (); +mm_flags_set (MMF_OOM_SKIP , mm); +/* * Walk the list again, actually closing and freeing it, with preemption * enabled, without holding any MM locks besides the unreachable --
Quoted 2 lines
2.56.1
--
Cheers, Lorenzo
Michal Hocko
maintainerPATCH 10/10 memcg: wake v1 OOM lock contenders on unlock
In reply to Michal HockoFrom: Chris Mason <[email protected]>
With the OOM killer disabled in a cgroup v1 memcg, a lost wakeup can leave a task that contends for the memcg OOM lock asleep indefinitely in mem_cgroup_oom_synchronize(), with no OOM notification sent for it.
Only the task that wins mem_cgroup_oom_trylock() notifies userspace. A task that loses the trylock sleeps without a notification of its own, so the holder has to wake it when the lock is dropped. Commit 18b1d18bc2bd ("memcg, oom: remove explicit wakeup in mem_cgroup_oom_synchronize()") removed that wakeup, because userspace triggers one. But userspace answers the holder's notification, and its wakeup only reaches the tasks that are on memcg_oom_waitq at that time:
holder A contender B
======== ===========
mem_cgroup_oom_trylock()
mem_cgroup_oom_notify()
schedule()
try_charge_memcg() fails
woken by memcg1_oom_recover()
prepare_to_wait() mem_cgroup_oom_trylock() fails schedule()
mem_cgroup_oom_unlock()
The lock covers a subtree, so the holder can also be at an ancestor of the contender's memcg: another waiter, or the OOM killer in the charge path, where memcg1_oom_finish() drops the lock without a wakeup as well. The contender can then sleep on while its memcg is still at the limit, again without a notification of its own.
The fix used here is to wake the contenders from the unlock itself, so that every path that drops the memcg OOM lock wakes them.
Userspace can get one more OOM notification after the holder has left, if the memcg is still at its limit. An OOM kill in the charge path that held the lock now also walks memcg_oom_waitq, which holds the waiters of all memcgs, and is empty on cgroup v2.
--- mm/memcontrol-v1.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
mm/memcontrol-v1.c +7 -2
@@ -81,6 +81,7 @@ static struct lockdep_map memcg_oom_lock_dep_map = {#endif DEFINE_SPINLOCK (memcg_oom_lock); +static DECLARE_WAIT_QUEUE_HEAD (memcg_oom_waitq);static u64 mem_cgroup_move_charge_read (struct cgroup_subsys_state *css,struct cftype *cft)
@@ -958,6 +959,12 @@ static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)for_each_mem_cgroup_tree (iter, memcg) iter->oom_lock = false;spin_unlock (&memcg_oom_lock); + +/* +* A task that lost the trylock sleeps without a notification of its +* own, so nothing but the unlock is sure to wake it. +*/ +__wake_up (&memcg_oom_waitq,TASK_NORMAL ,0 , memcg); }static void mem_cgroup_mark_under_oom (struct mem_cgroup *memcg)
@@ -985,8 +992,6 @@ static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)spin_unlock (&memcg_oom_lock); } -static DECLARE_WAIT_QUEUE_HEAD (memcg_oom_waitq); -struct oom_wait_info {struct mem_cgroup *memcg;wait_queue_entry_t wait;
Signature · 1 line
2.56.1
Quoted 5 lines · Michal Hocko
Hi David,
these are assorted oom related fixes. There is nothing super critical in there but the patch1 is using a potential UAF foroom_disabled(v1 only feature) situations so I've marked it for stable explicitly. All these are based on Chris Mason's reports so thanks for those!
Thanks, likely best for all to go through Andrew's tree. Unless this is 7.6 stuff that you could take through the memcg tree?
Thanks!
Signature · 3 lines
Cheers, David
Michal Hocko
maintainerQuoted 9 lines · David Hildenbrand
Quoted 5 lines · Michal Hocko
Hi David,
these are assorted oom related fixes. There is nothing super critical in there but the patch1 is using a potential UAF foroom_disabled(v1 only feature) situations so I've marked it for stable explicitly. All these are based on Chris Mason's reports so thanks for those!Thanks, likely best for all to go through Andrew's tree. Unless this is 7.6 stuff that you could take through the memcg tree?
I am fine both ways. If we should wait for the next release cycle then take patch 1 at least. That one doesn't have any dependencies so it can go through either your or Andrew's tree.
Signature · 2 lines
Michal Hocko SUSE Labs