All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH v3 12/12] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze
  2026-12-04 18:40 [PATCH v3 00/12] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
@ 2026-12-04 18:40 ` Shakeel Butt
  2026-12-05 18:42   ` sashiko-bot
  0 siblings, 1 reply; 5+ messages in thread
From: Shakeel Butt @ 2026-12-04 18:40 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.

 - The first pass marks the cgroups whose state it changes, and the
   second pass walks only those. A cgroup created during the walk
   inherits the new state and needs no walk, also when it is created
   below a subtree that the walk skipped. For a changed cgroup whose
   subtree has no tasks, the first pass also emits the trace event and
   updates the frozen state, so the second pass can skip the branch. In
   an 8-CPU VM without lock debugging, a freeze or thaw write to a cgroup
   with 1,024 empty children took a median of 183 us, against 416 us with
   two full passes and 273 us before this patch.

 - 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.

Co-developed-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 include/linux/cgroup-defs.h |  13 +++
 include/linux/cgroup.h      |   2 +-
 kernel/cgroup/cgroup.c      |  64 +++++++++-----
 kernel/cgroup/freezer.c     | 169 ++++++++++++++++++++++++++++--------
 4 files changed, 188 insertions(+), 60 deletions(-)

diff --git a/include/linux/cgroup-defs.h b/include/linux/cgroup-defs.h
index 44e69e784057..aad599cf3283 100644
--- a/include/linux/cgroup-defs.h
+++ b/include/linux/cgroup-defs.h
@@ -455,12 +455,25 @@ 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;
 
 	/* Should the cgroup actually be frozen? */
 	bool e_freeze;
 
+	/*
+	 * The cgroup_freeze() call that last changed e_freeze.  Only
+	 * cgroup_freeze() uses it, with cgroup_freeze_mutex held.
+	 */
+	unsigned int walk_seq;
+
 	/* Fields below are protected by css_set_lock */
 
 	/* Number of frozen descendant cgroups */
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 070d15f4031d..aa7832cc9e1d 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -4451,7 +4451,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;
 }
@@ -4470,15 +4470,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;
 }
 
 /*
@@ -4825,7 +4830,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;
@@ -5083,7 +5093,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))
@@ -6331,23 +6342,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);
@@ -6366,6 +6361,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++;
@@ -6378,9 +6394,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..214704444906 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,96 @@ 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);
+
+/* Numbers the cgroup_freeze() calls, protected by cgroup_freeze_mutex */
+static unsigned int cgroup_freeze_seq;
+
+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;
+	unsigned int seq;
+	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);
+	seq = ++cgroup_freeze_seq;
 
 	/*
-	 * 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.  The first pass marks the
+	 * cgroups it changes with @seq for the second pass.
 	 */
+	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;
 		}
+		dsct->freezer.e_freeze = e_freeze;
+		dsct->freezer.walk_seq = seq;
+		cgroup_set_freeze(dsct, e_freeze);
 
 		/*
-		 * Do change actual state: freeze or unfreeze.
+		 * No task in an empty subtree needs to be signalled.  Update its
+		 * frozen state now, so that the second pass can skip the whole
+		 * branch.  Tasks that enter it later get the new CGRP_FREEZE
+		 * state when they fork or migrate.
 		 */
