1G page support for guest_memfd
Subsystems (22)
v2 cover 1G page support for guest_memfd
Hello,
This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.
This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].
For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2
This patchset can be divided into two sections:
(a) Patches from the beginning up to and including "KVM: selftests:
Update script to map shared memory from guest_memfd" are a modified version of "conversion support for guest_memfd", which Fuad is managing [2].
(b) Patches after "KVM: selftests: Update script to map shared memory from guest_memfd" till the end are patches that actually bring in 1G page support for guest_memfd.
These are the significant differences between (a) and [2]:
+ [2] uses an xarray to track sharability, but I used a maple tree because for 1G pages, iterating pagewise to update shareability was prohibitively slow even for testing. I was choosing from among multi-index xarrays, interval trees and maple trees [3], and picked maple trees because
+ Maple trees were easier to figure out since I didn't have to compute the correct multi-index order and handle edge cases if the converted range wasn't a neat power of 2.
+ Maple trees were easier to figure out as compared to updating parts of a multi-index xarray.
+ Maple trees had an easier API to use than interval trees.
+ [2] doesn't yet have a conversion ioctl, but I needed it to test 1G support end-to-end.
+ (a) Removes guest_memfd from participating in LRU, which I needed, to get conversion selftests to work as expected, since participation in LRU was causing some unexpected refcounts on folios which was blocking conversions.
I am sending (a) in emails as well, as opposed to just leaving it on GitHub, so that we can discuss by commenting inline on emails. If you'd like to just look at 1G page support, here are some key takeaways from the first section (a):
+ If GUEST_MEMFD_FLAG_SUPPORT_SHARED is requested during guest_memfd creation, guest_memfd will
+ Track shareability (whether an index in the inode is guest-only or if the host is allowed to fault memory at a given index).
+ Always be used for guest faults - specifically, kvm_gmem_get_pfn() will be used to provide pages for the guest.
+ Always be used by KVM to check private/shared status of a gfn.
+ guest_memfd now has conversion ioctls, allowing conversion to private/shared
+ Conversion can fail if there are unexpected refcounts on any folios in the range.
Focusing on (b) 1G page support, here's an overview:
1. A bunch of refactoring patches for HugeTLB that isolates the allocation of a HugeTLB folio from other HugeTLB concepts such as VMA-level reservations, and HugeTLBfs-specific concepts, such as where memory policy is stored in the VMA, or where the subpool is stored on the inode.
2. A few patches that add a guestmem_hugetlb allocator within mm/. The guestmem_hugetlb allocator is a wrapper around HugeTLB to modularize the memory management functions, and to cleanly handle cleanup, so that folio cleanup can happen after the guest_memfd inode (and even KVM) goes away.
3. Some updates to guest_memfd to use the guestmem_hugetlb allocator.
4. Selftests for 1G page support.
Here are some remaining issues/TODOs:
1. Memory error handling such as machine check errors have not been implemented.
2. I've not looked into preparedness of pages, only zeroing has been considered.
3. When allocating HugeTLB pages, if two threads allocate indices mapping to the same huge page, the utilization in guest_memfd inode's subpool may momentarily go over the subpool limit (the requested size of the inode at guest_memfd creation time), causing one of the two threads to get -ENOMEM. Suggestions to solve this are appreciated!
4. max_usage_in_bytes statistic (cgroups v1) for guest_memfd HugeTLB pages should be correct but needs testing and could be wrong.
5. memcg charging (charge_memcg()) for cgroups v2 for guest_memfd HugeTLB pages after splitting should be correct but needs testing and could be wrong.
6. Page cache accounting: When a hugetlb page is split, guest_memfd will incur page count in both NR_HUGETLB (counted at hugetlb allocation time) and NR_FILE_PAGES stats (counted when split pages are added to the filemap). Is this aligned with what people expect?
Here are some optimizations that could be explored in future series:
1. Pages could be split from 1G to 2M first and only split to 4K if necessary.
2. Zeroing could be skipped for Coco VMs if hardware already zeroes the pages.
Here's RFC v1 [4] if you're interested in the motivation behind choosing HugeTLB, or the history of this patch series.
[1] https://lore.kernel.org/all/[email protected]/T/
[2] https://lore.kernel.org/all/[email protected]/T/
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/T/
---
Ackerley Tng (49):
KVM: guest_memfd: Make guest mem use guest mem inodes instead of
anonymous inodes
KVM: guest_memfd: Introduce and use shareability to guard faulting
KVM: selftests: Update guest_memfd_test for INIT_PRIVATE flag
KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
KVM: guest_memfd: Skip LRU for guest_memfd folios
KVM: Query guest_memfd for private/shared status
KVM: guest_memfd: Add CAP KVM_CAP_GMEM_CONVERSION
KVM: selftests: Test flag validity after guest_memfd supports
conversions
KVM: selftests: Test faulting with respect to
GUEST_MEMFD_FLAG_INIT_PRIVATE
KVM: selftests: Refactor vm_mem_add to be more flexible
KVM: selftests: Allow cleanup of ucall_pool from host
KVM: selftests: Test conversion flows for guest_memfd
KVM: selftests: Add script to exercise private_mem_conversions_test
KVM: selftests: Update private_mem_conversions_test to mmap
guest_memfd
KVM: selftests: Update script to map shared memory from guest_memfd
mm: hugetlb: Consolidate interpretation of gbl_chg within
alloc_hugetlb_folio()
mm: hugetlb: Cleanup interpretation of gbl_chg in
alloc_hugetlb_folio()
mm: hugetlb: Cleanup interpretation of map_chg_state within
alloc_hugetlb_folio()
mm: hugetlb: Rename alloc_surplus_hugetlb_folio
mm: mempolicy: Refactor out policy_node_nodemask()
mm: hugetlb: Inline huge_node() into callers
mm: hugetlb: Refactor hugetlb allocation functions
mm: hugetlb: Refactor out hugetlb_alloc_folio()
mm: hugetlb: Add option to create new subpool without using surplus
mm: truncate: Expose preparation steps for truncate_inode_pages_final
mm: hugetlb: Expose hugetlb_subpool_{get,put}_pages()
mm: Introduce guestmem_hugetlb to support folio_put() handling of
guestmem pages
mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
mm: truncate: Expose truncate_inode_folio()
KVM: x86: Set disallow_lpage on base_gfn and guest_memfd pgoff
misalignment
KVM: guest_memfd: Support guestmem_hugetlb as custom allocator
KVM: guest_memfd: Allocate and truncate from custom allocator
mm: hugetlb: Add functions to add/delete folio from hugetlb lists
mm: guestmem_hugetlb: Add support for splitting and merging pages
mm: Convert split_folio() macro to function
KVM: guest_memfd: Split allocator pages for guest_memfd use
KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)
KVM: guest_memfd: Update kvm_gmem_mapping_order to account for page
status
KVM: Add CAP to indicate support for HugeTLB as custom allocator
KVM: selftests: Add basic selftests for hugetlb-backed guest_memfd
KVM: selftests: Update conversion flows test for HugeTLB
KVM: selftests: Test truncation paths of guest_memfd
KVM: selftests: Test allocation and conversion of subfolios
KVM: selftests: Test that guest_memfd usage is reported via hugetlb
KVM: selftests: Support various types of backing sources for private
memory
KVM: selftests: Update test for various private memory backing source
types
KVM: selftests: Update private_mem_conversions_test.sh to test with
HugeTLB pages
KVM: selftests: Add script to test HugeTLB statistics
KVM: selftests: Test guest_memfd for accuracy of st_blocks
Elliot Berman (1):
filemap: Pass address_space mapping to ->free_folio()
Fuad Tabba (1):
mm: Consolidate freeing of typed folios on final folio_put()
Documentation/filesystems/locking.rst | 2 +- Documentation/filesystems/vfs.rst | 15 +- Documentation/virt/kvm/api.rst | 5 + arch/arm64/include/asm/kvm_host.h | 5 - arch/x86/include/asm/kvm_host.h | 10 - arch/x86/kvm/x86.c | 53 +- fs/hugetlbfs/inode.c | 2 +- fs/nfs/dir.c | 9 +- fs/orangefs/inode.c | 3 +- include/linux/fs.h | 2 +- include/linux/guestmem.h | 23 + include/linux/huge_mm.h | 6 +- include/linux/hugetlb.h | 19 +- include/linux/kvm_host.h | 32 +- include/linux/mempolicy.h | 11 +- include/linux/mm.h | 2 + include/linux/page-flags.h | 32 + include/uapi/linux/guestmem.h | 29 + include/uapi/linux/kvm.h | 16 + include/uapi/linux/magic.h | 1 + mm/Kconfig | 13 + mm/Makefile | 1 + mm/debug.c | 1 + mm/filemap.c | 12 +- mm/guestmem_hugetlb.c | 512 +++++ mm/guestmem_hugetlb.h | 9 + mm/hugetlb.c | 488 ++--- mm/internal.h | 1 - mm/memcontrol.c | 2 + mm/memory.c | 1 + mm/mempolicy.c | 44 +- mm/secretmem.c | 3 +- mm/swap.c | 32 +- mm/truncate.c | 27 +- mm/vmscan.c | 4 +- tools/testing/selftests/kvm/Makefile.kvm | 2 + .../kvm/guest_memfd_conversions_test.c | 797 ++++++++ .../kvm/guest_memfd_hugetlb_reporting_test.c | 384 ++++ ...uest_memfd_provide_hugetlb_cgroup_mount.sh | 36 + .../testing/selftests/kvm/guest_memfd_test.c | 293 ++- ...memfd_wrap_test_check_hugetlb_reporting.sh | 95 + .../testing/selftests/kvm/include/kvm_util.h | 104 +- .../testing/selftests/kvm/include/test_util.h | 20 +- .../selftests/kvm/include/ucall_common.h | 1 + tools/testing/selftests/kvm/lib/kvm_util.c | 465 +++-- tools/testing/selftests/kvm/lib/test_util.c | 102 + .../testing/selftests/kvm/lib/ucall_common.c | 16 +- .../kvm/x86/private_mem_conversions_test.c | 195 +- .../kvm/x86/private_mem_conversions_test.sh | 100 + virt/kvm/Kconfig | 5 + virt/kvm/guest_memfd.c | 1655 ++++++++++++++++- virt/kvm/kvm_main.c | 14 +- virt/kvm/kvm_mm.h | 9 +- 53 files changed, 5080 insertions(+), 640 deletions(-) create mode 100644 include/linux/guestmem.h create mode 100644 include/uapi/linux/guestmem.h create mode 100644 mm/guestmem_hugetlb.c create mode 100644 mm/guestmem_hugetlb.h create mode 100644 tools/testing/selftests/kvm/guest_memfd_conversions_test.c create mode 100644 tools/testing/selftests/kvm/guest_memfd_hugetlb_reporting_test.c create mode 100755 tools/testing/selftests/kvm/guest_memfd_provide_hugetlb_cgroup_mount.sh create mode 100755 tools/testing/selftests/kvm/guest_memfd_wrap_test_check_hugetlb_reporting.sh create mode 100755 tools/testing/selftests/kvm/x86/private_mem_conversions_test.sh
--
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 1/51 KVM: guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodes
guest_memfd's inode represents memory the guest_memfd is providing. guest_memfd's file represents a struct kvm's view of that memory.
Using a custom inode allows customization of the inode teardown process via callbacks. For example, ->evict_inode() allows customization of the truncation process on file close, and ->destroy_inode() and ->free_inode() allow customization of the inode freeing process.
Customizing the truncation process allows flexibility in management of guest_memfd memory and customization of the inode freeing process allows proper cleanup of memory metadata stored on the inode.
Memory metadata is more appropriately stored on the inode (as opposed to the file), since the metadata is for the memory and is not unique to a specific binding and struct kvm.
Change-Id: I5c23bce8fefe492b40b8042ece1e81448752da99
--- include/uapi/linux/magic.h | 1 + virt/kvm/guest_memfd.c | 134 +++++++++++++++++++++++++++++++------ virt/kvm/kvm_main.c | 7 +- virt/kvm/kvm_mm.h | 9 ++- 4 files changed, 125 insertions(+), 26 deletions(-)
include/uapi/linux/magic.h +1 -0
@@ -103,5 +103,6 @@#define DEVMEM_MAGIC 0x454d444d/* "DMEM" */ #define SECRETMEM_MAGIC 0x5345434d/* "SECM" */ #define PID_FS_MAGIC 0x50494446/* "PIDF" */ +#define GUEST_MEMFD_MAGIC 0x474d454d/* "GMEM" */ #endif /* __LINUX_MAGIC_H__ */
virt/kvm/guest_memfd.c +112 -22
176 lines not on this page · raw message
virt/kvm/kvm_main.c +6 -1
@@ -6419,7 +6419,9 @@ int kvm_init(unsigned vcpu_size, unsigned vcpu_align, struct module *module)if (WARN_ON_ONCE (r)) goto err_vfio; -kvm_gmem_init (module); + r =kvm_gmem_init (module); +if (r) + goto err_gmem; r =kvm_init_virtualization ();if (r)
@@ -6440,6 +6442,8 @@ int kvm_init(unsigned vcpu_size, unsigned vcpu_align, struct module *module) err_register:kvm_uninit_virtualization (); err_virt: +kvm_gmem_exit (); +err_gmem:kvm_vfio_ops_exit (); err_vfio:kvm_async_pf_deinit ();
@@ -6471,6 +6475,7 @@ void kvm_exit(void)for_each_possible_cpu (cpu)free_cpumask_var (per_cpu (cpu_kick_mask, cpu));kmem_cache_destroy (kvm_vcpu_cache); +kvm_gmem_exit ();kvm_vfio_ops_exit ();kvm_async_pf_deinit ();kvm_irqfd_exit ();
virt/kvm/kvm_mm.h +6 -3
@@ -68,17 +68,20 @@ static inline void gfn_to_pfn_cache_invalidate_start(struct kvm *kvm,#endif /* HAVE_KVM_PFNCACHE */ #ifdef CONFIG_KVM_GMEM -void kvm_gmem_init (struct module *module); +int kvm_gmem_init (struct module *module); +void kvm_gmem_exit (void );int kvm_gmem_create (struct kvm *kvm,struct kvm_create_guest_memfd *args);int kvm_gmem_bind (struct kvm *kvm,struct kvm_memory_slot *slot,unsigned int fd,loff_t offset);void kvm_gmem_unbind (struct kvm_memory_slot *slot);#else -static inline void kvm_gmem_init (struct module *module) +static inline int kvm_gmem_init (struct module *module) { - +return 0 ; } +static inline void kvm_gmem_exit (void ) {}; +static inline int kvm_gmem_bind (struct kvm *kvm,struct kvm_memory_slot *slot,unsigned int fd,loff_t offset)
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 2/51 KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ackerley TngTrack guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.
Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.
KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.
Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.
--- Documentation/virt/kvm/api.rst | 5 ++ include/uapi/linux/kvm.h | 2 + virt/kvm/guest_memfd.c | 124 ++++++++++++++++++++++++++++++++- 3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +5 -0
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr. The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs. This is validated when the guest_memfd instance is bound to the VM. +If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field +supports GUEST_MEMFD_FLAG_INIT_PRIVATE. Setting GUEST_MEMFD_FLAG_INIT_PRIVATE +will initialize the memory for the guest_memfd as guest-only and not faultable +by the host. + See KVM_SET_USER_MEMORY_REGION2 for additional details. 4.143 KVM_PRE_FAULT_MEMORY
include/uapi/linux/kvm.h +2 -0
@@ -1567,7 +1567,9 @@ struct kvm_memory_attributes {#define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3)#define KVM_CREATE_GUEST_MEMFD _IOWR(KVMIO, 0xd4, struct kvm_create_guest_memfd) +#define GUEST_MEMFD_FLAG_SUPPORT_SHARED (1UL << 0) +#define GUEST_MEMFD_FLAG_INIT_PRIVATE (1UL << 1)struct kvm_create_guest_memfd {__u64 size;
virt/kvm/guest_memfd.c +122 -2
193 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 3/51 KVM: selftests: Update guest_memfd_test for INIT_PRIVATE flag
In reply to Ackerley TngTest that GUEST_MEMFD_FLAG_INIT_PRIVATE is only valid when GUEST_MEMFD_FLAG_SUPPORT_SHARED is set.
--- .../testing/selftests/kvm/guest_memfd_test.c | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-)
tools/testing/selftests/kvm/guest_memfd_test.c +24 -12
@@ -401,13 +401,31 @@ static void test_with_type(unsigned long vm_type, uint64_t guest_memfd_flags,kvm_vm_release (vm); } +static void test_vm_with_gmem_flag (struct kvm_vm *vm,uint64_t flag, +bool expect_valid) +{ +size_t page_size =getpagesize (); +int fd; + + fd =__vm_create_guest_memfd (vm, page_size, flag); + +if (expect_valid) { +TEST_ASSERT (fd >0 , +"guest_memfd() with flag '0x%lx' should be valid" , + flag); +close (fd); + }else { +TEST_ASSERT (fd ==-1 && errno ==EINVAL , +"guest_memfd() with flag '0x%lx' should fail with EINVAL" , + flag); + } +} +static void test_vm_type_gmem_flag_validity (unsigned long vm_type,uint64_t expected_valid_flags) { -size_t page_size =getpagesize ();struct kvm_vm *vm;uint64_t flag =0 ; -int fd;if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type)))return ;
@@ -415,17 +433,11 @@ static void test_vm_type_gmem_flag_validity(unsigned long vm_type, vm =vm_create_barebones_type (vm_type);for (flag =BIT (0 ); flag; flag <<=1 ) { - fd =__vm_create_guest_memfd (vm, page_size, flag); +test_vm_with_gmem_flag (vm, flag, flag & expected_valid_flags); -if (flag & expected_valid_flags) { -TEST_ASSERT (fd >0 , -"guest_memfd() with flag '0x%lx' should be valid" , - flag); -close (fd); - }else { -TEST_ASSERT (fd ==-1 && errno ==EINVAL , -"guest_memfd() with flag '0x%lx' should fail with EINVAL" , - flag); +if (flag ==GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { +test_vm_with_gmem_flag ( + vm, flag |GUEST_MEMFD_FLAG_INIT_PRIVATE , true); } }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 4/51 KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Ackerley TngThe two new guest_memfd ioctls KVM_GMEM_CONVERT_SHARED and KVM_GMEM_CONVERT_PRIVATE convert the requested memory ranges to shared and private respectively.
A guest_memfd ioctl is used because shareability is a property of the memory, and this property should be modifiable independently of the attached struct kvm. This allows shareability to be modified even if the memory is not yet bound using memslots.
For shared to private conversions, if refcounts on any of the folios within the range are elevated, fail the conversion with -EAGAIN.
At the point of shared to private conversion, all folios in range are also unmapped. The filemap_invalidate_lock() is held, so no faulting can occur. Hence, from that point on, only transient refcounts can be taken on the folios associated with that guest_memfd.
Hence, it is safe to do the conversion from shared to private.
After conversion is complete, refcounts may become elevated, but that is fine since users of transient refcounts don't actually access memory.
For private to shared conversions, there are no refcount checks. any transient refcounts are expected to drop their refcounts soon. The conversion process will spin waiting for these transient refcounts to go away.
Change-Id: I3546aaf6c1b795de6dc9ba09e816b64934221918
--- include/uapi/linux/kvm.h | 11 ++ virt/kvm/guest_memfd.c | 357 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 366 insertions(+), 2 deletions(-)
include/uapi/linux/kvm.h +11 -0
@@ -1577,6 +1577,17 @@ struct kvm_create_guest_memfd {__u64 reserved[6 ]; }; +#define KVM_GMEM_IO 0xAF +#define KVM_GMEM_CONVERT_SHARED _IOWR(KVM_GMEM_IO, 0x41, struct kvm_gmem_convert) +#define KVM_GMEM_CONVERT_PRIVATE _IOWR(KVM_GMEM_IO, 0x42, struct kvm_gmem_convert) + +struct kvm_gmem_convert { +__u64 offset; +__u64 size; +__u64 error_offset; +__u64 reserved[5 ]; +}; +#define KVM_PRE_FAULT_MEMORY _IOWR(KVMIO, 0xd5, struct kvm_pre_fault_memory)struct kvm_pre_fault_memory {
virt/kvm/guest_memfd.c +355 -2
393 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 5/51 KVM: guest_memfd: Skip LRU for guest_memfd folios
In reply to Ackerley Tngfilemap_add_folio(), called from filemap_grab_folio(), adds the folio onto some LRU list, which is not necessary for guest_memfd since guest_memfd folios don't participate in any swapping.
This patch reimplements part of filemap_add_folio() to avoid adding allocated guest_memfd folios to the filemap.
With shared to private conversions dependent on refcounts, avoiding usage of LRU ensures that LRU lists no longer take any refcounts on guest_memfd folios and significantly reduces the chance of elevated refcounts during conversion.
--- mm/filemap.c | 1 + mm/memcontrol.c | 2 + virt/kvm/guest_memfd.c | 91 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 86 insertions(+), 8 deletions(-)
mm/filemap.c +1 -0
@@ -954,6 +954,7 @@ noinline int __filemap_add_folio(struct address_space *mapping,return xas_error (&xas); }ALLOW_ERROR_INJECTION (__filemap_add_folio,ERRNO ); +EXPORT_SYMBOL_GPL (__filemap_add_folio);int filemap_add_folio (struct address_space *mapping,struct folio *folio,pgoff_t index,gfp_t gfp)
mm/memcontrol.c +2 -0
@@ -4611,6 +4611,7 @@ int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)return ret; } +EXPORT_SYMBOL_GPL (__mem_cgroup_charge);/** * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio
@@ -4785,6 +4786,7 @@ void __mem_cgroup_uncharge(struct folio *folio)uncharge_folio (folio, &ug);uncharge_batch (&ug); } +EXPORT_SYMBOL_GPL (__mem_cgroup_uncharge);void __mem_cgroup_uncharge_folios (struct folio_batch *folios) {
virt/kvm/guest_memfd.c +83 -8
120 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 6/51 KVM: Query guest_memfd for private/shared status
In reply to Ackerley TngQuery guest_memfd for private/shared status if those guest_memfds track private/shared status.
With this patch, Coco VMs can use guest_memfd for both shared and private memory. If Coco VMs choose to use guest_memfd for both shared and private memory, by creating guest_memfd with the GUEST_MEMFD_FLAG_SUPPORT_SHARED flag, guest_memfd will be used to provide the private/shared status of the memory, instead of kvm->mem_attr_array.
--- include/linux/kvm_host.h | 19 ++++++++++++------- virt/kvm/guest_memfd.c | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-)
include/linux/kvm_host.h +12 -7
@@ -2508,12 +2508,22 @@ static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu, }#ifdef CONFIG_KVM_GMEM_SHARED_MEM +bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot); +bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn); +#else +static inline bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot) {return false; } + +static inline bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn) +{ +return false; +} +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
@@ -2544,13 +2554,8 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)return false; slot =gfn_to_memslot (kvm, gfn); -if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) { -/* -* For now, memslots only support in-place shared memory if the -* host is allowed to mmap memory (i.e., non-Coco VMs). -*/ -return false; - } +if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) +return kvm_gmem_is_private (slot, gfn);return kvm_get_memory_attributes (kvm, gfn) &KVM_MEMORY_ATTRIBUTE_PRIVATE ; }
virt/kvm/guest_memfd.c +22 -0
@@ -865,6 +865,28 @@ bool kvm_gmem_memslot_supports_shared(const struct kvm_memory_slot *slot) }EXPORT_SYMBOL_GPL (kvm_gmem_memslot_supports_shared); +bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn) +{ +struct inode *inode; +struct file *file; +pgoff_t index; +bool ret; + + file =kvm_gmem_get_file (slot); +if (!file) +return false; + + index =kvm_gmem_get_index (slot, gfn); + inode =file_inode (file); + +filemap_invalidate_lock_shared (inode->i_mapping); + ret =kvm_gmem_shareability_get (inode, index) ==SHAREABILITY_GUEST ; +filemap_invalidate_unlock_shared (inode->i_mapping); + +fput (file); +return ret; +} +#else #define kvm_gmem_mmap NULL#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 7/51 KVM: guest_memfd: Add CAP KVM_CAP_GMEM_CONVERSION
In reply to Ackerley TngKVM_CAP_GMEM_CONVERSION indicates that guest_memfd supports conversion.
With this patch, as long as guest_memfd supports shared memory, it also supports conversion.
With conversion support comes tracking of private/shared memory within guest_memfd, hence now all VM types support shared memory in guest_memfd.
Before this patch, Coco VMs did not support shared memory because that would allow private memory to be accessible to the host. Coco VMs now support shared memory because with private/shared status tracked in guest_memfd, private memory will not be allowed to be mapped into the host.
--- arch/arm64/include/asm/kvm_host.h | 5 ----- arch/x86/include/asm/kvm_host.h | 10 ---------- include/linux/kvm_host.h | 13 ------------- include/uapi/linux/kvm.h | 1 + virt/kvm/guest_memfd.c | 12 ++++-------- virt/kvm/kvm_main.c | 3 ++- 6 files changed, 7 insertions(+), 37 deletions(-)
arch/arm64/include/asm/kvm_host.h +0 -5
@@ -1598,9 +1598,4 @@ static inline bool kvm_arch_supports_gmem(struct kvm *kvm) return IS_ENABLED(CONFIG_KVM_GMEM); } -static inline bool kvm_arch_vm_supports_gmem_shared_mem (struct kvm *kvm) -{ -return IS_ENABLED (CONFIG_KVM_GMEM_SHARED_MEM ); -} -#endif /* __ARM64_KVM_HOST_H__ */
arch/x86/include/asm/kvm_host.h +0 -10
@@ -2255,18 +2255,8 @@ void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,#ifdef CONFIG_KVM_GMEM #define kvm_arch_supports_gmem (kvm) ((kvm)->arch.supports_gmem) - -/* -* CoCo VMs with hardware support that use guest_memfd only for backing private -* memory, e.g., TDX, cannot use guest_memfd with userspace mapping enabled. -*/ -#define kvm_arch_vm_supports_gmem_shared_mem (kvm) \ - (IS_ENABLED(CONFIG_KVM_GMEM_SHARED_MEM) && \ - ((kvm)->arch.vm_type == KVM_X86_SW_PROTECTED_VM || \ - (kvm)->arch.vm_type == KVM_X86_DEFAULT_VM))#else #define kvm_arch_supports_gmem (kvm) false -#define kvm_arch_vm_supports_gmem_shared_mem (kvm) false#endif #define kvm_arch_has_readonly_mem (kvm) (!(kvm)->arch.has_protected_state)
include/linux/kvm_host.h +0 -13
@@ -729,19 +729,6 @@ static inline bool kvm_arch_supports_gmem(struct kvm *kvm) }#endif -/* -* Returns true if this VM supports shared mem in guest_memfd. -* -* Arch code must define kvm_arch_vm_supports_gmem_shared_mem if support for -* guest_memfd is enabled. -*/ -#if !defined(kvm_arch_vm_supports_gmem_shared_mem) && !IS_ENABLED (CONFIG_KVM_GMEM ) -static inline bool kvm_arch_vm_supports_gmem_shared_mem (struct kvm *kvm) -{ -return false; -} -#endif -#ifndef kvm_arch_has_readonly_memstatic inline bool kvm_arch_has_readonly_mem (struct kvm *kvm) {
include/uapi/linux/kvm.h +1 -0
@@ -931,6 +931,7 @@ struct kvm_enable_cap {#define KVM_CAP_X86_GUEST_MODE 238#define KVM_CAP_ARM_WRITABLE_IMP_ID_REGS 239#define KVM_CAP_GMEM_SHARED_MEM 240 +#define KVM_CAP_GMEM_CONVERSION 241struct kvm_irq_routing_irqchip {__u32 irqchip;
virt/kvm/guest_memfd.c +4 -8
@@ -1216,7 +1216,7 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)u64 flags = args->flags;u64 valid_flags =0 ; -if (kvm_arch_vm_supports_gmem_shared_mem (kvm)) +if (IS_ENABLED (CONFIG_KVM_GMEM_SHARED_MEM )) valid_flags |=GUEST_MEMFD_FLAG_SUPPORT_SHARED ;if (flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED )
@@ -1286,13 +1286,9 @@ int kvm_gmem_bind(struct kvm *kvm, struct kvm_memory_slot *slot, offset + size > i_size_read(inode)) goto err; -if (kvm_gmem_supports_shared (inode)) { -if (!kvm_arch_vm_supports_gmem_shared_mem (kvm)) - goto err; - -if (slot->userspace_addr && - !kvm_gmem_is_same_range (kvm, slot, file, offset)) - goto err; +if (kvm_gmem_supports_shared (inode) && slot->userspace_addr && + !kvm_gmem_is_same_range (kvm, slot, file, offset)) { + goto err; }filemap_invalidate_lock (inode->i_mapping);
virt/kvm/kvm_main.c +2 -1
@@ -4843,7 +4843,8 @@ static int kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)#endif #ifdef CONFIG_KVM_GMEM_SHARED_MEM case KVM_CAP_GMEM_SHARED_MEM : -return !kvm ||kvm_arch_vm_supports_gmem_shared_mem (kvm); +case KVM_CAP_GMEM_CONVERSION : +return true;#endif default :break ;
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 8/51 KVM: selftests: Test flag validity after guest_memfd supports conversions
In reply to Ackerley TngBefore guest_memfd supports conversions, Coco VMs must not allow GUEST_MEMFD_FLAG_SUPPORT_SHARED.
Because this is a platform stability requirement for hosts supporting Coco VMs, this is an important test to retain.
--- .../testing/selftests/kvm/guest_memfd_test.c | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-)
tools/testing/selftests/kvm/guest_memfd_test.c +23 -3
@@ -435,7 +435,8 @@ static void test_vm_type_gmem_flag_validity(unsigned long vm_type,for (flag =BIT (0 ); flag; flag <<=1 ) {test_vm_with_gmem_flag (vm, flag, flag & expected_valid_flags); -if (flag ==GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { +if (flag ==GUEST_MEMFD_FLAG_SUPPORT_SHARED && +kvm_has_cap (KVM_CAP_GMEM_CONVERSION )) {test_vm_with_gmem_flag ( vm, flag |GUEST_MEMFD_FLAG_INIT_PRIVATE , true); }
@@ -444,7 +445,7 @@ static void test_vm_type_gmem_flag_validity(unsigned long vm_type,kvm_vm_release (vm); } -static void test_gmem_flag_validity (void ) +static void test_gmem_flag_validity_without_conversion_cap (void ) {uint64_t non_coco_vm_valid_flags =0 ;
@@ -462,11 +463,30 @@ static void test_gmem_flag_validity(void)#endif } +static void test_gmem_flag_validity (void ) +{ +/* After conversions are supported, all VM types support shared mem. */ +uint64_t valid_flags =GUEST_MEMFD_FLAG_SUPPORT_SHARED ; + +test_vm_type_gmem_flag_validity (VM_TYPE_DEFAULT , valid_flags); + +#ifdef __x86_64__ +test_vm_type_gmem_flag_validity (KVM_X86_SW_PROTECTED_VM , valid_flags); +test_vm_type_gmem_flag_validity (KVM_X86_SEV_VM , valid_flags); +test_vm_type_gmem_flag_validity (KVM_X86_SEV_ES_VM , valid_flags); +test_vm_type_gmem_flag_validity (KVM_X86_SNP_VM , valid_flags); +test_vm_type_gmem_flag_validity (KVM_X86_TDX_VM , valid_flags); +#endif +} +int main (int argc,char *argv[]) {TEST_REQUIRE (kvm_has_cap (KVM_CAP_GUEST_MEMFD )); -test_gmem_flag_validity (); +if (kvm_has_cap (KVM_CAP_GMEM_CONVERSION )) +test_gmem_flag_validity (); +else +test_gmem_flag_validity_without_conversion_cap ();test_with_type (VM_TYPE_DEFAULT ,0 , false);if (kvm_has_cap (KVM_CAP_GMEM_SHARED_MEM )) {
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 9/51 KVM: selftests: Test faulting with respect to GUEST_MEMFD_FLAG_INIT_PRIVATE
In reply to Ackerley TngTest that faulting is denied when guest_memfd's shareability is initialized as private with GUEST_MEMFD_FLAG_INIT_PRIVATE and allowed if the flag is not specified.
Change-Id: Id93d4683b36fc5a9c924458d26f0525baed26435
--- .../testing/selftests/kvm/guest_memfd_test.c | 112 +++++++++++++++--- 1 file changed, 97 insertions(+), 15 deletions(-)
tools/testing/selftests/kvm/guest_memfd_test.c +97 -15
@@ -16,6 +16,7 @@#include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> +#include <sys/wait.h> #include "kvm_util.h" #include "test_util.h"
@@ -34,7 +35,7 @@ static void test_file_read_write(int fd) "pwrite on a guest_mem fd should fail"); } -static void test_mmap_allowed (int fd,size_t page_size,size_t total_size) +static void test_faulting_allowed (int fd,size_t page_size,size_t total_size) {const char val =0xaa ;char *mem;
@@ -65,6 +66,53 @@ static void test_mmap_allowed(int fd, size_t page_size, size_t total_size)TEST_ASSERT (!ret,"munmap should succeed" ); } +static void assert_not_faultable (char *address) +{ +pid_t child_pid; + + child_pid =fork (); +TEST_ASSERT (child_pid !=-1 ,"fork failed" ); + +if (child_pid ==0 ) { + *address ='A' ; +TEST_FAIL ("Child should have exited with a signal" ); + }else { +int status; + +waitpid (child_pid, &status,0 ); + +TEST_ASSERT (WIFSIGNALED (status), +"Child should have exited with a signal" ); +TEST_ASSERT_EQ (WTERMSIG (status),SIGBUS ); + } +} + +static void test_faulting_sigbus (int fd,size_t total_size) +{ +char *mem; +int ret; + + mem =mmap (NULL , total_size,PROT_READ |PROT_WRITE ,MAP_SHARED , fd,0 ); +TEST_ASSERT (mem !=MAP_FAILED ,"mmaping() guest memory should pass." ); + +assert_not_faultable (mem); + + ret =munmap (mem, total_size); +TEST_ASSERT (!ret,"munmap should succeed" ); +} + +static void test_mmap_allowed (int fd,size_t total_size) +{ +char *mem; +int ret; + + mem =mmap (NULL , total_size,PROT_READ |PROT_WRITE ,MAP_SHARED , fd,0 ); +TEST_ASSERT (mem !=MAP_FAILED ,"mmaping() guest memory should pass." ); + + ret =munmap (mem, total_size); +TEST_ASSERT (!ret,"munmap should succeed" ); +} +static void test_mmap_denied (int fd,size_t page_size,size_t total_size) {char *mem;
@@ -364,40 +412,74 @@ static void test_bind_guest_memfd_wrt_userspace_addr(struct kvm_vm *vm)close (fd); } -static void test_with_type (unsigned long vm_type,uint64_t guest_memfd_flags, -bool expect_mmap_allowed) +static void test_guest_memfd_features (struct kvm_vm *vm,size_t page_size, +uint64_t guest_memfd_flags, +bool expect_mmap_allowed, +bool expect_faulting_allowed) { -struct kvm_vm *vm;size_t total_size; -size_t page_size;int fd; -if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type))) -return ; - - page_size =getpagesize (); total_size = page_size *4 ; - vm =vm_create_barebones_type (vm_type); +if (expect_faulting_allowed) +TEST_REQUIRE (expect_mmap_allowed); -test_create_guest_memfd_multiple (vm); -test_bind_guest_memfd_wrt_userspace_addr (vm);test_create_guest_memfd_invalid_sizes (vm, guest_memfd_flags, page_size); fd =vm_create_guest_memfd (vm, total_size, guest_memfd_flags);test_file_read_write (fd); -if (expect_mmap_allowed) -test_mmap_allowed (fd, page_size, total_size); -else +if (expect_mmap_allowed) { +test_mmap_allowed (fd, total_size); + +if (expect_faulting_allowed) +test_faulting_allowed (fd, page_size, total_size); +else +test_faulting_sigbus (fd, total_size); + }else {test_mmap_denied (fd, page_size, total_size); + }test_file_size (fd, page_size, total_size);test_fallocate (fd, page_size, total_size);test_invalid_punch_hole (fd, page_size, total_size);close (fd); +} + +static void test_with_type (unsigned long vm_type,uint64_t guest_memfd_flags, +bool expect_mmap_allowed) +{ +struct kvm_vm *vm; +size_t page_size; + +if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type))) +return ; + + vm =vm_create_barebones_type (vm_type); + +test_create_guest_memfd_multiple (vm); +test_bind_guest_memfd_wrt_userspace_addr (vm); + + page_size =getpagesize (); +if (guest_memfd_flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { +test_guest_memfd_features (vm, page_size, guest_memfd_flags, + expect_mmap_allowed, true); + +if (kvm_has_cap (KVM_CAP_GMEM_CONVERSION )) { +uint64_t flags = guest_memfd_flags | +GUEST_MEMFD_FLAG_INIT_PRIVATE ; + +test_guest_memfd_features (vm, page_size, flags, + expect_mmap_allowed, false); + } + }else { +test_guest_memfd_features (vm, page_size, guest_memfd_flags, + expect_mmap_allowed, false); + } +kvm_vm_release (vm); }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 10/51 KVM: selftests: Refactor vm_mem_add to be more flexible
In reply to Ackerley Tngenum vm_mem_backing_src_type is encoding too many different possibilities on different axes of (1) whether to mmap from an fd, (2) granularity of mapping for THP, (3) size of hugetlb mapping, and has yet to be extended to support guest_memfd.
When guest_memfd supports mmap() and we also want to support testing with mmap()ing from guest_memfd, the number of combinations make enumeration in vm_mem_backing_src_type difficult.
This refactor separates out vm_mem_backing_src_type from userspace_mem_region. For now, vm_mem_backing_src_type remains a possible way for tests to specify, on the command line, the combination of backing memory to test.
vm_mem_add() is now the last place where vm_mem_backing_src_type is interpreted, to
1. Check validity of requested guest_paddr
2. Align mmap_size appropriately based on the mapping's page_size and architecture
3. Install memory appropriately according to mapping's page size
mmap()ing an alias seems to be specific to userfaultfd tests and could be refactored out of struct userspace_mem_region and localized in userfaultfd tests in future.
This paves the way for replacing vm_mem_backing_src_type with multiple command line flags that would specify backing memory more flexibly. Future tests are expected to use vm_mem_region_alloc() to allocate a struct userspace_mem_region, then use more fundamental functions like vm_mem_region_mmap(), vm_mem_region_madvise_thp(), kvm_memfd_create(), vm_create_guest_memfd(), and other functions in vm_mem_add() to flexibly build up struct userspace_mem_region before finally adding the region to the vm with vm_mem_region_add().
--- .../testing/selftests/kvm/include/kvm_util.h | 29 +- .../testing/selftests/kvm/include/test_util.h | 2 + tools/testing/selftests/kvm/lib/kvm_util.c | 429 +++++++++++------- tools/testing/selftests/kvm/lib/test_util.c | 25 + 4 files changed, 328 insertions(+), 157 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +28 -1
@@ -35,11 +35,26 @@ struct userspace_mem_region {struct sparsebit *protected_phy_pages;int fd;off_t offset; -enum vm_mem_backing_src_type backing_src_type; +/* +* host_mem is mmap_start aligned upwards to an address suitable for the +* architecture. In most cases, host_mem and mmap_start are the same, +* except for s390x, where the host address must be aligned to 1M (due +* to PGSTEs). +*/ +#ifdef __s390x__ +#define S390X_HOST_ADDRESS_ALIGNMENT 0x100000 +#endif void *host_mem; +/* host_alias is to mmap_alias as host_mem is to mmap_start */ void *host_alias;void *mmap_start;void *mmap_alias; +/* +* mmap_size is possibly larger than region.memory_size because in some +* cases, host_mem has to be adjusted upwards (see comment for host_mem +* above). In those cases, mmap_size has to be adjusted upwards so that +* enough memory is available in this memslot. +*/ size_t mmap_size;struct rb_node gpa_node;struct rb_node hva_node;
@@ -582,6 +597,18 @@ int __vm_set_user_memory_region2(struct kvm_vm *vm, uint32_t slot, uint32_t flag uint64_t gpa, uint64_t size, void *hva, uint32_t guest_memfd, uint64_t guest_memfd_offset); +struct userspace_mem_region *vm_mem_region_alloc (struct kvm_vm *vm); +void *vm_mem_region_mmap (struct userspace_mem_region *region,size_t length, +int flags,int fd,off_t offset); +void vm_mem_region_install_memory (struct userspace_mem_region *region, +size_t memslot_size,size_t alignment); +void vm_mem_region_madvise_thp (struct userspace_mem_region *region,int advice); +int vm_mem_region_install_guest_memfd (struct userspace_mem_region *region, +int guest_memfd); +void *vm_mem_region_mmap_alias (struct userspace_mem_region *region,int flags, +size_t alignment); +void vm_mem_region_add (struct kvm_vm *vm,struct userspace_mem_region *region); + void vm_userspace_mem_region_add(struct kvm_vm *vm, enum vm_mem_backing_src_type src_type, uint64_t guest_paddr, uint32_t slot, uint64_t npages,
tools/testing/selftests/kvm/include/test_util.h +2 -0
@@ -149,6 +149,8 @@ size_t get_trans_hugepagesz(void);size_t get_def_hugetlb_pagesz (void );const struct vm_mem_backing_src_alias *vm_mem_backing_src_alias (uint32_t i);size_t get_backing_src_pagesz (uint32_t i); +int backing_src_should_madvise (uint32_t i); +int get_backing_src_madvise_advice (uint32_t i);bool is_backing_src_hugetlb (uint32_t i);void backing_src_help (const char *flag);enum vm_mem_backing_src_type parse_backing_src_type (const char *type_name);
tools/testing/selftests/kvm/lib/kvm_util.c +273 -156
479 lines not on this page · raw message
tools/testing/selftests/kvm/lib/test_util.c +25 -0
@@ -308,6 +308,31 @@ size_t get_backing_src_pagesz(uint32_t i) } } +int backing_src_should_madvise (uint32_t i) +{ +switch (i) { +case VM_MEM_SRC_ANONYMOUS : +case VM_MEM_SRC_SHMEM : +case VM_MEM_SRC_ANONYMOUS_THP : +return true; +default : +return false; + } +} + +int get_backing_src_madvise_advice (uint32_t i) +{ +switch (i) { +case VM_MEM_SRC_ANONYMOUS : +case VM_MEM_SRC_SHMEM : +return MADV_NOHUGEPAGE ; +case VM_MEM_SRC_ANONYMOUS_THP : +return MADV_NOHUGEPAGE ; +default : +return 0 ; + } +} +bool is_backing_src_hugetlb (uint32_t i) {return !!(vm_mem_backing_src_alias (i)->flag &MAP_HUGETLB );
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 11/51 KVM: selftests: Allow cleanup of ucall_pool from host
In reply to Ackerley TngMany selftests use GUEST_DONE() to signal the end of guest code, which is handled in userspace. In most tests, the test exits and there is no need to clean up the ucall_pool->in_use bitmap.
If there are many guest code functions using GUEST_DONE(), or of guest code functions are run many times, the ucall_pool->in_use bitmap will fill up, causing later runs of the same guest code function to fail.
This patch allows ucall_free() to be called from userspace on uc.hva, which will unset and free the correct struct ucall in the pool, allowing ucalls to continue being used.
--- .../testing/selftests/kvm/include/ucall_common.h | 1 + tools/testing/selftests/kvm/lib/ucall_common.c | 16 ++++++++-------- 2 files changed, 9 insertions(+), 8 deletions(-)
tools/testing/selftests/kvm/include/ucall_common.h +1 -0
@@ -40,6 +40,7 @@ __printf(5, 6) void ucall_assert(uint64_t cmd, const char *exp, const char *fmt, ...);uint64_t get_ucall (struct kvm_vcpu *vcpu,struct ucall *uc);void ucall_init (struct kvm_vm *vm,vm_paddr_t mmio_gpa); +void ucall_free (struct ucall *uc);int ucall_nr_pages_required (uint64_t page_size);/*
tools/testing/selftests/kvm/lib/ucall_common.c +8 -8
@@ -21,24 +21,24 @@ int ucall_nr_pages_required(uint64_t page_size)/* * ucall_pool holds per-VM values (global data is duplicated by each VM), it -* must not be accessed from host code. +* should generally not be accessed from host code other than via ucall_free(), +* to cleanup after using GUEST_DONE() */ static struct ucall_header *ucall_pool;void ucall_init (struct kvm_vm *vm,vm_paddr_t mmio_gpa) { -struct ucall_header *hdr;struct ucall *uc;vm_vaddr_t vaddr;int i; - vaddr =vm_vaddr_alloc_shared (vm,sizeof (*hdr),KVM_UTIL_MIN_VADDR , -MEM_REGION_DATA ); - hdr = (struct ucall_header *)addr_gva2hva (vm, vaddr); -memset (hdr,0 ,sizeof (*hdr)); + vaddr =vm_vaddr_alloc_shared (vm,sizeof (*ucall_pool), +KVM_UTIL_MIN_VADDR ,MEM_REGION_DATA ); + ucall_pool = (struct ucall_header *)addr_gva2hva (vm, vaddr); +memset (ucall_pool,0 ,sizeof (*ucall_pool));for (i =0 ; i <KVM_MAX_VCPUS ; ++i) { - uc = &hdr->ucalls[i]; + uc = &ucall_pool->ucalls[i]; uc->hva = uc; }
@@ -73,7 +73,7 @@ static struct ucall *ucall_alloc(void)return NULL ; } -static void ucall_free (struct ucall *uc) +void ucall_free (struct ucall *uc) {/* Beware, here be pointer arithmetic. */ clear_bit (uc - ucall_pool->ucalls, ucall_pool->in_use);
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 12/51 KVM: selftests: Test conversion flows for guest_memfd
In reply to Ackerley TngAdd minimal tests for guest_memfd to test that when memory is marked shared in a VM, the host can read and write to it via an mmap()ed address, and the guest can also read and write to it.
Tests added in this patch use refcounts taken via GUP (requiring CONFIG_GUP_TEST) to simulate unexpected refcounts on guest_memfd pages.
Test that unexpected refcounts cause conversions to fail.
--- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../kvm/guest_memfd_conversions_test.c | 589 ++++++++++++++++++ .../testing/selftests/kvm/include/kvm_util.h | 74 +++ 3 files changed, 664 insertions(+) create mode 100644 tools/testing/selftests/kvm/guest_memfd_conversions_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
@@ -131,6 +131,7 @@ TEST_GEN_PROGS_x86 += access_tracking_perf_test TEST_GEN_PROGS_x86 += coalesced_io_test TEST_GEN_PROGS_x86 += dirty_log_perf_test TEST_GEN_PROGS_x86 += guest_memfd_test +TEST_GEN_PROGS_x86 += guest_memfd_conversions_test TEST_GEN_PROGS_x86 += hardware_disable_test TEST_GEN_PROGS_x86 += memslot_modification_stress_test TEST_GEN_PROGS_x86 += memslot_perf_test
tools/testing/selftests/kvm/guest_memfd_conversions_test.c new file +589 -0
589 lines not on this page · raw message
tools/testing/selftests/kvm/include/kvm_util.h +74 -0
91 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 13/51 KVM: selftests: Add script to exercise private_mem_conversions_test
In reply to Ackerley TngMakes testing different combinations of private_mem_conversions_test flags easier.
--- .../kvm/x86/private_mem_conversions_test.sh | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100755 tools/testing/selftests/kvm/x86/private_mem_conversions_test.sh
tools/testing/selftests/kvm/x86/private_mem_conversions_test.sh new file +82 -0
@@ -0,0 +1,82 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-only */ +# +# Wrapper script which runs different test setups of +# private_mem_conversions_test. +# +# Copyright (C) 2024, Google LLC. + +set -e + +num_vcpus_to_test=4 +num_memslots_to_test=$num_vcpus_to_test + +get_default_hugepage_size_in_kB() { + grep "Hugepagesize:" /proc/meminfo | grep -o '[[:digit:]]\+' +} + +# Required pages are based on the test setup (see computation for memfd_size) in +# test_mem_conversions() in private_mem_migrate_tests.c) + +# These static requirements are set to the maximum required for +# num_vcpus_to_test, over all the hugetlb-related tests +required_num_2m_hugepages=$(( 1024 * num_vcpus_to_test )) +required_num_1g_hugepages=$(( 2 * num_vcpus_to_test )) + +# The other hugetlb sizes are not supported on x86_64 +[ "$(cat /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages 2>/dev/null || echo 0)" \ + -ge "$required_num_2m_hugepages" ] && hugepage_2mb_enabled=1 +[ "$(cat /sys/kernel/mm/hugepages/hugepages-1048576kB/nr_hugepages 2>/dev/null || echo 0)" \ + -ge "$required_num_1g_hugepages" ] && hugepage_1gb_enabled=1 + +case $(get_default_hugepage_size_in_kB) in + 2048) + hugepage_default_enabled=$hugepage_2mb_enabled + ;; + 1048576) + hugepage_default_enabled=$hugepage_1gb_enabled + ;; + *) + hugepage_default_enabled=0 + ;; +esac + +backing_src_types=( anonymous ) +backing_src_types+=( anonymous_thp ) +[ -n "$hugepage_default_enabled" ] && \ + backing_src_types+=( anonymous_hugetlb ) || \ + echo "skipping anonymous_hugetlb backing source type" +[ -n "$hugepage_2mb_enabled" ] && \ + backing_src_types+=( anonymous_hugetlb_2mb ) || \ + echo "skipping anonymous_hugetlb_2mb backing source type" +[ -n "$hugepage_1gb_enabled" ] && \ + backing_src_types+=( anonymous_hugetlb_1gb ) || \ + echo "skipping anonymous_hugetlb_1gb backing source type" +backing_src_types+=( shmem ) +[ -n "$hugepage_default_enabled" ] && \ + backing_src_types+=( shared_hugetlb ) || \ + echo "skipping shared_hugetlb backing source type" + +set +e + +TEST_EXECUTABLE="$(dirname "$0")/private_mem_conversions_test" + +( + set -e + + for src_type in "${backing_src_types[@]}"; do + + set -x + + $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test + $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -m $num_memslots_to_test + + { set +x; } 2>/dev/null + + echo + + done +) +RET=$? + +exit $RET
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 14/51 KVM: selftests: Update private_mem_conversions_test to mmap guest_memfd
In reply to Ackerley TngThis patch updates private_mem_conversions_test to use guest_memfd for both private and shared memory. The guest_memfd conversion ioctls are used to perform conversions.
Specify -g to also back shared memory with memory from guest_memfd.
--- .../testing/selftests/kvm/include/kvm_util.h | 1 + tools/testing/selftests/kvm/lib/kvm_util.c | 36 ++++ .../kvm/x86/private_mem_conversions_test.c | 163 +++++++++++++++--- 3 files changed, 176 insertions(+), 24 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +1 -0
@@ -721,6 +721,7 @@ void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa);void *addr_gva2hva (struct kvm_vm *vm,vm_vaddr_t gva);vm_paddr_t addr_hva2gpa (struct kvm_vm *vm,void *hva);void *addr_gpa2alias (struct kvm_vm *vm,vm_paddr_t gpa); +int addr_gpa2guest_memfd (struct kvm_vm *vm,vm_paddr_t gpa,loff_t *offset);#ifndef vcpu_arch_put_guest#define vcpu_arch_put_guest (mem, val) do { (mem) = (val); } while (0)
tools/testing/selftests/kvm/lib/kvm_util.c +36 -0
@@ -1734,6 +1734,42 @@ void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa) + (gpa - region->region.guest_phys_addr)); } +/* +* Address VM Physical to guest_memfd +* +* Input Args: +* vm - Virtual Machine +* gpa - VM physical address +* +* Output Args: +* offset - offset in guest_memfd for gpa +* +* Return: +* guest_memfd for +* +* Locates the memory region containing the VM physical address given by gpa, +* within the VM given by vm. When found, the guest_memfd providing the memory +* to the vm physical address and the offset in the file corresponding to the +* requested gpa is returned. A TEST_ASSERT failure occurs if no region +* containing gpa exists. +*/ +int addr_gpa2guest_memfd (struct kvm_vm *vm,vm_paddr_t gpa,loff_t *offset) +{ +struct userspace_mem_region *region; + + gpa =vm_untag_gpa (vm, gpa); + + region =userspace_mem_region_find (vm, gpa, gpa); +if (!region) { +TEST_FAIL ("No vm physical memory at 0x%lx" , gpa); +return -1 ; + } + + *offset = region->region.guest_memfd_offset + gpa - region->region.guest_phys_addr; + +return region->region.guest_memfd; +} +/* * Address Host Virtual to VM Physical *
tools/testing/selftests/kvm/x86/private_mem_conversions_test.c +139 -24
282 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 15/51 KVM: selftests: Update script to map shared memory from guest_memfd
In reply to Ackerley TngUpdate the private_mem_conversions_test.sh script to use the -g flag to also test conversions when both private and shared memory are mapped from guest_memfd.
--- .../testing/selftests/kvm/x86/private_mem_conversions_test.sh | 3 +++ 1 file changed, 3 insertions(+)
tools/testing/selftests/kvm/x86/private_mem_conversions_test.sh +3 -0
@@ -71,6 +71,9 @@ TEST_EXECUTABLE="$(dirname "$0")/private_mem_conversions_test" $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -m $num_memslots_to_test + $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -g + $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -m $num_memslots_to_test -g + { set +x; } 2>/dev/null echo
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 16/51 mm: hugetlb: Consolidate interpretation of gbl_chg within alloc_hugetlb_folio()
In reply to Ackerley TngPreviously, gbl_chg was passed from alloc_hugetlb_folio() into dequeue_hugetlb_folio_vma(), leaking the concept of gbl_chg into dequeue_hugetlb_folio_vma().
This patch consolidates the interpretation of gbl_chg into alloc_hugetlb_folio(), also renaming dequeue_hugetlb_folio_vma() to dequeue_hugetlb_folio() so dequeue_hugetlb_folio() can just focus on dequeuing a folio.
--- mm/hugetlb.c | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-)
mm/hugetlb.c +11 -17
@@ -1364,9 +1364,9 @@ static unsigned long available_huge_pages(struct hstate *h)return h->free_huge_pages - h->resv_huge_pages; } -static struct folio *dequeue_hugetlb_folio_vma (struct hstate *h, -struct vm_area_struct *vma, -unsigned long address,long gbl_chg) +static struct folio *dequeue_hugetlb_folio (struct hstate *h, +struct vm_area_struct *vma, +unsigned long address) {struct folio *folio =NULL ;struct mempolicy *mpol;
@@ -1374,13 +1374,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,nodemask_t *nodemask;int nid; -/* -* gbl_chg==1 means the allocation requires a new page that was not -* reserved before. Making sure there's at least one free page. -*/ -if (gbl_chg && !available_huge_pages (h)) - goto err; - gfp_mask =htlb_alloc_mask (h); nid =huge_node (vma, address, gfp_mask, &mpol, &nodemask);
@@ -1398,9 +1391,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,mpol_cond_put (mpol);return folio; - -err: -return NULL ; }/*
@@ -3074,12 +3064,16 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, goto out_uncharge_cgroup_reservation;spin_lock_irq (&hugetlb_lock); +/* -* glb_chg is passed to indicate whether or not a page must be taken -* from the global free pool (global change). gbl_chg == 0 indicates -* a reservation exists for the allocation. +* gbl_chg == 0 indicates a reservation exists for the allocation - so +* try dequeuing a page. If there are available_huge_pages(), try using +* them! */ - folio =dequeue_hugetlb_folio_vma (h, vma, addr, gbl_chg); + folio =NULL ; +if (!gbl_chg ||available_huge_pages (h)) + folio =dequeue_hugetlb_folio (h, vma, addr); +if (!folio) {spin_unlock_irq (&hugetlb_lock); folio =alloc_buddy_hugetlb_folio_with_mpol (h, vma, addr);
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 17/51 mm: hugetlb: Cleanup interpretation of gbl_chg in alloc_hugetlb_folio()
In reply to Ackerley TngThe comment before dequeuing a folio explains that if gbl_chg == 0, a reservation exists for the allocation.
In addition, if a vma reservation exists, there's no need to get a reservation from the subpool, and gbl_chg was set to 0.
This patch replaces both of that with code: subpool_reservation_exists defaults to false, and if a vma reservation does not exist, a reservation is sought from the subpool.
Then, the existence of a reservation, whether in the vma or subpool, is summarized into reservation_exists, which is then used to determine whether to dequeue a folio.
--- mm/hugetlb.c | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-)
mm/hugetlb.c +12 -16
@@ -2999,8 +2999,10 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, {struct hugepage_subpool *spool =subpool_vma (vma);struct hstate *h =hstate_vma (vma); +bool subpool_reservation_exists; +bool reservation_exists;struct folio *folio; -long retval, gbl_chg; +long retval;map_chg_state map_chg;int ret, idx;struct hugetlb_cgroup *h_cg =NULL ;
@@ -3036,17 +3038,16 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,* that the allocation will not exceed the subpool limit. * Or if it can get one from the pool reservation directly. */ + subpool_reservation_exists = false;if (map_chg) { - gbl_chg =hugepage_subpool_get_pages (spool,1 ); -if (gbl_chg <0 ) +int npages_req =hugepage_subpool_get_pages (spool,1 ); + +if (npages_req <0 ) goto out_end_reservation; - }else { -/* -* If we have the vma reservation ready, no need for extra -* global reservation. -*/ - gbl_chg =0 ; + + subpool_reservation_exists = npages_req ==0 ; } + reservation_exists = !map_chg || subpool_reservation_exists;/* * If this allocation is not consuming a per-vma reservation,
@@ -3065,13 +3066,8 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,spin_lock_irq (&hugetlb_lock); -/* -* gbl_chg == 0 indicates a reservation exists for the allocation - so -* try dequeuing a page. If there are available_huge_pages(), try using -* them! -*/ folio =NULL ; -if (!gbl_chg ||available_huge_pages (h)) +if (reservation_exists ||available_huge_pages (h)) folio =dequeue_hugetlb_folio (h, vma, addr);if (!folio) {
@@ -3089,7 +3085,7 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,* Either dequeued or buddy-allocated folio needs to add special * mark to the folio when it consumes a global reservation. */ -if (!gbl_chg) { +if (reservation_exists) {folio_set_hugetlb_restore_reserve (folio); h->resv_huge_pages--; }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 18/51 mm: hugetlb: Cleanup interpretation of map_chg_state within alloc_hugetlb_folio()
In reply to Ackerley TngInterpreting map_chg_state inline, within alloc_hugetlb_folio(), improves readability.
Instead of having cow_from_owner and the result of vma_needs_reservation() compute a map_chg_state, and then interpreting map_chg_state within alloc_hugetlb_folio() to determine whether to
+ Get a page from the subpool or
+ Charge cgroup reservations or
+ Commit vma reservations or
+ Clean up reservations
This refactoring makes those decisions just based on whether a vma_reservation_exists. If a vma_reservation_exists, the subpool had already been debited and the cgroup had been charged, hence alloc_hugetlb_folio() should not double-debit or double-charge. If the vma reservation can't be used (as in cow_from_owner), then the vma reservation effectively does not exist and vma_reservation_exists is set to false.
The conditions for committing reservations or cleaning are also updated to be paired with the corresponding conditions guarding reservation creation.
--- mm/hugetlb.c | 94 ++++++++++++++++++++++------------------------------ 1 file changed, 39 insertions(+), 55 deletions(-)
mm/hugetlb.c +39 -55
@@ -2968,25 +2968,6 @@ void wait_for_freed_hugetlb_folios(void)flush_work (&free_hpage_work); } -typedef enum { -/* -* For either 0/1: we checked the per-vma resv map, and one resv -* count either can be reused (0), or an extra needed (1). -*/ -MAP_CHG_REUSE =0 , -MAP_CHG_NEEDED =1 , -/* -* Cannot use per-vma resv count can be used, hence a new resv -* count is enforced. -* -* NOTE: This is mostly identical to MAP_CHG_NEEDED, except -* that currently vma_needs_reservation() has an unwanted side -* effect to either use end() or commit() to complete the -* transaction. Hence it needs to differenciate from NEEDED. -*/ -MAP_CHG_ENFORCED =2 , -}map_chg_state ; -/* * NOTE! "cow_from_owner" represents a very hacky usage only used in CoW * faults of hugetlb private mappings on top of a non-page-cache folio (in
@@ -3000,46 +2981,45 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,struct hugepage_subpool *spool =subpool_vma (vma);struct hstate *h =hstate_vma (vma);bool subpool_reservation_exists; +bool vma_reservation_exists;bool reservation_exists; +bool charge_cgroup_rsvd;struct folio *folio; -long retval; -map_chg_state map_chg;int ret, idx;struct hugetlb_cgroup *h_cg =NULL ;gfp_t gfp =htlb_alloc_mask (h) | __GFP_RETRY_MAYFAIL; idx =hstate_index (h); -/* Whether we need a separate per-vma reservation? */ if (cow_from_owner) {/* * Special case! Since it's a CoW on top of a reserved * page, the private resv map doesn't count. So it cannot * consume the per-vma resv map even if it's reserved. */ - map_chg =MAP_CHG_ENFORCED ; + vma_reservation_exists = false; }else {/* * Examine the region/reserve map to determine if the process -* has a reservation for the page to be allocated. A return -* code of zero indicates a reservation exists (no change). +* has a reservation for the page to be allocated and debit the +* reservation. If the number of pages required is 0, +* reservation exists. */ - retval =vma_needs_reservation (h, vma, addr); -if (retval <0 ) +int npages_req =vma_needs_reservation (h, vma, addr); + +if (npages_req <0 )return ERR_PTR (-ENOMEM ); - map_chg = retval ?MAP_CHG_NEEDED :MAP_CHG_REUSE ; + + vma_reservation_exists = npages_req ==0 ; }/* -* Whether we need a separate global reservation? -* -* Processes that did not create the mapping will have no -* reserves as indicated by the region/reserve map. Check -* that the allocation will not exceed the subpool limit. -* Or if it can get one from the pool reservation directly. +* Debit subpool only if a vma reservation does not exist. If +* vma_reservation_exists, the vma reservation was either moved from the +* subpool or taken directly from hstate in hugetlb_reserve_pages() */ subpool_reservation_exists = false; -if (map_chg) { +if (!vma_reservation_exists) {int npages_req =hugepage_subpool_get_pages (spool,1 );if (npages_req <0 )
@@ -3047,13 +3027,16 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, subpool_reservation_exists = npages_req ==0 ; } - reservation_exists = !map_chg || subpool_reservation_exists; + + reservation_exists = vma_reservation_exists || subpool_reservation_exists;/* -* If this allocation is not consuming a per-vma reservation, -* charge the hugetlb cgroup now. +* If a vma_reservation_exists, we can skip charging hugetlb +* reservations since that was charged in hugetlb_reserve_pages() when +* the reservation was recorded on the resv_map. */ -if (map_chg) { + charge_cgroup_rsvd = !vma_reservation_exists; +if (charge_cgroup_rsvd) { ret =hugetlb_cgroup_charge_cgroup_rsvd ( idx,pages_per_huge_page (h), &h_cg);if (ret)
@@ -3091,10 +3074,8 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, }hugetlb_cgroup_commit_charge (idx,pages_per_huge_page (h), h_cg, folio); -/* If allocation is not consuming a reservation, also store the -* hugetlb_cgroup pointer on the page. -*/ -if (map_chg) { + +if (charge_cgroup_rsvd) {hugetlb_cgroup_commit_charge_rsvd (idx,pages_per_huge_page (h), h_cg, folio); }
@@ -3103,25 +3084,27 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,hugetlb_set_folio_subpool (folio, spool); -if (map_chg !=MAP_CHG_ENFORCED ) { -/* commit() is only needed if the map_chg is not enforced */ - retval =vma_commit_reservation (h, vma, addr); +/* If vma accounting wasn't bypassed earlier, follow up with commit. */ +if (!cow_from_owner) { +int ret =vma_commit_reservation (h, vma, addr);/* -* Check for possible race conditions. When it happens.. -* The page was added to the reservation map between -* vma_needs_reservation and vma_commit_reservation. -* This indicates a race with hugetlb_reserve_pages. +* If there is a discrepancy in reservation status between the +* time of vma_needs_reservation() and vma_commit_reservation(), +* then there the page must have been added to the reservation +* map between vma_needs_reservation() and +* vma_commit_reservation(). +* * Adjust for the subpool count incremented above AND * in hugetlb_reserve_pages for the same page. Also, * the reservation count added in hugetlb_reserve_pages * no longer applies. */ -if (unlikely (map_chg ==MAP_CHG_NEEDED && retval ==0 )) { +if (unlikely (!vma_reservation_exists && ret ==0 )) {long rsv_adjust; rsv_adjust =hugepage_subpool_put_pages (spool,1 );hugetlb_acct_memory (h, -rsv_adjust); -if (map_chg) { +if (charge_cgroup_rsvd) {spin_lock_irq (&hugetlb_lock); hugetlb_cgroup_uncharge_folio_rsvd( hstate_index(h), pages_per_huge_page(h),
@@ -3149,14 +3132,15 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, out_uncharge_cgroup:hugetlb_cgroup_uncharge_cgroup (idx,pages_per_huge_page (h), h_cg); out_uncharge_cgroup_reservation: -if (map_chg) +if (charge_cgroup_rsvd)hugetlb_cgroup_uncharge_cgroup_rsvd (idx,pages_per_huge_page (h), h_cg); out_subpool_put: -if (map_chg) +if (!vma_reservation_exists)hugepage_subpool_put_pages (spool,1 ); out_end_reservation: -if (map_chg !=MAP_CHG_ENFORCED ) +/* If vma accounting wasn't bypassed earlier, cleanup. */ +if (!cow_from_owner)vma_end_reservation (h, vma, addr);return ERR_PTR (-ENOSPC ); }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 19/51 mm: hugetlb: Rename alloc_surplus_hugetlb_folio
In reply to Ackerley TngRename alloc_surplus_hugetlb_folio vs alloc_surplus_hugetlb_folio_nodemask to align with dequeue_hugetlb_folio vs dequeue_hugetlb_folio_nodemask.
--- mm/hugetlb.c | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-)
mm/hugetlb.c +20 -18
@@ -2236,7 +2236,7 @@ int dissolve_free_hugetlb_folios(unsigned long start_pfn, unsigned long end_pfn)/* * Allocates a fresh surplus page from the page allocator. */ -static struct folio *alloc_surplus_hugetlb_folio (struct hstate *h, +static struct folio *alloc_surplus_hugetlb_folio_nodemask (struct hstate *h,gfp_t gfp_mask,int nid,nodemask_t *nmask) {struct folio *folio =NULL ;
@@ -2312,9 +2312,9 @@ static struct folio *alloc_migrate_hugetlb_folio(struct hstate *h, gfp_t gfp_mas/* * Use the VMA's mpolicy to allocate a huge page from the buddy. */ -static -struct folio *alloc_buddy_hugetlb_folio_with_mpol (struct hstate *h, -struct vm_area_struct *vma,unsigned long addr) +static struct folio *alloc_surplus_hugetlb_folio (struct hstate *h, +struct vm_area_struct *vma, +unsigned long addr) {struct folio *folio =NULL ;struct mempolicy *mpol;
@@ -2326,14 +2326,14 @@ struct folio *alloc_buddy_hugetlb_folio_with_mpol(struct hstate *h,if (mpol_is_preferred_many (mpol)) {gfp_t gfp = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL); - folio =alloc_surplus_hugetlb_folio (h, gfp, nid, nodemask); + folio =alloc_surplus_hugetlb_folio_nodemask (h, gfp, nid, nodemask);/* Fallback to all nodes if page==NULL */ nodemask =NULL ; }if (!folio) - folio =alloc_surplus_hugetlb_folio (h, gfp_mask, nid, nodemask); + folio =alloc_surplus_hugetlb_folio_nodemask (h, gfp_mask, nid, nodemask);mpol_cond_put (mpol);return folio; }
@@ -2435,14 +2435,14 @@ static int gather_surplus_pages(struct hstate *h, long delta)/* Prioritize current node */ if (node_isset (numa_mem_id (), alloc_nodemask)) - folio =alloc_surplus_hugetlb_folio (h,htlb_alloc_mask (h), + folio =alloc_surplus_hugetlb_folio_nodemask (h,htlb_alloc_mask (h),numa_mem_id (),NULL );if (!folio) {for_each_node_mask (node, alloc_nodemask) {if (node ==numa_mem_id ())continue ; - folio =alloc_surplus_hugetlb_folio (h,htlb_alloc_mask (h), + folio =alloc_surplus_hugetlb_folio_nodemask (h,htlb_alloc_mask (h), node,NULL );if (folio)break ;
@@ -3055,7 +3055,7 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,if (!folio) {spin_unlock_irq (&hugetlb_lock); - folio =alloc_buddy_hugetlb_folio_with_mpol (h, vma, addr); + folio =alloc_surplus_hugetlb_folio (h, vma, addr);if (!folio) goto out_uncharge_cgroup;spin_lock_irq (&hugetlb_lock);
@@ -3868,11 +3868,12 @@ static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,* First take pages out of surplus state. Then make up the * remaining difference by allocating fresh huge pages. * -* We might race with alloc_surplus_hugetlb_folio() here and be unable -* to convert a surplus huge page to a normal huge page. That is -* not critical, though, it just means the overall size of the -* pool might be one hugepage larger than it needs to be, but -* within all the constraints specified by the sysctls. +* We might race with alloc_surplus_hugetlb_folio_nodemask() +* here and be unable to convert a surplus huge page to a normal +* huge page. That is not critical, though, it just means the +* overall size of the pool might be one hugepage larger than it +* needs to be, but within all the constraints specified by the +* sysctls. */ while (h->surplus_huge_pages && count >persistent_huge_pages (h)) {if (!adjust_pool_surplus (h, nodes_allowed,-1 ))
@@ -3930,10 +3931,11 @@ static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,* By placing pages into the surplus state independent of the * overcommit value, we are allowing the surplus pool size to * exceed overcommit. There are few sane options here. Since -* alloc_surplus_hugetlb_folio() is checking the global counter, -* though, we'll note that we're not allowed to exceed surplus -* and won't grow the pool anywhere else. Not until one of the -* sysctls are changed, or the surplus pages go out of use. +* alloc_surplus_hugetlb_folio_nodemask() is checking the global +* counter, though, we'll note that we're not allowed to exceed +* surplus and won't grow the pool anywhere else. Not until one +* of the sysctls are changed, or the surplus pages go out of +* use. * * min_count is the expected number of persistent pages, we * shouldn't calculate min_count by using
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 20/51 mm: mempolicy: Refactor out policy_node_nodemask()
In reply to Ackerley TngThis was refactored out of huge_node().
huge_node()'s interpretation of vma for order assumes the hugetlb-specific storage of the hstate information in the inode. policy_node_nodemask() does not assume that, and can be used more generically.
This refactoring also enforces that nid default to the current node id, which was not previously enforced.
alloc_pages_mpol() is the last remaining direct user of policy_nodemask(). All its callers begin with nid being the current node id as well. More refactoring is required for to simplify that.
Change-Id: I5774b27d2e718f4d08b59f8d2fedbb34eda7bac3
--- include/linux/mempolicy.h | 9 +++++++++ mm/mempolicy.c | 33 ++++++++++++++++++++++++++------- 2 files changed, 35 insertions(+), 7 deletions(-)
include/linux/mempolicy.h +9 -0
@@ -138,6 +138,8 @@ extern void numa_policy_init(void);extern void mpol_rebind_task (struct task_struct *tsk,const nodemask_t *new);extern void mpol_rebind_mm (struct mm_struct *mm,nodemask_t *new); +extern int policy_node_nodemask (struct mempolicy *mpol,gfp_t gfp_flags, +pgoff_t ilx,nodemask_t **nodemask);extern int huge_node (struct vm_area_struct *vma,unsigned long addr,gfp_t gfp_flags,struct mempolicy **mpol,nodemask_t **nodemask);
@@ -251,6 +253,13 @@ static inline void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new) { } +static inline int policy_node_nodemask (struct mempolicy *mpol,gfp_t gfp_flags, +pgoff_t ilx,nodemask_t **nodemask) +{ + *nodemask =NULL ; +return 0 ; +} +static inline int huge_node (struct vm_area_struct *vma,unsigned long addr,gfp_t gfp_flags,struct mempolicy **mpol,nodemask_t **nodemask)
mm/mempolicy.c +26 -7
@@ -1261,7 +1261,7 @@ static struct folio *alloc_migration_target_by_mpol(struct folio *src, h =folio_hstate (src); gfp =htlb_alloc_mask (h); - nodemask =policy_nodemask (gfp, pol, ilx, &nid); + nid =policy_node_nodemask (pol, gfp, ilx, &nodemask);return alloc_hugetlb_folio_nodemask (h, nid, nodemask, gfp,htlb_allow_alloc_fallback (MR_MEMPOLICY_MBIND )); }
@@ -2121,6 +2121,29 @@ static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *pol,return nodemask; } +/** +* policy_node_nodemask() - Interpret memory policy to get nodemask and nid. +* +* @mpol: the memory policy to interpret. +* @gfp_flags: gfp flags for this request. +* @ilx: interleave index, for use only when MPOL_INTERLEAVE or +* MPOL_WEIGHTED_INTERLEAVE +* @nodemask: (output) pointer to nodemask pointer for 'bind' and 'prefer-many' +* policy +* +* Context: must hold reference on @mpol. +* Return: a nid suitable for a page allocation and a pointer. If the effective +* policy is 'bind' or 'prefer-many', returns a pointer to the +* mempolicy's @nodemask for filtering the zonelist. +*/ +int policy_node_nodemask (struct mempolicy *mpol,gfp_t gfp_flags, +pgoff_t ilx,nodemask_t **nodemask) +{ +int nid =numa_node_id (); + *nodemask =policy_nodemask (gfp_flags, mpol, ilx, &nid); +return nid; +} +#ifdef CONFIG_HUGETLBFS /* * huge_node(@vma, @addr, @gfp_flags, @mpol)
@@ -2139,12 +2162,9 @@ int huge_node(struct vm_area_struct *vma, unsigned long addr, gfp_t gfp_flags, struct mempolicy **mpol, nodemask_t **nodemask) { pgoff_t ilx; -int nid; - nid =numa_node_id (); *mpol =get_vma_policy (vma, addr,hstate_vma (vma)->order, &ilx); - *nodemask =policy_nodemask (gfp_flags, *mpol, ilx, &nid); -return nid; +return policy_node_nodemask (*mpol, gfp_flags, ilx, nodemask); }/*
@@ -2601,8 +2621,7 @@ unsigned long alloc_pages_bulk_mempolicy_noprof(gfp_t gfp,return alloc_pages_bulk_preferred_many (gfp,numa_node_id (), pol, nr_pages, page_array); - nid =numa_node_id (); - nodemask =policy_nodemask (gfp, pol,NO_INTERLEAVE_INDEX , &nid); + nid =policy_node_nodemask (pol, gfp,NO_INTERLEAVE_INDEX , &nodemask);return alloc_pages_bulk_noprof (gfp, nid, nodemask, nr_pages, page_array); }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 21/51 mm: hugetlb: Inline huge_node() into callers
In reply to Ackerley Tnghuge_node()'s role was to read struct mempolicy (mpol) from the vma and also interpret mpol to get node id and nodemask.
huge_node() can be inlined into callers since 2 out of 3 of the callers will be refactored in later patches to take and interpret mpol without reading mpol from the vma.
Change-Id: Ic94b2ed916fd4f89b7d2755288a3a2f6a56051f7
--- include/linux/mempolicy.h | 12 ------------ mm/hugetlb.c | 13 ++++++++++--- mm/mempolicy.c | 21 --------------------- 3 files changed, 10 insertions(+), 36 deletions(-)
include/linux/mempolicy.h +0 -12
@@ -140,9 +140,6 @@ extern void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new);extern int policy_node_nodemask (struct mempolicy *mpol,gfp_t gfp_flags,pgoff_t ilx,nodemask_t **nodemask); -extern int huge_node (struct vm_area_struct *vma, -unsigned long addr,gfp_t gfp_flags, -struct mempolicy **mpol,nodemask_t **nodemask);extern bool init_nodemask_of_mempolicy (nodemask_t *mask);extern bool mempolicy_in_oom_domain (struct task_struct *tsk,const nodemask_t *mask);
@@ -260,15 +257,6 @@ static inline int policy_node_nodemask(struct mempolicy *mpol, gfp_t gfp_flags,return 0 ; } -static inline int huge_node (struct vm_area_struct *vma, -unsigned long addr,gfp_t gfp_flags, -struct mempolicy **mpol,nodemask_t **nodemask) -{ - *mpol =NULL ; - *nodemask =NULL ; -return 0 ; -} -static inline bool init_nodemask_of_mempolicy (nodemask_t *m) {return false;
mm/hugetlb.c +10 -3
@@ -1372,10 +1372,12 @@ static struct folio *dequeue_hugetlb_folio(struct hstate *h,struct mempolicy *mpol;gfp_t gfp_mask;nodemask_t *nodemask; +pgoff_t ilx;int nid; gfp_mask =htlb_alloc_mask (h); - nid =huge_node (vma, address, gfp_mask, &mpol, &nodemask); + mpol =get_vma_policy (vma, address, h->order, &ilx); + nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask);if (mpol_is_preferred_many (mpol)) { folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
@@ -2321,8 +2323,11 @@ static struct folio *alloc_surplus_hugetlb_folio(struct hstate *h,gfp_t gfp_mask =htlb_alloc_mask (h);int nid;nodemask_t *nodemask; +pgoff_t ilx; + + mpol =get_vma_policy (vma, addr, h->order, &ilx); + nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask); - nid =huge_node (vma, addr, gfp_mask, &mpol, &nodemask);if (mpol_is_preferred_many (mpol)) {gfp_t gfp = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
@@ -6829,10 +6834,12 @@ static struct folio *alloc_hugetlb_folio_vma(struct hstate *h,nodemask_t *nodemask;struct folio *folio;gfp_t gfp_mask; +pgoff_t ilx;int node; gfp_mask =htlb_alloc_mask (h); - node =huge_node (vma, address, gfp_mask, &mpol, &nodemask); + mpol =get_vma_policy (vma, address, h->order, &ilx); + node =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask);/* * This is used to allocate a temporary hugetlb to hold the copied * content, which will then be copied again to the final hugetlb
mm/mempolicy.c +0 -21
@@ -2145,27 +2145,6 @@ int policy_node_nodemask(struct mempolicy *mpol, gfp_t gfp_flags, }#ifdef CONFIG_HUGETLBFS -/* -* huge_node(@vma, @addr, @gfp_flags, @mpol) -* @vma: virtual memory area whose policy is sought -* @addr: address in @vma for shared policy lookup and interleave policy -* @gfp_flags: for requested zone -* @mpol: pointer to mempolicy pointer for reference counted mempolicy -* @nodemask: pointer to nodemask pointer for 'bind' and 'prefer-many' policy -* -* Returns a nid suitable for a huge page allocation and a pointer -* to the struct mempolicy for conditional unref after allocation. -* If the effective policy is 'bind' or 'prefer-many', returns a pointer -* to the mempolicy's @nodemask for filtering the zonelist. -*/ -int huge_node (struct vm_area_struct *vma,unsigned long addr,gfp_t gfp_flags, -struct mempolicy **mpol,nodemask_t **nodemask) -{ -pgoff_t ilx; - - *mpol =get_vma_policy (vma, addr,hstate_vma (vma)->order, &ilx); -return policy_node_nodemask (*mpol, gfp_flags, ilx, nodemask); -}/* * init_nodemask_of_mempolicy
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 22/51 mm: hugetlb: Refactor hugetlb allocation functions
In reply to Ackerley TngRefactor dequeue_hugetlb_folio() and alloc_surplus_hugetlb_folio() to take mpol, nid and nodemask. This decouples allocation of a folio from a vma.
--- mm/hugetlb.c | 64 ++++++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 34 deletions(-)
mm/hugetlb.c +30 -34
@@ -1364,34 +1364,22 @@ static unsigned long available_huge_pages(struct hstate *h)return h->free_huge_pages - h->resv_huge_pages; } -static struct folio *dequeue_hugetlb_folio (struct hstate *h, -struct vm_area_struct *vma, -unsigned long address) +static struct folio *dequeue_hugetlb_folio (struct hstate *h,gfp_t gfp_mask, +struct mempolicy *mpol, +int nid,nodemask_t *nodemask) {struct folio *folio =NULL ; -struct mempolicy *mpol; -gfp_t gfp_mask; -nodemask_t *nodemask; -pgoff_t ilx; -int nid; - - gfp_mask =htlb_alloc_mask (h); - mpol =get_vma_policy (vma, address, h->order, &ilx); - nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask);if (mpol_is_preferred_many (mpol)) { - folio =dequeue_hugetlb_folio_nodemask (h, gfp_mask, - nid, nodemask); + folio =dequeue_hugetlb_folio_nodemask (h, gfp_mask, nid, nodemask);/* Fallback to all nodes if page==NULL */ nodemask =NULL ; }if (!folio) - folio =dequeue_hugetlb_folio_nodemask (h, gfp_mask, - nid, nodemask); + folio =dequeue_hugetlb_folio_nodemask (h, gfp_mask, nid, nodemask); -mpol_cond_put (mpol);return folio; }
@@ -2312,21 +2300,14 @@ static struct folio *alloc_migrate_hugetlb_folio(struct hstate *h, gfp_t gfp_mas }/* -* Use the VMA's mpolicy to allocate a huge page from the buddy. +* Allocate a huge page from the buddy allocator given memory policy and node information. */ static struct folio *alloc_surplus_hugetlb_folio (struct hstate *h, -struct vm_area_struct *vma, -unsigned long addr) +gfp_t gfp_mask, +struct mempolicy *mpol, +int nid,nodemask_t *nodemask) {struct folio *folio =NULL ; -struct mempolicy *mpol; -gfp_t gfp_mask =htlb_alloc_mask (h); -int nid; -nodemask_t *nodemask; -pgoff_t ilx; - - mpol =get_vma_policy (vma, addr, h->order, &ilx); - nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask);if (mpol_is_preferred_many (mpol)) {gfp_t gfp = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
@@ -2339,7 +2320,7 @@ static struct folio *alloc_surplus_hugetlb_folio(struct hstate *h,if (!folio) folio =alloc_surplus_hugetlb_folio_nodemask (h, gfp_mask, nid, nodemask); -mpol_cond_put (mpol); +return folio; }
@@ -2993,6 +2974,11 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,int ret, idx;struct hugetlb_cgroup *h_cg =NULL ;gfp_t gfp =htlb_alloc_mask (h) | __GFP_RETRY_MAYFAIL; +struct mempolicy *mpol; +nodemask_t *nodemask; +gfp_t gfp_mask; +pgoff_t ilx; +int nid; idx =hstate_index (h);
@@ -3032,7 +3018,6 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, subpool_reservation_exists = npages_req ==0 ; } - reservation_exists = vma_reservation_exists || subpool_reservation_exists;/*
@@ -3048,21 +3033,30 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, goto out_subpool_put; } + mpol =get_vma_policy (vma, addr, h->order, &ilx); + ret =hugetlb_cgroup_charge_cgroup (idx,pages_per_huge_page (h), &h_cg); -if (ret) +if (ret) { +mpol_cond_put (mpol); goto out_uncharge_cgroup_reservation; + } + + gfp_mask =htlb_alloc_mask (h); + nid =policy_node_nodemask (mpol, gfp_mask, ilx, &nodemask);spin_lock_irq (&hugetlb_lock); folio =NULL ;if (reservation_exists ||available_huge_pages (h)) - folio =dequeue_hugetlb_folio (h, vma, addr); + folio =dequeue_hugetlb_folio (h, gfp_mask, mpol, nid, nodemask);if (!folio) {spin_unlock_irq (&hugetlb_lock); - folio =alloc_surplus_hugetlb_folio (h, vma, addr); -if (!folio) + folio =alloc_surplus_hugetlb_folio (h, gfp_mask, mpol, nid, nodemask); +if (!folio) { +mpol_cond_put (mpol); goto out_uncharge_cgroup; + }spin_lock_irq (&hugetlb_lock);list_add (&folio->lru, &h->hugepage_activelist);folio_ref_unfreeze (folio,1 );
@@ -3087,6 +3081,8 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,spin_unlock_irq (&hugetlb_lock); +mpol_cond_put (mpol); +hugetlb_set_folio_subpool (folio, spool);/* If vma accounting wasn't bypassed earlier, follow up with commit. */
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 23/51 mm: hugetlb: Refactor out hugetlb_alloc_folio()
In reply to Ackerley TngRefactor out hugetlb_alloc_folio() from alloc_hugetlb_folio(), which handles allocation of a folio and cgroup charging.
Other than flags to control charging in the allocation process, hugetlb_alloc_folio() also has parameters for memory policy.
This refactoring as a whole decouples the hugetlb page allocation from hugetlbfs, (1) where the subpool is stored at the fs mount, (2) reservations are made during mmap and stored in the vma, and (3) mpol must be stored at vma->vm_policy (4) a vma must be used for allocation even if the pages are not meant to be used by host process.
This decoupling will allow hugetlb_alloc_folio() to be used by guest_memfd in later patches. In guest_memfd, (1) a subpool is created per-fd and is stored on the inode, (2) no vma-related reservations are used (3) mpol may not be associated with a vma since (4) for private pages, the pages will not be mappable to userspace and hence have to associated vmas.
This could hopefully also open hugetlb up as a more generic source of hugetlb pages that are not bound to hugetlbfs, with the complexities of userspace/mmap/vma-related reservations contained just to hugetlbfs.
--- include/linux/hugetlb.h | 12 +++ mm/hugetlb.c | 192 ++++++++++++++++++++++------------------ 2 files changed, 118 insertions(+), 86 deletions(-)
include/linux/hugetlb.h +12 -0
@@ -698,6 +698,9 @@ bool hugetlb_bootmem_page_zones_valid(int nid, struct huge_bootmem_page *m);int isolate_or_dissolve_huge_page (struct page *page,struct list_head *list);int replace_free_hugepage_folios (unsigned long start_pfn,unsigned long end_pfn);void wait_for_freed_hugetlb_folios (void ); +struct folio *hugetlb_alloc_folio (struct hstate *h,struct mempolicy *mpol, +pgoff_t ilx,bool charge_cgroup_rsvd, +bool use_existing_reservation);struct folio *alloc_hugetlb_folio (struct vm_area_struct *vma,unsigned long addr,bool cow_from_owner); struct folio *alloc_hugetlb_folio_nodemask(struct hstate *h, int preferred_nid,
@@ -1099,6 +1102,15 @@ static inline void wait_for_freed_hugetlb_folios(void) { } +static inline struct folio *hugetlb_alloc_folio (struct hstate *h, +struct mempolicy *mpol, +pgoff_t ilx, +bool charge_cgroup_rsvd, +bool use_existing_reservation) +{ +return NULL ; +} +static inline struct folio *alloc_hugetlb_folio (struct vm_area_struct *vma,unsigned long addr,bool cow_from_owner)
mm/hugetlb.c +106 -86
233 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 24/51 mm: hugetlb: Add option to create new subpool without using surplus
In reply to Ackerley Tng__hugetlb_acct_memory() today does more than just memory accounting. When there's insufficient HugeTLB pages, __hugetlb_acct_memory() will attempt to get surplus pages.
This change adds a flag to disable getting surplus pages if there are insufficient HugeTLB pages.
--- fs/hugetlbfs/inode.c | 2 +- include/linux/hugetlb.h | 2 +- mm/hugetlb.c | 77 +++++++++++++++++++++++++++++++---------- 3 files changed, 61 insertions(+), 20 deletions(-)
fs/hugetlbfs/inode.c +1 -1
@@ -1424,7 +1424,7 @@ hugetlbfs_fill_super(struct super_block *sb, struct fs_context *fc)if (ctx->max_hpages !=-1 || ctx->min_hpages !=-1 ) { sbinfo->spool =hugepage_new_subpool (ctx->hstate, ctx->max_hpages, - ctx->min_hpages); + ctx->min_hpages, true);if (!sbinfo->spool) goto out_free; }
include/linux/hugetlb.h +1 -1
@@ -116,7 +116,7 @@ extern int hugetlb_max_hstate __read_mostly;for ((h) = hstates; (h) < &hstates[hugetlb_max_hstate]; (h)++) struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages, -long min_hpages); +long min_hpages,bool use_surplus);void hugepage_put_subpool (struct hugepage_subpool *spool);void hugetlb_dup_vma_private (struct vm_area_struct *vma);
mm/hugetlb.c +59 -18
148 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 25/51 mm: truncate: Expose preparation steps for truncate_inode_pages_final
In reply to Ackerley TngThis will allow preparation steps to be shared while implementing truncation differently.
--- include/linux/mm.h | 1 + mm/truncate.c | 26 ++++++++++++++++---------- 2 files changed, 17 insertions(+), 10 deletions(-)
include/linux/mm.h +1 -0
@@ -3514,6 +3514,7 @@ extern unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info);extern void truncate_inode_pages (struct address_space *,loff_t );extern void truncate_inode_pages_range (struct address_space *,loff_t lstart,loff_t lend); +extern void truncate_inode_pages_final_prepare (struct address_space *mapping);extern void truncate_inode_pages_final (struct address_space *);/* generic vm_area_ops exported for stackable file systems */
mm/truncate.c +16 -10
@@ -457,16 +457,7 @@ void truncate_inode_pages(struct address_space *mapping, loff_t lstart) }EXPORT_SYMBOL (truncate_inode_pages); -/** -* truncate_inode_pages_final - truncate *all* pages before inode dies -* @mapping: mapping to truncate -* -* Called under (and serialized by) inode->i_rwsem. -* -* Filesystems have to use this in the .evict_inode path to inform the -* VM that this is the final truncate and the inode is going away. -*/ -void truncate_inode_pages_final (struct address_space *mapping) +void truncate_inode_pages_final_prepare (struct address_space *mapping) {/* * Page reclaim can not participate in regular inode lifetime
@@ -487,6 +478,21 @@ void truncate_inode_pages_final(struct address_space *mapping)xa_lock_irq (&mapping->i_pages);xa_unlock_irq (&mapping->i_pages); } +} +EXPORT_SYMBOL (truncate_inode_pages_final_prepare); + +/** +* truncate_inode_pages_final - truncate *all* pages before inode dies +* @mapping: mapping to truncate +* +* Called under (and serialized by) inode->i_rwsem. +* +* Filesystems have to use this in the .evict_inode path to inform the +* VM that this is the final truncate and the inode is going away. +*/ +void truncate_inode_pages_final (struct address_space *mapping) +{ +truncate_inode_pages_final_prepare (mapping);truncate_inode_pages (mapping,0 ); }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 26/51 mm: Consolidate freeing of typed folios on final folio_put()
In reply to Ackerley TngFrom: Fuad Tabba <[email protected]>
Some folio types, such as hugetlb, handle freeing their own folios.
The guestmem_hugetlb folio, to be introduced in a later patch, requires extra handling as part of the freeing process.
As a first step towards that, this patch consolidates freeing folios that have a type. The first user is hugetlb folios. Later in this patch series, guestmem_hugetlb will become the second user of this.
--- include/linux/page-flags.h | 15 +++++++++++++++ mm/swap.c | 23 ++++++++++++++++++----- 2 files changed, 33 insertions(+), 5 deletions(-)
include/linux/page-flags.h +15 -0
@@ -985,6 +985,21 @@ static inline bool page_has_type(const struct page *page)return page_mapcount_is_type (data_race (page->page_type)); } +static inline int page_get_type (const struct page *page) +{ +return page->page_type >>24 ; +} + +static inline bool folio_has_type (const struct folio *folio) +{ +return page_has_type (&folio->page); +} + +static inline int folio_get_type (const struct folio *folio) +{ +return page_get_type (&folio->page); +} +#define FOLIO_TYPE_OPS (lname, fname) \ static __always_inline bool folio_test_##fname(const struct folio *folio) \ { \
mm/swap.c +18 -5
@@ -94,6 +94,19 @@ static void page_cache_release(struct folio *folio)unlock_page_lruvec_irqrestore (lruvec, flags); } +static void free_typed_folio (struct folio *folio) +{ +switch (folio_get_type (folio)) { +#ifdef CONFIG_HUGETLBFS +case PGTY_hugetlb: +free_huge_folio (folio); +return ; +#endif +default : +WARN_ON_ONCE (1 ); + } +} +void __folio_put (struct folio *folio) {if (unlikely (folio_is_zone_device (folio))) {
@@ -101,8 +114,8 @@ void __folio_put(struct folio *folio)return ; } -if (folio_test_hugetlb (folio)) { -free_huge_folio (folio); +if (unlikely (folio_has_type (folio))) { +free_typed_folio (folio);return ; }
@@ -964,13 +977,13 @@ void folios_put_refs(struct folio_batch *folios, unsigned int *refs)if (!folio_ref_sub_and_test (folio, nr_refs))continue ; -/* hugetlb has its own memcg */ -if (folio_test_hugetlb (folio)) { +if (unlikely (folio_has_type (folio))) { +/* typed folios have their own memcg, if any */ if (lruvec) {unlock_page_lruvec_irqrestore (lruvec, flags); lruvec =NULL ; } -free_huge_folio (folio); +free_typed_folio (folio);continue ; }folio_unqueue_deferred_split (folio);
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 27/51 mm: hugetlb: Expose hugetlb_subpool_{get,put}_pages()
In reply to Ackerley TngThis will allow hugetlb subpools to be used by guestmem_hugetlb.
--- include/linux/hugetlb.h | 3 +++ mm/hugetlb.c | 6 ++---- 2 files changed, 5 insertions(+), 4 deletions(-)
include/linux/hugetlb.h +3 -0
@@ -119,6 +119,9 @@ struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages, long min_hpages, bool use_surplus);void hugepage_put_subpool (struct hugepage_subpool *spool); +long hugepage_subpool_get_pages (struct hugepage_subpool *spool,long delta); +long hugepage_subpool_put_pages (struct hugepage_subpool *spool,long delta); +void hugetlb_dup_vma_private (struct vm_area_struct *vma);void clear_vma_resv_huge_pages (struct vm_area_struct *vma); int move_hugetlb_page_tables(struct vm_area_struct *vma,
mm/hugetlb.c +2 -4
@@ -205,8 +205,7 @@ void hugepage_put_subpool(struct hugepage_subpool *spool)* only be different than the passed value (delta) in the case where * a subpool minimum size must be maintained. */ -static long hugepage_subpool_get_pages (struct hugepage_subpool *spool, -long delta) +long hugepage_subpool_get_pages (struct hugepage_subpool *spool,long delta) {long ret = delta;
@@ -250,8 +249,7 @@ static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,* The return value may only be different than the passed value (delta) * in the case where a subpool minimum size must be maintained. */ -static long hugepage_subpool_put_pages (struct hugepage_subpool *spool, -long delta) +long hugepage_subpool_put_pages (struct hugepage_subpool *spool,long delta) {long ret = delta;unsigned long flags;
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 28/51 mm: Introduce guestmem_hugetlb to support folio_put() handling of guestmem pages
In reply to Ackerley TngThe PGTY_guestmem_hugetlb is introduced so folios can be marked for further cleanup by guestmem_hugetlb.
guestmem_hugetlb folios can have positive mapcounts, which will conflict with the installation of a page type. Hence, PGTY_guestmem_hugetlb will only be installed when a folio is truncated, after the folio has been unmapped and has a mapcount of 0.
Change-Id: I635f8929e06f73d7899737bd47090b7cbc7222dc
--- include/linux/page-flags.h | 17 +++++++++++++++++ mm/Kconfig | 10 ++++++++++ mm/Makefile | 1 + mm/debug.c | 1 + mm/guestmem_hugetlb.c | 14 ++++++++++++++ mm/guestmem_hugetlb.h | 9 +++++++++ mm/swap.c | 9 +++++++++ 7 files changed, 61 insertions(+) create mode 100644 mm/guestmem_hugetlb.c create mode 100644 mm/guestmem_hugetlb.h
include/linux/page-flags.h +17 -0
@@ -965,6 +965,7 @@ enum pagetype { PGTY_zsmalloc =0xf6 , PGTY_unaccepted =0xf7 , PGTY_large_kmalloc =0xf8 , + PGTY_guestmem_hugetlb =0xf9 , PGTY_mapcount_underflow = 0xff };
@@ -1114,6 +1115,22 @@ FOLIO_TYPE_OPS(hugetlb, hugetlb) FOLIO_TEST_FLAG_FALSE(hugetlb)#endif +/* +* PGTY_guestmem_hugetlb, for now, is used to mark a folio as requiring further +* cleanup by the guestmem_hugetlb allocator. This page type is installed only +* at truncation time, by guest_memfd, if further cleanup is required. It is +* safe to install this page type at truncation time because by then mapcount +* would be 0. +* +* The plan is to always set this page type for any folios allocated by +* guestmem_hugetlb once typed folios can be mapped to userspace cleanly. +*/ +#ifdef CONFIG_GUESTMEM_HUGETLB +FOLIO_TYPE_OPS(guestmem_hugetlb, guestmem_hugetlb) +#else +FOLIO_TEST_FLAG_FALSE(guestmem_hugetlb) +#endif +PAGE_TYPE_OPS (Zsmalloc, zsmalloc, zsmalloc)/*
mm/Kconfig +10 -0
@@ -1216,6 +1216,16 @@ config SECRETMEM memory areas visible only in the context of the owning process and not mapped to other processes and other kernel page tables. +config GUESTMEM_HUGETLB + bool "Enable guestmem_hugetlb allocator for guest_memfd" + depends on HUGETLBFS + help + Enable this to make HugeTLB folios available to guest_memfd + (KVM virtualization) as backing memory. + + This feature wraps HugeTLB as a custom allocator that + guest_memfd can use. + config ANON_VMA_NAME bool "Anonymous VMA name support" depends on PROC_FS && ADVISE_SYSCALLS && MMU
mm/Makefile +1 -0
@@ -127,6 +127,7 @@ obj-$(CONFIG_PAGE_EXTENSION) += page_ext.o obj-$(CONFIG_PAGE_TABLE_CHECK) += page_table_check.o obj-$(CONFIG_CMA_DEBUGFS) += cma_debug.o obj-$(CONFIG_SECRETMEM) += secretmem.o +obj-$(CONFIG_GUESTMEM_HUGETLB) += guestmem_hugetlb.o obj-$(CONFIG_CMA_SYSFS) += cma_sysfs.o obj-$(CONFIG_USERFAULTFD) += userfaultfd.o obj-$(CONFIG_IDLE_PAGE_TRACKING) += page_idle.o
mm/debug.c +1 -0
@@ -56,6 +56,7 @@ static const char *page_type_names[] = {DEF_PAGETYPE_NAME (table),DEF_PAGETYPE_NAME (buddy),DEF_PAGETYPE_NAME (unaccepted), + DEF_PAGETYPE_NAME(guestmem_hugetlb), };static const char *page_type_name (unsigned int page_type)
mm/guestmem_hugetlb.c new file +14 -0
@@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* guestmem_hugetlb is an allocator for guest_memfd. guest_memfd wraps HugeTLB +* as an allocator for guest_memfd. +*/ + +#include <linux/mm_types.h> + +#include "guestmem_hugetlb.h" + +void guestmem_hugetlb_handle_folio_put (struct folio *folio) +{ +WARN_ONCE (1 ,"A placeholder that shouldn't trigger. Work in progress." ); +}
mm/guestmem_hugetlb.h new file +9 -0
@@ -0,0 +1,9 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _LINUX_MM_GUESTMEM_HUGETLB_H +#define _LINUX_MM_GUESTMEM_HUGETLB_H + +#include <linux/mm_types.h> + +void guestmem_hugetlb_handle_folio_put (struct folio *folio); + +#endif
mm/swap.c +9 -0
@@ -40,6 +40,10 @@#include "internal.h" +#ifdef CONFIG_GUESTMEM_HUGETLB +#include "guestmem_hugetlb.h" +#endif +#define CREATE_TRACE_POINTS #include <trace/events/pagemap.h>
@@ -101,6 +105,11 @@ static void free_typed_folio(struct folio *folio)case PGTY_hugetlb:free_huge_folio (folio);return ; +#endif +#ifdef CONFIG_GUESTMEM_HUGETLB +case PGTY_guestmem_hugetlb: +guestmem_hugetlb_handle_folio_put (folio); +return ;#endif default :WARN_ON_ONCE (1 );
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 29/51 mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
In reply to Ackerley Tngguestmem_hugetlb is an allocator for guest_memfd. It wraps HugeTLB to provide huge folios for guest_memfd.
This patch also introduces guestmem_allocator_operations as a set of operations that allocators for guest_memfd can provide. In a later patch, guest_memfd will use these operations to manage pages from an allocator.
The allocator operations are memory-management specific and are placed in mm/ so key mm-specific functions do not have to be exposed unnecessarily.
Change-Id: I3cafe111ea7b3c84755d7112ff8f8c541c11136d
--- include/linux/guestmem.h | 20 +++++ include/uapi/linux/guestmem.h | 29 +++++++ mm/Kconfig | 5 +- mm/guestmem_hugetlb.c | 159 ++++++++++++++++++++++++++++++++++ 4 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 include/linux/guestmem.h create mode 100644 include/uapi/linux/guestmem.h
include/linux/guestmem.h new file +20 -0
@@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _LINUX_GUESTMEM_H +#define _LINUX_GUESTMEM_H + +#include <linux/fs.h> + +struct guestmem_allocator_operations { +void *(*inode_setup)(size_t size,u64 flags); +void (*inode_teardown)(void *private,size_t inode_size); +struct folio *(*alloc_folio)(void *private); +/* +* Returns the number of PAGE_SIZE pages in a page that this guestmem +* allocator provides. +*/ +size_t (*nr_pages_in_folio)(void *priv); +}; + +extern const struct guestmem_allocator_operations guestmem_hugetlb_ops; + +#endif
include/uapi/linux/guestmem.h new file +29 -0
@@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _UAPI_LINUX_GUESTMEM_H +#define _UAPI_LINUX_GUESTMEM_H + +/* +* Huge page size must be explicitly defined when using the guestmem_hugetlb +* allocator for guest_memfd. It is the responsibility of the application to +* know which sizes are supported on the running system. See mmap(2) man page +* for details. +*/ + +#define GUESTMEM_HUGETLB_FLAG_SHIFT 58 +#define GUESTMEM_HUGETLB_FLAG_MASK 0x3fUL + +#define GUESTMEM_HUGETLB_FLAG_16KB (14UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_64KB (16UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_512KB (19UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_1MB (20UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_2MB (21UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_8MB (23UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_16MB (24UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_32MB (25UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_256MB (28UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_512MB (29UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_1GB (30UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_2GB (31UL << GUESTMEM_HUGETLB_FLAG_SHIFT) +#define GUESTMEM_HUGETLB_FLAG_16GB (34UL << GUESTMEM_HUGETLB_FLAG_SHIFT) + +#endif /* _UAPI_LINUX_GUESTMEM_H */
mm/Kconfig +4 -1
@@ -1218,7 +1218,10 @@ config SECRETMEM config GUESTMEM_HUGETLB bool "Enable guestmem_hugetlb allocator for guest_memfd" - depends on HUGETLBFS + select GUESTMEM + select HUGETLBFS + select HUGETLB_PAGE + select HUGETLB_PAGE_OPTIMIZE_VMEMMAP help Enable this to make HugeTLB folios available to guest_memfd (KVM virtualization) as backing memory.
mm/guestmem_hugetlb.c +159 -0
168 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 30/51 mm: truncate: Expose truncate_inode_folio()
In reply to Ackerley Tngguest_memfd will be using truncate_inode_folio() to remove folios from guest_memfd's filemap.
--- include/linux/mm.h | 1 + mm/guestmem_hugetlb.c | 2 +- mm/internal.h | 1 - mm/truncate.c | 1 + 4 files changed, 3 insertions(+), 2 deletions(-)
include/linux/mm.h +1 -0
@@ -2530,6 +2530,7 @@ extern void truncate_pagecache(struct inode *inode, loff_t new);extern void truncate_setsize (struct inode *inode,loff_t newsize);void pagecache_isize_extended (struct inode *inode,loff_t from,loff_t to);void truncate_pagecache_range (struct inode *inode,loff_t offset,loff_t end); +int truncate_inode_folio (struct address_space *mapping,struct folio *folio);int generic_error_remove_folio (struct address_space *mapping,struct folio *folio);
mm/guestmem_hugetlb.c +1 -1
@@ -4,12 +4,12 @@* as an allocator for guest_memfd. */ -#include <linux/mm_types.h> #include <linux/guestmem.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/mempolicy.h> #include <linux/mm.h> +#include <linux/mm_types.h> #include <linux/pagemap.h> #include <uapi/linux/guestmem.h>
mm/internal.h +0 -1
@@ -448,7 +448,6 @@ unsigned find_lock_entries(struct address_space *mapping, pgoff_t *start,unsigned find_get_entries (struct address_space *mapping,pgoff_t *start,pgoff_t end,struct folio_batch *fbatch,pgoff_t *indices);void filemap_free_folio (struct address_space *mapping,struct folio *folio); -int truncate_inode_folio (struct address_space *mapping,struct folio *folio);bool truncate_inode_partial_folio (struct folio *folio,loff_t start,loff_t end);long mapping_evict_folio (struct address_space *mapping,struct folio *folio);
mm/truncate.c +1 -0
@@ -176,6 +176,7 @@ int truncate_inode_folio(struct address_space *mapping, struct folio *folio)filemap_remove_folio (folio);return 0 ; } +EXPORT_SYMBOL_GPL (truncate_inode_folio);/* * Handle partial folios. The folio may be entirely within the
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 31/51 KVM: x86: Set disallow_lpage on base_gfn and guest_memfd pgoff misalignment
In reply to Ackerley TngWhen slot->base_gfn and userspace_addr are not aligned wrt each other, large page support is disabled for the entire memslot.
This patch applies the same logic for when slot->base_gfn and gmem.pgoff are not aligned wrt each other.
--- arch/x86/kvm/x86.c | 53 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 9 deletions(-)
arch/x86/kvm/x86.c +44 -9
@@ -12950,6 +12950,46 @@ int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)return 0 ; } +static inline bool kvm_is_level_aligned (u64 value,int level) +{ +return IS_ALIGNED (value,KVM_PAGES_PER_HPAGE (level)); +} + +static inline bool +kvm_should_allow_lpage_for_slot (struct kvm_memory_slot *slot,int level) +{ +bool gfn_and_userspace_addr_aligned; +unsigned long ugfn; + + ugfn = slot->userspace_addr >>PAGE_SHIFT ; + +/* +* If addresses are not aligned wrt each other, then large page mapping +* cannot be allowed for the slot since page tables only allow guest to +* host translations to function at fixed levels. +*/ + gfn_and_userspace_addr_aligned = +kvm_is_level_aligned (slot->base_gfn ^ ugfn, level); + +/* +* If slot->userspace_addr is 0 (disabled), 0 is always aligned so the +* check is deferred to gmem.pgoff. +*/ +if (!gfn_and_userspace_addr_aligned) +return false; + +if (kvm_slot_has_gmem (slot)) { +bool gfn_and_gmem_pgoff_aligned; + + gfn_and_gmem_pgoff_aligned =kvm_is_level_aligned ( + slot->base_gfn ^ slot->gmem.pgoff, level); + +return gfn_and_gmem_pgoff_aligned; + } + +return true; +} +static int kvm_alloc_memslot_metadata (struct kvm *kvm,struct kvm_memory_slot *slot) {
@@ -12971,7 +13011,6 @@ static int kvm_alloc_memslot_metadata(struct kvm *kvm,for (i =1 ; i <KVM_NR_PAGE_SIZES ; ++i) {struct kvm_lpage_info *linfo; -unsigned long ugfn;int lpages;int level = i +1 ;
@@ -12983,16 +13022,12 @@ static int kvm_alloc_memslot_metadata(struct kvm *kvm, slot->arch.lpage_info[i -1 ] = linfo; -if (slot->base_gfn & (KVM_PAGES_PER_HPAGE (level) -1 )) +if (!kvm_is_level_aligned (slot->base_gfn, level)) linfo[0 ].disallow_lpage =1 ; -if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE (level) -1 )) +if (!kvm_is_level_aligned (slot->base_gfn + npages, level)) linfo[lpages -1 ].disallow_lpage =1 ; - ugfn = slot->userspace_addr >>PAGE_SHIFT ; -/* -* If the gfn and userspace address are not aligned wrt each -* other, disable large page support for this slot. -*/ -if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE (level) -1 )) { + +if (!kvm_should_allow_lpage_for_slot (slot, level)) {unsigned long j;for (j =0 ; j < lpages; ++j)
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 32/51 KVM: guest_memfd: Support guestmem_hugetlb as custom allocator
In reply to Ackerley TngThis patch adds support for guestmem_hugetlb as the first custom allocator in guest_memfd.
If requested at guest_memfd creation time, the custom allocator will be used in initialization and cleanup.
Change-Id: I1eb9625dc761ecadcc2aa21480cfdfcf9ab7ce67
--- include/uapi/linux/kvm.h | 1 + virt/kvm/Kconfig | 5 + virt/kvm/guest_memfd.c | 203 +++++++++++++++++++++++++++++++++++++-- 3 files changed, 199 insertions(+), 10 deletions(-)
include/uapi/linux/kvm.h +1 -0
@@ -1571,6 +1571,7 @@ struct kvm_memory_attributes {#define GUEST_MEMFD_FLAG_SUPPORT_SHARED (1UL << 0)#define GUEST_MEMFD_FLAG_INIT_PRIVATE (1UL << 1) +#define GUEST_MEMFD_FLAG_HUGETLB (1UL << 2)struct kvm_create_guest_memfd {__u64 size;
virt/kvm/Kconfig +5 -0
@@ -133,3 +133,8 @@ config KVM_GMEM_SHARED_MEM select KVM_GMEM bool prompt "Enables in-place shared memory for guest_memfd" + +config KVM_GMEM_HUGETLB + select KVM_PRIVATE_MEM + depends on GUESTMEM_HUGETLB + bool "Enables using a custom allocator with guest_memfd, see CONFIG_GUESTMEM_HUGETLB"
virt/kvm/guest_memfd.c +193 -10
284 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 33/51 KVM: guest_memfd: Allocate and truncate from custom allocator
In reply to Ackerley TngIf a custom allocator is requested at guest_memfd creation time, pages from the custom allocator will be used to back guest_memfd.
--- mm/memory.c | 1 + virt/kvm/guest_memfd.c | 142 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 132 insertions(+), 11 deletions(-)
mm/memory.c +1 -0
@@ -7249,6 +7249,7 @@ void folio_zero_user(struct folio *folio, unsigned long addr_hint)else process_huge_page (addr_hint, nr_pages, clear_subpage, folio); } +EXPORT_SYMBOL_GPL (folio_zero_user); static int copy_user_gigantic_page(struct folio *dst, struct folio *src, unsigned long addr_hint,
virt/kvm/guest_memfd.c +131 -11
202 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 34/51 mm: hugetlb: Add functions to add/delete folio from hugetlb lists
In reply to Ackerley TngThese functions are introduced in hugetlb.c so the private hugetlb_lock can be accessed.
These functions will be used in splitting and merging pages in a later patch.
Change-Id: I42f8feda40cbd28e5fd02e54fa58145d847a220e
--- include/linux/hugetlb.h | 2 ++ mm/hugetlb.c | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+)
include/linux/hugetlb.h +2 -0
@@ -156,6 +156,8 @@ bool hugetlb_reserve_pages(struct inode *inode, long from, long to, vm_flags_t vm_flags);long hugetlb_unreserve_pages (struct inode *inode,long start,long end,long freed); +void hugetlb_folio_list_add (struct folio *folio,struct list_head *list); +void hugetlb_folio_list_del (struct folio *folio);bool folio_isolate_hugetlb (struct folio *folio,struct list_head *list);int get_hwpoison_hugetlb_folio (struct folio *folio,bool *hugetlb,bool unpoison); int get_huge_page_for_hwpoison(unsigned long pfn, int flags,
mm/hugetlb.c +22 -0
@@ -7473,6 +7473,28 @@ long hugetlb_unreserve_pages(struct inode *inode, long start, long end,return 0 ; } +void hugetlb_folio_list_add (struct folio *folio,struct list_head *list) +{ +/* +* hstate's hugepage_activelist is guarded by hugetlb_lock, hence hold +* hugetlb_lock while modifying folio-> lru. +*/ +spin_lock_irq (&hugetlb_lock); +list_add (&folio->lru, list); +spin_unlock_irq (&hugetlb_lock); +} + +void hugetlb_folio_list_del (struct folio *folio) +{ +/* +* hstate's hugepage_activelist is guarded by hugetlb_lock, hence hold +* hugetlb_lock while modifying folio-> lru. +*/ +spin_lock_irq (&hugetlb_lock); +list_del (&folio->lru); +spin_unlock_irq (&hugetlb_lock); +} +#ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING static unsigned long page_table_shareable(struct vm_area_struct *svma, struct vm_area_struct *vma,
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 35/51 mm: guestmem_hugetlb: Add support for splitting and merging pages
In reply to Ackerley TngThese functions allow guest_memfd to split and merge HugeTLB pages, and clean them up on freeing the page.
For merging and splitting pages on conversion, guestmem_hugetlb expects the refcount on the pages to already be 0. The caller must ensure that.
For conversions, guest_memfd ensures that the refcounts are already 0 by checking that there are no unexpected refcounts, and then freezing the expected refcounts away. On unexpected refcounts, guest_memfd will return an error to userspace.
For truncation, on unexpected refcounts, guest_memfd will return an error to userspace.
For truncation on closing, guest_memfd will just remove its own refcounts (the filemap refcounts) and mark split pages with PGTY_guestmem_hugetlb.
The presence of PGTY_guestmem_hugetlb will trigger the folio_put() callback to handle further cleanup. This cleanup process will merge pages (with refcount 0, since cleanup is triggered from folio_put()) before returning the pages to HugeTLB.
Since the merging process is long, it is deferred to a worker thread since folio_put() could be called from atomic context.
--- include/linux/guestmem.h | 3 + mm/guestmem_hugetlb.c | 349 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 347 insertions(+), 5 deletions(-)
include/linux/guestmem.h +3 -0
@@ -8,6 +8,9 @@ struct guestmem_allocator_operations {void *(*inode_setup)(size_t size,u64 flags);void (*inode_teardown)(void *private,size_t inode_size);struct folio *(*alloc_folio)(void *private); +int (*split_folio)(struct folio *folio); +void (*merge_folio)(struct folio *folio); +void (*free_folio)(struct folio *folio);/* * Returns the number of PAGE_SIZE pages in a page that this guestmem * allocator provides.
mm/guestmem_hugetlb.c +344 -5
375 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 36/51 mm: Convert split_folio() macro to function
In reply to Ackerley TngThis will prevent the macro from overriding any function and function calls defined as split_folio().
--- include/linux/huge_mm.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
include/linux/huge_mm.h +5 -1
@@ -99,7 +99,11 @@ extern struct kobj_attribute thpsize_shmem_enabled_attr;#define thp_vma_allowable_order (vma, vm_flags, tva_flags, order) \ (!!thp_vma_allowable_orders(vma, vm_flags, tva_flags, BIT(order))) -#define split_folio (f) split_folio_to_list(f, NULL) +int split_folio_to_list (struct folio *folio,struct list_head *list); +static inline int split_folio (struct folio *folio) +{ +return split_folio_to_list (folio,NULL ); +}#ifdef CONFIG_PGTABLE_HAS_HUGE_LEAVES #define HPAGE_PMD_SHIFT PMD_SHIFT
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 37/51 filemap: Pass address_space mapping to ->free_folio()
In reply to Ackerley TngFrom: Elliot Berman <[email protected]>
The plan is to be able to support multiple allocators for guest_memfd folios. To allow each allocator to handle release of a folio from a guest_memfd filemap, ->free_folio() needs to retrieve allocator information that is stored on the guest_memfd inode.
->free_folio() shouldn't assume that folio->mapping is set/valid, and the mapping is well-known to callers of .free_folio(). Hence, pass address_space mapping to ->free_folio() for the callback to retrieve any necessary information.
--- Documentation/filesystems/locking.rst | 2 +- Documentation/filesystems/vfs.rst | 15 +++++++++------ fs/nfs/dir.c | 9 +++++++-- fs/orangefs/inode.c | 3 ++- include/linux/fs.h | 2 +- mm/filemap.c | 9 +++++---- mm/secretmem.c | 3 ++- mm/vmscan.c | 4 ++-- virt/kvm/guest_memfd.c | 3 ++- 9 files changed, 31 insertions(+), 19 deletions(-)
Documentation/filesystems/locking.rst +1 -1
@@ -263,7 +263,7 @@ prototypes:: sector_t (*bmap)(struct address_space *, sector_t); void (*invalidate_folio) (struct folio *, size_t start, size_t len); bool (*release_folio)(struct folio *, gfp_t); - void (*free_folio)(struct folio *); + void (*free_folio)(struct address_space *, struct folio *); int (*direct_IO)(struct kiocb *, struct iov_iter *iter); int (*migrate_folio)(struct address_space *, struct folio *dst, struct folio *src, enum migrate_mode);
Documentation/filesystems/vfs.rst +9 -6
@@ -833,7 +833,7 @@ cache in your filesystem. The following members are defined: sector_t (*bmap)(struct address_space *, sector_t); void (*invalidate_folio) (struct folio *, size_t start, size_t len); bool (*release_folio)(struct folio *, gfp_t); - void (*free_folio)(struct folio *); + void (*free_folio)(struct address_space *, struct folio *); ssize_t (*direct_IO)(struct kiocb *, struct iov_iter *iter); int (*migrate_folio)(struct mapping *, struct folio *dst, struct folio *src, enum migrate_mode);
@@ -1011,11 +1011,14 @@ cache in your filesystem. The following members are defined: clear the uptodate flag if it cannot free private data yet. ``free_folio`` - free_folio is called once the folio is no longer visible in the - page cache in order to allow the cleanup of any private data. - Since it may be called by the memory reclaimer, it should not - assume that the original address_space mapping still exists, and - it should not block. + free_folio is called once the folio is no longer visible in + the page cache in order to allow the cleanup of any private + data. Since it may be called by the memory reclaimer, it + should not assume that the original address_space mapping + still exists at folio->mapping. The mapping the folio used to + belong to is instead passed for free_folio to read any + information it might need from the mapping. free_folio should + not block. ``direct_IO`` called by the generic read/write routines to perform direct_IO -
fs/nfs/dir.c +7 -2
@@ -55,7 +55,7 @@ static int nfs_closedir(struct inode *, struct file *);static int nfs_readdir (struct file *,struct dir_context *);static int nfs_fsync_dir (struct file *,loff_t ,loff_t ,int );static loff_t nfs_llseek_dir (struct file *,loff_t ,int ); -static void nfs_readdir_clear_array (struct folio *); +static void nfs_free_folio (struct address_space *,struct folio *);static int nfs_do_create (struct inode *dir,struct dentry *dentry,umode_t mode,int open_flags);
@@ -69,7 +69,7 @@ const struct file_operations nfs_dir_operations = { };const struct address_space_operations nfs_dir_aops = { - .free_folio = nfs_readdir_clear_array, + .free_folio = nfs_free_folio, };#define NFS_INIT_DTSIZE PAGE_SIZE
@@ -230,6 +230,11 @@ static void nfs_readdir_clear_array(struct folio *folio)kunmap_local (array); } +static void nfs_free_folio (struct address_space *mapping,struct folio *folio) +{ +nfs_readdir_clear_array (folio); +} +static void nfs_readdir_folio_reinit_array (struct folio *folio,u64 last_cookie,u64 change_attr) {
fs/orangefs/inode.c +2 -1
@@ -449,7 +449,8 @@ static bool orangefs_release_folio(struct folio *folio, gfp_t foo)return !folio_test_private (folio); } -static void orangefs_free_folio (struct folio *folio) +static void orangefs_free_folio (struct address_space *mapping, +struct folio *folio) {kfree (folio_detach_private (folio)); }
include/linux/fs.h +1 -1
@@ -455,7 +455,7 @@ struct address_space_operations {sector_t (*bmap)(struct address_space *,sector_t );void (*invalidate_folio) (struct folio *,size_t offset,size_t len);bool (*release_folio)(struct folio *,gfp_t ); -void (*free_folio)(struct folio *folio); +void (*free_folio)(struct address_space *mapping,struct folio *folio);ssize_t (*direct_IO)(struct kiocb *,struct iov_iter *iter);/* * migrate the contents of a folio to the specified target. If
mm/filemap.c +5 -4
@@ -226,11 +226,11 @@ void __filemap_remove_folio(struct folio *folio, void *shadow)void filemap_free_folio (struct address_space *mapping,struct folio *folio) { -void (*free_folio)(struct folio *); +void (*free_folio)(struct address_space *,struct folio *); free_folio = mapping->a_ops->free_folio;if (free_folio) -free_folio (folio); +free_folio (mapping, folio);folio_put_refs (folio,folio_nr_pages (folio)); }
@@ -820,7 +820,8 @@ EXPORT_SYMBOL(file_write_and_wait_range);void replace_page_cache_folio (struct folio *old,struct folio *new) {struct address_space *mapping = old->mapping; -void (*free_folio)(struct folio *) = mapping->a_ops->free_folio; +void (*free_folio)(struct address_space *,struct folio *) = + mapping->a_ops->free_folio;pgoff_t offset = old->index;XA_STATE (xas, &mapping->i_pages, offset);
@@ -849,7 +850,7 @@ void replace_page_cache_folio(struct folio *old, struct folio *new)__lruvec_stat_add_folio (new,NR_SHMEM );xas_unlock_irq (&xas);if (free_folio) -free_folio (old); +free_folio (mapping, old);folio_put (old); }EXPORT_SYMBOL_GPL (replace_page_cache_folio);
mm/secretmem.c +2 -1
@@ -152,7 +152,8 @@ static int secretmem_migrate_folio(struct address_space *mapping,return -EBUSY ; } -static void secretmem_free_folio (struct folio *folio) +static void secretmem_free_folio (struct address_space *mapping, +struct folio *folio) {set_direct_map_default_noflush (&folio->page);folio_zero_segment (folio,0 ,folio_size (folio));
mm/vmscan.c +2 -2
@@ -788,7 +788,7 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio,xa_unlock_irq (&mapping->i_pages);put_swap_folio (folio, swap); }else { -void (*free_folio)(struct folio *); +void (*free_folio)(struct address_space *,struct folio *); free_folio = mapping->a_ops->free_folio;/*
@@ -817,7 +817,7 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio,spin_unlock (&mapping->host->i_lock);if (free_folio) -free_folio (folio); +free_folio (mapping, folio); }return 1 ;
virt/kvm/guest_memfd.c +2 -1
@@ -1319,7 +1319,8 @@ static void kvm_gmem_invalidate(struct folio *folio)static inline void kvm_gmem_invalidate (struct folio *folio) {}#endif -static void kvm_gmem_free_folio (struct folio *folio) +static void kvm_gmem_free_folio (struct address_space *mapping, +struct folio *folio) {folio_clear_unevictable (folio);
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 38/51 KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Ackerley TngIn this patch, newly allocated pages are split to 4K regular pages before providing them to the requester (fallocate() or KVM).
During a private to shared conversion, folios are split if not already split.
During a shared to private conversion, folios are merged if not already merged.
When the folios are removed from the filemap on truncation, the allocator is given a chance to do any necessary prep for when the folio is freed.
When a conversion is requested on a subfolio within a hugepage range, faulting must be prevented on the whole hugepage range for correctness.
See related discussion at
https://lore.kernel.org/all/[email protected]/T/
--- mm/filemap.c | 2 + virt/kvm/guest_memfd.c | 501 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 483 insertions(+), 20 deletions(-)
mm/filemap.c +2 -0
@@ -223,6 +223,7 @@ void __filemap_remove_folio(struct folio *folio, void *shadow)filemap_unaccount_folio (mapping, folio);page_cache_delete (mapping, folio, shadow); } +EXPORT_SYMBOL_GPL (__filemap_remove_folio);void filemap_free_folio (struct address_space *mapping,struct folio *folio) {
@@ -258,6 +259,7 @@ void filemap_remove_folio(struct folio *folio)filemap_free_folio (mapping, folio); } +EXPORT_SYMBOL_GPL (filemap_remove_folio);/* * page_cache_delete_batch - delete several folios from page cache
virt/kvm/guest_memfd.c +481 -20
632 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 39/51 KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)
In reply to Ackerley TngMerge and truncate on fallocate(PUNCH_HOLE), but if the file is being closed, defer merging to folio_put() callback.
--- virt/kvm/guest_memfd.c | 76 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 8 deletions(-)
virt/kvm/guest_memfd.c +68 -8
@@ -859,6 +859,35 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,return ret; } +static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +struct folio *f; +pgoff_t unused; +long num_freed; + +unmap_mapping_pages (inode->i_mapping, index, nr_pages, false); + +if (!kvm_gmem_has_safe_refcount (inode->i_mapping, index, nr_pages, &unused)) +return -EAGAIN ; + + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +return 0 ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); + + num_freed =folio_nr_pages (f); +folio_lock (f); +truncate_inode_folio (inode->i_mapping, f); +folio_unlock (f); + +return num_freed; +} +#else static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
@@ -874,6 +903,12 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode, return 0; } +static long kvm_gmem_merge_truncate_indices (struct inode *inode,pgoff_t index, +size_t nr_pages) +{ +return 0 ; +} +#endif #else
@@ -1182,8 +1217,10 @@ static long kvm_gmem_truncate_indices(struct address_space *mapping,* * Removes folios beginning @index for @nr_pages from filemap in @inode, updates * inode metadata. +* +* Return: 0 on success and negative error otherwise. */ -static void kvm_gmem_truncate_inode_aligned_pages (struct inode *inode, +static long kvm_gmem_truncate_inode_aligned_pages (struct inode *inode,pgoff_t index,size_t nr_pages) {
@@ -1191,19 +1228,34 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,long num_freed;pgoff_t idx;void *priv; +long ret; priv =kvm_gmem_allocator_private (inode); nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + ret =0 ; num_freed =0 ;for (idx = index; idx < index + nr_pages; idx += nr_per_huge_page) { - num_freed +=kvm_gmem_truncate_indices ( - inode->i_mapping, idx, nr_per_huge_page); +if (mapping_exiting (inode->i_mapping) || + !kvm_gmem_has_some_shared (inode, idx, nr_per_huge_page)) { + num_freed +=kvm_gmem_truncate_indices ( + inode->i_mapping, idx, nr_per_huge_page); + }else { + ret =kvm_gmem_merge_truncate_indices (inode, idx, + nr_per_huge_page); +if (ret <0 ) +break ; + + num_freed += ret; + ret =0 ; + } }spin_lock (&inode->i_lock); inode->i_blocks -= (num_freed <<PAGE_SHIFT ) /512 ;spin_unlock (&inode->i_lock); + +return ret; }/**
@@ -1252,8 +1304,10 @@ static void kvm_gmem_zero_range(struct address_space *mapping,* * Removes full (huge)pages from the filemap and zeroing incomplete * (huge)pages. The pages in the range may be split. +* +* Return: 0 on success and negative error otherwise. */ -static void kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart, +static long kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart,loff_t lend) {pgoff_t full_hpage_start;
@@ -1263,6 +1317,7 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,pgoff_t start;pgoff_t end;void *priv; +long ret; priv =kvm_gmem_allocator_private (inode); nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv);
@@ -1279,10 +1334,11 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,kvm_gmem_zero_range (inode->i_mapping, start, zero_end); } + ret =0 ;if (full_hpage_end > full_hpage_start) { nr_pages = full_hpage_end - full_hpage_start; -kvm_gmem_truncate_inode_aligned_pages (inode, full_hpage_start, - nr_pages); + ret =kvm_gmem_truncate_inode_aligned_pages ( + inode, full_hpage_start, nr_pages); }if (end > full_hpage_end && end > full_hpage_start) {
@@ -1290,6 +1346,8 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,kvm_gmem_zero_range (inode->i_mapping, zero_start, end); } + +return ret; }static long kvm_gmem_punch_hole (struct inode *inode,loff_t offset,loff_t len)
@@ -1298,6 +1356,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)pgoff_t start = offset >>PAGE_SHIFT ;pgoff_t end = (offset + len) >>PAGE_SHIFT ;struct kvm_gmem *gmem; +long ret;/* * Bindings must be stable across invalidation to ensure the start+end
@@ -1308,8 +1367,9 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_begin_and_zap (gmem, start, end); + ret =0 ;if (kvm_gmem_has_custom_allocator (inode)) { -kvm_gmem_truncate_inode_range (inode, offset, offset + len); + ret =kvm_gmem_truncate_inode_range (inode, offset, offset + len); }else {/* Page size is PAGE_SIZE, so use optimized truncation function. */ truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 );
@@ -1320,7 +1380,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)filemap_invalidate_unlock (inode->i_mapping); -return 0 ; +return ret; }static long kvm_gmem_allocate (struct inode *inode,loff_t offset,loff_t len)
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 40/51 KVM: guest_memfd: Update kvm_gmem_mapping_order to account for page status
In reply to Ackerley Tngkvm_gmem_mapping_order() should return the maximum mapping order for a gfn if a page were to be faulted in for that gfn.
For inodes that support a custom allocator, the maximum mapping order should be determined by the custom allocator in conjunction with guest_memfd.
This patch updates kvm_gmem_mapping_order() to take into account that for the guestmem_hugetlb custom allocator, pages are split if any page in a huge page range is shared.
--- virt/kvm/guest_memfd.c | 72 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 62 insertions(+), 10 deletions(-)
virt/kvm/guest_memfd.c +62 -10
@@ -709,19 +709,27 @@ static int kvm_gmem_split_folio_in_filemap(struct inode *inode, struct folio *foreturn ret; } +static inline bool kvm_gmem_should_split_at_index (struct inode *inode, +pgoff_t index) +{ +pgoff_t index_floor; +size_t nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + index_floor =round_down (index, nr_pages); + +return kvm_gmem_has_some_shared (inode, index_floor, nr_pages); +} +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode,struct folio *folio) { -size_t to_nr_pages; -void *priv; -if (!kvm_gmem_has_custom_allocator (inode))return 0 ; - priv =kvm_gmem_allocator_private (inode); - to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); - -if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages)) +if (kvm_gmem_should_split_at_index (inode, folio->index))return kvm_gmem_split_folio_in_filemap (inode, folio);return 0 ;
@@ -890,6 +898,12 @@ static long kvm_gmem_merge_truncate_indices(struct inode *inode, pgoff_t index,#else +static inline bool kvm_gmem_should_split_at_index (struct inode *inode, +pgoff_t index) +{ +return false; +} +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode,struct folio *folio) {
@@ -1523,7 +1537,7 @@ static inline struct file *kvm_gmem_get_file(struct kvm_memory_slot *slot)return get_file_active (&slot->gmem.file); } -static pgoff_t kvm_gmem_get_index (struct kvm_memory_slot *slot,gfn_t gfn) +static pgoff_t kvm_gmem_get_index (const struct kvm_memory_slot *slot,gfn_t gfn) {return gfn - slot->base_gfn + slot->gmem.pgoff; }
@@ -2256,14 +2270,52 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,EXPORT_SYMBOL_GPL (kvm_gmem_get_pfn);/** -* Returns the mapping order for this @gfn in @slot. +* kvm_gmem_mapping_order() - Get the mapping order for this @gfn in @slot. +* +* @slot: the memslot that gfn belongs to. +* @gfn: the gfn to look up mapping order for. * * This is equal to max_order that would be returned if kvm_gmem_get_pfn() were * called now. +* +* Return: the mapping order for this @gfn in @slot. */ int kvm_gmem_mapping_order (const struct kvm_memory_slot *slot,gfn_t gfn) { -return 0 ; +struct inode *inode; +struct file *file; +int ret; + + file =kvm_gmem_get_file ((struct kvm_memory_slot *)slot); +if (!file) +return 0 ; + + inode =file_inode (file); + + ret =0 ; +if (kvm_gmem_has_custom_allocator (inode)) { +bool should_split; +pgoff_t index; + + index =kvm_gmem_get_index (slot, gfn); + +filemap_invalidate_lock_shared (inode->i_mapping); + should_split =kvm_gmem_should_split_at_index (inode, index); +filemap_invalidate_unlock_shared (inode->i_mapping); + +if (!should_split) { +size_t nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + ret =ilog2 (nr_pages); + } + } + +fput (file); +return ret; }EXPORT_SYMBOL_GPL (kvm_gmem_mapping_order);
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 41/51 KVM: Add CAP to indicate support for HugeTLB as custom allocator
In reply to Ackerley TngIf this CAP returns true, then guestmem_hugetlb can be used as a custom allocator for guest_memfd.
--- include/uapi/linux/kvm.h | 1 + virt/kvm/kvm_main.c | 4 ++++ 2 files changed, 5 insertions(+)
include/uapi/linux/kvm.h +1 -0
@@ -932,6 +932,7 @@ struct kvm_enable_cap {#define KVM_CAP_ARM_WRITABLE_IMP_ID_REGS 239#define KVM_CAP_GMEM_SHARED_MEM 240#define KVM_CAP_GMEM_CONVERSION 241 +#define KVM_CAP_GMEM_HUGETLB 242struct kvm_irq_routing_irqchip {__u32 irqchip;
virt/kvm/kvm_main.c +4 -0
@@ -4845,6 +4845,10 @@ static int kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)case KVM_CAP_GMEM_SHARED_MEM :case KVM_CAP_GMEM_CONVERSION :return true; +#endif +#ifdef CONFIG_KVM_GMEM_HUGETLB +case KVM_CAP_GMEM_HUGETLB : +return true;#endif default :break ;
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 42/51 KVM: selftests: Add basic selftests for hugetlb-backed guest_memfd
In reply to Ackerley TngAdd tests for 2MB and 1GB page sizes, and update the invalid flags test for GUEST_MEMFD_FLAG_HUGETLB.
In tests, touch every page but not every byte in page to save time while testing.
--- .../testing/selftests/kvm/guest_memfd_test.c | 94 +++++++++++++------ 1 file changed, 67 insertions(+), 27 deletions(-)
tools/testing/selftests/kvm/guest_memfd_test.c +67 -27
@@ -13,6 +13,8 @@#include <linux/bitmap.h> #include <linux/falloc.h> +#include <linux/guestmem.h> +#include <linux/sizes.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h>
@@ -38,6 +40,7 @@ static void test_file_read_write(int fd)static void test_faulting_allowed (int fd,size_t page_size,size_t total_size) {const char val =0xaa ; +size_t increment;char *mem;size_t i;int ret;
@@ -45,21 +48,25 @@ static void test_faulting_allowed(int fd, size_t page_size, size_t total_size) mem =mmap (NULL , total_size,PROT_READ |PROT_WRITE ,MAP_SHARED , fd,0 );TEST_ASSERT (mem !=MAP_FAILED ,"mmaping() guest memory should pass." ); -memset (mem, val, total_size); -for (i =0 ; i < total_size; i++) + increment = page_size >>1 ; + +for (i =0 ; i < total_size; i += increment) + mem[i] = val; +for (i =0 ; i < total_size; i += increment)TEST_ASSERT_EQ (mem[i], val); ret =fallocate (fd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE ,0 , page_size);TEST_ASSERT (!ret,"fallocate the first page should succeed" ); -for (i =0 ; i < page_size; i++) +for (i =0 ; i < page_size; i += increment)TEST_ASSERT_EQ (mem[i],0x00 ); -for (; i < total_size; i++) +for (; i < total_size; i += increment)TEST_ASSERT_EQ (mem[i], val); -memset (mem, val, total_size); -for (i =0 ; i < total_size; i++) +for (i =0 ; i < total_size; i += increment) + mem[i] = val; +for (i =0 ; i < total_size; i += increment)TEST_ASSERT_EQ (mem[i], val); ret =munmap (mem, total_size);
@@ -209,7 +216,7 @@ static void test_create_guest_memfd_invalid_sizes(struct kvm_vm *vm,size_t size;int fd; -for (size =1 ; size < page_size; size++) { +for (size =1 ; size < page_size; size += (page_size >>1 )) { fd =__vm_create_guest_memfd (vm, size, guest_memfd_flags); TEST_ASSERT(fd == -1 && errno == EINVAL, "guest_memfd() with non-page-aligned page size '0x%lx' should fail with EINVAL",
@@ -217,28 +224,33 @@ static void test_create_guest_memfd_invalid_sizes(struct kvm_vm *vm, } } -static void test_create_guest_memfd_multiple (struct kvm_vm *vm) +static void test_create_guest_memfd_multiple (struct kvm_vm *vm, +uint64_t guest_memfd_flags, +size_t page_size) {int fd1, fd2, ret;struct stat st1, st2; - fd1 =__vm_create_guest_memfd (vm,4096 ,0 ); + fd1 =__vm_create_guest_memfd (vm, page_size, guest_memfd_flags);TEST_ASSERT (fd1 !=-1 ,"memfd creation should succeed" ); ret =fstat (fd1, &st1);TEST_ASSERT (ret !=-1 ,"memfd fstat should succeed" ); -TEST_ASSERT (st1.st_size ==4096 ,"memfd st_size should match requested size" ); +TEST_ASSERT (st1.st_size == page_size,"memfd st_size should match requested size" ); - fd2 =__vm_create_guest_memfd (vm,8192 ,0 ); + fd2 =__vm_create_guest_memfd (vm, page_size *2 , guest_memfd_flags);TEST_ASSERT (fd2 !=-1 ,"memfd creation should succeed" ); ret =fstat (fd2, &st2);TEST_ASSERT (ret !=-1 ,"memfd fstat should succeed" ); -TEST_ASSERT (st2.st_size ==8192 ,"second memfd st_size should match requested size" ); +TEST_ASSERT (st2.st_size == page_size *2 , +"second memfd st_size should match requested size" ); + ret =fstat (fd1, &st1);TEST_ASSERT (ret !=-1 ,"memfd fstat should succeed" ); -TEST_ASSERT (st1.st_size ==4096 ,"first memfd st_size should still match requested size" ); +TEST_ASSERT (st1.st_size == page_size, +"first memfd st_size should still match requested size" );TEST_ASSERT (st1.st_ino != st2.st_ino,"different memfd should have different inode numbers" );close (fd2);
@@ -449,21 +461,13 @@ static void test_guest_memfd_features(struct kvm_vm *vm, size_t page_size,close (fd); } -static void test_with_type (unsigned long vm_type,uint64_t guest_memfd_flags, -bool expect_mmap_allowed) +static void test_guest_memfd_features_for_page_size (struct kvm_vm *vm, +uint64_t guest_memfd_flags, +size_t page_size, +bool expect_mmap_allowed) { -struct kvm_vm *vm; -size_t page_size; +test_create_guest_memfd_multiple (vm, guest_memfd_flags, page_size); -if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type))) -return ; - - vm =vm_create_barebones_type (vm_type); - -test_create_guest_memfd_multiple (vm); -test_bind_guest_memfd_wrt_userspace_addr (vm); - - page_size =getpagesize ();if (guest_memfd_flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED ) {test_guest_memfd_features (vm, page_size, guest_memfd_flags, expect_mmap_allowed, true);
@@ -479,6 +483,34 @@ static void test_with_type(unsigned long vm_type, uint64_t guest_memfd_flags,test_guest_memfd_features (vm, page_size, guest_memfd_flags, expect_mmap_allowed, false); } +} + +static void test_with_type (unsigned long vm_type,uint64_t base_flags, +bool expect_mmap_allowed) +{ +struct kvm_vm *vm; +uint64_t flags; + +if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type))) +return ; + + vm =vm_create_barebones_type (vm_type); + +test_bind_guest_memfd_wrt_userspace_addr (vm); + +printf ("Test guest_memfd with 4K pages for vm_type %ld\n" , vm_type); +test_guest_memfd_features_for_page_size (vm, base_flags,getpagesize (), expect_mmap_allowed); +printf ("\tPASSED\n" ); + +printf ("Test guest_memfd with 2M pages for vm_type %ld\n" , vm_type); + flags = base_flags |GUEST_MEMFD_FLAG_HUGETLB |GUESTMEM_HUGETLB_FLAG_2MB ; +test_guest_memfd_features_for_page_size (vm, flags,SZ_2M , expect_mmap_allowed); +printf ("\tPASSED\n" ); + +printf ("Test guest_memfd with 1G pages for vm_type %ld\n" , vm_type); + flags = base_flags |GUEST_MEMFD_FLAG_HUGETLB |GUESTMEM_HUGETLB_FLAG_1GB ; +test_guest_memfd_features_for_page_size (vm, flags,SZ_1G , expect_mmap_allowed); +printf ("\tPASSED\n" );kvm_vm_release (vm); }
@@ -486,9 +518,14 @@ static void test_with_type(unsigned long vm_type, uint64_t guest_memfd_flags,static void test_vm_with_gmem_flag (struct kvm_vm *vm,uint64_t flag,bool expect_valid) { -size_t page_size =getpagesize (); +size_t page_size;int fd; +if (flag ==GUEST_MEMFD_FLAG_HUGETLB ) + page_size =get_def_hugetlb_pagesz (); +else + page_size =getpagesize (); + fd =__vm_create_guest_memfd (vm, page_size, flag);if (expect_valid) {
@@ -550,6 +587,9 @@ static void test_gmem_flag_validity(void)/* After conversions are supported, all VM types support shared mem. */ uint64_t valid_flags =GUEST_MEMFD_FLAG_SUPPORT_SHARED ; +if (kvm_has_cap (KVM_CAP_GMEM_HUGETLB )) + valid_flags |=GUEST_MEMFD_FLAG_HUGETLB ; +test_vm_type_gmem_flag_validity (VM_TYPE_DEFAULT , valid_flags);#ifdef __x86_64__
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 43/51 KVM: selftests: Update conversion flows test for HugeTLB
In reply to Ackerley TngThis patch updates conversion flows test to use GUEST_MEMFD_FLAG_HUGETLB and tests with the 2MB and 1GB sizes.
--- .../kvm/guest_memfd_conversions_test.c | 171 ++++++++++-------- 1 file changed, 98 insertions(+), 73 deletions(-)
tools/testing/selftests/kvm/guest_memfd_conversions_test.c +98 -73
@@ -5,6 +5,7 @@* Copyright (c) 2024, Google LLC. */ #include <linux/kvm.h> +#include <linux/sizes.h> #include <stdio.h> #include <string.h> #include <sys/mman.h>
@@ -228,6 +229,11 @@ static struct kvm_vm *setup_test(size_t test_page_size, bool init_private,if (init_private) flags |=GUEST_MEMFD_FLAG_INIT_PRIVATE ; +if (test_page_size ==SZ_2M ) + flags |=GUEST_MEMFD_FLAG_HUGETLB |GUESTMEM_HUGETLB_FLAG_2MB ; +else if (test_page_size ==SZ_1G ) + flags |=GUEST_MEMFD_FLAG_HUGETLB |GUESTMEM_HUGETLB_FLAG_1GB ; + *guest_memfd =vm_create_guest_memfd (vm, test_page_size, flags);TEST_ASSERT (*guest_memfd >0 ,"guest_memfd creation failed" );
@@ -249,79 +255,80 @@ static void cleanup_test(size_t guest_memfd_size, struct kvm_vm *vm,TEST_ASSERT_EQ (close (guest_memfd),0 ); } -static void test_sharing (void ) +static void test_sharing (size_t test_page_size) {struct kvm_vcpu *vcpu;struct kvm_vm *vm;int guest_memfd;char *mem; - vm =setup_test (PAGE_SIZE ,/*init_private=*/ false, &vcpu, &guest_memfd, &mem); + vm =setup_test (test_page_size,/*init_private=*/ false, &vcpu, &guest_memfd, &mem);host_use_memory (mem,'X' ,'A' );guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'A' ,'B' ,0 );/* Toggle private flag of memory attributes and run the test again. */ -guest_memfd_convert_private (guest_memfd,0 ,PAGE_SIZE ); +guest_memfd_convert_private (guest_memfd,0 , test_page_size);assert_host_cannot_fault (mem);guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'B' ,'C' ,0 ); -guest_memfd_convert_shared (guest_memfd,0 ,PAGE_SIZE ); +guest_memfd_convert_shared (guest_memfd,0 , test_page_size);host_use_memory (mem,'C' ,'D' );guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'D' ,'E' ,0 ); -cleanup_test (PAGE_SIZE , vm, guest_memfd, mem); +cleanup_test (test_page_size, vm, guest_memfd, mem); } -static void test_init_mappable_false (void ) +static void test_init_mappable_false (size_t test_page_size) {struct kvm_vcpu *vcpu;struct kvm_vm *vm;int guest_memfd;char *mem; - vm =setup_test (PAGE_SIZE ,/*init_private=*/ true, &vcpu, &guest_memfd, &mem); + vm =setup_test (test_page_size,/*init_private=*/ true, &vcpu, &guest_memfd, &mem);assert_host_cannot_fault (mem);guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'X' ,'A' ,0 ); -guest_memfd_convert_shared (guest_memfd,0 ,PAGE_SIZE ); +guest_memfd_convert_shared (guest_memfd,0 , test_page_size);host_use_memory (mem,'A' ,'B' );guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'B' ,'C' ,0 ); -cleanup_test (PAGE_SIZE , vm, guest_memfd, mem); +cleanup_test (test_page_size, vm, guest_memfd, mem); }/* * Test that even if there are no folios yet, conversion requests are recorded * in guest_memfd. */ -static void test_conversion_before_allocation (void ) +static void test_conversion_before_allocation (size_t test_page_size) {struct kvm_vcpu *vcpu;struct kvm_vm *vm;int guest_memfd;char *mem; - vm =setup_test (PAGE_SIZE ,/*init_private=*/ false, &vcpu, &guest_memfd, &mem); + vm =setup_test (test_page_size,/*init_private=*/ false, &vcpu, &guest_memfd, &mem); -guest_memfd_convert_private (guest_memfd,0 ,PAGE_SIZE ); +guest_memfd_convert_private (guest_memfd,0 , test_page_size);assert_host_cannot_fault (mem);guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'X' ,'A' ,0 ); -guest_memfd_convert_shared (guest_memfd,0 ,PAGE_SIZE ); +guest_memfd_convert_shared (guest_memfd,0 , test_page_size);host_use_memory (mem,'A' ,'B' );guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'B' ,'C' ,0 ); -cleanup_test (PAGE_SIZE , vm, guest_memfd, mem); +cleanup_test (test_page_size, vm, guest_memfd, mem); } -static void __test_conversion_if_not_all_folios_allocated (int total_nr_pages, +static void __test_conversion_if_not_all_folios_allocated (size_t test_page_size, +int total_nr_pages,int page_to_fault) {const int second_page_to_fault =8 ;
@@ -332,15 +339,15 @@ static void __test_conversion_if_not_all_folios_allocated(int total_nr_pages,char *mem;int i; - total_size =PAGE_SIZE * total_nr_pages; + total_size = test_page_size * total_nr_pages; vm =setup_test (total_size,/*init_private=*/ false, &vcpu, &guest_memfd, &mem);/* * Fault 2 of the pages to test filemap range operations except when * page_to_fault == second_page_to_fault. */ -host_use_memory (mem + page_to_fault *PAGE_SIZE ,'X' ,'A' ); -host_use_memory (mem + second_page_to_fault *PAGE_SIZE ,'X' ,'A' ); +host_use_memory (mem + page_to_fault * test_page_size,'X' ,'A' ); +host_use_memory (mem + second_page_to_fault * test_page_size,'X' ,'A' );guest_memfd_convert_private (guest_memfd,0 , total_size);
@@ -348,37 +355,37 @@ static void __test_conversion_if_not_all_folios_allocated(int total_nr_pages,bool is_faulted;char expected; -assert_host_cannot_fault (mem + i *PAGE_SIZE ); +assert_host_cannot_fault (mem + i * test_page_size); is_faulted = i == page_to_fault || i == second_page_to_fault; expected = is_faulted ?'A' :'X' ;guest_use_memory (vcpu, -GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +GUEST_MEMFD_SHARING_TEST_GVA + i * test_page_size, expected,'B' ,0 ); }guest_memfd_convert_shared (guest_memfd,0 , total_size);for (i =0 ; i < total_nr_pages; ++i) { -host_use_memory (mem + i *PAGE_SIZE ,'B' ,'C' ); +host_use_memory (mem + i * test_page_size,'B' ,'C' );guest_use_memory (vcpu, -GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +GUEST_MEMFD_SHARING_TEST_GVA + i * test_page_size,'C' ,'D' ,0 ); }cleanup_test (total_size, vm, guest_memfd, mem); } -static void test_conversion_if_not_all_folios_allocated (void ) +static void test_conversion_if_not_all_folios_allocated (size_t test_page_size) {const int total_nr_pages =16 ;int i;for (i =0 ; i < total_nr_pages; ++i) -__test_conversion_if_not_all_folios_allocated (total_nr_pages, i); +__test_conversion_if_not_all_folios_allocated (test_page_size, total_nr_pages, i); } -static void test_conversions_should_not_affect_surrounding_pages (void ) +static void test_conversions_should_not_affect_surrounding_pages (size_t test_page_size) {struct kvm_vcpu *vcpu;int page_to_convert;
@@ -391,40 +398,40 @@ static void test_conversions_should_not_affect_surrounding_pages(void) page_to_convert =2 ; nr_pages =4 ; - total_size =PAGE_SIZE * nr_pages; + total_size = test_page_size * nr_pages; vm =setup_test (total_size,/*init_private=*/ false, &vcpu, &guest_memfd, &mem);for (i =0 ; i < nr_pages; ++i) { -host_use_memory (mem + i *PAGE_SIZE ,'X' ,'A' ); -guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +host_use_memory (mem + i * test_page_size,'X' ,'A' ); +guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA + i * test_page_size,'A' ,'B' ,0 ); } -guest_memfd_convert_private (guest_memfd,PAGE_SIZE * page_to_convert,PAGE_SIZE ); +guest_memfd_convert_private (guest_memfd, test_page_size * page_to_convert, test_page_size);for (i =0 ; i < nr_pages; ++i) {char to_check;if (i == page_to_convert) { -assert_host_cannot_fault (mem + i *PAGE_SIZE ); +assert_host_cannot_fault (mem + i * test_page_size); to_check ='B' ; }else { -host_use_memory (mem + i *PAGE_SIZE ,'B' ,'C' ); +host_use_memory (mem + i * test_page_size,'B' ,'C' ); to_check ='C' ; } -guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA + i * test_page_size, to_check,'D' ,0 ); } -guest_memfd_convert_shared (guest_memfd,PAGE_SIZE * page_to_convert,PAGE_SIZE ); +guest_memfd_convert_shared (guest_memfd, test_page_size * page_to_convert, test_page_size);for (i =0 ; i < nr_pages; ++i) { -host_use_memory (mem + i *PAGE_SIZE ,'D' ,'E' ); -guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +host_use_memory (mem + i * test_page_size,'D' ,'E' ); +guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA + i * test_page_size,'E' ,'F' ,0 ); }
@@ -432,7 +439,7 @@ static void test_conversions_should_not_affect_surrounding_pages(void) }static void __test_conversions_should_fail_if_memory_has_elevated_refcount ( -int nr_pages,int page_to_convert) +size_t test_page_size,int nr_pages,int page_to_convert) {struct kvm_vcpu *vcpu;loff_t error_offset;
@@ -443,50 +450,50 @@ static void __test_conversions_should_fail_if_memory_has_elevated_refcount(int ret;int i; - total_size =PAGE_SIZE * nr_pages; + total_size = test_page_size * nr_pages; vm =setup_test (total_size,/*init_private=*/ false, &vcpu, &guest_memfd, &mem); -pin_pages (mem + page_to_convert *PAGE_SIZE ,PAGE_SIZE ); +pin_pages (mem + page_to_convert * test_page_size, test_page_size);for (i =0 ; i < nr_pages; i++) { -host_use_memory (mem + i *PAGE_SIZE ,'X' ,'A' ); -guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +host_use_memory (mem + i * test_page_size,'X' ,'A' ); +guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA + i * test_page_size,'A' ,'B' ,0 ); } error_offset =0 ; - ret =__guest_memfd_convert_private (guest_memfd, page_to_convert *PAGE_SIZE , -PAGE_SIZE , &error_offset); + ret =__guest_memfd_convert_private (guest_memfd, page_to_convert * test_page_size, + test_page_size, &error_offset);TEST_ASSERT_EQ (ret,-1 );TEST_ASSERT_EQ (errno,EAGAIN ); -TEST_ASSERT_EQ (error_offset, page_to_convert *PAGE_SIZE ); +TEST_ASSERT_EQ (error_offset, page_to_convert * test_page_size);unpin_pages (); -guest_memfd_convert_private (guest_memfd, page_to_convert *PAGE_SIZE ,PAGE_SIZE ); +guest_memfd_convert_private (guest_memfd, page_to_convert * test_page_size, test_page_size);for (i =0 ; i < nr_pages; i++) {char expected;if (i == page_to_convert) -assert_host_cannot_fault (mem + i *PAGE_SIZE ); +assert_host_cannot_fault (mem + i * test_page_size);else -host_use_memory (mem + i *PAGE_SIZE ,'B' ,'C' ); +host_use_memory (mem + i * test_page_size,'B' ,'C' ); expected = i == page_to_convert ?'X' :'C' ; -guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA + i * test_page_size, expected,'D' ,0 ); } -guest_memfd_convert_shared (guest_memfd, page_to_convert *PAGE_SIZE ,PAGE_SIZE ); +guest_memfd_convert_shared (guest_memfd, page_to_convert * test_page_size, test_page_size);for (i =0 ; i < nr_pages; i++) {char expected = i == page_to_convert ?'X' :'D' ; -host_use_memory (mem + i *PAGE_SIZE , expected,'E' ); +host_use_memory (mem + i * test_page_size, expected,'E' );guest_use_memory (vcpu, -GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +GUEST_MEMFD_SHARING_TEST_GVA + i * test_page_size,'E' ,'F' ,0 ); }
@@ -496,15 +503,18 @@ static void __test_conversions_should_fail_if_memory_has_elevated_refcount(* This test depends on CONFIG_GUP_TEST to provide a kernel module that exposes * pin_user_pages() to userspace. */ -static void test_conversions_should_fail_if_memory_has_elevated_refcount (void ) +static void test_conversions_should_fail_if_memory_has_elevated_refcount ( +size_t test_page_size) {int i; -for (i =0 ; i <4 ; i++) -__test_conversions_should_fail_if_memory_has_elevated_refcount (4 , i); +for (i =0 ; i <4 ; i++) { +__test_conversions_should_fail_if_memory_has_elevated_refcount ( + test_page_size,4 , i); + } } -static void test_truncate_should_not_change_mappability (void ) +static void test_truncate_should_not_change_mappability (size_t test_page_size) {struct kvm_vcpu *vcpu;struct kvm_vm *vm;
@@ -512,40 +522,40 @@ static void test_truncate_should_not_change_mappability(void)char *mem;int ret; - vm =setup_test (PAGE_SIZE ,/*init_private=*/ false, &vcpu, &guest_memfd, &mem); + vm =setup_test (test_page_size,/*init_private=*/ false, &vcpu, &guest_memfd, &mem);host_use_memory (mem,'X' ,'A' ); ret =fallocate (guest_memfd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , -0 ,PAGE_SIZE ); +0 , test_page_size);TEST_ASSERT (!ret,"truncating the first page should succeed" );host_use_memory (mem,'X' ,'A' ); -guest_memfd_convert_private (guest_memfd,0 ,PAGE_SIZE ); +guest_memfd_convert_private (guest_memfd,0 , test_page_size);assert_host_cannot_fault (mem);guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'A' ,'A' ,0 ); ret =fallocate (guest_memfd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , -0 ,PAGE_SIZE ); +0 , test_page_size);TEST_ASSERT (!ret,"truncating the first page should succeed" );assert_host_cannot_fault (mem);guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'X' ,'A' ,0 ); -cleanup_test (PAGE_SIZE , vm, guest_memfd, mem); +cleanup_test (test_page_size, vm, guest_memfd, mem); } -static void test_fault_type_independent_of_mem_attributes (void ) +static void test_fault_type_independent_of_mem_attributes (size_t test_page_size) {struct kvm_vcpu *vcpu;struct kvm_vm *vm;int guest_memfd;char *mem; - vm =setup_test (PAGE_SIZE ,/*init_private=*/ true, &vcpu, &guest_memfd, &mem); -vm_mem_set_shared (vm,GUEST_MEMFD_SHARING_TEST_GPA ,PAGE_SIZE ); + vm =setup_test (test_page_size,/*init_private=*/ true, &vcpu, &guest_memfd, &mem); +vm_mem_set_shared (vm,GUEST_MEMFD_SHARING_TEST_GPA , test_page_size);/* * kvm->mem_attr_array set to shared, guest_memfd memory initialized as
@@ -558,8 +568,8 @@ static void test_fault_type_independent_of_mem_attributes(void)/* Guest can fault and use memory. */ guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'X' ,'A' ,0 ); -guest_memfd_convert_shared (guest_memfd,0 ,PAGE_SIZE ); -vm_mem_set_private (vm,GUEST_MEMFD_SHARING_TEST_GPA ,PAGE_SIZE ); +guest_memfd_convert_shared (guest_memfd,0 , test_page_size); +vm_mem_set_private (vm,GUEST_MEMFD_SHARING_TEST_GPA , test_page_size);/* Host can use shared memory. */ host_use_memory (mem,'X' ,'A' );
@@ -567,7 +577,19 @@ static void test_fault_type_independent_of_mem_attributes(void)/* Guest can also use shared memory. */ guest_use_memory (vcpu,GUEST_MEMFD_SHARING_TEST_GVA ,'X' ,'A' ,0 ); -cleanup_test (PAGE_SIZE , vm, guest_memfd, mem); +cleanup_test (test_page_size, vm, guest_memfd, mem); +} + +static void test_with_size (size_t test_page_size) +{ +test_sharing (test_page_size); +test_init_mappable_false (test_page_size); +test_conversion_before_allocation (test_page_size); +test_conversion_if_not_all_folios_allocated (test_page_size); +test_conversions_should_not_affect_surrounding_pages (test_page_size); +test_truncate_should_not_change_mappability (test_page_size); +test_conversions_should_fail_if_memory_has_elevated_refcount (test_page_size); +test_fault_type_independent_of_mem_attributes (test_page_size); }int main (int argc,char *argv[])
@@ -576,14 +598,17 @@ int main(int argc, char *argv[])TEST_REQUIRE (kvm_check_cap (KVM_CAP_GMEM_SHARED_MEM ));TEST_REQUIRE (kvm_check_cap (KVM_CAP_GMEM_CONVERSION )); -test_sharing (); -test_init_mappable_false (); -test_conversion_before_allocation (); -test_conversion_if_not_all_folios_allocated (); -test_conversions_should_not_affect_surrounding_pages (); -test_truncate_should_not_change_mappability (); -test_conversions_should_fail_if_memory_has_elevated_refcount (); -test_fault_type_independent_of_mem_attributes (); +printf ("Test guest_memfd with 4K pages\n" ); +test_with_size (PAGE_SIZE ); +printf ("\tPASSED\n" ); + +printf ("Test guest_memfd with 2M pages\n" ); +test_with_size (SZ_2M ); +printf ("\tPASSED\n" ); + +printf ("Test guest_memfd with 1G pages\n" ); +test_with_size (SZ_1G ); +printf ("\tPASSED\n" );return 0 ; }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 44/51 KVM: selftests: Test truncation paths of guest_memfd
In reply to Ackerley TngWhen guest_memfd folios are truncated, if pages are split, they have to be merged.
For truncations, userspace will get an error if there are unexpected refcounts on the folios.
For truncation on closing, kernel will handle the merging even if there are unexpected refcounts on the folios.
This patch tests the above two scenarios.
--- .../kvm/guest_memfd_conversions_test.c | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+)
tools/testing/selftests/kvm/guest_memfd_conversions_test.c +95 -0
@@ -4,6 +4,7 @@* * Copyright (c) 2024, Google LLC. */ +#include <linux/guestmem.h> #include <linux/kvm.h> #include <linux/sizes.h> #include <stdio.h>
@@ -580,6 +581,97 @@ static void test_fault_type_independent_of_mem_attributes(size_t test_page_size)cleanup_test (test_page_size, vm, guest_memfd, mem); } +static void test_truncate_shared_while_pinned (size_t test_page_size) +{ +struct kvm_vcpu *vcpu; +struct kvm_vm *vm; +int guest_memfd; +char *mem; +int ret; + + vm =setup_test (test_page_size,/*init_private=*/ false, &vcpu, + &guest_memfd, &mem); + + ret =fallocate (guest_memfd,FALLOC_FL_KEEP_SIZE ,0 , test_page_size); +TEST_ASSERT (!ret,"fallocate should have succeeded" ); + +pin_pages (mem, test_page_size); + + ret =fallocate (guest_memfd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , +0 , test_page_size); +if (test_page_size ==PAGE_SIZE ) { +TEST_ASSERT (!ret,"truncate should have succeeded since there is no need to merge" ); + }else { +TEST_ASSERT (ret,"truncate should have failed since pages are pinned" ); +TEST_ASSERT_EQ (errno,EAGAIN ); + } + +unpin_pages (); + + ret =fallocate (guest_memfd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , +0 , test_page_size); +TEST_ASSERT (!ret,"truncate should succeed now that pages are unpinned" ); + +cleanup_test (test_page_size, vm, guest_memfd, mem); +} + +static void test_truncate_private (size_t test_page_size) +{ +struct kvm_vcpu *vcpu; +struct kvm_vm *vm; +int guest_memfd; +char *mem; +int ret; + + vm =setup_test (test_page_size,/*init_private=*/ true, &vcpu, + &guest_memfd, &mem); + + ret =fallocate (guest_memfd,FALLOC_FL_KEEP_SIZE ,0 , test_page_size); +TEST_ASSERT (!ret,"fallocate should have succeeded" ); + + ret =fallocate (guest_memfd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , +0 , test_page_size); +TEST_ASSERT (!ret,"truncate should have succeeded since there is no need to merge" ); + +cleanup_test (test_page_size, vm, guest_memfd, mem); +} + +static void __test_close_with_pinning (size_t test_page_size,bool init_private) +{ +struct kvm_vcpu *vcpu; +struct kvm_vm *vm; +int guest_memfd; +char *mem; +int ret; + + vm =setup_test (test_page_size, init_private, &vcpu, &guest_memfd, &mem); + + ret =fallocate (guest_memfd,FALLOC_FL_KEEP_SIZE ,0 , test_page_size); +TEST_ASSERT (!ret,"fallocate should have succeeded" ); + +if (!init_private) +pin_pages (mem, test_page_size); + +cleanup_test (test_page_size, vm, guest_memfd, mem); + +if (!init_private) +unpin_pages (); + +/* +* Test this with ./guest_memfd_wrap_test_check_hugetlb_reporting.sh to +* check that the HugeTLB page got merged and returned to HugeTLB. +* +* Sleep here to give kernel worker time to do the merge and return. +*/ +sleep (1 ); +} + +static void test_close_with_pinning (size_t test_page_size) +{ +__test_close_with_pinning (test_page_size, true); +__test_close_with_pinning (test_page_size, false); +} +static void test_with_size (size_t test_page_size) {test_sharing (test_page_size);
@@ -590,6 +682,9 @@ static void test_with_size(size_t test_page_size)test_truncate_should_not_change_mappability (test_page_size);test_conversions_should_fail_if_memory_has_elevated_refcount (test_page_size);test_fault_type_independent_of_mem_attributes (test_page_size); +test_truncate_shared_while_pinned (test_page_size); +test_truncate_private (test_page_size); +test_close_with_pinning (test_page_size); }int main (int argc,char *argv[])
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 45/51 KVM: selftests: Test allocation and conversion of subfolios
In reply to Ackerley TngThis patch adds tests for allocation and conversion of subfolios in a large folio.
--- .../kvm/guest_memfd_conversions_test.c | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+)
tools/testing/selftests/kvm/guest_memfd_conversions_test.c +88 -0
@@ -672,6 +672,92 @@ static void test_close_with_pinning(size_t test_page_size)__test_close_with_pinning (test_page_size, false); } +static void test_allocate_subfolios (size_t test_page_size) +{ +struct kvm_vcpu *vcpu; +struct kvm_vm *vm; +size_t increment; +int guest_memfd; +size_t nr_pages; +char *mem; +int i; + +if (test_page_size ==PAGE_SIZE ) +return ; + + vm =setup_test (test_page_size,/*init_private=*/ false, &vcpu, + &guest_memfd, &mem); + + nr_pages = test_page_size /PAGE_SIZE ; + +/* +* Loop backwards to check allocation of the correct subfolio within the +* huge folio. If it were allocated wrongly, the second loop would error +* out because one or more of the checks would be wrong. +*/ + increment = nr_pages >>1 ; +for (i = nr_pages -1 ; i >=0 ; i -= increment) +host_use_memory (mem + i *PAGE_SIZE ,'X' ,'A' + i); +for (i = nr_pages -1 ; i >=0 ; i -= increment) +host_use_memory (mem + i *PAGE_SIZE ,'A' + i,'A' + i); + +cleanup_test (test_page_size, vm, guest_memfd, mem); +} + +static void test_convert_subfolios (size_t test_page_size) +{ +struct kvm_vcpu *vcpu; +struct kvm_vm *vm; +size_t increment; +int guest_memfd; +size_t nr_pages; +int to_convert; +char *mem; +int i; + +if (test_page_size ==PAGE_SIZE ) +return ; + + vm =setup_test (test_page_size,/*init_private=*/ true, &vcpu, + &guest_memfd, &mem); + + nr_pages = test_page_size /PAGE_SIZE ; + + increment = nr_pages >>1 ; +for (i =0 ; i < nr_pages; i += increment) { +guest_use_memory (vcpu, +GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +'X' ,'A' ,0 ); +assert_host_cannot_fault (mem + i *PAGE_SIZE ); + } + + to_convert =round_up (nr_pages /2 , increment); +guest_memfd_convert_shared (guest_memfd, to_convert *PAGE_SIZE ,PAGE_SIZE ); + + +for (i =0 ; i < nr_pages; i += increment) { +if (i == to_convert) +host_use_memory (mem + i *PAGE_SIZE ,'A' ,'B' ); +else +assert_host_cannot_fault (mem + i *PAGE_SIZE ); + +guest_use_memory (vcpu, +GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +'X' ,'B' ,0 ); + } + +guest_memfd_convert_private (guest_memfd, to_convert *PAGE_SIZE ,PAGE_SIZE ); + +for (i =0 ; i < nr_pages; i += increment) { +guest_use_memory (vcpu, +GUEST_MEMFD_SHARING_TEST_GVA + i *PAGE_SIZE , +'B' ,'C' ,0 ); +assert_host_cannot_fault (mem + i *PAGE_SIZE ); + } + +cleanup_test (test_page_size, vm, guest_memfd, mem); +} +static void test_with_size (size_t test_page_size) {test_sharing (test_page_size);
@@ -685,6 +771,8 @@ static void test_with_size(size_t test_page_size)test_truncate_shared_while_pinned (test_page_size);test_truncate_private (test_page_size);test_close_with_pinning (test_page_size); +test_allocate_subfolios (test_page_size); +test_convert_subfolios (test_page_size); }int main (int argc,char *argv[])
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 46/51 KVM: selftests: Test that guest_memfd usage is reported via hugetlb
In reply to Ackerley TngUsing HugeTLB as the huge page allocator for guest_memfd allows reuse of HugeTLB's reporting mechanism, hence HugeTLB stats must be kept up-to-date.
This patch tests for the above.
--- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../kvm/guest_memfd_hugetlb_reporting_test.c | 384 ++++++++++++++++++ ...uest_memfd_provide_hugetlb_cgroup_mount.sh | 36 ++ 3 files changed, 421 insertions(+) create mode 100644 tools/testing/selftests/kvm/guest_memfd_hugetlb_reporting_test.c create mode 100755 tools/testing/selftests/kvm/guest_memfd_provide_hugetlb_cgroup_mount.sh
tools/testing/selftests/kvm/Makefile.kvm +1 -0
@@ -132,6 +132,7 @@ TEST_GEN_PROGS_x86 += coalesced_io_test TEST_GEN_PROGS_x86 += dirty_log_perf_test TEST_GEN_PROGS_x86 += guest_memfd_test TEST_GEN_PROGS_x86 += guest_memfd_conversions_test +TEST_GEN_PROGS_x86 += guest_memfd_hugetlb_reporting_test TEST_GEN_PROGS_x86 += hardware_disable_test TEST_GEN_PROGS_x86 += memslot_modification_stress_test TEST_GEN_PROGS_x86 += memslot_perf_test
tools/testing/selftests/kvm/guest_memfd_hugetlb_reporting_test.c new file +384 -0
384 lines not on this page · raw message
tools/testing/selftests/kvm/guest_memfd_provide_hugetlb_cgroup_mount.sh new file +36 -0
@@ -0,0 +1,36 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-only +# +# Wrapper that runs test, providing a hugetlb cgroup mount in environment +# variable HUGETLB_CGROUP_PATH +# +# Example: +# ./guest_memfd_provide_hugetlb_cgroup_mount.sh ./guest_memfd_hugetlb_reporting_test +# +# Copyright (C) 2025, Google LLC. + +script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) + +temp_dir=$(mktemp -d /tmp/guest_memfd_hugetlb_reporting_test_XXXXXX) +if [[ -z "$temp_dir" ]]; then + echo "Error: Failed to create temporary directory for hugetlb cgroup mount." >&2 + exit 1 +fi + +delete_temp_dir() { + rm -rf $temp_dir +} +trap delete_temp_dir EXIT + + +mount -t cgroup -o hugetlb none $temp_dir + + +cleanup() { + umount $temp_dir + rm -rf $temp_dir +} +trap cleanup EXIT + + +HUGETLB_CGROUP_PATH=$temp_dir $@
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 47/51 KVM: selftests: Support various types of backing sources for private memory
In reply to Ackerley TngAdds support for various type of backing sources for private memory (in the sense of confidential computing), similar to the backing sources available for shared memory.
--- .../testing/selftests/kvm/include/test_util.h | 18 ++++- tools/testing/selftests/kvm/lib/test_util.c | 77 +++++++++++++++++++ 2 files changed, 94 insertions(+), 1 deletion(-)
tools/testing/selftests/kvm/include/test_util.h +17 -1
@@ -139,9 +139,19 @@ enum vm_mem_backing_src_type {struct vm_mem_backing_src_alias {const char *name; -uint32_t flag; +uint64_t flag; }; +enum vm_private_mem_backing_src_type { +VM_PRIVATE_MEM_SRC_GUEST_MEM ,/* Use default page size */ +VM_PRIVATE_MEM_SRC_HUGETLB ,/* Use kernel default page size for hugetlb pages */ +VM_PRIVATE_MEM_SRC_HUGETLB_2MB , +VM_PRIVATE_MEM_SRC_HUGETLB_1GB , +NUM_PRIVATE_MEM_SRC_TYPES , +}; + +#define DEFAULT_VM_PRIVATE_MEM_SRC VM_PRIVATE_MEM_SRC_GUEST_MEM +#define MIN_RUN_DELAY_NS 200000ULbool thp_configured (void );
@@ -154,6 +164,12 @@ int get_backing_src_madvise_advice(uint32_t i);bool is_backing_src_hugetlb (uint32_t i);void backing_src_help (const char *flag);enum vm_mem_backing_src_type parse_backing_src_type (const char *type_name); + +void private_mem_backing_src_help (const char *flag); +enum vm_private_mem_backing_src_type parse_private_mem_backing_src_type (const char *type_name); +const struct vm_mem_backing_src_alias *vm_private_mem_backing_src_alias (uint32_t i); +size_t get_private_mem_backing_src_pagesz (uint32_t i); +long get_run_delay (void );/*
tools/testing/selftests/kvm/lib/test_util.c +77 -0
101 lines not on this page · raw message
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 48/51 KVM: selftests: Update test for various private memory backing source types
In reply to Ackerley TngUpdate private_mem_conversions_test for various private memory backing source types, testing HugeTLB support in guest_memfd.
--- .../kvm/x86/private_mem_conversions_test.c | 42 +++++++++++++------ 1 file changed, 29 insertions(+), 13 deletions(-)
tools/testing/selftests/kvm/x86/private_mem_conversions_test.c +29 -13
@@ -450,21 +450,18 @@ static void *__test_mem_conversions(void *params) }static void test_mem_conversions (enum vm_mem_backing_src_type src_type, +enum vm_private_mem_backing_src_type private_mem_src_type,uint32_t nr_vcpus,uint32_t nr_memslots,bool back_shared_memory_with_guest_memfd) { -/* -* Allocate enough memory so that each vCPU's chunk of memory can be -* naturally aligned with respect to the size of the backing store. -*/ -const size_t alignment =max_t (size_t,SZ_2M ,get_backing_src_pagesz (src_type));struct test_thread_args *thread_args[KVM_MAX_VCPUS ]; -const size_t per_cpu_size =align_up (PER_CPU_DATA_SIZE , alignment); -const size_t memfd_size = per_cpu_size * nr_vcpus; -const size_t slot_size = memfd_size / nr_memslots;struct kvm_vcpu *vcpus[KVM_MAX_VCPUS ];pthread_t threads[KVM_MAX_VCPUS ]; +size_t per_cpu_size; +size_t memfd_size;struct kvm_vm *vm; +size_t alignment; +size_t slot_size;int memfd, i, r;uint64_t flags;
@@ -473,6 +470,18 @@ static void test_mem_conversions(enum vm_mem_backing_src_type src_type, .type = KVM_X86_SW_PROTECTED_VM, }; +/* +* Allocate enough memory so that each vCPU's chunk of memory can be +* naturally aligned with respect to the size of the backing store. +*/ + alignment =max_t (size_t,SZ_2M , +max_t (size_t,get_backing_src_pagesz (src_type), +get_private_mem_backing_src_pagesz ( + private_mem_src_type))); + per_cpu_size =align_up (PER_CPU_DATA_SIZE , alignment); + memfd_size = per_cpu_size * nr_vcpus; + slot_size = memfd_size / nr_memslots; +TEST_ASSERT (slot_size * nr_memslots == memfd_size,"The memfd size (0x%lx) needs to be cleanly divisible by the number of memslots (%u)" , memfd_size, nr_memslots);
@@ -483,6 +492,7 @@ static void test_mem_conversions(enum vm_mem_backing_src_type src_type, flags = back_shared_memory_with_guest_memfd ?GUEST_MEMFD_FLAG_SUPPORT_SHARED :0 ; + flags |=vm_private_mem_backing_src_alias (private_mem_src_type)->flag; memfd =vm_create_guest_memfd (vm, memfd_size, flags);for (i =0 ; i < nr_memslots; i++) {
@@ -547,10 +557,13 @@ static void test_mem_conversions(enum vm_mem_backing_src_type src_type,static void usage (const char *cmd) {puts ("" ); -printf ("usage: %s [-h] [-g] [-m nr_memslots] [-s mem_type] [-n nr_vcpus]\n" , cmd); +printf ("usage: %s [-h] [-g] [-m nr_memslots] [-s mem_type] [-p private_mem_type] [-n nr_vcpus]\n" , + cmd);puts ("" );backing_src_help ("-s" );puts ("" ); +private_mem_backing_src_help ("-p" ); +puts ("" );puts (" -n: specify the number of vcpus (default: 1)" );puts ("" );puts (" -m: specify the number of memslots (default: 1)" );
@@ -561,6 +574,7 @@ static void usage(const char *cmd)int main (int argc,char *argv[]) { +enum vm_private_mem_backing_src_type private_mem_src_type =DEFAULT_VM_PRIVATE_MEM_SRC ;enum vm_mem_backing_src_type src_type =DEFAULT_VM_MEM_SRC ;bool back_shared_memory_with_guest_memfd = false;uint32_t nr_memslots =1 ;
@@ -569,11 +583,14 @@ int main(int argc, char *argv[])TEST_REQUIRE (kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (KVM_X86_SW_PROTECTED_VM )); -while ((opt =getopt (argc, argv,"hgm:s:n:" )) !=-1 ) { +while ((opt =getopt (argc, argv,"hgm:s:p:n:" )) !=-1 ) {switch (opt) {case 's' : src_type =parse_backing_src_type (optarg);break ; +case 'p' : + private_mem_src_type =parse_private_mem_backing_src_type (optarg); +break ;case 'n' : nr_vcpus =atoi_positive ("nr_vcpus" , optarg);break ;
@@ -590,9 +607,8 @@ int main(int argc, char *argv[]) } } -test_mem_conversions (src_type, nr_vcpus, nr_memslots, - back_shared_memory_with_guest_memfd); - +test_mem_conversions (src_type, private_mem_src_type, nr_vcpus, + nr_memslots, back_shared_memory_with_guest_memfd);return 0 ; }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 49/51 KVM: selftests: Update private_mem_conversions_test.sh to test with HugeTLB pages
In reply to Ackerley TngUpdate test script to also test HugeTLB support for guest_memfd.
Change-Id: I7c6cc25d6b86e1e0dc74018f46c7e2796fab6357
--- .../kvm/x86/private_mem_conversions_test.sh | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-)
tools/testing/selftests/kvm/x86/private_mem_conversions_test.sh +22 -7
@@ -57,6 +57,17 @@ backing_src_types+=( shmem ) backing_src_types+=( shared_hugetlb ) || \ echo "skipping shared_hugetlb backing source type" +private_mem_backing_src_types=( private_mem_guest_mem ) +[ -n "$hugepage_default_enabled" ] && \ + private_mem_backing_src_types+=( private_mem_hugetlb ) || \ + echo "skipping private_mem_hugetlb backing source type" +[ -n "$hugepage_2mb_enabled" ] && \ + private_mem_backing_src_types+=( private_mem_hugetlb_2mb ) || \ + echo "skipping private_mem_hugetlb_2mb backing source type" +[ -n "$hugepage_1gb_enabled" ] && \ + private_mem_backing_src_types+=( private_mem_hugetlb_1gb ) || \ + echo "skipping private_mem_hugetlb_1gb backing source type" + set +e TEST_EXECUTABLE="$(dirname "$0")/private_mem_conversions_test"
@@ -66,17 +77,21 @@ TEST_EXECUTABLE="$(dirname "$0")/private_mem_conversions_test" for src_type in "${backing_src_types[@]}"; do - set -x + for private_mem_src_type in "${private_mem_backing_src_types[@]}"; do - $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test - $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -m $num_memslots_to_test + set -x - $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -g - $TEST_EXECUTABLE -s "$src_type" -n $num_vcpus_to_test -m $num_memslots_to_test -g + $TEST_EXECUTABLE -s "$src_type" -p "$private_mem_src_type" -n $num_vcpus_to_test + $TEST_EXECUTABLE -s "$src_type" -p "$private_mem_src_type" -n $num_vcpus_to_test -m $num_memslots_to_test - { set +x; } 2>/dev/null + $TEST_EXECUTABLE -s "$src_type" -p "$private_mem_src_type" -n $num_vcpus_to_test -g + $TEST_EXECUTABLE -s "$src_type" -p "$private_mem_src_type" -n $num_vcpus_to_test -m $num_memslots_to_test -g - echo + { set +x; } 2>/dev/null + + echo + + done done )
Signature · 1 line
2.49.0.1045.g170613ef41-goog
RFC PATCH v2 50/51 KVM: selftests: Add script to test HugeTLB statistics
In reply to Ackerley TngThis script wraps other tests to check that HugeTLB statistics are restored to what they were before the test was run.
Does not account HugeTLB statistics updated by other non-test processes running in the background while the test is running.
--- ...memfd_wrap_test_check_hugetlb_reporting.sh | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100755 tools/testing/selftests/kvm/guest_memfd_wrap_test_check_hugetlb_reporting.sh
tools/testing/selftests/kvm/guest_memfd_wrap_test_check_hugetlb_reporting.sh new file +95 -0
@@ -0,0 +1,95 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-only +# +# Wrapper that runs test, checking that HugeTLB-related statistics have not +# changed before and after test. +# +# Example: +# ./guest_memfd_wrap_test_check_hugetlb_reporting.sh ./guest_memfd_test +# +# Example of combining this with ./guest_memfd_provide_hugetlb_cgroup_mount.sh: +# ./guest_memfd_provide_hugetlb_cgroup_mount.sh \ +# ./guest_memfd_wrap_test_check_hugetlb_reporting.sh \ +# ./guest_memfd_hugetlb_reporting_test +# +# Copyright (C) 2025, Google LLC. + +declare -A baseline + +hugetlb_sizes=( + "2048kB" + "1048576kB" +) + +statistics=( + "free_hugepages" + "nr_hugepages" + "nr_overcommit_hugepages" + "resv_hugepages" + "surplus_hugepages" +) + +cgroup_hugetlb_sizes=( + "2MB" + "1GB" +) + +cgroup_statistics=( + "limit_in_bytes" + "max_usage_in_bytes" + "usage_in_bytes" +) + +establish_statistics_baseline() { + for size in "${hugetlb_sizes[@]}"; do + + for statistic in "${statistics[@]}"; do + + local path="/sys/kernel/mm/hugepages/hugepages-${size}/${statistic}" + baseline["$path"]=$(cat "$path") + + done + + done + + if [ -n "$HUGETLB_CGROUP_PATH" ]; then + + for size in "${cgroup_hugetlb_sizes[@]}"; do + + for statistic in "${cgroup_statistics[@]}"; do + + local rsvd_path="${HUGETLB_CGROUP_PATH}/hugetlb.${size}.rsvd.${statistic}" + local path="${HUGETLB_CGROUP_PATH}/hugetlb.${size}.${statistic}" + + baseline["$rsvd_path"]=$(cat "$rsvd_path") + baseline["$path"]=$(cat "$path") + + done + + done + + fi +} + +assert_path_at_baseline() { + local path=$1 + + current=$(cat "$path") + expected=${baseline["$path"]} + if [ "$current" != "$expected" ]; then + echo "$path was $current instead of $expected" + fi +} + +assert_statistics_at_baseline() { + for path in "${!baseline[@]}"; do + assert_path_at_baseline $path + done +} + + +establish_statistics_baseline + +$@ + +assert_statistics_at_baseline
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Matthew Wilcox
maintainerRe: [RFC PATCH v2 16/51] mm: hugetlb: Consolidate interpretation of gbl_chg within alloc_hugetlb_folio()
In reply to Ackerley Tngmm/hugetlb.c static unsigned long available_huge_pages(struct hstate *h) · line 1369
Quoted 6 lines · Ackerley Tng
mm/hugetlb.c +3
-3-static struct folio *dequeue_hugetlb_folio_vma (struct hstate *h, -struct vm_area_struct *vma, -unsigned long address,long gbl_chg) +static struct folio *dequeue_hugetlb_folio (struct hstate *h, +struct vm_area_struct *vma, +unsigned long address)
Pleaase don't mess with the indentation unless necessary. Nobody cares what your personal style preference is. You're obscuring the actual changes.
Re: [RFC PATCH v2 03/51] KVM: selftests: Update guest_memfd_test for INIT_PRIVATE flag
In reply to Ackerley TngQuoted 56 lines · Ackerley Tng
Test that
GUEST_MEMFD_FLAG_INIT_PRIVATEis only valid whenGUEST_MEMFD_FLAG_SUPPORT_SHAREDis set.Change-Id I506e236a232047cfaee17bcaed02ee14c8d25bbbSigned-off-by Ackerley Tng <[email protected]>--- .../testing/selftests/kvm/guest_memfd_test.c | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-)tools/testing/selftests/kvm/guest_memfd_test.c +21
-5@@ -401,13 +401,31 @@ static void test_with_type(unsigned long vm_type, uint64_t guest_memfd_flags,kvm_vm_release (vm); } +static void test_vm_with_gmem_flag (struct kvm_vm *vm,uint64_t flag, +bool expect_valid) +{ +size_t page_size =getpagesize (); +int fd; + + fd =__vm_create_guest_memfd (vm, page_size, flag); + +if (expect_valid) { +TEST_ASSERT (fd >0 , +"guest_memfd() with flag '0x%lx' should be valid" , + flag); +close (fd); + }else { +TEST_ASSERT (fd ==-1 && errno ==EINVAL , +"guest_memfd() with flag '0x%lx' should fail with EINVAL" , + flag); + } +} +static void test_vm_type_gmem_flag_validity (unsigned long vm_type,uint64_t expected_valid_flags) { -size_t page_size =getpagesize ();struct kvm_vm *vm;uint64_t flag =0 ; -int fd;if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type)))return ;@@ -415,17 +433,11 @@ static void test_vm_type_gmem_flag_validity(unsigned long vm_type, vm =vm_create_barebones_type (vm_type);for (flag =BIT (0 ); flag; flag <<=1 ) { - fd =__vm_create_guest_memfd (vm, page_size, flag); +test_vm_with_gmem_flag (vm, flag, flag & expected_valid_flags); -if (flag & expected_valid_flags) { - TEST_ASSERT(fd > 0,
tools/testing/selftests/kvm/guest_memfd_test.c static void test_vm_type_gmem_flag_validity(unsigned long vm_type, · line 440
Quoted 10 lines
tools/testing/selftests/kvm/guest_memfd_test.c +3
-7-"guest_memfd() with flag '0x%lx' should be valid" , - flag); -close (fd); - }else { -TEST_ASSERT (fd ==-1 && errno ==EINVAL , -"guest_memfd() with flag '0x%lx' should fail with EINVAL" , - flag); +if (flag ==GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { +test_vm_with_gmem_flag ( + vm, flag |GUEST_MEMFD_FLAG_INIT_PRIVATE , true);
I don't understand the point of this check. In 2/51 we set GUEST_MEMFD_FLAG_INIT_PRIVATE when GUEST_MEMFD_FLAG_SUPPORT_SHARED is set.
When can this check ever fail?
Ira
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Ackerley TngAckerley Tng wrote:
[snip]
Quoted 2 lines
Signed-off-by Ackerley Tng <[email protected]>
[snip]
Quoted 19 lines
virt/kvm/guest_memfd.c +4
-0@@ -30,6 +30,10 @@ enum shareability { };static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index); +static void kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end); +static void kvm_gmem_invalidate_end (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end);static struct kvm_gmem_inode_private *kvm_gmem_private (struct inode *inode) {@@ -85,6 +89,306 @@ static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t indereturn kvm_gmem_get_folio (inode, index); }
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t inde · line 101
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+/** +* kvm_gmem_shareability_store() - Sets shareability to @value for range. +* +* @mt: the shareability maple tree. +* @index: the range begins at this index in the inode. +* @nr_pages: number of PAGE_SIZE pages in this range. +* @value: the shareability value to set for this range. +* +* Unlike mtree_store_range(), this function also merges adjacent ranges that +* have the same values as an optimization.
Is this an optimization or something which will be required to convert from shared back to private and back to a huge page mapping?
If this is purely an optimization it might be best to leave it out for now to get functionality first.
I have more to review but wanted to ask this.
Ira
[snip]
Quoted 5 lines · Ackerley Tng
Hello,
This patchset builds upon discussion at LPC 2024 and many
guest_memfdupstream calls to provide 1G page support forguest_memfdby taking pages from HugeTLB.
Do you have any more concrete numbers on benefits of 1GB huge pages for guestmemfd/coco VMs? I saw in the LPC talk it has the benefits as:
- Increase TLB hit rate and reduce page walks on TLB miss
- Improved IO performance
- Memory savings of ~1.6% from HugeTLB Vmemmap Optimization (HVO)
- Bring guest_memfd to parity with existing VMs that use HugeTLB pages for backing memory
Do you know how often the 1GB TDP mappings get shattered by shared pages?
Thinking from the TDX perspective, we might have bigger fish to fry than 1.6% memory savings (for example dynamic PAMT), and the rest of the benefits don't have numbers. How much are we getting for all the complexity, over say buddy allocated 2MB pages?
Quoted 16 lines · Rick P
Quoted 5 lines · Ackerley Tng
Hello,
This patchset builds upon discussion at LPC 2024 and many
guest_memfdupstream calls to provide 1G page support forguest_memfdby taking pages from HugeTLB.Do you have any more concrete numbers on benefits of 1GB huge pages for guestmemfd/coco VMs? I saw in the LPC talk it has the benefits as:
- Increase TLB hit rate and reduce page walks on TLB miss
- Improved IO performance
- Memory savings of ~1.6% from HugeTLB Vmemmap Optimization (HVO)
- Bringguest_memfdto parity with existing VMs that use HugeTLB pages for backing memory
Quoted 6 lines
Do you know how often the 1GB TDP mappings get shattered by shared pages?
Thinking from the TDX perspective, we might have bigger fish to fry than 1.6% memory savings (for example dynamic PAMT), and the rest of the benefits don't have numbers. How much are we getting for all the complexity, over say buddy allocated 2MB pages?
This series should work for any page sizes backed by hugetlb memory. Non-CoCo VMs, pKVM and Confidential VMs all need hugepages that are essential for certain workloads and will emerge as guest_memfd users. Features like KHO/memory persistence in addition also depend on hugepage support in guest_memfd.
This series takes strides towards making guest_memfd compatible with usecases where 1G pages are essential and non-confidential VMs are already exercising them.
I think the main complexity here lies in supporting in-place conversion which applies to any huge page size even for buddy allocated 2MB pages or THP.
This complexity arises because page structs work at a fixed granularity, future roadmap towards not having page structs for guest memory (at least private memory to begin with) should help towards greatly reducing this complexity.
That being said, DPAMT and huge page EPT mappings for TDX VMs remain essential and complement this series well for better memory footprint and overall performance of TDX VMs.
Quoted 39 lines · Vishal Annapurve
Quoted 16 lines · Rick P
Quoted 5 lines · Ackerley Tng
Hello,
This patchset builds upon discussion at LPC 2024 and many
guest_memfdupstream calls to provide 1G page support forguest_memfdby taking pages from HugeTLB.Do you have any more concrete numbers on benefits of 1GB huge pages for guestmemfd/coco VMs? I saw in the LPC talk it has the benefits as:
- Increase TLB hit rate and reduce page walks on TLB miss
- Improved IO performance
- Memory savings of ~1.6% from HugeTLB Vmemmap Optimization (HVO)
- Bringguest_memfdto parity with existing VMs that use HugeTLB pages for backing memoryQuoted 6 lines
Do you know how often the 1GB TDP mappings get shattered by shared pages?
Thinking from the TDX perspective, we might have bigger fish to fry than 1.6% memory savings (for example dynamic PAMT), and the rest of the benefits don't have numbers. How much are we getting for all the complexity, over say buddy allocated 2MB pages?
This series should work for any page sizes backed by hugetlb memory. Non-CoCo VMs, pKVM and Confidential VMs all need hugepages that are essential for certain workloads and will emerge as
guest_memfdusers. Features like KHO/memory persistence in addition also depend on hugepage support inguest_memfd.This series takes strides towards making
guest_memfdcompatible with usecases where 1G pages are essential and non-confidential VMs are already exercising them.I think the main complexity here lies in supporting in-place conversion which applies to any huge page size even for buddy allocated 2MB pages or THP.
Quoted 8 lines
This complexity arises because page structs work at a fixed granularity, future roadmap towards not having page structs for guest memory (at least private memory to begin with) should help towards greatly reducing this complexity.
That being said, DPAMT and huge page EPT mappings for TDX VMs remain essential and complement this series well for better memory footprint and overall performance of TDX VMs.
Hmm, this didn't really answer my questions about the concrete benefits.
I think it would help to include this kind of justification for the 1GB guestmemfd pages. "essential for certain workloads and will emerge" is a bit hard to review against...
I think one of the challenges with coco is that it's almost like a sprint to reimplement virtualization. But enough things are changing at once that not all of the normal assumptions hold, so it can't copy all the same solutions. The recent example was that for TDX huge pages we found that normal promotion paths weren't actually yielding any benefit for surprising TDX specific reasons.
On the TDX side we are also, at least currently, unmapping private pages while they are mapped shared, so any 1GB pages would get split to 2MB if there are any shared pages in them. I wonder how many 1GB pages there would be after all the shared pages are converted. At smaller TD sizes, it could be not much.
So for TDX in isolation, it seems like jumping out too far ahead to effectively consider the value. But presumably you guys are testing this on SEV or something? Have you measured any performance improvement? For what kind of applications? Or is the idea to basically to make guestmemfd work like however Google does guest memory?
RFC PATCH v2 51/51 KVM: selftests: Test guest_memfd for accuracy of st_blocks
In reply to Ackerley TngTest that st_blocks in struct stat (inode->i_blocks) is updated.
--- .../testing/selftests/kvm/guest_memfd_test.c | 55 ++++++++++++++++--- 1 file changed, 46 insertions(+), 9 deletions(-)
tools/testing/selftests/kvm/guest_memfd_test.c +46 -9
@@ -142,41 +142,78 @@ static void test_file_size(int fd, size_t page_size, size_t total_size)TEST_ASSERT_EQ (sb.st_blksize, page_size); } -static void test_fallocate (int fd,size_t page_size,size_t total_size) +static void assert_st_blocks_equals_size (int fd,size_t page_size,size_t expected_size) { +struct stat sb; +int ret; + +/* TODO: st_blocks is not updated for 4K-page guest_memfd. */ +if (page_size ==getpagesize ()) +return ; + + ret =fstat (fd, &sb); +TEST_ASSERT (!ret,"fstat should succeed" ); +TEST_ASSERT_EQ (sb.st_blocks, expected_size /512 ); +} + +static void test_fallocate (int fd,size_t test_page_size,size_t total_size) +{ +size_t page_size;int ret; ret =fallocate (fd,FALLOC_FL_KEEP_SIZE ,0 , total_size);TEST_ASSERT (!ret,"fallocate with aligned offset and size should succeed" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size); ret =fallocate (fd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , - page_size -1 , page_size); + test_page_size -1 , test_page_size);TEST_ASSERT (ret,"fallocate with unaligned offset should fail" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size); - ret =fallocate (fd,FALLOC_FL_KEEP_SIZE , total_size, page_size); + ret =fallocate (fd,FALLOC_FL_KEEP_SIZE , total_size, test_page_size);TEST_ASSERT (ret,"fallocate beginning at total_size should fail" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size); - ret =fallocate (fd,FALLOC_FL_KEEP_SIZE , total_size + page_size, page_size); + ret =fallocate (fd,FALLOC_FL_KEEP_SIZE , total_size + test_page_size, test_page_size);TEST_ASSERT (ret,"fallocate beginning after total_size should fail" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size); ret =fallocate (fd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , - total_size, page_size); + total_size, test_page_size);TEST_ASSERT (!ret,"fallocate(PUNCH_HOLE) at total_size should succeed" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size); ret =fallocate (fd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , - total_size + page_size, page_size); + total_size + test_page_size, test_page_size);TEST_ASSERT (!ret,"fallocate(PUNCH_HOLE) after total_size should succeed" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size); ret =fallocate (fd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , - page_size, page_size -1 ); + test_page_size, test_page_size -1 );TEST_ASSERT (ret,"fallocate with unaligned size should fail" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size); ret =fallocate (fd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , - page_size, page_size); + test_page_size, test_page_size);TEST_ASSERT (!ret,"fallocate(PUNCH_HOLE) with aligned offset and size should succeed" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size - test_page_size); - ret =fallocate (fd,FALLOC_FL_KEEP_SIZE , page_size, page_size); + ret =fallocate (fd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , + test_page_size, test_page_size); +TEST_ASSERT (!ret,"fallocate(PUNCH_HOLE) in a hole should succeed" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size - test_page_size); + + ret =fallocate (fd,FALLOC_FL_KEEP_SIZE , test_page_size, test_page_size);TEST_ASSERT (!ret,"fallocate to restore punched hole should succeed" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size); + + page_size =getpagesize (); +if (test_page_size == page_size) { + ret =fallocate (fd,FALLOC_FL_KEEP_SIZE |FALLOC_FL_PUNCH_HOLE , + test_page_size + page_size, page_size); +TEST_ASSERT (!ret,"fallocate(PUNCH_HOLE) of a subfolio should succeed" ); +assert_st_blocks_equals_size (fd, test_page_size, total_size); + } }static void test_invalid_punch_hole (int fd,size_t page_size,size_t total_size)
Signature · 1 line
2.49.0.1045.g170613ef41-goog
Sean Christopherson
maintainerQuoted 19 lines · Rick P Edgecombe
Quoted 18 lines · Vishal Annapurve
Quoted 16 lines · Rick P
Quoted 5 lines · Ackerley Tng
Hello,
This patchset builds upon discussion at LPC 2024 and many
guest_memfdupstream calls to provide 1G page support forguest_memfdby taking pages from HugeTLB.Do you have any more concrete numbers on benefits of 1GB huge pages for guestmemfd/coco VMs? I saw in the LPC talk it has the benefits as:
- Increase TLB hit rate and reduce page walks on TLB miss
- Improved IO performance
- Memory savings of ~1.6% from HugeTLB Vmemmap Optimization (HVO)
- Bringguest_memfdto parity with existing VMs that use HugeTLB pages for backing memory
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Do you know how often the 1GB TDP mappings get shattered by shared pages?
Thinking from the TDX perspective, we might have bigger fish to fry than 1.6% memory savings (for example dynamic PAMT), and the rest of the benefits don't have numbers. How much are we getting for all the complexity, over say buddy allocated 2MB pages?
TDX may have bigger fish to fry, but some of us have bigger fish to fry than TDX :-)
Quoted 35 lines
Quoted 14 lines
This series should work for any page sizes backed by hugetlb memory. Non-CoCo VMs, pKVM and Confidential VMs all need hugepages that are essential for certain workloads and will emerge as
guest_memfdusers. Features like KHO/memory persistence in addition also depend on hugepage support inguest_memfd.This series takes strides towards making
guest_memfdcompatible with usecases where 1G pages are essential and non-confidential VMs are already exercising them.I think the main complexity here lies in supporting in-place conversion which applies to any huge page size even for buddy allocated 2MB pages or THP.
Quoted 8 lines
This complexity arises because page structs work at a fixed granularity, future roadmap towards not having page structs for guest memory (at least private memory to begin with) should help towards greatly reducing this complexity.
That being said, DPAMT and huge page EPT mappings for TDX VMs remain essential and complement this series well for better memory footprint and overall performance of TDX VMs.
Hmm, this didn't really answer my questions about the concrete benefits.
I think it would help to include this kind of justification for the 1GB guestmemfd pages. "essential for certain workloads and will emerge" is a bit hard to review against...
I think one of the challenges with coco is that it's almost like a sprint to reimplement virtualization. But enough things are changing at once that not all of the normal assumptions hold, so it can't copy all the same solutions. The recent example was that for TDX huge pages we found that normal promotion paths weren't actually yielding any benefit for surprising TDX specific reasons.
Quoted 4 lines
On the TDX side we are also, at least currently, unmapping private pages while they are mapped shared, so any 1GB pages would get split to 2MB if there are any shared pages in them. I wonder how many 1GB pages there would be after all the shared pages are converted. At smaller TD sizes, it could be not much.
You're conflating two different things. guest_memfd allocating and managing 1GiB physical pages, and KVM mapping memory into the guest at 1GiB/2MiB granularity. Allocating memory in 1GiB chunks is useful even if KVM can only map memory into the guest using 4KiB pages.
Quoted 5 lines
So for TDX in isolation, it seems like jumping out too far ahead to effectively consider the value. But presumably you guys are testing this on SEV or something? Have you measured any performance improvement? For what kind of applications? Or is the idea to basically to make guestmemfd work like however Google does guest memory?
The longer term goal of guest_memfd is to make it suitable for backing all VMs, hence Vishal's "Non-CoCo VMs" comment. Yes, some of this is useful for TDX, but we (and others) want to use guest_memfd for far more than just CoCo VMs. And for non-CoCo VMs, 1GiB hugepages are mandatory for various workloads.
Quoted 7 lines · Sean Christopherson
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Thinking from the TDX perspective, we might have bigger fish to fry than 1.6% memory savings (for example dynamic PAMT), and the rest of the benefits don't have numbers. How much are we getting for all the complexity, over say buddy allocated 2MB pages?
TDX may have bigger fish to fry, but some of us have bigger fish to fry than TDX :-)
Fair enough. But TDX is on the "roadmap". So it helps to say what the target of this series is.
Quoted 43 lines
Quoted 37 lines
Quoted 15 lines
This series should work for any page sizes backed by hugetlb memory. Non-CoCo VMs, pKVM and Confidential VMs all need hugepages that are essential for certain workloads and will emerge as
guest_memfdusers. Features like KHO/memory persistence in addition also depend on hugepage support inguest_memfd.This series takes strides towards making
guest_memfdcompatible with usecases where 1G pages are essential and non-confidential VMs are already exercising them.I think the main complexity here lies in supporting in-place conversion which applies to any huge page size even for buddy allocated 2MB pages or THP.
Quoted 8 lines
This complexity arises because page structs work at a fixed granularity, future roadmap towards not having page structs for guest memory (at least private memory to begin with) should help towards greatly reducing this complexity.
That being said, DPAMT and huge page EPT mappings for TDX VMs remain essential and complement this series well for better memory footprint and overall performance of TDX VMs.
Hmm, this didn't really answer my questions about the concrete benefits.
I think it would help to include this kind of justification for the 1GB guestmemfd pages. "essential for certain workloads and will emerge" is a bit hard to review against...
I think one of the challenges with coco is that it's almost like a sprint to reimplement virtualization. But enough things are changing at once that not all of the normal assumptions hold, so it can't copy all the same solutions. The recent example was that for TDX huge pages we found that normal promotion paths weren't actually yielding any benefit for surprising TDX specific reasons.
Quoted 5 lines
On the TDX side we are also, at least currently, unmapping private pages while they are mapped shared, so any 1GB pages would get split to 2MB if there are any shared pages in them. I wonder how many 1GB pages there would be after all the shared pages are converted. At smaller TD sizes, it could be not much.
Quoted 4 lines
You're conflating two different things.
guest_memfdallocating and managing 1GiB physical pages, and KVM mapping memory into the guest at 1GiB/2MiB granularity. Allocating memory in 1GiB chunks is useful even if KVM can only map memory into the guest using 4KiB pages.
I'm aware of the 1.6% vmemmap benefits from the LPC talk. Is there more? The list quoted there was more about guest performance. Or maybe the clever page table walkers that find contiguous small mappings could benefit guest performance too? It's the kind of thing I'd like to see at least broadly called out.
I'm thinking that Google must have a ridiculous amount of learnings about VM memory management. And this is probably designed around those learnings. But reviewers can't really evaluate it if they don't know the reasons and tradeoffs taken. If it's going upstream, I think it should have at least the high level reasoning explained.
I don't mean to harp on the point so hard, but I didn't expect it to be controversial either.
Quoted 9 lines
Quoted 6 lines
So for TDX in isolation, it seems like jumping out too far ahead to effectively consider the value. But presumably you guys are testing this on SEV or something? Have you measured any performance improvement? For what kind of applications? Or is the idea to basically to make guestmemfd work like however Google does guest memory?
The longer term goal of
guest_memfdis to make it suitable for backing all VMs, hence Vishal's "Non-CoCo VMs" comment.
Oh, I actually wasn't aware of this. Or maybe I remember now. I thought he was talking about pKVM.
Quoted 5 lines
Yes, some of this is useful for TDX, but we (and others) want to use
guest_memfdfor far more than just CoCo VMs.And for non-CoCo VMs, 1GiB hugepages are mandatory for various workloads.
I've heard this a lot. It must be true, but I've never seen the actual numbers. For a long time people believed 1GB huge pages on the direct map were critical, but then benchmarking on a contemporary CPU couldn't find much difference between 2MB and 1GB. I'd expect TDP huge pages to be different than that because the combined walks are huge, iTLB, etc, but I'd love to see a real number.
Quoted 4 lines · Sean Christopherson
You're conflating two different things.
guest_memfdallocating and managing 1GiB physical pages, and KVM mapping memory into the guest at 1GiB/2MiB granularity. Allocating memory in 1GiB chunks is useful even if KVM can only map memory into the guest using 4KiB pages.
Even if KVM is limited to 4K the IOMMU might not be - alot of these workloads have a heavy IO component and we need the iommu to perform well too.
Frankly, I don't think there should be objection to making memory more contiguous. There is alot of data that this always brings wins somewhere for someone.
Quoted 4 lines
The longer term goal of
guest_memfdis to make it suitable for backing all VMs, hence Vishal's "Non-CoCo VMs" comment. Yes, some of this is useful for TDX, but we (and others) want to useguest_memfdfor far more than just CoCo VMs. And for non-CoCo VMs, 1GiB hugepages are mandatory for various workloads.
Yes, even from an iommu perspective with 2D translation we need to have the 1G pages from the S2 resident in the IOTLB or performance falls off a cliff.
Jason
Quoted 61 lines · Rick P
Quoted 7 lines · Sean Christopherson
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Thinking from the TDX perspective, we might have bigger fish to fry than 1.6% memory savings (for example dynamic PAMT), and the rest of the benefits don't have numbers. How much are we getting for all the complexity, over say buddy allocated 2MB pages?
TDX may have bigger fish to fry, but some of us have bigger fish to fry than TDX :-)
Fair enough. But TDX is on the "roadmap". So it helps to say what the target of this series is.
Quoted 43 lines
Quoted 37 lines
Quoted 15 lines
This series should work for any page sizes backed by hugetlb memory. Non-CoCo VMs, pKVM and Confidential VMs all need hugepages that are essential for certain workloads and will emerge as
guest_memfdusers. Features like KHO/memory persistence in addition also depend on hugepage support inguest_memfd.This series takes strides towards making
guest_memfdcompatible with usecases where 1G pages are essential and non-confidential VMs are already exercising them.I think the main complexity here lies in supporting in-place conversion which applies to any huge page size even for buddy allocated 2MB pages or THP.
Quoted 8 lines
This complexity arises because page structs work at a fixed granularity, future roadmap towards not having page structs for guest memory (at least private memory to begin with) should help towards greatly reducing this complexity.
That being said, DPAMT and huge page EPT mappings for TDX VMs remain essential and complement this series well for better memory footprint and overall performance of TDX VMs.
Hmm, this didn't really answer my questions about the concrete benefits.
I think it would help to include this kind of justification for the 1GB guestmemfd pages. "essential for certain workloads and will emerge" is a bit hard to review against...
I think one of the challenges with coco is that it's almost like a sprint to reimplement virtualization. But enough things are changing at once that not all of the normal assumptions hold, so it can't copy all the same solutions. The recent example was that for TDX huge pages we found that normal promotion paths weren't actually yielding any benefit for surprising TDX specific reasons.
Quoted 5 lines
On the TDX side we are also, at least currently, unmapping private pages while they are mapped shared, so any 1GB pages would get split to 2MB if there are any shared pages in them. I wonder how many 1GB pages there would be after all the shared pages are converted. At smaller TD sizes, it could be not much.
Quoted 4 lines
You're conflating two different things.
guest_memfdallocating and managing 1GiB physical pages, and KVM mapping memory into the guest at 1GiB/2MiB granularity. Allocating memory in 1GiB chunks is useful even if KVM can only map memory into the guest using 4KiB pages.
Quoted 5 lines
I'm aware of the 1.6% vmemmap benefits from the LPC talk. Is there more? The list quoted there was more about guest performance. Or maybe the clever page table walkers that find contiguous small mappings could benefit guest performance too? It's the kind of thing I'd like to see at least broadly called out.
The crux of this series really is hugetlb backing support for guest_memfd and handling CoCo VMs irrespective of the page size as I suggested earlier, so 2M page sizes will need to handle similar complexity of in-place conversion.
Google internally uses 1G hugetlb pages to achieve high bandwidth IO, lower memory footprint using HVO and lower MMU/IOMMU page table memory footprint among other improvements. These percentages carry a substantial impact when working at the scale of large fleets of hosts each carrying significant memory capacity.
guest_memfd hugepage support + hugepage EPT mapping support for TDX VMs significantly help:
1) ~70% decrease in TDX VM boot up time
2) ~65% decrease in TDX VM shutdown time
3) ~90% decrease in TDX VM PAMT memory overhead
4) Improvement in TDX SEPT memory overhead
And we believe this combination should also help achieve better performance with TDX connect in future.
Hugetlb huge pages are preferred as they are statically carved out at boot and so provide much better guarantees of availability. Once the pages are carved out, any VMs scheduled on such a host will need to work with the same hugetlb memory sizes. This series attempts to use hugetlb pages with in-place conversion, avoiding the double allocation problem that otherwise results in significant memory overheads for CoCo VMs.
Quoted 33 lines
I'm thinking that Google must have a ridiculous amount of learnings about VM memory management. And this is probably designed around those learnings. But reviewers can't really evaluate it if they don't know the reasons and tradeoffs taken. If it's going upstream, I think it should have at least the high level reasoning explained.
I don't mean to harp on the point so hard, but I didn't expect it to be controversial either.
Quoted 9 lines
Quoted 6 lines
So for TDX in isolation, it seems like jumping out too far ahead to effectively consider the value. But presumably you guys are testing this on SEV or something? Have you measured any performance improvement? For what kind of applications? Or is the idea to basically to make guestmemfd work like however Google does guest memory?
The longer term goal of
guest_memfdis to make it suitable for backing all VMs, hence Vishal's "Non-CoCo VMs" comment.Oh, I actually wasn't aware of this. Or maybe I remember now. I thought he was talking about pKVM.
Quoted 5 lines
Yes, some of this is useful for TDX, but we (and others) want to use
guest_memfdfor far more than just CoCo VMs.And for non-CoCo VMs, 1GiB hugepages are mandatory for various workloads.
I've heard this a lot. It must be true, but I've never seen the actual numbers. For a long time people believed 1GB huge pages on the direct map were critical, but then benchmarking on a contemporary CPU couldn't find much difference between 2MB and 1GB. I'd expect TDP huge pages to be different than that because the combined walks are huge, iTLB, etc, but I'd love to see a real number.
Re: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
In reply to Ackerley TngQuoted 31 lines · Ackerley Tng
guestmem_hugetlbis an allocator forguest_memfd. It wraps HugeTLB to provide huge folios forguest_memfd.This patch also introduces
guestmem_allocator_operationsas a set of operations that allocators forguest_memfdcan provide. In a later patch,guest_memfdwill use these operations to manage pages from an allocator.The allocator operations are memory-management specific and are placed in
mm/so key mm-specific functions do not have to be exposed unnecessarily.Signed-off-by Ackerley Tng <[email protected]>Change-Id: I3cafe111ea7b3c84755d7112ff8f8c541c11136d
--- include/linux/guestmem.h | 20 +++++ include/uapi/linux/guestmem.h | 29 +++++++ mm/Kconfig | 5 +- mm/guestmem_hugetlb.c | 159 ++++++++++++++++++++++++++++++++++ 4 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 include/linux/guestmem.h create mode 100644 include/uapi/linux/guestmem.h<snip>
mm/Kconfig +0
-0
mm/Kconfig config SECRETMEM · line 1224
Quoted 8 lines
mm/Kconfig +4
-1@@ -1218,7 +1218,10 @@ config SECRETMEM config GUESTMEM_HUGETLB bool "Enable guestmem_hugetlb allocator for guest_memfd" - depends on HUGETLBFS + select GUESTMEM + select HUGETLBFS + select HUGETLB_PAGE + select HUGETLB_PAGE_OPTIMIZE_VMEMMAP
My bad. I left out CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP_DEFAULT_ON=y in my testing and just found that when it is set, I hit
BUG_ON(pte_page(ptep_get(pte)) != walk->reuse_page);
with the basic guest_memfd_test on splitting pages on allocation.
I'll follow up with the fix soon.
Another note about testing: I've been testing in a nested VM for the development process:
1. Host
2. VM for development
3. Nested VM running kernel being developed
4. Nested nested VMs created during selftests
This series has not yet been tested on a physical host.
Quoted 6 lines
mm/Kconfig +0
-0help Enable this to make HugeTLB folios available to guest_memfd (KVM virtualization) as backing memory.
Quoted 4 lines · Vishal Annapurve
The crux of this series really is hugetlb backing support for
guest_memfdand handling CoCo VMs irrespective of the page size as I suggested earlier, so 2M page sizes will need to handle similar complexity of in-place conversion.
I assumed this part was added 1GB complexity:
mm/hugetlb.c | 488 ++---
I'll dig into the series and try to understand the point better.
Quoted 6 lines
Google internally uses 1G hugetlb pages to achieve high bandwidth IO, lower memory footprint using HVO and lower MMU/IOMMU page table memory footprint among other improvements. These percentages carry a substantial impact when working at the scale of large fleets of hosts each carrying significant memory capacity.
There must have been a lot of measuring involved in that. But the numbers I was hoping for were how much does *this* series help upstream.
Quoted 7 lines
guest_memfdhugepage support + hugepage EPT mapping support for TDX VMs significantly help:
1) ~70% decrease in TDX VM boot up time
2) ~65% decrease in TDX VM shutdown time
3) ~90% decrease in TDX VM PAMT memory overhead
4) Improvement in TDX SEPT memory overhead
Thanks. It is the difference between 4k mappings and 2MB mappings I guess? Or are you saying this is the difference between 1GB contiguous pages for TDX at 2MB mapping, and 2MB contiguous pages at TDX 2MB mappings? The 1GB part is the one I was curious about.
Quoted 3 lines
And we believe this combination should also help achieve better performance with TDX connect in future.
Please don't take this query as an objection that the series doesn't help TDX enough or something like that. If it doesn't help TDX at all (not the case), that is fine. The objection is only that the specific benefits and tradeoffs around 1GB pages are not clear in the upstream posting.
Quoted 4 lines
Hugetlb huge pages are preferred as they are statically carved out at boot and so provide much better guarantees of availability.
Reserved memory can provide physically contiguous pages more frequently. Seems not surprising at all, and something that could have a number.
Quoted 6 lines
Once the
pages are carved out, any VMs scheduled on such a host will need to work with the same hugetlb memory sizes. This series attempts to use hugetlb pages with in-place conversion, avoiding the double allocation problem that otherwise results in significant memory overheads for CoCo VMs.
I asked this question assuming there were some measurements for the 1GB part of this series. It sounds like the reasoning is instead that this is how Google does things, which is backed by way more benchmarking than kernel patches are used to getting. So it can just be reasonable assumed to be helpful.
But for upstream code, I'd expect there to be a bit more concrete than "we believe" and "substantial impact". It seems like I'm in the minority here though. So if no one else wants to pressure test the thinking in the usual way, I guess I'll just have to wonder.
Quoted 9 lines · Jason Gunthorpe
Quoted 5 lines
You're conflating two different things.
guest_memfdallocating and managing 1GiB physical pages, and KVM mapping memory into the guest at 1GiB/2MiB granularity. Allocating memory in 1GiB chunks is useful even if KVM can only
map memory into the guest using 4KiB pages.Even if KVM is limited to 4K the IOMMU might not be - alot of these workloads have a heavy IO component and we need the iommu to perform well too.
Oh, interesting point.
Quoted 3 lines
Frankly, I don't think there should be objection to making memory more contiguous.
No objections from me to anything except the lack of concrete justification.
Quoted 2 lines
There is alot of data that this always brings wins somewhere for someone.
For the direct map huge page benchmarking, they saw that sometimes 1GB pages helped, but also sometimes 2MB pages helped. That 1GB will help *some* workload doesn't seem surprising.
Quoted 9 lines
Quoted 8 lines
The longer term goal of
guest_memfdis to make it suitable for backing all VMs,
hence Vishal's "Non-CoCo VMs" comment. Yes, some of this is useful for TDX, but
we (and others) want to useguest_memfdfor far more than just CoCo VMs. And
for non-CoCo VMs, 1GiB hugepages are mandatory for various workloads.
Quoted 3 lines
Yes, even from an iommu perspective with 2D translation we need to have the 1G pages from the S2 resident in the IOTLB or performance falls off a cliff.
"falls off a cliff" is the level of detail and the direction of hand waving I have been hearing. But it also seems modern CPUs are quite good at hiding the cost of walks with caches etc. Like how 5 level paging was made unconditional. I didn't think about IOTLB though. Thanks for mentioning it.
Re: [RFC PATCH v2 03/51] KVM: selftests: Update guest_memfd_test for INIT_PRIVATE flag
In reply to Ira WeinyQuoted 71 lines · Ira Weiny
Quoted 56 lines · Ackerley Tng
Test that
GUEST_MEMFD_FLAG_INIT_PRIVATEis only valid whenGUEST_MEMFD_FLAG_SUPPORT_SHAREDis set.Change-Id I506e236a232047cfaee17bcaed02ee14c8d25bbbSigned-off-by Ackerley Tng <[email protected]>--- .../testing/selftests/kvm/guest_memfd_test.c | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-)tools/testing/selftests/kvm/guest_memfd_test.c +21
-5@@ -401,13 +401,31 @@ static void test_with_type(unsigned long vm_type, uint64_t guest_memfd_flags,kvm_vm_release (vm); } +static void test_vm_with_gmem_flag (struct kvm_vm *vm,uint64_t flag, +bool expect_valid) +{ +size_t page_size =getpagesize (); +int fd; + + fd =__vm_create_guest_memfd (vm, page_size, flag); + +if (expect_valid) { +TEST_ASSERT (fd >0 , +"guest_memfd() with flag '0x%lx' should be valid" , + flag); +close (fd); + }else { +TEST_ASSERT (fd ==-1 && errno ==EINVAL , +"guest_memfd() with flag '0x%lx' should fail with EINVAL" , + flag); + } +} +static void test_vm_type_gmem_flag_validity (unsigned long vm_type,uint64_t expected_valid_flags) { -size_t page_size =getpagesize ();struct kvm_vm *vm;uint64_t flag =0 ; -int fd;if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type)))return ;@@ -415,17 +433,11 @@ static void test_vm_type_gmem_flag_validity(unsigned long vm_type, vm =vm_create_barebones_type (vm_type);for (flag =BIT (0 ); flag; flag <<=1 ) { - fd =__vm_create_guest_memfd (vm, page_size, flag); +test_vm_with_gmem_flag (vm, flag, flag & expected_valid_flags); -if (flag & expected_valid_flags) { - TEST_ASSERT(fd > 0,tools/testing/selftests/kvm/guest_memfd_test.c static void test_vm_type_gmem_flag_validity(unsigned long vm_type, · line 440
Quoted 10 lines
tools/testing/selftests/kvm/guest_memfd_test.c +3
-7-"guest_memfd() with flag '0x%lx' should be valid" , - flag); -close (fd); - }else { -TEST_ASSERT (fd ==-1 && errno ==EINVAL , -"guest_memfd() with flag '0x%lx' should fail with EINVAL" , - flag); +if (flag ==GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { +test_vm_with_gmem_flag ( + vm, flag |GUEST_MEMFD_FLAG_INIT_PRIVATE , true);I don't understand the point of this check. In 2/51 we set
GUEST_MEMFD_FLAG_INIT_PRIVATEwhenGUEST_MEMFD_FLAG_SUPPORT_SHAREDis set.
Quoted 3 lines
When can this check ever fail?
Ira
In 02/51, GUEST_MEMFD_FLAG_INIT_PRIVATE is not set by default, GUEST_MEMFD_FLAG_INIT_PRIVATE is set as one of the valid_flags.
The intention is that GUEST_MEMFD_FLAG_INIT_PRIVATE is only valid if GUEST_MEMFD_FLAG_SUPPORT_SHARED is requested by userspace.
In this test, the earlier part before the if block calls test_vm_with_gmem_flag() all valid flags, and that already tests GUEST_MEMFD_FLAG_SUPPORT_SHARED individually.
Specifically if GUEST_MEMFD_FLAG_SUPPORT_SHARED is set, this if block adds a test for when both GUEST_MEMFD_FLAG_SUPPORT_SHARED and GUEST_MEMFD_FLAG_INIT_PRIVATE are set, and sets that expect_valid is true.
This second test doesn't fail, it is meant to check that the kernel allows the pair of flags to be set. Hope that makes sense.
Sean Christopherson
maintainerQuoted 13 lines · Vishal Annapurve
Quoted 11 lines · Rick P
Quoted 4 lines · Sean Christopherson
You're conflating two different things.
guest_memfdallocating and managing 1GiB physical pages, and KVM mapping memory into the guest at 1GiB/2MiB granularity. Allocating memory in 1GiB chunks is useful even if KVM can only map memory into the guest using 4KiB pages.I'm aware of the 1.6% vmemmap benefits from the LPC talk. Is there more? The list quoted there was more about guest performance. Or maybe the clever page table walkers that find contiguous small mappings could benefit guest performance too? It's the kind of thing I'd like to see at least broadly called out.
Quoted 5 lines
The crux of this series really is hugetlb backing support for
guest_memfdand handling CoCo VMs irrespective of the page size as I suggested earlier, so 2M page sizes will need to handle similar complexity of in-place conversion.Google internally uses 1G hugetlb pages to achieve high bandwidth IO,
E.g. hitting target networking line rates is only possible with 1GiB mappings, otherwise TLB pressure gets in the way.
Quoted 4 lines
lower memory footprint using HVO and lower MMU/IOMMU page table memory footprint among other improvements. These percentages carry a substantial impact when working at the scale of large fleets of hosts each carrying significant memory capacity.
Yeah, 1.6% might sound small, but over however many bytes of RAM there are in the fleet, it's a huge (lol) amount of memory saved.
Quoted 10 lines
Quoted 10 lines
Quoted 5 lines
Yes, some of this is useful for TDX, but we (and others) want to use
guest_memfdfor far more than just CoCo VMs.And for non-CoCo VMs, 1GiB hugepages are mandatory for various workloads.
I've heard this a lot. It must be true, but I've never seen the actual numbers. For a long time people believed 1GB huge pages on the direct map were critical, but then benchmarking on a contemporary CPU couldn't find much difference between 2MB and 1GB. I'd expect TDP huge pages to be different than that because the combined walks are huge, iTLB, etc, but I'd love to see a real number.
The direct map is very, very different than userspace and thus guest mappings. Software (hopefully) isn't using the direct map to index multi-TiB databases, or to transfer GiBs of data over the network. The amount of memory the kernel is regularly accessing is an order or two magnitude smaller than single process use cases.
A few examples from a quick search:
http://pvk.ca/Blog/2014/02/18/how-bad-can-1gb-pages-be
https://www.percona.com/blog/benchmark-postgresql-with-linux-hugepages/
Sean Christopherson
maintainerQuoted 9 lines · Rick P Edgecombe
Quoted 5 lines · Vishal Annapurve
Google internally uses 1G hugetlb pages to achieve high bandwidth IO, lower memory footprint using HVO and lower MMU/IOMMU page table memory footprint among other improvements. These percentages carry a substantial impact when working at the scale of large fleets of hosts each carrying significant memory capacity.
There must have been a lot of measuring involved in that. But the numbers I was hoping for were how much does *this* series help upstream.
...
Quoted 9 lines
I asked this question assuming there were some measurements for the 1GB part of this series. It sounds like the reasoning is instead that this is how Google does things, which is backed by way more benchmarking than kernel patches are used to getting. So it can just be reasonable assumed to be helpful.
But for upstream code, I'd expect there to be a bit more concrete than "we believe" and "substantial impact". It seems like I'm in the minority here though. So if no one else wants to pressure test the thinking in the usual way, I guess I'll just have to wonder.
From my perspective, 1GiB hugepage support in guest_memfd isn't about improving CoCo performance, it's about achieving feature parity on guest_memfd with respect to existing backing stores so that it's possible to use guest_memfd to back all VM shapes in a fleet.
Let's assume there is significant value in backing non-CoCo VMs with 1GiB pages, unless you want to re-litigate the existence of 1GiB support in HugeTLBFS.
If we assume 1GiB support is mandatory for non-CoCo VMs, then it becomes mandatory for CoCo VMs as well, because it's the only realistic way to run CoCo VMs and non-CoCo VMs on a single host. Mixing 1GiB HugeTLBFS with any other backing store for VMs simply isn't tenable due to the nature of 1GiB allocations. E.g. grabbing sub-1GiB chunks of memory for CoCo VMs quickly fragments memory to the point where HugeTLBFS can't allocate memory for non-CoCo VMs.
Teaching HugeTLBFS to play nice with TDX and SNP isn't happening, which leaves adding 1GiB support to guest_memfd as the only way forward.
Any boost to TDX (or SNP) performance is purely a bonus.
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Ira WeinyQuoted 28 lines · Ira Weiny
Ackerley Tng wrote:
[snip]
Quoted 2 lines
Signed-off-by Ackerley Tng <[email protected]>[snip]
Quoted 19 lines
virt/kvm/guest_memfd.c +4
-0@@ -30,6 +30,10 @@ enum shareability { };static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index); +static void kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end); +static void kvm_gmem_invalidate_end (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end);static struct kvm_gmem_inode_private *kvm_gmem_private (struct inode *inode) {@@ -85,6 +89,306 @@ static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t indereturn kvm_gmem_get_folio (inode, index); }
Quoted 14 lines
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t inde
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+/** +* kvm_gmem_shareability_store() - Sets shareability to @value for range. +* +* @mt: the shareability maple tree. +* @index: the range begins at this index in the inode. +* @nr_pages: number of PAGE_SIZE pages in this range. +* @value: the shareability value to set for this range. +* +* Unlike mtree_store_range(), this function also merges adjacent ranges that +* have the same values as an optimization. Is this an optimization or something which will be required to convert from shared back to private and back to a huge page mapping?
This is an optimization.
Quoted 3 lines
If this is purely an optimization it might be best to leave it out for now to get functionality first.
I see this (small) optimization as part of using maple trees.
Fuad's version [1] uses xarrays and has 1 xarray entry per page offset. I wanted to illustrate that by using maple trees, we can share just 1 entry for a whole range, and part of that sharing involves merging adjacent shareability entries that have the same value.
IIUC, these other users of maple trees also do some kind of expansion/range merging:
+ VMAs in vma_expand() [2]
+ regcache in regcache_maple_write() [3]
Quoted 5 lines
I have more to review but wanted to ask this.
Ira
[snip]
[1] https://lore.kernel.org/all/[email protected]/
[2] https://elixir.bootlin.com/linux/v6.14.6/source/mm/vma.c#L1059
[3] https://elixir.bootlin.com/linux/v6.14.6/source/drivers/base/regmap/regcache-maple.c#L38
Quoted 7 lines · Sean Christopherson
From my perspective, 1GiB hugepage support in
guest_memfdisn't about improving CoCo performance, it's about achieving feature parity onguest_memfdwith respect to existing backing stores so that it's possible to useguest_memfdto back all VM shapes in a fleet.Let's assume there is significant value in backing non-CoCo VMs with 1GiB pages, unless you want to re-litigate the existence of 1GiB support in HugeTLBFS.
I didn't expect to go in that direction when I first asked. But everyone says huge, but no one knows the numbers. It can be a sign of things.
Meanwhile I'm watching patches to make 5 level paging walks unconditional fly by because people couldn't find a cost to the extra level of walk. So re-litigate, no. But I'll probably remain quietly suspicious of the exact cost/value. At least on the CPU side, I totally missed the IOTLB side at first, sorry.
Quoted 7 lines
If we assume 1GiB support is mandatory for non-CoCo VMs, then it becomes mandatory for CoCo VMs as well, because it's the only realistic way to run CoCo VMs and non-CoCo VMs on a single host. Mixing 1GiB HugeTLBFS with any other backing store for VMs simply isn't tenable due to the nature of 1GiB allocations. E.g. grabbing sub-1GiB chunks of memory for CoCo VMs quickly fragments memory to the point where HugeTLBFS can't allocate memory for non-CoCo VMs.
It makes sense that there would be a difference in how many huge pages the non- coco guests would get. Where I start to lose you is when you guys talk about "mandatory" or similar. If you want upstream review, it would help to have more numbers on the "why" question. At least for us folks outside the hyperscalars where such things are not as obvious.
Quoted 5 lines
Teaching HugeTLBFS to play nice with TDX and SNP isn't happening, which leaves adding 1GiB support to
guest_memfdas the only way forward.Any boost to TDX (or SNP) performance is purely a bonus.
Most of the bullets in the talk were about mapping sizes AFAICT, so this is the kind of reasoning I was hoping for. Thanks for elaborating on it, even though still no one has any numbers besides the vmemmap savings.
Re: [RFC PATCH v2 03/51] KVM: selftests: Update guest_memfd_test for INIT_PRIVATE flag
In reply to Ackerley TngQuoted 73 lines · Ackerley Tng
Quoted 71 lines · Ira Weiny
Quoted 56 lines · Ackerley Tng
Test that
GUEST_MEMFD_FLAG_INIT_PRIVATEis only valid whenGUEST_MEMFD_FLAG_SUPPORT_SHAREDis set.Change-Id I506e236a232047cfaee17bcaed02ee14c8d25bbbSigned-off-by Ackerley Tng <[email protected]>--- .../testing/selftests/kvm/guest_memfd_test.c | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-)tools/testing/selftests/kvm/guest_memfd_test.c +21
-5@@ -401,13 +401,31 @@ static void test_with_type(unsigned long vm_type, uint64_t guest_memfd_flags,kvm_vm_release (vm); } +static void test_vm_with_gmem_flag (struct kvm_vm *vm,uint64_t flag, +bool expect_valid) +{ +size_t page_size =getpagesize (); +int fd; + + fd =__vm_create_guest_memfd (vm, page_size, flag); + +if (expect_valid) { +TEST_ASSERT (fd >0 , +"guest_memfd() with flag '0x%lx' should be valid" , + flag); +close (fd); + }else { +TEST_ASSERT (fd ==-1 && errno ==EINVAL , +"guest_memfd() with flag '0x%lx' should fail with EINVAL" , + flag); + } +} +static void test_vm_type_gmem_flag_validity (unsigned long vm_type,uint64_t expected_valid_flags) { -size_t page_size =getpagesize ();struct kvm_vm *vm;uint64_t flag =0 ; -int fd;if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type)))return ;@@ -415,17 +433,11 @@ static void test_vm_type_gmem_flag_validity(unsigned long vm_type, vm =vm_create_barebones_type (vm_type);for (flag =BIT (0 ); flag; flag <<=1 ) { - fd =__vm_create_guest_memfd (vm, page_size, flag); +test_vm_with_gmem_flag (vm, flag, flag & expected_valid_flags); -if (flag & expected_valid_flags) { - TEST_ASSERT(fd > 0,tools/testing/selftests/kvm/guest_memfd_test.c static void test_vm_type_gmem_flag_validity(unsigned long vm_type, · line 440
Quoted 10 lines
tools/testing/selftests/kvm/guest_memfd_test.c +3
-7-"guest_memfd() with flag '0x%lx' should be valid" , - flag); -close (fd); - }else { -TEST_ASSERT (fd ==-1 && errno ==EINVAL , -"guest_memfd() with flag '0x%lx' should fail with EINVAL" , - flag); +if (flag ==GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { +test_vm_with_gmem_flag ( + vm, flag |GUEST_MEMFD_FLAG_INIT_PRIVATE , true);I don't understand the point of this check. In 2/51 we set
GUEST_MEMFD_FLAG_INIT_PRIVATEwhenGUEST_MEMFD_FLAG_SUPPORT_SHAREDis set.
Quoted 6 lines
Quoted 3 lines
When can this check ever fail?
Ira
In 02/51,
GUEST_MEMFD_FLAG_INIT_PRIVATEis not set by default,GUEST_MEMFD_FLAG_INIT_PRIVATEis set as one of thevalid_flags.
Ah My mistake I read that too quickly.
Thanks,
Ira
Quoted 15 lines
The intention is that
GUEST_MEMFD_FLAG_INIT_PRIVATEis only valid ifGUEST_MEMFD_FLAG_SUPPORT_SHAREDis requested by userspace.In this test, the earlier part before the if block calls
test_vm_with_gmem_flag()all valid flags, and that already testsGUEST_MEMFD_FLAG_SUPPORT_SHAREDindividually.Specifically if
GUEST_MEMFD_FLAG_SUPPORT_SHAREDis set, this if block adds a test for when bothGUEST_MEMFD_FLAG_SUPPORT_SHAREDandGUEST_MEMFD_FLAG_INIT_PRIVATEare set, and sets thatexpect_validis true.This second test doesn't fail, it is meant to check that the kernel allows the pair of flags to be set. Hope that makes sense.
Quoted 8 lines · Ackerley Tng
Hello,
This patchset builds upon discussion at LPC 2024 and many
guest_memfdupstream calls to provide 1G page support forguest_memfdby taking pages from HugeTLB.This patchset is based on Linux v6.15-rc6, and requires the mmap support for
guest_memfdpatchset (Thanks Fuad!) [1].
Trying to manage dependencies I find that Ryan's just released series[1] is required to build this set.
[1] https://lore.kernel.org/all/[email protected]/
Specifically this patch:
https://lore.kernel.org/all/1f42c32fc18d973b8ec97c8be8b7cd921912d42a.1747368092.git.afranji@google.com/ defines alloc_anon_secure_inode()
Am I wrong in that?
Quoted 4 lines
For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2
I went digging in your git tree and then found Ryan's set. So thanks for the git tree. :-D
However, it seems this add another dependency which should be managed in David's email of dependencies?
Ira
Quoted 99 lines
This patchset can be divided into two sections:
(a) Patches from the beginning up to and including "KVM: selftests:
Update script to map shared memory fromguest_memfd" are a modified version of "conversion support forguest_memfd", which Fuad is managing [2].(b) Patches after "KVM: selftests: Update script to map shared memory from
guest_memfd" till the end are patches that actually bring in 1G page support forguest_memfd.These are the significant differences between (a) and [2]:
+ [2] uses an xarray to track sharability, but I used a maple tree because for 1G pages, iterating pagewise to update shareability was prohibitively slow even for testing. I was choosing from among multi-index xarrays, interval trees and maple trees [3], and picked maple trees because
+ Maple trees were easier to figure out since I didn't have to compute the correct multi-index order and handle edge cases if the converted range wasn't a neat power of 2.
+ Maple trees were easier to figure out as compared to updating parts of a multi-index xarray.
+ Maple trees had an easier API to use than interval trees.
+ [2] doesn't yet have a conversion ioctl, but I needed it to test 1G support end-to-end.
+ (a) Removesguest_memfdfrom participating in LRU, which I needed, to get conversion selftests to work as expected, since participation in LRU was causing some unexpected refcounts on folios which was blocking conversions.I am sending (a) in emails as well, as opposed to just leaving it on GitHub, so that we can discuss by commenting inline on emails. If you'd like to just look at 1G page support, here are some key takeaways from the first section (a):
+ If
GUEST_MEMFD_FLAG_SUPPORT_SHAREDis requested duringguest_memfdcreation,guest_memfdwill
+ Track shareability (whether an index in the inode is guest-only or if the host is allowed to fault memory at a given index).
+ Always be used for guest faults - specifically,kvm_gmem_get_pfn()will be used to provide pages for the guest.
+ Always be used by KVM to check private/shared status of a gfn.
+guest_memfdnow has conversion ioctls, allowing conversion to private/shared
+ Conversion can fail if there are unexpected refcounts on any folios in the range.Focusing on (b) 1G page support, here's an overview:
1. A bunch of refactoring patches for HugeTLB that isolates the allocation of a HugeTLB folio from other HugeTLB concepts such as VMA-level reservations, and HugeTLBfs-specific concepts, such as where memory policy is stored in the VMA, or where the subpool is stored on the inode.
2. A few patches that add aguestmem_hugetlballocator withinmm/. Theguestmem_hugetlballocator is a wrapper around HugeTLB to modularize the memory management functions, and to cleanly handle cleanup, so that folio cleanup can happen after theguest_memfdinode (and even KVM) goes away.
3. Some updates toguest_memfdto use theguestmem_hugetlballocator.
4. Selftests for 1G page support.Here are some remaining issues/TODOs:
1. Memory error handling such as machine check errors have not been implemented.
2. I've not looked into preparedness of pages, only zeroing has been considered.
3. When allocating HugeTLB pages, if two threads allocate indices mapping to the same huge page, the utilization inguest_memfdinode's subpool may momentarily go over the subpool limit (the requested size of the inode atguest_memfdcreation time), causing one of the two threads to get-ENOMEM. Suggestions to solve this are appreciated!
4.max_usage_in_bytesstatistic (cgroups v1) forguest_memfdHugeTLB pages should be correct but needs testing and could be wrong.
5. memcg charging (charge_memcg()) for cgroups v2 forguest_memfdHugeTLB pages after splitting should be correct but needs testing and could be wrong.
6. Page cache accounting: When a hugetlb page is split,guest_memfdwill incur page count in bothNR_HUGETLB(counted at hugetlb allocation time) andNR_FILE_PAGESstats (counted when split pages are added to the filemap). Is this aligned with what people expect?Here are some optimizations that could be explored in future series:
1. Pages could be split from 1G to 2M first and only split to 4K if necessary.
2. Zeroing could be skipped for Coco VMs if hardware already zeroes the pages.Here's RFC v1 [4] if you're interested in the motivation behind choosing HugeTLB, or the history of this patch series.
[1] https://lore.kernel.org/all/[email protected]/T/
[2] https://lore.kernel.org/all/[email protected]/T/
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/T/
Quoted 13 lines · Ira Weiny
Quoted 8 lines · Ackerley Tng
Hello,
This patchset builds upon discussion at LPC 2024 and many
guest_memfdupstream calls to provide 1G page support forguest_memfdby taking pages from HugeTLB.This patchset is based on Linux v6.15-rc6, and requires the mmap support for
guest_memfdpatchset (Thanks Fuad!) [1].Trying to manage dependencies I find that Ryan's just released series[1] is required to build this set.
Quoted 8 lines
[1] https://lore.kernel.org/all/[email protected]/
Specifically this patch:
https://lore.kernel.org/all/1f42c32fc18d973b8ec97c8be8b7cd921912d42a.1747368092.git.afranji@google.com/ defines alloc_anon_secure_inode()
Perhaps Ryan's set is not required? Just that patch?
It looks like Ryan's 2/13 is the same as your 1/51 patch?
I'll pull 1/13 and see where I get.
Ira
Quoted 16 lines
Am I wrong in that?
Quoted 4 lines
For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2
I went digging in your git tree and then found Ryan's set. So thanks for the git tree. :-D
However, it seems this add another dependency which should be managed in David's email of dependencies?
Ira
Quoted 4 lines · Rick P
Meanwhile I'm watching patches to make 5 level paging walks unconditional fly by because people couldn't find a cost to the extra level of walk. So re-litigate, no. But I'll probably remain quietly suspicious of the exact cost/value. At least on the CPU side, I totally missed the IOTLB side at first, sorry.
It's a little more complicated than just the depth of the worst-case walk.
In practice, many page walks can use the mid-level paging structure caches because the mappings aren't sparse.
With 5-level paging in particular, userspace doesn't actually change much at all. Its layout is pretty much the same unless folks are opting in to the higher (5-level only) address space. So userspace isn't sparse, at least at the scale of what 5-level paging is capable of.
For the kernel, things are a bit more spread out than they were before. For instance, the direct map and vmalloc() are in separate p4d pages when they used to be nestled together in the same half of one pgd.
But, again, they're not *that* sparse. The direct map, for example, doesn't become more sparse, it just moves to a lower virtual address. Ditto for vmalloc(). Just because 5-level paging has a massive vmalloc() area doesn't mean we use it.
Basically, 5-level paging adds a level to the top of the page walk, and we're really good at caching those when they're not accessed sparsely.
CPUs are not as good at caching the leaf side of the page walk. There are tricks like AMD's TLB coalescing that help. But, generally, each walk on the leaf end of the walks eats a TLB entry. Those just don't cache as well as the top of the tree.
That's why we need to be more maniacal about reducing leaf levels than the levels toward the root.
Quoted 25 lines · Ira Weiny
Quoted 13 lines · Ira Weiny
Quoted 8 lines · Ackerley Tng
Hello,
This patchset builds upon discussion at LPC 2024 and many
guest_memfdupstream calls to provide 1G page support forguest_memfdby taking pages from HugeTLB.This patchset is based on Linux v6.15-rc6, and requires the mmap support for
guest_memfdpatchset (Thanks Fuad!) [1].Trying to manage dependencies I find that Ryan's just released series[1] is required to build this set.
Quoted 8 lines
[1] https://lore.kernel.org/all/[email protected]/
Specifically this patch:
https://lore.kernel.org/all/1f42c32fc18d973b8ec97c8be8b7cd921912d42a.1747368092.git.afranji@google.com/ defines alloc_anon_secure_inode()Perhaps Ryan's set is not required? Just that patch?
Quoted 11 lines
It looks like Ryan's 2/13 is the same as your 1/51 patch?
I'll pull 1/13 and see where I get.
Ira
Quoted 3 lines
Am I wrong in that?
My bad, this patch was missing from this series:
From bd629d1ec6ffb7091a5f996dc7835abed8467f3e Mon Sep 17 00:00:00 2001
Message-ID: <bd629d1ec6ffb7091a5f996dc7835abed8467f3e.1747426836.git.ackerleytng@google.com>
From: Ackerley Tng <[email protected]>
Date: Wed, 7 May 2025 07:59:28 -0700
Subject: [RFC PATCH v2 1/1] fs: Refactor to provide function that allocates a
secure anonymous inode
alloc_anon_secure_inode() returns an inode after running checks in security_inode_init_security_anon().
Also refactor secretmem's file creation process to use the new function.
--- fs/anon_inodes.c | 22 ++++++++++++++++------ include/linux/fs.h | 1 + mm/secretmem.c | 9 +-------- 3 files changed, 18 insertions(+), 14 deletions(-)
fs/anon_inodes.c +16 -6
@@ -55,17 +55,20 @@ static struct file_system_type anon_inode_fs_type = { .kill_sb = kill_anon_super, }; -static struct inode *anon_inode_make_secure_inode ( -const char *name, -const struct inode *context_inode) +static struct inode *anon_inode_make_secure_inode (struct super_block *s, +const char *name,const struct inode *context_inode, +bool fs_internal) {struct inode *inode;int error; - inode =alloc_anon_inode (anon_inode_mnt->mnt_sb); + inode =alloc_anon_inode (s);if (IS_ERR (inode))return inode; - inode->i_flags &= ~S_PRIVATE ; + +if (!fs_internal) + inode->i_flags &= ~S_PRIVATE ; + error =security_inode_init_security_anon (inode, &QSTR (name), context_inode);if (error) {
@@ -75,6 +78,12 @@ static struct inode *anon_inode_make_secure_inode(return inode; } +struct inode *alloc_anon_secure_inode (struct super_block *s,const char *name) +{ +return anon_inode_make_secure_inode (s, name,NULL , true); +} +EXPORT_SYMBOL_GPL (alloc_anon_secure_inode); + static struct file *__anon_inode_getfile(const char *name, const struct file_operations *fops, void *priv, int flags,
@@ -88,7 +97,8 @@ static struct file *__anon_inode_getfile(const char *name,return ERR_PTR (-ENOENT );if (make_inode) { - inode =anon_inode_make_secure_inode (name, context_inode); + inode =anon_inode_make_secure_inode (anon_inode_mnt->mnt_sb, + name, context_inode, false);if (IS_ERR (inode)) { file =ERR_CAST (inode); goto err;
include/linux/fs.h +1 -0
@@ -3550,6 +3550,7 @@ extern int simple_write_begin(struct file *file, struct address_space *mapping,extern const struct address_space_operations ram_aops;extern int always_delete_dentry (const struct dentry *);extern struct inode *alloc_anon_inode (struct super_block *); +extern struct inode *alloc_anon_secure_inode (struct super_block *,const char *);extern int simple_nosetlease (struct file *,int ,struct file_lease **,void **);extern const struct dentry_operations simple_dentry_operations;
mm/secretmem.c +1 -8
@@ -195,18 +195,11 @@ static struct file *secretmem_file_create(unsigned long flags)struct file *file;struct inode *inode;const char *anon_name ="[secretmem]" ; -int err; - inode =alloc_anon_inode (secretmem_mnt->mnt_sb); + inode =alloc_anon_secure_inode (secretmem_mnt->mnt_sb, anon_name);if (IS_ERR (inode))return ERR_CAST (inode); - err =security_inode_init_security_anon (inode, &QSTR (anon_name),NULL ); -if (err) { - file =ERR_PTR (err); - goto err_free_inode; - } - file =alloc_file_pseudo (inode, secretmem_mnt,"secretmem" ,O_RDWR , &secretmem_fops);if (IS_ERR (file))
Signature · 1 line
2.49.0.1101.gccaa498523-goog
Quoted 7 lines
Quoted 7 lines
Quoted 4 lines
For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2
I went digging in your git tree and then found Ryan's set. So thanks for the git tree. :-D
Glad that helped!
Quoted 3 lines
Quoted 3 lines
However, it seems this add another dependency which should be managed in David's email of dependencies?
This is a good idea. David, do you think these two patches should be managed as a separate patch series in the email of dependencies?
+ (left out of RFCv2, but is above) "fs: Refactor to provide function that allocates a secure anonymous inode"
+ 01/51 "KVM: guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodes"
They're being used by a few patch series now.
Quoted 3 lines
Quoted 3 lines
Ira
Re: [RFC PATCH v2 29/51] mm: guestmem_hugetlb: Wrap HugeTLB as an allocator for guest_memfd
In reply to Ackerley TngQuoted 54 lines · Ackerley Tng
Quoted 31 lines · Ackerley Tng
guestmem_hugetlbis an allocator forguest_memfd. It wraps HugeTLB to provide huge folios forguest_memfd.This patch also introduces
guestmem_allocator_operationsas a set of operations that allocators forguest_memfdcan provide. In a later patch,guest_memfdwill use these operations to manage pages from an allocator.The allocator operations are memory-management specific and are placed in
mm/so key mm-specific functions do not have to be exposed unnecessarily.Signed-off-by Ackerley Tng <[email protected]>Change-Id: I3cafe111ea7b3c84755d7112ff8f8c541c11136d
--- include/linux/guestmem.h | 20 +++++ include/uapi/linux/guestmem.h | 29 +++++++ mm/Kconfig | 5 +- mm/guestmem_hugetlb.c | 159 ++++++++++++++++++++++++++++++++++ 4 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 include/linux/guestmem.h create mode 100644 include/uapi/linux/guestmem.h<snip>
mm/Kconfig +0
-0mm/Kconfig config SECRETMEM · line 1224
Quoted 8 lines
mm/Kconfig +4
-1@@ -1218,7 +1218,10 @@ config SECRETMEM config GUESTMEM_HUGETLB bool "Enable guestmem_hugetlb allocator for guest_memfd" - depends on HUGETLBFS + select GUESTMEM + select HUGETLBFS + select HUGETLB_PAGE + select HUGETLB_PAGE_OPTIMIZE_VMEMMAPMy bad. I left out
CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP_DEFAULT_ON=yin my testing and just found that when it is set, I hitBUG_ON(pte_page(ptep_get(pte)) != walk->reuse_page);with the basic
guest_memfd_teston splitting pages on allocation.I'll follow up with the fix soon.
Another note about testing: I've been testing in a nested VM for the development process:
Quoted 13 lines
1. Host
2. VM for development
3. Nested VM running kernel being developed
4. Nested nested VMs created during selftestsThis series has not yet been tested on a physical host.
Quoted 6 lines
mm/Kconfig +0
-0help Enable this to make HugeTLB folios available to guest_memfd (KVM virtualization) as backing memory.
Here's the fix for this issue
From 998af6404d4e39920ba42764e7f3815cb9bb9e3d Mon Sep 17 00:00:00 2001
Message-ID: <998af6404d4e39920ba42764e7f3815cb9bb9e3d.1747427489.git.ackerleytng@google.com>
From: Ackerley Tng <[email protected]>
Date: Fri, 16 May 2025 13:14:55 -0700
Subject: [RFC PATCH v2 1/1] KVM: guest_memfd: Reorder undoing vmemmap
optimization and stashing hugetlb folio metadata
Without this patch, when HugeTLB folio metadata is stashed, the vmemmap_optimized flag, stored in a HugeTLB folio's folio->private was stashed as set.
The first splitting works, but on merging, when the folio metadata was unstashed, vmemmap_optimized is unstashed as set, making the call to hugetlb_vmemmap_optimize_folio() skip actually applying optimizations.
On a second split, hugetlb_vmemmap_restore_folio() attempts to reapply optimizations when it was already applied, hence hitting the BUG().
--- mm/guestmem_hugetlb.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-)
mm/guestmem_hugetlb.c +11 -7
@@ -200,16 +200,21 @@ static int guestmem_hugetlb_split_folio(struct folio *folio)return 0 ; orig_nr_pages =folio_nr_pages (folio); - ret =guestmem_hugetlb_stash_metadata (folio); + +/* +* hugetlb_vmemmap_restore_folio() has to be called ahead of the rest +* because it checks page type. This doesn't actually split the folio, +* so the first few struct pages are still intact. +*/ + ret =hugetlb_vmemmap_restore_folio (folio_hstate (folio), folio);if (ret)return ret;/* -* hugetlb_vmemmap_restore_folio() has to be called ahead of the rest -* because it checks and page type. This doesn't actually split the -* folio, so the first few struct pages are still intact. +* Stash metadata after vmemmap stuff so the outcome of the vmemmap +* restoration is stashed. */ - ret =hugetlb_vmemmap_restore_folio (folio_hstate (folio), folio); + ret =guestmem_hugetlb_stash_metadata (folio);if (ret) goto err;
@@ -254,8 +259,7 @@ static int guestmem_hugetlb_split_folio(struct folio *folio)return 0 ; err: -guestmem_hugetlb_unstash_free_metadata (folio); - +hugetlb_vmemmap_optimize_folio (folio_hstate (folio), folio);return ret; }
Signature · 1 line
2.49.0.1101.gccaa498523-goog
Quoted 22 lines · Dave Hansen
It's a little more complicated than just the depth of the worst-case walk.
In practice, many page walks can use the mid-level paging structure caches because the mappings aren't sparse.
With 5-level paging in particular, userspace doesn't actually change much at all. Its layout is pretty much the same unless folks are opting in to the higher (5-level only) address space. So userspace isn't sparse, at least at the scale of what 5-level paging is capable of.
For the kernel, things are a bit more spread out than they were before. For instance, the direct map and
vmalloc()are in separate p4d pages when they used to be nestled together in the same half of one pgd.But, again, they're not *that* sparse. The direct map, for example, doesn't become more sparse, it just moves to a lower virtual address. Ditto for vmalloc(). Just because 5-level paging has a massive
vmalloc()area doesn't mean we use it.Basically, 5-level paging adds a level to the top of the page walk, and we're really good at caching those when they're not accessed sparsely.
Quoted 7 lines
CPUs are not as good at caching the leaf side of the page walk. There are tricks like AMD's TLB coalescing that help. But, generally, each walk on the leaf end of the walks eats a TLB entry. Those just don't cache as well as the top of the tree.
That's why we need to be more maniacal about reducing leaf levels than the levels toward the root.
Makes sense. For what is easy for the CPU to cache, it can be more about the address space layout then the length of the walk.
Going off topic from this patchset...
I have a possibly fun related anecdote. A while ago when I was doing the KVM XO stuff, I was trying to test how much worse the performance was from caches being forced to deal with the sparser GPA accesses. The test was to modify the guest to force all the executable GVA mappings to go on the XO alias. I was confused to find that KVM XO was faster than the normal layout by a small, but consistent amount. It had me scratching my head. It turned out that the NX huge page mitigation was able to maintain large pages for the data accesses because all the executable accesses were moved off of the main GPA alias.
My takeaway was that the real world implementations can interact in surprising ways, and for at least my ability to reason about it, it's good to verify with a test when possible.
Quoted 14 lines · Ackerley Tng
<snip>
Here are some remaining issues/TODOs:
1. Memory error handling such as machine check errors have not been implemented.
2. I've not looked into preparedness of pages, only zeroing has been considered.
3. When allocating HugeTLB pages, if two threads allocate indices mapping to the same huge page, the utilization inguest_memfdinode's subpool may momentarily go over the subpool limit (the requested size of the inode atguest_memfdcreation time), causing one of the two threads to get-ENOMEM. Suggestions to solve this are appreciated!
4.max_usage_in_bytesstatistic (cgroups v1) forguest_memfdHugeTLB
Quoted 9 lines
pages should be correct but needs testing and could be wrong.
5. memcg charging (charge_memcg()) for cgroups v2 forguest_memfdHugeTLB pages after splitting should be correct but needs testing and could be wrong.
6. Page cache accounting: When a hugetlb page is split,guest_memfdwill incur page count in bothNR_HUGETLB(counted at hugetlb allocation time) andNR_FILE_PAGESstats (counted when split pages are added to the filemap). Is this aligned with what people expect?
For people who might be testing this series with non-Coco VMs (heads up, Patrick and Nikita!), this currently splits the folio as long as some shareability in the huge folio is shared, which is probably unnecessary?
IIUC core-mm doesn't support mapping at 1G but from a cursory reading it seems like the faulting function calling kvm_gmem_fault_shared() could possibly be able to map a 1G page at 4K.
Looks like we might need another flag like GUEST_MEMFD_FLAG_SUPPORT_CONVERSION, which will gate initialization of the shareability maple tree/xarray.
If shareability is NULL for the entire hugepage range, then no splitting will occur.
For Coco VMs, this should be safe, since if this flag is not set, kvm_gmem_fault_shared() will always not be able to fault (the shareability value will be NULL.
Quoted 8 lines
Here are some optimizations that could be explored in future series:
1. Pages could be split from 1G to 2M first and only split to 4K if necessary.
2. Zeroing could be skipped for Coco VMs if hardware already zeroes the pages.<snip>
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Ackerley TngHi Ackerley,
Quoted 4 lines · Ackerley Tng
The two new
guest_memfdioctlsKVM_GMEM_CONVERT_SHAREDandKVM_GMEM_CONVERT_PRIVATEconvert the requested memory ranges to shared and private respectively.
I have a high level question about this particular patch and this approach for conversion: why do we need IOCTLs to manage conversion between private and shared?
In the presentations I gave at LPC [1, 2], and in my latest patch series that performs in-place conversion [3] and the associated (by now outdated) state diagram [4], I didn't see the need to have a userspace-facing interface to manage that. KVM has all the information it needs to handle conversions, which are triggered by the guest. To me this seems like it adds additional complexity, as well as a user facing interface that we would need to maintain.
There are various ways we could handle conversion without explicit interference from userspace. What I had in mind is the following (as an example, details can vary according to VM type). I will use use the case of conversion from shared to private because that is the more complicated (interesting) case:
- Guest issues a hypercall to request that a shared folio become private.
- The hypervisor receives the call, and passes it to KVM.
- KVM unmaps the folio from the guest stage-2 (EPT I think in x86 parlance), and unmaps it from the host. The host however, could still have references (e.g., GUP).
- KVM exits to the host (hypervisor call exit), with the information that the folio has been unshared from it.
- A well behaving host would now get rid of all of its references (e.g., release GUPs), perform a VCPU run, and the guest continues running as normal. I expect this to be the common case.
But to handle the more interesting situation, let's say that the host doesn't do it immediately, and for some reason it holds on to some references to that folio.
- Even if that's the case, the guest can still run *. If the guest tries to access the folio, KVM detects that access when it tries to fault it into the guest, sees that the host still has references to that folio, and exits back to the host with a memory fault exit. At this point, the VCPU that has tried to fault in that particular folio cannot continue running as long as it cannot fault in that folio.
- The host tries a VCPU run again, and the above repeats, i.e., KVM checks the refcount, finds that the host still holds references, doesn't fault the folio into the guest, and exits back to the host.
- Eventually a well-behaving host releases all its references, and the following VCPU run is able to fault the page into the guest, and proceed with running it.
In case the guest is destroyed before that happens, we have the whole folio_put() callback scenario we had discussed earlier.
In other words, the interface that I had in mind where KVM run exists (hyp call, memory fault), as well as VCPU run. Both which already exist, and convey the same information. Is there a case where that isn't enough or suboptimal?
Thanks,
/fuad
(*) An alternative suggestion was to block the VCPU from running altogether, regardless of whether it wants to fault the unshared page immediately, and continually exit to the host until references are dropped and the conversion can happen.
[1] https://lpc.events/event/17/contributions/1487/
[2] https://lpc.events/event/18/contributions/1758/
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lpc.events/event/18/contributions/1758/attachments/1457/3699/Guestmemfd%20folio%20state%20page_type.pdf
Quoted 458 lines
A
guest_memfdioctl is used because shareability is a property of the memory, and this property should be modifiable independently of the attached struct kvm. This allows shareability to be modified even if the memory is not yet bound using memslots.For shared to private conversions, if refcounts on any of the folios within the range are elevated, fail the conversion with
-EAGAIN.At the point of shared to private conversion, all folios in range are also unmapped. The
filemap_invalidate_lock()is held, so no faulting can occur. Hence, from that point on, only transient refcounts can be taken on the folios associated with thatguest_memfd.Hence, it is safe to do the conversion from shared to private.
After conversion is complete, refcounts may become elevated, but that is fine since users of transient refcounts don't actually access memory.
For private to shared conversions, there are no refcount checks. any transient refcounts are expected to drop their refcounts soon. The conversion process will spin waiting for these transient refcounts to go away.
Signed-off-by Ackerley Tng <[email protected]>Change-Id: I3546aaf6c1b795de6dc9ba09e816b64934221918
--- include/uapi/linux/kvm.h | 11 ++ virt/kvm/guest_memfd.c | 357 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 366 insertions(+), 2 deletions(-)include/uapi/linux/kvm.h +11
-0@@ -1577,6 +1577,17 @@ struct kvm_create_guest_memfd {__u64 reserved[6 ]; }; +#define KVM_GMEM_IO 0xAF +#define KVM_GMEM_CONVERT_SHARED _IOWR(KVM_GMEM_IO, 0x41, struct kvm_gmem_convert) +#define KVM_GMEM_CONVERT_PRIVATE _IOWR(KVM_GMEM_IO, 0x42, struct kvm_gmem_convert) + +struct kvm_gmem_convert { +__u64 offset; +__u64 size; +__u64 error_offset; +__u64 reserved[5 ]; +}; +#define KVM_PRE_FAULT_MEMORY _IOWR(KVMIO, 0xd5, struct kvm_pre_fault_memory)struct kvm_pre_fault_memory {virt/kvm/guest_memfd.c +355
-3@@ -30,6 +30,10 @@ enum shareability { };static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index); +static void kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end); +static void kvm_gmem_invalidate_end (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end);static struct kvm_gmem_inode_private *kvm_gmem_private (struct inode *inode) {@@ -85,6 +89,306 @@ static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t inde return kvm_gmem_get_folio(inode, index); } +/** +* kvm_gmem_shareability_store() - Sets shareability to @value for range. +* +* @mt: the shareability maple tree. +* @index: the range begins at this index in the inode. +* @nr_pages: number of PAGE_SIZE pages in this range. +* @value: the shareability value to set for this range. +* +* Unlike mtree_store_range(), this function also merges adjacent ranges that +* have the same values as an optimization. Assumes that all stores to @mt go +* through this function, such that adjacent ranges are always merged. +* +* Return: 0 on success and negative error otherwise. +*/ +static int kvm_gmem_shareability_store (struct maple_tree *mt,pgoff_t index, +size_t nr_pages,enum shareability value) +{ +MA_STATE (mas, mt,0 ,0 ); +unsigned long start; +unsigned long last; +void *entry; +int ret; + + start = index; + last = start + nr_pages -1 ; + +mas_lock (&mas); + +/* Try extending range. entry is NULL on overflow/wrap-around. */ +mas_set_range (&mas, last +1 , last +1 ); + entry =mas_find (&mas, last +1 ); +if (entry &&xa_to_value (entry) == value) + last = mas.last; + +mas_set_range (&mas, start -1 , start -1 ); + entry =mas_find (&mas, start -1 ); +if (entry &&xa_to_value (entry) == value) + start = mas.index; + +mas_set_range (&mas, start, last); + ret =mas_store_gfp (&mas,xa_mk_value (value),GFP_KERNEL ); + +mas_unlock (&mas); + +return ret; +} + +struct conversion_work { +struct list_head list; +pgoff_t start; +size_t nr_pages; +}; + +static int add_to_work_list (struct list_head *list,pgoff_t start,pgoff_t last) +{ +struct conversion_work *work; + + work =kzalloc (sizeof (*work),GFP_KERNEL ); +if (!work) +return -ENOMEM ; + + work->start = start; + work->nr_pages = last +1 - start; + +list_add_tail (&work->list, list); + +return 0 ; +} + +static bool kvm_gmem_has_safe_refcount (struct address_space *mapping,pgoff_t start, +size_t nr_pages,pgoff_t *error_index) +{ +const int filemap_get_folios_refcount =1 ; +struct folio_batch fbatch; +bool refcount_safe; +pgoff_t last; +int i; + + last = start + nr_pages -1 ; + refcount_safe = true; + +folio_batch_init (&fbatch); +while (refcount_safe && +filemap_get_folios (mapping, &start, last, &fbatch)) { + +for (i =0 ; i <folio_batch_count (&fbatch); ++i) { +int filemap_refcount; +int safe_refcount; +struct folio *f; + + f = fbatch.folios[i]; + filemap_refcount =folio_nr_pages (f); + + safe_refcount = filemap_refcount + filemap_get_folios_refcount; +if (folio_ref_count (f) != safe_refcount) { + refcount_safe = false; + *error_index = f->index; +break ; + } + } + +folio_batch_release (&fbatch); + } + +return refcount_safe; +} + +static int kvm_gmem_shareability_apply (struct inode *inode, +struct conversion_work *work, +enum shareability m) +{ +struct maple_tree *mt; + + mt = &kvm_gmem_private (inode)->shareability; +return kvm_gmem_shareability_store (mt, work->start, work->nr_pages, m); +} + +static int kvm_gmem_convert_compute_work (struct inode *inode,pgoff_t start, +size_t nr_pages,enum shareability m, +struct list_head *work_list) +{ +struct maple_tree *mt; +struct ma_state mas; +pgoff_t last; +void *entry; +int ret; + + last = start + nr_pages -1 ; + + mt = &kvm_gmem_private (inode)->shareability; + ret =0 ; + +mas_init (&mas, mt, start); + +rcu_read_lock (); +mas_for_each (&mas, entry, last) { +enum shareability current_m; +pgoff_t m_range_index; +pgoff_t m_range_last; +int ret; + + m_range_index =max (mas.index, start); + m_range_last =min (mas.last, last); + + current_m =xa_to_value (entry); +if (m == current_m) +continue ; + +mas_pause (&mas); +rcu_read_unlock (); +/* Caller will clean this up on error. */ + ret =add_to_work_list (work_list, m_range_index, m_range_last); +rcu_read_lock (); +if (ret) +break ; + } +rcu_read_unlock (); + +return ret; +} + +static void kvm_gmem_convert_invalidate_begin (struct inode *inode, +struct conversion_work *work) +{ +struct list_head *gmem_list; +struct kvm_gmem *gmem; +pgoff_t end; + + end = work->start + work->nr_pages; + + gmem_list = &inode->i_mapping->i_private_list; +list_for_each_entry (gmem, gmem_list, entry) +kvm_gmem_invalidate_begin (gmem, work->start, end); +} + +static void kvm_gmem_convert_invalidate_end (struct inode *inode, +struct conversion_work *work) +{ +struct list_head *gmem_list; +struct kvm_gmem *gmem; +pgoff_t end; + + end = work->start + work->nr_pages; + + gmem_list = &inode->i_mapping->i_private_list; +list_for_each_entry (gmem, gmem_list, entry) +kvm_gmem_invalidate_end (gmem, work->start, end); +} + +static int kvm_gmem_convert_should_proceed (struct inode *inode, +struct conversion_work *work, +bool to_shared,pgoff_t *error_index) +{ +if (!to_shared) { +unmap_mapping_pages (inode->i_mapping, work->start, + work->nr_pages, false); + +if (!kvm_gmem_has_safe_refcount (inode->i_mapping, work->start, + work->nr_pages, error_index)) { +return -EAGAIN ; + } + } + +return 0 ; +} + +static int kvm_gmem_convert_range (struct file *file,pgoff_t start, +size_t nr_pages,bool shared, +pgoff_t *error_index) +{ +struct conversion_work *work, *tmp, *rollback_stop_item; +LIST_HEAD (work_list); +struct inode *inode; +enum shareability m; +int ret; + + inode =file_inode (file); + +filemap_invalidate_lock (inode->i_mapping); + + m = shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ; + ret =kvm_gmem_convert_compute_work (inode, start, nr_pages, m, &work_list); +if (ret ||list_empty (&work_list)) + goto out; + +list_for_each_entry (work, &work_list, list) +kvm_gmem_convert_invalidate_begin (inode, work); + +list_for_each_entry (work, &work_list, list) { + ret =kvm_gmem_convert_should_proceed (inode, work, shared, + error_index); +if (ret) + goto invalidate_end; + } + +list_for_each_entry (work, &work_list, list) { + rollback_stop_item = work; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +break ; + } + +if (ret) { + m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ; +list_for_each_entry (work, &work_list, list) { +if (work == rollback_stop_item) +break ; + +WARN_ON (kvm_gmem_shareability_apply (inode, work, m)); + } + } + +invalidate_end: +list_for_each_entry (work, &work_list, list) +kvm_gmem_convert_invalidate_end (inode, work); +out: +filemap_invalidate_unlock (inode->i_mapping); + +list_for_each_entry_safe (work, tmp, &work_list, list) { +list_del (&work->list); +kfree (work); + } + +return ret; +} + +static int kvm_gmem_ioctl_convert_range (struct file *file, +struct kvm_gmem_convert *param, +bool shared) +{ +pgoff_t error_index; +size_t nr_pages; +pgoff_t start; +int ret; + +if (param->error_offset) +return -EINVAL ; + +if (param->size ==0 ) +return 0 ; + +if (param->offset + param->size < param->offset || + param->offset >file_inode (file)->i_size || + param->offset + param->size >file_inode (file)->i_size) +return -EINVAL ; + +if (!IS_ALIGNED (param->offset,PAGE_SIZE ) || + !IS_ALIGNED (param->size,PAGE_SIZE )) +return -EINVAL ; + + start = param->offset >>PAGE_SHIFT ; + nr_pages = param->size >>PAGE_SHIFT ; + + ret =kvm_gmem_convert_range (file, start, nr_pages, shared, &error_index); +if (ret) + param->error_offset = error_index <<PAGE_SHIFT ; + +return ret; +} +#else static int kvm_gmem_shareability_setup (struct maple_tree *mt,loff_t size,u64 flags)@@ -186,15 +490,26 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,unsigned long index;xa_for_each_range (&gmem->bindings, index, slot, start, end -1 ) { +enum kvm_gfn_range_filter filter;pgoff_t pgoff = slot->gmem.pgoff; + filter =KVM_FILTER_PRIVATE ; +if (kvm_gmem_memslot_supports_shared (slot)) { +/* +* Unmapping would also cause invalidation, but cannot +* rely on mmu_notifiers to do invalidation via +* unmapping, since memory may not be mapped to +* userspace. +*/ + filter |=KVM_FILTER_SHARED ; + } +struct kvm_gfn_range gfn_range = { .start = slot->base_gfn +max (pgoff, start) - pgoff, .end = slot->base_gfn +min (pgoff + slot->npages, end) - pgoff, .slot = slot, .may_block = true, -/* guest memfd is relevant to only private mappings. */ - .attr_filter =KVM_FILTER_PRIVATE , + .attr_filter = filter, };if (!found_memslot) {@@ -484,11 +799,49 @@ EXPORT_SYMBOL_GPL(kvm_gmem_memslot_supports_shared);#define kvm_gmem_mmap NULL#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ +static long kvm_gmem_ioctl (struct file *file,unsigned int ioctl, +unsigned long arg) +{ +void __user *argp; +int r; + + argp = (void __user *)arg; + +switch (ioctl) { +#ifdef CONFIG_KVM_GMEM_SHARED_MEM +case KVM_GMEM_CONVERT_SHARED : +case KVM_GMEM_CONVERT_PRIVATE : { +struct kvm_gmem_convert param; +bool to_shared; + + r = -EFAULT ; +if (copy_from_user (¶m, argp,sizeof (param))) + goto out; + + to_shared = ioctl ==KVM_GMEM_CONVERT_SHARED ; + r =kvm_gmem_ioctl_convert_range (file, ¶m, to_shared); +if (r) { +if (copy_to_user (argp, ¶m,sizeof (param))) { + r = -EFAULT ; + goto out; + } + } +break ; + } +#endif +default : + r = -ENOTTY ; + } +out: +return r; +} +static struct file_operations kvm_gmem_fops = { .mmap = kvm_gmem_mmap, .open = generic_file_open, .release = kvm_gmem_release, .fallocate = kvm_gmem_fallocate, + .unlocked_ioctl = kvm_gmem_ioctl, };static void kvm_gmem_free_inode (struct inode *inode) --2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 46 lines · Fuad Tabba
Hi Ackerley,
Quoted 4 lines · Ackerley Tng
The two new
guest_memfdioctlsKVM_GMEM_CONVERT_SHAREDandKVM_GMEM_CONVERT_PRIVATEconvert the requested memory ranges to shared and private respectively.I have a high level question about this particular patch and this approach for conversion: why do we need IOCTLs to manage conversion between private and shared?
In the presentations I gave at LPC [1, 2], and in my latest patch series that performs in-place conversion [3] and the associated (by now outdated) state diagram [4], I didn't see the need to have a userspace-facing interface to manage that. KVM has all the information it needs to handle conversions, which are triggered by the guest. To me this seems like it adds additional complexity, as well as a user facing interface that we would need to maintain.
There are various ways we could handle conversion without explicit interference from userspace. What I had in mind is the following (as an example, details can vary according to VM type). I will use use the case of conversion from shared to private because that is the more complicated (interesting) case:
- Guest issues a hypercall to request that a shared folio become private.
- The hypervisor receives the call, and passes it to KVM.
- KVM unmaps the folio from the guest stage-2 (EPT I think in x86 parlance), and unmaps it from the host. The host however, could still have references (e.g., GUP).
- KVM exits to the host (hypervisor call exit), with the information that the folio has been unshared from it.
- A well behaving host would now get rid of all of its references (e.g., release GUPs), perform a VCPU run, and the guest continues running as normal. I expect this to be the common case.
But to handle the more interesting situation, let's say that the host doesn't do it immediately, and for some reason it holds on to some references to that folio.
Quoted 6 lines
- Even if that's the case, the guest can still run *. If the guest tries to access the folio, KVM detects that access when it tries to fault it into the guest, sees that the host still has references to that folio, and exits back to the host with a memory fault exit. At this point, the VCPU that has tried to fault in that particular folio cannot continue running as long as it cannot fault in that folio.
Are you talking about the following scheme?
1) guest_memfd checks shareability on each get pfn and if there is a mismatch exit to the host.
2) host user space has to guess whether it's a pending refcount or whether it's an actual mismatch.
3) guest_memfd will maintain a third state "pending_private_conversion" or equivalent which will transition to private upon the last refcount drop of each page.
If conversion is triggered by userspace (in case of pKVM, it will be triggered from within the KVM (?)):
* Conversion will just fail if there are extra refcounts and userspace can try to get rid of extra refcounts on the range while it has enough context without hitting any ambiguity with memory fault exit.
* guest_memfd will not have to deal with this extra state from 3 above and overall guest_memfd conversion handling becomes relatively simpler.
Note that for x86 CoCo cases, memory conversion is already triggered by userspace using KVM ioctl, this series is proposing to use guest_memfd ioctl to do the same.
- Allows not having to keep track of separate shared/private range
information in KVM.
- Simpler handling of the conversion process done per guest_memfd
rather than for full range.
- Userspace can handle the rollback as needed, simplifying error
handling in guest_memfd.
- guest_memfd is single source of truth and notifies the users of
shareability change.
- e.g. IOMMU, userspace, KVM MMU all can be registered for
getting notifications from guest_memfd directly and will get notified for invalidation upon shareability attribute updates.
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Hi Vishal,
Quoted 55 lines · Vishal Annapurve
Quoted 46 lines · Fuad Tabba
Hi Ackerley,
Quoted 4 lines · Ackerley Tng
The two new
guest_memfdioctlsKVM_GMEM_CONVERT_SHAREDandKVM_GMEM_CONVERT_PRIVATEconvert the requested memory ranges to shared and private respectively.I have a high level question about this particular patch and this approach for conversion: why do we need IOCTLs to manage conversion between private and shared?
In the presentations I gave at LPC [1, 2], and in my latest patch series that performs in-place conversion [3] and the associated (by now outdated) state diagram [4], I didn't see the need to have a userspace-facing interface to manage that. KVM has all the information it needs to handle conversions, which are triggered by the guest. To me this seems like it adds additional complexity, as well as a user facing interface that we would need to maintain.
There are various ways we could handle conversion without explicit interference from userspace. What I had in mind is the following (as an example, details can vary according to VM type). I will use use the case of conversion from shared to private because that is the more complicated (interesting) case:
- Guest issues a hypercall to request that a shared folio become private.
- The hypervisor receives the call, and passes it to KVM.
- KVM unmaps the folio from the guest stage-2 (EPT I think in x86 parlance), and unmaps it from the host. The host however, could still have references (e.g., GUP).
- KVM exits to the host (hypervisor call exit), with the information that the folio has been unshared from it.
- A well behaving host would now get rid of all of its references (e.g., release GUPs), perform a VCPU run, and the guest continues running as normal. I expect this to be the common case.
But to handle the more interesting situation, let's say that the host doesn't do it immediately, and for some reason it holds on to some references to that folio.
Quoted 6 lines
- Even if that's the case, the guest can still run *. If the guest tries to access the folio, KVM detects that access when it tries to fault it into the guest, sees that the host still has references to that folio, and exits back to the host with a memory fault exit. At this point, the VCPU that has tried to fault in that particular folio cannot continue running as long as it cannot fault in that folio.
Quoted 3 lines
Are you talking about the following scheme?
1)guest_memfdchecks shareability on each get pfn and if there is a mismatch exit to the host.
I think we are not really on the same page here (no pun intended :) ). I'll try to answer your questions anyway...
Which get_pfn? Are you referring to get_pfn when faulting the page into the guest or into the host?
Quoted 2 lines
2) host user space has to guess whether it's a pending refcount or whether it's an actual mismatch.
No need to guess. VCPU run will let it know exactly why it's exiting.
Quoted 6 lines
3)
guest_memfdwill maintain a third state "pending_private_conversion" or equivalent which will transition to private upon the last refcount drop of each page.If conversion is triggered by userspace (in case of pKVM, it will be triggered from within the KVM (?)):
Why would conversion be triggered by userspace? As far as I know, it's the guest that triggers the conversion.
Quoted 6 lines
* Conversion will just fail if there are extra refcounts and userspace can try to get rid of extra refcounts on the range while it has enough context without hitting any ambiguity with memory fault exit.
*guest_memfdwill not have to deal with this extra state from 3 above and overallguest_memfdconversion handling becomes relatively simpler.
That's not really related. The extra state isn't necessary any more once we agreed in the previous discussion that we will retry instead.
Quoted 3 lines
Note that for x86 CoCo cases, memory conversion is already triggered by userspace using KVM ioctl, this series is proposing to use
guest_memfdioctl to do the same.
The reason why for x86 CoCo cases conversion is already triggered by userspace using KVM ioctl is that it has to, since shared memory and private memory are two separate pages, and userspace needs to manage that. Sharing memory in place removes the need for that.
This series isn't using the same ioctl, it's introducing new ones to perform a task that as far as I can tell so far, KVM can handle by itself.
Quoted 2 lines
- Allows not having to keep track of separate shared/private range
information in KVM.
This patch series is already tracking shared/private range information in KVM.
Quoted 9 lines
- Simpler handling of the conversion process done per
guest_memfd
rather than for full range.
- Userspace can handle the rollback as needed, simplifying error
handling inguest_memfd.
-guest_memfdis single source of truth and notifies the users of
shareability change.
- e.g. IOMMU, userspace, KVM MMU all can be registered for
getting notifications fromguest_memfddirectly and will get notified for invalidation upon shareability attribute updates.
All of these can still be done without introducing a new ioctl.
Cheers,
/fuad
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 63 lines · Fuad Tabba
Hi Vishal,
Quoted 55 lines · Vishal Annapurve
Quoted 46 lines · Fuad Tabba
Hi Ackerley,
Quoted 4 lines · Ackerley Tng
The two new
guest_memfdioctlsKVM_GMEM_CONVERT_SHAREDandKVM_GMEM_CONVERT_PRIVATEconvert the requested memory ranges to shared and private respectively.I have a high level question about this particular patch and this approach for conversion: why do we need IOCTLs to manage conversion between private and shared?
In the presentations I gave at LPC [1, 2], and in my latest patch series that performs in-place conversion [3] and the associated (by now outdated) state diagram [4], I didn't see the need to have a userspace-facing interface to manage that. KVM has all the information it needs to handle conversions, which are triggered by the guest. To me this seems like it adds additional complexity, as well as a user facing interface that we would need to maintain.
There are various ways we could handle conversion without explicit interference from userspace. What I had in mind is the following (as an example, details can vary according to VM type). I will use use the case of conversion from shared to private because that is the more complicated (interesting) case:
- Guest issues a hypercall to request that a shared folio become private.
- The hypervisor receives the call, and passes it to KVM.
- KVM unmaps the folio from the guest stage-2 (EPT I think in x86 parlance), and unmaps it from the host. The host however, could still have references (e.g., GUP).
- KVM exits to the host (hypervisor call exit), with the information that the folio has been unshared from it.
- A well behaving host would now get rid of all of its references (e.g., release GUPs), perform a VCPU run, and the guest continues running as normal. I expect this to be the common case.
But to handle the more interesting situation, let's say that the host doesn't do it immediately, and for some reason it holds on to some references to that folio.
Quoted 6 lines
- Even if that's the case, the guest can still run *. If the guest tries to access the folio, KVM detects that access when it tries to fault it into the guest, sees that the host still has references to that folio, and exits back to the host with a memory fault exit. At this point, the VCPU that has tried to fault in that particular folio cannot continue running as long as it cannot fault in that folio.
Quoted 3 lines
Are you talking about the following scheme?
1)guest_memfdchecks shareability on each get pfn and if there is a mismatch exit to the host.
Quoted 5 lines
I think we are not really on the same page here (no pun intended :) ). I'll try to answer your questions anyway...
Which
get_pfn? Are you referring toget_pfnwhen faulting the page into the guest or into the host?
I am referring to guest fault handling in KVM.
Quoted 23 lines
Quoted 3 lines
2) host user space has to guess whether it's a pending refcount or whether it's an actual mismatch.
No need to guess. VCPU run will let it know exactly why it's exiting.
Quoted 6 lines
3)
guest_memfdwill maintain a third state "pending_private_conversion" or equivalent which will transition to private upon the last refcount drop of each page.If conversion is triggered by userspace (in case of pKVM, it will be triggered from within the KVM (?)):
Why would conversion be triggered by userspace? As far as I know, it's the guest that triggers the conversion.
Quoted 6 lines
* Conversion will just fail if there are extra refcounts and userspace can try to get rid of extra refcounts on the range while it has enough context without hitting any ambiguity with memory fault exit.
*guest_memfdwill not have to deal with this extra state from 3 above and overallguest_memfdconversion handling becomes relatively simpler.
Quoted 2 lines
That's not really related. The extra state isn't necessary any more once we agreed in the previous discussion that we will retry instead.
Who is *we* here? Which entity will retry conversion?
Quoted 9 lines
Quoted 4 lines
Note that for x86 CoCo cases, memory conversion is already triggered by userspace using KVM ioctl, this series is proposing to use
guest_memfdioctl to do the same.The reason why for x86 CoCo cases conversion is already triggered by userspace using KVM ioctl is that it has to, since shared memory and private memory are two separate pages, and userspace needs to manage that. Sharing memory in place removes the need for that.
Userspace still needs to clean up memory usage before conversion is successful. e.g. remove IOMMU mappings for shared to private conversion. I would think that memory conversion should not succeed before all existing users let go of the guest_memfd pages for the range being converted.
In x86 CoCo usecases, userspace can also decide to not allow conversion for scenarios where ranges are still under active use by the host and guest is erroneously trying to take away memory. Both SNP/TDX spec allow failure of conversion due to in use memory.
Quoted 4 lines
This series isn't using the same ioctl, it's introducing new ones to perform a task that as far as I can tell so far, KVM can handle by itself.
I would like to understand this better. How will KVM handle the conversion process for guest_memfd pages? Can you help walk an example sequence for shared to private conversion specifically around guest_memfd offset states?
Quoted 20 lines
Quoted 3 lines
- Allows not having to keep track of separate shared/private range
information in KVM.This patch series is already tracking shared/private range information in KVM.
Quoted 9 lines
- Simpler handling of the conversion process done per
guest_memfd
rather than for full range.
- Userspace can handle the rollback as needed, simplifying error
handling inguest_memfd.
-guest_memfdis single source of truth and notifies the users of
shareability change.
- e.g. IOMMU, userspace, KVM MMU all can be registered for
getting notifications fromguest_memfddirectly and will get notified for invalidation upon shareability attribute updates.All of these can still be done without introducing a new ioctl.
Cheers,
/fuad
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Hi Vishal,
Quoted 96 lines · Vishal Annapurve
Quoted 63 lines · Fuad Tabba
Hi Vishal,
Quoted 55 lines · Vishal Annapurve
Quoted 46 lines · Fuad Tabba
Hi Ackerley,
Quoted 4 lines · Ackerley Tng
The two new
guest_memfdioctlsKVM_GMEM_CONVERT_SHAREDandKVM_GMEM_CONVERT_PRIVATEconvert the requested memory ranges to shared and private respectively.I have a high level question about this particular patch and this approach for conversion: why do we need IOCTLs to manage conversion between private and shared?
In the presentations I gave at LPC [1, 2], and in my latest patch series that performs in-place conversion [3] and the associated (by now outdated) state diagram [4], I didn't see the need to have a userspace-facing interface to manage that. KVM has all the information it needs to handle conversions, which are triggered by the guest. To me this seems like it adds additional complexity, as well as a user facing interface that we would need to maintain.
There are various ways we could handle conversion without explicit interference from userspace. What I had in mind is the following (as an example, details can vary according to VM type). I will use use the case of conversion from shared to private because that is the more complicated (interesting) case:
- Guest issues a hypercall to request that a shared folio become private.
- The hypervisor receives the call, and passes it to KVM.
- KVM unmaps the folio from the guest stage-2 (EPT I think in x86 parlance), and unmaps it from the host. The host however, could still have references (e.g., GUP).
- KVM exits to the host (hypervisor call exit), with the information that the folio has been unshared from it.
- A well behaving host would now get rid of all of its references (e.g., release GUPs), perform a VCPU run, and the guest continues running as normal. I expect this to be the common case.
But to handle the more interesting situation, let's say that the host doesn't do it immediately, and for some reason it holds on to some references to that folio.
Quoted 6 lines
- Even if that's the case, the guest can still run *. If the guest tries to access the folio, KVM detects that access when it tries to fault it into the guest, sees that the host still has references to that folio, and exits back to the host with a memory fault exit. At this point, the VCPU that has tried to fault in that particular folio cannot continue running as long as it cannot fault in that folio.
Quoted 3 lines
Are you talking about the following scheme?
1)guest_memfdchecks shareability on each get pfn and if there is a mismatch exit to the host.Quoted 5 lines
I think we are not really on the same page here (no pun intended :) ). I'll try to answer your questions anyway...
Which
get_pfn? Are you referring toget_pfnwhen faulting the page into the guest or into the host?I am referring to guest fault handling in KVM.
Quoted 23 lines
Quoted 3 lines
2) host user space has to guess whether it's a pending refcount or whether it's an actual mismatch.
No need to guess. VCPU run will let it know exactly why it's exiting.
Quoted 6 lines
3)
guest_memfdwill maintain a third state "pending_private_conversion" or equivalent which will transition to private upon the last refcount drop of each page.If conversion is triggered by userspace (in case of pKVM, it will be triggered from within the KVM (?)):
Why would conversion be triggered by userspace? As far as I know, it's the guest that triggers the conversion.
Quoted 6 lines
* Conversion will just fail if there are extra refcounts and userspace can try to get rid of extra refcounts on the range while it has enough context without hitting any ambiguity with memory fault exit.
*guest_memfdwill not have to deal with this extra state from 3 above and overallguest_memfdconversion handling becomes relatively simpler.
Quoted 4 lines
Quoted 2 lines
That's not really related. The extra state isn't necessary any more once we agreed in the previous discussion that we will retry instead.
Who is *we* here? Which entity will retry conversion?
Userspace will re-attempt the VCPU run.
Quoted 10 lines
Quoted 9 lines
Quoted 4 lines
Note that for x86 CoCo cases, memory conversion is already triggered by userspace using KVM ioctl, this series is proposing to use
guest_memfdioctl to do the same.The reason why for x86 CoCo cases conversion is already triggered by userspace using KVM ioctl is that it has to, since shared memory and private memory are two separate pages, and userspace needs to manage that. Sharing memory in place removes the need for that.
Quoted 5 lines
Userspace still needs to clean up memory usage before conversion is successful. e.g. remove IOMMU mappings for shared to private conversion. I would think that memory conversion should not succeed before all existing users let go of the
guest_memfdpages for the range being converted.
Yes. Userspace will know that it needs to do that on the VCPU exit, which informs it of the guest's hypervisor request to unshare (convert from shared to private) the page.
Quoted 4 lines
In x86 CoCo usecases, userspace can also decide to not allow conversion for scenarios where ranges are still under active use by the host and guest is erroneously trying to take away memory. Both SNP/TDX spec allow failure of conversion due to in use memory.
How can the guest erroneously try to take away memory? If the guest sends a hypervisor request asking for a conversion of memory that doesn't belong to it, then I would expect the hypervisor to prevent that.
I don't see how having an IOCTL to trigger the conversion is needed to allow conversion failure. How is that different from userspace ignoring or delaying releasing all references it has for the conversion request?
Quoted 9 lines
Quoted 4 lines
This series isn't using the same ioctl, it's introducing new ones to perform a task that as far as I can tell so far, KVM can handle by itself.
I would like to understand this better. How will KVM handle the conversion process for
guest_memfdpages? Can you help walk an example sequence for shared to private conversion specifically aroundguest_memfdoffset states?
To make sure that we are discussing the same scenario: can you do the same as well please --- walk me through an example sequence for shared to private conversion specifically around guest_memfd offset states With the IOCTLs involved?
Here is an example that I have implemented and tested with pKVM. Note that there are alternatives, the flow below is architecture or even vm-type dependent. None of this code is code KVM code and the behaviour could vary.
Assuming the folio is shared with the host:
Guest sends unshare hypercall to the hypervisor
Hypervisor forwards request to KVM (gmem) (having done due diligence) KVM (gmem) performs an unmap_folio(), exits to userspace with KVM_EXIT_UNSHARE and all the information about the folio being unshared
Case 1:
Userspace removes any remaining references (GUPs, IOMMU Mappings etc...) Userspace calls vcpu_run(): KVM (gmem) sees that there aren't any references, sets state to PRIVATE
Case 2 (alternative 1):
Userspace doesn't release its references
Userspace calls vcpu_run(): KVM (gmem) sees that there are still references, exits back to userspace with KVM_EXIT_UNSHARE
Case 2 (alternative 2):
Userspace doesn't release its references
Userspace calls vcpu_run(): KVM (gmem) sees that there are still references, unmaps folio from guest, but allows it to run (until it tries to fault in the folio)
Guest tries to fault in folio that still has reference, KVM does not allow that (it sees that the folio is shared, and it doesn't fault in shared folios to confidential guests)
KVM exits back to userspace with KVM_EXIT_UNSHARE
As I mentioned, the alternatives above are _not_ set in core KVM code. They can vary by architecture of VM type, depending on the policy, support, etc..
Now for your example please on how this would work with IOCTLs :)
Thanks,
/fuad
Quoted 20 lines
Quoted 20 lines
Quoted 3 lines
- Allows not having to keep track of separate shared/private range
information in KVM.This patch series is already tracking shared/private range information in KVM.
Quoted 9 lines
- Simpler handling of the conversion process done per
guest_memfd
rather than for full range.
- Userspace can handle the rollback as needed, simplifying error
handling inguest_memfd.
-guest_memfdis single source of truth and notifies the users of
shareability change.
- e.g. IOMMU, userspace, KVM MMU all can be registered for
getting notifications fromguest_memfddirectly and will get notified for invalidation upon shareability attribute updates.All of these can still be done without introducing a new ioctl.
Cheers,
/fuad
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 100 lines · Fuad Tabba
Hi Vishal,
Quoted 96 lines · Vishal Annapurve
Quoted 63 lines · Fuad Tabba
Hi Vishal,
Quoted 55 lines · Vishal Annapurve
Quoted 46 lines · Fuad Tabba
Hi Ackerley,
Quoted 4 lines · Ackerley Tng
The two new
guest_memfdioctlsKVM_GMEM_CONVERT_SHAREDandKVM_GMEM_CONVERT_PRIVATEconvert the requested memory ranges to shared and private respectively.I have a high level question about this particular patch and this approach for conversion: why do we need IOCTLs to manage conversion between private and shared?
In the presentations I gave at LPC [1, 2], and in my latest patch series that performs in-place conversion [3] and the associated (by now outdated) state diagram [4], I didn't see the need to have a userspace-facing interface to manage that. KVM has all the information it needs to handle conversions, which are triggered by the guest. To me this seems like it adds additional complexity, as well as a user facing interface that we would need to maintain.
There are various ways we could handle conversion without explicit interference from userspace. What I had in mind is the following (as an example, details can vary according to VM type). I will use use the case of conversion from shared to private because that is the more complicated (interesting) case:
- Guest issues a hypercall to request that a shared folio become private.
- The hypervisor receives the call, and passes it to KVM.
- KVM unmaps the folio from the guest stage-2 (EPT I think in x86 parlance), and unmaps it from the host. The host however, could still have references (e.g., GUP).
- KVM exits to the host (hypervisor call exit), with the information that the folio has been unshared from it.
- A well behaving host would now get rid of all of its references (e.g., release GUPs), perform a VCPU run, and the guest continues running as normal. I expect this to be the common case.
But to handle the more interesting situation, let's say that the host doesn't do it immediately, and for some reason it holds on to some references to that folio.
Quoted 6 lines
- Even if that's the case, the guest can still run *. If the guest tries to access the folio, KVM detects that access when it tries to fault it into the guest, sees that the host still has references to that folio, and exits back to the host with a memory fault exit. At this point, the VCPU that has tried to fault in that particular folio cannot continue running as long as it cannot fault in that folio.
Quoted 3 lines
Are you talking about the following scheme?
1)guest_memfdchecks shareability on each get pfn and if there is a mismatch exit to the host.Quoted 5 lines
I think we are not really on the same page here (no pun intended :) ). I'll try to answer your questions anyway...
Which
get_pfn? Are you referring toget_pfnwhen faulting the page into the guest or into the host?I am referring to guest fault handling in KVM.
Quoted 23 lines
Quoted 3 lines
2) host user space has to guess whether it's a pending refcount or whether it's an actual mismatch.
No need to guess. VCPU run will let it know exactly why it's exiting.
Quoted 6 lines
3)
guest_memfdwill maintain a third state "pending_private_conversion" or equivalent which will transition to private upon the last refcount drop of each page.If conversion is triggered by userspace (in case of pKVM, it will be triggered from within the KVM (?)):
Why would conversion be triggered by userspace? As far as I know, it's the guest that triggers the conversion.
Quoted 6 lines
* Conversion will just fail if there are extra refcounts and userspace can try to get rid of extra refcounts on the range while it has enough context without hitting any ambiguity with memory fault exit.
*guest_memfdwill not have to deal with this extra state from 3 above and overallguest_memfdconversion handling becomes relatively simpler.
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines
That's not really related. The extra state isn't necessary any more once we agreed in the previous discussion that we will retry instead.
Who is *we* here? Which entity will retry conversion?
Userspace will re-attempt the VCPU run.
Then KVM will have to keep track of the ranges that need conversion across exits. I think it's cleaner to let userspace make the decision and invoke conversion without carrying additional state in KVM about guest request.
Quoted 26 lines
Quoted 11 lines
Quoted 10 lines
Quoted 5 lines
Note that for x86 CoCo cases, memory conversion is already triggered by userspace using KVM ioctl, this series is proposing to use
guest_memfdioctl to do the same.The reason why for x86 CoCo cases conversion is already triggered by userspace using KVM ioctl is that it has to, since shared memory and private memory are two separate pages, and userspace needs to manage that. Sharing memory in place removes the need for that.
Quoted 5 lines
Userspace still needs to clean up memory usage before conversion is successful. e.g. remove IOMMU mappings for shared to private conversion. I would think that memory conversion should not succeed before all existing users let go of the
guest_memfdpages for the range being converted.Yes. Userspace will know that it needs to do that on the VCPU exit, which informs it of the guest's hypervisor request to unshare (convert from shared to private) the page.
Quoted 4 lines
In x86 CoCo usecases, userspace can also decide to not allow conversion for scenarios where ranges are still under active use by the host and guest is erroneously trying to take away memory. Both SNP/TDX spec allow failure of conversion due to in use memory.
Quoted 4 lines
How can the guest erroneously try to take away memory? If the guest sends a hypervisor request asking for a conversion of memory that doesn't belong to it, then I would expect the hypervisor to prevent that.
Making a range as private is effectively disallowing host from accessing those ranges -> so taking away memory.
Quoted 27 lines
I don't see how having an IOCTL to trigger the conversion is needed to allow conversion failure. How is that different from userspace ignoring or delaying releasing all references it has for the conversion request?
Quoted 9 lines
Quoted 4 lines
This series isn't using the same ioctl, it's introducing new ones to perform a task that as far as I can tell so far, KVM can handle by itself.
I would like to understand this better. How will KVM handle the conversion process for
guest_memfdpages? Can you help walk an example sequence for shared to private conversion specifically aroundguest_memfdoffset states?To make sure that we are discussing the same scenario: can you do the same as well please --- walk me through an example sequence for shared to private conversion specifically around
guest_memfdoffset states With the IOCTLs involved?Here is an example that I have implemented and tested with pKVM. Note that there are alternatives, the flow below is architecture or even vm-type dependent. None of this code is code KVM code and the behaviour could vary.
Quoted 5 lines
Assuming the folio is shared with the host:
Guest sends unshare hypercall to the hypervisor
Hypervisor forwards request to KVM (gmem) (having done due diligence) KVM (gmem) performs anunmap_folio(), exits to userspace with
For x86 CoCo VM usecases I was talking about, userspace would like to avoid unmap_mapping_range() on the range before it's safe to unshare the range.
Quoted 52 lines
KVM_EXIT_UNSHAREand all the information about the folio being unsharedCase 1:
Userspace removes any remaining references (GUPs, IOMMU Mappings etc...) Userspace callsvcpu_run(): KVM (gmem) sees that there aren't any references, sets state to PRIVATECase 2 (alternative 1):
Userspace doesn't release its references
Userspace callsvcpu_run(): KVM (gmem) sees that there are still references, exits back to userspace withKVM_EXIT_UNSHARECase 2 (alternative 2):
Userspace doesn't release its references
Userspace callsvcpu_run(): KVM (gmem) sees that there are still references, unmaps folio from guest, but allows it to run (until it tries to fault in the folio)
Guest tries to fault in folio that still has reference, KVM does not allow that (it sees that the folio is shared, and it doesn't fault in shared folios to confidential guests)
KVM exits back to userspace withKVM_EXIT_UNSHAREAs I mentioned, the alternatives above are _not_ set in core KVM code. They can vary by architecture of VM type, depending on the policy, support, etc..
Now for your example please on how this would work with IOCTLs :)
Thanks,
/fuadQuoted 20 lines
Quoted 20 lines
Quoted 3 lines
- Allows not having to keep track of separate shared/private range
information in KVM.This patch series is already tracking shared/private range information in KVM.
Quoted 9 lines
- Simpler handling of the conversion process done per
guest_memfd
rather than for full range.
- Userspace can handle the rollback as needed, simplifying error
handling inguest_memfd.
-guest_memfdis single source of truth and notifies the users of
shareability change.
- e.g. IOMMU, userspace, KVM MMU all can be registered for
getting notifications fromguest_memfddirectly and will get notified for invalidation upon shareability attribute updates.All of these can still be done without introducing a new ioctl.
Cheers,
/fuad
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Hi Vishal,
Quoted 105 lines · Vishal Annapurve
Quoted 103 lines · Fuad Tabba
Hi Vishal,
Quoted 99 lines · Vishal Annapurve
Quoted 63 lines · Fuad Tabba
Hi Vishal,
Quoted 55 lines · Vishal Annapurve
Quoted 46 lines · Fuad Tabba
Hi Ackerley,
Quoted 4 lines · Ackerley Tng
The two new
guest_memfdioctlsKVM_GMEM_CONVERT_SHAREDandKVM_GMEM_CONVERT_PRIVATEconvert the requested memory ranges to shared and private respectively.I have a high level question about this particular patch and this approach for conversion: why do we need IOCTLs to manage conversion between private and shared?
In the presentations I gave at LPC [1, 2], and in my latest patch series that performs in-place conversion [3] and the associated (by now outdated) state diagram [4], I didn't see the need to have a userspace-facing interface to manage that. KVM has all the information it needs to handle conversions, which are triggered by the guest. To me this seems like it adds additional complexity, as well as a user facing interface that we would need to maintain.
There are various ways we could handle conversion without explicit interference from userspace. What I had in mind is the following (as an example, details can vary according to VM type). I will use use the case of conversion from shared to private because that is the more complicated (interesting) case:
- Guest issues a hypercall to request that a shared folio become private.
- The hypervisor receives the call, and passes it to KVM.
- KVM unmaps the folio from the guest stage-2 (EPT I think in x86 parlance), and unmaps it from the host. The host however, could still have references (e.g., GUP).
- KVM exits to the host (hypervisor call exit), with the information that the folio has been unshared from it.
- A well behaving host would now get rid of all of its references (e.g., release GUPs), perform a VCPU run, and the guest continues running as normal. I expect this to be the common case.
But to handle the more interesting situation, let's say that the host doesn't do it immediately, and for some reason it holds on to some references to that folio.
Quoted 6 lines
- Even if that's the case, the guest can still run *. If the guest tries to access the folio, KVM detects that access when it tries to fault it into the guest, sees that the host still has references to that folio, and exits back to the host with a memory fault exit. At this point, the VCPU that has tried to fault in that particular folio cannot continue running as long as it cannot fault in that folio.
Quoted 3 lines
Are you talking about the following scheme?
1)guest_memfdchecks shareability on each get pfn and if there is a mismatch exit to the host.Quoted 5 lines
I think we are not really on the same page here (no pun intended :) ). I'll try to answer your questions anyway...
Which
get_pfn? Are you referring toget_pfnwhen faulting the page into the guest or into the host?I am referring to guest fault handling in KVM.
Quoted 25 lines
Quoted 3 lines
2) host user space has to guess whether it's a pending refcount or whether it's an actual mismatch.
No need to guess. VCPU run will let it know exactly why it's exiting.
Quoted 6 lines
3)
guest_memfdwill maintain a third state "pending_private_conversion" or equivalent which will transition to private upon the last refcount drop of each page.If conversion is triggered by userspace (in case of pKVM, it will be triggered from within the KVM (?)):
Why would conversion be triggered by userspace? As far as I know, it's the guest that triggers the conversion.
Quoted 6 lines
* Conversion will just fail if there are extra refcounts and userspace can try to get rid of extra refcounts on the range while it has enough context without hitting any ambiguity with memory fault exit.
*guest_memfdwill not have to deal with this extra state from 3 above and overallguest_memfdconversion handling becomes relatively simpler.That's not really related. The extra state isn't necessary any more once we agreed in the previous discussion that we will retry instead.
Quoted 8 lines
Quoted 3 lines
Quoted 1 line
Who is *we* here? Which entity will retry conversion?
Userspace will re-attempt the VCPU run.
Then KVM will have to keep track of the ranges that need conversion across exits. I think it's cleaner to let userspace make the decision and invoke conversion without carrying additional state in KVM about guest request.
I disagree. I think it's cleaner not to introduce a user interface, and just to track the reason for the last exit, along with the required additional data. KVM is responsible already for handling the workflow, why delegate this last part to the VMM?
Quoted 26 lines
Quoted 26 lines
Quoted 11 lines
Quoted 10 lines
Quoted 5 lines
Note that for x86 CoCo cases, memory conversion is already triggered by userspace using KVM ioctl, this series is proposing to use
guest_memfdioctl to do the same.The reason why for x86 CoCo cases conversion is already triggered by userspace using KVM ioctl is that it has to, since shared memory and private memory are two separate pages, and userspace needs to manage that. Sharing memory in place removes the need for that.
Quoted 5 lines
Userspace still needs to clean up memory usage before conversion is successful. e.g. remove IOMMU mappings for shared to private conversion. I would think that memory conversion should not succeed before all existing users let go of the
guest_memfdpages for the range being converted.Yes. Userspace will know that it needs to do that on the VCPU exit, which informs it of the guest's hypervisor request to unshare (convert from shared to private) the page.
Quoted 4 lines
In x86 CoCo usecases, userspace can also decide to not allow conversion for scenarios where ranges are still under active use by the host and guest is erroneously trying to take away memory. Both SNP/TDX spec allow failure of conversion due to in use memory.
Quoted 7 lines
Quoted 4 lines
How can the guest erroneously try to take away memory? If the guest sends a hypervisor request asking for a conversion of memory that doesn't belong to it, then I would expect the hypervisor to prevent that.
Making a range as private is effectively disallowing host from accessing those ranges -> so taking away memory.
You said "erroneously" earlier. My question is, how can the guest *erroneously* try to take away memory? This is the normal flow of guest/host relations. The memory is the guest's: it decides when to share it with the host, and it can take it away.
Quoted 29 lines
Quoted 29 lines
I don't see how having an IOCTL to trigger the conversion is needed to allow conversion failure. How is that different from userspace ignoring or delaying releasing all references it has for the conversion request?
Quoted 9 lines
Quoted 4 lines
This series isn't using the same ioctl, it's introducing new ones to perform a task that as far as I can tell so far, KVM can handle by itself.
I would like to understand this better. How will KVM handle the conversion process for
guest_memfdpages? Can you help walk an example sequence for shared to private conversion specifically aroundguest_memfdoffset states?To make sure that we are discussing the same scenario: can you do the same as well please --- walk me through an example sequence for shared to private conversion specifically around
guest_memfdoffset states With the IOCTLs involved?Here is an example that I have implemented and tested with pKVM. Note that there are alternatives, the flow below is architecture or even vm-type dependent. None of this code is code KVM code and the behaviour could vary.
Assuming the folio is shared with the host:
Quoted 7 lines
Quoted 3 lines
Guest sends unshare hypercall to the hypervisor
Hypervisor forwards request to KVM (gmem) (having done due diligence) KVM (gmem) performs anunmap_folio(), exits to userspace withFor x86 CoCo VM usecases I was talking about, userspace would like to avoid
unmap_mapping_range()on the range before it's safe to unshare the range.
Why? There is no harm in userspace unmapping before the memory isn't shared. I don't see the problem with that.
You still haven't responded to my question from the previous email:
can you please return the favor and walk me through an example sequence for shared to private conversion specifically around guest_memfd offset states with the IOCTLs involved? :D
Thanks!
/fuad
Quoted 52 lines
Quoted 52 lines
KVM_EXIT_UNSHAREand all the information about the folio being unsharedCase 1:
Userspace removes any remaining references (GUPs, IOMMU Mappings etc...) Userspace callsvcpu_run(): KVM (gmem) sees that there aren't any references, sets state to PRIVATECase 2 (alternative 1):
Userspace doesn't release its references
Userspace callsvcpu_run(): KVM (gmem) sees that there are still references, exits back to userspace withKVM_EXIT_UNSHARECase 2 (alternative 2):
Userspace doesn't release its references
Userspace callsvcpu_run(): KVM (gmem) sees that there are still references, unmaps folio from guest, but allows it to run (until it tries to fault in the folio)
Guest tries to fault in folio that still has reference, KVM does not allow that (it sees that the folio is shared, and it doesn't fault in shared folios to confidential guests)
KVM exits back to userspace withKVM_EXIT_UNSHAREAs I mentioned, the alternatives above are _not_ set in core KVM code. They can vary by architecture of VM type, depending on the policy, support, etc..
Now for your example please on how this would work with IOCTLs :)
Thanks,
/fuadQuoted 20 lines
Quoted 20 lines
Quoted 3 lines
- Allows not having to keep track of separate shared/private range
information in KVM.This patch series is already tracking shared/private range information in KVM.
Quoted 9 lines
- Simpler handling of the conversion process done per
guest_memfd
rather than for full range.
- Userspace can handle the rollback as needed, simplifying error
handling inguest_memfd.
-guest_memfdis single source of truth and notifies the users of
shareability change.
- e.g. IOMMU, userspace, KVM MMU all can be registered for
getting notifications fromguest_memfddirectly and will get notified for invalidation upon shareability attribute updates.All of these can still be done without introducing a new ioctl.
Cheers,
/fuad
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Fuad Tabba <[email protected]> writes:
Let me try to bridge the gap here beginning with the flow we were counting on for a shared to private conversion, for TDX:
1. Guest sends unshare hypercall to the hypervisor
2. (For x86 IIUC hypervisor is the same as KVM) KVM forwards the request to userspace via a KVM_EXIT_HYPERCALL, with KVM_HC_MAP_GPA_RANGE as the hypercall number.
KVM also records that the guest wanted a shared to private conversion, the gpa and size of the request (no change from now, KVM already records that information in struct kvm_run) [1]
3. Userspace will do necessary coordination in userspace, then call the conversion ioctl, passing the parameters along to the ioctl.
4. Ioctl goes to guest_memfd, guest_memfd unmaps the pages, checks refcounts. If there's anything unexpected, error out to userspace. If all is well, flip shareability, exit to userspace with success.
5. Userspace calls vcpu_run() again, the handler for KVM_HC_MAP_GPA_RANGE will tell the guest that userspace was able to fulfill guest request with hypercall.ret set to 0 and then the guest will continue.
6. On the next fault guest_memfd will allow the private fault from the guest.
The flow you're proposing works too, with some changes, but it's probably okay for x86 to have a slightly different flow anyway: (I refactored the steps you outlined)
Quoted 1 line
1. Guest sends unshare hypercall to the hypervisor
Same
Quoted 1 line
2. Hypervisor forwards request to KVM (gmem) (having done due diligence)
For x86 IIUC hypervisor is the same as KVM, so there's no forwarding to KVM.
Quoted 2 lines
3. KVM (gmem) performs an
unmap_folio(), exits to userspace withKVM_EXIT_UNSHAREand all the information about the folio being unshared
The KVM_EXIT_UNSHARE here would correspond to x86's KVM_HC_MAP_GPA_RANGE.
Unmapping before exiting with KVM_EXIT_UNSHARE here might be a little premature since userspace may have to do some stuff before permitting the conversion. For example, the memory may be mapped into another userspace driver process, which needs to first be stopped.
But no issue though, as long as we don't flip shareability, if the host uses the memory, the kvm_gmem_fault_shared() will just happen again, nullifying the unmapping.
We could just shift the unmapping till after vcpu_run() is called again.
Quoted 2 lines
4. Userspace will do necessary coordination in userspace, then do
vcpu_run()
There's another layer here, at least for x86, as to whether the coordination was successful. For x86's KVM_HC_MAP_GPA_RANGE, userspace can indicate a non-zero hypercall.ret for error.
For unsuccessful coordinations, userspace sets hypercall.ret to error and the vcpu_run() handler doesn't try the conversion. Guest is informed of hypercall error and guest will figure it out.
Quoted 2 lines
5. Successful coordination, case 1:
vcpu_run()knows the last exit wasKVM_EXIT_UNSHAREand will set state to PRIVATE
For case 1, userspace will set hypercall.ret == 0, guest_memfd will do the conversion, basically calling the same function that the ioctl calls within guest_memfd.
Quoted 2 lines
5. Successful coordination, case 2, alternative 1:
vcpu_run()knows the last exit wasKVM_EXIT_UNSHARE
Exit to userspace with KVM_EXIT_MEMORY_FAULT.
Quoted 2 lines
5. Successful coordination, case 2, alternative 2:
vcpu_run()knows the last exit wasKVM_EXIT_UNSHARE
Forward hypercall.ret == 0 to the guest. Since the conversion was not performed, the next fault will be mismatched and there will be a KVM_EXIT_MEMORY_FAULT.
Quoted 117 lines
Hi Vishal,
Quoted 105 lines · Vishal Annapurve
Quoted 103 lines · Fuad Tabba
Hi Vishal,
Quoted 99 lines · Vishal Annapurve
Quoted 63 lines · Fuad Tabba
Hi Vishal,
Quoted 55 lines · Vishal Annapurve
Quoted 46 lines · Fuad Tabba
Hi Ackerley,
Quoted 4 lines · Ackerley Tng
The two new
guest_memfdioctlsKVM_GMEM_CONVERT_SHAREDandKVM_GMEM_CONVERT_PRIVATEconvert the requested memory ranges to shared and private respectively.I have a high level question about this particular patch and this approach for conversion: why do we need IOCTLs to manage conversion between private and shared?
In the presentations I gave at LPC [1, 2], and in my latest patch series that performs in-place conversion [3] and the associated (by now outdated) state diagram [4], I didn't see the need to have a userspace-facing interface to manage that. KVM has all the information it needs to handle conversions, which are triggered by the guest. To me this seems like it adds additional complexity, as well as a user facing interface that we would need to maintain.
There are various ways we could handle conversion without explicit interference from userspace. What I had in mind is the following (as an example, details can vary according to VM type). I will use use the case of conversion from shared to private because that is the more complicated (interesting) case:
- Guest issues a hypercall to request that a shared folio become private.
- The hypervisor receives the call, and passes it to KVM.
- KVM unmaps the folio from the guest stage-2 (EPT I think in x86 parlance), and unmaps it from the host. The host however, could still have references (e.g., GUP).
- KVM exits to the host (hypervisor call exit), with the information that the folio has been unshared from it.
- A well behaving host would now get rid of all of its references (e.g., release GUPs), perform a VCPU run, and the guest continues running as normal. I expect this to be the common case.
But to handle the more interesting situation, let's say that the host doesn't do it immediately, and for some reason it holds on to some references to that folio.
Quoted 6 lines
- Even if that's the case, the guest can still run *. If the guest tries to access the folio, KVM detects that access when it tries to fault it into the guest, sees that the host still has references to that folio, and exits back to the host with a memory fault exit. At this point, the VCPU that has tried to fault in that particular folio cannot continue running as long as it cannot fault in that folio.
Quoted 3 lines
Are you talking about the following scheme?
1)guest_memfdchecks shareability on each get pfn and if there is a mismatch exit to the host.Quoted 5 lines
I think we are not really on the same page here (no pun intended :) ). I'll try to answer your questions anyway...
Which
get_pfn? Are you referring toget_pfnwhen faulting the page into the guest or into the host?I am referring to guest fault handling in KVM.
Quoted 25 lines
Quoted 3 lines
2) host user space has to guess whether it's a pending refcount or whether it's an actual mismatch.
No need to guess. VCPU run will let it know exactly why it's exiting.
Quoted 6 lines
3)
guest_memfdwill maintain a third state "pending_private_conversion" or equivalent which will transition to private upon the last refcount drop of each page.If conversion is triggered by userspace (in case of pKVM, it will be triggered from within the KVM (?)):
Why would conversion be triggered by userspace? As far as I know, it's the guest that triggers the conversion.
Quoted 6 lines
* Conversion will just fail if there are extra refcounts and userspace can try to get rid of extra refcounts on the range while it has enough context without hitting any ambiguity with memory fault exit.
*guest_memfdwill not have to deal with this extra state from 3 above and overallguest_memfdconversion handling becomes relatively simpler.That's not really related. The extra state isn't necessary any more once we agreed in the previous discussion that we will retry instead.
Quoted 8 lines
Quoted 3 lines
Quoted 1 line
Who is *we* here? Which entity will retry conversion?
Userspace will re-attempt the VCPU run.
Then KVM will have to keep track of the ranges that need conversion across exits. I think it's cleaner to let userspace make the decision and invoke conversion without carrying additional state in KVM about guest request.
Quoted 5 lines
I disagree. I think it's cleaner not to introduce a user interface, and just to track the reason for the last exit, along with the required additional data. KVM is responsible already for handling the workflow, why delegate this last part to the VMM?
I believe Fuad's concern is the complexity of adding and maintaining another ioctl, as opposed to having vcpu_run() do the conversions.
I think the two options are basically the same in that both are actually adding some form of user contract, just in different places.
For the ioctl approach, in this RFCv2 I added a error_offset field so that userspace has a hint of where the conversion had an issue. the ioctl also returns errors to indicate what went wrong, like -EINVAL or -ENOMEM if perhaps splitting the page required memory and there wasn't any, or the kernel ran out of memory trying to update mappability.
If we want to provide the same level of error information for the vcpu_run() approach, we should probably add error_offset to KVM_EXIT_MEMORY_FAULT so that on a conversion failure we could re-exit to userspace with more information about the error_offset.
So what we're really comparing is two ways to perform the conversion (1) via a direct ioctl and (2) via vcpu_run().
I think having a direct ioctl is cleaner because it doesn't involve vCPUs for a memory operation.
Conceptually, the conversion is a memory operation belonging to memory in the guest_memfd. Hence, the conversion operation is better addressed directly to the memory via a direct ioctl.
For this same reason, we didn't want to do the conversion via the KVM_SET_MEMORY_ATTRIBUTES ioctl. KVM_SET_MEMORY_ATTRIBUTES is an operation for KVM's view of guest_memfd, which is linked to but not directly the same as a memory operation.
By having a direct ioctl over using KVM_SET_MEMORY_ATTRIBUTES, we avoid having a dependency where memslots must first be bound to guest_memfd for the conversion to work.
When rebooting, the memslots may not yet be bound to the guest_memfd, but we want to reset the guest_memfd's to private. If we use KVM_SET_MEMORY_ATTRIBUTES to convert, we'd be forced to first bind, then convert. If we had a direct ioctl, we don't have this restriction.
If we do the conversion via vcpu_run() we would be forced to handle conversions only with a vcpu_run() and only the guest can initiate a conversion.
On a guest boot for TDX, the memory is assumed to be private. If the we gave it memory set as shared, we'd just have a bunch of KVM_EXIT_MEMORY_FAULTs that slow down boot. Hence on a guest reboot, we will want to reset the guest memory to private.
We could say the firmware should reset memory to private on guest reboot, but we can't force all guests to update firmware.
Quoted 31 lines
Quoted 31 lines
Quoted 30 lines
Quoted 11 lines
Quoted 10 lines
Quoted 5 lines
Note that for x86 CoCo cases, memory conversion is already triggered by userspace using KVM ioctl, this series is proposing to use
guest_memfdioctl to do the same.The reason why for x86 CoCo cases conversion is already triggered by userspace using KVM ioctl is that it has to, since shared memory and private memory are two separate pages, and userspace needs to manage that. Sharing memory in place removes the need for that.
Quoted 5 lines
Userspace still needs to clean up memory usage before conversion is successful. e.g. remove IOMMU mappings for shared to private conversion. I would think that memory conversion should not succeed before all existing users let go of the
guest_memfdpages for the range being converted.Yes. Userspace will know that it needs to do that on the VCPU exit, which informs it of the guest's hypervisor request to unshare (convert from shared to private) the page.
Quoted 4 lines
In x86 CoCo usecases, userspace can also decide to not allow conversion for scenarios where ranges are still under active use by the host and guest is erroneously trying to take away memory. Both SNP/TDX spec allow failure of conversion due to in use memory.
How can the guest erroneously try to take away memory? If the guest sends a hypervisor request asking for a conversion of memory that doesn't belong to it, then I would expect the hypervisor to prevent that.
Quoted 8 lines
Quoted 2 lines
Making a range as private is effectively disallowing host from accessing those ranges -> so taking away memory.
You said "erroneously" earlier. My question is, how can the guest *erroneously* try to take away memory? This is the normal flow of guest/host relations. The memory is the guest's: it decides when to share it with the host, and it can take it away.
See above, it's not really erroneous as long as we kvm_gmem_fault_shared() can still happen, since after unmapping, any host access will just fault the page again.
Quoted 33 lines
Quoted 33 lines
Quoted 32 lines
I don't see how having an IOCTL to trigger the conversion is needed to allow conversion failure. How is that different from userspace ignoring or delaying releasing all references it has for the conversion request?
Quoted 9 lines
Quoted 4 lines
This series isn't using the same ioctl, it's introducing new ones to perform a task that as far as I can tell so far, KVM can handle by itself.
I would like to understand this better. How will KVM handle the conversion process for
guest_memfdpages? Can you help walk an example sequence for shared to private conversion specifically aroundguest_memfdoffset states?To make sure that we are discussing the same scenario: can you do the same as well please --- walk me through an example sequence for shared to private conversion specifically around
guest_memfdoffset states With the IOCTLs involved?Here is an example that I have implemented and tested with pKVM. Note that there are alternatives, the flow below is architecture or even vm-type dependent. None of this code is code KVM code and the behaviour could vary.
Assuming the folio is shared with the host:
Guest sends unshare hypercall to the hypervisor
Hypervisor forwards request to KVM (gmem) (having done due diligence) KVM (gmem) performs anunmap_folio(), exits to userspace with
Quoted 7 lines
Quoted 3 lines
For x86 CoCo VM usecases I was talking about, userspace would like to avoid
unmap_mapping_range()on the range before it's safe to unshare the range.Why? There is no harm in userspace unmapping before the memory isn't shared. I don't see the problem with that.
Yes, no harm done, just possible remapping after unmapping.
Quoted 5 lines
You still haven't responded to my question from the previous email:
can you please return the favor and walk me through an example sequence for shared to private conversion specifically aroundguest_memfdoffset states with the IOCTLs involved? :D
Right at the top :)
Quoted 56 lines
Thanks!
/fuadQuoted 52 lines
Quoted 52 lines
KVM_EXIT_UNSHAREand all the information about the folio being unsharedCase 1:
Userspace removes any remaining references (GUPs, IOMMU Mappings etc...) Userspace callsvcpu_run(): KVM (gmem) sees that there aren't any references, sets state to PRIVATECase 2 (alternative 1):
Userspace doesn't release its references
Userspace callsvcpu_run(): KVM (gmem) sees that there are still references, exits back to userspace withKVM_EXIT_UNSHARECase 2 (alternative 2):
Userspace doesn't release its references
Userspace callsvcpu_run(): KVM (gmem) sees that there are still references, unmaps folio from guest, but allows it to run (until it tries to fault in the folio)
Guest tries to fault in folio that still has reference, KVM does not allow that (it sees that the folio is shared, and it doesn't fault in shared folios to confidential guests)
KVM exits back to userspace withKVM_EXIT_UNSHAREAs I mentioned, the alternatives above are _not_ set in core KVM code. They can vary by architecture of VM type, depending on the policy, support, etc..
Now for your example please on how this would work with IOCTLs :)
Thanks,
/fuadQuoted 20 lines
Quoted 20 lines
Quoted 3 lines
- Allows not having to keep track of separate shared/private range
information in KVM.This patch series is already tracking shared/private range information in KVM.
Quoted 9 lines
- Simpler handling of the conversion process done per
guest_memfd
rather than for full range.
- Userspace can handle the rollback as needed, simplifying error
handling inguest_memfd.
-guest_memfdis single source of truth and notifies the users of
shareability change.
- e.g. IOMMU, userspace, KVM MMU all can be registered for
getting notifications fromguest_memfddirectly and will get notified for invalidation upon shareability attribute updates.All of these can still be done without introducing a new ioctl.
Cheers,
/fuad
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Hi Ackerley,
Quoted 83 lines · Ackerley Tng
Fuad Tabba <[email protected]> writes:
Let me try to bridge the gap here beginning with the flow we were counting on for a shared to private conversion, for TDX:
1. Guest sends unshare hypercall to the hypervisor
2. (For x86 IIUC hypervisor is the same as KVM) KVM forwards the request to userspace via a
KVM_EXIT_HYPERCALL, withKVM_HC_MAP_GPA_RANGEas the hypercall number.KVM also records that the guest wanted a shared to private conversion, the gpa and size of the request (no change from now, KVM already records that information in struct
kvm_run) [1]3. Userspace will do necessary coordination in userspace, then call the conversion ioctl, passing the parameters along to the ioctl.
4. Ioctl goes to
guest_memfd,guest_memfdunmaps the pages, checks refcounts. If there's anything unexpected, error out to userspace. If all is well, flip shareability, exit to userspace with success.5. Userspace calls
vcpu_run()again, the handler forKVM_HC_MAP_GPA_RANGEwill tell the guest that userspace was able to fulfill guest request with hypercall.ret set to 0 and then the guest will continue.6. On the next fault
guest_memfdwill allow the private fault from the guest.The flow you're proposing works too, with some changes, but it's probably okay for x86 to have a slightly different flow anyway: (I refactored the steps you outlined)
Quoted 1 line
1. Guest sends unshare hypercall to the hypervisor
Same
Quoted 1 line
2. Hypervisor forwards request to KVM (gmem) (having done due diligence)
For x86 IIUC hypervisor is the same as KVM, so there's no forwarding to KVM.
Quoted 2 lines
3. KVM (gmem) performs an
unmap_folio(), exits to userspace withKVM_EXIT_UNSHAREand all the information about the folio being unsharedThe
KVM_EXIT_UNSHAREhere would correspond to x86'sKVM_HC_MAP_GPA_RANGE.Unmapping before exiting with
KVM_EXIT_UNSHAREhere might be a little premature since userspace may have to do some stuff before permitting the conversion. For example, the memory may be mapped into another userspace driver process, which needs to first be stopped.But no issue though, as long as we don't flip shareability, if the host uses the memory, the
kvm_gmem_fault_shared()will just happen again, nullifying the unmapping.We could just shift the unmapping till after
vcpu_run()is called again.Quoted 2 lines
4. Userspace will do necessary coordination in userspace, then do
vcpu_run()There's another layer here, at least for x86, as to whether the coordination was successful. For x86's
KVM_HC_MAP_GPA_RANGE, userspace can indicate a non-zero hypercall.ret for error.For unsuccessful coordinations, userspace sets hypercall.ret to error and the
vcpu_run()handler doesn't try the conversion. Guest is informed of hypercall error and guest will figure it out.Quoted 2 lines
5. Successful coordination, case 1:
vcpu_run()knows the last exit wasKVM_EXIT_UNSHAREand will set state to PRIVATEFor case 1, userspace will set hypercall.ret == 0,
guest_memfdwill do the conversion, basically calling the same function that the ioctl calls withinguest_memfd.Quoted 2 lines
5. Successful coordination, case 2, alternative 1:
vcpu_run()knows the last exit wasKVM_EXIT_UNSHARE
Quoted 8 lines
Exit to userspace with
KVM_EXIT_MEMORY_FAULT.Quoted 2 lines
5. Successful coordination, case 2, alternative 2:
vcpu_run()knows the last exit wasKVM_EXIT_UNSHAREForward hypercall.ret == 0 to the guest. Since the conversion was not performed, the next fault will be mismatched and there will be a
KVM_EXIT_MEMORY_FAULT.
So far so good. With regard to the flow, in the code that I had, all the specific details were arm64, and even pKVM specific. None of it was baked into core KVM code, since of course, different architectures, and even different VM types, will vary significantly. Arm CCA for example is closer to TDX than it is to pKVM. Moreover, it was just a hack at getting something reasonable that works, as a proof of concept.
This is one of the reasons I'm not a fan of having a userspace IOCTL as an additional required step as part of this protocol. KVM exits already exist (*), and we need them anyway here. The flow above is VM-type specific, and since much of it isn't exposed to the user: it's easy (and likely) to change. Having an IOCTL and adding another step in the process makes it more difficult to change things later.
(*) Try saying that ten times fast! Note: first word is exit, second word is exist :)
Quoted 135 lines
Quoted 117 lines
Hi Vishal,
Quoted 105 lines · Vishal Annapurve
Quoted 103 lines · Fuad Tabba
Hi Vishal,
Quoted 99 lines · Vishal Annapurve
Quoted 63 lines · Fuad Tabba
Hi Vishal,
Quoted 55 lines · Vishal Annapurve
Quoted 46 lines · Fuad Tabba
Hi Ackerley,
Quoted 4 lines · Ackerley Tng
The two new
guest_memfdioctlsKVM_GMEM_CONVERT_SHAREDandKVM_GMEM_CONVERT_PRIVATEconvert the requested memory ranges to shared and private respectively.I have a high level question about this particular patch and this approach for conversion: why do we need IOCTLs to manage conversion between private and shared?
In the presentations I gave at LPC [1, 2], and in my latest patch series that performs in-place conversion [3] and the associated (by now outdated) state diagram [4], I didn't see the need to have a userspace-facing interface to manage that. KVM has all the information it needs to handle conversions, which are triggered by the guest. To me this seems like it adds additional complexity, as well as a user facing interface that we would need to maintain.
There are various ways we could handle conversion without explicit interference from userspace. What I had in mind is the following (as an example, details can vary according to VM type). I will use use the case of conversion from shared to private because that is the more complicated (interesting) case:
- Guest issues a hypercall to request that a shared folio become private.
- The hypervisor receives the call, and passes it to KVM.
- KVM unmaps the folio from the guest stage-2 (EPT I think in x86 parlance), and unmaps it from the host. The host however, could still have references (e.g., GUP).
- KVM exits to the host (hypervisor call exit), with the information that the folio has been unshared from it.
- A well behaving host would now get rid of all of its references (e.g., release GUPs), perform a VCPU run, and the guest continues running as normal. I expect this to be the common case.
But to handle the more interesting situation, let's say that the host doesn't do it immediately, and for some reason it holds on to some references to that folio.
Quoted 6 lines
- Even if that's the case, the guest can still run *. If the guest tries to access the folio, KVM detects that access when it tries to fault it into the guest, sees that the host still has references to that folio, and exits back to the host with a memory fault exit. At this point, the VCPU that has tried to fault in that particular folio cannot continue running as long as it cannot fault in that folio.
Quoted 3 lines
Are you talking about the following scheme?
1)guest_memfdchecks shareability on each get pfn and if there is a mismatch exit to the host.Quoted 5 lines
I think we are not really on the same page here (no pun intended :) ). I'll try to answer your questions anyway...
Which
get_pfn? Are you referring toget_pfnwhen faulting the page into the guest or into the host?I am referring to guest fault handling in KVM.
Quoted 25 lines
Quoted 3 lines
2) host user space has to guess whether it's a pending refcount or whether it's an actual mismatch.
No need to guess. VCPU run will let it know exactly why it's exiting.
Quoted 6 lines
3)
guest_memfdwill maintain a third state "pending_private_conversion" or equivalent which will transition to private upon the last refcount drop of each page.If conversion is triggered by userspace (in case of pKVM, it will be triggered from within the KVM (?)):
Why would conversion be triggered by userspace? As far as I know, it's the guest that triggers the conversion.
Quoted 6 lines
* Conversion will just fail if there are extra refcounts and userspace can try to get rid of extra refcounts on the range while it has enough context without hitting any ambiguity with memory fault exit.
*guest_memfdwill not have to deal with this extra state from 3 above and overallguest_memfdconversion handling becomes relatively simpler.That's not really related. The extra state isn't necessary any more once we agreed in the previous discussion that we will retry instead.
Quoted 8 lines
Quoted 3 lines
Quoted 1 line
Who is *we* here? Which entity will retry conversion?
Userspace will re-attempt the VCPU run.
Then KVM will have to keep track of the ranges that need conversion across exits. I think it's cleaner to let userspace make the decision and invoke conversion without carrying additional state in KVM about guest request.
Quoted 5 lines
I disagree. I think it's cleaner not to introduce a user interface, and just to track the reason for the last exit, along with the required additional data. KVM is responsible already for handling the workflow, why delegate this last part to the VMM?
I believe Fuad's concern is the complexity of adding and maintaining another ioctl, as opposed to having
vcpu_run()do the conversions.I think the two options are basically the same in that both are actually adding some form of user contract, just in different places.
For the ioctl approach, in this RFCv2 I added a
error_offsetfield so that userspace has a hint of where the conversion had an issue. the ioctl also returns errors to indicate what went wrong, like-EINVALor-ENOMEMif perhaps splitting the page required memory and there wasn't any, or the kernel ran out of memory trying to update mappability.
Quoted 8 lines
If we want to provide the same level of error information for the
vcpu_run()approach, we should probably adderror_offsettoKVM_EXIT_MEMORY_FAULTso that on a conversion failure we could re-exit to userspace with more information about theerror_offset.So what we're really comparing is two ways to perform the conversion (1) via a direct ioctl and (2) via
vcpu_run().
That's exactly right.
Quoted 25 lines
I think having a direct ioctl is cleaner because it doesn't involve vCPUs for a memory operation.
Conceptually, the conversion is a memory operation belonging to memory in the
guest_memfd. Hence, the conversion operation is better addressed directly to the memory via a direct ioctl.For this same reason, we didn't want to do the conversion via the
KVM_SET_MEMORY_ATTRIBUTESioctl.KVM_SET_MEMORY_ATTRIBUTESis an operation for KVM's view ofguest_memfd, which is linked to but not directly the same as a memory operation.By having a direct ioctl over using
KVM_SET_MEMORY_ATTRIBUTES, we avoid having a dependency where memslots must first be bound toguest_memfdfor the conversion to work.When rebooting, the memslots may not yet be bound to the
guest_memfd, but we want to reset the guest_memfd's to private. If we useKVM_SET_MEMORY_ATTRIBUTESto convert, we'd be forced to first bind, then convert. If we had a direct ioctl, we don't have this restriction.If we do the conversion via
vcpu_run()we would be forced to handle conversions only with avcpu_run()and only the guest can initiate a conversion.
Quoted 7 lines
On a guest boot for TDX, the memory is assumed to be private. If the we gave it memory set as shared, we'd just have a bunch of
KVM_EXIT_MEMORY_FAULTsthat slow down boot. Hence on a guest reboot, we will want to reset the guest memory to private.We could say the firmware should reset memory to private on guest reboot, but we can't force all guests to update firmware.
Here is where I disagree. I do think that this is the CoCo guest's responsibility (and by guest I include its firmware) to fix its own state after a reboot. How would the host even know that a guest is rebooting if it's a CoCo guest?
Either the host doesn't (or cannot even) know that the guest is rebooting, in which case I don't see how having an IOCTL would help. Or somehow the host does know that, i.e., via a hypercall that indicates that. In which case, we could have it so that for that type of VM, we would reconvert its pages to private on a reboot.
Additionally, we could introduce range operations for sharing/unsharing, to avoid having to have an exit for every one.
Quoted 40 lines
Quoted 31 lines
Quoted 31 lines
Quoted 30 lines
Quoted 11 lines
Quoted 10 lines
Quoted 5 lines
Note that for x86 CoCo cases, memory conversion is already triggered by userspace using KVM ioctl, this series is proposing to use
guest_memfdioctl to do the same.The reason why for x86 CoCo cases conversion is already triggered by userspace using KVM ioctl is that it has to, since shared memory and private memory are two separate pages, and userspace needs to manage that. Sharing memory in place removes the need for that.
Quoted 5 lines
Userspace still needs to clean up memory usage before conversion is successful. e.g. remove IOMMU mappings for shared to private conversion. I would think that memory conversion should not succeed before all existing users let go of the
guest_memfdpages for the range being converted.Yes. Userspace will know that it needs to do that on the VCPU exit, which informs it of the guest's hypervisor request to unshare (convert from shared to private) the page.
Quoted 4 lines
In x86 CoCo usecases, userspace can also decide to not allow conversion for scenarios where ranges are still under active use by the host and guest is erroneously trying to take away memory. Both SNP/TDX spec allow failure of conversion due to in use memory.
How can the guest erroneously try to take away memory? If the guest sends a hypervisor request asking for a conversion of memory that doesn't belong to it, then I would expect the hypervisor to prevent that.
Quoted 8 lines
Quoted 2 lines
Making a range as private is effectively disallowing host from accessing those ranges -> so taking away memory.
You said "erroneously" earlier. My question is, how can the guest *erroneously* try to take away memory? This is the normal flow of guest/host relations. The memory is the guest's: it decides when to share it with the host, and it can take it away.
Quoted 3 lines
See above, it's not really erroneous as long as we
kvm_gmem_fault_shared()can still happen, since after unmapping, any host access will just fault the page again.
I was confused by the word "erroneous", as you would expect that for a CoCo guest, the host wouldn't (or shouldn't) know the intention behind a CoCo guest's access. I would expect that erroneous guest accesses would be handled by the hypervisor. But I think we're on the same page now.
Quoted 43 lines
Quoted 33 lines
Quoted 33 lines
Quoted 32 lines
I don't see how having an IOCTL to trigger the conversion is needed to allow conversion failure. How is that different from userspace ignoring or delaying releasing all references it has for the conversion request?
Quoted 9 lines
Quoted 4 lines
This series isn't using the same ioctl, it's introducing new ones to perform a task that as far as I can tell so far, KVM can handle by itself.
I would like to understand this better. How will KVM handle the conversion process for
guest_memfdpages? Can you help walk an example sequence for shared to private conversion specifically aroundguest_memfdoffset states?To make sure that we are discussing the same scenario: can you do the same as well please --- walk me through an example sequence for shared to private conversion specifically around
guest_memfdoffset states With the IOCTLs involved?Here is an example that I have implemented and tested with pKVM. Note that there are alternatives, the flow below is architecture or even vm-type dependent. None of this code is code KVM code and the behaviour could vary.
Assuming the folio is shared with the host:
Guest sends unshare hypercall to the hypervisor
Hypervisor forwards request to KVM (gmem) (having done due diligence) KVM (gmem) performs anunmap_folio(), exits to userspace withQuoted 7 lines
Quoted 3 lines
For x86 CoCo VM usecases I was talking about, userspace would like to avoid
unmap_mapping_range()on the range before it's safe to unshare the range.Why? There is no harm in userspace unmapping before the memory isn't shared. I don't see the problem with that.
Yes, no harm done, just possible remapping after unmapping.
Quoted 7 lines
Quoted 5 lines
You still haven't responded to my question from the previous email:
can you please return the favor and walk me through an example sequence for shared to private conversion specifically aroundguest_memfdoffset states with the IOCTLs involved? :DRight at the top :)
Thank you Ackerley!
Cheers,
/fuad
Quoted 57 lines
Quoted 57 lines
Thanks!
/fuadQuoted 52 lines
Quoted 52 lines
KVM_EXIT_UNSHAREand all the information about the folio being unsharedCase 1:
Userspace removes any remaining references (GUPs, IOMMU Mappings etc...) Userspace callsvcpu_run(): KVM (gmem) sees that there aren't any references, sets state to PRIVATECase 2 (alternative 1):
Userspace doesn't release its references
Userspace callsvcpu_run(): KVM (gmem) sees that there are still references, exits back to userspace withKVM_EXIT_UNSHARECase 2 (alternative 2):
Userspace doesn't release its references
Userspace callsvcpu_run(): KVM (gmem) sees that there are still references, unmaps folio from guest, but allows it to run (until it tries to fault in the folio)
Guest tries to fault in folio that still has reference, KVM does not allow that (it sees that the folio is shared, and it doesn't fault in shared folios to confidential guests)
KVM exits back to userspace withKVM_EXIT_UNSHAREAs I mentioned, the alternatives above are _not_ set in core KVM code. They can vary by architecture of VM type, depending on the policy, support, etc..
Now for your example please on how this would work with IOCTLs :)
Thanks,
/fuadQuoted 20 lines
Quoted 20 lines
Quoted 3 lines
- Allows not having to keep track of separate shared/private range
information in KVM.This patch series is already tracking shared/private range information in KVM.
Quoted 9 lines
- Simpler handling of the conversion process done per
guest_memfd
rather than for full range.
- Userspace can handle the rollback as needed, simplifying error
handling inguest_memfd.
-guest_memfdis single source of truth and notifies the users of
shareability change.
- e.g. IOMMU, userspace, KVM MMU all can be registered for
getting notifications fromguest_memfddirectly and will get notified for invalidation upon shareability attribute updates.All of these can still be done without introducing a new ioctl.
Cheers,
/fuad
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 15 lines · Fuad Tabba
....
Quoted 14 lines
When rebooting, the memslots may not yet be bound to the
guest_memfd, but we want to reset the guest_memfd's to private. If we useKVM_SET_MEMORY_ATTRIBUTESto convert, we'd be forced to first bind, then convert. If we had a direct ioctl, we don't have this restriction.If we do the conversion via
vcpu_run()we would be forced to handle conversions only with avcpu_run()and only the guest can initiate a conversion.On a guest boot for TDX, the memory is assumed to be private. If the we gave it memory set as shared, we'd just have a bunch of
KVM_EXIT_MEMORY_FAULTsthat slow down boot. Hence on a guest reboot, we will want to reset the guest memory to private.
Quoted 7 lines
Quoted 2 lines
We could say the firmware should reset memory to private on guest reboot, but we can't force all guests to update firmware.
Here is where I disagree. I do think that this is the CoCo guest's responsibility (and by guest I include its firmware) to fix its own state after a reboot. How would the host even know that a guest is rebooting if it's a CoCo guest?
There are a bunch of complexities here, reboot sequence on x86 can be triggered using multiple ways that I don't fully understand, but few of them include reading/writing to "reset register" in MMIO/PCI config space that are emulated by the host userspace directly. Host has to know when the guest is shutting down to manage it's lifecycle.
x86 CoCo VM firmwares don't support warm/soft reboot and even if it does in future, guest kernel can choose a different reboot mechanism. So guest reboot needs to be emulated by always starting from scratch. This sequence needs initial guest firmware payload to be installed into private ranges of guest_memfd.
Quoted 3 lines
Either the host doesn't (or cannot even) know that the guest is rebooting, in which case I don't see how having an IOCTL would help.
Host does know that the guest is rebooting.
Quoted 3 lines
Or somehow the host does know that, i.e., via a hypercall that indicates that. In which case, we could have it so that for that type of VM, we would reconvert its pages to private on a reboot.
This possibly could be solved by resetting the ranges to private when binding with a memslot of certain VM type. But then Google also has a usecase to support intrahost migration where a live VM and associated guest_memfd files are bound to new KVM VM and memslots.
Otherwise, we need an additional contract between userspace/KVM to intercept/handle guest_memfd range reset.
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Hi Vishal,
Quoted 25 lines · Vishal Annapurve
Quoted 15 lines · Fuad Tabba
....
Quoted 14 lines
When rebooting, the memslots may not yet be bound to the
guest_memfd, but we want to reset the guest_memfd's to private. If we useKVM_SET_MEMORY_ATTRIBUTESto convert, we'd be forced to first bind, then convert. If we had a direct ioctl, we don't have this restriction.If we do the conversion via
vcpu_run()we would be forced to handle conversions only with avcpu_run()and only the guest can initiate a conversion.On a guest boot for TDX, the memory is assumed to be private. If the we gave it memory set as shared, we'd just have a bunch of
KVM_EXIT_MEMORY_FAULTsthat slow down boot. Hence on a guest reboot, we will want to reset the guest memory to private.Quoted 7 lines
Quoted 2 lines
We could say the firmware should reset memory to private on guest reboot, but we can't force all guests to update firmware.
Here is where I disagree. I do think that this is the CoCo guest's responsibility (and by guest I include its firmware) to fix its own state after a reboot. How would the host even know that a guest is rebooting if it's a CoCo guest?
Quoted 5 lines
There are a bunch of complexities here, reboot sequence on x86 can be triggered using multiple ways that I don't fully understand, but few of them include reading/writing to "reset register" in MMIO/PCI config space that are emulated by the host userspace directly. Host has to know when the guest is shutting down to manage it's lifecycle.
In that case, I think we need to fully understand these complexities before adding new IOCTLs. It could be that once we understand these issues, we find that we don't need these IOCTLs. It's hard to justify adding an IOCTL for something we don't understand.
Quoted 11 lines
x86 CoCo VM firmwares don't support warm/soft reboot and even if it does in future, guest kernel can choose a different reboot mechanism. So guest reboot needs to be emulated by always starting from scratch. This sequence needs initial guest firmware payload to be installed into private ranges of
guest_memfd.Quoted 3 lines
Either the host doesn't (or cannot even) know that the guest is rebooting, in which case I don't see how having an IOCTL would help.
Host does know that the guest is rebooting.
In that case, that (i.e., the host finding out that the guest is rebooting) could trigger the conversion back to private. No need for an IOCTL.
Quoted 11 lines
Quoted 3 lines
Or somehow the host does know that, i.e., via a hypercall that indicates that. In which case, we could have it so that for that type of VM, we would reconvert its pages to private on a reboot.
This possibly could be solved by resetting the ranges to private when binding with a memslot of certain VM type. But then Google also has a usecase to support intrahost migration where a live VM and associated
guest_memfdfiles are bound to new KVM VM and memslots.Otherwise, we need an additional contract between userspace/KVM to intercept/handle
guest_memfdrange reset.
Then this becomes a migration issue to be solved then, not a huge page support issue. If such IOCTLs are needed for migration, it's too early to add them now.
Cheers,
/fuad
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 35 lines · Fuad Tabba
Hi Vishal,
Quoted 25 lines · Vishal Annapurve
Quoted 15 lines · Fuad Tabba
....
Quoted 14 lines
When rebooting, the memslots may not yet be bound to the
guest_memfd, but we want to reset the guest_memfd's to private. If we useKVM_SET_MEMORY_ATTRIBUTESto convert, we'd be forced to first bind, then convert. If we had a direct ioctl, we don't have this restriction.If we do the conversion via
vcpu_run()we would be forced to handle conversions only with avcpu_run()and only the guest can initiate a conversion.On a guest boot for TDX, the memory is assumed to be private. If the we gave it memory set as shared, we'd just have a bunch of
KVM_EXIT_MEMORY_FAULTsthat slow down boot. Hence on a guest reboot, we will want to reset the guest memory to private.Quoted 7 lines
Quoted 2 lines
We could say the firmware should reset memory to private on guest reboot, but we can't force all guests to update firmware.
Here is where I disagree. I do think that this is the CoCo guest's responsibility (and by guest I include its firmware) to fix its own state after a reboot. How would the host even know that a guest is rebooting if it's a CoCo guest?
Quoted 5 lines
There are a bunch of complexities here, reboot sequence on x86 can be triggered using multiple ways that I don't fully understand, but few of them include reading/writing to "reset register" in MMIO/PCI config space that are emulated by the host userspace directly. Host has to know when the guest is shutting down to manage it's lifecycle.
Quoted 5 lines
In that case, I think we need to fully understand these complexities before adding new IOCTLs. It could be that once we understand these issues, we find that we don't need these IOCTLs. It's hard to justify adding an IOCTL for something we don't understand.
I don't understand all the ways x86 guest can trigger reboot but I do know that x86 CoCo linux guest kernel triggers reset using MMIO/PCI config register write that is emulated by host userspace.
Quoted 7 lines
Quoted 7 lines
x86 CoCo VM firmwares don't support warm/soft reboot and even if it does in future, guest kernel can choose a different reboot mechanism. So guest reboot needs to be emulated by always starting from scratch. This sequence needs initial guest firmware payload to be installed into private ranges of
guest_memfd.Quoted 1 line
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
Either the host doesn't (or cannot even) know that the guest is rebooting, in which case I don't see how having an IOCTL would help.
Host does know that the guest is rebooting.
In that case, that (i.e., the host finding out that the guest is rebooting) could trigger the conversion back to private. No need for an IOCTL.
In the reboot scenarios, it's the host userspace finding out that the guest kernel wants to reboot.
Quoted 10 lines
Quoted 10 lines
Quoted 4 lines
Or somehow the host does know that, i.e., via a hypercall that indicates that. In which case, we could have it so that for that type of VM, we would reconvert its pages to private on a reboot.
This possibly could be solved by resetting the ranges to private when binding with a memslot of certain VM type. But then Google also has a usecase to support intrahost migration where a live VM and associated
guest_memfdfiles are bound to new KVM VM and memslots.
Quoted 6 lines
Quoted 2 lines
Otherwise, we need an additional contract between userspace/KVM to intercept/handle
guest_memfdrange reset.Then this becomes a migration issue to be solved then, not a huge page support issue. If such IOCTLs are needed for migration, it's too early to add them now.
The guest_memfd ioctl is not needed for migration but to change/reset guest_memfd range attributes. I am saying that migration usecase can conflict with some ways that we can solve resetting guest_memfd range attributes without adding a new IOCTL as migration closely resembles reboot scenario as both of them can/need reusing the same guest memory files but one needs to preserve guest memory state.
Reiterating my understanding here, guest memfd ioctl can be used by host userspace to -
1) Change guest memfd range attributes during memory conversion
- This can be handled by KVM hypercall exits in theory as you are
suggesting but Ackerley and me are still thinking that this is a memory operation that goes beyond vcpu scope and will involve interaction with IOMMU backend as well, it's cleaner to have a separate guest memfd specific ioctl for this operation as the impact is even beyond KVM.
2) Reset guest memfd range attributes during guest reboot to allow reusing the same guest memfd files.
- This helps reset the range state to private as needed inline
with initial shared/private configuration chosen at the guest memfd creation.
- This also helps reconstitute all the huge pages back to their
original state that may have gotten split during the runtime of the guest.
This is a host initiated request for guest memfd memory conversion
that we should not be overloading with other KVM interactions in my opinion.
Quoted 3 lines
Cheers,
/fuad
Re: [RFC PATCH v2 36/51] mm: Convert split_folio() macro to function
In reply to Ackerley TngQuoted 1 line · Ackerley Tng
+int
split_folio_to_list(struct folio *folio, struct list_head *list);
With CONFIG_TRANSPARENT_HUGEPAGE=n, I get:
include/linux/huge_mm.h:569:19: error: static declaration of ‘split_folio_to_list’ follows non-static declaration
569 | static inline int split_folio_to_list(struct folio *folio, structlist_head *list)
| ^~~~~~~~~~~~~~~~~~~
include/linux/huge_mm.h:102:5: note: previous declaration of ‘split_folio_to_list’ with type ‘int(struct folio *, struct list_head *)’
102 | int split_folio_to_list(struct folio *folio, struct list_head *list);
Quoted 5 lines
include/linux/huge_mm.h +4
-0+static inline int split_folio (struct folio *folio) +{ +return split_folio_to_list (folio,NULL ); +}
Re: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator
In reply to Ackerley TngQuoted 21 lines · Ackerley Tng
...
virt/kvm/guest_memfd.c +20
-0+/** +* kvm_gmem_zero_range() - Zeroes all sub-pages in range [@start, @end). +* +* @mapping: the filemap to remove this range from. +* @start: index in filemap for start of range (inclusive). +* @end: index in filemap for end of range (exclusive). +* +* The pages in range may be split. truncate_inode_pages_range() isn't the right +* function because it removes pages from the page cache; this function only +* zeroes the pages. +*/ +static void kvm_gmem_zero_range (struct address_space *mapping, +pgoff_t start,pgoff_t end) +{ +struct folio_batch fbatch; + +folio_batch_init (&fbatch); +while (filemap_get_folios (mapping, &start, end -1 , &fbatch)) { +unsigned int i; +
virt/kvm/guest_memfd.c static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode, · line 780
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+for (i =0 ; i <folio_batch_count (&fbatch); ++i) { +struct folio *f; +size_t nr_bytes; + + f = fbatch.folios[i]; + nr_bytes =offset_in_folio (f, end <<PAGE_SHIFT ); +if (nr_bytes ==0 ) + nr_bytes =folio_size (f); + +folio_zero_segment (f,0 , nr_bytes);
folio_zero_segment takes byte offset and number of bytes within the folio. This invocation needs to operate on the folio range that is overlapping with [Start, end) and instead it's always starting from 0 and ending at an unaligned offset within the folio. This will result in zeroing more than requested or lesser than requested or both depending on the request and folio size.
Quoted 7 lines
virt/kvm/guest_memfd.c +7
-0+ } + +folio_batch_release (&fbatch); +cond_resched (); + } +} +
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Vishal AnnapurveHi Vishal,
Quoted 57 lines · Vishal Annapurve
Quoted 35 lines · Fuad Tabba
Hi Vishal,
Quoted 25 lines · Vishal Annapurve
Quoted 15 lines · Fuad Tabba
....
Quoted 14 lines
When rebooting, the memslots may not yet be bound to the
guest_memfd, but we want to reset the guest_memfd's to private. If we useKVM_SET_MEMORY_ATTRIBUTESto convert, we'd be forced to first bind, then convert. If we had a direct ioctl, we don't have this restriction.If we do the conversion via
vcpu_run()we would be forced to handle conversions only with avcpu_run()and only the guest can initiate a conversion.On a guest boot for TDX, the memory is assumed to be private. If the we gave it memory set as shared, we'd just have a bunch of
KVM_EXIT_MEMORY_FAULTsthat slow down boot. Hence on a guest reboot, we will want to reset the guest memory to private.Quoted 7 lines
Quoted 2 lines
We could say the firmware should reset memory to private on guest reboot, but we can't force all guests to update firmware.
Here is where I disagree. I do think that this is the CoCo guest's responsibility (and by guest I include its firmware) to fix its own state after a reboot. How would the host even know that a guest is rebooting if it's a CoCo guest?
Quoted 5 lines
There are a bunch of complexities here, reboot sequence on x86 can be triggered using multiple ways that I don't fully understand, but few of them include reading/writing to "reset register" in MMIO/PCI config space that are emulated by the host userspace directly. Host has to know when the guest is shutting down to manage it's lifecycle.
Quoted 5 lines
In that case, I think we need to fully understand these complexities before adding new IOCTLs. It could be that once we understand these issues, we find that we don't need these IOCTLs. It's hard to justify adding an IOCTL for something we don't understand.
I don't understand all the ways x86 guest can trigger reboot but I do know that x86 CoCo linux guest kernel triggers reset using MMIO/PCI config register write that is emulated by host userspace.
Quoted 10 lines
Quoted 10 lines
x86 CoCo VM firmwares don't support warm/soft reboot and even if it does in future, guest kernel can choose a different reboot mechanism. So guest reboot needs to be emulated by always starting from scratch. This sequence needs initial guest firmware payload to be installed into private ranges of
guest_memfd.Quoted 3 lines
Either the host doesn't (or cannot even) know that the guest is rebooting, in which case I don't see how having an IOCTL would help.
Quoted 8 lines
Quoted 5 lines
Quoted 1 line
Host does know that the guest is rebooting.
In that case, that (i.e., the host finding out that the guest is rebooting) could trigger the conversion back to private. No need for an IOCTL.
In the reboot scenarios, it's the host userspace finding out that the guest kernel wants to reboot.
How does the host userspace find that out? If the host userspace is capable of finding that out, then surely KVM is also capable of finding out the same.
Quoted 24 lines
Quoted 10 lines
Quoted 10 lines
Quoted 4 lines
Or somehow the host does know that, i.e., via a hypercall that indicates that. In which case, we could have it so that for that type of VM, we would reconvert its pages to private on a reboot.
This possibly could be solved by resetting the ranges to private when binding with a memslot of certain VM type. But then Google also has a usecase to support intrahost migration where a live VM and associated
guest_memfdfiles are bound to new KVM VM and memslots.Quoted 6 lines
Quoted 2 lines
Otherwise, we need an additional contract between userspace/KVM to intercept/handle
guest_memfdrange reset.Then this becomes a migration issue to be solved then, not a huge page support issue. If such IOCTLs are needed for migration, it's too early to add them now.
The
guest_memfdioctl is not needed for migration but to change/resetguest_memfdrange attributes. I am saying that migration usecase can conflict with some ways that we can solve resettingguest_memfdrange attributes without adding a new IOCTL as migration closely resembles reboot scenario as both of them can/need reusing the same guest memory files but one needs to preserve guest memory state.
Quoted 9 lines
Reiterating my understanding here, guest memfd ioctl can be used by host userspace to -
1) Change guest memfd range attributes during memory conversion
- This can be handled by KVM hypercall exits in theory as you are
suggesting but Ackerley and me are still thinking that this is a memory operation that goes beyond vcpu scope and will involve interaction with IOMMU backend as well, it's cleaner to have a separate guest memfd specific ioctl for this operation as the impact is even beyond KVM.
The IOMMU backend needs to know about the sharing/unsharing, not trigger it. The memory is the guest's. We already have a mechanism for informing userspace of these kinds of events with KVM exits. This doesn't justify adding a new IOCTL.
Quoted 11 lines
2) Reset guest memfd range attributes during guest reboot to allow reusing the same guest memfd files.
- This helps reset the range state to private as needed inline
with initial shared/private configuration chosen at the guest memfd creation.
- This also helps reconstitute all the huge pages back to their
original state that may have gotten split during the runtime of the guest.
This is a host initiated request for guest memfd memory conversion
that we should not be overloading with other KVM interactions in my opinion.
Then, we could argue about whether we need a "reset" IOCTL (not that I am arguing for that). But still, like I said, if the host becomes aware that the confidential guest is rebooting, then surely KVM can be made aware.
I wonder if this might be better suited for the biweekly guest_memfd sync.
Cheers,
/fuad
Quoted 3 lines
Quoted 3 lines
Cheers,
/fuad
Sean Christopherson
maintainerRe: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 36 lines · Fuad Tabba
Quoted 35 lines · Vishal Annapurve
Quoted 8 lines · Fuad Tabba
Quoted 6 lines · Vishal Annapurve
On Wed, May 21, 2025 at 5:36 AM Fuad Tabba <[email protected]> wrote:
There are a bunch of complexities here, reboot sequence on x86 can be triggered using multiple ways that I don't fully understand, but few of them include reading/writing to "reset register" in MMIO/PCI config space that are emulated by the host userspace directly. Host has to know when the guest is shutting down to manage it's lifecycle.Quoted 5 lines
In that case, I think we need to fully understand these complexities before adding new IOCTLs. It could be that once we understand these issues, we find that we don't need these IOCTLs. It's hard to justify adding an IOCTL for something we don't understand.
I don't understand all the ways x86 guest can trigger reboot but I do know that x86 CoCo linux guest kernel triggers reset using MMIO/PCI config register write that is emulated by host userspace.
Quoted 15 lines
Quoted 11 lines
x86 CoCo VM firmwares don't support warm/soft reboot and even if it does in future, guest kernel can choose a different reboot mechanism. So guest reboot needs to be emulated by always starting from scratch. This sequence needs initial guest firmware payload to be installed into private ranges of
guest_memfd.Quoted 3 lines
Either the host doesn't (or cannot even) know that the guest is rebooting, in which case I don't see how having an IOCTL would help.
Host does know that the guest is rebooting.
In that case, that (i.e., the host finding out that the guest is rebooting) could trigger the conversion back to private. No need for an IOCTL.
Quoted 5 lines
Quoted 2 lines
In the reboot scenarios, it's the host userspace finding out that the guest kernel wants to reboot.
How does the host userspace find that out? If the host userspace is capable of finding that out, then surely KVM is also capable of finding out the same.
Nope, not on x86. Well, not without userspace invoking a new ioctl, which would defeat the purpose of adding these ioctls.
KVM is only responsible for emulating/virtualizing the "CPU". The chipset, e.g. the PCI config space, is fully owned by userspace. KVM doesn't even know whether or not PCI exists for the VM. And reboot may be emulated by simply creating a new KVM instance, i.e. even if KVM was somehow aware of the reboot request, the change in state would happen in an entirely new struct kvm.
That said, Vishal and Ackerley, this patch is a bit lacking on the documentation front. The changelog asserts that:
A guest_memfd ioctl is used because shareability is a property of the memory, and this property should be modifiable independently of the attached struct kvm
but then follows with a very weak and IMO largely irrelevant justification of:
This allows shareability to be modified even if the memory is not yet bound using memslots.
Allowing userspace to change shareability without memslots is one relatively minor flow in one very specific use case.
The real justification for these ioctls is that fundamentally, shareability for in-place conversions is a property of a guest_memfd instance and not a struct kvm instance, and so needs to owned by guest_memfd.
I.e. focus on justifying the change from a design and conceptual perspective, not from a mechanical perspective of a flow that likely's somewhat unique to our specific environment. Y'all are getting deep into the weeds on a random aspect of x86 platform architecture, instead of focusing on the overall design.
The other issue that's likely making this more confusing than it needs to be is that this series is actually two completely different series bundled into one, with very little explanation. Moving shared vs. private ownership into guest_memfd isn't a requirement for 1GiB support, it's a requirement for in-place shared/private conversion in guest_memfd.
For the current guest_memfd implementation, shared vs. private is tracked in the VM via memory attributes, because a guest_memfd instance is *only* private. I.e. shared vs. private is a property of the VM, not of the guest_memfd instance. But when in-place conversion support comes along, ownership of that particular attribute needs to shift to the guest_memfd instance.
I know I gave feedback on earlier posting about there being too series flying around, but shoving two distinct concepts into a single series is not the answer. My complaints about too much noise wasn't that there were multiple series, it was that there was very little coordination and lots of chaos.
If you split this series in two, which should be trivial since you've already organized the patches as a split, then sans the selftests (thank you for those!), in-place conversion support will be its own (much smaller!) series that can focus on that specific aspect of the design, and can provide a cover letter that expounds on the design goals and uAPI.
KVM: guest_memfd: Add CAP KVM_CAP_GMEM_CONVERSION
KVM: Query guest_memfd for private/shared status
KVM: guest_memfd: Skip LRU for guest_memfd folios
KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
KVM: guest_memfd: Introduce and use shareability to guard faulting
KVM: guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodes
And then you can post the 1GiB series separately. So long as you provide pointers to dependencies along with a link to a repo+branch with the kitchen sink, I won't complain about things being too chaotic :-)
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Hi Sean,
Quoted 64 lines · Sean Christopherson
Quoted 36 lines · Fuad Tabba
Quoted 35 lines · Vishal Annapurve
Quoted 8 lines · Fuad Tabba
Quoted 6 lines · Vishal Annapurve
On Wed, May 21, 2025 at 5:36 AM Fuad Tabba <[email protected]> wrote:
There are a bunch of complexities here, reboot sequence on x86 can be triggered using multiple ways that I don't fully understand, but few of them include reading/writing to "reset register" in MMIO/PCI config space that are emulated by the host userspace directly. Host has to know when the guest is shutting down to manage it's lifecycle.Quoted 5 lines
In that case, I think we need to fully understand these complexities before adding new IOCTLs. It could be that once we understand these issues, we find that we don't need these IOCTLs. It's hard to justify adding an IOCTL for something we don't understand.
I don't understand all the ways x86 guest can trigger reboot but I do know that x86 CoCo linux guest kernel triggers reset using MMIO/PCI config register write that is emulated by host userspace.
Quoted 15 lines
Quoted 11 lines
x86 CoCo VM firmwares don't support warm/soft reboot and even if it does in future, guest kernel can choose a different reboot mechanism. So guest reboot needs to be emulated by always starting from scratch. This sequence needs initial guest firmware payload to be installed into private ranges of
guest_memfd.Quoted 3 lines
Either the host doesn't (or cannot even) know that the guest is rebooting, in which case I don't see how having an IOCTL would help.
Host does know that the guest is rebooting.
In that case, that (i.e., the host finding out that the guest is rebooting) could trigger the conversion back to private. No need for an IOCTL.
Quoted 5 lines
Quoted 2 lines
In the reboot scenarios, it's the host userspace finding out that the guest kernel wants to reboot.
How does the host userspace find that out? If the host userspace is capable of finding that out, then surely KVM is also capable of finding out the same.
Nope, not on x86. Well, not without userspace invoking a new ioctl, which would defeat the purpose of adding these ioctls.
KVM is only responsible for emulating/virtualizing the "CPU". The chipset, e.g. the PCI config space, is fully owned by userspace. KVM doesn't even know whether or not PCI exists for the VM. And reboot may be emulated by simply creating a new KVM instance, i.e. even if KVM was somehow aware of the reboot request, the change in state would happen in an entirely new struct kvm.
That said, Vishal and Ackerley, this patch is a bit lacking on the documentation front. The changelog asserts that:
A
guest_memfdioctl is used because shareability is a property of the memory, and this property should be modifiable independently of the attached struct kvmbut then follows with a very weak and IMO largely irrelevant justification of:
This allows shareability to be modified even if the memory is not yet bound using memslots.
Quoted 6 lines
Allowing userspace to change shareability without memslots is one relatively minor flow in one very specific use case.
The real justification for these ioctls is that fundamentally, shareability for in-place conversions is a property of a
guest_memfdinstance and not a struct kvm instance, and so needs to owned byguest_memfd.
Thanks for the clarification Sean. I have a couple of followup questions/comments that you might be able to help with:
From a conceptual point of view, I understand that the in-place conversion is a property of guest_memfd. But that doesn't necessarily mean that the interface between kvm <-> guest_memfd is a userspace IOCTL. We already communicate directly between the two. Other, even less related subsystems within the kernel also interact without going through userspace. Why can't we do the same here? I'm not suggesting it not be owned by guest_memfd, but that we communicate directly.
From a performance point of view, I would expect the common case to be that when KVM gets an unshare request from the guest, it would be able to unmap those pages from the (cooperative) host userspace, and return back to the guest. In this scenario, the host userspace wouldn't even need to be involved. Having a userspace IOCTL as part of this makes that trip unnecessarily longer for the common case.
Cheers,
/fuad
Quoted 38 lines
I.e. focus on justifying the change from a design and conceptual perspective, not from a mechanical perspective of a flow that likely's somewhat unique to our specific environment. Y'all are getting deep into the weeds on a random aspect of x86 platform architecture, instead of focusing on the overall design.
The other issue that's likely making this more confusing than it needs to be is that this series is actually two completely different series bundled into one, with very little explanation. Moving shared vs. private ownership into
guest_memfdisn't a requirement for 1GiB support, it's a requirement for in-place shared/private conversion inguest_memfd.For the current
guest_memfdimplementation, shared vs. private is tracked in the VM via memory attributes, because aguest_memfdinstance is *only* private. I.e. shared vs. private is a property of the VM, not of theguest_memfdinstance. But when in-place conversion support comes along, ownership of that particular attribute needs to shift to theguest_memfdinstance.I know I gave feedback on earlier posting about there being too series flying around, but shoving two distinct concepts into a single series is not the answer. My complaints about too much noise wasn't that there were multiple series, it was that there was very little coordination and lots of chaos.
If you split this series in two, which should be trivial since you've already organized the patches as a split, then sans the selftests (thank you for those!), in-place conversion support will be its own (much smaller!) series that can focus on that specific aspect of the design, and can provide a cover letter that expounds on the design goals and uAPI.
KVM:
guest_memfd: Add CAPKVM_CAP_GMEM_CONVERSION
KVM: Queryguest_memfdfor private/shared status
KVM:guest_memfd: Skip LRU forguest_memfdfolios
KVM:guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
KVM:guest_memfd: Introduce and use shareability to guard faulting
KVM:guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodesAnd then you can post the 1GiB series separately. So long as you provide pointers to dependencies along with a link to a repo+branch with the kitchen sink, I won't complain about things being too chaotic :-)
Sean Christopherson
maintainerRe: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
Quoted 32 lines · Fuad Tabba
Quoted 24 lines · Sean Christopherson
Quoted 2 lines · Fuad Tabba
How does the host userspace find that out? If the host userspace is capable of finding that out, then surely KVM is also capable of finding out the same.
Nope, not on x86. Well, not without userspace invoking a new ioctl, which would defeat the purpose of adding these ioctls.
KVM is only responsible for emulating/virtualizing the "CPU". The chipset, e.g. the PCI config space, is fully owned by userspace. KVM doesn't even know whether or not PCI exists for the VM. And reboot may be emulated by simply creating a new KVM instance, i.e. even if KVM was somehow aware of the reboot request, the change in state would happen in an entirely new struct kvm.
That said, Vishal and Ackerley, this patch is a bit lacking on the documentation front. The changelog asserts that:
A
guest_memfdioctl is used because shareability is a property of the memory, and this property should be modifiable independently of the attached struct kvmbut then follows with a very weak and IMO largely irrelevant justification of:
This allows shareability to be modified even if the memory is not yet bound using memslots.
Quoted 6 lines
Allowing userspace to change shareability without memslots is one relatively minor flow in one very specific use case.
The real justification for these ioctls is that fundamentally, shareability for in-place conversions is a property of a
guest_memfdinstance and not a struct kvm instance, and so needs to owned byguest_memfd.
Quoted 6 lines
Thanks for the clarification Sean. I have a couple of followup questions/comments that you might be able to help with:
From a conceptual point of view, I understand that the in-place conversion is a property of
guest_memfd. But that doesn't necessarily mean that the interface between kvm <->guest_memfdis a userspace IOCTL.
kvm and guest_memfd aren't the communication endpoints for in-place conversions, and more importantly, kvm isn't part of the control plane. kvm's primary role (for guest_memfd with in-place conversions) is to manage the page tables to map memory into the guest.
kvm *may* also explicitly provide a communication channel between the guest and host, e.g. when conversions are initiated via hypercalls, but in some cases the communication channel may be created through pre-existing mechanisms, e.g. a shared memory buffer or emulated I/O (such as the PCI reset case).
guest => kvm (dumb pipe) => userspace => guest_memfd => kvm (invalidate)
And in other cases, kvm might not be in that part of the picture at all, e.g. if the userspace VMM provides an interface to the VM owner (which could also be the user running the VM) to reset the VM, then the flow would look like:
userspace => guest_memfd => kvm (invalidate)
A decent comparison is vCPUs. KVM _could_ route all ioctls through the VM, but that's unpleasant for all parties, as it'd be cumbersome for userspace, and unnecessarily complex and messy for KVM. Similarly, routing guest_memfd state changes through KVM_SET_MEMORY_ATTRIBUTES is awkward from both design and mechanical perspectives.
Even if we disagree on how ugly/pretty routing conversions through kvm would be, which I'll allow is subjective, the bigger problem is that bouncing through KVM_SET_MEMORY_ATTRIBUTES would create an unholy mess of an ABI.
Today, KVM_SET_MEMORY_ATTRIBUTES is handled entirely within kvm, and any changes take effect irrespective of any memslot bindings. And that didn't happen by chance; preserving and enforcing attribute changes independently of memslots was a key design requirement, precisely because memslots are ephemeral to a certain extent.
Adding support for in-place guest_memfd conversion will require new ABI, and so will be a "breaking" change for KVM_SET_MEMORY_ATTRIBUTES no matter what. E.g. KVM will need to reject KVM_MEMORY_ATTRIBUTE_PRIVATE for VMs that elect to use in-place guest_memfd conversions. But very critically, KVM can cripsly enumerate the lack of KVM_MEMORY_ATTRIBUTE_PRIVATE via KVM_CAP_MEMORY_ATTRIBUTES, the behavior will be very straightforward to document (e.g. CAP X is mutually excusive with KVM_MEMORY_ATTRIBUTE_PRIVATE), and it will be opt-in, i.e. won't truly be a breaking change.
If/when we move shareability to guest_memfd, routing state changes through KVM_SET_MEMORY_ATTRIBUTES will gain a subtle dependency on userspace having to create memslots in order for state changes to take effect. That wrinkle would be weird and annoying to document, e.g. "if CAP X is enabled, the ioctl ordering is A => B => C, otherwise the ordering doesn't matter", and would create many more conundrums:
- If a memslot needs to exist in order for KVM_SET_MEMORY_ATTRIBUTES to take effect, what should happen if that memslot is deleted?
- If a memslot isn't found, should KVM_SET_MEMORY_ATTRIBUTES fail and report an error, or silently do nothing?
- If KVM_SET_MEMORY_ATTRIBUTES affects multiple memslots that are bound to multiple guest_memfd, how does KVM guarantee atomicity? What happens if one guest_memfd conversion succeeds, but a later fails?
Quoted 4 lines
We already communicate directly between the two. Other, even less related subsystems within the kernel also interact without going through userspace. Why can't we do the same here? I'm not suggesting it not be owned by
guest_memfd, but that we communicate directly.
I'm not concerned about kvm communicating with guest_memfd, as you note it's all KVM. As above, my concerns are all about KVM's ABI and who owns/controls what.
Quoted 5 lines
From a performance point of view, I would expect the common case to be that when KVM gets an unshare request from the guest, it would be able to unmap those pages from the (cooperative) host userspace, and return back to the guest. In this scenario, the host userspace wouldn't even need to be involved.
Hard NAK, at least from an x86 perspective. Userspace is the sole decision maker with respect to what memory is state of shared vs. private, full stop. The guest can make *requests* to convert memory, but ultimately it's host userspace that decides whether or not to honor the request.
We've litigated this exact issue multiple times. All state changes must be controlled by userspace, because userspace is the only entity that can gracefully handle exceptions and edge cases, and is the only entity with (almost) full knowledge of the system. We can discuss this again if necessary, but I'd much prefer to not rehash all of those conversations.
Quoted 2 lines
Having a userspace IOCTL as part of this makes that trip unnecessarily longer for the common case.
I'm very skeptical that an exit to userspace is going to even be measurable in terms of the cost to convert memory. Conversion is going to require multiple locks, modifications to multiple sets of page tables with all the associated TLB maintenance, possibly cache maintenance, and probably a few other things I'm forgetting. The cost of a few user<=>kernel transitions is likely going to be a drop in the bucket.
If I'm wrong, and there are flows where the user<=>kernel transitions are the long pole, then we could certainly exploring adding a way for userspace to opt into a "fast path" conversion. But it would need to be exactly that, an optional fast path that can fall back to the "slow" userspace-driven conversion as needed.
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Ackerley Tngvirt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349
Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8
-0+ +static pgoff_t kvm_gmem_compute_invalidate_bound (struct inode *inode, +pgoff_t bound,bool start) +{ +size_t nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode))
General comment - It's a bit unfortunate how kvm_gmem_has_custom_allocator() is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic in guest_memfd.c.
Did you consider designing struct guestmem_allocator_operations so that it could encapsulate the special logic for both the existing and new allocators? If it didn't work well, could we expect that a next allocator would actually fit struct guestmem_allocator_operations?
Quoted 23 lines
virt/kvm/guest_memfd.c +23
-0+return bound; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (start) +return round_down (bound, nr_pages); +else +return round_up (bound, nr_pages); +} + +static pgoff_t kvm_gmem_compute_invalidate_start (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, true); +} + +static pgoff_t kvm_gmem_compute_invalidate_end (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, false); +} +
Re: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator
In reply to Ackerley TngQuoted 5 lines · Ackerley Tng
If a custom allocator is requested at
guest_memfdcreation time, pages from the custom allocator will be used to backguest_memfd.Change-Id I59df960b3273790f42fe5bea54a234f40962eb75Signed-off-by Ackerley Tng <[email protected]>
I know it's an RFC, but for future maturity, these logs are pretty thin across the series. Only one sentence for 143 lines is way to limited.
Quoted 27 lines
--- mm/memory.c | 1 + virt/kvm/guest_memfd.c | 142 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 132 insertions(+), 11 deletions(-)mm/memory.c +1
-0@@ -7249,6 +7249,7 @@ void folio_zero_user(struct folio *folio, unsigned long addr_hint)else process_huge_page (addr_hint, nr_pages, clear_subpage, folio); } +EXPORT_SYMBOL_GPL (folio_zero_user); static int copy_user_gigantic_page(struct folio *dst, struct folio *src, unsigned long addr_hint,virt/kvm/guest_memfd.c +1
-1@@ -478,15 +478,13 @@ static inline void kvm_gmem_mark_prepared(struct folio *folio)* leaking host data and the up-to-date flag is set. */ static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, -gfn_t gfn,struct folio *folio) + gfn_t gfn, struct folio *folio,
virt/kvm/guest_memfd.c static inline void kvm_gmem_mark_prepared(struct folio *folio) · line 487
Quoted 10 lines
virt/kvm/guest_memfd.c +2
-4+ unsigned long addr_hint) { -unsigned long nr_pages, i;pgoff_t index;int r; - nr_pages =folio_nr_pages (folio); -for (i =0 ; i < nr_pages; i++) -clear_highpage (folio_page (folio, i)); +folio_zero_user (folio, addr_hint);
This is unrelated cleanup.
Quoted 104 lines
virt/kvm/guest_memfd.c +72
-2/* * Preparing huge folios should always be safe, since it should @@ -554,7 +552,9 @@ static int kvm_gmem_filemap_add_folio(struct address_space *mapping,*/ static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index) { +size_t allocated_size;struct folio *folio; +pgoff_t index_floor;int ret; repeat:@@ -581,8 +581,10 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } } + allocated_size =folio_size (folio); - ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index); + index_floor =round_down (index,folio_nr_pages (folio)); + ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index_floor);if (ret) {folio_put (folio);@@ -598,7 +600,17 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } -__folio_set_locked (folio); +spin_lock (&inode->i_lock); + inode->i_blocks += allocated_size /512 ; +spin_unlock (&inode->i_lock); + +/* +* folio is the one that is allocated, this gets the folio at the +* requested index. +*/ + folio =page_folio (folio_file_page (folio, index)); +folio_lock (folio); +return folio; }@@ -736,6 +748,92 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,spin_unlock (&inode->i_lock); } +/** +* kvm_gmem_zero_range() - Zeroes all sub-pages in range [@start, @end). +* +* @mapping: the filemap to remove this range from. +* @start: index in filemap for start of range (inclusive). +* @end: index in filemap for end of range (exclusive). +* +* The pages in range may be split. truncate_inode_pages_range() isn't the right +* function because it removes pages from the page cache; this function only +* zeroes the pages. +*/ +static void kvm_gmem_zero_range (struct address_space *mapping, +pgoff_t start,pgoff_t end) +{ +struct folio_batch fbatch; + +folio_batch_init (&fbatch); +while (filemap_get_folios (mapping, &start, end -1 , &fbatch)) { +unsigned int i; + +for (i =0 ; i <folio_batch_count (&fbatch); ++i) { +struct folio *f; +size_t nr_bytes; + + f = fbatch.folios[i]; + nr_bytes =offset_in_folio (f, end <<PAGE_SHIFT ); +if (nr_bytes ==0 ) + nr_bytes =folio_size (f); + +folio_zero_segment (f,0 , nr_bytes); + } + +folio_batch_release (&fbatch); +cond_resched (); + } +} + +/** +* kvm_gmem_truncate_inode_range() - Truncate pages in range [@lstart, @lend). +* +* @inode: inode to truncate from. +* @lstart: offset in inode for start of range (inclusive). +* @lend: offset in inode for end of range (exclusive). +* +* Removes full (huge)pages from the filemap and zeroing incomplete +* (huge)pages. The pages in the range may be split. +*/ +static void kvm_gmem_truncate_inode_range (struct inode *inode,loff_t lstart, +loff_t lend) +{ +pgoff_t full_hpage_start; +size_t nr_per_huge_page; +pgoff_t full_hpage_end; +size_t nr_pages; +pgoff_t start; +pgoff_t end;
virt/kvm/guest_memfd.c static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode, · line 816
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+void *priv; + + priv =kvm_gmem_allocator_private (inode); + nr_per_huge_page =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start = lstart >>PAGE_SHIFT ; + end =min (lend,i_size_read (inode)) >>PAGE_SHIFT ; + + full_hpage_start =round_up (start, nr_per_huge_page); + full_hpage_end =round_down (end, nr_per_huge_page);
I think it's supposed to zero the start at a byte granularity.
Quoted 5 lines
virt/kvm/guest_memfd.c +5
-0+ +if (start < full_hpage_start) { +pgoff_t zero_end =min (full_hpage_start, end); + +kvm_gmem_zero_range (inode->i_mapping, start, zero_end);
virt/kvm/guest_memfd.c static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode, · line 831
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ } + +if (full_hpage_end > full_hpage_start) { + nr_pages = full_hpage_end - full_hpage_start; +kvm_gmem_truncate_inode_aligned_pages (inode, full_hpage_start, + nr_pages); + } + +if (end > full_hpage_end && end > full_hpage_start) { +pgoff_t zero_start =max (full_hpage_end, start);
This is weird. Could it just round up end, then check it and use it instead?
Quoted 40 lines
virt/kvm/guest_memfd.c +21
-1+ +kvm_gmem_zero_range (inode->i_mapping, zero_start, end); + } +} +static long kvm_gmem_punch_hole (struct inode *inode,loff_t offset,loff_t len) {struct list_head *gmem_list = &inode->i_mapping->i_private_list;@@ -752,7 +850,12 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_begin (gmem, start, end); -truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 ); +if (kvm_gmem_has_custom_allocator (inode)) { +kvm_gmem_truncate_inode_range (inode, offset, offset + len); + }else { +/* Page size is PAGE_SIZE, so use optimized truncation function. */ +truncate_inode_pages_range (inode->i_mapping, offset, offset + len -1 ); + }list_for_each_entry (gmem, gmem_list, entry)kvm_gmem_invalidate_end (gmem, start, end);@@ -776,6 +879,16 @@ static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len) start = offset >>PAGE_SHIFT ; end = (offset + len) >>PAGE_SHIFT ; +if (kvm_gmem_has_custom_allocator (inode)) { +size_t nr_pages; +void *p; + + p =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (p); + + start =round_down (start, nr_pages); + end =round_down (end, nr_pages); + } r =0 ;for (index = start; index < end; ) {
virt/kvm/guest_memfd.c static struct folio *__kvm_gmem_get_pfn(struct file *file, · line 1686
Quoted 5 lines
virt/kvm/guest_memfd.c +1
-1@@ -1570,7 +1683,7 @@ static struct folio *__kvm_gmem_get_pfn(struct file *file, *pfn =folio_file_pfn (folio, index);if (max_order) - *max_order =0 ; + *max_order =folio_order (folio);
You might be able to have a separate patch that makes existing code work with larger folio sizes. Then add in the custom allocator/truncator bits in another one.
Quoted 5 lines
virt/kvm/guest_memfd.c +0
-0*is_prepared =folio_test_uptodate (folio);return folio;@@ -1597,8 +1710,15 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, goto out;
virt/kvm/guest_memfd.c int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 1718
Quoted 10 lines
virt/kvm/guest_memfd.c +6
-2} -if (!is_prepared) - r =kvm_gmem_prepare_folio (kvm, slot, gfn, folio); +if (!is_prepared) { +/* +* Use the same address as hugetlb for zeroing private pages +* that won't be mapped to userspace anyway. +*/ +unsigned long addr_hint = folio->index <<PAGE_SHIFT ;
This could use some more explanation.
Quoted 6 lines
virt/kvm/guest_memfd.c +3
-0+ + r =kvm_gmem_prepare_folio (kvm, slot, gfn, folio, addr_hint); + }folio_unlock (folio);
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Sean ChristophersonHi Sean,
Quoted 134 lines · Sean Christopherson
Quoted 32 lines · Fuad Tabba
Quoted 24 lines · Sean Christopherson
Quoted 2 lines · Fuad Tabba
How does the host userspace find that out? If the host userspace is capable of finding that out, then surely KVM is also capable of finding out the same.
Nope, not on x86. Well, not without userspace invoking a new ioctl, which would defeat the purpose of adding these ioctls.
KVM is only responsible for emulating/virtualizing the "CPU". The chipset, e.g. the PCI config space, is fully owned by userspace. KVM doesn't even know whether or not PCI exists for the VM. And reboot may be emulated by simply creating a new KVM instance, i.e. even if KVM was somehow aware of the reboot request, the change in state would happen in an entirely new struct kvm.
That said, Vishal and Ackerley, this patch is a bit lacking on the documentation front. The changelog asserts that:
A
guest_memfdioctl is used because shareability is a property of the memory, and this property should be modifiable independently of the attached struct kvmbut then follows with a very weak and IMO largely irrelevant justification of:
This allows shareability to be modified even if the memory is not yet bound using memslots.
Quoted 6 lines
Allowing userspace to change shareability without memslots is one relatively minor flow in one very specific use case.
The real justification for these ioctls is that fundamentally, shareability for in-place conversions is a property of a
guest_memfdinstance and not a struct kvm instance, and so needs to owned byguest_memfd.Quoted 6 lines
Thanks for the clarification Sean. I have a couple of followup questions/comments that you might be able to help with:
From a conceptual point of view, I understand that the in-place conversion is a property of
guest_memfd. But that doesn't necessarily mean that the interface between kvm <->guest_memfdis a userspace IOCTL.kvm and
guest_memfdaren't the communication endpoints for in-place conversions, and more importantly, kvm isn't part of the control plane. kvm's primary role (forguest_memfdwith in-place conversions) is to manage the page tables to map memory into the guest.kvm *may* also explicitly provide a communication channel between the guest and host, e.g. when conversions are initiated via hypercalls, but in some cases the communication channel may be created through pre-existing mechanisms, e.g. a shared memory buffer or emulated I/O (such as the PCI reset case).
guest => kvm (dumb pipe) => userspace =>
guest_memfd=> kvm (invalidate)And in other cases, kvm might not be in that part of the picture at all, e.g. if the userspace VMM provides an interface to the VM owner (which could also be the user running the VM) to reset the VM, then the flow would look like:
userspace =>
guest_memfd=> kvm (invalidate)A decent comparison is vCPUs. KVM _could_ route all ioctls through the VM, but that's unpleasant for all parties, as it'd be cumbersome for userspace, and unnecessarily complex and messy for KVM. Similarly, routing
guest_memfdstate changes throughKVM_SET_MEMORY_ATTRIBUTESis awkward from both design and mechanical perspectives.Even if we disagree on how ugly/pretty routing conversions through kvm would be, which I'll allow is subjective, the bigger problem is that bouncing through
KVM_SET_MEMORY_ATTRIBUTESwould create an unholy mess of an ABI.Today,
KVM_SET_MEMORY_ATTRIBUTESis handled entirely within kvm, and any changes take effect irrespective of any memslot bindings. And that didn't happen by chance; preserving and enforcing attribute changes independently of memslots was a key design requirement, precisely because memslots are ephemeral to a certain extent.Adding support for in-place
guest_memfdconversion will require new ABI, and so will be a "breaking" change forKVM_SET_MEMORY_ATTRIBUTESno matter what. E.g. KVM will need to rejectKVM_MEMORY_ATTRIBUTE_PRIVATEfor VMs that elect to use in-placeguest_memfdconversions. But very critically, KVM can cripsly enumerate the lack ofKVM_MEMORY_ATTRIBUTE_PRIVATEviaKVM_CAP_MEMORY_ATTRIBUTES, the behavior will be very straightforward to document (e.g. CAP X is mutually excusive withKVM_MEMORY_ATTRIBUTE_PRIVATE), and it will be opt-in, i.e. won't truly be a breaking change.If/when we move shareability to
guest_memfd, routing state changes throughKVM_SET_MEMORY_ATTRIBUTESwill gain a subtle dependency on userspace having to create memslots in order for state changes to take effect. That wrinkle would be weird and annoying to document, e.g. "if CAP X is enabled, the ioctl ordering is A => B => C, otherwise the ordering doesn't matter", and would create many more conundrums:- If a memslot needs to exist in order for
KVM_SET_MEMORY_ATTRIBUTESto take effect, what should happen if that memslot is deleted?
- If a memslot isn't found, shouldKVM_SET_MEMORY_ATTRIBUTESfail and report an error, or silently do nothing?
- IfKVM_SET_MEMORY_ATTRIBUTESaffects multiple memslots that are bound to multipleguest_memfd, how does KVM guarantee atomicity? What happens if oneguest_memfdconversion succeeds, but a later fails?Quoted 4 lines
We already communicate directly between the two. Other, even less related subsystems within the kernel also interact without going through userspace. Why can't we do the same here? I'm not suggesting it not be owned by
guest_memfd, but that we communicate directly.I'm not concerned about kvm communicating with
guest_memfd, as you note it's all KVM. As above, my concerns are all about KVM's ABI and who owns/controls what.Quoted 5 lines
From a performance point of view, I would expect the common case to be that when KVM gets an unshare request from the guest, it would be able to unmap those pages from the (cooperative) host userspace, and return back to the guest. In this scenario, the host userspace wouldn't even need to be involved.
Hard NAK, at least from an x86 perspective. Userspace is the sole decision maker with respect to what memory is state of shared vs. private, full stop. The guest can make *requests* to convert memory, but ultimately it's host userspace that decides whether or not to honor the request.
We've litigated this exact issue multiple times. All state changes must be controlled by userspace, because userspace is the only entity that can gracefully handle exceptions and edge cases, and is the only entity with (almost) full knowledge of the system. We can discuss this again if necessary, but I'd much prefer to not rehash all of those conversations.
Quoted 2 lines
Having a userspace IOCTL as part of this makes that trip unnecessarily longer for the common case.
I'm very skeptical that an exit to userspace is going to even be measurable in terms of the cost to convert memory. Conversion is going to require multiple locks, modifications to multiple sets of page tables with all the associated TLB maintenance, possibly cache maintenance, and probably a few other things I'm forgetting. The cost of a few user<=>kernel transitions is likely going to be a drop in the bucket.
Quoted 4 lines
If I'm wrong, and there are flows where the user<=>kernel transitions are the long pole, then we could certainly exploring adding a way for userspace to opt into a "fast path" conversion. But it would need to be exactly that, an optional fast path that can fall back to the "slow" userspace-driven conversion as needed.
Thanks for this very thorough explanation. I know that we have litigated this issue, but not this _exact_ issue. My understanding was that the main reason for using IOCTLs for memory attributes is that userspace needs to manage private and shared memory seperately, including allocation and punching holes where necessary.
That said, no need to discuss this again. If it turns out that user<->kernel transitions are a bottleneck we could look into an opt-in fast path as you said.
Cheers,
/fuad
Re: [RFC PATCH v2 32/51] KVM: guest_memfd: Support guestmem_hugetlb as custom allocator
In reply to Ackerley TngQuoted 10 lines · Ackerley Tng
enum shareability {
virt/kvm/guest_memfd.c +5
-0@@ -40,6 +47,44 @@ static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode)return inode->i_mapping->i_private_data; } +#ifdef CONFIG_KVM_GMEM_HUGETLB + +static const struct guestmem_allocator_operations * +kvm_gmem_allocator_ops (struct inode *inode) +{
virt/kvm/guest_memfd.c static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode) · line 64
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+return kvm_gmem_private (inode)->allocator_ops; +} + +static void *kvm_gmem_allocator_private (struct inode *inode) +{ +return kvm_gmem_private (inode)->allocator_private; +} + +static bool kvm_gmem_has_custom_allocator (struct inode *inode) +{
+ if (!kvm_gmem_private(inode))
+ return NULL;
Quoted 3 lines
virt/kvm/guest_memfd.c +3
-0+return kvm_gmem_allocator_ops (inode) !=NULL ; +} +
...
virt/kvm/guest_memfd.c static void kvm_gmem_destroy_inode(struct inode *inode) · line 1098
Quoted 5 lines
virt/kvm/guest_memfd.c +5
-0+static void kvm_gmem_evict_inode (struct inode *inode) +{ +truncate_inode_pages_final_prepare (inode->i_mapping); + +if (kvm_gmem_has_custom_allocator (inode)) {
The i_private_data of the root inode in pseudo fs is NULL. Without the two lines added above, evicting the root inode during unmount will cause NULL pointer deference.
Quoted 16 lines
virt/kvm/guest_memfd.c +11
-0+size_t nr_pages = inode->i_size >>PAGE_SHIFT ; + +kvm_gmem_truncate_inode_aligned_pages (inode,0 , nr_pages); + }else { +truncate_inode_pages (inode->i_mapping,0 ); + } + +clear_inode (inode); +} +static const struct super_operations kvm_gmem_super_operations = { .statfs = simple_statfs, + .evict_inode = kvm_gmem_evict_inode, .destroy_inode = kvm_gmem_destroy_inode, .free_inode = kvm_gmem_free_inode, };
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ackerley TngQuoted 118 lines · Ackerley Tng
Track
guest_memfdmemory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within
guest_memfdinstead of within KVM, like inkvm->mem_attr_array.
KVM_MEMORY_ATTRIBUTE_PRIVATEinkvm->mem_attr_arraymust still be retained to allow VMs to only useguest_memfdfor private memory and some other memory for shared memory.Not all use cases require
guest_memfd()to be shared with the host when first created. Add a new flag,GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set onKVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.Signed-off-by Ackerley Tng <[email protected]>Co-developed-by Vishal Annapurve <[email protected]>Signed-off-by Vishal Annapurve <[email protected]>Co-developed-by Fuad Tabba <[email protected]>Signed-off-by Fuad Tabba <[email protected]>Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f--- Documentation/virt/kvm/api.rst | 5 ++ include/uapi/linux/kvm.h | 2 + virt/kvm/guest_memfd.c | 124 ++++++++++++++++++++++++++++++++- 3 files changed, 129 insertions(+), 2 deletions(-)Documentation/virt/kvm/api.rst +5
-0@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr. The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs. This is validated when the guest_memfd instance is bound to the VM. +If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field +supports GUEST_MEMFD_FLAG_INIT_PRIVATE. Setting GUEST_MEMFD_FLAG_INIT_PRIVATE +will initialize the memory for the guest_memfd as guest-only and not faultable +by the host. + See KVM_SET_USER_MEMORY_REGION2 for additional details. 4.143 KVM_PRE_FAULT_MEMORYinclude/uapi/linux/kvm.h +2
-0@@ -1567,7 +1567,9 @@ struct kvm_memory_attributes {#define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3)#define KVM_CREATE_GUEST_MEMFD _IOWR(KVMIO, 0xd4, struct kvm_create_guest_memfd) +#define GUEST_MEMFD_FLAG_SUPPORT_SHARED (1UL << 0) +#define GUEST_MEMFD_FLAG_INIT_PRIVATE (1UL << 1)struct kvm_create_guest_memfd {__u64 size;virt/kvm/guest_memfd.c +34
-0@@ -4,6 +4,7 @@#include <linux/falloc.h> #include <linux/fs.h> #include <linux/kvm_host.h> +#include <linux/maple_tree.h> #include <linux/pseudo_fs.h> #include <linux/pagemap.h> @@ -17,6 +18,24 @@ struct kvm_gmem {struct list_head entry; }; +struct kvm_gmem_inode_private { +#ifdef CONFIG_KVM_GMEM_SHARED_MEM +struct maple_tree shareability; +#endif +}; + +enum shareability { +SHAREABILITY_GUEST =1 ,/* Only the guest can map (fault) folios in this range. */ +SHAREABILITY_ALL =2 ,/* Both guest and host can fault folios in this range. */ +}; + +static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index); + +static struct kvm_gmem_inode_private *kvm_gmem_private (struct inode *inode) +{ +return inode->i_mapping->i_private_data; +} +/** * folio_file_pfn - like folio_file_page, but return a pfn. * @folio: The folio which contains this index. @@ -29,6 +48,58 @@ static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index)return folio_pfn (folio) + (index & (folio_nr_pages (folio) -1 )); } +#ifdef CONFIG_KVM_GMEM_SHARED_MEM + +static int kvm_gmem_shareability_setup (struct kvm_gmem_inode_private *private, +loff_t size,u64 flags) +{ +enum shareability m; +pgoff_t last; + + last = (size >>PAGE_SHIFT ) -1 ; + m = flags &GUEST_MEMFD_FLAG_INIT_PRIVATE ?SHAREABILITY_GUEST : +SHAREABILITY_ALL ; +return mtree_store_range (&private->shareability,0 , last,xa_mk_value (m), +GFP_KERNEL ); +} +
virt/kvm/guest_memfd.c static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 75
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+static enum shareability kvm_gmem_shareability_get (struct inode *inode, +pgoff_t index) +{ +struct maple_tree *mt; +void *entry; + + mt = &kvm_gmem_private (inode)->shareability; + entry =mtree_load (mt, index); +WARN (!entry, +"Shareability should always be defined for all indices in inode." );
I noticed that in [1], the kvm_gmem_mmap() does not check the range. So, the WARN() here can be hit when userspace mmap() an area larger than the inode size and accesses the out of band HVA.
Maybe limit the mmap() range?
@@ -1609,6 +1620,10 @@ static int kvm_gmem_mmap(struct file *file, struct vm_area_struct *vma)
if (!kvm_gmem_supports_shared(file_inode(file)))
return -ENODEV;+ if (vma->vm_end - vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT) > i_size_read(file_inode(file)))
+ return -EINVAL;
+
if ((vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) !=
(VM_SHARED | VM_MAYSHARE)) {
return -EINVAL;Quoted 80 lines
virt/kvm/guest_memfd.c +54
-1+return xa_to_value (entry); +} + +static struct folio *kvm_gmem_get_shared_folio (struct inode *inode,pgoff_t index) +{ +if (kvm_gmem_shareability_get (inode, index) !=SHAREABILITY_ALL ) +return ERR_PTR (-EACCES ); + +return kvm_gmem_get_folio (inode, index); +} + +#else + +static int kvm_gmem_shareability_setup (struct maple_tree *mt,loff_t size,u64 flags) +{ +return 0 ; +} + +static inline struct folio *kvm_gmem_get_shared_folio (struct inode *inode,pgoff_t index) +{ + WARN_ONCE("Unexpected call to get shared folio.") +return NULL ; +} + +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ +static int __kvm_gmem_prepare_folio (struct kvm *kvm,struct kvm_memory_slot *slot,pgoff_t index,struct folio *folio) {@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)filemap_invalidate_lock_shared (inode->i_mapping); - folio =kvm_gmem_get_folio (inode, vmf->pgoff); + folio =kvm_gmem_get_shared_folio (inode, vmf->pgoff);if (IS_ERR (folio)) {int err =PTR_ERR (folio);@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = { .fallocate = kvm_gmem_fallocate, }; +static void kvm_gmem_free_inode (struct inode *inode) +{ +struct kvm_gmem_inode_private *private =kvm_gmem_private (inode); + +kfree (private); + +free_inode_nonrcu (inode); +} + +static void kvm_gmem_destroy_inode (struct inode *inode) +{ +struct kvm_gmem_inode_private *private =kvm_gmem_private (inode); + +#ifdef CONFIG_KVM_GMEM_SHARED_MEM +/* +* mtree_destroy() can't be used within rcu callback, hence can't be +* done in ->free_inode(). +*/ +if (private) +mtree_destroy (&private->shareability); +#endif +} +static const struct super_operations kvm_gmem_super_operations = { .statfs = simple_statfs, + .destroy_inode = kvm_gmem_destroy_inode, + .free_inode = kvm_gmem_free_inode, };static int kvm_gmem_init_fs_context (struct fs_context *fc)@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {static struct inode *kvm_gmem_inode_make_secure_inode (const char *name,loff_t size,u64 flags) { +struct kvm_gmem_inode_private *private;struct inode *inode; +int err;
virt/kvm/guest_memfd.c static const struct inode_operations kvm_gmem_iops = { · line 661
Quoted 10 lines
virt/kvm/guest_memfd.c +6
-0inode =alloc_anon_secure_inode (kvm_gmem_mnt->mnt_sb, name);if (IS_ERR (inode))return inode; + err = -ENOMEM ; + private =kzalloc (sizeof (*private),GFP_KERNEL ); +if (!private) + goto out; + +mt_init (&private->shareability);
Wrap the mt_init() inside "#ifdef CONFIG_KVM_GMEM_SHARED_MEM" ?
Quoted 54 lines
virt/kvm/guest_memfd.c +17
-1+ inode->i_mapping->i_private_data = private; + + err =kvm_gmem_shareability_setup (private, size, flags); +if (err) + goto out; + inode->i_private = (void *)(unsigned long )flags; inode->i_op = &kvm_gmem_iops; inode->i_mapping->a_ops = &kvm_gmem_aops;@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,WARN_ON_ONCE (!mapping_unevictable (inode->i_mapping));return inode; + +out: +iput (inode); + +return ERR_PTR (err); } static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)if (kvm_arch_vm_supports_gmem_shared_mem (kvm)) valid_flags |=GUEST_MEMFD_FLAG_SUPPORT_SHARED ; +if (flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED ) + valid_flags |=GUEST_MEMFD_FLAG_INIT_PRIVATE ; +if (flags & ~valid_flags)return -EINVAL ;@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,if (!file)return -EFAULT ; +filemap_invalidate_lock_shared (file_inode (file)->i_mapping); + folio =__kvm_gmem_get_pfn (file, slot, index, pfn, &is_prepared, max_order);if (IS_ERR (folio)) { r =PTR_ERR (folio);@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, *page =folio_file_page (folio, index); elsefolio_put (folio ); - out: +filemap_invalidate_unlock_shared (file_inode (file)->i_mapping);fput (file);return r; }Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 06/51] KVM: Query guest_memfd for private/shared status
In reply to Ackerley TngQuoted 47 lines · Ackerley Tng
Query
guest_memfdfor private/shared status if thoseguest_memfdstrack private/shared status.With this patch, Coco VMs can use
guest_memfdfor both shared and private memory. If Coco VMs choose to useguest_memfdfor both shared and private memory, by creatingguest_memfdwith theGUEST_MEMFD_FLAG_SUPPORT_SHAREDflag,guest_memfdwill be used to provide the private/shared status of the memory, instead ofkvm->mem_attr_array.Change-Id I8f23d7995c12242aa4e09ccf5ec19360e9c9ed83Signed-off-by Ackerley Tng <[email protected]>--- include/linux/kvm_host.h | 19 ++++++++++++------- virt/kvm/guest_memfd.c | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-)include/linux/kvm_host.h +10
-0@@ -2508,12 +2508,22 @@ static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu, }#ifdef CONFIG_KVM_GMEM_SHARED_MEM +bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot); +bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn); +#else +static inline bool kvm_gmem_memslot_supports_shared (const struct kvm_memory_slot *slot) {return false; } + +static inline bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn) +{ +return false; +} +#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES @@ -2544,13 +2554,8 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)return false;
include/linux/kvm_host.h static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn) · line 2558
Quoted 10 lines
include/linux/kvm_host.h +2
-7slot =gfn_to_memslot (kvm, gfn); -if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) { -/* -* For now, memslots only support in-place shared memory if the -* host is allowed to mmap memory (i.e., non-Coco VMs). -*/ -return false; - } +if (kvm_slot_has_gmem (slot) &&kvm_gmem_memslot_supports_shared (slot)) +return kvm_gmem_is_private (slot, gfn);
When userspace gets an exit reason KVM_EXIT_MEMORY_FAULT, looks it needs to update both KVM memory attribute and gmem shareability, via two separate ioctls?
Quoted 39 lines
include/linux/kvm_host.h +0
-0return kvm_get_memory_attributes (kvm, gfn) &KVM_MEMORY_ATTRIBUTE_PRIVATE ; }virt/kvm/guest_memfd.c +22
-0@@ -865,6 +865,28 @@ bool kvm_gmem_memslot_supports_shared(const struct kvm_memory_slot *slot) }EXPORT_SYMBOL_GPL (kvm_gmem_memslot_supports_shared); +bool kvm_gmem_is_private (struct kvm_memory_slot *slot,gfn_t gfn) +{ +struct inode *inode; +struct file *file; +pgoff_t index; +bool ret; + + file =kvm_gmem_get_file (slot); +if (!file) +return false; + + index =kvm_gmem_get_index (slot, gfn); + inode =file_inode (file); + +filemap_invalidate_lock_shared (inode->i_mapping); + ret =kvm_gmem_shareability_get (inode, index) ==SHAREABILITY_GUEST ; +filemap_invalidate_unlock_shared (inode->i_mapping); + +fput (file); +return ret; +} +#else #define kvm_gmem_mmap NULL#endif /* CONFIG_KVM_GMEM_SHARED_MEM */ Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Ackerley TngQuoted 206 lines · Ackerley Tng
In this patch, newly allocated pages are split to 4K regular pages before providing them to the requester (
fallocate()or KVM).During a private to shared conversion, folios are split if not already split.
During a shared to private conversion, folios are merged if not already merged.
When the folios are removed from the filemap on truncation, the allocator is given a chance to do any necessary prep for when the folio is freed.
When a conversion is requested on a subfolio within a hugepage range, faulting must be prevented on the whole hugepage range for correctness.
See related discussion at
https://lore.kernel.org/all/[email protected]/T/Signed-off-by Ackerley Tng <[email protected]>Co-developed-by Vishal Annapurve <[email protected]>Signed-off-by Vishal Annapurve <[email protected]>Change-Id Ib5ee22e3dae034c529773048a626ad98d4b10af3--- mm/filemap.c | 2 + virt/kvm/guest_memfd.c | 501 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 483 insertions(+), 20 deletions(-)mm/filemap.c +2
-0@@ -223,6 +223,7 @@ void __filemap_remove_folio(struct folio *folio, void *shadow)filemap_unaccount_folio (mapping, folio);page_cache_delete (mapping, folio, shadow); } +EXPORT_SYMBOL_GPL (__filemap_remove_folio);void filemap_free_folio (struct address_space *mapping,struct folio *folio) {@@ -258,6 +259,7 @@ void filemap_remove_folio(struct folio *folio)filemap_free_folio (mapping, folio); } +EXPORT_SYMBOL_GPL (filemap_remove_folio);/* * page_cache_delete_batch - delete several folios from page cache virt/kvm/guest_memfd.c +128
-0@@ -41,6 +41,11 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start, pgoff_t end);static void kvm_gmem_invalidate_end (struct kvm_gmem *gmem,pgoff_t start,pgoff_t end); +static int __kvm_gmem_filemap_add_folio (struct address_space *mapping, +struct folio *folio,pgoff_t index); +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation);static struct kvm_gmem_inode_private *kvm_gmem_private (struct inode *inode) {@@ -126,6 +131,31 @@ static enum shareability kvm_gmem_shareability_get(struct inode *inode,return xa_to_value (entry); } +static bool kvm_gmem_shareability_in_range (struct inode *inode,pgoff_t start, +size_t nr_pages,enum shareability m) +{ +struct maple_tree *mt; +pgoff_t last; +void *entry; + + mt = &kvm_gmem_private (inode)->shareability; + + last = start + nr_pages -1 ; +mt_for_each (mt, entry, start, last) { +if (xa_to_value (entry) == m) +return true; + } + +return false; +} + +static inline bool kvm_gmem_has_some_shared (struct inode *inode,pgoff_t start, +size_t nr_pages) +{ +return kvm_gmem_shareability_in_range (inode, start, nr_pages, +SHAREABILITY_ALL ); +} +static struct folio *kvm_gmem_get_shared_folio (struct inode *inode,pgoff_t index) {if (kvm_gmem_shareability_get (inode, index) !=SHAREABILITY_ALL )@@ -241,6 +271,105 @@ static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t streturn refcount_safe; } +static void kvm_gmem_unmap_private (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end) +{ +struct kvm_memory_slot *slot; +struct kvm *kvm = gmem->kvm; +unsigned long index; +bool locked = false; +bool flush = false; + +xa_for_each_range (&gmem->bindings, index, slot, start, end -1 ) { +pgoff_t pgoff = slot->gmem.pgoff; + +struct kvm_gfn_range gfn_range = { + .start = slot->base_gfn +max (pgoff, start) - pgoff, + .end = slot->base_gfn +min (pgoff + slot->npages, end) - pgoff, + .slot = slot, + .may_block = true, +/* This function is only concerned with private mappings. */ + .attr_filter =KVM_FILTER_PRIVATE , + }; + +if (!locked) { +KVM_MMU_LOCK (kvm); + locked = true; + } + + flush |=kvm_mmu_unmap_gfn_range (kvm, &gfn_range); + } + +if (flush) +kvm_flush_remote_tlbs (kvm); + +if (locked) +KVM_MMU_UNLOCK (kvm); +} + +static void kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, +pgoff_t end) +{ +struct kvm_memory_slot *slot; +struct kvm *kvm = gmem->kvm; +unsigned long index; +bool found_memslot; + + found_memslot = false; +xa_for_each_range (&gmem->bindings, index, slot, start, end -1 ) { +gfn_t gfn_start; +gfn_t gfn_end; +pgoff_t pgoff; + + pgoff = slot->gmem.pgoff; + + gfn_start = slot->base_gfn +max (pgoff, start) - pgoff; + gfn_end = slot->base_gfn +min (pgoff + slot->npages, end) - pgoff; +if (!found_memslot) { + found_memslot = true; + +KVM_MMU_LOCK (kvm); +kvm_mmu_invalidate_begin (kvm); + } + +kvm_mmu_invalidate_range_add (kvm, gfn_start, gfn_end); + } + +if (found_memslot) +KVM_MMU_UNLOCK (kvm); +} + +static pgoff_t kvm_gmem_compute_invalidate_bound (struct inode *inode, +pgoff_t bound,bool start) +{ +size_t nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return bound; + + priv =kvm_gmem_allocator_private (inode); + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (start) +return round_down (bound, nr_pages); +else +return round_up (bound, nr_pages); +} + +static pgoff_t kvm_gmem_compute_invalidate_start (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, true); +} + +static pgoff_t kvm_gmem_compute_invalidate_end (struct inode *inode, +pgoff_t bound) +{ +return kvm_gmem_compute_invalidate_bound (inode, bound, false); +} +static int kvm_gmem_shareability_apply (struct inode *inode,struct conversion_work *work,enum shareability m)@@ -299,35 +428,53 @@ static void kvm_gmem_convert_invalidate_begin(struct inode *inode, struct conversion_work *work) {struct list_head *gmem_list;
virt/kvm/guest_memfd.c static void kvm_gmem_convert_invalidate_begin(struct inode *inode, · line 438
Quoted 10 lines
virt/kvm/guest_memfd.c +6
-2+pgoff_t invalidate_start; +pgoff_t invalidate_end;struct kvm_gmem *gmem; -pgoff_t end; +pgoff_t work_end; - end = work->start + work->nr_pages; + work_end = work->start + work->nr_pages; + invalidate_start =kvm_gmem_compute_invalidate_start (inode, work->start); + invalidate_end =kvm_gmem_compute_invalidate_end (inode, work_end);
Could we just notify the exact gfn range and let KVM adjust the invalidate range?
Then kvm_gmem_invalidate_begin() can asks KVM to do EPT splitting before any kvm_mmu_unmap_gfn_range() is performed.
Quoted 211 lines
virt/kvm/guest_memfd.c +154
-9gmem_list = &inode->i_mapping->i_private_list;list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_begin (gmem, work->start, end); +kvm_gmem_invalidate_begin (gmem, invalidate_start, invalidate_end); }static void kvm_gmem_convert_invalidate_end (struct inode *inode,struct conversion_work *work) {struct list_head *gmem_list; +pgoff_t invalidate_start; +pgoff_t invalidate_end;struct kvm_gmem *gmem; -pgoff_t end; +pgoff_t work_end; - end = work->start + work->nr_pages; + work_end = work->start + work->nr_pages; + invalidate_start =kvm_gmem_compute_invalidate_start (inode, work->start); + invalidate_end =kvm_gmem_compute_invalidate_end (inode, work_end); gmem_list = &inode->i_mapping->i_private_list;list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_end (gmem, work->start, end); +kvm_gmem_invalidate_end (gmem, invalidate_start, invalidate_end); }static int kvm_gmem_convert_should_proceed (struct inode *inode,struct conversion_work *work,bool to_shared,pgoff_t *error_index) { -if (!to_shared) { +if (to_shared) { +struct list_head *gmem_list; +struct kvm_gmem *gmem; +pgoff_t work_end; + + work_end = work->start + work->nr_pages; + + gmem_list = &inode->i_mapping->i_private_list; +list_for_each_entry (gmem, gmem_list, entry) +kvm_gmem_unmap_private (gmem, work->start, work_end); + }else {unmap_mapping_pages (inode->i_mapping, work->start, work->nr_pages, false);@@ -340,6 +487,27 @@ static int kvm_gmem_convert_should_proceed(struct inode *inode,return 0 ; } +static int kvm_gmem_convert_execute_work (struct inode *inode, +struct conversion_work *work, +bool to_shared) +{ +enum shareability m; +int ret; + + m = to_shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +return ret; +/* +* Apply shareability first so split/merge can operate on new +* shareability state. +*/ + ret =kvm_gmem_restructure_folios_in_range ( + inode, work->start, work->nr_pages, to_shared); + +return ret; +} +static int kvm_gmem_convert_range (struct file *file,pgoff_t start,size_t nr_pages,bool shared,pgoff_t *error_index)@@ -371,18 +539,21 @@ static int kvm_gmem_convert_range(struct file *file, pgoff_t start,list_for_each_entry (work, &work_list, list) { rollback_stop_item = work; - ret =kvm_gmem_shareability_apply (inode, work, m); + + ret =kvm_gmem_convert_execute_work (inode, work, shared);if (ret)break ; }if (ret) { - m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ;list_for_each_entry (work, &work_list, list) { +int r; + + r =kvm_gmem_convert_execute_work (inode, work, !shared); +WARN_ON (r); +if (work == rollback_stop_item)break ; - -WARN_ON (kvm_gmem_shareability_apply (inode, work, m)); } }@@ -434,6 +605,277 @@ static int kvm_gmem_ioctl_convert_range(struct file *file,return ret; } +#ifdef CONFIG_KVM_GMEM_HUGETLB + +static inline void __filemap_remove_folio_for_restructuring (struct folio *folio) +{ +struct address_space *mapping = folio->mapping; + +spin_lock (&mapping->host->i_lock); +xa_lock_irq (&mapping->i_pages); + +__filemap_remove_folio (folio,NULL ); + +xa_unlock_irq (&mapping->i_pages); +spin_unlock (&mapping->host->i_lock); +} + +/** +* filemap_remove_folio_for_restructuring() - Remove @folio from filemap for +* split/merge. +* +* @folio: the folio to be removed. +* +* Similar to filemap_remove_folio(), but skips LRU-related calls (meaningless +* for guest_memfd), and skips call to ->free_folio() to maintain folio flags. +* +* Context: Expects only the filemap's refcounts to be left on the folio. Will +* freeze these refcounts away so that no other users will interfere +* with restructuring. +*/ +static inline void filemap_remove_folio_for_restructuring (struct folio *folio) +{ +int filemap_refcount; + + filemap_refcount =folio_nr_pages (folio); +while (!folio_ref_freeze (folio, filemap_refcount)) { +/* +* At this point only filemap refcounts are expected, hence okay +* to spin until speculative refcounts go away. +*/ +WARN_ONCE (1 ,"Spinning on folio=%p refcount=%d" , folio,folio_ref_count (folio)); + } + +folio_lock (folio); +__filemap_remove_folio_for_restructuring (folio); +folio_unlock (folio); +} + +/** +* kvm_gmem_split_folio_in_filemap() - Split @folio within filemap in @inode. +* +* @inode: inode containing the folio. +* @folio: folio to be split. +* +* Split a folio into folios of size PAGE_SIZE. Will clean up folio from filemap +* and add back the split folios. +* +* Context: Expects that before this call, folio's refcount is just the +* filemap's refcounts. After this function returns, the split folios' +* refcounts will also be filemap's refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_split_folio_in_filemap (struct inode *inode,struct folio *folio) +{ +size_t orig_nr_pages; +pgoff_t orig_index; +size_t i, j; +int ret; + + orig_nr_pages =folio_nr_pages (folio); +if (orig_nr_pages ==1 ) +return 0 ; + + orig_index = folio->index; + +filemap_remove_folio_for_restructuring (folio); + + ret =kvm_gmem_allocator_ops (inode)->split_folio (folio); +if (ret) + goto err; + +for (i =0 ; i < orig_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (folio, i)); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, f, + orig_index + i); +if (ret) + goto rollback; + } + +return ret; + +rollback: +for (j =0 ; j < i; ++j) { +struct folio *f =page_folio (folio_page (folio, j)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (folio); +err: +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, folio, orig_index)); + +return ret; +} + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 724
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+size_t to_nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); + +if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages))
If the guest_memfd is configured with GUESTMEM_HUGETLB_FLAG_1GB, it seems that whenever there's a shared page within a 1GB range, the folio will always be split into 4KB folios. Is it good?
Quoted 99 lines
virt/kvm/guest_memfd.c +99
-0+return kvm_gmem_split_folio_in_filemap (inode, folio); + +return 0 ; +} + +/** +* kvm_gmem_merge_folio_in_filemap() - Merge @first_folio within filemap in +* @inode. +* +* @inode: inode containing the folio. +* @first_folio: first folio among folios to be merged. +* +* Will clean up subfolios from filemap and add back the merged folio. +* +* Context: Expects that before this call, all subfolios only have filemap +* refcounts. After this function returns, the merged folio will only +* have filemap refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +pgoff_t index; +void *priv; +size_t i; +int ret; + + index = first_folio->index; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); +if (folio_nr_pages (first_folio) == to_nr_pages) +return 0 ; + +for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (first_folio); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, first_folio, index); +if (ret) + goto err_split; + +return ret; + +err_split: +WARN_ON (kvm_gmem_allocator_ops (inode)->split_folio (first_folio)); +for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, f, index + i)); + } + +return ret; +} + +static inline int kvm_gmem_try_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (kvm_gmem_has_some_shared (inode, first_folio->index, to_nr_pages)) +return 0 ; + +return kvm_gmem_merge_folio_in_filemap (inode, first_folio); +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +size_t to_nr_pages; +pgoff_t index; +pgoff_t end; +void *priv; +int ret; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + end = start + nr_pages; + +/* Round to allocator page size, to check all (huge) pages in range. */ + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start =round_down (start, to_nr_pages); + end =round_up (end, to_nr_pages); + +for (index = start; index < end; index += to_nr_pages) { +struct folio *f;
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) + ret =kvm_gmem_split_folio_in_filemap (inode, f);
The split operation is performed after kvm_gmem_unmap_private() within kvm_gmem_convert_should_proceed(), right?
So, it seems that that it's not necessary for TDX to avoid holding private page references, as TDX must have released the page refs after kvm_gmem_unmap_private() (except when there's TDX module or KVM bug).
Quoted 155 lines
virt/kvm/guest_memfd.c +73
-9+ else + ret =kvm_gmem_try_merge_folio_in_filemap (inode, f); + +if (ret) + goto rollback; + } +return ret; + +rollback: +for (index -= to_nr_pages; index >= start; index -= to_nr_pages) { +struct folio *f; + + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); +else +WARN_ON (kvm_gmem_split_folio_in_filemap (inode, f)); + } + +return ret; +} + +#else + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +return 0 ; +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +return 0 ; +} + +#endif +#else static int kvm_gmem_shareability_setup (struct maple_tree *mt,loff_t size,u64 flags)@@ -563,11 +1005,16 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return folio;if (kvm_gmem_has_custom_allocator (inode)) { -void *p =kvm_gmem_allocator_private (inode); +size_t nr_pages; +void *p; + p =kvm_gmem_allocator_private (inode); folio =kvm_gmem_allocator_ops (inode)->alloc_folio (p);if (IS_ERR (folio))return folio; + + nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (p); + index_floor =round_down (index, nr_pages); }else {gfp_t gfp =mapping_gfp_mask (inode->i_mapping);@@ -580,10 +1027,11 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)folio_put (folio);return ERR_PTR (ret); } + + index_floor = index; } allocated_size =folio_size (folio); - index_floor =round_down (index,folio_nr_pages (folio)); ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index_floor);if (ret) {folio_put (folio);@@ -600,6 +1048,13 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)return ERR_PTR (ret); } +/* Leave just filemap's refcounts on folio. */ +folio_put (folio); + + ret =kvm_gmem_try_split_folio_in_filemap (inode, folio); +if (ret) + goto err; +spin_lock (&inode->i_lock); inode->i_blocks += allocated_size /512 ;spin_unlock (&inode->i_lock);@@ -608,14 +1063,17 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)* folio is the one that is allocated, this gets the folio at the * requested index. */ - folio =page_folio (folio_file_page (folio, index)); -folio_lock (folio); + folio =filemap_lock_folio (inode->i_mapping, index);return folio; + +err: +filemap_remove_folio (folio); +return ERR_PTR (ret); } -static void kvm_gmem_invalidate_begin (struct kvm_gmem *gmem,pgoff_t start, -pgoff_t end) +static void kvm_gmem_invalidate_begin_and_zap (struct kvm_gmem *gmem, +pgoff_t start,pgoff_t end) {bool flush = false, found_memslot = false;struct kvm_memory_slot *slot;@@ -848,7 +1306,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)filemap_invalidate_lock (inode->i_mapping);list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_begin (gmem, start, end); +kvm_gmem_invalidate_begin_and_zap (gmem, start, end);if (kvm_gmem_has_custom_allocator (inode)) {kvm_gmem_truncate_inode_range (inode, offset, offset + len);@@ -978,7 +1436,7 @@ static int kvm_gmem_release(struct inode *inode, struct file *file)* Zap all SPTEs pointed at by this file. Do not free the backing * memory, as its lifetime is associated with the inode, not the file. */ -kvm_gmem_invalidate_begin (gmem,0 ,-1ul ); +kvm_gmem_invalidate_begin_and_zap (gmem,0 ,-1ul );kvm_gmem_invalidate_end (gmem,0 ,-1ul );list_del (&gmem->entry);@@ -1289,7 +1747,7 @@ static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol end = start +folio_nr_pages (folio);list_for_each_entry (gmem, gmem_list, entry) -kvm_gmem_invalidate_begin (gmem, start, end); +kvm_gmem_invalidate_begin_and_zap (gmem, start, end);/* * Do not truncate the range, what action is taken in response to the @@ -1330,6 +1788,9 @@ static void kvm_gmem_free_folio(struct address_space *mapping,*/ folio_clear_uptodate (folio); +if (kvm_gmem_has_custom_allocator (mapping->host)) +kvm_gmem_allocator_ops (mapping->host)->free_folio (folio); +kvm_gmem_invalidate (folio); }Signature · 1 line
2.49.0.1045.g170613ef41-goog
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
Quoted 37 lines
Quoted 24 lines
virt/kvm/guest_memfd.c +24
-0+static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +size_t to_nr_pages; +pgoff_t index; +pgoff_t end; +void *priv; +int ret; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + end = start + nr_pages; + +/* Round to allocator page size, to check all (huge) pages in range. */ + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start =round_down (start, to_nr_pages); + end =round_up (end, to_nr_pages); + +for (index = start; index < end; index += to_nr_pages) { +struct folio *f;virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) + ret =kvm_gmem_split_folio_in_filemap (inode, f);The split operation is performed after
kvm_gmem_unmap_private()withinkvm_gmem_convert_should_proceed(), right?
Quoted 3 lines
So, it seems that that it's not necessary for TDX to avoid holding private page references, as TDX must have released the page refs after
kvm_gmem_unmap_private()(except when there's TDX module or KVM bug).
Oops. Please ignore this one.
The unmap does not necessarily cover the entire folio range, so split still requires TDX not to hold ref count.
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
In reply to Ackerley TngQuoted 37 lines · Ackerley Tng
Track
guest_memfdmemory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within
guest_memfdinstead of within KVM, like inkvm->mem_attr_array.
KVM_MEMORY_ATTRIBUTE_PRIVATEinkvm->mem_attr_arraymust still be retained to allow VMs to only useguest_memfdfor private memory and some other memory for shared memory.Not all use cases require
guest_memfd()to be shared with the host when first created. Add a new flag,GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set onKVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.Signed-off-by Ackerley Tng <[email protected]>Co-developed-by Vishal Annapurve <[email protected]>Signed-off-by Vishal Annapurve <[email protected]>Co-developed-by Fuad Tabba <[email protected]>Signed-off-by Fuad Tabba <[email protected]>Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f--- Documentation/virt/kvm/api.rst | 5 ++ include/uapi/linux/kvm.h | 2 + virt/kvm/guest_memfd.c | 124 ++++++++++++++++++++++++++++++++- 3 files changed, 129 insertions(+), 2 deletions(-)Documentation/virt/kvm/api.rst +0
-0
Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6412
Quoted 5 lines
Documentation/virt/kvm/api.rst +2
-0@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr. The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs. This is validated when the guest_memfd instance is bound to the VM. +If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field +supports GUEST_MEMFD_FLAG_INIT_PRIVATE.
It seems that the sentence is stale?
Didn't find the definition of KVM_CAP_GMEM_CONVERSIONS.
Quoted 4 lines
Setting
GUEST_MEMFD_FLAG_INIT_PRIVATEDocumentation/virt/kvm/api.rst +3
-0+will initialize the memory for the guest_memfd as guest-only and not faultable +by the host. +
[...]
Quoted 10 lines
static int
kvm_gmem_init_fs_context(struct fs_context *fc)Documentation/virt/kvm/api.rst +2
-0@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = { static struct inode *kvm_gmem_inode_make_secure_inode(const char *name, loff_t size, u64 flags) { + struct kvm_gmem_inode_private *private; struct inode *inode; + int err;
Documentation/virt/kvm/api.rst static const struct inode_operations kvm_gmem_iops = { · line 661
Quoted 10 lines
Documentation/virt/kvm/api.rst +6
-0inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name); if (IS_ERR(inode)) return inode; + err = -ENOMEM; + private = kzalloc(sizeof(*private), GFP_KERNEL); + if (!private) + goto out; + + mt_init(&private->shareability);
shareability is defined only when CONFIG_KVM_GMEM_SHARED_MEM enabled, should be done within CONFIG_KVM_GMEM_SHARED_MEM .
Quoted 21 lines
Documentation/virt/kvm/api.rst +11
-0+ inode->i_mapping->i_private_data = private; + + err = kvm_gmem_shareability_setup(private, size, flags); + if (err) + goto out; + inode->i_private = (void *)(unsigned long)flags; inode->i_op = &kvm_gmem_iops; inode->i_mapping->a_ops = &kvm_gmem_aops;@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name, WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping)); return inode; + +out: + iput(inode); + + return ERR_PTR(err); }
[...]
Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting
Quoted 35 lines · Binbin Wu
Quoted 32 lines · Ackerley Tng
Track
guest_memfdmemory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within
guest_memfdinstead of within KVM, like inkvm->mem_attr_array.
KVM_MEMORY_ATTRIBUTE_PRIVATEinkvm->mem_attr_arraymust still be retained to allow VMs to only useguest_memfdfor private memory and some other memory for shared memory.Not all use cases require
guest_memfd()to be shared with the host when first created. Add a new flag,GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set onKVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.Signed-off-by Ackerley Tng <[email protected]>Co-developed-by Vishal Annapurve <[email protected]>Signed-off-by Vishal Annapurve <[email protected]>Co-developed-by Fuad Tabba <[email protected]>Signed-off-by Fuad Tabba <[email protected]>Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f---
Documentation/virt/kvm/api.rst| 5 ++ include/uapi/linux/kvm.h | 2 + virt/kvm/guest_memfd.c | 124 ++++++++++++++++++++++++++++++++-3 files changed, 129 insertions(+), 2 deletions(-)
Quoted 12 lines
Quoted 9 lines
Documentation/virt/kvm/api.rst +0
-0@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.The use of
GUEST_MEMFD_FLAG_SUPPORT_SHAREDwill not be allowed for CoCo VMs. This is validated when theguest_memfdinstance is bound to the VM. +If the capabilityKVM_CAP_GMEM_CONVERSIONSis supported, then the 'flags' field +supportsGUEST_MEMFD_FLAG_INIT_PRIVATE.It seems that the sentence is stale?
Didn't find the definition ofKVM_CAP_GMEM_CONVERSIONS.
Aha! It's a typo, should be KVM_CAP_GMEM_CONVERSION.
Quoted 48 lines
Quoted 5 lines
Setting
GUEST_MEMFD_FLAG_INIT_PRIVATEDocumentation/virt/kvm/api.rst +3
-0+will initialize the memory for the guest_memfd as guest-only and not faultable +by the host. +[...]
Quoted 7 lines
static int
kvm_gmem_init_fs_context(struct fs_context *fc)Documentation/virt/kvm/api.rst +1
-0@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = { static struct inode *kvm_gmem_inode_make_secure_inode(const char *name, loff_t size, u64 flags) { + struct kvm_gmem_inode_private *private; struct inode *inode;Documentation/virt/kvm/api.rst static const struct inode_operations kvm_gmem_iops = { · line 659
Quoted 10 lines
Documentation/virt/kvm/api.rst +6
-0+ int err; inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name); if (IS_ERR(inode)) return inode; + err = -ENOMEM; + private = kzalloc(sizeof(*private), GFP_KERNEL); + if (!private) + goto out; + + mt_init(&private->shareability);shareability is defined only when
CONFIG_KVM_GMEM_SHARED_MEMenabled, should be done withinCONFIG_KVM_GMEM_SHARED_MEM.Quoted 19 lines
Documentation/virt/kvm/api.rst +11
-0+ inode->i_mapping->i_private_data = private; + + err = kvm_gmem_shareability_setup(private, size, flags); + if (err) + goto out; + inode->i_private = (void *)(unsigned long)flags; inode->i_op = &kvm_gmem_iops; inode->i_mapping->a_ops = &kvm_gmem_aops;@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name, WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping)); return inode; + +out: + iput(inode); + + return ERR_PTR(err); }[...]
Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use
In reply to Ackerley TngQuoted 37 lines · Ackerley Tng
virt/kvm/guest_memfd.c +23
-2+static int kvm_gmem_convert_execute_work (struct inode *inode, +struct conversion_work *work, +bool to_shared) +{ +enum shareability m; +int ret; + + m = to_shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +return ret; +/* +* Apply shareability first so split/merge can operate on new +* shareability state. +*/ + ret =kvm_gmem_restructure_folios_in_range ( + inode, work->start, work->nr_pages, to_shared); + +return ret; +} +static int kvm_gmem_convert_range (struct file *file,pgoff_t start,size_t nr_pages,bool shared,pgoff_t *error_index)@@ -371,18 +539,21 @@ static int kvm_gmem_convert_range(struct file *file, pgoff_t start,list_for_each_entry (work, &work_list, list) { rollback_stop_item = work; - ret =kvm_gmem_shareability_apply (inode, work, m); + + ret =kvm_gmem_convert_execute_work (inode, work, shared);if (ret)break ; }if (ret) { - m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ;
virt/kvm/guest_memfd.c static int kvm_gmem_convert_range(struct file *file, pgoff_t start, · line 385
Quoted 10 lines
virt/kvm/guest_memfd.c +5
-2list_for_each_entry (work, &work_list, list) { +int r; + + r =kvm_gmem_convert_execute_work (inode, work, !shared); +WARN_ON (r); +if (work == rollback_stop_item)break ; - -WARN_ON (kvm_gmem_shareability_apply (inode, work, m));
Could kvm_gmem_shareability_apply() fail here?
Quoted 81 lines
virt/kvm/guest_memfd.c +74
-0} }@@ -434,6 +605,277 @@ static int kvm_gmem_ioctl_convert_range(struct file *file,return ret; } +#ifdef CONFIG_KVM_GMEM_HUGETLB + +static inline void __filemap_remove_folio_for_restructuring (struct folio *folio) +{ +struct address_space *mapping = folio->mapping; + +spin_lock (&mapping->host->i_lock); +xa_lock_irq (&mapping->i_pages); + +__filemap_remove_folio (folio,NULL ); + +xa_unlock_irq (&mapping->i_pages); +spin_unlock (&mapping->host->i_lock); +} + +/** +* filemap_remove_folio_for_restructuring() - Remove @folio from filemap for +* split/merge. +* +* @folio: the folio to be removed. +* +* Similar to filemap_remove_folio(), but skips LRU-related calls (meaningless +* for guest_memfd), and skips call to ->free_folio() to maintain folio flags. +* +* Context: Expects only the filemap's refcounts to be left on the folio. Will +* freeze these refcounts away so that no other users will interfere +* with restructuring. +*/ +static inline void filemap_remove_folio_for_restructuring (struct folio *folio) +{ +int filemap_refcount; + + filemap_refcount =folio_nr_pages (folio); +while (!folio_ref_freeze (folio, filemap_refcount)) { +/* +* At this point only filemap refcounts are expected, hence okay +* to spin until speculative refcounts go away. +*/ +WARN_ONCE (1 ,"Spinning on folio=%p refcount=%d" , folio,folio_ref_count (folio)); + } + +folio_lock (folio); +__filemap_remove_folio_for_restructuring (folio); +folio_unlock (folio); +} + +/** +* kvm_gmem_split_folio_in_filemap() - Split @folio within filemap in @inode. +* +* @inode: inode containing the folio. +* @folio: folio to be split. +* +* Split a folio into folios of size PAGE_SIZE. Will clean up folio from filemap +* and add back the split folios. +* +* Context: Expects that before this call, folio's refcount is just the +* filemap's refcounts. After this function returns, the split folios' +* refcounts will also be filemap's refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_split_folio_in_filemap (struct inode *inode,struct folio *folio) +{ +size_t orig_nr_pages; +pgoff_t orig_index; +size_t i, j; +int ret; + + orig_nr_pages =folio_nr_pages (folio); +if (orig_nr_pages ==1 ) +return 0 ; + + orig_index = folio->index; + +filemap_remove_folio_for_restructuring (folio);
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 691
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + ret =kvm_gmem_allocator_ops (inode)->split_folio (folio); +if (ret) + goto err; + +for (i =0 ; i < orig_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (folio, i)); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, f, + orig_index + i);
Why does the failure of __kvm_gmem_filemap_add_folio() here lead to rollback, while the failure of the one under rollback only triggers WARN_ON()?
Quoted 74 lines
virt/kvm/guest_memfd.c +74
-0+if (ret) + goto rollback; + } + +return ret; + +rollback: +for (j =0 ; j < i; ++j) { +struct folio *f =page_folio (folio_page (folio, j)); + +filemap_remove_folio_for_restructuring (f); + } + +kvm_gmem_allocator_ops (inode)->merge_folio (folio); +err: +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, folio, orig_index)); + +return ret; +} + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +size_t to_nr_pages; +void *priv; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_page (priv); + +if (kvm_gmem_has_some_shared (inode, folio->index, to_nr_pages)) +return kvm_gmem_split_folio_in_filemap (inode, folio); + +return 0 ; +} + +/** +* kvm_gmem_merge_folio_in_filemap() - Merge @first_folio within filemap in +* @inode. +* +* @inode: inode containing the folio. +* @first_folio: first folio among folios to be merged. +* +* Will clean up subfolios from filemap and add back the merged folio. +* +* Context: Expects that before this call, all subfolios only have filemap +* refcounts. After this function returns, the merged folio will only +* have filemap refcounts. +* Return: 0 on success or negative error otherwise. +*/ +static int kvm_gmem_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +pgoff_t index; +void *priv; +size_t i; +int ret; + + index = first_folio->index; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); +if (folio_nr_pages (first_folio) == to_nr_pages) +return 0 ; + +for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +filemap_remove_folio_for_restructuring (f); + } +
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 775
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+kvm_gmem_allocator_ops (inode)->merge_folio (first_folio); + + ret =__kvm_gmem_filemap_add_folio (inode->i_mapping, first_folio, index); +if (ret) + goto err_split; + +return ret; + +err_split: +WARN_ON (kvm_gmem_allocator_ops (inode)->split_folio (first_folio));
guestmem_hugetlb_split_folio() is possible to fail. e.g.
After the stash is freed by guestmem_hugetlb_unstash_free_metadata() in guestmem_hugetlb_merge_folio(), it's possible to get -ENOMEM for the stash allocation in guestmem_hugetlb_stash_metadata() in guestmem_hugetlb_split_folio().
Quoted 48 lines
virt/kvm/guest_memfd.c +48
-0+for (i =0 ; i < to_nr_pages; ++i) { +struct folio *f =page_folio (folio_page (first_folio, i)); + +WARN_ON (__kvm_gmem_filemap_add_folio (inode->i_mapping, f, index + i)); + } + +return ret; +} + +static inline int kvm_gmem_try_merge_folio_in_filemap (struct inode *inode, +struct folio *first_folio) +{ +size_t to_nr_pages; +void *priv; + + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + +if (kvm_gmem_has_some_shared (inode, first_folio->index, to_nr_pages)) +return 0 ; + +return kvm_gmem_merge_folio_in_filemap (inode, first_folio); +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +size_t to_nr_pages; +pgoff_t index; +pgoff_t end; +void *priv; +int ret; + +if (!kvm_gmem_has_custom_allocator (inode)) +return 0 ; + + end = start + nr_pages; + +/* Round to allocator page size, to check all (huge) pages in range. */ + priv =kvm_gmem_allocator_private (inode); + to_nr_pages =kvm_gmem_allocator_ops (inode)->nr_pages_in_folio (priv); + + start =round_down (start, to_nr_pages); + end =round_up (end, to_nr_pages); + +for (index = start; index < end; index += to_nr_pages) { +struct folio *f;
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + f =filemap_get_folio (inode->i_mapping, index); +if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) + ret =kvm_gmem_split_folio_in_filemap (inode, f);
kvm_gmem_try_split_folio_in_filemap()?
Quoted 13 lines
virt/kvm/guest_memfd.c +13
-0+else + ret =kvm_gmem_try_merge_folio_in_filemap (inode, f); + +if (ret) + goto rollback; + } +return ret; + +rollback: +for (index -= to_nr_pages; index >= start; index -= to_nr_pages) { +struct folio *f; + + f =filemap_get_folio (inode->i_mapping, index);
virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 856
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+if (IS_ERR (f)) +continue ; + +/* Leave just filemap's refcounts on the folio. */ +folio_put (f); + +if (is_split_operation) +WARN_ON (kvm_gmem_merge_folio_in_filemap (inode, f)); +else +WARN_ON (kvm_gmem_split_folio_in_filemap (inode, f));
Is it safe to just leave WARN_ON()s in the rollback case?
Besides, are the kvm_gmem_merge_folio_in_filemap() and kvm_gmem_split_folio_in_filemap() here duplicated with the kvm_gmem_split_folio_in_filemap() and kvm_gmem_try_merge_folio_in_filemap() in the following "r = kvm_gmem_convert_execute_work(inode, work, !shared)"?
Quoted 22 lines
virt/kvm/guest_memfd.c +22
-0+ } + +return ret; +} + +#else + +static inline int kvm_gmem_try_split_folio_in_filemap (struct inode *inode, +struct folio *folio) +{ +return 0 ; +} + +static int kvm_gmem_restructure_folios_in_range (struct inode *inode, +pgoff_t start,size_t nr_pages, +bool is_split_operation) +{ +return 0 ; +} + +#endif +
Re: [RFC PATCH v2 03/51] KVM: selftests: Update guest_memfd_test for INIT_PRIVATE flag
In reply to Ackerley TngQuoted 81 lines · Ackerley Tng
Quoted 70 lines · Ira Weiny
Quoted 56 lines · Ackerley Tng
Test that
GUEST_MEMFD_FLAG_INIT_PRIVATEis only valid whenGUEST_MEMFD_FLAG_SUPPORT_SHAREDis set.Change-Id I506e236a232047cfaee17bcaed02ee14c8d25bbbSigned-off-by Ackerley Tng <[email protected]>--- .../testing/selftests/kvm/guest_memfd_test.c | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-)tools/testing/selftests/kvm/guest_memfd_test.c +21
-5@@ -401,13 +401,31 @@ static void test_with_type(unsigned long vm_type, uint64_t guest_memfd_flags,kvm_vm_release (vm); } +static void test_vm_with_gmem_flag (struct kvm_vm *vm,uint64_t flag, +bool expect_valid) +{ +size_t page_size =getpagesize (); +int fd; + + fd =__vm_create_guest_memfd (vm, page_size, flag); + +if (expect_valid) { +TEST_ASSERT (fd >0 , +"guest_memfd() with flag '0x%lx' should be valid" , + flag); +close (fd); + }else { +TEST_ASSERT (fd ==-1 && errno ==EINVAL , +"guest_memfd() with flag '0x%lx' should fail with EINVAL" , + flag); + } +} +static void test_vm_type_gmem_flag_validity (unsigned long vm_type,uint64_t expected_valid_flags) { -size_t page_size =getpagesize ();struct kvm_vm *vm;uint64_t flag =0 ; -int fd;if (!(kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (vm_type)))return ;@@ -415,17 +433,11 @@ static void test_vm_type_gmem_flag_validity(unsigned long vm_type, vm =vm_create_barebones_type (vm_type);for (flag =BIT (0 ); flag; flag <<=1 ) { - fd =__vm_create_guest_memfd (vm, page_size, flag); +test_vm_with_gmem_flag (vm, flag, flag & expected_valid_flags); -if (flag & expected_valid_flags) { - TEST_ASSERT(fd > 0,tools/testing/selftests/kvm/guest_memfd_test.c static void test_vm_type_gmem_flag_validity(unsigned long vm_type, · line 440
Quoted 10 lines
tools/testing/selftests/kvm/guest_memfd_test.c +3
-7-"guest_memfd() with flag '0x%lx' should be valid" , - flag); -close (fd); - }else { -TEST_ASSERT (fd ==-1 && errno ==EINVAL , -"guest_memfd() with flag '0x%lx' should fail with EINVAL" , - flag); +if (flag ==GUEST_MEMFD_FLAG_SUPPORT_SHARED ) { +test_vm_with_gmem_flag ( + vm, flag |GUEST_MEMFD_FLAG_INIT_PRIVATE , true);I don't understand the point of this check. In 2/51 we set
GUEST_MEMFD_FLAG_INIT_PRIVATEwhenGUEST_MEMFD_FLAG_SUPPORT_SHAREDis set.Quoted 3 lines
When can this check ever fail?
Ira
In 02/51,
GUEST_MEMFD_FLAG_INIT_PRIVATEis not set by default,GUEST_MEMFD_FLAG_INIT_PRIVATEis set as one of thevalid_flags.The intention is that
GUEST_MEMFD_FLAG_INIT_PRIVATEis only valid ifGUEST_MEMFD_FLAG_SUPPORT_SHAREDis requested by userspace.
Quoted 8 lines
In this test, the earlier part before the if block calls
test_vm_with_gmem_flag()all valid flags, and that already testsGUEST_MEMFD_FLAG_SUPPORT_SHAREDindividually.Specifically if
GUEST_MEMFD_FLAG_SUPPORT_SHAREDis set, this if block adds a test for when bothGUEST_MEMFD_FLAG_SUPPORT_SHAREDandGUEST_MEMFD_FLAG_INIT_PRIVATEare set, and sets thatexpect_validis true.
Maybe it's more clear to move this case out of the loop?
Quoted 3 lines
This second test doesn't fail, it is meant to check that the kernel allows the pair of flags to be set. Hope that makes sense.
Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
In reply to Ackerley TngOn 5/15/2025 7:41 AM, Ackerley Tng wrote:
[...]
Quoted 16 lines
virt/kvm/guest_memfd.c +16
-0+ +static int kvm_gmem_convert_range (struct file *file,pgoff_t start, +size_t nr_pages,bool shared, +pgoff_t *error_index) +{ +struct conversion_work *work, *tmp, *rollback_stop_item; +LIST_HEAD (work_list); +struct inode *inode; +enum shareability m; +int ret; + + inode =file_inode (file); + +filemap_invalidate_lock (inode->i_mapping); + + m = shared ?SHAREABILITY_ALL :SHAREABILITY_GUEST ;
virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t inde · line 322
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ ret =kvm_gmem_convert_compute_work (inode, start, nr_pages, m, &work_list); +if (ret ||list_empty (&work_list)) + goto out; + +list_for_each_entry (work, &work_list, list) +kvm_gmem_convert_invalidate_begin (inode, work); + +list_for_each_entry (work, &work_list, list) { + ret =kvm_gmem_convert_should_proceed (inode, work, shared, + error_index);
Since kvm_gmem_invalidate_begin() begins to handle shared memory, kvm_gmem_convert_invalidate_begin() will zap the table.
The shared mapping could be zapped in kvm_gmem_convert_invalidate_begin() even when kvm_gmem_convert_should_proceed() returns error.
The sequence is a bit confusing to me, at least in this patch so far.
Quoted 35 lines
virt/kvm/guest_memfd.c +35
-0+if (ret) + goto invalidate_end; + } + +list_for_each_entry (work, &work_list, list) { + rollback_stop_item = work; + ret =kvm_gmem_shareability_apply (inode, work, m); +if (ret) +break ; + } + +if (ret) { + m = shared ?SHAREABILITY_GUEST :SHAREABILITY_ALL ; +list_for_each_entry (work, &work_list, list) { +if (work == rollback_stop_item) +break ; + +WARN_ON (kvm_gmem_shareability_apply (inode, work, m)); + } + } + +invalidate_end: +list_for_each_entry (work, &work_list, list) +kvm_gmem_convert_invalidate_end (inode, work); +out: +filemap_invalidate_unlock (inode->i_mapping); + +list_for_each_entry_safe (work, tmp, &work_list, list) { +list_del (&work->list); +kfree (work); + } + +return ret; +} +
[...]
Quoted 33 lines
virt/kvm/guest_memfd.c +13
-2@@ -186,15 +490,26 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,unsigned long index;xa_for_each_range (&gmem->bindings, index, slot, start, end -1 ) { +enum kvm_gfn_range_filter filter;pgoff_t pgoff = slot->gmem.pgoff; + filter =KVM_FILTER_PRIVATE ; +if (kvm_gmem_memslot_supports_shared (slot)) { +/* +* Unmapping would also cause invalidation, but cannot +* rely on mmu_notifiers to do invalidation via +* unmapping, since memory may not be mapped to +* userspace. +*/ + filter |=KVM_FILTER_SHARED ; + } +struct kvm_gfn_range gfn_range = { .start = slot->base_gfn +max (pgoff, start) - pgoff, .end = slot->base_gfn +min (pgoff + slot->npages, end) - pgoff, .slot = slot, .may_block = true, -/* guest memfd is relevant to only private mappings. */ - .attr_filter =KVM_FILTER_PRIVATE , + .attr_filter = filter, };if (!found_memslot) {@@ -484,11 +799,49 @@ EXPORT_SYMBOL_GPL(kvm_gmem_memslot_supports_shared);#define kvm_gmem_mmap NULL#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
[...]
Re: [RFC PATCH v2 05/51] KVM: guest_memfd: Skip LRU for guest_memfd folios
In reply to Ackerley TngQuoted 6 lines · Ackerley Tng
filemap_add_folio(), called fromfilemap_grab_folio(), adds the folio onto some LRU list, which is not necessary forguest_memfdsinceguest_memfdfolios don't participate in any swapping.This patch reimplements part of
filemap_add_folio()to avoid adding allocatedguest_memfdfolios to the filemap.
filemap -> LRU list?
Quoted 14 lines
With shared to private conversions dependent on refcounts, avoiding usage of LRU ensures that LRU lists no longer take any refcounts on
guest_memfdfolios and significantly reduces the chance of elevated refcounts during conversion.Signed-off-by Ackerley Tng <[email protected]>Change-Id Ia2540d9fc132d46219e6e714fd42bc82a62a27fa--- mm/filemap.c | 1 + mm/memcontrol.c | 2 + virt/kvm/guest_memfd.c | 91 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 86 insertions(+), 8 deletions(-)
[...]
Quoted 29 lines
/*
* Returns a locked folio on success. The caller is responsible for
* setting the up-to-date flag before the memory is mapped into the guest.virt/kvm/guest_memfd.c +20
-1@@ -477,8 +509,46 @@ static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,*/ static struct folio *kvm_gmem_get_folio (struct inode *inode,pgoff_t index) { +struct folio *folio; +gfp_t gfp; +int ret; + +repeat: + folio =filemap_lock_folio (inode->i_mapping, index); +if (!IS_ERR (folio)) +return folio; + + gfp =mapping_gfp_mask (inode->i_mapping); +/* TODO: Support huge pages. */ -return filemap_grab_folio (inode->i_mapping, index); + folio =filemap_alloc_folio (gfp,0 ); +if (!folio) +return ERR_PTR (-ENOMEM ); + + ret =mem_cgroup_charge (folio,NULL , gfp); +if (ret) { +folio_put (folio); +return ERR_PTR (ret); + }
virt/kvm/guest_memfd.c static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, · line 542
Quoted 10 lines
virt/kvm/guest_memfd.c +10
-0+ + ret =kvm_gmem_filemap_add_folio (inode->i_mapping, folio, index); +if (ret) { +folio_put (folio); + +/* +* There was a race, two threads tried to get a folio indexing +* to the same location in the filemap. The losing thread should +* free the allocated folio, then lock the folio added to the +* filemap by the winning thread.
How about changing
“then lock the folio added to the filemap by the winning thread” to
"the winning thread locks the folio added to the filemap"?
Quoted 14 lines
virt/kvm/guest_memfd.c +9
-0+*/ +if (ret == -EEXIST ) + goto repeat; + +return ERR_PTR (ret); + } + +__folio_set_locked (folio); +return folio; } static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,@@ -956,23 +1026,28 @@ static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol }
virt/kvm/guest_memfd.c static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol · line 1036
Quoted 10 lines
virt/kvm/guest_memfd.c +8
-0#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE +static void kvm_gmem_invalidate (struct folio *folio) +{ +kvm_pfn_t pfn =folio_pfn (folio); + +kvm_arch_gmem_invalidate (pfn, pfn +folio_nr_pages (folio)); +} +#else +static inline void kvm_gmem_invalidate (struct folio *folio) {}
No need to tag a local static function with "inline".
Quoted 2 lines
virt/kvm/guest_memfd.c +2
-0+#endif +
[...]