MemoryManager.cpp 52 KB

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