[RFC PATCH 2/8] kvm: use slowpath in gfn_to_hva_cache if memory is private

Patrick Roy
2024-07-09T13:21:02Z

Currently, KVM uses gfn_to_hva_caches to cache gfn->memslot->userspace
host virtual address (uhva) translations. If a gfn is backed by
guest_memfd however, there is no uhva-equivalent item we could possible
cache, since accesses go through a file descriptor instead of a VMA.
Thus, we effectively disable gfn_to_hva_caches in the case where gfns
are gmem-backed, and instead do a gfn->pfn translation on the fly by
calling `kvm_{read,write}_guest` inside `kvm_{read,write}_guest_cached`.

Signed-off-by: Patrick Roy <roypat@amazon.co.uk>
---
virt/kvm/kvm_main.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
index b3b3de70a4df..4357f7cdf040 100644
--- a/virt/kvm/kvm_main.c
+++ b/virt/kvm/kvm_main.c
@@ -3603,7 +3603,7 @@ int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
if (kvm_is_error_hva(ghc->hva))
return -EFAULT;

- if (unlikely(!ghc->memslot))
+ if (unlikely(!ghc->memslot || kvm_mem_is_private(kvm, gpa_to_gfn(gpa))))
return kvm_write_guest(kvm, gpa, data, len);

r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
@@ -3641,7 +3641,7 @@ int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
if (kvm_is_error_hva(ghc->hva))
return -EFAULT;

- if (unlikely(!ghc->memslot))
+ if (unlikely(!ghc->memslot || kvm_mem_is_private(kvm, gpa_to_gfn(gpa))))
return kvm_read_guest(kvm, gpa, data, len);

r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
--
2.45.2