Region.cpp 19 KB

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