MemoryManager.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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 multiboot_module_entry_t multiboot_copy_boot_modules_array[16];
  48. extern size_t multiboot_copy_boot_modules_count;
  49. // Treat the super pages as logically separate from .bss
  50. __attribute__((section(".super_pages"))) static u8 super_pages[1 * MiB];
  51. namespace Kernel {
  52. // NOTE: We can NOT use AK::Singleton for this class, because
  53. // MemoryManager::initialize is called *before* global constructors are
  54. // run. If we do, then AK::Singleton would get re-initialized, causing
  55. // the memory manager to be initialized twice!
  56. static MemoryManager* s_the;
  57. RecursiveSpinLock s_mm_lock;
  58. const LogStream& operator<<(const LogStream& stream, const UsedMemoryRange& value)
  59. {
  60. return stream << UserMemoryRangeTypeNames[static_cast<int>(value.type)] << " range @ " << value.start << " - " << value.end;
  61. }
  62. MemoryManager& MM
  63. {
  64. return *s_the;
  65. }
  66. bool MemoryManager::is_initialized()
  67. {
  68. return s_the != nullptr;
  69. }
  70. MemoryManager::MemoryManager()
  71. {
  72. ScopedSpinLock lock(s_mm_lock);
  73. m_kernel_page_directory = PageDirectory::create_kernel_page_directory();
  74. parse_memory_map();
  75. write_cr3(kernel_page_directory().cr3());
  76. protect_kernel_image();
  77. // We're temporarily "committing" to two pages that we need to allocate below
  78. if (!commit_user_physical_pages(2))
  79. ASSERT_NOT_REACHED();
  80. m_shared_zero_page = allocate_committed_user_physical_page();
  81. // We're wasting a page here, we just need a special tag (physical
  82. // address) so that we know when we need to lazily allocate a page
  83. // that we should be drawing this page from the committed pool rather
  84. // than potentially failing if no pages are available anymore.
  85. // By using a tag we don't have to query the VMObject for every page
  86. // whether it was committed or not
  87. m_lazy_committed_page = allocate_committed_user_physical_page();
  88. }
  89. MemoryManager::~MemoryManager()
  90. {
  91. }
  92. void MemoryManager::protect_kernel_image()
  93. {
  94. ScopedSpinLock page_lock(kernel_page_directory().get_lock());
  95. // Disable writing to the kernel text and rodata segments.
  96. for (size_t i = (FlatPtr)&start_of_kernel_text; i < (FlatPtr)&start_of_kernel_data; i += PAGE_SIZE) {
  97. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  98. pte.set_writable(false);
  99. }
  100. if (Processor::current().has_feature(CPUFeature::NX)) {
  101. // Disable execution of the kernel data, bss and heap segments.
  102. for (size_t i = (FlatPtr)&start_of_kernel_data; i < (FlatPtr)&end_of_kernel_image; i += PAGE_SIZE) {
  103. auto& pte = *ensure_pte(kernel_page_directory(), VirtualAddress(i));
  104. pte.set_execute_disabled(true);
  105. }
  106. }
  107. }
  108. void MemoryManager::parse_memory_map()
  109. {
  110. RefPtr<PhysicalRegion> region;
  111. // Register used memory regions that we know of.
  112. m_used_memory_ranges.ensure_capacity(4);
  113. m_used_memory_ranges.append(UsedMemoryRange { UsedMemoryRangeType::LowMemory, PhysicalAddress(0x00000000), PhysicalAddress(1 * MiB) });
  114. 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)))) });
  115. if (multiboot_info_ptr->flags & 0x4) {
  116. auto* bootmods_start = multiboot_copy_boot_modules_array;
  117. auto* bootmods_end = bootmods_start + multiboot_copy_boot_modules_count;
  118. for (auto* bootmod = bootmods_start; bootmod < bootmods_end; bootmod++) {
  119. m_used_memory_ranges.append(UsedMemoryRange { UsedMemoryRangeType::BootModule, PhysicalAddress(bootmod->start), PhysicalAddress(bootmod->end) });
  120. }
  121. }
  122. auto* mmap_begin = reinterpret_cast<multiboot_memory_map_t*>(low_physical_to_virtual(multiboot_info_ptr->mmap_addr));
  123. auto* mmap_end = reinterpret_cast<multiboot_memory_map_t*>(low_physical_to_virtual(multiboot_info_ptr->mmap_addr) + multiboot_info_ptr->mmap_length);
  124. for (auto used_range : m_used_memory_ranges) {
  125. klog() << "MM: " << used_range;
  126. }
  127. for (auto* mmap = mmap_begin; mmap < mmap_end; mmap++) {
  128. klog() << "MM: Multiboot mmap: address = " << String::format("0x%016llx", mmap->addr) << ", length = " << String::format("0x%016llx", mmap->len) << ", type = 0x" << String::format("%x", mmap->type);
  129. if (mmap->type != MULTIBOOT_MEMORY_AVAILABLE)
  130. continue;
  131. if ((mmap->addr + mmap->len) > 0xffffffff)
  132. continue;
  133. // Fix up unaligned memory regions.
  134. auto diff = (FlatPtr)mmap->addr % PAGE_SIZE;
  135. if (diff != 0) {
  136. klog() << "MM: got an unaligned region base from the bootloader; correcting " << String::format("%p", (void*)mmap->addr) << " by " << diff << " bytes";
  137. diff = PAGE_SIZE - diff;
  138. mmap->addr += diff;
  139. mmap->len -= diff;
  140. }
  141. if ((mmap->len % PAGE_SIZE) != 0) {
  142. klog() << "MM: got an unaligned region length from the bootloader; correcting " << mmap->len << " by " << (mmap->len % PAGE_SIZE) << " bytes";
  143. mmap->len -= mmap->len % PAGE_SIZE;
  144. }
  145. if (mmap->len < PAGE_SIZE) {
  146. klog() << "MM: memory region from bootloader is too small; we want >= " << PAGE_SIZE << " bytes, but got " << mmap->len << " bytes";
  147. continue;
  148. }
  149. for (size_t page_base = mmap->addr; page_base <= (mmap->addr + mmap->len); page_base += PAGE_SIZE) {
  150. auto addr = PhysicalAddress(page_base);
  151. // Skip used memory ranges.
  152. bool should_skip = false;
  153. for (auto used_range : m_used_memory_ranges) {
  154. if (addr.get() >= used_range.start.get() && addr.get() <= used_range.end.get()) {
  155. should_skip = true;
  156. break;
  157. }
  158. }
  159. if (should_skip)
  160. continue;
  161. // Assign page to user physical region.
  162. if (region.is_null() || region->upper().offset(PAGE_SIZE) != addr) {
  163. m_user_physical_regions.append(PhysicalRegion::create(addr, addr));
  164. region = m_user_physical_regions.last();
  165. } else {
  166. region->expand(region->lower(), addr);
  167. }
  168. }
  169. }
  170. // Append statically-allocated super physical region.
  171. m_super_physical_regions.append(PhysicalRegion::create(
  172. PhysicalAddress(virtual_to_low_physical(FlatPtr(super_pages))),
  173. PhysicalAddress(virtual_to_low_physical(FlatPtr(super_pages + sizeof(super_pages))))));
  174. for (auto& region : m_super_physical_regions) {
  175. m_super_physical_pages += region.finalize_capacity();
  176. klog() << "MM: Super physical region: " << region.lower() << " - " << region.upper();
  177. }
  178. for (auto& region : m_user_physical_regions) {
  179. m_user_physical_pages += region.finalize_capacity();
  180. klog() << "MM: User physical region: " << region.lower() << " - " << region.upper();
  181. }
  182. ASSERT(m_super_physical_pages > 0);
  183. ASSERT(m_user_physical_pages > 0);
  184. // We start out with no committed pages
  185. m_user_physical_pages_uncommitted = m_user_physical_pages.load();
  186. }
  187. PageTableEntry* MemoryManager::pte(PageDirectory& page_directory, VirtualAddress vaddr)
  188. {
  189. ASSERT_INTERRUPTS_DISABLED();
  190. ASSERT(s_mm_lock.own_lock());
  191. ASSERT(page_directory.get_lock().own_lock());
  192. u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
  193. u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
  194. u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
  195. auto* pd = quickmap_pd(const_cast<PageDirectory&>(page_directory), page_directory_table_index);
  196. const PageDirectoryEntry& pde = pd[page_directory_index];
  197. if (!pde.is_present())
  198. return nullptr;
  199. return &quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()))[page_table_index];
  200. }
  201. PageTableEntry* MemoryManager::ensure_pte(PageDirectory& page_directory, VirtualAddress vaddr)
  202. {
  203. ASSERT_INTERRUPTS_DISABLED();
  204. ASSERT(s_mm_lock.own_lock());
  205. ASSERT(page_directory.get_lock().own_lock());
  206. u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
  207. u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
  208. u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
  209. auto* pd = quickmap_pd(page_directory, page_directory_table_index);
  210. PageDirectoryEntry& pde = pd[page_directory_index];
  211. if (!pde.is_present()) {
  212. bool did_purge = false;
  213. auto page_table = allocate_user_physical_page(ShouldZeroFill::Yes, &did_purge);
  214. if (!page_table) {
  215. dbgln("MM: Unable to allocate page table to map {}", vaddr);
  216. return nullptr;
  217. }
  218. if (did_purge) {
  219. // If any memory had to be purged, ensure_pte may have been called as part
  220. // of the purging process. So we need to re-map the pd in this case to ensure
  221. // we're writing to the correct underlying physical page
  222. pd = quickmap_pd(page_directory, page_directory_table_index);
  223. ASSERT(&pde == &pd[page_directory_index]); // Sanity check
  224. ASSERT(!pde.is_present()); // Should have not changed
  225. }
  226. pde.set_page_table_base(page_table->paddr().get());
  227. pde.set_user_allowed(true);
  228. pde.set_present(true);
  229. pde.set_writable(true);
  230. pde.set_global(&page_directory == m_kernel_page_directory.ptr());
  231. // Use page_directory_table_index and page_directory_index as key
  232. // This allows us to release the page table entry when no longer needed
  233. auto result = page_directory.m_page_tables.set(vaddr.get() & ~0x1fffff, move(page_table));
  234. ASSERT(result == AK::HashSetResult::InsertedNewEntry);
  235. }
  236. return &quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()))[page_table_index];
  237. }
  238. void MemoryManager::release_pte(PageDirectory& page_directory, VirtualAddress vaddr, bool is_last_release)
  239. {
  240. ASSERT_INTERRUPTS_DISABLED();
  241. ASSERT(s_mm_lock.own_lock());
  242. ASSERT(page_directory.get_lock().own_lock());
  243. u32 page_directory_table_index = (vaddr.get() >> 30) & 0x3;
  244. u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff;
  245. u32 page_table_index = (vaddr.get() >> 12) & 0x1ff;
  246. auto* pd = quickmap_pd(page_directory, page_directory_table_index);
  247. PageDirectoryEntry& pde = pd[page_directory_index];
  248. if (pde.is_present()) {
  249. auto* page_table = quickmap_pt(PhysicalAddress((FlatPtr)pde.page_table_base()));
  250. auto& pte = page_table[page_table_index];
  251. pte.clear();
  252. if (is_last_release || page_table_index == 0x1ff) {
  253. // If this is the last PTE in a region or the last PTE in a page table then
  254. // check if we can also release the page table
  255. bool all_clear = true;
  256. for (u32 i = 0; i <= 0x1ff; i++) {
  257. if (!page_table[i].is_null()) {
  258. all_clear = false;
  259. break;
  260. }
  261. }
  262. if (all_clear) {
  263. pde.clear();
  264. auto result = page_directory.m_page_tables.remove(vaddr.get() & ~0x1fffff);
  265. ASSERT(result);
  266. }
  267. }
  268. }
  269. }
  270. void MemoryManager::initialize(u32 cpu)
  271. {
  272. auto mm_data = new MemoryManagerData;
  273. Processor::current().set_mm_data(*mm_data);
  274. if (cpu == 0) {
  275. s_the = new MemoryManager;
  276. kmalloc_enable_expand();
  277. }
  278. }
  279. Region* MemoryManager::kernel_region_from_vaddr(VirtualAddress vaddr)
  280. {
  281. ScopedSpinLock lock(s_mm_lock);
  282. for (auto& region : MM.m_kernel_regions) {
  283. if (region.contains(vaddr))
  284. return &region;
  285. }
  286. return nullptr;
  287. }
  288. Region* MemoryManager::user_region_from_vaddr(Process& process, VirtualAddress vaddr)
  289. {
  290. ScopedSpinLock lock(s_mm_lock);
  291. // FIXME: Use a binary search tree (maybe red/black?) or some other more appropriate data structure!
  292. for (auto& region : process.m_regions) {
  293. if (region.contains(vaddr))
  294. return &region;
  295. }
  296. return nullptr;
  297. }
  298. Region* MemoryManager::find_region_from_vaddr(Process& process, VirtualAddress vaddr)
  299. {
  300. ScopedSpinLock lock(s_mm_lock);
  301. if (auto* region = user_region_from_vaddr(process, vaddr))
  302. return region;
  303. return kernel_region_from_vaddr(vaddr);
  304. }
  305. const Region* MemoryManager::find_region_from_vaddr(const Process& process, VirtualAddress vaddr)
  306. {
  307. ScopedSpinLock lock(s_mm_lock);
  308. if (auto* region = user_region_from_vaddr(const_cast<Process&>(process), vaddr))
  309. return region;
  310. return kernel_region_from_vaddr(vaddr);
  311. }
  312. Region* MemoryManager::find_region_from_vaddr(VirtualAddress vaddr)
  313. {
  314. ScopedSpinLock lock(s_mm_lock);
  315. if (auto* region = kernel_region_from_vaddr(vaddr))
  316. return region;
  317. auto page_directory = PageDirectory::find_by_cr3(read_cr3());
  318. if (!page_directory)
  319. return nullptr;
  320. ASSERT(page_directory->process());
  321. return user_region_from_vaddr(*page_directory->process(), vaddr);
  322. }
  323. PageFaultResponse MemoryManager::handle_page_fault(const PageFault& fault)
  324. {
  325. ASSERT_INTERRUPTS_DISABLED();
  326. ScopedSpinLock lock(s_mm_lock);
  327. if (Processor::current().in_irq()) {
  328. dbgln("CPU[{}] BUG! Page fault while handling IRQ! code={}, vaddr={}, irq level: {}",
  329. Processor::id(), fault.code(), fault.vaddr(), Processor::current().in_irq());
  330. dump_kernel_regions();
  331. return PageFaultResponse::ShouldCrash;
  332. }
  333. #if PAGE_FAULT_DEBUG
  334. dbgln("MM: CPU[{}] handle_page_fault({:#04x}) at {}", Processor::id(), fault.code(), fault.vaddr());
  335. #endif
  336. auto* region = find_region_from_vaddr(fault.vaddr());
  337. if (!region) {
  338. klog() << "CPU[" << Processor::id() << "] NP(error) fault at invalid address " << fault.vaddr();
  339. return PageFaultResponse::ShouldCrash;
  340. }
  341. return region->handle_fault(fault, lock);
  342. }
  343. OwnPtr<Region> MemoryManager::allocate_contiguous_kernel_region(size_t size, const StringView& name, u8 access, size_t physical_alignment, bool user_accessible, bool cacheable)
  344. {
  345. ASSERT(!(size % PAGE_SIZE));
  346. ScopedSpinLock lock(s_mm_lock);
  347. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  348. if (!range.has_value())
  349. return {};
  350. auto vmobject = ContiguousVMObject::create_with_size(size, physical_alignment);
  351. return allocate_kernel_region_with_vmobject(range.value(), vmobject, name, access, user_accessible, cacheable);
  352. }
  353. OwnPtr<Region> MemoryManager::allocate_kernel_region(size_t size, const StringView& name, u8 access, bool user_accessible, AllocationStrategy strategy, bool cacheable)
  354. {
  355. ASSERT(!(size % PAGE_SIZE));
  356. ScopedSpinLock lock(s_mm_lock);
  357. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  358. if (!range.has_value())
  359. return {};
  360. auto vmobject = AnonymousVMObject::create_with_size(size, strategy);
  361. if (!vmobject)
  362. return {};
  363. return allocate_kernel_region_with_vmobject(range.value(), vmobject.release_nonnull(), name, access, user_accessible, cacheable);
  364. }
  365. OwnPtr<Region> MemoryManager::allocate_kernel_region(PhysicalAddress paddr, size_t size, const StringView& name, u8 access, bool user_accessible, bool cacheable)
  366. {
  367. ASSERT(!(size % PAGE_SIZE));
  368. ScopedSpinLock lock(s_mm_lock);
  369. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  370. if (!range.has_value())
  371. return {};
  372. auto vmobject = AnonymousVMObject::create_for_physical_range(paddr, size);
  373. if (!vmobject)
  374. return {};
  375. return allocate_kernel_region_with_vmobject(range.value(), *vmobject, name, access, user_accessible, cacheable);
  376. }
  377. OwnPtr<Region> MemoryManager::allocate_kernel_region_identity(PhysicalAddress paddr, size_t size, const StringView& name, u8 access, bool user_accessible, bool cacheable)
  378. {
  379. ASSERT(!(size % PAGE_SIZE));
  380. ScopedSpinLock lock(s_mm_lock);
  381. auto range = kernel_page_directory().identity_range_allocator().allocate_specific(VirtualAddress(paddr.get()), size);
  382. if (!range.has_value())
  383. return {};
  384. auto vmobject = AnonymousVMObject::create_for_physical_range(paddr, size);
  385. if (!vmobject)
  386. return {};
  387. return allocate_kernel_region_with_vmobject(range.value(), *vmobject, name, access, user_accessible, cacheable);
  388. }
  389. OwnPtr<Region> MemoryManager::allocate_user_accessible_kernel_region(size_t size, const StringView& name, u8 access, bool cacheable)
  390. {
  391. return allocate_kernel_region(size, name, access, true, AllocationStrategy::Reserve, cacheable);
  392. }
  393. OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(const Range& range, VMObject& vmobject, const StringView& name, u8 access, bool user_accessible, bool cacheable)
  394. {
  395. ScopedSpinLock lock(s_mm_lock);
  396. OwnPtr<Region> region;
  397. if (user_accessible)
  398. region = Region::create_user_accessible(nullptr, range, vmobject, 0, name, access, cacheable, false);
  399. else
  400. region = Region::create_kernel_only(range, vmobject, 0, name, access, cacheable);
  401. if (region)
  402. region->map(kernel_page_directory());
  403. return region;
  404. }
  405. OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(VMObject& vmobject, size_t size, const StringView& name, u8 access, bool user_accessible, bool cacheable)
  406. {
  407. ASSERT(!(size % PAGE_SIZE));
  408. ScopedSpinLock lock(s_mm_lock);
  409. auto range = kernel_page_directory().range_allocator().allocate_anywhere(size);
  410. if (!range.has_value())
  411. return {};
  412. return allocate_kernel_region_with_vmobject(range.value(), vmobject, name, access, user_accessible, cacheable);
  413. }
  414. bool MemoryManager::commit_user_physical_pages(size_t page_count)
  415. {
  416. ASSERT(page_count > 0);
  417. ScopedSpinLock lock(s_mm_lock);
  418. if (m_user_physical_pages_uncommitted < page_count)
  419. return false;
  420. m_user_physical_pages_uncommitted -= page_count;
  421. m_user_physical_pages_committed += page_count;
  422. return true;
  423. }
  424. void MemoryManager::uncommit_user_physical_pages(size_t page_count)
  425. {
  426. ASSERT(page_count > 0);
  427. ScopedSpinLock lock(s_mm_lock);
  428. ASSERT(m_user_physical_pages_committed >= page_count);
  429. m_user_physical_pages_uncommitted += page_count;
  430. m_user_physical_pages_committed -= page_count;
  431. }
  432. void MemoryManager::deallocate_user_physical_page(const PhysicalPage& page)
  433. {
  434. ScopedSpinLock lock(s_mm_lock);
  435. for (auto& region : m_user_physical_regions) {
  436. if (!region.contains(page))
  437. continue;
  438. region.return_page(page);
  439. --m_user_physical_pages_used;
  440. // Always return pages to the uncommitted pool. Pages that were
  441. // committed and allocated are only freed upon request. Once
  442. // returned there is no guarantee being able to get them back.
  443. ++m_user_physical_pages_uncommitted;
  444. return;
  445. }
  446. klog() << "MM: deallocate_user_physical_page couldn't figure out region for user page @ " << page.paddr();
  447. ASSERT_NOT_REACHED();
  448. }
  449. RefPtr<PhysicalPage> MemoryManager::find_free_user_physical_page(bool committed)
  450. {
  451. ASSERT(s_mm_lock.is_locked());
  452. RefPtr<PhysicalPage> page;
  453. if (committed) {
  454. // Draw from the committed pages pool. We should always have these pages available
  455. ASSERT(m_user_physical_pages_committed > 0);
  456. m_user_physical_pages_committed--;
  457. } else {
  458. // We need to make sure we don't touch pages that we have committed to
  459. if (m_user_physical_pages_uncommitted == 0)
  460. return {};
  461. m_user_physical_pages_uncommitted--;
  462. }
  463. for (auto& region : m_user_physical_regions) {
  464. page = region.take_free_page(false);
  465. if (!page.is_null()) {
  466. ++m_user_physical_pages_used;
  467. break;
  468. }
  469. }
  470. ASSERT(!committed || !page.is_null());
  471. return page;
  472. }
  473. NonnullRefPtr<PhysicalPage> MemoryManager::allocate_committed_user_physical_page(ShouldZeroFill should_zero_fill)
  474. {
  475. ScopedSpinLock lock(s_mm_lock);
  476. auto page = find_free_user_physical_page(true);
  477. if (should_zero_fill == ShouldZeroFill::Yes) {
  478. auto* ptr = quickmap_page(*page);
  479. memset(ptr, 0, PAGE_SIZE);
  480. unquickmap_page();
  481. }
  482. return page.release_nonnull();
  483. }
  484. RefPtr<PhysicalPage> MemoryManager::allocate_user_physical_page(ShouldZeroFill should_zero_fill, bool* did_purge)
  485. {
  486. ScopedSpinLock lock(s_mm_lock);
  487. auto page = find_free_user_physical_page(false);
  488. bool purged_pages = false;
  489. if (!page) {
  490. // We didn't have a single free physical page. Let's try to free something up!
  491. // First, we look for a purgeable VMObject in the volatile state.
  492. for_each_vmobject([&](auto& vmobject) {
  493. if (!vmobject.is_anonymous())
  494. return IterationDecision::Continue;
  495. int purged_page_count = static_cast<AnonymousVMObject&>(vmobject).purge_with_interrupts_disabled({});
  496. if (purged_page_count) {
  497. klog() << "MM: Purge saved the day! Purged " << purged_page_count << " pages from AnonymousVMObject{" << &vmobject << "}";
  498. page = find_free_user_physical_page(false);
  499. purged_pages = true;
  500. ASSERT(page);
  501. return IterationDecision::Break;
  502. }
  503. return IterationDecision::Continue;
  504. });
  505. if (!page) {
  506. klog() << "MM: no user physical pages available";
  507. return {};
  508. }
  509. }
  510. if (should_zero_fill == ShouldZeroFill::Yes) {
  511. auto* ptr = quickmap_page(*page);
  512. memset(ptr, 0, PAGE_SIZE);
  513. unquickmap_page();
  514. }
  515. if (did_purge)
  516. *did_purge = purged_pages;
  517. return page;
  518. }
  519. void MemoryManager::deallocate_supervisor_physical_page(const PhysicalPage& page)
  520. {
  521. ScopedSpinLock lock(s_mm_lock);
  522. for (auto& region : m_super_physical_regions) {
  523. if (!region.contains(page)) {
  524. klog() << "MM: deallocate_supervisor_physical_page: " << page.paddr() << " not in " << region.lower() << " -> " << region.upper();
  525. continue;
  526. }
  527. region.return_page(page);
  528. --m_super_physical_pages_used;
  529. return;
  530. }
  531. klog() << "MM: deallocate_supervisor_physical_page couldn't figure out region for super page @ " << page.paddr();
  532. ASSERT_NOT_REACHED();
  533. }
  534. NonnullRefPtrVector<PhysicalPage> MemoryManager::allocate_contiguous_supervisor_physical_pages(size_t size, size_t physical_alignment)
  535. {
  536. ASSERT(!(size % PAGE_SIZE));
  537. ScopedSpinLock lock(s_mm_lock);
  538. size_t count = ceil_div(size, PAGE_SIZE);
  539. NonnullRefPtrVector<PhysicalPage> physical_pages;
  540. for (auto& region : m_super_physical_regions) {
  541. physical_pages = region.take_contiguous_free_pages(count, true, physical_alignment);
  542. if (!physical_pages.is_empty())
  543. continue;
  544. }
  545. if (physical_pages.is_empty()) {
  546. if (m_super_physical_regions.is_empty()) {
  547. klog() << "MM: no super physical regions available (?)";
  548. }
  549. klog() << "MM: no super physical pages available";
  550. ASSERT_NOT_REACHED();
  551. return {};
  552. }
  553. auto cleanup_region = MM.allocate_kernel_region(physical_pages[0].paddr(), PAGE_SIZE * count, "MemoryManager Allocation Sanitization", Region::Access::Read | Region::Access::Write);
  554. fast_u32_fill((u32*)cleanup_region->vaddr().as_ptr(), 0, (PAGE_SIZE * count) / sizeof(u32));
  555. m_super_physical_pages_used += count;
  556. return physical_pages;
  557. }
  558. RefPtr<PhysicalPage> MemoryManager::allocate_supervisor_physical_page()
  559. {
  560. ScopedSpinLock lock(s_mm_lock);
  561. RefPtr<PhysicalPage> page;
  562. for (auto& region : m_super_physical_regions) {
  563. page = region.take_free_page(true);
  564. if (!page.is_null())
  565. break;
  566. }
  567. if (!page) {
  568. if (m_super_physical_regions.is_empty()) {
  569. klog() << "MM: no super physical regions available (?)";
  570. }
  571. klog() << "MM: no super physical pages available";
  572. ASSERT_NOT_REACHED();
  573. return {};
  574. }
  575. fast_u32_fill((u32*)page->paddr().offset(0xc0000000).as_ptr(), 0, PAGE_SIZE / sizeof(u32));
  576. ++m_super_physical_pages_used;
  577. return page;
  578. }
  579. void MemoryManager::enter_process_paging_scope(Process& process)
  580. {
  581. auto current_thread = Thread::current();
  582. ASSERT(current_thread != nullptr);
  583. ScopedSpinLock lock(s_mm_lock);
  584. current_thread->tss().cr3 = process.page_directory().cr3();
  585. write_cr3(process.page_directory().cr3());
  586. }
  587. void MemoryManager::flush_tlb_local(VirtualAddress vaddr, size_t page_count)
  588. {
  589. Processor::flush_tlb_local(vaddr, page_count);
  590. }
  591. void MemoryManager::flush_tlb(const PageDirectory* page_directory, VirtualAddress vaddr, size_t page_count)
  592. {
  593. Processor::flush_tlb(page_directory, vaddr, page_count);
  594. }
  595. extern "C" PageTableEntry boot_pd3_pt1023[1024];
  596. PageDirectoryEntry* MemoryManager::quickmap_pd(PageDirectory& directory, size_t pdpt_index)
  597. {
  598. ASSERT(s_mm_lock.own_lock());
  599. auto& mm_data = get_data();
  600. auto& pte = boot_pd3_pt1023[4];
  601. auto pd_paddr = directory.m_directory_pages[pdpt_index]->paddr();
  602. if (pte.physical_page_base() != pd_paddr.as_ptr()) {
  603. pte.set_physical_page_base(pd_paddr.get());
  604. pte.set_present(true);
  605. pte.set_writable(true);
  606. pte.set_user_allowed(false);
  607. // Because we must continue to hold the MM lock while we use this
  608. // mapping, it is sufficient to only flush on the current CPU. Other
  609. // CPUs trying to use this API must wait on the MM lock anyway
  610. flush_tlb_local(VirtualAddress(0xffe04000));
  611. } else {
  612. // Even though we don't allow this to be called concurrently, it's
  613. // possible that this PD was mapped on a different CPU and we don't
  614. // broadcast the flush. If so, we still need to flush the TLB.
  615. if (mm_data.m_last_quickmap_pd != pd_paddr)
  616. flush_tlb_local(VirtualAddress(0xffe04000));
  617. }
  618. mm_data.m_last_quickmap_pd = pd_paddr;
  619. return (PageDirectoryEntry*)0xffe04000;
  620. }
  621. PageTableEntry* MemoryManager::quickmap_pt(PhysicalAddress pt_paddr)
  622. {
  623. ASSERT(s_mm_lock.own_lock());
  624. auto& mm_data = get_data();
  625. auto& pte = boot_pd3_pt1023[0];
  626. if (pte.physical_page_base() != pt_paddr.as_ptr()) {
  627. pte.set_physical_page_base(pt_paddr.get());
  628. pte.set_present(true);
  629. pte.set_writable(true);
  630. pte.set_user_allowed(false);
  631. // Because we must continue to hold the MM lock while we use this
  632. // mapping, it is sufficient to only flush on the current CPU. Other
  633. // CPUs trying to use this API must wait on the MM lock anyway
  634. flush_tlb_local(VirtualAddress(0xffe00000));
  635. } else {
  636. // Even though we don't allow this to be called concurrently, it's
  637. // possible that this PT was mapped on a different CPU and we don't
  638. // broadcast the flush. If so, we still need to flush the TLB.
  639. if (mm_data.m_last_quickmap_pt != pt_paddr)
  640. flush_tlb_local(VirtualAddress(0xffe00000));
  641. }
  642. mm_data.m_last_quickmap_pt = pt_paddr;
  643. return (PageTableEntry*)0xffe00000;
  644. }
  645. u8* MemoryManager::quickmap_page(PhysicalPage& physical_page)
  646. {
  647. ASSERT_INTERRUPTS_DISABLED();
  648. auto& mm_data = get_data();
  649. mm_data.m_quickmap_prev_flags = mm_data.m_quickmap_in_use.lock();
  650. ScopedSpinLock lock(s_mm_lock);
  651. u32 pte_idx = 8 + Processor::id();
  652. VirtualAddress vaddr(0xffe00000 + pte_idx * PAGE_SIZE);
  653. auto& pte = boot_pd3_pt1023[pte_idx];
  654. if (pte.physical_page_base() != physical_page.paddr().as_ptr()) {
  655. pte.set_physical_page_base(physical_page.paddr().get());
  656. pte.set_present(true);
  657. pte.set_writable(true);
  658. pte.set_user_allowed(false);
  659. flush_tlb_local(vaddr);
  660. }
  661. return vaddr.as_ptr();
  662. }
  663. void MemoryManager::unquickmap_page()
  664. {
  665. ASSERT_INTERRUPTS_DISABLED();
  666. ScopedSpinLock lock(s_mm_lock);
  667. auto& mm_data = get_data();
  668. ASSERT(mm_data.m_quickmap_in_use.is_locked());
  669. u32 pte_idx = 8 + Processor::id();
  670. VirtualAddress vaddr(0xffe00000 + pte_idx * PAGE_SIZE);
  671. auto& pte = boot_pd3_pt1023[pte_idx];
  672. pte.clear();
  673. flush_tlb_local(vaddr);
  674. mm_data.m_quickmap_in_use.unlock(mm_data.m_quickmap_prev_flags);
  675. }
  676. template<MemoryManager::AccessSpace space, MemoryManager::AccessType access_type>
  677. bool MemoryManager::validate_range(const Process& process, VirtualAddress base_vaddr, size_t size) const
  678. {
  679. ASSERT(s_mm_lock.is_locked());
  680. ASSERT(size);
  681. if (base_vaddr > base_vaddr.offset(size)) {
  682. dbgln("Shenanigans! Asked to validate wrappy {} size={}", base_vaddr, size);
  683. return false;
  684. }
  685. VirtualAddress vaddr = base_vaddr.page_base();
  686. VirtualAddress end_vaddr = base_vaddr.offset(size - 1).page_base();
  687. if (end_vaddr < vaddr) {
  688. dbgln("Shenanigans! Asked to validate {} size={}", base_vaddr, size);
  689. return false;
  690. }
  691. const Region* region = nullptr;
  692. while (vaddr <= end_vaddr) {
  693. if (!region || !region->contains(vaddr)) {
  694. if (space == AccessSpace::Kernel)
  695. region = kernel_region_from_vaddr(vaddr);
  696. if (!region || !region->contains(vaddr))
  697. region = user_region_from_vaddr(const_cast<Process&>(process), vaddr);
  698. if (!region
  699. || (space == AccessSpace::User && !region->is_user_accessible())
  700. || (access_type == AccessType::Read && !region->is_readable())
  701. || (access_type == AccessType::Write && !region->is_writable())) {
  702. return false;
  703. }
  704. }
  705. vaddr = region->range().end();
  706. }
  707. return true;
  708. }
  709. bool MemoryManager::validate_user_stack(const Process& process, VirtualAddress vaddr) const
  710. {
  711. if (!is_user_address(vaddr))
  712. return false;
  713. ScopedSpinLock lock(s_mm_lock);
  714. auto* region = user_region_from_vaddr(const_cast<Process&>(process), vaddr);
  715. return region && region->is_user_accessible() && region->is_stack();
  716. }
  717. void MemoryManager::register_vmobject(VMObject& vmobject)
  718. {
  719. ScopedSpinLock lock(s_mm_lock);
  720. m_vmobjects.append(&vmobject);
  721. }
  722. void MemoryManager::unregister_vmobject(VMObject& vmobject)
  723. {
  724. ScopedSpinLock lock(s_mm_lock);
  725. m_vmobjects.remove(&vmobject);
  726. }
  727. void MemoryManager::register_region(Region& region)
  728. {
  729. ScopedSpinLock lock(s_mm_lock);
  730. if (region.is_kernel())
  731. m_kernel_regions.append(&region);
  732. else
  733. m_user_regions.append(&region);
  734. }
  735. void MemoryManager::unregister_region(Region& region)
  736. {
  737. ScopedSpinLock lock(s_mm_lock);
  738. if (region.is_kernel())
  739. m_kernel_regions.remove(&region);
  740. else
  741. m_user_regions.remove(&region);
  742. }
  743. void MemoryManager::dump_kernel_regions()
  744. {
  745. klog() << "Kernel regions:";
  746. klog() << "BEGIN END SIZE ACCESS NAME";
  747. ScopedSpinLock lock(s_mm_lock);
  748. for (auto& region : MM.m_kernel_regions) {
  749. klog() << String::format("%08x", region.vaddr().get()) << " -- " << String::format("%08x", region.vaddr().offset(region.size() - 1).get()) << " " << String::format("%08zx", region.size()) << " " << (region.is_readable() ? 'R' : ' ') << (region.is_writable() ? 'W' : ' ') << (region.is_executable() ? 'X' : ' ') << (region.is_shared() ? 'S' : ' ') << (region.is_stack() ? 'T' : ' ') << (region.vmobject().is_anonymous() ? 'A' : ' ') << " " << region.name().characters();
  750. }
  751. }
  752. }