1G page support for guest_memfd
Subsystems (22)
Re: [POC PATCH 3/5] memory/guest_memfd: Enable in-place conversion when available
In reply to Xiaoyao LiQuoted 126 lines · Xiaoyao Li
From: Yan Zhao <[email protected]>
(This is just the POC code to use in-place conversion gmem.)
Try to use in-place conversion gmem when it is supported.
When in-place conversion is enabled, there is no need to discard memory since it still needs to be used as the memory of opposite attribute after conversion.
For a upstreamable solution, we can introduce memory-backend-guestmemfd for in-place conversion. With the non in-place conversion, it needs seperate non-gmem memory to back the shared memory and gmem is created implicitly and internally based on vm type. While with in-place conversion, there is no need for seperate non-gmem memory because gmem itself can be served as shared memory. So that we can introduce memory-backend-guestmemfd as the specific backend for in-place conversion gmem.
Signed-off-by Yan Zhao <[email protected]>Co-developed-by Xiaoyao Li <[email protected]>
Signed-off-by Xiaoyao Li <[email protected]>--- accel/kvm/kvm-all.c | 79 ++++++++++++++++++++++++++++----------- accel/stubs/kvm-stub.c | 1 + include/system/kvm.h | 1 + include/system/memory.h | 2 + include/system/ramblock.h | 1 + system/memory.c | 7 ++++ system/physmem.c | 21 ++++++++++- 7 files changed, 90 insertions(+), 22 deletions(-)accel/kvm/kvm-all.c +38
-10@@ -105,6 +105,7 @@ static int kvm_sstep_flags;static bool kvm_immediate_exit;static uint64_t kvm_supported_memory_attributes;static bool kvm_guest_memfd_supported; +bool kvm_guest_memfd_inplace_supported;static hwaddr kvm_max_slot_size = ~0 ;static const KVMCapabilityInfo kvm_required_capabilites[] = {@@ -1487,6 +1488,30 @@ static int kvm_set_memory_attributes(hwaddr start, uint64_t size, uint64_t attr)return r; } +static int kvm_set_guest_memfd_shareability (MemoryRegion *mr,ram_addr_t offset, +uint64_t size,bool shared) +{ +int guest_memfd = mr->ram_block->guest_memfd; +struct kvm_gmem_convert param = { + .offset = offset, + .size = size, + .error_offset =0 , + }; +unsigned long op; +int r; + + op = shared ?KVM_GMEM_CONVERT_SHARED :KVM_GMEM_CONVERT_PRIVATE ; + + r =ioctl (guest_memfd, op, ¶m); +if (r) { +error_report ("failed to set guest_memfd offset 0x%lx size 0x%lx to %s " +"error '%s' error offset 0x%llx" , + offset, size, shared ?"shared" :"private" , +strerror (errno), param.error_offset); + } +return r; +} +int kvm_set_memory_attributes_private (hwaddr start,uint64_t size) {return kvm_set_memory_attributes (start, size,KVM_MEMORY_ATTRIBUTE_PRIVATE );@@ -1604,7 +1629,8 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,abort (); } -if (memory_region_has_guest_memfd (mr)) { +if (memory_region_has_guest_memfd (mr) && + !memory_region_guest_memfd_in_place_conversion (mr)) { err =kvm_set_memory_attributes_private (start_addr, slot_size);if (err) { error_report("%s: failed to set memory attribute private: %s",@@ -2779,6 +2805,9 @@ static int kvm_init(AccelState *as, MachineState *ms)kvm_check_extension (s,KVM_CAP_GUEST_MEMFD ) &&kvm_check_extension (s,KVM_CAP_USER_MEMORY2 ) && (kvm_supported_memory_attributes &KVM_MEMORY_ATTRIBUTE_PRIVATE ); + kvm_guest_memfd_inplace_supported = +kvm_check_extension (s,KVM_CAP_GMEM_SHARED_MEM ) && +kvm_check_extension (s,KVM_CAP_GMEM_CONVERSION ); kvm_pre_fault_memory_supported =kvm_vm_check_extension (s,KVM_CAP_PRE_FAULT_MEMORY );if (s->kernel_irqchip_split ==ON_OFF_AUTO_AUTO ) {@@ -3056,6 +3085,7 @@ static void kvm_eat_signals(CPUState *cpu)int kvm_convert_memory (hwaddr start,hwaddr size,bool to_private) { +bool in_place_conversion = false;MemoryRegionSection section;ram_addr_t offset;MemoryRegion *mr;@@ -3112,18 +3142,23 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) goto out_unref; } -if (to_private) { - ret =kvm_set_memory_attributes_private (start, size); - }else { - ret =kvm_set_memory_attributes_shared (start, size); - } -if (ret) { - goto out_unref; - } - addr =memory_region_get_ram_ptr (mr) + section.offset_within_region; rb =qemu_ram_block_from_host (addr, false, &offset); + in_place_conversion =memory_region_guest_memfd_in_place_conversion (mr); +if (in_place_conversion) { + ret =kvm_set_guest_memfd_shareability (mr, offset, size, !to_private); + }else { +if (to_private) { + ret =kvm_set_memory_attributes_private (start, size); + }else {
accel/kvm/kvm-all.c int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) · line 3164
Quoted 10 lines
accel/kvm/kvm-all.c +7
-0+ ret =kvm_set_memory_attributes_shared (start, size); + } + } +if (ret) { + goto out_unref; + } + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), offset, size, to_private);if (ret) {
There's one thing required for shared device assignment with in-place conversion, we need to follow the sequence of unmap-before-conversion-to-private and map-after-conversion-to-shared. Maybe change it like:
accel/kvm/kvm-all.c +20 -7
@@ -3146,6 +3146,17 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) addr =memory_region_get_ram_ptr (mr) + section.offset_within_region; rb =qemu_ram_block_from_host (addr, false, &offset); +if (to_private) { + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), + offset, size, to_private); +if (ret) { +error_report ("Failed to notify the listener the state change of " +"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , + start, size, to_private ?"private" :"shared" ); + goto out_unref; + } + } + in_place_conversion =memory_region_guest_memfd_in_place_conversion (mr);if (in_place_conversion) { ret =kvm_set_guest_memfd_shareability (mr, offset, size, !to_private);
@@ -3160,13 +3171,15 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) goto out_unref; } - ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), - offset, size, to_private); -if (ret) { -error_report ("Failed to notify the listener the state change of " -"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , - start, size, to_private ?"private" :"shared" ); - goto out_unref; +if (!to_private) { + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), + offset, size, to_private); +if (ret) { +error_report ("Failed to notify the listener the state change of " +"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , + start, size, to_private ?"private" :"shared" ); + goto out_unref; + } }
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Ackerley TngQuoted 33 lines · Ackerley Tng
Quoted 21 lines · Yan Zhao
Quoted 8 lines · Vishal Annapurve
Quoted 7 lines · Jason Gunthorpe
Quoted 4 lines · Alexey Kardashevskiy
Now, I am rebasing my RFC on top of this patchset and it fails in
kvm_gmem_has_safe_refcount()as IOMMU holds references to all these folios in my RFC.Quoted 7 lines
Quoted 3 lines
Quoted 3 lines
So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB
As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely onguest_memfdfor pinning -> no page refcounts taken by IOMMU stackIn TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.Quoted 9 lines
If IOMMU side does not increase refcount, IMHO, some way to indicate that certain PFNs are used by TDs for DMA is still required, so
guest_memfdcan reject the request before attempting the actual unmap. Otherwise, the unmap of TD-DMA-pinned pages will fail.Upon this kind of unmapping failure, it also doesn't help for host to retry unmapping without unpinning from TD.
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 range
It is the Guest fw call to release the pinning. 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 3 lines
2. IOMMU forwards the notification to TDX code in the kernel
3. TDX code in kernel tells TDX module to stop thinking of any PFNs in the range as pinned for DMA?
TDX host can't stop the pinning. Actually this mechanism is to prevent host from unpin/unmap the DMA out of Guest expectation.
Thanks,
Yilun
Quoted 4 lines
If the above is possible then by the time we get to unmapping from S-EPTs, TDX module would already consider the PFNs in the range "not pinned for DMA".
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 34 lines · Xu Yilun
Quoted 33 lines · Ackerley Tng
Quoted 30 lines · Yan Zhao
Quoted 8 lines · Vishal Annapurve
Quoted 7 lines · Jason Gunthorpe
Quoted 4 lines · Alexey Kardashevskiy
Now, I am rebasing my RFC on top of this patchset and it fails in
kvm_gmem_has_safe_refcount()as IOMMU holds references to all these folios in my RFC.Quoted 7 lines
Quoted 3 lines
Quoted 3 lines
So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB
As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely onguest_memfdfor pinning -> no page refcounts taken by IOMMU stackIn TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.If IOMMU side does not increase refcount, IMHO, some way to indicate that certain PFNs are used by TDs for DMA is still required, so
guest_memfdcan reject the request before attempting the actual unmap. Otherwise, the unmap of TD-DMA-pinned pages will fail.Upon this kind of unmapping failure, it also doesn't help for host to retry unmapping without unpinning from TD.
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.
If by the time KVM gets the conversion request, the page is unpinned, then we're all good, right?
When guest_memfd gets the conversion request, as part of conversion handling it will request to zap the page from stage-2 page tables. TDX module would see that the page is unpinned and the unmapping will proceed fine. Is that understanding correct?
Quoted 7 lines
Quoted 3 lines
2. IOMMU forwards the notification to TDX code in the kernel
3. TDX code in kernel tells TDX module to stop thinking of any PFNs in the range as pinned for DMA?TDX host can't stop the pinning. Actually this mechanism is to prevent host from unpin/unmap the DMA out of Guest expectation.
On this note, I'd also like to check something else. Putting TDX connect and IOMMUs aside, if the host unmaps a guest private page today without the guest requesting it, the unmapping will work and the guest will be broken, right?
Quoted 7 lines
Thanks,
YilunQuoted 4 lines
If the above is possible then by the time we get to unmapping from S-EPTs, TDX module would already consider the PFNs in the range "not pinned for DMA".
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 45 lines · Ackerley Tng
Quoted 34 lines · Xu Yilun
Quoted 33 lines · Ackerley Tng
Quoted 30 lines · Yan Zhao
Quoted 8 lines · Vishal Annapurve
Quoted 7 lines · Jason Gunthorpe
Quoted 4 lines · Alexey Kardashevskiy
Now, I am rebasing my RFC on top of this patchset and it fails in
kvm_gmem_has_safe_refcount()as IOMMU holds references to all these folios in my RFC.Quoted 7 lines
Quoted 3 lines
Quoted 3 lines
So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB
As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely onguest_memfdfor pinning -> no page refcounts taken by IOMMU stackIn TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.If IOMMU side does not increase refcount, IMHO, some way to indicate that certain PFNs are used by TDs for DMA is still required, so
guest_memfdcan reject the request before attempting the actual unmap. Otherwise, the unmap of TD-DMA-pinned pages will fail.Upon this kind of unmapping failure, it also doesn't help for host to retry unmapping without unpinning from TD.
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 7 lines
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.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. Guest would invoke a fw call tdg.mem.page.release to unpin the page before KVM_HC_MAP_GPA_RANGE.
Quoted 5 lines
When
guest_memfdgets the conversion request, as part of conversion handling it will request to zap the page from stage-2 page tables. TDX module would see that the page is unpinned and the unmapping will proceed fine. Is that understanding correct?
Yes, again unless guess doesn't unpin.
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
2. IOMMU forwards the notification to TDX code in the kernel
3. TDX code in kernel tells TDX module to stop thinking of any PFNs in the range as pinned for DMA?
Quoted 8 lines
Quoted 3 lines
TDX host can't stop the pinning. Actually this mechanism is to prevent host from unpin/unmap the DMA out of Guest expectation.
On this note, I'd also like to check something else. Putting TDX connect and IOMMUs aside, if the host unmaps a guest private page today without the guest requesting it, the unmapping will work and the guest will be broken, right?
Correct. The unmapping will work, the guest can't continue anymore.
Thanks,
Yilun
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 6 lines · Xu Yilun
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. Guest would invoke a fw call tdg.mem.page.release to unpin the page before
KVM_HC_MAP_GPA_RANGE.
What does guest pinning mean?
Jason
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Xu YilunQuoted 51 lines · Xu Yilun
Quoted 50 lines · Ackerley Tng
Quoted 34 lines · Xu Yilun
Quoted 33 lines · Ackerley Tng
Quoted 30 lines · Yan Zhao
Quoted 8 lines · Vishal Annapurve
Quoted 7 lines · Jason Gunthorpe
Quoted 4 lines · Alexey Kardashevskiy
Now, I am rebasing my RFC on top of this patchset and it fails in
kvm_gmem_has_safe_refcount()as IOMMU holds references to all these folios in my RFC.Quoted 7 lines
Quoted 3 lines
Quoted 3 lines
So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB
As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely onguest_memfdfor pinning -> no page refcounts taken by IOMMU stackIn TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.If IOMMU side does not increase refcount, IMHO, some way to indicate that certain PFNs are used by TDs for DMA is still required, so
guest_memfdcan reject the request before attempting the actual unmap. Otherwise, the unmap of TD-DMA-pinned pages will fail.Upon this kind of unmapping failure, it also doesn't help for host to retry unmapping without unpinning from TD.
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 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? :-(
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?
Ira
Quoted 30 lines
Guest would
invoke a fw call tdg.mem.page.release to unpin the page beforeKVM_HC_MAP_GPA_RANGE.Quoted 5 lines
When
guest_memfdgets the conversion request, as part of conversion handling it will request to zap the page from stage-2 page tables. TDX module would see that the page is unpinned and the unmapping will proceed fine. Is that understanding correct?Yes, again unless guess doesn't unpin.
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
2. IOMMU forwards the notification to TDX code in the kernel
3. TDX code in kernel tells TDX module to stop thinking of any PFNs in the range as pinned for DMA?Quoted 8 lines
Quoted 3 lines
TDX host can't stop the pinning. Actually this mechanism is to prevent host from unpin/unmap the DMA out of Guest expectation.
On this note, I'd also like to check something else. Putting TDX connect and IOMMUs aside, if the host unmaps a guest private page today without the guest requesting it, the unmapping will work and the guest will be broken, right?
Correct. The unmapping will work, the guest can't continue anymore.
Thanks,
Yilun
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
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?
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
In reply to Jason GunthorpeQuoted 9 lines · Jason Gunthorpe
Quoted 6 lines · Xu Yilun
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. Guest would invoke a fw call tdg.mem.page.release to unpin the page before
KVM_HC_MAP_GPA_RANGE.What does guest pinning mean?
TDX firmware provides a mode, that host can't block the S-EPT mapping after TD accepts the mapping. Guest 'pins' the private mapping (KVM & IOMMU).
TD should explicitly unaccept the page by tdg.mem.page.release, then host could successfully block/unmap the S-EPT. This is necessary when shared <-> private conversion.
When TDX Connect is enabled, this mode is enforced.
Thanks,
Yilun
Quoted 3 lines
Jason
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Xu YilunQuoted 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 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ackerley TngQuoted 4 lines · Ackerley Tng
(quoted diff) +4
-0+static enum shareability kvm_gmem_shareability_get(struct inode *inode, + pgoff_t index) +{ + struct maple_tree *mt;
Review
Quoted 10 lines
(quoted diff) +10
-0+ void *entry; + + mt = &kvm_gmem_private(inode)->shareability; + entry = mtree_load(mt, index); + WARN(!entry, + "Shareability should always be defined for all indices in inode."); + + return xa_to_value(entry); +} +
Hi Ackerley,
Not sure if it's a known issue. Just want to let you know in case you're unaware.
During a test to repeatedly launching/destroying TDs, I encountered a warning from kvm_gmem_shareability_get() (see the attached log at the bottom). The reproducing rate is 1 in every 20-100 times of launching TD.
After some analysis, I found that the warning was produced by kvm_gmem_shareability_get() when it's called from kvm_gmem_is_private(), which is not protected by any locks.
I can get rid of the warning by either fix 1 or fix 2 below. (I prefer fix 1 though :))
fix 1:
virt/kvm/guest_memfd.c +1 -1
@@ -2024,7 +2024,7 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,#ifdef CONFIG_KVM_GMEM_SHARED_MEM if (flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { -mt_init (&private->shareability); +mt_init_flags (&private->shareability,MT_FLAGS_USE_RCU ); err =kvm_gmem_shareability_setup (private, size, flags);if (err)
fix 2:
virt/kvm/guest_memfd.c +2 -0
@@ -171,7 +171,9 @@ static enum shareability kvm_gmem_shareability_get(struct inode *inode,void *entry; mt = &kvm_gmem_private (inode)->shareability; +mtree_lock (mt); entry =mtree_load (mt, index); +mtree_unlock (mt);WARN (!entry,"Shareability should always be defined for all indices in inode." );
Thanks
Yan
[ 845.253021] ------------[ cut here ]------------ [ 845.259236] Shareability should always be defined for all indices in inode. [ 845.259273] WARNING: CPU: 148 PID: 3775 at arch/x86/kvm/../../../virt/kvm/guest_memfd.c:175 kvm_gmem_shareability_get.isra.0+0x39/0x50 [kvm] [ 845.283330] Modules linked in: kvm_intel i2c_i801 idxd i2c_smbus i2c_ismt kvm irqbypass nls_iso8859_1 nls_cp437 squashfs ghash_clmulni_intel hid_generic aesni_intel [ 845.300914] CPU: 148 UID: 0 PID: 3775 Comm: qemu-system-x86 Tainted: G S 6.16.0-rc6-upstream+ #520 PREEMPT(voluntary) 49e4d0c13b52dd8fe7006bbbb80b018c4576ab2d [ 845.319631] Tainted: [S]=CPU_OUT_OF_SPEC [ 845.324956] Hardware name: Intel Corporation ArcherCity/ArcherCity, BIOS EGSDCRB1.SYS.0101.D29.2303301937 03/30/2023 [ 845.337749] RIP: 0010:kvm_gmem_shareability_get.isra.0+0x39/0x50 [kvm] [ 845.346085] Code: bf 48 02 00 00 e8 a7 d4 08 d1 48 85 c0 74 09 c9 48 d1 e8 c3 cc cc cc cc 48 89 45 f8 90 48 c7 c7 a0 56 5c c0 e8 68 3c b5 cf 90 <0f> 0b 90 90 48 8b 45 f8 c9 48 d1 e8 c3 cc cc cc cc 66 0f 1f 44 00 [ 845.368227] RSP: 0018:ff29e9c2e336baa0 EFLAGS: 00010282 [ 845.375038] RAX: 0000000000000000 RBX: 00000000001825d4 RCX: 0000000000000000 [ 845.384020] RDX: 0000000000000002 RSI: 0000000000000001 RDI: 00000000ffffffff [ 845.392966] RBP: ff29e9c2e336baa8 R08: 0000000000000000 R09: 0000000000000000 [ 845.401912] R10: 0000000000000001 R11: 0000000000000000 R12: ff1236f76e067a80 [ 845.410878] R13: ff1236f76e0ecc00 R14: 0000000000000000 R15: ff1236f783af8000 [ 845.419850] FS: 00007f8b863fc6c0(0000) GS:ff12370458883000(0000) knlGS:0000000000000000 [ 845.429915] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 845.437304] CR2: 0000000000000000 CR3: 00000003e9989005 CR4: 0000000000773ef0 [ 845.446265] PKRU: 55555554 [ 845.450224] Call Trace: [ 845.453887] <TASK> [ 845.457161] kvm_gmem_is_private+0x4b/0x70 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.467348] kvm_mmu_faultin_pfn+0x14a/0x360 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.477740] kvm_tdp_page_fault+0x97/0xf0 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.487843] kvm_mmu_do_page_fault+0x23d/0x290 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.505524] ? __this_cpu_preempt_check+0x13/0x20 [ 845.515349] kvm_mmu_page_fault+0x8c/0x3d0 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.529136] tdx_handle_ept_violation+0x16a/0x310 [kvm_intel 1efe846cc4054cc289d319f1912cf040ec0ca0e6] [ 845.547760] tdx_handle_exit+0x44f/0x540 [kvm_intel 1efe846cc4054cc289d319f1912cf040ec0ca0e6] [ 845.565647] ? lock_acquire+0x52/0x70 [ 845.574284] ? vcpu_enter_guest+0x452/0x11d0 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.591886] vt_handle_exit+0x25/0x30 [kvm_intel 1efe846cc4054cc289d319f1912cf040ec0ca0e6] [ 845.609407] vcpu_enter_guest+0x4b1/0x11d0 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.623253] ? kvm_apic_local_deliver+0x8a/0xe0 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.641247] vcpu_run+0x4d/0x280 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.654096] ? vcpu_run+0x4d/0x280 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.667165] kvm_arch_vcpu_ioctl_run+0x544/0x890 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.685231] kvm_vcpu_ioctl+0x143/0x7c0 [kvm 6f655eadf3c2ae71b90b04a3d4ef5b799600c3f8] [ 845.698810] ? __fget_files+0xc2/0x1b0 [ 845.707633] ? __this_cpu_preempt_check+0x13/0x20 [ 845.717555] ? __fget_files+0xcc/0x1b0 [ 845.726405] __x64_sys_ioctl+0x9a/0xf0 [ 845.735241] ? __this_cpu_preempt_check+0x13/0x20 [ 845.745163] x64_sys_call+0x1054/0x20c0 [ 845.754043] do_syscall_64+0xc3/0x470 [ 845.762701] entry_SYSCALL_64_after_hwframe+0x77/0x7f [ 845.772906] RIP: 0033:0x7f8d9c124ded [ 845.781398] Code: 04 25 28 00 00 00 48 89 45 c8 31 c0 48 8d 45 10 c7 45 b0 10 00 00 00 48 89 45 b8 48 8d 45 d0 48 89 45 c0 b8 10 00 00 00 0f 05 <89> c2 3d 00 f0 ff ff 77 1a 48 8b 45 c8 64 48 2b 04 25 28 00 00 00 [ 845.814651] RSP: 002b:00007f8b863f7cd0 EFLAGS: 00000246 ORIG_RAX: 0000000000000010 [ 845.827882] RAX: ffffffffffffffda RBX: 00007f8b863fccdc RCX: 00007f8d9c124ded [ 845.840591] RDX: 0000000000000000 RSI: 000000000000ae80 RDI: 000000000000001e [ 845.853201] RBP: 00007f8b863f7d20 R08: 0000000000000000 R09: 0000000000000000 [ 845.865776] R10: 0000000000000000 R11: 0000000000000246 R12: 00007f8b863fc6c0 [ 845.878246] R13: ffffffffffffdbf0 R14: 0000000000000007 R15: 00007ffedb593c00 [ 845.890732] </TASK> [ 845.897565] irq event stamp: 859157 [ 845.905815] hardirqs last enabled at (859171): [<ffffffff902447d3>] __up_console_sem+0x63/0x90 [ 845.923321] hardirqs last disabled at (859184): [<ffffffff902447b8>] __up_console_sem+0x48/0x90 [ 845.940892] softirqs last enabled at (859126): [<ffffffff90194ef8>] handle_softirqs+0x358/0x4b0 [ 845.958654] softirqs last disabled at (859207): [<ffffffff901951cf>] __irq_exit_rcu+0xef/0x170 [ 845.976232] ---[ end trace 0000000000000000 ]---
Re: [POC PATCH 3/5] memory/guest_memfd: Enable in-place conversion when available
In reply to Chenyi QiangQuoted 176 lines · Chenyi Qiang
Quoted 126 lines · Xiaoyao Li
From: Yan Zhao <[email protected]>
(This is just the POC code to use in-place conversion gmem.)
Try to use in-place conversion gmem when it is supported.
When in-place conversion is enabled, there is no need to discard memory since it still needs to be used as the memory of opposite attribute after conversion.
For a upstreamable solution, we can introduce memory-backend-guestmemfd for in-place conversion. With the non in-place conversion, it needs seperate non-gmem memory to back the shared memory and gmem is created implicitly and internally based on vm type. While with in-place conversion, there is no need for seperate non-gmem memory because gmem itself can be served as shared memory. So that we can introduce memory-backend-guestmemfd as the specific backend for in-place conversion gmem.
Signed-off-by Yan Zhao <[email protected]>Co-developed-by Xiaoyao Li <[email protected]>
Signed-off-by Xiaoyao Li <[email protected]>--- accel/kvm/kvm-all.c | 79 ++++++++++++++++++++++++++++----------- accel/stubs/kvm-stub.c | 1 + include/system/kvm.h | 1 + include/system/memory.h | 2 + include/system/ramblock.h | 1 + system/memory.c | 7 ++++ system/physmem.c | 21 ++++++++++- 7 files changed, 90 insertions(+), 22 deletions(-)accel/kvm/kvm-all.c +38
-10@@ -105,6 +105,7 @@ static int kvm_sstep_flags;static bool kvm_immediate_exit;static uint64_t kvm_supported_memory_attributes;static bool kvm_guest_memfd_supported; +bool kvm_guest_memfd_inplace_supported;static hwaddr kvm_max_slot_size = ~0 ;static const KVMCapabilityInfo kvm_required_capabilites[] = {@@ -1487,6 +1488,30 @@ static int kvm_set_memory_attributes(hwaddr start, uint64_t size, uint64_t attr)return r; } +static int kvm_set_guest_memfd_shareability (MemoryRegion *mr,ram_addr_t offset, +uint64_t size,bool shared) +{ +int guest_memfd = mr->ram_block->guest_memfd; +struct kvm_gmem_convert param = { + .offset = offset, + .size = size, + .error_offset =0 , + }; +unsigned long op; +int r; + + op = shared ?KVM_GMEM_CONVERT_SHARED :KVM_GMEM_CONVERT_PRIVATE ; + + r =ioctl (guest_memfd, op, ¶m); +if (r) { +error_report ("failed to set guest_memfd offset 0x%lx size 0x%lx to %s " +"error '%s' error offset 0x%llx" , + offset, size, shared ?"shared" :"private" , +strerror (errno), param.error_offset); + } +return r; +} +int kvm_set_memory_attributes_private (hwaddr start,uint64_t size) {return kvm_set_memory_attributes (start, size,KVM_MEMORY_ATTRIBUTE_PRIVATE );@@ -1604,7 +1629,8 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,abort (); } -if (memory_region_has_guest_memfd (mr)) { +if (memory_region_has_guest_memfd (mr) && + !memory_region_guest_memfd_in_place_conversion (mr)) { err =kvm_set_memory_attributes_private (start_addr, slot_size);if (err) { error_report("%s: failed to set memory attribute private: %s",@@ -2779,6 +2805,9 @@ static int kvm_init(AccelState *as, MachineState *ms)kvm_check_extension (s,KVM_CAP_GUEST_MEMFD ) &&kvm_check_extension (s,KVM_CAP_USER_MEMORY2 ) && (kvm_supported_memory_attributes &KVM_MEMORY_ATTRIBUTE_PRIVATE ); + kvm_guest_memfd_inplace_supported = +kvm_check_extension (s,KVM_CAP_GMEM_SHARED_MEM ) && +kvm_check_extension (s,KVM_CAP_GMEM_CONVERSION ); kvm_pre_fault_memory_supported =kvm_vm_check_extension (s,KVM_CAP_PRE_FAULT_MEMORY );if (s->kernel_irqchip_split ==ON_OFF_AUTO_AUTO ) {@@ -3056,6 +3085,7 @@ static void kvm_eat_signals(CPUState *cpu)int kvm_convert_memory (hwaddr start,hwaddr size,bool to_private) { +bool in_place_conversion = false;MemoryRegionSection section;ram_addr_t offset;MemoryRegion *mr;@@ -3112,18 +3142,23 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) goto out_unref; } -if (to_private) { - ret =kvm_set_memory_attributes_private (start, size); - }else { - ret =kvm_set_memory_attributes_shared (start, size); - } -if (ret) { - goto out_unref; - } - addr =memory_region_get_ram_ptr (mr) + section.offset_within_region; rb =qemu_ram_block_from_host (addr, false, &offset); + in_place_conversion =memory_region_guest_memfd_in_place_conversion (mr); +if (in_place_conversion) { + ret =kvm_set_guest_memfd_shareability (mr, offset, size, !to_private); + }else { +if (to_private) { + ret =kvm_set_memory_attributes_private (start, size); + }else {accel/kvm/kvm-all.c int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) · line 3164
Quoted 10 lines
accel/kvm/kvm-all.c +7
-0+ ret =kvm_set_memory_attributes_shared (start, size); + } + } +if (ret) { + goto out_unref; + } + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), offset, size, to_private);if (ret) {There's one thing required for shared device assignment with in-place conversion, we need to follow the sequence of unmap-before-conversion-to-private and map-after-conversion-to-shared. Maybe change it like:
accel/kvm/kvm-all.c +11
-7@@ -3146,6 +3146,17 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) addr =memory_region_get_ram_ptr (mr) + section.offset_within_region; rb =qemu_ram_block_from_host (addr, false, &offset); +if (to_private) { + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), + offset, size, to_private); +if (ret) { +error_report ("Failed to notify the listener the state change of " +"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , + start, size, to_private ?"private" :"shared" ); + goto out_unref; + } + } + in_place_conversion =memory_region_guest_memfd_in_place_conversion (mr);if (in_place_conversion) { ret =kvm_set_guest_memfd_shareability (mr, offset, size, !to_private);@@ -3160,13 +3171,15 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) goto out_unref; } - ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), - offset, size, to_private); -if (ret) { -error_report ("Failed to notify the listener the state change of " -"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , - start, size, to_private ?"private" :"shared" ); - goto out_unref;
accel/kvm/kvm-all.c int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) · line 3183
Quoted 10 lines
accel/kvm/kvm-all.c +9
-0+if (!to_private) { + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), + offset, size, to_private); +if (ret) { +error_report ("Failed to notify the listener the state change of " +"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , + start, size, to_private ?"private" :"shared" ); + goto out_unref; + } }
(Sorry for forgetting to reply in the community)
Thanks for catching and reporting it. I have incorporated it to the internal branch.
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Michael RothHi,
Quoted 90 lines · Michael Roth
Quoted 71 lines · Vishal Annapurve
Quoted 70 lines · Michael Roth
Quoted 68 lines · Ackerley Tng
Quoted 41 lines · Michael Roth
Quoted 40 lines · Ackerley Tng
Track
guest_memfdmemory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within
guest_memfdinstead of within KVM, like inkvm->mem_attr_array.
KVM_MEMORY_ATTRIBUTE_PRIVATEinkvm->mem_attr_arraymust still be retained to allow VMs to only useguest_memfdfor private memory and some other memory for shared memory.Not all use cases require
guest_memfd()to be shared with the host when first created. Add a new flag,GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set onKVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.Signed-off-by Ackerley Tng <[email protected]>Co-developed-by Vishal Annapurve <[email protected]>Signed-off-by Vishal Annapurve <[email protected]>Co-developed-by Fuad Tabba <[email protected]>Signed-off-by Fuad Tabba <[email protected]>Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f--- Documentation/virt/kvm/api.rst | 5 ++ include/uapi/linux/kvm.h | 2 + virt/kvm/guest_memfd.c | 124 ++++++++++++++++++++++++++++++++- 3 files changed, 129 insertions(+), 2 deletions(-)Documentation/virt/kvm/api.rst +0
-0@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr. The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs. This is validated when the guest_memfd instance is bound to the VM.Quoted 11 lines
Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6415
Quoted 5 lines
Documentation/virt/kvm/api.rst +5
-0+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field +supports GUEST_MEMFD_FLAG_INIT_PRIVATE. Setting GUEST_MEMFD_FLAG_INIT_PRIVATE +will initialize the memory for the guest_memfd as guest-only and not faultable +by the host. +
KVM_CAP_GMEM_CONVERSIONdoesn't get introduced until later, so it seems like this flag should be deferred until that patch is in place. Is it really needed at that point though? Userspace would be able to set the initial state via KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls.I can move this change to the later patch. Thanks! Will fix in the next revision.
Quoted 9 lines
The mtree contents seems to get stored in the same manner in either case so performance-wise only the overhead of a few userspace<->kernel switches would be saved. Are there any other reasons?
Otherwise, maybe just settle on SHARED as a documented default (since at least non-CoCo VMs would be able to reliably benefit) and let CoCo/GUEST_MEMFD_FLAG_SUPPORT_SHARED VMs set PRIVATE at whatever granularity makes sense for the architecture/guest configuration.
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Because shared pages are split once any memory is allocated, having a way to
INIT_PRIVATEcould avoid the split and then merge on conversion. I feel that is enough value to have this config flag, what do you think?I guess we could also have userspace be careful not to do any allocation before converting.
(Re-visiting this with the assumption that we *don't* intend to use
mmap()to populate memory (in which case you can pretty much ignore my previous response))I'm still not sure where the
INIT_PRIVATEflag comes into play. For SNP, userspace already defaults to marking everything private pretty close toguest_memfdcreation time, so the potential for allocations to occur in-between seems small, but worth confirming.
Quoted 8 lines
But I know in the past there was a desire to ensure TDX/SNP could support pre-allocating
guest_memfdmemory (and even pre-faulting viaKVM_PRE_FAULT_MEMORY), but I think that could still work right? Thefallocate()handling could still avoid the split if the whole hugepage is private, though there is a bit more potential for thatfallocate()to happen before userspace does the "manually"shared->privateconversion. I'll double-check on that aspect, but otherwise, is there still any other need for it?
It's not just about performance. I think that the need is more a matter of having a consistent API with the hypervisors guest_memfd is going to support. Memory in guest_memfd is shared by default, but in pKVM for example, it's private by default. Therefore, it would be good to have a way to ensure that all guest_memfd allocations can be made private from the get-go.
Cheers,
/fuad
Quoted 482 lines
Quoted 19 lines
Quoted 19 lines
I assume we do want to support things like preallocating guest memory so not sure this approach is feasible to avoid splits.
But I feel like we might be working around a deeper issue here, which is that we are pre-emptively splitting anything that *could* be mapped into userspace (i.e. allocated+shared/mixed), rather than splitting when necessary.
I know that was the plan laid out in the
guest_memfdcalls, but I've run into a couple instances that have me thinking we should revisit this.1) Some of the recent
guest_memfdseems to be gravitating towards having userspace populate/initialize guest memory payload prior to boot via mmap()'ing the sharedguest_memfdpages so things work the same as they would for initialized normal VM memory payload (rather than relying on back-channels in the kernel to user data intoguest_memfdpages).Quoted 8 lines
Quoted 3 lines
When you do this though, for an SNP guest at least, that memory acceptance is done in chunks of 4MB (with accept_memory=lazy), and because that will put each 1GB page into an allocated+mixed state,
I would like your help in understanding why we need to start
guest_memfdranges as shared for SNP guests.guest_memfdranges being private simply should mean that certain ranges are not faultable by the userspace.It's seeming like I probably misremembered, but I thought there was a discussion on
guest_memfdcall a month (or so?) ago about whether to continue to use backchannels to populateguest_memfdpages prior to launch. It was in the context of whether to keep usingkvm_gmem_populate()for populatingguest_memfdpages by copying them in from separate userspace buffer vs. simply populating them directly from userspace. I thought we were leaning on the latter since it was simpler all-around, which is great for SNP since that is already how it populates memory: by writing to it from userspace, whichkvm_gmem_populate()then copies intoguest_memfdpages. With shared gmem support, we just skip the latter now in the kernel rather needing changes to how userspace handles things in that regard. But maybe that was just wishful thinking :)But you raise some very compelling points on why this might not be a good idea even if that was how that discussion went.
Quoted 11 lines
Will following work?
1) Userspace starts allguest_memfdranges as private.
2) During early guest boot it starts issuing PSC requests for converting memory from shared to private-> KVM forwards this request to userspace -> Userspace checks that the pages are already private and simplydoes nothing.
3) Pvalidate from guest on that memory will result inguest_memfdoffset query which will cause the RMP table entries to actually get populated.That would work, but there will need to be changes on userspace to deal with how SNP populates memory pre-boot just like normal VMs do. We will instead need to copy that data into separate buffers, and pass those in as the buffer hva instead of the shared hva corresponding to that GPA.
But that seems reasonable if it avoids so many other problems.
Quoted 16 lines
Quoted 16 lines
we end up splitting every 1GB to 4K and the guest can't even accept/PVALIDATE it 2MB at that point even if userspace doesn't touch anything in the range. As some point the guest will convert/accept the entire range, at which point we could merge, but for SNP we'd need guest cooperation to actually use a higher-granularity in stage2 page tables at that point since RMP entries are effectively all split to 4K.
I understand the intent is to default to private where this wouldn't be an issue, and we could punt to userspace to deal with it, but it feels like an artificial restriction to place on userspace. And if we do want to allow/expect
guest_memfdcontents to be initialized pre-boot just like normal memory, then userspace would need to jump through some hoops:Quoted 4 lines
Quoted 2 lines
- if defaulting to private: add hooks to convert each range that's being modified to a shared state prior to writing to it
Why is that a problem?
These were only problems if we went the above-mentioned way of populating memory pre-boot via
mmap()instead of other backchannels. If we don't do that, then both these things cease to be problems. Sounds goods to me. :)Quoted 11 lines
Quoted 8 lines
- if defaulting to shared: initialize memory in-place, then covert everything else to private to avoid unecessarily splitting folios at run-time
It feels like implementations details are bleeding out into the API to some degree here (e.g. we'd probably at least need to document this so users know how to take proper advantage of hugepage support).
Does it make sense to keep the default behavior as
INIT_PRIVATEfor SNP VMs always even without using hugepages?Yes!
Though, revisiting discussion around
INIT_PRIVATE(without the baggage of potentially relying onmmap()to populate memory), I'm still not sure why it's needed. I responded in the context of Ackerley's initial reply above.Quoted 15 lines
Quoted 9 lines
2) There are some use-cases for HugeTLB + CoCo that have come to my attention recently that put a lot of weight on still being able to maximize mapping/hugepage size when accessing shared mem from userspace, e.g. for certain DPDK workloads that accessed shared guest buffers from host userspace. We don't really have a story for this, and I wouldn't expect us to at this stage, but I think it ties into #1 so might be worth considering in that context.
Major problem I see here is that if anything in the kernel does a GUP on shared memory ranges (which is very likely to happen), it would be difficult to get them to let go of the whole hugepage before it can be split safely.
Quoted 4 lines
Another problem is
guest_memfdtoday doesn't support management of large user space page table mappings, this can turnout to be significant work to do referring to hugetlb pagetable management logic.Yah that was more line-of-sight that might be possible by going this route, but the refcount'ing issue above is a showstopper as always. I'd somehow convinced myself that supporting fine-grained splitting somehow worked around it, but you still have no idea what page you need to avoid converting and fancy splitting doesn't get you past that. More wishful thinking. =\
Thanks,
Mike
Quoted 343 lines
Quoted 343 lines
I'm still fine with the current approach as a starting point, but I'm wondering if improving both #1/#2 might not be so bad and maybe even give us some more flexibility (for instance, Sean had mentioned leaving open the option of tracking more than just shareability/mappability, and if there is split/merge logic associated with those transitions then re-scanning each of these attributes for a 1G range seems like it could benefit from some sort of intermediate data structure to help determine things like what mapping granularity is available for guest/userspace for a particular range.
One approach I was thinking of was that we introduce a data structure similar to KVM's
memslot->arch.lpage_info()where we store information about what 1G/2M ranges are shared/private/mixed, and then instead of splitting ahead of time we just record that state into this data structure (using the same write lock as with the shareability/mappability state), and then at *fault* time we split the folio if our lpage_info-like data structure says the range is mixed.Then, if guest converts a 2M/4M range to private while lazilly-accepting (for instance), we can still keep the folio intact as 1GB, but mark the 1G range in the lpage_info-like data structure as mixed so that we still inform KVM/etc. they need to map it as 2MB or lower in stage2 page tables. In that case, even at guest fault-time, we can leave the folio unsplit until userspace tries to touch it (though in most cases it never will and we can keep most of the guest's 1G intact for the duration of its lifetime).
On the userspace side, another nice thing there is if we see 1G is in a mixed state, but 2M is all-shared, then we can still leave the folio as 2M, and I think the refcount'ing logic would still work for the most part, which makes #2 a bit easier to implement as well.
And of course, we wouldn't need the
INIT_PRIVATEthen since we are only splitting when necessary.But I guess this all comes down to how much extra pain there is in tracking a 1G folio that's been split into a mixed of 2MB/4K regions, but I think we'd get a lot more mileage out of getting that working and just completely stripping out all of the merging logic for initial implementation (other than at cleanup time), so maybe complexity-wise it balances out a bit?
Thanks,
Mike
Quoted 295 lines
Quoted 294 lines
Quoted 62 lines
Documentation/virt/kvm/api.rst +0
-0See KVM_SET_USER_MEMORY_REGION2 for additional details. 4.143 KVM_PRE_FAULT_MEMORYinclude/uapi/linux/kvm.h +2
-0@@ -1567,7 +1567,9 @@ struct kvm_memory_attributes {#define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3)#define KVM_CREATE_GUEST_MEMFD _IOWR(KVMIO, 0xd4, struct kvm_create_guest_memfd) +#define GUEST_MEMFD_FLAG_SUPPORT_SHARED (1UL << 0) +#define GUEST_MEMFD_FLAG_INIT_PRIVATE (1UL << 1)struct kvm_create_guest_memfd {__u64 size;virt/kvm/guest_memfd.c +22
-0@@ -4,6 +4,7 @@#include <linux/falloc.h> #include <linux/fs.h> #include <linux/kvm_host.h> +#include <linux/maple_tree.h> #include <linux/pseudo_fs.h> #include <linux/pagemap.h> @@ -17,6 +18,24 @@ struct kvm_gmem {struct list_head entry; }; +struct kvm_gmem_inode_private { +#ifdef CONFIG_KVM_GMEM_SHARED_MEM +struct maple_tree shareability; +#endif +}; + +enum shareability { +SHAREABILITY_GUEST =1 ,/* Only the guest can map (fault) folios in this range. */ +SHAREABILITY_ALL =2 ,/* Both guest and host can fault folios in this range. */ +}; + +static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index); + +static struct kvm_gmem_inode_private *kvm_gmem_private (struct inode *inode) +{ +return inode->i_mapping->i_private_data; +} +/** * folio_file_pfn - like folio_file_page, but return a pfn. * @folio: The folio which contains this index. @@ -29,6 +48,58 @@ static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index)return folio_pfn (folio) + (index & (folio_nr_pages (folio) -1 )); } +#ifdef CONFIG_KVM_GMEM_SHARED_MEM + +static int kvm_gmem_shareability_setup(struct kvm_gmem_inode_private *private,virt/kvm/guest_memfd.c static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 63
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ loff_t size, u64 flags) +{ +enum shareability m; +pgoff_t last; + + last = (size >>PAGE_SHIFT ) -1 ; + m = flags &GUEST_MEMFD_FLAG_INIT_PRIVATE ?SHAREABILITY_GUEST : +SHAREABILITY_ALL ; +return mtree_store_range (&private->shareability,0 , last,xa_mk_value (m), +GFP_KERNEL );One really nice thing about using a maple tree is that it should get rid of a fairly significant startup delay for SNP/TDX when the entire xarray gets initialized with private attribute entries via
KVM_SET_MEMORY_ATTRIBUTES(which is the current QEMU default behavior).I'd originally advocated for sticking with the xarray implementation Fuad was using until we'd determined we really need it for HugeTLB support, but I'm sort of thinking it's already justified just based on the above.
Maybe it would make sense for KVM memory attributes too?
Quoted 135 lines
virt/kvm/guest_memfd.c +87
-1+} + +static enum shareability kvm_gmem_shareability_get (struct inode *inode, +pgoff_t index) +{ +struct maple_tree *mt; +void *entry; + + mt = &kvm_gmem_private (inode)->shareability; + entry =mtree_load (mt, index); +WARN (!entry, +"Shareability should always be defined for all indices in inode." ); + +return xa_to_value (entry); +} + +static struct folio *kvm_gmem_get_shared_folio (struct inode *inode,pgoff_t index) +{ +if (kvm_gmem_shareability_get (inode, index) !=SHAREABILITY_ALL ) +return ERR_PTR (-EACCES ); + +return kvm_gmem_get_folio (inode, index); +} + +#else + +static int kvm_gmem_shareability_setup (struct maple_tree *mt,loff_t size,u64 flags) +{ +return 0 ; +} + +static inline struct folio *kvm_gmem_get_shared_folio (struct inode *inode,pgoff_t index) +{ + WARN_ONCE("Unexpected call to get shared folio.") +return NULL ; +} + +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ +static int __kvm_gmem_prepare_folio (struct kvm *kvm,struct kvm_memory_slot *slot,pgoff_t index,struct folio *folio) {@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)filemap_invalidate_lock_shared (inode->i_mapping); - folio =kvm_gmem_get_folio (inode, vmf->pgoff); + folio =kvm_gmem_get_shared_folio (inode, vmf->pgoff);if (IS_ERR (folio)) {int err =PTR_ERR (folio);@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = { .fallocate = kvm_gmem_fallocate, }; +static void kvm_gmem_free_inode (struct inode *inode) +{ +struct kvm_gmem_inode_private *private =kvm_gmem_private (inode); + +kfree (private); + +free_inode_nonrcu (inode); +} + +static void kvm_gmem_destroy_inode (struct inode *inode) +{ +struct kvm_gmem_inode_private *private =kvm_gmem_private (inode); + +#ifdef CONFIG_KVM_GMEM_SHARED_MEM +/* +* mtree_destroy() can't be used within rcu callback, hence can't be +* done in ->free_inode(). +*/ +if (private) +mtree_destroy (&private->shareability); +#endif +} +static const struct super_operations kvm_gmem_super_operations = { .statfs = simple_statfs, + .destroy_inode = kvm_gmem_destroy_inode, + .free_inode = kvm_gmem_free_inode, };static int kvm_gmem_init_fs_context (struct fs_context *fc)@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {static struct inode *kvm_gmem_inode_make_secure_inode (const char *name,loff_t size,u64 flags) { +struct kvm_gmem_inode_private *private;struct inode *inode; +int err; inode =alloc_anon_secure_inode (kvm_gmem_mnt->mnt_sb, name);if (IS_ERR (inode))return inode; + err = -ENOMEM ; + private =kzalloc (sizeof (*private),GFP_KERNEL ); +if (!private) + goto out; + +mt_init (&private->shareability); + inode->i_mapping->i_private_data = private; + + err =kvm_gmem_shareability_setup (private, size, flags); +if (err) + goto out; + inode->i_private = (void *)(unsigned long )flags; inode->i_op = &kvm_gmem_iops; inode->i_mapping->a_ops = &kvm_gmem_aops;@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,WARN_ON_ONCE (!mapping_unevictable (inode->i_mapping));return inode; + +out: +iput (inode); + +return ERR_PTR (err); } static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)if (kvm_arch_vm_supports_gmem_shared_mem (kvm)) valid_flags |=GUEST_MEMFD_FLAG_SUPPORT_SHARED ; +if (flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED ) + valid_flags |=GUEST_MEMFD_FLAG_INIT_PRIVATE ; +if (flags & ~valid_flags)return -EINVAL ;virt/kvm/guest_memfd.c int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 964
Quoted 5 lines
virt/kvm/guest_memfd.c +2
-0@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,if (!file)return -EFAULT ; +filemap_invalidate_lock_shared (file_inode (file)->i_mapping); +I like the idea of using a write-lock/read-lock to protect write/read access to shareability state (though maybe not necessarily re-using filemap's invalidate lock), it's simple and still allows concurrent faulting in of gmem pages. One issue on the SNP side (which also came up in one of the gmem calls) is if we introduce support for tracking preparedness as discussed (e.g. via a new
SHAREABILITY_GUEST_PREPAREDstate) theSHAREABILITY_GUEST->SHAREABILITY_GUEST_PREPAREDtransition would occur at fault-time, and so would need to take the write-lock and no longer allow for concurrent fault-handling.I was originally planning on introducing a new
rw_semaphorewith similar semantics to therw_lockthat Fuad previously had in his restricted mmap series[1] (and simiar semantics to filemap invalidate lock here). The main difference, to handle settingSHAREABILITY_GUEST_PREPAREDwithin fault paths, was that in the case of a folio being present for an index, the folio lock would also need to be held in order to update the shareability state. Because of that, fault paths (which will always either have or allocate folio basically) can rely on the folio lock to guard shareability state in a more granular way and so can avoid a global write lock.They would still need to hold the read lock to access the tree however. Or more specifically, any paths that could allocate a folio need to take a read lock so there isn't a TOCTOU situation where shareability is being updated for an index for which a folio hasn't been allocated, but then just afterward the folio gets faulted in/allocated while the shareability state is already being updated which the understand that there was no folio around that needed locking.
I had a branch with in-place conversion support for SNP[2] that added this lock reworking on top of Fuad's series along with preparation tracking, but I'm now planning to rebase that on top of the patches from this series that Sean mentioned[3] earlier:
KVM:
guest_memfd: Add CAPKVM_CAP_GMEM_CONVERSION
KVM: Queryguest_memfdfor private/shared status
KVM:guest_memfd: Skip LRU forguest_memfdfolios
KVM:guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
KVM:guest_memfd: Introduce and use shareability to guard faulting
KVM:guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodesbut figured I'd mention it here in case there are other things to consider on the locking front.
Definitely agree with Sean though that it would be nice to start identifying a common base of patches for the in-place conversion enablement for SNP, TDX, and pKVM so the APIs/interfaces for hugepages can be handled separately.
-Mike
[1] https://lore.kernel.org/kvm/[email protected]/
[2] https://github.com/mdroth/linux/commits/mmap-swprot-v10-snp0-wip2/
[3] https://lore.kernel.org/kvm/[email protected]/Quoted 16 lines
virt/kvm/guest_memfd.c +1
-2folio =__kvm_gmem_get_pfn (file, slot, index, pfn, &is_prepared, max_order);if (IS_ERR (folio)) { r =PTR_ERR (folio);@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, *page =folio_file_page (folio, index); elsefolio_put (folio ); - out: +filemap_invalidate_unlock_shared (file_inode (file)->i_mapping);fput (file);return r; } --2.49.0.1045.g170613ef41-goog
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 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Fuad TabbaQuoted 11 lines · Fuad Tabba
Hi,
Quoted 8 lines · Michael Roth
Quoted 6 lines · Vishal Annapurve
Quoted 5 lines · Michael Roth
Quoted 3 lines · Ackerley Tng
Quoted 1 line · Michael Roth
On Wed, May 14, 2025 at 04:41:41PM -0700, Ackerley Tng wrote:
[snip]
Quoted 36 lines
Quoted 27 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 9 lines
The mtree contents seems to get stored in the same manner in either case so performance-wise only the overhead of a few userspace<->kernel switches would be saved. Are there any other reasons?
Otherwise, maybe just settle on SHARED as a documented default (since at least non-CoCo VMs would be able to reliably benefit) and let CoCo/GUEST_MEMFD_FLAG_SUPPORT_SHARED VMs set PRIVATE at whatever granularity makes sense for the architecture/guest configuration.
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Because shared pages are split once any memory is allocated, having a way to
INIT_PRIVATEcould avoid the split and then merge on conversion. I feel that is enough value to have this config flag, what do you think?I guess we could also have userspace be careful not to do any allocation before converting.
(Re-visiting this with the assumption that we *don't* intend to use
mmap()to populate memory (in which case you can pretty much ignore my previous response))I'm still not sure where the
INIT_PRIVATEflag comes into play. For SNP, userspace already defaults to marking everything private pretty close toguest_memfdcreation time, so the potential for allocations to occur in-between seems small, but worth confirming.Quoted 8 lines
But I know in the past there was a desire to ensure TDX/SNP could support pre-allocating
guest_memfdmemory (and even pre-faulting viaKVM_PRE_FAULT_MEMORY), but I think that could still work right? Thefallocate()handling could still avoid the split if the whole hugepage is private, though there is a bit more potential for thatfallocate()to happen before userspace does the "manually"shared->privateconversion. I'll double-check on that aspect, but otherwise, is there still any other need for it?
Quoted 4 lines
It's not just about performance. I think that the need is more a matter of having a consistent API with the hypervisors
guest_memfdis going to support. Memory inguest_memfdis shared by default, but in pKVM for example, it's private by default. Therefore, it would be good
^^^^^^^^^^^^^^^^
And Coco's as well right?
Ira
Quoted 6 lines
to have a way to ensure that all
guest_memfdallocations can be made private from the get-go.Cheers,
/fuad
[snip]
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Yan ZhaoQuoted 17 lines · Yan Zhao
Quoted 4 lines · Ackerley Tng
(quoted diff) +4
-0+static enum shareability kvm_gmem_shareability_get(struct inode *inode, + pgoff_t index) +{ + struct maple_tree *mt;Review
Quoted 10 lines
(quoted diff) +10
-0+ void *entry; + + mt = &kvm_gmem_private(inode)->shareability; + entry = mtree_load(mt, index); + WARN(!entry, + "Shareability should always be defined for all indices in inode."); + + return xa_to_value(entry); +} +Hi Ackerley,
Quoted 2 lines
Not sure if it's a known issue. Just want to let you know in case you're unaware.
Thanks for informing me, and thanks for the analysis :)
Quoted 19 lines
During a test to repeatedly launching/destroying TDs, I encountered a warning from
kvm_gmem_shareability_get()(see the attached log at the bottom). The reproducing rate is 1 in every 20-100 times of launching TD.After some analysis, I found that the warning was produced by
kvm_gmem_shareability_get()when it's called fromkvm_gmem_is_private(), which is not protected by any locks.I can get rid of the warning by either fix 1 or fix 2 below. (I prefer fix 1 though :))
fix 1:
virt/kvm/guest_memfd.c +0
-0
virt/kvm/guest_memfd.c static struct inode *kvm_gmem_inode_make_secure_inode(const char *name, · line 2030
Quoted 8 lines
virt/kvm/guest_memfd.c +1
-1@@ -2024,7 +2024,7 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,#ifdef CONFIG_KVM_GMEM_SHARED_MEM if (flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { -mt_init (&private->shareability); +mt_init_flags (&private->shareability,MT_FLAGS_USE_RCU ); err =kvm_gmem_shareability_setup (private, size, flags);if (err)
Not sure about the version of the conversion patch series that you're using, in the version I'm preparing, I'm using filemap_invalidate_lock_shared() to guard shareability reads. filemap_invalidate_lock() is held during shareability updates, so I think this issue should be fixed.
Please let me know if you're still seeing this issue in the next series (coming soon). Thank you!
Quoted 23 lines
fix 2:
virt/kvm/guest_memfd.c +2
-0@@ -171,7 +171,9 @@ static enum shareability kvm_gmem_shareability_get(struct inode *inode,void *entry; mt = &kvm_gmem_private (inode)->shareability; +mtree_lock (mt); entry =mtree_load (mt, index); +mtree_unlock (mt);WARN (!entry,"Shareability should always be defined for all indices in inode." );Thanks
Yan[...snip...]
Re: [RFC PATCH v2 35/51] mm: guestmem_hugetlb: Add support for splitting and merging pages
In reply to Ackerley TngQuoted 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 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
In reply to Ackerley TngQuoted 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); +} +
Re: [RFC PATCH v2 35/51] mm: guestmem_hugetlb: Add support for splitting and merging pages
In reply to Michael RothQuoted 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
Re: [RFC PATCH v2 39/51] KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)
In reply to Yan ZhaoQuoted 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...]
Sean Christopherson
maintainerRe: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ackerley TngTrimmed the Cc substantially as I doubt non-gmem/KVM folks will be excited about thread necromancy.
Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6414
Quoted 12 lines · Ackerley Tng
Documentation/virt/kvm/api.rst +4
-0@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr. The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs. This is validated when the guest_memfd instance is bound to the VM. +If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field +supports GUEST_MEMFD_FLAG_INIT_PRIVATE. Setting GUEST_MEMFD_FLAG_INIT_PRIVATE +will initialize the memory for the guest_memfd as guest-only and not faultable +by the host.
Whatever documentation we add should land at the same time as the collateral. KVM_CAP_GMEM_CONVERSIONS literally doesn't exist at this time.
Quoted 4 lines
Documentation/virt/kvm/api.rst +0
-0@@ -17,6 +18,24 @@ struct kvm_gmem { struct list_head entry; };
Documentation/virt/kvm/api.rst struct kvm_gmem { · line 30
Quoted 10 lines
Documentation/virt/kvm/api.rst +10
-0+struct kvm_gmem_inode_private { +#ifdef CONFIG_KVM_GMEM_SHARED_MEM + struct maple_tree shareability; +#endif +}; + +enum shareability { + SHAREABILITY_GUEST = 1, /* Only the guest can map (fault) folios in this range. */ + SHAREABILITY_ALL = 2, /* Both guest and host can fault folios in this range. */ +};
Rather than define new values and new KVM uAPI, I think we should instead simply support KVM_SET_MEMORY_ATTRIBUTES. We'll probably need a new CAP, as I'm not sure supporting KVM_CHECK_EXTENSION+KVM_CAP_MEMORY_ATTRIBUTES on a gmem fd would be a good idea (e.g. trying to do KVM_CAP_GUEST_MEMFD_FLAGS on a gmem fd doesn't work because the whole point is to get flags _before_ creating the gmem instance). But adding e.g. KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES is easy enough.
But for specifying PRIVATE vs. SHARED, I don't see any reason to define new uAPI. I also don't want an entirely new set of terms in KVM to describe the same things. PRIVATE and SHARED are far from perfect, but they're better than https://xkcd.com/927.
And if we ever want to let userspace restrict RWX protections in gmem, we'll have a ready-made way to do so.
Internally, that let's us do some fun things in KVM. E.g. if we make the "disable legacy per-VM memory attributes" a read-only module param, then we can wire up a static_call() for kvm_get_memory_attributes() and then kvm_mem_is_private() will Just Work.
static inline unsigned long kvm_get_memory_attributes(struct kvm *kvm, gfn_t gfn)
{
return static_call(__kvm_get_memory_attributes)(kvm, gfn);}
static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)
{
return kvm_get_memory_attributes(kvm, gfn) & KVM_MEMORY_ATTRIBUTE_PRIVATE;}
That might trigger some additional surgery if/when we want to support RWX protections on a per-VM basis _and_ a per-gmem basic, but I suspect such churn would pale in comparison to the overall support needed for RWX protections.
The kvm_memory_attributes structure is compatible, all that's needed AFAICT is a union to clarify it's a pgoff instead of an address when used for guest_memfd.
include/uapi/linux/kvm.h +4 -1
@@ -1590,7 +1590,10 @@ struct kvm_stats_desc {#define KVM_SET_MEMORY_ATTRIBUTES _IOW(KVMIO, 0xd2, struct kvm_memory_attributes)struct kvm_memory_attributes { -__u64 address; +union { +__u64 address; +__u64 offset; + };__u64 size;__u64 attributes;__u64 flags;
Documentation/virt/kvm/api.rst struct kvm_gmem { · line 35
Quoted 5 lines
Documentation/virt/kvm/api.rst +5
-0+static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index); + +static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode) +{ + return inode->i_mapping->i_private_data;
This is a hilarious bad helper. Everyone and their mother is going to think about "private vs. shared" when they see kvm_gmem_private(), at least on the x86 side.
What's even more absurd is that the only "final" usage of the helper is to free/destroy the inode:
$ git grep kvm_gmem_private virt/kvm/guest_memfd.c:static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode) virt/kvm/guest_memfd.c: return kvm_gmem_private(inode)->allocator_ops; virt/kvm/guest_memfd.c: return kvm_gmem_private(inode)->allocator_private; virt/kvm/guest_memfd.c: mt = &kvm_gmem_private(inode)->shareability; virt/kvm/guest_memfd.c: mt = &kvm_gmem_private(inode)->shareability; virt/kvm/guest_memfd.c: mt = &kvm_gmem_private(inode)->shareability; virt/kvm/guest_memfd.c: mt = &kvm_gmem_private(inode)->shareability; virt/kvm/guest_memfd.c: struct kvm_gmem_inode_private *private = kvm_gmem_private(inode); virt/kvm/guest_memfd.c: struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
And in that case, using a wrapper is counter-productive, just reference inode->i_mapping->i_private_data directly so that readeres don't have to jump through a useless layer.
Luckily, "struct kvm_gmem_inode_private" no longer needs to exist, now that Shivank's NUMA policy series wraps the vfs_inode with a gmem_inode, and can be retrieved via GMEM_I(). FWIW, before looking that series, I was going to suggest something like to_gmem(), but I definitely think we should follow filesystems convention, not KVM vCPU/VM convention.
Quoted 20 lines
Documentation/virt/kvm/api.rst +14
-0* folio_file_pfn - like folio_file_page, but return a pfn. * @folio: The folio which contains this index.@@ -29,6 +48,58 @@ static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) return folio_pfn(folio) + (index & (folio_nr_pages(folio) - 1)); } +#ifdef CONFIG_KVM_GMEM_SHARED_MEM + +static int kvm_gmem_shareability_setup(struct kvm_gmem_inode_private *private, + loff_t size, u64 flags) +{ + enum shareability m; + pgoff_t last; + + last = (size >> PAGE_SHIFT) - 1; + m = flags & GUEST_MEMFD_FLAG_INIT_PRIVATE ? SHAREABILITY_GUEST : + SHAREABILITY_ALL; + return mtree_store_range(&private->shareability, 0, last, xa_mk_value(m), + GFP_KERNEL); +}
Documentation/virt/kvm/api.rst static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 74
Quoted 10 lines
Documentation/virt/kvm/api.rst +10
-0+ +static enum shareability kvm_gmem_shareability_get(struct inode *inode, + pgoff_t index) +{ + struct maple_tree *mt; + void *entry; + + mt = &kvm_gmem_private(inode)->shareability; + entry = mtree_load(mt, index); + WARN(!entry,
WARN_ON_ONCE(), otherwise we risk escalating a per-VM problem into a system-wide DoS.
Documentation/virt/kvm/api.rst static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 85
Quoted 11 lines
Documentation/virt/kvm/api.rst +11
-0+ "Shareability should always be defined for all indices in inode."); + + return xa_to_value(entry); +} + +static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index) +{ + if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL) + return ERR_PTR(-EACCES); + + return kvm_gmem_get_folio(inode, index);
Please don't add 1-3 line helpers with one caller and very little hope of gaining additional users, especially in guest_memfd where "shared" and "private" have multiple meanings, and so things like "get_shared_folio" are inherently ambiguous.
I'm pretty sure a lot of this stems from CONFIG_KVM_GMEM_SHARED_MEM, which AFAICT simply won't exist. But just in case this is a Google3 pattern...
Quoted 21 lines
Documentation/virt/kvm/api.rst +17
-0+} + +#else + +static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags) +{ + return 0; +} + +static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index) +{ + WARN_ONCE("Unexpected call to get shared folio.") + return NULL; +} + +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ + static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, pgoff_t index, struct folio *folio) {
Documentation/virt/kvm/api.rst static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf) · line 407
Quoted 5 lines
Documentation/virt/kvm/api.rst +1
-1@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf) filemap_invalidate_lock_shared(inode->i_mapping); - folio = kvm_gmem_get_folio(inode, vmf->pgoff); + folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);
I am fairly certain there's a TOCTOU bug here. AFAICT, nothing prevents the underlying memory from being converted from shared=>private after checking that the page is SHARED.
The locking rules for the maple_tree are also undocumented and haphazard. I think we can kill several birds with one stone by protecting the attributes with invalidate_lock. A bonus with using invalidate_lock is that it's a sleepable lock, not a spinlock. I don't think there's anything that would immediately benefit? But if we wanted to populate the tree on-demand (versus pre-filling all possible pages), then it'd be easier to handle things like allocations in a race free manner.
/* * Protect the attributes with the invalidation lock, which will always * be held on conversions */ mt_init_flags(&gi->attributes, MT_FLAGS_LOCK_EXTERN); mt_set_external_lock(&gi->attributes, &inode->i_mapping->invalidate_lock);
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
Sean Christopherson
maintainerRe: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to a message not in the archiveQuoted 1 line · Sean Christopherson
Trimmed Cc again.
And of course I forgot to actually Cc folks...
Quoted 53 lines · Sean Christopherson
Quoted 4 lines · Fuad Tabba
Quoted 3 lines
From a conceptual point of view, I understand that the in-place conversion is a property of
guest_memfd. But that doesn't necessarily mean that the interface between kvm <->guest_memfdis a userspace IOCTL....
Quoted 32 lines
A decent comparison is vCPUs. KVM _could_ route all ioctls through the VM, but that's unpleasant for all parties, as it'd be cumbersome for userspace, and unnecessarily complex and messy for KVM. Similarly, routing
guest_memfdstate changes throughKVM_SET_MEMORY_ATTRIBUTESis awkward from both design and mechanical perspectives.Even if we disagree on how ugly/pretty routing conversions through kvm would be, which I'll allow is subjective, the bigger problem is that bouncing through
KVM_SET_MEMORY_ATTRIBUTESwould create an unholy mess of an ABI.Today,
KVM_SET_MEMORY_ATTRIBUTESis handled entirely within kvm, and any changes take effect irrespective of any memslot bindings. And that didn't happen by chance; preserving and enforcing attribute changes independently of memslots was a key design requirement, precisely because memslots are ephemeral to a certain extent.Adding support for in-place
guest_memfdconversion will require new ABI, and so will be a "breaking" change forKVM_SET_MEMORY_ATTRIBUTESno matter what. E.g. KVM will need to rejectKVM_MEMORY_ATTRIBUTE_PRIVATEfor VMs that elect to use in-placeguest_memfdconversions. But very critically, KVM can cripsly enumerate the lack ofKVM_MEMORY_ATTRIBUTE_PRIVATEviaKVM_CAP_MEMORY_ATTRIBUTES, the behavior will be very straightforward to document (e.g. CAP X is mutually excusive withKVM_MEMORY_ATTRIBUTE_PRIVATE), and it will be opt-in, i.e. won't truly be a breaking change.If/when we move shareability to
guest_memfd, routing state changes throughKVM_SET_MEMORY_ATTRIBUTESwill gain a subtle dependency on userspace having to create memslots in order for state changes to take effect. That wrinkle would be weird and annoying to document, e.g. "if CAP X is enabled, the ioctl ordering is A => B => C, otherwise the ordering doesn't matter", and would create many more conundrums:Quoted 7 lines
- If a memslot needs to exist in order for
KVM_SET_MEMORY_ATTRIBUTESto take effect, what should happen if that memslot is deleted?
- If a memslot isn't found, shouldKVM_SET_MEMORY_ATTRIBUTESfail and report an error, or silently do nothing?
- IfKVM_SET_MEMORY_ATTRIBUTESaffects multiple memslots that are bound to multipleguest_memfd, how does KVM guarantee atomicity? What happens if oneguest_memfdconversion succeeds, but a later fails?Note, my above objections were purely about routing updates through a VM, e.g. due to having to resolve memslots and whatnot. I.e. I swear I'm not contradicting myself by suggesting we reuse
KVM_SET_MEMORY_ATTRIBUTESitself on the gmem file descriptor. I'm pretty sure past me didn't think at all about the actual uAPI, only the roles and responsibilities.
Sean Christopherson
maintainerRe: [RFC PATCH v2 06/51] KVM: Query guest_memfd for private/shared status
In reply to Yan ZhaoQuoted 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.
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Sean ChristophersonQuoted 12 lines · Sean Christopherson
Trimmed the Cc substantially as I doubt non-gmem/KVM folks will be excited about thread necromancy.
Quoted 8 lines · Ackerley Tng
Documentation/virt/kvm/api.rst +0
-0@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr. The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs. This is validated when the guest_memfd instance is bound to the VM.
Quoted 8 lines
Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6414
Quoted 4 lines
Documentation/virt/kvm/api.rst +4
-0+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field +supports GUEST_MEMFD_FLAG_INIT_PRIVATE. Setting GUEST_MEMFD_FLAG_INIT_PRIVATE +will initialize the memory for the guest_memfd as guest-only and not faultable +by the host.Whatever documentation we add should land at the same time as the collateral.
KVM_CAP_GMEM_CONVERSIONSliterally doesn't exist at this time.
Thanks, will keep this in mind for next time.
Quoted 13 lines
Quoted 13 lines
Documentation/virt/kvm/api.rst +9
-0@@ -17,6 +18,24 @@ struct kvm_gmem { struct list_head entry; }; +struct kvm_gmem_inode_private { +#ifdef CONFIG_KVM_GMEM_SHARED_MEM + struct maple_tree shareability; +#endif +}; + +enum shareability { + SHAREABILITY_GUEST = 1, /* Only the guest can map (fault) folios in this range. */ + SHAREABILITY_ALL = 2, /* Both guest and host can fault folios in this range. */
Quoted 9 lines
Documentation/virt/kvm/api.rst struct kvm_gmem { · line 30
Quoted 1 line
Documentation/virt/kvm/api.rst +1
-0+};Rather than define new values and new KVM uAPI, I think we should instead simply support
KVM_SET_MEMORY_ATTRIBUTES. We'll probably need a new CAP, as I'm not sure supporting KVM_CHECK_EXTENSION+KVM_CAP_MEMORY_ATTRIBUTES on a gmem fd would be a good idea (e.g. trying to doKVM_CAP_GUEST_MEMFD_FLAGSon a gmem fd doesn't work because the whole point is to get flags _before_ creating the gmem instance). But adding e.g.KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTESis easy enough.
I've read this a few times and I'm a bit confused, so just making sure:
you are suggesting that we reuse the KVM_SET_MEMORY_ATTRIBUTES ioctl as a guest_memfd (not a VM) ioctl and still store private/shared state within guest_memfd, right?
I think fundamentally the introduction of the guest_memfd ioctls was motivated by how private/shared state is a property of memory and not a property of the VM. (IIRC you were the one to most succinctly phrase it this way on one of the guest_memfd biweeklies.) So I hope you don't mean to revert to doing conversions through a VM ioctl.
Quoted 6 lines
But for specifying PRIVATE vs. SHARED, I don't see any reason to define new uAPI. I also don't want an entirely new set of terms in KVM to describe the same things. PRIVATE and SHARED are far from perfect, but they're better than https://xkcd.com/927.
And if we ever want to let userspace restrict RWX protections in gmem, we'll have a ready-made way to do so.
Would like to understand more about RWX protections: is the use case to let userspace specify that certain ranges of guest memory are to be mapped into stage 2 page tables without executable permissions?
Is there a further use case to let the guest specify that userspace must not mmap() some ranges as executable?
For guest_memfd the userspace mapping permissions are already defined by userspace and so unless guest_memfd must enforce something on behalf of the guest, there shouldn't be anything more that guest_memfd should track with respect to RWX permissions.
Quoted 10 lines
Internally, that let's us do some fun things in KVM. E.g. if we make the "disable legacy per-VM memory attributes" a read-only module param, then we can wire up a
static_call()forkvm_get_memory_attributes()and thenkvm_mem_is_private()will Just Work.static inline unsigned long
kvm_get_memory_attributes(struct kvm *kvm, gfn_t gfn){ return static_call(__kvm_get_memory_attributes)(kvm, gfn);}
Quoted 9 lines
static inline bool
kvm_mem_is_private(struct kvm *kvm, gfn_t gfn){ return kvm_get_memory_attributes(kvm, gfn) & KVM_MEMORY_ATTRIBUTE_PRIVATE;}
That might trigger some additional surgery if/when we want to support RWX protections on a per-VM basis _and_ a per-gmem basic, but I suspect such churn would pale in comparison to the overall support needed for RWX protections.
RWX protections are more of a VM-level property, if I understood the use case correctly that some gfn ranges are to be marked non-executable by userspace. Setting RWX within guest_memfd would be kind of awkward since userspace must first translate GFN to offset, then set it using the offset within guest_memfd. Hence I think it's okay to have RWX stuff go through the regular KVM_SET_MEMORY_ATTRIBUTES *VM* ioctl and have it tracked in mem_attr_array.
I'd prefer not to have the module param choose between the use of mem_attr_array and guest_memfd conversion in case we need both mem_attr_array to support other stuff in future while supporting conversions.
Quoted 10 lines
The
kvm_memory_attributesstructure is compatible, all that's needed AFAICT is a union to clarify it's a pgoff instead of an address when used forguest_memfd.include/uapi/linux/kvm.h +0
-0@@ -1590,7 +1590,10 @@ struct kvm_stats_desc {#define KVM_SET_MEMORY_ATTRIBUTES _IOW(KVMIO, 0xd2, struct kvm_memory_attributes)
include/uapi/linux/kvm.h struct kvm_stats_desc { · line 1599
Quoted 10 lines
include/uapi/linux/kvm.h +4
-1struct kvm_memory_attributes { -__u64 address; +union { +__u64 address; +__u64 offset; + };__u64 size;__u64 attributes;__u64 flags;
struct kvm_memory_attributes doesn't have room for reporting the offset at which conversion failed (error_offset in the new struct). How do we handle this? Do we reuse the flags field, or do we not report error_offset?
Quoted 10 lines
Documentation/virt/kvm/api.rst struct kvm_gmem { · line 35
Quoted 5 lines
Documentation/virt/kvm/api.rst +5
-0+static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index); + +static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode) +{ + return inode->i_mapping->i_private_data;This is a hilarious bad helper. Everyone and their mother is going to think about "private vs. shared" when they see
kvm_gmem_private(), at least on the x86 side.
Totally missed this interpretation of private, lol. Too many interpretations of private: MAP_PRIVATE, CoCo's private vs shared, and i_private_data.
Quoted 18 lines
What's even more absurd is that the only "final" usage of the helper is to free/destroy the inode:
$ git grep kvm_gmem_private virt/kvm/guest_memfd.c:static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode) virt/kvm/guest_memfd.c: return kvm_gmem_private(inode)->allocator_ops; virt/kvm/guest_memfd.c: return kvm_gmem_private(inode)->allocator_private; virt/kvm/guest_memfd.c: mt = &kvm_gmem_private(inode)->shareability; virt/kvm/guest_memfd.c: mt = &kvm_gmem_private(inode)->shareability; virt/kvm/guest_memfd.c: mt = &kvm_gmem_private(inode)->shareability; virt/kvm/guest_memfd.c: mt = &kvm_gmem_private(inode)->shareability; virt/kvm/guest_memfd.c: struct kvm_gmem_inode_private *private = kvm_gmem_private(inode); virt/kvm/guest_memfd.c: struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);And in that case, using a wrapper is counter-productive, just reference
inode->i_mapping->i_private_datadirectly so that readeres don't have to jump through a useless layer.
Quoted 6 lines
Luckily, "struct
kvm_gmem_inode_private" no longer needs to exist, now that Shivank's NUMA policy series wraps thevfs_inodewith agmem_inode, and can be retrieved viaGMEM_I(). FWIW, before looking that series, I was going to suggest something liketo_gmem(), but I definitely think we should follow filesystems convention, not KVM vCPU/VM convention.
I'll align with the wrapper struct to align with filesystems conventions then.
Quoted 25 lines
Quoted 25 lines
Documentation/virt/kvm/api.rst +19
-0* folio_file_pfn - like folio_file_page, but return a pfn. * @folio: The folio which contains this index.@@ -29,6 +48,58 @@ static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) return folio_pfn(folio) + (index & (folio_nr_pages(folio) - 1)); } +#ifdef CONFIG_KVM_GMEM_SHARED_MEM + +static int kvm_gmem_shareability_setup(struct kvm_gmem_inode_private *private, + loff_t size, u64 flags) +{ + enum shareability m; + pgoff_t last; + + last = (size >> PAGE_SHIFT) - 1; + m = flags & GUEST_MEMFD_FLAG_INIT_PRIVATE ? SHAREABILITY_GUEST : + SHAREABILITY_ALL; + return mtree_store_range(&private->shareability, 0, last, xa_mk_value(m), + GFP_KERNEL); +} + +static enum shareability kvm_gmem_shareability_get(struct inode *inode, + pgoff_t index) +{ + struct maple_tree *mt;
Quoted 9 lines
Documentation/virt/kvm/api.rst static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 74
Quoted 5 lines
Documentation/virt/kvm/api.rst +5
-0+ void *entry; + + mt = &kvm_gmem_private(inode)->shareability; + entry = mtree_load(mt, index); + WARN(!entry,
WARN_ON_ONCE(), otherwise we risk escalating a per-VM problem into a system-wide DoS.
Will take note for next time.
Quoted 16 lines
Documentation/virt/kvm/api.rst static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 85
Quoted 11 lines
Documentation/virt/kvm/api.rst +11
-0+ "Shareability should always be defined for all indices in inode."); + + return xa_to_value(entry); +} + +static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index) +{ + if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL) + return ERR_PTR(-EACCES); + + return kvm_gmem_get_folio(inode, index);Please don't add 1-3 line helpers with one caller and very little hope of gaining additional users, especially in
guest_memfdwhere "shared" and "private" have multiple meanings, and so things like "get_shared_folio" are inherently ambiguous.
Quoted 3 lines
I'm pretty sure a lot of this stems from
CONFIG_KVM_GMEM_SHARED_MEM, which AFAICT simply won't exist. But just in case this is a Google3 pattern...
Will take note for next time.
Quoted 22 lines
Quoted 22 lines
Documentation/virt/kvm/api.rst +17
-0+} + +#else + +static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags) +{ + return 0; +} + +static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index) +{ + WARN_ONCE("Unexpected call to get shared folio.") + return NULL; +} + +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ + static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, pgoff_t index, struct folio *folio) {@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)
Quoted 9 lines
Documentation/virt/kvm/api.rst static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf) · line 407
Quoted 4 lines
Documentation/virt/kvm/api.rst +1
-1filemap_invalidate_lock_shared(inode->i_mapping); - folio = kvm_gmem_get_folio(inode, vmf->pgoff); + folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);I am fairly certain there's a TOCTOU bug here. AFAICT, nothing prevents the underlying memory from being converted from shared=>private after checking that the page is SHARED.
Conversions take the filemap_invalidate_lock() too, along with allocations, truncations.
Because the filemap_invalidate_lock() might be reused for other fs-specific operations, I didn't do the mt_set_external_lock() thing to lock at a low level to avoid nested locking or special maple tree code to avoid taking the lock on other paths.
Quoted 15 lines
The locking rules for the
maple_treeare also undocumented and haphazard. I think we can kill several birds with one stone by protecting the attributes withinvalidate_lock. A bonus with usinginvalidate_lockis that it's a sleepable lock, not a spinlock. I don't think there's anything that would immediately benefit? But if we wanted to populate the tree on-demand (versus pre-filling all possible pages), then it'd be easier to handle things like allocations in a race free manner./* * Protect the attributes with the invalidation lock, which will always * be held on conversions */ mt_init_flags(&gi->attributes, MT_FLAGS_LOCK_EXTERN); mt_set_external_lock(&gi->attributes, &inode->i_mapping->invalidate_lock);
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Sean ChristophersonQuoted 15 lines · Sean Christopherson
Review
Quoted 7 lines
(quoted diff) +6
-0+}; + +enum shareability { + SHAREABILITY_GUEST = 1, /* Only the guest can map (fault) folios in this range. */ + SHAREABILITY_ALL = 2, /* Both guest and host can fault folios in this range. */ +};Rather than define new values and new KVM uAPI, I think we should instead simply support
KVM_SET_MEMORY_ATTRIBUTES. We'll probably need a new CAP, as I'm not sure supporting KVM_CHECK_EXTENSION+KVM_CAP_MEMORY_ATTRIBUTES on a gmem fd would be a good idea (e.g. trying to doKVM_CAP_GUEST_MEMFD_FLAGSon a gmem fd doesn't work because the whole point is to get flags _before_ creating the gmem instance). But adding e.g.KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTESis easy enough.
Quoted 6 lines
But for specifying PRIVATE vs. SHARED, I don't see any reason to define new uAPI. I also don't want an entirely new set of terms in KVM to describe the same things. PRIVATE and SHARED are far from perfect, but they're better than https://xkcd.com/927.
And if we ever want to let userspace restrict RWX protections in gmem, we'll have a ready-made way to do so.
I don't understand why we need to reuse KVM_SET_MEMORY_ATTRIBUTES. It anyways is a new ABI as it's on a guest_memfd FD instead of KVM FD.
RWX protections seem to be pagetable configuration rather than guest_memfd properties. Can mmap flags + kvm userfaultfd help enforce RWX protections?
Sean Christopherson
maintainerRe: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ackerley TngQuoted 15 lines · Ackerley Tng
Quoted 13 lines · Sean Christopherson
Review
Quoted 4 lines · Ackerley Tng
(quoted diff) +4
-0+enum shareability { + SHAREABILITY_GUEST = 1, /* Only the guest can map (fault) folios in this range. */ + SHAREABILITY_ALL = 2, /* Both guest and host can fault folios in this range. */ +};Rather than define new values and new KVM uAPI, I think we should instead simply support
KVM_SET_MEMORY_ATTRIBUTES. We'll probably need a new CAP, as I'm not sure supporting KVM_CHECK_EXTENSION+KVM_CAP_MEMORY_ATTRIBUTES on a gmem fd would be a good idea (e.g. trying to doKVM_CAP_GUEST_MEMFD_FLAGSon a gmem fd doesn't work because the whole point is to get flags _before_ creating the gmem instance). But adding e.g.KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTESis easy enough.
Quoted 4 lines
I've read this a few times and I'm a bit confused, so just making sure:
you are suggesting that we reuse theKVM_SET_MEMORY_ATTRIBUTESioctl as aguest_memfd(not a VM) ioctl and still store private/shared state withinguest_memfd, right?
Yep. Something like:
static long kvm_gmem_set_attributes(struct file *file, void __user *argp)
{
struct gmem_file *f = file->private_data;
struct inode *inode = file_inode(file);
struct kvm_memory_attributes attrs;
pgoff_t err_index;
int r;
if (copy_from_user(&attrs, argp, sizeof(attrs)))
return -EFAULT;
if (attrs.flags)
return -EINVAL;
if (attrs.attributes & ~kvm_gmem_supported_mem_attributes(f))
return -EINVAL;
if (attrs.size == 0 || attrs.offset + attrs.size < attrs.offset)
return -EINVAL;
if (!PAGE_ALIGNED(attrs.offset) || !PAGE_ALIGNED(attrs.offset))
return -EINVAL;
if (attrs.offset > inode->i_size ||
attrs.offset + attrs.size > inode->i_size)
return -EINVAL;
r = __kvm_gmem_set_attributes(inode, &attrs, &err_index);
if (r) {
attrs.offset = err_index << PAGE_SHIFT;
if (copy_to_user(argp, &attrs, sizeof(attrs)))
return -EFAULT;
return r;
}
return 0;
}static long kvm_gmem_ioctl(struct file *file, unsigned int ioctl,
unsigned long arg)
{
switch (ioctl) {
case KVM_SET_MEMORY_ATTRIBUTES:
return kvm_gmem_set_attributes(file, (void __user *)arg);
default:
return -ENOTTY;
}
}Quoted 5 lines
I think fundamentally the introduction of the
guest_memfdioctls was motivated by how private/shared state is a property of memory and not a property of the VM. (IIRC you were the one to most succinctly phrase it this way on one of theguest_memfdbiweeklies.) So I hope you don't mean to revert to doing conversions through a VM ioctl.
I do not. Ah shoot. I responded to my (much earlier) mail on this to clarify exactly this point, but I botched the Cc and threading, and it didn't make it's way to you.
https://lore.kernel.org/all/[email protected]
Quoted 10 lines
Quoted 6 lines
But for specifying PRIVATE vs. SHARED, I don't see any reason to define new uAPI. I also don't want an entirely new set of terms in KVM to describe the same things. PRIVATE and SHARED are far from perfect, but they're better than https://xkcd.com/927.
And if we ever want to let userspace restrict RWX protections in gmem, we'll have a ready-made way to do so.Would like to understand more about RWX protections: is the use case to let userspace specify that certain ranges of guest memory are to be mapped into stage 2 page tables without executable permissions?
Yep. Or execute-only. Or read-only. The primary use case I'm aware of is for supporting things VBS (Hyper-V's virtualization based security) and HEKI[1] (which is effectively the same thing as VBS, and is indeed being dropped in favor of simply piggybacking the VBS guest<=>host ABI).
VBS allows the kernel to deprivilege itself, and hoist a small amount of code into a more privilege "thing". In KVM, the separate privilege domains will be called "planes"[2]. For RWX protections, the more privileged plane would have full RWX access to all of guest memory, while the deprivilege kernel will have select chunks of memory mapped RO (e.g. kernel page tables, GDT, IDT, etc., or potentially not at all (see Credential Guard).
I don't know if tracking per-plane RWX state in guest_memfd would be a good idea, but it costs practically nothing to keep the possibility open.
[1] https://lore.kernel.org/all/[email protected]
[2] https://lore.kernel.org/all/[email protected]
Quoted 7 lines
Is there a further use case to let the guest specify that userspace must not
mmap()some ranges as executable?For
guest_memfdthe userspace mapping permissions are already defined by userspace and so unlessguest_memfdmust enforce something on behalf of the guest, there shouldn't be anything more thatguest_memfdshould track with respect to RWX permissions.
But not all userspaces are created equal. E.g. if a VM is sharing memory with another entity, it might want to restrict that sharing to be read-only. I don't know that memory attributes would be the best way to express such rules, just saying that fully relying on mmap() has limitations.
Quoted 20 lines
Quoted 10 lines
Internally, that let's us do some fun things in KVM. E.g. if we make the "disable legacy per-VM memory attributes" a read-only module param, then we can wire up a
static_call()forkvm_get_memory_attributes()and thenkvm_mem_is_private()will Just Work.static inline unsigned long
kvm_get_memory_attributes(struct kvm *kvm, gfn_t gfn){ return static_call(__kvm_get_memory_attributes)(kvm, gfn);}
Quoted 9 lines
static inline bool
kvm_mem_is_private(struct kvm *kvm, gfn_t gfn){ return kvm_get_memory_attributes(kvm, gfn) & KVM_MEMORY_ATTRIBUTE_PRIVATE;}
That might trigger some additional surgery if/when we want to support RWX protections on a per-VM basis _and_ a per-gmem basic, but I suspect such churn would pale in comparison to the overall support needed for RWX protections.
Quoted 7 lines
RWX protections are more of a VM-level property, if I understood the use case correctly that some gfn ranges are to be marked non-executable by userspace. Setting RWX within
guest_memfdwould be kind of awkward since userspace must first translate GFN to offset, then set it using the offset withinguest_memfd. Hence I think it's okay to have RWX stuff go through the regularKVM_SET_MEMORY_ATTRIBUTES*VM* ioctl and have it tracked inmem_attr_array.
Maybe. It will depend on how the use cases shake out. E.g. before the planes idea came along, the proposal for supporting different privilege levels was to represent each privilege level with its own "struct kvm", at which point tracking RWX protections per-VM (struct kvm) made sense.
But with planes, that's no longer true. E.g. we'd need RWX flags for plane0 and separate RWX flags for plane1 regardless of whether they're tracked in struct kvm or in the gmem instance.
To be clear, I don't have an opinion one way or the other, because what we'll end up with is quite unclear. All I was calling out is that reusing KVM_SET_MEMORY_ATTRIBUTES provides a lot of the plumbing, _if_ we want to define RWX protections on a gmem instance.
Quoted 4 lines
I'd prefer not to have the module param choose between the use of
mem_attr_arrayandguest_memfdconversion in case we need bothmem_attr_arrayto support other stuff in future while supporting conversions.
Luckily, we don't actually need to make a decision on this, because PRIVATE is the only attribute that exists. Which is partly why I want to go with a module param. We can make the behavior very definitive without significant risk of causing ABI hell.
It's entirely possible I'm completely wrong and we'll end up with per-VM RWX protections and no other per-gmem memory attributes, but as above, unwinding or adjusting the module param will be a drop in the bucket compared to the effort needed to add whatever support comes along.
Quoted 10 lines
Quoted 10 lines
The
kvm_memory_attributesstructure is compatible, all that's needed AFAICT is a union to clarify it's a pgoff instead of an address when used forguest_memfd.include/uapi/linux/kvm.h +0
-0@@ -1590,7 +1590,10 @@ struct kvm_stats_desc {#define KVM_SET_MEMORY_ATTRIBUTES _IOW(KVMIO, 0xd2, struct kvm_memory_attributes)
Quoted 15 lines
include/uapi/linux/kvm.h struct kvm_stats_desc { · line 1599
Quoted 10 lines
include/uapi/linux/kvm.h +4
-1struct kvm_memory_attributes { -__u64 address; +union { +__u64 address; +__u64 offset; + };__u64 size;__u64 attributes;__u64 flags;struct
kvm_memory_attributesdoesn't have room for reporting the offset at which conversion failed (error_offsetin the new struct). How do we handle this? Do we reuse the flags field, or do we not reporterror_offset?
Write back at address/offset (and update size too, which I probably forgot to do). Ugh, but it's defined _IOW. I forget if that matters in practice (IIRC, it's not enforced anywhere, i.e. purely informational for userspace).
Quoted 15 lines
Quoted 5 lines
Quoted 5 lines
static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct
kvm_memory_slot*slot,(quoted diff) +0
-0pgoff_t index, struct folio *folio) {@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)Quoted 9 lines
Review static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf) · line 407
Quoted 4 lines
(quoted diff) +1
-1filemap_invalidate_lock_shared(inode->i_mapping); - folio = kvm_gmem_get_folio(inode, vmf->pgoff); + folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);I am fairly certain there's a TOCTOU bug here. AFAICT, nothing prevents the underlying memory from being converted from shared=>private after checking that the page is SHARED.
Quoted 7 lines
Conversions take the
filemap_invalidate_lock()too, along with allocations, truncations.Because the
filemap_invalidate_lock()might be reused for other fs-specific operations, I didn't do themt_set_external_lock()thing to lock at a low level to avoid nested locking or special maple tree code to avoid taking the lock on other paths.
mt_set_external_lock() is a nop. It exists purely for lockdep assertions. Per the comment for MT_FLAGS_LOCK_EXTERN, "mt_lock is not used", LOCK_EXTERN simply
tells maple tree to not use/take mt_lock. I.e. it doesn't say "take this lock
instead", it says "I'll handle locking".
Sean Christopherson
maintainerRe: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Vishal AnnapurveQuoted 23 lines · Vishal Annapurve
Quoted 15 lines · Sean Christopherson
Review
Quoted 7 lines
(quoted diff) +6
-0+}; + +enum shareability { + SHAREABILITY_GUEST = 1, /* Only the guest can map (fault) folios in this range. */ + SHAREABILITY_ALL = 2, /* Both guest and host can fault folios in this range. */ +};Rather than define new values and new KVM uAPI, I think we should instead simply support
KVM_SET_MEMORY_ATTRIBUTES. We'll probably need a new CAP, as I'm not sure supporting KVM_CHECK_EXTENSION+KVM_CAP_MEMORY_ATTRIBUTES on a gmem fd would be a good idea (e.g. trying to doKVM_CAP_GUEST_MEMFD_FLAGSon a gmem fd doesn't work because the whole point is to get flags _before_ creating the gmem instance). But adding e.g.KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTESis easy enough.Quoted 6 lines
But for specifying PRIVATE vs. SHARED, I don't see any reason to define new uAPI. I also don't want an entirely new set of terms in KVM to describe the same things. PRIVATE and SHARED are far from perfect, but they're better than https://xkcd.com/927.
And if we ever want to let userspace restrict RWX protections in gmem, we'll have a ready-made way to do so.
Quoted 2 lines
I don't understand why we need to reuse
KVM_SET_MEMORY_ATTRIBUTES. It anyways is a new ABI as it's on aguest_memfdFD instead of KVM FD.
Yes, it's new functionality, but the semantics are the same (modulo s/address/offset), which makes life easier for KVM and its developers. Specifically I want to avoid ending up with two entirely different ways for describing private vs. shared memory. E.g. I don't want to have to translate between SHAREABILITY_GUEST and PRIVATE, in code or in conversation.
Quoted 3 lines
RWX protections seem to be pagetable configuration rather than
guest_memfdproperties. Can mmap flags + kvm userfaultfd help enforce RWX protections?
No, because mmap() is optional. Potential use cases are for (seletively) restricting _guest_ access as well as host access. mmap() isn't a good fit regardless, as that's much more about describing what the process wants, not the properties of the underlying memory.
E.g. read-only and noexec file systems exist for a reason.
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Sean ChristophersonQuoted 76 lines · Sean Christopherson
Quoted 15 lines · Ackerley Tng
Quoted 13 lines · Sean Christopherson
Review
Quoted 4 lines · Ackerley Tng
(quoted diff) +4
-0+enum shareability { + SHAREABILITY_GUEST = 1, /* Only the guest can map (fault) folios in this range. */ + SHAREABILITY_ALL = 2, /* Both guest and host can fault folios in this range. */ +};Rather than define new values and new KVM uAPI, I think we should instead simply support
KVM_SET_MEMORY_ATTRIBUTES. We'll probably need a new CAP, as I'm not sure supporting KVM_CHECK_EXTENSION+KVM_CAP_MEMORY_ATTRIBUTES on a gmem fd would be a good idea (e.g. trying to doKVM_CAP_GUEST_MEMFD_FLAGSon a gmem fd doesn't work because the whole point is to get flags _before_ creating the gmem instance). But adding e.g.KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTESis easy enough.Quoted 4 lines
I've read this a few times and I'm a bit confused, so just making sure:
you are suggesting that we reuse theKVM_SET_MEMORY_ATTRIBUTESioctl as aguest_memfd(not a VM) ioctl and still store private/shared state withinguest_memfd, right?Yep. Something like:
static long
kvm_gmem_set_attributes(struct file *file, void __user *argp){ struct gmem_file *f = file->private_data; struct inode *inode = file_inode(file); struct kvm_memory_attributes attrs; pgoff_t err_index; int r; if (copy_from_user(&attrs, argp, sizeof(attrs))) return -EFAULT; if (attrs.flags) return -EINVAL; if (attrs.attributes & ~kvm_gmem_supported_mem_attributes(f)) return -EINVAL; if (attrs.size == 0 || attrs.offset + attrs.size < attrs.offset) return -EINVAL; if (!PAGE_ALIGNED(attrs.offset) || !PAGE_ALIGNED(attrs.offset)) return -EINVAL; if (attrs.offset > inode->i_size || attrs.offset + attrs.size > inode->i_size) return -EINVAL; r = __kvm_gmem_set_attributes(inode, &attrs, &err_index); if (r) { attrs.offset = err_index << PAGE_SHIFT; if (copy_to_user(argp, &attrs, sizeof(attrs))) return -EFAULT; return r; } return 0; }static long kvm_gmem_ioctl(struct file *file, unsigned int ioctl,
unsigned long arg){ switch (ioctl) { case KVM_SET_MEMORY_ATTRIBUTES: return kvm_gmem_set_attributes(file, (void __user *)arg); default: return -ENOTTY; } }Quoted 5 lines
I think fundamentally the introduction of the
guest_memfdioctls was motivated by how private/shared state is a property of memory and not a property of the VM. (IIRC you were the one to most succinctly phrase it this way on one of theguest_memfdbiweeklies.) So I hope you don't mean to revert to doing conversions through a VM ioctl.
Quoted 6 lines
I do not. Ah shoot. I responded to my (much earlier) mail on this to clarify exactly this point, but I botched the Cc and threading, and it didn't make it's way to you.
Phew. Good to have this clarified.
Quoted 8 lines
Quoted 7 lines
[...snip...]
I'd prefer not to have the module param choose between the use of
mem_attr_arrayandguest_memfdconversion in case we need bothmem_attr_arrayto support other stuff in future while supporting conversions.
Quoted 5 lines
Luckily, we don't actually need to make a decision on this, because PRIVATE is the only attribute that exists. Which is partly why I want to go with a module param. We can make the behavior very definitive without significant risk of causing ABI hell.
Then maybe I'm misunderstanding the static_call() thing you were describing. Is it like, at KVM module initialization time,
if module_param == disable_tracking:
.__kvm_get_memory_attributes = read_attributes_from_guest_memfd
else
.__kvm_get_memory_attributes = read_attributes_from_mem_attr_array
With that, I can't have both CoCo private/shared state tracked in guest_memfd and RWX (as an example, could be any future attribute) tracked in mem_attr_array on the same VM.
Quoted 5 lines
It's entirely possible I'm completely wrong and we'll end up with per-VM RWX protections and no other per-gmem memory attributes, but as above, unwinding or adjusting the module param will be a drop in the bucket compared to the effort needed to add whatever support comes along.
Is a module param a weaker userspace contract such that the definition for module params can be more flexibly adjusted?
Quoted 26 lines
Quoted 10 lines
Quoted 10 lines
The
kvm_memory_attributesstructure is compatible, all that's needed AFAICT is a union to clarify it's a pgoff instead of an address when used forguest_memfd.include/uapi/linux/kvm.h +0
-0@@ -1590,7 +1590,10 @@ struct kvm_stats_desc {#define KVM_SET_MEMORY_ATTRIBUTES _IOW(KVMIO, 0xd2, struct kvm_memory_attributes)Quoted 15 lines
include/uapi/linux/kvm.h struct kvm_stats_desc { · line 1599
Quoted 10 lines
include/uapi/linux/kvm.h +4
-1struct kvm_memory_attributes { -__u64 address; +union { +__u64 address; +__u64 offset; + };__u64 size;__u64 attributes;__u64 flags;struct
kvm_memory_attributesdoesn't have room for reporting the offset at which conversion failed (error_offsetin the new struct). How do we handle this? Do we reuse the flags field, or do we not reporterror_offset?
Quoted 1 line
Write back at address/offset
I think it might be surprising to the userspace program, when it wants to check the offset that it had requested and found that it changed due to an error, or upon decoding the error, be unable to find the original offset it had requested. Like,
printf("Error during conversion from offset=%lx with size=%lx, at
error_offset=%lx", attr.offset, attr.size, attr.error_offset)
would be nicer than
original_offset = attr.offset
printf("Error during conversion from offset=%lx with size=%lx, at
error_offset=%lx", original_offset, attr.size, attr.error_offset)
Quoted 1 line
(and update size too, which I probably forgot to do).
Why does size need to be updated? I think u64 for size is great, and size is better than nr_pages since nr_pages differs on different platforms based on PAGE_SIZE and also nr_pages introduces the question of "was it hugetlb, or a native page size?".
Quoted 3 lines
Ugh, but it's defined
_IOW. I forget if that matters in practice (IIRC, it's not enforced anywhere, i.e. purely informational for userspace).
I didn't notice this IOW vs IORW part, but if it starts getting enforced/specified [1] or auto-documented we'd be in trouble.
At this point, maybe it's better to just have a different ioctl number and struct definition. I feel that it would be easier for a user to associate/separate
+ KVM_SET_MEMORY_ATTRIBUTES
+ Is VM ioctl
+ Is a write-only ioctl
+ Is for setting memory attributes at a VM level
+ Use struct kvm_memory_attributes for this
+ KVM_GUEST_MEMFD_SET_MEMORY_ATTRIBUTES (name TBD)
+ Is guest_memfd ioctl
+ Is a read/write ioctl
+ Is for setting memory attributes only for this guest_memfd
+ Use struct guest_memfd_memory_attributes for this
+ Also decode errors from this struct
[1] https://lore.kernel.org/all/[email protected]/
Quoted 23 lines
Quoted 15 lines
Quoted 5 lines
Quoted 5 lines
static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct
kvm_memory_slot*slot,(quoted diff) +0
-0pgoff_t index, struct folio *folio) {@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)Quoted 9 lines
Review static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf) · line 407
Quoted 4 lines
(quoted diff) +1
-1filemap_invalidate_lock_shared(inode->i_mapping); - folio = kvm_gmem_get_folio(inode, vmf->pgoff); + folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);I am fairly certain there's a TOCTOU bug here. AFAICT, nothing prevents the underlying memory from being converted from shared=>private after checking that the page is SHARED.
Quoted 7 lines
Conversions take the
filemap_invalidate_lock()too, along with allocations, truncations.Because the
filemap_invalidate_lock()might be reused for other fs-specific operations, I didn't do themt_set_external_lock()thing to lock at a low level to avoid nested locking or special maple tree code to avoid taking the lock on other paths.
Quoted 4 lines
mt_set_external_lock()is a nop. It exists purely for lockdep assertions. Per the comment forMT_FLAGS_LOCK_EXTERN, "mt_lockis not used",LOCK_EXTERNsimply
tells maple tree to not use/takemt_lock. I.e. it doesn't say "take this lock
instead", it says "I'll handle locking".
Thanks for pointing this out!
Conversions (and others) taking the filemap_invalidate_lock() probably fixes the TOCTOU bug, right?
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
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ackerley TngQuoted 2 lines · Ackerley Tng
Sean Christopherson <[email protected]> writes:
[snip]
Quoted 29 lines
Quoted 11 lines
Internally, that let's us do some fun things in KVM. E.g. if we make the "disable legacy per-VM memory attributes" a read-only module param, then we can wire up a
static_call()forkvm_get_memory_attributes()and thenkvm_mem_is_private()will Just Work.static inline unsigned long
kvm_get_memory_attributes(struct kvm *kvm, gfn_t gfn){ return static_call(__kvm_get_memory_attributes)(kvm, gfn);}
Quoted 9 lines
static inline bool
kvm_mem_is_private(struct kvm *kvm, gfn_t gfn){ return kvm_get_memory_attributes(kvm, gfn) & KVM_MEMORY_ATTRIBUTE_PRIVATE;}
That might trigger some additional surgery if/when we want to support RWX protections on a per-VM basis _and_ a per-gmem basic, but I suspect such churn would pale in comparison to the overall support needed for RWX protections.
RWX protections are more of a VM-level property, if I understood the use case correctly that some gfn ranges are to be marked non-executable by userspace. Setting RWX within
guest_memfdwould be kind of awkward since userspace must first translate GFN to offset, then set it using the offset withinguest_memfd. Hence I think it's okay to have RWX stuff go through the regularKVM_SET_MEMORY_ATTRIBUTES*VM* ioctl and have it tracked inmem_attr_array.
Quoted 4 lines
I'd prefer not to have the module param choose between the use of
mem_attr_arrayandguest_memfdconversion in case we need bothmem_attr_arrayto support other stuff in future while supporting conversions.
I'm getting pretty confused on how userspace is going to know which ioctl to use VM vs gmem.
I was starting to question if going through the VM ioctl should actually change the guest_memfd flags (shareability).
In a prototype I'm playing with shareability has become a bit field which I think aligns with the idea of expanding the memory attributes. But I've had some issues with the TDX tests in trying to decipher when to call vm_set_memory_attributes() vs guest_memfd_convert_private().
Quoted 11 lines
Quoted 11 lines
The
kvm_memory_attributesstructure is compatible, all that's needed AFAICT is a union to clarify it's a pgoff instead of an address when used forguest_memfd.include/uapi/linux/kvm.h +0
-0@@ -1590,7 +1590,10 @@ struct kvm_stats_desc {#define KVM_SET_MEMORY_ATTRIBUTES _IOW(KVMIO, 0xd2, struct kvm_memory_attributes)
Quoted 15 lines
include/uapi/linux/kvm.h struct kvm_stats_desc { · line 1599
Quoted 10 lines
include/uapi/linux/kvm.h +4
-1struct kvm_memory_attributes { -__u64 address; +union { +__u64 address; +__u64 offset; + };__u64 size;__u64 attributes;__u64 flags;struct
kvm_memory_attributesdoesn't have room for reporting the offset at which conversion failed (error_offsetin the new struct). How do we handle this? Do we reuse the flags field, or do we not reporterror_offset?
We could extend this for gmem's version of the struct.
Quoted 12 lines
Quoted 11 lines
Review
Quoted 6 lines
(quoted diff) +5
-0+static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index); + +static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode) +{ + return inode->i_mapping->i_private_data;This is a hilarious bad helper. Everyone and their mother is going to think about "private vs. shared" when they see
kvm_gmem_private(), at least on the x86 side.
Quoted 4 lines
Totally missed this interpretation of private, lol. Too many interpretations of private:
MAP_PRIVATE, CoCo's private vs shared, andi_private_data.
FWIW this did not confuse me and it probably should have... ;-) I'm fine with Sean's suggestion though.
Quoted 32 lines
Quoted 22 lines
Quoted 22 lines
(quoted diff) +17
-0+} + +#else + +static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags) +{ + return 0; +} + +static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index) +{ + WARN_ONCE("Unexpected call to get shared folio.") + return NULL; +} + +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ + static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, pgoff_t index, struct folio *folio) {@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)Quoted 9 lines
Review static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf) · line 407
Quoted 4 lines
(quoted diff) +1
-1filemap_invalidate_lock_shared(inode->i_mapping); - folio = kvm_gmem_get_folio(inode, vmf->pgoff); + folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);I am fairly certain there's a TOCTOU bug here. AFAICT, nothing prevents the underlying memory from being converted from shared=>private after checking that the page is SHARED.
Quoted 7 lines
Conversions take the
filemap_invalidate_lock()too, along with allocations, truncations.Because the
filemap_invalidate_lock()might be reused for other fs-specific operations, I didn't do themt_set_external_lock()thing to lock at a low level to avoid nested locking or special maple tree code to avoid taking the lock on other paths.
I don't think using the filemap_invalidate_lock() is going to work well here. I've had some hangs on it in my testing and experiments. I think it is better to specifically lock the state tracking itself. I believe Michael mentioned this as well in a previous thread.
Ira
[snip]
Sean Christopherson
maintainerRe: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ackerley TngQuoted 15 lines · Ackerley Tng
Quoted 10 lines · Sean Christopherson
Quoted 4 lines
I'd prefer not to have the module param choose between the use of
mem_attr_arrayandguest_memfdconversion in case we need bothmem_attr_arrayto support other stuff in future while supporting conversions.Luckily, we don't actually need to make a decision on this, because PRIVATE is the only attribute that exists. Which is partly why I want to go with a module param. We can make the behavior very definitive without significant risk of causing ABI hell.
Then maybe I'm misunderstanding the
static_call()thing you were describing. Is it like, at KVM module initialization time,
Quoted 8 lines
if
module_param==disable_tracking:
.__kvm_get_memory_attributes =read_attributes_from_guest_memfd
else
.__kvm_get_memory_attributes =read_attributes_from_mem_attr_arrayWith that, I can't have both CoCo private/shared state tracked in
guest_memfdand RWX (as an example, could be any future attribute) tracked inmem_attr_arrayon the same VM.
More or less.
Quoted 8 lines
Quoted 5 lines
It's entirely possible I'm completely wrong and we'll end up with per-VM RWX protections and no other per-gmem memory attributes, but as above, unwinding or adjusting the module param will be a drop in the bucket compared to the effort needed to add whatever support comes along.
Is a module param a weaker userspace contract such that the definition for module params can be more flexibly adjusted?
Yes, much weaker.
Quoted 26 lines
Quoted 26 lines
Quoted 25 lines
Quoted 10 lines
The
kvm_memory_attributesstructure is compatible, all that's needed AFAICT is a union to clarify it's a pgoff instead of an address when used forguest_memfd.include/uapi/linux/kvm.h +0
-0@@ -1590,7 +1590,10 @@ struct kvm_stats_desc {#define KVM_SET_MEMORY_ATTRIBUTES _IOW(KVMIO, 0xd2, struct kvm_memory_attributes)include/uapi/linux/kvm.h struct kvm_stats_desc { · line 1599
Quoted 10 lines
include/uapi/linux/kvm.h +4
-1struct kvm_memory_attributes { -__u64 address; +union { +__u64 address; +__u64 offset; + };__u64 size;__u64 attributes;__u64 flags;struct
kvm_memory_attributesdoesn't have room for reporting the offset at which conversion failed (error_offsetin the new struct). How do we handle this? Do we reuse the flags field, or do we not reporterror_offset?
Quoted 6 lines
Quoted 1 line
Write back at address/offset
I think it might be surprising to the userspace program, when it wants to check the offset that it had requested and found that it changed due to an error, or upon decoding the error, be unable to find the original offset it had requested.
It's a somewhat common pattern in the kernel. Updating the offset+size is most often used with -EAGAIN to say "got this far, try the syscall again from this point".
Quoted 11 lines
Like,
printf("Error during conversion from offset=%lx with size=%lx, at
error_offset=%lx", attr.offset, attr.size, attr.error_offset)would be nicer than
original_offset= attr.offset
printf("Error during conversion from offset=%lx with size=%lx, at
error_offset=%lx",original_offset, attr.size, attr.error_offset)
Quoted 6 lines
Quoted 1 line
(and update size too, which I probably forgot to do).
Why does size need to be updated? I think u64 for size is great, and size is better than
nr_pagessincenr_pagesdiffers on different platforms based onPAGE_SIZEand alsonr_pagesintroduces the question of "was it hugetlb, or a native page size?".
I meant update the number of bytes remaining when updating the offset so that userspace can redo the ioctl without having to update parameters.
Quoted 6 lines
Quoted 3 lines
Ugh, but it's defined
_IOW. I forget if that matters in practice (IIRC, it's not enforced anywhere, i.e. purely informational for userspace).I didn't notice this IOW vs IORW part, but if it starts getting enforced/specified [1] or auto-documented we'd be in trouble.
IOW vs IORW is alread specified in the ioctl. More below.
Quoted 3 lines
At this point, maybe it's better to just have a different ioctl number and struct definition. I feel that it would be easier for a user to associate/separate
Amusingly, we'd only need a different name along with the IORW thing. A full ioctl number is comproised of the "directory" (KVM), the number, the size of the payload, and how the payload is accessed.
#define _IOC(dir,type,nr,size) \ (((dir) << _IOC_DIRSHIFT) | \ ((type) << _IOC_TYPESHIFT) | \ ((nr) << _IOC_NRSHIFT) | \ ((size) << _IOC_SIZESHIFT))
So this:
#define KVM_SET_MEMORY_ATTRIBUTES _IOW(KVMIO, 0xd2, struct kvm_memory_attributes) #define KVM_SET_MEMORY_ATTRIBUTES2 _IOWR(KVMIO, 0xd2, struct kvm_memory_attributes2)
actually generates two different values, and so is two different ioctls from a code perspective.
The "size" of the payload is nice to have as it allows userspace to assert that it's passing the right structure, e.g. this static assert from KVM selftests:
#define kvm_do_ioctl(fd, cmd, arg) \
({ \
kvm_static_assert(!_IOC_SIZE(cmd) || sizeof(*arg) == _IOC_SIZE(cmd)); \
ioctl(fd, cmd, arg); \
})Quoted 11 lines
+
KVM_SET_MEMORY_ATTRIBUTES
+ Is VM ioctl
+ Is a write-only ioctl
+ Is for setting memory attributes at a VM level
+ Use structkvm_memory_attributesfor this
+KVM_GUEST_MEMFD_SET_MEMORY_ATTRIBUTES(name TBD)
+ Isguest_memfdioctl
+ Is a read/write ioctl
+ Is for setting memory attributes only for thisguest_memfd
+ Use structguest_memfd_memory_attributesfor this
+ Also decode errors from this struct
+ Has extra padding for future expansion (because why not)
If we really truly need a new ioctl, I'd probably prefer KVM_SET_MEMORY_ATTRIBUTES2. Yeah, it's silly, but I don't think baking GUEST_MEMFD into the names buys us anything. Then we can use KVM_SET_MEMORY_ATTRIBUTES2 on a VM if the need ever arises.
Alternative #1 is to try and unwind on failure, but that gets complex, and it simply can't be done for some CoCo VMs. E.g. a private=>shared conversion for TDX is descrutive.
Alternative #2 is to make the updates atomic and all-or-nothing, which is what we did for per-VM attributes. That's doable, but it'd either be much more complex than telling userspace to retry, or we'd have to lose the maple tree optimizations (which is effectively what we did for per-VM attributes).
Quoted 30 lines
[1] https://lore.kernel.org/all/[email protected]/
Quoted 23 lines
Quoted 15 lines
Quoted 5 lines
Quoted 5 lines
static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct
kvm_memory_slot*slot,(quoted diff) +0
-0pgoff_t index, struct folio *folio) {@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)Quoted 9 lines
Review static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf) · line 407
Quoted 4 lines
(quoted diff) +1
-1filemap_invalidate_lock_shared(inode->i_mapping); - folio = kvm_gmem_get_folio(inode, vmf->pgoff); + folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);I am fairly certain there's a TOCTOU bug here. AFAICT, nothing prevents the underlying memory from being converted from shared=>private after checking that the page is SHARED.
Quoted 7 lines
Conversions take the
filemap_invalidate_lock()too, along with allocations, truncations.Because the
filemap_invalidate_lock()might be reused for other fs-specific operations, I didn't do themt_set_external_lock()thing to lock at a low level to avoid nested locking or special maple tree code to avoid taking the lock on other paths.Quoted 4 lines
mt_set_external_lock()is a nop. It exists purely for lockdep assertions. Per the comment forMT_FLAGS_LOCK_EXTERN, "mt_lockis not used",LOCK_EXTERNsimply
tells maple tree to not use/takemt_lock. I.e. it doesn't say "take this lock
instead", it says "I'll handle locking".
Quoted 4 lines
Thanks for pointing this out!
Conversions (and others) taking the
filemap_invalidate_lock()probably fixes the TOCTOU bug, right?
Yes, grabbing a reference to the folio under lock and thus elevating its refcount should prevent conversions to private from that point forward, until the PTE is zapped and the folio is released:
filemap_invalidate_lock_shared(inode->i_mapping); if (kvm_gmem_is_shared_mem(inode, vmf->pgoff)) folio = kvm_gmem_get_folio(inode, vmf->pgoff); else folio = ERR_PTR(-EACCES); filemap_invalidate_unlock_shared(inode->i_mapping);
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
Quoted 21 lines · Sean Christopherson
Quoted 20 lines · Ackerley Tng
Quoted 10 lines · Sean Christopherson
Quoted 4 lines
I'd prefer not to have the module param choose between the use of
mem_attr_arrayandguest_memfdconversion in case we need bothmem_attr_arrayto support other stuff in future while supporting conversions.Luckily, we don't actually need to make a decision on this, because PRIVATE is the only attribute that exists. Which is partly why I want to go with a module param. We can make the behavior very definitive without significant risk of causing ABI hell.
Then maybe I'm misunderstanding the
static_call()thing you were describing. Is it like, at KVM module initialization time,if
module_param==disable_tracking:
.__kvm_get_memory_attributes =read_attributes_from_guest_memfd
else
.__kvm_get_memory_attributes =read_attributes_from_mem_attr_array
Quoted 6 lines
Quoted 3 lines
With that, I can't have both CoCo private/shared state tracked in
guest_memfdand RWX (as an example, could be any future attribute) tracked inmem_attr_arrayon the same VM.More or less.
Hm okay. So introducing the module param will only allow the use of one of the following?
+ KVM_SET_MEMORY_ATTRIBUTES (vm ioctl)
+ KVM_SET_MEMORY_ATTRIBUTES2 (guest_memfd ioctl)
Then I guess using a module param which is a weaker userspace contract allows us to later enable both vm and guest_memfd ioctl if the need arises?
Quoted 11 lines
Quoted 8 lines
Quoted 5 lines
It's entirely possible I'm completely wrong and we'll end up with per-VM RWX protections and no other per-gmem memory attributes, but as above, unwinding or adjusting the module param will be a drop in the bucket compared to the effort needed to add whatever support comes along.
Is a module param a weaker userspace contract such that the definition for module params can be more flexibly adjusted?
Yes, much weaker.
I have a new tool in my toolbox now :)
Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 10 lines
Quoted 10 lines
The
kvm_memory_attributesstructure is compatible, all that's needed AFAICT is a union to clarify it's a pgoff instead of an address when used forguest_memfd.include/uapi/linux/kvm.h +0
-0@@ -1590,7 +1590,10 @@ struct kvm_stats_desc {#define KVM_SET_MEMORY_ATTRIBUTES _IOW(KVMIO, 0xd2, struct kvm_memory_attributes)Quoted 15 lines
include/uapi/linux/kvm.h struct kvm_stats_desc { · line 1599
Quoted 10 lines
include/uapi/linux/kvm.h +4
-1struct kvm_memory_attributes { -__u64 address; +union { +__u64 address; +__u64 offset; + };__u64 size;__u64 attributes;__u64 flags;struct
kvm_memory_attributesdoesn't have room for reporting the offset at which conversion failed (error_offsetin the new struct). How do we handle this? Do we reuse the flags field, or do we not reporterror_offset?Write back at address/offset
Quoted 9 lines
Quoted 4 lines
I think it might be surprising to the userspace program, when it wants to check the offset that it had requested and found that it changed due to an error, or upon decoding the error, be unable to find the original offset it had requested.
It's a somewhat common pattern in the kernel. Updating the offset+size is most often used with
-EAGAINto say "got this far, try the syscall again from this point".
TIL, thanks!
Quoted 73 lines
Quoted 11 lines
Like,
printf("Error during conversion from offset=%lx with size=%lx, at
error_offset=%lx", attr.offset, attr.size, attr.error_offset)would be nicer than
original_offset= attr.offset
printf("Error during conversion from offset=%lx with size=%lx, at
error_offset=%lx",original_offset, attr.size, attr.error_offset)Quoted 6 lines
Quoted 1 line
(and update size too, which I probably forgot to do).
Why does size need to be updated? I think u64 for size is great, and size is better than
nr_pagessincenr_pagesdiffers on different platforms based onPAGE_SIZEand alsonr_pagesintroduces the question of "was it hugetlb, or a native page size?".I meant update the number of bytes remaining when updating the offset so that userspace can redo the ioctl without having to update parameters.
Quoted 6 lines
Quoted 3 lines
Ugh, but it's defined
_IOW. I forget if that matters in practice (IIRC, it's not enforced anywhere, i.e. purely informational for userspace).I didn't notice this IOW vs IORW part, but if it starts getting enforced/specified [1] or auto-documented we'd be in trouble.
IOW vs IORW is alread specified in the ioctl. More below.
Quoted 3 lines
At this point, maybe it's better to just have a different ioctl number and struct definition. I feel that it would be easier for a user to associate/separate
Amusingly, we'd only need a different name along with the IORW thing. A full ioctl number is comproised of the "directory" (KVM), the number, the size of the payload, and how the payload is accessed.
#define _IOC(dir,type,nr,size) \ (((dir) << _IOC_DIRSHIFT) | \ ((type) << _IOC_TYPESHIFT) | \ ((nr) << _IOC_NRSHIFT) | \ ((size) << _IOC_SIZESHIFT))So this:
#define KVM_SET_MEMORY_ATTRIBUTES _IOW(KVMIO, 0xd2, struct kvm_memory_attributes) #define KVM_SET_MEMORY_ATTRIBUTES2 _IOWR(KVMIO, 0xd2, struct kvm_memory_attributes2)actually generates two different values, and so is two different ioctls from a code perspective.
The "size" of the payload is nice to have as it allows userspace to assert that it's passing the right structure, e.g. this static assert from KVM selftests:
#define
kvm_do_ioctl(fd, cmd, arg)\({ \ kvm_static_assert(!_IOC_SIZE(cmd) || sizeof(*arg) == _IOC_SIZE(cmd)); \ ioctl(fd, cmd, arg); \ })Quoted 11 lines
+
KVM_SET_MEMORY_ATTRIBUTES
+ Is VM ioctl
+ Is a write-only ioctl
+ Is for setting memory attributes at a VM level
+ Use structkvm_memory_attributesfor this
+KVM_GUEST_MEMFD_SET_MEMORY_ATTRIBUTES(name TBD)
+ Isguest_memfdioctl
+ Is a read/write ioctl
+ Is for setting memory attributes only for thisguest_memfd
+ Use structguest_memfd_memory_attributesfor this
+ Also decode errors from this struct
Quoted 7 lines
+ Has extra padding for future expansion (because why not)
If we really truly need a new ioctl, I'd probably prefer
KVM_SET_MEMORY_ATTRIBUTES2. Yeah, it's silly, but I don't think bakingGUEST_MEMFDinto the names buys us anything. Then we can useKVM_SET_MEMORY_ATTRIBUTES2on a VM if the need ever arises.
I'm for having a new ioctl number and new struct, which are you leaning towards?
As for the naming, I think it's confusing to have something similar, and Ira mentioned it being confusing in the other email too. At the same time, I accept that it's useful if the same struct were to be used for a new iteration of the KVM_SET_MEMORY_ATTRIBUTES VM ioctl in future. No strong preference either way on naming.
Trying to understand the difference between unwind on failure vs all-or-nothing:
Quoted 4 lines
Alternative #1 is to try and unwind on failure, but that gets complex, and it simply can't be done for some CoCo VMs. E.g. a private=>shared conversion for TDX is descrutive.
Unwind on failure is:
1. Store current state
2. Convert
3. Restore current state on conversion failure
Quoted 5 lines
Alternative #2 is to make the updates atomic and all-or-nothing, which is what we did for per-VM attributes. That's doable, but it'd either be much more complex than telling userspace to retry, or we'd have to lose the maple tree optimizations (which is effectively what we did for per-VM attributes).
All-or-nothing:
1. Do everything to make sure conversion doesn't fail, bail early if it fails
2. Convert (always successful)
Is that it?
Zapping private pages from the stage 2 page tables for TDX can't be recovered without help from the guest (I think that's what you're talking about too), although technically I think this zapping step could be delayed right till the end.
Maple tree allocations for conversion could fail, and allocations are a bit more complicated since we try to compact ranges with the same shared/private status into one same maple tree node. Still technically possible, maybe by updating a copy of the maple tree first, then swapping the current maple tree out atomically.
With HugeTLB, undoing HVO needs pages to be allocated, will need more digging into the details to determine if preallocation could work.
I'd still prefer having the option to return an error so that we don't paint ourselves into a corner.
Quoted 5 lines
Quoted 5 lines
[1] https://lore.kernel.org/all/[email protected]/
[...snip...]
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ira WeinyQuoted 35 lines · Ira Weiny
Quoted 2 lines · Ackerley Tng
Sean Christopherson <[email protected]> writes:
[snip]
Quoted 29 lines
Quoted 11 lines
Internally, that let's us do some fun things in KVM. E.g. if we make the "disable legacy per-VM memory attributes" a read-only module param, then we can wire up a
static_call()forkvm_get_memory_attributes()and thenkvm_mem_is_private()will Just Work.static inline unsigned long
kvm_get_memory_attributes(struct kvm *kvm, gfn_t gfn){ return static_call(__kvm_get_memory_attributes)(kvm, gfn);}
Quoted 9 lines
static inline bool
kvm_mem_is_private(struct kvm *kvm, gfn_t gfn){ return kvm_get_memory_attributes(kvm, gfn) & KVM_MEMORY_ATTRIBUTE_PRIVATE;}
That might trigger some additional surgery if/when we want to support RWX protections on a per-VM basis _and_ a per-gmem basic, but I suspect such churn would pale in comparison to the overall support needed for RWX protections.
RWX protections are more of a VM-level property, if I understood the use case correctly that some gfn ranges are to be marked non-executable by userspace. Setting RWX within
guest_memfdwould be kind of awkward since userspace must first translate GFN to offset, then set it using the offset withinguest_memfd. Hence I think it's okay to have RWX stuff go through the regularKVM_SET_MEMORY_ATTRIBUTES*VM* ioctl and have it tracked inmem_attr_array.
Quoted 8 lines
Quoted 4 lines
I'd prefer not to have the module param choose between the use of
mem_attr_arrayandguest_memfdconversion in case we need bothmem_attr_arrayto support other stuff in future while supporting conversions.I'm getting pretty confused on how userspace is going to know which ioctl to use VM vs gmem.
It is confusing, yes!
Quoted 3 lines
I was starting to question if going through the VM ioctl should actually change the
guest_memfdflags (shareability).
At one of the guest_memfd biweeklies, we came to the conclusion that we should have a per-VM KVM_CAP_DISABLE_LEGACY_PRIVATE_TRACKING, which will disable the use of just KVM_MEMORY_ATTRIBUTE_PRIVATE for the KVM_SET_MEMORY_ATTRIBUTES ioctl, and KVM_CAP_DISABLE_LEGACY_PRIVATE_TRACKING is the only way to enable conversions for a guest_memfd with mmap() support.
IOW, KVM_CAP_DISABLE_LEGACY_PRIVATE_TRACKING makes userspace choose either
+ Using guest_memfd for private memory and some other memory (e.g. anonymous memory) for shared memory (aka legacy dual backing)
+ And using KVM_SET_MEMORY_ATTRIBUTES VM ioctl for conversions
+ And using mem_attr_array to track shared/private status
+ Using guest_memfd for both private and shared memory (aka single backing)
+ And using the guest_memfd ioctl for conversions
+ And using guest_memfd shareability to track shared/private status
Since userspace has to choose one of the above, there's no point in the VM ioctl affecting shareability.
Sean's suggestion of a module param moves this choice from VM-level to KVM/host-level.
Quoted 2 lines
In a prototype I'm playing with shareability has become a bit field which I think aligns with the idea of expanding the memory attributes.
I guess this is tangentially related and could do with some profiling, but we should be careful about adding too many states in the maple tree.
Conversion iterates over offset ranges in the maple tree, and iteration is faster if there are fewer nodes in the maple tree.
If we just have two states (shared/private) in the maple tree, each node is either all private or all shared.
If we have more states, private ranges might get fragmented based on the orthogonal bits, e.g. RWX, which could then impact conversion performance.
Quoted 4 lines
But I've
had some issues with the TDX tests in trying to decipher when to callvm_set_memory_attributes()vsguest_memfd_convert_private().
Hope the above explanation helps!
+ Legacy dual backing: vm_set_memory_attributes()
+ Single backing: guest_memfd_convert_private()
I don't think this will change much even with the module param, since userspace will still need to know whether to pass in a vm fd or a guest_memfd fd.
Or maybe vm_set_memory_attributes() can take a vm fd, then query module params and then figure out if it should pass vm or guest_mefd fds?
Quoted 26 lines
Quoted 18 lines
[...snip...]
Quoted 5 lines
Quoted 5 lines
static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct
kvm_memory_slot*slot,(quoted diff) +0
-0pgoff_t index, struct folio *folio) {@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)Quoted 9 lines
Review static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf) · line 407
Quoted 4 lines
(quoted diff) +1
-1filemap_invalidate_lock_shared(inode->i_mapping); - folio = kvm_gmem_get_folio(inode, vmf->pgoff); + folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);I am fairly certain there's a TOCTOU bug here. AFAICT, nothing prevents the underlying memory from being converted from shared=>private after checking that the page is SHARED.
Quoted 7 lines
Conversions take the
filemap_invalidate_lock()too, along with allocations, truncations.Because the
filemap_invalidate_lock()might be reused for other fs-specific operations, I didn't do themt_set_external_lock()thing to lock at a low level to avoid nested locking or special maple tree code to avoid taking the lock on other paths.
Quoted 4 lines
I don't think using the
filemap_invalidate_lock()is going to work well here. I've had some hangs on it in my testing and experiments. I think it is better to specifically lock the state tracking itself. I believe Michael mentioned this as well in a previous thread.
Definitely took the big hammer lock for a start and might be optimizable.
Considerations so far: when a conversion is happening, these have to be locked out:
+ Conversions from competing threads
+ Allocations in kvm_gmem_fault_user_mapping(), because whether an offset can be faulted depends on the outcome of conversion
+ Allocations (fallocate() or kvm_gmem_get_pfn()) and truncations, because conversions (for now) involves removing a folio from the filemap, restructuring, then restoring to the filemap, and
+ Allocations should reuse a folio that was already in the filemap
+ Truncations remove a folio, and should not skip removal of a folio because it was taken out just for conversion
+ memory failure handling, where we don't remove folios from the filemap, but we might restructure, to split huge folios to just unmap pages with failed memory
I think essentially because conversion involves restructuring, and restructuring involves filemap operations and other filemap operations have to wait, conversion also takes the filemap_invalidate_lock() that filemap operations use.
Quoted 4 lines
Ira
[snip]
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
Quoted 8 lines · Ackerley Tng
Quoted 6 lines · Ira Weiny
Quoted 2 lines · Ackerley Tng
Sean Christopherson <[email protected]> writes:
[snip]
[snip]
Quoted 35 lines
Quoted 9 lines
Quoted 5 lines
I'd prefer not to have the module param choose between the use of
mem_attr_arrayandguest_memfdconversion in case we need bothmem_attr_arrayto support other stuff in future while supporting conversions.I'm getting pretty confused on how userspace is going to know which ioctl to use VM vs gmem.
It is confusing, yes!
Quoted 3 lines
I was starting to question if going through the VM ioctl should actually change the
guest_memfdflags (shareability).At one of the
guest_memfdbiweeklies, we came to the conclusion that we should have a per-VMKVM_CAP_DISABLE_LEGACY_PRIVATE_TRACKING, which will disable the use of justKVM_MEMORY_ATTRIBUTE_PRIVATEfor theKVM_SET_MEMORY_ATTRIBUTESioctl, andKVM_CAP_DISABLE_LEGACY_PRIVATE_TRACKINGis the only way to enable conversions for aguest_memfdwithmmap()support.IOW,
KVM_CAP_DISABLE_LEGACY_PRIVATE_TRACKINGmakes userspace choose either+ Using
guest_memfdfor private memory and some other memory (e.g. anonymous memory) for shared memory (aka legacy dual backing)
+ And usingKVM_SET_MEMORY_ATTRIBUTESVM ioctl for conversions
+ And usingmem_attr_arrayto track shared/private status+ Using
guest_memfdfor both private and shared memory (aka single backing)
+ And using theguest_memfdioctl for conversions
+ And usingguest_memfdshareability to track shared/private status
Quoted 5 lines
Since userspace has to choose one of the above, there's no point in the VM ioctl affecting shareability.
Sean's suggestion of a module param moves this choice from VM-level to KVM/host-level.
Ok I remember this discussion but I was not clear on the mechanics. This helps clarify things thanks!
Quoted 10 lines
Quoted 3 lines
In a prototype I'm playing with shareability has become a bit field which I think aligns with the idea of expanding the memory attributes.
I guess this is tangentially related and could do with some profiling, but we should be careful about adding too many states in the maple tree.
Conversion iterates over offset ranges in the maple tree, and iteration is faster if there are fewer nodes in the maple tree.
Quoted 6 lines
If we just have two states (shared/private) in the maple tree, each node is either all private or all shared.
If we have more states, private ranges might get fragmented based on the orthogonal bits, e.g. RWX, which could then impact conversion performance.
I'm thinking along these same lines yea.
Quoted 11 lines
Quoted 5 lines
But I've
had some issues with the TDX tests in trying to decipher when to callvm_set_memory_attributes()vsguest_memfd_convert_private().Hope the above explanation helps!
+ Legacy dual backing:
vm_set_memory_attributes()
+ Single backing:guest_memfd_convert_private()
Quoted 6 lines
I don't think this will change much even with the module param, since userspace will still need to know whether to pass in a vm fd or a
guest_memfdfd.Or maybe
vm_set_memory_attributes()can take a vm fd, then query module params and then figure out if it should pass vm orguest_mefdfds?
For the tests that might help for sure.
Generally I'm hesitant to introduce module parameters as they are pretty big hammers to change behavior. But if it makes things easier and is acceptable then I'm not going to complain...
Quoted 32 lines
Quoted 27 lines
Quoted 19 lines
[...snip...]
Quoted 5 lines
Quoted 5 lines
static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct
kvm_memory_slot*slot,(quoted diff) +0
-0pgoff_t index, struct folio *folio) {@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)Quoted 9 lines
Review static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf) · line 407
Quoted 4 lines
(quoted diff) +1
-1filemap_invalidate_lock_shared(inode->i_mapping); - folio = kvm_gmem_get_folio(inode, vmf->pgoff); + folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);I am fairly certain there's a TOCTOU bug here. AFAICT, nothing prevents the underlying memory from being converted from shared=>private after checking that the page is SHARED.
Quoted 7 lines
Conversions take the
filemap_invalidate_lock()too, along with allocations, truncations.Because the
filemap_invalidate_lock()might be reused for other fs-specific operations, I didn't do themt_set_external_lock()thing to lock at a low level to avoid nested locking or special maple tree code to avoid taking the lock on other paths.Quoted 4 lines
I don't think using the
filemap_invalidate_lock()is going to work well here. I've had some hangs on it in my testing and experiments. I think it is better to specifically lock the state tracking itself. I believe Michael mentioned this as well in a previous thread.
Quoted 6 lines
Definitely took the big hammer lock for a start and might be optimizable.
Considerations so far: when a conversion is happening, these have to be locked out:
+ Conversions from competing threads
Agreed. And this needs filemap_invalidate_lock() as well as the maple tree lock.
Call this item 1.
Quoted 2 lines
+ Allocations in
kvm_gmem_fault_user_mapping(), because whether an offset can be faulted depends on the outcome of conversion
Agreed. And this needs filemap_invalidate_lock() as well as the maple tree lock.
Call this item 2.
Quoted 6 lines
+ Allocations (
fallocate()orkvm_gmem_get_pfn()) and truncations, because conversions (for now) involves removing a folio from the filemap, restructuring, then restoring to the filemap, and
+ Allocations should reuse a folio that was already in the filemap
+ Truncations remove a folio, and should not skip removal of a folio because it was taken out just for conversion
I don't think this is required...
Quoted 3 lines
+ memory failure handling, where we don't remove folios from the filemap, but we might restructure, to split huge folios to just unmap pages with failed memory
... nor this. These don't change the sharability maple tree.
These operations don't change or need to know the shareability AFAICT.
Merging a folio would have to check the maple tree to ensure we don't merge incompatible folios... But that is a read check and should be easy to add.
Quoted 4 lines
I think essentially because conversion involves restructuring, and restructuring involves filemap operations and other filemap operations have to wait, conversion also takes the
filemap_invalidate_lock()that filemap operations use.
I could be convinced otherwise but I'm thinking the overhead of another lock for the sake of simplicity is a good trade off. I don't think any of the conversions are a fast path operation are they?
Ira
[snip]
Re: [RFC PATCH v2 11/51] KVM: selftests: Allow cleanup of ucall_pool from host
In reply to Ackerley TngQuoted 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.
Sean Christopherson
maintainerRe: [RFC PATCH v2 12/51] KVM: selftests: Test conversion flows for guest_memfd
In reply to Ackerley TngQuoted 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 --
Sean Christopherson
maintainerRe: [RFC PATCH v2 10/51] KVM: selftests: Refactor vm_mem_add to be more flexible
In reply to Ackerley TngQuoted 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 --
Sean Christopherson
maintainerRe: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ackerley TngQuoted 33 lines · Ackerley Tng
Quoted 21 lines · Sean Christopherson
Quoted 20 lines · Ackerley Tng
Quoted 10 lines · Sean Christopherson
Quoted 4 lines
I'd prefer not to have the module param choose between the use of
mem_attr_arrayandguest_memfdconversion in case we need bothmem_attr_arrayto support other stuff in future while supporting conversions.Luckily, we don't actually need to make a decision on this, because PRIVATE is the only attribute that exists. Which is partly why I want to go with a module param. We can make the behavior very definitive without significant risk of causing ABI hell.
Then maybe I'm misunderstanding the
static_call()thing you were describing. Is it like, at KVM module initialization time,if
module_param==disable_tracking:
.__kvm_get_memory_attributes =read_attributes_from_guest_memfd
else
.__kvm_get_memory_attributes =read_attributes_from_mem_attr_arrayQuoted 6 lines
Quoted 3 lines
With that, I can't have both CoCo private/shared state tracked in
guest_memfdand RWX (as an example, could be any future attribute) tracked inmem_attr_arrayon the same VM.More or less.
Hm okay. So introducing the module param will only allow the use of one of the following?
Quoted 6 lines
+
KVM_SET_MEMORY_ATTRIBUTES(vm ioctl)
+KVM_SET_MEMORY_ATTRIBUTES2(guest_memfdioctl)Then I guess using a module param which is a weaker userspace contract allows us to later enable both vm and
guest_memfdioctl if the need arises?
In theory. More importantly from my perspective, making the knob global instead of per-VM simplifies the implementation.
Quoted 20 lines
Quoted 12 lines
Quoted 11 lines
+
KVM_SET_MEMORY_ATTRIBUTES
+ Is VM ioctl
+ Is a write-only ioctl
+ Is for setting memory attributes at a VM level
+ Use structkvm_memory_attributesfor this
+KVM_GUEST_MEMFD_SET_MEMORY_ATTRIBUTES(name TBD)
+ Isguest_memfdioctl
+ Is a read/write ioctl
+ Is for setting memory attributes only for thisguest_memfd
+ Use structguest_memfd_memory_attributesfor this
+ Also decode errors from this structQuoted 7 lines
+ Has extra padding for future expansion (because why not)
If we really truly need a new ioctl, I'd probably prefer
KVM_SET_MEMORY_ATTRIBUTES2. Yeah, it's silly, but I don't think bakingGUEST_MEMFDinto the names buys us anything. Then we can useKVM_SET_MEMORY_ATTRIBUTES2on a VM if the need ever arises.
Quoted 5 lines
I'm for having a new ioctl number and new struct, which are you leaning towards?
As for the naming, I think it's confusing to have something similar, and Ira mentioned it being confusing in the other email too.
It might sound confusing, but I don't think the _code_ will be confusing. If it's a module param, it's guaranteed to be global for any VMM. Then the conversion code can be a simple redirect, e.g. I would expect/hope the QEMU change to be something like:
accel/kvm/kvm-all.c +4 -0
@@ -1421,6 +1421,10 @@ static int kvm_set_memory_attributes(hwaddr start, uint64_t size, uint64_t attr)int r;assert ((attr & kvm_supported_memory_attributes) == attr); + +if (kvm_use_gmem_attributes) +return kvm_get_gmem_fd (start, size, attr); + attrs.attributes = attr; attrs.address = start; attrs.size = size;
Quoted 12 lines
At the same time, I accept that it's useful if the same struct were to be used for a new iteration of the
KVM_SET_MEMORY_ATTRIBUTESVM ioctl in future. No strong preference either way on naming.Trying to understand the difference between unwind on failure vs all-or-nothing:
Quoted 4 lines
Alternative #1 is to try and unwind on failure, but that gets complex, and it simply can't be done for some CoCo VMs. E.g. a private=>shared conversion for TDX is descrutive.
Quoted 5 lines
Unwind on failure is:
1. Store current state
2. Convert
3. Restore current state on conversion failure
Not quite, the above is missing key steps that cause problems: invalidation and memory allocation.
1. Zap stage-1 mappings
2. Check if range can be converted
3. Zap stage-2 mappings
4. Store state for target range
For TDX, #3 is the point of no return. That means #4 must not fail, because at the very least invididual page conversions need to be atomic.
Quoted 6 lines
Quoted 5 lines
Alternative #2 is to make the updates atomic and all-or-nothing, which is what we did for per-VM attributes. That's doable, but it'd either be much more complex than telling userspace to retry, or we'd have to lose the maple tree optimizations (which is effectively what we did for per-VM attributes).
Quoted 7 lines
All-or-nothing:
1. Do everything to make sure conversion doesn't fail, bail early if it fails
2. Convert (always successful)Is that it?
No, because #1 is non-trivial. The wrinkle is that, without doing an initial pass through mtree, it's impossible to know how many new entries will be needed (which you already know). It's a solvable problem, e.g. in this RFC, it's kinda sorta handled by allocating temporary structures to track the mtree metadata, but that's the type of complexity I want to avoid.
Quoted 3 lines
Zapping private pages from the stage 2 page tables for TDX can't be recovered without help from the guest (I think that's what you're talking about too),
Ya.
Quoted 1 line
although technically I think this zapping step could be delayed right till the end.
Hmm. If we fully committed to blocking all "gets" via the filemap lock, then
yes, I think it could be delayed until the end? Tempting. But as you note
below, I'd prefer to give ourselves an out from an ABI perspective.
Quoted 1 line
Maple tree allocations for conversion could fail,
Ya, in my local version I handle that by pre-allocating.
mas_for_each(&mas, entry, end - 1) {
MA_STATE(m2, &gi->attributes, 0, 0);
if (attrs->attributes == xa_to_value(entry))
continue;
r = kvm_gmem_mas_preallocate(&m2, attrs->attributes, start, end);
if (r) {
*err_index = m2.index;
goto out;
}
unmap_mapping_pages(mapping, start, nr_pages, false);
if (!kvm_gmem_is_safe_for_conversion(inode, start, nr_pages, err_index)) {
mas_destroy(&m2);
r = -EAGAIN;
goto out;
}
kvm_gmem_invalidate_begin(inode, start, end);
mas_store_prealloc(&m2, xa_mk_value(attrs->attributes));
kvm_gmem_invalidate_end(inode, start, end);
}Quoted 4 lines
and allocations are a bit more complicated since we try to compact ranges with the same shared/private status into one same maple tree node. Still technically possible, maybe by updating a copy of the maple tree first, then swapping the current maple tree out atomically.
Heh, more complexity I'd prefer to avoid.
Quoted 2 lines
With HugeTLB, undoing HVO needs pages to be allocated, will need more digging into the details to determine if preallocation could work.
It has to work, otherwise we're hosed. Though it should be noted that "preallocate" here just means before kvm_gmem_invalidate_begin(). Everything up to that point can fail.
The other option in all of this is to add an API to _block_ stage-2 mappings, in TDX terminology. In TDX, BLOCK marks leaf S-EPT entries !PRESENT, but preserves all the metadata. So if we're too scared to do an after-the-fact invalidation, and we need to support failure after kvm_gmem_invalidate_begin(), we could rework the TDX backend to support e.g. kvm_gmem_invalidate_abort(). On begin(), KVM would BLOCK mappings; on abort(), restore; on end() fully remove.
Quoted 2 lines
I'd still prefer having the option to return an error so that we don't paint ourselves into a corner.
Yep, my thoughts exactly.
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 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; +}
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).
Sean Christopherson
maintainerRe: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
In reply to Sean ChristophersonQuoted 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.
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.
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ackerley TngQuoted 36 lines · Ackerley Tng
[...snip...]
Quoted 33 lines
Quoted 32 lines
Quoted 26 lines
Quoted 10 lines
Quoted 10 lines
The
kvm_memory_attributesstructure is compatible, all that's needed AFAICT is a union to clarify it's a pgoff instead of an address when used forguest_memfd.include/uapi/linux/kvm.h +0
-0@@ -1590,7 +1590,10 @@ struct kvm_stats_desc {#define KVM_SET_MEMORY_ATTRIBUTES _IOW(KVMIO, 0xd2, struct kvm_memory_attributes)Quoted 15 lines
include/uapi/linux/kvm.h struct kvm_stats_desc { · line 1599
Quoted 10 lines
include/uapi/linux/kvm.h +4
-1struct kvm_memory_attributes { -__u64 address; +union { +__u64 address; +__u64 offset; + };__u64 size;__u64 attributes;__u64 flags;struct
kvm_memory_attributesdoesn't have room for reporting the offset at which conversion failed (error_offsetin the new struct). How do we handle this? Do we reuse the flags field, or do we not reporterror_offset?Quoted 1 line
Write back at address/offset
I think it might be surprising to the userspace program, when it wants to check the offset that it had requested and found that it changed due to an error, or upon decoding the error, be unable to find the original offset it had requested.
Quoted 28 lines
Quoted 4 lines
It's a somewhat common pattern in the kernel. Updating the offset+size is most often used with
-EAGAINto say "got this far, try the syscall again from this point".TIL, thanks!
Quoted 21 lines
Quoted 11 lines
Like,
printf("Error during conversion from offset=%lx with size=%lx, at
error_offset=%lx", attr.offset, attr.size, attr.error_offset)would be nicer than
original_offset= attr.offset
printf("Error during conversion from offset=%lx with size=%lx, at
error_offset=%lx",original_offset, attr.size, attr.error_offset)Quoted 6 lines
Quoted 1 line
(and update size too, which I probably forgot to do).
Why does size need to be updated? I think u64 for size is great, and size is better than
nr_pagessincenr_pagesdiffers on different platforms based onPAGE_SIZEand alsonr_pagesintroduces the question of "was it hugetlb, or a native page size?".I meant update the number of bytes remaining when updating the offset so that userspace can redo the ioctl without having to update parameters.
Was working through this again, I think the attr.offset returned from the conversion ioctl is not the same as other syscalls where an updated offset+size indicates "got this far, try the syscall again from this point".
For the conversion ioctl, -EAGAIN indicates that a some unexpected refcount was first found at offset error_offset, but does not imply that everything up till error_offset had been converted.
This arises when we start to have hugepage support. To restructure hugepage-by-hugepage, we will iterate hugepage-wise and check for elevated refcounts.
Suppose we're converting 10 1G pages and on the 3rd hugepage, the 5th offset has an elevated refcount.
error_offset should be set to the 5th offset in the 3rd hugepage, but userspace should retry beginning at the offset of the 3rd hugepage with size 8G.
If the offset returned to userspace is the 3rd hugepage, then we lose precision. The refcount at the 3rd hugepage could be fine and expected - it is the page at the 5th offset in the 3rd hugepage that is pinned and userspace should be unpin.
So perhaps the interface needs to be defined as
If the error is -EAGAIN:
+ offset: the offset to retry from
+ size: the remaining size to retry
+ error_offset: the offset where an unexpected refcount was found
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
[...snip...]
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ira WeinyQuoted 58 lines · Ira Weiny
[...snip...]
Quoted 14 lines
Quoted 9 lines
Quoted 8 lines
Conversions take the
filemap_invalidate_lock()too, along with allocations, truncations.Because the
filemap_invalidate_lock()might be reused for other fs-specific operations, I didn't do themt_set_external_lock()thing to lock at a low level to avoid nested locking or special maple tree code to avoid taking the lock on other paths.Quoted 4 lines
I don't think using the
filemap_invalidate_lock()is going to work well here. I've had some hangs on it in my testing and experiments. I think it is better to specifically lock the state tracking itself. I believe Michael mentioned this as well in a previous thread.Quoted 6 lines
Definitely took the big hammer lock for a start and might be optimizable.
Considerations so far: when a conversion is happening, these have to be locked out:
+ Conversions from competing threads
Agreed. And this needs
filemap_invalidate_lock()as well as the maple tree lock.Call this item 1.
Quoted 2 lines
+ Allocations in
kvm_gmem_fault_user_mapping(), because whether an offset can be faulted depends on the outcome of conversionAgreed. And this needs
filemap_invalidate_lock()as well as the maple tree lock.Call this item 2.
Quoted 6 lines
+ Allocations (
fallocate()orkvm_gmem_get_pfn()) and truncations, because conversions (for now) involves removing a folio from the filemap, restructuring, then restoring to the filemap, and
+ Allocations should reuse a folio that was already in the filemap
+ Truncations remove a folio, and should not skip removal of a folio because it was taken out just for conversionI don't think this is required...
Quoted 3 lines
+ memory failure handling, where we don't remove folios from the filemap, but we might restructure, to split huge folios to just unmap pages with failed memory
... nor this. These don't change the sharability maple tree.
These operations don't change or need to know the shareability AFAICT.
Merging a folio would have to check the maple tree to ensure we don't merge incompatible folios... But that is a read check and should be easy to add.
Quoted 8 lines
Quoted 4 lines
I think essentially because conversion involves restructuring, and restructuring involves filemap operations and other filemap operations have to wait, conversion also takes the
filemap_invalidate_lock()that filemap operations use.I could be convinced otherwise but I'm thinking the overhead of another lock for the sake of simplicity is a good trade off. I don't think any of the conversions are a fast path operation are they?
Haha, I think not having another lock is simpler! Looks like it's starting to get subjective.
For the next RFC, I'll go with re-using the filemap_invalidate_lock(), and the next RFC will have quite some changes too. Please feel free to bring this up again. The next RFC is an RFC and won't be committal anyway :)
Quoted 4 lines
Ira
[snip]
Ackerley Tng <[email protected]> writes:
Re-using this thread to collect discussions related to guest_memfd HugeTLB support, also trimmed cc list.
Here's the latest public version Vishal and I have:
On the guest_memfd call on 2026-01-22, Michael found another bug to do with multiple threads trying to allocate within the same huge page at the same time.
The fix we're using to make progress is to use hugetlb_fault_mutex_lock.
unsigned int gmem_hugetlb_mapping_index_lock(struct address_space *mapping,
pgoff_t index, u8 page_order)
{
pgoff_t index_floor = round_down(index, 1ULL << page_order);
return hugetlb_fault_mutex_lock(mapping, index_floor);
}void gmem_hugetlb_mapping_index_unlock(unsigned int hash)
{
hugetlb_fault_mutex_unlock(hash);
}and then
static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
{
... declarations ...
if (gmem_is_hugetlb(gi->flags))
lock_id = gmem_hugetlb_mapping_index_lock(mapping, index, gi->page_order);
... and this right at the end ...
if (gmem_is_hugetlb(gi->flags))
gmem_hugetlb_mapping_index_unlock(lock_id);
}Yan also found some bugs (thanks!) and there's a discussion at [*].
[*] https://lore.kernel.org/all/CAEvNRgGG+xYhsz62foOrTeAxUCYxpCKCJnNgTAMYMV=w2eq+6Q@mail.gmail.com/