coco: guest: Add a shared-granule allocator for host-shared memory
Subsystems (21)
v9 cover coco: guest: Add a shared-granule allocator for host-shared memory
This series tightens the alignment requirements for buffers that are shared between confidential-computing guests and the host, and adds a common allocator for host-shared memory.
When a guest runs with private memory, buffers shared with the hypervisor are not only accessed by the guest. They are also accessed by the host kernel, and the host may manage the corresponding shared/private state at a granularity larger than the guest page size.
Architectures such as Arm can detect incorrect accesses to Realm physical address space PFNs through GPC faults. However, relying on that as the only line of defence is fragile and can still lead to kernel crashes. The risk is especially visible for shared buffers that are later mmapped into userspace, such as guest_memfd or dma-buf backed allocations. Once userspace can access the mapping, the kernel cannot guarantee that applications will only touch the intended 4K region rather than the whole host page mapped into their address space. Those userspace addresses may also be passed back into the kernel and accessed through the linear map, resulting in a GPC fault.
To avoid this, host-shared buffers must satisfy two constraints:
- the address must be aligned to the CoCo shared-granule size
- the size must be a multiple of that granule size
The series adds a common CoCo shared-memory layer for enforcing these constraints. It provides shared-granule geometry and range-validation helpers, byte-oriented private/shared transition helpers, and alloc_cc_shared_pages(). The allocator rounds a request to the architecture shared granule, allocates suitably aligned contiguous pages, transitions the complete allocation to shared state, and returns the transitioned size alongside the page.
The corresponding free helper restores the complete allocation to private state before returning it to the buddy allocator. If private state cannot be restored safely, the allocation is deliberately leaked rather than returning potentially shared memory for unrelated use.
The series also makes zeroing part of private-to-shared transitions, with each architecture clearing memory at the appropriate point. Callers must therefore initialize shared buffers after the transition; existing contents are not preserved.
The shared-granule size defaults to PAGE_SIZE and can be overridden by an architecture. The arm64 CCA changes to discover the host's IPA state change alignment are not included in this series.
GIC ITS command queues and tables and the dma-buf system_cc_shared heap use the common allocator. DMA direct, atomic DMA pools and SWIOTLB retain their allocation paths and use the common layout or transition helpers. Restricted DMA pools are checked for shared-granule alignment.
Hyper-V users of set_memory_encrypted() and set_memory_decrypted() are not changed by this series. Those paths are not currently used by the arm64 CCA code path, and therefore are not part of the arm64 CCA IPA state change alignment problem addressed here.
The series also preallocates GIC ITS VPE L1 tables so shared-memory transitions are performed in a context that may sleep.
Notes:
* I have not added explicit MAINTAINERS entries for mm/cc_shared.c and include/linux/cc_shared.h, as I am unsure whether we need a separate section for common CoCo-related files. I will add the entries based on feedback.
* Codex assisted with implementation, review and series organization.
Changes from v8:
https://lore.kernel.org/all/[email protected]
* Rebase onto the 7.4-rc1
* Move TDX and AMD (including SEV-SNP) zeroing to their finish callbacks so private-to-shared transitions clear the final shared mapping.
* Clear __GFP_MOVABLE for shared allocations, which cannot be migrated.
* Resolve NUMA_NO_NODE in the common ITS allocation helper to preserve placement for all ITS callers.
* Stop SWIOTLB allocation retries when the reduced pool would fall below the shared granule size, avoiding an allocation retry loop.
Changes from v7:
https://lore.kernel.org/all/[email protected]
* Add the following new patches:
* "irqchip/gic-v3-its: Preallocate VPE L1 tables"
* "mm: Assert CoCo shared allocations may sleep"
* "mm: Zero memory during shared memory transitions"
* Drop the arm64 RHI and shared granule size patches so that the series can be rebased on top of upstream to enable Shashiko review.
Changes from v6:
https://lore.kernel.org/all/[email protected]
* Add a common allocator and geometry/transition helpers for CoCo host-shared memory.
* Convert GIC ITS, dma-direct, atomic DMA pools, and the dma-buf system_cc_shared heap to the common allocator.
* Limit dma-buf scatterlist entries to the requested buffer size so rounded backing is not exposed to importers.
Changes from v5:
https://lore.kernel.org/all/[email protected]
* Rebased to latest kernel
* Drop patch arm64: realm: Move Realm memory encryption ops to RSI code
Changes from v4:
https://lore.kernel.org/all/[email protected]
* Rename the helpers to use CoCo terminology (mem_cc_shared_granule_size() / mem_cc_align_to_shared_granule() instead of mem_decrypt_granule_size() / mem_decrypt_align()).
* Use __DMA_ATTR_ALLOC_CC_SHARED to pass CoCo shared allocation requirements down to CMA-based allocation helpers.
* Add validation for restricted DMA pools to reject pools that are not aligned to the shared granule size.
* Add dma-buf system heap handling for cc-shared buffers.
* Split the previous combined DMA/SWIOTLB/ITS change into smaller subsystem patches covering ITS, DMA direct, SWIOTLB, restricted DMA pools, dma-buf system heap, and arm64 Realm support.
* Rework arm64 Realm support by moving Realm memory encryption ops into RSI code and exposing the CCA shared granule size through arm64_mem_crypt_ops.
Changes from v3:
https://lore.kernel.org/all/[email protected]
* Fix build error reported by kernel test robot <[email protected]>
Changes from v2:
https://lore.kernel.org/all/[email protected]
* Rebase to latest kernel
* Consider swiotlb always decrypted and don't align when allocating from swiotlb.
Changes from v1:
* Rename the helper to mem_encrypt_align
* Improve the commit message
* Handle DMA allocations from contiguous memory
* Handle DMA allocations from the pool
* swiotlb is still considered unencrypted. Support for an encrypted swiotlb pool is left as TODO and is independent of this series.
Aneesh Kumar K.V (Arm) (14):
mm: Add an allocator for CoCo shared memory
mm: Zero memory during shared memory transitions irqchip/gic-v3-its: Resolve the default NUMA node explicitly irqchip/gic-v3-its: Allocate shared tables using CoCo shared memory
allocator
dma-contiguous: Derive shared alignment from DMA attributes
dma-pool: Allocate CoCo atomic pools using CoCo shared memory
allocator
dma-direct: Align CoCo shared DMA allocations to the shared granule
size
swiotlb: Align shared IO TLB pools to the shared granule size
swiotlb: Reject misaligned restricted DMA pools for CoCo guests
dma-buf: system_heap: Limit scatterlist entries to the buffer size
dma-buf: system_heap: Allocate shared buffers using CoCo shared memory
allocator
swiotlb: Make rounded shared pool capacity allocatable
mm: Assert CoCo shared allocations may sleep irqchip/gic-v3-its: Preallocate VPE L1 tables
arch/arm/mm/dma-mapping.c | 5 +- arch/powerpc/platforms/pseries/svm.c | 2 + arch/s390/mm/init.c | 3 + arch/x86/coco/tdx/tdx.c | 3 + arch/x86/hyperv/hv_init.c | 6 +- arch/x86/hyperv/ivm.c | 4 + arch/x86/kernel/kvmclock.c | 6 +- arch/x86/mm/mem_encrypt_amd.c | 4 + drivers/dma-buf/heaps/system_heap.c | 128 +++++----- drivers/firmware/arm_rmm/rsi.c | 4 + drivers/hv/connection.c | 41 ++- drivers/hv/hv.c | 11 +- drivers/hv/hv_common.c | 2 - drivers/iommu/dma-iommu.c | 2 +- drivers/irqchip/irq-gic-v3-its.c | 152 +++++++++--- drivers/irqchip/irq-gic-v3.c | 4 +- drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c | 3 + include/linux/cc_shared.h | 39 +++ include/linux/dma-map-ops.h | 9 +- include/linux/irqchip/arm-gic-v3.h | 3 +- kernel/dma/contiguous.c | 41 ++- kernel/dma/direct.c | 73 ++++-- kernel/dma/ops_helpers.c | 2 +- kernel/dma/pool.c | 27 +- kernel/dma/swiotlb.c | 87 +++++-- kernel/kexec_file.c | 3 +- mm/Makefile | 1 + mm/cc_shared.c | 233 ++++++++++++++++++ 28 files changed, 693 insertions(+), 205 deletions(-) create mode 100644 include/linux/cc_shared.h create mode 100644 mm/cc_shared.c
base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
prerequisite-patch-id: 1d4a2fa9dc0f4b560e55f419d23835f0a9fbe485
Signature · 1 line
2.43.0
PATCH v9 1/14 mm: Add an allocator for CoCo shared memory
Confidential-computing guests may require memory shared with the host to be aligned and transitioned in units larger than PAGE_SIZE. Several DMA users need struct page-backed allocations satisfying these requirements. Provide a common allocator instead of requiring each user to open-code this sequence.
Add alloc_cc_shared_pages() and its node-aware variant. The allocator rounds the requested size to the architecture's shared granule, allocates suitably aligned contiguous pages and transitions the complete range to shared state. It also preserves the caller's GFP policy.
A private-to-shared transition may alter memory contents. Mask __GFP_ZERO from the underlying allocation and when requested, clear the complete transitioned range after cc_make_shared() succeeds.
Return the page and transitioned size so free_cc_shared_pages() can restore the complete range to private state before freeing it. If private state cannot be established, retain the allocation instead of returning a possibly shared page to the buddy allocator.
Also provide the shared-granule geometry and byte-oriented transition helpers used by the allocator and by callers managing their own backing memory.
--- include/linux/cc_shared.h | 39 +++++++ mm/Makefile | 1 + mm/cc_shared.c | 233 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 273 insertions(+) create mode 100644 include/linux/cc_shared.h create mode 100644 mm/cc_shared.c
include/linux/cc_shared.h new file +39 -0
@@ -0,0 +1,39 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _LINUX_CC_SHARED_H +#define _LINUX_CC_SHARED_H + +#include <linux/gfp_types.h> +#include <linux/types.h> + +struct page ; + +struct cc_shared_pages { +struct page *page; +size_t shared_size; +}; + +struct cc_shared_layout { +size_t requested_size; +size_t shared_size; +size_t alignment; +}; + +/* +* Architectures may override this to return the granule used for transitions +* between private and shared memory. The value must be a power of two and no +* smaller than PAGE_SIZE. +*/ +size_t arch_cc_shared_granule_size (void ); + +size_t cc_shared_granule_size (void ); +int cc_shared_calc_layout (size_t requested,struct cc_shared_layout *layout); +bool cc_shared_range_valid (phys_addr_t base,size_t size); +int cc_make_shared (void *addr,size_t size); +int cc_make_private (void *addr,size_t size); +int alloc_cc_shared_pages_node (int nid,gfp_t gfp, +size_t requested,struct cc_shared_pages *mem); +int alloc_cc_shared_pages (gfp_t gfp, +size_t requested,struct cc_shared_pages *mem); +void free_cc_shared_pages (struct cc_shared_pages *mem); + +#endif /* _LINUX_CC_SHARED_H */
mm/Makefile +1 -0
@@ -57,6 +57,7 @@ obj-y := filemap.o mempool.o oom_kill.o fadvise.o \ interval_tree.o list_lru.o workingset.o \ debug.o gup.o mmap_lock.o vma_init.o char-mem.o \ $(mmu-y) +obj-y += cc_shared.o # Give 'page_alloc' its own module-parameter namespace page-alloc-y := page_alloc.o
mm/cc_shared.c new file +233 -0
233 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v9 2/14 mm: Zero memory during shared memory transitions
In reply to Aneesh Kumar K.V (Arm)Architectures need to zero memory at different points in a private-to-shared transition. For example, pKVM must clear memory before sharing it, while Arm CCA can only clear it after the RSI transition has completed.
Make zeroing an implicit property of set_memory_decrypted(). Each architecture or platform performs the clear at the safe point in its transition. TDX clears memory after the private-to-shared conversion succeeds in the finish callback. AMD clears memory in its finish callback after the page-table update, TLB flush, and hypervisor notification, including for SEV-SNP. This zeros the final shared mapping without adding a flag to set_memory_decrypted() or threading it through architecture-specific callbacks.
Keep allocations on platforms without memory encryption on the ordinary page allocator path so the original GFP constraints, including __GFP_ZERO, remain intact. Remove post-transition memset() calls that are now redundant and explicitly clear allocations on paths where no transition occurs.
This intentionally makes every private-to-shared transition destructive; callers can no longer use set_memory_decrypted() to preserve existing contents.
--- arch/powerpc/platforms/pseries/svm.c | 2 + arch/s390/mm/init.c | 3 ++ arch/x86/coco/tdx/tdx.c | 3 ++ arch/x86/hyperv/hv_init.c | 6 ++- arch/x86/hyperv/ivm.c | 4 ++ arch/x86/kernel/kvmclock.c | 6 +-- arch/x86/mm/mem_encrypt_amd.c | 4 ++ drivers/firmware/arm_rmm/rsi.c | 4 ++ drivers/hv/connection.c | 41 +++++++++---------- drivers/hv/hv.c | 11 ++--- drivers/hv/hv_common.c | 2 - drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c | 3 ++ kernel/dma/direct.c | 22 ++++++---- mm/cc_shared.c | 7 +--- 14 files changed, 73 insertions(+), 45 deletions(-)
arch/powerpc/platforms/pseries/svm.c +2 -0
@@ -9,6 +9,7 @@#include <linux/mm.h> #include <linux/memblock.h> #include <linux/mem_encrypt.h> +#include <linux/string.h> #include <linux/cc_platform.h> #include <asm/machdep.h> #include <asm/svm.h>
@@ -59,6 +60,7 @@ int set_memory_decrypted(unsigned long addr, int numpages)if (!PAGE_ALIGNED (addr))return -EINVAL ; +memset ((void *)addr,0 , (size_t )numpages <<PAGE_SHIFT );uv_share_page (PHYS_PFN (__pa (addr)), numpages);return 0 ;
arch/s390/mm/init.c +3 -0
@@ -129,6 +129,9 @@ int set_memory_encrypted(unsigned long vaddr, int numpages)int set_memory_decrypted (unsigned long vaddr,int numpages) {int i; + +memset ((void *)vaddr,0 , (size_t )numpages <<PAGE_SHIFT ); +/* make specified pages shared (swiotlb, dma_alloca) */ for (i =0 ; i < numpages; ++i) {uv_set_shared (virt_to_phys ((void *)vaddr));
arch/x86/coco/tdx/tdx.c +3 -0
@@ -980,6 +980,9 @@ static int tdx_enc_status_change_finish(unsigned long vaddr, int numpages,if (!enc && !tdx_enc_status_changed (vaddr, numpages, enc))return -EIO ; +if (!enc) +memset ((void *)vaddr,0 , (size_t )numpages <<PAGE_SHIFT ); +if (enc)atomic_long_sub (numpages, &nr_shared);else
arch/x86/hyperv/hv_init.c +4 -2
@@ -156,8 +156,10 @@ static int hv_cpu_init(unsigned int cpu)* page in non-root partition here. */ if (*hvp && !ms_hyperv.paravisor_present &&hv_isolation_type_snp ()) { -WARN_ON_ONCE (set_memory_decrypted ((unsigned long )(*hvp),1 )); -memset (*hvp,0 ,PAGE_SIZE ); +int ret; + + ret =set_memory_decrypted ((unsigned long )*hvp,1 ); +WARN_ON_ONCE (ret); } }
arch/x86/hyperv/ivm.c +4 -0
@@ -755,6 +755,10 @@ static int hv_mark_gpa_visibility(u16 count, const u64 pfn[],*/ static int hv_vtom_clear_present (unsigned long kbuffer,int pagecount,bool enc) { +if (!enc) +memset ((void *)kbuffer,0 , + (size_t )pagecount <<PAGE_SHIFT ); +return set_memory_np (kbuffer, pagecount); }
arch/x86/kernel/kvmclock.c +3 -3
@@ -248,7 +248,7 @@ static void __init kvmclock_init_mem(void)* be mapped decrypted. */ if (cc_platform_has (CC_ATTR_GUEST_MEM_ENCRYPT )) { - r =set_memory_decrypted ((unsigned long ) hvclock_mem, + r =set_memory_decrypted ((unsigned long )hvclock_mem,1UL << order);if (r) {__free_pages (p, order);
@@ -256,9 +256,9 @@ static void __init kvmclock_init_mem(void)pr_warn ("kvmclock: set_memory_decrypted() failed. Disabling\n" );return ; } + }else { +memset (hvclock_mem,0 ,PAGE_SIZE << order); } - -memset (hvclock_mem,0 ,PAGE_SIZE << order); }static int __init kvm_setup_vsyscall_timeinfo (void )
arch/x86/mm/mem_encrypt_amd.c +4 -0
@@ -13,6 +13,7 @@#include <linux/dma-direct.h> #include <linux/swiotlb.h> #include <linux/mem_encrypt.h> +#include <linux/string.h> #include <linux/device.h> #include <linux/kernel.h> #include <linux/bitops.h>
@@ -308,6 +309,9 @@ static int amd_enc_status_change_finish(unsigned long vaddr, int npages, bool enif (!cc_platform_has (CC_ATTR_HOST_MEM_ENCRYPT ))enc_dec_hypercall (vaddr, npages <<PAGE_SHIFT , enc); +if (!enc) +memset ((void *)vaddr,0 , (size_t )npages <<PAGE_SHIFT ); +return 0 ; }
drivers/firmware/arm_rmm/rsi.c +4 -0
@@ -6,6 +6,7 @@#include <linux/jump_label.h> #include <linux/memblock.h> #include <linux/psci.h> +#include <linux/string.h> #include <linux/swiotlb.h> #include <linux/arm-rsi-cmds.h> #include <linux/kobject.h>
@@ -146,6 +147,9 @@ static int realm_set_memory_decrypted(unsigned long addr, int numpages) {int ret =__set_memory_enc_dec (addr, numpages, false); +if (!ret) +memset ((void *)addr,0 , (size_t )numpages <<PAGE_SHIFT ); +WARN (ret,"Failed to decrypt memory, %d pages will be leaked" , numpages);
drivers/hv/connection.c +20 -21
55 lines not on this page · raw message
drivers/hv/hv.c +6 -5
@@ -123,12 +123,13 @@ static int hv_alloc_page(void **page, bool decrypt, const char *note)if (!*page)return -ENOMEM ; -if (decrypt) +if (decrypt) { ret =set_memory_decrypted ((unsigned long )*page,1 ); -if (ret) - goto failed; - -memset (*page,0 ,PAGE_SIZE ); +if (ret) + goto failed; + }else { +memset (*page,0 ,PAGE_SIZE ); + }return 0 ; failed:
drivers/hv/hv_common.c +0 -2
@@ -535,8 +535,6 @@ int hv_common_cpu_init(unsigned int cpu)/* It may be unsafe to free 'mem' */ return ret; } - -memset (mem,0x00 , pgcount *HV_HYP_PAGE_SIZE ); }/*
drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c +3 -0
@@ -13,6 +13,7 @@#include <linux/mem_encrypt.h> #include <linux/mm.h> #include <linux/pgtable.h> +#include <linux/string.h> #include <asm/hypervisor.h>
@@ -61,6 +62,8 @@ static int pkvm_set_memory_encrypted(unsigned long addr, int numpages)static int pkvm_set_memory_decrypted (unsigned long addr,int numpages) { +memset ((void *)addr,0 , (size_t )numpages <<PAGE_SHIFT ); +return __set_memory_range (ARM_SMCCC_VENDOR_HYP_KVM_MEM_SHARE_FUNC_ID , addr, numpages); }
kernel/dma/direct.c +15 -7
@@ -229,7 +229,8 @@ void *dma_direct_alloc(struct device *dev, size_t size,if (force_dma_unencrypted (dev)) attrs |= __DMA_ATTR_ALLOC_CC_SHARED; -if (attrs & __DMA_ATTR_ALLOC_CC_SHARED) { + mark_mem_decrypt = attrs & __DMA_ATTR_ALLOC_CC_SHARED; +if (mark_mem_decrypt) {/* * Unencrypted/shared DMA requires a linear-mapped buffer * address to look up the PFN and set architecture-required PFN
@@ -237,7 +238,6 @@ void *dma_direct_alloc(struct device *dev, size_t size,* allocation. */ allow_highmem = false; - mark_mem_decrypt = true; } size =PAGE_ALIGN (size);
@@ -341,7 +341,9 @@ void *dma_direct_alloc(struct device *dev, size_t size, cpu_addr =page_address (page); } -memset (cpu_addr,0 , size); +/* Zero after remapping because the page may be in HighMem. */ +if (!mark_mem_decrypt) +memset (cpu_addr,0 , size);if (set_uncached) {void *uncached_cpu_addr;
@@ -451,10 +453,13 @@ struct page *dma_direct_alloc_pages(struct device *dev, size_t size,unsigned long attrs =0 ;struct page *page;void *cpu_addr; +bool mark_mem_decrypt;if (force_dma_unencrypted (dev)) attrs |= __DMA_ATTR_ALLOC_CC_SHARED; + mark_mem_decrypt = attrs & __DMA_ATTR_ALLOC_CC_SHARED; +if ((attrs & __DMA_ATTR_ALLOC_CC_SHARED) &&dma_direct_use_pool (dev, gfp))return dma_direct_alloc_from_pool (dev, size, dma_handle, &cpu_addr, gfp, attrs);
@@ -465,6 +470,7 @@ struct page *dma_direct_alloc_pages(struct device *dev, size_t size,return NULL ; cpu_addr =page_address (page); + mark_mem_decrypt = false; goto setup_page; }
@@ -473,11 +479,13 @@ struct page *dma_direct_alloc_pages(struct device *dev, size_t size,return NULL ; cpu_addr =page_address (page); -if ((attrs & __DMA_ATTR_ALLOC_CC_SHARED) && -dma_set_decrypted (dev, cpu_addr, size)) - goto out_leak_pages; setup_page: -memset (cpu_addr,0 , size); +if (mark_mem_decrypt) { +if (dma_set_decrypted (dev, cpu_addr, size)) + goto out_leak_pages; + }else { +memset (cpu_addr,0 , size); + } *dma_handle =phys_to_dma_direct (dev,page_to_phys (page), attrs & __DMA_ATTR_ALLOC_CC_SHARED);return page;
mm/cc_shared.c +2 -5
@@ -104,7 +104,6 @@ static int __alloc_cc_shared_pages_node(int nid, gfp_t gfp,struct cc_shared_layout layout;struct page *page;unsigned int order; -bool zero = gfp & __GFP_ZERO;int ret; ret =cc_shared_calc_layout (requested, &layout);
@@ -116,7 +115,8 @@ static int __alloc_cc_shared_pages_node(int nid, gfp_t gfp,return -EINVAL ;/* * State transitions require a linear-map address and may modify memory. -* Allocate from low memory and defer requested zeroing until afterwards. +* Allocate from low memory and let the architecture place zeroing at the +* appropriate point in the transition. * Shared allocations have no migration support, so they must not * be allocated with __GFP_MOVABLE. */
@@ -138,9 +138,6 @@ static int __alloc_cc_shared_pages_node(int nid, gfp_t gfp,return ret; } -if (zero) -memset (page_address (page),0 , layout.shared_size); - mem->page = page; mem->shared_size = layout.shared_size;return 0 ;
Signature · 1 line
2.43.0
PATCH v9 3/14 irqchip/gic-v3-its: Resolve the default NUMA node explicitly
In reply to Aneesh Kumar K.V (Arm)alloc_pages_node() resolves NUMA_NO_NODE to numa_mem_id() internally. In preparation for switching ITS allocations to the CoCo shared memory allocator, resolve the default node explicitly in its_alloc_pages_node().
The CoCo shared memory allocator interprets NUMA_NO_NODE as a request to apply the current task's memory policy. Resolving it to numa_mem_id() in the common ITS allocation helper preserves the existing nearest-memory-node placement for all callers
This patch does not change the current allocation behavior.
--- drivers/irqchip/irq-gic-v3-its.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/irqchip/irq-gic-v3-its.c +4 -0
@@ -32,6 +32,7 @@#include <linux/set_memory.h> #include <linux/slab.h> #include <linux/syscore_ops.h> +#include <linux/topology.h> #include <linux/irqchip.h> #include <linux/irqchip/arm-gic-v3.h>
@@ -218,6 +219,9 @@ static struct page *its_alloc_pages_node(int node, gfp_t gfp,struct page *page;int ret =0 ; +if (node ==NUMA_NO_NODE ) + node =numa_mem_id (); + page =alloc_pages_node (node, gfp | gfp_flags_quirk, order);if (!page)
Signature · 1 line
2.43.0
PATCH v9 4/14 irqchip/gic-v3-its: Allocate shared tables using CoCo shared memory allocator
In reply to Aneesh Kumar K.V (Arm)ITS command queues and tables are shared with the host in a confidential-computing guest. The ITS allocator currently assumes that the guest PAGE_SIZE is sufficient for both allocation alignment and private/shared state changes.
Route ITS page allocations through alloc_cc_shared_pages_node(). Keep the tracked table size based on the ITS-requested order. On release, reconstruct the common allocation metadata from the original ITS order and the architecture granule size so the same transitioned range and buddy order are used.
--- drivers/irqchip/irq-gic-v3-its.c | 40 ++++++++++++-------------------- 1 file changed, 15 insertions(+), 25 deletions(-)
drivers/irqchip/irq-gic-v3-its.c +15 -25
@@ -8,6 +8,7 @@#include <linux/acpi_iort.h> #include <linux/bitfield.h> #include <linux/bitmap.h> +#include <linux/cc_shared.h> #include <linux/cpu.h> #include <linux/crash_dump.h> #include <linux/delay.h>
@@ -19,7 +20,6 @@#include <linux/irqdomain.h> #include <linux/list.h> #include <linux/log2.h> -#include <linux/mem_encrypt.h> #include <linux/memblock.h> #include <linux/mm.h> #include <linux/msi.h>
@@ -29,7 +29,6 @@#include <linux/of_pci.h> #include <linux/of_platform.h> #include <linux/percpu.h> -#include <linux/set_memory.h> #include <linux/slab.h> #include <linux/syscore_ops.h> #include <linux/topology.h>
@@ -216,28 +215,16 @@ static gfp_t gfp_flags_quirk;static struct page *its_alloc_pages_node (int node,gfp_t gfp,unsigned int order) { -struct page *page; -int ret =0 ; +struct cc_shared_pages mem;if (node ==NUMA_NO_NODE ) node =numa_mem_id (); - page =alloc_pages_node (node, gfp | gfp_flags_quirk, order); - -if (!page) -return NULL ; - - ret =set_memory_decrypted ((unsigned long )page_address (page), -1 << order); -/* -* If set_memory_decrypted() fails then we don't know what state the -* page is in, so we can't free it. Instead we leak it. -* set_memory_decrypted() will already have WARNed. -*/ -if (ret) +if (alloc_cc_shared_pages_node (node, gfp | gfp_flags_quirk, +PAGE_SIZE << order, &mem))return NULL ; -return page; +return mem.page; }static struct page *its_alloc_pages (gfp_t gfp,unsigned int order)
@@ -247,13 +234,15 @@ static struct page *its_alloc_pages(gfp_t gfp, unsigned int order)static void its_free_pages (void *addr,unsigned int order) { -/* -* If the memory cannot be encrypted again then we must leak the pages. -* set_memory_encrypted() will already have WARNed. -*/ -if (set_memory_encrypted ((unsigned long )addr,1 << order)) +struct cc_shared_layout layout; +struct cc_shared_pages mem; + +if (WARN_ON (cc_shared_calc_layout (PAGE_SIZE << order, &layout)))return ; -free_pages ((unsigned long )addr, order); + + mem.page =virt_to_page (addr); + mem.shared_size = layout.shared_size; +free_cc_shared_pages (&mem); }static struct gen_pool *itt_pool;
@@ -278,7 +267,8 @@ static void *itt_alloc_pool(int node, int size)if (!page)break ; -gen_pool_add (itt_pool, (unsigned long )page_address (page),PAGE_SIZE , node); +gen_pool_add (itt_pool, (unsigned long )page_address (page), +cc_shared_granule_size (), node); }while (!addr);return (void *)addr;
Signature · 1 line
2.43.0
PATCH v9 5/14 dma-contiguous: Derive shared alignment from DMA attributes
In reply to Aneesh Kumar K.V (Arm)Confidential-computing shared DMA allocations require CMA backing memory to be aligned to the architecture shared-memory granule. Passing explicit alignment orders through the DMA allocation stack exposes this derived constraint to callers and requires separate preferred and mandatory values.
The DMA core already records whether an allocation needs shared backing in __DMA_ATTR_ALLOC_CC_SHARED. Pass allocation attributes to the DMA-contiguous entry points and derive the mandatory alignment there before calling CMA. Preserve the existing alignment clamping for ordinary allocations, while rejecting shared allocations whose granule exceeds CONFIG_CMA_ALIGNMENT so callers can fall back to the page allocator.
--- arch/arm/mm/dma-mapping.c | 5 +++-- drivers/iommu/dma-iommu.c | 2 +- include/linux/dma-map-ops.h | 9 ++++---- kernel/dma/contiguous.c | 41 +++++++++++++++++++++++++++---------- kernel/dma/direct.c | 2 +- kernel/dma/ops_helpers.c | 2 +- kernel/dma/pool.c | 2 +- kernel/kexec_file.c | 3 ++- 8 files changed, 44 insertions(+), 22 deletions(-)
arch/arm/mm/dma-mapping.c +3 -2
@@ -398,7 +398,8 @@ static void *__alloc_from_contiguous(struct device *dev, size_t size,struct page *page;void *ptr =NULL ; - page =dma_alloc_from_contiguous (dev, count, order, gfp & __GFP_NOWARN); + page =dma_alloc_from_contiguous (dev, count, order,0 , + gfp & __GFP_NOWARN);if (!page)return NULL ;
@@ -866,7 +867,7 @@ static struct page **__iommu_alloc_buffer(struct device *dev, size_t size,unsigned long order =get_order (size);struct page *page; - page =dma_alloc_from_contiguous (dev, count, order, + page =dma_alloc_from_contiguous (dev, count, order,0 , gfp & __GFP_NOWARN);if (!page) goto error;
drivers/iommu/dma-iommu.c +1 -1
@@ -1646,7 +1646,7 @@ static void *iommu_dma_alloc_pages(struct device *dev, size_t size,struct page *page =NULL ;void *cpu_addr; - page =dma_alloc_contiguous (dev, alloc_size, gfp); + page =dma_alloc_contiguous (dev, alloc_size, gfp,0 );if (!page) { cpu_addr =alloc_pages_exact_nid (node, alloc_size, gfp);if (!cpu_addr)
include/linux/dma-map-ops.h +5 -4
@@ -99,10 +99,11 @@ int __init dma_contiguous_reserve_area(phys_addr_t size, phys_addr_t base, phys_addr_t limit, struct cma **res_cma, bool fixed);struct page *dma_alloc_from_contiguous (struct device *dev,size_t count, -unsigned int order,bool no_warn); +unsigned int order,unsigned long attrs,bool no_warn);bool dma_release_from_contiguous (struct device *dev,struct page *pages,int count); -struct page *dma_alloc_contiguous (struct device *dev,size_t size,gfp_t gfp); +struct page *dma_alloc_contiguous (struct device *dev,size_t size, +gfp_t gfp,unsigned long attrs);void dma_free_contiguous (struct device *dev,struct page *page,size_t size);void dma_contiguous_early_fixup (phys_addr_t base,unsigned long size);
@@ -125,7 +126,7 @@ static inline int dma_contiguous_reserve_area(phys_addr_t size,return -ENOSYS ; }static inline struct page *dma_alloc_from_contiguous (struct device *dev, -size_t count,unsigned int order,bool no_warn) +size_t count,unsigned int order,unsigned long attrs,bool no_warn) {return NULL ; }
@@ -136,7 +137,7 @@ static inline bool dma_release_from_contiguous(struct device *dev, }/* Use fallback alloc() and free() when CONFIG_DMA_CMA=n */ static inline struct page *dma_alloc_contiguous (struct device *dev,size_t size, -gfp_t gfp) +gfp_t gfp,unsigned long attrs) {return NULL ; }
kernel/dma/contiguous.c +30 -11
101 lines not on this page · raw message
kernel/dma/direct.c +1 -1
@@ -125,7 +125,7 @@ static struct page *__dma_direct_alloc_pages(struct device *dev, size_t size,WARN_ON_ONCE (!PAGE_ALIGNED (size)); gfp |=dma_direct_optimal_gfp_mask (dev, &phys_limit); - page =dma_alloc_contiguous (dev, size, gfp); + page =dma_alloc_contiguous (dev, size, gfp,0 );if (page) {if (dma_coherent_ok (dev,page_to_phys (page), size) && (allow_highmem || !PageHighMem (page)))
kernel/dma/ops_helpers.c +1 -1
@@ -66,7 +66,7 @@ struct page *dma_common_alloc_pages(struct device *dev, size_t size,struct page *page;phys_addr_t phys; - page =dma_alloc_contiguous (dev, size, gfp); + page =dma_alloc_contiguous (dev, size, gfp,0 );if (!page) {void *va =alloc_pages_exact_nid (dev_to_node (dev), size, gfp);
kernel/dma/pool.c +1 -1
@@ -99,7 +99,7 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size, pool_size =1 << (PAGE_SHIFT + order);if (cma_in_zone (gfp)) page =dma_alloc_from_contiguous (NULL ,1 << order, - order, false); + order,0 , false);if (!page) page =alloc_pages (gfp | __GFP_NOWARN, order); }while (!page && order-- >0 );
kernel/kexec_file.c +2 -1
@@ -702,7 +702,8 @@ static int kexec_alloc_contig(struct kexec_buf *kbuf)if (kbuf->image->type ==KEXEC_TYPE_CRASH )return -EPERM ; - p =dma_alloc_from_contiguous (NULL , nr_pages,get_order (kbuf->buf_align), true); + p =dma_alloc_from_contiguous (NULL , nr_pages, +get_order (kbuf->buf_align),0 , true);if (!p)return -ENOMEM ;
Signature · 1 line
2.43.0
PATCH v9 6/14 dma-pool: Allocate CoCo atomic pools using CoCo shared memory allocator
In reply to Aneesh Kumar K.V (Arm)Atomic DMA allocations cannot perform a potentially sleeping private/shared state transition at allocation time. The atomic DMA pools avoid this by transitioning their backing allocations in a sleepable context and suballocating memory that is already shared.
Architectures may require these transitions to use a shared granule size larger than PAGE_SIZE. The existing fallback loop can reduce the backing allocation below the order required by that size, producing a range that cannot be safely transitioned.
For pools marked cc_shared, round the requested pool size up to a multiple of the shared granule size and prevent allocation fallback below the order required by that size. Pass __DMA_ATTR_ALLOC_CC_SHARED to dma_alloc_from_contiguous() so it enforces the mandatory alignment. If CMA cannot satisfy it, fall back to the buddy allocator. Non-shared pools pass zero attributes and retain the existing CMA alignment policy.
Use the cc_make_shared() and cc_make_private() helpers to transition the backing allocation and validate its address and size.
Individual atomic allocations may remain smaller than the shared granule size because the backing allocation remains owned by the pool and in the shared state.
--- kernel/dma/pool.c | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-)
kernel/dma/pool.c +21 -6
@@ -4,12 +4,12 @@* Copyright (C) 2020 Google LLC */ #include <linux/cma.h> +#include <linux/cc_shared.h> #include <linux/debugfs.h> #include <linux/dma-map-ops.h> #include <linux/dma-direct.h> #include <linux/init.h> #include <linux/genalloc.h> -#include <linux/set_memory.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/cc_platform.h>
@@ -85,6 +85,9 @@ static bool cma_in_zone(gfp_t gfp)static int atomic_pool_expand (struct dma_gen_pool *dma_pool,size_t pool_size,gfp_t gfp) { +struct cc_shared_layout layout; +unsigned long attrs =0 ; +unsigned int min_order =0 ;unsigned int order;struct page *page =NULL ;bool leak_pages = false;
@@ -92,6 +95,19 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size,int ret = -ENOMEM ;pgprot_t prot__maybe_unused ; +if (dma_pool->cc_shared) { +int err; + + err =cc_shared_calc_layout (pool_size, &layout); +if (err) +return err; + pool_size = layout.shared_size; + min_order =get_order (layout.alignment); +if (min_order >MAX_PAGE_ORDER ) +return -E2BIG ; + attrs = __DMA_ATTR_ALLOC_CC_SHARED; + } +/* Cannot allocate larger than MAX_PAGE_ORDER */ order =min (get_order (pool_size),MAX_PAGE_ORDER );
@@ -99,10 +115,10 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size, pool_size =1 << (PAGE_SHIFT + order);if (cma_in_zone (gfp)) page =dma_alloc_from_contiguous (NULL ,1 << order, - order,0 , false); + order, attrs, false);if (!page) page =alloc_pages (gfp | __GFP_NOWARN, order); - }while (!page && order-- >0 ); + }while (!page && order-- > min_order);if (!page) goto out;
@@ -126,8 +142,7 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size,* shrink so no re-encryption occurs in dma_direct_free(). */ if (dma_pool->cc_shared) { - ret =set_memory_decrypted ((unsigned long )page_to_virt (page), -1 << order); + ret =cc_make_shared (page_to_virt (page), pool_size);if (ret) { leak_pages = true; goto remove_mapping;
@@ -144,7 +159,7 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size, encrypt_mapping:if (dma_pool->cc_shared && -set_memory_encrypted ((unsigned long )page_to_virt (page),1 << order)) +cc_make_private (page_to_virt (page), pool_size)) leak_pages = true; remove_mapping:
Signature · 1 line
2.43.0
PATCH v9 7/14 dma-direct: Align CoCo shared DMA allocations to the shared granule size
In reply to Aneesh Kumar K.V (Arm)Use the common CoCo shared-memory geometry helpers for allocations backed directly by CMA or the page allocator. Round the backing allocation to a whole shared granule and pass the resolved shared-allocation attribute through the DMA contiguous allocator so it can enforce the mandatory alignment. Transition the complete range through the common shared/private helpers.
Recompute the layout before freeing ordinary direct allocations so the transition back to private memory and dma_free_contiguous() cover exactly the range acquired by the allocation path. If restoring private state fails, retain the existing fail-safe behavior and leak the pages rather than returning potentially shared memory to the allocator.
This also applies the same rules to dma_direct_alloc_pages(), covering callers which require a struct page result rather than a CPU virtual address.
--- kernel/dma/direct.c | 51 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 12 deletions(-)
kernel/dma/direct.c +39 -12
@@ -11,10 +11,10 @@#include <linux/scatterlist.h> #include <linux/pfn.h> #include <linux/vmalloc.h> -#include <linux/set_memory.h> #include <linux/slab.h> #include <linux/pci-p2pdma.h> #include <linux/cc_platform.h> +#include <linux/cc_shared.h> #include "direct.h"
@@ -85,7 +85,7 @@ static int dma_set_decrypted(struct device *dev, void *vaddr, size_t size) {int ret; - ret =set_memory_decrypted ((unsigned long )vaddr,PFN_UP (size)); + ret =cc_make_shared (vaddr, size);if (ret)pr_warn_ratelimited ("leaking DMA memory that can't be decrypted\n" );return ret;
@@ -95,7 +95,7 @@ static int dma_set_encrypted(struct device *dev, void *vaddr, size_t size) {int ret; - ret =set_memory_encrypted ((unsigned long )vaddr,PFN_UP (size)); + ret =cc_make_private (vaddr, size);if (ret)pr_warn_ratelimited ("leaking DMA memory that can't be re-encrypted\n" );return ret;
@@ -115,7 +115,7 @@ static struct page *dma_direct_alloc_swiotlb(struct device *dev, size_t size, }static struct page *__dma_direct_alloc_pages (struct device *dev,size_t size, -gfp_t gfp,bool allow_highmem) +gfp_t gfp,bool allow_highmem,unsigned long attrs) {int node =dev_to_node (dev);struct page *page;
@@ -125,7 +125,7 @@ static struct page *__dma_direct_alloc_pages(struct device *dev, size_t size,WARN_ON_ONCE (!PAGE_ALIGNED (size)); gfp |=dma_direct_optimal_gfp_mask (dev, &phys_limit); - page =dma_alloc_contiguous (dev, size, gfp,0 ); + page =dma_alloc_contiguous (dev, size, gfp, attrs);if (page) {if (dma_coherent_ok (dev,page_to_phys (page), size) && (allow_highmem || !PageHighMem (page)))
@@ -202,7 +202,7 @@ static void *dma_direct_alloc_no_mapping(struct device *dev, size_t size, {struct page *page; - page =__dma_direct_alloc_pages (dev, size, gfp & ~__GFP_ZERO, true); + page =__dma_direct_alloc_pages (dev, size, gfp & ~__GFP_ZERO, true,0 );if (!page)return NULL ;
@@ -223,6 +223,7 @@ void *dma_direct_alloc(struct device *dev, size_t size,bool remap = false, set_uncached = false;bool mark_mem_decrypt = false;bool allow_highmem = true; +struct cc_shared_layout layout;struct page *page;void *cpu_addr;
@@ -302,8 +303,15 @@ void *dma_direct_alloc(struct device *dev, size_t size,return NULL ; } +if (mark_mem_decrypt) { +if (cc_shared_calc_layout (size, &layout)) +return NULL ; + size = layout.shared_size; + } +/* we always manually zero the memory once we are done */ - page =__dma_direct_alloc_pages (dev, size, gfp & ~__GFP_ZERO, allow_highmem); + page =__dma_direct_alloc_pages (dev, size, gfp & ~__GFP_ZERO, + allow_highmem, attrs);if (!page)return NULL ;
@@ -322,7 +330,7 @@ void *dma_direct_alloc(struct device *dev, size_t size,void *lm_addr; lm_addr =page_address (page); -if (set_memory_decrypted ((unsigned long )lm_addr,PFN_UP (size))) +if (dma_set_decrypted (dev, lm_addr, size)) goto out_leak_pages; }
@@ -381,6 +389,7 @@ void dma_direct_free(struct device *dev, size_t size,phys_addr_t phys;bool mark_mem_encrypted = false;struct io_tlb_pool *swiotlb_pool; +struct cc_shared_layout layout;unsigned int page_order =get_order (size);/*
@@ -424,6 +433,12 @@ void dma_direct_free(struct device *dev, size_t size,/* Swiotlb doesn't need a page attribute update on free */ mark_mem_encrypted = false; +if (mark_mem_encrypted) { +if (WARN_ON_ONCE (cc_shared_calc_layout (size, &layout))) +return ; + size = layout.shared_size; + } +if (is_vmalloc_addr (cpu_addr)) {vunmap (cpu_addr); }else {
@@ -435,10 +450,8 @@ void dma_direct_free(struct device *dev, size_t size,void *lm_addr; lm_addr =phys_to_virt (phys); -if (set_memory_encrypted ((unsigned long )lm_addr,PFN_UP (size))) { -pr_warn_ratelimited ("leaking DMA memory that can't be re-encrypted\n" ); +if (dma_set_encrypted (dev, lm_addr, size))return ; - } }if (swiotlb_pool)
@@ -451,6 +464,7 @@ struct page *dma_direct_alloc_pages(struct device *dev, size_t size, dma_addr_t *dma_handle, enum dma_data_direction dir, gfp_t gfp) { unsigned long attrs = 0; +struct cc_shared_layout layout;struct page *page;void *cpu_addr;bool mark_mem_decrypt;
@@ -474,7 +488,13 @@ struct page *dma_direct_alloc_pages(struct device *dev, size_t size, goto setup_page; } - page =__dma_direct_alloc_pages (dev, size, gfp, false); +if (mark_mem_decrypt) { +if (cc_shared_calc_layout (size, &layout)) +return NULL ; + size = layout.shared_size; + } + + page =__dma_direct_alloc_pages (dev, size, gfp, false, attrs);if (!page)return NULL ;
@@ -500,6 +520,7 @@ void dma_direct_free_pages(struct device *dev, size_t size,phys_addr_t phys;void *vaddr =page_address (page);struct io_tlb_pool *swiotlb_pool; +struct cc_shared_layout layout;/* * if the device had requested for an unencrypted buffer, * convert it to encrypted on free
@@ -516,6 +537,12 @@ void dma_direct_free_pages(struct device *dev, size_t size,if (swiotlb_pool) mark_mem_encrypted = false; +if (mark_mem_encrypted) { +if (WARN_ON_ONCE (cc_shared_calc_layout (size, &layout))) +return ; + size = layout.shared_size; + } +if (mark_mem_encrypted &&dma_set_encrypted (dev, vaddr, size))return ;
Signature · 1 line
2.43.0
PATCH v9 8/14 swiotlb: Align shared IO TLB pools to the shared granule size
In reply to Aneesh Kumar K.V (Arm)Align and size the early memblock pool to the common CoCo shared granule. Use the same rounded extent when the pool is transitioned and when it is released. This deliberately leaves the slot count unchanged:
any rounded tail belongs to the pool allocation but is not advertised as allocatable SWIOTLB space.
Replace the default and dynamic pool set_memory calls with the helpers so alignment validation and architecture dispatch are kept in one place. As before, pages are intentionally leaked if their private state cannot be restored safely.
--- kernel/dma/swiotlb.c | 47 +++++++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 18 deletions(-)
kernel/dma/swiotlb.c +29 -18
@@ -22,6 +22,7 @@#include <linux/cache.h> #include <linux/cc_platform.h> +#include <linux/cc_shared.h> #include <linux/ctype.h> #include <linux/debugfs.h> #include <linux/dma-direct.h>
@@ -38,7 +39,6 @@#include <linux/pfn.h> #include <linux/rculist.h> #include <linux/scatterlist.h> -#include <linux/set_memory.h> #include <linux/spinlock.h> #include <linux/string.h> #include <linux/swiotlb.h>
@@ -367,13 +367,13 @@ void __init swiotlb_update_mem_attributes(void)if (!mem->nslabs || mem->late_alloc)return ; - bytes =PAGE_ALIGN (mem->nslabs <<IO_TLB_SHIFT ); + + bytes =ALIGN (mem->nslabs <<IO_TLB_SHIFT ,cc_shared_granule_size ());if (io_tlb_default_mem.cc_shared) {int ret; - ret =set_memory_decrypted ((unsigned long )mem->vaddr, - bytes >>PAGE_SHIFT ); + ret =cc_make_shared (mem->vaddr, bytes);if (ret) {pr_warn ("Failed to decrypt default memory pool, disabling it\n" );swiotlb_mark_pool_used (mem);
@@ -434,8 +434,8 @@ static void __init *swiotlb_memblock_alloc(unsigned long nslabs,unsigned int flags, int (*remap)(void *tlb, unsigned long nslabs)) { - size_t bytes = PAGE_ALIGN(nslabs << IO_TLB_SHIFT); void *tlb; +size_t bytes =ALIGN (nslabs <<IO_TLB_SHIFT ,cc_shared_granule_size ());/* * By default allocate the bounce buffer memory from low memory, but
@@ -443,9 +443,9 @@ static void __init *swiotlb_memblock_alloc(unsigned long nslabs,* memory encryption. */ if (flags &SWIOTLB_ANY ) - tlb =memblock_alloc (bytes,PAGE_SIZE ); + tlb =memblock_alloc (bytes,cc_shared_granule_size ());else - tlb =memblock_alloc_low (bytes,PAGE_SIZE ); + tlb =memblock_alloc_low (bytes,cc_shared_granule_size ());if (!tlb) { pr_warn("%s: Failed to allocate %zu bytes tlb structure\n",
@@ -454,7 +454,7 @@ static void __init *swiotlb_memblock_alloc(unsigned long nslabs, }if (remap &&remap (tlb, nslabs) <0 ) { -memblock_free (tlb,PAGE_ALIGN (bytes)); +memblock_free (tlb, bytes);pr_warn ("%s: Failed to remap %zu bytes\n" , __func__, bytes);return NULL ; }
@@ -576,7 +576,7 @@ int swiotlb_init_late(size_t size, gfp_t gfp_mask,swiotlb_adjust_nareas (num_possible_cpus ()); retry: - order =get_order (nslabs <<IO_TLB_SHIFT ); + order =get_order (ALIGN (nslabs <<IO_TLB_SHIFT ,cc_shared_granule_size ())); nslabs =SLABS_PER_PAGE << order;while ((SLABS_PER_PAGE << order) >IO_TLB_MIN_SLABS ) {
@@ -585,6 +585,8 @@ int swiotlb_init_late(size_t size, gfp_t gfp_mask,if (vstart)break ; order--; +if (order <get_order (cc_shared_granule_size ())) +break ; nslabs =SLABS_PER_PAGE << order; retried = true; }
@@ -598,8 +600,13 @@ int swiotlb_init_late(size_t size, gfp_t gfp_mask,free_pages ((unsigned long )vstart, order); nslabs =ALIGN (nslabs >>1 ,IO_TLB_SEGSIZE ); -if (nslabs <IO_TLB_MIN_SLABS ) +if (nslabs <=IO_TLB_MIN_SLABS )return rc; + +/* Avoid infinite loop */ +if (WARN_ON (nslabs < (cc_shared_granule_size () >>IO_TLB_SHIFT ))) +return rc; + retried = true; goto retry; }
@@ -624,8 +631,7 @@ int swiotlb_init_late(size_t size, gfp_t gfp_mask, goto error_slots;if (io_tlb_default_mem.cc_shared) { - rc =set_memory_decrypted ((unsigned long )vstart, - (nslabs <<IO_TLB_SHIFT ) >>PAGE_SHIFT ); + rc =cc_make_shared (vstart, nslabs <<IO_TLB_SHIFT );if (rc) { leak_pages = true; goto error_decrypt;
@@ -665,11 +671,11 @@ void __init swiotlb_exit(void)pr_info ("tearing down default memory pool\n" ); tbl_vaddr = (unsigned long )phys_to_virt (mem->start); - tbl_size =PAGE_ALIGN (mem->end - mem->start); + tbl_size =ALIGN (mem->end - mem->start,cc_shared_granule_size ()); slots_size =PAGE_ALIGN (array_size (sizeof (*mem->slots), mem->nslabs));if (io_tlb_default_mem.cc_shared) { -if (set_memory_encrypted (tbl_vaddr, tbl_size >>PAGE_SHIFT )) +if (cc_make_private ((void *)tbl_vaddr, tbl_size)) leak_pages = true; }
@@ -709,12 +715,15 @@ void __init swiotlb_exit(void)static struct page *alloc_dma_pages (gfp_t gfp,size_t bytes,u64 phys_limit,unsigned long attrs) { -unsigned int order =get_order (bytes);bool cc_shared = attrs & __DMA_ATTR_ALLOC_CC_SHARED; +unsigned int order;struct page *page;phys_addr_t paddr;void *vaddr; +if (cc_shared) + bytes =ALIGN (bytes,cc_shared_granule_size ()); + order =get_order (bytes); page =alloc_pages (gfp, order);if (!page)return NULL ;
@@ -726,13 +735,13 @@ static struct page *alloc_dma_pages(gfp_t gfp, size_t bytes, } vaddr =phys_to_virt (paddr); -if (cc_shared &&set_memory_decrypted ((unsigned long )vaddr,PFN_UP (bytes))) +if (cc_shared &&cc_make_shared (vaddr, bytes)) goto error;return page; error:/* Intentional leak if pages cannot be encrypted again. */ -if (cc_shared && !set_memory_encrypted ((unsigned long )vaddr,PFN_UP (bytes))) +if (cc_shared && !cc_make_private (vaddr, bytes))__free_pages (page, order);return NULL ; }
@@ -805,9 +814,11 @@ static void swiotlb_free_tlb(void *vaddr, size_t bytes, bool cc_shared) dma_free_from_pool(NULL, vaddr, bytes))return ; +if (cc_shared) + bytes =ALIGN (bytes,cc_shared_granule_size ());/* Intentional leak if pages cannot be encrypted again. */ if (!cc_shared || - !set_memory_encrypted ((unsigned long )vaddr,PFN_UP (bytes))) + !cc_make_private (vaddr, bytes))__free_pages (virt_to_page (vaddr),get_order (bytes)); }
Signature · 1 line
2.43.0
PATCH v9 9/14 swiotlb: Reject misaligned restricted DMA pools for CoCo guests
In reply to Aneesh Kumar K.V (Arm)A restricted DMA pool is a firmware-described ownership boundary. Unlike a pool allocated by SWIOTLB itself, its base cannot be moved and its size cannot be rounded without claiming memory outside the reserved region.
Confidential-computing guests may require private/shared state changes to cover units larger than PAGE_SIZE. Passing a misaligned restricted region to set_memory_decrypted() can therefore fail.
Validate both the physical base and the complete reserved size with the common CoCo shared-range helper before allocating SWIOTLB metadata or performing a state transition. Perform the transition through cc_make_shared().
--- kernel/dma/swiotlb.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)
kernel/dma/swiotlb.c +10 -2
@@ -2011,6 +2011,14 @@ static int rmem_swiotlb_device_init(struct reserved_mem *rmem,return -EINVAL ; } +if (cc_platform_has (CC_ATTR_MEM_ENCRYPT ) && + !cc_shared_range_valid (rmem->base, rmem->size)) { +dev_err (dev, +"Restricted DMA pool must be aligned to %#zx bytes for memory encryption\n" , +cc_shared_granule_size ()); +return -EINVAL ; + } +/* * Since multiple devices can share the same pool, the private data, * io_tlb_mem struct, will be initialized by the first device attached
@@ -2044,8 +2052,8 @@ static int rmem_swiotlb_device_init(struct reserved_mem *rmem,int ret; mem->cc_shared = true; - ret =set_memory_decrypted ((unsigned long )phys_to_virt (rmem->base), - rmem->size >>PAGE_SHIFT ); + ret =cc_make_shared (phys_to_virt (rmem->base), + rmem->size);if (ret) {dev_err (dev,"Failed to decrypt restricted DMA pool\n" );kfree (pool->areas);
Signature · 1 line
2.43.0
PATCH v9 10/14 dma-buf: system_heap: Limit scatterlist entries to the buffer size
In reply to Aneesh Kumar K.V (Arm)The system heap currently allocates each backing page no larger than the remaining dma-buf length. It can therefore use the complete compound-page size for every scatterlist entry while keeping the total length equal to the buffer size.
Shared backing allocations may need to be rounded up to an architecture shared granule size. A backing allocation can then be larger than the remaining buffer length. Describing the complete allocation in the scatterlist would incorrectly expose the rounded tail to scatterlist consumers as part of the dma-buf.
Track the remaining buffer length while constructing the scatterlist and limit each entry to the smaller of the compound-page size and the remaining length. The complete backing allocation remains owned by the heap and is still released normally.
This does not change behavior with the current allocation policy, but prepares the heap for shared-granule-sized backing allocations.
--- drivers/dma-buf/heaps/system_heap.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/dma-buf/heaps/system_heap.c +6 -1
@@ -406,6 +406,7 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,struct system_heap_buffer *buffer;DEFINE_DMA_BUF_EXPORT_INFO (exp_info);unsigned long size_remaining = len; +unsigned long sg_remaining = len;unsigned int max_order = orders[0 ];struct system_heap_priv *priv =dma_heap_get_drvdata (heap);bool cc_shared = priv->cc_shared;
@@ -454,7 +455,11 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap, sg = table->sgl;list_for_each_entry_safe (page, tmp_page, &pages, lru) { -sg_set_page (sg, page,page_size (page),0 ); +unsigned long sg_len; + + sg_len = min_t(unsigned long, page_size(page), sg_remaining); +sg_set_page (sg, page, sg_len,0 ); + sg_remaining -= sg_len; sg =sg_next (sg);list_del (&page->lru); }
Signature · 1 line
2.43.0
PATCH v9 11/14 dma-buf: system_heap: Allocate shared buffers using CoCo shared memory allocator
In reply to Aneesh Kumar K.V (Arm)The system_cc_shared heap currently allocates its backing pages using the normal system-heap order policy and changes each resulting compound page to shared state. That is unsafe when an architecture requires state changes in units larger than PAGE_SIZE: an order-0 tail is neither sufficiently aligned nor large enough to transition independently.
Use the common CoCo shared-page allocator for every backing allocation of the shared heap. Preserve the existing preferred-order search and its GFP policy:
each candidate order is passed to the common allocator as a byte request, and that allocator rounds it up when the architecture shared granule is larger.
Add __GFP_COMP for shared allocations because an order-0 candidate can be rounded into a high-order allocation. The system heap uses compound_order() and page_size() for accounting and release, so the returned allocation must retain compound-page semantics.
Calculate a rounded internal backing length but retain the original length in dma_buf::size. The preceding scatterlist-length change ensures that the rounded tail is not included in DMA mappings or other operations. This permits a 4 KiB request on a 64 KiB shared-granule system without exposing the extra 60 KiB to an importer.
--- drivers/dma-buf/heaps/system_heap.c | 121 ++++++++++++---------------- 1 file changed, 53 insertions(+), 68 deletions(-)
drivers/dma-buf/heaps/system_heap.c +53 -68
@@ -11,14 +11,13 @@*/ #include <linux/cc_platform.h> +#include <linux/cc_shared.h> #include <linux/dma-buf.h> #include <linux/dma-mapping.h> #include <linux/dma-heap.h> #include <linux/err.h> #include <linux/highmem.h> -#include <linux/mem_encrypt.h> #include <linux/mm.h> -#include <linux/set_memory.h> #include <linux/module.h> #include <linux/pgtable.h> #include <linux/scatterlist.h>
@@ -65,34 +64,6 @@ static gfp_t order_flags[] = {HIGH_ORDER_GFP, HIGH_ORDER_GFP, LOW_ORDER_GFP};static const unsigned int orders[] = {8 ,4 ,0 };#define NUM_ORDERS ARRAY_SIZE(orders) -static int system_heap_set_page_decrypted (struct page *page) -{ -unsigned long addr = (unsigned long )page_address (page); -unsigned int nr_pages =1 <<compound_order (page); -int ret; - - ret =set_memory_decrypted (addr, nr_pages); -if (ret) -pr_warn_ratelimited ("dma-buf system heap: failed to decrypt page at %p\n" , -page_address (page)); - -return ret; -} - -static int system_heap_set_page_encrypted (struct page *page) -{ -unsigned long addr = (unsigned long )page_address (page); -unsigned int nr_pages =1 <<compound_order (page); -int ret; - - ret =set_memory_encrypted (addr, nr_pages); -if (ret) -pr_warn_ratelimited ("dma-buf system heap: failed to re-encrypt page at %p, leaking memory\n" , -page_address (page)); - -return ret; -} -static int dup_sg_table (struct sg_table *from,struct sg_table *to) {struct scatterlist *sg, *new_sg;
@@ -337,6 +308,20 @@ static void system_heap_vunmap(struct dma_buf *dmabuf, struct iosys_map *map)iosys_map_clear (map); } +static void system_heap_free_page (struct page *page,bool cc_shared) +{ +struct cc_shared_pages mem; + +if (!cc_shared) { +__free_pages (page,compound_order (page)); +return ; + } + + mem.page = page; + mem.shared_size =page_size (page); +free_cc_shared_pages (&mem); +} +static void system_heap_dma_buf_release (struct dma_buf *dmabuf) {struct system_heap_buffer *buffer = dmabuf->priv;
@@ -345,19 +330,8 @@ static void system_heap_dma_buf_release(struct dma_buf *dmabuf)int i; table = &buffer->sg_table; -for_each_sgtable_sg (table, sg, i) { -struct page *page =sg_page (sg); - -/* -* Intentionally leak pages that cannot be re-encrypted -* to prevent shared memory from being reused. -*/ -if (cc_shared_buffer (buffer) && -system_heap_set_page_encrypted (page)) -continue ; - -__free_pages (page,compound_order (page)); - } +for_each_sgtable_sg (table, sg, i) +system_heap_free_page (sg_page (sg),cc_shared_buffer (buffer));sg_free_table (table);kfree (buffer); }
@@ -375,22 +349,39 @@ static const struct dma_buf_ops system_heap_buf_ops = { .release = system_heap_dma_buf_release, }; +static struct page *system_heap_alloc_order (unsigned int order, +gfp_t flags,bool cc_shared) +{ +struct cc_shared_pages mem; + +if (!cc_shared) +return alloc_pages (flags, order); + +/* The shared granule can raise the actual allocation order. */ + flags |= __GFP_COMP; +if (alloc_cc_shared_pages (flags,PAGE_SIZE << order, &mem)) +return NULL ; + +return mem.page; +} +static struct page *alloc_largest_available (unsigned long size, -unsigned int max_order) +unsigned int max_order,bool cc_shared) {struct page *page; -int i;gfp_t flags; +int i;for (i =0 ; i <NUM_ORDERS ; i++) {if (size < (PAGE_SIZE << orders[i]))continue ;if (max_order < orders[i])continue ; + flags = order_flags[i];if (mem_accounting) flags |= __GFP_ACCOUNT; - page =alloc_pages (flags, orders[i]); + page =system_heap_alloc_order (orders[i], flags, cc_shared);if (!page)continue ;return page;
@@ -405,6 +396,7 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap, {struct system_heap_buffer *buffer;DEFINE_DMA_BUF_EXPORT_INFO (exp_info); +struct cc_shared_layout layout;unsigned long size_remaining = len;unsigned long sg_remaining = len;unsigned int max_order = orders[0 ];
@@ -417,6 +409,16 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,struct page *page, *tmp_page;int i, ret = -ENOMEM ; +if (cc_shared) { +int err; + + err =cc_shared_calc_layout (len, &layout); +if (err) +return ERR_PTR (err); + + size_remaining = layout.shared_size; + } + buffer =kzalloc_obj (*buffer);if (!buffer)return ERR_PTR (-ENOMEM );
@@ -439,7 +441,8 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap, goto free_buffer; } - page =alloc_largest_available (size_remaining, max_order); + page =alloc_largest_available (size_remaining, max_order, + cc_shared);if (!page) goto free_buffer;
@@ -464,14 +467,6 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,list_del (&page->lru); } -if (cc_shared_buffer (buffer)) { -for_each_sgtable_sg (table, sg, i) { - ret =system_heap_set_page_decrypted (sg_page (sg)); -if (ret) - goto free_pages; - } - } -/* create the dmabuf */ exp_info.exp_name =dma_heap_get_name (heap); exp_info.ops = &system_heap_buf_ops;
@@ -486,22 +481,12 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,return dmabuf; free_pages: -for_each_sgtable_sg (table, sg, i) { -struct page *p =sg_page (sg); - -/* -* Intentionally leak pages that cannot be re-encrypted -* to prevent shared memory from being reused. -*/ -if (cc_shared_buffer (buffer) && -system_heap_set_page_encrypted (p)) -continue ; -__free_pages (p,compound_order (p)); - } +for_each_sgtable_sg (table, sg, i) +system_heap_free_page (sg_page (sg), cc_shared);sg_free_table (table); free_buffer:list_for_each_entry_safe (page, tmp_page, &pages, lru) -__free_pages (page,compound_order (page)); +system_heap_free_page (page, cc_shared);kfree (buffer);return ERR_PTR (ret);
Signature · 1 line
2.43.0
PATCH v9 12/14 swiotlb: Make rounded shared pool capacity allocatable
In reply to Aneesh Kumar K.V (Arm)CoCo shared memory may need to be allocated and transitioned in units larger than the requested object. Before this change, users handled the resulting capacity as follows:
User Rounded capacity reused dma-buf system heap no DMA-direct no regular GIC tables no small GIC ITTs yes, through a gen_pool early SWIOTLB pool no late SWIOTLB pool yes persistent dynamic SWIOTLB no transient dynamic SWIOTLB no, one mapping only atomic DMA pools yes, through a gen_pool restricted SWIOTLB pool no additional padding
Improve the early and persistent dynamic SWIOTLB pools. They already own and transition backing rounded to the shared granule size, and SWIOTLB is itself a suballocator. Advertise the rounded extent as slots, size the slot metadata to match. This makes the extra capacity available without reserving more backing memory.
Keep transient dynamic pools unchanged. A transient pool belongs to one DMA mapping and is destroyed when that mapping is unmapped, so its spare backing cannot satisfy a later request without changing the lifetime model.
Do not attempt the same optimization for dma-buf, DMA-direct or regular GIC objects. Those allocations have independent caller-visible sizes and lifetimes. Reusing their padding requires a shared-granule suballocator with reference counting, per-object mappings and accounting.
Note:
For the current 64 KiB CCA shared granule size, SWIOTLB pool sizes are already multiples of the 256 KiB IO_TLB segment size. Consequently, the rounding does not change any runtime values on current CCA systems. It instead makes the code express the intended invariant that pool metadata describes the complete shared-granule-aligned backing allocation.
--- kernel/dma/swiotlb.c | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-)
kernel/dma/swiotlb.c +24 -6
@@ -328,6 +328,14 @@ static inline unsigned long nr_slots(u64 val)return DIV_ROUND_UP (val,IO_TLB_SIZE ); } +static unsigned long swiotlb_align_nslabs (unsigned long nslabs) +{ +unsigned long granule_nslabs; + + granule_nslabs =cc_shared_granule_size () >>IO_TLB_SHIFT ; +return ALIGN (nslabs, granule_nslabs); +} +static void swiotlb_mark_pool_used (struct io_tlb_pool *pool) {unsigned long i;
@@ -431,11 +439,12 @@ static void add_mem_pool(struct io_tlb_mem *mem, struct io_tlb_pool *pool) }static void __init *swiotlb_memblock_alloc (unsigned long nslabs, -unsigned int flags, +unsigned long *alloc_nslabs,unsigned int flags,int (*remap)(void *tlb,unsigned long nslabs)) { +unsigned long aligned_nslabs =swiotlb_align_nslabs (nslabs); +size_t bytes = aligned_nslabs <<IO_TLB_SHIFT ;void *tlb; -size_t bytes =ALIGN (nslabs <<IO_TLB_SHIFT ,cc_shared_granule_size ());/* * By default allocate the bounce buffer memory from low memory, but
@@ -453,12 +462,13 @@ static void __init *swiotlb_memblock_alloc(unsigned long nslabs,return NULL ; } -if (remap &&remap (tlb, nslabs) <0 ) { +if (remap &&remap (tlb, aligned_nslabs) <0 ) {memblock_free (tlb, bytes);pr_warn ("%s: Failed to remap %zu bytes\n" , __func__, bytes);return NULL ; } + *alloc_nslabs = aligned_nslabs;return tlb; }
@@ -471,6 +481,7 @@ void __init swiotlb_init_remap(bool addressing_limit, unsigned int flags, {struct io_tlb_pool *mem = &io_tlb_default_mem.defpool;unsigned long nslabs; +unsigned long alloc_nslabs;unsigned int nareas;size_t alloc_size;void *tlb;
@@ -495,13 +506,14 @@ void __init swiotlb_init_remap(bool addressing_limit, unsigned int flags,swiotlb_adjust_nareas (num_possible_cpus ()); nslabs = default_nslabs; - nareas =limit_nareas (default_nareas, nslabs); -while ((tlb =swiotlb_memblock_alloc (nslabs, flags, remap)) ==NULL ) { +while ((tlb =swiotlb_memblock_alloc (nslabs, &alloc_nslabs, flags, + remap)) ==NULL ) {if (nslabs <=IO_TLB_MIN_SLABS )return ; nslabs =ALIGN (nslabs >>1 ,IO_TLB_SEGSIZE ); - nareas =limit_nareas (nareas, nslabs); } + nslabs = alloc_nslabs; + nareas =limit_nareas (default_nareas, nslabs);if (default_nslabs != nslabs) { pr_info("SWIOTLB bounce buffer size adjusted %lu -> %lu slabs",
@@ -872,6 +884,12 @@ static struct io_tlb_pool *swiotlb_alloc_pool(struct device *dev, tlb_size = nslabs <<IO_TLB_SHIFT ; } +/* Transient pools are tied to one mapping and cannot reuse padding. */ +if (mem->cc_shared && !dev) { + nslabs =swiotlb_align_nslabs (nslabs); + tlb_size = nslabs <<IO_TLB_SHIFT ; + } + slot_order =get_order (array_size (sizeof (*pool->slots), nslabs)); pool->slots = (struct io_tlb_slot *)__get_free_pages (gfp, slot_order);
Signature · 1 line
2.43.0
PATCH v9 13/14 mm: Assert CoCo shared allocations may sleep
In reply to Aneesh Kumar K.V (Arm)On platforms with memory encryption, alloc_cc_shared_pages_node() transitions the allocated memory to the shared state. set_memory_decrypted() may sleep, so the transition must run from a sleepable context.
--- mm/cc_shared.c | 3 +++ 1 file changed, 3 insertions(+)
mm/cc_shared.c +3 -0
@@ -8,6 +8,7 @@#include <linux/errno.h> #include <linux/export.h> #include <linux/gfp.h> +#include <linux/kernel.h> #include <linux/log2.h> #include <linux/mm.h> #include <linux/mem_encrypt.h>
@@ -106,6 +107,8 @@ static int __alloc_cc_shared_pages_node(int nid, gfp_t gfp,unsigned int order;int ret; +might_sleep (); + ret =cc_shared_calc_layout (requested, &layout);if (ret)return ret;
Signature · 1 line
2.43.0
PATCH v9 14/14 irqchip/gic-v3-its: Preallocate VPE L1 tables
In reply to Aneesh Kumar K.V (Arm)VPE L1 tables are allocated from the CPU-starting callback, where sleeping is not allowed. Remove the page allocation from this atomic path.
Use a blocking allocation for the boot CPU and record the resulting table order. Allocate a page of that order from the sleepable CPU hotplug prepare stage for each secondary CPU. Consume the preallocated page only when the CPU cannot inherit an existing redistributor or ITS table.
Reclaim unused preallocations after the CPU reaches the online state, and from the prepare-state teardown when CPU bring-up aborts.
--- drivers/irqchip/irq-gic-v3-its.c | 110 +++++++++++++++++++++++++++-- drivers/irqchip/irq-gic-v3.c | 4 +- include/linux/irqchip/arm-gic-v3.h | 3 +- 3 files changed, 108 insertions(+), 9 deletions(-)
drivers/irqchip/irq-gic-v3-its.c +104 -6
@@ -197,6 +197,7 @@ static DEFINE_PER_CPU(struct cpu_lpi_count, cpu_lpi_count);static LIST_HEAD (its_nodes);static DEFINE_RAW_SPINLOCK (its_lock);static struct rdists *gic_rdists; +static unsigned int vpe_l1_prealloc_order =UINT_MAX ;static struct irq_domain *its_parent;static unsigned long its_list_map;
@@ -2892,12 +2893,35 @@ static bool allocate_vpe_l2_table(int cpu, u32 id)return true; } -static int allocate_vpe_l1_table (void ) +static unsigned int vpe_l1_table_order (u64 val) +{ +unsigned int psz; +u64 npg; + +switch (FIELD_GET (GICR_VPROPBASER_4_1_PAGE_SIZE , val)) { +default : +case GIC_PAGE_SIZE_4K : + psz =SZ_4K ; +break ; +case GIC_PAGE_SIZE_16K : + psz =SZ_16K ; +break ; +case GIC_PAGE_SIZE_64K : + psz =SZ_64K ; +break ; + } + + npg =FIELD_GET (GICR_VPROPBASER_4_1_SIZE , val) +1 ; +return get_order (npg * psz); +} + +static int allocate_vpe_l1_table (bool use_prealloc) {void __iomem *vlpi_base =gic_data_rdist_vlpi_base ();u64 val, gpsz, npg, pa;unsigned int psz =SZ_64K ;unsigned int np, epp, esz; +unsigned int order;struct page *page;if (!gic_rdists->has_rvpeid)
@@ -2990,7 +3014,16 @@ static int allocate_vpe_l1_table(void)pr_debug ("np = %d, npg = %lld, psz = %d, epp = %d, esz = %d\n" , np, npg, psz, epp, esz); - page =its_alloc_pages (GFP_ATOMIC | __GFP_ZERO,get_order (np *PAGE_SIZE )); + order =get_order (np *PAGE_SIZE ); +if (use_prealloc) { +if (WARN_ON_ONCE (order != vpe_l1_prealloc_order)) +return -EINVAL ; + + page =gic_data_rdist ()->vpe_l1_prealloc; +gic_data_rdist ()->vpe_l1_prealloc =NULL ; + }else { + page =its_alloc_pages (GFP_KERNEL | __GFP_ZERO, order); + }if (!page)return -ENOMEM ;
@@ -3007,6 +3040,9 @@ static int allocate_vpe_l1_table(void) val |=GICR_VPROPBASER_4_1_VALID ; out: +if (!use_prealloc) + vpe_l1_prealloc_order =vpe_l1_table_order (val); +gicr_write_vpropbaser (val, vlpi_base +GICR_VPROPBASER );cpumask_set_cpu (smp_processor_id (),gic_data_rdist ()->vpe_table_mask);
@@ -3146,7 +3182,7 @@ static u64 its_clear_vpend_valid(void __iomem *vlpi_base, u64 clr, u64 set)return val; } -static void its_cpu_init_lpis (void ) +static void its_cpu_init_lpis (bool use_prealloc) {void __iomem *rbase =gic_data_rdist_rd_base ();struct page *pend_page;
@@ -3259,7 +3295,7 @@ static void its_cpu_init_lpis(void) val =its_clear_vpend_valid (vlpi_base,0 ,0 ); } -if (allocate_vpe_l1_table ()) { +if (allocate_vpe_l1_table (use_prealloc)) {/* * If the allocation has failed, we're in massive trouble. * Disable direct injection, and pray that no VM was
@@ -5436,7 +5472,7 @@ static int redist_disable_lpis(void)return 0 ; } -int its_cpu_init (void ) +int its_cpu_init (bool use_prealloc) {if (!list_empty (&its_nodes)) {int ret;
@@ -5445,13 +5481,66 @@ int its_cpu_init(void)if (ret)return ret; -its_cpu_init_lpis (); +its_cpu_init_lpis (use_prealloc);its_cpu_init_collections (); }return 0 ; } +static int its_vpe_l1_prepare (unsigned int cpu) +{ +struct page **prealloc; + +if (!gic_rdists->has_rvpeid || + vpe_l1_prealloc_order ==UINT_MAX || + (gic_data_rdist_cpu (cpu)->flags &RD_LOCAL_LPI_ENABLED )) +return 0 ; + + prealloc = &gic_data_rdist_cpu (cpu)->vpe_l1_prealloc; +if (*prealloc) +return 0 ; + + *prealloc =its_alloc_pages_node (cpu_to_node (cpu), +GFP_KERNEL | __GFP_ZERO, + vpe_l1_prealloc_order); +return *prealloc ?0 : -ENOMEM ; +} + +static int its_vpe_l1_cleanup (unsigned int cpu) +{ +struct page *page; + + page =xchg (&gic_data_rdist_cpu (cpu)->vpe_l1_prealloc,NULL ); +if (page) +its_free_pages (page_address (page), vpe_l1_prealloc_order); + +return 0 ; +} + +static int __init its_vpe_l1_cpuhp_init (void ) +{ +int prepare_state, state; + + state =cpuhp_setup_state_nocalls (CPUHP_BP_PREPARE_DYN , +"irqchip/arm/gicv3-vpe:prepare" , + its_vpe_l1_prepare, + its_vpe_l1_cleanup); +if (state <0 ) +return state; + prepare_state = state; + + state =cpuhp_setup_state_nocalls (CPUHP_AP_ONLINE_DYN , +"irqchip/arm/gicv3-vpe:online" , + its_vpe_l1_cleanup,NULL ); +if (state <0 ) { +cpuhp_remove_state_nocalls (prepare_state); +return state; + } + +return 0 ; +} +static void rdist_memreserve_cpuhp_cleanup_workfn (struct work_struct *work) {cpuhp_remove_state_nocalls (gic_rdists->cpuhp_memreserve_state);
@@ -5876,6 +5965,15 @@ int __init its_init(struct fwnode_handle *handle, struct rdists *rdists,if (WARN_ON (!has_v4_1 && rdists->has_rvpeid)) rdists->has_rvpeid = false; +if (rdists->has_rvpeid) { + err =its_vpe_l1_cpuhp_init (); +if (err) { + rdists->has_rvpeid = false; + rdists->has_vlpis = false; +pr_err ("ITS: Failed to prepare VPE tables, disabling GICv4 support\n" ); + } + } +if (has_v4 & rdists->has_vlpis) {const struct irq_domain_ops *sgi_ops;
drivers/irqchip/irq-gic-v3.c +2 -2
@@ -1322,7 +1322,7 @@ static int gic_starting_cpu(unsigned int cpu)gic_cpu_init ();if (gic_dist_supports_lpis ()) -its_cpu_init (); +its_cpu_init (true);return 0 ; }
@@ -2056,7 +2056,7 @@ static int __init gic_init_bases(phys_addr_t dist_phys_base,if (gic_dist_supports_lpis ()) {its_init (handle, &gic_data.rdists, gic_data.domain, dist_prio_irq); -its_cpu_init (); +its_cpu_init (false);its_lpi_memreserve_init (); }else {if (IS_ENABLED (CONFIG_ARM_GIC_V2M ))
include/linux/irqchip/arm-gic-v3.h +2 -1
@@ -621,6 +621,7 @@ struct rdists {u64 flags;cpumask_t *vpe_table_mask;void *vpe_l1_base; +struct page *vpe_l1_prealloc; }__percpu *rdist;phys_addr_t prop_table_pa;void *prop_table_va;
@@ -637,7 +638,7 @@ struct rdists {struct irq_domain ;struct fwnode_handle ;int __init its_lpi_memreserve_init (void ); -int its_cpu_init (void ); +int its_cpu_init (bool use_prealloc);int its_init (struct fwnode_handle *handle,struct rdists *rdists,struct irq_domain *domain,u8 irq_prio);int mbi_init (struct fwnode_handle *fwnode,struct irq_domain *parent);
Signature · 1 line
2.43.0
Marc Zyngier
maintainerRe: [PATCH v9 14/14] irqchip/gic-v3-its: Preallocate VPE L1 tables
Quoted 11 lines · Aneesh Kumar K.V (Arm)
VPE L1 tables are allocated from the CPU-starting callback, where sleeping is not allowed. Remove the page allocation from this atomic path.
Use a blocking allocation for the boot CPU and record the resulting table order. Allocate a page of that order from the sleepable CPU hotplug prepare stage for each secondary CPU. Consume the preallocated page only when the CPU cannot inherit an existing redistributor or ITS table.
Reclaim unused preallocations after the CPU reaches the online state, and from the prepare-state teardown when CPU bring-up aborts.
No. The way to do it is to move the ITS probing out of the non-sleepable CPU hotplug path.
I proposed a potential hack at [1] (which I find far more palatable than this proposal), but the real fix is to probe the ITSs as devices. Putting even more ugly hacks on top of the existing PoS driver is definitely not an acceptable outcome.
M.
[1] https://lore.kernel.org/all/[email protected]/
Signature · 1 line
Without deviation from the norm, progress is not possible.
[email protected]
AI reviewRe: [PATCH v9 01/14] mm: Add an allocator for CoCo shared memory
In reply to Aneesh Kumar K.V (Arm)Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] mm: invalid cc_make_private() call on cc_make_shared() failure --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] mm: invalid cc_make_private() call on cc_make_shared() failure
--
commit 8a434c0ee7399613dbf060530383d80bbc1ab7af
Author: Aneesh Kumar K.V (Arm) <[email protected]>
mm: Add an allocator for CoCo shared memory
This commit introduces a common allocator and transition helpers for confidential-computing shared memory, including alloc_cc_shared_pages(), alloc_cc_shared_pages_node(), and free_cc_shared_pages().
Quoted 6 lines
mm/cc_shared.c new file +0
-0@@ -0,0 +1,233 @@
[ ... ]
Quoted 30 lines
mm/cc_shared.c new file +30
-0+static int __alloc_cc_shared_pages_node (int nid,gfp_t gfp, +size_t requested, +struct cc_shared_pages *mem) +{ +struct cc_shared_layout layout; +struct page *page; +unsigned int order; +bool zero = gfp & __GFP_ZERO; +int ret; + + ret =cc_shared_calc_layout (requested, &layout); +if (ret) +return ret; + + order =get_order (layout.shared_size); +if (order >MAX_PAGE_ORDER ) +return -EINVAL ; +/* +* State transitions require a linear-map address and may modify memory. +* Allocate from low memory and defer requested zeroing until afterwards. +* Shared allocations have no migration support, so they must not +* be allocated with __GFP_MOVABLE. +*/ + gfp &= ~(__GFP_HIGHMEM | __GFP_ZERO | __GFP_MOVABLE); +if (nid ==NUMA_NO_NODE ) + page =alloc_pages (gfp, order); +else + page =alloc_pages_node (nid, gfp, order); +if (!page) +return -ENOMEM ;
mm/cc_shared.c line 139
Quoted 10 lines
mm/cc_shared.c new file +10
-0+ + ret =cc_make_shared (page_address (page), layout.shared_size); +if (ret) { +if (!cc_make_private (page_address (page), layout.shared_size)) +__free_pages (page, order); +else +pr_warn_ratelimited ("leaking %zu bytes with uncertain shared state\n" , + layout.shared_size); +return ret; + }
[Severity: High]
Is it safe to call cc_make_private() across the entire layout.shared_size range when cc_make_shared() fails in __alloc_cc_shared_pages_node()?
When cc_make_shared() fails via set_memory_decrypted(), the pages in the range may not have been transitioned to shared state at all, or only a prefix of the range may have been transitioned.
For example, on x86 TDX in arch/x86/mm/pat/set_memory.c and arch/x86/coco/tdx/tdx.c:
__set_memory_enc_pgtable() {
ret = x86_platform.guest.enc_status_change_prepare(addr, numpages, enc);
if (ret)
goto vmm_fail;
ret = __change_page_attr_set_clr(&cpa, 1);
...
if (ret)
return ret;
ret = x86_platform.guest.enc_status_change_finish(addr, numpages, enc);
if (ret)
goto vmm_fail;
}tdx_enc_status_change_finish() {
if (!enc && !tdx_enc_status_changed(vaddr, numpages, enc))
return -EIO;
if (enc)
atomic_long_sub(numpages, &nr_shared);
else
atomic_long_add(numpages, &nr_shared);
return 0;
}If set_memory_decrypted() (enc = false) fails with -EBUSY on mem_enc_lock or with -ENOMEM in __change_page_attr_set_clr() before tdx_enc_status_change_finish() is reached, the pages remain private and accepted in the TDX module, and nr_shared is not incremented. Calling cc_make_private() (set_memory_encrypted(), enc = true) then invokes tdx_enc_status_change_prepare() -> tdx_accept_memory() -> try_accept_one() on already-accepted private memory, which fails and jumps to vmm_fail in __set_memory_enc_pgtable(), triggering a spurious WARN_ONCE and leaking memory that was never shared.
Conversely, if tdx_enc_status_change_finish() fails during cc_make_shared() before atomic_long_add(numpages, &nr_shared), and the subsequent cc_make_private() call succeeds, tdx_enc_status_change_finish() will execute atomic_long_sub(numpages, &nr_shared), underflowing nr_shared and corrupting the accounting checked in tdx_kexec_finish().
Similarly, on arm64 pKVM in drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c, pkvm_set_memory_decrypted() shares pages one by one and stops at the first failing page, leaving the remaining pages private. Calling cc_make_private() across the full range then invokes KVM_MEM_UNSHARE on private pages, which fails with -EPERM.
Other callers in the kernel (such as dma_direct_alloc_pages(), atomic_pool_expand(), and swiotlb_init_late()) do not call set_memory_encrypted() when set_memory_decrypted() fails, and instead leak the pages directly because the transition state of the range is unknown. Should __alloc_cc_shared_pages_node() do the same here instead of calling cc_make_private()?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewRe: [PATCH v9 02/14] mm: Zero memory during shared memory transitions
In reply to Aneesh Kumar K.V (Arm)Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [Critical] x86/hyperv: premature zeroing in hv_vtom_clear_present() before transition - [High] Drivers…
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [Critical] x86/hyperv: premature zeroing in hv_vtom_clear_present() before transition
- [High] Drivers: hv: uninitialized SynIC pages in hv_alloc_page() on non-CoCo VMs
- [High] dma-pool: dirty cache lines left on linear alias by set_memory_decrypted()
- [Medium] x86/mm: set_memory_decrypted() zeroes legacy VGA VRAM/MMIO in VGA_MAP_MEM()
- [Medium] powerpc/pseries/svm: set_memory_decrypted() zeroes private page before sharing --
commit 0a47431deefcabfb66f48104fa0c06cece49f6f0
Author: Aneesh Kumar K.V (Arm) <[email protected]>
mm: Zero memory during shared memory transitions
This commit moves memory zeroing into the architecture-specific implementations of set_memory_decrypted() so each platform clears shared memory at the appropriate point in the private-to-shared transition. It also removes post-transition memset() calls from callers and keeps explicit zeroing on paths where no transition takes place.
Quoted 4 lines
arch/powerpc/platforms/pseries/svm.c +0
-0
[ ... ]
arch/powerpc/platforms/pseries/svm.c int set_memory_decrypted(unsigned long addr, int numpages) · line 66
Quoted 8 lines
arch/powerpc/platforms/pseries/svm.c +1
-0@@ -59,6 +60,7 @@ int set_memory_decrypted(unsigned long addr, int numpages)if (!PAGE_ALIGNED (addr))return -EINVAL ; +memset ((void *)addr,0 , (size_t )numpages <<PAGE_SHIFT );uv_share_page (PHYS_PFN (__pa (addr)), numpages);return 0 ;
[Severity: Medium]
Should the memset() in set_memory_decrypted() happen after uv_share_page() rather than before it?
On PowerPC pSeries Secure VMs, memory is partitioned between secure memory and normal hypervisor-accessible memory rather than shared in place. When uv_share_page() is called, the Ultravisor unmaps the secure page and the hypervisor sets pvt->skip_page_out = true in kvmppc_share_page() before allocating a new normal page and mapping it into the guest:
arch/powerpc/kvm/book3s_hv_uvmem.c:kvmppc_share_page() {
if (kvmppc_gfn_is_uvmem_pfn(gfn, kvm, &uvmem_pfn)) {
uvmem_page = pfn_to_page(uvmem_pfn);
pvt = uvmem_page->zone_device_data;
pvt->skip_page_out = true;
...
}Zeroing addr before uv_share_page() writes zeros to the private secure page that is immediately unmapped and discarded (and faults in a secure page first if one was not yet populated), instead of zeroing the shared mapping after the transition completes.
[ ... ]
Quoted 5 lines
arch/x86/hyperv/ivm.c +0
-0
arch/x86/hyperv/ivm.c static int hv_mark_gpa_visibility(u16 count, const u64 pfn[], · line 763
Quoted 9 lines
arch/x86/hyperv/ivm.c +4
-0@@ -755,6 +755,10 @@ static int hv_mark_gpa_visibility(u16 count, const u64 pfn[],*/ static int hv_vtom_clear_present (unsigned long kbuffer,int pagecount,bool enc) { +if (!enc) +memset ((void *)kbuffer,0 , + (size_t )pagecount <<PAGE_SHIFT ); +return set_memory_np (kbuffer, pagecount); }
[Severity: Critical]
As reported by Sashiko on RFC v8 [1], doesn't zeroing kbuffer in hv_vtom_clear_present() clear the private mapping before the transition to shared completes, leaving the final shared mapping unzeroed?
In hv_vtom_init(), hv_vtom_clear_present() is registered as x86_platform.guest.enc_status_change_prepare, while hv_vtom_set_host_visibility() is registered as x86_platform.guest.enc_status_change_finish.
When set_memory_decrypted() runs on Hyper-V Isolation VMs using vTOM or a paravisor, __set_memory_enc_pgtable() invokes the callbacks in this order:
__set_memory_enc_pgtable()
-> hv_vtom_clear_present() (prepare: kbuffer is still private) -> __change_page_attr_set_clr() (updates PTEs with shared_gpa_boundary) -> hv_vtom_set_host_visibility() (finish: marks GPA host-visible and
restores _PAGE_PRESENT via set_memory_p())
Because memset() runs in hv_vtom_clear_present() while kbuffer still maps the encrypted/private GPA below ms_hyperv.shared_gpa_boundary, the shared mapping above vTOM is never zeroed after hv_vtom_set_host_visibility() makes the pages host-visible and present again. With the post-transition memset() calls removed from callers such as vmbus_connect(), hv_alloc_page(), dma_direct_alloc(), dma_direct_alloc_pages(), and __alloc_cc_shared_pages_node(), shared buffers on vTOM VMs will contain ciphertext or uninitialized data instead of zeros.
Should this memset() be moved to the end of hv_vtom_set_host_visibility() after set_memory_p() succeeds?
[ ... ]
Quoted 4 lines
arch/x86/mm/mem_encrypt_amd.c +0
-0
[ ... ]
arch/x86/mm/mem_encrypt_amd.c static int amd_enc_status_change_finish(unsigned long vaddr, int npages, bool en · line 316
Quoted 9 lines
arch/x86/mm/mem_encrypt_amd.c +3
-0@@ -308,6 +309,9 @@ static int amd_enc_status_change_finish(unsigned long vaddr, int npages, bool enif (!cc_platform_has (CC_ATTR_HOST_MEM_ENCRYPT ))enc_dec_hypercall (vaddr, npages <<PAGE_SHIFT , enc); +if (!enc) +memset ((void *)vaddr,0 , (size_t )npages <<PAGE_SHIFT ); +return 0 ; }
[Severity: Medium]
What happens during vgacon_startup() when VGA_MAP_MEM() calls set_memory_decrypted() on the legacy VGA video memory range?
In arch/x86/include/asm/vga.h, VGA_MAP_MEM() calls set_memory_decrypted() on the direct-map address of legacy VGA memory (0xb8000 or 0xb0000):
#define VGA_MAP_MEM(x, s) \
({ \
unsigned long start = (unsigned long)phys_to_virt(x); \
\
if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)) \
set_memory_decrypted(start, (s) >> PAGE_SHIFT); \
\
start; \
})During console initialization, con_init() -> vgacon_startup() calls VGA_MAP_MEM(vga_vram_base, vga_vram_size) before probing for VGA hardware and before vgacon_save_screen() saves the pre-boot screen contents.
With amd_enc_status_change_finish() and tdx_enc_status_change_finish() now unconditionally calling memset() on !enc:
1. On AMD SME/SEV, set_memory_decrypted() wipes the 32 KiB VGA text buffer before vgacon_startup() checks the buffer or saves the initial screen.
2. On AMD SEV-ES/SEV-SNP and Intel TDX guests, 0xb8000-0xbffff is an MMIO range; executing memset() (which uses rep stosb when X86_FEATURE_FSRS is set) on that shared MMIO range triggers a #VC or #VE exception that insn_decode_mmio() cannot decode, panicking the kernel at boot.
[ ... ]
Quoted 13 lines
drivers/hv/hv.c +1
-3@@ -123,12 +123,13 @@ static int hv_alloc_page(void **page, bool decrypt, const char *note)if (!*page)return -ENOMEM ; -if (decrypt) +if (decrypt) { ret =set_memory_decrypted ((unsigned long )*page,1 ); -if (ret) - goto failed;
drivers/hv/hv.c static int hv_alloc_page(void **page, bool decrypt, const char *note) · line 135
Quoted 10 lines
drivers/hv/hv.c +5
-2- -memset (*page,0 ,PAGE_SIZE ); +if (ret) + goto failed; + }else { +memset (*page,0 ,PAGE_SIZE ); + }return 0 ; failed:
[Severity: High]
As reported by Sashiko on RFC v8 [2], doesn't skipping memset() when decrypt is true leave SynIC message and event pages uninitialized on standard (non-CoCo) Hyper-V VMs?
In hv_synic_alloc(), decrypt is set to !vmbus_is_confidential():
drivers/hv/hv.c:hv_synic_alloc() {
const bool decrypt = !vmbus_is_confidential();
...
if (!ms_hyperv.paravisor_present && !hv_root_partition()) {
ret = hv_alloc_page(&hv_cpu->hyp_synic_message_page,
decrypt, "hypervisor SynIC msg");
if (ret)
goto err;
ret = hv_alloc_page(&hv_cpu->hyp_synic_event_page,
decrypt, "hypervisor SynIC event");
...
}On a standard non-confidential Hyper-V guest, vmbus_is_confidential() is false, so decrypt is true. However, on non-CoCo x86 and arm64 guests where memory encryption is inactive, set_memory_decrypted() is a no-op that returns 0 without zeroing the page. Because hv_alloc_page() allocates the page with __get_free_page(GFP_KERNEL) without __GFP_ZERO and skips the else branch when decrypt is true, hyp_synic_message_page and hyp_synic_event_page are handed to the hypervisor with uninitialized kernel memory, leaving non-zero garbage in message slot headers (msg->header.message_type != HVMSG_NONE) and event flags.
[ ... ]
Quoted 4 lines
drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c +0
-0
[ ... ]
drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c static int pkvm_set_memory_encrypted(unsigned long addr, int numpages) · line 69
Quoted 9 lines
drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c +2
-0@@ -61,6 +62,8 @@ static int pkvm_set_memory_encrypted(unsigned long addr, int numpages)static int pkvm_set_memory_decrypted (unsigned long addr,int numpages) { +memset ((void *)addr,0 , (size_t )numpages <<PAGE_SHIFT ); +return __set_memory_range (ARM_SMCCC_VENDOR_HYP_KVM_MEM_SHARE_FUNC_ID , addr, numpages); }
[Severity: High]
When atomic_pool_expand() expands a CoCo atomic DMA pool on arm64 (both here in pkvm_set_memory_decrypted() and in realm_set_memory_decrypted()), doesn't zeroing via the cacheable linear map allocate dirty cache lines after arch_dma_prep_coherent() has already cleaned the cache?
In kernel/dma/pool.c:atomic_pool_expand(), arch_dma_prep_coherent() and the non-cacheable vmap remap happen before set_memory_decrypted() is called on page_to_virt(page):
kernel/dma/pool.c:atomic_pool_expand() {
...
arch_dma_prep_coherent(page, pool_size);#ifdef CONFIG_DMA_DIRECT_REMAP
if (dma_pool->cc_shared)
prot = pgprot_decrypted(pgprot_dmacoherent(PAGE_KERNEL));
else
prot = pgprot_dmacoherent(PAGE_KERNEL);
addr = dma_common_contiguous_remap(page, pool_size, prot,
__builtin_return_address(0));
if (!addr)
goto free_page;
#else
addr = page_to_virt(page);
#endif
if (dma_pool->cc_shared) {
ret = set_memory_decrypted((unsigned long)page_to_virt(page),
1 << order);
...
}Because pkvm_set_memory_decrypted() and realm_set_memory_decrypted() execute memset() through the cacheable linear mapping page_to_virt(page) after arch_dma_prep_coherent() has already run, dirty zeroed cache lines remain in the CPU data cache for the linear alias while consumers of the atomic pool access the buffer through the non-cacheable vmap alias addr or via device DMA. If those dirty cache lines are later evicted, won't they overwrite data written via the non-cacheable mapping or by DMA?
[1] https://lore.kernel.org/r/[email protected]
[2] https://lore.kernel.org/r/[email protected]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewRe: [PATCH v9 06/14] dma-pool: Allocate CoCo atomic pools using CoCo shared memory allocator
In reply to Aneesh Kumar K.V (Arm)Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] dma-pool: cc_make_shared() runs after arch_dma_prep_coherent() --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] dma-pool: cc_make_shared() runs after arch_dma_prep_coherent()
--
commit daae4fcc15a00bc83c4081ef4b27786a7f224537
Author: Aneesh Kumar K.V (Arm) <[email protected]>
dma-pool: Allocate CoCo atomic pools using CoCo shared memory allocator
This commit updates atomic_pool_expand() to allocate confidential computing shared atomic DMA pools using the cc_shared layout and transition helpers (cc_shared_calc_layout(), cc_make_shared(), and cc_make_private()), enforcing shared granule size alignment and minimum allocation order.
Quoted 4 lines
kernel/dma/pool.c +0
-0
[ ... ]
kernel/dma/pool.c static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size, · line 145
Quoted 7 lines
kernel/dma/pool.c +1
-2@@ -126,8 +142,7 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size,* shrink so no re-encryption occurs in dma_direct_free(). */ if (dma_pool->cc_shared) { - ret =set_memory_decrypted ((unsigned long )page_to_virt (page), -1 << order); + ret =cc_make_shared (page_to_virt (page), pool_size);
[Severity: High]
Does calling cc_make_shared(page_to_virt(page), pool_size) after arch_dma_prep_coherent() and dma_common_contiguous_remap() leave dirty cache lines on the cacheable linear mapping alias when CONFIG_DMA_DIRECT_REMAP is enabled?
In atomic_pool_expand(), arch_dma_prep_coherent() and the vmap remapping run first:
kernel/dma/pool.c:atomic_pool_expand() {
...
arch_dma_prep_coherent(page, pool_size);#ifdef CONFIG_DMA_DIRECT_REMAP
if (dma_pool->cc_shared)
prot = pgprot_decrypted(pgprot_dmacoherent(PAGE_KERNEL));
else
prot = pgprot_dmacoherent(PAGE_KERNEL);
addr = dma_common_contiguous_remap(page, pool_size, prot,
__builtin_return_address(0));
if (!addr)
goto free_page;
#else
addr = page_to_virt(page);
#endif
if (dma_pool->cc_shared) {
ret = cc_make_shared(page_to_virt(page), pool_size);
...
}Because set_memory_decrypted() (in commit 0a47431deefc ("mm: Zero memory during shared memory transitions")) zeroes the range through the cacheable linear map address passed to it:
cc_make_shared()
-> set_memory_decrypted()
-> realm_set_memory_decrypted() / pkvm_set_memory_decrypted()
-> memset((void *)addr, 0, (size_t)numpages << PAGE_SHIFT);performing this transition after arch_dma_prep_coherent() has already cleaned the linear map alias dirties the CPU data cache for page_to_virt(page) with zeros without a subsequent cache clean (and on Arm CCA, cleans the protected physical address alias before the RIPAS transition rather than the shared physical address alias after zeroing). Those dirty cache lines on the linear mapping can later be evicted to the Point of Coherency and overwrite live DMA buffers accessed via the non-cacheable vmap alias at addr.
In contrast, dma_direct_alloc() transitions the pages before calling arch_dma_prep_coherent() and dma_common_contiguous_remap(). Should atomic_pool_expand() similarly call cc_make_shared() before arch_dma_prep_coherent() and dma_common_contiguous_remap()?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
[email protected]
AI reviewRe: [PATCH v9 08/14] swiotlb: Align shared IO TLB pools to the shared granule size
In reply to Aneesh Kumar K.V (Arm)Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] swiotlb: premature linux/set_memory.h removal breaks restricted pool build --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] swiotlb: premature linux/set_memory.h removal breaks restricted pool build --
commit 604798053e9de98cc147fbbd212cc3b2c9896b0e
Author: Aneesh Kumar K.V (Arm) <[email protected]>
swiotlb: Align shared IO TLB pools to the shared granule size
This commit aligns and sizes the SWIOTLB pool allocations to the common CoCo shared granule size and replaces the default and dynamic pool set_memory_*() calls with cc_make_shared() and cc_make_private().
Quoted 13 lines
kernel/dma/swiotlb.c +1
-0@@ -22,6 +22,7 @@#include <linux/cache.h> #include <linux/cc_platform.h> +#include <linux/cc_shared.h> #include <linux/ctype.h> #include <linux/debugfs.h> #include <linux/dma-direct.h>
kernel/dma/swiotlb.c line 41
Quoted 4 lines
kernel/dma/swiotlb.c +0
-1@@ -38,7 +39,6 @@#include <linux/pfn.h> #include <linux/rculist.h> #include <linux/scatterlist.h> -#include <linux/set_memory.h>
[Severity: Low]
Does removing linux/set_memory.h in this commit break the build when CONFIG_DMA_RESTRICTED_POOL is enabled?
At this commit, rmem_swiotlb_device_init() in kernel/dma/swiotlb.c still calls set_memory_decrypted() directly:
kernel/dma/swiotlb.c:rmem_swiotlb_device_init() {
...
if (cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
int ret;
mem->cc_shared = true;
ret = set_memory_decrypted((unsigned long)phys_to_virt(rmem->base),
rmem->size >> PAGE_SHIFT);
...
}That caller is not converted to cc_make_shared() until the subsequent commit ("swiotlb: Reject misaligned restricted DMA pools for CoCo guests").
Because none of the remaining headers included in kernel/dma/swiotlb.c pull in linux/set_memory.h, architectures without CONFIG_ARCH_HAS_MEM_ENCRYPT lose the static inline stub for set_memory_decrypted() from include/linux/set_memory.h, and x86 with CONFIG_ARCH_HAS_MEM_ENCRYPT=y loses its declaration from arch/x86/include/asm/set_memory.h, resulting in an implicit function declaration error during git bisect.
Should the removal of linux/set_memory.h be deferred to the next patch where rmem_swiotlb_device_init() is converted to cc_make_shared()?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
[email protected]
AI reviewRe: [PATCH v9 14/14] irqchip/gic-v3-its: Preallocate VPE L1 tables
In reply to Aneesh Kumar K.V (Arm)Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] irqchip/gic-v3-its: order mismatch in allocate_vpe_l1_table() on ITS inherit - [Medium]…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] irqchip/gic-v3-its: order mismatch in allocate_vpe_l1_table() on ITS inherit
- [Medium] irqchip/gic-v3-its: memory leak of vpe_table_mask in allocate_vpe_l1_table() --
commit d29e0b57c45efd854666ff7af1f84a27011e992c
Author: Aneesh Kumar K.V (Arm) <[email protected]>
irqchip/gic-v3-its: Preallocate VPE L1 tables
This commit removes the GFP_ATOMIC VPE L1 table page allocation from the CPU-starting callback by using a blocking allocation on the boot CPU, recording the table order, and preallocating pages for secondary CPUs in the sleepable CPU hotplug prepare stage.
Quoted 4 lines
drivers/irqchip/irq-gic-v3-its.c +0
-0
[ ... ]
Quoted 7 lines
drivers/irqchip/irq-gic-v3-its.c +2
-1@@ -2990,7 +3014,16 @@ static int allocate_vpe_l1_table(void)pr_debug ("np = %d, npg = %lld, psz = %d, epp = %d, esz = %d\n" , np, npg, psz, epp, esz); - page =its_alloc_pages (GFP_ATOMIC | __GFP_ZERO,get_order (np *PAGE_SIZE )); + order =get_order (np *PAGE_SIZE ); +if (use_prealloc) {
drivers/irqchip/irq-gic-v3-its.c static int allocate_vpe_l1_table(void) · line 3028
Quoted 10 lines
drivers/irqchip/irq-gic-v3-its.c +8
-0+if (WARN_ON_ONCE (order != vpe_l1_prealloc_order)) +return -EINVAL ; + + page =gic_data_rdist ()->vpe_l1_prealloc; +gic_data_rdist ()->vpe_l1_prealloc =NULL ; + }else { + page =its_alloc_pages (GFP_KERNEL | __GFP_ZERO, order); + }if (!page)return -ENOMEM ;
[Severity: Medium]
Does this leak gic_data_rdist()->vpe_table_mask on these error returns?
Earlier in allocate_vpe_l1_table(), when inherit_vpe_l1_table_from_rd() does not find an existing table to inherit, vpe_table_mask is allocated:
gic_data_rdist()->vpe_table_mask = kzalloc_obj(cpumask_t, GFP_ATOMIC); if (!gic_data_rdist()->vpe_table_mask) return -ENOMEM;
If inherit_vpe_l1_table_from_its() also does not find a table to inherit and allocate_vpe_l1_table() subsequently fails because order != vpe_l1_prealloc_order or page is NULL, it returns -EINVAL or -ENOMEM without freeing gic_data_rdist()->vpe_table_mask or clearing the pointer.
drivers/irqchip/irq-gic-v3-its.c static int allocate_vpe_l1_table(void) · line 3044
Quoted 6 lines
drivers/irqchip/irq-gic-v3-its.c +2
-0@@ -3007,6 +3040,9 @@ static int allocate_vpe_l1_table(void) val |=GICR_VPROPBASER_4_1_VALID ; out: +if (!use_prealloc) + vpe_l1_prealloc_order =vpe_l1_table_order (val);
[Severity: High]
Can vpe_l1_prealloc_order mismatch the order computed for a secondary CPU when the boot CPU inherits its VPE table from an ITS?
On the boot CPU, gic_init_bases() -> its_cpu_init(false) -> its_cpu_init_lpis(false) -> allocate_vpe_l1_table(false) calls inherit_vpe_l1_table_from_its():
val = inherit_vpe_l1_table_from_its(); if (val & GICR_VPROPBASER_4_1_VALID) goto out;
When the boot CPU redistributor shares a VPE table with an ITS in its affinity domain, this jumps to out: without probing GICR_VPROPBASER, and vpe_l1_prealloc_order is computed from the inherited GITS_BASER2 value.
However, the ITS VPE table is sized by its_parse_indirect_baser(), which only switches to a two-level indirect table when the flat table exceeds two GIC pages and GITS_BASER_INDIRECT is supported:
/* No need to enable Indirection if memory requirement < (psz*2)bytes */
if ((esz << ids) > (psz * 2)) {By contrast, when a secondary CPU in another affinity domain cannot inherit from a redistributor or an ITS, allocate_vpe_l1_table(true) probes GICR_VPROPBASER on the redistributor and enables indirection whenever the flat table exceeds a single GIC page:
if (epp < ITS_MAX_VPEID) {
int nl2;
val |= GICR_VPROPBASER_4_1_INDIRECT;For example, when the flat table is 2 * psz (or when GITS_BASER2 uses a flat table or a different probed page size than GICR_VPROPBASER), the inherited ITS table order is get_order(2 * psz) while the secondary redistributor L1 table order is get_order(psz).
When that secondary CPU comes online, wouldn't allocate_vpe_l1_table(true) hit WARN_ON_ONCE(order != vpe_l1_prealloc_order), return -EINVAL, and cause its_cpu_init_lpis() to disable GICv4 support?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
Suzuki K Poulose
reviewerRe: [PATCH v9 01/14] mm: Add an allocator for CoCo shared memory
In reply to Aneesh Kumar K.V (Arm)Quoted 12 lines · Aneesh Kumar K.V (Arm)
Confidential-computing guests may require memory shared with the host to be aligned and transitioned in units larger than
PAGE_SIZE. Several DMA users need struct page-backed allocations satisfying these requirements. Provide a common allocator instead of requiring each user to open-code this sequence.Add
alloc_cc_shared_pages()and its node-aware variant. The allocator rounds the requested size to the architecture's shared granule, allocates suitably aligned contiguous pages and transitions the complete range to shared state. It also preserves the caller's GFP policy.
Quoted 3 lines
A private-to-shared transition may alter memory contents. Mask
__GFP_ZEROfrom the underlying allocation and when requested, clear the complete transitioned range aftercc_make_shared()succeeds.
This is not true for pKVM though. It is the other way around. i.e, pages must be cleared before transition (e.g., from private to shared) to make sure the contents don't leak into the host.
Do we need to handle such cases with a pre_conversion and post_conversion hook ?
Cheers
Suzuki
Re: [PATCH v9 01/14] mm: Add an allocator for CoCo shared memory
Quoted 17 lines · Suzuki K Poulose
Quoted 12 lines · Aneesh Kumar K.V (Arm)
Confidential-computing guests may require memory shared with the host to be aligned and transitioned in units larger than
PAGE_SIZE. Several DMA users need struct page-backed allocations satisfying these requirements. Provide a common allocator instead of requiring each user to open-code this sequence.Add
alloc_cc_shared_pages()and its node-aware variant. The allocator rounds the requested size to the architecture's shared granule, allocates suitably aligned contiguous pages and transitions the complete range to shared state. It also preserves the caller's GFP policy.Quoted 3 lines
A private-to-shared transition may alter memory contents. Mask
__GFP_ZEROfrom the underlying allocation and when requested, clear the complete transitioned range aftercc_make_shared()succeeds.
Quoted 7 lines
This is not true for pKVM though. It is the other way around. i.e, pages must be cleared before transition (e.g., from private to shared) to make sure the contents don't leak into the host.
Do we need to handle such cases with a
pre_conversionandpost_conversionhook ?
Patch 2 does something similar.
-aneesh
Suzuki K Poulose
reviewerRe: [PATCH v9 01/14] mm: Add an allocator for CoCo shared memory
Quoted 23 lines · Aneesh Kumar K.V
Quoted 21 lines · Suzuki K Poulose
Quoted 12 lines · Aneesh Kumar K.V (Arm)
Confidential-computing guests may require memory shared with the host to be aligned and transitioned in units larger than
PAGE_SIZE. Several DMA users need struct page-backed allocations satisfying these requirements. Provide a common allocator instead of requiring each user to open-code this sequence.Add
alloc_cc_shared_pages()and its node-aware variant. The allocator rounds the requested size to the architecture's shared granule, allocates suitably aligned contiguous pages and transitions the complete range to shared state. It also preserves the caller's GFP policy.Quoted 3 lines
A private-to-shared transition may alter memory contents. Mask
__GFP_ZEROfrom the underlying allocation and when requested, clear the complete transitioned range aftercc_make_shared()succeeds.This is not true for pKVM though. It is the other way around. i.e, pages must be cleared before transition (e.g., from private to shared) to make sure the contents don't leak into the host.
Quoted 5 lines
Quoted 3 lines
Do we need to handle such cases with a
pre_conversionandpost_conversionhook ?Patch 2 does something similar.
Ah, yes! Thanks
Cheers
Suzuki
Quoted 2 lines
-aneesh
Re: [PATCH v9 14/14] irqchip/gic-v3-its: Preallocate VPE L1 tables
In reply to Marc ZyngierQuoted 14 lines · Marc Zyngier
Quoted 11 lines · Aneesh Kumar K.V (Arm)
VPE L1 tables are allocated from the CPU-starting callback, where sleeping is not allowed. Remove the page allocation from this atomic path.
Use a blocking allocation for the boot CPU and record the resulting table order. Allocate a page of that order from the sleepable CPU hotplug prepare stage for each secondary CPU. Consume the preallocated page only when the CPU cannot inherit an existing redistributor or ITS table.
Reclaim unused preallocations after the CPU reaches the online state, and from the prepare-state teardown when CPU bring-up aborts.
Quoted 7 lines
No. The way to do it is to move the ITS probing out of the non-sleepable CPU hotplug path.
I proposed a potential hack at [1] (which I find far more palatable than this proposal), but the real fix is to probe the ITSs as devices.
Could you share a bit more detail on what you have in mind?
Are you suggesting that we create a platform device for each ITS and initialize it through the driver's probe callback, while the rest of the GIC initialization stays in the existing early boot path?
Would that mean the main GIC is operational during early boot, while ITS-dependent features, such as MSI delivery and direct injection, become available after the ITS devices probe?
Is that the split you have in mind?
-aneesh
Re: [PATCH v9 01/14] mm: Add an allocator for CoCo shared memory
In reply to [email protected]Quoted 123 lines · [email protected] writes:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] mm: invalidcc_make_private()call oncc_make_shared()failure
--commit
8a434c0ee7399613dbf060530383d80bbc1ab7af
Author: Aneesh Kumar K.V (Arm) <[email protected]>mm: Add an allocator for CoCo shared memory
This commit introduces a common allocator and transition helpers for confidential-computing shared memory, including
alloc_cc_shared_pages(),alloc_cc_shared_pages_node(), andfree_cc_shared_pages().Quoted 6 lines
mm/cc_shared.c new file +0
-0@@ -0,0 +1,233 @@[ ... ]
Quoted 30 lines
mm/cc_shared.c new file +30
-0+static int __alloc_cc_shared_pages_node (int nid,gfp_t gfp, +size_t requested, +struct cc_shared_pages *mem) +{ +struct cc_shared_layout layout; +struct page *page; +unsigned int order; +bool zero = gfp & __GFP_ZERO; +int ret; + + ret =cc_shared_calc_layout (requested, &layout); +if (ret) +return ret; + + order =get_order (layout.shared_size); +if (order >MAX_PAGE_ORDER ) +return -EINVAL ; +/* +* State transitions require a linear-map address and may modify memory. +* Allocate from low memory and defer requested zeroing until afterwards. +* Shared allocations have no migration support, so they must not +* be allocated with __GFP_MOVABLE. +*/ + gfp &= ~(__GFP_HIGHMEM | __GFP_ZERO | __GFP_MOVABLE); +if (nid ==NUMA_NO_NODE ) + page =alloc_pages (gfp, order); +else + page =alloc_pages_node (nid, gfp, order); +if (!page) +return -ENOMEM ;mm/cc_shared.c line 139
Quoted 10 lines
mm/cc_shared.c new file +10
-0+ + ret =cc_make_shared (page_address (page), layout.shared_size); +if (ret) { +if (!cc_make_private (page_address (page), layout.shared_size)) +__free_pages (page, order); +else +pr_warn_ratelimited ("leaking %zu bytes with uncertain shared state\n" , + layout.shared_size); +return ret; + }[Severity: High]
Is it safe to callcc_make_private()across the entire layout.shared_size range whencc_make_shared()fails in__alloc_cc_shared_pages_node()?When
cc_make_shared()fails viaset_memory_decrypted(), the pages in the range may not have been transitioned to shared state at all, or only a prefix of the range may have been transitioned.For example, on x86 TDX in
arch/x86/mm/pat/set_memory.candarch/x86/coco/tdx/tdx.c:__set_memory_enc_pgtable() { ret = x86_platform.guest.enc_status_change_prepare(addr, numpages, enc); if (ret) goto vmm_fail; ret = __change_page_attr_set_clr(&cpa, 1); ... if (ret) return ret; ret = x86_platform.guest.enc_status_change_finish(addr, numpages, enc); if (ret) goto vmm_fail; }tdx_enc_status_change_finish() { if (!enc && !tdx_enc_status_changed(vaddr, numpages, enc)) return -EIO; if (enc) atomic_long_sub(numpages, &nr_shared); else atomic_long_add(numpages, &nr_shared); return 0; }If
set_memory_decrypted()(enc = false) fails with-EBUSYonmem_enc_lockor with-ENOMEMin__change_page_attr_set_clr()beforetdx_enc_status_change_finish()is reached, the pages remain private and accepted in the TDX module, andnr_sharedis not incremented. Callingcc_make_private()(set_memory_encrypted(), enc = true) then invokestdx_enc_status_change_prepare()->tdx_accept_memory()->try_accept_one()on already-accepted private memory, which fails and jumps tovmm_failin__set_memory_enc_pgtable(), triggering a spuriousWARN_ONCEand leaking memory that was never shared.Conversely, if
tdx_enc_status_change_finish()fails duringcc_make_shared()beforeatomic_long_add(numpages, &nr_shared), and the subsequentcc_make_private()call succeeds,tdx_enc_status_change_finish()will executeatomic_long_sub(numpages, &nr_shared), underflowingnr_sharedand corrupting the accounting checked intdx_kexec_finish().Similarly, on arm64 pKVM in
drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c,pkvm_set_memory_decrypted()shares pages one by one and stops at the first failing page, leaving the remaining pages private. Callingcc_make_private()across the full range then invokesKVM_MEM_UNSHAREon private pages, which fails with-EPERM.
Quoted 7 lines
Other callers in the kernel (such as
dma_direct_alloc_pages(),atomic_pool_expand(), andswiotlb_init_late()) do not callset_memory_encrypted()whenset_memory_decrypted()fails, and instead leak the pages directly because the transition state of the range is unknown. Should__alloc_cc_shared_pages_node()do the same here instead of callingcc_make_private()?
Yes, I agree that we should do this. Something like:
modified kernel/dma/swiotlb.c
@@ -748,14 +748,9 @@ static struct page *alloc_dma_pages(gfp_t gfp, size_t bytes,
vaddr = phys_to_virt(paddr);
if (cc_shared && cc_make_shared(vaddr, bytes))
- goto error;
+ /* leak pages on error */
+ return NULL;
return page;
-
-error:
- /* Intentional leak if pages cannot be encrypted again. */
- if (cc_shared && !cc_make_private(vaddr, bytes))
- __free_pages(page, order);
- return NULL;
}
/**
modified mm/cc_shared.c
@@ -133,11 +133,16 @@ static int __alloc_cc_shared_pages_node(int nid, gfp_t gfp,
ret = cc_make_shared(page_address(page), layout.shared_size); if (ret) {
- if (!cc_make_private(page_address(page), layout.shared_size))
- __free_pages(page, order);
- else
- pr_warn_ratelimited("leaking %zu bytes with uncertain shared state\n",
- layout.shared_size);
+ /*
+ * A failed transition may leave the range partially
+ * shared, with no indication of which pages changed state.
+ * Converting the whole range back to private is not safe
+ * on architectures that cannot handle pages which are
+ * already private. Leak the allocation rather than return
+ * pages with uncertain state to the allocator.
+ */
+ pr_warn_ratelimited("leaking %zu bytes with uncertain shared state\n",
+ layout.shared_size);
return ret;
}
Re: [PATCH v9 02/14] mm: Zero memory during shared memory transitions
In reply to [email protected]Quoted 8 lines · [email protected] writes:
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [Critical] x86/hyperv: premature zeroing inhv_vtom_clear_present()before transition
- [High] Drivers: hv: uninitialized SynIC pages inhv_alloc_page()on non-CoCo VMs
- [High] dma-pool: dirty cache lines left on linear alias byset_memory_decrypted()
- [Medium] x86/mm:set_memory_decrypted()zeroes legacy VGA VRAM/MMIO inVGA_MAP_MEM()
- [Medium] powerpc/pseries/svm:set_memory_decrypted()zeroes private page before sharing --
I used an LLM to review the CoCo implementations and suggest the correct sequence for clearing memory. Except on s390 and pKVM, memory must be cleared after it is converted to shared. The resulting patch is below, with comments explaining the architecture-specific differences.
This needs review and acknowledgment from the relevant architecture maintainers.
modified arch/arm64/mm/mem_encrypt.c
@@ -17,6 +17,7 @@
#include <linux/compiler.h>
#include <linux/err.h>
#include <linux/mm.h>
+#include <linux/string.h>
#include <asm/mem_encrypt.h>
@@ -42,8 +43,13 @@ EXPORT_SYMBOL_GPL(set_memory_encrypted);
int set_memory_decrypted(unsigned long addr, int numpages) {
- if (likely(!crypt_ops) || WARN_ON(!PAGE_ALIGNED(addr)))
+ if (likely(!crypt_ops)) {
+ memset((void *)addr, 0, (size_t)numpages << PAGE_SHIFT);
return 0;
+ }
+
+ if (WARN_ON(!PAGE_ALIGNED(addr)))
+ return -EINVAL;
return crypt_ops->decrypt(addr, numpages);
}
modified arch/powerpc/platforms/pseries/svm.c
@@ -54,14 +54,13 @@ int set_memory_encrypted(unsigned long addr, int numpages)
int set_memory_decrypted(unsigned long addr, int numpages) {
- if (!cc_platform_has(CC_ATTR_MEM_ENCRYPT))
- return 0;
-
if (!PAGE_ALIGNED(addr))
return -EINVAL;
+ if (cc_platform_has(CC_ATTR_MEM_ENCRYPT))
+ uv_share_page(PHYS_PFN(__pa(addr)), numpages);
+ /* Sharing can replace the secure backing; clear the final mapping. */
memset((void *)addr, 0, (size_t)numpages << PAGE_SHIFT);
- uv_share_page(PHYS_PFN(__pa(addr)), numpages);
return 0;
}
modified arch/s390/mm/init.c
@@ -130,6 +130,10 @@ int set_memory_decrypted(unsigned long vaddr, int numpages)
{
int i;
+ /*
+ * uv_set_shared() exposes existing contents to the host; see the data
+ * leakage warning in share() in asm/uv.h. Clear private data first.
+ */
memset((void *)vaddr, 0, (size_t)numpages << PAGE_SHIFT);
/* make specified pages shared (swiotlb, dma_alloca) */
modified arch/x86/coco/tdx/tdx.c
@@ -980,9 +980,6 @@ static int tdx_enc_status_change_finish(unsigned long vaddr, int numpages,
if (!enc && !tdx_enc_status_changed(vaddr, numpages, enc))
return -EIO;
- if (!enc)
- memset((void *)vaddr, 0, (size_t)numpages << PAGE_SHIFT);
-
if (enc)
atomic_long_sub(numpages, &nr_shared);
else
modified arch/x86/hyperv/ivm.c
@@ -755,10 +755,6 @@ static int hv_mark_gpa_visibility(u16 count, const u64 pfn[],
*/
static int hv_vtom_clear_present(unsigned long kbuffer, int pagecount, bool enc) {
- if (!enc)
- memset((void *)kbuffer, 0,
- (size_t)pagecount << PAGE_SHIFT);
-
return set_memory_np(kbuffer, pagecount);
}
modified arch/x86/include/asm/set_memory.h
@@ -52,6 +52,7 @@ bool set_memory_enc_stop_conversion(void);
bool set_memory_enc_stop_conversion(void);
int set_memory_encrypted(unsigned long addr, int numpages); int set_memory_decrypted(unsigned long addr, int numpages);
+int set_memory_decrypted_nozero(unsigned long addr, int numpages);
int set_memory_np_noalias(unsigned long addr, int numpages); int set_memory_nonglobal(unsigned long addr, int numpages);
modified arch/x86/include/asm/vga.h
@@ -14,7 +14,7 @@
* On the PC, we can just recalculate addresses and then
* access the videoram directly without any black magic.
* To support memory encryption however, we need to access
- * the videoram as decrypted memory.
+ * the videoram as decrypted memory without clearing its contents.
*/
#define VGA_MAP_MEM(x, s) \
@@ -22,7 +22,7 @@
unsigned long start = (unsigned long)phys_to_virt(x); \
\
if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)) \
- set_memory_decrypted(start, (s) >> PAGE_SHIFT); \
+ set_memory_decrypted_nozero(start, (s) >> PAGE_SHIFT); \
\
start; \
})
modified arch/x86/mm/mem_encrypt_amd.c
@@ -309,9 +309,6 @@ static int amd_enc_status_change_finish(unsigned long vaddr, int npages, bool en
if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
enc_dec_hypercall(vaddr, npages << PAGE_SHIFT, enc);
- if (!enc)
- memset((void *)vaddr, 0, (size_t)npages << PAGE_SHIFT);
-
return 0;
}
modified arch/x86/mm/pat/set_memory.c
@@ -2545,9 +2545,22 @@ EXPORT_SYMBOL_GPL(set_memory_encrypted);
int set_memory_decrypted(unsigned long addr, int numpages)
{
+ int ret = __set_memory_enc_dec(addr, numpages, false);
+
+ /* The finish callback must restore the shared mapping before clearing. */
+ if (!ret)
+ memset((void *)addr, 0, (size_t)numpages << PAGE_SHIFT);
+
+ return ret;
+}
+EXPORT_SYMBOL_GPL(set_memory_decrypted);
+
+/* Device memory needs a decrypted mapping without writes to its contents. */ +int set_memory_decrypted_nozero(unsigned long addr, int numpages) +{
return __set_memory_enc_dec(addr, numpages, false);
}
-EXPORT_SYMBOL_GPL(set_memory_decrypted); +EXPORT_SYMBOL_GPL(set_memory_decrypted_nozero);
int set_pages_uc(struct page *page, int numpages) {
modified drivers/firmware/arm_rmm/rsi.c
@@ -147,6 +147,7 @@ static int realm_set_memory_decrypted(unsigned long addr, int numpages)
{
int ret = __set_memory_enc_dec(addr, numpages, false);
+ /* The transition invalidates private contents; clear the shared mapping. */
if (!ret)
memset((void *)addr, 0, (size_t)numpages << PAGE_SHIFT);
modified drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c
@@ -62,6 +62,7 @@ static int pkvm_set_memory_encrypted(unsigned long addr, int numpages)
static int pkvm_set_memory_decrypted(unsigned long addr, int numpages) {
+ /* Sharing exposes the existing contents to the host; clear them first. */
memset((void *)addr, 0, (size_t)numpages << PAGE_SHIFT);
return __set_memory_range(ARM_SMCCC_VENDOR_HYP_KVM_MEM_SHARE_FUNC_ID,
modified include/linux/set_memory.h
@@ -5,6 +5,10 @@
#ifndef _LINUX_SET_MEMORY_H_
#define _LINUX_SET_MEMORY_H_
+#include <linux/string.h>
+
+#include <asm/page.h>
+
/**
* DOC: Kernel page table permissions
*
@@ -21,7 +25,8 @@
*
* When an architecture does not implement these APIs they succeed without
* doing anything, so a return value of 0 does not mean that the permissions
- * were actually changed.
+ * were actually changed. set_memory_decrypted() also clears the range,
+ * including when no encryption change is needed. It is for normal RAM only. *
* Callers that depend on the permissions being applied must ensure that the
* architecture supports the required operation for the target addresses. The
@@ -186,6 +191,7 @@ static inline int set_memory_encrypted(unsigned long addr, int numpages)
static inline int set_memory_decrypted(unsigned long addr, int numpages) {
+ memset((void *)addr, 0, (size_t)numpages << PAGE_SHIFT);
return 0;
}
#endif /* CONFIG_ARCH_HAS_MEM_ENCRYPT */
Marc Zyngier
maintainerRe: [PATCH v9 14/14] irqchip/gic-v3-its: Preallocate VPE L1 tables
In reply to Aneesh Kumar K.VQuoted 31 lines · Aneesh Kumar K.V
Quoted 14 lines · Marc Zyngier
Quoted 11 lines · Aneesh Kumar K.V (Arm)
VPE L1 tables are allocated from the CPU-starting callback, where sleeping is not allowed. Remove the page allocation from this atomic path.
Use a blocking allocation for the boot CPU and record the resulting table order. Allocate a page of that order from the sleepable CPU hotplug prepare stage for each secondary CPU. Consume the preallocated page only when the CPU cannot inherit an existing redistributor or ITS table.
Reclaim unused preallocations after the CPU reaches the online state, and from the prepare-state teardown when CPU bring-up aborts.
Quoted 7 lines
No. The way to do it is to move the ITS probing out of the non-sleepable CPU hotplug path.
I proposed a potential hack at [1] (which I find far more palatable than this proposal), but the real fix is to probe the ITSs as devices.
Could you share a bit more detail on what you have in mind?
Are you suggesting that we create a platform device for each ITS and initialize it through the driver's probe callback, while the rest of the GIC initialization stays in the existing early boot path?
Quoted 5 lines
Would that mean the main GIC is operational during early boot, while ITS-dependent features, such as MSI delivery and direct injection, become available after the ITS devices probe?
Is that the split you have in mind?
Yes. Then once this is done, all the tables become normal DMA allocations, for which there should already be adequate support.
M.
Signature · 1 line
Jazz isn't dead. It just smells funny.
Re: [PATCH v9 06/14] dma-pool: Allocate CoCo atomic pools using CoCo shared memory allocator
In reply to [email protected]Quoted 21 lines · [email protected] writes:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] dma-pool:cc_make_shared()runs afterarch_dma_prep_coherent()
--commit
daae4fcc15a00bc83c4081ef4b27786a7f224537
Author: Aneesh Kumar K.V (Arm) <[email protected]>dma-pool: Allocate CoCo atomic pools using CoCo shared memory allocator
This commit updates
atomic_pool_expand()to allocate confidential computing shared atomic DMA pools using thecc_sharedlayout and transition helpers (cc_shared_calc_layout(),cc_make_shared(), andcc_make_private()), enforcing shared granule size alignment and minimum allocation order.Quoted 4 lines
kernel/dma/pool.c +0
-0[ ... ]
Quoted 14 lines
kernel/dma/pool.c static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size, · line 145
Quoted 7 lines
kernel/dma/pool.c +1
-2@@ -126,8 +142,7 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size,* shrink so no re-encryption occurs in dma_direct_free(). */ if (dma_pool->cc_shared) { - ret =set_memory_decrypted ((unsigned long )page_to_virt (page), -1 << order); + ret =cc_make_shared (page_to_virt (page), pool_size);[Severity: High]
Does callingcc_make_shared(page_to_virt(page), pool_size)afterarch_dma_prep_coherent()anddma_common_contiguous_remap()leave dirty cache lines on the cacheable linear mapping alias whenCONFIG_DMA_DIRECT_REMAPis enabled?
This is getting fixed by
https://lore.kernel.org/all/[email protected]
-aneesh
Re: [PATCH v9 14/14] irqchip/gic-v3-its: Preallocate VPE L1 tables
In reply to Marc ZyngierQuoted 33 lines · Marc Zyngier
Quoted 31 lines · Aneesh Kumar K.V
Quoted 14 lines · Marc Zyngier
Quoted 11 lines · Aneesh Kumar K.V (Arm)
VPE L1 tables are allocated from the CPU-starting callback, where sleeping is not allowed. Remove the page allocation from this atomic path.
Use a blocking allocation for the boot CPU and record the resulting table order. Allocate a page of that order from the sleepable CPU hotplug prepare stage for each secondary CPU. Consume the preallocated page only when the CPU cannot inherit an existing redistributor or ITS table.
Reclaim unused preallocations after the CPU reaches the online state, and from the prepare-state teardown when CPU bring-up aborts.
Quoted 7 lines
No. The way to do it is to move the ITS probing out of the non-sleepable CPU hotplug path.
I proposed a potential hack at [1] (which I find far more palatable than this proposal), but the real fix is to probe the ITSs as devices.
Could you share a bit more detail on what you have in mind?
Are you suggesting that we create a platform device for each ITS and initialize it through the driver's probe callback, while the rest of the GIC initialization stays in the existing early boot path?
Quoted 9 lines
Quoted 5 lines
Would that mean the main GIC is operational during early boot, while ITS-dependent features, such as MSI delivery and direct injection, become available after the ITS devices probe?
Is that the split you have in mind?
Yes. Then once this is done, all the tables become normal DMA allocations, for which there should already be adequate support.
Thanks for confirming. Can we handle the ITS platform-device conversion and the switch to DMA allocations in a separate series?
The existing VPE L1 allocation path calls set_memory_decrypted() from the non-sleepable CPU-starting callback, even though set_memory_decrypted() can sleep. This issue predates the shared-granule allocator changes.
Since fixing this properly needs a broader ITS rework, can we handle that separately and drop the preallocation patch from this series?
-aneesh
Re: [PATCH v9 14/14] irqchip/gic-v3-its: Preallocate VPE L1 tables
Quoted 45 lines · Aneesh Kumar K.V
Quoted 33 lines · Marc Zyngier
Quoted 31 lines · Aneesh Kumar K.V
Quoted 14 lines · Marc Zyngier
Quoted 11 lines · Aneesh Kumar K.V (Arm)
VPE L1 tables are allocated from the CPU-starting callback, where sleeping is not allowed. Remove the page allocation from this atomic path.
Use a blocking allocation for the boot CPU and record the resulting table order. Allocate a page of that order from the sleepable CPU hotplug prepare stage for each secondary CPU. Consume the preallocated page only when the CPU cannot inherit an existing redistributor or ITS table.
Reclaim unused preallocations after the CPU reaches the online state, and from the prepare-state teardown when CPU bring-up aborts.
Quoted 7 lines
No. The way to do it is to move the ITS probing out of the non-sleepable CPU hotplug path.
I proposed a potential hack at [1] (which I find far more palatable than this proposal), but the real fix is to probe the ITSs as devices.
Could you share a bit more detail on what you have in mind?
Are you suggesting that we create a platform device for each ITS and initialize it through the driver's probe callback, while the rest of the GIC initialization stays in the existing early boot path?
Quoted 9 lines
Quoted 5 lines
Would that mean the main GIC is operational during early boot, while ITS-dependent features, such as MSI delivery and direct injection, become available after the ITS devices probe?
Is that the split you have in mind?
Yes. Then once this is done, all the tables become normal DMA allocations, for which there should already be adequate support.
Quoted 7 lines
Thanks for confirming. Can we handle the ITS platform-device conversion and the switch to DMA allocations in a separate series?
The existing VPE L1 allocation path calls
set_memory_decrypted()from the non-sleepable CPU-starting callback, even thoughset_memory_decrypted()can sleep. This issue predates the shared-granule allocator changes.
If I may ask, why does the existing code ends up calling set_memory_decrypt(), or reworded, why does the VPE L1 allocation path goes through the ITS specific allocation function rather than using alloc_pages() (as it was before b08e2f42e86b5) ?
Why did b08e2f42e86b5 patched allocate_vpe_l1_table() allocation and moved it to using its_alloc_pages() ?
Thanks,
Lorenzo
Quoted 5 lines
Since fixing this properly needs a broader ITS rework, can we handle that separately and drop the preallocation patch from this series?
-aneesh
Re: [PATCH v9 14/14] irqchip/gic-v3-its: Preallocate VPE L1 tables
Quoted 54 lines · Lorenzo Pieralisi
Quoted 45 lines · Aneesh Kumar K.V
Quoted 33 lines · Marc Zyngier
Quoted 31 lines · Aneesh Kumar K.V
Quoted 14 lines · Marc Zyngier
Quoted 11 lines · Aneesh Kumar K.V (Arm)
VPE L1 tables are allocated from the CPU-starting callback, where sleeping is not allowed. Remove the page allocation from this atomic path.
Use a blocking allocation for the boot CPU and record the resulting table order. Allocate a page of that order from the sleepable CPU hotplug prepare stage for each secondary CPU. Consume the preallocated page only when the CPU cannot inherit an existing redistributor or ITS table.
Reclaim unused preallocations after the CPU reaches the online state, and from the prepare-state teardown when CPU bring-up aborts.
Quoted 7 lines
No. The way to do it is to move the ITS probing out of the non-sleepable CPU hotplug path.
I proposed a potential hack at [1] (which I find far more palatable than this proposal), but the real fix is to probe the ITSs as devices.
Could you share a bit more detail on what you have in mind?
Are you suggesting that we create a platform device for each ITS and initialize it through the driver's probe callback, while the rest of the GIC initialization stays in the existing early boot path?
Quoted 9 lines
Quoted 5 lines
Would that mean the main GIC is operational during early boot, while ITS-dependent features, such as MSI delivery and direct injection, become available after the ITS devices probe?
Is that the split you have in mind?
Yes. Then once this is done, all the tables become normal DMA allocations, for which there should already be adequate support.
Quoted 7 lines
Thanks for confirming. Can we handle the ITS platform-device conversion and the switch to DMA allocations in a separate series?
The existing VPE L1 allocation path calls
set_memory_decrypted()from the non-sleepable CPU-starting callback, even thoughset_memory_decrypted()can sleep. This issue predates the shared-granule allocator changes.
Quoted 4 lines
If I may ask, why does the existing code ends up calling
set_memory_decrypt(), or reworded, why does the VPE L1 allocation path goes through the ITS specific allocation function rather than usingalloc_pages()(as it was beforeb08e2f42e86b5) ?
Because it needs to be accessible to the GIC "hardware". In this case the GIC is emulated by the hypervisor and the hypervisor for a realm can only see the unprotected memory.
Now I agree this is a little academic in practise because Linux (as a hypervisor) will not expose RVPEID - so allocate_vpe_l1_table() will early out. IIUC this would only actually be relevant in the case of nested virtualisation within a realm guest - which is a long way off if it ever happens.
Quoted 2 lines
Why did
b08e2f42e86b5patchedallocate_vpe_l1_table()allocation and moved it to usingits_alloc_pages()?
In that commit I simply changed all the allocation paths which were allocating memory to be visible to the GIC to use the new allocator. As we "know" that the GIC can only access "decrypted" memory. Admittedly that could easily change in the future - but my expectation is that it will only change with the switch to GICv5.
Of course what I missed was that this specific allocation uses GFP_ATOMIC and that set_memory_decrypted() can sleep. This wouldn't have shown up on any testing because of the early exit:
if (!gic_rdists->has_rvpeid)
return 0;Thanks,
Steve
Quoted 8 lines
Thanks,
LorenzoQuoted 5 lines
Since fixing this properly needs a broader ITS rework, can we handle that separately and drop the preallocation patch from this series?
-aneesh
Re: [PATCH v9 14/14] irqchip/gic-v3-its: Preallocate VPE L1 tables
On Mon, Nov 16, 2026 at 03:32:25PM +0000, Steven Price wrote:
[...]
Quoted 17 lines
Quoted 8 lines
Quoted 7 lines
Thanks for confirming. Can we handle the ITS platform-device conversion and the switch to DMA allocations in a separate series?
The existing VPE L1 allocation path calls
set_memory_decrypted()from the non-sleepable CPU-starting callback, even thoughset_memory_decrypted()can sleep. This issue predates the shared-granule allocator changes.Quoted 4 lines
If I may ask, why does the existing code ends up calling
set_memory_decrypt(), or reworded, why does the VPE L1 allocation path goes through the ITS specific allocation function rather than usingalloc_pages()(as it was beforeb08e2f42e86b5) ?Because it needs to be accessible to the GIC "hardware". In this case the GIC is emulated by the hypervisor and the hypervisor for a realm can only see the unprotected memory.
Quoted 5 lines
Now I agree this is a little academic in practise because Linux (as a hypervisor) will not expose RVPEID - so
allocate_vpe_l1_table()will early out. IIUC this would only actually be relevant in the case of nested virtualisation within a realm guest - which is a long way off if it ever happens.
That's what I was actually getting at.
Quoted 8 lines
Quoted 2 lines
Why did
b08e2f42e86b5patchedallocate_vpe_l1_table()allocation and moved it to usingits_alloc_pages()?In that commit I simply changed all the allocation paths which were allocating memory to be visible to the GIC to use the new allocator. As we "know" that the GIC can only access "decrypted" memory. Admittedly that could easily change in the future - but my expectation is that it will only change with the switch to GICv5.
Yes. I just wanted to understand whether, for VPE tables, this is, currently, a requirement.
Quoted 6 lines
Of course what I missed was that this specific allocation uses
GFP_ATOMICand thatset_memory_decrypted()can sleep. This wouldn't have shown up on any testing because of the early exit:if (!gic_rdists->has_rvpeid) return 0;
Understood, see above.
Thanks,
Lorenzo