diff --git a/src/audio/module_adapter/module_adapter.c b/src/audio/module_adapter/module_adapter.c index 1257d15978b9..94d0f15c7a32 100644 --- a/src/audio/module_adapter/module_adapter.c +++ b/src/audio/module_adapter/module_adapter.c @@ -73,7 +73,7 @@ __cold static struct vregion *module_adapter_dp_heap_new(const struct comp_ipc_c LOG_INF("%zu byte heap size requested in IPC for %#x", buf_size, config->id); } #endif - return vregion_create_map(&vreg_start, &buf_size); + return vregion_create_map(&vreg_start, &buf_size, 0); } __cold static @@ -130,9 +130,9 @@ struct processing_module *module_adapter_mem_alloc(const struct comp_driver *drv if (!mod_vreg) mod = sof_heap_alloc(mod_heap, flags, sizeof(*mod), 0); else if (flags & SOF_MEM_FLAG_COHERENT) - mod = vregion_alloc_coherent(mod_vreg, sizeof(*mod)); + mod = vregion_user_alloc_coherent_align(mod_vreg, sizeof(*mod), 0); else - mod = vregion_alloc(mod_vreg, sizeof(*mod)); + mod = vregion_user_alloc_align(mod_vreg, sizeof(*mod), 0); if (!mod) { comp_cl_err(drv, "failed to allocate memory for module"); @@ -150,9 +150,9 @@ struct processing_module *module_adapter_mem_alloc(const struct comp_driver *drv if (!mod_vreg) alloc = sof_heap_alloc(mod_heap, flags, sizeof(*alloc), 0); else if (flags & SOF_MEM_FLAG_COHERENT) - alloc = vregion_alloc_coherent(mod_vreg, sizeof(*alloc)); + alloc = vregion_user_alloc_coherent_align(mod_vreg, sizeof(*alloc), 0); else - alloc = vregion_alloc(mod_vreg, sizeof(*alloc)); + alloc = vregion_user_alloc_align(mod_vreg, sizeof(*alloc), 0); if (!alloc) goto ealloc; @@ -171,7 +171,7 @@ struct processing_module *module_adapter_mem_alloc(const struct comp_driver *drv * single-core configurations. */ if (mod_vreg) - dev = vregion_alloc_coherent(mod_vreg, sizeof(*dev)); + dev = vregion_user_alloc_coherent_align(mod_vreg, sizeof(*dev), 0); else dev = sof_heap_alloc(mod_heap, SOF_MEM_FLAG_COHERENT, sizeof(*dev), 0); @@ -193,7 +193,7 @@ struct processing_module *module_adapter_mem_alloc(const struct comp_driver *drv sof_heap_free(mod_heap, alloc); ealloc: if (mod_vreg) - vregion_free(mod_vreg, mod); + vregion_user_free(mod_vreg, mod); else sof_heap_free(mod_heap, mod); emod: diff --git a/src/audio/pipeline/pipeline-graph.c b/src/audio/pipeline/pipeline-graph.c index ae3eb317b000..cf6e97b23b8d 100644 --- a/src/audio/pipeline/pipeline-graph.c +++ b/src/audio/pipeline/pipeline-graph.c @@ -200,13 +200,18 @@ __cold struct pipeline *pipeline_new(struct k_heap *heap, uint32_t pipeline_id, memset(alloc, 0, sizeof(*alloc)); alloc->heap = heap; - /* Create vregion for pipeline and its modules if size info is available */ + /* + * Create vregion for pipeline and its modules if size info is available. + * With user-space LL, the IPC user threads run its interim heap. + */ if (IS_ENABLED(CONFIG_SOF_VREGIONS) && pparams && pparams->mem_data && pparams->mem_data->heap_bytes) { + uint32_t vreg_flags = IS_ENABLED(CONFIG_SOF_VREGION_USER_HEAP) ? + VREGION_FLAG_USER_HEAP : 0; size_t buf_size = pparams->mem_data->heap_bytes; uintptr_t vreg_start; - alloc->vreg = vregion_create_map(&vreg_start, &buf_size); + alloc->vreg = vregion_create_map(&vreg_start, &buf_size, vreg_flags); if (!alloc->vreg) pipe_cl_err("Failed to create pipeline vregion of %u bytes, using heap", pparams->mem_data->heap_bytes); @@ -378,7 +383,8 @@ __cold int pipeline_free(struct pipeline *p) /* now free the pipeline */ sof_ctx_free(alloc, p); - /* free alloc context and vregion */ + /* free alloc context and vregion, the modules are gone */ + vregion_user_heap_remove(alloc->vreg); if (vregion_put(alloc->vreg)) pipe_cl_warn("pipeline vregion still in use"); sof_heap_free(alloc->heap, alloc); @@ -495,9 +501,14 @@ int pipeline_complete(struct pipeline *p, struct comp_dev *source, p->source_comp = source; p->sink_comp = sink; - if (p->alloc->vreg) + if (p->alloc->vreg) { vregion_set_interim(p->alloc->vreg); + /* like a region too small for a kernel interim heap, not fatal here */ + if (vregion_user_heap_add(p->alloc->vreg) < 0) + pipe_warn(p, "no interim heap"); + } + p->status = COMP_STATE_READY; /* show heap status */ diff --git a/src/include/sof/lib/vregion.h b/src/include/sof/lib/vregion.h index eab7e42a36ff..d7d007773b46 100644 --- a/src/include/sof/lib/vregion.h +++ b/src/include/sof/lib/vregion.h @@ -43,6 +43,28 @@ enum vregion_mem_type { VREGION_MEM_TYPE_INVALID, }; +/** + * @brief The interim heap of the region is run by the user threads that use it. + * + * vregion_set_interim() then only reserves the interim range, and the kernel + * neither allocates from nor frees to that range. The users get the range + * with vregion_interim_get() and run their own allocator on it, see + * vregion_user_heap_add(). Only with CONFIG_SOF_VREGION_USER_HEAP. + */ +#define VREGION_FLAG_USER_HEAP (1U << 0) + +/** + * @brief Usage counters of a user-mode interim heap. + * + * At the start of the interim range of a region with VREGION_FLAG_USER_HEAP. + * Maintained by the user threads, so the kernel only copies them as numbers. + */ +struct vregion_user_heap_stats { + size_t allocated_bytes; /**< usable bytes allocated now */ + size_t max_allocated_bytes; /**< peak of allocated_bytes */ + unsigned int fail_count; /**< failed allocations */ +}; + #if CONFIG_SOF_VREGIONS /** @@ -64,9 +86,11 @@ struct vregion *vregion_create(size_t memsize); * @param[out] vreg_start Output pointer receiving the virtual start address of the region. * @param[in,out] vreg_size Input pointer specifying the requested size in bytes (must be non-zero); * updated on return with the actual mapped size in bytes. + * @param[in] flags VREGION_FLAG_* flags. * @return Pointer to the allocated virtual region instance, or NULL on failure. */ -__syscall struct vregion *vregion_create_map(uintptr_t *vreg_start, size_t *vreg_size); +__syscall struct vregion *vregion_create_map(uintptr_t *vreg_start, size_t *vreg_size, + uint32_t flags); /** * @brief Switch virtual region allocations to interim mode. @@ -79,6 +103,18 @@ __syscall struct vregion *vregion_create_map(uintptr_t *vreg_start, size_t *vreg */ __syscall void vregion_set_interim(struct vregion *vr); +/** + * @brief Get the interim range of a virtual region with VREGION_FLAG_USER_HEAP. + * + * @param[in] vr Pointer to the virtual region instance. + * @param[out] start Start address of the interim range (cached alias). + * @param[out] size Size of the interim range in bytes. + * @return 0 on success, -EAGAIN before vregion_set_interim(), -ENOMEM if no + * interim range was left, -EPERM if the interim heap of vr is run by + * the kernel. + */ +__syscall int vregion_interim_get(struct vregion *vr, uintptr_t *start, size_t *size); + /** * @brief Increment virtual region's user count. * @@ -213,6 +249,119 @@ bool vregion_pinned_get(struct vregion *vr); */ int vregion_pinned_put(struct vregion *vr); +#if CONFIG_SOF_VREGION_USER_HEAP + +/** + * @brief Set up the user-mode interim heap of a region. + * + * For a region with VREGION_FLAG_USER_HEAP, after vregion_set_interim(). In + * the LL or IPC user thread only: initialises the heap in the interim range + * and makes vregion_user_alloc_align() and the other vregion_user_*() + * functions use it in user mode. + * + * @param[in] vr Pointer to the virtual region instance. + * @return 0 on success or a negative error code. + */ +int vregion_user_heap_add(struct vregion *vr); + +/** + * @brief Stop using the user-mode interim heap of a region. + * + * Call before dropping the last reference that allocates from the region. + * Later frees of its interim memory go to the kernel, which refuses them. + * + * @param[in] vr Pointer to the virtual region instance. + */ +void vregion_user_heap_remove(struct vregion *vr); + +/** + * @brief Get the usage counters of the user-mode interim heap of a region. + * + * @param[in] vr Pointer to the virtual region instance. + * @param[out] stats Usage counters. + * @return 0 on success, -ENOENT if vr has no user-mode heap. + */ +int vregion_user_heap_stats_get(struct vregion *vr, struct vregion_user_heap_stats *stats); + +/** + * @brief Allocate aligned memory from a region. + * + * In user mode, from the user-mode interim heap of vr, if it has one. Else + * the same as vregion_alloc_align(). + * + * @param[in] vr Pointer to the virtual region instance. + * @param[in] size Size of memory to allocate in bytes. + * @param[in] alignment Alignment of memory to allocate in bytes. + * @return Pointer to the allocated memory, or NULL on failure. + */ +void *vregion_user_alloc_align(struct vregion *vr, size_t size, size_t alignment); + +/** + * @brief Allocate aligned coherent (uncached) memory from a region. + * + * In user mode, from the user-mode interim heap of vr, if it has one. Else + * the same as vregion_alloc_coherent_align(). + * + * @param[in] vr Pointer to the virtual region instance. + * @param[in] size Size of memory to allocate in bytes. + * @param[in] alignment Alignment of memory to allocate in bytes. + * @return Pointer to the allocated coherent memory, or NULL on failure. + */ +void *vregion_user_alloc_coherent_align(struct vregion *vr, size_t size, size_t alignment); + +/** + * @brief Free memory allocated from a region. + * + * In user mode, to the user-mode interim heap of vr, if ptr is in it. Else + * the same as vregion_free(). + * + * @param[in] vr Pointer to the virtual region instance. + * @param[in] ptr Pointer to the memory to free. + */ +void vregion_user_free(struct vregion *vr, void *ptr); + +#if CONFIG_SOF_BOOT_TEST_STANDALONE +struct sys_heap; +struct sys_mutex; + +/** + * @brief Get the allocator state of the user-mode heap of a region, for tests. + * @param[in] vr Pointer to the virtual region instance. + * @param[out] heap The heap, in the region memory, or NULL if vr has no heap. + * @param[out] lock The lock of all user-mode region heaps, in LL memory. + */ +void vregion_user_heap_test_get(struct vregion *vr, struct sys_heap **heap, + struct sys_mutex **lock); +#endif + +#else + +static inline int vregion_user_heap_add(struct vregion *vr) +{ + return 0; +} +static inline void vregion_user_heap_remove(struct vregion *vr) {} +static inline int vregion_user_heap_stats_get(struct vregion *vr, + struct vregion_user_heap_stats *stats) +{ + return -ENOENT; +} +static inline void *vregion_user_alloc_align(struct vregion *vr, size_t size, size_t alignment) +{ + return vregion_alloc_align(vr, size, alignment); +} +static inline void *vregion_user_alloc_coherent_align(struct vregion *vr, size_t size, + size_t alignment) +{ + return vregion_alloc_coherent_align(vr, size, alignment); +} +static inline void vregion_user_free(struct vregion *vr, void *ptr) +{ + vregion_free(vr, ptr); +} + +#endif /* CONFIG_SOF_VREGION_USER_HEAP */ + #include #else @@ -225,11 +374,16 @@ static inline struct vregion *vregion_create(size_t memsize) { return NULL; } -static inline struct vregion *vregion_create_map(uintptr_t *vreg_start, size_t *vreg_size) +static inline struct vregion *vregion_create_map(uintptr_t *vreg_start, size_t *vreg_size, + uint32_t flags) { return NULL; } static inline void vregion_set_interim(struct vregion *vr) {} +static inline int vregion_interim_get(struct vregion *vr, uintptr_t *start, size_t *size) +{ + return -EPERM; +} static inline struct vregion *vregion_get(struct vregion *vr) { return vr; @@ -262,6 +416,26 @@ static inline void vregion_mem_info(struct vregion *vr, size_t *size, uintptr_t if (size) *size = 0; } +static inline int vregion_user_heap_add(struct vregion *vr) +{ + return 0; +} +static inline void vregion_user_heap_remove(struct vregion *vr) {} +static inline int vregion_user_heap_stats_get(struct vregion *vr, + struct vregion_user_heap_stats *stats) +{ + return -ENOENT; +} +static inline void *vregion_user_alloc_align(struct vregion *vr, size_t size, size_t alignment) +{ + return NULL; +} +static inline void *vregion_user_alloc_coherent_align(struct vregion *vr, size_t size, + size_t alignment) +{ + return NULL; +} +static inline void vregion_user_free(struct vregion *vr, void *ptr) {} static inline bool vregion_verify_pin(struct vregion *vr) { return false; } static inline void vregion_unpin(struct vregion *vr) {} static inline bool vregion_pinned_get(struct vregion *vr) { return false; } diff --git a/src/include/sof/userspace/README.md b/src/include/sof/userspace/README.md index 5a53260dd034..8d761d338f6d 100644 --- a/src/include/sof/userspace/README.md +++ b/src/include/sof/userspace/README.md @@ -115,7 +115,7 @@ syscall by subsystem: | Subsystem | Syscalls | Declared in | Validator (`z_vrfy_`) / logic (`z_impl_`) | |-----------|----------|-------------|-------------------------------------------| | IPC | `ipc_msg_send`, `ipc_msg_list_remove`, `ipc_msg_reply`, `ipc_compound_pre_start`, `ipc_compound_post_start`, `ipc_wait_for_compound_msg`, `send_resource_notif` | `sof/ipc/msg.h`, `sof/ipc/ipc_reply.h`, `ipc4/handler.h`, `ipc4/notification.h` | scattered: `ipc/ipc-common.c`, `kernel/ipc/ipc3/helper.c`, `kernel/ipc/ipc4/handler-kernel.c`, `kernel/ipc/ipc4/notification.c` | -| Virtual regions | `vregion_create_map`, `vregion_set_interim`, `vregion_get`, `vregion_put`, `vregion_alloc_align`, `vregion_alloc_coherent_align`, `vregion_free` | `sof/lib/vregion.h` | `zephyr/syscall/vregion.c` / `zephyr/lib/vregion.c` | +| Virtual regions | `vregion_create_map`, `vregion_set_interim`, `vregion_interim_get`, `vregion_get`, `vregion_put`, `vregion_alloc_align`, `vregion_alloc_coherent_align`, `vregion_free` | `sof/lib/vregion.h` | `zephyr/syscall/vregion.c` / `zephyr/lib/vregion.c` | | DMA | `sof_dma_get`, `sof_dma_put`, `sof_dma_get_attribute`, `sof_dma_request_channel`, `sof_dma_release_channel`, `sof_dma_config`, `sof_dma_start`, `sof_dma_stop`, `sof_dma_get_status`, `sof_dma_reload`, `sof_dma_suspend`, `sof_dma_resume` | `sof/lib/sof_dma.h` | `zephyr/syscall/sof_dma.c` / `kernel/lib/dma-kernel.c` (get/put); remaining 10 are `static inline z_impl_*` in `sof/lib/sof_dma.h` | | DAI | `dai_get_device` | `sof/lib/dai-zephyr.h` | `zephyr/syscall/dai.c` / `kernel/lib/dai-kernel.c` | | CPU | `cpu_get_id` | `sof/lib/cpu.h` | `zephyr/syscall/cpu.c` / `zephyr/lib/cpu.c` | @@ -240,6 +240,23 @@ heap. A user thread that corrupts the heap can only make LL and IPC user threads `zephyr_ll_user_heap()` returns a kernel-only `struct k_heap` that is never initialised: its address only selects the LL user heap. +Each pipeline also has a virtual region (vregion) for itself and its LL modules, mapped +read-write into the LL memory domain. Allocations made before the pipeline is complete come +from the lifetime allocator of the region, whose state is kernel-only, through the `vregion_*` +syscalls. The interim heap, used after that, keeps its `sys_heap` metadata in the region, so it +runs in user mode too ([`lib/vregion_user.c`](../../../lib/vregion_user.c)). The pipeline +regions are created with `VREGION_FLAG_USER_HEAP`: `vregion_set_interim()` then only reserves +the rest of the region for the interim heap, and kernel code, including the `vregion_*` +syscalls, refuses to allocate from or free to that range and logs the caller. When the +pipeline is complete, the IPC user thread gets the range with the `vregion_interim_get()` +syscall, which only the LL and IPC user threads may call, and initialises the heap in it. The +heap header at the start of the range holds the usage counters, which telemetry reads as +numbers, and the `sys_heap` object. The user threads find the header of a region in a table +in the system user partition, under a `sys_mutex` there, so `sof_ctx_alloc()`, +`sof_ctx_free()` and the object pools allocate from the heap with no syscall, through +`vregion_user_alloc_align()` and `vregion_user_free()`. The heap is removed when the pipeline +is freed, after its modules. The kernel still runs the interim heap of the DP module regions. + The fast_get area holds the `fast_get()` copies of the LL modules, such as SRC coefficients. LL and IPC user threads get them with the `fast_get_ll()` and `fast_put_ll()` syscalls, and all users of the same data share a copy. The allocator is a bitmap of 256-byte blocks in kernel diff --git a/src/lib/CMakeLists.txt b/src/lib/CMakeLists.txt index 47e7984c952b..d858365b941a 100644 --- a/src/lib/CMakeLists.txt +++ b/src/lib/CMakeLists.txt @@ -14,5 +14,6 @@ is_zephyr(zephyr) if(zephyr) ### Zephyr ### add_local_sources(sof ${common_files}) + add_local_sources_ifdef(CONFIG_SOF_VREGION_USER_HEAP sof vregion_user.c) endif() diff --git a/src/lib/objpool.c b/src/lib/objpool.c index 9636e018d3d1..566fb9958757 100644 --- a/src/lib/objpool.c +++ b/src/lib/objpool.c @@ -44,11 +44,11 @@ static int objpool_add(struct objpool_head *head, unsigned int n, size_t size, u pobjpool = sof_heap_alloc(head->heap, flags, aligned_size + sizeof(*pobjpool), 0); else if (flags & SOF_MEM_FLAG_COHERENT) - pobjpool = vregion_alloc_coherent(head->vreg, - aligned_size + sizeof(*pobjpool)); + pobjpool = vregion_user_alloc_coherent_align(head->vreg, + aligned_size + sizeof(*pobjpool), 0); else - pobjpool = vregion_alloc(head->vreg, - aligned_size + sizeof(*pobjpool)); + pobjpool = vregion_user_alloc_align(head->vreg, + aligned_size + sizeof(*pobjpool), 0); if (!pobjpool) return -ENOMEM; @@ -164,7 +164,7 @@ void objpool_prune(struct objpool_head *head) list_item_del(next); if (head->vreg) - vregion_free(head->vreg, pool); + vregion_user_free(head->vreg, pool); else sof_heap_free(head->heap, pool); } diff --git a/src/lib/vregion_user.c b/src/lib/vregion_user.c new file mode 100644 index 000000000000..ad29b07e1817 --- /dev/null +++ b/src/lib/vregion_user.c @@ -0,0 +1,344 @@ +// SPDX-License-Identifier: BSD-3-Clause +// +// Copyright(c) 2026 Intel Corporation. + +/* + * User-mode interim heap of the virtual regions with VREGION_FLAG_USER_HEAP. + * + * The pipeline regions are mapped into the LL memory domain, and the IPC user + * threads allocate from their interim heap. The heap metadata is in the + * region memory, which LL and IPC user threads can write, so the heap runs in + * those threads, in user mode: the kernel only reserves the interim range, + * and vregion_user_heap_add() initialises the heap in it. The heap header at + * the start of the range holds the usage counters and the sys_heap object. + * + * The user threads find the header of a region in a table in the system user + * partition, which is mapped only into the LL memory domain, so DP threads + * cannot add or change entries. One sys_mutex, also in that partition, + * serialises the table and all the heaps. + */ + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +LOG_MODULE_DECLARE(vregion, CONFIG_SOF_LOG_LEVEL); + +struct vregion_user_hdr { + /* first, the kernel reads them for telemetry */ + struct vregion_user_heap_stats stats; + struct sys_heap heap; +}; + +/* the heap starts at the cache line after the header */ +#define VREGION_USER_HDR_SIZE ALIGN_UP(sizeof(struct vregion_user_hdr), PLATFORM_DCACHE_ALIGN) +/* sys_heap_init() asserts with too little memory, see interim_heap_init() */ +#define VREGION_USER_HEAP_MIN 1024 + +struct vregion_user_entry { + struct vregion *vr; + struct vregion_user_hdr *hdr; /* uncached alias */ +}; + +static APP_SYSUSER_BSS struct vregion_user_entry vregion_user_heaps[CONFIG_SOF_VREGION_USER_HEAP_COUNT]; +static APP_SYSUSER_BSS SYS_MUTEX_DEFINE(vregion_user_lock); + +/* the table entry of vr, a free entry for NULL. Call with vregion_user_lock held. */ +static struct vregion_user_entry *vregion_user_find(struct vregion *vr) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(vregion_user_heaps); i++) + if (vregion_user_heaps[i].vr == vr) + return &vregion_user_heaps[i]; + + return NULL; +} + +/* + * Whether vr may have a user-mode heap, without taking the lock, so that + * allocations from the regions without one cost no lock. That includes all + * lifetime allocations. Entries are only added and removed by the thread + * that completes and frees the pipeline of the region, not while other + * threads allocate from it. The table is in uncached memory. + */ +static bool vregion_user_listed(struct vregion *vr) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(vregion_user_heaps); i++) + if (vregion_user_heaps[i].vr == vr) + return true; + + return false; +} + +int vregion_user_heap_add(struct vregion *vr) +{ + struct vregion_user_entry *entry; + struct vregion_user_hdr *hdr; + uintptr_t start; + size_t size; + int ret; + + if (!vr) + return -EINVAL; + + /* the kernel never runs the heap on user-writable metadata */ + if (!k_is_user_context()) { + LOG_ERR("error: user heap of %p added in kernel context", (void *)vr); + return -EPERM; + } + + ret = vregion_interim_get(vr, &start, &size); + if (ret < 0) + goto out; + + if (size < VREGION_USER_HDR_SIZE + VREGION_USER_HEAP_MIN) { + ret = -ENOMEM; + goto out; + } + + /* + * The metadata is only accessed through the uncached alias. Write back + * and drop any cached lines of the range, so that none is written back + * over it later. + */ + sys_cache_data_flush_and_invd_range(UINT_TO_POINTER(start), size); + hdr = sys_cache_uncached_ptr_get((__sparse_force void __sparse_cache *)UINT_TO_POINTER(start)); + + ret = sys_mutex_lock(&vregion_user_lock, K_FOREVER); + if (ret) + goto out; + + /* reuse a stale entry of the same region */ + entry = vregion_user_find(vr); + if (!entry) + entry = vregion_user_find(NULL); + + if (entry) { + memset(&hdr->stats, 0, sizeof(hdr->stats)); + sys_heap_init(&hdr->heap, (uint8_t *)hdr + VREGION_USER_HDR_SIZE, + size - VREGION_USER_HDR_SIZE); + /* sys_heap_init() does not set these */ + hdr->heap.init_mem = (uint8_t *)hdr + VREGION_USER_HDR_SIZE; + hdr->heap.init_bytes = size - VREGION_USER_HDR_SIZE; + + entry->vr = vr; + entry->hdr = hdr; + } else { + ret = -ENOSPC; + } + + sys_mutex_unlock(&vregion_user_lock); + +out: + if (ret < 0) + LOG_ERR("error: no user heap for %p: %d", (void *)vr, ret); + + return ret; +} + +void vregion_user_heap_remove(struct vregion *vr) +{ + struct vregion_user_entry *entry; + + if (!vr || !k_is_user_context()) + return; + + if (sys_mutex_lock(&vregion_user_lock, K_FOREVER)) + return; + + entry = vregion_user_find(vr); + if (entry) { + if (entry->hdr->stats.allocated_bytes) + LOG_WRN("user heap of %p removed with %zu bytes allocated", + (void *)vr, entry->hdr->stats.allocated_bytes); + entry->vr = NULL; + entry->hdr = NULL; + } + + sys_mutex_unlock(&vregion_user_lock); +} + +int vregion_user_heap_stats_get(struct vregion *vr, struct vregion_user_heap_stats *stats) +{ + struct vregion_user_entry *entry; + int ret; + + if (!vr || !k_is_user_context()) + return -ENOENT; + + ret = sys_mutex_lock(&vregion_user_lock, K_FOREVER); + if (ret) + return ret; + + entry = vregion_user_find(vr); + if (entry) + *stats = entry->hdr->stats; + + sys_mutex_unlock(&vregion_user_lock); + + return entry ? 0 : -ENOENT; +} + +/* + * Allocate from the user-mode heap of vr. Returns the uncached alias. Clears + * @found if vr has no user-mode heap. + */ +static void *vregion_user_heap_alloc(struct vregion *vr, size_t size, size_t alignment, + bool *found) +{ + struct vregion_user_entry *entry; + struct vregion_user_hdr *hdr; + void *ptr = NULL; + + *found = false; + + if (!k_is_user_context() || !vregion_user_listed(vr)) + return NULL; + + /* + * The heap metadata is next to the allocations and both aliases are + * used, so never share a cache line between a cached allocation and + * metadata or another allocation. + */ + alignment = MAX(PLATFORM_DCACHE_ALIGN, alignment); + if (size > SIZE_MAX - PLATFORM_DCACHE_ALIGN) + return NULL; + size = ALIGN_UP(size, PLATFORM_DCACHE_ALIGN); + + if (sys_mutex_lock(&vregion_user_lock, K_FOREVER)) + return NULL; + + entry = vregion_user_find(vr); + if (entry) { + *found = true; + hdr = entry->hdr; + + ptr = sys_heap_aligned_alloc(&hdr->heap, alignment, size); + if (ptr) { + hdr->stats.allocated_bytes += sys_heap_usable_size(&hdr->heap, ptr); + hdr->stats.max_allocated_bytes = MAX(hdr->stats.max_allocated_bytes, + hdr->stats.allocated_bytes); + } else { + hdr->stats.fail_count++; + } + } + + sys_mutex_unlock(&vregion_user_lock); + + if (*found && !ptr) + LOG_WRN("user heap alloc of %zu from %p failed", size, (void *)vr); + + return ptr; +} + +void *vregion_user_alloc_align(struct vregion *vr, size_t size, size_t alignment) +{ + bool found; + void *ptr; + + if (!vr || !size) + return NULL; + + ptr = vregion_user_heap_alloc(vr, size, alignment, &found); + if (!found) + return vregion_alloc_align(vr, size, alignment); + + return ptr ? (__sparse_force void *)sys_cache_cached_ptr_get(ptr) : NULL; +} + +void *vregion_user_alloc_coherent_align(struct vregion *vr, size_t size, size_t alignment) +{ + bool found; + void *ptr; + + if (!vr || !size) + return NULL; + + /* + * No cached lines: the range is flushed when the heap is added, and + * every cached allocation when it is freed. + */ + ptr = vregion_user_heap_alloc(vr, size, alignment, &found); + if (!found) + return vregion_alloc_coherent_align(vr, size, alignment); + + return ptr; +} + +/* bounds from user-writable memory, so for user-mode checks only */ +static bool vregion_user_heap_owns(struct vregion_user_hdr *hdr, void *uncached) +{ + uintptr_t start = (uintptr_t)hdr->heap.init_mem; + uintptr_t addr = (uintptr_t)uncached; + + return addr >= start && addr - start < hdr->heap.init_bytes; +} + +/* Free ptr to the user-mode heap of vr. Returns false if ptr is not in it. */ +static bool vregion_user_heap_free(struct vregion *vr, void *ptr) +{ + struct vregion_user_entry *entry; + struct vregion_user_hdr *hdr; + void *uncached = ptr; + bool freed = false; + size_t usable; + + if (!k_is_user_context() || !vregion_user_listed(vr)) + return false; + + if (sys_cache_is_ptr_cached(ptr)) + uncached = sys_cache_uncached_ptr_get((__sparse_force void __sparse_cache *)ptr); + + if (sys_mutex_lock(&vregion_user_lock, K_FOREVER)) + /* do not pass a heap pointer to the kernel */ + return true; + + entry = vregion_user_find(vr); + if (entry && vregion_user_heap_owns(entry->hdr, uncached)) { + hdr = entry->hdr; + usable = sys_heap_usable_size(&hdr->heap, uncached); + + if (uncached != ptr) + sys_cache_data_flush_and_invd_range(ptr, usable); + + hdr->stats.allocated_bytes -= MIN(usable, hdr->stats.allocated_bytes); + sys_heap_free(&hdr->heap, uncached); + freed = true; + } + + sys_mutex_unlock(&vregion_user_lock); + + return freed; +} + +#if CONFIG_SOF_BOOT_TEST_STANDALONE +void vregion_user_heap_test_get(struct vregion *vr, struct sys_heap **heap, + struct sys_mutex **lock) +{ + struct vregion_user_entry *entry = vregion_user_find(vr); + + *heap = entry ? &entry->hdr->heap : NULL; + *lock = &vregion_user_lock; +} +#endif + +void vregion_user_free(struct vregion *vr, void *ptr) +{ + if (!vr || !ptr) + return; + + /* lifetime allocations and the regions without a user-mode heap */ + if (!vregion_user_heap_free(vr, ptr)) + vregion_free(vr, ptr); +} diff --git a/zephyr/Kconfig b/zephyr/Kconfig index 1cd530fc1d2c..58ade5941942 100644 --- a/zephyr/Kconfig +++ b/zephyr/Kconfig @@ -388,6 +388,22 @@ config SOF_VREGIONS 1) multiple pipeline static lifetime allocations. 2) runtime pipeline allocations. +config SOF_VREGION_USER_HEAP + bool + default y if SOF_VREGIONS && SOF_USERSPACE_LL + help + The interim heap of the pipeline regions, which the LL and IPC user + threads share, is run by those threads in user mode, and the kernel + only reserves the interim range. + +config SOF_VREGION_USER_HEAP_COUNT + int "Number of user-mode region heaps" + default 32 + depends on SOF_VREGION_USER_HEAP + help + How many regions, one per pipeline, can have a user-mode interim + heap at the same time. Each takes 8 bytes of LL memory. + config VIRTUAL_HEAP bool "Use virtual memory heap to allocate buffers" default y if ACE diff --git a/zephyr/include/rtos/alloc.h b/zephyr/include/rtos/alloc.h index 686c994c540f..d5a52f1ba9da 100644 --- a/zephyr/include/rtos/alloc.h +++ b/zephyr/include/rtos/alloc.h @@ -249,9 +249,9 @@ struct mod_alloc_ctx { /** * @brief Allocate memory from an allocation context. * - * When the context has an associated vregion, allocates from the vregion interim - * partition using vregion_alloc_coherent_align() (if #SOF_MEM_FLAG_COHERENT is set) - * or vregion_alloc_align(). When no vregion is attached, falls back to + * When the context has an associated vregion, allocates from the vregion + * using vregion_user_alloc_coherent_align() (if #SOF_MEM_FLAG_COHERENT is set) + * or vregion_user_alloc_align(). When no vregion is attached, falls back to * sof_heap_alloc(). * * @param[in,out] ctx Allocation context (heap + optional vregion). @@ -267,9 +267,9 @@ static inline void *sof_ctx_alloc(struct mod_alloc_ctx *ctx, uint32_t flags, return sof_heap_alloc(ctx ? ctx->heap : NULL, flags, size, alignment); if (flags & SOF_MEM_FLAG_COHERENT) - return vregion_alloc_coherent_align(ctx->vreg, size, alignment); + return vregion_user_alloc_coherent_align(ctx->vreg, size, alignment); - return vregion_alloc_align(ctx->vreg, size, alignment); + return vregion_user_alloc_align(ctx->vreg, size, alignment); } /** @@ -297,7 +297,7 @@ static inline void *sof_ctx_zalloc(struct mod_alloc_ctx *ctx, uint32_t flags, /** * @brief Free memory allocated from an allocation context. * - * If the context contains a vregion, frees via vregion_free(); otherwise delegates + * If the context contains a vregion, frees via vregion_user_free(); otherwise delegates * to sof_heap_free(). Passing a NULL pointer is safely treated as a no-op. * * @param[in,out] ctx Allocation context. @@ -309,7 +309,7 @@ static inline void sof_ctx_free(struct mod_alloc_ctx *ctx, void *ptr) return; if (ctx && ctx->vreg) - vregion_free(ctx->vreg, ptr); + vregion_user_free(ctx->vreg, ptr); else sof_heap_free(ctx ? ctx->heap : NULL, ptr); } diff --git a/zephyr/lib/vregion.c b/zephyr/lib/vregion.c index a52788f84a0a..09c6ed17647f 100644 --- a/zephyr/lib/vregion.c +++ b/zephyr/lib/vregion.c @@ -68,6 +68,13 @@ LOG_MODULE_REGISTER(vregion, CONFIG_SOF_LOG_LEVEL); * * More types can be added in the future. * + * The kernel runs the interim heap only if the region memory is kernel-only + * or mapped into one user domain, such as the domain of a DP module. With + * VREGION_FLAG_USER_HEAP, used for the pipeline regions that the LL and IPC + * user threads share, the kernel only reserves the interim range and keeps + * its bounds here. The users run their own allocator on it, see + * vregion_user.c, and the kernel neither parses nor uses the range. + * * * TODO: Pipeline/module reset() could reset the dynamic heap. */ @@ -102,8 +109,13 @@ struct vregion { /* current allocation mode */ enum vregion_mem_type type; /* LIFETIME at creation, switch to INTERIM */ + uint32_t flags; /* VREGION_FLAG_* */ + + /* interim range, set when switching to INTERIM */ + uint8_t *interim_base; + size_t interim_size; - /* interim heap - created lazily on first interim allocation */ + /* interim heap, not used with VREGION_FLAG_USER_HEAP */ struct interim_heap interim; /* interim heap */ /* lifetime heap */ @@ -134,8 +146,19 @@ static void vregion_tel_fill_info(struct vregion *vr, struct sof_tel_vregion_inf info->lifetime_size_bytes = (uint32_t)vr->lifetime.size; info->lifetime_used_bytes = (uint32_t)MIN(vr->lifetime.used, vr->lifetime.size); info->lifetime_free_count = (uint16_t)MIN(vr->lifetime.free_count, UINT16_MAX); + if (vr->type == VREGION_MEM_TYPE_INTERIM && vr->flags & VREGION_FLAG_USER_HEAP) { + /* user-writable counters at the start of the range, only copied as numbers */ + const volatile struct vregion_user_heap_stats *stats = + sys_cache_uncached_ptr_get((__sparse_force void __sparse_cache *) + vr->interim_base); + size_t allocated = MIN(stats->allocated_bytes, vr->interim_size); + + info->interim_alloc_bytes = (uint32_t)allocated; + info->interim_free_kb = (uint16_t)((vr->interim_size - allocated) >> 10); + } #if CONFIG_SYS_HEAP_RUNTIME_STATS - if (vr->type == VREGION_MEM_TYPE_INTERIM && vr->interim.heap.heap.heap) { + if (vr->type == VREGION_MEM_TYPE_INTERIM && !(vr->flags & VREGION_FLAG_USER_HEAP) && + vr->interim.heap.heap.heap) { struct sys_memory_stats stats = { 0 }; int ret = sys_heap_runtime_stats_get(&vr->interim.heap.heap, &stats); @@ -260,6 +283,9 @@ __cold struct vregion *vregion_create(size_t memsize) /* start in lifetime allocation mode */ vr->type = VREGION_MEM_TYPE_LIFETIME; + vr->flags = 0; + vr->interim_base = NULL; + vr->interim_size = 0; k_mutex_init(&vr->lock); /* The creator is the first user */ @@ -292,11 +318,16 @@ struct vregion *z_impl_vregion_get(struct vregion *vr) return vr; } -struct vregion *z_impl_vregion_create_map(uintptr_t *vreg_start, size_t *vreg_size) +struct vregion *z_impl_vregion_create_map(uintptr_t *vreg_start, size_t *vreg_size, + uint32_t flags) { if (!vreg_start || !vreg_size) return NULL; + if (flags & ~VREGION_FLAG_USER_HEAP || + (flags & VREGION_FLAG_USER_HEAP && !IS_ENABLED(CONFIG_SOF_VREGION_USER_HEAP))) + return NULL; + /* * Called as a system call, both pointers refer to user memory that * another thread can modify at any time. Read the size once and only @@ -313,6 +344,9 @@ struct vregion *z_impl_vregion_create_map(uintptr_t *vreg_start, size_t *vreg_si if (!vr) return NULL; + /* vr is not returned yet, so no other thread uses it */ + vr->flags = flags; + vregion_mem_info(vr, &size, &start); #if CONFIG_USERSPACE && CONFIG_SOF_USERSPACE_LL @@ -443,7 +477,8 @@ struct vregion *z_impl_vregion_put(struct vregion *vr) * @brief Initialize the interim heap from remaining vregion space. * * Called on first interim allocation. Creates the k_heap from all buffer - * space not yet consumed by lifetime allocations. + * space not yet consumed by lifetime allocations. With + * VREGION_FLAG_USER_HEAP only reserves that space. * * @param[in] vr Pointer to the virtual region instance. */ @@ -478,15 +513,20 @@ static void interim_heap_init(struct vregion *vr) /* cap lifetime so no more lifetime allocs can grow into interim */ vr->lifetime.size = interim_base - vr->base; - vr->interim.heap.heap.init_mem = interim_base; - vr->interim.heap.heap.init_bytes = interim_size; + vr->interim_base = interim_base; + vr->interim_size = interim_size; - k_heap_init(&vr->interim.heap, interim_base, interim_size); - /* - * Ensure the heap metadata written into interim_base on the IPC core - * is visible to DP worker cores running on other CPUs without L1 cache coherency. - */ - sys_cache_data_flush_range(interim_base, interim_size); + if (!(vr->flags & VREGION_FLAG_USER_HEAP)) { + vr->interim.heap.heap.init_mem = interim_base; + vr->interim.heap.heap.init_bytes = interim_size; + + k_heap_init(&vr->interim.heap, interim_base, interim_size); + /* + * Ensure the heap metadata written into interim_base on the IPC core + * is visible to DP worker cores running on other CPUs without L1 cache coherency. + */ + sys_cache_data_flush_range(interim_base, interim_size); + } vr->type = VREGION_MEM_TYPE_INTERIM; /* Update lifetime heap with the interim heap usage. */ @@ -507,6 +547,47 @@ void z_impl_vregion_set_interim(struct vregion *vr) k_mutex_unlock(&vr->lock); } +int z_impl_vregion_interim_get(struct vregion *vr, uintptr_t *start, size_t *size) +{ + uintptr_t base = 0; + size_t bytes = 0; + int ret = 0; + + if (!vr || !start || !size) + return -EINVAL; + + k_mutex_lock(&vr->lock, K_FOREVER); + + if (!(vr->flags & VREGION_FLAG_USER_HEAP)) { + ret = -EPERM; + } else if (vr->type == VREGION_MEM_TYPE_LIFETIME) { + ret = -EAGAIN; + } else if (vr->type != VREGION_MEM_TYPE_INTERIM) { + ret = -ENOMEM; + } else { + base = POINTER_TO_UINT(vr->interim_base); + bytes = vr->interim_size; + } + + k_mutex_unlock(&vr->lock); + + /* user memory in a system call, write it outside of the lock */ + if (!ret) { + *start = base; + *size = bytes; + } + + return ret; +} + +/* in the interim range, for either alias of ptr */ +static bool vregion_in_interim(struct vregion *vr, void *ptr) +{ + return vr->type == VREGION_MEM_TYPE_INTERIM && + ptr >= (void *)vr->interim_base && + ptr < (void *)(vr->interim_base + vr->interim_size); +} + /** * @brief Allocate memory with alignment from the virtual region dynamic heap. * @@ -612,10 +693,11 @@ void z_impl_vregion_free(struct vregion *vr, void *ptr) ptr = sys_cache_cached_ptr_get(ptr); /* Check if pointer is in interim heap (if initialized) */ - if (vr->type == VREGION_MEM_TYPE_INTERIM && - ptr >= (void *)vr->interim.heap.heap.init_mem && - ptr < (void *)((uint8_t *)vr->interim.heap.heap.init_mem + - vr->interim.heap.heap.init_bytes)) + if (vregion_in_interim(vr, ptr) && vr->flags & VREGION_FLAG_USER_HEAP) + /* the users run this heap, see vregion_user_free() */ + LOG_ERR("error: interim free %p from user heap of %p refused", + ptr, (void *)vr); + else if (vregion_in_interim(vr, ptr)) interim_free(&vr->interim, ptr); else if (ptr >= (void *)vr->lifetime.base && ptr < (void *)(vr->lifetime.base + vr->lifetime.size)) @@ -653,6 +735,13 @@ void *z_impl_vregion_alloc_align(struct vregion *vr, switch (vr->type) { case VREGION_MEM_TYPE_INTERIM: + if (vr->flags & VREGION_FLAG_USER_HEAP) { + /* the users run this heap, see vregion_user_alloc() */ + LOG_ERR("error: interim alloc of %zu from user heap of %p refused", + size, (void *)vr); + p = NULL; + break; + } p = interim_alloc(&vr->interim, size, alignment); break; case VREGION_MEM_TYPE_LIFETIME: @@ -671,7 +760,7 @@ void *z_impl_vregion_alloc_align(struct vregion *vr, LOG_DBG("lifetime alloc of %zu, used %zu, free %zu", size, vr->lifetime.used, vr->lifetime.size - vr->lifetime.used); - } else if (vr->type == VREGION_MEM_TYPE_INTERIM) { + } else if (vr->type == VREGION_MEM_TYPE_INTERIM && !(vr->flags & VREGION_FLAG_USER_HEAP)) { struct sys_memory_stats stats = {0}; sys_heap_runtime_stats_get(&vr->interim.heap.heap, &stats); diff --git a/zephyr/syscall/vregion.c b/zephyr/syscall/vregion.c index e133c876eab0..153bdf8880fa 100644 --- a/zephyr/syscall/vregion.c +++ b/zephyr/syscall/vregion.c @@ -93,13 +93,14 @@ struct vregion *z_vrfy_vregion_put(struct vregion *vr) } #include -struct vregion *z_vrfy_vregion_create_map(uintptr_t *vreg_start, size_t *vreg_size) +struct vregion *z_vrfy_vregion_create_map(uintptr_t *vreg_start, size_t *vreg_size, + uint32_t flags) { SOF_SYSCALL_CALLER_CHECK(SOF_SYSUSER_INFRA); K_OOPS(K_SYSCALL_MEMORY_WRITE(vreg_start, sizeof(*vreg_start))); K_OOPS(K_SYSCALL_MEMORY_WRITE(vreg_size, sizeof(*vreg_size))); - return z_impl_vregion_create_map(vreg_start, vreg_size); + return z_impl_vregion_create_map(vreg_start, vreg_size, flags); } #include @@ -113,3 +114,22 @@ void z_vrfy_vregion_set_interim(struct vregion *vr) } } #include + +int z_vrfy_vregion_interim_get(struct vregion *vr, uintptr_t *start, size_t *size) +{ + int ret; + + SOF_SYSCALL_CALLER_CHECK(SOF_SYSUSER_INFRA); + + K_OOPS(K_SYSCALL_MEMORY_WRITE(start, sizeof(*start))); + K_OOPS(K_SYSCALL_MEMORY_WRITE(size, sizeof(*size))); + + if (!vregion_verify_pin(vr)) + return -EINVAL; + + ret = z_impl_vregion_interim_get(vr, start, size); + vregion_unpin(vr); + + return ret; +} +#include diff --git a/zephyr/test/userspace/README.md b/zephyr/test/userspace/README.md index 78cefadb76f9..dfc0195de268 100644 --- a/zephyr/test/userspace/README.md +++ b/zephyr/test/userspace/README.md @@ -29,6 +29,10 @@ Available tests: without stale data, only the LL and IPC user threads may get copies of data they can read, and LL modules fall back to a private copy when the area is full. + - Also tests the user-mode interim heap of the pipeline regions: + the IPC user thread allocates from it, kernel code refuses to use + the interim range, only the LL and IPC user threads get the range, + and a user thread corrupting the heap metadata only faults itself. Building for Intel Panther Lake: ./scripts/xtensa-build-zephyr.py --cmake-args=-DCONFIG_SOF_BOOT_TEST_STANDALONE=y \ diff --git a/zephyr/test/userspace/test_ll_user_heap.c b/zephyr/test/userspace/test_ll_user_heap.c index 906337b5cef3..d40ba3c10c8e 100644 --- a/zephyr/test/userspace/test_ll_user_heap.c +++ b/zephyr/test/userspace/test_ll_user_heap.c @@ -15,6 +15,11 @@ * without stale data, only the LL and IPC user threads may make the calls, * and kernel code does not release LL copies with fast_put(). LL modules * fall back to a private copy when the area is full. + * + * Tests for the user-mode interim heap of the pipeline regions: the IPC + * user thread allocates from it without system calls, kernel code refuses + * to use the interim range, only the LL and IPC user threads get the range, + * and a user thread that corrupts the heap metadata can only fault itself. */ #include @@ -535,6 +540,286 @@ ZTEST_SUITE(userspace_ll_fast_get, ll_fast_get_predicate, ll_fast_get_setup, #endif /* HAVE_LL_FAST_GET_COPIES */ +#if CONFIG_SOF_VREGION_USER_HEAP +#define VREG_PAGES 3 +/* lifetime allocation made before the switch to interim allocations */ +#define VREG_LIFETIME 100 + +K_APP_BMEM(ll_user_heap_test_part) static struct vregion *test_vreg; +K_APP_BMEM(ll_user_heap_test_part) static int vheap_ret; +K_APP_BMEM(ll_user_heap_test_part) static struct vregion_user_heap_stats vheap_stats; + +enum vregion_heap_test_case { + /* set up the user-mode heap, result in vheap_ret */ + VHEAP_ADD, + /* remove the user-mode heap */ + VHEAP_REMOVE, + /* allocate, check and free memory */ + VHEAP_ALLOC_FREE, + /* allocate and keep the memory in user_ptr */ + VHEAP_ALLOC_KEEP, + /* free user_ptr */ + VHEAP_FREE_KEPT, + /* get the usage counters into vheap_stats */ + VHEAP_STATS, + /* overwrite the heap header with user_hdr_value */ + VHEAP_CORRUPT, + /* allocate from the corrupted heap */ + VHEAP_ALLOC_CORRUPTED, + /* get the interim range */ + VHEAP_INTERIM_GET, +}; + +static void check_vheap_alloc(bool coherent, size_t bytes, size_t align) +{ + struct vregion_user_heap_stats before, after; + uintptr_t start, addr; + uint8_t *ptr; + size_t size; + + zassert_ok(vregion_interim_get(test_vreg, &start, &size)); + zassert_ok(vregion_user_heap_stats_get(test_vreg, &before)); + + if (coherent) + ptr = vregion_user_alloc_coherent_align(test_vreg, bytes, align); + else + ptr = vregion_user_alloc_align(test_vreg, bytes, align); + zassert_not_null(ptr); + zassert_equal((uintptr_t)ptr % MAX(align, PLATFORM_DCACHE_ALIGN), 0, "%p misaligned", + ptr); + zassert_equal(sys_cache_is_ptr_cached(ptr), !coherent); + + /* in the interim range */ + addr = (uintptr_t)ptr; + if (coherent) + addr = (uintptr_t)sys_cache_cached_ptr_get(ptr); + zassert_true(addr >= start && addr + bytes <= start + size, "%p not in interim", ptr); + memset(ptr, 0x5a, bytes); + + zassert_ok(vregion_user_heap_stats_get(test_vreg, &after)); + zassert_true(after.allocated_bytes >= before.allocated_bytes + bytes); + + vregion_user_free(test_vreg, ptr); + + zassert_ok(vregion_user_heap_stats_get(test_vreg, &after)); + zassert_equal(after.allocated_bytes, before.allocated_bytes); +} + +static void vheap_user_function(void *p1, void *p2, void *p3) +{ + enum vregion_heap_test_case test_case = (enum vregion_heap_test_case)(uintptr_t)p1; + uintptr_t start; + size_t size; + int i; + + zassert_true(k_is_user_context(), "isn't user"); + + switch (test_case) { + case VHEAP_ADD: + vheap_ret = vregion_user_heap_add(test_vreg); + return; + case VHEAP_REMOVE: + vregion_user_heap_remove(test_vreg); + return; + case VHEAP_ALLOC_FREE: + check_vheap_alloc(true, 100, 0); + check_vheap_alloc(false, 100, 256); + check_vheap_alloc(false, 3000, 4096); + return; + case VHEAP_ALLOC_KEEP: + user_ptr = vregion_user_alloc_align(test_vreg, 64, 0); + zassert_not_null(user_ptr); + return; + case VHEAP_FREE_KEPT: + vregion_user_free(test_vreg, user_ptr); + user_ptr = NULL; + return; + case VHEAP_STATS: + vheap_ret = vregion_user_heap_stats_get(test_vreg, &vheap_stats); + return; + case VHEAP_CORRUPT: + /* the heap metadata is user-writable by design */ + for (i = 0; i < HDR_WORDS; i++) + user_hdr[i] = user_hdr_value; + return; + case VHEAP_ALLOC_CORRUPTED: + /* may fault, and may also return garbage */ + (void)vregion_user_alloc_align(test_vreg, 64, 0); + return; + case VHEAP_INTERIM_GET: + (void)vregion_interim_get(test_vreg, &start, &size); + break; + default: + zassert_unreachable("unknown test case"); + } + + zassert_unreachable("user thread did not fault"); +} + +static void run_vheap_case(enum vregion_heap_test_case test_case, bool infra, + bool fault_allowed) +{ + run_user(vheap_user_function, test_case, infra, fault_allowed); +} + +/* a pipeline region with a lifetime allocation, mapped into the LL domain */ +static struct vregion *vheap_vreg_create(uint32_t flags, bool interim) +{ + size_t size = VREG_PAGES * CONFIG_MM_DRV_PAGE_SIZE; + struct vregion *vr; + uintptr_t start; + + vr = z_impl_vregion_create_map(&start, &size, flags); + zassert_not_null(vr); + zassert_not_null(vregion_alloc(vr, VREG_LIFETIME)); + + if (interim) + vregion_set_interim(vr); + + return vr; +} + +static void vheap_vreg_destroy(struct vregion *vr) +{ + zassert_is_null(vregion_put(vr)); +} + +ZTEST(userspace_vregion_user_heap, user_alloc_free) +{ + test_vreg = vheap_vreg_create(VREGION_FLAG_USER_HEAP, true); + + run_vheap_case(VHEAP_ADD, true, false); + zassert_ok(vheap_ret); + run_vheap_case(VHEAP_ALLOC_FREE, true, false); + + /* the heap is gone with the region */ + run_vheap_case(VHEAP_REMOVE, true, false); + run_vheap_case(VHEAP_STATS, true, false); + zassert_equal(vheap_ret, -ENOENT); + + vheap_vreg_destroy(test_vreg); +} + +ZTEST(userspace_vregion_user_heap, lifetime_before_interim) +{ + uintptr_t start; + size_t size; + + test_vreg = vheap_vreg_create(VREGION_FLAG_USER_HEAP, false); + + /* lifetime allocations still go to the kernel */ + zassert_equal(z_impl_vregion_interim_get(test_vreg, &start, &size), -EAGAIN); + run_vheap_case(VHEAP_ADD, true, false); + zassert_equal(vheap_ret, -EAGAIN); + run_vheap_case(VHEAP_ALLOC_KEEP, true, false); + run_vheap_case(VHEAP_FREE_KEPT, true, false); + + vheap_vreg_destroy(test_vreg); + + /* the kernel runs the interim heap of the other regions */ + test_vreg = vheap_vreg_create(0, true); + zassert_equal(z_impl_vregion_interim_get(test_vreg, &start, &size), -EPERM); + run_vheap_case(VHEAP_ADD, true, false); + zassert_equal(vheap_ret, -EPERM); + run_vheap_case(VHEAP_ALLOC_KEEP, true, false); + run_vheap_case(VHEAP_FREE_KEPT, true, false); + + vheap_vreg_destroy(test_vreg); +} + +ZTEST(userspace_vregion_user_heap, kernel_use_refused) +{ + const struct vregion_user_heap_stats *stats; + size_t allocated; + uintptr_t start; + size_t size; + + test_vreg = vheap_vreg_create(VREGION_FLAG_USER_HEAP, true); + run_vheap_case(VHEAP_ADD, true, false); + zassert_ok(vheap_ret); + + zassert_ok(z_impl_vregion_interim_get(test_vreg, &start, &size)); + stats = sys_cache_uncached_ptr_get((__sparse_force void __sparse_cache *) + UINT_TO_POINTER(start)); + + run_vheap_case(VHEAP_ALLOC_KEEP, true, false); + allocated = stats->allocated_bytes; + zassert_true(allocated >= 64); + + /* kernel code does not run the allocator, and frees nothing */ + zassert_is_null(vregion_alloc(test_vreg, 64)); + zassert_is_null(vregion_alloc_coherent(test_vreg, 64)); + vregion_free(test_vreg, user_ptr); + zassert_is_null(vregion_user_alloc_align(test_vreg, 64, 0)); + vregion_user_free(test_vreg, user_ptr); + zassert_equal(stats->allocated_bytes, allocated); + + run_vheap_case(VHEAP_FREE_KEPT, true, false); + zassert_equal(stats->allocated_bytes, 0); + + run_vheap_case(VHEAP_REMOVE, true, false); + vheap_vreg_destroy(test_vreg); +} + +ZTEST(userspace_vregion_user_heap, interim_get_caller_check) +{ + test_vreg = vheap_vreg_create(VREGION_FLAG_USER_HEAP, true); + + /* an LL domain thread that is not the LL or IPC user thread */ + run_vheap_case(VHEAP_INTERIM_GET, false, true); + + vheap_vreg_destroy(test_vreg); +} + +ZTEST(userspace_vregion_user_heap, corrupted_metadata_faults_user_only) +{ + struct sys_mutex *lock; + struct sys_heap *sh; +#ifdef CONFIG_SYS_MUTEX_IMPL_K_MUTEX + struct k_object *ko; +#endif + + test_vreg = vheap_vreg_create(VREGION_FLAG_USER_HEAP, true); + run_vheap_case(VHEAP_ADD, true, false); + zassert_ok(vheap_ret); + run_vheap_case(VHEAP_ALLOC_KEEP, true, false); + + vregion_user_heap_test_get(test_vreg, &sh, &lock); + zassert_not_null(sh); + user_hdr = (uint32_t *)sh->heap; + + /* + * Make every chunk index in the header point at address 0x100, so + * that following one faults instead of writing to LL memory. + */ + user_hdr_value = (uint32_t)((0x100 - (uintptr_t)user_hdr) / 8); + + run_vheap_case(VHEAP_CORRUPT, true, false); + run_vheap_case(VHEAP_ALLOC_CORRUPTED, true, true); + + /* the paths that used to run the allocator in the kernel */ + zassert_is_null(vregion_alloc(test_vreg, 64)); + vregion_free(test_vreg, user_ptr); + + /* the faulting thread may have died holding the heap lock */ +#ifdef CONFIG_SYS_MUTEX_IMPL_K_MUTEX + ko = k_object_find(lock); + zassert_not_null(ko); + k_mutex_init(ko->data.mutex); +#else + sys_mutex_init(lock); +#endif + + /* the kernel frees the region with the corrupted heap */ + run_vheap_case(VHEAP_REMOVE, true, false); + vheap_vreg_destroy(test_vreg); + user_ptr = NULL; +} + +ZTEST_SUITE(userspace_vregion_user_heap, sof_boot_test_standalone_predicate, ll_user_heap_setup, + NULL, NULL, ll_user_heap_teardown); + +#endif /* CONFIG_SOF_VREGION_USER_HEAP */ /** * SOF main has booted up and IPC handling is stopped. @@ -545,6 +830,9 @@ static int run_tests(void) ztest_run_test_suite(userspace_ll_user_heap, false, 1, 1, NULL); #if HAVE_LL_FAST_GET_COPIES && CONFIG_SOF_ZEPHYR_LL_FG_AREA_SIZE ztest_run_test_suite(userspace_ll_fast_get, false, 1, 1, NULL); +#endif +#if CONFIG_SOF_VREGION_USER_HEAP + ztest_run_test_suite(userspace_vregion_user_heap, false, 1, 1, NULL); #endif return 0; }