Add a new internal flag in the top half of memslot->flags to track when a guest_memfd-backed slot supports shared memory, which is reserved for internal use in KVM. This avoids repeatedly checking the underlying guest_memfd file for shared memory support, which requires taking a reference on the file. Reviewed-by: Gavin Shan <gshan@xxxxxxxxxx> Acked-by: David Hildenbrand <david@xxxxxxxxxx> Suggested-by: David Hildenbrand <david@xxxxxxxxxx> Signed-off-by: Fuad Tabba <tabba@xxxxxxxxxx> --- include/linux/kvm_host.h | 11 ++++++++++- virt/kvm/guest_memfd.c | 2 ++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h index 6b63556ca150..bba7d2c14177 100644 --- a/include/linux/kvm_host.h +++ b/include/linux/kvm_host.h @@ -54,7 +54,8 @@ * used in kvm, other bits are visible for userspace which are defined in * include/uapi/linux/kvm.h. */ -#define KVM_MEMSLOT_INVALID (1UL << 16) +#define KVM_MEMSLOT_INVALID (1UL << 16) +#define KVM_MEMSLOT_SUPPORTS_GMEM_SHARED (1UL << 17) /* * Bit 63 of the memslot generation number is an "update in-progress flag", @@ -2525,6 +2526,14 @@ static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu, vcpu->run->memory_fault.flags |= KVM_MEMORY_EXIT_FLAG_PRIVATE; } +static inline bool kvm_gmem_memslot_supports_shared(const struct kvm_memory_slot *slot) +{ + if (!IS_ENABLED(CONFIG_KVM_GMEM_SHARED_MEM)) + return false; + + return slot->flags & KVM_MEMSLOT_SUPPORTS_GMEM_SHARED; +} + #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES static inline unsigned long kvm_get_memory_attributes(struct kvm *kvm, gfn_t gfn) { diff --git a/virt/kvm/guest_memfd.c b/virt/kvm/guest_memfd.c index 06616b6b493b..73b0aa2bc45f 100644 --- a/virt/kvm/guest_memfd.c +++ b/virt/kvm/guest_memfd.c @@ -592,6 +592,8 @@ int kvm_gmem_bind(struct kvm *kvm, struct kvm_memory_slot *slot, */ WRITE_ONCE(slot->gmem.file, file); slot->gmem.pgoff = start; + if (kvm_gmem_supports_shared(inode)) + slot->flags |= KVM_MEMSLOT_SUPPORTS_GMEM_SHARED; xa_store_range(&gmem->bindings, start, end - 1, slot, GFP_KERNEL); filemap_invalidate_unlock(inode->i_mapping); -- 2.50.0.rc0.642.g800a2b2222-goog