Re: [PATCH 6.18.y v2] mm: shmem: fix potential livelock issue for shmem direct swapin

From: Barry Song

Date: Fri Jul 10 2026 - 05:41:49 EST


On Fri, Jul 10, 2026 at 10:09 AM Baolin Wang
<baolin.wang@xxxxxxxxxxxxxxxxx> wrote:
>
> When skipping swapcache for synchronous IO swap devices, swapcache_prepare()
> is used to prevent parallel swapin from proceeding with the swap cache flag.
> However, on PREEMPT kernels this can lead to a livelock, as reported by Chao[1]:
>
> Thread A starts direct swapin of a shmem folio and calls swapcache_prepare()
> to set SWAP_HAS_CACHE. It may then be preempted inside workingset_refault().
> Meanwhile, a higher priority thread B also attempts direct swapin of the same
> shmem swap entry. Since swapcache_prepare() already marks the entry, thread B
> repeatedly gets -EEXIST and busy-loops waiting for thread A to finish. But as
> thread B runs at higher priority, thread A cannot preempt it, resulting in
> starvation and a livelock.
>
> Fix it by yielding the CPU with schedule_timeout_uninterruptible(1) when
> swapcache_prepare() fails, following the same approach used in commit
> 029c4628b2eb ("mm: swap: get rid of livelock in swapin readahead") and
> commit 13ddaf26be32 ("mm/swap: fix race when skipping swapcache").
>
> However, commit 01626a1823 ("mm: avoid unconditional one-tick sleep when
> swapcache_prepare fails") found that the unconditional one-tick sleep can
> cause UI stuttering on latency-sensitive Android devices. So we can follow
> the same approach by adding a waitqueue to wake up tasks when needed,
> instead of always sleeping for a full tick.
>
> Note that mainline does not have this potential issue, which has already been
> resolved by Kairui's swap refactoring work[2].
>
> [1] https://lore.kernel.org/all/700a2cbf90a2484f979aac858f08f5d4@xxxxxxxxxx/
> [2] https://lore.kernel.org/all/20260517-swap-table-p4-v5-0-88ae43e064c7@xxxxxxxxxxx/
> Fixes: 1dd44c0af4fa ("mm: shmem: skip swapcache for swapin of synchronous swap device")
> Reported-by: Ma Chao <machao26@xxxxxxxxxx>
> Closes: https://lore.kernel.org/all/700a2cbf90a2484f979aac858f08f5d4@xxxxxxxxxx/
> Signed-off-by: Baolin Wang <baolin.wang@xxxxxxxxxxxxxxxxx>
> ---

LGTM,
Acked-by: Barry Song <baohua@xxxxxxxxxx>