kernel_api/mapping/mappable.rs
1use alloc::boxed::Box;
2use core::num::NonZero;
3
4/// Basic operations to decide how to map memory together.
5///
6/// See the [module level documentation](`super`) for more information.
7pub trait Mappable {
8 /// The number of pages required to create a mapping with `frame_count` frames.
9 fn virtual_size(&self, frame_count: usize) -> NonZero<usize>;
10
11 /// The number of pages to offset the physical memory into the allocated virtual memory.
12 fn base_virtual_offset(&self) -> isize;
13}
14
15/// A basic map of virtual to physical memory.
16///
17/// In certain build configurations, this may include guard pages to check for out-of-bounds access.
18/// If a guaranteed amount of virtual address space usage of virtual location is required, see [`UncheckedMmap`].
19///
20/// <div class="warning">
21///
22/// When combined with [`virtual_location`](`super::Config::virtual_location`), the use of guard pages may mean that the valid start
23/// of the virtual allocation is not at the requested location. Retrieve the valid start using
24/// [`virtual_valid_start`](`Mapping::virtual_valid_start`), [`as_ptr`](`Mapping::as_ptr`), or similar after
25/// creating the mapping to get the correct address.
26///
27/// </div>
28#[derive(Default, Debug, Copy, Clone)]
29#[non_exhaustive]
30pub struct Mmap {}
31
32impl Mappable for Mmap {
33 fn virtual_size(&self, frame_count: usize) -> NonZero<usize> {
34 NonZero::new(frame_count + 2).unwrap()
35 }
36
37 fn base_virtual_offset(&self) -> isize {
38 1
39 }
40}
41
42/// An implementation of [`Mappable`] for a stack, providing guard pages at the start and end of each allocation.
43pub type Stack = Mmap;
44
45/// A basic map of virtual to physical memory, with no out-of-bounds checking.
46///
47/// Most uses should instead use [`Mmap`], unless a guaranteed amount of or location
48/// in virtual memory is required.
49#[deprecated = "renamed to `UncheckedMmap`"]
50pub type UnsafeMmap = UncheckedMmap;
51
52/// A basic map of virtual to physical memory, with no out-of-bounds checking.
53///
54/// Most uses should instead use [`Mmap`], unless a guaranteed amount of or location
55/// in virtual memory is required.
56#[derive(Default, Debug, Copy, Clone)]
57pub struct UncheckedMmap(());
58
59impl Mappable for UncheckedMmap {
60 fn virtual_size(&self, frame_count: usize) -> NonZero<usize> {
61 NonZero::new(frame_count).unwrap()
62 }
63
64 fn base_virtual_offset(&self) -> isize {
65 0
66 }
67}
68
69impl<T: ?Sized + Mappable> Mappable for Box<T> {
70 fn virtual_size(&self, frame_count: usize) -> NonZero<usize> {
71 T::virtual_size(&**self, frame_count)
72 }
73
74 fn base_virtual_offset(&self) -> isize {
75 T::base_virtual_offset(&**self)
76 }
77}