MemoryManager.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Assertions.h>
  27. #include <AK/Memory.h>
  28. #include <AK/StringView.h>
  29. #include <Kernel/Arch/i386/CPU.h>
  30. #include <Kernel/CMOS.h>
  31. #include <Kernel/FileSystem/Inode.h>
  32. #include <Kernel/Heap/kmalloc.h>
  33. #include <Kernel/Multiboot.h>
  34. #include <Kernel/Process.h>
  35. #include <Kernel/StdLib.h>
  36. #include <Kernel/VM/AnonymousVMObject.h>
  37. #include <Kernel/VM/ContiguousVMObject.h>
  38. #include <Kernel/VM/MemoryManager.h>
  39. #include <Kernel/VM/PageDirectory.h>
  40. #include <Kernel/VM/PhysicalRegion.h>
  41. #include <Kernel/VM/SharedInodeVMObject.h>
  42. extern u8* start_of_kernel_image;
  43. extern u8* end_of_kernel_image;
  44. extern FlatPtr start_of_kernel_text;
  45. extern FlatPtr start_of_kernel_data;
  46. extern FlatPtr end_of_kernel_bss;
  47. extern FlatPtr start_of_ro_after_init;
  48. extern FlatPtr end_of_ro_after_init;
  49. extern FlatPtr start_of_unmap_after_init;
  50. extern FlatPtr end_of_unmap_after_init;
  51. extern multiboot_module_entry_t multiboot_copy_boot_modules_array[16];
  52. extern size_t multiboot_copy_boot_modules_count;
  53. // Treat the super pages as logically separate from .bss
  54. __attribute__((section(".super_pages"))) static u8 super_pages[1 * MiB];
  55. namespace Kernel {
  56. // NOTE: We can NOT use AK::Singleton for this class, because
  57. // MemoryManager::initialize is called *before* global constructors are
  58. // run. If we do, then AK::Singleton would get re-initialized, causing
  59. // the memory manager to be initialized twice!
  60. static MemoryManager* s_the;
  61. RecursiveSpinLock s_mm_lock;
  62. const LogStream& operator<<(const LogStream& stream, const UsedMemoryRange& value)
  63. {
  64. return stream << UserMemoryRangeTypeNames[static_cast<int>(value.type)] << " range @ " << value.start << " - " << value.end;
  65. }
  66. MemoryManager& MM
  67. {
  68. return *s_the;
  69. }
  70. bool MemoryManager::is_initialized()
  71. {
  72. return s_the != nullptr;
  73. }
  74. UNMAP_AFTER_INIT MemoryManager::MemoryManager()
  75. {
  76. ScopedSpinLock lock(s_mm_lock);
  77. m_kernel_page_directory = PageDirectory::create_kernel_page_directory();
  78. parse_memory_map();
  79. write_cr3(kernel_page_directory().cr3());
  80. protect_kernel_image();
  81. // We're temporarily "committing" to two pages that we need to allocate below
  82. if (!commit_user_physical_pages(2))
  83. VERIFY_NOT_REACHED();
  84. m_shared_zero_page = allocate_committed_user_physical_page();
  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 = allocate_committed_user_physical_page();
  92. }
  93. UNMAP_AFTER_INIT MemoryManager::~MemoryManager()
  94. {
  95. }
  96. UNMAP_AFTER_INIT void MemoryManager::protect_kernel_image()
  97. {
  98. ScopedSpinLock page_lock(kernel_page_directory().get_lock());
  99. // Disable writing to the kernel text and rodata segments.
  100. for (auto i = (FlatPtr)&start_of_kernel_text; i < (FlatPtr)&start_of_kernel_data; i += PAGE_SIZE) {
  101. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  102. pte.set_writable(false);
  103. }
  104. if (Processor::current().has_feature(CPUFeature::NX)) {
  105. // Disable execution of the kernel data, bss and heap segments.
  106. for (auto i = (FlatPtr)&start_of_kernel_data; i < (FlatPtr)&end_of_kernel_image; i += PAGE_SIZE) {
  107. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  108. pte.set_execute_disabled(true);
  109. }
  110. }
  111. }
  112. UNMAP_AFTER_INIT void MemoryManager::protect_readonly_after_init_memory()
  113. {
  114. ScopedSpinLock mm_lock(s_mm_lock);
  115. ScopedSpinLock page_lock(kernel_page_directory().get_lock());
  116. // Disable writing to the .ro_after_init section
  117. for (auto i = (FlatPtr)&start_of_ro_after_init; i < (FlatPtr)&end_of_ro_after_init; i += PAGE_SIZE) {
  118. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  119. pte.set_writable(false);
  120. flush_tlb(&kernel_page_directory(), VirtualAddress(i));
  121. }
  122. }
  123. void MemoryManager::unmap_memory_after_init()
  124. {
  125. ScopedSpinLock mm_lock(s_mm_lock);
  126. ScopedSpinLock page_lock(kernel_page_directory().get_lock());
  127. auto start = page_round_down((FlatPtr)&start_of_unmap_after_init);
  128. auto end = page_round_up((FlatPtr)&end_of_unmap_after_init);
  129. // Unmap the entire .unmap_after_init section
  130. for (auto i = start; i < end; i += PAGE_SIZE) {
  131. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  132. pte.clear();
  133. flush_tlb(&kernel_page_directory(), VirtualAddress(i));
  134. }
  135. dmesgln("Unmapped {} KiB of kernel text after init! :^)", (end - start) / KiB);
  136. //Processor::halt();
  137. }
  138. UNMAP_AFTER_INIT void MemoryManager::register_reserved_ranges()
  139. {
  140. VERIFY(!m_physical_memory_ranges.is_empty());
  141. ContiguousReservedMemoryRange range;
  142. for (auto& current_range : m_physical_memory_ranges) {
  143. if (current_range.type != PhysicalMemoryRangeType::Reserved) {
  144. if (range.start.is_null())
  145. continue;
  146. m_reserved_memory_ranges.append(ContiguousReservedMemoryRange { range.start, current_range.start.get() - range.start.get() });
  147. range.start.set((FlatPtr) nullptr);
  148. continue;
  149. }
  150. if (!range.start.is_null()) {
  151. continue;
  152. }
  153. range.start = current_range.start;
  154. }
  155. if (m_physical_memory_ranges.last().type != PhysicalMemoryRangeType::Reserved)
  156. return;
  157. if (range.start.is_null())
  158. return;
  159. m_reserved_memory_ranges.append(ContiguousReservedMemoryRange { range.start, m_physical_memory_ranges.last().start.get() + m_physical_memory_ranges.last().length - range.start.get() });
  160. }
  161. bool MemoryManager::is_allowed_to_mmap_to_userspace(PhysicalAddress start_address, const Range& range) const
  162. {
  163. VERIFY(!m_reserved_memory_ranges.is_empty());
  164. for (auto& current_range : m_reserved_memory_ranges) {
  165. if (!(current_range.start <= start_address))
  166. continue;
  167. if (!(current_range.start.offset(current_range.length) > start_address))
  168. continue;
  169. if (current_range.length < range.size())
  170. return false;
  171. return true;
  172. }
  173. return false;
  174. }
  175. UNMAP_AFTER_INIT void MemoryManager::parse_memory_map()
  176. {
  177. RefPtr<PhysicalRegion> physical_region;
  178. // Register used memory regions that we know of.
  179. m_used_memory_ranges.ensure_capacity(4);
  180. m_used_memory_ranges.append(UsedMemoryRange { UsedMemoryRangeType::LowMemory, PhysicalAddress(0x00000000), PhysicalAddress(1 * MiB) });
  181. 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)))) });
  182. if (multiboot_info_ptr->flags & 0x4) {
  183. auto* bootmods_start = multiboot_copy_boot_modules_array;
  184. auto* bootmods_end = bootmods_start + multiboot_copy_boot_modules_count;
  185. for (auto* bootmod = bootmods_start; bootmod < bootmods_end; bootmod++) {
  186. m_used_memory_ranges.append(UsedMemoryRange { UsedMemoryRangeType::BootModule, PhysicalAddress(bootmod->start), PhysicalAddress(bootmod->end) });
  187. }
  188. }
  189. auto* mmap_begin = reinterpret_cast<multiboot_memory_map_t*>(low_physical_to_virtual(multiboot_info_ptr->mmap_addr));
  190. auto* mmap_end = reinterpret_cast<multiboot_memory_map_t*>(low_physical_to_virtual(multiboot_info_ptr->mmap_addr) + multiboot_info_ptr->mmap_length);
  191. for (auto& used_range : m_used_memory_ranges) {
  192. klog() << "MM: " << used_range;
  193. }
  194. for (auto* mmap = mmap_begin; mmap < mmap_end; mmap++) {
  195. dmesgln("MM: Multiboot mmap: address={:p}, length={}, type={}", mmap->addr, mmap->len, mmap->type);
  196. auto start_address = PhysicalAddress(mmap->addr);
  197. auto length = static_cast<size_t>(mmap->len);
  198. switch (mmap->type) {
  199. case (MULTIBOOT_MEMORY_AVAILABLE):
  200. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Usable, start_address, length });
  201. break;
  202. case (MULTIBOOT_MEMORY_RESERVED):
  203. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Reserved, start_address, length });
  204. break;
  205. case (MULTIBOOT_MEMORY_ACPI_RECLAIMABLE):
  206. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::ACPI_Reclaimable, start_address, length });
  207. break;
  208. case (MULTIBOOT_MEMORY_NVS):
  209. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::ACPI_NVS, start_address, length });
  210. break;
  211. case (MULTIBOOT_MEMORY_BADRAM):
  212. klog() << "MM: Warning, detected bad memory range!";
  213. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::BadMemory, start_address, length });
  214. break;
  215. default:
  216. dbgln("MM: Unknown range!");
  217. m_physical_memory_ranges.append(PhysicalMemoryRange { PhysicalMemoryRangeType::Unknown, start_address, length });
  218. break;
  219. }
  220. if (mmap->type != MULTIBOOT_MEMORY_AVAILABLE)
  221. continue;
  222. if ((mmap->addr + mmap->len) > 0xffffffff)
  223. continue;
  224. // Fix up unaligned memory regions.
  225. auto diff = (FlatPtr)mmap->addr % PAGE_SIZE;
  226. if (diff != 0) {
  227. dmesgln("MM: Got an unaligned physical_region from the bootloader; correcting {:p} by {} bytes", mmap->addr, diff);
  228. diff = PAGE_SIZE - diff;
  229. mmap->addr += diff;
  230. mmap->len -= diff;
  231. }
  232. if ((mmap->len % PAGE_SIZE) != 0) {
  233. dmesgln("MM: Got an unaligned physical_region from the bootloader; correcting length {} by {} bytes", mmap->len, mmap->len % PAGE_SIZE);
  234. mmap->len -= mmap->len % PAGE_SIZE;
  235. }
  236. if (mmap->len < PAGE_SIZE) {
  237. dmesgln("MM: Memory physical_region from bootloader is too small; we want >= {} bytes, but got {} bytes", PAGE_SIZE, mmap->len);
  238. continue;
  239. }
  240. for (size_t page_base = mmap->addr; page_base <= (mmap->addr + mmap->len); page_base += PAGE_SIZE) {
  241. auto addr = PhysicalAddress(page_base);
  242. // Skip used memory ranges.
  243. bool should_skip = false;
  244. for (auto& used_range : m_used_memory_ranges) {
  245. if (addr.get() >= used_range.start.get() && addr.get() <= used_range.end.get()) {
  246. should_skip = true;
  247. break;
  248. }
  249. }
  250. if (should_skip)
  251. continue;
  252. // Assign page to user physical physical_region.
  253. if (physical_region.is_null() || physical_region->upper().offset(PAGE_SIZE) != addr) {
  254. m_user_physical_regions.append(PhysicalRegion::create(addr, addr));
  255. physical_region = m_user_physical_regions.last();
  256. } else {
  257. physical_region->expand(physical_region->lower(), addr);
  258. }
  259. }
  260. }
  261. // Append statically-allocated super physical physical_region.
  262. m_super_physical_regions.append(PhysicalRegion::create(
  263. PhysicalAddress(virtual_to_low_physical(FlatPtr(super_pages))),
  264. PhysicalAddress(virtual_to_low_physical(FlatPtr(super_pages + sizeof(super_pages))))));
  265. for (auto& region : m_super_physical_regions) {
  266. m_super_physical_pages += region.finalize_capacity();
  267. dmesgln("MM: Super physical region: {} - {}", region.lower(), region.upper());
  268. }
  269. for (auto& region : m_user_physical_regions) {
  270. m_user_physical_pages += region.finalize_capacity();
  271. dmesgln("MM: User physical region: {} - {}", region.lower(), region.upper());
  272. }
  273. VERIFY(m_super_physical_pages > 0);
  274. VERIFY(m_user_physical_pages > 0);
  275. // We start out with no committed pages
  276. m_user_physical_pages_uncommitted = m_user_physical_pages.load();
  277. register_reserved_ranges();
  278. for (auto& range : m_reserved_memory_ranges) {
  279. dmesgln("MM: Contiguous reserved range from {}, length is {}", range.start, range.length);
  280. }
  281. }
  282. PageTableEntry* MemoryManager::pte(PageDirectory& page_directory, VirtualAddress vaddr)
  283. {
  284. VERIFY_INTERRUPTS_DISABLED();
  285. VERIFY(s_mm_lock.own_lock());
  286. VERIFY(page_directory.get_lock().own_lock());
  287. u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
  288. u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
  289. u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
  290. auto* pd = quickmap_pd(const_cast<PageDirectory&>(page_directory), page_directory_table_index);
  291. const PageDirectoryEntry& pde = pd[page_directory_index];
  292. if (!pde.is_present())
  293. return nullptr;
  294. return &quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()))[page_table_index];
  295. }
  296. PageTableEntry* MemoryManager::ensure_pte(PageDirectory& page_directory, VirtualAddress vaddr)
  297. {
  298. VERIFY_INTERRUPTS_DISABLED();
  299. VERIFY(s_mm_lock.own_lock());
  300. VERIFY(page_directory.get_lock().own_lock());
  301. u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
  302. u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
  303. u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
  304. auto* pd = quickmap_pd(page_directory, page_directory_table_index);
  305. PageDirectoryEntry& pde = pd[page_directory_index];
  306. if (!pde.is_present()) {
  307. bool did_purge = false;
  308. auto page_table = allocate_user_physical_page(ShouldZeroFill::Yes, &did_purge);
  309. if (!page_table) {
  310. dbgln("MM: Unable to allocate page table to map {}", vaddr);
  311. return nullptr;
  312. }
  313. if (did_purge) {
  314. // If any memory had to be purged, ensure_pte may have been called as part
  315. // of the purging process. So we need to re-map the pd in this case to ensure
  316. // we're writing to the correct underlying physical page
  317. pd = quickmap_pd(page_directory, page_directory_table_index);
  318. VERIFY(&pde == &pd[page_directory_index]); // Sanity check
  319. VERIFY(!pde.is_present()); // Should have not changed
  320. }
  321. pde.set_page_table_base(page_table->paddr().get());
  322. pde.set_user_allowed(true);
  323. pde.set_present(true);
  324. pde.set_writable(true);
  325. pde.set_global(&page_directory == m_kernel_page_directory.ptr());
  326. // Use page_directory_table_index and page_directory_index as key
  327. // This allows us to release the page table entry when no longer needed
  328. auto result = page_directory.m_page_tables.set(vaddr.get() & ~0x1fffff, move(page_table));
  329. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  330. }
  331. return &quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()))[page_table_index];
  332. }
  333. void MemoryManager::release_pte(PageDirectory& page_directory, VirtualAddress vaddr, bool is_last_release)
  334. {
  335. VERIFY_INTERRUPTS_DISABLED();
  336. VERIFY(s_mm_lock.own_lock());
  337. VERIFY(page_directory.get_lock().own_lock());
  338. u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
  339. u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
  340. u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
  341. auto* pd = quickmap_pd(page_directory, page_directory_table_index);
  342. PageDirectoryEntry& pde = pd[page_directory_index];
  343. if (pde.is_present()) {
  344. auto* page_table = quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()));
  345. auto& pte = page_table[page_table_index];
  346. pte.clear();
  347. if (is_last_release || page_table_index == 0x1ff) {
  348. // If this is the last PTE in a region or the last PTE in a page table then
  349. // check if we can also release the page table
  350. bool all_clear = true;
  351. for (u32 i = 0; i <= 0x1ff; i++) {
  352. if (!page_table[i].is_null()) {
  353. all_clear = false;
  354. break;
  355. }
  356. }
  357. if (all_clear) {
  358. pde.clear();
  359. auto result = page_directory.m_page_tables.remove(vaddr.get() & ~0x1fffff);
  360. VERIFY(result);
  361. }
  362. }
  363. }
  364. }
  365. UNMAP_AFTER_INIT void MemoryManager::initialize(u32 cpu)
  366. {
  367. auto mm_data = new MemoryManagerData;
  368. Processor::current().set_mm_data(*mm_data);
  369. if (cpu == 0) {
  370. s_the = new MemoryManager;
  371. kmalloc_enable_expand();
  372. }
  373. }
  374. Region* MemoryManager::kernel_region_from_vaddr(VirtualAddress vaddr)
  375. {
  376. ScopedSpinLock lock(s_mm_lock);
  377. for (auto& region : MM.m_kernel_regions) {
  378. if (region.contains(vaddr))
  379. return &region;
  380. }
  381. return nullptr;
  382. }
  383. Region* MemoryManager::user_region_from_vaddr(Space& space, VirtualAddress vaddr)
  384. {
  385. // FIXME: Use a binary search tree (maybe red/black?) or some other more appropriate data structure!
  386. ScopedSpinLock lock(space.get_lock());
  387. for (auto& region : space.regions()) {
  388. if (region.contains(vaddr))
  389. return &region;
  390. }
  391. return nullptr;
  392. }
  393. Region* MemoryManager::find_region_from_vaddr(Space& space, VirtualAddress vaddr)
  394. {
  395. ScopedSpinLock lock(s_mm_lock);
  396. if (auto* region = user_region_from_vaddr(space, vaddr))
  397. return region;
  398. return kernel_region_from_vaddr(vaddr);
  399. }
  400. Region* MemoryManager::find_region_from_vaddr(VirtualAddress vaddr)
  401. {
  402. ScopedSpinLock lock(s_mm_lock);
  403. if (auto* region = kernel_region_from_vaddr(vaddr))
  404. return region;
  405. auto page_directory = PageDirectory::find_by_cr3(read_cr3());
  406. if (!page_directory)
  407. return nullptr;
  408. VERIFY(page_directory->space());
  409. return user_region_from_vaddr(*page_directory->space(), vaddr);
  410. }
  411. PageFaultResponse MemoryManager::handle_page_fault(const PageFault& fault)
  412. {
  413. VERIFY_INTERRUPTS_DISABLED();
  414. ScopedSpinLock lock(s_mm_lock);
  415. if (Processor::current().in_irq()) {
  416. dbgln("CPU[{}] BUG! Page fault while handling IRQ! code={}, vaddr={}, irq level: {}",
  417. Processor::id(), fault.code(), fault.vaddr(), Processor::current().in_irq());
  418. dump_kernel_regions();
  419. return PageFaultResponse::ShouldCrash;
  420. }
  421. #if PAGE_FAULT_DEBUG
  422. dbgln("MM: CPU[{}] handle_page_fault({:#04x}) at {}", Processor::id(), fault.code(), fault.vaddr());
  423. #endif
  424. auto* region = find_region_from_vaddr(fault.vaddr());
  425. if (!region) {
  426. dmesgln("CPU[{}] NP(error) fault at invalid address {}", Processor::id(), fault.vaddr());
  427. return PageFaultResponse::ShouldCrash;
  428. }
  429. return region->handle_fault(fault, lock);
  430. }
  431. OwnPtr<Region> MemoryManager::allocate_contiguous_kernel_region(size_t size, String name, Region::Access access, size_t physical_alignment, Region::Cacheable cacheable)
  432. {
  433. VERIFY(!(size % PAGE_SIZE));
  434. ScopedSpinLock lock(s_mm_lock);
  435. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  436. if (!range.has_value())
  437. return {};
  438. auto vmobject = ContiguousVMObject::create_with_size(size, physical_alignment);
  439. return allocate_kernel_region_with_vmobject(range.value(), vmobject, move(name), access, cacheable);
  440. }
  441. OwnPtr<Region> MemoryManager::allocate_kernel_region(size_t size, String name, Region::Access access, AllocationStrategy strategy, Region::Cacheable cacheable)
  442. {
  443. VERIFY(!(size % PAGE_SIZE));
  444. ScopedSpinLock lock(s_mm_lock);
  445. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  446. if (!range.has_value())
  447. return {};
  448. auto vmobject = AnonymousVMObject::create_with_size(size, strategy);
  449. if (!vmobject)
  450. return {};
  451. return allocate_kernel_region_with_vmobject(range.value(), vmobject.release_nonnull(), move(name), access, cacheable);
  452. }
  453. OwnPtr<Region> MemoryManager::allocate_kernel_region(PhysicalAddress paddr, size_t size, String name, Region::Access access, Region::Cacheable cacheable)
  454. {
  455. VERIFY(!(size % PAGE_SIZE));
  456. ScopedSpinLock lock(s_mm_lock);
  457. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  458. if (!range.has_value())
  459. return {};
  460. auto vmobject = AnonymousVMObject::create_for_physical_range(paddr, size);
  461. if (!vmobject)
  462. return {};
  463. return allocate_kernel_region_with_vmobject(range.value(), *vmobject, move(name), access, cacheable);
  464. }
  465. OwnPtr<Region> MemoryManager::allocate_kernel_region_identity(PhysicalAddress paddr, size_t size, String name, Region::Access access, Region::Cacheable cacheable)
  466. {
  467. VERIFY(!(size % PAGE_SIZE));
  468. ScopedSpinLock lock(s_mm_lock);
  469. auto range = kernel_page_directory().identity_range_allocator().allocate_specific(VirtualAddress(paddr.get()), size);
  470. if (!range.has_value())
  471. return {};
  472. auto vmobject = AnonymousVMObject::create_for_physical_range(paddr, size);
  473. if (!vmobject)
  474. return {};
  475. return allocate_kernel_region_with_vmobject(range.value(), *vmobject, move(name), access, cacheable);
  476. }
  477. OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(const Range& range, VMObject& vmobject, String name, Region::Access access, Region::Cacheable cacheable)
  478. {
  479. ScopedSpinLock lock(s_mm_lock);
  480. auto region = Region::create_kernel_only(range, vmobject, 0, move(name), access, cacheable);
  481. if (region)
  482. region->map(kernel_page_directory());
  483. return region;
  484. }
  485. OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(VMObject& vmobject, size_t size, String name, Region::Access access, Region::Cacheable cacheable)
  486. {
  487. VERIFY(!(size % PAGE_SIZE));
  488. ScopedSpinLock lock(s_mm_lock);
  489. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  490. if (!range.has_value())
  491. return {};
  492. return allocate_kernel_region_with_vmobject(range.value(), vmobject, move(name), access, cacheable);
  493. }
  494. bool MemoryManager::commit_user_physical_pages(size_t page_count)
  495. {
  496. VERIFY(page_count > 0);
  497. ScopedSpinLock lock(s_mm_lock);
  498. if (m_user_physical_pages_uncommitted < page_count)
  499. return false;
  500. m_user_physical_pages_uncommitted -= page_count;
  501. m_user_physical_pages_committed += page_count;
  502. return true;
  503. }
  504. void MemoryManager::uncommit_user_physical_pages(size_t page_count)
  505. {
  506. VERIFY(page_count > 0);
  507. ScopedSpinLock lock(s_mm_lock);
  508. VERIFY(m_user_physical_pages_committed >= page_count);
  509. m_user_physical_pages_uncommitted += page_count;
  510. m_user_physical_pages_committed -= page_count;
  511. }
  512. void MemoryManager::deallocate_user_physical_page(const PhysicalPage& page)
  513. {
  514. ScopedSpinLock lock(s_mm_lock);
  515. for (auto& region : m_user_physical_regions) {
  516. if (!region.contains(page))
  517. continue;
  518. region.return_page(page);
  519. --m_user_physical_pages_used;
  520. // Always return pages to the uncommitted pool. Pages that were
  521. // committed and allocated are only freed upon request. Once
  522. // returned there is no guarantee being able to get them back.
  523. ++m_user_physical_pages_uncommitted;
  524. return;
  525. }
  526. dmesgln("MM: deallocate_user_physical_page couldn't figure out region for user page @ {}", page.paddr());
  527. VERIFY_NOT_REACHED();
  528. }
  529. RefPtr<PhysicalPage> MemoryManager::find_free_user_physical_page(bool committed)
  530. {
  531. VERIFY(s_mm_lock.is_locked());
  532. RefPtr<PhysicalPage> page;
  533. if (committed) {
  534. // Draw from the committed pages pool. We should always have these pages available
  535. VERIFY(m_user_physical_pages_committed > 0);
  536. m_user_physical_pages_committed--;
  537. } else {
  538. // We need to make sure we don't touch pages that we have committed to
  539. if (m_user_physical_pages_uncommitted == 0)
  540. return {};
  541. m_user_physical_pages_uncommitted--;
  542. }
  543. for (auto& region : m_user_physical_regions) {
  544. page = region.take_free_page(false);
  545. if (!page.is_null()) {
  546. ++m_user_physical_pages_used;
  547. break;
  548. }
  549. }
  550. VERIFY(!committed || !page.is_null());
  551. return page;
  552. }
  553. NonnullRefPtr<PhysicalPage> MemoryManager::allocate_committed_user_physical_page(ShouldZeroFill should_zero_fill)
  554. {
  555. ScopedSpinLock lock(s_mm_lock);
  556. auto page = find_free_user_physical_page(true);
  557. if (should_zero_fill == ShouldZeroFill::Yes) {
  558. auto* ptr = quickmap_page(*page);
  559. memset(ptr, 0, PAGE_SIZE);
  560. unquickmap_page();
  561. }
  562. return page.release_nonnull();
  563. }
  564. RefPtr<PhysicalPage> MemoryManager::allocate_user_physical_page(ShouldZeroFill should_zero_fill, bool* did_purge)
  565. {
  566. ScopedSpinLock lock(s_mm_lock);
  567. auto page = find_free_user_physical_page(false);
  568. bool purged_pages = false;
  569. if (!page) {
  570. // We didn't have a single free physical page. Let's try to free something up!
  571. // First, we look for a purgeable VMObject in the volatile state.
  572. for_each_vmobject([&](auto& vmobject) {
  573. if (!vmobject.is_anonymous())
  574. return IterationDecision::Continue;
  575. int purged_page_count = static_cast<AnonymousVMObject&>(vmobject).purge_with_interrupts_disabled({});
  576. if (purged_page_count) {
  577. dbgln("MM: Purge saved the day! Purged {} pages from AnonymousVMObject", purged_page_count);
  578. page = find_free_user_physical_page(false);
  579. purged_pages = true;
  580. VERIFY(page);
  581. return IterationDecision::Break;
  582. }
  583. return IterationDecision::Continue;
  584. });
  585. if (!page) {
  586. dmesgln("MM: no user physical pages available");
  587. return {};
  588. }
  589. }
  590. if (should_zero_fill == ShouldZeroFill::Yes) {
  591. auto* ptr = quickmap_page(*page);
  592. memset(ptr, 0, PAGE_SIZE);
  593. unquickmap_page();
  594. }
  595. if (did_purge)
  596. *did_purge = purged_pages;
  597. return page;
  598. }
  599. void MemoryManager::deallocate_supervisor_physical_page(const PhysicalPage& page)
  600. {
  601. ScopedSpinLock lock(s_mm_lock);
  602. for (auto& region : m_super_physical_regions) {
  603. if (!region.contains(page)) {
  604. dbgln("MM: deallocate_supervisor_physical_page: {} not in {} - {}", page.paddr(), region.lower(), region.upper());
  605. continue;
  606. }
  607. region.return_page(page);
  608. --m_super_physical_pages_used;
  609. return;
  610. }
  611. dbgln("MM: deallocate_supervisor_physical_page couldn't figure out region for super page @ {}", page.paddr());
  612. VERIFY_NOT_REACHED();
  613. }
  614. NonnullRefPtrVector<PhysicalPage> MemoryManager::allocate_contiguous_supervisor_physical_pages(size_t size, size_t physical_alignment)
  615. {
  616. VERIFY(!(size % PAGE_SIZE));
  617. ScopedSpinLock lock(s_mm_lock);
  618. size_t count = ceil_div(size, static_cast<size_t>(PAGE_SIZE));
  619. NonnullRefPtrVector<PhysicalPage> physical_pages;
  620. for (auto& region : m_super_physical_regions) {
  621. physical_pages = region.take_contiguous_free_pages(count, true, physical_alignment);
  622. if (!physical_pages.is_empty())
  623. continue;
  624. }
  625. if (physical_pages.is_empty()) {
  626. if (m_super_physical_regions.is_empty()) {
  627. dmesgln("MM: no super physical regions available (?)");
  628. }
  629. dmesgln("MM: no super physical pages available");
  630. VERIFY_NOT_REACHED();
  631. return {};
  632. }
  633. auto cleanup_region = MM.allocate_kernel_region(physical_pages[0].paddr(), PAGE_SIZE * count, "MemoryManager Allocation Sanitization", Region::Access::Read | Region::Access::Write);
  634. fast_u32_fill((u32*)cleanup_region->vaddr().as_ptr(), 0, (PAGE_SIZE * count) / sizeof(u32));
  635. m_super_physical_pages_used += count;
  636. return physical_pages;
  637. }
  638. RefPtr<PhysicalPage> MemoryManager::allocate_supervisor_physical_page()
  639. {
  640. ScopedSpinLock lock(s_mm_lock);
  641. RefPtr<PhysicalPage> page;
  642. for (auto& region : m_super_physical_regions) {
  643. page = region.take_free_page(true);
  644. if (!page.is_null())
  645. break;
  646. }
  647. if (!page) {
  648. if (m_super_physical_regions.is_empty()) {
  649. dmesgln("MM: no super physical regions available (?)");
  650. }
  651. dmesgln("MM: no super physical pages available");
  652. VERIFY_NOT_REACHED();
  653. return {};
  654. }
  655. fast_u32_fill((u32*)page->paddr().offset(0xc0000000).as_ptr(), 0, PAGE_SIZE / sizeof(u32));
  656. ++m_super_physical_pages_used;
  657. return page;
  658. }
  659. void MemoryManager::enter_process_paging_scope(Process& process)
  660. {
  661. enter_space(process.space());
  662. }
  663. void MemoryManager::enter_space(Space& space)
  664. {
  665. auto current_thread = Thread::current();
  666. VERIFY(current_thread != nullptr);
  667. ScopedSpinLock lock(s_mm_lock);
  668. current_thread->tss().cr3 = space.page_directory().cr3();
  669. write_cr3(space.page_directory().cr3());
  670. }
  671. void MemoryManager::flush_tlb_local(VirtualAddress vaddr, size_t page_count)
  672. {
  673. Processor::flush_tlb_local(vaddr, page_count);
  674. }
  675. void MemoryManager::flush_tlb(const PageDirectory* page_directory, VirtualAddress vaddr, size_t page_count)
  676. {
  677. Processor::flush_tlb(page_directory, vaddr, page_count);
  678. }
  679. extern "C" PageTableEntry boot_pd3_pt1023[1024];
  680. PageDirectoryEntry* MemoryManager::quickmap_pd(PageDirectory& directory, size_t pdpt_index)
  681. {
  682. VERIFY(s_mm_lock.own_lock());
  683. auto& mm_data = get_data();
  684. auto& pte = boot_pd3_pt1023[4];
  685. auto pd_paddr = directory.m_directory_pages[pdpt_index]->paddr();
  686. if (pte.physical_page_base() != pd_paddr.as_ptr()) {
  687. pte.set_physical_page_base(pd_paddr.get());
  688. pte.set_present(true);
  689. pte.set_writable(true);
  690. pte.set_user_allowed(false);
  691. // Because we must continue to hold the MM lock while we use this
  692. // mapping, it is sufficient to only flush on the current CPU. Other
  693. // CPUs trying to use this API must wait on the MM lock anyway
  694. flush_tlb_local(VirtualAddress(0xffe04000));
  695. } else {
  696. // Even though we don't allow this to be called concurrently, it's
  697. // possible that this PD was mapped on a different CPU and we don't
  698. // broadcast the flush. If so, we still need to flush the TLB.
  699. if (mm_data.m_last_quickmap_pd != pd_paddr)
  700. flush_tlb_local(VirtualAddress(0xffe04000));
  701. }
  702. mm_data.m_last_quickmap_pd = pd_paddr;
  703. return (PageDirectoryEntry*)0xffe04000;
  704. }
  705. PageTableEntry* MemoryManager::quickmap_pt(PhysicalAddress pt_paddr)
  706. {
  707. VERIFY(s_mm_lock.own_lock());
  708. auto& mm_data = get_data();
  709. auto& pte = boot_pd3_pt1023[0];
  710. if (pte.physical_page_base() != pt_paddr.as_ptr()) {
  711. pte.set_physical_page_base(pt_paddr.get());
  712. pte.set_present(true);
  713. pte.set_writable(true);
  714. pte.set_user_allowed(false);
  715. // Because we must continue to hold the MM lock while we use this
  716. // mapping, it is sufficient to only flush on the current CPU. Other
  717. // CPUs trying to use this API must wait on the MM lock anyway
  718. flush_tlb_local(VirtualAddress(0xffe00000));
  719. } else {
  720. // Even though we don't allow this to be called concurrently, it's
  721. // possible that this PT was mapped on a different CPU and we don't
  722. // broadcast the flush. If so, we still need to flush the TLB.
  723. if (mm_data.m_last_quickmap_pt != pt_paddr)
  724. flush_tlb_local(VirtualAddress(0xffe00000));
  725. }
  726. mm_data.m_last_quickmap_pt = pt_paddr;
  727. return (PageTableEntry*)0xffe00000;
  728. }
  729. u8* MemoryManager::quickmap_page(PhysicalPage& physical_page)
  730. {
  731. VERIFY_INTERRUPTS_DISABLED();
  732. auto& mm_data = get_data();
  733. mm_data.m_quickmap_prev_flags = mm_data.m_quickmap_in_use.lock();
  734. ScopedSpinLock lock(s_mm_lock);
  735. u32 pte_idx = 8 + Processor::id();
  736. VirtualAddress vaddr(0xffe00000 + pte_idx * PAGE_SIZE);
  737. auto& pte = boot_pd3_pt1023[pte_idx];
  738. if (pte.physical_page_base() != physical_page.paddr().as_ptr()) {
  739. pte.set_physical_page_base(physical_page.paddr().get());
  740. pte.set_present(true);
  741. pte.set_writable(true);
  742. pte.set_user_allowed(false);
  743. flush_tlb_local(vaddr);
  744. }
  745. return vaddr.as_ptr();
  746. }
  747. void MemoryManager::unquickmap_page()
  748. {
  749. VERIFY_INTERRUPTS_DISABLED();
  750. ScopedSpinLock lock(s_mm_lock);
  751. auto& mm_data = get_data();
  752. VERIFY(mm_data.m_quickmap_in_use.is_locked());
  753. u32 pte_idx = 8 + Processor::id();
  754. VirtualAddress vaddr(0xffe00000 + pte_idx * PAGE_SIZE);
  755. auto& pte = boot_pd3_pt1023[pte_idx];
  756. pte.clear();
  757. flush_tlb_local(vaddr);
  758. mm_data.m_quickmap_in_use.unlock(mm_data.m_quickmap_prev_flags);
  759. }
  760. bool MemoryManager::validate_user_stack(const Process& process, VirtualAddress vaddr) const
  761. {
  762. if (!is_user_address(vaddr))
  763. return false;
  764. ScopedSpinLock lock(s_mm_lock);
  765. auto* region = user_region_from_vaddr(const_cast<Process&>(process).space(), vaddr);
  766. return region && region->is_user() && region->is_stack();
  767. }
  768. void MemoryManager::register_vmobject(VMObject& vmobject)
  769. {
  770. ScopedSpinLock lock(s_mm_lock);
  771. m_vmobjects.append(&vmobject);
  772. }
  773. void MemoryManager::unregister_vmobject(VMObject& vmobject)
  774. {
  775. ScopedSpinLock lock(s_mm_lock);
  776. m_vmobjects.remove(&vmobject);
  777. }
  778. void MemoryManager::register_region(Region& region)
  779. {
  780. ScopedSpinLock lock(s_mm_lock);
  781. if (region.is_kernel())
  782. m_kernel_regions.append(&region);
  783. else
  784. m_user_regions.append(&region);
  785. }
  786. void MemoryManager::unregister_region(Region& region)
  787. {
  788. ScopedSpinLock lock(s_mm_lock);
  789. if (region.is_kernel())
  790. m_kernel_regions.remove(&region);
  791. else
  792. m_user_regions.remove(&region);
  793. }
  794. void MemoryManager::dump_kernel_regions()
  795. {
  796. dbgln("Kernel regions:");
  797. dbgln("BEGIN END SIZE ACCESS NAME");
  798. ScopedSpinLock lock(s_mm_lock);
  799. for (auto& region : m_kernel_regions) {
  800. dbgln("{:08x} -- {:08x} {:08x} {:c}{:c}{:c}{:c}{:c}{:c} {}",
  801. region.vaddr().get(),
  802. region.vaddr().offset(region.size() - 1).get(),
  803. region.size(),
  804. region.is_readable() ? 'R' : ' ',
  805. region.is_writable() ? 'W' : ' ',
  806. region.is_executable() ? 'X' : ' ',
  807. region.is_shared() ? 'S' : ' ',
  808. region.is_stack() ? 'T' : ' ',
  809. region.is_syscall_region() ? 'C' : ' ',
  810. region.name());
  811. }
  812. }
  813. }