Direct Map Removal Support for guest_memfd
Subsystems (26)
v10 cover Direct Map Removal Support for guest_memfd
[ based on kvm/next ]
Unmapping virtual machine guest memory from the host kernel's direct map is a successful mitigation against Spectre-style transient execution
issues: if the kernel page tables do not contain entries pointing to guest memory, then any attempted speculative read through the direct map will necessarily be blocked by the MMU before any observable microarchitectural side-effects happen. This means that Spectre-gadgets and similar cannot be used to target virtual machine memory. Roughly 60% of speculative execution issues fall into this category [1, Table 1].
This patch series extends guest_memfd with the ability to remove its memory from the host kernel's direct map, to be able to attain the above protection for KVM guests running inside guest_memfd.
Additionally, a Firecracker branch with support for these VMs can be found on GitHub [2].
For more details, please refer to the v5 cover letter. No substantial changes in design have taken place since.
See also related write() syscall support in guest_memfd [3] where the interoperation between the two features is described.
Changes since v9:
- Huacai/Ackerley: formatting and error handling fixes
- Heiko: remove TLB flushing from folio_zap_direct_map() on s390
- Willy: set_direct_map_valid_noflush() to take const void * instead of struct page *page
- Ackerley: remove reject_file_backed variable in gup_fast_folio_allowed()
- Ackerley: avoid referencing memfd_secret in doc
- Ackerley: make calls to kvm_gmem_folio_zap_direct_map() conditional to GUEST_MEMFD_FLAG_NO_DIRECT_MAP
- Rick: Exclude TDX from direct map removal
- Rick: Add a comment about current impossibility of zapping at non-base page granularity.
v9: https://lore.kernel.org/kvm/[email protected]
v8: https://lore.kernel.org/kvm/[email protected]
v7: https://lore.kernel.org/kvm/[email protected]
v6: https://lore.kernel.org/kvm/[email protected]
v5: https://lore.kernel.org/kvm/[email protected]
v4: https://lore.kernel.org/kvm/[email protected]
RFCv3: https://lore.kernel.org/kvm/[email protected]
RFCv2: https://lore.kernel.org/kvm/[email protected]
RFCv1: https://lore.kernel.org/kvm/[email protected]
[1] https://download.vusec.net/papers/quarantine_raid23.pdf
[2] https://github.com/firecracker-microvm/firecracker/tree/feature/secret-hiding
[3] https://lore.kernel.org/kvm/[email protected]
Nikita Kalyazin (3):
set_memory: set_direct_map_* to take address
set_memory: add folio_{zap,restore}_direct_map helpers mm/gup: drop local variable in gup_fast_folio_allowed
Patrick Roy (12):
mm/gup: drop secretmem optimization from gup_fast_folio_allowed
mm: introduce AS_NO_DIRECT_MAP
KVM: guest_memfd: Add stub for kvm_arch_gmem_invalidate
KVM: x86: define kvm_arch_gmem_supports_no_direct_map()
KVM: arm64: define kvm_arch_gmem_supports_no_direct_map()
KVM: guest_memfd: Add flag to remove from direct map
KVM: selftests: load elf via bounce buffer
KVM: selftests: set KVM_MEM_GUEST_MEMFD in vm_mem_add() if guest_memfd
!= -1
KVM: selftests: Add guest_memfd based vm_mem_backing_src_types
KVM: selftests: cover GUEST_MEMFD_FLAG_NO_DIRECT_MAP in existing
selftests
KVM: selftests: stuff vm_mem_backing_src_type into vm_shape
KVM: selftests: Test guest execution from direct map removed gmem
Documentation/virt/kvm/api.rst | 21 +++-- arch/arm64/include/asm/kvm_host.h | 13 +++ arch/arm64/include/asm/set_memory.h | 9 +- arch/arm64/mm/pageattr.c | 31 ++++--- arch/loongarch/include/asm/set_memory.h | 9 +- arch/loongarch/mm/pageattr.c | 37 +++++--- arch/riscv/include/asm/set_memory.h | 9 +- arch/riscv/mm/pageattr.c | 29 +++++-- arch/s390/include/asm/set_memory.h | 9 +- arch/s390/mm/pageattr.c | 25 ++++-- arch/x86/include/asm/kvm_host.h | 6 ++ arch/x86/include/asm/set_memory.h | 9 +- arch/x86/kvm/x86.c | 5 ++ arch/x86/mm/pat/set_memory.c | 43 +++++++--- include/linux/kvm_host.h | 14 ++++ include/linux/pagemap.h | 16 ++++ include/linux/secretmem.h | 18 ---- include/linux/set_memory.h | 19 ++++- include/uapi/linux/kvm.h | 1 + kernel/power/snapshot.c | 4 +- lib/buildid.c | 4 +- mm/execmem.c | 6 +- mm/gup.c | 37 +++----- mm/mlock.c | 2 +- mm/secretmem.c | 14 ++-- mm/vmalloc.c | 11 ++- .../testing/selftests/kvm/guest_memfd_test.c | 17 +++- .../testing/selftests/kvm/include/kvm_util.h | 37 ++++++-- .../testing/selftests/kvm/include/test_util.h | 8 ++ tools/testing/selftests/kvm/lib/elf.c | 8 +- tools/testing/selftests/kvm/lib/io.c | 23 +++++ tools/testing/selftests/kvm/lib/kvm_util.c | 59 +++++++------ tools/testing/selftests/kvm/lib/test_util.c | 8 ++ tools/testing/selftests/kvm/lib/x86/sev.c | 1 + .../selftests/kvm/pre_fault_memory_test.c | 1 + .../selftests/kvm/set_memory_region_test.c | 52 +++++++++++- .../kvm/x86/private_mem_conversions_test.c | 7 +- virt/kvm/guest_memfd.c | 84 +++++++++++++++++-- 38 files changed, 511 insertions(+), 195 deletions(-)
base-commit: 0499add8efd72456514c6218c062911ccc922a99
Signature · 1 line
2.50.1
PATCH v10 1/15 set_memory: set_direct_map_* to take address
From: Nikita Kalyazin <[email protected]>
This is to avoid excessive conversions folio->page->address when adding helpers on top of set_direct_map_valid_noflush() in the next patch.
--- arch/arm64/include/asm/set_memory.h | 7 ++++--- arch/arm64/mm/pageattr.c | 19 +++++++++---------- arch/loongarch/include/asm/set_memory.h | 7 ++++--- arch/loongarch/mm/pageattr.c | 25 ++++++++++++------------- arch/riscv/include/asm/set_memory.h | 7 ++++--- arch/riscv/mm/pageattr.c | 17 +++++++++-------- arch/s390/include/asm/set_memory.h | 7 ++++--- arch/s390/mm/pageattr.c | 13 +++++++------ arch/x86/include/asm/set_memory.h | 7 ++++--- arch/x86/mm/pat/set_memory.c | 23 ++++++++++++----------- include/linux/set_memory.h | 9 +++++---- kernel/power/snapshot.c | 4 ++-- mm/execmem.c | 6 ++++-- mm/secretmem.c | 6 +++--- mm/vmalloc.c | 11 +++++++---- 15 files changed, 90 insertions(+), 78 deletions(-)
arch/arm64/include/asm/set_memory.h +4 -3
@@ -11,9 +11,10 @@ bool can_set_direct_map(void);int set_memory_valid (unsigned long addr,int numpages,int enable); -int set_direct_map_invalid_noflush (struct page *page); -int set_direct_map_default_noflush (struct page *page); -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid); +int set_direct_map_invalid_noflush (const void *addr); +int set_direct_map_default_noflush (const void *addr); +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid);bool kernel_page_present (struct page *page);int set_memory_encrypted (unsigned long addr,int numpages);
arch/arm64/mm/pageattr.c +9 -10
@@ -243,7 +243,7 @@ int set_memory_valid(unsigned long addr, int numpages, int enable) __pgprot(PTE_VALID)); } -int set_direct_map_invalid_noflush (struct page *page) +int set_direct_map_invalid_noflush (const void *addr) {pgprot_t clear_mask =__pgprot (PTE_VALID );pgprot_t set_mask =__pgprot (0 );
@@ -251,11 +251,11 @@ int set_direct_map_invalid_noflush(struct page *page)if (!can_set_direct_map ())return 0 ; -return update_range_prot ((unsigned long )page_address (page), -PAGE_SIZE , set_mask, clear_mask); +return update_range_prot ((unsigned long )addr,PAGE_SIZE , set_mask, + clear_mask); } -int set_direct_map_default_noflush (struct page *page) +int set_direct_map_default_noflush (const void *addr) {pgprot_t set_mask =__pgprot (PTE_VALID |PTE_WRITE );pgprot_t clear_mask =__pgprot (PTE_RDONLY );
@@ -263,8 +263,8 @@ int set_direct_map_default_noflush(struct page *page)if (!can_set_direct_map ())return 0 ; -return update_range_prot ((unsigned long )page_address (page), -PAGE_SIZE , set_mask, clear_mask); +return update_range_prot ((unsigned long )addr,PAGE_SIZE , set_mask, + clear_mask); } static int __set_memory_enc_dec(unsigned long addr,
@@ -347,14 +347,13 @@ int realm_register_memory_enc_ops(void)return arm64_mem_crypt_ops_register (&realm_crypt_ops); } -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid) +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid) { -unsigned long addr = (unsigned long )page_address (page); -if (!can_set_direct_map ())return 0 ; -return set_memory_valid (addr, nr, valid); +return set_memory_valid ((unsigned long )addr, numpages, valid); }#ifdef CONFIG_DEBUG_PAGEALLOC
arch/loongarch/include/asm/set_memory.h +4 -3
@@ -15,8 +15,9 @@ int set_memory_ro(unsigned long addr, int numpages);int set_memory_rw (unsigned long addr,int numpages);bool kernel_page_present (struct page *page); -int set_direct_map_default_noflush (struct page *page); -int set_direct_map_invalid_noflush (struct page *page); -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid); +int set_direct_map_invalid_noflush (const void *addr); +int set_direct_map_default_noflush (const void *addr); +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid);#endif /* _ASM_LOONGARCH_SET_MEMORY_H */
arch/loongarch/mm/pageattr.c +12 -13
@@ -198,32 +198,31 @@ bool kernel_page_present(struct page *page)return pte_present (ptep_get (pte)); } -int set_direct_map_default_noflush (struct page *page) +int set_direct_map_default_noflush (const void *addr) { -unsigned long addr = (unsigned long )page_address (page); - -if (addr < vm_map_base) +if ((unsigned long )addr < vm_map_base)return 0 ; -return __set_memory (addr,1 ,PAGE_KERNEL ,__pgprot (0 )); +return __set_memory ((unsigned long )addr,1 ,PAGE_KERNEL ,__pgprot (0 )); } -int set_direct_map_invalid_noflush (struct page *page) +int set_direct_map_invalid_noflush (const void *addr) { -unsigned long addr = (unsigned long )page_address (page); +unsigned long addr = (unsigned long )addr; -if (addr < vm_map_base) +if ((unsigned long )addr < vm_map_base)return 0 ; -return __set_memory (addr,1 ,__pgprot (0 ),__pgprot (_PAGE_PRESENT | _PAGE_VALID)); +return __set_memory ((unsigned long )addr,1 ,__pgprot (0 ), +__pgprot (_PAGE_PRESENT | _PAGE_VALID)); } -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid) +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid) { -unsigned long addr = (unsigned long )page_address (page);pgprot_t set, clear; -if (addr < vm_map_base) +if ((unsigned long )addr < vm_map_base)return 0 ;if (valid) {
@@ -234,5 +233,5 @@ int set_direct_map_valid_noflush(struct page *page, unsigned nr, bool valid) clear =__pgprot (_PAGE_PRESENT | _PAGE_VALID); } -return __set_memory (addr,1 , set, clear); +return __set_memory ((unsigned long )addr,1 , set, clear); }
arch/riscv/include/asm/set_memory.h +4 -3
@@ -40,9 +40,10 @@ static inline int set_kernel_memory(char *startp, char *endp, }#endif -int set_direct_map_invalid_noflush (struct page *page); -int set_direct_map_default_noflush (struct page *page); -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid); +int set_direct_map_invalid_noflush (const void *addr); +int set_direct_map_default_noflush (const void *addr); +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid);bool kernel_page_present (struct page *page);#endif /* __ASSEMBLER__ */
arch/riscv/mm/pageattr.c +9 -8
@@ -374,19 +374,20 @@ int set_memory_nx(unsigned long addr, int numpages)return __set_memory (addr, numpages,__pgprot (0 ),__pgprot (_PAGE_EXEC)); } -int set_direct_map_invalid_noflush (struct page *page) +int set_direct_map_invalid_noflush (const void *addr) { -return __set_memory ((unsigned long )page_address (page),1 , -__pgprot (0 ),__pgprot (_PAGE_PRESENT)); +return __set_memory ((unsigned long )addr,1 ,__pgprot (0 ), +__pgprot (_PAGE_PRESENT)); } -int set_direct_map_default_noflush (struct page *page) +int set_direct_map_default_noflush (const void *addr) { -return __set_memory ((unsigned long )page_address (page),1 , -PAGE_KERNEL ,__pgprot (_PAGE_EXEC)); +return __set_memory ((unsigned long )addr,1 ,PAGE_KERNEL , +__pgprot (_PAGE_EXEC)); } -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid) +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid) {pgprot_t set, clear;
@@ -398,7 +399,7 @@ int set_direct_map_valid_noflush(struct page *page, unsigned nr, bool valid) clear =__pgprot (_PAGE_PRESENT); } -return __set_memory ((unsigned long )page_address (page), nr, set, clear); +return __set_memory ((unsigned long )addr, numpages, set, clear); }#ifdef CONFIG_DEBUG_PAGEALLOC
arch/s390/include/asm/set_memory.h +4 -3
@@ -60,9 +60,10 @@ __SET_MEMORY_FUNC(set_memory_rox, SET_MEMORY_RO | SET_MEMORY_X) __SET_MEMORY_FUNC(set_memory_rwnx, SET_MEMORY_RW | SET_MEMORY_NX) __SET_MEMORY_FUNC(set_memory_4k, SET_MEMORY_4K) -int set_direct_map_invalid_noflush (struct page *page); -int set_direct_map_default_noflush (struct page *page); -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid); +int set_direct_map_invalid_noflush (const void *addr); +int set_direct_map_default_noflush (const void *addr); +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid);bool kernel_page_present (struct page *page);#endif
arch/s390/mm/pageattr.c +7 -6
@@ -390,17 +390,18 @@ int __set_memory(unsigned long addr, unsigned long numpages, unsigned long flagsreturn rc; } -int set_direct_map_invalid_noflush (struct page *page) +int set_direct_map_invalid_noflush (const void *addr) { -return __set_memory ((unsigned long )page_to_virt (page),1 ,SET_MEMORY_INV ); +return __set_memory ((unsigned long )addr,1 ,SET_MEMORY_INV ); } -int set_direct_map_default_noflush (struct page *page) +int set_direct_map_default_noflush (const void *addr) { -return __set_memory ((unsigned long )page_to_virt (page),1 ,SET_MEMORY_DEF ); +return __set_memory ((unsigned long )addr,1 ,SET_MEMORY_DEF ); } -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid) +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid) {unsigned long flags;
@@ -409,7 +410,7 @@ int set_direct_map_valid_noflush(struct page *page, unsigned nr, bool valid)else flags =SET_MEMORY_INV ; -return __set_memory ((unsigned long )page_to_virt (page), nr, flags); +return __set_memory ((unsigned long )addr, numpages, flags); }bool kernel_page_present (struct page *page)
arch/x86/include/asm/set_memory.h +4 -3
@@ -87,9 +87,10 @@ int set_pages_wb(struct page *page, int numpages);int set_pages_ro (struct page *page,int numpages);int set_pages_rw (struct page *page,int numpages); -int set_direct_map_invalid_noflush (struct page *page); -int set_direct_map_default_noflush (struct page *page); -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid); +int set_direct_map_invalid_noflush (const void *addr); +int set_direct_map_default_noflush (const void *addr); +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid);bool kernel_page_present (struct page *page);extern int kernel_set_to_readonly;
arch/x86/mm/pat/set_memory.c +12 -11
@@ -2600,9 +2600,9 @@ int set_pages_rw(struct page *page, int numpages)return set_memory_rw (addr, numpages); } -static int __set_pages_p (struct page *page,int numpages) +static int __set_pages_p (const void *addr,int numpages) { -unsigned long tempaddr = (unsigned long )page_address (page); +unsigned long tempaddr = (unsigned long )addr;struct cpa_data cpa = { .vaddr = &tempaddr, .pgd =NULL , .numpages = numpages,
@@ -2619,9 +2619,9 @@ static int __set_pages_p(struct page *page, int numpages)return __change_page_attr_set_clr (&cpa,1 ); } -static int __set_pages_np (struct page *page,int numpages) +static int __set_pages_np (const void *addr,int numpages) { -unsigned long tempaddr = (unsigned long )page_address (page); +unsigned long tempaddr = (unsigned long )addr;struct cpa_data cpa = { .vaddr = &tempaddr, .pgd =NULL , .numpages = numpages,
@@ -2638,22 +2638,23 @@ static int __set_pages_np(struct page *page, int numpages)return __change_page_attr_set_clr (&cpa,1 ); } -int set_direct_map_invalid_noflush (struct page *page) +int set_direct_map_invalid_noflush (const void *addr) { -return __set_pages_np (page,1 ); +return __set_pages_np (addr,1 ); } -int set_direct_map_default_noflush (struct page *page) +int set_direct_map_default_noflush (const void *addr) { -return __set_pages_p (page,1 ); +return __set_pages_p (addr,1 ); } -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid) +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid) {if (valid) -return __set_pages_p (page, nr); +return __set_pages_p (addr, numpages); -return __set_pages_np (page, nr); +return __set_pages_np (addr, numpages); }#ifdef CONFIG_DEBUG_PAGEALLOC
include/linux/set_memory.h +5 -4
@@ -25,17 +25,18 @@ static inline int set_memory_rox(unsigned long addr, int numpages)#endif #ifndef CONFIG_ARCH_HAS_SET_DIRECT_MAP -static inline int set_direct_map_invalid_noflush (struct page *page) +static inline int set_direct_map_invalid_noflush (const void *addr) {return 0 ; } -static inline int set_direct_map_default_noflush (struct page *page) +static inline int set_direct_map_default_noflush (const void *addr) {return 0 ; } -static inline int set_direct_map_valid_noflush (struct page *page, -unsigned nr,bool valid) +static inline int set_direct_map_valid_noflush (const void *addr, +unsigned long numpages, +bool valid) {return 0 ; }
kernel/power/snapshot.c +2 -2
@@ -88,7 +88,7 @@ static inline int hibernate_restore_unprotect_page(void *page_address) {return 0static inline void hibernate_map_page (struct page *page) {if (IS_ENABLED (CONFIG_ARCH_HAS_SET_DIRECT_MAP )) { -int ret =set_direct_map_default_noflush (page); +int ret =set_direct_map_default_noflush (page_address (page));if (ret)pr_warn_once ("Failed to remap page\n" );
@@ -101,7 +101,7 @@ static inline void hibernate_unmap_page(struct page *page) {if (IS_ENABLED (CONFIG_ARCH_HAS_SET_DIRECT_MAP )) {unsigned long addr = (unsigned long )page_address (page); -int ret =set_direct_map_invalid_noflush (page); +int ret =set_direct_map_invalid_noflush (page_address (page));if (ret)pr_warn_once ("Failed to remap page\n" );
mm/execmem.c +4 -2
@@ -119,7 +119,8 @@ static int execmem_set_direct_map_valid(struct vm_struct *vm, bool valid)int err =0 ;for (int i =0 ; i < vm->nr_pages; i += nr) { - err =set_direct_map_valid_noflush (vm->pages[i], nr, valid); + err =set_direct_map_valid_noflush (page_address (vm->pages[i]), + nr, valid);if (err) goto err_restore; updated += nr;
@@ -129,7 +130,8 @@ static int execmem_set_direct_map_valid(struct vm_struct *vm, bool valid) err_restore:for (int i =0 ; i < updated; i += nr) -set_direct_map_valid_noflush (vm->pages[i], nr, !valid); +set_direct_map_valid_noflush (page_address (vm->pages[i]), nr, + !valid);return err; }
mm/secretmem.c +3 -3
@@ -72,7 +72,7 @@ static vm_fault_t secretmem_fault(struct vm_fault *vmf) goto out; } - err =set_direct_map_invalid_noflush (folio_page (folio,0 )); + err =set_direct_map_invalid_noflush (folio_address (folio));if (err) {folio_put (folio); ret =vmf_error (err);
@@ -87,7 +87,7 @@ static vm_fault_t secretmem_fault(struct vm_fault *vmf)* already happened when we marked the page invalid * which guarantees that this call won't fail */ -set_direct_map_default_noflush (folio_page (folio,0 )); +set_direct_map_default_noflush (folio_address (folio));folio_put (folio);if (err == -EEXIST ) goto retry;
@@ -152,7 +152,7 @@ static int secretmem_migrate_folio(struct address_space *mapping,static void secretmem_free_folio (struct folio *folio) { -set_direct_map_default_noflush (folio_page (folio,0 )); +set_direct_map_default_noflush (folio_address (folio));folio_zero_segment (folio,0 ,folio_size (folio)); }
mm/vmalloc.c +7 -4
@@ -3329,14 +3329,17 @@ struct vm_struct *remove_vm_area(const void *addr) }static inline void set_area_direct_map (const struct vm_struct *area, -int (*set_direct_map)(struct page *page)) +int (*set_direct_map)(const void *addr)) {int i;/* HUGE_VMALLOC passes small pages to set_direct_map */ -for (i =0 ; i < area->nr_pages; i++) -if (page_address (area->pages[i])) -set_direct_map (area->pages[i]); +for (i =0 ; i < area->nr_pages; i++) { +const void *addr =page_address (area->pages[i]); + +if (addr) +set_direct_map (addr); + } }/*
Signature · 1 line
2.50.1
PATCH v10 3/15 mm/gup: drop secretmem optimization from gup_fast_folio_allowed
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
This drops an optimization in gup_fast_folio_allowed() where secretmem_mapping() was only called if CONFIG_SECRETMEM=y. secretmem is enabled by default since commit b758fe6df50d ("mm/secretmem: make it on by default"), so the secretmem check did not actually end up elided in most cases anymore anyway.
This is in preparation of the generalization of handling mappings where direct map entries of folios are set to not present. Currently, mappings that match this description are secretmem mappings (memfd_secret()). Later, some guest_memfd configurations will also fall into this category.
--- mm/gup.c | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-)
mm/gup.c +1 -10
@@ -2739,7 +2739,6 @@ static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags) {bool reject_file_backed = false;struct address_space *mapping; -bool check_secretmem = false;unsigned long mapping_flags;/*
@@ -2751,14 +2750,6 @@ static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags) reject_file_backed = true;/* We hold a folio reference, so we can safely access folio fields. */ - -/* secretmem folios are always order-0 folios. */ -if (IS_ENABLED (CONFIG_SECRETMEM ) && !folio_test_large (folio)) - check_secretmem = true; - -if (!reject_file_backed && !check_secretmem) -return true; -if (WARN_ON_ONCE (folio_test_slab (folio)))return false;
@@ -2800,7 +2791,7 @@ static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags)* At this point, we know the mapping is non-null and points to an * address_space object. */ -if (check_secretmem &&secretmem_mapping (mapping)) +if (secretmem_mapping (mapping))return false;/* The only remaining allowed file system is shmem. */ return !reject_file_backed ||shmem_mapping (mapping);
Signature · 1 line
2.50.1
PATCH v10 2/15 set_memory: add folio_{zap,restore}_direct_map helpers
In reply to Kalyazin, NikitaFrom: Nikita Kalyazin <[email protected]>
These allow guest_memfd to remove its memory from the direct map. Only implement them for architectures that have direct map. In folio_zap_direct_map(), flush TLB on architectures where set_direct_map_valid_noflush() does not flush it internally.
The new helpers need to be accessible to KVM on architectures that support guest_memfd (x86 and arm64). Since arm64 does not support building KVM as a module, only export them on x86.
Direct map removal gives guest_memfd the same protection that memfd_secret does, such as hardening against Spectre-like attacks through in-kernel gadgets.
--- arch/arm64/include/asm/set_memory.h | 2 ++ arch/arm64/mm/pageattr.c | 12 ++++++++++++ arch/loongarch/include/asm/set_memory.h | 2 ++ arch/loongarch/mm/pageattr.c | 12 ++++++++++++ arch/riscv/include/asm/set_memory.h | 2 ++ arch/riscv/mm/pageattr.c | 12 ++++++++++++ arch/s390/include/asm/set_memory.h | 2 ++ arch/s390/mm/pageattr.c | 12 ++++++++++++ arch/x86/include/asm/set_memory.h | 2 ++ arch/x86/mm/pat/set_memory.c | 20 ++++++++++++++++++++ include/linux/set_memory.h | 10 ++++++++++ 11 files changed, 88 insertions(+)
arch/arm64/include/asm/set_memory.h +2 -0
@@ -15,6 +15,8 @@ int set_direct_map_invalid_noflush(const void *addr);int set_direct_map_default_noflush (const void *addr);int set_direct_map_valid_noflush (const void *addr,unsigned long numpages,bool valid); +int folio_zap_direct_map (struct folio *folio); +int folio_restore_direct_map (struct folio *folio);bool kernel_page_present (struct page *page);int set_memory_encrypted (unsigned long addr,int numpages);
arch/arm64/mm/pageattr.c +12 -0
@@ -356,6 +356,18 @@ int set_direct_map_valid_noflush(const void *addr, unsigned long numpages,return set_memory_valid ((unsigned long )addr, numpages, valid); } +int folio_zap_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), false); +} + +int folio_restore_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), true); +} +#ifdef CONFIG_DEBUG_PAGEALLOC /* * This is - apart from the return value - doing the same
arch/loongarch/include/asm/set_memory.h +2 -0
@@ -19,5 +19,7 @@ int set_direct_map_invalid_noflush(const void *addr);int set_direct_map_default_noflush (const void *addr);int set_direct_map_valid_noflush (const void *addr,unsigned long numpages,bool valid); +int folio_zap_direct_map (struct folio *folio); +int folio_restore_direct_map (struct folio *folio);#endif /* _ASM_LOONGARCH_SET_MEMORY_H */
arch/loongarch/mm/pageattr.c +12 -0
@@ -235,3 +235,15 @@ int set_direct_map_valid_noflush(const void *addr, unsigned long numpages,return __set_memory ((unsigned long )addr,1 , set, clear); } + +int folio_zap_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), false); +} + +int folio_restore_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), true); +}
arch/riscv/include/asm/set_memory.h +2 -0
@@ -44,6 +44,8 @@ int set_direct_map_invalid_noflush(const void *addr);int set_direct_map_default_noflush (const void *addr);int set_direct_map_valid_noflush (const void *addr,unsigned long numpages,bool valid); +int folio_zap_direct_map (struct folio *folio); +int folio_restore_direct_map (struct folio *folio);bool kernel_page_present (struct page *page);#endif /* __ASSEMBLER__ */
arch/riscv/mm/pageattr.c +12 -0
@@ -402,6 +402,18 @@ int set_direct_map_valid_noflush(const void *addr, unsigned long numpages,return __set_memory ((unsigned long )addr, numpages, set, clear); } +int folio_zap_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), false); +} + +int folio_restore_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), true); +} +#ifdef CONFIG_DEBUG_PAGEALLOC static int debug_pagealloc_set_page (pte_t *pte,unsigned long addr,void *data) {
arch/s390/include/asm/set_memory.h +2 -0
@@ -64,6 +64,8 @@ int set_direct_map_invalid_noflush(const void *addr);int set_direct_map_default_noflush (const void *addr);int set_direct_map_valid_noflush (const void *addr,unsigned long numpages,bool valid); +int folio_zap_direct_map (struct folio *folio); +int folio_restore_direct_map (struct folio *folio);bool kernel_page_present (struct page *page);#endif
arch/s390/mm/pageattr.c +12 -0
@@ -413,6 +413,18 @@ int set_direct_map_valid_noflush(const void *addr, unsigned long numpages,return __set_memory ((unsigned long )addr, numpages, flags); } +int folio_zap_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), false); +} + +int folio_restore_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), true); +} +bool kernel_page_present (struct page *page) {unsigned long addr;
arch/x86/include/asm/set_memory.h +2 -0
@@ -91,6 +91,8 @@ int set_direct_map_invalid_noflush(const void *addr);int set_direct_map_default_noflush (const void *addr);int set_direct_map_valid_noflush (const void *addr,unsigned long numpages,bool valid); +int folio_zap_direct_map (struct folio *folio); +int folio_restore_direct_map (struct folio *folio);bool kernel_page_present (struct page *page);extern int kernel_set_to_readonly;
arch/x86/mm/pat/set_memory.c +20 -0
@@ -2657,6 +2657,26 @@ int set_direct_map_valid_noflush(const void *addr, unsigned long numpages,return __set_pages_np (addr, numpages); } +int folio_zap_direct_map (struct folio *folio) +{ +const void *addr =folio_address (folio); +int ret; + + ret =set_direct_map_valid_noflush (addr,folio_nr_pages (folio), false); +flush_tlb_kernel_range ((unsigned long )addr, + (unsigned long )addr +folio_size (folio)); + +return ret; +} +EXPORT_SYMBOL_FOR_MODULES (folio_zap_direct_map,"kvm" ); + +int folio_restore_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), true); +} +EXPORT_SYMBOL_FOR_MODULES (folio_restore_direct_map,"kvm" ); +#ifdef CONFIG_DEBUG_PAGEALLOC void __kernel_map_pages (struct page *page,int numpages,int enable) {
include/linux/set_memory.h +10 -0
@@ -41,6 +41,16 @@ static inline int set_direct_map_valid_noflush(const void *addr,return 0 ; } +static inline int folio_zap_direct_map (struct folio *folio) +{ +return 0 ; +} + +static inline int folio_restore_direct_map (struct folio *folio) +{ +return 0 ; +} +static inline bool kernel_page_present (struct page *page) {return true;
Signature · 1 line
2.50.1
PATCH v10 4/15 mm/gup: drop local variable in gup_fast_folio_allowed
In reply to Kalyazin, NikitaFrom: Nikita Kalyazin <[email protected]>
Move the check for pinning closer to where the result is used. No functional changes.
--- mm/gup.c | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-)
mm/gup.c +8 -11
@@ -2737,18 +2737,9 @@ EXPORT_SYMBOL(get_user_pages_unlocked);*/ static bool gup_fast_folio_allowed (struct folio *folio,unsigned int flags) { -bool reject_file_backed = false;struct address_space *mapping;unsigned long mapping_flags; -/* -* If we aren't pinning then no problematic write can occur. A long term -* pin is the most egregious case so this is the one we disallow. -*/ -if ((flags & (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE )) == - (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE )) - reject_file_backed = true; -/* We hold a folio reference, so we can safely access folio fields. */ if (WARN_ON_ONCE (folio_test_slab (folio)))return false;
@@ -2793,8 +2784,14 @@ static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags)*/ if (secretmem_mapping (mapping))return false; -/* The only remaining allowed file system is shmem. */ -return !reject_file_backed ||shmem_mapping (mapping); + +/* +* If we aren't pinning then no problematic write can occur. A long term +* pin is the most egregious case so this is the one we disallow. +* Also check the only remaining allowed file system - shmem. +*/ +return (flags & (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE )) != + (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE ) ||shmem_mapping (mapping); } static void __maybe_unused gup_fast_undo_dev_pagemap(int *nr, int nr_start,
Signature · 1 line
2.50.1
PATCH v10 5/15 mm: introduce AS_NO_DIRECT_MAP
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
Add AS_NO_DIRECT_MAP for mappings where direct map entries of folios are set to not present. Currently, mappings that match this description are secretmem mappings (memfd_secret()). Later, some guest_memfd configurations will also fall into this category.
Reject this new type of mappings in all locations that currently reject secretmem mappings, on the assumption that if secretmem mappings are rejected somewhere, it is precisely because of an inability to deal with folios without direct map entries, and then make memfd_secret() use AS_NO_DIRECT_MAP on its address_space to drop its special vma_is_secretmem()/secretmem_mapping() checks.
Use a new flag instead of overloading AS_INACCESSIBLE (which is already set by guest_memfd) because not all guest_memfd mappings will end up being direct map removed (e.g. in pKVM setups, parts of guest_memfd that can be mapped to userspace should also be GUP-able, and generally not have restrictions on who can access it).
--- include/linux/pagemap.h | 16 ++++++++++++++++ include/linux/secretmem.h | 18 ------------------ lib/buildid.c | 4 ++-- mm/gup.c | 9 ++++----- mm/mlock.c | 2 +- mm/secretmem.c | 8 ++------ 6 files changed, 25 insertions(+), 32 deletions(-)
include/linux/pagemap.h +16 -0
@@ -210,6 +210,7 @@ enum mapping_flags {AS_WRITEBACK_MAY_DEADLOCK_ON_RECLAIM =9 ,AS_KERNEL_FILE =10 ,/* mapping for a fake kernel file that shouldn't account usage to user cgroups */ +AS_NO_DIRECT_MAP =11 ,/* Folios in the mapping are not in the direct map */ /* Bits 16-25 are used for FOLIO_ORDER */ AS_FOLIO_ORDER_BITS =5 , AS_FOLIO_ORDER_MIN = 16,
@@ -345,6 +346,21 @@ static inline bool mapping_writeback_may_deadlock_on_reclaim(const struct addresreturn test_bit (AS_WRITEBACK_MAY_DEADLOCK_ON_RECLAIM , &mapping->flags); } +static inline void mapping_set_no_direct_map (struct address_space *mapping) +{ +set_bit (AS_NO_DIRECT_MAP , &mapping->flags); +} + +static inline bool mapping_no_direct_map (const struct address_space *mapping) +{ +return test_bit (AS_NO_DIRECT_MAP , &mapping->flags); +} + +static inline bool vma_has_no_direct_map (const struct vm_area_struct *vma) +{ +return vma->vm_file &&mapping_no_direct_map (vma->vm_file->f_mapping); +} +static inline gfp_t mapping_gfp_mask (const struct address_space *mapping) {return mapping->gfp_mask;
include/linux/secretmem.h +0 -18
@@ -4,28 +4,10 @@#ifdef CONFIG_SECRETMEM -extern const struct address_space_operations secretmem_aops; - -static inline bool secretmem_mapping (struct address_space *mapping) -{ -return mapping->a_ops == &secretmem_aops; -} - -bool vma_is_secretmem (struct vm_area_struct *vma);bool secretmem_active (void );#else -static inline bool vma_is_secretmem (struct vm_area_struct *vma) -{ -return false; -} - -static inline bool secretmem_mapping (struct address_space *mapping) -{ -return false; -} -static inline bool secretmem_active (void ) {return false;
lib/buildid.c +2 -2
@@ -46,8 +46,8 @@ static int freader_get_folio(struct freader *r, loff_t file_off)freader_put_folio (r); -/* reject secretmem folios created with memfd_secret() */ -if (secretmem_mapping (r->file->f_mapping)) +/* reject folios without direct map entries (e.g. from memfd_secret() or guest_memfd()) */ +if (mapping_no_direct_map (r->file->f_mapping))return -EFAULT ; r->folio =filemap_get_folio (r->file->f_mapping, file_off >>PAGE_SHIFT );
mm/gup.c +4 -5
@@ -11,7 +11,6 @@#include <linux/rmap.h> #include <linux/swap.h> #include <linux/swapops.h> -#include <linux/secretmem.h> #include <linux/sched/signal.h> #include <linux/rwsem.h>
@@ -1216,7 +1215,7 @@ static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)if ((gup_flags &FOLL_SPLIT_PMD ) &&is_vm_hugetlb_page (vma))return -EOPNOTSUPP ; -if (vma_is_secretmem (vma)) +if (vma_has_no_direct_map (vma))return -EFAULT ;if (write) {
@@ -2724,7 +2723,7 @@ EXPORT_SYMBOL(get_user_pages_unlocked);* This call assumes the caller has pinned the folio, that the lowest page table * level still points to this folio, and that interrupts have been disabled. * -* GUP-fast must reject all secretmem folios. +* GUP-fast must reject all folios without direct map entries (such as secretmem). * * Writing to pinned file-backed dirty tracked folios is inherently problematic * (see comment describing the writable_file_mapping_allowed() function). We
@@ -2744,7 +2743,7 @@ static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags)if (WARN_ON_ONCE (folio_test_slab (folio)))return false; -/* hugetlb neither requires dirty-tracking nor can be secretmem. */ +/* hugetlb neither requires dirty-tracking nor can be without direct map. */ if (folio_test_hugetlb (folio))return true;
@@ -2782,7 +2781,7 @@ static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags)* At this point, we know the mapping is non-null and points to an * address_space object. */ -if (secretmem_mapping (mapping)) +if (mapping_no_direct_map (mapping))return false;/*
mm/mlock.c +1 -1
@@ -474,7 +474,7 @@ static int mlock_fixup(struct vma_iterator *vmi, struct vm_area_struct *vma,if (newflags == oldflags || (oldflags &VM_SPECIAL ) ||is_vm_hugetlb_page (vma) || vma ==get_gate_vma (current->mm) || -vma_is_dax (vma) ||vma_is_secretmem (vma) || (oldflags &VM_DROPPABLE )) +vma_is_dax (vma) ||vma_has_no_direct_map (vma) || (oldflags &VM_DROPPABLE ))/* don't set VM_LOCKED or VM_LOCKONFAULT and don't count */ goto out;
mm/secretmem.c +2 -6
@@ -134,11 +134,6 @@ static int secretmem_mmap_prepare(struct vm_area_desc *desc)return 0 ; } -bool vma_is_secretmem (struct vm_area_struct *vma) -{ -return vma->vm_ops == &secretmem_vm_ops; -} -static const struct file_operations secretmem_fops = { .release = secretmem_release, .mmap_prepare = secretmem_mmap_prepare,
@@ -156,7 +151,7 @@ static void secretmem_free_folio(struct folio *folio)folio_zero_segment (folio,0 ,folio_size (folio)); } -const struct address_space_operations secretmem_aops = { +static const struct address_space_operations secretmem_aops = { .dirty_folio = noop_dirty_folio, .free_folio = secretmem_free_folio, .migrate_folio = secretmem_migrate_folio,
@@ -205,6 +200,7 @@ static struct file *secretmem_file_create(unsigned long flags)mapping_set_gfp_mask (inode->i_mapping,GFP_HIGHUSER );mapping_set_unevictable (inode->i_mapping); +mapping_set_no_direct_map (inode->i_mapping); inode->i_op = &secretmem_iops; inode->i_mapping->a_ops = &secretmem_aops;
Signature · 1 line
2.50.1
PATCH v10 6/15 KVM: guest_memfd: Add stub for kvm_arch_gmem_invalidate
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
Add a no-op stub for kvm_arch_gmem_invalidate if CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE=n. This allows defining kvm_gmem_free_folio without ifdef-ery, which allows more cleanly using guest_memfd's free_folio callback for non-arch-invalidation related code.
--- include/linux/kvm_host.h | 2 ++ virt/kvm/guest_memfd.c | 4 ---- 2 files changed, 2 insertions(+), 4 deletions(-)
include/linux/kvm_host.h +2 -0
@@ -2589,6 +2589,8 @@ long kvm_gmem_populate(struct kvm *kvm, gfn_t gfn, void __user *src, long npages#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE void kvm_arch_gmem_invalidate (kvm_pfn_t start,kvm_pfn_t end); +#else +static inline void kvm_arch_gmem_invalidate (kvm_pfn_t start,kvm_pfn_t end) { }#endif #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY
virt/kvm/guest_memfd.c +0 -4
@@ -527,7 +527,6 @@ static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *folreturn MF_DELAYED ; } -#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE static void kvm_gmem_free_folio (struct folio *folio) {struct page *page =folio_page (folio,0 );
@@ -536,15 +535,12 @@ static void kvm_gmem_free_folio(struct folio *folio)kvm_arch_gmem_invalidate (pfn, pfn + (1ul << order)); } -#endif static const struct address_space_operations kvm_gmem_aops = { .dirty_folio = noop_dirty_folio, .migrate_folio = kvm_gmem_migrate_folio, .error_remove_folio = kvm_gmem_error_folio, -#ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE .free_folio = kvm_gmem_free_folio, -#endif }; static int kvm_gmem_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
Signature · 1 line
2.50.1
PATCH v10 8/15 KVM: arm64: define kvm_arch_gmem_supports_no_direct_map()
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
Support for GUEST_MEMFD_FLAG_NO_DIRECT_MAP on arm64 depends on 1) direct map manipulations at 4k granularity being possible, and 2) FEAT_S2FWB.
1) is met whenever the direct map is set up at 4k granularity (e.g. not with huge/gigantic pages) at boottime, as due to ARM's
break-before-make semantics, breaking huge mappings into 4k mappings in the direct map is not possible (BBM would require temporary invalidation of the entire huge mapping, even if only a 4k subrange should be zapped, which will probably crash the kernel). However, the current default for rodata_full is true, which forces a 4k direct map.
2) is required to allow KVM to elide cache coherency operations when installing stage 2 page tables, which require the direct map to be entry for the newly mapped memory to be present (which it will not be, as guest_memfd would have removed direct map entries in kvm_gmem_get_pfn()).
--- arch/arm64/include/asm/kvm_host.h | 13 +++++++++++++ 1 file changed, 13 insertions(+)
arch/arm64/include/asm/kvm_host.h +13 -0
@@ -19,6 +19,7 @@#include <linux/maple_tree.h> #include <linux/percpu.h> #include <linux/psci.h> +#include <linux/set_memory.h> #include <asm/arch_gicv3.h> #include <asm/barrier.h> #include <asm/cpufeature.h>
@@ -1654,5 +1655,17 @@ static __always_inline enum fgt_group_id __fgt_reg_to_group_id(enum vcpu_sysreg \ p; \ }) +#ifdef CONFIG_KVM_GUEST_MEMFD +static inline bool kvm_arch_gmem_supports_no_direct_map (void ) +{ +/* +* Without FWB, direct map access is needed in kvm_pgtable_stage2_map(), +* as it calls dcache_clean_inval_poc(). +*/ +return can_set_direct_map () &&cpus_have_final_cap (ARM64_HAS_STAGE2_FWB ); +} +#define kvm_arch_gmem_supports_no_direct_map kvm_arch_gmem_supports_no_direct_map +#endif /* CONFIG_KVM_GUEST_MEMFD */ +#endif /* __ARM64_KVM_HOST_H__ */
Signature · 1 line
2.50.1
PATCH v10 7/15 KVM: x86: define kvm_arch_gmem_supports_no_direct_map()
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
x86 supports GUEST_MEMFD_FLAG_NO_DIRECT_MAP whenever direct map modifications are possible (which is always the case).
--- arch/x86/include/asm/kvm_host.h | 9 +++++++++ 1 file changed, 9 insertions(+)
arch/x86/include/asm/kvm_host.h +9 -0
@@ -28,6 +28,7 @@#include <linux/sched/vhost_task.h> #include <linux/call_once.h> #include <linux/atomic.h> +#include <linux/set_memory.h> #include <asm/apic.h> #include <asm/pvclock-abi.h>
@@ -2481,4 +2482,12 @@ static inline bool kvm_arch_has_irq_bypass(void) return enable_device_posted_irqs; } +#ifdef CONFIG_KVM_GUEST_MEMFD +static inline bool kvm_arch_gmem_supports_no_direct_map (void ) +{ +return can_set_direct_map (); +} +#define kvm_arch_gmem_supports_no_direct_map kvm_arch_gmem_supports_no_direct_map +#endif /* CONFIG_KVM_GUEST_MEMFD */ +#endif /* _ASM_X86_KVM_HOST_H */
Signature · 1 line
2.50.1
PATCH v10 9/15 KVM: guest_memfd: Add flag to remove from direct map
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
Add GUEST_MEMFD_FLAG_NO_DIRECT_MAP flag for KVM_CREATE_GUEST_MEMFD() ioctl. When set, guest_memfd folios will be removed from the direct map after preparation, with direct map entries only restored when the folios are freed.
To ensure these folios do not end up in places where the kernel cannot deal with them, set AS_NO_DIRECT_MAP on the guest_memfd's struct address_space if GUEST_MEMFD_FLAG_NO_DIRECT_MAP is requested.
Note that this flag causes removal of direct map entries for all guest_memfd folios independent of whether they are "shared" or "private" (although current guest_memfd only supports either all folios in the "shared" state, or all folios in the "private" state if GUEST_MEMFD_FLAG_MMAP is not set). The usecase for removing direct map entries of also the shared parts of guest_memfd are a special type of non-CoCo VM where, host userspace is trusted to have access to all of guest memory, but where Spectre-style transient execution attacks through the host kernel's direct map should still be mitigated. In this setup, KVM retains access to guest memory via userspace mappings of guest_memfd, which are reflected back into KVM's memslots via userspace_addr. This is needed for things like MMIO emulation on x86_64 to work.
Direct map entries are zapped right before guest or userspace mappings of gmem folios are set up, e.g. in kvm_gmem_fault_user_mapping() or kvm_gmem_get_pfn() [called from the KVM MMU code]. The only place where a gmem folio can be allocated without being mapped anywhere is kvm_gmem_populate(), where handling potential failures of direct map removal is not possible (by the time direct map removal is attempted, the folio is already marked as prepared, meaning attempting to re-try kvm_gmem_populate() would just result in -EEXIST without fixing up the direct map state). These folios are then removed form the direct map upon kvm_gmem_get_pfn(), e.g. when they are mapped into the guest later.
--- Documentation/virt/kvm/api.rst | 21 +++++---- arch/x86/include/asm/kvm_host.h | 5 +-- arch/x86/kvm/x86.c | 5 +++ include/linux/kvm_host.h | 12 +++++ include/uapi/linux/kvm.h | 1 + virt/kvm/guest_memfd.c | 80 ++++++++++++++++++++++++++++++--- 6 files changed, 106 insertions(+), 18 deletions(-)
Documentation/virt/kvm/api.rst +12 -9
@@ -6440,15 +6440,18 @@ a single guest_memfd file, but the bound ranges must not overlap). The capability KVM_CAP_GUEST_MEMFD_FLAGS enumerates the `flags` that can be specified via KVM_CREATE_GUEST_MEMFD. Currently defined flags: - ============================ ================================================ - GUEST_MEMFD_FLAG_MMAP Enable using mmap() on the guest_memfd file - descriptor. - GUEST_MEMFD_FLAG_INIT_SHARED Make all memory in the file shared during - KVM_CREATE_GUEST_MEMFD (memory files created - without INIT_SHARED will be marked private). - Shared memory can be faulted into host userspace - page tables. Private memory cannot. - ============================ ================================================ + ============================== ================================================ + GUEST_MEMFD_FLAG_MMAP Enable using mmap() on the guest_memfd file + descriptor. + GUEST_MEMFD_FLAG_INIT_SHARED Make all memory in the file shared during + KVM_CREATE_GUEST_MEMFD (memory files created + without INIT_SHARED will be marked private). + Shared memory can be faulted into host userspace + page tables. Private memory cannot. + GUEST_MEMFD_FLAG_NO_DIRECT_MAP The guest_memfd instance will unmap the memory + backing it from the kernel's address space + before passing it off to userspace or the guest. + ============================== ================================================ When the KVM MMU performs a PFN lookup to service a guest fault and the backing guest_memfd has the GUEST_MEMFD_FLAG_MMAP set, then the fault will always be
arch/x86/include/asm/kvm_host.h +1 -4
@@ -2483,10 +2483,7 @@ static inline bool kvm_arch_has_irq_bypass(void) }#ifdef CONFIG_KVM_GUEST_MEMFD -static inline bool kvm_arch_gmem_supports_no_direct_map (void ) -{ -return can_set_direct_map (); -} +bool kvm_arch_gmem_supports_no_direct_map (struct kvm *kvm);#define kvm_arch_gmem_supports_no_direct_map kvm_arch_gmem_supports_no_direct_map#endif /* CONFIG_KVM_GUEST_MEMFD */
arch/x86/kvm/x86.c +5 -0
@@ -14007,6 +14007,11 @@ void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)kvm_x86_call (gmem_invalidate)(start, end); }#endif + +bool kvm_arch_gmem_supports_no_direct_map (struct kvm *kvm) +{ +return can_set_direct_map () && kvm->arch.vm_type !=KVM_X86_TDX_VM ; +}#endif int kvm_spec_ctrl_test_value (u64 value)
include/linux/kvm_host.h +12 -0
@@ -738,10 +738,22 @@ static inline u64 kvm_gmem_get_supported_flags(struct kvm *kvm)if (!kvm ||kvm_arch_supports_gmem_init_shared (kvm)) flags |=GUEST_MEMFD_FLAG_INIT_SHARED ; +if (!kvm ||kvm_arch_gmem_supports_no_direct_map (kvm)) + flags |=GUEST_MEMFD_FLAG_NO_DIRECT_MAP ; +return flags; }#endif +#ifdef CONFIG_KVM_GUEST_MEMFD +#ifndef kvm_arch_gmem_supports_no_direct_map +static inline bool kvm_arch_gmem_supports_no_direct_map (struct kvm *kvm) +{ +return false; +} +#endif +#endif /* CONFIG_KVM_GUEST_MEMFD */ +#ifndef kvm_arch_has_readonly_memstatic inline bool kvm_arch_has_readonly_mem (struct kvm *kvm) {
include/uapi/linux/kvm.h +1 -0
@@ -1612,6 +1612,7 @@ struct kvm_memory_attributes {#define KVM_CREATE_GUEST_MEMFD _IOWR(KVMIO, 0xd4, struct kvm_create_guest_memfd)#define GUEST_MEMFD_FLAG_MMAP (1ULL << 0)#define GUEST_MEMFD_FLAG_INIT_SHARED (1ULL << 1) +#define GUEST_MEMFD_FLAG_NO_DIRECT_MAP (1ULL << 2)struct kvm_create_guest_memfd {__u64 size;
virt/kvm/guest_memfd.c +75 -5
131 lines not on this page · raw message
Signature · 1 line
2.50.1
PATCH v10 11/15 KVM: selftests: set KVM_MEM_GUEST_MEMFD in vm_mem_add() if guest_memfd != -1
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
Have vm_mem_add() always set KVM_MEM_GUEST_MEMFD in the memslot flags if a guest_memfd is passed in as an argument. This eliminates the possibility where a guest_memfd instance is passed to vm_mem_add(), but it ends up being ignored because the flags argument does not specify KVM_MEM_GUEST_MEMFD at the same time.
This makes it easy to support more scenarios in which no vm_mem_add() is not passed a guest_memfd instance, but is expected to allocate one. Currently, this only happens if guest_memfd == -1 but flags & KVM_MEM_GUEST_MEMFD != 0, but later vm_mem_add() will gain support for loading the test code itself into guest_memfd (via GUEST_MEMFD_FLAG_MMAP) if requested via a special vm_mem_backing_src_type, at which point having to make sure the src_type and flags are in-sync becomes cumbersome.
--- tools/testing/selftests/kvm/lib/kvm_util.c | 24 +++++++++++++--------- 1 file changed, 14 insertions(+), 10 deletions(-)
tools/testing/selftests/kvm/lib/kvm_util.c +14 -10
@@ -1057,21 +1057,25 @@ void vm_mem_add(struct kvm_vm *vm, enum vm_mem_backing_src_type src_type, region->backing_src_type = src_type; -if (flags &KVM_MEM_GUEST_MEMFD ) { -if (guest_memfd <0 ) { +if (guest_memfd <0 ) { +if (flags &KVM_MEM_GUEST_MEMFD ) {uint32_t guest_memfd_flags =0 ;TEST_ASSERT (!guest_memfd_offset,"Offset must be zero when creating new guest_memfd" ); guest_memfd =vm_create_guest_memfd (vm, mem_size, guest_memfd_flags); - }else { -/* -* Install a unique fd for each memslot so that the fd -* can be closed when the region is deleted without -* needing to track if the fd is owned by the framework -* or by the caller. -*/ - guest_memfd =kvm_dup (guest_memfd); } + }else { +/* +* Install a unique fd for each memslot so that the fd +* can be closed when the region is deleted without +* needing to track if the fd is owned by the framework +* or by the caller. +*/ + guest_memfd =kvm_dup (guest_memfd); + } + +if (guest_memfd >=0 ) { + flags |=KVM_MEM_GUEST_MEMFD ; region->region.guest_memfd = guest_memfd; region->region.guest_memfd_offset = guest_memfd_offset;
Signature · 1 line
2.50.1
PATCH v10 10/15 KVM: selftests: load elf via bounce buffer
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
If guest memory is backed using a VMA that does not allow GUP (e.g. a userspace mapping of guest_memfd when the fd was allocated using GUEST_MEMFD_FLAG_NO_DIRECT_MAP), then directly loading the test ELF binary into it via read(2) potentially does not work. To nevertheless support loading binaries in this cases, do the read(2) syscall using a bounce buffer, and then memcpy from the bounce buffer into guest memory.
--- .../testing/selftests/kvm/include/test_util.h | 1 + tools/testing/selftests/kvm/lib/elf.c | 8 +++---- tools/testing/selftests/kvm/lib/io.c | 23 +++++++++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-)
tools/testing/selftests/kvm/include/test_util.h +1 -0
@@ -48,6 +48,7 @@ do { \ssize_t test_write (int fd,const void *buf,size_t count);ssize_t test_read (int fd,void *buf,size_t count); +ssize_t test_read_bounce (int fd,void *buf,size_t count);int test_seq_read (const char *path,char **bufp,size_t *sizep); void __printf(5, 6) test_assert(bool exp, const char *exp_str,
tools/testing/selftests/kvm/lib/elf.c +4 -4
@@ -31,7 +31,7 @@ static void elfhdr_get(const char *filename, Elf64_Ehdr *hdrp)* the real size of the ELF header. */ unsigned char ident[EI_NIDENT ]; -test_read (fd, ident,sizeof (ident)); +test_read_bounce (fd, ident,sizeof (ident));TEST_ASSERT ((ident[EI_MAG0 ] ==ELFMAG0 ) && (ident[EI_MAG1 ] ==ELFMAG1 ) && (ident[EI_MAG2 ] ==ELFMAG2 ) && (ident[EI_MAG3 ] ==ELFMAG3 ), "ELF MAGIC Mismatch,\n"
@@ -79,7 +79,7 @@ static void elfhdr_get(const char *filename, Elf64_Ehdr *hdrp) offset_rv =lseek (fd,0 ,SEEK_SET );TEST_ASSERT (offset_rv ==0 ,"Seek to ELF header failed,\n" " rv: %zi expected: %i" , offset_rv,0 ); -test_read (fd, hdrp,sizeof (*hdrp)); +test_read_bounce (fd, hdrp,sizeof (*hdrp));TEST_ASSERT (hdrp->e_phentsize ==sizeof (Elf64_Phdr),"Unexpected physical header size,\n" " hdrp->e_phentsize: %x\n"
@@ -146,7 +146,7 @@ void kvm_vm_elf_load(struct kvm_vm *vm, const char *filename)/* Read in the program header. */ Elf64_Phdr phdr; -test_read (fd, &phdr,sizeof (phdr)); +test_read_bounce (fd, &phdr,sizeof (phdr));/* Skip if this header doesn't describe a loadable segment. */ if (phdr.p_type !=PT_LOAD )
@@ -187,7 +187,7 @@ void kvm_vm_elf_load(struct kvm_vm *vm, const char *filename)" expected: 0x%jx" , n1, errno, (intmax_t ) offset_rv, (intmax_t) phdr.p_offset); -test_read (fd,addr_gva2hva (vm, phdr.p_vaddr), +test_read_bounce (fd,addr_gva2hva (vm, phdr.p_vaddr), phdr.p_filesz); } }
tools/testing/selftests/kvm/lib/io.c +23 -0
@@ -155,3 +155,26 @@ ssize_t test_read(int fd, void *buf, size_t count)return num_read; } + +/* Test read via intermediary buffer +* +* Same as test_read, except read(2)s happen into a bounce buffer that is memcpy'd +* to buf. For use with buffers that cannot be GUP'd (e.g. guest_memfd VMAs if +* guest_memfd was created with GUEST_MEMFD_FLAG_NO_DIRECT_MAP). +*/ +ssize_t test_read_bounce (int fd,void *buf,size_t count) +{ +void *bounce_buffer; +ssize_t num_read; + +TEST_ASSERT (count >=0 ,"Unexpected count, count: %li" , count); + + bounce_buffer =malloc (count); +TEST_ASSERT (bounce_buffer !=NULL ,"Failed to allocate bounce buffer" ); + + num_read =test_read (fd, bounce_buffer, count); +memcpy (buf, bounce_buffer, num_read); +free (bounce_buffer); + +return num_read; +}
Signature · 1 line
2.50.1
PATCH v10 13/15 KVM: selftests: cover GUEST_MEMFD_FLAG_NO_DIRECT_MAP in existing selftests
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
Extend mem conversion selftests to cover the scenario that the guest can fault in and write gmem-backed guest memory even if its direct map removed. Also cover the new flag in guest_memfd_test.c tests.
--- tools/testing/selftests/kvm/guest_memfd_test.c | 17 ++++++++++++++++- .../kvm/x86/private_mem_conversions_test.c | 7 ++++--- 2 files changed, 20 insertions(+), 4 deletions(-)
tools/testing/selftests/kvm/guest_memfd_test.c +16 -1
@@ -403,6 +403,17 @@ static void test_guest_memfd(unsigned long vm_type)__test_guest_memfd (vm,GUEST_MEMFD_FLAG_MMAP |GUEST_MEMFD_FLAG_INIT_SHARED ); +if (flags &GUEST_MEMFD_FLAG_NO_DIRECT_MAP ) { +__test_guest_memfd (vm,GUEST_MEMFD_FLAG_NO_DIRECT_MAP ); +if (flags &GUEST_MEMFD_FLAG_MMAP ) +__test_guest_memfd (vm,GUEST_MEMFD_FLAG_NO_DIRECT_MAP | +GUEST_MEMFD_FLAG_MMAP ); +if (flags &GUEST_MEMFD_FLAG_INIT_SHARED ) +__test_guest_memfd (vm,GUEST_MEMFD_FLAG_NO_DIRECT_MAP | +GUEST_MEMFD_FLAG_MMAP | +GUEST_MEMFD_FLAG_INIT_SHARED ); + } +kvm_vm_free (vm); }
@@ -445,10 +456,14 @@ static void test_guest_memfd_guest(void)TEST_ASSERT (vm_check_cap (vm,KVM_CAP_GUEST_MEMFD_FLAGS ) &GUEST_MEMFD_FLAG_INIT_SHARED ,"Default VM type should support INIT_SHARED, supported flags = 0x%x" ,vm_check_cap (vm,KVM_CAP_GUEST_MEMFD_FLAGS )); +TEST_ASSERT (vm_check_cap (vm,KVM_CAP_GUEST_MEMFD_FLAGS ) &GUEST_MEMFD_FLAG_NO_DIRECT_MAP , +"Default VM type should support INIT_SHARED, supported flags = 0x%x" , +vm_check_cap (vm,KVM_CAP_GUEST_MEMFD_FLAGS )); size = vm->page_size; fd =vm_create_guest_memfd (vm, size,GUEST_MEMFD_FLAG_MMAP | -GUEST_MEMFD_FLAG_INIT_SHARED ); +GUEST_MEMFD_FLAG_INIT_SHARED | +GUEST_MEMFD_FLAG_NO_DIRECT_MAP );vm_set_user_memory_region2 (vm, slot,KVM_MEM_GUEST_MEMFD , gpa, size,NULL , fd,0 ); mem =kvm_mmap (size,PROT_READ |PROT_WRITE ,MAP_SHARED , fd);
tools/testing/selftests/kvm/x86/private_mem_conversions_test.c +4 -3
@@ -367,7 +367,7 @@ static void *__test_mem_conversions(void *__vcpu) }static void test_mem_conversions (enum vm_mem_backing_src_type src_type,uint32_t nr_vcpus, -uint32_t nr_memslots) +uint32_t nr_memslots,uint64_t gmem_flags) {/* * Allocate enough memory so that each vCPU's chunk of memory can be
@@ -394,7 +394,7 @@ static void test_mem_conversions(enum vm_mem_backing_src_type src_type, uint32_tvm_enable_cap (vm,KVM_CAP_EXIT_HYPERCALL , (1 <<KVM_HC_MAP_GPA_RANGE )); - memfd =vm_create_guest_memfd (vm, memfd_size,0 ); + memfd =vm_create_guest_memfd (vm, memfd_size, gmem_flags);for (i =0 ; i < nr_memslots; i++) vm_mem_add(vm, src_type, BASE_DATA_GPA + slot_size * i,
@@ -474,7 +474,8 @@ int main(int argc, char *argv[]) } } -test_mem_conversions (src_type, nr_vcpus, nr_memslots); +test_mem_conversions (src_type, nr_vcpus, nr_memslots,0 ); +test_mem_conversions (src_type, nr_vcpus, nr_memslots,GUEST_MEMFD_FLAG_NO_DIRECT_MAP );return 0 ; }
Signature · 1 line
2.50.1
PATCH v10 12/15 KVM: selftests: Add guest_memfd based vm_mem_backing_src_types
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
Allow selftests to configure their memslots such that userspace_addr is set to a MAP_SHARED mapping of the guest_memfd that's associated with the memslot. This setup is the configuration for non-CoCo VMs, where all guest memory is backed by a guest_memfd whose folios are all marked shared, but KVM is still able to access guest memory to provide functionality such as MMIO emulation on x86.
Add backing types for normal guest_memfd, as well as direct map removed guest_memfd.
--- .../testing/selftests/kvm/include/kvm_util.h | 18 ++++++ .../testing/selftests/kvm/include/test_util.h | 7 +++ tools/testing/selftests/kvm/lib/kvm_util.c | 61 ++++++++++--------- tools/testing/selftests/kvm/lib/test_util.c | 8 +++ 4 files changed, 65 insertions(+), 29 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +18 -0
@@ -641,6 +641,24 @@ static inline bool is_smt_on(void)void vm_create_irqchip (struct kvm_vm *vm); +static inline uint32_t backing_src_guest_memfd_flags (enum vm_mem_backing_src_type t) +{ +uint32_t flags =0 ; + +switch (t) { +case VM_MEM_SRC_GUEST_MEMFD_NO_DIRECT_MAP : + flags |=GUEST_MEMFD_FLAG_NO_DIRECT_MAP ; + fallthrough; +case VM_MEM_SRC_GUEST_MEMFD : + flags |=GUEST_MEMFD_FLAG_MMAP |GUEST_MEMFD_FLAG_INIT_SHARED ; +break ; +default : +break ; + } + +return flags; +} +static inline int __vm_create_guest_memfd (struct kvm_vm *vm,uint64_t size,uint64_t flags) {
tools/testing/selftests/kvm/include/test_util.h +7 -0
@@ -152,6 +152,8 @@ enum vm_mem_backing_src_type {VM_MEM_SRC_ANONYMOUS_HUGETLB_16GB ,VM_MEM_SRC_SHMEM ,VM_MEM_SRC_SHARED_HUGETLB , +VM_MEM_SRC_GUEST_MEMFD , +VM_MEM_SRC_GUEST_MEMFD_NO_DIRECT_MAP , NUM_SRC_TYPES, };
@@ -184,6 +186,11 @@ static inline bool backing_src_is_shared(enum vm_mem_backing_src_type t)return vm_mem_backing_src_alias (t)->flag &MAP_SHARED ; } +static inline bool backing_src_is_guest_memfd (enum vm_mem_backing_src_type t) +{ +return t ==VM_MEM_SRC_GUEST_MEMFD || t ==VM_MEM_SRC_GUEST_MEMFD_NO_DIRECT_MAP ; +} +static inline bool backing_src_can_be_huge (enum vm_mem_backing_src_type t) {return t !=VM_MEM_SRC_ANONYMOUS && t !=VM_MEM_SRC_SHMEM ;
tools/testing/selftests/kvm/lib/kvm_util.c +32 -29
81 lines not on this page · raw message
tools/testing/selftests/kvm/lib/test_util.c +8 -0
@@ -306,6 +306,14 @@ const struct vm_mem_backing_src_alias *vm_mem_backing_src_alias(uint32_t i)*/ .flag = MAP_SHARED, }, + [VM_MEM_SRC_GUEST_MEMFD] = { + .name = "guest_memfd", + .flag = MAP_SHARED, + }, + [VM_MEM_SRC_GUEST_MEMFD_NO_DIRECT_MAP] = { + .name = "guest_memfd_no_direct_map", + .flag = MAP_SHARED, + } };_Static_assert (ARRAY_SIZE (aliases) ==NUM_SRC_TYPES ,"Missing new backing src types?" );
Signature · 1 line
2.50.1
PATCH v10 15/15 KVM: selftests: Test guest execution from direct map removed gmem
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
Add a selftest that loads itself into guest_memfd (via GUEST_MEMFD_FLAG_MMAP) and triggers an MMIO exit when executed. This exercises x86 MMIO emulation code inside KVM for guest_memfd-backed memslots where the guest_memfd folios are direct map removed. Particularly, it validates that x86 MMIO emulation code (guest page table walks + instruction fetch) correctly accesses gmem through the VMA that's been reflected into the memslot's userspace_addr field (instead of trying to do direct map accesses).
--- .../selftests/kvm/set_memory_region_test.c | 52 +++++++++++++++++-- 1 file changed, 48 insertions(+), 4 deletions(-)
tools/testing/selftests/kvm/set_memory_region_test.c +48 -4
@@ -602,6 +602,41 @@ static void test_mmio_during_vectoring(void)kvm_vm_free (vm); } + +static void guest_code_trigger_mmio (void ) +{ +/* +* Read some GPA that is not backed by a memslot. KVM consider this +* as MMIO and tell userspace to emulate the read. +*/ +READ_ONCE (*((uint64_t *)MEM_REGION_GPA )); + +GUEST_DONE (); +} + +static void test_guest_memfd_mmio (void ) +{ +struct kvm_vm *vm; +struct kvm_vcpu *vcpu; +struct vm_shape shape = { + .mode =VM_MODE_DEFAULT , + .src_type =VM_MEM_SRC_GUEST_MEMFD_NO_DIRECT_MAP , + }; +pthread_t vcpu_thread; + +pr_info ("Testing MMIO emulation for instructions in gmem\n" ); + + vm =__vm_create_shape_with_one_vcpu (shape, &vcpu,0 , guest_code_trigger_mmio); + +virt_map (vm,MEM_REGION_GPA ,MEM_REGION_GPA ,1 ); + +pthread_create (&vcpu_thread,NULL , vcpu_worker, vcpu); + +/* If the MMIO read was successfully emulated, the vcpu thread will exit */ +pthread_join (vcpu_thread,NULL ); + +kvm_vm_free (vm); +}#endif int main (int argc,char *argv[])
@@ -625,10 +660,19 @@ int main(int argc, char *argv[])test_add_max_memory_regions ();#ifdef __x86_64__ -if (kvm_has_cap (KVM_CAP_GUEST_MEMFD ) && - (kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (KVM_X86_SW_PROTECTED_VM ))) { -test_add_private_memory_region (); -test_add_overlapping_private_memory_regions (); +if (kvm_has_cap (KVM_CAP_GUEST_MEMFD )) { +uint64_t valid_flags =kvm_check_cap (KVM_CAP_GUEST_MEMFD_FLAGS ); + +if (kvm_check_cap (KVM_CAP_VM_TYPES ) &BIT (KVM_X86_SW_PROTECTED_VM )) { +test_add_private_memory_region (); +test_add_overlapping_private_memory_regions (); + } + +if ((valid_flags &GUEST_MEMFD_FLAG_MMAP ) + && (valid_flags &GUEST_MEMFD_FLAG_NO_DIRECT_MAP )) +test_guest_memfd_mmio (); +else +pr_info ("Skipping tests requiring GUEST_MEMFD_FLAG_MMAP | GUEST_MEMFD_FLAG_NO_DIRECT_MAP" ); }else {pr_info ("Skipping tests for KVM_MEM_GUEST_MEMFD memory regions\n" ); }
Signature · 1 line
2.50.1
PATCH v10 14/15 KVM: selftests: stuff vm_mem_backing_src_type into vm_shape
In reply to Kalyazin, NikitaFrom: Patrick Roy <[email protected]>
Use one of the padding fields in struct vm_shape to carry an enum vm_mem_backing_src_type value, to give the option to overwrite the default of VM_MEM_SRC_ANONYMOUS in __vm_create().
Overwriting this default will allow tests to create VMs where the test code is backed by mmap'd guest_memfd instead of anonymous memory.
--- .../testing/selftests/kvm/include/kvm_util.h | 19 ++++++++++--------- tools/testing/selftests/kvm/lib/kvm_util.c | 2 +- tools/testing/selftests/kvm/lib/x86/sev.c | 1 + .../selftests/kvm/pre_fault_memory_test.c | 1 + 4 files changed, 13 insertions(+), 10 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +10 -9
@@ -192,7 +192,7 @@ enum vm_guest_mode {struct vm_shape {uint32_t type;uint8_t mode; -uint8_t pad0; +uint8_t src_type;uint16_t pad1; };
@@ -200,14 +200,15 @@ kvm_static_assert(sizeof(struct vm_shape) == sizeof(uint64_t));#define VM_TYPE_DEFAULT 0 -#define VM_SHAPE (__mode) \ -({ \ - struct vm_shape shape = { \ - .mode = (__mode), \ - .type = VM_TYPE_DEFAULT \ - }; \ - \ - shape; \ +#define VM_SHAPE (__mode) \ +({ \ + struct vm_shape shape = { \ + .mode = (__mode), \ + .type = VM_TYPE_DEFAULT, \ + .src_type = VM_MEM_SRC_ANONYMOUS \ + }; \ + \ + shape; \ })#if defined(__aarch64__)
tools/testing/selftests/kvm/lib/kvm_util.c +1 -1
@@ -467,7 +467,7 @@ struct kvm_vm *__vm_create(struct vm_shape shape, uint32_t nr_runnable_vcpus,if (is_guest_memfd_required (shape)) flags |=KVM_MEM_GUEST_MEMFD ; -vm_userspace_mem_region_add (vm,VM_MEM_SRC_ANONYMOUS ,0 ,0 , nr_pages, flags); +vm_userspace_mem_region_add (vm, shape.src_type,0 ,0 , nr_pages, flags);for (i =0 ; i <NR_MEM_REGIONS ; i++) vm->memslots[i] =0 ;
tools/testing/selftests/kvm/lib/x86/sev.c +1 -0
@@ -164,6 +164,7 @@ struct kvm_vm *vm_sev_create_with_one_vcpu(uint32_t type, void *guest_code,struct vm_shape shape = { .mode =VM_MODE_DEFAULT , .type = type, + .src_type =VM_MEM_SRC_ANONYMOUS , };struct kvm_vm *vm;struct kvm_vcpu *cpus[1 ];
tools/testing/selftests/kvm/pre_fault_memory_test.c +1 -0
@@ -165,6 +165,7 @@ static void __test_pre_fault_memory(unsigned long vm_type, bool private)const struct vm_shape shape = { .mode =VM_MODE_DEFAULT , .type = vm_type, + .src_type =VM_MEM_SRC_ANONYMOUS , };struct kvm_vcpu *vcpu;struct kvm_run *run;
Signature · 1 line
2.50.1
kernel test robot
build botRe: [PATCH v10 01/15] set_memory: set_direct_map_* to take address
In reply to Kalyazin, Nikitakernel test robot noticed the following build errors:
Hi Nikita,
kernel test robot noticed the following build errors:
[auto build test ERROR on 0499add8efd72456514c6218c062911ccc922a99]
url: https://github.com/intel-lab-lkp/linux/commits/Kalyazin-Nikita/set_memory-set_direct_map_-to-take-address/20260127-005641 base: 0499add8efd72456514c6218c062911ccc922a99 patch link: https://lore.kernel.org/r/20260126164445.11867-2-kalyazin%40amazon.com patch subject: [PATCH v10 01/15] set_memory: set_direct_map_* to take address config: loongarch-allnoconfig (https://download.01.org/0day-ci/archive/20260128/[email protected]/config) compiler: clang version 22.0.0git (https://github.com/llvm/llvm-project 9b8addffa70cee5b2acc5454712d9cf78ce45710) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260128/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
>> arch/loongarch/mm/pageattr.c:211:16: error: redefinition of 'addr' with a different type: 'unsigned long' vs 'const void *'
211 | unsigned long addr = (unsigned long)addr;
| ^ arch/loongarch/mm/pageattr.c:209:48: note: previous definition is here
209 | int set_direct_map_invalid_noflush(const void *addr)
| ^
1 error generated.
vim +211 arch/loongarch/mm/pageattr.c
208
209 int set_direct_map_invalid_noflush(const void *addr)
210 {
> 211 unsigned long addr = (unsigned long)addr;
212
213 if ((unsigned long)addr < vm_map_base)
214 return 0;
215
216 return __set_memory((unsigned long)addr, 1, __pgprot(0),
217 __pgprot(_PAGE_PRESENT | _PAGE_VALID));
218 }
219
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Re: [PATCH v10 01/15] set_memory: set_direct_map_* to take address
In reply to Kalyazin, NikitaQuoted 23 lines · Nikita
From: Nikita Kalyazin <[email protected]>
This is to avoid excessive conversions
folio->page->addresswhen adding helpers on top ofset_direct_map_valid_noflush()in the next patch.Signed-off-by Nikita Kalyazin <[email protected]>--- arch/arm64/include/asm/set_memory.h | 7 ++++--- arch/arm64/mm/pageattr.c | 19 +++++++++---------- arch/loongarch/include/asm/set_memory.h | 7 ++++--- arch/loongarch/mm/pageattr.c | 25 ++++++++++++------------- arch/riscv/include/asm/set_memory.h | 7 ++++--- arch/riscv/mm/pageattr.c | 17 +++++++++-------- arch/s390/include/asm/set_memory.h | 7 ++++--- arch/s390/mm/pageattr.c | 13 +++++++------ arch/x86/include/asm/set_memory.h | 7 ++++--- arch/x86/mm/pat/set_memory.c | 23 ++++++++++++----------- include/linux/set_memory.h | 9 +++++---- kernel/power/snapshot.c | 4 ++-- mm/execmem.c | 6 ++++-- mm/secretmem.c | 6 +++--- mm/vmalloc.c | 11 +++++++---- 15 files changed, 90 insertions(+), 78 deletions(-)
[...]
Quoted 14 lines
arch/loongarch/mm/pageattr.c +2
-4@@ -198,32 +198,31 @@ bool kernel_page_present(struct page *page)return pte_present (ptep_get (pte)); } -int set_direct_map_default_noflush (struct page *page) +int set_direct_map_default_noflush (const void *addr) { -unsigned long addr = (unsigned long )page_address (page); - -if (addr < vm_map_base) +if ((unsigned long )addr < vm_map_base)return 0 ;
arch/loongarch/mm/pageattr.c bool kernel_page_present(struct page *page) · line 211
Quoted 10 lines
arch/loongarch/mm/pageattr.c +3
-3-return __set_memory (addr,1 ,PAGE_KERNEL ,__pgprot (0 )); +return __set_memory ((unsigned long )addr,1 ,PAGE_KERNEL ,__pgprot (0 )); } -int set_direct_map_invalid_noflush (struct page *page) +int set_direct_map_invalid_noflush (const void *addr) { -unsigned long addr = (unsigned long )page_address (page); +unsigned long addr = (unsigned long )addr;
Are you sure you want a local variable with the exact same name
...
arch/loongarch/mm/pageattr.c bool kernel_page_present(struct page *page) · line 217
Quoted 8 lines
arch/loongarch/mm/pageattr.c +3
-2-if (addr < vm_map_base) +if ((unsigned long )addr < vm_map_base)return 0 ; -return __set_memory (addr,1 ,__pgprot (0 ),__pgprot (_PAGE_PRESENT | _PAGE_VALID)); +return __set_memory ((unsigned long )addr,1 ,__pgprot (0 ), +__pgprot (_PAGE_PRESENT | _PAGE_VALID));
And cast it to (unsigned long) even though not required two times? :)
I assume you wanted to get rid of the local varable.
arch/loongarch/mm/pageattr.c bool kernel_page_present(struct page *page) · line 220
Quoted 5 lines
arch/loongarch/mm/pageattr.c +2
-1} -int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid) +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid)
Nothing else jumped at me.
It would be good to get some ACK from some arch people that are CCed :)
Signature · 3 lines
Cheers, David
David Hildenbrand (Arm)
maintainerRe: [PATCH v10 02/15] set_memory: add folio_{zap,restore}_direct_map helpers
In reply to Kalyazin, NikitaQuoted 6 lines · Nikita
From: Nikita Kalyazin <[email protected]>
These allow
guest_memfdto remove its memory from the direct map. Only implement them for architectures that have direct map. Infolio_zap_direct_map(), flush TLB on architectures whereset_direct_map_valid_noflush()does not flush it internally.
"Let's provide folio_{zap,restore}_direct_map helpers as preparation for supporting removal of the direct map for guest_memfd folios. ...
Quoted 8 lines
The new helpers need to be accessible to KVM on architectures that support
guest_memfd(x86 and arm64). Since arm64 does not support building KVM as a module, only export them on x86.Direct map removal gives
guest_memfdthe same protection thatmemfd_secretdoes, such as hardening against Spectre-like attacks through in-kernel gadgets.
Would it be possible to convert mm/secretmem.c as well?
There, we use
set_direct_map_invalid_noflush(folio_page(folio, 0));
and
set_direct_map_default_noflush(folio_page(folio, 0));
Which is a bit different to below code. At least looking at the x86 variants, I wonder why we don't simply use set_direct_map_valid_noflush().
If so, can you add a patch to do the conversion, pleeeeassse ? :)
Quoted 39 lines
Reviewed-by Ackerley Tng <[email protected]>Signed-off-by Nikita Kalyazin <[email protected]>--- arch/arm64/include/asm/set_memory.h | 2 ++ arch/arm64/mm/pageattr.c | 12 ++++++++++++ arch/loongarch/include/asm/set_memory.h | 2 ++ arch/loongarch/mm/pageattr.c | 12 ++++++++++++ arch/riscv/include/asm/set_memory.h | 2 ++ arch/riscv/mm/pageattr.c | 12 ++++++++++++ arch/s390/include/asm/set_memory.h | 2 ++ arch/s390/mm/pageattr.c | 12 ++++++++++++ arch/x86/include/asm/set_memory.h | 2 ++ arch/x86/mm/pat/set_memory.c | 20 ++++++++++++++++++++ include/linux/set_memory.h | 10 ++++++++++ 11 files changed, 88 insertions(+)arch/arm64/include/asm/set_memory.h +2
-0@@ -15,6 +15,8 @@ int set_direct_map_invalid_noflush(const void *addr);int set_direct_map_default_noflush (const void *addr);int set_direct_map_valid_noflush (const void *addr,unsigned long numpages,bool valid); +int folio_zap_direct_map (struct folio *folio); +int folio_restore_direct_map (struct folio *folio);bool kernel_page_present (struct page *page);int set_memory_encrypted (unsigned long addr,int numpages);arch/arm64/mm/pageattr.c +1
-0@@ -356,6 +356,18 @@ int set_direct_map_valid_noflush(const void *addr, unsigned long numpages,return set_memory_valid ((unsigned long )addr, numpages, valid); } +int folio_zap_direct_map (struct folio *folio)
arch/arm64/mm/pageattr.c int set_direct_map_valid_noflush(const void *addr, unsigned long numpages, · line 369
Quoted 10 lines
arch/arm64/mm/pageattr.c +10
-0+{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), false); +} + +int folio_restore_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), true); +}
Is there a good reason why we cannot have two generic inline functions that simply call set_direct_map_valid_noflush() ?
Is it because of some flushing behavior? (which we could figure out)
In particular, a single set of functions could have a beautiful centralized kerneldoc, right?! :)
Signature · 3 lines
Cheers, David
David Hildenbrand (Arm)
maintainerRe: [PATCH v10 04/15] mm/gup: drop local variable in gup_fast_folio_allowed
In reply to Kalyazin, NikitaQuoted 37 lines · Nikita
From: Nikita Kalyazin <[email protected]>
Move the check for pinning closer to where the result is used. No functional changes.
Signed-off-by Nikita Kalyazin <[email protected]>--- mm/gup.c | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-)mm/gup.c +0
-9@@ -2737,18 +2737,9 @@ EXPORT_SYMBOL(get_user_pages_unlocked);*/ static bool gup_fast_folio_allowed (struct folio *folio,unsigned int flags) { -bool reject_file_backed = false;struct address_space *mapping;unsigned long mapping_flags; -/* -* If we aren't pinning then no problematic write can occur. A long term -* pin is the most egregious case so this is the one we disallow. -*/ -if ((flags & (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE )) == - (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE )) - reject_file_backed = true; -/* We hold a folio reference, so we can safely access folio fields. */ if (WARN_ON_ONCE (folio_test_slab (folio)))return false;@@ -2793,8 +2784,14 @@ static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags)*/ if (secretmem_mapping (mapping))return false;
mm/gup.c static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags) · line 2794
Quoted 10 lines
mm/gup.c +8
-2-/* The only remaining allowed file system is shmem. */ -return !reject_file_backed ||shmem_mapping (mapping); + +/* +* If we aren't pinning then no problematic write can occur. A long term +* pin is the most egregious case so this is the one we disallow. +* Also check the only remaining allowed file system - shmem. +*/ +return (flags & (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE )) != + (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE ) ||shmem_mapping (mapping);
Best to keep this split and a bit more readable.
/*
* If we aren't pinning then no problematic write can occur. A writable
* long term pin is the most egregious case, so this is the one we
* allow only for ...
*/
if ((flags & (FOLL_PIN | FOLL_LONGTERM | FOLL_WRITE)) !=
(FOLL_PIN | FOLL_LONGTERM | FOLL_WRITE)
return true;
/* ... hugetlb (which we allowed above already) and shared memory. */ return shmem_mapping(mapping);
Quoted 3 lines
mm/gup.c +0
-0} static void __maybe_unused gup_fast_undo_dev_pagemap(int *nr, int nr_start,
Signature · 3 lines
Cheers, David
Re: [PATCH v10 07/15] KVM: x86: define kvm_arch_gmem_supports_no_direct_map()
In reply to Kalyazin, NikitaQuoted 9 lines · Nikita
From: Patrick Roy <[email protected]>
x86 supports
GUEST_MEMFD_FLAG_NO_DIRECT_MAPwhenever direct map modifications are possible (which is always the case).Signed-off-by Patrick Roy <[email protected]>Reviewed-by Ackerley Tng <[email protected]>Signed-off-by Nikita Kalyazin <[email protected]>---
Signature · 3 lines
Cheers, David
Re: [PATCH v10 08/15] KVM: arm64: define kvm_arch_gmem_supports_no_direct_map()
In reply to Kalyazin, NikitaQuoted 19 lines · Nikita
From: Patrick Roy <[email protected]>
Support for
GUEST_MEMFD_FLAG_NO_DIRECT_MAPon arm64 depends on 1) direct map manipulations at 4k granularity being possible, and 2)FEAT_S2FWB.1) is met whenever the direct map is set up at 4k granularity (e.g. not with huge/gigantic pages) at boottime, as due to ARM's
break-before-make semantics, breaking huge mappings into 4k mappings in the direct map is not possible (BBM would require temporary invalidation of the entire huge mapping, even if only a 4k subrange should be zapped, which will probably crash the kernel). However, the current default forrodata_fullis true, which forces a 4k direct map.2) is required to allow KVM to elide cache coherency operations when installing stage 2 page tables, which require the direct map to be entry for the newly mapped memory to be present (which it will not be, as
guest_memfdwould have removed direct map entries inkvm_gmem_get_pfn()).
Quoted 4 lines
Cc Will Deacon <[email protected]>Signed-off-by Patrick Roy <[email protected]>Signed-off-by Nikita Kalyazin <[email protected]>---
Signature · 3 lines
Cheers, David
David Hildenbrand (Arm)
maintainerRe: [PATCH v10 09/15] KVM: guest_memfd: Add flag to remove from direct map
In reply to Kalyazin, NikitaQuoted 84 lines · Nikita
From: Patrick Roy <[email protected]>
Add
GUEST_MEMFD_FLAG_NO_DIRECT_MAPflag forKVM_CREATE_GUEST_MEMFD()ioctl. When set,guest_memfdfolios will be removed from the direct map after preparation, with direct map entries only restored when the folios are freed.To ensure these folios do not end up in places where the kernel cannot deal with them, set
AS_NO_DIRECT_MAPon the guest_memfd's structaddress_spaceifGUEST_MEMFD_FLAG_NO_DIRECT_MAPis requested.Note that this flag causes removal of direct map entries for all
guest_memfdfolios independent of whether they are "shared" or "private" (although currentguest_memfdonly supports either all folios in the "shared" state, or all folios in the "private" state ifGUEST_MEMFD_FLAG_MMAPis not set). The usecase for removing direct map entries of also the shared parts ofguest_memfdare a special type of non-CoCo VM where, host userspace is trusted to have access to all of guest memory, but where Spectre-style transient execution attacks through the host kernel's direct map should still be mitigated. In this setup, KVM retains access to guest memory via userspace mappings ofguest_memfd, which are reflected back into KVM's memslots viauserspace_addr. This is needed for things like MMIO emulation onx86_64to work.Direct map entries are zapped right before guest or userspace mappings of gmem folios are set up, e.g. in
kvm_gmem_fault_user_mapping()orkvm_gmem_get_pfn()[called from the KVM MMU code]. The only place where a gmem folio can be allocated without being mapped anywhere iskvm_gmem_populate(), where handling potential failures of direct map removal is not possible (by the time direct map removal is attempted, the folio is already marked as prepared, meaning attempting to re-trykvm_gmem_populate()would just result in-EEXISTwithout fixing up the direct map state). These folios are then removed form the direct map uponkvm_gmem_get_pfn(), e.g. when they are mapped into the guest later.Signed-off-by Patrick Roy <[email protected]>Signed-off-by Nikita Kalyazin <[email protected]>--- Documentation/virt/kvm/api.rst | 21 +++++---- arch/x86/include/asm/kvm_host.h | 5 +-- arch/x86/kvm/x86.c | 5 +++ include/linux/kvm_host.h | 12 +++++ include/uapi/linux/kvm.h | 1 + virt/kvm/guest_memfd.c | 80 ++++++++++++++++++++++++++++++--- 6 files changed, 106 insertions(+), 18 deletions(-)Documentation/virt/kvm/api.rst +12
-9@@ -6440,15 +6440,18 @@ a single guest_memfd file, but the bound ranges must not overlap). The capability KVM_CAP_GUEST_MEMFD_FLAGS enumerates the `flags` that can be specified via KVM_CREATE_GUEST_MEMFD. Currently defined flags: - ============================ ================================================ - GUEST_MEMFD_FLAG_MMAP Enable using mmap() on the guest_memfd file - descriptor. - GUEST_MEMFD_FLAG_INIT_SHARED Make all memory in the file shared during - KVM_CREATE_GUEST_MEMFD (memory files created - without INIT_SHARED will be marked private). - Shared memory can be faulted into host userspace - page tables. Private memory cannot. - ============================ ================================================ + ============================== ================================================ + GUEST_MEMFD_FLAG_MMAP Enable using mmap() on the guest_memfd file + descriptor. + GUEST_MEMFD_FLAG_INIT_SHARED Make all memory in the file shared during + KVM_CREATE_GUEST_MEMFD (memory files created + without INIT_SHARED will be marked private). + Shared memory can be faulted into host userspace + page tables. Private memory cannot. + GUEST_MEMFD_FLAG_NO_DIRECT_MAP The guest_memfd instance will unmap the memory + backing it from the kernel's address space + before passing it off to userspace or the guest. + ============================== ================================================ When the KVM MMU performs a PFN lookup to service a guest fault and the backing guest_memfd has the GUEST_MEMFD_FLAG_MMAP set, then the fault will always bearch/x86/include/asm/kvm_host.h +0
-0
arch/x86/include/asm/kvm_host.h static inline bool kvm_arch_has_irq_bypass(void) · line 2486
Quoted 8 lines
arch/x86/include/asm/kvm_host.h +1
-4@@ -2483,10 +2483,7 @@ static inline bool kvm_arch_has_irq_bypass(void) }#ifdef CONFIG_KVM_GUEST_MEMFD -static inline bool kvm_arch_gmem_supports_no_direct_map (void ) -{ -return can_set_direct_map (); -} +bool kvm_arch_gmem_supports_no_direct_map (struct kvm *kvm);
It's odd given that you introduced that code two patches previously. Can these changes directly be squashed into the earlier patch? [...]
Quoted 8 lines
arch/x86/include/asm/kvm_host.h +7
-0+#define KVM_GMEM_FOLIO_NO_DIRECT_MAP BIT(0) + +static bool kvm_gmem_folio_no_direct_map (struct folio *folio) +{ +return ((u64 )folio->private) &KVM_GMEM_FOLIO_NO_DIRECT_MAP ; +} +
arch/x86/include/asm/kvm_host.h static inline bool kvm_arch_has_irq_bypass(void)
Quoted 10 lines
arch/x86/include/asm/kvm_host.h +10
-0+static int kvm_gmem_folio_zap_direct_map (struct folio *folio) +{ +u64 gmem_flags =GMEM_I (folio_inode (folio))->flags; +int r =0 ; + +if (kvm_gmem_folio_no_direct_map (folio) || !(gmem_flags &GUEST_MEMFD_FLAG_NO_DIRECT_MAP )) + goto out; + + folio->private = (void *)((u64 )folio->private |KVM_GMEM_FOLIO_NO_DIRECT_MAP ); + r =folio_zap_direct_map (folio);
And if it fails, you'd leave KVM_GMEM_FOLIO_NO_DIRECT_MAP set.
What about modifying ->private only if it really worked?
Quoted 7 lines
arch/x86/include/asm/kvm_host.h +7
-0+ +out: +return r; +} + +static void kvm_gmem_folio_restore_direct_map (struct folio *folio) +{
arch/x86/include/asm/kvm_host.h
Quoted 10 lines
arch/x86/include/asm/kvm_host.h +10
-0+/* +* Direct map restoration cannot fail, as the only error condition +* for direct map manipulation is failure to allocate page tables +* when splitting huge pages, but this split would have already +* happened in folio_zap_direct_map() in kvm_gmem_folio_zap_direct_map(). +* Note that the splitting occurs always because guest_memfd +* currently supports only base pages. +* Thus folio_restore_direct_map() here only updates prot bits. +*/ +WARN_ON_ONCE (folio_restore_direct_map (folio));
Which raised the question: why should this function then even return an error?
Quoted 65 lines
arch/x86/include/asm/kvm_host.h +24
-1+ folio->private = (void *)((u64 )folio->private & ~KVM_GMEM_FOLIO_NO_DIRECT_MAP ); +} +static inline void kvm_gmem_mark_prepared (struct folio *folio) {folio_mark_uptodate (folio);@@ -393,11 +433,17 @@ static bool kvm_gmem_supports_mmap(struct inode *inode)return GMEM_I (inode)->flags &GUEST_MEMFD_FLAG_MMAP ; } +static bool kvm_gmem_no_direct_map (struct inode *inode) +{ +return GMEM_I (inode)->flags &GUEST_MEMFD_FLAG_NO_DIRECT_MAP ; +} +static vm_fault_t kvm_gmem_fault_user_mapping (struct vm_fault *vmf) {struct inode *inode =file_inode (vmf->vma->vm_file);struct folio *folio;vm_fault_t ret =VM_FAULT_LOCKED ; +int err;if (((loff_t )vmf->pgoff <<PAGE_SHIFT ) >=i_size_read (inode))return VM_FAULT_SIGBUS ;@@ -423,6 +469,14 @@ static vm_fault_t kvm_gmem_fault_user_mapping(struct vm_fault *vmf)kvm_gmem_mark_prepared (folio); } +if (kvm_gmem_no_direct_map (folio_inode (folio))) { + err =kvm_gmem_folio_zap_direct_map (folio); +if (err) { + ret =vmf_error (err); + goto out_folio; + } + } + vmf->page =folio_file_page (folio, vmf->pgoff); out_folio:@@ -533,6 +587,9 @@ static void kvm_gmem_free_folio(struct folio *folio)kvm_pfn_t pfn =page_to_pfn (page);int order =folio_order (folio); +if (kvm_gmem_folio_no_direct_map (folio)) +kvm_gmem_folio_restore_direct_map (folio); +kvm_arch_gmem_invalidate (pfn, pfn + (1ul << order)); }@@ -596,6 +653,9 @@ static int __kvm_gmem_create(struct kvm *kvm, loff_t size, u64 flags)/* Unmovable mappings are supposed to be marked unevictable as well. */ WARN_ON_ONCE (!mapping_unevictable (inode->i_mapping)); +if (flags &GUEST_MEMFD_FLAG_NO_DIRECT_MAP ) +mapping_set_no_direct_map (inode->i_mapping); +GMEM_I (inode)->flags = flags; file =alloc_file_pseudo (inode, kvm_gmem_mnt, name,O_RDWR , &kvm_gmem_fops);@@ -804,15 +864,25 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,if (IS_ERR (folio))return PTR_ERR (folio); -if (!is_prepared) +if (!is_prepared) {
arch/x86/include/asm/kvm_host.h int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 877
Quoted 10 lines
arch/x86/include/asm/kvm_host.h +9
-0r =kvm_gmem_prepare_folio (kvm, slot, gfn, folio); +if (r) + goto out_unlock; + } + +if (kvm_gmem_no_direct_map (folio_inode (folio))) { + r =kvm_gmem_folio_zap_direct_map (folio); +if (r) + goto out_unlock; + }
It's a bit nasty that we have two different places where we have to call this. Smells error prone.
I was wondering why kvm_gmem_get_folio() cannot handle that?
Then also fallocate() would directly be handled directly, instead of later at fault time etc.
Is it because __kvm_gmem_populate() etc need to write to this page?
Signature · 3 lines
Cheers, David
Re: [PATCH v10 01/15] set_memory: set_direct_map_* to take address
In reply to David Hildenbrand (Arm)Quoted 46 lines · David Hildenbrand (Arm)
Quoted 23 lines · Nikita
From: Nikita Kalyazin <[email protected]>
This is to avoid excessive conversions
folio->page->addresswhen adding helpers on top ofset_direct_map_valid_noflush()in the next patch.Signed-off-by Nikita Kalyazin <[email protected]>--- arch/arm64/include/asm/set_memory.h | 7 ++++--- arch/arm64/mm/pageattr.c | 19 +++++++++---------- arch/loongarch/include/asm/set_memory.h | 7 ++++--- arch/loongarch/mm/pageattr.c | 25 ++++++++++++------------- arch/riscv/include/asm/set_memory.h | 7 ++++--- arch/riscv/mm/pageattr.c | 17 +++++++++-------- arch/s390/include/asm/set_memory.h | 7 ++++--- arch/s390/mm/pageattr.c | 13 +++++++------ arch/x86/include/asm/set_memory.h | 7 ++++--- arch/x86/mm/pat/set_memory.c | 23 ++++++++++++----------- include/linux/set_memory.h | 9 +++++---- kernel/power/snapshot.c | 4 ++-- mm/execmem.c | 6 ++++-- mm/secretmem.c | 6 +++--- mm/vmalloc.c | 11 +++++++---- 15 files changed, 90 insertions(+), 78 deletions(-)[...]
Quoted 19 lines
arch/loongarch/mm/pageattr.c +3
-5@@ -198,32 +198,31 @@ bool kernel_page_present(struct page *page)return pte_present (ptep_get (pte)); } -int set_direct_map_default_noflush (struct page *page) +int set_direct_map_default_noflush (const void *addr) { -unsigned long addr = (unsigned long )page_address (page); - -if (addr < vm_map_base) +if ((unsigned long )addr < vm_map_base)return 0 ; -return __set_memory (addr,1 ,PAGE_KERNEL ,__pgprot (0 )); +return __set_memory ((unsigned long )addr,1 ,PAGE_KERNEL ,__pgprot (0 )); }
Quoted 8 lines
arch/loongarch/mm/pageattr.c bool kernel_page_present(struct page *page) · line 211
Quoted 5 lines
arch/loongarch/mm/pageattr.c +2
-2-int set_direct_map_invalid_noflush (struct page *page) +int set_direct_map_invalid_noflush (const void *addr) { -unsigned long addr = (unsigned long )page_address (page); +unsigned long addr = (unsigned long )addr;Are you sure you want a local variable with the exact same name
You're right. Thanks for spotting that.
Quoted 7 lines
...
Quoted 5 lines
arch/loongarch/mm/pageattr.c +1
-1-if (addr < vm_map_base) +if ((unsigned long )addr < vm_map_base)return 0 ;
Quoted 7 lines
arch/loongarch/mm/pageattr.c bool kernel_page_present(struct page *page) · line 217
Quoted 3 lines
arch/loongarch/mm/pageattr.c +2
-1-return __set_memory (addr,1 ,__pgprot (0 ),__pgprot (_PAGE_PRESENT | _PAGE_VALID)); +return __set_memory ((unsigned long )addr,1 ,__pgprot (0 ), +__pgprot (_PAGE_PRESENT | _PAGE_VALID));And cast it to (unsigned long) even though not required two times? :)
I assume you wanted to get rid of the local varable.
Yes, that's what I meant.
Quoted 11 lines
arch/loongarch/mm/pageattr.c
Quoted 6 lines
}arch/loongarch/mm/pageattr.c +2
-1-int set_direct_map_valid_noflush (struct page *page,unsigned nr,bool valid) +int set_direct_map_valid_noflush (const void *addr,unsigned long numpages, +bool valid)Nothing else jumped at me.
Quoted 1 line
Thanks!
Quoted 7 lines
It would be good to get some ACK from some arch people that are CCed :)
--
Cheers,David
Re: [PATCH v10 02/15] set_memory: add folio_{zap, restore}_direct_map helpers
In reply to David Hildenbrand (Arm)Quoted 10 lines · David Hildenbrand (Arm)
Quoted 6 lines · Nikita
From: Nikita Kalyazin <[email protected]>
These allow
guest_memfdto remove its memory from the direct map. Only implement them for architectures that have direct map. Infolio_zap_direct_map(), flush TLB on architectures whereset_direct_map_valid_noflush()does not flush it internally."Let's provide folio_{zap,restore}_direct_map helpers as preparation for supporting removal of the direct map for
guest_memfdfolios. ...
Will update, thanks.
Quoted 18 lines
Quoted 9 lines
The new helpers need to be accessible to KVM on architectures that support
guest_memfd(x86 and arm64). Since arm64 does not support building KVM as a module, only export them on x86.Direct map removal gives
guest_memfdthe same protection thatmemfd_secretdoes, such as hardening against Spectre-like attacks through in-kernel gadgets.Would it be possible to convert
mm/secretmem.cas well?There, we use
set_direct_map_invalid_noflush(folio_page(folio, 0));and
Quoted 7 lines
set_direct_map_default_noflush(folio_page(folio, 0));Which is a bit different to below code. At least looking at the x86 variants, I wonder why we don't simply use
set_direct_map_valid_noflush().If so, can you add a patch to do the conversion, pleeeeassse ? :)
Absolutely!
Quoted 54 lines
Quoted 40 lines
Reviewed-by Ackerley Tng <[email protected]>Signed-off-by Nikita Kalyazin <[email protected]>--- arch/arm64/include/asm/set_memory.h | 2 ++ arch/arm64/mm/pageattr.c | 12 ++++++++++++ arch/loongarch/include/asm/set_memory.h | 2 ++ arch/loongarch/mm/pageattr.c | 12 ++++++++++++ arch/riscv/include/asm/set_memory.h | 2 ++ arch/riscv/mm/pageattr.c | 12 ++++++++++++ arch/s390/include/asm/set_memory.h | 2 ++ arch/s390/mm/pageattr.c | 12 ++++++++++++ arch/x86/include/asm/set_memory.h | 2 ++ arch/x86/mm/pat/set_memory.c | 20 ++++++++++++++++++++ include/linux/set_memory.h | 10 ++++++++++ 11 files changed, 88 insertions(+)arch/arm64/include/asm/set_memory.h +2
-0@@ -15,6 +15,8 @@ int set_direct_map_invalid_noflush(const void *addr);int set_direct_map_default_noflush (const void *addr);int set_direct_map_valid_noflush (const void *addr,unsigned long numpages,bool valid); +int folio_zap_direct_map (struct folio *folio); +int folio_restore_direct_map (struct folio *folio);bool kernel_page_present (struct page *page);int set_memory_encrypted (unsigned long addr,int numpages);arch/arm64/mm/pageattr.c +1
-0@@ -356,6 +356,18 @@ int set_direct_map_valid_noflush(const void *addr, unsigned long numpages,return set_memory_valid ((unsigned long )addr, numpages, valid); } +int folio_zap_direct_map (struct folio *folio)arch/arm64/mm/pageattr.c int set_direct_map_valid_noflush(const void *addr, unsigned long numpages, · line 369
Quoted 10 lines
arch/arm64/mm/pageattr.c +10
-0+{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), false); +} + +int folio_restore_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), true); +}Is there a good reason why we cannot have two generic inline functions that simply call
set_direct_map_valid_noflush()?
Quoted 1 line
Is it because of some flushing behavior? (which we could figure out)
Yes, on x86 we need an explicit flush. Other architectures deal with it internally. Do you propose a bespoke implementation for x86 and a "generic" one for others?
Quoted 9 lines
In particular, a single set of functions could have a beautiful centralized kerneldoc, right?! :)
--
Cheers,David
Re: [PATCH v10 04/15] mm/gup: drop local variable in gup_fast_folio_allowed
In reply to David Hildenbrand (Arm)Quoted 51 lines · David Hildenbrand (Arm)
Quoted 37 lines · Nikita
From: Nikita Kalyazin <[email protected]>
Move the check for pinning closer to where the result is used. No functional changes.
Signed-off-by Nikita Kalyazin <[email protected]>--- mm/gup.c | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-)mm/gup.c +0
-9@@ -2737,18 +2737,9 @@ EXPORT_SYMBOL(get_user_pages_unlocked);*/ static bool gup_fast_folio_allowed (struct folio *folio,unsigned int flags) { -bool reject_file_backed = false;struct address_space *mapping;unsigned long mapping_flags; -/* -* If we aren't pinning then no problematic write can occur. A long term -* pin is the most egregious case so this is the one we disallow. -*/ -if ((flags & (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE )) == - (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE )) - reject_file_backed = true; -/* We hold a folio reference, so we can safely access folio fields. */ if (WARN_ON_ONCE (folio_test_slab (folio)))return false;@@ -2793,8 +2784,14 @@ static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags)*/ if (secretmem_mapping (mapping))return false;mm/gup.c static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags) · line 2794
Quoted 10 lines
mm/gup.c +8
-2-/* The only remaining allowed file system is shmem. */ -return !reject_file_backed ||shmem_mapping (mapping); + +/* +* If we aren't pinning then no problematic write can occur. A long term +* pin is the most egregious case so this is the one we disallow. +* Also check the only remaining allowed file system - shmem. +*/ +return (flags & (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE )) != + (FOLL_PIN |FOLL_LONGTERM |FOLL_WRITE ) ||shmem_mapping (mapping);Best to keep this split and a bit more readable.
Quoted 10 lines
/*
* If we aren't pinning then no problematic write can occur. A writable
* long term pin is the most egregious case, so this is the one we
* allow only for ...
*/
if ((flags & (FOLL_PIN|FOLL_LONGTERM|FOLL_WRITE)) !=
(FOLL_PIN|FOLL_LONGTERM|FOLL_WRITE)
return true;
/* ... hugetlb (which we allowed above already) and shared memory. */ returnshmem_mapping(mapping);
Makes sense, thank you!
Quoted 10 lines
mm/gup.c static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags) · line 2797
Quoted 4 lines
mm/gup.c +0
-0} static void __maybe_unused gup_fast_undo_dev_pagemap(int *nr, int nr_start,--
Cheers,David
Re: [PATCH v10 09/15] KVM: guest_memfd: Add flag to remove from direct map
In reply to David Hildenbrand (Arm)Quoted 87 lines · David Hildenbrand (Arm)
Quoted 86 lines · Nikita
From: Patrick Roy <[email protected]>
Add
GUEST_MEMFD_FLAG_NO_DIRECT_MAPflag forKVM_CREATE_GUEST_MEMFD()ioctl. When set,guest_memfdfolios will be removed from the direct map after preparation, with direct map entries only restored when the folios are freed.To ensure these folios do not end up in places where the kernel cannot deal with them, set
AS_NO_DIRECT_MAPon the guest_memfd's structaddress_spaceifGUEST_MEMFD_FLAG_NO_DIRECT_MAPis requested.Note that this flag causes removal of direct map entries for all
guest_memfdfolios independent of whether they are "shared" or "private" (although currentguest_memfdonly supports either all folios in the "shared" state, or all folios in the "private" state ifGUEST_MEMFD_FLAG_MMAPis not set). The usecase for removing direct map entries of also the shared parts ofguest_memfdare a special type of non-CoCo VM where, host userspace is trusted to have access to all of guest memory, but where Spectre-style transient execution attacks through the host kernel's direct map should still be mitigated. In this setup, KVM retains access to guest memory via userspace mappings ofguest_memfd, which are reflected back into KVM's memslots viauserspace_addr. This is needed for things like MMIO emulation onx86_64to work.Direct map entries are zapped right before guest or userspace mappings of gmem folios are set up, e.g. in
kvm_gmem_fault_user_mapping()orkvm_gmem_get_pfn()[called from the KVM MMU code]. The only place where a gmem folio can be allocated without being mapped anywhere iskvm_gmem_populate(), where handling potential failures of direct map removal is not possible (by the time direct map removal is attempted, the folio is already marked as prepared, meaning attempting to re-trykvm_gmem_populate()would just result in-EEXISTwithout fixing up the direct map state). These folios are then removed form the direct map uponkvm_gmem_get_pfn(), e.g. when they are mapped into the guest later.Signed-off-by Patrick Roy <[email protected]>Signed-off-by Nikita Kalyazin <[email protected]>--- Documentation/virt/kvm/api.rst | 21 +++++---- arch/x86/include/asm/kvm_host.h | 5 +-- arch/x86/kvm/x86.c | 5 +++ include/linux/kvm_host.h | 12 +++++ include/uapi/linux/kvm.h | 1 + virt/kvm/guest_memfd.c | 80 ++++++++++++++++++++++++++++++--- 6 files changed, 106 insertions(+), 18 deletions(-)Documentation/virt/kvm/api.rst +12
-9@@ -6440,15 +6440,18 @@ a single guest_memfd file, but the bound ranges must not overlap). The capability KVM_CAP_GUEST_MEMFD_FLAGS enumerates the `flags` that can be specified via KVM_CREATE_GUEST_MEMFD. Currently defined flags: - ============================ ================================================ - GUEST_MEMFD_FLAG_MMAP Enable using mmap() on the guest_memfd file - descriptor. - GUEST_MEMFD_FLAG_INIT_SHARED Make all memory in the file shared during - KVM_CREATE_GUEST_MEMFD (memory files created - without INIT_SHARED will be marked private). - Shared memory can be faulted into host userspace - page tables. Private memory cannot. - ============================ ================================================ + ============================== ================================================ + GUEST_MEMFD_FLAG_MMAP Enable using mmap() on the guest_memfd file + descriptor. + GUEST_MEMFD_FLAG_INIT_SHARED Make all memory in the file shared during + KVM_CREATE_GUEST_MEMFD (memory files created + without INIT_SHARED will be marked private). + Shared memory can be faulted into host userspace + page tables. Private memory cannot. + GUEST_MEMFD_FLAG_NO_DIRECT_MAP The guest_memfd instance will unmap the memory + backing it from the kernel's address space + before passing it off to userspace or the guest. + ============================== ================================================ When the KVM MMU performs a PFN lookup to service a guest fault and the backing guest_memfd has the GUEST_MEMFD_FLAG_MMAP set, then the fault will always bearch/x86/include/asm/kvm_host.h +0
-0@@ -2483,10 +2483,7 @@ static inline bool kvm_arch_has_irq_bypass(void) }
Quoted 10 lines
arch/x86/include/asm/kvm_host.h static inline bool kvm_arch_has_irq_bypass(void) · line 2486
Quoted 6 lines
arch/x86/include/asm/kvm_host.h +1
-4#ifdef CONFIG_KVM_GUEST_MEMFD -static inline bool kvm_arch_gmem_supports_no_direct_map (void ) -{ -return can_set_direct_map (); -} +bool kvm_arch_gmem_supports_no_direct_map (struct kvm *kvm);It's odd given that you introduced that code two patches previously. Can these changes directly be squashed into the earlier patch? [...]
You're right, I'll pull it in the "KVM: x86: define kvm_arch_gmem_supports_no_direct_map()".
Quoted 22 lines
Quoted 9 lines
arch/x86/include/asm/kvm_host.h +7
-0+#define KVM_GMEM_FOLIO_NO_DIRECT_MAP BIT(0) + +static bool kvm_gmem_folio_no_direct_map (struct folio *folio) +{ +return ((u64 )folio->private) &KVM_GMEM_FOLIO_NO_DIRECT_MAP ; +} +arch/x86/include/asm/kvm_host.h static inline bool kvm_arch_has_irq_bypass(void)
Quoted 10 lines
arch/x86/include/asm/kvm_host.h +10
-0+static int kvm_gmem_folio_zap_direct_map (struct folio *folio) +{ +u64 gmem_flags =GMEM_I (folio_inode (folio))->flags; +int r =0 ; + +if (kvm_gmem_folio_no_direct_map (folio) || !(gmem_flags &GUEST_MEMFD_FLAG_NO_DIRECT_MAP )) + goto out; + + folio->private = (void *)((u64 )folio->private |KVM_GMEM_FOLIO_NO_DIRECT_MAP ); + r =folio_zap_direct_map (folio);And if it fails, you'd leave
KVM_GMEM_FOLIO_NO_DIRECT_MAPset.
Quoted 1 line
What about modifying ->private only if it really worked?
True. I'll do
r = folio_zap_direct_map(folio); if (!r) folio->private = (void *)((u64)folio->private |
KVM_GMEM_FOLIO_NO_DIRECT_MAP);
Quoted 13 lines
Quoted 13 lines
arch/x86/include/asm/kvm_host.h +12
-0+ +out: +return r; +} + +static void kvm_gmem_folio_restore_direct_map (struct folio *folio) +{ +/* +* Direct map restoration cannot fail, as the only error condition +* for direct map manipulation is failure to allocate page tables +* when splitting huge pages, but this split would have already +* happened in folio_zap_direct_map() in kvm_gmem_folio_zap_direct_map().
Quoted 8 lines
arch/x86/include/asm/kvm_host.h
Quoted 5 lines
arch/x86/include/asm/kvm_host.h +5
-0+* Note that the splitting occurs always because guest_memfd +* currently supports only base pages. +* Thus folio_restore_direct_map() here only updates prot bits. +*/ +WARN_ON_ONCE (folio_restore_direct_map (folio));Which raised the question: why should this function then even return an error?
Dave pointed earlier that the failures were possible [1]. Do you think we can document it better?
[1] https://lore.kernel.org/kvm/[email protected]/
Quoted 65 lines
Quoted 65 lines
arch/x86/include/asm/kvm_host.h +23
-0+ folio->private = (void *)((u64 )folio->private & ~KVM_GMEM_FOLIO_NO_DIRECT_MAP ); +} +static inline void kvm_gmem_mark_prepared (struct folio *folio) {folio_mark_uptodate (folio);@@ -393,11 +433,17 @@ static bool kvm_gmem_supports_mmap(struct inode *inode)return GMEM_I (inode)->flags &GUEST_MEMFD_FLAG_MMAP ; } +static bool kvm_gmem_no_direct_map (struct inode *inode) +{ +return GMEM_I (inode)->flags &GUEST_MEMFD_FLAG_NO_DIRECT_MAP ; +} +static vm_fault_t kvm_gmem_fault_user_mapping (struct vm_fault *vmf) {struct inode *inode =file_inode (vmf->vma->vm_file);struct folio *folio;vm_fault_t ret =VM_FAULT_LOCKED ; +int err;if (((loff_t )vmf->pgoff <<PAGE_SHIFT ) >=i_size_read (inode))return VM_FAULT_SIGBUS ;@@ -423,6 +469,14 @@ static vm_fault_t kvm_gmem_fault_user_mapping(struct vm_fault *vmf)kvm_gmem_mark_prepared (folio); } +if (kvm_gmem_no_direct_map (folio_inode (folio))) { + err =kvm_gmem_folio_zap_direct_map (folio); +if (err) { + ret =vmf_error (err); + goto out_folio; + } + } + vmf->page =folio_file_page (folio, vmf->pgoff); out_folio:@@ -533,6 +587,9 @@ static void kvm_gmem_free_folio(struct folio *folio)kvm_pfn_t pfn =page_to_pfn (page);int order =folio_order (folio); +if (kvm_gmem_folio_no_direct_map (folio)) +kvm_gmem_folio_restore_direct_map (folio); +kvm_arch_gmem_invalidate (pfn, pfn + (1ul << order)); }@@ -596,6 +653,9 @@ static int __kvm_gmem_create(struct kvm *kvm, loff_t size, u64 flags)/* Unmovable mappings are supposed to be marked unevictable as well. */ WARN_ON_ONCE (!mapping_unevictable (inode->i_mapping)); +if (flags &GUEST_MEMFD_FLAG_NO_DIRECT_MAP ) +mapping_set_no_direct_map (inode->i_mapping); +GMEM_I (inode)->flags = flags; file =alloc_file_pseudo (inode, kvm_gmem_mnt, name,O_RDWR , &kvm_gmem_fops);@@ -804,15 +864,25 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,if (IS_ERR (folio))return PTR_ERR (folio);
Quoted 16 lines
arch/x86/include/asm/kvm_host.h int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 877
Quoted 12 lines
arch/x86/include/asm/kvm_host.h +10
-1-if (!is_prepared) +if (!is_prepared) { r =kvm_gmem_prepare_folio (kvm, slot, gfn, folio); +if (r) + goto out_unlock; + } + +if (kvm_gmem_no_direct_map (folio_inode (folio))) { + r =kvm_gmem_folio_zap_direct_map (folio); +if (r) + goto out_unlock; + }It's a bit nasty that we have two different places where we have to call this. Smells error prone.
We will actually have 2 more: for the write() syscall and UFFDIO_COPY, and 0 once we have [2]
[2] https://lore.kernel.org/linux-mm/[email protected]/
Quoted 2 lines
I was wondering why
kvm_gmem_get_folio()cannot handle that?
Most of the call sites follow the pattern alloc -> write -> zap so they'll need direct map for some time after the allocation.
Quoted 3 lines
Then also
fallocate()would directly be handled directly, instead of later at fault time etc.
Good question about fallocate(). It's not apparent to me that it needs to remove pages from direct map because we may not be able to initisalise them later on if we do.
Quoted 2 lines
Is it because
__kvm_gmem_populate()etc need to write to this page?
I think it also applies to write(), UFFDIO_COPY and kvm_gmem_fault_user_mapping().
Quoted 6 lines
--
Cheers,David
David Hildenbrand (Arm)
maintainerRe: [PATCH v10 02/15] set_memory: add folio_{zap, restore}_direct_map helpers
In reply to Nikita KalyazinQuoted 102 lines · Nikita Kalyazin
Quoted 10 lines · David Hildenbrand (Arm)
Quoted 6 lines · Nikita
From: Nikita Kalyazin <[email protected]>
These allow
guest_memfdto remove its memory from the direct map. Only implement them for architectures that have direct map. Infolio_zap_direct_map(), flush TLB on architectures whereset_direct_map_valid_noflush()does not flush it internally."Let's provide folio_{zap,restore}_direct_map helpers as preparation for supporting removal of the direct map for
guest_memfdfolios. ...Will update, thanks.
Quoted 18 lines
Quoted 9 lines
The new helpers need to be accessible to KVM on architectures that support
guest_memfd(x86 and arm64). Since arm64 does not support building KVM as a module, only export them on x86.Direct map removal gives
guest_memfdthe same protection thatmemfd_secretdoes, such as hardening against Spectre-like attacks through in-kernel gadgets.Would it be possible to convert
mm/secretmem.cas well?There, we use
set_direct_map_invalid_noflush(folio_page(folio, 0));and
Quoted 8 lines
set_direct_map_default_noflush(folio_page(folio, 0));Which is a bit different to below code. At least looking at the x86 variants, I wonder why we don't simply use
set_direct_map_valid_noflush().If so, can you add a patch to do the conversion, pleeeeassse ? :)
Absolutely!
Quoted 57 lines
Quoted 43 lines
Reviewed-by Ackerley Tng <[email protected]>Signed-off-by Nikita Kalyazin <[email protected]>---
arch/arm64/include/asm/set_memory.h | 2 ++ arch/arm64/mm/pageattr.c | 12 ++++++++++++arch/loongarch/include/asm/set_memory.h| 2 ++ arch/loongarch/mm/pageattr.c | 12 ++++++++++++ arch/riscv/include/asm/set_memory.h | 2 ++ arch/riscv/mm/pageattr.c | 12 ++++++++++++ arch/s390/include/asm/set_memory.h | 2 ++ arch/s390/mm/pageattr.c | 12 ++++++++++++ arch/x86/include/asm/set_memory.h | 2 ++ arch/x86/mm/pat/set_memory.c | 20 ++++++++++++++++++++ include/linux/set_memory.h | 10 ++++++++++11 files changed, 88 insertions(+)arch/arm64/ renamed from arch/arm64/include/asm/set_memory.h +0
-0
include/asm/set_memory.h
indexc71a2a6812c4..49fd54f3c265100644arch/arm64/include/asm/set_memory.h +0
-0@@ -15,6 +15,8 @@ int set_direct_map_invalid_noflush(const void *addr); int set_direct_map_default_noflush(const void *addr);int set_direct_map_valid_noflush(const void *addr, unsigned long numpages,
bool valid);arch/arm64/include/asm/set_memory.h +2
-0+int folio_zap_direct_map (struct folio *folio); +int folio_restore_direct_map (struct folio *folio);bool
kernel_page_present(struct page *page);int
set_memory_encrypted(unsigned long addr, int numpages);arch/arm64/mm/pageattr.c +1
-0@@ -356,6 +356,18 @@ int set_direct_map_valid_noflush(const void *addr, unsigned long numpages, return set_memory_valid((unsigned long)addr, numpages, valid); } +int folio_zap_direct_map (struct folio *folio)arch/arm64/mm/pageattr.c int set_direct_map_valid_noflush(const void · line 370
Quoted 10 lines
arch/arm64/mm/pageattr.c +10
-0+{ + return set_direct_map_valid_noflush(folio_address(folio), + folio_nr_pages(folio), false); +} + +int folio_restore_direct_map (struct folio *folio) +{ + return set_direct_map_valid_noflush(folio_address(folio), + folio_nr_pages(folio), true); +}Is there a good reason why we cannot have two generic inline functions that simply call
set_direct_map_valid_noflush()?
Quoted 4 lines
Quoted 1 line
Is it because of some flushing behavior? (which we could figure out)
Yes, on x86 we need an explicit flush. Other architectures deal with it internally.
So, we call a _noflush function and it performs a ... flush. What.
Take a look at secretmem_fault(), where we do an unconditional flush_tlb_kernel_range().
Do we end up double-flushing in that case?
Quoted 2 lines
Do you propose a bespoke implementation for x86 and a "generic" one for others?
We have to find a way to have a single set of functions for all archs that support directmap removal.
One option might be to have some indication from the architecture that no flush_tlb_kernel_range() is required.
Could be a config option or some simple helper function.
Signature · 3 lines
Cheers, David
David Hildenbrand (Arm)
maintainerRe: [PATCH v10 09/15] KVM: guest_memfd: Add flag to remove from direct map
In reply to Nikita Kalyazin[...]
Quoted 12 lines
Quoted 12 lines
Quoted 11 lines
+ /*
+ * Direct map restoration cannot fail, as the only error condition + * for direct map manipulation is failure to allocate page tables + * when splitting huge pages, but this split would have already + * happened infolio_zap_direct_map()inkvm_gmem_folio_zap_direct_map().
+ * Note that the splitting occurs always becauseguest_memfd+ * currently supports only base pages.
+ * Thusfolio_restore_direct_map()here only updates prot bits. + */
+ WARN_ON_ONCE(folio_restore_direct_map(folio));
Quoted 5 lines
Quoted 2 lines
Which raised the question: why should this function then even return an error?
Dave pointed earlier that the failures were possible [1]. Do you think we can document it better?
I'm fine with checking that somewhere (to catch any future problems).
Why not do the WARN_ON_ONCE() in folio_restore_direct_map()?
Then, carefully document (in the new kerneldoc for folio_restore_direct_map() etc) that folio_restore_direct_map() is only allowed after a prior successful folio_zap_direct_map(), and add a helpful comment above the WARN_ON_ONCE() in folio_restore_direct_map() that we don't expect errors etc.
[...]
Quoted 20 lines
Quoted 14 lines
Quoted 4 lines
- if (!is_prepared)
+ if (!is_prepared) {
r =kvm_gmem_prepare_folio(kvm, slot, gfn, folio); + if (r)Quoted 8 lines
+ goto
out_unlock;
+ }
+
+ if (kvm_gmem_no_direct_map(folio_inode(folio))) { + r =kvm_gmem_folio_zap_direct_map(folio); + if (r)
+ gotoout_unlock;
+ }Quoted 2 lines
It's a bit nasty that we have two different places where we have to call this. Smells error prone.
We will actually have 2 more: for the
write()syscall andUFFDIO_COPY, and 0 once we have [2]
Quoted 9 lines
[2] https://lore.kernel.org/linux-mm/20260225-page_alloc-unmapped-v1-0-
[email protected]/Quoted 2 lines
I was wondering why
kvm_gmem_get_folio()cannot handle that?Most of the call sites follow the pattern alloc -> write -> zap so they'll need direct map for some time after the allocation.
Okay. Nasty. :)
Signature · 3 lines
Cheers, David
Re: [PATCH v10 02/15] set_memory: add folio_{zap, restore}_direct_map helpers
In reply to David Hildenbrand (Arm)Quoted 103 lines · David Hildenbrand (Arm)
Quoted 102 lines · Nikita Kalyazin
Quoted 10 lines · David Hildenbrand (Arm)
Quoted 6 lines · Nikita
From: Nikita Kalyazin <[email protected]>
These allow
guest_memfdto remove its memory from the direct map. Only implement them for architectures that have direct map. Infolio_zap_direct_map(), flush TLB on architectures whereset_direct_map_valid_noflush()does not flush it internally."Let's provide folio_{zap,restore}_direct_map helpers as preparation for supporting removal of the direct map for
guest_memfdfolios. ...Will update, thanks.
Quoted 18 lines
Quoted 9 lines
The new helpers need to be accessible to KVM on architectures that support
guest_memfd(x86 and arm64). Since arm64 does not support building KVM as a module, only export them on x86.Direct map removal gives
guest_memfdthe same protection thatmemfd_secretdoes, such as hardening against Spectre-like attacks through in-kernel gadgets.Would it be possible to convert
mm/secretmem.cas well?There, we use
set_direct_map_invalid_noflush(folio_page(folio, 0));and
Quoted 8 lines
set_direct_map_default_noflush(folio_page(folio, 0));Which is a bit different to below code. At least looking at the x86 variants, I wonder why we don't simply use
set_direct_map_valid_noflush().If so, can you add a patch to do the conversion, pleeeeassse ? :)
Absolutely!
Quoted 57 lines
Quoted 43 lines
Reviewed-by Ackerley Tng <[email protected]>Signed-off-by Nikita Kalyazin <[email protected]>--- arch/arm64/include/asm/set_memory.h | 2 ++ arch/arm64/mm/pageattr.c | 12 ++++++++++++ arch/loongarch/include/asm/set_memory.h | 2 ++ arch/loongarch/mm/pageattr.c | 12 ++++++++++++ arch/riscv/include/asm/set_memory.h | 2 ++ arch/riscv/mm/pageattr.c | 12 ++++++++++++ arch/s390/include/asm/set_memory.h | 2 ++ arch/s390/mm/pageattr.c | 12 ++++++++++++ arch/x86/include/asm/set_memory.h | 2 ++ arch/x86/mm/pat/set_memory.c | 20 ++++++++++++++++++++ include/linux/set_memory.h | 10 ++++++++++ 11 files changed, 88 insertions(+)arch/arm64/ renamed from arch/arm64/include/asm/set_memory.h +0
-0
include/asm/set_memory.h
indexc71a2a6812c4..49fd54f3c265100644arch/arm64/include/asm/set_memory.h +2
-0@@ -15,6 +15,8 @@ int set_direct_map_invalid_noflush(const void *addr);int set_direct_map_default_noflush (const void *addr);int set_direct_map_valid_noflush (const void *addr,unsigned long numpages,bool valid); +int folio_zap_direct_map (struct folio *folio); +int folio_restore_direct_map (struct folio *folio);bool kernel_page_present (struct page *page);int set_memory_encrypted(unsigned long addr, int numpages);arch/arm64/mm/pageattr.c +1
-0@@ -356,6 +356,18 @@ int set_direct_map_valid_noflush(const void *addr, unsigned long numpages, return set_memory_valid((unsigned long)addr, numpages, valid); } +int folio_zap_direct_map (struct folio *folio)arch/arm64/mm/pageattr.c int set_direct_map_valid_noflush(const void · line 370
Quoted 10 lines
arch/arm64/mm/pageattr.c +10
-0+{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), false); +} + +int folio_restore_direct_map (struct folio *folio) +{ +return set_direct_map_valid_noflush (folio_address (folio), +folio_nr_pages (folio), true); +}Is there a good reason why we cannot have two generic inline functions that simply call
set_direct_map_valid_noflush()?
Quoted 6 lines
Quoted 4 lines
Quoted 1 line
Is it because of some flushing behavior? (which we could figure out)
Yes, on x86 we need an explicit flush. Other architectures deal with it internally.
So, we call a
_noflushfunction and it performs a ... flush. What.
Yeah, that's unfortunately the status quo as pointed by Aneesh [1]
[1] https://lore.kernel.org/kvm/[email protected]/
Quoted 5 lines
Take a look at
secretmem_fault(), where we do an unconditionalflush_tlb_kernel_range().Do we end up double-flushing in that case?
Yes, looks like that. I'll remove the explicit flush and rely on folio_zap_direct_map().
Quoted 6 lines
Quoted 3 lines
Do you propose a bespoke implementation for x86 and a "generic" one for others?
We have to find a way to have a single set of functions for all archs that support directmap removal.
I believe Dave meant to address that with folio_{zap,restore}_direct_map() [2].
[2] https://lore.kernel.org/kvm/[email protected]/
Quoted 5 lines
One option might be to have some indication from the architecture that no
flush_tlb_kernel_range()is required.Could be a config option or some simple helper function.
I'd be inclined to know what arch maintainers think because I don't have a strong opinion on that.
Quoted 5 lines
--
Cheers,David
Re: [PATCH v10 09/15] KVM: guest_memfd: Add flag to remove from direct map
In reply to David Hildenbrand (Arm)Quoted 22 lines · David Hildenbrand (Arm)
[...]
Quoted 12 lines
Quoted 12 lines
Quoted 11 lines
virt/kvm/guest_memfd.c +5
-0+/* +* Direct map restoration cannot fail, as the only error condition +* for direct map manipulation is failure to allocate page tables +* when splitting huge pages, but this split would have already +* happened in folio_zap_direct_map() in
kvm_gmem_folio_zap_direct_map().virt/kvm/guest_memfd.c +5
-0+* Note that the splitting occurs always because guest_memfd +* currently supports only base pages. +* Thus folio_restore_direct_map() here only updates prot bits. +*/ +WARN_ON_ONCE (folio_restore_direct_map (folio));Quoted 5 lines
Quoted 2 lines
Which raised the question: why should this function then even return an error?
Dave pointed earlier that the failures were possible [1]. Do you think we can document it better?
I'm fine with checking that somewhere (to catch any future problems).
Quoted 7 lines
Why not do the
WARN_ON_ONCE()infolio_restore_direct_map()?Then, carefully document (in the new kerneldoc for
folio_restore_direct_map()etc) thatfolio_restore_direct_map()is only allowed after a prior successfulfolio_zap_direct_map(), and add a helpful comment above theWARN_ON_ONCE()infolio_restore_direct_map()that we don't expect errors etc.
My only concern about that is the assumptions we make in KVM may not apply to the general case and the WARN_ON_ONCE may become too restrictive compared to proper error handling in some (rare) cases. For example, is it possible for the folio to migrate in between?
Quoted 39 lines
[...]
Quoted 20 lines
Quoted 14 lines
virt/kvm/guest_memfd.c int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 877
Quoted 12 lines
virt/kvm/guest_memfd.c +10
-1-if (!is_prepared) +if (!is_prepared) { r =kvm_gmem_prepare_folio (kvm, slot, gfn, folio); +if (r) + goto out_unlock; + } + +if (kvm_gmem_no_direct_map (folio_inode (folio))) { + r =kvm_gmem_folio_zap_direct_map (folio); +if (r) + goto out_unlock; + }Quoted 2 lines
It's a bit nasty that we have two different places where we have to call this. Smells error prone.
We will actually have 2 more: for the
write()syscall andUFFDIO_COPY, and 0 once we have [2]Quoted 9 lines
[2] https://lore.kernel.org/linux-mm/20260225-page_alloc-unmapped-v1-0-
[email protected]/Quoted 2 lines
I was wondering why
kvm_gmem_get_folio()cannot handle that?Most of the call sites follow the pattern alloc -> write -> zap so they'll need direct map for some time after the allocation.
Okay. Nasty. :)
--
Cheers,David
David Hildenbrand (Arm)
maintainerRe: [PATCH v10 09/15] KVM: guest_memfd: Add flag to remove from direct map
Quoted 19 lines · Nikita Kalyazin
Quoted 8 lines · David Hildenbrand (Arm)
[...]
Quoted 3 lines
Dave pointed earlier that the failures were possible [1]. Do you think we can document it better?
I'm fine with checking that somewhere (to catch any future problems).
Quoted 7 lines
Why not do the
WARN_ON_ONCE()infolio_restore_direct_map()?Then, carefully document (in the new kerneldoc for
folio_restore_direct_map()etc) thatfolio_restore_direct_map()is only allowed after a prior successfulfolio_zap_direct_map(), and add a helpful comment above theWARN_ON_ONCE()infolio_restore_direct_map()that we don't expect errors etc.
Quoted 4 lines
My only concern about that is the assumptions we make in KVM may not apply to the general case and the
WARN_ON_ONCEmay become too restrictive compared to proper error handling in some (rare) cases. For example, is it possible for the folio to migrate in between?
Not without migration support. But then, migration would have to make sure that the destination folio has the direct map removed. So I wouldn't worry about that.
Once you return an error from folio_restore_direct_map(), you better document when/why it happens and how the caller should handle it.
There is nothing existing callers could really do, so it's an implementation detail of the folio_zap_direct_map()/folio_restore_direct_map() functions to make sure it keeps working.
If it ever fails, we'll have to figure out how to keep the interface working.
You can document any restrictions regarding when folio_zap_direct_map()/folio_restore_direct_map() is allowed to be used in the kerneldoc.
Signature · 3 lines
Cheers, David
David Hildenbrand (Arm)
maintainerRe: [PATCH v10 02/15] set_memory: add folio_{zap, restore}_direct_map helpers
In reply to Nikita KalyazinQuoted 45 lines · Nikita Kalyazin
Quoted 7 lines · David Hildenbrand (Arm)
Quoted 6 lines · Nikita Kalyazin
Will update, thanks.
Quoted 7 lines
Quoted 5 lines
Absolutely!
Yes, on x86 we need an explicit flush. Other architectures deal with it internally.
So, we call a
_noflushfunction and it performs a ... flush. What.Yeah, that's unfortunately the status quo as pointed by Aneesh [1]
[1] https://lore.kernel.org/kvm/[email protected]/
Quoted 5 lines
Take a look at
secretmem_fault(), where we do an unconditionalflush_tlb_kernel_range().Do we end up double-flushing in that case?
Yes, looks like that. I'll remove the explicit flush and rely on
folio_zap_direct_map().Quoted 6 lines
Quoted 3 lines
Do you propose a bespoke implementation for x86 and a "generic" one for others?
We have to find a way to have a single set of functions for all archs that support directmap removal.
I believe Dave meant to address that with folio_{zap,restore}
_direct_map()[2].[2] https://lore.kernel.org/kvm/9409531b-589b-4a54-
[email protected]/Quoted 1 line
Quoted 7 lines
Quoted 4 lines
One option might be to have some indication from the architecture that no
flush_tlb_kernel_range()is required.Could be a config option or some simple helper function.
I'd be inclined to know what arch maintainers think because I don't have a strong opinion on that.
You could also just perform a double flush, and let people that implemented a _noflush() to perform a flush optimize that later.
I mean, that's what secretmem did :)
Signature · 3 lines
Cheers, David
Re: [PATCH v10 02/15] set_memory: add folio_{zap, restore}_direct_map helpers
Quoted 49 lines · David Hildenbrand (Arm)
Quoted 48 lines · Nikita Kalyazin
Quoted 7 lines · David Hildenbrand (Arm)
Quoted 6 lines · Nikita Kalyazin
Will update, thanks.
Quoted 7 lines
Quoted 5 lines
Absolutely!
Yes, on x86 we need an explicit flush. Other architectures deal with it internally.
So, we call a
_noflushfunction and it performs a ... flush. What.Yeah, that's unfortunately the status quo as pointed by Aneesh [1]
[1] https://lore.kernel.org/kvm/[email protected]/
Quoted 5 lines
Take a look at
secretmem_fault(), where we do an unconditionalflush_tlb_kernel_range().Do we end up double-flushing in that case?
Yes, looks like that. I'll remove the explicit flush and rely on
folio_zap_direct_map().Quoted 6 lines
Quoted 3 lines
Do you propose a bespoke implementation for x86 and a "generic" one for others?
We have to find a way to have a single set of functions for all archs that support directmap removal.
I believe Dave meant to address that with folio_{zap,restore}
_direct_map()[2].[2] https://lore.kernel.org/kvm/9409531b-589b-4a54-
[email protected]/Quoted 4 lines
One option might be to have some indication from the architecture that no
flush_tlb_kernel_range()is required.
Quoted 7 lines
Quoted 4 lines
Quoted 1 line
Could be a config option or some simple helper function.
I'd be inclined to know what arch maintainers think because I don't have a strong opinion on that.
You could also just perform a double flush, and let people that implemented a
_noflush()to perform a flush optimize that later.
Do you propose to just universalise the one from x86?
int folio_zap_direct_map(struct folio *folio)
{
const void *addr = folio_address(folio);
int ret;
ret = set_direct_map_valid_noflush(addr, folio_nr_pages(folio), false);
flush_tlb_kernel_range((unsigned long)addr,
(unsigned long)addr + folio_size(folio));
return ret;
}I'm fine with that too.
Quoted 2 lines
I mean, that's what secretmem did :)
With the solution above, secretmem stays where it was: no optimisation so far :)
Quoted 5 lines
--
Cheers,David
Re: [PATCH v10 09/15] KVM: guest_memfd: Add flag to remove from direct map
In reply to David Hildenbrand (Arm)Quoted 37 lines · David Hildenbrand (Arm)
Quoted 19 lines · Nikita Kalyazin
Quoted 8 lines · David Hildenbrand (Arm)
[...]
Quoted 3 lines
Dave pointed earlier that the failures were possible [1]. Do you think we can document it better?
I'm fine with checking that somewhere (to catch any future problems).
Quoted 7 lines
Why not do the
WARN_ON_ONCE()infolio_restore_direct_map()?Then, carefully document (in the new kerneldoc for
folio_restore_direct_map()etc) thatfolio_restore_direct_map()is only allowed after a prior successfulfolio_zap_direct_map(), and add a helpful comment above theWARN_ON_ONCE()infolio_restore_direct_map()that we don't expect errors etc.Quoted 4 lines
My only concern about that is the assumptions we make in KVM may not apply to the general case and the
WARN_ON_ONCEmay become too restrictive compared to proper error handling in some (rare) cases. For example, is it possible for the folio to migrate in between?Not without migration support. But then, migration would have to make sure that the destination folio has the direct map removed. So I wouldn't worry about that.
Once you return an error from
folio_restore_direct_map(), you better document when/why it happens and how the caller should handle it.There is nothing existing callers could really do, so it's an implementation detail of the folio_zap_direct_map()/folio_restore_direct_map() functions to make sure it keeps working.
Quoted 6 lines
If it ever fails, we'll have to figure out how to keep the interface working.
You can document any restrictions regarding when folio_zap_direct_map()/folio_restore_direct_map() is allowed to be used in the kerneldoc.
Ok, makes sense to me.
Quoted 5 lines
--
Cheers,David
David Hildenbrand (Arm)
maintainerRe: [PATCH v10 02/15] set_memory: add folio_{zap, restore}_direct_map helpers
In reply to Nikita KalyazinQuoted 36 lines · Nikita Kalyazin
Quoted 20 lines · David Hildenbrand (Arm)
Quoted 19 lines · Nikita Kalyazin
Yeah, that's unfortunately the status quo as pointed by Aneesh [1]
[1] https://lore.kernel.org/kvm/[email protected]/
Yes, looks like that. I'll remove the explicit flush and rely on
folio_zap_direct_map().I believe Dave meant to address that with folio_{zap,restore}
_direct_map()[2].[2] https://lore.kernel.org/kvm/9409531b-589b-4a54-
[email protected]/Quoted 5 lines
Quoted 2 lines
I'd be inclined to know what arch maintainers think because I don't have a strong opinion on that.
You could also just perform a double flush, and let people that implemented a
_noflush()to perform a flush optimize that later.Do you propose to just universalise the one from x86?
int
folio_zap_direct_map(struct folio *folio)
{
const void *addr =folio_address(folio);
int ret;
Quoted 6 lines
ret =
set_direct_map_valid_noflush(addr, folio_nr_pages(folio), false); flush_tlb_kernel_range((unsigned long)addr,
(unsigned long)addr +folio_size(folio));return ret;
}
Yes, exactly something along those lines!
Signature · 3 lines
Cheers, David