Skip to main content

hermit/syscalls/
mman.rs

1//! Memory management syscalls.
2//!
3//! These system calls are similar to [sys/mman.h].
4//!
5//! <div class="warning">These system calls are not very POSIX-like yet!</div>
6//!
7//! [sys/mman.h]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/sys_mman.h.html
8
9use core::ffi::{c_int, c_void};
10
11use align_address::Align;
12use free_list::{PageLayout, PageRange};
13use memory_addresses::{PhysAddr, VirtAddr};
14
15#[cfg(target_arch = "x86_64")]
16use crate::arch::mm::paging::PageTableEntryFlagsExt;
17use crate::arch::mm::paging::{self, BasePageSize, PageSize, PageTableEntryFlags};
18use crate::mm::{FrameAlloc, PageAlloc, PageRangeAllocator};
19
20bitflags! {
21	#[repr(transparent)]
22	#[derive(Debug, Copy, Clone, Default, PartialEq)]
23	pub struct MemoryProtection: u32 {
24		/// Pages may not be accessed.
25		const None = 0;
26		/// Indicates that the memory region should be readable.
27		const Read = 1 << 0;
28		/// Indicates that the memory region should be writable.
29		const Write = 1 << 1;
30		/// Indicates that the memory region should be executable.
31		const Exec = 1 << 2;
32	}
33}
34
35const PAGE_SIZE: usize = BasePageSize::SIZE as usize;
36
37/// Looks at up to `count` pages starting at `virtual_address` and returns how many of them,
38/// from the start, share the state of the first page, together with the first page's frame.
39///
40/// Sharing the state means: all pages are unmapped (frame is `None`), or all pages are mapped
41/// to physically contiguous frames.
42fn contiguous_pages(virtual_address: VirtAddr, count: usize) -> (usize, Option<PhysAddr>) {
43	let first_frame = paging::virtual_to_physical(virtual_address);
44
45	let mut len = 1;
46	while len < count {
47		let offset = (len * PAGE_SIZE) as u64;
48		let frame = paging::virtual_to_physical(virtual_address + offset);
49		let expected_frame = first_frame.map(|phys| phys + offset);
50		if frame != expected_frame {
51			break;
52		}
53		len += 1;
54	}
55
56	(len, first_frame)
57}
58
59/// Creates a new virtual memory mapping of the `size` specified with
60/// protection bits specified in `prot_flags`.
61#[hermit_macro::system(errno)]
62#[unsafe(no_mangle)]
63pub extern "C" fn sys_mmap(size: usize, prot_flags: MemoryProtection, ret: &mut *mut u8) -> i32 {
64	let size = size.align_up(BasePageSize::SIZE as usize);
65	let layout = PageLayout::from_size(size).unwrap();
66	let page_range = PageAlloc::allocate(layout).unwrap();
67	let virtual_address = VirtAddr::from(page_range.start());
68	if prot_flags.is_empty() {
69		*ret = virtual_address.as_mut_ptr();
70		return 0;
71	}
72	let frame_layout = PageLayout::from_size(size).unwrap();
73	let frame_range = FrameAlloc::allocate_zeroed(frame_layout).unwrap();
74	let physical_address = PhysAddr::from(frame_range.start());
75
76	debug!("Mmap {physical_address:X} -> {virtual_address:X} ({size})");
77	let count = size / BasePageSize::SIZE as usize;
78	let mut flags = PageTableEntryFlags::normal();
79	flags
80		.set_writable(prot_flags.contains(MemoryProtection::Write))
81		.set_execute(prot_flags.contains(MemoryProtection::Exec));
82
83	paging::map::<BasePageSize>(virtual_address, physical_address, count, flags);
84
85	*ret = virtual_address.as_mut_ptr();
86
87	0
88}
89
90/// Unmaps memory at the specified `ptr` for `size` bytes.
91#[hermit_macro::system(errno)]
92#[unsafe(no_mangle)]
93pub extern "C" fn sys_munmap(ptr: *mut u8, size: usize) -> i32 {
94	let virtual_address = VirtAddr::from_ptr(ptr);
95	let size = size.align_up(BasePageSize::SIZE as usize);
96	let page_range = PageRange::from_start_len(virtual_address.as_usize(), size).unwrap();
97
98	// Unmap and free the frames run by run, as the range may consist of several mappings.
99	let mut virt = virtual_address;
100	let mut remaining = size / PAGE_SIZE;
101	while remaining > 0 {
102		let (count, phys) = contiguous_pages(virt, remaining);
103		if let Some(phys) = phys {
104			paging::unmap::<BasePageSize>(virt, count);
105			debug!("Unmapping {virt:X} ({count} pages) -> {phys:X}");
106
107			let frame_range =
108				PageRange::from_start_len(phys.as_u64() as usize, count * PAGE_SIZE).unwrap();
109			unsafe {
110				FrameAlloc::deallocate(frame_range);
111			}
112		}
113		virt += (count * PAGE_SIZE) as u64;
114		remaining -= count;
115	}
116
117	unsafe {
118		PageAlloc::deallocate(page_range);
119	}
120
121	0
122}
123
124/// Configures the protections associated with a region of virtual memory
125/// starting at `ptr` and going to `size`.
126///
127/// Returns 0 on success and an error code on failure.
128#[hermit_macro::system(errno)]
129#[unsafe(no_mangle)]
130pub extern "C" fn sys_mprotect(ptr: *mut u8, size: usize, prot_flags: MemoryProtection) -> i32 {
131	let size = size.align_up(PAGE_SIZE);
132	let count = size / PAGE_SIZE;
133	if count == 0 {
134		return 0;
135	}
136	let mut flags = PageTableEntryFlags::normal();
137	flags
138		.set_writable(prot_flags.contains(MemoryProtection::Write))
139		.set_execute(prot_flags.contains(MemoryProtection::Exec));
140
141	let virtual_address = VirtAddr::from_ptr(ptr);
142
143	let (run_len, mapped) = contiguous_pages(virtual_address, count);
144	if run_len < count {
145		unimplemented!("mprotect on a partially mapped or non-contiguous range");
146	}
147
148	debug!("Mprotect {virtual_address:X} ({size}) -> {prot_flags:?})");
149	if let Some(physical_address) = mapped {
150		// Memory is already mapped
151		if prot_flags == MemoryProtection::None {
152			unimplemented!("mprotect to PROT_NONE is not yet supported");
153		}
154		paging::map::<BasePageSize>(virtual_address, physical_address, count, flags);
155		0
156	} else if prot_flags == MemoryProtection::None {
157		// Unmapped memory stays reserved without frames
158		0
159	} else {
160		// Memory was not mapped but now becomes accessible
161		let frame_layout = PageLayout::from_size(size).unwrap();
162		let frame_range = FrameAlloc::allocate_zeroed(frame_layout).unwrap();
163		let physical_address = PhysAddr::from(frame_range.start());
164		paging::map::<BasePageSize>(virtual_address, physical_address, count, flags);
165		0
166	}
167}
168
169#[hermit_macro::system(errno)]
170#[unsafe(no_mangle)]
171pub extern "C" fn sys_mlock(_addr: *const c_void, _size: usize) -> i32 {
172	// Hermit does not do any swapping yet.
173	0
174}
175
176#[hermit_macro::system(errno)]
177#[unsafe(no_mangle)]
178pub extern "C" fn sys_munlock(_addr: *const c_void, _size: usize) -> i32 {
179	// Hermit does not do any swapping yet.
180	0
181}
182
183#[hermit_macro::system(errno)]
184#[unsafe(no_mangle)]
185pub extern "C" fn sys_mlockall(_flags: c_int) -> i32 {
186	// Hermit does not do any swapping yet.
187	0
188}
189
190#[hermit_macro::system(errno)]
191#[unsafe(no_mangle)]
192pub extern "C" fn sys_munlockall(_flags: c_int) -> i32 {
193	// Hermit does not do any swapping yet.
194	0
195}