[RFC PATCH 3/9 v2] mm/memcontrol: Refactor page_counter charging in try_charge_memcg

From: Joshua Hahn

Date: Thu Apr 23 2026 - 16:38:01 EST


In preparation for adding charging and uncharging of a new page_counter
toptier to try_charge_memcg, refactor the code so that it is easier to
roll back partial charges when any one of the three page_counters
fail to charge.

No functional changes intended.

Signed-off-by: Joshua Hahn <joshua.hahnjy@xxxxxxxxx>
---
mm/memcontrol.c | 20 ++++++++++++--------
1 file changed, 12 insertions(+), 8 deletions(-)

diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 7de23ecd7cef6..8f7bedb55dbb1 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -2385,18 +2385,22 @@ static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,

retry:
reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
- if (!do_memsw_account() ||
- page_counter_try_charge(&memcg->memsw, nr_pages, &counter)) {
- if (page_counter_try_charge(&memcg->memory, nr_pages, &counter))
- goto done_restock;
- if (do_memsw_account())
- page_counter_uncharge(&memcg->memsw, nr_pages);
- mem_over_limit = mem_cgroup_from_counter(counter, memory);
- } else {
+
+ if (do_memsw_account() &&
+ !page_counter_try_charge(&memcg->memsw, nr_pages, &counter)) {
mem_over_limit = mem_cgroup_from_counter(counter, memsw);
reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
+ goto reclaim;
}

+ if (page_counter_try_charge(&memcg->memory, nr_pages, &counter))
+ goto done_restock;
+
+ if (do_memsw_account())
+ page_counter_uncharge(&memcg->memsw, nr_pages);
+ mem_over_limit = mem_cgroup_from_counter(counter, memory);
+
+reclaim:
/*
* Prevent unbounded recursion when reclaim operations need to
* allocate memory. This might exceed the limits temporarily,
--
2.52.0