Region.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Memory.h>
  7. #include <AK/StringView.h>
  8. #include <Kernel/Arch/PageDirectory.h>
  9. #include <Kernel/Arch/PageFault.h>
  10. #include <Kernel/Debug.h>
  11. #include <Kernel/FileSystem/Inode.h>
  12. #include <Kernel/Memory/AnonymousVMObject.h>
  13. #include <Kernel/Memory/MemoryManager.h>
  14. #include <Kernel/Memory/PageDirectory.h>
  15. #include <Kernel/Memory/Region.h>
  16. #include <Kernel/Memory/SharedInodeVMObject.h>
  17. #include <Kernel/Panic.h>
  18. #include <Kernel/Process.h>
  19. #include <Kernel/Scheduler.h>
  20. #include <Kernel/Thread.h>
  21. namespace Kernel::Memory {
  22. Region::Region(VirtualRange const& range)
  23. : m_range(range)
  24. {
  25. if (is_kernel())
  26. MM.register_kernel_region(*this);
  27. }
  28. Region::Region(VirtualRange const& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, OwnPtr<KString> name, Region::Access access, Cacheable cacheable, bool shared)
  29. : m_range(range)
  30. , m_offset_in_vmobject(offset_in_vmobject)
  31. , m_vmobject(move(vmobject))
  32. , m_name(move(name))
  33. , m_access(access | ((access & 0x7) << 4))
  34. , m_shared(shared)
  35. , m_cacheable(cacheable == Cacheable::Yes)
  36. {
  37. VERIFY(m_range.base().is_page_aligned());
  38. VERIFY(m_range.size());
  39. VERIFY((m_range.size() % PAGE_SIZE) == 0);
  40. m_vmobject->add_region(*this);
  41. if (is_kernel())
  42. MM.register_kernel_region(*this);
  43. }
  44. Region::~Region()
  45. {
  46. if (is_writable() && vmobject().is_shared_inode()) {
  47. // FIXME: This is very aggressive. Find a way to do less work!
  48. (void)static_cast<SharedInodeVMObject&>(vmobject()).sync();
  49. }
  50. m_vmobject->remove_region(*this);
  51. if (is_kernel())
  52. MM.unregister_kernel_region(*this);
  53. if (m_page_directory) {
  54. SpinlockLocker pd_locker(m_page_directory->get_lock());
  55. if (!is_readable() && !is_writable() && !is_executable()) {
  56. // If the region is "PROT_NONE", we didn't map it in the first place.
  57. } else {
  58. SpinlockLocker mm_locker(s_mm_lock);
  59. unmap_with_locks_held(ShouldDeallocateVirtualRange::Yes, ShouldFlushTLB::Yes, pd_locker, mm_locker);
  60. VERIFY(!m_page_directory);
  61. }
  62. }
  63. }
  64. ErrorOr<NonnullOwnPtr<Region>> Region::create_unbacked(VirtualRange const& range)
  65. {
  66. return adopt_nonnull_own_or_enomem(new (nothrow) Region(range));
  67. }
  68. ErrorOr<NonnullOwnPtr<Region>> Region::try_clone()
  69. {
  70. VERIFY(Process::has_current());
  71. if (m_shared) {
  72. VERIFY(!m_stack);
  73. if (vmobject().is_inode())
  74. VERIFY(vmobject().is_shared_inode());
  75. // Create a new region backed by the same VMObject.
  76. OwnPtr<KString> region_name;
  77. if (m_name)
  78. region_name = TRY(m_name->try_clone());
  79. auto region = TRY(Region::try_create_user_accessible(
  80. m_range, vmobject(), m_offset_in_vmobject, move(region_name), access(), m_cacheable ? Cacheable::Yes : Cacheable::No, m_shared));
  81. region->set_mmap(m_mmap);
  82. region->set_shared(m_shared);
  83. region->set_syscall_region(is_syscall_region());
  84. return region;
  85. }
  86. if (vmobject().is_inode())
  87. VERIFY(vmobject().is_private_inode());
  88. auto vmobject_clone = TRY(vmobject().try_clone());
  89. // Set up a COW region. The parent (this) region becomes COW as well!
  90. if (is_writable())
  91. remap();
  92. OwnPtr<KString> clone_region_name;
  93. if (m_name)
  94. clone_region_name = TRY(m_name->try_clone());
  95. auto clone_region = TRY(Region::try_create_user_accessible(
  96. m_range, move(vmobject_clone), m_offset_in_vmobject, move(clone_region_name), access(), m_cacheable ? Cacheable::Yes : Cacheable::No, m_shared));
  97. if (m_stack) {
  98. VERIFY(is_readable());
  99. VERIFY(is_writable());
  100. VERIFY(vmobject().is_anonymous());
  101. clone_region->set_stack(true);
  102. }
  103. clone_region->set_syscall_region(is_syscall_region());
  104. clone_region->set_mmap(m_mmap);
  105. return clone_region;
  106. }
  107. void Region::set_vmobject(NonnullRefPtr<VMObject>&& obj)
  108. {
  109. if (m_vmobject.ptr() == obj.ptr())
  110. return;
  111. m_vmobject->remove_region(*this);
  112. m_vmobject = move(obj);
  113. m_vmobject->add_region(*this);
  114. }
  115. size_t Region::cow_pages() const
  116. {
  117. if (!vmobject().is_anonymous())
  118. return 0;
  119. return static_cast<AnonymousVMObject const&>(vmobject()).cow_pages();
  120. }
  121. size_t Region::amount_dirty() const
  122. {
  123. if (!vmobject().is_inode())
  124. return amount_resident();
  125. return static_cast<InodeVMObject const&>(vmobject()).amount_dirty();
  126. }
  127. size_t Region::amount_resident() const
  128. {
  129. size_t bytes = 0;
  130. for (size_t i = 0; i < page_count(); ++i) {
  131. auto const* page = physical_page(i);
  132. if (page && !page->is_shared_zero_page() && !page->is_lazy_committed_page())
  133. bytes += PAGE_SIZE;
  134. }
  135. return bytes;
  136. }
  137. size_t Region::amount_shared() const
  138. {
  139. size_t bytes = 0;
  140. for (size_t i = 0; i < page_count(); ++i) {
  141. auto const* page = physical_page(i);
  142. if (page && page->ref_count() > 1 && !page->is_shared_zero_page() && !page->is_lazy_committed_page())
  143. bytes += PAGE_SIZE;
  144. }
  145. return bytes;
  146. }
  147. ErrorOr<NonnullOwnPtr<Region>> Region::try_create_user_accessible(VirtualRange const& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, OwnPtr<KString> name, Region::Access access, Cacheable cacheable, bool shared)
  148. {
  149. return adopt_nonnull_own_or_enomem(new (nothrow) Region(range, move(vmobject), offset_in_vmobject, move(name), access, cacheable, shared));
  150. }
  151. ErrorOr<NonnullOwnPtr<Region>> Region::try_create_kernel_only(VirtualRange const& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, OwnPtr<KString> name, Region::Access access, Cacheable cacheable)
  152. {
  153. return adopt_nonnull_own_or_enomem(new (nothrow) Region(range, move(vmobject), offset_in_vmobject, move(name), access, cacheable, false));
  154. }
  155. bool Region::should_cow(size_t page_index) const
  156. {
  157. if (!vmobject().is_anonymous())
  158. return false;
  159. return static_cast<AnonymousVMObject const&>(vmobject()).should_cow(first_page_index() + page_index, m_shared);
  160. }
  161. ErrorOr<void> Region::set_should_cow(size_t page_index, bool cow)
  162. {
  163. VERIFY(!m_shared);
  164. if (vmobject().is_anonymous())
  165. TRY(static_cast<AnonymousVMObject&>(vmobject()).set_should_cow(first_page_index() + page_index, cow));
  166. return {};
  167. }
  168. bool Region::map_individual_page_impl(size_t page_index)
  169. {
  170. VERIFY(m_page_directory->get_lock().is_locked_by_current_processor());
  171. VERIFY(s_mm_lock.is_locked_by_current_processor());
  172. auto page_vaddr = vaddr_from_page_index(page_index);
  173. bool user_allowed = page_vaddr.get() >= USER_RANGE_BASE && is_user_address(page_vaddr);
  174. if (is_mmap() && !user_allowed) {
  175. PANIC("About to map mmap'ed page at a kernel address");
  176. }
  177. auto* pte = MM.ensure_pte(*m_page_directory, page_vaddr);
  178. if (!pte)
  179. return false;
  180. auto* page = physical_page(page_index);
  181. if (!page || (!is_readable() && !is_writable())) {
  182. pte->clear();
  183. } else {
  184. pte->set_cache_disabled(!m_cacheable);
  185. pte->set_physical_page_base(page->paddr().get());
  186. pte->set_present(true);
  187. if (page->is_shared_zero_page() || page->is_lazy_committed_page() || should_cow(page_index))
  188. pte->set_writable(false);
  189. else
  190. pte->set_writable(is_writable());
  191. if (Processor::current().has_nx())
  192. pte->set_execute_disabled(!is_executable());
  193. if (Processor::current().has_pat())
  194. pte->set_pat(is_write_combine());
  195. pte->set_user_allowed(user_allowed);
  196. }
  197. return true;
  198. }
  199. bool Region::do_remap_vmobject_page(size_t page_index, bool with_flush)
  200. {
  201. if (!m_page_directory)
  202. return true; // not an error, region may have not yet mapped it
  203. if (!translate_vmobject_page(page_index))
  204. return true; // not an error, region doesn't map this page
  205. SpinlockLocker page_lock(m_page_directory->get_lock());
  206. SpinlockLocker lock(s_mm_lock);
  207. VERIFY(physical_page(page_index));
  208. bool success = map_individual_page_impl(page_index);
  209. if (with_flush)
  210. MemoryManager::flush_tlb(m_page_directory, vaddr_from_page_index(page_index));
  211. return success;
  212. }
  213. bool Region::remap_vmobject_page(size_t page_index, bool with_flush)
  214. {
  215. auto& vmobject = this->vmobject();
  216. bool success = true;
  217. SpinlockLocker lock(vmobject.m_lock);
  218. vmobject.for_each_region([&](auto& region) {
  219. if (!region.do_remap_vmobject_page(page_index, with_flush))
  220. success = false;
  221. });
  222. return success;
  223. }
  224. void Region::unmap(ShouldDeallocateVirtualRange should_deallocate_range, ShouldFlushTLB should_flush_tlb)
  225. {
  226. if (!m_page_directory)
  227. return;
  228. SpinlockLocker pd_locker(m_page_directory->get_lock());
  229. SpinlockLocker mm_locker(s_mm_lock);
  230. unmap_with_locks_held(should_deallocate_range, should_flush_tlb, pd_locker, mm_locker);
  231. }
  232. void Region::unmap_with_locks_held(ShouldDeallocateVirtualRange, ShouldFlushTLB should_flush_tlb, SpinlockLocker<RecursiveSpinlock>&, SpinlockLocker<RecursiveSpinlock>&)
  233. {
  234. if (!m_page_directory)
  235. return;
  236. size_t count = page_count();
  237. for (size_t i = 0; i < count; ++i) {
  238. auto vaddr = vaddr_from_page_index(i);
  239. MM.release_pte(*m_page_directory, vaddr, i == count - 1 ? MemoryManager::IsLastPTERelease::Yes : MemoryManager::IsLastPTERelease::No);
  240. }
  241. if (should_flush_tlb == ShouldFlushTLB::Yes)
  242. MemoryManager::flush_tlb(m_page_directory, vaddr(), page_count());
  243. m_page_directory = nullptr;
  244. }
  245. void Region::set_page_directory(PageDirectory& page_directory)
  246. {
  247. VERIFY(!m_page_directory || m_page_directory == &page_directory);
  248. VERIFY(s_mm_lock.is_locked_by_current_processor());
  249. m_page_directory = page_directory;
  250. }
  251. ErrorOr<void> Region::map(PageDirectory& page_directory, ShouldFlushTLB should_flush_tlb)
  252. {
  253. SpinlockLocker page_lock(page_directory.get_lock());
  254. SpinlockLocker lock(s_mm_lock);
  255. // FIXME: Find a better place for this sanity check(?)
  256. if (is_user() && !is_shared()) {
  257. VERIFY(!vmobject().is_shared_inode());
  258. }
  259. set_page_directory(page_directory);
  260. size_t page_index = 0;
  261. while (page_index < page_count()) {
  262. if (!map_individual_page_impl(page_index))
  263. break;
  264. ++page_index;
  265. }
  266. if (page_index > 0) {
  267. if (should_flush_tlb == ShouldFlushTLB::Yes)
  268. MemoryManager::flush_tlb(m_page_directory, vaddr(), page_index);
  269. if (page_index == page_count())
  270. return {};
  271. }
  272. return ENOMEM;
  273. }
  274. void Region::remap()
  275. {
  276. VERIFY(m_page_directory);
  277. auto result = map(*m_page_directory);
  278. if (result.is_error())
  279. TODO();
  280. }
  281. ErrorOr<void> Region::set_write_combine(bool enable)
  282. {
  283. if (enable && !Processor::current().has_pat()) {
  284. dbgln("PAT is not supported, implement MTRR fallback if available");
  285. return Error::from_errno(ENOTSUP);
  286. }
  287. m_write_combine = enable;
  288. remap();
  289. return {};
  290. }
  291. void Region::clear_to_zero()
  292. {
  293. VERIFY(vmobject().is_anonymous());
  294. SpinlockLocker locker(vmobject().m_lock);
  295. for (auto i = 0u; i < page_count(); ++i) {
  296. auto& page = physical_page_slot(i);
  297. VERIFY(page);
  298. if (page->is_shared_zero_page())
  299. continue;
  300. page = MM.shared_zero_page();
  301. }
  302. }
  303. PageFaultResponse Region::handle_fault(PageFault const& fault)
  304. {
  305. auto page_index_in_region = page_index_from_address(fault.vaddr());
  306. if (fault.type() == PageFault::Type::PageNotPresent) {
  307. if (fault.is_read() && !is_readable()) {
  308. dbgln("NP(non-readable) fault in Region({})[{}]", this, page_index_in_region);
  309. return PageFaultResponse::ShouldCrash;
  310. }
  311. if (fault.is_write() && !is_writable()) {
  312. dbgln("NP(non-writable) write fault in Region({})[{}] at {}", this, page_index_in_region, fault.vaddr());
  313. return PageFaultResponse::ShouldCrash;
  314. }
  315. if (vmobject().is_inode()) {
  316. dbgln_if(PAGE_FAULT_DEBUG, "NP(inode) fault in Region({})[{}]", this, page_index_in_region);
  317. return handle_inode_fault(page_index_in_region);
  318. }
  319. auto& page_slot = physical_page_slot(page_index_in_region);
  320. if (page_slot->is_lazy_committed_page()) {
  321. auto page_index_in_vmobject = translate_to_vmobject_page(page_index_in_region);
  322. VERIFY(m_vmobject->is_anonymous());
  323. page_slot = static_cast<AnonymousVMObject&>(*m_vmobject).allocate_committed_page({});
  324. if (!remap_vmobject_page(page_index_in_vmobject))
  325. return PageFaultResponse::OutOfMemory;
  326. return PageFaultResponse::Continue;
  327. }
  328. dbgln("BUG! Unexpected NP fault at {}", fault.vaddr());
  329. return PageFaultResponse::ShouldCrash;
  330. }
  331. VERIFY(fault.type() == PageFault::Type::ProtectionViolation);
  332. if (fault.access() == PageFault::Access::Write && is_writable() && should_cow(page_index_in_region)) {
  333. dbgln_if(PAGE_FAULT_DEBUG, "PV(cow) fault in Region({})[{}] at {}", this, page_index_in_region, fault.vaddr());
  334. auto* phys_page = physical_page(page_index_in_region);
  335. if (phys_page->is_shared_zero_page() || phys_page->is_lazy_committed_page()) {
  336. dbgln_if(PAGE_FAULT_DEBUG, "NP(zero) fault in Region({})[{}] at {}", this, page_index_in_region, fault.vaddr());
  337. return handle_zero_fault(page_index_in_region);
  338. }
  339. return handle_cow_fault(page_index_in_region);
  340. }
  341. dbgln("PV(error) fault in Region({})[{}] at {}", this, page_index_in_region, fault.vaddr());
  342. return PageFaultResponse::ShouldCrash;
  343. }
  344. PageFaultResponse Region::handle_zero_fault(size_t page_index_in_region)
  345. {
  346. VERIFY_INTERRUPTS_DISABLED();
  347. VERIFY(vmobject().is_anonymous());
  348. auto& page_slot = physical_page_slot(page_index_in_region);
  349. auto page_index_in_vmobject = translate_to_vmobject_page(page_index_in_region);
  350. SpinlockLocker locker(vmobject().m_lock);
  351. if (!page_slot.is_null() && !page_slot->is_shared_zero_page() && !page_slot->is_lazy_committed_page()) {
  352. dbgln_if(PAGE_FAULT_DEBUG, "MM: zero_page() but page already present. Fine with me!");
  353. if (!remap_vmobject_page(page_index_in_vmobject))
  354. return PageFaultResponse::OutOfMemory;
  355. return PageFaultResponse::Continue;
  356. }
  357. auto current_thread = Thread::current();
  358. if (current_thread != nullptr)
  359. current_thread->did_zero_fault();
  360. if (page_slot->is_lazy_committed_page()) {
  361. VERIFY(m_vmobject->is_anonymous());
  362. page_slot = static_cast<AnonymousVMObject&>(*m_vmobject).allocate_committed_page({});
  363. dbgln_if(PAGE_FAULT_DEBUG, " >> ALLOCATED COMMITTED {}", page_slot->paddr());
  364. } else {
  365. auto page_or_error = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::Yes);
  366. if (page_or_error.is_error()) {
  367. dmesgln("MM: handle_zero_fault was unable to allocate a physical page");
  368. return PageFaultResponse::OutOfMemory;
  369. }
  370. page_slot = page_or_error.release_value();
  371. dbgln_if(PAGE_FAULT_DEBUG, " >> ALLOCATED {}", page_slot->paddr());
  372. }
  373. if (!remap_vmobject_page(page_index_in_vmobject)) {
  374. dmesgln("MM: handle_zero_fault was unable to allocate a page table to map {}", page_slot);
  375. return PageFaultResponse::OutOfMemory;
  376. }
  377. return PageFaultResponse::Continue;
  378. }
  379. PageFaultResponse Region::handle_cow_fault(size_t page_index_in_region)
  380. {
  381. VERIFY_INTERRUPTS_DISABLED();
  382. auto current_thread = Thread::current();
  383. if (current_thread)
  384. current_thread->did_cow_fault();
  385. if (!vmobject().is_anonymous())
  386. return PageFaultResponse::ShouldCrash;
  387. auto page_index_in_vmobject = translate_to_vmobject_page(page_index_in_region);
  388. auto response = reinterpret_cast<AnonymousVMObject&>(vmobject()).handle_cow_fault(page_index_in_vmobject, vaddr().offset(page_index_in_region * PAGE_SIZE));
  389. if (!remap_vmobject_page(page_index_in_vmobject))
  390. return PageFaultResponse::OutOfMemory;
  391. return response;
  392. }
  393. PageFaultResponse Region::handle_inode_fault(size_t page_index_in_region)
  394. {
  395. VERIFY_INTERRUPTS_DISABLED();
  396. VERIFY(vmobject().is_inode());
  397. VERIFY(!s_mm_lock.is_locked_by_current_processor());
  398. VERIFY(!g_scheduler_lock.is_locked_by_current_processor());
  399. auto& inode_vmobject = static_cast<InodeVMObject&>(vmobject());
  400. auto page_index_in_vmobject = translate_to_vmobject_page(page_index_in_region);
  401. auto& vmobject_physical_page_entry = inode_vmobject.physical_pages()[page_index_in_vmobject];
  402. {
  403. SpinlockLocker locker(inode_vmobject.m_lock);
  404. if (!vmobject_physical_page_entry.is_null()) {
  405. dbgln_if(PAGE_FAULT_DEBUG, "handle_inode_fault: Page faulted in by someone else before reading, remapping.");
  406. if (!remap_vmobject_page(page_index_in_vmobject))
  407. return PageFaultResponse::OutOfMemory;
  408. return PageFaultResponse::Continue;
  409. }
  410. }
  411. dbgln_if(PAGE_FAULT_DEBUG, "Inode fault in {} page index: {}", name(), page_index_in_region);
  412. auto current_thread = Thread::current();
  413. if (current_thread)
  414. current_thread->did_inode_fault();
  415. u8 page_buffer[PAGE_SIZE];
  416. auto& inode = inode_vmobject.inode();
  417. auto buffer = UserOrKernelBuffer::for_kernel_buffer(page_buffer);
  418. auto result = inode.read_bytes(page_index_in_vmobject * PAGE_SIZE, PAGE_SIZE, buffer, nullptr);
  419. if (result.is_error()) {
  420. dmesgln("handle_inode_fault: Error ({}) while reading from inode", result.error());
  421. return PageFaultResponse::ShouldCrash;
  422. }
  423. auto nread = result.value();
  424. if (nread < PAGE_SIZE) {
  425. // If we read less than a page, zero out the rest to avoid leaking uninitialized data.
  426. memset(page_buffer + nread, 0, PAGE_SIZE - nread);
  427. }
  428. SpinlockLocker locker(inode_vmobject.m_lock);
  429. if (!vmobject_physical_page_entry.is_null()) {
  430. // Someone else faulted in this page while we were reading from the inode.
  431. // No harm done (other than some duplicate work), remap the page here and return.
  432. dbgln_if(PAGE_FAULT_DEBUG, "handle_inode_fault: Page faulted in by someone else, remapping.");
  433. if (!remap_vmobject_page(page_index_in_vmobject))
  434. return PageFaultResponse::OutOfMemory;
  435. return PageFaultResponse::Continue;
  436. }
  437. auto vmobject_physical_page_or_error = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::No);
  438. if (vmobject_physical_page_or_error.is_error()) {
  439. dmesgln("MM: handle_inode_fault was unable to allocate a physical page");
  440. return PageFaultResponse::OutOfMemory;
  441. }
  442. vmobject_physical_page_entry = vmobject_physical_page_or_error.release_value();
  443. {
  444. SpinlockLocker mm_locker(s_mm_lock);
  445. u8* dest_ptr = MM.quickmap_page(*vmobject_physical_page_entry);
  446. memcpy(dest_ptr, page_buffer, PAGE_SIZE);
  447. MM.unquickmap_page();
  448. }
  449. if (!remap_vmobject_page(page_index_in_vmobject))
  450. return PageFaultResponse::OutOfMemory;
  451. return PageFaultResponse::Continue;
  452. }
  453. }