AnonymousVMObject.cpp 18 KB

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