Debian Codegraph @

src/core/SkResourceCache.cpp

raw
1 /*
2 * Copyright 2013 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/core/SkResourceCache.h"
9
10 #include "include/core/SkString.h"
11 #include "include/core/SkTraceMemoryDump.h"
12 #include "include/core/SkTypes.h"
13 #include "include/private/base/SkAlign.h"
14 #include "include/private/base/SkDebug.h"
15 #include "include/private/base/SkMalloc.h"
16 #include "include/private/base/SkMath.h"
17 #include "include/private/base/SkTArray.h"
18 #include "include/private/base/SkTo.h"
19 #include "src/core/SkCachedData.h"
20 #include "src/core/SkChecksum.h"
21 #include "src/core/SkMessageBus.h"
22 #include "src/core/SkSynchronizedResourceCache.h"
23 #include "src/core/SkTHash.h"
24
25 #if defined(SK_USE_DISCARDABLE_SCALEDIMAGECACHE)
26 #include "include/private/chromium/SkDiscardableMemory.h"
27 #endif
28
29 #include <algorithm>
30
31 using namespace skia_private;
32
33 DECLARE_SKMESSAGEBUS_MESSAGE(SkResourceCache::PurgeSharedIDMessage, uint32_t, true)
34
35 static inline bool SkShouldPostMessageToBus(
36 const SkResourceCache::PurgeSharedIDMessage&, uint32_t) {
37 // SkResourceCache is typically used as a singleton and we don't label Inboxes so all messages
38 // go to all inboxes.
39 return true;
40 }
41
42 // This can be defined by the caller's build system
43 //#define SK_USE_DISCARDABLE_SCALEDIMAGECACHE
44
45 #ifndef SK_DISCARDABLEMEMORY_SCALEDIMAGECACHE_COUNT_LIMIT
46 # define SK_DISCARDABLEMEMORY_SCALEDIMAGECACHE_COUNT_LIMIT 1024
47 #endif
48
49 #ifndef SK_DEFAULT_IMAGE_CACHE_LIMIT
50 #define SK_DEFAULT_IMAGE_CACHE_LIMIT (32 * 1024 * 1024)
51 #endif
52
53 void SkResourceCache::Key::init(void* nameSpace, uint64_t sharedID, size_t dataSize) {
54 SkASSERT(SkAlign4(dataSize) == dataSize);
55
56 // fCount32 and fHash are not hashed
57 static const int kUnhashedLocal32s = 2; // fCache32 + fHash
58 static const int kSharedIDLocal32s = 2; // fSharedID_lo + fSharedID_hi
59 static const int kHashedLocal32s = kSharedIDLocal32s + (sizeof(fNamespace) >> 2);
60 static const int kLocal32s = kUnhashedLocal32s + kHashedLocal32s;
61
62 static_assert(sizeof(Key) == (kLocal32s << 2), "unaccounted_key_locals");
63 static_assert(sizeof(Key) == offsetof(Key, fNamespace) + sizeof(fNamespace),
64 "namespace_field_must_be_last");
65
66 fCount32 = SkToS32(kLocal32s + (dataSize >> 2));
67 fSharedID_lo = (uint32_t)(sharedID & 0xFFFFFFFF);
68 fSharedID_hi = (uint32_t)(sharedID >> 32);
69 fNamespace = nameSpace;
70 // skip unhashed fields when computing the hash
71 fHash = SkChecksum::Hash32(this->as32() + kUnhashedLocal32s,
72 (fCount32 - kUnhashedLocal32s) << 2);
73 }
74
75 namespace {
76 struct HashTraits {
77 static uint32_t Hash(const SkResourceCache::Key& key) { return key.hash(); }
78 static const SkResourceCache::Key& GetKey(const SkResourceCache::Rec* rec) {
79 return rec->getKey();
80 }
81 };
82 } // namespace
83
84 class SkResourceCache::Hash :
85 public THashTable<SkResourceCache::Rec*, SkResourceCache::Key, HashTraits> {};
86
87
88 ///////////////////////////////////////////////////////////////////////////////
89
90 void SkResourceCache::init() {
91 fHead = nullptr;
92 fTail = nullptr;
93 fHash = new Hash;
94 fTotalBytesUsed = 0;
95 fCount = 0;
96 fSingleAllocationByteLimit = 0;
97
98 // One of these should be explicit set by the caller after we return.
99 fTotalByteLimit = 0;
100 fDiscardableFactory = nullptr;
101 }
102
103 SkResourceCache::SkResourceCache(DiscardableFactory factory)
104 : fPurgeSharedIDInbox(SK_InvalidUniqueID) {
105 this->init();
106 fDiscardableFactory = factory;
107 }
108
109 SkResourceCache::SkResourceCache(size_t byteLimit)
110 : fPurgeSharedIDInbox(SK_InvalidUniqueID) {
111 this->init();
112 fTotalByteLimit = byteLimit;
113 }
114
115 SkResourceCache::~SkResourceCache() {
116 Rec* rec = fHead;
117 while (rec) {
118 Rec* next = rec->fNext;
119 delete rec;
120 rec = next;
121 }
122 delete fHash;
123 }
124
125 ////////////////////////////////////////////////////////////////////////////////
126
127 bool SkResourceCache::find(const Key& key, FindVisitor visitor, void* context) {
128 this->checkMessages();
129
130 if (auto found = fHash->find(key)) {
131 Rec* rec = *found;
132 if (visitor(*rec, context)) {
133 this->moveToHead(rec); // for our LRU
134 return true;
135 } else {
136 this->remove(rec); // stale
137 return false;
138 }
139 }
140 return false;
141 }
142
143 static void make_size_str(size_t size, SkString* str) {
144 const char suffix[] = { 'b', 'k', 'm', 'g', 't', 0 };
145 int i = 0;
146 while (suffix[i] && (size > 1024)) {
147 i += 1;
148 size >>= 10;
149 }
150 str->printf("%zu%c", size, suffix[i]);
151 }
152
153 static bool gDumpCacheTransactions;
154
155 void SkResourceCache::add(Rec* rec, void* payload) {
156 this->checkMessages();
157
158 SkASSERT(rec);
159 // See if we already have this key (racy inserts, etc.)
160 if (Rec** preexisting = fHash->find(rec->getKey())) {
161 Rec* prev = *preexisting;
162 if (prev->canBePurged()) {
163 // if it can be purged, the install may fail, so we have to remove it
164 this->remove(prev);
165 } else {
166 // if it cannot be purged, we reuse it and delete the new one
167 prev->postAddInstall(payload);
168 delete rec;
169 return;
170 }
171 }
172
173 this->addToHead(rec);
174 fHash->set(rec);
175 rec->postAddInstall(payload);
176
177 if (gDumpCacheTransactions) {
178 SkString bytesStr, totalStr;
179 make_size_str(rec->bytesUsed(), &bytesStr);
180 make_size_str(fTotalBytesUsed, &totalStr);
181 SkDebugf("RC: add %5s %12p key %08x -- total %5s, count %d\n",
182 bytesStr.c_str(), rec, rec->getHash(), totalStr.c_str(), fCount);
183 }
184
185 // since the new rec may push us over-budget, we perform a purge check now
186 this->purgeAsNeeded();
187 }
188
189 void SkResourceCache::remove(Rec* rec) {
190 SkASSERT(rec->canBePurged());
191 size_t used = rec->bytesUsed();
192 SkASSERT(used <= fTotalBytesUsed);
193
194 this->release(rec);
195 fHash->remove(rec->getKey());
196
197 fTotalBytesUsed -= used;
198 fCount -= 1;
199
200 //SkDebugf("-RC count [%3d] bytes %d\n", fCount, fTotalBytesUsed);
201
202 if (gDumpCacheTransactions) {
203 SkString bytesStr, totalStr;
204 make_size_str(used, &bytesStr);
205 make_size_str(fTotalBytesUsed, &totalStr);
206 SkDebugf("RC: remove %5s %12p key %08x -- total %5s, count %d\n",
207 bytesStr.c_str(), rec, rec->getHash(), totalStr.c_str(), fCount);
208 }
209
210 delete rec;
211 }
212
213 void SkResourceCache::purgeAsNeeded(bool forcePurge) {
214 size_t byteLimit;
215 int countLimit;
216
217 if (fDiscardableFactory) {
218 countLimit = SK_DISCARDABLEMEMORY_SCALEDIMAGECACHE_COUNT_LIMIT;
219 byteLimit = UINT32_MAX; // no limit based on bytes
220 } else {
221 countLimit = SK_MaxS32; // no limit based on count
222 byteLimit = fTotalByteLimit;
223 }
224
225 Rec* rec = fTail;
226 while (rec) {
227 if (!forcePurge && fTotalBytesUsed < byteLimit && fCount < countLimit) {
228 break;
229 }
230
231 Rec* prev = rec->fPrev;
232 if (rec->canBePurged()) {
233 this->remove(rec);
234 }
235 rec = prev;
236 }
237 }
238
239 //#define SK_TRACK_PURGE_SHAREDID_HITRATE
240
241 #ifdef SK_TRACK_PURGE_SHAREDID_HITRATE
242 static int gPurgeCallCounter;
243 static int gPurgeHitCounter;
244 #endif
245
246 void SkResourceCache::purgeSharedID(uint64_t sharedID) {
247 if (0 == sharedID) {
248 return;
249 }
250
251 #ifdef SK_TRACK_PURGE_SHAREDID_HITRATE
252 gPurgeCallCounter += 1;
253 bool found = false;
254 #endif
255 // go backwards, just like purgeAsNeeded, just to make the code similar.
256 // could iterate either direction and still be correct.
257 Rec* rec = fTail;
258 while (rec) {
259 Rec* prev = rec->fPrev;
260 if (rec->getKey().getSharedID() == sharedID) {
261 // even though the "src" is now dead, caches could still be in-flight, so
262 // we have to check if it can be removed.
263 if (rec->canBePurged()) {
264 this->remove(rec);
265 }
266 #ifdef SK_TRACK_PURGE_SHAREDID_HITRATE
267 found = true;
268 #endif
269 }
270 rec = prev;
271 }
272
273 #ifdef SK_TRACK_PURGE_SHAREDID_HITRATE
274 if (found) {
275 gPurgeHitCounter += 1;
276 }
277
278 SkDebugf("PurgeShared calls=%d hits=%d rate=%g\n", gPurgeCallCounter, gPurgeHitCounter,
279 gPurgeHitCounter * 100.0 / gPurgeCallCounter);
280 #endif
281 }
282
283 void SkResourceCache::visitAll(Visitor visitor, void* context) {
284 // go backwards, just like purgeAsNeeded, just to make the code similar.
285 // could iterate either direction and still be correct.
286 Rec* rec = fTail;
287 while (rec) {
288 visitor(*rec, context);
289 rec = rec->fPrev;
290 }
291 }
292
293 ///////////////////////////////////////////////////////////////////////////////////////////////////
294
295 size_t SkResourceCache::setTotalByteLimit(size_t newLimit) {
296 size_t prevLimit = fTotalByteLimit;
297 fTotalByteLimit = newLimit;
298 if (newLimit < prevLimit) {
299 this->purgeAsNeeded();
300 }
301 return prevLimit;
302 }
303
304 SkCachedData* SkResourceCache::newCachedData(size_t bytes) {
305 this->checkMessages();
306
307 if (fDiscardableFactory) {
308 SkDiscardableMemory* dm = fDiscardableFactory(bytes);
309 return dm ? new SkCachedData(bytes, dm) : nullptr;
310 } else {
311 return new SkCachedData(sk_malloc_throw(bytes), bytes);
312 }
313 }
314
315 ///////////////////////////////////////////////////////////////////////////////
316
317 void SkResourceCache::release(Rec* rec) {
318 Rec* prev = rec->fPrev;
319 Rec* next = rec->fNext;
320
321 if (!prev) {
322 SkASSERT(fHead == rec);
323 fHead = next;
324 } else {
325 prev->fNext = next;
326 }
327
328 if (!next) {
329 fTail = prev;
330 } else {
331 next->fPrev = prev;
332 }
333
334 rec->fNext = rec->fPrev = nullptr;
335 }
336
337 void SkResourceCache::moveToHead(Rec* rec) {
338 if (fHead == rec) {
339 return;
340 }
341
342 SkASSERT(fHead);
343 SkASSERT(fTail);
344
345 this->validate();
346
347 this->release(rec);
348
349 fHead->fPrev = rec;
350 rec->fNext = fHead;
351 fHead = rec;
352
353 this->validate();
354 }
355
356 void SkResourceCache::addToHead(Rec* rec) {
357 this->validate();
358
359 rec->fPrev = nullptr;
360 rec->fNext = fHead;
361 if (fHead) {
362 fHead->fPrev = rec;
363 }
364 fHead = rec;
365 if (!fTail) {
366 fTail = rec;
367 }
368 fTotalBytesUsed += rec->bytesUsed();
369 fCount += 1;
370
371 this->validate();
372 }
373
374 ///////////////////////////////////////////////////////////////////////////////
375
376 #ifdef SK_DEBUG
377 void SkResourceCache::validate() const {
378 if (nullptr == fHead) {
379 SkASSERT(nullptr == fTail);
380 SkASSERT(0 == fTotalBytesUsed);
381 return;
382 }
383
384 if (fHead == fTail) {
385 SkASSERT(nullptr == fHead->fPrev);
386 SkASSERT(nullptr == fHead->fNext);
387 SkASSERT(fHead->bytesUsed() == fTotalBytesUsed);
388 return;
389 }
390
391 SkASSERT(nullptr == fHead->fPrev);
392 SkASSERT(fHead->fNext);
393 SkASSERT(nullptr == fTail->fNext);
394 SkASSERT(fTail->fPrev);
395
396 size_t used = 0;
397 int count = 0;
398 const Rec* rec = fHead;
399 while (rec) {
400 count += 1;
401 used += rec->bytesUsed();
402 SkASSERT(used <= fTotalBytesUsed);
403 rec = rec->fNext;
404 }
405 SkASSERT(fCount == count);
406
407 rec = fTail;
408 while (rec) {
409 SkASSERT(count > 0);
410 count -= 1;
411 SkASSERT(used >= rec->bytesUsed());
412 used -= rec->bytesUsed();
413 rec = rec->fPrev;
414 }
415
416 SkASSERT(0 == count);
417 SkASSERT(0 == used);
418 }
419 #endif
420
421 void SkResourceCache::dump() const {
422 this->validate();
423
424 SkDebugf("SkResourceCache: count=%d bytes=%zu %s\n",
425 fCount, fTotalBytesUsed, fDiscardableFactory ? "discardable" : "malloc");
426 }
427
428 size_t SkResourceCache::setSingleAllocationByteLimit(size_t newLimit) {
429 size_t oldLimit = fSingleAllocationByteLimit;
430 fSingleAllocationByteLimit = newLimit;
431 return oldLimit;
432 }
433
434 size_t SkResourceCache::getSingleAllocationByteLimit() const {
435 return fSingleAllocationByteLimit;
436 }
437
438 size_t SkResourceCache::getEffectiveSingleAllocationByteLimit() const {
439 // fSingleAllocationByteLimit == 0 means the caller is asking for our default
440 size_t limit = fSingleAllocationByteLimit;
441
442 // if we're not discardable (i.e. we are fixed-budget) then cap the single-limit
443 // to our budget.
444 if (nullptr == fDiscardableFactory) {
445 if (0 == limit) {
446 limit = fTotalByteLimit;
447 } else {
448 limit = std::min(limit, fTotalByteLimit);
449 }
450 }
451 return limit;
452 }
453
454 void SkResourceCache::checkMessages() {
455 TArray<PurgeSharedIDMessage> msgs;
456 fPurgeSharedIDInbox.poll(&msgs);
457 for (int i = 0; i < msgs.size(); ++i) {
458 this->purgeSharedID(msgs[i].fSharedID);
459 }
460 }
461
462 ///////////////////////////////////////////////////////////////////////////////
463
464 /** Must hold resource_cache_mutex() when calling. */
465 static SkSynchronizedResourceCache* get_cache() {
466 static SkSynchronizedResourceCache* gResourceCache = nullptr;
467 if (nullptr == gResourceCache) {
468 #if defined(SK_USE_DISCARDABLE_SCALEDIMAGECACHE)
469 gResourceCache = new SkSynchronizedResourceCache(SkDiscardableMemory::Create);
470 #else
471 gResourceCache = new SkSynchronizedResourceCache(SK_DEFAULT_IMAGE_CACHE_LIMIT);
472 #endif
473 }
474 return gResourceCache;
475 }
476
477 size_t SkResourceCache::GetTotalBytesUsed() {
478 return get_cache()->getTotalBytesUsed();
479 }
480
481 size_t SkResourceCache::GetTotalByteLimit() {
482 return get_cache()->getTotalByteLimit();
483 }
484
485 size_t SkResourceCache::SetTotalByteLimit(size_t newLimit) {
486 return get_cache()->setTotalByteLimit(newLimit);
487 }
488
489 SkResourceCache::DiscardableFactory SkResourceCache::GetDiscardableFactory() {
490 return get_cache()->discardableFactory();
491 }
492
493 SkCachedData* SkResourceCache::NewCachedData(size_t bytes) {
494 return get_cache()->newCachedData(bytes);
495 }
496
497 void SkResourceCache::Dump() {
498 get_cache()->dump();
499 }
500
501 size_t SkResourceCache::SetSingleAllocationByteLimit(size_t size) {
502 return get_cache()->setSingleAllocationByteLimit(size);
503 }
504
505 size_t SkResourceCache::GetSingleAllocationByteLimit() {
506 return get_cache()->getSingleAllocationByteLimit();
507 }
508
509 size_t SkResourceCache::GetEffectiveSingleAllocationByteLimit() {
510 return get_cache()->getEffectiveSingleAllocationByteLimit();
511 }
512
513 void SkResourceCache::PurgeAll() {
514 return get_cache()->purgeAll();
515 }
516
517 void SkResourceCache::CheckMessages() {
518 return get_cache()->checkMessages();
519 }
520
521 bool SkResourceCache::Find(const Key& key, FindVisitor visitor, void* context) {
522 return get_cache()->find(key, visitor, context);
523 }
524
525 void SkResourceCache::Add(Rec* rec, void* payload) {
526 get_cache()->add(rec, payload);
527 }
528
529 void SkResourceCache::VisitAll(Visitor visitor, void* context) {
530 get_cache()->visitAll(visitor, context);
531 }
532
533 void SkResourceCache::PostPurgeSharedID(uint64_t sharedID) {
534 if (sharedID) {
535 SkMessageBus<PurgeSharedIDMessage, uint32_t>::Post(PurgeSharedIDMessage(sharedID));
536 }
537 }
538
539 ///////////////////////////////////////////////////////////////////////////////
540
541 static void dump_visitor(const SkResourceCache::Rec& rec, void*) {
542 SkDebugf("RC: %12s bytes %9zu discardable %p\n",
543 rec.getCategory(), rec.bytesUsed(), rec.diagnostic_only_getDiscardable());
544 }
545
546 void SkResourceCache::TestDumpMemoryStatistics() {
547 VisitAll(dump_visitor, nullptr);
548 }
549
550 static void sk_trace_dump_visitor(const SkResourceCache::Rec& rec, void* context) {
551 SkTraceMemoryDump* dump = static_cast<SkTraceMemoryDump*>(context);
552 SkString dumpName = SkStringPrintf("skia/sk_resource_cache/%s_%p", rec.getCategory(), &rec);
553 SkDiscardableMemory* discardable = rec.diagnostic_only_getDiscardable();
554 if (discardable) {
555 dump->setDiscardableMemoryBacking(dumpName.c_str(), *discardable);
556
557 // The discardable memory size will be calculated by dumper, but we also dump what we think
558 // the size of object in memory is irrespective of whether object is live or dead.
559 dump->dumpNumericValue(dumpName.c_str(), "discardable_size", "bytes", rec.bytesUsed());
560 } else {
561 dump->dumpNumericValue(dumpName.c_str(), "size", "bytes", rec.bytesUsed());
562 dump->setMemoryBacking(dumpName.c_str(), "malloc", nullptr);
563 }
564 }
565
566 void SkResourceCache::DumpMemoryStatistics(SkTraceMemoryDump* dump) {
567 // Since resource could be backed by malloc or discardable, the cache always dumps detailed
568 // stats to be accurate.
569 VisitAll(sk_trace_dump_visitor, dump);
570 }