blob: afb2b38028db13c17e1c380b6b79d905931f3017 [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>
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "include/gpu/GrContext.h"
11#include "include/gpu/GrTexture.h"
12#include "include/private/GrSingleOwner.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "include/private/SkTo.h"
14#include "include/utils/SkRandom.h"
15#include "src/core/SkExchange.h"
Ben Wagner21bca282019-05-15 10:15:52 -040016#include "src/core/SkMessageBus.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050017#include "src/core/SkOpts.h"
18#include "src/core/SkScopeExit.h"
19#include "src/core/SkTSort.h"
20#include "src/gpu/GrCaps.h"
21#include "src/gpu/GrContextPriv.h"
22#include "src/gpu/GrGpuResourceCacheAccess.h"
23#include "src/gpu/GrProxyProvider.h"
24#include "src/gpu/GrTextureProxyCacheAccess.h"
25#include "src/gpu/GrTracing.h"
26#include "src/gpu/SkGr.h"
bsalomon71cb0c22014-11-14 12:10:14 -080027
bsalomon8718aaf2015-02-19 07:24:21 -080028DECLARE_SKMESSAGEBUS_MESSAGE(GrUniqueKeyInvalidatedMessage);
bsalomon71cb0c22014-11-14 12:10:14 -080029
Brian Osman13dddce2017-05-09 13:19:50 -040030DECLARE_SKMESSAGEBUS_MESSAGE(GrGpuResourceFreedMessage);
31
Brian Salomon8f8995a2018-10-15 14:32:15 -040032#define ASSERT_SINGLE_OWNER \
33 SkDEBUGCODE(GrSingleOwner::AutoEnforce debug_SingleOwner(fSingleOwner);)
34
bsalomon71cb0c22014-11-14 12:10:14 -080035//////////////////////////////////////////////////////////////////////////////
36
bsalomon7775c852014-12-30 12:50:52 -080037GrScratchKey::ResourceType GrScratchKey::GenerateResourceType() {
Mike Klein0ec1c572018-12-04 11:52:51 -050038 static std::atomic<int32_t> nextType{INHERITED::kInvalidDomain + 1};
bsalomonfe369ee2014-11-10 11:59:06 -080039
Mike Klein0ec1c572018-12-04 11:52:51 -050040 int32_t type = nextType++;
Ben Wagner9bc36fd2018-06-15 14:23:36 -040041 if (type > SkTo<int32_t>(UINT16_MAX)) {
Ben Wagnerb4aab9a2017-08-16 10:53:04 -040042 SK_ABORT("Too many Resource Types");
bsalomon71cb0c22014-11-14 12:10:14 -080043 }
44
45 return static_cast<ResourceType>(type);
46}
47
bsalomon8718aaf2015-02-19 07:24:21 -080048GrUniqueKey::Domain GrUniqueKey::GenerateDomain() {
Mike Klein0ec1c572018-12-04 11:52:51 -050049 static std::atomic<int32_t> nextDomain{INHERITED::kInvalidDomain + 1};
bsalomon7775c852014-12-30 12:50:52 -080050
Mike Klein0ec1c572018-12-04 11:52:51 -050051 int32_t domain = nextDomain++;
Ben Wagner397ee0e2018-06-15 15:13:26 -040052 if (domain > SkTo<int32_t>(UINT16_MAX)) {
Ben Wagnerb4aab9a2017-08-16 10:53:04 -040053 SK_ABORT("Too many GrUniqueKey Domains");
bsalomon7775c852014-12-30 12:50:52 -080054 }
bsalomon24db3b12015-01-23 04:24:04 -080055
56 return static_cast<Domain>(domain);
57}
bsalomon3f324322015-04-08 11:01:54 -070058
bsalomon24db3b12015-01-23 04:24:04 -080059uint32_t GrResourceKeyHash(const uint32_t* data, size_t size) {
mtklein4e976072016-08-08 09:06:27 -070060 return SkOpts::hash(data, size);
bsalomon7775c852014-12-30 12:50:52 -080061}
62
bsalomonfe369ee2014-11-10 11:59:06 -080063//////////////////////////////////////////////////////////////////////////////
64
bsalomon0ea80f42015-02-11 10:49:59 -080065class GrResourceCache::AutoValidate : ::SkNoncopyable {
bsalomon71cb0c22014-11-14 12:10:14 -080066public:
bsalomon0ea80f42015-02-11 10:49:59 -080067 AutoValidate(GrResourceCache* cache) : fCache(cache) { cache->validate(); }
bsalomon71cb0c22014-11-14 12:10:14 -080068 ~AutoValidate() { fCache->validate(); }
69private:
bsalomon0ea80f42015-02-11 10:49:59 -080070 GrResourceCache* fCache;
bsalomon71cb0c22014-11-14 12:10:14 -080071};
72
Brian Salomon876a0172019-03-08 11:12:14 -050073//////////////////////////////////////////////////////////////////////////////
74
75inline GrResourceCache::ResourceAwaitingUnref::ResourceAwaitingUnref() = default;
76
77inline GrResourceCache::ResourceAwaitingUnref::ResourceAwaitingUnref(GrGpuResource* resource)
78 : fResource(resource), fNumUnrefs(1) {}
79
80inline GrResourceCache::ResourceAwaitingUnref::ResourceAwaitingUnref(ResourceAwaitingUnref&& that) {
81 fResource = skstd::exchange(that.fResource, nullptr);
82 fNumUnrefs = skstd::exchange(that.fNumUnrefs, 0);
83}
84
85inline GrResourceCache::ResourceAwaitingUnref& GrResourceCache::ResourceAwaitingUnref::operator=(
86 ResourceAwaitingUnref&& that) {
87 fResource = skstd::exchange(that.fResource, nullptr);
88 fNumUnrefs = skstd::exchange(that.fNumUnrefs, 0);
89 return *this;
90}
91
92inline GrResourceCache::ResourceAwaitingUnref::~ResourceAwaitingUnref() {
93 if (fResource) {
94 for (int i = 0; i < fNumUnrefs; ++i) {
95 fResource->unref();
96 }
97 }
98}
99
100inline void GrResourceCache::ResourceAwaitingUnref::addRef() { ++fNumUnrefs; }
101
102inline void GrResourceCache::ResourceAwaitingUnref::unref() {
103 SkASSERT(fNumUnrefs > 0);
104 fResource->unref();
105 --fNumUnrefs;
106}
107
108inline bool GrResourceCache::ResourceAwaitingUnref::finished() { return !fNumUnrefs; }
109
110//////////////////////////////////////////////////////////////////////////////
robertphillipsee843b22016-10-04 05:30:20 -0700111
Brian Salomon8f8995a2018-10-15 14:32:15 -0400112GrResourceCache::GrResourceCache(const GrCaps* caps, GrSingleOwner* singleOwner,
113 uint32_t contextUniqueID)
Brian Salomon2c791fc2019-04-02 11:52:03 -0400114 : fInvalidUniqueKeyInbox(contextUniqueID)
Brian Salomon238069b2018-07-11 15:58:57 -0400115 , fFreedGpuResourceInbox(contextUniqueID)
116 , fContextUniqueID(contextUniqueID)
Brian Salomon8f8995a2018-10-15 14:32:15 -0400117 , fSingleOwner(singleOwner)
Brian Salomon238069b2018-07-11 15:58:57 -0400118 , fPreferVRAMUseOverFlushes(caps->preferVRAMUseOverFlushes()) {
119 SkASSERT(contextUniqueID != SK_InvalidUniqueID);
bsalomon71cb0c22014-11-14 12:10:14 -0800120}
121
bsalomon0ea80f42015-02-11 10:49:59 -0800122GrResourceCache::~GrResourceCache() {
bsalomonc8dc1f72014-08-21 13:02:13 -0700123 this->releaseAll();
124}
125
Robert Phillipscf39f372019-09-03 10:29:20 -0400126void GrResourceCache::setLimit(size_t bytes) {
bsalomon71cb0c22014-11-14 12:10:14 -0800127 fMaxBytes = bytes;
128 this->purgeAsNeeded();
129}
130
bsalomon0ea80f42015-02-11 10:49:59 -0800131void GrResourceCache::insertResource(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400132 ASSERT_SINGLE_OWNER
bsalomon49f085d2014-09-05 13:34:00 -0700133 SkASSERT(resource);
bsalomon16961262014-08-26 14:01:07 -0700134 SkASSERT(!this->isInCache(resource));
bsalomonf320e042015-02-17 15:09:34 -0800135 SkASSERT(!resource->wasDestroyed());
Brian Salomon614c1a82018-12-19 15:42:06 -0500136 SkASSERT(!resource->resourcePriv().isPurgeable());
bsalomonddf30e62015-02-19 11:38:44 -0800137
138 // We must set the timestamp before adding to the array in case the timestamp wraps and we wind
139 // up iterating over all the resources that already have timestamps.
140 resource->cacheAccess().setTimestamp(this->getNextTimestamp());
141
bsalomonf320e042015-02-17 15:09:34 -0800142 this->addToNonpurgeableArray(resource);
bsalomon71cb0c22014-11-14 12:10:14 -0800143
bsalomondace19e2014-11-17 07:34:06 -0800144 size_t size = resource->gpuMemorySize();
bsalomonf320e042015-02-17 15:09:34 -0800145 SkDEBUGCODE(++fCount;)
bsalomon84c8e622014-11-17 09:33:27 -0800146 fBytes += size;
bsalomon82b1d622014-11-14 13:59:57 -0800147#if GR_CACHE_STATS
bsalomonf320e042015-02-17 15:09:34 -0800148 fHighWaterCount = SkTMax(this->getResourceCount(), fHighWaterCount);
bsalomon82b1d622014-11-14 13:59:57 -0800149 fHighWaterBytes = SkTMax(fBytes, fHighWaterBytes);
150#endif
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500151 if (GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType()) {
bsalomondace19e2014-11-17 07:34:06 -0800152 ++fBudgetedCount;
153 fBudgetedBytes += size;
Brian Osman39c08ac2017-07-26 09:36:09 -0400154 TRACE_COUNTER2("skia.gpu.cache", "skia budget", "used",
hendrikw876c3132015-03-04 10:33:49 -0800155 fBudgetedBytes, "free", fMaxBytes - fBudgetedBytes);
bsalomondace19e2014-11-17 07:34:06 -0800156#if GR_CACHE_STATS
157 fBudgetedHighWaterCount = SkTMax(fBudgetedCount, fBudgetedHighWaterCount);
158 fBudgetedHighWaterBytes = SkTMax(fBudgetedBytes, fBudgetedHighWaterBytes);
159#endif
160 }
robertphillipsc4ed6842016-05-24 14:17:12 -0700161 if (resource->resourcePriv().getScratchKey().isValid() &&
162 !resource->getUniqueKey().isValid()) {
kkinnunen2e6055b2016-04-22 01:48:29 -0700163 SkASSERT(!resource->resourcePriv().refsWrappedObjects());
bsalomon3582d3e2015-02-13 14:20:05 -0800164 fScratchMap.insert(resource->resourcePriv().getScratchKey(), resource);
bsalomon744998e2014-08-28 09:54:34 -0700165 }
bsalomon9f2d1572015-02-17 11:47:40 -0800166
bsalomon71cb0c22014-11-14 12:10:14 -0800167 this->purgeAsNeeded();
bsalomonc8dc1f72014-08-21 13:02:13 -0700168}
169
bsalomon0ea80f42015-02-11 10:49:59 -0800170void GrResourceCache::removeResource(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400171 ASSERT_SINGLE_OWNER
bsalomon9f2d1572015-02-17 11:47:40 -0800172 this->validate();
bsalomon16961262014-08-26 14:01:07 -0700173 SkASSERT(this->isInCache(resource));
bsalomondace19e2014-11-17 07:34:06 -0800174
Derek Sollenbergeree479142017-05-24 11:41:33 -0400175 size_t size = resource->gpuMemorySize();
Brian Salomon614c1a82018-12-19 15:42:06 -0500176 if (resource->resourcePriv().isPurgeable()) {
bsalomon9f2d1572015-02-17 11:47:40 -0800177 fPurgeableQueue.remove(resource);
Derek Sollenbergeree479142017-05-24 11:41:33 -0400178 fPurgeableBytes -= size;
bsalomonf320e042015-02-17 15:09:34 -0800179 } else {
180 this->removeFromNonpurgeableArray(resource);
bsalomon9f2d1572015-02-17 11:47:40 -0800181 }
182
bsalomonf320e042015-02-17 15:09:34 -0800183 SkDEBUGCODE(--fCount;)
bsalomondace19e2014-11-17 07:34:06 -0800184 fBytes -= size;
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500185 if (GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType()) {
bsalomondace19e2014-11-17 07:34:06 -0800186 --fBudgetedCount;
187 fBudgetedBytes -= size;
Brian Osman39c08ac2017-07-26 09:36:09 -0400188 TRACE_COUNTER2("skia.gpu.cache", "skia budget", "used",
hendrikw876c3132015-03-04 10:33:49 -0800189 fBudgetedBytes, "free", fMaxBytes - fBudgetedBytes);
bsalomondace19e2014-11-17 07:34:06 -0800190 }
191
robertphillipsc4ed6842016-05-24 14:17:12 -0700192 if (resource->resourcePriv().getScratchKey().isValid() &&
193 !resource->getUniqueKey().isValid()) {
bsalomon3582d3e2015-02-13 14:20:05 -0800194 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
bsalomon744998e2014-08-28 09:54:34 -0700195 }
bsalomon8718aaf2015-02-19 07:24:21 -0800196 if (resource->getUniqueKey().isValid()) {
197 fUniqueHash.remove(resource->getUniqueKey());
bsalomon8b79d232014-11-10 10:19:06 -0800198 }
bsalomonb436ed62014-11-17 12:15:56 -0800199 this->validate();
bsalomonc8dc1f72014-08-21 13:02:13 -0700200}
201
bsalomon0ea80f42015-02-11 10:49:59 -0800202void GrResourceCache::abandonAll() {
bsalomon71cb0c22014-11-14 12:10:14 -0800203 AutoValidate av(this);
204
Brian Salomon876a0172019-03-08 11:12:14 -0500205 // We need to make sure to free any resources that were waiting on a free message but never
206 // received one.
207 fResourcesAwaitingUnref.reset();
Greg Danielb2acf0a2018-09-12 09:17:11 -0400208
bsalomonf320e042015-02-17 15:09:34 -0800209 while (fNonpurgeableResources.count()) {
210 GrGpuResource* back = *(fNonpurgeableResources.end() - 1);
211 SkASSERT(!back->wasDestroyed());
212 back->cacheAccess().abandon();
bsalomonc8dc1f72014-08-21 13:02:13 -0700213 }
bsalomonf320e042015-02-17 15:09:34 -0800214
215 while (fPurgeableQueue.count()) {
216 GrGpuResource* top = fPurgeableQueue.peek();
217 SkASSERT(!top->wasDestroyed());
218 top->cacheAccess().abandon();
219 }
220
bsalomon744998e2014-08-28 09:54:34 -0700221 SkASSERT(!fScratchMap.count());
bsalomon8718aaf2015-02-19 07:24:21 -0800222 SkASSERT(!fUniqueHash.count());
bsalomonc8dc1f72014-08-21 13:02:13 -0700223 SkASSERT(!fCount);
bsalomonf320e042015-02-17 15:09:34 -0800224 SkASSERT(!this->getResourceCount());
bsalomondace19e2014-11-17 07:34:06 -0800225 SkASSERT(!fBytes);
226 SkASSERT(!fBudgetedCount);
227 SkASSERT(!fBudgetedBytes);
Derek Sollenbergeree479142017-05-24 11:41:33 -0400228 SkASSERT(!fPurgeableBytes);
Brian Salomon876a0172019-03-08 11:12:14 -0500229 SkASSERT(!fResourcesAwaitingUnref.count());
bsalomonc8dc1f72014-08-21 13:02:13 -0700230}
231
bsalomon0ea80f42015-02-11 10:49:59 -0800232void GrResourceCache::releaseAll() {
bsalomon71cb0c22014-11-14 12:10:14 -0800233 AutoValidate av(this);
234
Brian Osman13dddce2017-05-09 13:19:50 -0400235 this->processFreedGpuResources();
236
Greg Danielc27eb722018-08-10 09:48:08 -0400237 // We need to make sure to free any resources that were waiting on a free message but never
238 // received one.
Brian Salomon876a0172019-03-08 11:12:14 -0500239 fResourcesAwaitingUnref.reset();
Greg Danielc27eb722018-08-10 09:48:08 -0400240
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500241 SkASSERT(fProxyProvider); // better have called setProxyProvider
Robert Phillips3ec95732017-09-29 15:10:39 -0400242 // We must remove the uniqueKeys from the proxies here. While they possess a uniqueKey
243 // they also have a raw pointer back to this class (which is presumably going away)!
Robert Phillips1afd4cd2018-01-08 13:40:32 -0500244 fProxyProvider->removeAllUniqueKeys();
Robert Phillips45a6f142017-09-29 09:49:41 -0400245
Brian Salomon614c1a82018-12-19 15:42:06 -0500246 while (fNonpurgeableResources.count()) {
bsalomonf320e042015-02-17 15:09:34 -0800247 GrGpuResource* back = *(fNonpurgeableResources.end() - 1);
248 SkASSERT(!back->wasDestroyed());
249 back->cacheAccess().release();
bsalomonc8dc1f72014-08-21 13:02:13 -0700250 }
bsalomonf320e042015-02-17 15:09:34 -0800251
252 while (fPurgeableQueue.count()) {
253 GrGpuResource* top = fPurgeableQueue.peek();
254 SkASSERT(!top->wasDestroyed());
255 top->cacheAccess().release();
256 }
257
bsalomon744998e2014-08-28 09:54:34 -0700258 SkASSERT(!fScratchMap.count());
bsalomon8718aaf2015-02-19 07:24:21 -0800259 SkASSERT(!fUniqueHash.count());
bsalomonc8dc1f72014-08-21 13:02:13 -0700260 SkASSERT(!fCount);
bsalomonf320e042015-02-17 15:09:34 -0800261 SkASSERT(!this->getResourceCount());
bsalomondace19e2014-11-17 07:34:06 -0800262 SkASSERT(!fBytes);
263 SkASSERT(!fBudgetedCount);
264 SkASSERT(!fBudgetedBytes);
Derek Sollenbergeree479142017-05-24 11:41:33 -0400265 SkASSERT(!fPurgeableBytes);
Brian Salomon876a0172019-03-08 11:12:14 -0500266 SkASSERT(!fResourcesAwaitingUnref.count());
bsalomonc8dc1f72014-08-21 13:02:13 -0700267}
bsalomonbcf0a522014-10-08 08:40:09 -0700268
Brian Salomon2c791fc2019-04-02 11:52:03 -0400269void GrResourceCache::refResource(GrGpuResource* resource) {
270 SkASSERT(resource);
271 SkASSERT(resource->getContext()->priv().getResourceCache() == this);
272 if (resource->cacheAccess().hasRef()) {
273 resource->ref();
274 } else {
275 this->refAndMakeResourceMRU(resource);
276 }
277 this->validate();
278}
279
bsalomon0ea80f42015-02-11 10:49:59 -0800280class GrResourceCache::AvailableForScratchUse {
bsalomonbcf0a522014-10-08 08:40:09 -0700281public:
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400282 AvailableForScratchUse() { }
bsalomonbcf0a522014-10-08 08:40:09 -0700283
284 bool operator()(const GrGpuResource* resource) const {
robertphillipsc4ed6842016-05-24 14:17:12 -0700285 SkASSERT(!resource->getUniqueKey().isValid() &&
286 resource->resourcePriv().getScratchKey().isValid());
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400287
288 // isScratch() also tests that the resource is budgeted. TODO: why are unbudgeted
289 // scratch resouces in the scratchMap?
bsalomon12299ab2014-11-14 13:33:09 -0800290 if (resource->internalHasRef() || !resource->cacheAccess().isScratch()) {
bsalomon000f8292014-10-15 19:04:14 -0700291 return false;
bsalomonbcf0a522014-10-08 08:40:09 -0700292 }
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400293 return true;
bsalomonbcf0a522014-10-08 08:40:09 -0700294 }
bsalomonbcf0a522014-10-08 08:40:09 -0700295};
296
bsalomon0ea80f42015-02-11 10:49:59 -0800297GrGpuResource* GrResourceCache::findAndRefScratchResource(const GrScratchKey& scratchKey,
robertphillips6e83ac72015-08-13 05:19:14 -0700298 size_t resourceSize,
Chris Daltond004e0b2018-09-27 09:28:03 -0600299 ScratchFlags flags) {
bsalomon7775c852014-12-30 12:50:52 -0800300 SkASSERT(scratchKey.isValid());
robertphillipsee843b22016-10-04 05:30:20 -0700301
bsalomon71cb0c22014-11-14 12:10:14 -0800302 GrGpuResource* resource;
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400303 // TODO: remove these conditions and fuse the two code paths!
Chris Daltond004e0b2018-09-27 09:28:03 -0600304 if (flags & (ScratchFlags::kPreferNoPendingIO | ScratchFlags::kRequireNoPendingIO)) {
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400305 resource = fScratchMap.find(scratchKey, AvailableForScratchUse());
bsalomon000f8292014-10-15 19:04:14 -0700306 if (resource) {
bsalomon9f2d1572015-02-17 11:47:40 -0800307 this->refAndMakeResourceMRU(resource);
bsalomonb436ed62014-11-17 12:15:56 -0800308 this->validate();
309 return resource;
Chris Daltond004e0b2018-09-27 09:28:03 -0600310 } else if (flags & ScratchFlags::kRequireNoPendingIO) {
halcanary96fcdcc2015-08-27 07:41:13 -0700311 return nullptr;
bsalomon000f8292014-10-15 19:04:14 -0700312 }
robertphillips63926682015-08-20 09:39:02 -0700313 // We would prefer to consume more available VRAM rather than flushing
314 // immediately, but on ANGLE this can lead to starving of the GPU.
315 if (fPreferVRAMUseOverFlushes && this->wouldFit(resourceSize)) {
robertphillips6e83ac72015-08-13 05:19:14 -0700316 // kPrefer is specified, we didn't find a resource without pending io,
robertphillips63926682015-08-20 09:39:02 -0700317 // but there is still space in our budget for the resource so force
318 // the caller to allocate a new resource.
halcanary96fcdcc2015-08-27 07:41:13 -0700319 return nullptr;
robertphillips6e83ac72015-08-13 05:19:14 -0700320 }
bsalomon000f8292014-10-15 19:04:14 -0700321 }
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400322 resource = fScratchMap.find(scratchKey, AvailableForScratchUse());
bsalomon71cb0c22014-11-14 12:10:14 -0800323 if (resource) {
bsalomon9f2d1572015-02-17 11:47:40 -0800324 this->refAndMakeResourceMRU(resource);
bsalomonb436ed62014-11-17 12:15:56 -0800325 this->validate();
bsalomon71cb0c22014-11-14 12:10:14 -0800326 }
327 return resource;
bsalomonbcf0a522014-10-08 08:40:09 -0700328}
bsalomon8b79d232014-11-10 10:19:06 -0800329
bsalomon0ea80f42015-02-11 10:49:59 -0800330void GrResourceCache::willRemoveScratchKey(const GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400331 ASSERT_SINGLE_OWNER
bsalomon3582d3e2015-02-13 14:20:05 -0800332 SkASSERT(resource->resourcePriv().getScratchKey().isValid());
robertphillipsc4ed6842016-05-24 14:17:12 -0700333 if (!resource->getUniqueKey().isValid()) {
334 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
335 }
bsalomon10e23ca2014-11-25 05:52:06 -0800336}
337
bsalomonf99e9612015-02-19 08:24:16 -0800338void GrResourceCache::removeUniqueKey(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400339 ASSERT_SINGLE_OWNER
bsalomon3f324322015-04-08 11:01:54 -0700340 // Someone has a ref to this resource in order to have removed the key. When the ref count
341 // reaches zero we will get a ref cnt notification and figure out what to do with it.
bsalomonf99e9612015-02-19 08:24:16 -0800342 if (resource->getUniqueKey().isValid()) {
343 SkASSERT(resource == fUniqueHash.find(resource->getUniqueKey()));
344 fUniqueHash.remove(resource->getUniqueKey());
345 }
346 resource->cacheAccess().removeUniqueKey();
robertphillipsc4ed6842016-05-24 14:17:12 -0700347 if (resource->resourcePriv().getScratchKey().isValid()) {
348 fScratchMap.insert(resource->resourcePriv().getScratchKey(), resource);
349 }
350
Brian Salomon9bc76d92019-01-24 12:18:33 -0500351 // Removing a unique key from a kUnbudgetedCacheable resource would make the resource
352 // require purging. However, the resource must be ref'ed to get here and therefore can't
353 // be purgeable. We'll purge it when the refs reach zero.
354 SkASSERT(!resource->resourcePriv().isPurgeable());
bsalomonf99e9612015-02-19 08:24:16 -0800355 this->validate();
bsalomon23e619c2015-02-06 11:54:28 -0800356}
357
bsalomonf99e9612015-02-19 08:24:16 -0800358void GrResourceCache::changeUniqueKey(GrGpuResource* resource, const GrUniqueKey& newKey) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400359 ASSERT_SINGLE_OWNER
bsalomon8b79d232014-11-10 10:19:06 -0800360 SkASSERT(resource);
bsalomon71cb0c22014-11-14 12:10:14 -0800361 SkASSERT(this->isInCache(resource));
bsalomon8b79d232014-11-10 10:19:06 -0800362
bsalomonf99e9612015-02-19 08:24:16 -0800363 // If another resource has the new key, remove its key then install the key on this resource.
364 if (newKey.isValid()) {
Greg Daniel0d537802017-09-08 11:44:14 -0400365 if (GrGpuResource* old = fUniqueHash.find(newKey)) {
366 // If the old resource using the key is purgeable and is unreachable, then remove it.
Brian Salomon614c1a82018-12-19 15:42:06 -0500367 if (!old->resourcePriv().getScratchKey().isValid() &&
368 old->resourcePriv().isPurgeable()) {
Greg Daniel0d537802017-09-08 11:44:14 -0400369 old->cacheAccess().release();
370 } else {
Brian Salomon9bc76d92019-01-24 12:18:33 -0500371 // removeUniqueKey expects an external owner of the resource.
372 this->removeUniqueKey(sk_ref_sp(old).get());
Greg Daniel0d537802017-09-08 11:44:14 -0400373 }
374 }
375 SkASSERT(nullptr == fUniqueHash.find(newKey));
376
robertphillipsc4ed6842016-05-24 14:17:12 -0700377 // Remove the entry for this resource if it already has a unique key.
378 if (resource->getUniqueKey().isValid()) {
379 SkASSERT(resource == fUniqueHash.find(resource->getUniqueKey()));
380 fUniqueHash.remove(resource->getUniqueKey());
381 SkASSERT(nullptr == fUniqueHash.find(resource->getUniqueKey()));
382 } else {
383 // 'resource' didn't have a valid unique key before so it is switching sides. Remove it
384 // from the ScratchMap
385 if (resource->resourcePriv().getScratchKey().isValid()) {
386 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
387 }
388 }
389
bsalomonf99e9612015-02-19 08:24:16 -0800390 resource->cacheAccess().setUniqueKey(newKey);
391 fUniqueHash.add(resource);
392 } else {
robertphillipsc4ed6842016-05-24 14:17:12 -0700393 this->removeUniqueKey(resource);
bsalomonf99e9612015-02-19 08:24:16 -0800394 }
395
bsalomon71cb0c22014-11-14 12:10:14 -0800396 this->validate();
bsalomon8b79d232014-11-10 10:19:06 -0800397}
bsalomon71cb0c22014-11-14 12:10:14 -0800398
bsalomon9f2d1572015-02-17 11:47:40 -0800399void GrResourceCache::refAndMakeResourceMRU(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400400 ASSERT_SINGLE_OWNER
bsalomon71cb0c22014-11-14 12:10:14 -0800401 SkASSERT(resource);
402 SkASSERT(this->isInCache(resource));
bsalomonddf30e62015-02-19 11:38:44 -0800403
Brian Salomon614c1a82018-12-19 15:42:06 -0500404 if (resource->resourcePriv().isPurgeable()) {
bsalomon9f2d1572015-02-17 11:47:40 -0800405 // It's about to become unpurgeable.
Derek Sollenbergeree479142017-05-24 11:41:33 -0400406 fPurgeableBytes -= resource->gpuMemorySize();
bsalomon9f2d1572015-02-17 11:47:40 -0800407 fPurgeableQueue.remove(resource);
bsalomonf320e042015-02-17 15:09:34 -0800408 this->addToNonpurgeableArray(resource);
Brian Salomon2c791fc2019-04-02 11:52:03 -0400409 } else if (!resource->cacheAccess().hasRef() &&
410 resource->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted) {
411 SkASSERT(fNumBudgetedResourcesFlushWillMakePurgeable > 0);
412 fNumBudgetedResourcesFlushWillMakePurgeable--;
bsalomon9f2d1572015-02-17 11:47:40 -0800413 }
Brian Salomon01ceae92019-04-02 11:49:54 -0400414 resource->cacheAccess().ref();
bsalomonddf30e62015-02-19 11:38:44 -0800415
416 resource->cacheAccess().setTimestamp(this->getNextTimestamp());
bsalomonf320e042015-02-17 15:09:34 -0800417 this->validate();
bsalomon71cb0c22014-11-14 12:10:14 -0800418}
419
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400420void GrResourceCache::notifyRefCntReachedZero(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400421 ASSERT_SINGLE_OWNER
bsalomon71cb0c22014-11-14 12:10:14 -0800422 SkASSERT(resource);
bsalomon3f324322015-04-08 11:01:54 -0700423 SkASSERT(!resource->wasDestroyed());
bsalomon71cb0c22014-11-14 12:10:14 -0800424 SkASSERT(this->isInCache(resource));
bsalomon3f324322015-04-08 11:01:54 -0700425 // This resource should always be in the nonpurgeable array when this function is called. It
426 // will be moved to the queue if it is newly purgeable.
427 SkASSERT(fNonpurgeableResources[*resource->cacheAccess().accessCacheIndex()] == resource);
bsalomon71cb0c22014-11-14 12:10:14 -0800428
bsalomon3f324322015-04-08 11:01:54 -0700429#ifdef SK_DEBUG
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400430 // When the timestamp overflows validate() is called. validate() checks that resources in
431 // the nonpurgeable array are indeed not purgeable. However, the movement from the array to
432 // the purgeable queue happens just below in this function. So we mark it as an exception.
433 if (resource->resourcePriv().isPurgeable()) {
434 fNewlyPurgeableResourceForValidation = resource;
bsalomon3f324322015-04-08 11:01:54 -0700435 }
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400436#endif
437 resource->cacheAccess().setTimestamp(this->getNextTimestamp());
438 SkDEBUGCODE(fNewlyPurgeableResourceForValidation = nullptr);
bsalomon3f324322015-04-08 11:01:54 -0700439
Robert Phillipsbf8bf832019-08-30 13:13:44 -0400440 if (!resource->resourcePriv().isPurgeable() &&
441 resource->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted) {
442 ++fNumBudgetedResourcesFlushWillMakePurgeable;
bsalomon3f324322015-04-08 11:01:54 -0700443 }
444
Brian Salomon9bc76d92019-01-24 12:18:33 -0500445 if (!resource->resourcePriv().isPurgeable()) {
446 this->validate();
447 return;
448 }
449
bsalomonf320e042015-02-17 15:09:34 -0800450 this->removeFromNonpurgeableArray(resource);
bsalomon9f2d1572015-02-17 11:47:40 -0800451 fPurgeableQueue.insert(resource);
Brian Salomon5e150852017-03-22 14:53:13 -0400452 resource->cacheAccess().setTimeWhenResourceBecomePurgeable();
Derek Sollenbergeree479142017-05-24 11:41:33 -0400453 fPurgeableBytes += resource->gpuMemorySize();
bsalomon71cb0c22014-11-14 12:10:14 -0800454
Greg Daniel303e83e2018-09-10 14:10:19 -0400455 bool hasUniqueKey = resource->getUniqueKey().isValid();
456
Brian Salomon9bc76d92019-01-24 12:18:33 -0500457 GrBudgetedType budgetedType = resource->resourcePriv().budgetedType();
Brian Salomon614c1a82018-12-19 15:42:06 -0500458
Brian Salomon9bc76d92019-01-24 12:18:33 -0500459 if (budgetedType == GrBudgetedType::kBudgeted) {
460 // Purge the resource immediately if we're over budget
461 // Also purge if the resource has neither a valid scratch key nor a unique key.
462 bool hasKey = resource->resourcePriv().getScratchKey().isValid() || hasUniqueKey;
463 if (!this->overBudget() && hasKey) {
464 return;
465 }
466 } else {
467 // We keep unbudgeted resources with a unique key in the purgeable queue of the cache so
468 // they can be reused again by the image connected to the unique key.
469 if (hasUniqueKey && budgetedType == GrBudgetedType::kUnbudgetedCacheable) {
470 return;
471 }
472 // Check whether this resource could still be used as a scratch resource.
473 if (!resource->resourcePriv().refsWrappedObjects() &&
474 resource->resourcePriv().getScratchKey().isValid()) {
475 // We won't purge an existing resource to make room for this one.
Robert Phillipscf39f372019-09-03 10:29:20 -0400476 if (this->wouldFit(resource->gpuMemorySize())) {
Brian Salomon9bc76d92019-01-24 12:18:33 -0500477 resource->resourcePriv().makeBudgeted();
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500478 return;
479 }
bsalomonc2f35b72015-01-23 07:19:22 -0800480 }
bsalomonc2f35b72015-01-23 07:19:22 -0800481 }
Brian Salomon9bc76d92019-01-24 12:18:33 -0500482
bsalomonf320e042015-02-17 15:09:34 -0800483 SkDEBUGCODE(int beforeCount = this->getResourceCount();)
bsalomon9f2d1572015-02-17 11:47:40 -0800484 resource->cacheAccess().release();
485 // We should at least free this resource, perhaps dependent resources as well.
bsalomonf320e042015-02-17 15:09:34 -0800486 SkASSERT(this->getResourceCount() < beforeCount);
bsalomon71cb0c22014-11-14 12:10:14 -0800487 this->validate();
488}
489
bsalomon0ea80f42015-02-11 10:49:59 -0800490void GrResourceCache::didChangeBudgetStatus(GrGpuResource* resource) {
Brian Salomon8f8995a2018-10-15 14:32:15 -0400491 ASSERT_SINGLE_OWNER
bsalomon84c8e622014-11-17 09:33:27 -0800492 SkASSERT(resource);
493 SkASSERT(this->isInCache(resource));
494
495 size_t size = resource->gpuMemorySize();
Brian Salomon9bc76d92019-01-24 12:18:33 -0500496 // Changing from BudgetedType::kUnbudgetedCacheable to another budgeted type could make
497 // resource become purgeable. However, we should never allow that transition. Wrapped
498 // resources are the only resources that can be in that state and they aren't allowed to
499 // transition from one budgeted state to another.
500 SkDEBUGCODE(bool wasPurgeable = resource->resourcePriv().isPurgeable());
501 if (resource->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted) {
bsalomon84c8e622014-11-17 09:33:27 -0800502 ++fBudgetedCount;
503 fBudgetedBytes += size;
bsalomonafe30052015-01-16 07:32:33 -0800504#if GR_CACHE_STATS
505 fBudgetedHighWaterBytes = SkTMax(fBudgetedBytes, fBudgetedHighWaterBytes);
506 fBudgetedHighWaterCount = SkTMax(fBudgetedCount, fBudgetedHighWaterCount);
507#endif
Brian Salomon2c791fc2019-04-02 11:52:03 -0400508 if (!resource->resourcePriv().isPurgeable() && !resource->cacheAccess().hasRef()) {
509 ++fNumBudgetedResourcesFlushWillMakePurgeable;
510 }
bsalomon84c8e622014-11-17 09:33:27 -0800511 this->purgeAsNeeded();
512 } else {
Brian Salomon9bc76d92019-01-24 12:18:33 -0500513 SkASSERT(resource->resourcePriv().budgetedType() != GrBudgetedType::kUnbudgetedCacheable);
bsalomon84c8e622014-11-17 09:33:27 -0800514 --fBudgetedCount;
515 fBudgetedBytes -= size;
Brian Salomon2c791fc2019-04-02 11:52:03 -0400516 if (!resource->resourcePriv().isPurgeable() && !resource->cacheAccess().hasRef()) {
517 --fNumBudgetedResourcesFlushWillMakePurgeable;
518 }
bsalomon84c8e622014-11-17 09:33:27 -0800519 }
Brian Salomon9bc76d92019-01-24 12:18:33 -0500520 SkASSERT(wasPurgeable == resource->resourcePriv().isPurgeable());
Brian Osman39c08ac2017-07-26 09:36:09 -0400521 TRACE_COUNTER2("skia.gpu.cache", "skia budget", "used",
hendrikw876c3132015-03-04 10:33:49 -0800522 fBudgetedBytes, "free", fMaxBytes - fBudgetedBytes);
bsalomon84c8e622014-11-17 09:33:27 -0800523
524 this->validate();
525}
526
robertphillipsee843b22016-10-04 05:30:20 -0700527void GrResourceCache::purgeAsNeeded() {
bsalomon3f324322015-04-08 11:01:54 -0700528 SkTArray<GrUniqueKeyInvalidatedMessage> invalidKeyMsgs;
529 fInvalidUniqueKeyInbox.poll(&invalidKeyMsgs);
530 if (invalidKeyMsgs.count()) {
Robert Phillips427966a2018-12-20 17:20:43 -0500531 SkASSERT(fProxyProvider);
532
533 for (int i = 0; i < invalidKeyMsgs.count(); ++i) {
534 fProxyProvider->processInvalidUniqueKey(invalidKeyMsgs[i].key(), nullptr,
535 GrProxyProvider::InvalidateGPUResource::kYes);
536 SkASSERT(!this->findAndRefUniqueResource(invalidKeyMsgs[i].key()));
537 }
bsalomon3f324322015-04-08 11:01:54 -0700538 }
bsalomon71cb0c22014-11-14 12:10:14 -0800539
Brian Osman13dddce2017-05-09 13:19:50 -0400540 this->processFreedGpuResources();
541
bsalomon3f324322015-04-08 11:01:54 -0700542 bool stillOverbudget = this->overBudget();
543 while (stillOverbudget && fPurgeableQueue.count()) {
robertphillipsee843b22016-10-04 05:30:20 -0700544 GrGpuResource* resource = fPurgeableQueue.peek();
Brian Salomon614c1a82018-12-19 15:42:06 -0500545 SkASSERT(resource->resourcePriv().isPurgeable());
bsalomon9f2d1572015-02-17 11:47:40 -0800546 resource->cacheAccess().release();
bsalomon3f324322015-04-08 11:01:54 -0700547 stillOverbudget = this->overBudget();
bsalomon9f2d1572015-02-17 11:47:40 -0800548 }
bsalomon71cb0c22014-11-14 12:10:14 -0800549
bsalomonb436ed62014-11-17 12:15:56 -0800550 this->validate();
bsalomon71cb0c22014-11-14 12:10:14 -0800551}
552
Robert Phillips6eba0632018-03-28 12:25:42 -0400553void GrResourceCache::purgeUnlockedResources(bool scratchResourcesOnly) {
554 if (!scratchResourcesOnly) {
555 // We could disable maintaining the heap property here, but it would add a lot of
556 // complexity. Moreover, this is rarely called.
557 while (fPurgeableQueue.count()) {
558 GrGpuResource* resource = fPurgeableQueue.peek();
Brian Salomon614c1a82018-12-19 15:42:06 -0500559 SkASSERT(resource->resourcePriv().isPurgeable());
Robert Phillips6eba0632018-03-28 12:25:42 -0400560 resource->cacheAccess().release();
561 }
562 } else {
563 // Sort the queue
564 fPurgeableQueue.sort();
565
566 // Make a list of the scratch resources to delete
567 SkTDArray<GrGpuResource*> scratchResources;
568 for (int i = 0; i < fPurgeableQueue.count(); i++) {
569 GrGpuResource* resource = fPurgeableQueue.at(i);
Brian Salomon614c1a82018-12-19 15:42:06 -0500570 SkASSERT(resource->resourcePriv().isPurgeable());
Robert Phillips6eba0632018-03-28 12:25:42 -0400571 if (!resource->getUniqueKey().isValid()) {
572 *scratchResources.append() = resource;
573 }
574 }
575
576 // Delete the scratch resources. This must be done as a separate pass
577 // to avoid messing up the sorted order of the queue
578 for (int i = 0; i < scratchResources.count(); i++) {
579 scratchResources.getAt(i)->cacheAccess().release();
580 }
bsalomon9f2d1572015-02-17 11:47:40 -0800581 }
bsalomon71cb0c22014-11-14 12:10:14 -0800582
bsalomonb436ed62014-11-17 12:15:56 -0800583 this->validate();
bsalomon71cb0c22014-11-14 12:10:14 -0800584}
585
Brian Salomon5e150852017-03-22 14:53:13 -0400586void GrResourceCache::purgeResourcesNotUsedSince(GrStdSteadyClock::time_point purgeTime) {
587 while (fPurgeableQueue.count()) {
588 const GrStdSteadyClock::time_point resourceTime =
589 fPurgeableQueue.peek()->cacheAccess().timeWhenResourceBecamePurgeable();
590 if (resourceTime >= purgeTime) {
591 // Resources were given both LRU timestamps and tagged with a frame number when
592 // they first became purgeable. The LRU timestamp won't change again until the
593 // resource is made non-purgeable again. So, at this point all the remaining
594 // resources in the timestamp-sorted queue will have a frame number >= to this
595 // one.
596 break;
597 }
598 GrGpuResource* resource = fPurgeableQueue.peek();
Brian Salomon614c1a82018-12-19 15:42:06 -0500599 SkASSERT(resource->resourcePriv().isPurgeable());
Brian Salomon5e150852017-03-22 14:53:13 -0400600 resource->cacheAccess().release();
601 }
602}
603
Derek Sollenberger5480a182017-05-25 16:43:59 -0400604void GrResourceCache::purgeUnlockedResources(size_t bytesToPurge, bool preferScratchResources) {
605
606 const size_t tmpByteBudget = SkTMax((size_t)0, fBytes - bytesToPurge);
607 bool stillOverbudget = tmpByteBudget < fBytes;
608
609 if (preferScratchResources && bytesToPurge < fPurgeableBytes) {
610 // Sort the queue
611 fPurgeableQueue.sort();
612
613 // Make a list of the scratch resources to delete
614 SkTDArray<GrGpuResource*> scratchResources;
615 size_t scratchByteCount = 0;
616 for (int i = 0; i < fPurgeableQueue.count() && stillOverbudget; i++) {
617 GrGpuResource* resource = fPurgeableQueue.at(i);
Brian Salomon614c1a82018-12-19 15:42:06 -0500618 SkASSERT(resource->resourcePriv().isPurgeable());
Derek Sollenberger5480a182017-05-25 16:43:59 -0400619 if (!resource->getUniqueKey().isValid()) {
620 *scratchResources.append() = resource;
621 scratchByteCount += resource->gpuMemorySize();
622 stillOverbudget = tmpByteBudget < fBytes - scratchByteCount;
623 }
624 }
625
626 // Delete the scratch resources. This must be done as a separate pass
627 // to avoid messing up the sorted order of the queue
628 for (int i = 0; i < scratchResources.count(); i++) {
629 scratchResources.getAt(i)->cacheAccess().release();
630 }
631 stillOverbudget = tmpByteBudget < fBytes;
632
633 this->validate();
634 }
635
636 // Purge any remaining resources in LRU order
637 if (stillOverbudget) {
638 const size_t cachedByteCount = fMaxBytes;
639 fMaxBytes = tmpByteBudget;
640 this->purgeAsNeeded();
641 fMaxBytes = cachedByteCount;
642 }
643}
Brian Salomon8cefa3e2019-04-04 11:39:55 -0400644bool GrResourceCache::requestsFlush() const {
645 return this->overBudget() && !fPurgeableQueue.count() &&
646 fNumBudgetedResourcesFlushWillMakePurgeable > 0;
647}
648
Derek Sollenberger5480a182017-05-25 16:43:59 -0400649
Brian Salomon876a0172019-03-08 11:12:14 -0500650void GrResourceCache::insertDelayedResourceUnref(GrGpuResource* resource) {
Brian Osman13dddce2017-05-09 13:19:50 -0400651 resource->ref();
Brian Salomon876a0172019-03-08 11:12:14 -0500652 uint32_t id = resource->uniqueID().asUInt();
653 if (auto* data = fResourcesAwaitingUnref.find(id)) {
654 data->addRef();
655 } else {
656 fResourcesAwaitingUnref.set(id, {resource});
657 }
Brian Osman13dddce2017-05-09 13:19:50 -0400658}
659
660void GrResourceCache::processFreedGpuResources() {
661 SkTArray<GrGpuResourceFreedMessage> msgs;
662 fFreedGpuResourceInbox.poll(&msgs);
663 for (int i = 0; i < msgs.count(); ++i) {
Brian Salomon238069b2018-07-11 15:58:57 -0400664 SkASSERT(msgs[i].fOwningUniqueID == fContextUniqueID);
Brian Salomon876a0172019-03-08 11:12:14 -0500665 uint32_t id = msgs[i].fResource->uniqueID().asUInt();
666 ResourceAwaitingUnref* info = fResourcesAwaitingUnref.find(id);
Greg Danielb2acf0a2018-09-12 09:17:11 -0400667 // If we called release or abandon on the GrContext we will have already released our ref on
668 // the GrGpuResource. If then the message arrives before the actual GrContext gets destroyed
669 // we will try to process the message when we destroy the GrContext. This protects us from
670 // trying to unref the resource twice.
Brian Salomon876a0172019-03-08 11:12:14 -0500671 if (info) {
672 info->unref();
673 if (info->finished()) {
674 fResourcesAwaitingUnref.remove(id);
675 }
Greg Danielb2acf0a2018-09-12 09:17:11 -0400676 }
Brian Osman13dddce2017-05-09 13:19:50 -0400677 }
678}
679
bsalomonf320e042015-02-17 15:09:34 -0800680void GrResourceCache::addToNonpurgeableArray(GrGpuResource* resource) {
681 int index = fNonpurgeableResources.count();
682 *fNonpurgeableResources.append() = resource;
683 *resource->cacheAccess().accessCacheIndex() = index;
684}
685
686void GrResourceCache::removeFromNonpurgeableArray(GrGpuResource* resource) {
687 int* index = resource->cacheAccess().accessCacheIndex();
688 // Fill the whole we will create in the array with the tail object, adjust its index, and
689 // then pop the array
690 GrGpuResource* tail = *(fNonpurgeableResources.end() - 1);
691 SkASSERT(fNonpurgeableResources[*index] == resource);
692 fNonpurgeableResources[*index] = tail;
693 *tail->cacheAccess().accessCacheIndex() = *index;
694 fNonpurgeableResources.pop();
695 SkDEBUGCODE(*index = -1);
696}
697
bsalomonddf30e62015-02-19 11:38:44 -0800698uint32_t GrResourceCache::getNextTimestamp() {
699 // If we wrap then all the existing resources will appear older than any resources that get
700 // a timestamp after the wrap.
701 if (0 == fTimestamp) {
702 int count = this->getResourceCount();
703 if (count) {
704 // Reset all the timestamps. We sort the resources by timestamp and then assign
705 // sequential timestamps beginning with 0. This is O(n*lg(n)) but it should be extremely
706 // rare.
707 SkTDArray<GrGpuResource*> sortedPurgeableResources;
708 sortedPurgeableResources.setReserve(fPurgeableQueue.count());
709
710 while (fPurgeableQueue.count()) {
711 *sortedPurgeableResources.append() = fPurgeableQueue.peek();
712 fPurgeableQueue.pop();
713 }
robertphillipsee843b22016-10-04 05:30:20 -0700714
bsalomone2e87f32016-09-22 12:42:11 -0700715 SkTQSort(fNonpurgeableResources.begin(), fNonpurgeableResources.end() - 1,
716 CompareTimestamp);
bsalomonddf30e62015-02-19 11:38:44 -0800717
718 // Pick resources out of the purgeable and non-purgeable arrays based on lowest
719 // timestamp and assign new timestamps.
720 int currP = 0;
721 int currNP = 0;
722 while (currP < sortedPurgeableResources.count() &&
mtklein56da0252015-11-16 11:16:23 -0800723 currNP < fNonpurgeableResources.count()) {
bsalomonddf30e62015-02-19 11:38:44 -0800724 uint32_t tsP = sortedPurgeableResources[currP]->cacheAccess().timestamp();
725 uint32_t tsNP = fNonpurgeableResources[currNP]->cacheAccess().timestamp();
726 SkASSERT(tsP != tsNP);
727 if (tsP < tsNP) {
728 sortedPurgeableResources[currP++]->cacheAccess().setTimestamp(fTimestamp++);
729 } else {
730 // Correct the index in the nonpurgeable array stored on the resource post-sort.
731 *fNonpurgeableResources[currNP]->cacheAccess().accessCacheIndex() = currNP;
732 fNonpurgeableResources[currNP++]->cacheAccess().setTimestamp(fTimestamp++);
733 }
734 }
735
736 // The above loop ended when we hit the end of one array. Finish the other one.
737 while (currP < sortedPurgeableResources.count()) {
738 sortedPurgeableResources[currP++]->cacheAccess().setTimestamp(fTimestamp++);
739 }
740 while (currNP < fNonpurgeableResources.count()) {
741 *fNonpurgeableResources[currNP]->cacheAccess().accessCacheIndex() = currNP;
742 fNonpurgeableResources[currNP++]->cacheAccess().setTimestamp(fTimestamp++);
743 }
744
745 // Rebuild the queue.
746 for (int i = 0; i < sortedPurgeableResources.count(); ++i) {
747 fPurgeableQueue.insert(sortedPurgeableResources[i]);
748 }
749
750 this->validate();
751 SkASSERT(count == this->getResourceCount());
752
753 // count should be the next timestamp we return.
754 SkASSERT(fTimestamp == SkToU32(count));
mtklein56da0252015-11-16 11:16:23 -0800755 }
bsalomonddf30e62015-02-19 11:38:44 -0800756 }
757 return fTimestamp++;
758}
759
ericrk0a5fa482015-09-15 14:16:10 -0700760void GrResourceCache::dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const {
761 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
762 fNonpurgeableResources[i]->dumpMemoryStatistics(traceMemoryDump);
763 }
764 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
765 fPurgeableQueue.at(i)->dumpMemoryStatistics(traceMemoryDump);
766 }
767}
768
Robert Phillipsdbaf3172019-02-06 15:12:53 -0500769#if GR_CACHE_STATS
770void GrResourceCache::getStats(Stats* stats) const {
771 stats->reset();
772
773 stats->fTotal = this->getResourceCount();
774 stats->fNumNonPurgeable = fNonpurgeableResources.count();
775 stats->fNumPurgeable = fPurgeableQueue.count();
776
777 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
778 stats->update(fNonpurgeableResources[i]);
779 }
780 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
781 stats->update(fPurgeableQueue.at(i));
782 }
783}
784
785#if GR_TEST_UTILS
786void GrResourceCache::dumpStats(SkString* out) const {
787 this->validate();
788
789 Stats stats;
790
791 this->getStats(&stats);
792
Robert Phillipsdbaf3172019-02-06 15:12:53 -0500793 float byteUtilization = (100.f * fBudgetedBytes) / fMaxBytes;
794
Robert Phillipscf39f372019-09-03 10:29:20 -0400795 out->appendf("Budget: %d bytes\n", (int)fMaxBytes);
Robert Phillipsdbaf3172019-02-06 15:12:53 -0500796 out->appendf("\t\tEntry Count: current %d"
Robert Phillipscf39f372019-09-03 10:29:20 -0400797 " (%d budgeted, %d wrapped, %d locked, %d scratch), high %d\n",
Robert Phillipsdbaf3172019-02-06 15:12:53 -0500798 stats.fTotal, fBudgetedCount, stats.fWrapped, stats.fNumNonPurgeable,
Robert Phillipscf39f372019-09-03 10:29:20 -0400799 stats.fScratch, fHighWaterCount);
Robert Phillipsdbaf3172019-02-06 15:12:53 -0500800 out->appendf("\t\tEntry Bytes: current %d (budgeted %d, %.2g%% full, %d unbudgeted) high %d\n",
801 SkToInt(fBytes), SkToInt(fBudgetedBytes), byteUtilization,
802 SkToInt(stats.fUnbudgetedSize), SkToInt(fHighWaterBytes));
803}
804
805void GrResourceCache::dumpStatsKeyValuePairs(SkTArray<SkString>* keys,
806 SkTArray<double>* values) const {
807 this->validate();
808
809 Stats stats;
810 this->getStats(&stats);
811
812 keys->push_back(SkString("gpu_cache_purgable_entries")); values->push_back(stats.fNumPurgeable);
813}
814#endif
815
816#endif
817
bsalomon71cb0c22014-11-14 12:10:14 -0800818#ifdef SK_DEBUG
bsalomon0ea80f42015-02-11 10:49:59 -0800819void GrResourceCache::validate() const {
bsalomonc2f35b72015-01-23 07:19:22 -0800820 // Reduce the frequency of validations for large resource counts.
821 static SkRandom gRandom;
822 int mask = (SkNextPow2(fCount + 1) >> 5) - 1;
823 if (~mask && (gRandom.nextU() & mask)) {
824 return;
825 }
826
bsalomonf320e042015-02-17 15:09:34 -0800827 struct Stats {
828 size_t fBytes;
829 int fBudgetedCount;
830 size_t fBudgetedBytes;
831 int fLocked;
832 int fScratch;
833 int fCouldBeScratch;
834 int fContent;
835 const ScratchMap* fScratchMap;
bsalomon8718aaf2015-02-19 07:24:21 -0800836 const UniqueHash* fUniqueHash;
bsalomon71cb0c22014-11-14 12:10:14 -0800837
bsalomonf320e042015-02-17 15:09:34 -0800838 Stats(const GrResourceCache* cache) {
839 memset(this, 0, sizeof(*this));
840 fScratchMap = &cache->fScratchMap;
bsalomon8718aaf2015-02-19 07:24:21 -0800841 fUniqueHash = &cache->fUniqueHash;
bsalomon71cb0c22014-11-14 12:10:14 -0800842 }
843
bsalomonf320e042015-02-17 15:09:34 -0800844 void update(GrGpuResource* resource) {
845 fBytes += resource->gpuMemorySize();
bsalomondace19e2014-11-17 07:34:06 -0800846
Brian Salomon614c1a82018-12-19 15:42:06 -0500847 if (!resource->resourcePriv().isPurgeable()) {
bsalomonf320e042015-02-17 15:09:34 -0800848 ++fLocked;
849 }
bsalomon9f2d1572015-02-17 11:47:40 -0800850
robertphillipsc4ed6842016-05-24 14:17:12 -0700851 const GrScratchKey& scratchKey = resource->resourcePriv().getScratchKey();
852 const GrUniqueKey& uniqueKey = resource->getUniqueKey();
853
bsalomonf320e042015-02-17 15:09:34 -0800854 if (resource->cacheAccess().isScratch()) {
robertphillipsc4ed6842016-05-24 14:17:12 -0700855 SkASSERT(!uniqueKey.isValid());
bsalomonf320e042015-02-17 15:09:34 -0800856 ++fScratch;
robertphillipsc4ed6842016-05-24 14:17:12 -0700857 SkASSERT(fScratchMap->countForKey(scratchKey));
kkinnunen2e6055b2016-04-22 01:48:29 -0700858 SkASSERT(!resource->resourcePriv().refsWrappedObjects());
robertphillipsc4ed6842016-05-24 14:17:12 -0700859 } else if (scratchKey.isValid()) {
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500860 SkASSERT(GrBudgetedType::kBudgeted != resource->resourcePriv().budgetedType() ||
robertphillipsc4ed6842016-05-24 14:17:12 -0700861 uniqueKey.isValid());
862 if (!uniqueKey.isValid()) {
mtklein4e976072016-08-08 09:06:27 -0700863 ++fCouldBeScratch;
robertphillipsc4ed6842016-05-24 14:17:12 -0700864 SkASSERT(fScratchMap->countForKey(scratchKey));
865 }
kkinnunen2e6055b2016-04-22 01:48:29 -0700866 SkASSERT(!resource->resourcePriv().refsWrappedObjects());
bsalomonf320e042015-02-17 15:09:34 -0800867 }
bsalomon8718aaf2015-02-19 07:24:21 -0800868 if (uniqueKey.isValid()) {
bsalomonf320e042015-02-17 15:09:34 -0800869 ++fContent;
bsalomon8718aaf2015-02-19 07:24:21 -0800870 SkASSERT(fUniqueHash->find(uniqueKey) == resource);
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500871 SkASSERT(GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType() ||
Brian Osman0562eb92017-05-08 11:16:39 -0400872 resource->resourcePriv().refsWrappedObjects());
robertphillipsc4ed6842016-05-24 14:17:12 -0700873
874 if (scratchKey.isValid()) {
875 SkASSERT(!fScratchMap->has(resource, scratchKey));
876 }
bsalomonf320e042015-02-17 15:09:34 -0800877 }
878
Brian Salomonfa2ebea2019-01-24 15:58:58 -0500879 if (GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType()) {
bsalomonf320e042015-02-17 15:09:34 -0800880 ++fBudgetedCount;
881 fBudgetedBytes += resource->gpuMemorySize();
882 }
bsalomon9f2d1572015-02-17 11:47:40 -0800883 }
bsalomonf320e042015-02-17 15:09:34 -0800884 };
885
robertphillipsc4ed6842016-05-24 14:17:12 -0700886 {
887 ScratchMap::ConstIter iter(&fScratchMap);
888
889 int count = 0;
890 for ( ; !iter.done(); ++iter) {
891 const GrGpuResource* resource = *iter;
892 SkASSERT(resource->resourcePriv().getScratchKey().isValid());
893 SkASSERT(!resource->getUniqueKey().isValid());
894 count++;
895 }
896 SkASSERT(count == fScratchMap.count()); // ensure the iterator is working correctly
897 }
898
bsalomonf320e042015-02-17 15:09:34 -0800899 Stats stats(this);
Derek Sollenbergeree479142017-05-24 11:41:33 -0400900 size_t purgeableBytes = 0;
Brian Salomon2c791fc2019-04-02 11:52:03 -0400901 int numBudgetedResourcesFlushWillMakePurgeable = 0;
bsalomonf320e042015-02-17 15:09:34 -0800902
903 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
Brian Salomon614c1a82018-12-19 15:42:06 -0500904 SkASSERT(!fNonpurgeableResources[i]->resourcePriv().isPurgeable() ||
bsalomon3f324322015-04-08 11:01:54 -0700905 fNewlyPurgeableResourceForValidation == fNonpurgeableResources[i]);
bsalomonf320e042015-02-17 15:09:34 -0800906 SkASSERT(*fNonpurgeableResources[i]->cacheAccess().accessCacheIndex() == i);
907 SkASSERT(!fNonpurgeableResources[i]->wasDestroyed());
Brian Salomon2c791fc2019-04-02 11:52:03 -0400908 if (fNonpurgeableResources[i]->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted &&
909 !fNonpurgeableResources[i]->cacheAccess().hasRef() &&
910 fNewlyPurgeableResourceForValidation != fNonpurgeableResources[i]) {
Brian Salomon2c791fc2019-04-02 11:52:03 -0400911 ++numBudgetedResourcesFlushWillMakePurgeable;
912 }
bsalomonf320e042015-02-17 15:09:34 -0800913 stats.update(fNonpurgeableResources[i]);
bsalomon71cb0c22014-11-14 12:10:14 -0800914 }
bsalomon9f2d1572015-02-17 11:47:40 -0800915 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
Brian Salomon614c1a82018-12-19 15:42:06 -0500916 SkASSERT(fPurgeableQueue.at(i)->resourcePriv().isPurgeable());
bsalomonf320e042015-02-17 15:09:34 -0800917 SkASSERT(*fPurgeableQueue.at(i)->cacheAccess().accessCacheIndex() == i);
918 SkASSERT(!fPurgeableQueue.at(i)->wasDestroyed());
919 stats.update(fPurgeableQueue.at(i));
Derek Sollenbergeree479142017-05-24 11:41:33 -0400920 purgeableBytes += fPurgeableQueue.at(i)->gpuMemorySize();
bsalomon9f2d1572015-02-17 11:47:40 -0800921 }
922
bsalomonf320e042015-02-17 15:09:34 -0800923 SkASSERT(fCount == this->getResourceCount());
bsalomondace19e2014-11-17 07:34:06 -0800924 SkASSERT(fBudgetedCount <= fCount);
bsalomonf320e042015-02-17 15:09:34 -0800925 SkASSERT(fBudgetedBytes <= fBytes);
926 SkASSERT(stats.fBytes == fBytes);
Brian Salomon2c791fc2019-04-02 11:52:03 -0400927 SkASSERT(fNumBudgetedResourcesFlushWillMakePurgeable ==
928 numBudgetedResourcesFlushWillMakePurgeable);
bsalomonf320e042015-02-17 15:09:34 -0800929 SkASSERT(stats.fBudgetedBytes == fBudgetedBytes);
930 SkASSERT(stats.fBudgetedCount == fBudgetedCount);
Derek Sollenbergeree479142017-05-24 11:41:33 -0400931 SkASSERT(purgeableBytes == fPurgeableBytes);
bsalomon71cb0c22014-11-14 12:10:14 -0800932#if GR_CACHE_STATS
bsalomondace19e2014-11-17 07:34:06 -0800933 SkASSERT(fBudgetedHighWaterCount <= fHighWaterCount);
934 SkASSERT(fBudgetedHighWaterBytes <= fHighWaterBytes);
bsalomonf320e042015-02-17 15:09:34 -0800935 SkASSERT(fBytes <= fHighWaterBytes);
936 SkASSERT(fCount <= fHighWaterCount);
937 SkASSERT(fBudgetedBytes <= fBudgetedHighWaterBytes);
938 SkASSERT(fBudgetedCount <= fBudgetedHighWaterCount);
bsalomon71cb0c22014-11-14 12:10:14 -0800939#endif
bsalomon8718aaf2015-02-19 07:24:21 -0800940 SkASSERT(stats.fContent == fUniqueHash.count());
bsalomonf320e042015-02-17 15:09:34 -0800941 SkASSERT(stats.fScratch + stats.fCouldBeScratch == fScratchMap.count());
bsalomon71cb0c22014-11-14 12:10:14 -0800942
bsalomon3f324322015-04-08 11:01:54 -0700943 // This assertion is not currently valid because we can be in recursive notifyCntReachedZero()
bsalomon12299ab2014-11-14 13:33:09 -0800944 // calls. This will be fixed when subresource registration is explicit.
bsalomondace19e2014-11-17 07:34:06 -0800945 // bool overBudget = budgetedBytes > fMaxBytes || budgetedCount > fMaxCount;
bsalomon12299ab2014-11-14 13:33:09 -0800946 // SkASSERT(!overBudget || locked == count || fPurging);
bsalomon71cb0c22014-11-14 12:10:14 -0800947}
bsalomonf320e042015-02-17 15:09:34 -0800948
949bool GrResourceCache::isInCache(const GrGpuResource* resource) const {
950 int index = *resource->cacheAccess().accessCacheIndex();
951 if (index < 0) {
952 return false;
953 }
954 if (index < fPurgeableQueue.count() && fPurgeableQueue.at(index) == resource) {
955 return true;
956 }
957 if (index < fNonpurgeableResources.count() && fNonpurgeableResources[index] == resource) {
958 return true;
959 }
960 SkDEBUGFAIL("Resource index should be -1 or the resource should be in the cache.");
961 return false;
962}
963
bsalomon71cb0c22014-11-14 12:10:14 -0800964#endif