Region.cpp 18 KB

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