1G page support for guest_memfd
Subsystems (22)
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
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?
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 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.
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.
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.
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.
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 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.
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/
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 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.
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
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 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
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>
Quoted 11 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].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
Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.
Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a guest_memfd that performs in-place conversion between shared and private memory. This is because the guest_memfd will first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.
Currently, we tested the initial memory region using the in-place conversion version of guest_memfd as backend by modifying QEMU to add an extra anonymous backend to hold the source initial content in shared memory. The extra anonymous backend is freed after finishing ading the initial memory region.
This issue is benign for TDX, as the initial memory region can also utilize the traditional guest_memfd, which only allows 4KB mappings. This is acceptable for now, as the initial memory region typically involves a small amount of memory, and we may not enable huge pages for ranges covered by the initial memory region in the near future.
Quoted 20 lines · Yan Zhao
Quoted 11 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].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
Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.
Quoted 5 lines
Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a
guest_memfdthat performs in-place conversion between shared and private memory. This is because theguest_memfdwill first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.
I have an idea.
If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?
So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.
For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.
Quoted 10 lines
Currently, we tested the initial memory region using the in-place conversion version of
guest_memfdas backend by modifying QEMU to add an extra anonymous backend to hold the source initial content in shared memory. The extra anonymous backend is freed after finishing ading the initial memory region.This issue is benign for TDX, as the initial memory region can also utilize the traditional
guest_memfd, which only allows 4KB mappings. This is acceptable for now, as the initial memory region typically involves a small amount of memory, and we may not enable huge pages for ranges covered by the initial memory region in the near future.
Quoted 26 lines · Xiaoyao Li
Quoted 19 lines · Yan Zhao
Quoted 11 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].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
Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.
Quoted 5 lines
Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a
guest_memfdthat performs in-place conversion between shared and private memory. This is because theguest_memfdwill first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.
Quoted 7 lines
I have an idea.
If I understand correctly, the
KVM_GMEM_CONVERT_PRIVATEof in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?So
KVM_GMEM_CONVERT_PRIVATEcan be used to initialize the private memory actually for non-CoCo case actually, that userspace firstmmap()it and ensure it's shared and writes the initial content to it, after it userspace convert it to private withKVM_GMEM_CONVERT_PRIVATE.For CoCo case, like TDX, it can hook to
KVM_GMEM_CONVERT_PRIVATEif it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.
And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to explicitly request that the page range is converted to private and the content needs to be retained. So that TDX can identify which case needs to call in-place TDH.PAGE.ADD.
Quoted 35 lines · Xiaoyao Li
Quoted 34 lines · Xiaoyao Li
Quoted 32 lines · Yan Zhao
Quoted 6 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.Quoted 7 lines
This patchset is based on Linux v6.15-rc6, and requires the mmap support for
guest_memfdpatchset (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-v2Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build
time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory
and private target memory.Therefore, userspace cannot store the initial content in shared memory at the
mmap-ed VA of aguest_memfdthat performs in-place conversion between shared and
private memory. This is because theguest_memfdwill first unmap a PFN in shared
page tables and then check for any extra refcount held for the shared PFN before
converting it to private.
Quoted 5 lines
Quoted 5 lines
I have an idea.
If I understand correctly, the
KVM_GMEM_CONVERT_PRIVATEof in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?
However, whenever there's a GUP in TDX to get the source page, there will be an extra page refcount.
Quoted 4 lines
Quoted 4 lines
So
KVM_GMEM_CONVERT_PRIVATEcan be used to initialize the private memory actually for non-CoCo case actually, that userspace firstmmap()it and ensure it's shared and writes the initial content to it, after it userspace convert it to private withKVM_GMEM_CONVERT_PRIVATE.
The conversion request here will be declined therefore.
Quoted 9 lines
Quoted 3 lines
For CoCo case, like TDX, it can hook to
KVM_GMEM_CONVERT_PRIVATEif it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.And maybe a new flag for
KVM_GMEM_CONVERT_PRIVATEfor user space to explicitly request that the page range is converted to private and the content needs to be retained. So that TDX can identify which case needs to call in-place TDH.PAGE.ADD.
Quoted 36 lines · Yan Zhao
Quoted 35 lines · Xiaoyao Li
Quoted 34 lines · Xiaoyao Li
Quoted 32 lines · Yan Zhao
Quoted 6 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.Quoted 7 lines
This patchset is based on Linux v6.15-rc6, and requires the mmap support for
guest_memfdpatchset (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-v2Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build
time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory
and private target memory.Therefore, userspace cannot store the initial content in shared memory at the
mmap-ed VA of aguest_memfdthat performs in-place conversion between shared and
private memory. This is because theguest_memfdwill first unmap a PFN in shared
page tables and then check for any extra refcount held for the shared PFN before
converting it to private.
Quoted 7 lines
Quoted 5 lines
Quoted 5 lines
I have an idea.
If I understand correctly, the
KVM_GMEM_CONVERT_PRIVATEof in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?However, whenever there's a GUP in TDX to get the source page, there will be an extra page refcount.
The GUP in TDX happens after the gmem converts the page to private.
In the view of TDX, the physical page is converted to private already and it contains the initial content. But the content is not usable for TDX until TDX calls in-place PAGE.ADD
Quoted 16 lines
Quoted 4 lines
Quoted 4 lines
So
KVM_GMEM_CONVERT_PRIVATEcan be used to initialize the private memory actually for non-CoCo case actually, that userspace firstmmap()it and ensure it's shared and writes the initial content to it, after it userspace convert it to private withKVM_GMEM_CONVERT_PRIVATE.The conversion request here will be declined therefore.
Quoted 9 lines
Quoted 3 lines
For CoCo case, like TDX, it can hook to
KVM_GMEM_CONVERT_PRIVATEif it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.And maybe a new flag for
KVM_GMEM_CONVERT_PRIVATEfor user space to explicitly request that the page range is converted to private and the content needs to be retained. So that TDX can identify which case needs to call in-place TDH.PAGE.ADD.
Quoted 39 lines · Xiaoyao Li
Quoted 38 lines · Yan Zhao
Quoted 37 lines · Xiaoyao Li
Quoted 36 lines · Xiaoyao Li
Quoted 23 lines · Yan Zhao
Quoted 6 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.Quoted 7 lines
This patchset is based on Linux v6.15-rc6, and requires the mmap support for
guest_memfdpatchset (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-v2Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build
time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory
and private target memory.Quoted 9 lines
Therefore, userspace cannot store the initial content in shared memory at the
mmap-ed VA of aguest_memfdthat performs in-place conversion between shared and
private memory. This is because theguest_memfdwill first unmap a PFN in shared
page tables and then check for any extra refcount held for the shared PFN before
converting it to private.I have an idea.
Quoted 7 lines
Quoted 5 lines
Quoted 3 lines
Quoted 3 lines
If I understand correctly, the
KVM_GMEM_CONVERT_PRIVATEof in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?However, whenever there's a GUP in TDX to get the source page, there will be an extra page refcount.
The GUP in TDX happens after the gmem converts the page to private.
May it's not GUP since the page has been unmapped from userspace? (Sorry that I'm not familiar with the terminology)
Quoted 20 lines
In the view of TDX, the physical page is converted to private already and it contains the initial content. But the content is not usable for TDX until TDX calls in-place PAGE.ADD
Quoted 16 lines
Quoted 4 lines
Quoted 4 lines
So
KVM_GMEM_CONVERT_PRIVATEcan be used to initialize the private memory actually for non-CoCo case actually, that userspace firstmmap()it and ensure it's shared and writes the initial content to it, after it userspace convert it to private withKVM_GMEM_CONVERT_PRIVATE.The conversion request here will be declined therefore.
Quoted 9 lines
Quoted 3 lines
For CoCo case, like TDX, it can hook to
KVM_GMEM_CONVERT_PRIVATEif it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.And maybe a new flag for
KVM_GMEM_CONVERT_PRIVATEfor user space to explicitly request that the page range is converted to private and the content needs to be retained. So that TDX can identify which case needs to call in-place TDH.PAGE.ADD.
Quoted 28 lines · Xiaoyao Li
Quoted 20 lines · Yan Zhao
Quoted 11 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].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
Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.
Quoted 5 lines
Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a
guest_memfdthat performs in-place conversion between shared and private memory. This is because theguest_memfdwill first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.
Quoted 5 lines
I have an idea.
If I understand correctly, the
KVM_GMEM_CONVERT_PRIVATEof in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?
That's correct.
Quoted 5 lines
So
KVM_GMEM_CONVERT_PRIVATEcan be used to initialize the private memory actually for non-CoCo case actually, that userspace firstmmap()it and ensure it's shared and writes the initial content to it, after it userspace convert it to private withKVM_GMEM_CONVERT_PRIVATE.
I think you mean pKVM by non-coco VMs that care about private memory. Yes, initial memory regions can start as shared which userspace can populate and then convert the ranges to private.
Quoted 4 lines
For CoCo case, like TDX, it can hook to
KVM_GMEM_CONVERT_PRIVATEif it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.
I think this scheme will be cleaner:
1) Userspace marks the guest_memfd ranges corresponding to initial payload as shared.
2) Userspace mmaps and populates the ranges.
3) Userspace converts those guest_memfd ranges to private.
4) For both SNP and TDX, userspace continues to invoke corresponding initial payload preparation operations via existing KVM ioctls e.g. KVM_SEV_SNP_LAUNCH_UPDATE/KVM_TDX_INIT_MEM_REGION.
- SNP/TDX KVM logic fetches the right pfns for the target gfns
using the normal paths supported by KVM and passes those pfns directly to the right trusted module to initialize the "encrypted" memory contents.
- Avoiding any GUP or memcpy from source addresses.
i.e. for TDX VMs, KVM_TDX_INIT_MEM_REGION still does the in-place TDH.PAGE.ADD.
Since we need to support VMs that will/won't use in-place conversion, I think operations like KVM_TDX_INIT_MEM_REGION can introduce explicit flags to allow userspace to indicate whether to assume in-place conversion or not. Maybe kvm_tdx_init_mem_region.source_addr/kvm_sev_snp_launch_update.uaddr can be null in the scenarios where in-place conversion is used.
Quoted 52 lines · Vishal Annapurve
Quoted 28 lines · Xiaoyao Li
Quoted 20 lines · Yan Zhao
Quoted 11 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].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
Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.
Quoted 5 lines
Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a
guest_memfdthat performs in-place conversion between shared and private memory. This is because theguest_memfdwill first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.Quoted 5 lines
I have an idea.
If I understand correctly, the
KVM_GMEM_CONVERT_PRIVATEof in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?That's correct.
Quoted 5 lines
So
KVM_GMEM_CONVERT_PRIVATEcan be used to initialize the private memory actually for non-CoCo case actually, that userspace firstmmap()it and ensure it's shared and writes the initial content to it, after it userspace convert it to private withKVM_GMEM_CONVERT_PRIVATE.I think you mean pKVM by non-coco VMs that care about private memory. Yes, initial memory regions can start as shared which userspace can populate and then convert the ranges to private.
Quoted 4 lines
For CoCo case, like TDX, it can hook to
KVM_GMEM_CONVERT_PRIVATEif it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.
Quoted 13 lines
I think this scheme will be cleaner:
1) Userspace marks theguest_memfdranges corresponding to initial payload as shared.
2) Userspace mmaps and populates the ranges.
3) Userspace converts thoseguest_memfdranges to private.
4) For both SNP and TDX, userspace continues to invoke corresponding initial payload preparation operations via existing KVM ioctls e.g. KVM_SEV_SNP_LAUNCH_UPDATE/KVM_TDX_INIT_MEM_REGION.
- SNP/TDX KVM logic fetches the right pfns for the target gfns
using the normal paths supported by KVM and passes those pfns directly to the right trusted module to initialize the "encrypted" memory contents.
- Avoiding any GUP or memcpy from source addresses.
One caveat:
when TDX populates the mirror root, kvm_gmem_get_pfn() is invoked. Then kvm_gmem_prepare_folio() is further invoked to zero the folio.
Quoted 1 line
i.e. for TDX VMs,
KVM_TDX_INIT_MEM_REGIONstill does the in-place TDH.PAGE.ADD.
So, upon here, the pages should not contain the original content?
Quoted 6 lines
Since we need to support VMs that will/won't use in-place conversion, I think operations like
KVM_TDX_INIT_MEM_REGIONcan introduce explicit flags to allow userspace to indicate whether to assume in-place conversion or not. Maybe kvm_tdx_init_mem_region.source_addr/kvm_sev_snp_launch_update.uaddr can be null in the scenarios where in-place conversion is used.
Quoted 67 lines · Yan Zhao
Quoted 52 lines · Vishal Annapurve
Quoted 28 lines · Xiaoyao Li
Quoted 20 lines · Yan Zhao
Quoted 11 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].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
Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.
Quoted 5 lines
Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a
guest_memfdthat performs in-place conversion between shared and private memory. This is because theguest_memfdwill first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.Quoted 5 lines
I have an idea.
If I understand correctly, the
KVM_GMEM_CONVERT_PRIVATEof in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?That's correct.
Quoted 5 lines
So
KVM_GMEM_CONVERT_PRIVATEcan be used to initialize the private memory actually for non-CoCo case actually, that userspace firstmmap()it and ensure it's shared and writes the initial content to it, after it userspace convert it to private withKVM_GMEM_CONVERT_PRIVATE.I think you mean pKVM by non-coco VMs that care about private memory. Yes, initial memory regions can start as shared which userspace can populate and then convert the ranges to private.
Quoted 4 lines
For CoCo case, like TDX, it can hook to
KVM_GMEM_CONVERT_PRIVATEif it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.Quoted 13 lines
I think this scheme will be cleaner:
1) Userspace marks theguest_memfdranges corresponding to initial payload as shared.
2) Userspace mmaps and populates the ranges.
3) Userspace converts thoseguest_memfdranges to private.
4) For both SNP and TDX, userspace continues to invoke corresponding initial payload preparation operations via existing KVM ioctls e.g. KVM_SEV_SNP_LAUNCH_UPDATE/KVM_TDX_INIT_MEM_REGION.
- SNP/TDX KVM logic fetches the right pfns for the target gfns
using the normal paths supported by KVM and passes those pfns directly to the right trusted module to initialize the "encrypted" memory contents.
- Avoiding any GUP or memcpy from source addresses.
Quoted 4 lines
One caveat:
when TDX populates the mirror root,
kvm_gmem_get_pfn()is invoked. Thenkvm_gmem_prepare_folio()is further invoked to zero the folio.
Given that confidential VMs have their own way of initializing private memory, I think zeroing makes sense for only shared memory ranges. i.e. something like below:
1) Don't zero at allocation time.
2) If faulting in a shared page and its not uptodate, then zero the page and set the page as uptodate.
3) Clear uptodate flag on private to shared conversion.
4) For faults on private ranges, don't zero the memory.
There might be some other considerations here e.g. pKVM needs non-destructive conversion operation, which might need a way to enable zeroing at allocation time only.
On a TDX specific note, IIUC, KVM TDX logic doesn't need to clear pages on future platforms [1].
[1] https://lore.kernel.org/lkml/[email protected]/
Quoted 4 lines
Quoted 2 lines
i.e. for TDX VMs,
KVM_TDX_INIT_MEM_REGIONstill does the in-place TDH.PAGE.ADD.So, upon here, the pages should not contain the original content?
Pages should contain the original content. Michael is already experimenting with similar logic [2] for SNP.
Quoted 82 lines · Vishal Annapurve
Quoted 67 lines · Yan Zhao
Quoted 52 lines · Vishal Annapurve
Quoted 28 lines · Xiaoyao Li
Quoted 20 lines · Yan Zhao
Quoted 11 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].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
Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.
Quoted 5 lines
Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a
guest_memfdthat performs in-place conversion between shared and private memory. This is because theguest_memfdwill first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.Quoted 5 lines
I have an idea.
If I understand correctly, the
KVM_GMEM_CONVERT_PRIVATEof in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?That's correct.
Quoted 5 lines
So
KVM_GMEM_CONVERT_PRIVATEcan be used to initialize the private memory actually for non-CoCo case actually, that userspace firstmmap()it and ensure it's shared and writes the initial content to it, after it userspace convert it to private withKVM_GMEM_CONVERT_PRIVATE.I think you mean pKVM by non-coco VMs that care about private memory. Yes, initial memory regions can start as shared which userspace can populate and then convert the ranges to private.
Quoted 4 lines
For CoCo case, like TDX, it can hook to
KVM_GMEM_CONVERT_PRIVATEif it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.Quoted 13 lines
I think this scheme will be cleaner:
1) Userspace marks theguest_memfdranges corresponding to initial payload as shared.
2) Userspace mmaps and populates the ranges.
3) Userspace converts thoseguest_memfdranges to private.
4) For both SNP and TDX, userspace continues to invoke corresponding initial payload preparation operations via existing KVM ioctls e.g. KVM_SEV_SNP_LAUNCH_UPDATE/KVM_TDX_INIT_MEM_REGION.
- SNP/TDX KVM logic fetches the right pfns for the target gfns
using the normal paths supported by KVM and passes those pfns directly to the right trusted module to initialize the "encrypted" memory contents.
- Avoiding any GUP or memcpy from source addresses.Quoted 4 lines
One caveat:
when TDX populates the mirror root,
kvm_gmem_get_pfn()is invoked. Thenkvm_gmem_prepare_folio()is further invoked to zero the folio.Given that confidential VMs have their own way of initializing private memory, I think zeroing makes sense for only shared memory ranges. i.e. something like below:
1) Don't zero at allocation time.
2) If faulting in a shared page and its not uptodate, then zero the page and set the page as uptodate.
3) Clear uptodate flag on private to shared conversion.
4) For faults on private ranges, don't zero the memory.
Quoted 6 lines
There might be some other considerations here e.g. pKVM needs non-destructive conversion operation, which might need a way to enable zeroing at allocation time only.
On a TDX specific note, IIUC, KVM TDX logic doesn't need to clear pages on future platforms [1].
Yes, TDX does not need to clear pages on private page allocation. But current kvm_gmem_prepare_folio() clears private pages in the common path for both TDX and SEV-SNP.
I just wanted to point out that it's a kind of obstacle that need to be removed to implement the proposed approach.
Quoted 11 lines
[1] https://lore.kernel.org/lkml/[email protected]/
Quoted 4 lines
Quoted 2 lines
i.e. for TDX VMs,
KVM_TDX_INIT_MEM_REGIONstill does the in-place TDH.PAGE.ADD.So, upon here, the pages should not contain the original content?
Pages should contain the original content. Michael is already experimenting with similar logic [2] for SNP.
Quoted 88 lines · Yan Zhao
Quoted 86 lines · Vishal Annapurve
Quoted 67 lines · Yan Zhao
Quoted 52 lines · Vishal Annapurve
Quoted 28 lines · Xiaoyao Li
Quoted 20 lines · Yan Zhao
Quoted 11 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].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
Just to record a found issue -- not one that must be fixed.
In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.
Quoted 5 lines
Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a
guest_memfdthat performs in-place conversion between shared and private memory. This is because theguest_memfdwill first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.Quoted 5 lines
I have an idea.
If I understand correctly, the
KVM_GMEM_CONVERT_PRIVATEof in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?That's correct.
Quoted 5 lines
So
KVM_GMEM_CONVERT_PRIVATEcan be used to initialize the private memory actually for non-CoCo case actually, that userspace firstmmap()it and ensure it's shared and writes the initial content to it, after it userspace convert it to private withKVM_GMEM_CONVERT_PRIVATE.I think you mean pKVM by non-coco VMs that care about private memory. Yes, initial memory regions can start as shared which userspace can populate and then convert the ranges to private.
Quoted 4 lines
For CoCo case, like TDX, it can hook to
KVM_GMEM_CONVERT_PRIVATEif it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.Quoted 13 lines
I think this scheme will be cleaner:
1) Userspace marks theguest_memfdranges corresponding to initial payload as shared.
2) Userspace mmaps and populates the ranges.
3) Userspace converts thoseguest_memfdranges to private.
4) For both SNP and TDX, userspace continues to invoke corresponding initial payload preparation operations via existing KVM ioctls e.g. KVM_SEV_SNP_LAUNCH_UPDATE/KVM_TDX_INIT_MEM_REGION.
- SNP/TDX KVM logic fetches the right pfns for the target gfns
using the normal paths supported by KVM and passes those pfns directly to the right trusted module to initialize the "encrypted" memory contents.
- Avoiding any GUP or memcpy from source addresses.Quoted 4 lines
One caveat:
when TDX populates the mirror root,
kvm_gmem_get_pfn()is invoked. Thenkvm_gmem_prepare_folio()is further invoked to zero the folio.Given that confidential VMs have their own way of initializing private memory, I think zeroing makes sense for only shared memory ranges. i.e. something like below:
1) Don't zero at allocation time.
2) If faulting in a shared page and its not uptodate, then zero the page and set the page as uptodate.
3) Clear uptodate flag on private to shared conversion.
4) For faults on private ranges, don't zero the memory.There might be some other considerations here e.g. pKVM needs non-destructive conversion operation, which might need a way to enable zeroing at allocation time only.
Quoted 9 lines
Quoted 2 lines
On a TDX specific note, IIUC, KVM TDX logic doesn't need to clear pages on future platforms [1].
Yes, TDX does not need to clear pages on private page allocation. But current
kvm_gmem_prepare_folio()clears private pages in the common path for both TDX and SEV-SNP.I just wanted to point out that it's a kind of obstacle that need to be removed to implement the proposed approach.
Proposed approach will work with 4K pages without any additional changes. For huge pages it's easy to prototype this approach by just disabling zeroing logic in guest mem on faulting and instead always doing zeroing on allocation.
I would be curious to understand if we need zeroing on conversion for Confidential VMs. If not, then the simple rule of zeroing on allocation only will work for all usecases.
Sean Christopherson
maintainerQuoted 3 lines · Vishal Annapurve
I would be curious to understand if we need zeroing on conversion for Confidential VMs. If not, then the simple rule of zeroing on allocation only will work for all usecases.
Unless I'm misunderstanding what your asking, pKVM very specific does NOT want zeroing on conversion, because one of its use cases is in-place conversion, e.g. to fill a shared buffer and then convert it to private so that the buffer can be processed in the TEE.
Some architectures, e.g. SNP and TDX, may effectively require zeroing on conversion, but that's essentially a property of the architecture, i.e. an arch/vendor specific detail.
Quoted 10 lines · Sean Christopherson
Quoted 3 lines · Vishal Annapurve
I would be curious to understand if we need zeroing on conversion for Confidential VMs. If not, then the simple rule of zeroing on allocation only will work for all usecases.
Unless I'm misunderstanding what your asking, pKVM very specific does NOT want zeroing on conversion, because one of its use cases is in-place conversion, e.g. to fill a shared buffer and then convert it to private so that the buffer can be processed in the TEE.
Yeah, that makes sense. So "just zero on allocation" (and no more zeroing during conversion) policy will work for pKVM.
Quoted 4 lines
Some architectures, e.g. SNP and TDX, may effectively require zeroing on conversion, but that's essentially a property of the architecture, i.e. an
arch/vendorspecific detail.
Conversion operation is a unique capability supported by guest_memfd files so my intention of bringing up zeroing was to better understand the need and clarify the role of guest_memfd in handling zeroing during conversion.
Not sure if I am misinterpreting you, but treating "zeroing during conversion" as the responsibility of arch/vendor specific implementation outside of guest_memfd sounds good to me.
Quoted 7 lines · Vishal Annapurve
Quoted 6 lines
Some architectures, e.g. SNP and TDX, may effectively require zeroing on conversion,
but that's essentially a property of the architecture, i.e. anarch/vendorspecific
detail.
Quoted 8 lines
Conversion operation is a unique capability supported by
guest_memfdfiles so my intention of bringing up zeroing was to better understand the need and clarify the role ofguest_memfdin handling zeroing during conversion.Not sure if I am misinterpreting you, but treating "zeroing during conversion" as the responsibility of
arch/vendorspecific implementation outside ofguest_memfdsounds good to me.
For TDX if we don't zero on conversion from private->shared we will be dependent on behavior of the CPU when reading memory with keyid 0, which was previously encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the kernel in order to not make non-architectual behavior into userspace ABI.
Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning? Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)
Sean Christopherson
maintainerQuoted 17 lines · Rick P Edgecombe
Quoted 7 lines · Vishal Annapurve
Quoted 6 lines
Some architectures, e.g. SNP and TDX, may effectively require zeroing on conversion,
but that's essentially a property of the architecture, i.e. anarch/vendorspecific
detail.Quoted 8 lines
Conversion operation is a unique capability supported by
guest_memfdfiles so my intention of bringing up zeroing was to better understand the need and clarify the role ofguest_memfdin handling zeroing during conversion.Not sure if I am misinterpreting you, but treating "zeroing during conversion" as the responsibility of
arch/vendorspecific implementation outside ofguest_memfdsounds good to me.
Quoted 5 lines
For TDX if we don't zero on conversion from
private->sharedwe will be dependent on behavior of the CPU when reading memory with keyid 0, which was previously encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the kernel in order to not make non-architectual behavior into userspace ABI.
Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.
Quoted 3 lines
Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning?
Because it's literally converting memory from shared to private? And IICU, it's not a one-time provisioning, e.g. memory can go:
shared => fill => private => consume => shared => fill => private => consume
Quoted 2 lines
Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)
Are you referring to this suggestion?
: And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.
If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion, and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.
Quoted 9 lines · Sean Christopherson
Quoted 8 lines
For TDX if we don't zero on conversion from
private->sharedwe will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.
Quoted 3 lines
Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.
Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.
Quoted 9 lines
Quoted 4 lines
Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning?
Because it's literally converting memory from shared to private? And IICU, it's
not a one-time provisioning, e.g. memory can go:
Quoted 6 lines
shared => fill => private => consume => shared => fill => private => consume
Quoted 2 lines
Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)
Are you referring to this suggestion?
Yea, in general to make it a specific operation preserving operation.
Quoted 11 lines
: And maybe a new flag for
KVM_GMEM_CONVERT_PRIVATEfor user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.
Ok, we should POC how it works with TDX.
Quoted 15 lines · Rick P
Quoted 9 lines · Sean Christopherson
Quoted 8 lines
For TDX if we don't zero on conversion from
private->sharedwe will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.Quoted 3 lines
Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.
Quoted 6 lines
Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.
If the answer is that "always zero on private to shared conversions" for all CC VMs, then does the scheme outlined in [1] make sense for handling the private -> shared conversions? For pKVM, there can be a VM type check to avoid the zeroing during conversions and instead just zero on allocations. This allows delaying zeroing until the fault time for CC VMs and can be done in guest_memfd centrally. We will need more inputs from the SEV side for this discussion.
[1] https://lore.kernel.org/lkml/CAGtprH-83EOz8rrUjE+O8m7nUDjt=THyXx=kfft1xQry65mtQg@mail.gmail.com/
Quoted 25 lines
Quoted 10 lines
Quoted 5 lines
Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning?
Because it's literally converting memory from shared to private? And IICU, it's
not a one-time provisioning, e.g. memory can go:Quoted 6 lines
shared => fill => private => consume => shared => fill => private => consume
Quoted 2 lines
Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)
Are you referring to this suggestion?
Yea, in general to make it a specific operation preserving operation.
Quoted 6 lines
: And maybe a new flag for
KVM_GMEM_CONVERT_PRIVATEfor user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.
Quoted 7 lines
Quoted 5 lines
If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.Ok, we should POC how it works with TDX.
I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.
2) Shared to private conversions are always content-preserving for all VMs as far as guest_memfd is concerned.
3) Private to shared conversions are not content-preserving for CC VMs as far as guest_memfd is concerned, subject to more discussions.
[2] https://lore.kernel.org/lkml/CAGtprH-Kzn2kOGZ4JuNtUT53Hugw64M-_XMmhz_gCiDS6BAFtQ@mail.gmail.com/
Quoted 32 lines · Vishal Annapurve
Quoted 15 lines · Rick P
Quoted 9 lines · Sean Christopherson
Quoted 8 lines
For TDX if we don't zero on conversion from
private->sharedwe will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.Quoted 3 lines
Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.
Quoted 6 lines
Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.
If the answer is that "always zero on private to shared conversions" for all CC VMs, then does the scheme outlined in [1] make sense for handling the private -> shared conversions? For pKVM, there can be a VM type check to avoid the zeroing during conversions and instead just zero on allocations. This allows delaying zeroing until the fault time for CC VMs and can be done in
guest_memfdcentrally. We will need more inputs from the SEV side for this discussion.
Quoted 1 line
[1] https://lore.kernel.org/lkml/CAGtprH-83EOz8rrUjE+O8m7nUDjt=THyXx=kfft1xQry65mtQg@mail.gmail.com/
It's nice that we don't double zero (since TDX module will do it too) for private allocation/mapping. Seems ok to me.
Quoted 34 lines
Quoted 26 lines
Quoted 11 lines
Quoted 6 lines
Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning?
Because it's literally converting memory from shared to private? And IICU, it's
not a one-time provisioning, e.g. memory can go:Quoted 6 lines
shared => fill => private => consume => shared => fill => private => consume
Quoted 2 lines
Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)
Are you referring to this suggestion?
Yea, in general to make it a specific operation preserving operation.
Quoted 6 lines
: And maybe a new flag for
KVM_GMEM_CONVERT_PRIVATEfor user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.Quoted 7 lines
Quoted 5 lines
If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.Ok, we should POC how it works with TDX.
Quoted 8 lines
I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.
2) Shared to private conversions are always content-preserving for all VMs as far asguest_memfdis concerned.
3) Private to shared conversions are not content-preserving for CC VMs as far asguest_memfdis concerned, subject to more discussions.[2] https://lore.kernel.org/lkml/CAGtprH-Kzn2kOGZ4JuNtUT53Hugw64M-_XMmhz_gCiDS6BAFtQ@mail.gmail.com/
Right, I read that. I still don't see why pKVM needs to do normal private/shared conversion for data provisioning. Vs a dedicated operation/flag to make it a special case.
I'm trying to suggest there could be a benefit to making all gmem VM types behave the same. If conversions are always content preserving for pKVM, why can't userspace always use the operation that says preserve content? Vs changing the behavior of the common operations?
So for all VM types, the user ABI would be:private->shared - Always zero's pageshared->private - Always destructiveshared->private (w/flag) - Always preserves data or return error if not possible
Do you see a problem?
Quoted 80 lines · Rick P
Quoted 32 lines · Vishal Annapurve
Quoted 15 lines · Rick P
Quoted 9 lines · Sean Christopherson
Quoted 8 lines
For TDX if we don't zero on conversion from
private->sharedwe will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.Quoted 3 lines
Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.
Quoted 6 lines
Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.
If the answer is that "always zero on private to shared conversions" for all CC VMs, then does the scheme outlined in [1] make sense for handling the private -> shared conversions? For pKVM, there can be a VM type check to avoid the zeroing during conversions and instead just zero on allocations. This allows delaying zeroing until the fault time for CC VMs and can be done in
guest_memfdcentrally. We will need more inputs from the SEV side for this discussion.Quoted 1 line
[1] https://lore.kernel.org/lkml/CAGtprH-83EOz8rrUjE+O8m7nUDjt=THyXx=kfft1xQry65mtQg@mail.gmail.com/
It's nice that we don't double zero (since TDX module will do it too) for private allocation/mapping. Seems ok to me.
Quoted 41 lines
Quoted 26 lines
Quoted 11 lines
Quoted 6 lines
Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning?
Because it's literally converting memory from shared to private? And IICU, it's
not a one-time provisioning, e.g. memory can go:Quoted 6 lines
shared => fill => private => consume => shared => fill => private => consume
Quoted 2 lines
Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)
Are you referring to this suggestion?
Yea, in general to make it a specific operation preserving operation.
Quoted 6 lines
: And maybe a new flag for
KVM_GMEM_CONVERT_PRIVATEfor user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.Quoted 7 lines
Quoted 5 lines
If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.Ok, we should POC how it works with TDX.
I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.
2) Shared to private conversions are always content-preserving for all VMs as far asguest_memfdis concerned.
3) Private to shared conversions are not content-preserving for CC VMs as far asguest_memfdis concerned, subject to more discussions.
Quoted 5 lines
Quoted 1 line
[2] https://lore.kernel.org/lkml/CAGtprH-Kzn2kOGZ4JuNtUT53Hugw64M-_XMmhz_gCiDS6BAFtQ@mail.gmail.com/
Right, I read that. I still don't see why pKVM needs to do normal private/shared conversion for data provisioning. Vs a dedicated operation/flag to make it a special case.
It's dictated by pKVM usecases, memory contents need to be preserved for every conversion not just for initial payload population.
Quoted 5 lines
I'm trying to suggest there could be a benefit to making all gmem VM types behave the same. If conversions are always content preserving for pKVM, why can't userspace always use the operation that says preserve content? Vs changing the behavior of the common operations?
I don't see a benefit of userspace passing a flag that's kind of default for the VM type (assuming pKVM will use a special VM type). Common operations in guest_memfd will need to either check for the userspace passed flag or the VM type, so no major change in guest_memfd implementation for either mechanism.
Quoted 9 lines
So for all VM types, the user ABI would be:
private->shared- Always zero's pageshared->private- Always destructiveshared->private(w/flag) - Always preserves data or return error if not possibleDo you see a problem?
Quoted 7 lines · Vishal Annapurve
Quoted 4 lines
Right, I read that. I still don't see why pKVM needs to do normal private/shared
conversion for data provisioning. Vs a dedicated operation/flag to make it a special case.It's dictated by pKVM usecases, memory contents need to be preserved for every conversion not just for initial payload population.
We are weighing pros/cons between:
- Unifying this uABI across all gmemfd VM types
- Userspace for one VM type passing a flag for it's special non-shared use case
I don't see how passing a flag or not is dictated by pKVM use case.
P.S. This doesn't really impact TDX I think. Except that TDX development needs to work in the code without bumping anything. So just wishing to work in code with less conditionals.
Quoted 9 lines
Quoted 6 lines
I'm trying to suggest there could be a benefit to making all gmem VM types behave the same. If conversions are always content preserving for pKVM, why can't userspace always use the operation that says preserve content? Vs changing the behavior of the common operations?
I don't see a benefit of userspace passing a flag that's kind of default for the VM type (assuming pKVM will use a special VM type).
The benefit is that we don't need to have special VM default behavior for gmemfd. Think about if some day (very hypothetical and made up) we want to add a mode for TDX that adds new private data to a running guest (with special accept on the guest side or something). Then we might want to add a flag to override the default destructive behavior. Then maybe pKVM wants to add a "don't preserve" operation and it adds a second flag to not destroy. Now gmemfd has lots of VM specific flags. The point of this example is to show how unified uABI can he helpful.
Quoted 3 lines
Common operations in
guest_memfdwill need to either check for the userspace passed flag or the VM type, so no major change inguest_memfdimplementation for either mechanism.
While we discuss ABI, we should allow ourselves to think ahead. So, is a gmemfd fd tied to a VM? I think there is interest in de-coupling it? Is the VM type sticky?
It seems the more they are separate, the better it will be to not have VM-aware behavior living in gmem.
Sean Christopherson
maintainerQuoted 6 lines · Rick P Edgecombe
Quoted 5 lines · Vishal Annapurve
Quoted 4 lines
Right, I read that. I still don't see why pKVM needs to do normal private/shared
conversion for data provisioning. Vs a dedicated operation/flag to make it a special case.
Quoted 8 lines
Quoted 2 lines
It's dictated by pKVM usecases, memory contents need to be preserved for every conversion not just for initial payload population.
We are weighing pros/cons between:
- Unifying this uABI across all gmemfd VM types
- Userspace for one VM type passing a flag for it's special non-shared use caseI don't see how passing a flag or not is dictated by pKVM use case.
Yep. Baking the behavior of a single usecase into the kernel's ABI is rarely a good idea. Just because pKVM's current usecases always wants contents to be preserved doesn't mean that pKVM will never change.
As a general rule, KVM should push policy to userspace whenever possible.
Quoted 14 lines
P.S. This doesn't really impact TDX I think. Except that TDX development needs to work in the code without bumping anything. So just wishing to work in code with less conditionals.Quoted 9 lines
Quoted 6 lines
I'm trying to suggest there could be a benefit to making all gmem VM types behave the same. If conversions are always content preserving for pKVM, why can't userspace always use the operation that says preserve content? Vs changing the behavior of the common operations?
I don't see a benefit of userspace passing a flag that's kind of default for the VM type (assuming pKVM will use a special VM type).
Quoted 8 lines
The benefit is that we don't need to have special VM default behavior for gmemfd. Think about if some day (very hypothetical and made up) we want to add a mode for TDX that adds new private data to a running guest (with special accept on the guest side or something). Then we might want to add a flag to override the default destructive behavior. Then maybe pKVM wants to add a "don't preserve" operation and it adds a second flag to not destroy. Now gmemfd has lots of VM specific flags. The point of this example is to show how unified uABI can he helpful.
Yep again. Pivoting on the VM type would be completely inflexible. If pKVM gains a usecase that wants to zero memory on conversions, we're hosed. If SNP or TDX gains the ability to preserve data on conversions, we're hosed.
The VM type may restrict what is possible, but (a) that should be abstracted, e.g. by defining the allowed flags during guest_memfd creation, and (b) the capabilities of the guest_memfd instance need to be communicated to userspace.
Quoted 6 lines
Quoted 3 lines
Common operations in
guest_memfdwill need to either check for the userspace passed flag or the VM type, so no major change inguest_memfdimplementation for either mechanism.While we discuss ABI, we should allow ourselves to think ahead. So, is a gmemfd fd tied to a VM?
Yes.
Quoted 1 line
I think there is interest in de-coupling it?
No? Even if we get to a point where multiple distinct VMs can bind to a single guest_memfd, e.g. for inter-VM shared memory, there will still need to be a sole owner of the memory. AFAICT, fully decoupling guest_memfd from a VM would add non-trivial complexity for zero practical benefit.
Quoted 4 lines
Is the VM type sticky?
It seems the more they are separate, the better it will be to not have VM-aware behavior living in gmem.
Ya. A guest_memfd instance may have capabilities/features that are restricted and/or defined based on the properties of the owning VM, but we should do our best to make guest_memfd itself blissly unaware of the VM type.
Quoted 3 lines · Sean Christopherson
Quoted 1 line
I think there is interest in de-coupling it?
No?
I'm talking about the intra-host migration/reboot optimization stuff. And not doing a good job, sorry.
Quoted 5 lines
Even if we get to a point where multiple distinct VMs can bind to a single
guest_memfd, e.g. for inter-VM shared memory, there will still need to be a sole
owner of the memory. AFAICT, fully decouplingguest_memfdfrom a VM would add non-trivial complexity for zero practical benefit.
I'm talking about moving a gmem fd between different VMs or something using KVM_LINK_GUEST_MEMFD [0]. Not advocating to try to support it. But trying to feel out where the concepts are headed. It kind of allows gmem fds (or just their source memory?) to live beyond a VM lifecycle.
[0] https://lore.kernel.org/all/[email protected]/
https://lore.kernel.org/kvm/[email protected]/
Sean Christopherson
maintainerQuoted 14 lines · Rick P Edgecombe
Quoted 3 lines · Sean Christopherson
Quoted 1 line
I think there is interest in de-coupling it?
No?
I'm talking about the intra-host migration/reboot optimization stuff. And not doing a good job, sorry.
Quoted 5 lines
Even if we get to a point where multiple distinct VMs can bind to a single
guest_memfd, e.g. for inter-VM shared memory, there will still need to be a sole
owner of the memory. AFAICT, fully decouplingguest_memfdfrom a VM would add non-trivial complexity for zero practical benefit.
Quoted 4 lines
I'm talking about moving a gmem fd between different VMs or something using
KVM_LINK_GUEST_MEMFD[0]. Not advocating to try to support it. But trying to feel out where the concepts are headed. It kind of allows gmem fds (or just their source memory?) to live beyond a VM lifecycle.
I think the answer is that we want to let guest_memfd live beyond the "struct kvm" instance, but not beyond the Virtual Machine. From a past discussion on this topic[*].
: No go. Because again, the inode (physical memory) is coupled to the virtual machine : as a thing, not to a "struct kvm". Or more concretely, the inode is coupled to an : ASID or an HKID, and there can be multiple "struct kvm" objects associated with a : single ASID. And at some point in the future, I suspect we'll have multiple KVM : objects per HKID too.
:
: The current SEV use case is for the migration helper, where two KVM objects share : a single ASID (the "real" VM and the helper). I suspect TDX will end up with : similar behavior where helper "VMs" can use the HKID of the "real" VM. For KVM, : that means multiple struct kvm objects being associated with a single HKID. :
: To prevent use-after-free, KVM "just" needs to ensure the helper instances can't : outlive the real instance, i.e. can't use the HKID/ASID after the owning virtual : machine has been destroyed.
:
: To put it differently, "struct kvm" is a KVM software construct that _usually_, : but not always, is associated 1:1 with a virtual machine.
:
: And FWIW, stashing the pointer without holding a reference would not be a complete : solution, because it couldn't guard against KVM reusing a pointer. E.g. if a : struct kvm was unbound and then freed, KVM could reuse the same memory for a new : struct kvm, with a different ASID/HKID, and get a false negative on the rebinding : check.
Exactly what that will look like in code is TBD, but the concept/logic holds up.
Quoted 4 lines · Sean Christopherson
I think the answer is that we want to let
guest_memfdlive beyond the "struct kvm" instance, but not beyond the Virtual Machine. From a past discussion on this topic[*].
[snip]
Quoted 3 lines
Exactly what that will look like in code is TBD, but the concept/logic holds up.
Thanks for digging this up. Makes sense. One gmemfd per VM, but struct kvm != a VM.
Quoted 48 lines · Sean Christopherson
Quoted 14 lines · Rick P Edgecombe
Quoted 3 lines · Sean Christopherson
Quoted 1 line
I think there is interest in de-coupling it?
No?
I'm talking about the intra-host migration/reboot optimization stuff. And not doing a good job, sorry.
Quoted 5 lines
Even if we get to a point where multiple distinct VMs can bind to a single
guest_memfd, e.g. for inter-VM shared memory, there will still need to be a sole
owner of the memory. AFAICT, fully decouplingguest_memfdfrom a VM would add non-trivial complexity for zero practical benefit.Quoted 4 lines
I'm talking about moving a gmem fd between different VMs or something using
KVM_LINK_GUEST_MEMFD[0]. Not advocating to try to support it. But trying to feel out where the concepts are headed. It kind of allows gmem fds (or just their source memory?) to live beyond a VM lifecycle.I think the answer is that we want to let
guest_memfdlive beyond the "struct kvm" instance, but not beyond the Virtual Machine. From a past discussion on this topic[*].: No go. Because again, the inode (physical memory) is coupled to the virtual machine : as a thing, not to a "struct kvm". Or more concretely, the inode is coupled to an : ASID or an HKID, and there can be multiple "struct kvm" objects associated with a : single ASID. And at some point in the future, I suspect we'll have multiple KVM : objects per HKID too.
:
: The current SEV use case is for the migration helper, where two KVM objects share : a single ASID (the "real" VM and the helper). I suspect TDX will end up with : similar behavior where helper "VMs" can use the HKID of the "real" VM. For KVM, : that means multiple struct kvm objects being associated with a single HKID. :
: To prevent use-after-free, KVM "just" needs to ensure the helper instances can't : outlive the real instance, i.e. can't use the HKID/ASID after the owning virtual : machine has been destroyed.
:
: To put it differently, "struct kvm" is a KVM software construct that _usually_, : but not always, is associated 1:1 with a virtual machine.
:
: And FWIW, stashing the pointer without holding a reference would not be a complete : solution, because it couldn't guard against KVM reusing a pointer. E.g. if a : struct kvm was unbound and then freed, KVM could reuse the same memory for a new : struct kvm, with a different ASID/HKID, and get a false negative on the rebinding : check.
Quoted 1 line
Exactly what that will look like in code is TBD, but the concept/logic holds up.
I think we can simplify the role of guest_memfd in line with discussion [1]:
1) guest_memfd is a memory provider for userspace, KVM, IOMMU.
- It allows fallocate to populate/deallocate memory
2) guest_memfd supports the notion of private/shared faults.
3) guest_memfd supports memory access control:
- It allows shared faults from userspace, KVM, IOMMU
- It allows private faults from KVM, IOMMU
4) guest_memfd supports changing access control on its ranges between shared/private.
- It notifies the users to invalidate their mappings for the
ranges getting converted/truncated.
Responsibilities that ideally should not be taken up by guest_memfd:
1) guest_memfd can not initiate pre-faulting on behalf of it's users.
2) guest_memfd should not be directly communicating with the underlying architecture layers.
- All communication should go via KVM/IOMMU.
3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with guest_memfd.
- Today KVM SNP logic ties RMP table entry lifetimes with how
long the folios are mapped in guest_memfd, which I think should be revisited.
Some very early thoughts on how guest_memfd could be laid out for the long term:
1) guest_memfd code ideally should be built-in to the kernel.
2) guest_memfd instances should still be created using KVM IOCTLs that carry specific capabilities/restrictions for its users based on the backing VM/arch.
3) Any outgoing communication from guest_memfd to it's users like userspace/KVM/IOMMU should be via notifiers to invalidate similar to how MMU notifiers work.
4) KVM and IOMMU can implement intermediate layers to handle interaction with guest_memfd.
- e.g. there could be a layer within kvm that handles:
- creating guest_memfd files and associating akvm_gmem_context with those files.
- memslot binding
- kvm_gmem_context will be used to bind kvm
memslots with the context ranges.
- invalidate notifier handling
- kvm_gmem_context will be used to interceptguest_memfd callbacks and
translate them to the right GPA ranges.
- linking
- kvm_gmem_context can be linked to different
KVM instances.
This line of thinking can allow cleaner separation between guest_memfd/KVM/IOMMU [2].
[1] https://lore.kernel.org/lkml/CAGtprH-+gPN8J_RaEit=M_ErHWTmFHeCipC6viT6PHhG3ELg6A@mail.gmail.com/#t
[2] https://lore.kernel.org/lkml/[email protected]/
Quoted 5 lines
Sean Christopherson
maintainerQuoted 1 line · Vishal Annapurve
I think we can simplify the role of
guest_memfdin line with discussion [1]:
I genuinely don't understand what you're trying to "simplify". We need to define an ABI that is flexible and robust, but beyond that most of these guidelines boil down to "don't write bad code".
Quoted 1 line
1)
guest_memfdis a memory provider for userspace, KVM, IOMMU.
No, guest_memfd is a memory provider for KVM guests. That memory *might* be mapped by userspace and/or into IOMMU page tables in order out of functional necessity, but guest_memfd exists solely to serve memory to KVM guests, full stop.
Quoted 3 lines
3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with
guest_memfd.
Again, please align your indentation.
Quoted 3 lines
- Today KVM SNP logic ties RMP table entry lifetimes with how long the folios are mapped in
guest_memfd, which I think should be revisited.
Why? Memslots are ephemeral per-"struct kvm" mappings. RMP entries and guest_memfd inodes are tied to the Virtual Machine, not to the "struct kvm" instance.
Quoted 2 lines
Some very early thoughts on how
guest_memfdcould be laid out for the long term:
1)guest_memfdcode ideally should be built-in to the kernel.
Why? How is this at all relevant? If we need to bake some parts of guest_memfd into the kernel in order to avoid nasty exports and/or ordering dependencies, then we can do so. But that is 100% an implementation detail and in no way a design goal.
Quoted 7 lines · Sean Christopherson
Quoted 1 line · Vishal Annapurve
I think we can simplify the role of
guest_memfdin line with discussion [1]:I genuinely don't understand what you're trying to "simplify". We need to define an ABI that is flexible and robust, but beyond that most of these guidelines boil down to "don't write bad code".
My goal for bringing this discussion up is to see if we can better define the role of guest_memfd and how it interacts with other layers, as I see some scenarios that can be improved like kvm_gmem_populate[1] where guest_memfd is trying to fault in pages on behalf of KVM.
[1] https://lore.kernel.org/lkml/[email protected]/
Quoted 6 lines
Quoted 2 lines
1)
guest_memfdis a memory provider for userspace, KVM, IOMMU.No,
guest_memfdis a memory provider for KVM guests. That memory *might* be mapped by userspace and/or into IOMMU page tables in order out of functional necessity, butguest_memfdexists solely to serve memory to KVM guests, full stop.
I look at this as guest_memfd should serve memory to KVM guests and to other users by following some KVM/Arch related guidelines e.g. for CC VMs, guest_memfd can handle certain behavior differently.
Quoted 5 lines
Quoted 4 lines
3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with
guest_memfd.
Quoted 8 lines
Again, please align your indentation.
Quoted 3 lines
- Today KVM SNP logic ties RMP table entry lifetimes with how long the folios are mapped in
guest_memfd, which I think should be revisited.Why? Memslots are ephemeral per-"struct kvm" mappings. RMP entries and
guest_memfdinodes are tied to the Virtual Machine, not to the "struct kvm" instance.
IIUC guest_memfd can only be accessed through the window of memslots and if there are no memslots I don't see the reason for memory still being associated with "virtual machine". Likely because I am yet to completely wrap my head around 'guest_memfd inodes are tied to the Virtual Machine, not to the "struct kvm" instance', I need to spend more time on this one.
Quoted 8 lines
Quoted 3 lines
Some very early thoughts on how
guest_memfdcould be laid out for the long term:
1)guest_memfdcode ideally should be built-in to the kernel.Why? How is this at all relevant? If we need to bake some parts of
guest_memfdinto the kernel in order to avoid nasty exports and/or ordering dependencies, then we can do so. But that is 100% an implementation detail and in no way a design goal.
I agree, this is implementation detail and we need real code to discuss this better.
Sean Christopherson
maintainerQuoted 5 lines · Vishal Annapurve
Quoted 4 lines · Sean Christopherson
Quoted 1 line · Vishal Annapurve
I think we can simplify the role of
guest_memfdin line with discussion [1]:
Quoted 8 lines
Quoted 3 lines
I genuinely don't understand what you're trying to "simplify". We need to define an ABI that is flexible and robust, but beyond that most of these guidelines boil down to "don't write bad code".
My goal for bringing this discussion up is to see if we can better define the role of
guest_memfdand how it interacts with other layers, as I see some scenarios that can be improved like kvm_gmem_populate[1] whereguest_memfdis trying to fault in pages on behalf of KVM.
Ah, gotcha. From my perspective, it's all just KVM, which is why I'm not feeling the same sense of urgency to formally define anything. We want to encapsulate code, have separate of concerns, etc., but I don't see that as being anything unique or special to guest_memfd. We try to achieve the same for all major areas of KVM, though obviously with mixed results :-)
Quoted 13 lines · Vishal Annapurve
Quoted 4 lines
Quoted 3 lines
3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with
guest_memfd.Quoted 8 lines
Again, please align your indentation.
Quoted 3 lines
- Today KVM SNP logic ties RMP table entry lifetimes with how long the folios are mapped in
guest_memfd, which I think should be revisited.Why? Memslots are ephemeral per-"struct kvm" mappings. RMP entries and
guest_memfdinodes are tied to the Virtual Machine, not to the "struct kvm" instance.
Quoted 7 lines
IIUC
guest_memfdcan only be accessed through the window of memslots and if there are no memslots I don't see the reason for memory still being associated with "virtual machine". Likely because I am yet to completely wrap my head around 'guest_memfdinodes are tied to the Virtual Machine, not to the "struct kvm" instance', I need to spend more time on this one.
I see the benefits of tying inodes to the virtual machine and different guest_memfd files to different KVM instances. This allows us to exercise intra-host migration usecases for TDX/SNP. But I think this model doesn't allow us to reuse guest_memfd files for SNP VMs during reboot.
Reboot scenario assuming reuse of existing guest_memfd inode for the next instance:
1) Create a VM
2) Create guest_memfd files that pin KVM instance
3) Create memslots
4) Start the VM
5) For reboot/shutdown, Execute VM specific Termination (e.g. KVM_TDX_TERMINATE_VM)
6) if allowed, delete the memslots
7) Create a new VM instance
8) Link the existing guest_memfd files to the new VM -> which creates new files for the same inode.
9) Close the existing guest_memfd files and the existing VM
10) Jump to step 3
The difference between SNP and TDX is that TDX memory ownership is limited to the duration the pages are mapped in the second stage secure EPT tables, whereas SNP/RMP memory ownership lasts beyond memslots and effectively remains till folios are punched out from guest_memfd filemap. IIUC CCA might follow the suite of SNP in this regard with the pfns populated in GPT entries.
I don't have a sense of how critical this problem could be, but this would mean for every reboot all large memory allocations will have to let go and need to be reallocated. For 1G support, we will be freeing guest_memfd pages using a background thread which may add some delays in being able to free up the memory in time.
Instead if we did this:
1) Support creating guest_memfd files for a certain VM type that allows KVM to dictate the behavior of the guest_memfd.
2) Tie lifetime of KVM SNP/TDX memory ownership with guest_memfd and memslot bindings
- Each binding will increase a refcount on both guest_memfd file
and KVM, so both can't go away while the binding exists.
3) For SNP/CCA, pfns are invalidated from RMP/GPT tables during unbind operations while for TDX, KVM will invalidate secure EPT entries.
This can allow us to decouple memory lifecycle from VM lifecycle and match the behavior with non-confidential VMs where memory can outlast VMs. Though this approach will mean change in intrahost migration implementation as we don't need to differentiate guest_memfd files and inodes.
That being said, I might be missing something here and I don't have any data to back the criticality of this usecase for SNP and possibly CCA VMs.
Quoted 57 lines · Vishal Annapurve
Quoted 13 lines · Vishal Annapurve
Quoted 4 lines
Quoted 3 lines
3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with
guest_memfd.Quoted 8 lines
Again, please align your indentation.
Quoted 3 lines
- Today KVM SNP logic ties RMP table entry lifetimes with how long the folios are mapped in
guest_memfd, which I think should be revisited.Why? Memslots are ephemeral per-"struct kvm" mappings. RMP entries and
guest_memfdinodes are tied to the Virtual Machine, not to the "struct kvm" instance.Quoted 7 lines
IIUC
guest_memfdcan only be accessed through the window of memslots and if there are no memslots I don't see the reason for memory still being associated with "virtual machine". Likely because I am yet to completely wrap my head around 'guest_memfdinodes are tied to the Virtual Machine, not to the "struct kvm" instance', I need to spend more time on this one.I see the benefits of tying inodes to the virtual machine and different
guest_memfdfiles to different KVM instances. This allows us to exercise intra-host migration usecases for TDX/SNP. But I think this model doesn't allow us to reuseguest_memfdfiles for SNP VMs during reboot.Reboot scenario assuming reuse of existing
guest_memfdinode for the next instance:
1) Create a VM
2) Createguest_memfdfiles that pin KVM instance
3) Create memslots
4) Start the VM
5) For reboot/shutdown, Execute VM specific Termination (e.g.KVM_TDX_TERMINATE_VM)
6) if allowed, delete the memslots
7) Create a new VM instance
8) Link the existingguest_memfdfiles to the new VM -> which creates new files for the same inode.
9) Close the existingguest_memfdfiles and the existing VM
10) Jump to step 3The difference between SNP and TDX is that TDX memory ownership is limited to the duration the pages are mapped in the second stage secure EPT tables, whereas SNP/RMP memory ownership lasts beyond memslots and effectively remains till folios are punched out from
guest_memfdfilemap. IIUC CCA might follow the suite of SNP in this regard with the pfns populated in GPT entries.I don't have a sense of how critical this problem could be, but this would mean for every reboot all large memory allocations will have to let go and need to be reallocated. For 1G support, we will be freeing
guest_memfdpages using a background thread which may add some delays in being able to free up the memory in time.
Quoted 7 lines
Instead if we did this:
1) Support creatingguest_memfdfiles for a certain VM type that allows KVM to dictate the behavior of theguest_memfd.
2) Tie lifetime of KVM SNP/TDX memory ownership withguest_memfdand memslot bindings
- Each binding will increase a refcount on bothguest_memfdfile
and KVM, so both can't go away while the binding exists.
I think if we can ensure that any guest_memfd initiated interaction with KVM is only for invalidation and is based on binding and under filemap_invalidate_lock then there is no need to pin KVM on each binding, as binding/unbinding should be protected using filemap_invalidate_lock and so KVM can't go away during invalidation.
Quoted 12 lines
3) For SNP/CCA, pfns are invalidated from RMP/GPT tables during unbind operations while for TDX, KVM will invalidate secure EPT entries.
This can allow us to decouple memory lifecycle from VM lifecycle and match the behavior with non-confidential VMs where memory can outlast VMs. Though this approach will mean change in intrahost migration implementation as we don't need to differentiate
guest_memfdfiles and inodes.That being said, I might be missing something here and I don't have any data to back the criticality of this usecase for SNP and possibly CCA VMs.
Quoted 11 lines · Vishal Annapurve
I think we can simplify the role of
guest_memfdin line with discussion [1]:
1)guest_memfdis a memory provider for userspace, KVM, IOMMU.
- It allows fallocate to populate/deallocate memory
2)guest_memfdsupports the notion of private/shared faults.
3)guest_memfdsupports memory access control:
- It allows shared faults from userspace, KVM, IOMMU
- It allows private faults from KVM, IOMMU
4)guest_memfdsupports changing access control on its ranges between shared/private.
- It notifies the users to invalidate their mappings for the
ranges getting converted/truncated.
KVM needs to know if a GFN is private/shared. I think it is also intended to now be a repository for this information, right? Besides invalidations, it needs to be queryable.
Quoted 6 lines
Responsibilities that ideally should not be taken up by
guest_memfd:
1)guest_memfdcan not initiate pre-faulting on behalf of it's users.
2)guest_memfdshould not be directly communicating with the underlying architecture layers.
- All communication should go via KVM/IOMMU.
Maybe stronger, there should be generic gmem behaviors. Not any special if (vm_type == tdx) type logic.
Quoted 6 lines
3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with
guest_memfd.
- Today KVM SNP logic ties RMP table entry lifetimes with how
long the folios are mapped inguest_memfd, which I think should be revisited.
I don't understand the problem. KVM needs to respond to user accessible invalidations, but how long it keeps other resources around could be useful for various optimizations. Like deferring work to a work queue or something.
I think it would help to just target the ackerly series goals. We should get that code into shape and this kind of stuff will fall out of it.
Quoted 16 lines
Some very early thoughts on how
guest_memfdcould be laid out for the long term:
1)guest_memfdcode ideally should be built-in to the kernel.
2)guest_memfdinstances should still be created using KVM IOCTLs that carry specific capabilities/restrictions for its users based on the backing VM/arch.
3) Any outgoing communication fromguest_memfdto it's users like userspace/KVM/IOMMU should be via notifiers to invalidate similar to how MMU notifiers work.
4) KVM and IOMMU can implement intermediate layers to handle interaction withguest_memfd.
- e.g. there could be a layer within kvm that handles:
- creatingguest_memfdfiles and associating akvm_gmem_contextwith those files.
- memslot binding
-kvm_gmem_contextwill be used to bind kvm
Quoted 8 lines
memslots with the context ranges.
- invalidate notifier handling
-kvm_gmem_contextwill be used to interceptguest_memfdcallbacks and
translate them to the right GPA ranges.
- linking
-kvm_gmem_contextcan be linked to different
KVM instances.
We can probably look at the code to decide these.
Quoted 14 lines
This line of thinking can allow cleaner separation between guest_memfd/KVM/IOMMU [2].
[1] https://lore.kernel.org/lkml/CAGtprH-+gPN8J_RaEit=M_ErHWTmFHeCipC6viT6PHhG3ELg6A@mail.gmail.com/#t
[2] https://lore.kernel.org/lkml/[email protected]/Quoted 5 lines
Quoted 14 lines · Rick P
Quoted 11 lines · Vishal Annapurve
I think we can simplify the role of
guest_memfdin line with discussion [1]:
1)guest_memfdis a memory provider for userspace, KVM, IOMMU.
- It allows fallocate to populate/deallocate memory
2)guest_memfdsupports the notion of private/shared faults.
3)guest_memfdsupports memory access control:
- It allows shared faults from userspace, KVM, IOMMU
- It allows private faults from KVM, IOMMU
4)guest_memfdsupports changing access control on its ranges between shared/private.
- It notifies the users to invalidate their mappings for the
ranges getting converted/truncated.
Quoted 3 lines
KVM needs to know if a GFN is private/shared. I think it is also intended to now be a repository for this information, right? Besides invalidations, it needs to be queryable.
Yeah, that interface can be added as well. Though, if possible KVM can just directly pass the fault type to guest_memfd and it can return an error if the fault type doesn't match the permission. Additionally KVM does query the mapping order for a certain pfn/gfn which will need to be supported as well.
Quoted 18 lines
Quoted 7 lines
Responsibilities that ideally should not be taken up by
guest_memfd:
1)guest_memfdcan not initiate pre-faulting on behalf of it's users.
2)guest_memfdshould not be directly communicating with the underlying architecture layers.
- All communication should go via KVM/IOMMU.Maybe stronger, there should be generic gmem behaviors. Not any special if (
vm_type== tdx) type logic.Quoted 6 lines
3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with
guest_memfd.
- Today KVM SNP logic ties RMP table entry lifetimes with how
long the folios are mapped inguest_memfd, which I think should be revisited.
Quoted 3 lines
I don't understand the problem. KVM needs to respond to user accessible invalidations, but how long it keeps other resources around could be useful for various optimizations. Like deferring work to a work queue or something.
I don't think it could be deferred to a work queue as the RMP table entries will need to be removed synchronously once the last reference on the guest_memfd drops, unless memory itself is kept around after filemap eviction. I can see benefits of this approach for handling scenarios like intrahost-migration.
Quoted 29 lines
I think it would help to just target the ackerly series goals. We should get that code into shape and this kind of stuff will fall out of it.
Quoted 16 lines
Some very early thoughts on how
guest_memfdcould be laid out for the long term:
1)guest_memfdcode ideally should be built-in to the kernel.
2)guest_memfdinstances should still be created using KVM IOCTLs that carry specific capabilities/restrictions for its users based on the backing VM/arch.
3) Any outgoing communication fromguest_memfdto it's users like userspace/KVM/IOMMU should be via notifiers to invalidate similar to how MMU notifiers work.
4) KVM and IOMMU can implement intermediate layers to handle interaction withguest_memfd.
- e.g. there could be a layer within kvm that handles:
- creatingguest_memfdfiles and associating akvm_gmem_contextwith those files.
- memslot binding
-kvm_gmem_contextwill be used to bind kvmQuoted 8 lines
memslots with the context ranges.
- invalidate notifier handling
-kvm_gmem_contextwill be used to interceptguest_memfdcallbacks and
translate them to the right GPA ranges.
- linking
-kvm_gmem_contextcan be linked to different
KVM instances.
Quoted 2 lines
We can probably look at the code to decide these.
Agree.
Quoted 46 lines · Sean Christopherson
Quoted 6 lines · Rick P Edgecombe
Quoted 5 lines · Vishal Annapurve
Quoted 4 lines
Right, I read that. I still don't see why pKVM needs to do normal private/shared
conversion for data provisioning. Vs a dedicated operation/flag to make it a special case.Quoted 8 lines
Quoted 2 lines
It's dictated by pKVM usecases, memory contents need to be preserved for every conversion not just for initial payload population.
We are weighing pros/cons between:
- Unifying this uABI across all gmemfd VM types
- Userspace for one VM type passing a flag for it's special non-shared use caseI don't see how passing a flag or not is dictated by pKVM use case.
Yep. Baking the behavior of a single usecase into the kernel's ABI is rarely a good idea. Just because pKVM's current usecases always wants contents to be preserved doesn't mean that pKVM will never change.
As a general rule, KVM should push policy to userspace whenever possible.
Quoted 14 lines
P.S. This doesn't really impact TDX I think. Except that TDX development needs to work in the code without bumping anything. So just wishing to work in code with less conditionals.Quoted 9 lines
Quoted 6 lines
I'm trying to suggest there could be a benefit to making all gmem VM types behave the same. If conversions are always content preserving for pKVM, why can't userspace always use the operation that says preserve content? Vs changing the behavior of the common operations?
I don't see a benefit of userspace passing a flag that's kind of default for the VM type (assuming pKVM will use a special VM type).
Quoted 8 lines
The benefit is that we don't need to have special VM default behavior for gmemfd. Think about if some day (very hypothetical and made up) we want to add a mode for TDX that adds new private data to a running guest (with special accept on the guest side or something). Then we might want to add a flag to override the default destructive behavior. Then maybe pKVM wants to add a "don't preserve" operation and it adds a second flag to not destroy. Now gmemfd has lots of VM specific flags. The point of this example is to show how unified uABI can he helpful.
Quoted 7 lines
Yep again. Pivoting on the VM type would be completely inflexible. If pKVM gains a usecase that wants to zero memory on conversions, we're hosed. If SNP or TDX gains the ability to preserve data on conversions, we're hosed.
The VM type may restrict what is possible, but (a) that should be abstracted, e.g. by defining the allowed flags during
guest_memfdcreation, and (b) the capabilities of theguest_memfdinstance need to be communicated to userspace.
Ok, I concur with this: It's beneficial to keep a unified ABI that allows guest_memfd to make runtime decisions without relying on VM type as far as possible.
Few points that seem important here:
1) Userspace can and should be able to only dictate if memory contents need to be preserved on shared to private conversion.
-> For SNP/TDX VMs:
* Only usecase for preserving contents is initial memory
population, which can be achieved by:
- Userspace converting the ranges to shared,
populating the contents, converting them back to private and then calling SNP/TDX specific existing ABI functions.
* For runtime conversions, guest_memfd can't ensure memory
contents are preserved during shared to private conversions as the architectures don't support that behavior.
* So IMO, this "preserve" flag doesn't make sense for SNP/TDX
VMs, even if we add this flag, today guest_memfd should effectively mark this unsupported based on the backing architecture support.
2) For pKVM, if userspace wants to specify a "preserve" flag then this flag can be allowed based on the known capabilities of the backing architecture.
So this topic is still orthogonal to "zeroing on private to shared conversion".
Quoted 25 lines
Quoted 7 lines
Quoted 4 lines
Common operations in
guest_memfdwill need to either check for the userspace passed flag or the VM type, so no major change inguest_memfdimplementation for either mechanism.While we discuss ABI, we should allow ourselves to think ahead. So, is a gmemfd fd tied to a VM?
Yes.
Quoted 1 line
I think there is interest in de-coupling it?
No? Even if we get to a point where multiple distinct VMs can bind to a single
guest_memfd, e.g. for inter-VM shared memory, there will still need to be a sole owner of the memory. AFAICT, fully decouplingguest_memfdfrom a VM would add non-trivial complexity for zero practical benefit.Quoted 4 lines
Is the VM type sticky?
It seems the more they are separate, the better it will be to not have VM-aware behavior living in gmem.
Ya. A
guest_memfdinstance may have capabilities/features that are restricted and/or defined based on the properties of the owning VM, but we should do our best to makeguest_memfditself blissly unaware of the VM type.
Sean Christopherson
maintainerQuoted 4 lines · Vishal Annapurve
On Tue, Jul 8, 2025 at 11:03 AM Sean Christopherson <[email protected]> wrote:
Few points that seem important here:
1) Userspace can and should be able to only dictate if memory contents need to be preserved on shared to private conversion.
No, I was wrong, pKVM has use cases where it's desirable to preserve data on private => shared conversions.
Side topic, if you're going to use fancy indentation, align the indentation so it's actually readable.
Quoted 10 lines
-> For SNP/TDX VMs:
* Only usecase for preserving contents is initial memory population, which can be achieved by:
- Userspace converting the ranges to shared, populating the contents, converting them back to private and then calling SNP/TDX specific existing ABI functions.
* For runtime conversions,guest_memfdcan't ensure memory contents are preserved during shared to private conversions as the architectures don't support that behavior.
* So IMO, this "preserve" flag doesn't make sense for SNP/TDX VMs, even
It makes sense, it's just not supported by the architecture *at runtime*. Case in point, *something* needs to allow preserving data prior to launching the VM. If we want to go with the PRIVATE => SHARED => FILL => PRIVATE approach for TDX and SNP, then we'll probably want to allow PRESERVE only until the VM image is finalized.
Quoted 4 lines
if we add this flag, today
guest_memfdshould effectively mark this unsupported based on the backing architecture support.2) For pKVM, if userspace wants to specify a "preserve" flag then this
There is no "For pKVM". We are defining uAPI for guest_memfd. I.e. this statement holds true for all implementations: PRESERVE is allowed based on the capabilities of the architecture.
Quoted 1 line
So this topic is still orthogonal to "zeroing on private to shared conversion".
As above, no. pKVM might not expose PRESERVE to _userspace_ since all current conversions are initiated by the guest, but for guest_memfd itself, this is all one and the same.
Quoted 24 lines · Sean Christopherson
Quoted 4 lines · Vishal Annapurve
On Tue, Jul 8, 2025 at 11:03 AM Sean Christopherson <[email protected]> wrote:
Few points that seem important here:
1) Userspace can and should be able to only dictate if memory contents need to be preserved on shared to private conversion.No, I was wrong, pKVM has use cases where it's desirable to preserve data on private => shared conversions.
Side topic, if you're going to use fancy indentation, align the indentation so it's actually readable.
Quoted 10 lines
-> For SNP/TDX VMs:
* Only usecase for preserving contents is initial memory population, which can be achieved by:
- Userspace converting the ranges to shared, populating the contents, converting them back to private and then calling SNP/TDX specific existing ABI functions.
* For runtime conversions,guest_memfdcan't ensure memory contents are preserved during shared to private conversions as the architectures don't support that behavior.
* So IMO, this "preserve" flag doesn't make sense for SNP/TDX VMs, even
Quoted 5 lines
It makes sense, it's just not supported by the architecture *at runtime*. Case in point, *something* needs to allow preserving data prior to launching the VM. If we want to go with the PRIVATE => SHARED => FILL => PRIVATE approach for TDX and SNP, then we'll probably want to allow PRESERVE only until the VM image is finalized.
Maybe we can simplify the story a bit here for today, how about:
1) For shared to private conversions:
* Is it safe to say that the conversion itself is always
content preserving, it's upto the
architecture what it does with memory contents on the private faults?
- During initial memory setup, userspace can control
how private memory would
be faulted in by architecture supported ABI operations.
- After initial memory setup, userspace can't control
how private memory would
be faulted in.
2) For private to shared conversions:
* Architecture decides what should be done with the memory on
shared faults.
- guest_memfd can query architecture whether to zero
memory or not.
-> guest_memfd will only take on the responsibility of zeroing if needed by the architecture on shared faults.
-> Architecture is responsible for the behavior on private faults.
In future, if there is a usecase for controlling runtime behavior of private faults, architecture can expose additional ABI that userspace can use after initiating guest_memfd conversion.
Sean Christopherson
maintainerQuoted 24 lines · Vishal Annapurve
Quoted 15 lines · Rick P
Quoted 9 lines · Sean Christopherson
Quoted 8 lines
For TDX if we don't zero on conversion from
private->sharedwe will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.Quoted 3 lines
Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.
Quoted 6 lines
Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.
Quoted 2 lines
If the answer is that "always zero on private to shared conversions" for all CC VMs,
pKVM VMs *are* CoCo VMs. Just because pKVM doesn't rely on third party firmware to provide confidentiality and integrity doesn't make it any less of a CoCo VM.
Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
: And maybe a new flag for
KVM_GMEM_CONVERT_PRIVATEfor user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.
Quoted 4 lines
Quoted 1 line
Ok, we should POC how it works with TDX.
I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.
No? Perserving contents on private => shared is a security vulnerability waiting to happen.
Quoted 2 lines
2) Shared to private conversions are always content-preserving for all VMs as far as
guest_memfdis concerned.
There is no "as far as guest_memfd is concerned". Userspace doesn't care whether code lives in guest_memfd.c versus arch/xxx/kvm, the only thing that matters is the behavior that userspace sees. I don't want to end up with userspace ABI that is vendor/VM specific.
Quoted 4 lines
3) Private to shared conversions are not content-preserving for CC VMs as far as
guest_memfdis concerned, subject to more discussions.[2] https://lore.kernel.org/lkml/CAGtprH-Kzn2kOGZ4JuNtUT53Hugw64M-_XMmhz_gCiDS6BAFtQ@mail.gmail.com/
Hi Sean,
Quoted 45 lines · Sean Christopherson
Quoted 24 lines · Vishal Annapurve
Quoted 15 lines · Rick P
Quoted 9 lines · Sean Christopherson
Quoted 8 lines
For TDX if we don't zero on conversion from
private->sharedwe will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.Quoted 3 lines
Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.
Quoted 6 lines
Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.
Quoted 2 lines
If the answer is that "always zero on private to shared conversions" for all CC VMs,
pKVM VMs *are* CoCo VMs. Just because pKVM doesn't rely on third party firmware to provide confidentiality and integrity doesn't make it any less of a CoCo VM.
Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
: And maybe a new flag for
KVM_GMEM_CONVERT_PRIVATEfor user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.
Quoted 7 lines
Quoted 4 lines
Quoted 1 line
Ok, we should POC how it works with TDX.
I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.No? Perserving contents on private => shared is a security vulnerability waiting to happen.
Actually it is one of the requirements for pKVM as well as its current behavior. We would like to preserve contents both ways, private <=> shared, since it is required by some of the potential use cases (e.g., guest handling video encoding/decoding).
To make it clear, I'm talking about explicit sharing from the guest, not relinquishing memory back to the host. In the case of relinquishing (and guest teardown), relinquished memory is poisoned (zeroed) in pKVM.
Cheers,
/fuad
Quoted 12 lines
Quoted 2 lines
2) Shared to private conversions are always content-preserving for all VMs as far as
guest_memfdis concerned.There is no "as far as
guest_memfdis concerned". Userspace doesn't care whether code lives inguest_memfd.cversusarch/xxx/kvm, the only thing that matters is the behavior that userspace sees. I don't want to end up with userspace ABI that is vendor/VM specific.Quoted 4 lines
3) Private to shared conversions are not content-preserving for CC VMs as far as
guest_memfdis concerned, subject to more discussions.[2] https://lore.kernel.org/lkml/CAGtprH-Kzn2kOGZ4JuNtUT53Hugw64M-_XMmhz_gCiDS6BAFtQ@mail.gmail.com/
Sean Christopherson
maintainerQuoted 11 lines · Fuad Tabba
Quoted 5 lines
Quoted 2 lines
I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.No? Perserving contents on private => shared is a security vulnerability waiting to happen.
Actually it is one of the requirements for pKVM as well as its current behavior. We would like to preserve contents both ways, private <=> shared, since it is required by some of the potential use cases (e.g., guest handling video encoding/decoding).
Quoted 4 lines
To make it clear, I'm talking about explicit sharing from the guest, not relinquishing memory back to the host. In the case of relinquishing (and guest teardown), relinquished memory is poisoned (zeroed) in pKVM.
I forget, what's the "explicit sharing" flow look like? E.g. how/when does pKVM know it's ok to convert memory from private to shared? I think we'd still want to make data preservation optional, e.g. to avoid potential leakage with setups where memory is private by default, but a flag in KVM's uAPI might not be a good fit since whether or not to preserve data is more of a guest decision (or at least needs to be ok'd by the guest).
Quoted 18 lines · Sean Christopherson
Quoted 11 lines · Fuad Tabba
Quoted 5 lines
Quoted 2 lines
I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.No? Perserving contents on private => shared is a security vulnerability waiting to happen.
Actually it is one of the requirements for pKVM as well as its current behavior. We would like to preserve contents both ways, private <=> shared, since it is required by some of the potential use cases (e.g., guest handling video encoding/decoding).
Quoted 4 lines
To make it clear, I'm talking about explicit sharing from the guest, not relinquishing memory back to the host. In the case of relinquishing (and guest teardown), relinquished memory is poisoned (zeroed) in pKVM.
Quoted 6 lines
I forget, what's the "explicit sharing" flow look like? E.g. how/when does pKVM know it's ok to convert memory from private to shared? I think we'd still want to make data preservation optional, e.g. to avoid potential leakage with setups where memory is private by default, but a flag in KVM's uAPI might not be a good fit since whether or not to preserve data is more of a guest decision (or at least needs to be ok'd by the guest).
In pKVM all sharing and unsharing is triggered by the guest via hypercalls. The host cannot unshare. That said, making data preservation optional works for pKVM and is a good idea, for the reasons that you've mentioned.
Cheers,
/fuad
Quoted 26 lines · Fuad Tabba
Quoted 18 lines · Sean Christopherson
Quoted 11 lines · Fuad Tabba
Quoted 5 lines
Quoted 2 lines
I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.No? Perserving contents on private => shared is a security vulnerability waiting to happen.
Actually it is one of the requirements for pKVM as well as its current behavior. We would like to preserve contents both ways, private <=> shared, since it is required by some of the potential use cases (e.g., guest handling video encoding/decoding).
Quoted 4 lines
To make it clear, I'm talking about explicit sharing from the guest, not relinquishing memory back to the host. In the case of relinquishing (and guest teardown), relinquished memory is poisoned (zeroed) in pKVM.
Quoted 6 lines
I forget, what's the "explicit sharing" flow look like? E.g. how/when does pKVM know it's ok to convert memory from private to shared? I think we'd still want to make data preservation optional, e.g. to avoid potential leakage with setups where memory is private by default, but a flag in KVM's uAPI might not be a good fit since whether or not to preserve data is more of a guest decision (or at least needs to be ok'd by the guest).
Quoted 2 lines
In pKVM all sharing and unsharing is triggered by the guest via hypercalls. The host cannot unshare.
In pKVM's case, would the conversion ioctl be disabled completely, or would the ioctl be allowed, but conversion always checks with pKVM to see if the guest had previously requested a unshare?
Quoted 6 lines
That said, making data
preservation optional works for pKVM and is a good idea, for the reasons that you've mentioned.Cheers,
/fuad
Quoted 7 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.[...]
At the guest_memfd upstream call today (2025-06-26), we talked about when to merge folios with respect to conversions.
Just want to call out that in this RFCv2, we managed to get conversions working with merges happening as soon as possible.
"As soon as possible" means merges happen as long as shareability is all private (or all meaningless) within an aligned hugepage range. We try to merge after every conversion request and on truncation. On truncation, shareability becomes meaningless.
On explicit truncation (e.g. fallocate(PUNCH_HOLE)), truncation can fail if there are unexpected refcounts (because we can't merge with unexpected refcounts). Explicit truncation will succeed only if refcounts are expected, and merge is performed before finally removing from filemap.
On truncation caused by file close or inode release, guest_memfd may not hold the last refcount on the folio. Only in this case, we defer merging to the folio_put() callback, and because the callback can be called from atomic context, the merge is further deferred to be performed by a kernel worker.
Deferment of merging is already minimized so that most of the restructuring is synchronous with some userspace-initiated action (conversion or explicit truncation). The only deferred merge is when the file is closed, and in that case there's no way to reject/fail this file close.
(There are possible optimizations here - Yan suggested [1] checking if the folio_put() was called from interrupt context - I have not tried implementing that yet)
I did propose an explicit guest_memfd merge ioctl, but since RFCv2 works, I was thinking to to have the merge ioctl be a separate optimization/project/patch series if it turns out that merging as-soon-as-possible is an inefficient strategy, or if some VM use cases prefer to have an explicit merge ioctl.
During the call, Michael also brought up that SNP adds some constraints with respect to guest accepting pages/levels.
Could you please expand on that? Suppose for an SNP guest,
1. Guest accepted a page at 2M level
2. Guest converts a 4K sub page to shared
3. guest_memfd requests unmapping of the guest-requested 4K range (the rest of the 2M remains mapped into stage 2 page tables)
4. guest_memfd splits the huge page to 4K pages (the 4K is set to SHAREABILITY_ALL, the rest of the 2M is still SHAREABILITY_GUEST)
Can the SNP guest continue to use the rest of the 2M page or must it re-accept all the pages at 4K?
And for the reverse:
1. Guest accepted a 2M range at 4K
2. guest_memfd merges the full 2M range to a single 2M page
Must the SNP guest re-accept at 2M for the guest to continue functioning, or will the SNP guest continue to work (just with poorer performance than if the memory was accepted at 2M)?
[1] https://lore.kernel.org/all/aDfT35EsYP%[email protected]/
cover QEMU: Enable in-place conversion and hugetlb gmem
In reply to Ackerley TngHi all,
This is the POC to enable in-place conversion and hugetlb support of gmem (guest memfd) in QEMU. It can work with 1G gmem support series[1] and TDX hugepage support series[2] to run TDX guest with hugepage. I don't have SNP environment and don't know how it goes with SNP.
It is just the POC and we share it to show how QEMU work with gmem ABI.
The POC uses the simple implementation that switches to use in-place conversion and hugetlb when it is supported and it doesn't introduce new interface in QEMU so that existing command line to boot TDX can work without any change.
Please go to each patch (specifically patch 3/4/5) to discuss the ABI usage, potential issue, and maybe the upstreamable design.
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
Xiaoyao Li (4):
update-linux-headers: Add guestmem.h
headers: Fetch gmem updates
memory/guest_memfd: Enable hugetlb support
[HACK] memory: Don't enable in-place conversion for internal
MemoryRegion with gmem
Yan Zhao (1):
memory/guest_memfd: Enable in-place conversion when available
accel/kvm/kvm-all.c | 82 ++++++++++++++++++++++++--------- accel/stubs/kvm-stub.c | 2 + include/system/kvm.h | 2 + include/system/memory.h | 5 ++ include/system/ramblock.h | 1 + linux-headers/linux/guestmem.h | 29 ++++++++++++ linux-headers/linux/kvm.h | 18 ++++++++ scripts/update-linux-headers.sh | 2 +- system/memory.c | 9 +++- system/physmem.c | 40 ++++++++++++++-- 10 files changed, 163 insertions(+), 27 deletions(-) create mode 100644 linux-headers/linux/guestmem.h
Signature · 1 line
2.43.0
PATCH 1/5 update-linux-headers: Add guestmem.h
--- scripts/update-linux-headers.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/update-linux-headers.sh +1 -1
@@ -200,7 +200,7 @@ rm -rf "$output/linux-headers/linux" mkdir -p "$output/linux-headers/linux" for header in const.h stddef.h kvm.h vfio.h vfio_ccw.h vfio_zdev.h vhost.h \ psci.h psp-sev.h userfaultfd.h memfd.h mman.h nvme_ioctl.h \ - vduse.h iommufd.h bits.h; do + vduse.h iommufd.h bits.h guestmem.h; do cp "$hdrdir/include/linux/$header" "$output/linux-headers/linux" done
Signature · 1 line
2.43.0
PATCH 2/5 headers: Fetch gmem updates
In reply to Xiaoyao Li--- linux-headers/linux/guestmem.h | 29 +++++++++++++++++++++++++++++ linux-headers/linux/kvm.h | 18 ++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 linux-headers/linux/guestmem.h
linux-headers/linux/guestmem.h new file +29 -0
@@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _LINUX_GUESTMEM_H +#define _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 /* _LINUX_GUESTMEM_H */
linux-headers/linux/kvm.h +18 -0
@@ -952,6 +952,9 @@ struct kvm_enable_cap {#define KVM_CAP_ARM_EL2 240#define KVM_CAP_ARM_EL2_E2H0 241#define KVM_CAP_RISCV_MP_STATE_RESET 242 +#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;
@@ -1589,12 +1592,27 @@ struct kvm_memory_attributes {#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) +#define GUEST_MEMFD_FLAG_HUGETLB (1UL << 2) +struct kvm_create_guest_memfd {__u64 size;__u64 flags;__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 {
Signature · 1 line
2.43.0
PATCH 3/5 memory/guest_memfd: Enable in-place conversion when available
In reply to Xiaoyao LiFrom: Yan Zhao <[email protected]>
(This is just the POC code to use in-place conversion gmem.)
Try to use in-place conversion gmem when it is supported.
When in-place conversion is enabled, there is no need to discard memory since it still needs to be used as the memory of opposite attribute after conversion.
For a upstreamable solution, we can introduce memory-backend-guestmemfd for in-place conversion. With the non in-place conversion, it needs seperate non-gmem memory to back the shared memory and gmem is created implicitly and internally based on vm type. While with in-place conversion, there is no need for seperate non-gmem memory because gmem itself can be served as shared memory. So that we can introduce memory-backend-guestmemfd as the specific backend for in-place conversion gmem.
Co-developed-by Xiaoyao Li <[email protected]>
--- accel/kvm/kvm-all.c | 79 ++++++++++++++++++++++++++++----------- accel/stubs/kvm-stub.c | 1 + include/system/kvm.h | 1 + include/system/memory.h | 2 + include/system/ramblock.h | 1 + system/memory.c | 7 ++++ system/physmem.c | 21 ++++++++++- 7 files changed, 90 insertions(+), 22 deletions(-)
accel/kvm/kvm-all.c +58 -21
@@ -105,6 +105,7 @@ static int kvm_sstep_flags;static bool kvm_immediate_exit;static uint64_t kvm_supported_memory_attributes;static bool kvm_guest_memfd_supported; +bool kvm_guest_memfd_inplace_supported;static hwaddr kvm_max_slot_size = ~0 ;static const KVMCapabilityInfo kvm_required_capabilites[] = {
@@ -1487,6 +1488,30 @@ static int kvm_set_memory_attributes(hwaddr start, uint64_t size, uint64_t attr)return r; } +static int kvm_set_guest_memfd_shareability (MemoryRegion *mr,ram_addr_t offset, +uint64_t size,bool shared) +{ +int guest_memfd = mr->ram_block->guest_memfd; +struct kvm_gmem_convert param = { + .offset = offset, + .size = size, + .error_offset =0 , + }; +unsigned long op; +int r; + + op = shared ?KVM_GMEM_CONVERT_SHARED :KVM_GMEM_CONVERT_PRIVATE ; + + r =ioctl (guest_memfd, op, ¶m); +if (r) { +error_report ("failed to set guest_memfd offset 0x%lx size 0x%lx to %s " +"error '%s' error offset 0x%llx" , + offset, size, shared ?"shared" :"private" , +strerror (errno), param.error_offset); + } +return r; +} +int kvm_set_memory_attributes_private (hwaddr start,uint64_t size) {return kvm_set_memory_attributes (start, size,KVM_MEMORY_ATTRIBUTE_PRIVATE );
@@ -1604,7 +1629,8 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,abort (); } -if (memory_region_has_guest_memfd (mr)) { +if (memory_region_has_guest_memfd (mr) && + !memory_region_guest_memfd_in_place_conversion (mr)) { err =kvm_set_memory_attributes_private (start_addr, slot_size);if (err) { error_report("%s: failed to set memory attribute private: %s",
@@ -2779,6 +2805,9 @@ static int kvm_init(AccelState *as, MachineState *ms)kvm_check_extension (s,KVM_CAP_GUEST_MEMFD ) &&kvm_check_extension (s,KVM_CAP_USER_MEMORY2 ) && (kvm_supported_memory_attributes &KVM_MEMORY_ATTRIBUTE_PRIVATE ); + kvm_guest_memfd_inplace_supported = +kvm_check_extension (s,KVM_CAP_GMEM_SHARED_MEM ) && +kvm_check_extension (s,KVM_CAP_GMEM_CONVERSION ); kvm_pre_fault_memory_supported =kvm_vm_check_extension (s,KVM_CAP_PRE_FAULT_MEMORY );if (s->kernel_irqchip_split ==ON_OFF_AUTO_AUTO ) {
@@ -3056,6 +3085,7 @@ static void kvm_eat_signals(CPUState *cpu)int kvm_convert_memory (hwaddr start,hwaddr size,bool to_private) { +bool in_place_conversion = false;MemoryRegionSection section;ram_addr_t offset;MemoryRegion *mr;
@@ -3112,18 +3142,23 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) goto out_unref; } -if (to_private) { - ret =kvm_set_memory_attributes_private (start, size); - }else { - ret =kvm_set_memory_attributes_shared (start, size); - } -if (ret) { - goto out_unref; - } - addr =memory_region_get_ram_ptr (mr) + section.offset_within_region; rb =qemu_ram_block_from_host (addr, false, &offset); + in_place_conversion =memory_region_guest_memfd_in_place_conversion (mr); +if (in_place_conversion) { + ret =kvm_set_guest_memfd_shareability (mr, offset, size, !to_private); + }else { +if (to_private) { + ret =kvm_set_memory_attributes_private (start, size); + }else { + ret =kvm_set_memory_attributes_shared (start, size); + } + } +if (ret) { + goto out_unref; + } + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), offset, size, to_private);if (ret) {
@@ -3133,17 +3168,19 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) goto out_unref; } -if (to_private) { -if (rb->page_size !=qemu_real_host_page_size ()) { -/* -* shared memory is backed by hugetlb, which is supposed to be -* pre-allocated and doesn't need to be discarded -*/ - goto out_unref; - } - ret =ram_block_discard_range (rb, offset, size); - }else { - ret =ram_block_discard_guest_memfd_range (rb, offset, size); +if (!in_place_conversion) { +if (to_private) { +if (rb->page_size !=qemu_real_host_page_size ()) { +/* +* shared memory is backed by hugetlb, which is supposed to be +* pre-allocated and doesn't need to be discarded +*/ + goto out_unref; + } + ret =ram_block_discard_range (rb, offset, size); + }else { + ret =ram_block_discard_guest_memfd_range (rb, offset, size); + } } out_unref:
accel/stubs/kvm-stub.c +1 -0
@@ -24,6 +24,7 @@ bool kvm_gsi_direct_mapping;bool kvm_allowed;bool kvm_readonly_mem_allowed;bool kvm_msi_use_devid; +bool kvm_guest_memfd_inplace_supported;void kvm_flush_coalesced_mmio_buffer (void ) {
include/system/kvm.h +1 -0
@@ -43,6 +43,7 @@ extern bool kvm_gsi_direct_mapping;extern bool kvm_readonly_mem_allowed;extern bool kvm_msi_use_devid;extern bool kvm_pre_fault_memory_supported; +extern bool kvm_guest_memfd_inplace_supported;#define kvm_enabled () (kvm_allowed)/**
include/system/memory.h +2 -0
@@ -1812,6 +1812,8 @@ bool memory_region_is_protected(MemoryRegion *mr);*/ bool memory_region_has_guest_memfd (MemoryRegion *mr); +bool memory_region_guest_memfd_in_place_conversion (MemoryRegion *mr); +/** * memory_region_get_iommu: check whether a memory region is an iommu *
include/system/ramblock.h +1 -0
@@ -46,6 +46,7 @@ struct RAMBlock {int fd;uint64_t fd_offset;int guest_memfd; +uint64_t guest_memfd_flags;RamBlockAttributes *attributes;size_t page_size;/* dirty bitmap used during migration */
system/memory.c +7 -0
@@ -35,6 +35,7 @@#include "memory-internal.h" +#include <linux/kvm.h> //#define DEBUG_UNASSIGNED static unsigned memory_region_transaction_depth;
@@ -1878,6 +1879,12 @@ bool memory_region_has_guest_memfd(MemoryRegion *mr)return mr->ram_block && mr->ram_block->guest_memfd >=0 ; } +bool memory_region_guest_memfd_in_place_conversion (MemoryRegion *mr) +{ +return mr &&memory_region_has_guest_memfd (mr) && + (mr->ram_block->guest_memfd_flags &GUEST_MEMFD_FLAG_SUPPORT_SHARED ); +} +uint8_t memory_region_get_dirty_log_mask (MemoryRegion *mr) {uint8_t mask = mr->dirty_log_mask;
system/physmem.c +20 -1
@@ -89,6 +89,9 @@#include "memory-internal.h" +#include <linux/guestmem.h> +#include <linux/kvm.h> +//#define DEBUG_SUBPAGE /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
@@ -1913,6 +1916,9 @@ static void ram_block_add(RAMBlock *new_block, Error **errp)if (new_block->flags &RAM_GUEST_MEMFD ) {int ret; +bool in_place = kvm_guest_memfd_inplace_supported; + + new_block->guest_memfd_flags =0 ;if (!kvm_enabled ()) { error_setg(errp, "cannot set up private guest memory for %s: KVM required",
@@ -1929,13 +1935,26 @@ static void ram_block_add(RAMBlock *new_block, Error **errp) goto out_free; } +if (in_place) { + new_block->guest_memfd_flags |=GUEST_MEMFD_FLAG_SUPPORT_SHARED | +GUEST_MEMFD_FLAG_INIT_PRIVATE ; + } + new_block->guest_memfd =kvm_create_guest_memfd (new_block->max_length, -0 , errp); + new_block->guest_memfd_flags, errp);if (new_block->guest_memfd <0 ) {qemu_mutex_unlock_ramlist (); goto out_free; } +if (in_place) { +qemu_ram_munmap (new_block->fd, new_block->host, new_block->max_length); + new_block->host =qemu_ram_mmap (new_block->guest_memfd, + new_block->max_length, +QEMU_VMALLOC_ALIGN , +QEMU_MAP_SHARED ,0 ); + } +/* * The attribute bitmap of the RamBlockAttributes is default to * discarded, which mimics the behavior of kvm_set_phys_mem() when it
Signature · 1 line
2.43.0
Re: [POC PATCH 3/5] memory/guest_memfd: Enable in-place conversion when available
Quoted 126 lines · Xiaoyao Li
From: Yan Zhao <[email protected]>
(This is just the POC code to use in-place conversion gmem.)
Try to use in-place conversion gmem when it is supported.
When in-place conversion is enabled, there is no need to discard memory since it still needs to be used as the memory of opposite attribute after conversion.
For a upstreamable solution, we can introduce memory-backend-guestmemfd for in-place conversion. With the non in-place conversion, it needs seperate non-gmem memory to back the shared memory and gmem is created implicitly and internally based on vm type. While with in-place conversion, there is no need for seperate non-gmem memory because gmem itself can be served as shared memory. So that we can introduce memory-backend-guestmemfd as the specific backend for in-place conversion gmem.
Signed-off-by Yan Zhao <[email protected]>Co-developed-by Xiaoyao Li <[email protected]>
Signed-off-by Xiaoyao Li <[email protected]>--- accel/kvm/kvm-all.c | 79 ++++++++++++++++++++++++++++----------- accel/stubs/kvm-stub.c | 1 + include/system/kvm.h | 1 + include/system/memory.h | 2 + include/system/ramblock.h | 1 + system/memory.c | 7 ++++ system/physmem.c | 21 ++++++++++- 7 files changed, 90 insertions(+), 22 deletions(-)accel/kvm/kvm-all.c +38
-10@@ -105,6 +105,7 @@ static int kvm_sstep_flags;static bool kvm_immediate_exit;static uint64_t kvm_supported_memory_attributes;static bool kvm_guest_memfd_supported; +bool kvm_guest_memfd_inplace_supported;static hwaddr kvm_max_slot_size = ~0 ;static const KVMCapabilityInfo kvm_required_capabilites[] = {@@ -1487,6 +1488,30 @@ static int kvm_set_memory_attributes(hwaddr start, uint64_t size, uint64_t attr)return r; } +static int kvm_set_guest_memfd_shareability (MemoryRegion *mr,ram_addr_t offset, +uint64_t size,bool shared) +{ +int guest_memfd = mr->ram_block->guest_memfd; +struct kvm_gmem_convert param = { + .offset = offset, + .size = size, + .error_offset =0 , + }; +unsigned long op; +int r; + + op = shared ?KVM_GMEM_CONVERT_SHARED :KVM_GMEM_CONVERT_PRIVATE ; + + r =ioctl (guest_memfd, op, ¶m); +if (r) { +error_report ("failed to set guest_memfd offset 0x%lx size 0x%lx to %s " +"error '%s' error offset 0x%llx" , + offset, size, shared ?"shared" :"private" , +strerror (errno), param.error_offset); + } +return r; +} +int kvm_set_memory_attributes_private (hwaddr start,uint64_t size) {return kvm_set_memory_attributes (start, size,KVM_MEMORY_ATTRIBUTE_PRIVATE );@@ -1604,7 +1629,8 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,abort (); } -if (memory_region_has_guest_memfd (mr)) { +if (memory_region_has_guest_memfd (mr) && + !memory_region_guest_memfd_in_place_conversion (mr)) { err =kvm_set_memory_attributes_private (start_addr, slot_size);if (err) { error_report("%s: failed to set memory attribute private: %s",@@ -2779,6 +2805,9 @@ static int kvm_init(AccelState *as, MachineState *ms)kvm_check_extension (s,KVM_CAP_GUEST_MEMFD ) &&kvm_check_extension (s,KVM_CAP_USER_MEMORY2 ) && (kvm_supported_memory_attributes &KVM_MEMORY_ATTRIBUTE_PRIVATE ); + kvm_guest_memfd_inplace_supported = +kvm_check_extension (s,KVM_CAP_GMEM_SHARED_MEM ) && +kvm_check_extension (s,KVM_CAP_GMEM_CONVERSION ); kvm_pre_fault_memory_supported =kvm_vm_check_extension (s,KVM_CAP_PRE_FAULT_MEMORY );if (s->kernel_irqchip_split ==ON_OFF_AUTO_AUTO ) {@@ -3056,6 +3085,7 @@ static void kvm_eat_signals(CPUState *cpu)int kvm_convert_memory (hwaddr start,hwaddr size,bool to_private) { +bool in_place_conversion = false;MemoryRegionSection section;ram_addr_t offset;MemoryRegion *mr;@@ -3112,18 +3142,23 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) goto out_unref; } -if (to_private) { - ret =kvm_set_memory_attributes_private (start, size); - }else { - ret =kvm_set_memory_attributes_shared (start, size); - } -if (ret) { - goto out_unref; - } - addr =memory_region_get_ram_ptr (mr) + section.offset_within_region; rb =qemu_ram_block_from_host (addr, false, &offset); + in_place_conversion =memory_region_guest_memfd_in_place_conversion (mr); +if (in_place_conversion) { + ret =kvm_set_guest_memfd_shareability (mr, offset, size, !to_private); + }else { +if (to_private) { + ret =kvm_set_memory_attributes_private (start, size); + }else {
accel/kvm/kvm-all.c int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) · line 3164
Quoted 10 lines
accel/kvm/kvm-all.c +7
-0+ ret =kvm_set_memory_attributes_shared (start, size); + } + } +if (ret) { + goto out_unref; + } + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), offset, size, to_private);if (ret) {
There's one thing required for shared device assignment with in-place conversion, we need to follow the sequence of unmap-before-conversion-to-private and map-after-conversion-to-shared. Maybe change it like:
accel/kvm/kvm-all.c +20 -7
@@ -3146,6 +3146,17 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) addr =memory_region_get_ram_ptr (mr) + section.offset_within_region; rb =qemu_ram_block_from_host (addr, false, &offset); +if (to_private) { + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), + offset, size, to_private); +if (ret) { +error_report ("Failed to notify the listener the state change of " +"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , + start, size, to_private ?"private" :"shared" ); + goto out_unref; + } + } + in_place_conversion =memory_region_guest_memfd_in_place_conversion (mr);if (in_place_conversion) { ret =kvm_set_guest_memfd_shareability (mr, offset, size, !to_private);
@@ -3160,13 +3171,15 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) goto out_unref; } - ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), - offset, size, to_private); -if (ret) { -error_report ("Failed to notify the listener the state change of " -"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , - start, size, to_private ?"private" :"shared" ); - goto out_unref; +if (!to_private) { + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), + offset, size, to_private); +if (ret) { +error_report ("Failed to notify the listener the state change of " +"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , + start, size, to_private ?"private" :"shared" ); + goto out_unref; + } }
Re: [POC PATCH 3/5] memory/guest_memfd: Enable in-place conversion when available
Quoted 176 lines · Chenyi Qiang
Quoted 126 lines · Xiaoyao Li
From: Yan Zhao <[email protected]>
(This is just the POC code to use in-place conversion gmem.)
Try to use in-place conversion gmem when it is supported.
When in-place conversion is enabled, there is no need to discard memory since it still needs to be used as the memory of opposite attribute after conversion.
For a upstreamable solution, we can introduce memory-backend-guestmemfd for in-place conversion. With the non in-place conversion, it needs seperate non-gmem memory to back the shared memory and gmem is created implicitly and internally based on vm type. While with in-place conversion, there is no need for seperate non-gmem memory because gmem itself can be served as shared memory. So that we can introduce memory-backend-guestmemfd as the specific backend for in-place conversion gmem.
Signed-off-by Yan Zhao <[email protected]>Co-developed-by Xiaoyao Li <[email protected]>
Signed-off-by Xiaoyao Li <[email protected]>--- accel/kvm/kvm-all.c | 79 ++++++++++++++++++++++++++++----------- accel/stubs/kvm-stub.c | 1 + include/system/kvm.h | 1 + include/system/memory.h | 2 + include/system/ramblock.h | 1 + system/memory.c | 7 ++++ system/physmem.c | 21 ++++++++++- 7 files changed, 90 insertions(+), 22 deletions(-)accel/kvm/kvm-all.c +38
-10@@ -105,6 +105,7 @@ static int kvm_sstep_flags;static bool kvm_immediate_exit;static uint64_t kvm_supported_memory_attributes;static bool kvm_guest_memfd_supported; +bool kvm_guest_memfd_inplace_supported;static hwaddr kvm_max_slot_size = ~0 ;static const KVMCapabilityInfo kvm_required_capabilites[] = {@@ -1487,6 +1488,30 @@ static int kvm_set_memory_attributes(hwaddr start, uint64_t size, uint64_t attr)return r; } +static int kvm_set_guest_memfd_shareability (MemoryRegion *mr,ram_addr_t offset, +uint64_t size,bool shared) +{ +int guest_memfd = mr->ram_block->guest_memfd; +struct kvm_gmem_convert param = { + .offset = offset, + .size = size, + .error_offset =0 , + }; +unsigned long op; +int r; + + op = shared ?KVM_GMEM_CONVERT_SHARED :KVM_GMEM_CONVERT_PRIVATE ; + + r =ioctl (guest_memfd, op, ¶m); +if (r) { +error_report ("failed to set guest_memfd offset 0x%lx size 0x%lx to %s " +"error '%s' error offset 0x%llx" , + offset, size, shared ?"shared" :"private" , +strerror (errno), param.error_offset); + } +return r; +} +int kvm_set_memory_attributes_private (hwaddr start,uint64_t size) {return kvm_set_memory_attributes (start, size,KVM_MEMORY_ATTRIBUTE_PRIVATE );@@ -1604,7 +1629,8 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,abort (); } -if (memory_region_has_guest_memfd (mr)) { +if (memory_region_has_guest_memfd (mr) && + !memory_region_guest_memfd_in_place_conversion (mr)) { err =kvm_set_memory_attributes_private (start_addr, slot_size);if (err) { error_report("%s: failed to set memory attribute private: %s",@@ -2779,6 +2805,9 @@ static int kvm_init(AccelState *as, MachineState *ms)kvm_check_extension (s,KVM_CAP_GUEST_MEMFD ) &&kvm_check_extension (s,KVM_CAP_USER_MEMORY2 ) && (kvm_supported_memory_attributes &KVM_MEMORY_ATTRIBUTE_PRIVATE ); + kvm_guest_memfd_inplace_supported = +kvm_check_extension (s,KVM_CAP_GMEM_SHARED_MEM ) && +kvm_check_extension (s,KVM_CAP_GMEM_CONVERSION ); kvm_pre_fault_memory_supported =kvm_vm_check_extension (s,KVM_CAP_PRE_FAULT_MEMORY );if (s->kernel_irqchip_split ==ON_OFF_AUTO_AUTO ) {@@ -3056,6 +3085,7 @@ static void kvm_eat_signals(CPUState *cpu)int kvm_convert_memory (hwaddr start,hwaddr size,bool to_private) { +bool in_place_conversion = false;MemoryRegionSection section;ram_addr_t offset;MemoryRegion *mr;@@ -3112,18 +3142,23 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) goto out_unref; } -if (to_private) { - ret =kvm_set_memory_attributes_private (start, size); - }else { - ret =kvm_set_memory_attributes_shared (start, size); - } -if (ret) { - goto out_unref; - } - addr =memory_region_get_ram_ptr (mr) + section.offset_within_region; rb =qemu_ram_block_from_host (addr, false, &offset); + in_place_conversion =memory_region_guest_memfd_in_place_conversion (mr); +if (in_place_conversion) { + ret =kvm_set_guest_memfd_shareability (mr, offset, size, !to_private); + }else { +if (to_private) { + ret =kvm_set_memory_attributes_private (start, size); + }else {accel/kvm/kvm-all.c int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) · line 3164
Quoted 10 lines
accel/kvm/kvm-all.c +7
-0+ ret =kvm_set_memory_attributes_shared (start, size); + } + } +if (ret) { + goto out_unref; + } + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), offset, size, to_private);if (ret) {There's one thing required for shared device assignment with in-place conversion, we need to follow the sequence of unmap-before-conversion-to-private and map-after-conversion-to-shared. Maybe change it like:
accel/kvm/kvm-all.c +11
-7@@ -3146,6 +3146,17 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) addr =memory_region_get_ram_ptr (mr) + section.offset_within_region; rb =qemu_ram_block_from_host (addr, false, &offset); +if (to_private) { + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), + offset, size, to_private); +if (ret) { +error_report ("Failed to notify the listener the state change of " +"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , + start, size, to_private ?"private" :"shared" ); + goto out_unref; + } + } + in_place_conversion =memory_region_guest_memfd_in_place_conversion (mr);if (in_place_conversion) { ret =kvm_set_guest_memfd_shareability (mr, offset, size, !to_private);@@ -3160,13 +3171,15 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) goto out_unref; } - ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), - offset, size, to_private); -if (ret) { -error_report ("Failed to notify the listener the state change of " -"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , - start, size, to_private ?"private" :"shared" ); - goto out_unref;
accel/kvm/kvm-all.c int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) · line 3183
Quoted 10 lines
accel/kvm/kvm-all.c +9
-0+if (!to_private) { + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), + offset, size, to_private); +if (ret) { +error_report ("Failed to notify the listener the state change of " +"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , + start, size, to_private ?"private" :"shared" ); + goto out_unref; + } }
(Sorry for forgetting to reply in the community)
Thanks for catching and reporting it. I have incorporated it to the internal branch.
PATCH 4/5 memory/guest_memfd: Enable hugetlb support
In reply to Xiaoyao Li(This is just the POC code to use gmem with hugetlb.)
Try with hugetlb first when hugetlb is supported by gmem. If hugetlb cannot afford the requested memory size and returns -ENOMEM, fallback to create gmem withtout hugetlb.
The hugetlb size is hardcoded as GUESTMEM_HUGETLB_FLAG_2MB. I'm not sure if it will be better if gmem can report the supported hugetlb size. But look at the current implementation of memfd, it just tries with the requested hugetlb size from user and fail when not supported. Hence gmem can do the same way without the supported size being enuemrated.
For a upstreamable solution, the hugetlb support of gmem can be implemented as "hugetlb" and "hugetlbsize" properties of memory-backend-guestmemfd as similar of memory-backend-memfd. (It requires memory-backed-guestmemfd introduced for in-place conversion gmem at first)
--- accel/kvm/kvm-all.c | 3 ++- accel/stubs/kvm-stub.c | 1 + include/system/kvm.h | 1 + system/physmem.c | 13 +++++++++++++ 4 files changed, 17 insertions(+), 1 deletion(-)
accel/kvm/kvm-all.c +2 -1
@@ -106,6 +106,7 @@ static bool kvm_immediate_exit;static uint64_t kvm_supported_memory_attributes;static bool kvm_guest_memfd_supported;bool kvm_guest_memfd_inplace_supported; +bool kvm_guest_memfd_hugetlb_supported;static hwaddr kvm_max_slot_size = ~0 ;static const KVMCapabilityInfo kvm_required_capabilites[] = {
@@ -2808,6 +2809,7 @@ static int kvm_init(AccelState *as, MachineState *ms) kvm_guest_memfd_inplace_supported =kvm_check_extension (s,KVM_CAP_GMEM_SHARED_MEM ) &&kvm_check_extension (s,KVM_CAP_GMEM_CONVERSION ); + kvm_guest_memfd_hugetlb_supported =kvm_check_extension (s,KVM_CAP_GMEM_HUGETLB ); kvm_pre_fault_memory_supported =kvm_vm_check_extension (s,KVM_CAP_PRE_FAULT_MEMORY );if (s->kernel_irqchip_split ==ON_OFF_AUTO_AUTO ) {
@@ -4536,7 +4538,6 @@ int kvm_create_guest_memfd(uint64_t size, uint64_t flags, Error **errp) fd =kvm_vm_ioctl (kvm_state,KVM_CREATE_GUEST_MEMFD , &guest_memfd);if (fd <0 ) {error_setg_errno (errp, errno,"Error creating KVM guest_memfd" ); -return -1 ; }return fd;
accel/stubs/kvm-stub.c +1 -0
@@ -25,6 +25,7 @@ bool kvm_allowed;bool kvm_readonly_mem_allowed;bool kvm_msi_use_devid;bool kvm_guest_memfd_inplace_supported; +bool kvm_guest_memfd_hugetlb_supported;void kvm_flush_coalesced_mmio_buffer (void ) {
include/system/kvm.h +1 -0
@@ -44,6 +44,7 @@ extern bool kvm_readonly_mem_allowed;extern bool kvm_msi_use_devid;extern bool kvm_pre_fault_memory_supported;extern bool kvm_guest_memfd_inplace_supported; +extern bool kvm_guest_memfd_hugetlb_supported;#define kvm_enabled () (kvm_allowed)/**
system/physmem.c +13 -0
@@ -1940,8 +1940,21 @@ static void ram_block_add(RAMBlock *new_block, Error **errp)GUEST_MEMFD_FLAG_INIT_PRIVATE ; } +if (kvm_guest_memfd_hugetlb_supported) { + new_block->guest_memfd_flags |=GUEST_MEMFD_FLAG_HUGETLB | +GUESTMEM_HUGETLB_FLAG_2MB ; + } + + new_block->guest_memfd =kvm_create_guest_memfd (new_block->max_length, + new_block->guest_memfd_flags, &err); +if (new_block->guest_memfd == -ENOMEM ) { +error_free (err); + new_block->guest_memfd_flags &= ~(GUEST_MEMFD_FLAG_HUGETLB | +GUESTMEM_HUGETLB_FLAG_2MB ); + } new_block->guest_memfd =kvm_create_guest_memfd (new_block->max_length, new_block->guest_memfd_flags, errp); +if (new_block->guest_memfd <0 ) {qemu_mutex_unlock_ramlist (); goto out_free;
Signature · 1 line
2.43.0
PATCH 5/5 memory: Don't enable in-place conversion for internal MemoryRegion with gmem
In reply to Xiaoyao LiCurrently, the TDVF cannot work with gmem in-place conversion because current implementation of KVM_TDX_INIT_MEM_REGION in KVM requires gmem of TDVF to be valid for both shared and private at the same time.
To workaround it, explicitly not enable in-place conversion for internal MemoryRegion with gmem. So that TDVF doesn't use in-place conversion gmem and KVM_TDX_INIT_MEM_REGION will initialize the gmem with the separate shared memory.
To make in-place conversion work with TDX's initial memory, the one possible solution and flow would be as below and it requires KVM change:
- QEMU create gmem as shared;
- QEMU mmap the gmem and load TDVF binary into it;
- QEMU convert gmem to private with the content preserved[1];
- QEMU invokes KVM_TDX_INIT_MEM_REGION without valid src, so that KVM knows to fetch the content in-place and use in-place PAGE.ADD for TDX.
[1] https://lore.kernel.org/all/[email protected]/
--- include/system/memory.h | 3 +++ system/memory.c | 2 +- system/physmem.c | 8 +++++--- 3 files changed, 9 insertions(+), 4 deletions(-)
include/system/memory.h +3 -0
@@ -256,6 +256,9 @@ typedef struct IOMMUTLBEvent {*/ #define RAM_PRIVATE (1 << 13) +/* Don't use enable in-place conversion for the guest mmefd backend */ +#define RAM_GUEST_MEMFD_NO_INPLACE (1 << 14) + static inline void iommu_notifier_init(IOMMUNotifier *n, IOMMUNotify fn, IOMMUNotifierFlag flags, hwaddr start, hwaddr end,
system/memory.c +1 -1
@@ -3702,7 +3702,7 @@ bool memory_region_init_ram_guest_memfd(MemoryRegion *mr,DeviceState *owner_dev;if (!memory_region_init_ram_flags_nomigrate (mr, owner, name, size, -RAM_GUEST_MEMFD , errp)) { +RAM_GUEST_MEMFD |RAM_GUEST_MEMFD_NO_INPLACE , errp)) {return false; }/* This will assert if owner is neither NULL nor a DeviceState.
system/physmem.c +5 -3
@@ -1916,7 +1916,8 @@ static void ram_block_add(RAMBlock *new_block, Error **errp)if (new_block->flags &RAM_GUEST_MEMFD ) {int ret; -bool in_place = kvm_guest_memfd_inplace_supported; +bool in_place = !(new_block->flags &RAM_GUEST_MEMFD_NO_INPLACE ) && + kvm_guest_memfd_inplace_supported; new_block->guest_memfd_flags =0 ;
@@ -2230,7 +2231,8 @@ RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size, ram_flags &= ~RAM_PRIVATE ;assert ((ram_flags & ~(RAM_SHARED |RAM_RESIZEABLE |RAM_PREALLOC | -RAM_NORESERVE |RAM_GUEST_MEMFD )) ==0 ); +RAM_NORESERVE |RAM_GUEST_MEMFD | +RAM_GUEST_MEMFD_NO_INPLACE )) ==0 );assert (!host ^ (ram_flags &RAM_PREALLOC ));assert (max_size >= size);
@@ -2314,7 +2316,7 @@ RAMBlock *qemu_ram_alloc(ram_addr_t size, uint32_t ram_flags, MemoryRegion *mr, Error **errp) {assert ((ram_flags & ~(RAM_SHARED |RAM_NORESERVE |RAM_GUEST_MEMFD | -RAM_PRIVATE )) ==0 ); +RAM_PRIVATE |RAM_GUEST_MEMFD_NO_INPLACE )) ==0 );return qemu_ram_alloc_internal (size, size,NULL ,NULL , ram_flags, mr, errp); }
Signature · 1 line
2.43.0
Ackerley Tng <[email protected]> writes:
Re-using this thread to collect discussions related to guest_memfd HugeTLB support, also trimmed cc list.
Here's the latest public version Vishal and I have:
On the guest_memfd call on 2026-01-22, Michael found another bug to do with multiple threads trying to allocate within the same huge page at the same time.
The fix we're using to make progress is to use hugetlb_fault_mutex_lock.
unsigned int gmem_hugetlb_mapping_index_lock(struct address_space *mapping,
pgoff_t index, u8 page_order)
{
pgoff_t index_floor = round_down(index, 1ULL << page_order);
return hugetlb_fault_mutex_lock(mapping, index_floor);
}void gmem_hugetlb_mapping_index_unlock(unsigned int hash)
{
hugetlb_fault_mutex_unlock(hash);
}and then
static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
{
... declarations ...
if (gmem_is_hugetlb(gi->flags))
lock_id = gmem_hugetlb_mapping_index_lock(mapping, index, gi->page_order);
... and this right at the end ...
if (gmem_is_hugetlb(gi->flags))
gmem_hugetlb_mapping_index_unlock(lock_id);
}Yan also found some bugs (thanks!) and there's a discussion at [*].
[*] https://lore.kernel.org/all/CAEvNRgGG+xYhsz62foOrTeAxUCYxpCKCJnNgTAMYMV=w2eq+6Q@mail.gmail.com/