MemoryManager.cpp 50 KB

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