Region.cpp 18 KB

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