diff --git a/doc/sof.doxygen.in b/doc/sof.doxygen.in index 19a2ce47a063..54cc2c0ad202 100644 --- a/doc/sof.doxygen.in +++ b/doc/sof.doxygen.in @@ -56,7 +56,6 @@ PREDEFINED = "__attribute__(x)= " \ "__ZEPHYR__=1" \ "CONFIG_LLEXT=1" \ "CONFIG_LLEXT_TYPE_ELF_RELOCATABLE=1" \ - "CONFIG_SOF_USERSPACE_INTERFACE_ALLOC=1" \ "CONFIG_SOF_FULL_ZEPHYR_APPLICATION=1" \ "CONFIG_SOF_USERSPACE_USE_SHARED_HEAP=1" \ "CONFIG_SOF_TELEMETRY_PERFORMANCE_MEASUREMENTS=1" \ diff --git a/src/audio/module_adapter/module/generic.c b/src/audio/module_adapter/module/generic.c index 845ecc417f69..a2176be33f85 100644 --- a/src/audio/module_adapter/module/generic.c +++ b/src/audio/module_adapter/module/generic.c @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -32,13 +33,43 @@ LOG_MODULE_DECLARE(module_adapter, CONFIG_SOF_LOG_LEVEL); /* - * A single lock shared by all module resource pools. The resource API is only - * ever entered from supervisor context (the z_impl_* syscall bodies), so the - * lock does not need to live in the per-module, user-writable struct - a static - * kernel object serialises all pools. Contention is negligible because resource + * A single lock shared by the module resource pools that are used in + * supervisor mode, by kernel code and the mod_dp_*() system calls, so it does + * not need to live in the per-module, user-writable struct - a static kernel + * object serialises all pools. Contention is negligible because resource * bookkeeping only happens at module setup/teardown, not on the processing path. */ -static K_MUTEX_DEFINE(mod_res_lock); +static K_MUTEX_DEFINE(mod_res_klock); + +#if CONFIG_SOF_USERSPACE_LL +/* + * The pools of LL modules are only used in user mode, by the LL and IPC user + * threads, see mod_res_user(), and have their own lock in LL memory. + */ +static APP_SYSUSER_BSS SYS_MUTEX_DEFINE(mod_res_ulock); +#endif + +static void mod_res_lock(void) +{ +#if CONFIG_SOF_USERSPACE_LL + if (k_is_user_context()) { + sys_mutex_lock(&mod_res_ulock, K_FOREVER); + return; + } +#endif + k_mutex_lock(&mod_res_klock, K_FOREVER); +} + +static void mod_res_unlock(void) +{ +#if CONFIG_SOF_USERSPACE_LL + if (k_is_user_context()) { + sys_mutex_unlock(&mod_res_ulock); + return; + } +#endif + k_mutex_unlock(&mod_res_klock); +} /* * Configuration buffers of DP modules are in the module heap: DP modules @@ -261,18 +292,18 @@ void *z_impl_mod_balloc_align(struct processing_module *mod, size_t size, size_t struct module_resources *res = &mod->priv.resources; struct module_resource *container; - k_mutex_lock(&mod_res_lock, K_FOREVER); + mod_res_lock(); container = container_get(mod); if (!container) { - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return NULL; } if (!size) { comp_err(mod->dev, "requested allocation of 0 bytes."); container_put(mod, container); - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return NULL; } @@ -284,7 +315,7 @@ void *z_impl_mod_balloc_align(struct processing_module *mod, size_t size, size_t comp_err(mod->dev, "Failed to alloc %zu bytes %zu alignment for comp %#x.", size, alignment, dev_comp_id(mod->dev)); container_put(mod, container); - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return NULL; } /* Store reference to allocated memory */ @@ -296,7 +327,7 @@ void *z_impl_mod_balloc_align(struct processing_module *mod, size_t size, size_t if (res->heap_usage > res->heap_high_water_mark) res->heap_high_water_mark = res->heap_usage; - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); perf_data_update_module_resources(mod->dev); return ptr; } @@ -323,11 +354,11 @@ void *z_impl_mod_alloc_ext(struct processing_module *mod, uint32_t flags, size_t return NULL; } - k_mutex_lock(&mod_res_lock, K_FOREVER); + mod_res_lock(); container = container_get(mod); if (!container) { - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return NULL; } @@ -338,7 +369,7 @@ void *z_impl_mod_alloc_ext(struct processing_module *mod, uint32_t flags, size_t comp_err(mod->dev, "Failed to alloc %zu bytes %zu alignment for comp %#x.", size, alignment, dev_comp_id(mod->dev)); container_put(mod, container); - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return NULL; } /* Store reference to allocated memory */ @@ -350,7 +381,7 @@ void *z_impl_mod_alloc_ext(struct processing_module *mod, uint32_t flags, size_t if (res->heap_usage > res->heap_high_water_mark) res->heap_high_water_mark = res->heap_usage; - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); perf_data_update_module_resources(mod->dev); return ptr; } @@ -382,11 +413,11 @@ struct comp_data_blob_handler *z_impl_mod_data_blob_handler_new(struct processin struct comp_data_blob_handler *bhp; struct module_resource *container; - k_mutex_lock(&mod_res_lock, K_FOREVER); + mod_res_lock(); int ret = objpool_iterate(&res->objpool, mod_data_blob_find, &bhp); if (!ret) { - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); /* data blob already exists */ comp_warn(mod->dev, "Returning existing data blob"); return bhp; @@ -394,14 +425,14 @@ struct comp_data_blob_handler *z_impl_mod_data_blob_handler_new(struct processin container = container_get(mod); if (!container) { - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return NULL; } bhp = comp_data_blob_handler_new_ext(mod->dev, false, NULL, NULL); if (!bhp) { container_put(mod, container); - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return NULL; } @@ -409,7 +440,7 @@ struct comp_data_blob_handler *z_impl_mod_data_blob_handler_new(struct processin container->size = 0; container->type = MOD_RES_BLOB_HANDLER; - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return bhp; } EXPORT_SYMBOL(z_impl_mod_data_blob_handler_new); @@ -421,9 +452,9 @@ int z_impl_mod_data_blob_set(struct processing_module *mod, struct module_resources *res = &mod->priv.resources; struct comp_data_blob_handler *bhp = NULL; - k_mutex_lock(&mod_res_lock, K_FOREVER); + mod_res_lock(); int ret = objpool_iterate(&res->objpool, mod_data_blob_find, &bhp); - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); if (ret < 0) return ret; @@ -450,18 +481,18 @@ const void *z_impl_mod_fast_get(struct processing_module *mod, const void * cons struct module_resource *container; const void *ptr; - k_mutex_lock(&mod_res_lock, K_FOREVER); + mod_res_lock(); container = container_get(mod); if (!container) { - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return NULL; } ptr = fast_get(res->alloc, dram_ptr, size); if (!ptr) { container_put(mod, container); - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return NULL; } @@ -469,7 +500,7 @@ const void *z_impl_mod_fast_get(struct processing_module *mod, const void * cons container->size = 0; container->type = MOD_RES_FAST_GET; - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); return ptr; } EXPORT_SYMBOL(z_impl_mod_fast_get); @@ -547,10 +578,10 @@ int z_impl_mod_free(struct processing_module *mod, const void *ptr) /* Find which container holds this memory */ struct mod_res_cb_arg cb_arg = {mod, ptr}; - k_mutex_lock(&mod_res_lock, K_FOREVER); + mod_res_lock(); int ret = objpool_iterate(&res->objpool, mod_res_free, &cb_arg); - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); if (ret < 0) comp_err(mod->dev, "error: could not find memory pointed by %p", ptr); @@ -561,116 +592,303 @@ int z_impl_mod_free(struct processing_module *mod, const void *ptr) } EXPORT_SYMBOL(z_impl_mod_free); -#ifdef CONFIG_USERSPACE -#include +#if defined(__ZEPHYR__) && defined(CONFIG_SOF_FULL_ZEPHYR_APPLICATION) +/* + * 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 + * LL user heap are all in LL memory, and the kernel must not run the heap + * allocator on metadata that user threads can write. DP module resources are + * used through the mod_dp_*() system calls, as DP threads cannot access the + * 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. + */ +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; +#else + return false; +#endif +} + +void *mod_balloc_align(struct processing_module *mod, size_t size, size_t alignment) +{ + if (mod_res_user(mod)) + return z_impl_mod_balloc_align(mod, size, alignment); + + return mod_dp_balloc_align(mod, size, alignment); +} +EXPORT_SYMBOL(mod_balloc_align); + +void *mod_alloc_ext(struct processing_module *mod, uint32_t flags, size_t size, + size_t alignment) +{ + if (mod_res_user(mod)) + return z_impl_mod_alloc_ext(mod, flags, size, alignment); + + return mod_dp_alloc_ext(mod, flags, size, alignment); +} +EXPORT_SYMBOL(mod_alloc_ext); + +int mod_free(struct processing_module *mod, const void *ptr) +{ + if (mod_res_user(mod)) + return z_impl_mod_free(mod, ptr); + + return mod_dp_free(mod, ptr); +} +EXPORT_SYMBOL(mod_free); + +void mod_free_all(struct processing_module *mod) +{ + if (mod_res_user(mod)) + z_impl_mod_free_all(mod); + else + mod_dp_free_all(mod); +} +EXPORT_SYMBOL(mod_free_all); + +#if CONFIG_COMP_BLOB +struct comp_data_blob_handler *mod_data_blob_handler_new(struct processing_module *mod) +{ + if (mod_res_user(mod)) + return z_impl_mod_data_blob_handler_new(mod); + + return mod_dp_data_blob_handler_new(mod); +} +EXPORT_SYMBOL(mod_data_blob_handler_new); + +int mod_data_blob_set(struct processing_module *mod, + enum module_cfg_fragment_position pos, uint32_t data_offset_size, + const uint8_t *fragment, size_t fragment_size) +{ + if (mod_res_user(mod)) + return z_impl_mod_data_blob_set(mod, pos, data_offset_size, fragment, + fragment_size); + + return mod_dp_data_blob_set(mod, pos, data_offset_size, fragment, fragment_size); +} +EXPORT_SYMBOL(mod_data_blob_set); +#endif #if CONFIG_FAST_GET -const void *z_vrfy_mod_fast_get(struct processing_module *mod, const void * const dram_ptr, - size_t size) +#if CONFIG_SOF_USERSPACE_LL +/* + * fast_get() keeps its state in kernel memory, so LL modules in user mode + * get a private copy in the module memory instead of a shared one. The + * copy is a heap resource, so mod_fast_put() frees it with mod_free(). + */ +static const void *mod_fast_get_copy(struct processing_module *mod, + const void * const dram_ptr, size_t size) { - size_t h_size = 0; - uintptr_t h_start; + void *ptr = z_impl_mod_alloc_ext(mod, SOF_MEM_FLAG_USER, size, 0); - K_OOPS(K_SYSCALL_MEMORY_WRITE(mod, sizeof(*mod))); - mod_heap_info(mod, &h_size, &h_start); - if (h_size) - K_OOPS(K_SYSCALL_MEMORY_WRITE(h_start, h_size)); - K_OOPS(K_SYSCALL_MEMORY_READ(dram_ptr, size)); + if (!ptr) + return NULL; - return z_impl_mod_fast_get(mod, dram_ptr, size); + memcpy_s(ptr, size, dram_ptr, size); + dcache_writeback_region((__sparse_force void __sparse_cache *)ptr, size); + + return ptr; } -#include #endif -void *z_vrfy_mod_alloc_ext(struct processing_module *mod, uint32_t flags, size_t size, - size_t alignment) +const void *mod_fast_get(struct processing_module *mod, const void * const dram_ptr, + size_t size) { - size_t h_size = 0; - uintptr_t h_start; +#if CONFIG_SOF_USERSPACE_LL + if (mod_res_user(mod)) + return mod_fast_get_copy(mod, dram_ptr, size); +#endif - K_OOPS(K_SYSCALL_MEMORY_WRITE(mod, sizeof(*mod))); - mod_heap_info(mod, &h_size, &h_start); - if (h_size) - K_OOPS(K_SYSCALL_MEMORY_WRITE(h_start, h_size)); + return mod_dp_fast_get(mod, dram_ptr, size); +} +EXPORT_SYMBOL(mod_fast_get); +#endif + +void *z_impl_mod_dp_balloc_align(struct processing_module *mod, size_t size, size_t alignment) +{ + return z_impl_mod_balloc_align(mod, size, alignment); +} +void *z_impl_mod_dp_alloc_ext(struct processing_module *mod, uint32_t flags, size_t size, + size_t alignment) +{ return z_impl_mod_alloc_ext(mod, flags, size, alignment); } -#include -void *z_vrfy_mod_balloc_align(struct processing_module *mod, size_t size, size_t alignment) +int z_impl_mod_dp_free(struct processing_module *mod, const void *ptr) { - size_t h_size = 0; - uintptr_t h_start; + return z_impl_mod_free(mod, ptr); +} - K_OOPS(K_SYSCALL_MEMORY_WRITE(mod, sizeof(*mod))); - mod_heap_info(mod, &h_size, &h_start); - if (h_size) - K_OOPS(K_SYSCALL_MEMORY_WRITE(h_start, h_size)); +void z_impl_mod_dp_free_all(struct processing_module *mod) +{ + z_impl_mod_free_all(mod); +} - return z_impl_mod_balloc_align(mod, size, alignment); +#if CONFIG_COMP_BLOB +struct comp_data_blob_handler *z_impl_mod_dp_data_blob_handler_new(struct processing_module *mod) +{ + return z_impl_mod_data_blob_handler_new(mod); } -#include -int z_vrfy_mod_free(struct processing_module *mod, const void *ptr) +int z_impl_mod_dp_data_blob_set(struct processing_module *mod, + enum module_cfg_fragment_position pos, uint32_t data_offset_size, + const uint8_t *fragment, size_t fragment_size) +{ + return z_impl_mod_data_blob_set(mod, pos, data_offset_size, fragment, fragment_size); +} +#endif + +#if CONFIG_FAST_GET +const void *z_impl_mod_dp_fast_get(struct processing_module *mod, const void * const dram_ptr, + size_t size) +{ + return z_impl_mod_fast_get(mod, dram_ptr, size); +} +#endif +#endif /* __ZEPHYR__ && CONFIG_SOF_FULL_ZEPHYR_APPLICATION */ + +#ifdef CONFIG_USERSPACE +#include + +/* + * Checks shared by the mod_dp_*() validators. Returns a pinned vregion of the + * module, or NULL, to release with mod_dp_vrfy_done() after the call. + */ +static struct vregion *mod_dp_vrfy(struct processing_module *mod) { + struct vregion *vreg = NULL; size_t h_size = 0; uintptr_t h_start; K_OOPS(K_SYSCALL_MEMORY_WRITE(mod, sizeof(*mod))); +#if CONFIG_SOF_USERSPACE_LL + struct mod_alloc_ctx *alloc; + + /* + * LL modules use their resources in user mode. Only DP modules, + * whose allocation context uses a vregion, may get here, so the + * kernel never allocates from the LL user heap or from a heap that a + * user thread made up. + */ + K_OOPS(K_SYSCALL_MEMORY_READ(mod->dev, sizeof(*mod->dev))); + K_OOPS(mod->dev->ipc_config.proc_domain != COMP_PROCESSING_DOMAIN_DP); + alloc = mod->priv.resources.alloc; + K_OOPS(K_SYSCALL_MEMORY_READ(alloc, sizeof(*alloc))); + vreg = alloc->vreg; + K_OOPS(!vregion_verify_pin(vreg)); +#endif mod_heap_info(mod, &h_size, &h_start); - if (h_size) - K_OOPS(K_SYSCALL_MEMORY_WRITE(h_start, h_size)); + if (h_size && K_SYSCALL_MEMORY_WRITE(h_start, h_size)) { + if (vreg) + vregion_unpin(vreg); + K_OOPS(true); + } - return z_impl_mod_free(mod, ptr); + return vreg; } -#include -void z_vrfy_mod_free_all(struct processing_module *mod) +static void mod_dp_vrfy_done(struct vregion *vreg) { - size_t h_size = 0; - uintptr_t h_start; + if (vreg) + vregion_unpin(vreg); +} - K_OOPS(K_SYSCALL_MEMORY_WRITE(mod, sizeof(*mod))); - mod_heap_info(mod, &h_size, &h_start); - if (h_size) - K_OOPS(K_SYSCALL_MEMORY_WRITE(h_start, h_size)); +#if CONFIG_FAST_GET +const void *z_vrfy_mod_dp_fast_get(struct processing_module *mod, const void * const dram_ptr, + size_t size) +{ + struct vregion *vreg; + const void *ptr; - z_impl_mod_free_all(mod); + K_OOPS(K_SYSCALL_MEMORY_READ(dram_ptr, size)); + vreg = mod_dp_vrfy(mod); + ptr = z_impl_mod_dp_fast_get(mod, dram_ptr, size); + mod_dp_vrfy_done(vreg); + + return ptr; +} +#include +#endif + +void *z_vrfy_mod_dp_alloc_ext(struct processing_module *mod, uint32_t flags, size_t size, + size_t alignment) +{ + struct vregion *vreg = mod_dp_vrfy(mod); + void *ptr = z_impl_mod_dp_alloc_ext(mod, flags, size, alignment); + + mod_dp_vrfy_done(vreg); + + return ptr; +} +#include + +void *z_vrfy_mod_dp_balloc_align(struct processing_module *mod, size_t size, size_t alignment) +{ + struct vregion *vreg = mod_dp_vrfy(mod); + void *ptr = z_impl_mod_dp_balloc_align(mod, size, alignment); + + mod_dp_vrfy_done(vreg); + + return ptr; +} +#include + +int z_vrfy_mod_dp_free(struct processing_module *mod, const void *ptr) +{ + struct vregion *vreg = mod_dp_vrfy(mod); + int ret = z_impl_mod_dp_free(mod, ptr); + + mod_dp_vrfy_done(vreg); + + return ret; +} +#include + +void z_vrfy_mod_dp_free_all(struct processing_module *mod) +{ + struct vregion *vreg = mod_dp_vrfy(mod); + + z_impl_mod_dp_free_all(mod); + mod_dp_vrfy_done(vreg); } -#include +#include #if CONFIG_COMP_BLOB -struct comp_data_blob_handler *z_vrfy_mod_data_blob_handler_new(struct processing_module *mod) +struct comp_data_blob_handler *z_vrfy_mod_dp_data_blob_handler_new(struct processing_module *mod) { - size_t h_size = 0; - uintptr_t h_start; + struct vregion *vreg = mod_dp_vrfy(mod); + struct comp_data_blob_handler *bhp = z_impl_mod_dp_data_blob_handler_new(mod); - K_OOPS(K_SYSCALL_MEMORY_WRITE(mod, sizeof(*mod))); - mod_heap_info(mod, &h_size, &h_start); - if (h_size) - K_OOPS(K_SYSCALL_MEMORY_WRITE(h_start, h_size)); + mod_dp_vrfy_done(vreg); - return z_impl_mod_data_blob_handler_new(mod); + return bhp; } -#include +#include -int z_vrfy_mod_data_blob_set(struct processing_module *mod, - enum module_cfg_fragment_position pos, uint32_t data_offset_size, - const uint8_t *fragment_in, size_t fragment_size) +int z_vrfy_mod_dp_data_blob_set(struct processing_module *mod, + enum module_cfg_fragment_position pos, uint32_t data_offset_size, + const uint8_t *fragment_in, size_t fragment_size) { - size_t h_size = 0; - uintptr_t h_start; + struct vregion *vreg; + int ret; - K_OOPS(K_SYSCALL_MEMORY_WRITE(mod, sizeof(*mod))); - mod_heap_info(mod, &h_size, &h_start); - if (h_size) - K_OOPS(K_SYSCALL_MEMORY_WRITE(h_start, h_size)); if (fragment_size) K_OOPS(K_SYSCALL_MEMORY_READ(fragment_in, fragment_size)); + vreg = mod_dp_vrfy(mod); + ret = z_impl_mod_dp_data_blob_set(mod, pos, data_offset_size, fragment_in, + fragment_size); + mod_dp_vrfy_done(vreg); - return z_impl_mod_data_blob_set(mod, pos, data_offset_size, fragment_in, fragment_size); + return ret; } -#include +#include #endif #endif @@ -852,10 +1070,10 @@ __cold void z_impl_mod_free_all(struct processing_module *mod) assert_can_be_cold(); - k_mutex_lock(&mod_res_lock, K_FOREVER); + mod_res_lock(); objpool_iterate(&res->objpool, mod_res_free, &cb_arg); objpool_prune(&res->objpool); - k_mutex_unlock(&mod_res_lock); + mod_res_unlock(); /* Make sure resource lists and accounting are reset */ mod_resource_init(mod); diff --git a/src/include/sof/audio/module_adapter/module/generic.h b/src/include/sof/audio/module_adapter/module/generic.h index 52369bc7e92c..4d93ff1daff8 100644 --- a/src/include/sof/audio/module_adapter/module/generic.h +++ b/src/include/sof/audio/module_adapter/module/generic.h @@ -196,7 +196,15 @@ int module_init(struct processing_module *mod); * @return Pointer to allocated buffer, or NULL on failure. */ #if defined(__ZEPHYR__) && defined(CONFIG_SOF_FULL_ZEPHYR_APPLICATION) -__syscall void *mod_balloc_align(struct processing_module *mod, size_t size, size_t alignment); +void *mod_balloc_align(struct processing_module *mod, size_t size, size_t alignment); +/* + * The mod_dp_*() system calls implement the module resource functions for + * DP modules in user threads, see mod_res_user() in generic.c. Modules call + * the functions without the dp prefix. + */ +__syscall void *mod_dp_balloc_align(struct processing_module *mod, size_t size, + size_t alignment); +void *z_impl_mod_balloc_align(struct processing_module *mod, size_t size, size_t alignment); #else void *z_impl_mod_balloc_align(struct processing_module *mod, size_t size, size_t alignment); #define mod_balloc_align z_impl_mod_balloc_align @@ -229,21 +237,30 @@ void mod_heap_info(struct processing_module *mod, size_t *size, uintptr_t *start * @return Pointer to allocated memory, or NULL on failure. */ #if defined(__ZEPHYR__) && defined(CONFIG_SOF_FULL_ZEPHYR_APPLICATION) -__syscall void *mod_alloc_ext(struct processing_module *mod, uint32_t flags, size_t size, - size_t alignment); +void *mod_alloc_ext(struct processing_module *mod, uint32_t flags, size_t size, + size_t alignment); /** * @brief Free a memory block previously allocated for a module. * @param mod Pointer to processing module. * @param ptr Pointer to memory to free. * @return 0 on success, negative error code on failure. */ -__syscall int mod_free(struct processing_module *mod, const void *ptr); +int mod_free(struct processing_module *mod, const void *ptr); /** * @brief Free all heap resources currently tracked for a module. * @param mod Pointer to processing module. */ -__syscall void mod_free_all(struct processing_module *mod); +void mod_free_all(struct processing_module *mod); + +__syscall void *mod_dp_alloc_ext(struct processing_module *mod, uint32_t flags, size_t size, + size_t alignment); +__syscall int mod_dp_free(struct processing_module *mod, const void *ptr); +__syscall void mod_dp_free_all(struct processing_module *mod); +void *z_impl_mod_alloc_ext(struct processing_module *mod, uint32_t flags, size_t size, + size_t alignment); +int z_impl_mod_free(struct processing_module *mod, const void *ptr); +void z_impl_mod_free_all(struct processing_module *mod); #else void *z_impl_mod_alloc_ext(struct processing_module *mod, uint32_t flags, size_t size, size_t alignment); @@ -375,15 +392,26 @@ static inline void mod_ipc_msg_free(struct processing_module *mod, /** * \brief Module-managed wrapper for comp_data_blob_handler_new_ext(). */ -__syscall struct comp_data_blob_handler *mod_data_blob_handler_new(struct processing_module *mod); +struct comp_data_blob_handler *mod_data_blob_handler_new(struct processing_module *mod); /** * \brief Module-managed wrapper for comp_data_blob_set(). * * Note, that only one data blob per module is allowed. */ -__syscall int mod_data_blob_set(struct processing_module *mod, - enum module_cfg_fragment_position pos, uint32_t data_offset_size, - const uint8_t *fragment, size_t fragment_size); +int mod_data_blob_set(struct processing_module *mod, + enum module_cfg_fragment_position pos, uint32_t data_offset_size, + const uint8_t *fragment, size_t fragment_size); + +__syscall struct comp_data_blob_handler * +mod_dp_data_blob_handler_new(struct processing_module *mod); +__syscall int mod_dp_data_blob_set(struct processing_module *mod, + enum module_cfg_fragment_position pos, + uint32_t data_offset_size, const uint8_t *fragment, + size_t fragment_size); +struct comp_data_blob_handler *z_impl_mod_data_blob_handler_new(struct processing_module *mod); +int z_impl_mod_data_blob_set(struct processing_module *mod, + enum module_cfg_fragment_position pos, uint32_t data_offset_size, + const uint8_t *fragment, size_t fragment_size); #else struct comp_data_blob_handler *z_impl_mod_data_blob_handler_new(struct processing_module *mod); int z_impl_mod_data_blob_set(struct processing_module *mod, @@ -396,8 +424,12 @@ void mod_data_blob_handler_free(struct processing_module *mod, struct comp_data_ #endif #if CONFIG_FAST_GET #if defined(__ZEPHYR__) && defined(CONFIG_SOF_FULL_ZEPHYR_APPLICATION) -__syscall const void *mod_fast_get(struct processing_module *mod, const void * const dram_ptr, - size_t size); +const void *mod_fast_get(struct processing_module *mod, const void * const dram_ptr, + size_t size); +__syscall const void *mod_dp_fast_get(struct processing_module *mod, + const void * const dram_ptr, size_t size); +const void *z_impl_mod_fast_get(struct processing_module *mod, const void * const dram_ptr, + size_t size); #else const void *z_impl_mod_fast_get(struct processing_module *mod, const void * const dram_ptr, size_t size); diff --git a/src/include/sof/schedule/ll_schedule.h b/src/include/sof/schedule/ll_schedule.h index 2e667daed5ac..7d00ec5b2ab0 100644 --- a/src/include/sof/schedule/ll_schedule.h +++ b/src/include/sof/schedule/ll_schedule.h @@ -93,6 +93,65 @@ struct k_heap; * @return Pointer to the k_heap instance. */ struct k_heap *zephyr_ll_user_heap(void); + +/** @brief Usage counters of the LL user heap */ +struct zephyr_ll_user_heap_stats { + size_t allocated_bytes; /**< bytes allocated now */ + size_t max_allocated_bytes; /**< most bytes allocated at a time */ + uint32_t fail_count; /**< failed allocations */ +}; + +/** + * @brief Initialise the LL user heap allocator on its memory. + * + * Kernel context only, called once at boot. + * @param[in] mem Start of the heap memory, uncached alias. + * @param[in] bytes Size of the heap memory. + */ +void zephyr_ll_user_heap_init(void *mem, size_t bytes); + +/** + * @brief Allocate from the LL user heap. + * + * Runs the heap allocator in the calling context. User threads of the LL + * memory domain call it directly, kernel code must not use it, since the + * heap metadata is user-writable. + * @param[in] flags SOF_MEM_FLAG_COHERENT for an uncached pointer. + * @param[in] bytes Size in bytes. + * @param[in] alignment Required alignment in bytes, 0 for the cache line size. + * @return Pointer to the memory, or NULL on failure. + */ +void *zephyr_ll_user_heap_alloc(uint32_t flags, size_t bytes, size_t alignment); + +/** + * @brief Free memory allocated with zephyr_ll_user_heap_alloc(). + * + * Same context rules as zephyr_ll_user_heap_alloc(). Faults the calling + * thread if @p ptr is not in the heap. + * @param[in] ptr Memory to free, cached or uncached alias, or NULL. + */ +void zephyr_ll_user_heap_free(void *ptr); + +/** + * @brief Copy the usage counters of the LL user heap. + * + * The counters are in user-writable memory, so treat them as untrusted + * numbers. Callable from any context. + * @param[out] stats The counters. + */ +void zephyr_ll_user_heap_stats_get(struct zephyr_ll_user_heap_stats *stats); + +#if CONFIG_SOF_BOOT_TEST_STANDALONE +struct sys_heap; +struct sys_mutex; + +/** + * @brief Get the allocator state of the LL user heap, for tests. + * @param[out] heap The heap, in LL memory. + * @param[out] lock The heap lock, in LL memory. + */ +void zephyr_ll_user_heap_test_get(struct sys_heap **heap, struct sys_mutex **lock); +#endif #endif /* CONFIG_SOF_USERSPACE_LL */ /* ll tracing */ diff --git a/src/include/sof/schedule/ll_schedule_domain.h b/src/include/sof/schedule/ll_schedule_domain.h index a9b91daa5b18..890d6a5d3e8f 100644 --- a/src/include/sof/schedule/ll_schedule_domain.h +++ b/src/include/sof/schedule/ll_schedule_domain.h @@ -212,11 +212,10 @@ static inline struct ll_schedule_domain *dma_domain_get(void) struct task *zephyr_ll_task_alloc(void); /** - * @brief Verify that a pointer belongs to the user-space LL heap. - * @param[in] heap Heap handle to check. - * @return true if valid, false otherwise. + * @brief Get the size of the LL user heap memory. + * @return Size in bytes. */ -bool zephyr_ll_user_heap_verify(struct k_heap *heap); +size_t zephyr_ll_user_heap_size(void); /** * @brief Initialize user-space memory partitions and access permissions for LL scheduling. diff --git a/src/include/sof/userspace/README.md b/src/include/sof/userspace/README.md index cf7e378602e8..4fa5a79f8541 100644 --- a/src/include/sof/userspace/README.md +++ b/src/include/sof/userspace/README.md @@ -87,8 +87,8 @@ and their kernel halves moved there, separately. Classification is grep-verifiable — see [Verifying the taxonomy](#verifying-the-taxonomy). > **`zephyr/syscall/` is the model to grow toward.** The Zephyr integration tree already -> collects the validating half of several syscalls in one place — `zephyr/syscall/alloc.c`, -> `cpu.c`, `vregion.c`, `dai.c`, `sof_dma.c` each hold the `z_vrfy_*` wrappers for their +> collects the validating half of several syscalls in one place — `zephyr/syscall/cpu.c`, +> `vregion.c`, `dai.c`, `sof_dma.c` each hold the `z_vrfy_*` wrappers for their > subsystem, physically separated from the `z_impl_*` logic (in `zephyr/lib/*.c` and > `src/kernel/lib/*.c`). This is exactly the boundary-tier separation this document promotes; the > migration opportunity is to move the *still-scattered* validators (IPC, module management, @@ -115,12 +115,11 @@ 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` | -| Heap alloc | `sof_heap_alloc`, `sof_heap_free` | `rtos/alloc.h` | `zephyr/syscall/alloc.c` / `zephyr/lib/alloc.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` | | 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` | -| Module management | `mod_balloc_align`, `mod_alloc_ext`, `mod_free`, `mod_free_all`, `mod_data_blob_handler_new`, `mod_data_blob_set`, `mod_fast_get` | `sof/audio/module_adapter/module/generic.h` | scattered: `audio/module_adapter/module/generic.c` | +| Module management | `mod_dp_balloc_align`, `mod_dp_alloc_ext`, `mod_dp_free`, `mod_dp_free_all`, `mod_dp_data_blob_handler_new`, `mod_dp_data_blob_set`, `mod_dp_fast_get` | `sof/audio/module_adapter/module/generic.h` | scattered: `audio/module_adapter/module/generic.c` | | Library manager | `lib_manager_free_module` | `sof/lib_manager.h` | scattered: `kernel/library_manager/lib_manager.c` | | Scheduling | `zephyr_ll_task_sem_alloc`, `zephyr_ll_task_sem_free`, `scheduler_dp_internal_free`, `scheduler_dp_ll_tick`, `scheduler_dp_kick` | `sof/schedule/ll_schedule_domain.h`, `sof/schedule/dp_schedule.h` | scattered: `kernel/schedule/zephyr_ll-kernel.c`, `kernel/schedule/zephyr_dp_schedule*-kernel.c` | | Debug | `debug_stream_slot_send_record` | `user/debug_stream_slot.h` | `kernel/debug/debug_stream/debug_stream_slot.c` | @@ -137,7 +136,7 @@ from user-writable data such as `ipc_user->thread[]`. | Allowed callers | Syscalls | |-----------------|----------| -| Any user thread, including DP module threads | `cpu_get_id`, all module management syscalls (`mod_*`), `ipc_msg_send`, `ipc_msg_list_remove`, `send_resource_notif`, `kpb_notifier_schedule` | +| 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 | all other SOF syscalls | @@ -152,7 +151,16 @@ 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 heap, vregion, DMA, DAI or scheduler syscalls. +syscalls or to vregion, DMA, DAI or scheduler syscalls. + +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 makes a private copy, as the +shared copies are kernel state. 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 +live vregion, and pin the vregion during the call. They still read the context from DP memory, +so a DP thread that rewrites it during the call is not stopped. A message sent by a user thread is never linked into the kernel send queue. `ipc_msg_send()` copies its header and payload (at most `CONFIG_SOF_IPC_USER_MSG_MAX_SIZE` bytes) once into @@ -179,7 +187,7 @@ With `CONFIG_SOF_USERSPACE_LL`, the memory of the LL and IPC user threads is one |------|---------------------------------|-----------| | Kernel RO area (`CONFIG_SOF_ZEPHYR_LL_KAREA_RO_SIZE`) | read-only | `zephyr_ll_karea_alloc(ZEPHYR_LL_KAREA_RO, ...)` | | Kernel RW area (`CONFIG_SOF_ZEPHYR_LL_KAREA_RW_SIZE`) | read-write | `zephyr_ll_karea_alloc(ZEPHYR_LL_KAREA_RW, ...)` | -| LL user heap (the rest) | read-write | `sof_heap_alloc(sof_sys_user_heap_get(), ...)` | +| LL user heap (the rest) | read-write | `sof_heap_alloc(sof_sys_user_heap_get(), ...)`, in user mode only | The kernel areas are for objects that kernel code creates and LL user threads access. Their allocator is a bump allocator with kernel-only state and no free, so use it for objects that @@ -218,12 +226,21 @@ User threads can write the `dma[]` array, so kernel code drives DMA through the wrappers, which take the Zephyr device from `struct sof_dma_kinfo` (`sof_dma_kdev()`), and never calls the Zephyr DMA API on `dma->z_dev`. -The LL user heap keeps its `sys_heap` metadata in user-writable memory. Kernel threads no -longer allocate from it or free to it; `CONFIG_SOF_ZEPHYR_LL_HEAP_KERNEL_TRACE` logs any use -by a kernel thread. User threads still allocate from it through the `sof_heap_alloc()` and -`sof_heap_free()` system calls, so the allocator still runs in supervisor mode on this -metadata. Kernel code still follows some pointers stored in user-writable memory, for example -`task->sch` and the domain `ops`. +The LL user heap keeps its `sys_heap` metadata in user-writable memory, so its allocator runs +in user mode only ([`schedule/zephyr_ll_user_heap.c`](../../../schedule/zephyr_ll_user_heap.c)). +The `sys_heap` object, its `sys_mutex` lock and the usage counters are in the system user +partition. The kernel initialises the heap at boot and does not parse it after that: in +kernel mode, including system calls, `sof_heap_alloc()` and `sof_heap_free()` refuse the LL +user heap and log the caller, and telemetry reads only the usage counters, as numbers. In user +mode they call the allocator directly, with no system call, and kill the thread for any other +heap. A user thread that corrupts the heap can only make LL and IPC user threads fault. +`zephyr_ll_user_heap()` returns a kernel-only `struct k_heap` that is never initialised: its +address only selects the LL user heap. + +Large `fast_get()` copies for DP modules are taken from `vpage_alloc()` instead of the heap of +the module allocation context, which is the LL user heap, and mapped read-only into the domain +of each user. Kernel code still follows some pointers stored in user-writable memory, for +example `task->sch` and the domain `ops`. ## Memory-partition markers @@ -246,9 +263,8 @@ must never trust it — re-validate on every use. DP modules running under `SOF_USERSPACE_APPLICATION` access data through their per-module memory domain set up by the proxy or DP thread infrastructure, not through `APP_TASK_*` / `APP_SYSUSER_*` markers. See [`kernel/schedule/zephyr_ll_user.c`](../../../kernel/schedule/zephyr_ll_user.c): `zephyr_ll_user_heap()` -returns the address of the kernel-only heap object rather than a pointer stored in -user-writable memory, and `zephyr_ll_user_heap_verify()` checks the heap pointer that user -threads pass to the heap system calls. +returns the address of a kernel-only heap handle rather than a pointer stored in +user-writable memory. ## Kconfig hierarchy @@ -258,11 +274,9 @@ The userspace behaviour is assembled from a small option tree (source of truth: ```mermaid graph TD US["USERSPACE (Zephyr MMU)"] - US --> ALLOC[SOF_USERSPACE_INTERFACE_ALLOC] US --> DMA[SOF_USERSPACE_INTERFACE_DMA] US --> VREG["SOF_USERSPACE_INTERFACE_VREGION (needs SOF_VREGIONS)"] US --> LL[SOF_USERSPACE_LL] - LL -.selects.-> ALLOC LL -.selects.-> DMA LL -.selects if SOF_VREGIONS.-> VREG US --> SHEAP[SOF_USERSPACE_USE_SHARED_HEAP] @@ -277,7 +291,7 @@ graph TD Key options: - **`SOF_USERSPACE_LL`** — run LL pipelines in user threads (`depends on USERSPACE`; selects - the ALLOC/DMA/VREGION interfaces). This is what `ll_userspace_overlay.conf` turns on. + the DMA/VREGION interfaces). This is what `ll_userspace_overlay.conf` turns on. - **`SOF_USERSPACE_PROXY`** — run modules inside a proxy container that forwards kernel-side calls to user-privileged module code (selects the driver + shared heaps). - **`SOF_USERSPACE_APPLICATION`** — not user-settable; a shortcut for diff --git a/src/kernel/schedule/zephyr_ll_user.c b/src/kernel/schedule/zephyr_ll_user.c index 9c701928c7ca..5930a5da2cb1 100644 --- a/src/kernel/schedule/zephyr_ll_user.c +++ b/src/kernel/schedule/zephyr_ll_user.c @@ -24,7 +24,9 @@ LOG_MODULE_DECLARE(ll_schedule, CONFIG_SOF_LOG_LEVEL); * domain, the kernel RO area read-only. Kernel code allocates objects that * LL user threads must access from the kernel areas, see * zephyr_ll_karea_alloc(). The allocator state of those areas is kept in - * ll_mem_resources, which is kernel-only. + * ll_mem_resources, which is kernel-only. The heap allocator runs in user + * mode, see src/schedule/zephyr_ll_user_heap.c: the kernel initialises the + * heap at boot and does not parse its metadata after that. */ #define LL_REGION_SIZE CONFIG_SOF_ZEPHYR_SYS_USER_HEAP_SIZE #define LL_KAREA_RO_SIZE CONFIG_SOF_ZEPHYR_LL_KAREA_RO_SIZE @@ -53,7 +55,11 @@ struct zephyr_ll_karea_state { */ struct zephyr_ll_mem_resources { struct k_mem_domain mem_domain; /**< Memory domain for LL thread isolation */ - struct k_heap heap; /**< Heap allocator for LL scheduler memory */ + /** + * Handle of the LL user heap, only used for its address, see + * zephyr_ll_user_heap(). The heap itself is in LL memory. + */ + struct k_heap heap; struct zephyr_ll_karea_state karea[ZEPHYR_LL_KAREA_COUNT]; /**< Kernel-managed areas */ }; @@ -103,14 +109,8 @@ static void ll_region_init(void) rw->size = LL_KAREA_RW_SIZE; mem += LL_KAREA_RO_SIZE + LL_KAREA_RW_SIZE; - k_heap_init(&ll_mem_resources.heap, mem, LL_HEAP_SIZE); - - /* - * k_heap_init() does not set these, so set the values - * manually here - */ - ll_mem_resources.heap.heap.init_mem = mem; - ll_mem_resources.heap.heap.init_bytes = LL_HEAP_SIZE; + /* the only time the kernel writes the heap metadata */ + zephyr_ll_user_heap_init(mem, LL_HEAP_SIZE); if (ro->size) ll_region_map(ro->base, ro->size, K_MEM_PARTITION_P_RO_U_RO); @@ -206,26 +206,19 @@ void zephyr_ll_user_resources_init(void) k_panic(); } -/** - * Check if 'heap' is a valid heap pointer. - * - * Available only in kernel mode. - * - * @return true if valid - */ -bool zephyr_ll_user_heap_verify(struct k_heap *heap) +size_t zephyr_ll_user_heap_size(void) { - return heap == &ll_mem_resources.heap; + return LL_HEAP_SIZE; } /** * Returns heap object to use in user-space LL code. * - * Can be called from both kernel and user-space. The heap object itself is - * kernel-only, but its address is a link-time constant, so returning it - * does not read any memory. User threads only pass it to the - * sof_heap_alloc()/sof_heap_free() system calls, whose validators check it - * with zephyr_ll_user_heap_verify(). + * Can be called from both kernel and user-space. The returned object is a + * kernel-only handle that is never initialised as a heap: its address, + * a link-time constant, selects the LL user heap in sof_heap_alloc() and + * sof_heap_free(), which then call zephyr_ll_user_heap_alloc() and + * zephyr_ll_user_heap_free(). * * Do not cache the pointer in user-writable memory for kernel use: kernel * code must call this function, so it never trusts a stored copy. diff --git a/src/schedule/CMakeLists.txt b/src/schedule/CMakeLists.txt index ee9ceb32ef9d..59310d73a198 100644 --- a/src/schedule/CMakeLists.txt +++ b/src/schedule/CMakeLists.txt @@ -20,6 +20,10 @@ zephyr_library_sources( zephyr_domain.c ) +zephyr_library_sources_ifdef(CONFIG_SOF_USERSPACE_LL + zephyr_ll_user_heap.c +) + if (CONFIG_SOC_ACP_6_0) # Zephyr DMA domain should only be used with zephyr_ll if (CONFIG_DMA_DOMAIN) diff --git a/src/schedule/zephyr_ll_user_heap.c b/src/schedule/zephyr_ll_user_heap.c new file mode 100644 index 000000000000..bff111071e8f --- /dev/null +++ b/src/schedule/zephyr_ll_user_heap.c @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: BSD-3-Clause +// +// Copyright(c) 2026 Intel Corporation. + +/* + * Allocator of the LL user heap, the user part of the LL memory region. + * + * The heap metadata is in memory that LL and IPC user threads can write, so + * the allocator runs in user mode: kernel code only initialises the heap at + * boot and never parses it after that. The sys_heap object, its lock and the + * usage counters are in the system user partition, mapped only into the LL + * memory domain. The lock is a sys_mutex, which user threads can take. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +LOG_MODULE_DECLARE(mem_allocator, CONFIG_SOF_LOG_LEVEL); + +static APP_SYSUSER_BSS struct sys_heap ll_user_sys_heap; +static APP_SYSUSER_BSS SYS_MUTEX_DEFINE(ll_user_heap_lock); +static APP_SYSUSER_BSS struct zephyr_ll_user_heap_stats ll_user_heap_stats; + +void zephyr_ll_user_heap_init(void *mem, size_t bytes) +{ + __ASSERT(!k_is_user_context(), "kernel context only"); + + sys_heap_init(&ll_user_sys_heap, mem, bytes); + + /* sys_heap_init() does not set these */ + ll_user_sys_heap.init_mem = mem; + ll_user_sys_heap.init_bytes = bytes; +} + +void *zephyr_ll_user_heap_alloc(uint32_t flags, size_t bytes, size_t alignment) +{ + void *ptr; + int ret; + + /* + * 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 (bytes > SIZE_MAX - PLATFORM_DCACHE_ALIGN) + return NULL; + bytes = ALIGN_UP(bytes, PLATFORM_DCACHE_ALIGN); + + ret = sys_mutex_lock(&ll_user_heap_lock, K_FOREVER); + if (ret) + return NULL; + + ptr = sys_heap_aligned_alloc(&ll_user_sys_heap, alignment, bytes); + if (ptr) { + ll_user_heap_stats.allocated_bytes += sys_heap_usable_size(&ll_user_sys_heap, ptr); + ll_user_heap_stats.max_allocated_bytes = MAX(ll_user_heap_stats.max_allocated_bytes, + ll_user_heap_stats.allocated_bytes); + } else { + ll_user_heap_stats.fail_count++; + } + +#if CONFIG_SYS_HEAP_RUNTIME_STATS && CONFIG_IPC_MAJOR_4 + /* like the kernel heaps, see heap_alloc_aligned() in zephyr/lib/alloc.c */ + struct sys_memory_stats stats; + + sys_heap_runtime_stats_get(&ll_user_sys_heap, &stats); + LOG_INF("LL user heap allocated: %zu free: %zu max allocated: %zu", + stats.allocated_bytes, stats.free_bytes, stats.max_allocated_bytes); +#endif + + sys_mutex_unlock(&ll_user_heap_lock); + + if (ptr && !(flags & SOF_MEM_FLAG_COHERENT)) + ptr = (__sparse_force void *)sys_cache_cached_ptr_get(ptr); + + return ptr; +} + +/* bounds from user-writable memory, so for user-mode checks only */ +static bool ll_user_heap_owns(const void *ptr) +{ + void __sparse_cache *cptr = (__sparse_force void __sparse_cache *)ptr; + uintptr_t start = (uintptr_t)ll_user_sys_heap.init_mem; + uintptr_t addr = (uintptr_t)sys_cache_uncached_ptr_get(cptr); + + return addr >= start && addr - start < ll_user_sys_heap.init_bytes; +} + +void zephyr_ll_user_heap_free(void *ptr) +{ + size_t usable; + int ret; + + if (!ptr) + return; + + if (!ll_user_heap_owns(ptr)) { + k_oops(); + return; + } + + ret = sys_mutex_lock(&ll_user_heap_lock, K_FOREVER); + if (ret) + return; + + if (sys_cache_is_ptr_cached(ptr)) { + void __sparse_cache *cptr = (__sparse_force void __sparse_cache *)ptr; + void *uncached = sys_cache_uncached_ptr_get(cptr); + + sys_cache_data_flush_and_invd_range(ptr, + sys_heap_usable_size(&ll_user_sys_heap, + uncached)); + ptr = uncached; + } + + usable = sys_heap_usable_size(&ll_user_sys_heap, ptr); + ll_user_heap_stats.allocated_bytes -= MIN(usable, ll_user_heap_stats.allocated_bytes); + + sys_heap_free(&ll_user_sys_heap, ptr); + + sys_mutex_unlock(&ll_user_heap_lock); +} + +#if CONFIG_SOF_BOOT_TEST_STANDALONE +void zephyr_ll_user_heap_test_get(struct sys_heap **heap, struct sys_mutex **lock) +{ + *heap = &ll_user_sys_heap; + *lock = &ll_user_heap_lock; +} +#endif + +void zephyr_ll_user_heap_stats_get(struct zephyr_ll_user_heap_stats *stats) +{ + /* user-writable values, only copied as numbers */ + stats->allocated_bytes = ll_user_heap_stats.allocated_bytes; + stats->max_allocated_bytes = ll_user_heap_stats.max_allocated_bytes; + stats->fail_count = ll_user_heap_stats.fail_count; +} diff --git a/zephyr/CMakeLists.txt b/zephyr/CMakeLists.txt index ed9b620aba4a..ed1cdb42340e 100644 --- a/zephyr/CMakeLists.txt +++ b/zephyr/CMakeLists.txt @@ -631,8 +631,6 @@ zephyr_syscall_header(${SOF_SRC_PATH}/include/sof/schedule/dp_schedule.h) zephyr_syscall_header(${SOF_SRC_PATH}/include/sof/schedule/ll_schedule_domain.h) zephyr_syscall_header(${SOF_SRC_PATH}/include/ipc4/handler.h) zephyr_syscall_header(${SOF_SRC_PATH}/include/sof/ipc/msg.h) -zephyr_syscall_header(include/rtos/alloc.h) -zephyr_library_sources_ifdef(CONFIG_SOF_USERSPACE_INTERFACE_ALLOC syscall/alloc.c) zephyr_syscall_header(${SOF_SRC_PATH}/include/sof/lib/vregion.h) zephyr_library_sources_ifdef(CONFIG_SOF_USERSPACE_INTERFACE_VREGION syscall/vregion.c) zephyr_syscall_header(${SOF_SRC_PATH}/include/sof/lib/dai-zephyr.h) diff --git a/zephyr/Kconfig b/zephyr/Kconfig index 148374c533a8..bd0e1278f5ea 100644 --- a/zephyr/Kconfig +++ b/zephyr/Kconfig @@ -29,13 +29,6 @@ config SOF_USERSPACE_INTERFACE_DMA help Allow user-space threads to use the SOF DMA interface. -config SOF_USERSPACE_INTERFACE_ALLOC - bool "Enable SOF heap alloc interface to userspace threads" - depends on USERSPACE - help - Allow user-space threads to use sof_heap_alloc/sof_heap_free - as Zephyr system calls. - config SOF_USERSPACE_INTERFACE_VREGION bool "Enable SOF vregion interface to userspace threads" depends on USERSPACE @@ -47,14 +40,19 @@ config SOF_USERSPACE_INTERFACE_VREGION config SOF_USERSPACE_LL bool "Run Low-Latency pipelines in userspace threads" depends on USERSPACE - select SOF_USERSPACE_INTERFACE_ALLOC + # DP modules then use their resources through the mod_dp_*() system + # calls, which need the module vregion + depends on !ZEPHYR_DP_SCHEDULER || \ + (SOF_USERSPACE_APPLICATION && !SOF_USERSPACE_USE_DRIVER_HEAP) select SOF_USERSPACE_INTERFACE_DMA select SOF_USERSPACE_INTERFACE_VREGION if SOF_VREGIONS select UAOL_USERSPACE if UAOL_INTEL_ADSP help Run Low-Latency (LL) pipelines in userspace threads. This adds memory protection between operating system resources and - audio application threads. + audio application threads. With the DP scheduler, DP modules + must run in userspace with a vregion each, so the userspace + proxy and the driver heap are not supported. If unsure, select "N". config SOF_USERSPACE_SYSCALL_CALLER_CHECK @@ -205,16 +203,6 @@ config SOF_ZEPHYR_LL_KAREA_RO_SIZE SOF_ZEPHYR_SYS_USER_HEAP_SIZE. Must be a multiple of the MMU page size. -config SOF_ZEPHYR_LL_HEAP_KERNEL_TRACE - bool "Log LL user heap allocations made by kernel threads" - depends on SOF_USERSPACE_LL - help - Log every allocation from and free to the LL user heap that a - kernel thread makes, with its size and caller address. Kernel - code is being moved off this heap, whose metadata user threads - can write. Use this to find the remaining callers. Calls made by - user threads, including through system calls, are not logged. - config SOF_USERSPACE_PROXY bool "Use userspace proxy to support userspace modules" select SOF_USERSPACE_USE_DRIVER_HEAP diff --git a/zephyr/include/rtos/alloc.h b/zephyr/include/rtos/alloc.h index 7c712e85f6aa..686c994c540f 100644 --- a/zephyr/include/rtos/alloc.h +++ b/zephyr/include/rtos/alloc.h @@ -177,21 +177,14 @@ void l3_heap_save(void); * @param[in] alignment Required memory alignment in bytes. * @return Pointer to allocated buffer, or NULL on allocation failure. */ -#ifdef CONFIG_SOF_USERSPACE_INTERFACE_ALLOC -__syscall void *sof_heap_alloc(struct k_heap *heap, uint32_t flags, size_t bytes, - size_t alignment); +void *sof_heap_alloc(struct k_heap *heap, uint32_t flags, size_t bytes, + size_t alignment); /** * @brief Free memory allocated via sof_heap_alloc(). * @param[in,out] heap Target Zephyr k_heap. * @param[in,out] addr Address of allocated buffer to free. */ -__syscall void sof_heap_free(struct k_heap *heap, void *addr); -#include -#else -void *sof_heap_alloc(struct k_heap *heap, uint32_t flags, size_t bytes, - size_t alignment); void sof_heap_free(struct k_heap *heap, void *addr); -#endif /** * @brief Get the system kernel heap descriptor. diff --git a/zephyr/lib/alloc.c b/zephyr/lib/alloc.c index d87e621c8d0d..3fbafa158f14 100644 --- a/zephyr/lib/alloc.c +++ b/zephyr/lib/alloc.c @@ -646,7 +646,6 @@ void z_impl_sof_heap_free(struct k_heap *heap, void *addr) rfree(addr); } -#ifndef CONFIG_SOF_USERSPACE_INTERFACE_ALLOC void *sof_heap_alloc(struct k_heap *heap, uint32_t flags, size_t bytes, size_t alignment) { @@ -657,7 +656,6 @@ void sof_heap_free(struct k_heap *heap, void *addr) { z_impl_sof_heap_free(heap, addr); } -#endif /* CONFIG_SOF_USERSPACE_INTERFACE_ALLOC */ #else @@ -834,41 +832,25 @@ EXPORT_SYMBOL(rfree); * To match the fall-back SOF main heap all private heaps should also be in the * uncached address range. */ -#if CONFIG_SOF_ZEPHYR_LL_HEAP_KERNEL_TRACE -/* Log use of the LL user heap by kernel threads, see the Kconfig help */ -static void ll_heap_kernel_trace(const char *op, struct k_heap *heap, const void *ptr, - size_t bytes, const void *caller) +#ifdef CONFIG_SOF_USERSPACE_LL +/* + * The LL user heap metadata is in memory that user threads can write, so + * kernel code, including system calls made by user threads, must not run its + * allocator. Only LL and IPC user threads allocate from it, in user mode. + */ +static void ll_heap_kernel_refuse(const char *op, const void *ptr, size_t bytes, + const void *caller) { struct k_thread *thread = k_current_get(); - if (heap != zephyr_ll_user_heap() || (thread->base.user_options & K_USER)) - return; - - tr_warn(&zephyr_tr, "LL heap %s by kernel thread %s: %p %zu bytes, caller %p", op, - k_thread_name_get(thread) ? k_thread_name_get(thread) : "?", ptr, bytes, caller); -} -#else -static inline void ll_heap_kernel_trace(const char *op, struct k_heap *heap, const void *ptr, - size_t bytes, const void *caller) -{ + tr_err(&zephyr_tr, "LL user heap %s in kernel mode refused, thread %s: %p %zu bytes, caller %p", + op, k_thread_name_get(thread) ? k_thread_name_get(thread) : "?", ptr, bytes, + caller); } #endif -static void *sof_heap_alloc_impl(struct k_heap *heap, uint32_t flags, size_t bytes, - size_t alignment); - void *z_impl_sof_heap_alloc(struct k_heap *heap, uint32_t flags, size_t bytes, size_t alignment) -{ - void *ptr = sof_heap_alloc_impl(heap, flags, bytes, alignment); - - ll_heap_kernel_trace("alloc", heap, ptr, bytes, __builtin_return_address(0)); - - return ptr; -} - -static void *sof_heap_alloc_impl(struct k_heap *heap, uint32_t flags, size_t bytes, - size_t alignment) { #if CONFIG_SOF_USERSPACE_USE_SHARED_HEAP /* @@ -891,6 +873,13 @@ static void *sof_heap_alloc_impl(struct k_heap *heap, uint32_t flags, size_t byt heap = &sof_heap; } +#ifdef CONFIG_SOF_USERSPACE_LL + if (heap == zephyr_ll_user_heap()) { + ll_heap_kernel_refuse("alloc", NULL, bytes, __builtin_return_address(0)); + return NULL; + } +#endif + void *ptr; if (flags & SOF_MEM_FLAG_COHERENT) @@ -910,8 +899,6 @@ static void *sof_heap_alloc_impl(struct k_heap *heap, uint32_t flags, size_t byt void z_impl_sof_heap_free(struct k_heap *heap, void *addr) { - ll_heap_kernel_trace("free", heap, addr, 0, __builtin_return_address(0)); - #ifdef CONFIG_SOF_USERSPACE_LL /* * The kernel-managed LL areas are inside a kernel heap block and are @@ -923,6 +910,13 @@ void z_impl_sof_heap_free(struct k_heap *heap, void *addr) tr_err(&zephyr_tr, "%p is in a kernel LL area, not freed", addr); return; } + + if (heap == zephyr_ll_user_heap()) { + /* leaks the memory, but leaves the kernel heap intact */ + if (addr) + ll_heap_kernel_refuse("free", addr, 0, __builtin_return_address(0)); + return; + } #endif if (heap && addr && is_heap_pointer(heap, addr)) @@ -931,8 +925,6 @@ void z_impl_sof_heap_free(struct k_heap *heap, void *addr) rfree(addr); } -#ifndef CONFIG_SOF_USERSPACE_INTERFACE_ALLOC - /* * Putting these as inlines in alloc.h breaks Zephyr native * ztests like sof/test/ztest/unit/fast-get that include rtos/alloc.h @@ -943,15 +935,44 @@ void z_impl_sof_heap_free(struct k_heap *heap, void *addr) void *sof_heap_alloc(struct k_heap *heap, uint32_t flags, size_t bytes, size_t alignment) { +#ifdef CONFIG_SOF_USERSPACE_LL + /* the LL and IPC user threads only have the LL user heap */ + if (k_is_user_context()) { + if (heap != zephyr_ll_user_heap()) + k_oops(); + + return zephyr_ll_user_heap_alloc(flags, bytes, alignment); + } + + if (heap == zephyr_ll_user_heap()) { + ll_heap_kernel_refuse("alloc", NULL, bytes, __builtin_return_address(0)); + return NULL; + } +#endif + return z_impl_sof_heap_alloc(heap, flags, bytes, alignment); } void sof_heap_free(struct k_heap *heap, void *addr) { - return z_impl_sof_heap_free(heap, addr); -} +#ifdef CONFIG_SOF_USERSPACE_LL + if (k_is_user_context()) { + if (heap != zephyr_ll_user_heap()) + k_oops(); + + zephyr_ll_user_heap_free(addr); + return; + } + + if (heap == zephyr_ll_user_heap()) { + if (addr) + ll_heap_kernel_refuse("free", addr, 0, __builtin_return_address(0)); + return; + } +#endif -#endif /* CONFIG_SOF_USERSPACE_INTERFACE_ALLOC */ + z_impl_sof_heap_free(heap, addr); +} #endif /* CONFIG_SOF_NATIVE_SIM_HOST_HEAP */ #if CONFIG_L3_HEAP @@ -1040,6 +1061,27 @@ static void fill_one_heap_telemetry(struct sof_tel_heap_info *dst, struct k_heap #endif } +#ifdef CONFIG_SOF_USERSPACE_LL +/* + * The LL user heap metadata is user-writable, so do not parse it: report the + * counters that the user-mode allocator keeps. + */ +static void fill_ll_user_heap_telemetry(struct sof_tel_heap_info *dst, uint16_t fail_cnt) +{ + struct zephyr_ll_user_heap_stats stats; + size_t total = zephyr_ll_user_heap_size(); + + zephyr_ll_user_heap_stats_get(&stats); + + dst->heap_type = SOF_TEL_HEAP_LL_USER; + dst->alloc_fail_count = fail_cnt + stats.fail_count; + dst->total_bytes = (uint32_t)total; + dst->allocated_bytes = (uint32_t)MIN(stats.allocated_bytes, total); + dst->free_bytes = (uint32_t)(total - dst->allocated_bytes); + dst->max_allocated_bytes = (uint32_t)MIN(stats.max_allocated_bytes, total); +} +#endif + void telemetry_collect_mem_stats(struct sof_tel_mem_section *mem) { uint32_t free_heap_pages; @@ -1054,8 +1096,8 @@ void telemetry_collect_mem_stats(struct sof_tel_mem_section *mem) SOF_TEL_HEAP_SHARED, heap_fail_counts[TEL_HEAP_SHARED_IDX]); #endif #ifdef CONFIG_SOF_USERSPACE_LL - fill_one_heap_telemetry(&mem->heaps[TEL_HEAP_LL_USER_IDX], zephyr_ll_user_heap(), - SOF_TEL_HEAP_LL_USER, heap_fail_counts[TEL_HEAP_LL_USER_IDX]); + fill_ll_user_heap_telemetry(&mem->heaps[TEL_HEAP_LL_USER_IDX], + heap_fail_counts[TEL_HEAP_LL_USER_IDX]); #endif #if CONFIG_L3_HEAP fill_one_heap_telemetry(&mem->heaps[TEL_HEAP_L3_IMR_IDX], &l3_heap, diff --git a/zephyr/lib/fast-get.c b/zephyr/lib/fast-get.c index 9ea839ca3761..532552cb9f33 100644 --- a/zephyr/lib/fast-get.c +++ b/zephyr/lib/fast-get.c @@ -12,6 +12,9 @@ #include #include #include +#if CONFIG_SOF_USERSPACE_LL && CONFIG_SOF_VREGIONS +#include +#endif #include #include #include @@ -30,14 +33,48 @@ struct sof_fast_get_entry { }; struct sof_fast_get_data { +#if CONFIG_SOF_USERSPACE_LL + /* held while allocating large copies, see fast_get_large_alloc() */ + struct k_mutex lock; +#else struct k_spinlock lock; +#endif struct objpool_head pool; }; static struct sof_fast_get_data fast_get_data = { +#if CONFIG_SOF_USERSPACE_LL + .lock = Z_MUTEX_INITIALIZER(fast_get_data.lock), +#endif .pool.list = LIST_INIT(fast_get_data.pool.list), }; +#if CONFIG_SOF_USERSPACE_LL +typedef int fast_get_key_t; + +static fast_get_key_t fast_get_lock(void) +{ + return k_mutex_lock(&fast_get_data.lock, K_FOREVER); +} + +static void fast_get_unlock(fast_get_key_t key) +{ + k_mutex_unlock(&fast_get_data.lock); +} +#else +typedef k_spinlock_key_t fast_get_key_t; + +static fast_get_key_t fast_get_lock(void) +{ + return k_spin_lock(&fast_get_data.lock); +} + +static void fast_get_unlock(fast_get_key_t key) +{ + k_spin_unlock(&fast_get_data.lock, key); +} +#endif + #ifdef CONFIG_SOF_TELEMETRY_MEMORY static uint32_t fast_get_total_calls; static uint16_t fast_get_active_entries; @@ -138,22 +175,55 @@ static int fast_get_access_grant(struct k_mem_domain *mdom, void *addr, size_t s } #endif /* CONFIG_USERSPACE */ +/* large copies are page aligned and shared, see fast_get() */ +static bool fast_get_is_large(size_t size) +{ + return IS_ENABLED(CONFIG_USERSPACE) && size > FAST_GET_MAX_COPY_SIZE; +} + +#if CONFIG_SOF_USERSPACE_LL && CONFIG_SOF_VREGIONS +/* + * The heap of the allocation contexts is the LL user heap, which kernel code + * must not allocate from, since user threads can write its metadata. Take + * large copies, which are page aligned and mapped read-only into the memory + * domain of each user, from the page allocator instead. + */ +static void *fast_get_large_alloc(struct k_heap *heap, uint32_t flags, size_t size) +{ + return vpage_alloc(size / PAGE_SZ); +} + +static void fast_get_large_free(struct k_heap *heap, void *ptr) +{ + vpage_free(ptr); +} +#else +static void *fast_get_large_alloc(struct k_heap *heap, uint32_t flags, size_t size) +{ + return sof_heap_alloc(heap, flags, size, PAGE_SZ); +} + +static void fast_get_large_free(struct k_heap *heap, void *ptr) +{ + sof_heap_free(heap, ptr); +} +#endif + const void *fast_get(struct mod_alloc_ctx *alloc, const void *dram_ptr, size_t size) { struct k_heap *heap = alloc ? alloc->heap : NULL; #if CONFIG_USERSPACE bool current_is_userspace = thread_is_userspace(k_current_get()); #endif - struct sof_fast_get_data *data = &fast_get_data; uint32_t alloc_flags = SOF_MEM_FLAG_USER; struct sof_fast_get_entry *entry; size_t alloc_size, alloc_align; const void *alloc_ptr; - k_spinlock_key_t key; + fast_get_key_t key; void *ret; - key = k_spin_lock(&data->lock); - if (IS_ENABLED(CONFIG_USERSPACE) && size > FAST_GET_MAX_COPY_SIZE) { + key = fast_get_lock(); + if (fast_get_is_large(size)) { alloc_size = ALIGN_UP(size, PAGE_SZ); alloc_align = PAGE_SZ; alloc_flags |= SOF_MEM_FLAG_LARGE_BUFFER; @@ -246,6 +316,8 @@ const void *fast_get(struct mod_alloc_ctx *alloc, const void *dram_ptr, size_t s /* A userspace allocation, that won't be shared */ ret = vregion_alloc_align(alloc->vreg, alloc_size, alloc_align); + else if (fast_get_is_large(size)) + ret = fast_get_large_alloc(heap, alloc_flags, alloc_size); else ret = sof_heap_alloc(heap, alloc_flags, alloc_size, alloc_align); if (!ret) @@ -268,7 +340,7 @@ const void *fast_get(struct mod_alloc_ctx *alloc, const void *dram_ptr, size_t s if (err < 0) { LOG_ERR("failed to grant access err=%d", err); - sof_heap_free(heap, ret); + fast_get_large_free(heap, ret); ret = NULL; goto out; } @@ -291,7 +363,7 @@ const void *fast_get(struct mod_alloc_ctx *alloc, const void *dram_ptr, size_t s if (!ret) fast_get_fail_count++; #endif - k_spin_unlock(&data->lock, key); + fast_get_unlock(key); LOG_DBG("get %p, %p, size %u, refcnt %u", dram_ptr, ret, size, entry ? entry->refcount : 0); return ret; @@ -327,11 +399,10 @@ static bool fast_put_find_entry(void *data, void *arg) void fast_put(struct mod_alloc_ctx *alloc, struct k_mem_domain *mdom, const void *sram_ptr) { struct k_heap *heap = alloc ? alloc->heap : NULL; - struct sof_fast_get_data *data = &fast_get_data; struct sof_fast_get_entry *entry; - k_spinlock_key_t key; + fast_get_key_t key; - key = k_spin_lock(&fast_get_data.lock); + key = fast_get_lock(); struct fast_get_find find = { .ptr = sram_ptr, @@ -355,8 +426,14 @@ void fast_put(struct mod_alloc_ctx *alloc, struct k_mem_domain *mdom, const void fast_get_live_bytes = 0; #endif LOG_DBG("freeing buffer %p", sram_ptr); + /* + * Free pages while the domain still maps them: vpage_free() + * writes back and invalidates the cache in the current domain. + */ if (alloc && alloc->vreg && entry->size <= FAST_GET_MAX_COPY_SIZE) vregion_free(alloc->vreg, entry->sram_ptr); + else if (fast_get_is_large(entry->size)) + fast_get_large_free(heap, entry->sram_ptr); else sof_heap_free(heap, entry->sram_ptr); } @@ -391,6 +468,6 @@ void fast_put(struct mod_alloc_ctx *alloc, struct k_mem_domain *mdom, const void out: LOG_DBG("put %p, DRAM %p size %u refcnt %u", sram_ptr, entry ? entry->dram_ptr : 0, entry ? entry->size : 0, entry ? entry->refcount : 0); - k_spin_unlock(&data->lock, key); + fast_get_unlock(key); } EXPORT_SYMBOL(fast_put); diff --git a/zephyr/syscall/alloc.c b/zephyr/syscall/alloc.c deleted file mode 100644 index fec10fc39762..000000000000 --- a/zephyr/syscall/alloc.c +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: BSD-3-Clause -// -// Copyright(c) 2026 Intel Corporation. - -#include -#include -#include -#include -#include - -static inline void *z_vrfy_sof_heap_alloc(struct k_heap *heap, uint32_t flags, - size_t bytes, size_t alignment) -{ - SOF_SYSCALL_CALLER_CHECK(SOF_SYSUSER_INFRA); - - /* only allow flags that are safe for user-space heap isolation */ - static const uint32_t allowed_flags = - SOF_MEM_FLAG_USER | SOF_MEM_FLAG_COHERENT | SOF_MEM_FLAG_DMA | - SOF_MEM_FLAG_LARGE_BUFFER; - - K_OOPS(flags & ~allowed_flags); - - /* user-space use of sof_heap_alloc() limited to this single heap */ - K_OOPS(!zephyr_ll_user_heap_verify(heap)); - - return z_impl_sof_heap_alloc(heap, flags, bytes, alignment); -} -#include - -static inline void z_vrfy_sof_heap_free(struct k_heap *heap, void *addr) -{ - SOF_SYSCALL_CALLER_CHECK(SOF_SYSUSER_INFRA); - - /* user-space use of sof_heap_alloc() limited to this single heap */ - K_OOPS(!zephyr_ll_user_heap_verify(heap)); - - if (addr) { - uintptr_t start = (uintptr_t)heap->heap.init_mem; - uintptr_t addr_uc = (uintptr_t)sys_cache_uncached_ptr_get(addr); - K_OOPS(addr_uc < start || addr_uc >= start + heap->heap.init_bytes); - K_OOPS(K_SYSCALL_MEMORY_WRITE(addr, 1)); - } - z_impl_sof_heap_free(heap, addr); -} -#include diff --git a/zephyr/test/CMakeLists.txt b/zephyr/test/CMakeLists.txt index c526860f769c..e2daa7ec235d 100644 --- a/zephyr/test/CMakeLists.txt +++ b/zephyr/test/CMakeLists.txt @@ -11,9 +11,6 @@ if(CONFIG_SOF_BOOT_TEST) zephyr_library_sources_ifdef(CONFIG_USERSPACE userspace/ksem.c ) - if(CONFIG_USERSPACE AND CONFIG_SOF_USERSPACE_INTERFACE_ALLOC AND NOT CONFIG_SOF_USERSPACE_LL) - zephyr_library_sources(userspace/test_heap_alloc.c) - endif() endif() if(CONFIG_SOF_BOOT_TEST_STANDALONE AND CONFIG_SOF_USERSPACE_INTERFACE_DMA) @@ -33,6 +30,7 @@ if(CONFIG_SOF_BOOT_TEST_STANDALONE AND CONFIG_SOF_USERSPACE_LL) zephyr_library_sources(userspace/test_ll_task.c) zephyr_library_sources(userspace/test_ll_karea.c) zephyr_library_sources(userspace/test_ipc_msg_queue.c) + zephyr_library_sources(userspace/test_ll_user_heap.c) endif() if(CONFIG_SOF_BOOT_TEST_STANDALONE AND CONFIG_SOF_USERSPACE_SYSCALL_CALLER_CHECK AND diff --git a/zephyr/test/userspace/README.md b/zephyr/test/userspace/README.md index 6c14300ee333..8e40d4812de7 100644 --- a/zephyr/test/userspace/README.md +++ b/zephyr/test/userspace/README.md @@ -19,6 +19,11 @@ Available tests: create tasks for audio pipeline logic. - test_mailbox.c - Test use of sof/mailbox.h interface from a Zephyr user thread. +- test_ll_user_heap.c + - Test the LL user heap, whose allocator runs in user mode. Checks + that kernel code refuses to use it, that a user thread corrupting + its metadata only faults user threads, and that the DP module + resource system calls reject LL modules and forged contexts. Building for Intel Panther Lake: ./scripts/xtensa-build-zephyr.py --cmake-args=-DCONFIG_SOF_BOOT_TEST_STANDALONE=y \ diff --git a/zephyr/test/userspace/test_heap_alloc.c b/zephyr/test/userspace/test_heap_alloc.c deleted file mode 100644 index e4dcb567b616..000000000000 --- a/zephyr/test/userspace/test_heap_alloc.c +++ /dev/null @@ -1,156 +0,0 @@ -// SPDX-License-Identifier: BSD-3-Clause -/* - * Copyright(c) 2026 Intel Corporation. - */ - -/* - * Test cases for sof_heap_alloc() / sof_heap_free() use from a Zephyr - * user-space thread. - */ - -#include -#include -#include - -#include -#include -#include -#include - -LOG_MODULE_DECLARE(sof_boot_test, LOG_LEVEL_DBG); - -#define USER_STACKSIZE 2048 - -static struct k_thread user_thread; -static K_THREAD_STACK_DEFINE(user_stack, USER_STACKSIZE); - -K_APPMEM_PARTITION_DEFINE(heap_alloc_test_part); -K_APP_BMEM(heap_alloc_test_part) static uint8_t non_heap_byte; - -enum heap_alloc_test_case { - HEAP_ALLOC_VALID, - HEAP_ALLOC_NULL_HEAP, - HEAP_ALLOC_FORBIDDEN_FLAGS, - HEAP_FREE_NON_HEAP_POINTER, - HEAP_FREE_INACCESSIBLE_POINTER, -}; - -static void user_function(void *p1, void *p2, void *p3) -{ - struct k_heap *heap = p1; - enum heap_alloc_test_case test_case = (enum heap_alloc_test_case)(uintptr_t)p2; - void *free_ptr = p3; - void *ptr; - - __ASSERT(k_is_user_context(), "isn't user"); - - LOG_INF("SOF thread %s (%s)", - k_is_user_context() ? "UserSpace!" : "privileged mode.", - CONFIG_BOARD_TARGET); - - switch (test_case) { - case HEAP_ALLOC_VALID: - ptr = sof_heap_alloc(heap, SOF_MEM_FLAG_USER, 128, 0); - zassert_not_null(ptr, "sof_heap_alloc returned NULL"); - sof_heap_free(heap, ptr); - return; - case HEAP_ALLOC_NULL_HEAP: - (void)sof_heap_alloc(NULL, SOF_MEM_FLAG_USER, 128, 0); - break; - case HEAP_ALLOC_FORBIDDEN_FLAGS: - (void)sof_heap_alloc(heap, SOF_MEM_FLAG_LARGE_BUFFER, 128, 0); - break; - case HEAP_FREE_NON_HEAP_POINTER: - sof_heap_free(heap, &non_heap_byte); - break; - case HEAP_FREE_INACCESSIBLE_POINTER: - sof_heap_free(heap, free_ptr); - break; - default: - zassert_unreachable("unknown heap allocation test case"); - } - - zassert_unreachable("syscall security check did not fault"); -} - -static void run_user_heap_alloc_case(enum heap_alloc_test_case test_case, struct k_heap *heap, - void *ptr, bool grant_ll_domain, bool expect_fault) -{ - int ret; - - k_thread_create(&user_thread, user_stack, USER_STACKSIZE, - user_function, heap, (void *)(uintptr_t)test_case, ptr, - -1, K_USER, K_FOREVER); - - if (grant_ll_domain) - k_mem_domain_add_thread(zephyr_ll_mem_domain(), &user_thread); - - if (expect_fault) - sof_boot_test_set_fault_valid(&user_thread); - - k_thread_start(&user_thread); - ret = k_thread_join(&user_thread, K_FOREVER); - zassert_equal(ret, 0, "user thread join failed: %d", ret); -} - -static void test_user_thread_heap_alloc(enum heap_alloc_test_case test_case) -{ - bool grant_ll_domain = true; - bool expect_fault = false; - void *ptr = NULL; - struct k_heap *heap; - - heap = zephyr_ll_user_heap(); - zassert_not_null(heap, "user heap not found"); - - switch (test_case) { - case HEAP_ALLOC_VALID: - break; - case HEAP_ALLOC_NULL_HEAP: - case HEAP_ALLOC_FORBIDDEN_FLAGS: - case HEAP_FREE_NON_HEAP_POINTER: - expect_fault = true; - break; - case HEAP_FREE_INACCESSIBLE_POINTER: - ptr = sof_heap_alloc(heap, SOF_MEM_FLAG_USER, 128, 0); - zassert_not_null(ptr, "kernel heap allocation failed"); - grant_ll_domain = false; - expect_fault = true; - break; - default: - zassert_unreachable("unknown heap allocation test case"); - } - - run_user_heap_alloc_case(test_case, heap, ptr, grant_ll_domain, expect_fault); - - sof_heap_free(heap, ptr); -} - -ZTEST(sof_boot, user_space_heap_alloc) -{ - test_user_thread_heap_alloc(HEAP_ALLOC_VALID); -} - -ZTEST(sof_boot, user_space_heap_alloc_rejects_null_heap) -{ - test_user_thread_heap_alloc(HEAP_ALLOC_NULL_HEAP); -} - -ZTEST(sof_boot, user_space_heap_alloc_rejects_forbidden_flags) -{ - test_user_thread_heap_alloc(HEAP_ALLOC_FORBIDDEN_FLAGS); -} - -ZTEST(sof_boot, user_space_heap_free_rejects_non_heap_pointer) -{ - k_mem_domain_add_partition(zephyr_ll_mem_domain(), &heap_alloc_test_part); - - test_user_thread_heap_alloc(HEAP_FREE_NON_HEAP_POINTER); - - k_mem_domain_remove_partition(zephyr_ll_mem_domain(), &heap_alloc_test_part); -} - -ZTEST(sof_boot, user_space_heap_free_rejects_inaccessible_pointer) -{ - test_user_thread_heap_alloc(HEAP_FREE_INACCESSIBLE_POINTER); -} diff --git a/zephyr/test/userspace/test_ll_task.c b/zephyr/test/userspace/test_ll_task.c index 2599ce0ec859..56d754ad890f 100644 --- a/zephyr/test/userspace/test_ll_task.c +++ b/zephyr/test/userspace/test_ll_task.c @@ -16,6 +16,8 @@ #include #include #include +#include +#include #include #include @@ -96,7 +98,13 @@ ZTEST(userspace_ll, ll_task_test) ll_task_test(); } -static void pipeline_check(void) +#define USER_STACKSIZE 4096 + +static struct k_thread user_thread; +static K_THREAD_STACK_DEFINE(user_stack, USER_STACKSIZE); + +/* the LL user heap allocator runs in user mode, so do this in a user thread */ +static void pipeline_check_user(void *p1, void *p2, void *p3) { struct pipeline *p; struct k_heap *heap; @@ -105,6 +113,8 @@ static void pipeline_check(void) uint32_t comp_id = 10; int ret; + zassert_true(k_is_user_context(), "isn't user"); + heap = zephyr_ll_user_heap(); zassert_not_null(heap, "user heap not found"); @@ -125,6 +135,23 @@ static void pipeline_check(void) zassert_ok(ret, "pipeline free failed"); } +static void pipeline_check(void) +{ + int ret; + + k_thread_create(&user_thread, user_stack, USER_STACKSIZE, + pipeline_check_user, NULL, NULL, NULL, -1, K_USER, K_FOREVER); + k_mem_domain_add_thread(zephyr_ll_mem_domain(), &user_thread); + pipeline_posn_grant_access(&user_thread); + /* pipelines are created by the IPC user thread, which may use vregions */ + sof_sysuser_thread_set(SOF_SYSUSER_IPC, PLATFORM_PRIMARY_CORE_ID, &user_thread); + + k_thread_start(&user_thread); + ret = k_thread_join(&user_thread, K_FOREVER); + sof_sysuser_thread_set(SOF_SYSUSER_IPC, PLATFORM_PRIMARY_CORE_ID, NULL); + zassert_equal(ret, 0, "user thread join failed: %d", ret); +} + ZTEST(userspace_ll, pipeline_check) { pipeline_check(); diff --git a/zephyr/test/userspace/test_ll_user_heap.c b/zephyr/test/userspace/test_ll_user_heap.c new file mode 100644 index 000000000000..e622671a10c8 --- /dev/null +++ b/zephyr/test/userspace/test_ll_user_heap.c @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: BSD-3-Clause +/* + * Copyright(c) 2026 Intel Corporation. + */ + +/* + * Tests for the LL user heap, whose allocator runs in user mode: LL user + * threads allocate from it without system calls, kernel code refuses to + * use it, and a user thread that corrupts its metadata can only fault + * itself. Also checks that the module resource system calls reject LL + * modules and forged allocation contexts. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +LOG_MODULE_DECLARE(sof_boot_test, LOG_LEVEL_DBG); + +#define USER_STACKSIZE 2048 +/* words of the heap header that the corruption case overwrites */ +#define HDR_WORDS 32 + +static struct k_thread user_thread; +static K_THREAD_STACK_DEFINE(user_stack, USER_STACKSIZE); + +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 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; +K_APP_BMEM(ll_user_heap_test_part) static uint32_t *user_hdr; +K_APP_BMEM(ll_user_heap_test_part) static uint32_t user_hdr_value; + +/* kernel-only: a forged heap or vregion handle points here */ +static uint32_t kernel_only_words[16]; + +static uint32_t saved_hdr[HDR_WORDS]; + +enum user_heap_test_case { + /* allocate, check and free memory */ + UHEAP_ALLOC_FREE, + /* allocate and keep the memory in user_ptr */ + UHEAP_ALLOC_KEEP, + /* free user_ptr */ + UHEAP_FREE_KEPT, + /* overwrite the heap header with user_hdr_value */ + UHEAP_CORRUPT, + /* allocate from the corrupted heap */ + UHEAP_ALLOC_CORRUPTED, + /* allocate from a heap that is not the LL user heap */ + UHEAP_ALLOC_OTHER_HEAP, + /* call the DP resource system call with fake_mod */ + UHEAP_MOD_DP_SYSCALL, + /* call the module allocator in user mode with fake_mod */ + UHEAP_MOD_USER_ALLOC, +}; + +static void check_alloc(uint32_t flags, size_t bytes, size_t align) +{ + struct zephyr_ll_user_heap_stats before, after; + struct k_heap *heap = zephyr_ll_user_heap(); + uint8_t *ptr; + + zephyr_ll_user_heap_stats_get(&before); + + ptr = sof_heap_alloc(heap, flags, bytes, align); + zassert_not_null(ptr); + zassert_equal((uintptr_t)ptr % MAX(align, PLATFORM_DCACHE_ALIGN), 0, "%p misaligned", + ptr); + /* only mirrored cached and uncached aliases can be told apart */ + if (IS_ENABLED(CONFIG_CACHE_MANAGEMENT) && + IS_ENABLED(CONFIG_CACHE_HAS_MIRRORED_MEMORY_REGIONS)) + zassert_equal(sys_cache_is_ptr_cached(ptr), !(flags & SOF_MEM_FLAG_COHERENT)); + memset(ptr, 0x5a, bytes); + + zephyr_ll_user_heap_stats_get(&after); + zassert_true(after.allocated_bytes >= before.allocated_bytes + bytes); + + sof_heap_free(heap, ptr); + + zephyr_ll_user_heap_stats_get(&after); + zassert_equal(after.allocated_bytes, before.allocated_bytes); +} + +static void user_function(void *p1, void *p2, void *p3) +{ + enum user_heap_test_case test_case = (enum user_heap_test_case)(uintptr_t)p1; + struct k_heap *heap = zephyr_ll_user_heap(); + int i; + + zassert_true(k_is_user_context(), "isn't user"); + + switch (test_case) { + case UHEAP_ALLOC_FREE: + check_alloc(SOF_MEM_FLAG_USER | SOF_MEM_FLAG_COHERENT, 100, 0); + check_alloc(SOF_MEM_FLAG_USER, 100, 256); + check_alloc(SOF_MEM_FLAG_USER, 3000, 4096); + return; + case UHEAP_ALLOC_KEEP: + user_ptr = sof_heap_alloc(heap, SOF_MEM_FLAG_USER, 64, 0); + zassert_not_null(user_ptr); + return; + case UHEAP_FREE_KEPT: + sof_heap_free(heap, user_ptr); + user_ptr = NULL; + return; + case UHEAP_CORRUPT: + /* the heap metadata is user-writable by design */ + for (i = 0; i < HDR_WORDS; i++) + user_hdr[i] = user_hdr_value; + return; + case UHEAP_ALLOC_CORRUPTED: + /* may fault, and may also return garbage */ + (void)sof_heap_alloc(heap, SOF_MEM_FLAG_USER, 64, 0); + return; + case UHEAP_ALLOC_OTHER_HEAP: + (void)sof_heap_alloc((struct k_heap *)kernel_only_words, SOF_MEM_FLAG_USER, 64, 0); + break; + case UHEAP_MOD_DP_SYSCALL: + (void)mod_dp_alloc_ext(&fake_mod, SOF_MEM_FLAG_USER, 64, 0); + break; + case UHEAP_MOD_USER_ALLOC: + (void)mod_alloc_ext(&fake_mod, SOF_MEM_FLAG_USER, 64, 0); + break; + default: + zassert_unreachable("unknown test case"); + } + + zassert_unreachable("user thread did not fault"); +} + +static void run_case(enum user_heap_test_case test_case, bool fault_allowed) +{ + int ret; + + k_thread_create(&user_thread, user_stack, USER_STACKSIZE, + user_function, (void *)(uintptr_t)test_case, NULL, NULL, + -1, K_USER, K_FOREVER); + k_mem_domain_add_thread(zephyr_ll_mem_domain(), &user_thread); + + if (fault_allowed) + sof_boot_test_set_fault_valid(&user_thread); + + k_thread_start(&user_thread); + ret = k_thread_join(&user_thread, K_FOREVER); + + sof_boot_test_set_fault_valid(NULL); + + zassert_equal(ret, 0, "user thread join failed: %d", ret); +} + +static void *ll_user_heap_setup(void) +{ + k_mem_domain_add_partition(zephyr_ll_mem_domain(), &ll_user_heap_test_part); + + return NULL; +} + +static void ll_user_heap_teardown(void *fixture) +{ + k_mem_domain_remove_partition(zephyr_ll_mem_domain(), &ll_user_heap_test_part); +} + +ZTEST(userspace_ll_user_heap, user_alloc_free) +{ + run_case(UHEAP_ALLOC_FREE, false); +} + +ZTEST(userspace_ll_user_heap, kernel_use_refused) +{ + struct zephyr_ll_user_heap_stats before, after; + struct k_heap *heap = zephyr_ll_user_heap(); + + run_case(UHEAP_ALLOC_KEEP, false); + zephyr_ll_user_heap_stats_get(&before); + + /* kernel code does not run the allocator: nothing is allocated or freed */ + zassert_is_null(sof_heap_alloc(heap, SOF_MEM_FLAG_USER, 64, 0)); + zassert_is_null(sof_heap_alloc(heap, SOF_MEM_FLAG_USER | SOF_MEM_FLAG_COHERENT, 64, 0)); + sof_heap_free(heap, user_ptr); + + zephyr_ll_user_heap_stats_get(&after); + zassert_equal(after.allocated_bytes, before.allocated_bytes); + + run_case(UHEAP_FREE_KEPT, false); +} + +ZTEST(userspace_ll_user_heap, user_rejects_other_heaps) +{ + run_case(UHEAP_ALLOC_OTHER_HEAP, true); +} + +ZTEST(userspace_ll_user_heap, corrupted_metadata_faults_user_only) +{ + struct zephyr_ll_user_heap_stats stats; + struct k_heap *heap = zephyr_ll_user_heap(); + struct sys_mutex *lock; + struct sys_heap *sh; +#ifdef CONFIG_SYS_MUTEX_IMPL_K_MUTEX + struct k_object *ko; +#endif + + zephyr_ll_user_heap_test_get(&sh, &lock); + user_hdr = (uint32_t *)sh->heap; + memcpy(saved_hdr, user_hdr, sizeof(saved_hdr)); + + /* + * 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_case(UHEAP_CORRUPT, false); + run_case(UHEAP_ALLOC_CORRUPTED, true); + + /* the paths that used to run the allocator in the kernel */ + zassert_is_null(sof_heap_alloc(heap, SOF_MEM_FLAG_USER, 64, 0)); + sof_heap_free(heap, (uint8_t *)user_hdr + 4096); + zephyr_ll_user_heap_stats_get(&stats); + + /* 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 + + memcpy(user_hdr, saved_hdr, sizeof(saved_hdr)); + + run_case(UHEAP_ALLOC_FREE, false); +} + +ZTEST(userspace_ll_user_heap, mod_dp_rejects_ll_module) +{ + memset(&fake_mod, 0, sizeof(fake_mod)); + memset(&fake_dev, 0, sizeof(fake_dev)); + fake_mod.dev = &fake_dev; + fake_dev.mod = &fake_mod; + fake_mod.priv.resources.alloc = &fake_alloc; + fake_alloc.heap = zephyr_ll_user_heap(); + fake_alloc.vreg = NULL; + + fake_dev.ipc_config.proc_domain = COMP_PROCESSING_DOMAIN_LL; + run_case(UHEAP_MOD_DP_SYSCALL, true); +} + +ZTEST(userspace_ll_user_heap, mod_dp_rejects_forged_context) +{ + memset(&fake_mod, 0, sizeof(fake_mod)); + memset(&fake_dev, 0, sizeof(fake_dev)); + fake_mod.dev = &fake_dev; + fake_dev.mod = &fake_mod; + fake_mod.priv.resources.alloc = &fake_alloc; + fake_dev.ipc_config.proc_domain = COMP_PROCESSING_DOMAIN_DP; + + /* a made-up heap, no vregion */ + fake_alloc.heap = (struct k_heap *)kernel_only_words; + fake_alloc.vreg = NULL; + run_case(UHEAP_MOD_DP_SYSCALL, true); + + /* a made-up vregion */ + fake_alloc.heap = NULL; + fake_alloc.vreg = (struct vregion *)kernel_only_words; + run_case(UHEAP_MOD_DP_SYSCALL, true); +} + +ZTEST(userspace_ll_user_heap, mod_user_rejects_forged_heap) +{ + memset(&fake_mod, 0, sizeof(fake_mod)); + memset(&fake_dev, 0, sizeof(fake_dev)); + fake_mod.dev = &fake_dev; + fake_dev.mod = &fake_mod; + fake_mod.priv.resources.alloc = &fake_alloc; + fake_dev.ipc_config.proc_domain = COMP_PROCESSING_DOMAIN_LL; + fake_alloc.heap = (struct k_heap *)kernel_only_words; + fake_alloc.vreg = NULL; + mod_resource_init(&fake_mod); + + /* the allocator runs in user mode and refuses the heap */ + run_case(UHEAP_MOD_USER_ALLOC, true); +} + +ZTEST_SUITE(userspace_ll_user_heap, sof_boot_test_standalone_predicate, ll_user_heap_setup, + NULL, NULL, ll_user_heap_teardown); + +/** + * SOF main has booted up and IPC handling is stopped. + * Run test suites with ztest_run_all. + */ +static int run_tests(void) +{ + ztest_run_test_suite(userspace_ll_user_heap, false, 1, 1, NULL); + return 0; +} + +SYS_INIT(run_tests, APPLICATION, 99);