Linux cgroups development
 help / color / mirror / Atom feed
* [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze
@ 2026-11-30 17:34 Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 01/11] cgroup: don't lose a task in css_task_iter when a migration fails Shakeel Butt
                   ` (10 more replies)
  0 siblings, 11 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel

cgroup.kill and cgroup.freeze take cgroup_mutex and hold it while they
walk every task of the subtree. cgroup.kill is how userspace OOM
killers, service managers and container runtimes stop a workload, often
when the system is already under pressure. Waiting for cgroup_mutex
makes the kill as slow as the slowest cgroup operation on the machine.

In the Meta fleet:

 - Over the last ten days we recorded several hung-task reports of
   tasks blocked for more than 120 seconds in cgroup_kill_write(),
   waiting for cgroup_mutex. The writers were systemd, two userspace OOM
   killers (oomd and systemd-oomd), buck2 (a build system) and our
   container agent.

 - In the reports that named the mutex owner, the owner was a
   mkdir or rmdir that was itself waiting for kernfs_rwsem to add or
   remove cgroup files. Two more were a mkdir reclaiming memory while it
   allocated memcg state.

 - Over four weeks, a D-state sampler saw cgroup.kill writers waiting
   for cgroup_mutex for up to 61 minutes.

There is work to shorten the kernfs_rwsem waits, but cgroup.kill doesn't
need cgroup_mutex in the first place. It needs every task that is in the
subtree when the kill starts to get SIGKILL, including tasks that fork
or move while the kill runs. This series keeps that guarantee without
cgroup_mutex, and moves cgroup.freeze off cgroup_mutex as well. After
it, these writes don't wait for other cgroup operations (a freeze write
only waits for other freeze writes), and other cgroup operations don't
wait for a kill or freeze walk.

Patches 1-5 fix bugs found while auditing these paths and in the review
of v1. They don't depend on the rest and can be taken first. Patches 1-4
are tagged for stable; patch 4 needs patch 3.

 1. A failed migration can make a task walk miss a task that never left
    the cgroup, for example a cgroup.procs reader.
 2. A child forked while cgroup.kill walks its parent's cgroup can
    survive the kill.
 3. A cgroup with its own tasks and child cgroups reports frozen=1 while
    part of its subtree still runs, and can stay frozen=1 after a thaw.
 4. rmdir of a cgroup whose last task is still exiting breaks the
    ancestors' frozen counts, so they can stop reporting frozen=1.
 5. cgroup_leave_frozen() tests the freeze trap bit without siglock.

Patches 6 and 7 add selftests for bugs 1 and 3, and patch 8 a selftest
for cgroup.kill in threaded cgroups, which must keep working. Patch 9
splits the kernfs active reference handling out of
cgroup_kn_lock_live(). Patch 10 moves cgroup.kill off cgroup_mutex and
patch 11 does the same for cgroup.freeze. Both walks rely on patch 1.

Without cgroup_mutex, cgroup.kill (patch 10) keeps its guarantees this
way:

 - Fork: a child forked while a walk runs is killed, as in patch 2, with
   counters so that several walks can overlap.
 - Migration: a task that leaves a cgroup in a subtree being killed is
   killed when the move commits, so moves out of the tree and inside it
   can't escape. It is killed the way the walk would kill it: a pid
   namespace init is spared only if the cgroup.kill writer is inside its
   pid namespace. A task that moves in from outside may or may not be
   killed; it arrived after the kill started.
 - CLONE_INTO_CGROUP: a child placed outside the subtree by a parent
   inside it is killed.
 - Threaded cgroups: a cgroup can't switch to threaded while it is being
   killed. Otherwise a thread from outside could join it, and killing
   that thread would kill its whole process. A cgroup must be empty to
   switch, and cgroup.kill returns right away for an empty tree.

Three behaviours change, and patch 10 documents them:

 - A process moved out of a tree while the tree is being killed now gets
   SIGKILL during the move. Before, the move waited until the kill was
   done.
 - A process in the tree that creates a child outside it with
   CLONE_INTO_CGROUP gets a child that is killed right away. Before, the
   fork waited until the kill was done, and then failed.
 - Writing "threaded" to cgroup.type fails with EBUSY while the cgroup
   is being killed. Before, it waited until the kill was done. The
   cgroup has to be empty to switch, so this needs a kill and a switch
   that run at the same time.

cgroup.freeze (patch 11) gets a mutex of its own for writers. New
cgroups inherit the freeze state under css_set_lock. The walk sets the
new state of every cgroup in the tree before it walks the tasks, and
each task is set to the state of the cgroup it is in at that moment.

Testing, in an 8 CPU VM with lockdep:

 - reproducers for bugs 1-4: 1, 3 and 4 need no kernel changes, 2 needs
   a sleep added by a debug patch. Bug 5 was found by reading the code.
   The selftests in patches 6 and 7 fail without patches 1 and 3;
 - Tejun's reproducers from the review of v1 pass;
 - race tests that widen each new window with sleeps from the same debug
   patch, including migrations that fail and pid namespace inits that
   move. Each passes, and fails with its protection turned off;
 - a random stress test (freeze, kill, migrations that succeed and fail,
   fork, clone3, pid namespace inits, mkdir and rmdir), followed by
   checks that the tree freezes and empties;
 - the test_freezer, test_kill and test_core selftests;
 - KCSAN in strict mode, with no reports in the changed code.

Changes since v1, all from Tejun's review:
 - New patch 1: a failed migration could make the kill and freeze walks
   skip a task. The bug is in css_task_iter and mainline has it since
   5ee01f1a7343, so it is a separate fix for stable, with a selftest
   (patch 6).
 - Patch 10: a task that leaves a tree being killed is killed the way
   the walk would kill it, so the cgroup.kill writer's pid namespace
   decides whether a pid namespace init dies.
 - Patch 10: cgroup.kill returns 0 right away for an empty tree, and
   CGRP_THREADED is set only when a switch to threaded succeeds, so a
   switch that fails can't make cgroup.kill fail with EOPNOTSUPP.
 - Patch 10: document the CLONE_INTO_CGROUP case.
 - Patch 11: set the state of the whole tree before walking the tasks,
   so a frozen task moved ahead of the walk doesn't run again.
 - Patch 4: the stable tag names patch 3.
 - Rebased on cgroup/for-next 7da6eb0e0177.

v1: https://lore.kernel.org/r/20261129183524.1052436-1-shakeel.butt@linux.dev

Shakeel Butt (11):
  cgroup: don't lose a task in css_task_iter when a migration fails
  cgroup: kill a child forked while cgroup.kill runs
  cgroup/freezer: check own tasks and descendants for the frozen state
  cgroup/freezer: don't update the frozen state of removed cgroups
  cgroup/freezer: test the freeze trap bit under siglock
  selftests/cgroup: test cgroup.procs reads across a failed migration
  selftests/cgroup: test the frozen state of a cgroup with tasks and
    children
  selftests/cgroup: test cgroup.kill in a threaded cgroup
  cgroup: factor out cgroup_kn_break_active() and
    cgroup_kn_unbreak_active()
  cgroup: don't hold cgroup_mutex for cgroup.kill
  cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze

 Documentation/admin-guide/cgroup-v2.rst       |  10 +-
 include/linux/cgroup-defs.h                   |  24 +-
 include/linux/cgroup.h                        |   4 +-
 include/linux/sched/task.h                    |   1 +
 kernel/cgroup/cgroup.c                        | 425 ++++++++++++++----
 kernel/cgroup/freezer.c                       | 232 ++++++----
 tools/testing/selftests/cgroup/test_core.c    | 154 +++++++
 tools/testing/selftests/cgroup/test_freezer.c | 105 +++++
 tools/testing/selftests/cgroup/test_kill.c    |  68 +++
 9 files changed, 857 insertions(+), 166 deletions(-)


base-commit: 7da6eb0e0177edff74d288f94511fa55155d8477
-- 
2.53.1-Meta


^ permalink raw reply	[flat|nested] 12+ messages in thread

* [PATCH v2 01/11] cgroup: don't lose a task in css_task_iter when a migration fails
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 02/11] cgroup: kill a child forked while cgroup.kill runs Shakeel Butt
                   ` (9 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel,
	Qingye Zhao, stable

A cgroup.procs reader can miss a process that never left the cgroup.
With processes 148, 150 and 151 in src:

  read one byte of src/cgroup.procs
  echo 151 > empty/cgroup.procs        fails with ENOSPC
  read the rest                        "148 150", 151 is missing

Since commit 5ee01f1a7343 ("cgroup: fix race between task migration and
iteration"), cgroup_migrate_add_task() skips an iterator past a task
before it moves the task to mg_tasks. If the task was the last one on
->tasks, the iterator stops at the head of ->tasks and goes to mg_tasks
next. If the migration then fails, out_release_tset splices mg_tasks
back onto the tail of ->tasks. The iterator finds mg_tasks empty and
moves on to the next css_set, so it never returns the task.

Any task walk that doesn't hold cgroup_mutex can miss a task this way.
cgroup.procs reads are the easiest case, because they keep the iterator
between reads. A ->can_attach() callback can fail the migration, for
example cpuset's for a cgroup without CPUs.

Point such an iterator at the first task that is moved back. The
iterator can then return a task twice, which a migration to a css_set
it hasn't walked yet can already cause.

The selftest added later in this series fails without this patch.

Fixes: 5ee01f1a7343 ("cgroup: fix race between task migration and iteration")
Reported-by: Tejun Heo <tj@kernel.org>
Closes: https://lore.kernel.org/r/a6553d7921f3f47b7b890bfd232de644@kernel.org
Cc: Qingye Zhao <zhaoqingye@honor.com>
Cc: stable@vger.kernel.org
Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 kernel/cgroup/cgroup.c | 31 ++++++++++++++++++++++++++++++-
 1 file changed, 30 insertions(+), 1 deletion(-)

diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c
index f6df19241772..a5a7395dc5b8 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -865,6 +865,35 @@ static void css_set_skip_task_iters(struct css_set *cset,
 		css_task_iter_skip(it, task);
 }
 
+/**
+ * css_set_splice_mg_tasks - move the tasks on a css_set's mg_tasks to its tasks
+ * @cset: css_set of interest
+ *
+ * The tasks go to the tail of @cset->tasks.  An iterator that is done with
+ * @cset->tasks and is about to move on to @cset->mg_tasks would miss them.
+ * This happens when cgroup_migrate_add_task() skipped the iterator past the
+ * last task on @cset->tasks and the migration then failed.  Point such an
+ * iterator at the first task that is moved.  It may return tasks that it
+ * returned before, as it may when a task migrates to a css_set it hasn't
+ * walked yet.
+ */
+static void css_set_splice_mg_tasks(struct css_set *cset)
+{
+	struct css_task_iter *it;
+
+	lockdep_assert_held(&css_set_lock);
+
+	if (list_empty(&cset->mg_tasks))
+		return;
+
+	/* only a skipped iterator stops at the head, see css_task_iter_skip() */
+	list_for_each_entry(it, &cset->task_iters, iters_node)
+		if (it->task_pos == &cset->tasks)
+			it->task_pos = cset->mg_tasks.next;
+
+	list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
+}
+
 /**
  * css_set_move_task - move a task from one css_set to another
  * @task: task being moved
@@ -2851,7 +2880,7 @@ static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
 	spin_lock_irq(&css_set_lock);
 	list_splice_init(&tset->dst_csets, &tset->src_csets);
 	list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
-		list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
+		css_set_splice_mg_tasks(cset);
 		list_del_init(&cset->mg_node);
 	}
 	spin_unlock_irq(&css_set_lock);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v2 02/11] cgroup: kill a child forked while cgroup.kill runs
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 01/11] cgroup: don't lose a task in css_task_iter when a migration fails Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 03/11] cgroup/freezer: check own tasks and descendants for the frozen state Shakeel Butt
                   ` (8 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel,
	stable

A process forked while cgroup.kill is walking its parent's cgroup can
survive the kill:

  kill                               fork
  ----                               ----
  kill_seq++
                                     cgroup_can_fork() reads kill_seq
  iterator returns the parent
  and moves on
                                     copy_process() sees no SIGKILL yet
                                     and commits to the fork
  send SIGKILL to the parent
                                     cgroup_post_fork() links the child
                                     behind the iterator; kill_seq is
                                     unchanged, so the child lives

The fork read kill_seq after the kill started, so the check from commit
b69bb476dee9 ("cgroup: fix race between fork and cgroup.kill") misses it.
The window is the gap between the iterator step and send_sig(), and
preemption can stretch it.

Make kill_seq odd while __cgroup_kill() walks the tasks. Kill the child if
kill_seq was odd when the fork read it, or if it changed since. A walk that
ended before the read has already sent SIGKILL to the parent, so the fork
fails. A walk that starts after the child is linked finds the child.
CLONE_INTO_CGROUP forks hold cgroup_mutex across both reads, so they always
see an even, unchanged kill_seq.

Reproduced in a VM with a sleep between the iterator and send_sig(): the
child survived in 5 of 5 runs, and in 0 of 5 with this patch.

Fixes: b69bb476dee9 ("cgroup: fix race between fork and cgroup.kill")
Cc: stable@vger.kernel.org # v5.14+
Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 include/linux/cgroup-defs.h |  5 +++--
 kernel/cgroup/cgroup.c      | 15 ++++++++++++++-
 2 files changed, 17 insertions(+), 3 deletions(-)

diff --git a/include/linux/cgroup-defs.h b/include/linux/cgroup-defs.h
index cbfe8937647c..0dae54b033e9 100644
--- a/include/linux/cgroup-defs.h
+++ b/include/linux/cgroup-defs.h
@@ -528,8 +528,9 @@ struct cgroup {
 	int nr_threaded_children;	/* # of live threaded child cgroups */
 
 	/*
-	 * Sequence number for cgroup.kill. Incremented with both cgroup_mutex
-	 * and css_set_lock held. Readers hold either one.
+	 * 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.
 	 */
 	unsigned int kill_seq;
 
diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c
index a5a7395dc5b8..0fcd2c1b0da9 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -4329,6 +4329,14 @@ static void __cgroup_kill(struct cgroup *cgrp)
 
 	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.
+	 */
 	spin_lock_irq(&css_set_lock);
 	cgrp->kill_seq++;
 	spin_unlock_irq(&css_set_lock);
@@ -4346,6 +4354,10 @@ static void __cgroup_kill(struct cgroup *cgrp)
 		send_sig(SIGKILL, task, 0);
 	}
 	css_task_iter_end(&it);
+
+	spin_lock_irq(&css_set_lock);
+	cgrp->kill_seq++;
+	spin_unlock_irq(&css_set_lock);
 }
 
 static void cgroup_kill(struct cgroup *cgrp)
