Re: [PATCH v2 3/3] mm/khugepaged: release contended mmap read lock after scanning enough VMAs

From: Baolin Wang

Date: Fri Nov 06 2026 - 04:56:40 EST




On 11/6/26 4:57 AM, Lorenzo Stoakes (ARM) wrote:
khugepaged walks an mm's VMAs under the mmap read lock in
collapse_scan_mm_slot(), checking for ineligible VMAs first, and skipping
them if encountered.

It charges cc->progress 1 page against the /sys/.../pages_to_scan budget
when these are encountered, however only checking this budget once an
eligible PMD-spanning VMA is encountered.

It can therefore hold the mmap read lock for a long time if there are a
large number of ineligible VMAs present in an mm, over which time no mmap
write locks (and thus no VMA write locks) can be acquired.

Address this by checking whether the mmap lock is contended after every
KHUGEPAGED_MAX_VMA_SCAN_BATCH VMAs walked, that is a quarter of the
pages_to_scan budget, and if so dropping and re-acquiring the mmap read
lock before resuming the walk from the per-mm cursor.

As the walk is resumed from the cursor rather than the VMA that was current
when the lock was dropped, the cursor must never move backwards. A VMA
ending at the top of the address space causes ALIGN() to wrap the cursor to
zero, so treat such a VMA as the last in the mm rather than skipping past
it.

This was tested locally with ~1M ineligible VMAs mapped ahead of a
collapsible region of memory, and resulted in a reduced mmap_lock hold time
of 170us down from 95ms.

This was also observed to reduce mmap_lock stalls in concurrent threads of
a similar duration. Note that a reader re-acquiring the lock can currently
steal it from a writer that is queued but not yet running, so the full
benefit to writers depends on the separate rwsem change at [0].

Local measurements indicated no change for ordinary use cases, so this is
all upside.

This work came out of investigations into mmap stalls when getting latency
numbers for an unrelated patch series.

[0]: https://lore.kernel.org/all/20261105-rwsem-dont-steal-from-queued-writer-v1-1-275e070f426f@xxxxxxxxxx/

Signed-off-by: Lorenzo Stoakes (ARM) <ljs@xxxxxxxxxx>
---

[snip]

if (!collapse_possible_orders(vma, vma->vm_flags, TVA_KHUGEPAGED)) {
- /* Unable to collapse, skip to the next candidate. */
- mm_slot->address = ALIGN(vma->vm_end, HPAGE_PMD_SIZE);
+ const unsigned long next =
+ ALIGN(vma->vm_end, HPAGE_PMD_SIZE);
+
cc->progress++;
+ /* Check for overflow. */
+ if (unlikely(next < vma->vm_end)) {
+ vma = NULL;
+ break;
+ }
+ /* Unable to collapse, skip to the next candidate. */
+ mm_slot->address = next;
continue;
}

IMO, these changes seem to belong in patch 2?