Linux-mm Archive on lore.kernel.org
 help / color / mirror / Atom feed
From: Shakeel Butt <shakeel.butt@linux.dev>
To: Tejun Heo <tj@kernel.org>
Cc: Andrew Morton <akpm@linux-foundation.org>,
	Johannes Weiner <hannes@cmpxchg.org>,
	Michal Koutny <mkoutny@suse.com>,
	Michal Hocko <mhocko@kernel.org>,
	Roman Gushchin <roman.gushchin@linux.dev>,
	Christian Brauner <brauner@kernel.org>,
	Oleg Nesterov <oleg@redhat.com>,
	Sebastian Andrzej Siewior <bigeasy@linutronix.de>,
	Suren Baghdasaryan <surenb@google.com>,
	"T . J . Mercier" <tjmercier@google.com>,
	Usama Arif <usama.arif@linux.dev>,
	Meta kernel team <kernel-team@meta.com>,
	cgroups@vger.kernel.org, linux-mm@kvack.org,
	linux-kernel@vger.kernel.org
Subject: [PATCH 8/9] cgroup: don't hold cgroup_mutex for cgroup.kill
Date: Sun, 29 Nov 2026 10:35:23 -0800	[thread overview]
Message-ID: <20261129183524.1052436-9-shakeel.butt@linux.dev> (raw)
In-Reply-To: <20261129183524.1052436-1-shakeel.butt@linux.dev>

cgroup.kill holds cgroup_mutex while it signals every task in the subtree.
It is often used when the system is already in trouble, so it should not
wait for other cgroup operations, and they should not wait for it.

