From 0770c2ad5bac594d2389dfe0b4fe0469488b2b7a Mon Sep 17 00:00:00 2001 From: 0x6D70 Date: Tue, 23 Jan 2024 21:40:17 +0100 Subject: [PATCH] deallocate kernel stack --- xernel/kernel/src/sched/process.rs | 3 --- xernel/kernel/src/sched/thread.rs | 24 ++++++++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/xernel/kernel/src/sched/process.rs b/xernel/kernel/src/sched/process.rs index c6eeb905..8b25c3fe 100644 --- a/xernel/kernel/src/sched/process.rs +++ b/xernel/kernel/src/sched/process.rs @@ -82,9 +82,6 @@ impl Process { ); } - // TODO: how to unmap this stack later?? - // We can't add it to Vm because it's not in the lower half of the address space - stack_top } diff --git a/xernel/kernel/src/sched/thread.rs b/xernel/kernel/src/sched/thread.rs index d2cd373d..abd3d08f 100644 --- a/xernel/kernel/src/sched/thread.rs +++ b/xernel/kernel/src/sched/thread.rs @@ -1,5 +1,10 @@ use alloc::sync::Arc; use libxernel::sync::Spinlock; +use x86_64::structures::paging::{Page, PageSize, PhysFrame, Size4KiB}; + +use crate::mem::frame::FRAME_ALLOCATOR; +use crate::mem::paging::KERNEL_PAGE_MAPPER; +use crate::mem::STACK_SIZE; use super::context::CpuContext; use super::process::{Process, KERNEL_PROCESS}; @@ -167,3 +172,22 @@ impl Thread { self.process.upgrade() } } + +impl Drop for Thread { + fn drop(&mut self) { + if self.is_kernel_thread() { + let mut page_mapper = KERNEL_PAGE_MAPPER.lock(); + let mut frame_allocator = FRAME_ALLOCATOR.lock(); + + for addr in (self.thread_stack..self.thread_stack + STACK_SIZE as usize).step_by(Size4KiB::SIZE as usize) { + unsafe { + let page = Page::::from_start_address(VirtAddr::new(addr as u64)).unwrap(); + let phys_addr = page_mapper.translate(page.start_address()).unwrap(); + + frame_allocator.deallocate_frame(PhysFrame::::containing_address(phys_addr)); + page_mapper.unmap(page.start_address()); + } + } + } + } +}