AnonymousVMObject.cpp 17 KB

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