MemoryManager.cpp 46 KB

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