A cgroup.procs reader can miss a process that never left the cgroup. With processes 148, 150 and 151 in src: read one byte of src/cgroup.procs echo 151 > empty/cgroup.procs fails with ENOSPC read the rest "148 150", 151 is missing Since commit 5ee01f1a7343 ("cgroup: fix race between task migration and iteration"), cgroup_migrate_add_task() skips an iterator past a task before it moves the task to mg_tasks. If the task was the last one on ->tasks, the iterator stops at the head of ->tasks and goes to mg_tasks next. If the migration then fails, out_release_tset splices mg_tasks back onto the tail of ->tasks. The iterator finds mg_tasks empty and moves on to the next css_set, so it never returns the task. Any task walk that doesn't hold cgroup_mutex can miss a task this way. cgroup.procs reads are the easiest case, because they keep the iterator between reads. A ->can_attach() callback can fail the migration, for example cpuset's for a cgroup without CPUs. Point such an iterator at the first task that is moved back. The iterator can then return a task twice, which a migration to a css_set it hasn't walked yet can already cause. The selftest added later in this series fails without this patch. Fixes: 5ee01f1a7343 ("cgroup: fix race between task migration and iteration") Reported-by: Tejun Heo Closes: https://lore.kernel.org/r/a6553d7921f3f47b7b890bfd232de644@kernel.org Reported-by: Sashiko Closes: https://lore.kernel.org/r/sashiko-outbox-241838@kernel.org Cc: Qingye Zhao Cc: stable@vger.kernel.org Signed-off-by: Shakeel Butt --- kernel/cgroup/cgroup.c | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c index f6df19241772..a5a7395dc5b8 100644 --- a/kernel/cgroup/cgroup.c +++ b/kernel/cgroup/cgroup.c @@ -865,6 +865,35 @@ static void css_set_skip_task_iters(struct css_set *cset, css_task_iter_skip(it, task); } +/** + * css_set_splice_mg_tasks - move the tasks on a css_set's mg_tasks to its tasks + * @cset: css_set of interest + * + * The tasks go to the tail of @cset->tasks. An iterator that is done with + * @cset->tasks and is about to move on to @cset->mg_tasks would miss them. + * This happens when cgroup_migrate_add_task() skipped the iterator past the + * last task on @cset->tasks and the migration then failed. Point such an + * iterator at the first task that is moved. It may return tasks that it + * returned before, as it may when a task migrates to a css_set it hasn't + * walked yet. + */ +static void css_set_splice_mg_tasks(struct css_set *cset) +{ + struct css_task_iter *it; + + lockdep_assert_held(&css_set_lock); + + if (list_empty(&cset->mg_tasks)) + return; + + /* only a skipped iterator stops at the head, see css_task_iter_skip() */ + list_for_each_entry(it, &cset->task_iters, iters_node) + if (it->task_pos == &cset->tasks) + it->task_pos = cset->mg_tasks.next; + + list_splice_tail_init(&cset->mg_tasks, &cset->tasks); +} + /** * css_set_move_task - move a task from one css_set to another * @task: task being moved @@ -2851,7 +2880,7 @@ static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx) spin_lock_irq(&css_set_lock); list_splice_init(&tset->dst_csets, &tset->src_csets); list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) { - list_splice_tail_init(&cset->mg_tasks, &cset->tasks); + css_set_splice_mg_tasks(cset); list_del_init(&cset->mg_node); } spin_unlock_irq(&css_set_lock); -- 2.53.1-Meta A process forked while cgroup.kill is walking its parent's cgroup can survive the kill: kill fork ---- ---- kill_seq++ cgroup_can_fork() reads kill_seq iterator returns the parent and moves on copy_process() sees no SIGKILL yet and commits to the fork send SIGKILL to the parent cgroup_post_fork() links the child behind the iterator; kill_seq is unchanged, so the child lives The fork read kill_seq after the kill started, so the check from commit b69bb476dee9 ("cgroup: fix race between fork and cgroup.kill") misses it. The window is the gap between the iterator step and send_sig(), and preemption can stretch it. Make kill_seq odd while __cgroup_kill() walks the tasks. Kill the child if kill_seq was odd when the fork read it, or if it changed since. A walk that ended before the read has already sent SIGKILL to the parent, so the fork fails. A walk that starts after the child is linked finds the child. CLONE_INTO_CGROUP forks hold cgroup_mutex across both reads, so they always see an even, unchanged kill_seq. Reproduced in a VM with a sleep between the iterator and send_sig(): the child survived in 5 of 5 runs, and in 0 of 5 with this patch. Fixes: b69bb476dee9 ("cgroup: fix race between fork and cgroup.kill") Cc: stable@vger.kernel.org # v5.14+ Signed-off-by: Shakeel Butt --- include/linux/cgroup-defs.h | 5 +++-- kernel/cgroup/cgroup.c | 15 ++++++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/include/linux/cgroup-defs.h b/include/linux/cgroup-defs.h index cbfe8937647c..0dae54b033e9 100644 --- a/include/linux/cgroup-defs.h +++ b/include/linux/cgroup-defs.h @@ -528,8 +528,9 @@ struct cgroup { int nr_threaded_children; /* # of live threaded child cgroups */ /* - * Sequence number for cgroup.kill. Incremented with both cgroup_mutex - * and css_set_lock held. Readers hold either one. + * Sequence number for cgroup.kill, odd while a kill is walking the + * cgroup's tasks. Incremented with both cgroup_mutex and css_set_lock + * held. Readers hold either one. */ unsigned int kill_seq; diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c index a5a7395dc5b8..0fcd2c1b0da9 100644 --- a/kernel/cgroup/cgroup.c +++ b/kernel/cgroup/cgroup.c @@ -4329,6 +4329,14 @@ static void __cgroup_kill(struct cgroup *cgrp) lockdep_assert_held(&cgroup_mutex); + /* + * kill_seq is odd while this walk is in progress. The walk can signal + * a forking parent after copy_process() passed its + * fatal_signal_pending() check, and can pass the parent before the + * child is linked. cgroup_post_fork() therefore kills the child if + * kill_seq was odd when cgroup_css_set_fork() sampled it, or if it + * changed since. + */ spin_lock_irq(&css_set_lock); cgrp->kill_seq++; spin_unlock_irq(&css_set_lock); @@ -4346,6 +4354,10 @@ static void __cgroup_kill(struct cgroup *cgrp) send_sig(SIGKILL, task, 0); } css_task_iter_end(&it); + + spin_lock_irq(&css_set_lock); + cgrp->kill_seq++; + spin_unlock_irq(&css_set_lock); } static void cgroup_kill(struct cgroup *cgrp) @@ -7208,7 +7220,8 @@ void cgroup_post_fork(struct task_struct *child, * child down right after we finished preparing it for * userspace. */ - kill = kargs->kill_seq != cgrp_kill_seq; + kill = kargs->kill_seq != cgrp_kill_seq || + (kargs->kill_seq & 1); } spin_unlock_irq(&css_set_lock); -- 2.53.1-Meta cgroup.kill refuses threaded cgroups, because killing is a process directed operation: killing one thread takes down its whole process. But it accepts a cgroup below a threaded cgroup, which can hold threads of processes that live outside of it: mkdir -p A/B/C echo threaded > A/B/C/cgroup.type B becomes a thread root echo threaded > A/cgroup.type C joins the root's domain, and B becomes "domain invalid" echo > A/B/C/cgroup.threads a thread of a process in the root echo 1 > A/B/cgroup.kill succeeds and kills that process When a cgroup turns threaded, the threaded cgroups below it join its new domain, also those below a thread root such as B. Every cgroup below a threaded cgroup is threaded or an invalid domain, so refuse cgroup.kill for all of them, as it is refused for threaded cgroups. Reproduced in a VM. A selftest follows later in this series. Fixes: 661ee6280931 ("cgroup: introduce cgroup.kill") Reported-by: Sashiko Closes: https://lore.kernel.org/r/sashiko-outbox-241838@kernel.org Cc: stable@vger.kernel.org # v5.14+ Signed-off-by: Shakeel Butt --- Documentation/admin-guide/cgroup-v2.rst | 6 +++--- kernel/cgroup/cgroup.c | 19 +++++++++++++++++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst index 2f792ff29425..9539f3a99a2f 100644 --- a/Documentation/admin-guide/cgroup-v2.rst +++ b/Documentation/admin-guide/cgroup-v2.rst @@ -1059,9 +1059,9 @@ All cgroup core files are prefixed with "cgroup." Killing a cgroup tree will deal with concurrent forks appropriately and is protected against migrations. - 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. + In a threaded cgroup, or a cgroup below one, writing this file fails + with EOPNOTSUPP as killing cgroups is a process directed operation, + i.e. it affects the whole thread-group. cgroup.pressure A read-write single value file that allowed values are "0" and "1". diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c index 0fcd2c1b0da9..f38da8b810f1 100644 --- a/kernel/cgroup/cgroup.c +++ b/kernel/cgroup/cgroup.c @@ -4322,6 +4322,20 @@ static ssize_t cgroup_freeze_write(struct kernfs_open_file *of, return nbytes; } +/* + * Is @cgrp threaded, or below a threaded cgroup? When a cgroup turns threaded, + * the threaded cgroups below it join its new domain, also those below a thread + * root. So a cgroup below a threaded cgroup can hold threads of processes that + * live outside of it. + */ +static bool cgroup_in_threaded_subtree(struct cgroup *cgrp) +{ + for (; cgrp; cgrp = cgroup_parent(cgrp)) + if (cgroup_is_threaded(cgrp)) + return true; + return false; +} + static void __cgroup_kill(struct cgroup *cgrp) { struct css_task_iter it; @@ -4392,9 +4406,10 @@ static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf, /* * Killing is a process directed operation, i.e. the whole thread-group * is taken down so act like we do for cgroup.procs and only make this - * writable in non-threaded cgroups. + * writable in non-threaded cgroups. The cgroups below a threaded cgroup + * can hold threads of processes outside of them, so refuse those too. */ - if (cgroup_is_threaded(cgrp)) + if (cgroup_in_threaded_subtree(cgrp)) ret = -EOPNOTSUPP; else cgroup_kill(cgrp); -- 2.53.1-Meta A cgroup with its own tasks and child cgroups can report frozen=1 while part of its subtree still runs. cgroup2 allows this layout in threaded cgroups, and in domain cgroups that don't enable a domain controller for their children. cgroup_update_frozen() only looks at the cgroup's own tasks, and cgroup_propagate_frozen() only looks at its descendants. So a parent can become frozen when only one of the two is frozen. The wrong state can also stay after a thaw: cgroup_do_freeze() skips the update while a descendant is unfrozen, and a stopped task is not woken to fix it. Use one test everywhere: CGRP_FREEZE is set, all own tasks are frozen and all descendants are frozen. Merge cgroup_propagate_frozen() into cgroup_update_frozen() and always call it from cgroup_do_freeze(). Reproduced in a VM with a task stuck in D state, writing to an fsfreeze'd filesystem. With the stuck task in the child or in the parent, the parent reported frozen=1. With a stopped task moved into the parent, the parent still reported frozen=1 after the thaw. With this patch it reports frozen=0 in all three cases. Fixes: 76f969e8948d ("cgroup: cgroup v2 freezer") Cc: stable@vger.kernel.org # v5.2+ Signed-off-by: Shakeel Butt --- kernel/cgroup/freezer.c | 63 ++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 39 deletions(-) diff --git a/kernel/cgroup/freezer.c b/kernel/cgroup/freezer.c index 35112d62318a..6ecb42084ecc 100644 --- a/kernel/cgroup/freezer.c +++ b/kernel/cgroup/freezer.c @@ -28,53 +28,39 @@ static bool cgroup_update_frozen_flag(struct cgroup *cgrp, bool frozen) } /* - * Propagate the cgroup frozen state upwards by the cgroup tree. + * A cgroup is frozen when it has to be frozen (CGRP_FREEZE bit set), all of + * its own tasks are frozen and/or stopped, and all of its descendants are + * frozen. A non-leaf cgroup can have tasks of its own: threaded cgroups always + * can, and domain cgroups can while no domain controller is enabled in their + * subtree_control. */ -static void cgroup_propagate_frozen(struct cgroup *cgrp, bool frozen) +static bool cgroup_frozen_state(struct cgroup *cgrp) { - int desc = 1; - - /* - * If the new state is frozen, some freezing ancestor cgroups may change - * their state too, depending on if all their descendants are frozen. - * - * Otherwise, all ancestor cgroups are forced into the non-frozen state. - */ - while ((cgrp = cgroup_parent(cgrp))) { - if (frozen) { - cgrp->freezer.nr_frozen_descendants += desc; - if (!test_bit(CGRP_FREEZE, &cgrp->flags) || - (cgrp->freezer.nr_frozen_descendants != - cgrp->nr_descendants)) - continue; - } else { - cgrp->freezer.nr_frozen_descendants -= desc; - } - - if (cgroup_update_frozen_flag(cgrp, frozen)) - desc++; - } + /* __cgroup_task_count() walks the css_sets, test it last */ + return test_bit(CGRP_FREEZE, &cgrp->flags) && + cgrp->freezer.nr_frozen_descendants == cgrp->nr_descendants && + cgrp->freezer.nr_frozen_tasks == __cgroup_task_count(cgrp); } /* - * Revisit the cgroup frozen state. - * Checks if the cgroup is really frozen and perform all state transitions. + * Revisit the frozen state of @cgrp and propagate a change to the ancestors. + * delta counts the cgroups below the one being looked at whose frozen state + * changed in this update, negative if they were unfrozen. */ void cgroup_update_frozen(struct cgroup *cgrp) { - bool frozen; + int delta = 0; - /* - * If the cgroup has to be frozen (CGRP_FREEZE bit set), - * and all tasks are frozen and/or stopped, let's consider - * the cgroup frozen. Otherwise it's not frozen. - */ - frozen = test_bit(CGRP_FREEZE, &cgrp->flags) && - cgrp->freezer.nr_frozen_tasks == __cgroup_task_count(cgrp); + lockdep_assert_held(&css_set_lock); + + do { + bool frozen; - /* If flags is updated, update the state of ancestor cgroups. */ - if (cgroup_update_frozen_flag(cgrp, frozen)) - cgroup_propagate_frozen(cgrp, frozen); + cgrp->freezer.nr_frozen_descendants += delta; + frozen = cgroup_frozen_state(cgrp); + if (cgroup_update_frozen_flag(cgrp, frozen)) + delta += frozen ? 1 : -1; + } while (delta && (cgrp = cgroup_parent(cgrp))); } /* @@ -210,8 +196,7 @@ static void cgroup_do_freeze(struct cgroup *cgrp, bool freeze, u64 ts_nsec) * and cgroups which descendants are already in the desired state. */ spin_lock_irq(&css_set_lock); - if (cgrp->nr_descendants == cgrp->freezer.nr_frozen_descendants) - cgroup_update_frozen(cgrp); + cgroup_update_frozen(cgrp); spin_unlock_irq(&css_set_lock); } -- 2.53.1-Meta Since commit 93618edf7538 ("cgroup: Defer css percpu_ref kill on rmdir until cgroup is depopulated"), rmdir can remove a cgroup while an exiting task is still linked to it. The task is unlinked later, in cgroup_task_dead(). This breaks the freezer counts: - rmdir takes the cgroup out of the ancestors' nr_frozen_descendants only if it is frozen, and a cgroup with an exiting task is not. When the task is unlinked, cgroup_update_frozen() marks the dead cgroup frozen and counts it again in every ancestor. The count stays one too high, so a freezing ancestor reports frozen=1 too early or never. - If the removed cgroup was the parent's last unfrozen descendant, the parent is not checked again and stays at frozen=0. Clear CSS_ONLINE, fix the ancestors' counts and check the parent again in one css_set_lock section, and make cgroup_update_frozen() skip dead cgroups. cgroup_is_dead() can now run with only css_set_lock held, while other bits of the same flags word change under cgroup_mutex, so use READ_ONCE() and WRITE_ONCE() for CSS_ONLINE. The parent's check needs the frozen state to cover descendants, so a backport needs "cgroup/freezer: check own tasks and descendants for the frozen state" first. Reproduced in a VM: freeze G/P, kill the only task in G/P/C while its exit is held on an fsfreeze'd filesystem, remove G/P/C, and let the task finish. G/P, empty and freezing, reports frozen=0, and a later freeze of G never completes. This patch fixes both. Fixes: 93618edf7538 ("cgroup: Defer css percpu_ref kill on rmdir until cgroup is depopulated") Cc: stable@vger.kernel.org # v7.0+, needs "cgroup/freezer: check own tasks and descendants for the frozen state" Signed-off-by: Shakeel Butt --- include/linux/cgroup.h | 2 +- kernel/cgroup/cgroup.c | 33 +++++++++++++++++++-------------- kernel/cgroup/freezer.c | 8 ++++++++ 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/include/linux/cgroup.h b/include/linux/cgroup.h index f3c65991acac..7279613d6804 100644 --- a/include/linux/cgroup.h +++ b/include/linux/cgroup.h @@ -462,7 +462,7 @@ static inline bool css_is_self(struct cgroup_subsys_state *css) static inline bool cgroup_is_dead(const struct cgroup *cgrp) { - return !(cgrp->self.flags & CSS_ONLINE); + return !(READ_ONCE(cgrp->self.flags) & CSS_ONLINE); } static inline void cgroup_get(struct cgroup *cgrp) diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c index f38da8b810f1..29e4c5160c6a 100644 --- a/kernel/cgroup/cgroup.c +++ b/kernel/cgroup/cgroup.c @@ -6441,25 +6441,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++; @@ -6470,8 +6462,21 @@ static int cgroup_destroy_locked(struct cgroup *cgrp) if (test_bit(CGRP_FROZEN, &cgrp->flags)) tcgrp->freezer.nr_frozen_descendants--; } + + /* @cgrp may have been the last unfrozen descendant of a freezing parent */ + cgroup_update_frozen(parent); spin_unlock_irq(&css_set_lock); + for_each_css(css, ssid, cgrp) + kill_css_sync(css); + + /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */ + css_clear_dir(&cgrp->self); + kernfs_remove(cgrp->kn); + + if (cgroup_is_threaded(cgrp)) + parent->nr_threaded_children--; + cgroup1_check_for_release(parent); ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier, diff --git a/kernel/cgroup/freezer.c b/kernel/cgroup/freezer.c index 6ecb42084ecc..a85f8897ffa2 100644 --- a/kernel/cgroup/freezer.c +++ b/kernel/cgroup/freezer.c @@ -53,6 +53,14 @@ void cgroup_update_frozen(struct cgroup *cgrp) lockdep_assert_held(&css_set_lock); + /* + * An exiting task can stay linked to a cgroup after rmdir. + * cgroup_destroy_locked() took the cgroup out of its ancestors' counts + * when it cleared CSS_ONLINE. Leave its state alone from then on. + */ + if (cgroup_is_dead(cgrp)) + return; + do { bool frozen; -- 2.53.1-Meta When a task leaves the frozen state while its cgroup is still freezing, for example a vfork parent, cgroup_leave_frozen() sets JOBCTL_TRAP_FREEZE and TIF_SIGPENDING so that the task traps again. It tests JOBCTL_TRAP_FREEZE without siglock. cgroup_freeze_task() sets that bit and then TIF_SIGPENDING, both under siglock. If the task sees only the first store, it can return to user space while it is counted as frozen, until the wakeup kick arrives. Take siglock before the test. The window is a few instructions wide, and this was not reproduced. Fixes: cb2c4cd87874 ("cgroup: prevent spurious transition into non-frozen state") Signed-off-by: Shakeel Butt --- kernel/cgroup/freezer.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/kernel/cgroup/freezer.c b/kernel/cgroup/freezer.c index a85f8897ffa2..b905df5e416b 100644 --- a/kernel/cgroup/freezer.c +++ b/kernel/cgroup/freezer.c @@ -127,10 +127,17 @@ void cgroup_leave_frozen(bool always_leave) cgroup_update_frozen(cgrp); WARN_ON_ONCE(!current->frozen); current->frozen = false; - } else if (!(current->jobctl & JOBCTL_TRAP_FREEZE)) { + } else { + /* + * Test the trap bit under siglock: cgroup_freeze_task() sets it + * before signal_wake_up() sets TIF_SIGPENDING, and a vfork + * parent returns to user space right after this. + */ spin_lock(¤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); -- 2.53.1-Meta cgroup.procs keeps its task iterator between reads. A failed migration used to make the iterator skip the last process of a css_set. Read one byte of cgroup.procs, so that the iterator waits on the last of three processes. Then fail a migration of that process, and check that the rest of the read still lists it. cpuset makes the migration fail: a partition with one CPU gives that CPU to a child partition, which leaves its other child without CPUs. The test is skipped if this can't be set up. The test fails without "cgroup: don't lose a task in css_task_iter when a migration fails". Signed-off-by: Shakeel Butt --- tools/testing/selftests/cgroup/test_core.c | 154 +++++++++++++++++++++ 1 file changed, 154 insertions(+) diff --git a/tools/testing/selftests/cgroup/test_core.c b/tools/testing/selftests/cgroup/test_core.c index 53592bf309fa..01c268672d6d 100644 --- a/tools/testing/selftests/cgroup/test_core.c +++ b/tools/testing/selftests/cgroup/test_core.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -739,6 +740,158 @@ static int test_cgcore_thread_migration(const char *root) return ret; } +/* Return the highest CPU number in a cpu list like "0-3,8-11", or -1. */ +static int cpulist_last(const char *list) +{ + const char *p = list + strlen(list); + + while (p > list && !isdigit(p[-1])) + p--; + while (p > list && isdigit(p[-1])) + p--; + return isdigit(*p) ? atoi(p) : -1; +} + +/* Is @pid on a line of its own in @buf? */ +static bool pid_listed(const char *buf, pid_t pid) +{ + const char *p = buf; + char *end; + + while (*p) { + if (strtol(p, &end, 10) == pid && end != p && *end == '\n') + return true; + p = strchr(p, '\n'); + if (!p) + break; + p++; + } + return false; +} + +/* + * A migration that fails must not make a cgroup.procs reader miss a process. + * + * cgroup.procs keeps its task iterator between reads. Read one byte, so that + * the iterator waits on the last process, then fail a migration of that + * process: cpuset refuses tasks for a cgroup without CPUs. The process never + * left the cgroup, so the rest of the read must list it. + */ +static int test_cgcore_procs_failed_migration(const char *root) +{ + char *parent = NULL, *full = NULL, *empty = NULL, *cg = NULL; + char cpus[256], cpu[16], buf[4096]; + bool cpuset_enabled = false; + pid_t pids[3] = { 0 }; + int ret = KSFT_FAIL; + int fd = -1, i, last; + ssize_t len, n; + + if (cg_test_v1_named) + return KSFT_SKIP; + + parent = cg_name(root, "cg_test_fail"); + full = cg_name(root, "cg_test_fail/full"); + empty = cg_name(root, "cg_test_fail/empty"); + cg = cg_name(root, "cg_test_src"); + if (!parent || !full || !empty || !cg) + goto cleanup; + + /* + * Make "empty" a cgroup without CPUs: "parent" is a partition with one + * CPU, and its child partition "full" takes that CPU. + */ + ret = KSFT_SKIP; + if (cg_read_strstr(root, "cgroup.subtree_control", "cpuset")) { + if (cg_write(root, "cgroup.subtree_control", "+cpuset")) + goto cleanup; + cpuset_enabled = true; + } + if (cg_read(root, "cpuset.cpus.effective", cpus, sizeof(cpus))) + goto cleanup; + last = cpulist_last(cpus); + if (last <= 0) + goto cleanup; + snprintf(cpu, sizeof(cpu), "%d", last); + + if (cg_create(parent) || cg_write(parent, "cpuset.cpus", cpu) || + cg_write(parent, "cpuset.cpus.partition", "root") || + cg_read_strcmp(parent, "cpuset.cpus.partition", "root\n") || + cg_write(parent, "cgroup.subtree_control", "+cpuset") || + cg_create(full) || cg_write(full, "cpuset.cpus", cpu) || + cg_write(full, "cpuset.cpus.partition", "root") || + cg_read_strcmp(full, "cpuset.cpus.partition", "root\n") || + cg_create(empty) || + cg_read_strcmp(empty, "cpuset.cpus.effective", "\n")) + goto cleanup; + + ret = KSFT_FAIL; + if (cg_create(cg)) + goto cleanup; + + /* Move the processes in one by one, so that they are listed in order. */ + for (i = 0; i < 3; i++) { + pids[i] = fork(); + if (pids[i] < 0) + goto cleanup; + if (!pids[i]) { + while (1) + pause(); + } + if (cg_enter(cg, pids[i])) + goto cleanup; + } + + /* Without a failing migration there is nothing to test. */ + if (cg_enter(empty, pids[2]) != -ENOSPC) { + ret = KSFT_SKIP; + goto cleanup; + } + + fd = cg_open(cg, "cgroup.procs", O_RDONLY); + if (fd < 0) + goto cleanup; + if (read(fd, buf, 1) != 1) + goto cleanup; + len = 1; + + if (cg_enter(empty, pids[2]) != -ENOSPC) + goto cleanup; + + while ((n = read(fd, buf + len, sizeof(buf) - 1 - len)) > 0) + len += n; + if (n < 0) + goto cleanup; + buf[len] = '\0'; + + for (i = 0; i < 3; i++) + if (!pid_listed(buf, pids[i])) + goto cleanup; + + ret = KSFT_PASS; + +cleanup: + if (fd >= 0) + close(fd); + for (i = 0; i < 3; i++) { + if (pids[i] > 0) { + kill(pids[i], SIGKILL); + waitpid(pids[i], NULL, 0); + } + } + cg_destroy(cg); + cg_destroy(empty); + cg_destroy(full); + cg_destroy(parent); + if (cpuset_enabled) + cg_write(root, "cgroup.subtree_control", "-cpuset"); + free(cg); + free(empty); + free(full); + free(parent); + return ret; +} + /* * cgroup migration permission check should be performed based on the * credentials at the time of open instead of write. @@ -941,6 +1094,7 @@ struct corecg_test { T(test_cgcore_populated), T(test_cgcore_proc_migration), T(test_cgcore_thread_migration), + T(test_cgcore_procs_failed_migration), T(test_cgcore_destroy), T(test_cgcore_lesser_euid_open), T(test_cgcore_lesser_ns_open), -- 2.53.1-Meta Add a test for a cgroup that has tasks of its own and a child cgroup. It must report frozen only when its own tasks and the child are all frozen, and it must not stay frozen after a thaw. To get a task that the cgroup2 freezer can't stop, freeze it in a cgroup v1 freezer hierarchy. It then sleeps in the refrigerator, where the cgroup2 freezer can't trap it. A stopped task counts as frozen, and a thaw doesn't wake it. The test is skipped if the v1 freezer can't be mounted. Without "cgroup/freezer: check own tasks and descendants for the frozen state", the parent reports frozen=1 while its child is not frozen. Signed-off-by: Shakeel Butt --- tools/testing/selftests/cgroup/test_freezer.c | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/tools/testing/selftests/cgroup/test_freezer.c b/tools/testing/selftests/cgroup/test_freezer.c index 266b1a0f889f..92dd743ca7bb 100644 --- a/tools/testing/selftests/cgroup/test_freezer.c +++ b/tools/testing/selftests/cgroup/test_freezer.c @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -804,6 +805,112 @@ 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"); + if (!parent) + goto cleanup; + + child = cg_name(parent, "child"); + staging = cg_name(root, "cg_test_nonleaf_staging"); + v1cg = cg_name(v1root, "cg_test_nonleaf"); + if (!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 +1586,7 @@ struct cgfreezer_test { T(test_cgfreezer_stopped), T(test_cgfreezer_ptraced), T(test_cgfreezer_vfork), + T(test_cgfreezer_nonleaf), T(test_cgfreezer_time_empty), T(test_cgfreezer_time_simple), T(test_cgfreezer_time_populate), -- 2.53.1-Meta Check that writing cgroup.kill in a threaded cgroup fails with EOPNOTSUPP and kills nothing, and that the thread root can still kill a process whose thread was moved into the threaded cgroup. This is existing behavior. The next patches change how cgroup.kill checks for threaded cgroups, and this test shows that the behavior stays the same. Also check that cgroup.kill fails with EOPNOTSUPP below a threaded cgroup: a thread root that became an invalid domain when its parent turned threaded, with a thread from outside in its threaded child. This test fails without "cgroup: refuse cgroup.kill below a threaded cgroup". Signed-off-by: Shakeel Butt --- tools/testing/selftests/cgroup/test_kill.c | 127 +++++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/tools/testing/selftests/cgroup/test_kill.c b/tools/testing/selftests/cgroup/test_kill.c index 756bc7193d4b..e8db5b3356a4 100644 --- a/tools/testing/selftests/cgroup/test_kill.c +++ b/tools/testing/selftests/cgroup/test_kill.c @@ -471,6 +471,131 @@ 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; +} + +/* + * cgroup.kill also fails below a threaded cgroup. Once a turns threaded, its + * child b, a thread root, becomes an invalid domain, and b's threaded child c + * joins the domain of a's parent. A thread of a process outside of a can then + * join c, and killing b would kill that whole process. + */ +static int test_cgkill_below_threaded(const char *root) +{ + char *a = NULL, *b = NULL, *c = NULL; + int ret = KSFT_FAIL; + pid_t pid = -ESRCH; + + a = cg_name(root, "cg_test_kill_below_threaded"); + b = cg_name(root, "cg_test_kill_below_threaded/b"); + c = cg_name(root, "cg_test_kill_below_threaded/b/c"); + if (!a || !b || !c) + goto cleanup; + + if (cg_create(a) || cg_create(b) || cg_create(c)) + goto cleanup; + + if (cg_write(c, "cgroup.type", "threaded") || + cg_write(a, "cgroup.type", "threaded")) + goto cleanup; + + pid = cg_run_nowait(root, child_fn, NULL); + if (pid < 0) + goto cleanup; + + if (cg_write_numeric(c, "cgroup.threads", pid)) + goto cleanup; + + if (cg_write(b, "cgroup.kill", "1") != -EOPNOTSUPP) + goto cleanup; + + /* As in test_cgkill_threaded(), the refused write must not kill. */ + usleep(100000); + if (waitpid(pid, NULL, WNOHANG)) { + pid = -ESRCH; + goto cleanup; + } + + ret = KSFT_PASS; + +cleanup: + if (pid > 0) { + kill(pid, SIGKILL); + wait_for_pid(pid); + } + cg_destroy(c); + cg_destroy(b); + cg_destroy(a); + free(c); + free(b); + free(a); + return ret; +} + #define T(x) { x, #x } struct cgkill_test { int (*fn)(const char *root); @@ -482,6 +607,8 @@ struct cgkill_test { T(test_cgkill_clone_into_killed), T(test_cgkill_exited_leader), T(test_cgkill_exited_leader_migrated), + T(test_cgkill_threaded), + T(test_cgkill_below_threaded), }; #undef T -- 2.53.1-Meta Move the part of cgroup_kn_lock_live() that runs before cgroup_mutex into cgroup_kn_break_active(). It pins the cgroup and drops the node's active reference. cgroup_kn_unbreak_active() undoes it. Later patches use them in writes that don't take cgroup_mutex. No functional change. Signed-off-by: Shakeel Butt --- kernel/cgroup/cgroup.c | 52 ++++++++++++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c index 29e4c5160c6a..644bc653b180 100644 --- a/kernel/cgroup/cgroup.c +++ b/kernel/cgroup/cgroup.c @@ -1669,6 +1669,37 @@ static u32 cgroup_calc_subtree_ss_mask(u32 subtree_control, u32 this_ss_mask) return cur_ss_mask; } +/* + * Pin the cgroup of @kn and drop @kn's active reference, so that removing the + * cgroup doesn't wait for the caller. The cgroup stays accessible but can go + * offline at any time: the caller checks cgroup_is_dead() under a lock that + * removal also takes. Undo with cgroup_kn_unbreak_active(), or + * cgroup_kn_unlock() if cgroup_mutex is held. + */ +static struct cgroup *cgroup_kn_break_active(struct kernfs_node *kn) +{ + struct cgroup *cgrp; + + if (kernfs_type(kn) == KERNFS_DIR) + cgrp = kn->priv; + else + cgrp = kn_priv(kn); + + /* ensure @cgrp stays accessible and break the active_ref protection */ + if (!cgroup_tryget(cgrp)) + return ERR_PTR(-ENODEV); + kernfs_break_active_protection(kn); + return cgrp; +} + +/* undo cgroup_kn_break_active() */ +static void cgroup_kn_unbreak_active(struct kernfs_node *kn, + struct cgroup *cgrp) +{ + kernfs_unbreak_active_protection(kn); + cgroup_put(cgrp); +} + /** * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods * @kn: the kernfs_node being serviced @@ -1689,9 +1720,7 @@ void cgroup_kn_unlock(struct kernfs_node *kn) cgrp = kn_priv(kn); cgroup_unlock(); - - kernfs_unbreak_active_protection(kn); - cgroup_put(cgrp); + cgroup_kn_unbreak_active(kn, cgrp); } /** @@ -1717,26 +1746,19 @@ struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline) struct cgroup *cgrp; int ret; - if (kernfs_type(kn) == KERNFS_DIR) - cgrp = kn->priv; - else - cgrp = kn_priv(kn); - /* * We're gonna grab cgroup_mutex which nests outside kernfs * active_ref. cgroup liveliness check alone provides enough - * protection against removal. Ensure @cgrp stays accessible and - * break the active_ref protection. + * protection against removal. */ - if (!cgroup_tryget(cgrp)) - return ERR_PTR(-ENODEV); - kernfs_break_active_protection(kn); + cgrp = cgroup_kn_break_active(kn); + if (IS_ERR(cgrp)) + return cgrp; if (drain_offline) { ret = cgroup_lock_and_drain_offline(cgrp); if (unlikely(ret)) { - kernfs_unbreak_active_protection(kn); - cgroup_put(cgrp); + cgroup_kn_unbreak_active(kn, cgrp); return ERR_PTR(ret); } } else { -- 2.53.1-Meta cgroup.kill holds cgroup_mutex while it signals every task in the subtree. It is often used when the system is already in trouble, so it should not wait for other cgroup operations, and they should not wait for it. cgroup_mutex kept the cgroup and its subtree stable, and blocked migrations, CLONE_INTO_CGROUP forks and switches to threaded during the kill. Replace it: - Pin the cgroup with cgroup_kn_break_active(), which also drops the kernfs active reference so that rmdir doesn't wait for the kill. rmdir can now remove the cgroup during the kill. The reference keeps the cgroup in memory, the walk skips removed cgroups, and kernfs lets the write outlive the removal of its file. Commit 071d8e4c2a3b ("kernfs: Relax constraint in draining guard") removed a warning that this overlap could trigger. Walk the subtree under RCU, pin each cgroup while its tasks are killed, and skip empty subtrees. - Count the running kills in the top cgroup (nr_subtree_kills). When a task leaves a css_set in a subtree being killed, cgroup_migrate_execute() kills it. This covers moves out of the subtree, moves inside it, and css_set changes from controller changes. Tasks that move in are left alone. A list of running kills lets migrations skip the check when no kill runs. - The walk sends SIGKILL from the writer, and a pid namespace init ignores it unless the writer is outside the init's pid namespace. In cgroup_migrate_execute(), current is the migrating task instead. So each kill records its writer's pid, and a task that leaves the subtree gets a forced SIGKILL only if one of the writers is outside its pid namespace. Otherwise a pid namespace init is left alone, as the walk would leave it. cgroup_post_fork() decides the same way for a child it kills: the parent can be a thread of a pid namespace init, and with CLONE_THREAD and CLONE_INTO_CGROUP the child can land in a cgroup that the walk has already passed. - 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. The switch also moves the threaded cgroups below the cgroup into the new domain. So the switch fails with EBUSY while the cgroup, or a cgroup below it, is being killed. cgroup.kill returns right away for an empty subtree, which has nothing to kill, and nothing can enter the subtree during the switch, so no such kill can start during the switch. A CGRP_THREADED flag is set under css_set_lock when the switch succeeds, and cgroup.kill fails with EOPNOTSUPP if the cgroup or one of its ancestors has it. cgroup.kill checks for a removed cgroup in the same section. The walk relies on the task iterator to return every task that stays in a cgroup during the walk. This needs "cgroup: don't lose a task in css_task_iter when a migration fails". Document that a process moved out of the tree or inside it during a kill is killed, and so is a CLONE_INTO_CGROUP child that a process in the tree creates outside of it. Also document that a process moved in may or may not be killed, and the new EBUSY. Tested in a VM, with sleeps added by a debug patch that is not part of this series. Tasks moved inside or out of the subtree, and a CLONE_INTO_CGROUP child of a task in it, all died, and so did a task whose migration failed during the walk. A pid namespace init that moved during a kill died when the kill was written from the host, and survived when it was written inside its namespace, as it does with the walk. So did an init whose thread created a thread in a cgroup the walk had passed and then exited. With the matching check turned off, these tests failed. A switch to threaded of the cgroup, or of an ancestor, during a kill failed with EBUSY, and a kill during a switch that failed returned 0. With the EBUSY check turned off, an outside thread that joined took its whole process down. The test_kill and test_core selftests pass with lockdep on. Signed-off-by: Shakeel Butt --- Documentation/admin-guide/cgroup-v2.rst | 11 +- include/linux/cgroup-defs.h | 18 +- include/linux/sched/task.h | 1 + kernel/cgroup/cgroup.c | 312 +++++++++++++++++++++--- 4 files changed, 298 insertions(+), 44 deletions(-) diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst index 9539f3a99a2f..8fa190eaf65f 100644 --- a/Documentation/admin-guide/cgroup-v2.rst +++ b/Documentation/admin-guide/cgroup-v2.rst @@ -1057,11 +1057,18 @@ All cgroup core files are prefixed with "cgroup." tree will be killed via SIGKILL. Killing a cgroup tree will deal with concurrent forks appropriately and - is protected against migrations. + is protected against migrations: a process that is moved out of the + tree, or between its cgroups, while the tree is being killed is killed + as well, and so is a process that a process in the tree creates + outside of it with CLONE_INTO_CGROUP. A process that is moved into + the tree, or created in it with CLONE_INTO_CGROUP from outside, while + the tree is being killed may or may not be killed. In a threaded cgroup, or a cgroup below one, writing this file fails with EOPNOTSUPP as killing cgroups is a process directed operation, - i.e. it affects the whole thread-group. + i.e. it affects the whole thread-group. Writing "threaded" to + "cgroup.type" fails with EBUSY while the cgroup, or a cgroup below + it, is being killed. cgroup.pressure A read-write single value file that allowed values are "0" and "1". diff --git a/include/linux/cgroup-defs.h b/include/linux/cgroup-defs.h index 0dae54b033e9..44e69e784057 100644 --- a/include/linux/cgroup-defs.h +++ b/include/linux/cgroup-defs.h @@ -72,6 +72,13 @@ enum { /* Cgroup is frozen. */ CGRP_FROZEN, + + /* + * cgroup.type is threaded. Set under css_set_lock when a switch to + * threaded succeeds, so that a kill and the switch exclude each other, + * see cgroup_enable_threaded() and cgroup_in_threaded_subtree(). + */ + CGRP_THREADED, }; /* cgroup_root->flags */ @@ -528,11 +535,16 @@ struct cgroup { int nr_threaded_children; /* # of live threaded child cgroups */ /* - * Sequence number for cgroup.kill, odd while a kill is walking the - * cgroup's tasks. Incremented with both cgroup_mutex and css_set_lock - * held. Readers hold either one. + * cgroup.kill state, protected by css_set_lock. A kill bumps + * kill_seq when it starts and when it ends walking this cgroup's + * tasks, and nr_killing counts such walks in progress. + * subtree_kill_seq and nr_subtree_kills do the same for whole kills + * of the subtree rooted here. See cgroup_kill(). */ unsigned int kill_seq; + unsigned int nr_killing; + unsigned int subtree_kill_seq; + unsigned int nr_subtree_kills; struct kernfs_node *kn; /* cgroup kernfs entry */ struct cgroup_file procs_file; /* handle for "cgroup.procs" */ diff --git a/include/linux/sched/task.h b/include/linux/sched/task.h index 90ed5bc3c7af..bc1c17fcafea 100644 --- a/include/linux/sched/task.h +++ b/include/linux/sched/task.h @@ -45,6 +45,7 @@ struct kernel_clone_args { struct cgroup *cgrp; struct css_set *cset; unsigned int kill_seq; + unsigned int subtree_kill_seq; }; /* diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c index 644bc653b180..070d15f4031d 100644 --- a/kernel/cgroup/cgroup.c +++ b/kernel/cgroup/cgroup.c @@ -2635,6 +2635,116 @@ void cgroup_attach_unlock(enum cgroup_attach_lock_mode lock_mode, cpus_read_unlock(); } +/* + * A cgroup.kill write in progress. It lives on the writer's stack and is on + * cgroup_kills, which is protected by css_set_lock. + */ +struct cgroup_kill_ctx { + struct list_head node; + struct cgroup *cgrp; /* the cgroup written to */ + struct pid *writer; /* see cgroup_kill_leaving_task() */ +}; + +static LIST_HEAD(cgroup_kills); + +/** + * cgroup_subtree_kill_seq - sample the cgroup.kill state of a cgroup's subtrees + * @cgrp: cgroup of interest + * @killing: if not %NULL, set to %true if a kill of @cgrp's subtree or of an + * ancestor's subtree is in progress + * + * Returns a value that changes whenever such a kill starts or ends. The root + * can't be killed. + */ +static unsigned int cgroup_subtree_kill_seq(struct cgroup *cgrp, bool *killing) +{ + unsigned int seq = 0; + int i; + + lockdep_assert_held(&css_set_lock); + + for (i = cgrp->level; i > 0; i--) { + struct cgroup *anc = cgrp->ancestors[i]; + + seq += anc->subtree_kill_seq; + if (killing && anc->nr_subtree_kills) + *killing = true; + } + return seq; +} + +/** + * cgroup_kill_forced - would a running kill force its SIGKILL to a task + * @task: task of interest + * @cgrp: cgroup of interest + * @killing: if not %NULL, set to %true if a kill of @cgrp's subtree or of an + * ancestor's subtree is in progress + * + * Returns %true if the walk of such a kill would force its SIGKILL to @task. + * The walk sends SIGKILL from the writer, and a pid namespace init ignores it + * unless the writer is outside its pid namespace, see send_signal_locked(). + * Code that kills on behalf of a kill runs in another task's context, so it + * decides for the writers here. + */ +static bool cgroup_kill_forced(struct task_struct *task, struct cgroup *cgrp, + bool *killing) +{ + struct pid_namespace *ns = task_active_pid_ns(task); + struct cgroup_kill_ctx *kill; + bool force = false; + + lockdep_assert_held(&css_set_lock); + + list_for_each_entry(kill, &cgroup_kills, node) { + if (!cgroup_is_descendant(cgrp, kill->cgrp)) + continue; + if (killing) + *killing = true; + if (!pid_nr_ns(kill->writer, ns)) + force = true; + } + return force; +} + +/** + * cgroup_kill_leaving_task - kill a task that leaves a subtree being killed + * @task: task leaving a css_set of @cgrp + * @cgrp: cgroup of interest + * + * If a kill of @cgrp's subtree or of an ancestor's subtree is in progress, + * kill @task the way the walk of that kill would, see cgroup_kill_forced(). + * current is the migrating task, not the writer. + */ +static void cgroup_kill_leaving_task(struct task_struct *task, + struct cgroup *cgrp) +{ + bool killing = false, force; + unsigned long flags; + + lockdep_assert_held(&css_set_lock); + + force = cgroup_kill_forced(task, cgrp, &killing); + if (!killing || (task->flags & PF_KTHREAD) || + !lock_task_sighand(task, &flags)) + return; + if (force || !(task->signal->flags & SIGNAL_UNKILLABLE)) + send_signal_locked(SIGKILL, SEND_SIG_PRIV, task, PIDTYPE_TGID); + unlock_task_sighand(task, &flags); +} + +/* Is a kill of @cgrp, or of a cgroup below it, in progress? */ +static bool cgroup_subtree_killing(struct cgroup *cgrp) +{ + struct cgroup_kill_ctx *kill; + + lockdep_assert_held(&css_set_lock); + + list_for_each_entry(kill, &cgroup_kills, node) + if (cgroup_is_descendant(kill->cgrp, cgrp)) + return true; + return false; +} + /** * cgroup_migrate_add_task - add a migration target task to a migration context * @task: target task @@ -2820,6 +2930,10 @@ static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx) struct css_set *from_cset = task_css_set(task); struct css_set *to_cset = cset->mg_dst_cset; + /* a task can't leave a subtree being killed */ + if (unlikely(!list_empty(&cgroup_kills))) + cgroup_kill_leaving_task(task, cset->dfl_cgrp); + get_css_set(to_cset); to_cset->nr_tasks++; css_set_move_task(task, from_cset, to_cset, true); @@ -3810,6 +3924,22 @@ static int cgroup_enable_threaded(struct cgroup *cgrp) !cgroup_can_be_thread_root(dom_cgrp)) return -EOPNOTSUPP; + /* + * cgroup.kill doesn't hold cgroup_mutex. The switch moves @cgrp and + * the threaded cgroups below it into the domain of @cgrp's parent. + * Threads of outside processes could then join a cgroup that a running + * kill walks, and the kill would take their whole process down. So + * don't switch while a kill of @cgrp, or of a cgroup below it, runs. + * No such kill can start until we're done: the subtree is empty, + * nothing can enter it while we hold cgroup_mutex, and cgroup_kill() + * returns right away for an empty subtree. + */ + spin_lock_irq(&css_set_lock); + ret = cgroup_subtree_killing(cgrp) ? -EBUSY : 0; + spin_unlock_irq(&css_set_lock); + if (ret) + return ret; + /* * The following shouldn't cause actual migrations and should * always succeed. @@ -3825,6 +3955,13 @@ static int cgroup_enable_threaded(struct cgroup *cgrp) parent->nr_threaded_children++; cgroup_finalize_control(cgrp, ret); + + /* new kills of @cgrp fail from now on, see cgroup_kill() */ + if (!ret) { + spin_lock_irq(&css_set_lock); + set_bit(CGRP_THREADED, &cgrp->flags); + spin_unlock_irq(&css_set_lock); + } return ret; } @@ -4348,12 +4485,15 @@ static ssize_t cgroup_freeze_write(struct kernfs_open_file *of, * Is @cgrp threaded, or below a threaded cgroup? When a cgroup turns threaded, * the threaded cgroups below it join its new domain, also those below a thread * root. So a cgroup below a threaded cgroup can hold threads of processes that - * live outside of it. + * live outside of it. CGRP_THREADED is set under css_set_lock when a switch to + * threaded succeeds, see cgroup_enable_threaded(). */ static bool cgroup_in_threaded_subtree(struct cgroup *cgrp) { + lockdep_assert_held(&css_set_lock); + for (; cgrp; cgrp = cgroup_parent(cgrp)) - if (cgroup_is_threaded(cgrp)) + if (test_bit(CGRP_THREADED, &cgrp->flags)) return true; return false; } @@ -4363,18 +4503,16 @@ static void __cgroup_kill(struct cgroup *cgrp) struct css_task_iter it; struct task_struct *task; - lockdep_assert_held(&cgroup_mutex); - /* - * kill_seq is odd while this walk is in progress. The walk can signal - * a forking parent after copy_process() passed its - * fatal_signal_pending() check, and can pass the parent before the - * child is linked. cgroup_post_fork() therefore kills the child if - * kill_seq was odd when cgroup_css_set_fork() sampled it, or if it - * changed since. + * The walk below can signal a forking parent after copy_process() + * passed its fatal_signal_pending() check, and can pass the parent + * before the child is linked. cgroup_post_fork() kills a child that + * is linked while a walk is in progress (nr_killing), or after one + * started or ended since cgroup_css_set_fork() sampled kill_seq. */ spin_lock_irq(&css_set_lock); cgrp->kill_seq++; + cgrp->nr_killing++; spin_unlock_irq(&css_set_lock); css_task_iter_start(&cgrp->self, CSS_TASK_ITER_THREADED, &it); @@ -4393,18 +4531,86 @@ static void __cgroup_kill(struct cgroup *cgrp) spin_lock_irq(&css_set_lock); cgrp->kill_seq++; + cgrp->nr_killing--; spin_unlock_irq(&css_set_lock); } -static void cgroup_kill(struct cgroup *cgrp) +/* + * cgroup.kill doesn't hold cgroup_mutex, so tasks can migrate, the subtree can + * grow and CLONE_INTO_CGROUP forks can run while it walks. Tasks that are in + * the subtree when the kill starts (nr_subtree_kills raised) can't get out: + * + * - a regular fork links the child next to the parent, see __cgroup_kill(); + * - cgroup_migrate_execute() kills a task leaving a css_set of a cgroup in the + * subtree, which covers moves out of the subtree, moves between its cgroups + * and css_set changes from controller changes; + * - cgroup_post_fork() kills a CLONE_INTO_CGROUP child whose parent is in the + * subtree while it is being killed. + * + * Both decide whether the SIGKILL is forced like the walk would, see + * cgroup_kill_forced(). + * + * Tasks that join the subtree from outside after the kill started may or may + * not be killed. So a kill of an empty subtree has nothing to do. + * + * Killing is a process directed operation, i.e. the whole thread-group is + * taken down, so act like we do for cgroup.procs and refuse threaded cgroups + * and the cgroups below them, see cgroup_in_threaded_subtree(). A cgroup can't + * switch to threaded while it, or a cgroup below it, is being killed, see + * cgroup_enable_threaded(). So every process with a thread in the subtree is + * entirely inside it. + */ +static int cgroup_kill(struct cgroup *cgrp) { + struct cgroup_kill_ctx kill = { .cgrp = cgrp }; struct cgroup_subsys_state *css; - struct cgroup *dsct; + int ret = 0; - lockdep_assert_held(&cgroup_mutex); + spin_lock_irq(&css_set_lock); + if (cgroup_is_dead(cgrp)) + ret = -ENODEV; + else if (cgroup_in_threaded_subtree(cgrp)) + ret = -EOPNOTSUPP; + /* an empty subtree has nothing to kill, see above */ + if (ret || !cgroup_is_populated(cgrp)) { + spin_unlock_irq(&css_set_lock); + return ret; + } + kill.writer = get_pid(task_pid(current)); + list_add(&kill.node, &cgroup_kills); + cgrp->subtree_kill_seq++; + cgrp->nr_subtree_kills++; + spin_unlock_irq(&css_set_lock); + + rcu_read_lock(); + css_for_each_descendant_pre(css, &cgrp->self) { + /* + * A task that enters an empty subtree later comes from + * outside, or from the part being killed and is killed then. + */ + if (!cgroup_is_populated(css->cgroup)) { + css = css_rightmost_descendant(css); + continue; + } + if (!css_tryget_online(css)) + continue; + rcu_read_unlock(); + + __cgroup_kill(css->cgroup); + cond_resched(); + + rcu_read_lock(); + css_put(css); + } + rcu_read_unlock(); - cgroup_for_each_live_descendant_pre(dsct, css, cgrp) - __cgroup_kill(dsct); + spin_lock_irq(&css_set_lock); + list_del(&kill.node); + cgrp->subtree_kill_seq++; + cgrp->nr_subtree_kills--; + spin_unlock_irq(&css_set_lock); + put_pid(kill.writer); + return 0; } static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf, @@ -4421,22 +4627,17 @@ static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf, if (kill != 1) return -ERANGE; - cgrp = cgroup_kn_lock_live(of->kn, false); + /* + * No cgroup_mutex, see cgroup_kill(). Still drop the active + * reference, so that removing the cgroup doesn't wait for a long walk. + */ + cgrp = cgroup_kn_break_active(of->kn); if (IS_ERR(cgrp)) return PTR_ERR(cgrp); - /* - * Killing is a process directed operation, i.e. the whole thread-group - * is taken down so act like we do for cgroup.procs and only make this - * writable in non-threaded cgroups. The cgroups below a threaded cgroup - * can hold threads of processes outside of them, so refuse those too. - */ - if (cgroup_in_threaded_subtree(cgrp)) - ret = -EOPNOTSUPP; - else - cgroup_kill(cgrp); + ret = cgroup_kill(cgrp); - cgroup_kn_unlock(of->kn); + cgroup_kn_unbreak_active(of->kn, cgrp); return ret ?: nbytes; } @@ -7085,9 +7286,18 @@ static int cgroup_css_set_fork(struct kernel_clone_args *kargs) goto err; } + /* + * cgroup.kill doesn't hold cgroup_mutex. Sample the target, which the + * child joins, and the subtrees containing the parent, which the child + * leaves, see cgroup_post_fork(). + */ + spin_lock_irq(&css_set_lock); + kargs->kill_seq = dst_cgrp->kill_seq; + kargs->subtree_kill_seq = cgroup_subtree_kill_seq(cset->dfl_cgrp, NULL); + spin_unlock_irq(&css_set_lock); + put_css_set(cset); kargs->cgrp = dst_cgrp; - kargs->kill_seq = dst_cgrp->kill_seq; return ret; err: @@ -7209,7 +7419,7 @@ void cgroup_post_fork(struct task_struct *child, { unsigned int cgrp_kill_seq = 0; unsigned long cgrp_flags = 0; - bool kill = false; + bool kill = false, killing = false, force = false; struct cgroup_subsys *ss; struct css_set *cset; int i; @@ -7221,13 +7431,22 @@ void cgroup_post_fork(struct task_struct *child, /* init tasks are special, only link regular threads */ if (likely(child->pid)) { - if (kargs->cgrp) { - cgrp_flags = kargs->cgrp->flags; - cgrp_kill_seq = kargs->cgrp->kill_seq; - } else { - cgrp_flags = cset->dfl_cgrp->flags; - cgrp_kill_seq = cset->dfl_cgrp->kill_seq; - } + struct cgroup *cgrp = kargs->cgrp ?: cset->dfl_cgrp; + + cgrp_flags = cgrp->flags; + cgrp_kill_seq = cgrp->kill_seq; + killing = cgrp->nr_killing; + + /* + * A CLONE_INTO_CGROUP child leaves the parent's cgroup. Don't + * let it out of a subtree that was being killed at any time + * during the fork. @current's cgroup is pinned by the + * threadgroup lock. + */ + if (kargs->cgrp && + cgroup_subtree_kill_seq(task_dfl_cgroup(current), + &killing) != kargs->subtree_kill_seq) + killing = true; WARN_ON_ONCE(!list_empty(&child->cg_list)); cset->nr_tasks++; @@ -7262,8 +7481,22 @@ void cgroup_post_fork(struct task_struct *child, * child down right after we finished preparing it for * userspace. */ - kill = kargs->kill_seq != cgrp_kill_seq || - (kargs->kill_seq & 1); + kill = killing || kargs->kill_seq != cgrp_kill_seq; + + /* + * Kill the child the way the walk would. current, the parent, + * can be a thread of a pid namespace init that a writer outside + * its namespace kills, and with CLONE_THREAD | CLONE_INTO_CGROUP + * the child can land in a cgroup that the walk has passed. If + * no kill is running anymore, its walk has already signalled the + * parent's thread group, and SEND_SIG_NOINFO from the parent + * decides the same way. + */ + if (kill && cset) + force = cgroup_kill_forced(child, cset->dfl_cgrp, NULL) || + (kargs->cgrp && + cgroup_kill_forced(child, task_dfl_cgroup(current), + NULL)); } spin_unlock_irq(&css_set_lock); @@ -7288,7 +7521,8 @@ void cgroup_post_fork(struct task_struct *child, /* Cgroup has to be killed so take down child immediately. */ if (unlikely(kill)) - do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, child, PIDTYPE_TGID); + do_send_sig_info(SIGKILL, force ? SEND_SIG_PRIV : SEND_SIG_NOINFO, + child, PIDTYPE_TGID); cgroup_fork_child_unlock(child); cgroup_css_set_put_fork(kargs); -- 2.53.1-Meta 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 Signed-off-by: Andrew Morton Signed-off-by: Shakeel Butt --- 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