@@ -7208,7 +7220,8 @@ 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;
+		kill = kargs->kill_seq != cgrp_kill_seq ||
+		       (kargs->kill_seq & 1);
 	}
 
 	spin_unlock_irq(&css_set_lock);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v2 03/11] cgroup/freezer: check own tasks and descendants for the frozen state
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 01/11] cgroup: don't lose a task in css_task_iter when a migration fails Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 02/11] cgroup: kill a child forked while cgroup.kill runs Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 04/11] cgroup/freezer: don't update the frozen state of removed cgroups Shakeel Butt
                   ` (7 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel,
	stable

A cgroup with its own tasks and child cgroups can report frozen=1 while
part of its subtree still runs. cgroup2 allows this layout in threaded
cgroups, and in domain cgroups that don't enable a domain controller for
their children.

cgroup_update_frozen() only looks at the cgroup's own tasks, and
cgroup_propagate_frozen() only looks at its descendants. So a parent can
become frozen when only one of the two is frozen. The wrong state can also
stay after a thaw: cgroup_do_freeze() skips the update while a descendant
is unfrozen, and a stopped task is not woken to fix it.

Use one test everywhere: CGRP_FREEZE is set, all own tasks are frozen and
all descendants are frozen. Merge cgroup_propagate_frozen() into
cgroup_update_frozen() and always call it from cgroup_do_freeze().

Reproduced in a VM with a task stuck in D state, writing to an fsfreeze'd
filesystem. With the stuck task in the child or in the parent, the parent
reported frozen=1. With a stopped task moved into the parent, the parent
still reported frozen=1 after the thaw. With this patch it reports
frozen=0 in all three cases.

Fixes: 76f969e8948d ("cgroup: cgroup v2 freezer")
Cc: stable@vger.kernel.org # v5.2+
Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 kernel/cgroup/freezer.c | 63 ++++++++++++++++-------------------------
 1 file changed, 24 insertions(+), 39 deletions(-)

diff --git a/kernel/cgroup/freezer.c b/kernel/cgroup/freezer.c
index 35112d62318a..6ecb42084ecc 100644
--- a/kernel/cgroup/freezer.c
+++ b/kernel/cgroup/freezer.c
@@ -28,53 +28,39 @@ static bool cgroup_update_frozen_flag(struct cgroup *cgrp, bool frozen)
 }
 
 /*
- * Propagate the cgroup frozen state upwards by the cgroup tree.
+ * A cgroup is frozen when it has to be frozen (CGRP_FREEZE bit set), all of
+ * its own tasks are frozen and/or stopped, and all of its descendants are
+ * frozen.  A non-leaf cgroup can have tasks of its own: threaded cgroups always
+ * can, and domain cgroups can while no domain controller is enabled in their
+ * subtree_control.
  */
-static void cgroup_propagate_frozen(struct cgroup *cgrp, bool frozen)
+static bool cgroup_frozen_state(struct cgroup *cgrp)
 {
-	int desc = 1;
-
-	/*
-	 * If the new state is frozen, some freezing ancestor cgroups may change
-	 * their state too, depending on if all their descendants are frozen.
-	 *
-	 * Otherwise, all ancestor cgroups are forced into the non-frozen state.
-	 */
-	while ((cgrp = cgroup_parent(cgrp))) {
-		if (frozen) {
-			cgrp->freezer.nr_frozen_descendants += desc;
-			if (!test_bit(CGRP_FREEZE, &cgrp->flags) ||
-			    (cgrp->freezer.nr_frozen_descendants !=
-			    cgrp->nr_descendants))
-				continue;
-		} else {
-			cgrp->freezer.nr_frozen_descendants -= desc;
-		}
-
-		if (cgroup_update_frozen_flag(cgrp, frozen))
-			desc++;
-	}
+	/* __cgroup_task_count() walks the css_sets, test it last */
+	return test_bit(CGRP_FREEZE, &cgrp->flags) &&
+	       cgrp->freezer.nr_frozen_descendants == cgrp->nr_descendants &&
+	       cgrp->freezer.nr_frozen_tasks == __cgroup_task_count(cgrp);
 }
 
 /*
- * Revisit the cgroup frozen state.
- * Checks if the cgroup is really frozen and perform all state transitions.
+ * Revisit the frozen state of @cgrp and propagate a change to the ancestors.
+ * delta counts the cgroups below the one being looked at whose frozen state
+ * changed in this update, negative if they were unfrozen.
  */
 void cgroup_update_frozen(struct cgroup *cgrp)
 {
-	bool frozen;
+	int delta = 0;
 
-	/*
-	 * If the cgroup has to be frozen (CGRP_FREEZE bit set),
-	 * and all tasks are frozen and/or stopped, let's consider
-	 * the cgroup frozen. Otherwise it's not frozen.
-	 */
-	frozen = test_bit(CGRP_FREEZE, &cgrp->flags) &&
-		cgrp->freezer.nr_frozen_tasks == __cgroup_task_count(cgrp);
+	lockdep_assert_held(&css_set_lock);
+
+	do {
+		bool frozen;
 
-	/* If flags is updated, update the state of ancestor cgroups. */
-	if (cgroup_update_frozen_flag(cgrp, frozen))
-		cgroup_propagate_frozen(cgrp, frozen);
+		cgrp->freezer.nr_frozen_descendants += delta;
+		frozen = cgroup_frozen_state(cgrp);
+		if (cgroup_update_frozen_flag(cgrp, frozen))
+			delta += frozen ? 1 : -1;
+	} while (delta && (cgrp = cgroup_parent(cgrp)));
 }
 
 /*
@@ -210,8 +196,7 @@ static void cgroup_do_freeze(struct cgroup *cgrp, bool freeze, u64 ts_nsec)
 	 * and cgroups which descendants are already in the desired state.
 	 */
 	spin_lock_irq(&css_set_lock);
-	if (cgrp->nr_descendants == cgrp->freezer.nr_frozen_descendants)
-		cgroup_update_frozen(cgrp);
+	cgroup_update_frozen(cgrp);
 	spin_unlock_irq(&css_set_lock);
 }
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v2 04/11] cgroup/freezer: don't update the frozen state of removed cgroups
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
                   ` (2 preceding siblings ...)
  2026-11-30 17:34 ` [PATCH v2 03/11] cgroup/freezer: check own tasks and descendants for the frozen state Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 05/11] cgroup/freezer: test the freeze trap bit under siglock Shakeel Butt
                   ` (6 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel,
	stable

Since commit 93618edf7538 ("cgroup: Defer css percpu_ref kill on rmdir
until cgroup is depopulated"), rmdir can remove a cgroup while an exiting
task is still linked to it. The task is unlinked later, in
cgroup_task_dead(). This breaks the freezer counts:

 - rmdir takes the cgroup out of the ancestors' nr_frozen_descendants only
   if it is frozen, and a cgroup with an exiting task is not. When the task
   is unlinked, cgroup_update_frozen() marks the dead cgroup frozen and
   counts it again in every ancestor. The count stays one too high, so a
   freezing ancestor reports frozen=1 too early or never.

 - If the removed cgroup was the parent's last unfrozen descendant, the
   parent is not checked again and stays at frozen=0.

Clear CSS_ONLINE, fix the ancestors' counts and check the parent again in
one css_set_lock section, and make cgroup_update_frozen() skip dead
cgroups. cgroup_is_dead() can now run with only css_set_lock held, while
other bits of the same flags word change under cgroup_mutex, so use
READ_ONCE() and WRITE_ONCE() for CSS_ONLINE.

The parent's check needs the frozen state to cover descendants, so a
backport needs "cgroup/freezer: check own tasks and descendants for the
frozen state" first.

Reproduced in a VM: freeze G/P, kill the only task in G/P/C while its exit
is held on an fsfreeze'd filesystem, remove G/P/C, and let the task finish.
G/P, empty and freezing, reports frozen=0, and a later freeze of G never
completes. This patch fixes both.

Fixes: 93618edf7538 ("cgroup: Defer css percpu_ref kill on rmdir until cgroup is depopulated")
Cc: stable@vger.kernel.org # v7.0+, needs "cgroup/freezer: check own tasks and descendants for the frozen state"
Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 include/linux/cgroup.h  |  2 +-
 kernel/cgroup/cgroup.c  | 33 +++++++++++++++++++--------------
 kernel/cgroup/freezer.c |  8 ++++++++
 3 files changed, 28 insertions(+), 15 deletions(-)

diff --git a/include/linux/cgroup.h b/include/linux/cgroup.h
index f3c65991acac..7279613d6804 100644
--- a/include/linux/cgroup.h
+++ b/include/linux/cgroup.h
@@ -462,7 +462,7 @@ static inline bool css_is_self(struct cgroup_subsys_state *css)
 
 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
 {
-	return !(cgrp->self.flags & CSS_ONLINE);
+	return !(READ_ONCE(cgrp->self.flags) & CSS_ONLINE);
 }
 
 static inline void cgroup_get(struct cgroup *cgrp)
diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c
index 0fcd2c1b0da9..3972cf413797 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -6426,25 +6426,17 @@ static int cgroup_destroy_locked(struct cgroup *cgrp)
 	 * further task migration and child creation by disabling
 	 * cgroup_kn_lock_live().  The latter makes the csets ignored by
 	 * the migration path.
+	 *
+	 * Exiting tasks can stay linked to @cgrp until cgroup_task_dead().
+	 * Take @cgrp out of its ancestors' descendant counts in the same
+	 * css_set_lock section, so that cgroup_update_frozen() for those
+	 * tasks sees @cgrp dead and leaves the counts alone.
 	 */
-	cgrp->self.flags &= ~CSS_ONLINE;
-
 	spin_lock_irq(&css_set_lock);
+	WRITE_ONCE(cgrp->self.flags, cgrp->self.flags & ~CSS_ONLINE);
 	list_for_each_entry(link, &cgrp->cset_links, cset_link)
 		link->cset->dead = true;
-	spin_unlock_irq(&css_set_lock);
-
-	for_each_css(css, ssid, cgrp)
-		kill_css_sync(css);
-
-	/* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
-	css_clear_dir(&cgrp->self);
-	kernfs_remove(cgrp->kn);
-
-	if (cgroup_is_threaded(cgrp))
-		parent->nr_threaded_children--;
 
-	spin_lock_irq(&css_set_lock);
 	for (tcgrp = parent; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
 		tcgrp->nr_descendants--;
 		tcgrp->nr_dying_descendants++;
@@ -6455,8 +6447,21 @@ static int cgroup_destroy_locked(struct cgroup *cgrp)
 		if (test_bit(CGRP_FROZEN, &cgrp->flags))
 			tcgrp->freezer.nr_frozen_descendants--;
 	}
+
+	/* @cgrp may have been the last unfrozen descendant of a freezing parent */
+	cgroup_update_frozen(parent);
 	spin_unlock_irq(&css_set_lock);
 
+	for_each_css(css, ssid, cgrp)
+		kill_css_sync(css);
+
+	/* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
+	css_clear_dir(&cgrp->self);
+	kernfs_remove(cgrp->kn);
+
+	if (cgroup_is_threaded(cgrp))
+		parent->nr_threaded_children--;
+
 	cgroup1_check_for_release(parent);
 
 	ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier,
diff --git a/kernel/cgroup/freezer.c b/kernel/cgroup/freezer.c
index 6ecb42084ecc..a85f8897ffa2 100644
--- a/kernel/cgroup/freezer.c
+++ b/kernel/cgroup/freezer.c
@@ -53,6 +53,14 @@ void cgroup_update_frozen(struct cgroup *cgrp)
 
 	lockdep_assert_held(&css_set_lock);
 
+	/*
+	 * An exiting task can stay linked to a cgroup after rmdir.
+	 * cgroup_destroy_locked() took the cgroup out of its ancestors' counts
+	 * when it cleared CSS_ONLINE.  Leave its state alone from then on.
+	 */
+	if (cgroup_is_dead(cgrp))
+		return;
+
 	do {
 		bool frozen;
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v2 05/11] cgroup/freezer: test the freeze trap bit under siglock
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
                   ` (3 preceding siblings ...)
  2026-11-30 17:34 ` [PATCH v2 04/11] cgroup/freezer: don't update the frozen state of removed cgroups Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 06/11] selftests/cgroup: test cgroup.procs reads across a failed migration Shakeel Butt
                   ` (5 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel

When a task leaves the frozen state while its cgroup is still freezing,
for example a vfork parent, cgroup_leave_frozen() sets JOBCTL_TRAP_FREEZE
and TIF_SIGPENDING so that the task traps again. It tests
JOBCTL_TRAP_FREEZE without siglock.

cgroup_freeze_task() sets that bit and then TIF_SIGPENDING, both under
siglock. If the task sees only the first store, it can return to user
space while it is counted as frozen, until the wakeup kick arrives. Take
siglock before the test. The window is a few instructions wide, and this
was not reproduced.

Fixes: cb2c4cd87874 ("cgroup: prevent spurious transition into non-frozen state")
Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 kernel/cgroup/freezer.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/kernel/cgroup/freezer.c b/kernel/cgroup/freezer.c
index a85f8897ffa2..b905df5e416b 100644
--- a/kernel/cgroup/freezer.c
+++ b/kernel/cgroup/freezer.c
@@ -127,10 +127,17 @@ void cgroup_leave_frozen(bool always_leave)
 		cgroup_update_frozen(cgrp);
 		WARN_ON_ONCE(!current->frozen);
 		current->frozen = false;
-	} else if (!(current->jobctl & JOBCTL_TRAP_FREEZE)) {
+	} else {
+		/*
+		 * Test the trap bit under siglock: cgroup_freeze_task() sets it
+		 * before signal_wake_up() sets TIF_SIGPENDING, and a vfork
+		 * parent returns to user space right after this.
+		 */
 		spin_lock(&current->sighand->siglock);
-		current->jobctl |= JOBCTL_TRAP_FREEZE;
-		set_thread_flag(TIF_SIGPENDING);
+		if (!(current->jobctl & JOBCTL_TRAP_FREEZE)) {
+			current->jobctl |= JOBCTL_TRAP_FREEZE;
+			set_thread_flag(TIF_SIGPENDING);
+		}
 		spin_unlock(&current->sighand->siglock);
 	}
 	spin_unlock_irq(&css_set_lock);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v2 06/11] selftests/cgroup: test cgroup.procs reads across a failed migration
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
                   ` (4 preceding siblings ...)
  2026-11-30 17:34 ` [PATCH v2 05/11] cgroup/freezer: test the freeze trap bit under siglock Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 07/11] selftests/cgroup: test the frozen state of a cgroup with tasks and children Shakeel Butt
                   ` (4 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel

cgroup.procs keeps its task iterator between reads. A failed migration
used to make the iterator skip the last process of a css_set.

Read one byte of cgroup.procs, so that the iterator waits on the last of
three processes. Then fail a migration of that process, and check that
the rest of the read still lists it. cpuset makes the migration fail: a
partition with one CPU gives that CPU to a child partition, which leaves
its other child without CPUs. The test is skipped if this can't be set
up.

The test fails without "cgroup: don't lose a task in css_task_iter when
a migration fails".

Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 tools/testing/selftests/cgroup/test_core.c | 154 +++++++++++++++++++++
 1 file changed, 154 insertions(+)

diff --git a/tools/testing/selftests/cgroup/test_core.c b/tools/testing/selftests/cgroup/test_core.c
index 53592bf309fa..01c268672d6d 100644
--- a/tools/testing/selftests/cgroup/test_core.c
+++ b/tools/testing/selftests/cgroup/test_core.c
@@ -9,6 +9,7 @@
 #include <sys/stat.h>
 #include <sys/wait.h>
 #include <unistd.h>
+#include <ctype.h>
 #include <dirent.h>
 #include <fcntl.h>
 #include <sched.h>
@@ -739,6 +740,158 @@ static int test_cgcore_thread_migration(const char *root)
 	return ret;
 }
 
+/* Return the highest CPU number in a cpu list like "0-3,8-11", or -1. */
+static int cpulist_last(const char *list)
+{
+	const char *p = list + strlen(list);
+
+	while (p > list && !isdigit(p[-1]))
+		p--;
+	while (p > list && isdigit(p[-1]))
+		p--;
+	return isdigit(*p) ? atoi(p) : -1;
+}
+
+/* Is @pid on a line of its own in @buf? */
+static bool pid_listed(const char *buf, pid_t pid)
+{
+	const char *p = buf;
+	char *end;
+
+	while (*p) {
+		if (strtol(p, &end, 10) == pid && end != p && *end == '\n')
+			return true;
+		p = strchr(p, '\n');
+		if (!p)
+			break;
+		p++;
+	}
+	return false;
+}
+
+/*
+ * A migration that fails must not make a cgroup.procs reader miss a process.
+ *
+ * cgroup.procs keeps its task iterator between reads.  Read one byte, so that
+ * the iterator waits on the last process, then fail a migration of that
+ * process: cpuset refuses tasks for a cgroup without CPUs.  The process never
+ * left the cgroup, so the rest of the read must list it.
+ */
+static int test_cgcore_procs_failed_migration(const char *root)
+{
+	char *parent = NULL, *full = NULL, *empty = NULL, *cg = NULL;
+	char cpus[256], cpu[16], buf[4096];
+	bool cpuset_enabled = false;
+	pid_t pids[3] = { 0 };
+	int ret = KSFT_FAIL;
+	int fd = -1, i, last;
+	ssize_t len, n;
+
+	if (cg_test_v1_named)
+		return KSFT_SKIP;
+
+	parent = cg_name(root, "cg_test_fail");
+	full = cg_name(root, "cg_test_fail/full");
+	empty = cg_name(root, "cg_test_fail/empty");
+	cg = cg_name(root, "cg_test_src");
+	if (!parent || !full || !empty || !cg)
+		goto cleanup;
+
+	/*
+	 * Make "empty" a cgroup without CPUs: "parent" is a partition with one
+	 * CPU, and its child partition "full" takes that CPU.
+	 */
+	ret = KSFT_SKIP;
+	if (cg_read_strstr(root, "cgroup.subtree_control", "cpuset")) {
+		if (cg_write(root, "cgroup.subtree_control", "+cpuset"))
+			goto cleanup;
+		cpuset_enabled = true;
+	}
+	if (cg_read(root, "cpuset.cpus.effective", cpus, sizeof(cpus)))
+		goto cleanup;
+	last = cpulist_last(cpus);
+	if (last <= 0)
+		goto cleanup;
+	snprintf(cpu, sizeof(cpu), "%d", last);
+
+	if (cg_create(parent) || cg_write(parent, "cpuset.cpus", cpu) ||
+	    cg_write(parent, "cpuset.cpus.partition", "root") ||
+	    cg_read_strcmp(parent, "cpuset.cpus.partition", "root\n") ||
+	    cg_write(parent, "cgroup.subtree_control", "+cpuset") ||
+	    cg_create(full) || cg_write(full, "cpuset.cpus", cpu) ||
+	    cg_write(full, "cpuset.cpus.partition", "root") ||
+	    cg_read_strcmp(full, "cpuset.cpus.partition", "root\n") ||
+	    cg_create(empty) ||
+	    cg_read_strcmp(empty, "cpuset.cpus.effective", "\n"))
+		goto cleanup;
+
+	ret = KSFT_FAIL;
+	if (cg_create(cg))
+		goto cleanup;
+
+	/* Move the processes in one by one, so that they are listed in order. */
+	for (i = 0; i < 3; i++) {
+		pids[i] = fork();
+		if (pids[i] < 0)
+			goto cleanup;
+		if (!pids[i]) {
+			while (1)
+				pause();
+		}
+		if (cg_enter(cg, pids[i]))
+			goto cleanup;
+	}
+
+	/* Without a failing migration there is nothing to test. */
+	if (cg_enter(empty, pids[2]) != -ENOSPC) {
+		ret = KSFT_SKIP;
+		goto cleanup;
+	}
+
+	fd = cg_open(cg, "cgroup.procs", O_RDONLY);
+	if (fd < 0)
+		goto cleanup;
+	if (read(fd, buf, 1) != 1)
+		goto cleanup;
+	len = 1;
+
+	if (cg_enter(empty, pids[2]) != -ENOSPC)
+		goto cleanup;
+
+	while ((n = read(fd, buf + len, sizeof(buf) - 1 - len)) > 0)
+		len += n;
+	if (n < 0)
+		goto cleanup;
+	buf[len] = '\0';
+
+	for (i = 0; i < 3; i++)
+		if (!pid_listed(buf, pids[i]))
+			goto cleanup;
+
+	ret = KSFT_PASS;
+
+cleanup:
+	if (fd >= 0)
+		close(fd);
+	for (i = 0; i < 3; i++) {
+		if (pids[i] > 0) {
+			kill(pids[i], SIGKILL);
+			waitpid(pids[i], NULL, 0);
+		}
+	}
+	cg_destroy(cg);
+	cg_destroy(empty);
+	cg_destroy(full);
+	cg_destroy(parent);
+	if (cpuset_enabled)
+		cg_write(root, "cgroup.subtree_control", "-cpuset");
+	free(cg);
+	free(empty);
+	free(full);
+	free(parent);
+	return ret;
+}
+
 /*
  * cgroup migration permission check should be performed based on the
  * credentials at the time of open instead of write.
@@ -941,6 +1094,7 @@ struct corecg_test {
 	T(test_cgcore_populated),
 	T(test_cgcore_proc_migration),
 	T(test_cgcore_thread_migration),
+	T(test_cgcore_procs_failed_migration),
 	T(test_cgcore_destroy),
 	T(test_cgcore_lesser_euid_open),
 	T(test_cgcore_lesser_ns_open),
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v2 07/11] selftests/cgroup: test the frozen state of a cgroup with tasks and children
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
                   ` (5 preceding siblings ...)
  2026-11-30 17:34 ` [PATCH v2 06/11] selftests/cgroup: test cgroup.procs reads across a failed migration Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 08/11] selftests/cgroup: test cgroup.kill in a threaded cgroup Shakeel Butt
                   ` (3 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel

Add a test for a cgroup that has tasks of its own and a child cgroup. It
must report frozen only when its own tasks and the child are all frozen,
and it must not stay frozen after a thaw.

To get a task that the cgroup2 freezer can't stop, freeze it in a cgroup
v1 freezer hierarchy. It then sleeps in the refrigerator, where the
cgroup2 freezer can't trap it. A stopped task counts as frozen, and a
thaw doesn't wake it. The test is skipped if the v1 freezer can't be
mounted.

Without "cgroup/freezer: check own tasks and descendants for the frozen
state", the parent reports frozen=1 while its child is not frozen.

Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 tools/testing/selftests/cgroup/test_freezer.c | 105 ++++++++++++++++++
 1 file changed, 105 insertions(+)

diff --git a/tools/testing/selftests/cgroup/test_freezer.c b/tools/testing/selftests/cgroup/test_freezer.c
index 266b1a0f889f..e24e97742492 100644
--- a/tools/testing/selftests/cgroup/test_freezer.c
+++ b/tools/testing/selftests/cgroup/test_freezer.c
@@ -4,6 +4,7 @@
 #include <sys/ptrace.h>
 #include <sys/types.h>
 #include <sys/mman.h>
+#include <sys/mount.h>
 #include <unistd.h>
 #include <stdio.h>
 #include <errno.h>
@@ -804,6 +805,109 @@ static int test_cgfreezer_vfork(const char *root)
 	return ret;
 }
 
+/*
+ * A cgroup with tasks of its own and child cgroups is frozen only once its
+ * tasks and all its descendants are frozen.
+ *
+ * A task frozen in a cgroup v1 freezer hierarchy sleeps in the refrigerator,
+ * where the cgroup v2 freezer can't trap it, so its v2 cgroup can't freeze
+ * until it is thawed.  A stopped task counts as frozen and isn't woken by a
+ * thaw.
+ */
+static int test_cgfreezer_nonleaf(const char *root)
+{
+	char *parent = NULL, *child = NULL, *staging = NULL, *v1cg = NULL;
+	char v1root[] = "/tmp/cg_test_freezer_v1_XXXXXX";
+	int ret = KSFT_FAIL, frozen_pid, stopped_pid, i;
+	bool mounted = false;
+
+	if (!mkdtemp(v1root))
+		return KSFT_FAIL;
+
+	if (mount("none", v1root, "cgroup", 0, "freezer")) {
+		debug("Can't mount the cgroup v1 freezer\n");
+		ret = KSFT_SKIP;
+		goto cleanup;
+	}
+	mounted = true;
+
+	parent = cg_name(root, "cg_test_nonleaf");
+	child = cg_name(parent, "child");
+	staging = cg_name(root, "cg_test_nonleaf_staging");
+	v1cg = cg_name(v1root, "cg_test_nonleaf");
+	if (!parent || !child || !staging || !v1cg)
+		goto cleanup;
+
+	if (cg_create(parent) || cg_create(child) || cg_create(staging) ||
+	    cg_create(v1cg))
+		goto cleanup;
+
+	frozen_pid = cg_run_nowait(child, child_fn, NULL);
+	stopped_pid = cg_run_nowait(staging, child_fn, NULL);
+	if (frozen_pid < 0 || stopped_pid < 0 ||
+	    cg_wait_for_proc_count(child, 1) ||
+	    cg_wait_for_proc_count(staging, 1))
+		goto cleanup;
+
+	/* Freeze one task in the v1 hierarchy and stop the other. */
+	if (cg_enter(v1cg, frozen_pid) ||
+	    cg_write(v1cg, "freezer.state", "FROZEN") ||
+	    cg_read_strcmp_wait(v1cg, "freezer.state", "FROZEN\n"))
+		goto cleanup;
+
+	if (kill(stopped_pid, SIGSTOP) ||
+	    waitpid(stopped_pid, NULL, WUNTRACED) != stopped_pid)
+		goto cleanup;
+
+	/*
+	 * Freeze the parent and move the stopped task in.  All of the
+	 * parent's own tasks are frozen now, but its child isn't.
+	 */
+	if (cg_freeze_nowait(parent, true) || cg_enter(parent, stopped_pid))
+		goto cleanup;
+
+	for (i = 0; i < 50; i++) {
+		if (cg_check_frozen(parent, false) ||
+		    cg_check_frozen(child, false))
+			goto cleanup;
+		usleep(10000);
+	}
+
+	/* The thaw doesn't wake the stopped task, the parent stays thawed. */
+	if (cg_freeze_nowait(parent, false) || cg_check_frozen(parent, false))
+		goto cleanup;
+
+	/* Once the task is thawed in v1, the whole subtree can freeze. */
+	if (cg_write(v1cg, "freezer.state", "THAWED"))
+		goto cleanup;
+
+	if (cg_freeze_wait(parent, true) || cg_check_frozen(child, true))
+		goto cleanup;
+
+	if (cg_freeze_wait(parent, false))
+		goto cleanup;
+
+	ret = KSFT_PASS;
+
+cleanup:
+	/* SIGKILL doesn't wake up a task in the refrigerator. */
+	if (mounted && v1cg)
+		cg_write(v1cg, "freezer.state", "THAWED");
+	cg_destroy(child);
+	cg_destroy(parent);
+	cg_destroy(staging);
+	if (mounted) {
+		cg_destroy(v1cg);
+		umount(v1root);
+	}
+	rmdir(v1root);
+	free(v1cg);
+	free(staging);
+	free(child);
+	free(parent);
+	return ret;
+}
+
 /*
  * Get the current frozen_usec for the cgroup.
  */
@@ -1479,6 +1583,7 @@ struct cgfreezer_test {
 	T(test_cgfreezer_stopped),
 	T(test_cgfreezer_ptraced),
 	T(test_cgfreezer_vfork),
+	T(test_cgfreezer_nonleaf),
 	T(test_cgfreezer_time_empty),
 	T(test_cgfreezer_time_simple),
 	T(test_cgfreezer_time_populate),
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v2 08/11] selftests/cgroup: test cgroup.kill in a threaded cgroup
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
                   ` (6 preceding siblings ...)
  2026-11-30 17:34 ` [PATCH v2 07/11] selftests/cgroup: test the frozen state of a cgroup with tasks and children Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 09/11] cgroup: factor out cgroup_kn_break_active() and cgroup_kn_unbreak_active() Shakeel Butt
                   ` (2 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel

Check that writing cgroup.kill in a threaded cgroup fails with EOPNOTSUPP
and kills nothing, and that the thread root can still kill a process whose
thread was moved into the threaded cgroup.

This is existing behavior. The next patches change how cgroup.kill checks
for threaded cgroups, and this test shows that the behavior stays the
same.

Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 tools/testing/selftests/cgroup/test_kill.c | 68 ++++++++++++++++++++++
 1 file changed, 68 insertions(+)

diff --git a/tools/testing/selftests/cgroup/test_kill.c b/tools/testing/selftests/cgroup/test_kill.c
index 756bc7193d4b..d3fab2ba732b 100644
--- a/tools/testing/selftests/cgroup/test_kill.c
+++ b/tools/testing/selftests/cgroup/test_kill.c
@@ -471,6 +471,73 @@ static int test_cgkill_exited_leader_migrated(const char *root)
 	return ret;
 }
 
+/*
+ * cgroup.kill is refused in a threaded cgroup, as killing is directed at
+ * whole processes.  The thread root can still kill a process whose thread
+ * was moved into the threaded cgroup.
+ */
+static int test_cgkill_threaded(const char *root)
+{
+	char *parent = NULL, *threaded = NULL;
+	int ret = KSFT_FAIL;
+	pid_t pid = -ESRCH;
+
+	parent = cg_name(root, "cg_test_kill_thread_root");
+	if (!parent)
+		goto cleanup;
+
+	threaded = cg_name(parent, "threaded");
+	if (!threaded)
+		goto cleanup;
+
+	if (cg_create(parent) || cg_create(threaded))
+		goto cleanup;
+
+	if (cg_write(threaded, "cgroup.type", "threaded"))
+		goto cleanup;
+
+	pid = cg_run_nowait(parent, child_fn, NULL);
+	if (pid < 0 || cg_wait_for_proc_count(parent, 1))
+		goto cleanup;
+
+	if (cg_write_numeric(threaded, "cgroup.threads", pid))
+		goto cleanup;
+
+	if (cg_write(threaded, "cgroup.kill", "1") != -EOPNOTSUPP)
+		goto cleanup;
+
+	/*
+	 * The refused write must not kill the child.  A SIGKILL from it would
+	 * end the child well within this delay.
+	 */
+	usleep(100000);
+	if (waitpid(pid, NULL, WNOHANG)) {
+		pid = -ESRCH;
+		goto cleanup;
+	}
+
+	if (cg_kill_wait(parent))
+		goto cleanup;
+
+	if (cg_read_strcmp_wait(parent, "cgroup.events", "populated 0\n"))
+		goto cleanup;
+
+	ret = KSFT_PASS;
+
+cleanup:
+	if (pid > 0) {
+		kill(pid, SIGKILL);
+		wait_for_pid(pid);
+	}
+	if (threaded)
+		cg_destroy(threaded);
+	if (parent)
+		cg_destroy(parent);
+	free(threaded);
+	free(parent);
+	return ret;
+}
+
 #define T(x) { x, #x }
 struct cgkill_test {
 	int (*fn)(const char *root);
@@ -482,6 +549,7 @@ struct cgkill_test {
 	T(test_cgkill_clone_into_killed),
 	T(test_cgkill_exited_leader),
 	T(test_cgkill_exited_leader_migrated),
+	T(test_cgkill_threaded),
 };
 #undef T
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v2 09/11] cgroup: factor out cgroup_kn_break_active() and cgroup_kn_unbreak_active()
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
                   ` (7 preceding siblings ...)
  2026-11-30 17:34 ` [PATCH v2 08/11] selftests/cgroup: test cgroup.kill in a threaded cgroup Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 10/11] cgroup: don't hold cgroup_mutex for cgroup.kill Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 11/11] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze Shakeel Butt
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel

Move the part of cgroup_kn_lock_live() that runs before cgroup_mutex into
cgroup_kn_break_active(). It pins the cgroup and drops the node's active
reference. cgroup_kn_unbreak_active() undoes it. Later patches use them in
writes that don't take cgroup_mutex. No functional change.

Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 kernel/cgroup/cgroup.c | 52 ++++++++++++++++++++++++++++++------------
 1 file changed, 37 insertions(+), 15 deletions(-)

diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c
index 3972cf413797..bdc044ad21d3 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -1669,6 +1669,37 @@ static u32 cgroup_calc_subtree_ss_mask(u32 subtree_control, u32 this_ss_mask)
 	return cur_ss_mask;
 }
 
+/*
+ * Pin the cgroup of @kn and drop @kn's active reference, so that removing the
+ * cgroup doesn't wait for the caller.  The cgroup stays accessible but can go
+ * offline at any time: the caller checks cgroup_is_dead() under a lock that
+ * removal also takes.  Undo with cgroup_kn_unbreak_active(), or
+ * cgroup_kn_unlock() if cgroup_mutex is held.
+ */
+static struct cgroup *cgroup_kn_break_active(struct kernfs_node *kn)
+{
+	struct cgroup *cgrp;
+
+	if (kernfs_type(kn) == KERNFS_DIR)
+		cgrp = kn->priv;
+	else
+		cgrp = kn_priv(kn);
+
+	/* ensure @cgrp stays accessible and break the active_ref protection */
+	if (!cgroup_tryget(cgrp))
+		return ERR_PTR(-ENODEV);
+	kernfs_break_active_protection(kn);
+	return cgrp;
+}
+
+/* undo cgroup_kn_break_active() */
+static void cgroup_kn_unbreak_active(struct kernfs_node *kn,
+				     struct cgroup *cgrp)
+{
+	kernfs_unbreak_active_protection(kn);
+	cgroup_put(cgrp);
+}
+
 /**
  * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
  * @kn: the kernfs_node being serviced
@@ -1689,9 +1720,7 @@ void cgroup_kn_unlock(struct kernfs_node *kn)
 		cgrp = kn_priv(kn);
 
 	cgroup_unlock();
-
-	kernfs_unbreak_active_protection(kn);
-	cgroup_put(cgrp);
+	cgroup_kn_unbreak_active(kn, cgrp);
 }
 
 /**
@@ -1717,26 +1746,19 @@ struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
 	struct cgroup *cgrp;
 	int ret;
 
-	if (kernfs_type(kn) == KERNFS_DIR)
-		cgrp = kn->priv;
-	else
-		cgrp = kn_priv(kn);
-
 	/*
 	 * We're gonna grab cgroup_mutex which nests outside kernfs
 	 * active_ref.  cgroup liveliness check alone provides enough
-	 * protection against removal.  Ensure @cgrp stays accessible and
-	 * break the active_ref protection.
+	 * protection against removal.
 	 */
-	if (!cgroup_tryget(cgrp))
-		return ERR_PTR(-ENODEV);
-	kernfs_break_active_protection(kn);
+	cgrp = cgroup_kn_break_active(kn);
+	if (IS_ERR(cgrp))
+		return cgrp;
 
 	if (drain_offline) {
 		ret = cgroup_lock_and_drain_offline(cgrp);
 		if (unlikely(ret)) {
-			kernfs_unbreak_active_protection(kn);
-			cgroup_put(cgrp);
+			cgroup_kn_unbreak_active(kn, cgrp);
 			return ERR_PTR(ret);
 		}
 	} else {
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v2 10/11] cgroup: don't hold cgroup_mutex for cgroup.kill
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
                   ` (8 preceding siblings ...)
  2026-11-30 17:34 ` [PATCH v2 09/11] cgroup: factor out cgroup_kn_break_active() and cgroup_kn_unbreak_active() Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  2026-11-30 17:34 ` [PATCH v2 11/11] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze Shakeel Butt
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel

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 list of running kills lets
   migrations skip the check when no kill runs.

 - The walk sends SIGKILL from the writer, and a pid namespace init
   ignores it unless the writer is outside the init's pid namespace. In
   cgroup_migrate_execute(), current is the migrating task instead. So
   each kill records its writer's pid, and a task that leaves the subtree
   gets a forced SIGKILL only if one of the writers is outside its pid
   namespace. Otherwise a pid namespace init is left alone, as the walk
   would leave it.

 - 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. So the switch fails with EBUSY while
   the cgroup is being killed. cgroup.kill returns right away for an
   empty subtree, which has nothing to kill, and nothing can enter the
   cgroup during the switch, so no kill can start during the switch. A
   CGRP_THREADED flag is set under css_set_lock when the switch succeeds,
   and cgroup.kill fails with EOPNOTSUPP once it is set. cgroup.kill
   checks for a removed cgroup in the same section.

The walk relies on the task iterator to return every task that stays in
a cgroup during the walk. This needs "cgroup: don't lose a task in
css_task_iter when a migration fails".

Document that a process moved out of the tree or inside it during a kill
is killed, and so is a CLONE_INTO_CGROUP child that a process in the tree
creates outside of it. Also document that a process moved in may or may
not be killed, 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, and so did a task
whose migration failed during the walk. A pid namespace init that moved
during a kill died when the kill was written from the host, and survived
when it was written inside its namespace, as it does with the walk. With
the matching check turned off, these tests failed. A switch to threaded
during a kill failed with EBUSY, and a kill during a switch that failed
returned 0. With the EBUSY 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 |  10 +-
 include/linux/cgroup-defs.h             |  18 +-
 include/linux/sched/task.h              |   1 +
 kernel/cgroup/cgroup.c                  | 246 ++++++++++++++++++++----
 4 files changed, 235 insertions(+), 40 deletions(-)

diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst
index 2f792ff29425..7d60d405d508 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -1057,11 +1057,17 @@ 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, and so is a process that a process in the tree creates
+	outside of it with CLONE_INTO_CGROUP.  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..a6f42dede900 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.  Set under css_set_lock when a switch to
+	 * threaded succeeds, so that a kill of the cgroup and the switch exclude
+	 * each other, see cgroup_enable_threaded() and cgroup_kill().
+	 */
+	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 bdc044ad21d3..cb8d9165ead2 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -2635,6 +2635,81 @@ void cgroup_attach_unlock(enum cgroup_attach_lock_mode lock_mode,
 	cpus_read_unlock();
 }
 
+/*
+ * A cgroup.kill write in progress.  It lives on the writer's stack and is on
+ * cgroup_kills, which is protected by css_set_lock.
+ */
+struct cgroup_kill_ctx {
+	struct list_head node;
+	struct cgroup *cgrp;		/* the cgroup written to */
+	struct pid *writer;		/* see cgroup_kill_leaving_task() */
+};
+
+static LIST_HEAD(cgroup_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_kill_leaving_task - kill a task that leaves a subtree being killed
+ * @task: task leaving a css_set of @cgrp
+ * @cgrp: cgroup of interest
+ *
+ * If a kill of @cgrp's subtree or of an ancestor's subtree is in progress,
+ * kill @task the way the walk of that kill would.  The walk sends SIGKILL from
+ * the writer, and a pid namespace init ignores it unless the writer is outside
+ * its pid namespace, see send_signal_locked().  current is the migrating task,
+ * so decide for the writers here.
+ */
+static void cgroup_kill_leaving_task(struct task_struct *task,
+				     struct cgroup *cgrp)
+{
+	struct pid_namespace *ns = task_active_pid_ns(task);
+	bool killing = false, force = false;
+	struct cgroup_kill_ctx *kill;
+	unsigned long flags;
+
+	lockdep_assert_held(&css_set_lock);
+
+	list_for_each_entry(kill, &cgroup_kills, node) {
+		if (!cgroup_is_descendant(cgrp, kill->cgrp))
+			continue;
+		killing = true;
+		if (!pid_nr_ns(kill->writer, ns))
+			force = true;
+	}
+
+	if (!killing || (task->flags & PF_KTHREAD) ||
+	    !lock_task_sighand(task, &flags))
+		return;
+	if (force || !(task->signal->flags & SIGNAL_UNKILLABLE))
+		send_signal_locked(SIGKILL, SEND_SIG_PRIV, task, PIDTYPE_TGID);
+	unlock_task_sighand(task, &flags);
+}
+
 /**
  * cgroup_migrate_add_task - add a migration target task to a migration context
  * @task: target task
@@ -2820,6 +2895,10 @@ static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
 			struct css_set *from_cset = task_css_set(task);
 			struct css_set *to_cset = cset->mg_dst_cset;
 
+			/* a task can't leave a subtree being killed */
+			if (unlikely(!list_empty(&cgroup_kills)))
+				cgroup_kill_leaving_task(task, cset->dfl_cgrp);
+
 			get_css_set(to_cset);
 			to_cset->nr_tasks++;
 			css_set_move_task(task, from_cset, to_cset, true);
@@ -3810,6 +3889,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.
+	 * No new kill of @cgrp can start until we're done: @cgrp is empty,
+	 * nothing can enter it while we hold cgroup_mutex, and cgroup_kill()
+	 * returns right away for an empty subtree.
+	 */
+	spin_lock_irq(&css_set_lock);
+	ret = cgrp->nr_subtree_kills ? -EBUSY : 0;
+	spin_unlock_irq(&css_set_lock);
+	if (ret)
+		return ret;
+
 	/*
 	 * The following shouldn't cause actual migrations and should
 	 * always succeed.
@@ -3825,6 +3918,13 @@ static int cgroup_enable_threaded(struct cgroup *cgrp)
 		parent->nr_threaded_children++;
 
 	cgroup_finalize_control(cgrp, ret);
+
+	/* new kills of @cgrp fail from now on, see cgroup_kill() */
+	if (!ret) {
+		spin_lock_irq(&css_set_lock);
+		set_bit(CGRP_THREADED, &cgrp->flags);
+		spin_unlock_irq(&css_set_lock);
+	}
 	return ret;
 }
 
@@ -4349,18 +4449,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);
@@ -4379,18 +4477,83 @@ 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.  It decides like the walk
+ *   would, see cgroup_kill_leaving_task();
+ * - 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.  So a kill of an empty subtree has nothing to do.
+ *
+ * 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_kill_ctx kill = { .cgrp = 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;
+	/* an empty subtree has nothing to kill, see above */
+	if (ret || !cgroup_is_populated(cgrp)) {
+		spin_unlock_irq(&css_set_lock);
+		return ret;
+	}
+	kill.writer = get_pid(task_pid(current));
+	list_add(&kill.node, &cgroup_kills);
+	cgrp->subtree_kill_seq++;
+	cgrp->nr_subtree_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_kill(css->cgroup);
+		cond_resched();
 
-	cgroup_for_each_live_descendant_pre(dsct, css, cgrp)
-		__cgroup_kill(dsct);
+		rcu_read_lock();
+		css_put(css);
+	}
+	rcu_read_unlock();
+
+	spin_lock_irq(&css_set_lock);
+	list_del(&kill.node);
+	cgrp->subtree_kill_seq++;
+	cgrp->nr_subtree_kills--;
+	spin_unlock_irq(&css_set_lock);
+	put_pid(kill.writer);
+	return 0;
 }
 
 static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf,
