AnonymousVMObject.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /*
  2. * Copyright (c) 2018-2021, 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/Arch/x86/SmapDisabler.h>
  27. #include <Kernel/Debug.h>
  28. #include <Kernel/Process.h>
  29. #include <Kernel/VM/AnonymousVMObject.h>
  30. #include <Kernel/VM/MemoryManager.h>
  31. #include <Kernel/VM/PhysicalPage.h>
  32. namespace Kernel {
  33. RefPtr<VMObject> AnonymousVMObject::clone()
  34. {
  35. // We need to acquire our lock so we copy a sane state
  36. ScopedSpinLock lock(m_lock);
  37. // We're the parent. Since we're about to become COW we need to
  38. // commit the number of pages that we need to potentially allocate
  39. // so that the parent is still guaranteed to be able to have all
  40. // non-volatile memory available.
  41. size_t need_cow_pages = 0;
  42. {
  43. // We definitely need to commit non-volatile areas
  44. for_each_nonvolatile_range([&](const VolatilePageRange& nonvolatile_range) {
  45. need_cow_pages += nonvolatile_range.count;
  46. return IterationDecision::Continue;
  47. });
  48. }
  49. dbgln_if(COMMIT_DEBUG, "Cloning {:p}, need {} committed cow pages", this, need_cow_pages);
  50. if (!MM.commit_user_physical_pages(need_cow_pages))
  51. return {};
  52. // Create or replace the committed cow pages. When cloning a previously
  53. // cloned vmobject, we want to essentially "fork", leaving us and the
  54. // new clone with one set of shared committed cow pages, and the original
  55. // one would keep the one it still has. This ensures that the original
  56. // one and this one, as well as the clone have sufficient resources
  57. // to cow all pages as needed
  58. m_shared_committed_cow_pages = adopt(*new CommittedCowPages(need_cow_pages));
  59. // Both original and clone become COW. So create a COW map for ourselves
  60. // or reset all pages to be copied again if we were previously cloned
  61. ensure_or_reset_cow_map();
  62. return adopt(*new AnonymousVMObject(*this));
  63. }
  64. RefPtr<AnonymousVMObject> AnonymousVMObject::create_with_size(size_t size, AllocationStrategy commit)
  65. {
  66. if (commit == AllocationStrategy::Reserve || commit == AllocationStrategy::AllocateNow) {
  67. // We need to attempt to commit before actually creating the object
  68. if (!MM.commit_user_physical_pages(ceil_div(size, static_cast<size_t>(PAGE_SIZE))))
  69. return {};
  70. }
  71. return adopt(*new AnonymousVMObject(size, commit));
  72. }
  73. NonnullRefPtr<AnonymousVMObject> AnonymousVMObject::create_with_physical_pages(NonnullRefPtrVector<PhysicalPage> physical_pages)
  74. {
  75. return adopt(*new AnonymousVMObject(physical_pages));
  76. }
  77. NonnullRefPtr<AnonymousVMObject> AnonymousVMObject::create_with_physical_page(PhysicalPage& page)
  78. {
  79. return adopt(*new AnonymousVMObject(page));
  80. }
  81. RefPtr<AnonymousVMObject> AnonymousVMObject::create_for_physical_range(PhysicalAddress paddr, size_t size)
  82. {
  83. if (paddr.offset(size) < paddr) {
  84. dbgln("Shenanigans! create_for_physical_range({}, {}) would wrap around", paddr, size);
  85. return nullptr;
  86. }
  87. return adopt(*new AnonymousVMObject(paddr, size));
  88. }
  89. AnonymousVMObject::AnonymousVMObject(size_t size, AllocationStrategy strategy)
  90. : VMObject(size)
  91. , m_volatile_ranges_cache({ 0, page_count() })
  92. , m_unused_committed_pages(strategy == AllocationStrategy::Reserve ? page_count() : 0)
  93. {
  94. if (strategy == AllocationStrategy::AllocateNow) {
  95. // Allocate all pages right now. We know we can get all because we committed the amount needed
  96. for (size_t i = 0; i < page_count(); ++i)
  97. physical_pages()[i] = MM.allocate_committed_user_physical_page(MemoryManager::ShouldZeroFill::Yes);
  98. } else {
  99. auto& initial_page = (strategy == AllocationStrategy::Reserve) ? MM.lazy_committed_page() : MM.shared_zero_page();
  100. for (size_t i = 0; i < page_count(); ++i)
  101. physical_pages()[i] = initial_page;
  102. }
  103. }
  104. AnonymousVMObject::AnonymousVMObject(PhysicalAddress paddr, size_t size)
  105. : VMObject(size)
  106. , m_volatile_ranges_cache({ 0, page_count() })
  107. {
  108. VERIFY(paddr.page_base() == paddr);
  109. for (size_t i = 0; i < page_count(); ++i)
  110. physical_pages()[i] = PhysicalPage::create(paddr.offset(i * PAGE_SIZE), false, false);
  111. }
  112. AnonymousVMObject::AnonymousVMObject(PhysicalPage& page)
  113. : VMObject(PAGE_SIZE)
  114. , m_volatile_ranges_cache({ 0, page_count() })
  115. {
  116. physical_pages()[0] = page;
  117. }
  118. AnonymousVMObject::AnonymousVMObject(NonnullRefPtrVector<PhysicalPage> physical_pages)
  119. : VMObject()
  120. , m_volatile_ranges_cache({ 0, page_count() })
  121. {
  122. for (auto& page : physical_pages) {
  123. m_physical_pages.append(page);
  124. }
  125. }
  126. AnonymousVMObject::AnonymousVMObject(const AnonymousVMObject& other)
  127. : VMObject(other)
  128. , m_volatile_ranges_cache({ 0, page_count() }) // do *not* clone this
  129. , m_volatile_ranges_cache_dirty(true) // do *not* clone this
  130. , m_purgeable_ranges() // do *not* clone this
  131. , m_unused_committed_pages(other.m_unused_committed_pages)
  132. , m_cow_map() // do *not* clone this
  133. , m_shared_committed_cow_pages(other.m_shared_committed_cow_pages) // share the pool
  134. {
  135. // We can't really "copy" a spinlock. But we're holding it. Clear in the clone
  136. VERIFY(other.m_lock.is_locked());
  137. m_lock.initialize();
  138. // The clone also becomes COW
  139. ensure_or_reset_cow_map();
  140. if (m_unused_committed_pages > 0) {
  141. // The original vmobject didn't use up all committed pages. When
  142. // cloning (fork) we will overcommit. For this purpose we drop all
  143. // lazy-commit references and replace them with shared zero pages.
  144. for (size_t i = 0; i < page_count(); i++) {
  145. auto& phys_page = m_physical_pages[i];
  146. if (phys_page && phys_page->is_lazy_committed_page()) {
  147. phys_page = MM.shared_zero_page();
  148. if (--m_unused_committed_pages == 0)
  149. break;
  150. }
  151. }
  152. VERIFY(m_unused_committed_pages == 0);
  153. }
  154. }
  155. AnonymousVMObject::~AnonymousVMObject()
  156. {
  157. // Return any unused committed pages
  158. if (m_unused_committed_pages > 0)
  159. MM.uncommit_user_physical_pages(m_unused_committed_pages);
  160. }
  161. int AnonymousVMObject::purge()
  162. {
  163. LOCKER(m_paging_lock);
  164. return purge_impl();
  165. }
  166. int AnonymousVMObject::purge_with_interrupts_disabled(Badge<MemoryManager>)
  167. {
  168. VERIFY_INTERRUPTS_DISABLED();
  169. if (m_paging_lock.is_locked())
  170. return 0;
  171. return purge_impl();
  172. }
  173. void AnonymousVMObject::set_was_purged(const VolatilePageRange& range)
  174. {
  175. VERIFY(m_lock.is_locked());
  176. for (auto* purgeable_ranges : m_purgeable_ranges)
  177. purgeable_ranges->set_was_purged(range);
  178. }
  179. int AnonymousVMObject::purge_impl()
  180. {
  181. int purged_page_count = 0;
  182. ScopedSpinLock lock(m_lock);
  183. for_each_volatile_range([&](const auto& range) {
  184. int purged_in_range = 0;
  185. auto range_end = range.base + range.count;
  186. for (size_t i = range.base; i < range_end; i++) {
  187. auto& phys_page = m_physical_pages[i];
  188. if (phys_page && !phys_page->is_shared_zero_page()) {
  189. VERIFY(!phys_page->is_lazy_committed_page());
  190. ++purged_in_range;
  191. }
  192. phys_page = MM.shared_zero_page();
  193. }
  194. if (purged_in_range > 0) {
  195. purged_page_count += purged_in_range;
  196. set_was_purged(range);
  197. for_each_region([&](auto& region) {
  198. if (&region.vmobject() == this) {
  199. if (auto owner = region.get_owner()) {
  200. // we need to hold a reference the process here (if there is one) as we may not own this region
  201. dmesgln("Purged {} pages from region {} owned by {} at {} - {}",
  202. purged_in_range,
  203. region.name(),
  204. *owner,
  205. region.vaddr_from_page_index(range.base),
  206. region.vaddr_from_page_index(range.base + range.count));
  207. } else {
  208. dmesgln("Purged {} pages from region {} (no ownership) at {} - {}",
  209. purged_in_range,
  210. region.name(),
  211. region.vaddr_from_page_index(range.base),
  212. region.vaddr_from_page_index(range.base + range.count));
  213. }
  214. region.remap_vmobject_page_range(range.base, range.count);
  215. }
  216. });
  217. }
  218. return IterationDecision::Continue;
  219. });
  220. return purged_page_count;
  221. }
  222. void AnonymousVMObject::register_purgeable_page_ranges(PurgeablePageRanges& purgeable_page_ranges)
  223. {
  224. ScopedSpinLock lock(m_lock);
  225. purgeable_page_ranges.set_vmobject(this);
  226. VERIFY(!m_purgeable_ranges.contains_slow(&purgeable_page_ranges));
  227. m_purgeable_ranges.append(&purgeable_page_ranges);
  228. }
  229. void AnonymousVMObject::unregister_purgeable_page_ranges(PurgeablePageRanges& purgeable_page_ranges)
  230. {
  231. ScopedSpinLock lock(m_lock);
  232. for (size_t i = 0; i < m_purgeable_ranges.size(); i++) {
  233. if (m_purgeable_ranges[i] != &purgeable_page_ranges)
  234. continue;
  235. purgeable_page_ranges.set_vmobject(nullptr);
  236. m_purgeable_ranges.remove(i);
  237. return;
  238. }
  239. VERIFY_NOT_REACHED();
  240. }
  241. bool AnonymousVMObject::is_any_volatile() const
  242. {
  243. ScopedSpinLock lock(m_lock);
  244. for (auto& volatile_ranges : m_purgeable_ranges) {
  245. ScopedSpinLock lock(volatile_ranges->m_volatile_ranges_lock);
  246. if (!volatile_ranges->is_empty())
  247. return true;
  248. }
  249. return false;
  250. }
  251. size_t AnonymousVMObject::remove_lazy_commit_pages(const VolatilePageRange& range)
  252. {
  253. VERIFY(m_lock.is_locked());
  254. size_t removed_count = 0;
  255. auto range_end = range.base + range.count;
  256. for (size_t i = range.base; i < range_end; i++) {
  257. auto& phys_page = m_physical_pages[i];
  258. if (phys_page && phys_page->is_lazy_committed_page()) {
  259. phys_page = MM.shared_zero_page();
  260. removed_count++;
  261. VERIFY(m_unused_committed_pages > 0);
  262. if (--m_unused_committed_pages == 0)
  263. break;
  264. }
  265. }
  266. return removed_count;
  267. }
  268. void AnonymousVMObject::update_volatile_cache()
  269. {
  270. VERIFY(m_lock.is_locked());
  271. VERIFY(m_volatile_ranges_cache_dirty);
  272. m_volatile_ranges_cache.clear();
  273. for_each_nonvolatile_range([&](const VolatilePageRange& range) {
  274. m_volatile_ranges_cache.add_unchecked(range);
  275. return IterationDecision::Continue;
  276. });
  277. m_volatile_ranges_cache_dirty = false;
  278. }
  279. void AnonymousVMObject::range_made_volatile(const VolatilePageRange& range)
  280. {
  281. VERIFY(m_lock.is_locked());
  282. if (m_unused_committed_pages == 0)
  283. return;
  284. // We need to check this range for any pages that are marked for
  285. // lazy committed allocation and turn them into shared zero pages
  286. // and also adjust the m_unused_committed_pages for each such page.
  287. // Take into account all the other views as well.
  288. size_t uncommit_page_count = 0;
  289. for_each_volatile_range([&](const auto& r) {
  290. auto intersected = range.intersected(r);
  291. if (!intersected.is_empty()) {
  292. uncommit_page_count += remove_lazy_commit_pages(intersected);
  293. if (m_unused_committed_pages == 0)
  294. return IterationDecision::Break;
  295. }
  296. return IterationDecision::Continue;
  297. });
  298. // Return those committed pages back to the system
  299. if (uncommit_page_count > 0) {
  300. dbgln_if(COMMIT_DEBUG, "Uncommit {} lazy-commit pages from {:p}", uncommit_page_count, this);
  301. MM.uncommit_user_physical_pages(uncommit_page_count);
  302. }
  303. m_volatile_ranges_cache_dirty = true;
  304. }
  305. void AnonymousVMObject::range_made_nonvolatile(const VolatilePageRange&)
  306. {
  307. VERIFY(m_lock.is_locked());
  308. m_volatile_ranges_cache_dirty = true;
  309. }
  310. size_t AnonymousVMObject::count_needed_commit_pages_for_nonvolatile_range(const VolatilePageRange& range)
  311. {
  312. VERIFY(m_lock.is_locked());
  313. VERIFY(!range.is_empty());
  314. size_t need_commit_pages = 0;
  315. auto range_end = range.base + range.count;
  316. for (size_t page_index = range.base; page_index < range_end; page_index++) {
  317. // COW pages are accounted for in m_shared_committed_cow_pages
  318. if (!m_cow_map.is_null() && m_cow_map.get(page_index))
  319. continue;
  320. auto& phys_page = m_physical_pages[page_index];
  321. if (phys_page && phys_page->is_shared_zero_page())
  322. need_commit_pages++;
  323. }
  324. return need_commit_pages;
  325. }
  326. size_t AnonymousVMObject::mark_committed_pages_for_nonvolatile_range(const VolatilePageRange& range, size_t mark_total)
  327. {
  328. VERIFY(m_lock.is_locked());
  329. VERIFY(!range.is_empty());
  330. VERIFY(mark_total > 0);
  331. size_t pages_updated = 0;
  332. auto range_end = range.base + range.count;
  333. for (size_t page_index = range.base; page_index < range_end; page_index++) {
  334. // COW pages are accounted for in m_shared_committed_cow_pages
  335. if (!m_cow_map.is_null() && m_cow_map.get(page_index))
  336. continue;
  337. auto& phys_page = m_physical_pages[page_index];
  338. if (phys_page && phys_page->is_shared_zero_page()) {
  339. phys_page = MM.lazy_committed_page();
  340. if (++pages_updated == mark_total)
  341. break;
  342. }
  343. }
  344. dbgln_if(COMMIT_DEBUG, "Added {} lazy-commit pages to {:p}", pages_updated, this);
  345. m_unused_committed_pages += pages_updated;
  346. return pages_updated;
  347. }
  348. RefPtr<PhysicalPage> AnonymousVMObject::allocate_committed_page(size_t page_index)
  349. {
  350. {
  351. ScopedSpinLock lock(m_lock);
  352. VERIFY(m_unused_committed_pages > 0);
  353. // We shouldn't have any committed page tags in volatile regions
  354. VERIFY([&]() {
  355. for (auto* purgeable_ranges : m_purgeable_ranges) {
  356. if (purgeable_ranges->is_volatile(page_index))
  357. return false;
  358. }
  359. return true;
  360. }());
  361. m_unused_committed_pages--;
  362. }
  363. return MM.allocate_committed_user_physical_page(MemoryManager::ShouldZeroFill::Yes);
  364. }
  365. Bitmap& AnonymousVMObject::ensure_cow_map()
  366. {
  367. if (m_cow_map.is_null())
  368. m_cow_map = Bitmap { page_count(), true };
  369. return m_cow_map;
  370. }
  371. void AnonymousVMObject::ensure_or_reset_cow_map()
  372. {
  373. if (m_cow_map.is_null())
  374. ensure_cow_map();
  375. else
  376. m_cow_map.fill(true);
  377. }
  378. bool AnonymousVMObject::should_cow(size_t page_index, bool is_shared) const
  379. {
  380. auto& page = physical_pages()[page_index];
  381. if (page && (page->is_shared_zero_page() || page->is_lazy_committed_page()))
  382. return true;
  383. if (is_shared)
  384. return false;
  385. return !m_cow_map.is_null() && m_cow_map.get(page_index);
  386. }
  387. void AnonymousVMObject::set_should_cow(size_t page_index, bool cow)
  388. {
  389. ensure_cow_map().set(page_index, cow);
  390. }
  391. size_t AnonymousVMObject::cow_pages() const
  392. {
  393. if (m_cow_map.is_null())
  394. return 0;
  395. return m_cow_map.count_slow(true);
  396. }
  397. bool AnonymousVMObject::is_nonvolatile(size_t page_index)
  398. {
  399. if (m_volatile_ranges_cache_dirty)
  400. update_volatile_cache();
  401. return !m_volatile_ranges_cache.contains(page_index);
  402. }
  403. PageFaultResponse AnonymousVMObject::handle_cow_fault(size_t page_index, VirtualAddress vaddr)
  404. {
  405. VERIFY_INTERRUPTS_DISABLED();
  406. ScopedSpinLock lock(m_lock);
  407. auto& page_slot = physical_pages()[page_index];
  408. bool have_committed = m_shared_committed_cow_pages && is_nonvolatile(page_index);
  409. if (page_slot->ref_count() == 1) {
  410. #if PAGE_FAULT_DEBUG
  411. dbgln(" >> It's a COW page but nobody is sharing it anymore. Remap r/w");
  412. #endif
  413. set_should_cow(page_index, false);
  414. if (have_committed) {
  415. if (m_shared_committed_cow_pages->return_one())
  416. m_shared_committed_cow_pages = nullptr;
  417. }
  418. return PageFaultResponse::Continue;
  419. }
  420. RefPtr<PhysicalPage> page;
  421. if (have_committed) {
  422. #if PAGE_FAULT_DEBUG
  423. dbgln(" >> It's a committed COW page and it's time to COW!");
  424. #endif
  425. page = m_shared_committed_cow_pages->allocate_one();
  426. } else {
  427. #if PAGE_FAULT_DEBUG
  428. dbgln(" >> It's a COW page and it's time to COW!");
  429. #endif
  430. page = MM.allocate_user_physical_page(MemoryManager::ShouldZeroFill::No);
  431. if (page.is_null()) {
  432. dmesgln("MM: handle_cow_fault was unable to allocate a physical page");
  433. return PageFaultResponse::OutOfMemory;
  434. }
  435. }
  436. u8* dest_ptr = MM.quickmap_page(*page);
  437. dbgln_if(PAGE_FAULT_DEBUG, " >> COW {} <- {}", page->paddr(), page_slot->paddr());
  438. {
  439. SmapDisabler disabler;
  440. void* fault_at;
  441. if (!safe_memcpy(dest_ptr, vaddr.as_ptr(), PAGE_SIZE, fault_at)) {
  442. if ((u8*)fault_at >= dest_ptr && (u8*)fault_at <= dest_ptr + PAGE_SIZE)
  443. dbgln(" >> COW: error copying page {}/{} to {}/{}: failed to write to page at {}",
  444. page_slot->paddr(), vaddr, page->paddr(), VirtualAddress(dest_ptr), VirtualAddress(fault_at));
  445. else if ((u8*)fault_at >= vaddr.as_ptr() && (u8*)fault_at <= vaddr.as_ptr() + PAGE_SIZE)
  446. dbgln(" >> COW: error copying page {}/{} to {}/{}: failed to read from page at {}",
  447. page_slot->paddr(), vaddr, page->paddr(), VirtualAddress(dest_ptr), VirtualAddress(fault_at));
  448. else
  449. VERIFY_NOT_REACHED();
  450. }
  451. }
  452. page_slot = move(page);
  453. MM.unquickmap_page();
  454. set_should_cow(page_index, false);
  455. return PageFaultResponse::Continue;
  456. }
  457. }