MemoryManager.cpp 43 KB

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