Re: [PATCH] mm/swap: fix swap cache memcg accounting
From: Nhat Pham
Date: Fri Mar 20 2026 - 15:36:52 EST
On Thu, Mar 19, 2026 at 10:06 PM Alexandre Ghiti <alex@xxxxxxxx> wrote:
>
> The swap readahead path was recently refactored and while doing this,
> the order between the charging of the folio in the memcg and the addition
> of the folio in the swap cache was inverted.
>
> Since the accounting of the folio is done while adding the folio to the
> swap cache and the folio is not charged in the memcg yet, the accounting
> is then done at the node level, which is wrong.
>
> Fix this by charging the folio in the memcg before adding it to the swap cache.
>
> Fixes: 2732acda82c9 ("mm, swap: use swap cache as the swap in synchronize layer")
> Signed-off-by: Alexandre Ghiti <alex@xxxxxxxx>
> ---
> mm/swap_state.c | 9 ++++-----
> 1 file changed, 4 insertions(+), 5 deletions(-)
>
> diff --git a/mm/swap_state.c b/mm/swap_state.c
> index 6d0eef7470be..48aff2c917c0 100644
> --- a/mm/swap_state.c
> +++ b/mm/swap_state.c
> @@ -494,6 +494,10 @@ static struct folio *__swap_cache_prepare_and_add(swp_entry_t entry,
>
> __folio_set_locked(folio);
> __folio_set_swapbacked(folio);
> +
> + if (!charged && mem_cgroup_swapin_charge_folio(folio, NULL, gfp, entry))
> + goto failed;
> +
> for (;;) {
> ret = swap_cache_add_folio(folio, entry, &shadow);
> if (!ret)
> @@ -514,11 +518,6 @@ static struct folio *__swap_cache_prepare_and_add(swp_entry_t entry,
> goto failed;
> }
>
Reviewed-by: Nhat Pham <nphamcs@xxxxxxxxx>