MemoryManager.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. /*
  2. * Copyright (c) 2018-2021, 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/CMOS.h>
  10. #include <Kernel/FileSystem/Inode.h>
  11. #include <Kernel/Heap/kmalloc.h>
  12. #include <Kernel/Multiboot.h>
  13. #include <Kernel/Panic.h>
  14. #include <Kernel/Process.h>
  15. #include <Kernel/Sections.h>
  16. #include <Kernel/StdLib.h>
  17. #include <Kernel/VM/AnonymousVMObject.h>
  18. #include <Kernel/VM/ContiguousVMObject.h>
  19. #include <Kernel/VM/MemoryManager.h>
  20. #include <Kernel/VM/PageDirectory.h>
  21. #include <Kernel/VM/PhysicalRegion.h>
  22. #include <Kernel/VM/SharedInodeVMObject.h>
  23. extern u8* start_of_kernel_image;
  24. extern u8* end_of_kernel_image;
  25. extern FlatPtr start_of_kernel_text;
  26. extern FlatPtr start_of_kernel_data;
  27. extern FlatPtr end_of_kernel_bss;
  28. extern FlatPtr start_of_ro_after_init;
  29. extern FlatPtr end_of_ro_after_init;
  30. extern FlatPtr start_of_unmap_after_init;
  31. extern FlatPtr end_of_unmap_after_init;
  32. extern FlatPtr start_of_kernel_ksyms;
  33. extern FlatPtr end_of_kernel_ksyms;
  34. extern multiboot_module_entry_t multiboot_copy_boot_modules_array[16];
  35. extern size_t multiboot_copy_boot_modules_count;
  36. // Treat the super pages as logically separate from .bss
  37. __attribute__((section(".super_pages"))) static u8 super_pages[1 * MiB];
  38. namespace Kernel {
  39. // NOTE: We can NOT use AK::Singleton for this class, because
  40. // MemoryManager::initialize is called *before* global constructors are
  41. // run. If we do, then AK::Singleton would get re-initialized, causing
  42. // the memory manager to be initialized twice!
  43. static MemoryManager* s_the;
  44. RecursiveSpinLock s_mm_lock;
  45. MemoryManager& MM
  46. {
  47. return *s_the;
  48. }
  49. bool MemoryManager::is_initialized()
  50. {
  51. return s_the != nullptr;
  52. }
  53. UNMAP_AFTER_INIT MemoryManager::MemoryManager()
  54. {
  55. s_the = this;
  56. ScopedSpinLock lock(s_mm_lock);
  57. parse_memory_map();
  58. write_cr3(kernel_page_directory().cr3());
  59. protect_kernel_image();
  60. // We're temporarily "committing" to two pages that we need to allocate below
  61. if (!commit_user_physical_pages(2))
  62. VERIFY_NOT_REACHED();
  63. m_shared_zero_page = allocate_committed_user_physical_page();
  64. // We're wasting a page here, we just need a special tag (physical
  65. // address) so that we know when we need to lazily allocate a page
  66. // that we should be drawing this page from the committed pool rather
  67. // than potentially failing if no pages are available anymore.
  68. // By using a tag we don't have to query the VMObject for every page
  69. // whether it was committed or not
  70. m_lazy_committed_page = allocate_committed_user_physical_page();
  71. }
  72. UNMAP_AFTER_INIT MemoryManager::~MemoryManager()
  73. {
  74. }
  75. UNMAP_AFTER_INIT void MemoryManager::protect_kernel_image()
  76. {
  77. ScopedSpinLock page_lock(kernel_page_directory().get_lock());
  78. // Disable writing to the kernel text and rodata segments.
  79. for (auto i = (FlatPtr)&start_of_kernel_text; i < (FlatPtr)&start_of_kernel_data; i += PAGE_SIZE) {
  80. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  81. pte.set_writable(false);
  82. }
  83. if (Processor::current().has_feature(CPUFeature::NX)) {
  84. // Disable execution of the kernel data, bss and heap segments.
  85. for (auto i = (FlatPtr)&start_of_kernel_data; i < (FlatPtr)&end_of_kernel_image; i += PAGE_SIZE) {
  86. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  87. pte.set_execute_disabled(true);
  88. }
  89. }
  90. }
  91. UNMAP_AFTER_INIT void MemoryManager::protect_readonly_after_init_memory()
  92. {
  93. ScopedSpinLock mm_lock(s_mm_lock);
  94. ScopedSpinLock page_lock(kernel_page_directory().get_lock());
  95. // Disable writing to the .ro_after_init section
  96. for (auto i = (FlatPtr)&start_of_ro_after_init; i < (FlatPtr)&end_of_ro_after_init; i += PAGE_SIZE) {
  97. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  98. pte.set_writable(false);
  99. flush_tlb(&kernel_page_directory(), VirtualAddress(i));
  100. }
  101. }
  102. void MemoryManager::unmap_text_after_init()
  103. {
  104. ScopedSpinLock mm_lock(s_mm_lock);
  105. ScopedSpinLock page_lock(kernel_page_directory().get_lock());
  106. auto start = page_round_down((FlatPtr)&start_of_unmap_after_init);
  107. auto end = page_round_up((FlatPtr)&end_of_unmap_after_init);
  108. // Unmap the entire .unmap_after_init section
  109. for (auto i = start; i < end; i += PAGE_SIZE) {
  110. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  111. pte.clear();
  112. flush_tlb(&kernel_page_directory(), VirtualAddress(i));
  113. }
  114. dmesgln("Unmapped {} KiB of kernel text after init! :^)", (end - start) / KiB);
  115. }
  116. void MemoryManager::unmap_ksyms_after_init()
  117. {
  118. ScopedSpinLock mm_lock(s_mm_lock);
  119. ScopedSpinLock page_lock(kernel_page_directory().get_lock());
  120. auto start = page_round_down((FlatPtr)&start_of_kernel_ksyms);
  121. auto end = page_round_up((FlatPtr)&end_of_kernel_ksyms);
  122. // Unmap the entire .ksyms section
  123. for (auto i = start; i < end; i += PAGE_SIZE) {
  124. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  125. pte.clear();
  126. flush_tlb(&kernel_page_directory(), VirtualAddress(i));
  127. }
  128. dmesgln("Unmapped {} KiB of kernel symbols after init! :^)", (end - start) / KiB);
  129. }
  130. UNMAP_AFTER_INIT void MemoryManager::register_reserved_ranges()
  131. {
  132. VERIFY(!m_physical_memory_ranges.is_empty());
  133. ContiguousReservedMemoryRange range;
  134. for (auto& current_range : m_physical_memory_ranges) {
  135. if (current_range.type != PhysicalMemoryRangeType::Reserved) {
  136. if (range.start.is_null())
  137. continue;
  138. m_reserved_memory_ranges.append(ContiguousReservedMemoryRange { range.start, current_range.start.get() - range.start.get() });
  139. range.start.set((FlatPtr) nullptr);
  140. continue;
  141. }
  142. if (!range.start.is_null()) {
  143. continue;
  144. }
  145. range.start = current_range.start;
  146. }
  147. if (m_physical_memory_ranges.last().type != PhysicalMemoryRangeType::Reserved)
  148. return;
  149. if (range.start.is_null())
  150. return;
  151. m_reserved_memory_ranges.append(ContiguousReservedMemoryRange { range.start, m_physical_memory_ranges.last().start.get() + m_physical_memory_ranges.last().length - range.start.get() });
  152. }
  153. bool MemoryManager::is_allowed_to_mmap_to_userspace(PhysicalAddress start_address, Range const& range) const
  154. {
  155. VERIFY(!m_reserved_memory_ranges.is_empty());
  156. for (auto& current_range : m_reserved_memory_ranges) {
  157. if (!(current_range.start <= start_address))
  158. continue;
  159. if (!(current_range.start.offset(current_range.length) > start_address))
  160. continue;
  161. if (current_range.length < range.size())
  162. return false;
  163. return true;
  164. }
  165. return false;
  166. }
  167. UNMAP_AFTER_INIT void MemoryManager::parse_memory_map()
  168. {
  169. // Register used memory regions that we know of.
  170. m_used_memory_ranges.ensure_capacity(4);
  171. m_used_memory_ranges.append(UsedMemoryRange { UsedMemoryRangeType::LowMemory, PhysicalAddress(0x00000000), PhysicalAddress(1 * MiB) });
  172. 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)))) });
  173. if (multiboot_info_ptr->flags & 0x4) {
  174. auto* bootmods_start = multiboot_copy_boot_modules_array;
  175. auto* bootmods_end = bootmods_start + multiboot_copy_boot_modules_count;
  176. for (auto* bootmod = bootmods_start; bootmod < bootmods_end; bootmod++) {
  177. m_used_memory_ranges.append(UsedMemoryRange { UsedMemoryRangeType::BootModule, PhysicalAddress(bootmod->start), PhysicalAddress(bootmod->end) });
  178. }
  179. }
  180. auto* mmap_begin = reinterpret_cast<multiboot_memory_map_t*>(low_physical_to_virtual(multiboot_info_ptr->mmap_addr));
  181. auto* mmap_end = reinterpret_cast<multiboot_memory_map_t*>(low_physical_to_virtual(multiboot_info_ptr->mmap_addr) + multiboot_info_ptr->mmap_length);
  182. struct ContiguousPhysicalRange {
  183. PhysicalAddress lower;
  184. PhysicalAddress upper;
  185. };
  186. Vector<ContiguousPhysicalRange> contiguous_physical_ranges;
  187. for (auto* mmap = mmap_begin; mmap < mmap_end; mmap++) {
  188. dmesgln("MM: Multiboot mmap: address={:p}, length={}, type={}", mmap->addr, mmap->len, mmap->type);
  189. auto start_address = PhysicalAddress(mmap->addr);
  190. auto length = mmap->len;
  191. switch (mmap->type) {
  192. case (MULTIBOOT_MEMORY_AVAILABLE):
  193. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Usable, start_address, length });
  194. break;
  195. case (MULTIBOOT_MEMORY_RESERVED):
  196. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Reserved, start_address, length });
  197. break;
  198. case (MULTIBOOT_MEMORY_ACPI_RECLAIMABLE):
  199. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::ACPI_Reclaimable, start_address, length });
  200. break;
  201. case (MULTIBOOT_MEMORY_NVS):
  202. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::ACPI_NVS, start_address, length });
  203. break;
  204. case (MULTIBOOT_MEMORY_BADRAM):
  205. dmesgln("MM: Warning, detected bad memory range!");
  206. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::BadMemory, start_address, length });
  207. break;
  208. default:
  209. dbgln("MM: Unknown range!");
  210. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Unknown, start_address, length });
  211. break;
  212. }
  213. if (mmap->type != MULTIBOOT_MEMORY_AVAILABLE)
  214. continue;
  215. // Fix up unaligned memory regions.
  216. auto diff = (FlatPtr)mmap->addr % PAGE_SIZE;
  217. if (diff != 0) {
  218. dmesgln("MM: Got an unaligned physical_region from the bootloader; correcting {:p} by {} bytes", mmap->addr, diff);
  219. diff = PAGE_SIZE - diff;
  220. mmap->addr += diff;
  221. mmap->len -= diff;
  222. }
  223. if ((mmap->len % PAGE_SIZE) != 0) {
  224. dmesgln("MM: Got an unaligned physical_region from the bootloader; correcting length {} by {} bytes", mmap->len, mmap->len % PAGE_SIZE);
  225. mmap->len -= mmap->len % PAGE_SIZE;
  226. }
  227. if (mmap->len < PAGE_SIZE) {
  228. dmesgln("MM: Memory physical_region from bootloader is too small; we want >= {} bytes, but got {} bytes", PAGE_SIZE, mmap->len);
  229. continue;
  230. }
  231. for (PhysicalSize page_base = mmap->addr; page_base <= (mmap->addr + mmap->len); page_base += PAGE_SIZE) {
  232. auto addr = PhysicalAddress(page_base);
  233. // Skip used memory ranges.
  234. bool should_skip = false;
  235. for (auto& used_range : m_used_memory_ranges) {
  236. if (addr.get() >= used_range.start.get() && addr.get() <= used_range.end.get()) {
  237. should_skip = true;
  238. break;
  239. }
  240. }
  241. if (should_skip)
  242. continue;
  243. if (contiguous_physical_ranges.is_empty() || contiguous_physical_ranges.last().upper.offset(PAGE_SIZE) != addr) {
  244. contiguous_physical_ranges.append(ContiguousPhysicalRange {
  245. .lower = addr,
  246. .upper = addr,
  247. });
  248. } else {
  249. contiguous_physical_ranges.last().upper = addr;
  250. }
  251. }
  252. }
  253. for (auto& range : contiguous_physical_ranges) {
  254. m_user_physical_regions.append(PhysicalRegion::try_create(range.lower, range.upper).release_nonnull());
  255. }
  256. // Append statically-allocated super physical physical_region.
  257. m_super_physical_regions.append(PhysicalRegion::try_create(
  258. PhysicalAddress(virtual_to_low_physical(FlatPtr(super_pages))),
  259. PhysicalAddress(virtual_to_low_physical(FlatPtr(super_pages + sizeof(super_pages)))))
  260. .release_nonnull());
  261. for (auto& region : m_super_physical_regions)
  262. m_system_memory_info.super_physical_pages += region.size();
  263. for (auto& region : m_user_physical_regions)
  264. m_system_memory_info.user_physical_pages += region.size();
  265. register_reserved_ranges();
  266. for (auto& range : m_reserved_memory_ranges) {
  267. dmesgln("MM: Contiguous reserved range from {}, length is {}", range.start, range.length);
  268. }
  269. initialize_physical_pages();
  270. VERIFY(m_system_memory_info.super_physical_pages > 0);
  271. VERIFY(m_system_memory_info.user_physical_pages > 0);
  272. // We start out with no committed pages
  273. m_system_memory_info.user_physical_pages_uncommitted = m_system_memory_info.user_physical_pages;
  274. for (auto& used_range : m_used_memory_ranges) {
  275. dmesgln("MM: {} range @ {} - {} (size 0x{: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());
  276. }
  277. for (auto& region : m_super_physical_regions) {
  278. dmesgln("MM: Super physical region: {} - {} (size 0x{:x})", region.lower(), region.upper().offset(-1), PAGE_SIZE * region.size());
  279. region.initialize_zones();
  280. }
  281. for (auto& region : m_user_physical_regions) {
  282. dmesgln("MM: User physical region: {} - {} (size 0x{:x})", region.lower(), region.upper().offset(-1), PAGE_SIZE * region.size());
  283. region.initialize_zones();
  284. }
  285. }
  286. extern "C" PageDirectoryEntry boot_pd3[1024];
  287. UNMAP_AFTER_INIT void MemoryManager::initialize_physical_pages()
  288. {
  289. // We assume that the physical page range is contiguous and doesn't contain huge gaps!
  290. PhysicalAddress highest_physical_address;
  291. for (auto& range : m_used_memory_ranges) {
  292. if (range.end.get() > highest_physical_address.get())
  293. highest_physical_address = range.end;
  294. }
  295. for (auto& region : m_physical_memory_ranges) {
  296. auto range_end = PhysicalAddress(region.start).offset(region.length);
  297. if (range_end.get() > highest_physical_address.get())
  298. highest_physical_address = range_end;
  299. }
  300. // Calculate how many total physical pages the array will have
  301. m_physical_page_entries_count = PhysicalAddress::physical_page_index(highest_physical_address.get()) + 1;
  302. VERIFY(m_physical_page_entries_count != 0);
  303. VERIFY(!Checked<decltype(m_physical_page_entries_count)>::multiplication_would_overflow(m_physical_page_entries_count, sizeof(PhysicalPageEntry)));
  304. // Calculate how many bytes the array will consume
  305. auto physical_page_array_size = m_physical_page_entries_count * sizeof(PhysicalPageEntry);
  306. auto physical_page_array_pages = page_round_up(physical_page_array_size) / PAGE_SIZE;
  307. VERIFY(physical_page_array_pages * PAGE_SIZE >= physical_page_array_size);
  308. // Calculate how many page tables we will need to be able to map them all
  309. auto needed_page_table_count = (physical_page_array_pages + 512 - 1) / 512;
  310. auto physical_page_array_pages_and_page_tables_count = physical_page_array_pages + needed_page_table_count;
  311. // Now that we know how much memory we need for a contiguous array of PhysicalPage instances, find a memory region that can fit it
  312. PhysicalRegion* found_region { nullptr };
  313. Optional<size_t> found_region_index;
  314. for (size_t i = 0; i < m_user_physical_regions.size(); ++i) {
  315. auto& region = m_user_physical_regions[i];
  316. if (region.size() >= physical_page_array_pages_and_page_tables_count) {
  317. found_region = &region;
  318. found_region_index = i;
  319. break;
  320. }
  321. }
  322. if (!found_region) {
  323. dmesgln("MM: Need {} bytes for physical page management, but no memory region is large enough!", physical_page_array_pages_and_page_tables_count);
  324. VERIFY_NOT_REACHED();
  325. }
  326. VERIFY(m_system_memory_info.user_physical_pages >= physical_page_array_pages_and_page_tables_count);
  327. m_system_memory_info.user_physical_pages -= physical_page_array_pages_and_page_tables_count;
  328. if (found_region->size() == physical_page_array_pages_and_page_tables_count) {
  329. // We're stealing the entire region
  330. m_physical_pages_region = m_user_physical_regions.take(*found_region_index);
  331. } else {
  332. m_physical_pages_region = found_region->try_take_pages_from_beginning(physical_page_array_pages_and_page_tables_count);
  333. }
  334. m_used_memory_ranges.append({ UsedMemoryRangeType::PhysicalPages, m_physical_pages_region->lower(), m_physical_pages_region->upper() });
  335. // Create the bare page directory. This is not a fully constructed page directory and merely contains the allocators!
  336. m_kernel_page_directory = PageDirectory::create_kernel_page_directory();
  337. // Allocate a virtual address range for our array
  338. auto range = m_kernel_page_directory->range_allocator().allocate_anywhere(physical_page_array_pages * PAGE_SIZE);
  339. if (!range.has_value()) {
  340. dmesgln("MM: Could not allocate {} bytes to map physical page array!", physical_page_array_pages * PAGE_SIZE);
  341. VERIFY_NOT_REACHED();
  342. }
  343. // Now that we have our special m_physical_pages_region region with enough pages to hold the entire array
  344. // try to map the entire region into kernel space so we always have it
  345. // We can't use ensure_pte here because it would try to allocate a PhysicalPage and we don't have the array
  346. // mapped yet so we can't create them
  347. ScopedSpinLock lock(s_mm_lock);
  348. // Create page tables at the beginning of m_physical_pages_region, followed by the PhysicalPageEntry array
  349. auto page_tables_base = m_physical_pages_region->lower();
  350. auto physical_page_array_base = page_tables_base.offset(needed_page_table_count * PAGE_SIZE);
  351. auto physical_page_array_current_page = physical_page_array_base.get();
  352. auto virtual_page_array_base = range.value().base().get();
  353. auto virtual_page_array_current_page = virtual_page_array_base;
  354. for (size_t pt_index = 0; pt_index < needed_page_table_count; pt_index++) {
  355. auto virtual_page_base_for_this_pt = virtual_page_array_current_page;
  356. auto pt_paddr = page_tables_base.offset(pt_index * PAGE_SIZE);
  357. auto* pt = reinterpret_cast<PageTableEntry*>(quickmap_page(pt_paddr));
  358. __builtin_memset(pt, 0, PAGE_SIZE);
  359. for (size_t pte_index = 0; pte_index < PAGE_SIZE / sizeof(PageTableEntry); pte_index++) {
  360. auto& pte = pt[pte_index];
  361. pte.set_physical_page_base(physical_page_array_current_page);
  362. pte.set_user_allowed(false);
  363. pte.set_writable(true);
  364. if (Processor::current().has_feature(CPUFeature::NX))
  365. pte.set_execute_disabled(false);
  366. pte.set_global(true);
  367. pte.set_present(true);
  368. physical_page_array_current_page += PAGE_SIZE;
  369. virtual_page_array_current_page += PAGE_SIZE;
  370. }
  371. unquickmap_page();
  372. // Hook the page table into the kernel page directory
  373. VERIFY(((virtual_page_base_for_this_pt >> 30) & 0x3) == 3);
  374. PhysicalAddress boot_pd3_paddr(virtual_to_low_physical((FlatPtr)boot_pd3));
  375. u32 page_directory_index = (virtual_page_base_for_this_pt >> 21) & 0x1ff;
  376. auto* pd = reinterpret_cast<PageDirectoryEntry*>(quickmap_page(boot_pd3_paddr));
  377. PageDirectoryEntry& pde = pd[page_directory_index];
  378. VERIFY(!pde.is_present()); // Nothing should be using this PD yet
  379. // We can't use ensure_pte quite yet!
  380. pde.set_page_table_base(pt_paddr.get());
  381. pde.set_user_allowed(false);
  382. pde.set_present(true);
  383. pde.set_writable(true);
  384. pde.set_global(true);
  385. unquickmap_page();
  386. flush_tlb_local(VirtualAddress(virtual_page_base_for_this_pt));
  387. }
  388. // We now have the entire PhysicalPageEntry array mapped!
  389. m_physical_page_entries = (PhysicalPageEntry*)range.value().base().get();
  390. for (size_t i = 0; i < m_physical_page_entries_count; i++)
  391. new (&m_physical_page_entries[i]) PageTableEntry();
  392. // Now we should be able to allocate PhysicalPage instances,
  393. // so finish setting up the kernel page directory
  394. m_kernel_page_directory->allocate_kernel_directory();
  395. // Now create legit PhysicalPage objects for the page tables we created, so that
  396. // we can put them into kernel_page_directory().m_page_tables
  397. auto& kernel_page_tables = kernel_page_directory().m_page_tables;
  398. virtual_page_array_current_page = virtual_page_array_base;
  399. for (size_t pt_index = 0; pt_index < needed_page_table_count; pt_index++) {
  400. VERIFY(virtual_page_array_current_page <= range.value().end().get());
  401. auto pt_paddr = page_tables_base.offset(pt_index * PAGE_SIZE);
  402. auto physical_page_index = PhysicalAddress::physical_page_index(pt_paddr.get());
  403. auto& physical_page_entry = m_physical_page_entries[physical_page_index];
  404. auto physical_page = adopt_ref(*new (&physical_page_entry.allocated.physical_page) PhysicalPage(MayReturnToFreeList::No));
  405. auto result = kernel_page_tables.set(virtual_page_array_current_page & ~0x1fffff, move(physical_page));
  406. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  407. virtual_page_array_current_page += (PAGE_SIZE / sizeof(PageTableEntry)) * PAGE_SIZE;
  408. }
  409. dmesgln("MM: Physical page entries: {}", range.value());
  410. }
  411. PhysicalPageEntry& MemoryManager::get_physical_page_entry(PhysicalAddress physical_address)
  412. {
  413. VERIFY(m_physical_page_entries);
  414. auto physical_page_entry_index = PhysicalAddress::physical_page_index(physical_address.get());
  415. VERIFY(physical_page_entry_index < m_physical_page_entries_count);
  416. return m_physical_page_entries[physical_page_entry_index];
  417. }
  418. PhysicalAddress MemoryManager::get_physical_address(PhysicalPage const& physical_page)
  419. {
  420. PhysicalPageEntry const& physical_page_entry = *reinterpret_cast<PhysicalPageEntry const*>((u8 const*)&physical_page - __builtin_offsetof(PhysicalPageEntry, allocated.physical_page));
  421. VERIFY(m_physical_page_entries);
  422. size_t physical_page_entry_index = &physical_page_entry - m_physical_page_entries;
  423. VERIFY(physical_page_entry_index < m_physical_page_entries_count);
  424. return PhysicalAddress((PhysicalPtr)physical_page_entry_index * PAGE_SIZE);
  425. }
  426. PageTableEntry* MemoryManager::pte(PageDirectory& page_directory, VirtualAddress vaddr)
  427. {
  428. VERIFY_INTERRUPTS_DISABLED();
  429. VERIFY(s_mm_lock.own_lock());
  430. VERIFY(page_directory.get_lock().own_lock());
  431. u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
  432. u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
  433. u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
  434. auto* pd = quickmap_pd(const_cast<PageDirectory&>(page_directory), page_directory_table_index);
  435. PageDirectoryEntry const& pde = pd[page_directory_index];
  436. if (!pde.is_present())
  437. return nullptr;
  438. return &quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()))[page_table_index];
  439. }
  440. PageTableEntry* MemoryManager::ensure_pte(PageDirectory& page_directory, VirtualAddress vaddr)
  441. {
  442. VERIFY_INTERRUPTS_DISABLED();
  443. VERIFY(s_mm_lock.own_lock());
  444. VERIFY(page_directory.get_lock().own_lock());
  445. u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
  446. u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
  447. u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
  448. auto* pd = quickmap_pd(page_directory, page_directory_table_index);
  449. PageDirectoryEntry& pde = pd[page_directory_index];
  450. if (!pde.is_present()) {
  451. bool did_purge = false;
  452. auto page_table = allocate_user_physical_page(ShouldZeroFill::Yes, &did_purge);
  453. if (!page_table) {
  454. dbgln("MM: Unable to allocate page table to map {}", vaddr);
  455. return nullptr;
  456. }
  457. if (did_purge) {
  458. // If any memory had to be purged, ensure_pte may have been called as part
  459. // of the purging process. So we need to re-map the pd in this case to ensure
  460. // we're writing to the correct underlying physical page
  461. pd = quickmap_pd(page_directory, page_directory_table_index);
  462. VERIFY(&pde == &pd[page_directory_index]); // Sanity check
  463. VERIFY(!pde.is_present()); // Should have not changed
  464. }
  465. pde.set_page_table_base(page_table->paddr().get());
  466. pde.set_user_allowed(true);
  467. pde.set_present(true);
  468. pde.set_writable(true);
  469. pde.set_global(&page_directory == m_kernel_page_directory.ptr());
  470. // Use page_directory_table_index and page_directory_index as key
  471. // This allows us to release the page table entry when no longer needed
  472. auto result = page_directory.m_page_tables.set(vaddr.get() & ~0x1fffff, move(page_table));
  473. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  474. }
  475. return &quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()))[page_table_index];
  476. }
  477. void MemoryManager::release_pte(PageDirectory& page_directory, VirtualAddress vaddr, bool is_last_release)
  478. {
  479. VERIFY_INTERRUPTS_DISABLED();
  480. VERIFY(s_mm_lock.own_lock());
  481. VERIFY(page_directory.get_lock().own_lock());
  482. u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
  483. u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
  484. u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
  485. auto* pd = quickmap_pd(page_directory, page_directory_table_index);
  486. PageDirectoryEntry& pde = pd[page_directory_index];
  487. if (pde.is_present()) {
  488. auto* page_table = quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()));
  489. auto& pte = page_table[page_table_index];
  490. pte.clear();
  491. if (is_last_release || page_table_index == 0x1ff) {
  492. // If this is the last PTE in a region or the last PTE in a page table then
  493. // check if we can also release the page table
  494. bool all_clear = true;
  495. for (u32 i = 0; i <= 0x1ff; i++) {
  496. if (!page_table[i].is_null()) {
  497. all_clear = false;
  498. break;
  499. }
  500. }
  501. if (all_clear) {
  502. pde.clear();
  503. auto result = page_directory.m_page_tables.remove(vaddr.get() & ~0x1fffff);
  504. VERIFY(result);
  505. }
  506. }
  507. }
  508. }
  509. UNMAP_AFTER_INIT void MemoryManager::initialize(u32 cpu)
  510. {
  511. auto mm_data = new MemoryManagerData;
  512. Processor::current().set_mm_data(*mm_data);
  513. if (cpu == 0) {
  514. new MemoryManager;
  515. kmalloc_enable_expand();
  516. }
  517. }
  518. Region* MemoryManager::kernel_region_from_vaddr(VirtualAddress vaddr)
  519. {
  520. ScopedSpinLock lock(s_mm_lock);
  521. for (auto& region : MM.m_kernel_regions) {
  522. if (region.contains(vaddr))
  523. return &region;
  524. }
  525. return nullptr;
  526. }
  527. Region* MemoryManager::find_user_region_from_vaddr(Space& space, VirtualAddress vaddr)
  528. {
  529. ScopedSpinLock lock(space.get_lock());
  530. return space.find_region_containing({ vaddr, 1 });
  531. }
  532. Region* MemoryManager::find_region_from_vaddr(VirtualAddress vaddr)
  533. {
  534. ScopedSpinLock lock(s_mm_lock);
  535. if (auto* region = kernel_region_from_vaddr(vaddr))
  536. return region;
  537. auto page_directory = PageDirectory::find_by_cr3(read_cr3());
  538. if (!page_directory)
  539. return nullptr;
  540. VERIFY(page_directory->space());
  541. return find_user_region_from_vaddr(*page_directory->space(), vaddr);
  542. }
  543. PageFaultResponse MemoryManager::handle_page_fault(PageFault const& fault)
  544. {
  545. VERIFY_INTERRUPTS_DISABLED();
  546. ScopedSpinLock lock(s_mm_lock);
  547. if (Processor::current().in_irq()) {
  548. dbgln("CPU[{}] BUG! Page fault while handling IRQ! code={}, vaddr={}, irq level: {}",
  549. Processor::id(), fault.code(), fault.vaddr(), Processor::current().in_irq());
  550. dump_kernel_regions();
  551. return PageFaultResponse::ShouldCrash;
  552. }
  553. dbgln_if(PAGE_FAULT_DEBUG, "MM: CPU[{}] handle_page_fault({:#04x}) at {}", Processor::id(), fault.code(), fault.vaddr());
  554. auto* region = find_region_from_vaddr(fault.vaddr());
  555. if (!region) {
  556. return PageFaultResponse::ShouldCrash;
  557. }
  558. return region->handle_fault(fault, lock);
  559. }
  560. OwnPtr<Region> MemoryManager::allocate_contiguous_kernel_region(size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
  561. {
  562. VERIFY(!(size % PAGE_SIZE));
  563. ScopedSpinLock lock(s_mm_lock);
  564. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  565. if (!range.has_value())
  566. return {};
  567. auto vmobject = ContiguousVMObject::try_create_with_size(size);
  568. if (!vmobject) {
  569. kernel_page_directory().range_allocator().deallocate(range.value());
  570. return {};
  571. }
  572. return allocate_kernel_region_with_vmobject(range.value(), *vmobject, name, access, cacheable);
  573. }
  574. OwnPtr<Region> MemoryManager::allocate_kernel_region(size_t size, StringView name, Region::Access access, AllocationStrategy strategy, Region::Cacheable cacheable)
  575. {
  576. VERIFY(!(size % PAGE_SIZE));
  577. auto vm_object = AnonymousVMObject::try_create_with_size(size, strategy);
  578. if (!vm_object)
  579. return {};
  580. ScopedSpinLock lock(s_mm_lock);
  581. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  582. if (!range.has_value())
  583. return {};
  584. return allocate_kernel_region_with_vmobject(range.value(), vm_object.release_nonnull(), name, access, cacheable);
  585. }
  586. OwnPtr<Region> MemoryManager::allocate_kernel_region(PhysicalAddress paddr, size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
  587. {
  588. auto vm_object = AnonymousVMObject::try_create_for_physical_range(paddr, size);
  589. if (!vm_object)
  590. return {};
  591. VERIFY(!(size % PAGE_SIZE));
  592. ScopedSpinLock lock(s_mm_lock);
  593. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  594. if (!range.has_value())
  595. return {};
  596. return allocate_kernel_region_with_vmobject(range.value(), *vm_object, name, access, cacheable);
  597. }
  598. OwnPtr<Region> MemoryManager::allocate_kernel_region_identity(PhysicalAddress paddr, size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
  599. {
  600. auto vm_object = AnonymousVMObject::try_create_for_physical_range(paddr, size);
  601. if (!vm_object)
  602. return {};
  603. VERIFY(!(size % PAGE_SIZE));
  604. ScopedSpinLock lock(s_mm_lock);
  605. auto range = kernel_page_directory().identity_range_allocator().allocate_specific(VirtualAddress(paddr.get()), size);
  606. if (!range.has_value())
  607. return {};
  608. return allocate_kernel_region_with_vmobject(range.value(), *vm_object, name, access, cacheable);
  609. }
  610. OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(Range const& range, VMObject& vmobject, StringView name, Region::Access access, Region::Cacheable cacheable)
  611. {
  612. ScopedSpinLock lock(s_mm_lock);
  613. auto region = Region::try_create_kernel_only(range, vmobject, 0, KString::try_create(name), access, cacheable);
  614. if (region)
  615. region->map(kernel_page_directory());
  616. return region;
  617. }
  618. OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(VMObject& vmobject, size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
  619. {
  620. VERIFY(!(size % PAGE_SIZE));
  621. ScopedSpinLock lock(s_mm_lock);
  622. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  623. if (!range.has_value())
  624. return {};
  625. return allocate_kernel_region_with_vmobject(range.value(), vmobject, name, access, cacheable);
  626. }
  627. bool MemoryManager::commit_user_physical_pages(size_t page_count)
  628. {
  629. VERIFY(page_count > 0);
  630. ScopedSpinLock lock(s_mm_lock);
  631. if (m_system_memory_info.user_physical_pages_uncommitted < page_count)
  632. return false;
  633. m_system_memory_info.user_physical_pages_uncommitted -= page_count;
  634. m_system_memory_info.user_physical_pages_committed += page_count;
  635. return true;
  636. }
  637. void MemoryManager::uncommit_user_physical_pages(size_t page_count)
  638. {
  639. VERIFY(page_count > 0);
  640. ScopedSpinLock lock(s_mm_lock);
  641. VERIFY(m_system_memory_info.user_physical_pages_committed >= page_count);
  642. m_system_memory_info.user_physical_pages_uncommitted += page_count;
  643. m_system_memory_info.user_physical_pages_committed -= page_count;
  644. }
  645. void MemoryManager::deallocate_physical_page(PhysicalAddress paddr)
  646. {
  647. ScopedSpinLock lock(s_mm_lock);
  648. // Are we returning a user page?
  649. for (auto& region : m_user_physical_regions) {
  650. if (!region.contains(paddr))
  651. continue;
  652. region.return_page(paddr);
  653. --m_system_memory_info.user_physical_pages_used;
  654. // Always return pages to the uncommitted pool. Pages that were
  655. // committed and allocated are only freed upon request. Once
  656. // returned there is no guarantee being able to get them back.
  657. ++m_system_memory_info.user_physical_pages_uncommitted;
  658. return;
  659. }
  660. // If it's not a user page, it should be a supervisor page.
  661. for (auto& region : m_super_physical_regions) {
  662. if (!region.contains(paddr)) {
  663. dbgln("MM: deallocate_supervisor_physical_page: {} not in {} - {}", paddr, region.lower(), region.upper());
  664. continue;
  665. }
  666. region.return_page(paddr);
  667. --m_system_memory_info.super_physical_pages_used;
  668. return;
  669. }
  670. PANIC("MM: deallocate_user_physical_page couldn't figure out region for page @ {}", paddr);
  671. }
  672. RefPtr<PhysicalPage> MemoryManager::find_free_user_physical_page(bool committed)
  673. {
  674. VERIFY(s_mm_lock.is_locked());
  675. RefPtr<PhysicalPage> page;
  676. if (committed) {
  677. // Draw from the committed pages pool. We should always have these pages available
  678. VERIFY(m_system_memory_info.user_physical_pages_committed > 0);
  679. m_system_memory_info.user_physical_pages_committed--;
  680. } else {
  681. // We need to make sure we don't touch pages that we have committed to
  682. if (m_system_memory_info.user_physical_pages_uncommitted == 0)
  683. return {};
  684. m_system_memory_info.user_physical_pages_uncommitted--;
  685. }
  686. for (auto& region : m_user_physical_regions) {
  687. page = region.take_free_page();
  688. if (!page.is_null()) {
  689. ++m_system_memory_info.user_physical_pages_used;
  690. break;
  691. }
  692. }
  693. VERIFY(!committed || !page.is_null());
  694. return page;
  695. }
  696. NonnullRefPtr<PhysicalPage> MemoryManager::allocate_committed_user_physical_page(ShouldZeroFill should_zero_fill)
  697. {
  698. ScopedSpinLock lock(s_mm_lock);
  699. auto page = find_free_user_physical_page(true);
  700. if (should_zero_fill == ShouldZeroFill::Yes) {
  701. auto* ptr = quickmap_page(*page);
  702. memset(ptr, 0, PAGE_SIZE);
  703. unquickmap_page();
  704. }
  705. return page.release_nonnull();
  706. }
  707. RefPtr<PhysicalPage> MemoryManager::allocate_user_physical_page(ShouldZeroFill should_zero_fill, bool* did_purge)
  708. {
  709. ScopedSpinLock lock(s_mm_lock);
  710. auto page = find_free_user_physical_page(false);
  711. bool purged_pages = false;
  712. if (!page) {
  713. // We didn't have a single free physical page. Let's try to free something up!
  714. // First, we look for a purgeable VMObject in the volatile state.
  715. for_each_vmobject([&](auto& vmobject) {
  716. if (!vmobject.is_anonymous())
  717. return IterationDecision::Continue;
  718. int purged_page_count = static_cast<AnonymousVMObject&>(vmobject).purge_with_interrupts_disabled({});
  719. if (purged_page_count) {
  720. dbgln("MM: Purge saved the day! Purged {} pages from AnonymousVMObject", purged_page_count);
  721. page = find_free_user_physical_page(false);
  722. purged_pages = true;
  723. VERIFY(page);
  724. return IterationDecision::Break;
  725. }
  726. return IterationDecision::Continue;
  727. });
  728. if (!page) {
  729. dmesgln("MM: no user physical pages available");
  730. return {};
  731. }
  732. }
  733. if (should_zero_fill == ShouldZeroFill::Yes) {
  734. auto* ptr = quickmap_page(*page);
  735. memset(ptr, 0, PAGE_SIZE);
  736. unquickmap_page();
  737. }
  738. if (did_purge)
  739. *did_purge = purged_pages;
  740. return page;
  741. }
  742. NonnullRefPtrVector<PhysicalPage> MemoryManager::allocate_contiguous_supervisor_physical_pages(size_t size)
  743. {
  744. VERIFY(!(size % PAGE_SIZE));
  745. ScopedSpinLock lock(s_mm_lock);
  746. size_t count = ceil_div(size, static_cast<size_t>(PAGE_SIZE));
  747. NonnullRefPtrVector<PhysicalPage> physical_pages;
  748. for (auto& region : m_super_physical_regions) {
  749. physical_pages = region.take_contiguous_free_pages(count);
  750. if (!physical_pages.is_empty())
  751. continue;
  752. }
  753. if (physical_pages.is_empty()) {
  754. if (m_super_physical_regions.is_empty()) {
  755. dmesgln("MM: no super physical regions available (?)");
  756. }
  757. dmesgln("MM: no super physical pages available");
  758. VERIFY_NOT_REACHED();
  759. return {};
  760. }
  761. auto cleanup_region = MM.allocate_kernel_region(physical_pages[0].paddr(), PAGE_SIZE * count, "MemoryManager Allocation Sanitization", Region::Access::Read | Region::Access::Write);
  762. fast_u32_fill((u32*)cleanup_region->vaddr().as_ptr(), 0, (PAGE_SIZE * count) / sizeof(u32));
  763. m_system_memory_info.super_physical_pages_used += count;
  764. return physical_pages;
  765. }
  766. RefPtr<PhysicalPage> MemoryManager::allocate_supervisor_physical_page()
  767. {
  768. ScopedSpinLock lock(s_mm_lock);
  769. RefPtr<PhysicalPage> page;
  770. for (auto& region : m_super_physical_regions) {
  771. page = region.take_free_page();
  772. if (!page.is_null())
  773. break;
  774. }
  775. if (!page) {
  776. if (m_super_physical_regions.is_empty()) {
  777. dmesgln("MM: no super physical regions available (?)");
  778. }
  779. dmesgln("MM: no super physical pages available");
  780. VERIFY_NOT_REACHED();
  781. return {};
  782. }
  783. fast_u32_fill((u32*)page->paddr().offset(KERNEL_BASE).as_ptr(), 0, PAGE_SIZE / sizeof(u32));
  784. ++m_system_memory_info.super_physical_pages_used;
  785. return page;
  786. }
  787. void MemoryManager::enter_process_paging_scope(Process& process)
  788. {
  789. enter_space(process.space());
  790. }
  791. void MemoryManager::enter_space(Space& space)
  792. {
  793. auto current_thread = Thread::current();
  794. VERIFY(current_thread != nullptr);
  795. ScopedSpinLock lock(s_mm_lock);
  796. current_thread->regs().cr3 = space.page_directory().cr3();
  797. write_cr3(space.page_directory().cr3());
  798. }
  799. void MemoryManager::flush_tlb_local(VirtualAddress vaddr, size_t page_count)
  800. {
  801. Processor::flush_tlb_local(vaddr, page_count);
  802. }
  803. void MemoryManager::flush_tlb(PageDirectory const* page_directory, VirtualAddress vaddr, size_t page_count)
  804. {
  805. Processor::flush_tlb(page_directory, vaddr, page_count);
  806. }
  807. extern "C" PageTableEntry boot_pd3_pt1023[1024];
  808. PageDirectoryEntry* MemoryManager::quickmap_pd(PageDirectory& directory, size_t pdpt_index)
  809. {
  810. VERIFY(s_mm_lock.own_lock());
  811. auto& mm_data = get_data();
  812. auto& pte = boot_pd3_pt1023[(KERNEL_QUICKMAP_PD - KERNEL_PT1024_BASE) / PAGE_SIZE];
  813. auto pd_paddr = directory.m_directory_pages[pdpt_index]->paddr();
  814. if (pte.physical_page_base() != pd_paddr.get()) {
  815. pte.set_physical_page_base(pd_paddr.get());
  816. pte.set_present(true);
  817. pte.set_writable(true);
  818. pte.set_user_allowed(false);
  819. // Because we must continue to hold the MM lock while we use this
  820. // mapping, it is sufficient to only flush on the current CPU. Other
  821. // CPUs trying to use this API must wait on the MM lock anyway
  822. flush_tlb_local(VirtualAddress(KERNEL_QUICKMAP_PD));
  823. } else {
  824. // Even though we don't allow this to be called concurrently, it's
  825. // possible that this PD was mapped on a different CPU and we don't
  826. // broadcast the flush. If so, we still need to flush the TLB.
  827. if (mm_data.m_last_quickmap_pd != pd_paddr)
  828. flush_tlb_local(VirtualAddress(KERNEL_QUICKMAP_PD));
  829. }
  830. mm_data.m_last_quickmap_pd = pd_paddr;
  831. return (PageDirectoryEntry*)KERNEL_QUICKMAP_PD;
  832. }
  833. PageTableEntry* MemoryManager::quickmap_pt(PhysicalAddress pt_paddr)
  834. {
  835. VERIFY(s_mm_lock.own_lock());
  836. auto& mm_data = get_data();
  837. auto& pte = boot_pd3_pt1023[(KERNEL_QUICKMAP_PT - KERNEL_PT1024_BASE) / PAGE_SIZE];
  838. if (pte.physical_page_base() != pt_paddr.get()) {
  839. pte.set_physical_page_base(pt_paddr.get());
  840. pte.set_present(true);
  841. pte.set_writable(true);
  842. pte.set_user_allowed(false);
  843. // Because we must continue to hold the MM lock while we use this
  844. // mapping, it is sufficient to only flush on the current CPU. Other
  845. // CPUs trying to use this API must wait on the MM lock anyway
  846. flush_tlb_local(VirtualAddress(KERNEL_QUICKMAP_PT));
  847. } else {
  848. // Even though we don't allow this to be called concurrently, it's
  849. // possible that this PT was mapped on a different CPU and we don't
  850. // broadcast the flush. If so, we still need to flush the TLB.
  851. if (mm_data.m_last_quickmap_pt != pt_paddr)
  852. flush_tlb_local(VirtualAddress(KERNEL_QUICKMAP_PT));
  853. }
  854. mm_data.m_last_quickmap_pt = pt_paddr;
  855. return (PageTableEntry*)KERNEL_QUICKMAP_PT;
  856. }
  857. u8* MemoryManager::quickmap_page(PhysicalAddress const& physical_address)
  858. {
  859. VERIFY_INTERRUPTS_DISABLED();
  860. auto& mm_data = get_data();
  861. mm_data.m_quickmap_prev_flags = mm_data.m_quickmap_in_use.lock();
  862. ScopedSpinLock lock(s_mm_lock);
  863. VirtualAddress vaddr(KERNEL_QUICKMAP_PER_CPU_BASE + Processor::id() * PAGE_SIZE);
  864. u32 pte_idx = (vaddr.get() - KERNEL_PT1024_BASE) / PAGE_SIZE;
  865. auto& pte = boot_pd3_pt1023[pte_idx];
  866. if (pte.physical_page_base() != physical_address.get()) {
  867. pte.set_physical_page_base(physical_address.get());
  868. pte.set_present(true);
  869. pte.set_writable(true);
  870. pte.set_user_allowed(false);
  871. flush_tlb_local(vaddr);
  872. }
  873. return vaddr.as_ptr();
  874. }
  875. void MemoryManager::unquickmap_page()
  876. {
  877. VERIFY_INTERRUPTS_DISABLED();
  878. ScopedSpinLock lock(s_mm_lock);
  879. auto& mm_data = get_data();
  880. VERIFY(mm_data.m_quickmap_in_use.is_locked());
  881. VirtualAddress vaddr(KERNEL_QUICKMAP_PER_CPU_BASE + Processor::id() * PAGE_SIZE);
  882. u32 pte_idx = (vaddr.get() - KERNEL_PT1024_BASE) / PAGE_SIZE;
  883. auto& pte = boot_pd3_pt1023[pte_idx];
  884. pte.clear();
  885. flush_tlb_local(vaddr);
  886. mm_data.m_quickmap_in_use.unlock(mm_data.m_quickmap_prev_flags);
  887. }
  888. bool MemoryManager::validate_user_stack(Process const& process, VirtualAddress vaddr) const
  889. {
  890. if (!is_user_address(vaddr))
  891. return false;
  892. ScopedSpinLock lock(s_mm_lock);
  893. auto* region = find_user_region_from_vaddr(const_cast<Process&>(process).space(), vaddr);
  894. return region && region->is_user() && region->is_stack();
  895. }
  896. void MemoryManager::register_vmobject(VMObject& vmobject)
  897. {
  898. ScopedSpinLock lock(s_mm_lock);
  899. m_vmobjects.append(vmobject);
  900. }
  901. void MemoryManager::unregister_vmobject(VMObject& vmobject)
  902. {
  903. ScopedSpinLock lock(s_mm_lock);
  904. m_vmobjects.remove(vmobject);
  905. }
  906. void MemoryManager::register_region(Region& region)
  907. {
  908. ScopedSpinLock lock(s_mm_lock);
  909. if (region.is_kernel())
  910. m_kernel_regions.append(region);
  911. else
  912. m_user_regions.append(region);
  913. }
  914. void MemoryManager::unregister_region(Region& region)
  915. {
  916. ScopedSpinLock lock(s_mm_lock);
  917. if (region.is_kernel())
  918. m_kernel_regions.remove(region);
  919. else
  920. m_user_regions.remove(region);
  921. }
  922. void MemoryManager::dump_kernel_regions()
  923. {
  924. dbgln("Kernel regions:");
  925. dbgln("BEGIN END SIZE ACCESS NAME");
  926. ScopedSpinLock lock(s_mm_lock);
  927. for (auto& region : m_kernel_regions) {
  928. dbgln("{:08x} -- {:08x} {:08x} {:c}{:c}{:c}{:c}{:c}{:c} {}",
  929. region.vaddr().get(),
  930. region.vaddr().offset(region.size() - 1).get(),
  931. region.size(),
  932. region.is_readable() ? 'R' : ' ',
  933. region.is_writable() ? 'W' : ' ',
  934. region.is_executable() ? 'X' : ' ',
  935. region.is_shared() ? 'S' : ' ',
  936. region.is_stack() ? 'T' : ' ',
  937. region.is_syscall_region() ? 'C' : ' ',
  938. region.name());
  939. }
  940. }
  941. void MemoryManager::set_page_writable_direct(VirtualAddress vaddr, bool writable)
  942. {
  943. ScopedSpinLock lock(s_mm_lock);
  944. ScopedSpinLock page_lock(kernel_page_directory().get_lock());
  945. auto* pte = ensure_pte(kernel_page_directory(), vaddr);
  946. VERIFY(pte);
  947. if (pte->is_writable() == writable)
  948. return;
  949. pte->set_writable(writable);
  950. flush_tlb(&kernel_page_directory(), vaddr);
  951. }
  952. }