Region.cpp 16 KB

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