MemoryManager.cpp 51 KB

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