Re: [PATCH 13/19] mm, swap: remove workaround for unsynchronized swap map cache state

From: Kairui Song
Date: Sun Nov 09 2025 - 09:19:03 EST


On Fri, Nov 7, 2025 at 11:07 AM Barry Song <21cnbao@xxxxxxxxx> wrote:
>
> > struct folio *swap_cache_alloc_folio(swp_entry_t entry, gfp_t gfp_mask,
> > struct mempolicy *mpol, pgoff_t ilx,
> > - bool *new_page_allocated,
> > - bool skip_if_exists)
> > + bool *new_page_allocated)
> > {
> > struct swap_info_struct *si = __swap_entry_to_info(entry);
> > struct folio *folio;
> > @@ -548,8 +542,7 @@ struct folio *swap_cache_alloc_folio(swp_entry_t entry, gfp_t gfp_mask,
> > if (!folio)
> > return NULL;
> > /* Try add the new folio, returns existing folio or NULL on failure. */
> > - result = __swap_cache_prepare_and_add(entry, folio, gfp_mask,
> > - false, skip_if_exists);
> > + result = __swap_cache_prepare_and_add(entry, folio, gfp_mask, false);
> > if (result == folio)
> > *new_page_allocated = true;
> > else
> > @@ -578,7 +571,7 @@ struct folio *swapin_folio(swp_entry_t entry, struct folio *folio)
> > unsigned long nr_pages = folio_nr_pages(folio);
> >
> > entry = swp_entry(swp_type(entry), round_down(offset, nr_pages));
> > - swapcache = __swap_cache_prepare_and_add(entry, folio, 0, true, false);
> > + swapcache = __swap_cache_prepare_and_add(entry, folio, 0, true);
> > if (swapcache == folio)
> > swap_read_folio(folio, NULL);
> > return swapcache;
>
> I wonder if we could also drop the "charged" — it doesn’t seem
> difficult to move the charging step before
> __swap_cache_prepare_and_add(), even for swap_cache_alloc_folio()?

Hi Barry, thanks for the review and suggestion.

It may cause much more serious cgroup thrashing. Charge may cause
reclaim, so races swapin will have a much larger race window and cause
a lot of repeated folio alloc / charge.

This param exists because anon / shmem does their own charge for large
folio swapin, and then inserts the folio into the swap cache, which is
causing more memory pressure already. I think ideally we want to unify
all alloc & charging for swap in folio allocation, and have a
swap_cache_alloc_folio that supports `orders`. For raced swapin only
one will insert a folio successfully into the swap cache and charge
it, which should make the race window very tiny or maybe avoid
redundant folio allocation completely with further work. I did some
tests and it shows that it will improve the memory usage and avoid
some OOM under pressure for (m)THP.

BTW with current SWAP_HAS_CACHE design, we also have redundant folio
alloc for order 0 when under global pressure, as folio alloc is done
before setting SWAP_HAS_CACHE. But having SWAP_HAS_CACHE set then do
the folio alloc will increase the chance of hitting the idle/busy loop
on SWAP_HAS_CACHE which is also kind of problematic. We should be able
to clean it up in later phases.