Skip to main content

hermit/mm/
mod.rs

1//! Memory management.
2//!
3//! This is an overview of Hermit's memory layout:
4//!
5//! - `DeviceAlloc.device_offset` is 0 if `!cfg!(careful)`
6//! - User space virtual memory is only used if `!cfg!(feature = "common-os")`
7//! - On x86-64, PCI BARs, I/O APICs, and local APICs may be in `0xc0000000..0xffffffff`, which could be inside of `MEM`.
8//!
9//! ```text
10//!                               Virtual address
11//!                                    space
12//!
13//!                                 ...┌───┬──► 00000000
14//!           Physical address   ...   │   │
15//!                space      ...      │   │ Identity map
16//!                        ...         │   │
17//!    00000000 ◄──┬───┐...         ...├───┼──► mem_size
18//!                │   │   ...   ...   │   │
19//!     FrameAlloc │MEM│      ...      │   │ Unused
20//!                │   │   ...   ...   │   │
21//!    mem_size ◄──┼───┤...         ...├───┼──► DeviceAlloc.phys_offset
22//!                │   │   ...         │   │
23//!                │   │      ...      │   │ DeviceAlloc
24//!                │   │         ...   │   │
25//!          Empty │   │            ...├───┼──► DeviceAlloc.phys_offset + mem_size
26//!                │   │               │   │
27//!                │   │               │   │
28//!                │   │               │   │ Unused
29//!     Unknown ◄──┼───┤               │   │
30//!                │   │               │   │
31//!            PCI │   │               ├───┼──► kernel_virt_start
32//!                │   │               │   │
33//!     Unknown ◄──┼───┤               │   │ PageAlloc
34//!                │   │               │   │
35//!                │   │               ├───┼──► kernel_virt_end
36//!                │   │               │   │
37//!          Empty │   │               │   │
38//!                │   │               │   │ User space
39//!                │   │               │   │
40//!                │   │               │   │
41//! ```
42
43pub(crate) mod bitmap;
44pub(crate) mod device_alloc;
45mod mapped_page_box;
46mod page_range_alloc;
47mod physicalmem;
48mod virtualmem;
49
50use core::alloc::Layout;
51use core::mem::MaybeUninit;
52
53use align_address::Align;
54use free_list::{PageLayout, PageRange};
55use hermit_sync::RawInterruptSpinMutex;
56pub use memory_addresses::{PhysAddr, VirtAddr};
57#[cfg(target_os = "none")]
58use talc::TalcLock;
59#[cfg(target_os = "none")]
60use talc::source::Manual;
61
62pub use self::mapped_page_box::MappedPageBox;
63pub use self::page_range_alloc::{PageRangeAllocator, PageRangeBox};
64pub use self::physicalmem::{FrameAlloc, FrameBox};
65pub use self::virtualmem::{PageAlloc, PageBox};
66use crate::arch;
67#[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))]
68use crate::arch::mm::paging::HugePageSize;
69pub use crate::arch::mm::paging::virtual_to_physical;
70use crate::arch::mm::paging::{BasePageSize, LargePageSize, PageSize};
71
72#[cfg(target_os = "none")]
73#[global_allocator]
74pub(crate) static ALLOCATOR: TalcLock<RawInterruptSpinMutex, Manual> = TalcLock::new(Manual);
75
76#[cfg(target_os = "none")]
77pub(crate) fn claim_initial_heap() {
78	#[repr(C, align(0x1000))]
79	struct InitialHeap([MaybeUninit<u8>; 0x1000]);
80
81	debug_assert_eq!(
82		Layout::new::<InitialHeap>(),
83		Layout::from_size_align(0x1000, 0x1000).unwrap()
84	);
85
86	static mut INITIAL_HEAP: InitialHeap = InitialHeap([MaybeUninit::uninit(); _]);
87
88	let base = (&raw mut INITIAL_HEAP).cast::<u8>();
89	let size = size_of::<InitialHeap>();
90	unsafe {
91		ALLOCATOR.lock().claim(base, size).unwrap();
92	}
93}
94
95#[cfg(target_os = "none")]
96pub(crate) fn init() {
97	use arch::mm::paging;
98
99	#[cfg(not(target_arch = "riscv64"))]
100	unsafe {
101		paging::init();
102	}
103	let avail_frames = unsafe { FrameAlloc::init() };
104	#[cfg(target_arch = "x86_64")]
105	unsafe {
106		paging::log_page_tables();
107	}
108	let _avail_pages = unsafe { PageAlloc::init() };
109	#[cfg(target_arch = "riscv64")]
110	unsafe {
111		paging::enable_page_table();
112	}
113
114	info!("Total memory size: {} MiB", avail_frames >> 20);
115
116	// we reserve physical memory for the required page tables
117	// In worst case, we use page size of BasePageSize::SIZE
118	let npages = avail_frames / BasePageSize::SIZE as usize;
119	let npage_div = BasePageSize::SIZE as usize / align_of::<usize>();
120	let npage_3tables = npages / npage_div + 1;
121	let npage_2tables = npage_3tables / npage_div + 1;
122	let npage_1tables = npage_2tables / npage_div + 1;
123	let min_mem = (npage_3tables + npage_2tables + npage_1tables) * BasePageSize::SIZE as usize
124		+ 2 * LargePageSize::SIZE as usize;
125	#[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))]
126	let has_1gib_pages = arch::kernel::processor::supports_1gib_pages();
127	let has_2mib_pages = arch::kernel::processor::supports_2mib_pages();
128
129	info!("Minimum memory size: {} MiB", min_mem >> 20);
130	let avail_mem = avail_frames
131		.checked_sub(min_mem)
132		.unwrap_or_else(|| panic!("Not enough memory available!"))
133		.align_down(LargePageSize::SIZE as usize);
134
135	let mut map_addr;
136	let mut map_size;
137	let heap_start_addr;
138
139	#[cfg(feature = "common-os")]
140	{
141		info!("Using Hermit as common OS!");
142
143		// we reserve at least 75% of the memory for the user space
144		let reserve: usize = (avail_mem * 75) / 100;
145		// 64 MB is enough as kernel heap
146		let reserve = core::cmp::min(reserve, 0x0400_0000);
147
148		let virt_size: usize = reserve.align_down(LargePageSize::SIZE as usize);
149		let layout = PageLayout::from_size_align(virt_size, LargePageSize::SIZE as usize).unwrap();
150		let page_range = PageAlloc::allocate(layout).unwrap();
151		let virt_addr = VirtAddr::from(page_range.start());
152		heap_start_addr = virt_addr;
153
154		info!(
155			"Heap: size {} MB, start address {:p}",
156			virt_size >> 20,
157			virt_addr
158		);
159
160		#[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))]
161		if has_1gib_pages && virt_size > HugePageSize::SIZE as usize {
162			// Mount large pages to the next huge page boundary
163			let npages = (virt_addr.align_up(HugePageSize::SIZE) - virt_addr) as usize
164				/ LargePageSize::SIZE as usize;
165			if let Err(n) = paging::map_heap::<LargePageSize>(virt_addr, npages) {
166				map_addr = virt_addr + n as u64 * LargePageSize::SIZE;
167				map_size = virt_size - (map_addr - virt_addr) as usize;
168			} else {
169				map_addr = virt_addr.align_up(HugePageSize::SIZE);
170				map_size = virt_size - (map_addr - virt_addr) as usize;
171			}
172		} else {
173			map_addr = virt_addr;
174			map_size = virt_size;
175		}
176
177		#[cfg(not(any(target_arch = "x86_64", target_arch = "riscv64")))]
178		{
179			map_addr = virt_addr;
180			map_size = virt_size;
181		}
182	}
183
184	#[cfg(not(feature = "common-os"))]
185	{
186		// we reserve 10% of the memory for stack allocations
187		#[cfg(not(feature = "mman"))]
188		let stack_reserve: usize = (avail_mem * 10) / 100;
189
190		// At first, we map only a small part into the heap.
191		// Afterwards, we already use the heap and map the rest into
192		// the virtual address space.
193
194		#[cfg(not(feature = "mman"))]
195		let virt_size: usize = (avail_mem - stack_reserve).align_down(LargePageSize::SIZE as usize);
196		#[cfg(feature = "mman")]
197		let virt_size: usize = ((avail_mem * 75) / 100).align_down(LargePageSize::SIZE as usize);
198
199		let layout = PageLayout::from_size_align(virt_size, LargePageSize::SIZE as usize).unwrap();
200		let page_range = PageAlloc::allocate(layout).unwrap();
201		let virt_addr = VirtAddr::from(page_range.start());
202		heap_start_addr = virt_addr;
203
204		info!(
205			"Heap: size {} MB, start address {:p}",
206			virt_size >> 20,
207			virt_addr
208		);
209
210		#[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))]
211		if has_1gib_pages && virt_size > HugePageSize::SIZE as usize {
212			// Mount large pages to the next huge page boundary
213			let npages = (virt_addr.align_up(HugePageSize::SIZE) - virt_addr) / LargePageSize::SIZE;
214			if let Err(n) = paging::map_heap::<LargePageSize>(virt_addr, npages as usize) {
215				map_addr = virt_addr + n as u64 * LargePageSize::SIZE;
216				map_size = virt_size - (map_addr - virt_addr) as usize;
217			} else {
218				map_addr = virt_addr.align_up(HugePageSize::SIZE);
219				map_size = virt_size - (map_addr - virt_addr) as usize;
220			}
221		} else {
222			map_addr = virt_addr;
223			map_size = virt_size;
224		}
225
226		#[cfg(not(any(target_arch = "x86_64", target_arch = "riscv64")))]
227		{
228			map_addr = virt_addr;
229			map_size = virt_size;
230		}
231	}
232
233	#[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))]
234	if has_1gib_pages
235		&& map_size > HugePageSize::SIZE as usize
236		&& map_addr.is_aligned_to(HugePageSize::SIZE)
237	{
238		let size = map_size.align_down(HugePageSize::SIZE as usize);
239		if let Err(num_pages) =
240			paging::map_heap::<HugePageSize>(map_addr, size / HugePageSize::SIZE as usize)
241		{
242			map_size -= num_pages * HugePageSize::SIZE as usize;
243			map_addr += num_pages as u64 * HugePageSize::SIZE;
244		} else {
245			map_size -= size;
246			map_addr += size;
247		}
248	}
249
250	if has_2mib_pages
251		&& map_size > LargePageSize::SIZE as usize
252		&& map_addr.is_aligned_to(LargePageSize::SIZE)
253	{
254		let size = map_size.align_down(LargePageSize::SIZE as usize);
255		if let Err(num_pages) =
256			paging::map_heap::<LargePageSize>(map_addr, size / LargePageSize::SIZE as usize)
257		{
258			map_size -= num_pages * LargePageSize::SIZE as usize;
259			map_addr += num_pages as u64 * LargePageSize::SIZE;
260		} else {
261			map_size -= size;
262			map_addr += size;
263		}
264	}
265
266	if map_size > BasePageSize::SIZE as usize && map_addr.is_aligned_to(BasePageSize::SIZE) {
267		let size = map_size.align_down(BasePageSize::SIZE as usize);
268		if let Err(num_pages) =
269			paging::map_heap::<BasePageSize>(map_addr, size / BasePageSize::SIZE as usize)
270		{
271			map_size -= num_pages * BasePageSize::SIZE as usize;
272			map_addr += num_pages as u64 * BasePageSize::SIZE;
273		} else {
274			map_size -= size;
275			map_addr += size;
276		}
277	}
278
279	let heap_end_addr = map_addr;
280
281	let size = heap_end_addr.as_usize() - heap_start_addr.as_usize();
282	unsafe {
283		ALLOCATOR
284			.lock()
285			.claim(heap_start_addr.as_mut_ptr(), size)
286			.unwrap();
287	}
288
289	info!("Heap is located at {heap_start_addr:p}..{heap_end_addr:p} ({map_size} Bytes unmapped)");
290}
291
292pub(crate) fn print_information() {
293	debug!("{FrameAlloc}");
294	debug!("{PageAlloc}");
295}
296
297/// Maps a given physical address and size in virtual space and returns address.
298#[cfg(feature = "pci")]
299pub(crate) fn map(
300	physical_address: PhysAddr,
301	size: usize,
302	writable: bool,
303	no_execution: bool,
304	no_cache: bool,
305) -> VirtAddr {
306	use crate::arch::mm::paging::PageTableEntryFlags;
307	#[cfg(target_arch = "x86_64")]
308	use crate::arch::mm::paging::PageTableEntryFlagsExt;
309
310	let size = size.align_up(BasePageSize::SIZE as usize);
311	let count = size / BasePageSize::SIZE as usize;
312
313	let mut flags = if no_cache {
314		PageTableEntryFlags::device()
315	} else {
316		PageTableEntryFlags::normal()
317	};
318	flags.set_writable(writable).set_execute(!no_execution);
319
320	let layout = PageLayout::from_size(size).unwrap();
321	let page_range = PageAlloc::allocate(layout).unwrap();
322	let virtual_address = VirtAddr::from(page_range.start());
323	arch::mm::paging::map::<BasePageSize>(virtual_address, physical_address, count, flags);
324
325	virtual_address
326}
327
328#[allow(dead_code)]
329/// Unmaps virtual address, without 'freeing' physical memory it is mapped to!
330pub(crate) fn unmap(virtual_address: VirtAddr, size: usize) {
331	let size = size.align_up(BasePageSize::SIZE as usize);
332
333	if virtual_to_physical(virtual_address).is_some() {
334		arch::mm::paging::unmap::<BasePageSize>(
335			virtual_address,
336			size / BasePageSize::SIZE as usize,
337		);
338
339		let range = PageRange::from_start_len(virtual_address.as_usize(), size).unwrap();
340		unsafe {
341			PageAlloc::deallocate(range);
342		}
343	} else {
344		panic!("No page table entry for virtual address {virtual_address:p}");
345	}
346}