[PATCH linux-next 2/6] memcontrol: introduce the new mem_cgroup_scan_tasks()

From: xu.xin16
Date: Thu Apr 03 2025 - 01:30:26 EST


From: xu xin <xu.xin16@xxxxxxxxxx>

Introduce a new mem_cgroup_scan_tasks function that strictly iterates
processes only within the current memcgroup, aligning its behavior with
its name.

Signed-off-by: xu xin <xu.xin16@xxxxxxxxxx>
---
include/linux/memcontrol.h | 7 +++++++
mm/memcontrol.c | 24 ++++++++++++++++++++++++
2 files changed, 31 insertions(+)

diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
index 232cea80e71f..3af34e124ce6 100644
--- a/include/linux/memcontrol.h
+++ b/include/linux/memcontrol.h
@@ -795,6 +795,8 @@ struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *,
struct mem_cgroup *,
struct mem_cgroup_reclaim_cookie *);
void mem_cgroup_iter_break(struct mem_cgroup *, struct mem_cgroup *);
+void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
+ int (*)(struct task_struct *, void *), void *arg);
void mem_cgroup_tree_scan_tasks(struct mem_cgroup *memcg,
int (*)(struct task_struct *, void *), void *arg);

@@ -1289,6 +1291,11 @@ static inline void mem_cgroup_iter_break(struct mem_cgroup *root,
{
}

+static inline void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
+ int (*fn)(struct task_struct *, void *), void *arg)
+{
+}
+
static inline void mem_cgroup_tree_scan_tasks(struct mem_cgroup *memcg,
int (*fn)(struct task_struct *, void *), void *arg)
{
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 9af30fbfe819..aff5a095b9e4 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -1150,6 +1150,30 @@ static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
dead_memcg);
}

+/* *
+ * mem_cgroup_scan_tasks - iterate over tasks of only this memory cgroup.
+ * @memcg: the specified memory cgroup.
+ * @fn: function to call for each task
+ * @arg: argument passed to @fn
+ *
+ * Unlike mem_cgroup_tree_scan_tasks(), this function only iterate over
+ * these tasks attached to @memcg, not including any of its descendants
+ * memcg. And this could be called for the root memory cgroup.
+ */
+void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
+ int (*fn)(struct task_struct *, void *), void *arg)
+{
+ int ret = 0;
+ struct css_task_iter it;
+ struct task_struct *task;
+
+ css_task_iter_start(&memcg->css, CSS_TASK_ITER_PROCS, &it);
+ while (!ret && (task = css_task_iter_next(&it)))
+ ret = fn(task, arg);
+
+ css_task_iter_end(&it);
+}
+
/**
* mem_cgroup_tree_scan_tasks - iterate over tasks of a memory cgroup hierarchy
* @memcg: hierarchy root
--
2.15.