-		cgroup_do_freeze(dsct, freeze, ts_nsec);
+		if (!cgroup_is_populated(dsct)) {
+			if (e_freeze)
+				TRACE_CGROUP_PATH(freeze, dsct);
+			else
+				TRACE_CGROUP_PATH(unfreeze, dsct);
+			cgroup_update_frozen(dsct);
+		}
+		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 +387,36 @@ 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, and only of those.  A cgroup that the first pass didn't
+	 * mark kept its state, was removed, or was created after the first pass
+	 * visited its parent, and so was its whole subtree.  Subtrees without
+	 * tasks were done in the first pass.
+	 */
+	rcu_read_lock();
+	css_for_each_descendant_pre(css, &cgrp->self) {
+		if (css->cgroup->freezer.walk_seq != seq ||
+		    !cgroup_is_populated(css->cgroup)) {
+			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] 5+ messages in thread

* Re: [PATCH v3 12/12] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze
@ 2026-12-04 23:16 Espen Tveit
  2026-12-04 23:35 ` Shakeel Butt
  0 siblings, 1 reply; 5+ messages in thread
From: Espen Tveit @ 2026-12-04 23:16 UTC (permalink / raw)
  To: Shakeel Butt
  Cc: Tejun Heo, 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@vger.kernel.org,
	linux-mm@kvack.org, linux-kernel@vger.kernel.org

Hi Shakeel,

While experimenting with a TLA+ solver (warpspec) against patch 12, I
found two races between pass 1 and pass 2. Details follow (LLM-drafted,
cross-checked against the patch code):

On Fri, Dec 04, 2026 at 10:40:41AM -0800, Shakeel Butt wrote:
> +		dsct->freezer.e_freeze = e_freeze;
> +		dsct->freezer.walk_seq = seq;
> +		cgroup_set_freeze(dsct, e_freeze);
> +
> +		if (!cgroup_is_populated(dsct)) {
> +			if (e_freeze)
> +				TRACE_CGROUP_PATH(freeze, dsct);
> +			else
> +				TRACE_CGROUP_PATH(unfreeze, dsct);
> +			cgroup_update_frozen(dsct);
> +		}
> +		spin_unlock_irq(&css_set_lock);
...
> +	rcu_read_lock();
> +	css_for_each_descendant_pre(css, &cgrp->self) {
> +		if (css->cgroup->freezer.walk_seq != seq ||
> +		    !cgroup_is_populated(css->cgroup)) {
> +			css = css_rightmost_descendant(css);
> +			continue;
> +		}

1) Permanent CGRP_FROZEN=0 after freezing an ancestor with an already-frozen child.

Take A/B where A is unfrozen with 0 direct tasks, and B is already frozen
(CGRP_FREEZE=1, CGRP_FROZEN=1) with one frozen task T.  So
A->nr_frozen_descendants == A->nr_descendants == 1, and
cgroup_is_populated(A) is true (via B).

  CPU0 (echo 1 > A/cgroup.freeze)          CPU1 (migrate T out of B)
  -------------------------------          -------------------------
  pass 1 on A:
    A->e_freeze = 1, walk_seq = seq
    cgroup_set_freeze(A, true)
    cgroup_is_populated(A) is true ->
      skip cgroup_update_frozen(A)
    unlock css_set_lock
  pass 1 on B:
    B->e_freeze already 1 -> skip B
                                           migrate T from B to outside cgroup C
                                           cgroup_update_frozen(B):
                                             B stays CGRP_FROZEN=1 -> delta == 0,
                                             does not propagate to A
                                           cgroup_is_populated(A) is now false
  pass 2 on A:
    !cgroup_is_populated(A) is true ->
      skip A (never calls cgroup_do_freeze(A)
      or cgroup_update_frozen(A))

cgroup_freeze(A, true) returns 0 with A having CGRP_FREEZE=1, 0 tasks, and
its only child B frozen, yet A stays at CGRP_FROZEN=0 until something else
re-evaluates A (e.g., a task enters A or a child changes state / is removed).

2) Transient CGRP_FROZEN=1 with a running task on unfreeze.

Take B frozen (CGRP_FREEZE=1, CGRP_FROZEN=1) with a frozen task T2, and an
unfrozen cgroup A with a running task T1.

  CPU0 (echo 0 > B/cgroup.freeze)          CPU1 (migrate T1 from A to B)
  -------------------------------          -----------------------------
  pass 1 on B:
    B->e_freeze = 0
    cgroup_set_freeze(B, false)
    cgroup_is_populated(B) is true ->
      skip cgroup_update_frozen(B)
    unlock css_set_lock
    (B now has CGRP_FREEZE=0, CGRP_FROZEN=1)
                                           cgroup_freezer_migrate_task(T1, A, B):
                                             !CGRP_FREEZE(A) && !CGRP_FREEZE(B) &&
                                             !T1->frozen && !JOBCTL_TRAP_FREEZE ->
                                             returns early without calling
                                             cgroup_update_frozen(B)

T1 runs in B while B still reports frozen=1 until T2 leaves the frozen
state or pass 2 reaches B.

Moving cgroup_update_frozen(dsct) outside the !cgroup_is_populated(dsct)
check in pass 1 (css_set_lock is already held there) closes both in the
model without double-emitting the trace event:

		if (!cgroup_is_populated(dsct)) {
			if (e_freeze)
				TRACE_CGROUP_PATH(freeze, dsct);
			else
				TRACE_CGROUP_PATH(unfreeze, dsct);
		}
		cgroup_update_frozen(dsct);

On freeze, A transitions to CGRP_FROZEN=1 in pass 1 when it has no
unfrozen direct tasks and all descendants are already frozen; on unfreeze,
CGRP_FROZEN is cleared in the same css_set_lock section as CGRP_FREEZE so
the fast path in cgroup_freezer_migrate_task() remains valid.

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

* Re: [PATCH v3 12/12] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze
  2026-12-04 23:16 [PATCH v3 12/12] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze Espen Tveit
@ 2026-12-04 23:35 ` Shakeel Butt
  2026-12-05  2:10   ` Espen Tveit
  0 siblings, 1 reply; 5+ messages in thread
From: Shakeel Butt @ 2026-12-04 23:35 UTC (permalink / raw)
  To: Espen Tveit
  Cc: Tejun Heo, 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@vger.kernel.org,
	linux-mm@kvack.org, linux-kernel@vger.kernel.org

Hi Espen,

On Fri, Dec 04, 2026 at 11:16:50PM +0000, Espen Tveit wrote:
> Hi Shakeel,
> 
> While experimenting with a TLA+ solver (warpspec) against patch 12, I
> found two races between pass 1 and pass 2. Details follow (LLM-drafted,
> cross-checked against the patch code):

Thanks for the report, I will take a look. Can you also run your TLA+ solver
against patch 11 ("cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze")?


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

* Re: [PATCH v3 12/12] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze
  2026-12-04 23:35 ` Shakeel Butt
@ 2026-12-05  2:10   ` Espen Tveit
  0 siblings, 0 replies; 5+ messages in thread
From: Espen Tveit @ 2026-12-05  2:10 UTC (permalink / raw)
  To: Shakeel Butt
  Cc: Tejun Heo, 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@vger.kernel.org,
	linux-mm@kvack.org, linux-kernel@vger.kernel.org

Hi Shakeel,

I ran TLA+ models of patch 11 ("cgroup: don't hold cgroup_mutex for
cgroup.kill") exhaustively with warpspec. No violations were found on
the patch as posted, and disabling each added safeguard individually
reproduces the bug it is meant to prevent.

What was checked (LLM-drafted):

Two models:
- domain: root/A/B with sibling root/C, modeling processes and rmdir
- threaded: root/A/B/C with sibling root/D, modeling individual threads
  and switches to threaded

Each run explores all interleavings of kills, forks (including
CLONE_THREAD and CLONE_INTO_CGROUP), and migrations, bounded to 1-3
forks and 1-2 migrations. Below, "host" means a writer in the initial
pid ns, and "in-ns" means a writer inside the child pid ns (same ns as
the pid ns init).

Properties checked in every run:
 - every process in the tree at kill start, and every child it forks,
   gets SIGKILL
 - a pid ns init is killed only by a writer outside its pid ns
 - no process with threads outside the tree is killed
 - nr_killing / nr_subtree_kills return to 0 after all writers finish

Patch as posted:

  scenario                                           states  fork/mig
  -------------------------------------------------  ------  --------
  domain:   1 host kill on A                            24M    2/2
  domain:   1 in-ns kill on A                           13M    2/2
  domain:   host kills on A & B, pid ns init in B     3.14G    2/2
  domain:   in-ns kills on A & B                      1.20G    2/2
  domain:   host kill on B + in-ns kill on A          2.67G    2/2
  domain:   2 overlapping host kills on A             9.18G    2/2
  domain:   host kills on A & C, tasks moving         9.22G    3/2
  threaded: switches to threaded vs kill below          33M    1/2
  threaded: kill on thread root B vs switch of A        49M    1/2
  threaded: host kill on A, init threads in B          927M    2/2
  threaded: in-ns kill on A, init threads in B         998M    2/2
  threaded: host kill on A + in-ns kill on B           464M    1/1

  All pass.

Each mechanism was disabled on the same scenario as a passing run
above (the migration kill and the CLONE_INTO_CGROUP check on "1 host
kill on A", the EBUSY checks on "kill on thread root B vs switch of
A", and the post_fork force on "host kill on A, init threads in B");
in each case the model finds the bug it prevents.

Limitations / not modeled:
- Locked sections are atomic steps, and unlocked reads such as
  cgroup_is_populated() are treated as consistent snapshots.
- The task walk is assumed to return every task that stays in its
  cgroup (checked separately for patch 01).
- Not modeled: CLONE_NEWPID children, controller-driven css_set
  changes, the extra threaded css_sets visited by
  CSS_TASK_ITER_THREADED, lock ordering, refcount lifetimes, and
  memory ordering (covered by lockdep / KCSAN rather than the model).

Overall, patch 11's concurrency logic looks solid; the two races
between pass 1 and pass 2 of patch 12 (cgroup_update_frozen() skipped
for populated cgroups in pass 1) were the only issues found in the
series.

Thanks,
Espen
________________________________________
From: Shakeel Butt <shakeel.butt@linux.dev>
Sent: Saturday, December 5, 2026 12:35 AM
To: Espen Tveit
Cc: Tejun Heo; 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@vger.kernel.org; linux-mm@kvack.org; linux-kernel@vger.kernel.org
Subject: Re: [PATCH v3 12/12] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze

Hi Espen,

On Fri, Dec 04, 2026 at 11:16:50PM +0000, Espen Tveit wrote:
> Hi Shakeel,
>
> While experimenting with a TLA+ solver (warpspec) against patch 12, I
> found two races between pass 1 and pass 2. Details follow (LLM-drafted,
> cross-checked against the patch code):

Thanks for the report, I will take a look. Can you also run your TLA+ solver
against patch 11 ("cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze")?

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

* Re: [PATCH v3 12/12] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze
  2026-12-04 18:40 ` [PATCH v3 12/12] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze Shakeel Butt
@ 2026-12-05 18:42   ` sashiko-bot
  0 siblings, 0 replies; 5+ messages in thread
From: sashiko-bot @ 2026-12-05 18:42 UTC (permalink / raw)
  To: Shakeel Butt, 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, linux-mm

Thank you for your contribution! Sashiko AI review found 7 potential
issues to consider:
- [High] cgroup/freezer: stale CGRP_FROZEN on depopulation during
  cgroup_freeze()
- [High] cgroup/freezer: cgroup_freeze() pass 2 skips cgroups
  depopulated after pass 1
- [Medium] cgroup/freezer: unbroken rcu_read_lock() in cgroup_freeze()
  pass 1 walk
- [Medium] cgroup/freezer: cgroup_do_freeze() holds css_set_lock across
  task wakeups
- [Medium] cgroup/freezer: cgroup_freeze() locks css_set_lock before
  cgroup_is_dead()
- [Low] cgroup/freezer: 32-bit cgroup_freeze_seq wraparound collides
  with walk_seq
- [Low] cgroup/freezer: pass 2 scans all children on empty root in
  cgroup_freeze()
--

commit 1daf17f41b09f5eb26f17c686d2813abbc4f604d
Author: Shakeel Butt <shakeel.butt@linux.dev>

cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze

This commit replaces cgroup_mutex in cgroup.freeze with a dedicated
cgroup_freeze_mutex and css_set_lock.  It splits the subtree update into an
RCU pass that updates cgroup freeze state and a second pass that signals
tasks in populated cgroups.

> diff --git a/kernel/cgroup/freezer.c b/kernel/cgroup/freezer.c
> index b905df5e416bf..214704444906c 100644
> --- a/kernel/cgroup/freezer.c
> +++ b/kernel/cgroup/freezer.c

[ ... ]

> @@ -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);

[Severity: Medium]
Does holding global css_set_lock across cgroup_freeze_task() create heavy
lock contention when freezing or thawing a populated cgroup?

css_task_iter_next() already acquires and drops css_set_lock for each task,
and re-acquiring it here holds the IRQ-disabled spinlock across
lock_task_sighand() and signal_wake_up() or wake_up_process() (taking
pi_lock, rq->lock, and sending reschedule IPIs).  Each signalled or woken
task then immediately contends on css_set_lock in cgroup_enter_frozen() or
cgroup_leave_frozen(), compounding contention with host-wide fork and exit.

Only reading task_dfl_cgroup(), testing CGRP_FREEZE, and updating
JOBCTL_TRAP_FREEZE (plus setting TIF_SIGPENDING on freeze) need
css_set_lock; the wakeup or kick can run after releasing siglock and
css_set_lock.

[ ... ]

> @@ -257,55 +284,96 @@ 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);
> +
> +/* Numbers the cgroup_freeze() calls, protected by cgroup_freeze_mutex */
> +static unsigned int cgroup_freeze_seq;
> +
> +int cgroup_freeze(struct cgroup *cgrp, bool freeze)

[ ... ]

> +	WRITE_ONCE(cgrp->freezer.freeze, freeze);
> +	spin_unlock_irq(&css_set_lock);
> +	seq = ++cgroup_freeze_seq;

[Severity: Low]
Can 32-bit cgroup_freeze_seq wrap around to 0 and collide with walk_seq?

cgroup_create() zero-initializes walk_seq, and cgroup_freeze_seq increments
without skipping 0.  After 2^32 state-changing writes, pass 2 will falsely
match untouched or newly created populated cgroups (or long-lived cgroups
holding an earlier matching walk_seq) and call cgroup_do_freeze() on
subtrees that pass 1 skipped, emitting wrong freeze/unfreeze trace events
and doing extra task walks and wakeups.  Using u64 for cgroup_freeze_seq
and walk_seq avoids wraparound.

[ ... ]

> +	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;
> +		}

[Severity: Medium]
Should pass 1 check cgroup_is_dead(dsct) before acquiring css_set_lock?

Dying cgroups remain on parent->self.children until subsystem references
such as memcg drain, so a subtree with many lingering dead cgroups will
repeatedly bounce global css_set_lock in a tight loop and contend with
host-wide fork and exit.  Because CSS_ONLINE only transitions 1->0 and
cgroup_is_dead() already uses READ_ONCE(), a lockless fast-path check
before spin_lock_irq(&css_set_lock) (keeping the locked re-check for
concurrent rmdir) avoids taking the lock for dead cgroups.

[ ... ]

> +		dsct->freezer.e_freeze = e_freeze;
> +		dsct->freezer.walk_seq = seq;
> +		cgroup_set_freeze(dsct, e_freeze);
>  
>  		/*
> -		 * Do change actual state: freeze or unfreeze.
> +		 * No task in an empty subtree needs to be signalled.  Update its
> +		 * frozen state now, so that the second pass can skip the whole
> +		 * branch.  Tasks that enter it later get the new CGRP_FREEZE
> +		 * state when they fork or migrate.
>  		 */
> -		cgroup_do_freeze(dsct, freeze, ts_nsec);
> +		if (!cgroup_is_populated(dsct)) {
> +			if (e_freeze)
> +				TRACE_CGROUP_PATH(freeze, dsct);
> +			else
> +				TRACE_CGROUP_PATH(unfreeze, dsct);
> +			cgroup_update_frozen(dsct);
> +		}
> +		spin_unlock_irq(&css_set_lock);
>  		applied = true;
>  	}
> +	rcu_read_unlock();

[Severity: Medium]
Can this unbroken rcu_read_lock() stall RCU grace periods or trigger
softlockups on large or deep hierarchies?

max_descendants and max_depth default to INT_MAX, and each iteration takes
css_set_lock, formats tracepoint paths, and for unpopulated cgroups calls
cgroup_update_frozen(), which walks all ancestors up to the root (O(D^2)
steps when unfreezing a chain of depth D).  Periodically pinning css,
dropping rcu_read_lock(), and calling cond_resched() on need_resched(), as
pass 2 already does, would avoid stalling RCU and preemption on
!CONFIG_PREEMPT_RCU kernels.

[ ... ]

> +	rcu_read_lock();
> +	css_for_each_descendant_pre(css, &cgrp->self) {
> +		if (css->cgroup->freezer.walk_seq != seq ||
> +		    !cgroup_is_populated(css->cgroup)) {
> +			css = css_rightmost_descendant(css);
> +			continue;
> +		}

[Severity: High]
Can skipping !cgroup_is_populated() here leave CGRP_FROZEN permanently
stale if a cgroup becomes unpopulated between pass 1 and pass 2?

Suppose parent P has no direct tasks and an independently frozen child C
(C->freezer.freeze == 1, CGRP_FROZEN == 1) with a frozen task T:

CPU0                              CPU1
cgroup_freeze(P, true/false)
  pass 1:
    cgroup_set_freeze(P, ...)
    cgroup_is_populated(P) == true
    (skips cgroup_update_frozen(P))
    (skips C: e_freeze unchanged)
                                  cgroup_migrate_execute() (T: C -> U)
                                    css_set_move_task()
                                      (depopulates C and P)
                                    cgroup_freezer_migrate_task()
                                      cgroup_update_frozen(C)
                                        (C stays frozen, delta == 0;
                                         returns without updating P)
  pass 2:
    !cgroup_is_populated(P)
    css = css_rightmost_descendant()  <-- skips cgroup_update_frozen(P)

On freeze, P stays permanently stuck at CGRP_FROZEN == 0 and userspace
waiting on cgroup.events hangs; on unfreeze, P stays stuck at
CGRP_FROZEN == 1 with ancestors' nr_frozen_descendants permanently
inflated by 1.

In the opposite direction, because pass 1 sets walk_seq even when
!cgroup_is_populated(dsct), a task entering dsct before pass 2 causes pass
2 to run cgroup_do_freeze() and emit a duplicate freeze/unfreeze trace
event.  Setting walk_seq = seq only when cgroup_is_populated(dsct) in pass
1 and checking only walk_seq != seq in pass 2 would fix both races.

[Severity: High]
Can an exiting task finishing in a dying child also depopulate a parent
between pass 1 and pass 2 and leave its CGRP_FROZEN permanently stale?

If child D of P was removed by rmdir while an exiting task T was past
exit_signals(), D keeps P populated until do_cgroup_task_dead():

CPU0                              CPU1
cgroup_freeze(P, true/false)
  pass 1:
    cgroup_set_freeze(P, ...)
    cgroup_is_populated(P) == true
    (skips cgroup_update_frozen(P))
    (skips dead child D)
                                  do_cgroup_task_dead(T)
                                    css_set_move_task()
                                      (depopulates D and P)
                                    cgroup_update_frozen(D)
                                      cgroup_is_dead(D) -> returns
                                      (P is never updated)
  pass 2:
    !cgroup_is_populated(P)
    css = css_rightmost_descendant()  <-- skips cgroup_update_frozen(P)

Because cgroup_update_frozen() returns immediately for a dead cgroup, P
never gets its CGRP_FROZEN flag or ancestor nr_frozen_descendants updated.

[Severity: Low]
Does pass 2 still perform an O(N) walk of all immediate children when the
entire subtree is empty?

When cgrp has no tasks in its subtree, pass 1 handles every changed cgroup
and sets applied = true, so pass 2 still starts at &cgrp->self, sees
!cgroup_is_populated(cgrp), and calls css_rightmost_descendant(&cgrp->self).
Because ->prev is not RCU-safe, css_rightmost_descendant() linearly walks
every child in cgrp->self.children before exiting the loop.  Tracking
whether pass 1 encountered any populated changed cgroup (or skipping pass 2
when !cgroup_is_populated(cgrp)) avoids this traversal.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261204184041.1489976-1-shakeel.butt@linux.dev?part=12


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

end of thread, other threads:[~2026-12-05 18:42 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-04 23:16 [PATCH v3 12/12] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze Espen Tveit
2026-12-04 23:35 ` Shakeel Butt
2026-12-05  2:10   ` Espen Tveit
  -- strict thread matches above, loose matches on Subject: below --
2026-12-04 18:40 [PATCH v3 00/12] cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze Shakeel Butt
2026-12-04 18:40 ` [PATCH v3 12/12] cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze Shakeel Butt
2026-12-05 18:42   ` sashiko-bot

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.