3 * Copyright 2010 Google Inc.
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
11 #include "GrResourceCache.h"
12 #include "GrResource.h"
14 DECLARE_SKMESSAGEBUS_MESSAGE(GrResourceInvalidatedMessage);
16 GrResourceKey::ResourceType GrResourceKey::GenerateResourceType() {
17 static int32_t gNextType = 0;
19 int32_t type = sk_atomic_inc(&gNextType);
20 if (type >= (1 << 8 * sizeof(ResourceType))) {
21 GrCrash("Too many Resource Types");
24 return static_cast<ResourceType>(type);
27 ///////////////////////////////////////////////////////////////////////////////
29 GrResourceEntry::GrResourceEntry(const GrResourceKey& key, GrResource* resource)
30 : fKey(key), fResource(resource) {
31 // we assume ownership of the resource, and will unref it when we die
36 GrResourceEntry::~GrResourceEntry() {
37 fResource->setCacheEntry(NULL);
42 void GrResourceEntry::validate() const {
44 SkASSERT(fResource->getCacheEntry() == this);
45 fResource->validate();
49 ///////////////////////////////////////////////////////////////////////////////
51 GrResourceCache::GrResourceCache(int maxCount, size_t maxBytes) :
55 fHighWaterEntryCount = 0;
56 fHighWaterEntryBytes = 0;
57 fHighWaterClientDetachedCount = 0;
58 fHighWaterClientDetachedBytes = 0;
63 fClientDetachedCount = 0;
64 fClientDetachedBytes = 0;
69 fOverbudgetData = NULL;
72 GrResourceCache::~GrResourceCache() {
73 GrAutoResourceCacheValidate atcv(this);
77 // Unlike the removeAll, here we really remove everything, including locked resources.
78 while (GrResourceEntry* entry = fList.head()) {
79 GrAutoResourceCacheValidate atcv(this);
81 // remove from our cache
82 fCache.remove(entry->fKey, entry);
84 // remove from our llist
85 this->internalDetach(entry);
91 void GrResourceCache::getLimits(int* maxResources, size_t* maxResourceBytes) const{
92 if (NULL != maxResources) {
93 *maxResources = fMaxCount;
95 if (NULL != maxResourceBytes) {
96 *maxResourceBytes = fMaxBytes;
100 void GrResourceCache::setLimits(int maxResources, size_t maxResourceBytes) {
101 bool smaller = (maxResources < fMaxCount) || (maxResourceBytes < fMaxBytes);
103 fMaxCount = maxResources;
104 fMaxBytes = maxResourceBytes;
107 this->purgeAsNeeded();
111 void GrResourceCache::internalDetach(GrResourceEntry* entry,
112 BudgetBehaviors behavior) {
116 if (kIgnore_BudgetBehavior == behavior) {
117 fClientDetachedCount += 1;
118 fClientDetachedBytes += entry->resource()->sizeInBytes();
121 if (fHighWaterClientDetachedCount < fClientDetachedCount) {
122 fHighWaterClientDetachedCount = fClientDetachedCount;
124 if (fHighWaterClientDetachedBytes < fClientDetachedBytes) {
125 fHighWaterClientDetachedBytes = fClientDetachedBytes;
130 SkASSERT(kAccountFor_BudgetBehavior == behavior);
133 fEntryBytes -= entry->resource()->sizeInBytes();
137 void GrResourceCache::attachToHead(GrResourceEntry* entry,
138 BudgetBehaviors behavior) {
139 fList.addToHead(entry);
142 if (kIgnore_BudgetBehavior == behavior) {
143 fClientDetachedCount -= 1;
144 fClientDetachedBytes -= entry->resource()->sizeInBytes();
146 SkASSERT(kAccountFor_BudgetBehavior == behavior);
149 fEntryBytes += entry->resource()->sizeInBytes();
152 if (fHighWaterEntryCount < fEntryCount) {
153 fHighWaterEntryCount = fEntryCount;
155 if (fHighWaterEntryBytes < fEntryBytes) {
156 fHighWaterEntryBytes = fEntryBytes;
162 // This functor just searches for an entry with only a single ref (from
163 // the texture cache itself). Presumably in this situation no one else
164 // is relying on the texture.
165 class GrTFindUnreffedFunctor {
167 bool operator()(const GrResourceEntry* entry) const {
168 return entry->resource()->unique();
172 GrResource* GrResourceCache::find(const GrResourceKey& key, uint32_t ownershipFlags) {
173 GrAutoResourceCacheValidate atcv(this);
175 GrResourceEntry* entry = NULL;
177 if (ownershipFlags & kNoOtherOwners_OwnershipFlag) {
178 GrTFindUnreffedFunctor functor;
180 entry = fCache.find<GrTFindUnreffedFunctor>(key, functor);
182 entry = fCache.find(key);
189 if (ownershipFlags & kHide_OwnershipFlag) {
190 this->makeExclusive(entry);
192 // Make this resource MRU
193 this->internalDetach(entry);
194 this->attachToHead(entry);
197 return entry->fResource;
200 void GrResourceCache::addResource(const GrResourceKey& key,
201 GrResource* resource,
202 uint32_t ownershipFlags) {
203 SkASSERT(NULL == resource->getCacheEntry());
204 // we don't expect to create new resources during a purge. In theory
205 // this could cause purgeAsNeeded() into an infinite loop (e.g.
206 // each resource destroyed creates and locks 2 resources and
207 // unlocks 1 thereby causing a new purge).
209 GrAutoResourceCacheValidate atcv(this);
211 GrResourceEntry* entry = SkNEW_ARGS(GrResourceEntry, (key, resource));
212 resource->setCacheEntry(entry);
214 this->attachToHead(entry);
215 fCache.insert(key, entry);
217 if (ownershipFlags & kHide_OwnershipFlag) {
218 this->makeExclusive(entry);
223 void GrResourceCache::makeExclusive(GrResourceEntry* entry) {
224 GrAutoResourceCacheValidate atcv(this);
226 // When scratch textures are detached (to hide them from future finds) they
227 // still count against the resource budget
228 this->internalDetach(entry, kIgnore_BudgetBehavior);
229 fCache.remove(entry->key(), entry);
232 fExclusiveList.addToHead(entry);
236 void GrResourceCache::removeInvalidResource(GrResourceEntry* entry) {
237 // If the resource went invalid while it was detached then purge it
238 // This can happen when a 3D context was lost,
239 // the client called GrContext::contextDestroyed() to notify Gr,
240 // and then later an SkGpuDevice's destructor releases its backing
241 // texture (which was invalidated at contextDestroyed time).
242 fClientDetachedCount -= 1;
244 size_t size = entry->resource()->sizeInBytes();
245 fClientDetachedBytes -= size;
249 void GrResourceCache::makeNonExclusive(GrResourceEntry* entry) {
250 GrAutoResourceCacheValidate atcv(this);
253 fExclusiveList.remove(entry);
256 if (entry->resource()->isValid()) {
257 // Since scratch textures still count against the cache budget even
258 // when they have been removed from the cache, re-adding them doesn't
259 // alter the budget information.
260 attachToHead(entry, kIgnore_BudgetBehavior);
261 fCache.insert(entry->key(), entry);
263 this->removeInvalidResource(entry);
268 * Destroying a resource may potentially trigger the unlock of additional
269 * resources which in turn will trigger a nested purge. We block the nested
270 * purge using the fPurging variable. However, the initial purge will keep
271 * looping until either all resources in the cache are unlocked or we've met
272 * the budget. There is an assertion in createAndLock to check against a
273 * resource's destructor inserting new resources into the cache. If these
274 * new resources were unlocked before purgeAsNeeded completed it could
275 * potentially make purgeAsNeeded loop infinitely.
277 * extraCount and extraBytes are added to the current resource totals to account
278 * for incoming resources (e.g., GrContext is about to add 10MB split between
281 void GrResourceCache::purgeAsNeeded(int extraCount, size_t extraBytes) {
288 this->purgeInvalidated();
290 this->internalPurge(extraCount, extraBytes);
291 if (((fEntryCount+extraCount) > fMaxCount ||
292 (fEntryBytes+extraBytes) > fMaxBytes) &&
293 NULL != fOverbudgetCB) {
294 // Despite the purge we're still over budget. See if Ganesh can
295 // release some resources and purge again.
296 if ((*fOverbudgetCB)(fOverbudgetData)) {
297 this->internalPurge(extraCount, extraBytes);
304 void GrResourceCache::purgeInvalidated() {
305 SkTDArray<GrResourceInvalidatedMessage> invalidated;
306 fInvalidationInbox.poll(&invalidated);
308 for (int i = 0; i < invalidated.count(); i++) {
309 // We're somewhat missing an opportunity here. We could use the
310 // default find functor that gives us back resources whether we own
311 // them exclusively or not, and when they're not exclusively owned mark
312 // them for purging later when they do become exclusively owned.
314 // This is complicated and confusing. May try this in the future. For
315 // now, these resources are just LRU'd as if we never got the message.
316 while (GrResourceEntry* entry = fCache.find(invalidated[i].key, GrTFindUnreffedFunctor())) {
317 this->deleteResource(entry);
322 void GrResourceCache::deleteResource(GrResourceEntry* entry) {
323 SkASSERT(1 == entry->fResource->getRefCnt());
325 // remove from our cache
326 fCache.remove(entry->key(), entry);
328 // remove from our llist
329 this->internalDetach(entry);
333 void GrResourceCache::internalPurge(int extraCount, size_t extraBytes) {
336 bool withinBudget = false;
337 bool changed = false;
339 // The purging process is repeated several times since one pass
340 // may free up other resources
342 EntryList::Iter iter;
346 // Note: the following code relies on the fact that the
347 // doubly linked list doesn't invalidate its data/pointers
348 // outside of the specific area where a deletion occurs (e.g.,
349 // in internalDetach)
350 GrResourceEntry* entry = iter.init(fList, EntryList::Iter::kTail_IterStart);
352 while (NULL != entry) {
353 GrAutoResourceCacheValidate atcv(this);
355 if ((fEntryCount+extraCount) <= fMaxCount &&
356 (fEntryBytes+extraBytes) <= fMaxBytes) {
361 GrResourceEntry* prev = iter.prev();
362 if (entry->fResource->unique()) {
364 this->deleteResource(entry);
368 } while (!withinBudget && changed);
371 void GrResourceCache::purgeAllUnlocked() {
372 GrAutoResourceCacheValidate atcv(this);
374 // we can have one GrResource holding a lock on another
375 // so we don't want to just do a simple loop kicking each
376 // entry out. Instead change the budget and purge.
378 size_t savedMaxBytes = fMaxBytes;
379 int savedMaxCount = fMaxCount;
380 fMaxBytes = (size_t) -1;
382 this->purgeAsNeeded();
385 SkASSERT(fExclusiveList.countEntries() == fClientDetachedCount);
386 SkASSERT(countBytes(fExclusiveList) == fClientDetachedBytes);
387 if (!fCache.count()) {
388 // Items may have been detached from the cache (such as the backing
389 // texture for an SkGpuDevice). The above purge would not have removed
391 SkASSERT(fEntryCount == fClientDetachedCount);
392 SkASSERT(fEntryBytes == fClientDetachedBytes);
393 SkASSERT(fList.isEmpty());
397 fMaxBytes = savedMaxBytes;
398 fMaxCount = savedMaxCount;
401 ///////////////////////////////////////////////////////////////////////////////
404 size_t GrResourceCache::countBytes(const EntryList& list) {
407 EntryList::Iter iter;
409 const GrResourceEntry* entry = iter.init(const_cast<EntryList&>(list),
410 EntryList::Iter::kTail_IterStart);
412 for ( ; NULL != entry; entry = iter.prev()) {
413 bytes += entry->resource()->sizeInBytes();
418 static bool both_zero_or_nonzero(int count, size_t bytes) {
419 return (count == 0 && bytes == 0) || (count > 0 && bytes > 0);
422 void GrResourceCache::validate() const {
424 fExclusiveList.validate();
425 SkASSERT(both_zero_or_nonzero(fEntryCount, fEntryBytes));
426 SkASSERT(both_zero_or_nonzero(fClientDetachedCount, fClientDetachedBytes));
427 SkASSERT(fClientDetachedBytes <= fEntryBytes);
428 SkASSERT(fClientDetachedCount <= fEntryCount);
429 SkASSERT((fEntryCount - fClientDetachedCount) == fCache.count());
431 EntryList::Iter iter;
433 // check that the exclusively held entries are okay
434 const GrResourceEntry* entry = iter.init(const_cast<EntryList&>(fExclusiveList),
435 EntryList::Iter::kHead_IterStart);
437 for ( ; NULL != entry; entry = iter.next()) {
441 // check that the shareable entries are okay
442 entry = iter.init(const_cast<EntryList&>(fList), EntryList::Iter::kHead_IterStart);
445 for ( ; NULL != entry; entry = iter.next()) {
447 SkASSERT(fCache.find(entry->key()));
450 SkASSERT(count == fEntryCount - fClientDetachedCount);
452 size_t bytes = countBytes(fList);
453 SkASSERT(bytes == fEntryBytes - fClientDetachedBytes);
455 bytes = countBytes(fExclusiveList);
456 SkASSERT(bytes == fClientDetachedBytes);
458 SkASSERT(fList.countEntries() == fEntryCount - fClientDetachedCount);
460 SkASSERT(fExclusiveList.countEntries() == fClientDetachedCount);
466 void GrResourceCache::printStats() {
469 EntryList::Iter iter;
471 GrResourceEntry* entry = iter.init(fList, EntryList::Iter::kTail_IterStart);
473 for ( ; NULL != entry; entry = iter.prev()) {
474 if (entry->fResource->getRefCnt() > 1) {
479 SkDebugf("Budget: %d items %d bytes\n", fMaxCount, fMaxBytes);
480 SkDebugf("\t\tEntry Count: current %d (%d locked) high %d\n",
481 fEntryCount, locked, fHighWaterEntryCount);
482 SkDebugf("\t\tEntry Bytes: current %d high %d\n",
483 fEntryBytes, fHighWaterEntryBytes);
484 SkDebugf("\t\tDetached Entry Count: current %d high %d\n",
485 fClientDetachedCount, fHighWaterClientDetachedCount);
486 SkDebugf("\t\tDetached Bytes: current %d high %d\n",
487 fClientDetachedBytes, fHighWaterClientDetachedBytes);
492 ///////////////////////////////////////////////////////////////////////////////