Re: [PATCH] mm/hugetlb: charge hugetlb cgroup and memcg in alloc_hugetlb_folio_reserve()

From: Hongfu Li

Date: Thu Oct 22 2026 - 02:42:22 EST



On 10/22/26 7:59 AM, Andrew Morton wrote:
On Tue, 20 Oct 2026 16:46:30 +0800 Hongfu Li <hongfu.li@xxxxxxxxx> wrote:

From: Hongfu Li <lihongfu@xxxxxxxxxx>

alloc_hugetlb_folio_reserve() hands out a folio from the hugetlb pool and
consumes a global reservation, but unlike the fault path it never charged
the folio to the hugetlb cgroup or to the memcg. Folios allocated for
memfd_pin_folios() through memfd_alloc_folio() were therefore silently
bypassing the accounting: they are never charged to the hugetlb cgroup
usage counter (hugetlb.<size>.current) nor to the memcg (memory.current),
so both limits (hugetlb.<size>.max, memory.max) are bypassed.

Charge the folios to both the hugetlb cgroup and the memcg, just like
hugetlb_alloc_folio() does.

Test with a process that creates a hugetlb memfd and pins pages through
UDMABUF_CREATE. The counters were read while the folio was still pinned:

Before this patch:
$ echo $$ > /sys/fs/cgroup/test/cgroup.procs
$ ./memfd-alloc-folio 1 &
$ cat /sys/fs/cgroup/test/hugetlb.2MB.current
0
$ cat /sys/fs/cgroup/test/memory.current
1351680
$

After this patch:
$ echo $$ > /sys/fs/cgroup/test/cgroup.procs
$ ./memfd-alloc-folio 1 &
$ cat /sys/fs/cgroup/test/hugetlb.2MB.current
2097152
$ cat /sys/fs/cgroup/test/memory.current
3313664
$
Thanks. The before-and-after output is useful.

However there are potential interactions with Daehyeon Ko's
"mm/hugetlb_cgroup: prevent use-after-free during cgroup offlining".
https://lore.kernel.org/20261020100345.1677643-1-4ncienth@xxxxxxxxx

Your patch adds another caller of hugetlb_cgroup_charge_cgroup(), which
has the cgroup-offlining CSS lifetime race addressed by Daehyeon Ko's
fix.

An existing memfd reservation can belong to cgroup A while the task
pinning the folio belongs to cgroup B. A's reservation CSS reference
does not protect B's usage CSS across charge and commit.

Also, the accounting bypass predates 26a8ea80929c. The original
memfd_pin_folios() implementation already used an uncharged allocator,
so the Fixes tag should reference 89c1905d9c14 instead.

Agreed, the bypass has been there since memfd_pin_folios() was
introduced. I'll update the Fixes tag.

The memory.max claim should be qualified: HugeTLB accounting in memcg
is conditional on the cgroup v2 hierarchy's accounting configuration.

Right, I'll qualify that in the commit message.

Daehyeon's fix is in the pipeline at present, awaiting a minor fixup
and maintainer review. Everything is rather swamped at present.

So please assume that Daehyeon's fix is present and rethink your fix on
top of that?

Sure, I'll rework the patch on top of his fix and resend as v2 after his
series has been reviewed.  I'll re-run the test with both applied before
sending.

--
Best regards,
Hongfu