MemoryManager.cpp 46 KB

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