MemoryManager.cpp 49 KB

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