cgroup_mutex kept the cgroup and its subtree stable, and blocked
migrations, CLONE_INTO_CGROUP forks and switches to threaded during the
kill. Replace it:

 - Pin the cgroup with cgroup_kn_break_active(), which also drops the
   kernfs active reference so that rmdir doesn't wait for the kill. rmdir
   can now remove the cgroup during the kill. The reference keeps the
   cgroup in memory, the walk skips removed cgroups, and kernfs lets the
   write outlive the removal of its file. Commit 071d8e4c2a3b ("kernfs:
   Relax constraint in draining guard") removed a warning that this
   overlap could trigger. Walk the subtree under RCU, pin each cgroup
   while its tasks are killed, and skip empty subtrees.

 - Count the running kills in the top cgroup (nr_subtree_kills). When a
   task leaves a css_set in a subtree being killed,
   cgroup_migrate_execute() kills it. This covers moves out of the
   subtree, moves inside it, and css_set changes from controller changes.
   Tasks that move in are left alone. A global count of running kills
   lets migrations skip the check when no kill runs.

 - Kill a CLONE_INTO_CGROUP child if its parent's subtree was being killed
   at any time during the fork.

 - Several kills can now walk one cgroup at once. Instead of an odd
   kill_seq, bump it when a walk starts and when it ends, and count the
   walks in nr_killing.

 - Only an empty cgroup can switch to threaded, but threads from outside
   could join it while a kill of it still runs, and the checks above
   would kill their whole process. Make the kill and the switch exclude
   each other with a CGRP_THREADED flag that changes under css_set_lock:
   the switch fails with EBUSY while the cgroup is being killed, and
   cgroup.kill fails with EOPNOTSUPP once a switch has started.
   cgroup.kill checks for a removed cgroup in the same section.

Document that a process moved out of the tree or inside it during a kill
is killed, that a process moved in may or may not be, and the new EBUSY.

Tested in a VM, with sleeps added by a debug patch that is not part of
this series. Tasks moved inside or out of the subtree, and a
CLONE_INTO_CGROUP child of a task in it, all died. With the matching check
turned off, they survived. A switch to threaded during a kill failed with
EBUSY. With that check turned off, an outside thread that joined and
created a thread took its whole process down. The test_kill and test_core
selftests pass with lockdep on.

Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 Documentation/admin-guide/cgroup-v2.rst |   9 +-
 include/linux/cgroup-defs.h             |  18 ++-
 include/linux/sched/task.h              |   1 +
 kernel/cgroup/cgroup.c                  | 199 +++++++++++++++++++-----
 4 files changed, 187 insertions(+), 40 deletions(-)

diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst
index 2f792ff29425..a56903eba69b 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -1057,11 +1057,16 @@ All cgroup core files are prefixed with "cgroup."
 	tree will be killed via SIGKILL.
 
 	Killing a cgroup tree will deal with concurrent forks appropriately and
-	is protected against migrations.
+	is protected against migrations: a process that is moved out of the
+	tree, or between its cgroups, while the tree is being killed is killed
+	as well.  A process that is moved into the tree, or created in it with
+	CLONE_INTO_CGROUP from outside, while the tree is being killed may or
+	may not be killed.
 
 	In a threaded cgroup, writing this file fails with EOPNOTSUPP as
 	killing cgroups is a process directed operation, i.e. it affects
-	the whole thread-group.
+	the whole thread-group.  Writing "threaded" to "cgroup.type" fails
+	with EBUSY while the cgroup is being killed.
 
   cgroup.pressure
 	A read-write single value file that allowed values are "0" and "1".
diff --git a/include/linux/cgroup-defs.h b/include/linux/cgroup-defs.h
index 0dae54b033e9..e06c5384be1d 100644
--- a/include/linux/cgroup-defs.h
+++ b/include/linux/cgroup-defs.h
@@ -72,6 +72,13 @@ enum {
 
 	/* Cgroup is frozen. */
 	CGRP_FROZEN,
+
+	/*
+	 * cgroup.type is threaded or is being switched to threaded.  Changed
+	 * under css_set_lock, so that a kill of the cgroup and a switch to
+	 * threaded exclude each other, see cgroup_enable_threaded().
+	 */
+	CGRP_THREADED,
 };
 
 /* cgroup_root->flags */
@@ -528,11 +535,16 @@ struct cgroup {
 	int nr_threaded_children;	/* # of live threaded child cgroups */
 
 	/*
-	 * Sequence number for cgroup.kill, odd while a kill is walking the
-	 * cgroup's tasks. Incremented with both cgroup_mutex and css_set_lock
-	 * held. Readers hold either one.
+	 * cgroup.kill state, protected by css_set_lock.  A kill bumps
+	 * kill_seq when it starts and when it ends walking this cgroup's
+	 * tasks, and nr_killing counts such walks in progress.
+	 * subtree_kill_seq and nr_subtree_kills do the same for whole kills
+	 * of the subtree rooted here.  See cgroup_kill().
 	 */
 	unsigned int kill_seq;
+	unsigned int nr_killing;
+	unsigned int subtree_kill_seq;
+	unsigned int nr_subtree_kills;
 
 	struct kernfs_node *kn;		/* cgroup kernfs entry */
 	struct cgroup_file procs_file;	/* handle for "cgroup.procs" */
diff --git a/include/linux/sched/task.h b/include/linux/sched/task.h
index 90ed5bc3c7af..bc1c17fcafea 100644
--- a/include/linux/sched/task.h
+++ b/include/linux/sched/task.h
@@ -45,6 +45,7 @@ struct kernel_clone_args {
 	struct cgroup *cgrp;
 	struct css_set *cset;
 	unsigned int kill_seq;
+	unsigned int subtree_kill_seq;
 };
 
 /*
diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c
index e16595905edf..d3407064b07b 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -2606,6 +2606,35 @@ void cgroup_attach_unlock(enum cgroup_attach_lock_mode lock_mode,
 	cpus_read_unlock();
 }
 
+/* cgroup.kill writes in progress, protected by css_set_lock */
+static unsigned int cgroup_nr_kills;
+
+/**
+ * cgroup_subtree_kill_seq - sample the cgroup.kill state of a cgroup's subtrees
+ * @cgrp: cgroup of interest
+ * @killing: if not %NULL, set to %true if a kill of @cgrp's subtree or of an
+ *	     ancestor's subtree is in progress
+ *
+ * Returns a value that changes whenever such a kill starts or ends.  The root
+ * can't be killed.
+ */
+static unsigned int cgroup_subtree_kill_seq(struct cgroup *cgrp, bool *killing)
+{
+	unsigned int seq = 0;
+	int i;
+
+	lockdep_assert_held(&css_set_lock);
+
+	for (i = cgrp->level; i > 0; i--) {
+		struct cgroup *anc = cgrp->ancestors[i];
+
+		seq += anc->subtree_kill_seq;
+		if (killing && anc->nr_subtree_kills)
+			*killing = true;
+	}
+	return seq;
+}
+
 /**
  * cgroup_migrate_add_task - add a migration target task to a migration context
  * @task: target task
@@ -2787,10 +2816,19 @@ static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
 	 */
 	spin_lock_irq(&css_set_lock);
 	list_for_each_entry(cset, &tset->src_csets, mg_node) {
+		bool kill = false;
+
+		/* don't let tasks out of a subtree being killed, see cgroup_kill() */
+		if (cgroup_nr_kills)
+			cgroup_subtree_kill_seq(cset->dfl_cgrp, &kill);
+
 		list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
 			struct css_set *from_cset = task_css_set(task);
 			struct css_set *to_cset = cset->mg_dst_cset;
 
+			if (unlikely(kill) && !(task->flags & PF_KTHREAD))
+				send_sig(SIGKILL, task, 0);
+
 			get_css_set(to_cset);
 			to_cset->nr_tasks++;
 			css_set_move_task(task, from_cset, to_cset, true);
@@ -3781,6 +3819,20 @@ static int cgroup_enable_threaded(struct cgroup *cgrp)
 	    !cgroup_can_be_thread_root(dom_cgrp))
 		return -EOPNOTSUPP;
 
+	/*
+	 * cgroup.kill doesn't hold cgroup_mutex.  Threads that join @cgrp
+	 * after the switch could be killed with their whole process by a kill
+	 * of @cgrp that is still running, so don't switch during such a kill.
+	 * Set the flag now, so that new kills of @cgrp fail, see cgroup_kill().
+	 */
+	spin_lock_irq(&css_set_lock);
+	if (cgrp->nr_subtree_kills) {
+		spin_unlock_irq(&css_set_lock);
+		return -EBUSY;
+	}
+	set_bit(CGRP_THREADED, &cgrp->flags);
+	spin_unlock_irq(&css_set_lock);
+
 	/*
 	 * The following shouldn't cause actual migrations and should
 	 * always succeed.
@@ -3796,6 +3848,12 @@ static int cgroup_enable_threaded(struct cgroup *cgrp)
 		parent->nr_threaded_children++;
 
 	cgroup_finalize_control(cgrp, ret);
+
+	if (ret) {
+		spin_lock_irq(&css_set_lock);
+		clear_bit(CGRP_THREADED, &cgrp->flags);
+		spin_unlock_irq(&css_set_lock);
+	}
 	return ret;
 }
 
@@ -4320,18 +4378,16 @@ static void __cgroup_kill(struct cgroup *cgrp)
 	struct css_task_iter it;
 	struct task_struct *task;
 
-	lockdep_assert_held(&cgroup_mutex);
-
 	/*
-	 * kill_seq is odd while this walk is in progress.  The walk can signal
-	 * a forking parent after copy_process() passed its
-	 * fatal_signal_pending() check, and can pass the parent before the
-	 * child is linked.  cgroup_post_fork() therefore kills the child if
-	 * kill_seq was odd when cgroup_css_set_fork() sampled it, or if it
-	 * changed since.
+	 * The walk below can signal a forking parent after copy_process()
+	 * passed its fatal_signal_pending() check, and can pass the parent
+	 * before the child is linked.  cgroup_post_fork() kills a child that
+	 * is linked while a walk is in progress (nr_killing), or after one
+	 * started or ended since cgroup_css_set_fork() sampled kill_seq.
 	 */
 	spin_lock_irq(&css_set_lock);
 	cgrp->kill_seq++;
+	cgrp->nr_killing++;
 	spin_unlock_irq(&css_set_lock);
 
 	css_task_iter_start(&cgrp->self, CSS_TASK_ITER_THREADED, &it);
@@ -4350,18 +4406,78 @@ static void __cgroup_kill(struct cgroup *cgrp)
 
 	spin_lock_irq(&css_set_lock);
 	cgrp->kill_seq++;
+	cgrp->nr_killing--;
 	spin_unlock_irq(&css_set_lock);
 }
 
-static void cgroup_kill(struct cgroup *cgrp)
+/*
+ * cgroup.kill doesn't hold cgroup_mutex, so tasks can migrate, the subtree can
+ * grow and CLONE_INTO_CGROUP forks can run while it walks.  Tasks that are in
+ * the subtree when the kill starts (nr_subtree_kills raised) can't get out:
+ *
+ * - a regular fork links the child next to the parent, see __cgroup_kill();
+ * - cgroup_migrate_execute() kills a task leaving a css_set of a cgroup in the
+ *   subtree, which covers moves out of the subtree, moves between its cgroups
+ *   and css_set changes from controller changes;
+ * - cgroup_post_fork() kills a CLONE_INTO_CGROUP child whose parent is in the
+ *   subtree while it is being killed.
+ *
+ * Tasks that join the subtree from outside after the kill started may or may
+ * not be killed.
+ *
+ * Killing is a process directed operation, i.e. the whole thread-group is
+ * taken down, so act like we do for cgroup.procs and refuse threaded cgroups.
+ * A cgroup can't switch to threaded while it is being killed, see
+ * cgroup_enable_threaded(), so every process with a thread in the subtree is
+ * entirely inside it.
+ */
+static int cgroup_kill(struct cgroup *cgrp)
 {
 	struct cgroup_subsys_state *css;
-	struct cgroup *dsct;
+	int ret = 0;
 
-	lockdep_assert_held(&cgroup_mutex);
+	spin_lock_irq(&css_set_lock);
+	if (cgroup_is_dead(cgrp))
+		ret = -ENODEV;
+	else if (test_bit(CGRP_THREADED, &cgrp->flags))
+		ret = -EOPNOTSUPP;
+	if (ret) {
+		spin_unlock_irq(&css_set_lock);
+		return ret;
+	}
+	cgrp->subtree_kill_seq++;
+	cgrp->nr_subtree_kills++;
+	cgroup_nr_kills++;
+	spin_unlock_irq(&css_set_lock);
+
+	rcu_read_lock();
+	css_for_each_descendant_pre(css, &cgrp->self) {
+		/*
+		 * A task that enters an empty subtree later comes from
+		 * outside, or from the part being killed and is killed then.
+		 */
+		if (!cgroup_is_populated(css->cgroup)) {
+			css = css_rightmost_descendant(css);
+			continue;
+		}
+		if (!css_tryget_online(css))
+			continue;
+		rcu_read_unlock();
 
-	cgroup_for_each_live_descendant_pre(dsct, css, cgrp)
-		__cgroup_kill(dsct);
+		__cgroup_kill(css->cgroup);
+		cond_resched();
+
+		rcu_read_lock();
+		css_put(css);
+	}
+	rcu_read_unlock();
+
+	spin_lock_irq(&css_set_lock);
+	cgrp->subtree_kill_seq++;
+	cgrp->nr_subtree_kills--;
+	cgroup_nr_kills--;
+	spin_unlock_irq(&css_set_lock);
+	return 0;
 }
 
 static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf,
@@ -4378,21 +4494,17 @@ static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf,
 	if (kill != 1)
 		return -ERANGE;
 
-	cgrp = cgroup_kn_lock_live(of->kn, false);
+	/*
+	 * No cgroup_mutex, see cgroup_kill().  Still drop the active
+	 * reference, so that removing the cgroup doesn't wait for a long walk.
+	 */
+	cgrp = cgroup_kn_break_active(of->kn);
 	if (IS_ERR(cgrp))
 		return PTR_ERR(cgrp);
 
-	/*
-	 * Killing is a process directed operation, i.e. the whole thread-group
-	 * is taken down so act like we do for cgroup.procs and only make this
-	 * writable in non-threaded cgroups.
-	 */
-	if (cgroup_is_threaded(cgrp))
-		ret = -EOPNOTSUPP;
-	else
-		cgroup_kill(cgrp);
+	ret = cgroup_kill(cgrp);
 
-	cgroup_kn_unlock(of->kn);
+	cgroup_kn_unbreak_active(of->kn, cgrp);
 
 	return ret ?: nbytes;
 }
