From 0849833226b6539665f130dd70d7e226fdab6618 Mon Sep 17 00:00:00 2001 From: Liam Girdwood Date: Sun, 1 Nov 2026 19:53:38 +0000 Subject: [PATCH 1/3] zephyr: vpage: add an API to reserve virtual pages without mapping The LLEXT library manager needs virtual address space for loadable modules, but it maps the module sections itself, with different permissions for code, read-only and writable data. Using the shared virtual page allocator for that avoids a second, private virtual address range for modules. Split allocation into reserving a range of virtual pages and mapping physical pages to it, and export: - vpage_reserve() to reserve virtual pages without mapping them, - vpage_reserve_at() to reserve a range at a given address, needed to restore modules after the DSP has been powered down, because the allocator starts out empty on every boot, - vpage_release() to release a reserved range, - vpage_get_region() to get the region to map reserved pages in. vpage_alloc() and vpage_free() keep working as before. Co-developed-by: Jyri Sarha Signed-off-by: Jyri Sarha Signed-off-by: Liam Girdwood Co-Authored-By: Claude Opus 5.5 --- src/kernel/include/sof/kernel/lib/vpage.h | 46 +++ zephyr/lib/vpage.c | 383 +++++++++++++++++----- 2 files changed, 346 insertions(+), 83 deletions(-) diff --git a/src/kernel/include/sof/kernel/lib/vpage.h b/src/kernel/include/sof/kernel/lib/vpage.h index d05b8d3a3137..f4cd68496b49 100644 --- a/src/kernel/include/sof/kernel/lib/vpage.h +++ b/src/kernel/include/sof/kernel/lib/vpage.h @@ -11,6 +11,7 @@ #define __SOF_LIB_VPAGE_H__ #include +#include #include #ifdef __cplusplus @@ -41,6 +42,51 @@ void *vpage_alloc(unsigned int pages); */ void vpage_free(void *ptr); +/** + * @brief Reserve contiguous virtual pages. + * + * Reserves a specified number of contiguous virtual memory pages without + * mapping any physical pages to them. For users that need to map the pages + * themselves, e.g. with different permissions for parts of the range. + * + * @param[in] pages Number of pages (typically 4KB per page) to reserve. + * @return Pointer to the reserved virtual memory region, or NULL on failure. + */ +void *vpage_reserve(unsigned int pages); + +/** + * @brief Reserve contiguous virtual pages at a given address. + * + * Like vpage_reserve() but for a range at a fixed address, e.g. for users that + * had the range reserved before the DSP was powered down and are restored at + * the same address. + * + * @param[in] ptr Page aligned address of the first page to reserve. + * @param[in] pages Number of pages (typically 4KB per page) to reserve. + * @return 0 on success or a negative error code if any of the pages is already + * in use or outside of the virtual page region. + */ +int vpage_reserve_at(void *ptr, unsigned int pages); + +/** + * @brief Release reserved virtual pages. + * + * Releases virtual memory pages, reserved with vpage_reserve() or + * vpage_reserve_at(). The caller has to unmap any pages it has mapped first. + * + * @param[in] ptr Pointer to the first reserved page. + */ +void vpage_release(void *ptr); + +/** + * @brief Get the virtual memory region managed by the allocator. + * + * Users of vpage_reserve() need it to map pages in the reserved range. + * + * @return The region, or NULL if no virtual page region could be created. + */ +const struct sys_mm_drv_region *vpage_get_region(void); + /** @}*/ #ifdef __cplusplus diff --git a/zephyr/lib/vpage.c b/zephyr/lib/vpage.c index f6a4435eb0d5..a83dd8746dcc 100644 --- a/zephyr/lib/vpage.c +++ b/zephyr/lib/vpage.c @@ -69,17 +69,120 @@ static uint16_t vpage_min_free_pages = UINT16_MAX; static uint32_t vpage_alloc_fail_count; #endif +static inline void vpage_telemetry_record(int ret) +{ +#ifdef CONFIG_SOF_TELEMETRY_VREGION + if (ret < 0) + vpage_alloc_fail_count++; + else if (vpage_ctx.free_pages < vpage_min_free_pages) + vpage_min_free_pages = (uint16_t)vpage_ctx.free_pages; +#else + ARG_UNUSED(ret); +#endif +} + /** - * @brief Allocate and map virtual memory pages + * @brief Find the allocation element of a range of virtual memory pages * - * Allocates memory pages from the virtual page allocator. - * Maps physical memory pages to the virtual region as needed. + * @param ptr Pointer to the first page of the range. + * @param elem_idx Pointer to store the index of the allocation element. + * @retval number of pages in the range or 0 if not found. + */ +static unsigned int vpages_find(void *ptr, unsigned int *elem_idx) +{ + unsigned int alloc_idx, i; + + /* check for valid ptr which must be page aligned */ + CHECKIF(!IS_ALIGNED(ptr, CONFIG_MM_DRV_PAGE_SIZE)) { + LOG_ERR("error: invalid non aligned page pointer %p", ptr); + return 0; + } + + alloc_idx = (POINTER_TO_UINT(ptr) - POINTER_TO_UINT(vpage_ctx.virtual_region->addr)) / + CONFIG_MM_DRV_PAGE_SIZE; + + /* find the allocation element */ + for (i = 0; i < vpage_ctx.num_elems_in_use; i++) { + if (vpage_ctx.velems[i].vpage == alloc_idx) { + LOG_DBG("found allocation element %d pages %u vpage %u for ptr %p", + i, vpage_ctx.velems[i].pages, vpage_ctx.velems[i].vpage, ptr); + *elem_idx = i; + return vpage_ctx.velems[i].pages; + } + } + + LOG_ERR("error: invalid page pointer %p not found", ptr); + return 0; +} + +/** + * @brief Account for a reserved range of virtual memory pages * - * @param pages Number of pages to allocate. - * @param ptr Pointer to store the address of allocated pages. + * @param vaddr Pointer to the first page of the range. + * @param pages Number of pages in the range. + */ +static void vpages_add_elem(void *vaddr, unsigned int pages) +{ + vpage_ctx.free_pages -= pages; + + /* Elements are acquired densely, just use the next one */ + vpage_ctx.velems[vpage_ctx.num_elems_in_use].pages = pages; + vpage_ctx.velems[vpage_ctx.num_elems_in_use].vpage = + (POINTER_TO_UINT(vaddr) - + POINTER_TO_UINT(vpage_ctx.virtual_region->addr)) / + CONFIG_MM_DRV_PAGE_SIZE; + vpage_ctx.num_elems_in_use++; +} + +/** + * @brief Release a range of virtual memory pages + * + * Returns the virtual pages to the allocator. Doesn't touch any mappings. + * + * @param ptr Pointer to the first page of the range. + * @param elem_idx Index of the allocation element of the range. + * @param pages Number of pages in the range. * @retval 0 if successful. */ -__cold static int vpages_alloc_and_map(unsigned int pages, void **ptr) +static int vpages_release_elem(void *ptr, unsigned int elem_idx, unsigned int pages) +{ + int ret; + + /* free virtual blocks */ + ret = sys_mem_blocks_free_contiguous(&vpage_ctx.vpage_blocks, ptr, pages); + if (ret < 0) { + LOG_ERR("error: failed to free %u continuous virtual page blocks at %p, error %d", + pages, ptr, ret); + return ret; + } + + /* + * Keep the elements dense: move the last in-use element (num_elems_in_use - 1) + * over the released one and clear the last slot. + */ + vpage_ctx.num_elems_in_use--; + if (vpage_ctx.num_elems_in_use != elem_idx) + vpage_ctx.velems[elem_idx] = vpage_ctx.velems[vpage_ctx.num_elems_in_use]; + vpage_ctx.velems[vpage_ctx.num_elems_in_use].pages = 0; + vpage_ctx.velems[vpage_ctx.num_elems_in_use].vpage = 0; + + /* success update the free pages */ + vpage_ctx.free_pages += pages; + + return 0; +} + +/** + * @brief Reserve virtual memory pages + * + * Reserves memory pages from the virtual page allocator without mapping + * them. + * + * @param pages Number of pages to reserve. + * @param ptr Pointer to store the address of reserved pages. + * @retval 0 if successful. + */ +__cold static int vpages_reserve(unsigned int pages, void **ptr) { void *vaddr; int ret; @@ -120,12 +223,97 @@ __cold static int vpages_alloc_and_map(unsigned int pages, void **ptr) return ret; } + vpages_add_elem(vaddr, pages); + + /* return the virtual address */ + *ptr = vaddr; + + return 0; +} + +/** + * @brief Reserve a specific range of virtual memory pages + * + * Reserves memory pages at a given address, e.g. for users that had them + * reserved before the DSP was powered down and are restored at the same + * address. + * + * @param ptr Pointer to the first page to reserve. + * @param pages Number of pages to reserve. + * @retval 0 if successful. + */ +__cold static int vpages_reserve_at(void *ptr, unsigned int pages) +{ + uintptr_t start, end; + int ret; + + assert_can_be_cold(); + + /* the virtual region is missing if init found no space for it */ + if (!vpage_ctx.virtual_region) + return -ENODEV; + + if (!pages) + return 0; + + CHECKIF(!IS_ALIGNED(ptr, CONFIG_MM_DRV_PAGE_SIZE)) { + LOG_ERR("error: invalid non aligned page pointer %p", ptr); + return -EINVAL; + } + + start = POINTER_TO_UINT(vpage_ctx.virtual_region->addr); + end = start + vpage_ctx.virtual_region->size; + if (POINTER_TO_UINT(ptr) < start || POINTER_TO_UINT(ptr) >= end || + pages > (end - POINTER_TO_UINT(ptr)) / CONFIG_MM_DRV_PAGE_SIZE) { + LOG_ERR("error: %u pages at %p outside of the virtual region", pages, ptr); + return -EINVAL; + } + + /* check for allocation elements */ + if (vpage_ctx.num_elems_in_use >= VPAGE_MAX_ALLOCS) { + LOG_ERR("error: max allocation elements reached"); + return -ENOMEM; + } + + /* fails if any of the pages is already in use */ + ret = sys_mem_blocks_get(&vpage_ctx.vpage_blocks, ptr, pages); + if (ret < 0) { + LOG_ERR("error: failed to reserve %u virtual pages at %p, error %d", + pages, ptr, ret); + return ret; + } + + vpages_add_elem(ptr, pages); + + return 0; +} + +/** + * @brief Allocate and map virtual memory pages + * + * Allocates memory pages from the virtual page allocator. + * Maps physical memory pages to the virtual region as needed. + * + * @param pages Number of pages to allocate. + * @param ptr Pointer to store the address of allocated pages. + * @retval 0 if successful. + */ +__cold static int vpages_alloc_and_map(unsigned int pages, void **ptr) +{ + int ret; + + assert_can_be_cold(); + + ret = vpages_reserve(pages, ptr); + if (ret < 0 || !*ptr) + return ret; + /* map the virtual blocks in virtual region to free physical blocks */ - ret = sys_mm_drv_map_region_safe(vpage_ctx.virtual_region, vaddr, + ret = sys_mm_drv_map_region_safe(vpage_ctx.virtual_region, *ptr, 0, pages * CONFIG_MM_DRV_PAGE_SIZE, SYS_MM_MEM_PERM_RW); if (ret < 0) { LOG_ERR("error: failed to map virtual region %p to physical region %p, error %d", - vaddr, vpage_ctx.virtual_region->addr, ret); + *ptr, vpage_ctx.virtual_region->addr, ret); /* * The driver maps page by page and leaves already mapped pages (and @@ -133,30 +321,18 @@ __cold static int vpages_alloc_and_map(unsigned int pages, void **ptr) * exhausted. Release them so they do not leak. */ for (unsigned int i = 0; i < pages; i++) { - void *va = (uint8_t *)vaddr + i * CONFIG_MM_DRV_PAGE_SIZE; + void *va = (uint8_t *)*ptr + i * CONFIG_MM_DRV_PAGE_SIZE; if (!sys_mm_drv_page_phys_get(va, NULL)) sys_mm_drv_unmap_page(va); } - sys_mem_blocks_free_contiguous(&vpage_ctx.vpage_blocks, vaddr, pages); + /* the element just added is the last one */ + vpages_release_elem(*ptr, vpage_ctx.num_elems_in_use - 1, pages); + *ptr = NULL; return ret; } - /* success update the free pages */ - vpage_ctx.free_pages -= pages; - - /* Elements are acquired densely, just use the next one */ - vpage_ctx.velems[vpage_ctx.num_elems_in_use].pages = pages; - vpage_ctx.velems[vpage_ctx.num_elems_in_use].vpage = - (POINTER_TO_UINT(vaddr) - - POINTER_TO_UINT(vpage_ctx.virtual_region->addr)) / - CONFIG_MM_DRV_PAGE_SIZE; - vpage_ctx.num_elems_in_use++; - - /* return the virtual address */ - *ptr = vaddr; - return 0; } @@ -177,12 +353,7 @@ __cold void *vpage_alloc(unsigned int pages) k_mutex_lock(&vpage_ctx.lock, K_FOREVER); ret = vpages_alloc_and_map(pages, &ptr); -#ifdef CONFIG_SOF_TELEMETRY_VREGION - if (ret < 0) - vpage_alloc_fail_count++; - else if (vpage_ctx.free_pages < vpage_min_free_pages) - vpage_min_free_pages = (uint16_t)vpage_ctx.free_pages; -#endif + vpage_telemetry_record(ret); k_mutex_unlock(&vpage_ctx.lock); if (ret < 0) LOG_ERR("vpage_alloc failed %d for %d pages, total %d free %d", @@ -203,73 +374,27 @@ __cold void *vpage_alloc(unsigned int pages) * @retval 0 if successful. * @retval -EINVAL if ptr is invalid. */ -static int vpages_free_and_unmap(uintptr_t *ptr) +static int vpages_free_and_unmap(void *ptr) { - unsigned int alloc_idx, elem_idx; - unsigned int pages = 0; + unsigned int elem_idx, pages; int ret; if (!vpage_ctx.virtual_region) return -ENODEV; - /* check for valid ptr which must be page aligned */ - CHECKIF(!IS_ALIGNED(ptr, CONFIG_MM_DRV_PAGE_SIZE)) { - LOG_ERR("error: invalid non aligned page pointer %p", ptr); + pages = vpages_find(ptr, &elem_idx); + if (!pages) return -EINVAL; - } - - alloc_idx = (POINTER_TO_UINT(ptr) - POINTER_TO_UINT(vpage_ctx.virtual_region->addr)) / - CONFIG_MM_DRV_PAGE_SIZE; - - /* find the allocation element */ - for (elem_idx = 0; elem_idx < VPAGE_MAX_ALLOCS; elem_idx++) { - if (vpage_ctx.velems[elem_idx].pages > 0 && - vpage_ctx.velems[elem_idx].vpage == alloc_idx) { - pages = vpage_ctx.velems[elem_idx].pages; - - LOG_DBG("found allocation element %d pages %u vpage %u for ptr %p", - elem_idx, vpage_ctx.velems[elem_idx].pages, - vpage_ctx.velems[elem_idx].vpage, ptr); - break; - } - } - - /* check we found allocation element */ - CHECKIF(!pages) { - LOG_ERR("error: invalid page pointer %p not found", ptr); - return -EINVAL; - } /* unmap the pages from virtual region */ - ret = sys_mm_drv_unmap_region((void *)ptr, pages * CONFIG_MM_DRV_PAGE_SIZE); + ret = sys_mm_drv_unmap_region(ptr, pages * CONFIG_MM_DRV_PAGE_SIZE); if (ret < 0) { LOG_ERR("error: failed to unmap virtual region %p pages %u, error %d", ptr, pages, ret); return ret; } - /* free physical blocks */ - ret = sys_mem_blocks_free_contiguous(&vpage_ctx.vpage_blocks, ptr, pages); - if (ret < 0) { - LOG_ERR("error: failed to free %u continuous virtual page blocks at %p, error %d", - pages, ptr, ret); - return ret; - } - - /* - * Keep the elements dense: move the last in-use element (num_elems_in_use - 1) - * over the released one and clear the last slot. - */ - vpage_ctx.num_elems_in_use--; - if (vpage_ctx.num_elems_in_use != elem_idx) - vpage_ctx.velems[elem_idx] = vpage_ctx.velems[vpage_ctx.num_elems_in_use]; - vpage_ctx.velems[vpage_ctx.num_elems_in_use].pages = 0; - vpage_ctx.velems[vpage_ctx.num_elems_in_use].vpage = 0; - - /* success update the free pages */ - vpage_ctx.free_pages += pages; - - return ret; + return vpages_release_elem(ptr, elem_idx, pages); } /** @@ -283,7 +408,7 @@ void vpage_free(void *ptr) int ret; k_mutex_lock(&vpage_ctx.lock, K_FOREVER); - ret = vpages_free_and_unmap((uintptr_t *)ptr); + ret = vpages_free_and_unmap(ptr); k_mutex_unlock(&vpage_ctx.lock); if (!ret) { @@ -293,6 +418,98 @@ void vpage_free(void *ptr) } } +/** + * @brief Reserve virtual pages + * Reserves virtual memory pages without mapping them. + * + * @param pages Number of pages (usually 4kB large) to reserve. + * @retval NULL on reservation failure. + */ +__cold void *vpage_reserve(unsigned int pages) +{ + void *ptr = NULL; + int ret; + + assert_can_be_cold(); + + k_mutex_lock(&vpage_ctx.lock, K_FOREVER); + ret = vpages_reserve(pages, &ptr); + vpage_telemetry_record(ret); + k_mutex_unlock(&vpage_ctx.lock); + if (ret < 0) + LOG_ERR("vpage_reserve failed %d for %u pages, total %u free %u", + ret, pages, vpage_ctx.total_pages, vpage_ctx.free_pages); + else + LOG_INF("vpage_reserve ptr %p pages %u free %u/%u", ptr, pages, + vpage_ctx.free_pages, vpage_ctx.total_pages); + telemetry_notify_vregion_change(); + return ptr; +} + +/** + * @brief Reserve virtual pages at a given address + * Reserves virtual memory pages at a given address without mapping them. + * + * @param ptr Pointer to the first page to reserve. + * @param pages Number of pages (usually 4kB large) to reserve. + * @retval 0 if successful. + */ +__cold int vpage_reserve_at(void *ptr, unsigned int pages) +{ + int ret; + + assert_can_be_cold(); + + k_mutex_lock(&vpage_ctx.lock, K_FOREVER); + ret = vpages_reserve_at(ptr, pages); + vpage_telemetry_record(ret); + k_mutex_unlock(&vpage_ctx.lock); + if (ret < 0) + LOG_ERR("vpage_reserve_at failed %d for %u pages at %p, total %u free %u", + ret, pages, ptr, vpage_ctx.total_pages, vpage_ctx.free_pages); + else + LOG_INF("vpage_reserve_at ptr %p pages %u free %u/%u", ptr, pages, + vpage_ctx.free_pages, vpage_ctx.total_pages); + telemetry_notify_vregion_change(); + return ret; +} + +/** + * @brief Release reserved virtual pages + * Releases virtual memory pages, reserved with vpage_reserve() or + * vpage_reserve_at(). Any mappings have to be removed by the caller. + * + * @param ptr Pointer to the first reserved page. + */ +void vpage_release(void *ptr) +{ + unsigned int elem_idx, pages; + int ret = -ENODEV; + + k_mutex_lock(&vpage_ctx.lock, K_FOREVER); + if (vpage_ctx.virtual_region) { + pages = vpages_find(ptr, &elem_idx); + ret = pages ? vpages_release_elem(ptr, elem_idx, pages) : -EINVAL; + } + k_mutex_unlock(&vpage_ctx.lock); + + if (!ret) { + LOG_INF("vptr %p release free/total pages %u/%u", ptr, vpage_ctx.free_pages, + vpage_ctx.total_pages); + telemetry_notify_vregion_change(); + } +} + +/** + * @brief Get the virtual memory region of the allocator + * + * @retval the region or NULL if there is no virtual page region. + */ +const struct sys_mm_drv_region *vpage_get_region(void) +{ + return vpage_ctx.virtual_region; +} + #ifdef CONFIG_SOF_TELEMETRY_VREGION void telemetry_collect_vpage_stats(struct sof_tel_vregion_section *vsec) { From 3298216c4d28447ad1643e49a8963f6a5742a9e2 Mon Sep 17 00:00:00 2001 From: Liam Girdwood Date: Sun, 22 Nov 2026 19:35:46 +0000 Subject: [PATCH 2/3] zephyr: test: add vpage reservation tests Add boot tests for the vpage reservation APIs: - vpage_reserve() and vpage_release(): reserved pages are within the region and aren't mapped, a reserved range or a part of it can't be reserved again, and all pages are available again after release. - vpage_reserve_at() with ranges outside of the region or unaligned. Signed-off-by: Liam Girdwood Co-Authored-By: Claude Opus 5.5 --- zephyr/test/vpage.c | 72 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/zephyr/test/vpage.c b/zephyr/test/vpage.c index f6509d6ef03e..9e887829a634 100644 --- a/zephyr/test/vpage.c +++ b/zephyr/test/vpage.c @@ -11,7 +11,9 @@ #include #include +#include #include +#include #include LOG_MODULE_DECLARE(sof_boot_test, CONFIG_SOF_LOG_LEVEL); @@ -339,3 +341,73 @@ ZTEST(sof_boot, vpage_max_allocs) zassert_not_null(p[0]); vpage_free(p[0]); } + +/* Check that a range is inside the virtual page region */ +static void vpage_check_in_region(void *ptr, unsigned int pages) +{ + const struct sys_mm_drv_region *region = vpage_get_region(); + uintptr_t start = POINTER_TO_UINT(region->addr); + + zassert_true(IS_ALIGNED(ptr, VPAGE_TEST_PAGE_SIZE), "%p not page aligned", ptr); + zassert_true(POINTER_TO_UINT(ptr) >= start && + POINTER_TO_UINT(ptr) + pages * VPAGE_TEST_PAGE_SIZE <= start + region->size, + "%p outside of the region", ptr); +} + +/* Allocated pages are mapped, reserved pages aren't */ +ZTEST(sof_boot, vpage_reserve) +{ + unsigned int max = vpage_largest(); + uintptr_t phys; + void *p; + + zassert_not_null(vpage_get_region()); + zassert_is_null(vpage_reserve(0)); + + p = vpage_alloc(1); + zassert_not_null(p); + vpage_check_in_region(p, 1); + zassert_ok(sys_mm_drv_page_phys_get(p, &phys), "allocated page %p not mapped", p); + vpage_free(p); + + p = vpage_reserve(2); + zassert_not_null(p); + vpage_check_in_region(p, 2); + zassert_not_ok(sys_mm_drv_page_phys_get(p, &phys), "reserved page %p mapped", p); + zassert_not_ok(sys_mm_drv_page_phys_get((uint8_t *)p + VPAGE_TEST_PAGE_SIZE, &phys), + "reserved page %p mapped", (uint8_t *)p + VPAGE_TEST_PAGE_SIZE); + + /* neither the whole range nor a part of it can be reserved again */ + zassert_not_ok(vpage_reserve_at(p, 2)); + zassert_not_ok(vpage_reserve_at((uint8_t *)p + VPAGE_TEST_PAGE_SIZE, 1)); + + vpage_release(p); + + /* the whole range is free again after release */ + zassert_ok(vpage_reserve_at(p, 2)); + vpage_release(p); + + zassert_equal(vpage_largest(), max, "pages leaked after reserve/release"); +} + +/* vpage_reserve_at() only accepts page aligned ranges within the region */ +ZTEST(sof_boot, vpage_reserve_at_invalid) +{ + const struct sys_mm_drv_region *region = vpage_get_region(); + uint8_t *start, *end; + + zassert_not_null(region); + + start = region->addr; + end = start + region->size; + + zassert_ok(vpage_reserve_at(start, 0)); + zassert_equal(vpage_reserve_at(start - VPAGE_TEST_PAGE_SIZE, 1), -EINVAL); + zassert_equal(vpage_reserve_at(end, 1), -EINVAL); + zassert_equal(vpage_reserve_at(end + VPAGE_TEST_PAGE_SIZE, 1), -EINVAL); + zassert_equal(vpage_reserve_at(end - VPAGE_TEST_PAGE_SIZE, 2), -EINVAL); + + /* CHECKIF() asserts or skips the check in some configurations */ + if (!IS_ENABLED(CONFIG_ASSERT_ON_ERRORS) && !IS_ENABLED(CONFIG_NO_RUNTIME_CHECKS)) + zassert_equal(vpage_reserve_at(start + 1, 1), -EINVAL); +} From 5ef6acc89b97f3a8a33adc13347fe8823d053fb7 Mon Sep 17 00:00:00 2001 From: Liam Girdwood Date: Sun, 1 Nov 2026 19:55:09 +0000 Subject: [PATCH 3/3] library_manager: llext: place relocatable modules in virtual pages LLEXT modules are linked at build time to run at fixed addresses in a dedicated virtual memory region. Each module gets the addresses after the previous one, so all modules have to be built together, and the region has to be large enough for all modules even if only a few of them are used. Relocatable (ET_REL) modules don't need fixed addresses: they still carry all their relocations, so the build-time addresses are only placeholders. When such a module is linked for the first time, reserve virtual pages for it from the shared virtual page allocator and move all its sections, that are copied to SRAM, by the same offset into that range before calling llext_load(). The offset is a multiple of the largest section alignment, at least a page, so moving by it keeps the relative placement and alignment of all sections. References, that the linker has already resolved, stay valid, and LLEXT relocates the rest. Detached sections stay in DRAM and aren't moved. The ELF header and section header table are checked before use, as llext_load() only validates them after the sections have been moved. As before, a module is linked only once. The addresses stay assigned to the module until the firmware is rebooted, so re-instantiating a module only maps and copies it again. After the DSP has been powered down, the modules are restored from DRAM with the addresses they were linked for, so reserve those pages again, because the allocator starts out empty on every boot. Without that the allocator hands them out again, e.g. for a DP module heap. llext_load() returns the use count of an extension, if it has already been loaded, so only release the pages on a negative return value. Shared object (ET_DYN) modules can only run at their build-time addresses, they keep using the dedicated region, and so do relocatable modules if there is no virtual page region. The virtual page allocator kept L2 for the dedicated region, which left too few pages for the modules on platforms, where the image and the virtual heap use most of L2, e.g. 8 pages on WCL, so most modules failed to load with -ENOMEM. Keep L2 for it only when modules are built as shared objects. Co-developed-by: Jyri Sarha Signed-off-by: Jyri Sarha Signed-off-by: Liam Girdwood Co-Authored-By: Claude Opus 5.5 --- src/include/sof/lib_manager.h | 1 + src/kernel/library_manager/llext_manager.c | 162 ++++++++++++++++-- .../library_manager/llext_manager_dram.c | 18 +- zephyr/CMakeLists.txt | 6 +- zephyr/lib/vpage.c | 11 +- 5 files changed, 183 insertions(+), 15 deletions(-) diff --git a/src/include/sof/lib_manager.h b/src/include/sof/lib_manager.h index 70ca5f97102c..9c05ac340835 100644 --- a/src/include/sof/lib_manager.h +++ b/src/include/sof/lib_manager.h @@ -119,6 +119,7 @@ struct lib_manager_module { bool domain_dp; struct lib_manager_segment_desc segment[LIB_MANAGER_N_SEGMENTS]; struct lib_manager_segment_desc writable_merged; + struct lib_manager_segment_desc vma; /* Reserved virtual pages for ET_REL modules */ }; struct lib_manager_mod_ctx { diff --git a/src/kernel/library_manager/llext_manager.c b/src/kernel/library_manager/llext_manager.c index 02a0ef947a14..57c103bfed21 100644 --- a/src/kernel/library_manager/llext_manager.c +++ b/src/kernel/library_manager/llext_manager.c @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -298,21 +299,29 @@ __cold static int llext_manager_load_module(struct lib_manager_module *mctx) struct llext_loader *ldr = &mctx->ebl->loader; const struct llext *ext = mctx->llext; - - /* find dedicated virtual memory zone */ - const struct sys_mm_drv_region *virtual_memory_regions = sys_mm_drv_query_memory_regions(); const struct sys_mm_drv_region *virtual_region; - if (!virtual_memory_regions) - return -EFAULT; + if (mctx->vma.size) { + /* relocated to pages, reserved from the virtual page allocator */ + virtual_region = vpage_get_region(); + if (!virtual_region) + return -EFAULT; + } else { + /* find dedicated virtual memory zone */ + const struct sys_mm_drv_region *virtual_memory_regions = + sys_mm_drv_query_memory_regions(); - SYS_MM_DRV_MEMORY_REGION_FOREACH(virtual_memory_regions, virtual_region) { - if (virtual_region->attr == VIRTUAL_REGION_LLEXT_LIBRARIES_ATTR) - break; - } + if (!virtual_memory_regions) + return -EFAULT; - if (!virtual_region->size) - return -EFAULT; + SYS_MM_DRV_MEMORY_REGION_FOREACH(virtual_memory_regions, virtual_region) { + if (virtual_region->attr == VIRTUAL_REGION_LLEXT_LIBRARIES_ATTR) + break; + } + + if (!virtual_region->size) + return -EFAULT; + } /* Copy Code */ ret = llext_manager_load_data_from_storage(virtual_region, ldr, ext, LLEXT_MEM_TEXT, @@ -434,6 +443,120 @@ static bool llext_manager_section_detached(const elf_shdr_t *shdr) return shdr->sh_addr < SOF_MODULE_DRAM_LINK_END; } +/* + * Relocatable (ET_REL) modules are linked at placeholder addresses. Reserve + * virtual pages for all sections, that will be copied to SRAM, and move them + * there, keeping their relative placement, so that llext_load() relocates the + * module to run at those addresses. Detached sections stay in DRAM and keep + * their addresses. Shared object (ET_DYN) modules can only run at addresses, + * fixed at build time, they stay in the dedicated virtual memory region. + */ +__cold static int llext_manager_place(struct lib_manager_module *mctx) +{ + static const uint8_t elf_magic[] = {0x7f, 'E', 'L', 'F'}; + uint8_t *elf = (uint8_t *)mctx->ebl->buf; + size_t len = mctx->ebl->len; + const elf_ehdr_t *ehdr = (const elf_ehdr_t *)elf; + uintptr_t start = UINTPTR_MAX, end = 0, base; + size_t align = PAGE_SZ, size; + unsigned int i, shnum; + elf_shdr_t *shdr; + void *vma; + + assert_can_be_cold(); + + /* llext_load() validates the image, only check what is used here */ + if (len < sizeof(*ehdr) || memcmp(ehdr->e_ident, elf_magic, sizeof(elf_magic))) + return -ENOEXEC; + + /* + * Fall back to the addresses from the build for shared object modules + * and without a virtual page region. Build-time addresses will go away, + * all addresses will be assigned when modules are linked. + */ + if (ehdr->e_type != ET_REL) { + tr_warn(&lib_manager_tr, "not a relocatable module, using build-time addresses"); + return 0; + } + + if (!vpage_get_region()) { + tr_warn(&lib_manager_tr, "no virtual page region, using build-time addresses"); + return 0; + } + + /* + * The section header table must be within the image and must not + * overlap the ELF header: section addresses are rewritten below. Read + * the number of sections only once for the same reason. + */ + shnum = ehdr->e_shnum; + if (ehdr->e_shentsize != sizeof(*shdr) || ehdr->e_shoff < sizeof(*ehdr) || + ehdr->e_shoff > len || shnum > (len - ehdr->e_shoff) / sizeof(*shdr) || + !IS_ALIGNED(elf + ehdr->e_shoff, sizeof(uint32_t))) { + tr_err(&lib_manager_tr, "invalid section header table"); + return -ENOEXEC; + } + + shdr = (elf_shdr_t *)(elf + ehdr->e_shoff); + + /* Find the address range and the largest alignment of SRAM sections */ + for (i = 0; i < shnum; i++) { + if (!(shdr[i].sh_flags & SHF_ALLOC) || !shdr[i].sh_size || + llext_manager_section_detached(shdr + i)) + continue; + + if (shdr[i].sh_addr + shdr[i].sh_size < shdr[i].sh_addr || + !is_power_of_two(shdr[i].sh_addralign ? : 1)) { + tr_err(&lib_manager_tr, "invalid section %u", i); + return -ENOEXEC; + } + + start = MIN(start, shdr[i].sh_addr); + end = MAX(end, shdr[i].sh_addr + shdr[i].sh_size); + align = MAX(align, shdr[i].sh_addralign); + } + + /* Nothing to copy to SRAM, nothing to move */ + if (!end) + return 0; + + /* + * Moving by a multiple of the largest section alignment, at least a + * page, preserves the alignment of all sections. If that alignment is + * larger than a page, reserve extra pages to find an aligned start. + */ + start = ALIGN_DOWN(start, align); + size = ALIGN_UP(end - start, PAGE_SZ) + align - PAGE_SZ; + + vma = vpage_reserve(size / PAGE_SZ); + if (!vma) { + tr_err(&lib_manager_tr, "cannot reserve %#zx bytes of virtual memory", size); + return -ENOMEM; + } + + base = ALIGN_UP((uintptr_t)vma, align); + + /* Move all SRAM sections by the same offset, llext_load() relocates them */ + for (i = 0; i < shnum; i++) { + if (!(shdr[i].sh_flags & SHF_ALLOC) || !shdr[i].sh_size || + llext_manager_section_detached(shdr + i)) + continue; + + shdr[i].sh_addr += base - start; + } + + /* The ELF image is kept in DRAM over DSP power cycles */ + sys_cache_data_flush_range(shdr, shnum * sizeof(*shdr)); + + /* Released only if linking fails, restored with the module after D3 */ + mctx->vma.addr = (uintptr_t)vma; + mctx->vma.size = size; + + tr_dbg(&lib_manager_tr, "placed %#lx-%#lx at %#lx", start, end, base); + + return 0; +} + __cold static int llext_manager_link(const char *name, struct lib_manager_module *mctx, const void **buildinfo, const struct sof_man_module_manifest **mod_manifest) @@ -468,8 +591,23 @@ __cold static int llext_manager_link(const char *name, .section_detached = llext_manager_section_detached, .keep_section_info = true, }; + bool placed = false; + + if (!*llext) { + ret = llext_manager_place(mctx); + if (ret < 0) + return ret; + placed = mctx->vma.size; + } + + /* a positive value is the use count of an already loaded extension */ ret = llext_load(ldr, name, llext, &ldr_parm); + if (ret < 0 && placed) { + vpage_release((void *)mctx->vma.addr); + mctx->vma.addr = 0; + mctx->vma.size = 0; + } if (ret) return ret; } @@ -583,6 +721,8 @@ __cold static int llext_manager_mod_init(struct lib_manager_mod_ctx *ctx, ctx->mod[n_mod].llext = NULL; ctx->mod[n_mod].ebl = NULL; ctx->mod[n_mod].n_dependent = 0; + ctx->mod[n_mod].vma.addr = 0; + ctx->mod[n_mod].vma.size = 0; ctx->mod[n_mod].start_idx = i; if (n_mod) ctx->mod[n_mod - 1].n_mod = i - ctx->mod[n_mod - 1].start_idx; diff --git a/src/kernel/library_manager/llext_manager_dram.c b/src/kernel/library_manager/llext_manager_dram.c index 2f6cff2b3501..1b5b9e2b2f49 100644 --- a/src/kernel/library_manager/llext_manager_dram.c +++ b/src/kernel/library_manager/llext_manager_dram.c @@ -5,6 +5,7 @@ #include #include +#include #include #include @@ -232,6 +233,18 @@ int llext_manager_restore_from_dram(void) /* Not instantiated - nothing to restore */ continue; + /* + * The virtual page allocator starts out empty on every + * boot, reserve the pages the module is linked at again + */ + if (mod[k].vma.size && + vpage_reserve_at((void *)mod[k].vma.addr, + mod[k].vma.size / CONFIG_MM_DRV_PAGE_SIZE) < 0) { + tr_err(&lib_manager_tr, "cannot reclaim %#zx bytes at %#lx", + mod[k].vma.size, mod[k].vma.addr); + goto nomem; + } + /* Loaders are supplied by the caller */ struct llext_buf_loader *bldr = rmalloc(SOF_MEM_FLAG_KERNEL | SOF_MEM_FLAG_COHERENT, sizeof(*bldr)); @@ -329,8 +342,11 @@ int llext_manager_restore_from_dram(void) continue; for (k = 0; k < ctx->n_mod; k++) { - if (mod[k].llext) + if (mod[k].llext) { llext_unload(&mod[k].llext); + if (mod[k].vma.size) + vpage_release((void *)mod[k].vma.addr); + } if (mod[k].ebl) rfree(mod[k].ebl); diff --git a/zephyr/CMakeLists.txt b/zephyr/CMakeLists.txt index ed9b620aba4a..507701118b24 100644 --- a/zephyr/CMakeLists.txt +++ b/zephyr/CMakeLists.txt @@ -287,8 +287,12 @@ if (CONFIG_SOC_SERIES_INTEL_ADSP_ACE) ${SOF_PLATFORM_PATH}/novalake/lib/clk.c ) + # the LLEXT library manager reserves virtual pages for loadable modules + if(CONFIG_SOF_VREGIONS OR (CONFIG_LIBRARY_MANAGER AND CONFIG_MM_DRV)) + zephyr_library_sources(lib/vpage.c) + endif() + zephyr_library_sources_ifdef(CONFIG_SOF_VREGIONS - lib/vpage.c lib/vregion.c ) diff --git a/zephyr/lib/vpage.c b/zephyr/lib/vpage.c index a83dd8746dcc..afc93035f3e1 100644 --- a/zephyr/lib/vpage.c +++ b/zephyr/lib/vpage.c @@ -560,14 +560,21 @@ __cold static int vpage_init(void) CONFIG_SOF_ZEPHYR_VIRTUAL_HEAP_REGION_SIZE; uintptr_t end; size_t remaining_ram; + /* + * The LLEXT library manager places relocatable modules in vpages, only + * shared object modules use the library region, so L2 has to be kept + * for it only when modules are built as shared objects. + */ + const size_t library_l2_size = IS_ENABLED(CONFIG_LLEXT_TYPE_ELF_RELOCATABLE) ? + 0 : CONFIG_LIBRARY_REGION_SIZE; assert_can_be_cold(); k_mutex_init(&vpage_ctx.lock); - if (start + CONFIG_LIBRARY_REGION_SIZE + CONFIG_MM_DRV_PAGE_SIZE <= l2_end) { + if (start + library_l2_size + CONFIG_MM_DRV_PAGE_SIZE <= l2_end) { /* virtual heap and library regions fit in L2, vpages get the rest */ - end = l2_end - CONFIG_LIBRARY_REGION_SIZE; + end = l2_end - library_l2_size; } else { /* * Small L2 (e.g. NVL-S): the virtual heap and library regions are only