Serenity Operating System
1/*
2 * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/Assertions.h>
8#include <AK/StringView.h>
9#include <Kernel/Arch/CPU.h>
10#include <Kernel/Arch/PageDirectory.h>
11#include <Kernel/Arch/PageFault.h>
12#include <Kernel/Arch/RegisterState.h>
13#include <Kernel/BootInfo.h>
14#include <Kernel/FileSystem/Inode.h>
15#include <Kernel/Heap/kmalloc.h>
16#include <Kernel/InterruptDisabler.h>
17#include <Kernel/KSyms.h>
18#include <Kernel/Memory/AnonymousVMObject.h>
19#include <Kernel/Memory/MemoryManager.h>
20#include <Kernel/Memory/PhysicalRegion.h>
21#include <Kernel/Memory/SharedInodeVMObject.h>
22#include <Kernel/Multiboot.h>
23#include <Kernel/Panic.h>
24#include <Kernel/Prekernel/Prekernel.h>
25#include <Kernel/Process.h>
26#include <Kernel/Sections.h>
27#include <Kernel/StdLib.h>
28
29extern u8 start_of_kernel_image[];
30extern u8 end_of_kernel_image[];
31extern u8 start_of_kernel_text[];
32extern u8 start_of_kernel_data[];
33extern u8 end_of_kernel_bss[];
34extern u8 start_of_ro_after_init[];
35extern u8 end_of_ro_after_init[];
36extern u8 start_of_unmap_after_init[];
37extern u8 end_of_unmap_after_init[];
38extern u8 start_of_kernel_ksyms[];
39extern u8 end_of_kernel_ksyms[];
40
41extern multiboot_module_entry_t multiboot_copy_boot_modules_array[16];
42extern size_t multiboot_copy_boot_modules_count;
43
44namespace Kernel::Memory {
45
46ErrorOr<FlatPtr> page_round_up(FlatPtr x)
47{
48 if (x > (explode_byte(0xFF) & ~0xFFF)) {
49 return Error::from_errno(EINVAL);
50 }
51 return (((FlatPtr)(x)) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1));
52}
53
54// NOTE: We can NOT use Singleton for this class, because
55// MemoryManager::initialize is called *before* global constructors are
56// run. If we do, then Singleton would get re-initialized, causing
57// the memory manager to be initialized twice!
58static MemoryManager* s_the;
59
60MemoryManager& MemoryManager::the()
61{
62 return *s_the;
63}
64
65bool MemoryManager::is_initialized()
66{
67 return s_the != nullptr;
68}
69
70static UNMAP_AFTER_INIT VirtualRange kernel_virtual_range()
71{
72#if ARCH(AARCH64)
73 // NOTE: This is not the same as x86_64, because the aarch64 kernel currently doesn't use the pre-kernel.
74 return VirtualRange { VirtualAddress(kernel_mapping_base), KERNEL_PD_END - kernel_mapping_base };
75#else
76 size_t kernel_range_start = kernel_mapping_base + 2 * MiB; // The first 2 MiB are used for mapping the pre-kernel
77 return VirtualRange { VirtualAddress(kernel_range_start), KERNEL_PD_END - kernel_range_start };
78#endif
79}
80
81MemoryManager::GlobalData::GlobalData()
82 : region_tree(kernel_virtual_range())
83{
84}
85
86UNMAP_AFTER_INIT MemoryManager::MemoryManager()
87{
88 s_the = this;
89
90 parse_memory_map();
91 activate_kernel_page_directory(kernel_page_directory());
92 protect_kernel_image();
93
94 // We're temporarily "committing" to two pages that we need to allocate below
95 auto committed_pages = commit_physical_pages(2).release_value();
96
97 m_shared_zero_page = committed_pages.take_one();
98
99 // We're wasting a page here, we just need a special tag (physical
100 // address) so that we know when we need to lazily allocate a page
101 // that we should be drawing this page from the committed pool rather
102 // than potentially failing if no pages are available anymore.
103 // By using a tag we don't have to query the VMObject for every page
104 // whether it was committed or not
105 m_lazy_committed_page = committed_pages.take_one();
106}
107
108UNMAP_AFTER_INIT MemoryManager::~MemoryManager() = default;
109
110UNMAP_AFTER_INIT void MemoryManager::protect_kernel_image()
111{
112 SpinlockLocker page_lock(kernel_page_directory().get_lock());
113 // Disable writing to the kernel text and rodata segments.
114 for (auto const* i = start_of_kernel_text; i < start_of_kernel_data; i += PAGE_SIZE) {
115 auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
116 pte.set_writable(false);
117 }
118 if (Processor::current().has_nx()) {
119 // Disable execution of the kernel data, bss and heap segments.
120 for (auto const* i = start_of_kernel_data; i < end_of_kernel_image; i += PAGE_SIZE) {
121 auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
122 pte.set_execute_disabled(true);
123 }
124 }
125}
126
127UNMAP_AFTER_INIT void MemoryManager::unmap_prekernel()
128{
129 SpinlockLocker page_lock(kernel_page_directory().get_lock());
130
131 auto start = start_of_prekernel_image.page_base().get();
132 auto end = end_of_prekernel_image.page_base().get();
133
134 for (auto i = start; i <= end; i += PAGE_SIZE)
135 release_pte(kernel_page_directory(), VirtualAddress(i), i == end ? IsLastPTERelease::Yes : IsLastPTERelease::No);
136 flush_tlb(&kernel_page_directory(), VirtualAddress(start), (end - start) / PAGE_SIZE);
137}
138
139UNMAP_AFTER_INIT void MemoryManager::protect_readonly_after_init_memory()
140{
141 SpinlockLocker page_lock(kernel_page_directory().get_lock());
142 // Disable writing to the .ro_after_init section
143 for (auto i = (FlatPtr)&start_of_ro_after_init; i < (FlatPtr)&end_of_ro_after_init; i += PAGE_SIZE) {
144 auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
145 pte.set_writable(false);
146 flush_tlb(&kernel_page_directory(), VirtualAddress(i));
147 }
148}
149
150void MemoryManager::unmap_text_after_init()
151{
152 SpinlockLocker page_lock(kernel_page_directory().get_lock());
153
154 auto start = page_round_down((FlatPtr)&start_of_unmap_after_init);
155 auto end = page_round_up((FlatPtr)&end_of_unmap_after_init).release_value_but_fixme_should_propagate_errors();
156
157 // Unmap the entire .unmap_after_init section
158 for (auto i = start; i < end; i += PAGE_SIZE) {
159 auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
160 pte.clear();
161 flush_tlb(&kernel_page_directory(), VirtualAddress(i));
162 }
163
164 dmesgln("Unmapped {} KiB of kernel text after init! :^)", (end - start) / KiB);
165}
166
167UNMAP_AFTER_INIT void MemoryManager::protect_ksyms_after_init()
168{
169 SpinlockLocker page_lock(kernel_page_directory().get_lock());
170
171 auto start = page_round_down((FlatPtr)start_of_kernel_ksyms);
172 auto end = page_round_up((FlatPtr)end_of_kernel_ksyms).release_value_but_fixme_should_propagate_errors();
173
174 for (auto i = start; i < end; i += PAGE_SIZE) {
175 auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
176 pte.set_writable(false);
177 flush_tlb(&kernel_page_directory(), VirtualAddress(i));
178 }
179
180 dmesgln("Write-protected kernel symbols after init.");
181}
182
183IterationDecision MemoryManager::for_each_physical_memory_range(Function<IterationDecision(PhysicalMemoryRange const&)> callback)
184{
185 return m_global_data.with([&](auto& global_data) {
186 VERIFY(!global_data.physical_memory_ranges.is_empty());
187 for (auto& current_range : global_data.physical_memory_ranges) {
188 IterationDecision decision = callback(current_range);
189 if (decision != IterationDecision::Continue)
190 return decision;
191 }
192 return IterationDecision::Continue;
193 });
194}
195
196UNMAP_AFTER_INIT void MemoryManager::register_reserved_ranges()
197{
198 m_global_data.with([&](auto& global_data) {
199 VERIFY(!global_data.physical_memory_ranges.is_empty());
200 ContiguousReservedMemoryRange range;
201 for (auto& current_range : global_data.physical_memory_ranges) {
202 if (current_range.type != PhysicalMemoryRangeType::Reserved) {
203 if (range.start.is_null())
204 continue;
205 global_data.reserved_memory_ranges.append(ContiguousReservedMemoryRange { range.start, current_range.start.get() - range.start.get() });
206 range.start.set((FlatPtr) nullptr);
207 continue;
208 }
209 if (!range.start.is_null()) {
210 continue;
211 }
212 range.start = current_range.start;
213 }
214 if (global_data.physical_memory_ranges.last().type != PhysicalMemoryRangeType::Reserved)
215 return;
216 if (range.start.is_null())
217 return;
218 global_data.reserved_memory_ranges.append(ContiguousReservedMemoryRange { range.start, global_data.physical_memory_ranges.last().start.get() + global_data.physical_memory_ranges.last().length - range.start.get() });
219 });
220}
221
222bool MemoryManager::is_allowed_to_read_physical_memory_for_userspace(PhysicalAddress start_address, size_t read_length) const
223{
224 // Note: Guard against overflow in case someone tries to mmap on the edge of
225 // the RAM
226 if (start_address.offset_addition_would_overflow(read_length))
227 return false;
228 auto end_address = start_address.offset(read_length);
229
230 return m_global_data.with([&](auto& global_data) {
231 for (auto const& current_range : global_data.reserved_memory_ranges) {
232 if (current_range.start > start_address)
233 continue;
234 if (current_range.start.offset(current_range.length) < end_address)
235 continue;
236 return true;
237 }
238 return false;
239 });
240}
241
242UNMAP_AFTER_INIT void MemoryManager::parse_memory_map()
243{
244 // Register used memory regions that we know of.
245 m_global_data.with([&](auto& global_data) {
246 global_data.used_memory_ranges.ensure_capacity(4);
247#if ARCH(X86_64)
248 global_data.used_memory_ranges.append(UsedMemoryRange { UsedMemoryRangeType::LowMemory, PhysicalAddress(0x00000000), PhysicalAddress(1 * MiB) });
249#endif
250 global_data.used_memory_ranges.append(UsedMemoryRange { UsedMemoryRangeType::Kernel, PhysicalAddress(virtual_to_low_physical((FlatPtr)start_of_kernel_image)), PhysicalAddress(page_round_up(virtual_to_low_physical((FlatPtr)end_of_kernel_image)).release_value_but_fixme_should_propagate_errors()) });
251
252 if (multiboot_flags & 0x4) {
253 auto* bootmods_start = multiboot_copy_boot_modules_array;
254 auto* bootmods_end = bootmods_start + multiboot_copy_boot_modules_count;
255
256 for (auto* bootmod = bootmods_start; bootmod < bootmods_end; bootmod++) {
257 global_data.used_memory_ranges.append(UsedMemoryRange { UsedMemoryRangeType::BootModule, PhysicalAddress(bootmod->start), PhysicalAddress(bootmod->end) });
258 }
259 }
260
261 auto* mmap_begin = multiboot_memory_map;
262 auto* mmap_end = multiboot_memory_map + multiboot_memory_map_count;
263
264 struct ContiguousPhysicalVirtualRange {
265 PhysicalAddress lower;
266 PhysicalAddress upper;
267 };
268
269 Vector<ContiguousPhysicalVirtualRange> contiguous_physical_ranges;
270
271 for (auto* mmap = mmap_begin; mmap < mmap_end; mmap++) {
272 // We have to copy these onto the stack, because we take a reference to these when printing them out,
273 // and doing so on a packed struct field is UB.
274 auto address = mmap->addr;
275 auto length = mmap->len;
276 ArmedScopeGuard write_back_guard = [&]() {
277 mmap->addr = address;
278 mmap->len = length;
279 };
280
281 dmesgln("MM: Multiboot mmap: address={:p}, length={}, type={}", address, length, mmap->type);
282
283 auto start_address = PhysicalAddress(address);
284 switch (mmap->type) {
285 case (MULTIBOOT_MEMORY_AVAILABLE):
286 global_data.physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Usable, start_address, length });
287 break;
288 case (MULTIBOOT_MEMORY_RESERVED):
289#if ARCH(X86_64)
290 // Workaround for https://gitlab.com/qemu-project/qemu/-/commit/8504f129450b909c88e199ca44facd35d38ba4de
291 // That commit added a reserved 12GiB entry for the benefit of virtual firmware.
292 // We can safely ignore this block as it isn't actually reserved on any real hardware.
293 // From: https://lore.kernel.org/all/20220701161014.3850-1-joao.m.martins@oracle.com/
294 // "Always add the HyperTransport range into e820 even when the relocation isn't
295 // done *and* there's >= 40 phys bit that would put max phyusical boundary to 1T
296 // This should allow virtual firmware to avoid the reserved range at the
297 // 1T boundary on VFs with big bars."
298 if (address != 0x000000fd00000000 || length != (0x000000ffffffffff - 0x000000fd00000000) + 1)
299#endif
300 global_data.physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Reserved, start_address, length });
301 break;
302 case (MULTIBOOT_MEMORY_ACPI_RECLAIMABLE):
303 global_data.physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::ACPI_Reclaimable, start_address, length });
304 break;
305 case (MULTIBOOT_MEMORY_NVS):
306 global_data.physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::ACPI_NVS, start_address, length });
307 break;
308 case (MULTIBOOT_MEMORY_BADRAM):
309 dmesgln("MM: Warning, detected bad memory range!");
310 global_data.physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::BadMemory, start_address, length });
311 break;
312 default:
313 dbgln("MM: Unknown range!");
314 global_data.physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Unknown, start_address, length });
315 break;
316 }
317
318 if (mmap->type != MULTIBOOT_MEMORY_AVAILABLE)
319 continue;
320
321 // Fix up unaligned memory regions.
322 auto diff = (FlatPtr)address % PAGE_SIZE;
323 if (diff != 0) {
324 dmesgln("MM: Got an unaligned physical_region from the bootloader; correcting {:p} by {} bytes", address, diff);
325 diff = PAGE_SIZE - diff;
326 address += diff;
327 length -= diff;
328 }
329 if ((length % PAGE_SIZE) != 0) {
330 dmesgln("MM: Got an unaligned physical_region from the bootloader; correcting length {} by {} bytes", length, length % PAGE_SIZE);
331 length -= length % PAGE_SIZE;
332 }
333 if (length < PAGE_SIZE) {
334 dmesgln("MM: Memory physical_region from bootloader is too small; we want >= {} bytes, but got {} bytes", PAGE_SIZE, length);
335 continue;
336 }
337
338 for (PhysicalSize page_base = address; page_base <= (address + length); page_base += PAGE_SIZE) {
339 auto addr = PhysicalAddress(page_base);
340
341 // Skip used memory ranges.
342 bool should_skip = false;
343 for (auto& used_range : global_data.used_memory_ranges) {
344 if (addr.get() >= used_range.start.get() && addr.get() <= used_range.end.get()) {
345 should_skip = true;
346 break;
347 }
348 }
349 if (should_skip)
350 continue;
351
352 if (contiguous_physical_ranges.is_empty() || contiguous_physical_ranges.last().upper.offset(PAGE_SIZE) != addr) {
353 contiguous_physical_ranges.append(ContiguousPhysicalVirtualRange {
354 .lower = addr,
355 .upper = addr,
356 });
357 } else {
358 contiguous_physical_ranges.last().upper = addr;
359 }
360 }
361 }
362
363 for (auto& range : contiguous_physical_ranges) {
364 global_data.physical_regions.append(PhysicalRegion::try_create(range.lower, range.upper).release_nonnull());
365 }
366
367 for (auto& region : global_data.physical_regions)
368 global_data.system_memory_info.physical_pages += region->size();
369
370 register_reserved_ranges();
371 for (auto& range : global_data.reserved_memory_ranges) {
372 dmesgln("MM: Contiguous reserved range from {}, length is {}", range.start, range.length);
373 }
374
375 initialize_physical_pages();
376
377 VERIFY(global_data.system_memory_info.physical_pages > 0);
378
379 // We start out with no committed pages
380 global_data.system_memory_info.physical_pages_uncommitted = global_data.system_memory_info.physical_pages;
381
382 for (auto& used_range : global_data.used_memory_ranges) {
383 dmesgln("MM: {} range @ {} - {} (size {:#x})", UserMemoryRangeTypeNames[to_underlying(used_range.type)], used_range.start, used_range.end.offset(-1), used_range.end.as_ptr() - used_range.start.as_ptr());
384 }
385
386 for (auto& region : global_data.physical_regions) {
387 dmesgln("MM: User physical region: {} - {} (size {:#x})", region->lower(), region->upper().offset(-1), PAGE_SIZE * region->size());
388 region->initialize_zones();
389 }
390 });
391}
392
393UNMAP_AFTER_INIT void MemoryManager::initialize_physical_pages()
394{
395 m_global_data.with([&](auto& global_data) {
396 // We assume that the physical page range is contiguous and doesn't contain huge gaps!
397 PhysicalAddress highest_physical_address;
398 for (auto& range : global_data.used_memory_ranges) {
399 if (range.end.get() > highest_physical_address.get())
400 highest_physical_address = range.end;
401 }
402 for (auto& region : global_data.physical_memory_ranges) {
403 auto range_end = PhysicalAddress(region.start).offset(region.length);
404 if (range_end.get() > highest_physical_address.get())
405 highest_physical_address = range_end;
406 }
407
408 // Calculate how many total physical pages the array will have
409 m_physical_page_entries_count = PhysicalAddress::physical_page_index(highest_physical_address.get()) + 1;
410 VERIFY(m_physical_page_entries_count != 0);
411 VERIFY(!Checked<decltype(m_physical_page_entries_count)>::multiplication_would_overflow(m_physical_page_entries_count, sizeof(PhysicalPageEntry)));
412
413 // Calculate how many bytes the array will consume
414 auto physical_page_array_size = m_physical_page_entries_count * sizeof(PhysicalPageEntry);
415 auto physical_page_array_pages = page_round_up(physical_page_array_size).release_value_but_fixme_should_propagate_errors() / PAGE_SIZE;
416 VERIFY(physical_page_array_pages * PAGE_SIZE >= physical_page_array_size);
417
418 // Calculate how many page tables we will need to be able to map them all
419 auto needed_page_table_count = (physical_page_array_pages + 512 - 1) / 512;
420
421 auto physical_page_array_pages_and_page_tables_count = physical_page_array_pages + needed_page_table_count;
422
423 // Now that we know how much memory we need for a contiguous array of PhysicalPage instances, find a memory region that can fit it
424 PhysicalRegion* found_region { nullptr };
425 Optional<size_t> found_region_index;
426 for (size_t i = 0; i < global_data.physical_regions.size(); ++i) {
427 auto& region = global_data.physical_regions[i];
428 if (region->size() >= physical_page_array_pages_and_page_tables_count) {
429 found_region = region;
430 found_region_index = i;
431 break;
432 }
433 }
434
435 if (!found_region) {
436 dmesgln("MM: Need {} bytes for physical page management, but no memory region is large enough!", physical_page_array_pages_and_page_tables_count);
437 VERIFY_NOT_REACHED();
438 }
439
440 VERIFY(global_data.system_memory_info.physical_pages >= physical_page_array_pages_and_page_tables_count);
441 global_data.system_memory_info.physical_pages -= physical_page_array_pages_and_page_tables_count;
442
443 if (found_region->size() == physical_page_array_pages_and_page_tables_count) {
444 // We're stealing the entire region
445 global_data.physical_pages_region = global_data.physical_regions.take(*found_region_index);
446 } else {
447 global_data.physical_pages_region = found_region->try_take_pages_from_beginning(physical_page_array_pages_and_page_tables_count);
448 }
449 global_data.used_memory_ranges.append({ UsedMemoryRangeType::PhysicalPages, global_data.physical_pages_region->lower(), global_data.physical_pages_region->upper() });
450
451 // Create the bare page directory. This is not a fully constructed page directory and merely contains the allocators!
452 m_kernel_page_directory = PageDirectory::must_create_kernel_page_directory();
453
454 {
455 // Carve out the whole page directory covering the kernel image to make MemoryManager::initialize_physical_pages() happy
456 FlatPtr start_of_range = ((FlatPtr)start_of_kernel_image & ~(FlatPtr)0x1fffff);
457 FlatPtr end_of_range = ((FlatPtr)end_of_kernel_image & ~(FlatPtr)0x1fffff) + 0x200000;
458 MUST(global_data.region_tree.place_specifically(*MUST(Region::create_unbacked()).leak_ptr(), VirtualRange { VirtualAddress(start_of_range), end_of_range - start_of_range }));
459 }
460
461 // Allocate a virtual address range for our array
462 // This looks awkward, but it basically creates a dummy region to occupy the address range permanently.
463 auto& region = *MUST(Region::create_unbacked()).leak_ptr();
464 MUST(global_data.region_tree.place_anywhere(region, RandomizeVirtualAddress::No, physical_page_array_pages * PAGE_SIZE));
465 auto range = region.range();
466
467 // Now that we have our special m_physical_pages_region region with enough pages to hold the entire array
468 // try to map the entire region into kernel space so we always have it
469 // We can't use ensure_pte here because it would try to allocate a PhysicalPage and we don't have the array
470 // mapped yet so we can't create them
471
472 // Create page tables at the beginning of m_physical_pages_region, followed by the PhysicalPageEntry array
473 auto page_tables_base = global_data.physical_pages_region->lower();
474 auto physical_page_array_base = page_tables_base.offset(needed_page_table_count * PAGE_SIZE);
475 auto physical_page_array_current_page = physical_page_array_base.get();
476 auto virtual_page_array_base = range.base().get();
477 auto virtual_page_array_current_page = virtual_page_array_base;
478 for (size_t pt_index = 0; pt_index < needed_page_table_count; pt_index++) {
479 auto virtual_page_base_for_this_pt = virtual_page_array_current_page;
480 auto pt_paddr = page_tables_base.offset(pt_index * PAGE_SIZE);
481 auto* pt = reinterpret_cast<PageTableEntry*>(quickmap_page(pt_paddr));
482 __builtin_memset(pt, 0, PAGE_SIZE);
483 for (size_t pte_index = 0; pte_index < PAGE_SIZE / sizeof(PageTableEntry); pte_index++) {
484 auto& pte = pt[pte_index];
485 pte.set_physical_page_base(physical_page_array_current_page);
486 pte.set_user_allowed(false);
487 pte.set_writable(true);
488 if (Processor::current().has_nx())
489 pte.set_execute_disabled(false);
490 pte.set_global(true);
491 pte.set_present(true);
492
493 physical_page_array_current_page += PAGE_SIZE;
494 virtual_page_array_current_page += PAGE_SIZE;
495 }
496 unquickmap_page();
497
498 // Hook the page table into the kernel page directory
499 u32 page_directory_index = (virtual_page_base_for_this_pt >> 21) & 0x1ff;
500 auto* pd = reinterpret_cast<PageDirectoryEntry*>(quickmap_page(boot_pd_kernel));
501 PageDirectoryEntry& pde = pd[page_directory_index];
502
503 VERIFY(!pde.is_present()); // Nothing should be using this PD yet
504
505 // We can't use ensure_pte quite yet!
506 pde.set_page_table_base(pt_paddr.get());
507 pde.set_user_allowed(false);
508 pde.set_present(true);
509 pde.set_writable(true);
510 pde.set_global(true);
511
512 unquickmap_page();
513
514 flush_tlb_local(VirtualAddress(virtual_page_base_for_this_pt));
515 }
516
517 // We now have the entire PhysicalPageEntry array mapped!
518 m_physical_page_entries = (PhysicalPageEntry*)range.base().get();
519 for (size_t i = 0; i < m_physical_page_entries_count; i++)
520 new (&m_physical_page_entries[i]) PageTableEntry();
521
522 // Now we should be able to allocate PhysicalPage instances,
523 // so finish setting up the kernel page directory
524 m_kernel_page_directory->allocate_kernel_directory();
525
526 // Now create legit PhysicalPage objects for the page tables we created.
527 virtual_page_array_current_page = virtual_page_array_base;
528 for (size_t pt_index = 0; pt_index < needed_page_table_count; pt_index++) {
529 VERIFY(virtual_page_array_current_page <= range.end().get());
530 auto pt_paddr = page_tables_base.offset(pt_index * PAGE_SIZE);
531 auto physical_page_index = PhysicalAddress::physical_page_index(pt_paddr.get());
532 auto& physical_page_entry = m_physical_page_entries[physical_page_index];
533 auto physical_page = adopt_lock_ref(*new (&physical_page_entry.allocated.physical_page) PhysicalPage(MayReturnToFreeList::No));
534
535 // NOTE: This leaked ref is matched by the unref in MemoryManager::release_pte()
536 (void)physical_page.leak_ref();
537
538 virtual_page_array_current_page += (PAGE_SIZE / sizeof(PageTableEntry)) * PAGE_SIZE;
539 }
540
541 dmesgln("MM: Physical page entries: {}", range);
542 });
543}
544
545PhysicalPageEntry& MemoryManager::get_physical_page_entry(PhysicalAddress physical_address)
546{
547 auto physical_page_entry_index = PhysicalAddress::physical_page_index(physical_address.get());
548 VERIFY(physical_page_entry_index < m_physical_page_entries_count);
549 return m_physical_page_entries[physical_page_entry_index];
550}
551
552PhysicalAddress MemoryManager::get_physical_address(PhysicalPage const& physical_page)
553{
554 PhysicalPageEntry const& physical_page_entry = *reinterpret_cast<PhysicalPageEntry const*>((u8 const*)&physical_page - __builtin_offsetof(PhysicalPageEntry, allocated.physical_page));
555 size_t physical_page_entry_index = &physical_page_entry - m_physical_page_entries;
556 VERIFY(physical_page_entry_index < m_physical_page_entries_count);
557 return PhysicalAddress((PhysicalPtr)physical_page_entry_index * PAGE_SIZE);
558}
559
560PageTableEntry* MemoryManager::pte(PageDirectory& page_directory, VirtualAddress vaddr)
561{
562 VERIFY_INTERRUPTS_DISABLED();
563 VERIFY(page_directory.get_lock().is_locked_by_current_processor());
564 u32 page_directory_table_index = (vaddr.get() >> 30) & 0x1ff;
565 u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
566 u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
567
568 auto* pd = quickmap_pd(const_cast<PageDirectory&>(page_directory), page_directory_table_index);
569 PageDirectoryEntry const& pde = pd[page_directory_index];
570 if (!pde.is_present())
571 return nullptr;
572
573 return &quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()))[page_table_index];
574}
575
576PageTableEntry* MemoryManager::ensure_pte(PageDirectory& page_directory, VirtualAddress vaddr)
577{
578 VERIFY_INTERRUPTS_DISABLED();
579 VERIFY(page_directory.get_lock().is_locked_by_current_processor());
580 u32 page_directory_table_index = (vaddr.get() >> 30) & 0x1ff;
581 u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
582 u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
583
584 auto* pd = quickmap_pd(page_directory, page_directory_table_index);
585 auto& pde = pd[page_directory_index];
586 if (pde.is_present())
587 return &quickmap_pt(PhysicalAddress(pde.page_table_base()))[page_table_index];
588
589 bool did_purge = false;
590 auto page_table_or_error = allocate_physical_page(ShouldZeroFill::Yes, &did_purge);
591 if (page_table_or_error.is_error()) {
592 dbgln("MM: Unable to allocate page table to map {}", vaddr);
593 return nullptr;
594 }
595 auto page_table = page_table_or_error.release_value();
596 if (did_purge) {
597 // If any memory had to be purged, ensure_pte may have been called as part
598 // of the purging process. So we need to re-map the pd in this case to ensure
599 // we're writing to the correct underlying physical page
600 pd = quickmap_pd(page_directory, page_directory_table_index);
601 VERIFY(&pde == &pd[page_directory_index]); // Sanity check
602
603 VERIFY(!pde.is_present()); // Should have not changed
604 }
605 pde.set_page_table_base(page_table->paddr().get());
606 pde.set_user_allowed(true);
607 pde.set_present(true);
608 pde.set_writable(true);
609 pde.set_global(&page_directory == m_kernel_page_directory.ptr());
610
611 // NOTE: This leaked ref is matched by the unref in MemoryManager::release_pte()
612 (void)page_table.leak_ref();
613
614 return &quickmap_pt(PhysicalAddress(pde.page_table_base()))[page_table_index];
615}
616
617void MemoryManager::release_pte(PageDirectory& page_directory, VirtualAddress vaddr, IsLastPTERelease is_last_pte_release)
618{
619 VERIFY_INTERRUPTS_DISABLED();
620 VERIFY(page_directory.get_lock().is_locked_by_current_processor());
621 u32 page_directory_table_index = (vaddr.get() >> 30) & 0x1ff;
622 u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
623 u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
624
625 auto* pd = quickmap_pd(page_directory, page_directory_table_index);
626 PageDirectoryEntry& pde = pd[page_directory_index];
627 if (pde.is_present()) {
628 auto* page_table = quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()));
629 auto& pte = page_table[page_table_index];
630 pte.clear();
631
632 if (is_last_pte_release == IsLastPTERelease::Yes || page_table_index == 0x1ff) {
633 // If this is the last PTE in a region or the last PTE in a page table then
634 // check if we can also release the page table
635 bool all_clear = true;
636 for (u32 i = 0; i <= 0x1ff; i++) {
637 if (!page_table[i].is_null()) {
638 all_clear = false;
639 break;
640 }
641 }
642 if (all_clear) {
643 get_physical_page_entry(PhysicalAddress { pde.page_table_base() }).allocated.physical_page.unref();
644 pde.clear();
645 }
646 }
647 }
648}
649
650UNMAP_AFTER_INIT void MemoryManager::initialize(u32 cpu)
651{
652 dmesgln("Initialize MMU");
653 ProcessorSpecific<MemoryManagerData>::initialize();
654
655 if (cpu == 0) {
656 new MemoryManager;
657 kmalloc_enable_expand();
658 }
659}
660
661Region* MemoryManager::kernel_region_from_vaddr(VirtualAddress address)
662{
663 if (is_user_address(address))
664 return nullptr;
665
666 return MM.m_global_data.with([&](auto& global_data) {
667 return global_data.region_tree.find_region_containing(address);
668 });
669}
670
671Region* MemoryManager::find_user_region_from_vaddr(AddressSpace& space, VirtualAddress vaddr)
672{
673 return space.find_region_containing({ vaddr, 1 });
674}
675
676void MemoryManager::validate_syscall_preconditions(Process& process, RegisterState const& regs)
677{
678 bool should_crash = false;
679 char const* crash_description = nullptr;
680 int crash_signal = 0;
681
682 auto unlock_and_handle_crash = [&](char const* description, int signal) {
683 should_crash = true;
684 crash_description = description;
685 crash_signal = signal;
686 };
687
688 process.address_space().with([&](auto& space) -> void {
689 VirtualAddress userspace_sp = VirtualAddress { regs.userspace_sp() };
690 if (!MM.validate_user_stack(*space, userspace_sp)) {
691 dbgln("Invalid stack pointer: {}", userspace_sp);
692 return unlock_and_handle_crash("Bad stack on syscall entry", SIGSEGV);
693 }
694
695 VirtualAddress ip = VirtualAddress { regs.ip() };
696 auto* calling_region = MM.find_user_region_from_vaddr(*space, ip);
697 if (!calling_region) {
698 dbgln("Syscall from {:p} which has no associated region", ip);
699 return unlock_and_handle_crash("Syscall from unknown region", SIGSEGV);
700 }
701
702 if (calling_region->is_writable()) {
703 dbgln("Syscall from writable memory at {:p}", ip);
704 return unlock_and_handle_crash("Syscall from writable memory", SIGSEGV);
705 }
706
707 if (space->enforces_syscall_regions() && !calling_region->is_syscall_region()) {
708 dbgln("Syscall from non-syscall region");
709 return unlock_and_handle_crash("Syscall from non-syscall region", SIGSEGV);
710 }
711 });
712
713 if (should_crash) {
714 handle_crash(regs, crash_description, crash_signal);
715 }
716}
717
718Region* MemoryManager::find_region_from_vaddr(VirtualAddress vaddr)
719{
720 if (auto* region = kernel_region_from_vaddr(vaddr))
721 return region;
722 auto page_directory = PageDirectory::find_current();
723 if (!page_directory)
724 return nullptr;
725 VERIFY(page_directory->address_space());
726 return find_user_region_from_vaddr(*page_directory->address_space(), vaddr);
727}
728
729PageFaultResponse MemoryManager::handle_page_fault(PageFault const& fault)
730{
731 auto faulted_in_range = [&fault](auto const* start, auto const* end) {
732 return fault.vaddr() >= VirtualAddress { start } && fault.vaddr() < VirtualAddress { end };
733 };
734
735 if (faulted_in_range(&start_of_ro_after_init, &end_of_ro_after_init))
736 PANIC("Attempt to write into READONLY_AFTER_INIT section");
737
738 if (faulted_in_range(&start_of_unmap_after_init, &end_of_unmap_after_init)) {
739 auto const* kernel_symbol = symbolicate_kernel_address(fault.vaddr().get());
740 PANIC("Attempt to access UNMAP_AFTER_INIT section ({:p}: {})", fault.vaddr(), kernel_symbol ? kernel_symbol->name : "(Unknown)");
741 }
742
743 if (faulted_in_range(&start_of_kernel_ksyms, &end_of_kernel_ksyms))
744 PANIC("Attempt to access KSYMS section");
745
746 if (Processor::current_in_irq()) {
747 dbgln("CPU[{}] BUG! Page fault while handling IRQ! code={}, vaddr={}, irq level: {}",
748 Processor::current_id(), fault.code(), fault.vaddr(), Processor::current_in_irq());
749 dump_kernel_regions();
750 return PageFaultResponse::ShouldCrash;
751 }
752 dbgln_if(PAGE_FAULT_DEBUG, "MM: CPU[{}] handle_page_fault({:#04x}) at {}", Processor::current_id(), fault.code(), fault.vaddr());
753 auto* region = find_region_from_vaddr(fault.vaddr());
754 if (!region) {
755 return PageFaultResponse::ShouldCrash;
756 }
757 return region->handle_fault(fault);
758}
759
760ErrorOr<NonnullOwnPtr<Region>> MemoryManager::allocate_contiguous_kernel_region(size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
761{
762 VERIFY(!(size % PAGE_SIZE));
763 OwnPtr<KString> name_kstring;
764 if (!name.is_null())
765 name_kstring = TRY(KString::try_create(name));
766 auto vmobject = TRY(AnonymousVMObject::try_create_physically_contiguous_with_size(size));
767 auto region = TRY(Region::create_unplaced(move(vmobject), 0, move(name_kstring), access, cacheable));
768 TRY(m_global_data.with([&](auto& global_data) { return global_data.region_tree.place_anywhere(*region, RandomizeVirtualAddress::No, size); }));
769 TRY(region->map(kernel_page_directory()));
770 return region;
771}
772
773ErrorOr<NonnullOwnPtr<Memory::Region>> MemoryManager::allocate_dma_buffer_page(StringView name, Memory::Region::Access access, RefPtr<Memory::PhysicalPage>& dma_buffer_page)
774{
775 dma_buffer_page = TRY(allocate_physical_page());
776 // Do not enable Cache for this region as physical memory transfers are performed (Most architectures have this behaviour by default)
777 return allocate_kernel_region(dma_buffer_page->paddr(), PAGE_SIZE, name, access, Region::Cacheable::No);
778}
779
780ErrorOr<NonnullOwnPtr<Memory::Region>> MemoryManager::allocate_dma_buffer_page(StringView name, Memory::Region::Access access)
781{
782 RefPtr<Memory::PhysicalPage> dma_buffer_page;
783
784 return allocate_dma_buffer_page(name, access, dma_buffer_page);
785}
786
787ErrorOr<NonnullOwnPtr<Memory::Region>> MemoryManager::allocate_dma_buffer_pages(size_t size, StringView name, Memory::Region::Access access, Vector<NonnullRefPtr<Memory::PhysicalPage>>& dma_buffer_pages)
788{
789 VERIFY(!(size % PAGE_SIZE));
790 dma_buffer_pages = TRY(allocate_contiguous_physical_pages(size));
791 // Do not enable Cache for this region as physical memory transfers are performed (Most architectures have this behaviour by default)
792 return allocate_kernel_region(dma_buffer_pages.first()->paddr(), size, name, access, Region::Cacheable::No);
793}
794
795ErrorOr<NonnullOwnPtr<Memory::Region>> MemoryManager::allocate_dma_buffer_pages(size_t size, StringView name, Memory::Region::Access access)
796{
797 VERIFY(!(size % PAGE_SIZE));
798 Vector<NonnullRefPtr<Memory::PhysicalPage>> dma_buffer_pages;
799
800 return allocate_dma_buffer_pages(size, name, access, dma_buffer_pages);
801}
802
803ErrorOr<NonnullOwnPtr<Region>> MemoryManager::allocate_kernel_region(size_t size, StringView name, Region::Access access, AllocationStrategy strategy, Region::Cacheable cacheable)
804{
805 VERIFY(!(size % PAGE_SIZE));
806 OwnPtr<KString> name_kstring;
807 if (!name.is_null())
808 name_kstring = TRY(KString::try_create(name));
809 auto vmobject = TRY(AnonymousVMObject::try_create_with_size(size, strategy));
810 auto region = TRY(Region::create_unplaced(move(vmobject), 0, move(name_kstring), access, cacheable));
811 TRY(m_global_data.with([&](auto& global_data) { return global_data.region_tree.place_anywhere(*region, RandomizeVirtualAddress::No, size); }));
812 TRY(region->map(kernel_page_directory()));
813 return region;
814}
815
816ErrorOr<NonnullOwnPtr<Region>> MemoryManager::allocate_kernel_region(PhysicalAddress paddr, size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
817{
818 VERIFY(!(size % PAGE_SIZE));
819 auto vmobject = TRY(AnonymousVMObject::try_create_for_physical_range(paddr, size));
820 OwnPtr<KString> name_kstring;
821 if (!name.is_null())
822 name_kstring = TRY(KString::try_create(name));
823 auto region = TRY(Region::create_unplaced(move(vmobject), 0, move(name_kstring), access, cacheable));
824 TRY(m_global_data.with([&](auto& global_data) { return global_data.region_tree.place_anywhere(*region, RandomizeVirtualAddress::No, size, PAGE_SIZE); }));
825 TRY(region->map(kernel_page_directory()));
826 return region;
827}
828
829ErrorOr<NonnullOwnPtr<Region>> MemoryManager::allocate_kernel_region_with_vmobject(VMObject& vmobject, size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
830{
831 VERIFY(!(size % PAGE_SIZE));
832
833 OwnPtr<KString> name_kstring;
834 if (!name.is_null())
835 name_kstring = TRY(KString::try_create(name));
836
837 auto region = TRY(Region::create_unplaced(vmobject, 0, move(name_kstring), access, cacheable));
838 TRY(m_global_data.with([&](auto& global_data) { return global_data.region_tree.place_anywhere(*region, RandomizeVirtualAddress::No, size); }));
839 TRY(region->map(kernel_page_directory()));
840 return region;
841}
842
843ErrorOr<CommittedPhysicalPageSet> MemoryManager::commit_physical_pages(size_t page_count)
844{
845 VERIFY(page_count > 0);
846 auto result = m_global_data.with([&](auto& global_data) -> ErrorOr<CommittedPhysicalPageSet> {
847 if (global_data.system_memory_info.physical_pages_uncommitted < page_count) {
848 dbgln("MM: Unable to commit {} pages, have only {}", page_count, global_data.system_memory_info.physical_pages_uncommitted);
849 return ENOMEM;
850 }
851
852 global_data.system_memory_info.physical_pages_uncommitted -= page_count;
853 global_data.system_memory_info.physical_pages_committed += page_count;
854 return CommittedPhysicalPageSet { {}, page_count };
855 });
856 if (result.is_error()) {
857 Process::for_each_ignoring_jails([&](Process const& process) {
858 size_t amount_resident = 0;
859 size_t amount_shared = 0;
860 size_t amount_virtual = 0;
861 process.address_space().with([&](auto& space) {
862 amount_resident = space->amount_resident();
863 amount_shared = space->amount_shared();
864 amount_virtual = space->amount_virtual();
865 });
866 process.name().with([&](auto& process_name) {
867 dbgln("{}({}) resident:{}, shared:{}, virtual:{}",
868 process_name->view(),
869 process.pid(),
870 amount_resident / PAGE_SIZE,
871 amount_shared / PAGE_SIZE,
872 amount_virtual / PAGE_SIZE);
873 });
874 return IterationDecision::Continue;
875 });
876 }
877 return result;
878}
879
880void MemoryManager::uncommit_physical_pages(Badge<CommittedPhysicalPageSet>, size_t page_count)
881{
882 VERIFY(page_count > 0);
883
884 m_global_data.with([&](auto& global_data) {
885 VERIFY(global_data.system_memory_info.physical_pages_committed >= page_count);
886
887 global_data.system_memory_info.physical_pages_uncommitted += page_count;
888 global_data.system_memory_info.physical_pages_committed -= page_count;
889 });
890}
891
892void MemoryManager::deallocate_physical_page(PhysicalAddress paddr)
893{
894 return m_global_data.with([&](auto& global_data) {
895 // Are we returning a user page?
896 for (auto& region : global_data.physical_regions) {
897 if (!region->contains(paddr))
898 continue;
899
900 region->return_page(paddr);
901 --global_data.system_memory_info.physical_pages_used;
902
903 // Always return pages to the uncommitted pool. Pages that were
904 // committed and allocated are only freed upon request. Once
905 // returned there is no guarantee being able to get them back.
906 ++global_data.system_memory_info.physical_pages_uncommitted;
907 return;
908 }
909 PANIC("MM: deallocate_physical_page couldn't figure out region for page @ {}", paddr);
910 });
911}
912
913RefPtr<PhysicalPage> MemoryManager::find_free_physical_page(bool committed)
914{
915 RefPtr<PhysicalPage> page;
916 m_global_data.with([&](auto& global_data) {
917 if (committed) {
918 // Draw from the committed pages pool. We should always have these pages available
919 VERIFY(global_data.system_memory_info.physical_pages_committed > 0);
920 global_data.system_memory_info.physical_pages_committed--;
921 } else {
922 // We need to make sure we don't touch pages that we have committed to
923 if (global_data.system_memory_info.physical_pages_uncommitted == 0)
924 return;
925 global_data.system_memory_info.physical_pages_uncommitted--;
926 }
927 for (auto& region : global_data.physical_regions) {
928 page = region->take_free_page();
929 if (!page.is_null()) {
930 ++global_data.system_memory_info.physical_pages_used;
931 break;
932 }
933 }
934 });
935
936 if (page.is_null())
937 dbgln("MM: couldn't find free physical page. Continuing...");
938
939 return page;
940}
941
942NonnullRefPtr<PhysicalPage> MemoryManager::allocate_committed_physical_page(Badge<CommittedPhysicalPageSet>, ShouldZeroFill should_zero_fill)
943{
944 auto page = find_free_physical_page(true);
945 VERIFY(page);
946 if (should_zero_fill == ShouldZeroFill::Yes) {
947 InterruptDisabler disabler;
948 auto* ptr = quickmap_page(*page);
949 memset(ptr, 0, PAGE_SIZE);
950 unquickmap_page();
951 }
952 return page.release_nonnull();
953}
954
955ErrorOr<NonnullRefPtr<PhysicalPage>> MemoryManager::allocate_physical_page(ShouldZeroFill should_zero_fill, bool* did_purge)
956{
957 return m_global_data.with([&](auto&) -> ErrorOr<NonnullRefPtr<PhysicalPage>> {
958 auto page = find_free_physical_page(false);
959 bool purged_pages = false;
960
961 if (!page) {
962 // We didn't have a single free physical page. Let's try to free something up!
963 // First, we look for a purgeable VMObject in the volatile state.
964 for_each_vmobject([&](auto& vmobject) {
965 if (!vmobject.is_anonymous())
966 return IterationDecision::Continue;
967 auto& anonymous_vmobject = static_cast<AnonymousVMObject&>(vmobject);
968 if (!anonymous_vmobject.is_purgeable() || !anonymous_vmobject.is_volatile())
969 return IterationDecision::Continue;
970 if (auto purged_page_count = anonymous_vmobject.purge()) {
971 dbgln("MM: Purge saved the day! Purged {} pages from AnonymousVMObject", purged_page_count);
972 page = find_free_physical_page(false);
973 purged_pages = true;
974 VERIFY(page);
975 return IterationDecision::Break;
976 }
977 return IterationDecision::Continue;
978 });
979 }
980 if (!page) {
981 // Second, we look for a file-backed VMObject with clean pages.
982 for_each_vmobject([&](auto& vmobject) {
983 if (!vmobject.is_inode())
984 return IterationDecision::Continue;
985 auto& inode_vmobject = static_cast<InodeVMObject&>(vmobject);
986 if (auto released_page_count = inode_vmobject.try_release_clean_pages(1)) {
987 dbgln("MM: Clean inode release saved the day! Released {} pages from InodeVMObject", released_page_count);
988 page = find_free_physical_page(false);
989 VERIFY(page);
990 return IterationDecision::Break;
991 }
992 return IterationDecision::Continue;
993 });
994 }
995 if (!page) {
996 dmesgln("MM: no physical pages available");
997 return ENOMEM;
998 }
999
1000 if (should_zero_fill == ShouldZeroFill::Yes) {
1001 auto* ptr = quickmap_page(*page);
1002 memset(ptr, 0, PAGE_SIZE);
1003 unquickmap_page();
1004 }
1005
1006 if (did_purge)
1007 *did_purge = purged_pages;
1008 return page.release_nonnull();
1009 });
1010}
1011
1012ErrorOr<Vector<NonnullRefPtr<PhysicalPage>>> MemoryManager::allocate_contiguous_physical_pages(size_t size)
1013{
1014 VERIFY(!(size % PAGE_SIZE));
1015 size_t page_count = ceil_div(size, static_cast<size_t>(PAGE_SIZE));
1016
1017 auto physical_pages = TRY(m_global_data.with([&](auto& global_data) -> ErrorOr<Vector<NonnullRefPtr<PhysicalPage>>> {
1018 // We need to make sure we don't touch pages that we have committed to
1019 if (global_data.system_memory_info.physical_pages_uncommitted < page_count)
1020 return ENOMEM;
1021
1022 for (auto& physical_region : global_data.physical_regions) {
1023 auto physical_pages = physical_region->take_contiguous_free_pages(page_count);
1024 if (!physical_pages.is_empty()) {
1025 global_data.system_memory_info.physical_pages_uncommitted -= page_count;
1026 global_data.system_memory_info.physical_pages_used += page_count;
1027 return physical_pages;
1028 }
1029 }
1030 dmesgln("MM: no contiguous physical pages available");
1031 return ENOMEM;
1032 }));
1033
1034 {
1035 auto cleanup_region = TRY(MM.allocate_kernel_region(physical_pages[0]->paddr(), PAGE_SIZE * page_count, {}, Region::Access::Read | Region::Access::Write));
1036 memset(cleanup_region->vaddr().as_ptr(), 0, PAGE_SIZE * page_count);
1037 }
1038 return physical_pages;
1039}
1040
1041void MemoryManager::enter_process_address_space(Process& process)
1042{
1043 process.address_space().with([](auto& space) {
1044 enter_address_space(*space);
1045 });
1046}
1047
1048void MemoryManager::enter_address_space(AddressSpace& space)
1049{
1050 auto* current_thread = Thread::current();
1051 VERIFY(current_thread != nullptr);
1052 activate_page_directory(space.page_directory(), current_thread);
1053}
1054
1055void MemoryManager::flush_tlb_local(VirtualAddress vaddr, size_t page_count)
1056{
1057 Processor::flush_tlb_local(vaddr, page_count);
1058}
1059
1060void MemoryManager::flush_tlb(PageDirectory const* page_directory, VirtualAddress vaddr, size_t page_count)
1061{
1062 Processor::flush_tlb(page_directory, vaddr, page_count);
1063}
1064
1065PageDirectoryEntry* MemoryManager::quickmap_pd(PageDirectory& directory, size_t pdpt_index)
1066{
1067 VERIFY_INTERRUPTS_DISABLED();
1068
1069 VirtualAddress vaddr(KERNEL_QUICKMAP_PD_PER_CPU_BASE + Processor::current_id() * PAGE_SIZE);
1070 size_t pte_index = (vaddr.get() - KERNEL_PT1024_BASE) / PAGE_SIZE;
1071
1072 auto& pte = boot_pd_kernel_pt1023[pte_index];
1073 auto pd_paddr = directory.m_directory_pages[pdpt_index]->paddr();
1074 if (pte.physical_page_base() != pd_paddr.get()) {
1075 pte.set_physical_page_base(pd_paddr.get());
1076 pte.set_present(true);
1077 pte.set_writable(true);
1078 pte.set_user_allowed(false);
1079 flush_tlb_local(vaddr);
1080 }
1081 return (PageDirectoryEntry*)vaddr.get();
1082}
1083
1084PageTableEntry* MemoryManager::quickmap_pt(PhysicalAddress pt_paddr)
1085{
1086 VERIFY_INTERRUPTS_DISABLED();
1087
1088 VirtualAddress vaddr(KERNEL_QUICKMAP_PT_PER_CPU_BASE + Processor::current_id() * PAGE_SIZE);
1089 size_t pte_index = (vaddr.get() - KERNEL_PT1024_BASE) / PAGE_SIZE;
1090
1091 auto& pte = ((PageTableEntry*)boot_pd_kernel_pt1023)[pte_index];
1092 if (pte.physical_page_base() != pt_paddr.get()) {
1093 pte.set_physical_page_base(pt_paddr.get());
1094 pte.set_present(true);
1095 pte.set_writable(true);
1096 pte.set_user_allowed(false);
1097 flush_tlb_local(vaddr);
1098 }
1099 return (PageTableEntry*)vaddr.get();
1100}
1101
1102u8* MemoryManager::quickmap_page(PhysicalAddress const& physical_address)
1103{
1104 VERIFY_INTERRUPTS_DISABLED();
1105 auto& mm_data = get_data();
1106 mm_data.m_quickmap_previous_interrupts_state = mm_data.m_quickmap_in_use.lock();
1107
1108 VirtualAddress vaddr(KERNEL_QUICKMAP_PER_CPU_BASE + Processor::current_id() * PAGE_SIZE);
1109 u32 pte_idx = (vaddr.get() - KERNEL_PT1024_BASE) / PAGE_SIZE;
1110
1111 auto& pte = ((PageTableEntry*)boot_pd_kernel_pt1023)[pte_idx];
1112 if (pte.physical_page_base() != physical_address.get()) {
1113 pte.set_physical_page_base(physical_address.get());
1114 pte.set_present(true);
1115 pte.set_writable(true);
1116 pte.set_user_allowed(false);
1117 flush_tlb_local(vaddr);
1118 }
1119 return vaddr.as_ptr();
1120}
1121
1122void MemoryManager::unquickmap_page()
1123{
1124 VERIFY_INTERRUPTS_DISABLED();
1125 auto& mm_data = get_data();
1126 VERIFY(mm_data.m_quickmap_in_use.is_locked());
1127 VirtualAddress vaddr(KERNEL_QUICKMAP_PER_CPU_BASE + Processor::current_id() * PAGE_SIZE);
1128 u32 pte_idx = (vaddr.get() - KERNEL_PT1024_BASE) / PAGE_SIZE;
1129 auto& pte = ((PageTableEntry*)boot_pd_kernel_pt1023)[pte_idx];
1130 pte.clear();
1131 flush_tlb_local(vaddr);
1132 mm_data.m_quickmap_in_use.unlock(mm_data.m_quickmap_previous_interrupts_state);
1133}
1134
1135bool MemoryManager::validate_user_stack(AddressSpace& space, VirtualAddress vaddr) const
1136{
1137 if (!is_user_address(vaddr))
1138 return false;
1139
1140 auto* region = find_user_region_from_vaddr(space, vaddr);
1141 return region && region->is_user() && region->is_stack();
1142}
1143
1144void MemoryManager::unregister_kernel_region(Region& region)
1145{
1146 VERIFY(region.is_kernel());
1147 m_global_data.with([&](auto& global_data) { global_data.region_tree.remove(region); });
1148}
1149
1150void MemoryManager::dump_kernel_regions()
1151{
1152 dbgln("Kernel regions:");
1153 char const* addr_padding = " ";
1154 dbgln("BEGIN{} END{} SIZE{} ACCESS NAME",
1155 addr_padding, addr_padding, addr_padding);
1156 m_global_data.with([&](auto& global_data) {
1157 for (auto& region : global_data.region_tree.regions()) {
1158 dbgln("{:p} -- {:p} {:p} {:c}{:c}{:c}{:c}{:c}{:c} {}",
1159 region.vaddr().get(),
1160 region.vaddr().offset(region.size() - 1).get(),
1161 region.size(),
1162 region.is_readable() ? 'R' : ' ',
1163 region.is_writable() ? 'W' : ' ',
1164 region.is_executable() ? 'X' : ' ',
1165 region.is_shared() ? 'S' : ' ',
1166 region.is_stack() ? 'T' : ' ',
1167 region.is_syscall_region() ? 'C' : ' ',
1168 region.name());
1169 }
1170 });
1171}
1172
1173void MemoryManager::set_page_writable_direct(VirtualAddress vaddr, bool writable)
1174{
1175 SpinlockLocker page_lock(kernel_page_directory().get_lock());
1176 auto* pte = ensure_pte(kernel_page_directory(), vaddr);
1177 VERIFY(pte);
1178 if (pte->is_writable() == writable)
1179 return;
1180 pte->set_writable(writable);
1181 flush_tlb(&kernel_page_directory(), vaddr);
1182}
1183
1184CommittedPhysicalPageSet::~CommittedPhysicalPageSet()
1185{
1186 if (m_page_count)
1187 MM.uncommit_physical_pages({}, m_page_count);
1188}
1189
1190NonnullRefPtr<PhysicalPage> CommittedPhysicalPageSet::take_one()
1191{
1192 VERIFY(m_page_count > 0);
1193 --m_page_count;
1194 return MM.allocate_committed_physical_page({}, MemoryManager::ShouldZeroFill::Yes);
1195}
1196
1197void CommittedPhysicalPageSet::uncommit_one()
1198{
1199 VERIFY(m_page_count > 0);
1200 --m_page_count;
1201 MM.uncommit_physical_pages({}, 1);
1202}
1203
1204void MemoryManager::copy_physical_page(PhysicalPage& physical_page, u8 page_buffer[PAGE_SIZE])
1205{
1206 auto* quickmapped_page = quickmap_page(physical_page);
1207 memcpy(page_buffer, quickmapped_page, PAGE_SIZE);
1208 unquickmap_page();
1209}
1210
1211ErrorOr<NonnullOwnPtr<Memory::Region>> MemoryManager::create_identity_mapped_region(PhysicalAddress address, size_t size)
1212{
1213 auto vmobject = TRY(Memory::AnonymousVMObject::try_create_for_physical_range(address, size));
1214 auto region = TRY(Memory::Region::create_unplaced(move(vmobject), 0, {}, Memory::Region::Access::ReadWriteExecute));
1215 Memory::VirtualRange range { VirtualAddress { (FlatPtr)address.get() }, size };
1216 region->m_range = range;
1217 TRY(region->map(MM.kernel_page_directory()));
1218 return region;
1219}
1220
1221ErrorOr<NonnullOwnPtr<Region>> MemoryManager::allocate_unbacked_region_anywhere(size_t size, size_t alignment)
1222{
1223 auto region = TRY(Region::create_unbacked());
1224 TRY(m_global_data.with([&](auto& global_data) { return global_data.region_tree.place_anywhere(*region, RandomizeVirtualAddress::No, size, alignment); }));
1225 return region;
1226}
1227
1228MemoryManager::SystemMemoryInfo MemoryManager::get_system_memory_info()
1229{
1230 return m_global_data.with([&](auto& global_data) {
1231 auto physical_pages_unused = global_data.system_memory_info.physical_pages_committed + global_data.system_memory_info.physical_pages_uncommitted;
1232 VERIFY(global_data.system_memory_info.physical_pages == (global_data.system_memory_info.physical_pages_used + physical_pages_unused));
1233 return global_data.system_memory_info;
1234 });
1235}
1236}