Debian Codegraph @

src/gpu/graphite/ResourceCache.cpp

raw
1 /*
2 * Copyright 2022 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/gpu/graphite/ResourceCache.h"
9
10 #include "include/private/base/SingleOwner.h"
11 #include "src/base/SkNoDestructor.h"
12 #include "src/base/SkRandom.h"
13 #include "src/core/SkTMultiMap.h"
14 #include "src/core/SkTraceEvent.h"
15 #include "src/gpu/graphite/GraphiteResourceKey.h"
16 #include "src/gpu/graphite/ProxyCache.h"
17 #include "src/gpu/graphite/Resource.h"
18
19 #if defined(GPU_TEST_UTILS)
20 #include "src/gpu/graphite/Texture.h"
21 #endif
22
23 namespace skgpu::graphite {
24
25 #define ASSERT_SINGLE_OWNER SKGPU_ASSERT_SINGLE_OWNER(fSingleOwner)
26
27 namespace {
28
29 static constexpr uint32_t kMaxUseToken = 0xFFFFFFFF;
30
31 // Singleton Resource subclass that provides a fixed address used to track the end of the return
32 // queue and when the resource cache is shutdown.
33 class Sentinel : public Resource {
34 public:
35 static Resource* Get() {
36 static SkNoDestructor<Sentinel> kSentinel{};
37 return kSentinel.get();
38 }
39
40 private:
41 template <typename T>
42 friend class ::SkNoDestructor;
43
44 // We can pass in a null shared context here because the only instance that is ever created is
45 // wrapped in SkNoDestructor, and we never actually use it as a Resource.
46 Sentinel() : Resource(/*sharedContext=*/nullptr, Ownership::kOwned, /*gpuMemorySize=*/0) {}
47
48 const char* getResourceType() const override { return "Sentinel"; }
49
50 void freeGpuData() override {}
51 };
52
53 } // anonymous namespace
54
55 sk_sp<ResourceCache> ResourceCache::Make(SingleOwner* singleOwner,
56 uint32_t recorderID,
57 size_t maxBytes) {
58 return sk_sp<ResourceCache>(new ResourceCache(singleOwner, recorderID, maxBytes));
59 }
60
61 ResourceCache::ResourceCache(SingleOwner* singleOwner, uint32_t recorderID, size_t maxBytes)
62 : fMaxBytes(maxBytes)
63 , fSingleOwner(singleOwner) {
64 if (recorderID != SK_InvalidGenID) {
65 fProxyCache = std::make_unique<ProxyCache>(recorderID);
66 }
67 // TODO: Maybe when things start using ResourceCache, then like Ganesh the compiler won't
68 // complain about not using fSingleOwner in Release builds and we can delete this.
69 #if !defined(SK_DEBUG)
70 (void)fSingleOwner;
71 #endif
72 }
73
74 ResourceCache::~ResourceCache() {
75 // The ResourceCache must have been shutdown by the ResourceProvider before it is destroyed.
76 SkASSERT(fReturnQueue.load(std::memory_order_acquire) == Sentinel::Get());
77 }
78
79 void ResourceCache::shutdown() {
80 ASSERT_SINGLE_OWNER
81
82 // At this point no more changes will happen to fReturnQueue or the resources within that
83 // linked list. We do need to finish processing them for a graceful shutdown.
84 this->processReturnedResources(Sentinel::Get());
85
86 if (fProxyCache) {
87 fProxyCache->purgeAll();
88 // NOTE: any resources that would become purgeable or reusable from purging the proxy cache
89 // are not added to the return queue and remain in the nonpurgeable array. Below their
90 // cache ref will be removed, causing them to be deleted immediately.
91 }
92
93 while (!fNonpurgeableResources.empty()) {
94 Resource* back = *(fNonpurgeableResources.end() - 1);
95 SkASSERT(!back->wasDestroyed());
96 this->removeFromNonpurgeableArray(back);
97 back->unrefCache();
98 }
99
100 while (fPurgeableQueue.count()) {
101 Resource* top = fPurgeableQueue.peek();
102 SkASSERT(!top->wasDestroyed());
103 this->removeFromPurgeableQueue(top);
104 top->unrefCache();
105 }
106
107 TRACE_EVENT_INSTANT0("skia.gpu.cache", TRACE_FUNC, TRACE_EVENT_SCOPE_THREAD);
108 }
109
110 void ResourceCache::insertResource(Resource* resource,
111 const GraphiteResourceKey& key,
112 Budgeted budgeted,
113 Shareable shareable) {
114 ASSERT_SINGLE_OWNER
115 SkASSERT(resource);
116 SkASSERT(key.isValid());
117 SkASSERT(shareable == Shareable::kNo || budgeted == Budgeted::kYes);
118
119 SkASSERT(!this->isInCache(resource));
120 SkASSERT(!resource->wasDestroyed());
121 SkASSERT(!resource->isPurgeable());
122 SkASSERT(!resource->key().isValid());
123 // All resources in the cache are owned. If we track wrapped resources in the cache we'll need
124 // to update this check.
125 SkASSERT(resource->ownership() == Ownership::kOwned);
126
127 // Make sure we have the most accurate memory size for "memoryless" resources.
128 resource->updateGpuMemorySize();
129
130 // The reason to call processReturnedResources here is to get an accurate accounting of our
131 // memory usage as some resources can go from unbudgeted to budgeted when they return. So we
132 // want to have them all returned before adding the budget for the new resource in case we need
133 // to purge things. However, if the new resource has a memory size of 0, then we just skip
134 // returning resources (which has overhead for each call) since the new resource won't be
135 // affecting whether we're over or under budget.
136 if (resource->gpuMemorySize() > 0) {
137 this->processReturnedResources();
138 }
139
140 resource->registerWithCache(sk_ref_sp(this), key, budgeted, shareable);
141
142 // We must set the use token before adding to the array in case the token wraps and we wind
143 // up iterating over all the resources that already have use tokens.
144 this->setResourceUseToken(resource, this->getNextUseToken());
145 resource->updateAccessTime();
146
147 this->addToNonpurgeableArray(resource);
148
149 SkDEBUGCODE(fCount++;)
150
151 if (resource->shareable() != Shareable::kNo) {
152 // Scratch and shareable resources are always available for reuse
153 this->addToResourceMap(resource);
154 }
155
156 if (resource->budgeted() == Budgeted::kYes) {
157 fBudgetedBytes += resource->gpuMemorySize();
158 }
159
160 this->purgeAsNeeded();
161 }
162
163 Resource* ResourceCache::findAndRefResource(const GraphiteResourceKey& key,
164 Budgeted budgeted,
165 Shareable shareable,
166 const ScratchResourceSet* unavailable) {
167 ASSERT_SINGLE_OWNER
168
169 SkASSERT(key.isValid());
170 SkASSERT(shareable == Shareable::kNo || budgeted == Budgeted::kYes);
171 SkASSERT(shareable != Shareable::kScratch || SkToBool(unavailable));
172
173 auto shareablePredicate = [shareable, unavailable](Resource* r) {
174 // If the resource is in fResourceMap then it's available, so a non-shareable state means
175 // it really has no outstanding uses and can be converted to any other shareable state.
176 // Otherwise, if it's available, it can only be reused with the same mode. Additionally,
177 // for kScratch resources, they cannot already be in the `unavailable` set passed in.
178 return (r->shareable() == Shareable::kNo || r->shareable() == shareable) &&
179 (shareable != Shareable::kScratch || !unavailable->contains(r));
180 };
181
182 Resource* resource = fResourceMap.find(key, shareablePredicate);
183 if (!resource) {
184 // The main reason to call processReturnedResources in this call is to see if there are any
185 // resources that we could match with the key. However, there is overhead into calling it.
186 // So we only call it if we first failed to find a matching resource.
187 if (this->processReturnedResources()) {
188 resource = fResourceMap.find(key, shareablePredicate);
189 }
190 }
191 if (resource) {
192 // All resources we pull out of the cache for use should be budgeted
193 SkASSERT(resource->budgeted() == Budgeted::kYes);
194 SkASSERT(resource->key() == key);
195
196 if (shareable == Shareable::kNo) {
197 // If the returned resource is no longer shareable then we remove it from the map so
198 // that it isn't found again.
199 SkASSERT(resource->shareable() == Shareable::kNo);
200 this->removeFromResourceMap(resource);
201 if (budgeted == Budgeted::kNo) {
202 resource->setBudgeted(Budgeted::kNo);
203 fBudgetedBytes -= resource->gpuMemorySize();
204 }
205 } else {
206 // Shareable and scratch resources should never be requested as non-budgeted
207 SkASSERT(budgeted == Budgeted::kYes);
208 resource->setShareable(shareable);
209 }
210 this->refAndMakeResourceMRU(resource);
211 this->validate();
212 }
213
214 // processReturnedResources may have added resources back into our budget if they were being
215 // using in an SkImage or SkSurface previously. However, instead of calling purgeAsNeeded in
216 // processReturnedResources, we delay calling it until now so we don't end up purging a resource
217 // we're looking for in this function.
218 //
219 // We could avoid calling this if we didn't return any resources from processReturnedResources.
220 // However, when not overbudget purgeAsNeeded is very cheap. When overbudget there may be some
221 // really niche usage patterns that could cause us to never actually return resources to the
222 // cache, but still be overbudget due to shared resources. So to be safe we just always call it
223 // here.
224 this->purgeAsNeeded();
225
226 return resource;
227 }
228
229 void ResourceCache::refAndMakeResourceMRU(Resource* resource) {
230 SkASSERT(resource);
231 SkASSERT(this->isInCache(resource));
232
233 if (this->inPurgeableQueue(resource)) {
234 // It's about to become unpurgeable.
235 this->removeFromPurgeableQueue(resource);
236 this->addToNonpurgeableArray(resource);
237 }
238 resource->initialUsageRef();
239
240 this->setResourceUseToken(resource, this->getNextUseToken());
241 this->validate();
242 }
243
244 void ResourceCache::forceProcessReturnedResources() {
245 ASSERT_SINGLE_OWNER
246 this->processReturnedResources();
247 }
248
249 bool ResourceCache::returnResource(Resource* resource) {
250 SkASSERT(resource && resource->cache() == this);
251 // We only allow one instance of a Resource to be in the return queue at a time but it should
252 // have already added a return queue ref.
253 SkASSERT(!resource->inReturnQueue() && resource->hasReturnQueueRef());
254
255 // Check once with a relaxed load to try and minimize the amount of wasted preparation work if
256 // the cache is already shutdown.
257 Resource* oldHeadPtr = fReturnQueue.load(std::memory_order_relaxed);
258 if (oldHeadPtr == Sentinel::Get()) {
259 return false;
260 }
261
262 // When a non-shareable resource's CB and Usage refs are both zero, give it a chance to prepare
263 // itself to be reused. On Dawn/WebGPU we use this to remap kXferCpuToGpu buffers asynchronously
264 // so that they are already mapped before they come out of the cache again.
265 if (resource->shouldDeleteASAP() == Resource::DeleteASAP::kNo &&
266 resource->requiresPrepareForReturnToCache()) {
267 // If we get here, we know the usage ref count is 0, so the only way for that to increase
268 // again is if the Resource triggers the initial usage ref in the callback.
269 struct TakeRefContext {
270 Resource* resource;
271 SkDEBUGCODE(bool takeRefActuallyCalled = false;)
272 } ctx = {resource};
273 bool takeRefCalled = resource->prepareForReturnToCache([](void* ctx) {
274 // This adds a usage ref AND removes the return queue ref. When returnResource()
275 // returns true, the cache takes responsibility for releasing the return queue ref.
276 // If we returned false from returnResource() when the resource invokes the takeRef
277 // function, there's a gap between when the resource can be used on another thread
278 // and when this thread removes the return queue ref. If the resource's new usage
279 // ref is removed on the other thread before this thread were to remove the return
280 // queue ref, it would end up skipping the return.
281 //
282 // By immediately unreffing the return queue ref before the resource can be exposed
283 // to another thread, the resource will always be able to be re-returned when the
284 // async work completes.
285 //
286 // Since prepareForReturnToCache() can only be used with resources that require
287 // purgeability for reusability, and it is non-shareable, the only ref that can
288 // change off thread is the resource's cache ref if the cache is simultaneously
289 // shutdown.
290 //
291 // Adding the usage ref first ensures the resource won't be disposed of early. When
292 // the resource is prepared, it will come through returnResource() again but should
293 // return false from prepareForReturnToCache() so that cache shutdown is detected.
294 // This can add unnecessary preparation work for resources that won't ever be used,
295 // but keeps the preparation logic relatively simple w/o needing a mutex.
296 auto* context = static_cast<TakeRefContext*>(ctx);
297 context->resource->initialUsageRef();
298 context->resource->unrefReturnQueue();
299
300 SkDEBUGCODE(context->takeRefActuallyCalled = true;
301 )}, &ctx);
302
303 SkASSERT(takeRefCalled == ctx.takeRefActuallyCalled);
304 if (takeRefCalled) {
305 // Return 'true' here because we've removed the return queue ref already and don't
306 // want Resource to try and do that again. But since we added an initial ref, this
307 // resource will be re-returned once the async prepare-for-return work has finished.
308 return true;
309 }
310 }
311
312 // Set the newly returned resource to be the head of the list, with its next pointer holding
313 // the old head. If the head has changed between the assignment of the next pointer, we repeat
314 // because it means there was a simultaneous return or the cache was shutdown.
315 do {
316 oldHeadPtr = fReturnQueue.load(std::memory_order_acquire);
317 if (oldHeadPtr == Sentinel::Get()) {
318 // Once the cache is shutdown, it can never be re-opened and we don't want to actually
319 // return this resource.
320 resource->setNextInReturnQueue(nullptr);
321 return false;
322 } else {
323 // If oldHeadPtr is null, this resource will be the tail of the return queue as it grows
324 // so set it's next pointer to the sentinel so that nullity can be used to test for
325 // being in the queue or not.
326 resource->setNextInReturnQueue(oldHeadPtr ? oldHeadPtr : Sentinel::Get());
327 }
328 } while(!fReturnQueue.compare_exchange_weak(oldHeadPtr, resource,
329 std::memory_order_release,
330 std::memory_order_relaxed));
331
332 // Once we've got here, it means that `resource` has been atomically included in the return
333 // queue. At this point, fReturnQueue's head value may or may not be `resource`, depending on if
334 // another thread has added another resource or processed the return queue, but in either event,
335 // `resource` will be visible to that thread.
336 return true;
337 }
338
339 bool ResourceCache::processReturnedResources(Resource* queueHead) {
340 SkASSERT(queueHead == nullptr || queueHead == Sentinel::Get());
341 // We need to move the returned Resources off of the ReturnQueue before we start processing them
342 // so that we can manipulate the resources without blocking subsequent returns on other threads.
343 Resource* oldQueue = fReturnQueue.exchange(queueHead, std::memory_order_acq_rel);
344
345 // Can't un-shutdown the cache
346 SkASSERT(oldQueue != Sentinel::Get() || queueHead == Sentinel::Get());
347
348 int returnCount = 0;
349 // Stop if we encounter null or the sentinel address (either the list is empty, the cache is
350 // shutdown, or we reached the tail returned resource that had next set to the sentinel).
351 while (oldQueue && oldQueue != Sentinel::Get()) {
352 returnCount++;
353 oldQueue = this->processReturnedResource(oldQueue);
354 }
355
356 TRACE_EVENT_INSTANT1("skia.gpu.cache", TRACE_FUNC, TRACE_EVENT_SCOPE_THREAD,
357 "count", returnCount);
358 return returnCount > 0;
359 }
360
361 Resource* ResourceCache::processReturnedResource(Resource* resource) {
362 // A resource should not have been destroyed when placed into the return queue. Also before
363 // purging any resources from the cache itself, it should always empty the queue first. When the
364 // cache releases/abandons all of its resources, it first invalidates the return queue so no new
365 // resources can be added. Thus we should not end up in a situation where a resource gets
366 // destroyed after it was added to the return queue.
367 SkASSERT(!resource->wasDestroyed());
368 SkASSERT(this->isInCache(resource));
369
370 const auto [isReusable, isPurgeable, next] = resource->unrefReturnQueue();
371
372 if (resource->shareable() != Shareable::kNo) {
373 // Shareable resources should still be discoverable in the resource map
374 SkASSERT(fResourceMap.has(resource, resource->key()));
375 SkASSERT(resource->isAvailableForReuse());
376
377 // Reset the resource's sharing mode so that any shareable request can use it (e.g. now that
378 // no more usages that required it to be scratch/shareable are held, the underlying resource
379 // can be used in a non-shareable manner the next time it's fetched from the cache). We can
380 // only change the shareable state when there are no outstanding usage refs. Because this
381 // resource was shareable, it remained in fResourceMap and could have a new usage ref before
382 // a prior return event was processed from the return queue. However, when a shareable ref
383 // has no usage refs, this is the only thread that can add an initial usage ref so it is
384 // safe to adjust its shareable type
385 if (isReusable) {
386 resource->setShareable(Shareable::kNo);
387 }
388 } else if (isReusable) {
389 // Non-shareable resources are removed from the resource map when they are given out by the
390 // cache. A resource is returned for either becoming reusable (needs to be added to the
391 // resource map) or becoming purgeable (needs to be moved to the purgeable queue). Becoming
392 // purgeable always implies becoming reusable, so as long as a previous return hasn't put it
393 // into the resource map already, we do that now.
394 if (!resource->isAvailableForReuse()) {
395 SkASSERT(!fResourceMap.has(resource, resource->key()));
396 this->addToResourceMap(resource);
397
398 if (resource->budgeted() == Budgeted::kNo) {
399 resource->setBudgeted(Budgeted::kYes);
400 fBudgetedBytes += resource->gpuMemorySize();
401 }
402 }
403
404 SkASSERT(fResourceMap.has(resource, resource->key()));
405 SkASSERT(resource->isAvailableForReuse());
406 // Since the resource should be non-shareable available as scratch, there are no outstanding
407 // refs that would make this assert not thread safe.
408 SkASSERT(resource->isUsableAsScratch());
409 } else {
410 // This was a stale entry in the return queue, which can arise when a Resource becomes
411 // reusable while it has outstanding command buffer refs. If the timing is right, the
412 // command buffer ref can be removed so the resource is purgeable (and goes back into the
413 // queue to be processed from non-purgeable to purgeable), but immediately after, the cache
414 // thread can add a usage ref. By the next time the return queue is processed, the resource
415 // is neither purgeable nor reusable.
416 SkASSERT(!fResourceMap.has(resource, resource->key()));
417 SkASSERT(!resource->isAvailableForReuse());
418 // At an instanteous moment, this resource should not be considered usable as scratch, but
419 // we cannot assert !isUsableAsScratch() because the other threads that are holding the
420 // extra refs described above can just as easily drop them between this assert and the last
421 // call to unrefReturnQueue() that put us into this branch.
422 }
423
424 // Update GPU budget now that the budget policy is up to date. Some GPU resources may have their
425 // actual memory amount change over time so update periodically.
426 if (resource->budgeted() == Budgeted::kYes) {
427 size_t oldSize = resource->gpuMemorySize();
428 resource->updateGpuMemorySize();
429 if (oldSize != resource->gpuMemorySize()) {
430 fBudgetedBytes -= oldSize;
431 fBudgetedBytes += resource->gpuMemorySize();
432 }
433 }
434
435 this->setResourceUseToken(resource, this->getNextUseToken());
436
437 // If the resource was not purgeable at the time the return queue ref was released, the
438 // resource should still be in the non-purgeable array from when it was originally given
439 // out. Another thread may have already removed the last refs keeping it non-purgeable by
440 // the time this thread reachs this line but that will only have re-added it to the return
441 // queue. The cache stores the resource based on its purgeability at the time of releasing
442 // the return queue ref. Any subsequent return due to becoming purgeable will complete
443 // moving the resource from the non-purgeable array to the purgeable queue.
444 SkASSERT(this->inNonpurgeableArray(resource));
445 if (!isPurgeable) {
446 this->validate();
447 return next;
448 }
449
450 // Since the resource is purgeable, there are no external refs that can add new refs to make
451 // it non-purgeable at this point. Only the current cache thread has that ability so we can
452 // safely continue moving the resource from non-purgeable to purgeable without worrying about
453 // another state change.
454 this->removeFromNonpurgeableArray(resource);
455
456 if (resource->shouldDeleteASAP() == Resource::DeleteASAP::kYes) {
457 this->purgeResource(resource);
458 } else {
459 // We don't purge this resource immediately even if we are overbudget. This allows later
460 // purgeAsNeeded() calls to prioritize deleting less-recently-used Resources first.
461 resource->updateAccessTime();
462 fPurgeableQueue.insert(resource);
463 fPurgeableBytes += resource->gpuMemorySize();
464 }
465 this->validate();
466
467 return next;
468 }
469
470 void ResourceCache::addToResourceMap(Resource* resource) {
471 SkASSERT(this->isInCache(resource));
472 SkASSERT(!resource->isAvailableForReuse());
473 SkASSERT(!fResourceMap.has(resource, resource->key()));
474 fResourceMap.insert(resource->key(), resource);
475 resource->setAvailableForReuse(true);
476 }
477
478 void ResourceCache::removeFromResourceMap(Resource* resource) {
479 SkASSERT(this->isInCache(resource));
480 SkASSERT(resource->isAvailableForReuse());
481 SkASSERT(fResourceMap.has(resource, resource->key()));
482 fResourceMap.remove(resource->key(), resource);
483 resource->setAvailableForReuse(false);
484 }
485
486 void ResourceCache::addToNonpurgeableArray(Resource* resource) {
487 SkASSERT(!this->inNonpurgeableArray(resource));
488
489 int index = fNonpurgeableResources.size();
490 *fNonpurgeableResources.append() = resource;
491 *resource->accessCacheIndex() = index;
492 }
493
494 void ResourceCache::removeFromNonpurgeableArray(Resource* resource) {
495 SkASSERT(this->inNonpurgeableArray(resource));
496
497 int* index = resource->accessCacheIndex();
498 // Fill the hole we will create in the array with the tail object, adjust its index, and
499 // then pop the array
500 Resource* tail = *(fNonpurgeableResources.end() - 1);
501 SkASSERT(fNonpurgeableResources[*index] == resource);
502 fNonpurgeableResources[*index] = tail;
503 *tail->accessCacheIndex() = *index;
504 fNonpurgeableResources.pop_back();
505 *index = -1;
506 }
507
508 void ResourceCache::removeFromPurgeableQueue(Resource* resource) {
509 SkASSERT(this->inPurgeableQueue(resource));
510
511 fPurgeableQueue.remove(resource);
512 fPurgeableBytes -= resource->gpuMemorySize();
513 // SkTDPQueue will set the index back to -1 in debug builds, but we are using the index as a
514 // flag for whether the Resource has been purged from the cache or not. So we need to make sure
515 // it always gets set.
516 *resource->accessCacheIndex() = -1;
517 }
518
519 bool ResourceCache::inPurgeableQueue(const Resource* resource) const {
520 int index = *resource->accessCacheIndex();
521 return index >= 0 && index < fPurgeableQueue.count() &&
522 fPurgeableQueue.at(index) == resource;
523 }
524
525 #if defined(SK_DEBUG)
526
527 bool ResourceCache::inNonpurgeableArray(const Resource* resource) const {
528 int index = *resource->accessCacheIndex();
529 return index >= 0 && index < fNonpurgeableResources.size() &&
530 fNonpurgeableResources[index] == resource;
531 }
532
533 bool ResourceCache::isInCache(const Resource* resource) const {
534 if (this->inPurgeableQueue(resource) || this->inNonpurgeableArray(resource)) {
535 SkASSERT(resource->cache() == this);
536 SkASSERT(resource->hasCacheRef());
537 return true;
538 }
539 // Resource index should have been set to -1 if the resource is not in the cache
540 SkASSERT(*resource->accessCacheIndex() == -1);
541 // Don't assert that the resource has no cache ref, as the ResourceCache asserts this is false
542 // before it removes its cache ref in the event that that was the last resource keeping it alive
543 return false;
544 }
545
546 #endif // SK_DEBUG
547
548 void ResourceCache::purgeResource(Resource* resource) {
549 SkASSERT(resource->isPurgeable());
550
551 TRACE_EVENT_INSTANT1("skia.gpu.cache", TRACE_FUNC, TRACE_EVENT_SCOPE_THREAD,
552 "size", resource->gpuMemorySize());
553
554 this->removeFromResourceMap(resource);
555
556 if (resource->shouldDeleteASAP() == Resource::DeleteASAP::kNo) {
557 SkASSERT(this->inPurgeableQueue(resource));
558 this->removeFromPurgeableQueue(resource);
559 }
560
561 SkASSERT(!this->isInCache(resource));
562
563 fBudgetedBytes -= resource->gpuMemorySize();
564 resource->unrefCache();
565 }
566
567 void ResourceCache::purgeAsNeeded() {
568 ASSERT_SINGLE_OWNER
569
570 if (this->overbudget() && fProxyCache) {
571 fProxyCache->freeUniquelyHeld();
572
573 // After the image cache frees resources we need to return those resources to the cache
574 this->processReturnedResources();
575 }
576 while (this->overbudget() && fPurgeableQueue.count()) {
577 Resource* resource = fPurgeableQueue.peek();
578 SkASSERT(!resource->wasDestroyed());
579 SkASSERT(fResourceMap.has(resource, resource->key()));
580
581 if (resource->lastUseToken() == kMaxUseToken) {
582 // If we hit a resource that is at kMaxUseToken, then we've hit the part of the
583 // purgeable queue with all zero sized resources. We don't want to actually remove those
584 // so we just break here.
585 SkASSERT(resource->gpuMemorySize() == 0);
586 break;
587 }
588
589 this->purgeResource(resource);
590 }
591
592 this->validate();
593 }
594
595 void ResourceCache::purgeResourcesNotUsedSince(StdSteadyClock::time_point purgeTime) {
596 ASSERT_SINGLE_OWNER
597 this->purgeResources(&purgeTime);
598 }
599
600 void ResourceCache::purgeResources() {
601 ASSERT_SINGLE_OWNER
602 this->purgeResources(nullptr);
603 }
604
605 void ResourceCache::purgeResources(const StdSteadyClock::time_point* purgeTime) {
606 TRACE_EVENT0("skia.gpu.cache", TRACE_FUNC);
607 if (fProxyCache) {
608 fProxyCache->purgeProxiesNotUsedSince(purgeTime);
609 }
610 this->processReturnedResources();
611
612 // Early out if the very first item is too new to purge to avoid sorting the queue when
613 // nothing will be deleted.
614 if (fPurgeableQueue.count() &&
615 purgeTime &&
616 fPurgeableQueue.peek()->lastAccessTime() >= *purgeTime) {
617 return;
618 }
619
620 // Sort the queue
621 fPurgeableQueue.sort();
622
623 // Make a list of the scratch resources to delete
624 SkTDArray<Resource*> resourcesToPurge;
625 for (int i = 0; i < fPurgeableQueue.count(); i++) {
626 Resource* resource = fPurgeableQueue.at(i);
627
628 const skgpu::StdSteadyClock::time_point resourceTime = resource->lastAccessTime();
629 if (purgeTime && resourceTime >= *purgeTime) {
630 // scratch or not, all later iterations will be too recently used to purge.
631 break;
632 }
633 SkASSERT(resource->isPurgeable());
634 *resourcesToPurge.append() = resource;
635 }
636
637 // Delete the scratch resources. This must be done as a separate pass
638 // to avoid messing up the sorted order of the queue
639 for (int i = 0; i < resourcesToPurge.size(); i++) {
640 this->purgeResource(resourcesToPurge[i]);
641 }
642
643 // Since we called process returned resources at the start of this call, we could still end up
644 // over budget even after purging resources based on purgeTime. So we call purgeAsNeeded at the
645 // end here.
646 this->purgeAsNeeded();
647 }
648
649 uint32_t ResourceCache::getNextUseToken() {
650 // If we wrap then all the existing resources will appear older than any resources that get
651 // a token after the wrap. We wrap one value early when we reach kMaxUseToken so that we
652 // can continue to use kMaxUseToken as a special case for zero sized resources.
653 if (fUseToken == kMaxUseToken) {
654 fUseToken = 0;
655 int count = this->getResourceCount();
656 if (count) {
657 // Reset all the tokens. We sort the resources by their use token and then assign
658 // sequential tokens beginning with 0. This is O(n*lg(n)) but it should be very rare.
659 SkTDArray<Resource*> sortedPurgeableResources;
660 sortedPurgeableResources.reserve(fPurgeableQueue.count());
661
662 while (fPurgeableQueue.count()) {
663 *sortedPurgeableResources.append() = fPurgeableQueue.peek();
664 fPurgeableQueue.pop();
665 }
666
667 SkTQSort(fNonpurgeableResources.begin(), fNonpurgeableResources.end(), CompareUseToken);
668
669 // Pick resources out of the purgeable and non-purgeable arrays based on lowest
670 // use token and assign new tokens.
671 int currP = 0;
672 int currNP = 0;
673 while (currP < sortedPurgeableResources.size() &&
674 currNP < fNonpurgeableResources.size()) {
675 uint32_t tsP = sortedPurgeableResources[currP]->lastUseToken();
676 uint32_t tsNP = fNonpurgeableResources[currNP]->lastUseToken();
677 SkASSERT(tsP != tsNP);
678 if (tsP < tsNP) {
679 this->setResourceUseToken(sortedPurgeableResources[currP++], fUseToken++);
680 } else {
681 // Correct the index in the nonpurgeable array stored on the resource post-sort.
682 *fNonpurgeableResources[currNP]->accessCacheIndex() = currNP;
683 this->setResourceUseToken(fNonpurgeableResources[currNP++], fUseToken++);
684 }
685 }
686
687 // The above loop ended when we hit the end of one array. Finish the other one.
688 while (currP < sortedPurgeableResources.size()) {
689 this->setResourceUseToken(sortedPurgeableResources[currP++], fUseToken++);
690 }
691 while (currNP < fNonpurgeableResources.size()) {
692 *fNonpurgeableResources[currNP]->accessCacheIndex() = currNP;
693 this->setResourceUseToken(fNonpurgeableResources[currNP++], fUseToken++);
694 }
695
696 // Rebuild the queue.
697 for (int i = 0; i < sortedPurgeableResources.size(); ++i) {
698 fPurgeableQueue.insert(sortedPurgeableResources[i]);
699 }
700
701 this->validate();
702 SkASSERT(count == this->getResourceCount());
703
704 // count should be the next use token we return.
705 SkASSERT(fUseToken == SkToU32(count));
706 }
707 }
708 return fUseToken++;
709 }
710
711 void ResourceCache::setResourceUseToken(Resource* resource, uint32_t token) {
712 // We always set the use token for zero-sized resources to be kMaxUseToken
713 if (resource->gpuMemorySize() == 0) {
714 token = kMaxUseToken;
715 }
716 resource->setLastUseToken(token);
717 }
718
719 void ResourceCache::dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const {
720 ASSERT_SINGLE_OWNER
721
722 // There is no need to process the return queue here. Resources in the queue are still in
723 // either the purgeable queue or the nonpurgeable resources list (likely to be moved to the
724 // purgeable queue). However, the Resource's own ref counts are used to report its purgeable
725 // state to the memory dump, which is accurate without draining the return queue.
726
727 for (int i = 0; i < fNonpurgeableResources.size(); ++i) {
728 fNonpurgeableResources[i]->dumpMemoryStatistics(traceMemoryDump, false);
729 }
730 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
731 fPurgeableQueue.at(i)->dumpMemoryStatistics(traceMemoryDump, true);
732 }
733 }
734
735 void ResourceCache::setMaxBudget(size_t bytes) {
736 fMaxBytes = bytes;
737 this->processReturnedResources();
738 this->purgeAsNeeded();
739 }
740
741 ////////////////////////////////////////////////////////////////////////////////
742
743 #if defined(SK_DEBUG)
744 void ResourceCache::validate() const {
745 // Reduce the frequency of validations for large resource counts.
746 static SkRandom gRandom;
747 int mask = (SkNextPow2(fCount + 1) >> 5) - 1;
748 if (~mask && (gRandom.nextU() & mask)) {
749 return;
750 }
751
752 struct Stats {
753 int fShareable;
754 int fScratch;
755 size_t fBudgetedBytes;
756 size_t fPurgeableBytes;
757 const ResourceMap* fResourceMap;
758 const PurgeableQueue* fPurgeableQueue;
759
760 Stats(const ResourceCache* cache) {
761 memset(this, 0, sizeof(*this));
762 fResourceMap = &cache->fResourceMap;
763 fPurgeableQueue = &cache->fPurgeableQueue;
764 }
765
766 void update(Resource* resource) {
767 const GraphiteResourceKey& key = resource->key();
768 SkASSERT(key.isValid());
769
770 // All resources in the cache are owned. If we track wrapped resources in the cache
771 // we'll need to update this check.
772 SkASSERT(resource->ownership() == Ownership::kOwned);
773
774 if (resource->shareable() == Shareable::kYes) {
775 SkASSERT(resource->isAvailableForReuse());
776 SkASSERT(fResourceMap->has(resource, key));
777 SkASSERT(resource->budgeted() == Budgeted::kYes);
778 ++fShareable;
779 } else if (resource->isAvailableForReuse()) {
780 // We track scratch resources (either non-shareable with no refs that are returned,
781 // or explicitly scratch shared) separately from fully shareable.
782 SkASSERT(resource->isUsableAsScratch());
783 SkASSERT(fResourceMap->has(resource, key));
784 ++fScratch;
785 } else {
786 // This should be a non-shareable resource that isn't available for reuse.
787 SkASSERT(resource->shareable() == Shareable::kNo);
788 SkASSERT(!fResourceMap->has(resource, key));
789 }
790
791 if (resource->budgeted() == Budgeted::kYes) {
792 fBudgetedBytes += resource->gpuMemorySize();
793 }
794
795 if (resource->gpuMemorySize() == 0) {
796 SkASSERT(resource->lastUseToken() == kMaxUseToken);
797 } else {
798 SkASSERT(resource->lastUseToken() < kMaxUseToken);
799 }
800
801 int index = *resource->accessCacheIndex();
802 if (index < fPurgeableQueue->count() && fPurgeableQueue->at(index) == resource) {
803 SkASSERT(resource->isPurgeable());
804 fPurgeableBytes += resource->gpuMemorySize();
805 }
806 }
807 };
808
809 {
810 int count = 0;
811 fResourceMap.foreach([&](const Resource& resource) {
812 SkASSERT(resource.isUsableAsScratch() || resource.shareable() == Shareable::kYes);
813 SkASSERT(resource.budgeted() == Budgeted::kYes);
814 SkASSERT(resource.isAvailableForReuse());
815 SkASSERT(this->isInCache(&resource));
816 count++;
817 });
818 SkASSERT(count == fResourceMap.count());
819 }
820
821 // In the below checks we can assert that anything in the purgeable queue is purgeable because
822 // we won't put a Resource into that queue unless all refs are zero. Thus there is no way for
823 // that resource to be made non-purgeable without going through the cache (which will switch
824 // queues back to non-purgeable).
825 //
826 // However, we can't say the same for things in the non-purgeable array. It is possible that
827 // Resources have removed all their refs (thus technically become purgeable) but have not been
828 // processed back into the cache yet. Thus we may not have moved resources to the purgeable
829 // queue yet. Its also possible that Resource hasn't been added to the ReturnQueue yet (thread
830 // paused between unref and adding to ReturnQueue) so we can't even make asserts like not
831 // purgeable or is in ReturnQueue.
832 Stats stats(this);
833 for (int i = 0; i < fNonpurgeableResources.size(); ++i) {
834 SkASSERT(this->isInCache(fNonpurgeableResources[i]));
835 SkASSERT(*fNonpurgeableResources[i]->accessCacheIndex() == i);
836 SkASSERT(!fNonpurgeableResources[i]->wasDestroyed());
837 SkASSERT(!this->inPurgeableQueue(fNonpurgeableResources[i]));
838 stats.update(fNonpurgeableResources[i]);
839 }
840 bool firstPurgeableIsSizeZero = false;
841 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
842 if (i == 0) {
843 firstPurgeableIsSizeZero = (fPurgeableQueue.at(0)->gpuMemorySize() == 0);
844 }
845 if (firstPurgeableIsSizeZero) {
846 // If the first purgeable item (i.e. least recently used) is sized zero, then all other
847 // purgeable resources must also be sized zero since they should all have a use token of
848 // kMaxUseToken.
849 SkASSERT(fPurgeableQueue.at(i)->gpuMemorySize() == 0);
850 }
851 SkASSERT(this->isInCache(fPurgeableQueue.at(i)));
852 SkASSERT(fPurgeableQueue.at(i)->isPurgeable());
853 SkASSERT(*fPurgeableQueue.at(i)->accessCacheIndex() == i);
854 SkASSERT(!fPurgeableQueue.at(i)->wasDestroyed());
855 stats.update(fPurgeableQueue.at(i));
856 }
857
858 SkASSERT((stats.fScratch + stats.fShareable) == fResourceMap.count());
859 SkASSERT(stats.fBudgetedBytes == fBudgetedBytes);
860 SkASSERT(stats.fPurgeableBytes == fPurgeableBytes);
861 }
862
863 #endif // SK_DEBUG
864
865 #if defined(GPU_TEST_UTILS)
866
867 int ResourceCache::numFindableResources() const {
868 return fResourceMap.count();
869 }
870
871 Resource* ResourceCache::topOfPurgeableQueue() {
872 if (!fPurgeableQueue.count()) {
873 return nullptr;
874 }
875 return fPurgeableQueue.peek();
876 }
877
878 void ResourceCache::visitTextures(
879 const std::function<void(const Texture*, bool purgeable)>& func) const {
880 for (int i = 0; i < fNonpurgeableResources.size(); ++i) {
881 if (const Texture* tex = fNonpurgeableResources[i]->asTexture()) {
882 func(tex, /* purgeable= */ false);
883 }
884 }
885 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
886 if (const Texture* tex = fPurgeableQueue.at(i)->asTexture()) {
887 func(tex, /* purgeable= */ true);
888 }
889 }
890 }
891
892 #endif // defined(GPU_TEST_UTILS)
893
894 } // namespace skgpu::graphite