1 /*
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
8 #include "src/gpu/GrResourceCache.h"
9 #include <atomic>
10 #include <ctime>
11 #include <vector>
12 #include <map>
13 #include <sstream>
14 #ifdef NOT_BUILD_FOR_OHOS_SDK
15 #include <parameters.h>
16 #endif
17 #include "include/core/SkString.h"
18 #include "include/gpu/GrDirectContext.h"
19 #include "include/private/GrSingleOwner.h"
20 #include "include/private/SkTo.h"
21 #include "include/utils/SkRandom.h"
22 #include "src/core/SkMessageBus.h"
23 #include "src/core/SkOpts.h"
24 #include "src/core/SkScopeExit.h"
25 #include "src/core/SkTSort.h"
26 #include "src/gpu/GrCaps.h"
27 #include "src/gpu/GrDirectContextPriv.h"
28 #include "src/gpu/GrGpuResourceCacheAccess.h"
29 #include "src/gpu/GrProxyProvider.h"
30 #include "src/gpu/GrTexture.h"
31 #include "src/gpu/GrTextureProxyCacheAccess.h"
32 #include "src/gpu/GrThreadSafeCache.h"
33 #include "src/gpu/GrTracing.h"
34 #include "src/gpu/SkGr.h"
35
36 DECLARE_SKMESSAGEBUS_MESSAGE(GrUniqueKeyInvalidatedMessage, uint32_t, true);
37
38 DECLARE_SKMESSAGEBUS_MESSAGE(GrTextureFreedMessage, GrDirectContext::DirectContextID, true);
39
40 #define ASSERT_SINGLE_OWNER GR_ASSERT_SINGLE_OWNER(fSingleOwner)
41
42 //////////////////////////////////////////////////////////////////////////////
43
GenerateResourceType()44 GrScratchKey::ResourceType GrScratchKey::GenerateResourceType() {
45 static std::atomic<int32_t> nextType{INHERITED::kInvalidDomain + 1};
46
47 int32_t type = nextType.fetch_add(1, std::memory_order_relaxed);
48 if (type > SkTo<int32_t>(UINT16_MAX)) {
49 SK_ABORT("Too many Resource Types");
50 }
51
52 return static_cast<ResourceType>(type);
53 }
54
GenerateDomain()55 GrUniqueKey::Domain GrUniqueKey::GenerateDomain() {
56 static std::atomic<int32_t> nextDomain{INHERITED::kInvalidDomain + 1};
57
58 int32_t domain = nextDomain.fetch_add(1, std::memory_order_relaxed);
59 if (domain > SkTo<int32_t>(UINT16_MAX)) {
60 SK_ABORT("Too many GrUniqueKey Domains");
61 }
62
63 return static_cast<Domain>(domain);
64 }
65
GrResourceKeyHash(const uint32_t * data,size_t size)66 uint32_t GrResourceKeyHash(const uint32_t* data, size_t size) {
67 return SkOpts::hash(data, size);
68 }
69
70 //////////////////////////////////////////////////////////////////////////////
71
72 class GrResourceCache::AutoValidate : ::SkNoncopyable {
73 public:
AutoValidate(GrResourceCache * cache)74 AutoValidate(GrResourceCache* cache) : fCache(cache) { cache->validate(); }
~AutoValidate()75 ~AutoValidate() { fCache->validate(); }
76 private:
77 GrResourceCache* fCache;
78 };
79
80 //////////////////////////////////////////////////////////////////////////////
81
82 inline GrResourceCache::TextureAwaitingUnref::TextureAwaitingUnref() = default;
83
TextureAwaitingUnref(GrTexture * texture)84 inline GrResourceCache::TextureAwaitingUnref::TextureAwaitingUnref(GrTexture* texture)
85 : fTexture(texture), fNumUnrefs(1) {}
86
TextureAwaitingUnref(TextureAwaitingUnref && that)87 inline GrResourceCache::TextureAwaitingUnref::TextureAwaitingUnref(TextureAwaitingUnref&& that) {
88 fTexture = std::exchange(that.fTexture, nullptr);
89 fNumUnrefs = std::exchange(that.fNumUnrefs, 0);
90 }
91
operator =(TextureAwaitingUnref && that)92 inline GrResourceCache::TextureAwaitingUnref& GrResourceCache::TextureAwaitingUnref::operator=(
93 TextureAwaitingUnref&& that) {
94 fTexture = std::exchange(that.fTexture, nullptr);
95 fNumUnrefs = std::exchange(that.fNumUnrefs, 0);
96 return *this;
97 }
98
~TextureAwaitingUnref()99 inline GrResourceCache::TextureAwaitingUnref::~TextureAwaitingUnref() {
100 if (fTexture) {
101 for (int i = 0; i < fNumUnrefs; ++i) {
102 fTexture->unref();
103 }
104 }
105 }
106
addRef()107 inline void GrResourceCache::TextureAwaitingUnref::TextureAwaitingUnref::addRef() { ++fNumUnrefs; }
108
unref()109 inline void GrResourceCache::TextureAwaitingUnref::unref() {
110 SkASSERT(fNumUnrefs > 0);
111 fTexture->unref();
112 --fNumUnrefs;
113 }
114
finished()115 inline bool GrResourceCache::TextureAwaitingUnref::finished() { return !fNumUnrefs; }
116
117 //////////////////////////////////////////////////////////////////////////////
118
GrResourceCache(GrSingleOwner * singleOwner,GrDirectContext::DirectContextID owningContextID,uint32_t familyID)119 GrResourceCache::GrResourceCache(GrSingleOwner* singleOwner,
120 GrDirectContext::DirectContextID owningContextID,
121 uint32_t familyID)
122 : fInvalidUniqueKeyInbox(familyID)
123 , fFreedTextureInbox(owningContextID)
124 , fOwningContextID(owningContextID)
125 , fContextUniqueID(familyID)
126 , fSingleOwner(singleOwner) {
127 SkASSERT(owningContextID.isValid());
128 SkASSERT(familyID != SK_InvalidUniqueID);
129 #ifdef NOT_BUILD_FOR_OHOS_SDK
130 static int overtimeDuration =
131 std::atoi(OHOS::system::GetParameter("persist.sys.graphic.mem.async_free_cache_overtime", "600").c_str());
132 static double maxBytesRate =
133 std::atof(OHOS::system::GetParameter("persist.sys.graphic.mem.async_free_cache_max_rate", "0.9").c_str());
134 #else
135 static int overtimeDuration = 600;
136 static double maxBytesRate = 0.9;
137 #endif
138 fMaxBytesRate = maxBytesRate;
139 fOvertimeDuration = overtimeDuration;
140 }
141
~GrResourceCache()142 GrResourceCache::~GrResourceCache() {
143 this->releaseAll();
144 }
145
setLimit(size_t bytes)146 void GrResourceCache::setLimit(size_t bytes) {
147 fMaxBytes = bytes;
148 this->purgeAsNeeded();
149 }
150
151 #ifdef SKIA_DFX_FOR_OHOS
152 static constexpr int MB = 1024 * 1024;
153
154 #ifdef SKIA_OHOS_FOR_OHOS_TRACE
155 bool GrResourceCache::purgeUnlocakedResTraceEnabled_ =
156 std::atoi((OHOS::system::GetParameter("sys.graphic.skia.cache.debug", "0").c_str())) == 1;
157 #endif
158
dumpInfo(SkString * out)159 void GrResourceCache::dumpInfo(SkString* out) {
160 if (out == nullptr) {
161 SkDebugf("OHOS GrResourceCache::dumpInfo outPtr is nullptr!");
162 return;
163 }
164 auto info = cacheInfo();
165 constexpr uint8_t STEP_INDEX = 1;
166 SkTArray<SkString> lines;
167 SkStrSplit(info.substr(STEP_INDEX, info.length() - STEP_INDEX).c_str(), ";", &lines);
168 for (int i = 0; i < lines.size(); ++i) {
169 out->appendf(" %s\n", lines[i].c_str());
170 }
171 }
172
cacheInfo()173 std::string GrResourceCache::cacheInfo()
174 {
175 auto fPurgeableQueueInfoStr = cacheInfoPurgeableQueue();
176 auto fNonpurgeableResourcesInfoStr = cacheInfoNoPurgeableQueue();
177 size_t fRealAllocBytes = cacheInfoRealAllocSize();
178 auto fRealAllocInfoStr = cacheInfoRealAllocQueue();
179 auto fRealBytesOfPidInfoStr = realBytesOfPid();
180
181 std::ostringstream cacheInfoStream;
182 cacheInfoStream << "[fPurgeableQueueInfoStr.count : " << fPurgeableQueue.count()
183 << "; fNonpurgeableResources.count : " << fNonpurgeableResources.count()
184 << "; fBudgetedBytes : " << fBudgetedBytes
185 << "(" << static_cast<size_t>(fBudgetedBytes / MB)
186 << " MB) / " << fMaxBytes
187 << "(" << static_cast<size_t>(fMaxBytes / MB)
188 << " MB); fBudgetedCount : " << fBudgetedCount
189 << "; fBytes : " << fBytes
190 << "(" << static_cast<size_t>(fBytes / MB)
191 << " MB); fPurgeableBytes : " << fPurgeableBytes
192 << "(" << static_cast<size_t>(fPurgeableBytes / MB)
193 << " MB); fAllocImageBytes : " << fAllocImageBytes
194 << "(" << static_cast<size_t>(fAllocImageBytes / MB)
195 << " MB); fAllocBufferBytes : " << fAllocBufferBytes
196 << "(" << static_cast<size_t>(fAllocBufferBytes / MB)
197 << " MB); fRealAllocBytes : " << fRealAllocBytes
198 << "(" << static_cast<size_t>(fRealAllocBytes / MB)
199 << " MB); fTimestamp : " << fTimestamp
200 << "; " << fPurgeableQueueInfoStr << "; " << fNonpurgeableResourcesInfoStr
201 << "; " << fRealAllocInfoStr << "; " << fRealBytesOfPidInfoStr;
202 return cacheInfoStream.str();
203 }
204
205 #ifdef SKIA_OHOS_FOR_OHOS_TRACE
traceBeforePurgeUnlockRes(const std::string & method,SimpleCacheInfo & simpleCacheInfo)206 void GrResourceCache::traceBeforePurgeUnlockRes(const std::string& method, SimpleCacheInfo& simpleCacheInfo)
207 {
208 if (purgeUnlocakedResTraceEnabled_) {
209 StartTrace(HITRACE_TAG_GRAPHIC_AGP, method + " begin cacheInfo = " + cacheInfo());
210 } else {
211 simpleCacheInfo.fPurgeableQueueCount = fPurgeableQueue.count();
212 simpleCacheInfo.fNonpurgeableResourcesCount = fNonpurgeableResources.count();
213 simpleCacheInfo.fPurgeableBytes = fPurgeableBytes;
214 simpleCacheInfo.fBudgetedCount = fBudgetedCount;
215 simpleCacheInfo.fBudgetedBytes = fBudgetedBytes;
216 simpleCacheInfo.fAllocImageBytes = fAllocImageBytes;
217 simpleCacheInfo.fAllocBufferBytes = fAllocBufferBytes;
218 }
219 }
220
traceAfterPurgeUnlockRes(const std::string & method,const SimpleCacheInfo & simpleCacheInfo)221 void GrResourceCache::traceAfterPurgeUnlockRes(const std::string& method, const SimpleCacheInfo& simpleCacheInfo)
222 {
223 if (purgeUnlocakedResTraceEnabled_) {
224 HITRACE_OHOS_NAME_FMT_ALWAYS("%s end cacheInfo = %s", method.c_str(), cacheInfo().c_str());
225 FinishTrace(HITRACE_TAG_GRAPHIC_AGP);
226 } else {
227 HITRACE_OHOS_NAME_FMT_ALWAYS("%s end cacheInfo = %s",
228 method.c_str(), cacheInfoComparison(simpleCacheInfo).c_str());
229 }
230 }
231
cacheInfoComparison(const SimpleCacheInfo & simpleCacheInfo)232 std::string GrResourceCache::cacheInfoComparison(const SimpleCacheInfo& simpleCacheInfo)
233 {
234 std::ostringstream cacheInfoComparison;
235 cacheInfoComparison << "PurgeableCount : " << simpleCacheInfo.fPurgeableQueueCount
236 << " / " << fPurgeableQueue.count()
237 << "; NonpurgeableCount : " << simpleCacheInfo.fNonpurgeableResourcesCount
238 << " / " << fNonpurgeableResources.count()
239 << "; PurgeableBytes : " << simpleCacheInfo.fPurgeableBytes << " / " << fPurgeableBytes
240 << "; BudgetedCount : " << simpleCacheInfo.fBudgetedCount << " / " << fBudgetedCount
241 << "; BudgetedBytes : " << simpleCacheInfo.fBudgetedBytes << " / " << fBudgetedBytes
242 << "; AllocImageBytes : " << simpleCacheInfo.fAllocImageBytes << " / " << fAllocImageBytes
243 << "; AllocBufferBytes : " << simpleCacheInfo.fAllocBufferBytes << " / " << fAllocBufferBytes;
244 return cacheInfoComparison.str();
245 }
246 #endif // SKIA_OHOS_FOR_OHOS_TRACE
247
cacheInfoPurgeableQueue()248 std::string GrResourceCache::cacheInfoPurgeableQueue()
249 {
250 std::map<uint32_t, int> purgSizeInfoWid;
251 std::map<uint32_t, int> purgCountInfoWid;
252 std::map<uint32_t, std::string> purgNameInfoWid;
253 std::map<uint32_t, int> purgPidInfoWid;
254
255 std::map<uint32_t, int> purgSizeInfoPid;
256 std::map<uint32_t, int> purgCountInfoPid;
257 std::map<uint32_t, std::string> purgNameInfoPid;
258
259 std::map<uint32_t, int> purgSizeInfoFid;
260 std::map<uint32_t, int> purgCountInfoFid;
261 std::map<uint32_t, std::string> purgNameInfoFid;
262
263 int purgCountUnknown = 0;
264 int purgSizeUnknown = 0;
265
266 for (int i = 0; i < fPurgeableQueue.count(); i++) {
267 auto resource = fPurgeableQueue.at(i);
268 auto resourceTag = resource->getResourceTag();
269 if (resourceTag.fWid != 0) {
270 updatePurgeableWidMap(resource, purgNameInfoWid, purgSizeInfoWid, purgPidInfoWid, purgCountInfoWid);
271 } else if (resourceTag.fPid != 0) {
272 updatePurgeablePidMap(resource, purgNameInfoPid, purgSizeInfoPid, purgCountInfoPid);
273 } else if (resourceTag.fFid != 0) {
274 updatePurgeableFidMap(resource, purgNameInfoFid, purgSizeInfoFid, purgCountInfoFid);
275 } else {
276 purgCountUnknown++;
277 purgSizeUnknown += resource->gpuMemorySize();
278 }
279 }
280
281 std::string infoStr;
282 if (purgSizeInfoWid.size() > 0) {
283 infoStr += ";PurgeableInfo_Node:[";
284 updatePurgeableWidInfo(infoStr, purgNameInfoWid, purgSizeInfoWid, purgPidInfoWid, purgCountInfoWid);
285 }
286 if (purgSizeInfoPid.size() > 0) {
287 infoStr += ";PurgeableInfo_Pid:[";
288 updatePurgeablePidInfo(infoStr, purgNameInfoWid, purgSizeInfoWid, purgCountInfoWid);
289 }
290 if (purgSizeInfoFid.size() > 0) {
291 infoStr += ";PurgeableInfo_Fid:[";
292 updatePurgeableFidInfo(infoStr, purgNameInfoFid, purgSizeInfoFid, purgCountInfoFid);
293 }
294 updatePurgeableUnknownInfo(infoStr, ";PurgeableInfo_Unknown:", purgCountUnknown, purgSizeUnknown);
295 return infoStr;
296 }
297
cacheInfoNoPurgeableQueue()298 std::string GrResourceCache::cacheInfoNoPurgeableQueue()
299 {
300 std::map<uint32_t, int> noPurgSizeInfoWid;
301 std::map<uint32_t, int> noPurgCountInfoWid;
302 std::map<uint32_t, std::string> noPurgNameInfoWid;
303 std::map<uint32_t, int> noPurgPidInfoWid;
304
305 std::map<uint32_t, int> noPurgSizeInfoPid;
306 std::map<uint32_t, int> noPurgCountInfoPid;
307 std::map<uint32_t, std::string> noPurgNameInfoPid;
308
309 std::map<uint32_t, int> noPurgSizeInfoFid;
310 std::map<uint32_t, int> noPurgCountInfoFid;
311 std::map<uint32_t, std::string> noPurgNameInfoFid;
312
313 int noPurgCountUnknown = 0;
314 int noPurgSizeUnknown = 0;
315
316 for (int i = 0; i < fNonpurgeableResources.count(); i++) {
317 auto resource = fNonpurgeableResources[i];
318 if (resource == nullptr) {
319 continue;
320 }
321 auto resourceTag = resource->getResourceTag();
322 if (resourceTag.fWid != 0) {
323 updatePurgeableWidMap(resource, noPurgNameInfoWid, noPurgSizeInfoWid, noPurgPidInfoWid, noPurgCountInfoWid);
324 } else if (resourceTag.fPid != 0) {
325 updatePurgeablePidMap(resource, noPurgNameInfoPid, noPurgSizeInfoPid, noPurgCountInfoPid);
326 } else if (resourceTag.fFid != 0) {
327 updatePurgeableFidMap(resource, noPurgNameInfoFid, noPurgSizeInfoFid, noPurgCountInfoFid);
328 } else {
329 noPurgCountUnknown++;
330 noPurgSizeUnknown += resource->gpuMemorySize();
331 }
332 }
333
334 std::string infoStr;
335 if (noPurgSizeInfoWid.size() > 0) {
336 infoStr += ";NonPurgeableInfo_Node:[";
337 updatePurgeableWidInfo(infoStr, noPurgNameInfoWid, noPurgSizeInfoWid, noPurgPidInfoWid, noPurgCountInfoWid);
338 }
339 if (noPurgSizeInfoPid.size() > 0) {
340 infoStr += ";NonPurgeableInfo_Pid:[";
341 updatePurgeablePidInfo(infoStr, noPurgNameInfoPid, noPurgSizeInfoPid, noPurgCountInfoPid);
342 }
343 if (noPurgSizeInfoFid.size() > 0) {
344 infoStr += ";NonPurgeableInfo_Fid:[";
345 updatePurgeableFidInfo(infoStr, noPurgNameInfoFid, noPurgSizeInfoFid, noPurgCountInfoFid);
346 }
347 updatePurgeableUnknownInfo(infoStr, ";NonPurgeableInfo_Unknown:", noPurgCountUnknown, noPurgSizeUnknown);
348 return infoStr;
349 }
350
cacheInfoRealAllocSize()351 size_t GrResourceCache::cacheInfoRealAllocSize()
352 {
353 size_t realAllocImageSize = 0;
354 for (int i = 0; i < fPurgeableQueue.count(); i++) {
355 auto resource = fPurgeableQueue.at(i);
356 if (resource == nullptr || !resource->isRealAlloc()) {
357 continue;
358 }
359 realAllocImageSize += resource->getRealAllocSize();
360 }
361 for (int i = 0; i < fNonpurgeableResources.count(); i++) {
362 auto resource = fNonpurgeableResources[i];
363 if (resource == nullptr || !resource->isRealAlloc()) {
364 continue;
365 }
366 realAllocImageSize += resource->getRealAllocSize();
367 }
368 return realAllocImageSize;
369 }
370
cacheInfoRealAllocQueue()371 std::string GrResourceCache::cacheInfoRealAllocQueue()
372 {
373 std::map<uint32_t, std::string> realAllocNameInfoWid;
374 std::map<uint32_t, int> realAllocSizeInfoWid;
375 std::map<uint32_t, int> realAllocPidInfoWid;
376 std::map<uint32_t, int> realAllocCountInfoWid;
377
378 std::map<uint32_t, std::string> realAllocNameInfoPid;
379 std::map<uint32_t, int> realAllocSizeInfoPid;
380 std::map<uint32_t, int> realAllocCountInfoPid;
381
382 std::map<uint32_t, std::string> realAllocNameInfoFid;
383 std::map<uint32_t, int> realAllocSizeInfoFid;
384 std::map<uint32_t, int> realAllocCountInfoFid;
385
386 int realAllocCountUnknown = 0;
387 int realAllocSizeUnknown = 0;
388
389 for (int i = 0; i < fNonpurgeableResources.count(); i++) {
390 auto resource = fNonpurgeableResources[i];
391 if (resource == nullptr || !resource->isRealAlloc()) {
392 continue;
393 }
394 auto resourceTag = resource->getResourceTag();
395 if (resourceTag.fWid != 0) {
396 updateRealAllocWidMap(
397 resource, realAllocNameInfoWid, realAllocSizeInfoWid, realAllocPidInfoWid, realAllocCountInfoWid);
398 } else if (resourceTag.fPid != 0) {
399 updateRealAllocPidMap(resource, realAllocNameInfoPid, realAllocSizeInfoPid, realAllocCountInfoPid);
400 } else if (resourceTag.fFid != 0) {
401 updateRealAllocFidMap(resource, realAllocNameInfoFid, realAllocSizeInfoFid, realAllocCountInfoFid);
402 } else {
403 realAllocCountUnknown++;
404 realAllocSizeUnknown += resource->getRealAllocSize();
405 }
406 }
407
408 for (int i = 0; i < fPurgeableQueue.count(); i++) {
409 auto resource = fPurgeableQueue.at(i);
410 if (resource == nullptr || !resource->isRealAlloc()) {
411 continue;
412 }
413 auto resourceTag = resource->getResourceTag();
414 if (resourceTag.fWid != 0) {
415 updateRealAllocWidMap(
416 resource, realAllocNameInfoWid, realAllocSizeInfoWid, realAllocPidInfoWid, realAllocCountInfoWid);
417 } else if (resourceTag.fPid != 0) {
418 updateRealAllocPidMap(resource, realAllocNameInfoPid, realAllocSizeInfoPid, realAllocCountInfoPid);
419 } else if (resourceTag.fFid != 0) {
420 updateRealAllocFidMap(resource, realAllocNameInfoFid, realAllocSizeInfoFid, realAllocCountInfoFid);
421 } else {
422 realAllocCountUnknown++;
423 realAllocSizeUnknown += resource->getRealAllocSize();
424 }
425 }
426
427 std::string infoStr;
428 if (realAllocSizeInfoWid.size() > 0) {
429 infoStr += ";RealAllocInfo_Node:[";
430 updatePurgeableWidInfo(
431 infoStr, realAllocNameInfoWid, realAllocSizeInfoWid, realAllocPidInfoWid, realAllocCountInfoWid);
432 }
433 if (realAllocSizeInfoPid.size() > 0) {
434 infoStr += ";RealAllocInfo_Pid:[";
435 updatePurgeablePidInfo(infoStr, realAllocNameInfoPid, realAllocSizeInfoPid, realAllocCountInfoPid);
436 }
437 if (realAllocSizeInfoFid.size() > 0) {
438 infoStr += ";RealAllocInfo_Fid:[";
439 updatePurgeableFidInfo(infoStr, realAllocNameInfoFid, realAllocSizeInfoFid, realAllocCountInfoFid);
440 }
441 updatePurgeableUnknownInfo(infoStr, ";RealAllocInfo_Unknown:", realAllocCountUnknown, realAllocSizeUnknown);
442 return infoStr;
443 }
444
realBytesOfPid()445 std::string GrResourceCache::realBytesOfPid()
446 {
447 std::string infoStr;
448 infoStr += ";fBytesOfPid : [";
449 if (fBytesOfPid.size() > 0) {
450 for (auto it = fBytesOfPid.begin(); it != fBytesOfPid.end(); it++) {
451 infoStr += std::to_string(it->first) + ":" + std::to_string(it->second) + ", ";
452 }
453 }
454 infoStr += "]";
455 return infoStr;
456 }
457
updatePurgeableWidMap(GrGpuResource * resource,std::map<uint32_t,std::string> & nameInfoWid,std::map<uint32_t,int> & sizeInfoWid,std::map<uint32_t,int> & pidInfoWid,std::map<uint32_t,int> & countInfoWid)458 void GrResourceCache::updatePurgeableWidMap(GrGpuResource* resource,
459 std::map<uint32_t, std::string>& nameInfoWid,
460 std::map<uint32_t, int>& sizeInfoWid,
461 std::map<uint32_t, int>& pidInfoWid,
462 std::map<uint32_t, int>& countInfoWid)
463 {
464 auto resourceTag = resource->getResourceTag();
465 auto it = sizeInfoWid.find(resourceTag.fWid);
466 if (it != sizeInfoWid.end()) {
467 sizeInfoWid[resourceTag.fWid] = it->second + resource->gpuMemorySize();
468 countInfoWid[resourceTag.fWid]++;
469 } else {
470 sizeInfoWid[resourceTag.fWid] = resource->gpuMemorySize();
471 nameInfoWid[resourceTag.fWid] = resourceTag.fName;
472 pidInfoWid[resourceTag.fWid] = resourceTag.fPid;
473 countInfoWid[resourceTag.fWid] = 1;
474 }
475 }
476
updatePurgeablePidMap(GrGpuResource * resource,std::map<uint32_t,std::string> & nameInfoPid,std::map<uint32_t,int> & sizeInfoPid,std::map<uint32_t,int> & countInfoPid)477 void GrResourceCache::updatePurgeablePidMap(GrGpuResource* resource,
478 std::map<uint32_t, std::string>& nameInfoPid,
479 std::map<uint32_t, int>& sizeInfoPid,
480 std::map<uint32_t, int>& countInfoPid)
481 {
482 auto resourceTag = resource->getResourceTag();
483 auto it = sizeInfoPid.find(resourceTag.fPid);
484 if (it != sizeInfoPid.end()) {
485 sizeInfoPid[resourceTag.fPid] = it->second + resource->gpuMemorySize();
486 countInfoPid[resourceTag.fPid]++;
487 } else {
488 sizeInfoPid[resourceTag.fPid] = resource->gpuMemorySize();
489 nameInfoPid[resourceTag.fPid] = resourceTag.fName;
490 countInfoPid[resourceTag.fPid] = 1;
491 }
492 }
493
updatePurgeableFidMap(GrGpuResource * resource,std::map<uint32_t,std::string> & nameInfoFid,std::map<uint32_t,int> & sizeInfoFid,std::map<uint32_t,int> & countInfoFid)494 void GrResourceCache::updatePurgeableFidMap(GrGpuResource* resource,
495 std::map<uint32_t, std::string>& nameInfoFid,
496 std::map<uint32_t, int>& sizeInfoFid,
497 std::map<uint32_t, int>& countInfoFid)
498 {
499 auto resourceTag = resource->getResourceTag();
500 auto it = sizeInfoFid.find(resourceTag.fFid);
501 if (it != sizeInfoFid.end()) {
502 sizeInfoFid[resourceTag.fFid] = it->second + resource->gpuMemorySize();
503 countInfoFid[resourceTag.fFid]++;
504 } else {
505 sizeInfoFid[resourceTag.fFid] = resource->gpuMemorySize();
506 nameInfoFid[resourceTag.fFid] = resourceTag.fName;
507 countInfoFid[resourceTag.fFid] = 1;
508 }
509 }
510
updateRealAllocWidMap(GrGpuResource * resource,std::map<uint32_t,std::string> & nameInfoWid,std::map<uint32_t,int> & sizeInfoWid,std::map<uint32_t,int> & pidInfoWid,std::map<uint32_t,int> & countInfoWid)511 void GrResourceCache::updateRealAllocWidMap(GrGpuResource* resource,
512 std::map<uint32_t, std::string>& nameInfoWid,
513 std::map<uint32_t, int>& sizeInfoWid,
514 std::map<uint32_t, int>& pidInfoWid,
515 std::map<uint32_t, int>& countInfoWid)
516 {
517 size_t size = resource->getRealAllocSize();
518 auto resourceTag = resource->getResourceTag();
519 auto it = sizeInfoWid.find(resourceTag.fWid);
520 if (it != sizeInfoWid.end()) {
521 sizeInfoWid[resourceTag.fWid] = it->second + size;
522 countInfoWid[resourceTag.fWid]++;
523 } else {
524 sizeInfoWid[resourceTag.fWid] = size;
525 nameInfoWid[resourceTag.fWid] = resourceTag.fName;
526 pidInfoWid[resourceTag.fWid] = resourceTag.fPid;
527 countInfoWid[resourceTag.fWid] = 1;
528 }
529 }
530
updateRealAllocPidMap(GrGpuResource * resource,std::map<uint32_t,std::string> & nameInfoPid,std::map<uint32_t,int> & sizeInfoPid,std::map<uint32_t,int> & countInfoPid)531 void GrResourceCache::updateRealAllocPidMap(GrGpuResource* resource,
532 std::map<uint32_t, std::string>& nameInfoPid,
533 std::map<uint32_t, int>& sizeInfoPid,
534 std::map<uint32_t, int>& countInfoPid)
535 {
536 size_t size = resource->getRealAllocSize();
537 auto resourceTag = resource->getResourceTag();
538 auto it = sizeInfoPid.find(resourceTag.fPid);
539 if (it != sizeInfoPid.end()) {
540 sizeInfoPid[resourceTag.fPid] = it->second + size;
541 countInfoPid[resourceTag.fPid]++;
542 } else {
543 sizeInfoPid[resourceTag.fPid] = size;
544 nameInfoPid[resourceTag.fPid] = resourceTag.fName;
545 countInfoPid[resourceTag.fPid] = 1;
546 }
547 }
548
updateRealAllocFidMap(GrGpuResource * resource,std::map<uint32_t,std::string> & nameInfoFid,std::map<uint32_t,int> & sizeInfoFid,std::map<uint32_t,int> & countInfoFid)549 void GrResourceCache::updateRealAllocFidMap(GrGpuResource* resource,
550 std::map<uint32_t, std::string>& nameInfoFid,
551 std::map<uint32_t, int>& sizeInfoFid,
552 std::map<uint32_t, int>& countInfoFid)
553 {
554 size_t size = resource->getRealAllocSize();
555 auto resourceTag = resource->getResourceTag();
556 auto it = sizeInfoFid.find(resourceTag.fFid);
557 if (it != sizeInfoFid.end()) {
558 sizeInfoFid[resourceTag.fFid] = it->second + size;
559 countInfoFid[resourceTag.fFid]++;
560 } else {
561 sizeInfoFid[resourceTag.fFid] = size;
562 nameInfoFid[resourceTag.fFid] = resourceTag.fName;
563 countInfoFid[resourceTag.fFid] = 1;
564 }
565 }
566
updatePurgeableWidInfo(std::string & infoStr,std::map<uint32_t,std::string> & nameInfoWid,std::map<uint32_t,int> & sizeInfoWid,std::map<uint32_t,int> & pidInfoWid,std::map<uint32_t,int> & countInfoWid)567 void GrResourceCache::updatePurgeableWidInfo(std::string& infoStr,
568 std::map<uint32_t, std::string>& nameInfoWid,
569 std::map<uint32_t, int>& sizeInfoWid,
570 std::map<uint32_t, int>& pidInfoWid,
571 std::map<uint32_t, int>& countInfoWid)
572 {
573 for (auto it = sizeInfoWid.begin(); it != sizeInfoWid.end(); it++) {
574 infoStr += "[" + nameInfoWid[it->first] +
575 ",pid=" + std::to_string(pidInfoWid[it->first]) +
576 ",NodeId=" + std::to_string(it->first & 0xFFFFFFFF) +
577 ",count=" + std::to_string(countInfoWid[it->first]) +
578 ",size=" + std::to_string(it->second) +
579 "(" + std::to_string(it->second / MB) + " MB)],";
580 }
581 infoStr += ']';
582 }
583
updatePurgeablePidInfo(std::string & infoStr,std::map<uint32_t,std::string> & nameInfoPid,std::map<uint32_t,int> & sizeInfoPid,std::map<uint32_t,int> & countInfoPid)584 void GrResourceCache::updatePurgeablePidInfo(std::string& infoStr,
585 std::map<uint32_t, std::string>& nameInfoPid,
586 std::map<uint32_t, int>& sizeInfoPid,
587 std::map<uint32_t, int>& countInfoPid)
588 {
589 for (auto it = sizeInfoPid.begin(); it != sizeInfoPid.end(); it++) {
590 infoStr += "[" + nameInfoPid[it->first] +
591 ",pid=" + std::to_string(it->first) +
592 ",count=" + std::to_string(countInfoPid[it->first]) +
593 ",size=" + std::to_string(it->second) +
594 "(" + std::to_string(it->second / MB) + " MB)],";
595 }
596 infoStr += ']';
597 }
598
updatePurgeableFidInfo(std::string & infoStr,std::map<uint32_t,std::string> & nameInfoFid,std::map<uint32_t,int> & sizeInfoFid,std::map<uint32_t,int> & countInfoFid)599 void GrResourceCache::updatePurgeableFidInfo(std::string& infoStr,
600 std::map<uint32_t, std::string>& nameInfoFid,
601 std::map<uint32_t, int>& sizeInfoFid,
602 std::map<uint32_t, int>& countInfoFid)
603 {
604 for (auto it = sizeInfoFid.begin(); it != sizeInfoFid.end(); it++) {
605 infoStr += "[" + nameInfoFid[it->first] +
606 ",typeid=" + std::to_string(it->first) +
607 ",count=" + std::to_string(countInfoFid[it->first]) +
608 ",size=" + std::to_string(it->second) +
609 "(" + std::to_string(it->second / MB) + " MB)],";
610 }
611 infoStr += ']';
612 }
613
updatePurgeableUnknownInfo(std::string & infoStr,const std::string & unknownPrefix,const int countUnknown,const int sizeUnknown)614 void GrResourceCache::updatePurgeableUnknownInfo(
615 std::string& infoStr, const std::string& unknownPrefix, const int countUnknown, const int sizeUnknown)
616 {
617 if (countUnknown > 0) {
618 infoStr += unknownPrefix +
619 "[count=" + std::to_string(countUnknown) +
620 ",size=" + std::to_string(sizeUnknown) +
621 "(" + std::to_string(sizeUnknown / MB) + "MB)]";
622 }
623 }
624 #endif
625
insertResource(GrGpuResource * resource)626 void GrResourceCache::insertResource(GrGpuResource* resource)
627 {
628 ASSERT_SINGLE_OWNER
629 SkASSERT(resource);
630 SkASSERT(!this->isInCache(resource));
631 SkASSERT(!resource->wasDestroyed());
632 SkASSERT(!resource->resourcePriv().isPurgeable());
633
634 // We must set the timestamp before adding to the array in case the timestamp wraps and we wind
635 // up iterating over all the resources that already have timestamps.
636 resource->cacheAccess().setTimestamp(this->getNextTimestamp());
637
638 this->addToNonpurgeableArray(resource);
639
640 size_t size = resource->gpuMemorySize();
641 SkDEBUGCODE(++fCount;)
642 fBytes += size;
643
644 // OH ISSUE: memory count
645 auto pid = resource->getResourceTag().fPid;
646 if (pid && resource->isRealAlloc()) {
647 auto& pidSize = fBytesOfPid[pid];
648 pidSize += size;
649 fUpdatedBytesOfPid[pid] = pidSize;
650 if (pidSize >= fMemoryControl_ && fExitedPid_.find(pid) == fExitedPid_.end() && fMemoryOverflowCallback_) {
651 fMemoryOverflowCallback_(pid, pidSize, true);
652 fExitedPid_.insert(pid);
653 SkDebugf("OHOS resource overflow! pid[%{public}d], size[%{public}zu]", pid, pidSize);
654 #ifdef SKIA_OHOS_FOR_OHOS_TRACE
655 HITRACE_METER_FMT(HITRACE_TAG_GRAPHIC_AGP, "OHOS gpu resource overflow: pid(%d), size:(%zu)",
656 pid, pidSize);
657 #endif
658 }
659 }
660
661 #if GR_CACHE_STATS
662 fHighWaterCount = std::max(this->getResourceCount(), fHighWaterCount);
663 fHighWaterBytes = std::max(fBytes, fHighWaterBytes);
664 #endif
665 if (GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType()) {
666 ++fBudgetedCount;
667 fBudgetedBytes += size;
668 TRACE_COUNTER2("skia.gpu.cache", "skia budget", "used",
669 fBudgetedBytes, "free", fMaxBytes - fBudgetedBytes);
670 #if GR_CACHE_STATS
671 fBudgetedHighWaterCount = std::max(fBudgetedCount, fBudgetedHighWaterCount);
672 fBudgetedHighWaterBytes = std::max(fBudgetedBytes, fBudgetedHighWaterBytes);
673 #endif
674 }
675 SkASSERT(!resource->cacheAccess().isUsableAsScratch());
676 #ifdef SKIA_OHOS_FOR_OHOS_TRACE
677 if (fBudgetedBytes >= fMaxBytes) {
678 HITRACE_OHOS_NAME_FMT_ALWAYS("cache over fBudgetedBytes:(%u),fMaxBytes:(%u)", fBudgetedBytes, fMaxBytes);
679 #ifdef SKIA_DFX_FOR_OHOS
680 SimpleCacheInfo simpleCacheInfo;
681 traceBeforePurgeUnlockRes("insertResource", simpleCacheInfo);
682 #endif
683 this->purgeAsNeeded();
684 #ifdef SKIA_DFX_FOR_OHOS
685 traceAfterPurgeUnlockRes("insertResource", simpleCacheInfo);
686 #endif
687 } else {
688 this->purgeAsNeeded();
689 }
690 #else
691 this->purgeAsNeeded();
692 #endif
693 }
694
removeResource(GrGpuResource * resource)695 void GrResourceCache::removeResource(GrGpuResource* resource) {
696 ASSERT_SINGLE_OWNER
697 this->validate();
698 SkASSERT(this->isInCache(resource));
699
700 size_t size = resource->gpuMemorySize();
701 if (resource->resourcePriv().isPurgeable()) {
702 fPurgeableQueue.remove(resource);
703 fPurgeableBytes -= size;
704 } else {
705 this->removeFromNonpurgeableArray(resource);
706 }
707
708 SkDEBUGCODE(--fCount;)
709 fBytes -= size;
710
711 // OH ISSUE: memory count
712 auto pid = resource->getResourceTag().fPid;
713 if (pid && resource->isRealAlloc()) {
714 auto& pidSize = fBytesOfPid[pid];
715 pidSize -= size;
716 fUpdatedBytesOfPid[pid] = pidSize;
717 if (pidSize == 0) {
718 fBytesOfPid.erase(pid);
719 }
720 }
721
722 if (GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType()) {
723 --fBudgetedCount;
724 fBudgetedBytes -= size;
725 TRACE_COUNTER2("skia.gpu.cache", "skia budget", "used",
726 fBudgetedBytes, "free", fMaxBytes - fBudgetedBytes);
727 }
728
729 if (resource->cacheAccess().isUsableAsScratch()) {
730 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
731 }
732 if (resource->getUniqueKey().isValid()) {
733 fUniqueHash.remove(resource->getUniqueKey());
734 }
735 this->validate();
736 }
737
abandonAll()738 void GrResourceCache::abandonAll() {
739 AutoValidate av(this);
740
741 // We need to make sure to free any resources that were waiting on a free message but never
742 // received one.
743 fTexturesAwaitingUnref.reset();
744
745 while (fNonpurgeableResources.count()) {
746 GrGpuResource* back = *(fNonpurgeableResources.end() - 1);
747 SkASSERT(!back->wasDestroyed());
748 back->cacheAccess().abandon();
749 }
750
751 while (fPurgeableQueue.count()) {
752 GrGpuResource* top = fPurgeableQueue.peek();
753 SkASSERT(!top->wasDestroyed());
754 top->cacheAccess().abandon();
755 }
756
757 fThreadSafeCache->dropAllRefs();
758
759 SkASSERT(!fScratchMap.count());
760 SkASSERT(!fUniqueHash.count());
761 SkASSERT(!fCount);
762 SkASSERT(!this->getResourceCount());
763 SkASSERT(!fBytes);
764 SkASSERT(!fBudgetedCount);
765 SkASSERT(!fBudgetedBytes);
766 SkASSERT(!fPurgeableBytes);
767 SkASSERT(!fTexturesAwaitingUnref.count());
768 }
769
releaseAll()770 void GrResourceCache::releaseAll() {
771 AutoValidate av(this);
772
773 fThreadSafeCache->dropAllRefs();
774
775 this->processFreedGpuResources();
776
777 // We need to make sure to free any resources that were waiting on a free message but never
778 // received one.
779 fTexturesAwaitingUnref.reset();
780
781 SkASSERT(fProxyProvider); // better have called setProxyProvider
782 SkASSERT(fThreadSafeCache); // better have called setThreadSafeCache too
783
784 // We must remove the uniqueKeys from the proxies here. While they possess a uniqueKey
785 // they also have a raw pointer back to this class (which is presumably going away)!
786 fProxyProvider->removeAllUniqueKeys();
787
788 while (fNonpurgeableResources.count()) {
789 GrGpuResource* back = *(fNonpurgeableResources.end() - 1);
790 SkASSERT(!back->wasDestroyed());
791 back->cacheAccess().release();
792 }
793
794 while (fPurgeableQueue.count()) {
795 GrGpuResource* top = fPurgeableQueue.peek();
796 SkASSERT(!top->wasDestroyed());
797 top->cacheAccess().release();
798 }
799
800 SkASSERT(!fScratchMap.count());
801 SkASSERT(!fUniqueHash.count());
802 SkASSERT(!fCount);
803 SkASSERT(!this->getResourceCount());
804 SkASSERT(!fBytes);
805 SkASSERT(!fBudgetedCount);
806 SkASSERT(!fBudgetedBytes);
807 SkASSERT(!fPurgeableBytes);
808 SkASSERT(!fTexturesAwaitingUnref.count());
809 }
810
releaseByTag(const GrGpuResourceTag & tag)811 void GrResourceCache::releaseByTag(const GrGpuResourceTag& tag) {
812 AutoValidate av(this);
813 this->processFreedGpuResources();
814 SkASSERT(fProxyProvider); // better have called setProxyProvider
815 std::vector<GrGpuResource*> recycleVector;
816 for (int i = 0; i < fNonpurgeableResources.count(); i++) {
817 GrGpuResource* resource = fNonpurgeableResources[i];
818 if (tag.filter(resource->getResourceTag())) {
819 recycleVector.emplace_back(resource);
820 if (resource->getUniqueKey().isValid()) {
821 fProxyProvider->processInvalidUniqueKey(resource->getUniqueKey(), nullptr,
822 GrProxyProvider::InvalidateGPUResource::kNo);
823 }
824 }
825 }
826
827 for (int i = 0; i < fPurgeableQueue.count(); i++) {
828 GrGpuResource* resource = fPurgeableQueue.at(i);
829 if (tag.filter(resource->getResourceTag())) {
830 recycleVector.emplace_back(resource);
831 if (resource->getUniqueKey().isValid()) {
832 fProxyProvider->processInvalidUniqueKey(resource->getUniqueKey(), nullptr,
833 GrProxyProvider::InvalidateGPUResource::kNo);
834 }
835 }
836 }
837
838 for (auto resource : recycleVector) {
839 SkASSERT(!resource->wasDestroyed());
840 resource->cacheAccess().release();
841 }
842 }
843
setCurrentGrResourceTag(const GrGpuResourceTag & tag)844 void GrResourceCache::setCurrentGrResourceTag(const GrGpuResourceTag& tag) {
845 if (tag.isGrTagValid()) {
846 grResourceTagCacheStack.push(tag);
847 return;
848 }
849 if (!grResourceTagCacheStack.empty()) {
850 grResourceTagCacheStack.pop();
851 }
852 }
853
popGrResourceTag()854 void GrResourceCache::popGrResourceTag()
855 {
856 if (!grResourceTagCacheStack.empty()) {
857 grResourceTagCacheStack.pop();
858 }
859 }
860
getCurrentGrResourceTag() const861 GrGpuResourceTag GrResourceCache::getCurrentGrResourceTag() const {
862 if (grResourceTagCacheStack.empty()) {
863 return{};
864 }
865 return grResourceTagCacheStack.top();
866 }
867
getAllGrGpuResourceTags() const868 std::set<GrGpuResourceTag> GrResourceCache::getAllGrGpuResourceTags() const {
869 std::set<GrGpuResourceTag> result;
870 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
871 auto tag = fNonpurgeableResources[i]->getResourceTag();
872 result.insert(tag);
873 }
874 return result;
875 }
876
877 // OH ISSUE: get the memory information of the updated pid.
getUpdatedMemoryMap(std::unordered_map<int32_t,size_t> & out)878 void GrResourceCache::getUpdatedMemoryMap(std::unordered_map<int32_t, size_t> &out)
879 {
880 fUpdatedBytesOfPid.swap(out);
881 }
882
883 // OH ISSUE: init gpu memory limit.
initGpuMemoryLimit(MemoryOverflowCalllback callback,uint64_t size)884 void GrResourceCache::initGpuMemoryLimit(MemoryOverflowCalllback callback, uint64_t size)
885 {
886 if (fMemoryOverflowCallback_ == nullptr) {
887 fMemoryOverflowCallback_ = callback;
888 fMemoryControl_ = size;
889 }
890 }
891
892 // OH ISSUE: check whether the PID is abnormal.
isPidAbnormal() const893 bool GrResourceCache::isPidAbnormal() const
894 {
895 return fExitedPid_.find(getCurrentGrResourceTag().fPid) != fExitedPid_.end();
896 }
897
898 // OH ISSUE: change the fbyte when the resource tag changes.
changeByteOfPid(int32_t beforePid,int32_t afterPid,size_t bytes)899 void GrResourceCache::changeByteOfPid(int32_t beforePid, int32_t afterPid, size_t bytes)
900 {
901 if (beforePid) {
902 auto& pidSize = fBytesOfPid[beforePid];
903 pidSize -= bytes;
904 fUpdatedBytesOfPid[beforePid] = pidSize;
905 if (pidSize == 0) {
906 fBytesOfPid.erase(beforePid);
907 }
908 }
909 if (afterPid) {
910 auto& size = fBytesOfPid[afterPid];
911 size += bytes;
912 fUpdatedBytesOfPid[afterPid] = size;
913 }
914 }
915
refResource(GrGpuResource * resource)916 void GrResourceCache::refResource(GrGpuResource* resource) {
917 SkASSERT(resource);
918 SkASSERT(resource->getContext()->priv().getResourceCache() == this);
919 if (resource->cacheAccess().hasRef()) {
920 resource->ref();
921 } else {
922 this->refAndMakeResourceMRU(resource);
923 }
924 this->validate();
925 }
926
927 class GrResourceCache::AvailableForScratchUse {
928 public:
AvailableForScratchUse()929 AvailableForScratchUse() { }
930
operator ()(const GrGpuResource * resource) const931 bool operator()(const GrGpuResource* resource) const {
932 // Everything that is in the scratch map should be usable as a
933 // scratch resource.
934 return true;
935 }
936 };
937
findAndRefScratchResource(const GrScratchKey & scratchKey)938 GrGpuResource* GrResourceCache::findAndRefScratchResource(const GrScratchKey& scratchKey) {
939 SkASSERT(scratchKey.isValid());
940
941 GrGpuResource* resource = fScratchMap.find(scratchKey, AvailableForScratchUse());
942 if (resource) {
943 fScratchMap.remove(scratchKey, resource);
944 this->refAndMakeResourceMRU(resource);
945 this->validate();
946 }
947 return resource;
948 }
949
willRemoveScratchKey(const GrGpuResource * resource)950 void GrResourceCache::willRemoveScratchKey(const GrGpuResource* resource) {
951 ASSERT_SINGLE_OWNER
952 SkASSERT(resource->resourcePriv().getScratchKey().isValid());
953 if (resource->cacheAccess().isUsableAsScratch()) {
954 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
955 }
956 }
957
removeUniqueKey(GrGpuResource * resource)958 void GrResourceCache::removeUniqueKey(GrGpuResource* resource) {
959 ASSERT_SINGLE_OWNER
960 // Someone has a ref to this resource in order to have removed the key. When the ref count
961 // reaches zero we will get a ref cnt notification and figure out what to do with it.
962 if (resource->getUniqueKey().isValid()) {
963 SkASSERT(resource == fUniqueHash.find(resource->getUniqueKey()));
964 fUniqueHash.remove(resource->getUniqueKey());
965 }
966 resource->cacheAccess().removeUniqueKey();
967 if (resource->cacheAccess().isUsableAsScratch()) {
968 fScratchMap.insert(resource->resourcePriv().getScratchKey(), resource);
969 }
970
971 // Removing a unique key from a kUnbudgetedCacheable resource would make the resource
972 // require purging. However, the resource must be ref'ed to get here and therefore can't
973 // be purgeable. We'll purge it when the refs reach zero.
974 SkASSERT(!resource->resourcePriv().isPurgeable());
975 this->validate();
976 }
977
changeUniqueKey(GrGpuResource * resource,const GrUniqueKey & newKey)978 void GrResourceCache::changeUniqueKey(GrGpuResource* resource, const GrUniqueKey& newKey) {
979 ASSERT_SINGLE_OWNER
980 SkASSERT(resource);
981 SkASSERT(this->isInCache(resource));
982
983 // If another resource has the new key, remove its key then install the key on this resource.
984 if (newKey.isValid()) {
985 if (GrGpuResource* old = fUniqueHash.find(newKey)) {
986 // If the old resource using the key is purgeable and is unreachable, then remove it.
987 if (!old->resourcePriv().getScratchKey().isValid() &&
988 old->resourcePriv().isPurgeable()) {
989 old->cacheAccess().release();
990 } else {
991 // removeUniqueKey expects an external owner of the resource.
992 this->removeUniqueKey(sk_ref_sp(old).get());
993 }
994 }
995 SkASSERT(nullptr == fUniqueHash.find(newKey));
996
997 // Remove the entry for this resource if it already has a unique key.
998 if (resource->getUniqueKey().isValid()) {
999 SkASSERT(resource == fUniqueHash.find(resource->getUniqueKey()));
1000 fUniqueHash.remove(resource->getUniqueKey());
1001 SkASSERT(nullptr == fUniqueHash.find(resource->getUniqueKey()));
1002 } else {
1003 // 'resource' didn't have a valid unique key before so it is switching sides. Remove it
1004 // from the ScratchMap. The isUsableAsScratch call depends on us not adding the new
1005 // unique key until after this check.
1006 if (resource->cacheAccess().isUsableAsScratch()) {
1007 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
1008 }
1009 }
1010
1011 resource->cacheAccess().setUniqueKey(newKey);
1012 fUniqueHash.add(resource);
1013 } else {
1014 this->removeUniqueKey(resource);
1015 }
1016
1017 this->validate();
1018 }
1019
refAndMakeResourceMRU(GrGpuResource * resource)1020 void GrResourceCache::refAndMakeResourceMRU(GrGpuResource* resource) {
1021 ASSERT_SINGLE_OWNER
1022 SkASSERT(resource);
1023 SkASSERT(this->isInCache(resource));
1024
1025 if (resource->resourcePriv().isPurgeable()) {
1026 // It's about to become unpurgeable.
1027 fPurgeableBytes -= resource->gpuMemorySize();
1028 fPurgeableQueue.remove(resource);
1029 this->addToNonpurgeableArray(resource);
1030 } else if (!resource->cacheAccess().hasRefOrCommandBufferUsage() &&
1031 resource->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted) {
1032 SkASSERT(fNumBudgetedResourcesFlushWillMakePurgeable > 0);
1033 fNumBudgetedResourcesFlushWillMakePurgeable--;
1034 }
1035 resource->cacheAccess().ref();
1036
1037 resource->cacheAccess().setTimestamp(this->getNextTimestamp());
1038 this->validate();
1039 }
1040
notifyARefCntReachedZero(GrGpuResource * resource,GrGpuResource::LastRemovedRef removedRef)1041 void GrResourceCache::notifyARefCntReachedZero(GrGpuResource* resource,
1042 GrGpuResource::LastRemovedRef removedRef) {
1043 ASSERT_SINGLE_OWNER
1044 SkASSERT(resource);
1045 SkASSERT(!resource->wasDestroyed());
1046 SkASSERT(this->isInCache(resource));
1047 // This resource should always be in the nonpurgeable array when this function is called. It
1048 // will be moved to the queue if it is newly purgeable.
1049 SkASSERT(fNonpurgeableResources[*resource->cacheAccess().accessCacheIndex()] == resource);
1050
1051 if (removedRef == GrGpuResource::LastRemovedRef::kMainRef) {
1052 if (resource->cacheAccess().isUsableAsScratch()) {
1053 fScratchMap.insert(resource->resourcePriv().getScratchKey(), resource);
1054 }
1055 }
1056
1057 if (resource->cacheAccess().hasRefOrCommandBufferUsage()) {
1058 this->validate();
1059 return;
1060 }
1061
1062 #ifdef SK_DEBUG
1063 // When the timestamp overflows validate() is called. validate() checks that resources in
1064 // the nonpurgeable array are indeed not purgeable. However, the movement from the array to
1065 // the purgeable queue happens just below in this function. So we mark it as an exception.
1066 if (resource->resourcePriv().isPurgeable()) {
1067 fNewlyPurgeableResourceForValidation = resource;
1068 }
1069 #endif
1070 resource->cacheAccess().setTimestamp(this->getNextTimestamp());
1071 SkDEBUGCODE(fNewlyPurgeableResourceForValidation = nullptr);
1072
1073 if (!resource->resourcePriv().isPurgeable() &&
1074 resource->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted) {
1075 ++fNumBudgetedResourcesFlushWillMakePurgeable;
1076 }
1077
1078 if (!resource->resourcePriv().isPurgeable()) {
1079 this->validate();
1080 return;
1081 }
1082
1083 this->removeFromNonpurgeableArray(resource);
1084 fPurgeableQueue.insert(resource);
1085 resource->cacheAccess().setTimeWhenResourceBecomePurgeable();
1086 fPurgeableBytes += resource->gpuMemorySize();
1087
1088 bool hasUniqueKey = resource->getUniqueKey().isValid();
1089
1090 GrBudgetedType budgetedType = resource->resourcePriv().budgetedType();
1091
1092 if (budgetedType == GrBudgetedType::kBudgeted) {
1093 // Purge the resource immediately if we're over budget
1094 // Also purge if the resource has neither a valid scratch key nor a unique key.
1095 bool hasKey = resource->resourcePriv().getScratchKey().isValid() || hasUniqueKey;
1096 if (!this->overBudget() && hasKey) {
1097 return;
1098 }
1099 } else {
1100 // We keep unbudgeted resources with a unique key in the purgeable queue of the cache so
1101 // they can be reused again by the image connected to the unique key.
1102 if (hasUniqueKey && budgetedType == GrBudgetedType::kUnbudgetedCacheable) {
1103 return;
1104 }
1105 // Check whether this resource could still be used as a scratch resource.
1106 if (!resource->resourcePriv().refsWrappedObjects() &&
1107 resource->resourcePriv().getScratchKey().isValid()) {
1108 // We won't purge an existing resource to make room for this one.
1109 if (this->wouldFit(resource->gpuMemorySize())) {
1110 resource->resourcePriv().makeBudgeted();
1111 return;
1112 }
1113 }
1114 }
1115
1116 SkDEBUGCODE(int beforeCount = this->getResourceCount();)
1117 resource->cacheAccess().release();
1118 // We should at least free this resource, perhaps dependent resources as well.
1119 SkASSERT(this->getResourceCount() < beforeCount);
1120 this->validate();
1121 }
1122
didChangeBudgetStatus(GrGpuResource * resource)1123 void GrResourceCache::didChangeBudgetStatus(GrGpuResource* resource) {
1124 ASSERT_SINGLE_OWNER
1125 SkASSERT(resource);
1126 SkASSERT(this->isInCache(resource));
1127
1128 size_t size = resource->gpuMemorySize();
1129 // Changing from BudgetedType::kUnbudgetedCacheable to another budgeted type could make
1130 // resource become purgeable. However, we should never allow that transition. Wrapped
1131 // resources are the only resources that can be in that state and they aren't allowed to
1132 // transition from one budgeted state to another.
1133 SkDEBUGCODE(bool wasPurgeable = resource->resourcePriv().isPurgeable());
1134 if (resource->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted) {
1135 ++fBudgetedCount;
1136 fBudgetedBytes += size;
1137 #if GR_CACHE_STATS
1138 fBudgetedHighWaterBytes = std::max(fBudgetedBytes, fBudgetedHighWaterBytes);
1139 fBudgetedHighWaterCount = std::max(fBudgetedCount, fBudgetedHighWaterCount);
1140 #endif
1141 if (!resource->resourcePriv().isPurgeable() &&
1142 !resource->cacheAccess().hasRefOrCommandBufferUsage()) {
1143 ++fNumBudgetedResourcesFlushWillMakePurgeable;
1144 }
1145 if (resource->cacheAccess().isUsableAsScratch()) {
1146 fScratchMap.insert(resource->resourcePriv().getScratchKey(), resource);
1147 }
1148 this->purgeAsNeeded();
1149 } else {
1150 SkASSERT(resource->resourcePriv().budgetedType() != GrBudgetedType::kUnbudgetedCacheable);
1151 --fBudgetedCount;
1152 fBudgetedBytes -= size;
1153 if (!resource->resourcePriv().isPurgeable() &&
1154 !resource->cacheAccess().hasRefOrCommandBufferUsage()) {
1155 --fNumBudgetedResourcesFlushWillMakePurgeable;
1156 }
1157 if (!resource->cacheAccess().hasRef() && !resource->getUniqueKey().isValid() &&
1158 resource->resourcePriv().getScratchKey().isValid()) {
1159 fScratchMap.remove(resource->resourcePriv().getScratchKey(), resource);
1160 }
1161 }
1162 SkASSERT(wasPurgeable == resource->resourcePriv().isPurgeable());
1163 TRACE_COUNTER2("skia.gpu.cache", "skia budget", "used",
1164 fBudgetedBytes, "free", fMaxBytes - fBudgetedBytes);
1165
1166 this->validate();
1167 }
1168
1169 static constexpr int timeUnit = 1000;
1170
1171 // OH ISSUE: allow access to release interface
allowToPurge(const std::function<bool (void)> & nextFrameHasArrived)1172 bool GrResourceCache::allowToPurge(const std::function<bool(void)>& nextFrameHasArrived)
1173 {
1174 if (!fEnabled) {
1175 return true;
1176 }
1177 if (fFrameInfo.duringFrame == 0) {
1178 if (nextFrameHasArrived && nextFrameHasArrived()) {
1179 return false;
1180 }
1181 return true;
1182 }
1183 if (fFrameInfo.frameCount != fLastFrameCount) { // the next frame arrives
1184 struct timespec startTime = {0, 0};
1185 if (clock_gettime(CLOCK_REALTIME, &startTime) == -1) {
1186 return true;
1187 }
1188 fStartTime = startTime.tv_sec * timeUnit * timeUnit + startTime.tv_nsec / timeUnit;
1189 fLastFrameCount = fFrameInfo.frameCount;
1190 return true;
1191 }
1192 struct timespec endTime = {0, 0};
1193 if (clock_gettime(CLOCK_REALTIME, &endTime) == -1) {
1194 return true;
1195 }
1196 if (((endTime.tv_sec * timeUnit * timeUnit + endTime.tv_nsec / timeUnit) - fStartTime) >= fOvertimeDuration) {
1197 return false;
1198 }
1199 return true;
1200 }
1201
purgeAsNeeded(const std::function<bool (void)> & nextFrameHasArrived)1202 void GrResourceCache::purgeAsNeeded(const std::function<bool(void)>& nextFrameHasArrived) {
1203 SkTArray<GrUniqueKeyInvalidatedMessage> invalidKeyMsgs;
1204 fInvalidUniqueKeyInbox.poll(&invalidKeyMsgs);
1205 if (invalidKeyMsgs.count()) {
1206 SkASSERT(fProxyProvider);
1207
1208 for (int i = 0; i < invalidKeyMsgs.count(); ++i) {
1209 if (invalidKeyMsgs[i].inThreadSafeCache()) {
1210 fThreadSafeCache->remove(invalidKeyMsgs[i].key());
1211 SkASSERT(!fThreadSafeCache->has(invalidKeyMsgs[i].key()));
1212 } else {
1213 fProxyProvider->processInvalidUniqueKey(
1214 invalidKeyMsgs[i].key(), nullptr,
1215 GrProxyProvider::InvalidateGPUResource::kYes);
1216 SkASSERT(!this->findAndRefUniqueResource(invalidKeyMsgs[i].key()));
1217 }
1218 }
1219 }
1220
1221 this->processFreedGpuResources();
1222
1223 bool stillOverbudget = this->overBudget(nextFrameHasArrived);
1224 while (stillOverbudget && fPurgeableQueue.count() && this->allowToPurge(nextFrameHasArrived)) {
1225 GrGpuResource* resource = fPurgeableQueue.peek();
1226 SkASSERT(resource->resourcePriv().isPurgeable());
1227 resource->cacheAccess().release();
1228 stillOverbudget = this->overBudget(nextFrameHasArrived);
1229 }
1230
1231 if (stillOverbudget) {
1232 fThreadSafeCache->dropUniqueRefs(this);
1233
1234 stillOverbudget = this->overBudget(nextFrameHasArrived);
1235 while (stillOverbudget && fPurgeableQueue.count() && this->allowToPurge(nextFrameHasArrived)) {
1236 GrGpuResource* resource = fPurgeableQueue.peek();
1237 SkASSERT(resource->resourcePriv().isPurgeable());
1238 resource->cacheAccess().release();
1239 stillOverbudget = this->overBudget(nextFrameHasArrived);
1240 }
1241 }
1242
1243 this->validate();
1244 }
1245
purgeUnlockedResources(const GrStdSteadyClock::time_point * purgeTime,bool scratchResourcesOnly)1246 void GrResourceCache::purgeUnlockedResources(const GrStdSteadyClock::time_point* purgeTime,
1247 bool scratchResourcesOnly) {
1248 #if defined (SKIA_OHOS_FOR_OHOS_TRACE) && defined (SKIA_DFX_FOR_OHOS)
1249 SimpleCacheInfo simpleCacheInfo;
1250 traceBeforePurgeUnlockRes("purgeUnlockedResources", simpleCacheInfo);
1251 #endif
1252 if (!scratchResourcesOnly) {
1253 if (purgeTime) {
1254 fThreadSafeCache->dropUniqueRefsOlderThan(*purgeTime);
1255 } else {
1256 fThreadSafeCache->dropUniqueRefs(nullptr);
1257 }
1258
1259 // We could disable maintaining the heap property here, but it would add a lot of
1260 // complexity. Moreover, this is rarely called.
1261 while (fPurgeableQueue.count()) {
1262 GrGpuResource* resource = fPurgeableQueue.peek();
1263
1264 const GrStdSteadyClock::time_point resourceTime =
1265 resource->cacheAccess().timeWhenResourceBecamePurgeable();
1266 if (purgeTime && resourceTime >= *purgeTime) {
1267 // Resources were given both LRU timestamps and tagged with a frame number when
1268 // they first became purgeable. The LRU timestamp won't change again until the
1269 // resource is made non-purgeable again. So, at this point all the remaining
1270 // resources in the timestamp-sorted queue will have a frame number >= to this
1271 // one.
1272 break;
1273 }
1274
1275 SkASSERT(resource->resourcePriv().isPurgeable());
1276 resource->cacheAccess().release();
1277 }
1278 } else {
1279 // Early out if the very first item is too new to purge to avoid sorting the queue when
1280 // nothing will be deleted.
1281 if (purgeTime && fPurgeableQueue.count() &&
1282 fPurgeableQueue.peek()->cacheAccess().timeWhenResourceBecamePurgeable() >= *purgeTime) {
1283 #if defined (SKIA_OHOS_FOR_OHOS_TRACE) && defined (SKIA_DFX_FOR_OHOS)
1284 traceAfterPurgeUnlockRes("purgeUnlockedResources", simpleCacheInfo);
1285 #endif
1286 return;
1287 }
1288
1289 // Sort the queue
1290 fPurgeableQueue.sort();
1291
1292 // Make a list of the scratch resources to delete
1293 SkTDArray<GrGpuResource*> scratchResources;
1294 for (int i = 0; i < fPurgeableQueue.count(); i++) {
1295 GrGpuResource* resource = fPurgeableQueue.at(i);
1296
1297 const GrStdSteadyClock::time_point resourceTime =
1298 resource->cacheAccess().timeWhenResourceBecamePurgeable();
1299 if (purgeTime && resourceTime >= *purgeTime) {
1300 // scratch or not, all later iterations will be too recently used to purge.
1301 break;
1302 }
1303 SkASSERT(resource->resourcePriv().isPurgeable());
1304 if (!resource->getUniqueKey().isValid()) {
1305 *scratchResources.append() = resource;
1306 }
1307 }
1308
1309 // Delete the scratch resources. This must be done as a separate pass
1310 // to avoid messing up the sorted order of the queue
1311 for (int i = 0; i < scratchResources.count(); i++) {
1312 scratchResources.getAt(i)->cacheAccess().release();
1313 }
1314 }
1315
1316 this->validate();
1317 #if defined (SKIA_OHOS_FOR_OHOS_TRACE) && defined (SKIA_DFX_FOR_OHOS)
1318 traceAfterPurgeUnlockRes("purgeUnlockedResources", simpleCacheInfo);
1319 #endif
1320 }
1321
purgeUnlockAndSafeCacheGpuResources()1322 void GrResourceCache::purgeUnlockAndSafeCacheGpuResources() {
1323 #if defined (SKIA_OHOS_FOR_OHOS_TRACE) && defined (SKIA_DFX_FOR_OHOS)
1324 SimpleCacheInfo simpleCacheInfo;
1325 traceBeforePurgeUnlockRes("purgeUnlockAndSafeCacheGpuResources", simpleCacheInfo);
1326 #endif
1327 fThreadSafeCache->dropUniqueRefs(nullptr);
1328 // Sort the queue
1329 fPurgeableQueue.sort();
1330
1331 //Make a list of the scratch resources to delete
1332 SkTDArray<GrGpuResource*> scratchResources;
1333 for (int i = 0; i < fPurgeableQueue.count(); i++) {
1334 GrGpuResource* resource = fPurgeableQueue.at(i);
1335 if (!resource) {
1336 continue;
1337 }
1338 SkASSERT(resource->resourcePriv().isPurgeable());
1339 if (!resource->getUniqueKey().isValid()) {
1340 *scratchResources.append() = resource;
1341 }
1342 }
1343
1344 //Delete the scatch resource. This must be done as a separate pass
1345 //to avoid messing up the sorted order of the queue
1346 for (int i = 0; i <scratchResources.count(); i++) {
1347 scratchResources.getAt(i)->cacheAccess().release();
1348 }
1349
1350 this->validate();
1351 #if defined (SKIA_OHOS_FOR_OHOS_TRACE) && defined (SKIA_DFX_FOR_OHOS)
1352 traceAfterPurgeUnlockRes("purgeUnlockAndSafeCacheGpuResources", simpleCacheInfo);
1353 #endif
1354 }
1355
1356 // OH ISSUE: suppress release window
suppressGpuCacheBelowCertainRatio(const std::function<bool (void)> & nextFrameHasArrived)1357 void GrResourceCache::suppressGpuCacheBelowCertainRatio(const std::function<bool(void)>& nextFrameHasArrived)
1358 {
1359 if (!fEnabled) {
1360 return;
1361 }
1362 this->purgeAsNeeded(nextFrameHasArrived);
1363 }
1364
purgeCacheBetweenFrames(bool scratchResourcesOnly,const std::set<int> & exitedPidSet,const std::set<int> & protectedPidSet)1365 void GrResourceCache::purgeCacheBetweenFrames(bool scratchResourcesOnly, const std::set<int>& exitedPidSet,
1366 const std::set<int>& protectedPidSet) {
1367 HITRACE_OHOS_NAME_FMT_ALWAYS("PurgeGrResourceCache cur=%d, limit=%d", fBudgetedBytes, fMaxBytes);
1368 if (exitedPidSet.size() > 1) {
1369 for (int i = 1; i < fPurgeableQueue.count(); i++) {
1370 GrGpuResource* resource = fPurgeableQueue.at(i);
1371 SkASSERT(resource->resourcePriv().isPurgeable());
1372 if (exitedPidSet.find(resource->getResourceTag().fPid) != exitedPidSet.end()) {
1373 resource->cacheAccess().release();
1374 this->validate();
1375 return;
1376 }
1377 }
1378 }
1379 fPurgeableQueue.sort();
1380 const char* softLimitPercentage = "0.9";
1381 #ifdef NOT_BUILD_FOR_OHOS_SDK
1382 static int softLimit =
1383 std::atof(OHOS::system::GetParameter("persist.sys.graphic.mem.soft_limit",
1384 softLimitPercentage).c_str()) * fMaxBytes;
1385 #else
1386 static int softLimit = 0.9 * fMaxBytes;
1387 #endif
1388 if (fBudgetedBytes >= softLimit) {
1389 for (int i=0; i < fPurgeableQueue.count(); i++) {
1390 GrGpuResource* resource = fPurgeableQueue.at(i);
1391 SkASSERT(resource->resourcePriv().isPurgeable());
1392 if (protectedPidSet.find(resource->getResourceTag().fPid) == protectedPidSet.end()
1393 && (!scratchResourcesOnly || !resource->getUniqueKey().isValid())) {
1394 resource->cacheAccess().release();
1395 this->validate();
1396 return;
1397 }
1398 }
1399 }
1400 }
1401
purgeUnlockedResourcesByPid(bool scratchResourceOnly,const std::set<int> & exitedPidSet)1402 void GrResourceCache::purgeUnlockedResourcesByPid(bool scratchResourceOnly, const std::set<int>& exitedPidSet) {
1403 #if defined (SKIA_OHOS_FOR_OHOS_TRACE) && defined (SKIA_DFX_FOR_OHOS)
1404 SimpleCacheInfo simpleCacheInfo;
1405 traceBeforePurgeUnlockRes("purgeUnlockedResourcesByPid", simpleCacheInfo);
1406 #endif
1407 // Sort the queue
1408 fPurgeableQueue.sort();
1409
1410 //Make lists of the need purged resources to delete
1411 fThreadSafeCache->dropUniqueRefs(nullptr);
1412 SkTDArray<GrGpuResource*> exitPidResources;
1413 SkTDArray<GrGpuResource*> scratchResources;
1414 for (int i = 0; i < fPurgeableQueue.count(); i++) {
1415 GrGpuResource* resource = fPurgeableQueue.at(i);
1416 if (!resource) {
1417 continue;
1418 }
1419 SkASSERT(resource->resourcePriv().isPurgeable());
1420 if (exitedPidSet.count(resource->getResourceTag().fPid)) {
1421 *exitPidResources.append() = resource;
1422 } else if (!resource->getUniqueKey().isValid()) {
1423 *scratchResources.append() = resource;
1424 }
1425 }
1426
1427 //Delete the exited pid and scatch resource. This must be done as a separate pass
1428 //to avoid messing up the sorted order of the queue
1429 for (int i = 0; i <exitPidResources.count(); i++) {
1430 exitPidResources.getAt(i)->cacheAccess().release();
1431 }
1432 for (int i = 0; i <scratchResources.count(); i++) {
1433 scratchResources.getAt(i)->cacheAccess().release();
1434 }
1435
1436 for (auto pid : exitedPidSet) {
1437 fExitedPid_.erase(pid);
1438 }
1439
1440 this->validate();
1441 #if defined (SKIA_OHOS_FOR_OHOS_TRACE) && defined (SKIA_DFX_FOR_OHOS)
1442 traceAfterPurgeUnlockRes("purgeUnlockedResourcesByPid", simpleCacheInfo);
1443 #endif
1444 }
1445
purgeUnlockedResourcesByTag(bool scratchResourcesOnly,const GrGpuResourceTag & tag)1446 void GrResourceCache::purgeUnlockedResourcesByTag(bool scratchResourcesOnly, const GrGpuResourceTag& tag) {
1447 // Sort the queue
1448 fPurgeableQueue.sort();
1449
1450 //Make a list of the scratch resources to delete
1451 SkTDArray<GrGpuResource*> scratchResources;
1452 for (int i = 0; i < fPurgeableQueue.count(); i++) {
1453 GrGpuResource* resource = fPurgeableQueue.at(i);
1454 SkASSERT(resource->resourcePriv().isPurgeable());
1455 if (tag.filter(resource->getResourceTag()) && (!scratchResourcesOnly || !resource->getUniqueKey().isValid())) {
1456 *scratchResources.append() = resource;
1457 }
1458 }
1459
1460 //Delete the scatch resource. This must be done as a separate pass
1461 //to avoid messing up the sorted order of the queue
1462 for (int i = 0; i <scratchResources.count(); i++) {
1463 scratchResources.getAt(i)->cacheAccess().release();
1464 }
1465
1466 this->validate();
1467 }
1468
purgeToMakeHeadroom(size_t desiredHeadroomBytes)1469 bool GrResourceCache::purgeToMakeHeadroom(size_t desiredHeadroomBytes) {
1470 AutoValidate av(this);
1471 if (desiredHeadroomBytes > fMaxBytes) {
1472 return false;
1473 }
1474 if (this->wouldFit(desiredHeadroomBytes)) {
1475 return true;
1476 }
1477 fPurgeableQueue.sort();
1478
1479 size_t projectedBudget = fBudgetedBytes;
1480 int purgeCnt = 0;
1481 for (int i = 0; i < fPurgeableQueue.count(); i++) {
1482 GrGpuResource* resource = fPurgeableQueue.at(i);
1483 if (GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType()) {
1484 projectedBudget -= resource->gpuMemorySize();
1485 }
1486 if (projectedBudget + desiredHeadroomBytes <= fMaxBytes) {
1487 purgeCnt = i + 1;
1488 break;
1489 }
1490 }
1491 if (purgeCnt == 0) {
1492 return false;
1493 }
1494
1495 // Success! Release the resources.
1496 // Copy to array first so we don't mess with the queue.
1497 std::vector<GrGpuResource*> resources;
1498 resources.reserve(purgeCnt);
1499 for (int i = 0; i < purgeCnt; i++) {
1500 resources.push_back(fPurgeableQueue.at(i));
1501 }
1502 for (GrGpuResource* resource : resources) {
1503 resource->cacheAccess().release();
1504 }
1505 return true;
1506 }
1507
purgeUnlockedResources(size_t bytesToPurge,bool preferScratchResources)1508 void GrResourceCache::purgeUnlockedResources(size_t bytesToPurge, bool preferScratchResources) {
1509
1510 const size_t tmpByteBudget = std::max((size_t)0, fBytes - bytesToPurge);
1511 bool stillOverbudget = tmpByteBudget < fBytes;
1512
1513 if (preferScratchResources && bytesToPurge < fPurgeableBytes) {
1514 // Sort the queue
1515 fPurgeableQueue.sort();
1516
1517 // Make a list of the scratch resources to delete
1518 SkTDArray<GrGpuResource*> scratchResources;
1519 size_t scratchByteCount = 0;
1520 for (int i = 0; i < fPurgeableQueue.count() && stillOverbudget; i++) {
1521 GrGpuResource* resource = fPurgeableQueue.at(i);
1522 SkASSERT(resource->resourcePriv().isPurgeable());
1523 if (!resource->getUniqueKey().isValid()) {
1524 *scratchResources.append() = resource;
1525 scratchByteCount += resource->gpuMemorySize();
1526 stillOverbudget = tmpByteBudget < fBytes - scratchByteCount;
1527 }
1528 }
1529
1530 // Delete the scratch resources. This must be done as a separate pass
1531 // to avoid messing up the sorted order of the queue
1532 for (int i = 0; i < scratchResources.count(); i++) {
1533 scratchResources.getAt(i)->cacheAccess().release();
1534 }
1535 stillOverbudget = tmpByteBudget < fBytes;
1536
1537 this->validate();
1538 }
1539
1540 // Purge any remaining resources in LRU order
1541 if (stillOverbudget) {
1542 const size_t cachedByteCount = fMaxBytes;
1543 fMaxBytes = tmpByteBudget;
1544 this->purgeAsNeeded();
1545 fMaxBytes = cachedByteCount;
1546 }
1547 }
1548
requestsFlush() const1549 bool GrResourceCache::requestsFlush() const {
1550 return this->overBudget() && !fPurgeableQueue.count() &&
1551 fNumBudgetedResourcesFlushWillMakePurgeable > 0;
1552 }
1553
insertDelayedTextureUnref(GrTexture * texture)1554 void GrResourceCache::insertDelayedTextureUnref(GrTexture* texture) {
1555 texture->ref();
1556 uint32_t id = texture->uniqueID().asUInt();
1557 if (auto* data = fTexturesAwaitingUnref.find(id)) {
1558 data->addRef();
1559 } else {
1560 fTexturesAwaitingUnref.set(id, {texture});
1561 }
1562 }
1563
processFreedGpuResources()1564 void GrResourceCache::processFreedGpuResources() {
1565 if (!fTexturesAwaitingUnref.count()) {
1566 return;
1567 }
1568
1569 SkTArray<GrTextureFreedMessage> msgs;
1570 fFreedTextureInbox.poll(&msgs);
1571 for (int i = 0; i < msgs.count(); ++i) {
1572 SkASSERT(msgs[i].fIntendedRecipient == fOwningContextID);
1573 uint32_t id = msgs[i].fTexture->uniqueID().asUInt();
1574 TextureAwaitingUnref* info = fTexturesAwaitingUnref.find(id);
1575 // If the GrContext was released or abandoned then fTexturesAwaitingUnref should have been
1576 // empty and we would have returned early above. Thus, any texture from a message should be
1577 // in the list of fTexturesAwaitingUnref.
1578 SkASSERT(info);
1579 info->unref();
1580 if (info->finished()) {
1581 fTexturesAwaitingUnref.remove(id);
1582 }
1583 }
1584 }
1585
addToNonpurgeableArray(GrGpuResource * resource)1586 void GrResourceCache::addToNonpurgeableArray(GrGpuResource* resource) {
1587 int index = fNonpurgeableResources.count();
1588 *fNonpurgeableResources.append() = resource;
1589 *resource->cacheAccess().accessCacheIndex() = index;
1590 }
1591
removeFromNonpurgeableArray(GrGpuResource * resource)1592 void GrResourceCache::removeFromNonpurgeableArray(GrGpuResource* resource) {
1593 int* index = resource->cacheAccess().accessCacheIndex();
1594 // Fill the hole we will create in the array with the tail object, adjust its index, and
1595 // then pop the array
1596 GrGpuResource* tail = *(fNonpurgeableResources.end() - 1);
1597 SkASSERT(fNonpurgeableResources[*index] == resource);
1598 fNonpurgeableResources[*index] = tail;
1599 *tail->cacheAccess().accessCacheIndex() = *index;
1600 fNonpurgeableResources.pop();
1601 SkDEBUGCODE(*index = -1);
1602 }
1603
getNextTimestamp()1604 uint32_t GrResourceCache::getNextTimestamp() {
1605 // If we wrap then all the existing resources will appear older than any resources that get
1606 // a timestamp after the wrap.
1607 if (0 == fTimestamp) {
1608 int count = this->getResourceCount();
1609 if (count) {
1610 // Reset all the timestamps. We sort the resources by timestamp and then assign
1611 // sequential timestamps beginning with 0. This is O(n*lg(n)) but it should be extremely
1612 // rare.
1613 SkTDArray<GrGpuResource*> sortedPurgeableResources;
1614 sortedPurgeableResources.setReserve(fPurgeableQueue.count());
1615
1616 while (fPurgeableQueue.count()) {
1617 *sortedPurgeableResources.append() = fPurgeableQueue.peek();
1618 fPurgeableQueue.pop();
1619 }
1620
1621 SkTQSort(fNonpurgeableResources.begin(), fNonpurgeableResources.end(),
1622 CompareTimestamp);
1623
1624 // Pick resources out of the purgeable and non-purgeable arrays based on lowest
1625 // timestamp and assign new timestamps.
1626 int currP = 0;
1627 int currNP = 0;
1628 while (currP < sortedPurgeableResources.count() &&
1629 currNP < fNonpurgeableResources.count()) {
1630 uint32_t tsP = sortedPurgeableResources[currP]->cacheAccess().timestamp();
1631 uint32_t tsNP = fNonpurgeableResources[currNP]->cacheAccess().timestamp();
1632 SkASSERT(tsP != tsNP);
1633 if (tsP < tsNP) {
1634 sortedPurgeableResources[currP++]->cacheAccess().setTimestamp(fTimestamp++);
1635 } else {
1636 // Correct the index in the nonpurgeable array stored on the resource post-sort.
1637 *fNonpurgeableResources[currNP]->cacheAccess().accessCacheIndex() = currNP;
1638 fNonpurgeableResources[currNP++]->cacheAccess().setTimestamp(fTimestamp++);
1639 }
1640 }
1641
1642 // The above loop ended when we hit the end of one array. Finish the other one.
1643 while (currP < sortedPurgeableResources.count()) {
1644 sortedPurgeableResources[currP++]->cacheAccess().setTimestamp(fTimestamp++);
1645 }
1646 while (currNP < fNonpurgeableResources.count()) {
1647 *fNonpurgeableResources[currNP]->cacheAccess().accessCacheIndex() = currNP;
1648 fNonpurgeableResources[currNP++]->cacheAccess().setTimestamp(fTimestamp++);
1649 }
1650
1651 // Rebuild the queue.
1652 for (int i = 0; i < sortedPurgeableResources.count(); ++i) {
1653 fPurgeableQueue.insert(sortedPurgeableResources[i]);
1654 }
1655
1656 this->validate();
1657 SkASSERT(count == this->getResourceCount());
1658
1659 // count should be the next timestamp we return.
1660 SkASSERT(fTimestamp == SkToU32(count));
1661 }
1662 }
1663 return fTimestamp++;
1664 }
1665
dumpMemoryStatistics(SkTraceMemoryDump * traceMemoryDump) const1666 void GrResourceCache::dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const {
1667 SkTDArray<GrGpuResource*> resources;
1668 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
1669 *resources.append() = fNonpurgeableResources[i];
1670 }
1671 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
1672 *resources.append() = fPurgeableQueue.at(i);
1673 }
1674 for (int i = 0; i < resources.count(); i++) {
1675 auto resource = resources.getAt(i);
1676 if (!resource || resource->wasDestroyed()) {
1677 continue;
1678 }
1679 resource->dumpMemoryStatistics(traceMemoryDump);
1680 }
1681 }
1682
dumpMemoryStatistics(SkTraceMemoryDump * traceMemoryDump,const GrGpuResourceTag & tag) const1683 void GrResourceCache::dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump, const GrGpuResourceTag& tag) const {
1684 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
1685 if (tag.filter(fNonpurgeableResources[i]->getResourceTag())) {
1686 fNonpurgeableResources[i]->dumpMemoryStatistics(traceMemoryDump);
1687 }
1688 }
1689 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
1690 if (tag.filter(fPurgeableQueue.at(i)->getResourceTag())) {
1691 fPurgeableQueue.at(i)->dumpMemoryStatistics(traceMemoryDump);
1692 }
1693 }
1694 }
1695
1696 #if GR_CACHE_STATS
getStats(Stats * stats) const1697 void GrResourceCache::getStats(Stats* stats) const {
1698 stats->reset();
1699
1700 stats->fTotal = this->getResourceCount();
1701 stats->fNumNonPurgeable = fNonpurgeableResources.count();
1702 stats->fNumPurgeable = fPurgeableQueue.count();
1703
1704 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
1705 stats->update(fNonpurgeableResources[i]);
1706 }
1707 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
1708 stats->update(fPurgeableQueue.at(i));
1709 }
1710 }
1711
1712 #if GR_TEST_UTILS
dumpStats(SkString * out) const1713 void GrResourceCache::dumpStats(SkString* out) const {
1714 this->validate();
1715
1716 Stats stats;
1717
1718 this->getStats(&stats);
1719
1720 float byteUtilization = (100.f * fBudgetedBytes) / fMaxBytes;
1721
1722 out->appendf("Budget: %d bytes\n", (int)fMaxBytes);
1723 out->appendf("\t\tEntry Count: current %d"
1724 " (%d budgeted, %d wrapped, %d locked, %d scratch), high %d\n",
1725 stats.fTotal, fBudgetedCount, stats.fWrapped, stats.fNumNonPurgeable,
1726 stats.fScratch, fHighWaterCount);
1727 out->appendf("\t\tEntry Bytes: current %d (budgeted %d, %.2g%% full, %d unbudgeted) high %d\n",
1728 SkToInt(fBytes), SkToInt(fBudgetedBytes), byteUtilization,
1729 SkToInt(stats.fUnbudgetedSize), SkToInt(fHighWaterBytes));
1730 }
1731
dumpStatsKeyValuePairs(SkTArray<SkString> * keys,SkTArray<double> * values) const1732 void GrResourceCache::dumpStatsKeyValuePairs(SkTArray<SkString>* keys,
1733 SkTArray<double>* values) const {
1734 this->validate();
1735
1736 Stats stats;
1737 this->getStats(&stats);
1738
1739 keys->push_back(SkString("gpu_cache_purgable_entries")); values->push_back(stats.fNumPurgeable);
1740 }
1741 #endif // GR_TEST_UTILS
1742 #endif // GR_CACHE_STATS
1743
1744 #ifdef SK_DEBUG
validate() const1745 void GrResourceCache::validate() const {
1746 // Reduce the frequency of validations for large resource counts.
1747 static SkRandom gRandom;
1748 int mask = (SkNextPow2(fCount + 1) >> 5) - 1;
1749 if (~mask && (gRandom.nextU() & mask)) {
1750 return;
1751 }
1752
1753 struct Stats {
1754 size_t fBytes;
1755 int fBudgetedCount;
1756 size_t fBudgetedBytes;
1757 int fLocked;
1758 int fScratch;
1759 int fCouldBeScratch;
1760 int fContent;
1761 const ScratchMap* fScratchMap;
1762 const UniqueHash* fUniqueHash;
1763
1764 Stats(const GrResourceCache* cache) {
1765 memset(this, 0, sizeof(*this));
1766 fScratchMap = &cache->fScratchMap;
1767 fUniqueHash = &cache->fUniqueHash;
1768 }
1769
1770 void update(GrGpuResource* resource) {
1771 fBytes += resource->gpuMemorySize();
1772
1773 if (!resource->resourcePriv().isPurgeable()) {
1774 ++fLocked;
1775 }
1776
1777 const GrScratchKey& scratchKey = resource->resourcePriv().getScratchKey();
1778 const GrUniqueKey& uniqueKey = resource->getUniqueKey();
1779
1780 if (resource->cacheAccess().isUsableAsScratch()) {
1781 SkASSERT(!uniqueKey.isValid());
1782 SkASSERT(GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType());
1783 SkASSERT(!resource->cacheAccess().hasRef());
1784 ++fScratch;
1785 SkASSERT(fScratchMap->countForKey(scratchKey));
1786 SkASSERT(!resource->resourcePriv().refsWrappedObjects());
1787 } else if (scratchKey.isValid()) {
1788 SkASSERT(GrBudgetedType::kBudgeted != resource->resourcePriv().budgetedType() ||
1789 uniqueKey.isValid() || resource->cacheAccess().hasRef());
1790 SkASSERT(!resource->resourcePriv().refsWrappedObjects());
1791 SkASSERT(!fScratchMap->has(resource, scratchKey));
1792 }
1793 if (uniqueKey.isValid()) {
1794 ++fContent;
1795 SkASSERT(fUniqueHash->find(uniqueKey) == resource);
1796 SkASSERT(GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType() ||
1797 resource->resourcePriv().refsWrappedObjects());
1798 }
1799
1800 if (GrBudgetedType::kBudgeted == resource->resourcePriv().budgetedType()) {
1801 ++fBudgetedCount;
1802 fBudgetedBytes += resource->gpuMemorySize();
1803 }
1804 }
1805 };
1806
1807 {
1808 int count = 0;
1809 fScratchMap.foreach([&](const GrGpuResource& resource) {
1810 SkASSERT(resource.cacheAccess().isUsableAsScratch());
1811 count++;
1812 });
1813 SkASSERT(count == fScratchMap.count());
1814 }
1815
1816 Stats stats(this);
1817 size_t purgeableBytes = 0;
1818 int numBudgetedResourcesFlushWillMakePurgeable = 0;
1819
1820 for (int i = 0; i < fNonpurgeableResources.count(); ++i) {
1821 SkASSERT(!fNonpurgeableResources[i]->resourcePriv().isPurgeable() ||
1822 fNewlyPurgeableResourceForValidation == fNonpurgeableResources[i]);
1823 SkASSERT(*fNonpurgeableResources[i]->cacheAccess().accessCacheIndex() == i);
1824 SkASSERT(!fNonpurgeableResources[i]->wasDestroyed());
1825 if (fNonpurgeableResources[i]->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted &&
1826 !fNonpurgeableResources[i]->cacheAccess().hasRefOrCommandBufferUsage() &&
1827 fNewlyPurgeableResourceForValidation != fNonpurgeableResources[i]) {
1828 ++numBudgetedResourcesFlushWillMakePurgeable;
1829 }
1830 stats.update(fNonpurgeableResources[i]);
1831 }
1832 for (int i = 0; i < fPurgeableQueue.count(); ++i) {
1833 SkASSERT(fPurgeableQueue.at(i)->resourcePriv().isPurgeable());
1834 SkASSERT(*fPurgeableQueue.at(i)->cacheAccess().accessCacheIndex() == i);
1835 SkASSERT(!fPurgeableQueue.at(i)->wasDestroyed());
1836 stats.update(fPurgeableQueue.at(i));
1837 purgeableBytes += fPurgeableQueue.at(i)->gpuMemorySize();
1838 }
1839
1840 SkASSERT(fCount == this->getResourceCount());
1841 SkASSERT(fBudgetedCount <= fCount);
1842 SkASSERT(fBudgetedBytes <= fBytes);
1843 SkASSERT(stats.fBytes == fBytes);
1844 SkASSERT(fNumBudgetedResourcesFlushWillMakePurgeable ==
1845 numBudgetedResourcesFlushWillMakePurgeable);
1846 SkASSERT(stats.fBudgetedBytes == fBudgetedBytes);
1847 SkASSERT(stats.fBudgetedCount == fBudgetedCount);
1848 SkASSERT(purgeableBytes == fPurgeableBytes);
1849 #if GR_CACHE_STATS
1850 SkASSERT(fBudgetedHighWaterCount <= fHighWaterCount);
1851 SkASSERT(fBudgetedHighWaterBytes <= fHighWaterBytes);
1852 SkASSERT(fBytes <= fHighWaterBytes);
1853 SkASSERT(fCount <= fHighWaterCount);
1854 SkASSERT(fBudgetedBytes <= fBudgetedHighWaterBytes);
1855 SkASSERT(fBudgetedCount <= fBudgetedHighWaterCount);
1856 #endif
1857 SkASSERT(stats.fContent == fUniqueHash.count());
1858 SkASSERT(stats.fScratch == fScratchMap.count());
1859
1860 // This assertion is not currently valid because we can be in recursive notifyCntReachedZero()
1861 // calls. This will be fixed when subresource registration is explicit.
1862 // bool overBudget = budgetedBytes > fMaxBytes || budgetedCount > fMaxCount;
1863 // SkASSERT(!overBudget || locked == count || fPurging);
1864 }
1865
isInCache(const GrGpuResource * resource) const1866 bool GrResourceCache::isInCache(const GrGpuResource* resource) const {
1867 int index = *resource->cacheAccess().accessCacheIndex();
1868 if (index < 0) {
1869 return false;
1870 }
1871 if (index < fPurgeableQueue.count() && fPurgeableQueue.at(index) == resource) {
1872 return true;
1873 }
1874 if (index < fNonpurgeableResources.count() && fNonpurgeableResources[index] == resource) {
1875 return true;
1876 }
1877 SkDEBUGFAIL("Resource index should be -1 or the resource should be in the cache.");
1878 return false;
1879 }
1880
1881 #endif // SK_DEBUG
1882
1883 #if GR_TEST_UTILS
1884
countUniqueKeysWithTag(const char * tag) const1885 int GrResourceCache::countUniqueKeysWithTag(const char* tag) const {
1886 int count = 0;
1887 fUniqueHash.foreach([&](const GrGpuResource& resource){
1888 if (0 == strcmp(tag, resource.getUniqueKey().tag())) {
1889 ++count;
1890 }
1891 });
1892 return count;
1893 }
1894
changeTimestamp(uint32_t newTimestamp)1895 void GrResourceCache::changeTimestamp(uint32_t newTimestamp) {
1896 fTimestamp = newTimestamp;
1897 }
1898
1899 #endif // GR_TEST_UTILS
1900