shmem_partial_swap_usage() counts whole swap entries even when only part of an entry falls within the requested range. Further, when a walk starts inside a large entry, xas_pause() can resume beyond its end and skip subsequent entries. Consequently, we can overcount "Swap" in /proc//smaps and smaps_rollup, especially for private writable mappings where the function can be called once per empty PTE, but we can also undercount it. Let's fix it by clamping each entry to the remaining range and advancing "start" to avoid counting pages twice, and by using xas_set() to resume at the first uncounted index after cond_resched_rcu(). This has low urgency, as it only affects the "Swap" statistics in /proc//smaps and smaps_rollup. No need to CC stable. Fixes: 50f381eccefd ("mm: shmem: extend shmem_partial_swap_usage() to support large folio swap") Reported-by: Chris Mason Reviewed-by: Zi Yan Tested-by: Gregory Price (Meta) Reviewed-by: Baolin Wang Signed-off-by: David Hildenbrand (Arm) --- mm/shmem.c | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/mm/shmem.c b/mm/shmem.c index 9bc4388e38c6b..57eaa867028ef 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -1256,14 +1256,32 @@ unsigned long shmem_partial_swap_usage(struct address_space *mapping, rcu_read_lock(); xas_for_each(&xas, folio, max) { + unsigned long nr_pages; + pgoff_t first, last; + if (xas_retry(&xas, folio)) continue; + + /* Obtain the range of the spanned entry. */ + nr_pages = 1UL << xas_get_order(&xas); + first = round_down(xas.xa_index, nr_pages); + last = first + nr_pages - 1; + + /* Clamp to the remaining range of interest. */ + first = max(first, start); + last = min(last, max); + if (first > last) + continue; + + /* Account only clamped range as swapped. */ if (xa_is_value(folio)) - swapped += 1 << xas_get_order(&xas); - if (xas.xa_index == max) + swapped += last - first + 1; + if (last == max) break; + start = last + 1; if (need_resched()) { - xas_pause(&xas); + /* Resume at the first index that is not counted yet. */ + xas_set(&xas, start); cond_resched_rcu(); } } -- 2.56.1