cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze
Subsystems (5)
cover cgroup: don't hold cgroup_mutex for cgroup.kill and cgroup.freeze
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-4 fix bugs found while auditing these paths. They don't depend on the rest and can be taken first. Patches 1-3 are tagged for stable; patch 3 needs patch 2.
1. A child forked while cgroup.kill walks its parent's cgroup can survive the kill.
2. 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.
3. rmdir of a cgroup whose last task is still exiting breaks the ancestors' frozen counts, so they can stop reporting frozen=1.
4. cgroup_leave_frozen() tests the freeze trap bit without siglock.
Patch 5 adds a selftest for bug 2, and patch 6 a selftest for cgroup.kill in threaded cgroups, which must keep working. Patch 7 splits the kernfs active reference handling out of cgroup_kn_lock_live(). Patch 8 moves cgroup.kill off cgroup_mutex and patch 9 does the same for cgroup.freeze.
Without cgroup_mutex, cgroup.kill (patch 8) keeps its guarantees this way:
- Fork: a child forked while a walk runs is killed, as in patch 1, 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. 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.
Two behaviours change, and patch 8 documents both:
- 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.
- 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 9) gets a mutex of its own for writers. New cgroups inherit the freeze state under css_set_lock, 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-3: 2 and 3 need no kernel changes, 1 needs a sleep added by a debug patch. Bug 4 was found by reading the code. The selftest in patch 5 fails without patch 2;
- race tests that widen each new window with sleeps from the same debug patch. Each passes, and fails with its protection turned off;
- a random stress test (freeze, kill, migration, fork, clone3, 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.
Shakeel Butt (9):
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 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 | 9 +- include/linux/cgroup-defs.h | 24 +- include/linux/cgroup.h | 4 +- include/linux/sched/task.h | 1 + kernel/cgroup/cgroup.c | 347 ++++++++++++++---- kernel/cgroup/freezer.c | 208 +++++++---- tools/testing/selftests/cgroup/test_freezer.c | 105 ++++++ tools/testing/selftests/cgroup/test_kill.c | 68 ++++ 8 files changed, 605 insertions(+), 161 deletions(-)
base-commit: 14dbe5fa6933de380a1e75dc5ad83c22eef70a0b
Signature · 1 line
2.53.1-Meta
PATCH 1/9 cgroup: kill a child forked while cgroup.kill runs
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.
--- include/linux/cgroup-defs.h | 5 +++-- kernel/cgroup/cgroup.c | 15 ++++++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-)
include/linux/cgroup-defs.h +3 -2
@@ -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;
kernel/cgroup/cgroup.c +14 -1
@@ -4300,6 +4300,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);
@@ -4317,6 +4325,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)
@@ -7179,7 +7191,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);
Signature · 1 line
2.53.1-Meta
PATCH 2/9 cgroup/freezer: check own tasks and descendants for the frozen state
In reply to Shakeel ButtA 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.
--- kernel/cgroup/freezer.c | 63 ++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 39 deletions(-)
kernel/cgroup/freezer.c +24 -39
@@ -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); }
Signature · 1 line
2.53.1-Meta
PATCH 3/9 cgroup/freezer: don't update the frozen state of removed cgroups
In reply to Shakeel ButtSince 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 relies on the previous patch.
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.
--- include/linux/cgroup.h | 2 +- kernel/cgroup/cgroup.c | 33 +++++++++++++++++++-------------- kernel/cgroup/freezer.c | 8 ++++++++ 3 files changed, 28 insertions(+), 15 deletions(-)
include/linux/cgroup.h +1 -1
@@ -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)
kernel/cgroup/cgroup.c +19 -14
@@ -6397,25 +6397,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++;
@@ -6426,8 +6418,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,
kernel/cgroup/freezer.c +8 -0
@@ -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;
Signature · 1 line
2.53.1-Meta
PATCH 4/9 cgroup/freezer: test the freeze trap bit under siglock
In reply to Shakeel ButtWhen 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.
--- kernel/cgroup/freezer.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-)
kernel/cgroup/freezer.c +10 -3
@@ -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 (¤t->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 (¤t->sighand->siglock); }spin_unlock_irq (&css_set_lock);
Signature · 1 line
2.53.1-Meta
PATCH 5/9 selftests/cgroup: test the frozen state of a cgroup with tasks and children
In reply to Shakeel ButtAdd 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.
--- tools/testing/selftests/cgroup/test_freezer.c | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+)
tools/testing/selftests/cgroup/test_freezer.c +105 -0
@@ -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),
Signature · 1 line
2.53.1-Meta
PATCH 6/9 selftests/cgroup: test cgroup.kill in a threaded cgroup
In reply to Shakeel ButtCheck 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.
--- tools/testing/selftests/cgroup/test_kill.c | 68 ++++++++++++++++++++++ 1 file changed, 68 insertions(+)
tools/testing/selftests/cgroup/test_kill.c +68 -0
@@ -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
Signature · 1 line
2.53.1-Meta
PATCH 7/9 cgroup: factor out cgroup_kn_break_active() and cgroup_kn_unbreak_active()
In reply to Shakeel ButtMove 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.
--- kernel/cgroup/cgroup.c | 52 ++++++++++++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 15 deletions(-)
kernel/cgroup/cgroup.c +37 -15
@@ -1640,6 +1640,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
@@ -1660,9 +1691,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); }/**
@@ -1688,26 +1717,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 {
Signature · 1 line
2.53.1-Meta
PATCH 8/9 cgroup: don't hold cgroup_mutex for cgroup.kill
In reply to Shakeel Buttcgroup.kill holds cgroup_mutex while it signals every task in the subtree. It is often used when the system is already in trouble, so it should not wait for other cgroup operations, and they should not wait for it.
cgroup_mutex kept the cgroup and its subtree stable, and blocked migrations, CLONE_INTO_CGROUP forks and switches to threaded during the kill. Replace it:
- Pin the cgroup with cgroup_kn_break_active(), which also drops the kernfs active reference so that rmdir doesn't wait for the kill. rmdir can now remove the cgroup during the kill. The reference keeps the cgroup in memory, the walk skips removed cgroups, and kernfs lets the write outlive the removal of its file. Commit 071d8e4c2a3b ("kernfs:
Relax constraint in draining guard") removed a warning that this overlap could trigger. Walk the subtree under RCU, pin each cgroup while its tasks are killed, and skip empty subtrees.
- Count the running kills in the top cgroup (nr_subtree_kills). When a task leaves a css_set in a subtree being killed, cgroup_migrate_execute() kills it. This covers moves out of the subtree, moves inside it, and css_set changes from controller changes. Tasks that move in are left alone. A global count of running kills lets migrations skip the check when no kill runs.
- Kill a CLONE_INTO_CGROUP child if its parent's subtree was being killed at any time during the fork.
- Several kills can now walk one cgroup at once. Instead of an odd kill_seq, bump it when a walk starts and when it ends, and count the walks in nr_killing.
- Only an empty cgroup can switch to threaded, but threads from outside could join it while a kill of it still runs, and the checks above would kill their whole process. Make the kill and the switch exclude each other with a CGRP_THREADED flag that changes under css_set_lock:
the switch fails with EBUSY while the cgroup is being killed, and cgroup.kill fails with EOPNOTSUPP once a switch has started. cgroup.kill checks for a removed cgroup in the same section.
Document that a process moved out of the tree or inside it during a kill is killed, that a process moved in may or may not be, and the new EBUSY.
Tested in a VM, with sleeps added by a debug patch that is not part of this series. Tasks moved inside or out of the subtree, and a CLONE_INTO_CGROUP child of a task in it, all died. With the matching check turned off, they survived. A switch to threaded during a kill failed with EBUSY. With that check turned off, an outside thread that joined and created a thread took its whole process down. The test_kill and test_core selftests pass with lockdep on.
--- Documentation/admin-guide/cgroup-v2.rst | 9 +- include/linux/cgroup-defs.h | 18 ++- include/linux/sched/task.h | 1 + kernel/cgroup/cgroup.c | 199 +++++++++++++++++++----- 4 files changed, 187 insertions(+), 40 deletions(-)
Documentation/admin-guide/cgroup-v2.rst +7 -2
@@ -1057,11 +1057,16 @@ All cgroup core files are prefixed with "cgroup." tree will be killed via SIGKILL. Killing a cgroup tree will deal with concurrent forks appropriately and - is protected against migrations. + is protected against migrations: a process that is moved out of the + tree, or between its cgroups, while the tree is being killed is killed + as well. A process that is moved into the tree, or created in it with + CLONE_INTO_CGROUP from outside, while the tree is being killed may or + may not be killed. In a threaded cgroup, writing this file fails with EOPNOTSUPP as killing cgroups is a process directed operation, i.e. it affects - the whole thread-group. + the whole thread-group. Writing "threaded" to "cgroup.type" fails + with EBUSY while the cgroup is being killed. cgroup.pressure A read-write single value file that allowed values are "0" and "1".
include/linux/cgroup-defs.h +15 -3
@@ -72,6 +72,13 @@ enum {/* Cgroup is frozen. */ CGRP_FROZEN , + +/* +* cgroup.type is threaded or is being switched to threaded. Changed +* under css_set_lock, so that a kill of the cgroup and a switch to +* threaded exclude each other, see cgroup_enable_threaded(). +*/ + CGRP_THREADED, };/* cgroup_root->flags */
@@ -528,11 +535,16 @@ struct cgroup {int nr_threaded_children;/* # of live threaded child cgroups */ /* -* Sequence number for cgroup.kill, odd while a kill is walking the -* cgroup's tasks. Incremented with both cgroup_mutex and css_set_lock -* held. Readers hold either one. +* cgroup.kill state, protected by css_set_lock. A kill bumps +* kill_seq when it starts and when it ends walking this cgroup's +* tasks, and nr_killing counts such walks in progress. +* subtree_kill_seq and nr_subtree_kills do the same for whole kills +* of the subtree rooted here. See cgroup_kill(). */ unsigned int kill_seq; +unsigned int nr_killing; +unsigned int subtree_kill_seq; +unsigned int nr_subtree_kills;struct kernfs_node *kn;/* cgroup kernfs entry */ struct cgroup_file procs_file;/* handle for "cgroup.procs" */
include/linux/sched/task.h +1 -0
@@ -45,6 +45,7 @@ struct kernel_clone_args {struct cgroup *cgrp;struct css_set *cset;unsigned int kill_seq; +unsigned int subtree_kill_seq; };/*
kernel/cgroup/cgroup.c +164 -35
286 lines not on this page · raw message
Signature · 1 line
2.53.1-Meta
PATCH 9/9 cgroup/freezer: don't hold cgroup_mutex for cgroup.freeze
In reply to Shakeel Buttcgroup.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.
- 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.
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, and frozen_usec stays sane. The test_freezer selftest passes with lockdep on.
--- include/linux/cgroup-defs.h | 7 ++ include/linux/cgroup.h | 2 +- kernel/cgroup/cgroup.c | 64 +++++++++++------- kernel/cgroup/freezer.c | 128 ++++++++++++++++++++++++++---------- 4 files changed, 142 insertions(+), 59 deletions(-)
include/linux/cgroup-defs.h +7 -0
@@ -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;
include/linux/cgroup.h +1 -1
@@ -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);
kernel/cgroup/cgroup.c +40 -24
114 lines not on this page · raw message
kernel/cgroup/freezer.c +94 -34
198 lines not on this page · raw message
Signature · 1 line
2.53.1-Meta
Tejun Heo
maintainerHello, Shakeel.
The following is a Claude-generated review.
Two problems were found, in 8/9 and 9/9. Both were reproduced in a VM with delays added to widen the windows. The debug patch and the reproducer are attached.
1. A migration that fails before it commits makes the task walk skip a task (8/9 and 9/9).
cgroup_migrate_add_task() calls css_set_skip_task_iters() and moves the task to cset->mg_tasks. When ->can_attach() then fails, out_release_tset in cgroup_migrate_execute() splices mg_tasks back onto cset->tasks. An iterator whose next task was that one has already moved past the end of cset->tasks and never returns it. The task didn't change css_set, so neither the kill in cgroup_migrate_execute() nor cgroup_freezer_migrate_task() runs for it. cgroup_mutex used to keep migrations out of the walks.
The task has to be the last one on its css_set that the iterator hasn't returned, so a cgroup with one task is enough. With the failed attach between css_task_iter_start() and the first css_task_iter_next():
- cgroup.kill returns success and the task survives.
- A freeze leaves cgroup.freeze at 1 with the task running, and the cgroup never reports frozen.
- A thaw leaves cgroup.freeze at 0 and "frozen 0" in cgroup.events with the task still frozen.
2. The SIGKILL sent from cgroup_migrate_execute() isn't forced (8/9).
send_sig(SIGKILL, task, 0) sends SEND_SIG_NOINFO, which send_signal_locked() forces only when current is outside the target's pid namespace. current is the migrator there, not the cgroup.kill writer. A pid namespace init which writes its own pid to cgroup.procs of a cgroup that the walk has already passed ignores the signal and survives a kill written from the host. The same move made from the host kills it.
The other direction follows from the code and wasn't run: a host migration during a kill written inside the container kills an init which that kill would have left alone.
A few smaller points, from reading the code only:
- 3/9 is only right on top of 2/9, and its stable tag doesn't name 2/9 as a prerequisite.
- 8/9: a CLONE_INTO_CGROUP child placed outside the tree by a parent inside it is now killed. The cover letter says so but the documentation update doesn't. cgroup.kill can also fail with EOPNOTSUPP on a domain cgroup while a "threaded" write that later fails is in progress.
- 9/9: a task frozen by a freeze that is still in progress runs again when it is moved to a cgroup that the walk hasn't reached, until the walk gets there. Maybe worth documenting?
Thanks.
--
tejun
kernel/cgroup/cgroup.c +11 -0
@@ -2609,6 +2609,13 @@ void cgroup_attach_unlock(enum cgroup_attach_lock_mode lock_mode,/* cgroup.kill writes in progress, protected by css_set_lock */ static unsigned int cgroup_nr_kills; +/* REVIEW DEBUG: widen race windows */ +#include <linux/delay.h> +static unsigned int cgkill_dbg_iter_ms; +core_param (cgkill_dbg_iter_ms, cgkill_dbg_iter_ms, uint,0644 ); +static unsigned int cgkill_dbg_cg_ms; +core_param (cgkill_dbg_cg_ms, cgkill_dbg_cg_ms, uint,0644 ); +/** * cgroup_subtree_kill_seq - sample the cgroup.kill state of a cgroup's subtrees * @cgrp: cgroup of interest
@@ -4396,6 +4403,8 @@ static void __cgroup_kill(struct cgroup *cgrp)spin_unlock_irq (&css_set_lock);css_task_iter_start (&cgrp->self,CSS_TASK_ITER_THREADED , &it); +if (cgkill_dbg_iter_ms) +msleep (cgkill_dbg_iter_ms);while ((task =css_task_iter_next (&it))) {/* Ignore kernel threads here. */ if (task->flags &PF_KTHREAD )
@@ -4470,6 +4479,8 @@ static int cgroup_kill(struct cgroup *cgrp)rcu_read_unlock ();__cgroup_kill (css->cgroup); +if (cgkill_dbg_cg_ms) +msleep (cgkill_dbg_cg_ms);cond_resched ();rcu_read_lock ();
kernel/cgroup/freezer.c +8 -0
@@ -6,6 +6,12 @@#include "cgroup-internal.h" +/* REVIEW DEBUG: widen race windows */ +#include <linux/delay.h> +#include <linux/moduleparam.h> +static unsigned int cgfreeze_dbg_iter_ms; +core_param (cgfreeze_dbg_iter_ms, cgfreeze_dbg_iter_ms, uint,0644 ); +#include <trace/events/cgroup.h> /*
@@ -205,6 +211,8 @@ static void cgroup_do_freeze(struct cgroup *cgrp, bool freeze)TRACE_CGROUP_PATH (unfreeze, cgrp);css_task_iter_start (&cgrp->self,0 , &it); +if (cgfreeze_dbg_iter_ms) +msleep (cgfreeze_dbg_iter_ms);while ((task =css_task_iter_next (&it))) {/* * Ignore kernel threads here. Freezing cgroups containing
#!/bin/bash
#
# Reproducers for two problems in "cgroup: don't hold cgroup_mutex for
# cgroup.kill and cgroup.freeze": # # 1. A migration that fails before it commits makes the task walk of # cgroup.kill and cgroup.freeze skip a task. # 2. A pid namespace init that moves itself during a cgroup.kill written # from an ancestor pid namespace survives the kill. # # Needs a kernel with debug-delays.diff applied, cpuset enabled, and root. # Run it in a scratch VM. Each case has a control run that must behave.
P=/sys/module/kernel/parameters
CG=/run/cgtest
mkdir -p $CG
mount -t cgroup2 none $CG || exit 1
alive() { [ -d /proc/$1 ] && ! grep -q '^State:.*Z' /proc/$1/status; } utime() { awk '{print $14}' /proc/$1/stat; }
runs() {
local a=$(utime $1)
sleep 1
local b=$(utime $1)
[ "$b" -gt "$a" ] && echo "running" || echo "not running"
}# D/e is a cgroup that every attach fails on with ENOSPC: its cpuset has no
# effective CPUs because the sibling partition D/p took all of D's. echo +cpuset > $CG/cgroup.subtree_control mkdir $CG/D echo 0-1 > $CG/D/cpuset.cpus echo root > $CG/D/cpuset.cpus.partition echo +cpuset > $CG/D/cgroup.subtree_control mkdir $CG/D/p $CG/D/e echo 0-1 > $CG/D/p/cpuset.cpus echo root > $CG/D/p/cpuset.cpus.partition sleep 1000 & probe=$! if echo $probe > $CG/D/e/cgroup.procs 2>/dev/null; then echo "SETUP: attaching to D/e did not fail, case 1 is void" fi kill -9 $probe
echo "=== 1a. cgroup.kill, failed migration during the task walk" for with_mig in 0 1; do
mkdir -p $CG/S/x sleep 1000 & t=$! echo $t > $CG/S/x/cgroup.procs echo 2000 > $P/cgkill_dbg_iter_ms echo 1 > $CG/S/cgroup.kill & w=$! sleep 3 # the walk of S is done, the iterator of S/x has started [ $with_mig = 1 ] && echo $t > $CG/D/e/cgroup.procs 2>/dev/null wait $w echo 0 > $P/cgkill_dbg_iter_ms sleep 0.5 if alive $t; then echo "failed migration=$with_mig: task SURVIVED, S $(grep populated $CG/S/cgroup.events)" else echo "failed migration=$with_mig: task killed" fi kill -9 $t 2>/dev/null sleep 0.3 rmdir $CG/S/x $CG/S
done
echo "=== 1b. cgroup.freeze, failed migration during the task walk" for with_mig in 0 1; do
mkdir -p $CG/G/x bash -c 'while :; do :; done' & t=$! echo $t > $CG/G/x/cgroup.procs echo 2000 > $P/cgfreeze_dbg_iter_ms echo 1 > $CG/G/cgroup.freeze & w=$! sleep 3 [ $with_mig = 1 ] && echo $t > $CG/D/e/cgroup.procs 2>/dev/null wait $w echo 0 > $P/cgfreeze_dbg_iter_ms sleep 5 echo "failed migration=$with_mig: freeze=$(cat $CG/G/cgroup.freeze), G $(grep frozen $CG/G/cgroup.events), task $(runs $t)" # freeze it fully, then the same for the thaw echo 0 > $CG/G/cgroup.freeze sleep 0.5 echo 1 > $CG/G/cgroup.freeze sleep 1 echo 2000 > $P/cgfreeze_dbg_iter_ms echo 0 > $CG/G/cgroup.freeze & w=$! sleep 3 [ $with_mig = 1 ] && echo $t > $CG/D/e/cgroup.procs 2>/dev/null wait $w echo 0 > $P/cgfreeze_dbg_iter_ms sleep 5 echo "failed migration=$with_mig: freeze=$(cat $CG/G/cgroup.freeze), G/x $(grep frozen $CG/G/x/cgroup.events), task $(runs $t)" kill -9 $t 2>/dev/null sleep 0.3 rmdir $CG/G/x $CG/G
done
echo "=== 2. cgroup.kill, pid namespace init moved during the kill" for mover in host init; do
mkdir -p $CG/C/a $CG/C/b sleep 1000 & echo $! > $CG/C/a/cgroup.procs if [ $mover = init ]; then ( echo $BASHPID > $CG/C/b/cgroup.procs exec unshare -fp bash -c "sleep 4.5; echo 1 > $CG/C/a/cgroup.procs; sleep 1000; true" ) & else ( echo $BASHPID > $CG/C/b/cgroup.procs exec unshare -fp bash -c "sleep 1000; true" ) & fi sleep 0.5 init= for p in $(cat $CG/C/b/cgroup.procs); do grep -q -P '^NSpid:\t\d+\t1$' /proc/$p/status && init=$p done # sleep after each cgroup of the walk: C, then C/a, then C/b echo 3000 > $P/cgkill_dbg_cg_ms echo 1 > $CG/C/cgroup.kill & w=$! if [ $mover = host ]; then sleep 4 echo $init > $CG/C/a/cgroup.procs fi wait $w echo 0 > $P/cgkill_dbg_cg_ms sleep 0.5 if alive $init; then echo "moved by $mover: init SURVIVED in $(cat /proc/$init/cgroup), C $(grep populated $CG/C/cgroup.events)" else echo "moved by $mover: init killed" fi echo 1 > $CG/C/cgroup.kill sleep 0.5 rmdir $CG/C/a $CG/C/b $CG/C
done
Quoted 7 lines · Tejun Heo
Hello, Shakeel.
The following is a Claude-generated review.
Two problems were found, in 8/9 and 9/9. Both were reproduced in a VM with delays added to widen the windows. The debug patch and the reproducer are attached.
Thanks a lot for taking a look.
Quoted 18 lines
1. A migration that fails before it commits makes the task walk skip a task (8/9 and 9/9).
cgroup_migrate_add_task()callscss_set_skip_task_iters()and moves the task tocset->mg_tasks. When ->can_attach() then fails,out_release_tsetincgroup_migrate_execute()splicesmg_tasksback ontocset->tasks. An iterator whose next task was that one has already moved past the end ofcset->tasksand never returns it. The task didn't changecss_set, so neither the kill incgroup_migrate_execute()norcgroup_freezer_migrate_task()runs for it.cgroup_mutexused to keep migrations out of the walks.The task has to be the last one on its
css_setthat the iterator hasn't returned, so a cgroup with one task is enough. With the failed attach betweencss_task_iter_start()and the firstcss_task_iter_next():
Quoted 5 lines
- cgroup.kill returns success and the task survives.
- A freeze leaves cgroup.freeze at 1 with the task running, and the cgroup never reports frozen.
- A thaw leaves cgroup.freeze at 0 and "frozen 0" in cgroup.events with the task still frozen.
I think this failed migration issue is in css_task_iter and has been present since the commit 5ee01f1a7343. Will fix as a separate patch in v2.
Quoted 11 lines
2. The SIGKILL sent from
cgroup_migrate_execute()isn't forced (8/9).
send_sig(SIGKILL, task, 0)sendsSEND_SIG_NOINFO, whichsend_signal_locked()forces only when current is outside the target's pid namespace. current is the migrator there, not the cgroup.kill writer. A pid namespace init which writes its own pid to cgroup.procs of a cgroup that the walk has already passed ignores the signal and survives a kill written from the host. The same move made from the host kills it.
Quoted 3 lines
The other direction follows from the code and wasn't run: a host migration during a kill written inside the container kills an init which that kill would have left alone.
Here I think we need to remember the writer and for the migration path, if the writer is outside the target's pid namespace, only then force the kill.
I will address the remaining points as well in v2.
[email protected]
AI reviewRe: [PATCH 5/9] selftests/cgroup: test the frozen state of a cgroup with tasks and children
In reply to Shakeel ButtThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] selftests/cgroup: NULL dereference in test_cgfreezer_nonleaf() via cg_name() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] selftests/cgroup: NULL dereference in test_cgfreezer_nonleaf() via cg_name()
--
commit 1df209888c185f01c0eccdd24511bdf071690704
Author: Shakeel Butt <[email protected]>
selftests/cgroup: test the frozen state of a cgroup with tasks and children
This commit adds a selftest verifying that a non-leaf cgroup reports frozen only when both its own tasks and its child cgroups are frozen.
Quoted 4 lines
tools/testing/selftests/cgroup/test_freezer.c +0
-0
[ ... ]
Quoted 26 lines
tools/testing/selftests/cgroup/test_freezer.c +22
-0@@ -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 ;
tools/testing/selftests/cgroup/test_freezer.c static int test_cgfreezer_vfork(const char *root) · line 839
Quoted 10 lines
tools/testing/selftests/cgroup/test_freezer.c +10
-0+ 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;
[Severity: Low]
Can cg_name(parent, "child") dereference a NULL pointer if allocating parent fails? cg_name() unconditionally calls strlen(root) before the combined NULL check runs, crashing the test before cleanup can unmount and remove v1root.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
[email protected]
AI reviewRe: [PATCH 8/9] cgroup: don't hold cgroup_mutex for cgroup.kill
In reply to Shakeel ButtThank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] cgroup: tasks skipped by __cgroup_kill() on concurrent migration rollback - [Medium] cgroup: missing…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] cgroup: tasks skipped by __cgroup_kill() on concurrent migration rollback
- [Medium] cgroup: missing ancestor and descendant kill checks in cgroup_enable_threaded()
--
commit ab02abb83964966dc217bd7131caae946253c1f3
Author: Shakeel Butt <[email protected]>
cgroup: don't hold cgroup_mutex for cgroup.kill
This commit removes cgroup_mutex from cgroup.kill by walking the subtree under RCU and using css_set_lock-protected counters and sequence numbers to synchronize against concurrent migrations, forks, and switches to threaded mode.
Quoted 4 lines
kernel/cgroup/cgroup.c +0
-0
[ ... ]
Quoted 10 lines
kernel/cgroup/cgroup.c +6
-0@@ -2787,10 +2816,19 @@ static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)*/ spin_lock_irq (&css_set_lock);list_for_each_entry (cset, &tset->src_csets, mg_node) { +bool kill = false; + +/* don't let tasks out of a subtree being killed, see cgroup_kill() */ +if (cgroup_nr_kills) +cgroup_subtree_kill_seq (cset->dfl_cgrp, &kill); +
kernel/cgroup/cgroup.c static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx) · line 2834
Quoted 10 lines
kernel/cgroup/cgroup.c +3
-0list_for_each_entry_safe (task, tmp_task, &cset->mg_tasks, cg_list) {struct css_set *from_cset =task_css_set (task);struct css_set *to_cset = cset->mg_dst_cset; +if (unlikely (kill) && !(task->flags &PF_KTHREAD )) +send_sig (SIGKILL , task,0 ); +get_css_set (to_cset); to_cset->nr_tasks++;css_set_move_task (task, from_cset, to_cset, true);
[Severity: High]
Can a task in a subtree being killed escape SIGKILL if its migration fails before this commit point?
Without cgroup_mutex, __cgroup_kill()'s css_task_iter can interleave with cgroup_migrate_add_task() and cgroup_migrate_execute():
CPU0 CPU1__cgroup_kill()
css_task_iter_start()
/* it->task_pos = &task->cg_list
on cset->tasks */
cgroup_migrate_add_task(task)
css_set_skip_task_iters(cset, task)
/* it->task_pos = &cset->tasks,
CSS_TASK_ITER_SKIPPED set */
list_move_tail(..., &cset->mg_tasks)
cgroup_migrate_execute()
ss->can_attach() -> fails
goto out_release_tset;
list_splice_tail_init(&cset->mg_tasks,
&cset->tasks)
css_task_iter_next()
css_task_iter_advance()
/* sees it->task_pos == &cset->tasks,
moves to empty cset->mg_tasks */
<-- task is never visited or killedWhen cgroup_migrate_add_task() moves the last (or only) task from cset->tasks to cset->mg_tasks, css_set_skip_task_iters() advances it->task_pos to the list head &cset->tasks and sets CSS_TASK_ITER_SKIPPED. If ss->can_attach() or the CGROUP_TASK_MIGRATING notifier fails, cgroup_migrate_execute() skips the commit-point SIGKILL and out_release_tset splices cset->mg_tasks back to the tail of cset->tasks (behind it->task_pos == &cset->tasks) without updating cset->task_iters. The next css_task_iter_next() in __cgroup_kill() then transitions from &cset->tasks to the now-empty cset->mg_tasks and finishes cset without signaling the task.
Quoted 11 lines
kernel/cgroup/cgroup.c +7
-0@@ -3781,6 +3819,20 @@ static int cgroup_enable_threaded(struct cgroup *cgrp) !cgroup_can_be_thread_root(dom_cgrp))return -EOPNOTSUPP ; +/* +* cgroup.kill doesn't hold cgroup_mutex. Threads that join @cgrp +* after the switch could be killed with their whole process by a kill +* of @cgrp that is still running, so don't switch during such a kill. +* Set the flag now, so that new kills of @cgrp fail, see cgroup_kill(). +*/ +spin_lock_irq (&css_set_lock);
kernel/cgroup/cgroup.c static int cgroup_enable_threaded(struct cgroup *cgrp) · line 3838
Quoted 10 lines
kernel/cgroup/cgroup.c +7
-0+if (cgrp->nr_subtree_kills) { +spin_unlock_irq (&css_set_lock); +return -EBUSY ; + } +set_bit (CGRP_THREADED , &cgrp->flags); +spin_unlock_irq (&css_set_lock); +/* * The following shouldn't cause actual migrations and should * always succeed.
[Severity: Medium]
Does checking only cgrp->nr_subtree_kills miss kills running on an ancestor or a descendant of cgrp?
cgroup_kill() increments nr_subtree_kills only on the top cgroup of the kill. If an ancestor of cgrp is being killed, cgrp->nr_subtree_kills is 0, so cgroup_enable_threaded(cgrp) succeeds instead of returning -EBUSY while the ancestor's kill walks cgrp.
Conversely, in a hierarchy root -> A -> B -> C where B is a thread root (B->dom_cgrp == B, CGRP_THREADED clear) and C is threaded (C->dom_cgrp == B), a kill on B sets B->nr_subtree_kills = 1 while A->nr_subtree_kills is 0. If A, B, and C are empty, cgroup_enable_threaded(A) passes this check and updates dsct->dom_cgrp for all threaded descendants of A, moving C->dom_cgrp from B to root. A thread of a process in root can then join C via cgroup.threads and have its whole outside process killed by the ongoing kill of B.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Re: [PATCH 8/9] cgroup: don't hold cgroup_mutex for cgroup.kill
On Mon, Nov 30, 2026 at 06:36:20PM +0000, [email protected] wrote:
[...]
Quoted 3 lines
Can a task in a subtree being killed escape SIGKILL if its migration fails before this commit point?
Yes, Tejun reported the same issue. The bug is in css_task_iter and has been there since commit 5ee01f1a7343 ("cgroup: fix race between task migration and iteration"), so v2 fixes it in a separate patch.
[...]
Quoted 8 lines
Does checking only
cgrp->nr_subtree_killsmiss kills running on an ancestor or a descendant of cgrp?
cgroup_kill()incrementsnr_subtree_killsonly on the top cgroup of the kill. If an ancestor of cgrp is being killed,cgrp->nr_subtree_killsis 0, socgroup_enable_threaded(cgrp)succeeds instead of returning-EBUSYwhile the ancestor's kill walks cgrp.
This case is fine. cgrp joins the domain of its parent, which is inside the ancestor's tree, so any thread that can join cgrp belongs to a process that is entirely inside the tree being killed. This needs the ancestor to be a valid domain, which v2 makes sure of (see below).
Quoted 8 lines
Conversely, in a hierarchy root -> A -> B -> C where B is a thread root (
B->dom_cgrp== B,CGRP_THREADEDclear) and C is threaded (C->dom_cgrp== B), a kill on B setsB->nr_subtree_kills= 1 whileA->nr_subtree_killsis 0. If A, B, and C are empty,cgroup_enable_threaded(A)passes this check and updatesdsct->dom_cgrpfor all threaded descendants of A, movingC->dom_cgrpfrom B to root. A thread of a process in root can then join C via cgroup.threads and have its whole outside process killed by the ongoing kill of B.
Yes, this one is real and reproducable. v2 went out before this review and still has it. In v3, a switch to threaded will fail with EBUSY while the cgroup, or any cgroup below it, is being killed.
It also showed a related bug in mainline. After A switches, B is "domain invalid", but C can still take threads of outside processes, and cgroup.kill of B kills those processes. v3 will add a separate fix that refuses cgroup.kill below a threaded cgroup.
I will wait for sashiko review for v2 before sending out the v3 (and maybe couple of days).