From ce7eb91f2a5099cf08d5bcb4f544b6e8126fab47 Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Wed, 2 Dec 2026 14:54:43 +0200 Subject: [PATCH 01/12] vregion: let the users run the interim heap of a region The interim heap of a pipeline region is a k_heap whose metadata is in the region memory. With user-space LL that memory is mapped into the LL memory domain, and the IPC user threads allocate from the heap through the vregion system calls, so a user thread that forges the heap metadata gets the kernel to write anywhere. Add VREGION_FLAG_USER_HEAP to vregion_create_map(). For such a region vregion_set_interim() only reserves the interim range and keeps its bounds in the kernel-only struct vregion, without k_heap_init(). It does so right away, not on the next allocation like for the k_heap, as the kernel writes no heap metadata and the users set up their heap through the uncached alias. Kernel code, including the vregion system calls, refuses to allocate from or free to that range and logs the caller. The new vregion_interim_get() system call gives the range to the LL and IPC user threads, which run their own allocator on it in user mode. The flag is only accepted with CONFIG_SOF_VREGION_USER_HEAP, which is set with user-space LL. No region uses it yet. Regions without the flag, such as the DP module regions, keep the k_heap. As vregion_create_map() maps those into the LL memory domain too, the system call can not require the flag before the DP thread runs the interim heap of its region. Signed-off-by: Kai Vehmanen --- src/audio/module_adapter/module_adapter.c | 2 +- src/audio/pipeline/pipeline-graph.c | 2 +- src/include/sof/lib/vregion.h | 33 +++++- zephyr/Kconfig | 8 ++ zephyr/lib/vregion.c | 134 ++++++++++++++++++---- zephyr/syscall/vregion.c | 24 +++- 6 files changed, 177 insertions(+), 26 deletions(-) diff --git a/src/audio/module_adapter/module_adapter.c b/src/audio/module_adapter/module_adapter.c index 1257d15978b9..f8cfd00b2c77 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 diff --git a/src/audio/pipeline/pipeline-graph.c b/src/audio/pipeline/pipeline-graph.c index ae3eb317b000..c9a11715d5ca 100644 --- a/src/audio/pipeline/pipeline-graph.c +++ b/src/audio/pipeline/pipeline-graph.c @@ -206,7 +206,7 @@ __cold struct pipeline *pipeline_new(struct k_heap *heap, uint32_t pipeline_id, 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, 0); if (!alloc->vreg) pipe_cl_err("Failed to create pipeline vregion of %u bytes, using heap", pparams->mem_data->heap_bytes); diff --git a/src/include/sof/lib/vregion.h b/src/include/sof/lib/vregion.h index eab7e42a36ff..6dca3c2bbb81 100644 --- a/src/include/sof/lib/vregion.h +++ b/src/include/sof/lib/vregion.h @@ -43,6 +43,16 @@ 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) + #if CONFIG_SOF_VREGIONS /** @@ -64,9 +74,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 +91,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. * @@ -225,11 +249,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; diff --git a/zephyr/Kconfig b/zephyr/Kconfig index 1cd530fc1d2c..7b5791a0cf48 100644 --- a/zephyr/Kconfig +++ b/zephyr/Kconfig @@ -388,6 +388,14 @@ 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 VIRTUAL_HEAP bool "Use virtual memory heap to allocate buffers" default y if ACE diff --git a/zephyr/lib/vregion.c b/zephyr/lib/vregion.c index e340d0ff4b76..01085dc04a2a 100644 --- a/zephyr/lib/vregion.c +++ b/zephyr/lib/vregion.c @@ -68,6 +68,18 @@ LOG_MODULE_REGISTER(vregion, CONFIG_SOF_LOG_LEVEL); * * More types can be added in the future. * + * The kernel should run 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: with user-space LL, vregion_create_map() maps every region into the + * LL memory domain, also the DP module regions, whose interim heap the kernel + * still runs. Until the DP thread runs that heap, the vregion_create_map() + * system call can not require VREGION_FLAG_USER_HEAP. + * * * TODO: Pipeline/module reset() could reset the dynamic heap. */ @@ -103,8 +115,13 @@ struct vregion { /* current allocation mode */ enum vregion_mem_type type; /* LIFETIME at creation, switch to INTERIM */ bool interim_pending; /* vregion_set_interim() called, heap not yet created */ + 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 */ @@ -136,7 +153,8 @@ static void vregion_tel_fill_info(struct vregion *vr, struct sof_tel_vregion_inf 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 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); @@ -261,7 +279,10 @@ __cold struct vregion *vregion_create(size_t memsize) /* start in lifetime allocation mode */ vr->type = VREGION_MEM_TYPE_LIFETIME; + vr->flags = 0; vr->interim_pending = false; + vr->interim_base = NULL; + vr->interim_size = 0; k_mutex_init(&vr->lock); /* The creator is the first user */ @@ -294,11 +315,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 @@ -315,6 +341,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 @@ -445,7 +474,9 @@ 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, already in + * vregion_set_interim(). * * @param[in] vr Pointer to the virtual region instance. */ @@ -480,15 +511,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. */ @@ -510,14 +546,64 @@ void z_impl_vregion_set_interim(struct vregion *vr) * is called on the pipeline core, which can differ from the core of * a DP module in the pipeline. */ - if (vr->type == VREGION_MEM_TYPE_LIFETIME && !vr->interim_pending) - vr->interim_pending = true; - else + if (vr->type != VREGION_MEM_TYPE_LIFETIME || vr->interim_pending) { LOG_WRN("vregion %p already in interim mode", (void *)vr); + } else if (vr->flags & VREGION_FLAG_USER_HEAP) { + /* + * The kernel writes no heap metadata, and the users set up + * their heap through the uncached alias, on any core, so + * reserve the range now for vregion_interim_get(). + */ + interim_heap_init(vr); + vregion_tel_sync_locked(vr); + } else { + vr->interim_pending = true; + } 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. * @@ -623,10 +709,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)) @@ -669,6 +756,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: @@ -687,7 +781,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 From 1965d51ac847e54b2cd57314b04fe896f15bcdfa Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Tue, 24 Nov 2026 19:50:10 +0200 Subject: [PATCH 02/12] vregion: add a user-mode interim heap for the user threads Add the allocator that the LL and IPC user threads run on the interim range of a region with VREGION_FLAG_USER_HEAP, in user mode, like the LL user heap. vregion_user_heap_add() gets the range with vregion_interim_get() and initialises a sys_heap in it. The header at the start of the range holds the usage counters and the sys_heap object, and the metadata is only accessed through the uncached alias. The threads find the header of a region in a table in the system user partition, which DP threads cannot write. One sys_mutex in that partition serialises the table and all the heaps. CONFIG_SOF_VREGION_USER_HEAP_COUNT sets the table size, 32 by default, the IPC4 limit of pipelines. vregion_user_alloc_align(), vregion_user_alloc_coherent_align() and vregion_user_free() use that heap in user mode when the region has one, and otherwise call vregion_alloc_align(), vregion_alloc_coherent_align() and vregion_free(), so they can replace those calls for any region. Telemetry reads only the counters of a user-mode heap, as numbers. As the allocations no longer enter the kernel, it reads them each time it collects the region data. Signed-off-by: Kai Vehmanen --- src/include/sof/lib/vregion.h | 131 +++++++++++++ src/lib/CMakeLists.txt | 1 + src/lib/vregion_user.c | 333 ++++++++++++++++++++++++++++++++++ zephyr/Kconfig | 8 + zephyr/lib/vregion.c | 32 ++++ 5 files changed, 505 insertions(+) create mode 100644 src/lib/vregion_user.c diff --git a/src/include/sof/lib/vregion.h b/src/include/sof/lib/vregion.h index 6dca3c2bbb81..2c595765e527 100644 --- a/src/include/sof/lib/vregion.h +++ b/src/include/sof/lib/vregion.h @@ -53,6 +53,18 @@ enum vregion_mem_type { */ #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 /** @@ -237,6 +249,105 @@ 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); + +#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 @@ -291,6 +402,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/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/vregion_user.c b/src/lib/vregion_user.c new file mode 100644 index 000000000000..3a48e2e907fe --- /dev/null +++ b/src/lib/vregion_user.c @@ -0,0 +1,333 @@ +// 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; +} + +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 7b5791a0cf48..58ade5941942 100644 --- a/zephyr/Kconfig +++ b/zephyr/Kconfig @@ -396,6 +396,14 @@ config SOF_VREGION_USER_HEAP 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/lib/vregion.c b/zephyr/lib/vregion.c index 01085dc04a2a..d5a850cfa921 100644 --- a/zephyr/lib/vregion.c +++ b/zephyr/lib/vregion.c @@ -152,6 +152,16 @@ 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->flags & VREGION_FLAG_USER_HEAP) && vr->interim.heap.heap.heap) { @@ -929,6 +939,25 @@ int vregion_pinned_put(struct vregion *vr) #endif #ifdef CONFIG_SOF_TELEMETRY_VREGION +/* + * The user threads run the user-mode heaps without system calls, so read + * their counters when telemetry is collected. The list lock keeps the + * listed regions, and so their memory, from being freed meanwhile. + */ +static void vregion_tel_sync_user_heaps(void) +{ + struct vregion *vr; + + k_mutex_lock(&vregion_list_lock, K_FOREVER); + SYS_DLIST_FOR_EACH_CONTAINER(&vregion_list, vr, node) { + k_mutex_lock(&vr->lock, K_FOREVER); + if (vr->type == VREGION_MEM_TYPE_INTERIM && vr->flags & VREGION_FLAG_USER_HEAP) + vregion_tel_sync_locked(vr); + k_mutex_unlock(&vr->lock); + } + k_mutex_unlock(&vregion_list_lock); +} + void telemetry_collect_vregion_stats(struct sof_tel_vregion_section *vsec) { uint16_t active_cnt = 0; @@ -936,6 +965,9 @@ void telemetry_collect_vregion_stats(struct sof_tel_vregion_section *vsec) if (!vsec) return; + if (IS_ENABLED(CONFIG_SOF_VREGION_USER_HEAP)) + vregion_tel_sync_user_heaps(); + for (int i = 0; i < SOF_TEL_MAX_VREGIONS; i++) { if (!tel_vregions[i]) { memset(&vsec->vregions[i], 0, sizeof(vsec->vregions[i])); From 49e46cdc47129f54a2eb3446ff3298c3c6fa624e Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Tue, 24 Nov 2026 19:51:45 +0200 Subject: [PATCH 03/12] alloc: use the user-mode region heaps in user mode Allocate and free the region memory of allocation contexts, object pools and module instances with vregion_user_alloc_align(), vregion_user_alloc_coherent_align() and vregion_user_free(), so that in user mode they use the user-mode interim heap of a region that has one. For the other regions, and in kernel mode, nothing changes: the functions then call the vregion system calls as before. Signed-off-by: Kai Vehmanen --- src/audio/module_adapter/module_adapter.c | 12 ++++++------ src/lib/objpool.c | 10 +++++----- zephyr/include/rtos/alloc.h | 14 +++++++------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/audio/module_adapter/module_adapter.c b/src/audio/module_adapter/module_adapter.c index f8cfd00b2c77..94d0f15c7a32 100644 --- a/src/audio/module_adapter/module_adapter.c +++ b/src/audio/module_adapter/module_adapter.c @@ -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/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/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); } From 376cee03d168bacf1022d769eaf40999c70c08f9 Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Tue, 24 Nov 2026 19:52:13 +0200 Subject: [PATCH 04/12] pipeline: run the interim heap of pipeline regions in user mode With user-space LL, every pipeline has a region, and the IPC user threads allocate from its interim heap at every pipeline start, for the pipeline and trigger tasks, and in the prepare of LL modules. The kernel ran that k_heap on memory that LL and IPC user threads can write. Create the pipeline regions with VREGION_FLAG_USER_HEAP. Set up the user-mode heap when the pipeline is complete, after switching the region to interim allocations, and remove it when the pipeline is freed, after its modules. Allocations then do not enter the kernel. The DP module regions are not changed. Signed-off-by: Kai Vehmanen --- src/audio/pipeline/pipeline-graph.c | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/audio/pipeline/pipeline-graph.c b/src/audio/pipeline/pipeline-graph.c index c9a11715d5ca..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, 0); + 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 */ From 18e4247cc046be747e3157a1b39185cccbbcc081 Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Tue, 24 Nov 2026 20:11:25 +0200 Subject: [PATCH 05/12] zephyr: test: userspace: test the user-mode region heap Add a standalone suite for the user-mode interim heap of the regions with VREGION_FLAG_USER_HEAP. The IPC user thread sets up the heap of a region mapped into the LL memory domain and allocates coherent and cached memory of several alignments from the interim range, and the counters drop back when it is freed. Lifetime allocations still go to the kernel, and a region without the flag keeps its kernel heap. Kernel code neither allocates from the interim range nor frees to it, but telemetry reports the usage, an LL domain thread that is not the LL or IPC user thread cannot get the range, and a user thread that corrupts the heap metadata only faults itself. The suite shares the user thread of the LL user heap suite, as the standalone build has no thread ID left for another one. vregion_user_heap_test_get() gives the test the heap and its lock. Signed-off-by: Kai Vehmanen --- src/include/sof/lib/vregion.h | 14 + src/lib/vregion_user.c | 11 + zephyr/test/userspace/test_ll_user_heap.c | 317 ++++++++++++++++++++++ 3 files changed, 342 insertions(+) diff --git a/src/include/sof/lib/vregion.h b/src/include/sof/lib/vregion.h index 2c595765e527..d7d007773b46 100644 --- a/src/include/sof/lib/vregion.h +++ b/src/include/sof/lib/vregion.h @@ -320,6 +320,20 @@ void *vregion_user_alloc_coherent_align(struct vregion *vr, size_t size, size_t */ 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) diff --git a/src/lib/vregion_user.c b/src/lib/vregion_user.c index 3a48e2e907fe..ad29b07e1817 100644 --- a/src/lib/vregion_user.c +++ b/src/lib/vregion_user.c @@ -322,6 +322,17 @@ static bool vregion_user_heap_free(struct vregion *vr, void *ptr) 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) diff --git a/zephyr/test/userspace/test_ll_user_heap.c b/zephyr/test/userspace/test_ll_user_heap.c index 906337b5cef3..da0adde0f6a1 100644 --- a/zephyr/test/userspace/test_ll_user_heap.c +++ b/zephyr/test/userspace/test_ll_user_heap.c @@ -15,11 +15,17 @@ * 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 #include #include +#include #include #include #include @@ -535,6 +541,314 @@ 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; +/* region base, for the kernel side of the tests */ +static uintptr_t test_vreg_base; +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); + test_vreg_base = start; + 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); +} + +#if CONFIG_SOF_TELEMETRY_VREGION +static struct sof_tel_vregion_section tel_vsec; + +/* the interim usage that telemetry reports for the test region */ +static uint32_t tel_interim_alloc_bytes(void) +{ + int i; + + telemetry_collect_vregion_stats(&tel_vsec); + for (i = 0; i < SOF_TEL_MAX_VREGIONS; i++) + if (tel_vsec.vregions[i].base_va == test_vreg_base) + return tel_vsec.vregions[i].interim_alloc_bytes; + + zassert_unreachable("region %p not in telemetry", (void *)test_vreg_base); + return 0; +} +#endif + +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); +#if CONFIG_SOF_TELEMETRY_VREGION + /* the allocation made no system call, telemetry reads it anyway */ + zassert_equal(tel_interim_alloc_bytes(), allocated); +#endif + + /* 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); +#if CONFIG_SOF_TELEMETRY_VREGION + zassert_equal(tel_interim_alloc_bytes(), 0); +#endif + + 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 +859,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; } From 631d98e008337399fe53f8838ec9dc88619c995e Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Tue, 24 Nov 2026 20:11:25 +0200 Subject: [PATCH 06/12] userspace: doc: describe the user-mode region heap Describe the user-mode interim heap of the pipeline regions next to the LL user heap, add vregion_interim_get() to the syscall map, and list the new test cases. Signed-off-by: Kai Vehmanen --- src/include/sof/userspace/README.md | 20 +++++++++++++++++++- zephyr/test/userspace/README.md | 4 ++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/include/sof/userspace/README.md b/src/include/sof/userspace/README.md index 5a53260dd034..7d2a5cb915a7 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,24 @@ 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 each time it collects the region data, 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, which are mapped into the LL memory domain too. + 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/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 \ From 225c80b2acf5feda8c1dddbdb80387f28b257044 Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Wed, 25 Nov 2026 12:26:43 +0200 Subject: [PATCH 07/12] dp_schedule: take the DP module region from the kernel scheduler_dp_task_init() built the heap partitions of the DP domain from mod_heap_info(), which follows the allocation context pointer in module memory to the region. LL and IPC user threads can write that memory, so they could make the kernel map other memory into the DP domain. The kernel creates the region of a DP module itself, in module_adapter_mem_alloc(). Pass it on through pipeline_comp_dp_task_init() to scheduler_dp_task_init(), which keeps a reference in the kernel-only task record and takes the partition bounds from the kernel-only struct vregion. The reference is dropped when the task is freed. The free system call checks the caller's access to that region too. Modules without a region keep using mod_heap_info(). Signed-off-by: Kai Vehmanen --- src/audio/module_adapter/module_adapter.c | 12 ++++++--- src/audio/pipeline/pipeline-schedule.c | 4 +-- src/include/sof/audio/pipeline.h | 4 ++- src/include/sof/schedule/dp_schedule.h | 5 ++++ .../zephyr_dp_schedule_application-kernel.c | 27 +++++++++++++------ .../zephyr_dp_schedule_thread-kernel.c | 1 + 6 files changed, 39 insertions(+), 14 deletions(-) diff --git a/src/audio/module_adapter/module_adapter.c b/src/audio/module_adapter/module_adapter.c index 94d0f15c7a32..894e86e8a826 100644 --- a/src/audio/module_adapter/module_adapter.c +++ b/src/audio/module_adapter/module_adapter.c @@ -80,7 +80,8 @@ __cold static struct processing_module *module_adapter_mem_alloc(const struct comp_driver *drv, const struct comp_ipc_config *config, const struct module_ext_init_data *ext_init, - struct mod_alloc_ctx *ppl_alloc) + struct mod_alloc_ctx *ppl_alloc, + struct vregion **dp_vreg) { struct k_heap *mod_heap; struct vregion *mod_vreg; @@ -186,6 +187,9 @@ struct processing_module *module_adapter_mem_alloc(const struct comp_driver *drv mod->dev = dev; dev->mod = mod; + /* the region of a DP module, from here and not from module memory */ + *dp_vreg = use_ppl_alloc ? NULL : mod_vreg; + return mod; edev: @@ -296,7 +300,9 @@ __cold struct comp_dev *module_adapter_new_ext(const struct comp_driver *drv, ppl_alloc = ipc_pipe->pipeline->alloc; #endif - struct processing_module *mod = module_adapter_mem_alloc(drv, config, ext_init, ppl_alloc); + struct vregion *dp_vreg; + struct processing_module *mod = module_adapter_mem_alloc(drv, config, ext_init, ppl_alloc, + &dp_vreg); if (!mod) return NULL; @@ -338,7 +344,7 @@ __cold struct comp_dev *module_adapter_new_ext(const struct comp_driver *drv, /* create a task for DP processing */ if (config->proc_domain == COMP_PROCESSING_DOMAIN_DP) { /* All data allocated, create a thread */ - ret = pipeline_comp_dp_task_init(dev); + ret = pipeline_comp_dp_task_init(dev, dp_vreg); if (ret) { comp_cl_err(drv, "DP task creation failed with error %d.", ret); goto err; diff --git a/src/audio/pipeline/pipeline-schedule.c b/src/audio/pipeline/pipeline-schedule.c index 63b9fd979088..82916b9bee83 100644 --- a/src/audio/pipeline/pipeline-schedule.c +++ b/src/audio/pipeline/pipeline-schedule.c @@ -591,7 +591,7 @@ static enum task_state dp_task_run(void *data) return SOF_TASK_STATE_RESCHEDULE; } -int pipeline_comp_dp_task_init(struct comp_dev *comp) +int pipeline_comp_dp_task_init(struct comp_dev *comp, struct vregion *vreg) { /* DP tasks are guaranteed to have a module_adapter */ struct processing_module *mod = comp_mod(comp); @@ -620,7 +620,7 @@ int pipeline_comp_dp_task_init(struct comp_dev *comp) CONFIG_ZEPHYR_DP_SCHEDULER_MIN_STACK_SIZE); } - return scheduler_dp_task_init(&comp->task, SOF_UUID(dp_task_uuid), &ops, mod, + return scheduler_dp_task_init(&comp->task, SOF_UUID(dp_task_uuid), &ops, mod, vreg, comp->ipc_config.core, stack_size, flags); } #endif /* CONFIG_ZEPHYR_DP_SCHEDULER */ diff --git a/src/include/sof/audio/pipeline.h b/src/include/sof/audio/pipeline.h index 9409eaec0236..198c49980d7f 100644 --- a/src/include/sof/audio/pipeline.h +++ b/src/include/sof/audio/pipeline.h @@ -33,6 +33,7 @@ struct comp_buffer; struct comp_dev; struct ipc; +struct vregion; struct ipc_msg; struct k_heap; struct mod_alloc_ctx; @@ -411,9 +412,10 @@ void pipeline_comp_ll_task_free(struct pipeline *p); /** * \brief Initializes a data processing (DP) task for a component. * \param[in,out] comp Component device for which the task is created. + * \param[in] vreg Region of the module created by the kernel, or NULL. * \return 0 on success, or negative error code on failure. */ -int pipeline_comp_dp_task_init(struct comp_dev *comp); +int pipeline_comp_dp_task_init(struct comp_dev *comp, struct vregion *vreg); /** * \brief Schedules a pipeline copy operation to run after a delay. diff --git a/src/include/sof/schedule/dp_schedule.h b/src/include/sof/schedule/dp_schedule.h index ab511e125f65..88b86cc90bab 100644 --- a/src/include/sof/schedule/dp_schedule.h +++ b/src/include/sof/schedule/dp_schedule.h @@ -44,6 +44,7 @@ struct processing_module; struct module_ext_init_data; +struct vregion; /** * @brief Initialize the Data Processing (DP) scheduler on the calling core. @@ -63,6 +64,9 @@ int scheduler_dp_init(void); * @param[in] uid UUID identifying the task/module. * @param[in] ops Task operations callbacks (@ref task_ops). * @param[in] mod Processing module descriptor bound to this task. + * @param[in] vreg Region that the kernel created for the module, or NULL if + * the module has none. Not read back from module memory, which + * user threads can write. * @param[in] core DSP core affinity for the task thread. * @param[in] stack_size Stack byte size for the Zephyr worker thread. * @param[in] options Task configuration flags. @@ -72,6 +76,7 @@ int scheduler_dp_task_init(struct task **task, const struct sof_uuid_entry *uid, const struct task_ops *ops, struct processing_module *mod, + struct vregion *vreg, uint16_t core, size_t stack_size, uint32_t options); diff --git a/src/kernel/schedule/zephyr_dp_schedule_application-kernel.c b/src/kernel/schedule/zephyr_dp_schedule_application-kernel.c index e839d32f716b..29cfa4638d2c 100644 --- a/src/kernel/schedule/zephyr_dp_schedule_application-kernel.c +++ b/src/kernel/schedule/zephyr_dp_schedule_application-kernel.c @@ -66,6 +66,7 @@ struct scheduler_dp_task_kobj { struct ipc4_flat *flat; /* IPC parameter area in task memory */ void *config_data; /* LARGE_CONFIG_GET reply buffer in task memory */ struct k_mem_domain *mdom; + struct vregion *vreg; /* module region, a reference, or NULL */ struct k_mem_partition mpart[SOF_DP_PART_TYPE_COUNT]; uint32_t comp_id; uint16_t core; @@ -223,6 +224,7 @@ static bool scheduler_dp_internal_free_kobj(struct task *task, scheduler_dp_domain_free(kobj->mod, kobj->mdom, kobj->mpart, kobj->comp_id); mod_free(kobj->mod, container_of(task, struct scheduler_dp_task_memory, task)); + vregion_put(kobj->vreg); rfree(kobj); return true; @@ -251,7 +253,8 @@ static void scheduler_dp_thread_name_set(k_tid_t thread_id, struct processing_mo /* Called only in IPC context in kernel mode (this can change) */ int scheduler_dp_task_init(struct task **task, const struct sof_uuid_entry *uid, const struct task_ops *ops, struct processing_module *mod, - uint16_t core, size_t stack_size, uint32_t options) + struct vregion *vreg, uint16_t core, size_t stack_size, + uint32_t options) { k_thread_stack_t *p_stack; struct scheduler_dp_task_memory *task_memory; @@ -321,6 +324,7 @@ int scheduler_dp_task_init(struct task **task, const struct sof_uuid_entry *uid, kobj->task = ptask; kobj->mod = mod; + kobj->vreg = vregion_get(vreg); kobj->core = core; comp_id = mod->dev->ipc_config.id; kobj->comp_id = comp_id; @@ -418,8 +422,14 @@ int scheduler_dp_task_init(struct task **task, const struct sof_uuid_entry *uid, goto e_thread; } - /* Module heap partition */ - mod_heap_info(mod, &size, &start); + /* + * Module heap partition. Take the region bounds from the kernel-only + * struct vregion, not through the allocation context in module memory. + */ + if (kobj->vreg) + vregion_mem_info(kobj->vreg, &size, &start); + else + mod_heap_info(mod, &size, &start); kobj->mpart[SOF_DP_PART_HEAP] = (struct k_mem_partition){ .start = (uintptr_t)sys_cache_uncached_ptr_get((void *)start), .size = size, @@ -491,6 +501,7 @@ int scheduler_dp_task_init(struct task **task, const struct sof_uuid_entry *uid, e_config: mod_free(mod, ipc_config_data); e_kobj: + vregion_put(kobj->vreg); rfree(kobj); e_stack: user_stack_free(p_stack); @@ -615,7 +626,7 @@ void scheduler_dp_test_record_del(struct task *task) * supervisor mode. They are user-writable, so at least check that they * point to memory the caller can access. */ -static void scheduler_dp_mod_vrfy(struct processing_module *mod) +static void scheduler_dp_mod_vrfy(struct processing_module *mod, struct vregion *vreg) { K_OOPS(K_SYSCALL_MEMORY_WRITE(mod, sizeof(*mod))); K_OOPS(K_SYSCALL_MEMORY_WRITE(mod->dev, sizeof(*mod->dev))); @@ -624,7 +635,7 @@ static void scheduler_dp_mod_vrfy(struct processing_module *mod) struct mod_alloc_ctx *alloc = mod->priv.resources.alloc; K_OOPS(K_SYSCALL_MEMORY_WRITE(alloc, sizeof(*alloc))); - if (alloc->heap) { + if (alloc->heap && !vreg) { size_t h_size = 0; uintptr_t h_start; @@ -632,11 +643,11 @@ static void scheduler_dp_mod_vrfy(struct processing_module *mod) if (h_size) K_OOPS(K_SYSCALL_MEMORY_WRITE(h_start, h_size)); } - if (alloc->vreg) { + if (vreg) { size_t vr_size = 0; uintptr_t vr_start; - vregion_mem_info(alloc->vreg, &vr_size, &vr_start); + vregion_mem_info(vreg, &vr_size, &vr_start); K_OOPS(K_SYSCALL_MEMORY_WRITE(vr_start, vr_size)); } } @@ -666,7 +677,7 @@ void z_vrfy_scheduler_dp_internal_free(struct task *task) */ K_OOPS(K_SYSCALL_OBJ(kobj.event, K_OBJ_EVENT)); K_OOPS(K_SYSCALL_OBJ_INIT(kobj.thread, K_OBJ_THREAD)); - scheduler_dp_mod_vrfy(kobj.mod); + scheduler_dp_mod_vrfy(kobj.mod, kobj.vreg); K_OOPS(!scheduler_dp_internal_free_kobj(task, &kobj)); } diff --git a/src/kernel/schedule/zephyr_dp_schedule_thread-kernel.c b/src/kernel/schedule/zephyr_dp_schedule_thread-kernel.c index 05c85ad98b1e..a871dcbcd634 100644 --- a/src/kernel/schedule/zephyr_dp_schedule_thread-kernel.c +++ b/src/kernel/schedule/zephyr_dp_schedule_thread-kernel.c @@ -38,6 +38,7 @@ int scheduler_dp_task_init(struct task **task, const struct sof_uuid_entry *uid, const struct task_ops *ops, struct processing_module *mod, + struct vregion *vreg, uint16_t core, size_t stack_size, uint32_t options) From 4a74c944e39ab023dca4d7f946e57e82690e5ede Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Wed, 25 Nov 2026 12:27:25 +0200 Subject: [PATCH 08/12] vregion: record the DP thread that owns a region Add vregion_owner_set(), which records the owner thread of a region in the kernel-only struct vregion. The DP scheduler sets the DP thread as the owner of its module region right before the thread starts, and clears it when the task is freed, after the thread is aborted. The owner is not used yet. It lets the vregion system calls tell the DP thread of a module from other DP threads. Signed-off-by: Kai Vehmanen --- src/include/sof/lib/vregion.h | 14 ++++++++++++++ .../zephyr_dp_schedule_application-kernel.c | 4 ++++ zephyr/lib/vregion.c | 12 ++++++++++++ 3 files changed, 30 insertions(+) diff --git a/src/include/sof/lib/vregion.h b/src/include/sof/lib/vregion.h index d7d007773b46..5209364a3777 100644 --- a/src/include/sof/lib/vregion.h +++ b/src/include/sof/lib/vregion.h @@ -27,6 +27,7 @@ extern "C" { * @brief Virtual region descriptor managing lifetime and interim heap partitions. */ struct vregion; +struct k_thread; /** * @brief Memory allocation modes within a virtual memory region. @@ -103,6 +104,18 @@ __syscall struct vregion *vregion_create_map(uintptr_t *vreg_start, size_t *vreg */ __syscall void vregion_set_interim(struct vregion *vr); +/** + * @brief Record the user thread that owns a virtual region. + * + * Kernel code only. The owner is the DP thread of the module that the region + * belongs to. It may use the region through the vregion system calls, see + * vregion_owner_check(). The owner is kept in the kernel-only struct vregion. + * + * @param[in] vr Pointer to the virtual region instance, may be NULL. + * @param[in] thread The owner thread, or NULL to clear the owner. + */ +void vregion_owner_set(struct vregion *vr, struct k_thread *thread); + /** * @brief Get the interim range of a virtual region with VREGION_FLAG_USER_HEAP. * @@ -380,6 +393,7 @@ static inline struct vregion *vregion_create_map(uintptr_t *vreg_start, size_t * return NULL; } static inline void vregion_set_interim(struct vregion *vr) {} +static inline void vregion_owner_set(struct vregion *vr, struct k_thread *thread) {} static inline int vregion_interim_get(struct vregion *vr, uintptr_t *start, size_t *size) { return -EPERM; diff --git a/src/kernel/schedule/zephyr_dp_schedule_application-kernel.c b/src/kernel/schedule/zephyr_dp_schedule_application-kernel.c index 29cfa4638d2c..f2bda2afe4bd 100644 --- a/src/kernel/schedule/zephyr_dp_schedule_application-kernel.c +++ b/src/kernel/schedule/zephyr_dp_schedule_application-kernel.c @@ -219,6 +219,7 @@ static bool scheduler_dp_internal_free_kobj(struct task *task, /* normally already terminated by scheduler_dp_task_free(), no-op then */ k_thread_abort(kobj->thread); + vregion_owner_set(kobj->vreg, NULL); k_object_free(kobj->event); k_object_free(kobj->thread); scheduler_dp_domain_free(kobj->mod, kobj->mdom, kobj->mpart, kobj->comp_id); @@ -476,6 +477,9 @@ int scheduler_dp_task_init(struct task **task, const struct sof_uuid_entry *uid, goto e_dom; } + /* the DP thread may use its region through the vregion system calls */ + vregion_owner_set(kobj->vreg, thread_id); + /* publish the record before the thread can run */ dp_task_kobj_add(kobj); diff --git a/zephyr/lib/vregion.c b/zephyr/lib/vregion.c index d5a850cfa921..5f2952bb0255 100644 --- a/zephyr/lib/vregion.c +++ b/zephyr/lib/vregion.c @@ -111,6 +111,7 @@ struct vregion { unsigned int use_count; /* references held by kernel and user code */ unsigned int pins; /* system calls in progress, see vregion_verify_pin() */ struct k_mem_domain *domain; + struct k_thread *owner; /* DP thread of the module, see vregion_owner_set() */ /* current allocation mode */ enum vregion_mem_type type; /* LIFETIME at creation, switch to INTERIM */ @@ -279,6 +280,7 @@ __cold struct vregion *vregion_create(size_t memsize) vr->size = total_size; vr->pages = pages; vr->domain = NULL; + vr->owner = NULL; /* lifetime linear allocator starts at the beginning of the vregion memory */ vr->lifetime.base = vregion_base; @@ -542,6 +544,16 @@ static void interim_heap_init(struct vregion *vr) vr->lifetime.used = (uint8_t *)vr->lifetime.ptr - (uint8_t *)vr->lifetime.base; } +void vregion_owner_set(struct vregion *vr, struct k_thread *thread) +{ + if (!vr) + return; + + k_mutex_lock(&vr->lock, K_FOREVER); + vr->owner = thread; + k_mutex_unlock(&vr->lock); +} + void z_impl_vregion_set_interim(struct vregion *vr) { if (!vr) From 98ca49a446149c7ffc909f43e627dbb1f6558d08 Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Wed, 25 Nov 2026 12:28:38 +0200 Subject: [PATCH 09/12] vregion: let the owner DP thread use its lifetime allocator Add vregion_owner_check() for the vregion system call validators. It passes for the LL and IPC user threads and for the owner thread of the region, and unpins the region and kills any other caller, such as the DP thread of another module. vregion_alloc_align(), vregion_alloc_coherent_align() and vregion_free() now accept the owner DP thread, but only for the lifetime allocator, through the new kernel functions vregion_lifetime_alloc_align() and vregion_lifetime_free(): the kernel never runs the interim heap for it. The other vregion system calls stay limited to the LL and IPC user threads. The DP threads do not use the calls yet. They will, once DP modules use their resources in user mode. Without the syscall caller registry, every user thread but the owner is treated as before. Signed-off-by: Kai Vehmanen --- src/include/sof/lib/vregion.h | 46 ++++++++++++++++++++ zephyr/lib/vregion.c | 79 ++++++++++++++++++++++++++++++++--- zephyr/syscall/vregion.c | 47 ++++++++++++++------- 3 files changed, 152 insertions(+), 20 deletions(-) diff --git a/src/include/sof/lib/vregion.h b/src/include/sof/lib/vregion.h index 5209364a3777..09938da23bb3 100644 --- a/src/include/sof/lib/vregion.h +++ b/src/include/sof/lib/vregion.h @@ -235,6 +235,45 @@ void vregion_mem_info(struct vregion *vr, size_t *size, uintptr_t *start); */ bool vregion_verify_pin(struct vregion *vr); +/** + * @brief Check the caller of a vregion system call. + * + * For system call validators, on a vregion pinned with vregion_verify_pin(). + * Passes for the LL and IPC user threads and for the owner thread of vr, see + * vregion_owner_set(). Unpins vr and kills any other caller. + * + * @param[in] vr Pinned virtual region instance. + * @return True for the LL and IPC user threads, false for the owner, which + * may only use the lifetime allocator. + */ +bool vregion_owner_check(struct vregion *vr); + +/** + * @brief Allocate from the lifetime allocator of a virtual region only. + * + * Kernel code only, for the owner thread of the region. Never allocates from + * the interim heap, which the kernel may run on the region memory. + * + * @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. + * @param[in] coherent Return the uncached alias, as vregion_alloc_coherent_align(). + * @return Pointer to the allocated memory, or NULL on failure. + */ +void *vregion_lifetime_alloc_align(struct vregion *vr, size_t size, size_t alignment, + bool coherent); + +/** + * @brief Free to the lifetime allocator of a virtual region only. + * + * Kernel code only, for the owner thread of the region. Refuses pointers in + * the interim range. + * + * @param[in] vr Pointer to the virtual region instance. + * @param[in] ptr Pointer to the memory to free. + */ +void vregion_lifetime_free(struct vregion *vr, void *ptr); + /** * @brief Release a pin taken with vregion_verify_pin(). * @@ -451,6 +490,13 @@ static inline void *vregion_user_alloc_coherent_align(struct vregion *vr, size_t } static inline void vregion_user_free(struct vregion *vr, void *ptr) {} static inline bool vregion_verify_pin(struct vregion *vr) { return false; } +static inline bool vregion_owner_check(struct vregion *vr) { return false; } +static inline void *vregion_lifetime_alloc_align(struct vregion *vr, size_t size, + size_t alignment, bool coherent) +{ + return NULL; +} +static inline void vregion_lifetime_free(struct vregion *vr, void *ptr) {} static inline void vregion_unpin(struct vregion *vr) {} static inline bool vregion_pinned_get(struct vregion *vr) { return false; } static inline int vregion_pinned_put(struct vregion *vr) { return -EINVAL; } diff --git a/zephyr/lib/vregion.c b/zephyr/lib/vregion.c index 5f2952bb0255..ad7a2d454533 100644 --- a/zephyr/lib/vregion.c +++ b/zephyr/lib/vregion.c @@ -720,7 +720,8 @@ static void lifetime_free(struct vlinear_heap *heap, void *ptr) * @param vr Pointer to the virtual region instance. * @param ptr Pointer to the memory to free. */ -void z_impl_vregion_free(struct vregion *vr, void *ptr) +/* With @lifetime_only, refuse to free to the interim heap */ +static void vregion_free_mode(struct vregion *vr, void *ptr, bool lifetime_only) { if (!vr || !ptr) return; @@ -731,7 +732,9 @@ 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 (vregion_in_interim(vr, ptr) && vr->flags & VREGION_FLAG_USER_HEAP) + if (vregion_in_interim(vr, ptr) && lifetime_only) + LOG_ERR("error: interim free %p from %p by its owner refused", ptr, (void *)vr); + else 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); @@ -747,19 +750,30 @@ void z_impl_vregion_free(struct vregion *vr, void *ptr) vregion_tel_sync_locked(vr); k_mutex_unlock(&vr->lock); } + +void z_impl_vregion_free(struct vregion *vr, void *ptr) +{ + vregion_free_mode(vr, ptr, false); +} EXPORT_SYMBOL(z_impl_vregion_free); +void vregion_lifetime_free(struct vregion *vr, void *ptr) +{ + vregion_free_mode(vr, ptr, true); +} + /** * @brief Allocate memory from the virtual region. * * @param[in] vr Pointer to the virtual region instance. * @param[in] size Size of the allocation. * @param[in] alignment Alignment of the allocation. + * @param[in] lifetime_only Refuse to allocate from the interim heap. * * @return void* Pointer to the allocated memory, or NULL on failure. */ -void *z_impl_vregion_alloc_align(struct vregion *vr, - size_t size, size_t alignment) +static void *vregion_alloc_mode(struct vregion *vr, size_t size, size_t alignment, + bool lifetime_only) { void *p; @@ -778,6 +792,13 @@ void *z_impl_vregion_alloc_align(struct vregion *vr, switch (vr->type) { case VREGION_MEM_TYPE_INTERIM: + if (lifetime_only) { + /* the kernel does not run a heap for the owner thread */ + LOG_ERR("error: interim alloc of %zu from %p by its owner refused", + size, (void *)vr); + p = NULL; + break; + } 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", @@ -816,15 +837,21 @@ void *z_impl_vregion_alloc_align(struct vregion *vr, return p; } + +void *z_impl_vregion_alloc_align(struct vregion *vr, size_t size, size_t alignment) +{ + return vregion_alloc_mode(vr, size, alignment, false); +} EXPORT_SYMBOL(z_impl_vregion_alloc_align); -void *z_impl_vregion_alloc_coherent_align(struct vregion *vr, size_t size, size_t alignment) +static void *vregion_alloc_coherent_mode(struct vregion *vr, size_t size, size_t alignment, + bool lifetime_only) { if (alignment < CONFIG_DCACHE_LINE_SIZE) alignment = CONFIG_DCACHE_LINE_SIZE; size = ALIGN_UP(size, CONFIG_DCACHE_LINE_SIZE); - void *p = z_impl_vregion_alloc_align(vr, size, alignment); + void *p = vregion_alloc_mode(vr, size, alignment, lifetime_only); if (!p) return NULL; @@ -833,8 +860,22 @@ void *z_impl_vregion_alloc_coherent_align(struct vregion *vr, size_t size, size_ return sys_cache_uncached_ptr_get(p); } + +void *z_impl_vregion_alloc_coherent_align(struct vregion *vr, size_t size, size_t alignment) +{ + return vregion_alloc_coherent_mode(vr, size, alignment, false); +} EXPORT_SYMBOL(z_impl_vregion_alloc_coherent_align); +void *vregion_lifetime_alloc_align(struct vregion *vr, size_t size, size_t alignment, + bool coherent) +{ + if (coherent) + return vregion_alloc_coherent_mode(vr, size, alignment, true); + + return vregion_alloc_mode(vr, size, alignment, true); +} + /** * @brief Log virtual region memory usage. * @@ -862,6 +903,7 @@ void vregion_mem_info(struct vregion *vr, size_t *size, uintptr_t *start) #if CONFIG_SOF_VREGIONS && CONFIG_USERSPACE #include +#include bool vregion_verify_pin(struct vregion *vr) { @@ -906,6 +948,31 @@ bool vregion_verify_pin(struct vregion *vr) return true; } +bool vregion_owner_check(struct vregion *vr) +{ + bool owner; + + k_mutex_lock(&vr->lock, K_FOREVER); + owner = vr->owner && vr->owner == k_current_get(); + k_mutex_unlock(&vr->lock); + +#ifdef CONFIG_SOF_USERSPACE_SYSCALL_CALLER_CHECK + if (sof_syscall_caller_allowed(SOF_SYSUSER_INFRA)) + return true; + + if (!owner) { + /* another DP thread, or a thread that is no SOF infrastructure */ + vregion_unpin(vr); + K_OOPS(true); + } + + return false; +#else + /* no registry of the infrastructure threads, trust all but the owner */ + return !owner; +#endif +} + void vregion_unpin(struct vregion *vr) { bool destroy; diff --git a/zephyr/syscall/vregion.c b/zephyr/syscall/vregion.c index 153bdf8880fa..52c2fdf11964 100644 --- a/zephyr/syscall/vregion.c +++ b/zephyr/syscall/vregion.c @@ -13,18 +13,27 @@ * cannot free the vregion while the implementation uses it. The pin is * counted separately from references, so such a vregion_put() can not * consume it either. + * + * The allocation calls are also open to the owner DP thread of a region, + * for its lifetime allocator only. The other calls are for the LL and IPC + * user threads only. */ static inline void *z_vrfy_vregion_alloc_align(struct vregion *vr, size_t size, size_t alignment) { - void *ptr = NULL; + void *ptr; - SOF_SYSCALL_CALLER_CHECK(SOF_SYSUSER_INFRA); + if (!vregion_verify_pin(vr)) { + SOF_SYSCALL_CALLER_CHECK(SOF_SYSUSER_INFRA); + return NULL; + } - if (vregion_verify_pin(vr)) { + if (vregion_owner_check(vr)) ptr = z_impl_vregion_alloc_align(vr, size, alignment); - vregion_unpin(vr); - } + else + ptr = vregion_lifetime_alloc_align(vr, size, alignment, false); + + vregion_unpin(vr); return ptr; } @@ -33,14 +42,19 @@ static inline void *z_vrfy_vregion_alloc_align(struct vregion *vr, size_t size, static inline void *z_vrfy_vregion_alloc_coherent_align(struct vregion *vr, size_t size, size_t alignment) { - void *ptr = NULL; + void *ptr; - SOF_SYSCALL_CALLER_CHECK(SOF_SYSUSER_INFRA); + if (!vregion_verify_pin(vr)) { + SOF_SYSCALL_CALLER_CHECK(SOF_SYSUSER_INFRA); + return NULL; + } - if (vregion_verify_pin(vr)) { + if (vregion_owner_check(vr)) ptr = z_impl_vregion_alloc_coherent_align(vr, size, alignment); - vregion_unpin(vr); - } + else + ptr = vregion_lifetime_alloc_align(vr, size, alignment, true); + + vregion_unpin(vr); return ptr; } @@ -48,12 +62,17 @@ static inline void *z_vrfy_vregion_alloc_coherent_align(struct vregion *vr, static inline void z_vrfy_vregion_free(struct vregion *vr, void *ptr) { - SOF_SYSCALL_CALLER_CHECK(SOF_SYSUSER_INFRA); + if (!vregion_verify_pin(vr)) { + SOF_SYSCALL_CALLER_CHECK(SOF_SYSUSER_INFRA); + return; + } - if (vregion_verify_pin(vr)) { + if (vregion_owner_check(vr)) z_impl_vregion_free(vr, ptr); - vregion_unpin(vr); - } + else + vregion_lifetime_free(vr, ptr); + + vregion_unpin(vr); } #include From f4205b1d5ae85711e0069103bc118948aeb4f2ab Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Wed, 25 Nov 2026 12:35:39 +0200 Subject: [PATCH 10/12] module: use LL module resources in user mode only for registered modules The LL and IPC user threads decided from the processing domain in the comp_dev whether to run the module resource functions in user mode or through the mod_dp_*() system calls. The comp_dev and module objects of a DP module are in DP memory, so a DP thread could mark its module as an LL module, or hand over a made-up module through dev->mod, and an IPC user thread would then walk a resource pool and allocation context that the DP thread controls, in user mode, with access to all LL memory. Register the LL modules in LL memory when they are created in user mode, in module_adapter_mem_alloc(), and remove them when their memory is freed. The user-mode path is now taken only for registered modules. Any other module goes to the system calls, whose validators reject LL modules and modules without a live vregion. The processing domain is still checked first, so that DP threads, which cannot access the list, use the system calls for their own module. Signed-off-by: Kai Vehmanen --- src/audio/module_adapter/module/generic.c | 91 ++++++++++++++++++- src/audio/module_adapter/module_adapter.c | 19 ++++ .../sof/audio/module_adapter/module/generic.h | 28 ++++++ 3 files changed, 135 insertions(+), 3 deletions(-) diff --git a/src/audio/module_adapter/module/generic.c b/src/audio/module_adapter/module/generic.c index 219054dbd1de..5a82f1dbb56f 100644 --- a/src/audio/module_adapter/module/generic.c +++ b/src/audio/module_adapter/module/generic.c @@ -605,6 +605,83 @@ int z_impl_mod_free(struct processing_module *mod, const void *ptr) EXPORT_SYMBOL(z_impl_mod_free); #if defined(__ZEPHYR__) && defined(CONFIG_SOF_FULL_ZEPHYR_APPLICATION) +#if CONFIG_SOF_USERSPACE_LL +/* an LL module whose resources the LL and IPC user threads use in user mode */ +struct mod_res_user_entry { + struct list_item list; + struct processing_module *mod; +}; + +/* the LL modules registered with mod_res_user_add(), under mod_res_ulock */ +static APP_SYSUSER_DATA struct list_item mod_res_user_list = LIST_INIT(mod_res_user_list); + +int mod_res_user_add(struct processing_module *mod) +{ + struct mod_res_user_entry *entry; + + if (!k_is_user_context()) + return -EPERM; + + /* the IPC user threads of all cores walk the list */ + entry = sof_heap_alloc(sof_sys_user_heap_get(), SOF_MEM_FLAG_USER | SOF_MEM_FLAG_COHERENT, + sizeof(*entry), 0); + if (!entry) + return -ENOMEM; + + entry->mod = mod; + + sys_mutex_lock(&mod_res_ulock, K_FOREVER); + list_item_append(&entry->list, &mod_res_user_list); + sys_mutex_unlock(&mod_res_ulock); + + return 0; +} + +void mod_res_user_remove(struct processing_module *mod) +{ + struct mod_res_user_entry *entry = NULL; + struct list_item *item; + + if (!k_is_user_context()) + return; + + sys_mutex_lock(&mod_res_ulock, K_FOREVER); + list_for_item(item, &mod_res_user_list) { + entry = container_of(item, struct mod_res_user_entry, list); + if (entry->mod == mod) { + list_item_del(item); + break; + } + entry = NULL; + } + sys_mutex_unlock(&mod_res_ulock); + + sof_heap_free(sof_sys_user_heap_get(), entry); +} + +static bool mod_res_user_listed(const struct processing_module *mod) +{ + struct mod_res_user_entry *entry; + struct list_item *item; + bool found = false; + + /* not an LL or IPC user thread */ + if (sys_mutex_lock(&mod_res_ulock, K_FOREVER)) + return false; + + list_for_item(item, &mod_res_user_list) { + entry = container_of(item, struct mod_res_user_entry, list); + if (entry->mod == mod) { + found = true; + break; + } + } + sys_mutex_unlock(&mod_res_ulock); + + return found; +} +#endif + /* * With CONFIG_SOF_USERSPACE_LL, the LL and IPC user threads use the resources * of LL modules in user mode: the module memory, its resource pool and the @@ -614,14 +691,22 @@ EXPORT_SYMBOL(z_impl_mod_free); * kernel structures behind their vregions. In kernel mode the system call * wrappers call the implementation directly. * - * The processing domain is user-writable, so a user thread can only pick the - * wrong path for itself: the system calls reject LL modules. + * The user-mode path is taken only for the LL modules registered in LL + * memory when they were created, not by the processing domain or other + * module data: the comp_dev and module objects of a DP module are in DP + * memory, so a DP thread could make them look like an LL module, or hand + * over a made-up module, whose resource pool the IPC user thread would then + * walk in user mode. Any other module goes to the system calls, which reject + * LL modules and modules without a live vregion. The processing domain is + * only checked first, so that DP threads, which have no access to the list, + * use the system calls for their own module. */ static bool mod_res_user(struct processing_module *mod) { #if CONFIG_SOF_USERSPACE_LL return k_is_user_context() && - mod->dev->ipc_config.proc_domain != COMP_PROCESSING_DOMAIN_DP; + mod->dev->ipc_config.proc_domain != COMP_PROCESSING_DOMAIN_DP && + mod_res_user_listed(mod); #else return false; #endif diff --git a/src/audio/module_adapter/module_adapter.c b/src/audio/module_adapter/module_adapter.c index 894e86e8a826..8dcd2082695b 100644 --- a/src/audio/module_adapter/module_adapter.c +++ b/src/audio/module_adapter/module_adapter.c @@ -187,11 +187,27 @@ struct processing_module *module_adapter_mem_alloc(const struct comp_driver *drv mod->dev = dev; dev->mod = mod; +#if CONFIG_SOF_USERSPACE_LL + /* an LL module in LL memory, its resources are used in user mode */ + if (k_is_user_context() && config->proc_domain != COMP_PROCESSING_DOMAIN_DP && + mod_res_user_add(mod) < 0) { + comp_cl_err(drv, "failed to register the module resources"); + goto eres; + } +#endif + /* the region of a DP module, from here and not from module memory */ *dp_vreg = use_ppl_alloc ? NULL : mod_vreg; return mod; +#if CONFIG_SOF_USERSPACE_LL +eres: + if (mod_vreg) + vregion_user_free(mod_vreg, dev); + else + sof_heap_free(mod_heap, dev); +#endif edev: if (!use_ppl_alloc && !mod_vreg) sof_heap_free(mod_heap, alloc); @@ -214,6 +230,9 @@ __cold static void module_adapter_mem_free(struct processing_module *mod) assert_can_be_cold(); + /* after the last module resource call */ + mod_res_user_remove(mod); + /* * In principle it shouldn't even be needed to free individual objects * on the module heap since we're freeing the heap itself too diff --git a/src/include/sof/audio/module_adapter/module/generic.h b/src/include/sof/audio/module_adapter/module/generic.h index 4d93ff1daff8..3038d497e61f 100644 --- a/src/include/sof/audio/module_adapter/module/generic.h +++ b/src/include/sof/audio/module_adapter/module/generic.h @@ -216,6 +216,34 @@ void *z_impl_mod_balloc_align(struct processing_module *mod, size_t size, size_t */ void mod_resource_init(struct processing_module *mod); +#if CONFIG_SOF_USERSPACE_LL +/** + * @brief Let the LL and IPC user threads use the resources of an LL module. + * + * In user mode only, for a module whose memory and resource pool are in LL + * memory. The module resource functions then run in user mode for @p mod, + * see mod_res_user() in generic.c, and use the system calls for any other + * module. + * + * @param mod Pointer to processing module. + * @return 0 on success or a negative error code. + */ +int mod_res_user_add(struct processing_module *mod); + +/** + * @brief Undo mod_res_user_add(), before the module memory is freed. + * @param mod Pointer to processing module. + */ +void mod_res_user_remove(struct processing_module *mod); +#else +static inline int mod_res_user_add(struct processing_module *mod) +{ + return 0; +} + +static inline void mod_res_user_remove(struct processing_module *mod) {} +#endif + /** * @brief Query module memory heap boundary and size. * @param mod Pointer to processing module. From fbd9bda7e610bf17a55c82668906720f51a8df47 Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Wed, 25 Nov 2026 12:46:58 +0200 Subject: [PATCH 11/12] zephyr: test: userspace: test the region owner and the LL module list Add cases for the owner of a region, the DP thread of a module. It allocates from and frees to the lifetime allocator of its own region with the vregion system calls, coherent memory too, and its requests are refused, without a fault, once the kernel runs the interim heap. The IPC user thread may still use that heap. A thread that is neither the owner nor an LL or IPC user thread is killed, also when the region is mapped for it, and the pins of the killed calls are released. The module resource functions only run in user mode for LL modules that were registered when they were created: a module that claims to be an LL module but is not registered goes to the DP system call, which kills the IPC user thread. The existing cases register their module. Signed-off-by: Kai Vehmanen --- zephyr/test/userspace/test_ll_user_heap.c | 113 ++++++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/zephyr/test/userspace/test_ll_user_heap.c b/zephyr/test/userspace/test_ll_user_heap.c index da0adde0f6a1..82f5bf1d4a28 100644 --- a/zephyr/test/userspace/test_ll_user_heap.c +++ b/zephyr/test/userspace/test_ll_user_heap.c @@ -20,6 +20,10 @@ * 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. + * + * Tests for the owner of a region, the DP thread of a module: it may use the + * lifetime allocator of its own region through the system calls, never the + * kernel interim heap, and other DP threads may not use the region at all. */ #include @@ -54,6 +58,7 @@ K_APPMEM_PARTITION_DEFINE(ll_user_heap_test_part); /* test objects that user threads write, so in a user partition */ K_APP_BMEM(ll_user_heap_test_part) static struct processing_module fake_mod; +K_APP_BMEM(ll_user_heap_test_part) static struct processing_module other_mod; K_APP_BMEM(ll_user_heap_test_part) static struct comp_dev fake_dev; K_APP_BMEM(ll_user_heap_test_part) static struct mod_alloc_ctx fake_alloc; K_APP_BMEM(ll_user_heap_test_part) static void *user_ptr; @@ -82,6 +87,10 @@ enum user_heap_test_case { UHEAP_MOD_DP_SYSCALL, /* call the module allocator in user mode with fake_mod */ UHEAP_MOD_USER_ALLOC, + /* register fake_mod as an LL module for the user-mode resource path */ + UHEAP_MOD_REGISTER, + /* call the module allocator in user mode with other_mod */ + UHEAP_MOD_OTHER_ALLOC, }; static void check_alloc(uint32_t flags, size_t bytes, size_t align) @@ -151,6 +160,12 @@ static void user_function(void *p1, void *p2, void *p3) case UHEAP_MOD_USER_ALLOC: (void)mod_alloc_ext(&fake_mod, SOF_MEM_FLAG_USER, 64, 0); break; + case UHEAP_MOD_REGISTER: + zassert_ok(mod_res_user_add(&fake_mod)); + return; + case UHEAP_MOD_OTHER_ALLOC: + (void)mod_alloc_ext(&other_mod, SOF_MEM_FLAG_USER, 64, 0); + break; default: zassert_unreachable("unknown test case"); } @@ -188,6 +203,20 @@ static void run_case(enum user_heap_test_case test_case, bool fault_allowed) run_user(user_function, test_case, false, fault_allowed); } +/* + * Register fake_mod as an LL module once, as LL modules are when they are + * created. It stays registered: a case may leave the resource lock with a + * faulted thread. + */ +static void fake_mod_register(void) +{ + static bool registered; + + if (!registered) + run_case(UHEAP_MOD_REGISTER, false); + registered = true; +} + static void *ll_user_heap_setup(void) { k_mem_domain_add_partition(zephyr_ll_mem_domain(), &ll_user_heap_test_part); @@ -316,11 +345,32 @@ ZTEST(userspace_ll_user_heap, mod_user_rejects_forged_heap) fake_alloc.heap = (struct k_heap *)kernel_only_words; fake_alloc.vreg = NULL; mod_resource_init(&fake_mod); + fake_mod_register(); /* the allocator runs in user mode and refuses the heap */ run_case(UHEAP_MOD_USER_ALLOC, true); } +ZTEST(userspace_ll_user_heap, mod_user_needs_registration) +{ + /* + * A module that claims to be an LL module, as a DP thread could make + * its own module look, but was not registered when it was created. + */ + memset(&other_mod, 0, sizeof(other_mod)); + memset(&fake_dev, 0, sizeof(fake_dev)); + other_mod.dev = &fake_dev; + fake_dev.mod = &other_mod; + other_mod.priv.resources.alloc = &fake_alloc; + fake_dev.ipc_config.proc_domain = COMP_PROCESSING_DOMAIN_LL; + fake_alloc.heap = zephyr_ll_user_heap(); + fake_alloc.vreg = NULL; + mod_resource_init(&other_mod); + + /* the IPC user thread uses the system call, which rejects LL modules */ + run_user(user_function, UHEAP_MOD_OTHER_ALLOC, true, true); +} + ZTEST_SUITE(userspace_ll_user_heap, sof_boot_test_standalone_predicate, ll_user_heap_setup, NULL, NULL, ll_user_heap_teardown); @@ -506,6 +556,7 @@ ZTEST(userspace_ll_fast_get, mod_fast_get_falls_back) fake_alloc.heap = zephyr_ll_user_heap(); fake_alloc.vreg = NULL; mod_resource_init(&fake_mod); + fake_mod_register(); run_fg_case(FG_MOD_GET, true, false); zassert_true(zephyr_ll_fg_contains(fg_ptr[0], DATA_SIZE)); @@ -571,6 +622,12 @@ enum vregion_heap_test_case { VHEAP_ALLOC_CORRUPTED, /* get the interim range */ VHEAP_INTERIM_GET, + /* allocate and free with the system calls */ + VHEAP_SYSCALL_ALLOC_FREE, + /* allocate with the system calls, expect a refusal */ + VHEAP_SYSCALL_ALLOC_REFUSED, + /* allocate with the system call */ + VHEAP_SYSCALL_ALLOC, }; static void check_vheap_alloc(bool coherent, size_t bytes, size_t align) @@ -652,6 +709,22 @@ static void vheap_user_function(void *p1, void *p2, void *p3) case VHEAP_INTERIM_GET: (void)vregion_interim_get(test_vreg, &start, &size); break; + case VHEAP_SYSCALL_ALLOC_FREE: + user_ptr = vregion_alloc(test_vreg, 64); + zassert_not_null(user_ptr); + vregion_free(test_vreg, user_ptr); + user_ptr = vregion_alloc_coherent(test_vreg, 64); + zassert_not_null(user_ptr); + zassert_false(sys_cache_is_ptr_cached(user_ptr)); + vregion_free(test_vreg, user_ptr); + return; + case VHEAP_SYSCALL_ALLOC_REFUSED: + zassert_is_null(vregion_alloc(test_vreg, 64)); + zassert_is_null(vregion_alloc_coherent(test_vreg, 64)); + return; + case VHEAP_SYSCALL_ALLOC: + (void)vregion_alloc(test_vreg, 64); + break; default: zassert_unreachable("unknown test case"); } @@ -845,6 +918,46 @@ ZTEST(userspace_vregion_user_heap, corrupted_metadata_faults_user_only) user_ptr = NULL; } +ZTEST(userspace_vregion_user_heap, owner_lifetime_only) +{ + /* a DP module region, the kernel runs its interim heap */ + test_vreg = vheap_vreg_create(0, false); + + /* the DP thread of the module, not an LL or IPC user thread */ + vregion_owner_set(test_vreg, &user_thread); + + run_vheap_case(VHEAP_SYSCALL_ALLOC_FREE, false, false); + + /* never the kernel interim heap */ + vregion_set_interim(test_vreg); + run_vheap_case(VHEAP_SYSCALL_ALLOC_REFUSED, false, false); + + /* the IPC user thread may */ + vregion_owner_set(test_vreg, NULL); + run_vheap_case(VHEAP_SYSCALL_ALLOC_FREE, true, false); + + vheap_vreg_destroy(test_vreg); +} + +ZTEST(userspace_vregion_user_heap, other_dp_thread_killed) +{ + struct vregion *own_vreg = vheap_vreg_create(0, false); + + /* the region of another module, also mapped for the caller */ + test_vreg = vheap_vreg_create(0, false); + vregion_owner_set(own_vreg, &user_thread); + + run_vheap_case(VHEAP_SYSCALL_ALLOC, false, true); + + /* no owner at all */ + vregion_owner_set(own_vreg, NULL); + run_vheap_case(VHEAP_SYSCALL_ALLOC, false, true); + + /* the pins of the killed calls are released */ + vheap_vreg_destroy(test_vreg); + vheap_vreg_destroy(own_vreg); +} + ZTEST_SUITE(userspace_vregion_user_heap, sof_boot_test_standalone_predicate, ll_user_heap_setup, NULL, NULL, ll_user_heap_teardown); From 1d9b96f0284ee82029548c83c783733a74cf2848 Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Wed, 25 Nov 2026 12:47:17 +0200 Subject: [PATCH 12/12] userspace: doc: describe the DP region owner and the LL module list Describe how the kernel keeps the region of a DP module and records its DP thread as the owner, which vregion system calls the owner may use, and that the LL and IPC user threads use the resources of registered LL modules only in user mode. Signed-off-by: Kai Vehmanen --- src/include/sof/userspace/README.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/include/sof/userspace/README.md b/src/include/sof/userspace/README.md index 7d2a5cb915a7..6b428cefd91a 100644 --- a/src/include/sof/userspace/README.md +++ b/src/include/sof/userspace/README.md @@ -140,6 +140,7 @@ from user-writable data such as `ipc_user->thread[]`. | Any user thread, including DP module threads | `cpu_get_id`, all module management syscalls (`mod_dp_*`), `ipc_msg_send`, `ipc_msg_list_remove`, `send_resource_notif`, `kpb_notifier_schedule` | | IPC user thread only | `ipc_compound_pre_start`, `ipc_compound_post_start`, `ipc_wait_for_compound_msg`, `lib_manager_free_module` | | LL user thread only | `scheduler_dp_ll_tick`, `scheduler_dp_kick` | +| LL or IPC user thread, or the owner DP thread of the region (lifetime allocator only) | `vregion_alloc_align`, `vregion_alloc_coherent_align`, `vregion_free` | | LL or IPC user thread | all other SOF syscalls | With `CONFIG_SOF_USERSPACE_APPLICATION`, the DP task list and task memory are writable by DP @@ -152,12 +153,23 @@ DP modules only get the syscalls needed to implement the module interface. That sending notifications: modules queue messages from `mod_ipc_msg_init()` with `ipc_msg_send()` and free them with `mod_ipc_msg_free()`, and `dp_task_run()` reports processing errors with `send_resource_notif()`. DP modules have no access to the other IPC -syscalls or to vregion, DMA, DAI or scheduler syscalls. +syscalls or to DMA, DAI or scheduler syscalls. + +The kernel creates the vregion of a DP module and passes it to `scheduler_dp_task_init()`, +which keeps a reference in the kernel-only task record and builds the heap partitions of the +DP memory domain from the bounds in the kernel-only `struct vregion`, not from the allocation +context in module memory. It also records the DP thread as the owner of the region +(`vregion_owner_set()`), until the task is freed. The vregion allocation syscalls accept the +owner for the lifetime allocator of its own region only (`vregion_owner_check()`): the kernel +never runs the interim heap for a DP thread, and any other DP thread is killed. Modules call the module resource functions without the `dp` prefix (`mod_alloc_ext()`, `mod_free()`, `mod_fast_get()` and so on), which are plain functions. For an LL module in the LL or IPC user thread they run in user mode, on the module's resource pool and the LL user -heap, under a `sys_mutex` in LL memory. `mod_fast_get()` then gets a shared read-only copy +heap, under a `sys_mutex` in LL memory. That path is only taken for the LL modules that +`module_adapter_mem_alloc()` registered in a list in LL memory when it created them in user +mode (`mod_res_user_add()`), not by the processing domain: the `comp_dev` and module objects +of a DP module are in DP memory, so a DP thread could make its module look like an LL module. `mod_fast_get()` then gets a shared read-only copy with the `fast_get_ll()` syscall, see below, or makes a private copy when the fast_get area is full. For DP modules, and in kernel code, they call the `mod_dp_*` syscalls. Those validators reject LL modules and DP modules whose allocation context has no