[PATCH] cgroup: optimize the account of nr_cgrps

From: haifeng.xu
Date: Tue Oct 11 2022 - 03:30:42 EST


When use 'lscgroup' to account the number of cgroups in hierarchy,
we find that it's much less than the number showed by '/proc/cgroups'.

The reason is that the cgroup isn't freed even though remove the
directory, unless the percpu_ref of cgroup.self reaches zero.
For example, there are many page/buffer cache which obtain
references on the specified css. So only these memory are relcaimed,
the cgroup could be freed.

The cgroup is invisible for users after the corresponding directory
is removed. Therefore decrease the number of cgroups when call
'cgroup_rmdir'.

Signed-off-by: haifeng.xu <haifeng.xu@xxxxxxxxxx>
---
kernel/cgroup/cgroup.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c
index c37b8265c0a3..9443df5d86bb 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -5222,7 +5222,6 @@ static void css_free_rwork_fn(struct work_struct *work)
css_put(parent);
} else {
/* cgroup free path */
- atomic_dec(&cgrp->root->nr_cgrps);
cgroup1_pidlist_destroy_all(cgrp);
cancel_work_sync(&cgrp->release_agent_work);

@@ -5781,6 +5780,7 @@ static int cgroup_destroy_locked(struct cgroup *cgrp)
/* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
css_clear_dir(&cgrp->self);
kernfs_remove(cgrp->kn);
+ atomic_dec(&cgrp->root->nr_cgrps);

if (cgroup_is_threaded(cgrp))
parent->nr_threaded_children--;
--
2.25.1