@@ -4407,21 +4570,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;
 }
@@ -7070,9 +7229,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:
@@ -7194,7 +7362,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;
@@ -7206,13 +7374,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++;
@@ -7247,8 +7424,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


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v2 11/11] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze
  2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
                   ` (9 preceding siblings ...)
  2026-11-30 17:34 ` [PATCH v2 10/11] cgroup: don't hold cgroup_mutex for cgroup.kill Shakeel Butt
@ 2026-11-30 17:34 ` Shakeel Butt
  10 siblings, 0 replies; 12+ messages in thread
From: Shakeel Butt @ 2026-11-30 17:34 UTC (permalink / raw)
  To: Tejun Heo
  Cc: Andrew Morton, Johannes Weiner, Michal Koutny, Michal Hocko,
	Roman Gushchin, Christian Brauner, Oleg Nesterov,
	Sebastian Andrzej Siewior, Suren Baghdasaryan, T . J . Mercier,
	Usama Arif, Meta kernel team, cgroups, linux-mm, linux-kernel

cgroup.freeze holds cgroup_mutex while it walks the subtree and its tasks.
cgroup_mutex kept freeze writers apart, gave new cgroups a stable parent
state, and blocked migrations. Replace it:

 - Serialize cgroup.freeze writers with a new cgroup_freeze_mutex. Nothing
   else takes it.

 - Protect freeze and e_freeze with css_set_lock. cgroup_create() copies
   the parent's e_freeze and links the new cgroup in one css_set_lock
   section, so the walk either sees the new cgroup or the new cgroup sees
   the new state. cgroup_freeze_show() reads freeze without a lock, so
   mark its accesses.

 - Check that the cgroup is alive in the section that changes freeze.
   rmdir clears CSS_ONLINE under css_set_lock, so a write either takes
   effect before the removal or fails with ENODEV, as before.

 - Set each task to the state of the cgroup it is in at that moment, under
   css_set_lock, instead of the walk's direction. A task can move after
   the walk picked it.

 - Set the new state of every cgroup in the subtree first, and walk the
   tasks after that. Otherwise a task that this write already froze could
   move to a cgroup that the walk hasn't reached and run again until the
   walk gets there. A task frozen by an earlier freeze of a nested cgroup
   can still run again if it moves while the states are being set, until
   the task walk reaches it.

 - A task can also move before the walk reaches it, with
   JOBCTL_TRAP_FREEZE still set from an earlier freeze.
   cgroup_freezer_migrate_task() returned early for it, and the task froze
   in a cgroup that isn't freezing. Don't return early while the bit is
   set. All writers of the bit now hold css_set_lock.

 - Read the clock for each cgroup when its state changes, under
   css_set_lock. With one timestamp per walk, a cgroup created during an
   unfreeze walk had its frozen time wrap around to a huge value.

 - A walk can now notify a new cgroup before its files are populated.
   Publish cfile->kn after its timer and lock are set up.

 - Walk the subtree under RCU, pin each cgroup while its tasks are walked,
   and skip removed cgroups.

The walk relies on the task iterator to return every task that stays in
a cgroup during the walk. This needs "cgroup: don't lose a task in
css_task_iter when a migration fails".

Tested in a VM, with sleeps added by a debug patch that is not part of
this series: cgroups created during a freeze come out frozen, tasks that
move during a freeze or thaw end up in their new cgroup's state, a frozen
task moved ahead of the walk stays frozen, a task whose migration fails
during the walk ends up in its cgroup's state, and frozen_usec stays
sane. The test_freezer selftest passes with lockdep on.

Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 include/linux/cgroup-defs.h |   7 ++
 include/linux/cgroup.h      |   2 +-
 kernel/cgroup/cgroup.c      |  64 +++++++++------
 kernel/cgroup/freezer.c     | 152 +++++++++++++++++++++++++++---------
 4 files changed, 162 insertions(+), 63 deletions(-)

diff --git a/include/linux/cgroup-defs.h b/include/linux/cgroup-defs.h
index a6f42dede900..7c96a2d6cfe9 100644
--- a/include/linux/cgroup-defs.h
+++ b/include/linux/cgroup-defs.h
@@ -455,6 +455,13 @@ struct cgroup_rstat_base_cpu {
 };
 
 struct cgroup_freezer_state {
+	/*
+	 * freeze and e_freeze are protected by css_set_lock.  cgroup_freeze()
+	 * also holds cgroup_freeze_mutex when it changes them.  cgroup_create()
+	 * sets e_freeze of a new cgroup in the css_set_lock section that links
+	 * it to its parent.
+	 */
+
 	/* Should the cgroup and its descendants be frozen. */
 	bool freeze;
 
diff --git a/include/linux/cgroup.h b/include/linux/cgroup.h
index 7279613d6804..7d051aad0f14 100644
--- a/include/linux/cgroup.h
+++ b/include/linux/cgroup.h
@@ -931,7 +931,7 @@ static inline void cgroup_sk_free(struct sock_cgroup_data *skcd) {}
 void cgroup_enter_frozen(void);
 void cgroup_leave_frozen(bool always_leave);
 void cgroup_update_frozen(struct cgroup *cgrp);
-void cgroup_freeze(struct cgroup *cgrp, bool freeze);
+int cgroup_freeze(struct cgroup *cgrp, bool freeze);
 void cgroup_freezer_migrate_task(struct task_struct *task, struct cgroup *src,
 				 struct cgroup *dst);
 
diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c
index cb8d9165ead2..4a4de2b7b552 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -4414,7 +4414,7 @@ static int cgroup_freeze_show(struct seq_file *seq, void *v)
 {
 	struct cgroup *cgrp = seq_css(seq)->cgroup;
 
-	seq_printf(seq, "%d\n", cgrp->freezer.freeze);
+	seq_printf(seq, "%d\n", READ_ONCE(cgrp->freezer.freeze));
 
 	return 0;
 }
@@ -4433,15 +4433,20 @@ static ssize_t cgroup_freeze_write(struct kernfs_open_file *of,
 	if (freeze < 0 || freeze > 1)
 		return -ERANGE;
 
-	cgrp = cgroup_kn_lock_live(of->kn, false);
+	/*
+	 * No cgroup_mutex: cgroup_freeze() has its own writer mutex.  Still
+	 * drop the active reference, so that removing the cgroup doesn't wait
+	 * for a long walk or for another writer.
+	 */
+	cgrp = cgroup_kn_break_active(of->kn);
 	if (IS_ERR(cgrp))
 		return PTR_ERR(cgrp);
 
-	cgroup_freeze(cgrp, freeze);
+	ret = cgroup_freeze(cgrp, freeze);
 
-	cgroup_kn_unlock(of->kn);
+	cgroup_kn_unbreak_active(of->kn, cgrp);
 
-	return nbytes;
+	return ret ?: nbytes;
 }
 
 static void __cgroup_kill(struct cgroup *cgrp)
@@ -4768,7 +4773,12 @@ static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
 
 		timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
 		spin_lock_init(&cfile->lock);
-		cfile->kn = kn;
+		/*
+		 * A cgroup.freeze walk can notify a new cgroup before its
+		 * files are populated, see cgroup_create().  Publish the
+		 * initialized timer and lock with the node.
+		 */
+		smp_store_release(&cfile->kn, kn);
 	}
 
 	return 0;
@@ -5026,7 +5036,8 @@ void cgroup_file_notify(struct cgroup_file *cfile)
 	unsigned long flags, last, next;
 	struct kernfs_node *kn = NULL;
 
-	if (!READ_ONCE(cfile->kn))
+	/* pairs with smp_store_release() in cgroup_add_file() */
+	if (!smp_load_acquire(&cfile->kn))
 		return;
 
 	if (timer_pending(&cfile->notify_timer))
@@ -6274,23 +6285,7 @@ static struct cgroup *cgroup_create(struct cgroup *parent, const char *name,
 	for_each_subsys(ss, i)
 		RCU_INIT_POINTER(cgrp->e_css[i], cgroup_e_css(parent, ss));
 
-	/*
-	 * New cgroup inherits effective freeze counter, and
-	 * if the parent has to be frozen, the child has too.
-	 */
-	cgrp->freezer.e_freeze = parent->freezer.e_freeze;
 	seqcount_spinlock_init(&cgrp->freezer.freeze_seq, &css_set_lock);
-	if (cgrp->freezer.e_freeze) {
-		/*
-		 * Set the CGRP_FREEZE flag, so when a process will be
-		 * attached to the child cgroup, it will become frozen.
-		 * At this point the new cgroup is unpopulated, so we can
-		 * consider it frozen immediately.
-		 */
-		set_bit(CGRP_FREEZE, &cgrp->flags);
-		cgrp->freezer.freeze_start_nsec = ktime_get_ns();
-		set_bit(CGRP_FROZEN, &cgrp->flags);
-	}
 
 	if (notify_on_release(parent))
 		set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
@@ -6309,6 +6304,27 @@ static struct cgroup *cgroup_create(struct cgroup *parent, const char *name,
 
 	/* allocation complete, commit to creation */
 	spin_lock_irq(&css_set_lock);
+
+	/*
+	 * New cgroup inherits effective freeze counter, and if the parent has
+	 * to be frozen, the child has too.  cgroup_freeze() doesn't hold
+	 * cgroup_mutex: inherit and become visible to its descendant walk in
+	 * the same css_set_lock section, so that the walk either sees the new
+	 * cgroup or the new cgroup sees the parent's new state.
+	 */
+	cgrp->freezer.e_freeze = parent->freezer.e_freeze;
+	if (cgrp->freezer.e_freeze) {
+		/*
+		 * Set the CGRP_FREEZE flag, so when a process will be
+		 * attached to the child cgroup, it will become frozen.
+		 * At this point the new cgroup is unpopulated, so we can
+		 * consider it frozen immediately.
+		 */
+		set_bit(CGRP_FREEZE, &cgrp->flags);
+		cgrp->freezer.freeze_start_nsec = ktime_get_ns();
+		set_bit(CGRP_FROZEN, &cgrp->flags);
+	}
+
 	for (i = 0; i < level; i++) {
 		tcgrp = cgrp->ancestors[i];
 		tcgrp->nr_descendants++;
@@ -6321,9 +6337,9 @@ static struct cgroup *cgroup_create(struct cgroup *parent, const char *name,
 		if (cgrp->freezer.e_freeze)
 			tcgrp->freezer.nr_frozen_descendants++;
 	}
-	spin_unlock_irq(&css_set_lock);
 
 	list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
+	spin_unlock_irq(&css_set_lock);
 	atomic_inc(&root->nr_cgrps);
 	cgroup_get_live(parent);
 
diff --git a/kernel/cgroup/freezer.c b/kernel/cgroup/freezer.c
index b905df5e416b..41c8e22668cd 100644
--- a/kernel/cgroup/freezer.c
+++ b/kernel/cgroup/freezer.c
@@ -167,27 +167,37 @@ static void cgroup_freeze_task(struct task_struct *task, bool freeze)
 }
 
 /*
- * Freeze or unfreeze all tasks in the given cgroup.
+ * Set or clear CGRP_FREEZE on a cgroup whose effective freeze state changed.
+ * Read the clock here: a cgroup created during an unfreeze walk takes its
+ * freeze_start_nsec from the time it was created.
  */
-static void cgroup_do_freeze(struct cgroup *cgrp, bool freeze, u64 ts_nsec)
+static void cgroup_set_freeze(struct cgroup *cgrp, bool freeze)
 {
-	struct css_task_iter it;
-	struct task_struct *task;
+	u64 now = ktime_get_ns();
 
-	lockdep_assert_held(&cgroup_mutex);
+	lockdep_assert_held(&css_set_lock);
 
-	spin_lock_irq(&css_set_lock);
 	write_seqcount_begin(&cgrp->freezer.freeze_seq);
 	if (freeze) {
 		set_bit(CGRP_FREEZE, &cgrp->flags);
-		cgrp->freezer.freeze_start_nsec = ts_nsec;
+		cgrp->freezer.freeze_start_nsec = now;
 	} else {
 		clear_bit(CGRP_FREEZE, &cgrp->flags);
-		cgrp->freezer.frozen_nsec += (ts_nsec -
-			cgrp->freezer.freeze_start_nsec);
+		cgrp->freezer.frozen_nsec +=
+			now - cgrp->freezer.freeze_start_nsec;
 	}
 	write_seqcount_end(&cgrp->freezer.freeze_seq);
-	spin_unlock_irq(&css_set_lock);
+}
+
+/*
+ * Freeze or unfreeze all tasks in the given cgroup after its CGRP_FREEZE
+ * changed.
+ */
+static void cgroup_do_freeze(struct cgroup *cgrp, bool freeze)
+{
+	struct css_task_iter it;
+	struct task_struct *task;
+	struct cgroup *tcgrp;
 
 	if (freeze)
 		TRACE_CGROUP_PATH(freeze, cgrp);
@@ -202,7 +212,17 @@ static void cgroup_do_freeze(struct cgroup *cgrp, bool freeze, u64 ts_nsec)
 		 */
 		if (task->flags & PF_KTHREAD)
 			continue;
-		cgroup_freeze_task(task, freeze);
+
+		/*
+		 * Without cgroup_mutex, @task can have migrated since the
+		 * iterator returned it, and cgroup_freezer_migrate_task() has
+		 * already set it to its new cgroup's state.  Set it to the
+		 * state of the cgroup it is in now.
+		 */
+		spin_lock_irq(&css_set_lock);
+		tcgrp = task_dfl_cgroup(task);
+		cgroup_freeze_task(task, test_bit(CGRP_FREEZE, &tcgrp->flags));
+		spin_unlock_irq(&css_set_lock);
 	}
 	css_task_iter_end(&it);
 
@@ -232,11 +252,18 @@ void cgroup_freezer_migrate_task(struct task_struct *task,
 
 	/*
 	 * It's not necessary to do changes if both of the src and dst cgroups
-	 * are not freezing and task is not frozen.
+	 * are not freezing and task is not frozen, unless the task still has
+	 * the freeze trap set: an unfreeze clears CGRP_FREEZE before it gets
+	 * to the tasks.
 	 */
 	if (!test_bit(CGRP_FREEZE, &src->flags) &&
 	    !test_bit(CGRP_FREEZE, &dst->flags) &&
-	    !task->frozen)
+	    !task->frozen &&
+	    /*
+	     * The trap bit is set and cleared under css_set_lock, but other
+	     * jobctl bits change under siglock alone.
+	     */
+	    !data_race(task->jobctl & JOBCTL_TRAP_FREEZE))
 		return;
 
 	/*
@@ -257,55 +284,75 @@ void cgroup_freezer_migrate_task(struct task_struct *task,
 	cgroup_freeze_task(task, test_bit(CGRP_FREEZE, &dst->flags));
 }
 
-void cgroup_freeze(struct cgroup *cgrp, bool freeze)
+/*
+ * Serializes cgroup.freeze writers.  The freeze state is protected by
+ * css_set_lock, which cgroup_create() uses to inherit it, so cgroup_mutex is
+ * not needed.
+ */
+static DEFINE_MUTEX(cgroup_freeze_mutex);
+
+int cgroup_freeze(struct cgroup *cgrp, bool freeze)
 {
 	struct cgroup_subsys_state *css;
-	struct cgroup *parent;
-	struct cgroup *dsct;
 	bool applied = false;
-	u64 ts_nsec;
-	bool old_e;
+	int ret = 0;
 
-	lockdep_assert_held(&cgroup_mutex);
+	mutex_lock(&cgroup_freeze_mutex);
 
 	/*
-	 * Nothing changed? Just exit.
+	 * rmdir clears CSS_ONLINE under css_set_lock, so the write takes effect
+	 * before the cgroup is removed or fails.  Nothing changed? Just exit.
 	 */
-	if (cgrp->freezer.freeze == freeze)
-		return;
-
-	cgrp->freezer.freeze = freeze;
-	ts_nsec = ktime_get_ns();
+	spin_lock_irq(&css_set_lock);
+	if (cgroup_is_dead(cgrp))
+		ret = -ENODEV;
+	if (ret || cgrp->freezer.freeze == freeze) {
+		spin_unlock_irq(&css_set_lock);
+		goto out_unlock;
+	}
+	WRITE_ONCE(cgrp->freezer.freeze, freeze);
+	spin_unlock_irq(&css_set_lock);
 
 	/*
-	 * Propagate changes downwards the cgroup tree.
+	 * Propagate changes downwards the cgroup tree.  Set the new state of
+	 * every cgroup first and walk the tasks after that, so that a task that
+	 * moves inside the subtree during the task walk lands in a cgroup that
+	 * already has the new state.  New cgroups inherit e_freeze from their
+	 * parent under css_set_lock and become visible to this walk in the same
+	 * critical section, see cgroup_create().  Removed cgroups are skipped.
+	 * A cgroup removed during the walk only has exiting tasks, and
+	 * cgroup_update_frozen() leaves it alone.
 	 */
+	rcu_read_lock();
 	css_for_each_descendant_pre(css, &cgrp->self) {
-		dsct = css->cgroup;
+		struct cgroup *dsct = css->cgroup;
+		bool e_freeze;
 
-		if (cgroup_is_dead(dsct))
+		spin_lock_irq(&css_set_lock);
+		if (cgroup_is_dead(dsct)) {
+			spin_unlock_irq(&css_set_lock);
+			css = css_rightmost_descendant(css);
 			continue;
+		}
 
 		/*
 		 * e_freeze is affected by parent's e_freeze and dst's freeze.
 		 * If old e_freeze eq new e_freeze, no change, its children
 		 * will not be affected. So do nothing and skip the subtree
 		 */
-		old_e = dsct->freezer.e_freeze;
-		parent = cgroup_parent(dsct);
-		dsct->freezer.e_freeze = (dsct->freezer.freeze ||
-					  parent->freezer.e_freeze);
-		if (dsct->freezer.e_freeze == old_e) {
+		e_freeze = dsct->freezer.freeze ||
+			   cgroup_parent(dsct)->freezer.e_freeze;
+		if (dsct->freezer.e_freeze == e_freeze) {
+			spin_unlock_irq(&css_set_lock);
 			css = css_rightmost_descendant(css);
 			continue;
 		}
-
-		/*
-		 * Do change actual state: freeze or unfreeze.
-		 */
-		cgroup_do_freeze(dsct, freeze, ts_nsec);
+		dsct->freezer.e_freeze = e_freeze;
+		cgroup_set_freeze(dsct, e_freeze);
+		spin_unlock_irq(&css_set_lock);
 		applied = true;
 	}
+	rcu_read_unlock();
 
 	/*
 	 * Even if the actual state hasn't changed, let's notify a user.
@@ -319,5 +366,34 @@ void cgroup_freeze(struct cgroup *cgrp, bool freeze)
 		TRACE_CGROUP_PATH(notify_frozen, cgrp,
 				  test_bit(CGRP_FROZEN, &cgrp->flags));
 		cgroup_file_notify(&cgrp->events_file);
+		goto out_unlock;
+	}
+
+	/*
+	 * Do change actual state: freeze or unfreeze the tasks of the cgroups
+	 * changed above.  A descendant with its own freeze set kept its state,
+	 * and so did its subtree.  Only writers, which hold
+	 * cgroup_freeze_mutex, change freeze.
+	 */
+	rcu_read_lock();
+	css_for_each_descendant_pre(css, &cgrp->self) {
+		if (css != &cgrp->self && css->cgroup->freezer.freeze) {
+			css = css_rightmost_descendant(css);
+			continue;
+		}
+		if (!css_tryget_online(css))
+			continue;
+		rcu_read_unlock();
+
+		cgroup_do_freeze(css->cgroup, freeze);
+		cond_resched();
+
+		rcu_read_lock();
+		css_put(css);
 	}
+	rcu_read_unlock();
+
+out_unlock:
+	mutex_unlock(&cgroup_freeze_mutex);
+	return ret;
 }
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 12+ messages in thread

end of thread, other threads:[~2026-11-30 17:35 UTC | newest]

Thread overview: 12+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-30 17:34 [PATCH v2 00/11] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 01/11] cgroup: don't lose a task in css_task_iter when a migration fails Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 02/11] cgroup: kill a child forked while cgroup.kill runs Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 03/11] cgroup/freezer: check own tasks and descendants for the frozen state Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 04/11] cgroup/freezer: don't update the frozen state of removed cgroups Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 05/11] cgroup/freezer: test the freeze trap bit under siglock Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 06/11] selftests/cgroup: test cgroup.procs reads across a failed migration Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 07/11] selftests/cgroup: test the frozen state of a cgroup with tasks and children Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 08/11] selftests/cgroup: test cgroup.kill in a threaded cgroup Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 09/11] cgroup: factor out cgroup_kn_break_active() and cgroup_kn_unbreak_active() Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 10/11] cgroup: don't hold cgroup_mutex for cgroup.kill Shakeel Butt
2026-11-30 17:34 ` [PATCH v2 11/11] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze Shakeel Butt

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox