GrResourceCache.cpp revision 1f47f4f7325971dd53991e2bb02da94fa7c6d962
1
2/*
3 * Copyright 2010 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9
10
11#include "GrResourceCache.h"
12#include "GrResource.h"
13
14GrResourceEntry::GrResourceEntry(const GrResourceKey& key, GrResource* resource)
15        : fKey(key), fResource(resource) {
16    fLockCount = 0;
17    fPrev = fNext = NULL;
18
19    // we assume ownership of the resource, and will unref it when we die
20    GrAssert(resource);
21}
22
23GrResourceEntry::~GrResourceEntry() {
24    fResource->unref();
25}
26
27#if GR_DEBUG
28void GrResourceEntry::validate() const {
29    GrAssert(fLockCount >= 0);
30    GrAssert(fResource);
31    GrAssert(fResource->getCacheEntry() == this);
32    fResource->validate();
33}
34#endif
35
36///////////////////////////////////////////////////////////////////////////////
37
38GrResourceCache::GrResourceCache(int maxCount, size_t maxBytes) :
39        fMaxCount(maxCount),
40        fMaxBytes(maxBytes) {
41    fEntryCount          = 0;
42    fUnlockedEntryCount  = 0;
43    fEntryBytes          = 0;
44    fClientDetachedCount = 0;
45    fClientDetachedBytes = 0;
46
47    fHead = fTail = NULL;
48    fPurging = false;
49}
50
51GrResourceCache::~GrResourceCache() {
52    GrAutoResourceCacheValidate atcv(this);
53
54    this->removeAll();
55}
56
57void GrResourceCache::getLimits(int* maxResources, size_t* maxResourceBytes) const{
58    if (maxResources) {
59        *maxResources = fMaxCount;
60    }
61    if (maxResourceBytes) {
62        *maxResourceBytes = fMaxBytes;
63    }
64}
65
66void GrResourceCache::setLimits(int maxResources, size_t maxResourceBytes) {
67    bool smaller = (maxResources < fMaxCount) || (maxResourceBytes < fMaxBytes);
68
69    fMaxCount = maxResources;
70    fMaxBytes = maxResourceBytes;
71
72    if (smaller) {
73        this->purgeAsNeeded();
74    }
75}
76
77void GrResourceCache::internalDetach(GrResourceEntry* entry,
78                                    bool clientDetach) {
79    GrResourceEntry* prev = entry->fPrev;
80    GrResourceEntry* next = entry->fNext;
81
82    if (prev) {
83        prev->fNext = next;
84    } else {
85        fHead = next;
86    }
87    if (next) {
88        next->fPrev = prev;
89    } else {
90        fTail = prev;
91    }
92    if (!entry->isLocked()) {
93        --fUnlockedEntryCount;
94    }
95
96    entry->fPrev = NULL;
97    entry->fNext = NULL;
98
99    // update our stats
100    if (clientDetach) {
101        fClientDetachedCount += 1;
102        fClientDetachedBytes += entry->resource()->sizeInBytes();
103    } else {
104        fEntryCount -= 1;
105        fEntryBytes -= entry->resource()->sizeInBytes();
106    }
107}
108
109void GrResourceCache::attachToHead(GrResourceEntry* entry,
110                                  bool clientReattach) {
111    entry->fPrev = NULL;
112    entry->fNext = fHead;
113    if (fHead) {
114        fHead->fPrev = entry;
115    }
116    fHead = entry;
117    if (NULL == fTail) {
118        fTail = entry;
119    }
120    if (!entry->isLocked()) {
121        ++fUnlockedEntryCount;
122    }
123
124    // update our stats
125    if (clientReattach) {
126        fClientDetachedCount -= 1;
127        fClientDetachedBytes -= entry->resource()->sizeInBytes();
128    } else {
129        fEntryCount += 1;
130        fEntryBytes += entry->resource()->sizeInBytes();
131    }
132}
133
134class GrResourceCache::Key {
135    typedef GrResourceEntry T;
136
137    const GrResourceKey& fKey;
138public:
139    Key(const GrResourceKey& key) : fKey(key) {}
140
141    uint32_t getHash() const { return fKey.hashIndex(); }
142
143    static bool LT(const T& entry, const Key& key) {
144        return entry.key() < key.fKey;
145    }
146    static bool EQ(const T& entry, const Key& key) {
147        return entry.key() == key.fKey;
148    }
149#if GR_DEBUG
150    static uint32_t GetHash(const T& entry) {
151        return entry.key().hashIndex();
152    }
153    static bool LT(const T& a, const T& b) {
154        return a.key() < b.key();
155    }
156    static bool EQ(const T& a, const T& b) {
157        return a.key() == b.key();
158    }
159#endif
160};
161
162GrResource* GrResourceCache::findAndLock(const GrResourceKey& key,
163                                         LockType type) {
164    GrAutoResourceCacheValidate atcv(this);
165
166    GrResourceEntry* entry = fCache.find(key);
167    if (NULL == entry) {
168        return NULL;
169    }
170
171    this->internalDetach(entry, false);
172    // mark the entry as "busy" so it doesn't get purged
173    // do this between detach and attach for locked count tracking
174    if (kNested_LockType == type || !entry->isLocked()) {
175        entry->lock();
176    }
177    this->attachToHead(entry, false);
178
179    return entry->fResource;
180}
181
182bool GrResourceCache::hasKey(const GrResourceKey& key) const {
183    return NULL != fCache.find(key);
184}
185
186GrResourceEntry* GrResourceCache::create(const GrResourceKey& key,
187                                         GrResource* resource,
188                                         bool lock,
189                                         bool clientReattach) {
190    // we don't expect to create new resources during a purge. In theory
191    // this could cause purgeAsNeeded() into an infinite loop (e.g.
192    // each resource destroyed creates and locks 2 resources and
193    // unlocks 1 thereby causing a new purge).
194    GrAssert(!fPurging);
195    GrAutoResourceCacheValidate atcv(this);
196
197    GrResourceEntry* entry = SkNEW_ARGS(GrResourceEntry, (key, resource));
198
199    resource->setCacheEntry(entry);
200
201    if (lock) {
202        // mark the entry as "busy" so it doesn't get purged
203        // do this before attach for locked count tracking
204        entry->lock();
205    }
206
207    this->attachToHead(entry, clientReattach);
208    fCache.insert(key, entry);
209
210#if GR_DUMP_TEXTURE_UPLOAD
211    GrPrintf("--- add resource to cache %p, count=%d bytes= %d %d\n",
212             entry, fEntryCount, resource->sizeInBytes(), fEntryBytes);
213#endif
214
215    this->purgeAsNeeded();
216    return entry;
217}
218
219void GrResourceCache::createAndLock(const GrResourceKey& key,
220                                    GrResource* resource) {
221    GrAssert(NULL == resource->getCacheEntry());
222    this->create(key, resource, true, false);
223}
224
225void GrResourceCache::attach(const GrResourceKey& key,
226                             GrResource* resource) {
227    GrAssert(NULL == resource->getCacheEntry());
228    this->create(key, resource, false, true);
229}
230
231void GrResourceCache::detach(GrResourceEntry* entry) {
232    GrAutoResourceCacheValidate atcv(this);
233    this->internalDetach(entry, true);
234    fCache.remove(entry->fKey, entry);
235}
236
237void GrResourceCache::freeEntry(GrResourceEntry* entry) {
238    GrAssert(NULL == entry->fNext && NULL == entry->fPrev);
239    delete entry;
240}
241
242void GrResourceCache::reattachAndUnlock(GrResourceEntry* entry) {
243    GrAutoResourceCacheValidate atcv(this);
244    if (entry->resource()->isValid()) {
245        attachToHead(entry, true);
246        fCache.insert(entry->key(), entry);
247    } else {
248        // If the resource went invalid while it was detached then purge it
249        // This can happen when a 3D context was lost,
250        // the client called GrContext::contextDestroyed() to notify Gr,
251        // and then later an SkGpuDevice's destructor releases its backing
252        // texture (which was invalidated at contextDestroyed time).
253        fClientDetachedCount -= 1;
254        fEntryCount -= 1;
255        size_t size = entry->resource()->sizeInBytes();
256        fClientDetachedBytes -= size;
257        fEntryBytes -= size;
258    }
259    this->unlock(entry);
260}
261
262void GrResourceCache::unlock(GrResourceEntry* entry) {
263    GrAutoResourceCacheValidate atcv(this);
264
265    GrAssert(entry);
266    GrAssert(entry->isLocked());
267    GrAssert(fCache.find(entry->key()));
268
269    entry->unlock();
270    if (!entry->isLocked()) {
271        ++fUnlockedEntryCount;
272    }
273    this->purgeAsNeeded();
274}
275
276/**
277 * Destroying a resource may potentially trigger the unlock of additional
278 * resources which in turn will trigger a nested purge. We block the nested
279 * purge using the fPurging variable. However, the initial purge will keep
280 * looping until either all resources in the cache are unlocked or we've met
281 * the budget. There is an assertion in createAndLock to check against a
282 * resource's destructor inserting new resources into the cache. If these
283 * new resources were unlocked before purgeAsNeeded completed it could
284 * potentially make purgeAsNeeded loop infinitely.
285 */
286void GrResourceCache::purgeAsNeeded() {
287    if (!fPurging) {
288        fPurging = true;
289        bool withinBudget = false;
290        do {
291            GrResourceEntry* entry = fTail;
292            while (entry && fUnlockedEntryCount) {
293                GrAutoResourceCacheValidate atcv(this);
294                if (fEntryCount <= fMaxCount && fEntryBytes <= fMaxBytes) {
295                    withinBudget = true;
296                    break;
297                }
298
299                GrResourceEntry* prev = entry->fPrev;
300                if (!entry->isLocked()) {
301                    // remove from our cache
302                    fCache.remove(entry->fKey, entry);
303
304                    // remove from our llist
305                    this->internalDetach(entry, false);
306
307        #if GR_DUMP_TEXTURE_UPLOAD
308                    GrPrintf("--- ~resource from cache %p [%d %d]\n",
309                             entry->resource(),
310                             entry->resource()->width(),
311                             entry->resource()->height());
312        #endif
313                    delete entry;
314                }
315                entry = prev;
316            }
317        } while (!withinBudget && fUnlockedEntryCount);
318        fPurging = false;
319    }
320}
321
322void GrResourceCache::removeAll() {
323    GrAutoResourceCacheValidate atcv(this);
324
325    // we can have one GrResource holding a lock on another
326    // so we don't want to just do a simple loop kicking each
327    // entry out. Instead change the budget and purge.
328
329    int savedMaxBytes = fMaxBytes;
330    int savedMaxCount = fMaxCount;
331    fMaxBytes = (size_t) -1;
332    fMaxCount = 0;
333    this->purgeAsNeeded();
334
335#if GR_DEBUG
336    GrAssert(!fUnlockedEntryCount);
337    if (!fCache.count()) {
338        // Items may have been detached from the cache (such as the backing
339        // texture for an SkGpuDevice). The above purge would not have removed
340        // them.
341        GrAssert(fEntryCount == fClientDetachedCount);
342        GrAssert(fEntryBytes == fClientDetachedBytes);
343        GrAssert(NULL == fHead);
344        GrAssert(NULL == fTail);
345    }
346#endif
347
348    fMaxBytes = savedMaxBytes;
349    fMaxCount = savedMaxCount;
350}
351
352///////////////////////////////////////////////////////////////////////////////
353
354#if GR_DEBUG
355static int countMatches(const GrResourceEntry* head, const GrResourceEntry* target) {
356    const GrResourceEntry* entry = head;
357    int count = 0;
358    while (entry) {
359        if (target == entry) {
360            count += 1;
361        }
362        entry = entry->next();
363    }
364    return count;
365}
366
367#if GR_DEBUG
368static bool both_zero_or_nonzero(int count, size_t bytes) {
369    return (count == 0 && bytes == 0) || (count > 0 && bytes > 0);
370}
371#endif
372
373void GrResourceCache::validate() const {
374    GrAssert(!fHead == !fTail);
375    GrAssert(both_zero_or_nonzero(fEntryCount, fEntryBytes));
376    GrAssert(both_zero_or_nonzero(fClientDetachedCount, fClientDetachedBytes));
377    GrAssert(fClientDetachedBytes <= fEntryBytes);
378    GrAssert(fClientDetachedCount <= fEntryCount);
379    GrAssert((fEntryCount - fClientDetachedCount) == fCache.count());
380
381    fCache.validate();
382
383    GrResourceEntry* entry = fHead;
384    int count = 0;
385    int unlockCount = 0;
386    size_t bytes = 0;
387    while (entry) {
388        entry->validate();
389        GrAssert(fCache.find(entry->key()));
390        count += 1;
391        bytes += entry->resource()->sizeInBytes();
392        if (!entry->isLocked()) {
393            unlockCount += 1;
394        }
395        entry = entry->fNext;
396    }
397    GrAssert(count == fEntryCount - fClientDetachedCount);
398    GrAssert(bytes == fEntryBytes  - fClientDetachedBytes);
399    GrAssert(unlockCount == fUnlockedEntryCount);
400
401    count = 0;
402    for (entry = fTail; entry; entry = entry->fPrev) {
403        count += 1;
404    }
405    GrAssert(count == fEntryCount - fClientDetachedCount);
406
407    for (int i = 0; i < count; i++) {
408        int matches = countMatches(fHead, fCache.getArray()[i]);
409        GrAssert(1 == matches);
410    }
411}
412#endif
413