MemoryManager.cpp 56 KB

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