Region.cpp 19 KB

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