1G page support for guest_memfd
Subsystems (22)
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Ira WeinyQuoted 14 lines
Quoted 14 lines
Quoted 14 lines
Quoted 6 lines
Quoted 4 lines
Yan, Yilun, would it work if, on conversion,
1.
guest_memfdnotifies IOMMU that a conversion is about to happen for a PFN rangeIt is the Guest fw call to release the pinning.
I see, thanks for explaining.
Quoted 4 lines
By the time VMM get the
conversion requirement, the page is already physically unpinned. So I agree with Jason the pinning doesn't have to reach to iommu from SW POV.
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines
If by the time KVM gets the conversion request, the page is unpinned, then we're all good, right?
Yes, unless guest doesn't unpin the page first by mistake.
Or maliciously? :-(
Yes.
Quoted 5 lines
My initial response to this was that this is a bug and we don't need to be concerned with it. However, can't this be a DOS from one TD to crash the system if the host uses the private page for something else and the machine #MC's?
I think we are already doing something to prevent vcpus from executing then destroy VM, so no further TD accessing. But I assume there is concern a TD could just leak a lot of resources, and we are investigating if host can reclaim them.
Thanks,
Yilun
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 29 lines · Xu Yilun
Quoted 14 lines
Quoted 14 lines
Quoted 14 lines
Quoted 6 lines
Quoted 4 lines
Yan, Yilun, would it work if, on conversion,
1.
guest_memfdnotifies IOMMU that a conversion is about to happen for a PFN rangeIt is the Guest fw call to release the pinning.
I see, thanks for explaining.
Quoted 4 lines
By the time VMM get the
conversion requirement, the page is already physically unpinned. So I agree with Jason the pinning doesn't have to reach to iommu from SW POV.Quoted 6 lines
Quoted 4 lines
Quoted 2 lines
If by the time KVM gets the conversion request, the page is unpinned, then we're all good, right?
Yes, unless guest doesn't unpin the page first by mistake.
Or maliciously? :-(
Yes.
Quoted 5 lines
My initial response to this was that this is a bug and we don't need to be concerned with it. However, can't this be a DOS from one TD to crash the system if the host uses the private page for something else and the machine #MC's?
Quoted 7 lines
I think we are already doing something to prevent vcpus from executing then destroy VM, so no further TD accessing. But I assume there is concern a TD could just leak a lot of resources, and we are investigating if host can reclaim them.
Thanks,
Yilun
Sounds like a malicious guest could skip unpinning private memory, and guest_memfd's unmap will fail, leading to a KVM_BUG_ON() as Yan/Rick suggested here [1].
Actually it seems like a legacy guest would also lead to unmap failures and the KVM_BUG_ON(), since when TDX connect is enabled, the pinning mode is enforced, even for non-IO private pages?
I hope your team's investigations find a good way for the host to reclaim memory, at least from dead TDs! Otherwise this would be an open hole for guests to leak a host's memory.
Circling back to the original topic [2], it sounds like we're okay for IOMMU to *not* take any refcounts on pages and can rely on guest_memfd to keep the page around on behalf of the VM?
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/CAGtprH_qh8sEY3s-JucW3n1Wvoq7jdVZDDokvG5HzPf0HV2=pg@mail.gmail.com/
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 12 lines · Ackerley Tng
Sounds like a malicious guest could skip unpinning private memory, and guest_memfd's unmap will fail, leading to a
KVM_BUG_ON()as Yan/Rick suggested here [1].Actually it seems like a legacy guest would also lead to unmap failures and the
KVM_BUG_ON(), since when TDX connect is enabled, the pinning mode is enforced, even for non-IO private pages?I hope your team's investigations find a good way for the host to reclaim memory, at least from dead TDs! Otherwise this would be an open hole for guests to leak a host's memory.
Quoted 6 lines
Circling back to the original topic [2], it sounds like we're okay for IOMMU to *not* take any refcounts on pages and can rely on
guest_memfdto keep the page around on behalf of the VM?[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/CAGtprH_qh8sEY3s-JucW3n1Wvoq7jdVZDDokvG5HzPf0HV2=pg@mail.gmail.com/
Djbw, Yilun and I had a chat yesterday. We'll investigate a way to have an operation that can't fail and will allow total cleanup and reclaim for the TD's resources, as well as a per-TDX module scoped version.
If host userspace or the guest kernel does something wrong, the guest can be destroyed in the normal VM case. So we can try to use these operations as a way to save host kernel complexity for cases like that. But if an error condition might come up in normal cases (i.e. rare races, non-bugs) we need to look to other error handling solutions.
We were planning to investigate first and then share back to the list. It probably deserves broader consideration beyond folks still reading deep down in this thread.
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Ackerley TngOn 5/15/2025 7:41 AM, Ackerley Tng wrote:
[...]
Quoted 16 lines
virt/kvm/guest_memfd.c +16
-0+ +static int kvm_gmem_convert_range (struct file *file,pgoff_t start, +size_t nr_pages,bool shared, +pgoff_t *error_index) +{ +struct conversion_work *work, *tmp, *rollback_stop_item; +LIST_HEAD (work_list); +struct inode *inode; +enum shareability m; +int ret; + + inode =file_inode (file); + +filemap_invalidate_lock (inode->i_mapping); + + m = shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ;
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t inde · line 322
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ ret =kvm_gmem_convert_compute_work (inode, start, nr_pages, m, &work_list); +if (ret ||list_empty (&work_list)) + goto out; + +list_for_each_entry (work, &work_list, list) +kvm_gmem_convert_invalidate_begin (inode, work); + +list_for_each_entry (work, &work_list, list) { + ret =kvm_gmem_convert_should_proceed (inode, work, shared, + error_index);
Since kvm_gmem_invalidate_begin() begins to handle shared memory, kvm_gmem_convert_invalidate_begin() will zap the table.
The shared mapping could be zapped in kvm_gmem_convert_invalidate_begin() even when kvm_gmem_convert_should_proceed() returns error.
The sequence is a bit confusing to me, at least in this patch so far.
Quoted 35 lines
virt/kvm/guest_memfd.c +35
-0+if (ret) + goto invalidate_end; + } + +list_for_each_entry (work, &work_list, list) { + rollback_stop_item = work; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +break ; + } + +if (ret) { + m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ; +list_for_each_entry (work, &work_list, list) { +if (work == rollback_stop_item) +break ; + +WARN_ON (kvm_gmem_shareability_apply (inode, work, m)); + } + } + +invalidate_end: +list_for_each_entry (work, &work_list, list) +kvm_gmem_convert_invalidate_end (inode, work); +out: +filemap_invalidate_unlock (inode->i_mapping); + +list_for_each_entry_safe (work, tmp, &work_list, list) { +list_del (&work->list); +kfree (work); + } + +return ret; +} +
[...]
Quoted 33 lines
virt/kvm/guest_memfd.c +13
-2@@ -186,15 +490,26 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,unsigned long index;xa_for_each_range (&gmem->bindings, index, slot, start, end -1 ) { +enum kvm_gfn_range_filter filter;pgoff_t pgoff = slot->gmem.pgoff; + filter =KVM_FILTER_PRIVATE ; +if (kvm_gmem_memslot_supports_shared (slot)) { +/* +* Unmapping would also cause invalidation, but cannot +* rely on mmu_notifiers to do invalidation via +* unmapping, since memory may not be mapped to +* userspace. +*/ + filter |=KVM_FILTER_SHARED ; + } +struct kvm_gfn_range gfn_range = { .start = slot->base_gfn +max (pgoff, start) - pgoff, .end = slot->base_gfn +min (pgoff + slot->npages, end) - pgoff, .slot = slot, .may_block = true, -/* guest memfd is relevant to only private mappings. */ - .attr_filter =KVM_FILTER_PRIVATE , + .attr_filter = filter, };if (!found_memslot) {@@ -484,11 +799,49 @@ EXPORT_SYMBOL_GPL(kvm_gmem_memslot_supports_shared);#define kvm_gmem_mmap NULL#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
[...]
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 27 lines · Binbin Wu
On 5/15/2025 7:41 AM, Ackerley Tng wrote:
[...]
Quoted 24 lines
virt/kvm/guest_memfd.c +24
-0+ +static int kvm_gmem_convert_range (struct file *file,pgoff_t start, +size_t nr_pages,bool shared, +pgoff_t *error_index) +{ +struct conversion_work *work, *tmp, *rollback_stop_item; +LIST_HEAD (work_list); +struct inode *inode; +enum shareability m; +int ret; + + inode =file_inode (file); + +filemap_invalidate_lock (inode->i_mapping); + + m = shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ; + ret =kvm_gmem_convert_compute_work (inode, start, nr_pages, m, &work_list); +if (ret ||list_empty (&work_list)) + goto out; + +list_for_each_entry (work, &work_list, list) +kvm_gmem_convert_invalidate_begin (inode, work); + +list_for_each_entry (work, &work_list, list) {
Quoted 9 lines
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t inde · line 322
Quoted 2 lines
virt/kvm/guest_memfd.c +2
-0+ ret =kvm_gmem_convert_should_proceed (inode, work, shared, + error_index);Since
kvm_gmem_invalidate_begin()begins to handle shared memory,kvm_gmem_convert_invalidate_begin()will zap the table.
The shared mapping could be zapped inkvm_gmem_convert_invalidate_begin()even whenkvm_gmem_convert_should_proceed()returns error.
The sequence is a bit confusing to me, at least in this patch so far.
It is true that zapping of pages from the guest page table will happen before we figure out whether conversion is allowed.
For a shared-to-private conversion, we will definitely unmap from the host before checking if conversion is allowed, and there's no choice there since conversion is allowed if there are no unexpected refcounts, and the way to eliminate expected refcounts is to unmap from the host.
Since we're unmapping before checking if conversion is allowed, I thought it would be fine to also zap from guest page tables before checking if conversion is allowed.
Conversion is not meant to happen very regularly, and even if it is unmapped or zapped, the next access will fault in the page anyway, so there is a performance but not a functionality impact.
Hope that helps. Is it still odd to zap before checking if conversion should proceed?
Quoted 70 lines
Quoted 35 lines
virt/kvm/guest_memfd.c +35
-0+if (ret) + goto invalidate_end; + } + +list_for_each_entry (work, &work_list, list) { + rollback_stop_item = work; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +break ; + } + +if (ret) { + m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ; +list_for_each_entry (work, &work_list, list) { +if (work == rollback_stop_item) +break ; + +WARN_ON (kvm_gmem_shareability_apply (inode, work, m)); + } + } + +invalidate_end: +list_for_each_entry (work, &work_list, list) +kvm_gmem_convert_invalidate_end (inode, work); +out: +filemap_invalidate_unlock (inode->i_mapping); + +list_for_each_entry_safe (work, tmp, &work_list, list) { +list_del (&work->list); +kfree (work); + } + +return ret; +} +[...]
Quoted 33 lines
virt/kvm/guest_memfd.c +13
-2@@ -186,15 +490,26 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,unsigned long index;xa_for_each_range (&gmem->bindings, index, slot, start, end -1 ) { +enum kvm_gfn_range_filter filter;pgoff_t pgoff = slot->gmem.pgoff; + filter =KVM_FILTER_PRIVATE ; +if (kvm_gmem_memslot_supports_shared (slot)) { +/* +* Unmapping would also cause invalidation, but cannot +* rely on mmu_notifiers to do invalidation via +* unmapping, since memory may not be mapped to +* userspace. +*/ + filter |=KVM_FILTER_SHARED ; + } +struct kvm_gfn_range gfn_range = { .start = slot->base_gfn +max (pgoff, start) - pgoff, .end = slot->base_gfn +min (pgoff + slot->npages, end) - pgoff, .slot = slot, .may_block = true, -/* guest memfd is relevant to only private mappings. */ - .attr_filter =KVM_FILTER_PRIVATE , + .attr_filter = filter, };if (!found_memslot) {@@ -484,11 +799,49 @@ EXPORT_SYMBOL_GPL(kvm_gmem_memslot_supports_shared);#define kvm_gmem_mmap NULL#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ [...]
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 45 lines · Ackerley Tng
Quoted 26 lines · Binbin Wu
On 5/15/2025 7:41 AM, Ackerley Tng wrote:
[...]
Quoted 23 lines
virt/kvm/guest_memfd.c +23
-0+ +static int kvm_gmem_convert_range (struct file *file,pgoff_t start, +size_t nr_pages,bool shared, +pgoff_t *error_index) +{ +struct conversion_work *work, *tmp, *rollback_stop_item; +LIST_HEAD (work_list); +struct inode *inode; +enum shareability m; +int ret; + + inode =file_inode (file); + +filemap_invalidate_lock (inode->i_mapping); + + m = shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ; + ret =kvm_gmem_convert_compute_work (inode, start, nr_pages, m, &work_list); +if (ret ||list_empty (&work_list)) + goto out; + +list_for_each_entry (work, &work_list, list) +kvm_gmem_convert_invalidate_begin (inode, work); +Quoted 9 lines
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t inde · line 322
Quoted 3 lines
virt/kvm/guest_memfd.c +3
-0+list_for_each_entry (work, &work_list, list) { + ret =kvm_gmem_convert_should_proceed (inode, work, shared, + error_index);Since
kvm_gmem_invalidate_begin()begins to handle shared memory,kvm_gmem_convert_invalidate_begin()will zap the table.
The shared mapping could be zapped inkvm_gmem_convert_invalidate_begin()even whenkvm_gmem_convert_should_proceed()returns error.
The sequence is a bit confusing to me, at least in this patch so far.It is true that zapping of pages from the guest page table will happen before we figure out whether conversion is allowed.
For a shared-to-private conversion, we will definitely unmap from the host before checking if conversion is allowed, and there's no choice there since conversion is allowed if there are no unexpected refcounts, and the way to eliminate expected refcounts is to unmap from the host.
Quoted 7 lines
Since we're unmapping before checking if conversion is allowed, I thought it would be fine to also zap from guest page tables before checking if conversion is allowed.
Conversion is not meant to happen very regularly, and even if it is unmapped or zapped, the next access will fault in the page anyway, so there is a performance but not a functionality impact.
Yes, it's OK for shared mapping.
Quoted 2 lines
Hope that helps.
It helped, thanks!
Quoted 73 lines
Is it still odd to zap before checking if conversion should proceed?
Quoted 70 lines
Quoted 35 lines
virt/kvm/guest_memfd.c +35
-0+if (ret) + goto invalidate_end; + } + +list_for_each_entry (work, &work_list, list) { + rollback_stop_item = work; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +break ; + } + +if (ret) { + m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ; +list_for_each_entry (work, &work_list, list) { +if (work == rollback_stop_item) +break ; + +WARN_ON (kvm_gmem_shareability_apply (inode, work, m)); + } + } + +invalidate_end: +list_for_each_entry (work, &work_list, list) +kvm_gmem_convert_invalidate_end (inode, work); +out: +filemap_invalidate_unlock (inode->i_mapping); + +list_for_each_entry_safe (work, tmp, &work_list, list) { +list_del (&work->list); +kfree (work); + } + +return ret; +} +[...]
Quoted 33 lines
virt/kvm/guest_memfd.c +13
-2@@ -186,15 +490,26 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,unsigned long index;xa_for_each_range (&gmem->bindings, index, slot, start, end -1 ) { +enum kvm_gfn_range_filter filter;pgoff_t pgoff = slot->gmem.pgoff; + filter =KVM_FILTER_PRIVATE ; +if (kvm_gmem_memslot_supports_shared (slot)) { +/* +* Unmapping would also cause invalidation, but cannot +* rely on mmu_notifiers to do invalidation via +* unmapping, since memory may not be mapped to +* userspace. +*/ + filter |=KVM_FILTER_SHARED ; + } +struct kvm_gfn_range gfn_range = { .start = slot->base_gfn +max (pgoff, start) - pgoff, .end = slot->base_gfn +min (pgoff + slot->npages, end) - pgoff, .slot = slot, .may_block = true, -/* guest memfd is relevant to only private mappings. */ - .attr_filter =KVM_FILTER_PRIVATE , + .attr_filter = filter, };if (!found_memslot) {@@ -484,11 +799,49 @@ EXPORT_SYMBOL_GPL(kvm_gmem_memslot_supports_shared);#define kvm_gmem_mmap NULL#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ [...]
RFC PATCH v2 5/51 KVM: guest_memfd: Skip LRU for guest_memfd folios
In reply to Ackerley Tngfilemap_add_folio(), called from filemap_grab_folio(), adds the folio onto some LRU list, which is not necessary for guest_memfd since guest_memfd folios don't participate in any swapping.
This patch reimplements part of filemap_add_folio() to avoid adding allocated guest_memfd folios to the filemap.
With shared to private conversions dependent on refcounts, avoiding usage of LRU ensures that LRU lists no longer take any refcounts on guest_memfd folios and significantly reduces the chance of elevated refcounts during conversion.
--- mm/filemap.c | 1 + mm/memcontrol.c | 2 + virt/kvm/guest_memfd.c | 91 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 86 insertions(+), 8 deletions(-)
mm/filemap.c +1 -0
@@ -954,6 +954,7 @@ noinline int __filemap_add_folio(struct address_space *mapping,return xas_error (&xas); }ALLOW_ERROR_INJECTION (__filemap_add_folio,ERRNO ); +EXPORT_SYMBOL_GPL (__filemap_add_folio);int filemap_add_folio (struct address_space *mapping,struct folio *folio,pgoff_t index,gfp_t gfp)
mm/memcontrol.c +2 -0
@@ -4611,6 +4611,7 @@ int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)return ret; } +EXPORT_SYMBOL_GPL (__mem_cgroup_charge);/** * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio
@@ -4785,6 +4786,7 @@ void __mem_cgroup_uncharge(struct folio *folio)uncharge_folio (folio, &ug);uncharge_batch (&ug); } +EXPORT_SYMBOL_GPL (__mem_cgroup_uncharge);void __mem_cgroup_uncharge_folios (struct folio_batch *folios) {
virt/kvm/guest_memfd.c +83 -8
120 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 05/51] KVM: guest_memfd: Skip LRU for guest_memfd folios
Quoted 6 lines · Ackerley Tng
filemap_add_folio(), called fromfilemap_grab_folio(), adds the folio onto some LRU list, which is not necessary forguest_memfdsinceguest_memfdfolios don't participate in any swapping.This patch reimplements part of
filemap_add_folio()to avoid adding allocatedguest_memfdfolios to the filemap.
filemap -> LRU list?
Quoted 14 lines
With shared to private conversions dependent on refcounts, avoiding usage of LRU ensures that LRU lists no longer take any refcounts on
guest_memfdfolios and significantly reduces the chance of elevated refcounts during conversion.Signed-off-by Ackerley Tng <[email protected]>Change-Id Ia2540d9fc132d46219e6e714fd42bc82a62a27fa--- mm/filemap.c | 1 + mm/memcontrol.c | 2 + virt/kvm/guest_memfd.c | 91 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 86 insertions(+), 8 deletions(-)
[...]
Quoted 29 lines
/*
* Returns a locked folio on success. The caller is responsible for
* setting the up-to-date flag before the memory is mapped into the guest.virt/kvm/guest_memfd.c +20
-1@@ -477,8 +509,46 @@ static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,*/ static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index) { +struct folio *folio; +gfp_t gfp; +int ret; + +repeat: + folio =filemap_lock_folio (inode->i_mapping, index); +if (!IS_ERR (folio)) +return folio; + + gfp =mapping_gfp_mask (inode->i_mapping); +/* TODO: Support huge pages. */ -return filemap_grab_folio (inode->i_mapping, index); + folio =filemap_alloc_folio (gfp,0 ); +if (!folio) +return ERR_PTR (-ENOMEM ); + + ret =mem_cgroup_charge (folio,NULL , gfp); +if (ret) { +folio_put (folio); +return ERR_PTR (ret); + }
virt/kvm/guest_memfd.c static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, · line 542
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index); +if (ret) { +folio_put (folio); + +/* +* There was a race, two threads tried to get a folio indexing +* to the same location in the filemap. The losing thread should +* free the allocated folio, then lock the folio added to the +* filemap by the winning thread.
How about changing
“then lock the folio added to the filemap by the winning thread” to
"the winning thread locks the folio added to the filemap"?
Quoted 14 lines
virt/kvm/guest_memfd.c +9
-0+*/ +if (ret == -EEXIST ) + goto repeat; + +return ERR_PTR (ret); + } + +__folio_set_locked (folio); +return folio; } static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,@@ -956,23 +1026,28 @@ static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol }
virt/kvm/guest_memfd.c static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol · line 1036
Quoted 10 lines
virt/kvm/guest_memfd.c +8
-0#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE +static void kvm_gmem_invalidate (struct folio *folio) +{ +kvm_pfn_t pfn =folio_pfn (folio); + +kvm_arch_gmem_invalidate (pfn, pfn +folio_nr_pages (folio)); +} +#else +static inline void kvm_gmem_invalidate (struct folio *folio) {}
No need to tag a local static function with "inline".
Quoted 2 lines
virt/kvm/guest_memfd.c +2
-0+#endif +
[...]
Re: [RFC PATCH v2 05/51] KVM: guest_memfd: Skip LRU for guest_memfd folios
Quoted 10 lines · Binbin Wu
Quoted 6 lines · Ackerley Tng
filemap_add_folio(), called fromfilemap_grab_folio(), adds the folio onto some LRU list, which is not necessary forguest_memfdsinceguest_memfdfolios don't participate in any swapping.This patch reimplements part of
filemap_add_folio()to avoid adding allocatedguest_memfdfolios to the filemap.filemap -> LRU list?
Yes, thank you. Will fix this in the next revision.
Quoted 51 lines
Quoted 14 lines
With shared to private conversions dependent on refcounts, avoiding usage of LRU ensures that LRU lists no longer take any refcounts on
guest_memfdfolios and significantly reduces the chance of elevated refcounts during conversion.Signed-off-by Ackerley Tng <[email protected]>Change-Id Ia2540d9fc132d46219e6e714fd42bc82a62a27fa--- mm/filemap.c | 1 + mm/memcontrol.c | 2 + virt/kvm/guest_memfd.c | 91 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 86 insertions(+), 8 deletions(-)[...]
Quoted 36 lines
/*
* Returns a locked folio on success. The caller is responsible for
* setting the up-to-date flag before the memory is mapped into the guest.virt/kvm/guest_memfd.c +27
-1@@ -477,8 +509,46 @@ static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,*/ static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index) { +struct folio *folio; +gfp_t gfp; +int ret; + +repeat: + folio =filemap_lock_folio (inode->i_mapping, index); +if (!IS_ERR (folio)) +return folio; + + gfp =mapping_gfp_mask (inode->i_mapping); +/* TODO: Support huge pages. */ -return filemap_grab_folio (inode->i_mapping, index); + folio =filemap_alloc_folio (gfp,0 ); +if (!folio) +return ERR_PTR (-ENOMEM ); + + ret =mem_cgroup_charge (folio,NULL , gfp); +if (ret) { +folio_put (folio); +return ERR_PTR (ret); + } + + ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index); +if (ret) { +folio_put (folio); + +/* +* There was a race, two threads tried to get a folio indexing
Quoted 9 lines
virt/kvm/guest_memfd.c static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, · line 542
Quoted 3 lines
virt/kvm/guest_memfd.c +3
-0+* to the same location in the filemap. The losing thread should +* free the allocated folio, then lock the folio added to the +* filemap by the winning thread. How about changing
“then lock the folio added to the filemap by the winning thread” to
"the winning thread locks the folio added to the filemap"?
How about:
There was a race. Threads tried to get a folio indexing to the same location in the filemap. The winning thread allocated and locked the folio at the requested index. The losing threads should free the extra allocated folio, then wait to lock the same folio allocated (and locked) by the winning thread.
Quoted 15 lines
Quoted 15 lines
virt/kvm/guest_memfd.c +9
-0+*/ +if (ret == -EEXIST ) + goto repeat; + +return ERR_PTR (ret); + } + +__folio_set_locked (folio); +return folio; } static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,@@ -956,23 +1026,28 @@ static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol }
Quoted 12 lines
virt/kvm/guest_memfd.c static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol · line 1036
Quoted 9 lines
virt/kvm/guest_memfd.c +8
-0#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE +static void kvm_gmem_invalidate (struct folio *folio) +{ +kvm_pfn_t pfn =folio_pfn (folio); + +kvm_arch_gmem_invalidate (pfn, pfn +folio_nr_pages (folio)); +} +#else +static inline void kvm_gmem_invalidate (struct folio *folio) {}No need to tag a local static function with "inline".
Will fix in the next revision.
Quoted 3 lines
Quoted 2 lines
virt/kvm/guest_memfd.c +2
-0+#endif +[...]
Sean Christopherson
maintainerRe: [RFC PATCH v2 05/51] KVM: guest_memfd: Skip LRU for guest_memfd folios
In reply to Ackerley TngTrimmed Cc again.
Quoted 7 lines · Ackerley Tng
filemap_add_folio(), called fromfilemap_grab_folio(), adds the folio onto some LRU list, which is not necessary forguest_memfdsinceguest_memfdfolios don't participate in any swapping.This patch reimplements part of
filemap_add_folio()to avoid adding allocatedguest_memfdfolios to the filemap.
Quoted 7 lines
With shared to private conversions dependent on refcounts, avoiding usage of LRU ensures that LRU lists no longer take any refcounts on
guest_memfdfolios and significantly reduces the chance of elevated refcounts during conversion.Signed-off-by Ackerley Tng <[email protected]>Change-Id Ia2540d9fc132d46219e6e714fd42bc82a62a27fa
Please make sure to purge Change-Id before posting upstream.
Quoted 31 lines
--- mm/filemap.c | 1 + mm/memcontrol.c | 2 + virt/kvm/guest_memfd.c | 91 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 86 insertions(+), 8 deletions(-)mm/filemap.c +1
-0@@ -954,6 +954,7 @@ noinline int __filemap_add_folio(struct address_space *mapping,return xas_error (&xas); }ALLOW_ERROR_INJECTION (__filemap_add_folio,ERRNO ); +EXPORT_SYMBOL_GPL (__filemap_add_folio);int filemap_add_folio (struct address_space *mapping,struct folio *folio,pgoff_t index,gfp_t gfp)mm/memcontrol.c +1
-0@@ -4611,6 +4611,7 @@ int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)return ret; } +EXPORT_SYMBOL_GPL (__mem_cgroup_charge);/** * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio
mm/memcontrol.c void __mem_cgroup_uncharge(struct folio *folio) · line 4789
Quoted 4 lines
mm/memcontrol.c +1
-0@@ -4785,6 +4786,7 @@ void __mem_cgroup_uncharge(struct folio *folio)uncharge_folio (folio, &ug);uncharge_batch (&ug); } +EXPORT_SYMBOL_GPL (__mem_cgroup_uncharge);
These exports need to be added in a separate patch. As a general rule, isolate changes that need approval from non-KVM (or whatever subsystem you're targeting) Maintainers. That provides maximum flexibility, e.g. the patch can be Acked and carried in the targeted tree, it can be applied separately and exposed via a topic branch, etc.
Quoted 11 lines
mm/memcontrol.c +0
-0void __mem_cgroup_uncharge_folios (struct folio_batch *folios) {virt/kvm/guest_memfd.c +1
-0@@ -466,6 +466,38 @@ static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,return r; } +static int __kvm_gmem_filemap_add_folio(struct address_space *mapping,
virt/kvm/guest_memfd.c static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, · line 479
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ struct folio *folio, pgoff_t index) +{ + void *shadow = NULL; +gfp_t gfp; +int ret; + + gfp =mapping_gfp_mask (mapping); + +__folio_set_locked (folio); + ret =__filemap_add_folio (mapping, folio, index, gfp, &shadow);
The @shadow param can be NULL, at least in current upstream code.
virt/kvm/guest_memfd.c static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, · line 487
Quoted 8 lines
virt/kvm/guest_memfd.c +8
-0+__folio_clear_locked (folio); + +return ret; +} + +/* +* Adds a folio to the filemap for guest_memfd. Skips adding the folio to any +* LRU list.
Eh, the function name covers the first sentence, and stating something without explaining _why_ isn't all that helpful for non-library code. E.g. there's no kvm_gmem_file_add_folio() that DOES add to LRUs, so on its own the distinction is uninteresting.
Quoted 48 lines
virt/kvm/guest_memfd.c +39
-1+*/ +static int kvm_gmem_filemap_add_folio (struct address_space *mapping, +struct folio *folio,pgoff_t index) +{ +int ret; + + ret =__kvm_gmem_filemap_add_folio (mapping, folio, index); +if (!ret) +folio_set_unevictable (folio); + +return ret; +} +/* * Returns a locked folio on success. The caller is responsible for * setting the up-to-date flag before the memory is mapped into the guest. @@ -477,8 +509,46 @@ static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,*/ static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index) { +struct folio *folio; +gfp_t gfp; +int ret; + +repeat: + folio =filemap_lock_folio (inode->i_mapping, index); +if (!IS_ERR (folio)) +return folio; + + gfp =mapping_gfp_mask (inode->i_mapping); +/* TODO: Support huge pages. */ -return filemap_grab_folio (inode->i_mapping, index); + folio =filemap_alloc_folio (gfp,0 ); +if (!folio) +return ERR_PTR (-ENOMEM ); + + ret =mem_cgroup_charge (folio,NULL , gfp); +if (ret) { +folio_put (folio); +return ERR_PTR (ret); + } + + ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index); +if (ret) { +folio_put (folio); + +/*
virt/kvm/guest_memfd.c static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, · line 548
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+* There was a race, two threads tried to get a folio indexing +* to the same location in the filemap. The losing thread should +* free the allocated folio, then lock the folio added to the +* filemap by the winning thread. +*/ +if (ret == -EEXIST ) + goto repeat; + +return ERR_PTR (ret); + }
I don't see any value in copy+pasting the complex "goto repeat" pattern from the filemap code. Copying names and exact patterns seems to be a theme with pulling code from the kernel into guest_memfd code. Please don't do that. Write code that makes the most sense for guest_memfd/KVM. There's value in consistency throughout the kernel, but copying code verbatim from a subsystem that's going to evolve independently and thus diverage at some point isn't a net positive.
This code in particular can be reworked to something like this. The do-while loop makes it _much_ more obvious when KVM retries, and also makes it much easier to see that the allocated folio is freed on any error, i.e. even on EEXIST.
static struct folio *__kvm_gmem_get_folio(struct address_space *mapping,
pgoff_t index, struct mempolicy *policy)
{
const gfp_t gfp = mapping_gfp_mask(mapping);
struct folio *folio;
int err;
folio = filemap_lock_folio(mapping, index);
if (!IS_ERR(folio))
return folio;
folio = filemap_alloc_folio(gfp, 0, policy);
if (!folio)
return ERR_PTR(-ENOMEM);
err = mem_cgroup_charge(folio, NULL, gfp);
if (err)
goto err_put;
__folio_set_locked(folio);
err = __filemap_add_folio(mapping, folio, index, gfp, NULL);
if (err) {
__folio_clear_locked(folio);
goto err_put;
}
return folio;err_put:
folio_put(folio); return ERR_PTR(err); }
/*
* Returns a locked folio on success. The caller is responsible for
* setting the up-to-date flag before the memory is mapped into the guest.
* There is no backing storage for the memory, so the folio will remain
* up-to-date until it's removed.
*
* Ignore accessed, referenced, and dirty flags. The memory is
* unevictable and there is no storage to write back to.
*/
static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
{
/* TODO: Support huge pages. */
struct address_space *mapping = inode->i_mapping;
struct mempolicy *policy;
struct folio *folio;
/*
* Fast-path: See if folio is already present in mapping to avoid
* policy_lookup.
*/
folio = filemap_lock_folio(mapping, index);
if (!IS_ERR(folio))
return folio;
policy = kvm_gmem_get_folio_policy(GMEM_I(inode), index);
do {
folio = __kvm_gmem_get_folio(mapping, index, policy);
} while (IS_ERR(folio) && PTR_ERR(folio) == -EEXIST);
mpol_cond_put(policy);
return folio;
}Quoted 9 lines
virt/kvm/guest_memfd.c +3
-0+ +__folio_set_locked (folio); +return folio; } static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,@@ -956,23 +1026,28 @@ static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol }
virt/kvm/guest_memfd.c static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol · line 1037
Quoted 10 lines
virt/kvm/guest_memfd.c +9
-0#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE +static void kvm_gmem_invalidate (struct folio *folio) +{ +kvm_pfn_t pfn =folio_pfn (folio); + +kvm_arch_gmem_invalidate (pfn, pfn +folio_nr_pages (folio)); +} +#else +static inline void kvm_gmem_invalidate (struct folio *folio) {} +#endif
Similar to my comment about not adding one-off helpers without good reason, don't add one-off #ifdef-guarded helpers. Just bury the #ifdef in the function (or if possible, avoid #ifdefs entirely). This way a reader doesn't have to bounce through ifdeffery just to see that kvm_gmem_invalidate() is a nop when CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE=n
static void kvm_gmem_free_folio(struct folio *folio)
{
folio_clear_unevictable(folio);#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE kvm_arch_gmem_invalidate(folio_pfn(folio), folio_pfn(folio) + folio_nr_pages(folio));
#endif
}
Quoted 26 lines
virt/kvm/guest_memfd.c +3
-7+static void kvm_gmem_free_folio (struct folio *folio) { -struct page *page =folio_page (folio,0 ); -kvm_pfn_t pfn =page_to_pfn (page); -int order =folio_order (folio); +folio_clear_unevictable (folio); -kvm_arch_gmem_invalidate (pfn, pfn + (1ul << order)); +kvm_gmem_invalidate (folio); } -#endif static const struct address_space_operations kvm_gmem_aops = { .dirty_folio = noop_dirty_folio, .migrate_folio = kvm_gmem_migrate_folio, .error_remove_folio = kvm_gmem_error_folio, -#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE .free_folio = kvm_gmem_free_folio, -#endif }; static int kvm_gmem_getattr(struct mnt_idmap *idmap, const struct path *path,Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 6/51 KVM: Query guest_memfd for private/shared status
In reply to Ackerley TngQuery guest_memfd for private/shared status if those guest_memfds track private/shared status.
With this patch, Coco VMs can use guest_memfd for both shared and private memory. If Coco VMs choose to use guest_memfd for both shared and private memory, by creating guest_memfd with the GUEST_MEMFD_FLAG_SUPPORT_SHARED flag, guest_memfd will be used to provide the private/shared status of the memory, instead of kvm->mem_attr_array.
--- include/linux/kvm_host.h | 19 ++++++++++++------- virt/kvm/guest_memfd.c | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-)
include/linux/kvm_host.h +12 -7
@@ -2508,12 +2508,22 @@ static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu, }#ifdef CONFIG_KVM_GMEM_SHARED_MEM +bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot); +bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn); +#else +static inline bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot) {return false; } + +static inline bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn) +{ +return false; +} +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
@@ -2544,13 +2554,8 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)return false; slot =gfn_to_memslot (kvm, gfn); -if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) { -/* -* For now, memslots only support in-place shared memory if the -* host is allowed to mmap memory (i.e., non-Coco VMs). -*/ -return false; - } +if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) +return kvm_gmem_is_private (slot, gfn);return kvm_get_memory_attributes (kvm, gfn) &KVM_MEMORY_ATTRIBUTE_PRIVATE ; }
virt/kvm/guest_memfd.c +22 -0
@@ -865,6 +865,28 @@ bool kvm_gmem_memslot_supports_shared(const struct kvm_memory_slot *slot) }EXPORT_SYMBOL_GPL (kvm_gmem_memslot_supports_shared); +bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn) +{ +struct inode *inode; +struct file *file; +pgoff_t index; +bool ret; + + file =kvm_gmem_get_file (slot); +if (!file) +return false; + + index =kvm_gmem_get_index (slot, gfn); + inode =file_inode (file); + +filemap_invalidate_lock_shared (inode->i_mapping); + ret =kvm_gmem_shareability_get (inode, index) ==SHAREABILITY_GUEST ; +filemap_invalidate_unlock_shared (inode->i_mapping); + +fput (file); +return ret; +} +#else #define kvm_gmem_mmap NULL#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 06/51] KVM: Query guest_memfd for private/shared status
Quoted 47 lines · Ackerley Tng
Query
guest_memfdfor private/shared status if thoseguest_memfdstrack private/shared status.With this patch, Coco VMs can use
guest_memfdfor both shared and private memory. If Coco VMs choose to useguest_memfdfor both shared and private memory, by creatingguest_memfdwith theGUEST_MEMFD_FLAG_SUPPORT_SHAREDflag,guest_memfdwill be used to provide the private/shared status of the memory, instead ofkvm->mem_attr_array.Change-Id I8f23d7995c12242aa4e09ccf5ec19360e9c9ed83Signed-off-by Ackerley Tng <[email protected]>--- include/linux/kvm_host.h | 19 ++++++++++++------- virt/kvm/guest_memfd.c | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-)include/linux/kvm_host.h +10
-0@@ -2508,12 +2508,22 @@ static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu, }#ifdef CONFIG_KVM_GMEM_SHARED_MEM +bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot); +bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn); +#else +static inline bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot) {return false; } + +static inline bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn) +{ +return false; +} +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES @@ -2544,13 +2554,8 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)return false;
include/linux/kvm_host.h static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn) · line 2558
Quoted 10 lines
include/linux/kvm_host.h +2
-7slot =gfn_to_memslot (kvm, gfn); -if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) { -/* -* For now, memslots only support in-place shared memory if the -* host is allowed to mmap memory (i.e., non-Coco VMs). -*/ -return false; - } +if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) +return kvm_gmem_is_private (slot, gfn);
When userspace gets an exit reason KVM_EXIT_MEMORY_FAULT, looks it needs to update both KVM memory attribute and gmem shareability, via two separate ioctls?
Quoted 39 lines
include/linux/kvm_host.h +0
-0return kvm_get_memory_attributes (kvm, gfn) &KVM_MEMORY_ATTRIBUTE_PRIVATE ; }virt/kvm/guest_memfd.c +22
-0@@ -865,6 +865,28 @@ bool kvm_gmem_memslot_supports_shared(const struct kvm_memory_slot *slot) }EXPORT_SYMBOL_GPL (kvm_gmem_memslot_supports_shared); +bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn) +{ +struct inode *inode; +struct file *file; +pgoff_t index; +bool ret; + + file =kvm_gmem_get_file (slot); +if (!file) +return false; + + index =kvm_gmem_get_index (slot, gfn); + inode =file_inode (file); + +filemap_invalidate_lock_shared (inode->i_mapping); + ret =kvm_gmem_shareability_get (inode, index) ==SHAREABILITY_GUEST ; +filemap_invalidate_unlock_shared (inode->i_mapping); + +fput (file); +return ret; +} +#else #define kvm_gmem_mmap NULL#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 06/51] KVM: Query guest_memfd for private/shared status
Quoted 48 lines · Yan Zhao
Quoted 47 lines · Ackerley Tng
Query
guest_memfdfor private/shared status if thoseguest_memfdstrack private/shared status.With this patch, Coco VMs can use
guest_memfdfor both shared and private memory. If Coco VMs choose to useguest_memfdfor both shared and private memory, by creatingguest_memfdwith theGUEST_MEMFD_FLAG_SUPPORT_SHAREDflag,guest_memfdwill be used to provide the private/shared status of the memory, instead ofkvm->mem_attr_array.Change-Id I8f23d7995c12242aa4e09ccf5ec19360e9c9ed83Signed-off-by Ackerley Tng <[email protected]>--- include/linux/kvm_host.h | 19 ++++++++++++------- virt/kvm/guest_memfd.c | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-)include/linux/kvm_host.h +10
-0@@ -2508,12 +2508,22 @@ static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu, }#ifdef CONFIG_KVM_GMEM_SHARED_MEM +bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot); +bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn); +#else +static inline bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot) {return false; } + +static inline bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn) +{ +return false; +} +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES @@ -2544,13 +2554,8 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)return false;
Quoted 12 lines
include/linux/kvm_host.h static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn) · line 2558
Quoted 10 lines
include/linux/kvm_host.h +2
-7slot =gfn_to_memslot (kvm, gfn); -if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) { -/* -* For now, memslots only support in-place shared memory if the -* host is allowed to mmap memory (i.e., non-Coco VMs). -*/ -return false; - } +if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) +return kvm_gmem_is_private (slot, gfn);When userspace gets an exit reason
KVM_EXIT_MEMORY_FAULT, looks it needs to update both KVM memory attribute and gmem shareability, via two separate ioctls?
IIUC, when userspace sets flag GUEST_MEMFD_FLAG_SUPPORT_SHARED to create the guest_memfd, the check for memory attribute will go through the guest_memfd way, the information in kvm->mem_attr_array will not be used.
So if userspace sets GUEST_MEMFD_FLAG_SUPPORT_SHARED, it uses KVM_GMEM_CONVERT_SHARED/PRIVATE to update gmem shareability. If userspace doesn't set GUEST_MEMFD_FLAG_SUPPORT_SHARED, it still uses KVM_SET_MEMORY_ATTRIBUTES to update KVM memory attribute tracking.
Quoted 4 lines
Quoted 4 lines
include/linux/kvm_host.h +0
-0return kvm_get_memory_attributes (kvm, gfn) &KVM_MEMORY_ATTRIBUTE_PRIVATE ; }
Re: [RFC PATCH v2 06/51] KVM: Query guest_memfd for private/shared status
Quoted 60 lines · Binbin Wu
Quoted 49 lines · Yan Zhao
Quoted 48 lines · Ackerley Tng
Query
guest_memfdfor private/shared status if thoseguest_memfdstrack private/shared status.With this patch, Coco VMs can use
guest_memfdfor both shared and private memory. If Coco VMs choose to useguest_memfdfor both shared and private memory, by creatingguest_memfdwith theGUEST_MEMFD_FLAG_SUPPORT_SHAREDflag,guest_memfdwill be used to provide the private/shared status of the memory, instead ofkvm->mem_attr_array.Change-Id I8f23d7995c12242aa4e09ccf5ec19360e9c9ed83Signed-off-by Ackerley Tng <[email protected]>--- include/linux/kvm_host.h | 19 ++++++++++++------- virt/kvm/guest_memfd.c | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-)include/linux/kvm_host.h +10
-3@@ -2508,12 +2508,22 @@ static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu, }#ifdef CONFIG_KVM_GMEM_SHARED_MEM +bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot); +bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn); +#else +static inline bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot) {return false; } + +static inline bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn) +{ +return false; +} +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES @@ -2544,13 +2554,8 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)return false; slot =gfn_to_memslot (kvm, gfn); -if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) { -/* -* For now, memslots only support in-place shared memory if the Quoted 8 lines
include/linux/kvm_host.h static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn) · line 2558
Quoted 6 lines
include/linux/kvm_host.h +2
-4-* host is allowed to mmap memory (i.e., non-Coco VMs). -*/ -return false; - } +if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) +return kvm_gmem_is_private (slot, gfn);When userspace gets an exit reason
KVM_EXIT_MEMORY_FAULT, looks it needs to update both KVM memory attribute and gmem shareability, via two separate ioctls?
Quoted 8 lines
IIUC, when userspace sets flag
GUEST_MEMFD_FLAG_SUPPORT_SHAREDto create theguest_memfd, the check for memory attribute will go through theguest_memfdway, the information inkvm->mem_attr_arraywill not be used.So if userspace sets
GUEST_MEMFD_FLAG_SUPPORT_SHARED, it uses KVM_GMEM_CONVERT_SHARED/PRIVATE to update gmem shareability. If userspace doesn't setGUEST_MEMFD_FLAG_SUPPORT_SHARED, it still usesKVM_SET_MEMORY_ATTRIBUTESto update KVM memory attribute tracking.
Ok, so the user needs to search the memory region and guest_memfd to choose the right ioctl.
For slots with guest_memfd of flag GUEST_MEMFD_FLAG_SUPPORT_SHARED, the KVM_LPAGE_MIXED_FLAG bit in the lpage_info cannot reflect the truth and a false value there may also prevent KVM from installing a huge page.
Quoted 6 lines
Quoted 4 lines
Quoted 4 lines
include/linux/kvm_host.h +0
-0return kvm_get_memory_attributes (kvm, gfn) &KVM_MEMORY_ATTRIBUTE_PRIVATE ; }
Sean Christopherson
maintainerRe: [RFC PATCH v2 06/51] KVM: Query guest_memfd for private/shared status
Quoted 21 lines · Yan Zhao
Quoted 20 lines · Binbin Wu
Quoted 15 lines · Yan Zhao
include/linux/kvm_host.h static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn) · line 2557
Quoted 12 lines · Ackerley Tng
include/linux/kvm_host.h +2
-7@@ -2544,13 +2554,8 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)return false; slot =gfn_to_memslot (kvm, gfn); -if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) { -/* -* For now, memslots only support in-place shared memory if the -* host is allowed to mmap memory (i.e., non-Coco VMs). -*/ -return false; - } +if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) +return kvm_gmem_is_private (slot, gfn);When userspace gets an exit reason
KVM_EXIT_MEMORY_FAULT, looks it needs to update both KVM memory attribute and gmem shareability, via two separate ioctls?IIUC, when userspace sets flag
GUEST_MEMFD_FLAG_SUPPORT_SHAREDto create theguest_memfd, the check for memory attribute will go through theguest_memfdway, the information inkvm->mem_attr_arraywill not be used.
Quoted 6 lines
Quoted 4 lines
So if userspace sets
GUEST_MEMFD_FLAG_SUPPORT_SHARED, it uses KVM_GMEM_CONVERT_SHARED/PRIVATE to update gmem shareability. If userspace doesn't setGUEST_MEMFD_FLAG_SUPPORT_SHARED, it still usesKVM_SET_MEMORY_ATTRIBUTESto update KVM memory attribute tracking.Ok, so the user needs to search the memory region and
guest_memfdto choose the right ioctl.
I don't see any reason to support "split" models like this. Tracking PRIVATE in two separate locations would be all kinds of crazy. E.g. if a slot is temporarily deleted, memory could unexpected toggle between private and shared. As evidenced by Yan's questions, the cognitive load on developers would also be very high.
Just make userspace choose between per-VM and per-gmem, and obviously allow in-place conversions if and only if attributes are per-gmem.
I (or someone else?) suggested adding a capability to disable per-VM tracking, but I don't see any reason to allow userspace to opt-out on a per-VM basis either. The big selling point of in-place conversions is that it avoids having to double provision some amount of guest memory. Those types of changes go far beyond the VMM. So I have a very hard time imagining a use case where VMM A will want to use per-VM attributes while VMM B will want per-gmem attributes.
Using a read-only module param will also simplify the internal code, as KVM will be able to route memory attributes queries without need a pointer to the "struct kvm".
In the future, we might have to swizzle things, e.g. if we want with per-VM RWX attributes, but that's largely a future problem, and a module param also gives us more flexibility anyways since they tend not to be considered rigid ABI in KVM.
RFC PATCH v2 7/51 KVM: guest_memfd: Add CAP KVM_CAP_GMEM_CONVERSION
In reply to Ackerley TngKVM_CAP_GMEM_CONVERSION indicates that guest_memfd supports conversion.
With this patch, as long as guest_memfd supports shared memory, it also supports conversion.
With conversion support comes tracking of private/shared memory within guest_memfd, hence now all VM types support shared memory in guest_memfd.
Before this patch, Coco VMs did not support shared memory because that would allow private memory to be accessible to the host. Coco VMs now support shared memory because with private/shared status tracked in guest_memfd, private memory will not be allowed to be mapped into the host.
--- arch/arm64/include/asm/kvm_host.h | 5 ----- arch/x86/include/asm/kvm_host.h | 10 ---------- include/linux/kvm_host.h | 13 ------------- include/uapi/linux/kvm.h | 1 + virt/kvm/guest_memfd.c | 12 ++++-------- virt/kvm/kvm_main.c | 3 ++- 6 files changed, 7 insertions(+), 37 deletions(-)
arch/arm64/include/asm/kvm_host.h +0 -5
@@ -1598,9 +1598,4 @@ static inline bool kvm_arch_supports_gmem(struct kvm *kvm) return IS_ENABLED(CONFIG_KVM_GMEM); } -static inline bool kvm_arch_vm_supports_gmem_shared_mem (struct kvm *kvm) -{ -return IS_ENABLED (CONFIG_KVM_GMEM_SHARED_MEM ); -} -#endif /* __ARM64_KVM_HOST_H__ */
arch/x86/include/asm/kvm_host.h +0 -10
@@ -2255,18 +2255,8 @@ void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,#ifdef CONFIG_KVM_GMEM #define kvm_arch_supports_gmem (kvm) ((kvm)->arch.supports_gmem) - -/* -* CoCo VMs with hardware support that use guest_memfd only for backing private -* memory, e.g., TDX, cannot use guest_memfd with userspace mapping enabled. -*/ -#define kvm_arch_vm_supports_gmem_shared_mem (kvm) \ - (IS_ENABLED(CONFIG_KVM_GMEM_SHARED_MEM) && \ - ((kvm)->arch.vm_type == KVM_X86_SW_PROTECTED_VM || \ - (kvm)->arch.vm_type == KVM_X86_DEFAULT_VM))#else #define kvm_arch_supports_gmem (kvm) false -#define kvm_arch_vm_supports_gmem_shared_mem (kvm) false#endif #define kvm_arch_has_readonly_mem (kvm) (!(kvm)->arch.has_protected_state)
include/linux/kvm_host.h +0 -13
@@ -729,19 +729,6 @@ static inline bool kvm_arch_supports_gmem(struct kvm *kvm) }#endif -/* -* Returns true if this VM supports shared mem in guest_memfd. -* -* Arch code must define kvm_arch_vm_supports_gmem_shared_mem if support for -* guest_memfd is enabled. -*/ -#if !defined(kvm_arch_vm_supports_gmem_shared_mem) && !IS_ENABLED (CONFIG_KVM_GMEM ) -static inline bool kvm_arch_vm_supports_gmem_shared_mem (struct kvm *kvm) -{ -return false; -} -#endif -#ifndef kvm_arch_has_readonly_memstatic inline bool kvm_arch_has_readonly_mem (struct kvm *kvm) {
include/uapi/linux/kvm.h +1 -0
@@ -931,6 +931,7 @@ struct kvm_enable_cap {#define KVM_CAP_X86_GUEST_MODE 238#define KVM_CAP_ARM_WRITABLE_IMP_ID_REGS 239#define KVM_CAP_GMEM_SHARED_MEM 240 +#define KVM_CAP_GMEM_CONVERSION 241struct kvm_irq_routing_irqchip {__u32 irqchip;
virt/kvm/guest_memfd.c +4 -8
@@ -1216,7 +1216,7 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)u64 flags = args->flags;u64 valid_flags =0 ; -if (kvm_arch_vm_supports_gmem_shared_mem (kvm)) +if (IS_ENABLED (CONFIG_KVM_GMEM_SHARED_MEM )) valid_flags |=GUEST_MEMFD_FLAG_SUPPORT_SHARED ;if (flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED )
@@ -1286,13 +1286,9 @@ int kvm_gmem_bind(struct kvm *kvm, struct kvm_memory_slot *slot, offset + size > i_size_read(inode)) goto err; -if (kvm_gmem_supports_shared (inode)) { -if (!kvm_arch_vm_supports_gmem_shared_mem (kvm)) - goto err; - -if (slot->userspace_addr && - !kvm_gmem_is_same_range (kvm, slot, file, offset)) - goto err; +if (kvm_gmem_supports_shared (inode) && slot->userspace_addr && + !kvm_gmem_is_same_range (kvm, slot, file, offset)) { + goto err; }filemap_invalidate_lock (inode->i_mapping);
virt/kvm/kvm_main.c +2 -1
@@ -4843,7 +4843,8 @@ static int kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)#endif #ifdef CONFIG_KVM_GMEM_SHARED_MEM case KVM_CAP_GMEM_SHARED_MEM : -return !kvm ||kvm_arch_vm_supports_gmem_shared_mem (kvm); +case KVM_CAP_GMEM_CONVERSION : +return true;#endif default :break ;
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 8/51 KVM: selftests: Test flag validity after guest_memfd supports conversions
In reply to Ackerley TngBefore guest_memfd supports conversions, Coco VMs must not allow GUEST_MEMFD_FLAG_SUPPORT_SHARED.
Because this is a platform stability requirement for hosts supporting Coco VMs, this is an important test to retain.
--- .../testing/selftests/kvm/guest_memfd_test.c | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-)
tools/testing/selftests/kvm/guest_memfd_test.c +23 -3
@@ -435,7 +435,8 @@ static void test_vm_type_gmem_flag_validity(unsigned long vm_type,for (flag =BIT (0 ); flag; flag <<=1 ) {test_vm_with_gmem_flag (vm, flag, flag & expected_valid_flags); -if (flag ==GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { +if (flag ==GUEST_MEMFD_FLAG_SUPPORT_SHARED && +kvm_has_cap (KVM_CAP_GMEM_CONVERSION )) {test_vm_with_gmem_flag ( vm, flag |GUEST_MEMFD_FLAG_INIT_PRIVATE , true); }
@@ -444,7 +445,7 @@ static void test_vm_type_gmem_flag_validity(unsigned long vm_type,kvm_vm_release (vm); } -static void test_gmem_flag_validity (void ) +static void test_gmem_flag_validity_without_conversion_cap (void ) {uint64_t non_coco_vm_valid_flags =0 ;
@@ -462,11 +463,30 @@ static void test_gmem_flag_validity(void)#endif } +static void test_gmem_flag_validity (void ) +{ +/* After conversions are supported, all VM types support shared mem. */ +uint64_t valid_flags =GUEST_MEMFD_FLAG_SUPPORT_SHARED ; + +test_vm_type_gmem_flag_validity (VM_TYPE_DEFAULT , valid_flags); + +#ifdef __x86_64__ +test_vm_type_gmem_flag_validity (KVM_X86_SW_PROTECTED_VM , valid_flags); +test_vm_type_gmem_flag_validity (KVM_X86_SEV_VM , valid_flags); +test_vm_type_gmem_flag_validity (KVM_X86_SEV_ES_VM , valid_flags); +test_vm_type_gmem_flag_validity (KVM_X86_SNP_VM , valid_flags); +test_vm_type_gmem_flag_validity (KVM_X86_TDX_VM , valid_flags); +#endif +} +int main (int argc,char *argv[]) {TEST_REQUIRE (kvm_has_cap (KVM_CAP_GUEST_MEMFD )); -test_gmem_flag_validity (); +if (kvm_has_cap (KVM_CAP_GMEM_CONVERSION )) +test_gmem_flag_validity (); +else +test_gmem_flag_validity_without_conversion_cap ();test_with_type (VM_TYPE_DEFAULT ,0 , false);if (kvm_has_cap (KVM_CAP_GMEM_SHARED_MEM )) {
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 9/51 KVM: selftests: Test faulting with respect to GUEST_MEMFD_FLAG_INIT_PRIVATE
In reply to Ackerley TngTest that faulting is denied when guest_memfd's shareability is initialized as private with GUEST_MEMFD_FLAG_INIT_PRIVATE and allowed if the flag is not specified.
Change-Id: Id93d4683b36fc5a9c924458d26f0525baed26435
--- .../testing/selftests/kvm/guest_memfd_test.c | 112 +++++++++++++++--- 1 file changed, 97 insertions(+), 15 deletions(-)
tools/testing/selftests/kvm/guest_memfd_test.c +97 -15
@@ -16,6 +16,7 @@#include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> +#include <sys/wait.h> #include "kvm_util.h" #include "test_util.h"
@@ -34,7 +35,7 @@ static void test_file_read_write(int fd) "pwrite on a guest_mem fd should fail"); } -static void test_mmap_allowed (int fd,size_t page_size,size_t total_size) +static void test_faulting_allowed (int fd,size_t page_size,size_t total_size) {const char val =0xaa ;char *mem;
@@ -65,6 +66,53 @@ static void test_mmap_allowed(int fd, size_t page_size, size_t total_size)TEST_ASSERT (!ret,"munmap should succeed" ); } +static void assert_not_faultable (char *address) +{ +pid_t child_pid; + + child_pid =fork (); +TEST_ASSERT (child_pid !=-1 ,"fork failed" ); + +if (child_pid ==0 ) { + *address ='A' ; +TEST_FAIL ("Child should have exited with a signal" ); + }else { +int status; + +waitpid (child_pid, &status,0 ); + +TEST_ASSERT (WIFSIGNALED (status), +"Child should have exited with a signal" ); +TEST_ASSERT_EQ (WTERMSIG (status),SIGBUS ); + } +} + +static void test_faulting_sigbus (int fd,size_t total_size) +{ +char *mem; +int ret; + + mem =mmap (NULL , total_size,PROT_READ |PROT_WRITE ,MAP_SHARED , fd,0 ); +TEST_ASSERT (mem !=MAP_FAILED ,"mmaping() guest memory should pass." ); + +assert_not_faultable (mem); + + ret =munmap (mem, total_size); +TEST_ASSERT (!ret,"munmap should succeed" ); +} + +static void test_mmap_allowed (int fd,size_t total_size) +{ +char *mem; +int ret; + + mem =mmap (NULL , total_size,PROT_READ |PROT_WRITE ,MAP_SHARED , fd,0 ); +TEST_ASSERT (mem !=MAP_FAILED ,"mmaping() guest memory should pass." ); + + ret =munmap (mem, total_size); +TEST_ASSERT (!ret,"munmap should succeed" ); +} +static void test_mmap_denied (int fd,size_t page_size,size_t total_size) {char *mem;
@@ -364,40 +412,74 @@ static void test_bind_guest_memfd_wrt_userspace_addr(struct kvm_vm *vm)close (fd); } -static void test_with_type (unsigned long vm_type,uint64_t guest_memfd_flags, -bool expect_mmap_allowed) +static void test_guest_memfd_features (struct kvm_vm *vm,size_t page_size, +uint64_t guest_memfd_flags, +bool expect_mmap_allowed, +bool expect_faulting_allowed) { -struct kvm_vm *vm;size_t total_size; -size_t page_size;int fd; -if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type))) -return ; - - page_size =getpagesize (); total_size = page_size *4 ; - vm =vm_create_barebones_type (vm_type); +if (expect_faulting_allowed) +TEST_REQUIRE (expect_mmap_allowed); -test_create_guest_memfd_multiple (vm); -test_bind_guest_memfd_wrt_userspace_addr (vm);test_create_guest_memfd_invalid_sizes (vm, guest_memfd_flags, page_size); fd =vm_create_guest_memfd (vm, total_size, guest_memfd_flags);test_file_read_write (fd); -if (expect_mmap_allowed) -test_mmap_allowed (fd, page_size, total_size); -else +if (expect_mmap_allowed) { +test_mmap_allowed (fd, total_size); + +if (expect_faulting_allowed) +test_faulting_allowed (fd, page_size, total_size); +else +test_faulting_sigbus (fd, total_size); + }else {test_mmap_denied (fd, page_size, total_size); + }test_file_size (fd, page_size, total_size);test_fallocate (fd, page_size, total_size);test_invalid_punch_hole (fd, page_size, total_size);close (fd); +} + +static void test_with_type (unsigned long vm_type,uint64_t guest_memfd_flags, +bool expect_mmap_allowed) +{ +struct kvm_vm *vm; +size_t page_size; + +if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type))) +return ; + + vm =vm_create_barebones_type (vm_type); + +test_create_guest_memfd_multiple (vm); +test_bind_guest_memfd_wrt_userspace_addr (vm); + + page_size =getpagesize (); +if (guest_memfd_flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { +test_guest_memfd_features (vm, page_size, guest_memfd_flags, + expect_mmap_allowed, true); + +if (kvm_has_cap (KVM_CAP_GMEM_CONVERSION )) { +uint64_t flags = guest_memfd_flags | +GUEST_MEMFD_FLAG_INIT_PRIVATE ; + +test_guest_memfd_features (vm, page_size, flags, + expect_mmap_allowed, false); + } + }else { +test_guest_memfd_features (vm, page_size, guest_memfd_flags, + expect_mmap_allowed, false); + } +kvm_vm_release (vm); }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 10/51 KVM: selftests: Refactor vm_mem_add to be more flexible
In reply to Ackerley Tngenum vm_mem_backing_src_type is encoding too many different possibilities on different axes of (1) whether to mmap from an fd, (2) granularity of mapping for THP, (3) size of hugetlb mapping, and has yet to be extended to support guest_memfd.
When guest_memfd supports mmap() and we also want to support testing with mmap()ing from guest_memfd, the number of combinations make enumeration in vm_mem_backing_src_type difficult.
This refactor separates out vm_mem_backing_src_type from userspace_mem_region. For now, vm_mem_backing_src_type remains a possible way for tests to specify, on the command line, the combination of backing memory to test.
vm_mem_add() is now the last place where vm_mem_backing_src_type is interpreted, to
1. Check validity of requested guest_paddr
2. Align mmap_size appropriately based on the mapping's page_size and architecture
3. Install memory appropriately according to mapping's page size
mmap()ing an alias seems to be specific to userfaultfd tests and could be refactored out of struct userspace_mem_region and localized in userfaultfd tests in future.
This paves the way for replacing vm_mem_backing_src_type with multiple command line flags that would specify backing memory more flexibly. Future tests are expected to use vm_mem_region_alloc() to allocate a struct userspace_mem_region, then use more fundamental functions like vm_mem_region_mmap(), vm_mem_region_madvise_thp(), kvm_memfd_create(), vm_create_guest_memfd(), and other functions in vm_mem_add() to flexibly build up struct userspace_mem_region before finally adding the region to the vm with vm_mem_region_add().
--- .../testing/selftests/kvm/include/kvm_util.h | 29 +- .../testing/selftests/kvm/include/test_util.h | 2 + tools/testing/selftests/kvm/lib/kvm_util.c | 429 +++++++++++------- tools/testing/selftests/kvm/lib/test_util.c | 25 + 4 files changed, 328 insertions(+), 157 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +28 -1
@@ -35,11 +35,26 @@ struct userspace_mem_region {struct sparsebit *protected_phy_pages;int fd;off_t offset; -enum vm_mem_backing_src_type backing_src_type; +/* +* host_mem is mmap_start aligned upwards to an address suitable for the +* architecture. In most cases, host_mem and mmap_start are the same, +* except for s390x, where the host address must be aligned to 1M (due +* to PGSTEs). +*/ +#ifdef __s390x__ +#define S390X_HOST_ADDRESS_ALIGNMENT 0x100000 +#endif void *host_mem; +/* host_alias is to mmap_alias as host_mem is to mmap_start */ void *host_alias;void *mmap_start;void *mmap_alias; +/* +* mmap_size is possibly larger than region.memory_size because in some +* cases, host_mem has to be adjusted upwards (see comment for host_mem +* above). In those cases, mmap_size has to be adjusted upwards so that +* enough memory is available in this memslot. +*/ size_t mmap_size;struct rb_node gpa_node;struct rb_node hva_node;
@@ -582,6 +597,18 @@ int __vm_set_user_memory_region2(struct kvm_vm *vm, uint32_t slot, uint32_t flag uint64_t gpa, uint64_t size, void *hva, uint32_t guest_memfd, uint64_t guest_memfd_offset); +struct userspace_mem_region *vm_mem_region_alloc (struct kvm_vm *vm); +void *vm_mem_region_mmap (struct userspace_mem_region *region,size_t length, +int flags,int fd,off_t offset); +void vm_mem_region_install_memory (struct userspace_mem_region *region, +size_t memslot_size,size_t alignment); +void vm_mem_region_madvise_thp (struct userspace_mem_region *region,int advice); +int vm_mem_region_install_guest_memfd (struct userspace_mem_region *region, +int guest_memfd); +void *vm_mem_region_mmap_alias (struct userspace_mem_region *region,int flags, +size_t alignment); +void vm_mem_region_add (struct kvm_vm *vm,struct userspace_mem_region *region); + void vm_userspace_mem_region_add(struct kvm_vm *vm, enum vm_mem_backing_src_type src_type, uint64_t guest_paddr, uint32_t slot, uint64_t npages,
tools/testing/selftests/kvm/include/test_util.h +2 -0
@@ -149,6 +149,8 @@ size_t get_trans_hugepagesz(void);size_t get_def_hugetlb_pagesz (void );const struct vm_mem_backing_src_alias *vm_mem_backing_src_alias (uint32_t i);size_t get_backing_src_pagesz (uint32_t i); +int backing_src_should_madvise (uint32_t i); +int get_backing_src_madvise_advice (uint32_t i);bool is_backing_src_hugetlb (uint32_t i);void backing_src_help (const char *flag);enum vm_mem_backing_src_type parse_backing_src_type (const char *type_name);
tools/testing/selftests/kvm/lib/kvm_util.c +273 -156
479 lines not on this page · raw message
tools/testing/selftests/kvm/lib/test_util.c +25 -0
@@ -308,6 +308,31 @@ size_t get_backing_src_pagesz(uint32_t i) } } +int backing_src_should_madvise (uint32_t i) +{ +switch (i) { +case VM_MEM_SRC_ANONYMOUS : +case VM_MEM_SRC_SHMEM : +case VM_MEM_SRC_ANONYMOUS_THP : +return true; +default : +return false; + } +} + +int get_backing_src_madvise_advice (uint32_t i) +{ +switch (i) { +case VM_MEM_SRC_ANONYMOUS : +case VM_MEM_SRC_SHMEM : +return MADV_NOHUGEPAGE ; +case VM_MEM_SRC_ANONYMOUS_THP : +return MADV_NOHUGEPAGE ; +default : +return 0 ; + } +} +bool is_backing_src_hugetlb (uint32_t i) {return !!(vm_mem_backing_src_alias (i)->flag &MAP_HUGETLB );
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Sean Christopherson
maintainerRe: [RFC PATCH v2 10/51] KVM: selftests: Refactor vm_mem_add to be more flexible
Quoted 4 lines · Ackerley Tng
enum
vm_mem_backing_src_typeis encoding too many different possibilities on different axes of (1) whether to mmap from an fd, (2) granularity of mapping for THP, (3) size of hugetlb mapping, and has yet to be extended to supportguest_memfd.
I don't disagree (I added the FIXME after all), but IMO what you've done here doesn't improve the situation, it just punts the mess to tests, i.e. lets the guest_memfd_conversions test do its thing, but doesn't actually improve anything.
A test has no business dealing with details about "installing" memory or even mapping the memslot. The whole point of the core library is to deal with those details so they don't need to be copy+pasted. Adding a gmem-backed memslot shouldn't require this much effort:
region = vm_mem_region_alloc(vm); guest_memfd = vm_mem_region_install_guest_memfd(region, guest_memfd); mem = vm_mem_region_mmap(region, memslot_size, MAP_SHARED, guest_memfd, 0); vm_mem_region_install_memory(region, memslot_size, PAGE_SIZE); region->region.slot = GUEST_MEMFD_SHARING_TEST_SLOT; region->region.flags = KVM_MEM_GUEST_MEMFD; region->region.guest_phys_addr = GUEST_MEMFD_SHARING_TEST_GPA; region->region.guest_memfd_offset = 0; vm_mem_region_add(vm, region);
Again, I agree vm_mem_add() is a mess. But overall, this is a big step backwards.
Quoted 6 lines
--- .../testing/selftests/kvm/include/kvm_util.h | 29 +- .../testing/selftests/kvm/include/test_util.h | 2 + tools/testing/selftests/kvm/lib/kvm_util.c | 429 +++++++++++------- tools/testing/selftests/kvm/lib/test_util.c | 25 + 4 files changed, 328 insertions(+), 157 deletions(-)
It's also not reviewable. There is far, far too much going on here. This is quite obviously not one logical change. The changelog is appropriate for the cover letter of a decently large series, not for a patch that touches core code of the selftests.
The massive refactoring is also unnecessary, at least for conversions. With some prep renames to shorten line lengths, all that is needed at this time is to dup() the gmem_fd into region->fd when the gmem_fd can be mmap()'d. It's not just a clever hack, it's also how we want gmem to be used going forward; and for non-CoCo VMs, it's the _only_ sane way to use gmem.
The only scenario where a test would want to shove a different userspace address into the memslot is a test that deliberately tests that exact scenario. And that sort of thing belongs in a test; core code should only concern itself with the scenario that 99 of usage will want.
With this, the test can do:
vm_mem_add(vm, VM_MEM_SRC_SHMEM, gpa, slot, nr_pages, KVM_MEM_GUEST_MEMFD, -1, 0, gmem_flags); t->gmem_fd = kvm_slot_to_fd(vm, slot); t->mem = addr_gpa2hva(vm, gpa); virt_map(vm, GUEST_MEMFD_SHARING_TEST_GVA, gpa, nr_pages);
--- tools/testing/selftests/kvm/include/kvm_util.h | 7 ++++++- tools/testing/selftests/kvm/lib/kvm_util.c | 9 +++++---- .../selftests/kvm/x86/private_mem_conversions_test.c | 2 +- 3 files changed, 12 insertions(+), 6 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +6 -1
@@ -678,7 +678,7 @@ void vm_userspace_mem_region_add(struct kvm_vm *vm, uint32_t flags);void vm_mem_add (struct kvm_vm *vm,enum vm_mem_backing_src_type src_type,uint64_t gpa,uint32_t slot,uint64_t npages,uint32_t flags, -int guest_memfd_fd,uint64_t guest_memfd_offset); +int gmem_fd,uint64_t gmem_offset,uint64_t gmem_flags);#ifndef vm_arch_has_protected_memorystatic inline bool vm_arch_has_protected_memory (struct kvm_vm *vm)
@@ -711,6 +711,11 @@ void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva);vm_paddr_t addr_hva2gpa (struct kvm_vm *vm,void *hva);void *addr_gpa2alias (struct kvm_vm *vm,vm_paddr_t gpa); +static inline int kvm_slot_to_fd (struct kvm_vm *vm,uint32_t slot) +{ +return memslot2region (vm, slot)->fd; +} +#ifndef vcpu_arch_put_guest#define vcpu_arch_put_guest (mem, val) do { (mem) = (val); } while (0)#endif
tools/testing/selftests/kvm/lib/kvm_util.c +5 -4
@@ -944,7 +944,7 @@ void vm_set_user_memory_region2(struct kvm_vm *vm, uint32_t slot, uint32_t flags/* FIXME: This thing needs to be ripped apart and rewritten. */ void vm_mem_add (struct kvm_vm *vm,enum vm_mem_backing_src_type src_type,uint64_t gpa,uint32_t slot,uint64_t npages,uint32_t flags, -int gmem_fd,uint64_t gmem_offset) +int gmem_fd,uint64_t gmem_offset,uint64_t gmem_flags) {int ret;struct userspace_mem_region *region;
@@ -1028,7 +1028,6 @@ void vm_mem_add(struct kvm_vm *vm, enum vm_mem_backing_src_type src_type,if (flags &KVM_MEM_GUEST_MEMFD ) {if (gmem_fd <0 ) { -uint32_t gmem_flags =0 ;TEST_ASSERT (!gmem_offset,"Offset must be zero when creating new guest_memfd" ); gmem_fd =vm_create_guest_memfd (vm, mem_size, gmem_flags);
@@ -1049,7 +1048,9 @@ void vm_mem_add(struct kvm_vm *vm, enum vm_mem_backing_src_type src_type, } region->fd =-1 ; -if (backing_src_is_shared (src_type)) +if (flags &KVM_MEM_GUEST_MEMFD && gmem_flags &GUEST_MEMFD_FLAG_MMAP ) + region->fd =kvm_dup (gmem_fd); +else if (backing_src_is_shared (src_type)) region->fd =kvm_memfd_alloc (region->mmap_size, src_type ==VM_MEM_SRC_SHARED_HUGETLB );
@@ -1116,7 +1117,7 @@ void vm_userspace_mem_region_add(struct kvm_vm *vm, uint64_t gpa, uint32_t slot, uint64_t npages, uint32_t flags) { - vm_mem_add(vm, src_type, gpa, slot, npages, flags, -1, 0); + vm_mem_add(vm, src_type, gpa, slot, npages, flags, -1, 0, 0); }/*
tools/testing/selftests/kvm/x86/private_mem_conversions_test.c +1 -1
@@ -399,7 +399,7 @@ static void test_mem_conversions(enum vm_mem_backing_src_type src_type, uint32_tfor (i =0 ; i < nr_memslots; i++)vm_mem_add (vm, src_type,BASE_DATA_GPA + slot_size * i,BASE_DATA_SLOT + i, slot_size / vm->page_size, -KVM_MEM_GUEST_MEMFD , memfd, slot_size * i); +KVM_MEM_GUEST_MEMFD , memfd, slot_size * i,0 );for (i =0 ; i < nr_vcpus; i++) {uint64_t gpa =BASE_DATA_GPA + i * per_cpu_size;
base-commit: 3572aeafd53394f4bf0a61d79c5c1b8cfccc3860 --
RFC PATCH v2 11/51 KVM: selftests: Allow cleanup of ucall_pool from host
In reply to Ackerley TngMany selftests use GUEST_DONE() to signal the end of guest code, which is handled in userspace. In most tests, the test exits and there is no need to clean up the ucall_pool->in_use bitmap.
If there are many guest code functions using GUEST_DONE(), or of guest code functions are run many times, the ucall_pool->in_use bitmap will fill up, causing later runs of the same guest code function to fail.
This patch allows ucall_free() to be called from userspace on uc.hva, which will unset and free the correct struct ucall in the pool, allowing ucalls to continue being used.
--- .../testing/selftests/kvm/include/ucall_common.h | 1 + tools/testing/selftests/kvm/lib/ucall_common.c | 16 ++++++++-------- 2 files changed, 9 insertions(+), 8 deletions(-)
tools/testing/selftests/kvm/include/ucall_common.h +1 -0
@@ -40,6 +40,7 @@ __printf(5, 6) void ucall_assert(uint64_t cmd, const char *exp, const char *fmt, ...);uint64_t get_ucall (struct kvm_vcpu *vcpu,struct ucall *uc);void ucall_init (struct kvm_vm *vm,vm_paddr_t mmio_gpa); +void ucall_free (struct ucall *uc);int ucall_nr_pages_required (uint64_t page_size);/*
tools/testing/selftests/kvm/lib/ucall_common.c +8 -8
@@ -21,24 +21,24 @@ int ucall_nr_pages_required(uint64_t page_size)/* * ucall_pool holds per-VM values (global data is duplicated by each VM), it -* must not be accessed from host code. +* should generally not be accessed from host code other than via ucall_free(), +* to cleanup after using GUEST_DONE() */ static struct ucall_header *ucall_pool;void ucall_init (struct kvm_vm *vm,vm_paddr_t mmio_gpa) { -struct ucall_header *hdr;struct ucall *uc;vm_vaddr_t vaddr;int i; - vaddr =vm_vaddr_alloc_shared (vm,sizeof (*hdr),KVM_UTIL_MIN_VADDR , -MEM_REGION_DATA ); - hdr = (struct ucall_header *)addr_gva2hva (vm, vaddr); -memset (hdr,0 ,sizeof (*hdr)); + vaddr =vm_vaddr_alloc_shared (vm,sizeof (*ucall_pool), +KVM_UTIL_MIN_VADDR ,MEM_REGION_DATA ); + ucall_pool = (struct ucall_header *)addr_gva2hva (vm, vaddr); +memset (ucall_pool,0 ,sizeof (*ucall_pool));for (i =0 ; i <KVM_MAX_VCPUS ; ++i) { - uc = &hdr->ucalls[i]; + uc = &ucall_pool->ucalls[i]; uc->hva = uc; }
@@ -73,7 +73,7 @@ static struct ucall *ucall_alloc(void)return NULL ; } -static void ucall_free (struct ucall *uc) +void ucall_free (struct ucall *uc) {/* Beware, here be pointer arithmetic. */ clear_bit (uc - ucall_pool->ucalls, ucall_pool->in_use);
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 11/51] KVM: selftests: Allow cleanup of ucall_pool from host
Quoted 11 lines · Ackerley Tng
Many selftests use
GUEST_DONE()to signal the end of guest code, which is handled in userspace. In most tests, the test exits and there is no need to clean up theucall_pool->in_usebitmap.If there are many guest code functions using
GUEST_DONE(), or of guest code functions are run many times, theucall_pool->in_usebitmap will fill up, causing later runs of the same guest code function to fail.This patch allows
ucall_free()to be called from userspace on uc.hva, which will unset and free the correct struct ucall in the pool, allowing ucalls to continue being used.
NAK.
The ucall thing isn't an issue with GUEST_DONE(), it's a general issue with not completing a ucall. The simple answer here is to not abuse GUEST_xxx().
I tried doing the same thing (jumping back to a guest's entry point) in what is now the mmu_stress_test, and it didn't end well. Restoring just registers mostly works on x86, but it's not foolproof even there. And on other architectures, the approach is even less viable (IIRC). E.g. if the guest code touches *anything* that's not saved/restore, the test is hosed.
In short, while clever, the approach just doesn't work. Which is why I don't want ucall_free() to exist: it's only useful for a pattern that is deeply flawed.
The easiest alternative is to use GUEST_SYNC(), have the guest code loop, and use global variables to pass data. It's ugly, but it works and is much less likely
to have arch specific quirks. The worst of the ugliness can be mitigated by
using a struct to pass info, e.g. so that you only have to do one "sync global" call.
RFC PATCH v2 12/51 KVM: selftests: Test conversion flows for guest_memfd
In reply to Ackerley TngAdd minimal tests for guest_memfd to test that when memory is marked shared in a VM, the host can read and write to it via an mmap()ed address, and the guest can also read and write to it.
Tests added in this patch use refcounts taken via GUP (requiring CONFIG_GUP_TEST) to simulate unexpected refcounts on guest_memfd pages.
Test that unexpected refcounts cause conversions to fail.
--- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../kvm/guest_memfd_conversions_test.c | 589 ++++++++++++++++++ .../testing/selftests/kvm/include/kvm_util.h | 74 +++ 3 files changed, 664 insertions(+) create mode 100644 tools/testing/selftests/kvm/guest_memfd_conversions_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
@@ -131,6 +131,7 @@ TEST_GEN_PROGS_x86 += access_tracking_perf_test TEST_GEN_PROGS_x86 += coalesced_io_test TEST_GEN_PROGS_x86 += dirty_log_perf_test TEST_GEN_PROGS_x86 += guest_memfd_test +TEST_GEN_PROGS_x86 += guest_memfd_conversions_test TEST_GEN_PROGS_x86 += hardware_disable_test TEST_GEN_PROGS_x86 += memslot_modification_stress_test TEST_GEN_PROGS_x86 += memslot_perf_test
tools/testing/selftests/kvm/guest_memfd_conversions_test.c new file +589 -0
589 lines not on this page · raw message
tools/testing/selftests/kvm/include/kvm_util.h +74 -0
91 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Sean Christopherson
maintainerRe: [RFC PATCH v2 12/51] KVM: selftests: Test conversion flows for guest_memfd
Quoted 7 lines · Ackerley Tng
Add minimal tests for
guest_memfdto test that when memory is marked shared in a VM, the host can read and write to it via an mmap()ed address, and the guest can also read and write to it.Tests added in this patch use refcounts taken via GUP (requiring
CONFIG_GUP_TEST) to simulate unexpected refcounts onguest_memfdpages.
This absolutely needs to be split up into multiple patches, one testcase per patch. Reviewing megapatches like this is no fun, and trying to debug failures months or years down the road is even less fun, especially for folks who weren't involved in the original development, because there's basically zero information provided for each individual testcase.
Quoted 68 lines
(quoted diff) +68
-0+#define GUEST_MEMFD_SHARING_TEST_SLOT 10 +/* + * Use high GPA above APIC_DEFAULT_PHYS_BASE to avoid clashing with + * APIC_DEFAULT_PHYS_BASE. + */ +#define GUEST_MEMFD_SHARING_TEST_GPA 0x100000000ULL +#define GUEST_MEMFD_SHARING_TEST_GVA 0x90000000ULL + +static int gup_test_fd; + +static void pin_pages(void *vaddr, uint64_t size) +{ + const struct pin_longterm_test args = { + .addr = (uint64_t)vaddr, + .size = size, + .flags = PIN_LONGTERM_TEST_FLAG_USE_WRITE, + }; + + gup_test_fd = open("/sys/kernel/debug/gup_test", O_RDWR); + TEST_REQUIRE(gup_test_fd > 0); + + TEST_ASSERT_EQ(ioctl(gup_test_fd, PIN_LONGTERM_TEST_START, &args), 0); +} + +static void unpin_pages(void) +{ + TEST_ASSERT_EQ(ioctl(gup_test_fd, PIN_LONGTERM_TEST_STOP), 0); +} + +static void guest_check_mem(uint64_t gva, char expected_read_value, char write_value) +{ + char *mem = (char *)gva; + + if (expected_read_value != 'X') + GUEST_ASSERT_EQ(*mem, expected_read_value); + + if (write_value != 'X') + *mem = write_value; + + GUEST_DONE(); +} + +static int vcpu_run_handle_basic_ucalls(struct kvm_vcpu *vcpu) +{ + struct ucall uc; + int rc; + +keep_going: + do { + rc = __vcpu_run(vcpu); + } while (rc == -1 && errno == EINTR); + + switch (get_ucall(vcpu, &uc)) { + case UCALL_PRINTF: + REPORT_GUEST_PRINTF(uc); + goto keep_going; + case UCALL_ABORT: + REPORT_GUEST_ASSERT(uc); + } + + return rc; +} + +/** + * guest_use_memory() - Assert that guest can use memory at @gva. + * + * @vcpu: the vcpu to run this test on. + * @gva: the virtual address in the guest to try to use.
Review
Quoted 10 lines
(quoted diff) +10
-0+ * @expected_read_value: the value that is expected at @gva. Set this to 'X' to + * skip checking current value. + * @write_value: value to write to @gva. Set to 'X' to skip writing value to + * @address. + * @expected_errno: the expected errno if an error is expected while reading or + * writing @gva. Set to 0 if no exception is expected, + * otherwise set it to the expected errno. If @expected_errno + * is set, 'Z' is used instead of @expected_read_value or + * @write_value. + */
Please don't add kerneldoc comments for selftests, and certainly not for a local helper in a test. The fact that documentation is needed is a sign that the behavior is too magical.
And all of that magic is comipletely unnecessary. Reads should _never_ be skipped, because there is _always_ a deterministic, predictable value in memory. And passing a magic value to skip writes is silly; just do the bare read.
Similarly, shoving 'Z' into values at this point is absurd, the caller is fully capable of specifying a garbage value that it knows can't be encountered. Even worse, expected_errno is never non-zero, making this even harder to review.
Quoted 1 line
+static void guest_use_memory(struct
kvm_vcpu*vcpu,uint64_tgva,
"use_memory" is far too vague. This also should be prefaced with run_guest so that it's obviously a host-side function. E.g. run_guest_do_rmw() and host_do_rmw() are short and a bit more descriptive.
Quoted 9 lines
(quoted diff) +9
-0+ char expected_read_value, char write_value, + int expected_errno) +{ + struct kvm_regs original_regs; + int rc; + + if (expected_errno > 0) { + expected_read_value = 'Z'; + write_value = 'Z';
Review
Quoted 10 lines
(quoted diff) +10
-0+ } + + /* + * Backup and vCPU state from first run so that guest_check_mem can be + * run again and again. + */ + vcpu_regs_get(vcpu, &original_regs); + + vcpu_args_set(vcpu, 3, gva, expected_read_value, write_value); + vcpu_arch_set_entry_point(vcpu, guest_check_mem);
As mentioned in the earlier patch, don't do this, it's too fragile.
Quoted 57 lines
(quoted diff) +57
-0+ rc = vcpu_run_handle_basic_ucalls(vcpu); + + if (expected_errno) { + TEST_ASSERT_EQ(rc, -1); + TEST_ASSERT_EQ(errno, expected_errno); + + switch (expected_errno) { + case EFAULT: + TEST_ASSERT_EQ(vcpu->run->exit_reason, 0); + break; + case EACCES: + TEST_ASSERT_EQ(vcpu->run->exit_reason, KVM_EXIT_MEMORY_FAULT); + break; + } + } else { + struct ucall uc; + + TEST_ASSERT_EQ(rc, 0); + TEST_ASSERT_EQ(get_ucall(vcpu, &uc), UCALL_DONE); + + /* + * UCALL_DONE() uses up one struct ucall slot. To reuse the slot + * in another run of guest_check_mem, free up that slot. + */ + ucall_free((struct ucall *)uc.hva); + } + + vcpu_regs_set(vcpu, &original_regs); +} + +/** + * host_use_memory() - Assert that host can fault and use memory at @address. + * + * @address: the address to be testing. + * @expected_read_value: the value expected to be read from @address. Set to 'X' + * to skip checking current value at @address. + * @write_value: the value to write to @address. Set to 'X' to skip writing + * value to @address. + */ +static void host_use_memory(char *address, char expected_read_value, + char write_value) +{ + if (expected_read_value != 'X') + TEST_ASSERT_EQ(*address, expected_read_value); + + if (write_value != 'X') + *address = write_value; +} + +static void assert_host_cannot_fault(char *address) +{ + pid_t child_pid; + + child_pid = fork(); + TEST_ASSERT(child_pid != -1, "fork failed"); + + if (child_pid == 0) {
Review
Quoted 10 lines
(quoted diff) +10
-0+ *address = 'A'; + TEST_FAIL("Child should have exited with a signal"); + } else { + int status; + + waitpid(child_pid, &status, 0); + + TEST_ASSERT(WIFSIGNALED(status), + "Child should have exited with a signal"); + TEST_ASSERT_EQ(WTERMSIG(status), SIGBUS);
This is just TEST_EXPECT_SIGBUS(), right? But in a rather weird way. It does highlight a testcase that's missing: fork() and _then_ convert private to ensure the new mm_struct's PTEs are also unmapped.
Quoted 52 lines
(quoted diff) +52
-0+static void *add_memslot(struct kvm_vm *vm, size_t memslot_size, int guest_memfd) +{ + struct userspace_mem_region *region; + void *mem; + + TEST_REQUIRE(guest_memfd > 0); + + region = vm_mem_region_alloc(vm); + + guest_memfd = vm_mem_region_install_guest_memfd(region, guest_memfd); + mem = vm_mem_region_mmap(region, memslot_size, MAP_SHARED, guest_memfd, 0); + vm_mem_region_install_memory(region, memslot_size, PAGE_SIZE); + + region->region.slot = GUEST_MEMFD_SHARING_TEST_SLOT; + region->region.flags = KVM_MEM_GUEST_MEMFD; + region->region.guest_phys_addr = GUEST_MEMFD_SHARING_TEST_GPA; + region->region.guest_memfd_offset = 0; + + vm_mem_region_add(vm, region); + + return mem; +} + +static struct kvm_vm *setup_test(size_t test_page_size, bool init_private, + struct kvm_vcpu **vcpu, int *guest_memfd, + char **mem) +{ + const struct vm_shape shape = { + .mode = VM_MODE_DEFAULT, + .type = KVM_X86_SW_PROTECTED_VM, + }; + size_t test_nr_pages; + struct kvm_vm *vm; + uint64_t flags; + + test_nr_pages = test_page_size / PAGE_SIZE; + vm = __vm_create_shape_with_one_vcpu(shape, vcpu, test_nr_pages, NULL); + + flags = GUEST_MEMFD_FLAG_SUPPORT_SHARED; + if (init_private) + flags |= GUEST_MEMFD_FLAG_INIT_PRIVATE; + + *guest_memfd = vm_create_guest_memfd(vm, test_page_size, flags); + TEST_ASSERT(*guest_memfd > 0, "guest_memfd creation failed"); + + *mem = add_memslot(vm, test_page_size, *guest_memfd); + + virt_map(vm, GUEST_MEMFD_SHARING_TEST_GVA, GUEST_MEMFD_SHARING_TEST_GPA, + test_nr_pages); + + return vm; +}
Review
Quoted 10 lines
(quoted diff) +10
-0+ +static void cleanup_test(size_t guest_memfd_size, struct kvm_vm *vm, + int guest_memfd, char *mem) +{ + kvm_vm_free(vm); + TEST_ASSERT_EQ(munmap(mem, guest_memfd_size), 0); + + if (guest_memfd > -1) + TEST_ASSERT_EQ(close(guest_memfd), 0); +}
This is a perfect test to utilize kselftest_harness.h and fixtures. That'll cut down on the boilerplate by a lot, and spitting out which test is running is super useful, e.g. if something completely blows up.
A big bonus with the harness is that it runs each test in a separate process, and so the gup pinning stuff can do TEST_REQUIRE() and show up as a Skip without any real effort.
Quoted 14 lines
(quoted diff) +14
-0+static void test_sharing(void) +{ + struct kvm_vcpu *vcpu; + struct kvm_vm *vm; + int guest_memfd; + char *mem; + + vm = setup_test(PAGE_SIZE, /*init_private=*/false, &vcpu, &guest_memfd, &mem); + + host_use_memory(mem, 'X', 'A'); + guest_use_memory(vcpu, GUEST_MEMFD_SHARING_TEST_GVA, 'A', 'B', 0); + + /* Toggle private flag of memory attributes and run the test again. */ + guest_memfd_convert_private(guest_memfd, 0, PAGE_SIZE);
Review
Quoted 10 lines
(quoted diff) +10
-0+ + assert_host_cannot_fault(mem); + guest_use_memory(vcpu, GUEST_MEMFD_SHARING_TEST_GVA, 'B', 'C', 0); + + guest_memfd_convert_shared(guest_memfd, 0, PAGE_SIZE); + + host_use_memory(mem, 'C', 'D'); + guest_use_memory(vcpu, GUEST_MEMFD_SHARING_TEST_GVA, 'D', 'E', 0); + + cleanup_test(PAGE_SIZE, vm, guest_memfd, mem);
There is so much boilerplate here that gets in the way of understanding what each test is actually doing. There's also quite a bit of easy coverage being left on the table. E.g. *every* conversion should check accessibility from both host and guest.
Using a fixture and a collection of helpers, tests can be distilled down to exactly what they're testing, e.g.
GMEM_CONVERSION_TEST_INIT_SHARED(init_shared)
{
test_shared(t, 0, 0, 'A', 'B');
test_convert_to_private(t, 0, 'B', 'C');
test_convert_to_shared(t, 0, 'C', 'D', 'E');
}GMEM_CONVERSION_TEST_INIT_PRIVATE(init_private)
{
test_private(t, 0, 0, 'A');
test_convert_to_shared(t, 0, 'A', 'B', 'C');
test_convert_to_private(t, 0, 'C', 'E');
}/*
* Test that even if there are no folios yet, conversion requests are recorded
* in guest_memfd.
*/GMEM_CONVERSION_TEST_INIT_SHARED(before_allocation)
{
test_convert_to_private(t, 0, 0, 'A');
test_convert_to_shared(t, 0, 'A', 'B', 'C');
}Quoted 1 line
+static void
test_init_mappable_false(void)
This is a very misleading name. It's testing that memory is initialized PRIVATE; the memfd instance is still very much mmap()able.
Quoted 20 lines
(quoted diff) +20
-0+ /* + * Fault 2 of the pages to test filemap range operations except when + * page_to_fault == second_page_to_fault. + */ + host_use_memory(mem + page_to_fault * PAGE_SIZE, 'X', 'A'); + host_use_memory(mem + second_page_to_fault * PAGE_SIZE, 'X', 'A'); + + guest_memfd_convert_private(guest_memfd, 0, total_size); + + for (i = 0; i < total_nr_pages; ++i) { + bool is_faulted; + char expected; + + assert_host_cannot_fault(mem + i * PAGE_SIZE); + + is_faulted = i == page_to_fault || i == second_page_to_fault; + expected = is_faulted ? 'A' : 'X'; + guest_use_memory(vcpu, + GUEST_MEMFD_SHARING_TEST_GVA + i * PAGE_SIZE, + expected, 'B', 0);
Review
Quoted 10 lines
(quoted diff) +10
-0+ } + + guest_memfd_convert_shared(guest_memfd, 0, total_size); + + for (i = 0; i < total_nr_pages; ++i) { + host_use_memory(mem + i * PAGE_SIZE, 'B', 'C'); + guest_use_memory(vcpu, + GUEST_MEMFD_SHARING_TEST_GVA + i * PAGE_SIZE, + 'C', 'D', 0); + }
This is where helpers add a _lot_ of clarity. Piecing together everything that's going on makes it rather hard to see that the test is verifying that pages that have been written to the guest.
Which reminds me, when we add conversion support, we also need to add a flag to control whether or not contents are preserved.
Anyways, with helpers to handle the gory details, the flow of the testcase is more apparent:
/*
* Fault 2 of the pages to test filemap range operations except when
* page_to_fault == second_page_to_fault.
*/
host_do_rmw(t->mem, page_to_fault, 0, 'A');
host_do_rmw(t->mem, second_page_to_fault, 0, 'A');
gmem_set_private(t->gmem_fd, 0, nr_pages * page_size);
for (i = 0; i < nr_pages; ++i) {
if (i == page_to_fault || i == second_page_to_fault)
test_private(t, i, 'A', 'B');
else
test_private(t, i, 0, 'B');
}
for (i = 0; i < nr_pages; ++i)
test_convert_to_shared(t, i, 'B', 'C', 'D');Quoted 4 lines
(quoted diff) +4
-0+ + cleanup_test(total_size, vm, guest_memfd, mem); +} +
Review
Quoted 10 lines
(quoted diff) +10
-0+static void test_conversion_if_not_all_folios_allocated(void) +{ + const int total_nr_pages = 16; + int i; + + for (i = 0; i < total_nr_pages; ++i) + __test_conversion_if_not_all_folios_allocated(total_nr_pages, i); +} + +static void test_conversions_should_not_affect_surrounding_pages(void)
C is not Java. Keep function names short and sweet, and add a comment if it's not immediately obvious what semantics are being tested. Something like "partial_conversions" or just "single_page" conveys the basic gist. The "should not affect surrounding pages" is largely stating the obvious.
Quoted 9 lines
(quoted diff) +9
-0+{ + struct kvm_vcpu *vcpu; + int page_to_convert; + struct kvm_vm *vm; + size_t total_size; + int guest_memfd; + int nr_pages; + char *mem; + int i;
Review
Quoted 10 lines
(quoted diff) +10
-0+ + page_to_convert = 2; + nr_pages = 4; + total_size = PAGE_SIZE * nr_pages; + + vm = setup_test(total_size, /*init_private=*/false, &vcpu, &guest_memfd, &mem); + + for (i = 0; i < nr_pages; ++i) { + host_use_memory(mem + i * PAGE_SIZE, 'X', 'A'); + guest_use_memory(vcpu, GUEST_MEMFD_SHARING_TEST_GVA + i * PAGE_SIZE,
Use getpagesize(), not PAGE_SIZE, otherwise this test will be unnecessarily difficult to port to non-x86 architectures, where PAGE_SIZE isn't a compile-time constant.
Quoted 22 lines
(quoted diff) +22
-0+ 'A', 'B', 0); + } + + guest_memfd_convert_private(guest_memfd, PAGE_SIZE * page_to_convert, PAGE_SIZE); + + + for (i = 0; i < nr_pages; ++i) { + char to_check; + + if (i == page_to_convert) { + assert_host_cannot_fault(mem + i * PAGE_SIZE); + to_check = 'B'; + } else { + host_use_memory(mem + i * PAGE_SIZE, 'B', 'C'); + to_check = 'C'; + } + + guest_use_memory(vcpu, GUEST_MEMFD_SHARING_TEST_GVA + i * PAGE_SIZE, + to_check, 'D', 0); + } + + guest_memfd_convert_shared(guest_memfd, PAGE_SIZE * page_to_convert, PAGE_SIZE);
Review
Quoted 10 lines
(quoted diff) +10
-0+ + + for (i = 0; i < nr_pages; ++i) { + host_use_memory(mem + i * PAGE_SIZE, 'D', 'E'); + guest_use_memory(vcpu, GUEST_MEMFD_SHARING_TEST_GVA + i * PAGE_SIZE, + 'E', 'F', 0); + } + + cleanup_test(total_size, vm, guest_memfd, mem); +}
With fixtures and helpers:
GMEM_CONVERSION_TEST_INIT_SHARED_ITERATE(single_page, 4)
{
int i;
for (i = 0; i < nr_pages; ++i)
test_shared(t, i, 0, 'A', 'B');
for (i = 0; i < nr_pages; ++i) {
if (i == test_page)
test_convert_to_private(t, i, 'B', 'D');
else
test_shared(t, i, 'B', 'C', 'D');
}
for (i = 0; i < nr_pages; ++i) {
if (i == test_page)
test_convert_to_shared(t, i, 'D', 'E', 'F');
else
test_shared(t, i, 'D', 'E', 'F');
}
/* Reset memory back to zero for the next iteration. */
for (i = 0; i < nr_pages; ++i)
host_do_rmw(t->mem, i, 'F', 0);
}Review
Quoted 3 lines
(quoted diff) +3
-0+ +static void __test_conversions_should_fail_if_memory_has_elevated_refcount( + int nr_pages, int page_to_convert)
Yeah, no :-)
With some hacks to avoid dependencies on "Refactor vm_mem_add to be more flexible", this is what I have locally (I'll work with you off-list to get all of this into RFC-worthy series).
Note, there's a lot of "magic" in the fixture framework, but it's "good magic" in the sense that it takes care of a lot things that aren't at all interesting to what's being tested, at the cost of making it difficult to understand certain details. E.g. where structures and stuff come from, their names, etc. The big different to me, versus the magic 'X' behavior, is that understanding the magic is generally only necessary if you care about the gory, uninteresting things. Understanding the testcases themselves is (hopefully) easier.
--- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../kvm/guest_memfd_conversions_test.c | 441 ++++++++++++++++++ .../testing/selftests/kvm/guest_memfd_test.c | 17 +- .../testing/selftests/kvm/include/kvm_util.h | 82 +++- tools/testing/selftests/kvm/lib/kvm_util.c | 42 ++ 5 files changed, 561 insertions(+), 22 deletions(-) create mode 100644 tools/testing/selftests/kvm/guest_memfd_conversions_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
@@ -141,6 +141,7 @@ TEST_GEN_PROGS_x86 += access_tracking_perf_test TEST_GEN_PROGS_x86 += coalesced_io_test TEST_GEN_PROGS_x86 += dirty_log_perf_test TEST_GEN_PROGS_x86 += guest_memfd_test +TEST_GEN_PROGS_x86 += guest_memfd_conversions_test TEST_GEN_PROGS_x86 += hardware_disable_test TEST_GEN_PROGS_x86 += memslot_modification_stress_test TEST_GEN_PROGS_x86 += memslot_perf_test
tools/testing/selftests/kvm/guest_memfd_conversions_test.c new file +441 -0
441 lines not on this page · raw message
tools/testing/selftests/kvm/guest_memfd_test.c +1 -16
@@ -489,28 +489,15 @@ static void test_guest_memfd_guest(void)kvm_vm_free (vm); } -static void report_unexpected_sigbus (int signum) -{ -TEST_FAIL ("Unexpected SIGBUS(%d)\n" , signum); -} -int main (int argc,char *argv[]) { -struct sigaction sa_old, sa_new = { - .sa_handler = report_unexpected_sigbus, - }; +unsigned long vm_types, vm_type;TEST_REQUIRE (kvm_has_cap (KVM_CAP_GUEST_MEMFD )); page_size =getpagesize (); -/* -* Register a SIGBUS handler so that unexpected SIGBUS errors, e.g. due -* to test or KVM bugs, are reported as failures with backtraces. -*/ -sigaction (SIGBUS , &sa_new, &sa_old); -/* * Not all architectures support KVM_CAP_VM_TYPES. However, those that * support guest_memfd have that support for the default VM type.
@@ -523,6 +510,4 @@ int main(int argc, char *argv[])test_guest_memfd (vm_type);test_guest_memfd_guest (); - -sigaction (SIGBUS , &sa_old,NULL ); }
tools/testing/selftests/kvm/include/kvm_util.h +76 -6
112 lines not on this page · raw message
tools/testing/selftests/kvm/lib/kvm_util.c +42 -0
62 lines not on this page · raw message
base-commit: f582f3cc5c93dff1260fcaa39f96f8bc8cdd0dbb --
RFC PATCH v2 13/51 KVM: selftests: Add script to exercise private_mem_conversions_test
In reply to Ackerley TngMakes testing different combinations of private_mem_conversions_test flags easier.
--- .../kvm/x86/private_mem_conversions_test.sh | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100755 tools/testing/selftests/kvm/x86/private_mem_conversions_test.sh
tools/testing/selftests/kvm/x86/private_mem_conversions_test.sh new file +82 -0
@@ -0,0 +1,82 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-only */ +# +# Wrapper script which runs different test setups of +# private_mem_conversions_test. +# +# Copyright (C) 2024, Google LLC. + +set -e + +num_vcpus_to_test=4 +num_memslots_to_test=$num_vcpus_to_test + +get_default_hugepage_size_in_kB() { + grep "Hugepagesize:" /proc/meminfo | grep -o '[[:digit:]]\+' +} + +# Required pages are based on the test setup (see computation for memfd_size) in +# test_mem_conversions() in private_mem_migrate_tests.c) + +# These static requirements are set to the maximum required for +# num_vcpus_to_test, over all the hugetlb-related tests +required_num_2m_hugepages=$(( 1024 * num_vcpus_to_test )) +required_num_1g_hugepages=$(( 2 * num_vcpus_to_test )) + +# The other hugetlb sizes are not supported on x86_64 +[ "$(cat /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages 2>/dev/null || echo 0)" \ + -ge "$required_num_2m_hugepages" ] && hugepage_2mb_enabled=1 +[ "$(cat /sys/kernel/mm/hugepages/hugepages-1048576kB/nr_hugepages 2>/dev/null || echo 0)" \ + -ge "$required_num_1g_hugepages" ] && hugepage_1gb_enabled=1 + +case $(get_default_hugepage_size_in_kB) in + 2048) + hugepage_default_enabled=$hugepage_2mb_enabled + ;; + 1048576) + hugepage_default_enabled=$hugepage_1gb_enabled + ;; + *) + hugepage_default_enabled=0 + ;; +esac + +backing_src_types=( anonymous ) +backing_src_types+=( anonymous_thp ) +[ -n "$hugepage_default_enabled" ] && \ + backing_src_types+=( anonymous_hugetlb ) || \ + echo "skipping anonymous_hugetlb backing source type" +[ -n "$hugepage_2mb_enabled" ] && \ + backing_src_types+=( anonymous_hugetlb_2mb ) || \ + echo "skipping anonymous_hugetlb_2mb backing source type" +[ -n "$hugepage_1gb_enabled" ] && \ + backing_src_types+=( anonymous_hugetlb_1gb ) || \ + echo "skipping anonymous_hugetlb_1gb backing source type" +backing_src_types+=( shmem ) +[ -n "$hugepage_default_enabled" ] && \ + backing_src_types+=( shared_hugetlb ) || \ + echo "skipping shared_hugetlb backing source type" + +set +e + +TEST_EXECUTABLE="$(dirname "$0")/private_mem_conversions_test" + +( + set -e + + for src_type in "${backing_src_types[@]}"; do + + set -x + + $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test + $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -m $num_memslots_to_test + + { set +x; } 2>/dev/null + + echo + + done +) +RET=$? + +exit $RET
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 14/51 KVM: selftests: Update private_mem_conversions_test to mmap guest_memfd
In reply to Ackerley TngThis patch updates private_mem_conversions_test to use guest_memfd for both private and shared memory. The guest_memfd conversion ioctls are used to perform conversions.
Specify -g to also back shared memory with memory from guest_memfd.
--- .../testing/selftests/kvm/include/kvm_util.h | 1 + tools/testing/selftests/kvm/lib/kvm_util.c | 36 ++++ .../kvm/x86/private_mem_conversions_test.c | 163 +++++++++++++++--- 3 files changed, 176 insertions(+), 24 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +1 -0
@@ -721,6 +721,7 @@ void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa);void *addr_gva2hva (struct kvm_vm *vm,vm_vaddr_t gva);vm_paddr_t addr_hva2gpa (struct kvm_vm *vm,void *hva);void *addr_gpa2alias (struct kvm_vm *vm,vm_paddr_t gpa); +int addr_gpa2guest_memfd (struct kvm_vm *vm,vm_paddr_t gpa,loff_t *offset);#ifndef vcpu_arch_put_guest#define vcpu_arch_put_guest (mem, val) do { (mem) = (val); } while (0)
tools/testing/selftests/kvm/lib/kvm_util.c +36 -0
@@ -1734,6 +1734,42 @@ void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa) + (gpa - region->region.guest_phys_addr)); } +/* +* Address VM Physical to guest_memfd +* +* Input Args: +* vm - Virtual Machine +* gpa - VM physical address +* +* Output Args: +* offset - offset in guest_memfd for gpa +* +* Return: +* guest_memfd for +* +* Locates the memory region containing the VM physical address given by gpa, +* within the VM given by vm. When found, the guest_memfd providing the memory +* to the vm physical address and the offset in the file corresponding to the +* requested gpa is returned. A TEST_ASSERT failure occurs if no region +* containing gpa exists. +*/ +int addr_gpa2guest_memfd (struct kvm_vm *vm,vm_paddr_t gpa,loff_t *offset) +{ +struct userspace_mem_region *region; + + gpa =vm_untag_gpa (vm, gpa); + + region =userspace_mem_region_find (vm, gpa, gpa); +if (!region) { +TEST_FAIL ("No vm physical memory at 0x%lx" , gpa); +return -1 ; + } + + *offset = region->region.guest_memfd_offset + gpa - region->region.guest_phys_addr; + +return region->region.guest_memfd; +} +/* * Address Host Virtual to VM Physical *
tools/testing/selftests/kvm/x86/private_mem_conversions_test.c +139 -24
282 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 15/51 KVM: selftests: Update script to map shared memory from guest_memfd
In reply to Ackerley TngUpdate the private_mem_conversions_test.sh script to use the -g flag to also test conversions when both private and shared memory are mapped from guest_memfd.
--- .../testing/selftests/kvm/x86/private_mem_conversions_test.sh | 3 +++ 1 file changed, 3 insertions(+)
tools/testing/selftests/kvm/x86/private_mem_conversions_test.sh +3 -0
@@ -71,6 +71,9 @@ TEST_EXECUTABLE="$(dirname "$0")/private_mem_conversions_test" $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -m $num_memslots_to_test + $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -g + $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -m $num_memslots_to_test -g + { set +x; } 2>/dev/null echo
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 16/51 mm: hugetlb: Consolidate interpretation of gbl_chg within alloc_hugetlb_folio()
In reply to Ackerley TngPreviously, gbl_chg was passed from alloc_hugetlb_folio() into dequeue_hugetlb_folio_vma(), leaking the concept of gbl_chg into dequeue_hugetlb_folio_vma().
This patch consolidates the interpretation of gbl_chg into alloc_hugetlb_folio(), also renaming dequeue_hugetlb_folio_vma() to dequeue_hugetlb_folio() so dequeue_hugetlb_folio() can just focus on dequeuing a folio.
--- mm/hugetlb.c | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-)
mm/hugetlb.c +11 -17
@@ -1364,9 +1364,9 @@ static unsigned long available_huge_pages(struct hstate *h)return h->free_huge_pages - h->resv_huge_pages; } -static struct folio *dequeue_hugetlb_folio_vma (struct hstate *h, -struct vm_area_struct *vma, -unsigned long address,long gbl_chg) +static struct folio *dequeue_hugetlb_folio (struct hstate *h, +struct vm_area_struct *vma, +unsigned long address) {struct folio *folio =NULL ;struct mempolicy *mpol;
@@ -1374,13 +1374,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,nodemask_t *nodemask;int nid; -/* -* gbl_chg==1 means the allocation requires a new page that was not -* reserved before. Making sure there's at least one free page. -*/ -if (gbl_chg && !available_huge_pages (h)) - goto err; - gfp_mask =htlb_alloc_mask (h); nid =huge_node (vma, address, gfp_mask, &mpol, &nodemask);
@@ -1398,9 +1391,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,mpol_cond_put (mpol);return folio; - -err: -return NULL ; }/*
@@ -3074,12 +3064,16 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, goto out_uncharge_cgroup_reservation;spin_lock_irq (&hugetlb_lock); +/* -* glb_chg is passed to indicate whether or not a page must be taken -* from the global free pool (global change). gbl_chg == 0 indicates -* a reservation exists for the allocation. +* gbl_chg == 0 indicates a reservation exists for the allocation - so +* try dequeuing a page. If there are available_huge_pages(), try using +* them! */ - folio =dequeue_hugetlb_folio_vma (h, vma, addr, gbl_chg); + folio =NULL ; +if (!gbl_chg ||available_huge_pages (h)) + folio =dequeue_hugetlb_folio (h, vma, addr); +if (!folio) {spin_unlock_irq (&hugetlb_lock); folio =alloc_buddy_hugetlb_folio_with_mpol (h, vma, addr);
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Matthew Wilcox
maintainerRe: [RFC PATCH v2 16/51] mm: hugetlb: Consolidate interpretation of gbl_chg within alloc_hugetlb_folio()
mm/hugetlb.c static unsigned long available_huge_pages(struct hstate *h) · line 1369
Quoted 6 lines · Ackerley Tng
mm/hugetlb.c +3
-3-static struct folio *dequeue_hugetlb_folio_vma (struct hstate *h, -struct vm_area_struct *vma, -unsigned long address,long gbl_chg) +static struct folio *dequeue_hugetlb_folio (struct hstate *h, +struct vm_area_struct *vma, +unsigned long address)
Pleaase don't mess with the indentation unless necessary. Nobody cares what your personal style preference is. You're obscuring the actual changes.
Re: [RFC PATCH v2 16/51] mm: hugetlb: Consolidate interpretation of gbl_chg within alloc_hugetlb_folio()
In reply to Ackerley TngQuoted 20 lines · Ackerley Tng
Previously,
gbl_chgwas passed fromalloc_hugetlb_folio()intodequeue_hugetlb_folio_vma(), leaking the concept ofgbl_chgintodequeue_hugetlb_folio_vma().This patch consolidates the interpretation of
gbl_chgintoalloc_hugetlb_folio(), also renamingdequeue_hugetlb_folio_vma()todequeue_hugetlb_folio()sodequeue_hugetlb_folio()can just focus on dequeuing a folio.Change-Id I31bf48af2400b6e13b44d03c8be22ce1a9092a9cSigned-off-by Ackerley Tng <[email protected]>--- mm/hugetlb.c | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-)mm/hugetlb.c +0
-0
mm/hugetlb.c static unsigned long available_huge_pages(struct hstate *h) · line 1369
Quoted 9 lines
mm/hugetlb.c +3
-3@@ -1364,9 +1364,9 @@ static unsigned long available_huge_pages(struct hstate *h)return h->free_huge_pages - h->resv_huge_pages; } -static struct folio *dequeue_hugetlb_folio_vma (struct hstate *h, -struct vm_area_struct *vma, -unsigned long address,long gbl_chg) +static struct folio *dequeue_hugetlb_folio (struct hstate *h, +struct vm_area_struct *vma, +unsigned long address)
The rename seems not needed in this patch, since the function still takes vma and uses it. May be better to move the rename to a later patch.
Quoted 48 lines
mm/hugetlb.c +8
-14{struct folio *folio =NULL ;struct mempolicy *mpol;@@ -1374,13 +1374,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,nodemask_t *nodemask;int nid; -/* -* gbl_chg==1 means the allocation requires a new page that was not -* reserved before. Making sure there's at least one free page. -*/ -if (gbl_chg && !available_huge_pages (h)) - goto err; - gfp_mask =htlb_alloc_mask (h); nid =huge_node (vma, address, gfp_mask, &mpol, &nodemask);@@ -1398,9 +1391,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,mpol_cond_put (mpol);return folio; - -err: -return NULL ; }/* @@ -3074,12 +3064,16 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, goto out_uncharge_cgroup_reservation;spin_lock_irq (&hugetlb_lock); +/* -* glb_chg is passed to indicate whether or not a page must be taken -* from the global free pool (global change). gbl_chg == 0 indicates -* a reservation exists for the allocation. +* gbl_chg == 0 indicates a reservation exists for the allocation - so +* try dequeuing a page. If there are available_huge_pages(), try using +* them! */ - folio =dequeue_hugetlb_folio_vma (h, vma, addr, gbl_chg); + folio =NULL ; +if (!gbl_chg ||available_huge_pages (h)) + folio =dequeue_hugetlb_folio (h, vma, addr); +if (!folio) {spin_unlock_irq (&hugetlb_lock); folio =alloc_buddy_hugetlb_folio_with_mpol (h, vma, addr);
Re: [RFC PATCH v2 16/51] mm: hugetlb: Consolidate interpretation of gbl_chg within alloc_hugetlb_folio()
In reply to Ackerley TngQuoted 5 lines · Ackerley Tng
Previously,
gbl_chgwas passed fromalloc_hugetlb_folio()intodequeue_hugetlb_folio_vma(), leaking the concept ofgbl_chgintodequeue_hugetlb_folio_vma().
Quoted 7 lines
This patch consolidates the interpretation of
gbl_chgintoalloc_hugetlb_folio(), also renamingdequeue_hugetlb_folio_vma()todequeue_hugetlb_folio()sodequeue_hugetlb_folio()can just focus on dequeuing a folio.Change-Id I31bf48af2400b6e13b44d03c8be22ce1a9092a9cSigned-off-by Ackerley Tng <[email protected]>
I think I agree with Binbin[1] to either put the rename of dequeue_hugetlb_folio{_vma => }() in its own patch or drop it entirely.
I think the rename would 100% make sense if all of the dequeue_hugetlb_folio*() functions were called from dequeue_hugetlb_folio_vma() (i.e., after this patch, dequeue_hugetlb_folio() was always the entry point to dequeue a folio), but in fact dequeue_hugetlb_folio_nodemask() is not always called from dequeue_hugetlb_folio_vma().
I don't feel strongly at all, either way the name is not confusing. So feel free to add:
[1]: https://lore.kernel.org/all/[email protected]/
Quoted 69 lines
--- mm/hugetlb.c | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-)mm/hugetlb.c +11
-18@@ -1364,9 +1364,9 @@ static unsigned long available_huge_pages(struct hstate *h)return h->free_huge_pages - h->resv_huge_pages; } -static struct folio *dequeue_hugetlb_folio_vma (struct hstate *h, -struct vm_area_struct *vma, -unsigned long address,long gbl_chg) +static struct folio *dequeue_hugetlb_folio (struct hstate *h, +struct vm_area_struct *vma, +unsigned long address) {struct folio *folio =NULL ;struct mempolicy *mpol;@@ -1374,13 +1374,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,nodemask_t *nodemask;int nid; -/* -* gbl_chg==1 means the allocation requires a new page that was not -* reserved before. Making sure there's at least one free page. -*/ -if (gbl_chg && !available_huge_pages (h)) - goto err; - gfp_mask =htlb_alloc_mask (h); nid =huge_node (vma, address, gfp_mask, &mpol, &nodemask);@@ -1398,9 +1391,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,mpol_cond_put (mpol);return folio; - -err: -return NULL ; }/* @@ -3074,12 +3064,16 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, goto out_uncharge_cgroup_reservation;spin_lock_irq (&hugetlb_lock); +/* -* glb_chg is passed to indicate whether or not a page must be taken -* from the global free pool (global change). gbl_chg == 0 indicates -* a reservation exists for the allocation. +* gbl_chg == 0 indicates a reservation exists for the allocation - so +* try dequeuing a page. If there are available_huge_pages(), try using +* them! */ - folio =dequeue_hugetlb_folio_vma (h, vma, addr, gbl_chg); + folio =NULL ; +if (!gbl_chg ||available_huge_pages (h)) + folio =dequeue_hugetlb_folio (h, vma, addr); +if (!folio) {spin_unlock_irq (&hugetlb_lock); folio =alloc_buddy_hugetlb_folio_with_mpol (h, vma, addr); --2.49.0.1045.g170613ef41-goog
RFC PATCH v2 17/51 mm: hugetlb: Cleanup interpretation of gbl_chg in alloc_hugetlb_folio()
In reply to Ackerley TngThe comment before dequeuing a folio explains that if gbl_chg == 0, a reservation exists for the allocation.
In addition, if a vma reservation exists, there's no need to get a reservation from the subpool, and gbl_chg was set to 0.
This patch replaces both of that with code: subpool_reservation_exists defaults to false, and if a vma reservation does not exist, a reservation is sought from the subpool.
Then, the existence of a reservation, whether in the vma or subpool, is summarized into reservation_exists, which is then used to determine whether to dequeue a folio.
--- mm/hugetlb.c | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-)
mm/hugetlb.c +12 -16
@@ -2999,8 +2999,10 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, {struct hugepage_subpool *spool =subpool_vma (vma);struct hstate *h =hstate_vma (vma); +bool subpool_reservation_exists; +bool reservation_exists;struct folio *folio; -long retval, gbl_chg; +long retval;map_chg_state map_chg;int ret, idx;struct hugetlb_cgroup *h_cg =NULL ;
@@ -3036,17 +3038,16 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,* that the allocation will not exceed the subpool limit. * Or if it can get one from the pool reservation directly. */ + subpool_reservation_exists = false;if (map_chg) { - gbl_chg =hugepage_subpool_get_pages (spool,1 ); -if (gbl_chg <0 ) +int npages_req =hugepage_subpool_get_pages (spool,1 ); + +if (npages_req <0 ) goto out_end_reservation; - }else { -/* -* If we have the vma reservation ready, no need for extra -* global reservation. -*/ - gbl_chg =0 ; + + subpool_reservation_exists = npages_req ==0 ; } + reservation_exists = !map_chg || subpool_reservation_exists;/* * If this allocation is not consuming a per-vma reservation,
@@ -3065,13 +3066,8 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,spin_lock_irq (&hugetlb_lock); -/* -* gbl_chg == 0 indicates a reservation exists for the allocation - so -* try dequeuing a page. If there are available_huge_pages(), try using -* them! -*/ folio =NULL ; -if (!gbl_chg ||available_huge_pages (h)) +if (reservation_exists ||available_huge_pages (h)) folio =dequeue_hugetlb_folio (h, vma, addr);if (!folio) {
@@ -3089,7 +3085,7 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,* Either dequeued or buddy-allocated folio needs to add special * mark to the folio when it consumes a global reservation. */ -if (!gbl_chg) { +if (reservation_exists) {folio_set_hugetlb_restore_reserve (folio); h->resv_huge_pages--; }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 18/51 mm: hugetlb: Cleanup interpretation of map_chg_state within alloc_hugetlb_folio()
In reply to Ackerley TngInterpreting map_chg_state inline, within alloc_hugetlb_folio(), improves readability.
Instead of having cow_from_owner and the result of vma_needs_reservation() compute a map_chg_state, and then interpreting map_chg_state within alloc_hugetlb_folio() to determine whether to
+ Get a page from the subpool or
+ Charge cgroup reservations or
+ Commit vma reservations or
+ Clean up reservations
This refactoring makes those decisions just based on whether a vma_reservation_exists. If a vma_reservation_exists, the subpool had already been debited and the cgroup had been charged, hence alloc_hugetlb_folio() should not double-debit or double-charge. If the vma reservation can't be used (as in cow_from_owner), then the vma reservation effectively does not exist and vma_reservation_exists is set to false.
The conditions for committing reservations or cleaning are also updated to be paired with the corresponding conditions guarding reservation creation.
--- mm/hugetlb.c | 94 ++++++++++++++++++++++------------------------------ 1 file changed, 39 insertions(+), 55 deletions(-)
mm/hugetlb.c +39 -55
@@ -2968,25 +2968,6 @@ void wait_for_freed_hugetlb_folios(void)flush_work (&free_hpage_work); } -typedef enum { -/* -* For either 0/1: we checked the per-vma resv map, and one resv -* count either can be reused (0), or an extra needed (1). -*/ -MAP_CHG_REUSE =0 , -MAP_CHG_NEEDED =1 , -/* -* Cannot use per-vma resv count can be used, hence a new resv -* count is enforced. -* -* NOTE: This is mostly identical to MAP_CHG_NEEDED, except -* that currently vma_needs_reservation() has an unwanted side -* effect to either use end() or commit() to complete the -* transaction. Hence it needs to differenciate from NEEDED. -*/ -MAP_CHG_ENFORCED =2 , -}map_chg_state ; -/* * NOTE! "cow_from_owner" represents a very hacky usage only used in CoW * faults of hugetlb private mappings on top of a non-page-cache folio (in
@@ -3000,46 +2981,45 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,struct hugepage_subpool *spool =subpool_vma (vma);struct hstate *h =hstate_vma (vma);bool subpool_reservation_exists; +bool vma_reservation_exists;bool reservation_exists; +bool charge_cgroup_rsvd;struct folio *folio; -long retval; -map_chg_state map_chg;int ret, idx;struct hugetlb_cgroup *h_cg =NULL ;gfp_t gfp =htlb_alloc_mask (h) | __GFP_RETRY_MAYFAIL; idx =hstate_index (h); -/* Whether we need a separate per-vma reservation? */ if (cow_from_owner) {/* * Special case! Since it's a CoW on top of a reserved * page, the private resv map doesn't count. So it cannot * consume the per-vma resv map even if it's reserved. */ - map_chg =MAP_CHG_ENFORCED ; + vma_reservation_exists = false; }else {/* * Examine the region/reserve map to determine if the process -* has a reservation for the page to be allocated. A return -* code of zero indicates a reservation exists (no change). +* has a reservation for the page to be allocated and debit the +* reservation. If the number of pages required is 0, +* reservation exists. */ - retval =vma_needs_reservation (h, vma, addr); -if (retval <0 ) +int npages_req =vma_needs_reservation (h, vma, addr); + +if (npages_req <0 )return ERR_PTR (-ENOMEM ); - map_chg = retval ?MAP_CHG_NEEDED :MAP_CHG_REUSE ; + + vma_reservation_exists = npages_req ==0 ; }/* -* Whether we need a separate global reservation? -* -* Processes that did not create the mapping will have no -* reserves as indicated by the region/reserve map. Check -* that the allocation will not exceed the subpool limit. -* Or if it can get one from the pool reservation directly. +* Debit subpool only if a vma reservation does not exist. If +* vma_reservation_exists, the vma reservation was either moved from the +* subpool or taken directly from hstate in hugetlb_reserve_pages() */ subpool_reservation_exists = false; -if (map_chg) { +if (!vma_reservation_exists) {int npages_req =hugepage_subpool_get_pages (spool,1 );if (npages_req <0 )
@@ -3047,13 +3027,16 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, subpool_reservation_exists = npages_req ==0 ; } - reservation_exists = !map_chg || subpool_reservation_exists; + + reservation_exists = vma_reservation_exists || subpool_reservation_exists;/* -* If this allocation is not consuming a per-vma reservation, -* charge the hugetlb cgroup now. +* If a vma_reservation_exists, we can skip charging hugetlb +* reservations since that was charged in hugetlb_reserve_pages() when +* the reservation was recorded on the resv_map. */ -if (map_chg) { + charge_cgroup_rsvd = !vma_reservation_exists; +if (charge_cgroup_rsvd) { ret =hugetlb_cgroup_charge_cgroup_rsvd ( idx,pages_per_huge_page (h), &h_cg);if (ret)
@@ -3091,10 +3074,8 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, }hugetlb_cgroup_commit_charge (idx,pages_per_huge_page (h), h_cg, folio); -/* If allocation is not consuming a reservation, also store the -* hugetlb_cgroup pointer on the page. -*/ -if (map_chg) { + +if (charge_cgroup_rsvd) {hugetlb_cgroup_commit_charge_rsvd (idx,pages_per_huge_page (h), h_cg, folio); }
@@ -3103,25 +3084,27 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,hugetlb_set_folio_subpool (folio, spool); -if (map_chg !=MAP_CHG_ENFORCED ) { -/* commit() is only needed if the map_chg is not enforced */ - retval =vma_commit_reservation (h, vma, addr); +/* If vma accounting wasn't bypassed earlier, follow up with commit. */ +if (!cow_from_owner) { +int ret =vma_commit_reservation (h, vma, addr);/* -* Check for possible race conditions. When it happens.. -* The page was added to the reservation map between -* vma_needs_reservation and vma_commit_reservation. -* This indicates a race with hugetlb_reserve_pages. +* If there is a discrepancy in reservation status between the +* time of vma_needs_reservation() and vma_commit_reservation(), +* then there the page must have been added to the reservation +* map between vma_needs_reservation() and +* vma_commit_reservation(). +* * Adjust for the subpool count incremented above AND * in hugetlb_reserve_pages for the same page. Also, * the reservation count added in hugetlb_reserve_pages * no longer applies. */ -if (unlikely (map_chg ==MAP_CHG_NEEDED && retval ==0 )) { +if (unlikely (!vma_reservation_exists && ret ==0 )) {long rsv_adjust; rsv_adjust =hugepage_subpool_put_pages (spool,1 );hugetlb_acct_memory (h, -rsv_adjust); -if (map_chg) { +if (charge_cgroup_rsvd) {spin_lock_irq (&hugetlb_lock); hugetlb_cgroup_uncharge_folio_rsvd( hstate_index(h), pages_per_huge_page(h),
@@ -3149,14 +3132,15 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, out_uncharge_cgroup:hugetlb_cgroup_uncharge_cgroup (idx,pages_per_huge_page (h), h_cg); out_uncharge_cgroup_reservation: -if (map_chg) +if (charge_cgroup_rsvd)hugetlb_cgroup_uncharge_cgroup_rsvd (idx,pages_per_huge_page (h), h_cg); out_subpool_put: -if (map_chg) +if (!vma_reservation_exists)hugepage_subpool_put_pages (spool,1 ); out_end_reservation: -if (map_chg !=MAP_CHG_ENFORCED ) +/* If vma accounting wasn't bypassed earlier, cleanup. */ +if (!cow_from_owner)vma_end_reservation (h, vma, addr);return ERR_PTR (-ENOSPC ); }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 18/51] mm: hugetlb: Cleanup interpretation of map_chg_state within alloc_hugetlb_folio()
Quoted 21 lines · Ackerley Tng
Interpreting
map_chg_stateinline, withinalloc_hugetlb_folio(), improves readability.Instead of having
cow_from_ownerand the result ofvma_needs_reservation()compute amap_chg_state, and then interpretingmap_chg_statewithinalloc_hugetlb_folio()to determine whether to+ Get a page from the subpool or
+ Charge cgroup reservations or
+ Commit vma reservations or
+ Clean up reservationsThis refactoring makes those decisions just based on whether a
vma_reservation_exists. If avma_reservation_exists, the subpool had already been debited and the cgroup had been charged, hencealloc_hugetlb_folio()should not double-debit or double-charge. If the vma reservation can't be used (as incow_from_owner), then the vma reservation effectively does not exist andvma_reservation_existsis set to false.
Quoted 6 lines
The conditions for committing reservations or cleaning are also updated to be paired with the corresponding conditions guarding reservation creation.
Signed-off-by Ackerley Tng <[email protected]>Change-Id I22d72a2cae61fb64dc78e0a870b254811a06a31e
Hi Ackerley,
Can you help me better understand how useful the refactors in this and the preceding patch are for the series as a whole?
It seems like you and Peter had two different, but mostly equivalent, directions with how this code should be refactored[1]. Do you gain much by replacing Peter's refactoring strategy? If it's mostly a stylistic thing, maybe it would be better to remove these patches just to get the number of patches to review down.
The logic in these two patches looks good to me, and I think I do slightly prefer your approach. But if we could drop these patches (i.e., mail them separately), that's probably better.
RFC PATCH v2 19/51 mm: hugetlb: Rename alloc_surplus_hugetlb_folio
In reply to Ackerley TngRename alloc_surplus_hugetlb_folio vs alloc_surplus_hugetlb_folio_nodemask to align with dequeue_hugetlb_folio vs dequeue_hugetlb_folio_nodemask.
--- mm/hugetlb.c | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-)
mm/hugetlb.c +20 -18
@@ -2236,7 +2236,7 @@ int dissolve_free_hugetlb_folios(unsigned long start_pfn, unsigned long end_pfn)/* * Allocates a fresh surplus page from the page allocator. */ -static struct folio *alloc_surplus_hugetlb_folio (struct hstate *h, +static struct folio *alloc_surplus_hugetlb_folio_nodemask (struct hstate *h,gfp_t gfp_mask,int nid,nodemask_t *nmask) {struct folio *folio =NULL ;
@@ -2312,9 +2312,9 @@ static struct folio *alloc_migrate_hugetlb_folio(struct hstate *h, gfp_t gfp_mas/* * Use the VMA's mpolicy to allocate a huge page from the buddy. */ -static -struct folio *alloc_buddy_hugetlb_folio_with_mpol (struct hstate *h, -struct vm_area_struct *vma,unsigned long addr) +static struct folio *alloc_surplus_hugetlb_folio (struct hstate *h, +struct vm_area_struct *vma, +unsigned long addr) {struct folio *folio =NULL ;struct mempolicy *mpol;
@@ -2326,14 +2326,14 @@ struct folio *alloc_buddy_hugetlb_folio_with_mpol(struct hstate *h,if (mpol_is_preferred_many (mpol)) {gfp_t gfp = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL); - folio =alloc_surplus_hugetlb_folio (h, gfp, nid, nodemask); + folio =alloc_surplus_hugetlb_folio_nodemask (h, gfp, nid, nodemask);/* Fallback to all nodes if page==NULL */ nodemask =NULL ; }if (!folio) - folio =alloc_surplus_hugetlb_folio (h, gfp_mask, nid, nodemask); + folio =alloc_surplus_hugetlb_folio_nodemask (h, gfp_mask, nid, nodemask);mpol_cond_put (mpol);return folio; }
@@ -2435,14 +2435,14 @@ static int gather_surplus_pages(struct hstate *h, long delta)/* Prioritize current node */ if (node_isset (numa_mem_id (), alloc_nodemask)) - folio =alloc_surplus_hugetlb_folio (h,htlb_alloc_mask (h), + folio =alloc_surplus_hugetlb_folio_nodemask (h,htlb_alloc_mask (h),numa_mem_id (),NULL );if (!folio) {for_each_node_mask (node, alloc_nodemask) {if (node ==numa_mem_id ())continue ; - folio =alloc_surplus_hugetlb_folio (h,htlb_alloc_mask (h), + folio =alloc_surplus_hugetlb_folio_nodemask (h,htlb_alloc_mask (h), node,NULL );if (folio)break ;
@@ -3055,7 +3055,7 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,if (!folio) {spin_unlock_irq (&hugetlb_lock); - folio =alloc_buddy_hugetlb_folio_with_mpol (h, vma, addr); + folio =alloc_surplus_hugetlb_folio (h, vma, addr);if (!folio) goto out_uncharge_cgroup;spin_lock_irq (&hugetlb_lock);
@@ -3868,11 +3868,12 @@ static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,* First take pages out of surplus state. Then make up the * remaining difference by allocating fresh huge pages. * -* We might race with alloc_surplus_hugetlb_folio() here and be unable -* to convert a surplus huge page to a normal huge page. That is -* not critical, though, it just means the overall size of the -* pool might be one hugepage larger than it needs to be, but -* within all the constraints specified by the sysctls. +* We might race with alloc_surplus_hugetlb_folio_nodemask() +* here and be unable to convert a surplus huge page to a normal +* huge page. That is not critical, though, it just means the +* overall size of the pool might be one hugepage larger than it +* needs to be, but within all the constraints specified by the +* sysctls. */ while (h->surplus_huge_pages && count >persistent_huge_pages (h)) {if (!adjust_pool_surplus (h, nodes_allowed,-1 ))
@@ -3930,10 +3931,11 @@ static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,* By placing pages into the surplus state independent of the * overcommit value, we are allowing the surplus pool size to * exceed overcommit. There are few sane options here. Since -* alloc_surplus_hugetlb_folio() is checking the global counter, -* though, we'll note that we're not allowed to exceed surplus -* and won't grow the pool anywhere else. Not until one of the -* sysctls are changed, or the surplus pages go out of use. +* alloc_surplus_hugetlb_folio_nodemask() is checking the global +* counter, though, we'll note that we're not allowed to exceed +* surplus and won't grow the pool anywhere else. Not until one +* of the sysctls are changed, or the surplus pages go out of +* use. * * min_count is the expected number of persistent pages, we * shouldn't calculate min_count by using
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 20/51 mm: mempolicy: Refactor out policy_node_nodemask()
In reply to Ackerley TngThis was refactored out of huge_node().
huge_node()'s interpretation of vma for order assumes the hugetlb-specific storage of the hstate information in the inode. policy_node_nodemask() does not assume that, and can be used more generically.
This refactoring also enforces that nid default to the current node id, which was not previously enforced.
alloc_pages_mpol() is the last remaining direct user of policy_nodemask(). All its callers begin with nid being the current node id as well. More refactoring is required for to simplify that.
Change-Id: I5774b27d2e718f4d08b59f8d2fedbb34eda7bac3
--- include/linux/mempolicy.h | 9 +++++++++ mm/mempolicy.c | 33 ++++++++++++++++++++++++++------- 2 files changed, 35 insertions(+), 7 deletions(-)
include/linux/mempolicy.h +9 -0
@@ -138,6 +138,8 @@ extern void numa_policy_init(void);extern void mpol_rebind_task (struct task_struct *tsk,const nodemask_t *new);extern void mpol_rebind_mm (struct mm_struct *mm,nodemask_t *new); +extern int policy_node_nodemask (struct mempolicy *mpol,gfp_t gfp_flags, +pgoff_t ilx,nodemask_t **nodemask);extern int huge_node (struct vm_area_struct *vma,unsigned long addr,gfp_t gfp_flags,struct mempolicy **mpol,nodemask_t **nodemask);
@@ -251,6 +253,13 @@ static inline void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new) { } +static inline int policy_node_nodemask (struct mempolicy *mpol,gfp_t gfp_flags, +pgoff_t ilx,nodemask_t **nodemask) +{ + *nodemask =NULL ; +return 0 ; +} +static inline int huge_node (struct vm_area_struct *vma,unsigned long addr,gfp_t gfp_flags,struct mempolicy **mpol,nodemask_t **nodemask)
mm/mempolicy.c +26 -7
@@ -1261,7 +1261,7 @@ static struct folio *alloc_migration_target_by_mpol(struct folio *src, h =folio_hstate (src); gfp =htlb_alloc_mask (h); - nodemask =policy_nodemask (gfp, pol, ilx, &nid); + nid =policy_node_nodemask (pol, gfp, ilx, &nodemask);return alloc_hugetlb_folio_nodemask (h, nid, nodemask, gfp,htlb_allow_alloc_fallback (MR_MEMPOLICY_MBIND )); }
@@ -2121,6 +2121,29 @@ static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *pol,return nodemask; } +/** +* policy_node_nodemask() - Interpret memory policy to get nodemask and nid. +* +* @mpol: the memory policy to interpret. +* @gfp_flags: gfp flags for this request. +* @ilx: interleave index, for use only when MPOL_INTERLEAVE or +* MPOL_WEIGHTED_INTERLEAVE +* @nodemask: (output) pointer to nodemask pointer for 'bind' and 'prefer-many' +* policy +* +* Context: must hold reference on @mpol. +* Return: a nid suitable for a page allocation and a pointer. If the effective +* policy is 'bind' or 'prefer-many', returns a pointer to the +* mempolicy's @nodemask for filtering the zonelist. +*/ +int policy_node_nodemask (struct mempolicy *mpol,gfp_t gfp_flags, +pgoff_t ilx,nodemask_t **nodemask) +{ +int nid =numa_node_id (); + *nodemask =policy_nodemask (gfp_flags, mpol, ilx, &nid); +return nid; +} +#ifdef CONFIG_HUGETLBFS /* * huge_node(@vma, @addr, @gfp_flags, @mpol)
@@ -2139,12 +2162,9 @@ int huge_node(struct vm_area_struct *vma, unsigned long addr, gfp_t gfp_flags, struct mempolicy **mpol, nodemask_t **nodemask) { pgoff_t ilx; -int nid; - nid =numa_node_id (); *mpol =get_vma_policy (vma, addr,hstate_vma (vma)->order, &ilx); - *nodemask =policy_nodemask (gfp_flags, *mpol, ilx, &nid); -return nid; +return policy_node_nodemask (*mpol, gfp_flags, ilx, nodemask); }/*
@@ -2601,8 +2621,7 @@ unsigned long alloc_pages_bulk_mempolicy_noprof(gfp_t gfp,return alloc_pages_bulk_preferred_many (gfp,numa_node_id (), pol, nr_pages, page_array); - nid =numa_node_id (); - nodemask =policy_nodemask (gfp, pol,NO_INTERLEAVE_INDEX , &nid); + nid =policy_node_nodemask (pol, gfp,NO_INTERLEAVE_INDEX , &nodemask);return alloc_pages_bulk_noprof (gfp, nid, nodemask, nr_pages, page_array); }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 21/51 mm: hugetlb: Inline huge_node() into callers
In reply to Ackerley Tnghuge_node()'s role was to read struct mempolicy (mpol) from the vma and also interpret mpol to get node id and nodemask.
huge_node() can be inlined into callers since 2 out of 3 of the callers will be refactored in later patches to take and interpret mpol without reading mpol from the vma.
Change-Id: Ic94b2ed916fd4f89b7d2755288a3a2f6a56051f7
--- include/linux/mempolicy.h | 12 ------------ mm/hugetlb.c | 13 ++++++++++--- mm/mempolicy.c | 21 --------------------- 3 files changed, 10 insertions(+), 36 deletions(-)
include/linux/mempolicy.h +0 -12
@@ -140,9 +140,6 @@ extern void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new);extern int policy_node_nodemask (struct mempolicy *mpol,gfp_t gfp_flags,pgoff_t ilx,nodemask_t **nodemask); -extern int huge_node (struct vm_area_struct *vma, -unsigned long addr,gfp_t gfp_flags, -struct mempolicy **mpol,nodemask_t **nodemask);extern bool init_nodemask_of_mempolicy (nodemask_t *mask);extern bool mempolicy_in_oom_domain (struct task_struct *tsk,const nodemask_t *mask);
@@ -260,15 +257,6 @@ static inline int policy_node_nodemask(struct mempolicy *mpol, gfp_t gfp_flags,return 0 ; } -static inline int huge_node (struct vm_area_struct *vma, -unsigned long addr,gfp_t gfp_flags, -struct mempolicy **mpol,nodemask_t **nodemask) -{ - *mpol =NULL ; - *nodemask =NULL ; -return 0 ; -} -static inline bool init_nodemask_of_mempolicy (nodemask_t *m) {return false;
mm/hugetlb.c +10 -3
@@ -1372,10 +1372,12 @@ static struct folio *dequeue_hugetlb_folio(struct hstate *h,struct mempolicy *mpol;gfp_t gfp_mask;nodemask_t *nodemask; +pgoff_t ilx;int nid; gfp_mask =htlb_alloc_mask (h); - nid =huge_node (vma, address, gfp_mask, &mpol, &nodemask); + mpol =get_vma_policy (vma, address, h->order, &ilx); + nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask);if (mpol_is_preferred_many (mpol)) { folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
@@ -2321,8 +2323,11 @@ static struct folio *alloc_surplus_hugetlb_folio(struct hstate *h,gfp_t gfp_mask =htlb_alloc_mask (h);int nid;nodemask_t *nodemask; +pgoff_t ilx; + + mpol =get_vma_policy (vma, addr, h->order, &ilx); + nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask); - nid =huge_node (vma, addr, gfp_mask, &mpol, &nodemask);if (mpol_is_preferred_many (mpol)) {gfp_t gfp = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
@@ -6829,10 +6834,12 @@ static struct folio *alloc_hugetlb_folio_vma(struct hstate *h,nodemask_t *nodemask;struct folio *folio;gfp_t gfp_mask; +pgoff_t ilx;int node; gfp_mask =htlb_alloc_mask (h); - node =huge_node (vma, address, gfp_mask, &mpol, &nodemask); + mpol =get_vma_policy (vma, address, h->order, &ilx); + node =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask);/* * This is used to allocate a temporary hugetlb to hold the copied * content, which will then be copied again to the final hugetlb
mm/mempolicy.c +0 -21
@@ -2145,27 +2145,6 @@ int policy_node_nodemask(struct mempolicy *mpol, gfp_t gfp_flags, }#ifdef CONFIG_HUGETLBFS -/* -* huge_node(@vma, @addr, @gfp_flags, @mpol) -* @vma: virtual memory area whose policy is sought -* @addr: address in @vma for shared policy lookup and interleave policy -* @gfp_flags: for requested zone -* @mpol: pointer to mempolicy pointer for reference counted mempolicy -* @nodemask: pointer to nodemask pointer for 'bind' and 'prefer-many' policy -* -* Returns a nid suitable for a huge page allocation and a pointer -* to the struct mempolicy for conditional unref after allocation. -* If the effective policy is 'bind' or 'prefer-many', returns a pointer -* to the mempolicy's @nodemask for filtering the zonelist. -*/ -int huge_node (struct vm_area_struct *vma,unsigned long addr,gfp_t gfp_flags, -struct mempolicy **mpol,nodemask_t **nodemask) -{ -pgoff_t ilx; - - *mpol =get_vma_policy (vma, addr,hstate_vma (vma)->order, &ilx); -return policy_node_nodemask (*mpol, gfp_flags, ilx, nodemask); -}/* * init_nodemask_of_mempolicy
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 22/51 mm: hugetlb: Refactor hugetlb allocation functions
In reply to Ackerley TngRefactor dequeue_hugetlb_folio() and alloc_surplus_hugetlb_folio() to take mpol, nid and nodemask. This decouples allocation of a folio from a vma.
--- mm/hugetlb.c | 64 ++++++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 34 deletions(-)
mm/hugetlb.c +30 -34
@@ -1364,34 +1364,22 @@ static unsigned long available_huge_pages(struct hstate *h)return h->free_huge_pages - h->resv_huge_pages; } -static struct folio *dequeue_hugetlb_folio (struct hstate *h, -struct vm_area_struct *vma, -unsigned long address) +static struct folio *dequeue_hugetlb_folio (struct hstate *h,gfp_t gfp_mask, +struct mempolicy *mpol, +int nid,nodemask_t *nodemask) {struct folio *folio =NULL ; -struct mempolicy *mpol; -gfp_t gfp_mask; -nodemask_t *nodemask; -pgoff_t ilx; -int nid; - - gfp_mask =htlb_alloc_mask (h); - mpol =get_vma_policy (vma, address, h->order, &ilx); - nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask);if (mpol_is_preferred_many (mpol)) { - folio =dequeue_hugetlb_folio_nodemask (h, gfp_mask, - nid, nodemask); + folio =dequeue_hugetlb_folio_nodemask (h, gfp_mask, nid, nodemask);/* Fallback to all nodes if page==NULL */ nodemask =NULL ; }if (!folio) - folio =dequeue_hugetlb_folio_nodemask (h, gfp_mask, - nid, nodemask); + folio =dequeue_hugetlb_folio_nodemask (h, gfp_mask, nid, nodemask); -mpol_cond_put (mpol);return folio; }
@@ -2312,21 +2300,14 @@ static struct folio *alloc_migrate_hugetlb_folio(struct hstate *h, gfp_t gfp_mas }/* -* Use the VMA's mpolicy to allocate a huge page from the buddy. +* Allocate a huge page from the buddy allocator given memory policy and node information. */ static struct folio *alloc_surplus_hugetlb_folio (struct hstate *h, -struct vm_area_struct *vma, -unsigned long addr) +gfp_t gfp_mask, +struct mempolicy *mpol, +int nid,nodemask_t *nodemask) {struct folio *folio =NULL ; -struct mempolicy *mpol; -gfp_t gfp_mask =htlb_alloc_mask (h); -int nid; -nodemask_t *nodemask; -pgoff_t ilx; - - mpol =get_vma_policy (vma, addr, h->order, &ilx); - nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask);if (mpol_is_preferred_many (mpol)) {gfp_t gfp = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
@@ -2339,7 +2320,7 @@ static struct folio *alloc_surplus_hugetlb_folio(struct hstate *h,if (!folio) folio =alloc_surplus_hugetlb_folio_nodemask (h, gfp_mask, nid, nodemask); -mpol_cond_put (mpol); +return folio; }
@@ -2993,6 +2974,11 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,int ret, idx;struct hugetlb_cgroup *h_cg =NULL ;gfp_t gfp =htlb_alloc_mask (h) | __GFP_RETRY_MAYFAIL; +struct mempolicy *mpol; +nodemask_t *nodemask; +gfp_t gfp_mask; +pgoff_t ilx; +int nid; idx =hstate_index (h);
@@ -3032,7 +3018,6 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, subpool_reservation_exists = npages_req ==0 ; } - reservation_exists = vma_reservation_exists || subpool_reservation_exists;/*
@@ -3048,21 +3033,30 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, goto out_subpool_put; } + mpol =get_vma_policy (vma, addr, h->order, &ilx); + ret =hugetlb_cgroup_charge_cgroup (idx,pages_per_huge_page (h), &h_cg); -if (ret) +if (ret) { +mpol_cond_put (mpol); goto out_uncharge_cgroup_reservation; + } + + gfp_mask =htlb_alloc_mask (h); + nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask);spin_lock_irq (&hugetlb_lock); folio =NULL ;if (reservation_exists ||available_huge_pages (h)) - folio =dequeue_hugetlb_folio (h, vma, addr); + folio =dequeue_hugetlb_folio (h, gfp_mask, mpol, nid, nodemask);if (!folio) {spin_unlock_irq (&hugetlb_lock); - folio =alloc_surplus_hugetlb_folio (h, vma, addr); -if (!folio) + folio =alloc_surplus_hugetlb_folio (h, gfp_mask, mpol, nid, nodemask); +if (!folio) { +mpol_cond_put (mpol); goto out_uncharge_cgroup; + }spin_lock_irq (&hugetlb_lock);list_add (&folio->lru, &h->hugepage_activelist);folio_ref_unfreeze (folio,1 );
@@ -3087,6 +3081,8 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,spin_unlock_irq (&hugetlb_lock); +mpol_cond_put (mpol); +hugetlb_set_folio_subpool (folio, spool);/* If vma accounting wasn't bypassed earlier, follow up with commit. */
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 22/51] mm: hugetlb: Refactor hugetlb allocation functions
Quoted 10 lines · Ackerley Tng
Refactor
dequeue_hugetlb_folio()andalloc_surplus_hugetlb_folio()to take mpol, nid and nodemask. This decouples allocation of a folio from a vma.Signed-off-by Ackerley Tng <[email protected]>Change-Id I890fb46fe8c6349383d8cf89befc68a4994eb416--- mm/hugetlb.c | 64 ++++++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 34 deletions(-)
[snip]
Quoted 22 lines
mm/hugetlb.c +5
-1@@ -2993,6 +2974,11 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,int ret, idx;struct hugetlb_cgroup *h_cg =NULL ;gfp_t gfp =htlb_alloc_mask (h) | __GFP_RETRY_MAYFAIL; +struct mempolicy *mpol; +nodemask_t *nodemask; +gfp_t gfp_mask; +pgoff_t ilx; +int nid; idx =hstate_index (h);@@ -3032,7 +3018,6 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, subpool_reservation_exists = npages_req ==0 ; } - reservation_exists = vma_reservation_exists || subpool_reservation_exists;/*
mm/hugetlb.c struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, · line 3036
Quoted 4 lines
mm/hugetlb.c +1
-0@@ -3048,21 +3033,30 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, goto out_subpool_put; } + mpol =get_vma_policy (vma, addr, h->order, &ilx);
Why does the memory policy need to be acquired here instead of after the cgroup charge? AFAICT this is not needed and would at least eliminate 1 of the error conditions puts.
mm/hugetlb.c struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, · line 3040
Quoted 5 lines
mm/hugetlb.c +3
-1+ ret =hugetlb_cgroup_charge_cgroup (idx,pages_per_huge_page (h), &h_cg); -if (ret) +if (ret) { +mpol_cond_put (mpol);
^^^^ here
All that said I think the use of some new cleanup macros could really help a lot of this code.
What do folks in this area of the kernel think of those?
Ira
[snip]
Re: [RFC PATCH v2 22/51] mm: hugetlb: Refactor hugetlb allocation functions
Quoted 39 lines · Ira Weiny
Quoted 10 lines · Ackerley Tng
Refactor
dequeue_hugetlb_folio()andalloc_surplus_hugetlb_folio()to take mpol, nid and nodemask. This decouples allocation of a folio from a vma.Signed-off-by Ackerley Tng <[email protected]>Change-Id I890fb46fe8c6349383d8cf89befc68a4994eb416--- mm/hugetlb.c | 64 ++++++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 34 deletions(-)[snip]
Quoted 25 lines
mm/hugetlb.c +5
-1@@ -2993,6 +2974,11 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,int ret, idx;struct hugetlb_cgroup *h_cg =NULL ;gfp_t gfp =htlb_alloc_mask (h) | __GFP_RETRY_MAYFAIL; +struct mempolicy *mpol; +nodemask_t *nodemask; +gfp_t gfp_mask; +pgoff_t ilx; +int nid; idx =hstate_index (h);@@ -3032,7 +3018,6 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, subpool_reservation_exists = npages_req ==0 ; } - reservation_exists = vma_reservation_exists || subpool_reservation_exists;/* @@ -3048,21 +3033,30 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, goto out_subpool_put; }
Quoted 6 lines
mm/hugetlb.c struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, · line 3036
Quoted 1 line
mm/hugetlb.c +1
-0+ mpol =get_vma_policy (vma, addr, h->order, &ilx);Why does the memory policy need to be acquired here instead of after the cgroup charge? AFAICT this is not needed and would at least eliminate 1 of the error conditions puts.
I was hoping that by taking this early, the upcoming refactoring out of hugetlb_alloc_folio() will look like a nice, clean removal of the middle of this function, leaving acquiring of the mpol and mpol_cond_put() in-place.
In the next revision I'm splitting up the refactoring in this patch further so if this is still an issue in some number of revisions' time, I can fix this.
Quoted 11 lines
mm/hugetlb.c struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, · line 3040
Quoted 5 lines
mm/hugetlb.c +3
-1+ ret =hugetlb_cgroup_charge_cgroup (idx,pages_per_huge_page (h), &h_cg); -if (ret) +if (ret) { +mpol_cond_put (mpol);^^^^ hereAll that said I think the use of some new cleanup macros could really help a lot of this code.
I'm happy to try that out...
Quoted 2 lines
What do folks in this area of the kernel think of those?
not sure though.
Quoted 3 lines
Ira
[snip]
RFC PATCH v2 23/51 mm: hugetlb: Refactor out hugetlb_alloc_folio()
In reply to Ackerley TngRefactor out hugetlb_alloc_folio() from alloc_hugetlb_folio(), which handles allocation of a folio and cgroup charging.
Other than flags to control charging in the allocation process, hugetlb_alloc_folio() also has parameters for memory policy.
This refactoring as a whole decouples the hugetlb page allocation from hugetlbfs, (1) where the subpool is stored at the fs mount, (2) reservations are made during mmap and stored in the vma, and (3) mpol must be stored at vma->vm_policy (4) a vma must be used for allocation even if the pages are not meant to be used by host process.
This decoupling will allow hugetlb_alloc_folio() to be used by guest_memfd in later patches. In guest_memfd, (1) a subpool is created per-fd and is stored on the inode, (2) no vma-related reservations are used (3) mpol may not be associated with a vma since (4) for private pages, the pages will not be mappable to userspace and hence have to associated vmas.
This could hopefully also open hugetlb up as a more generic source of hugetlb pages that are not bound to hugetlbfs, with the complexities of userspace/mmap/vma-related reservations contained just to hugetlbfs.
--- include/linux/hugetlb.h | 12 +++ mm/hugetlb.c | 192 ++++++++++++++++++++++------------------ 2 files changed, 118 insertions(+), 86 deletions(-)
include/linux/hugetlb.h +12 -0
@@ -698,6 +698,9 @@ bool hugetlb_bootmem_page_zones_valid(int nid, struct huge_bootmem_page *m);int isolate_or_dissolve_huge_page (struct page *page,struct list_head *list);int replace_free_hugepage_folios (unsigned long start_pfn,unsigned long end_pfn);void wait_for_freed_hugetlb_folios (void ); +struct folio *hugetlb_alloc_folio (struct hstate *h,struct mempolicy *mpol, +pgoff_t ilx,bool charge_cgroup_rsvd, +bool use_existing_reservation);struct folio *alloc_hugetlb_folio (struct vm_area_struct *vma,unsigned long addr,bool cow_from_owner); struct folio *alloc_hugetlb_folio_nodemask(struct hstate *h, int preferred_nid,
@@ -1099,6 +1102,15 @@ static inline void wait_for_freed_hugetlb_folios(void) { } +static inline struct folio *hugetlb_alloc_folio (struct hstate *h, +struct mempolicy *mpol, +pgoff_t ilx, +bool charge_cgroup_rsvd, +bool use_existing_reservation) +{ +return NULL ; +} +static inline struct folio *alloc_hugetlb_folio (struct vm_area_struct *vma,unsigned long addr,bool cow_from_owner)
mm/hugetlb.c +106 -86
233 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 23/51] mm: hugetlb: Refactor out hugetlb_alloc_folio()
Quoted 31 lines · Ackerley Tng
Refactor out
hugetlb_alloc_folio()fromalloc_hugetlb_folio(), which handles allocation of a folio and cgroup charging.Other than flags to control charging in the allocation process,
hugetlb_alloc_folio()also has parameters for memory policy.This refactoring as a whole decouples the hugetlb page allocation from hugetlbfs, (1) where the subpool is stored at the fs mount, (2) reservations are made during mmap and stored in the vma, and (3) mpol must be stored at
vma->vm_policy(4) a vma must be used for allocation even if the pages are not meant to be used by host process.This decoupling will allow
hugetlb_alloc_folio()to be used byguest_memfdin later patches. Inguest_memfd, (1) a subpool is created per-fd and is stored on the inode, (2) no vma-related reservations are used (3) mpol may not be associated with a vma since (4) for private pages, the pages will not be mappable to userspace and hence have to associated vmas.This could hopefully also open hugetlb up as a more generic source of hugetlb pages that are not bound to hugetlbfs, with the complexities of userspace/mmap/vma-related reservations contained just to hugetlbfs.
Signed-off-by Ackerley Tng <[email protected]>Change-Id I60528f246341268acbf0ed5de7752ae2cacbef93--- include/linux/hugetlb.h | 12 +++ mm/hugetlb.c | 192 ++++++++++++++++++++++------------------ 2 files changed, 118 insertions(+), 86 deletions(-)
[snip]
Quoted 24 lines
mm/hugetlb.c +23
-0+/** +* hugetlb_alloc_folio() - Allocates a hugetlb folio. +* +* @h: struct hstate to allocate from. +* @mpol: struct mempolicy to apply for this folio allocation. +* @ilx: Interleave index for interpretation of @mpol. +* @charge_cgroup_rsvd: Set to true to charge cgroup reservation. +* @use_existing_reservation: Set to true if this allocation should use an +* existing hstate reservation. +* +* This function handles cgroup and global hstate reservations. VMA-related +* reservations and subpool debiting must be handled by the caller if necessary. +* +* Return: folio on success or negated error otherwise. +*/ +struct folio *hugetlb_alloc_folio (struct hstate *h,struct mempolicy *mpol, +pgoff_t ilx,bool charge_cgroup_rsvd, +bool use_existing_reservation) +{ +unsigned int nr_pages =pages_per_huge_page (h); +struct hugetlb_cgroup *h_cg =NULL ; +struct folio *folio =NULL ; +nodemask_t *nodemask;
mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 2989
Quoted 10 lines
mm/hugetlb.c +10
-0+gfp_t gfp_mask; +int nid; +int idx; +int ret; + + idx =hstate_index (h); + +if (charge_cgroup_rsvd) { +if (hugetlb_cgroup_charge_cgroup_rsvd (idx, nr_pages, &h_cg)) + goto out;
Why not just return here?
return ERR_PTR(-ENOSPC);
Quoted 47 lines
mm/hugetlb.c +47
-0+ } + +if (hugetlb_cgroup_charge_cgroup (idx, nr_pages, &h_cg)) + goto out_uncharge_cgroup_reservation; + + gfp_mask =htlb_alloc_mask (h); + nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask); + +spin_lock_irq (&hugetlb_lock); + +if (use_existing_reservation ||available_huge_pages (h)) + folio =dequeue_hugetlb_folio (h, gfp_mask, mpol, nid, nodemask); + +if (!folio) { +spin_unlock_irq (&hugetlb_lock); + folio =alloc_surplus_hugetlb_folio (h, gfp_mask, mpol, nid, nodemask); +if (!folio) + goto out_uncharge_cgroup; +spin_lock_irq (&hugetlb_lock); +list_add (&folio->lru, &h->hugepage_activelist); +folio_ref_unfreeze (folio,1 ); +/* Fall through */ + } + +if (use_existing_reservation) { +folio_set_hugetlb_restore_reserve (folio); + h->resv_huge_pages--; + } + +hugetlb_cgroup_commit_charge (idx, nr_pages, h_cg, folio); + +if (charge_cgroup_rsvd) +hugetlb_cgroup_commit_charge_rsvd (idx, nr_pages, h_cg, folio); + +spin_unlock_irq (&hugetlb_lock); + + gfp_mask =htlb_alloc_mask (h) | __GFP_RETRY_MAYFAIL; + ret =mem_cgroup_charge_hugetlb (folio, gfp_mask); +/* +* Unconditionally increment NR_HUGETLB here. If it turns out that +* mem_cgroup_charge_hugetlb failed, then immediately free the page and +* decrement NR_HUGETLB. +*/ +lruvec_stat_mod_folio (folio,NR_HUGETLB ,pages_per_huge_page (h)); + +if (ret == -ENOMEM ) { +free_huge_folio (folio);
mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 3046
Quoted 10 lines
mm/hugetlb.c +10
-0+return ERR_PTR (-ENOMEM ); + } + +return folio; + +out_uncharge_cgroup: +hugetlb_cgroup_uncharge_cgroup (idx, nr_pages, h_cg); +out_uncharge_cgroup_reservation: +if (charge_cgroup_rsvd) +hugetlb_cgroup_uncharge_cgroup_rsvd (idx, nr_pages, h_cg);
I find the direct copy of the unwind logic from alloc_hugetlb_folio() cumbersome and it seems like a good opportunity to clean it up.
mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 3049
Quoted 3 lines
mm/hugetlb.c +3
-0+out: + folio =ERR_PTR (-ENOSPC ); + goto out;
Endless loop?
Ira
[snip]
Re: [RFC PATCH v2 23/51] mm: hugetlb: Refactor out hugetlb_alloc_folio()
Quoted 71 lines · Ira Weiny
Quoted 31 lines · Ackerley Tng
Refactor out
hugetlb_alloc_folio()fromalloc_hugetlb_folio(), which handles allocation of a folio and cgroup charging.Other than flags to control charging in the allocation process,
hugetlb_alloc_folio()also has parameters for memory policy.This refactoring as a whole decouples the hugetlb page allocation from hugetlbfs, (1) where the subpool is stored at the fs mount, (2) reservations are made during mmap and stored in the vma, and (3) mpol must be stored at
vma->vm_policy(4) a vma must be used for allocation even if the pages are not meant to be used by host process.This decoupling will allow
hugetlb_alloc_folio()to be used byguest_memfdin later patches. Inguest_memfd, (1) a subpool is created per-fd and is stored on the inode, (2) no vma-related reservations are used (3) mpol may not be associated with a vma since (4) for private pages, the pages will not be mappable to userspace and hence have to associated vmas.This could hopefully also open hugetlb up as a more generic source of hugetlb pages that are not bound to hugetlbfs, with the complexities of userspace/mmap/vma-related reservations contained just to hugetlbfs.
Signed-off-by Ackerley Tng <[email protected]>Change-Id I60528f246341268acbf0ed5de7752ae2cacbef93--- include/linux/hugetlb.h | 12 +++ mm/hugetlb.c | 192 ++++++++++++++++++++++------------------ 2 files changed, 118 insertions(+), 86 deletions(-)[snip]
Quoted 24 lines
mm/hugetlb.c +23
-0+/** +* hugetlb_alloc_folio() - Allocates a hugetlb folio. +* +* @h: struct hstate to allocate from. +* @mpol: struct mempolicy to apply for this folio allocation. +* @ilx: Interleave index for interpretation of @mpol. +* @charge_cgroup_rsvd: Set to true to charge cgroup reservation. +* @use_existing_reservation: Set to true if this allocation should use an +* existing hstate reservation. +* +* This function handles cgroup and global hstate reservations. VMA-related +* reservations and subpool debiting must be handled by the caller if necessary. +* +* Return: folio on success or negated error otherwise. +*/ +struct folio *hugetlb_alloc_folio (struct hstate *h,struct mempolicy *mpol, +pgoff_t ilx,bool charge_cgroup_rsvd, +bool use_existing_reservation) +{ +unsigned int nr_pages =pages_per_huge_page (h); +struct hugetlb_cgroup *h_cg =NULL ; +struct folio *folio =NULL ; +nodemask_t *nodemask;mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 2989
Quoted 10 lines
mm/hugetlb.c +10
-0+gfp_t gfp_mask; +int nid; +int idx; +int ret; + + idx =hstate_index (h); + +if (charge_cgroup_rsvd) { +if (hugetlb_cgroup_charge_cgroup_rsvd (idx, nr_pages, &h_cg)) + goto out;Why not just return here?
Quoted 2 lines
return ERR_PTR(-ENOSPC);
I wanted to consistently exit the function on errors at the same place, and also make this refactoring look like I just took the middle of alloc_hugetlb_folio() out as much as possible.
Quoted 52 lines
Quoted 52 lines
mm/hugetlb.c +52
-0+ } + +if (hugetlb_cgroup_charge_cgroup (idx, nr_pages, &h_cg)) + goto out_uncharge_cgroup_reservation; + + gfp_mask =htlb_alloc_mask (h); + nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask); + +spin_lock_irq (&hugetlb_lock); + +if (use_existing_reservation ||available_huge_pages (h)) + folio =dequeue_hugetlb_folio (h, gfp_mask, mpol, nid, nodemask); + +if (!folio) { +spin_unlock_irq (&hugetlb_lock); + folio =alloc_surplus_hugetlb_folio (h, gfp_mask, mpol, nid, nodemask); +if (!folio) + goto out_uncharge_cgroup; +spin_lock_irq (&hugetlb_lock); +list_add (&folio->lru, &h->hugepage_activelist); +folio_ref_unfreeze (folio,1 ); +/* Fall through */ + } + +if (use_existing_reservation) { +folio_set_hugetlb_restore_reserve (folio); + h->resv_huge_pages--; + } + +hugetlb_cgroup_commit_charge (idx, nr_pages, h_cg, folio); + +if (charge_cgroup_rsvd) +hugetlb_cgroup_commit_charge_rsvd (idx, nr_pages, h_cg, folio); + +spin_unlock_irq (&hugetlb_lock); + + gfp_mask =htlb_alloc_mask (h) | __GFP_RETRY_MAYFAIL; + ret =mem_cgroup_charge_hugetlb (folio, gfp_mask); +/* +* Unconditionally increment NR_HUGETLB here. If it turns out that +* mem_cgroup_charge_hugetlb failed, then immediately free the page and +* decrement NR_HUGETLB. +*/ +lruvec_stat_mod_folio (folio,NR_HUGETLB ,pages_per_huge_page (h)); + +if (ret == -ENOMEM ) { +free_huge_folio (folio); +return ERR_PTR (-ENOMEM ); + } + +return folio; +
Quoted 9 lines
mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 3046
Quoted 5 lines
mm/hugetlb.c +5
-0+out_uncharge_cgroup: +hugetlb_cgroup_uncharge_cgroup (idx, nr_pages, h_cg); +out_uncharge_cgroup_reservation: +if (charge_cgroup_rsvd) +hugetlb_cgroup_uncharge_cgroup_rsvd (idx, nr_pages, h_cg);I find the direct copy of the unwind logic from
alloc_hugetlb_folio()cumbersome and it seems like a good opportunity to clean it up.
I really wanted to make this refactoring look like I just took the middle of alloc_hugetlb_folio() out as much as possible, to make it obvious and understandable. I think the cleanup can be a separate patch (series?)
Quoted 6 lines
mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 3049
Quoted 3 lines
mm/hugetlb.c +3
-0+out: + folio =ERR_PTR (-ENOSPC ); + goto out;Endless loop?
Thanks, this should have been
return folio;
Quoted 3 lines
Ira
[snip]
RFC PATCH v2 24/51 mm: hugetlb: Add option to create new subpool without using surplus
In reply to Ackerley Tng__hugetlb_acct_memory() today does more than just memory accounting. When there's insufficient HugeTLB pages, __hugetlb_acct_memory() will attempt to get surplus pages.
This change adds a flag to disable getting surplus pages if there are insufficient HugeTLB pages.
--- fs/hugetlbfs/inode.c | 2 +- include/linux/hugetlb.h | 2 +- mm/hugetlb.c | 77 +++++++++++++++++++++++++++++++---------- 3 files changed, 61 insertions(+), 20 deletions(-)
fs/hugetlbfs/inode.c +1 -1
@@ -1424,7 +1424,7 @@ hugetlbfs_fill_super(struct super_block *sb, struct fs_context *fc)if (ctx->max_hpages !=-1 || ctx->min_hpages !=-1 ) { sbinfo->spool =hugepage_new_subpool (ctx->hstate, ctx->max_hpages, - ctx->min_hpages); + ctx->min_hpages, true);if (!sbinfo->spool) goto out_free; }
include/linux/hugetlb.h +1 -1
@@ -116,7 +116,7 @@ extern int hugetlb_max_hstate __read_mostly;for ((h) = hstates; (h) < &hstates[hugetlb_max_hstate]; (h)++) struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages, -long min_hpages); +long min_hpages,bool use_surplus);void hugepage_put_subpool (struct hugepage_subpool *spool);void hugetlb_dup_vma_private (struct vm_area_struct *vma);
mm/hugetlb.c +59 -18
148 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 25/51 mm: truncate: Expose preparation steps for truncate_inode_pages_final
In reply to Ackerley TngThis will allow preparation steps to be shared while implementing truncation differently.
--- include/linux/mm.h | 1 + mm/truncate.c | 26 ++++++++++++++++---------- 2 files changed, 17 insertions(+), 10 deletions(-)
include/linux/mm.h +1 -0
@@ -3514,6 +3514,7 @@ extern unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info);extern void truncate_inode_pages (struct address_space *,loff_t );extern void truncate_inode_pages_range (struct address_space *,loff_t lstart,loff_t lend); +extern void truncate_inode_pages_final_prepare (struct address_space *mapping);extern void truncate_inode_pages_final (struct address_space *);/* generic vm_area_ops exported for stackable file systems */
mm/truncate.c +16 -10
@@ -457,16 +457,7 @@ void truncate_inode_pages(struct address_space *mapping, loff_t lstart) }EXPORT_SYMBOL (truncate_inode_pages); -/** -* truncate_inode_pages_final - truncate *all* pages before inode dies -* @mapping: mapping to truncate -* -* Called under (and serialized by) inode->i_rwsem. -* -* Filesystems have to use this in the .evict_inode path to inform the -* VM that this is the final truncate and the inode is going away. -*/ -void truncate_inode_pages_final (struct address_space *mapping) +void truncate_inode_pages_final_prepare (struct address_space *mapping) {/* * Page reclaim can not participate in regular inode lifetime
@@ -487,6 +478,21 @@ void truncate_inode_pages_final(struct address_space *mapping)xa_lock_irq (&mapping->i_pages);xa_unlock_irq (&mapping->i_pages); } +} +EXPORT_SYMBOL (truncate_inode_pages_final_prepare); + +/** +* truncate_inode_pages_final - truncate *all* pages before inode dies +* @mapping: mapping to truncate +* +* Called under (and serialized by) inode->i_rwsem. +* +* Filesystems have to use this in the .evict_inode path to inform the +* VM that this is the final truncate and the inode is going away. +*/ +void truncate_inode_pages_final (struct address_space *mapping) +{ +truncate_inode_pages_final_prepare (mapping);truncate_inode_pages (mapping,0 ); }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 26/51 mm: Consolidate freeing of typed folios on final folio_put()
In reply to Ackerley TngFrom: Fuad Tabba <[email protected]>
Some folio types, such as hugetlb, handle freeing their own folios.
The guestmem_hugetlb folio, to be introduced in a later patch, requires extra handling as part of the freeing process.
As a first step towards that, this patch consolidates freeing folios that have a type. The first user is hugetlb folios. Later in this patch series, guestmem_hugetlb will become the second user of this.
--- include/linux/page-flags.h | 15 +++++++++++++++ mm/swap.c | 23 ++++++++++++++++++----- 2 files changed, 33 insertions(+), 5 deletions(-)
include/linux/page-flags.h +15 -0
@@ -985,6 +985,21 @@ static inline bool page_has_type(const struct page *page)return page_mapcount_is_type (data_race (page->page_type)); } +static inline int page_get_type (const struct page *page) +{ +return page->page_type >>24 ; +} + +static inline bool folio_has_type (const struct folio *folio) +{ +return page_has_type (&folio->page); +} + +static inline int folio_get_type (const struct folio *folio) +{ +return page_get_type (&folio->page); +} +#define FOLIO_TYPE_OPS (lname, fname) \ static __always_inline bool folio_test_##fname(const struct folio *folio) \ { \
mm/swap.c +18 -5
@@ -94,6 +94,19 @@ static void page_cache_release(struct folio *folio)unlock_page_lruvec_irqrestore (lruvec, flags); } +static void free_typed_folio (struct folio *folio) +{ +switch (folio_get_type (folio)) { +#ifdef CONFIG_HUGETLBFS +case PGTY_hugetlb: +free_huge_folio (folio); +return ; +#endif +default : +WARN_ON_ONCE (1 ); + } +} +void __folio_put (struct folio *folio) {if (unlikely (folio_is_zone_device (folio))) {
@@ -101,8 +114,8 @@ void __folio_put(struct folio *folio)return ; } -if (folio_test_hugetlb (folio)) { -free_huge_folio (folio); +if (unlikely (folio_has_type (folio))) { +free_typed_folio (folio);return ; }
@@ -964,13 +977,13 @@ void folios_put_refs(struct folio_batch *folios, unsigned int *refs)if (!folio_ref_sub_and_test (folio, nr_refs))continue ; -/* hugetlb has its own memcg */ -if (folio_test_hugetlb (folio)) { +if (unlikely (folio_has_type (folio))) { +/* typed folios have their own memcg, if any */ if (lruvec) {unlock_page_lruvec_irqrestore (lruvec, flags); lruvec =NULL ; } -free_huge_folio (folio); +free_typed_folio (folio);continue ; }folio_unqueue_deferred_split (folio);
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 27/51 mm: hugetlb: Expose hugetlb_subpool_{get,put}_pages()
In reply to Ackerley TngThis will allow hugetlb subpools to be used by guestmem_hugetlb.
--- include/linux/hugetlb.h | 3 +++ mm/hugetlb.c | 6 ++---- 2 files changed, 5 insertions(+), 4 deletions(-)
include/linux/hugetlb.h +3 -0
@@ -119,6 +119,9 @@ struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages, long min_hpages, bool use_surplus);void hugepage_put_subpool (struct hugepage_subpool *spool); +long hugepage_subpool_get_pages (struct hugepage_subpool *spool,long delta); +long hugepage_subpool_put_pages (struct hugepage_subpool *spool,long delta); +void hugetlb_dup_vma_private (struct vm_area_struct *vma);void clear_vma_resv_huge_pages (struct vm_area_struct *vma); int move_hugetlb_page_tables(struct vm_area_struct *vma,
mm/hugetlb.c +2 -4
@@ -205,8 +205,7 @@ void hugepage_put_subpool(struct hugepage_subpool *spool)* only be different than the passed value (delta) in the case where * a subpool minimum size must be maintained. */ -static long hugepage_subpool_get_pages (struct hugepage_subpool *spool, -long delta) +long hugepage_subpool_get_pages (struct hugepage_subpool *spool,long delta) {long ret = delta;
@@ -250,8 +249,7 @@ static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,* The return value may only be different than the passed value (delta) * in the case where a subpool minimum size must be maintained. */ -static long hugepage_subpool_put_pages (struct hugepage_subpool *spool, -long delta) +long hugepage_subpool_put_pages (struct hugepage_subpool *spool,long delta) {long ret = delta;unsigned long flags;
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 28/51 mm: Introduce guestmem_hugetlb to support folio_put() handling of guestmem pages
In reply to Ackerley TngThe PGTY_guestmem_hugetlb is introduced so folios can be marked for further cleanup by guestmem_hugetlb.
guestmem_hugetlb folios can have positive mapcounts, which will conflict with the installation of a page type. Hence, PGTY_guestmem_hugetlb will only be installed when a folio is truncated, after the folio has been unmapped and has a mapcount of 0.
Change-Id: I635f8929e06f73d7899737bd47090b7cbc7222dc
--- include/linux/page-flags.h | 17 +++++++++++++++++ mm/Kconfig | 10 ++++++++++ mm/Makefile | 1 + mm/debug.c | 1 + mm/guestmem_hugetlb.c | 14 ++++++++++++++ mm/guestmem_hugetlb.h | 9 +++++++++ mm/swap.c | 9 +++++++++ 7 files changed, 61 insertions(+) create mode 100644 mm/guestmem_hugetlb.c create mode 100644 mm/guestmem_hugetlb.h
include/linux/page-flags.h +17 -0
@@ -965,6 +965,7 @@ enum pagetype { PGTY_zsmalloc =0xf6 , PGTY_unaccepted =0xf7 , PGTY_large_kmalloc =0xf8 , + PGTY_guestmem_hugetlb =0xf9 , PGTY_mapcount_underflow = 0xff };
@@ -1114,6 +1115,22 @@ FOLIO_TYPE_OPS(hugetlb, hugetlb) FOLIO_TEST_FLAG_FALSE(hugetlb)#endif +/* +* PGTY_guestmem_hugetlb, for now, is used to mark a folio as requiring further +* cleanup by the guestmem_hugetlb allocator. This page type is installed only +* at truncation time, by guest_memfd, if further cleanup is required. It is +* safe to install this page type at truncation time because by then mapcount +* would be 0. +* +* The plan is to always set this page type for any folios allocated by +* guestmem_hugetlb once typed folios can be mapped to userspace cleanly. +*/ +#ifdef CONFIG_GUESTMEM_HUGETLB +FOLIO_TYPE_OPS(guestmem_hugetlb, guestmem_hugetlb) +#else +FOLIO_TEST_FLAG_FALSE(guestmem_hugetlb) +#endif +PAGE_TYPE_OPS (Zsmalloc, zsmalloc, zsmalloc)/*
mm/Kconfig +10 -0
@@ -1216,6 +1216,16 @@ config SECRETMEM memory areas visible only in the context of the owning process and not mapped to other processes and other kernel page tables. +config GUESTMEM_HUGETLB + bool "Enable guestmem_hugetlb allocator for guest_memfd" + depends on HUGETLBFS + help + Enable this to make HugeTLB folios available to guest_memfd + (KVM virtualization) as backing memory. + + This feature wraps HugeTLB as a custom allocator that + guest_memfd can use. + config ANON_VMA_NAME bool "Anonymous VMA name support" depends on PROC_FS && ADVISE_SYSCALLS && MMU
mm/Makefile +1 -0
@@ -127,6 +127,7 @@ obj-$(CONFIG_PAGE_EXTENSION) += page_ext.o obj-$(CONFIG_PAGE_TABLE_CHECK) += page_table_check.o obj-$(CONFIG_CMA_DEBUGFS) += cma_debug.o obj-$(CONFIG_SECRETMEM) += secretmem.o +obj-$(CONFIG_GUESTMEM_HUGETLB) += guestmem_hugetlb.o obj-$(CONFIG_CMA_SYSFS) += cma_sysfs.o obj-$(CONFIG_USERFAULTFD) += userfaultfd.o obj-$(CONFIG_IDLE_PAGE_TRACKING) += page_idle.o
mm/debug.c +1 -0
@@ -56,6 +56,7 @@ static const char *page_type_names[] = {DEF_PAGETYPE_NAME (table),DEF_PAGETYPE_NAME (buddy),DEF_PAGETYPE_NAME (unaccepted), + DEF_PAGETYPE_NAME(guestmem_hugetlb), };static const char *page_type_name (unsigned int page_type)
mm/guestmem_hugetlb.c new file +14 -0
@@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* guestmem_hugetlb is an allocator for guest_memfd. guest_memfd wraps HugeTLB +* as an allocator for guest_memfd. +*/ + +#include <linux/mm_types.h> + +#include "guestmem_hugetlb.h" + +void guestmem_hugetlb_handle_folio_put (struct folio *folio) +{ +WARN_ONCE (1 ,"A placeholder that shouldn't trigger. Work in progress." ); +}
mm/guestmem_hugetlb.h new file +9 -0
@@ -0,0 +1,9 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _LINUX_MM_GUESTMEM_HUGETLB_H +#define _LINUX_MM_GUESTMEM_HUGETLB_H + +#include <linux/mm_types.h> + +void guestmem_hugetlb_handle_folio_put (struct folio *folio); + +#endif
mm/swap.c +9 -0
@@ -40,6 +40,10 @@#include "internal.h" +#ifdef CONFIG_GUESTMEM_HUGETLB +#include "guestmem_hugetlb.h" +#endif +#define CREATE_TRACE_POINTS #include <trace/events/pagemap.h>
@@ -101,6 +105,11 @@ static void free_typed_folio(struct folio *folio)case PGTY_hugetlb:free_huge_folio (folio);return ; +#endif +#ifdef CONFIG_GUESTMEM_HUGETLB +case PGTY_guestmem_hugetlb: +guestmem_hugetlb_handle_folio_put (folio); +return ;#endif default :WARN_ON_ONCE (1 );
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 29/51 mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
In reply to Ackerley Tngguestmem_hugetlb is an allocator for guest_memfd. It wraps HugeTLB to provide huge folios for guest_memfd.
This patch also introduces guestmem_allocator_operations as a set of operations that allocators for guest_memfd can provide. In a later patch, guest_memfd will use these operations to manage pages from an allocator.
The allocator operations are memory-management specific and are placed in mm/ so key mm-specific functions do not have to be exposed unnecessarily.
Change-Id: I3cafe111ea7b3c84755d7112ff8f8c541c11136d
--- include/linux/guestmem.h | 20 +++++ include/uapi/linux/guestmem.h | 29 +++++++ mm/Kconfig | 5 +- mm/guestmem_hugetlb.c | 159 ++++++++++++++++++++++++++++++++++ 4 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 include/linux/guestmem.h create mode 100644 include/uapi/linux/guestmem.h
include/linux/guestmem.h new file +20 -0
@@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _LINUX_GUESTMEM_H +#define _LINUX_GUESTMEM_H + +#include <linux/fs.h> + +struct guestmem_allocator_operations { +void *(*inode_setup)(size_t size,u64 flags); +void (*inode_teardown)(void *private,size_t inode_size); +struct folio *(*alloc_folio)(void *private); +/* +* Returns the number of PAGE_SIZE pages in a page that this guestmem +* allocator provides. +*/ +size_t (*nr_pages_in_folio)(void *priv); +}; + +extern const struct guestmem_allocator_operations guestmem_hugetlb_ops; + +#endif
include/uapi/linux/guestmem.h new file +29 -0
@@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _UAPI_LINUX_GUESTMEM_H +#define _UAPI_LINUX_GUESTMEM_H + +/* +* Huge page size must be explicitly defined when using the guestmem_hugetlb +* allocator for guest_memfd. It is the responsibility of the application to +* know which sizes are supported on the running system. See mmap(2) man page +* for details. +*/ + +#define GUESTMEM_HUGETLB_FLAG_SHIFT 58 +#define GUESTMEM_HUGETLB_FLAG_MASK 0x3fUL + +#define GUESTMEM_HUGETLB_FLAG_16KB (14UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_64KB (16UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_512KB (19UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_1MB (20UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_2MB (21UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_8MB (23UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_16MB (24UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_32MB (25UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_256MB (28UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_512MB (29UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_1GB (30UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_2GB (31UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_16GB (34UL << GUESTMEM_HUGETLB_FLAG_SHIFT) + +#endif /* _UAPI_LINUX_GUESTMEM_H */
mm/Kconfig +4 -1
@@ -1218,7 +1218,10 @@ config SECRETMEM config GUESTMEM_HUGETLB bool "Enable guestmem_hugetlb allocator for guest_memfd" - depends on HUGETLBFS + select GUESTMEM + select HUGETLBFS + select HUGETLB_PAGE + select HUGETLB_PAGE_OPTIMIZE_VMEMMAP help Enable this to make HugeTLB folios available to guest_memfd (KVM virtualization) as backing memory.
mm/guestmem_hugetlb.c +159 -0
168 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
Quoted 31 lines · Ackerley Tng
guestmem_hugetlbis an allocator forguest_memfd. It wraps HugeTLB to provide huge folios forguest_memfd.This patch also introduces
guestmem_allocator_operationsas a set of operations that allocators forguest_memfdcan provide. In a later patch,guest_memfdwill use these operations to manage pages from an allocator.The allocator operations are memory-management specific and are placed in
mm/so key mm-specific functions do not have to be exposed unnecessarily.Signed-off-by Ackerley Tng <[email protected]>Change-Id: I3cafe111ea7b3c84755d7112ff8f8c541c11136d
--- include/linux/guestmem.h | 20 +++++ include/uapi/linux/guestmem.h | 29 +++++++ mm/Kconfig | 5 +- mm/guestmem_hugetlb.c | 159 ++++++++++++++++++++++++++++++++++ 4 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 include/linux/guestmem.h create mode 100644 include/uapi/linux/guestmem.h<snip>
mm/Kconfig +0
-0
mm/Kconfig config SECRETMEM · line 1224
Quoted 8 lines
mm/Kconfig +4
-1@@ -1218,7 +1218,10 @@ config SECRETMEM config GUESTMEM_HUGETLB bool "Enable guestmem_hugetlb allocator for guest_memfd" - depends on HUGETLBFS + select GUESTMEM + select HUGETLBFS + select HUGETLB_PAGE + select HUGETLB_PAGE_OPTIMIZE_VMEMMAP
My bad. I left out CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP_DEFAULT_ON=y in my testing and just found that when it is set, I hit
BUG_ON(pte_page(ptep_get(pte)) != walk->reuse_page);
with the basic guest_memfd_test on splitting pages on allocation.
I'll follow up with the fix soon.
Another note about testing: I've been testing in a nested VM for the development process:
1. Host
2. VM for development
3. Nested VM running kernel being developed
4. Nested nested VMs created during selftests
This series has not yet been tested on a physical host.
Quoted 6 lines
mm/Kconfig +0
-0help Enable this to make HugeTLB folios available to guest_memfd (KVM virtualization) as backing memory.
Re: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
Quoted 54 lines · Ackerley Tng
Quoted 31 lines · Ackerley Tng
guestmem_hugetlbis an allocator forguest_memfd. It wraps HugeTLB to provide huge folios forguest_memfd.This patch also introduces
guestmem_allocator_operationsas a set of operations that allocators forguest_memfdcan provide. In a later patch,guest_memfdwill use these operations to manage pages from an allocator.The allocator operations are memory-management specific and are placed in
mm/so key mm-specific functions do not have to be exposed unnecessarily.Signed-off-by Ackerley Tng <[email protected]>Change-Id: I3cafe111ea7b3c84755d7112ff8f8c541c11136d
--- include/linux/guestmem.h | 20 +++++ include/uapi/linux/guestmem.h | 29 +++++++ mm/Kconfig | 5 +- mm/guestmem_hugetlb.c | 159 ++++++++++++++++++++++++++++++++++ 4 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 include/linux/guestmem.h create mode 100644 include/uapi/linux/guestmem.h<snip>
mm/Kconfig +0
-0mm/Kconfig config SECRETMEM · line 1224
Quoted 8 lines
mm/Kconfig +4
-1@@ -1218,7 +1218,10 @@ config SECRETMEM config GUESTMEM_HUGETLB bool "Enable guestmem_hugetlb allocator for guest_memfd" - depends on HUGETLBFS + select GUESTMEM + select HUGETLBFS + select HUGETLB_PAGE + select HUGETLB_PAGE_OPTIMIZE_VMEMMAPMy bad. I left out
CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP_DEFAULT_ON=yin my testing and just found that when it is set, I hitBUG_ON(pte_page(ptep_get(pte)) != walk->reuse_page);with the basic
guest_memfd_teston splitting pages on allocation.I'll follow up with the fix soon.
Another note about testing: I've been testing in a nested VM for the development process:
Quoted 13 lines
1. Host
2. VM for development
3. Nested VM running kernel being developed
4. Nested nested VMs created during selftestsThis series has not yet been tested on a physical host.
Quoted 6 lines
mm/Kconfig +0
-0help Enable this to make HugeTLB folios available to guest_memfd (KVM virtualization) as backing memory.
Here's the fix for this issue
From 998af6404d4e39920ba42764e7f3815cb9bb9e3d Mon Sep 17 00:00:00 2001
Message-ID: <998af6404d4e39920ba42764e7f3815cb9bb9e3d.1747427489.git.ackerleytng@google.com>
From: Ackerley Tng <[email protected]>
Date: Fri, 16 May 2025 13:14:55 -0700
Subject: [RFC PATCH v2 1/1] KVM: guest_memfd: Reorder undoing vmemmap
optimization and stashing hugetlb folio metadata
Without this patch, when HugeTLB folio metadata is stashed, the vmemmap_optimized flag, stored in a HugeTLB folio's folio->private was stashed as set.
The first splitting works, but on merging, when the folio metadata was unstashed, vmemmap_optimized is unstashed as set, making the call to hugetlb_vmemmap_optimize_folio() skip actually applying optimizations.
On a second split, hugetlb_vmemmap_restore_folio() attempts to reapply optimizations when it was already applied, hence hitting the BUG().
--- mm/guestmem_hugetlb.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-)
mm/guestmem_hugetlb.c +11 -7
@@ -200,16 +200,21 @@ static int guestmem_hugetlb_split_folio(struct folio *folio)return 0 ; orig_nr_pages =folio_nr_pages (folio); - ret =guestmem_hugetlb_stash_metadata (folio); + +/* +* hugetlb_vmemmap_restore_folio() has to be called ahead of the rest +* because it checks page type. This doesn't actually split the folio, +* so the first few struct pages are still intact. +*/ + ret =hugetlb_vmemmap_restore_folio (folio_hstate (folio), folio);if (ret)return ret;/* -* hugetlb_vmemmap_restore_folio() has to be called ahead of the rest -* because it checks and page type. This doesn't actually split the -* folio, so the first few struct pages are still intact. +* Stash metadata after vmemmap stuff so the outcome of the vmemmap +* restoration is stashed. */ - ret =hugetlb_vmemmap_restore_folio (folio_hstate (folio), folio); + ret =guestmem_hugetlb_stash_metadata (folio);if (ret) goto err;
@@ -254,8 +259,7 @@ static int guestmem_hugetlb_split_folio(struct folio *folio)return 0 ; err: -guestmem_hugetlb_unstash_free_metadata (folio); - +hugetlb_vmemmap_optimize_folio (folio_hstate (folio), folio);return ret; }
Signature · 1 line
2.49.0.1101.gccaa498523-goog
Re: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
Quoted 115 lines · Ackerley Tng
Quoted 54 lines · Ackerley Tng
Quoted 31 lines · Ackerley Tng
guestmem_hugetlbis an allocator forguest_memfd. It wraps HugeTLB to provide huge folios forguest_memfd.This patch also introduces
guestmem_allocator_operationsas a set of operations that allocators forguest_memfdcan provide. In a later patch,guest_memfdwill use these operations to manage pages from an allocator.The allocator operations are memory-management specific and are placed in
mm/so key mm-specific functions do not have to be exposed unnecessarily.Signed-off-by Ackerley Tng <[email protected]>Change-Id: I3cafe111ea7b3c84755d7112ff8f8c541c11136d
--- include/linux/guestmem.h | 20 +++++ include/uapi/linux/guestmem.h | 29 +++++++ mm/Kconfig | 5 +- mm/guestmem_hugetlb.c | 159 ++++++++++++++++++++++++++++++++++ 4 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 include/linux/guestmem.h create mode 100644 include/uapi/linux/guestmem.h<snip>
mm/Kconfig +0
-0mm/Kconfig config SECRETMEM · line 1224
Quoted 8 lines
mm/Kconfig +4
-1@@ -1218,7 +1218,10 @@ config SECRETMEM config GUESTMEM_HUGETLB bool "Enable guestmem_hugetlb allocator for guest_memfd" - depends on HUGETLBFS + select GUESTMEM + select HUGETLBFS + select HUGETLB_PAGE + select HUGETLB_PAGE_OPTIMIZE_VMEMMAPMy bad. I left out
CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP_DEFAULT_ON=yin my testing and just found that when it is set, I hitBUG_ON(pte_page(ptep_get(pte)) != walk->reuse_page);with the basic
guest_memfd_teston splitting pages on allocation.I'll follow up with the fix soon.
Another note about testing: I've been testing in a nested VM for the development process:
Quoted 13 lines
1. Host
2. VM for development
3. Nested VM running kernel being developed
4. Nested nested VMs created during selftestsThis series has not yet been tested on a physical host.
Quoted 6 lines
mm/Kconfig +0
-0help Enable this to make HugeTLB folios available to guest_memfd (KVM virtualization) as backing memory.Here's the fix for this issue
From
998af6404d4e39920ba42764e7f3815cb9bb9e3dMon Sep 17 00:00:00 2001
Message-ID: <998af6404d4e39920ba42764e7f3815cb9bb9e3d.1747427489.git.ackerleytng@google.com>
From: Ackerley Tng <[email protected]>
Date: Fri, 16 May 2025 13:14:55 -0700
Subject: [RFC PATCH v2 1/1] KVM:guest_memfd: Reorder undoing vmemmap
optimization and stashing hugetlb folio metadataWithout this patch, when HugeTLB folio metadata is stashed, the
vmemmap_optimizedflag, stored in a HugeTLB folio'sfolio->privatewas stashed as set.The first splitting works, but on merging, when the folio metadata was unstashed,
vmemmap_optimizedis unstashed as set, making the call tohugetlb_vmemmap_optimize_folio()skip actually applying optimizations.On a second split,
hugetlb_vmemmap_restore_folio()attempts to reapply optimizations when it was already applied, hence hitting theBUG().Signed-off-by Ackerley Tng <[email protected]>--- mm/guestmem_hugetlb.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-)mm/guestmem_hugetlb.c +7
-1@@ -200,16 +200,21 @@ static int guestmem_hugetlb_split_folio(struct folio *folio)return 0 ; orig_nr_pages =folio_nr_pages (folio); - ret =guestmem_hugetlb_stash_metadata (folio); + +/* +* hugetlb_vmemmap_restore_folio() has to be called ahead of the rest +* because it checks page type. This doesn't actually split the folio, +* so the first few struct pages are still intact. +*/ + ret =hugetlb_vmemmap_restore_folio (folio_hstate (folio), folio);if (ret)return ret;/*
mm/guestmem_hugetlb.c static int guestmem_hugetlb_split_folio(struct folio *folio) · line 219
Quoted 10 lines
mm/guestmem_hugetlb.c +3
-4-* hugetlb_vmemmap_restore_folio() has to be called ahead of the rest -* because it checks and page type. This doesn't actually split the -* folio, so the first few struct pages are still intact. +* Stash metadata after vmemmap stuff so the outcome of the vmemmap +* restoration is stashed. */ - ret =hugetlb_vmemmap_restore_folio (folio_hstate (folio), folio); + ret =guestmem_hugetlb_stash_metadata (folio);if (ret) goto err;
Doh, I missed this before replying earlier. This definitely seems like the cleaner fix as it pertains to other flags/state that potentially becomes stale after calling hugetlb_vmemmap_restore_folio().
-Mike
Re: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
In reply to Ackerley TngQuoted 153 lines · Ackerley Tng
guestmem_hugetlbis an allocator forguest_memfd. It wraps HugeTLB to provide huge folios forguest_memfd.This patch also introduces
guestmem_allocator_operationsas a set of operations that allocators forguest_memfdcan provide. In a later patch,guest_memfdwill use these operations to manage pages from an allocator.The allocator operations are memory-management specific and are placed in
mm/so key mm-specific functions do not have to be exposed unnecessarily.Signed-off-by Ackerley Tng <[email protected]>Change-Id: I3cafe111ea7b3c84755d7112ff8f8c541c11136d
--- include/linux/guestmem.h | 20 +++++ include/uapi/linux/guestmem.h | 29 +++++++ mm/Kconfig | 5 +- mm/guestmem_hugetlb.c | 159 ++++++++++++++++++++++++++++++++++ 4 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 include/linux/guestmem.h create mode 100644 include/uapi/linux/guestmem.hinclude/linux/guestmem.h new file +20
-0@@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _LINUX_GUESTMEM_H +#define _LINUX_GUESTMEM_H + +#include <linux/fs.h> + +struct guestmem_allocator_operations { +void *(*inode_setup)(size_t size,u64 flags); +void (*inode_teardown)(void *private,size_t inode_size); +struct folio *(*alloc_folio)(void *private); +/* +* Returns the number of PAGE_SIZE pages in a page that this guestmem +* allocator provides. +*/ +size_t (*nr_pages_in_folio)(void *priv); +}; + +extern const struct guestmem_allocator_operations guestmem_hugetlb_ops; + +#endif include/uapi/linux/guestmem.h new file +29
-0@@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _UAPI_LINUX_GUESTMEM_H +#define _UAPI_LINUX_GUESTMEM_H + +/* +* Huge page size must be explicitly defined when using the guestmem_hugetlb +* allocator for guest_memfd. It is the responsibility of the application to +* know which sizes are supported on the running system. See mmap(2) man page +* for details. +*/ + +#define GUESTMEM_HUGETLB_FLAG_SHIFT 58 +#define GUESTMEM_HUGETLB_FLAG_MASK 0x3fUL + +#define GUESTMEM_HUGETLB_FLAG_16KB (14UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_64KB (16UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_512KB (19UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_1MB (20UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_2MB (21UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_8MB (23UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_16MB (24UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_32MB (25UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_256MB (28UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_512MB (29UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_1GB (30UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_2GB (31UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_16GB (34UL << GUESTMEM_HUGETLB_FLAG_SHIFT) + +#endif /* _UAPI_LINUX_GUESTMEM_H */ mm/Kconfig +4
-1@@ -1218,7 +1218,10 @@ config SECRETMEM config GUESTMEM_HUGETLB bool "Enable guestmem_hugetlb allocator for guest_memfd" - depends on HUGETLBFS + select GUESTMEM + select HUGETLBFS + select HUGETLB_PAGE + select HUGETLB_PAGE_OPTIMIZE_VMEMMAP help Enable this to make HugeTLB folios available to guest_memfd (KVM virtualization) as backing memory.mm/guestmem_hugetlb.c +37
-0@@ -5,6 +5,14 @@*/ #include <linux/mm_types.h> +#include <linux/guestmem.h> +#include <linux/hugetlb.h> +#include <linux/hugetlb_cgroup.h> +#include <linux/mempolicy.h> +#include <linux/mm.h> +#include <linux/pagemap.h> + +#include <uapi/linux/guestmem.h> #include "guestmem_hugetlb.h" @@ -12,3 +20,154 @@ void guestmem_hugetlb_handle_folio_put(struct folio *folio) {WARN_ONCE (1 ,"A placeholder that shouldn't trigger. Work in progress." ); } + +struct guestmem_hugetlb_private { +struct hstate *h; +struct hugepage_subpool *spool; +struct hugetlb_cgroup *h_cg_rsvd; +}; + +static size_t guestmem_hugetlb_nr_pages_in_folio (void *priv) +{ +struct guestmem_hugetlb_private *private = priv; + +return pages_per_huge_page (private->h); +} + +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 ;
mm/guestmem_hugetlb.c void guestmem_hugetlb_handle_folio_put(struct folio *folio) · line 61
Quoted 10 lines
mm/guestmem_hugetlb.c +10
-0+ 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.
-Mike
Quoted 116 lines
mm/guestmem_hugetlb.c +112
-0+ + 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); +} + +static void guestmem_hugetlb_teardown (void *priv,size_t inode_size) +{ +struct guestmem_hugetlb_private *private = priv; +unsigned long nr_pages; +int idx; + +hugepage_put_subpool (private->spool); + + idx =hstate_index (private->h); + nr_pages = inode_size >>PAGE_SHIFT ; +hugetlb_cgroup_uncharge_cgroup_rsvd (idx, nr_pages, private->h_cg_rsvd); + +kfree (private); +} + +static struct folio *guestmem_hugetlb_alloc_folio (void *priv) +{ +struct guestmem_hugetlb_private *private = priv; +struct mempolicy *mpol; +struct folio *folio; +pgoff_t ilx; +int ret; + + ret =hugepage_subpool_get_pages (private->spool,1 ); +if (ret == -ENOMEM ) { +return ERR_PTR (-ENOMEM ); + }else if (ret >0 ) { +/* guest_memfd will not use surplus pages. */ + goto err_put_pages; + } + +/* +* TODO: mempolicy would probably have to be stored on the inode, use +* task policy for now. +*/ + mpol =get_task_policy (current); + +/* TODO: ignore interleaving for now. */ + ilx =NO_INTERLEAVE_INDEX ; + +/* +* charge_cgroup_rsvd is false because we already charged reservations +* when creating the subpool for this +* guest_memfd. use_existing_reservation is true - we're using a +* reservation from the guest_memfd's subpool. +*/ + folio =hugetlb_alloc_folio (private->h, mpol, ilx, false, true); +mpol_cond_put (mpol); + +if (IS_ERR_OR_NULL (folio)) + goto err_put_pages; + +/* +* Clear restore_reserve here so that when this folio is freed, +* free_huge_folio() will always attempt to return the reservation to +* the subpool. guest_memfd, unlike regular hugetlb, has no resv_map, +* and hence when freeing, the folio needs to be returned to the +* subpool. guest_memfd does not use surplus hugetlb pages, so in +* free_huge_folio(), returning to subpool will always succeed and the +* hstate reservation will then get restored. +* +* hugetlbfs does this in hugetlb_add_to_page_cache(). +*/ +folio_clear_hugetlb_restore_reserve (folio); + +hugetlb_set_folio_subpool (folio, private->spool); + +return folio; + +err_put_pages: +hugepage_subpool_put_pages (private->spool,1 ); +return ERR_PTR (-ENOMEM ); +} + +const struct guestmem_allocator_operations guestmem_hugetlb_ops = { + .inode_setup = guestmem_hugetlb_setup, + .inode_teardown = guestmem_hugetlb_teardown, + .alloc_folio = guestmem_hugetlb_alloc_folio, + .nr_pages_in_folio = guestmem_hugetlb_nr_pages_in_folio, +}; +EXPORT_SYMBOL_GPL (guestmem_hugetlb_ops);Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
Quoted 41 lines · Michael Roth
Quoted 18 lines · Ackerley Tng
[...snip...]
mm/guestmem_hugetlb.c +15
-0+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 ;mm/guestmem_hugetlb.c void guestmem_hugetlb_handle_folio_put(struct folio *folio) · line 61
Quoted 10 lines
mm/guestmem_hugetlb.c +10
-0+ 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.
Quoted 3 lines
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.
Quoted 37 lines
-Mike
Quoted 34 lines
mm/guestmem_hugetlb.c +31
-0+ + 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); +} +
Sean Christopherson
maintainerRe: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
In reply to Ackerley TngQuoted 11 lines · Ackerley Tng
guestmem_hugetlbis an allocator forguest_memfd. It wraps HugeTLB to provide huge folios forguest_memfd.This patch also introduces
guestmem_allocator_operationsas a set of operations that allocators forguest_memfdcan provide. In a later patch,guest_memfdwill use these operations to manage pages from an allocator.The allocator operations are memory-management specific and are placed in
mm/so key mm-specific functions do not have to be exposed unnecessarily.
This code doesn't have to be put in mm/, all of the #includes are to <linux/xxx.h>. Unless I'm missing something, what you actually want to avoid is _exporting_ mm/ APIs, and for that all that is needed is ensure the code is built-in to the kernel binary, not to kvm.ko.
virt/kvm/Makefile.kvm +2 -0
@@ -13,3 +13,5 @@ kvm-$(CONFIG_HAVE_KVM_IRQ_ROUTING) += $(KVM)/irqchip.o kvm-$(CONFIG_HAVE_KVM_DIRTY_RING) += $(KVM)/dirty_ring.o kvm-$(CONFIG_HAVE_KVM_PFNCACHE) += $(KVM)/pfncache.o kvm-$(CONFIG_KVM_GUEST_MEMFD) += $(KVM)/guest_memfd.o + +obj-$(subst m,y,$(CONFIG_KVM_GUEST_MEMFD)) += $(KVM)/guest_memfd_hugepages.o
People may want the code to live in mm/ for maintenance and ownership reasons (or not, I haven't followed the discussions on hugepage support), but that's a very different justification than what's described in the changelog.
And if the _only_ user is guest_memfd, putting this in mm/ feels quite weird. And if we anticipate other users, the name guestmem_hugetlb is weird, because AFAICT there's nothing in here that is in any way guest specific, it's just a few APIs for allocating and accounting hugepages.
Personally, I don't see much point in trying to make this a "generic" library, in quotes because the whole guestmem_xxx namespace makes it anything but generic. I don't see anything in mm/guestmem_hugetlb.c that makes me go "ooh, that's nasty, I'm glad this is handled by a library". But if we want to go straight to a library, it should be something that is really truly generic, i.e. not "guest" specific in any way.
Quoted 11 lines
Signed-off-by Ackerley Tng <[email protected]>Change-Id: I3cafe111ea7b3c84755d7112ff8f8c541c11136d
--- include/linux/guestmem.h | 20 +++++ include/uapi/linux/guestmem.h | 29 +++++++ mm/Kconfig | 5 +- mm/guestmem_hugetlb.c | 159 ++++++++++++++++++++++++++++++++++ 4 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 include/linux/guestmem.h create mode 100644 include/uapi/linux/guestmem.h
..
include/uapi/linux/guestmem.h
Quoted 5 lines
include/uapi/linux/guestmem.h new file +0
-0
With my KVM hat on, NAK to defining uAPI in a library like this. This subtly defines uAPI for KVM, and effectively any other userspace-facing entity that utilizes the library/allocator. KVM's uAPI needs to be defined by KVM, period.
There's absolutely zero reason to have guestmem_hugetlb_setup() take in flags. Explicitly pass the page size, or if preferred, the page_size_log, and let the caller figure out how to communicate the size to the kernel.
IMO, the whole MAP_HUGE_xxx approach is a (clever) hack to squeeze the desired size into mmap() flags. I don't see any reason to carry that forward to guest_memfd. For once, we had the foresight to reserve some space in KVM's uAPI structure, so there's no need to squeeze things into flags.
E.g. we could do something like this:
uapi/linux/kvm.h +6 -1
@@ -1605,11 +1605,16 @@ struct kvm_memory_attributes {#define KVM_CREATE_GUEST_MEMFD _IOWR(KVMIO, 0xd4, struct kvm_create_guest_memfd)#define GUEST_MEMFD_FLAG_MMAP (1ULL << 0)#define GUEST_MEMFD_FLAG_INIT_SHARED (1ULL << 1) +#define GUEST_MEMFD_FLAG_HUGE_PAGES (1ULL << 2)struct kvm_create_guest_memfd {__u64 size;__u64 flags; -__u64 reserved[6 ]; +__u8 huge_page_size_log2; +__u8 reserve8; +__u16 reserve16; +__u32 reserve32; +__u64 reserved[5 ]; };#define KVM_PRE_FAULT_MEMORY _IOWR(KVMIO, 0xd5, struct kvm_pre_fault_memory)
And not have to burn 6 bits of flags to encode the size in a weird location.
But that's a detail for KVM to sort out, which is exactly my point; how this is presented to userspace for guest_memfd is question for KVM.
Quoted 30 lines
include/uapi/linux/guestmem.h new file +29
-0@@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _UAPI_LINUX_GUESTMEM_H +#define _UAPI_LINUX_GUESTMEM_H + +/* +* Huge page size must be explicitly defined when using the guestmem_hugetlb +* allocator for guest_memfd. It is the responsibility of the application to +* know which sizes are supported on the running system. See mmap(2) man page +* for details. +*/ + +#define GUESTMEM_HUGETLB_FLAG_SHIFT 58 +#define GUESTMEM_HUGETLB_FLAG_MASK 0x3fUL + +#define GUESTMEM_HUGETLB_FLAG_16KB (14UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_64KB (16UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_512KB (19UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_1MB (20UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_2MB (21UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_8MB (23UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_16MB (24UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_32MB (25UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_256MB (28UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_512MB (29UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_1GB (30UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_2GB (31UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_16GB (34UL << GUESTMEM_HUGETLB_FLAG_SHIFT) + +#endif /* _UAPI_LINUX_GUESTMEM_H */
...
include/uapi/linux/guestmem.h
Quoted 7 lines
include/uapi/linux/guestmem.h new file +7
-0+const struct guestmem_allocator_operations guestmem_hugetlb_ops = { + .inode_setup = guestmem_hugetlb_setup, + .inode_teardown = guestmem_hugetlb_teardown, + .alloc_folio = guestmem_hugetlb_alloc_folio, + .nr_pages_in_folio = guestmem_hugetlb_nr_pages_in_folio, +}; +EXPORT_SYMBOL_GPL (guestmem_hugetlb_ops);
Why are these bundled into a structure? AFAICT, that adds layers of indirection for absolutely no reason. And especially on the KVM guest_memfd side, implementing a pile of infrastructure to support "custom" allocators is very premature. Without a second "custom" allocator, it's impossible to determine if the indirection provided is actually a good design. I.e. all of the kvm_gmem_has_custom_allocator() logic in guest_memfd.c is just HugeTLB logic buried behind a layer of unnecessary indirection.
Sean Christopherson
maintainerRe: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
Quoted 39 lines · Sean Christopherson
Quoted 11 lines · Ackerley Tng
guestmem_hugetlbis an allocator forguest_memfd. It wraps HugeTLB to provide huge folios forguest_memfd.This patch also introduces
guestmem_allocator_operationsas a set of operations that allocators forguest_memfdcan provide. In a later patch,guest_memfdwill use these operations to manage pages from an allocator.The allocator operations are memory-management specific and are placed in
mm/so key mm-specific functions do not have to be exposed unnecessarily.This code doesn't have to be put in
mm/, all of the #includes are to <linux/xxx.h>. Unless I'm missing something, what you actually want to avoid is _exporting_mm/APIs, and for that all that is needed is ensure the code is built-in to the kernel binary, not to kvm.ko.virt/kvm/Makefile.kvm +2
-0@@ -13,3 +13,5 @@ kvm-$(CONFIG_HAVE_KVM_IRQ_ROUTING) += $(KVM)/irqchip.o kvm-$(CONFIG_HAVE_KVM_DIRTY_RING) += $(KVM)/dirty_ring.o kvm-$(CONFIG_HAVE_KVM_PFNCACHE) += $(KVM)/pfncache.o kvm-$(CONFIG_KVM_GUEST_MEMFD) += $(KVM)/guest_memfd.o + +obj-$(subst m,y,$(CONFIG_KVM_GUEST_MEMFD)) += $(KVM)/guest_memfd_hugepages.oPeople may want the code to live in
mm/for maintenance and ownership reasons (or not, I haven't followed the discussions on hugepage support), but that's a very different justification than what's described in the changelog.And if the _only_ user is
guest_memfd, putting this inmm/feels quite weird. And if we anticipate other users, the nameguestmem_hugetlbis weird, because AFAICT there's nothing in here that is in any way guest specific, it's just a few APIs for allocating and accounting hugepages.
Quoted 6 lines
Personally, I don't see much point in trying to make this a "generic" library, in quotes because the whole
guestmem_xxxnamespace makes it anything but generic. I don't see anything inmm/guestmem_hugetlb.cthat makes me go "ooh, that's nasty, I'm glad this is handled by a library". But if we want to go straight to a library, it should be something that is really truly generic, i.e. not "guest" specific in any way.
Ah, the complexity and the mm-internal dependencies come along in the splitting and merging patch. Putting that code in mm/ makes perfect sense, but I'm still not convinced that putting _all_ of this code in mm/ is the correct split.
As proposed, this is a weird combination of being an extension of guest_memfd, a somewhat generic library, _and_ a subsystem (e.g. the global workqueue and stash).
_If_ we need a library, then IMO it should be a truly generic library. Any pieces that are guest_memfd specific belong in KVM. And any subsystem-like things should should probably be implemented as an extension to HugeTLB itself, which is already it's own subsytem. Emphasis on "if", because it's not clear to me that that a library is warranted.
AFAICT, the novelty here is the splitting and re-merging of hugetlb folios, and that seems like it should be explicitly an extension of the hugetlb subsystem. E.g. that behavior needs to take hugetlb_lock, interact with global vmemmap state like hugetlb_optimize_vmemmap_key, etc. If that's implemented as something like hugetlb_splittable.c or whatever, and wired up to be explicitly configured via hugetlb_init(), then there may not be much left for a library.
RFC PATCH v2 30/51 mm: truncate: Expose truncate_inode_folio()
In reply to Ackerley Tngguest_memfd will be using truncate_inode_folio() to remove folios from guest_memfd's filemap.
--- include/linux/mm.h | 1 + mm/guestmem_hugetlb.c | 2 +- mm/internal.h | 1 - mm/truncate.c | 1 + 4 files changed, 3 insertions(+), 2 deletions(-)
include/linux/mm.h +1 -0
@@ -2530,6 +2530,7 @@ extern void truncate_pagecache(struct inode *inode, loff_t new);extern void truncate_setsize (struct inode *inode,loff_t newsize);void pagecache_isize_extended (struct inode *inode,loff_t from,loff_t to);void truncate_pagecache_range (struct inode *inode,loff_t offset,loff_t end); +int truncate_inode_folio (struct address_space *mapping,struct folio *folio);int generic_error_remove_folio (struct address_space *mapping,struct folio *folio);
mm/guestmem_hugetlb.c +1 -1
@@ -4,12 +4,12 @@* as an allocator for guest_memfd. */ -#include <linux/mm_types.h> #include <linux/guestmem.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/mempolicy.h> #include <linux/mm.h> +#include <linux/mm_types.h> #include <linux/pagemap.h> #include <uapi/linux/guestmem.h>
mm/internal.h +0 -1
@@ -448,7 +448,6 @@ unsigned find_lock_entries(struct address_space *mapping, pgoff_t *start,unsigned find_get_entries (struct address_space *mapping,pgoff_t *start,pgoff_t end,struct folio_batch *fbatch,pgoff_t *indices);void filemap_free_folio (struct address_space *mapping,struct folio *folio); -int truncate_inode_folio (struct address_space *mapping,struct folio *folio);bool truncate_inode_partial_folio (struct folio *folio,loff_t start,loff_t end);long mapping_evict_folio (struct address_space *mapping,struct folio *folio);
mm/truncate.c +1 -0
@@ -176,6 +176,7 @@ int truncate_inode_folio(struct address_space *mapping, struct folio *folio)filemap_remove_folio (folio);return 0 ; } +EXPORT_SYMBOL_GPL (truncate_inode_folio);/* * Handle partial folios. The folio may be entirely within the
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 31/51 KVM: x86: Set disallow_lpage on base_gfn and guest_memfd pgoff misalignment
In reply to Ackerley TngWhen slot->base_gfn and userspace_addr are not aligned wrt each other, large page support is disabled for the entire memslot.
This patch applies the same logic for when slot->base_gfn and gmem.pgoff are not aligned wrt each other.
--- arch/x86/kvm/x86.c | 53 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 9 deletions(-)
arch/x86/kvm/x86.c +44 -9
@@ -12950,6 +12950,46 @@ int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)return 0 ; } +static inline bool kvm_is_level_aligned (u64 value,int level) +{ +return IS_ALIGNED (value,KVM_PAGES_PER_HPAGE (level)); +} + +static inline bool +kvm_should_allow_lpage_for_slot (struct kvm_memory_slot *slot,int level) +{ +bool gfn_and_userspace_addr_aligned; +unsigned long ugfn; + + ugfn = slot->userspace_addr >>PAGE_SHIFT ; + +/* +* If addresses are not aligned wrt each other, then large page mapping +* cannot be allowed for the slot since page tables only allow guest to +* host translations to function at fixed levels. +*/ + gfn_and_userspace_addr_aligned = +kvm_is_level_aligned (slot->base_gfn ^ ugfn, level); + +/* +* If slot->userspace_addr is 0 (disabled), 0 is always aligned so the +* check is deferred to gmem.pgoff. +*/ +if (!gfn_and_userspace_addr_aligned) +return false; + +if (kvm_slot_has_gmem (slot)) { +bool gfn_and_gmem_pgoff_aligned; + + gfn_and_gmem_pgoff_aligned =kvm_is_level_aligned ( + slot->base_gfn ^ slot->gmem.pgoff, level); + +return gfn_and_gmem_pgoff_aligned; + } + +return true; +} +static int kvm_alloc_memslot_metadata (struct kvm *kvm,struct kvm_memory_slot *slot) {
@@ -12971,7 +13011,6 @@ static int kvm_alloc_memslot_metadata(struct kvm *kvm,for (i =1 ; i <KVM_NR_PAGE_SIZES ; ++i) {struct kvm_lpage_info *linfo; -unsigned long ugfn;int lpages;int level = i +1 ;
@@ -12983,16 +13022,12 @@ static int kvm_alloc_memslot_metadata(struct kvm *kvm, slot->arch.lpage_info[i -1 ] = linfo; -if (slot->base_gfn & (KVM_PAGES_PER_HPAGE (level) -1 )) +if (!kvm_is_level_aligned (slot->base_gfn, level)) linfo[0 ].disallow_lpage =1 ; -if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE (level) -1 )) +if (!kvm_is_level_aligned (slot->base_gfn + npages, level)) linfo[lpages -1 ].disallow_lpage =1 ; - ugfn = slot->userspace_addr >>PAGE_SHIFT ; -/* -* If the gfn and userspace address are not aligned wrt each -* other, disable large page support for this slot. -*/ -if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE (level) -1 )) { + +if (!kvm_should_allow_lpage_for_slot (slot, level)) {unsigned long j;for (j =0 ; j < lpages; ++j)
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 32/51 KVM: guest_memfd: Support guestmem_hugetlb as custom allocator
In reply to Ackerley TngThis patch adds support for guestmem_hugetlb as the first custom allocator in guest_memfd.
If requested at guest_memfd creation time, the custom allocator will be used in initialization and cleanup.
Change-Id: I1eb9625dc761ecadcc2aa21480cfdfcf9ab7ce67
--- include/uapi/linux/kvm.h | 1 + virt/kvm/Kconfig | 5 + virt/kvm/guest_memfd.c | 203 +++++++++++++++++++++++++++++++++++++-- 3 files changed, 199 insertions(+), 10 deletions(-)
include/uapi/linux/kvm.h +1 -0
@@ -1571,6 +1571,7 @@ struct kvm_memory_attributes {#define GUEST_MEMFD_FLAG_SUPPORT_SHARED (1UL << 0)#define GUEST_MEMFD_FLAG_INIT_PRIVATE (1UL << 1) +#define GUEST_MEMFD_FLAG_HUGETLB (1UL << 2)struct kvm_create_guest_memfd {__u64 size;
virt/kvm/Kconfig +5 -0
@@ -133,3 +133,8 @@ config KVM_GMEM_SHARED_MEM select KVM_GMEM bool prompt "Enables in-place shared memory for guest_memfd" + +config KVM_GMEM_HUGETLB + select KVM_PRIVATE_MEM + depends on GUESTMEM_HUGETLB + bool "Enables using a custom allocator with guest_memfd, see CONFIG_GUESTMEM_HUGETLB"
virt/kvm/guest_memfd.c +193 -10
284 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 32/51] KVM: guest_memfd: Support guestmem_hugetlb as custom allocator
Quoted 10 lines · Ackerley Tng
enum shareability {
virt/kvm/guest_memfd.c +5
-0@@ -40,6 +47,44 @@ static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode)return inode->i_mapping->i_private_data; } +#ifdef CONFIG_KVM_GMEM_HUGETLB + +static const struct guestmem_allocator_operations * +kvm_gmem_allocator_ops (struct inode *inode) +{
virt/kvm/guest_memfd.c static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode) · line 64
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+return kvm_gmem_private (inode)->allocator_ops; +} + +static void *kvm_gmem_allocator_private (struct inode *inode) +{ +return kvm_gmem_private (inode)->allocator_private; +} + +static bool kvm_gmem_has_custom_allocator (struct inode *inode) +{
+ if (!kvm_gmem_private(inode))
+ return NULL;
Quoted 3 lines
virt/kvm/guest_memfd.c +3
-0+return kvm_gmem_allocator_ops (inode) !=NULL ; +} +
...
virt/kvm/guest_memfd.c static void kvm_gmem_destroy_inode(struct inode *inode) · line 1098
Quoted 5 lines
virt/kvm/guest_memfd.c +5
-0+static void kvm_gmem_evict_inode (struct inode *inode) +{ +truncate_inode_pages_final_prepare (inode->i_mapping); + +if (kvm_gmem_has_custom_allocator (inode)) {
The i_private_data of the root inode in pseudo fs is NULL. Without the two lines added above, evicting the root inode during unmount will cause NULL pointer deference.
Quoted 16 lines
virt/kvm/guest_memfd.c +11
-0+size_t nr_pages = inode->i_size >>PAGE_SHIFT ; + +kvm_gmem_truncate_inode_aligned_pages (inode,0 , nr_pages); + }else { +truncate_inode_pages (inode->i_mapping,0 ); + } + +clear_inode (inode); +} +static const struct super_operations kvm_gmem_super_operations = { .statfs = simple_statfs, + .evict_inode = kvm_gmem_evict_inode, .destroy_inode = kvm_gmem_destroy_inode, .free_inode = kvm_gmem_free_inode, };
Re: [RFC PATCH v2 32/51] KVM: guest_memfd: Support guestmem_hugetlb as custom allocator
In reply to Ackerley TngHi,
virt/kvm/Kconfig config KVM_GMEM_SHARED_MEM · line 140
Quoted 11 lines · Ackerley Tng
virt/kvm/Kconfig +5
-0@@ -133,3 +133,8 @@ config KVM_GMEM_SHARED_MEM select KVM_GMEM bool prompt "Enables in-place shared memory for guest_memfd" + +config KVM_GMEM_HUGETLB + select KVM_PRIVATE_MEM + depends on GUESTMEM_HUGETLB + bool "Enables using a custom allocator with guest_memfd, see CONFIG_GUESTMEM_HUGETLB"
For v3, this needs s/KVM_PRIVATE_MEM/KVM_GMEM/ assuming the patches are based on "KVM: Rename CONFIG_KVM_PRIVATE_MEM to CONFIG_KVM_GMEM".
Also probably good idea to run some make randconfig builds on the series to check the various Kconfig changes and inline functions for build errors.
Regards,
Tony
Re: [RFC PATCH v2 32/51] KVM: guest_memfd: Support guestmem_hugetlb as custom allocator
In reply to Ackerley TngTaking Sean's cue on trimming Cc list:
Quoted 15 lines · Ackerley Tng
This patch adds support for
guestmem_hugetlbas the first custom allocator inguest_memfd.If requested at
guest_memfdcreation time, the custom allocator will be used in initialization and cleanup.Signed-off-by Ackerley Tng <[email protected]>Change-Id: I1eb9625dc761ecadcc2aa21480cfdfcf9ab7ce67
--- include/uapi/linux/kvm.h | 1 + virt/kvm/Kconfig | 5 + virt/kvm/guest_memfd.c | 203 +++++++++++++++++++++++++++++++++++++-- 3 files changed, 199 insertions(+), 10 deletions(-)
<snip>
Quoted 5 lines
virt/kvm/guest_memfd.c +0
-1@@ -518,17 +562,24 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)if (!IS_ERR (folio))return folio; - gfp =mapping_gfp_mask (inode->i_mapping);
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index) · line 570
Quoted 10 lines
virt/kvm/guest_memfd.c +5
-4+if (kvm_gmem_has_custom_allocator (inode)) { +void *p =kvm_gmem_allocator_private (inode); -/* TODO: Support huge pages. */ - folio =filemap_alloc_folio (gfp,0 ); -if (!folio) -return ERR_PTR (-ENOMEM ); + folio =kvm_gmem_allocator_ops (inode)->alloc_folio (p); +if (IS_ERR (folio)) +return folio;
One issue with current guestmem_hugetlb implementation of ->alloc_folio() is that if you have 2 vCPUs faulting in the same GPA range, they might both attempt to reserve the allocation, and if they happen to be fighting over the last folio available in the subpool, then 1 of them might return ENOMEM and the guest will crash (this is much more likely if using 1GB pages).
It seems like we need to allow the allocator to return EAGAIN to signal that it's still worth retrying, but at the same time I'm not sure guestmem_hugetlb will be able to distinguish between *actually* being out of memory vs. a temporary situation like this. We can make guestmem_hugetlb smarter so that it could do this but it would need to track stuff like whether 2 allocations are in-flight for the same GPA range, and that's sounding a lot more like something guest_memfd proper should be doing.
There's also another potential/related issue below that I haven't run into but seems possible...
Quoted 9 lines
virt/kvm/guest_memfd.c +4
-4+ }else { +gfp_t gfp =mapping_gfp_mask (inode->i_mapping); - ret =mem_cgroup_charge (folio,NULL , gfp); -if (ret) { -folio_put (folio); -return ERR_PTR (ret); + folio =filemap_alloc_folio (gfp,0 ); +if (!folio)
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index) · line 585
Quoted 10 lines
virt/kvm/guest_memfd.c +7
-0+return ERR_PTR (-ENOMEM ); + + ret =mem_cgroup_charge (folio,NULL , gfp); +if (ret) { +folio_put (folio); +return ERR_PTR (ret); + } } ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index);
I think the relevant bits are in another patch, but it's closely related to the above scenario so I'll just paste it here for context:
ret = kvm_gmem_filemap_add_folio(inode->i_mapping, folio, index_floor);
if (ret) {
folio_put(folio);
/*
* There was a race, two threads tried to get a folio indexing
* to the same location in the filemap. The losing thread should
* free the allocated folio, then lock the folio added to the
* filemap by the winning thread.
*/
if (ret == -EEXIST)
goto repeat;
WARN_ON_ONCE(ret);
return ERR_PTR(ret);
}
/* Leave just filemap's refcounts on folio. */
folio_put(folio);
ret = kvm_gmem_try_split_folio_in_filemap(inode, folio);
if (ret)
goto err;
spin_lock(&inode->i_lock);
inode->i_blocks += allocated_size / 512;
spin_unlock(&inode->i_lock);
/*
* folio is the one that is allocated, this gets the folio at the
* requested index.
*/
folio = filemap_lock_folio(inode->i_mapping, index); Here you check for a similar race like the above (except the reservation doesn't fail so you get 2+ vCPUs with allocated folios they are trying to map), and the losing vCPUs are expected to free their un-filemapped folios and retry to get the winning/mapped one. However, later in this function you might end up splitting the winning page, which involves unmapping it beforehand, so with really bad timing it seems like a "losing" vCPU can still insert its folio in the filemap and trip up the splitting path, which I'm not sure is handled gracefully.
This is another case where I wish we had something like a range lock so we can still parallelize allocations with having vCPUs interleaving allocation/splitting work for a particular range. Lacking that, maybe some other locking scheme will work, but with allocation/splitting/HVO in the mix it would be pretty easy to kill performance if we're not careful.
-Mike
Quoted 187 lines
virt/kvm/guest_memfd.c +132
-0@@ -611,6 +662,80 @@ static void kvm_gmem_invalidate_end(struct kvm_gmem *gmem, pgoff_t start, } } +/** +* kvm_gmem_truncate_indices() - Truncates all folios beginning @index for +* @nr_pages. +* +* @mapping: filemap to truncate pages from. +* @index: the index in the filemap to begin truncation. +* @nr_pages: number of PAGE_SIZE pages to truncate. +* +* Return: the number of PAGE_SIZE pages that were actually truncated. +*/ +static long kvm_gmem_truncate_indices (struct address_space *mapping, +pgoff_t index,size_t nr_pages) +{ +struct folio_batch fbatch; +long truncated; +pgoff_t last; + + last = index + nr_pages -1 ; + + truncated =0 ; +folio_batch_init (&fbatch); +while (filemap_get_folios (mapping, &index, last, &fbatch)) { +unsigned int i; + +for (i =0 ; i <folio_batch_count (&fbatch); ++i) { +struct folio *f = fbatch.folios[i]; + + truncated +=folio_nr_pages (f); +folio_lock (f); +truncate_inode_folio (f->mapping, f); +folio_unlock (f); + } + +folio_batch_release (&fbatch); +cond_resched (); + } + +return truncated; +} + +/** +* kvm_gmem_truncate_inode_aligned_pages() - Removes entire folios from filemap +* in @inode. +* +* @inode: inode to remove folios from. +* @index: start of range to be truncated. Must be hugepage aligned. +* @nr_pages: number of PAGE_SIZE pages to be iterated over. +* +* Removes folios beginning @index for @nr_pages from filemap in @inode, updates +* inode metadata. +*/ +static void kvm_gmem_truncate_inode_aligned_pages (struct inode *inode, +pgoff_t index, +size_t nr_pages) +{ +size_t nr_per_huge_page; +long num_freed; +pgoff_t idx; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + num_freed =0 ; +for (idx = index; idx < index + nr_pages; idx += nr_per_huge_page) { + num_freed +=kvm_gmem_truncate_indices ( + inode->i_mapping, idx, nr_per_huge_page); + } + +spin_lock (&inode->i_lock); + inode->i_blocks -= (num_freed <<PAGE_SHIFT ) /512 ; +spin_unlock (&inode->i_lock); +} +static long kvm_gmem_punch_hole (struct inode *inode,loff_t offset,loff_t len) {struct list_head *gmem_list = &inode->i_mapping->i_private_list;@@ -940,6 +1065,13 @@ static void kvm_gmem_free_inode(struct inode *inode) {struct kvm_gmem_inode_private *private =kvm_gmem_private (inode); +/* private may be NULL if inode creation process had an error. */ +if (private &&kvm_gmem_has_custom_allocator (inode)) { +void *p =kvm_gmem_allocator_private (inode); + +kvm_gmem_allocator_ops (inode)->inode_teardown (p, inode->i_size); + } +kfree (private);free_inode_nonrcu (inode);@@ -959,8 +1091,24 @@ static void kvm_gmem_destroy_inode(struct inode *inode)#endif } +static void kvm_gmem_evict_inode (struct inode *inode) +{ +truncate_inode_pages_final_prepare (inode->i_mapping); + +if (kvm_gmem_has_custom_allocator (inode)) { +size_t nr_pages = inode->i_size >>PAGE_SHIFT ; + +kvm_gmem_truncate_inode_aligned_pages (inode,0 , nr_pages); + }else { +truncate_inode_pages (inode->i_mapping,0 ); + } + +clear_inode (inode); +} +static const struct super_operations kvm_gmem_super_operations = { .statfs = simple_statfs, + .evict_inode = kvm_gmem_evict_inode, .destroy_inode = kvm_gmem_destroy_inode, .free_inode = kvm_gmem_free_inode, };@@ -1062,6 +1210,12 @@ static void kvm_gmem_free_folio(struct folio *folio) {folio_clear_unevictable (folio); +/* +* No-op for 4K page since the PG_uptodate is cleared as part of +* freeing, but may be required for other allocators to reset page. +*/ +folio_clear_uptodate (folio); +kvm_gmem_invalidate (folio); }@@ -1115,6 +1269,25 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,if (err) goto out; +#ifdef CONFIG_KVM_GMEM_HUGETLB +if (flags &GUEST_MEMFD_FLAG_HUGETLB ) { +void *allocator_priv; +size_t nr_pages; + + allocator_priv = guestmem_hugetlb_ops.inode_setup (size, flags); +if (IS_ERR (allocator_priv)) { + err =PTR_ERR (allocator_priv); + goto out; + } + + private->allocator_ops = &guestmem_hugetlb_ops; + private->allocator_private = allocator_priv; + + nr_pages = guestmem_hugetlb_ops.nr_pages_in_folio (allocator_priv); + inode->i_blkbits =ilog2 (nr_pages <<PAGE_SHIFT ); + } +#endif + inode->i_private = (void *)(unsigned long )flags; inode->i_op = &kvm_gmem_iops; inode->i_mapping->a_ops = &kvm_gmem_aops;@@ -1210,6 +1383,10 @@ static int __kvm_gmem_create(struct kvm *kvm, loff_t size, u64 flags)return err; } +/* Mask of bits belonging to allocators and are opaque to guest_memfd. */ +#define SUPPORTED_CUSTOM_ALLOCATOR_MASK \ + (GUESTMEM_HUGETLB_FLAG_MASK << GUESTMEM_HUGETLB_FLAG_SHIFT) +int kvm_gmem_create (struct kvm *kvm,struct kvm_create_guest_memfd *args) {loff_t size = args->size;@@ -1222,6 +1399,12 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)if (flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED ) valid_flags |=GUEST_MEMFD_FLAG_INIT_PRIVATE ; +if (IS_ENABLED (CONFIG_KVM_GMEM_HUGETLB ) && + flags &GUEST_MEMFD_FLAG_HUGETLB ) { + valid_flags |=GUEST_MEMFD_FLAG_HUGETLB | +SUPPORTED_CUSTOM_ALLOCATOR_MASK ; + } +if (flags & ~valid_flags)return -EINVAL ;Signature · 1 line
2.49.0.1045.g170613ef41-goog
Sean Christopherson
maintainerRe: [RFC PATCH v2 32/51] KVM: guest_memfd: Support guestmem_hugetlb as custom allocator
In reply to Ackerley TngTrimmed the Cc to KVM/guest_memfd folks.
virt/kvm/guest_memfd.c struct kvm_gmem_inode_private { · line 31
Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +4
-0@@ -22,6 +25,10 @@ struct kvm_gmem_inode_private {#ifdef CONFIG_KVM_GMEM_SHARED_MEM struct maple_tree shareability;#endif +#ifdef CONFIG_KVM_GMEM_HUGETLB +const struct guestmem_allocator_operations *allocator_ops; +void *allocator_private; +#endif
This is beyond silly. There is _one_ "custom" allocator, and no evidence that the "generic" logic written for custom allocators would actually be correct for anything other than a hugetlb allocator.
And to my point about guestmem_hugetlb.c not actually needing access to "private" mm/ state, I would much rather add e.g. virt/kvm/guest_memfd_hugetlb.{c.h}, and in the header define:
struct gmem_hugetlb_inode {
struct hstate *h;
struct hugepage_subpool *spool;
struct hugetlb_cgroup *h_cg_rsvd;};
and then in guest_memfd.c have
struct gmem_inode {
struct shared_policy policy;
struct inode vfs_inode;
u64 flags;
struct maple_tree attributes;#ifdef CONFIG_KVM_GUEST_MEMFD_HUGETLB struct gmem_hugetlb_inode hugetlb;
#endif
};
or maybe even better, avoid even that "jump" and define "struct gmem_inode" in a new virt/kvm/guest_memfd.h:
struct gmem_inode {
struct shared_policy policy;
struct inode vfs_inode;
u64 flags;
struct maple_tree attributes;#ifdef CONFIG_KVM_GUEST_MEMFD_HUGETLB struct hstate *h; struct hugepage_subpool *spool; struct hugetlb_cgroup *h_cg_rsvd;
#endif
};
The setup code can them be:
#ifdef CONFIG_KVM_GUEST_MEMFD_HUGETLB
if (flags & GUEST_MEMFD_FLAG_HUGETLB) {
err = kvm_gmem_init_hugetlb(inode, size, huge_page_size_log2)
if (err)
goto out;
}#endif
Actually, if we're at all clever, the #ifdefs can go away completely so long as kvm_gmem_init_hugetlb() is uncondtionally _declared_, because we rely on dead code elimination to drop the call before linking.
virt/kvm/guest_memfd.c static void kvm_gmem_invalidate_end(struct kvm_gmem *gmem, pgoff_t start, · line 674
Quoted 11 lines
virt/kvm/guest_memfd.c +10
-0}; +/** +* kvm_gmem_truncate_indices() - Truncates all folios beginning @index for +* @nr_pages. +* +* @mapping: filemap to truncate pages from. +* @index: the index in the filemap to begin truncation. +* @nr_pages: number of PAGE_SIZE pages to truncate. +* +* Return: the number of PAGE_SIZE pages that were actually truncated. +*/
Do not add kerneldoc comments for internal helpers. They inevitably become stale and are a source of friction for developers. The _only_ non-obvious thing here is the return value.
Quoted 29 lines
virt/kvm/guest_memfd.c +29
-0+static long kvm_gmem_truncate_indices (struct address_space *mapping, +pgoff_t index,size_t nr_pages) +{ +struct folio_batch fbatch; +long truncated; +pgoff_t last; + + last = index + nr_pages -1 ; + + truncated =0 ; +folio_batch_init (&fbatch); +while (filemap_get_folios (mapping, &index, last, &fbatch)) { +unsigned int i; + +for (i =0 ; i <folio_batch_count (&fbatch); ++i) { +struct folio *f = fbatch.folios[i]; + + truncated +=folio_nr_pages (f); +folio_lock (f); +truncate_inode_folio (f->mapping, f); +folio_unlock (f); + } + +folio_batch_release (&fbatch); +cond_resched (); + } + +return truncated; +}
RFC PATCH v2 33/51 KVM: guest_memfd: Allocate and truncate from custom allocator
In reply to Ackerley TngIf a custom allocator is requested at guest_memfd creation time, pages from the custom allocator will be used to back guest_memfd.
--- mm/memory.c | 1 + virt/kvm/guest_memfd.c | 142 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 132 insertions(+), 11 deletions(-)
mm/memory.c +1 -0
@@ -7249,6 +7249,7 @@ void folio_zero_user(struct folio *folio, unsigned long addr_hint)else process_huge_page (addr_hint, nr_pages, clear_subpage, folio); } +EXPORT_SYMBOL_GPL (folio_zero_user); static int copy_user_gigantic_page(struct folio *dst, struct folio *src, unsigned long addr_hint,
virt/kvm/guest_memfd.c +131 -11
202 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator
Quoted 21 lines · Ackerley Tng
...
virt/kvm/guest_memfd.c +20
-0+/** +* kvm_gmem_zero_range() - Zeroes all sub-pages in range [@start, @end). +* +* @mapping: the filemap to remove this range from. +* @start: index in filemap for start of range (inclusive). +* @end: index in filemap for end of range (exclusive). +* +* The pages in range may be split. truncate_inode_pages_range() isn't the right +* function because it removes pages from the page cache; this function only +* zeroes the pages. +*/ +static void kvm_gmem_zero_range (struct address_space *mapping, +pgoff_t start,pgoff_t end) +{ +struct folio_batch fbatch; + +folio_batch_init (&fbatch); +while (filemap_get_folios (mapping, &start, end -1 , &fbatch)) { +unsigned int i; +
virt/kvm/guest_memfd.c static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode, · line 780
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+for (i =0 ; i <folio_batch_count (&fbatch); ++i) { +struct folio *f; +size_t nr_bytes; + + f = fbatch.folios[i]; + nr_bytes =offset_in_folio (f, end <<PAGE_SHIFT ); +if (nr_bytes ==0 ) + nr_bytes =folio_size (f); + +folio_zero_segment (f,0 , nr_bytes);
folio_zero_segment takes byte offset and number of bytes within the folio. This invocation needs to operate on the folio range that is overlapping with [Start, end) and instead it's always starting from 0 and ending at an unaligned offset within the folio. This will result in zeroing more than requested or lesser than requested or both depending on the request and folio size.
Quoted 7 lines
virt/kvm/guest_memfd.c +7
-0+ } + +folio_batch_release (&fbatch); +cond_resched (); + } +} +
Re: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator
In reply to Ackerley TngQuoted 5 lines · Ackerley Tng
If a custom allocator is requested at
guest_memfdcreation time, pages from the custom allocator will be used to backguest_memfd.Change-Id I59df960b3273790f42fe5bea54a234f40962eb75Signed-off-by Ackerley Tng <[email protected]>
I know it's an RFC, but for future maturity, these logs are pretty thin across the series. Only one sentence for 143 lines is way to limited.
Quoted 27 lines
--- mm/memory.c | 1 + virt/kvm/guest_memfd.c | 142 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 132 insertions(+), 11 deletions(-)mm/memory.c +1
-0@@ -7249,6 +7249,7 @@ void folio_zero_user(struct folio *folio, unsigned long addr_hint)else process_huge_page (addr_hint, nr_pages, clear_subpage, folio); } +EXPORT_SYMBOL_GPL (folio_zero_user); static int copy_user_gigantic_page(struct folio *dst, struct folio *src, unsigned long addr_hint,virt/kvm/guest_memfd.c +1
-1@@ -478,15 +478,13 @@ static inline void kvm_gmem_mark_prepared(struct folio *folio)* leaking host data and the up-to-date flag is set. */ static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, -gfn_t gfn,struct folio *folio) + gfn_t gfn, struct folio *folio,
virt/kvm/guest_memfd.c static inline void kvm_gmem_mark_prepared(struct folio *folio) · line 487
Quoted 10 lines
virt/kvm/guest_memfd.c +2
-4+ unsigned long addr_hint) { -unsigned long nr_pages, i;pgoff_t index;int r; - nr_pages =folio_nr_pages (folio); -for (i =0 ; i < nr_pages; i++) -clear_highpage (folio_page (folio, i)); +folio_zero_user (folio, addr_hint);
This is unrelated cleanup.
Quoted 104 lines
virt/kvm/guest_memfd.c +72
-2/* * Preparing huge folios should always be safe, since it should @@ -554,7 +552,9 @@ static int kvm_gmem_filemap_add_folio(struct address_space *mapping,*/ static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index) { +size_t allocated_size;struct folio *folio; +pgoff_t index_floor;int ret; repeat:@@ -581,8 +581,10 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } } + allocated_size =folio_size (folio); - ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index); + index_floor =round_down (index,folio_nr_pages (folio)); + ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index_floor);if (ret) {folio_put (folio);@@ -598,7 +600,17 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } -__folio_set_locked (folio); +spin_lock (&inode->i_lock); + inode->i_blocks += allocated_size /512 ; +spin_unlock (&inode->i_lock); + +/* +* folio is the one that is allocated, this gets the folio at the +* requested index. +*/ + folio =page_folio (folio_file_page (folio, index)); +folio_lock (folio); +return folio; }@@ -736,6 +748,92 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,spin_unlock (&inode->i_lock); } +/** +* kvm_gmem_zero_range() - Zeroes all sub-pages in range [@start, @end). +* +* @mapping: the filemap to remove this range from. +* @start: index in filemap for start of range (inclusive). +* @end: index in filemap for end of range (exclusive). +* +* The pages in range may be split. truncate_inode_pages_range() isn't the right +* function because it removes pages from the page cache; this function only +* zeroes the pages. +*/ +static void kvm_gmem_zero_range (struct address_space *mapping, +pgoff_t start,pgoff_t end) +{ +struct folio_batch fbatch; + +folio_batch_init (&fbatch); +while (filemap_get_folios (mapping, &start, end -1 , &fbatch)) { +unsigned int i; + +for (i =0 ; i <folio_batch_count (&fbatch); ++i) { +struct folio *f; +size_t nr_bytes; + + f = fbatch.folios[i]; + nr_bytes =offset_in_folio (f, end <<PAGE_SHIFT ); +if (nr_bytes ==0 ) + nr_bytes =folio_size (f); + +folio_zero_segment (f,0 , nr_bytes); + } + +folio_batch_release (&fbatch); +cond_resched (); + } +} + +/** +* kvm_gmem_truncate_inode_range() - Truncate pages in range [@lstart, @lend). +* +* @inode: inode to truncate from. +* @lstart: offset in inode for start of range (inclusive). +* @lend: offset in inode for end of range (exclusive). +* +* Removes full (huge)pages from the filemap and zeroing incomplete +* (huge)pages. The pages in the range may be split. +*/ +static void kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart, +loff_t lend) +{ +pgoff_t full_hpage_start; +size_t nr_per_huge_page; +pgoff_t full_hpage_end; +size_t nr_pages; +pgoff_t start; +pgoff_t end;
virt/kvm/guest_memfd.c static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode, · line 816
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+void *priv; + + priv =kvm_gmem_allocator_private (inode); + nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start = lstart >>PAGE_SHIFT ; + end =min (lend,i_size_read (inode)) >>PAGE_SHIFT ; + + full_hpage_start =round_up (start, nr_per_huge_page); + full_hpage_end =round_down (end, nr_per_huge_page);
I think it's supposed to zero the start at a byte granularity.
Quoted 5 lines
virt/kvm/guest_memfd.c +5
-0+ +if (start < full_hpage_start) { +pgoff_t zero_end =min (full_hpage_start, end); + +kvm_gmem_zero_range (inode->i_mapping, start, zero_end);
virt/kvm/guest_memfd.c static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode, · line 831
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ } + +if (full_hpage_end > full_hpage_start) { + nr_pages = full_hpage_end - full_hpage_start; +kvm_gmem_truncate_inode_aligned_pages (inode, full_hpage_start, + nr_pages); + } + +if (end > full_hpage_end && end > full_hpage_start) { +pgoff_t zero_start =max (full_hpage_end, start);
This is weird. Could it just round up end, then check it and use it instead?
Quoted 40 lines
virt/kvm/guest_memfd.c +21
-1+ +kvm_gmem_zero_range (inode->i_mapping, zero_start, end); + } +} +static long kvm_gmem_punch_hole (struct inode *inode,loff_t offset,loff_t len) {struct list_head *gmem_list = &inode->i_mapping->i_private_list;@@ -752,7 +850,12 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_begin (gmem, start, end); -truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 ); +if (kvm_gmem_has_custom_allocator (inode)) { +kvm_gmem_truncate_inode_range (inode, offset, offset + len); + }else { +/* Page size is PAGE_SIZE, so use optimized truncation function. */ +truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 ); + }list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_end (gmem, start, end);@@ -776,6 +879,16 @@ static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len) start = offset >>PAGE_SHIFT ; end = (offset + len) >>PAGE_SHIFT ; +if (kvm_gmem_has_custom_allocator (inode)) { +size_t nr_pages; +void *p; + + p =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (p); + + start =round_down (start, nr_pages); + end =round_down (end, nr_pages); + } r =0 ;for (index = start; index < end; ) {
virt/kvm/guest_memfd.c static struct folio *__kvm_gmem_get_pfn(struct file *file, · line 1686
Quoted 5 lines
virt/kvm/guest_memfd.c +1
-1@@ -1570,7 +1683,7 @@ static struct folio *__kvm_gmem_get_pfn(struct file *file, *pfn =folio_file_pfn (folio, index);if (max_order) - *max_order =0 ; + *max_order =folio_order (folio);
You might be able to have a separate patch that makes existing code work with larger folio sizes. Then add in the custom allocator/truncator bits in another one.
Quoted 5 lines
virt/kvm/guest_memfd.c +0
-0*is_prepared =folio_test_uptodate (folio);return folio;@@ -1597,8 +1710,15 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, goto out;
virt/kvm/guest_memfd.c int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 1718
Quoted 10 lines
virt/kvm/guest_memfd.c +6
-2} -if (!is_prepared) - r =kvm_gmem_prepare_folio (kvm, slot, gfn, folio); +if (!is_prepared) { +/* +* Use the same address as hugetlb for zeroing private pages +* that won't be mapped to userspace anyway. +*/ +unsigned long addr_hint = folio->index <<PAGE_SHIFT ;
This could use some more explanation.
Quoted 6 lines
virt/kvm/guest_memfd.c +3
-0+ + r =kvm_gmem_prepare_folio (kvm, slot, gfn, folio, addr_hint); + }folio_unlock (folio);
Re: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator
In reply to Ackerley TngQuoted 109 lines · Ackerley Tng
If a custom allocator is requested at
guest_memfdcreation time, pages from the custom allocator will be used to backguest_memfd.Change-Id I59df960b3273790f42fe5bea54a234f40962eb75Signed-off-by Ackerley Tng <[email protected]>--- mm/memory.c | 1 + virt/kvm/guest_memfd.c | 142 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 132 insertions(+), 11 deletions(-)mm/memory.c +1
-0@@ -7249,6 +7249,7 @@ void folio_zero_user(struct folio *folio, unsigned long addr_hint)else process_huge_page (addr_hint, nr_pages, clear_subpage, folio); } +EXPORT_SYMBOL_GPL (folio_zero_user); static int copy_user_gigantic_page(struct folio *dst, struct folio *src, unsigned long addr_hint,virt/kvm/guest_memfd.c +38
-7@@ -478,15 +478,13 @@ static inline void kvm_gmem_mark_prepared(struct folio *folio)* leaking host data and the up-to-date flag is set. */ static int kvm_gmem_prepare_folio (struct kvm *kvm,struct kvm_memory_slot *slot, -gfn_t gfn,struct folio *folio) +gfn_t gfn,struct folio *folio, +unsigned long addr_hint) { -unsigned long nr_pages, i;pgoff_t index;int r; - nr_pages =folio_nr_pages (folio); -for (i =0 ; i < nr_pages; i++) -clear_highpage (folio_page (folio, i)); +folio_zero_user (folio, addr_hint);/* * Preparing huge folios should always be safe, since it should @@ -554,7 +552,9 @@ static int kvm_gmem_filemap_add_folio(struct address_space *mapping,*/ static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index) { +size_t allocated_size;struct folio *folio; +pgoff_t index_floor;int ret; repeat:@@ -581,8 +581,10 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } } + allocated_size =folio_size (folio); - ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index); + index_floor =round_down (index,folio_nr_pages (folio)); + ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index_floor);if (ret) {folio_put (folio);@@ -598,7 +600,17 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } -__folio_set_locked (folio); +spin_lock (&inode->i_lock); + inode->i_blocks += allocated_size /512 ; +spin_unlock (&inode->i_lock); + +/* +* folio is the one that is allocated, this gets the folio at the +* requested index. +*/ + folio =page_folio (folio_file_page (folio, index)); +folio_lock (folio); +return folio; }@@ -736,6 +748,92 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,spin_unlock (&inode->i_lock); } +/** +* kvm_gmem_zero_range() - Zeroes all sub-pages in range [@start, @end). +* +* @mapping: the filemap to remove this range from. +* @start: index in filemap for start of range (inclusive). +* @end: index in filemap for end of range (exclusive). +* +* The pages in range may be split. truncate_inode_pages_range() isn't the right +* function because it removes pages from the page cache; this function only +* zeroes the pages. +*/ +static void kvm_gmem_zero_range (struct address_space *mapping, +pgoff_t start,pgoff_t end) +{ +struct folio_batch fbatch; + +folio_batch_init (&fbatch); +while (filemap_get_folios (mapping, &start, end -1 , &fbatch)) { +unsigned int i;
virt/kvm/guest_memfd.c static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode, · line 779
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ +for (i =0 ; i <folio_batch_count (&fbatch); ++i) { +struct folio *f; +size_t nr_bytes; + + f = fbatch.folios[i]; + nr_bytes =offset_in_folio (f, end <<PAGE_SHIFT ); +if (nr_bytes ==0 ) + nr_bytes =folio_size (f); +
Is folio_lock() required here?
Quoted 61 lines
virt/kvm/guest_memfd.c +57
-0+folio_zero_segment (f,0 , nr_bytes); + } + +folio_batch_release (&fbatch); +cond_resched (); + } +} + +/** +* kvm_gmem_truncate_inode_range() - Truncate pages in range [@lstart, @lend). +* +* @inode: inode to truncate from. +* @lstart: offset in inode for start of range (inclusive). +* @lend: offset in inode for end of range (exclusive). +* +* Removes full (huge)pages from the filemap and zeroing incomplete +* (huge)pages. The pages in the range may be split. +*/ +static void kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart, +loff_t lend) +{ +pgoff_t full_hpage_start; +size_t nr_per_huge_page; +pgoff_t full_hpage_end; +size_t nr_pages; +pgoff_t start; +pgoff_t end; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start = lstart >>PAGE_SHIFT ; + end =min (lend,i_size_read (inode)) >>PAGE_SHIFT ; + + full_hpage_start =round_up (start, nr_per_huge_page); + full_hpage_end =round_down (end, nr_per_huge_page); + +if (start < full_hpage_start) { +pgoff_t zero_end =min (full_hpage_start, end); + +kvm_gmem_zero_range (inode->i_mapping, start, zero_end); + } + +if (full_hpage_end > full_hpage_start) { + nr_pages = full_hpage_end - full_hpage_start; +kvm_gmem_truncate_inode_aligned_pages (inode, full_hpage_start, + nr_pages); + } + +if (end > full_hpage_end && end > full_hpage_start) { +pgoff_t zero_start =max (full_hpage_end, start); + +kvm_gmem_zero_range (inode->i_mapping, zero_start, end); + } +} +static long kvm_gmem_punch_hole (struct inode *inode,loff_t offset,loff_t len) {struct list_head *gmem_list = &inode->i_mapping->i_private_list;
virt/kvm/guest_memfd.c static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len) · line 851
Quoted 2 lines
virt/kvm/guest_memfd.c +0
-0@@ -752,7 +850,12 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_begin (gmem, start, end);
The kvm_gmem_punch_hole() can be triggered by user's madvise() operation, e.g.,
mem = mmap(NULL, test_page_size, PROT_READ | PROT_WRITE, MAP_SHARED, guest_memfd, 0); madvise(mem, test_page_size, MADV_REMOVE);
As the mmap'ed VA is only for shared memory, it seems that the madvise() on a VA range should only affect the shared memory. However, kvm_gmem_punch_hole() indiscriminately truncates or zeros any memory.
Quoted 57 lines
virt/kvm/guest_memfd.c +26
-4-truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 ); +if (kvm_gmem_has_custom_allocator (inode)) { +kvm_gmem_truncate_inode_range (inode, offset, offset + len); + }else { +/* Page size is PAGE_SIZE, so use optimized truncation function. */ +truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 ); + }list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_end (gmem, start, end);@@ -776,6 +879,16 @@ static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len) start = offset >>PAGE_SHIFT ; end = (offset + len) >>PAGE_SHIFT ; +if (kvm_gmem_has_custom_allocator (inode)) { +size_t nr_pages; +void *p; + + p =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (p); + + start =round_down (start, nr_pages); + end =round_down (end, nr_pages); + } r =0 ;for (index = start; index < end; ) {@@ -1570,7 +1683,7 @@ static struct folio *__kvm_gmem_get_pfn(struct file *file, *pfn =folio_file_pfn (folio, index);if (max_order) - *max_order =0 ; + *max_order =folio_order (folio); *is_prepared =folio_test_uptodate (folio);return folio;@@ -1597,8 +1710,15 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, goto out; } -if (!is_prepared) - r =kvm_gmem_prepare_folio (kvm, slot, gfn, folio); +if (!is_prepared) { +/* +* Use the same address as hugetlb for zeroing private pages +* that won't be mapped to userspace anyway. +*/ +unsigned long addr_hint = folio->index <<PAGE_SHIFT ; + + r =kvm_gmem_prepare_folio (kvm, slot, gfn, folio, addr_hint); + }folio_unlock (folio);Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator
In reply to Ackerley TngOn 5/15/2025 7:42 AM, Ackerley Tng wrote:
[...]
Quoted 6 lines
list_for_each_entry(gmem, gmem_list, entry) kvm_gmem_invalidate_end(gmem, start, end);virt/kvm/guest_memfd.c +0
-0@@ -776,6 +879,16 @@ static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len) start = offset >>PAGE_SHIFT ;
virt/kvm/guest_memfd.c static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len) · line 890
Quoted 10 lines
virt/kvm/guest_memfd.c +9
-0end = (offset + len) >>PAGE_SHIFT ; +if (kvm_gmem_has_custom_allocator (inode)) { +size_t nr_pages; +void *p; + + p =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (p); + + start =round_down (start, nr_pages); + end =round_down (end, nr_pages);
It's weird here.
Should the end be round_up()?
Quoted 5 lines
virt/kvm/guest_memfd.c +1
-0+ } r =0 ;for (index = start; index < end; ) {
[...]
Re: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator
Quoted 7 lines · Binbin Wu
On 5/15/2025 7:42 AM, Ackerley Tng wrote:
[...]Quoted 5 lines
list_for_each_entry(gmem, gmem_list, entry) kvm_gmem_invalidate_end(gmem, start, end);(quoted diff) +0
-0@@ -776,6 +879,16 @@ static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len)
Quoted 14 lines
virt/kvm/guest_memfd.c static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len) · line 890
Quoted 11 lines
virt/kvm/guest_memfd.c +9
-0start = offset >>PAGE_SHIFT ; end = (offset + len) >>PAGE_SHIFT ; +if (kvm_gmem_has_custom_allocator (inode)) { +size_t nr_pages; +void *p; + + p =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (p); + + start =round_down (start, nr_pages); + end =round_down (end, nr_pages);It's weird here.
Should the end beround_up()?
Thanks, you're right.
I believe the current consensus is that fallocate() will only be permitted for offset and lengths that are aligned not only to PAGE_SIZE but to allocator page size.
In a future revision I'll check for allocator page size earlier on, before this function will get called, so this rounding will probably go away.
Quoted 6 lines
Quoted 5 lines
virt/kvm/guest_memfd.c +1
-0+ } r =0 ;for (index = start; index < end; ) {[...]
Sean Christopherson
maintainerRe: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator
In reply to Ackerley TngTrimmed Cc to KVM/guest_memfd again.
Quoted 15 lines · Ackerley Tng
If a custom allocator is requested at
guest_memfdcreation time, pages from the custom allocator will be used to backguest_memfd.Change-Id I59df960b3273790f42fe5bea54a234f40962eb75Signed-off-by Ackerley Tng <[email protected]>--- mm/memory.c | 1 + virt/kvm/guest_memfd.c | 142 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 132 insertions(+), 11 deletions(-)mm/memory.c +0
-0
mm/memory.c void folio_zero_user(struct folio *folio, unsigned long addr_hint) · line 7252
Quoted 4 lines
mm/memory.c +1
-0@@ -7249,6 +7249,7 @@ void folio_zero_user(struct folio *folio, unsigned long addr_hint)else process_huge_page (addr_hint, nr_pages, clear_subpage, folio); } +EXPORT_SYMBOL_GPL (folio_zero_user);
This needs to be in a separate patch.
Quoted 12 lines
mm/memory.c +0
-0static int copy_user_gigantic_page(struct folio *dst, struct folio *src, unsigned long addr_hint,virt/kvm/guest_memfd.c +1
-1@@ -478,15 +478,13 @@ static inline void kvm_gmem_mark_prepared(struct folio *folio)* leaking host data and the up-to-date flag is set. */ static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, -gfn_t gfn,struct folio *folio) + gfn_t gfn, struct folio *folio,
virt/kvm/guest_memfd.c static inline void kvm_gmem_mark_prepared(struct folio *folio) · line 487
Quoted 10 lines
virt/kvm/guest_memfd.c +2
-4+ unsigned long addr_hint) { -unsigned long nr_pages, i;pgoff_t index;int r; - nr_pages =folio_nr_pages (folio); -for (i =0 ; i < nr_pages; i++) -clear_highpage (folio_page (folio, i)); +folio_zero_user (folio, addr_hint);
As does this.
Quoted 25 lines
virt/kvm/guest_memfd.c +5
-1/* * Preparing huge folios should always be safe, since it should @@ -554,7 +552,9 @@ static int kvm_gmem_filemap_add_folio(struct address_space *mapping,*/ static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index) { +size_t allocated_size;struct folio *folio; +pgoff_t index_floor;int ret; repeat:@@ -581,8 +581,10 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } } + allocated_size =folio_size (folio); - ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index); + index_floor =round_down (index,folio_nr_pages (folio)); + ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index_floor);if (ret) {folio_put (folio);
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index) · line 604
Quoted 6 lines
virt/kvm/guest_memfd.c +2
-1@@ -598,7 +600,17 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } -__folio_set_locked (folio); +spin_lock (&inode->i_lock); + inode->i_blocks += allocated_size /512 ;
??? If anything needs a comment, it's this.
Quoted 11 lines
virt/kvm/guest_memfd.c +9
-0+spin_unlock (&inode->i_lock); + +/* +* folio is the one that is allocated, this gets the folio at the +* requested index. +*/ + folio =page_folio (folio_file_page (folio, index)); +folio_lock (folio); +return folio; }
...
Quoted 9 lines
virt/kvm/guest_memfd.c +9
-0+static void kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart, +loff_t lend) +{ +pgoff_t full_hpage_start; +size_t nr_per_huge_page; +pgoff_t full_hpage_end; +size_t nr_pages; +pgoff_t start; +pgoff_t end;
virt/kvm/guest_memfd.c static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode, · line 816
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+void *priv; + + priv =kvm_gmem_allocator_private (inode); + nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start = lstart >>PAGE_SHIFT ; + end =min (lend,i_size_read (inode)) >>PAGE_SHIFT ; + + full_hpage_start =round_up (start, nr_per_huge_page); + full_hpage_end =round_down (end, nr_per_huge_page);
This is where the layer of indirection completely breaks down. This is blatantly specific to hugepages, but presented as if it's some generic logic.
Quoted 24 lines
virt/kvm/guest_memfd.c +20
-0+ +if (start < full_hpage_start) { +pgoff_t zero_end =min (full_hpage_start, end); + +kvm_gmem_zero_range (inode->i_mapping, start, zero_end); + } + +if (full_hpage_end > full_hpage_start) { + nr_pages = full_hpage_end - full_hpage_start; +kvm_gmem_truncate_inode_aligned_pages (inode, full_hpage_start, + nr_pages); + } + +if (end > full_hpage_end && end > full_hpage_start) { +pgoff_t zero_start =max (full_hpage_end, start); + +kvm_gmem_zero_range (inode->i_mapping, zero_start, end); + } +} +static long kvm_gmem_punch_hole (struct inode *inode,loff_t offset,loff_t len) {struct list_head *gmem_list = &inode->i_mapping->i_private_list;
virt/kvm/guest_memfd.c static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len) · line 856
Quoted 8 lines
virt/kvm/guest_memfd.c +4
-1@@ -752,7 +850,12 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_begin (gmem, start, end); -truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 ); +if (kvm_gmem_has_custom_allocator (inode)) { +kvm_gmem_truncate_inode_range (inode, offset, offset + len); + }else { +/* Page size is PAGE_SIZE, so use optimized truncation function. */
For cases like this, put the comment outside of the if-statement. Because what you're documenting isn't just the call to truncate_inode_pages_range(), it's the pivot on a "custom" allocator.
E.g. this should look more like:
/* Comment about why KVM needs custom code for hugetlb. */ if (kvm_gmem_is_hugetlb(inode)) kvm_gmem_truncate_inode_range(...); else truncate_inode_pages_range(...);
Quoted 9 lines
virt/kvm/guest_memfd.c +2
-0+truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 ); + }list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_end (gmem, start, end);@@ -776,6 +879,16 @@ static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len) start = offset >>PAGE_SHIFT ; end = (offset + len) >>PAGE_SHIFT ;
virt/kvm/guest_memfd.c static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len) · line 891
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+if (kvm_gmem_has_custom_allocator (inode)) { +size_t nr_pages; +void *p; + + p =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (p); + + start =round_down (start, nr_pages); + end =round_down (end, nr_pages); + }
This adds sooo much noise to a stupidly simple thing. The per-gmem page size is constant, just add gmem_inode.page_size and gmem_inode.page_shift then this becomes:
start = offset >> gi->page_shift; start = (offset + len) >> gi->page_shift;
We can do that even if we end up with a layer of indirection (which the more I look at this, the more I'm convinced that's completely unnecessary).
RFC PATCH v2 34/51 mm: hugetlb: Add functions to add/delete folio from hugetlb lists
In reply to Ackerley TngThese functions are introduced in hugetlb.c so the private hugetlb_lock can be accessed.
These functions will be used in splitting and merging pages in a later patch.
Change-Id: I42f8feda40cbd28e5fd02e54fa58145d847a220e
--- include/linux/hugetlb.h | 2 ++ mm/hugetlb.c | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+)
include/linux/hugetlb.h +2 -0
@@ -156,6 +156,8 @@ bool hugetlb_reserve_pages(struct inode *inode, long from, long to, vm_flags_t vm_flags);long hugetlb_unreserve_pages (struct inode *inode,long start,long end,long freed); +void hugetlb_folio_list_add (struct folio *folio,struct list_head *list); +void hugetlb_folio_list_del (struct folio *folio);bool folio_isolate_hugetlb (struct folio *folio,struct list_head *list);int get_hwpoison_hugetlb_folio (struct folio *folio,bool *hugetlb,bool unpoison); int get_huge_page_for_hwpoison(unsigned long pfn, int flags,
mm/hugetlb.c +22 -0
@@ -7473,6 +7473,28 @@ long hugetlb_unreserve_pages(struct inode *inode, long start, long end,return 0 ; } +void hugetlb_folio_list_add (struct folio *folio,struct list_head *list) +{ +/* +* hstate's hugepage_activelist is guarded by hugetlb_lock, hence hold +* hugetlb_lock while modifying folio-> lru. +*/ +spin_lock_irq (&hugetlb_lock); +list_add (&folio->lru, list); +spin_unlock_irq (&hugetlb_lock); +} + +void hugetlb_folio_list_del (struct folio *folio) +{ +/* +* hstate's hugepage_activelist is guarded by hugetlb_lock, hence hold +* hugetlb_lock while modifying folio-> lru. +*/ +spin_lock_irq (&hugetlb_lock); +list_del (&folio->lru); +spin_unlock_irq (&hugetlb_lock); +} +#ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING static unsigned long page_table_shareable(struct vm_area_struct *svma, struct vm_area_struct *vma,
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 35/51 mm: guestmem_hugetlb: Add support for splitting and merging pages
In reply to Ackerley TngThese functions allow guest_memfd to split and merge HugeTLB pages, and clean them up on freeing the page.
For merging and splitting pages on conversion, guestmem_hugetlb expects the refcount on the pages to already be 0. The caller must ensure that.
For conversions, guest_memfd ensures that the refcounts are already 0 by checking that there are no unexpected refcounts, and then freezing the expected refcounts away. On unexpected refcounts, guest_memfd will return an error to userspace.
For truncation, on unexpected refcounts, guest_memfd will return an error to userspace.
For truncation on closing, guest_memfd will just remove its own refcounts (the filemap refcounts) and mark split pages with PGTY_guestmem_hugetlb.
The presence of PGTY_guestmem_hugetlb will trigger the folio_put() callback to handle further cleanup. This cleanup process will merge pages (with refcount 0, since cleanup is triggered from folio_put()) before returning the pages to HugeTLB.
Since the merging process is long, it is deferred to a worker thread since folio_put() could be called from atomic context.
--- include/linux/guestmem.h | 3 + mm/guestmem_hugetlb.c | 349 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 347 insertions(+), 5 deletions(-)
include/linux/guestmem.h +3 -0
@@ -8,6 +8,9 @@ struct guestmem_allocator_operations {void *(*inode_setup)(size_t size,u64 flags);void (*inode_teardown)(void *private,size_t inode_size);struct folio *(*alloc_folio)(void *private); +int (*split_folio)(struct folio *folio); +void (*merge_folio)(struct folio *folio); +void (*free_folio)(struct folio *folio);/* * Returns the number of PAGE_SIZE pages in a page that this guestmem * allocator provides.
mm/guestmem_hugetlb.c +344 -5
375 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 35/51] mm: guestmem_hugetlb: Add support for splitting and merging pages
Quoted 199 lines · Ackerley Tng
These functions allow
guest_memfdto split and merge HugeTLB pages, and clean them up on freeing the page.For merging and splitting pages on conversion,
guestmem_hugetlbexpects the refcount on the pages to already be 0. The caller must ensure that.For conversions,
guest_memfdensures that the refcounts are already 0 by checking that there are no unexpected refcounts, and then freezing the expected refcounts away. On unexpected refcounts,guest_memfdwill return an error to userspace.For truncation, on unexpected refcounts,
guest_memfdwill return an error to userspace.For truncation on closing,
guest_memfdwill just remove its own refcounts (the filemap refcounts) and mark split pages withPGTY_guestmem_hugetlb.The presence of
PGTY_guestmem_hugetlbwill trigger thefolio_put()callback to handle further cleanup. This cleanup process will merge pages (with refcount 0, since cleanup is triggered fromfolio_put()) before returning the pages to HugeTLB.Since the merging process is long, it is deferred to a worker thread since
folio_put()could be called from atomic context.Change-Id Ib04a3236f1e7250fd9af827630c334d40fb09d40Signed-off-by Ackerley Tng <[email protected]>Co-developed-by Vishal Annapurve <[email protected]>Signed-off-by Vishal Annapurve <[email protected]>--- include/linux/guestmem.h | 3 + mm/guestmem_hugetlb.c | 349 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 347 insertions(+), 5 deletions(-)include/linux/guestmem.h +3
-0@@ -8,6 +8,9 @@ struct guestmem_allocator_operations {void *(*inode_setup)(size_t size,u64 flags);void (*inode_teardown)(void *private,size_t inode_size);struct folio *(*alloc_folio)(void *private); +int (*split_folio)(struct folio *folio); +void (*merge_folio)(struct folio *folio); +void (*free_folio)(struct folio *folio);/* * Returns the number of PAGE_SIZE pages in a page that this guestmem * allocator provides. mm/guestmem_hugetlb.c +125
-5@@ -11,15 +11,12 @@#include <linux/mm.h> #include <linux/mm_types.h> #include <linux/pagemap.h> +#include <linux/xarray.h> #include <uapi/linux/guestmem.h> #include "guestmem_hugetlb.h" - -void guestmem_hugetlb_handle_folio_put (struct folio *folio) -{ -WARN_ONCE (1 ,"A placeholder that shouldn't trigger. Work in progress." ); -} +#include "hugetlb_vmemmap.h" struct guestmem_hugetlb_private {struct hstate *h;@@ -34,6 +31,339 @@ static size_t guestmem_hugetlb_nr_pages_in_folio(void *priv)return pages_per_huge_page (private->h); } +static DEFINE_XARRAY (guestmem_hugetlb_stash); + +struct guestmem_hugetlb_metadata { +void *_hugetlb_subpool; +void *_hugetlb_cgroup; +void *_hugetlb_hwpoison; +void *private; +}; + +struct guestmem_hugetlb_stash_item { +struct guestmem_hugetlb_metadata hugetlb_metadata; +/* hstate tracks the original size of this folio. */ +struct hstate *h; +/* Count of split pages, individually freed, waiting to be merged. */ +atomic_t nr_pages_waiting_to_be_merged; +}; + +struct workqueue_struct *guestmem_hugetlb_wq__ro_after_init ; +static struct work_struct guestmem_hugetlb_cleanup_work; +static LLIST_HEAD (guestmem_hugetlb_cleanup_list); + +static inline void guestmem_hugetlb_register_folio_put_callback (struct folio *folio) +{ +__folio_set_guestmem_hugetlb (folio); +} + +static inline void guestmem_hugetlb_unregister_folio_put_callback (struct folio *folio) +{ +__folio_clear_guestmem_hugetlb (folio); +} + +static inline void guestmem_hugetlb_defer_cleanup (struct folio *folio) +{ +struct llist_node *node; + +/* +* Reuse the folio->mapping pointer as a struct llist_node, since +* folio->mapping is NULL at this point. +*/ +BUILD_BUG_ON (sizeof (folio->mapping) !=sizeof (struct llist_node )); + node = (struct llist_node *)&folio->mapping; + +/* +* Only schedule work if list is previously empty. Otherwise, +* schedule_work() had been called but the workfn hasn't retrieved the +* list yet. +*/ +if (llist_add (node, &guestmem_hugetlb_cleanup_list)) +queue_work (guestmem_hugetlb_wq, &guestmem_hugetlb_cleanup_work); +} + +void guestmem_hugetlb_handle_folio_put (struct folio *folio) +{ +guestmem_hugetlb_unregister_folio_put_callback (folio); + +/* +* folio_put() can be called in interrupt context, hence do the work +* outside of interrupt context +*/ +guestmem_hugetlb_defer_cleanup (folio); +} + +/* +* Stash existing hugetlb metadata. Use this function just before splitting a +* hugetlb page. +*/ +static inline void +__guestmem_hugetlb_stash_metadata (struct guestmem_hugetlb_metadata *metadata, +struct folio *folio) +{ +/* +* (folio->page + 1) doesn't have to be stashed since those fields are +* known on split/reconstruct and will be reinitialized anyway. +*/ + +/* +* subpool is created for every guest_memfd inode, but the folios will +* outlive the inode, hence we store the subpool here. +*/ + metadata->_hugetlb_subpool = folio->_hugetlb_subpool; +/* +* _hugetlb_cgroup has to be stored for freeing +* later. _hugetlb_cgroup_rsvd does not, since it is NULL for +* guest_memfd folios anyway. guest_memfd reservations are handled in +* the inode. +*/ + metadata->_hugetlb_cgroup = folio->_hugetlb_cgroup; + metadata->_hugetlb_hwpoison = folio->_hugetlb_hwpoison; + +/* +* HugeTLB flags are stored in folio->private. stash so that ->private +* can be used by core-mm. +*/ + metadata->private = folio->private; +} + +static int guestmem_hugetlb_stash_metadata (struct folio *folio) +{ +XA_STATE (xas, &guestmem_hugetlb_stash,0 ); +struct guestmem_hugetlb_stash_item *stash; +void *entry; + + stash =kzalloc (sizeof (*stash),1 ); +if (!stash) +return -ENOMEM ; + + stash->h =folio_hstate (folio); +__guestmem_hugetlb_stash_metadata (&stash->hugetlb_metadata, folio); + +xas_set_order (&xas,folio_pfn (folio),folio_order (folio)); + +xas_lock (&xas); + entry =xas_store (&xas, stash); +xas_unlock (&xas); + +if (xa_is_err (entry)) { +kfree (stash); +return xa_err (entry); + } + +return 0 ; +} +
mm/guestmem_hugetlb.c static size_t guestmem_hugetlb_nr_pages_in_folio(void *priv) · line 166
Quoted 10 lines
mm/guestmem_hugetlb.c +10
-0+static inline void +__guestmem_hugetlb_unstash_metadata (struct guestmem_hugetlb_metadata *metadata, +struct folio *folio) +{ + folio->_hugetlb_subpool = metadata->_hugetlb_subpool; + folio->_hugetlb_cgroup = metadata->_hugetlb_cgroup; + folio->_hugetlb_cgroup_rsvd =NULL ; + folio->_hugetlb_hwpoison = metadata->_hugetlb_hwpoison; + +folio_change_private (folio, metadata->private);
Hi Ackerley,
We've been doing some testing with this series on top of David's guestmemfd-preview branch with some SNP enablement[1][2] to exercise this code along with the NUMA support from Shivank (BTW, I know you have v3 in the works so let me know if we can help with testing that as well).
One issue we hit is if you do a split->merge sequence the unstash of the private data will result in folio_test_hugetlb_vmemmap_optimized() reporting true even though the hugetlb_vmemmap_optimize_folio() call hasn't been performed yet, and when that does get called it will be skipped, so some HVO optimization can be lost in this way.
More troublesome however is if you later split the folio again, hugetlb_vmemmap_restore_folio() may cause a BUG_ON() since the flags are in a state that's not consistent with the state of the folio/vmemmap.
The following patch seems to resolve the issue but I'm not sure what the best approach would be:
https://github.com/AMDESE/linux/commit/b1f25956f18d32730b8d4ded6d77e980091eb4d3
Thanks,
Mike
[1] https://github.com/AMDESE/linux/commits/snp-hugetlb-v2-wip0/
[2] https://github.com/AMDESE/qemu/tree/snp-hugetlb-dev-wip0
Re: [RFC PATCH v2 35/51] mm: guestmem_hugetlb: Add support for splitting and merging pages
Quoted 5 lines · Michael Roth
Quoted 3 lines · Ackerley Tng
[...snip...]
Quoted 8 lines
Hi Ackerley,
We've been doing some testing with this series on top of David's guestmemfd-preview branch with some SNP enablement[1][2] to exercise this code along with the NUMA support from Shivank (BTW, I know you have v3 in the works so let me know if we can help with testing that as well).
Thank you for offering! I'm quite backed up now with some internal work. Will definitely appreciate all the help I can get once I manage to push out an RFCv3!
Quoted 6 lines
One issue we hit is if you do a
split->mergesequence the unstash of the private data will result infolio_test_hugetlb_vmemmap_optimized()reporting true even though thehugetlb_vmemmap_optimize_folio()call hasn't been performed yet, and when that does get called it will be skipped, so some HVO optimization can be lost in this way.
Quoted 9 lines
More troublesome however is if you later split the folio again,
hugetlb_vmemmap_restore_folio()may cause aBUG_ON()since the flags are in a state that's not consistent with the state of the folio/vmemmap.The following patch seems to resolve the issue but I'm not sure what the best approach would be:
https://github.com/AMDESE/linux/commit/b1f25956f18d32730b8d4ded6d77e980091eb4d3
I saw your reply on the other thread. Thanks for informing me :)
Quoted 6 lines
Thanks,
Mike
[1] https://github.com/AMDESE/linux/commits/snp-hugetlb-v2-wip0/
[2] https://github.com/AMDESE/qemu/tree/snp-hugetlb-dev-wip0
Sean Christopherson
maintainerRe: [RFC PATCH v2 35/51] mm: guestmem_hugetlb: Add support for splitting and merging pages
In reply to Ackerley Tngmm/guestmem_hugetlb.c static struct folio *guestmem_hugetlb_alloc_folio(void *priv) · line 512
Quoted 10 lines · Ackerley Tng
const struct
guestmem_allocator_operationsguestmem_hugetlb_ops= {mm/guestmem_hugetlb.c +3
-0.inode_setup = guestmem_hugetlb_setup, .inode_teardown = guestmem_hugetlb_teardown, .alloc_folio = guestmem_hugetlb_alloc_folio, + .split_folio = guestmem_hugetlb_split_folio, + .merge_folio = guestmem_hugetlb_merge_folio, + .free_folio = guestmem_hugetlb_free_folio, .nr_pages_in_folio = guestmem_hugetlb_nr_pages_in_folio, };EXPORT_SYMBOL_GPL (guestmem_hugetlb_ops);
Don't bury exports in an "ops" like this. Be very explicit in what is exported. _If_ KVM needs a layer of indirection to support multiple, custom guest_memfd allocators, then KVM can wire up ops as above. Indirectly exporting core mm/ functionality via an ops structure like this is unnecessarily sneaky.
RFC PATCH v2 36/51 mm: Convert split_folio() macro to function
In reply to Ackerley TngThis will prevent the macro from overriding any function and function calls defined as split_folio().
--- include/linux/huge_mm.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
include/linux/huge_mm.h +5 -1
@@ -99,7 +99,11 @@ extern struct kobj_attribute thpsize_shmem_enabled_attr;#define thp_vma_allowable_order (vma, vm_flags, tva_flags, order) \ (!!thp_vma_allowable_orders(vma, vm_flags, tva_flags, BIT(order))) -#define split_folio (f) split_folio_to_list(f, NULL) +int split_folio_to_list (struct folio *folio,struct list_head *list); +static inline int split_folio (struct folio *folio) +{ +return split_folio_to_list (folio,NULL ); +}#ifdef CONFIG_PGTABLE_HAS_HUGE_LEAVES #define HPAGE_PMD_SHIFT PMD_SHIFT
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 36/51] mm: Convert split_folio() macro to function
Quoted 1 line · Ackerley Tng
+int
split_folio_to_list(struct folio *folio, struct list_head *list);
With CONFIG_TRANSPARENT_HUGEPAGE=n, I get:
include/linux/huge_mm.h:569:19: error: static declaration of ‘split_folio_to_list’ follows non-static declaration
569 | static inline int split_folio_to_list(struct folio *folio, structlist_head *list)
| ^~~~~~~~~~~~~~~~~~~
include/linux/huge_mm.h:102:5: note: previous declaration of ‘split_folio_to_list’ with type ‘int(struct folio *, struct list_head *)’
102 | int split_folio_to_list(struct folio *folio, struct list_head *list);
Quoted 5 lines
include/linux/huge_mm.h +4
-0+static inline int split_folio (struct folio *folio) +{ +return split_folio_to_list (folio,NULL ); +}
RFC PATCH v2 37/51 filemap: Pass address_space mapping to ->free_folio()
In reply to Ackerley TngFrom: Elliot Berman <[email protected]>
The plan is to be able to support multiple allocators for guest_memfd folios. To allow each allocator to handle release of a folio from a guest_memfd filemap, ->free_folio() needs to retrieve allocator information that is stored on the guest_memfd inode.
->free_folio() shouldn't assume that folio->mapping is set/valid, and the mapping is well-known to callers of .free_folio(). Hence, pass address_space mapping to ->free_folio() for the callback to retrieve any necessary information.
--- Documentation/filesystems/locking.rst | 2 +- Documentation/filesystems/vfs.rst | 15 +++++++++------ fs/nfs/dir.c | 9 +++++++-- fs/orangefs/inode.c | 3 ++- include/linux/fs.h | 2 +- mm/filemap.c | 9 +++++---- mm/secretmem.c | 3 ++- mm/vmscan.c | 4 ++-- virt/kvm/guest_memfd.c | 3 ++- 9 files changed, 31 insertions(+), 19 deletions(-)
Documentation/filesystems/locking.rst +1 -1
@@ -263,7 +263,7 @@ prototypes:: sector_t (*bmap)(struct address_space *, sector_t); void (*invalidate_folio) (struct folio *, size_t start, size_t len); bool (*release_folio)(struct folio *, gfp_t); - void (*free_folio)(struct folio *); + void (*free_folio)(struct address_space *, struct folio *); int (*direct_IO)(struct kiocb *, struct iov_iter *iter); int (*migrate_folio)(struct address_space *, struct folio *dst, struct folio *src, enum migrate_mode);
Documentation/filesystems/vfs.rst +9 -6
@@ -833,7 +833,7 @@ cache in your filesystem. The following members are defined: sector_t (*bmap)(struct address_space *, sector_t); void (*invalidate_folio) (struct folio *, size_t start, size_t len); bool (*release_folio)(struct folio *, gfp_t); - void (*free_folio)(struct folio *); + void (*free_folio)(struct address_space *, struct folio *); ssize_t (*direct_IO)(struct kiocb *, struct iov_iter *iter); int (*migrate_folio)(struct mapping *, struct folio *dst, struct folio *src, enum migrate_mode);
@@ -1011,11 +1011,14 @@ cache in your filesystem. The following members are defined: clear the uptodate flag if it cannot free private data yet. ``free_folio`` - free_folio is called once the folio is no longer visible in the - page cache in order to allow the cleanup of any private data. - Since it may be called by the memory reclaimer, it should not - assume that the original address_space mapping still exists, and - it should not block. + free_folio is called once the folio is no longer visible in + the page cache in order to allow the cleanup of any private + data. Since it may be called by the memory reclaimer, it + should not assume that the original address_space mapping + still exists at folio->mapping. The mapping the folio used to + belong to is instead passed for free_folio to read any + information it might need from the mapping. free_folio should + not block. ``direct_IO`` called by the generic read/write routines to perform direct_IO -
fs/nfs/dir.c +7 -2
@@ -55,7 +55,7 @@ static int nfs_closedir(struct inode *, struct file *);static int nfs_readdir (struct file *,struct dir_context *);static int nfs_fsync_dir (struct file *,loff_t ,loff_t ,int );static loff_t nfs_llseek_dir (struct file *,loff_t ,int ); -static void nfs_readdir_clear_array (struct folio *); +static void nfs_free_folio (struct address_space *,struct folio *);static int nfs_do_create (struct inode *dir,struct dentry *dentry,umode_t mode,int open_flags);
@@ -69,7 +69,7 @@ const struct file_operations nfs_dir_operations = { };const struct address_space_operations nfs_dir_aops = { - .free_folio = nfs_readdir_clear_array, + .free_folio = nfs_free_folio, };#define NFS_INIT_DTSIZE PAGE_SIZE
@@ -230,6 +230,11 @@ static void nfs_readdir_clear_array(struct folio *folio)kunmap_local (array); } +static void nfs_free_folio (struct address_space *mapping,struct folio *folio) +{ +nfs_readdir_clear_array (folio); +} +static void nfs_readdir_folio_reinit_array (struct folio *folio,u64 last_cookie,u64 change_attr) {
fs/orangefs/inode.c +2 -1
@@ -449,7 +449,8 @@ static bool orangefs_release_folio(struct folio *folio, gfp_t foo)return !folio_test_private (folio); } -static void orangefs_free_folio (struct folio *folio) +static void orangefs_free_folio (struct address_space *mapping, +struct folio *folio) {kfree (folio_detach_private (folio)); }
include/linux/fs.h +1 -1
@@ -455,7 +455,7 @@ struct address_space_operations {sector_t (*bmap)(struct address_space *,sector_t );void (*invalidate_folio) (struct folio *,size_t offset,size_t len);bool (*release_folio)(struct folio *,gfp_t ); -void (*free_folio)(struct folio *folio); +void (*free_folio)(struct address_space *mapping,struct folio *folio);ssize_t (*direct_IO)(struct kiocb *,struct iov_iter *iter);/* * migrate the contents of a folio to the specified target. If
mm/filemap.c +5 -4
@@ -226,11 +226,11 @@ void __filemap_remove_folio(struct folio *folio, void *shadow)void filemap_free_folio (struct address_space *mapping,struct folio *folio) { -void (*free_folio)(struct folio *); +void (*free_folio)(struct address_space *,struct folio *); free_folio = mapping->a_ops->free_folio;if (free_folio) -free_folio (folio); +free_folio (mapping, folio);folio_put_refs (folio,folio_nr_pages (folio)); }
@@ -820,7 +820,8 @@ EXPORT_SYMBOL(file_write_and_wait_range);void replace_page_cache_folio (struct folio *old,struct folio *new) {struct address_space *mapping = old->mapping; -void (*free_folio)(struct folio *) = mapping->a_ops->free_folio; +void (*free_folio)(struct address_space *,struct folio *) = + mapping->a_ops->free_folio;pgoff_t offset = old->index;XA_STATE (xas, &mapping->i_pages, offset);
@@ -849,7 +850,7 @@ void replace_page_cache_folio(struct folio *old, struct folio *new)__lruvec_stat_add_folio (new,NR_SHMEM );xas_unlock_irq (&xas);if (free_folio) -free_folio (old); +free_folio (mapping, old);folio_put (old); }EXPORT_SYMBOL_GPL (replace_page_cache_folio);
mm/secretmem.c +2 -1
@@ -152,7 +152,8 @@ static int secretmem_migrate_folio(struct address_space *mapping,return -EBUSY ; } -static void secretmem_free_folio (struct folio *folio) +static void secretmem_free_folio (struct address_space *mapping, +struct folio *folio) {set_direct_map_default_noflush (&folio->page);folio_zero_segment (folio,0 ,folio_size (folio));
mm/vmscan.c +2 -2
@@ -788,7 +788,7 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio,xa_unlock_irq (&mapping->i_pages);put_swap_folio (folio, swap); }else { -void (*free_folio)(struct folio *); +void (*free_folio)(struct address_space *,struct folio *); free_folio = mapping->a_ops->free_folio;/*
@@ -817,7 +817,7 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio,spin_unlock (&mapping->host->i_lock);if (free_folio) -free_folio (folio); +free_folio (mapping, folio); }return 1 ;
virt/kvm/guest_memfd.c +2 -1
@@ -1319,7 +1319,8 @@ static void kvm_gmem_invalidate(struct folio *folio)static inline void kvm_gmem_invalidate (struct folio *folio) {}#endif -static void kvm_gmem_free_folio (struct folio *folio) +static void kvm_gmem_free_folio (struct address_space *mapping, +struct folio *folio) {folio_clear_unevictable (folio);
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 38/51 KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Ackerley TngIn this patch, newly allocated pages are split to 4K regular pages before providing them to the requester (fallocate() or KVM).
During a private to shared conversion, folios are split if not already split.
During a shared to private conversion, folios are merged if not already merged.
When the folios are removed from the filemap on truncation, the allocator is given a chance to do any necessary prep for when the folio is freed.
When a conversion is requested on a subfolio within a hugepage range, faulting must be prevented on the whole hugepage range for correctness.
See related discussion at
https://lore.kernel.org/all/[email protected]/T/
--- mm/filemap.c | 2 + virt/kvm/guest_memfd.c | 501 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 483 insertions(+), 20 deletions(-)
mm/filemap.c +2 -0
@@ -223,6 +223,7 @@ void __filemap_remove_folio(struct folio *folio, void *shadow)filemap_unaccount_folio (mapping, folio);page_cache_delete (mapping, folio, shadow); } +EXPORT_SYMBOL_GPL (__filemap_remove_folio);void filemap_free_folio (struct address_space *mapping,struct folio *folio) {
@@ -258,6 +259,7 @@ void filemap_remove_folio(struct folio *folio)filemap_free_folio (mapping, folio); } +EXPORT_SYMBOL_GPL (filemap_remove_folio);/* * page_cache_delete_batch - delete several folios from page cache
virt/kvm/guest_memfd.c +481 -20
632 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349
Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8
-0+ +static pgoff_t kvm_gmem_compute_invalidate_bound (struct inode *inode, +pgoff_t bound,bool start) +{ +size_t nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode))
General comment - It's a bit unfortunate how kvm_gmem_has_custom_allocator() is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic in guest_memfd.c.
Did you consider designing struct guestmem_allocator_operations so that it could encapsulate the special logic for both the existing and new allocators? If it didn't work well, could we expect that a next allocator would actually fit struct guestmem_allocator_operations?
Quoted 23 lines
virt/kvm/guest_memfd.c +23
-0+return bound; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (start) +return round_down (bound, nr_pages); +else +return round_up (bound, nr_pages); +} + +static pgoff_t kvm_gmem_compute_invalidate_start (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, true); +} + +static pgoff_t kvm_gmem_compute_invalidate_end (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, false); +} +
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
Quoted 15 lines · Rick P
virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349
Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8
-0+ +static pgoff_t kvm_gmem_compute_invalidate_bound (struct inode *inode, +pgoff_t bound,bool start) +{ +size_t nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode))General comment - It's a bit unfortunate how
kvm_gmem_has_custom_allocator()is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic inguest_memfd.c.
Quoted 3 lines
Did you consider designing struct
guestmem_allocator_operationsso that it could encapsulate the special logic for both the existing and new allocators?
I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.
I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.
Quoted 4 lines
If it
didn't work well, could we expect that a next allocator would actually fit structguestmem_allocator_operations?
This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.
Quoted 23 lines
Quoted 23 lines
virt/kvm/guest_memfd.c +23
-0+return bound; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (start) +return round_down (bound, nr_pages); +else +return round_up (bound, nr_pages); +} + +static pgoff_t kvm_gmem_compute_invalidate_start (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, true); +} + +static pgoff_t kvm_gmem_compute_invalidate_end (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, false); +} +
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
Quoted 10 lines · Ackerley Tng
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Did you consider designing struct
guestmem_allocator_operationsso that > > > > it > > could
encapsulate the special logic for both the existing and new allocators?I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.
I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.
Usually new work should handle the refactor first, then build on top of it. The code today bolts on a new thing in a dirty way leaving cleanup.
Towards also expedient reviewability, a better order could be:
1. Add allocator callbacks one at a time (or in whatever granularity is possible), moving 4k allocator to callbacks at the same time. Basically a code move. Don't factor out common code between the planned allocators. Will be dirt simple to review.
2. Introduce changes to hugelbfs, explaining why each will be used by guestmemfd
3. Add hugetlbsfs/1GB custom allocator to guestmemfd code, a callback at a time. Have any necessary factoring out of 4k page allocator bits out of the callback implementation come in a separate preceding patch. Explain the commonality.
What do you think?
Also, for (2) do you think you could move some of these pure cleanup patches out of the series to go up ahead of time? And for any hugetlb changes that 1GB guestmemfd depends on, explain why in the log? I'm not clear what is required and what is opportunistic cleanup.
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
If it
didn't work well, could we expect that a next allocator would actually > > > > fit
structguestmem_allocator_operations?This was definitely designed to support allocators beyond
guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.
Makes sense. This was probing on whether the interface didn't fit the 4k allocator. It makes sense to have the interface target the existing 2 allocators, and no future ideas.
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Edgecombe, Rick PQuoted 15 lines · Rick P
virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349
Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8
-0+ +static pgoff_t kvm_gmem_compute_invalidate_bound (struct inode *inode, +pgoff_t bound,bool start) +{ +size_t nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode))General comment - It's a bit unfortunate how
kvm_gmem_has_custom_allocator()is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic inguest_memfd.c.
Quoted 3 lines
Did you consider designing struct
guestmem_allocator_operationsso that it could encapsulate the special logic for both the existing and new allocators?
I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.
I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.
Quoted 4 lines
If it
didn't work well, could we expect that a next allocator would actually fit structguestmem_allocator_operations?
This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.
Quoted 23 lines
Quoted 23 lines
virt/kvm/guest_memfd.c +23
-0+return bound; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (start) +return round_down (bound, nr_pages); +else +return round_up (bound, nr_pages); +} + +static pgoff_t kvm_gmem_compute_invalidate_start (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, true); +} + +static pgoff_t kvm_gmem_compute_invalidate_end (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, false); +} +
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Edgecombe, Rick PQuoted 15 lines · Rick P
virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349
Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8
-0+ +static pgoff_t kvm_gmem_compute_invalidate_bound (struct inode *inode, +pgoff_t bound,bool start) +{ +size_t nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode))General comment - It's a bit unfortunate how
kvm_gmem_has_custom_allocator()is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic inguest_memfd.c.
Quoted 3 lines
Did you consider designing struct
guestmem_allocator_operationsso that it could encapsulate the special logic for both the existing and new allocators?
I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.
I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.
Quoted 4 lines
If it
didn't work well, could we expect that a next allocator would actually fit structguestmem_allocator_operations?
This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.
Quoted 23 lines
Quoted 23 lines
virt/kvm/guest_memfd.c +23
-0+return bound; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (start) +return round_down (bound, nr_pages); +else +return round_up (bound, nr_pages); +} + +static pgoff_t kvm_gmem_compute_invalidate_start (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, true); +} + +static pgoff_t kvm_gmem_compute_invalidate_end (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, false); +} +
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Edgecombe, Rick PQuoted 15 lines · Rick P
virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349
Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8
-0+ +static pgoff_t kvm_gmem_compute_invalidate_bound (struct inode *inode, +pgoff_t bound,bool start) +{ +size_t nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode))General comment - It's a bit unfortunate how
kvm_gmem_has_custom_allocator()is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic inguest_memfd.c.
Quoted 3 lines
Did you consider designing struct
guestmem_allocator_operationsso that it could encapsulate the special logic for both the existing and new allocators?
I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.
I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.
Quoted 4 lines
If it
didn't work well, could we expect that a next allocator would actually fit structguestmem_allocator_operations?
This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.
Quoted 23 lines
Quoted 23 lines
virt/kvm/guest_memfd.c +23
-0+return bound; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (start) +return round_down (bound, nr_pages); +else +return round_up (bound, nr_pages); +} + +static pgoff_t kvm_gmem_compute_invalidate_start (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, true); +} + +static pgoff_t kvm_gmem_compute_invalidate_end (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, false); +} +
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Edgecombe, Rick PQuoted 15 lines · Rick P
virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349
Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8
-0+ +static pgoff_t kvm_gmem_compute_invalidate_bound (struct inode *inode, +pgoff_t bound,bool start) +{ +size_t nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode))General comment - It's a bit unfortunate how
kvm_gmem_has_custom_allocator()is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic inguest_memfd.c.
Quoted 3 lines
Did you consider designing struct
guestmem_allocator_operationsso that it could encapsulate the special logic for both the existing and new allocators?
I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.
I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.
Quoted 4 lines
If it
didn't work well, could we expect that a next allocator would actually fit structguestmem_allocator_operations?
This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.
Quoted 23 lines
Quoted 23 lines
virt/kvm/guest_memfd.c +23
-0+return bound; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (start) +return round_down (bound, nr_pages); +else +return round_up (bound, nr_pages); +} + +static pgoff_t kvm_gmem_compute_invalidate_start (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, true); +} + +static pgoff_t kvm_gmem_compute_invalidate_end (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, false); +} +
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Ackerley TngQuoted 206 lines · Ackerley Tng
In this patch, newly allocated pages are split to 4K regular pages before providing them to the requester (
fallocate()or KVM).During a private to shared conversion, folios are split if not already split.
During a shared to private conversion, folios are merged if not already merged.
When the folios are removed from the filemap on truncation, the allocator is given a chance to do any necessary prep for when the folio is freed.
When a conversion is requested on a subfolio within a hugepage range, faulting must be prevented on the whole hugepage range for correctness.
See related discussion at
https://lore.kernel.org/all/[email protected]/T/Signed-off-by Ackerley Tng <[email protected]>Co-developed-by Vishal Annapurve <[email protected]>Signed-off-by Vishal Annapurve <[email protected]>Change-Id Ib5ee22e3dae034c529773048a626ad98d4b10af3--- mm/filemap.c | 2 + virt/kvm/guest_memfd.c | 501 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 483 insertions(+), 20 deletions(-)mm/filemap.c +2
-0@@ -223,6 +223,7 @@ void __filemap_remove_folio(struct folio *folio, void *shadow)filemap_unaccount_folio (mapping, folio);page_cache_delete (mapping, folio, shadow); } +EXPORT_SYMBOL_GPL (__filemap_remove_folio);void filemap_free_folio (struct address_space *mapping,struct folio *folio) {@@ -258,6 +259,7 @@ void filemap_remove_folio(struct folio *folio)filemap_free_folio (mapping, folio); } +EXPORT_SYMBOL_GPL (filemap_remove_folio);/* * page_cache_delete_batch - delete several folios from page cache virt/kvm/guest_memfd.c +128
-0@@ -41,6 +41,11 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start, pgoff_t end);static void kvm_gmem_invalidate_end (struct kvm_gmem *gmem,pgoff_t start,pgoff_t end); +static int __kvm_gmem_filemap_add_folio (struct address_space *mapping, +struct folio *folio,pgoff_t index); +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation);static struct kvm_gmem_inode_private *kvm_gmem_private (struct inode *inode) {@@ -126,6 +131,31 @@ static enum shareability kvm_gmem_shareability_get(struct inode *inode,return xa_to_value (entry); } +static bool kvm_gmem_shareability_in_range (struct inode *inode,pgoff_t start, +size_t nr_pages,enum shareability m) +{ +struct maple_tree *mt; +pgoff_t last; +void *entry; + + mt = &kvm_gmem_private (inode)->shareability; + + last = start + nr_pages -1 ; +mt_for_each (mt, entry, start, last) { +if (xa_to_value (entry) == m) +return true; + } + +return false; +} + +static inline bool kvm_gmem_has_some_shared (struct inode *inode,pgoff_t start, +size_t nr_pages) +{ +return kvm_gmem_shareability_in_range (inode, start, nr_pages, +SHAREABILITY_ALL ); +} +static struct folio *kvm_gmem_get_shared_folio (struct inode *inode,pgoff_t index) {if (kvm_gmem_shareability_get (inode, index) !=SHAREABILITY_ALL )@@ -241,6 +271,105 @@ static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t streturn refcount_safe; } +static void kvm_gmem_unmap_private (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end) +{ +struct kvm_memory_slot *slot; +struct kvm *kvm = gmem->kvm; +unsigned long index; +bool locked = false; +bool flush = false; + +xa_for_each_range (&gmem->bindings, index, slot, start, end -1 ) { +pgoff_t pgoff = slot->gmem.pgoff; + +struct kvm_gfn_range gfn_range = { + .start = slot->base_gfn +max (pgoff, start) - pgoff, + .end = slot->base_gfn +min (pgoff + slot->npages, end) - pgoff, + .slot = slot, + .may_block = true, +/* This function is only concerned with private mappings. */ + .attr_filter =KVM_FILTER_PRIVATE , + }; + +if (!locked) { +KVM_MMU_LOCK (kvm); + locked = true; + } + + flush |=kvm_mmu_unmap_gfn_range (kvm, &gfn_range); + } + +if (flush) +kvm_flush_remote_tlbs (kvm); + +if (locked) +KVM_MMU_UNLOCK (kvm); +} + +static void kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end) +{ +struct kvm_memory_slot *slot; +struct kvm *kvm = gmem->kvm; +unsigned long index; +bool found_memslot; + + found_memslot = false; +xa_for_each_range (&gmem->bindings, index, slot, start, end -1 ) { +gfn_t gfn_start; +gfn_t gfn_end; +pgoff_t pgoff; + + pgoff = slot->gmem.pgoff; + + gfn_start = slot->base_gfn +max (pgoff, start) - pgoff; + gfn_end = slot->base_gfn +min (pgoff + slot->npages, end) - pgoff; +if (!found_memslot) { + found_memslot = true; + +KVM_MMU_LOCK (kvm); +kvm_mmu_invalidate_begin (kvm); + } + +kvm_mmu_invalidate_range_add (kvm, gfn_start, gfn_end); + } + +if (found_memslot) +KVM_MMU_UNLOCK (kvm); +} + +static pgoff_t kvm_gmem_compute_invalidate_bound (struct inode *inode, +pgoff_t bound,bool start) +{ +size_t nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return bound; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (start) +return round_down (bound, nr_pages); +else +return round_up (bound, nr_pages); +} + +static pgoff_t kvm_gmem_compute_invalidate_start (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, true); +} + +static pgoff_t kvm_gmem_compute_invalidate_end (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, false); +} +static int kvm_gmem_shareability_apply (struct inode *inode,struct conversion_work *work,enum shareability m)@@ -299,35 +428,53 @@ static void kvm_gmem_convert_invalidate_begin(struct inode *inode, struct conversion_work *work) {struct list_head *gmem_list;
virt/kvm/guest_memfd.c static void kvm_gmem_convert_invalidate_begin(struct inode *inode, · line 438
Quoted 10 lines
virt/kvm/guest_memfd.c +6
-2+pgoff_t invalidate_start; +pgoff_t invalidate_end;struct kvm_gmem *gmem; -pgoff_t end; +pgoff_t work_end; - end = work->start + work->nr_pages; + work_end = work->start + work->nr_pages; + invalidate_start =kvm_gmem_compute_invalidate_start (inode, work->start); + invalidate_end =kvm_gmem_compute_invalidate_end (inode, work_end);
Could we just notify the exact gfn range and let KVM adjust the invalidate range?
Then kvm_gmem_invalidate_begin() can asks KVM to do EPT splitting before any kvm_mmu_unmap_gfn_range() is performed.
Quoted 211 lines
virt/kvm/guest_memfd.c +154
-9gmem_list = &inode->i_mapping->i_private_list;list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_begin (gmem, work->start, end); +kvm_gmem_invalidate_begin (gmem, invalidate_start, invalidate_end); }static void kvm_gmem_convert_invalidate_end (struct inode *inode,struct conversion_work *work) {struct list_head *gmem_list; +pgoff_t invalidate_start; +pgoff_t invalidate_end;struct kvm_gmem *gmem; -pgoff_t end; +pgoff_t work_end; - end = work->start + work->nr_pages; + work_end = work->start + work->nr_pages; + invalidate_start =kvm_gmem_compute_invalidate_start (inode, work->start); + invalidate_end =kvm_gmem_compute_invalidate_end (inode, work_end); gmem_list = &inode->i_mapping->i_private_list;list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_end (gmem, work->start, end); +kvm_gmem_invalidate_end (gmem, invalidate_start, invalidate_end); }static int kvm_gmem_convert_should_proceed (struct inode *inode,struct conversion_work *work,bool to_shared,pgoff_t *error_index) { -if (!to_shared) { +if (to_shared) { +struct list_head *gmem_list; +struct kvm_gmem *gmem; +pgoff_t work_end; + + work_end = work->start + work->nr_pages; + + gmem_list = &inode->i_mapping->i_private_list; +list_for_each_entry (gmem, gmem_list, entry) +kvm_gmem_unmap_private (gmem, work->start, work_end); + }else {unmap_mapping_pages (inode->i_mapping, work->start, work->nr_pages, false);@@ -340,6 +487,27 @@ static int kvm_gmem_convert_should_proceed(struct inode *inode,return 0 ; } +static int kvm_gmem_convert_execute_work (struct inode *inode, +struct conversion_work *work, +bool to_shared) +{ +enum shareability m; +int ret; + + m = to_shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +return ret; +/* +* Apply shareability first so split/merge can operate on new +* shareability state. +*/ + ret =kvm_gmem_restructure_folios_in_range ( + inode, work->start, work->nr_pages, to_shared); + +return ret; +} +static int kvm_gmem_convert_range (struct file *file,pgoff_t start,size_t nr_pages,bool shared,pgoff_t *error_index)@@ -371,18 +539,21 @@ static int kvm_gmem_convert_range(struct file *file, pgoff_t start,list_for_each_entry (work, &work_list, list) { rollback_stop_item = work; - ret =kvm_gmem_shareability_apply (inode, work, m); + + ret =kvm_gmem_convert_execute_work (inode, work, shared);if (ret)break ; }if (ret) { - m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ;list_for_each_entry (work, &work_list, list) { +int r; + + r =kvm_gmem_convert_execute_work (inode, work, !shared); +WARN_ON (r); +if (work == rollback_stop_item)break ; - -WARN_ON (kvm_gmem_shareability_apply (inode, work, m)); } }@@ -434,6 +605,277 @@ static int kvm_gmem_ioctl_convert_range(struct file *file,return ret; } +#ifdef CONFIG_KVM_GMEM_HUGETLB + +static inline void __filemap_remove_folio_for_restructuring (struct folio *folio) +{ +struct address_space *mapping = folio->mapping; + +spin_lock (&mapping->host->i_lock); +xa_lock_irq (&mapping->i_pages); + +__filemap_remove_folio (folio,NULL ); + +xa_unlock_irq (&mapping->i_pages); +spin_unlock (&mapping->host->i_lock); +} + +/** +* filemap_remove_folio_for_restructuring() - Remove @folio from filemap for +* split/merge. +* +* @folio: the folio to be removed. +* +* Similar to filemap_remove_folio(), but skips LRU-related calls (meaningless +* for guest_memfd), and skips call to ->free_folio() to maintain folio flags. +* +* Context: Expects only the filemap's refcounts to be left on the folio. Will +* freeze these refcounts away so that no other users will interfere +* with restructuring. +*/ +static inline void filemap_remove_folio_for_restructuring (struct folio *folio) +{ +int filemap_refcount; + + filemap_refcount =folio_nr_pages (folio); +while (!folio_ref_freeze (folio, filemap_refcount)) { +/* +* At this point only filemap refcounts are expected, hence okay +* to spin until speculative refcounts go away. +*/ +WARN_ONCE (1 ,"Spinning on folio=%p refcount=%d" , folio,folio_ref_count (folio)); + } + +folio_lock (folio); +__filemap_remove_folio_for_restructuring (folio); +folio_unlock (folio); +} + +/** +* kvm_gmem_split_folio_in_filemap() - Split @folio within filemap in @inode. +* +* @inode: inode containing the folio. +* @folio: folio to be split. +* +* Split a folio into folios of size PAGE_SIZE. Will clean up folio from filemap +* and add back the split folios. +* +* Context: Expects that before this call, folio's refcount is just the +* filemap's refcounts. After this function returns, the split folios' +* refcounts will also be filemap's refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_split_folio_in_filemap (struct inode *inode,struct folio *folio) +{ +size_t orig_nr_pages; +pgoff_t orig_index; +size_t i, j; +int ret; + + orig_nr_pages =folio_nr_pages (folio); +if (orig_nr_pages ==1 ) +return 0 ; + + orig_index = folio->index; + +filemap_remove_folio_for_restructuring (folio); + + ret =kvm_gmem_allocator_ops (inode)->split_folio (folio); +if (ret) + goto err; + +for (i =0 ; i < orig_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (folio, i)); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, f, + orig_index + i); +if (ret) + goto rollback; + } + +return ret; + +rollback: +for (j =0 ; j < i; ++j) { +struct folio *f =page_folio (folio_page (folio, j)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (folio); +err: +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, folio, orig_index)); + +return ret; +} + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 724
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+size_t to_nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); + +if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages))
If the guest_memfd is configured with GUESTMEM_HUGETLB_FLAG_1GB, it seems that whenever there's a shared page within a 1GB range, the folio will always be split into 4KB folios. Is it good?
Quoted 99 lines
virt/kvm/guest_memfd.c +99
-0+return kvm_gmem_split_folio_in_filemap (inode, folio); + +return 0 ; +} + +/** +* kvm_gmem_merge_folio_in_filemap() - Merge @first_folio within filemap in +* @inode. +* +* @inode: inode containing the folio. +* @first_folio: first folio among folios to be merged. +* +* Will clean up subfolios from filemap and add back the merged folio. +* +* Context: Expects that before this call, all subfolios only have filemap +* refcounts. After this function returns, the merged folio will only +* have filemap refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +pgoff_t index; +void *priv; +size_t i; +int ret; + + index = first_folio->index; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); +if (folio_nr_pages (first_folio) == to_nr_pages) +return 0 ; + +for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (first_folio); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, first_folio, index); +if (ret) + goto err_split; + +return ret; + +err_split: +WARN_ON (kvm_gmem_allocator_ops (inode)->split_folio (first_folio)); +for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, f, index + i)); + } + +return ret; +} + +static inline int kvm_gmem_try_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (kvm_gmem_has_some_shared (inode, first_folio->index, to_nr_pages)) +return 0 ; + +return kvm_gmem_merge_folio_in_filemap (inode, first_folio); +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +size_t to_nr_pages; +pgoff_t index; +pgoff_t end; +void *priv; +int ret; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + end = start + nr_pages; + +/* Round to allocator page size, to check all (huge) pages in range. */ + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start =round_down (start, to_nr_pages); + end =round_up (end, to_nr_pages); + +for (index = start; index < end; index += to_nr_pages) { +struct folio *f;
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) + ret =kvm_gmem_split_folio_in_filemap (inode, f);
The split operation is performed after kvm_gmem_unmap_private() within kvm_gmem_convert_should_proceed(), right?
So, it seems that that it's not necessary for TDX to avoid holding private page references, as TDX must have released the page refs after kvm_gmem_unmap_private() (except when there's TDX module or KVM bug).
Quoted 155 lines
virt/kvm/guest_memfd.c +73
-9+ else + ret =kvm_gmem_try_merge_folio_in_filemap (inode, f); + +if (ret) + goto rollback; + } +return ret; + +rollback: +for (index -= to_nr_pages; index >= start; index -= to_nr_pages) { +struct folio *f; + + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); +else +WARN_ON (kvm_gmem_split_folio_in_filemap (inode, f)); + } + +return ret; +} + +#else + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +return 0 ; +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +return 0 ; +} + +#endif +#else static int kvm_gmem_shareability_setup (struct maple_tree *mt,loff_t size,u64 flags)@@ -563,11 +1005,16 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return folio;if (kvm_gmem_has_custom_allocator (inode)) { -void *p =kvm_gmem_allocator_private (inode); +size_t nr_pages; +void *p; + p =kvm_gmem_allocator_private (inode); folio =kvm_gmem_allocator_ops (inode)->alloc_folio (p);if (IS_ERR (folio))return folio; + + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (p); + index_floor =round_down (index, nr_pages); }else {gfp_t gfp =mapping_gfp_mask (inode->i_mapping);@@ -580,10 +1027,11 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)folio_put (folio);return ERR_PTR (ret); } + + index_floor = index; } allocated_size =folio_size (folio); - index_floor =round_down (index,folio_nr_pages (folio)); ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index_floor);if (ret) {folio_put (folio);@@ -600,6 +1048,13 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } +/* Leave just filemap's refcounts on folio. */ +folio_put (folio); + + ret =kvm_gmem_try_split_folio_in_filemap (inode, folio); +if (ret) + goto err; +spin_lock (&inode->i_lock); inode->i_blocks += allocated_size /512 ;spin_unlock (&inode->i_lock);@@ -608,14 +1063,17 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)* folio is the one that is allocated, this gets the folio at the * requested index. */ - folio =page_folio (folio_file_page (folio, index)); -folio_lock (folio); + folio =filemap_lock_folio (inode->i_mapping, index);return folio; + +err: +filemap_remove_folio (folio); +return ERR_PTR (ret); } -static void kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, -pgoff_t end) +static void kvm_gmem_invalidate_begin_and_zap (struct kvm_gmem *gmem, +pgoff_t start,pgoff_t end) {bool flush = false, found_memslot = false;struct kvm_memory_slot *slot;@@ -848,7 +1306,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)filemap_invalidate_lock (inode->i_mapping);list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_begin (gmem, start, end); +kvm_gmem_invalidate_begin_and_zap (gmem, start, end);if (kvm_gmem_has_custom_allocator (inode)) {kvm_gmem_truncate_inode_range (inode, offset, offset + len);@@ -978,7 +1436,7 @@ static int kvm_gmem_release(struct inode *inode, struct file *file)* Zap all SPTEs pointed at by this file. Do not free the backing * memory, as its lifetime is associated with the inode, not the file. */ -kvm_gmem_invalidate_begin (gmem,0 ,-1ul ); +kvm_gmem_invalidate_begin_and_zap (gmem,0 ,-1ul );kvm_gmem_invalidate_end (gmem,0 ,-1ul );list_del (&gmem->entry);@@ -1289,7 +1747,7 @@ static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol end = start +folio_nr_pages (folio);list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_begin (gmem, start, end); +kvm_gmem_invalidate_begin_and_zap (gmem, start, end);/* * Do not truncate the range, what action is taken in response to the @@ -1330,6 +1788,9 @@ static void kvm_gmem_free_folio(struct address_space *mapping,*/ folio_clear_uptodate (folio); +if (kvm_gmem_has_custom_allocator (mapping->host)) +kvm_gmem_allocator_ops (mapping->host)->free_folio (folio); +kvm_gmem_invalidate (folio); }Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
Quoted 37 lines
Quoted 24 lines
virt/kvm/guest_memfd.c +24
-0+static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +size_t to_nr_pages; +pgoff_t index; +pgoff_t end; +void *priv; +int ret; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + end = start + nr_pages; + +/* Round to allocator page size, to check all (huge) pages in range. */ + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start =round_down (start, to_nr_pages); + end =round_up (end, to_nr_pages); + +for (index = start; index < end; index += to_nr_pages) { +struct folio *f;virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) + ret =kvm_gmem_split_folio_in_filemap (inode, f);The split operation is performed after
kvm_gmem_unmap_private()withinkvm_gmem_convert_should_proceed(), right?
Quoted 3 lines
So, it seems that that it's not necessary for TDX to avoid holding private page references, as TDX must have released the page refs after
kvm_gmem_unmap_private()(except when there's TDX module or KVM bug).
Oops. Please ignore this one.
The unmap does not necessarily cover the entire folio range, so split still requires TDX not to hold ref count.
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Yan ZhaoQuoted 1 line · Yan Zhao
On Wed, May 14, 2025 at 04:42:17PM -0700, Ackerley Tng wrote:
[...]
Quoted 43 lines
Quoted 43 lines
virt/kvm/guest_memfd.c +33
-1+static pgoff_t kvm_gmem_compute_invalidate_bound (struct inode *inode, +pgoff_t bound,bool start) +{ +size_t nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return bound; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (start) +return round_down (bound, nr_pages); +else +return round_up (bound, nr_pages); +} + +static pgoff_t kvm_gmem_compute_invalidate_start (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, true); +} + +static pgoff_t kvm_gmem_compute_invalidate_end (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, false); +} +static int kvm_gmem_shareability_apply (struct inode *inode,struct conversion_work *work,enum shareability m)@@ -299,35 +428,53 @@ static void kvm_gmem_convert_invalidate_begin(struct inode *inode, struct conversion_work *work) {struct list_head *gmem_list; +pgoff_t invalidate_start; +pgoff_t invalidate_end;struct kvm_gmem *gmem; -pgoff_t end; +pgoff_t work_end;
Quoted 4 lines
virt/kvm/guest_memfd.c static void kvm_gmem_convert_invalidate_begin(struct inode *inode, · line 438
Quoted 4 lines
virt/kvm/guest_memfd.c +3
-1- end = work->start + work->nr_pages; + work_end = work->start + work->nr_pages; + invalidate_start =kvm_gmem_compute_invalidate_start (inode, work->start); + invalidate_end =kvm_gmem_compute_invalidate_end (inode, work_end);
The invalidation range is broadened to include the full range to take care of this race [1] reported for the conversion flow that uses KVM_SET_MEMORY_ATTRIBUTES ioctl, so I also repeated the broadening for this guest_memfd conversion ioctl.
Quoted 3 lines
Could we just notify the exact gfn range and let KVM adjust the invalidate range?
How do we get KVM to adjust the invalidate range?
Quoted 4 lines
Then
kvm_gmem_invalidate_begin()can asks KVM to do EPT splitting before anykvm_mmu_unmap_gfn_range()is performed.
In this snapshot of my WIP of putting this HugeTLB support with TDX huge page EPT support [2], I was thinking to combine EPT splitting together with unmap, and leaving the invalidate to be a separate part. (See kvm_gmem_unmap_private().) I did it this way so that the EPT splitting is range is the unmapping range, and only the invalidation range is broadened.
What do you think of that?
Quoted 216 lines
Quoted 216 lines
virt/kvm/guest_memfd.c +159
-9gmem_list = &inode->i_mapping->i_private_list;list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_begin (gmem, work->start, end); +kvm_gmem_invalidate_begin (gmem, invalidate_start, invalidate_end); }static void kvm_gmem_convert_invalidate_end (struct inode *inode,struct conversion_work *work) {struct list_head *gmem_list; +pgoff_t invalidate_start; +pgoff_t invalidate_end;struct kvm_gmem *gmem; -pgoff_t end; +pgoff_t work_end; - end = work->start + work->nr_pages; + work_end = work->start + work->nr_pages; + invalidate_start =kvm_gmem_compute_invalidate_start (inode, work->start); + invalidate_end =kvm_gmem_compute_invalidate_end (inode, work_end); gmem_list = &inode->i_mapping->i_private_list;list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_end (gmem, work->start, end); +kvm_gmem_invalidate_end (gmem, invalidate_start, invalidate_end); }static int kvm_gmem_convert_should_proceed (struct inode *inode,struct conversion_work *work,bool to_shared,pgoff_t *error_index) { -if (!to_shared) { +if (to_shared) { +struct list_head *gmem_list; +struct kvm_gmem *gmem; +pgoff_t work_end; + + work_end = work->start + work->nr_pages; + + gmem_list = &inode->i_mapping->i_private_list; +list_for_each_entry (gmem, gmem_list, entry) +kvm_gmem_unmap_private (gmem, work->start, work_end); + }else {unmap_mapping_pages (inode->i_mapping, work->start, work->nr_pages, false);@@ -340,6 +487,27 @@ static int kvm_gmem_convert_should_proceed(struct inode *inode,return 0 ; } +static int kvm_gmem_convert_execute_work (struct inode *inode, +struct conversion_work *work, +bool to_shared) +{ +enum shareability m; +int ret; + + m = to_shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +return ret; +/* +* Apply shareability first so split/merge can operate on new +* shareability state. +*/ + ret =kvm_gmem_restructure_folios_in_range ( + inode, work->start, work->nr_pages, to_shared); + +return ret; +} +static int kvm_gmem_convert_range (struct file *file,pgoff_t start,size_t nr_pages,bool shared,pgoff_t *error_index)@@ -371,18 +539,21 @@ static int kvm_gmem_convert_range(struct file *file, pgoff_t start,list_for_each_entry (work, &work_list, list) { rollback_stop_item = work; - ret =kvm_gmem_shareability_apply (inode, work, m); + + ret =kvm_gmem_convert_execute_work (inode, work, shared);if (ret)break ; }if (ret) { - m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ;list_for_each_entry (work, &work_list, list) { +int r; + + r =kvm_gmem_convert_execute_work (inode, work, !shared); +WARN_ON (r); +if (work == rollback_stop_item)break ; - -WARN_ON (kvm_gmem_shareability_apply (inode, work, m)); } }@@ -434,6 +605,277 @@ static int kvm_gmem_ioctl_convert_range(struct file *file,return ret; } +#ifdef CONFIG_KVM_GMEM_HUGETLB + +static inline void __filemap_remove_folio_for_restructuring (struct folio *folio) +{ +struct address_space *mapping = folio->mapping; + +spin_lock (&mapping->host->i_lock); +xa_lock_irq (&mapping->i_pages); + +__filemap_remove_folio (folio,NULL ); + +xa_unlock_irq (&mapping->i_pages); +spin_unlock (&mapping->host->i_lock); +} + +/** +* filemap_remove_folio_for_restructuring() - Remove @folio from filemap for +* split/merge. +* +* @folio: the folio to be removed. +* +* Similar to filemap_remove_folio(), but skips LRU-related calls (meaningless +* for guest_memfd), and skips call to ->free_folio() to maintain folio flags. +* +* Context: Expects only the filemap's refcounts to be left on the folio. Will +* freeze these refcounts away so that no other users will interfere +* with restructuring. +*/ +static inline void filemap_remove_folio_for_restructuring (struct folio *folio) +{ +int filemap_refcount; + + filemap_refcount =folio_nr_pages (folio); +while (!folio_ref_freeze (folio, filemap_refcount)) { +/* +* At this point only filemap refcounts are expected, hence okay +* to spin until speculative refcounts go away. +*/ +WARN_ONCE (1 ,"Spinning on folio=%p refcount=%d" , folio,folio_ref_count (folio)); + } + +folio_lock (folio); +__filemap_remove_folio_for_restructuring (folio); +folio_unlock (folio); +} + +/** +* kvm_gmem_split_folio_in_filemap() - Split @folio within filemap in @inode. +* +* @inode: inode containing the folio. +* @folio: folio to be split. +* +* Split a folio into folios of size PAGE_SIZE. Will clean up folio from filemap +* and add back the split folios. +* +* Context: Expects that before this call, folio's refcount is just the +* filemap's refcounts. After this function returns, the split folios' +* refcounts will also be filemap's refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_split_folio_in_filemap (struct inode *inode,struct folio *folio) +{ +size_t orig_nr_pages; +pgoff_t orig_index; +size_t i, j; +int ret; + + orig_nr_pages =folio_nr_pages (folio); +if (orig_nr_pages ==1 ) +return 0 ; + + orig_index = folio->index; + +filemap_remove_folio_for_restructuring (folio); + + ret =kvm_gmem_allocator_ops (inode)->split_folio (folio); +if (ret) + goto err; + +for (i =0 ; i < orig_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (folio, i)); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, f, + orig_index + i); +if (ret) + goto rollback; + } + +return ret; + +rollback: +for (j =0 ; j < i; ++j) { +struct folio *f =page_folio (folio_page (folio, j)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (folio); +err: +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, folio, orig_index)); + +return ret; +} + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +size_t to_nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ;
Quoted 9 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 724
Quoted 5 lines
virt/kvm/guest_memfd.c +5
-0+ + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); + +if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages))If the
guest_memfdis configured withGUESTMEM_HUGETLB_FLAG_1GB, it seems that whenever there's a shared page within a 1GB range, the folio will always be split into 4KB folios. Is it good?
It is not the best, but okay as an initial step.
We want to work on splitting 1G to 2M (as many 2M pages as possible) then to 4K. I believe the agreement with the community is that the 1G->2M->4K splitting is an optimization for the patch series after this one.
Quoted 112 lines
Quoted 99 lines
virt/kvm/guest_memfd.c +99
-0+return kvm_gmem_split_folio_in_filemap (inode, folio); + +return 0 ; +} + +/** +* kvm_gmem_merge_folio_in_filemap() - Merge @first_folio within filemap in +* @inode. +* +* @inode: inode containing the folio. +* @first_folio: first folio among folios to be merged. +* +* Will clean up subfolios from filemap and add back the merged folio. +* +* Context: Expects that before this call, all subfolios only have filemap +* refcounts. After this function returns, the merged folio will only +* have filemap refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +pgoff_t index; +void *priv; +size_t i; +int ret; + + index = first_folio->index; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); +if (folio_nr_pages (first_folio) == to_nr_pages) +return 0 ; + +for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (first_folio); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, first_folio, index); +if (ret) + goto err_split; + +return ret; + +err_split: +WARN_ON (kvm_gmem_allocator_ops (inode)->split_folio (first_folio)); +for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, f, index + i)); + } + +return ret; +} + +static inline int kvm_gmem_try_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (kvm_gmem_has_some_shared (inode, first_folio->index, to_nr_pages)) +return 0 ; + +return kvm_gmem_merge_folio_in_filemap (inode, first_folio); +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +size_t to_nr_pages; +pgoff_t index; +pgoff_t end; +void *priv; +int ret; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + end = start + nr_pages; + +/* Round to allocator page size, to check all (huge) pages in range. */ + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start =round_down (start, to_nr_pages); + end =round_up (end, to_nr_pages); + +for (index = start; index < end; index += to_nr_pages) { +struct folio *f;virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) + ret =kvm_gmem_split_folio_in_filemap (inode, f);The split operation is performed after
kvm_gmem_unmap_private()withinkvm_gmem_convert_should_proceed(), right?
Quoted 4 lines
So, it seems that that it's not necessary for TDX to avoid holding private page references, as TDX must have released the page refs after
kvm_gmem_unmap_private()(except when there's TDX module or KVM bug).
I agree with your assessment in the follow up email.
We don't want to unmap more than the requested conversion range to avoid extra churn. If TDX holds refcounts on mapped pages, the subpages that are still mapped will contribute to the refcount of the huge page, and we can't split a page that has refcounts because we don't know how the refcounts are distributed over the subpages.
I guess technically if the refcounts are divisible across nr_pages, we could still split, but if we have a 1G page, but only some of the 1G subpages are mapped into TDX EPTs, then we would have a refcount that we don't know how to divide out.
Quoted 22 lines
Quoted 22 lines
virt/kvm/guest_memfd.c +22
-0+else + ret =kvm_gmem_try_merge_folio_in_filemap (inode, f); + +if (ret) + goto rollback; + } +return ret; + +rollback: +for (index -= to_nr_pages; index >= start; index -= to_nr_pages) { +struct folio *f; + + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); +else
Quoted 8 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 863
Quoted 8 lines
virt/kvm/guest_memfd.c +8
-0+ WARN_ON(kvm_gmem_split_folio_in_filemap(inode, f)); + } + +return ret; +} + +#else +
[...]
[1] https://lore.kernel.org/all/[email protected]/
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept/
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Ackerley TngQuoted 37 lines · Ackerley Tng
virt/kvm/guest_memfd.c +23
-2+static int kvm_gmem_convert_execute_work (struct inode *inode, +struct conversion_work *work, +bool to_shared) +{ +enum shareability m; +int ret; + + m = to_shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +return ret; +/* +* Apply shareability first so split/merge can operate on new +* shareability state. +*/ + ret =kvm_gmem_restructure_folios_in_range ( + inode, work->start, work->nr_pages, to_shared); + +return ret; +} +static int kvm_gmem_convert_range (struct file *file,pgoff_t start,size_t nr_pages,bool shared,pgoff_t *error_index)@@ -371,18 +539,21 @@ static int kvm_gmem_convert_range(struct file *file, pgoff_t start,list_for_each_entry (work, &work_list, list) { rollback_stop_item = work; - ret =kvm_gmem_shareability_apply (inode, work, m); + + ret =kvm_gmem_convert_execute_work (inode, work, shared);if (ret)break ; }if (ret) { - m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ;
virt/kvm/guest_memfd.c static int kvm_gmem_convert_range(struct file *file, pgoff_t start, · line 385
Quoted 10 lines
virt/kvm/guest_memfd.c +5
-2list_for_each_entry (work, &work_list, list) { +int r; + + r =kvm_gmem_convert_execute_work (inode, work, !shared); +WARN_ON (r); +if (work == rollback_stop_item)break ; - -WARN_ON (kvm_gmem_shareability_apply (inode, work, m));
Could kvm_gmem_shareability_apply() fail here?
Quoted 81 lines
virt/kvm/guest_memfd.c +74
-0} }@@ -434,6 +605,277 @@ static int kvm_gmem_ioctl_convert_range(struct file *file,return ret; } +#ifdef CONFIG_KVM_GMEM_HUGETLB + +static inline void __filemap_remove_folio_for_restructuring (struct folio *folio) +{ +struct address_space *mapping = folio->mapping; + +spin_lock (&mapping->host->i_lock); +xa_lock_irq (&mapping->i_pages); + +__filemap_remove_folio (folio,NULL ); + +xa_unlock_irq (&mapping->i_pages); +spin_unlock (&mapping->host->i_lock); +} + +/** +* filemap_remove_folio_for_restructuring() - Remove @folio from filemap for +* split/merge. +* +* @folio: the folio to be removed. +* +* Similar to filemap_remove_folio(), but skips LRU-related calls (meaningless +* for guest_memfd), and skips call to ->free_folio() to maintain folio flags. +* +* Context: Expects only the filemap's refcounts to be left on the folio. Will +* freeze these refcounts away so that no other users will interfere +* with restructuring. +*/ +static inline void filemap_remove_folio_for_restructuring (struct folio *folio) +{ +int filemap_refcount; + + filemap_refcount =folio_nr_pages (folio); +while (!folio_ref_freeze (folio, filemap_refcount)) { +/* +* At this point only filemap refcounts are expected, hence okay +* to spin until speculative refcounts go away. +*/ +WARN_ONCE (1 ,"Spinning on folio=%p refcount=%d" , folio,folio_ref_count (folio)); + } + +folio_lock (folio); +__filemap_remove_folio_for_restructuring (folio); +folio_unlock (folio); +} + +/** +* kvm_gmem_split_folio_in_filemap() - Split @folio within filemap in @inode. +* +* @inode: inode containing the folio. +* @folio: folio to be split. +* +* Split a folio into folios of size PAGE_SIZE. Will clean up folio from filemap +* and add back the split folios. +* +* Context: Expects that before this call, folio's refcount is just the +* filemap's refcounts. After this function returns, the split folios' +* refcounts will also be filemap's refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_split_folio_in_filemap (struct inode *inode,struct folio *folio) +{ +size_t orig_nr_pages; +pgoff_t orig_index; +size_t i, j; +int ret; + + orig_nr_pages =folio_nr_pages (folio); +if (orig_nr_pages ==1 ) +return 0 ; + + orig_index = folio->index; + +filemap_remove_folio_for_restructuring (folio);
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 691
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + ret =kvm_gmem_allocator_ops (inode)->split_folio (folio); +if (ret) + goto err; + +for (i =0 ; i < orig_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (folio, i)); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, f, + orig_index + i);
Why does the failure of __kvm_gmem_filemap_add_folio() here lead to rollback, while the failure of the one under rollback only triggers WARN_ON()?
Quoted 74 lines
virt/kvm/guest_memfd.c +74
-0+if (ret) + goto rollback; + } + +return ret; + +rollback: +for (j =0 ; j < i; ++j) { +struct folio *f =page_folio (folio_page (folio, j)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (folio); +err: +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, folio, orig_index)); + +return ret; +} + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +size_t to_nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); + +if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages)) +return kvm_gmem_split_folio_in_filemap (inode, folio); + +return 0 ; +} + +/** +* kvm_gmem_merge_folio_in_filemap() - Merge @first_folio within filemap in +* @inode. +* +* @inode: inode containing the folio. +* @first_folio: first folio among folios to be merged. +* +* Will clean up subfolios from filemap and add back the merged folio. +* +* Context: Expects that before this call, all subfolios only have filemap +* refcounts. After this function returns, the merged folio will only +* have filemap refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +pgoff_t index; +void *priv; +size_t i; +int ret; + + index = first_folio->index; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); +if (folio_nr_pages (first_folio) == to_nr_pages) +return 0 ; + +for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +filemap_remove_folio_for_restructuring (f); + } +
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 775
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+kvm_gmem_allocator_ops (inode)->merge_folio (first_folio); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, first_folio, index); +if (ret) + goto err_split; + +return ret; + +err_split: +WARN_ON (kvm_gmem_allocator_ops (inode)->split_folio (first_folio));
guestmem_hugetlb_split_folio() is possible to fail. e.g.
After the stash is freed by guestmem_hugetlb_unstash_free_metadata() in guestmem_hugetlb_merge_folio(), it's possible to get -ENOMEM for the stash allocation in guestmem_hugetlb_stash_metadata() in guestmem_hugetlb_split_folio().
Quoted 48 lines
virt/kvm/guest_memfd.c +48
-0+for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, f, index + i)); + } + +return ret; +} + +static inline int kvm_gmem_try_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (kvm_gmem_has_some_shared (inode, first_folio->index, to_nr_pages)) +return 0 ; + +return kvm_gmem_merge_folio_in_filemap (inode, first_folio); +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +size_t to_nr_pages; +pgoff_t index; +pgoff_t end; +void *priv; +int ret; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + end = start + nr_pages; + +/* Round to allocator page size, to check all (huge) pages in range. */ + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start =round_down (start, to_nr_pages); + end =round_up (end, to_nr_pages); + +for (index = start; index < end; index += to_nr_pages) { +struct folio *f;
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) + ret =kvm_gmem_split_folio_in_filemap (inode, f);
kvm_gmem_try_split_folio_in_filemap()?
Quoted 13 lines
virt/kvm/guest_memfd.c +13
-0+else + ret =kvm_gmem_try_merge_folio_in_filemap (inode, f); + +if (ret) + goto rollback; + } +return ret; + +rollback: +for (index -= to_nr_pages; index >= start; index -= to_nr_pages) { +struct folio *f; + + f =filemap_get_folio (inode->i_mapping, index);
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 856
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); +else +WARN_ON (kvm_gmem_split_folio_in_filemap (inode, f));
Is it safe to just leave WARN_ON()s in the rollback case?
Besides, are the kvm_gmem_merge_folio_in_filemap() and kvm_gmem_split_folio_in_filemap() here duplicated with the kvm_gmem_split_folio_in_filemap() and kvm_gmem_try_merge_folio_in_filemap() in the following "r = kvm_gmem_convert_execute_work(inode, work, !shared)"?
Quoted 22 lines
virt/kvm/guest_memfd.c +22
-0+ } + +return ret; +} + +#else + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +return 0 ; +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +return 0 ; +} + +#endif +
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
Quoted 14 lines · Yan Zhao
Quoted 13 lines · Ackerley Tng
virt/kvm/guest_memfd.c +13
-0+static int kvm_gmem_convert_execute_work (struct inode *inode, +struct conversion_work *work, +bool to_shared) +{ +enum shareability m; +int ret; + + m = to_shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +return ret; +/* +* Apply shareability first so split/merge can operate on new
Quoted 8 lines
virt/kvm/guest_memfd.c static int kvm_gmem_convert_should_proceed(struct inode *inode, · line 510
Quoted 8 lines
virt/kvm/guest_memfd.c +8
-0+* shareability state. +*/ + ret =kvm_gmem_restructure_folios_in_range ( + inode, work->start, work->nr_pages, to_shared); + +return ret; +} +
Hi Yan,
Thanks for your thorough reviews and your alternative suggestion in the other discussion at [1]! I'll try to bring the conversion-related parts of that discussion over here.
Quoted 3 lines
virt/kvm/guest_memfd.c static int kvm_gmem_convert_should_proceed(struct inode *inode, · line 513
Quoted 3 lines
static int kvm_gmem_convert_range(struct file *file,
pgoff_tstart,virt/kvm/guest_memfd.c +0
-0size_t nr_pages, bool shared, pgoff_t *error_index)
The guiding principle I was using for the conversion ioctls is
* Have the shareability updates and any necessary page restructuring (aka splitting/merging) either fully complete for not at all by the time the conversion ioctl returns.
* Any unmapping (from host or guest page tables) will not be re-mapped on errors.
* Rollback undoes changes if conversion failed, and in those cases any errors are turned into WARNings.
The rationale is that we want page sizes to be in sync with shareability so that any faults after the (successful or failed) conversion will not wrongly map in a larger page than allowed and cause any host crashes.
We considered 3 places where the memory can be mapped for conversions:
1. Host page tables
2. Guest page tables
3. IOMMU page tables
Unmapping from host page tables is the simplest case. We unmap any shared ranges from the host page tables. Any accesses after the failed conversion would just fault the memory back in and proceed as usual.
guest_memfd memory is not unmapped from IOMMUs in conversions. This case is handled because IOMMU mappings hold refcounts. After unmapping from the host, we check for unexpected refcounts and fail if there are unexpected refcounts.
We also unmap from guest page tables. Considering failed conversions, if the pages are shared, we're good since the next time the guest accesses the page, the page will be faulted in as before.
If the pages are private, on the next guest access, the pages will be faulted in again as well. This is fine for software-protected VMs IIUC.
For TDX (and SNP) IIUC the memory would have been cleared, and the memory would also need to be re-accepted. I was thinking that this is by design, since when a TDX guest requests a conversion it knows that the contents is not to be used again.
The userspace VMM is obligated to keep trying convert and if it gives up, userspace VMM should inform the guest that the conversion failed. The guest should handle conversion failures too and not assume that conversion always succeeds.
Putting TDX aside for a moment, so far, there are a few ways this conversion could fail:
a. Unexpected refcounts. Userspace should clear up the unexpected
refcounts and report failure to the guest if it can't for whatever reason.
b. ENOMEM because (i) we ran out of memory updating the shareability
maple_tree or (ii) since splitting involves allocating more memory for struct pages and we ran out of memory there. In this case the userspace VMM gets -ENOMEM and can make more memory available and then retry, or if it can't, also report failure to the guest.
TDX introduces TDX-specific conversion failures (see discussion at [1]), which this series doesn't handle, but I think we still have a line of sight to handle new errors.
In the other thread [1], I was proposing to have guest_memfd decide what to do on errors, but I think that might be baking more TDX-specific details into guest_memfd/KVM, and perhaps this is better:
We could return the errors to userspace and let userspace determine what to do. For retryable errors (as determined by userspace), it should do what it needs to do, and retry. For errors like TDX being unable to reclaim the memory, it could tell guest_memfd to leak that memory.
If userspace gives up, it should report conversion failure to the guest if userspace thinks the guest can continue (to a clean shutdown or otherwise). If something terrible happened during conversion, then userspace might have to exit itself or shutdown the host.
In [2], for TDX-specific conversion failures, you proposed prepping to eliminate errors and exiting early on failure, then actually unmapping. I think that could work too.
I'm a little concerned that prepping could be complicated, since the nature of conversion depends on the current state of shareability, and there's a lot to prepare, everything from counting memory required for maple_tree allocation (and merging ranges in the maple_tree), and counting the number of pages required for undoing vmemmap optimization in the case of splitting...
And even after doing all the prep to eliminate errors, the unmapping could fail in TDX-specific cases anyway, which still needs to be handled.
Hence I'm hoping you'll consider to let TDX-specific failures be built-in and handled alongside other failures by getting help from the userspace VMM, and in the worst case letting the guest know the conversion failed.
I also appreciate comments or suggestions from anyone else!
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
Quoted 11 lines
Quoted 11 lines
virt/kvm/guest_memfd.c +2
-1@@ -371,18 +539,21 @@ static int kvm_gmem_convert_range(struct file *file, pgoff_t start,list_for_each_entry (work, &work_list, list) { rollback_stop_item = work; - ret =kvm_gmem_shareability_apply (inode, work, m); + + ret =kvm_gmem_convert_execute_work (inode, work, shared);if (ret)break ; }
Quoted 14 lines
virt/kvm/guest_memfd.c static int kvm_gmem_convert_range(struct file *file, pgoff_t start, · line 385
Quoted 12 lines
virt/kvm/guest_memfd.c +5
-3if (ret) { - m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ;list_for_each_entry (work, &work_list, list) { +int r; + + r =kvm_gmem_convert_execute_work (inode, work, !shared); +WARN_ON (r); +if (work == rollback_stop_item)break ; - -WARN_ON (kvm_gmem_shareability_apply (inode, work, m));Could
kvm_gmem_shareability_apply()fail here?
Yes, it could. If shareability cannot be updated, then we probably ran out of memory. Userspace VMM will probably get -ENOMEM set on some earlier ret and should handle that accordingly.
On -ENOMEM in a rollback, the host is in a very tough spot anyway, and a clean guest shutdown may be the only way out, hence this is a WARN and not returned to userspace.
Quoted 85 lines
Quoted 85 lines
virt/kvm/guest_memfd.c +78
-0} }@@ -434,6 +605,277 @@ static int kvm_gmem_ioctl_convert_range(struct file *file,return ret; } +#ifdef CONFIG_KVM_GMEM_HUGETLB + +static inline void __filemap_remove_folio_for_restructuring (struct folio *folio) +{ +struct address_space *mapping = folio->mapping; + +spin_lock (&mapping->host->i_lock); +xa_lock_irq (&mapping->i_pages); + +__filemap_remove_folio (folio,NULL ); + +xa_unlock_irq (&mapping->i_pages); +spin_unlock (&mapping->host->i_lock); +} + +/** +* filemap_remove_folio_for_restructuring() - Remove @folio from filemap for +* split/merge. +* +* @folio: the folio to be removed. +* +* Similar to filemap_remove_folio(), but skips LRU-related calls (meaningless +* for guest_memfd), and skips call to ->free_folio() to maintain folio flags. +* +* Context: Expects only the filemap's refcounts to be left on the folio. Will +* freeze these refcounts away so that no other users will interfere +* with restructuring. +*/ +static inline void filemap_remove_folio_for_restructuring (struct folio *folio) +{ +int filemap_refcount; + + filemap_refcount =folio_nr_pages (folio); +while (!folio_ref_freeze (folio, filemap_refcount)) { +/* +* At this point only filemap refcounts are expected, hence okay +* to spin until speculative refcounts go away. +*/ +WARN_ONCE (1 ,"Spinning on folio=%p refcount=%d" , folio,folio_ref_count (folio)); + } + +folio_lock (folio); +__filemap_remove_folio_for_restructuring (folio); +folio_unlock (folio); +} + +/** +* kvm_gmem_split_folio_in_filemap() - Split @folio within filemap in @inode. +* +* @inode: inode containing the folio. +* @folio: folio to be split. +* +* Split a folio into folios of size PAGE_SIZE. Will clean up folio from filemap +* and add back the split folios. +* +* Context: Expects that before this call, folio's refcount is just the +* filemap's refcounts. After this function returns, the split folios' +* refcounts will also be filemap's refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_split_folio_in_filemap (struct inode *inode,struct folio *folio) +{ +size_t orig_nr_pages; +pgoff_t orig_index; +size_t i, j; +int ret; + + orig_nr_pages =folio_nr_pages (folio); +if (orig_nr_pages ==1 ) +return 0 ; + + orig_index = folio->index; + +filemap_remove_folio_for_restructuring (folio); + + ret =kvm_gmem_allocator_ops (inode)->split_folio (folio); +if (ret) + goto err;
Quoted 9 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 691
Quoted 6 lines
virt/kvm/guest_memfd.c +6
-0+ +for (i =0 ; i < orig_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (folio, i)); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, f, + orig_index + i);Why does the failure of
__kvm_gmem_filemap_add_folio()here lead to rollback, while the failure of the one under rollback only triggersWARN_ON()?
Mostly because I don't really have a choice on rollback. On rollback we try to restore the merged folio back into the filemap, and if we couldn't, the host is probably in rather bad shape in terms of memory availability and there may not be many options for the userspace VMM.
Perhaps the different possible errors from __kvm_gmem_filemap_add_folio() in both should be handled differently. Do you have any suggestions on that?
Quoted 81 lines
Quoted 81 lines
virt/kvm/guest_memfd.c +81
-0+if (ret) + goto rollback; + } + +return ret; + +rollback: +for (j =0 ; j < i; ++j) { +struct folio *f =page_folio (folio_page (folio, j)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (folio); +err: +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, folio, orig_index)); + +return ret; +} + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +size_t to_nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); + +if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages)) +return kvm_gmem_split_folio_in_filemap (inode, folio); + +return 0 ; +} + +/** +* kvm_gmem_merge_folio_in_filemap() - Merge @first_folio within filemap in +* @inode. +* +* @inode: inode containing the folio. +* @first_folio: first folio among folios to be merged. +* +* Will clean up subfolios from filemap and add back the merged folio. +* +* Context: Expects that before this call, all subfolios only have filemap +* refcounts. After this function returns, the merged folio will only +* have filemap refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +pgoff_t index; +void *priv; +size_t i; +int ret; + + index = first_folio->index; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); +if (folio_nr_pages (first_folio) == to_nr_pages) +return 0 ; + +for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (first_folio); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, first_folio, index); +if (ret) + goto err_split; + +return ret;
Quoted 10 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 775
Quoted 3 lines
virt/kvm/guest_memfd.c +3
-0+ +err_split: +WARN_ON (kvm_gmem_allocator_ops (inode)->split_folio (first_folio));
guestmem_hugetlb_split_folio()is possible to fail. e.g.
After the stash is freed byguestmem_hugetlb_unstash_free_metadata()inguestmem_hugetlb_merge_folio(), it's possible to get-ENOMEMfor the stash allocation inguestmem_hugetlb_stash_metadata()inguestmem_hugetlb_split_folio().
Yes. This is also on the error path. In line with all the other error and rollback paths, I don't really have other options at this point, since on error, I probably ran out of memory, so I try my best to restore the original state but give up with a WARN otherwise.
Quoted 51 lines
Quoted 51 lines
virt/kvm/guest_memfd.c +51
-0+for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, f, index + i)); + } + +return ret; +} + +static inline int kvm_gmem_try_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (kvm_gmem_has_some_shared (inode, first_folio->index, to_nr_pages)) +return 0 ; + +return kvm_gmem_merge_folio_in_filemap (inode, first_folio); +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +size_t to_nr_pages; +pgoff_t index; +pgoff_t end; +void *priv; +int ret; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + end = start + nr_pages; + +/* Round to allocator page size, to check all (huge) pages in range. */ + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start =round_down (start, to_nr_pages); + end =round_up (end, to_nr_pages); + +for (index = start; index < end; index += to_nr_pages) { +struct folio *f; + + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f))
Quoted 9 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833
Quoted 7 lines
virt/kvm/guest_memfd.c +7
-0+continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) + ret =kvm_gmem_split_folio_in_filemap (inode, f);
kvm_gmem_try_split_folio_in_filemap()?
Here we know for sure that this was a private-to-shared conversion. Hence, we know that there are at least some shared parts in this huge page and we can skip checking that.
Quoted 3 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 836
Quoted 3 lines
virt/kvm/guest_memfd.c +3
-0+else + ret =kvm_gmem_try_merge_folio_in_filemap (inode, f); +
For merge, we don't know if the entire huge page might perhaps contain some other shared subpages, hence we "try" to merge by first checking against shareability to find shared subpages.
Quoted 7 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 843
Quoted 7 lines
virt/kvm/guest_memfd.c +7
-0+if (ret) + goto rollback; + } +return ret; + +rollback: +for (index -= to_nr_pages; index >= start; index -= to_nr_pages) {
Note to self: the first index -= to_nr_pages was meant to skip the index that caused the failure, but this could cause an underflow if index = 0 when entering rollback. Need to fix this in the next revision.
Quoted 6 lines
Quoted 6 lines
virt/kvm/guest_memfd.c +6
-0+struct folio *f; + + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; +
Quoted 9 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 856
Quoted 7 lines
virt/kvm/guest_memfd.c +7
-0+/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); +else +WARN_ON (kvm_gmem_split_folio_in_filemap (inode, f));Is it safe to just leave WARN_ON()s in the rollback case?
Same as above. I don't think we have much of a choice.
Quoted 5 lines
Besides, are the
kvm_gmem_merge_folio_in_filemap()andkvm_gmem_split_folio_in_filemap()here duplicated with thekvm_gmem_split_folio_in_filemap()andkvm_gmem_try_merge_folio_in_filemap()in the following "r =kvm_gmem_convert_execute_work(inode, work, !shared)"?
This handles the case where some pages in the range [start, start + nr_pages) were split and the failure was halfway through. I could call kvm_gmem_convert_execute_work() with !shared but that would go over all the folios again from the start.
Quoted 23 lines
Quoted 22 lines
virt/kvm/guest_memfd.c +22
-0+ } + +return ret; +} + +#else + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +return 0 ; +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +return 0 ; +} + +#endif +
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
Quoted 68 lines · Ackerley Tng
Quoted 14 lines · Yan Zhao
Quoted 13 lines · Ackerley Tng
virt/kvm/guest_memfd.c +13
-0+static int kvm_gmem_convert_execute_work (struct inode *inode, +struct conversion_work *work, +bool to_shared) +{ +enum shareability m; +int ret; + + m = to_shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +return ret; +/* +* Apply shareability first so split/merge can operate on new Quoted 8 lines
virt/kvm/guest_memfd.c static int kvm_gmem_convert_should_proceed(struct inode *inode, · line 510
Quoted 8 lines
virt/kvm/guest_memfd.c +8
-0+* shareability state. +*/ + ret =kvm_gmem_restructure_folios_in_range ( + inode, work->start, work->nr_pages, to_shared); + +return ret; +} +Hi Yan,
Thanks for your thorough reviews and your alternative suggestion in the other discussion at [1]! I'll try to bring the conversion-related parts of that discussion over here.
Quoted 3 lines
virt/kvm/guest_memfd.c static int kvm_gmem_convert_should_proceed(struct inode *inode, · line 513
Quoted 3 lines
static int kvm_gmem_convert_range(struct file *file,
pgoff_tstart,virt/kvm/guest_memfd.c +0
-0size_t nr_pages, bool shared, pgoff_t *error_index)The guiding principle I was using for the conversion ioctls is
* Have the shareability updates and any necessary page restructuring (aka splitting/merging) either fully complete for not at all by the time the conversion ioctl returns.
* Any unmapping (from host or guest page tables) will not be re-mapped on errors.
* Rollback undoes changes if conversion failed, and in those cases any errors are turned into WARNings.The rationale is that we want page sizes to be in sync with shareability so that any faults after the (successful or failed) conversion will not wrongly map in a larger page than allowed and cause any host crashes.
We considered 3 places where the memory can be mapped for conversions:
1. Host page tables
2. Guest page tables
3. IOMMU page tablesUnmapping from host page tables is the simplest case. We unmap any shared ranges from the host page tables. Any accesses after the failed conversion would just fault the memory back in and proceed as usual.
guest_memfdmemory is not unmapped from IOMMUs in conversions. This case is handled because IOMMU mappings hold refcounts. After unmapping from the host, we check for unexpected refcounts and fail if there are unexpected refcounts.We also unmap from guest page tables. Considering failed conversions, if the pages are shared, we're good since the next time the guest accesses the page, the page will be faulted in as before.
Quoted 7 lines
If the pages are private, on the next guest access, the pages will be faulted in again as well. This is fine for software-protected VMs IIUC.
For TDX (and SNP) IIUC the memory would have been cleared, and the memory would also need to be re-accepted. I was thinking that this is by design, since when a TDX guest requests a conversion it knows that the contents is not to be used again.
This is not guaranteed.
On private-to-shared conversion failure, the guest may leak the page or release the page. If the guest chooses the latter (e.g. in kvmclock_init_mem(), kvm_arch_ptp_init()), the page is regarded as private by the guest OS. Re-acceptance then will not happen before the guest access.
So, it's better for host to keep the original SEPT if private-to-shared conversion fails.
Quoted 4 lines
The userspace VMM is obligated to keep trying convert and if it gives up, userspace VMM should inform the guest that the conversion failed. The guest should handle conversion failures too and not assume that conversion always succeeds.
I don't think relying userspace to keep trying convert endlessly is a good design.
Quoted 7 lines
Putting TDX aside for a moment, so far, there are a few ways this conversion could fail:
a. Unexpected refcounts. Userspace should clear up the unexpected
refcounts and report failure to the guest if it can't for whatever reason.
This is acceptable. Unmapping shared mappings in the primary MMU or shared EPT is harmless.
Quoted 5 lines
b. ENOMEM because (i) we ran out of memory updating the shareability
maple_treeor (ii) since splitting involves allocating more memory for struct pages and we ran out of memory there. In this case the userspace VMM gets-ENOMEMand can make more memory available and then retry, or if it can't, also report failure to the guest.
This is unacceptable. Why not reserve the memory before determining to start the real conversion? If -ENOMEM is returned before executing the conversion, we don't need to handle the restore error, which is impossible to be handled gracefully.
Quoted 3 lines
TDX introduces TDX-specific conversion failures (see discussion at [1]), which this series doesn't handle, but I think we still have a line of sight to handle new errors.
The errors can be divided into two categories:
(1) errors due to kernel bugs
(2) errors that could occur in normal or bad conditions (e.g. the -ENOMEM)
We can't handle (1), so BUG_ON or leaking memory is allowed. However, we should try to avoid (2) especially in the rollback path.
Quoted 3 lines
In the other thread [1], I was proposing to have
guest_memfddecide what to do on errors, but I think that might be baking more TDX-specific details into guest_memfd/KVM, and perhaps this is better:
The TDX-specific errors in the unmapping path is of category (1). So, we hope to resolve it by BUG_ON and leaking the memory.
The other conversion error for TDX is for splitting memory. We hope to do the splitting before executing the real conversion.
Please check the proposal details at
https://lore.kernel.org/all/aE%[email protected].
Quoted 164 lines
We could return the errors to userspace and let userspace determine what to do. For retryable errors (as determined by userspace), it should do what it needs to do, and retry. For errors like TDX being unable to reclaim the memory, it could tell
guest_memfdto leak that memory.If userspace gives up, it should report conversion failure to the guest if userspace thinks the guest can continue (to a clean shutdown or otherwise). If something terrible happened during conversion, then userspace might have to exit itself or shutdown the host.
In [2], for TDX-specific conversion failures, you proposed prepping to eliminate errors and exiting early on failure, then actually unmapping. I think that could work too.
I'm a little concerned that prepping could be complicated, since the nature of conversion depends on the current state of shareability, and there's a lot to prepare, everything from counting memory required for
maple_treeallocation (and merging ranges in themaple_tree), and counting the number of pages required for undoing vmemmap optimization in the case of splitting...And even after doing all the prep to eliminate errors, the unmapping could fail in TDX-specific cases anyway, which still needs to be handled.
Hence I'm hoping you'll consider to let TDX-specific failures be built-in and handled alongside other failures by getting help from the userspace VMM, and in the worst case letting the guest know the conversion failed.
I also appreciate comments or suggestions from anyone else!
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/Quoted 11 lines
Quoted 11 lines
virt/kvm/guest_memfd.c +2
-1@@ -371,18 +539,21 @@ static int kvm_gmem_convert_range(struct file *file, pgoff_t start,list_for_each_entry (work, &work_list, list) { rollback_stop_item = work; - ret =kvm_gmem_shareability_apply (inode, work, m); + + ret =kvm_gmem_convert_execute_work (inode, work, shared);if (ret)break ; }Quoted 14 lines
virt/kvm/guest_memfd.c static int kvm_gmem_convert_range(struct file *file, pgoff_t start, · line 385
Quoted 12 lines
virt/kvm/guest_memfd.c +5
-3if (ret) { - m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ;list_for_each_entry (work, &work_list, list) { +int r; + + r =kvm_gmem_convert_execute_work (inode, work, !shared); +WARN_ON (r); +if (work == rollback_stop_item)break ; - -WARN_ON (kvm_gmem_shareability_apply (inode, work, m));Could
kvm_gmem_shareability_apply()fail here?Yes, it could. If shareability cannot be updated, then we probably ran out of memory. Userspace VMM will probably get
-ENOMEMset on some earlier ret and should handle that accordingly.On
-ENOMEMin a rollback, the host is in a very tough spot anyway, and a clean guest shutdown may be the only way out, hence this is a WARN and not returned to userspace.Quoted 85 lines
Quoted 85 lines
virt/kvm/guest_memfd.c +78
-0} }@@ -434,6 +605,277 @@ static int kvm_gmem_ioctl_convert_range(struct file *file,return ret; } +#ifdef CONFIG_KVM_GMEM_HUGETLB + +static inline void __filemap_remove_folio_for_restructuring (struct folio *folio) +{ +struct address_space *mapping = folio->mapping; + +spin_lock (&mapping->host->i_lock); +xa_lock_irq (&mapping->i_pages); + +__filemap_remove_folio (folio,NULL ); + +xa_unlock_irq (&mapping->i_pages); +spin_unlock (&mapping->host->i_lock); +} + +/** +* filemap_remove_folio_for_restructuring() - Remove @folio from filemap for +* split/merge. +* +* @folio: the folio to be removed. +* +* Similar to filemap_remove_folio(), but skips LRU-related calls (meaningless +* for guest_memfd), and skips call to ->free_folio() to maintain folio flags. +* +* Context: Expects only the filemap's refcounts to be left on the folio. Will +* freeze these refcounts away so that no other users will interfere +* with restructuring. +*/ +static inline void filemap_remove_folio_for_restructuring (struct folio *folio) +{ +int filemap_refcount; + + filemap_refcount =folio_nr_pages (folio); +while (!folio_ref_freeze (folio, filemap_refcount)) { +/* +* At this point only filemap refcounts are expected, hence okay +* to spin until speculative refcounts go away. +*/ +WARN_ONCE (1 ,"Spinning on folio=%p refcount=%d" , folio,folio_ref_count (folio)); + } + +folio_lock (folio); +__filemap_remove_folio_for_restructuring (folio); +folio_unlock (folio); +} + +/** +* kvm_gmem_split_folio_in_filemap() - Split @folio within filemap in @inode. +* +* @inode: inode containing the folio. +* @folio: folio to be split. +* +* Split a folio into folios of size PAGE_SIZE. Will clean up folio from filemap +* and add back the split folios. +* +* Context: Expects that before this call, folio's refcount is just the +* filemap's refcounts. After this function returns, the split folios' +* refcounts will also be filemap's refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_split_folio_in_filemap (struct inode *inode,struct folio *folio) +{ +size_t orig_nr_pages; +pgoff_t orig_index; +size_t i, j; +int ret; + + orig_nr_pages =folio_nr_pages (folio); +if (orig_nr_pages ==1 ) +return 0 ; + + orig_index = folio->index; + +filemap_remove_folio_for_restructuring (folio); + + ret =kvm_gmem_allocator_ops (inode)->split_folio (folio); +if (ret) + goto err;Quoted 9 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 691
Quoted 6 lines
virt/kvm/guest_memfd.c +6
-0+ +for (i =0 ; i < orig_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (folio, i)); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, f, + orig_index + i);Why does the failure of
__kvm_gmem_filemap_add_folio()here lead to rollback, while the failure of the one under rollback only triggersWARN_ON()?
Quoted 4 lines
Mostly because I don't really have a choice on rollback. On rollback we try to restore the merged folio back into the filemap, and if we couldn't, the host is probably in rather bad shape in terms of memory availability and there may not be many options for the userspace VMM.
Out of memory is not a good excuse for rollback error.
Quoted 3 lines
Perhaps the different possible errors from
__kvm_gmem_filemap_add_folio()in both should be handled differently. Do you have any suggestions on that?
Maybe reserving the memory or ruling out other factors that could lead to conversion failure before executing the conversion?
Then BUG_ON the if the failure is cause by a bug.
Quoted 158 lines
Quoted 81 lines
Quoted 81 lines
virt/kvm/guest_memfd.c +81
-0+if (ret) + goto rollback; + } + +return ret; + +rollback: +for (j =0 ; j < i; ++j) { +struct folio *f =page_folio (folio_page (folio, j)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (folio); +err: +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, folio, orig_index)); + +return ret; +} + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +size_t to_nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); + +if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages)) +return kvm_gmem_split_folio_in_filemap (inode, folio); + +return 0 ; +} + +/** +* kvm_gmem_merge_folio_in_filemap() - Merge @first_folio within filemap in +* @inode. +* +* @inode: inode containing the folio. +* @first_folio: first folio among folios to be merged. +* +* Will clean up subfolios from filemap and add back the merged folio. +* +* Context: Expects that before this call, all subfolios only have filemap +* refcounts. After this function returns, the merged folio will only +* have filemap refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +pgoff_t index; +void *priv; +size_t i; +int ret; + + index = first_folio->index; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); +if (folio_nr_pages (first_folio) == to_nr_pages) +return 0 ; + +for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (first_folio); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, first_folio, index); +if (ret) + goto err_split; + +return ret;Quoted 10 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 775
Quoted 3 lines
virt/kvm/guest_memfd.c +3
-0+ +err_split: +WARN_ON (kvm_gmem_allocator_ops (inode)->split_folio (first_folio));
guestmem_hugetlb_split_folio()is possible to fail. e.g.
After the stash is freed byguestmem_hugetlb_unstash_free_metadata()inguestmem_hugetlb_merge_folio(), it's possible to get-ENOMEMfor the stash allocation inguestmem_hugetlb_stash_metadata()inguestmem_hugetlb_split_folio().Yes. This is also on the error path. In line with all the other error and rollback paths, I don't really have other options at this point, since on error, I probably ran out of memory, so I try my best to restore the original state but give up with a WARN otherwise.
Quoted 51 lines
Quoted 51 lines
virt/kvm/guest_memfd.c +51
-0+for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, f, index + i)); + } + +return ret; +} + +static inline int kvm_gmem_try_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (kvm_gmem_has_some_shared (inode, first_folio->index, to_nr_pages)) +return 0 ; + +return kvm_gmem_merge_folio_in_filemap (inode, first_folio); +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +size_t to_nr_pages; +pgoff_t index; +pgoff_t end; +void *priv; +int ret; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + end = start + nr_pages; + +/* Round to allocator page size, to check all (huge) pages in range. */ + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start =round_down (start, to_nr_pages); + end =round_up (end, to_nr_pages); + +for (index = start; index < end; index += to_nr_pages) { +struct folio *f; + + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f))Quoted 9 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833
Quoted 7 lines
virt/kvm/guest_memfd.c +7
-0+continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) + ret =kvm_gmem_split_folio_in_filemap (inode, f);
kvm_gmem_try_split_folio_in_filemap()?
Quoted 3 lines
Here we know for sure that this was a private-to-shared conversion. Hence, we know that there are at least some shared parts in this huge page and we can skip checking that.
Ok.
Quoted 7 lines
Quoted 3 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 836
Quoted 3 lines
virt/kvm/guest_memfd.c +3
-0+else + ret =kvm_gmem_try_merge_folio_in_filemap (inode, f); +For merge, we don't know if the entire huge page might perhaps contain some other shared subpages, hence we "try" to merge by first checking against shareability to find shared subpages.
Makes sense.
Quoted 11 lines
Quoted 7 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 843
Quoted 7 lines
virt/kvm/guest_memfd.c +7
-0+if (ret) + goto rollback; + } +return ret; + +rollback: +for (index -= to_nr_pages; index >= start; index -= to_nr_pages) {Note to self: the first index -=
to_nr_pageswas meant to skip the index that caused the failure, but this could cause an underflow if index = 0 when entering rollback. Need to fix this in the next revision.
Yes :)
Quoted 52 lines
Quoted 6 lines
Quoted 6 lines
virt/kvm/guest_memfd.c +6
-0+struct folio *f; + + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; +Quoted 9 lines
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 856
Quoted 7 lines
virt/kvm/guest_memfd.c +7
-0+/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); +else +WARN_ON (kvm_gmem_split_folio_in_filemap (inode, f));Is it safe to just leave WARN_ON()s in the rollback case?
Same as above. I don't think we have much of a choice.
Quoted 5 lines
Besides, are the
kvm_gmem_merge_folio_in_filemap()andkvm_gmem_split_folio_in_filemap()here duplicated with thekvm_gmem_split_folio_in_filemap()andkvm_gmem_try_merge_folio_in_filemap()in the following "r =kvm_gmem_convert_execute_work(inode, work, !shared)"?This handles the case where some pages in the range [start, start +
nr_pages) were split and the failure was halfway through. I could callkvm_gmem_convert_execute_work()with !shared but that would go over all the folios again from the start.Quoted 23 lines
Quoted 22 lines
virt/kvm/guest_memfd.c +22
-0+ } + +return ret; +} + +#else + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +return 0 ; +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +return 0 ; +} + +#endif +
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Ackerley TngOn 5/15/2025 7:42 AM, Ackerley Tng wrote:
[...]
Quoted 4 lines
virt/kvm/guest_memfd.c +4
-0+ +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 724
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+size_t to_nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); + +if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages))
What if a huge page whose attribute is shared?
Quoted 5 lines
virt/kvm/guest_memfd.c +5
-0+return kvm_gmem_split_folio_in_filemap (inode, folio); + +return 0 ; +} +
[...]
Quoted 34 lines
static int
kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)virt/kvm/guest_memfd.c +8
-2@@ -563,11 +1005,16 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return folio;if (kvm_gmem_has_custom_allocator (inode)) { -void *p =kvm_gmem_allocator_private (inode); +size_t nr_pages; +void *p; + p =kvm_gmem_allocator_private (inode); folio =kvm_gmem_allocator_ops (inode)->alloc_folio (p);if (IS_ERR (folio))return folio; + + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (p); + index_floor =round_down (index, nr_pages); }else {gfp_t gfp =mapping_gfp_mask (inode->i_mapping);@@ -580,10 +1027,11 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)folio_put (folio);return ERR_PTR (ret); } + + index_floor = index; } allocated_size =folio_size (folio); - index_floor =round_down (index,folio_nr_pages (folio)); ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index_floor);if (ret) {folio_put (folio);
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index) · line 1054
Quoted 7 lines
virt/kvm/guest_memfd.c +4
-0@@ -600,6 +1048,13 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } +/* Leave just filemap's refcounts on folio. */ +folio_put (folio); + + ret =kvm_gmem_try_split_folio_in_filemap (inode, folio);
When !CONFIG_KVM_GMEM_SHARED_MEM, kvm_gmem_try_split_folio_in_filemap() is undefined.
Quoted 7 lines
virt/kvm/guest_memfd.c +3
-0+if (ret) + goto err; +spin_lock (&inode->i_lock); inode->i_blocks += allocated_size /512 ;spin_unlock (&inode->i_lock);
[...]
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
Quoted 19 lines · Binbin Wu
On 5/15/2025 7:42 AM, Ackerley Tng wrote:
[...]Quoted 4 lines
virt/kvm/guest_memfd.c +4
-0+ +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 724
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+size_t to_nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); + +if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages))What if a huge page whose attribute is shared?
This checks if there are any shared pages in the range [folio->index, folio->index + to_nr_pages), so if the entire huge page is shared this function should also return true.
folio->index is the start of the merged huge page, and to_nr_pages is the number of pages in the merged huge page, so this should be querying exactly the entire huge page.
Note to self: rename kvm_gmem_has_some_shared() to kvm_gmem_has_any_shared() in the next revision.
Hope I answered your question! Let me know if I misunderstood your question.
Quoted 43 lines
Quoted 5 lines
virt/kvm/guest_memfd.c +5
-0+return kvm_gmem_split_folio_in_filemap (inode, folio); + +return 0 ; +} +[...]
Quoted 37 lines
static int
kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)virt/kvm/guest_memfd.c +8
-2@@ -563,11 +1005,16 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return folio;if (kvm_gmem_has_custom_allocator (inode)) { -void *p =kvm_gmem_allocator_private (inode); +size_t nr_pages; +void *p; + p =kvm_gmem_allocator_private (inode); folio =kvm_gmem_allocator_ops (inode)->alloc_folio (p);if (IS_ERR (folio))return folio; + + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (p); + index_floor =round_down (index, nr_pages); }else {gfp_t gfp =mapping_gfp_mask (inode->i_mapping);@@ -580,10 +1027,11 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)folio_put (folio);return ERR_PTR (ret); } + + index_floor = index; } allocated_size =folio_size (folio); - index_floor =round_down (index,folio_nr_pages (folio)); ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index_floor);if (ret) {folio_put (folio);@@ -600,6 +1048,13 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); }
Quoted 8 lines
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index) · line 1054
Quoted 4 lines
virt/kvm/guest_memfd.c +4
-0+/* Leave just filemap's refcounts on folio. */ +folio_put (folio); + + ret =kvm_gmem_try_split_folio_in_filemap (inode, folio);When !CONFIG_KVM_GMEM_SHARED_MEM,
kvm_gmem_try_split_folio_in_filemap()is undefined.
Will fix this in the next revision. Thanks!
Quoted 8 lines
Quoted 7 lines
virt/kvm/guest_memfd.c +3
-0+if (ret) + goto err; +spin_lock (&inode->i_lock); inode->i_blocks += allocated_size /512 ;spin_unlock (&inode->i_lock);[...]
RFC PATCH v2 39/51 KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)
In reply to Ackerley TngMerge and truncate on fallocate(PUNCH_HOLE), but if the file is being closed, defer merging to folio_put() callback.
--- virt/kvm/guest_memfd.c | 76 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 8 deletions(-)
virt/kvm/guest_memfd.c +68 -8
@@ -859,6 +859,35 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,return ret; } +static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +struct folio *f; +pgoff_t unused; +long num_freed; + +unmap_mapping_pages (inode->i_mapping, index, nr_pages, false); + +if (!kvm_gmem_has_safe_refcount (inode->i_mapping, index, nr_pages, &unused)) +return -EAGAIN ; + + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +return 0 ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); + + num_freed =folio_nr_pages (f); +folio_lock (f); +truncate_inode_folio (inode->i_mapping, f); +folio_unlock (f); + +return num_freed; +} +#else static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
@@ -874,6 +903,12 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode, return 0; } +static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +return 0 ; +} +#endif #else
@@ -1182,8 +1217,10 @@ static long kvm_gmem_truncate_indices(struct address_space *mapping,* * Removes folios beginning @index for @nr_pages from filemap in @inode, updates * inode metadata. +* +* Return: 0 on success and negative error otherwise. */ -static void kvm_gmem_truncate_inode_aligned_pages (struct inode *inode, +static long kvm_gmem_truncate_inode_aligned_pages (struct inode *inode,pgoff_t index,size_t nr_pages) {
@@ -1191,19 +1228,34 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,long num_freed;pgoff_t idx;void *priv; +long ret; priv =kvm_gmem_allocator_private (inode); nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + ret =0 ; num_freed =0 ;for (idx = index; idx < index + nr_pages; idx += nr_per_huge_page) { - num_freed +=kvm_gmem_truncate_indices ( - inode->i_mapping, idx, nr_per_huge_page); +if (mapping_exiting (inode->i_mapping) || + !kvm_gmem_has_some_shared (inode, idx, nr_per_huge_page)) { + num_freed +=kvm_gmem_truncate_indices ( + inode->i_mapping, idx, nr_per_huge_page); + }else { + ret =kvm_gmem_merge_truncate_indices (inode, idx, + nr_per_huge_page); +if (ret <0 ) +break ; + + num_freed += ret; + ret =0 ; + } }spin_lock (&inode->i_lock); inode->i_blocks -= (num_freed <<PAGE_SHIFT ) /512 ;spin_unlock (&inode->i_lock); + +return ret; }/**
@@ -1252,8 +1304,10 @@ static void kvm_gmem_zero_range(struct address_space *mapping,* * Removes full (huge)pages from the filemap and zeroing incomplete * (huge)pages. The pages in the range may be split. +* +* Return: 0 on success and negative error otherwise. */ -static void kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart, +static long kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart,loff_t lend) {pgoff_t full_hpage_start;
@@ -1263,6 +1317,7 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,pgoff_t start;pgoff_t end;void *priv; +long ret; priv =kvm_gmem_allocator_private (inode); nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv);
@@ -1279,10 +1334,11 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,kvm_gmem_zero_range (inode->i_mapping, start, zero_end); } + ret =0 ;if (full_hpage_end > full_hpage_start) { nr_pages = full_hpage_end - full_hpage_start; -kvm_gmem_truncate_inode_aligned_pages (inode, full_hpage_start, - nr_pages); + ret =kvm_gmem_truncate_inode_aligned_pages ( + inode, full_hpage_start, nr_pages); }if (end > full_hpage_end && end > full_hpage_start) {
@@ -1290,6 +1346,8 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,kvm_gmem_zero_range (inode->i_mapping, zero_start, end); } + +return ret; }static long kvm_gmem_punch_hole (struct inode *inode,loff_t offset,loff_t len)
@@ -1298,6 +1356,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)pgoff_t start = offset >>PAGE_SHIFT ;pgoff_t end = (offset + len) >>PAGE_SHIFT ;struct kvm_gmem *gmem; +long ret;/* * Bindings must be stable across invalidation to ensure the start+end
@@ -1308,8 +1367,9 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_begin_and_zap (gmem, start, end); + ret =0 ;if (kvm_gmem_has_custom_allocator (inode)) { -kvm_gmem_truncate_inode_range (inode, offset, offset + len); + ret =kvm_gmem_truncate_inode_range (inode, offset, offset + len); }else {/* Page size is PAGE_SIZE, so use optimized truncation function. */ truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 );
@@ -1320,7 +1380,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)filemap_invalidate_unlock (inode->i_mapping); -return 0 ; +return ret; }static long kvm_gmem_allocate (struct inode *inode,loff_t offset,loff_t len)
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 39/51] KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)
Quoted 17 lines · Ackerley Tng
Merge and truncate on
fallocate(PUNCH_HOLE), but if the file is being closed, defer merging tofolio_put()callback.Change-Id Iae26987756e70c83f3b121edbc0ed0bc105eec0dSigned-off-by Ackerley Tng <[email protected]>--- virt/kvm/guest_memfd.c | 76 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 8 deletions(-)virt/kvm/guest_memfd.c +0
-0@@ -859,6 +859,35 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,return ret; }
virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 871
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +struct folio *f; +pgoff_t unused; +long num_freed; + +unmap_mapping_pages (inode->i_mapping, index, nr_pages, false); + +if (!kvm_gmem_has_safe_refcount (inode->i_mapping, index, nr_pages, &unused))
Why is kvm_gmem_has_safe_refcount() checked here, but not in kvm_gmem_zero_range() within kvm_gmem_truncate_inode_range() in patch 33?
virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 873
Quoted 2 lines
virt/kvm/guest_memfd.c +2
-0+return -EAGAIN ; +
Rather than merging the folios, could we simply call kvm_gmem_truncate_indices() instead?
num_freed = kvm_gmem_truncate_indices(inode->i_mapping, index, nr_pages); return num_freed;
Quoted 156 lines
virt/kvm/guest_memfd.c +56
-8+ f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +return 0 ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); + + num_freed =folio_nr_pages (f); +folio_lock (f); +truncate_inode_folio (inode->i_mapping, f); +folio_unlock (f); + +return num_freed; +} +#else static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,@@ -874,6 +903,12 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode, return 0; } +static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +return 0 ; +} +#endif #else @@ -1182,8 +1217,10 @@ static long kvm_gmem_truncate_indices(struct address_space *mapping,* * Removes folios beginning @index for @nr_pages from filemap in @inode, updates * inode metadata. +* +* Return: 0 on success and negative error otherwise. */ -static void kvm_gmem_truncate_inode_aligned_pages (struct inode *inode, +static long kvm_gmem_truncate_inode_aligned_pages (struct inode *inode,pgoff_t index,size_t nr_pages) {@@ -1191,19 +1228,34 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,long num_freed;pgoff_t idx;void *priv; +long ret; priv =kvm_gmem_allocator_private (inode); nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + ret =0 ; num_freed =0 ;for (idx = index; idx < index + nr_pages; idx += nr_per_huge_page) { - num_freed +=kvm_gmem_truncate_indices ( - inode->i_mapping, idx, nr_per_huge_page); +if (mapping_exiting (inode->i_mapping) || + !kvm_gmem_has_some_shared (inode, idx, nr_per_huge_page)) { + num_freed +=kvm_gmem_truncate_indices ( + inode->i_mapping, idx, nr_per_huge_page); + }else { + ret =kvm_gmem_merge_truncate_indices (inode, idx, + nr_per_huge_page); +if (ret <0 ) +break ; + + num_freed += ret; + ret =0 ; + } }spin_lock (&inode->i_lock); inode->i_blocks -= (num_freed <<PAGE_SHIFT ) /512 ;spin_unlock (&inode->i_lock); + +return ret; }/** @@ -1252,8 +1304,10 @@ static void kvm_gmem_zero_range(struct address_space *mapping,* * Removes full (huge)pages from the filemap and zeroing incomplete * (huge)pages. The pages in the range may be split. +* +* Return: 0 on success and negative error otherwise. */ -static void kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart, +static long kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart,loff_t lend) {pgoff_t full_hpage_start;@@ -1263,6 +1317,7 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,pgoff_t start;pgoff_t end;void *priv; +long ret; priv =kvm_gmem_allocator_private (inode); nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv);@@ -1279,10 +1334,11 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,kvm_gmem_zero_range (inode->i_mapping, start, zero_end); } + ret =0 ;if (full_hpage_end > full_hpage_start) { nr_pages = full_hpage_end - full_hpage_start; -kvm_gmem_truncate_inode_aligned_pages (inode, full_hpage_start, - nr_pages); + ret =kvm_gmem_truncate_inode_aligned_pages ( + inode, full_hpage_start, nr_pages); }if (end > full_hpage_end && end > full_hpage_start) {@@ -1290,6 +1346,8 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,kvm_gmem_zero_range (inode->i_mapping, zero_start, end); } + +return ret; }static long kvm_gmem_punch_hole (struct inode *inode,loff_t offset,loff_t len)@@ -1298,6 +1356,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)pgoff_t start = offset >>PAGE_SHIFT ;pgoff_t end = (offset + len) >>PAGE_SHIFT ;struct kvm_gmem *gmem; +long ret;/* * Bindings must be stable across invalidation to ensure the start+end @@ -1308,8 +1367,9 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_begin_and_zap (gmem, start, end); + ret =0 ;if (kvm_gmem_has_custom_allocator (inode)) { -kvm_gmem_truncate_inode_range (inode, offset, offset + len); + ret =kvm_gmem_truncate_inode_range (inode, offset, offset + len); }else {/* Page size is PAGE_SIZE, so use optimized truncation function. */ truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 );@@ -1320,7 +1380,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)filemap_invalidate_unlock (inode->i_mapping); -return 0 ; +return ret; }static long kvm_gmem_allocate (struct inode *inode,loff_t offset,loff_t len)Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 39/51] KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)
Quoted 18 lines · Yan Zhao
Quoted 17 lines · Ackerley Tng
Merge and truncate on
fallocate(PUNCH_HOLE), but if the file is being closed, defer merging tofolio_put()callback.Change-Id Iae26987756e70c83f3b121edbc0ed0bc105eec0dSigned-off-by Ackerley Tng <[email protected]>--- virt/kvm/guest_memfd.c | 76 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 8 deletions(-)virt/kvm/guest_memfd.c +0
-0@@ -859,6 +859,35 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,return ret; }
Quoted 10 lines
virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 871
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +struct folio *f; +pgoff_t unused; +long num_freed; + +unmap_mapping_pages (inode->i_mapping, index, nr_pages, false); + +if (!kvm_gmem_has_safe_refcount (inode->i_mapping, index, nr_pages, &unused))
Yan, thank you for your reviews!
Quoted 3 lines
Why is
kvm_gmem_has_safe_refcount()checked here, but not inkvm_gmem_zero_range()withinkvm_gmem_truncate_inode_range()in patch 33?
The contract for guest_memfd with HugeTLB pages is that if holes are punched in any ranges less than a full huge page, no pages are removed from the filemap. Those ranges are only zeroed.
In kvm_gmem_zero_range(), we never remove any folios, and so there is no need to merge. If there's no need to merge, then we don't need to check for a safe refcount, and can just proceed to zero.
kvm_gmem_merge_truncate_indices() is only used during hole punching and not when the file is closed. Hole punch vs file closure is checked using mapping_exiting(inode->i_mapping).
During a hole punch, we will only allow truncation if there are no unexpected refcounts on any subpages, hence this kvm_gmem_has_safe_refcount() check.
Quoted 9 lines
virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 873
Quoted 2 lines
virt/kvm/guest_memfd.c +2
-0+return -EAGAIN ; +Rather than merging the folios, could we simply call
kvm_gmem_truncate_indices()instead?
num_freed=kvm_gmem_truncate_indices(inode->i_mapping, index, nr_pages); returnnum_freed;
We could do this too, but then that would be deferring the huge page merging to the folio_put() callback and eventually the kernel worker thread.
My goal here is to try to not to defer merging and freeing as much as possible so that most of the page/memory operations are synchronous, because synchronous operations are more predictable.
As an example of improving predictability, in one of the selftests, I do a hole punch and then try to allocate again. Because the merging and freeing of the HugeTLB page sometimes takes too long, the allocation sometimes fails: the guest_memfd's subpool hadn't yet received the freed page back. With a synchronous truncation, the truncation may take longer, but the selftest predictably passes.
Quoted 156 lines
Quoted 156 lines
virt/kvm/guest_memfd.c +56
-8+ f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +return 0 ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); + + num_freed =folio_nr_pages (f); +folio_lock (f); +truncate_inode_folio (inode->i_mapping, f); +folio_unlock (f); + +return num_freed; +} +#else static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,@@ -874,6 +903,12 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode, return 0; } +static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +return 0 ; +} +#endif #else @@ -1182,8 +1217,10 @@ static long kvm_gmem_truncate_indices(struct address_space *mapping,* * Removes folios beginning @index for @nr_pages from filemap in @inode, updates * inode metadata. +* +* Return: 0 on success and negative error otherwise. */ -static void kvm_gmem_truncate_inode_aligned_pages (struct inode *inode, +static long kvm_gmem_truncate_inode_aligned_pages (struct inode *inode,pgoff_t index,size_t nr_pages) {@@ -1191,19 +1228,34 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,long num_freed;pgoff_t idx;void *priv; +long ret; priv =kvm_gmem_allocator_private (inode); nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + ret =0 ; num_freed =0 ;for (idx = index; idx < index + nr_pages; idx += nr_per_huge_page) { - num_freed +=kvm_gmem_truncate_indices ( - inode->i_mapping, idx, nr_per_huge_page); +if (mapping_exiting (inode->i_mapping) || + !kvm_gmem_has_some_shared (inode, idx, nr_per_huge_page)) { + num_freed +=kvm_gmem_truncate_indices ( + inode->i_mapping, idx, nr_per_huge_page); + }else { + ret =kvm_gmem_merge_truncate_indices (inode, idx, + nr_per_huge_page); +if (ret <0 ) +break ; + + num_freed += ret; + ret =0 ; + } }spin_lock (&inode->i_lock); inode->i_blocks -= (num_freed <<PAGE_SHIFT ) /512 ;spin_unlock (&inode->i_lock); + +return ret; }/** @@ -1252,8 +1304,10 @@ static void kvm_gmem_zero_range(struct address_space *mapping,* * Removes full (huge)pages from the filemap and zeroing incomplete * (huge)pages. The pages in the range may be split. +* +* Return: 0 on success and negative error otherwise. */ -static void kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart, +static long kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart,loff_t lend) {pgoff_t full_hpage_start;@@ -1263,6 +1317,7 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,pgoff_t start;pgoff_t end;void *priv; +long ret; priv =kvm_gmem_allocator_private (inode); nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv);@@ -1279,10 +1334,11 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,kvm_gmem_zero_range (inode->i_mapping, start, zero_end); } + ret =0 ;if (full_hpage_end > full_hpage_start) { nr_pages = full_hpage_end - full_hpage_start; -kvm_gmem_truncate_inode_aligned_pages (inode, full_hpage_start, - nr_pages); + ret =kvm_gmem_truncate_inode_aligned_pages ( + inode, full_hpage_start, nr_pages); }if (end > full_hpage_end && end > full_hpage_start) {@@ -1290,6 +1346,8 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,kvm_gmem_zero_range (inode->i_mapping, zero_start, end); } + +return ret; }static long kvm_gmem_punch_hole (struct inode *inode,loff_t offset,loff_t len)@@ -1298,6 +1356,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)pgoff_t start = offset >>PAGE_SHIFT ;pgoff_t end = (offset + len) >>PAGE_SHIFT ;struct kvm_gmem *gmem; +long ret;/* * Bindings must be stable across invalidation to ensure the start+end @@ -1308,8 +1367,9 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_begin_and_zap (gmem, start, end); + ret =0 ;if (kvm_gmem_has_custom_allocator (inode)) { -kvm_gmem_truncate_inode_range (inode, offset, offset + len); + ret =kvm_gmem_truncate_inode_range (inode, offset, offset + len); }else {/* Page size is PAGE_SIZE, so use optimized truncation function. */ truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 );@@ -1320,7 +1380,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)filemap_invalidate_unlock (inode->i_mapping); -return 0 ; +return ret; }static long kvm_gmem_allocate (struct inode *inode,loff_t offset,loff_t len)Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 39/51] KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)
Quoted 37 lines · Ackerley Tng
Quoted 18 lines · Yan Zhao
Quoted 17 lines · Ackerley Tng
Merge and truncate on
fallocate(PUNCH_HOLE), but if the file is being closed, defer merging tofolio_put()callback.Change-Id Iae26987756e70c83f3b121edbc0ed0bc105eec0dSigned-off-by Ackerley Tng <[email protected]>--- virt/kvm/guest_memfd.c | 76 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 8 deletions(-)virt/kvm/guest_memfd.c +0
-0@@ -859,6 +859,35 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,return ret; }Quoted 10 lines
virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 871
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +struct folio *f; +pgoff_t unused; +long num_freed; + +unmap_mapping_pages (inode->i_mapping, index, nr_pages, false); + +if (!kvm_gmem_has_safe_refcount (inode->i_mapping, index, nr_pages, &unused))Yan, thank you for your reviews!
Quoted 3 lines
Why is
kvm_gmem_has_safe_refcount()checked here, but not inkvm_gmem_zero_range()withinkvm_gmem_truncate_inode_range()in patch 33?
Quoted 7 lines
The contract for
guest_memfdwith HugeTLB pages is that if holes are punched in any ranges less than a full huge page, no pages are removed from the filemap. Those ranges are only zeroed.In
kvm_gmem_zero_range(), we never remove any folios, and so there is no need to merge. If there's no need to merge, then we don't need to check for a safe refcount, and can just proceed to zero.
However, if there are still extra ref count to a shared page, its content will be zeroed out.
Quoted 8 lines
kvm_gmem_merge_truncate_indices()is only used during hole punching and not when the file is closed. Hole punch vs file closure is checked usingmapping_exiting(inode->i_mapping).During a hole punch, we will only allow truncation if there are no unexpected refcounts on any subpages, hence this
kvm_gmem_has_safe_refcount()check.
Hmm, I couldn't find a similar refcount check in hugetlbfs_punch_hole(). Did I overlook it?
So, why does guest_memfd require this check when punching a hole?
Quoted 6 lines
Quoted 6 lines
virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 873
Quoted 2 lines
virt/kvm/guest_memfd.c +2
-0+return -EAGAIN ; +Rather than merging the folios, could we simply call
kvm_gmem_truncate_indices()instead?
Quoted 7 lines
Quoted 3 lines
num_freed=kvm_gmem_truncate_indices(inode->i_mapping, index, nr_pages); returnnum_freed;We could do this too, but then that would be deferring the huge page merging to the
folio_put()callback and eventually the kernel worker thread.
With deferring the huge page merging to folio_put(), a benefit is that __kvm_gmem_filemap_add_folio() can be saved for the merged folio. This function is possible to fail and is unnecessary for punch hole as the folio will be removed immediately from the filemap in truncate_inode_folio().
Quoted 10 lines
My goal here is to try to not to defer merging and freeing as much as possible so that most of the page/memory operations are synchronous, because synchronous operations are more predictable.
As an example of improving predictability, in one of the selftests, I do a hole punch and then try to allocate again. Because the merging and freeing of the HugeTLB page sometimes takes too long, the allocation sometimes fails: the guest_memfd's subpool hadn't yet received the freed page back. With a synchronous truncation, the truncation may take longer, but the selftest predictably passes.
Maybe check if guestmem_hugetlb_handle_folio_put() is invoked in the interrupt context, and, if not, invoke the guestmem_hugetlb_cleanup_folio() synchronously?
Quoted 157 lines
Quoted 156 lines
Quoted 156 lines
virt/kvm/guest_memfd.c +56
-8+ f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +return 0 ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); + + num_freed =folio_nr_pages (f); +folio_lock (f); +truncate_inode_folio (inode->i_mapping, f); +folio_unlock (f); + +return num_freed; +} +#else static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,@@ -874,6 +903,12 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode, return 0; } +static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +return 0 ; +} +#endif #else @@ -1182,8 +1217,10 @@ static long kvm_gmem_truncate_indices(struct address_space *mapping,* * Removes folios beginning @index for @nr_pages from filemap in @inode, updates * inode metadata. +* +* Return: 0 on success and negative error otherwise. */ -static void kvm_gmem_truncate_inode_aligned_pages (struct inode *inode, +static long kvm_gmem_truncate_inode_aligned_pages (struct inode *inode,pgoff_t index,size_t nr_pages) {@@ -1191,19 +1228,34 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,long num_freed;pgoff_t idx;void *priv; +long ret; priv =kvm_gmem_allocator_private (inode); nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + ret =0 ; num_freed =0 ;for (idx = index; idx < index + nr_pages; idx += nr_per_huge_page) { - num_freed +=kvm_gmem_truncate_indices ( - inode->i_mapping, idx, nr_per_huge_page); +if (mapping_exiting (inode->i_mapping) || + !kvm_gmem_has_some_shared (inode, idx, nr_per_huge_page)) { + num_freed +=kvm_gmem_truncate_indices ( + inode->i_mapping, idx, nr_per_huge_page); + }else { + ret =kvm_gmem_merge_truncate_indices (inode, idx, + nr_per_huge_page); +if (ret <0 ) +break ; + + num_freed += ret; + ret =0 ; + } }spin_lock (&inode->i_lock); inode->i_blocks -= (num_freed <<PAGE_SHIFT ) /512 ;spin_unlock (&inode->i_lock); + +return ret; }/** @@ -1252,8 +1304,10 @@ static void kvm_gmem_zero_range(struct address_space *mapping,* * Removes full (huge)pages from the filemap and zeroing incomplete * (huge)pages. The pages in the range may be split. +* +* Return: 0 on success and negative error otherwise. */ -static void kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart, +static long kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart,loff_t lend) {pgoff_t full_hpage_start;@@ -1263,6 +1317,7 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,pgoff_t start;pgoff_t end;void *priv; +long ret; priv =kvm_gmem_allocator_private (inode); nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv);@@ -1279,10 +1334,11 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,kvm_gmem_zero_range (inode->i_mapping, start, zero_end); } + ret =0 ;if (full_hpage_end > full_hpage_start) { nr_pages = full_hpage_end - full_hpage_start; -kvm_gmem_truncate_inode_aligned_pages (inode, full_hpage_start, - nr_pages); + ret =kvm_gmem_truncate_inode_aligned_pages ( + inode, full_hpage_start, nr_pages); }if (end > full_hpage_end && end > full_hpage_start) {@@ -1290,6 +1346,8 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,kvm_gmem_zero_range (inode->i_mapping, zero_start, end); } + +return ret; }static long kvm_gmem_punch_hole (struct inode *inode,loff_t offset,loff_t len)@@ -1298,6 +1356,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)pgoff_t start = offset >>PAGE_SHIFT ;pgoff_t end = (offset + len) >>PAGE_SHIFT ;struct kvm_gmem *gmem; +long ret;/* * Bindings must be stable across invalidation to ensure the start+end @@ -1308,8 +1367,9 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_begin_and_zap (gmem, start, end); + ret =0 ;if (kvm_gmem_has_custom_allocator (inode)) { -kvm_gmem_truncate_inode_range (inode, offset, offset + len); + ret =kvm_gmem_truncate_inode_range (inode, offset, offset + len); }else {/* Page size is PAGE_SIZE, so use optimized truncation function. */ truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 );@@ -1320,7 +1380,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)filemap_invalidate_unlock (inode->i_mapping); -return 0 ; +return ret; }static long kvm_gmem_allocate (struct inode *inode,loff_t offset,loff_t len)Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 39/51] KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)
Quoted 21 lines · Yan Zhao
Quoted 20 lines · Ackerley Tng
Quoted 18 lines · Yan Zhao
Quoted 17 lines · Ackerley Tng
Merge and truncate on
fallocate(PUNCH_HOLE), but if the file is being closed, defer merging tofolio_put()callback.Change-Id Iae26987756e70c83f3b121edbc0ed0bc105eec0dSigned-off-by Ackerley Tng <[email protected]>--- virt/kvm/guest_memfd.c | 76 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 8 deletions(-)virt/kvm/guest_memfd.c +0
-0@@ -859,6 +859,35 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,return ret; }
Quoted 13 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
virt/kvm/guest_memfd.c +4
-0+static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +struct folio *f;Quoted 9 lines
Quoted 6 lines
virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 871
Quoted 6 lines
virt/kvm/guest_memfd.c +6
-0+pgoff_t unused; +long num_freed; + +unmap_mapping_pages (inode->i_mapping, index, nr_pages, false); + +if (!kvm_gmem_has_safe_refcount (inode->i_mapping, index, nr_pages, &unused))Yan, thank you for your reviews!
Thanks again for your reviews. I would like to respond to this since I'm finally getting back to this part.
Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Why is
kvm_gmem_has_safe_refcount()checked here, but not inkvm_gmem_zero_range()withinkvm_gmem_truncate_inode_range()in patch 33?The contract for
guest_memfdwith HugeTLB pages is that if holes are punched in any ranges less than a full huge page, no pages are removed from the filemap. Those ranges are only zeroed.
Quoted 6 lines
Quoted 3 lines
In
kvm_gmem_zero_range(), we never remove any folios, and so there is no need to merge. If there's no need to merge, then we don't need to check for a safe refcount, and can just proceed to zero.However, if there are still extra ref count to a shared page, its content will be zeroed out.
I believe this topic is kind of overtaken by events. IIUC the current upstream stance is that for guest_memfd we're not allowing hole-punching of pages for huge pages, so once a HugeTLB guest_memfd is requested, hole punching of less than the requested HugeTLB size will result in -EINVAL being returned to userspace.
Quoted 5 lines
Quoted 5 lines
kvm_gmem_merge_truncate_indices()is only used during hole punching and not when the file is closed. Hole punch vs file closure is checked usingmapping_exiting(inode->i_mapping).
Quoted 8 lines
Quoted 3 lines
During a hole punch, we will only allow truncation if there are no unexpected refcounts on any subpages, hence this
kvm_gmem_has_safe_refcount()check.Hmm, I couldn't find a similar refcount check in
hugetlbfs_punch_hole(). Did I overlook it?So, why does
guest_memfdrequire this check when punching a hole?
There's no equivalent check in HugeTLBfs.
For guest_memfd, we want to defer merging to the kernel worker as little as possible, hence we want to merge before truncating. Checking for elevated refcounts is a prerequisite for merging, not directly for hole punching.
Quoted 10 lines
Quoted 10 lines
Quoted 9 lines
virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 873
Quoted 2 lines
virt/kvm/guest_memfd.c +2
-0+return -EAGAIN ; +Rather than merging the folios, could we simply call
kvm_gmem_truncate_indices()instead?
num_freed=kvm_gmem_truncate_indices(inode->i_mapping, index, nr_pages); returnnum_freed;
Quoted 9 lines
Quoted 3 lines
We could do this too, but then that would be deferring the huge page merging to the
folio_put()callback and eventually the kernel worker thread.With deferring the huge page merging to
folio_put(), a benefit is that__kvm_gmem_filemap_add_folio()can be saved for the merged folio. This function is possible to fail and is unnecessary for punch hole as the folio will be removed immediately from the filemap intruncate_inode_folio().
That is a good point! Definitely sounds good to defer this to folio_put().
Quoted 10 lines
Quoted 10 lines
My goal here is to try to not to defer merging and freeing as much as possible so that most of the page/memory operations are synchronous, because synchronous operations are more predictable.
As an example of improving predictability, in one of the selftests, I do a hole punch and then try to allocate again. Because the merging and freeing of the HugeTLB page sometimes takes too long, the allocation sometimes fails: the guest_memfd's subpool hadn't yet received the freed page back. With a synchronous truncation, the truncation may take longer, but the selftest predictably passes.
Quoted 5 lines
Maybe check if
guestmem_hugetlb_handle_folio_put()is invoked in the interrupt context, and, if not, invoke theguestmem_hugetlb_cleanup_folio()synchronously?
I think this is a good idea. I would like to pursue this in a future revision of a patch series.
It seems like the use of in_atomic() is strongly discouraged, do you have any tips on how to determine if folio_put() is being called from atomic context?
Quoted 3 lines
Quoted 3 lines
[...snip...]
RFC PATCH v2 40/51 KVM: guest_memfd: Update kvm_gmem_mapping_order to account for page status
In reply to Ackerley Tngkvm_gmem_mapping_order() should return the maximum mapping order for a gfn if a page were to be faulted in for that gfn.
For inodes that support a custom allocator, the maximum mapping order should be determined by the custom allocator in conjunction with guest_memfd.
This patch updates kvm_gmem_mapping_order() to take into account that for the guestmem_hugetlb custom allocator, pages are split if any page in a huge page range is shared.
--- virt/kvm/guest_memfd.c | 72 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 62 insertions(+), 10 deletions(-)
virt/kvm/guest_memfd.c +62 -10
@@ -709,19 +709,27 @@ static int kvm_gmem_split_folio_in_filemap(struct inode *inode, struct folio *foreturn ret; } +static inline bool kvm_gmem_should_split_at_index (struct inode *inode, +pgoff_t index) +{ +pgoff_t index_floor; +size_t nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + index_floor =round_down (index, nr_pages); + +return kvm_gmem_has_some_shared (inode, index_floor, nr_pages); +} +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode,struct folio *folio) { -size_t to_nr_pages; -void *priv; -if (!kvm_gmem_has_custom_allocator (inode))return 0 ; - priv =kvm_gmem_allocator_private (inode); - to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); - -if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages)) +if (kvm_gmem_should_split_at_index (inode, folio->index))return kvm_gmem_split_folio_in_filemap (inode, folio);return 0 ;
@@ -890,6 +898,12 @@ static long kvm_gmem_merge_truncate_indices(struct inode *inode, pgoff_t index,#else +static inline bool kvm_gmem_should_split_at_index (struct inode *inode, +pgoff_t index) +{ +return false; +} +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode,struct folio *folio) {
@@ -1523,7 +1537,7 @@ static inline struct file *kvm_gmem_get_file(struct kvm_memory_slot *slot)return get_file_active (&slot->gmem.file); } -static pgoff_t kvm_gmem_get_index (struct kvm_memory_slot *slot,gfn_t gfn) +static pgoff_t kvm_gmem_get_index (const struct kvm_memory_slot *slot,gfn_t gfn) {return gfn - slot->base_gfn + slot->gmem.pgoff; }
@@ -2256,14 +2270,52 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,EXPORT_SYMBOL_GPL (kvm_gmem_get_pfn);/** -* Returns the mapping order for this @gfn in @slot. +* kvm_gmem_mapping_order() - Get the mapping order for this @gfn in @slot. +* +* @slot: the memslot that gfn belongs to. +* @gfn: the gfn to look up mapping order for. * * This is equal to max_order that would be returned if kvm_gmem_get_pfn() were * called now. +* +* Return: the mapping order for this @gfn in @slot. */ int kvm_gmem_mapping_order (const struct kvm_memory_slot *slot,gfn_t gfn) { -return 0 ; +struct inode *inode; +struct file *file; +int ret; + + file =kvm_gmem_get_file ((struct kvm_memory_slot *)slot); +if (!file) +return 0 ; + + inode =file_inode (file); + + ret =0 ; +if (kvm_gmem_has_custom_allocator (inode)) { +bool should_split; +pgoff_t index; + + index =kvm_gmem_get_index (slot, gfn); + +filemap_invalidate_lock_shared (inode->i_mapping); + should_split =kvm_gmem_should_split_at_index (inode, index); +filemap_invalidate_unlock_shared (inode->i_mapping); + +if (!should_split) { +size_t nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + ret =ilog2 (nr_pages); + } + } + +fput (file); +return ret; }EXPORT_SYMBOL_GPL (kvm_gmem_mapping_order);
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 41/51 KVM: Add CAP to indicate support for HugeTLB as custom allocator
In reply to Ackerley TngIf this CAP returns true, then guestmem_hugetlb can be used as a custom allocator for guest_memfd.
--- include/uapi/linux/kvm.h | 1 + virt/kvm/kvm_main.c | 4 ++++ 2 files changed, 5 insertions(+)
include/uapi/linux/kvm.h +1 -0
@@ -932,6 +932,7 @@ struct kvm_enable_cap {#define KVM_CAP_ARM_WRITABLE_IMP_ID_REGS 239#define KVM_CAP_GMEM_SHARED_MEM 240#define KVM_CAP_GMEM_CONVERSION 241 +#define KVM_CAP_GMEM_HUGETLB 242struct kvm_irq_routing_irqchip {__u32 irqchip;
virt/kvm/kvm_main.c +4 -0
@@ -4845,6 +4845,10 @@ static int kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)case KVM_CAP_GMEM_SHARED_MEM :case KVM_CAP_GMEM_CONVERSION :return true; +#endif +#ifdef CONFIG_KVM_GMEM_HUGETLB +case KVM_CAP_GMEM_HUGETLB : +return true;#endif default :break ;
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 42/51 KVM: selftests: Add basic selftests for hugetlb-backed guest_memfd
In reply to Ackerley TngAdd tests for 2MB and 1GB page sizes, and update the invalid flags test for GUEST_MEMFD_FLAG_HUGETLB.
In tests, touch every page but not every byte in page to save time while testing.
--- .../testing/selftests/kvm/guest_memfd_test.c | 94 +++++++++++++------ 1 file changed, 67 insertions(+), 27 deletions(-)
tools/testing/selftests/kvm/guest_memfd_test.c +67 -27
@@ -13,6 +13,8 @@#include <linux/bitmap.h> #include <linux/falloc.h> +#include <linux/guestmem.h> +#include <linux/sizes.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h>
@@ -38,6 +40,7 @@ static void test_file_read_write(int fd)static void test_faulting_allowed (int fd,size_t page_size,size_t total_size) {const char val =0xaa ; +size_t increment;char *mem;size_t i;int ret;
@@ -45,21 +48,25 @@ static void test_faulting_allowed(int fd, size_t page_size, size_t total_size) mem =mmap (NULL , total_size,PROT_READ |PROT_WRITE ,MAP_SHARED , fd,0 );TEST_ASSERT (mem !=MAP_FAILED ,"mmaping() guest memory should pass." ); -memset (mem, val, total_size); -for (i =0 ; i < total_size; i++) + increment = page_size >>1 ; + +for (i =0 ; i < total_size; i += increment) + mem[i] = val; +for (i =0 ; i < total_size; i += increment)TEST_ASSERT_EQ (mem[i], val); ret =fallocate (fd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE ,0 , page_size);TEST_ASSERT (!ret,"fallocate the first page should succeed" ); -for (i =0 ; i < page_size; i++) +for (i =0 ; i < page_size; i += increment)TEST_ASSERT_EQ (mem[i],0x00 ); -for (; i < total_size; i++) +for (; i < total_size; i += increment)TEST_ASSERT_EQ (mem[i], val); -memset (mem, val, total_size); -for (i =0 ; i < total_size; i++) +for (i =0 ; i < total_size; i += increment) + mem[i] = val; +for (i =0 ; i < total_size; i += increment)TEST_ASSERT_EQ (mem[i], val); ret =munmap (mem, total_size);
@@ -209,7 +216,7 @@ static void test_create_guest_memfd_invalid_sizes(struct kvm_vm *vm,size_t size;int fd; -for (size =1 ; size < page_size; size++) { +for (size =1 ; size < page_size; size += (page_size >>1 )) { fd =__vm_create_guest_memfd (vm, size, guest_memfd_flags); TEST_ASSERT(fd == -1 && errno == EINVAL, "guest_memfd() with non-page-aligned page size '0x%lx' should fail with EINVAL",
@@ -217,28 +224,33 @@ static void test_create_guest_memfd_invalid_sizes(struct kvm_vm *vm, } } -static void test_create_guest_memfd_multiple (struct kvm_vm *vm) +static void test_create_guest_memfd_multiple (struct kvm_vm *vm, +uint64_t guest_memfd_flags, +size_t page_size) {int fd1, fd2, ret;struct stat st1, st2; - fd1 =__vm_create_guest_memfd (vm,4096 ,0 ); + fd1 =__vm_create_guest_memfd (vm, page_size, guest_memfd_flags);TEST_ASSERT (fd1 !=-1 ,"memfd creation should succeed" ); ret =fstat (fd1, &st1);TEST_ASSERT (ret !=-1 ,"memfd fstat should succeed" ); -TEST_ASSERT (st1.st_size ==4096 ,"memfd st_size should match requested size" ); +TEST_ASSERT (st1.st_size == page_size,"memfd st_size should match requested size" ); - fd2 =__vm_create_guest_memfd (vm,8192 ,0 ); + fd2 =__vm_create_guest_memfd (vm, page_size *2 , guest_memfd_flags);TEST_ASSERT (fd2 !=-1 ,"memfd creation should succeed" ); ret =fstat (fd2, &st2);TEST_ASSERT (ret !=-1 ,"memfd fstat should succeed" ); -TEST_ASSERT (st2.st_size ==8192 ,"second memfd st_size should match requested size" ); +TEST_ASSERT (st2.st_size == page_size *2 , +"second memfd st_size should match requested size" ); + ret =fstat (fd1, &st1);TEST_ASSERT (ret !=-1 ,"memfd fstat should succeed" ); -TEST_ASSERT (st1.st_size ==4096 ,"first memfd st_size should still match requested size" ); +TEST_ASSERT (st1.st_size == page_size, +"first memfd st_size should still match requested size" );TEST_ASSERT (st1.st_ino != st2.st_ino,"different memfd should have different inode numbers" );close (fd2);
@@ -449,21 +461,13 @@ static void test_guest_memfd_features(struct kvm_vm *vm, size_t page_size,close (fd); } -static void test_with_type (unsigned long vm_type,uint64_t guest_memfd_flags, -bool expect_mmap_allowed) +static void test_guest_memfd_features_for_page_size (struct kvm_vm *vm, +uint64_t guest_memfd_flags, +size_t page_size, +bool expect_mmap_allowed) { -struct kvm_vm *vm; -size_t page_size; +test_create_guest_memfd_multiple (vm, guest_memfd_flags, page_size); -if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type))) -return ; - - vm =vm_create_barebones_type (vm_type); - -test_create_guest_memfd_multiple (vm); -test_bind_guest_memfd_wrt_userspace_addr (vm); - - page_size =getpagesize ();if (guest_memfd_flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED ) {test_guest_memfd_features (vm, page_size, guest_memfd_flags, expect_mmap_allowed, true);
@@ -479,6 +483,34 @@ static void test_with_type(unsigned long vm_type, uint64_t guest_memfd_flags,test_guest_memfd_features (vm, page_size, guest_memfd_flags, expect_mmap_allowed, false); } +} + +static void test_with_type (unsigned long vm_type,uint64_t base_flags, +bool expect_mmap_allowed) +{ +struct kvm_vm *vm; +uint64_t flags; + +if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type))) +return ; + + vm =vm_create_barebones_type (vm_type); + +test_bind_guest_memfd_wrt_userspace_addr (vm); + +printf ("Test guest_memfd with 4K pages for vm_type %ld\n" , vm_type); +test_guest_memfd_features_for_page_size (vm, base_flags,getpagesize (), expect_mmap_allowed); +printf ("\tPASSED\n" ); + +printf ("Test guest_memfd with 2M pages for vm_type %ld\n" , vm_type); + flags = base_flags |GUEST_MEMFD_FLAG_HUGETLB |GUESTMEM_HUGETLB_FLAG_2MB ; +test_guest_memfd_features_for_page_size (vm, flags,SZ_2M , expect_mmap_allowed); +printf ("\tPASSED\n" ); + +printf ("Test guest_memfd with 1G pages for vm_type %ld\n" , vm_type); + flags = base_flags |GUEST_MEMFD_FLAG_HUGETLB |GUESTMEM_HUGETLB_FLAG_1GB ; +test_guest_memfd_features_for_page_size (vm, flags,SZ_1G , expect_mmap_allowed); +printf ("\tPASSED\n" );kvm_vm_release (vm); }
@@ -486,9 +518,14 @@ static void test_with_type(unsigned long vm_type, uint64_t guest_memfd_flags,static void test_vm_with_gmem_flag (struct kvm_vm *vm,uint64_t flag,bool expect_valid) { -size_t page_size =getpagesize (); +size_t page_size;int fd; +if (flag ==GUEST_MEMFD_FLAG_HUGETLB ) + page_size =get_def_hugetlb_pagesz (); +else + page_size =getpagesize (); + fd =__vm_create_guest_memfd (vm, page_size, flag);if (expect_valid) {
@@ -550,6 +587,9 @@ static void test_gmem_flag_validity(void)/* After conversions are supported, all VM types support shared mem. */ uint64_t valid_flags =GUEST_MEMFD_FLAG_SUPPORT_SHARED ; +if (kvm_has_cap (KVM_CAP_GMEM_HUGETLB )) + valid_flags |=GUEST_MEMFD_FLAG_HUGETLB ; +test_vm_type_gmem_flag_validity (VM_TYPE_DEFAULT , valid_flags);#ifdef __x86_64__
Signature · 1 line
2.49.0.1045.g170613ef41-goog