Re: [PATCH 2/4] mm/madvise: don't declare OOM for MADV_WILLNEED swapin

From: David Hildenbrand (Arm)

Date: Mon Nov 30 2026 - 07:30:48 EST


On 11/27/26 20:45, Lorenzo Stoakes (ARM) wrote:
> From: Chris Mason <mason@xxxxxxxxxx>
>
> MADV_WILLNEED on memory in swap can OOM kill a task when the memcg that
> the swap entries are charged to is at its limit.
>
> The hint is only a prefetch, so it has to give up on a page when memory
> is short. But swapin_walk_pmd_entry() and shmem_swapin_range() call
> read_swap_cache_async() with GFP_HIGHUSER_MOVABLE and with the gfp mask
> of the mapping, so the allocation and the memcg charge can both go as
> far as the OOM killer.

A lot of the "can trigger OOM killer" AI reports are utter garbage. But this
here seems like something reasonable to do.

>
> The charge goes to the memcg of the swap entry, which need not be the
> caller's.
>
> The fix used here is to allocate with the gfp mask of readahead, and to
> flush the block plug when a page fails. madvise_do_behavior() plugs the
> whole walk, so the swap writes of reclaim can sit in that plug. Their
> folios stay under writeback, and with no retries the rest of the range
> can fail as well.
>
> The hint can now skip pages when memory is short, whether in a memcg at
> its limit or on the system as a whole, since neither the allocation nor
> the memcg charge is retried any longer.
>
> This applies in particular where reclaim has to write to swap to make
> room. Skipped pages stay in swap until a fault reads them.
>
> Fixes: 4c6355b25e8b ("mm: memcontrol: charge swapin pages on instantiation")
> Signed-off-by: Chris Mason <mason@xxxxxxxxxx>
> [ ljs: commit message tweak ]
> Signed-off-by: Lorenzo Stoakes (ARM) <ljs@xxxxxxxxxx>
> ---
> mm/madvise.c | 19 ++++++++++++++-----
> 1 file changed, 14 insertions(+), 5 deletions(-)
>
> diff --git a/mm/madvise.c b/mm/madvise.c
> index ebb4ce7daf6c..8b56f7aea935 100644
> --- a/mm/madvise.c
> +++ b/mm/madvise.c
> @@ -196,6 +196,8 @@ static int madvise_update_vma(vm_flags_t new_flags,
> static int swapin_walk_pmd_entry(pmd_t *pmd, unsigned long start,
> unsigned long end, struct mm_walk *walk)
> {
> + /* Only a prefetch, as in readahead_gfp_mask() */
> + const gfp_t gfp = GFP_HIGHUSER_MOVABLE | __GFP_NORETRY | __GFP_NOWARN;
> struct vm_area_struct *vma = walk->private;
> struct swap_io_ctx ctx = {};
> pte_t *ptep = NULL;
> @@ -221,10 +223,13 @@ static int swapin_walk_pmd_entry(pmd_t *pmd, unsigned long start,
> pte_unmap_unlock(ptep, ptl);
> ptep = NULL;
>
> - folio = read_swap_cache_async(&ctx, entry, GFP_HIGHUSER_MOVABLE,
> - vma, addr);
> - if (folio)
> + folio = read_swap_cache_async(&ctx, entry, gfp, vma, addr);
> + if (folio) {
> folio_put(folio);
> + } else {
> + /* Reclaim queues its swap writes in our plug */
> + blk_flush_plug(current->plug, false);

No idea about that magic. Let's hope it doesn't cause harm :)

Acked-by: David Hildenbrand (Arm) <david@xxxxxxxxxx>

--
Cheers,

David