Re: [PATCH 3/4] cgroup: Defer task cgroup unlink until after the task is done switching out

Michal Koutný
2025-11-14T17:48:42Z

[-- Attachment #1: Type: text/plain, Size: 2461 bytes --]

On Tue, Oct 28, 2025 at 08:19:17PM -1000, Tejun Heo <tj@kernel.org> wrote:
> When a task exits, css_set_move_task(tsk, cset, NULL, false) unlinks the task
> from its cgroup. From the cgroup's perspective, the task is now gone. If this
> makes the cgroup empty, it can be removed, triggering ->css_offline() callbacks
> that notify controllers the cgroup is going offline resource-wise.
>
> However, the exiting task can still run, perform memory operations, and schedule
> until the final context switch in finish_task_switch().
> This creates a confusing
> situation where controllers are told a cgroup is offline while resource
> activities are still happening in it.

(FWIW, I've always considered it impossible to (mm) charge into offlined
memcgs. Alhtogh I don't remember whether anything _relied_ on that...

> While this hasn't broken existing controllers,

... so hopefully not.)

>
> Split cgroup_task_exit() into two functions. cgroup_task_exit() now only calls
> the subsystem exit callbacks and continues to be called from do_exit(). The
> css_set cleanup is moved to the new cgroup_task_dead() which is called from
> finish_task_switch() after the final context switch, so that the cgroup only
> appears empty after the task is truly done running.
>
> This also reorders operations so that subsys->exit() is now called before
> unlinking from the cgroup, which shouldn't break anything.
>
> Cc: Dan Schatzberg <dschatzberg@meta.com>
> Cc: Peter Zijlstra <peterz@infradead.org>
> Signed-off-by: Tejun Heo <tj@kernel.org>
> ---
> include/linux/cgroup.h | 2 ++
> kernel/cgroup/cgroup.c | 23 ++++++++++++++---------
> kernel/sched/core.c | 2 ++
> 3 files changed, 18 insertions(+), 9 deletions(-)

Acked-by: Michal Koutný <mkoutny@suse.com>

>
> diff --git a/include/linux/cgroup.h b/include/linux/cgroup.h
> index 4068035176c4..bc892e3b37ee 100644
> --- a/include/linux/cgroup.h
> +++ b/include/linux/cgroup.h
> @@ -138,6 +138,7 @@ extern void cgroup_cancel_fork(struct task_struct *p,
> extern void cgroup_post_fork(struct task_struct *p,
> struct kernel_clone_args *kargs);
> void cgroup_task_exit(struct task_struct *p);
> +void cgroup_task_dead(struct task_struct *p);
> void cgroup_task_release(struct task_struct *p);
> void cgroup_task_free(struct task_struct *p);

"Hi, I'm four-stage process, you may remember me such callbacks as
css_killed and css_release."

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 265 bytes --]