Region.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. return region;
  92. }
  93. #ifdef MM_DEBUG
  94. dbgprintf("%s<%u> Region::clone(): cowing %s (V%p)\n",
  95. current->process().name().characters(),
  96. current->pid(),
  97. m_name.characters(),
  98. vaddr().get());
  99. #endif
  100. // Set up a COW region. The parent (this) region becomes COW as well!
  101. ensure_cow_map().fill(true);
  102. remap();
  103. auto clone_region = Region::create_user_accessible(m_range, m_vmobject->clone(), m_offset_in_vmobject, m_name, m_access);
  104. clone_region->ensure_cow_map();
  105. if (m_stack) {
  106. ASSERT(is_readable());
  107. ASSERT(is_writable());
  108. ASSERT(!is_shared());
  109. ASSERT(vmobject().is_anonymous());
  110. clone_region->set_stack(true);
  111. }
  112. clone_region->set_mmap(m_mmap);
  113. return clone_region;
  114. }
  115. bool Region::commit()
  116. {
  117. InterruptDisabler disabler;
  118. #ifdef MM_DEBUG
  119. dbgprintf("MM: commit %u pages in Region %p (VMO=%p) at V%p\n", vmobject().page_count(), this, &vmobject(), vaddr().get());
  120. #endif
  121. for (size_t i = 0; i < page_count(); ++i) {
  122. if (!commit(i))
  123. return false;
  124. }
  125. return true;
  126. }
  127. bool Region::commit(size_t page_index)
  128. {
  129. ASSERT(vmobject().is_anonymous() || vmobject().is_purgeable());
  130. InterruptDisabler disabler;
  131. #ifdef MM_DEBUG
  132. dbgprintf("MM: commit single page (%zu) in Region %p (VMO=%p) at V%p\n", page_index, vmobject().page_count(), this, &vmobject(), vaddr().get());
  133. #endif
  134. auto& vmobject_physical_page_entry = vmobject().physical_pages()[first_page_index() + page_index];
  135. if (!vmobject_physical_page_entry.is_null())
  136. return true;
  137. auto physical_page = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::Yes);
  138. if (!physical_page) {
  139. kprintf("MM: commit was unable to allocate a physical page\n");
  140. return false;
  141. }
  142. vmobject_physical_page_entry = move(physical_page);
  143. remap_page(page_index);
  144. return true;
  145. }
  146. u32 Region::cow_pages() const
  147. {
  148. if (!m_cow_map)
  149. return 0;
  150. u32 count = 0;
  151. for (int i = 0; i < m_cow_map->size(); ++i)
  152. count += m_cow_map->get(i);
  153. return count;
  154. }
  155. size_t Region::amount_dirty() const
  156. {
  157. if (!vmobject().is_inode())
  158. return amount_resident();
  159. return static_cast<const InodeVMObject&>(vmobject()).amount_dirty();
  160. }
  161. size_t Region::amount_resident() const
  162. {
  163. size_t bytes = 0;
  164. for (size_t i = 0; i < page_count(); ++i) {
  165. if (m_vmobject->physical_pages()[first_page_index() + i])
  166. bytes += PAGE_SIZE;
  167. }
  168. return bytes;
  169. }
  170. size_t Region::amount_shared() const
  171. {
  172. size_t bytes = 0;
  173. for (size_t i = 0; i < page_count(); ++i) {
  174. auto& physical_page = m_vmobject->physical_pages()[first_page_index() + i];
  175. if (physical_page && physical_page->ref_count() > 1)
  176. bytes += PAGE_SIZE;
  177. }
  178. return bytes;
  179. }
  180. NonnullOwnPtr<Region> Region::create_user_accessible(const Range& range, const StringView& name, u8 access, bool cacheable)
  181. {
  182. auto region = make<Region>(range, name, access, cacheable);
  183. region->m_user_accessible = true;
  184. return region;
  185. }
  186. NonnullOwnPtr<Region> Region::create_user_accessible(const Range& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const StringView& name, u8 access, bool cacheable)
  187. {
  188. auto region = make<Region>(range, move(vmobject), offset_in_vmobject, name, access, cacheable);
  189. region->m_user_accessible = true;
  190. return region;
  191. }
  192. NonnullOwnPtr<Region> Region::create_user_accessible(const Range& range, NonnullRefPtr<Inode> inode, const StringView& name, u8 access, bool cacheable)
  193. {
  194. auto region = make<Region>(range, move(inode), name, access, cacheable);
  195. region->m_user_accessible = true;
  196. return region;
  197. }
  198. NonnullOwnPtr<Region> Region::create_kernel_only(const Range& range, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const StringView& name, u8 access, bool cacheable)
  199. {
  200. auto region = make<Region>(range, move(vmobject), offset_in_vmobject, name, access, cacheable);
  201. region->m_user_accessible = false;
  202. return region;
  203. }
  204. NonnullOwnPtr<Region> Region::create_kernel_only(const Range& range, const StringView& name, u8 access, bool cacheable)
  205. {
  206. auto region = make<Region>(range, name, access, cacheable);
  207. region->m_user_accessible = false;
  208. return region;
  209. }
  210. bool Region::should_cow(size_t page_index) const
  211. {
  212. if (m_shared)
  213. return false;
  214. return m_cow_map && m_cow_map->get(page_index);
  215. }
  216. void Region::set_should_cow(size_t page_index, bool cow)
  217. {
  218. ASSERT(!m_shared);
  219. ensure_cow_map().set(page_index, cow);
  220. }
  221. Bitmap& Region::ensure_cow_map() const
  222. {
  223. if (!m_cow_map)
  224. m_cow_map = make<Bitmap>(page_count(), true);
  225. return *m_cow_map;
  226. }
  227. void Region::map_individual_page_impl(size_t page_index)
  228. {
  229. auto page_vaddr = vaddr().offset(page_index * PAGE_SIZE);
  230. auto& pte = MM.ensure_pte(*m_page_directory, page_vaddr);
  231. auto& physical_page = vmobject().physical_pages()[first_page_index() + page_index];
  232. if (!physical_page) {
  233. pte.set_physical_page_base(0);
  234. pte.set_present(false);
  235. } else {
  236. pte.set_cache_disabled(!m_cacheable);
  237. pte.set_physical_page_base(physical_page->paddr().get());
  238. pte.set_present(true);
  239. if (should_cow(page_index))
  240. pte.set_writable(false);
  241. else
  242. pte.set_writable(is_writable());
  243. if (g_cpu_supports_nx)
  244. pte.set_execute_disabled(!is_executable());
  245. pte.set_user_allowed(is_user_accessible());
  246. #ifdef MM_DEBUG
  247. dbg() << "MM: >> region map (PD=" << m_page_directory->cr3() << ", PTE=" << (void*)pte.raw() << "{" << &pte << "}) " << name() << " " << page_vaddr << " => " << physical_page->paddr() << " (@" << physical_page.ptr() << ")";
  248. #endif
  249. }
  250. MM.flush_tlb(page_vaddr);
  251. }
  252. void Region::remap_page(size_t page_index)
  253. {
  254. ASSERT(m_page_directory);
  255. InterruptDisabler disabler;
  256. ASSERT(vmobject().physical_pages()[first_page_index() + page_index]);
  257. map_individual_page_impl(page_index);
  258. }
  259. void Region::unmap(ShouldDeallocateVirtualMemoryRange deallocate_range)
  260. {
  261. InterruptDisabler disabler;
  262. ASSERT(m_page_directory);
  263. for (size_t i = 0; i < page_count(); ++i) {
  264. auto vaddr = this->vaddr().offset(i * PAGE_SIZE);
  265. auto& pte = MM.ensure_pte(*m_page_directory, vaddr);
  266. pte.set_physical_page_base(0);
  267. pte.set_present(false);
  268. pte.set_writable(false);
  269. pte.set_user_allowed(false);
  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 PAGE_FAULT_DEBUG
  316. dbgprintf("NP(zero) fault in Region{%p}[%u]\n", this, page_index_in_region);
  317. #endif
  318. return handle_zero_fault(page_index_in_region);
  319. }
  320. ASSERT(fault.type() == PageFault::Type::ProtectionViolation);
  321. if (fault.access() == PageFault::Access::Write && is_writable() && should_cow(page_index_in_region)) {
  322. #ifdef PAGE_FAULT_DEBUG
  323. dbgprintf("PV(cow) fault in Region{%p}[%u]\n", this, page_index_in_region);
  324. #endif
  325. return handle_cow_fault(page_index_in_region);
  326. }
  327. kprintf("PV(error) fault in Region{%p}[%u] at V%p\n", this, page_index_in_region, fault.vaddr().get());
  328. return PageFaultResponse::ShouldCrash;
  329. }
  330. PageFaultResponse Region::handle_zero_fault(size_t page_index_in_region)
  331. {
  332. ASSERT_INTERRUPTS_DISABLED();
  333. ASSERT(vmobject().is_anonymous());
  334. sti();
  335. LOCKER(vmobject().m_paging_lock);
  336. cli();
  337. auto& vmobject_physical_page_entry = vmobject().physical_pages()[first_page_index() + page_index_in_region];
  338. if (!vmobject_physical_page_entry.is_null()) {
  339. #ifdef PAGE_FAULT_DEBUG
  340. dbgprintf("MM: zero_page() but page already present. Fine with me!\n");
  341. #endif
  342. remap_page(page_index_in_region);
  343. return PageFaultResponse::Continue;
  344. }
  345. if (current)
  346. current->did_zero_fault();
  347. auto physical_page = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::Yes);
  348. if (physical_page.is_null()) {
  349. kprintf("MM: handle_zero_fault was unable to allocate a physical page\n");
  350. return PageFaultResponse::ShouldCrash;
  351. }
  352. #ifdef PAGE_FAULT_DEBUG
  353. dbgprintf(" >> ZERO P%p\n", physical_page->paddr().get());
  354. #endif
  355. vmobject_physical_page_entry = move(physical_page);
  356. remap_page(page_index_in_region);
  357. return PageFaultResponse::Continue;
  358. }
  359. PageFaultResponse Region::handle_cow_fault(size_t page_index_in_region)
  360. {
  361. ASSERT_INTERRUPTS_DISABLED();
  362. auto& vmobject_physical_page_entry = vmobject().physical_pages()[first_page_index() + page_index_in_region];
  363. if (vmobject_physical_page_entry->ref_count() == 1) {
  364. #ifdef PAGE_FAULT_DEBUG
  365. dbgprintf(" >> It's a COW page but nobody is sharing it anymore. Remap r/w\n");
  366. #endif
  367. set_should_cow(page_index_in_region, false);
  368. remap_page(page_index_in_region);
  369. return PageFaultResponse::Continue;
  370. }
  371. if (current)
  372. current->did_cow_fault();
  373. #ifdef PAGE_FAULT_DEBUG
  374. dbgprintf(" >> It's a COW page and it's time to COW!\n");
  375. #endif
  376. auto physical_page_to_copy = move(vmobject_physical_page_entry);
  377. auto physical_page = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::No);
  378. if (physical_page.is_null()) {
  379. kprintf("MM: handle_cow_fault was unable to allocate a physical page\n");
  380. return PageFaultResponse::ShouldCrash;
  381. }
  382. u8* dest_ptr = MM.quickmap_page(*physical_page);
  383. const u8* src_ptr = vaddr().offset(page_index_in_region * PAGE_SIZE).as_ptr();
  384. #ifdef PAGE_FAULT_DEBUG
  385. dbgprintf(" >> COW P%p <- P%p\n", physical_page->paddr().get(), physical_page_to_copy->paddr().get());
  386. #endif
  387. copy_from_user(dest_ptr, src_ptr, PAGE_SIZE);
  388. vmobject_physical_page_entry = move(physical_page);
  389. MM.unquickmap_page();
  390. set_should_cow(page_index_in_region, false);
  391. remap_page(page_index_in_region);
  392. return PageFaultResponse::Continue;
  393. }
  394. PageFaultResponse Region::handle_inode_fault(size_t page_index_in_region)
  395. {
  396. ASSERT_INTERRUPTS_DISABLED();
  397. ASSERT(vmobject().is_inode());
  398. auto& inode_vmobject = static_cast<InodeVMObject&>(vmobject());
  399. auto& vmobject_physical_page_entry = inode_vmobject.physical_pages()[first_page_index() + page_index_in_region];
  400. sti();
  401. LOCKER(vmobject().m_paging_lock);
  402. cli();
  403. #ifdef PAGE_FAULT_DEBUG
  404. dbg() << "Inode fault in " << name() << " page index: " << page_index_in_region;
  405. #endif
  406. if (!vmobject_physical_page_entry.is_null()) {
  407. #ifdef PAGE_FAULT_DEBUG
  408. dbgprintf("MM: page_in_from_inode() but page already present. Fine with me!\n");
  409. #endif
  410. remap_page(page_index_in_region);
  411. return PageFaultResponse::Continue;
  412. }
  413. if (current)
  414. current->did_inode_fault();
  415. #ifdef MM_DEBUG
  416. dbgprintf("MM: page_in_from_inode ready to read from inode\n");
  417. #endif
  418. sti();
  419. u8 page_buffer[PAGE_SIZE];
  420. auto& inode = inode_vmobject.inode();
  421. auto nread = inode.read_bytes((first_page_index() + page_index_in_region) * PAGE_SIZE, PAGE_SIZE, page_buffer, nullptr);
  422. if (nread < 0) {
  423. kprintf("MM: handle_inode_fault had error (%d) while reading!\n", nread);
  424. return PageFaultResponse::ShouldCrash;
  425. }
  426. if (nread < PAGE_SIZE) {
  427. // If we read less than a page, zero out the rest to avoid leaking uninitialized data.
  428. memset(page_buffer + nread, 0, PAGE_SIZE - nread);
  429. }
  430. cli();
  431. vmobject_physical_page_entry = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::No);
  432. if (vmobject_physical_page_entry.is_null()) {
  433. kprintf("MM: handle_inode_fault was unable to allocate a physical page\n");
  434. return PageFaultResponse::ShouldCrash;
  435. }
  436. u8* dest_ptr = MM.quickmap_page(*vmobject_physical_page_entry);
  437. memcpy(dest_ptr, page_buffer, PAGE_SIZE);
  438. MM.unquickmap_page();
  439. remap_page(page_index_in_region);
  440. return PageFaultResponse::Continue;
  441. }