From f0b18da881785ff2952ba37489a0c8a3289a4dcf Mon Sep 17 00:00:00 2001 From: Bananymous Date: Mon, 14 Oct 2024 11:39:04 +0300 Subject: [PATCH] Kernel: Add kmalloc helper APIs --- kernel/include/kernel/Memory/kmalloc.h | 1 + kernel/kernel/Memory/kmalloc.cpp | 27 +++++++++++++++++++++----- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/kernel/include/kernel/Memory/kmalloc.h b/kernel/include/kernel/Memory/kmalloc.h index 2f330a2d..f465774f 100644 --- a/kernel/include/kernel/Memory/kmalloc.h +++ b/kernel/include/kernel/Memory/kmalloc.h @@ -13,3 +13,4 @@ void* kmalloc(size_t size, size_t align, bool force_identity_map = false); void kfree(void*); BAN::Optional kmalloc_paddr_of(Kernel::vaddr_t); +BAN::Optional kmalloc_vaddr_of(Kernel::paddr_t); diff --git a/kernel/kernel/Memory/kmalloc.cpp b/kernel/kernel/Memory/kmalloc.cpp index 83c1720f..edecf362 100644 --- a/kernel/kernel/Memory/kmalloc.cpp +++ b/kernel/kernel/Memory/kmalloc.cpp @@ -418,12 +418,29 @@ void kfree(void* address) } +static bool is_kmalloc_vaddr(Kernel::vaddr_t vaddr) +{ + using namespace Kernel; + if (vaddr < reinterpret_cast(s_kmalloc_storage)) + return false; + if (vaddr >= reinterpret_cast(s_kmalloc_storage) + sizeof(s_kmalloc_storage)) + return false; + return true; +} + BAN::Optional kmalloc_paddr_of(Kernel::vaddr_t vaddr) { using namespace Kernel; - - if ((vaddr_t)s_kmalloc_storage <= vaddr && vaddr < (vaddr_t)s_kmalloc_storage + sizeof(s_kmalloc_storage)) - return vaddr - KERNEL_OFFSET + g_boot_info.kernel_paddr; - - return {}; + if (!is_kmalloc_vaddr(vaddr)) + return {}; + return vaddr - KERNEL_OFFSET + g_boot_info.kernel_paddr; +} + +BAN::Optional kmalloc_vaddr_of(Kernel::paddr_t paddr) +{ + using namespace Kernel; + const vaddr_t vaddr = paddr + KERNEL_OFFSET - g_boot_info.kernel_paddr; + if (!is_kmalloc_vaddr(vaddr)) + return {}; + return vaddr; }