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, Copy, Debug)]
9pub struct Page {
10 pub data: [u8; PAGE_SIZE],
11}
12
13impl Page {
14 pub const fn new() -> Self {
15 Page { data: [0; PAGE_SIZE] }
16 }
17}
18
19/// Allocates a number of pages.
20///
21/// # Arguments
22/// * `num_of_pages` - The number of pages to allocate
23///
24/// # Returns
25/// A pointer to the allocated pages.
26pub fn allocate_raw_pages(num_of_pages: usize) -> *mut Page {
27 let boxed_pages = allocate_boxed_pages(num_of_pages);
28 Box::into_raw(boxed_pages) as *mut Page
29}
30
31/// Frees a number of pages.
32///
33/// # Arguments
34/// * `pages` - A pointer to the pages to free
35/// * `num_of_pages` - The number of pages to free
36pub fn free_raw_pages(pages: *mut Page, num_of_pages: usize) {
37 unsafe {
38 let boxed_pages = Box::from_raw(core::slice::from_raw_parts_mut(pages, num_of_pages));
39 free_boxed_pages(boxed_pages);
40 }
41}
42
43/// Allocates a number of pages and returns them as a boxed slice.
44///
45/// # Arguments
46/// * `num_of_pages` - The number of pages to allocate
47///
48/// # Returns
49/// A boxed slice of the allocated pages.
50///
51pub fn allocate_boxed_pages(num_of_pages: usize) -> Box<[Page]> {
52 let boxed_pages = alloc::vec![Page::new(); num_of_pages].into_boxed_slice();
53 boxed_pages
54}
55
56/// Frees a boxed slice of pages.
57///
58/// # Arguments
59/// * `pages` - A boxed slice of pages to free
60///
61pub fn free_boxed_pages(pages: Box<[Page]>) {
62 // The Box will be automatically freed when it goes out of scope
63 drop(pages);
64}
65
66/// Frees a boxed page.
67///
68/// # Arguments
69/// * `page` - A boxed page to free
70///
71pub fn free_boxed_page(page: Box<Page>) {
72 // The Box will be automatically freed when it goes out of scope
73 drop(page);
74}