Next Generation WASM Microkernel Operating System
1// Copyright 2025 Jonas Kruckenberg
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use core::alloc::Layout;
9use core::range::Range;
10
11use loader_api::BootInfo;
12use talc::{ErrOnOom, Span, Talc, Talck};
13
14use crate::mem::bootstrap_alloc::BootstrapAllocator;
15use crate::{INITIAL_HEAP_SIZE_PAGES, arch};
16
17#[global_allocator]
18static KERNEL_ALLOCATOR: Talck<spin::RawMutex, ErrOnOom> = Talc::new(ErrOnOom).lock();
19
20pub fn init(boot_alloc: &mut BootstrapAllocator, boot_info: &BootInfo) {
21 let layout =
22 Layout::from_size_align(INITIAL_HEAP_SIZE_PAGES * arch::PAGE_SIZE, arch::PAGE_SIZE)
23 .unwrap();
24
25 let phys = boot_alloc.allocate_contiguous(layout).unwrap();
26
27 let virt = {
28 let start = boot_info
29 .physical_address_offset
30 .checked_add(phys.get())
31 .unwrap();
32
33 Range::from(start..start.checked_add(layout.size()).unwrap())
34 };
35 tracing::debug!("Kernel Heap: {virt:#x?}");
36
37 let mut alloc = KERNEL_ALLOCATOR.lock();
38 let span = Span::from_base_size(
39 virt.start as *mut u8,
40 virt.end.checked_sub(virt.start).unwrap(),
41 );
42
43 // Safety: just allocated the memory region
44 unsafe {
45 let old_heap = alloc.claim(span).unwrap();
46 alloc.extend(old_heap, span);
47 }
48}