Re: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
From: Ackerley Tng
Date: Thu Sep 18 2025 - 02:38:34 EST
Michael Roth <michael.roth@xxxxxxx> writes:
> On Wed, May 14, 2025 at 04:42:08PM -0700, Ackerley Tng wrote:
>>
>> [...snip...]
>>
>> +static void *guestmem_hugetlb_setup(size_t size, u64 flags)
>> +
>> +{
>> + struct guestmem_hugetlb_private *private;
>> + struct hugetlb_cgroup *h_cg_rsvd = NULL;
>> + struct hugepage_subpool *spool;
>> + unsigned long nr_pages;
>> + int page_size_log;
>> + struct hstate *h;
>> + long hpages;
>> + int idx;
>> + int ret;
>> +
>> + page_size_log = (flags >> GUESTMEM_HUGETLB_FLAG_SHIFT) &
>> + GUESTMEM_HUGETLB_FLAG_MASK;
>> + h = hstate_sizelog(page_size_log);
>> + if (!h)
>> + return ERR_PTR(-EINVAL);
>> +
>> + /*
>> + * Check against h because page_size_log could be 0 to request default
>> + * HugeTLB page size.
>> + */
>> + if (!IS_ALIGNED(size, huge_page_size(h)))
>> + return ERR_PTR(-EINVAL);
>
> For SNP testing we ended up needing to relax this to play along a little
> easier with QEMU/etc. and instead just round the size up via:
>
> size = round_up(size, huge_page_size(h));
>
> The thinking is that since, presumably, the size would span beyond what
> we actually bind to any memslots, that KVM will simply map them as 4K
> in nested page table, and userspace already causes 4K split and inode
> size doesn't change as part of this adjustment so the extra pages would
> remain inaccessible.
>
> The accounting might get a little weird but it's probably fair to
> document that non-hugepage-aligned gmemfd sizes can result in wasted memory
> if userspace wants to fine tune around that.
Is there a specific use case where the userspace VMM must allocate some
guest_memfd file size that isn't huge_page_size(h) aligned?
Rounding up silently feels like it would be hiding errors, and feels a
little especially when we're doing so much work to save memory,
retaining HVO, removing double allocation and all.
>
> -Mike
>
>> +
>> + private = kzalloc(sizeof(*private), GFP_KERNEL);
>> + if (!private)
>> + return ERR_PTR(-ENOMEM);
>> +
>> + /* Creating a subpool makes reservations, hence charge for them now. */
>> + idx = hstate_index(h);
>> + nr_pages = size >> PAGE_SHIFT;
>> + ret = hugetlb_cgroup_charge_cgroup_rsvd(idx, nr_pages, &h_cg_rsvd);
>> + if (ret)
>> + goto err_free;
>> +
>> + hpages = size >> huge_page_shift(h);
>> + spool = hugepage_new_subpool(h, hpages, hpages, false);
>> + if (!spool)
>> + goto err_uncharge;
>> +
>> + private->h = h;
>> + private->spool = spool;
>> + private->h_cg_rsvd = h_cg_rsvd;
>> +
>> + return private;
>> +
>> +err_uncharge:
>> + ret = -ENOMEM;
>> + hugetlb_cgroup_uncharge_cgroup_rsvd(idx, nr_pages, h_cg_rsvd);
>> +err_free:
>> + kfree(private);
>> + return ERR_PTR(ret);
>> +}
>> +
>>
>> [...snip...]
>>