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::ops::Range;
10
11use kmem::{AddressRangeExt, VirtualAddress};
12use loader_api::BootInfo;
13use talc::{ErrOnOom, Span, Talc, Talck};
14
15use crate::mem::bootstrap_alloc::BootstrapAllocator;
16use crate::{INITIAL_HEAP_SIZE_PAGES, arch};
17
18#[global_allocator]
19static KERNEL_ALLOCATOR: Talck<k23_spin::RawMutex, ErrOnOom> = Talc::new(ErrOnOom).lock();
20
21pub fn init(boot_alloc: &mut BootstrapAllocator, boot_info: &BootInfo) {
22 let layout =
23 Layout::from_size_align(INITIAL_HEAP_SIZE_PAGES * arch::PAGE_SIZE, arch::PAGE_SIZE)
24 .unwrap();
25
26 let phys = boot_alloc.allocate_contiguous(layout).unwrap();
27
28 let virt: Range<VirtualAddress> = {
29 let start = boot_info.physical_address_offset.add(phys.get());
30
31 Range::from_start_len(start, layout.size())
32 };
33 tracing::debug!("Kernel Heap: {virt:#x?}");
34
35 let mut alloc = KERNEL_ALLOCATOR.lock();
36 let span = Span::from_base_size(virt.start.as_mut_ptr(), virt.len());
37
38 // Safety: just allocated the memory region
39 unsafe {
40 let old_heap = alloc.claim(span).unwrap();
41 alloc.extend(old_heap, span);
42 }
43}