MemoryManager.cpp 46 KB

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