2 * Copyright (C) 2013, 2014 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
27 #include "IOSurfacePool.h"
31 #include "GraphicsContextCG.h"
32 #include "IOSurface.h"
33 #include <CoreGraphics/CoreGraphics.h>
35 #include <wtf/NeverDestroyed.h>
37 const std::chrono::milliseconds collectionInterval = 500_ms;
38 const std::chrono::seconds surfaceAgeBeforeMarkingPurgeable = 2_s;
39 const size_t defaultMaximumBytesCached = 1024 * 1024 * 64;
41 // We'll never allow more than 1/2 of the cache to be filled with in-use surfaces, because
42 // they can't be immediately returned when requested (but will be freed up in the future).
43 const size_t maximumInUseBytes = defaultMaximumBytesCached / 2;
45 #define ENABLE_IOSURFACE_POOL_STATISTICS false
46 #if ENABLE_IOSURFACE_POOL_STATISTICS
47 #define DUMP_POOL_STATISTICS() do { showPoolStatistics(); } while (0);
49 #define DUMP_POOL_STATISTICS() ((void)0)
54 IOSurfacePool::IOSurfacePool()
55 : m_collectionTimer(this, &IOSurfacePool::collectionTimerFired)
57 , m_inUseBytesCached(0)
58 , m_maximumBytesCached(defaultMaximumBytesCached)
62 IOSurfacePool& IOSurfacePool::sharedPool()
64 static NeverDestroyed<IOSurfacePool> pool;
68 static bool surfaceMatchesParameters(IOSurface& surface, const IntSize& requestedSize, ColorSpace colorSpace)
70 IntSize surfaceSize = surface.size();
71 if (colorSpace != surface.colorSpace())
73 if (surfaceSize != requestedSize)
78 void IOSurfacePool::willAddSurface(IOSurface* surface, bool inUse)
80 CachedSurfaceDetails& details = m_surfaceDetails.add(surface, CachedSurfaceDetails()).iterator->value;
81 details.resetLastUseTime();
83 surface->clearGraphicsContext();
85 size_t surfaceBytes = surface->totalBytes();
86 m_bytesCached += surfaceBytes;
88 m_inUseBytesCached += surfaceBytes;
89 evict(surface->totalBytes());
92 void IOSurfacePool::didRemoveSurface(IOSurface* surface, bool inUse)
94 size_t surfaceBytes = surface->totalBytes();
95 m_bytesCached -= surfaceBytes;
97 m_inUseBytesCached -= surfaceBytes;
99 m_surfaceDetails.remove(surface);
102 void IOSurfacePool::didUseSurfaceOfSize(IntSize size)
104 m_sizesInPruneOrder.remove(m_sizesInPruneOrder.reverseFind(size));
105 m_sizesInPruneOrder.append(size);
108 PassRefPtr<IOSurface> IOSurfacePool::takeSurface(IntSize size, ColorSpace colorSpace)
110 CachedSurfaceMap::iterator mapIter = m_cachedSurfaces.find(size);
112 if (mapIter == m_cachedSurfaces.end()) {
113 DUMP_POOL_STATISTICS();
117 for (auto surfaceIter = mapIter->value.begin(); surfaceIter != mapIter->value.end(); ++surfaceIter) {
118 if (!surfaceMatchesParameters(*surfaceIter->get(), size, colorSpace))
121 RefPtr<IOSurface> surface = surfaceIter->get();
122 mapIter->value.remove(surfaceIter);
124 didUseSurfaceOfSize(size);
126 if (mapIter->value.isEmpty()) {
127 m_cachedSurfaces.remove(mapIter);
128 m_sizesInPruneOrder.removeLast();
131 didRemoveSurface(surface.get(), false);
133 surface->setIsVolatile(false);
135 DUMP_POOL_STATISTICS();
136 return surface.release();
139 // Some of the in-use surfaces may no longer actually be in-use, but we haven't moved them over yet.
140 for (auto surfaceIter = m_inUseSurfaces.begin(); surfaceIter != m_inUseSurfaces.end(); ++surfaceIter) {
141 if (!surfaceMatchesParameters(*surfaceIter->get(), size, colorSpace))
143 if (surfaceIter->get()->isInUse())
146 RefPtr<IOSurface> surface = surfaceIter->get();
147 m_inUseSurfaces.remove(surfaceIter);
148 didRemoveSurface(surface.get(), true);
150 surface->setIsVolatile(false);
152 DUMP_POOL_STATISTICS();
153 return surface.release();
156 DUMP_POOL_STATISTICS();
160 void IOSurfacePool::addSurface(IOSurface* surface)
162 if (surface->totalBytes() > m_maximumBytesCached)
165 bool surfaceIsInUse = surface->isInUse();
167 willAddSurface(surface, surfaceIsInUse);
169 if (surfaceIsInUse) {
170 m_inUseSurfaces.prepend(surface);
171 scheduleCollectionTimer();
172 DUMP_POOL_STATISTICS();
176 insertSurfaceIntoPool(surface);
177 DUMP_POOL_STATISTICS();
180 void IOSurfacePool::insertSurfaceIntoPool(IOSurface* surface)
182 auto insertedTuple = m_cachedSurfaces.add(surface->size(), CachedSurfaceQueue());
183 insertedTuple.iterator->value.prepend(surface);
184 if (!insertedTuple.isNewEntry)
185 m_sizesInPruneOrder.remove(m_sizesInPruneOrder.reverseFind(surface->size()));
186 m_sizesInPruneOrder.append(surface->size());
188 scheduleCollectionTimer();
191 void IOSurfacePool::setPoolSize(size_t poolSizeInBytes)
193 m_maximumBytesCached = poolSizeInBytes;
197 void IOSurfacePool::tryEvictInUseSurface()
199 if (m_inUseSurfaces.isEmpty())
202 RefPtr<IOSurface> surface = m_inUseSurfaces.takeLast();
203 didRemoveSurface(surface.get(), true);
206 void IOSurfacePool::tryEvictOldestCachedSurface()
208 if (m_cachedSurfaces.isEmpty())
211 if (m_sizesInPruneOrder.isEmpty())
214 CachedSurfaceMap::iterator surfaceQueueIter = m_cachedSurfaces.find(m_sizesInPruneOrder.first());
215 ASSERT(!surfaceQueueIter->value.isEmpty());
216 RefPtr<IOSurface> surface = surfaceQueueIter->value.takeLast();
217 didRemoveSurface(surface.get(), false);
219 if (surfaceQueueIter->value.isEmpty()) {
220 m_cachedSurfaces.remove(surfaceQueueIter);
221 m_sizesInPruneOrder.remove(0);
225 void IOSurfacePool::evict(size_t additionalSize)
227 // FIXME: Perhaps purgeable surfaces should count less against the cap?
228 // We don't want to end up with a ton of empty (purged) surfaces, though, as that would defeat the purpose of the pool.
229 size_t targetSize = m_maximumBytesCached - additionalSize;
231 // Interleave eviction of old cached surfaces and more recent in-use surfaces.
232 // In-use surfaces are more recently used, but less useful in the pool, as they aren't
233 // immediately available when requested.
234 while (m_bytesCached > targetSize) {
235 tryEvictOldestCachedSurface();
237 if (m_inUseBytesCached > maximumInUseBytes)
238 tryEvictInUseSurface();
241 while (m_inUseBytesCached > maximumInUseBytes)
242 tryEvictInUseSurface();
245 void IOSurfacePool::collectInUseSurfaces()
247 CachedSurfaceQueue newInUseSurfaces;
248 for (CachedSurfaceQueue::iterator surfaceIter = m_inUseSurfaces.begin(); surfaceIter != m_inUseSurfaces.end(); ++surfaceIter) {
249 IOSurface* surface = surfaceIter->get();
250 if (surface->isInUse()) {
251 newInUseSurfaces.append(*surfaceIter);
255 m_inUseBytesCached -= surface->totalBytes();
256 insertSurfaceIntoPool(surface);
259 m_inUseSurfaces = newInUseSurfaces;
262 bool IOSurfacePool::markOlderSurfacesPurgeable()
264 bool markedAllSurfaces = true;
265 auto markTime = std::chrono::steady_clock::now();
267 for (auto& surfaceAndDetails : m_surfaceDetails) {
268 if (surfaceAndDetails.value.hasMarkedPurgeable)
271 if (markTime - surfaceAndDetails.value.lastUseTime < surfaceAgeBeforeMarkingPurgeable) {
272 markedAllSurfaces = false;
276 surfaceAndDetails.key->setIsVolatile(true);
277 surfaceAndDetails.value.hasMarkedPurgeable = true;
280 return markedAllSurfaces;
283 void IOSurfacePool::collectionTimerFired(Timer<IOSurfacePool>&)
285 collectInUseSurfaces();
286 bool markedAllSurfaces = markOlderSurfacesPurgeable();
288 if (!m_inUseSurfaces.size() && markedAllSurfaces)
289 m_collectionTimer.stop();
291 platformGarbageCollectNow();
292 DUMP_POOL_STATISTICS();
295 void IOSurfacePool::scheduleCollectionTimer()
297 if (!m_collectionTimer.isActive())
298 m_collectionTimer.startRepeating(collectionInterval);
301 void IOSurfacePool::discardAllSurfaces()
304 m_inUseBytesCached = 0;
305 m_surfaceDetails.clear();
306 m_cachedSurfaces.clear();
307 m_inUseSurfaces.clear();
308 m_sizesInPruneOrder.clear();
309 m_collectionTimer.stop();
310 platformGarbageCollectNow();
313 void IOSurfacePool::showPoolStatistics()
315 #if ENABLE_IOSURFACE_POOL_STATISTICS
316 WTFLogAlways("IOSurfacePool Statistics\n");
317 unsigned totalSurfaces = 0;
318 size_t totalSize = 0;
319 size_t totalPurgeableSize = 0;
321 for (const auto& keyAndSurfaces : m_cachedSurfaces) {
322 ASSERT(!keyAndSurfaces.value.isEmpty());
323 size_t queueSize = 0;
324 size_t queuePurgeableSize = 0;
325 for (const auto& surface : keyAndSurfaces.value) {
326 size_t surfaceBytes = surface->totalBytes();
329 queueSize += surfaceBytes;
331 if (surface->isVolatile())
332 queuePurgeableSize += surfaceBytes;
335 totalSize += queueSize;
336 totalPurgeableSize += queuePurgeableSize;
338 WTFLogAlways(" %d x %d: %zu surfaces for %zd KB (%zd KB purgeable)", keyAndSurfaces.key.width(), keyAndSurfaces.key.height(), keyAndSurfaces.value.size(), queueSize / 1024, queuePurgeableSize / 1024);
341 size_t inUseSize = 0;
342 for (const auto& surface : m_inUseSurfaces) {
344 inUseSize += surface->totalBytes();
347 totalSize += inUseSize;
348 WTFLogAlways(" IN USE: %zu surfaces for %zd KB", m_inUseSurfaces.size(), inUseSize / 1024);
350 // FIXME: Should move consistency checks elsewhere, and always perform them in debug builds.
351 ASSERT(m_bytesCached == totalSize);
352 ASSERT(m_bytesCached <= m_maximumBytesCached);
354 WTFLogAlways(" TOTAL: %d surfaces for %zd KB (%zd KB purgeable)\n", totalSurfaces, totalSize / 1024, totalPurgeableSize / 1024);
359 #endif // USE(IOSURFACE)