KVM: TDX huge page support for private memory
Subsystems (16)
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
In reply to Yan ZhaoQuoted 62 lines · Yan Zhao
Quoted 26 lines · Vishal Annapurve
Quoted 8 lines · Yan Zhao
Quoted 5 lines · Rick P
So for this we can do something similar. Have the
arch/x86side of TDX grow a newtdx_buggy_shutdown(). Have it do an all-cpu IPI to kick CPUs out of SEAMMODE, wbivnd, and set a "no more seamcalls" bool. Then any SEAMCALLs after that will return aTDX_BUGGY_SHUTDOWNerror, or similar. All TDs in the system die. Zap/cleanup paths return success in the buggy shutdown case.All TDs in the system die could be too severe for unmap errors due to KVM bugs.
At this point, I don't see a way to quantify how bad a KVM bug can get unless you have explicit ideas about the severity. We should work on minimizing KVM side bugs too and assuming it would be a rare occurrence I think it's ok to take this intrusive measure.
Quoted 10 lines
Quoted 5 lines
Does it fit? Or, can you guys argue that the failures here are actually non- special cases that are worth more complex recovery? I remember we talked about IOMMU patterns that are similar, but it seems like the remaining cases under discussion are about TDX bugs.
I didn't mention TDX connect previously to avoid introducing unnecessary complexity.
For TDX connect, S-EPT is used for private mappings in IOMMU. Unmap could therefore fail due to pages being pinned for DMA.
Quoted 8 lines
We are discussing this scenario already[1], where the host will not pin the pages used by secure DMA for the same reasons why we can't have KVM pin the
guest_memfdpages mapped in SEPT. Is there some other kind of pinning you are referring to?If there is an ordering in which pages should be unmapped e.g. first in secure IOMMU and then KVM SEPT, then we can ensure the right ordering between invalidation callbacks from
guest_memfd.It's pinning from a different perspective.
Please check
https://lore.kernel.org/all/[email protected].Quoted 15 lines
[1] https://lore.kernel.org/lkml/CAGtprH_qh8sEY3s-JucW3n1Wvoq7jdVZDDokvG5HzPf0HV2=pg@mail.gmail.com/#t
Quoted 4 lines
So, my thinking was that if that happens, KVM could set a special flag to folios pinned for private DMA.
Quoted 8 lines
Then
guest_memfdcould check the special flag before allowing private-to-shared conversion, or punch hole.guest_memfdcould check this special flag and choose to poison or leak the folio.Otherwise, if we choose
tdx_buggy_shutdown()to "do an all-cpu IPI to kick CPUs out of SEAMMODE, wbivnd, and set a "no more seamcalls" bool", DMAs may still have access to the private pages mapped in S-EPT.Quoted 7 lines
guest_memfdwill have to ensure that pages are unmapped from secure IOMMU pagetables before allowing them to be used by the host.If secure IOMMU pagetables unmapping fails, I would assume it fails in the similar category of rare "KVM/TDX module/IOMMUFD" bug and I think it makes sense to do the same
tdx_buggy_shutdown()with such failures as well.
Quoted 5 lines
tdx_buggy_shutdown()should then
do an all-cpu IPI to kick CPU out of SEAMMODE, wbivnd, and set a "no more seamcalls" bool" and informing IOMMUF/VFIO to stop devices.BTW, is the "no more seamcall" set by KVM at the per-VM level?
No more seamcall here would be the host level.
Quoted 4 lines
If it's per-VM, other TDs could still entering SEAMMODE. So, potential corruption is still possible.
Besides, with "no more seamcalls" upon unmapping failure of a GFN, how to reclaim other pages which might succeed otherwise?
I would think that with no more seamcall on the host, KVM TDX logic could safely reclaim all the pages using the WBINVD method.
Quoted 2 lines
This approach seems very complex.
With "informing IOMMUF/VFIO to stop devices" specially only for secure devices, I agree this could become hard to orchestrate unless Dan Williams or somebody else has better insights here.
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
In reply to Ackerley TngQuoted 79 lines · Ackerley Tng
Quoted 42 lines · Rick P
Quoted 34 lines · Ackerley Tng
Let me try and summarize the current state of this discussion:
Topic 1: Does TDX need to somehow indicate that it is using a page?
This patch series uses refcounts to indicate that TDX is using a page, but that complicates private-to-shared conversions.
During a private-to-shared conversion,
guest_memfdassumes thatguest_memfdis trusted to manage private memory. TDX and other users should trustguest_memfdto keep the memory around.Yan's position is that holding a refcount is in line with how IOMMU takes a refcount when a page is mapped into the IOMMU [1].
Yan had another suggestion, which is to indicate using a page flag [2].
I think we're in agreement that we don't want to have TDX hold a refcount while the page is mapped into the Secure EPTs, but taking a step back, do we really need to indicate (at all) that TDX is using a page?
In [3] Yan said
Quoted 5 lines
If TDX does not hold any refcount,
guest_memfdhas to know that which private
page is still mapped. Otherwise, the page may be re-assigned to other kernel
components while it may still be mapped in the S-EPT.If the private page is mapped for regular VM use as private memory,
guest_memfdis managing that, and the same page will not be re-assigned to any other kernel component.guest_memfddoes hold refcounts in guest_memfd's filemap.Quoted 6 lines
If the private page is still mapped because there was an unmapping failure, we can discuss that separately under error handling in Topic 2.
With this, can I confirm that we are in agreement that TDX does not need to indicate that it is using a page, and can trust
guest_memfdto keep the page around for the VM?Quoted 10 lines
Minor correction here. Yan was concerned about *bugs* happening when freeing pages that are accidentally still mapped in the S-EPT. My opinion is that this is not especially risky to happen here vs other similar places, but it could be helpful if there was a way to catch such bugs. The page flag, or
page_extdirection came out of a discussion with Dave and Kirill. If it could run all the time that would be great, but if not a debug config could be sufficient. For example likeCONFIG_PAGE_TABLE_CHECK. It doesn't need to support vmemmap optimizations because the debug checking doesn't need to run all the time. Overhead for debug settings is very normal.I see, let's call debug checking Topic 3 then, to separate it from Topic 1, which is TDX indicating that it is using a page for production kernels.
Topic 3: How should TDX indicate use of a page for debugging?
I'm okay if for debugging, TDX uses anything other than refcounts for checking, because refcounts will interfere with conversions.
Rick's other email is correct. The correct link should be
https://lore.kernel.org/all/[email protected]/.[INTERFERE WITH CONVERSIONS]
To summarize, if TDX uses refcounts to indicate that it is using a page, or to indicate anything else, then we cannot easily split a page on private to shared conversions.
Specifically, consider the case where only the x-th subpage of a huge folio is mapped into Secure-EPTs. When the guest requests to convert some subpage to shared, the huge folio has to be split for core-mm. Core-mm, which will use the shared page, must have split folios to be able to accurately and separately track refcounts for subpages.
Quoted 5 lines
During splitting,
guest_memfdwould see refcount of 512 (for 2M page being in the filemap) + 1 (if TDX indicates that the x-th subpage is mapped using a refcount), but would not be able to tell that the 513th refcount belongs to the x-th subpage.guest_memfdcan't split the huge folio unless it knows how to distribute the 513th refcount.
In my POC, https://lore.kernel.org/all/aE%[email protected]/kvm_gmem_private_has_safe_refcount() was introduce to check the folio ref count. It rejects private-to-shared conversion after splitting and unmapping KVM's secondary page tables if the refcount exceeds a valid threshold.
Though in
https://lore.kernel.org/all/[email protected]/, we agreed that "EAGAIN is not the right code in case of "extra" refcounts held by TDX", this does not imply that rejecting the conversion itself is incorrect.
This is why we are exploring alternative solutions instead of having TDX hold the page refcount.
So, either a per-page flag, per-folio flag or solutions e,f,g should be good.
IMO, regardless of the final choice, guest_memfd needs to identify problematic folios to:
- reject the private-to-shared conversion
- prevent further recycling after kvm_gmem_free_folio()
Quoted 6 lines
One might say
guest_memfdcould clear all the refcounts that TDX is holding on the huge folio by unmapping the entire huge folio from the Secure-EPTs, but unmapping the entire huge folio for TDX means zeroing the contents and requiring guest re-acceptance. Both of these would mess up guest operation.
Quoted 7 lines
Hence, guest_memfd's solution is to require that users of
guest_memfdfor private memory trustguest_memfdto maintain the pages around and not take any refcounts.So back to Topic 1, for production kernels, is it okay that TDX does not need to indicate that it is using a page, and can trust
guest_memfdto keep the page around for the VM?
If the "TDX does not need to indicate that it is using a page" means "do not take page refcount", I'm ok.
Quoted 96 lines
Quoted 81 lines
Quoted 7 lines
Topic 2: How to handle unmapping/splitting errors arising from TDX?
Previously I was in favor of having
unmap()return an error (Rick suggested doing a POC, and in a more recent email Rick asked for a diffstat), but Vishal and I talked about this and now I agree having unmapping return an error is not a good approach for these reasons.Ok, let's close this option then.
Quoted 19 lines
1. Unmapping takes a range, and within the range there could be more than one unmapping error. I was previously thinking that
unmap()could return 0 for success and the failed PFN on error. Returning a single PFN on error is okay-ish but if there are more errors it could get complicated.Another error return option could be to return the folio where the unmapping/splitting issue happened, but that would not be sufficiently precise, since a folio could be larger than 4K and we want to track errors as precisely as we can to reduce memory loss due to errors.
2. What I think Yan has been trying to say:
unmap()returning an error is non-standard in the kernel.I think (1) is the dealbreaker here and there's no need to do the plumbing POC and diffstat.
Quoted 8 lines
So I think we're all in support of indicating unmapping/splitting issues without returning anything from
unmap(), and the discussed options area. Refcounts: won't work - mostly discussed in this (sub-)thread [3]. Using refcounts makes it impossible to distinguish between transient refcounts and refcounts due to errors.
b. Page flags: won't work with/can't benefit from HVO.
As above, this was for the purpose of catching bugs, not for guestmemfd to logically depend on it.
Quoted 6 lines
Suggestions still in the running:
c. Folio flags are not precise enough to indicate which page actually had an error, but this could be sufficient if we're willing to just waste the rest of the huge page on unmapping error.
For a scenario of TDX module bug, it seems ok to me.
Quoted 18 lines
d. Folio flags with folio splitting on error. This means that on unmapping/Secure EPT PTE splitting error, we have to split the (larger than 4K) folio to 4K, and then set a flag on the split folio.
The issue I see with this is that splitting pages with HVO applied means doing allocations, and in an error scenario there may not be memory left to split the pages.
e. Some other data structure in
guest_memfd, say, a linked list, and a function likekvm_gmem_add_error_pfn(struct page *page)that would look up theguest_memfdinode from the page and add the page's pfn to the linked list.Everywhere in
guest_memfdthat does unmapping/splitting would then check this linked list to see if the unmapping/splitting succeeded.Quoted 5 lines
Everywhere in
guest_memfdthat allocates pages will also check this linked list to make sure the pages are functional.When
guest_memfdtruncates, if the page being truncated is on the list, retain the refcount on the page and leak that page.I think this is a fine option.
Quoted 5 lines
f. Combination of c and e, something similar to HugeTLB's
folio_set_hugetlb_hwpoison(), which sets a flag AND adds the pages in trouble to a linked list on the folio.Quoted 8 lines
Quoted 5 lines
g. Like f, but basically treat an unmapping error as hardware poisoning.
I'm kind of inclined towards g, to just treat unmapping errors as HWPOISON and buying into all the HWPOISON handling requirements. What do yall think? Can a TDX unmapping error be considered as memory poisoning?
What does HWPOISON bring over refcounting the page/folio so that it never returns to the page allocator?
For Topic 2 (handling TDX unmapping errors), HWPOISON is better than refcounting because refcounting interferes with conversions (see [INTERFERE WITH CONVERSIONS] above).
Quoted 1 line
We are bugging the TD in these cases.
Quoted 7 lines
Bugging the TD does not help to prevent future conversions from being interfered with.
1. Conversions involves unmapping, so we could actually be in a conversion, the unmapping is performed and fails, and then we try to split and enter an infinite loop since private to shared conversions assumes
guest_memfdholds the only refcounts onguest_memfdmemory.
We should bail out conversion even with the HWPOISON.
e.g.,
1. user triggers private-to-shared ioctl to convert 4K page A within a 2MB folio B to shared.
2. kvm_gmem_convert_should_proceed() executes kvm_gmem_split_private() and kvm_gmem_zap().
3. kvm_gmem_convert_should_proceed() checks kvm_gmem_has_invalid_folio() (Suppose TDX sets HWPOISON to page A or folio B after kvm_gmem_zap(), then kvm_gmem_has_invalid_folio() should return true).
4. Return -EFAULT.
If we allow the actual conversion to proceed after step 3, folio B will be split into 4KB folios, with page A being converted to a shared 4KB folio, which becomes accessible by userspace.
This could cause a machine check (#MC) on certain platforms. We should avoid this scenario when possible.
Quoted 14 lines
2. The conversion ioctl is a
guest_memfdioctl, not a VM ioctl, and so there is no check that the VM is not dead. There shouldn't be any check on the VM, because shareability is a property of the memory and should be changeable independent of the associated VM.Quoted 2 lines
Ohhh... Is
this about the code to allow gmem fds to be handed to new VMs?Nope, it's not related to linking. The proposed
KVM_LINK_GUEST_MEMFDioctl [4] also doesn't check if the source VM is dead. There shouldn't be any check on the source VM, since the memory is fromguest_memfdand should be independently transferable to a new VM.
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 98 lines · Yan Zhao
Quoted 79 lines · Ackerley Tng
Quoted 42 lines · Rick P
Quoted 34 lines · Ackerley Tng
Let me try and summarize the current state of this discussion:
Topic 1: Does TDX need to somehow indicate that it is using a page?
This patch series uses refcounts to indicate that TDX is using a page, but that complicates private-to-shared conversions.
During a private-to-shared conversion,
guest_memfdassumes thatguest_memfdis trusted to manage private memory. TDX and other users should trustguest_memfdto keep the memory around.Yan's position is that holding a refcount is in line with how IOMMU takes a refcount when a page is mapped into the IOMMU [1].
Yan had another suggestion, which is to indicate using a page flag [2].
I think we're in agreement that we don't want to have TDX hold a refcount while the page is mapped into the Secure EPTs, but taking a step back, do we really need to indicate (at all) that TDX is using a page?
In [3] Yan said
Quoted 5 lines
If TDX does not hold any refcount,
guest_memfdhas to know that which private
page is still mapped. Otherwise, the page may be re-assigned to other kernel
components while it may still be mapped in the S-EPT.If the private page is mapped for regular VM use as private memory,
guest_memfdis managing that, and the same page will not be re-assigned to any other kernel component.guest_memfddoes hold refcounts in guest_memfd's filemap.Quoted 6 lines
If the private page is still mapped because there was an unmapping failure, we can discuss that separately under error handling in Topic 2.
With this, can I confirm that we are in agreement that TDX does not need to indicate that it is using a page, and can trust
guest_memfdto keep the page around for the VM?Quoted 10 lines
Minor correction here. Yan was concerned about *bugs* happening when freeing pages that are accidentally still mapped in the S-EPT. My opinion is that this is not especially risky to happen here vs other similar places, but it could be helpful if there was a way to catch such bugs. The page flag, or
page_extdirection came out of a discussion with Dave and Kirill. If it could run all the time that would be great, but if not a debug config could be sufficient. For example likeCONFIG_PAGE_TABLE_CHECK. It doesn't need to support vmemmap optimizations because the debug checking doesn't need to run all the time. Overhead for debug settings is very normal.I see, let's call debug checking Topic 3 then, to separate it from Topic 1, which is TDX indicating that it is using a page for production kernels.
Topic 3: How should TDX indicate use of a page for debugging?
I'm okay if for debugging, TDX uses anything other than refcounts for checking, because refcounts will interfere with conversions.
Rick's other email is correct. The correct link should be
https://lore.kernel.org/all/[email protected]/.[INTERFERE WITH CONVERSIONS]
To summarize, if TDX uses refcounts to indicate that it is using a page, or to indicate anything else, then we cannot easily split a page on private to shared conversions.
Specifically, consider the case where only the x-th subpage of a huge folio is mapped into Secure-EPTs. When the guest requests to convert some subpage to shared, the huge folio has to be split for core-mm. Core-mm, which will use the shared page, must have split folios to be able to accurately and separately track refcounts for subpages.
Quoted 5 lines
During splitting,
guest_memfdwould see refcount of 512 (for 2M page being in the filemap) + 1 (if TDX indicates that the x-th subpage is mapped using a refcount), but would not be able to tell that the 513th refcount belongs to the x-th subpage.guest_memfdcan't split the huge folio unless it knows how to distribute the 513th refcount.In my POC, https://lore.kernel.org/all/aE%[email protected]/
kvm_gmem_private_has_safe_refcount()was introduce to check the folio ref count. It rejects private-to-shared conversion after splitting and unmapping KVM's secondary page tables if the refcount exceeds a valid threshold.Though in
https://lore.kernel.org/all/[email protected]/, we agreed that "EAGAIN is not the right code in case of "extra" refcounts held by TDX", this does not imply that rejecting the conversion itself is incorrect.This is why we are exploring alternative solutions instead of having TDX hold the page refcount.
Quoted 7 lines
So, either a per-page flag, per-folio flag or solutions e,f,g should be good.
IMO, regardless of the final choice,
guest_memfdneeds to identify problematic folios to:
- reject the private-to-shared conversion
- prevent further recycling afterkvm_gmem_free_folio()
Agreed!
Quoted 10 lines
Quoted 10 lines
One might say
guest_memfdcould clear all the refcounts that TDX is holding on the huge folio by unmapping the entire huge folio from the Secure-EPTs, but unmapping the entire huge folio for TDX means zeroing the contents and requiring guest re-acceptance. Both of these would mess up guest operation.Hence, guest_memfd's solution is to require that users of
guest_memfdfor private memory trustguest_memfdto maintain the pages around and not take any refcounts.
Quoted 6 lines
Quoted 3 lines
So back to Topic 1, for production kernels, is it okay that TDX does not need to indicate that it is using a page, and can trust
guest_memfdto keep the page around for the VM?If the "TDX does not need to indicate that it is using a page" means "do not take page refcount", I'm ok.
Yes, I was trying to generalize "do not take page refcount" to "TDX does not need to indicate that it is using a page", but I guess TDX can indicate that it is using a page for debugging as long as it doesn't use refcounts or otherwise interfere with conversions. So I believe we are in agreement on Topic 1 :)
Quoted 114 lines
Quoted 96 lines
Quoted 81 lines
Quoted 7 lines
Topic 2: How to handle unmapping/splitting errors arising from TDX?
Previously I was in favor of having
unmap()return an error (Rick suggested doing a POC, and in a more recent email Rick asked for a diffstat), but Vishal and I talked about this and now I agree having unmapping return an error is not a good approach for these reasons.Ok, let's close this option then.
Quoted 19 lines
1. Unmapping takes a range, and within the range there could be more than one unmapping error. I was previously thinking that
unmap()could return 0 for success and the failed PFN on error. Returning a single PFN on error is okay-ish but if there are more errors it could get complicated.Another error return option could be to return the folio where the unmapping/splitting issue happened, but that would not be sufficiently precise, since a folio could be larger than 4K and we want to track errors as precisely as we can to reduce memory loss due to errors.
2. What I think Yan has been trying to say:
unmap()returning an error is non-standard in the kernel.I think (1) is the dealbreaker here and there's no need to do the plumbing POC and diffstat.
Quoted 8 lines
So I think we're all in support of indicating unmapping/splitting issues without returning anything from
unmap(), and the discussed options area. Refcounts: won't work - mostly discussed in this (sub-)thread [3]. Using refcounts makes it impossible to distinguish between transient refcounts and refcounts due to errors.
b. Page flags: won't work with/can't benefit from HVO.
As above, this was for the purpose of catching bugs, not for guestmemfd to logically depend on it.
Quoted 6 lines
Suggestions still in the running:
c. Folio flags are not precise enough to indicate which page actually had an error, but this could be sufficient if we're willing to just waste the rest of the huge page on unmapping error.
For a scenario of TDX module bug, it seems ok to me.
Quoted 18 lines
d. Folio flags with folio splitting on error. This means that on unmapping/Secure EPT PTE splitting error, we have to split the (larger than 4K) folio to 4K, and then set a flag on the split folio.
The issue I see with this is that splitting pages with HVO applied means doing allocations, and in an error scenario there may not be memory left to split the pages.
e. Some other data structure in
guest_memfd, say, a linked list, and a function likekvm_gmem_add_error_pfn(struct page *page)that would look up theguest_memfdinode from the page and add the page's pfn to the linked list.Everywhere in
guest_memfdthat does unmapping/splitting would then check this linked list to see if the unmapping/splitting succeeded.Quoted 5 lines
Everywhere in
guest_memfdthat allocates pages will also check this linked list to make sure the pages are functional.When
guest_memfdtruncates, if the page being truncated is on the list, retain the refcount on the page and leak that page.I think this is a fine option.
Quoted 5 lines
f. Combination of c and e, something similar to HugeTLB's
folio_set_hugetlb_hwpoison(), which sets a flag AND adds the pages in trouble to a linked list on the folio.Quoted 8 lines
Quoted 5 lines
g. Like f, but basically treat an unmapping error as hardware poisoning.
I'm kind of inclined towards g, to just treat unmapping errors as HWPOISON and buying into all the HWPOISON handling requirements. What do yall think? Can a TDX unmapping error be considered as memory poisoning?
What does HWPOISON bring over refcounting the page/folio so that it never returns to the page allocator?
For Topic 2 (handling TDX unmapping errors), HWPOISON is better than refcounting because refcounting interferes with conversions (see [INTERFERE WITH CONVERSIONS] above).
Quoted 1 line
We are bugging the TD in these cases.
Quoted 7 lines
Bugging the TD does not help to prevent future conversions from being interfered with.
1. Conversions involves unmapping, so we could actually be in a conversion, the unmapping is performed and fails, and then we try to split and enter an infinite loop since private to shared conversions assumes
guest_memfdholds the only refcounts onguest_memfdmemory.We should bail out conversion even with the HWPOISON.
e.g.,
1. user triggers private-to-shared ioctl to convert 4K page A within a 2MB folio B to shared.
2.kvm_gmem_convert_should_proceed()executeskvm_gmem_split_private()andkvm_gmem_zap().
3.kvm_gmem_convert_should_proceed()checkskvm_gmem_has_invalid_folio()(Suppose TDX sets HWPOISON to page A or folio B afterkvm_gmem_zap(), thenkvm_gmem_has_invalid_folio()should return true).
4. Return-EFAULT.
Quoted 8 lines
If we allow the actual conversion to proceed after step 3, folio B will be split into 4KB folios, with page A being converted to a shared 4KB folio, which becomes accessible by userspace.
This could cause a machine check (#MC) on certain platforms. We should avoid this scenario when possible.
Thanks for pointing this out. This is a good point and will definitely have to be handled separately under "what to do when there was some issue on a page (possibly caused by unmapping)", or as Yan pointed out above, what to do when "handling problematic folios".
Regarding handling errors, or recording errors, or communicating errors to guest_memfd, Yan seems in favor of some kind of page flag. I know Rick is suggesting option e. Can we do something between f and g? I'm thinking that the easiest page flag to use is the HWpoison flag, because
1. HWpoison checking is already part of guest_memfd, or should be.
guest_memfd already checks HWpoison for kvm_gmem_get_pfn(), and __do_fault() checks HWpoison for guest_memfd [5]. As Yan pointed out above, it should definitely check and deal with HWpoison on conversion. Perhaps on truncation it should look at HWpoison, or very likely memory_failure() will need special handling for guest_memfd folios. I'll look into this separately as part of HugeTLB support patch series.
2. HWpoison support (especially tracking of sub-folio HWpoison) in folio_set_hugetlb_hwpoison() can hopefully be reused for guest_memfd.
3. For now, no need to invent a new tracking mechanism or data structure to support option e.
4. HWpoison is kind of "part of guest_memfd" if you consider that guest_memfd folios to be pretty much always owned by some guest_memfd inode, and if the HWpoison flag is checked at the appropriate places.
Could we (at least for the next RFC of this TDX huge page support for private memory series, or as a first cut), use HWpoison, and then if we identify that the concept of HWpoison is being overloaded/polluted, then try another flag/mechanism for tracking?
I plan to work on HWpoison/kvm_gmem_error_folio() handling for HugeTLB soon and then I can keep the community updated if I find anything new or incompatible.
Quoted 8 lines
Quoted 8 lines
2. The conversion ioctl is a
guest_memfdioctl, not a VM ioctl, and so there is no check that the VM is not dead. There shouldn't be any check on the VM, because shareability is a property of the memory and should be changeable independent of the associated VM.Quoted 2 lines
Ohhh... Is
this about the code to allow gmem fds to be handed to new VMs?
Quoted 6 lines
Quoted 6 lines
Nope, it's not related to linking. The proposed
KVM_LINK_GUEST_MEMFDioctl [4] also doesn't check if the source VM is dead. There shouldn't be any check on the source VM, since the memory is fromguest_memfdand should be independently transferable to a new VM.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
In reply to Ackerley TngQuoted 3 lines · Ackerley Tng
a. Refcounts: won't work - mostly discussed in this (sub-)thread [3]. Using refcounts makes it impossible to distinguish between transient refcounts and refcounts due to errors.
[3] you pointed to this thread, which is the one we are discussing on. Is that the link you meant?
https://lore.kernel.org/all/[email protected]/
Edgecombe, Rick P
maintainerRe: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
In reply to Yan ZhaoQuoted 4 lines · Yan Zhao
Quoted 3 lines
Few questions here:
1) It sounds like the failure to remove entries from SEPT could only be due to bugs in the KVM/TDX module,Yes.
A TDX module bug could hypothetically cause many types of host instability. We should consider a little more on the context for the risk before we make TDX a special case or add much error handling code around it. If we end up with a bunch of paranoid error handling code around TDX module behavior, that is going to be a pain to maintain. And error handling code for rare cases will be hard to remove.
We've had a history of unreliable page removal during the base series development. When we solved the problem, it was not completely clean (though more on the guest affecting side). So I think there is reason to be concerned. But this should work reliably in theory. So I'm not sure we should use the error case as a hard reason. Instead maybe we should focus on how to make it less likely to have an error. Unless there is a specific case you are considering, Yan?
That said, I think the refcounting on error (or rather, notifying guestmemfd on error do let it handle the error how it wants) is a fine solution. As long as it doesn't take much code (as is the case for Yan's POC).
Quoted 20 lines
Quoted 3 lines
how reliable would it be to
continue executing TDX VMs on the host once such bugs are hit?The TDX VMs will be killed. However, the private pages are still mapped in the SEPT (after the unmapping failure).
The teardown flow for TDX VM is:
do_exit
|->exit_files
|->kvm_gmem_release ==> (1) Unmap guest pages |->release kvmfd
|->kvm_destroy_vm (2) Reclaiming resources |->kvm_arch_pre_destroy_vm ==> Release hkid |->kvm_arch_destroy_vm ==> Reclaim SEPT page table pagesWithout holding page reference after (1) fails, the guest pages may have been re-assigned by the host OS while they are still still tracked in the TDX module.
Quoted 5 lines
Quoted 2 lines
2) Is it reliable to continue executing the host kernel and other normal VMs once such bugs are hit?
If with TDX holding the page ref count, the impact of unmapping failure of guest
pages is just to leak those pages.
If the kernel might be able to continue working, it should try. It should warn if there is a risk, so people can use panic_on_warn if they want to stop the kernel.
Quoted 7 lines
Quoted 3 lines
3) Can the memory be reclaimed reliably if the VM is marked as dead and cleaned up right away?
As in the above flow, TDX needs to hold the page reference on unmapping failure
until after reclaiming is successful. Well, reclaiming itself is possible to fail either.
We could ask TDX module folks if there is anything they could guarantee.
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 13 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 3 lines
Few questions here:
1) It sounds like the failure to remove entries from SEPT could only be due to bugs in the KVM/TDX module,Yes.
A TDX module bug could hypothetically cause many types of host instability. We should consider a little more on the context for the risk before we make TDX a special case or add much error handling code around it. If we end up with a bunch of paranoid error handling code around TDX module behavior, that is going to be a pain to maintain. And error handling code for rare cases will be hard to remove.
Quoted 7 lines
We've had a history of unreliable page removal during the base series development. When we solved the problem, it was not completely clean (though more on the guest affecting side). So I think there is reason to be concerned. But this should work reliably in theory. So I'm not sure we should use the error case as a hard reason. Instead maybe we should focus on how to make it less likely to have an error. Unless there is a specific case you are considering, Yan?
Yes, KVM/TDX does its utmost to ensure that page removal cannot fail. However, if bugs occur, KVM/TDX will trigger a BUG_ON and leak the problematic page. This is a simple way to constrain the error within affected pages. It also helps in debugging when unexpected errors arise.
Returning the error code up the stack is not worthwhile and I don't even think it's feasible.
Quoted 44 lines
That said, I think the refcounting on error (or rather, notifying guestmemfd on error do let it handle the error how it wants) is a fine solution. As long as it doesn't take much code (as is the case for Yan's POC).
Quoted 20 lines
Quoted 3 lines
how reliable would it be to
continue executing TDX VMs on the host once such bugs are hit?The TDX VMs will be killed. However, the private pages are still mapped in the SEPT (after the unmapping failure).
The teardown flow for TDX VM is:
do_exit
|->exit_files
|->kvm_gmem_release ==> (1) Unmap guest pages |->release kvmfd
|->kvm_destroy_vm (2) Reclaiming resources |->kvm_arch_pre_destroy_vm ==> Release hkid |->kvm_arch_destroy_vm ==> Reclaim SEPT page table pagesWithout holding page reference after (1) fails, the guest pages may have been re-assigned by the host OS while they are still still tracked in the TDX module.
Quoted 5 lines
Quoted 2 lines
2) Is it reliable to continue executing the host kernel and other normal VMs once such bugs are hit?
If with TDX holding the page ref count, the impact of unmapping failure of guest
pages is just to leak those pages.If the kernel might be able to continue working, it should try. It should warn if there is a risk, so people can use
panic_on_warnif they want to stop the kernel.Quoted 7 lines
Quoted 3 lines
3) Can the memory be reclaimed reliably if the VM is marked as dead and cleaned up right away?
As in the above flow, TDX needs to hold the page reference on unmapping failure
until after reclaiming is successful. Well, reclaiming itself is possible to fail either.We could ask TDX module folks if there is anything they could guarantee.
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
In reply to Yan ZhaoQuoted 36 lines · Yan Zhao
Quoted 16 lines · Vishal Annapurve
Quoted 15 lines · Yan Zhao
We need to restore to the previous status (which includes the host page table) if conversion can't be done.
That said, in my view, a better flow would be:1.
guest_memfdsends a pre-invalidation request to users (users here means the consumers in kernel of memory allocated fromguest_memfd).2. Users (A, B, ..., X) perform pre-checks to determine if invalidation can proceed. For example, in the case of TDX, this might involve memory allocation and page splitting.
3. Based on the pre-check results,
guest_memfdeither aborts the invalidation or proceeds by sending the actual invalidation request.Quoted 8 lines
Quoted 4 lines
4. Users (A-X) perform the actual unmap operation, ensuring it cannot fail. For TDX, the unmap must succeed unless there are bugs in the KVM or TDX module. In such cases, TDX can callback
guest_memfdto inform the poison-status of the page or elevate the page reference count.Few questions here:
1) It sounds like the failure to remove entries from SEPT could only be due to bugs in the KVM/TDX module,Yes.
Quoted 2 lines
how reliable would it be to
continue executing TDX VMs on the host once such bugs are hit?The TDX VMs will be killed. However, the private pages are still mapped in the SEPT (after the unmapping failure).
The teardown flow for TDX VM is:
do_exit
|->exit_files
Quoted 8 lines
|->kvm_gmem_release ==> (1) Unmap guest pages |->release kvmfd |->kvm_destroy_vm (2) Reclaiming resources |->kvm_arch_pre_destroy_vm ==> Release hkid |->kvm_arch_destroy_vm ==> Reclaim SEPT page table pagesWithout holding page reference after (1) fails, the guest pages may have been re-assigned by the host OS while they are still still tracked in the TDX module.
What happens to the pagetable memory holding the SEPT entry? Is that also supposed to be leaked?
Quoted 9 lines
Quoted 4 lines
2) Is it reliable to continue executing the host kernel and other normal VMs once such bugs are hit?
If with TDX holding the page ref count, the impact of unmapping failure of guest pages is just to leak those pages.
Quoted 2 lines
3) Can the memory be reclaimed reliably if the VM is marked as dead and cleaned up right away?
Quoted 8 lines
As in the above flow, TDX needs to hold the page reference on unmapping failure until after reclaiming is successful. Well, reclaiming itself is possible to fail either.
So, below is my proposal. Showed in the simple POC code based on
https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2.Patch 1: TDX increases page ref count on unmap failure.
This will not work as Ackerley pointed out earlier [1], it will be impossible to differentiate between transient refcounts on private pages and extra refcounts of private memory due to TDX unmap failure.
[1] https://lore.kernel.org/lkml/[email protected]/
Quoted 4 lines
Patch 2: Bail out private-to-shared conversion if splitting fails. Patch 3: Make
kvm_gmem_zap()return void....
Quoted 8 lines
/*If the above changes are agreeable, we could consider a more ambitious approach:
introducing an interface like:int
guest_memfd_add_page_ref_count(gfn_t gfn, int nr); intguest_memfd_dec_page_ref_count(gfn_t gfn, int nr);
I don't see any reason to introduce full tracking of gfn mapping status in SEPTs just to handle very rare scenarios which KVM/TDX are taking utmost care to avoid.
That being said, I see value in letting guest_memfd know exact ranges still being under use by the TDX module due to unmapping failures. guest_memfd can take the right action instead of relying on refcounts.
Does KVM continue unmapping the full range even after TDX SEPT management fails to unmap a subrange?
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 43 lines · Vishal Annapurve
Quoted 42 lines · Yan Zhao
Quoted 16 lines · Vishal Annapurve
Quoted 15 lines · Yan Zhao
We need to restore to the previous status (which includes the host page table) if conversion can't be done.
That said, in my view, a better flow would be:1.
guest_memfdsends a pre-invalidation request to users (users here means the consumers in kernel of memory allocated fromguest_memfd).2. Users (A, B, ..., X) perform pre-checks to determine if invalidation can proceed. For example, in the case of TDX, this might involve memory allocation and page splitting.
3. Based on the pre-check results,
guest_memfdeither aborts the invalidation or proceeds by sending the actual invalidation request.Quoted 8 lines
Quoted 4 lines
4. Users (A-X) perform the actual unmap operation, ensuring it cannot fail. For TDX, the unmap must succeed unless there are bugs in the KVM or TDX module. In such cases, TDX can callback
guest_memfdto inform the poison-status of the page or elevate the page reference count.Few questions here:
1) It sounds like the failure to remove entries from SEPT could only be due to bugs in the KVM/TDX module,Yes.
Quoted 2 lines
how reliable would it be to
continue executing TDX VMs on the host once such bugs are hit?The TDX VMs will be killed. However, the private pages are still mapped in the SEPT (after the unmapping failure).
The teardown flow for TDX VM is:
do_exit
|->exit_files|->kvm_gmem_release ==> (1) Unmap guest pages |->release kvmfd |->kvm_destroy_vm (2) Reclaiming resources |->kvm_arch_pre_destroy_vm ==> Release hkid |->kvm_arch_destroy_vm ==> Reclaim SEPT page table pages
Quoted 5 lines
Quoted 2 lines
Without holding page reference after (1) fails, the guest pages may have been re-assigned by the host OS while they are still still tracked in the TDX module.
What happens to the pagetable memory holding the SEPT entry? Is that also supposed to be leaked?
It depends on if the reclaiming of the page table pages holding the SEPT entry fails. If it is, it will be also leaked.
But the page to hold TDR is for sure to be leaked as the reclaiming of TDR page will fail after (1) fails.
Quoted 11 lines
Quoted 11 lines
Quoted 2 lines
2) Is it reliable to continue executing the host kernel and other normal VMs once such bugs are hit?
If with TDX holding the page ref count, the impact of unmapping failure of guest pages is just to leak those pages.
Quoted 2 lines
3) Can the memory be reclaimed reliably if the VM is marked as dead and cleaned up right away?
As in the above flow, TDX needs to hold the page reference on unmapping failure until after reclaiming is successful. Well, reclaiming itself is possible to fail either.
Quoted 8 lines
Quoted 4 lines
So, below is my proposal. Showed in the simple POC code based on
https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2.Patch 1: TDX increases page ref count on unmap failure.
This will not work as Ackerley pointed out earlier [1], it will be impossible to differentiate between transient refcounts on private pages and extra refcounts of private memory due to TDX unmap failure.
Hmm. why are there transient refcounts on private pages? And why should we differentiate the two?
Quoted 19 lines
[1] https://lore.kernel.org/lkml/[email protected]/
Quoted 4 lines
Patch 2: Bail out private-to-shared conversion if splitting fails. Patch 3: Make
kvm_gmem_zap()return void....
Quoted 8 lines
/*If the above changes are agreeable, we could consider a more ambitious approach:
introducing an interface like:int
guest_memfd_add_page_ref_count(gfn_t gfn, int nr); intguest_memfd_dec_page_ref_count(gfn_t gfn, int nr);I don't see any reason to introduce full tracking of gfn mapping status in SEPTs just to handle very rare scenarios which KVM/TDX are taking utmost care to avoid.
Quoted 6 lines
That being said, I see value in letting
guest_memfdknow exact ranges still being under use by the TDX module due to unmapping failures.guest_memfdcan take the right action instead of relying on refcounts.Does KVM continue unmapping the full range even after TDX SEPT management fails to unmap a subrange?
Yes, if there's no bug in KVM, it will continue unmapping the full ranges.
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 48 lines · Yan Zhao
Quoted 46 lines · Vishal Annapurve
Quoted 44 lines · Yan Zhao
Quoted 16 lines · Vishal Annapurve
Quoted 15 lines · Yan Zhao
We need to restore to the previous status (which includes the host page table) if conversion can't be done.
That said, in my view, a better flow would be:1.
guest_memfdsends a pre-invalidation request to users (users here means the consumers in kernel of memory allocated fromguest_memfd).2. Users (A, B, ..., X) perform pre-checks to determine if invalidation can proceed. For example, in the case of TDX, this might involve memory allocation and page splitting.
3. Based on the pre-check results,
guest_memfdeither aborts the invalidation or proceeds by sending the actual invalidation request.Quoted 8 lines
Quoted 4 lines
4. Users (A-X) perform the actual unmap operation, ensuring it cannot fail. For TDX, the unmap must succeed unless there are bugs in the KVM or TDX module. In such cases, TDX can callback
guest_memfdto inform the poison-status of the page or elevate the page reference count.Few questions here:
1) It sounds like the failure to remove entries from SEPT could only be due to bugs in the KVM/TDX module,Yes.
Quoted 2 lines
how reliable would it be to
continue executing TDX VMs on the host once such bugs are hit?The TDX VMs will be killed. However, the private pages are still mapped in the SEPT (after the unmapping failure).
The teardown flow for TDX VM is:
do_exit
|->exit_files|->kvm_gmem_release ==> (1) Unmap guest pages |->release kvmfd |->kvm_destroy_vm (2) Reclaiming resources |->kvm_arch_pre_destroy_vm ==> Release hkid |->kvm_arch_destroy_vm ==> Reclaim SEPT page table pagesWithout holding page reference after (1) fails, the guest pages may have been re-assigned by the host OS while they are still still tracked in the TDX module.
Quoted 7 lines
Quoted 2 lines
What happens to the pagetable memory holding the SEPT entry? Is that also supposed to be leaked?
It depends on if the reclaiming of the page table pages holding the SEPT entry fails. If it is, it will be also leaked.
But the page to hold TDR is for sure to be leaked as the reclaiming of TDR page will fail after (1) fails.
Ok. Few questions that I would like to touch base briefly on:
i) If (1) fails and then VM is marked as bugged, will the TDX module actually access that page in context of the same VM again? ii) What all resources should remain unreclaimed if (1) fails?
* page backing SEPT entry
* page backing PAMT entry
* TDMR
If TDMR is the only one that fails to reclaim, will the TDX module
actually access the physical memory ever after the VM is cleaned up? Otherwise, should all of these be made unreclaimable?
iii) Will it be safe for the host to use that memory by proper WBINVD/memory clearing sequence if TDX module/TD is not going to use that memory?
Quoted 16 lines
Quoted 16 lines
Quoted 16 lines
Quoted 4 lines
2) Is it reliable to continue executing the host kernel and other normal VMs once such bugs are hit?
If with TDX holding the page ref count, the impact of unmapping failure of guest pages is just to leak those pages.
Quoted 2 lines
3) Can the memory be reclaimed reliably if the VM is marked as dead and cleaned up right away?
As in the above flow, TDX needs to hold the page reference on unmapping failure until after reclaiming is successful. Well, reclaiming itself is possible to fail either.
So, below is my proposal. Showed in the simple POC code based on
https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2.
Quoted 7 lines
Quoted 5 lines
Quoted 1 line
Patch 1: TDX increases page ref count on unmap failure.
This will not work as Ackerley pointed out earlier [1], it will be impossible to differentiate between transient refcounts on private pages and extra refcounts of private memory due to TDX unmap failure.
Hmm. why are there transient refcounts on private pages? And why should we differentiate the two?
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
Speculative/transient refcounts came up a few times In the context of guest_memfd discussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.
Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/lkml/[email protected]/
Quoted 28 lines
Quoted 21 lines
[1] https://lore.kernel.org/lkml/[email protected]/
Quoted 4 lines
Patch 2: Bail out private-to-shared conversion if splitting fails. Patch 3: Make
kvm_gmem_zap()return void....
Quoted 8 lines
/*If the above changes are agreeable, we could consider a more ambitious approach:
introducing an interface like:int
guest_memfd_add_page_ref_count(gfn_t gfn, int nr); intguest_memfd_dec_page_ref_count(gfn_t gfn, int nr);I don't see any reason to introduce full tracking of gfn mapping status in SEPTs just to handle very rare scenarios which KVM/TDX are taking utmost care to avoid.
Quoted 6 lines
That being said, I see value in letting
guest_memfdknow exact ranges still being under use by the TDX module due to unmapping failures.guest_memfdcan take the right action instead of relying on refcounts.Does KVM continue unmapping the full range even after TDX SEPT management fails to unmap a subrange?
Yes, if there's no bug in KVM, it will continue unmapping the full ranges.
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 57 lines · Vishal Annapurve
Quoted 48 lines · Yan Zhao
Quoted 46 lines · Vishal Annapurve
Quoted 44 lines · Yan Zhao
Quoted 16 lines · Vishal Annapurve
Quoted 15 lines · Yan Zhao
We need to restore to the previous status (which includes the host page table) if conversion can't be done.
That said, in my view, a better flow would be:1.
guest_memfdsends a pre-invalidation request to users (users here means the consumers in kernel of memory allocated fromguest_memfd).2. Users (A, B, ..., X) perform pre-checks to determine if invalidation can proceed. For example, in the case of TDX, this might involve memory allocation and page splitting.
3. Based on the pre-check results,
guest_memfdeither aborts the invalidation or proceeds by sending the actual invalidation request.Quoted 8 lines
Quoted 4 lines
4. Users (A-X) perform the actual unmap operation, ensuring it cannot fail. For TDX, the unmap must succeed unless there are bugs in the KVM or TDX module. In such cases, TDX can callback
guest_memfdto inform the poison-status of the page or elevate the page reference count.Few questions here:
1) It sounds like the failure to remove entries from SEPT could only be due to bugs in the KVM/TDX module,Yes.
Quoted 2 lines
how reliable would it be to
continue executing TDX VMs on the host once such bugs are hit?The TDX VMs will be killed. However, the private pages are still mapped in the SEPT (after the unmapping failure).
The teardown flow for TDX VM is:
do_exit
|->exit_files|->kvm_gmem_release ==> (1) Unmap guest pages |->release kvmfd |->kvm_destroy_vm (2) Reclaiming resources |->kvm_arch_pre_destroy_vm ==> Release hkid |->kvm_arch_destroy_vm ==> Reclaim SEPT page table pagesWithout holding page reference after (1) fails, the guest pages may have been re-assigned by the host OS while they are still still tracked in the TDX module.
Quoted 7 lines
Quoted 2 lines
What happens to the pagetable memory holding the SEPT entry? Is that also supposed to be leaked?
It depends on if the reclaiming of the page table pages holding the SEPT entry fails. If it is, it will be also leaked.
But the page to hold TDR is for sure to be leaked as the reclaiming of TDR page will fail after (1) fails.
Quoted 3 lines
Ok. Few questions that I would like to touch base briefly on:
i) If (1) fails and then VM is marked as bugged, will the TDX module actually access that page in context of the same VM again?
In TDX module, the TD is marked as TD_TEARDOWN after step (2) when hkid is released successfully.
Before that, TD is able to access the pages even if it is marked as buggy by KVM.
After TD is marked as TD_TEARDOWN, since (1) fails, the problematic guest private pages are still tracked in the PAMT entries.
So, re-assignment the same PFN to other TDs will fail.
Quoted 7 lines
ii) What all resources should remain unreclaimed if (1) fails?
* page backing SEPT entry
* page backing PAMT entry
* TDMR
If TDMR is the only one that fails to reclaim, will the TDX module
actually access the physical memory ever after the VM is cleaned up? Otherwise, should all of these be made unreclaimable?
From my understanding, they are
- guest private pages
- TDR page
- PAMT entries for guest private pages and TDR page
Quoted 3 lines
iii) Will it be safe for the host to use that memory by proper WBINVD/memory clearing sequence if TDX module/TD is not going to use that memory?
I'm not sure. But it should be impossible for host to re-assign the pages to other TDs as long as PAMT entries are not updated.
Quoted 22 lines
Quoted 14 lines
Quoted 14 lines
Quoted 14 lines
Quoted 2 lines
2) Is it reliable to continue executing the host kernel and other normal VMs once such bugs are hit?
If with TDX holding the page ref count, the impact of unmapping failure of guest pages is just to leak those pages.
Quoted 2 lines
3) Can the memory be reclaimed reliably if the VM is marked as dead and cleaned up right away?
As in the above flow, TDX needs to hold the page reference on unmapping failure until after reclaiming is successful. Well, reclaiming itself is possible to fail either.
So, below is my proposal. Showed in the simple POC code based on
https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2.Quoted 7 lines
Quoted 5 lines
Quoted 1 line
Patch 1: TDX increases page ref count on unmap failure.
This will not work as Ackerley pointed out earlier [1], it will be impossible to differentiate between transient refcounts on private pages and extra refcounts of private memory due to TDX unmap failure.
Hmm. why are there transient refcounts on private pages? And why should we differentiate the two?
Quoted 6 lines
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.
GUP-fast only walks page tables for shared memory?
Can other walkers get a private folio by walking shared mappings?
On those speculative/transient refcounts came up, can't the kvm_gmem_convert_should_proceed() wait in an interruptible way before returning failure?
The wait will anyway happen after the conversion is started, i.e., in filemap_remove_folio_for_restructuring().
while (!folio_ref_freeze(folio, filemap_refcount)) {
/*
* At this point only filemap refcounts are expected, hence okay
* to spin until speculative refcounts go away.
*/
WARN_ONCE(1, "Spinning on folio=%p refcount=%d", folio, folio_ref_count(folio));
}BTW, I noticed that there's no filemap_invalidate_lock_shared() in kvm_gmem_fault_shared() in
https://lore.kernel.org/all/[email protected]/.
Do you know why?
Quoted 11 lines
Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
Ok.
Currently, "letting guest_memfd know exact ranges still being under use by the TDX module due to unmapping failures" is good enough for TDX, though full tracking of each GFN is even better.
Quoted 31 lines
[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/lkml/[email protected]/Quoted 28 lines
Quoted 21 lines
[1] https://lore.kernel.org/lkml/[email protected]/
Quoted 4 lines
Patch 2: Bail out private-to-shared conversion if splitting fails. Patch 3: Make
kvm_gmem_zap()return void....
Quoted 8 lines
/*If the above changes are agreeable, we could consider a more ambitious approach:
introducing an interface like:int
guest_memfd_add_page_ref_count(gfn_t gfn, int nr); intguest_memfd_dec_page_ref_count(gfn_t gfn, int nr);I don't see any reason to introduce full tracking of gfn mapping status in SEPTs just to handle very rare scenarios which KVM/TDX are taking utmost care to avoid.
Quoted 6 lines
That being said, I see value in letting
guest_memfdknow exact ranges still being under use by the TDX module due to unmapping failures.guest_memfdcan take the right action instead of relying on refcounts.Does KVM continue unmapping the full range even after TDX SEPT management fails to unmap a subrange?
Yes, if there's no bug in KVM, it will continue unmapping the full ranges.
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 112 lines · Yan Zhao
Quoted 57 lines · Vishal Annapurve
Quoted 48 lines · Yan Zhao
Quoted 46 lines · Vishal Annapurve
Quoted 44 lines · Yan Zhao
Quoted 16 lines · Vishal Annapurve
Quoted 15 lines · Yan Zhao
We need to restore to the previous status (which includes the host page table) if conversion can't be done.
That said, in my view, a better flow would be:1.
guest_memfdsends a pre-invalidation request to users (users here means the consumers in kernel of memory allocated fromguest_memfd).2. Users (A, B, ..., X) perform pre-checks to determine if invalidation can proceed. For example, in the case of TDX, this might involve memory allocation and page splitting.
3. Based on the pre-check results,
guest_memfdeither aborts the invalidation or proceeds by sending the actual invalidation request.Quoted 8 lines
Quoted 4 lines
4. Users (A-X) perform the actual unmap operation, ensuring it cannot fail. For TDX, the unmap must succeed unless there are bugs in the KVM or TDX module. In such cases, TDX can callback
guest_memfdto inform the poison-status of the page or elevate the page reference count.Few questions here:
1) It sounds like the failure to remove entries from SEPT could only be due to bugs in the KVM/TDX module,Yes.
Quoted 2 lines
how reliable would it be to
continue executing TDX VMs on the host once such bugs are hit?The TDX VMs will be killed. However, the private pages are still mapped in the SEPT (after the unmapping failure).
The teardown flow for TDX VM is:
do_exit
|->exit_files|->kvm_gmem_release ==> (1) Unmap guest pages |->release kvmfd |->kvm_destroy_vm (2) Reclaiming resources |->kvm_arch_pre_destroy_vm ==> Release hkid |->kvm_arch_destroy_vm ==> Reclaim SEPT page table pagesWithout holding page reference after (1) fails, the guest pages may have been re-assigned by the host OS while they are still still tracked in the TDX module.
Quoted 7 lines
Quoted 2 lines
What happens to the pagetable memory holding the SEPT entry? Is that also supposed to be leaked?
It depends on if the reclaiming of the page table pages holding the SEPT entry fails. If it is, it will be also leaked.
But the page to hold TDR is for sure to be leaked as the reclaiming of TDR page will fail after (1) fails.Quoted 3 lines
Ok. Few questions that I would like to touch base briefly on:
i) If (1) fails and then VM is marked as bugged, will the TDX module actually access that page in context of the same VM again?In TDX module, the TD is marked as
TD_TEARDOWNafter step (2) when hkid is released successfully.
Before that, TD is able to access the pages even if it is marked as buggy by KVM.After TD is marked as
TD_TEARDOWN, since (1) fails, the problematic guest private pages are still tracked in the PAMT entries.
So, re-assignment the same PFN to other TDs will fail.Quoted 7 lines
ii) What all resources should remain unreclaimed if (1) fails?
* page backing SEPT entry
* page backing PAMT entry
* TDMR
If TDMR is the only one that fails to reclaim, will the TDX module
actually access the physical memory ever after the VM is cleaned up? Otherwise, should all of these be made unreclaimable?From my understanding, they are
- guest private pages
- TDR page
- PAMT entries for guest private pages and TDR pageQuoted 3 lines
iii) Will it be safe for the host to use that memory by proper WBINVD/memory clearing sequence if TDX module/TD is not going to use that memory?
I'm not sure. But it should be impossible for host to re-assign the pages to other TDs as long as PAMT entries are not updated.
Quoted 22 lines
Quoted 21 lines
Quoted 11 lines
Quoted 11 lines
Quoted 2 lines
2) Is it reliable to continue executing the host kernel and other normal VMs once such bugs are hit?
If with TDX holding the page ref count, the impact of unmapping failure of guest pages is just to leak those pages.
Quoted 2 lines
3) Can the memory be reclaimed reliably if the VM is marked as dead and cleaned up right away?
As in the above flow, TDX needs to hold the page reference on unmapping failure until after reclaiming is successful. Well, reclaiming itself is possible to fail either.
Quoted 8 lines
Quoted 4 lines
So, below is my proposal. Showed in the simple POC code based on
https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2.Patch 1: TDX increases page ref count on unmap failure.
This will not work as Ackerley pointed out earlier [1], it will be impossible to differentiate between transient refcounts on private pages and extra refcounts of private memory due to TDX unmap failure.
Hmm. why are there transient refcounts on private pages? And why should we differentiate the two?
Quoted 8 lines
Quoted 6 lines
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.GUP-fast only walks page tables for shared memory?
Can other walkers get a private folio by walking shared mappings?
No, they can't. There can be walkers that parse direct map entries.
Quoted 4 lines
On those speculative/transient refcounts came up, can't the
kvm_gmem_convert_should_proceed()wait in an interruptible way before returning failure?
These refcounts can land any time on any of the ranges, so guest_memfd implementation to bail out on errors will need to be time bound for each folio and will need traversal of each folio even before actual restructuring. That increases the complexity and latency of conversion operation.
Quoted 12 lines
The wait will anyway happen after the conversion is started, i.e., in
filemap_remove_folio_for_restructuring().while (!folio_ref_freeze(folio, filemap_refcount)) { /* * At this point only filemap refcounts are expected, hence okay * to spin until speculative refcounts go away. */ WARN_ONCE(1, "Spinning on folio=%p refcount=%d", folio, folio_ref_count(folio)); }
Quoted 5 lines
BTW, I noticed that there's no
filemap_invalidate_lock_shared()inkvm_gmem_fault_shared()in
https://lore.kernel.org/all/[email protected]/.Do you know why?
It will land when guest_memfd in-place conversion support will be posted.
Quoted 49 lines
Quoted 7 lines
Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Quoted 5 lines
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
Ok.
Currently, "lettingguest_memfdknow exact ranges still being under use by the TDX module due to unmapping failures" is good enough for TDX, though full tracking of each GFN is even better.Quoted 31 lines
[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/lkml/[email protected]/Quoted 28 lines
Quoted 21 lines
[1] https://lore.kernel.org/lkml/[email protected]/
Quoted 4 lines
Patch 2: Bail out private-to-shared conversion if splitting fails. Patch 3: Make
kvm_gmem_zap()return void....
Quoted 8 lines
/*If the above changes are agreeable, we could consider a more ambitious approach:
introducing an interface like:int
guest_memfd_add_page_ref_count(gfn_t gfn, int nr); intguest_memfd_dec_page_ref_count(gfn_t gfn, int nr);I don't see any reason to introduce full tracking of gfn mapping status in SEPTs just to handle very rare scenarios which KVM/TDX are taking utmost care to avoid.
Quoted 6 lines
That being said, I see value in letting
guest_memfdknow exact ranges still being under use by the TDX module due to unmapping failures.guest_memfdcan take the right action instead of relying on refcounts.Does KVM continue unmapping the full range even after TDX SEPT management fails to unmap a subrange?
Yes, if there's no bug in KVM, it will continue unmapping the full ranges.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
In reply to Vishal AnnapurveQuoted 1 line · Vishal Annapurve
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
I'm confused...
Quoted 11 lines
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
This means the refcount could be increased for other reasons, and so guestmemfd shouldn't rely on refcounts for it's purposes? So, it is not a problem for other components handling the page elevate the refcount?
Quoted 6 lines
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
If this becomes a thing for private memory (which it isn't yet), then couldn't we just change things at that point?
Is the only issue with TDX taking refcounts that it won't work with future code changes?
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 17 lines · Rick P
Quoted 1 line · Vishal Annapurve
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
I'm confused...
Quoted 11 lines
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Quoted 3 lines
This means the refcount could be increased for other reasons, and so guestmemfd shouldn't rely on refcounts for it's purposes? So, it is not a problem for other components handling the page elevate the refcount?
Besides that, in [3], when kvm_gmem_convert_should_proceed() determines whether to convert to private, why is it allowed to just invoke kvm_gmem_has_safe_refcount() without taking speculative/transient refcounts into account? Isn't it more easier for shared pages to have speculative/transient refcounts?
Quoted 17 lines
Quoted 6 lines
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
If this becomes a thing for private memory (which it isn't yet), then couldn't we just change things at that point?
Is the only issue with TDX taking refcounts that it won't work with future code changes?
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 19 lines · Yan Zhao
Quoted 17 lines · Rick P
Quoted 1 line · Vishal Annapurve
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
I'm confused...
Quoted 11 lines
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Quoted 8 lines
Quoted 3 lines
This means the refcount could be increased for other reasons, and so guestmemfd shouldn't rely on refcounts for it's purposes? So, it is not a problem for other components handling the page elevate the refcount?
Besides that, in [3], when
kvm_gmem_convert_should_proceed()determines whether to convert to private, why is it allowed to just invokekvm_gmem_has_safe_refcount()without taking speculative/transient refcounts into account? Isn't it more easier for shared pages to have speculative/transient refcounts?
These speculative refcounts are taken into account, in case of unsafe refcounts, conversion operation immediately exits to userspace with EAGAIN and userspace is supposed to retry conversion.
Yes, it's more easier for shared pages to have speculative/transient refcounts.
Quoted 20 lines
Quoted 17 lines
Quoted 6 lines
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
If this becomes a thing for private memory (which it isn't yet), then couldn't we just change things at that point?
Is the only issue with TDX taking refcounts that it won't work with future code changes?
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 29 lines · Vishal Annapurve
Quoted 19 lines · Yan Zhao
Quoted 17 lines · Rick P
Quoted 1 line · Vishal Annapurve
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
I'm confused...
Quoted 11 lines
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Quoted 8 lines
Quoted 3 lines
This means the refcount could be increased for other reasons, and so guestmemfd shouldn't rely on refcounts for it's purposes? So, it is not a problem for other components handling the page elevate the refcount?
Besides that, in [3], when
kvm_gmem_convert_should_proceed()determines whether to convert to private, why is it allowed to just invokekvm_gmem_has_safe_refcount()without taking speculative/transient refcounts into account? Isn't it more easier for shared pages to have speculative/transient refcounts?
Quoted 3 lines
These speculative refcounts are taken into account, in case of unsafe refcounts, conversion operation immediately exits to userspace with EAGAIN and userspace is supposed to retry conversion.
Hmm, so why can't private-to-shared conversion also exit to userspace with EAGAIN?
In the POC
https://lore.kernel.org/lkml/aE%[email protected],kvm_gmem_convert_should_proceed() just returns EFAULT (can be modified to EAGAIN) to userspace instead.
Quoted 23 lines
Yes, it's more easier for shared pages to have speculative/transient refcounts.
Quoted 20 lines
Quoted 17 lines
Quoted 6 lines
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
If this becomes a thing for private memory (which it isn't yet), then couldn't we just change things at that point?
Is the only issue with TDX taking refcounts that it won't work with future code changes?
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 31 lines · Yan Zhao
Quoted 29 lines · Vishal Annapurve
Quoted 27 lines · Yan Zhao
Quoted 17 lines · Rick P
Quoted 1 line · Vishal Annapurve
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
I'm confused...
Quoted 11 lines
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Quoted 3 lines
This means the refcount could be increased for other reasons, and so guestmemfd shouldn't rely on refcounts for it's purposes? So, it is not a problem for other components handling the page elevate the refcount?
Besides that, in [3], when
kvm_gmem_convert_should_proceed()determines whether to convert to private, why is it allowed to just invokekvm_gmem_has_safe_refcount()without taking speculative/transient refcounts into account? Isn't it more easier for shared pages to have speculative/transient refcounts?
Quoted 5 lines
Quoted 3 lines
These speculative refcounts are taken into account, in case of unsafe refcounts, conversion operation immediately exits to userspace with EAGAIN and userspace is supposed to retry conversion.
Hmm, so why can't private-to-shared conversion also exit to userspace with EAGAIN?
How would userspace/guest_memfd differentiate between speculative/transient refcounts and extra refcounts due to TDX unmap failures?
Quoted 29 lines
In the POC
https://lore.kernel.org/lkml/aE%[email protected],kvm_gmem_convert_should_proceed()just returns EFAULT (can be modified to EAGAIN) to userspace instead.Quoted 23 lines
Yes, it's more easier for shared pages to have speculative/transient refcounts.
Quoted 20 lines
Quoted 17 lines
Quoted 6 lines
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
If this becomes a thing for private memory (which it isn't yet), then couldn't we just change things at that point?
Is the only issue with TDX taking refcounts that it won't work with future code changes?
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 35 lines · Vishal Annapurve
Quoted 34 lines · Yan Zhao
Quoted 32 lines · Vishal Annapurve
Quoted 19 lines · Yan Zhao
Quoted 17 lines · Rick P
Quoted 1 line · Vishal Annapurve
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
I'm confused...
Quoted 11 lines
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Quoted 8 lines
Quoted 3 lines
This means the refcount could be increased for other reasons, and so guestmemfd shouldn't rely on refcounts for it's purposes? So, it is not a problem for other components handling the page elevate the refcount?
Besides that, in [3], when
kvm_gmem_convert_should_proceed()determines whether to convert to private, why is it allowed to just invokekvm_gmem_has_safe_refcount()without taking speculative/transient refcounts into account? Isn't it more easier for shared pages to have speculative/transient refcounts?These speculative refcounts are taken into account, in case of unsafe refcounts, conversion operation immediately exits to userspace with EAGAIN and userspace is supposed to retry conversion.
Quoted 6 lines
Quoted 2 lines
Hmm, so why can't private-to-shared conversion also exit to userspace with EAGAIN?
How would userspace/guest_memfd differentiate between speculative/transient refcounts and extra refcounts due to TDX unmap failures?
Hmm, it also can't differentiate between speculative/transient refcounts and extra refcounts on shared folios due to other reasons.
Quoted 30 lines
Quoted 30 lines
In the POC
https://lore.kernel.org/lkml/aE%[email protected],kvm_gmem_convert_should_proceed()just returns EFAULT (can be modified to EAGAIN) to userspace instead.Quoted 23 lines
Yes, it's more easier for shared pages to have speculative/transient refcounts.
Quoted 20 lines
Quoted 17 lines
Quoted 6 lines
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
If this becomes a thing for private memory (which it isn't yet), then couldn't we just change things at that point?
Is the only issue with TDX taking refcounts that it won't work with future code changes?
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 37 lines · Yan Zhao
Quoted 35 lines · Vishal Annapurve
Quoted 34 lines · Yan Zhao
Quoted 32 lines · Vishal Annapurve
Quoted 19 lines · Yan Zhao
Quoted 17 lines · Rick P
Quoted 1 line · Vishal Annapurve
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
I'm confused...
Quoted 11 lines
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Quoted 8 lines
Quoted 3 lines
This means the refcount could be increased for other reasons, and so guestmemfd shouldn't rely on refcounts for it's purposes? So, it is not a problem for other components handling the page elevate the refcount?
Besides that, in [3], when
kvm_gmem_convert_should_proceed()determines whether to convert to private, why is it allowed to just invokekvm_gmem_has_safe_refcount()without taking speculative/transient refcounts into account? Isn't it more easier for shared pages to have speculative/transient refcounts?These speculative refcounts are taken into account, in case of unsafe refcounts, conversion operation immediately exits to userspace with EAGAIN and userspace is supposed to retry conversion.
Quoted 9 lines
Quoted 6 lines
Quoted 2 lines
Hmm, so why can't private-to-shared conversion also exit to userspace with EAGAIN?
How would userspace/guest_memfd differentiate between speculative/transient refcounts and extra refcounts due to TDX unmap failures?
Hmm, it also can't differentiate between speculative/transient refcounts and extra refcounts on shared folios due to other reasons.
In case of shared memory ranges, userspace is effectively responsible for extra refcounts and can act towards removing them if not done already. If "extra" refcounts are taken care of then the only remaining scenario is speculative/transient refcounts.
But for private memory ranges, userspace is not responsible for any refcounts landing on them.
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 48 lines · Vishal Annapurve
Quoted 37 lines · Yan Zhao
Quoted 35 lines · Vishal Annapurve
Quoted 34 lines · Yan Zhao
Quoted 32 lines · Vishal Annapurve
Quoted 19 lines · Yan Zhao
Quoted 17 lines · Rick P
Quoted 1 line · Vishal Annapurve
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
I'm confused...
Quoted 11 lines
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Quoted 8 lines
Quoted 3 lines
This means the refcount could be increased for other reasons, and so guestmemfd shouldn't rely on refcounts for it's purposes? So, it is not a problem for other components handling the page elevate the refcount?
Besides that, in [3], when
kvm_gmem_convert_should_proceed()determines whether to convert to private, why is it allowed to just invokekvm_gmem_has_safe_refcount()without taking speculative/transient refcounts into account? Isn't it more easier for shared pages to have speculative/transient refcounts?These speculative refcounts are taken into account, in case of unsafe refcounts, conversion operation immediately exits to userspace with EAGAIN and userspace is supposed to retry conversion.
Quoted 9 lines
Quoted 6 lines
Quoted 2 lines
Hmm, so why can't private-to-shared conversion also exit to userspace with EAGAIN?
How would userspace/guest_memfd differentiate between speculative/transient refcounts and extra refcounts due to TDX unmap failures?
Hmm, it also can't differentiate between speculative/transient refcounts and extra refcounts on shared folios due to other reasons.
Quoted 7 lines
In case of shared memory ranges, userspace is effectively responsible for extra refcounts and can act towards removing them if not done already. If "extra" refcounts are taken care of then the only remaining scenario is speculative/transient refcounts.
But for private memory ranges, userspace is not responsible for any refcounts landing on them.
Ok. The similarities between the two are:
- userspace can't help on speculative/transient refcounts.
- userspace can't make conversion success with "extra" refcounts, whether held by user or by TDX.
But I think I get your point that EAGAIN is not the right code in case of "extra" refcounts held by TDX.
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
In reply to Edgecombe, Rick PQuoted 18 lines · Rick P
Quoted 1 line · Vishal Annapurve
Sorry I quoted Ackerley's response wrongly. Here is the correct reference [1].
I'm confused...
Quoted 11 lines
Speculative/transient refcounts came up a few times In the context of
guest_memfddiscussions, some examples include: pagetable walkers, page migration, speculative pagecache lookups, GUP-fast etc. David H can provide more context here as needed.Effectively some core-mm features that are present today or might land in the future can cause folio refcounts to be grabbed for short durations without actual access to underlying physical memory. These scenarios are unlikely to happen for private memory but can't be discounted completely.
Quoted 3 lines
This means the refcount could be increased for other reasons, and so guestmemfd shouldn't rely on refcounts for it's purposes? So, it is not a problem for other components handling the page elevate the refcount?
It's simpler to handle the transient refcounts as there are following options:
1) Wait for a small amount of time
2) Keep the folio refcounts frozen to zero at all times, which will effectively eliminate the scenario of transient refcounts.
3) Use raw memory without page structs - unmanaged by kernel.
Quoted 10 lines
Quoted 7 lines
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
If this becomes a thing for private memory (which it isn't yet), then couldn't we just change things at that point?
It would be great to avoid having to go through discussion again, if we have good reasons to handle it now.
Quoted 8 lines
Is the only issue with TDX taking refcounts that it won't work with future code changes?
Edgecombe, Rick P
maintainerRe: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 20 lines · Vishal Annapurve
Quoted 5 lines
This means the refcount could be increased for other reasons, and so guestmemfd
shouldn't rely on refcounts for it's purposes? So, it is not a problem for other
components handling the page elevate the refcount?It's simpler to handle the transient refcounts as there are following options:
1) Wait for a small amount of time
2) Keep the folio refcounts frozen to zero at all times, which will effectively eliminate the scenario of transient refcounts.
3) Use raw memory without page structs - unmanaged by kernel.Quoted 8 lines
Quoted 7 lines
Another reason to avoid relying on refcounts is to not block usage of raw physical memory unmanaged by kernel (without page structs) to back guest private memory as we had discussed previously. This will help simplify merge/split operations during conversions and help usecases like guest memory persistence [2] and non-confidential VMs.
Quoted 6 lines
Quoted 3 lines
If this becomes a thing for private memory (which it isn't yet), then couldn't
we just change things at that point?It would be great to avoid having to go through discussion again, if we have good reasons to handle it now.
I thought we already came to agreement on whether to spend time pre-designing for future things. This thread has gotten pretty long, can we stick to the current problems in an effort to close it?
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
In reply to Ackerley TngQuoted 7 lines · Ackerley Tng
Hi Yan,
While working on the 1G (aka HugeTLB) page support for
guest_memfdseries [1], we took into account conversion failures too. The steps are inkvm_gmem_convert_range(). (It might be easier to pull the entire series from GitHub [2] because the steps for conversion changed in two separate patches.)
...
Hi Ackerley,
Thanks for providing this branch.
I'm now trying to make TD huge pages working on this branch and would like to report to you errors I encountered during this process early.
1. symbol arch_get_align_mask() is not available when KVM is compiled as module. I currently workaround it as follows:
virt/kvm/guest_memfd.c +4 -2
@@ -102,8 +102,13 @@ static unsigned long kvm_gmem_get_align_mask(struct file *file,void *priv; inode =file_inode (file); -if (!kvm_gmem_has_custom_allocator (inode)) -return arch_get_align_mask (file, flags); +if (!kvm_gmem_has_custom_allocator (inode)) { + page_size =1 <<PAGE_SHIFT ; +return PAGE_MASK & (page_size -1 ); + }
2. Bug of Sleeping function called from invalid context
[ 193.523469] BUG: sleeping function called from invalid context at ./include/linux/sched/mm.h:325
[ 193.539885] in_atomic(): 1, irqs_disabled(): 0, non_block: 0, pid: 3332, name: guest_memfd_con
[ 193.556235] preempt_count: 1, expected: 0
[ 193.564518] RCU nest depth: 0, expected: 0
[ 193.572866] 3 locks held by guest_memfd_con/3332:
[ 193.581800] #0: ff16f8ec217e4438 (sb_writers#14){.+.+}-{0:0}, at: __x64_sys_fallocate+0x46/0x80
[ 193.598252] #1: ff16f8fbd85c8310 (mapping.invalidate_lock#4){++++}-{4:4}, at: kvm_gmem_fallocate+0x9e/0x310 [kvm]
[ 193.616706] #2: ff3189b5e4f65018 (&(kvm)->mmu_lock){++++}-{3:3}, at: kvm_gmem_invalidate_begin_and_zap+0x17f/0x260 [kvm]
[ 193.635790] Preemption disabled at:
[ 193.635793] [<ffffffffc0850c6f>] kvm_gmem_invalidate_begin_and_zap+0x17f/0x260 [kvm]This is because add_to_invalidated_kvms() invokes kzalloc() inside kvm->mmu_lock which is a kind of spinlock.
I workarounded it as follows.
static int kvm_gmem_invalidate_begin_and_zap(struct kvm_gmem *gmem,
pgoff_t start, pgoff_t end,
@@ -1261,13 +1268,13 @@ static int kvm_gmem_invalidate_begin_and_zap(struct kvm_gmem *gmem,
KVM_MMU_LOCK(kvm);
kvm_mmu_invalidate_begin(kvm);- if (invalidated_kvms) {
- ret = add_to_invalidated_kvms(invalidated_kvms, kvm);
- if (ret) {
- kvm_mmu_invalidate_end(kvm);
- goto out;
- }
- }
}
@@ -1523,12 +1530,14 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
}
out:
- list_for_each_entry_safe(entry, tmp, &invalidated_kvms, list) {
- kvm_gmem_do_invalidate_end(entry->kvm); - list_del(&entry->list); - kfree(entry);
- }
+ list_for_each_entry(gmem, gmem_list, entry)
+ kvm_gmem_do_invalidate_end(gmem->kvm);
filemap_invalidate_unlock(inode->i_mapping);
Will let you know more findings later.
Thanks
Yan
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 8 lines · Yan Zhao
Quoted 7 lines · Ackerley Tng
Hi Yan,
While working on the 1G (aka HugeTLB) page support for
guest_memfdseries [1], we took into account conversion failures too. The steps are inkvm_gmem_convert_range(). (It might be easier to pull the entire series from GitHub [2] because the steps for conversion changed in two separate patches.)
Quoted 5 lines
...
Hi Ackerley,
Thanks for providing this branch.
Here's the WIP branch [1], which I initially wasn't intending to make super public since it's not even RFC standard yet and I didn't want to add to the many guest_memfd in-flight series, but since you referred to it, [2] is a v2 of the WIP branch :)
[1] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2
This WIP branch has selftests that test 1G aka HugeTLB page support with TDX huge page EPT mappings [7]:
1. "KVM: selftests: TDX: Test conversion to private at different sizes". This uses the fact that TDX module will return error if the page is faulted into the guest at a different level from the accept level to check the level that the page was faulted in.
2. "KVM: selftests: Test TDs in private_mem_conversions_test". Updates private_mem_conversions_test for use with TDs. This test does multi-vCPU conversions and we use this to check for issues to do with conversion races.
3. "KVM: selftests: TDX: Test conversions when guest_memfd used for private and shared memory". Adds a selftest similar to/on top of guest_memfd_conversions_test that does conversions via MapGPA.
Full list of selftests I usually run from tools/testing/selftests/kvm:
+ ./guest_memfd_test
+ ./guest_memfd_conversions_test
+ ./guest_memfd_provide_hugetlb_cgroup_mount.sh ./guest_memfd_wrap_test_check_hugetlb_reporting.sh ./guest_memfd_test
+ ./guest_memfd_provide_hugetlb_cgroup_mount.sh ./guest_memfd_wrap_test_check_hugetlb_reporting.sh ./guest_memfd_conversions_test
+ ./guest_memfd_provide_hugetlb_cgroup_mount.sh ./guest_memfd_wrap_test_check_hugetlb_reporting.sh ./guest_memfd_hugetlb_reporting_test
+ ./x86/private_mem_conversions_test.sh
+ ./set_memory_region_test
+ ./x86/private_mem_kvm_exits_test
+ ./x86/tdx_vm_test
+ ./x86/tdx_upm_test
+ ./x86/tdx_shared_mem_test
+ ./x86/tdx_gmem_private_and_shared_test
As an overview for anyone who might be interested in this WIP branch:
1. I started with upstream's kvm/next
2. Applied TDX selftests series [3]
3. Applied guest_memfd mmap series [4]
4. Applied conversions (sub)series and HugeTLB (sub)series [5]
5. Added some fixes for 2 of the earlier series (as labeled in commit
message)
6. Updated guest_memfd conversions selftests to work with TDX
7. Applied 2M EPT series [6] with some hacks
8. Some patches to make guest_memfd mmap return huge-page-aligned userspace address
9. Selftests for guest_memfd conversion with TDX 2M EPT
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/T/
[5] https://lore.kernel.org/all/[email protected]/T/
[6] https://lore.kernel.org/all/Z%2FOMB7HNO%[email protected]/
[7] https://lore.kernel.org/all/[email protected]/
Quoted 11 lines
I'm now trying to make TD huge pages working on this branch and would like to report to you errors I encountered during this process early.
1. symbol
arch_get_align_mask()is not available when KVM is compiled as module. I currently workaround it as follows:virt/kvm/guest_memfd.c +0
-0@@ -102,8 +102,13 @@ static unsigned long kvm_gmem_get_align_mask(struct file *file,void *priv;
virt/kvm/guest_memfd.c static unsigned long kvm_gmem_get_align_mask(struct file *file, · line 110
Quoted 10 lines
virt/kvm/guest_memfd.c +4
-2inode =file_inode (file); -if (!kvm_gmem_has_custom_allocator (inode)) -return arch_get_align_mask (file, flags); +if (!kvm_gmem_has_custom_allocator (inode)) { + page_size =1 <<PAGE_SHIFT ; +return PAGE_MASK & (page_size -1 ); + }
Thanks, will fix in the next revision.
Quoted 39 lines
2. Bug of Sleeping function called from invalid context
[ 193.523469] BUG: sleeping function called from invalid context at ./include/linux/sched/mm.h:325 [ 193.539885] in_atomic(): 1, irqs_disabled(): 0, non_block: 0, pid: 3332, name: guest_memfd_con [ 193.556235] preempt_count: 1, expected: 0 [ 193.564518] RCU nest depth: 0, expected: 0 [ 193.572866] 3 locks held by guest_memfd_con/3332: [ 193.581800] #0: ff16f8ec217e4438 (sb_writers#14){.+.+}-{0:0}, at: __x64_sys_fallocate+0x46/0x80 [ 193.598252] #1: ff16f8fbd85c8310 (mapping.invalidate_lock#4){++++}-{4:4}, at: kvm_gmem_fallocate+0x9e/0x310 [kvm] [ 193.616706] #2: ff3189b5e4f65018 (&(kvm)->mmu_lock){++++}-{3:3}, at: kvm_gmem_invalidate_begin_and_zap+0x17f/0x260 [kvm] [ 193.635790] Preemption disabled at: [ 193.635793] [<ffffffffc0850c6f>] kvm_gmem_invalidate_begin_and_zap+0x17f/0x260 [kvm]This is because
add_to_invalidated_kvms()invokeskzalloc()insidekvm->mmu_lockwhich is a kind of spinlock.I workarounded it as follows.
static int kvm_gmem_invalidate_begin_and_zap(struct
kvm_gmem*gmem,
pgoff_tstart,pgoff_tend,virt/kvm/guest_memfd.c +0
-8@@ -1261,13 +1268,13 @@ static int kvm_gmem_invalidate_begin_and_zap(struct kvm_gmem *gmem,KVM_MMU_LOCK (kvm);kvm_mmu_invalidate_begin (kvm); -if (invalidated_kvms) { - ret =add_to_invalidated_kvms (invalidated_kvms, kvm); -if (ret) { -kvm_mmu_invalidate_end (kvm); - goto out; - } - } }@@ -1523,12 +1530,14 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len) } out: -list_for_each_entry_safe (entry, tmp, &invalidated_kvms, list) {
virt/kvm/guest_memfd.c static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len) · line 1538
Quoted 10 lines
virt/kvm/guest_memfd.c +2
-4-kvm_gmem_do_invalidate_end (entry->kvm); -list_del (&entry->list); -kfree (entry); - } +list_for_each_entry (gmem, gmem_list, entry) +kvm_gmem_do_invalidate_end (gmem->kvm);filemap_invalidate_unlock (inode->i_mapping);
I fixed this in WIP series v2 by grouping splitting with unmapping. Please see this commit [8], the commit message includes an explanation of what's done.
[8] https://github.com/googleprodkernel/linux-cc/commit/fd27635e5209b5e45a628d7fcf42a17a2b3c7e78
Quoted 4 lines
Will let you know more findings later.
Thanks
Yan
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 16 lines · Ackerley Tng
Quoted 8 lines · Yan Zhao
Quoted 7 lines · Ackerley Tng
Hi Yan,
While working on the 1G (aka HugeTLB) page support for
guest_memfdseries [1], we took into account conversion failures too. The steps are inkvm_gmem_convert_range(). (It might be easier to pull the entire series from GitHub [2] because the steps for conversion changed in two separate patches.)Quoted 5 lines
...
Hi Ackerley,
Thanks for providing this branch.
Quoted 7 lines
Here's the WIP branch [1], which I initially wasn't intending to make super public since it's not even RFC standard yet and I didn't want to add to the many
guest_memfdin-flight series, but since you referred to it, [2] is a v2 of the WIP branch :)[1] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2
Thanks. [2] works. TDX huge pages now has successfully been rebased on top of [2].
Quoted 40 lines
This WIP branch has selftests that test 1G aka HugeTLB page support with TDX huge page EPT mappings [7]:
1. "KVM: selftests: TDX: Test conversion to private at different sizes". This uses the fact that TDX module will return error if the page is faulted into the guest at a different level from the accept level to check the level that the page was faulted in.
2. "KVM: selftests: Test TDs inprivate_mem_conversions_test". Updatesprivate_mem_conversions_testfor use with TDs. This test does multi-vCPU conversions and we use this to check for issues to do with conversion races.
3. "KVM: selftests: TDX: Test conversions whenguest_memfdused for private and shared memory". Adds a selftest similar to/on top ofguest_memfd_conversions_testthat does conversions via MapGPA.Full list of selftests I usually run from
tools/testing/selftests/kvm:
+ ./guest_memfd_test
+ ./guest_memfd_conversions_test
+ ./guest_memfd_provide_hugetlb_cgroup_mount.sh ./guest_memfd_wrap_test_check_hugetlb_reporting.sh ./guest_memfd_test
+ ./guest_memfd_provide_hugetlb_cgroup_mount.sh ./guest_memfd_wrap_test_check_hugetlb_reporting.sh ./guest_memfd_conversions_test
+ ./guest_memfd_provide_hugetlb_cgroup_mount.sh ./guest_memfd_wrap_test_check_hugetlb_reporting.sh ./guest_memfd_hugetlb_reporting_test
+./x86/private_mem_conversions_test.sh
+ ./set_memory_region_test
+ ./x86/private_mem_kvm_exits_test
+ ./x86/tdx_vm_test
+ ./x86/tdx_upm_test
+ ./x86/tdx_shared_mem_test
+ ./x86/tdx_gmem_private_and_shared_testAs an overview for anyone who might be interested in this WIP branch:
1. I started with upstream's kvm/next 2. Applied TDX selftests series [3] 3. Applied guest_memfd mmap series [4] 4. Applied conversions (sub)series and HugeTLB (sub)series [5] 5. Added some fixes for 2 of the earlier series (as labeled in commit message) 6. Updated guest_memfd conversions selftests to work with TDX 7. Applied 2M EPT series [6] with some hacks 8. Some patches to make guest_memfd mmap return huge-page-aligned
Quoted 8 lines
userspace address
9. Selftests forguest_memfdconversion with TDX 2M EPT[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/T/
[5] https://lore.kernel.org/all/[email protected]/T/
[6] https://lore.kernel.org/all/Z%2FOMB7HNO%[email protected]/
[7] https://lore.kernel.org/all/[email protected]/
Thanks.
We noticed that it's not easy for TDX initial memory regions to use in-place conversion version of guest_memfd, because
- tdh_mem_page_add() requires simultaneous access to shared source memory and private target memory.
- shared-to-private in-place conversion first unmaps the shared memory and tests if any extra folio refcount is held before the conversion is allowed.
Therefore, though tdh_mem_page_add() actually supports in-place add, see [8], we can't store the initial content in the mmap-ed VA of the in-place conversion version of guest_memfd.
So, I modified QEMU to workaround this issue by adding an extra anonymous backend to hold source pages in shared memory, with the target private PFN allocated from guest_memfd with GUEST_MEMFD_FLAG_SUPPORT_SHARED set.
The goal is to test whether kvm_gmem_populate() works for TDX huge pages. This testing exposed a bug in kvm_gmem_populate(), which has been fixed in the following patch.
commit 5f33ed7ca26f00a61c611d2d1fbc001a7ecd8dca
Author: Yan Zhao <[email protected]> Date: Mon Jun 9 03:01:21 2025 -0700
Bug fix: Reduce max_order when GFN is not aligned
Fix the warning hit in kvm_gmem_populate().
"WARNING: CPU: 7 PID: 4421 at arch/x86/kvm/../../../virt/kvm/guest_memfd.c:
2496 kvm_gmem_populate+0x4a4/0x5b0"
The GFN passed to kvm_gmem_populate() may have an offset so it may not be aligned to folio order. In this case, reduce the max_order to decrease the mapping level.
virt/kvm/guest_memfd.c +2 -1
@@ -2493,7 +2493,8 @@ long kvm_gmem_populate(struct kvm *kvm, gfn_t start_gfn, void __user *src, long }folio_unlock (folio); -WARN_ON (!IS_ALIGNED (gfn,1 << max_order)); +while (!IS_ALIGNED (gfn,1 << max_order)) + max_order--; npages_to_populate =min (npages - i,1 << max_order); npages_to_populate = private_npages_to_populate(
[8] https://cdrdv2-public.intel.com/839195/intel-tdx-module-1.5-abi-spec-348551002.pdf
"In-Place Add: It is allowed to set the TD page HPA in R8 to the same address as the source page HPA in R9. In this case the source page is converted to be a TD private page".
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 84 lines · Yan Zhao
Quoted 16 lines · Ackerley Tng
Quoted 8 lines · Yan Zhao
Quoted 7 lines · Ackerley Tng
Hi Yan,
While working on the 1G (aka HugeTLB) page support for
guest_memfdseries [1], we took into account conversion failures too. The steps are inkvm_gmem_convert_range(). (It might be easier to pull the entire series from GitHub [2] because the steps for conversion changed in two separate patches.)Quoted 5 lines
...
Hi Ackerley,
Thanks for providing this branch.Quoted 7 lines
Here's the WIP branch [1], which I initially wasn't intending to make super public since it's not even RFC standard yet and I didn't want to add to the many
guest_memfdin-flight series, but since you referred to it, [2] is a v2 of the WIP branch :)[1] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2Thanks. [2] works. TDX huge pages now has successfully been rebased on top of [2].
Quoted 40 lines
This WIP branch has selftests that test 1G aka HugeTLB page support with TDX huge page EPT mappings [7]:
1. "KVM: selftests: TDX: Test conversion to private at different sizes". This uses the fact that TDX module will return error if the page is faulted into the guest at a different level from the accept level to check the level that the page was faulted in.
2. "KVM: selftests: Test TDs inprivate_mem_conversions_test". Updatesprivate_mem_conversions_testfor use with TDs. This test does multi-vCPU conversions and we use this to check for issues to do with conversion races.
3. "KVM: selftests: TDX: Test conversions whenguest_memfdused for private and shared memory". Adds a selftest similar to/on top ofguest_memfd_conversions_testthat does conversions via MapGPA.Full list of selftests I usually run from
tools/testing/selftests/kvm:
+ ./guest_memfd_test
+ ./guest_memfd_conversions_test
+ ./guest_memfd_provide_hugetlb_cgroup_mount.sh ./guest_memfd_wrap_test_check_hugetlb_reporting.sh ./guest_memfd_test
+ ./guest_memfd_provide_hugetlb_cgroup_mount.sh ./guest_memfd_wrap_test_check_hugetlb_reporting.sh ./guest_memfd_conversions_test
+ ./guest_memfd_provide_hugetlb_cgroup_mount.sh ./guest_memfd_wrap_test_check_hugetlb_reporting.sh ./guest_memfd_hugetlb_reporting_test
+./x86/private_mem_conversions_test.sh
+ ./set_memory_region_test
+ ./x86/private_mem_kvm_exits_test
+ ./x86/tdx_vm_test
+ ./x86/tdx_upm_test
+ ./x86/tdx_shared_mem_test
+ ./x86/tdx_gmem_private_and_shared_testAs an overview for anyone who might be interested in this WIP branch:
1. I started with upstream's kvm/next 2. Applied TDX selftests series [3] 3. Applied guest_memfd mmap series [4] 4. Applied conversions (sub)series and HugeTLB (sub)series [5] 5. Added some fixes for 2 of the earlier series (as labeled in commit message) 6. Updated guest_memfd conversions selftests to work with TDX 7. Applied 2M EPT series [6] with some hacks 8. Some patches to make guest_memfd mmap return huge-page-alignedQuoted 8 lines
userspace address
9. Selftests forguest_memfdconversion with TDX 2M EPT[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/T/
[5] https://lore.kernel.org/all/[email protected]/T/
[6] https://lore.kernel.org/all/Z%2FOMB7HNO%[email protected]/
[7] https://lore.kernel.org/all/[email protected]/Thanks.
We noticed that it's not easy for TDX initial memory regions to use in-place conversion version ofguest_memfd, because
-tdh_mem_page_add()requires simultaneous access to shared source memory and private target memory.
- shared-to-private in-place conversion first unmaps the shared memory and tests if any extra folio refcount is held before the conversion is allowed.
Quoted 7 lines
Therefore, though
tdh_mem_page_add()actually supports in-place add, see [8], we can't store the initial content in the mmap-ed VA of the in-place conversion version ofguest_memfd.So, I modified QEMU to workaround this issue by adding an extra anonymous backend to hold source pages in shared memory, with the target private PFN allocated from
guest_memfdwithGUEST_MEMFD_FLAG_SUPPORT_SHAREDset.
Yeah, this scheme of using different memory backing for initial payload makes sense to me.
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
In reply to Ackerley TngQuoted 16 lines · Ackerley Tng
Quoted 8 lines · Yan Zhao
Quoted 7 lines · Ackerley Tng
Hi Yan,
While working on the 1G (aka HugeTLB) page support for
guest_memfdseries [1], we took into account conversion failures too. The steps are inkvm_gmem_convert_range(). (It might be easier to pull the entire series from GitHub [2] because the steps for conversion changed in two separate patches.)Quoted 5 lines
...
Hi Ackerley,
Thanks for providing this branch.
Quoted 7 lines
Here's the WIP branch [1], which I initially wasn't intending to make super public since it's not even RFC standard yet and I didn't want to add to the many
guest_memfdin-flight series, but since you referred to it, [2] is a v2 of the WIP branch :)[1] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2
Hi Ackerley,
I'm working on preparing TDX huge page v2 based on [2] from you. The current decision is that the code base of TDX huge page v2 needs to include DPAMT and VM shutdown optimization as well.
So, we think kvm-x86/next is a good candidate for us.
(It is in repo https://github.com/kvm-x86/linux.git
commit 87198fb0208a (tag: kvm-x86-next-2025.07.15, kvm-x86/next) Merge branch 'vmx', which already includes code for VM shutdown optimization).
I still need to port DPAMT + gmem 1G + TDX huge page v2 on top it.
Therefore, I'm wondering if the rebase of [2] onto kvm-x86/next can be done from your side. A straightforward rebase is sufficient, with no need for any code modification. And it's better to be completed by the end of next week.
We thought it might be easier for you to do that (but depending on your bandwidth), allowing me to work on the DPAMT part for TDX huge page v2 in parallel.
However, if it's difficult for you, please feel free to let us know.
Thanks
Yan
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 36 lines · Yan Zhao
Quoted 16 lines · Ackerley Tng
Quoted 8 lines · Yan Zhao
Quoted 7 lines · Ackerley Tng
Hi Yan,
While working on the 1G (aka HugeTLB) page support for
guest_memfdseries [1], we took into account conversion failures too. The steps are inkvm_gmem_convert_range(). (It might be easier to pull the entire series from GitHub [2] because the steps for conversion changed in two separate patches.)Quoted 5 lines
...
Hi Ackerley,
Thanks for providing this branch.Quoted 7 lines
Here's the WIP branch [1], which I initially wasn't intending to make super public since it's not even RFC standard yet and I didn't want to add to the many
guest_memfdin-flight series, but since you referred to it, [2] is a v2 of the WIP branch :)[1] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2Hi Ackerley,
I'm working on preparing TDX huge page v2 based on [2] from you. The current decision is that the code base of TDX huge page v2 needs to include DPAMT and VM shutdown optimization as well.
So, we think kvm-x86/next is a good candidate for us.
(It is in repo https://github.com/kvm-x86/linux.git
commit87198fb0208a(tag: kvm-x86-next-2025.07.15, kvm-x86/next) Merge branch 'vmx', which already includes code for VM shutdown optimization).
I still need to port DPAMT + gmem 1G + TDX huge page v2 on top it.
Quoted 9 lines
Therefore, I'm wondering if the rebase of [2] onto kvm-x86/next can be done from your side. A straightforward rebase is sufficient, with no need for any code modification. And it's better to be completed by the end of next week.
We thought it might be easier for you to do that (but depending on your bandwidth), allowing me to work on the DPAMT part for TDX huge page v2 in parallel.
I'm a little tied up with some internal work, is it okay if, for the next RFC, you base the changes that you need to make for TDX huge page v2 and DPAMT on the base of [2]?
That will save both of us the rebasing. [2] was also based on (some other version of) kvm/next.
I think it's okay since the main goal is to show that it works. I'll let you know when I can get to a guest_memfd_HugeTLB v3 (and all the other patches that go into [2]).
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2
Quoted 4 lines
However, if it's difficult for you, please feel free to let us know.
Thanks
Yan
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 43 lines · Ackerley Tng
Quoted 41 lines · Yan Zhao
Quoted 16 lines · Ackerley Tng
Quoted 8 lines · Yan Zhao
Quoted 7 lines · Ackerley Tng
Hi Yan,
While working on the 1G (aka HugeTLB) page support for
guest_memfdseries [1], we took into account conversion failures too. The steps are inkvm_gmem_convert_range(). (It might be easier to pull the entire series from GitHub [2] because the steps for conversion changed in two separate patches.)Quoted 5 lines
...
Hi Ackerley,
Thanks for providing this branch.Quoted 7 lines
Here's the WIP branch [1], which I initially wasn't intending to make super public since it's not even RFC standard yet and I didn't want to add to the many
guest_memfdin-flight series, but since you referred to it, [2] is a v2 of the WIP branch :)[1] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2Hi Ackerley,
I'm working on preparing TDX huge page v2 based on [2] from you. The current decision is that the code base of TDX huge page v2 needs to include DPAMT and VM shutdown optimization as well.
So, we think kvm-x86/next is a good candidate for us.
(It is in repo https://github.com/kvm-x86/linux.git
commit87198fb0208a(tag: kvm-x86-next-2025.07.15, kvm-x86/next) Merge branch 'vmx', which already includes code for VM shutdown optimization).
I still need to port DPAMT + gmem 1G + TDX huge page v2 on top it.Therefore, I'm wondering if the rebase of [2] onto kvm-x86/next can be done from your side. A straightforward rebase is sufficient, with no need for any code modification. And it's better to be completed by the end of next week.
Quoted 6 lines
Quoted 4 lines
We thought it might be easier for you to do that (but depending on your bandwidth), allowing me to work on the DPAMT part for TDX huge page v2 in parallel.
I'm a little tied up with some internal work, is it okay if, for the
No problem.
Quoted 9 lines
next RFC, you base the changes that you need to make for TDX huge page v2 and DPAMT on the base of [2]?
That will save both of us the rebasing. [2] was also based on (some other version of) kvm/next.
I think it's okay since the main goal is to show that it works. I'll let you know when I can get to a
guest_memfd_HugeTLBv3 (and all the other patches that go into [2]).
Hmm, the upstream practice is to post code based on latest version, and there're lots TDX relates fixes in latest kvm-x86/next.
Quoted 6 lines
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2
Quoted 4 lines
However, if it's difficult for you, please feel free to let us know.
Thanks
Yan
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 55 lines · Yan Zhao
Quoted 43 lines · Ackerley Tng
Quoted 41 lines · Yan Zhao
Quoted 16 lines · Ackerley Tng
Quoted 8 lines · Yan Zhao
Quoted 7 lines · Ackerley Tng
Hi Yan,
While working on the 1G (aka HugeTLB) page support for
guest_memfdseries [1], we took into account conversion failures too. The steps are inkvm_gmem_convert_range(). (It might be easier to pull the entire series from GitHub [2] because the steps for conversion changed in two separate patches.)Quoted 5 lines
...
Hi Ackerley,
Thanks for providing this branch.Quoted 7 lines
Here's the WIP branch [1], which I initially wasn't intending to make super public since it's not even RFC standard yet and I didn't want to add to the many
guest_memfdin-flight series, but since you referred to it, [2] is a v2 of the WIP branch :)[1] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2Hi Ackerley,
I'm working on preparing TDX huge page v2 based on [2] from you. The current decision is that the code base of TDX huge page v2 needs to include DPAMT and VM shutdown optimization as well.
So, we think kvm-x86/next is a good candidate for us.
(It is in repo https://github.com/kvm-x86/linux.git
commit87198fb0208a(tag: kvm-x86-next-2025.07.15, kvm-x86/next) Merge branch 'vmx', which already includes code for VM shutdown optimization).
I still need to port DPAMT + gmem 1G + TDX huge page v2 on top it.Therefore, I'm wondering if the rebase of [2] onto kvm-x86/next can be done from your side. A straightforward rebase is sufficient, with no need for any code modification. And it's better to be completed by the end of next week.
Quoted 6 lines
Quoted 4 lines
We thought it might be easier for you to do that (but depending on your bandwidth), allowing me to work on the DPAMT part for TDX huge page v2 in parallel.
I'm a little tied up with some internal work, is it okay if, for the
No problem.
Quoted 2 lines
next RFC, you base the changes that you need to make for TDX huge page v2 and DPAMT on the base of [2]?
Quoted 9 lines
Quoted 6 lines
That will save both of us the rebasing. [2] was also based on (some other version of) kvm/next.
I think it's okay since the main goal is to show that it works. I'll let you know when I can get to a
guest_memfd_HugeTLBv3 (and all the other patches that go into [2]).Hmm, the upstream practice is to post code based on latest version, and there're lots TDX relates fixes in latest kvm-x86/next.
Yup I understand.
For guest_memfd//HugeTLB I'm still waiting for guest_memfd//mmap (managed by Fuad) to settle, and there are plenty of comments for the guest_memfd//conversion component to iron out still, so the full update to v3 will take longer than I think you want to wait.
I'd say for RFCs it's okay to post patch series based on some snapshot, since there are so many series in flight?
To unblock you, if posting based on a snapshot is really not okay, here are some other options I can think of:
a. Use [2] and posting a link to a WIP tree, similar to how [2] was
done
b. Use some placeholder patches, assuming some interfaces to
guest_memfd//HugeTLB, like how the first few patches in this series assumes some interfaces of guest_memfd with THP support, and post a series based on assumed interfaces
Please let me know if one of those options allow you to proceed, thanks!
Quoted 6 lines
Quoted 6 lines
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2
Quoted 4 lines
However, if it's difficult for you, please feel free to let us know.
Thanks
Yan
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 80 lines · Ackerley Tng
Quoted 55 lines · Yan Zhao
Quoted 43 lines · Ackerley Tng
Quoted 41 lines · Yan Zhao
Quoted 16 lines · Ackerley Tng
Quoted 8 lines · Yan Zhao
Quoted 7 lines · Ackerley Tng
Hi Yan,
While working on the 1G (aka HugeTLB) page support for
guest_memfdseries [1], we took into account conversion failures too. The steps are inkvm_gmem_convert_range(). (It might be easier to pull the entire series from GitHub [2] because the steps for conversion changed in two separate patches.)Quoted 5 lines
...
Hi Ackerley,
Thanks for providing this branch.Quoted 7 lines
Here's the WIP branch [1], which I initially wasn't intending to make super public since it's not even RFC standard yet and I didn't want to add to the many
guest_memfdin-flight series, but since you referred to it, [2] is a v2 of the WIP branch :)[1] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2Hi Ackerley,
I'm working on preparing TDX huge page v2 based on [2] from you. The current decision is that the code base of TDX huge page v2 needs to include DPAMT and VM shutdown optimization as well.
So, we think kvm-x86/next is a good candidate for us.
(It is in repo https://github.com/kvm-x86/linux.git
commit87198fb0208a(tag: kvm-x86-next-2025.07.15, kvm-x86/next) Merge branch 'vmx', which already includes code for VM shutdown optimization).
I still need to port DPAMT + gmem 1G + TDX huge page v2 on top it.Therefore, I'm wondering if the rebase of [2] onto kvm-x86/next can be done from your side. A straightforward rebase is sufficient, with no need for any code modification. And it's better to be completed by the end of next week.
Quoted 6 lines
Quoted 4 lines
We thought it might be easier for you to do that (but depending on your bandwidth), allowing me to work on the DPAMT part for TDX huge page v2 in parallel.
I'm a little tied up with some internal work, is it okay if, for the
No problem.
Quoted 2 lines
next RFC, you base the changes that you need to make for TDX huge page v2 and DPAMT on the base of [2]?
Quoted 9 lines
Quoted 6 lines
That will save both of us the rebasing. [2] was also based on (some other version of) kvm/next.
I think it's okay since the main goal is to show that it works. I'll let you know when I can get to a
guest_memfd_HugeTLBv3 (and all the other patches that go into [2]).Hmm, the upstream practice is to post code based on latest version, and there're lots TDX relates fixes in latest kvm-x86/next.
Yup I understand.
For guest_memfd//HugeTLB I'm still waiting for guest_memfd//mmap (managed by Fuad) to settle, and there are plenty of comments for the guest_memfd//conversion component to iron out still, so the full update to v3 will take longer than I think you want to wait.
I'd say for RFCs it's okay to post patch series based on some snapshot, since there are so many series in flight?
To unblock you, if posting based on a snapshot is really not okay, here are some other options I can think of:
Quoted 8 lines
a. Use [2] and posting a link to a WIP tree, similar to how [2] was
done
b. Use some placeholder patches, assuming some interfaces to
guest_memfd//HugeTLB, like how the first few patches in this series assumes some interfaces ofguest_memfdwith THP support, and post a series based on assumed interfacesPlease let me know if one of those options allow you to proceed, thanks!
Do you see any issues with directly rebasing [2] onto 6.16.0-rc6?
We currently prefer this approach. We have tested [2] for some time, and TDX huge page series doesn't rely on the implementation details of guest_memfd.
It's ok if you are currently occupied by Google's internal tasks. No worries.
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2
Quoted 4 lines
However, if it's difficult for you, please feel free to let us know.
Thanks
Yan
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 88 lines · Yan Zhao
Quoted 87 lines · Ackerley Tng
Quoted 55 lines · Yan Zhao
Quoted 43 lines · Ackerley Tng
Quoted 41 lines · Yan Zhao
Quoted 16 lines · Ackerley Tng
Quoted 8 lines · Yan Zhao
Quoted 7 lines · Ackerley Tng
Hi Yan,
While working on the 1G (aka HugeTLB) page support for
guest_memfdseries [1], we took into account conversion failures too. The steps are inkvm_gmem_convert_range(). (It might be easier to pull the entire series from GitHub [2] because the steps for conversion changed in two separate patches.)Quoted 5 lines
...
Hi Ackerley,
Thanks for providing this branch.Quoted 7 lines
Here's the WIP branch [1], which I initially wasn't intending to make super public since it's not even RFC standard yet and I didn't want to add to the many
guest_memfdin-flight series, but since you referred to it, [2] is a v2 of the WIP branch :)[1] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2Hi Ackerley,
I'm working on preparing TDX huge page v2 based on [2] from you. The current decision is that the code base of TDX huge page v2 needs to include DPAMT and VM shutdown optimization as well.
So, we think kvm-x86/next is a good candidate for us.
(It is in repo https://github.com/kvm-x86/linux.git
commit87198fb0208a(tag: kvm-x86-next-2025.07.15, kvm-x86/next) Merge branch 'vmx', which already includes code for VM shutdown optimization).
I still need to port DPAMT + gmem 1G + TDX huge page v2 on top it.Therefore, I'm wondering if the rebase of [2] onto kvm-x86/next can be done from your side. A straightforward rebase is sufficient, with no need for any code modification. And it's better to be completed by the end of next week.
Quoted 6 lines
Quoted 4 lines
We thought it might be easier for you to do that (but depending on your bandwidth), allowing me to work on the DPAMT part for TDX huge page v2 in parallel.
I'm a little tied up with some internal work, is it okay if, for the
No problem.
Quoted 2 lines
next RFC, you base the changes that you need to make for TDX huge page v2 and DPAMT on the base of [2]?
Quoted 9 lines
Quoted 6 lines
That will save both of us the rebasing. [2] was also based on (some other version of) kvm/next.
I think it's okay since the main goal is to show that it works. I'll let you know when I can get to a
guest_memfd_HugeTLBv3 (and all the other patches that go into [2]).Hmm, the upstream practice is to post code based on latest version, and there're lots TDX relates fixes in latest kvm-x86/next.
Yup I understand.
For guest_memfd//HugeTLB I'm still waiting for guest_memfd//mmap (managed by Fuad) to settle, and there are plenty of comments for the guest_memfd//conversion component to iron out still, so the full update to v3 will take longer than I think you want to wait.
I'd say for RFCs it's okay to post patch series based on some snapshot, since there are so many series in flight?
To unblock you, if posting based on a snapshot is really not okay, here are some other options I can think of:
a. Use [2] and posting a link to a WIP tree, similar to how [2] was
done
b. Use some placeholder patches, assuming some interfaces to
guest_memfd//HugeTLB, like how the first few patches in this series assumes some interfaces ofguest_memfdwith THP support, and post a series based on assumed interfaces
Quoted 3 lines
Quoted 1 line
Please let me know if one of those options allow you to proceed, thanks!
Do you see any issues with directly rebasing [2] onto 6.16.0-rc6?
Nope I think that should be fine. Thanks for checking!
Quoted 11 lines
We currently prefer this approach. We have tested [2] for some time, and TDX huge page series doesn't rely on the implementation details of
guest_memfd.It's ok if you are currently occupied by Google's internal tasks. No worries.
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept-v2
Quoted 4 lines
However, if it's difficult for you, please feel free to let us know.
Thanks
Yan
Re: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
In reply to Yan ZhaoQuoted 23 lines · Yan Zhao
Quoted 3 lines
<snip>
Very likely because these operations simply don't fail.
I think they are intentionally designed to be no-fail.
e.g. in
__iopt_area_unfill_domain(), no-fail is achieved by using a small backup buffer allocated on stack in case ofkmalloc()failure.Quoted 6 lines
Quoted 3 lines
That's why we rely on increasing folio ref count to reflect failure, which are due to unexpected SEAMCALL errors.
TDX stack is adding a scenario where invalidation can fail, a cleaner solution would be to propagate the result as an invalidation failure.
Not sure if linux kernel accepts unmap failure.
Quoted 2 lines
Another option is to notify
guest_memfdout of band to convey the ranges that failed invalidation.Yes, this might be better. Something similar like holding folio ref count to let
guest_memfdknow that a certain PFN cannot be re-assigned.
Quoted 7 lines
Quoted 3 lines
With in-place conversion supported, even if the refcount is raised for such pages, they can still get used by the host if the
guest_memfdis unaware that the invalidation failed.I thought
guest_memfdshould check if folio ref count is 0 (or a base count) before conversion, splitting or re-assignment. Otherwise, why do you care if TDX holds the ref count? :)
IIUC the question here is how we should handle failures in unmapping of private memory, which should be a rare occurrence.
I think there are two options here
1. Fail on unmapping *private* memory
2. Don't fail on unmapping *private* memory, instead tell the owner of the memory that this memory is never to be used again.
I think option 1 is better because it is more direct and provides timely feedback to the caller when the issue happens. There is also room to provide even more context about the address of the failure here.
It does seem like generally, unmapping memory does not support failing, but I think that is for shared memory (even in KVM MMU notifiers). Would it be possible to establish a new contract that for private pages, unmapping can fail?
The kernel/KVM-internal functions for unmapping GFNs can be modified to return error when unmapping private memory. Specifically, when KVM_FILTER_PRIVATE [1] is set, then the unmapping function can return an error and if not then the caller should not expect failures.
IIUC the only places where private memory is unmapped now is via guest_memfd's truncate and (future) convert operations, so guest_memfd can handle those failures or return failure to userspace.
Option 2 is possible too - but seems a little awkward. For conversion the general steps are to (a) unmap pages from either host, guest or both page tables (b) change shareability status in guest_memfd. It seems awkward to first let step (a) pass even though there was an error, and then proceed to (b) only to check somewhere (via refcount or otherwise) that there was an issue and the conversion needs to fail.
Currently for private to shared conversions, (will be posting this 1g page support series (with conversions) soon), I check refcounts == safe refcount for shared to private conversions before permitting conversions (error returned to userspace on failure).
For private to shared conversions, there is no check. At conversion time, when splitting pages, I just spin in the kernel waiting for any speculative refcounts to drop to go away. The refcount check at conversion time is currently purely to ensure a safe merge process.
It is possible to check all the refcounts of private pages (split or huge page) in the requested conversion range to handle unmapping failures, but that seems expensive to do for every conversion, for possibly many 4K pages, just to find a rare error case.
Also, if we do this refcount check to find the error, there wouldn't be any way to tell if it were an error or if it was a speculative refcount, so guest_memfd would just have to return -EAGAIN for private to shared conversions. This would make conversions complicated to handle in userspace, since the userspace VMM doesn't know whether it should retry (for speculative refcounts) or it should give up because of the unmapping error. Returning a different error on unmapping failure would allow userspace to handle the two cases differently.
Regarding Option 2, another way to indicate an error could be to mark the page as poisoned, but then again that would overlap/shadow true memory poisoning.
In summary, I think Option 1 is best, which is that we return error within the kernel, and the caller (for now only guest_memfd unmaps private memory) should handle the error.
Quoted 64 lines
Quoted 64 lines
Quoted 64 lines
Quoted 33 lines
Quoted 33 lines
Currently,
guest_memfdcan rely on page ref count to avoid re-assigning a PFN that fails to be unmapped.[1] https://lore.kernel.org/all/[email protected]/
Quoted 24 lines
Quoted 11 lines
Quoted 7 lines
Any
guest_memfdrange updates will result in invalidations/updates of userspace, guest, IOMMU or any other page tables referring toguest_memfdbacked pfns. This story will become clearer once the support for PFN range allocator for backingguest_memfdstarts getting discussed.Ok. It is indeed unclear right now to support such kind of memory.
Up to now, we don't anticipate TDX will allow any mapping of
VM_PFNMAPmemory into private EPT until TDX connect.There is a plan to use
VM_PFNMAPmemory for all ofguest_memfdshared/private ranges orthogonal to TDX connect usecase. With TDX connect/Sev TIO, major difference would be thatguest_memfdprivate ranges will be mapped into IOMMU page tables.Irrespective of whether/when
VM_PFNMAPmemory support lands, there have been discussions on not using page structs for private memory ranges altogether [1] even with hugetlb allocator, which will simplify seamless merge/split story for private hugepages to support memory conversion. So I think the general direction we should head towards is not relying on refcounts forguest_memfdprivate ranges and/or page structs altogether.Quoted 8 lines
Quoted 3 lines
It's fine to use PFN, but I wonder if there're counterparts of struct page to keep all necessary info.
Story will become clearer once VM_PFNMAP'd memory support starts getting discussed. In case of
guest_memfd, there is flexibility to store metadata for physical ranges withinguest_memfdjust like shareability tracking.Ok.
Quoted 21 lines
Quoted 20 lines
Quoted 4 lines
I think the series [2] to work better with PFNMAP'd physical memory in KVM is in the very right direction of not assuming page struct backed memory ranges for
guest_memfdas well.Note: Currently,
VM_PFNMAPis usually used together with flagVM_IO. in KVMhva_to_pfn_remapped()only applies to "vma->vm_flags& (VM_IO|VM_PFNMAP)".Quoted 12 lines
[1] https://lore.kernel.org/all/CAGtprH8akKUF=8+RkX_QMjp35C0bU1zxGi4v1Zm5AWCw=8V8AQ@mail.gmail.com/
[2] https://lore.kernel.org/linux-arm-kernel/[email protected]/Quoted 2 lines
And even in that scenario, the memory is only for private MMIO, so the backend driver is VFIO pci driver rather than
guest_memfd.Not necessary. As I mentioned above
guest_memfdranges will be backed byVM_PFNMAPmemory.Quoted 3 lines
Quoted 3 lines
[1] https://elixir.bootlin.com/linux/v6.14.5/source/mm/memory.c#L6543
Edgecombe, Rick P
maintainerRe: [RFC PATCH 08/21] KVM: TDX: Increase/decrease folio ref for huge pages
Quoted 19 lines · Ackerley Tng
IIUC the question here is how we should handle failures in unmapping of private memory, which should be a rare occurrence.
I think there are two options here
1. Fail on unmapping *private* memory
2. Don't fail on unmapping *private* memory, instead tell the owner of the memory that this memory is never to be used again.
I think option 1 is better because it is more direct and provides timely feedback to the caller when the issue happens. There is also room to provide even more context about the address of the failure here.
It does seem like generally, unmapping memory does not support failing, but I think that is for shared memory (even in KVM MMU notifiers). Would it be possible to establish a new contract that for private pages, unmapping can fail?
Quoted 8 lines
The
kernel/KVM-internalfunctions for unmapping GFNs can be modified to return error when unmapping private memory. Specifically, whenKVM_FILTER_PRIVATE[1] is set, then the unmapping function can return an error and if not then the caller should not expect failures.IIUC the only places where private memory is unmapped now is via guest_memfd's truncate and (future) convert operations, so
guest_memfdcan handle those failures or return failure to userspace.
1. Private->shared memory conversion
2. Memslot deletion
3. kvm_gmem_invalidate_begin() callers
Quoted 32 lines
Option 2 is possible too - but seems a little awkward. For conversion the general steps are to (a) unmap pages from either host, guest or both page tables (b) change shareability status in
guest_memfd. It seems awkward to first let step (a) pass even though there was an error, and then proceed to (b) only to check somewhere (via refcount or otherwise) that there was an issue and the conversion needs to fail.Currently for private to shared conversions, (will be posting this 1g page support series (with conversions) soon), I check refcounts == safe refcount for shared to private conversions before permitting conversions (error returned to userspace on failure).
For private to shared conversions, there is no check. At conversion time, when splitting pages, I just spin in the kernel waiting for any speculative refcounts to drop to go away. The refcount check at conversion time is currently purely to ensure a safe merge process.
It is possible to check all the refcounts of private pages (split or huge page) in the requested conversion range to handle unmapping failures, but that seems expensive to do for every conversion, for possibly many 4K pages, just to find a rare error case.
Also, if we do this refcount check to find the error, there wouldn't be any way to tell if it were an error or if it was a speculative refcount, so
guest_memfdwould just have to return-EAGAINfor private to shared conversions. This would make conversions complicated to handle in userspace, since the userspace VMM doesn't know whether it should retry (for speculative refcounts) or it should give up because of the unmapping error. Returning a different error on unmapping failure would allow userspace to handle the two cases differently.
Quoted 7 lines
Regarding Option 2, another way to indicate an error could be to mark the page as poisoned, but then again that would overlap/shadow true memory poisoning.
In summary, I think Option 1 is best, which is that we return error within the kernel, and the caller (for now only
guest_memfdunmaps private memory) should handle the error.
When we get to huge pages we will have two error conditions on the KVM side:
1. Fail to split
2. A TDX module error
For TDX module errors, today we are essentially talking about bugs. The handling in the case of TDX module bug should be to bug the VM and to prevent the memory from being freed to the kernel. In which case the unmapping sort of succeeded, albeit destructively.
So I'm not sure if userspace needs to know about the TDX module bugs (they are going to find out anyway on the next KVM ioctl). But if we plumbed the error code all the way through to guestmemfd, then I guess why not tell them.
On whether we should go to the trouble, could another option be to expose a guestmemfd function that allows for "poisoning" the memory, and have the TDX bug paths call it. This way guestmemfd could know specifically about unrecoverable errors. For splitting failures, we can return an error to guestmemfd without plumbing the error code all the way through.
Perhaps it might be worth doing a quick POC to see how bad plumbing the error code all the way looks.
RFC PATCH 9/21 KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
In reply to Yan ZhaoAllow TDX's .private_max_mapping_level hook to return 2MB after the TD is RUNNABLE, enabling KVM to map TDX private pages at the 2MB level. Remove TODOs and adjust KVM_BUG_ON()s accordingly.
Note: Instead of placing this patch at the tail of the series, it's positioned here to show the code changes for basic mapping of private huge pages (i.e., transitioning from non-present to present).
However, since this patch also allows KVM to trigger the merging of small entries into a huge leaf entry or the splitting of a huge leaf entry into small entries, errors are expected if any of these operations are triggered due to the current lack of splitting/merging support.
--- arch/x86/kvm/vmx/tdx.c | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-)
arch/x86/kvm/vmx/tdx.c +7 -9
@@ -1561,10 +1561,6 @@ int tdx_sept_set_private_spte(struct kvm *kvm, gfn_t gfn,struct kvm_tdx *kvm_tdx =to_kvm_tdx (kvm);struct page *page =pfn_to_page (pfn); -/* TODO: handle large pages. */ -if (KVM_BUG_ON (level !=PG_LEVEL_4K , kvm)) -return -EINVAL ; -/* * Because guest_memfd doesn't support page migration with * a_ops->migrate_folio (yet), no callback is triggered for KVM on page
@@ -1612,8 +1608,7 @@ static int tdx_sept_drop_private_spte(struct kvm *kvm, gfn_t gfn,gpa_t gpa =gfn_to_gpa (gfn);u64 err, entry, level_state; -/* TODO: handle large pages. */ -if (KVM_BUG_ON (level !=PG_LEVEL_4K , kvm)) +if (KVM_BUG_ON (kvm_tdx->state !=TD_STATE_RUNNABLE && level !=PG_LEVEL_4K , kvm))return -EINVAL ;if (KVM_BUG_ON (!is_hkid_assigned (kvm_tdx), kvm))
@@ -1714,8 +1709,8 @@ static int tdx_sept_zap_private_spte(struct kvm *kvm, gfn_t gfn,gpa_t gpa =gfn_to_gpa (gfn) &KVM_HPAGE_MASK (level);u64 err, entry, level_state; -/* For now large page isn't supported yet. */ -WARN_ON_ONCE (level !=PG_LEVEL_4K ); +/* Before TD runnable, large page is not supported */ +WARN_ON_ONCE (kvm_tdx->state !=TD_STATE_RUNNABLE && level !=PG_LEVEL_4K ); err =tdh_mem_range_block (&kvm_tdx->td, gpa, tdx_level, &entry, &level_state);
@@ -1817,6 +1812,9 @@ int tdx_sept_remove_private_spte(struct kvm *kvm, gfn_t gfn,struct page *page =pfn_to_page (pfn);int ret; +WARN_ON_ONCE (folio_page_idx (page_folio (page), page) +KVM_PAGES_PER_HPAGE (level) > +folio_nr_pages (page_folio (page))); +/* * HKID is released after all private pages have been removed, and set * before any might be populated. Warn if zapping is attempted when
@@ -3265,7 +3263,7 @@ int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn)if (unlikely (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE ))return PG_LEVEL_4K ; -return PG_LEVEL_4K ; +return PG_LEVEL_2M ; }static int tdx_online_cpu (unsigned int cpu)
Signature · 1 line
2.43.2
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 36 lines · Yan Zhao
Allow TDX's .private_max_mapping_level hook to return 2MB after the TD is RUNNABLE, enabling KVM to map TDX private pages at the 2MB level. Remove TODOs and adjust KVM_BUG_ON()s accordingly.
Note: Instead of placing this patch at the tail of the series, it's positioned here to show the code changes for basic mapping of private huge pages (i.e., transitioning from non-present to present).
However, since this patch also allows KVM to trigger the merging of small entries into a huge leaf entry or the splitting of a huge leaf entry into small entries, errors are expected if any of these operations are triggered due to the current lack of splitting/merging support.
Signed-off-by Xiaoyao Li <[email protected]>Signed-off-by Isaku Yamahata <[email protected]>Signed-off-by Yan Zhao <[email protected]>--- arch/x86/kvm/vmx/tdx.c | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-)arch/x86/kvm/vmx/tdx.c +0
-4@@ -1561,10 +1561,6 @@ int tdx_sept_set_private_spte(struct kvm *kvm, gfn_t gfn,struct kvm_tdx *kvm_tdx =to_kvm_tdx (kvm);struct page *page =pfn_to_page (pfn); -/* TODO: handle large pages. */ -if (KVM_BUG_ON (level !=PG_LEVEL_4K , kvm)) -return -EINVAL ; -/* * Because guest_memfd doesn't support page migration with * a_ops->migrate_folio (yet), no callback is triggered for KVM on page
arch/x86/kvm/vmx/tdx.c static int tdx_sept_drop_private_spte(struct kvm *kvm, gfn_t gfn, · line 1611
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +1
-2@@ -1612,8 +1608,7 @@ static int tdx_sept_drop_private_spte(struct kvm *kvm, gfn_t gfn,gpa_t gpa =gfn_to_gpa (gfn);u64 err, entry, level_state; -/* TODO: handle large pages. */ -if (KVM_BUG_ON (level !=PG_LEVEL_4K , kvm)) +if (KVM_BUG_ON (kvm_tdx->state !=TD_STATE_RUNNABLE && level !=PG_LEVEL_4K , kvm))
It's not clear why some of these warnings are here and some are in patch 4.
Quoted 25 lines
arch/x86/kvm/vmx/tdx.c +5
-2return -EINVAL ;if (KVM_BUG_ON (!is_hkid_assigned (kvm_tdx), kvm))@@ -1714,8 +1709,8 @@ static int tdx_sept_zap_private_spte(struct kvm *kvm, gfn_t gfn,gpa_t gpa =gfn_to_gpa (gfn) &KVM_HPAGE_MASK (level);u64 err, entry, level_state; -/* For now large page isn't supported yet. */ -WARN_ON_ONCE (level !=PG_LEVEL_4K ); +/* Before TD runnable, large page is not supported */ +WARN_ON_ONCE (kvm_tdx->state !=TD_STATE_RUNNABLE && level !=PG_LEVEL_4K ); err =tdh_mem_range_block (&kvm_tdx->td, gpa, tdx_level, &entry, &level_state);@@ -1817,6 +1812,9 @@ int tdx_sept_remove_private_spte(struct kvm *kvm, gfn_t gfn,struct page *page =pfn_to_page (pfn);int ret; +WARN_ON_ONCE (folio_page_idx (page_folio (page), page) +KVM_PAGES_PER_HPAGE (level) > +folio_nr_pages (page_folio (page))); +/* * HKID is released after all private pages have been removed, and set * before any might be populated. Warn if zapping is attempted when
arch/x86/kvm/vmx/tdx.c int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) · line 3266
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +1
-1@@ -3265,7 +3263,7 @@ int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn)if (unlikely (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE ))return PG_LEVEL_4K ; -return PG_LEVEL_4K ; +return PG_LEVEL_2M ;
Maybe combine this with patch 4, or split them into sensible categories.
Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +0
-0}static int tdx_online_cpu (unsigned int cpu)
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 8 lines · Rick P
arch/x86/kvm/vmx/tdx.c int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) · line 3266
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +0
-0@@ -3265,7 +3263,7 @@ int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) if (unlikely(to_kvm_tdx(kvm)->state != TD_STATE_RUNNABLE)) return PG_LEVEL_4K;arch/x86/kvm/vmx/tdx.c +1
-1-return PG_LEVEL_4K ; +return PG_LEVEL_2M ;Maybe combine this with patch 4, or split them into sensible categories.
How about merge with patch 12
[RFC PATCH 12/21] KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
instead?
Per patch 12, the fault due to TDH.MEM.PAGE.ACCPT contains fault level info, so KVM should just return that. But seems we are still returning PG_LEVEL_2M if no such info is provided (IIUC):
int tdx_gmem_private_max_mapping_level(struct kvm_vcpu *vcpu, kvm_pfn_t pfn,
gfn_t gfn)
{
+ struct vcpu_tdx *tdx = to_tdx(vcpu);
+
if (unlikely(to_kvm_tdx(vcpu->kvm)->state != TD_STATE_RUNNABLE))
return PG_LEVEL_4K;
+ if (gfn >= tdx->violation_gfn_start && gfn < tdx->violation_gfn_end)
+ return tdx->violation_request_level;
+
return PG_LEVEL_2M;
}
So why not returning PT_LEVEL_4K at the end?
I am asking because below text mentioned in the coverletter:
A rare case that could lead to splitting in the fault path is when a TD is configured to receive #VE and accesses memory before the ACCEPT operation. By the time a vCPU accesses a private GFN, due to the lack of any guest preferred level, KVM could create a mapping at 2MB level. If the TD then only performs the ACCEPT operation at 4KB level, splitting in the fault path will be triggered. However, this is not regarded as a typical use case, as usually TD always accepts pages in the order from 1GB->2MB->4KB. The worst outcome to ignore the resulting splitting request is an endless EPT violation. This would not happen for a Linux guest, which does not expect any #VE.
Changing to return PT_LEVEL_4K should avoid this problem. It doesn't hurt normal cases either, since guest will always do ACCEPT (which contains the accepting level) before accessing the memory.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 12 lines · Kai
Quoted 8 lines · Rick P
arch/x86/kvm/vmx/tdx.c int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) · line 3266
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +0
-0@@ -3265,7 +3263,7 @@ int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) if (unlikely(to_kvm_tdx(kvm)->state != TD_STATE_RUNNABLE)) return PG_LEVEL_4K;arch/x86/kvm/vmx/tdx.c +1
-1-return PG_LEVEL_4K ; +return PG_LEVEL_2M ;Maybe combine this with patch 4, or split them into sensible categories.
How about merge with patch 12
Quoted 8 lines
[RFC PATCH 12/21] KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
instead?
Per patch 12, the fault due to TDH.MEM.PAGE.ACCPT contains fault level info, so KVM should just return that. But seems we are still returning
PG_LEVEL_2Mif no such info is provided (IIUC):
Yes, if without such info (tdx->violation_request_level), we always return PG_LEVEL_2M.
Quoted 29 lines
int tdx_gmem_private_max_mapping_level(struct
kvm_vcpu*vcpu,kvm_pfn_tpfn,
gfn_tgfn)
{(quoted diff) +5
-0+ struct vcpu_tdx *tdx = to_tdx(vcpu); + if (unlikely(to_kvm_tdx(vcpu->kvm)->state != TD_STATE_RUNNABLE)) return PG_LEVEL_4K; + if (gfn >= tdx->violation_gfn_start && gfn < tdx->violation_gfn_end) + return tdx->violation_request_level; + return PG_LEVEL_2M; }So why not returning
PT_LEVEL_4Kat the end?I am asking because below text mentioned in the coverletter:
A rare case that could lead to splitting in the fault path is when a TD is configured to receive #VE and accesses memory before the ACCEPT operation. By the time a vCPU accesses a private GFN, due to the lack of any guest preferred level, KVM could create a mapping at 2MB level. If the TD then only performs the ACCEPT operation at 4KB level, splitting in the fault path will be triggered. However, this is not regarded as a typical use case, as usually TD always accepts pages in the order from 1GB->2MB->4KB. The worst outcome to ignore the resulting splitting request is an endless EPT violation. This would not happen for a Linux guest, which does not expect any #VE.
Quoted 1 line
Changing to return
PT_LEVEL_4Kshould avoid this problem. It doesn't hurt
For TDs expect #VE, guests access private memory before accept it. In that case, upon KVM receives EPT violation, there's no expected level from the TDX module. Returning PT_LEVEL_4K at the end basically disables huge pages for those TDs.
Besides, according to Kirill [1], the order from 1GB->2MB->4KB is only the case for linux guests.
[1] https://lore.kernel.org/all/6vdj4mfxlyvypn743klxq5twda66tkugwzljdt275rug2gmwwl@zdziylxpre6y/#t
Quoted 2 lines
normal cases either, since guest will always do ACCEPT (which contains the accepting level) before accessing the memory.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 54 lines · Yan Y
Quoted 12 lines · Kai
Quoted 8 lines · Rick P
arch/x86/kvm/vmx/tdx.c int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) · line 3266
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +0
-0@@ -3265,7 +3263,7 @@ int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) if (unlikely(to_kvm_tdx(kvm)->state != TD_STATE_RUNNABLE)) return PG_LEVEL_4K;arch/x86/kvm/vmx/tdx.c +1
-1-return PG_LEVEL_4K ; +return PG_LEVEL_2M ;Maybe combine this with patch 4, or split them into sensible categories.
How about merge with patch 12
Quoted 8 lines
[RFC PATCH 12/21] KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
instead?
Per patch 12, the fault due to TDH.MEM.PAGE.ACCPT contains fault level info, so KVM should just return that. But seems we are still returning
PG_LEVEL_2Mif no such info is provided (IIUC):Yes, if without such info (
tdx->violation_request_level), we always returnPG_LEVEL_2M.Quoted 29 lines
int tdx_gmem_private_max_mapping_level(struct
kvm_vcpu*vcpu,kvm_pfn_tpfn,
gfn_tgfn)
{(quoted diff) +5
-0+ struct vcpu_tdx *tdx = to_tdx(vcpu); + if (unlikely(to_kvm_tdx(vcpu->kvm)->state != TD_STATE_RUNNABLE)) return PG_LEVEL_4K; + if (gfn >= tdx->violation_gfn_start && gfn < tdx->violation_gfn_end) + return tdx->violation_request_level; + return PG_LEVEL_2M; }So why not returning
PT_LEVEL_4Kat the end?I am asking because below text mentioned in the coverletter:
A rare case that could lead to splitting in the fault path is when a TD is configured to receive #VE and accesses memory before the ACCEPT operation. By the time a vCPU accesses a private GFN, due to the lack of any guest preferred level, KVM could create a mapping at 2MB level. If the TD then only performs the ACCEPT operation at 4KB level, splitting in the fault path will be triggered. However, this is not regarded as a typical use case, as usually TD always accepts pages in the order from 1GB->2MB->4KB. The worst outcome to ignore the resulting splitting request is an endless EPT violation. This would not happen for a Linux guest, which does not expect any #VE.
Quoted 5 lines
Quoted 1 line
Changing to return
PT_LEVEL_4Kshould avoid this problem. It doesn't hurtFor TDs expect #VE, guests access private memory before accept it. In that case, upon KVM receives EPT violation, there's no expected level from the TDX module. Returning
PT_LEVEL_4Kat the end basically disables huge pages for those TDs.
Just want to make sure I understand correctly:
Linux TDs always ACCEPT memory first before touching that memory, therefore KVM should always be able to get the accept level for Linux TDs.
In other words, returning PG_LEVEL_4K doesn't impact establishing large page mapping for Linux TDs.
However, other TDs may choose to touch memory first to receive #VE and then accept that memory. Returning PG_LEVEL_2M allows those TDs to use large page mappings in SEPT. Otherwise, returning PG_LEVEL_4K essentially disables large page for them (since we don't support PROMOTE for now?).
But in the above text you mentioned that, if doing so, because we choose to ignore splitting request on read, returning 2M could result in *endless* EPT violation.
So to me it seems you choose a design that could bring performance gain for certain non-Linux TDs when they follow a certain behaviour but otherwise could result in endless EPT violation in KVM.
I am not sure how is this OK? Or probably I have misunderstanding?
Quoted 5 lines
Besides, according to Kirill [1], the order from 1GB->2MB->4KB is only the case for linux guests.
[1] https://lore.kernel.org/all/6vdj4mfxlyvypn743klxq5twda66tkugwzljdt275rug2gmwwl@zdziylxpre6y/#t
I am not sure how is this related?
On the opposite, if other non-Linux TDs don't follow 1G->2M->4K accept order, e.g., they always accept 4K, there could be *endless EPT violation* if I understand your words correctly.
Isn't this yet-another reason we should choose to return PG_LEVEL_4K instead of 2M if no accept level is provided in the fault?
Quoted 3 lines
Quoted 3 lines
normal cases either, since guest will always do ACCEPT (which contains the accepting level) before accessing the memory.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 25 lines · Kai
Quoted 6 lines
For TDs expect #VE, guests access private memory before accept it. In that case, upon KVM receives EPT violation, there's no expected level from
the TDX module. ReturningPT_LEVEL_4Kat the end basically disables huge pages
for those TDs.Just want to make sure I understand correctly:
Linux TDs always ACCEPT memory first before touching that memory, therefore KVM
should always be able to get the accept level for Linux TDs.In other words, returning
PG_LEVEL_4Kdoesn't impact establishing large page mapping for Linux TDs.However, other TDs may choose to touch memory first to receive #VE and then accept that memory. Returning
PG_LEVEL_2Mallows those TDs to use large page mappings in SEPT. Otherwise, returningPG_LEVEL_4Kessentially disables large page for them (since we don't support PROMOTE for now?).But in the above text you mentioned that, if doing so, because we choose to ignore splitting request on read, returning 2M could result in *endless* EPT violation.
Quoted 5 lines
So to me it seems you choose a design that could bring performance gain for certain non-Linux TDs when they follow a certain behaviour but otherwise could result in endless EPT violation in KVM.
I am not sure how is this OK? Or probably I have misunderstanding?
Good point. And if we just pass 4k level if the EPT violation doesn't have the accept size, then force prefetch to 4k too, like this does. Then what needs fault path demotion? Guest double accept bugs?
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
In reply to Huang, KaiQuoted 66 lines · Kai
Quoted 54 lines · Yan Y
Quoted 12 lines · Kai
Quoted 8 lines · Rick P
arch/x86/kvm/vmx/tdx.c int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) · line 3266
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +0
-0@@ -3265,7 +3263,7 @@ int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) if (unlikely(to_kvm_tdx(kvm)->state != TD_STATE_RUNNABLE)) return PG_LEVEL_4K;arch/x86/kvm/vmx/tdx.c +1
-1-return PG_LEVEL_4K ; +return PG_LEVEL_2M ;Maybe combine this with patch 4, or split them into sensible categories.
How about merge with patch 12
Quoted 8 lines
[RFC PATCH 12/21] KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
instead?
Per patch 12, the fault due to TDH.MEM.PAGE.ACCPT contains fault level info, so KVM should just return that. But seems we are still returning
PG_LEVEL_2Mif no such info is provided (IIUC):Yes, if without such info (
tdx->violation_request_level), we always returnPG_LEVEL_2M.Quoted 29 lines
int tdx_gmem_private_max_mapping_level(struct
kvm_vcpu*vcpu,kvm_pfn_tpfn,
gfn_tgfn)
{(quoted diff) +5
-0+ struct vcpu_tdx *tdx = to_tdx(vcpu); + if (unlikely(to_kvm_tdx(vcpu->kvm)->state != TD_STATE_RUNNABLE)) return PG_LEVEL_4K; + if (gfn >= tdx->violation_gfn_start && gfn < tdx->violation_gfn_end) + return tdx->violation_request_level; + return PG_LEVEL_2M; }So why not returning
PT_LEVEL_4Kat the end?I am asking because below text mentioned in the coverletter:
A rare case that could lead to splitting in the fault path is when a TD is configured to receive #VE and accesses memory before the ACCEPT operation. By the time a vCPU accesses a private GFN, due to the lack of any guest preferred level, KVM could create a mapping at 2MB level. If the TD then only performs the ACCEPT operation at 4KB level, splitting in the fault path will be triggered. However, this is not regarded as a typical use case, as usually TD always accepts pages in the order from 1GB->2MB->4KB. The worst outcome to ignore the resulting splitting request is an endless EPT violation. This would not happen for a Linux guest, which does not expect any #VE.
Quoted 5 lines
Quoted 1 line
Changing to return
PT_LEVEL_4Kshould avoid this problem. It doesn't hurtFor TDs expect #VE, guests access private memory before accept it. In that case, upon KVM receives EPT violation, there's no expected level from the TDX module. Returning
PT_LEVEL_4Kat the end basically disables huge pages for those TDs.Just want to make sure I understand correctly:
Linux TDs always ACCEPT memory first before touching that memory, therefore KVM should always be able to get the accept level for Linux TDs.
Quoted 7 lines
In other words, returning
PG_LEVEL_4Kdoesn't impact establishing large page mapping for Linux TDs.However, other TDs may choose to touch memory first to receive #VE and then accept that memory. Returning
PG_LEVEL_2Mallows those TDs to use large page mappings in SEPT. Otherwise, returningPG_LEVEL_4Kessentially disables large page for them (since we don't support PROMOTE for now?).
Not only because we don't support PROMOTE.
After KVM maps at 4KB level, if the guest accepts at 2MB level, it would get a TDACCEPT_SIZE_MISMATCH error.
The case of "KVM maps at 4KB, guest accepts at 2MB" is different from "KVM maps at 2MB, guest accepts at 4KB".
For the former, the guest can't trigger endless EPT violation. Just consider when the guest wants to accept at 2MB while KVM can't meet its request. If it can trigger endless EPT violation, the linux guest should trigger endless EPT already with today's basic TDX.
Quoted 3 lines
But in the above text you mentioned that, if doing so, because we choose to ignore splitting request on read, returning 2M could result in *endless* EPT violation.
I don't get what you mean.
What's the relationship between splitting and "returning 2M could result in *endless* EPT" ?
Quoted 3 lines
So to me it seems you choose a design that could bring performance gain for certain non-Linux TDs when they follow a certain behaviour but otherwise could result in endless EPT violation in KVM.
Also don't understand here.
Which design could result in endless EPT violation?
Quoted 8 lines
I am not sure how is this OK? Or probably I have misunderstanding?
Quoted 5 lines
Besides, according to Kirill [1], the order from 1GB->2MB->4KB is only the case for linux guests.
[1] https://lore.kernel.org/all/6vdj4mfxlyvypn743klxq5twda66tkugwzljdt275rug2gmwwl@zdziylxpre6y/#t
Quoted 8 lines
I am not sure how is this related?
On the opposite, if other non-Linux TDs don't follow 1G->2M->4K accept order, e.g., they always accept 4K, there could be *endless EPT violation* if I understand your words correctly.
Isn't this yet-another reason we should choose to return
PG_LEVEL_4Kinstead of 2M if no accept level is provided in the fault?
As I said, returning PG_LEVEL_4K would disallow huge pages for non-Linux TDs. TD's accept operations at size > 4KB will get TDACCEPT_SIZE_MISMATCH.
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
normal cases either, since guest will always do ACCEPT (which contains the accepting level) before accessing the memory.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 10 lines · Yan Zhao
Quoted 8 lines
On the opposite, if other non-Linux TDs don't follow 1G->2M->4K accept order,
e.g., they always accept 4K, there could be *endless EPT violation* if I understand your words correctly.Isn't this yet-another reason we should choose to return
PG_LEVEL_4Kinstead of
2M if no accept level is provided in the fault?As I said, returning
PG_LEVEL_4Kwould disallow huge pages for non-Linux TDs. TD's accept operations at size > 4KB will getTDACCEPT_SIZE_MISMATCH.
TDX_PAGE_SIZE_MISMATCH is a valid error code that the guest should handle. The docs say the VMM needs to demote *if* the mapping is large and the accept size is small. But if we map at 4k size for non-accept EPT violations, we won't hit this case. I also wonder what is preventing the TDX module from handling a 2MB accept size at 4k mappings. It could be changed maybe.
But I think Kai's question was: why are we complicating the code for the case of non-Linux TDs that also use #VE for accept? It's not necessary to be functional, and there aren't any known TDs like that which are expected to use KVM today. (err, except the MMU stress test). So in another form the question is: should we optimize KVM for a case we don't even know if anyone will use? The answer seems obviously no to me.
I think this connects the question of whether we can pass the necessary info into fault via synthetic error code. Consider this new design:
- tdx_gmem_private_max_mapping_level() simply returns 4k for prefetch and pre-
runnable, otherwise returns 2MB
- if fault has accept info 2MB size, pass 2MB size into fault. Otherwise pass
4k (i.e. VMs that are relying on #VE to do the accept won't get huge pages *yet*).
What goes wrong? Seems simpler and no more stuffing fault info on the vcpu.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 18 lines · Rick P
Quoted 10 lines · Yan Zhao
Quoted 8 lines
On the opposite, if other non-Linux TDs don't follow 1G->2M->4K accept order,
e.g., they always accept 4K, there could be *endless EPT violation* if I understand your words correctly.Isn't this yet-another reason we should choose to return
PG_LEVEL_4Kinstead of
2M if no accept level is provided in the fault?As I said, returning
PG_LEVEL_4Kwould disallow huge pages for non-Linux TDs. TD's accept operations at size > 4KB will getTDACCEPT_SIZE_MISMATCH.
TDX_PAGE_SIZE_MISMATCHis a valid error code that the guest should handle. The docs say the VMM needs to demote *if* the mapping is large and the accept size is small. But if we map at 4k size for non-accept EPT violations, we won't hit this case. I also wonder what is preventing the TDX module from handling a 2MB accept size at 4k mappings. It could be changed maybe.
Quoted 6 lines
But I think Kai's question was: why are we complicating the code for the case of non-Linux TDs that also use #VE for accept? It's not necessary to be functional, and there aren't any known TDs like that which are expected to use KVM today. (err, except the MMU stress test). So in another form the question is: should we optimize KVM for a case we don't even know if anyone will use? The answer seems obviously no to me.
So, you want to disallow huge pages for non-Linux TDs, then we have no need to support splitting in the fault path, right?
I'm OK if we don't care non-Linux TDs for now.
This can simplify the splitting code and we can add the support when there's a need.
Quoted 5 lines
I think this connects the question of whether we can pass the necessary info into fault via synthetic error code. Consider this new design:
-
tdx_gmem_private_max_mapping_level()simply returns 4k for prefetch and pre-
runnable, otherwise returns 2MB
Why prefetch and pre-runnable faults go the first path, while
Quoted 3 lines
- if fault has accept info 2MB size, pass 2MB size into fault. Otherwise pass
4k (i.e. VMs that are relying on #VE to do the accept won't get huge pages *yet*).
other faults go the second path?
Quoted 1 line
What goes wrong? Seems simpler and no more stuffing fault info on the vcpu.
I tried to avoid the double paths.
IMHO, it's confusing to specify max_level from two paths.
The fault info in vcpu_tdx isn't a real problem as it's per-vCPU. An existing example in KVM is vcpu->arch.mmio_gfn.
We don't need something like the vcpu->arch.mmio_gen because tdx->violation_gfn_* and tdx->violation_request_level are reset in each tdx_handle_ept_violation().
BTW, dug into some history:
In v18 of TDX basic series,
enforcing 4KB for pre-runnable faults were done by passing PG_LEVEL_4K to kvm_mmu_map_tdp_page().
https://lore.kernel.org/all/1a64f798b550dad9e096603e8dae3b6e8fb2fbd5.1705965635.git.isaku.yamahata@intel.com/
https://lore.kernel.org/all/97bb1f2996d8a7b828cd9e3309380d1a86ca681b.1705965635.git.isaku.yamahata@intel.com/
For the other faults, it's done by altering max_level in kvm_mmu_do_page_fault(), and Paolo asked to use the tdx_gmem_private_max_mapping_level() path.
https://lore.kernel.org/all/CABgObfbu1-Ok607uYdo4DzwZf8ZGVQnvHU+y9_M1Zae55K5xwQ@mail.gmail.com/
For the patch "KVM: x86/mmu: Allow per-VM override of the TDP max page level", it's initially acked by Paolo in v2, and Sean's reply is at
https://lore.kernel.org/all/YO3%[email protected] .
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 25 lines · Yan Y
Quoted 18 lines · Rick P
Quoted 10 lines · Yan Zhao
Quoted 8 lines
On the opposite, if other non-Linux TDs don't follow 1G->2M->4K accept order,
e.g., they always accept 4K, there could be *endless EPT violation* if I understand your words correctly.Isn't this yet-another reason we should choose to return
PG_LEVEL_4Kinstead of
2M if no accept level is provided in the fault?As I said, returning
PG_LEVEL_4Kwould disallow huge pages for non-Linux TDs. TD's accept operations at size > 4KB will getTDACCEPT_SIZE_MISMATCH.
TDX_PAGE_SIZE_MISMATCHis a valid error code that the guest should handle. The docs say the VMM needs to demote *if* the mapping is large and the accept size is small. But if we map at 4k size for non-accept EPT violations, we won't hit this case. I also wonder what is preventing the TDX module from handling a 2MB accept size at 4k mappings. It could be changed maybe.Quoted 6 lines
But I think Kai's question was: why are we complicating the code for the case of non-Linux TDs that also use #VE for accept? It's not necessary to be functional, and there aren't any known TDs like that which are expected to use KVM today. (err, except the MMU stress test). So in another form the question is: should we optimize KVM for a case we don't even know if anyone will use? The answer seems obviously no to me.
Quoted 6 lines
So, you want to disallow huge pages for non-Linux TDs, then we have no need to support splitting in the fault path, right?
I'm OK if we don't care non-Linux TDs for now.
This can simplify the splitting code and we can add the support when there's a need.
For the record, I am not saying we don't care non-Linux TDs. I am worrying about the *endless* EPT violation in your below words:
... The worst outcome to ignore the resulting
splitting request is an endless EPT violation. This would not happen for a Linux guest, which does not expect any #VE.
And the point is, it's not OK if a *legal* guest behaviour can trigger this.
Sean Christopherson
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 7 lines · Kai Huang
Quoted 6 lines · Yan Y
Quoted 5 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 4 lines
On the opposite, if other non-Linux TDs don't follow 1G->2M->4K accept order, e.g., they always accept 4K, there could be *endless EPT violation* if I understand your words correctly.
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
Isn't this yet-another reason we should choose to return
PG_LEVEL_4Kinstead of 2M if no accept level is provided in the fault?As I said, returning
PG_LEVEL_4Kwould disallow huge pages for non-Linux TDs. TD's accept operations at size > 4KB will getTDACCEPT_SIZE_MISMATCH.
TDX_PAGE_SIZE_MISMATCHis a valid error code that the guest should handle. The docs say the VMM needs to demote *if* the mapping is large and the accept size is small.
No thanks, fix the spec and the TDX Module. Punting an error to the VMM is inconsistent, convoluted, and inefficient.
Per "Table 8.2: TDG.MEM.PAGE.ACCEPT SEPT Walk Cases":
S-EPT state ACCEPT vs. Mapping Size Behavior Leaf SEPT_PRESENT Smaller TDACCEPT_SIZE_MISMATCH Leaf !SEPT_PRESENT Smaller EPT Violation <=========================| Leaf DONT_CARE Same Success | => THESE TWO SHOULD MATCH!!! !Leaf SEPT_FREE Larger EPT Violation, BECAUSE THERE'S NO PAGE | !Leaf SEPT_FREE Larger TDACCEPT_SIZE_MISMATCH <================|
If ACCEPT is "too small", an EPT violation occurs. But if ACCEPT is "too big", a TDACCEPT_SIZE_MISMATCH error occurs. That's asinine.
The only reason that comes to mind for punting the "too small" case to the VMM is to try and keep the guest alive if the VMM is mapping more memory than has been enumerated to the guest. E.g. if the guest suspects the VMM is malicious or buggy. IMO, that's a terrible reason to push this much complexity into the host. It also risks godawful boot times, e.g. if the guest kernel is buggy and accepts everything at 4KiB granularity.
The TDX Module should return TDACCEPT_SIZE_MISMATCH and force the guest to take action, not force the hypervisor to limp along in a degraded state. If the guest doesn't want to ACCEPT at a larger granularity, e.g. because it doesn't think the entire 2MiB/1GiB region is available, then the guest can either log a warning and "poison" the page(s), or terminate and refuse to boot.
If for some reason the guest _can't_ ACCEPT at larger granularity, i.e. if the guest _knows_ that 2MiB or 1GiB is available/usable but refuses to ACCEPT at the appropriate granularity, then IMO that's firmly a guest bug.
If there's a *legitimate* use case where the guest wants to ACCEPT a subset of memory, then there should be an explicit TDCALL to request that the unwanted regions of memory be unmapped. Smushing everything into implicit behavior has obvioulsy created a giant mess.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 4 lines · Sean Christopherson
If there's a *legitimate* use case where the guest wants to ACCEPT a subset of memory, then there should be an explicit TDCALL to request that the unwanted regions of memory be unmapped. Smushing everything into implicit behavior has obvioulsy created a giant mess.
Hi, still digging on if there is any possible use.
I think this may need a guest opt-in, so the guest can say it can handle errors for both smaller and larger page size matches. So it may not matter if there is a rare usage or not. If KVM finds the guest opts-in (how to do that TBD), it can start mapping at the host level. If KVM doesn't see the opt-in, the guest gets 4k pages.
Sean Christopherson
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 6 lines · Rick P Edgecombe
Quoted 4 lines · Sean Christopherson
If there's a *legitimate* use case where the guest wants to ACCEPT a subset of memory, then there should be an explicit TDCALL to request that the unwanted regions of memory be unmapped. Smushing everything into implicit behavior has obvioulsy created a giant mess.
Quoted 6 lines
Hi, still digging on if there is any possible use.
I think this may need a guest opt-in, so the guest can say it can handle errors for both smaller and larger page size matches. So it may not matter if there is a rare usage or not. If KVM finds the guest opts-in (how to do that TBD), it can start mapping at the host level.
Hmm, clever. That should work; requiring an updated guest kernel to get optimal performance doesn't seem too onerous.
Quoted 1 line
If KVM doesn't see the opt-in, the guest gets 4k pages.
As in, KVM doesn't even try to use hugepage mappings? If so, this idea probably gets my vote.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 12 lines · Sean Christopherson
Quoted 7 lines
I think this may need a guest opt-in, so the guest can say it can handle errors
for both smaller and larger page size matches. So it may not matter if there is
a rare usage or not. If KVM finds the guest opts-in (how to do that TBD), it can
start mapping at the host level.Hmm, clever. That should work; requiring an updated guest kernel to get optimal
performance doesn't seem too onerous.
Quoted 5 lines
Quoted 1 line
If KVM doesn't see the opt-in, the guest gets 4k pages.
As in, KVM doesn't even try to use hugepage mappings? If so, this idea probably
gets my vote.
Maybe an "I can handle it" accept size bit that comes in the exit qualification?
Yan, do you see any problems with that? Like if a guest passed it in some accept and not others? Thinking about the new "unaccept" SEAMCALL...
Sean Christopherson
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 9 lines · Rick P Edgecombe
Quoted 8 lines · Sean Christopherson
Quoted 4 lines
I think this may need a guest opt-in, so the guest can say it can handle errors for both smaller and larger page size matches. So it may not matter if there is a rare usage or not. If KVM finds the guest opts-in (how to do that TBD), it can start mapping at the host level.
Hmm, clever. That should work; requiring an updated guest kernel to get optimal performance doesn't seem too onerous.
Quoted 6 lines
Quoted 4 lines
Quoted 1 line
If KVM doesn't see the opt-in, the guest gets 4k pages.
As in, KVM doesn't even try to use hugepage mappings? If so, this idea probably gets my vote.
Maybe an "I can handle it" accept size bit that comes in the exit qualification?
Eww, no. Having to react on _every_ EPT violation would be annoying, and trying to debug issues where the guest is mixing options would probably be a nightmare.
I was thinking of something along the lines of an init-time or boot-time opt-in.
Quoted 2 lines
Yan, do you see any problems with that? Like if a guest passed it in some accept and not others? Thinking about the new "unaccept" SEAMCALL...
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 10 lines · Sean Christopherson
Quoted 2 lines
Maybe an "I can handle it" accept size bit that comes in the exit qualification?
Eww, no. Having to react on _every_ EPT violation would be annoying, and trying
to debug issues where the guest is mixing options would probably be a nightmare.I was thinking of something along the lines of an init-time or boot-time opt- in.
Fair.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 3 lines · Rick P
Quoted 2 lines · Sean Christopherson
Quoted 2 lines
Maybe an "I can handle it" accept size bit that comes in the exit qualification?
Dynamic turning on "I can handle it" would still require the supporting of demotion in the fault path because there may be existing huge pages when an EPT violation without "I can handle it" comes.
Quoted 9 lines
Quoted 7 lines
Eww, no. Having to react on _every_ EPT violation would be annoying, and trying
to debug issues where the guest is mixing options would probably be a nightmare.I was thinking of something along the lines of an init-time or boot-time opt- in.
Fair.
Agreed.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 5 lines · Yan Zhao
Quoted 5 lines
Quoted 5 lines
Eww, no. Having to react on _every_ EPT violation would be annoying, and trying
to debug issues where the guest is mixing options would probably be a nightmare.
Quoted 7 lines
Quoted 5 lines
Quoted 3 lines
I was thinking of something along the lines of an init-time or boot-time opt-
in.Fair.
Agreed.
Arg, I just realized a one-way opt-in will have a theoretical gap. If the guest kexec's, the new kernel will need to match the opt-in.
A full solution could allow a later opt-out that is handled by the VMM by shattering all page tables. But it starts to get too complex I think. Especially since Linux guests already try to accept in the order 1GB->2MB->4k. So in practice we are already worrying about correctness and not functional issues. Maybe we just ignore it.
Otherwise, we currently have the following requirements I think:
1. One-way guest opt-in to new TDG.MEM.PAGE.ACCEPT behavior
2. Some notification to KVM that the guest has opted in.
3. After opt-in, TDG.MEM.PAGE.ACCEPT will return TDX_PAGE_SIZE_MISMATCH if mapping is too small or too big
Thinking about how we would like the notification... Maybe we could have the actual behavior controlled by the host, and have some GHCI like communication like a TDVMCALL. The TDVMCALL (or similar) could be handled within KVM. Basically just call the host side opt-in.
The reason to have it host controllable is that, as above, the new behavior should be fine for a normal Linux guest. A host user controlled opt-in could be useful for anyone that wants to run huge pages for old guest kernels. A kvm module param maybe.
If this sounds good, I'll get the TDX modules input and come back with some specific spec.
Sean Christopherson
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 8 lines · Rick P Edgecombe
Quoted 7 lines · Yan Zhao
Quoted 7 lines
Quoted 6 lines
Eww, no. Having to react on _every_ EPT violation would be annoying, and trying to debug issues where the guest is mixing options would probably be a nightmare.
I was thinking of something along the lines of an init-time or boot-time opt- in.
Quoted 6 lines
Quoted 3 lines
Quoted 1 line
Fair.
Agreed.
Arg, I just realized a one-way opt-in will have a theoretical gap. If the guest kexec's, the new kernel will need to match the opt-in.
All the more reason to make this a property of the VM that is passed via "struct td_params". I.e. put the onus on the owner of the VM to ensure their kernel(s) have been updated accordingly.
I understand that this could be painful, but honestly _all_ of TDX and SNP is painful for the guest. E.g. I don't think it's any worse than the security issues with TDX (and SNP) guests using kvmclock (which I'd love some reviews on, btw).
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 7 lines · Sean Christopherson
Quoted 3 lines
Arg, I just realized a one-way opt-in will have a theoretical gap. If the guest
kexec's, the new kernel will need to match the opt-in.All the more reason to make this a property of the VM that is passed via "struct td_params". I.e. put the onus on the owner of the VM to ensure their kernel(s) have been updated accordingly.
Hmm, it gives me pause. At minimum it should have an enumeration to the guest.
Quoted 8 lines
I understand that this could be painful, but honestly _all_ of TDX and SNP is painful for the guest. E.g. I don't think it's any worse than the security issues with TDX (and SNP) guests using kvmclock (which I'd love some reviews on,
btw).
Oh, nice. I hadn't seen this. Agree that a comprehensive guest setup is quite manual. But here we are playing with guest ABI. In practice, yes it's similar to passing yet another arg to get a good TD.
We can start with a prototype the host side arg and see how it turns out. I realized we need to verify edk2 as well.
Thanks Sean.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 18 lines · Rick P
Quoted 7 lines · Sean Christopherson
Quoted 3 lines
Arg, I just realized a one-way opt-in will have a theoretical gap. If the guest
kexec's, the new kernel will need to match the opt-in.All the more reason to make this a property of the VM that is passed via "struct td_params". I.e. put the onus on the owner of the VM to ensure their kernel(s) have been updated accordingly.
Hmm, it gives me pause. At minimum it should have an enumeration to the guest.
Quoted 7 lines
I understand that this could be painful, but honestly _all_ of TDX and SNP is painful for the guest. E.g. I don't think it's any worse than the security issues with TDX (and SNP) guests using kvmclock (which I'd love some reviews on,
btw).
Quoted 5 lines
Quoted 1 line
Oh, nice. I hadn't seen this. Agree that a comprehensive guest setup is quite manual. But here we are playing with guest ABI. In practice, yes it's similar to passing yet another arg to get a good TD.
Could we introduce a TD attr TDX_ATTR_SEPT_EXPLICIT_DEMOTION?
It can be something similar to TDX_ATTR_SEPT_VE_DISABLE except that we don't provide a dynamical way as the TDCS_CONFIG_FLEXIBLE_PENDING_VE to allow guest to turn on/off SEPT_VE_DISABLE.
(See the disable_sept_ve() in ./arch/x86/coco/tdx/tdx.c).
So, if userspace configures a TD with TDX_ATTR_SEPT_EXPLICIT_DEMOTION, KVM first checks if SEPT_EXPLICIT_DEMOTION is supported.
The guest can also check if it would like to support SEPT_EXPLICIT_DEMOTION to determine to continue or shut down. (If it does not check SEPT_EXPLICIT_DEMOTION, e.g., if we don't want to update EDK2, the guest must accept memory before memory accessing).
- if TD is configured with SEPT_EXPLICIT_DEMOTION, KVM allows to map at 2MB when there's no level info in an EPT violation. The guest must accept memory before accessing memory or if it wants to accept only a partial of host's mapping, it needs to explicitly invoke a TDVMCALL to request KVM to perform page demotion.
- if TD is configured without SEPT_EXPLICIT_DEMOTION, KVM always maps at 4KB when there's no level info in an EPT violation.
- No matter SEPT_EXPLICIT_DEMOTION is configured or not, if there's a level info in an EPT violation, while KVM honors the level info as the max_level info, KVM ignores the demotion request in the fault path.
Quoted 2 lines
We can start with a prototype the host side arg and see how it turns out. I realized we need to verify edk2 as well.
Current EDK2 should always accept pages before actual memory access. So, I think it should be fine.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 31 lines · Yan Zhao
Quoted 5 lines
Oh, nice. I hadn't seen this. Agree that a comprehensive guest setup is quite
manual. But here we are playing with guest ABI. In practice, yes it's similar to
passing yet another arg to get a good TD.Could we introduce a TD attr
TDX_ATTR_SEPT_EXPLICIT_DEMOTION?It can be something similar to
TDX_ATTR_SEPT_VE_DISABLEexcept that we don't provide a dynamical way as theTDCS_CONFIG_FLEXIBLE_PENDING_VEto allow guest to
turn on/offSEPT_VE_DISABLE.
(See thedisable_sept_ve()in./arch/x86/coco/tdx/tdx.c).So, if userspace configures a TD with
TDX_ATTR_SEPT_EXPLICIT_DEMOTION, KVM first
checks ifSEPT_EXPLICIT_DEMOTIONis supported.
The guest can also check if it would like to supportSEPT_EXPLICIT_DEMOTIONto determine to continue or shut down. (If it does not checkSEPT_EXPLICIT_DEMOTION,
e.g., if we don't want to update EDK2, the guest must accept memory before memory accessing).- if TD is configured with
SEPT_EXPLICIT_DEMOTION, KVM allows to map at 2MB when
there's no level info in an EPT violation. The guest must accept memory before
accessing memory or if it wants to accept only a partial of host's mapping, it
needs to explicitly invoke a TDVMCALL to request KVM to perform page demotion.
Quoted 7 lines
- if TD is configured without
SEPT_EXPLICIT_DEMOTION, KVM always maps at 4KB when there's no level info in an EPT violation.- No matter
SEPT_EXPLICIT_DEMOTIONis configured or not, if there's a level info
in an EPT violation, while KVM honors the level info as themax_levelinfo, KVM ignores the demotion request in the fault path.
I think this is what Sean was suggesting. We are going to need a qemu command line opt-in too.
Quoted 5 lines
Quoted 3 lines
We can start with a prototype the host side arg and see how it turns out. I realized we need to verify edk2 as well.
Current EDK2 should always accept pages before actual memory access. So, I think it should be fine.
It's not just that, it needs to handle the the accept page size being lower than the mapping size. I went and looked and it is accepting at 4k size in places. It hopefully is just handling accepting a whole range that is not 2MB aligned. But I think we need to verify this more.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 44 lines · Rick P
Quoted 31 lines · Yan Zhao
Quoted 5 lines
Oh, nice. I hadn't seen this. Agree that a comprehensive guest setup is quite
manual. But here we are playing with guest ABI. In practice, yes it's similar to
passing yet another arg to get a good TD.Could we introduce a TD attr
TDX_ATTR_SEPT_EXPLICIT_DEMOTION?It can be something similar to
TDX_ATTR_SEPT_VE_DISABLEexcept that we don't provide a dynamical way as theTDCS_CONFIG_FLEXIBLE_PENDING_VEto allow guest to
turn on/offSEPT_VE_DISABLE.
(See thedisable_sept_ve()in./arch/x86/coco/tdx/tdx.c).So, if userspace configures a TD with
TDX_ATTR_SEPT_EXPLICIT_DEMOTION, KVM first
checks ifSEPT_EXPLICIT_DEMOTIONis supported.
The guest can also check if it would like to supportSEPT_EXPLICIT_DEMOTIONto determine to continue or shut down. (If it does not checkSEPT_EXPLICIT_DEMOTION,
e.g., if we don't want to update EDK2, the guest must accept memory before memory accessing).- if TD is configured with
SEPT_EXPLICIT_DEMOTION, KVM allows to map at 2MB when
there's no level info in an EPT violation. The guest must accept memory before
accessing memory or if it wants to accept only a partial of host's mapping, it
needs to explicitly invoke a TDVMCALL to request KVM to perform page demotion.Quoted 7 lines
- if TD is configured without
SEPT_EXPLICIT_DEMOTION, KVM always maps at 4KB when there's no level info in an EPT violation.- No matter
SEPT_EXPLICIT_DEMOTIONis configured or not, if there's a level info
in an EPT violation, while KVM honors the level info as themax_levelinfo, KVM ignores the demotion request in the fault path.I think this is what Sean was suggesting. We are going to need a qemu command line opt-in too.
Quoted 1 line
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
We can start with a prototype the host side arg and see how it turns out. I realized we need to verify edk2 as well.
Current EDK2 should always accept pages before actual memory access. So, I think it should be fine.
It's not just that, it needs to handle the the accept page size being lower than the mapping size. I went and looked and it is accepting at 4k size in places. It
As it accepts pages before memory access, the "accept page size being lower than the the mapping size" can't happen.
Quoted 2 lines
hopefully is just handling accepting a whole range that is not 2MB aligned. But I think we need to verify this more.
Ok.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 33 lines · Yan Zhao
Quoted 32 lines · Rick P
Quoted 31 lines · Yan Zhao
Quoted 5 lines
Oh, nice. I hadn't seen this. Agree that a comprehensive guest setup is quite
manual. But here we are playing with guest ABI. In practice, yes it's similar to
passing yet another arg to get a good TD.Could we introduce a TD attr
TDX_ATTR_SEPT_EXPLICIT_DEMOTION?It can be something similar to
TDX_ATTR_SEPT_VE_DISABLEexcept that we don't provide a dynamical way as theTDCS_CONFIG_FLEXIBLE_PENDING_VEto allow guest to
turn on/offSEPT_VE_DISABLE.
(See thedisable_sept_ve()in./arch/x86/coco/tdx/tdx.c).So, if userspace configures a TD with
TDX_ATTR_SEPT_EXPLICIT_DEMOTION, KVM first
checks ifSEPT_EXPLICIT_DEMOTIONis supported.
The guest can also check if it would like to supportSEPT_EXPLICIT_DEMOTIONto determine to continue or shut down. (If it does not checkSEPT_EXPLICIT_DEMOTION,
e.g., if we don't want to update EDK2, the guest must accept memory before memory accessing).- if TD is configured with
SEPT_EXPLICIT_DEMOTION, KVM allows to map at 2MB when
there's no level info in an EPT violation. The guest must accept memory before
accessing memory or if it wants to accept only a partial of host's mapping, it
needs to explicitly invoke a TDVMCALL to request KVM to perform page demotion.
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
- if TD is configured without
SEPT_EXPLICIT_DEMOTION, KVM always maps at 4KB when there's no level info in an EPT violation.- No matter
SEPT_EXPLICIT_DEMOTIONis configured or not, if there's a level info
in an EPT violation, while KVM honors the level info as themax_levelinfo, KVM ignores the demotion request in the fault path.
Hi Sean,
Could you please confirm if this matches what you think? i.e.,
when an EPT violation carries an ACCEPT level info
KVM maps the page at map level <= the specified level.
(If KVM finds a shadow-present lead SPTE, it will not try to merge/split it.) Guest's ACCEPT will succeed or return PAGE_SIZE_MATCH if map level < the specified level.
This can keep linux guests (with SEPT_VE_DISABLE being true) more efficient. So, for linux guests, if it only wants to accept at 4KB, the flow is
1. guest ACCEPT 4KB
2. KVM maps it at 4KB
3. ACCEPT 4KB returns success
As the ACCEPT comes before KVM actually maps anything, we can avoid the complex flow:
1. guest ACCEPT 4KB
2. KVM maps it at 2MB
3. ACCEPT 4KB returns PAGE_SIZE_MATCH.
4.(a) guest ACCEPT 2MB or
4.(b) guest triggers TDVMCALL to demote
5. KVM demotes the 2MB mapping
6. guest ACCEPT at 4KB
7. ACCEPT 4KB returns success
For non-linux guests (with SEPT_VE_DISABLE being false), I totally agree with your suggestions!
Thanks
Yan
Quoted 17 lines
Quoted 11 lines
I think this is what Sean was suggesting. We are going to need a qemu command line opt-in too.
Quoted 5 lines
Quoted 3 lines
We can start with a prototype the host side arg and see how it turns out. I realized we need to verify edk2 as well.
Current EDK2 should always accept pages before actual memory access. So, I think it should be fine.
It's not just that, it needs to handle the the accept page size being lower than the mapping size. I went and looked and it is accepting at 4k size in places. It
As it accepts pages before memory access, the "accept page size being lower than the the mapping size" can't happen.
Quoted 2 lines
hopefully is just handling accepting a whole range that is not 2MB aligned. But I think we need to verify this more.
Ok.
Sean Christopherson
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 2 lines · Yan Zhao
when an EPT violation carries an ACCEPT level info KVM maps the page at map level <= the specified level.
No. I want KVM to map at the maximal level KVM supports, irrespective of what the guest's ACCEPT level says. I.e. I want KVM to be able to completely ignore the ACCEPT level.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 7 lines · Sean Christopherson
Quoted 7 lines · Yan Zhao
Quoted 2 lines
Quoted 2 lines
when an EPT violation carries an ACCEPT level info KVM maps the page at map level <= the specified level.
No. I want KVM to map at the maximal level KVM supports, irrespective of what the guest's ACCEPT level says. I.e. I want KVM to be able to completely ignore the ACCEPT level.
This is what I was thinking, but I'm starting to think it might not be a good idea.
The PAGE_SIZE_MISMATCH error code asymmetry is indeed weird. But "accepted" is in some important ways a type of permission that is controllable by both the guest and host. To change the ABI and guests such that the permission is still controlled by the host and guest, but the allowed granularity is only controllable by the host, feels wrong in a couple ways.
First, it turns host mapping details into guest ABI that could break guests that rely on it. Second, it bets that there will never be a need for guests to set the accept state on a specific smaller granularity. Otherwise, this path would just be a temporary shortcut and not about components imposing things that are none of their business.
Instead I think the two impositions that matter here are:
1. TDX requires size to be passed through the generic fault handler somehow.
2. TDX demote is hard to make work under mmu read lock (already working on this one)
Sean, were the two options for (1) really that bad? Or how do you think about changing directions in general and we can try to find some other options?
On the subject of alternates to (1). I wonder if the ugly part is that both of the options sort of break the KVM model where the TDP is not the real backing state. TDG.MEM.PAGE.ACCEPT is kind of two things, changing the "permission" of the memory *and* the mapping of it. TDX module asks, map this at this page size so that I can map it at the right permission. KVM would rather learn that the permission from the backing GPA info (memslots, etc) and then map it at it's correct page size. Like what happens with kvm_lpage_info->disallow_lpage.
Maybe we could have EPT violations that contain 4k accept sizes first update the attribute for the GFN to be accepted or not, like have tdx.c call out to set kvm_lpage_info->disallow_lpage in the rarer case of 4k accept size? Or something like that. Maybe set a "accepted" attribute, or something. Not sure if could be done without the mmu write lock... But it might fit KVM better?
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 32 lines · Rick P
Quoted 7 lines · Sean Christopherson
Quoted 7 lines · Yan Zhao
Quoted 2 lines
Quoted 2 lines
when an EPT violation carries an ACCEPT level info KVM maps the page at map level <= the specified level.
No. I want KVM to map at the maximal level KVM supports, irrespective of what the guest's ACCEPT level says. I.e. I want KVM to be able to completely ignore the ACCEPT level.
This is what I was thinking, but I'm starting to think it might not be a good idea.
The
PAGE_SIZE_MISMATCHerror code asymmetry is indeed weird. But "accepted" is in some important ways a type of permission that is controllable by both the guest and host. To change the ABI and guests such that the permission is still controlled by the host and guest, but the allowed granularity is only controllable by the host, feels wrong in a couple ways.First, it turns host mapping details into guest ABI that could break guests that rely on it. Second, it bets that there will never be a need for guests to set the accept state on a specific smaller granularity. Otherwise, this path would just be a temporary shortcut and not about components imposing things that are none of their business.
Instead I think the two impositions that matter here are:
1. TDX requires size to be passed through the generic fault handler somehow.
2. TDX demote is hard to make work under mmu read lock (already working on this one)Sean, were the two options for (1) really that bad? Or how do you think about changing directions in general and we can try to find some other options?
Quoted 7 lines
On the subject of alternates to (1). I wonder if the ugly part is that both of the options sort of break the KVM model where the TDP is not the real backing state. TDG.MEM.PAGE.ACCEPT is kind of two things, changing the "permission" of the memory *and* the mapping of it. TDX module asks, map this at this page size so that I can map it at the right permission. KVM would rather learn that the permission from the backing GPA info (memslots, etc) and then map it at it's correct page size. Like what happens with
kvm_lpage_info->disallow_lpage.
Could we provide the info via the private_max_mapping_level hook (i.e. via tdx_gmem_private_max_mapping_level())?
Or what about introducing a vendor hook in __kvm_mmu_max_mapping_level() for a private fault?
Quoted 3 lines
Maybe we could have EPT violations that contain 4k accept sizes first update the attribute for the GFN to be accepted or not, like have
tdx.ccall out to setkvm_lpage_info->disallow_lpagein the rarer case of 4k accept size? Or something
Something like kvm_lpage_info->disallow_lpage would disallow later page promotion, though we don't support it right now.
Quoted 1 line
like that. Maybe set a "accepted" attribute, or something. Not sure if could be
Setting "accepted" attribute in the EPT violation handler? It's a little odd, as the accept operation is not yet completed.
Quoted 1 line
done without the mmu write lock... But it might fit KVM better?
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 2 lines · Yan Zhao
Could we provide the info via the
private_max_mapping_levelhook (i.e. viatdx_gmem_private_max_mapping_level())?
This is one of the previous two methods discussed. Can you elaborate on what you are trying to say?
Quoted 9 lines
Or what about introducing a vendor hook in
__kvm_mmu_max_mapping_level()for a private fault?Quoted 3 lines
Maybe we could have EPT violations that contain 4k accept sizes first update the attribute for the GFN to be accepted or not, like have
tdx.ccall out to setkvm_lpage_info->disallow_lpagein the rarer case of 4k accept size? Or somethingSomething like
kvm_lpage_info->disallow_lpagewould disallow later page promotion, though we don't support it right now.
Well I was originally thinking it would not set kvm_lpage_info->disallow_lpage directly, but rely on the logic that checks for mixed attributes. But more below...
Quoted 4 lines
Quoted 2 lines
like that. Maybe set a "accepted" attribute, or something. Not sure if could be
Setting "accepted" attribute in the EPT violation handler? It's a little odd, as the accept operation is not yet completed.
I guess the question in both of these comments is: what is the life cycle. Guest could call TDG.MEM.PAGE.RELEASE to unaccept it as well. Oh, geez. It looks like TDG.MEM.PAGE.RELEASE will give the same size hints in the EPT violation. So an accept attribute is not going work, at least without TDX module changes.
Actually, the problem we have doesn't fit the mixed attributes behavior. If many vCPU's accept at 2MB region at 4k page size, the entire 2MB range could be non- mixed and then individual accepts would fail.
So instead there could be a KVM_LPAGE_GUEST_INHIBIT that doesn't get cleared based on mixed attributes. It would be one way. It would need to get set by something like kvm_write_track_add_gfn() that lives in tdx.c and is called before going into the fault handler on 4k accept size. It would have to take mmu write lock I think, which would kill scalability in the 4k accept case (but not the normal 2MB one). But as long as mmu_write lock is held, demote will be no problem, which the operation would also need to do.
I think it actually makes KVM's behavior easier to understand. We don't need to worry about races between multiple accept sizes and things like that. It also leaves the core MMU code mostly untouched. Performance/scalability wise it only punishes the rare case.
For leaving the option open to promote the GFNs in the future, a GHCI interface or similar could be defined for the guest to say "I don't care about page size anymore for this gfn". So it won't close it off forever.
Quoted 2 lines
Quoted 2 lines
done without the mmu write lock... But it might fit KVM better?
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 6 lines · Rick P
Quoted 2 lines · Yan Zhao
Could we provide the info via the
private_max_mapping_levelhook (i.e. viatdx_gmem_private_max_mapping_level())?This is one of the previous two methods discussed. Can you elaborate on what you are trying to say?
I don't get why we can't use the existing tdx_gmem_private_max_mapping_level() to convey the max_level info at which a vendor hopes a GFN to be mapped.
Before TDX huge pages, tdx_gmem_private_max_mapping_level() always returns 4KB; after TDX huge pages, it returns
- 4KB during the TD build stage
- at TD runtime: 4KB or 2MB
Why does KVM need to care how the vendor determines this max_level? I think a vendor should have its freedom to decide based on software limitation, guest's wishes, hardware bugs or whatever.
Quoted 24 lines
Quoted 8 lines
Or what about introducing a vendor hook in
__kvm_mmu_max_mapping_level()for a private fault?Quoted 3 lines
Maybe we could have EPT violations that contain 4k accept sizes first update the attribute for the GFN to be accepted or not, like have
tdx.ccall out to setkvm_lpage_info->disallow_lpagein the rarer case of 4k accept size? Or somethingSomething like
kvm_lpage_info->disallow_lpagewould disallow later page promotion, though we don't support it right now.Well I was originally thinking it would not set
kvm_lpage_info->disallow_lpagedirectly, but rely on the logic that checks for mixed attributes. But more below...Quoted 4 lines
Quoted 2 lines
like that. Maybe set a "accepted" attribute, or something. Not sure if could be
Setting "accepted" attribute in the EPT violation handler? It's a little odd, as the accept operation is not yet completed.
I guess the question in both of these comments is: what is the life cycle. Guest could call TDG.MEM.PAGE.RELEASE to unaccept it as well. Oh, geez. It looks like TDG.MEM.PAGE.RELEASE will give the same size hints in the EPT violation. So an accept attribute is not going work, at least without TDX module changes.
Quoted 6 lines
Actually, the problem we have doesn't fit the mixed attributes behavior. If many vCPU's accept at 2MB region at 4k page size, the entire 2MB range could be non- mixed and then individual accepts would fail.
So instead there could be a
KVM_LPAGE_GUEST_INHIBITthat doesn't get cleared
Set KVM_LPAGE_GUEST_INHIBIT via a TDVMCALL ?
Or just set the KVM_LPAGE_GUEST_INHIBIT when an EPT violation contains 4KB level info?
I guess it's the latter one as it can avoid modification to both EDK2 and Linux guest. I observed ~2710 instances of "guest accepts at 4KB when KVM can map at 2MB" during the boot-up of a TD with 4GB memory.
But does it mean TDX needs to hold write mmu_lock in the EPT violation handler and set KVM_LPAGE_GUEST_INHIBIT on finding a violation carries 4KB level info?
Quoted 11 lines
based on mixed attributes. It would be one way. It would need to get set by something like
kvm_write_track_add_gfn()that lives intdx.cand is called before going into the fault handler on 4k accept size. It would have to take mmu write lock I think, which would kill scalability in the 4k accept case (but not the normal 2MB one). But as long asmmu_writelock is held, demote will be no problem, which the operation would also need to do.I think it actually makes KVM's behavior easier to understand. We don't need to worry about races between multiple accept sizes and things like that. It also leaves the core MMU code mostly untouched. Performance/scalability wise it only punishes the rare case.
Write down my understanding to check if it's correct:
- when a TD is NOT configured to support KVM_LPAGE_GUEST_INHIBIT TDVMCALL, KVM always maps at 4KB
- When a TD is configured to support KVM_LPAGE_GUEST_INHIBIT TDVMCALL,
(a)
1. guest accepts at 4KB
2. TDX sets KVM_LPAGE_GUEST_INHIBIT and try splitting.(with write mmu_lock)
3. KVM maps at 4KB (with read mmu_lock)
4. guest's 4KB accept succeeds.
(b)
1. guest accepts at 2MB.
2. KVM maps at 4KB due to a certain reason.
3. guest's accept 2MB fails with TDACCEPT_SIZE_MISMATCH.
4. guest accepts at 4KB
5. guest's 4KB accept succeeds.
Quoted 3 lines
For leaving the option open to promote the GFNs in the future, a GHCI interface or similar could be defined for the guest to say "I don't care about page size anymore for this gfn". So it won't close it off forever.
ok.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 6 lines · Yan Zhao
Write down my understanding to check if it's correct:
- when a TD is NOT configured to support
KVM_LPAGE_GUEST_INHIBITTDVMCALL, KVM always maps at 4KB- When a TD is configured to support
KVM_LPAGE_GUEST_INHIBITTDVMCALL,
Sorry, the two conditions are stale ones. No need any more. So it's always
(a)
1. guest accepts at 4KB
2. TDX sets KVM_LPAGE_GUEST_INHIBIT and try splitting.(with write mmu_lock)
3. KVM maps at 4KB (with read mmu_lock)
4. guest's 4KB accept succeeds.
(b)
1. guest accepts at 2MB.
2. KVM maps at 4KB due to a certain reason.
3. guest's accept 2MB fails with TDACCEPT_SIZE_MISMATCH.
4. guest accepts at 4KB
5. guest's 4KB accept succeeds.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 7 lines · Yan Zhao
Quoted 6 lines · Yan Zhao
Write down my understanding to check if it's correct:
- when a TD is NOT configured to support
KVM_LPAGE_GUEST_INHIBITTDVMCALL, KVM always maps at 4KB- When a TD is configured to support
KVM_LPAGE_GUEST_INHIBITTDVMCALL,
Quoted 8 lines
Sorry, the two conditions are stale ones. No need any more.
So it's always
(a)
1. guest accepts at 4KB
2. TDX setsKVM_LPAGE_GUEST_INHIBITand try splitting.(with writemmu_lock)
3. KVM maps at 4KB (with readmmu_lock)
4. guest's 4KB accept succeeds.
Yea.
Quoted 4 lines
(b)
1. guest accepts at 2MB.
2. KVM maps at 4KB due to a certain reason.
I don't follow this part. You mean because it spans a memslot or other? Basically that KVM won't guarantee the page size at exactly the accept size? I think this is ok and good. The ABI can be that KVM will guarantee the S-EPT mapping size <= the accept size.
Quoted 4 lines
3. guest's accept 2MB fails with
TDACCEPT_SIZE_MISMATCH.
4. guest accepts at 4KB
5. guest's 4KB accept succeeds.
In this option accept behavior doesn't need to change, but the TDACCEPT_SIZE_MISMATCH in step 3 still is a little weird. TDX module could accept at 4k mapping size. But this is an issue for the guest to deal with, not KVM.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 17 lines · Rick P
Quoted 7 lines · Yan Zhao
Quoted 6 lines · Yan Zhao
Write down my understanding to check if it's correct:
- when a TD is NOT configured to support
KVM_LPAGE_GUEST_INHIBITTDVMCALL, KVM always maps at 4KB- When a TD is configured to support
KVM_LPAGE_GUEST_INHIBITTDVMCALL,Quoted 8 lines
Sorry, the two conditions are stale ones. No need any more.
So it's always
(a)
1. guest accepts at 4KB
2. TDX setsKVM_LPAGE_GUEST_INHIBITand try splitting.(with writemmu_lock)
3. KVM maps at 4KB (with readmmu_lock)
4. guest's 4KB accept succeeds.
Quoted 8 lines
Yea.
Quoted 4 lines
(b)
1. guest accepts at 2MB.
2. KVM maps at 4KB due to a certain reason.I don't follow this part. You mean because it spans a memslot or other?
Sorry for bringing confusion. (b) is the same as the current bahavior. I listed (b) just to contrast with (a)...
KVM may map at 4KB due to adjacent shared GFNs, spanning a memslot, or because the TDX code doesn't support huge pages at all...
Quoted 3 lines
Basically that KVM won't guarantee the page size at exactly the accept size? I think this is ok and good. The ABI can be that KVM will guarantee the S-EPT mapping size <= the accept size.
Right.
Quoted 8 lines
Quoted 4 lines
3. guest's accept 2MB fails with
TDACCEPT_SIZE_MISMATCH.
4. guest accepts at 4KB
5. guest's 4KB accept succeeds.In this option accept behavior doesn't need to change, but the
TDACCEPT_SIZE_MISMATCHin step 3 still is a little weird. TDX module could accept at 4k mapping size. But this is an issue for the guest to deal with, not KVM.
With current TDX module, TDACCEPT_SIZE_MISMATCH is returned in step 3.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
In reply to Yan ZhaoQuoted 10 lines · Yan Zhao
Quoted 6 lines · Rick P
Quoted 2 lines · Yan Zhao
Could we provide the info via the
private_max_mapping_levelhook (i.e. viatdx_gmem_private_max_mapping_level())?This is one of the previous two methods discussed. Can you elaborate on what you are trying to say?
I don't get why we can't use the existing
tdx_gmem_private_max_mapping_level()to convey themax_levelinfo at which a vendor hopes a GFN to be mapped.
Quoted 8 lines
Before TDX huge pages,
tdx_gmem_private_max_mapping_level()always returns 4KB; after TDX huge pages, it returns
- 4KB during the TD build stage
- at TD runtime: 4KB or 2MBWhy does KVM need to care how the vendor determines this
max_level? I think a vendor should have its freedom to decide based on software limitation, guest's wishes, hardware bugs or whatever.
I don't see that big of a difference between "KVM" and "vendor". TDX code is KVM code. Just because it's in tdx.c doesn't mean it's ok for it to be hard to trace the logic.
I'm not sure what Sean's objection was to that approach, or if he objected to just the weird SIZE_MISMATCH behavior of TDX module. I think you already know why I don't prefer it:
- Requiring demote in the fault handler. This requires an additional write lock
inside the mmu read lock, or TDX module changes. Although now I wonder if the interrupt error code related problems will get worse with this solution. The solution is currently not settled.
- Requiring passing args on the vCPU struct, which as you point out will work
functionally today only because the prefault stuff will avoid seeing it. But it's fragile
- The page size behavior is a bit implicit
I'm coming back to this draft after PUCK. Sean shared his thoughts there. I'll try to summarize. He didn't like how the page size requirements were passed through the fault handler in a "transient" way. That "transient" property covers both of the two options for passing the size info through the fault handler that we were debating. He also didn't like how TDX arch requires KVM to map at a specific host size around accept. Michael Roth brought up that SNP has the same requirement, but it can do the zap and refault approach.
We then discussed this lpage_info idea. He was in favor of it, but not, I'd say, overly enthusiastic. In a "least worst option" kind of way.
I think the biggest downside is the MMU write lock. Our goal for this series is to help performance, not to get huge page sizes. So if we do this idea, we can't fully waive our hands that any optimization is pre-mature. It *is* an optimization. We need to either convince ourselves that the overall benefit is still there, or have a plan to adopt the guest to avoid 4k accepts. Which we were previously discussing of requiring anyway.
But I much prefer the deterministic behavior of this approach from a maintainability perspective.
Quoted 30 lines
Quoted 30 lines
Quoted 9 lines
Or what about introducing a vendor hook in
__kvm_mmu_max_mapping_level()for a private fault?Quoted 3 lines
Maybe we could have EPT violations that contain 4k accept sizes first update the attribute for the GFN to be accepted or not, like have
tdx.ccall out to setkvm_lpage_info->disallow_lpagein the rarer case of 4k accept size? Or somethingSomething like
kvm_lpage_info->disallow_lpagewould disallow later page promotion, though we don't support it right now.Well I was originally thinking it would not set
kvm_lpage_info->disallow_lpagedirectly, but rely on the logic that checks for mixed attributes. But more below...Quoted 4 lines
Quoted 2 lines
like that. Maybe set a "accepted" attribute, or something. Not sure if could be
Setting "accepted" attribute in the EPT violation handler? It's a little odd, as the accept operation is not yet completed.
I guess the question in both of these comments is: what is the life cycle. Guest could call TDG.MEM.PAGE.RELEASE to unaccept it as well. Oh, geez. It looks like TDG.MEM.PAGE.RELEASE will give the same size hints in the EPT violation. So an accept attribute is not going work, at least without TDX module changes.
Actually, the problem we have doesn't fit the mixed attributes behavior. If many vCPU's accept at 2MB region at 4k page size, the entire 2MB range could be non- mixed and then individual accepts would fail.
Quoted 5 lines
Quoted 1 line
So instead there could be a
KVM_LPAGE_GUEST_INHIBITthat doesn't get clearedSet
KVM_LPAGE_GUEST_INHIBITvia a TDVMCALL ?Or just set the
KVM_LPAGE_GUEST_INHIBITwhen an EPT violation contains 4KB level info?
Yes, that's the idea. 2MB accepts can behave like normal.
Quoted 4 lines
I guess it's the latter one as it can avoid modification to both EDK2 and Linux guest. I observed ~2710 instances of "guest accepts at 4KB when KVM can map at 2MB" during the boot-up of a TD with 4GB memory.
Oh, wow that is more than I expected. Did you notice how many vCPUs they were spread across? What memory size did you use? What was your guest memory configuration?
Quoted 3 lines
But does it mean TDX needs to hold write
mmu_lockin the EPT violation handler and setKVM_LPAGE_GUEST_INHIBITon finding a violation carries 4KB level info?
I think so. I didn't check the reason, but the other similar code took it. Maybe not? If we don't need to take mmu write lock, then this idea seems like a clear winner to me.
Quoted 8 lines
Quoted 8 lines
based on mixed attributes. It would be one way. It would need to get set by something like
kvm_write_track_add_gfn()that lives intdx.cand is called before going into the fault handler on 4k accept size. It would have to take mmu write lock I think, which would kill scalability in the 4k accept case (but not the normal 2MB one). But as long asmmu_writelock is held, demote will be no problem, which the operation would also need to do.
Quoted 5 lines
Quoted 4 lines
I think it actually makes KVM's behavior easier to understand. We don't need to worry about races between multiple accept sizes and things like that. It also leaves the core MMU code mostly untouched. Performance/scalability wise it only punishes the rare case.
Write down my understanding to check if it's correct:
Will respond to this part on your later mail with corrections.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 24 lines · Rick P
Quoted 10 lines · Yan Zhao
Quoted 6 lines · Rick P
Quoted 2 lines · Yan Zhao
Could we provide the info via the
private_max_mapping_levelhook (i.e. viatdx_gmem_private_max_mapping_level())?This is one of the previous two methods discussed. Can you elaborate on what you are trying to say?
I don't get why we can't use the existing
tdx_gmem_private_max_mapping_level()to convey themax_levelinfo at which a vendor hopes a GFN to be mapped.Quoted 8 lines
Before TDX huge pages,
tdx_gmem_private_max_mapping_level()always returns 4KB; after TDX huge pages, it returns
- 4KB during the TD build stage
- at TD runtime: 4KB or 2MBWhy does KVM need to care how the vendor determines this
max_level? I think a vendor should have its freedom to decide based on software limitation, guest's wishes, hardware bugs or whatever.I don't see that big of a difference between "KVM" and "vendor". TDX code is KVM code. Just because it's in
tdx.cdoesn't mean it's ok for it to be hard to trace the logic.
Quoted 11 lines
I'm not sure what Sean's objection was to that approach, or if he objected to just the weird
SIZE_MISMATCHbehavior of TDX module. I think you already know why I don't prefer it:
- Requiring demote in the fault handler. This requires an additional write lock
inside the mmu read lock, or TDX module changes. Although now I wonder if the interrupt error code related problems will get worse with this solution. The solution is currently not settled.
- Requiring passing args on the vCPU struct, which as you point out will work
functionally today only because the prefault stuff will avoid seeing it. But it's fragile
- The page size behavior is a bit implicit
Hmm, strictly speaking, all the 3 are not the fault of tdx_gmem_private_max_mapping_level().
With tdx_gmem_private_max_mapping_level() to pass in the level, we can track KVM_LPAGE_GUEST_INHIBIT with tdx.c without changing lpage_info. tdx.c then has the freedom to change KVM_LPAGE_GUEST_INHIBIT to some more flexible scheme in future while keeping KVM MMU core intact.
But with lpage_info, looks we can save some memory.
The downside is that we may need to update TDX MMU core in case of future changes.
Quoted 60 lines
I'm coming back to this draft after PUCK. Sean shared his thoughts there. I'll try to summarize. He didn't like how the page size requirements were passed through the fault handler in a "transient" way. That "transient" property covers both of the two options for passing the size info through the fault handler that we were debating. He also didn't like how TDX arch requires KVM to map at a specific host size around accept. Michael Roth brought up that SNP has the same requirement, but it can do the zap and refault approach.
We then discussed this
lpage_infoidea. He was in favor of it, but not, I'd say, overly enthusiastic. In a "least worst option" kind of way.I think the biggest downside is the MMU write lock. Our goal for this series is to help performance, not to get huge page sizes. So if we do this idea, we can't fully waive our hands that any optimization is pre-mature. It *is* an optimization. We need to either convince ourselves that the overall benefit is still there, or have a plan to adopt the guest to avoid 4k accepts. Which we were previously discussing of requiring anyway.
But I much prefer the deterministic behavior of this approach from a maintainability perspective.
Quoted 30 lines
Quoted 30 lines
Quoted 9 lines
Or what about introducing a vendor hook in
__kvm_mmu_max_mapping_level()for a private fault?Quoted 3 lines
Maybe we could have EPT violations that contain 4k accept sizes first update the attribute for the GFN to be accepted or not, like have
tdx.ccall out to setkvm_lpage_info->disallow_lpagein the rarer case of 4k accept size? Or somethingSomething like
kvm_lpage_info->disallow_lpagewould disallow later page promotion, though we don't support it right now.Well I was originally thinking it would not set
kvm_lpage_info->disallow_lpagedirectly, but rely on the logic that checks for mixed attributes. But more below...Quoted 4 lines
Quoted 2 lines
like that. Maybe set a "accepted" attribute, or something. Not sure if could be
Setting "accepted" attribute in the EPT violation handler? It's a little odd, as the accept operation is not yet completed.
I guess the question in both of these comments is: what is the life cycle. Guest could call TDG.MEM.PAGE.RELEASE to unaccept it as well. Oh, geez. It looks like TDG.MEM.PAGE.RELEASE will give the same size hints in the EPT violation. So an accept attribute is not going work, at least without TDX module changes.
Actually, the problem we have doesn't fit the mixed attributes behavior. If many vCPU's accept at 2MB region at 4k page size, the entire 2MB range could be non- mixed and then individual accepts would fail.
Quoted 5 lines
Quoted 1 line
So instead there could be a
KVM_LPAGE_GUEST_INHIBITthat doesn't get clearedSet
KVM_LPAGE_GUEST_INHIBITvia a TDVMCALL ?Or just set the
KVM_LPAGE_GUEST_INHIBITwhen an EPT violation contains 4KB level info?Yes, that's the idea. 2MB accepts can behave like normal.
Quoted 1 line
Quoted 7 lines
Quoted 3 lines
I guess it's the latter one as it can avoid modification to both EDK2 and Linux guest. I observed ~2710 instances of "guest accepts at 4KB when KVM can map at 2MB" during the boot-up of a TD with 4GB memory.
Oh, wow that is more than I expected. Did you notice how many vCPUs they were spread across? What memory size did you use? What was your guest memory configuration?
The guest memory is 4GB, 8 vCPUs.
The memory slots layout is:
slot 1: base gfn=0, npages=0x80000
slot 2: base gfn=0x100000, npages=0x80000
slot 3: base gfn=0xffc00, npages=0x400
The GFN spread for the ~2710 instances is:
GFNs 0x806-0x9ff (1 time for each of 506 pages)
GFNs 0x7e800-0x7e9ff (1 time for each of 512 pages)
GFN: 0x7d3ff~0x7e7fe (repeated private-to-shared, and shared-to-private are
conducted on this range), with the top 3 among them being:
0x7d9da (476 times)
0x7d9d9 (156 times)
0x7d9d7 (974 times)All those instances are from vCPU 0, when the guest is in EDK2 and during early kernel boot.
Based on my observation, the count of these instances does not scale with guest memory. In other words, the count remains roughly the same even when the guest memory is increased to 8GB.
Quoted 6 lines
Quoted 2 lines
But does it mean TDX needs to hold write
mmu_lockin the EPT violation handler and setKVM_LPAGE_GUEST_INHIBITon finding a violation carries 4KB level info?I think so. I didn't check the reason, but the other similar code took it. Maybe not? If we don't need to take mmu write lock, then this idea seems like a clear winner to me.
Hmm, setting KVM_LPAGE_GUEST_INHIBIT needs trying splitting to be followed. So, if we don't want to support splitting under read mmu_lock, we need to take write mmu_lock.
I drafted a change as below (will refine some parts of it later). The average count to take write mmu_lock is 11 during VM boot.
There's no signiticant difference in the count of 2M mappings During guest kerne booting to login, on average:
before this patch: 1144 2M mappings after this patch: 1143 2M mappings.
arch/x86/kvm/mmu.h +4 -0
@@ -322,4 +322,8 @@ static inline bool kvm_is_gfn_alias(struct kvm *kvm, gfn_t gfn) {return gfn &kvm_gfn_direct_bits (kvm); } + +void hugepage_set_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level); +bool hugepage_test_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level); +#endif
arch/x86/kvm/mmu/mmu.c +19 -2
@@ -721,6 +721,8 @@ static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,*/ #define KVM_LPAGE_MIXED_FLAG BIT(31) +#define KVM_LPAGE_GUEST_INHIBIT_FLAG BIT(30) +static void update_gfn_disallow_lpage_count (const struct kvm_memory_slot *slot,gfn_t gfn,int count) {
@@ -732,7 +734,8 @@ static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot, old = linfo->disallow_lpage; linfo->disallow_lpage += count; -WARN_ON_ONCE ((old ^ linfo->disallow_lpage) &KVM_LPAGE_MIXED_FLAG ); +WARN_ON_ONCE ((old ^ linfo->disallow_lpage) & + (KVM_LPAGE_MIXED_FLAG |KVM_LPAGE_GUEST_INHIBIT_FLAG )); } }
@@ -1653,13 +1656,15 @@ int kvm_split_boundary_leafs(struct kvm *kvm, struct kvm_gfn_range *range)bool ret =0 ;lockdep_assert_once (kvm->mmu_invalidate_in_progress || -lockdep_is_held (&kvm->slots_lock)); +lockdep_is_held (&kvm->slots_lock) || +srcu_read_lock_held (&kvm->srcu));if (tdp_mmu_enabled) ret =kvm_tdp_mmu_gfn_range_split_boundary (kvm, range);return ret; } +EXPORT_SYMBOL_GPL (kvm_split_boundary_leafs);bool kvm_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range) {
@@ -7734,6 +7739,18 @@ void kvm_mmu_pre_destroy_vm(struct kvm *kvm)vhost_task_stop (kvm->arch.nx_huge_page_recovery_thread); } +bool hugepage_test_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level) +{ +return lpage_info_slot (gfn, slot, level)->disallow_lpage &KVM_LPAGE_GUEST_INHIBIT_FLAG ; +} +EXPORT_SYMBOL_GPL (hugepage_test_guest_inhibit); + +void hugepage_set_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level) +{ +lpage_info_slot (gfn, slot, level)->disallow_lpage |=KVM_LPAGE_GUEST_INHIBIT_FLAG ; +} +EXPORT_SYMBOL_GPL (hugepage_set_guest_inhibit); +#ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES static bool hugepage_test_mixed (struct kvm_memory_slot *slot,gfn_t gfn,int level)
arch/x86/kvm/vmx/tdx.c +42 -45
127 lines not on this page · raw message
virt/kvm/kvm_main.c +1 -0
@@ -2610,6 +2610,7 @@ struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfnreturn NULL ; } +EXPORT_SYMBOL_GPL (kvm_vcpu_gfn_to_memslot);bool kvm_is_visible_gfn (struct kvm *kvm,gfn_t gfn) {
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 27 lines · Yan Zhao
Quoted 11 lines · Rick P
Quoted 6 lines · Yan Zhao
Quoted 2 lines · Rick P
On Tue, 2025-06-24 at 17:57 +0800, Yan Zhao wrote:
I guess it's the latter one as it can avoid modification to both EDK2 and Linux guest. I observed ~2710 instances of "guest accepts at 4KB when KVM can map at 2MB" during the boot-up of a TD with 4GB memory.
Oh, wow that is more than I expected. Did you notice how many vCPUs they were spread across? What memory size did you use? What was your guest memory configuration?
The guest memory is 4GB, 8 vCPUs.
The memory slots layout is:
slot 1: base gfn=0, npages=0x80000
slot 2: base gfn=0x100000, npages=0x80000
slot 3: base gfn=0xffc00, npages=0x400The GFN spread for the ~2710 instances is:
GFNs 0x806-0x9ff (1 time for each of 506 pages)
GFNs 0x7e800-0x7e9ff (1 time for each of 512 pages)
GFN: 0x7d3ff~0x7e7fe (repeated private-to-shared, and shared-to-private areconducted on this range), with the top 3 among them being: 0x7d9da (476 times) 0x7d9d9 (156 times) 0x7d9d7 (974 times)
Quoted 6 lines
All those instances are from vCPU 0, when the guest is in EDK2 and during early kernel boot.
Based on my observation, the count of these instances does not scale with guest memory. In other words, the count remains roughly the same even when the guest memory is increased to 8GB.
So the impact would be negligible. The mmu write lock would not meet much, if any, contention.
Quoted 11 lines
Quoted 7 lines
Quoted 3 lines
But does it mean TDX needs to hold write
mmu_lockin the EPT violation handler and setKVM_LPAGE_GUEST_INHIBITon finding a violation carries 4KB level info?I think so. I didn't check the reason, but the other similar code took it. Maybe not? If we don't need to take mmu write lock, then this idea seems like a clear winner to me.
Hmm, setting
KVM_LPAGE_GUEST_INHIBITneeds trying splitting to be followed. So, if we don't want to support splitting under readmmu_lock, we need to take writemmu_lock.
Quoted 7 lines
I drafted a change as below (will refine some parts of it later). The average count to take write
mmu_lockis 11 during VM boot.There's no signiticant difference in the count of 2M mappings During guest kerne booting to login, on average:
before this patch: 1144 2M mappings after this patch: 1143 2M mappings.
Oh, hmm. Well, it's not strong argument against.
Quoted 155 lines
arch/x86/kvm/mmu.h +4
-0@@ -322,4 +322,8 @@ static inline bool kvm_is_gfn_alias(struct kvm *kvm, gfn_t gfn) {return gfn &kvm_gfn_direct_bits (kvm); } + +void hugepage_set_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level); +bool hugepage_test_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level); +#endif arch/x86/kvm/mmu/mmu.c +19
-2@@ -721,6 +721,8 @@ static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,*/ #define KVM_LPAGE_MIXED_FLAG BIT(31) +#define KVM_LPAGE_GUEST_INHIBIT_FLAG BIT(30) +static void update_gfn_disallow_lpage_count (const struct kvm_memory_slot *slot,gfn_t gfn,int count) {@@ -732,7 +734,8 @@ static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot, old = linfo->disallow_lpage; linfo->disallow_lpage += count; -WARN_ON_ONCE ((old ^ linfo->disallow_lpage) &KVM_LPAGE_MIXED_FLAG ); +WARN_ON_ONCE ((old ^ linfo->disallow_lpage) & + (KVM_LPAGE_MIXED_FLAG |KVM_LPAGE_GUEST_INHIBIT_FLAG )); } }@@ -1653,13 +1656,15 @@ int kvm_split_boundary_leafs(struct kvm *kvm, struct kvm_gfn_range *range)bool ret =0 ;lockdep_assert_once (kvm->mmu_invalidate_in_progress || -lockdep_is_held (&kvm->slots_lock)); +lockdep_is_held (&kvm->slots_lock) || +srcu_read_lock_held (&kvm->srcu));if (tdp_mmu_enabled) ret =kvm_tdp_mmu_gfn_range_split_boundary (kvm, range);return ret; } +EXPORT_SYMBOL_GPL (kvm_split_boundary_leafs);bool kvm_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range) {@@ -7734,6 +7739,18 @@ void kvm_mmu_pre_destroy_vm(struct kvm *kvm)vhost_task_stop (kvm->arch.nx_huge_page_recovery_thread); } +bool hugepage_test_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level) +{ +return lpage_info_slot (gfn, slot, level)->disallow_lpage &KVM_LPAGE_GUEST_INHIBIT_FLAG ; +} +EXPORT_SYMBOL_GPL (hugepage_test_guest_inhibit); + +void hugepage_set_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level) +{ +lpage_info_slot (gfn, slot, level)->disallow_lpage |=KVM_LPAGE_GUEST_INHIBIT_FLAG ; +} +EXPORT_SYMBOL_GPL (hugepage_set_guest_inhibit); +#ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES static bool hugepage_test_mixed (struct kvm_memory_slot *slot,gfn_t gfn,int level)arch/x86/kvm/vmx/tdx.c +25
-35@@ -1852,28 +1852,8 @@ int tdx_sept_split_private_spt(struct kvm *kvm, gfn_t gfn, enum pg_level level,if (KVM_BUG_ON (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE || level !=PG_LEVEL_2M , kvm))return -EINVAL ; -/* -* Split request with mmu_lock held for reading can only occur when one -* vCPU accepts at 2MB level while another vCPU accepts at 4KB level. -* Ignore this 4KB mapping request by setting violation_request_level to -* 2MB and returning -EBUSY for retry. Then the next fault at 2MB level -* would be a spurious fault. The vCPU accepting at 2MB will accept the -* whole 2MB range. -*/ -if (mmu_lock_shared) { -struct kvm_vcpu *vcpu =kvm_get_running_vcpu (); -struct vcpu_tdx *tdx =to_tdx (vcpu); - -if (KVM_BUG_ON (!vcpu, kvm)) -return -EOPNOTSUPP ; - -/* Request to map as 2MB leaf for the whole 2MB range */ - tdx->violation_gfn_start =gfn_round_for_level (gfn, level); - tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); - tdx->violation_request_level = level; - -return -EBUSY ; - } +if (mmu_lock_shared) +return -EOPNOTSUPP ; ret =tdx_sept_zap_private_spte (kvm, gfn, level, page);if (ret <=0 )@@ -1937,28 +1917,51 @@ static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcpreturn !(eq &EPT_VIOLATION_PROT_MASK ) && !(eq &EPT_VIOLATION_EXEC_FOR_RING3_LIN ); } -static inline void tdx_get_accept_level (struct kvm_vcpu *vcpu,gpa_t gpa) +static inline int tdx_check_accept_level (struct kvm_vcpu *vcpu,gpa_t gpa) {struct vcpu_tdx *tdx =to_tdx (vcpu); +struct kvm *kvm = vcpu->kvm; +gfn_t gfn =gpa_to_gfn (gpa); +struct kvm_memory_slot *slot =kvm_vcpu_gfn_to_memslot (vcpu, gfn);int level =-1 ; +u64 eeq_info; -u64 eeq_type = tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_TYPE_MASK ; +if (!slot) +return 0 ; -u32 eeq_info = (tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_INFO_MASK ) >> -TDX_EXT_EXIT_QUAL_INFO_SHIFT ; +if ((tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_TYPE_MASK ) != +TDX_EXT_EXIT_QUAL_TYPE_ACCEPT ) +return 0 ; -if (eeq_type ==TDX_EXT_EXIT_QUAL_TYPE_ACCEPT ) { - level = (eeq_info &GENMASK (2 ,0 )) +1 ; + eeq_info = (tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_INFO_MASK ) >> +TDX_EXT_EXIT_QUAL_INFO_SHIFT ; - tdx->violation_gfn_start =gfn_round_for_level (gpa_to_gfn (gpa), level); - tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); - tdx->violation_request_level = level; - }else { - tdx->violation_gfn_start =-1 ; - tdx->violation_gfn_end =-1 ; - tdx->violation_request_level =-1 ; + level = (eeq_info &GENMASK (2 ,0 )) +1 ; + +if (level ==PG_LEVEL_4K ) { +if (!hugepage_test_guest_inhibit (slot, gfn,PG_LEVEL_2M )) { +struct kvm_gfn_range gfn_range = { + .start = gfn, + .end = gfn +1 , + .slot = slot, + .may_block = true, + .attr_filter =KVM_FILTER_PRIVATE , + };
arch/x86/kvm/vmx/tdx.c static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcp · line 1959
Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10
-0+ + scoped_guard(write_lock, &kvm->mmu_lock) { +int ret; + + ret =kvm_split_boundary_leafs (kvm, &gfn_range); + +if (ret) +return ret; + +hugepage_set_guest_inhibit (slot, gfn,PG_LEVEL_2M );
Can you explain what you found regarding the write lock need? For most accept cases, we could fault in the PTE's on the read lock. And in the future we could have a demote that could work under read lock, as we talked. So kvm_split_boundary_leafs() often or could be unneeded or work under read lock when needed.
What is the problem in hugepage_set_guest_inhibit() that requires the write lock?
But in any case, it seems like we have *a* solution here. It doesn't seem like there are any big downsides. Should we close it?
Quoted 56 lines
arch/x86/kvm/vmx/tdx.c +7
-10+ } + } } + +return 0 ; }static int tdx_handle_ept_violation (struct kvm_vcpu *vcpu)@@ -1987,7 +1990,8 @@ static int tdx_handle_ept_violation(struct kvm_vcpu *vcpu)*/ exit_qual =EPT_VIOLATION_ACC_WRITE ; -tdx_get_accept_level (vcpu, gpa); +if (tdx_check_accept_level (vcpu, gpa)) +return RET_PF_RETRY ;/* Only private GPA triggers zero-step mitigation */ local_retry = true;@@ -3022,9 +3026,6 @@ static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx) vcpu->arch.mp_state =KVM_MP_STATE_RUNNABLE ; - tdx->violation_gfn_start =-1 ; - tdx->violation_gfn_end =-1 ; - tdx->violation_request_level =-1 ;return 0 ; free_tdcx:@@ -3373,14 +3374,9 @@ int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp)int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn,bool prefetch) { -struct vcpu_tdx *tdx =to_tdx (vcpu); - -if (unlikely ((to_kvm_tdx (vcpu->kvm)->state !=TD_STATE_RUNNABLE ) || prefetch)) +if (unlikely ((to_kvm_tdx (vcpu->kvm)->state !=TD_STATE_RUNNABLE )))return PG_LEVEL_4K ; -if (gfn >= tdx->violation_gfn_start && gfn < tdx->violation_gfn_end) -return tdx->violation_request_level; -return PG_LEVEL_2M ; }virt/kvm/kvm_main.c +1
-0@@ -2610,6 +2610,7 @@ struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfnreturn NULL ; } +EXPORT_SYMBOL_GPL (kvm_vcpu_gfn_to_memslot);bool kvm_is_visible_gfn (struct kvm *kvm,gfn_t gfn) {
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 219 lines · Rick P
Quoted 27 lines · Yan Zhao
Quoted 11 lines · Rick P
Quoted 6 lines · Yan Zhao
Quoted 2 lines · Rick P
On Tue, 2025-06-24 at 17:57 +0800, Yan Zhao wrote:
I guess it's the latter one as it can avoid modification to both EDK2 and Linux guest. I observed ~2710 instances of "guest accepts at 4KB when KVM can map at 2MB" during the boot-up of a TD with 4GB memory.
Oh, wow that is more than I expected. Did you notice how many vCPUs they were spread across? What memory size did you use? What was your guest memory configuration?
The guest memory is 4GB, 8 vCPUs.
The memory slots layout is:
slot 1: base gfn=0, npages=0x80000
slot 2: base gfn=0x100000, npages=0x80000
slot 3: base gfn=0xffc00, npages=0x400The GFN spread for the ~2710 instances is:
GFNs 0x806-0x9ff (1 time for each of 506 pages)
GFNs 0x7e800-0x7e9ff (1 time for each of 512 pages)
GFN: 0x7d3ff~0x7e7fe (repeated private-to-shared, and shared-to-private areconducted on this range), with the top 3 among them being: 0x7d9da (476 times) 0x7d9d9 (156 times) 0x7d9d7 (974 times)Quoted 6 lines
All those instances are from vCPU 0, when the guest is in EDK2 and during early kernel boot.
Based on my observation, the count of these instances does not scale with guest memory. In other words, the count remains roughly the same even when the guest memory is increased to 8GB.
So the impact would be negligible. The mmu write lock would not meet much, if any, contention.
Quoted 11 lines
Quoted 7 lines
Quoted 3 lines
But does it mean TDX needs to hold write
mmu_lockin the EPT violation handler and setKVM_LPAGE_GUEST_INHIBITon finding a violation carries 4KB level info?I think so. I didn't check the reason, but the other similar code took it. Maybe not? If we don't need to take mmu write lock, then this idea seems like a clear winner to me.
Hmm, setting
KVM_LPAGE_GUEST_INHIBITneeds trying splitting to be followed. So, if we don't want to support splitting under readmmu_lock, we need to take writemmu_lock.Quoted 7 lines
I drafted a change as below (will refine some parts of it later). The average count to take write
mmu_lockis 11 during VM boot.There's no signiticant difference in the count of 2M mappings During guest kerne booting to login, on average:
before this patch: 1144 2M mappings after this patch: 1143 2M mappings.Oh, hmm. Well, it's not strong argument against.
Quoted 160 lines
arch/x86/kvm/mmu.h +4
-0@@ -322,4 +322,8 @@ static inline bool kvm_is_gfn_alias(struct kvm *kvm, gfn_t gfn) {return gfn &kvm_gfn_direct_bits (kvm); } + +void hugepage_set_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level); +bool hugepage_test_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level); +#endif arch/x86/kvm/mmu/mmu.c +19
-2@@ -721,6 +721,8 @@ static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,*/ #define KVM_LPAGE_MIXED_FLAG BIT(31) +#define KVM_LPAGE_GUEST_INHIBIT_FLAG BIT(30) +static void update_gfn_disallow_lpage_count (const struct kvm_memory_slot *slot,gfn_t gfn,int count) {@@ -732,7 +734,8 @@ static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot, old = linfo->disallow_lpage; linfo->disallow_lpage += count; -WARN_ON_ONCE ((old ^ linfo->disallow_lpage) &KVM_LPAGE_MIXED_FLAG ); +WARN_ON_ONCE ((old ^ linfo->disallow_lpage) & + (KVM_LPAGE_MIXED_FLAG |KVM_LPAGE_GUEST_INHIBIT_FLAG )); } }@@ -1653,13 +1656,15 @@ int kvm_split_boundary_leafs(struct kvm *kvm, struct kvm_gfn_range *range)bool ret =0 ;lockdep_assert_once (kvm->mmu_invalidate_in_progress || -lockdep_is_held (&kvm->slots_lock)); +lockdep_is_held (&kvm->slots_lock) || +srcu_read_lock_held (&kvm->srcu));if (tdp_mmu_enabled) ret =kvm_tdp_mmu_gfn_range_split_boundary (kvm, range);return ret; } +EXPORT_SYMBOL_GPL (kvm_split_boundary_leafs);bool kvm_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range) {@@ -7734,6 +7739,18 @@ void kvm_mmu_pre_destroy_vm(struct kvm *kvm)vhost_task_stop (kvm->arch.nx_huge_page_recovery_thread); } +bool hugepage_test_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level) +{ +return lpage_info_slot (gfn, slot, level)->disallow_lpage &KVM_LPAGE_GUEST_INHIBIT_FLAG ; +} +EXPORT_SYMBOL_GPL (hugepage_test_guest_inhibit); + +void hugepage_set_guest_inhibit (struct kvm_memory_slot *slot,gfn_t gfn,int level) +{ +lpage_info_slot (gfn, slot, level)->disallow_lpage |=KVM_LPAGE_GUEST_INHIBIT_FLAG ; +} +EXPORT_SYMBOL_GPL (hugepage_set_guest_inhibit); +#ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES static bool hugepage_test_mixed (struct kvm_memory_slot *slot,gfn_t gfn,int level)arch/x86/kvm/vmx/tdx.c +30
-35@@ -1852,28 +1852,8 @@ int tdx_sept_split_private_spt(struct kvm *kvm, gfn_t gfn, enum pg_level level,if (KVM_BUG_ON (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE || level !=PG_LEVEL_2M , kvm))return -EINVAL ; -/* -* Split request with mmu_lock held for reading can only occur when one -* vCPU accepts at 2MB level while another vCPU accepts at 4KB level. -* Ignore this 4KB mapping request by setting violation_request_level to -* 2MB and returning -EBUSY for retry. Then the next fault at 2MB level -* would be a spurious fault. The vCPU accepting at 2MB will accept the -* whole 2MB range. -*/ -if (mmu_lock_shared) { -struct kvm_vcpu *vcpu =kvm_get_running_vcpu (); -struct vcpu_tdx *tdx =to_tdx (vcpu); - -if (KVM_BUG_ON (!vcpu, kvm)) -return -EOPNOTSUPP ; - -/* Request to map as 2MB leaf for the whole 2MB range */ - tdx->violation_gfn_start =gfn_round_for_level (gfn, level); - tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); - tdx->violation_request_level = level; - -return -EBUSY ; - } +if (mmu_lock_shared) +return -EOPNOTSUPP ; ret =tdx_sept_zap_private_spte (kvm, gfn, level, page);if (ret <=0 )@@ -1937,28 +1917,51 @@ static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcpreturn !(eq &EPT_VIOLATION_PROT_MASK ) && !(eq &EPT_VIOLATION_EXEC_FOR_RING3_LIN ); } -static inline void tdx_get_accept_level (struct kvm_vcpu *vcpu,gpa_t gpa) +static inline int tdx_check_accept_level (struct kvm_vcpu *vcpu,gpa_t gpa) {struct vcpu_tdx *tdx =to_tdx (vcpu); +struct kvm *kvm = vcpu->kvm; +gfn_t gfn =gpa_to_gfn (gpa); +struct kvm_memory_slot *slot =kvm_vcpu_gfn_to_memslot (vcpu, gfn);int level =-1 ; +u64 eeq_info; -u64 eeq_type = tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_TYPE_MASK ; +if (!slot) +return 0 ; -u32 eeq_info = (tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_INFO_MASK ) >> -TDX_EXT_EXIT_QUAL_INFO_SHIFT ; +if ((tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_TYPE_MASK ) != +TDX_EXT_EXIT_QUAL_TYPE_ACCEPT ) +return 0 ; -if (eeq_type ==TDX_EXT_EXIT_QUAL_TYPE_ACCEPT ) { - level = (eeq_info &GENMASK (2 ,0 )) +1 ; + eeq_info = (tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_INFO_MASK ) >> +TDX_EXT_EXIT_QUAL_INFO_SHIFT ; - tdx->violation_gfn_start =gfn_round_for_level (gpa_to_gfn (gpa), level); - tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); - tdx->violation_request_level = level; - }else { - tdx->violation_gfn_start =-1 ; - tdx->violation_gfn_end =-1 ; - tdx->violation_request_level =-1 ; + level = (eeq_info &GENMASK (2 ,0 )) +1 ; + +if (level ==PG_LEVEL_4K ) { +if (!hugepage_test_guest_inhibit (slot, gfn,PG_LEVEL_2M )) { +struct kvm_gfn_range gfn_range = { + .start = gfn, + .end = gfn +1 , + .slot = slot, + .may_block = true, + .attr_filter =KVM_FILTER_PRIVATE , + }; + + scoped_guard(write_lock, &kvm->mmu_lock) { +int ret; + + ret =kvm_split_boundary_leafs (kvm, &gfn_range);
Quoted 8 lines
arch/x86/kvm/vmx/tdx.c static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcp · line 1959
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5
-0+ +if (ret) +return ret; + +hugepage_set_guest_inhibit (slot, gfn,PG_LEVEL_2M );Can you explain what you found regarding the write lock need?
Here, the write lock protects 2 steps:
(1) update lpage_info.
(2) try splitting if there's any existing 2MB mapping.
The write mmu_lock is needed because lpage_info is read under read mmu_lock in kvm_tdp_mmu_map().
kvm_tdp_mmu_map
kvm_mmu_hugepage_adjust
kvm_lpage_info_max_mapping_level
If we update the lpage_info with read mmu_lock, the other vCPUs may map at a stale 2MB level even after lpage_info is updated by hugepage_set_guest_inhibit().
Therefore, we must perform splitting under the write mmu_lock to ensure there are no 2MB mappings after hugepage_set_guest_inhibit().
Otherwise, during later mapping in __vmx_handle_ept_violation(), splitting at fault path could be triggered as KVM MMU finds the goal level is 4KB while an existing 2MB mapping is present.
Quoted 2 lines
For most accept
cases, we could fault in the PTE's on the read lock. And in the future we could
The actual mapping at 4KB level is still with read mmu_lock in __vmx_handle_ept_violation().
Quoted 3 lines
have a demote that could work under read lock, as we talked. So
kvm_split_boundary_leafs()often or could be unneeded or work under read lock when needed.
Could we leave the "demote under read lock" as a future optimization?
Quoted 2 lines
What is the problem in
hugepage_set_guest_inhibit()that requires the write lock?
As above, to avoid the other vCPUs reading stale mapping level and splitting under read mmu_lock.
As guest_inhibit is set one-way, we could test it using hugepage_test_guest_inhibit() without holding the lock. The chance to hold write mmu_lock for hugepage_set_guest_inhibit() is then greatly reduced. (in my testing, 11 during VM boot).
Quoted 2 lines
But in any case, it seems like we have *a* solution here. It doesn't seem like there are any big downsides. Should we close it?
I think it's good, as long as Sean doesn't disagree :)
Quoted 57 lines
Quoted 56 lines
arch/x86/kvm/vmx/tdx.c +7
-10+ } + } } + +return 0 ; }static int tdx_handle_ept_violation (struct kvm_vcpu *vcpu)@@ -1987,7 +1990,8 @@ static int tdx_handle_ept_violation(struct kvm_vcpu *vcpu)*/ exit_qual =EPT_VIOLATION_ACC_WRITE ; -tdx_get_accept_level (vcpu, gpa); +if (tdx_check_accept_level (vcpu, gpa)) +return RET_PF_RETRY ;/* Only private GPA triggers zero-step mitigation */ local_retry = true;@@ -3022,9 +3026,6 @@ static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx) vcpu->arch.mp_state =KVM_MP_STATE_RUNNABLE ; - tdx->violation_gfn_start =-1 ; - tdx->violation_gfn_end =-1 ; - tdx->violation_request_level =-1 ;return 0 ; free_tdcx:@@ -3373,14 +3374,9 @@ int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp)int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn,bool prefetch) { -struct vcpu_tdx *tdx =to_tdx (vcpu); - -if (unlikely ((to_kvm_tdx (vcpu->kvm)->state !=TD_STATE_RUNNABLE ) || prefetch)) +if (unlikely ((to_kvm_tdx (vcpu->kvm)->state !=TD_STATE_RUNNABLE )))return PG_LEVEL_4K ; -if (gfn >= tdx->violation_gfn_start && gfn < tdx->violation_gfn_end) -return tdx->violation_request_level; -return PG_LEVEL_2M ; }virt/kvm/kvm_main.c +1
-0@@ -2610,6 +2610,7 @@ struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfnreturn NULL ; } +EXPORT_SYMBOL_GPL (kvm_vcpu_gfn_to_memslot);bool kvm_is_visible_gfn (struct kvm *kvm,gfn_t gfn) {
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 16 lines · Yan Zhao
Quoted 1 line
Can you explain what you found regarding the write lock need?
Here, the write lock protects 2 steps:
(1) updatelpage_info.
(2) try splitting if there's any existing 2MB mapping.The write
mmu_lockis needed becauselpage_infois read under readmmu_lockinkvm_tdp_mmu_map().
kvm_tdp_mmu_map
kvm_mmu_hugepage_adjust
kvm_lpage_info_max_mapping_levelIf we update the
lpage_infowith readmmu_lock, the other vCPUs may map at a stale 2MB level even afterlpage_infois updated byhugepage_set_guest_inhibit().
Quoted 6 lines
Therefore, we must perform splitting under the write
mmu_lockto ensure there are no 2MB mappings afterhugepage_set_guest_inhibit().Otherwise, during later mapping in
__vmx_handle_ept_violation(), splitting at fault path could be triggered as KVM MMU finds the goal level is 4KB while an existing 2MB mapping is present.
It could be?
1. mmu read lock
2. update lpage_info
3. mmu write lock upgrade
4. demote
5. mmu unlock
Then (3) could be skipped in the case of ability to demote under read lock?
I noticed that the other lpage_info updaters took mmu write lock, and I wasn't sure why. We shouldn't take a lock that we don't actually need just for safety margin or to copy other code.
Quoted 6 lines
Quoted 5 lines
For most accept
cases, we could fault in the PTE's on the read lock. And in the future we could
Quoted 8 lines
The actual mapping at 4KB level is still with read
mmu_lockin__vmx_handle_ept_violation().Quoted 4 lines
have a demote that could work under read lock, as we talked. So
kvm_split_boundary_leafs()often or could be unneeded or work under read lock
when needed.Could we leave the "demote under read lock" as a future optimization?
We could add it to the list. If we have a TDX module that supports demote with a single SEAMCALL then we don't have the rollback problem. The optimization could utilize that. That said, we should focus on the optimizations that make the biggest difference to real TDs. Your data suggests this might not be the case today.
Quoted 6 lines
Quoted 4 lines
What is the problem in
hugepage_set_guest_inhibit()that requires the write lock?As above, to avoid the other vCPUs reading stale mapping level and splitting under read
mmu_lock.
We need mmu write lock for demote, but as long as the order is:
1. set lpage_info
2. demote if needed
3. go to fault handler
Then (3) should have what it needs even if another fault races (1).
Quoted 11 lines
As
guest_inhibitis set one-way, we could test it usinghugepage_test_guest_inhibit()without holding the lock. The chance to hold writemmu_lockforhugepage_set_guest_inhibit()is then greatly reduced. (in my testing, 11 during VM boot).Quoted 3 lines
But in any case, it seems like we have *a* solution here. It doesn't seem like
there are any big downsides. Should we close it?I think it's good, as long as Sean doesn't disagree :)
He seemed onboard. Let's close it. We can even discuss lpage_info update locking on v2.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 31 lines · Rick P
Quoted 16 lines · Yan Zhao
Quoted 1 line
Can you explain what you found regarding the write lock need?
Here, the write lock protects 2 steps:
(1) updatelpage_info.
(2) try splitting if there's any existing 2MB mapping.The write
mmu_lockis needed becauselpage_infois read under readmmu_lockinkvm_tdp_mmu_map().
kvm_tdp_mmu_map
kvm_mmu_hugepage_adjust
kvm_lpage_info_max_mapping_levelIf we update the
lpage_infowith readmmu_lock, the other vCPUs may map at a stale 2MB level even afterlpage_infois updated byhugepage_set_guest_inhibit().Quoted 6 lines
Therefore, we must perform splitting under the write
mmu_lockto ensure there are no 2MB mappings afterhugepage_set_guest_inhibit().Otherwise, during later mapping in
__vmx_handle_ept_violation(), splitting at fault path could be triggered as KVM MMU finds the goal level is 4KB while an existing 2MB mapping is present.It could be?
1. mmu read lock
2. updatelpage_info
3. mmu write lock upgrade
4. demote
5. mmu unlock
Quoted 5 lines
Then (3) could be skipped in the case of ability to demote under read lock?
I noticed that the other
lpage_infoupdaters took mmu write lock, and I wasn't sure why. We shouldn't take a lock that we don't actually need just for safety margin or to copy other code.
Use write mmu_lock is of reason.
In the 3 steps,
1. set lpage_info
2. demote if needed
3. go to fault handler
Step 2 requires holding write mmu_lock before invoking kvm_split_boundary_leafs(). The write mmu_lock is also possible to get dropped and re-acquired in kvm_split_boundary_leafs() for purpose like memory allocation.
If 1 is with read mmu_lock, the other vCPUs is still possible to fault in at 2MB level after the demote in step 2.
Luckily, current TDX doesn't support promotion now.
But we can avoid wading into this complex situation by holding write mmu_lock in 1.
Quoted 11 lines
Quoted 11 lines
Quoted 3 lines
For most accept
cases, we could fault in the PTE's on the read lock. And in the future we couldThe actual mapping at 4KB level is still with read
mmu_lockin__vmx_handle_ept_violation().Quoted 4 lines
have a demote that could work under read lock, as we talked. So
kvm_split_boundary_leafs()often or could be unneeded or work under read lock
when needed.
Quoted 7 lines
Quoted 1 line
Could we leave the "demote under read lock" as a future optimization?
We could add it to the list. If we have a TDX module that supports demote with a single SEAMCALL then we don't have the rollback problem. The optimization could utilize that. That said, we should focus on the optimizations that make the biggest difference to real TDs. Your data suggests this might not be the case today.
Ok.
Quoted 11 lines
Quoted 4 lines
Quoted 2 lines
What is the problem in
hugepage_set_guest_inhibit()that requires the write lock?As above, to avoid the other vCPUs reading stale mapping level and splitting under read
mmu_lock.We need mmu write lock for demote, but as long as the order is:
1. setlpage_info
2. demote if needed
3. go to fault handlerThen (3) should have what it needs even if another fault races (1).
See the above comment for why we need to hold write mmu_lock for 1.
Besides, as we need write mmu_lock anyway for 2 (i.e. hold write mmu_lock before walking the SPTEs to check if there's any existing mapping), I don't see any performance impact by holding write mmu_lock for 1.
Quoted 6 lines
Quoted 6 lines
As
guest_inhibitis set one-way, we could test it usinghugepage_test_guest_inhibit()without holding the lock. The chance to hold writemmu_lockforhugepage_set_guest_inhibit()is then greatly reduced. (in my testing, 11 during VM boot).
Quoted 7 lines
Quoted 4 lines
Quoted 3 lines
But in any case, it seems like we have *a* solution here. It doesn't seem like
there are any big downsides. Should we close it?I think it's good, as long as Sean doesn't disagree :)
He seemed onboard. Let's close it. We can even discuss
lpage_infoupdate locking on v2.
Ok. I'll use write mmu_lock for updating lpage_info in v2 first.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 19 lines · Yan Zhao
Quoted 7 lines
Then (3) could be skipped in the case of ability to demote under read lock?
I noticed that the other
lpage_infoupdaters took mmu write lock, and I wasn't
sure why. We shouldn't take a lock that we don't actually need just for safety
margin or to copy other code.Use write
mmu_lockis of reason.In the 3 steps,
1. setlpage_info
2. demote if needed
3. go to fault handlerStep 2 requires holding write
mmu_lockbefore invokingkvm_split_boundary_leafs().
The writemmu_lockis also possible to get dropped and re-acquired inkvm_split_boundary_leafs()for purpose like memory allocation.
Quoted 6 lines
If 1 is with read
mmu_lock, the other vCPUs is still possible to fault in at 2MB
level after the demote in step 2.
Luckily, current TDX doesn't support promotion now.
But we can avoid wading into this complex situation by holding writemmu_lockin 1.
I don't think because some code might race in the future is a good reason to take the write lock.
Quoted 37 lines
Quoted 15 lines
Quoted 6 lines
Quoted 5 lines
For most accept
cases, we could fault in the PTE's on the read lock. And in the future we
couldQuoted 8 lines
The actual mapping at 4KB level is still with read
mmu_lockin__vmx_handle_ept_violation().Quoted 4 lines
have a demote that could work under read lock, as we talked. So
kvm_split_boundary_leafs()often or could be unneeded or work under read lock
when needed.Could we leave the "demote under read lock" as a future optimization?
Quoted 8 lines
We could add it to the list. If we have a TDX module that supports demote with a
single SEAMCALL then we don't have the rollback problem. The optimization could
utilize that. That said, we should focus on the optimizations that make the biggest difference to real TDs. Your data suggests this might not be the case
today.Ok.
Quoted 12 lines
Quoted 6 lines
Quoted 3 lines
What is the problem in
hugepage_set_guest_inhibit()that requires the write
lock?As above, to avoid the other vCPUs reading stale mapping level and splitting
under readmmu_lock.We need mmu write lock for demote, but as long as the order is:
1. setlpage_info
2. demote if needed
3. go to fault handler
Quoted 7 lines
Quoted 1 line
Then (3) should have what it needs even if another fault races (1).
See the above comment for why we need to hold write
mmu_lockfor 1.Besides, as we need write
mmu_lockanyway for 2 (i.e. hold writemmu_lockbefore
walking the SPTEs to check if there's any existing mapping), I don't see any performance impact by holding writemmu_lockfor 1.
It's maintainability problem too. Someday someone may want to remove it and scratch their head for what race they are missing.
Quoted 12 lines
Quoted 12 lines
Quoted 12 lines
As
guest_inhibitis set one-way, we could test it usinghugepage_test_guest_inhibit()without holding the lock. The chance to hold writemmu_lockforhugepage_set_guest_inhibit()is then greatly reduced. (in my testing, 11 during VM boot).Quoted 4 lines
But in any case, it seems like we have *a* solution here. It doesn't seem
like
there are any big downsides. Should we close it?
Quoted 6 lines
Quoted 5 lines
Quoted 1 line
I think it's good, as long as Sean doesn't disagree :)
He seemed onboard. Let's close it. We can even discuss
lpage_infoupdate locking
on v2.Ok. I'll use write
mmu_lockfor updatinglpage_infoin v2 first.
Specifically, why do the other lpage_info updating functions take mmu write lock. Are you sure there is no other reason?
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 27 lines · Rick P
Quoted 19 lines · Yan Zhao
Quoted 7 lines
Then (3) could be skipped in the case of ability to demote under read lock?
I noticed that the other
lpage_infoupdaters took mmu write lock, and I wasn't
sure why. We shouldn't take a lock that we don't actually need just for safety
margin or to copy other code.Use write
mmu_lockis of reason.In the 3 steps,
1. setlpage_info
2. demote if needed
3. go to fault handlerStep 2 requires holding write
mmu_lockbefore invokingkvm_split_boundary_leafs().
The writemmu_lockis also possible to get dropped and re-acquired inkvm_split_boundary_leafs()for purpose like memory allocation.Quoted 6 lines
If 1 is with read
mmu_lock, the other vCPUs is still possible to fault in at 2MB
level after the demote in step 2.
Luckily, current TDX doesn't support promotion now.
But we can avoid wading into this complex situation by holding writemmu_lockin 1.
Quoted 2 lines
I don't think because some code might race in the future is a good reason to take the write lock.
I still prefer to hold write mmu_lock right now.
Otherwise, we at least need to convert disallow_lpage to atomic variable and updating it via an atomic way, e.g. cmpxchg.
struct kvm_lpage_info {
int disallow_lpage;
};Quoted 39 lines
Quoted 39 lines
Quoted 14 lines
Quoted 5 lines
Quoted 4 lines
For most accept
cases, we could fault in the PTE's on the read lock. And in the future we
couldQuoted 8 lines
The actual mapping at 4KB level is still with read
mmu_lockin__vmx_handle_ept_violation().Quoted 4 lines
have a demote that could work under read lock, as we talked. So
kvm_split_boundary_leafs()often or could be unneeded or work under read lock
when needed.Could we leave the "demote under read lock" as a future optimization?
Quoted 8 lines
We could add it to the list. If we have a TDX module that supports demote with a
single SEAMCALL then we don't have the rollback problem. The optimization could
utilize that. That said, we should focus on the optimizations that make the biggest difference to real TDs. Your data suggests this might not be the case
today.Ok.
Quoted 7 lines
Quoted 6 lines
Quoted 3 lines
What is the problem in
hugepage_set_guest_inhibit()that requires the write
lock?As above, to avoid the other vCPUs reading stale mapping level and splitting
under readmmu_lock.Quoted 6 lines
We need mmu write lock for demote, but as long as the order is:
1. setlpage_info
2. demote if needed
3. go to fault handlerThen (3) should have what it needs even if another fault races (1).
See the above comment for why we need to hold write
mmu_lockfor 1.
Quoted 7 lines
Quoted 4 lines
Besides, as we need write
mmu_lockanyway for 2 (i.e. hold writemmu_lockbefore
walking the SPTEs to check if there's any existing mapping), I don't see any performance impact by holding writemmu_lockfor 1.It's maintainability problem too. Someday someone may want to remove it and scratch their head for what race they are missing.
I don't get why holding write mmu_lock will cause maintainability problem. In contrast, if we want to use read mmu_lock in future, we need to carefully check if there's any potential risk.
Quoted 12 lines
Quoted 12 lines
Quoted 12 lines
Quoted 11 lines
As
guest_inhibitis set one-way, we could test it usinghugepage_test_guest_inhibit()without holding the lock. The chance to hold writemmu_lockforhugepage_set_guest_inhibit()is then greatly reduced. (in my testing, 11 during VM boot).Quoted 4 lines
But in any case, it seems like we have *a* solution here. It doesn't seem
like
there are any big downsides. Should we close it?I think it's good, as long as Sean doesn't disagree :)
Quoted 7 lines
Quoted 4 lines
Quoted 3 lines
He seemed onboard. Let's close it. We can even discuss
lpage_infoupdate locking
on v2.Ok. I'll use write
mmu_lockfor updatinglpage_infoin v2 first.Specifically, why do the other
lpage_infoupdating functions take mmu write lock. Are you sure there is no other reason?
1. The read mmu_lock can't prevent the other vCPUs from reading stale lpage_info.
2. Shadow code in KVM MMU only holds write mmu_lock, so it updates lpage_info with write mmu_lock.
3. lpage_info is not updated atomically. If there're two vCPUs updating lpage_info concurrently, lpage_info may hold an invalid value.
4. lpage_info is not updated in performance critical paths. No need to hold read mmu_lock.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 11 lines · Yan Zhao
Quoted 2 lines
I don't think because some code might race in the future is a good reason to take the write lock.
I still prefer to hold write
mmu_lockright now.Otherwise, we at least need to convert
disallow_lpageto atomic variable and updating it via an atomic way, e.g. cmpxchg.struct
kvm_lpage_info{
intdisallow_lpage;
};
This seems like a valid reason. I wanted to make sure there was some reason, besides it feels safer.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
In reply to Edgecombe, Rick PQuoted 6 lines · Rick P
Quoted 6 lines
Quoted 6 lines
We need mmu write lock for demote, but as long as the order is:
1. setlpage_info
2. demote if needed
3. go to fault handlerThen (3) should have what it needs even if another fault races (1).
For now I implemented the sequence as
1. check lpage_info, if 2MB is already disabled for a GFN, goto 3.
2. if 2MB is not disabled,
2.1 acquire write mmu_lock
2.2 split the GFN mapping and kvm_flush_remote_tlbs() if split is performed 2.3 update lpage_info to disable 2MB for the GFN
2.4 release write mmu_lock
3. fault handler for the GFN
Note: write mmu_lock is held during 2.2 successfully splitting a huge GFN entry and 2.3. So, it can guarantee that there's no 2MB mapping for the GFN after 2.3.
Step 1 can help reduce the count of write mmu_lock from 17626 to 11.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
In reply to Edgecombe, Rick PQuoted 5 lines · Rick P
...
For leaving the option open to promote the GFNs in the future, a GHCI interface or similar could be defined for the guest to say "I don't care about page size anymore for this gfn". So it won't close it off forever.
I think it's in the host's interest to get the pages mapped at large page granularity whenever possible. Even if guest doesn't buy-in into the "future" GHCI interface, there should be some ABI between TDX module and host VMM to allow promotion probably as soon as all the ranges within a hugepage get accepted but are still mapped at 4K granularity.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 8 lines · Vishal Annapurve
Quoted 5 lines · Rick P
...
For leaving the option open to promote the GFNs in the future, a GHCI interface or similar could be defined for the guest to say "I don't care about page size anymore for this gfn". So it won't close it off forever.
Quoted 6 lines
I think it's in the host's interest to get the pages mapped at large page granularity whenever possible. Even if guest doesn't buy-in into the "future" GHCI interface, there should be some ABI between TDX module and host VMM to allow promotion probably as soon as all the ranges within a hugepage get accepted but are still mapped at 4K granularity.
In the 4k accept size, the guest is kind of requesting a specific host page size. I agree it's not good to let the guest influence the host's resource usage. But this already happens with private/shared conversions.
As for future promotion opportunities, I think that part needs a re-think. I don't think cost/benefit is really there today. If we had a simpler solution (we discussed some TDX module changes offline), then it changes the calculus. But we shouldn't focus too much on the ideal TDX implementation. Getting the ideal case upstream is far, far away. In the meantime we should focus on the simplest things with the most benefit. In the end I'd expect an iterative, evolving implementation to be faster to upstream then thinking through how it works with every idea. The exception is thinking through a sane ABI ahead of time.
I don't think we necessarily need a GHCI interface to expose control of host page sizes to the guest, but I think it might help with determinism. I meant it sort of as an escape hatch. Like if we find some nasty races that prevent optimizations for promotion, we could have an option to have the guest help by making the ABI around page sizes more formal.
Side topic on page promotion, I'm wondering if the biggest bang-for-the-buck promotion opportunity will be the memory that gets added via PAGE.ADD at TD startup time. Which is a narrow specific case that may be easier to attack.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
In reply to Yan ZhaoQuoted 4 lines · Yan Zhao
Quoted 3 lines
hopefully is just handling accepting a whole range that is not 2MB aligned. But
I think we need to verify this more.Ok.
In Linux guest if a memory region is not 2MB aligned the guest will accept the ends at 4k size. If a memory region is identical to a memslot range this will be fine. KVM will map the ends at 4k because it won't let huge pages span a memslot. But if several memory regions are not 2MB aligned and are covered by one large memslot, the accept will fail on the 4k ends under this proposal. I don't know if this is a common configuration, but to cover it in the TDX guest may not be trivial.
So I think this will only work if guests can reasonably "merge" all of the adjacent accepts. Or of we declare a bunch of memory/memslot layouts illegal.
Kirill, how difficult would it be for TDX Linux guest to merge all 2MB adjacent accepts?
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 14 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 3 lines
hopefully is just handling accepting a whole range that is not 2MB aligned. But
I think we need to verify this more.Ok.
In Linux guest if a memory region is not 2MB aligned the guest will accept the ends at 4k size. If a memory region is identical to a memslot range this will be fine. KVM will map the ends at 4k because it won't let huge pages span a memslot. But if several memory regions are not 2MB aligned and are covered by one large memslot, the accept will fail on the 4k ends under this proposal. I don't know if this is a common configuration, but to cover it in the TDX guest may not be trivial.
Quoted 5 lines
So I think this will only work if guests can reasonably "merge" all of the adjacent accepts. Or of we declare a bunch of memory/memslot layouts illegal.
Kirill, how difficult would it be for TDX Linux guest to merge all 2MB adjacent accepts?
Hm. What do you mean by merging?
Kernel only accepts <4k during early boot -- in EFI stub. The bitmap we use to track unaccepted memory tracks the status in 2M granularity and all later accept requests will be issues on 2M pages with fallback to 4k.
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Sean Christopherson
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 8 lines · Kirill Shutemov
Quoted 7 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 3 lines
hopefully is just handling accepting a whole range that is not 2MB aligned. But
I think we need to verify this more.Ok.
In Linux guest if a memory region is not 2MB aligned the guest will accept the
What is a "memory region" in this context? An e820 region? Something else?
Quoted 21 lines
Quoted 7 lines
ends at 4k size. If a memory region is identical to a memslot range this will be fine. KVM will map the ends at 4k because it won't let huge pages span a memslot. But if several memory regions are not 2MB aligned and are covered by one large memslot, the accept will fail on the 4k ends under this proposal. I don't know if this is a common configuration, but to cover it in the TDX guest may not be trivial.
Quoted 5 lines
So I think this will only work if guests can reasonably "merge" all of the adjacent accepts. Or of we declare a bunch of memory/memslot layouts illegal.
Kirill, how difficult would it be for TDX Linux guest to merge all 2MB adjacent accepts?
Hm. What do you mean by merging?
Kernel only accepts <4k during early boot -- in EFI stub. The bitmap we use to track unaccepted memory tracks the status in 2M granularity and all later accept requests will be issues on 2M pages with fallback to 4k.
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 11 lines · Sean Christopherson
Quoted 8 lines · Kirill Shutemov
Quoted 7 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 3 lines
hopefully is just handling accepting a whole range that is not 2MB aligned. But
I think we need to verify this more.Ok.
In Linux guest if a memory region is not 2MB aligned the guest will accept the
What is a "memory region" in this context? An e820 region? Something else?
EFI memory map entry.
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Sean Christopherson
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 7 lines · Kirill Shutemov
Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Kirill Shutemov
Quoted 4 lines · Rick P
Quoted 3 lines · Yan Zhao
Quoted 3 lines
hopefully is just handling accepting a whole range that is not 2MB aligned. But
I think we need to verify this more.
Quoted 7 lines
Quoted 5 lines
Quoted 3 lines
Quoted 3 lines
Quoted 1 line
Ok.
In Linux guest if a memory region is not 2MB aligned the guest will accept the
What is a "memory region" in this context? An e820 region? Something else?
EFI memory map entry.
I forget, for TDX, is the EFI map built by guest firmware or by the VMM?
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 10 lines · Sean Christopherson
Quoted 9 lines · Kirill Shutemov
Quoted 8 lines · Sean Christopherson
Quoted 7 lines · Kirill Shutemov
Quoted 6 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 3 lines
hopefully is just handling accepting a whole range that is not 2MB aligned. But
I think we need to verify this more.Ok.
Quoted 7 lines
Quoted 5 lines
Quoted 3 lines
Quoted 1 line
Quoted 1 line
In Linux guest if a memory region is not 2MB aligned the guest will accept the
What is a "memory region" in this context? An e820 region? Something else?
EFI memory map entry.
I forget, for TDX, is the EFI map built by guest firmware or by the VMM?
Guest BIOS.
The BIOS would accept some memory on its own (typically the first 4G) and leave the rest to be accepted by OS. EFI boot services can also accept memory on OS request (e.g. on memory allocation), updating the map.
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
In reply to Sean ChristophersonQuoted 46 lines · Sean Christopherson
Quoted 7 lines · Kai Huang
Quoted 6 lines · Yan Y
Quoted 5 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 4 lines
On the opposite, if other non-Linux TDs don't follow 1G->2M->4K accept order, e.g., they always accept 4K, there could be *endless EPT violation* if I understand your words correctly.
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
Isn't this yet-another reason we should choose to return
PG_LEVEL_4Kinstead of 2M if no accept level is provided in the fault?As I said, returning
PG_LEVEL_4Kwould disallow huge pages for non-Linux TDs. TD's accept operations at size > 4KB will getTDACCEPT_SIZE_MISMATCH.
TDX_PAGE_SIZE_MISMATCHis a valid error code that the guest should handle. The docs say the VMM needs to demote *if* the mapping is large and the accept size is small.No thanks, fix the spec and the TDX Module. Punting an error to the VMM is inconsistent, convoluted, and inefficient.
Per "Table 8.2: TDG.MEM.PAGE.ACCEPT SEPT Walk Cases":
S-EPT state ACCEPT vs. Mapping Size Behavior Leaf SEPT_PRESENT Smaller TDACCEPT_SIZE_MISMATCH Leaf !SEPT_PRESENT Smaller EPT Violation <=========================| Leaf DONT_CARE Same Success | => THESE TWO SHOULD MATCH!!! !Leaf SEPT_FREE Larger EPT Violation, BECAUSE THERE'S NO PAGE | !Leaf SEPT_FREE Larger TDACCEPT_SIZE_MISMATCH <================|If ACCEPT is "too small", an EPT violation occurs. But if ACCEPT is "too big", a
TDACCEPT_SIZE_MISMATCHerror occurs. That's asinine.The only reason that comes to mind for punting the "too small" case to the VMM is to try and keep the guest alive if the VMM is mapping more memory than has been enumerated to the guest. E.g. if the guest suspects the VMM is malicious or buggy. IMO, that's a terrible reason to push this much complexity into the host. It also risks godawful boot times, e.g. if the guest kernel is buggy and accepts everything at 4KiB granularity.
The TDX Module should return
TDACCEPT_SIZE_MISMATCHand force the guest to take action, not force the hypervisor to limp along in a degraded state. If the guest doesn't want to ACCEPT at a larger granularity, e.g. because it doesn't think the entire 2MiB/1GiB region is available, then the guest can either log a warning and "poison" the page(s), or terminate and refuse to boot.
Quoted 3 lines
If for some reason the guest _can't_ ACCEPT at larger granularity, i.e. if the guest _knows_ that 2MiB or 1GiB is available/usable but refuses to ACCEPT at the appropriate granularity, then IMO that's firmly a guest bug.
It might just be guest doesn't want to accept a larger level instead of can't. Use case see below.
Quoted 4 lines
If there's a *legitimate* use case where the guest wants to ACCEPT a subset of memory, then there should be an explicit TDCALL to request that the unwanted regions of memory be unmapped. Smushing everything into implicit behavior has obvioulsy created a giant mess.
Isn't the ACCEPT with a specific level explicit? Note that ACCEPT is not only for the case that VMM has already mapped page and guest only needs to accept it to make it available, it also works for the case that guest requests VMM to map the page for a gpa (at specific level) then guest accepts it.
Even for the former case, it is understandable for behaving differently for the "too small" and "too big" case. If the requested accept level is "too small", VMM can handle it by demoting the page to satisfy guest. But when the level is "too big", usually the VMM cannot map the page at a higher level so that ept violation cannot help. I admit that it leads to the requirement that VMM should always try to map the page at the highest available level, if the EPT violation is not caused by ACCEPT which contains a desired mapping level.
As for the scenario, the one I can think of is, guest is trying to convert a 4K sized page between private and shared constantly, for testing purpose. Guest knows that if accepting the gpa at higher level, it takes more time. And when convert it to shared, it triggers DEMOTE and more time. So for better performance, guest just calls ACCEPT with 4KB page. However, VMM returns PAGE_SIZE_MATCH and enforces guest to accept a bigger size. what a stupid VMM.
Anyway, I'm just expressing how I understand the current design and I think it's reasonable. And I don't object the idea to return ACCEPT_SIZE_MISMATCH for "too small" case, but it's needs to be guest opt-in, i.e., let guest itself chooses the behavior.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 74 lines · Xiaoyao Li
Quoted 46 lines · Sean Christopherson
Quoted 7 lines · Kai Huang
Quoted 6 lines · Yan Y
Quoted 5 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 4 lines
On the opposite, if other non-Linux TDs don't follow 1G->2M->4K accept order, e.g., they always accept 4K, there could be *endless EPT violation* if I understand your words correctly.
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
Isn't this yet-another reason we should choose to return
PG_LEVEL_4Kinstead of 2M if no accept level is provided in the fault?As I said, returning
PG_LEVEL_4Kwould disallow huge pages for non-Linux TDs. TD's accept operations at size > 4KB will getTDACCEPT_SIZE_MISMATCH.
TDX_PAGE_SIZE_MISMATCHis a valid error code that the guest should handle. The docs say the VMM needs to demote *if* the mapping is large and the accept size is small.No thanks, fix the spec and the TDX Module. Punting an error to the VMM is inconsistent, convoluted, and inefficient.
Per "Table 8.2: TDG.MEM.PAGE.ACCEPT SEPT Walk Cases":
S-EPT state ACCEPT vs. Mapping Size Behavior Leaf SEPT_PRESENT Smaller TDACCEPT_SIZE_MISMATCH Leaf !SEPT_PRESENT Smaller EPT Violation <=========================| Leaf DONT_CARE Same Success | => THESE TWO SHOULD MATCH!!! !Leaf SEPT_FREE Larger EPT Violation, BECAUSE THERE'S NO PAGE | !Leaf SEPT_FREE Larger TDACCEPT_SIZE_MISMATCH <================|If ACCEPT is "too small", an EPT violation occurs. But if ACCEPT is "too big", a
TDACCEPT_SIZE_MISMATCHerror occurs. That's asinine.The only reason that comes to mind for punting the "too small" case to the VMM is to try and keep the guest alive if the VMM is mapping more memory than has been enumerated to the guest. E.g. if the guest suspects the VMM is malicious or buggy. IMO, that's a terrible reason to push this much complexity into the host. It also risks godawful boot times, e.g. if the guest kernel is buggy and accepts everything at 4KiB granularity.
The TDX Module should return
TDACCEPT_SIZE_MISMATCHand force the guest to take action, not force the hypervisor to limp along in a degraded state. If the guest doesn't want to ACCEPT at a larger granularity, e.g. because it doesn't think the entire 2MiB/1GiB region is available, then the guest can either log a warning and "poison" the page(s), or terminate and refuse to boot.Quoted 3 lines
If for some reason the guest _can't_ ACCEPT at larger granularity, i.e. if the guest _knows_ that 2MiB or 1GiB is available/usable but refuses to ACCEPT at the appropriate granularity, then IMO that's firmly a guest bug.
It might just be guest doesn't want to accept a larger level instead of can't. Use case see below.
Quoted 4 lines
If there's a *legitimate* use case where the guest wants to ACCEPT a subset of memory, then there should be an explicit TDCALL to request that the unwanted regions of memory be unmapped. Smushing everything into implicit behavior has obvioulsy created a giant mess.
Isn't the ACCEPT with a specific level explicit? Note that ACCEPT is not only for the case that VMM has already mapped page and guest only needs to accept it to make it available, it also works for the case that guest requests VMM to map the page for a gpa (at specific level) then guest accepts it.
Even for the former case, it is understandable for behaving differently for the "too small" and "too big" case. If the requested accept level is "too small", VMM can handle it by demoting the page to satisfy guest. But when the level is "too big", usually the VMM cannot map the page at a higher level so that ept violation cannot help. I admit that it leads to the requirement that VMM should always try to map the page at the highest available level, if the EPT violation is not caused by ACCEPT which contains a desired mapping level.
Quoted 5 lines
As for the scenario, the one I can think of is, guest is trying to convert a 4K sized page between private and shared constantly, for testing purpose. Guest knows that if accepting the gpa at higher level, it takes more time. And when convert it to shared, it triggers DEMOTE and more time. So for better performance, guest just calls ACCEPT with 4KB page. However, VMM
Hmm, ACCEPT at 4KB level at the first time triggers DEMOTE already. So, I don't see how ACCEPT at 4KB helps performance.
Support VMM has mapped a page at 4MB,
Scenario 1 Effort
(1) Guest ACCEPT at 2MB ACCEPT 2MB (2) converts a 4KB page to shared DEMOTE (3) convert it back to private ACCEPT 4KB
Scenario 2 Effort
(1) Guest ACCEPT at 4MB DEMOTE, ACCEPT 4MB
(2) converts a 4KB page to shared
(3) convert it back to private ACCEPT 4KB
In step (3) of "Scenario 1", VMM will not map the page at 2MB according to the current implementation because PROMOTION requires uniform ACCEPT status across all 512 4KB pages to be succeed.
Quoted 2 lines
returns
PAGE_SIZE_MATCHand enforces guest to accept a bigger size. what a stupid VMM.
I agree with Sean that if guest doesn't want to accept at a bigger size for certain reasons (e.g. it thinks it's unsafe or consider it as an attack), invoking an explicit TDVMCALL may be a better approach.
Quoted 4 lines
Anyway, I'm just expressing how I understand the current design and I think it's reasonable. And I don't object the idea to return
ACCEPT_SIZE_MISMATCHfor "too small" case, but it's needs to be guest opt-in, i.e., let guest itself chooses the behavior.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 60 lines · Yan Zhao
Quoted 59 lines · Xiaoyao Li
Quoted 46 lines · Sean Christopherson
Quoted 7 lines · Kai Huang
Quoted 6 lines · Yan Y
Quoted 5 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 4 lines
On the opposite, if other non-Linux TDs don't follow 1G->2M->4K accept order, e.g., they always accept 4K, there could be *endless EPT violation* if I understand your words correctly.
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
Isn't this yet-another reason we should choose to return
PG_LEVEL_4Kinstead of 2M if no accept level is provided in the fault?As I said, returning
PG_LEVEL_4Kwould disallow huge pages for non-Linux TDs. TD's accept operations at size > 4KB will getTDACCEPT_SIZE_MISMATCH.
TDX_PAGE_SIZE_MISMATCHis a valid error code that the guest should handle. The docs say the VMM needs to demote *if* the mapping is large and the accept size is small.No thanks, fix the spec and the TDX Module. Punting an error to the VMM is inconsistent, convoluted, and inefficient.
Per "Table 8.2: TDG.MEM.PAGE.ACCEPT SEPT Walk Cases":
S-EPT state ACCEPT vs. Mapping Size Behavior Leaf SEPT_PRESENT Smaller TDACCEPT_SIZE_MISMATCH Leaf !SEPT_PRESENT Smaller EPT Violation <=========================| Leaf DONT_CARE Same Success | => THESE TWO SHOULD MATCH!!! !Leaf SEPT_FREE Larger EPT Violation, BECAUSE THERE'S NO PAGE | !Leaf SEPT_FREE Larger TDACCEPT_SIZE_MISMATCH <================|If ACCEPT is "too small", an EPT violation occurs. But if ACCEPT is "too big", a
TDACCEPT_SIZE_MISMATCHerror occurs. That's asinine.The only reason that comes to mind for punting the "too small" case to the VMM is to try and keep the guest alive if the VMM is mapping more memory than has been enumerated to the guest. E.g. if the guest suspects the VMM is malicious or buggy. IMO, that's a terrible reason to push this much complexity into the host. It also risks godawful boot times, e.g. if the guest kernel is buggy and accepts everything at 4KiB granularity.
The TDX Module should return
TDACCEPT_SIZE_MISMATCHand force the guest to take action, not force the hypervisor to limp along in a degraded state. If the guest doesn't want to ACCEPT at a larger granularity, e.g. because it doesn't think the entire 2MiB/1GiB region is available, then the guest can either log a warning and "poison" the page(s), or terminate and refuse to boot.Quoted 3 lines
If for some reason the guest _can't_ ACCEPT at larger granularity, i.e. if the guest _knows_ that 2MiB or 1GiB is available/usable but refuses to ACCEPT at the appropriate granularity, then IMO that's firmly a guest bug.
It might just be guest doesn't want to accept a larger level instead of can't. Use case see below.
Quoted 4 lines
If there's a *legitimate* use case where the guest wants to ACCEPT a subset of memory, then there should be an explicit TDCALL to request that the unwanted regions of memory be unmapped. Smushing everything into implicit behavior has obvioulsy created a giant mess.
Quoted 5 lines
Quoted 5 lines
Isn't the ACCEPT with a specific level explicit? Note that ACCEPT is not only for the case that VMM has already mapped page and guest only needs to accept it to make it available, it also works for the case that guest requests VMM to map the page for a gpa (at specific level) then guest accepts it.
To avoid confusion, here's the full new design:
1.when an EPT violation carries an ACCEPT level info
(This occurs when TD performs ACCEPT before it accesses memory), KVM maps the page at map level <= the specified level. Guest's ACCEPT will succeed or return PAGE_SIZE_MATCH if map level < the specified level.
2.when an EPT violation does not carry ACCEPT level info
(This occurs when TD accesses memory before invoking ACCEPT),
1) if the TD is configured to always accept VMM's map level, KVM allows to map at 2MB.
TD's later 4KB ACCEPT will return PAGE_SIZE_MATCH.
TD can either retry with 2MB ACCEPT or explictly invoke a TDVMCALL for demotion.
2) if the TD is not configured to always accept VMM's map level, KVM always maps at 4KB.
TD's 2MB ACCEPT will return PAGE_SIZE_MATCH.
Please let me know if anything does not look right.
Quoted 9 lines
Quoted 9 lines
Even for the former case, it is understandable for behaving differently for the "too small" and "too big" case. If the requested accept level is "too small", VMM can handle it by demoting the page to satisfy guest. But when the level is "too big", usually the VMM cannot map the page at a higher level so that ept violation cannot help. I admit that it leads to the requirement that VMM should always try to map the page at the highest available level, if the EPT violation is not caused by ACCEPT which contains a desired mapping level.
Quoted 7 lines
Quoted 5 lines
As for the scenario, the one I can think of is, guest is trying to convert a 4K sized page between private and shared constantly, for testing purpose. Guest knows that if accepting the gpa at higher level, it takes more time. And when convert it to shared, it triggers DEMOTE and more time. So for better performance, guest just calls ACCEPT with 4KB page. However, VMM
Hmm, ACCEPT at 4KB level at the first time triggers DEMOTE already. So, I don't see how ACCEPT at 4KB helps performance.
Hmm, sent too fast previously. Some correction below:
Quoted 1 line
Support VMM has mapped a page at 4MB,
Suppose VMM has mapped a page at 2MB when an EPT violation (triggered by TD memory access instead of by TD ACCEPT) does not carry ACCEPT level info,
Quoted 9 lines
Scenario 1 Effort
(1) Guest ACCEPT at 2MB ACCEPT 2MB (2) converts a 4KB page to shared DEMOTE (3) convert it back to private ACCEPT 4KBScenario 2 Effort
(1) Guest ACCEPT at 4MB DEMOTE, ACCEPT 4MB
(1) Guest ACCEPT at 4KB DEMOTE, ACCEPT 4KB
Quoted 18 lines
(2) converts a 4KB page to shared
(3) convert it back to private ACCEPT 4KBIn step (3) of "Scenario 1", VMM will not map the page at 2MB according to the current implementation because PROMOTION requires uniform ACCEPT status across all 512 4KB pages to be succeed.
Quoted 2 lines
returns
PAGE_SIZE_MATCHand enforces guest to accept a bigger size. what a stupid VMM.I agree with Sean that if guest doesn't want to accept at a bigger size for certain reasons (e.g. it thinks it's unsafe or consider it as an attack), invoking an explicit TDVMCALL may be a better approach.
Quoted 4 lines
Anyway, I'm just expressing how I understand the current design and I think it's reasonable. And I don't object the idea to return
ACCEPT_SIZE_MISMATCHfor "too small" case, but it's needs to be guest opt-in, i.e., let guest itself chooses the behavior.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 11 lines · Yan Zhao
To avoid confusion, here's the full new design:
1.when an EPT violation carries an ACCEPT level info
(This occurs when TD performs ACCEPT before it accesses memory), KVM maps the page at map level <= the specified level. Guest's ACCEPT will succeed or returnPAGE_SIZE_MATCHif map level < the specified level.2.when an EPT violation does not carry ACCEPT level info
(This occurs when TD accesses memory before invoking ACCEPT),
Quoted 7 lines
1) if the TD is configured to always accept VMM's map level, KVM allows to map at 2MB.
TD's later 4KB ACCEPT will returnPAGE_SIZE_MATCH.
TD can either retry with 2MB ACCEPT or explictly invoke a TDVMCALL for demotion.
2) if the TD is not configured to always accept VMM's map level, KVM always maps at 4KB.
Is it the decision derived from the discussion of this series to make the design simple and avoid the demotion on ACCEPT?
It looks like KVM's own design preference that if the TD doesn't opt-in the proposed new feature "always accept VMM's map level', the only way it can get the page mapped by EPT as hugepage is always trying to accept the page before first access and trying accept starting from biggest page size.
I'm OK with it.
Quoted 3 lines
TD's 2MB ACCEPT will return
PAGE_SIZE_MATCH.Please let me know if anything does not look right.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
In reply to Yan ZhaoQuoted 6 lines · Yan Zhao
So, you want to disallow huge pages for non-Linux TDs, then we have no need to support splitting in the fault path, right?
I'm OK if we don't care non-Linux TDs for now.
This can simplify the splitting code and we can add the support when there's a need.
We do need to care about non-Linux TDs functioning, but we don't need to optimize for them at this point. We need to optimize for things that happen often. Pending-#VE using TDs are rare, and don't need to have huge pages in order to work.
Yesterday Kirill and I were chatting offline about the newly defined TDG.MEM.PAGE.RELEASE. It is kind of like an unaccept, so another possibility is:
1. Guest accepts at 2MB
2. Guest releases at 2MB (no notice to VMM)
3. Guest accepts at 4k, EPT violation with expectation to demote
In that case, KVM won't know to expect it, and that it needs to preemptively map things at 4k.
For full coverage of the issue, can we discuss a little bit about what demote in the fault path would look like? The current zapping operation that is involved depends on mmu write lock. And I remember you had a POC that added essentially a hidden exclusive lock in TDX code as a substitute. But unlike the other callers, the fault path demote case could actually handle failure. So if we just returned busy and didn't try to force the retry, we would just run the risk of interfering with TDX module sept lock? Is that the only issue with a design that would allows failure of demote in the fault path?
Let's keep in mind that we could ask for TDX module changes to enable this path. I think we could probably get away with ignoring TDG.MEM.PAGE.RELEASE if we had a plan to fix it up with TDX module changes. And if the ultimate root cause of the complication is avoiding zero-step (sept lock), we should fix that instead of design around it further.
Quoted 7 lines
Quoted 6 lines
I think this connects the question of whether we can pass the necessary info into fault via synthetic error code. Consider this new design:
-
tdx_gmem_private_max_mapping_level()simply returns 4k for prefetch and pre- runnable, otherwise returns 2MBWhy prefetch and pre-runnable faults go the first path, while
Because these are either passed into private_max_mapping_level(), or not associated with the fault (runnable state).
Quoted 5 lines
Quoted 4 lines
- if fault has accept info 2MB size, pass 2MB size into fault. Otherwise pass 4k (i.e. VMs that are relying on #VE to do the accept won't get huge pages *yet*).
other faults go the second path?
This info is related to the specific fault.
Quoted 7 lines
Quoted 1 line
What goes wrong? Seems simpler and no more stuffing fault info on the vcpu.
I tried to avoid the double paths.
IMHO, it's confusing to specifymax_levelfrom two paths.The fault info in
vcpu_tdxisn't a real problem as it's per-vCPU. An existing example in KVM isvcpu->arch.mmio_gfn.
mmio_gfn isn't info about the fault though, it's info about the gfn being mmio. So not fault scoped.
Quoted 14 lines
We don't need something like the
vcpu->arch.mmio_genbecause tdx->violation_gfn_* andtdx->violation_request_levelare reset in eachtdx_handle_ept_violation().BTW, dug into some history:
In v18 of TDX basic series,
enforcing 4KB for pre-runnable faults were done by passingPG_LEVEL_4Ktokvm_mmu_map_tdp_page().
https://lore.kernel.org/all/1a64f798b550dad9e096603e8dae3b6e8fb2fbd5.1705965635.git.isaku.yamahata@intel.com/
https://lore.kernel.org/all/97bb1f2996d8a7b828cd9e3309380d1a86ca681b.1705965635.git.isaku.yamahata@intel.com/
Quoted 7 lines
For the other faults, it's done by altering
max_levelinkvm_mmu_do_page_fault(), and Paolo asked to use thetdx_gmem_private_max_mapping_level()path.
https://lore.kernel.org/all/CABgObfbu1-Ok607uYdo4DzwZf8ZGVQnvHU+y9_M1Zae55K5xwQ@mail.gmail.com/For the patch "KVM: x86/mmu: Allow per-VM override of the TDP max page level", it's initially acked by Paolo in v2, and Sean's reply is at
https://lore.kernel.org/all/YO3%[email protected] .
The SNP case is not checking fault info, it's closer to the other cases. I don't see that any of that conversation applies to this case. Can you clarify?
On the subject of the whether to pass accept level into the fault, or stuff it on the vcpu, I'm still in the camp that it is better to pass it in the error code. If you disagree, let's see if we can flag down Sean and Paolo to weigh in.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 19 lines · Rick P
Quoted 6 lines · Yan Zhao
So, you want to disallow huge pages for non-Linux TDs, then we have no need to support splitting in the fault path, right?
I'm OK if we don't care non-Linux TDs for now.
This can simplify the splitting code and we can add the support when there's a need.We do need to care about non-Linux TDs functioning, but we don't need to optimize for them at this point. We need to optimize for things that happen often. Pending-#VE using TDs are rare, and don't need to have huge pages in order to work.
Yesterday Kirill and I were chatting offline about the newly defined TDG.MEM.PAGE.RELEASE. It is kind of like an unaccept, so another possibility is:
1. Guest accepts at 2MB
2. Guest releases at 2MB (no notice to VMM)
3. Guest accepts at 4k, EPT violation with expectation to demote
Quoted 5 lines
In that case, KVM won't know to expect it, and that it needs to preemptively map things at 4k.
For full coverage of the issue, can we discuss a little bit about what demote in the fault path would look like?
For demote in the fault path, it will take mmu read lock.
So, the flow in the fault path is
1. zap with mmu read lock.
ret = tdx_sept_zap_private_spte(kvm, gfn, level, page, true); if (ret <= 0)
return ret;
2. track with mmu read lock
ret = tdx_track(kvm, true);
if (ret)
return ret;
3. demote with mmu read lock
ret = tdx_spte_demote_private_spte(kvm, gfn, level, page, true);
if (ret)
goto err;4. return success or unzap as error fallback.
tdx_sept_unzap_private_spte(kvm, gfn, level);
Steps 1-3 will return -EBUSY on busy error (which will not be very often as we will introduce kvm_tdx->sept_lock. I can post the full lock analysis if necessary).
Step 4 will be ensured to succeed.
Here's the detailed code for step 1, 3 and 4.
static int tdx_sept_zap_private_spte(struct kvm *kvm, gfn_t gfn,
enum pg_level level, struct page *page, bool mmu_lock_shared)
{
int tdx_level = pg_level_to_tdx_sept_level(level);
struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
gpa_t gpa = gfn_to_gpa(gfn) & KVM_HPAGE_MASK(level);
u64 err, entry, level_state;
/* Before TD runnable, large page is not supported */
WARN_ON_ONCE(kvm_tdx->state != TD_STATE_RUNNABLE && level != PG_LEVEL_4K);
if (mmu_lock_shared)
lockdep_assert_held_read(&kvm->mmu_lock);
else
lockdep_assert_held_write(&kvm->mmu_lock);
write_lock(&kvm_tdx->sept_lock);
err = tdh_mem_range_block(&kvm_tdx->td, gpa, tdx_level, &entry, &level_state);
write_unlock(&kvm_tdx->sept_lock);
if (unlikely(tdx_operand_busy(err))) {
if (mmu_lock_shared)
return -EBUSY;
/* After no vCPUs enter, the second retry is expected to succeed */
write_lock(&kvm_tdx->sept_lock);
tdx_no_vcpus_enter_start(kvm);
err = tdh_mem_range_block(&kvm_tdx->td, gpa, tdx_level, &entry, &level_state);
tdx_no_vcpus_enter_stop(kvm);
write_unlock(&kvm_tdx->sept_lock);
}
if (tdx_is_sept_zap_err_due_to_premap(kvm_tdx, err, entry, level) &&
!KVM_BUG_ON(!atomic64_read(&kvm_tdx->nr_premapped), kvm)) {
atomic64_dec(&kvm_tdx->nr_premapped);
return 0;
}
if (KVM_BUG_ON(err, kvm)) {
pr_tdx_error_2(TDH_MEM_RANGE_BLOCK, err, entry, level_state);
return -EIO;
}
return 1;
}static int tdx_spte_demote_private_spte(struct kvm *kvm, gfn_t gfn,
enum pg_level level, struct page *page, bool mmu_lock_shared)
{
int tdx_level = pg_level_to_tdx_sept_level(level);
struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
gpa_t gpa = gfn_to_gpa(gfn);
u64 err, entry, level_state;
do {
read_lock(&kvm_tdx->sept_lock);
err = tdh_mem_page_demote(&kvm_tdx->td, gpa, tdx_level, page,
&entry, &level_state);
read_unlock(&kvm_tdx->sept_lock);
} while (err == TDX_INTERRUPTED_RESTARTABLE);
if (unlikely(tdx_operand_busy(err)) {
unsigned long flags;
if (mmu_lock_shared)
return -EBUSY;
tdx_no_vcpus_enter_start(kvm);
read_lock(&kvm_tdx->sept_lock);
local_irq_save(flags);
err = tdh_mem_page_demote(&kvm_tdx->td, gpa, tdx_level, page,
&entry, &level_state);
local_irq_restore(flags);
read_unlock(&kvm_tdx->sept_lock);
tdx_no_vcpus_enter_stop(kvm);
}
if (KVM_BUG_ON(err, kvm)) {
pr_tdx_error_2(TDH_MEM_PAGE_DEMOTE, err, entry, level_state);
return -EIO;
}
return 0;
}static void tdx_sept_unzap_private_spte(struct kvm *kvm, gfn_t gfn,
enum pg_level level)
{
int tdx_level = pg_level_to_tdx_sept_level(level);
struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
gpa_t gpa = gfn_to_gpa(gfn) & KVM_HPAGE_MASK(level);
u64 err, entry, level_state;
write_lock(&kvm_tdx->sept_lock);
err = tdh_mem_range_unblock(&kvm_tdx->td, gpa, tdx_level, &entry, &level_state);
write_unlock(&kvm_tdx->sept_lock);
if (unlikely(tdx_operand_busy(err))) {
write_lock(&kvm_tdx->sept_lock);
tdx_no_vcpus_enter_start(kvm);
err = tdh_mem_range_unblock(&kvm_tdx->td, gpa, tdx_level, &entry, &level_state);
tdx_no_vcpus_enter_stop(kvm);
write_unlock(&kvm_tdx->sept_lock);
}
if (KVM_BUG_ON(err, kvm)) {
pr_tdx_error_2(TDH_MEM_RANGE_UNBLOCK, err, entry, level_state);
}
}Quoted 3 lines
The current zapping operation that is involved
depends on mmu write lock. And I remember you had a POC that added essentially a hidden exclusive lock in TDX code as a substitute. But unlike the other callers,
Right, The kvm_tdx->sept_lock is introduced as a rw lock. The write lock is held in a very short period, around tdh_mem_sept_remove(), tdh_mem_range_block(), tdh_mem_range_unblock().
The read/write status of the kvm_tdx->sept_lock corresponds to that in the TDX module.
Resources SHARED users EXCLUSIVE users
-----------------------------------------------------------------------
secure_ept_lock tdh_mem_sept_add tdh_vp_enter
tdh_mem_page_aug tdh_mem_sept_remove
tdh_mem_page_remove tdh_mem_range_block
tdh_mem_page_promote tdh_mem_range_unblock tdh_mem_page_demote
Quoted 4 lines
the fault path demote case could actually handle failure. So if we just returned busy and didn't try to force the retry, we would just run the risk of interfering with TDX module sept lock? Is that the only issue with a design that would allows failure of demote in the fault path?
The concern to support split in the fault path is mainly to avoid unnecesssary split, e.g., when two vCPUs try to accept at different levels.
Besides that we need to introduce 3 locks inside TDX:rwlock_t sept_lock, spinlock_t no_vcpu_enter_lock, spinlock_t track_lock.
To ensure the success of unzap (to restore the state), kicking of vCPUs in the fault path is required, which is not ideal. But with the introduced lock and the proposed TDX modules's change to tdg_mem_page_accept() (as in the next comment), the chance to invoke unzap is very low.
Quoted 1 line
Let's keep in mind that we could ask for TDX module changes to enable this path.
We may need TDX module's change to let tdg_mem_page_accept() not to take lock on an non-ACCEPTable entry to avoid contention with guest and the potential error TDX_HOST_PRIORITY_BUSY_TIMEOUT.
Quoted 4 lines
I think we could probably get away with ignoring TDG.MEM.PAGE.RELEASE if we had a plan to fix it up with TDX module changes. And if the ultimate root cause of the complication is avoiding zero-step (sept lock), we should fix that instead of design around it further.
Ok.
Quoted 47 lines
Quoted 6 lines
Quoted 5 lines
I think this connects the question of whether we can pass the necessary info into fault via synthetic error code. Consider this new design:
-
tdx_gmem_private_max_mapping_level()simply returns 4k for prefetch and pre- runnable, otherwise returns 2MBWhy prefetch and pre-runnable faults go the first path, while
Because these are either passed into
private_max_mapping_level(), or not associated with the fault (runnable state).Quoted 5 lines
Quoted 4 lines
- if fault has accept info 2MB size, pass 2MB size into fault. Otherwise pass 4k (i.e. VMs that are relying on #VE to do the accept won't get huge pages *yet*).
other faults go the second path?
This info is related to the specific fault.
Quoted 7 lines
Quoted 1 line
What goes wrong? Seems simpler and no more stuffing fault info on the vcpu.
I tried to avoid the double paths.
IMHO, it's confusing to specifymax_levelfrom two paths.The fault info in
vcpu_tdxisn't a real problem as it's per-vCPU. An existing example in KVM isvcpu->arch.mmio_gfn.
mmio_gfnisn't info about the fault though, it's info about the gfn being mmio. So not fault scoped.Quoted 18 lines
We don't need something like the
vcpu->arch.mmio_genbecause tdx->violation_gfn_* andtdx->violation_request_levelare reset in eachtdx_handle_ept_violation().BTW, dug into some history:
In v18 of TDX basic series,
enforcing 4KB for pre-runnable faults were done by passingPG_LEVEL_4Ktokvm_mmu_map_tdp_page().
https://lore.kernel.org/all/1a64f798b550dad9e096603e8dae3b6e8fb2fbd5.1705965635.git.isaku.yamahata@intel.com/
https://lore.kernel.org/all/97bb1f2996d8a7b828cd9e3309380d1a86ca681b.1705965635.git.isaku.yamahata@intel.com/For the other faults, it's done by altering
max_levelinkvm_mmu_do_page_fault(), and Paolo asked to use thetdx_gmem_private_max_mapping_level()path.
https://lore.kernel.org/all/CABgObfbu1-Ok607uYdo4DzwZf8ZGVQnvHU+y9_M1Zae55K5xwQ@mail.gmail.com/
Quoted 6 lines
Quoted 3 lines
For the patch "KVM: x86/mmu: Allow per-VM override of the TDP max page level", it's initially acked by Paolo in v2, and Sean's reply is at
https://lore.kernel.org/all/YO3%[email protected] .The SNP case is not checking fault info, it's closer to the other cases. I don't see that any of that conversation applies to this case. Can you clarify?
My concern of stuffing the error_code to pass in the fault max_level is that if it's a good path, the TDX basic enabling code should have been implemented in that way by always passing in 4KB.
Why Sean said
"
Looks like SNP needs a dynamic check, i.e. a kvm_x86_ops hook, to handle an edge case in the RMP. That's probably the better route given that this is a short-term hack (hopefully :-D).
"
instead of suggesting TDX enable the error code path earlier and hardcode the level to 4KB?
Quoted 3 lines
On the subject of the whether to pass accept level into the fault, or stuff it on the vcpu, I'm still in the camp that it is better to pass it in the error code. If you disagree, let's see if we can flag down Sean and Paolo to weigh in.
Ok.
To document for further discussions with Sean and Paolo:
- Passing in max_level in tdx_gmem_private_max_mapping_level() Cons:
a) needs to stuff info in the vcpu to get accept level info.
Pros:
a) a uniform approach as to SEV.
b) dynamic. Can get more fault info, e.g. is_prefetch, gfn, pfn.
c) can get increased/decreased level for a given gfn similarly to get the accept level
d) flexibility for TDX to implement advanced features. e.g.
1. determine an accept level after certain negotiation with guest
2. pre-fetch memory
- To pass in max_level in error_code
Cons:
a) still need tdx_gmem_private_max_mapping_level() to get dynamic info.
b) still need info stuffed on the vcpu under certain conditions. e.g. when promotion fails with TDX_EPT_INVALID_PROMOTE_CONDITIONS, we can skip the local retry by reducing the max_level.
c) only effective in the EPT violation path.
Pros:
currently easy to pass in accept level info.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 40 lines · Yan Zhao
Quoted 19 lines · Rick P
Quoted 6 lines · Yan Zhao
So, you want to disallow huge pages for non-Linux TDs, then we have no need to support splitting in the fault path, right?
I'm OK if we don't care non-Linux TDs for now.
This can simplify the splitting code and we can add the support when there's a need.We do need to care about non-Linux TDs functioning, but we don't need to optimize for them at this point. We need to optimize for things that happen often. Pending-#VE using TDs are rare, and don't need to have huge pages in order to work.
Yesterday Kirill and I were chatting offline about the newly defined TDG.MEM.PAGE.RELEASE. It is kind of like an unaccept, so another possibility is:
1. Guest accepts at 2MB
2. Guest releases at 2MB (no notice to VMM)
3. Guest accepts at 4k, EPT violation with expectation to demoteQuoted 5 lines
In that case, KVM won't know to expect it, and that it needs to preemptively map things at 4k.
For full coverage of the issue, can we discuss a little bit about what demote in the fault path would look like?
For demote in the fault path, it will take mmu read lock.
So, the flow in the fault path is
1. zap with mmu read lock.
ret =tdx_sept_zap_private_spte(kvm, gfn, level, page, true); if (ret <= 0)return ret; 2. track with mmu read lock ret = tdx_track(kvm, true); if (ret) return ret; 3. demote with mmu read lock ret = tdx_spte_demote_private_spte(kvm, gfn, level, page, true); if (ret) goto err;
Quoted 6 lines
4. return success or unzap as error fallback.
tdx_sept_unzap_private_spte(kvm, gfn, level);Steps 1-3 will return
-EBUSYon busy error (which will not be very often as we will introducekvm_tdx->sept_lock. I can post the full lock analysis if necessary).
That is true that it would not be taken very often. It's not a performance issue, but I think we should not add a lock if we can at all avoid it. It creates a special case for TDX for the TDP MMU. People would have to then keep in mind that two mmu read lock threads could still still contend.
[snip]
Quoted 18 lines
Quoted 5 lines
The current zapping operation that is involved
depends on mmu write lock. And I remember you had a POC that added essentially a hidden exclusive lock in TDX code as a substitute. But unlike the other callers,Right, The
kvm_tdx->sept_lockis introduced as a rw lock. The write lock is held in a very short period, aroundtdh_mem_sept_remove(),tdh_mem_range_block(),tdh_mem_range_unblock().The read/write status of the
kvm_tdx->sept_lockcorresponds to that in the TDX module.Resources SHARED users EXCLUSIVE users
-----------------------------------------------------------------------secure_ept_lock tdh_mem_sept_add tdh_vp_enter tdh_mem_page_aug tdh_mem_sept_remove tdh_mem_page_remove tdh_mem_range_block tdh_mem_page_promote tdh_mem_range_unblock
Quoted 8 lines
tdh_mem_page_demoteQuoted 4 lines
the fault path demote case could actually handle failure. So if we just returned busy and didn't try to force the retry, we would just run the risk of interfering with TDX module sept lock? Is that the only issue with a design that would allows failure of demote in the fault path?
The concern to support split in the fault path is mainly to avoid unnecesssary split, e.g., when two vCPUs try to accept at different levels.
We are just talking about keeping rare TDs functional here, right? Two cases are:
- TDs using PAGE.RELEASE
- TDs using pending #VEs and accepting memory in strange patterns
Not maintaining huge pages there seems totally acceptable. How I look at this whole thing is that it just an optimization, not a feature. Every aspect has a complexity/performance tradeoff that we need to make a sensible decision on. Maintaining huge page mappings in every possible case is not the goal.
Quoted 3 lines
Besides that we need to introduce 3 locks inside TDX:
rwlock_tsept_lock,spinlock_tno_vcpu_enter_lock,spinlock_ttrack_lock.
Huh?
Quoted 5 lines
To ensure the success of unzap (to restore the state), kicking of vCPUs in the fault path is required, which is not ideal. But with the introduced lock and the proposed TDX modules's change to
tdg_mem_page_accept()(as in the next comment), the chance to invoke unzap is very low.
Yes, it's probably not safe to expect the exact same demote call chain again. The fault path could maybe learn to recover from the blocked state?
Quoted 5 lines
Quoted 2 lines
Let's keep in mind that we could ask for TDX module changes to enable this path.
We may need TDX module's change to let
tdg_mem_page_accept()not to take lock on an non-ACCEPTable entry to avoid contention with guest and the potential errorTDX_HOST_PRIORITY_BUSY_TIMEOUT.
Part of that is already in the works (accepting not-present entries). It seems reasonable. But also, what about looking at having the TDX module do the full demote operation internally. The track part obviously happens outside of the TDX module, but maybe the whole thing could be simplified.
Quoted 8 lines
Quoted 5 lines
I think we could probably get away with ignoring TDG.MEM.PAGE.RELEASE if we had a plan to fix it up with TDX module changes. And if the ultimate root cause of the complication is avoiding zero-step (sept lock), we should fix that instead of design around it further.
Ok.
Quoted 1 line
Quoted 1 line
I'll respond to the error code half of this mail separately.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 44 lines · Rick P
Quoted 43 lines · Yan Zhao
Quoted 19 lines · Rick P
Quoted 6 lines · Yan Zhao
So, you want to disallow huge pages for non-Linux TDs, then we have no need to support splitting in the fault path, right?
I'm OK if we don't care non-Linux TDs for now.
This can simplify the splitting code and we can add the support when there's a need.We do need to care about non-Linux TDs functioning, but we don't need to optimize for them at this point. We need to optimize for things that happen often. Pending-#VE using TDs are rare, and don't need to have huge pages in order to work.
Yesterday Kirill and I were chatting offline about the newly defined TDG.MEM.PAGE.RELEASE. It is kind of like an unaccept, so another possibility is:
1. Guest accepts at 2MB
2. Guest releases at 2MB (no notice to VMM)
3. Guest accepts at 4k, EPT violation with expectation to demoteQuoted 5 lines
In that case, KVM won't know to expect it, and that it needs to preemptively map things at 4k.
For full coverage of the issue, can we discuss a little bit about what demote in the fault path would look like?
For demote in the fault path, it will take mmu read lock.
So, the flow in the fault path is
1. zap with mmu read lock.
ret =tdx_sept_zap_private_spte(kvm, gfn, level, page, true); if (ret <= 0)return ret; 2. track with mmu read lock ret = tdx_track(kvm, true); if (ret) return ret; 3. demote with mmu read lock ret = tdx_spte_demote_private_spte(kvm, gfn, level, page, true); if (ret) goto err;4. return success or unzap as error fallback.
tdx_sept_unzap_private_spte(kvm, gfn, level);
Quoted 8 lines
Quoted 3 lines
Steps 1-3 will return
-EBUSYon busy error (which will not be very often as we will introducekvm_tdx->sept_lock. I can post the full lock analysis if necessary).That is true that it would not be taken very often. It's not a performance issue, but I think we should not add a lock if we can at all avoid it. It creates a special case for TDX for the TDP MMU. People would have to then keep in mind that two mmu read lock threads could still still contend.
Hmm, without the kvm_tdx->sept_lock, we can return retry if busy error is returned from tdh_mem_range_block(). However, we need to ensure the success of tdh_mem_range_unblock() before completing the split.
Besides, we need the kvm_tdx->track_lock to serialize tdh_mem_track() and kicking off vCPUs. In the base series, we use write kvm->mmu_lock to achieve this purpose.
BTW: Looks Kirill's DPAMT series will introduce a pamt_lock [1].
[1] https://lore.kernel.org/all/[email protected]/
Quoted 22 lines
Quoted 22 lines
Quoted 3 lines
The current zapping operation that is involved
depends on mmu write lock. And I remember you had a POC that added essentially a hidden exclusive lock in TDX code as a substitute. But unlike the other callers,Right, The
kvm_tdx->sept_lockis introduced as a rw lock. The write lock is held in a very short period, aroundtdh_mem_sept_remove(),tdh_mem_range_block(),tdh_mem_range_unblock().The read/write status of the
kvm_tdx->sept_lockcorresponds to that in the TDX module.Resources SHARED users EXCLUSIVE users
-----------------------------------------------------------------------secure_ept_lock tdh_mem_sept_add tdh_vp_enter tdh_mem_page_aug tdh_mem_sept_remove tdh_mem_page_remove tdh_mem_range_block tdh_mem_page_promote tdh_mem_range_unblock
tdh_mem_page_demoteQuoted 4 lines
the fault path demote case could actually handle failure. So if we just returned busy and didn't try to force the retry, we would just run the risk of interfering with TDX module sept lock? Is that the only issue with a design that would allows failure of demote in the fault path?
Quoted 6 lines
Quoted 2 lines
The concern to support split in the fault path is mainly to avoid unnecesssary split, e.g., when two vCPUs try to accept at different levels.
We are just talking about keeping rare TDs functional here, right? Two cases are:
- TDs using PAGE.RELEASE
This is for future linux TDs, right?
Quoted 6 lines
- TDs using pending #VEs and accepting memory in strange patterns
Not maintaining huge pages there seems totally acceptable. How I look at this whole thing is that it just an optimization, not a feature. Every aspect has a complexity/performance tradeoff that we need to make a sensible decision on. Maintaining huge page mappings in every possible case is not the goal.
So, can I interpret your preference as follows?
For now,
- Do not support huge pages on non-linux TDs.
- Do not support page splitting in fault path.
Quoted 5 lines
Quoted 3 lines
Besides that we need to introduce 3 locks inside TDX:
rwlock_tsept_lock,spinlock_tno_vcpu_enter_lock,spinlock_ttrack_lock.Huh?
In the base series, no_vcpu_enter_lock and track_lock are saved by holding the write kvm->mmu_lock.
Quoted 9 lines
Quoted 6 lines
To ensure the success of unzap (to restore the state), kicking of vCPUs in the fault path is required, which is not ideal. But with the introduced lock and the proposed TDX modules's change to
tdg_mem_page_accept()(as in the next comment), the chance to invoke unzap is very low.Yes, it's probably not safe to expect the exact same demote call chain again. The fault path could maybe learn to recover from the blocked state?
Do you mean you want to introduce a blocked state in the mirror page table? I don't like it for its complexity.
Do you think we can try to ask for tdh_mem_page_demote() not to use tdh_mem_range_block() and tdh_mem_range_unblock(). Looks it's anyway required for TDX connect.
If that's true, the tdh_mem_range_{un}block()/tdh_mem_track() can be avoided in the fault path.
Quoted 21 lines
Quoted 5 lines
Quoted 2 lines
Let's keep in mind that we could ask for TDX module changes to enable this path.
We may need TDX module's change to let
tdg_mem_page_accept()not to take lock on an non-ACCEPTable entry to avoid contention with guest and the potential errorTDX_HOST_PRIORITY_BUSY_TIMEOUT.Part of that is already in the works (accepting not-present entries). It seems reasonable. But also, what about looking at having the TDX module do the full demote operation internally. The track part obviously happens outside of the TDX module, but maybe the whole thing could be simplified.
Quoted 8 lines
Quoted 5 lines
I think we could probably get away with ignoring TDG.MEM.PAGE.RELEASE if we had a plan to fix it up with TDX module changes. And if the ultimate root cause of the complication is avoiding zero-step (sept lock), we should fix that instead of design around it further.
Ok.
Quoted 1 line
Quoted 1 line
I'll respond to the error code half of this mail separately.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
In reply to Yan ZhaoQuoted 7 lines · Yan Y
Quoted 3 lines
But in the above text you mentioned that, if doing so, because we choose to ignore splitting request on read, returning 2M could result in *endless* EPT violation.
I don't get what you mean.
What's the relationship between splitting and "returning 2M could result in *endless* EPT" ?
Quoted 5 lines
Quoted 3 lines
So to me it seems you choose a design that could bring performance gain for certain non-Linux TDs when they follow a certain behaviour but otherwise could result in endless EPT violation in KVM.
Also don't understand here.
Which design could result in endless EPT violation?
[Sorry somehow I didn't see your replies yesterday in my mailbox.]
You mentioned below in your coverletter:
(b) with shared kvm->mmu_lock, triggered by fault.
....
This series simply ignores the splitting request in the fault path to avoid unnecessary bounces between levels. The vCPU that performs ACCEPT at a lower level would finally figures out the page has been accepted at a higher level by another vCPU.
... The worst outcome to ignore the resulting
splitting request is an endless EPT violation. This would not happen for a Linux guest, which does not expect any #VE.
So to me, IIUC, this means:
- this series choose to ignore splitting request when read ..
- the worse outcome to ignore the resulting splitting request is an endless EPT violation..
And this happens exactly in below case:
1) Guest touches a 4K page
2) KVM AUGs 2M page
3) Guest re-accesses that 4K page, and receives #VE
4) Guest ACCEPTs that 4K page, this triggers EPT violation
IIUC, you choose to ignore splitting large page in step 4) (am I right???). Then if guest always ACCEPTs page at 4K level, then KVM will have *endless EPT violation*.
So, is this the "worst outcome to ignore the resulting splitting request" that you mentioned in your changelog?
If it is, then why is it OK?
It is OK *ONLY* when "guest always ACCEPTs 4K page" is a buggy behaviour of the guest itself (which KVM is not responsible for). I.e., the guest is always supposed to find the page size that KVM has AUGed upon receiving the #VE (does the #VE contain such information?) and then do ACCEPT at that page level.
Otherwise, if it's a legal behaviour for the guest to always ACCEPT at 4K level, then I don't think it's OK to have endless EPT violation in KVM.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
Quoted 44 lines · Kai
Quoted 7 lines · Yan Y
Quoted 3 lines
But in the above text you mentioned that, if doing so, because we choose to ignore splitting request on read, returning 2M could result in *endless* EPT violation.
I don't get what you mean.
What's the relationship between splitting and "returning 2M could result in *endless* EPT" ?Quoted 5 lines
Quoted 3 lines
So to me it seems you choose a design that could bring performance gain for certain non-Linux TDs when they follow a certain behaviour but otherwise could result in endless EPT violation in KVM.
Also don't understand here.
Which design could result in endless EPT violation?[Sorry somehow I didn't see your replies yesterday in my mailbox.]
You mentioned below in your coverletter:
(b) with shared
kvm->mmu_lock, triggered by fault.....
This series simply ignores the splitting request in the fault path to avoid unnecessary bounces between levels. The vCPU that performs ACCEPT at a lower level would finally figures out the page has been accepted at a higher level by another vCPU.
... The worst outcome to ignore the resulting
splitting request is an endless EPT violation. This would not happen for a Linux guest, which does not expect any #VE.So to me, IIUC, this means:
- this series choose to ignore splitting request when read ..
- the worse outcome to ignore the resulting splitting request is an endless EPT violation..And this happens exactly in below case:
1) Guest touches a 4K page
2) KVM AUGs 2M page
3) Guest re-accesses that 4K page, and receives #VE
4) Guest ACCEPTs that 4K page, this triggers EPT violation
Quoted 8 lines
IIUC, you choose to ignore splitting large page in step 4) (am I right???). Then if guest always ACCEPTs page at 4K level, then KVM will have *endless EPT violation*.
So, is this the "worst outcome to ignore the resulting splitting request" that you mentioned in your changelog?
If it is, then why is it OK?
Initially I assumed the guest should always accept in the sequence of "1G->2M->4K" as what's linux guest is doing.
If that's true, we can simply ignore the splitting request in the fault (shared) path because it's the guest that not follow the convention.
However, Kirill and you are right, the guest can accept at 4K.
Given that, the "worst outcome to ignore the resulting splitting request" is not OK.
Quoted 7 lines
It is OK *ONLY* when "guest always ACCEPTs 4K page" is a buggy behaviour of the guest itself (which KVM is not responsible for). I.e., the guest is always supposed to find the page size that KVM has AUGed upon receiving the #VE (does the #VE contain such information?) and then do ACCEPT at that page level.
Otherwise, if it's a legal behaviour for the guest to always ACCEPT at 4K level, then I don't think it's OK to have endless EPT violation in KVM.
We can avoid the endless EPT violation by allowing the splitting in the fault path, which involves the introduction of several locks in TDX code though. I had a POC for that one, but we felt that it's better to keep the initial support simple.
So, if we all agree not to support huge pages for non-Linux TDs as an initial step, your proposal is a good idea to keep splitting code simple.
Re: [RFC PATCH 09/21] KVM: TDX: Enable 2MB mapping size after TD is RUNNABLE
In reply to Edgecombe, Rick PQuoted 40 lines · Rick P
Quoted 39 lines · Yan Zhao
Allow TDX's .private_max_mapping_level hook to return 2MB after the TD is RUNNABLE, enabling KVM to map TDX private pages at the 2MB level. Remove TODOs and adjust KVM_BUG_ON()s accordingly.
Note: Instead of placing this patch at the tail of the series, it's positioned here to show the code changes for basic mapping of private huge pages (i.e., transitioning from non-present to present).
However, since this patch also allows KVM to trigger the merging of small entries into a huge leaf entry or the splitting of a huge leaf entry into small entries, errors are expected if any of these operations are triggered due to the current lack of splitting/merging support.
Signed-off-by Xiaoyao Li <[email protected]>Signed-off-by Isaku Yamahata <[email protected]>Signed-off-by Yan Zhao <[email protected]>--- arch/x86/kvm/vmx/tdx.c | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-)arch/x86/kvm/vmx/tdx.c +0
-4@@ -1561,10 +1561,6 @@ int tdx_sept_set_private_spte(struct kvm *kvm, gfn_t gfn,struct kvm_tdx *kvm_tdx =to_kvm_tdx (kvm);struct page *page =pfn_to_page (pfn); -/* TODO: handle large pages. */ -if (KVM_BUG_ON (level !=PG_LEVEL_4K , kvm)) -return -EINVAL ; -/* * Because guest_memfd doesn't support page migration with * a_ops->migrate_folio (yet), no callback is triggered for KVM on page @@ -1612,8 +1608,7 @@ static int tdx_sept_drop_private_spte(struct kvm *kvm, gfn_t gfn,gpa_t gpa =gfn_to_gpa (gfn);u64 err, entry, level_state;
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c static int tdx_sept_drop_private_spte(struct kvm *kvm, gfn_t gfn, · line 1611
Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +1
-2-/* TODO: handle large pages. */ -if (KVM_BUG_ON (level !=PG_LEVEL_4K , kvm)) +if (KVM_BUG_ON (kvm_tdx->state !=TD_STATE_RUNNABLE && level !=PG_LEVEL_4K , kvm))It's not clear why some of these warnings are here and some are in patch 4.
Patch 4 contains only changes for !TD_STATE_RUNNABLE stage. This patch is to allow huge page after TD_STATE_RUNNABLE. So, relaxed the condition to trigger BUG_ON in this patch, i.e., before this patch, always bug on level > 4K;
after this patch, only bug on level > 4K before TD is runnable.
Quoted 28 lines
Quoted 28 lines
arch/x86/kvm/vmx/tdx.c +5
-2return -EINVAL ;if (KVM_BUG_ON (!is_hkid_assigned (kvm_tdx), kvm))@@ -1714,8 +1709,8 @@ static int tdx_sept_zap_private_spte(struct kvm *kvm, gfn_t gfn,gpa_t gpa =gfn_to_gpa (gfn) &KVM_HPAGE_MASK (level);u64 err, entry, level_state; -/* For now large page isn't supported yet. */ -WARN_ON_ONCE (level !=PG_LEVEL_4K ); +/* Before TD runnable, large page is not supported */ +WARN_ON_ONCE (kvm_tdx->state !=TD_STATE_RUNNABLE && level !=PG_LEVEL_4K ); err =tdh_mem_range_block (&kvm_tdx->td, gpa, tdx_level, &entry, &level_state);@@ -1817,6 +1812,9 @@ int tdx_sept_remove_private_spte(struct kvm *kvm, gfn_t gfn,struct page *page =pfn_to_page (pfn);int ret; +WARN_ON_ONCE (folio_page_idx (page_folio (page), page) +KVM_PAGES_PER_HPAGE (level) > +folio_nr_pages (page_folio (page))); +/* * HKID is released after all private pages have been removed, and set * before any might be populated. Warn if zapping is attempted when @@ -3265,7 +3263,7 @@ int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn)if (unlikely (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE ))return PG_LEVEL_4K ;
Quoted 4 lines
arch/x86/kvm/vmx/tdx.c int tdx_gmem_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn) · line 3266
Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +1
-1-return PG_LEVEL_4K ; +return PG_LEVEL_2M ;Maybe combine this with patch 4, or split them into sensible categories.
Sorry to bring confusion.
As explained in the patch msg, this patch to return PG_LEVEL_2M actually needs to be placed at the end of the series, after patches for page splitting/merging.
As inital RFC, it's placed earlier to show changes to enable basic TDX huge page (without splitting/merging).
Quoted 4 lines
Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +0
-0}static int tdx_online_cpu (unsigned int cpu)
RFC PATCH 10/21 KVM: x86/mmu: Disallow page merging (huge page adjustment) for mirror root
In reply to Yan ZhaoFrom: "Edgecombe, Rick P" <[email protected]>
Disallow page merging (huge page adjustment) for mirror root by leveraging the disallowed_hugepage_adjust().
[Yan: Passing is_mirror to disallowed_hugepage_adjust()]
--- arch/x86/kvm/mmu/mmu.c | 6 +++--- arch/x86/kvm/mmu/mmu_internal.h | 2 +- arch/x86/kvm/mmu/paging_tmpl.h | 2 +- arch/x86/kvm/mmu/tdp_mmu.c | 7 ++++--- 4 files changed, 9 insertions(+), 8 deletions(-)
arch/x86/kvm/mmu/mmu.c +3 -3
@@ -3326,13 +3326,13 @@ void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault fault->pfn &= ~mask; } -void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level) +void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level,bool is_mirror) {if (cur_level >PG_LEVEL_4K && cur_level == fault->goal_level &&is_shadow_present_pte (spte) && !is_large_pte (spte) && -spte_to_child_sp (spte)->nx_huge_page_disallowed) { + (spte_to_child_sp (spte)->nx_huge_page_disallowed || is_mirror)) {/* * A small SPTE exists for this pfn, but FNAME(fetch), * direct_map(), or kvm_tdp_mmu_map() would like to create a
@@ -3363,7 +3363,7 @@ static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)* large page, as the leaf could be executable. */ if (fault->nx_huge_page_workaround_enabled) -disallowed_hugepage_adjust (fault, *it.sptep, it.level); +disallowed_hugepage_adjust (fault, *it.sptep, it.level, false); base_gfn =gfn_round_for_level (fault->gfn, it.level);if (it.level == fault->goal_level)
arch/x86/kvm/mmu/mmu_internal.h +1 -1
@@ -411,7 +411,7 @@ static inline int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,int kvm_mmu_max_mapping_level (struct kvm *kvm,const struct kvm_memory_slot *slot,gfn_t gfn);void kvm_mmu_hugepage_adjust (struct kvm_vcpu *vcpu,struct kvm_page_fault *fault); -void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level); +void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level,bool is_mirror);void track_possible_nx_huge_page (struct kvm *kvm,struct kvm_mmu_page *sp);void untrack_possible_nx_huge_page (struct kvm *kvm,struct kvm_mmu_page *sp);
arch/x86/kvm/mmu/paging_tmpl.h +1 -1
@@ -717,7 +717,7 @@ static int FNAME(fetch)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,* large page, as the leaf could be executable. */ if (fault->nx_huge_page_workaround_enabled) -disallowed_hugepage_adjust (fault, *it.sptep, it.level); +disallowed_hugepage_adjust (fault, *it.sptep, it.level, false); base_gfn =gfn_round_for_level (fault->gfn, it.level);if (it.level == fault->goal_level)
arch/x86/kvm/mmu/tdp_mmu.c +4 -3
@@ -1244,6 +1244,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)struct tdp_iter iter;struct kvm_mmu_page *sp;int ret =RET_PF_RETRY ; +bool is_mirror =is_mirror_sp (root);kvm_mmu_hugepage_adjust (vcpu, fault);
@@ -1254,8 +1255,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)for_each_tdp_pte (iter, kvm, root, fault->gfn, fault->gfn +1 ) {int r; -if (fault->nx_huge_page_workaround_enabled) -disallowed_hugepage_adjust (fault, iter.old_spte, iter.level); +if (fault->nx_huge_page_workaround_enabled || is_mirror) +disallowed_hugepage_adjust (fault, iter.old_spte, iter.level, is_mirror);/* * If SPTE has been frozen by another thread, just give up and
@@ -1278,7 +1279,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)*/ sp =tdp_mmu_alloc_sp (vcpu);tdp_mmu_init_child_sp (sp, &iter); -if (is_mirror_sp (sp)) +if (is_mirror)kvm_mmu_alloc_external_spt (vcpu, sp); sp->nx_huge_page_disallowed = fault->huge_page_disallowed;
Signature · 1 line
2.43.2
Edgecombe, Rick P
maintainerRe: [RFC PATCH 10/21] KVM: x86/mmu: Disallow page merging (huge page adjustment) for mirror root
Quoted 84 lines · Yan Zhao
From: "Edgecombe, Rick P" <[email protected]>
Disallow page merging (huge page adjustment) for mirror root by leveraging the
disallowed_hugepage_adjust().[Yan: Passing
is_mirrortodisallowed_hugepage_adjust()]Signed-off-by Edgecombe, Rick P <[email protected]>Signed-off-by Yan Zhao <[email protected]>--- arch/x86/kvm/mmu/mmu.c | 6 +++--- arch/x86/kvm/mmu/mmu_internal.h | 2 +- arch/x86/kvm/mmu/paging_tmpl.h | 2 +- arch/x86/kvm/mmu/tdp_mmu.c | 7 ++++--- 4 files changed, 9 insertions(+), 8 deletions(-)arch/x86/kvm/mmu/mmu.c +3
-3@@ -3326,13 +3326,13 @@ void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault fault->pfn &= ~mask; } -void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level) +void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level,bool is_mirror) {if (cur_level >PG_LEVEL_4K && cur_level == fault->goal_level &&is_shadow_present_pte (spte) && !is_large_pte (spte) && -spte_to_child_sp (spte)->nx_huge_page_disallowed) { + (spte_to_child_sp (spte)->nx_huge_page_disallowed || is_mirror)) {/* * A small SPTE exists for this pfn, but FNAME(fetch), * direct_map(), or kvm_tdp_mmu_map() would like to create a @@ -3363,7 +3363,7 @@ static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)* large page, as the leaf could be executable. */ if (fault->nx_huge_page_workaround_enabled) -disallowed_hugepage_adjust (fault, *it.sptep, it.level); +disallowed_hugepage_adjust (fault, *it.sptep, it.level, false); base_gfn =gfn_round_for_level (fault->gfn, it.level);if (it.level == fault->goal_level)arch/x86/kvm/mmu/mmu_internal.h +1
-1@@ -411,7 +411,7 @@ static inline int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,int kvm_mmu_max_mapping_level (struct kvm *kvm,const struct kvm_memory_slot *slot,gfn_t gfn);void kvm_mmu_hugepage_adjust (struct kvm_vcpu *vcpu,struct kvm_page_fault *fault); -void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level); +void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level,bool is_mirror);void track_possible_nx_huge_page (struct kvm *kvm,struct kvm_mmu_page *sp);void untrack_possible_nx_huge_page (struct kvm *kvm,struct kvm_mmu_page *sp);arch/x86/kvm/mmu/paging_tmpl.h +1
-1@@ -717,7 +717,7 @@ static int FNAME(fetch)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,* large page, as the leaf could be executable. */ if (fault->nx_huge_page_workaround_enabled) -disallowed_hugepage_adjust (fault, *it.sptep, it.level); +disallowed_hugepage_adjust (fault, *it.sptep, it.level, false); base_gfn =gfn_round_for_level (fault->gfn, it.level);if (it.level == fault->goal_level)arch/x86/kvm/mmu/tdp_mmu.c +1
-0@@ -1244,6 +1244,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)struct tdp_iter iter;struct kvm_mmu_page *sp;int ret =RET_PF_RETRY ; +bool is_mirror =is_mirror_sp (root);kvm_mmu_hugepage_adjust (vcpu, fault);
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1258
Quoted 6 lines
arch/x86/kvm/mmu/tdp_mmu.c +1
-2@@ -1254,8 +1255,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)for_each_tdp_pte (iter, kvm, root, fault->gfn, fault->gfn +1 ) {int r; -if (fault->nx_huge_page_workaround_enabled) -disallowed_hugepage_adjust (fault, iter.old_spte, iter.level); +if (fault->nx_huge_page_workaround_enabled || is_mirror)
Maybe we should rename nx_huge_page_workaround_enabled to something more generic and do the is_mirror logic in kvm_mmu_do_page_fault() when setting it. It should shrink the diff and centralize the logic.
Quoted 13 lines
arch/x86/kvm/mmu/tdp_mmu.c +2
-1+disallowed_hugepage_adjust (fault, iter.old_spte, iter.level, is_mirror);/* * If SPTE has been frozen by another thread, just give up and @@ -1278,7 +1279,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)*/ sp =tdp_mmu_alloc_sp (vcpu);tdp_mmu_init_child_sp (sp, &iter); -if (is_mirror_sp (sp)) +if (is_mirror)kvm_mmu_alloc_external_spt (vcpu, sp); sp->nx_huge_page_disallowed = fault->huge_page_disallowed;
Re: [RFC PATCH 10/21] KVM: x86/mmu: Disallow page merging (huge page adjustment) for mirror root
Quoted 88 lines · Rick P
Quoted 87 lines · Yan Zhao
From: "Edgecombe, Rick P" <[email protected]>
Disallow page merging (huge page adjustment) for mirror root by leveraging the
disallowed_hugepage_adjust().[Yan: Passing
is_mirrortodisallowed_hugepage_adjust()]Signed-off-by Edgecombe, Rick P <[email protected]>Signed-off-by Yan Zhao <[email protected]>--- arch/x86/kvm/mmu/mmu.c | 6 +++--- arch/x86/kvm/mmu/mmu_internal.h | 2 +- arch/x86/kvm/mmu/paging_tmpl.h | 2 +- arch/x86/kvm/mmu/tdp_mmu.c | 7 ++++--- 4 files changed, 9 insertions(+), 8 deletions(-)arch/x86/kvm/mmu/mmu.c +3
-3@@ -3326,13 +3326,13 @@ void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault fault->pfn &= ~mask; } -void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level) +void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level,bool is_mirror) {if (cur_level >PG_LEVEL_4K && cur_level == fault->goal_level &&is_shadow_present_pte (spte) && !is_large_pte (spte) && -spte_to_child_sp (spte)->nx_huge_page_disallowed) { + (spte_to_child_sp (spte)->nx_huge_page_disallowed || is_mirror)) {/* * A small SPTE exists for this pfn, but FNAME(fetch), * direct_map(), or kvm_tdp_mmu_map() would like to create a @@ -3363,7 +3363,7 @@ static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)* large page, as the leaf could be executable. */ if (fault->nx_huge_page_workaround_enabled) -disallowed_hugepage_adjust (fault, *it.sptep, it.level); +disallowed_hugepage_adjust (fault, *it.sptep, it.level, false); base_gfn =gfn_round_for_level (fault->gfn, it.level);if (it.level == fault->goal_level)arch/x86/kvm/mmu/mmu_internal.h +1
-1@@ -411,7 +411,7 @@ static inline int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,int kvm_mmu_max_mapping_level (struct kvm *kvm,const struct kvm_memory_slot *slot,gfn_t gfn);void kvm_mmu_hugepage_adjust (struct kvm_vcpu *vcpu,struct kvm_page_fault *fault); -void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level); +void disallowed_hugepage_adjust (struct kvm_page_fault *fault,u64 spte,int cur_level,bool is_mirror);void track_possible_nx_huge_page (struct kvm *kvm,struct kvm_mmu_page *sp);void untrack_possible_nx_huge_page (struct kvm *kvm,struct kvm_mmu_page *sp);arch/x86/kvm/mmu/paging_tmpl.h +1
-1@@ -717,7 +717,7 @@ static int FNAME(fetch)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,* large page, as the leaf could be executable. */ if (fault->nx_huge_page_workaround_enabled) -disallowed_hugepage_adjust (fault, *it.sptep, it.level); +disallowed_hugepage_adjust (fault, *it.sptep, it.level, false); base_gfn =gfn_round_for_level (fault->gfn, it.level);if (it.level == fault->goal_level)arch/x86/kvm/mmu/tdp_mmu.c +1
-0@@ -1244,6 +1244,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)struct tdp_iter iter;struct kvm_mmu_page *sp;int ret =RET_PF_RETRY ; +bool is_mirror =is_mirror_sp (root);kvm_mmu_hugepage_adjust (vcpu, fault);@@ -1254,8 +1255,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)for_each_tdp_pte (iter, kvm, root, fault->gfn, fault->gfn +1 ) {int r;
Quoted 7 lines
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1258
Quoted 3 lines
arch/x86/kvm/mmu/tdp_mmu.c +1
-2-if (fault->nx_huge_page_workaround_enabled) -disallowed_hugepage_adjust (fault, iter.old_spte, iter.level); +if (fault->nx_huge_page_workaround_enabled || is_mirror)Maybe we should rename
nx_huge_page_workaround_enabledto something more generic and do theis_mirrorlogic inkvm_mmu_do_page_fault()when setting it. It should shrink the diff and centralize the logic.
Hmm, I'm reluctant to rename nx_huge_page_workaround_enabled, because
(1) Invoking disallowed_hugepage_adjust() for mirror root is to disable page promotion for TDX private memory, so is only applied to TDP MMU.
(2) nx_huge_page_workaround_enabled is used specifically for nx huge pages.
fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
if (fault->huge_page_disallowed)
account_nx_huge_page(vcpu->kvm, sp,
fault->req_level >= it.level);
sp->nx_huge_page_disallowed = fault->huge_page_disallowed.
Affecting fault->huge_page_disallowed would impact
sp->nx_huge_page_disallowed as well and would disable huge pages entirely.
So, we still need to keep nx_huge_page_workaround_enabled.If we introduce a new flag fault->disable_hugepage_adjust, and set it in kvm_mmu_do_page_fault(), we would also need to invoke tdp_mmu_get_root_for_fault() there as well.
Checking for mirror root for non-TDX VMs is not necessary, and the invocation of tdp_mmu_get_root_for_fault() seems redundant with the one in kvm_tdp_mmu_map().
Quoted 14 lines
Quoted 13 lines
arch/x86/kvm/mmu/tdp_mmu.c +2
-1+disallowed_hugepage_adjust (fault, iter.old_spte, iter.level, is_mirror);/* * If SPTE has been frozen by another thread, just give up and @@ -1278,7 +1279,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)*/ sp =tdp_mmu_alloc_sp (vcpu);tdp_mmu_init_child_sp (sp, &iter); -if (is_mirror_sp (sp)) +if (is_mirror)kvm_mmu_alloc_external_spt (vcpu, sp); sp->nx_huge_page_disallowed = fault->huge_page_disallowed;
Edgecombe, Rick P
maintainerRe: [RFC PATCH 10/21] KVM: x86/mmu: Disallow page merging (huge page adjustment) for mirror root
Quoted 5 lines · Yan Zhao
Quoted 5 lines
Maybe we should rename
nx_huge_page_workaround_enabledto something more generic
and do theis_mirrorlogic inkvm_mmu_do_page_fault()when setting it. It should
shrink the diff and centralize the logic.
Quoted 7 lines
Hmm, I'm reluctant to rename
nx_huge_page_workaround_enabled, because(1) Invoking
disallowed_hugepage_adjust()for mirror root is to disable page promotion for TDX private memory, so is only applied to TDP MMU.
(2)nx_huge_page_workaround_enabledis used specifically for nx huge pages.fault->huge_page_disallowed=fault->exec&& fault-Quoted 1 line
nx_huge_page_workaround_enabled;
Oh, good point.
Quoted 12 lines
if (
fault->huge_page_disallowed)account_nx_huge_page(vcpu->kvm, sp, fault->req_level >= it.level);
sp->nx_huge_page_disallowed=fault->huge_page_disallowed.Affecting
fault->huge_page_disallowedwould impactsp->nx_huge_page_disallowedas well and would disable huge pages entirely.So, we still need to keep
nx_huge_page_workaround_enabled.
Quoted 8 lines
If we introduce a new flag
fault->disable_hugepage_adjust, and set it inkvm_mmu_do_page_fault(), we would also need to invoketdp_mmu_get_root_for_fault()there as well.Checking for mirror root for non-TDX VMs is not necessary, and the invocation of
tdp_mmu_get_root_for_fault()seems redundant with the one inkvm_tdp_mmu_map().
Also true. What about a wrapper for MMU code to check instead of fault-
Quoted 1 line
nx_huge_page_workaround_enabledthen?
Also, why not check is_mirror_sp() in disallowed_hugepage_adjust() instead of passing in an is_mirror arg?
There must be a way to have it fit in better with disallowed_hugepage_adjust() without adding so much open coded boolean logic.
Re: [RFC PATCH 10/21] KVM: x86/mmu: Disallow page merging (huge page adjustment) for mirror root
Quoted 32 lines · Rick P
Quoted 5 lines · Yan Zhao
Quoted 5 lines
Maybe we should rename
nx_huge_page_workaround_enabledto something more generic
and do theis_mirrorlogic inkvm_mmu_do_page_fault()when setting it. It should
shrink the diff and centralize the logic.Quoted 7 lines
Hmm, I'm reluctant to rename
nx_huge_page_workaround_enabled, because(1) Invoking
disallowed_hugepage_adjust()for mirror root is to disable page promotion for TDX private memory, so is only applied to TDP MMU.
(2)nx_huge_page_workaround_enabledis used specifically for nx huge pages.fault->huge_page_disallowed=fault->exec&& fault-Quoted 1 line
nx_huge_page_workaround_enabled;Oh, good point.
Quoted 16 lines
if (
fault->huge_page_disallowed)account_nx_huge_page(vcpu->kvm, sp, fault->req_level >= it.level);
sp->nx_huge_page_disallowed=fault->huge_page_disallowed.Affecting
fault->huge_page_disallowedwould impactsp->nx_huge_page_disallowedas well and would disable huge pages entirely.So, we still need to keep
nx_huge_page_workaround_enabled.If we introduce a new flag
fault->disable_hugepage_adjust, and set it inkvm_mmu_do_page_fault(), we would also need to invoketdp_mmu_get_root_for_fault()there as well.
Quoted 7 lines
Quoted 4 lines
Checking for mirror root for non-TDX VMs is not necessary, and the invocation of
tdp_mmu_get_root_for_fault()seems redundant with the one inkvm_tdp_mmu_map().Also true. What about a wrapper for MMU code to check instead of fault-
Quoted 1 line
nx_huge_page_workaround_enabledthen?
Like below?
arch/x86/kvm/mmu/tdp_mmu.c +6 -1
@@ -1275,6 +1275,11 @@ static int tdp_mmu_link_sp(struct kvm *kvm, struct tdp_iter *iter,return 0 ; } +static inline bool is_fault_disallow_huge_page_adust (struct kvm_page_fault *fault,bool is_mirror) +{ +return fault->nx_huge_page_workaround_enabled || is_mirror; +} +/* * Handle a TDP page fault (NPT/EPT violation/misconfiguration) by installing * page tables and SPTEs to translate the faulting guest physical address.
@@ -1297,7 +1302,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)for_each_tdp_pte (iter, kvm, root, fault->gfn, fault->gfn +1 ) {int r; -if (fault->nx_huge_page_workaround_enabled || is_mirror) +if (is_fault_disallow_huge_page_adust (fault, is_mirror))disallowed_hugepage_adjust (fault, iter.old_spte, iter.level, is_mirror);/*
Quoted 2 lines
Also, why not check
is_mirror_sp()indisallowed_hugepage_adjust()instead of passing in anis_mirrorarg?
It's an optimization.
As is_mirror_sptep(iter->sptep) == is_mirror_sp(root), passing in is_mirror arg can avoid checking mirror for each sp, which remains unchanged in a root.
Quoted 2 lines
There must be a way to have it fit in better with
disallowed_hugepage_adjust()without adding so much open coded boolean logic.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 10/21] KVM: x86/mmu: Disallow page merging (huge page adjustment) for mirror root
Quoted 7 lines · Yan Zhao
Like below?
arch/x86/kvm/mmu/tdp_mmu.c +0
-0
arch/x86/kvm/mmu/tdp_mmu.c static int tdp_mmu_link_sp(struct kvm *kvm, struct tdp_iter *iter, · line 1281
Quoted 7 lines
arch/x86/kvm/mmu/tdp_mmu.c +4
-0@@ -1275,6 +1275,11 @@ static int tdp_mmu_link_sp(struct kvm *kvm, struct tdp_iter *iter, return 0; } +static inline bool is_fault_disallow_huge_page_adust (struct kvm_page_fault *fault,bool is_mirror) +{ + return fault->nx_huge_page_workaround_enabled || is_mirror; +}
Err, no. It doesn't seem worth it.
Quoted 16 lines
arch/x86/kvm/mmu/tdp_mmu.c +2
-1+ /** Handle a TDP page fault (NPT/EPT violation/misconfiguration) by installing * page tables and SPTEs to translate the faulting guest physical address. @@ -1297,7 +1302,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) for_each_tdp_pte(iter, kvm, root, fault->gfn, fault->gfn + 1) { int r; - if (fault->nx_huge_page_workaround_enabled || is_mirror) + if (is_fault_disallow_huge_page_adust(fault, is_mirror)) disallowed_hugepage_adjust(fault, iter.old_spte, iter.level, is_mirror); /*
Quoted 3 lines
Quoted 2 lines
Also, why not check
is_mirror_sp()indisallowed_hugepage_adjust()instead of passing in anis_mirrorarg?It's an optimization.
But disallowed_hugepage_adjust() is already checking the sp.
I think part of the thing that is bugging me is that nx_huge_page_workaround_enabled is not conceptually about whether the specific fault/level needs to disallow huge page adjustments, it's whether it needs to check if it does. Then disallowed_hugepage_adjust() does the actual specific checking. But for the mirror logic the check is the same for both. It's asymmetric with NX huge pages, and just sort of jammed in. It would be easier to follow if the kvm_tdp_mmu_map() conditional checked wither mirror TDP was "active", rather than the mirror role.
Quoted 3 lines
As
is_mirror_sptep(iter->sptep)==is_mirror_sp(root), passing inis_mirrorarg can avoid checking mirror for each sp, which remains unchanged in a root.
Why not just this. It seems easier to comprehend to me. It does add a little bit of extra checking in the shared fault for TDX only. I think it's ok and better not to litter the generic MMU code.
arch/x86/kvm/mmu/mmu.c +0 -0
@@ -3328,11 +3328,13 @@ void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu,
struct kvm_page_fault *fault
void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, intcur_level)
{
+ struct kvm_mmu_page * sp = spte_to_child_sp(spte);
+
if (cur_level > PG_LEVEL_4K &&
cur_level == fault->goal_level &&
is_shadow_present_pte(spte) &&
!is_large_pte(spte) &&- spte_to_child_sp(spte)->nx_huge_page_disallowed) {
+ (sp->nx_huge_page_disallowed || sp->role.is_mirror)) {
/*
* A small SPTE exists for this pfn, but FNAME(fetch),
* direct_map(), or kvm_tdp_mmu_map() would like to create a
arch/x86/kvm/mmu/tdp_mmu.c +0 -0
@@ -1244,6 +1244,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct
kvm_page_fault *fault)
struct tdp_iter iter;
struct kvm_mmu_page *sp;
int ret = RET_PF_RETRY;
+ bool hugepage_adjust_disallowed = fault->nx_huge_page_workaround_enabled
||
+ kvm_has_mirrored_tdp(kvm);kvm_mmu_hugepage_adjust(vcpu, fault);
@@ -1254,7 +1256,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
for_each_tdp_pte(iter, kvm, root, fault->gfn, fault->gfn + 1) {
int r;- if (fault->nx_huge_page_workaround_enabled)
+ if (hugepage_adjust_disallowed)
disallowed_hugepage_adjust(fault, iter.old_spte,
iter.level);
/*
/*Re: [RFC PATCH 10/21] KVM: x86/mmu: Disallow page merging (huge page adjustment) for mirror root
Quoted 40 lines · Rick P
Quoted 7 lines · Yan Zhao
Like below?
arch/x86/kvm/mmu/tdp_mmu.c +0
-0arch/x86/kvm/mmu/tdp_mmu.c static int tdp_mmu_link_sp(struct kvm *kvm, struct tdp_iter *iter, · line 1281
Quoted 7 lines
arch/x86/kvm/mmu/tdp_mmu.c +4
-0@@ -1275,6 +1275,11 @@ static int tdp_mmu_link_sp(struct kvm *kvm, struct tdp_iter *iter, return 0; } +static inline bool is_fault_disallow_huge_page_adust (struct kvm_page_fault *fault,bool is_mirror) +{ + return fault->nx_huge_page_workaround_enabled || is_mirror; +}Err, no. It doesn't seem worth it.
Quoted 16 lines
arch/x86/kvm/mmu/tdp_mmu.c +2
-1+ /** Handle a TDP page fault (NPT/EPT violation/misconfiguration) by installing * page tables and SPTEs to translate the faulting guest physical address. @@ -1297,7 +1302,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) for_each_tdp_pte(iter, kvm, root, fault->gfn, fault->gfn + 1) { int r; - if (fault->nx_huge_page_workaround_enabled || is_mirror) + if (is_fault_disallow_huge_page_adust(fault, is_mirror)) disallowed_hugepage_adjust(fault, iter.old_spte, iter.level, is_mirror); /*Quoted 3 lines
Quoted 2 lines
Also, why not check
is_mirror_sp()indisallowed_hugepage_adjust()instead of passing in anis_mirrorarg?It's an optimization.
But
disallowed_hugepage_adjust()is already checking the sp.
Quoted 8 lines
I think part of the thing that is bugging me is that
nx_huge_page_workaround_enabledis not conceptually about whether the specific fault/level needs to disallow huge page adjustments, it's whether it needs to check if it does. Thendisallowed_hugepage_adjust()does the actual specific checking. But for the mirror logic the check is the same for both. It's asymmetric with NX huge pages, and just sort of jammed in. It would be easier to follow if thekvm_tdp_mmu_map()conditional checked wither mirror TDP was "active", rather than the mirror role.
You are right. It looks clearer.
Quoted 15 lines
Quoted 3 lines
As
is_mirror_sptep(iter->sptep)==is_mirror_sp(root), passing inis_mirrorarg can avoid checking mirror for each sp, which remains unchanged in a root.Why not just this. It seems easier to comprehend to me. It does add a little bit of extra checking in the shared fault for TDX only. I think it's ok and better not to litter the generic MMU code.
arch/x86/kvm/mmu/mmu.c +0
-0@@ -3328,11 +3328,13 @@ void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu,struct
kvm_page_fault*fault
Quoted 4 lines
void disallowed_hugepage_adjust(struct
kvm_page_fault*fault, u64 spte, intcur_level)
{
+ structkvm_mmu_page* sp =spte_to_child_sp(spte);
if !is_shadow_present_pte(spte) or spte is an leaf entry, it's incorrect to retrieve child sp. So, maybe
- spte_to_child_sp(spte)->nx_huge_page_disallowed) {
+ (spte_to_child_sp(spte)->nx_huge_page_disallowed &&
+ is_mirror_sp(spte_to_child_sp(spte))) {
Other changes look good to me.
Quoted 40 lines
arch/x86/kvm/mmu/mmu.c +2
-1+if (cur_level >PG_LEVEL_4K && cur_level == fault->goal_level &&is_shadow_present_pte (spte) && !is_large_pte (spte) && -spte_to_child_sp (spte)->nx_huge_page_disallowed) { + (sp->nx_huge_page_disallowed || sp->role.is_mirror)) {/* * A small SPTE exists for this pfn, but FNAME(fetch), * direct_map(), or kvm_tdp_mmu_map() would like to create a arch/x86/kvm/mmu/tdp_mmu.c +1
-0@@ -1244,6 +1244,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)struct tdp_iter iter;struct kvm_mmu_page *sp;int ret =RET_PF_RETRY ; +bool hugepage_adjust_disallowed = fault->nx_huge_page_workaround_enabled||
arch/x86/kvm/mmu/tdp_mmu.c +2
-1+kvm_has_mirrored_tdp (kvm);kvm_mmu_hugepage_adjust (vcpu, fault);@@ -1254,7 +1256,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)for_each_tdp_pte (iter, kvm, root, fault->gfn, fault->gfn +1 ) {int r; -if (fault->nx_huge_page_workaround_enabled) +if (hugepage_adjust_disallowed)disallowed_hugepage_adjust (fault, iter.old_spte, iter.level);/* /*
RFC PATCH 11/21 KVM: x86: Add "vcpu" "gfn" parameters to x86 hook private_max_mapping_level
In reply to Yan ZhaoIntroduce "vcpu" and "gfn" parameters to the KVM x86 hook private_max_mapping_level.
This is a preparation to enable TDX to return the max mapping level for a specific GFN in a vCPU.
No functional change expected.
--- arch/x86/include/asm/kvm_host.h | 2 +- arch/x86/kvm/mmu/mmu.c | 6 +++--- arch/x86/kvm/svm/sev.c | 4 ++-- arch/x86/kvm/svm/svm.h | 4 ++-- arch/x86/kvm/vmx/main.c | 6 +++--- arch/x86/kvm/vmx/tdx.c | 4 ++-- arch/x86/kvm/vmx/x86_ops.h | 4 ++-- 7 files changed, 15 insertions(+), 15 deletions(-)
arch/x86/include/asm/kvm_host.h +1 -1
@@ -1896,7 +1896,7 @@ struct kvm_x86_ops {void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu);int (*gmem_prepare)(struct kvm *kvm,kvm_pfn_t pfn,gfn_t gfn,int max_order);void (*gmem_invalidate)(kvm_pfn_t start,kvm_pfn_t end); -int (*private_max_mapping_level)(struct kvm *kvm,kvm_pfn_t pfn); +int (*private_max_mapping_level)(struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn); };struct kvm_x86_nested_ops {
arch/x86/kvm/mmu/mmu.c +3 -3
@@ -4466,7 +4466,7 @@ static inline u8 kvm_max_level_for_order(int order)return PG_LEVEL_4K ; } -static u8 kvm_max_private_mapping_level (struct kvm *kvm,kvm_pfn_t pfn, +static u8 kvm_max_private_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn,u8 max_level,int gmem_order) {u8 req_max_level;
@@ -4478,7 +4478,7 @@ static u8 kvm_max_private_mapping_level(struct kvm *kvm, kvm_pfn_t pfn,if (max_level ==PG_LEVEL_4K )return PG_LEVEL_4K ; - req_max_level =kvm_x86_call (private_max_mapping_level)(kvm, pfn); + req_max_level =kvm_x86_call (private_max_mapping_level)(vcpu, pfn, gfn);if (req_max_level) max_level =min (max_level, req_max_level);
@@ -4510,7 +4510,7 @@ static int kvm_mmu_faultin_pfn_private(struct kvm_vcpu *vcpu, } fault->map_writable = !(fault->slot->flags &KVM_MEM_READONLY ); - fault->max_level =kvm_max_private_mapping_level (vcpu->kvm, fault->pfn, + fault->max_level =kvm_max_private_mapping_level (vcpu, fault->pfn, fault->gfn, fault->max_level, max_order);return RET_PF_CONTINUE ;
arch/x86/kvm/svm/sev.c +2 -2
@@ -4910,12 +4910,12 @@ void sev_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end) } } -int sev_private_max_mapping_level (struct kvm *kvm,kvm_pfn_t pfn) +int sev_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) {int level, rc;bool assigned; -if (!sev_snp_guest (kvm)) +if (!sev_snp_guest (vcpu->kvm))return 0 ; rc =snp_lookup_rmpentry (pfn, &assigned, &level);
arch/x86/kvm/svm/svm.h +2 -2
@@ -782,7 +782,7 @@ void sev_handle_rmp_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code);void sev_snp_init_protected_guest_state (struct kvm_vcpu *vcpu);int sev_gmem_prepare (struct kvm *kvm,kvm_pfn_t pfn,gfn_t gfn,int max_order);void sev_gmem_invalidate (kvm_pfn_t start,kvm_pfn_t end); -int sev_private_max_mapping_level (struct kvm *kvm,kvm_pfn_t pfn); +int sev_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn);#else static inline struct page *snp_safe_alloc_page_node (int node,gfp_t gfp) {
@@ -809,7 +809,7 @@ static inline int sev_gmem_prepare(struct kvm *kvm, kvm_pfn_t pfn, gfn_t gfn, inreturn 0 ; }static inline void sev_gmem_invalidate (kvm_pfn_t start,kvm_pfn_t end) {} -static inline int sev_private_max_mapping_level (struct kvm *kvm,kvm_pfn_t pfn) +static inline int sev_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) {return 0 ; }
arch/x86/kvm/vmx/main.c +3 -3
@@ -880,10 +880,10 @@ static int vt_vcpu_mem_enc_ioctl(struct kvm_vcpu *vcpu, void __user *argp)return tdx_vcpu_ioctl (vcpu, argp); } -static int vt_gmem_private_max_mapping_level (struct kvm *kvm,kvm_pfn_t pfn) +static int vt_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) { -if (is_td (kvm)) -return tdx_gmem_private_max_mapping_level (kvm, pfn); +if (is_td (vcpu->kvm)) +return tdx_gmem_private_max_mapping_level (vcpu, pfn, gfn);return 0 ; }
arch/x86/kvm/vmx/tdx.c +2 -2
@@ -3258,9 +3258,9 @@ int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp)return ret; } -int tdx_gmem_private_max_mapping_level (struct kvm *kvm,kvm_pfn_t pfn) +int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) { -if (unlikely (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE )) +if (unlikely (to_kvm_tdx (vcpu->kvm)->state !=TD_STATE_RUNNABLE ))return PG_LEVEL_4K ;return PG_LEVEL_2M ;
arch/x86/kvm/vmx/x86_ops.h +2 -2
@@ -162,7 +162,7 @@ int tdx_sept_remove_private_spte(struct kvm *kvm, gfn_t gfn,void tdx_flush_tlb_current (struct kvm_vcpu *vcpu);void tdx_flush_tlb_all (struct kvm_vcpu *vcpu);void tdx_load_mmu_pgd (struct kvm_vcpu *vcpu,hpa_t root_hpa,int root_level); -int tdx_gmem_private_max_mapping_level (struct kvm *kvm,kvm_pfn_t pfn); +int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn);#else static inline void tdx_disable_virtualization_cpu (void ) {}static inline int tdx_vm_init (struct kvm *kvm) {return -EOPNOTSUPP ; }
@@ -227,7 +227,7 @@ static inline int tdx_sept_remove_private_spte(struct kvm *kvm, gfn_t gfn,static inline void tdx_flush_tlb_current (struct kvm_vcpu *vcpu) {}static inline void tdx_flush_tlb_all (struct kvm_vcpu *vcpu) {}static inline void tdx_load_mmu_pgd (struct kvm_vcpu *vcpu,hpa_t root_hpa,int root_level) {} -static inline int tdx_gmem_private_max_mapping_level (struct kvm *kvm,kvm_pfn_t pfn) {return 0 ; } +static inline int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) {return 0 ; }#endif #endif /* __KVM_X86_VMX_X86_OPS_H */
Signature · 1 line
2.43.2
RFC PATCH 12/21 KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
In reply to Yan ZhaoDetermine the max mapping level of a private GFN according to the vCPU's ACCEPT level specified in the TDCALL TDG.MEM.PAGE.ACCEPT.
When an EPT violation occurs due to a vCPU invoking TDG.MEM.PAGE.ACCEPT before any actual memory access, the vCPU's ACCEPT level is available in the extended exit qualification. Set the vCPU's ACCEPT level as the max mapping level for the faulting GFN. This is necessary because if KVM specifies a mapping level greater than the vCPU's ACCEPT level, and no other vCPUs are accepting at KVM's mapping level, TDG.MEM.PAGE.ACCEPT will produce another EPT violation on the vCPU after re-entering the TD, with the vCPU's ACCEPT level indicated in the extended exit qualification.
Introduce "violation_gfn_start", "violation_gfn_end", and "violation_request_level" in "struct vcpu_tdx" to pass the vCPU's ACCEPT level to TDX's private_max_mapping_level hook for determining the max mapping level.
Instead of taking some bits of the error_code passed to kvm_mmu_page_fault() and requiring KVM MMU core to check the error_code for a fault's max_level, having TDX's private_max_mapping_level hook check for request level avoids changes to the KVM MMU core. This approach also accommodates future scenarios where the requested mapping level is unknown at the start of tdx_handle_ept_violation() (i.e., before invoking kvm_mmu_page_fault()).
--- arch/x86/kvm/vmx/tdx.c | 36 +++++++++++++++++++++++++++++++++++- arch/x86/kvm/vmx/tdx.h | 4 ++++ arch/x86/kvm/vmx/tdx_arch.h | 3 +++ 3 files changed, 42 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/tdx.c +35 -1
@@ -1859,10 +1859,34 @@ static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcpreturn !(eq &EPT_VIOLATION_PROT_MASK ) && !(eq &EPT_VIOLATION_EXEC_FOR_RING3_LIN ); } +static inline void tdx_get_accept_level (struct kvm_vcpu *vcpu,gpa_t gpa) +{ +struct vcpu_tdx *tdx =to_tdx (vcpu); +int level =-1 ; + +u64 eeq_type = tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_TYPE_MASK ; + +u32 eeq_info = (tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_INFO_MASK ) >> +TDX_EXT_EXIT_QUAL_INFO_SHIFT ; + +if (eeq_type ==TDX_EXT_EXIT_QUAL_TYPE_ACCEPT ) { + level = (eeq_info &GENMASK (2 ,0 )) +1 ; + + tdx->violation_gfn_start =gfn_round_for_level (gpa_to_gfn (gpa), level); + tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); + tdx->violation_request_level = level; + }else { + tdx->violation_gfn_start =-1 ; + tdx->violation_gfn_end =-1 ; + tdx->violation_request_level =-1 ; + } +} +static int tdx_handle_ept_violation (struct kvm_vcpu *vcpu) {unsigned long exit_qual; -gpa_t gpa =to_tdx (vcpu)->exit_gpa; +struct vcpu_tdx *tdx =to_tdx (vcpu); +gpa_t gpa = tdx->exit_gpa;bool local_retry = false;int ret;
@@ -1884,6 +1908,8 @@ static int tdx_handle_ept_violation(struct kvm_vcpu *vcpu)*/ exit_qual =EPT_VIOLATION_ACC_WRITE ; +tdx_get_accept_level (vcpu, gpa); +/* Only private GPA triggers zero-step mitigation */ local_retry = true; }else {
@@ -2917,6 +2943,9 @@ static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx) vcpu->arch.mp_state =KVM_MP_STATE_RUNNABLE ; + tdx->violation_gfn_start =-1 ; + tdx->violation_gfn_end =-1 ; + tdx->violation_request_level =-1 ;return 0 ; free_tdcx:
@@ -3260,9 +3289,14 @@ int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp)int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) { +struct vcpu_tdx *tdx =to_tdx (vcpu); +if (unlikely (to_kvm_tdx (vcpu->kvm)->state !=TD_STATE_RUNNABLE ))return PG_LEVEL_4K ; +if (gfn >= tdx->violation_gfn_start && gfn < tdx->violation_gfn_end) +return tdx->violation_request_level; +return PG_LEVEL_2M ; }
arch/x86/kvm/vmx/tdx.h +4 -0
@@ -70,6 +70,10 @@ struct vcpu_tdx {u64 map_gpa_next;u64 map_gpa_end; + +u64 violation_gfn_start; +u64 violation_gfn_end; +int violation_request_level; };void tdh_vp_rd_failed (struct vcpu_tdx *tdx,char *uclass,u32 field,u64 err);
arch/x86/kvm/vmx/tdx_arch.h +3 -0
@@ -82,7 +82,10 @@ struct tdx_cpuid_value {#define TDX_TD_ATTR_PERFMON BIT_ULL(63)#define TDX_EXT_EXIT_QUAL_TYPE_MASK GENMASK(3, 0) +#define TDX_EXT_EXIT_QUAL_TYPE_ACCEPT 1#define TDX_EXT_EXIT_QUAL_TYPE_PENDING_EPT_VIOLATION 6 +#define TDX_EXT_EXIT_QUAL_INFO_MASK GENMASK(63, 32) +#define TDX_EXT_EXIT_QUAL_INFO_SHIFT 32/* * TD_PARAMS is provided as an input to TDH_MNG_INIT, the size of which is 1024B. */
Signature · 1 line
2.43.2
Edgecombe, Rick P
maintainerRe: [RFC PATCH 12/21] KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
Quoted 11 lines · Yan Zhao
Determine the max mapping level of a private GFN according to the vCPU's ACCEPT level specified in the TDCALL TDG.MEM.PAGE.ACCEPT.
When an EPT violation occurs due to a vCPU invoking TDG.MEM.PAGE.ACCEPT before any actual memory access, the vCPU's ACCEPT level is available in the extended exit qualification. Set the vCPU's ACCEPT level as the max mapping level for the faulting GFN. This is necessary because if KVM specifies a mapping level greater than the vCPU's ACCEPT level, and no other vCPUs are accepting at KVM's mapping level, TDG.MEM.PAGE.ACCEPT will produce another EPT violation on the vCPU after re-entering the TD, with the vCPU's ACCEPT level indicated in the extended exit qualification.
Maybe a little more info would help. It's because the TDX module wants to "accept" the smaller size in the real S-EPT, but KVM created a huge page. It can't demote to do this without help from KVM.
Quoted 40 lines
Introduce "
violation_gfn_start", "violation_gfn_end", and "violation_request_level" in "structvcpu_tdx" to pass the vCPU's ACCEPT level to TDX'sprivate_max_mapping_levelhook for determining the max mapping level.Instead of taking some bits of the
error_codepassed tokvm_mmu_page_fault()and requiring KVM MMU core to check theerror_codefor a fault'smax_level, having TDX'sprivate_max_mapping_levelhook check for request level avoids changes to the KVM MMU core. This approach also accommodates future scenarios where the requested mapping level is unknown at the start oftdx_handle_ept_violation()(i.e., before invokingkvm_mmu_page_fault()).Signed-off-by Xiaoyao Li <[email protected]>Signed-off-by Yan Zhao <[email protected]>--- arch/x86/kvm/vmx/tdx.c | 36 +++++++++++++++++++++++++++++++++++- arch/x86/kvm/vmx/tdx.h | 4 ++++ arch/x86/kvm/vmx/tdx_arch.h | 3 +++ 3 files changed, 42 insertions(+), 1 deletion(-)arch/x86/kvm/vmx/tdx.c +10
-0@@ -1859,10 +1859,34 @@ static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcpreturn !(eq &EPT_VIOLATION_PROT_MASK ) && !(eq &EPT_VIOLATION_EXEC_FOR_RING3_LIN ); } +static inline void tdx_get_accept_level (struct kvm_vcpu *vcpu,gpa_t gpa) +{ +struct vcpu_tdx *tdx =to_tdx (vcpu); +int level =-1 ; + +u64 eeq_type = tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_TYPE_MASK ; + +u32 eeq_info = (tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_INFO_MASK ) >> +TDX_EXT_EXIT_QUAL_INFO_SHIFT ; +
arch/x86/kvm/vmx/tdx.c static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcp · line 1881
Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10
-0+if (eeq_type ==TDX_EXT_EXIT_QUAL_TYPE_ACCEPT ) { + level = (eeq_info &GENMASK (2 ,0 )) +1 ; + + tdx->violation_gfn_start =gfn_round_for_level (gpa_to_gfn (gpa), level); + tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); + tdx->violation_request_level = level; + }else { + tdx->violation_gfn_start =-1 ; + tdx->violation_gfn_end =-1 ; + tdx->violation_request_level =-1 ;
We had some internal conversations on how KVM used to stuff a bunch of fault stuff in the vcpu so it didn't have to pass it around, but now uses the fault struct for this. The point was (IIRC) to prevent stale data from getting confused on future faults, and it being hard to track what came from where.
In the TDX case, I think the potential for confusion is still there. The MMU code could use stale data if an accept EPT violation happens and control returns to userspace, at which point userspace does a KVM_PRE_FAULT_MEMORY. Then it will see the stale tdx->violation_*. Not exactly a common case, but better to not have loose ends if we can avoid it.
Looking more closely, I don't see why it's too hard to pass in a max_fault_level into the fault struct. Totally untested rough idea, what do you think?
arch/x86/include/asm/kvm_host.h +5 -1
@@ -282,7 +282,11 @@ enum x86_intercept_stage;* when the guest was accessing private memory. */ #define PFERR_PRIVATE_ACCESS BIT_ULL(49) -#define PFERR_SYNTHETIC_MASK (PFERR_IMPLICIT_ACCESS | PFERR_PRIVATE_ACCESS) + +#define PFERR_FAULT_LEVEL_MASK (BIT_ULL(50) | BIT_ULL(51) | BIT_ULL(52)) +#define PFERR_FAULT_LEVEL_SHIFT 50 + +#define PFERR_SYNTHETIC_MASK (PFERR_IMPLICIT_ACCESS | PFERR_PRIVATE_ACCESS |
PFERR_FAULT_LEVEL_MASK)
/* apic attention bits */
#define KVM_APIC_CHECK_VAPIC 0
arch/x86/kvm/mmu/mmu_internal.h +0 -0
@@ -361,7 +361,7 @@ static inline int kvm_mmu_do_page_fault(struct kvm_vcpu
*vcpu, gpa_t cr2_or_gpa,
.nx_huge_page_workaround_enabled =
is_nx_huge_page_enabled(vcpu->kvm),- .max_level = KVM_MAX_HUGEPAGE_LEVEL,
+ .max_level = (err & PFERR_FAULT_LEVEL_MASK) >>PFERR_FAULT_LEVEL_SHIFT,
.req_level = PG_LEVEL_4K,
.goal_level = PG_LEVEL_4K,
.is_private = err & PFERR_PRIVATE_ACCESS,arch/x86/kvm/vmx/common.h +0 -0
@@ -83,7 +83,8 @@ static inline bool vt_is_tdx_private_gpa(struct kvm *kvm,
gpa_t gpa)
}
static inline int __vmx_handle_ept_violation(struct kvm_vcpu *vcpu, gpa_t gpa,
- unsigned long exit_qualification)
+ unsigned long exit_qualification,
+ u8 max_fault_level)
{
u64 error_code;@@ -107,6 +108,10 @@ static inline int __vmx_handle_ept_violation(struct kvm_vcpu *vcpu, gpa_t gpa,
if (vt_is_tdx_private_gpa(vcpu->kvm, gpa))
error_code |= PFERR_PRIVATE_ACCESS;+ BUILD_BUG_ON(KVM_MAX_HUGEPAGE_LEVEL >= (1 <<hweight64(PFERR_FAULT_LEVEL_MASK)));
+
+ error_code |= (u64)max_fault_level << PFERR_FAULT_LEVEL_SHIFT;
+
return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
}
arch/x86/kvm/vmx/tdx.c +1 -1
@@ -2027,7 +2027,7 @@ static int tdx_handle_ept_violation(struct kvm_vcpu *vcpu)* handle retries locally in their EPT violation handlers. */ while (1 ) { - ret =__vmx_handle_ept_violation (vcpu, gpa, exit_qual); + ret = __vmx_handle_ept_violation(vcpu, gpa, exit_qual,
KVM_MAX_HUGEPAGE_LEVEL);
if (ret != RET_PF_RETRY || !local_retry)
break;arch/x86/kvm/vmx/vmx.c +0 -0
@@ -5782,7 +5782,7 @@ static int handle_ept_violation(struct kvm_vcpu *vcpu) if (unlikely(allow_smaller_maxphyaddr && !kvm_vcpu_is_legal_gpa(vcpu,
gpa)))
return kvm_emulate_instruction(vcpu, 0);
- return __vmx_handle_ept_violation(vcpu, gpa, exit_qualification);
+ return __vmx_handle_ept_violation(vcpu, gpa, exit_qualification,KVM_MAX_HUGEPAGE_LEVEL);
}
static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
Re: [RFC PATCH 12/21] KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
Quoted 73 lines · Rick P
Quoted 11 lines · Yan Zhao
Determine the max mapping level of a private GFN according to the vCPU's ACCEPT level specified in the TDCALL TDG.MEM.PAGE.ACCEPT.
When an EPT violation occurs due to a vCPU invoking TDG.MEM.PAGE.ACCEPT before any actual memory access, the vCPU's ACCEPT level is available in the extended exit qualification. Set the vCPU's ACCEPT level as the max mapping level for the faulting GFN. This is necessary because if KVM specifies a mapping level greater than the vCPU's ACCEPT level, and no other vCPUs are accepting at KVM's mapping level, TDG.MEM.PAGE.ACCEPT will produce another EPT violation on the vCPU after re-entering the TD, with the vCPU's ACCEPT level indicated in the extended exit qualification.
Maybe a little more info would help. It's because the TDX module wants to "accept" the smaller size in the real S-EPT, but KVM created a huge page. It can't demote to do this without help from KVM.
Quoted 40 lines
Introduce "
violation_gfn_start", "violation_gfn_end", and "violation_request_level" in "structvcpu_tdx" to pass the vCPU's ACCEPT level to TDX'sprivate_max_mapping_levelhook for determining the max mapping level.Instead of taking some bits of the
error_codepassed tokvm_mmu_page_fault()and requiring KVM MMU core to check theerror_codefor a fault'smax_level, having TDX'sprivate_max_mapping_levelhook check for request level avoids changes to the KVM MMU core. This approach also accommodates future scenarios where the requested mapping level is unknown at the start oftdx_handle_ept_violation()(i.e., before invokingkvm_mmu_page_fault()).Signed-off-by Xiaoyao Li <[email protected]>Signed-off-by Yan Zhao <[email protected]>--- arch/x86/kvm/vmx/tdx.c | 36 +++++++++++++++++++++++++++++++++++- arch/x86/kvm/vmx/tdx.h | 4 ++++ arch/x86/kvm/vmx/tdx_arch.h | 3 +++ 3 files changed, 42 insertions(+), 1 deletion(-)arch/x86/kvm/vmx/tdx.c +10
-0@@ -1859,10 +1859,34 @@ static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcpreturn !(eq &EPT_VIOLATION_PROT_MASK ) && !(eq &EPT_VIOLATION_EXEC_FOR_RING3_LIN ); } +static inline void tdx_get_accept_level (struct kvm_vcpu *vcpu,gpa_t gpa) +{ +struct vcpu_tdx *tdx =to_tdx (vcpu); +int level =-1 ; + +u64 eeq_type = tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_TYPE_MASK ; + +u32 eeq_info = (tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_INFO_MASK ) >> +TDX_EXT_EXIT_QUAL_INFO_SHIFT ; +arch/x86/kvm/vmx/tdx.c static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcp · line 1881
Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10
-0+if (eeq_type ==TDX_EXT_EXIT_QUAL_TYPE_ACCEPT ) { + level = (eeq_info &GENMASK (2 ,0 )) +1 ; + + tdx->violation_gfn_start =gfn_round_for_level (gpa_to_gfn (gpa), level); + tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); + tdx->violation_request_level = level; + }else { + tdx->violation_gfn_start =-1 ; + tdx->violation_gfn_end =-1 ; + tdx->violation_request_level =-1 ;We had some internal conversations on how KVM used to stuff a bunch of fault stuff in the vcpu so it didn't have to pass it around, but now uses the fault struct for this. The point was (IIRC) to prevent stale data from getting confused on future faults, and it being hard to track what came from where.
Quoted 8 lines
In the TDX case, I think the potential for confusion is still there. The MMU code could use stale data if an accept EPT violation happens and control returns to userspace, at which point userspace does a
KVM_PRE_FAULT_MEMORY. Then it will see the stale tdx->violation_*. Not exactly a common case, but better to not have loose ends if we can avoid it.Looking more closely, I don't see why it's too hard to pass in a
max_fault_levelinto the fault struct. Totally untested rough idea, what do you think?
the original huge page support patch did encode the level info in error_code. So it has my vote.
Quoted 92 lines
arch/x86/include/asm/kvm_host.h +5
-1@@ -282,7 +282,11 @@ enum x86_intercept_stage;* when the guest was accessing private memory. */ #define PFERR_PRIVATE_ACCESS BIT_ULL(49) -#define PFERR_SYNTHETIC_MASK (PFERR_IMPLICIT_ACCESS | PFERR_PRIVATE_ACCESS) + +#define PFERR_FAULT_LEVEL_MASK (BIT_ULL(50) | BIT_ULL(51) | BIT_ULL(52)) +#define PFERR_FAULT_LEVEL_SHIFT 50 + +#define PFERR_SYNTHETIC_MASK (PFERR_IMPLICIT_ACCESS | PFERR_PRIVATE_ACCESS | PFERR_FAULT_LEVEL_MASK)/* apic attention bits */ #define KVM_APIC_CHECK_VAPIC 0arch/x86/kvm/mmu/mmu_internal.h +1
-1@@ -361,7 +361,7 @@ static inline int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, .nx_huge_page_workaround_enabled =is_nx_huge_page_enabled (vcpu->kvm), - .max_level = KVM_MAX_HUGEPAGE_LEVEL, + .max_level = (err & PFERR_FAULT_LEVEL_MASK) >>PFERR_FAULT_LEVEL_SHIFT , .req_level = PG_LEVEL_4K,.goal_level =
PG_LEVEL_4K, .is_private = err &PFERR_PRIVATE_ACCESS,arch/x86/kvm/vmx/common.h +6
-1@@ -83,7 +83,8 @@ static inline bool vt_is_tdx_private_gpa(struct kvm *kvm, gpa_t gpa) }static inline int __vmx_handle_ept_violation (struct kvm_vcpu *vcpu,gpa_t gpa, -unsigned long exit_qualification) +unsigned long exit_qualification, +u8 max_fault_level) {u64 error_code;@@ -107,6 +108,10 @@ static inline int __vmx_handle_ept_violation(struct kvm_vcpu *vcpu, gpa_t gpa, if (vt_is_tdx_private_gpa(vcpu->kvm, gpa)) error_code |= PFERR_PRIVATE_ACCESS; +BUILD_BUG_ON (KVM_MAX_HUGEPAGE_LEVEL >= (1 <<hweight64 (PFERR_FAULT_LEVEL_MASK ))); + + error_code |= (u64 )max_fault_level <<PFERR_FAULT_LEVEL_SHIFT ; +return kvm_mmu_page_fault (vcpu, gpa, error_code,NULL ,0 );}arch/x86/kvm/vmx/tdx.c +1
-1@@ -2027,7 +2027,7 @@ static int tdx_handle_ept_violation(struct kvm_vcpu *vcpu)* handle retries locally in their EPT violation handlers. */ while (1 ) { - ret =__vmx_handle_ept_violation (vcpu, gpa, exit_qual); + ret =__vmx_handle_ept_violation (vcpu, gpa, exit_qual,KVM_MAX_HUGEPAGE_LEVEL );if (ret !=RET_PF_RETRY || !local_retry)break;arch/x86/kvm/vmx/vmx.c +1
-1@@ -5782,7 +5782,7 @@ static int handle_ept_violation(struct kvm_vcpu *vcpu)if (unlikely (allow_smaller_maxphyaddr && !kvm_vcpu_is_legal_gpa (vcpu, gpa)))return kvm_emulate_instruction (vcpu,0 ); -return __vmx_handle_ept_violation (vcpu, gpa, exit_qualification); +return __vmx_handle_ept_violation (vcpu, gpa, exit_qualification,KVM_MAX_HUGEPAGE_LEVEL ); }static int
handle_ept_misconfig(struct kvm_vcpu *vcpu)
Re: [RFC PATCH 12/21] KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
In reply to Edgecombe, Rick PQuoted 13 lines · Rick P
Quoted 11 lines · Yan Zhao
Determine the max mapping level of a private GFN according to the vCPU's ACCEPT level specified in the TDCALL TDG.MEM.PAGE.ACCEPT.
When an EPT violation occurs due to a vCPU invoking TDG.MEM.PAGE.ACCEPT before any actual memory access, the vCPU's ACCEPT level is available in the extended exit qualification. Set the vCPU's ACCEPT level as the max mapping level for the faulting GFN. This is necessary because if KVM specifies a mapping level greater than the vCPU's ACCEPT level, and no other vCPUs are accepting at KVM's mapping level, TDG.MEM.PAGE.ACCEPT will produce another EPT violation on the vCPU after re-entering the TD, with the vCPU's ACCEPT level indicated in the extended exit qualification.
Quoted 3 lines
Maybe a little more info would help. It's because the TDX module wants to "accept" the smaller size in the real S-EPT, but KVM created a huge page. It can't demote to do this without help from KVM.
Ok. Right, the TDX module cannot set the entire 2MB mapping to the accepted state because the guest only specifies 4KB acceptance. The TDX module cannot perform demotion without a request from KVM. Therefore, the requested level must be passed to KVM to ensure the mirror page table faults at the expected level.
Quoted 55 lines
Quoted 39 lines
Introduce "
violation_gfn_start", "violation_gfn_end", and "violation_request_level" in "structvcpu_tdx" to pass the vCPU's ACCEPT level to TDX'sprivate_max_mapping_levelhook for determining the max mapping level.Instead of taking some bits of the
error_codepassed tokvm_mmu_page_fault()and requiring KVM MMU core to check theerror_codefor a fault'smax_level, having TDX'sprivate_max_mapping_levelhook check for request level avoids changes to the KVM MMU core. This approach also accommodates future scenarios where the requested mapping level is unknown at the start oftdx_handle_ept_violation()(i.e., before invokingkvm_mmu_page_fault()).Signed-off-by Xiaoyao Li <[email protected]>Signed-off-by Yan Zhao <[email protected]>--- arch/x86/kvm/vmx/tdx.c | 36 +++++++++++++++++++++++++++++++++++- arch/x86/kvm/vmx/tdx.h | 4 ++++ arch/x86/kvm/vmx/tdx_arch.h | 3 +++ 3 files changed, 42 insertions(+), 1 deletion(-)arch/x86/kvm/vmx/tdx.c +10
-0@@ -1859,10 +1859,34 @@ static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcpreturn !(eq &EPT_VIOLATION_PROT_MASK ) && !(eq &EPT_VIOLATION_EXEC_FOR_RING3_LIN ); } +static inline void tdx_get_accept_level (struct kvm_vcpu *vcpu,gpa_t gpa) +{ +struct vcpu_tdx *tdx =to_tdx (vcpu); +int level =-1 ; + +u64 eeq_type = tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_TYPE_MASK ; + +u32 eeq_info = (tdx->ext_exit_qualification &TDX_EXT_EXIT_QUAL_INFO_MASK ) >> +TDX_EXT_EXIT_QUAL_INFO_SHIFT ; +arch/x86/kvm/vmx/tdx.c static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcp · line 1881
Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10
-0+if (eeq_type ==TDX_EXT_EXIT_QUAL_TYPE_ACCEPT ) { + level = (eeq_info &GENMASK (2 ,0 )) +1 ; + + tdx->violation_gfn_start =gfn_round_for_level (gpa_to_gfn (gpa), level); + tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); + tdx->violation_request_level = level; + }else { + tdx->violation_gfn_start =-1 ; + tdx->violation_gfn_end =-1 ; + tdx->violation_request_level =-1 ;We had some internal conversations on how KVM used to stuff a bunch of fault stuff in the vcpu so it didn't have to pass it around, but now uses the fault struct for this. The point was (IIRC) to prevent stale data from getting confused on future faults, and it being hard to track what came from where.
Quoted 8 lines
In the TDX case, I think the potential for confusion is still there. The MMU code could use stale data if an accept EPT violation happens and control returns to userspace, at which point userspace does a
KVM_PRE_FAULT_MEMORY. Then it will see the stale tdx->violation_*. Not exactly a common case, but better to not have loose ends if we can avoid it.Looking more closely, I don't see why it's too hard to pass in a
max_fault_levelinto the fault struct. Totally untested rough idea, what do you think?
Thanks for bringing this up and providing the idea below. In the previous TDX huge page v8, there's a similar implementation [1] [2].
This series did not adopt that approach because that approach requires tdx_handle_ept_violation() to pass in max_fault_level, which is not always available at that stage. e.g.
In patch 19, when vCPU 1 faults on a GFN at 2MB level and then vCPU 2 faults on the same GFN at 4KB level, TDX wants to ignore the demotion request caused by vCPU 2's 4KB level fault. So, patch 19 sets tdx->violation_request_level to 2MB in vCPU 2's split callback and fails the split. vCPU 2's __vmx_handle_ept_violation() will see RET_PF_RETRY and either do local retry (or return to the guest).
If it retries locally, tdx_gmem_private_max_mapping_level() will return tdx->violation_request_level, causing KVM to fault at 2MB level for vCPU 2, resulting in a spurious fault, eventually returning to the guest.
As tdx->violation_request_level is per-vCPU and it resets in tdx_get_accept_level() in tdx_handle_ept_violation() (meaning it resets after each invocation of tdx_handle_ept_violation() and only affects the TDX local retry loop), it should not hold any stale value.
Alternatively, instead of having tdx_gmem_private_max_mapping_level() to return tdx->violation_request_level, tdx_handle_ept_violation() could grab tdx->violation_request_level as the max_fault_level to pass to __vmx_handle_ept_violation().
This series chose to use tdx_gmem_private_max_mapping_level() to avoid modification to the KVM MMU core.
[1] https://lore.kernel.org/all/4d61104bff388a081ff8f6ae4ac71e05a13e53c3.1708933624.git.isaku.yamahata@intel.com/
[2 ]https://lore.kernel.org/all/3d2a6bfb033ee1b51f7b875360bd295376c32b54.1708933624.git.isaku.yamahata@intel.com/
Quoted 92 lines
arch/x86/include/asm/kvm_host.h +5
-1@@ -282,7 +282,11 @@ enum x86_intercept_stage;* when the guest was accessing private memory. */ #define PFERR_PRIVATE_ACCESS BIT_ULL(49) -#define PFERR_SYNTHETIC_MASK (PFERR_IMPLICIT_ACCESS | PFERR_PRIVATE_ACCESS) + +#define PFERR_FAULT_LEVEL_MASK (BIT_ULL(50) | BIT_ULL(51) | BIT_ULL(52)) +#define PFERR_FAULT_LEVEL_SHIFT 50 + +#define PFERR_SYNTHETIC_MASK (PFERR_IMPLICIT_ACCESS | PFERR_PRIVATE_ACCESS | PFERR_FAULT_LEVEL_MASK)/* apic attention bits */ #define
KVM_APIC_CHECK_VAPIC0arch/x86/kvm/mmu/mmu_internal.h +1
-1@@ -361,7 +361,7 @@ static inline int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, .nx_huge_page_workaround_enabled =is_nx_huge_page_enabled (vcpu->kvm), - .max_level = KVM_MAX_HUGEPAGE_LEVEL, + .max_level = (err & PFERR_FAULT_LEVEL_MASK) >>PFERR_FAULT_LEVEL_SHIFT , .req_level = PG_LEVEL_4K,.goal_level =
PG_LEVEL_4K, .is_private = err &PFERR_PRIVATE_ACCESS,arch/x86/kvm/vmx/common.h +6
-1@@ -83,7 +83,8 @@ static inline bool vt_is_tdx_private_gpa(struct kvm *kvm, gpa_t gpa) }static inline int __vmx_handle_ept_violation (struct kvm_vcpu *vcpu,gpa_t gpa, -unsigned long exit_qualification) +unsigned long exit_qualification, +u8 max_fault_level) {u64 error_code;@@ -107,6 +108,10 @@ static inline int __vmx_handle_ept_violation(struct kvm_vcpu *vcpu, gpa_t gpa, if (vt_is_tdx_private_gpa(vcpu->kvm, gpa)) error_code |= PFERR_PRIVATE_ACCESS; +BUILD_BUG_ON (KVM_MAX_HUGEPAGE_LEVEL >= (1 <<hweight64 (PFERR_FAULT_LEVEL_MASK ))); + + error_code |= (u64 )max_fault_level <<PFERR_FAULT_LEVEL_SHIFT ; +return kvm_mmu_page_fault (vcpu, gpa, error_code,NULL ,0 );}
arch/x86/kvm/vmx/tdx.c +1
-1@@ -2027,7 +2027,7 @@ static int tdx_handle_ept_violation(struct kvm_vcpu *vcpu)* handle retries locally in their EPT violation handlers. */ while (1 ) { - ret =__vmx_handle_ept_violation (vcpu, gpa, exit_qual); + ret =__vmx_handle_ept_violation (vcpu, gpa, exit_qual,KVM_MAX_HUGEPAGE_LEVEL );if (ret !=RET_PF_RETRY || !local_retry)break;arch/x86/kvm/vmx/vmx.c +1
-1@@ -5782,7 +5782,7 @@ static int handle_ept_violation(struct kvm_vcpu *vcpu)if (unlikely (allow_smaller_maxphyaddr && !kvm_vcpu_is_legal_gpa (vcpu, gpa)))return kvm_emulate_instruction (vcpu,0 ); -return __vmx_handle_ept_violation (vcpu, gpa, exit_qualification); +return __vmx_handle_ept_violation (vcpu, gpa, exit_qualification,KVM_MAX_HUGEPAGE_LEVEL ); }static int
handle_ept_misconfig(struct kvm_vcpu *vcpu)
Edgecombe, Rick P
maintainerRe: [RFC PATCH 12/21] KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
Quoted 10 lines · Yan Zhao
Quoted 3 lines
Looking more closely, I don't see why it's too hard to pass in a
max_fault_level
into the fault struct. Totally untested rough idea, what do you think?Thanks for bringing this up and providing the idea below. In the previous TDX huge page v8, there's a similar implementation [1] [2].
This series did not adopt that approach because that approach requires
tdx_handle_ept_violation()to pass inmax_fault_level, which is not always available at that stage. e.g.
Quoted 9 lines
In patch 19, when vCPU 1 faults on a GFN at 2MB level and then vCPU 2 faults on
the same GFN at 4KB level, TDX wants to ignore the demotion request caused by vCPU 2's 4KB level fault. So, patch 19 setstdx->violation_request_levelto 2MB
in vCPU 2's split callback and fails the split. vCPU 2's__vmx_handle_ept_violation()will seeRET_PF_RETRYand either do local retry (or
return to the guest).
I think you mean patch 20 "KVM: x86: Force a prefetch fault's max mapping level to 4KB for TDX"?
Quoted 10 lines
If it retries locally,
tdx_gmem_private_max_mapping_level()will returntdx->violation_request_level, causing KVM to fault at 2MB level for vCPU 2, resulting in a spurious fault, eventually returning to the guest.As
tdx->violation_request_levelis per-vCPU and it resets intdx_get_accept_level()intdx_handle_ept_violation()(meaning it resets after each invocation oftdx_handle_ept_violation()and only affects the TDX local retry loop), it should not hold any stale value.
Quoted 8 lines
Alternatively, instead of having
tdx_gmem_private_max_mapping_level()to returntdx->violation_request_level,tdx_handle_ept_violation()could grabtdx->violation_request_levelas themax_fault_levelto pass to__vmx_handle_ept_violation().This series chose to use
tdx_gmem_private_max_mapping_level()to avoid modification to the KVM MMU core.
It sounds like Kirill is suggesting we do have to have demotion in the fault path. IIRC it adds a lock, but the cost to skip fault path demotion seems to be adding up.
Re: [RFC PATCH 12/21] KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
Quoted 21 lines · Rick P
Quoted 10 lines · Yan Zhao
Quoted 3 lines
Looking more closely, I don't see why it's too hard to pass in a
max_fault_level
into the fault struct. Totally untested rough idea, what do you think?Thanks for bringing this up and providing the idea below. In the previous TDX huge page v8, there's a similar implementation [1] [2].
This series did not adopt that approach because that approach requires
tdx_handle_ept_violation()to pass inmax_fault_level, which is not always available at that stage. e.g.Quoted 9 lines
In patch 19, when vCPU 1 faults on a GFN at 2MB level and then vCPU 2 faults on
the same GFN at 4KB level, TDX wants to ignore the demotion request caused by vCPU 2's 4KB level fault. So, patch 19 setstdx->violation_request_levelto 2MB
in vCPU 2's split callback and fails the split. vCPU 2's__vmx_handle_ept_violation()will seeRET_PF_RETRYand either do local retry (or
return to the guest).
Quoted 2 lines
I think you mean patch 20 "KVM: x86: Force a prefetch fault's max mapping level to 4KB for TDX"?
Sorry. It's patch 21 "KVM: x86: Ignore splitting huge pages in fault path for TDX"
Quoted 16 lines
Quoted 16 lines
If it retries locally,
tdx_gmem_private_max_mapping_level()will returntdx->violation_request_level, causing KVM to fault at 2MB level for vCPU 2, resulting in a spurious fault, eventually returning to the guest.As
tdx->violation_request_levelis per-vCPU and it resets intdx_get_accept_level()intdx_handle_ept_violation()(meaning it resets after each invocation oftdx_handle_ept_violation()and only affects the TDX local retry loop), it should not hold any stale value.Alternatively, instead of having
tdx_gmem_private_max_mapping_level()to returntdx->violation_request_level,tdx_handle_ept_violation()could grabtdx->violation_request_levelas themax_fault_levelto pass to__vmx_handle_ept_violation().
Quoted 6 lines
Quoted 2 lines
This series chose to use
tdx_gmem_private_max_mapping_level()to avoid modification to the KVM MMU core.It sounds like Kirill is suggesting we do have to have demotion in the fault path. IIRC it adds a lock, but the cost to skip fault path demotion seems to be adding up.
Yes, though Kirill is suggesting to support demotion in the fault path, I still think that using tdx_gmem_private_max_mapping_level() might be more friendly to other potential scenarios, such as when the KVM core MMU requests TDX to perform page promotion, and TDX finds that promotion would consistently fail on a GFN.
Another important reason for not passing a max_fault_level into the fault struct is that the KVM MMU now has the hook private_max_mapping_level to determine a private fault's maximum level, which was introduced by commit f32fb32820b1 ("KVM: x86: Add hook for determining max NPT mapping level"). We'd better not to introduce another mechanism if the same job can be accomplished via the private_max_mapping_level hook.
The code in TDX huge page v8 [1][2] simply inherited the old implementation from its v1 [3], where the private_max_mapping_level hook had not yet been introduced for private faults.
[1] https://lore.kernel.org/all/4d61104bff388a081ff8f6ae4ac71e05a13e53c3.1708933624.git.isaku.yamahata@intel.com/
[2] https://lore.kernel.org/all/3d2a6bfb033ee1b51f7b875360bd295376c32b54.1708933624.git.isaku.yamahata@intel.com/
[3] https://lore.kernel.org/all/[email protected]/
Edgecombe, Rick P
maintainerRe: [RFC PATCH 12/21] KVM: TDX: Determine max mapping level according to vCPU's ACCEPT level
Quoted 12 lines · Yan Zhao
Quoted 4 lines
It sounds like Kirill is suggesting we do have to have demotion in the fault path. IIRC it adds a lock, but the cost to skip fault path demotion seems to be
adding up.Yes, though Kirill is suggesting to support demotion in the fault path, I still
think that usingtdx_gmem_private_max_mapping_level()might be more friendly to
other potential scenarios, such as when the KVM core MMU requests TDX to perform
page promotion, and TDX finds that promotion would consistently fail on a GFN.
Quoted 8 lines
Another important reason for not passing a
max_fault_levelinto the fault struct
is that the KVM MMU now has the hookprivate_max_mapping_levelto determine a private fault's maximum level, which was introduced by commitf32fb32820b1("KVM: x86: Add hook for determining max NPT mapping level"). We'd better not to
introduce another mechanism if the same job can be accomplished via theprivate_max_mapping_levelhook.
How about the alternative discussed on the thread with Kai? I don't think Kirill was suggesting #VE based TDs need huge pages, just that they need to work with 4k accepts. Let's continue the discussion on that thread, because I think they are all related. Once we conclude there we can iron out any remaining issues on this specific patch.
Quoted 6 lines
The code in TDX huge page v8 [1][2] simply inherited the old implementation from
its v1 [3], where theprivate_max_mapping_levelhook had not yet been introduced
for private faults.
RFC PATCH 13/21 KVM: x86/tdp_mmu: Alloc external_spt page for mirror page table splitting
In reply to Yan ZhaoFrom: Isaku Yamahata <[email protected]>
Enhance tdp_mmu_alloc_sp_split() to allocate the external page table page for splitting the mirror page table.
[Yan: Rebased and simplified the code ]
--- arch/x86/kvm/mmu/tdp_mmu.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-)
arch/x86/kvm/mmu/tdp_mmu.c +13 -2
@@ -324,6 +324,8 @@ static void handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn, u64 old_spte, u64 new_spte, int level, bool shared); +static struct kvm_mmu_page *tdp_mmu_alloc_sp_for_split (bool mirror); +static void tdp_account_mmu_page (struct kvm *kvm,struct kvm_mmu_page *sp) {kvm_account_pgtable_pages ((void *)sp->spt,+1 );
@@ -1475,7 +1477,7 @@ bool kvm_tdp_mmu_wrprot_slot(struct kvm *kvm,return spte_set; } -static struct kvm_mmu_page *tdp_mmu_alloc_sp_for_split (void ) +static struct kvm_mmu_page *tdp_mmu_alloc_sp_for_split (bool mirror) {struct kvm_mmu_page *sp;
@@ -1489,6 +1491,15 @@ static struct kvm_mmu_page *tdp_mmu_alloc_sp_for_split(void)return NULL ; } +if (mirror) { + sp->external_spt = (void *)get_zeroed_page (GFP_KERNEL_ACCOUNT ); +if (!sp->external_spt) { +free_page ((unsigned long )sp->spt); +kmem_cache_free (mmu_page_header_cache, sp); +return NULL ; + } + } +return sp; }
@@ -1568,7 +1579,7 @@ static int tdp_mmu_split_huge_pages_root(struct kvm *kvm,else write_unlock (&kvm->mmu_lock); - sp =tdp_mmu_alloc_sp_for_split (); + sp =tdp_mmu_alloc_sp_for_split (is_mirror_sp (root));if (shared)read_lock (&kvm->mmu_lock);
Signature · 1 line
2.43.2
RFC PATCH 14/21 KVM: x86/tdp_mmu: Invoke split_external_spt hook with exclusive mmu_lock
In reply to Yan ZhaoIntroduce the split_external_spt hook and call it within tdp_mmu_set_spte() for the mirror page table when kvm->mmu_lock is held for writing.
When tdp_mmu_set_spte() is invoked to transition an old leaf SPTE to a new non-leaf SPTE in the mirror page table, use the split_external_spt hook to propagate the entry splitting request to the external page table.
--- arch/x86/include/asm/kvm-x86-ops.h | 1 + arch/x86/include/asm/kvm_host.h | 4 ++++ arch/x86/kvm/mmu/tdp_mmu.c | 26 ++++++++++++++++++++------ 3 files changed, 25 insertions(+), 6 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
@@ -99,6 +99,7 @@ KVM_X86_OP_OPTIONAL(link_external_spt) KVM_X86_OP_OPTIONAL(set_external_spte) KVM_X86_OP_OPTIONAL(free_external_spt) KVM_X86_OP_OPTIONAL(remove_external_spte) +KVM_X86_OP_OPTIONAL(split_external_spt) KVM_X86_OP(has_wbinvd_exit) KVM_X86_OP(get_l2_tsc_offset) KVM_X86_OP(get_l2_tsc_multiplier)
arch/x86/include/asm/kvm_host.h +4 -0
@@ -1812,6 +1812,10 @@ struct kvm_x86_ops {int (*remove_external_spte)(struct kvm *kvm,gfn_t gfn,enum pg_level level,kvm_pfn_t pfn_for_gfn); +/* Split the external page table into smaller page tables */ +int (*split_external_spt)(struct kvm *kvm,gfn_t gfn,enum pg_level level, +void *external_spt); +bool (*has_wbinvd_exit)(void );u64 (*get_l2_tsc_offset)(struct kvm_vcpu *vcpu);
arch/x86/kvm/mmu/tdp_mmu.c +20 -6
@@ -325,6 +325,7 @@ static void handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn, bool shared);static struct kvm_mmu_page *tdp_mmu_alloc_sp_for_split (bool mirror); +static void *get_external_spt (gfn_t gfn,u64 new_spte,int level);static void tdp_account_mmu_page (struct kvm *kvm,struct kvm_mmu_page *sp) {
@@ -384,6 +385,19 @@ static void remove_external_spte(struct kvm *kvm, gfn_t gfn, u64 old_spte,KVM_BUG_ON (ret, kvm); } +static int split_external_spt (struct kvm *kvm,gfn_t gfn,u64 old_spte, +u64 new_spte,int level) +{ +void *external_spt =get_external_spt (gfn, new_spte, level); +int ret; + +KVM_BUG_ON (!external_spt, kvm); + + ret =static_call (kvm_x86_split_external_spt)(kvm, gfn, level, external_spt); +KVM_BUG_ON (ret, kvm); + +return ret; +}/** * handle_removed_pt() - handle a page table removed from the TDP structure *
@@ -764,13 +778,13 @@ static u64 tdp_mmu_set_spte(struct kvm *kvm, int as_id, tdp_ptep_t sptep,handle_changed_spte (kvm, as_id, gfn, old_spte, new_spte, level, false); -/* -* Users that do non-atomic setting of PTEs don't operate on mirror -* roots, so don't handle it and bug the VM if it's seen. -*/ if (is_mirror_sptep (sptep)) { -KVM_BUG_ON (is_shadow_present_pte (new_spte), kvm); -remove_external_spte (kvm, gfn, old_spte, level); +if (!is_shadow_present_pte (new_spte)) +remove_external_spte (kvm, gfn, old_spte, level); +else if (is_last_spte (old_spte, level) && !is_last_spte (new_spte, level)) +split_external_spt (kvm, gfn, old_spte, new_spte, level); +else +KVM_BUG_ON (1 , kvm); }return old_spte;
Signature · 1 line
2.43.2
Edgecombe, Rick P
maintainerRe: [RFC PATCH 14/21] KVM: x86/tdp_mmu: Invoke split_external_spt hook with exclusive mmu_lock
arch/x86/kvm/mmu/tdp_mmu.c static void remove_external_spte(struct kvm *kvm, gfn_t gfn, u64 old_spte, · line 397
Quoted 10 lines · Yan Zhao
arch/x86/kvm/mmu/tdp_mmu.c +10
-0+static int split_external_spt (struct kvm *kvm,gfn_t gfn,u64 old_spte, + u64 new_spte, int level) +{ +void *external_spt =get_external_spt (gfn, new_spte, level); +int ret; + +KVM_BUG_ON (!external_spt, kvm); + + ret =static_call (kvm_x86_split_external_spt)(kvm, gfn, level, external_spt); +KVM_BUG_ON (ret, kvm);
Shouldn't this BUG_ON be handled in the split_external_spt implementation? I don't think we need another one.
Quoted 15 lines
arch/x86/kvm/mmu/tdp_mmu.c +3
-0+ +return ret; +}/**
*handle_removed_pt()- handle a page table removed from the TDP structure *(quoted diff) +0
-0@@ -764,13 +778,13 @@ static u64 tdp_mmu_set_spte(struct kvm *kvm, int as_id, tdp_ptep_t sptep,
handle_changed_spte(kvm, as_id, gfn, old_spte, new_spte, level, false);arch/x86/kvm/mmu/tdp_mmu.c +0
-4-/* -* Users that do non-atomic setting of PTEs don't operate on mirror -* roots, so don't handle it and bug the VM if it's seen. -*/ if (
is_mirror_sptep(sptep)) {
arch/x86/kvm/mmu/tdp_mmu.c static u64 tdp_mmu_set_spte(struct kvm *kvm, int as_id, tdp_ptep_t sptep, · line 787
Quoted 8 lines
arch/x86/kvm/mmu/tdp_mmu.c +6
-2-KVM_BUG_ON (is_shadow_present_pte (new_spte), kvm); -remove_external_spte (kvm, gfn, old_spte, level); +if (!is_shadow_present_pte (new_spte)) +remove_external_spte (kvm, gfn, old_spte, level); +else if (is_last_spte (old_spte, level) && !is_last_spte (new_spte, level)) +split_external_spt (kvm, gfn, old_spte, new_spte, level); +else +KVM_BUG_ON (1 , kvm);
It might be worth a comment what this is looking for at this point. I think it's that external EPT only support certain operations, so bug if any unsupported operations are seen.
Quoted 3 lines
}
returnold_spte;
Re: [RFC PATCH 14/21] KVM: x86/tdp_mmu: Invoke split_external_spt hook with exclusive mmu_lock
Quoted 14 lines · Rick P
arch/x86/kvm/mmu/tdp_mmu.c static void remove_external_spte(struct kvm *kvm, gfn_t gfn, u64 old_spte, · line 397
Quoted 10 lines · Yan Zhao
arch/x86/kvm/mmu/tdp_mmu.c +10
-0+static int split_external_spt (struct kvm *kvm,gfn_t gfn,u64 old_spte, + u64 new_spte, int level) +{ +void *external_spt =get_external_spt (gfn, new_spte, level); +int ret; + +KVM_BUG_ON (!external_spt, kvm); + + ret =static_call (kvm_x86_split_external_spt)(kvm, gfn, level, external_spt); +KVM_BUG_ON (ret, kvm);Shouldn't this
BUG_ONbe handled in thesplit_external_sptimplementation? I don't think we need another one.
Ok. But kvm_x86_split_external_spt() is not for TDX only.
Is it good for KVM MMU core to rely on each implementation to trigger BUG_ON?
Quoted 18 lines
Quoted 18 lines
arch/x86/kvm/mmu/tdp_mmu.c +2
-0+return ret; +}/**
*handle_removed_pt()- handle a page table removed from the TDP structure *(quoted diff) +0
-0@@ -764,13 +778,13 @@ static u64 tdp_mmu_set_spte(struct kvm *kvm, int as_id, tdp_ptep_t sptep,
handle_changed_spte(kvm, as_id, gfn, old_spte, new_spte, level, false);arch/x86/kvm/mmu/tdp_mmu.c +0
-4-/* -* Users that do non-atomic setting of PTEs don't operate on mirror -* roots, so don't handle it and bug the VM if it's seen. -*/ if (
is_mirror_sptep(sptep)) {arch/x86/kvm/mmu/tdp_mmu.c +2
-2-KVM_BUG_ON (is_shadow_present_pte (new_spte), kvm); -remove_external_spte (kvm, gfn, old_spte, level); +if (!is_shadow_present_pte (new_spte)) +remove_external_spte (kvm, gfn, old_spte, level);
Quoted 8 lines
arch/x86/kvm/mmu/tdp_mmu.c static u64 tdp_mmu_set_spte(struct kvm *kvm, int as_id, tdp_ptep_t sptep, · line 787
Quoted 4 lines
arch/x86/kvm/mmu/tdp_mmu.c +4
-0+else if (is_last_spte (old_spte, level) && !is_last_spte (new_spte, level)) +split_external_spt (kvm, gfn, old_spte, new_spte, level); +else +KVM_BUG_ON (1 , kvm);It might be worth a comment what this is looking for at this point. I think it's that external EPT only support certain operations, so bug if any unsupported operations are seen.
Will do.
Quoted 4 lines
Quoted 3 lines
}
returnold_spte;
Edgecombe, Rick P
maintainerRe: [RFC PATCH 14/21] KVM: x86/tdp_mmu: Invoke split_external_spt hook with exclusive mmu_lock
Quoted 4 lines · Yan Zhao
Quoted 2 lines
Shouldn't this
BUG_ONbe handled in thesplit_external_sptimplementation? I don't think we need another one.Ok. But
kvm_x86_split_external_spt()is not for TDX only.
Is it good for KVM MMU core to rely on each implementation to triggerBUG_ON?
It effectively is for TDX only. At least for the foreseeable future. The naming basically means that people don't have to see "TDX" everywhere when they look in the MMU code.
Quoted 2 lines
Quoted 2 lines
Re: [RFC PATCH 14/21] KVM: x86/tdp_mmu: Invoke split_external_spt hook with exclusive mmu_lock
Quoted 9 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 2 lines
Shouldn't this
BUG_ONbe handled in thesplit_external_sptimplementation? I don't think we need another one.Ok. But
kvm_x86_split_external_spt()is not for TDX only.
Is it good for KVM MMU core to rely on each implementation to triggerBUG_ON?It effectively is for TDX only. At least for the foreseeable future. The naming basically means that people don't have to see "TDX" everywhere when they look in the MMU code.
Hmm, another reason to add the BUG_ON is to align it with remove_external_spte(). There's also a KVM_BUG_ON() following the remove_external_spte hook.
I interpret this as error handling in the KVM MMU core, which returns "void", so issuing BUG_ON if ret != 0.
Edgecombe, Rick P
maintainerRe: [RFC PATCH 14/21] KVM: x86/tdp_mmu: Invoke split_external_spt hook with exclusive mmu_lock
Quoted 7 lines · Yan Zhao
Quoted 6 lines · Rick P
Quoted 4 lines · Yan Zhao
Quoted 2 lines
Shouldn't this
BUG_ONbe handled in thesplit_external_sptimplementation? I don't think we need another one.Ok. But
kvm_x86_split_external_spt()is not for TDX only.
Is it good for KVM MMU core to rely on each implementation to triggerBUG_ON?
Quoted 8 lines
Quoted 3 lines
It effectively is for TDX only. At least for the foreseeable future. The naming basically means that people don't have to see "TDX" everywhere when they look in the MMU code.
Hmm, another reason to add the
BUG_ONis to align it withremove_external_spte(). There's also aKVM_BUG_ON()following theremove_external_sptehook.I interpret this as error handling in the KVM MMU core, which returns "void", so issuing
BUG_ONif ret != 0.
This is related to the other thread about how to handle demote failure. Let's continue there.
But in general, the amount of KVM_BUG_ON()s we have for mirror EPT is a bit of a code smell. It's not exclusive to this series. But I'd love if we could keep it from getting worse.
Re: [RFC PATCH 14/21] KVM: x86/tdp_mmu: Invoke split_external_spt hook with exclusive mmu_lock
In reply to Yan ZhaoOn 4/24/2025 11:07 AM, Yan Zhao wrote:
[...]
arch/x86/kvm/mmu/tdp_mmu.c static void remove_external_spte(struct kvm *kvm, gfn_t gfn, u64 old_spte, · line 396
Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +9
-0+static int split_external_spt (struct kvm *kvm,gfn_t gfn,u64 old_spte, +u64 new_spte,int level) +{ +void *external_spt =get_external_spt (gfn, new_spte, level); +int ret; + +KVM_BUG_ON (!external_spt, kvm); + + ret =static_call (kvm_x86_split_external_spt)(kvm, gfn, level, external_spt);
Better to use kvm_x86_call() instead of static_call().
Quoted 27 lines
arch/x86/kvm/mmu/tdp_mmu.c +10
-6+KVM_BUG_ON (ret, kvm); + +return ret; +}/** * handle_removed_pt() - handle a page table removed from the TDP structure * @@ -764,13 +778,13 @@ static u64 tdp_mmu_set_spte(struct kvm *kvm, int as_id, tdp_ptep_t sptep,handle_changed_spte (kvm, as_id, gfn, old_spte, new_spte, level, false); -/* -* Users that do non-atomic setting of PTEs don't operate on mirror -* roots, so don't handle it and bug the VM if it's seen. -*/ if (is_mirror_sptep (sptep)) { -KVM_BUG_ON (is_shadow_present_pte (new_spte), kvm); -remove_external_spte (kvm, gfn, old_spte, level); +if (!is_shadow_present_pte (new_spte)) +remove_external_spte (kvm, gfn, old_spte, level); +else if (is_last_spte (old_spte, level) && !is_last_spte (new_spte, level)) +split_external_spt (kvm, gfn, old_spte, new_spte, level); +else +KVM_BUG_ON (1 , kvm); }return old_spte;
Re: [RFC PATCH 14/21] KVM: x86/tdp_mmu: Invoke split_external_spt hook with exclusive mmu_lock
Quoted 4 lines · Binbin Wu
On 4/24/2025 11:07 AM, Yan Zhao wrote:
[...]
Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c static void remove_external_spte(struct kvm *kvm, gfn_t gfn, u64 old_spte, · line 396
Quoted 9 lines
arch/x86/kvm/mmu/tdp_mmu.c +9
-0+static int split_external_spt (struct kvm *kvm,gfn_t gfn,u64 old_spte, +u64 new_spte,int level) +{ +void *external_spt =get_external_spt (gfn, new_spte, level); +int ret; + +KVM_BUG_ON (!external_spt, kvm); + + ret =static_call (kvm_x86_split_external_spt)(kvm, gfn, level, external_spt);Better to use
kvm_x86_call()instead ofstatic_call().
Will do. Thanks!
Quoted 25 lines
Quoted 24 lines
arch/x86/kvm/mmu/tdp_mmu.c +10
-6+KVM_BUG_ON (ret, kvm); + +return ret; +}/** * handle_removed_pt() - handle a page table removed from the TDP structure * @@ -764,13 +778,13 @@ static u64 tdp_mmu_set_spte(struct kvm *kvm, int as_id, tdp_ptep_t sptep,handle_changed_spte (kvm, as_id, gfn, old_spte, new_spte, level, false); -/* -* Users that do non-atomic setting of PTEs don't operate on mirror -* roots, so don't handle it and bug the VM if it's seen. -*/ if (is_mirror_sptep (sptep)) { -KVM_BUG_ON (is_shadow_present_pte (new_spte), kvm); -remove_external_spte (kvm, gfn, old_spte, level); +if (!is_shadow_present_pte (new_spte)) +remove_external_spte (kvm, gfn, old_spte, level); +else if (is_last_spte (old_spte, level) && !is_last_spte (new_spte, level)) +split_external_spt (kvm, gfn, old_spte, new_spte, level); +else +KVM_BUG_ON (1 , kvm); }return old_spte;
RFC PATCH 15/21 KVM: TDX: Support huge page splitting with exclusive kvm->mmu_lock
In reply to Yan ZhaoFrom: Xiaoyao Li <[email protected]>
Implement the split_external_spt hook to support huge page splitting for TDX when kvm->mmu_lock is held for writing.
Invoke tdh_mem_range_block(), tdh_mem_track(), kicking off vCPUs, tdh_mem_page_demote() in sequence. Since kvm->mmu_lock is held for writing, simply kick off vCPUs on tdx_operand_busy() to ensure the second SEAMCALL invocation succeeds.
TDX module may return TDX_INTERRUPTED_RESTARTABLE when there is a pending interrupt on the host side during tdh_mem_page_demote(). Retry indefinitely on this error, as with exclusive kvm->mmu_lock the pending interrupt is for host only.
[Yan: Split patch for exclusive mmu_lock only, handled busy error ]
--- arch/x86/kvm/vmx/main.c | 1 + arch/x86/kvm/vmx/tdx.c | 45 ++++++++++++++++++++++++++++++++++++ arch/x86/kvm/vmx/tdx_errno.h | 1 + arch/x86/kvm/vmx/x86_ops.h | 9 ++++++++ 4 files changed, 56 insertions(+)
arch/x86/kvm/vmx/main.c +1 -0
@@ -62,6 +62,7 @@ static __init int vt_hardware_setup(void) vt_x86_ops.set_external_spte = tdx_sept_set_private_spte; vt_x86_ops.free_external_spt = tdx_sept_free_private_spt; vt_x86_ops.remove_external_spte = tdx_sept_remove_private_spte; + vt_x86_ops.split_external_spt = tdx_sept_split_private_spt; vt_x86_ops.protected_apic_has_interrupt = tdx_protected_apic_has_interrupt; }
arch/x86/kvm/vmx/tdx.c +45 -0
51 lines not on this page · raw message
arch/x86/kvm/vmx/tdx_errno.h +1 -0
@@ -14,6 +14,7 @@#define TDX_NON_RECOVERABLE_TD_NON_ACCESSIBLE 0x6000000500000000ULL#define TDX_NON_RECOVERABLE_TD_WRONG_APIC_MODE 0x6000000700000000ULL#define TDX_INTERRUPTED_RESUMABLE 0x8000000300000000ULL +#define TDX_INTERRUPTED_RESTARTABLE 0x8000000400000000ULL#define TDX_OPERAND_INVALID 0xC000010000000000ULL#define TDX_OPERAND_BUSY 0x8000020000000000ULL#define TDX_PREVIOUS_TLB_EPOCH_BUSY 0x8000020100000000ULL
arch/x86/kvm/vmx/x86_ops.h +9 -0
@@ -158,6 +158,8 @@ int tdx_sept_set_private_spte(struct kvm *kvm, gfn_t gfn, enum pg_level level, kvm_pfn_t pfn);int tdx_sept_remove_private_spte (struct kvm *kvm,gfn_t gfn,enum pg_level level,kvm_pfn_t pfn); +int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, +void *private_spt);void tdx_flush_tlb_current (struct kvm_vcpu *vcpu);void tdx_flush_tlb_all (struct kvm_vcpu *vcpu);
@@ -224,6 +226,13 @@ static inline int tdx_sept_remove_private_spte(struct kvm *kvm, gfn_t gfn,return -EOPNOTSUPP ; } +static inline int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn, +enum pg_level level, +void *private_spt) +{ +return -EOPNOTSUPP ; +} +static inline void tdx_flush_tlb_current (struct kvm_vcpu *vcpu) {}static inline void tdx_flush_tlb_all (struct kvm_vcpu *vcpu) {}static inline void tdx_load_mmu_pgd (struct kvm_vcpu *vcpu,hpa_t root_hpa,int root_level) {}
Signature · 1 line
2.43.2
Re: [RFC PATCH 15/21] KVM: TDX: Support huge page splitting with exclusive kvm->mmu_lock
On 4/24/2025 11:08 AM, Yan Zhao wrote:
[...]
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5
-0+ +int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, +void *private_spt) +{ +struct page *page =virt_to_page (private_spt);
arch/x86/kvm/vmx/tdx.c int tdx_sept_free_private_spt(struct kvm *kvm, gfn_t gfn, · line 1849
Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10
-0+int ret; + +if (KVM_BUG_ON (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE || level !=PG_LEVEL_2M , kvm)) +return -EINVAL ; + + ret =tdx_sept_zap_private_spte (kvm, gfn, level, page); +if (ret <=0 ) +return ret; + +tdx_track (kvm);
It may worth a helper for the zap and track code.
It's the some code as what in tdx_sept_remove_private_spte(). So that they can share the code, including the bug check for HKID and the comments.
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +4
-0+ +return tdx_spte_demote_private_spte (kvm, gfn, level, page); +} +
[...]
Re: [RFC PATCH 15/21] KVM: TDX: Support huge page splitting with exclusive kvm->mmu_lock
Quoted 16 lines · Binbin Wu
On 4/24/2025 11:08 AM, Yan Zhao wrote:
[...]Quoted 12 lines
arch/x86/kvm/vmx/tdx.c +12
-0+ +int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, +void *private_spt) +{ +struct page *page =virt_to_page (private_spt); +int ret; + +if (KVM_BUG_ON (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE || level !=PG_LEVEL_2M , kvm)) +return -EINVAL ; + + ret =tdx_sept_zap_private_spte (kvm, gfn, level, page); +if (ret <=0 )
Quoted 8 lines
arch/x86/kvm/vmx/tdx.c int tdx_sept_free_private_spt(struct kvm *kvm, gfn_t gfn, · line 1849
Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3
-0+return ret; + +tdx_track (kvm);It may worth a helper for the zap and track code.
It's the some code as what intdx_sept_remove_private_spte(). So that they can share the code, including the bug check for HKID and the comments.
Not sure if it's worthwhile.
But I'm open to it if others also agree.
Quoted 7 lines
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +4
-0+ +return tdx_spte_demote_private_spte (kvm, gfn, level, page); +} +[...]
Edgecombe, Rick P
maintainerRe: [RFC PATCH 15/21] KVM: TDX: Support huge page splitting with exclusive kvm->mmu_lock
In reply to Yan ZhaoQuoted 34 lines · Yan Zhao
arch/x86/kvm/vmx/tdx.c +34
-0+static int tdx_spte_demote_private_spte (struct kvm *kvm,gfn_t gfn, +enum pg_level level,struct page *page) +{ +int tdx_level =pg_level_to_tdx_sept_level (level); +struct kvm_tdx *kvm_tdx =to_kvm_tdx (kvm); +gpa_t gpa =gfn_to_gpa (gfn); +u64 err, entry, level_state; + +do { + err =tdh_mem_page_demote (&kvm_tdx->td, gpa, tdx_level, page, + &entry, &level_state); + }while (err ==TDX_INTERRUPTED_RESTARTABLE ); + +if (unlikely (tdx_operand_busy (err))) { +tdx_no_vcpus_enter_start (kvm); + err =tdh_mem_page_demote (&kvm_tdx->td, gpa, tdx_level, page, + &entry, &level_state); +tdx_no_vcpus_enter_stop (kvm); + } + +if (KVM_BUG_ON (err, kvm)) { +pr_tdx_error_2 (TDH_MEM_PAGE_DEMOTE , err, entry, level_state); +return -EIO ; + } +return 0 ; +} + +int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, + void *private_spt) +{ +struct page *page =virt_to_page (private_spt); +int ret; + +if (KVM_BUG_ON (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE || level !=PG_LEVEL_2M , kvm))
arch/x86/kvm/vmx/tdx.c int tdx_sept_free_private_spt(struct kvm *kvm, gfn_t gfn, · line 1852
Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10
-0+return -EINVAL ; + + ret =tdx_sept_zap_private_spte (kvm, gfn, level, page); +if (ret <=0 ) +return ret; + +tdx_track (kvm); + +return tdx_spte_demote_private_spte (kvm, gfn, level, page); +}
The latest TDX docs talk about a feature called NON_BLOCKING_RESIZE. It allows for demote without blocking. If we rely on this feature we could simplify this code. Not having transitory blocked state would reduce the scenarios that have to be accounted for. We could also make demote operation accommodate failures (rollback on SEAMCALL BUSY issue), which means mmu write lock is no longer needed. It would have helped the fault path demote issue, which we have now worked around. But still, it seems more flexible as well as simpler.
What about we rely on it this feature for KVM TDX huge mappings?
RFC PATCH 16/21 KVM: x86/mmu: Introduce kvm_split_boundary_leafs() to split boundary leafs
In reply to Yan ZhaoIntroduce kvm_split_boundary_leafs() to manage the splitting of boundary leafs within the mirror root.
Before zapping a specific GFN range in the mirror root, split any huge leaf that intersects with the boundary of the GFN range to ensure that the subsequent zap operation does not impact any GFN outside the specified range. This is crucial for the mirror root as the private page table requires the guest's ACCEPT operation after faulting back a GFN.
This function should be called while kvm->mmu_lock is held for writing. The kvm->mmu_lock is temporarily released to allocate memory for sp for split. The only expected error is -ENOMEM.
Opportunistically, WARN in tdp_mmu_zap_leafs() if zapping a huge leaf in the mirror root affects a GFN outside the specified range.
--- arch/x86/kvm/mmu/mmu.c | 21 +++++++ arch/x86/kvm/mmu/tdp_mmu.c | 116 ++++++++++++++++++++++++++++++++++++- arch/x86/kvm/mmu/tdp_mmu.h | 1 + include/linux/kvm_host.h | 1 + 4 files changed, 136 insertions(+), 3 deletions(-)
arch/x86/kvm/mmu/mmu.c +21 -0
@@ -1640,6 +1640,27 @@ static bool __kvm_rmap_zap_gfn_range(struct kvm *kvm, start, end - 1, can_yield, true, flush); } +/* +* Split large leafs at the boundary of the specified range for the mirror root +* +* Return value: +* 0 : success, no flush is required; +* 1 : success, flush is required; +* <0: failure. +*/ +int kvm_split_boundary_leafs (struct kvm *kvm,struct kvm_gfn_range *range) +{ +bool ret =0 ; + +lockdep_assert_once (kvm->mmu_invalidate_in_progress || +lockdep_is_held (&kvm->slots_lock)); + +if (tdp_mmu_enabled) + ret =kvm_tdp_mmu_gfn_range_split_boundary (kvm, range); + +return ret; +} +bool kvm_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range) {bool flush = false;
arch/x86/kvm/mmu/tdp_mmu.c +113 -3
146 lines not on this page · raw message
arch/x86/kvm/mmu/tdp_mmu.h +1 -0
@@ -69,6 +69,7 @@ void kvm_tdp_mmu_zap_all(struct kvm *kvm);void kvm_tdp_mmu_invalidate_roots (struct kvm *kvm,enum kvm_tdp_mmu_root_types root_types);void kvm_tdp_mmu_zap_invalidated_roots (struct kvm *kvm,bool shared); +int kvm_tdp_mmu_gfn_range_split_boundary (struct kvm *kvm,struct kvm_gfn_range *range);int kvm_tdp_mmu_map (struct kvm_vcpu *vcpu,struct kvm_page_fault *fault);
include/linux/kvm_host.h +1 -0
@@ -272,6 +272,7 @@ struct kvm_gfn_range {bool kvm_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range);bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range);bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range); +int kvm_split_boundary_leafs (struct kvm *kvm,struct kvm_gfn_range *range);#endif enum {
Signature · 1 line
2.43.2
Edgecombe, Rick P
maintainerRe: [RFC PATCH 16/21] KVM: x86/mmu: Introduce kvm_split_boundary_leafs() to split boundary leafs
Quoted 91 lines · Yan Zhao
Introduce
kvm_split_boundary_leafs()to manage the splitting of boundary leafs within the mirror root.Before zapping a specific GFN range in the mirror root, split any huge leaf that intersects with the boundary of the GFN range to ensure that the subsequent zap operation does not impact any GFN outside the specified range. This is crucial for the mirror root as the private page table requires the guest's ACCEPT operation after faulting back a GFN.
This function should be called while
kvm->mmu_lockis held for writing. Thekvm->mmu_lockis temporarily released to allocate memory for sp for split. The only expected error is-ENOMEM.Opportunistically, WARN in
tdp_mmu_zap_leafs()if zapping a huge leaf in the mirror root affects a GFN outside the specified range.Signed-off-by Xiaoyao Li <[email protected]>Signed-off-by Yan Zhao <[email protected]>--- arch/x86/kvm/mmu/mmu.c | 21 +++++++ arch/x86/kvm/mmu/tdp_mmu.c | 116 ++++++++++++++++++++++++++++++++++++- arch/x86/kvm/mmu/tdp_mmu.h | 1 + include/linux/kvm_host.h | 1 + 4 files changed, 136 insertions(+), 3 deletions(-)arch/x86/kvm/mmu/mmu.c +21
-0@@ -1640,6 +1640,27 @@ static bool __kvm_rmap_zap_gfn_range(struct kvm *kvm, start, end - 1, can_yield, true, flush); } +/* +* Split large leafs at the boundary of the specified range for the mirror root +* +* Return value: +* 0 : success, no flush is required; +* 1 : success, flush is required; +* <0: failure. +*/ +int kvm_split_boundary_leafs (struct kvm *kvm,struct kvm_gfn_range *range) +{ +bool ret =0 ; + +lockdep_assert_once (kvm->mmu_invalidate_in_progress || +lockdep_is_held (&kvm->slots_lock)); + +if (tdp_mmu_enabled) + ret =kvm_tdp_mmu_gfn_range_split_boundary (kvm, range); + +return ret; +} +bool kvm_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range) {bool flush = false;arch/x86/kvm/mmu/tdp_mmu.c +15
-0@@ -324,6 +324,8 @@ static void handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn, u64 old_spte, u64 new_spte, int level, bool shared); +static int tdp_mmu_split_huge_page (struct kvm *kvm,struct tdp_iter *iter, +struct kvm_mmu_page *sp,bool shared);static struct kvm_mmu_page *tdp_mmu_alloc_sp_for_split (bool mirror);static void *get_external_spt (gfn_t gfn,u64 new_spte,int level);@@ -962,6 +964,19 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)return true; } +static inline bool iter_split_required (struct kvm *kvm,struct kvm_mmu_page *root, +struct tdp_iter *iter,gfn_t start,gfn_t end) +{ +if (!is_mirror_sp (root) || !is_large_pte (iter->old_spte)) +return false; + +/* Fully contained, no need to split */ +if (iter->gfn >= start && iter->gfn +KVM_PAGES_PER_HPAGE (iter->level) <= end) +return false; + +return true; +} +/* * If can_yield is true, will release the MMU lock and reschedule if the * scheduler needs the CPU or there is contention on the MMU lock. If this
arch/x86/kvm/mmu/tdp_mmu.c static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root, · line 1010
Quoted 5 lines
arch/x86/kvm/mmu/tdp_mmu.c +2
-0@@ -991,6 +1006,8 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root, !is_last_spte(iter.old_spte, iter.level))continue ; +WARN_ON_ONCE (iter_split_required (kvm, root, &iter, start, end)); +
Kind of unrelated change? But good idea. Maybe for another patch.
Quoted 17 lines
arch/x86/kvm/mmu/tdp_mmu.c +0
-3tdp_mmu_iter_set_spte (kvm, &iter,SHADOW_NONPRESENT_VALUE );/* @@ -1246,9 +1263,6 @@ static int tdp_mmu_link_sp(struct kvm *kvm, struct tdp_iter *iter,return 0 ; } -static int tdp_mmu_split_huge_page (struct kvm *kvm,struct tdp_iter *iter, -struct kvm_mmu_page *sp,bool shared); -/* * Handle a TDP page fault (NPT/EPT violation/misconfiguration) by installing * page tables and SPTEs to translate the faulting guest physical address. @@ -1341,6 +1355,102 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)return ret; }
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1367
Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10
-0+/* +* Split large leafs at the boundary of the specified range for the mirror root +*/ +static int tdp_mmu_split_boundary_leafs (struct kvm *kvm,struct kvm_mmu_page *root, +gfn_t start,gfn_t end,bool can_yield,bool *flush) +{ +struct kvm_mmu_page *sp =NULL ; +struct tdp_iter iter; + +WARN_ON_ONCE (!can_yield);
Why pass this in then?
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1370
Quoted 3 lines
arch/x86/kvm/mmu/tdp_mmu.c +3
-0+ +if (!is_mirror_sp (root)) +return 0 ;
What is special about mirror roots here?
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1380
Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10
-0+ + end =min (end,tdp_mmu_max_gfn_exclusive ()); + +lockdep_assert_held_write (&kvm->mmu_lock); + +rcu_read_lock (); + +for_each_tdp_pte_min_level (iter, kvm, root,PG_LEVEL_4K , start, end) { +retry: + if (can_yield &&
Do we need this part of the conditional based on the above?
Quoted 22 lines
arch/x86/kvm/mmu/tdp_mmu.c +22
-0+ tdp_mmu_iter_cond_resched(kvm, &iter, *flush, false)) { + *flush = false; +continue ; + } + +if (!is_shadow_present_pte (iter.old_spte) || + !is_last_spte (iter.old_spte, iter.level) || + !iter_split_required (kvm, root, &iter, start, end)) +continue ; + +if (!sp) { +rcu_read_unlock (); + +write_unlock (&kvm->mmu_lock); + + sp =tdp_mmu_alloc_sp_for_split (true); + +write_lock (&kvm->mmu_lock); + +if (!sp) { +trace_kvm_mmu_split_huge_page (iter.gfn, iter.old_spte, + iter.level, -ENOMEM );
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1412
Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10
-0+return -ENOMEM ; + } +rcu_read_lock (); + + iter.yielded = true; +continue ; + } +tdp_mmu_init_child_sp (sp, &iter); + +if (tdp_mmu_split_huge_page (kvm, &iter, sp, false))
I think it can't fail when you hold mmu write lock.
Quoted 6 lines
arch/x86/kvm/mmu/tdp_mmu.c +6
-0+ goto retry; + + sp =NULL ; +/* +* Set yielded in case after splitting to a lower level, +* the new iter requires furter splitting.
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1428
Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10
-0+*/ + iter.yielded = true; + *flush = true; + } + +rcu_read_unlock (); + +/* Leave it here though it should be impossible for the mirror root */ +if (sp) +tdp_mmu_free_sp (sp);
What do you think about relying on tdp_mmu_split_huge_pages_root() and moving this to an optimization patch at the end?
Or what about just two calls to tdp_mmu_split_huge_pages_root() at the boundaries?
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1439
Quoted 11 lines
arch/x86/kvm/mmu/tdp_mmu.c +11
-0+return 0 ; +} + +int kvm_tdp_mmu_gfn_range_split_boundary (struct kvm *kvm,struct kvm_gfn_range *range) +{ +enum kvm_tdp_mmu_root_types types; +struct kvm_mmu_page *root; +bool flush = false; +int ret; + + types =kvm_gfn_range_filter_to_root_types (kvm, range->attr_filter) |KVM_INVALID_ROOTS ;
What is the reason for KVM_INVALID_ROOTS in this case?
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1441
Quoted 2 lines
arch/x86/kvm/mmu/tdp_mmu.c +2
-0+ +__for_each_tdp_mmu_root_yield_safe (kvm, root, range->slot->as_id, types) {
It would be better to check for mirror roots here, instead of inside tdp_mmu_split_boundary_leafs().
Quoted 39 lines
arch/x86/kvm/mmu/tdp_mmu.c +12
-0+ ret =tdp_mmu_split_boundary_leafs (kvm, root, range->start, range->end, + range->may_block, &flush); +if (ret <0 ) { +if (flush) +kvm_flush_remote_tlbs (kvm); + +return ret; + } + } +return flush; +} +/* Used by mmu notifier via kvm_unmap_gfn_range() */ bool kvm_tdp_mmu_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range,bool flush)arch/x86/kvm/mmu/tdp_mmu.h +1
-0@@ -69,6 +69,7 @@ void kvm_tdp_mmu_zap_all(struct kvm *kvm);void kvm_tdp_mmu_invalidate_roots (struct kvm *kvm,enum kvm_tdp_mmu_root_types root_types);void kvm_tdp_mmu_zap_invalidated_roots (struct kvm *kvm,bool shared); +int kvm_tdp_mmu_gfn_range_split_boundary (struct kvm *kvm,struct kvm_gfn_range *range);int kvm_tdp_mmu_map (struct kvm_vcpu *vcpu,struct kvm_page_fault *fault);include/linux/kvm_host.h +1
-0@@ -272,6 +272,7 @@ struct kvm_gfn_range {bool kvm_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range);bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range);bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range); +int kvm_split_boundary_leafs (struct kvm *kvm,struct kvm_gfn_range *range);#endif enum {
Re: [RFC PATCH 16/21] KVM: x86/mmu: Introduce kvm_split_boundary_leafs() to split boundary leafs
Quoted 95 lines · Rick P
Quoted 94 lines · Yan Zhao
Introduce
kvm_split_boundary_leafs()to manage the splitting of boundary leafs within the mirror root.Before zapping a specific GFN range in the mirror root, split any huge leaf that intersects with the boundary of the GFN range to ensure that the subsequent zap operation does not impact any GFN outside the specified range. This is crucial for the mirror root as the private page table requires the guest's ACCEPT operation after faulting back a GFN.
This function should be called while
kvm->mmu_lockis held for writing. Thekvm->mmu_lockis temporarily released to allocate memory for sp for split. The only expected error is-ENOMEM.Opportunistically, WARN in
tdp_mmu_zap_leafs()if zapping a huge leaf in the mirror root affects a GFN outside the specified range.Signed-off-by Xiaoyao Li <[email protected]>Signed-off-by Yan Zhao <[email protected]>--- arch/x86/kvm/mmu/mmu.c | 21 +++++++ arch/x86/kvm/mmu/tdp_mmu.c | 116 ++++++++++++++++++++++++++++++++++++- arch/x86/kvm/mmu/tdp_mmu.h | 1 + include/linux/kvm_host.h | 1 + 4 files changed, 136 insertions(+), 3 deletions(-)arch/x86/kvm/mmu/mmu.c +21
-0@@ -1640,6 +1640,27 @@ static bool __kvm_rmap_zap_gfn_range(struct kvm *kvm, start, end - 1, can_yield, true, flush); } +/* +* Split large leafs at the boundary of the specified range for the mirror root +* +* Return value: +* 0 : success, no flush is required; +* 1 : success, flush is required; +* <0: failure. +*/ +int kvm_split_boundary_leafs (struct kvm *kvm,struct kvm_gfn_range *range) +{ +bool ret =0 ; + +lockdep_assert_once (kvm->mmu_invalidate_in_progress || +lockdep_is_held (&kvm->slots_lock)); + +if (tdp_mmu_enabled) + ret =kvm_tdp_mmu_gfn_range_split_boundary (kvm, range); + +return ret; +} +bool kvm_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range) {bool flush = false;arch/x86/kvm/mmu/tdp_mmu.c +15
-0@@ -324,6 +324,8 @@ static void handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn, u64 old_spte, u64 new_spte, int level, bool shared); +static int tdp_mmu_split_huge_page (struct kvm *kvm,struct tdp_iter *iter, +struct kvm_mmu_page *sp,bool shared);static struct kvm_mmu_page *tdp_mmu_alloc_sp_for_split (bool mirror);static void *get_external_spt (gfn_t gfn,u64 new_spte,int level);@@ -962,6 +964,19 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)return true; } +static inline bool iter_split_required (struct kvm *kvm,struct kvm_mmu_page *root, +struct tdp_iter *iter,gfn_t start,gfn_t end) +{ +if (!is_mirror_sp (root) || !is_large_pte (iter->old_spte)) +return false; + +/* Fully contained, no need to split */ +if (iter->gfn >= start && iter->gfn +KVM_PAGES_PER_HPAGE (iter->level) <= end) +return false; + +return true; +} +/* * If can_yield is true, will release the MMU lock and reschedule if the * scheduler needs the CPU or there is contention on the MMU lock. If this @@ -991,6 +1006,8 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root, !is_last_spte(iter.old_spte, iter.level))continue ;
Quoted 4 lines
arch/x86/kvm/mmu/tdp_mmu.c static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root, · line 1010
Quoted 2 lines
arch/x86/kvm/mmu/tdp_mmu.c +2
-0+WARN_ON_ONCE (iter_split_required (kvm, root, &iter, start, end)); +Kind of unrelated change? But good idea. Maybe for another patch.
Yes, will move it to a separate patch in a formal version.
As initial RFC, I hoped to show related changes in one patch to allow a whole picture.
Quoted 17 lines
Quoted 17 lines
arch/x86/kvm/mmu/tdp_mmu.c +0
-3tdp_mmu_iter_set_spte (kvm, &iter,SHADOW_NONPRESENT_VALUE );/* @@ -1246,9 +1263,6 @@ static int tdp_mmu_link_sp(struct kvm *kvm, struct tdp_iter *iter,return 0 ; } -static int tdp_mmu_split_huge_page (struct kvm *kvm,struct tdp_iter *iter, -struct kvm_mmu_page *sp,bool shared); -/* * Handle a TDP page fault (NPT/EPT violation/misconfiguration) by installing * page tables and SPTEs to translate the faulting guest physical address. @@ -1341,6 +1355,102 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)return ret; }
Quoted 12 lines
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1367
Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10
-0+/* +* Split large leafs at the boundary of the specified range for the mirror root +*/ +static int tdp_mmu_split_boundary_leafs (struct kvm *kvm,struct kvm_mmu_page *root, +gfn_t start,gfn_t end,bool can_yield,bool *flush) +{ +struct kvm_mmu_page *sp =NULL ; +struct tdp_iter iter; + +WARN_ON_ONCE (!can_yield);Why pass this in then?
Right, can move the warning up to the caller.
Currently callers of kvm_split_boundary_leafs() are only kvm_arch_pre_set_memory_attributes() and kvm_gmem_punch_hole(), so can_yield is always false.
Quoted 5 lines
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1370
Quoted 3 lines
arch/x86/kvm/mmu/tdp_mmu.c +3
-0+ +if (!is_mirror_sp (root)) +return 0 ;What is special about mirror roots here?
Hmm, I thought only the mirror root needs splitting before zapping of the S-EPT, which requires guest's acceptance. Other roots could tolerate zapping of a larger range than required.
Maybe AMD guys can shout out if I'm wrong.
Quoted 11 lines
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1380
Quoted 9 lines
arch/x86/kvm/mmu/tdp_mmu.c +9
-0+ end =min (end,tdp_mmu_max_gfn_exclusive ()); + +lockdep_assert_held_write (&kvm->mmu_lock); + +rcu_read_lock (); + +for_each_tdp_pte_min_level (iter, kvm, root,PG_LEVEL_4K , start, end) { +retry: + if (can_yield &&Do we need this part of the conditional based on the above?
No need if we don't pass in can_yield.
Quoted 26 lines
Quoted 26 lines
arch/x86/kvm/mmu/tdp_mmu.c +26
-0+ tdp_mmu_iter_cond_resched(kvm, &iter, *flush, false)) { + *flush = false; +continue ; + } + +if (!is_shadow_present_pte (iter.old_spte) || + !is_last_spte (iter.old_spte, iter.level) || + !iter_split_required (kvm, root, &iter, start, end)) +continue ; + +if (!sp) { +rcu_read_unlock (); + +write_unlock (&kvm->mmu_lock); + + sp =tdp_mmu_alloc_sp_for_split (true); + +write_lock (&kvm->mmu_lock); + +if (!sp) { +trace_kvm_mmu_split_huge_page (iter.gfn, iter.old_spte, + iter.level, -ENOMEM ); +return -ENOMEM ; + } +rcu_read_lock (); +
Quoted 8 lines
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1412
Quoted 6 lines
arch/x86/kvm/mmu/tdp_mmu.c +6
-0+ iter.yielded = true; +continue ; + } +tdp_mmu_init_child_sp (sp, &iter); + +if (tdp_mmu_split_huge_page (kvm, &iter, sp, false))I think it can't fail when you hold mmu write lock.
You are right!
Thanks for catching it.
Quoted 20 lines
Quoted 6 lines
arch/x86/kvm/mmu/tdp_mmu.c +6
-0+ goto retry; + + sp =NULL ; +/* +* Set yielded in case after splitting to a lower level, +* the new iter requires furter splitting. arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1428
Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10
-0+*/ + iter.yielded = true; + *flush = true; + } + +rcu_read_unlock (); + +/* Leave it here though it should be impossible for the mirror root */ +if (sp) +tdp_mmu_free_sp (sp);What do you think about relying on
tdp_mmu_split_huge_pages_root()and moving this to an optimization patch at the end?
Quoted 2 lines
Or what about just two calls to
tdp_mmu_split_huge_pages_root()at the boundaries?
Though the two generally look like the same, relying on tdp_mmu_split_huge_pages_root() will create several minor changes scattering in tdp_mmu_split_huge_pages_root().
e.g. update flush after tdp_mmu_iter_cond_resched(), check iter_split_required(), set "iter.yielded = true".
So, it may be hard to review as a initial RFC.
I prefer to do that after Paolo and Sean have taken a look of it :)
Quoted 5 lines
Quoted 5 lines
arch/x86/kvm/mmu/tdp_mmu.c +5
-0+return 0 ; +} + +int kvm_tdp_mmu_gfn_range_split_boundary (struct kvm *kvm,struct kvm_gfn_range *range) +{
Quoted 8 lines
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1439
Quoted 6 lines
arch/x86/kvm/mmu/tdp_mmu.c +6
-0+enum kvm_tdp_mmu_root_types types; +struct kvm_mmu_page *root; +bool flush = false; +int ret; + + types =kvm_gfn_range_filter_to_root_types (kvm, range->attr_filter) |KVM_INVALID_ROOTS ;What is the reason for
KVM_INVALID_ROOTSin this case?
I wanted to keep consistent with that in kvm_tdp_mmu_unmap_gfn_range(). Yes, we can remove the KVM_INVALID_ROOTS.
Quoted 5 lines
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1440
Quoted 2 lines
arch/x86/kvm/mmu/tdp_mmu.c +2
-0+ +__for_each_tdp_mmu_root_yield_safe (kvm, root, range->slot->as_id, types) {It would be better to check for mirror roots here, instead of inside
tdp_mmu_split_boundary_leafs().
Ok.
Quoted 41 lines
Quoted 40 lines
arch/x86/kvm/mmu/tdp_mmu.c +12
-0+ ret =tdp_mmu_split_boundary_leafs (kvm, root, range->start, range->end, + range->may_block, &flush); +if (ret <0 ) { +if (flush) +kvm_flush_remote_tlbs (kvm); + +return ret; + } + } +return flush; +} +/* Used by mmu notifier via kvm_unmap_gfn_range() */ bool kvm_tdp_mmu_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range,bool flush)arch/x86/kvm/mmu/tdp_mmu.h +1
-0@@ -69,6 +69,7 @@ void kvm_tdp_mmu_zap_all(struct kvm *kvm);void kvm_tdp_mmu_invalidate_roots (struct kvm *kvm,enum kvm_tdp_mmu_root_types root_types);void kvm_tdp_mmu_zap_invalidated_roots (struct kvm *kvm,bool shared); +int kvm_tdp_mmu_gfn_range_split_boundary (struct kvm *kvm,struct kvm_gfn_range *range);int kvm_tdp_mmu_map (struct kvm_vcpu *vcpu,struct kvm_page_fault *fault);include/linux/kvm_host.h +1
-0@@ -272,6 +272,7 @@ struct kvm_gfn_range {bool kvm_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range);bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range);bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range); +int kvm_split_boundary_leafs (struct kvm *kvm,struct kvm_gfn_range *range);#endif enum {
Re: [RFC PATCH 16/21] KVM: x86/mmu: Introduce kvm_split_boundary_leafs() to split boundary leafs
Quoted 28 lines · Yan Zhao
Quoted 9 lines · Rick P
Quoted 7 lines · Yan Zhao
/*
* Ifcan_yieldis true, will release the MMU lock and reschedule if the
* scheduler needs the CPU or there is contention on the MMU lock. If thisarch/x86/kvm/mmu/tdp_mmu.c +0
-0@@ -991,6 +1006,8 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root, !is_last_spte(iter.old_spte, iter.level))continue ;Quoted 4 lines
arch/x86/kvm/mmu/tdp_mmu.c static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root, · line 1010
Quoted 2 lines
arch/x86/kvm/mmu/tdp_mmu.c +2
-0+WARN_ON_ONCE (iter_split_required (kvm, root, &iter, start, end)); +Kind of unrelated change? But good idea. Maybe for another patch.
Yes, will move it to a separate patch in a formal version.
As initial RFC, I hoped to show related changes in one patch to allow a whole picture.Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1439
Quoted 8 lines
arch/x86/kvm/mmu/tdp_mmu.c +8
-0+int kvm_tdp_mmu_gfn_range_split_boundary (struct kvm *kvm,struct kvm_gfn_range *range) +{ +enum kvm_tdp_mmu_root_types types; +struct kvm_mmu_page *root; +bool flush = false; +int ret; + + types =kvm_gfn_range_filter_to_root_types (kvm, range->attr_filter) |KVM_INVALID_ROOTS ;What is the reason for
KVM_INVALID_ROOTSin this case?
Quoted 1 line
I wanted to keep consistent with that in
kvm_tdp_mmu_unmap_gfn_range().
With this consistency, we can warn in tdp_mmu_zap_leafs() as below though there should be no invalid mirror root.
WARN_ON_ONCE(iter_split_required(kvm, root, &iter, start, end));
Edgecombe, Rick P
maintainerRe: [RFC PATCH 16/21] KVM: x86/mmu: Introduce kvm_split_boundary_leafs() to split boundary leafs
Quoted 10 lines · Yan Zhao
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
+int
kvm_tdp_mmu_gfn_range_split_boundary(struct kvm *kvm, struct kvm_gfn_range *range)arch/x86/kvm/mmu/tdp_mmu.c +7
-0+{ +enum kvm_tdp_mmu_root_types types; +struct kvm_mmu_page *root; +bool flush = false; +int ret; + + types = kvm_gfn_range_filter_to_root_types(kvm, range-
Quoted 4 lines
Quoted 4 lines
Quoted 3 lines
Quoted 1 line
Quoted 1 line
attr_filter) |KVM_INVALID_ROOTS;What is the reason for
KVM_INVALID_ROOTSin this case?I wanted to keep consistent with that in
kvm_tdp_mmu_unmap_gfn_range().
Yea, lack of consistency would raise other questions.
Quoted 5 lines
With this consistency, we can warn in
tdp_mmu_zap_leafs()as below though there should be no invalid mirror root.
WARN_ON_ONCE(iter_split_required(kvm, root, &iter, start, end));
Hmm, let's be clear about the logic. This is essentially a mirror TDP only function, and there we don't have the same invalid root scenarios as the more complicated cases. I'm not exactly sure how we could hit the warning if they didn't match. I guess a hole punch on the fd while the TD is getting torn down?
Let's comment the reasoning at least.
Re: [RFC PATCH 16/21] KVM: x86/mmu: Introduce kvm_split_boundary_leafs() to split boundary leafs
Quoted 21 lines · Rick P
Quoted 10 lines · Yan Zhao
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
+int
kvm_tdp_mmu_gfn_range_split_boundary(struct kvm *kvm, struct kvm_gfn_range *range)arch/x86/kvm/mmu/tdp_mmu.c +7
-0+{ +enum kvm_tdp_mmu_root_types types; +struct kvm_mmu_page *root; +bool flush = false; +int ret; + + types = kvm_gfn_range_filter_to_root_types(kvm, range-Quoted 4 lines
Quoted 4 lines
Quoted 3 lines
Quoted 1 line
Quoted 1 line
attr_filter) |KVM_INVALID_ROOTS;What is the reason for
KVM_INVALID_ROOTSin this case?I wanted to keep consistent with that in
kvm_tdp_mmu_unmap_gfn_range().Yea, lack of consistency would raise other questions.
Quoted 3 lines
With this consistency, we can warn in
tdp_mmu_zap_leafs()as below though there should be no invalid mirror root.
Quoted 7 lines
Quoted 2 lines
WARN_ON_ONCE(iter_split_required(kvm, root, &iter, start, end));Hmm, let's be clear about the logic. This is essentially a mirror TDP only function, and there we don't have the same invalid root scenarios as the more complicated cases. I'm not exactly sure how we could hit the warning if they didn't match. I guess a hole punch on the fd while the TD is getting torn down?
In practice, the warning shoudn't be hit because mirror root should only be invalidated after gmem_fd is destroyed.
Quoted 1 line
Let's comment the reasoning at least.
Will do.
Re: [RFC PATCH 16/21] KVM: x86/mmu: Introduce kvm_split_boundary_leafs() to split boundary leafs
In reply to Yan ZhaoQuoted 26 lines · Yan Zhao
Quoted 20 lines
Quoted 6 lines
arch/x86/kvm/mmu/tdp_mmu.c +6
-0+ goto retry; + + sp =NULL ; +/* +* Set yielded in case after splitting to a lower level, +* the new iter requires furter splitting. arch/x86/kvm/mmu/tdp_mmu.c int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 1428
Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10
-0+*/ + iter.yielded = true; + *flush = true; + } + +rcu_read_unlock (); + +/* Leave it here though it should be impossible for the mirror root */ +if (sp) +tdp_mmu_free_sp (sp);What do you think about relying on
tdp_mmu_split_huge_pages_root()and moving this to an optimization patch at the end?Quoted 2 lines
Or what about just two calls to
tdp_mmu_split_huge_pages_root()at the boundaries?Though the two generally look like the same, relying on
tdp_mmu_split_huge_pages_root()will create several minor changes scattering intdp_mmu_split_huge_pages_root().
Quoted 6 lines
e.g. update flush after
tdp_mmu_iter_cond_resched(), checkiter_split_required(), set "iter.yielded = true".So, it may be hard to review as a initial RFC.
I prefer to do that after Paolo and Sean have taken a look of it :)
Oh, I might misunderstood your meaning.
Yes, if necessary, we can provide a separate patch at the end to combine code of tdp_mmu_split_huge_pages_root() and tdp_mmu_split_boundary_leafs().
Edgecombe, Rick P
maintainerRe: [RFC PATCH 16/21] KVM: x86/mmu: Introduce kvm_split_boundary_leafs() to split boundary leafs
Quoted 13 lines · Yan Zhao
Quoted 13 lines
Quoted 6 lines
What do you think about relying on
tdp_mmu_split_huge_pages_root()and moving
this to an optimization patch at the end?Or what about just two calls to
tdp_mmu_split_huge_pages_root()at the boundaries?Though the two generally look like the same, relying on
tdp_mmu_split_huge_pages_root()will create several minor changes scattering intdp_mmu_split_huge_pages_root().e.g. update flush after
tdp_mmu_iter_cond_resched(), checkiter_split_required(), set "iter.yielded = true".
Quoted 8 lines
Quoted 3 lines
So, it may be hard to review as a initial RFC.
I prefer to do that after Paolo and Sean have taken a look of it :)
Oh, I might misunderstood your meaning.
Yes, if necessary, we can provide a separate patch at the end to combine code oftdp_mmu_split_huge_pages_root()andtdp_mmu_split_boundary_leafs().
Hmm, I'm not sure if they will look at this version or wait until Intel folks work through it a bit. As for reviewability, the log could simply explain that tdp_mmu_split_huge_pages_root() is the simple option and an optimization patch will follow. I think it's helpful to separate optimization from implementation. It can be confusing what is for which purpose.
RFC PATCH 17/21 KVM: Change the return type of gfn_handler_t() from bool to int
In reply to Yan ZhaoModify the return type of gfn_handler_t() from bool to int. A negative return value indicates failure, while a return value of 1 signifies success with a flush required, and 0 denotes success without a flush required.
This adjustment prepares for a future change that will enable kvm_pre_set_memory_attributes() to fail.
No functional changes expected.
--- arch/arm64/kvm/mmu.c | 4 ++-- arch/loongarch/kvm/mmu.c | 4 ++-- arch/mips/kvm/mmu.c | 4 ++-- arch/powerpc/kvm/book3s.c | 4 ++-- arch/powerpc/kvm/e500_mmu_host.c | 4 ++-- arch/riscv/kvm/mmu.c | 4 ++-- arch/x86/kvm/mmu/mmu.c | 12 ++++++------ include/linux/kvm_host.h | 12 ++++++------ virt/kvm/kvm_main.c | 25 ++++++++++++++++--------- 9 files changed, 40 insertions(+), 33 deletions(-)
arch/arm64/kvm/mmu.c +2 -2
@@ -1973,7 +1973,7 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)return false; } -bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {u64 size = (range->end - range->start) <<PAGE_SHIFT ;
@@ -1989,7 +1989,7 @@ bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)*/ } -bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {u64 size = (range->end - range->start) <<PAGE_SHIFT ;
arch/loongarch/kvm/mmu.c +2 -2
@@ -511,7 +511,7 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range) range->end << PAGE_SHIFT, &ctx); } -bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {kvm_ptw_ctx ctx;
@@ -523,7 +523,7 @@ bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range) range->end << PAGE_SHIFT, &ctx); } -bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {gpa_t gpa = range->start <<PAGE_SHIFT ;kvm_pte_t *ptep =kvm_populate_gpa (kvm,NULL , gpa,0 );
arch/mips/kvm/mmu.c +2 -2
@@ -444,12 +444,12 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)return true; } -bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {return kvm_mips_mkold_gpa_pt (kvm, range->start, range->end); } -bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {gpa_t gpa = range->start <<PAGE_SHIFT ;pte_t *gpa_pte =kvm_mips_pte_for_gpa (kvm,NULL , gpa);
arch/powerpc/kvm/book3s.c +2 -2
@@ -886,12 +886,12 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)return kvm->arch.kvm_ops->unmap_gfn_range (kvm, range); } -bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {return kvm->arch.kvm_ops->age_gfn (kvm, range); } -bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {return kvm->arch.kvm_ops->test_age_gfn (kvm, range); }
arch/powerpc/kvm/e500_mmu_host.c +2 -2
@@ -697,13 +697,13 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)return kvm_e500_mmu_unmap_gfn (kvm, range); } -bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {/* XXX could be more clever ;) */ return false; } -bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {/* XXX could be more clever ;) */ return false;
arch/riscv/kvm/mmu.c +2 -2
@@ -550,7 +550,7 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)return false; } -bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {pte_t *ptep;u32 ptep_level =0 ;
@@ -568,7 +568,7 @@ bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)return ptep_test_and_clear_young (NULL ,0 , ptep); } -bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {pte_t *ptep;u32 ptep_level =0 ;
arch/x86/kvm/mmu/mmu.c +6 -6
@@ -1778,7 +1778,7 @@ static bool kvm_may_have_shadow_mmu_sptes(struct kvm *kvm)return !tdp_mmu_enabled ||READ_ONCE (kvm->arch.indirect_shadow_pages); } -bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {bool young = false;
@@ -1791,7 +1791,7 @@ bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)return young; } -bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range) {bool young = false;
@@ -7691,8 +7691,8 @@ void kvm_mmu_pre_destroy_vm(struct kvm *kvm) }#ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES -bool kvm_arch_pre_set_memory_attributes (struct kvm *kvm, -struct kvm_gfn_range *range) +int kvm_arch_pre_set_memory_attributes (struct kvm *kvm, +struct kvm_gfn_range *range) {/* * Zap SPTEs even if the slot can't be mapped PRIVATE. KVM x86 only
@@ -7752,8 +7752,8 @@ static bool hugepage_has_attrs(struct kvm *kvm, struct kvm_memory_slot *slot,return true; } -bool kvm_arch_post_set_memory_attributes (struct kvm *kvm, -struct kvm_gfn_range *range) +int kvm_arch_post_set_memory_attributes (struct kvm *kvm, +struct kvm_gfn_range *range) {unsigned long attrs = range->arg.attributes;struct kvm_memory_slot *slot = range->slot;
include/linux/kvm_host.h +6 -6
@@ -270,8 +270,8 @@ struct kvm_gfn_range { bool lockless; };bool kvm_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range); -bool kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range); -bool kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range); +int kvm_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range); +int kvm_test_age_gfn (struct kvm *kvm,struct kvm_gfn_range *range);int kvm_split_boundary_leafs (struct kvm *kvm,struct kvm_gfn_range *range);#endif
@@ -1526,7 +1526,7 @@ void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc);void kvm_mmu_invalidate_begin (struct kvm *kvm);void kvm_mmu_invalidate_range_add (struct kvm *kvm,gfn_t start,gfn_t end);void kvm_mmu_invalidate_end (struct kvm *kvm); -bool kvm_mmu_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range); +int kvm_mmu_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range);long kvm_arch_dev_ioctl (struct file *filp,unsigned int ioctl,unsigned long arg);
@@ -2504,10 +2504,10 @@ static inline unsigned long kvm_get_memory_attributes(struct kvm *kvm, gfn_t gfnbool kvm_range_has_memory_attributes (struct kvm *kvm,gfn_t start,gfn_t end,unsigned long mask,unsigned long attrs); -bool kvm_arch_pre_set_memory_attributes (struct kvm *kvm, +int kvm_arch_pre_set_memory_attributes (struct kvm *kvm, +struct kvm_gfn_range *range); +int kvm_arch_post_set_memory_attributes (struct kvm *kvm,struct kvm_gfn_range *range); -bool kvm_arch_post_set_memory_attributes (struct kvm *kvm, -struct kvm_gfn_range *range);static inline bool kvm_mem_is_private (struct kvm *kvm,gfn_t gfn) {
virt/kvm/kvm_main.c +16 -9
@@ -511,7 +511,7 @@ static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn) return container_of(mn, struct kvm, mmu_notifier); } -typedef bool (*gfn_handler_t )(struct kvm *kvm,struct kvm_gfn_range *range); +typedef int (*gfn_handler_t )(struct kvm *kvm,struct kvm_gfn_range *range);typedef void (*on_lock_fn_t )(struct kvm *kvm);
@@ -595,6 +595,7 @@ static __always_inline kvm_mn_ret_t kvm_handle_hva_range(struct kvm *kvm,kvm_for_each_memslot_in_hva_range (node, slots, range->start, range->end -1 ) {unsigned long hva_start, hva_end; +int ret; slot = container_of(node, struct kvm_memory_slot, hva_node[slots->node_idx]); hva_start = max_t(unsigned long, range->start, slot->userspace_addr);
@@ -635,7 +636,9 @@ static __always_inline kvm_mn_ret_t kvm_handle_hva_range(struct kvm *kvm, goto mmu_unlock; } } - r.ret |= range->handler (kvm, &gfn_range); + ret = range->handler (kvm, &gfn_range); +WARN_ON_ONCE (ret <0 ); + r.ret |= ret; } }
@@ -721,7 +724,7 @@ void kvm_mmu_invalidate_range_add(struct kvm *kvm, gfn_t start, gfn_t end) } } -bool kvm_mmu_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range) +int kvm_mmu_unmap_gfn_range (struct kvm *kvm,struct kvm_gfn_range *range) {kvm_mmu_invalidate_range_add (kvm, range->start, range->end);return kvm_unmap_gfn_range (kvm, range);
@@ -2413,7 +2416,8 @@ static __always_inline void kvm_handle_gfn_range(struct kvm *kvm,struct kvm_memslots *slots;struct kvm_memslot_iter iter;bool found_memslot = false; -bool ret = false; +bool flush = false; +int ret =0 ;int i; gfn_range.arg = range->arg;
@@ -2446,19 +2450,22 @@ static __always_inline void kvm_handle_gfn_range(struct kvm *kvm, range->on_lock (kvm); } - ret |= range->handler (kvm, &gfn_range); + ret = range->handler (kvm, &gfn_range); +if (ret <0 ) + goto err; + flush |= ret; } } - -if (range->flush_on_ret && ret) +err: +if (range->flush_on_ret && flush)kvm_flush_remote_tlbs (kvm);if (found_memslot)KVM_MMU_UNLOCK (kvm); } -static bool kvm_pre_set_memory_attributes (struct kvm *kvm, -struct kvm_gfn_range *range) +static int kvm_pre_set_memory_attributes (struct kvm *kvm, +struct kvm_gfn_range *range) {/* * Unconditionally add the range to the invalidation set, regardless of
Signature · 1 line
2.43.2
RFC PATCH 18/21 KVM: x86: Split huge boundary leafs before private to shared conversion
In reply to Yan ZhaoBefore converting a GFN range from private to shared, it is necessary to zap the mirror page table. When huge pages are supported and the GFN range intersects with a huge leaf, split the huge leaf to prevent zapping GFNs outside the conversion range.
Invoke kvm_split_boundary_leafs() in kvm_arch_pre_set_memory_attributes() to split the huge boundary leafs before calling kvm_unmap_gfn_range() to zap the GFN range that will be converted to shared.
Unlike kvm_unmap_gfn_range(), which cannot fail, kvm_split_boundary_leafs() may fail due to out of memory during splitting.
Update kvm_handle_gfn_range() to propagate the splitting error back to kvm_vm_set_mem_attributes(), which will subsequently fail the ioctl KVM_SET_MEMORY_ATTRIBUTES.
The downside of this approach is that although kvm_split_boundary_leafs() is invoked before kvm_unmap_gfn_range() for each GFN range, the entire conversion range may consist of several GFN ranges. If an out-of-memory error occurs during the splitting of a GFN range, some previous GFN ranges may have been successfully split and zapped, even though their page attributes remain unchanged due to the splitting failure. This may not be a big problem as the user can retry the ioctl to split and zap the full range.
--- arch/x86/kvm/mmu/mmu.c | 17 +++++++++++++---- virt/kvm/kvm_main.c | 13 +++++++++---- 2 files changed, 22 insertions(+), 8 deletions(-)
arch/x86/kvm/mmu/mmu.c +13 -4
@@ -7694,6 +7694,9 @@ void kvm_mmu_pre_destroy_vm(struct kvm *kvm)int kvm_arch_pre_set_memory_attributes (struct kvm *kvm,struct kvm_gfn_range *range) { +bool flush = false; +int ret; +/* * Zap SPTEs even if the slot can't be mapped PRIVATE. KVM x86 only * supports KVM_MEMORY_ATTRIBUTE_PRIVATE, and so it *seems* like KVM
@@ -7706,7 +7709,7 @@ int kvm_arch_pre_set_memory_attributes(struct kvm *kvm,* a hugepage can be used for affected ranges. */ if (WARN_ON_ONCE (!kvm_arch_has_private_mem (kvm))) -return false; +return 0 ;/* Unmap the old attribute page. */ if (range->arg.attributes &KVM_MEMORY_ATTRIBUTE_PRIVATE )
@@ -7714,7 +7717,13 @@ int kvm_arch_pre_set_memory_attributes(struct kvm *kvm,else range->attr_filter =KVM_FILTER_PRIVATE ; -return kvm_unmap_gfn_range (kvm, range); + ret =kvm_split_boundary_leafs (kvm, range); +if (ret <0 ) +return ret; + flush |= ret; + + flush |=kvm_unmap_gfn_range (kvm, range); +return flush; } static bool hugepage_test_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
@@ -7769,7 +7778,7 @@ int kvm_arch_post_set_memory_attributes(struct kvm *kvm,* SHARED may now allow hugepages. */ if (WARN_ON_ONCE (!kvm_arch_has_private_mem (kvm))) -return false; +return 0 ;/* * The sequence matters here: upper levels consume the result of lower
@@ -7816,7 +7825,7 @@ int kvm_arch_post_set_memory_attributes(struct kvm *kvm,hugepage_set_mixed (slot, gfn, level); } } -return false; +return 0 ; } void kvm_mmu_init_memslot_memory_attributes(struct kvm *kvm,
virt/kvm/kvm_main.c +9 -4
@@ -2408,8 +2408,8 @@ bool kvm_range_has_memory_attributes(struct kvm *kvm, gfn_t start, gfn_t end,return true; } -static __always_inline void kvm_handle_gfn_range(struct kvm *kvm, -struct kvm_mmu_notifier_range *range) +static __always_inline int kvm_handle_gfn_range(struct kvm *kvm, +struct kvm_mmu_notifier_range *range) {struct kvm_gfn_range gfn_range;struct kvm_memory_slot *slot;
@@ -2462,6 +2462,8 @@ static __always_inline void kvm_handle_gfn_range(struct kvm *kvm,if (found_memslot)KVM_MMU_UNLOCK (kvm); + +return ret <0 ? ret :0 ; } static int kvm_pre_set_memory_attributes(struct kvm *kvm,
@@ -2526,7 +2528,9 @@ static int kvm_vm_set_mem_attributes(struct kvm *kvm, gfn_t start, gfn_t end, goto out_unlock; } -kvm_handle_gfn_range (kvm, &pre_set_range); + r =kvm_handle_gfn_range (kvm, &pre_set_range); +if (r) + goto out_unlock;for (i = start; i < end; i++) { r = xa_err(xa_store(&kvm->mem_attr_array, i, entry,
@@ -2534,7 +2538,8 @@ static int kvm_vm_set_mem_attributes(struct kvm *kvm, gfn_t start, gfn_t end,KVM_BUG_ON (r, kvm); } -kvm_handle_gfn_range (kvm, &post_set_range); + r =kvm_handle_gfn_range (kvm, &post_set_range); +KVM_BUG_ON (r, kvm); out_unlock:mutex_unlock (&kvm->slots_lock);
Signature · 1 line
2.43.2
Edgecombe, Rick P
maintainerRe: [RFC PATCH 18/21] KVM: x86: Split huge boundary leafs before private to shared conversion
Quoted 4 lines · Yan Zhao
Before converting a GFN range from private to shared, it is necessary to zap the mirror page table. When huge pages are supported and the GFN range intersects with a huge leaf, split the huge leaf to prevent zapping GFNs outside the conversion range.
FALLOC_FL_PUNCH_HOLE demotion failure doesn't look like it is addressed in this series. I noticed that mmu notifier failures are allowed to be handled by blocking until success is possible, in most cases. KVM just doesn't need to because it can't fail. We could think about doing retries for FALLOC_FL_PUNCH_HOLE, while checking for signals. Or adding a ENOMEM error code to fallocate.
Re: [RFC PATCH 18/21] KVM: x86: Split huge boundary leafs before private to shared conversion
Quoted 7 lines · Rick P
Quoted 4 lines · Yan Zhao
Before converting a GFN range from private to shared, it is necessary to zap the mirror page table. When huge pages are supported and the GFN range intersects with a huge leaf, split the huge leaf to prevent zapping GFNs outside the conversion range.
FALLOC_FL_PUNCH_HOLEdemotion failure doesn't look like it is addressed in this
Hmm, FALLOC_FL_PUNCH_HOLE demotion failure is handled in patch 19.
Quoted 5 lines
series. I noticed that mmu notifier failures are allowed to be handled by blocking until success is possible, in most cases. KVM just doesn't need to because it can't fail. We could think about doing retries for
FALLOC_FL_PUNCH_HOLE, while checking for signals. Or adding a ENOMEM error code to fallocate.
In patch 19, FALLOC_FL_PUNCH_HOLE could return -ENOMEM.
Returning -ENOMEM may be inevitable as we can't endlessly retry. So for simplicity, there's no retry in this series.
Besides that, do you think whether we need to conduct splittings before any unmap is invoked?
As in the patch log:
"
The downside of this approach is that although kvm_split_boundary_leafs() is invoked before kvm_unmap_gfn_range() for each GFN range, the entire conversion range may consist of several GFN ranges. If an out-of-memory error occurs during the splitting of a GFN range, some previous GFN ranges may have been successfully split and zapped, even though their page attributes remain unchanged due to the splitting failure. This may not be a big problem as the user can retry the ioctl to split and zap the full range.
"
Edgecombe, Rick P
maintainerRe: [RFC PATCH 18/21] KVM: x86: Split huge boundary leafs before private to shared conversion
Quoted 3 lines · Yan Zhao
Quoted 2 lines
FALLOC_FL_PUNCH_HOLEdemotion failure doesn't look like it is addressed in thisHmm,
FALLOC_FL_PUNCH_HOLEdemotion failure is handled in patch 19.
Oh, right you are.
Quoted 8 lines
Quoted 7 lines
series. I noticed that mmu notifier failures are allowed to be handled by blocking until success is possible, in most cases. KVM just doesn't need to because it can't fail. We could think about doing retries for
FALLOC_FL_PUNCH_HOLE, while checking for signals. Or adding a ENOMEM error code
to fallocate.In patch 19,
FALLOC_FL_PUNCH_HOLEcould return-ENOMEM.
Yes. It is not in the man pages, but looking this morning I see other fallocate handlers are already returning it.
Quoted 3 lines
Returning
-ENOMEMmay be inevitable as we can't endlessly retry. So for simplicity, there's no retry in this series.
Ok, seems good.
Quoted 15 lines
Besides that, do you think whether we need to conduct splittings before any unmap is invoked?
As in the patch log:
"
The downside of this approach is that althoughkvm_split_boundary_leafs()
is invoked beforekvm_unmap_gfn_range()for each GFN range, the entire
conversion range may consist of several GFN ranges. If an out-of- memory
error occurs during the splitting of a GFN range, some previous GFN ranges
Quoted 8 lines
may have been successfully split and zapped, even though their page
attributes remain unchanged due to the splitting failure. This may not be a
big problem as the user can retry the ioctl to split and zap the full
range.
"
If we ended up plumbing the zapping errors all the way through the MMU, it probably would be simpler to do it during the unmap. Of course callers would have to be aware the range may be half unmapped on error. I think the way you have it is nice for not churning the MMU though.
But for the case of having to retry the split and walking the mirror EPT range again, it's a rare case and not worth optimizing for. Let's not consider it much.
RFC PATCH 19/21 KVM: gmem: Split huge boundary leafs for punch hole of private memory
In reply to Yan ZhaoSplitting of huge leafs in the mirror page table for kvm_gmem_punch_hole().
Enhance kvm_gmem_invalidate_begin() to invoke kvm_split_boundary_leafs() for splitting boundary huge leafs before caling kvm_unmap_gfn_range() to do the real zapping. As kvm_split_boundary_leafs() may fail due to out of memory, propagate the error to further fail the kvm_gmem_punch_hole().
Splitting huge boudary leafs in the mirror page table is not required for kvm_gmem_release() as the entire page table is to be zapped; it's also not required for kvm_gmem_error_folio() as a SPTE must not map more than one physical folio.
Note: as the kvm_gmem_punch_hole() may request to zap several GFN ranges, if an out-of-memory error occurs during the splitting of a GFN range, some previous GFN ranges may have been successfully split and zapped.
--- virt/kvm/guest_memfd.c | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-)
virt/kvm/guest_memfd.c +23 -7
@@ -292,13 +292,14 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index, intreturn folio; } -static void kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, -pgoff_t end) +static int kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end,bool need_split) {bool flush = false, found_memslot = false;struct kvm_memory_slot *slot;struct kvm *kvm = gmem->kvm;unsigned long index; +int ret =0 ;xa_for_each_range (&gmem->bindings, index, slot, start, end -1 ) {pgoff_t pgoff = slot->gmem.pgoff;
@@ -319,14 +320,23 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,kvm_mmu_invalidate_begin (kvm); } +if (need_split) { + ret =kvm_split_boundary_leafs (kvm, &gfn_range); +if (ret <0 ) + goto out; + + flush |= ret; + } flush |=kvm_mmu_unmap_gfn_range (kvm, &gfn_range); } +out:if (flush)kvm_flush_remote_tlbs (kvm);if (found_memslot)KVM_MMU_UNLOCK (kvm); +return 0 ; } static void kvm_gmem_invalidate_end(struct kvm_gmem *gmem, pgoff_t start,
@@ -347,6 +357,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)loff_t size =i_size_read (inode);pgoff_t start, end;struct kvm_gmem *gmem; +int ret =0 ;if (offset > size)return 0 ;
@@ -361,18 +372,22 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)*/ filemap_invalidate_lock (inode->i_mapping); -list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_begin (gmem, start, end); +list_for_each_entry (gmem, gmem_list, entry) { + ret =kvm_gmem_invalidate_begin (gmem, start, end, true); +if (ret <0 ) + goto out; + }truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 );kvm_gmem_mark_range_unprepared (inode, start, end - start); +out:list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_end (gmem, start, end);filemap_invalidate_unlock (inode->i_mapping); -return 0 ; +return ret; }static long kvm_gmem_allocate (struct inode *inode,loff_t offset,loff_t len)
@@ -440,7 +455,7 @@ static int kvm_gmem_release(struct inode *inode, struct file *file)* Zap all SPTEs pointed at by this file. Do not free the backing * memory, as its lifetime is associated with the inode, not the file. */ -kvm_gmem_invalidate_begin (gmem,0 ,-1ul ); +kvm_gmem_invalidate_begin (gmem,0 ,-1ul , false);kvm_gmem_invalidate_end (gmem,0 ,-1ul );list_del (&gmem->entry);
@@ -524,8 +539,9 @@ static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol start = folio->index; end = start +folio_nr_pages (folio); +/* The size of the SEPT will not exceed the size of the folio */ list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_begin (gmem, start, end); +kvm_gmem_invalidate_begin (gmem, start, end, false);/* * Do not truncate the range, what action is taken in response to the
Signature · 1 line
2.43.2
Re: [RFC PATCH 19/21] KVM: gmem: Split huge boundary leafs for punch hole of private memory
Quoted 38 lines · Yan Zhao
virt/kvm/guest_memfd.c +0
-0@@ -292,13 +292,14 @@ static struct folio *kvm_gmem_get_folio(structinode *inode,
pgoff_tindex, intvirt/kvm/guest_memfd.c +0
-1return folio; } -static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_tstart,
virt/kvm/guest_memfd.c +1
-1- pgoff_t end) +static int kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_tstart,
virt/kvm/guest_memfd.c +2
-0+ pgoff_t end, bool need_split) { bool flush = false, found_memslot = false;struct kvm_memory_slot *slot;struct kvm *kvm = gmem->kvm;unsigned long index; +int ret =0 ; xa_for_each_range(&gmem->bindings, index, slot, start, end -1) {
virt/kvm/guest_memfd.c +7
-0pgoff_t pgoff = slot->gmem.pgoff;@@ -319,14 +320,23 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,kvm_mmu_invalidate_begin (kvm ); } +if (need_split) { + ret =kvm_split_boundary_leafs (kvm, &gfn_range); +if (ret <0 ) + goto out; + + flush |= ret; + }
virt/kvm/guest_memfd.c static void kvm_gmem_invalidate_begin(struct · line 341
Quoted 10 lines
virt/kvm/guest_memfd.c +2
-0flush |=kvm_mmu_unmap_gfn_range (kvm, &gfn_range); } +out:if (flush)kvm_flush_remote_tlbs (kvm);if (found_memslot)KVM_MMU_UNLOCK (kvm); +return 0 ;
Should return ret, not 0
Re: [RFC PATCH 19/21] KVM: gmem: Split huge boundary leafs for punch hole of private memory
Quoted 46 lines · Francesco Lavra
Quoted 45 lines · Yan Zhao
virt/kvm/guest_memfd.c +0
-0@@ -292,13 +292,14 @@ static struct folio *kvm_gmem_get_folio(structinode *inode,
pgoff_tindex, intvirt/kvm/guest_memfd.c +0
-1return folio; } -static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_tstart,
virt/kvm/guest_memfd.c +1
-1- pgoff_t end) +static int kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_tstart,
virt/kvm/guest_memfd.c +2
-0+ pgoff_t end, bool need_split) { bool flush = false, found_memslot = false;struct kvm_memory_slot *slot;struct kvm *kvm = gmem->kvm;unsigned long index; +int ret =0 ; xa_for_each_range(&gmem->bindings, index, slot, start, end -1) {
virt/kvm/guest_memfd.c +8
-0pgoff_t pgoff = slot->gmem.pgoff;@@ -319,14 +320,23 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,kvm_mmu_invalidate_begin (kvm ); } +if (need_split) { + ret =kvm_split_boundary_leafs (kvm, &gfn_range); +if (ret <0 ) + goto out; + + flush |= ret; + } flush |=kvm_mmu_unmap_gfn_range (kvm, &gfn_range); } +out:if (flush)kvm_flush_remote_tlbs (kvm);
Quoted 5 lines
virt/kvm/guest_memfd.c static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start, · line 339
Quoted 3 lines
virt/kvm/guest_memfd.c +1
-0if (found_memslot)KVM_MMU_UNLOCK (kvm); +return 0 ;Should return ret, not 0
Yes, thank you for the correction!
Edgecombe, Rick P
maintainerRe: [RFC PATCH 19/21] KVM: gmem: Split huge boundary leafs for punch hole of private memory
In reply to Yan ZhaoQuoted 15 lines · Yan Zhao
virt/kvm/guest_memfd.c +2
-0+static int kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, + pgoff_t end, bool need_split){
bool flush = false,found_memslot= false; structkvm_memory_slot*slot; struct kvm *kvm =gmem->kvm; unsigned long index;(quoted diff) +1
-0+ int ret = 0;
xa_for_each_range(&gmem->bindings, index, slot, start, end - 1){pgoff_tpgoff =slot->gmem.pgoff;virt/kvm/guest_memfd.c +0
-0@@ -319,14 +320,23 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start, kvm_mmu_invalidate_begin(kvm); }
virt/kvm/guest_memfd.c static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start, · line 324
Quoted 2 lines
virt/kvm/guest_memfd.c +2
-0+if (need_split) { + ret =kvm_split_boundary_leafs (kvm, &gfn_range);
What is the effect for other guestmemfd users? SEV doesn't need this, right? Oh I see, down in tdp_mmu_split_boundary_leafs() it bails on non-mirror roots. I don't like the naming then. It sounds deterministic, but it's really only necessary splits for certain VM types.
I guess it all depends on how well teaching kvm_mmu_unmap_gfn_range() to fail goes. But otherwise, we should call it like kvm_prepare_zap_range() or something. And have it make it clearly do nothing for non-TDX high up where it's easy to see.
Quoted 15 lines
virt/kvm/guest_memfd.c +5
-0+if (ret <0 ) + goto out; + + flush |= ret; + }flush |=
kvm_mmu_unmap_gfn_range(kvm, &gfn_range); }
+out:
if (flush)
kvm_flush_remote_tlbs(kvm);
if (found_memslot)
KVM_MMU_UNLOCK(kvm);virt/kvm/guest_memfd.c +1
-0+
Re: [RFC PATCH 19/21] KVM: gmem: Split huge boundary leafs for punch hole of private memory
Quoted 15 lines · Rick P
Quoted 14 lines · Yan Zhao
virt/kvm/guest_memfd.c +2
-0+static int kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, + pgoff_t end, bool need_split){
bool flush = false,found_memslot= false; structkvm_memory_slot*slot; struct kvm *kvm =gmem->kvm; unsigned long index;(quoted diff) +1
-0+ int ret = 0;
xa_for_each_range(&gmem->bindings, index, slot, start, end - 1){pgoff_tpgoff =slot->gmem.pgoff;virt/kvm/guest_memfd.c +0
-0@@ -319,14 +320,23 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start, kvm_mmu_invalidate_begin(kvm); }
Quoted 8 lines
virt/kvm/guest_memfd.c static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start, · line 324
Quoted 3 lines
virt/kvm/guest_memfd.c +2
-0+if (need_split) { + ret =kvm_split_boundary_leafs (kvm, &gfn_range);What is the effect for other guestmemfd users? SEV doesn't need this, right? Oh I see, down in
tdp_mmu_split_boundary_leafs()it bails on non-mirror roots. I don't like the naming then. It sounds deterministic, but it's really only necessary splits for certain VM types.
Right, kvm_split_boundary_leafs() only takes effect on the mirror root.
Quoted 2 lines
I guess it all depends on how well teaching
kvm_mmu_unmap_gfn_range()to fail goes. But otherwise, we should call it likekvm_prepare_zap_range()or
Hmm, if we call it kvm_prepare_zap_range(), we have to invoke it for all zaps. However, except kvm_gmem_punch_hole(), the other two callers kvm_gmem_error_folio(), kvm_gmem_release() have no need to perfrom splitting before zapping.
Passing in the invalidation reason to kvm_gmem_invalidate_begin() also makes things complicated.
Quoted 2 lines
something. And have it make it clearly do nothing for non-TDX high up where it's easy to see.
Would a name like kvm_split_boundary_leafs_for_mirror() be too TDX specific?
If we name it kvm_split_boundary_leafs(), SEV can simply remove the bailing out if they want in future.
Quoted 17 lines
Quoted 16 lines
virt/kvm/guest_memfd.c +5
-0+if (ret <0 ) + goto out; + + flush |= ret; + }flush |=
kvm_mmu_unmap_gfn_range(kvm, &gfn_range); }
+out:
if (flush)
kvm_flush_remote_tlbs(kvm);
if (found_memslot)
KVM_MMU_UNLOCK(kvm);virt/kvm/guest_memfd.c +1
-0+
RFC PATCH 20/21 KVM: x86: Force a prefetch fault's max mapping level to 4KB for TDX
In reply to Yan ZhaoIntroduce a "prefetch" parameter to the private_max_mapping_level hook and enforce the max mapping level of a prefetch fault for private memory to be 4KB. This is a preparation to enable the ignoring huge page splitting in the fault path.
If a prefetch fault results in a 2MB huge leaf in the mirror page table, there may not be a vCPU available to accept the corresponding 2MB huge leaf in the S-EPT if the TD is not configured to receive #VE for page acceptance. Consequently, if a vCPU accepts the page at 4KB level, it will trigger an EPT violation to split the 2MB huge leaf generated by the prefetch fault.
Since handling the BUSY error from SEAMCALLs for huge page splitting is more comprehensive in the fault path, which is with kvm->mmu_lock held for reading, force the max mapping level of a prefetch fault of private memory to be 4KB to prevent potential splitting.
Since prefetch faults for private memory are uncommon after the TD's build time, enforcing a 4KB mapping level is unlikely to cause any performance degradation. The max mapping level is already set to 4KB during the TD's build phase.
--- arch/x86/include/asm/kvm_host.h | 3 ++- arch/x86/kvm/mmu/mmu.c | 7 ++++--- arch/x86/kvm/svm/sev.c | 3 ++- arch/x86/kvm/svm/svm.h | 5 +++-- arch/x86/kvm/vmx/main.c | 5 +++-- arch/x86/kvm/vmx/tdx.c | 5 +++-- arch/x86/kvm/vmx/x86_ops.h | 4 ++-- 7 files changed, 19 insertions(+), 13 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -1
@@ -1900,7 +1900,8 @@ struct kvm_x86_ops {void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu);int (*gmem_prepare)(struct kvm *kvm,kvm_pfn_t pfn,gfn_t gfn,int max_order);void (*gmem_invalidate)(kvm_pfn_t start,kvm_pfn_t end); -int (*private_max_mapping_level)(struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn); +int (*private_max_mapping_level)(struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn, +bool prefetch); };struct kvm_x86_nested_ops {
arch/x86/kvm/mmu/mmu.c +4 -3
@@ -4488,7 +4488,7 @@ static inline u8 kvm_max_level_for_order(int order) }static u8 kvm_max_private_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn, -u8 max_level,int gmem_order) +u8 max_level,int gmem_order,bool prefetch) {u8 req_max_level;
@@ -4499,7 +4499,7 @@ static u8 kvm_max_private_mapping_level(struct kvm_vcpu *vcpu, kvm_pfn_t pfn, gfif (max_level ==PG_LEVEL_4K )return PG_LEVEL_4K ; - req_max_level =kvm_x86_call (private_max_mapping_level)(vcpu, pfn, gfn); + req_max_level =kvm_x86_call (private_max_mapping_level)(vcpu, pfn, gfn, prefetch);if (req_max_level) max_level =min (max_level, req_max_level);
@@ -4532,7 +4532,8 @@ static int kvm_mmu_faultin_pfn_private(struct kvm_vcpu *vcpu, fault->map_writable = !(fault->slot->flags &KVM_MEM_READONLY ); fault->max_level =kvm_max_private_mapping_level (vcpu, fault->pfn, fault->gfn, - fault->max_level, max_order); + fault->max_level, max_order, + fault->prefetch);return RET_PF_CONTINUE ; }
arch/x86/kvm/svm/sev.c +2 -1
@@ -4910,7 +4910,8 @@ void sev_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end) } } -int sev_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) +int sev_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn, +bool prefetch) {int level, rc;bool assigned;
arch/x86/kvm/svm/svm.h +3 -2
@@ -782,7 +782,7 @@ void sev_handle_rmp_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code);void sev_snp_init_protected_guest_state (struct kvm_vcpu *vcpu);int sev_gmem_prepare (struct kvm *kvm,kvm_pfn_t pfn,gfn_t gfn,int max_order);void sev_gmem_invalidate (kvm_pfn_t start,kvm_pfn_t end); -int sev_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn); +int sev_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn,bool prefetch);#else static inline struct page *snp_safe_alloc_page_node (int node,gfp_t gfp) {
@@ -809,7 +809,8 @@ static inline int sev_gmem_prepare(struct kvm *kvm, kvm_pfn_t pfn, gfn_t gfn, inreturn 0 ; }static inline void sev_gmem_invalidate (kvm_pfn_t start,kvm_pfn_t end) {} -static inline int sev_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) +static inline int sev_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn, +gfn_t gfn,bool prefetch) {return 0 ; }
arch/x86/kvm/vmx/main.c +3 -2
@@ -881,10 +881,11 @@ static int vt_vcpu_mem_enc_ioctl(struct kvm_vcpu *vcpu, void __user *argp)return tdx_vcpu_ioctl (vcpu, argp); } -static int vt_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) +static int vt_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn, +gfn_t gfn,bool prefetch) {if (is_td (vcpu->kvm)) -return tdx_gmem_private_max_mapping_level (vcpu, pfn, gfn); +return tdx_gmem_private_max_mapping_level (vcpu, pfn, gfn, prefetch);return 0 ; }
arch/x86/kvm/vmx/tdx.c +3 -2
@@ -3332,11 +3332,12 @@ int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp)return ret; } -int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) +int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn, +gfn_t gfn,bool prefetch) {struct vcpu_tdx *tdx =to_tdx (vcpu); -if (unlikely (to_kvm_tdx (vcpu->kvm)->state !=TD_STATE_RUNNABLE )) +if (unlikely ((to_kvm_tdx (vcpu->kvm)->state !=TD_STATE_RUNNABLE ) || prefetch))return PG_LEVEL_4K ;if (gfn >= tdx->violation_gfn_start && gfn < tdx->violation_gfn_end)
arch/x86/kvm/vmx/x86_ops.h +2 -2
@@ -164,7 +164,7 @@ int tdx_sept_split_private_spt(struct kvm *kvm, gfn_t gfn, enum pg_level level,void tdx_flush_tlb_current (struct kvm_vcpu *vcpu);void tdx_flush_tlb_all (struct kvm_vcpu *vcpu);void tdx_load_mmu_pgd (struct kvm_vcpu *vcpu,hpa_t root_hpa,int root_level); -int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn); +int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn,bool prefetch);#else static inline void tdx_disable_virtualization_cpu (void ) {}static inline int tdx_vm_init (struct kvm *kvm) {return -EOPNOTSUPP ; }
@@ -236,7 +236,7 @@ static inline int tdx_sept_split_private_spt(struct kvm *kvm, gfn_t gfn,static inline void tdx_flush_tlb_current (struct kvm_vcpu *vcpu) {}static inline void tdx_flush_tlb_all (struct kvm_vcpu *vcpu) {}static inline void tdx_load_mmu_pgd (struct kvm_vcpu *vcpu,hpa_t root_hpa,int root_level) {} -static inline int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn) {return 0 ; } +static inline int tdx_gmem_private_max_mapping_level (struct kvm_vcpu *vcpu,kvm_pfn_t pfn,gfn_t gfn,bool prefetch) {return 0 ; }#endif #endif /* __KVM_X86_VMX_X86_OPS_H */
Signature · 1 line
2.43.2
Edgecombe, Rick P
maintainerRe: [RFC PATCH 20/21] KVM: x86: Force a prefetch fault's max mapping level to 4KB for TDX
Quoted 10 lines · Yan Zhao
Introduce a "prefetch" parameter to the
private_max_mapping_levelhook and enforce the max mapping level of a prefetch fault for private memory to be 4KB. This is a preparation to enable the ignoring huge page splitting in the fault path.If a prefetch fault results in a 2MB huge leaf in the mirror page table, there may not be a vCPU available to accept the corresponding 2MB huge leaf in the S-EPT if the TD is not configured to receive #VE for page acceptance.
Can you elaborate on this case more. A vCPU may not be available? What does that mean?
Quoted 3 lines
Consequently, if a vCPU accepts the page at 4KB level, it will trigger an EPT violation to split the 2MB huge leaf generated by the prefetch fault.
The case is KVM_PRE_FAULT_MEMORY faults in 2MB, then guest accepts at 4k (which it is not supposed to do)?
Then maybe the kvm_vm_dead() case I suggested in the other patch could handle this case too, and this patch could be dropped?
Quoted 5 lines
Since handling the BUSY error from SEAMCALLs for huge page splitting is more comprehensive in the fault path, which is with
kvm->mmu_lockheld for reading, force the max mapping level of a prefetch fault of private memory to be 4KB to prevent potential splitting.
Re: [RFC PATCH 20/21] KVM: x86: Force a prefetch fault's max mapping level to 4KB for TDX
Quoted 6 lines · Rick P
Quoted 5 lines · Yan Zhao
Introduce a "prefetch" parameter to the
private_max_mapping_levelhook and enforce the max mapping level of a prefetch fault for private memory to be 4KB. This is a preparation to enable the ignoring huge page splitting in the fault path.
Quoted 8 lines
Quoted 5 lines
If a prefetch fault results in a 2MB huge leaf in the mirror page table, there may not be a vCPU available to accept the corresponding 2MB huge leaf in the S-EPT if the TD is not configured to receive #VE for page acceptance.
Can you elaborate on this case more. A vCPU may not be available? What does that mean?
Sorry. I didn't express it clearly.
If a prefetch fault results in a 2MB mapping, as the guest is not aware of the prefetched mapping, it may accept at 4KB later, triggering a demotion.
Quoted 6 lines
Quoted 3 lines
Consequently, if a vCPU accepts the page at 4KB level, it will trigger an EPT violation to split the 2MB huge leaf generated by the prefetch fault.
The case is
KVM_PRE_FAULT_MEMORYfaults in 2MB, then guest accepts at 4k (which it is not supposed to do)?
Actually, the guest is innocent to accept at 4KB.
Quoted 2 lines
Then maybe the
kvm_vm_dead()case I suggested in the other patch could handle this case too, and this patch could be dropped?
This patch is not required if we decide to support demotion in the fault path.
Quoted 5 lines
Quoted 4 lines
Since handling the BUSY error from SEAMCALLs for huge page splitting is more comprehensive in the fault path, which is with
kvm->mmu_lockheld for reading, force the max mapping level of a prefetch fault of private memory to be 4KB to prevent potential splitting.
Re: [RFC PATCH 20/21] KVM: x86: Force a prefetch fault's max mapping level to 4KB for TDX
In reply to Yan ZhaoQuoted 12 lines · Yan Zhao
Introduce a "prefetch" parameter to the
private_max_mapping_levelhook and enforce the max mapping level of a prefetch fault for private memory to be 4KB. This is a preparation to enable the ignoring huge page splitting in the fault path.If a prefetch fault results in a 2MB huge leaf in the mirror page table, there may not be a vCPU available to accept the corresponding 2MB huge leaf in the S-EPT if the TD is not configured to receive #VE for page acceptance. Consequently, if a vCPU accepts the page at 4KB level, it will trigger an EPT violation to split the 2MB huge leaf generated by the prefetch fault.
Quoted 8 lines
Since handling the BUSY error from SEAMCALLs for huge page splitting is more comprehensive in the fault path, which is with
kvm->mmu_lockheld for reading, force the max mapping level of a prefetch fault of private memory to be 4KB to prevent potential splitting.Since prefetch faults for private memory are uncommon after the TD's build time, enforcing a 4KB mapping level is unlikely to cause any performance degradation.
I am wondering what are the use cases for KVM_PRE_FAULT_MEMORY.
Is there an API usage guide to limit that userspace shouldn't use it for a large amount of memory pre-fault? If no, and userspace uses it to pre-fault a lot of memory, this "unlikely to cause any performance degradation" might be not true.
Re: [RFC PATCH 20/21] KVM: x86: Force a prefetch fault's max mapping level to 4KB for TDX
Quoted 20 lines · Binbin Wu
Quoted 17 lines · Yan Zhao
Introduce a "prefetch" parameter to the
private_max_mapping_levelhook and enforce the max mapping level of a prefetch fault for private memory to be 4KB. This is a preparation to enable the ignoring huge page splitting in the fault path.If a prefetch fault results in a 2MB huge leaf in the mirror page table, there may not be a vCPU available to accept the corresponding 2MB huge leaf in the S-EPT if the TD is not configured to receive #VE for page acceptance. Consequently, if a vCPU accepts the page at 4KB level, it will trigger an EPT violation to split the 2MB huge leaf generated by the prefetch fault.
Since handling the BUSY error from SEAMCALLs for huge page splitting is more comprehensive in the fault path, which is with
kvm->mmu_lockheld for reading, force the max mapping level of a prefetch fault of private memory to be 4KB to prevent potential splitting.
Quoted 7 lines
Quoted 3 lines
Since prefetch faults for private memory are uncommon after the TD's build time, enforcing a 4KB mapping level is unlikely to cause any performance degradation.
I am wondering what are the use cases for
KVM_PRE_FAULT_MEMORY.
Is there an API usage guide to limit that userspace shouldn't use it for a large amount of memory pre-fault? If no, and userspace uses it to pre-fault a lot of memory, this "unlikely to cause any performance degradation" might be not true.
Currently, there are no known users of KVM_PRE_FAULT_MEMORY.
We can enable huge page support for prefetch faults (along with allowing splitting in the fault path) in the future if performance considerations arise for future users.
RFC PATCH 21/21 KVM: x86: Ignore splitting huge pages in fault path for TDX
In reply to Yan ZhaoAs handling the BUSY error from SEAMCALLs for splitting huge pages is more comprehensive in the fault path, which is with kvm->mmu_lock held for reading, simply ignore the splitting huge page request in fault path for TDX.
Splitting in fault path can now be caused by vCPUs' concurrent ACCEPT operations at diffent levels, e.g. one vCPU accepts at 2MB level while another vCPU accepts at 4KB level. As the first vCPU will accepts the whole 2MB range ultimately, ignoring the mapping request (which leads to huge page splitting) caused by the second 4KB ACCEPT operation is fine.
A rare case that could lead to splitting in the fault path is when a TD is configured to receive #VE and accesses memory before the ACCEPT operation. By the time a vCPU accesses a private GFN, due to the lack of any guest preferred level, KVM could create a mapping at 2MB level. If the TD then only performs the ACCEPT operation at 4KB level, splitting in the fault path will be triggered. However, this is not regarded as a typical use case, as usually TD always accepts pages in the order from 1GB->2MB->4KB. The worst outcome to ignore the resulting splitting request is an endless EPT violation. This would not happen for a Linux guest, which does not expect any #VE.
This ignoring of splitting huge page in fault path is achieved in 3 parts:
1. In KVM TDP MMU,
allow splitting huge pages in fault path for the mirror page table and propagate the splitting request to TDX.
2. Enhance the hook split_external_spt by
passing in shared/exclusive status of kvm->mmu_lock
3. In TDX's implementation of hook split_external_spt,
do nothing but to set the max_level of the next fault on the splitting GFN range on the vCPU to 2MB and return -EBUSY.
Then after tdx_sept_split_private_spt() returns, TDX's EPT violation handler may (a) return to guest directly (when signal/interrupt pending) or
(b) retry locally in the TDX's code.
- for (a), the TD can retry the ACCEPT operation, finding the memory is accepted at 2MB level by another vCPU.
- for (b), as the violation_request_level is set to 2MB, the next kvm_mmu_page_fault() will return RET_PF_SPURIOUS, causing re-entering of the TD.
--- arch/x86/include/asm/kvm_host.h | 2 +- arch/x86/kvm/mmu/tdp_mmu.c | 44 ++++++++++++++++++++------------- arch/x86/kvm/vmx/tdx.c | 25 ++++++++++++++++++- arch/x86/kvm/vmx/x86_ops.h | 5 ++-- 4 files changed, 55 insertions(+), 21 deletions(-)
arch/x86/include/asm/kvm_host.h +1 -1
@@ -1814,7 +1814,7 @@ struct kvm_x86_ops {/* Split the external page table into smaller page tables */ int (*split_external_spt)(struct kvm *kvm,gfn_t gfn,enum pg_level level, -void *external_spt); +void *external_spt,bool mmu_lock_shared);bool (*has_wbinvd_exit)(void );
arch/x86/kvm/mmu/tdp_mmu.c +27 -17
86 lines not on this page · raw message
arch/x86/kvm/vmx/tdx.c +24 -1
@@ -1834,7 +1834,7 @@ static int tdx_spte_demote_private_spte(struct kvm *kvm, gfn_t gfn, }int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, -void *private_spt) +void *private_spt,bool mmu_lock_shared) {struct page *page =virt_to_page (private_spt);int ret;
@@ -1842,6 +1842,29 @@ int tdx_sept_split_private_spt(struct kvm *kvm, gfn_t gfn, enum pg_level level,if (KVM_BUG_ON (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE || level !=PG_LEVEL_2M , kvm))return -EINVAL ; +/* +* Split request with mmu_lock held for reading can only occur when one +* vCPU accepts at 2MB level while another vCPU accepts at 4KB level. +* Ignore this 4KB mapping request by setting violation_request_level to +* 2MB and returning -EBUSY for retry. Then the next fault at 2MB level +* would be a spurious fault. The vCPU accepting at 2MB will accept the +* whole 2MB range. +*/ +if (mmu_lock_shared) { +struct kvm_vcpu *vcpu =kvm_get_running_vcpu (); +struct vcpu_tdx *tdx =to_tdx (vcpu); + +if (KVM_BUG_ON (!vcpu, kvm)) +return -EOPNOTSUPP ; + +/* Request to map as 2MB leaf for the whole 2MB range */ + tdx->violation_gfn_start =gfn_round_for_level (gfn, level); + tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); + tdx->violation_request_level = level; + +return -EBUSY ; + } + ret =tdx_sept_zap_private_spte (kvm, gfn, level, page);if (ret <=0 )return ret;
arch/x86/kvm/vmx/x86_ops.h +3 -2
@@ -159,7 +159,7 @@ int tdx_sept_set_private_spte(struct kvm *kvm, gfn_t gfn,int tdx_sept_remove_private_spte (struct kvm *kvm,gfn_t gfn,enum pg_level level,kvm_pfn_t pfn);int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, -void *private_spt); +void *private_spt,bool mmu_lock_shared);void tdx_flush_tlb_current (struct kvm_vcpu *vcpu);void tdx_flush_tlb_all (struct kvm_vcpu *vcpu);
@@ -228,7 +228,8 @@ static inline int tdx_sept_remove_private_spte(struct kvm *kvm, gfn_t gfn,static inline int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, -void *private_spt) +void *private_spt, +bool mmu_lock_shared) {return -EOPNOTSUPP ; }
Signature · 1 line
2.43.2
Edgecombe, Rick P
maintainerRe: [RFC PATCH 21/21] KVM: x86: Ignore splitting huge pages in fault path for TDX
Quoted 21 lines · Yan Zhao
int tdx_sept_split_private_spt(struct kvm *kvm,
gfn_tgfn, enumpg_levellevel,arch/x86/kvm/vmx/tdx.c +12
-1- void *private_spt) + void *private_spt, bool mmu_lock_shared) {struct page *page =virt_to_page (private_spt);int ret;@@ -1842,6 +1842,29 @@ int tdx_sept_split_private_spt(struct kvm *kvm, gfn_t gfn, enum pg_level level,if (KVM_BUG_ON (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE || level !=PG_LEVEL_2M , kvm))return -EINVAL ; +/* +* Split request with mmu_lock held for reading can only occur when one +* vCPU accepts at 2MB level while another vCPU accepts at 4KB level. +* Ignore this 4KB mapping request by setting violation_request_level to +* 2MB and returning -EBUSY for retry. Then the next fault at 2MB level +* would be a spurious fault. The vCPU accepting at 2MB will accept the +* whole 2MB range. +*/ +if (mmu_lock_shared) { +struct kvm_vcpu *vcpu =kvm_get_running_vcpu (); +struct vcpu_tdx *tdx =to_tdx (vcpu);
arch/x86/kvm/vmx/tdx.c int tdx_sept_split_private_spt(struct kvm *kvm, gfn_t gfn, enum pg_level level, · line 1865
Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10
-0+ +if (KVM_BUG_ON (!vcpu, kvm)) +return -EOPNOTSUPP ; + +/* Request to map as 2MB leaf for the whole 2MB range */ + tdx->violation_gfn_start =gfn_round_for_level (gfn, level); + tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); + tdx->violation_request_level = level; + +return -EBUSY ;
This is too hacky the way it infers so much from mmu_lock_shared. Since guests shouldn't be doing this, what about just doing kvm_vm_dead(), with a little pr_warn()? Maybe even just do it in set_external_spte_present() and declare it the rule for external page tables. It can shrink this patch significantly, for no expected user impact.
Quoted 28 lines
arch/x86/kvm/vmx/tdx.c +2
-0+ } + ret =tdx_sept_zap_private_spte (kvm, gfn, level, page);if (ret <=0 )return ret;arch/x86/kvm/vmx/x86_ops.h +3
-2@@ -159,7 +159,7 @@ int tdx_sept_set_private_spte(struct kvm *kvm, gfn_t gfn,int tdx_sept_remove_private_spte (struct kvm *kvm,gfn_t gfn,enum pg_level level,kvm_pfn_t pfn);int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, -void *private_spt); +void *private_spt,bool mmu_lock_shared);void tdx_flush_tlb_current (struct kvm_vcpu *vcpu);void tdx_flush_tlb_all (struct kvm_vcpu *vcpu);@@ -228,7 +228,8 @@ static inline int tdx_sept_remove_private_spte(struct kvm *kvm, gfn_t gfn,static inline int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, -void *private_spt) +void *private_spt, +bool mmu_lock_shared) {return -EOPNOTSUPP ; }
Re: [RFC PATCH 21/21] KVM: x86: Ignore splitting huge pages in fault path for TDX
Quoted 29 lines · Rick P
Quoted 27 lines · Yan Zhao
int tdx_sept_split_private_spt(struct kvm *kvm,
gfn_tgfn, enumpg_levellevel,arch/x86/kvm/vmx/tdx.c +18
-1- void *private_spt) + void *private_spt, bool mmu_lock_shared) {struct page *page =virt_to_page (private_spt);int ret;@@ -1842,6 +1842,29 @@ int tdx_sept_split_private_spt(struct kvm *kvm, gfn_t gfn, enum pg_level level,if (KVM_BUG_ON (to_kvm_tdx (kvm)->state !=TD_STATE_RUNNABLE || level !=PG_LEVEL_2M , kvm))return -EINVAL ; +/* +* Split request with mmu_lock held for reading can only occur when one +* vCPU accepts at 2MB level while another vCPU accepts at 4KB level. +* Ignore this 4KB mapping request by setting violation_request_level to +* 2MB and returning -EBUSY for retry. Then the next fault at 2MB level +* would be a spurious fault. The vCPU accepting at 2MB will accept the +* whole 2MB range. +*/ +if (mmu_lock_shared) { +struct kvm_vcpu *vcpu =kvm_get_running_vcpu (); +struct vcpu_tdx *tdx =to_tdx (vcpu); + +if (KVM_BUG_ON (!vcpu, kvm)) +return -EOPNOTSUPP ; + +/* Request to map as 2MB leaf for the whole 2MB range */ + tdx->violation_gfn_start =gfn_round_for_level (gfn, level);
Quoted 8 lines
arch/x86/kvm/vmx/tdx.c int tdx_sept_split_private_spt(struct kvm *kvm, gfn_t gfn, enum pg_level level, · line 1865
Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4
-0+ tdx->violation_gfn_end = tdx->violation_gfn_start +KVM_PAGES_PER_HPAGE (level); + tdx->violation_request_level = level; + +return -EBUSY ;This is too hacky the way it infers so much from
mmu_lock_shared. Since guests shouldn't be doing this, what about just doingkvm_vm_dead(), with a littlepr_warn()? Maybe even just do it inset_external_spte_present()and declare it
There's a valid case [1] besides double accept to trigger demotion in the fault path. Kirill believed we need to support that case [2].
KVM MMU core can't tell if the demotion is caused by double accept or not.
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/6vdj4mfxlyvypn743klxq5twda66tkugwzljdt275rug2gmwwl@zdziylxpre6y/
Quoted 34 lines
the rule for external page tables. It can shrink this patch significantly, for no expected user impact.
Quoted 28 lines
arch/x86/kvm/vmx/tdx.c +2
-0+ } + ret =tdx_sept_zap_private_spte (kvm, gfn, level, page);if (ret <=0 )return ret;arch/x86/kvm/vmx/x86_ops.h +3
-2@@ -159,7 +159,7 @@ int tdx_sept_set_private_spte(struct kvm *kvm, gfn_t gfn,int tdx_sept_remove_private_spte (struct kvm *kvm,gfn_t gfn,enum pg_level level,kvm_pfn_t pfn);int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, -void *private_spt); +void *private_spt,bool mmu_lock_shared);void tdx_flush_tlb_current (struct kvm_vcpu *vcpu);void tdx_flush_tlb_all (struct kvm_vcpu *vcpu);@@ -228,7 +228,8 @@ static inline int tdx_sept_remove_private_spte(struct kvm *kvm, gfn_t gfn,static inline int tdx_sept_split_private_spt (struct kvm *kvm,gfn_t gfn,enum pg_level level, -void *private_spt) +void *private_spt, +bool mmu_lock_shared) {return -EOPNOTSUPP ; }