MemoryManager.cpp 53 KB

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