Re: [PATCH 3/3] mm/hugetlb: fix NR_HUGETLB accounting for unused surplus folios

From: Muchun Song

Date: Wed Oct 28 2026 - 23:22:17 EST




> On Oct 28, 2026, at 23:01, Oscar Salvador (SUSE) <osalvador@xxxxxxxxxx> wrote:
>
> On Wed, Oct 28, 2026 at 07:33:19PM +0800, Kaitao Cheng wrote:
>> From: Kaitao Cheng <chengkaitao@xxxxxxxxxx>
>>
>> free_huge_folio() unconditionally decrements NR_HUGETLB, but freshly
>> allocated surplus folios can be freed before the counter has been
>> incremented.
>>
>> This happens when alloc_surplus_hugetlb_folio() rejects a fresh folio
>> after its second surplus limit check. It also happens when
>> gather_surplus_pages() frees folios because a reservation cannot be
>> satisfied, or because concurrent pool changes leave excess folios
>> after the reservation succeeds.
>>
>> These paths leave unmatched decrements, causing HugeTLB usage to be
>> underreported and potentially underflowing the counter.
>>
>> Increment NR_HUGETLB before calling free_huge_folio() in both paths
>> to balance its unconditional decrement.
>>
>> Fixes: 05d4532b60e3 ("memcg/hugetlb: add hugeTLB counters to memcg")
>> Closes: https://sashiko.dev/#/bug/linux-860a3b8f-0b07-4cd5-a122-aa2288463bee
>> Signed-off-by: Kaitao Cheng <chengkaitao@xxxxxxxxxx>
>
> I feel like the whole hugetlb accounting is a bit of a nightmare.

Can't agree more.

> I wish we could teach free_huge_folio to ignore accounting-wise these pages
> but not sure if that would be any prettier/easier.

My thinking is that we should not use lruvec_stat_mod_folio(). Instead, we
should use mod_node_page_state() and mod_memcg_lruvec_state()
independently. In that case, when a new hugetlb page is allocated, we could
account for it directly via mod_node_page_state(). The reason is that
lruvec_stat_mod_folio() also accounts per-memcg NR_HUGETLB; only by
splitting the two can we minimize the problems introduced by accounting. For
callers that need to consider memcg, mod_memcg_lruvec_state() can be used.

I expect that after some cleanup, there will be only one place that needs to
handle per-node NR_HUGETLB.

Thoughts?

Thanks,
Muchun


> I will have another look later on.
>
>
>
> --
> Oscar Salvador
> SUSE Labs