kernel/mem/
page.rs

1extern crate alloc;
2
3use alloc::boxed::Box;
4
5use crate::environment::PAGE_SIZE;
6
7#[repr(C, align(4096))]
8#[derive(Clone, Debug)]
9pub struct Page {
10    pub data: [u8; PAGE_SIZE],
11}
12
13impl Page {
14    pub const fn new() -> Self {
15        Page {
16            data: [0; PAGE_SIZE],
17        }
18    }
19}
20
21/// Allocates a number of pages.
22///
23/// # Arguments
24/// * `num_of_pages` - The number of pages to allocate
25///
26/// # Returns
27/// A pointer to the allocated pages.
28pub fn allocate_raw_pages(num_of_pages: usize) -> *mut Page {
29    let boxed_pages = allocate_boxed_pages(num_of_pages);
30    Box::into_raw(boxed_pages) as *mut Page
31}
32
33/// Frees a number of pages.
34///
35/// # Arguments
36/// * `pages` - A pointer to the pages to free
37/// * `num_of_pages` - The number of pages to free
38pub fn free_raw_pages(pages: *mut Page, num_of_pages: usize) {
39    unsafe {
40        let boxed_pages = Box::from_raw(core::ptr::slice_from_raw_parts_mut(pages, num_of_pages));
41        free_boxed_pages(boxed_pages);
42    }
43}
44
45/// Allocates a number of pages and returns them as a boxed slice.
46///
47/// # Arguments
48/// * `num_of_pages` - The number of pages to allocate
49///  
50/// # Returns
51/// A boxed slice of the allocated pages.
52///
53pub fn allocate_boxed_pages(num_of_pages: usize) -> Box<[Page]> {
54    // Allocate raw memory and initialize it
55    use alloc::alloc::{Layout, alloc_zeroed};
56    use core::ptr;
57
58    let layout = Layout::array::<Page>(num_of_pages).expect("Layout calculation failed");
59
60    unsafe {
61        let ptr = alloc_zeroed(layout) as *mut Page;
62        if ptr.is_null() {
63            alloc::alloc::handle_alloc_error(layout);
64        }
65
66        // Convert raw pointer to Box<[Page]>
67        let slice = ptr::slice_from_raw_parts_mut(ptr, num_of_pages);
68        Box::from_raw(slice)
69    }
70}
71
72/// Frees a boxed slice of pages.
73///
74/// # Arguments
75/// * `pages` - A boxed slice of pages to free
76///
77pub fn free_boxed_pages(pages: Box<[Page]>) {
78    // The Box will be automatically freed when it goes out of scope
79    drop(pages);
80}
81
82/// Frees a boxed page.
83///
84/// # Arguments
85/// * `page` - A boxed page to free
86///
87pub fn free_boxed_page(page: Box<Page>) {
88    // The Box will be automatically freed when it goes out of scope
89    drop(page);
90}