blob: ac2238527f0617e8a72013da3c5a336b3e40fddf [file] [log] [blame]
bsalomonc8dc1f72014-08-21 13:02:13 -07001/*
2 * Copyright 2014 Google Inc.
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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/gpu/GrResourceCache.h"
Brian Salomon614c1a82018-12-19 15:42:06 -05009#include <atomic>
Robert Phillips4e105e22020-07-16 09:18:50 -040010#include "include/gpu/GrDirectContext.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "include/private/GrSingleOwner.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "include/private/SkTo.h"
13#include "include/utils/SkRandom.h"
Ben Wagner21bca282019-05-15 10:15:52 -040014#include "src/core/SkMessageBus.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050015#include "src/core/SkOpts.h"
16#include "src/core/SkScopeExit.h"
John Stiles6e9ead92020-07-14 00:13:51 +000017#include "src/core/SkTSort.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/gpu/GrCaps.h"
Adlai Hollera0693042020-10-14 11:23:11 -040019#include "src/gpu/GrDirectContextPriv.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/gpu/GrGpuResourceCacheAccess.h"
21#include "src/gpu/GrProxyProvider.h"
Greg Daniel456f9b52020-03-05 19:14:18 +000022#include "src/gpu/GrTexture.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050023#include "src/gpu/GrTextureProxyCacheAccess.h"
Robert Phillipsd464feb2020-10-08 11:00:02 -040024#include "src/gpu/GrThreadSafeCache.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/gpu/GrTracing.h"
26#include "src/gpu/SkGr.h"
bsalomon71cb0c22014-11-14 12:10:14 -080027
Robert Phillipse7a959d2021-03-11 14:44:42 -050028DECLARE_SKMESSAGEBUS_MESSAGE(GrUniqueKeyInvalidatedMessage, uint32_t, true);
bsalomon71cb0c22014-11-14 12:10:14 -080029
Robert Phillipse7a959d2021-03-11 14:44:42 -050030DECLARE_SKMESSAGEBUS_MESSAGE(GrTextureFreedMessage, uint32_t, true);
Brian Osman13dddce2017-05-09 13:19:50 -040031
Adlai Holler33dbd652020-06-01 12:35:42 -040032#define ASSERT_SINGLE_OWNER GR_ASSERT_SINGLE_OWNER(fSingleOwner)
Brian Salomon8f8995a2018-10-15 14:32:15 -040033
bsalomon71cb0c22014-11-14 12:10:14 -080034//////////////////////////////////////////////////////////////////////////////
35
bsalomon7775c852014-12-30 12:50:52 -080036GrScratchKey::ResourceType GrScratchKey::GenerateResourceType() {
Mike Klein0ec1c572018-12-04 11:52:51 -050037 static std::atomic<int32_t> nextType{INHERITED::kInvalidDomain + 1};
bsalomonfe369ee2014-11-10 11:59:06 -080038
Adlai Holler4888cda2020-11-06 16:37:37 -050039 int32_t type = nextType.fetch_add(1, std::memory_order_relaxed);
Ben Wagner9bc36fd2018-06-15 14:23:36 -040040 if (type > SkTo<int32_t>(UINT16_MAX)) {
Ben Wagnerb4aab9a2017-08-16 10:53:04 -040041 SK_ABORT("Too many Resource Types");
bsalomon71cb0c22014-11-14 12:10:14 -080042 }
43
44 return static_cast<ResourceType>(type);
45}
46
bsalomon8718aaf2015-02-19 07:24:21 -080047GrUniqueKey::Domain GrUniqueKey::GenerateDomain() {
Mike Klein0ec1c572018-12-04 11:52:51 -050048 static std::atomic<int32_t> nextDomain{INHERITED::kInvalidDomain + 1};
bsalomon7775c852014-12-30 12:50:52 -080049
Adlai Holler4888cda2020-11-06 16:37:37 -050050 int32_t domain = nextDomain.fetch_add(1, std::memory_order_relaxed);
Ben Wagner397ee0e2018-06-15 15:13:26 -040051 if (domain > SkTo<int32_t>(UINT16_MAX)) {
Ben Wagnerb4aab9a2017-08-16 10:53:04 -040052 SK_ABORT("Too many GrUniqueKey Domains");
bsalomon7775c852014-12-30 12:50:52 -080053 }
bsalomon24db3b12015-01-23 04:24:04 -080054
55 return static_cast<Domain>(domain);
56}
bsalomon3f324322015-04-08 11:01:54 -070057
bsalomon24db3b12015-01-23 04:24:04 -080058uint32_t GrResourceKeyHash(const uint32_t* data, size_t size) {
mtklein4e976072016-08-08 09:06:27 -070059 return SkOpts::hash(data, size);
bsalomon7775c852014-12-30 12:50:52 -080060}
61
bsalomonfe369ee2014-11-10 11:59:06 -080062//////////////////////////////////////////////////////////////////////////////
63
bsalomon0ea80f42015-02-11 10:49:59 -080064class GrResourceCache::AutoValidate : ::SkNoncopyable {
bsalomon71cb0c22014-11-14 12:10:14 -080065public:
bsalomon0ea80f42015-02-11 10:49:59 -080066 AutoValidate(GrResourceCache* cache) : fCache(cache) { cache->validate(); }
bsalomon71cb0c22014-11-14 12:10:14 -080067 ~AutoValidate() { fCache->validate(); }
68private:
bsalomon0ea80f42015-02-11 10:49:59 -080069 GrResourceCache* fCache;
bsalomon71cb0c22014-11-14 12:10:14 -080070};
71
Brian Salomon876a0172019-03-08 11:12:14 -050072//////////////////////////////////////////////////////////////////////////////
73
Robert Phillipsddc21482019-10-16 14:30:09 -040074inline GrResourceCache::TextureAwaitingUnref::TextureAwaitingUnref() = default;
Brian Salomon876a0172019-03-08 11:12:14 -050075
Robert Phillipsddc21482019-10-16 14:30:09 -040076inline GrResourceCache::TextureAwaitingUnref::TextureAwaitingUnref(GrTexture* texture)
77 : fTexture(texture), fNumUnrefs(1) {}
Brian Salomon876a0172019-03-08 11:12:14 -050078
Robert Phillipsddc21482019-10-16 14:30:09 -040079inline GrResourceCache::TextureAwaitingUnref::TextureAwaitingUnref(TextureAwaitingUnref&& that) {
Adlai Holler5ba50af2020-04-29 21:11:14 -040080 fTexture = std::exchange(that.fTexture, nullptr);
81 fNumUnrefs = std::exchange(that.fNumUnrefs, 0);
Brian Salomon876a0172019-03-08 11:12:14 -050082}
83
Robert Phillipsddc21482019-10-16 14:30:09 -040084inline GrResourceCache::TextureAwaitingUnref& GrResourceCache::TextureAwaitingUnref::operator=(
85 TextureAwaitingUnref&& that) {
Adlai Holler5ba50af2020-04-29 21:11:14 -040086 fTexture = std::exchange(that.fTexture, nullptr);
87 fNumUnrefs = std::exchange(that.fNumUnrefs, 0);
Brian Salomon876a0172019-03-08 11:12:14 -050088 return *this;
89}
90
Robert Phillipsddc21482019-10-16 14:30:09 -040091inline GrResourceCache::TextureAwaitingUnref::~TextureAwaitingUnref() {
92 if (fTexture) {
Brian Salomon876a0172019-03-08 11:12:14 -050093 for (int i = 0; i < fNumUnrefs; ++i) {
Robert Phillipsddc21482019-10-16 14:30:09 -040094 fTexture->unref();
Brian Salomon876a0172019-03-08 11:12:14 -050095 }
96 }
97}
98
Robert Phillipsddc21482019-10-16 14:30:09 -040099inline void GrResourceCache::TextureAwaitingUnref::TextureAwaitingUnref::addRef() { ++fNumUnrefs; }
Brian Salomon876a0172019-03-08 11:12:14 -0500100
Robert Phillipsddc21482019-10-16 14:30:09 -0400101inline void GrResourceCache::TextureAwaitingUnref::unref() {
Brian Salomon876a0172019-03-08 11:12:14 -0500102 SkASSERT(fNumUnrefs > 0);
Robert Phillipsddc21482019-10-16 14:30:09 -0400103 fTexture->unref();
Brian Salomon876a0172019-03-08 11:12:14 -0500104 --fNumUnrefs;
105}
106
Robert Phillipsddc21482019-10-16 14:30:09 -0400107inline bool GrResourceCache::TextureAwaitingUnref::finished() { return !fNumUnrefs; }
Brian Salomon876a0172019-03-08 11:12:14 -0500108
109//////////////////////////////////////////////////////////////////////////////
robertphillipsee843b22016-10-04 05:30:20 -0700110
Brian Salomonbe1084b2021-01-26 13:29:30 -0500111GrResourceCache::GrResourceCache(GrSingleOwner* singleOwner, uint32_t contextUniqueID)
Brian Salomon2c791fc2019-04-02 11:52:03 -0400112 : fInvalidUniqueKeyInbox(contextUniqueID)
Robert Phillipsddc21482019-10-16 14:30:09 -0400113 , fFreedTextureInbox(contextUniqueID)
Brian Salomon238069b2018-07-11 15:58:57 -0400114 , fContextUniqueID(contextUniqueID)
Brian Salomonbe1084b2021-01-26 13:29:30 -0500115 , fSingleOwner(singleOwner) {
Brian Salomon238069b2018-07-11 15:58:57 -0400116 SkASSERT(contextUniqueID != SK_InvalidUniqueID);
bsalomon71cb0c22014-11-14 12:10:14 -0800117}
118
bsalomon0ea80f42015-02-11 10:49:59 -0800119GrResourceCache::~GrResourceCache() {
bsalomonc8dc1f72014-08-21 13:02:13 -0700120 this->releaseAll();
121}
122
Robert Phillipscf39f372019-09-03 10:29:20 -0400123void GrResourceCache::setLimit(size_t bytes) {
bsalomon71cb0c22014-11-14 12:10:14 -0800124 fMaxBytes = bytes;
125 this->purgeAsNeeded();
126}
127
bsalomon0ea80f42015-02-11 10:49:59 -0800128void GrResourceCache::insertResource(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400129 ASSERT_SINGLE_OWNER
bsalomon49f085d2014-09-05 13:34:00 -0700130 SkASSERT(resource);
bsalomon16961262014-08-26 14:01:07 -0700131 SkASSERT(!this->isInCache(resource));
bsalomonf320e042015-02-17 15:09:34 -0800132 SkASSERT(!resource->wasDestroyed());
Brian Salomon614c1a82018-12-19 15:42:06 -0500133 SkASSERT(!resource->resourcePriv().isPurgeable());
bsalomonddf30e62015-02-19 11:38:44 -0800134
135 // We must set the timestamp before adding to the array in case the timestamp wraps and we wind
136 // up iterating over all the resources that already have timestamps.
137 resource->cacheAccess().setTimestamp(this->getNextTimestamp());
138
bsalomonf320e042015-02-17 15:09:34 -0800139 this->addToNonpurgeableArray(resource);
bsalomon71cb0c22014-11-14 12:10:14 -0800140
bsalomondace19e2014-11-17 07:34:06 -0800141 size_t size = resource->gpuMemorySize();
bsalomonf320e042015-02-17 15:09:34 -0800142 SkDEBUGCODE(++fCount;)
bsalomon84c8e622014-11-17 09:33:27 -0800143 fBytes += size;
bsalomon82b1d622014-11-14 13:59:57 -0800144#if GR_CACHE_STATS
Brian Osman788b9162020-02-07 10:36:46 -0500145 fHighWaterCount = std::max(this->getResourceCount(), fHighWaterCount);
146 fHighWaterBytes = std::max(fBytes, fHighWaterBytes);
bsalomon82b1d622014-11-14 13:59:57 -0800147#endif
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500148 if (GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType()) {
bsalomondace19e2014-11-17 07:34:06 -0800149 ++fBudgetedCount;
150 fBudgetedBytes += size;
Brian Osman39c08ac2017-07-26 09:36:09 -0400151 TRACE_COUNTER2("skia.gpu.cache", "skia budget", "used",
hendrikw876c3132015-03-04 10:33:49 -0800152 fBudgetedBytes, "free", fMaxBytes - fBudgetedBytes);
bsalomondace19e2014-11-17 07:34:06 -0800153#if GR_CACHE_STATS
Brian Osman788b9162020-02-07 10:36:46 -0500154 fBudgetedHighWaterCount = std::max(fBudgetedCount, fBudgetedHighWaterCount);
155 fBudgetedHighWaterBytes = std::max(fBudgetedBytes, fBudgetedHighWaterBytes);
bsalomondace19e2014-11-17 07:34:06 -0800156#endif
157 }
Greg Danielda642612021-02-09 18:04:02 -0500158 SkASSERT(!resource->cacheAccess().isUsableAsScratch());
bsalomon71cb0c22014-11-14 12:10:14 -0800159 this->purgeAsNeeded();
bsalomonc8dc1f72014-08-21 13:02:13 -0700160}
161
bsalomon0ea80f42015-02-11 10:49:59 -0800162void GrResourceCache::removeResource(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400163 ASSERT_SINGLE_OWNER
bsalomon9f2d1572015-02-17 11:47:40 -0800164 this->validate();
bsalomon16961262014-08-26 14:01:07 -0700165 SkASSERT(this->isInCache(resource));
bsalomondace19e2014-11-17 07:34:06 -0800166
Derek Sollenbergeree479142017-05-24 11:41:33 -0400167 size_t size = resource->gpuMemorySize();
Brian Salomon614c1a82018-12-19 15:42:06 -0500168 if (resource->resourcePriv().isPurgeable()) {
bsalomon9f2d1572015-02-17 11:47:40 -0800169 fPurgeableQueue.remove(resource);
Derek Sollenbergeree479142017-05-24 11:41:33 -0400170 fPurgeableBytes -= size;
bsalomonf320e042015-02-17 15:09:34 -0800171 } else {
172 this->removeFromNonpurgeableArray(resource);
bsalomon9f2d1572015-02-17 11:47:40 -0800173 }
174
bsalomonf320e042015-02-17 15:09:34 -0800175 SkDEBUGCODE(--fCount;)
bsalomondace19e2014-11-17 07:34:06 -0800176 fBytes -= size;
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500177 if (GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType()) {
bsalomondace19e2014-11-17 07:34:06 -0800178 --fBudgetedCount;
179 fBudgetedBytes -= size;
Brian Osman39c08ac2017-07-26 09:36:09 -0400180 TRACE_COUNTER2("skia.gpu.cache", "skia budget", "used",
hendrikw876c3132015-03-04 10:33:49 -0800181 fBudgetedBytes, "free", fMaxBytes - fBudgetedBytes);
bsalomondace19e2014-11-17 07:34:06 -0800182 }
183
Greg Danielda642612021-02-09 18:04:02 -0500184 if (resource->cacheAccess().isUsableAsScratch()) {
bsalomon3582d3e2015-02-13 14:20:05 -0800185 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
bsalomon744998e2014-08-28 09:54:34 -0700186 }
bsalomon8718aaf2015-02-19 07:24:21 -0800187 if (resource->getUniqueKey().isValid()) {
188 fUniqueHash.remove(resource->getUniqueKey());
bsalomon8b79d232014-11-10 10:19:06 -0800189 }
bsalomonb436ed62014-11-17 12:15:56 -0800190 this->validate();
bsalomonc8dc1f72014-08-21 13:02:13 -0700191}
192
bsalomon0ea80f42015-02-11 10:49:59 -0800193void GrResourceCache::abandonAll() {
bsalomon71cb0c22014-11-14 12:10:14 -0800194 AutoValidate av(this);
195
Brian Salomon876a0172019-03-08 11:12:14 -0500196 // We need to make sure to free any resources that were waiting on a free message but never
197 // received one.
Robert Phillipsddc21482019-10-16 14:30:09 -0400198 fTexturesAwaitingUnref.reset();
Greg Danielb2acf0a2018-09-12 09:17:11 -0400199
bsalomonf320e042015-02-17 15:09:34 -0800200 while (fNonpurgeableResources.count()) {
201 GrGpuResource* back = *(fNonpurgeableResources.end() - 1);
202 SkASSERT(!back->wasDestroyed());
203 back->cacheAccess().abandon();
bsalomonc8dc1f72014-08-21 13:02:13 -0700204 }
bsalomonf320e042015-02-17 15:09:34 -0800205
206 while (fPurgeableQueue.count()) {
207 GrGpuResource* top = fPurgeableQueue.peek();
208 SkASSERT(!top->wasDestroyed());
209 top->cacheAccess().abandon();
210 }
211
Robert Phillipseb999bc2020-11-03 08:41:47 -0500212 fThreadSafeCache->dropAllRefs();
213
bsalomon744998e2014-08-28 09:54:34 -0700214 SkASSERT(!fScratchMap.count());
bsalomon8718aaf2015-02-19 07:24:21 -0800215 SkASSERT(!fUniqueHash.count());
bsalomonc8dc1f72014-08-21 13:02:13 -0700216 SkASSERT(!fCount);
bsalomonf320e042015-02-17 15:09:34 -0800217 SkASSERT(!this->getResourceCount());
bsalomondace19e2014-11-17 07:34:06 -0800218 SkASSERT(!fBytes);
219 SkASSERT(!fBudgetedCount);
220 SkASSERT(!fBudgetedBytes);
Derek Sollenbergeree479142017-05-24 11:41:33 -0400221 SkASSERT(!fPurgeableBytes);
Robert Phillipsddc21482019-10-16 14:30:09 -0400222 SkASSERT(!fTexturesAwaitingUnref.count());
bsalomonc8dc1f72014-08-21 13:02:13 -0700223}
224
bsalomon0ea80f42015-02-11 10:49:59 -0800225void GrResourceCache::releaseAll() {
bsalomon71cb0c22014-11-14 12:10:14 -0800226 AutoValidate av(this);
227
Robert Phillipsd464feb2020-10-08 11:00:02 -0400228 fThreadSafeCache->dropAllRefs();
Robert Phillips12d06a32020-09-16 12:31:34 -0400229
Brian Osman13dddce2017-05-09 13:19:50 -0400230 this->processFreedGpuResources();
231
Greg Danielc27eb722018-08-10 09:48:08 -0400232 // We need to make sure to free any resources that were waiting on a free message but never
233 // received one.
Robert Phillipsddc21482019-10-16 14:30:09 -0400234 fTexturesAwaitingUnref.reset();
Greg Danielc27eb722018-08-10 09:48:08 -0400235
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500236 SkASSERT(fProxyProvider); // better have called setProxyProvider
Robert Phillipsd464feb2020-10-08 11:00:02 -0400237 SkASSERT(fThreadSafeCache); // better have called setThreadSafeCache too
Robert Phillips12d06a32020-09-16 12:31:34 -0400238
Robert Phillips3ec95732017-09-29 15:10:39 -0400239 // We must remove the uniqueKeys from the proxies here. While they possess a uniqueKey
240 // they also have a raw pointer back to this class (which is presumably going away)!
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500241 fProxyProvider->removeAllUniqueKeys();
Robert Phillips45a6f142017-09-29 09:49:41 -0400242
Brian Salomon614c1a82018-12-19 15:42:06 -0500243 while (fNonpurgeableResources.count()) {
bsalomonf320e042015-02-17 15:09:34 -0800244 GrGpuResource* back = *(fNonpurgeableResources.end() - 1);
245 SkASSERT(!back->wasDestroyed());
246 back->cacheAccess().release();
bsalomonc8dc1f72014-08-21 13:02:13 -0700247 }
bsalomonf320e042015-02-17 15:09:34 -0800248
249 while (fPurgeableQueue.count()) {
250 GrGpuResource* top = fPurgeableQueue.peek();
251 SkASSERT(!top->wasDestroyed());
252 top->cacheAccess().release();
253 }
254
bsalomon744998e2014-08-28 09:54:34 -0700255 SkASSERT(!fScratchMap.count());
bsalomon8718aaf2015-02-19 07:24:21 -0800256 SkASSERT(!fUniqueHash.count());
bsalomonc8dc1f72014-08-21 13:02:13 -0700257 SkASSERT(!fCount);
bsalomonf320e042015-02-17 15:09:34 -0800258 SkASSERT(!this->getResourceCount());
bsalomondace19e2014-11-17 07:34:06 -0800259 SkASSERT(!fBytes);
260 SkASSERT(!fBudgetedCount);
261 SkASSERT(!fBudgetedBytes);
Derek Sollenbergeree479142017-05-24 11:41:33 -0400262 SkASSERT(!fPurgeableBytes);
Robert Phillipsddc21482019-10-16 14:30:09 -0400263 SkASSERT(!fTexturesAwaitingUnref.count());
bsalomonc8dc1f72014-08-21 13:02:13 -0700264}
bsalomonbcf0a522014-10-08 08:40:09 -0700265
Brian Salomon2c791fc2019-04-02 11:52:03 -0400266void GrResourceCache::refResource(GrGpuResource* resource) {
267 SkASSERT(resource);
268 SkASSERT(resource->getContext()->priv().getResourceCache() == this);
269 if (resource->cacheAccess().hasRef()) {
270 resource->ref();
271 } else {
272 this->refAndMakeResourceMRU(resource);
273 }
274 this->validate();
275}
276
bsalomon0ea80f42015-02-11 10:49:59 -0800277class GrResourceCache::AvailableForScratchUse {
bsalomonbcf0a522014-10-08 08:40:09 -0700278public:
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400279 AvailableForScratchUse() { }
bsalomonbcf0a522014-10-08 08:40:09 -0700280
281 bool operator()(const GrGpuResource* resource) const {
Greg Danielda642612021-02-09 18:04:02 -0500282 // Everything that is in the scratch map should be usable as a
283 // scratch resource.
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400284 return true;
bsalomonbcf0a522014-10-08 08:40:09 -0700285 }
bsalomonbcf0a522014-10-08 08:40:09 -0700286};
287
Robert Phillipsaee18c92019-09-06 11:48:27 -0400288GrGpuResource* GrResourceCache::findAndRefScratchResource(const GrScratchKey& scratchKey) {
bsalomon7775c852014-12-30 12:50:52 -0800289 SkASSERT(scratchKey.isValid());
robertphillipsee843b22016-10-04 05:30:20 -0700290
Robert Phillipsaee18c92019-09-06 11:48:27 -0400291 GrGpuResource* resource = fScratchMap.find(scratchKey, AvailableForScratchUse());
bsalomon71cb0c22014-11-14 12:10:14 -0800292 if (resource) {
Greg Danielda642612021-02-09 18:04:02 -0500293 fScratchMap.remove(scratchKey, resource);
bsalomon9f2d1572015-02-17 11:47:40 -0800294 this->refAndMakeResourceMRU(resource);
bsalomonb436ed62014-11-17 12:15:56 -0800295 this->validate();
bsalomon71cb0c22014-11-14 12:10:14 -0800296 }
297 return resource;
bsalomonbcf0a522014-10-08 08:40:09 -0700298}
bsalomon8b79d232014-11-10 10:19:06 -0800299
bsalomon0ea80f42015-02-11 10:49:59 -0800300void GrResourceCache::willRemoveScratchKey(const GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400301 ASSERT_SINGLE_OWNER
bsalomon3582d3e2015-02-13 14:20:05 -0800302 SkASSERT(resource->resourcePriv().getScratchKey().isValid());
Greg Danielda642612021-02-09 18:04:02 -0500303 if (resource->cacheAccess().isUsableAsScratch()) {
robertphillipsc4ed6842016-05-24 14:17:12 -0700304 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
305 }
bsalomon10e23ca2014-11-25 05:52:06 -0800306}
307
bsalomonf99e9612015-02-19 08:24:16 -0800308void GrResourceCache::removeUniqueKey(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400309 ASSERT_SINGLE_OWNER
bsalomon3f324322015-04-08 11:01:54 -0700310 // Someone has a ref to this resource in order to have removed the key. When the ref count
311 // reaches zero we will get a ref cnt notification and figure out what to do with it.
bsalomonf99e9612015-02-19 08:24:16 -0800312 if (resource->getUniqueKey().isValid()) {
313 SkASSERT(resource == fUniqueHash.find(resource->getUniqueKey()));
314 fUniqueHash.remove(resource->getUniqueKey());
315 }
316 resource->cacheAccess().removeUniqueKey();
Greg Danielda642612021-02-09 18:04:02 -0500317 if (resource->cacheAccess().isUsableAsScratch()) {
robertphillipsc4ed6842016-05-24 14:17:12 -0700318 fScratchMap.insert(resource->resourcePriv().getScratchKey(), resource);
319 }
320
Brian Salomon9bc76d92019-01-24 12:18:33 -0500321 // Removing a unique key from a kUnbudgetedCacheable resource would make the resource
322 // require purging. However, the resource must be ref'ed to get here and therefore can't
323 // be purgeable. We'll purge it when the refs reach zero.
324 SkASSERT(!resource->resourcePriv().isPurgeable());
bsalomonf99e9612015-02-19 08:24:16 -0800325 this->validate();
bsalomon23e619c2015-02-06 11:54:28 -0800326}
327
bsalomonf99e9612015-02-19 08:24:16 -0800328void GrResourceCache::changeUniqueKey(GrGpuResource* resource, const GrUniqueKey& newKey) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400329 ASSERT_SINGLE_OWNER
bsalomon8b79d232014-11-10 10:19:06 -0800330 SkASSERT(resource);
bsalomon71cb0c22014-11-14 12:10:14 -0800331 SkASSERT(this->isInCache(resource));
bsalomon8b79d232014-11-10 10:19:06 -0800332
bsalomonf99e9612015-02-19 08:24:16 -0800333 // If another resource has the new key, remove its key then install the key on this resource.
334 if (newKey.isValid()) {
Greg Daniel0d537802017-09-08 11:44:14 -0400335 if (GrGpuResource* old = fUniqueHash.find(newKey)) {
336 // If the old resource using the key is purgeable and is unreachable, then remove it.
Brian Salomon614c1a82018-12-19 15:42:06 -0500337 if (!old->resourcePriv().getScratchKey().isValid() &&
338 old->resourcePriv().isPurgeable()) {
Greg Daniel0d537802017-09-08 11:44:14 -0400339 old->cacheAccess().release();
340 } else {
Brian Salomon9bc76d92019-01-24 12:18:33 -0500341 // removeUniqueKey expects an external owner of the resource.
342 this->removeUniqueKey(sk_ref_sp(old).get());
Greg Daniel0d537802017-09-08 11:44:14 -0400343 }
344 }
345 SkASSERT(nullptr == fUniqueHash.find(newKey));
346
robertphillipsc4ed6842016-05-24 14:17:12 -0700347 // Remove the entry for this resource if it already has a unique key.
348 if (resource->getUniqueKey().isValid()) {
349 SkASSERT(resource == fUniqueHash.find(resource->getUniqueKey()));
350 fUniqueHash.remove(resource->getUniqueKey());
351 SkASSERT(nullptr == fUniqueHash.find(resource->getUniqueKey()));
352 } else {
353 // 'resource' didn't have a valid unique key before so it is switching sides. Remove it
Greg Danielda642612021-02-09 18:04:02 -0500354 // from the ScratchMap. The isUsableAsScratch call depends on us not adding the new
355 // unique key until after this check.
356 if (resource->cacheAccess().isUsableAsScratch()) {
robertphillipsc4ed6842016-05-24 14:17:12 -0700357 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
358 }
359 }
360
bsalomonf99e9612015-02-19 08:24:16 -0800361 resource->cacheAccess().setUniqueKey(newKey);
362 fUniqueHash.add(resource);
363 } else {
robertphillipsc4ed6842016-05-24 14:17:12 -0700364 this->removeUniqueKey(resource);
bsalomonf99e9612015-02-19 08:24:16 -0800365 }
366
bsalomon71cb0c22014-11-14 12:10:14 -0800367 this->validate();
bsalomon8b79d232014-11-10 10:19:06 -0800368}
bsalomon71cb0c22014-11-14 12:10:14 -0800369
bsalomon9f2d1572015-02-17 11:47:40 -0800370void GrResourceCache::refAndMakeResourceMRU(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400371 ASSERT_SINGLE_OWNER
bsalomon71cb0c22014-11-14 12:10:14 -0800372 SkASSERT(resource);
373 SkASSERT(this->isInCache(resource));
bsalomonddf30e62015-02-19 11:38:44 -0800374
Brian Salomon614c1a82018-12-19 15:42:06 -0500375 if (resource->resourcePriv().isPurgeable()) {
bsalomon9f2d1572015-02-17 11:47:40 -0800376 // It's about to become unpurgeable.
Derek Sollenbergeree479142017-05-24 11:41:33 -0400377 fPurgeableBytes -= resource->gpuMemorySize();
bsalomon9f2d1572015-02-17 11:47:40 -0800378 fPurgeableQueue.remove(resource);
bsalomonf320e042015-02-17 15:09:34 -0800379 this->addToNonpurgeableArray(resource);
Greg Daniel1fd8ac82020-12-11 11:22:01 -0500380 } else if (!resource->cacheAccess().hasRefOrCommandBufferUsage() &&
Brian Salomon2c791fc2019-04-02 11:52:03 -0400381 resource->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted) {
382 SkASSERT(fNumBudgetedResourcesFlushWillMakePurgeable > 0);
383 fNumBudgetedResourcesFlushWillMakePurgeable--;
bsalomon9f2d1572015-02-17 11:47:40 -0800384 }
Brian Salomon01ceae92019-04-02 11:49:54 -0400385 resource->cacheAccess().ref();
bsalomonddf30e62015-02-19 11:38:44 -0800386
387 resource->cacheAccess().setTimestamp(this->getNextTimestamp());
bsalomonf320e042015-02-17 15:09:34 -0800388 this->validate();
bsalomon71cb0c22014-11-14 12:10:14 -0800389}
390
Greg Danielda642612021-02-09 18:04:02 -0500391void GrResourceCache::notifyARefCntReachedZero(GrGpuResource* resource,
392 GrGpuResource::LastRemovedRef removedRef) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400393 ASSERT_SINGLE_OWNER
bsalomon71cb0c22014-11-14 12:10:14 -0800394 SkASSERT(resource);
bsalomon3f324322015-04-08 11:01:54 -0700395 SkASSERT(!resource->wasDestroyed());
bsalomon71cb0c22014-11-14 12:10:14 -0800396 SkASSERT(this->isInCache(resource));
bsalomon3f324322015-04-08 11:01:54 -0700397 // This resource should always be in the nonpurgeable array when this function is called. It
398 // will be moved to the queue if it is newly purgeable.
399 SkASSERT(fNonpurgeableResources[*resource->cacheAccess().accessCacheIndex()] == resource);
bsalomon71cb0c22014-11-14 12:10:14 -0800400
Greg Danielda642612021-02-09 18:04:02 -0500401 if (removedRef == GrGpuResource::LastRemovedRef::kMainRef) {
402 if (resource->cacheAccess().isUsableAsScratch()) {
403 fScratchMap.insert(resource->resourcePriv().getScratchKey(), resource);
404 }
405 }
406
407 if (resource->cacheAccess().hasRefOrCommandBufferUsage()) {
408 this->validate();
409 return;
410 }
411
bsalomon3f324322015-04-08 11:01:54 -0700412#ifdef SK_DEBUG
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400413 // When the timestamp overflows validate() is called. validate() checks that resources in
414 // the nonpurgeable array are indeed not purgeable. However, the movement from the array to
415 // the purgeable queue happens just below in this function. So we mark it as an exception.
416 if (resource->resourcePriv().isPurgeable()) {
417 fNewlyPurgeableResourceForValidation = resource;
bsalomon3f324322015-04-08 11:01:54 -0700418 }
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400419#endif
420 resource->cacheAccess().setTimestamp(this->getNextTimestamp());
421 SkDEBUGCODE(fNewlyPurgeableResourceForValidation = nullptr);
bsalomon3f324322015-04-08 11:01:54 -0700422
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400423 if (!resource->resourcePriv().isPurgeable() &&
424 resource->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted) {
425 ++fNumBudgetedResourcesFlushWillMakePurgeable;
bsalomon3f324322015-04-08 11:01:54 -0700426 }
427
Brian Salomon9bc76d92019-01-24 12:18:33 -0500428 if (!resource->resourcePriv().isPurgeable()) {
429 this->validate();
430 return;
431 }
432
bsalomonf320e042015-02-17 15:09:34 -0800433 this->removeFromNonpurgeableArray(resource);
bsalomon9f2d1572015-02-17 11:47:40 -0800434 fPurgeableQueue.insert(resource);
Brian Salomon5e150852017-03-22 14:53:13 -0400435 resource->cacheAccess().setTimeWhenResourceBecomePurgeable();
Derek Sollenbergeree479142017-05-24 11:41:33 -0400436 fPurgeableBytes += resource->gpuMemorySize();
bsalomon71cb0c22014-11-14 12:10:14 -0800437
Greg Daniel303e83e2018-09-10 14:10:19 -0400438 bool hasUniqueKey = resource->getUniqueKey().isValid();
439
Brian Salomon9bc76d92019-01-24 12:18:33 -0500440 GrBudgetedType budgetedType = resource->resourcePriv().budgetedType();
Brian Salomon614c1a82018-12-19 15:42:06 -0500441
Brian Salomon9bc76d92019-01-24 12:18:33 -0500442 if (budgetedType == GrBudgetedType::kBudgeted) {
443 // Purge the resource immediately if we're over budget
444 // Also purge if the resource has neither a valid scratch key nor a unique key.
445 bool hasKey = resource->resourcePriv().getScratchKey().isValid() || hasUniqueKey;
446 if (!this->overBudget() && hasKey) {
447 return;
448 }
449 } else {
450 // We keep unbudgeted resources with a unique key in the purgeable queue of the cache so
451 // they can be reused again by the image connected to the unique key.
452 if (hasUniqueKey && budgetedType == GrBudgetedType::kUnbudgetedCacheable) {
453 return;
454 }
455 // Check whether this resource could still be used as a scratch resource.
456 if (!resource->resourcePriv().refsWrappedObjects() &&
457 resource->resourcePriv().getScratchKey().isValid()) {
458 // We won't purge an existing resource to make room for this one.
Robert Phillipscf39f372019-09-03 10:29:20 -0400459 if (this->wouldFit(resource->gpuMemorySize())) {
Brian Salomon9bc76d92019-01-24 12:18:33 -0500460 resource->resourcePriv().makeBudgeted();
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500461 return;
462 }
bsalomonc2f35b72015-01-23 07:19:22 -0800463 }
bsalomonc2f35b72015-01-23 07:19:22 -0800464 }
Brian Salomon9bc76d92019-01-24 12:18:33 -0500465
bsalomonf320e042015-02-17 15:09:34 -0800466 SkDEBUGCODE(int beforeCount = this->getResourceCount();)
bsalomon9f2d1572015-02-17 11:47:40 -0800467 resource->cacheAccess().release();
468 // We should at least free this resource, perhaps dependent resources as well.
bsalomonf320e042015-02-17 15:09:34 -0800469 SkASSERT(this->getResourceCount() < beforeCount);
bsalomon71cb0c22014-11-14 12:10:14 -0800470 this->validate();
471}
472
bsalomon0ea80f42015-02-11 10:49:59 -0800473void GrResourceCache::didChangeBudgetStatus(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400474 ASSERT_SINGLE_OWNER
bsalomon84c8e622014-11-17 09:33:27 -0800475 SkASSERT(resource);
476 SkASSERT(this->isInCache(resource));
477
478 size_t size = resource->gpuMemorySize();
Brian Salomon9bc76d92019-01-24 12:18:33 -0500479 // Changing from BudgetedType::kUnbudgetedCacheable to another budgeted type could make
480 // resource become purgeable. However, we should never allow that transition. Wrapped
481 // resources are the only resources that can be in that state and they aren't allowed to
482 // transition from one budgeted state to another.
483 SkDEBUGCODE(bool wasPurgeable = resource->resourcePriv().isPurgeable());
484 if (resource->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted) {
bsalomon84c8e622014-11-17 09:33:27 -0800485 ++fBudgetedCount;
486 fBudgetedBytes += size;
bsalomonafe30052015-01-16 07:32:33 -0800487#if GR_CACHE_STATS
Brian Osman788b9162020-02-07 10:36:46 -0500488 fBudgetedHighWaterBytes = std::max(fBudgetedBytes, fBudgetedHighWaterBytes);
489 fBudgetedHighWaterCount = std::max(fBudgetedCount, fBudgetedHighWaterCount);
bsalomonafe30052015-01-16 07:32:33 -0800490#endif
Greg Daniel1fd8ac82020-12-11 11:22:01 -0500491 if (!resource->resourcePriv().isPurgeable() &&
492 !resource->cacheAccess().hasRefOrCommandBufferUsage()) {
Brian Salomon2c791fc2019-04-02 11:52:03 -0400493 ++fNumBudgetedResourcesFlushWillMakePurgeable;
494 }
Greg Danielda642612021-02-09 18:04:02 -0500495 if (resource->cacheAccess().isUsableAsScratch()) {
496 fScratchMap.insert(resource->resourcePriv().getScratchKey(), resource);
497 }
bsalomon84c8e622014-11-17 09:33:27 -0800498 this->purgeAsNeeded();
499 } else {
Brian Salomon9bc76d92019-01-24 12:18:33 -0500500 SkASSERT(resource->resourcePriv().budgetedType() != GrBudgetedType::kUnbudgetedCacheable);
bsalomon84c8e622014-11-17 09:33:27 -0800501 --fBudgetedCount;
502 fBudgetedBytes -= size;
Greg Daniel1fd8ac82020-12-11 11:22:01 -0500503 if (!resource->resourcePriv().isPurgeable() &&
504 !resource->cacheAccess().hasRefOrCommandBufferUsage()) {
Brian Salomon2c791fc2019-04-02 11:52:03 -0400505 --fNumBudgetedResourcesFlushWillMakePurgeable;
506 }
Greg Danielda642612021-02-09 18:04:02 -0500507 if (!resource->cacheAccess().hasRef() && !resource->getUniqueKey().isValid() &&
508 resource->resourcePriv().getScratchKey().isValid()) {
509 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
510 }
bsalomon84c8e622014-11-17 09:33:27 -0800511 }
Brian Salomon9bc76d92019-01-24 12:18:33 -0500512 SkASSERT(wasPurgeable == resource->resourcePriv().isPurgeable());
Brian Osman39c08ac2017-07-26 09:36:09 -0400513 TRACE_COUNTER2("skia.gpu.cache", "skia budget", "used",
hendrikw876c3132015-03-04 10:33:49 -0800514 fBudgetedBytes, "free", fMaxBytes - fBudgetedBytes);
bsalomon84c8e622014-11-17 09:33:27 -0800515
516 this->validate();
517}
518
robertphillipsee843b22016-10-04 05:30:20 -0700519void GrResourceCache::purgeAsNeeded() {
bsalomon3f324322015-04-08 11:01:54 -0700520 SkTArray<GrUniqueKeyInvalidatedMessage> invalidKeyMsgs;
521 fInvalidUniqueKeyInbox.poll(&invalidKeyMsgs);
522 if (invalidKeyMsgs.count()) {
Robert Phillips427966a2018-12-20 17:20:43 -0500523 SkASSERT(fProxyProvider);
524
525 for (int i = 0; i < invalidKeyMsgs.count(); ++i) {
Robert Phillips83c38a82020-10-28 14:57:53 -0400526 if (invalidKeyMsgs[i].inThreadSafeCache()) {
527 fThreadSafeCache->remove(invalidKeyMsgs[i].key());
528 SkASSERT(!fThreadSafeCache->has(invalidKeyMsgs[i].key()));
529 } else {
530 fProxyProvider->processInvalidUniqueKey(
531 invalidKeyMsgs[i].key(), nullptr,
Robert Phillips427966a2018-12-20 17:20:43 -0500532 GrProxyProvider::InvalidateGPUResource::kYes);
Robert Phillips83c38a82020-10-28 14:57:53 -0400533 SkASSERT(!this->findAndRefUniqueResource(invalidKeyMsgs[i].key()));
534 }
Robert Phillips427966a2018-12-20 17:20:43 -0500535 }
bsalomon3f324322015-04-08 11:01:54 -0700536 }
bsalomon71cb0c22014-11-14 12:10:14 -0800537
Brian Osman13dddce2017-05-09 13:19:50 -0400538 this->processFreedGpuResources();
539
bsalomon3f324322015-04-08 11:01:54 -0700540 bool stillOverbudget = this->overBudget();
541 while (stillOverbudget && fPurgeableQueue.count()) {
robertphillipsee843b22016-10-04 05:30:20 -0700542 GrGpuResource* resource = fPurgeableQueue.peek();
Brian Salomon614c1a82018-12-19 15:42:06 -0500543 SkASSERT(resource->resourcePriv().isPurgeable());
bsalomon9f2d1572015-02-17 11:47:40 -0800544 resource->cacheAccess().release();
bsalomon3f324322015-04-08 11:01:54 -0700545 stillOverbudget = this->overBudget();
bsalomon9f2d1572015-02-17 11:47:40 -0800546 }
bsalomon71cb0c22014-11-14 12:10:14 -0800547
Robert Phillips12d06a32020-09-16 12:31:34 -0400548 if (stillOverbudget) {
Robert Phillipsd464feb2020-10-08 11:00:02 -0400549 fThreadSafeCache->dropUniqueRefs(this);
Robert Phillips12d06a32020-09-16 12:31:34 -0400550
551 while (stillOverbudget && fPurgeableQueue.count()) {
552 GrGpuResource* resource = fPurgeableQueue.peek();
553 SkASSERT(resource->resourcePriv().isPurgeable());
554 resource->cacheAccess().release();
555 stillOverbudget = this->overBudget();
556 }
557 }
558
bsalomonb436ed62014-11-17 12:15:56 -0800559 this->validate();
bsalomon71cb0c22014-11-14 12:10:14 -0800560}
561
Robert Phillips6eba0632018-03-28 12:25:42 -0400562void GrResourceCache::purgeUnlockedResources(bool scratchResourcesOnly) {
Robert Phillips12d06a32020-09-16 12:31:34 -0400563
Robert Phillips6eba0632018-03-28 12:25:42 -0400564 if (!scratchResourcesOnly) {
Robert Phillipsd464feb2020-10-08 11:00:02 -0400565 fThreadSafeCache->dropUniqueRefs(nullptr);
Robert Phillips331699c2020-09-22 15:20:01 -0400566
Robert Phillips6eba0632018-03-28 12:25:42 -0400567 // We could disable maintaining the heap property here, but it would add a lot of
568 // complexity. Moreover, this is rarely called.
569 while (fPurgeableQueue.count()) {
570 GrGpuResource* resource = fPurgeableQueue.peek();
Brian Salomon614c1a82018-12-19 15:42:06 -0500571 SkASSERT(resource->resourcePriv().isPurgeable());
Robert Phillips6eba0632018-03-28 12:25:42 -0400572 resource->cacheAccess().release();
573 }
574 } else {
575 // Sort the queue
576 fPurgeableQueue.sort();
577
578 // Make a list of the scratch resources to delete
579 SkTDArray<GrGpuResource*> scratchResources;
580 for (int i = 0; i < fPurgeableQueue.count(); i++) {
581 GrGpuResource* resource = fPurgeableQueue.at(i);
Brian Salomon614c1a82018-12-19 15:42:06 -0500582 SkASSERT(resource->resourcePriv().isPurgeable());
Robert Phillips6eba0632018-03-28 12:25:42 -0400583 if (!resource->getUniqueKey().isValid()) {
584 *scratchResources.append() = resource;
585 }
586 }
587
588 // Delete the scratch resources. This must be done as a separate pass
589 // to avoid messing up the sorted order of the queue
590 for (int i = 0; i < scratchResources.count(); i++) {
591 scratchResources.getAt(i)->cacheAccess().release();
592 }
bsalomon9f2d1572015-02-17 11:47:40 -0800593 }
bsalomon71cb0c22014-11-14 12:10:14 -0800594
bsalomonb436ed62014-11-17 12:15:56 -0800595 this->validate();
bsalomon71cb0c22014-11-14 12:10:14 -0800596}
597
Brian Salomon5e150852017-03-22 14:53:13 -0400598void GrResourceCache::purgeResourcesNotUsedSince(GrStdSteadyClock::time_point purgeTime) {
Robert Phillipsd464feb2020-10-08 11:00:02 -0400599 fThreadSafeCache->dropUniqueRefsOlderThan(purgeTime);
Robert Phillipsc2fe1642020-09-22 17:34:51 -0400600
Brian Salomon5e150852017-03-22 14:53:13 -0400601 while (fPurgeableQueue.count()) {
602 const GrStdSteadyClock::time_point resourceTime =
603 fPurgeableQueue.peek()->cacheAccess().timeWhenResourceBecamePurgeable();
604 if (resourceTime >= purgeTime) {
605 // Resources were given both LRU timestamps and tagged with a frame number when
606 // they first became purgeable. The LRU timestamp won't change again until the
607 // resource is made non-purgeable again. So, at this point all the remaining
608 // resources in the timestamp-sorted queue will have a frame number >= to this
609 // one.
610 break;
611 }
612 GrGpuResource* resource = fPurgeableQueue.peek();
Brian Salomon614c1a82018-12-19 15:42:06 -0500613 SkASSERT(resource->resourcePriv().isPurgeable());
Brian Salomon5e150852017-03-22 14:53:13 -0400614 resource->cacheAccess().release();
615 }
616}
617
Derek Sollenberger5480a182017-05-25 16:43:59 -0400618void GrResourceCache::purgeUnlockedResources(size_t bytesToPurge, bool preferScratchResources) {
619
Brian Osman788b9162020-02-07 10:36:46 -0500620 const size_t tmpByteBudget = std::max((size_t)0, fBytes - bytesToPurge);
Derek Sollenberger5480a182017-05-25 16:43:59 -0400621 bool stillOverbudget = tmpByteBudget < fBytes;
622
623 if (preferScratchResources && bytesToPurge < fPurgeableBytes) {
624 // Sort the queue
625 fPurgeableQueue.sort();
626
627 // Make a list of the scratch resources to delete
628 SkTDArray<GrGpuResource*> scratchResources;
629 size_t scratchByteCount = 0;
630 for (int i = 0; i < fPurgeableQueue.count() && stillOverbudget; i++) {
631 GrGpuResource* resource = fPurgeableQueue.at(i);
Brian Salomon614c1a82018-12-19 15:42:06 -0500632 SkASSERT(resource->resourcePriv().isPurgeable());
Derek Sollenberger5480a182017-05-25 16:43:59 -0400633 if (!resource->getUniqueKey().isValid()) {
634 *scratchResources.append() = resource;
635 scratchByteCount += resource->gpuMemorySize();
636 stillOverbudget = tmpByteBudget < fBytes - scratchByteCount;
637 }
638 }
639
640 // Delete the scratch resources. This must be done as a separate pass
641 // to avoid messing up the sorted order of the queue
642 for (int i = 0; i < scratchResources.count(); i++) {
643 scratchResources.getAt(i)->cacheAccess().release();
644 }
645 stillOverbudget = tmpByteBudget < fBytes;
646
647 this->validate();
648 }
649
650 // Purge any remaining resources in LRU order
651 if (stillOverbudget) {
652 const size_t cachedByteCount = fMaxBytes;
653 fMaxBytes = tmpByteBudget;
654 this->purgeAsNeeded();
655 fMaxBytes = cachedByteCount;
656 }
657}
Robert Phillips12d06a32020-09-16 12:31:34 -0400658
Brian Salomon8cefa3e2019-04-04 11:39:55 -0400659bool GrResourceCache::requestsFlush() const {
660 return this->overBudget() && !fPurgeableQueue.count() &&
661 fNumBudgetedResourcesFlushWillMakePurgeable > 0;
662}
663
Robert Phillipsddc21482019-10-16 14:30:09 -0400664void GrResourceCache::insertDelayedTextureUnref(GrTexture* texture) {
665 texture->ref();
666 uint32_t id = texture->uniqueID().asUInt();
667 if (auto* data = fTexturesAwaitingUnref.find(id)) {
Brian Salomon876a0172019-03-08 11:12:14 -0500668 data->addRef();
669 } else {
Robert Phillipsddc21482019-10-16 14:30:09 -0400670 fTexturesAwaitingUnref.set(id, {texture});
Brian Salomon876a0172019-03-08 11:12:14 -0500671 }
Brian Osman13dddce2017-05-09 13:19:50 -0400672}
673
674void GrResourceCache::processFreedGpuResources() {
Robert Phillips1dfc77c2019-10-16 16:39:45 -0400675 if (!fTexturesAwaitingUnref.count()) {
Robert Phillips12d06a32020-09-16 12:31:34 -0400676 return;
Robert Phillips1dfc77c2019-10-16 16:39:45 -0400677 }
678
Robert Phillipsddc21482019-10-16 14:30:09 -0400679 SkTArray<GrTextureFreedMessage> msgs;
680 fFreedTextureInbox.poll(&msgs);
Brian Osman13dddce2017-05-09 13:19:50 -0400681 for (int i = 0; i < msgs.count(); ++i) {
Brian Salomon238069b2018-07-11 15:58:57 -0400682 SkASSERT(msgs[i].fOwningUniqueID == fContextUniqueID);
Robert Phillipsddc21482019-10-16 14:30:09 -0400683 uint32_t id = msgs[i].fTexture->uniqueID().asUInt();
684 TextureAwaitingUnref* info = fTexturesAwaitingUnref.find(id);
Greg Daniel1a5d2d52019-12-04 11:14:29 -0500685 // If the GrContext was released or abandoned then fTexturesAwaitingUnref should have been
686 // empty and we would have returned early above. Thus, any texture from a message should be
687 // in the list of fTexturesAwaitingUnref.
688 SkASSERT(info);
689 info->unref();
690 if (info->finished()) {
691 fTexturesAwaitingUnref.remove(id);
Greg Danielb2acf0a2018-09-12 09:17:11 -0400692 }
Brian Osman13dddce2017-05-09 13:19:50 -0400693 }
694}
695
bsalomonf320e042015-02-17 15:09:34 -0800696void GrResourceCache::addToNonpurgeableArray(GrGpuResource* resource) {
697 int index = fNonpurgeableResources.count();
698 *fNonpurgeableResources.append() = resource;
699 *resource->cacheAccess().accessCacheIndex() = index;
700}
701
702void GrResourceCache::removeFromNonpurgeableArray(GrGpuResource* resource) {
703 int* index = resource->cacheAccess().accessCacheIndex();
Adlai Holler9555f292020-10-09 09:41:14 -0400704 // Fill the hole we will create in the array with the tail object, adjust its index, and
bsalomonf320e042015-02-17 15:09:34 -0800705 // then pop the array
706 GrGpuResource* tail = *(fNonpurgeableResources.end() - 1);
707 SkASSERT(fNonpurgeableResources[*index] == resource);
708 fNonpurgeableResources[*index] = tail;
709 *tail->cacheAccess().accessCacheIndex() = *index;
710 fNonpurgeableResources.pop();
711 SkDEBUGCODE(*index = -1);
712}
713
bsalomonddf30e62015-02-19 11:38:44 -0800714uint32_t GrResourceCache::getNextTimestamp() {
715 // If we wrap then all the existing resources will appear older than any resources that get
716 // a timestamp after the wrap.
717 if (0 == fTimestamp) {
718 int count = this->getResourceCount();
719 if (count) {
720 // Reset all the timestamps. We sort the resources by timestamp and then assign
721 // sequential timestamps beginning with 0. This is O(n*lg(n)) but it should be extremely
722 // rare.
723 SkTDArray<GrGpuResource*> sortedPurgeableResources;
724 sortedPurgeableResources.setReserve(fPurgeableQueue.count());
725
726 while (fPurgeableQueue.count()) {
727 *sortedPurgeableResources.append() = fPurgeableQueue.peek();
728 fPurgeableQueue.pop();
729 }
robertphillipsee843b22016-10-04 05:30:20 -0700730
John Stiles886a9042020-07-14 16:28:33 -0400731 SkTQSort(fNonpurgeableResources.begin(), fNonpurgeableResources.end(),
John Stiles6e9ead92020-07-14 00:13:51 +0000732 CompareTimestamp);
bsalomonddf30e62015-02-19 11:38:44 -0800733
734 // Pick resources out of the purgeable and non-purgeable arrays based on lowest
735 // timestamp and assign new timestamps.
736 int currP = 0;
737 int currNP = 0;
738 while (currP < sortedPurgeableResources.count() &&
mtklein56da0252015-11-16 11:16:23 -0800739 currNP < fNonpurgeableResources.count()) {
bsalomonddf30e62015-02-19 11:38:44 -0800740 uint32_t tsP = sortedPurgeableResources[currP]->cacheAccess().timestamp();
741 uint32_t tsNP = fNonpurgeableResources[currNP]->cacheAccess().timestamp();
742 SkASSERT(tsP != tsNP);
743 if (tsP < tsNP) {
744 sortedPurgeableResources[currP++]->cacheAccess().setTimestamp(fTimestamp++);
745 } else {
746 // Correct the index in the nonpurgeable array stored on the resource post-sort.
747 *fNonpurgeableResources[currNP]->cacheAccess().accessCacheIndex() = currNP;
748 fNonpurgeableResources[currNP++]->cacheAccess().setTimestamp(fTimestamp++);
749 }
750 }
751
752 // The above loop ended when we hit the end of one array. Finish the other one.
753 while (currP < sortedPurgeableResources.count()) {
754 sortedPurgeableResources[currP++]->cacheAccess().setTimestamp(fTimestamp++);
755 }
756 while (currNP < fNonpurgeableResources.count()) {
757 *fNonpurgeableResources[currNP]->cacheAccess().accessCacheIndex() = currNP;
758 fNonpurgeableResources[currNP++]->cacheAccess().setTimestamp(fTimestamp++);
759 }
760
761 // Rebuild the queue.
762 for (int i = 0; i < sortedPurgeableResources.count(); ++i) {
763 fPurgeableQueue.insert(sortedPurgeableResources[i]);
764 }
765
766 this->validate();
767 SkASSERT(count == this->getResourceCount());
768
769 // count should be the next timestamp we return.
770 SkASSERT(fTimestamp == SkToU32(count));
mtklein56da0252015-11-16 11:16:23 -0800771 }
bsalomonddf30e62015-02-19 11:38:44 -0800772 }
773 return fTimestamp++;
774}
775
ericrk0a5fa482015-09-15 14:16:10 -0700776void GrResourceCache::dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const {
777 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
778 fNonpurgeableResources[i]->dumpMemoryStatistics(traceMemoryDump);
779 }
780 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
781 fPurgeableQueue.at(i)->dumpMemoryStatistics(traceMemoryDump);
782 }
783}
784
Robert Phillipsdbaf3172019-02-06 15:12:53 -0500785#if GR_CACHE_STATS
786void GrResourceCache::getStats(Stats* stats) const {
787 stats->reset();
788
789 stats->fTotal = this->getResourceCount();
790 stats->fNumNonPurgeable = fNonpurgeableResources.count();
791 stats->fNumPurgeable = fPurgeableQueue.count();
792
793 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
794 stats->update(fNonpurgeableResources[i]);
795 }
796 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
797 stats->update(fPurgeableQueue.at(i));
798 }
799}
800
801#if GR_TEST_UTILS
802void GrResourceCache::dumpStats(SkString* out) const {
803 this->validate();
804
805 Stats stats;
806
807 this->getStats(&stats);
808
Robert Phillipsdbaf3172019-02-06 15:12:53 -0500809 float byteUtilization = (100.f * fBudgetedBytes) / fMaxBytes;
810
Robert Phillipscf39f372019-09-03 10:29:20 -0400811 out->appendf("Budget: %d bytes\n", (int)fMaxBytes);
Robert Phillipsdbaf3172019-02-06 15:12:53 -0500812 out->appendf("\t\tEntry Count: current %d"
Robert Phillipscf39f372019-09-03 10:29:20 -0400813 " (%d budgeted, %d wrapped, %d locked, %d scratch), high %d\n",
Robert Phillipsdbaf3172019-02-06 15:12:53 -0500814 stats.fTotal, fBudgetedCount, stats.fWrapped, stats.fNumNonPurgeable,
Robert Phillipscf39f372019-09-03 10:29:20 -0400815 stats.fScratch, fHighWaterCount);
Robert Phillipsdbaf3172019-02-06 15:12:53 -0500816 out->appendf("\t\tEntry Bytes: current %d (budgeted %d, %.2g%% full, %d unbudgeted) high %d\n",
817 SkToInt(fBytes), SkToInt(fBudgetedBytes), byteUtilization,
818 SkToInt(stats.fUnbudgetedSize), SkToInt(fHighWaterBytes));
819}
820
821void GrResourceCache::dumpStatsKeyValuePairs(SkTArray<SkString>* keys,
822 SkTArray<double>* values) const {
823 this->validate();
824
825 Stats stats;
826 this->getStats(&stats);
827
828 keys->push_back(SkString("gpu_cache_purgable_entries")); values->push_back(stats.fNumPurgeable);
829}
830#endif
831
832#endif
833
bsalomon71cb0c22014-11-14 12:10:14 -0800834#ifdef SK_DEBUG
bsalomon0ea80f42015-02-11 10:49:59 -0800835void GrResourceCache::validate() const {
bsalomonc2f35b72015-01-23 07:19:22 -0800836 // Reduce the frequency of validations for large resource counts.
837 static SkRandom gRandom;
838 int mask = (SkNextPow2(fCount + 1) >> 5) - 1;
839 if (~mask && (gRandom.nextU() & mask)) {
840 return;
841 }
842
bsalomonf320e042015-02-17 15:09:34 -0800843 struct Stats {
844 size_t fBytes;
845 int fBudgetedCount;
846 size_t fBudgetedBytes;
847 int fLocked;
848 int fScratch;
849 int fCouldBeScratch;
850 int fContent;
851 const ScratchMap* fScratchMap;
bsalomon8718aaf2015-02-19 07:24:21 -0800852 const UniqueHash* fUniqueHash;
bsalomon71cb0c22014-11-14 12:10:14 -0800853
bsalomonf320e042015-02-17 15:09:34 -0800854 Stats(const GrResourceCache* cache) {
855 memset(this, 0, sizeof(*this));
856 fScratchMap = &cache->fScratchMap;
bsalomon8718aaf2015-02-19 07:24:21 -0800857 fUniqueHash = &cache->fUniqueHash;
bsalomon71cb0c22014-11-14 12:10:14 -0800858 }
859
bsalomonf320e042015-02-17 15:09:34 -0800860 void update(GrGpuResource* resource) {
861 fBytes += resource->gpuMemorySize();
bsalomondace19e2014-11-17 07:34:06 -0800862
Brian Salomon614c1a82018-12-19 15:42:06 -0500863 if (!resource->resourcePriv().isPurgeable()) {
bsalomonf320e042015-02-17 15:09:34 -0800864 ++fLocked;
865 }
bsalomon9f2d1572015-02-17 11:47:40 -0800866
robertphillipsc4ed6842016-05-24 14:17:12 -0700867 const GrScratchKey& scratchKey = resource->resourcePriv().getScratchKey();
868 const GrUniqueKey& uniqueKey = resource->getUniqueKey();
869
Greg Danielda642612021-02-09 18:04:02 -0500870 if (resource->cacheAccess().isUsableAsScratch()) {
robertphillipsc4ed6842016-05-24 14:17:12 -0700871 SkASSERT(!uniqueKey.isValid());
Greg Danielda642612021-02-09 18:04:02 -0500872 SkASSERT(GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType());
873 SkASSERT(!resource->cacheAccess().hasRef());
bsalomonf320e042015-02-17 15:09:34 -0800874 ++fScratch;
robertphillipsc4ed6842016-05-24 14:17:12 -0700875 SkASSERT(fScratchMap->countForKey(scratchKey));
kkinnunen2e6055b2016-04-22 01:48:29 -0700876 SkASSERT(!resource->resourcePriv().refsWrappedObjects());
robertphillipsc4ed6842016-05-24 14:17:12 -0700877 } else if (scratchKey.isValid()) {
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500878 SkASSERT(GrBudgetedType::kBudgeted != resource->resourcePriv().budgetedType() ||
Greg Danielda642612021-02-09 18:04:02 -0500879 uniqueKey.isValid() || resource->cacheAccess().hasRef());
kkinnunen2e6055b2016-04-22 01:48:29 -0700880 SkASSERT(!resource->resourcePriv().refsWrappedObjects());
Greg Danielda642612021-02-09 18:04:02 -0500881 SkASSERT(!fScratchMap->has(resource, scratchKey));
bsalomonf320e042015-02-17 15:09:34 -0800882 }
bsalomon8718aaf2015-02-19 07:24:21 -0800883 if (uniqueKey.isValid()) {
bsalomonf320e042015-02-17 15:09:34 -0800884 ++fContent;
bsalomon8718aaf2015-02-19 07:24:21 -0800885 SkASSERT(fUniqueHash->find(uniqueKey) == resource);
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500886 SkASSERT(GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType() ||
Brian Osman0562eb92017-05-08 11:16:39 -0400887 resource->resourcePriv().refsWrappedObjects());
bsalomonf320e042015-02-17 15:09:34 -0800888 }
889
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500890 if (GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType()) {
bsalomonf320e042015-02-17 15:09:34 -0800891 ++fBudgetedCount;
892 fBudgetedBytes += resource->gpuMemorySize();
893 }
bsalomon9f2d1572015-02-17 11:47:40 -0800894 }
bsalomonf320e042015-02-17 15:09:34 -0800895 };
896
robertphillipsc4ed6842016-05-24 14:17:12 -0700897 {
robertphillipsc4ed6842016-05-24 14:17:12 -0700898 int count = 0;
Mike Kleincff63962020-03-14 16:22:45 -0500899 fScratchMap.foreach([&](const GrGpuResource& resource) {
Greg Danielda642612021-02-09 18:04:02 -0500900 SkASSERT(resource.cacheAccess().isUsableAsScratch());
robertphillipsc4ed6842016-05-24 14:17:12 -0700901 count++;
Mike Kleincff63962020-03-14 16:22:45 -0500902 });
903 SkASSERT(count == fScratchMap.count());
robertphillipsc4ed6842016-05-24 14:17:12 -0700904 }
905
bsalomonf320e042015-02-17 15:09:34 -0800906 Stats stats(this);
Derek Sollenbergeree479142017-05-24 11:41:33 -0400907 size_t purgeableBytes = 0;
Brian Salomon2c791fc2019-04-02 11:52:03 -0400908 int numBudgetedResourcesFlushWillMakePurgeable = 0;
bsalomonf320e042015-02-17 15:09:34 -0800909
910 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
Brian Salomon614c1a82018-12-19 15:42:06 -0500911 SkASSERT(!fNonpurgeableResources[i]->resourcePriv().isPurgeable() ||
bsalomon3f324322015-04-08 11:01:54 -0700912 fNewlyPurgeableResourceForValidation == fNonpurgeableResources[i]);
bsalomonf320e042015-02-17 15:09:34 -0800913 SkASSERT(*fNonpurgeableResources[i]->cacheAccess().accessCacheIndex() == i);
914 SkASSERT(!fNonpurgeableResources[i]->wasDestroyed());
Brian Salomon2c791fc2019-04-02 11:52:03 -0400915 if (fNonpurgeableResources[i]->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted &&
Greg Daniel1fd8ac82020-12-11 11:22:01 -0500916 !fNonpurgeableResources[i]->cacheAccess().hasRefOrCommandBufferUsage() &&
Brian Salomon2c791fc2019-04-02 11:52:03 -0400917 fNewlyPurgeableResourceForValidation != fNonpurgeableResources[i]) {
Brian Salomon2c791fc2019-04-02 11:52:03 -0400918 ++numBudgetedResourcesFlushWillMakePurgeable;
919 }
bsalomonf320e042015-02-17 15:09:34 -0800920 stats.update(fNonpurgeableResources[i]);
bsalomon71cb0c22014-11-14 12:10:14 -0800921 }
bsalomon9f2d1572015-02-17 11:47:40 -0800922 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
Brian Salomon614c1a82018-12-19 15:42:06 -0500923 SkASSERT(fPurgeableQueue.at(i)->resourcePriv().isPurgeable());
bsalomonf320e042015-02-17 15:09:34 -0800924 SkASSERT(*fPurgeableQueue.at(i)->cacheAccess().accessCacheIndex() == i);
925 SkASSERT(!fPurgeableQueue.at(i)->wasDestroyed());
926 stats.update(fPurgeableQueue.at(i));
Derek Sollenbergeree479142017-05-24 11:41:33 -0400927 purgeableBytes += fPurgeableQueue.at(i)->gpuMemorySize();
bsalomon9f2d1572015-02-17 11:47:40 -0800928 }
929
bsalomonf320e042015-02-17 15:09:34 -0800930 SkASSERT(fCount == this->getResourceCount());
bsalomondace19e2014-11-17 07:34:06 -0800931 SkASSERT(fBudgetedCount <= fCount);
bsalomonf320e042015-02-17 15:09:34 -0800932 SkASSERT(fBudgetedBytes <= fBytes);
933 SkASSERT(stats.fBytes == fBytes);
Brian Salomon2c791fc2019-04-02 11:52:03 -0400934 SkASSERT(fNumBudgetedResourcesFlushWillMakePurgeable ==
935 numBudgetedResourcesFlushWillMakePurgeable);
bsalomonf320e042015-02-17 15:09:34 -0800936 SkASSERT(stats.fBudgetedBytes == fBudgetedBytes);
937 SkASSERT(stats.fBudgetedCount == fBudgetedCount);
Derek Sollenbergeree479142017-05-24 11:41:33 -0400938 SkASSERT(purgeableBytes == fPurgeableBytes);
bsalomon71cb0c22014-11-14 12:10:14 -0800939#if GR_CACHE_STATS
bsalomondace19e2014-11-17 07:34:06 -0800940 SkASSERT(fBudgetedHighWaterCount <= fHighWaterCount);
941 SkASSERT(fBudgetedHighWaterBytes <= fHighWaterBytes);
bsalomonf320e042015-02-17 15:09:34 -0800942 SkASSERT(fBytes <= fHighWaterBytes);
943 SkASSERT(fCount <= fHighWaterCount);
944 SkASSERT(fBudgetedBytes <= fBudgetedHighWaterBytes);
945 SkASSERT(fBudgetedCount <= fBudgetedHighWaterCount);
bsalomon71cb0c22014-11-14 12:10:14 -0800946#endif
bsalomon8718aaf2015-02-19 07:24:21 -0800947 SkASSERT(stats.fContent == fUniqueHash.count());
Greg Danielda642612021-02-09 18:04:02 -0500948 SkASSERT(stats.fScratch == fScratchMap.count());
bsalomon71cb0c22014-11-14 12:10:14 -0800949
bsalomon3f324322015-04-08 11:01:54 -0700950 // This assertion is not currently valid because we can be in recursive notifyCntReachedZero()
bsalomon12299ab2014-11-14 13:33:09 -0800951 // calls. This will be fixed when subresource registration is explicit.
bsalomondace19e2014-11-17 07:34:06 -0800952 // bool overBudget = budgetedBytes > fMaxBytes || budgetedCount > fMaxCount;
bsalomon12299ab2014-11-14 13:33:09 -0800953 // SkASSERT(!overBudget || locked == count || fPurging);
bsalomon71cb0c22014-11-14 12:10:14 -0800954}
bsalomonf320e042015-02-17 15:09:34 -0800955
956bool GrResourceCache::isInCache(const GrGpuResource* resource) const {
957 int index = *resource->cacheAccess().accessCacheIndex();
958 if (index < 0) {
959 return false;
960 }
961 if (index < fPurgeableQueue.count() && fPurgeableQueue.at(index) == resource) {
962 return true;
963 }
964 if (index < fNonpurgeableResources.count() && fNonpurgeableResources[index] == resource) {
965 return true;
966 }
967 SkDEBUGFAIL("Resource index should be -1 or the resource should be in the cache.");
968 return false;
969}
970
bsalomon71cb0c22014-11-14 12:10:14 -0800971#endif