MemoryManager.cpp 34 KB

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