From af26dce0388a2da663d3251fb116ba0b30003377 Mon Sep 17 00:00:00 2001 From: apio Date: Tue, 4 Jul 2023 00:49:26 +0200 Subject: [PATCH] kernel: Zero physical frames instead of virtual pages The memset() happens a bit earlier, and we don't have to remap the mapped virtual memory. --- kernel/src/memory/MemoryManager.cpp | 31 +++++++++++++++++++++++------ kernel/src/memory/MemoryManager.h | 1 + 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/kernel/src/memory/MemoryManager.cpp b/kernel/src/memory/MemoryManager.cpp index 4ee6e119..7763d4b6 100644 --- a/kernel/src/memory/MemoryManager.cpp +++ b/kernel/src/memory/MemoryManager.cpp @@ -151,6 +151,16 @@ namespace MemoryManager return index * ARCH_PAGE_SIZE; } + Result alloc_zeroed_frame() + { + const u64 frame = TRY(alloc_frame()); + + const u64 address = MMU::translate_physical_address(frame); + memset((void*)address, 0, ARCH_PAGE_SIZE); + + return frame; + } + Result free_frame(u64 frame) { const u64 index = frame / ARCH_PAGE_SIZE; @@ -263,15 +273,24 @@ namespace MemoryManager Result alloc_at_zeroed(u64 virt, usize count, int flags) { - u64 address = TRY(alloc_at(virt, count, MMU::ReadWrite)); + CHECK_PAGE_ALIGNED(virt); - memset((void*)address, 0, count * ARCH_PAGE_SIZE); + u64 start = virt; + usize pages_mapped = 0; - // This should never fail (we just mapped memory at that address) but we don't want to crash the kernel if it - // does. - TRY(remap(address, count, flags)); + auto guard = make_scope_guard([=, &pages_mapped] { unmap_owned(start, pages_mapped); }); - return address; + while (pages_mapped < count) + { + const u64 frame = TRY(alloc_zeroed_frame()); + TRY(MMU::map(virt, frame, flags, MMU::UseHugePages::No)); + virt += ARCH_PAGE_SIZE; + pages_mapped++; + } + + guard.deactivate(); + + return start; } Result alloc_for_kernel(usize count, int flags) diff --git a/kernel/src/memory/MemoryManager.h b/kernel/src/memory/MemoryManager.h index 443d5095..e16130bd 100644 --- a/kernel/src/memory/MemoryManager.h +++ b/kernel/src/memory/MemoryManager.h @@ -13,6 +13,7 @@ namespace MemoryManager Result protect_kernel_sections(); Result alloc_frame(); + Result alloc_zeroed_frame(); Result free_frame(u64 frame); Result free_frames(u64 address, usize count);