MemoryManager.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  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/BootInfo.h>
  10. #include <Kernel/CMOS.h>
  11. #include <Kernel/FileSystem/Inode.h>
  12. #include <Kernel/Heap/kmalloc.h>
  13. #include <Kernel/Multiboot.h>
  14. #include <Kernel/Panic.h>
  15. #include <Kernel/Process.h>
  16. #include <Kernel/Sections.h>
  17. #include <Kernel/StdLib.h>
  18. #include <Kernel/VM/AnonymousVMObject.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 u8 start_of_kernel_text[];
  26. extern u8 start_of_kernel_data[];
  27. extern u8 end_of_kernel_bss[];
  28. extern u8 start_of_ro_after_init[];
  29. extern u8 end_of_ro_after_init[];
  30. extern u8 start_of_unmap_after_init[];
  31. extern u8 end_of_unmap_after_init[];
  32. extern u8 start_of_kernel_ksyms[];
  33. extern u8 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 = start_of_kernel_text; i < 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 = start_of_kernel_data; i < 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::Prekernel, start_of_prekernel_image, end_of_prekernel_image });
  173. 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))) });
  174. if (multiboot_flags & 0x4) {
  175. auto* bootmods_start = multiboot_copy_boot_modules_array;
  176. auto* bootmods_end = bootmods_start + multiboot_copy_boot_modules_count;
  177. for (auto* bootmod = bootmods_start; bootmod < bootmods_end; bootmod++) {
  178. m_used_memory_ranges.append(UsedMemoryRange { UsedMemoryRangeType::BootModule, PhysicalAddress(bootmod->start), PhysicalAddress(bootmod->end) });
  179. }
  180. }
  181. auto* mmap_begin = multiboot_memory_map;
  182. auto* mmap_end = multiboot_memory_map + multiboot_memory_map_count;
  183. struct ContiguousPhysicalRange {
  184. PhysicalAddress lower;
  185. PhysicalAddress upper;
  186. };
  187. Vector<ContiguousPhysicalRange> contiguous_physical_ranges;
  188. for (auto* mmap = mmap_begin; mmap < mmap_end; mmap++) {
  189. dmesgln("MM: Multiboot mmap: address={:p}, length={}, type={}", mmap->addr, mmap->len, mmap->type);
  190. auto start_address = PhysicalAddress(mmap->addr);
  191. auto length = mmap->len;
  192. switch (mmap->type) {
  193. case (MULTIBOOT_MEMORY_AVAILABLE):
  194. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Usable, start_address, length });
  195. break;
  196. case (MULTIBOOT_MEMORY_RESERVED):
  197. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Reserved, start_address, length });
  198. break;
  199. case (MULTIBOOT_MEMORY_ACPI_RECLAIMABLE):
  200. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::ACPI_Reclaimable, start_address, length });
  201. break;
  202. case (MULTIBOOT_MEMORY_NVS):
  203. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::ACPI_NVS, start_address, length });
  204. break;
  205. case (MULTIBOOT_MEMORY_BADRAM):
  206. dmesgln("MM: Warning, detected bad memory range!");
  207. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::BadMemory, start_address, length });
  208. break;
  209. default:
  210. dbgln("MM: Unknown range!");
  211. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Unknown, start_address, length });
  212. break;
  213. }
  214. if (mmap->type != MULTIBOOT_MEMORY_AVAILABLE)
  215. continue;
  216. // Fix up unaligned memory regions.
  217. auto diff = (FlatPtr)mmap->addr % PAGE_SIZE;
  218. if (diff != 0) {
  219. dmesgln("MM: Got an unaligned physical_region from the bootloader; correcting {:p} by {} bytes", mmap->addr, diff);
  220. diff = PAGE_SIZE - diff;
  221. mmap->addr += diff;
  222. mmap->len -= diff;
  223. }
  224. if ((mmap->len % PAGE_SIZE) != 0) {
  225. dmesgln("MM: Got an unaligned physical_region from the bootloader; correcting length {} by {} bytes", mmap->len, mmap->len % PAGE_SIZE);
  226. mmap->len -= mmap->len % PAGE_SIZE;
  227. }
  228. if (mmap->len < PAGE_SIZE) {
  229. dmesgln("MM: Memory physical_region from bootloader is too small; we want >= {} bytes, but got {} bytes", PAGE_SIZE, mmap->len);
  230. continue;
  231. }
  232. for (PhysicalSize page_base = mmap->addr; page_base <= (mmap->addr + mmap->len); page_base += PAGE_SIZE) {
  233. auto addr = PhysicalAddress(page_base);
  234. // Skip used memory ranges.
  235. bool should_skip = false;
  236. for (auto& used_range : m_used_memory_ranges) {
  237. if (addr.get() >= used_range.start.get() && addr.get() <= used_range.end.get()) {
  238. should_skip = true;
  239. break;
  240. }
  241. }
  242. if (should_skip)
  243. continue;
  244. if (contiguous_physical_ranges.is_empty() || contiguous_physical_ranges.last().upper.offset(PAGE_SIZE) != addr) {
  245. contiguous_physical_ranges.append(ContiguousPhysicalRange {
  246. .lower = addr,
  247. .upper = addr,
  248. });
  249. } else {
  250. contiguous_physical_ranges.last().upper = addr;
  251. }
  252. }
  253. }
  254. for (auto& range : contiguous_physical_ranges) {
  255. m_user_physical_regions.append(PhysicalRegion::try_create(range.lower, range.upper).release_nonnull());
  256. }
  257. // Super pages are guaranteed to be in the first 16MB of physical memory
  258. VERIFY(virtual_to_low_physical((FlatPtr)super_pages) + sizeof(super_pages) < 0x1000000);
  259. // Append statically-allocated super physical physical_region.
  260. m_super_physical_regions.append(PhysicalRegion::try_create(
  261. PhysicalAddress(virtual_to_low_physical(FlatPtr(super_pages))),
  262. PhysicalAddress(virtual_to_low_physical(FlatPtr(super_pages + sizeof(super_pages)))))
  263. .release_nonnull());
  264. for (auto& region : m_super_physical_regions)
  265. m_system_memory_info.super_physical_pages += region.size();
  266. for (auto& region : m_user_physical_regions)
  267. m_system_memory_info.user_physical_pages += region.size();
  268. register_reserved_ranges();
  269. for (auto& range : m_reserved_memory_ranges) {
  270. dmesgln("MM: Contiguous reserved range from {}, length is {}", range.start, range.length);
  271. }
  272. initialize_physical_pages();
  273. VERIFY(m_system_memory_info.super_physical_pages > 0);
  274. VERIFY(m_system_memory_info.user_physical_pages > 0);
  275. // We start out with no committed pages
  276. m_system_memory_info.user_physical_pages_uncommitted = m_system_memory_info.user_physical_pages;
  277. for (auto& used_range : m_used_memory_ranges) {
  278. dmesgln("MM: {} range @ {} - {} (size {:#x})", UserMemoryRangeTypeNames[to_underlying(used_range.type)], used_range.start, used_range.end.offset(-1), used_range.end.as_ptr() - used_range.start.as_ptr());
  279. }
  280. for (auto& region : m_super_physical_regions) {
  281. dmesgln("MM: Super physical region: {} - {} (size {:#x})", region.lower(), region.upper().offset(-1), PAGE_SIZE * region.size());
  282. region.initialize_zones();
  283. }
  284. for (auto& region : m_user_physical_regions) {
  285. dmesgln("MM: User physical region: {} - {} (size {:#x})", region.lower(), region.upper().offset(-1), PAGE_SIZE * region.size());
  286. region.initialize_zones();
  287. }
  288. }
  289. UNMAP_AFTER_INIT void MemoryManager::initialize_physical_pages()
  290. {
  291. // We assume that the physical page range is contiguous and doesn't contain huge gaps!
  292. PhysicalAddress highest_physical_address;
  293. for (auto& range : m_used_memory_ranges) {
  294. if (range.end.get() > highest_physical_address.get())
  295. highest_physical_address = range.end;
  296. }
  297. for (auto& region : m_physical_memory_ranges) {
  298. auto range_end = PhysicalAddress(region.start).offset(region.length);
  299. if (range_end.get() > highest_physical_address.get())
  300. highest_physical_address = range_end;
  301. }
  302. // Calculate how many total physical pages the array will have
  303. m_physical_page_entries_count = PhysicalAddress::physical_page_index(highest_physical_address.get()) + 1;
  304. VERIFY(m_physical_page_entries_count != 0);
  305. VERIFY(!Checked<decltype(m_physical_page_entries_count)>::multiplication_would_overflow(m_physical_page_entries_count, sizeof(PhysicalPageEntry)));
  306. // Calculate how many bytes the array will consume
  307. auto physical_page_array_size = m_physical_page_entries_count * sizeof(PhysicalPageEntry);
  308. auto physical_page_array_pages = page_round_up(physical_page_array_size) / PAGE_SIZE;
  309. VERIFY(physical_page_array_pages * PAGE_SIZE >= physical_page_array_size);
  310. // Calculate how many page tables we will need to be able to map them all
  311. auto needed_page_table_count = (physical_page_array_pages + 512 - 1) / 512;
  312. auto physical_page_array_pages_and_page_tables_count = physical_page_array_pages + needed_page_table_count;
  313. // Now that we know how much memory we need for a contiguous array of PhysicalPage instances, find a memory region that can fit it
  314. PhysicalRegion* found_region { nullptr };
  315. Optional<size_t> found_region_index;
  316. for (size_t i = 0; i < m_user_physical_regions.size(); ++i) {
  317. auto& region = m_user_physical_regions[i];
  318. if (region.size() >= physical_page_array_pages_and_page_tables_count) {
  319. found_region = &region;
  320. found_region_index = i;
  321. break;
  322. }
  323. }
  324. if (!found_region) {
  325. dmesgln("MM: Need {} bytes for physical page management, but no memory region is large enough!", physical_page_array_pages_and_page_tables_count);
  326. VERIFY_NOT_REACHED();
  327. }
  328. VERIFY(m_system_memory_info.user_physical_pages >= physical_page_array_pages_and_page_tables_count);
  329. m_system_memory_info.user_physical_pages -= physical_page_array_pages_and_page_tables_count;
  330. if (found_region->size() == physical_page_array_pages_and_page_tables_count) {
  331. // We're stealing the entire region
  332. m_physical_pages_region = m_user_physical_regions.take(*found_region_index);
  333. } else {
  334. m_physical_pages_region = found_region->try_take_pages_from_beginning(physical_page_array_pages_and_page_tables_count);
  335. }
  336. m_used_memory_ranges.append({ UsedMemoryRangeType::PhysicalPages, m_physical_pages_region->lower(), m_physical_pages_region->upper() });
  337. // Create the bare page directory. This is not a fully constructed page directory and merely contains the allocators!
  338. m_kernel_page_directory = PageDirectory::create_kernel_page_directory();
  339. // Allocate a virtual address range for our array
  340. auto range = m_kernel_page_directory->range_allocator().allocate_anywhere(physical_page_array_pages * PAGE_SIZE);
  341. if (!range.has_value()) {
  342. dmesgln("MM: Could not allocate {} bytes to map physical page array!", physical_page_array_pages * PAGE_SIZE);
  343. VERIFY_NOT_REACHED();
  344. }
  345. // Now that we have our special m_physical_pages_region region with enough pages to hold the entire array
  346. // try to map the entire region into kernel space so we always have it
  347. // We can't use ensure_pte here because it would try to allocate a PhysicalPage and we don't have the array
  348. // mapped yet so we can't create them
  349. ScopedSpinLock lock(s_mm_lock);
  350. // Create page tables at the beginning of m_physical_pages_region, followed by the PhysicalPageEntry array
  351. auto page_tables_base = m_physical_pages_region->lower();
  352. auto physical_page_array_base = page_tables_base.offset(needed_page_table_count * PAGE_SIZE);
  353. auto physical_page_array_current_page = physical_page_array_base.get();
  354. auto virtual_page_array_base = range.value().base().get();
  355. auto virtual_page_array_current_page = virtual_page_array_base;
  356. for (size_t pt_index = 0; pt_index < needed_page_table_count; pt_index++) {
  357. auto virtual_page_base_for_this_pt = virtual_page_array_current_page;
  358. auto pt_paddr = page_tables_base.offset(pt_index * PAGE_SIZE);
  359. auto* pt = reinterpret_cast<PageTableEntry*>(quickmap_page(pt_paddr));
  360. __builtin_memset(pt, 0, PAGE_SIZE);
  361. for (size_t pte_index = 0; pte_index < PAGE_SIZE / sizeof(PageTableEntry); pte_index++) {
  362. auto& pte = pt[pte_index];
  363. pte.set_physical_page_base(physical_page_array_current_page);
  364. pte.set_user_allowed(false);
  365. pte.set_writable(true);
  366. if (Processor::current().has_feature(CPUFeature::NX))
  367. pte.set_execute_disabled(false);
  368. pte.set_global(true);
  369. pte.set_present(true);
  370. physical_page_array_current_page += PAGE_SIZE;
  371. virtual_page_array_current_page += PAGE_SIZE;
  372. }
  373. unquickmap_page();
  374. // Hook the page table into the kernel page directory
  375. u32 page_directory_index = (virtual_page_base_for_this_pt >> 21) & 0x1ff;
  376. auto* pd = reinterpret_cast<PageDirectoryEntry*>(quickmap_page(boot_pd_kernel));
  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) & 0x1ff;
  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) & 0x1ff;
  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() & ~(FlatPtr)0x1fffff, move(page_table));
  473. // If you're hitting this VERIFY on x86_64 chances are a 64-bit pointer was truncated somewhere
  474. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  475. }
  476. return &quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()))[page_table_index];
  477. }
  478. void MemoryManager::release_pte(PageDirectory& page_directory, VirtualAddress vaddr, bool is_last_release)
  479. {
  480. VERIFY_INTERRUPTS_DISABLED();
  481. VERIFY(s_mm_lock.own_lock());
  482. VERIFY(page_directory.get_lock().own_lock());
  483. u32 page_directory_table_index = (vaddr.get() >> 30) & 0x1ff;
  484. u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
  485. u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
  486. auto* pd = quickmap_pd(page_directory, page_directory_table_index);
  487. PageDirectoryEntry& pde = pd[page_directory_index];
  488. if (pde.is_present()) {
  489. auto* page_table = quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()));
  490. auto& pte = page_table[page_table_index];
  491. pte.clear();
  492. if (is_last_release || page_table_index == 0x1ff) {
  493. // If this is the last PTE in a region or the last PTE in a page table then
  494. // check if we can also release the page table
  495. bool all_clear = true;
  496. for (u32 i = 0; i <= 0x1ff; i++) {
  497. if (!page_table[i].is_null()) {
  498. all_clear = false;
  499. break;
  500. }
  501. }
  502. if (all_clear) {
  503. pde.clear();
  504. auto result = page_directory.m_page_tables.remove(vaddr.get() & ~0x1fffff);
  505. VERIFY(result);
  506. }
  507. }
  508. }
  509. }
  510. UNMAP_AFTER_INIT void MemoryManager::initialize(u32 cpu)
  511. {
  512. ProcessorSpecific<MemoryManagerData>::initialize();
  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_no_lock(Space& space, VirtualAddress vaddr)
  528. {
  529. VERIFY(space.get_lock().own_lock());
  530. return space.find_region_containing({ vaddr, 1 });
  531. }
  532. Region* MemoryManager::find_user_region_from_vaddr(Space& space, VirtualAddress vaddr)
  533. {
  534. ScopedSpinLock lock(space.get_lock());
  535. return find_user_region_from_vaddr_no_lock(space, vaddr);
  536. }
  537. void MemoryManager::validate_syscall_preconditions(Space& space, RegisterState const& regs)
  538. {
  539. // We take the space lock once here and then use the no_lock variants
  540. // to avoid excessive spinlock recursion in this extemely common path.
  541. ScopedSpinLock lock(space.get_lock());
  542. auto unlock_and_handle_crash = [&lock, &regs](const char* description, int signal) {
  543. lock.unlock();
  544. handle_crash(regs, description, signal);
  545. };
  546. {
  547. VirtualAddress userspace_sp = VirtualAddress { regs.userspace_sp() };
  548. if (!MM.validate_user_stack_no_lock(space, userspace_sp)) {
  549. dbgln("Invalid stack pointer: {:p}", userspace_sp);
  550. unlock_and_handle_crash("Bad stack on syscall entry", SIGSTKFLT);
  551. }
  552. }
  553. {
  554. VirtualAddress ip = VirtualAddress { regs.ip() };
  555. auto* calling_region = MM.find_user_region_from_vaddr_no_lock(space, ip);
  556. if (!calling_region) {
  557. dbgln("Syscall from {:p} which has no associated region", ip);
  558. unlock_and_handle_crash("Syscall from unknown region", SIGSEGV);
  559. }
  560. if (calling_region->is_writable()) {
  561. dbgln("Syscall from writable memory at {:p}", ip);
  562. unlock_and_handle_crash("Syscall from writable memory", SIGSEGV);
  563. }
  564. if (space.enforces_syscall_regions() && !calling_region->is_syscall_region()) {
  565. dbgln("Syscall from non-syscall region");
  566. unlock_and_handle_crash("Syscall from non-syscall region", SIGSEGV);
  567. }
  568. }
  569. }
  570. Region* MemoryManager::find_region_from_vaddr(VirtualAddress vaddr)
  571. {
  572. ScopedSpinLock lock(s_mm_lock);
  573. if (auto* region = kernel_region_from_vaddr(vaddr))
  574. return region;
  575. auto page_directory = PageDirectory::find_by_cr3(read_cr3());
  576. if (!page_directory)
  577. return nullptr;
  578. VERIFY(page_directory->space());
  579. return find_user_region_from_vaddr(*page_directory->space(), vaddr);
  580. }
  581. PageFaultResponse MemoryManager::handle_page_fault(PageFault const& fault)
  582. {
  583. VERIFY_INTERRUPTS_DISABLED();
  584. if (Processor::current().in_irq()) {
  585. dbgln("CPU[{}] BUG! Page fault while handling IRQ! code={}, vaddr={}, irq level: {}",
  586. Processor::id(), fault.code(), fault.vaddr(), Processor::current().in_irq());
  587. dump_kernel_regions();
  588. return PageFaultResponse::ShouldCrash;
  589. }
  590. dbgln_if(PAGE_FAULT_DEBUG, "MM: CPU[{}] handle_page_fault({:#04x}) at {}", Processor::id(), fault.code(), fault.vaddr());
  591. auto* region = find_region_from_vaddr(fault.vaddr());
  592. if (!region) {
  593. return PageFaultResponse::ShouldCrash;
  594. }
  595. return region->handle_fault(fault);
  596. }
  597. OwnPtr<Region> MemoryManager::allocate_contiguous_kernel_region(size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
  598. {
  599. VERIFY(!(size % PAGE_SIZE));
  600. ScopedSpinLock lock(s_mm_lock);
  601. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  602. if (!range.has_value())
  603. return {};
  604. auto vmobject = AnonymousVMObject::try_create_physically_contiguous_with_size(size);
  605. if (!vmobject) {
  606. kernel_page_directory().range_allocator().deallocate(range.value());
  607. return {};
  608. }
  609. return allocate_kernel_region_with_vmobject(range.value(), *vmobject, name, access, cacheable);
  610. }
  611. OwnPtr<Region> MemoryManager::allocate_kernel_region(size_t size, StringView name, Region::Access access, AllocationStrategy strategy, Region::Cacheable cacheable)
  612. {
  613. VERIFY(!(size % PAGE_SIZE));
  614. auto vm_object = AnonymousVMObject::try_create_with_size(size, strategy);
  615. if (!vm_object)
  616. return {};
  617. ScopedSpinLock lock(s_mm_lock);
  618. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  619. if (!range.has_value())
  620. return {};
  621. return allocate_kernel_region_with_vmobject(range.value(), vm_object.release_nonnull(), name, access, cacheable);
  622. }
  623. OwnPtr<Region> MemoryManager::allocate_kernel_region(PhysicalAddress paddr, size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
  624. {
  625. auto vm_object = AnonymousVMObject::try_create_for_physical_range(paddr, size);
  626. if (!vm_object)
  627. return {};
  628. VERIFY(!(size % PAGE_SIZE));
  629. ScopedSpinLock lock(s_mm_lock);
  630. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  631. if (!range.has_value())
  632. return {};
  633. return allocate_kernel_region_with_vmobject(range.value(), *vm_object, name, access, cacheable);
  634. }
  635. OwnPtr<Region> MemoryManager::allocate_kernel_region_identity(PhysicalAddress paddr, size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
  636. {
  637. auto vm_object = AnonymousVMObject::try_create_for_physical_range(paddr, size);
  638. if (!vm_object)
  639. return {};
  640. VERIFY(!(size % PAGE_SIZE));
  641. ScopedSpinLock lock(s_mm_lock);
  642. auto range = kernel_page_directory().identity_range_allocator().allocate_specific(VirtualAddress(paddr.get()), size);
  643. if (!range.has_value())
  644. return {};
  645. return allocate_kernel_region_with_vmobject(range.value(), *vm_object, name, access, cacheable);
  646. }
  647. OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(Range const& range, VMObject& vmobject, StringView name, Region::Access access, Region::Cacheable cacheable)
  648. {
  649. ScopedSpinLock lock(s_mm_lock);
  650. auto region = Region::try_create_kernel_only(range, vmobject, 0, KString::try_create(name), access, cacheable);
  651. if (region)
  652. region->map(kernel_page_directory());
  653. return region;
  654. }
  655. OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(VMObject& vmobject, size_t size, StringView name, Region::Access access, Region::Cacheable cacheable)
  656. {
  657. VERIFY(!(size % PAGE_SIZE));
  658. ScopedSpinLock lock(s_mm_lock);
  659. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  660. if (!range.has_value())
  661. return {};
  662. return allocate_kernel_region_with_vmobject(range.value(), vmobject, name, access, cacheable);
  663. }
  664. bool MemoryManager::commit_user_physical_pages(size_t page_count)
  665. {
  666. VERIFY(page_count > 0);
  667. ScopedSpinLock lock(s_mm_lock);
  668. if (m_system_memory_info.user_physical_pages_uncommitted < page_count)
  669. return false;
  670. m_system_memory_info.user_physical_pages_uncommitted -= page_count;
  671. m_system_memory_info.user_physical_pages_committed += page_count;
  672. return true;
  673. }
  674. void MemoryManager::uncommit_user_physical_pages(size_t page_count)
  675. {
  676. VERIFY(page_count > 0);
  677. ScopedSpinLock lock(s_mm_lock);
  678. VERIFY(m_system_memory_info.user_physical_pages_committed >= page_count);
  679. m_system_memory_info.user_physical_pages_uncommitted += page_count;
  680. m_system_memory_info.user_physical_pages_committed -= page_count;
  681. }
  682. void MemoryManager::deallocate_physical_page(PhysicalAddress paddr)
  683. {
  684. ScopedSpinLock lock(s_mm_lock);
  685. // Are we returning a user page?
  686. for (auto& region : m_user_physical_regions) {
  687. if (!region.contains(paddr))
  688. continue;
  689. region.return_page(paddr);
  690. --m_system_memory_info.user_physical_pages_used;
  691. // Always return pages to the uncommitted pool. Pages that were
  692. // committed and allocated are only freed upon request. Once
  693. // returned there is no guarantee being able to get them back.
  694. ++m_system_memory_info.user_physical_pages_uncommitted;
  695. return;
  696. }
  697. // If it's not a user page, it should be a supervisor page.
  698. for (auto& region : m_super_physical_regions) {
  699. if (!region.contains(paddr)) {
  700. dbgln("MM: deallocate_supervisor_physical_page: {} not in {} - {}", paddr, region.lower(), region.upper());
  701. continue;
  702. }
  703. region.return_page(paddr);
  704. --m_system_memory_info.super_physical_pages_used;
  705. return;
  706. }
  707. PANIC("MM: deallocate_user_physical_page couldn't figure out region for page @ {}", paddr);
  708. }
  709. RefPtr<PhysicalPage> MemoryManager::find_free_user_physical_page(bool committed)
  710. {
  711. VERIFY(s_mm_lock.is_locked());
  712. RefPtr<PhysicalPage> page;
  713. if (committed) {
  714. // Draw from the committed pages pool. We should always have these pages available
  715. VERIFY(m_system_memory_info.user_physical_pages_committed > 0);
  716. m_system_memory_info.user_physical_pages_committed--;
  717. } else {
  718. // We need to make sure we don't touch pages that we have committed to
  719. if (m_system_memory_info.user_physical_pages_uncommitted == 0)
  720. return {};
  721. m_system_memory_info.user_physical_pages_uncommitted--;
  722. }
  723. for (auto& region : m_user_physical_regions) {
  724. page = region.take_free_page();
  725. if (!page.is_null()) {
  726. ++m_system_memory_info.user_physical_pages_used;
  727. break;
  728. }
  729. }
  730. VERIFY(!committed || !page.is_null());
  731. return page;
  732. }
  733. NonnullRefPtr<PhysicalPage> MemoryManager::allocate_committed_user_physical_page(ShouldZeroFill should_zero_fill)
  734. {
  735. ScopedSpinLock lock(s_mm_lock);
  736. auto page = find_free_user_physical_page(true);
  737. if (should_zero_fill == ShouldZeroFill::Yes) {
  738. auto* ptr = quickmap_page(*page);
  739. memset(ptr, 0, PAGE_SIZE);
  740. unquickmap_page();
  741. }
  742. return page.release_nonnull();
  743. }
  744. RefPtr<PhysicalPage> MemoryManager::allocate_user_physical_page(ShouldZeroFill should_zero_fill, bool* did_purge)
  745. {
  746. ScopedSpinLock lock(s_mm_lock);
  747. auto page = find_free_user_physical_page(false);
  748. bool purged_pages = false;
  749. if (!page) {
  750. // We didn't have a single free physical page. Let's try to free something up!
  751. // First, we look for a purgeable VMObject in the volatile state.
  752. for_each_vmobject([&](auto& vmobject) {
  753. if (!vmobject.is_anonymous())
  754. return IterationDecision::Continue;
  755. auto& anonymous_vmobject = static_cast<AnonymousVMObject&>(vmobject);
  756. if (!anonymous_vmobject.is_purgeable() || !anonymous_vmobject.is_volatile())
  757. return IterationDecision::Continue;
  758. if (auto purged_page_count = anonymous_vmobject.purge()) {
  759. dbgln("MM: Purge saved the day! Purged {} pages from AnonymousVMObject", purged_page_count);
  760. page = find_free_user_physical_page(false);
  761. purged_pages = true;
  762. VERIFY(page);
  763. return IterationDecision::Break;
  764. }
  765. return IterationDecision::Continue;
  766. });
  767. if (!page) {
  768. dmesgln("MM: no user physical pages available");
  769. return {};
  770. }
  771. }
  772. if (should_zero_fill == ShouldZeroFill::Yes) {
  773. auto* ptr = quickmap_page(*page);
  774. memset(ptr, 0, PAGE_SIZE);
  775. unquickmap_page();
  776. }
  777. if (did_purge)
  778. *did_purge = purged_pages;
  779. return page;
  780. }
  781. NonnullRefPtrVector<PhysicalPage> MemoryManager::allocate_contiguous_supervisor_physical_pages(size_t size)
  782. {
  783. VERIFY(!(size % PAGE_SIZE));
  784. ScopedSpinLock lock(s_mm_lock);
  785. size_t count = ceil_div(size, static_cast<size_t>(PAGE_SIZE));
  786. NonnullRefPtrVector<PhysicalPage> physical_pages;
  787. for (auto& region : m_super_physical_regions) {
  788. physical_pages = region.take_contiguous_free_pages(count);
  789. if (!physical_pages.is_empty())
  790. continue;
  791. }
  792. if (physical_pages.is_empty()) {
  793. if (m_super_physical_regions.is_empty()) {
  794. dmesgln("MM: no super physical regions available (?)");
  795. }
  796. dmesgln("MM: no super physical pages available");
  797. VERIFY_NOT_REACHED();
  798. return {};
  799. }
  800. auto cleanup_region = MM.allocate_kernel_region(physical_pages[0].paddr(), PAGE_SIZE * count, "MemoryManager Allocation Sanitization", Region::Access::Read | Region::Access::Write);
  801. fast_u32_fill((u32*)cleanup_region->vaddr().as_ptr(), 0, (PAGE_SIZE * count) / sizeof(u32));
  802. m_system_memory_info.super_physical_pages_used += count;
  803. return physical_pages;
  804. }
  805. RefPtr<PhysicalPage> MemoryManager::allocate_supervisor_physical_page()
  806. {
  807. ScopedSpinLock lock(s_mm_lock);
  808. RefPtr<PhysicalPage> page;
  809. for (auto& region : m_super_physical_regions) {
  810. page = region.take_free_page();
  811. if (!page.is_null())
  812. break;
  813. }
  814. if (!page) {
  815. if (m_super_physical_regions.is_empty()) {
  816. dmesgln("MM: no super physical regions available (?)");
  817. }
  818. dmesgln("MM: no super physical pages available");
  819. VERIFY_NOT_REACHED();
  820. return {};
  821. }
  822. fast_u32_fill((u32*)page->paddr().offset(physical_to_virtual_offset).as_ptr(), 0, PAGE_SIZE / sizeof(u32));
  823. ++m_system_memory_info.super_physical_pages_used;
  824. return page;
  825. }
  826. void MemoryManager::enter_process_paging_scope(Process& process)
  827. {
  828. enter_space(process.space());
  829. }
  830. void MemoryManager::enter_space(Space& space)
  831. {
  832. auto current_thread = Thread::current();
  833. VERIFY(current_thread != nullptr);
  834. ScopedSpinLock lock(s_mm_lock);
  835. current_thread->regs().cr3 = space.page_directory().cr3();
  836. write_cr3(space.page_directory().cr3());
  837. }
  838. void MemoryManager::flush_tlb_local(VirtualAddress vaddr, size_t page_count)
  839. {
  840. Processor::flush_tlb_local(vaddr, page_count);
  841. }
  842. void MemoryManager::flush_tlb(PageDirectory const* page_directory, VirtualAddress vaddr, size_t page_count)
  843. {
  844. Processor::flush_tlb(page_directory, vaddr, page_count);
  845. }
  846. PageDirectoryEntry* MemoryManager::quickmap_pd(PageDirectory& directory, size_t pdpt_index)
  847. {
  848. VERIFY(s_mm_lock.own_lock());
  849. auto& mm_data = get_data();
  850. auto& pte = boot_pd_kernel_pt1023[(KERNEL_QUICKMAP_PD - KERNEL_PT1024_BASE) / PAGE_SIZE];
  851. auto pd_paddr = directory.m_directory_pages[pdpt_index]->paddr();
  852. if (pte.physical_page_base() != pd_paddr.get()) {
  853. pte.set_physical_page_base(pd_paddr.get());
  854. pte.set_present(true);
  855. pte.set_writable(true);
  856. pte.set_user_allowed(false);
  857. // Because we must continue to hold the MM lock while we use this
  858. // mapping, it is sufficient to only flush on the current CPU. Other
  859. // CPUs trying to use this API must wait on the MM lock anyway
  860. flush_tlb_local(VirtualAddress(KERNEL_QUICKMAP_PD));
  861. } else {
  862. // Even though we don't allow this to be called concurrently, it's
  863. // possible that this PD was mapped on a different CPU and we don't
  864. // broadcast the flush. If so, we still need to flush the TLB.
  865. if (mm_data.m_last_quickmap_pd != pd_paddr)
  866. flush_tlb_local(VirtualAddress(KERNEL_QUICKMAP_PD));
  867. }
  868. mm_data.m_last_quickmap_pd = pd_paddr;
  869. return (PageDirectoryEntry*)KERNEL_QUICKMAP_PD;
  870. }
  871. PageTableEntry* MemoryManager::quickmap_pt(PhysicalAddress pt_paddr)
  872. {
  873. VERIFY(s_mm_lock.own_lock());
  874. auto& mm_data = get_data();
  875. auto& pte = ((PageTableEntry*)boot_pd_kernel_pt1023)[(KERNEL_QUICKMAP_PT - KERNEL_PT1024_BASE) / PAGE_SIZE];
  876. if (pte.physical_page_base() != pt_paddr.get()) {
  877. pte.set_physical_page_base(pt_paddr.get());
  878. pte.set_present(true);
  879. pte.set_writable(true);
  880. pte.set_user_allowed(false);
  881. // Because we must continue to hold the MM lock while we use this
  882. // mapping, it is sufficient to only flush on the current CPU. Other
  883. // CPUs trying to use this API must wait on the MM lock anyway
  884. flush_tlb_local(VirtualAddress(KERNEL_QUICKMAP_PT));
  885. } else {
  886. // Even though we don't allow this to be called concurrently, it's
  887. // possible that this PT was mapped on a different CPU and we don't
  888. // broadcast the flush. If so, we still need to flush the TLB.
  889. if (mm_data.m_last_quickmap_pt != pt_paddr)
  890. flush_tlb_local(VirtualAddress(KERNEL_QUICKMAP_PT));
  891. }
  892. mm_data.m_last_quickmap_pt = pt_paddr;
  893. return (PageTableEntry*)KERNEL_QUICKMAP_PT;
  894. }
  895. u8* MemoryManager::quickmap_page(PhysicalAddress const& physical_address)
  896. {
  897. VERIFY_INTERRUPTS_DISABLED();
  898. auto& mm_data = get_data();
  899. mm_data.m_quickmap_prev_flags = mm_data.m_quickmap_in_use.lock();
  900. ScopedSpinLock lock(s_mm_lock);
  901. VirtualAddress vaddr(KERNEL_QUICKMAP_PER_CPU_BASE + Processor::id() * PAGE_SIZE);
  902. u32 pte_idx = (vaddr.get() - KERNEL_PT1024_BASE) / PAGE_SIZE;
  903. auto& pte = ((PageTableEntry*)boot_pd_kernel_pt1023)[pte_idx];
  904. if (pte.physical_page_base() != physical_address.get()) {
  905. pte.set_physical_page_base(physical_address.get());
  906. pte.set_present(true);
  907. pte.set_writable(true);
  908. pte.set_user_allowed(false);
  909. flush_tlb_local(vaddr);
  910. }
  911. return vaddr.as_ptr();
  912. }
  913. void MemoryManager::unquickmap_page()
  914. {
  915. VERIFY_INTERRUPTS_DISABLED();
  916. ScopedSpinLock lock(s_mm_lock);
  917. auto& mm_data = get_data();
  918. VERIFY(mm_data.m_quickmap_in_use.is_locked());
  919. VirtualAddress vaddr(KERNEL_QUICKMAP_PER_CPU_BASE + Processor::id() * PAGE_SIZE);
  920. u32 pte_idx = (vaddr.get() - KERNEL_PT1024_BASE) / PAGE_SIZE;
  921. auto& pte = ((PageTableEntry*)boot_pd_kernel_pt1023)[pte_idx];
  922. pte.clear();
  923. flush_tlb_local(vaddr);
  924. mm_data.m_quickmap_in_use.unlock(mm_data.m_quickmap_prev_flags);
  925. }
  926. bool MemoryManager::validate_user_stack_no_lock(Space& space, VirtualAddress vaddr) const
  927. {
  928. VERIFY(space.get_lock().own_lock());
  929. if (!is_user_address(vaddr))
  930. return false;
  931. auto* region = find_user_region_from_vaddr_no_lock(space, vaddr);
  932. return region && region->is_user() && region->is_stack();
  933. }
  934. bool MemoryManager::validate_user_stack(Space& space, VirtualAddress vaddr) const
  935. {
  936. ScopedSpinLock lock(space.get_lock());
  937. return validate_user_stack_no_lock(space, vaddr);
  938. }
  939. void MemoryManager::register_vmobject(VMObject& vmobject)
  940. {
  941. ScopedSpinLock lock(s_mm_lock);
  942. m_vmobjects.append(vmobject);
  943. }
  944. void MemoryManager::unregister_vmobject(VMObject& vmobject)
  945. {
  946. ScopedSpinLock lock(s_mm_lock);
  947. m_vmobjects.remove(vmobject);
  948. }
  949. void MemoryManager::register_region(Region& region)
  950. {
  951. ScopedSpinLock lock(s_mm_lock);
  952. if (region.is_kernel())
  953. m_kernel_regions.append(region);
  954. else
  955. m_user_regions.append(region);
  956. }
  957. void MemoryManager::unregister_region(Region& region)
  958. {
  959. ScopedSpinLock lock(s_mm_lock);
  960. if (region.is_kernel())
  961. m_kernel_regions.remove(region);
  962. else
  963. m_user_regions.remove(region);
  964. }
  965. void MemoryManager::dump_kernel_regions()
  966. {
  967. dbgln("Kernel regions:");
  968. #if ARCH(I386)
  969. auto addr_padding = "";
  970. #else
  971. auto addr_padding = " ";
  972. #endif
  973. dbgln("BEGIN{} END{} SIZE{} ACCESS NAME",
  974. addr_padding, addr_padding, addr_padding);
  975. ScopedSpinLock lock(s_mm_lock);
  976. for (auto& region : m_kernel_regions) {
  977. dbgln("{:p} -- {:p} {:p} {:c}{:c}{:c}{:c}{:c}{:c} {}",
  978. region.vaddr().get(),
  979. region.vaddr().offset(region.size() - 1).get(),
  980. region.size(),
  981. region.is_readable() ? 'R' : ' ',
  982. region.is_writable() ? 'W' : ' ',
  983. region.is_executable() ? 'X' : ' ',
  984. region.is_shared() ? 'S' : ' ',
  985. region.is_stack() ? 'T' : ' ',
  986. region.is_syscall_region() ? 'C' : ' ',
  987. region.name());
  988. }
  989. }
  990. void MemoryManager::set_page_writable_direct(VirtualAddress vaddr, bool writable)
  991. {
  992. ScopedSpinLock lock(s_mm_lock);
  993. ScopedSpinLock page_lock(kernel_page_directory().get_lock());
  994. auto* pte = ensure_pte(kernel_page_directory(), vaddr);
  995. VERIFY(pte);
  996. if (pte->is_writable() == writable)
  997. return;
  998. pte->set_writable(writable);
  999. flush_tlb(&kernel_page_directory(), vaddr);
  1000. }
  1001. }