@@ -7041,9 +7153,18 @@ static int cgroup_css_set_fork(struct kernel_clone_args *kargs)
 		goto err;
 	}
 
+	/*
+	 * cgroup.kill doesn't hold cgroup_mutex.  Sample the target, which the
+	 * child joins, and the subtrees containing the parent, which the child
+	 * leaves, see cgroup_post_fork().
+	 */
+	spin_lock_irq(&css_set_lock);
+	kargs->kill_seq = dst_cgrp->kill_seq;
+	kargs->subtree_kill_seq = cgroup_subtree_kill_seq(cset->dfl_cgrp, NULL);
+	spin_unlock_irq(&css_set_lock);
+
 	put_css_set(cset);
 	kargs->cgrp = dst_cgrp;
-	kargs->kill_seq = dst_cgrp->kill_seq;
 	return ret;
 
 err:
@@ -7165,7 +7286,7 @@ void cgroup_post_fork(struct task_struct *child,
 {
 	unsigned int cgrp_kill_seq = 0;
 	unsigned long cgrp_flags = 0;
-	bool kill = false;
+	bool kill = false, killing = false;
 	struct cgroup_subsys *ss;
 	struct css_set *cset;
 	int i;
@@ -7177,13 +7298,22 @@ void cgroup_post_fork(struct task_struct *child,
 
 	/* init tasks are special, only link regular threads */
 	if (likely(child->pid)) {
-		if (kargs->cgrp) {
-			cgrp_flags = kargs->cgrp->flags;
-			cgrp_kill_seq = kargs->cgrp->kill_seq;
-		} else {
-			cgrp_flags = cset->dfl_cgrp->flags;
-			cgrp_kill_seq = cset->dfl_cgrp->kill_seq;
-		}
+		struct cgroup *cgrp = kargs->cgrp ?: cset->dfl_cgrp;
+
+		cgrp_flags = cgrp->flags;
+		cgrp_kill_seq = cgrp->kill_seq;
+		killing = cgrp->nr_killing;
+
+		/*
+		 * A CLONE_INTO_CGROUP child leaves the parent's cgroup.  Don't
+		 * let it out of a subtree that was being killed at any time
+		 * during the fork.  @current's cgroup is pinned by the
+		 * threadgroup lock.
+		 */
+		if (kargs->cgrp &&
+		    cgroup_subtree_kill_seq(task_dfl_cgroup(current),
+					    &killing) != kargs->subtree_kill_seq)
+			killing = true;
 
 		WARN_ON_ONCE(!list_empty(&child->cg_list));
 		cset->nr_tasks++;
@@ -7218,8 +7348,7 @@ void cgroup_post_fork(struct task_struct *child,
 		 * child down right after we finished preparing it for
 		 * userspace.
 		 */
-		kill = kargs->kill_seq != cgrp_kill_seq ||
-		       (kargs->kill_seq & 1);
+		kill = killing || kargs->kill_seq != cgrp_kill_seq;
 	}
 
 	spin_unlock_irq(&css_set_lock);
-- 
2.53.1-Meta



  parent reply	other threads:[~2026-11-29 18:36 UTC|newest]

Thread overview: 10+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-29 18:35 [PATCH 0/9] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
2026-11-29 18:35 ` [PATCH 1/9] cgroup: kill a child forked while cgroup.kill runs Shakeel Butt
2026-11-29 18:35 ` [PATCH 2/9] cgroup/freezer: check own tasks and descendants for the frozen state Shakeel Butt
2026-11-29 18:35 ` [PATCH 3/9] cgroup/freezer: don't update the frozen state of removed cgroups Shakeel Butt
2026-11-29 18:35 ` [PATCH 4/9] cgroup/freezer: test the freeze trap bit under siglock Shakeel Butt
2026-11-29 18:35 ` [PATCH 5/9] selftests/cgroup: test the frozen state of a cgroup with tasks and children Shakeel Butt
2026-11-29 18:35 ` [PATCH 6/9] selftests/cgroup: test cgroup.kill in a threaded cgroup Shakeel Butt
2026-11-29 18:35 ` [PATCH 7/9] cgroup: factor out cgroup_kn_break_active() and cgroup_kn_unbreak_active() Shakeel Butt
2026-11-29 18:35 ` Shakeel Butt [this message]
2026-11-29 18:35 ` [PATCH 9/9] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze Shakeel Butt

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261129183524.1052436-9-shakeel.butt@linux.dev \
    --to=shakeel.butt@linux.dev \
    --cc=akpm@linux-foundation.org \
    --cc=bigeasy@linutronix.de \
    --cc=brauner@kernel.org \
    --cc=cgroups@vger.kernel.org \
    --cc=hannes@cmpxchg.org \
    --cc=kernel-team@meta.com \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-mm@kvack.org \
    --cc=mhocko@kernel.org \
    --cc=mkoutny@suse.com \
    --cc=oleg@redhat.com \
    --cc=roman.gushchin@linux.dev \
    --cc=surenb@google.com \
    --cc=tj@kernel.org \
    --cc=tjmercier@google.com \
    --cc=usama.arif@linux.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox