Region.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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/Memory.h>
  27. #include <AK/StringView.h>
  28. #include <Kernel/FileSystem/Inode.h>
  29. #include <Kernel/Process.h>
  30. #include <Kernel/Thread.h>
  31. #include <Kernel/VM/AnonymousVMObject.h>
  32. #include <Kernel/VM/MemoryManager.h>
  33. #include <Kernel/VM/PageDirectory.h>
  34. #include <Kernel/VM/Region.h>
  35. #include <Kernel/VM/SharedInodeVMObject.h>
  36. //#define MM_DEBUG
  37. //#define PAGE_FAULT_DEBUG
  38. namespace Kernel {
  39. Region::Region(const Range& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const String& name, u8 access, bool cacheable, bool kernel)
  40. : m_range(range)
  41. , m_offset_in_vmobject(offset_in_vmobject)
  42. , m_vmobject(move(vmobject))
  43. , m_name(name)
  44. , m_access(access)
  45. , m_cacheable(cacheable)
  46. , m_kernel(kernel)
  47. {
  48. MM.register_region(*this);
  49. }
  50. Region::~Region()
  51. {
  52. // Make sure we disable interrupts so we don't get interrupted between unmapping and unregistering.
  53. // Unmapping the region will give the VM back to the RangeAllocator, so an interrupt handler would
  54. // find the address<->region mappings in an invalid state there.
  55. InterruptDisabler disabler;
  56. if (m_page_directory) {
  57. unmap(ShouldDeallocateVirtualMemoryRange::Yes);
  58. ASSERT(!m_page_directory);
  59. }
  60. MM.unregister_region(*this);
  61. }
  62. NonnullOwnPtr<Region> Region::clone()
  63. {
  64. ASSERT(Process::current());
  65. if (m_inherit_mode == InheritMode::ZeroedOnFork) {
  66. ASSERT(m_mmap);
  67. ASSERT(!m_shared);
  68. ASSERT(vmobject().is_anonymous());
  69. auto zeroed_region = Region::create_user_accessible(m_range, AnonymousVMObject::create_with_size(size()), 0, m_name, m_access);
  70. zeroed_region->set_mmap(m_mmap);
  71. zeroed_region->set_inherit_mode(m_inherit_mode);
  72. return zeroed_region;
  73. }
  74. if (m_shared) {
  75. ASSERT(!m_stack);
  76. #ifdef MM_DEBUG
  77. dbg() << "Region::clone(): Sharing " << name() << " (" << vaddr() << ")";
  78. #endif
  79. if (vmobject().is_inode())
  80. ASSERT(vmobject().is_shared_inode());
  81. // Create a new region backed by the same VMObject.
  82. auto region = Region::create_user_accessible(m_range, m_vmobject, m_offset_in_vmobject, m_name, m_access);
  83. region->set_mmap(m_mmap);
  84. region->set_shared(m_shared);
  85. return region;
  86. }
  87. if (vmobject().is_inode())
  88. ASSERT(vmobject().is_private_inode());
  89. #ifdef MM_DEBUG
  90. dbg() << "Region::clone(): CoWing " << name() << " (" << vaddr() << ")";
  91. #endif
  92. // Set up a COW region. The parent (this) region becomes COW as well!
  93. ensure_cow_map().fill(true);
  94. remap();
  95. auto clone_region = Region::create_user_accessible(m_range, m_vmobject->clone(), m_offset_in_vmobject, m_name, m_access);
  96. clone_region->ensure_cow_map();
  97. if (m_stack) {
  98. ASSERT(is_readable());
  99. ASSERT(is_writable());
  100. ASSERT(vmobject().is_anonymous());
  101. clone_region->set_stack(true);
  102. }
  103. clone_region->set_mmap(m_mmap);
  104. return clone_region;
  105. }
  106. bool Region::commit()
  107. {
  108. InterruptDisabler disabler;
  109. #ifdef MM_DEBUG
  110. dbg() << "MM: Commit " << page_count() << " pages in Region " << this << " (VMO=" << &vmobject() << ") at " << vaddr();
  111. #endif
  112. for (size_t i = 0; i < page_count(); ++i) {
  113. if (!commit(i))
  114. return false;
  115. }
  116. return true;
  117. }
  118. bool Region::commit(size_t page_index)
  119. {
  120. ASSERT(vmobject().is_anonymous() || vmobject().is_purgeable());
  121. InterruptDisabler disabler;
  122. auto& vmobject_physical_page_entry = physical_page_slot(page_index);
  123. if (!vmobject_physical_page_entry.is_null() && !vmobject_physical_page_entry->is_shared_zero_page())
  124. return true;
  125. auto physical_page = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::Yes);
  126. if (!physical_page) {
  127. klog() << "MM: commit was unable to allocate a physical page";
  128. ASSERT_NOT_REACHED();
  129. return false;
  130. }
  131. vmobject_physical_page_entry = move(physical_page);
  132. remap_page(page_index);
  133. return true;
  134. }
  135. u32 Region::cow_pages() const
  136. {
  137. if (!m_cow_map)
  138. return 0;
  139. u32 count = 0;
  140. for (size_t i = 0; i < m_cow_map->size(); ++i)
  141. count += m_cow_map->get(i);
  142. return count;
  143. }
  144. size_t Region::amount_dirty() const
  145. {
  146. if (!vmobject().is_inode())
  147. return amount_resident();
  148. return static_cast<const InodeVMObject&>(vmobject()).amount_dirty();
  149. }
  150. size_t Region::amount_resident() const
  151. {
  152. size_t bytes = 0;
  153. for (size_t i = 0; i < page_count(); ++i) {
  154. auto* page = physical_page(i);
  155. if (page && !page->is_shared_zero_page())
  156. bytes += PAGE_SIZE;
  157. }
  158. return bytes;
  159. }
  160. size_t Region::amount_shared() const
  161. {
  162. size_t bytes = 0;
  163. for (size_t i = 0; i < page_count(); ++i) {
  164. auto* page = physical_page(i);
  165. if (page && page->ref_count() > 1 && !page->is_shared_zero_page())
  166. bytes += PAGE_SIZE;
  167. }
  168. return bytes;
  169. }
  170. NonnullOwnPtr<Region> Region::create_user_accessible(const Range& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const StringView& name, u8 access, bool cacheable)
  171. {
  172. auto region = make<Region>(range, move(vmobject), offset_in_vmobject, name, access, cacheable, false);
  173. region->m_user_accessible = true;
  174. return region;
  175. }
  176. NonnullOwnPtr<Region> Region::create_kernel_only(const Range& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const StringView& name, u8 access, bool cacheable)
  177. {
  178. auto region = make<Region>(range, move(vmobject), offset_in_vmobject, name, access, cacheable, true);
  179. region->m_user_accessible = false;
  180. return region;
  181. }
  182. bool Region::should_cow(size_t page_index) const
  183. {
  184. auto* page = physical_page(page_index);
  185. if (page && page->is_shared_zero_page())
  186. return true;
  187. if (m_shared)
  188. return false;
  189. return m_cow_map && m_cow_map->get(page_index);
  190. }
  191. void Region::set_should_cow(size_t page_index, bool cow)
  192. {
  193. ASSERT(!m_shared);
  194. ensure_cow_map().set(page_index, cow);
  195. }
  196. Bitmap& Region::ensure_cow_map() const
  197. {
  198. if (!m_cow_map)
  199. m_cow_map = make<Bitmap>(page_count(), true);
  200. return *m_cow_map;
  201. }
  202. void Region::map_individual_page_impl(size_t page_index)
  203. {
  204. auto page_vaddr = vaddr().offset(page_index * PAGE_SIZE);
  205. auto& pte = MM.ensure_pte(*m_page_directory, page_vaddr);
  206. auto* page = physical_page(page_index);
  207. if (!page || (!is_readable() && !is_writable())) {
  208. pte.clear();
  209. } else {
  210. pte.set_cache_disabled(!m_cacheable);
  211. pte.set_physical_page_base(page->paddr().get());
  212. pte.set_present(true);
  213. if (should_cow(page_index))
  214. pte.set_writable(false);
  215. else
  216. pte.set_writable(is_writable());
  217. if (Processor::current().has_feature(CPUFeature::NX))
  218. pte.set_execute_disabled(!is_executable());
  219. pte.set_user_allowed(is_user_accessible());
  220. #ifdef MM_DEBUG
  221. dbg() << "MM: >> region map (PD=" << m_page_directory->cr3() << ", PTE=" << (void*)pte.raw() << "{" << &pte << "}) " << name() << " " << page_vaddr << " => " << page->paddr() << " (@" << page << ")";
  222. #endif
  223. }
  224. MM.flush_tlb(page_vaddr);
  225. }
  226. void Region::remap_page(size_t page_index)
  227. {
  228. ASSERT(m_page_directory);
  229. InterruptDisabler disabler;
  230. ASSERT(physical_page(page_index));
  231. map_individual_page_impl(page_index);
  232. }
  233. void Region::unmap(ShouldDeallocateVirtualMemoryRange deallocate_range)
  234. {
  235. InterruptDisabler disabler;
  236. ASSERT(m_page_directory);
  237. for (size_t i = 0; i < page_count(); ++i) {
  238. auto vaddr = this->vaddr().offset(i * PAGE_SIZE);
  239. auto& pte = MM.ensure_pte(*m_page_directory, vaddr);
  240. pte.clear();
  241. MM.flush_tlb(vaddr);
  242. #ifdef MM_DEBUG
  243. auto* page = physical_page(i);
  244. dbg() << "MM: >> Unmapped " << vaddr << " => P" << String::format("%p", page ? page->paddr().get() : 0) << " <<";
  245. #endif
  246. }
  247. if (deallocate_range == ShouldDeallocateVirtualMemoryRange::Yes) {
  248. if (m_page_directory->range_allocator().contains(range()))
  249. m_page_directory->range_allocator().deallocate(range());
  250. else
  251. m_page_directory->identity_range_allocator().deallocate(range());
  252. }
  253. m_page_directory = nullptr;
  254. }
  255. void Region::set_page_directory(PageDirectory& page_directory)
  256. {
  257. ASSERT(!m_page_directory || m_page_directory == &page_directory);
  258. InterruptDisabler disabler;
  259. m_page_directory = page_directory;
  260. }
  261. void Region::map(PageDirectory& page_directory)
  262. {
  263. set_page_directory(page_directory);
  264. InterruptDisabler disabler;
  265. #ifdef MM_DEBUG
  266. dbg() << "MM: Region::map() will map VMO pages " << first_page_index() << " - " << last_page_index() << " (VMO page count: " << vmobject().page_count() << ")";
  267. #endif
  268. for (size_t page_index = 0; page_index < page_count(); ++page_index)
  269. map_individual_page_impl(page_index);
  270. }
  271. void Region::remap()
  272. {
  273. ASSERT(m_page_directory);
  274. map(*m_page_directory);
  275. }
  276. PageFaultResponse Region::handle_fault(const PageFault& fault)
  277. {
  278. auto page_index_in_region = page_index_from_address(fault.vaddr());
  279. if (fault.type() == PageFault::Type::PageNotPresent) {
  280. if (fault.is_read() && !is_readable()) {
  281. dbg() << "NP(non-readable) fault in Region{" << this << "}[" << page_index_in_region << "]";
  282. return PageFaultResponse::ShouldCrash;
  283. }
  284. if (fault.is_write() && !is_writable()) {
  285. dbg() << "NP(non-writable) write fault in Region{" << this << "}[" << page_index_in_region << "] at " << fault.vaddr();
  286. return PageFaultResponse::ShouldCrash;
  287. }
  288. if (vmobject().is_inode()) {
  289. #ifdef PAGE_FAULT_DEBUG
  290. dbg() << "NP(inode) fault in Region{" << this << "}[" << page_index_in_region << "]";
  291. #endif
  292. return handle_inode_fault(page_index_in_region);
  293. }
  294. #ifdef MAP_SHARED_ZERO_PAGE_LAZILY
  295. if (fault.is_read()) {
  296. physical_page_slot(page_index_in_region) = MM.shared_zero_page();
  297. remap_page(page_index_in_region);
  298. return PageFaultResponse::Continue;
  299. }
  300. return handle_zero_fault(page_index_in_region);
  301. #else
  302. dbg() << "BUG! Unexpected NP fault at " << fault.vaddr();
  303. return PageFaultResponse::ShouldCrash;
  304. #endif
  305. }
  306. ASSERT(fault.type() == PageFault::Type::ProtectionViolation);
  307. if (fault.access() == PageFault::Access::Write && is_writable() && should_cow(page_index_in_region)) {
  308. #ifdef PAGE_FAULT_DEBUG
  309. dbg() << "PV(cow) fault in Region{" << this << "}[" << page_index_in_region << "]";
  310. #endif
  311. if (physical_page(page_index_in_region)->is_shared_zero_page()) {
  312. #ifdef PAGE_FAULT_DEBUG
  313. dbg() << "NP(zero) fault in Region{" << this << "}[" << page_index_in_region << "]";
  314. #endif
  315. return handle_zero_fault(page_index_in_region);
  316. }
  317. return handle_cow_fault(page_index_in_region);
  318. }
  319. dbg() << "PV(error) fault in Region{" << this << "}[" << page_index_in_region << "] at " << fault.vaddr();
  320. return PageFaultResponse::ShouldCrash;
  321. }
  322. PageFaultResponse Region::handle_zero_fault(size_t page_index_in_region)
  323. {
  324. ASSERT_INTERRUPTS_DISABLED();
  325. ASSERT(vmobject().is_anonymous());
  326. sti();
  327. LOCKER(vmobject().m_paging_lock);
  328. cli();
  329. auto& page_slot = physical_page_slot(page_index_in_region);
  330. if (!page_slot.is_null() && !page_slot->is_shared_zero_page()) {
  331. #ifdef PAGE_FAULT_DEBUG
  332. dbg() << "MM: zero_page() but page already present. Fine with me!";
  333. #endif
  334. remap_page(page_index_in_region);
  335. return PageFaultResponse::Continue;
  336. }
  337. auto current_thread = Thread::current();
  338. if (current_thread != nullptr)
  339. current_thread->did_zero_fault();
  340. auto page = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::Yes);
  341. if (page.is_null()) {
  342. klog() << "MM: handle_zero_fault was unable to allocate a physical page";
  343. return PageFaultResponse::OutOfMemory;
  344. }
  345. #ifdef PAGE_FAULT_DEBUG
  346. dbg() << " >> ZERO " << physical_page->paddr();
  347. #endif
  348. page_slot = move(page);
  349. remap_page(page_index_in_region);
  350. return PageFaultResponse::Continue;
  351. }
  352. PageFaultResponse Region::handle_cow_fault(size_t page_index_in_region)
  353. {
  354. ASSERT_INTERRUPTS_DISABLED();
  355. auto& page_slot = physical_page_slot(page_index_in_region);
  356. if (page_slot->ref_count() == 1) {
  357. #ifdef PAGE_FAULT_DEBUG
  358. dbg() << " >> It's a COW page but nobody is sharing it anymore. Remap r/w";
  359. #endif
  360. set_should_cow(page_index_in_region, false);
  361. remap_page(page_index_in_region);
  362. return PageFaultResponse::Continue;
  363. }
  364. auto current_thread = Thread::current();
  365. if (current_thread)
  366. current_thread->did_cow_fault();
  367. #ifdef PAGE_FAULT_DEBUG
  368. dbg() << " >> It's a COW page and it's time to COW!";
  369. #endif
  370. auto page = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::No);
  371. if (page.is_null()) {
  372. klog() << "MM: handle_cow_fault was unable to allocate a physical page";
  373. return PageFaultResponse::OutOfMemory;
  374. }
  375. auto physical_page_to_copy = move(page_slot);
  376. u8* dest_ptr = MM.quickmap_page(*page);
  377. const u8* src_ptr = vaddr().offset(page_index_in_region * PAGE_SIZE).as_ptr();
  378. #ifdef PAGE_FAULT_DEBUG
  379. dbg() << " >> COW " << physical_page->paddr() << " <- " << physical_page_to_copy->paddr();
  380. #endif
  381. copy_from_user(dest_ptr, src_ptr, PAGE_SIZE);
  382. page_slot = move(page);
  383. MM.unquickmap_page();
  384. set_should_cow(page_index_in_region, false);
  385. remap_page(page_index_in_region);
  386. return PageFaultResponse::Continue;
  387. }
  388. PageFaultResponse Region::handle_inode_fault(size_t page_index_in_region)
  389. {
  390. ASSERT_INTERRUPTS_DISABLED();
  391. ASSERT(vmobject().is_inode());
  392. sti();
  393. LOCKER(vmobject().m_paging_lock);
  394. cli();
  395. auto& inode_vmobject = static_cast<InodeVMObject&>(vmobject());
  396. auto& vmobject_physical_page_entry = inode_vmobject.physical_pages()[first_page_index() + page_index_in_region];
  397. #ifdef PAGE_FAULT_DEBUG
  398. dbg() << "Inode fault in " << name() << " page index: " << page_index_in_region;
  399. #endif
  400. if (!vmobject_physical_page_entry.is_null()) {
  401. #ifdef PAGE_FAULT_DEBUG
  402. dbg() << ("MM: page_in_from_inode() but page already present. Fine with me!");
  403. #endif
  404. remap_page(page_index_in_region);
  405. return PageFaultResponse::Continue;
  406. }
  407. auto current_thread = Thread::current();
  408. if (current_thread)
  409. current_thread->did_inode_fault();
  410. #ifdef MM_DEBUG
  411. dbg() << "MM: page_in_from_inode ready to read from inode";
  412. #endif
  413. sti();
  414. u8 page_buffer[PAGE_SIZE];
  415. auto& inode = inode_vmobject.inode();
  416. auto nread = inode.read_bytes((first_page_index() + page_index_in_region) * PAGE_SIZE, PAGE_SIZE, page_buffer, nullptr);
  417. if (nread < 0) {
  418. klog() << "MM: handle_inode_fault had error (" << nread << ") while reading!";
  419. return PageFaultResponse::ShouldCrash;
  420. }
  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. cli();
  426. vmobject_physical_page_entry = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::No);
  427. if (vmobject_physical_page_entry.is_null()) {
  428. klog() << "MM: handle_inode_fault was unable to allocate a physical page";
  429. return PageFaultResponse::OutOfMemory;
  430. }
  431. u8* dest_ptr = MM.quickmap_page(*vmobject_physical_page_entry);
  432. memcpy(dest_ptr, page_buffer, PAGE_SIZE);
  433. MM.unquickmap_page();
  434. remap_page(page_index_in_region);
  435. return PageFaultResponse::Continue;
  436. }
  437. }