MemoryManager.cpp 34 KB

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