kernel: mem: fix memory zeroing

Fix memory zeroing when requesting a physical pointer. Previously, only
the first 25% of a page was zeroed due to a bug when casting between
*mut u8 and *mut usize.

This now uses `write_volatile` to ensure the memory clear isn't
optimized out, and uses `usize` pointers everywhere.

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2023-12-25 23:30:26 +08:00
parent f2e9d2b76c
commit 006a50d206
2 changed files with 20 additions and 4 deletions

View file

@ -451,7 +451,11 @@ impl MemoryManager {
let virt = virt as *mut usize;
// Zero-out the page
unsafe { virt.write_bytes(0, PAGE_SIZE / core::mem::size_of::<usize>()) };
let range_start = virt;
let range_end = range_start.wrapping_add(PAGE_SIZE / core::mem::size_of::<usize>());
unsafe {
crate::mem::bzero(range_start, range_end);
};
if is_user {
crate::arch::mem::hand_page_to_user(virt as _)?;
}
@ -870,3 +874,14 @@ impl MemoryManager {
Ok(())
}
}
pub unsafe fn bzero<T>(mut start: *mut T, end: *mut T)
where
T: Copy,
{
while start < end {
// NOTE(volatile) to prevent this from being transformed into `memclr`
core::ptr::write_volatile(start, core::mem::zeroed());
start = start.offset(1);
}
}

View file

@ -833,10 +833,11 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR
if !phys_ptr.is_null() {
if mm.is_main_memory(phys_ptr) {
let range_start = range.as_mut_ptr() as *mut usize;
let range_end =
range_start.wrapping_add(range.len() / core::mem::size_of::<usize>());
unsafe {
range
.as_mut_ptr()
.write_bytes(0, range.len() / core::mem::size_of::<usize>())
crate::mem::bzero(range_start, range_end);
};
}
for offset in (range.as_ptr() as usize..(range.as_ptr() as usize + range.len()))