xref: /aosp_15_r20/external/skia/src/gpu/ResourceKey.h (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
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 #ifndef skgpu_ResourceKey_DEFINED
9 #define skgpu_ResourceKey_DEFINED
10 
11 #include "include/core/SkData.h"
12 #include "include/core/SkRefCnt.h"
13 #include "include/core/SkTypes.h"
14 #include "include/private/base/SkAlign.h"
15 #include "include/private/base/SkAlignedStorage.h"
16 #include "include/private/base/SkDebug.h"
17 #include "include/private/base/SkTemplates.h"
18 #include "include/private/base/SkTo.h"
19 
20 #include <cstdint>
21 #include <cstring>
22 #include <new>
23 #include <utility>
24 
25 class TestResource;
26 
27 namespace skgpu {
28 
29 uint32_t ResourceKeyHash(const uint32_t* data, size_t size);
30 
31 /**
32  * Base class for all gpu Resource cache keys. There are two types of cache keys. Refer to the
33  * comments for each key type below.
34  */
35 class ResourceKey {
36 public:
hash()37     uint32_t hash() const {
38         this->validate();
39         return fKey[kHash_MetaDataIdx];
40     }
41 
size()42     size_t size() const {
43         this->validate();
44         SkASSERT(this->isValid());
45         return this->internalSize();
46     }
47 
48     /** Reset to an invalid key. */
reset()49     void reset() {
50         fKey.reset(kMetaDataCnt);
51         fKey[kHash_MetaDataIdx] = 0;
52         fKey[kDomainAndSize_MetaDataIdx] = kInvalidDomain;
53     }
54 
isValid()55     bool isValid() const { return kInvalidDomain != this->domain(); }
56 
57     /** Used to initialize a key. */
58     class Builder {
59     public:
~Builder()60         ~Builder() { this->finish(); }
61 
finish()62         void finish() {
63             if (nullptr == fKey) {
64                 return;
65             }
66             uint32_t* hash = &fKey->fKey[kHash_MetaDataIdx];
67             *hash = ResourceKeyHash(hash + 1, fKey->internalSize() - sizeof(uint32_t));
68             fKey->validate();
69             fKey = nullptr;
70         }
71 
72         uint32_t& operator[](int dataIdx) {
73             SkASSERT(fKey);
74             SkDEBUGCODE(size_t dataCount = fKey->internalSize() / sizeof(uint32_t) - kMetaDataCnt;)
75                     SkASSERT(SkToU32(dataIdx) < dataCount);
76             return fKey->fKey[(int)kMetaDataCnt + dataIdx];
77         }
78 
79     protected:
Builder(ResourceKey * key,uint32_t domain,int data32Count)80         Builder(ResourceKey* key, uint32_t domain, int data32Count) : fKey(key) {
81             size_t count = SkToSizeT(data32Count);
82             SkASSERT(domain != kInvalidDomain);
83             key->fKey.reset(kMetaDataCnt + count);
84             size_t size = (count + kMetaDataCnt) * sizeof(uint32_t);
85             SkASSERT(SkToU16(size) == size);
86             SkASSERT(SkToU16(domain) == domain);
87             key->fKey[kDomainAndSize_MetaDataIdx] = SkToU32(domain | (size << 16));
88         }
89 
90     private:
91         ResourceKey* fKey;
92     };
93 
94 protected:
95     static const uint32_t kInvalidDomain = 0;
96 
ResourceKey()97     ResourceKey() { this->reset(); }
98 
99     bool operator==(const ResourceKey& that) const {
100         // Both keys should be sized to at least contain the meta data. The metadata contains each
101         // key's length. So the second memcmp should only run if the keys have the same length.
102         return 0 == memcmp(fKey.get(), that.fKey.get(), kMetaDataCnt*sizeof(uint32_t)) &&
103                0 == memcmp(&fKey[kMetaDataCnt], &that.fKey[kMetaDataCnt], this->dataSize());
104     }
105 
106     ResourceKey& operator=(const ResourceKey& that) {
107         if (this != &that) {
108             if (!that.isValid()) {
109                 this->reset();
110             } else {
111                 size_t bytes = that.size();
112                 SkASSERT(SkIsAlign4(bytes));
113                 fKey.reset(bytes / sizeof(uint32_t));
114                 memcpy(fKey.get(), that.fKey.get(), bytes);
115                 this->validate();
116             }
117         }
118         return *this;
119     }
120 
domain()121     uint32_t domain() const { return fKey[kDomainAndSize_MetaDataIdx] & 0xffff; }
122 
123     /** size of the key data, excluding meta-data (hash, domain, etc).  */
dataSize()124     size_t dataSize() const { return this->size() - 4 * kMetaDataCnt; }
125 
126     /** ptr to the key data, excluding meta-data (hash, domain, etc).  */
data()127     const uint32_t* data() const {
128         this->validate();
129         return &fKey[kMetaDataCnt];
130     }
131 
132 #ifdef SK_DEBUG
dump()133     void dump() const {
134         if (!this->isValid()) {
135             SkDebugf("Invalid Key\n");
136         } else {
137             SkDebugf("hash: %u ", this->hash());
138             SkDebugf("domain: %u ", this->domain());
139             SkDebugf("size: %zuB ", this->internalSize());
140             size_t dataCount = this->internalSize() / sizeof(uint32_t) - kMetaDataCnt;
141             for (size_t i = 0; i < dataCount; ++i) {
142                 SkDebugf("%u ", fKey[SkTo<int>(kMetaDataCnt+i)]);
143             }
144             SkDebugf("\n");
145         }
146     }
147 #endif
148 
149 private:
150     enum MetaDataIdx {
151         kHash_MetaDataIdx,
152         // The key domain and size are packed into a single uint32_t.
153         kDomainAndSize_MetaDataIdx,
154 
155         kLastMetaDataIdx = kDomainAndSize_MetaDataIdx
156     };
157     static const uint32_t kMetaDataCnt = kLastMetaDataIdx + 1;
158 
internalSize()159     size_t internalSize() const { return fKey[kDomainAndSize_MetaDataIdx] >> 16; }
160 
validate()161     void validate() const {
162         SkASSERT(this->isValid());
163         SkASSERT(fKey[kHash_MetaDataIdx] ==
164                  ResourceKeyHash(&fKey[kHash_MetaDataIdx] + 1,
165                                  this->internalSize() - sizeof(uint32_t)));
166         SkASSERT(SkIsAlign4(this->internalSize()));
167     }
168 
169     friend class ::TestResource;  // For unit test to access kMetaDataCnt.
170 
171     // For Ganesh, bmp textures require 5 uint32_t values. Graphite requires 6 (due to
172     // storing mipmap status as part of the key).
173     skia_private::AutoSTMalloc<kMetaDataCnt + 6, uint32_t> fKey;
174 };
175 
176 /**
177  * A key used for scratch resources. There are three important rules about scratch keys:
178  *        * Multiple resources can share the same scratch key. Therefore resources assigned the same
179  *          scratch key should be interchangeable with respect to the code that uses them.
180  *        * A resource can have at most one scratch key and it is set at resource creation by the
181  *          resource itself.
182  *        * When a scratch resource is ref'ed it will not be returned from the
183  *          cache for a subsequent cache request until all refs are released. This facilitates using
184  *          a scratch key for multiple render-to-texture scenarios. An example is a separable blur:
185  *
186  *  GrTexture* texture[2];
187  *  texture[0] = get_scratch_texture(scratchKey);
188  *  texture[1] = get_scratch_texture(scratchKey); // texture[0] is already owned so we will get a
189  *                                                // different one for texture[1]
190  *  draw_mask(texture[0], path);        // draws path mask to texture[0]
191  *  blur_x(texture[0], texture[1]);     // blurs texture[0] in y and stores result in texture[1]
192  *  blur_y(texture[1], texture[0]);     // blurs texture[1] in y and stores result in texture[0]
193  *  texture[1]->unref();  // texture 1 can now be recycled for the next request with scratchKey
194  *  consume_blur(texture[0]);
195  *  texture[0]->unref();  // texture 0 can now be recycled for the next request with scratchKey
196  */
197 class ScratchKey : public ResourceKey {
198 public:
199     /** Uniquely identifies the type of resource that is cached as scratch. */
200     typedef uint32_t ResourceType;
201 
202     /** Generate a unique ResourceType. */
203     static ResourceType GenerateResourceType();
204 
205     /** Creates an invalid scratch key. It must be initialized using a Builder object before use. */
ScratchKey()206     ScratchKey() {}
207 
ScratchKey(const ScratchKey & that)208     ScratchKey(const ScratchKey& that) { *this = that; }
209 
resourceType()210     ResourceType resourceType() const { return this->domain(); }
211 
212     ScratchKey& operator=(const ScratchKey& that) {
213         this->ResourceKey::operator=(that);
214         return *this;
215     }
216 
217     bool operator==(const ScratchKey& that) const { return this->ResourceKey::operator==(that); }
218     bool operator!=(const ScratchKey& that) const { return !(*this == that); }
219 
220     class Builder : public ResourceKey::Builder {
221     public:
Builder(ScratchKey * key,ResourceType type,int data32Count)222         Builder(ScratchKey* key, ResourceType type, int data32Count)
223                 : ResourceKey::Builder(key, type, data32Count) {}
224     };
225 };
226 
227 /**
228  * A key that allows for exclusive use of a resource for a use case (AKA "domain"). There are three
229  * rules governing the use of unique keys:
230  *        * Only one resource can have a given unique key at a time. Hence, "unique".
231  *        * A resource can have at most one unique key at a time.
232  *        * Unlike scratch keys, multiple requests for a unique key will return the same
233  *          resource even if the resource already has refs.
234  * This key type allows a code path to create cached resources for which it is the exclusive user.
235  * The code path creates a domain which it sets on its keys. This guarantees that there are no
236  * cross-domain collisions.
237  *
238  * Unique keys preempt scratch keys. While a resource has a unique key it is inaccessible via its
239  * scratch key. It can become scratch again if the unique key is removed.
240  */
241 class UniqueKey : public ResourceKey {
242 public:
243     typedef uint32_t Domain;
244     /** Generate a Domain for unique keys. */
245     static Domain GenerateDomain();
246 
247     /** Creates an invalid unique key. It must be initialized using a Builder object before use. */
UniqueKey()248     UniqueKey() : fTag(nullptr) {}
249 
UniqueKey(const UniqueKey & that)250     UniqueKey(const UniqueKey& that) { *this = that; }
251 
252     UniqueKey& operator=(const UniqueKey& that) {
253         this->ResourceKey::operator=(that);
254         this->setCustomData(sk_ref_sp(that.getCustomData()));
255         fTag = that.fTag;
256         return *this;
257     }
258 
259     bool operator==(const UniqueKey& that) const { return this->ResourceKey::operator==(that); }
260     bool operator!=(const UniqueKey& that) const { return !(*this == that); }
261 
setCustomData(sk_sp<SkData> data)262     void setCustomData(sk_sp<SkData> data) { fData = std::move(data); }
getCustomData()263     SkData* getCustomData() const { return fData.get(); }
refCustomData()264     sk_sp<SkData> refCustomData() const { return fData; }
265 
tag()266     const char* tag() const { return fTag; }
267 
data()268     const uint32_t* data() const { return this->ResourceKey::data(); }
269 
270 #ifdef SK_DEBUG
domain()271     uint32_t domain() const { return this->ResourceKey::domain(); }
dataSize()272     size_t dataSize() const { return this->ResourceKey::dataSize(); }
273 
dump(const char * label)274     void dump(const char* label) const {
275         SkDebugf("%s tag: %s\n", label, fTag ? fTag : "None");
276         this->ResourceKey::dump();
277     }
278 #endif
279 
280     class Builder : public ResourceKey::Builder {
281     public:
282         Builder(UniqueKey* key, Domain type, int data32Count, const char* tag = nullptr)
Builder(key,type,data32Count)283                 : ResourceKey::Builder(key, type, data32Count) {
284             key->fTag = tag;
285         }
286 
287         /** Used to build a key that wraps another key and adds additional data. */
288         Builder(UniqueKey* key, const UniqueKey& innerKey, Domain domain, int extraData32Cnt,
289                 const char* tag = nullptr)
290                 : ResourceKey::Builder(key,
291                                        domain,
292                                        Data32CntForInnerKey(innerKey) + extraData32Cnt) {
293             SkASSERT(&innerKey != key);
294             // add the inner key to the end of the key so that op[] can be indexed normally.
295             uint32_t* innerKeyData = &this->operator[](extraData32Cnt);
296             const uint32_t* srcData = innerKey.data();
297             (*innerKeyData++) = innerKey.domain();
298             memcpy(innerKeyData, srcData, innerKey.dataSize());
299             key->fTag = tag;
300         }
301 
302     private:
Data32CntForInnerKey(const UniqueKey & innerKey)303         static int Data32CntForInnerKey(const UniqueKey& innerKey) {
304             // key data + domain
305             return SkToInt((innerKey.dataSize() >> 2) + 1);
306         }
307     };
308 
309 private:
310     sk_sp<SkData> fData;
311     const char* fTag;
312 };
313 
314 /**
315  * It is common to need a frequently reused UniqueKey where the only requirement is that the key
316  * is unique. These macros create such a key in a thread safe manner so the key can be truly global
317  * and only constructed once.
318  */
319 
320 /** Place outside of function/class definitions. */
321 #define SKGPU_DECLARE_STATIC_UNIQUE_KEY(name) static SkOnce name##_once
322 
323 /** Place inside function where the key is used. */
324 #define SKGPU_DEFINE_STATIC_UNIQUE_KEY(name)                                \
325     static SkAlignedSTStorage<1, skgpu::UniqueKey> name##_storage;          \
326     name##_once(skgpu::skgpu_init_static_unique_key_once, &name##_storage); \
327     static const skgpu::UniqueKey& name =                                   \
328         *reinterpret_cast<skgpu::UniqueKey*>(name##_storage.get())
329 
skgpu_init_static_unique_key_once(SkAlignedSTStorage<1,UniqueKey> * keyStorage)330 static inline void skgpu_init_static_unique_key_once(SkAlignedSTStorage<1, UniqueKey>* keyStorage) {
331     UniqueKey* key = new (keyStorage->get()) UniqueKey;
332     UniqueKey::Builder builder(key, UniqueKey::GenerateDomain(), 0);
333 }
334 
335 // The cache listens for these messages to purge junk resources proactively.
336 class UniqueKeyInvalidatedMessage {
337 public:
338     UniqueKeyInvalidatedMessage() = default;
339     UniqueKeyInvalidatedMessage(const UniqueKey& key,
340                                 uint32_t contextUniqueID,
341                                 bool inThreadSafeCache = false)
fKey(key)342             : fKey(key), fContextID(contextUniqueID), fInThreadSafeCache(inThreadSafeCache) {
343         SkASSERT(SK_InvalidUniqueID != contextUniqueID);
344     }
345 
346     UniqueKeyInvalidatedMessage(const UniqueKeyInvalidatedMessage&) = default;
347 
348     UniqueKeyInvalidatedMessage& operator=(const UniqueKeyInvalidatedMessage&) = default;
349 
key()350     const UniqueKey& key() const { return fKey; }
contextID()351     uint32_t contextID() const { return fContextID; }
inThreadSafeCache()352     bool inThreadSafeCache() const { return fInThreadSafeCache; }
353 
354 private:
355     UniqueKey fKey;
356     uint32_t fContextID = SK_InvalidUniqueID;
357     bool fInThreadSafeCache = false;
358 };
359 
SkShouldPostMessageToBus(const UniqueKeyInvalidatedMessage & msg,uint32_t msgBusUniqueID)360 static inline bool SkShouldPostMessageToBus(const UniqueKeyInvalidatedMessage& msg,
361                                             uint32_t msgBusUniqueID) {
362     return msg.contextID() == msgBusUniqueID;
363 }
364 
365 class UniqueKeyInvalidatedMsg_Graphite {
366 public:
367     UniqueKeyInvalidatedMsg_Graphite() = default;
UniqueKeyInvalidatedMsg_Graphite(const UniqueKey & key,uint32_t recorderID)368     UniqueKeyInvalidatedMsg_Graphite(const UniqueKey& key, uint32_t recorderID)
369             : fKey(key), fRecorderID(recorderID) {
370         SkASSERT(SK_InvalidUniqueID != fRecorderID);
371     }
372 
373     UniqueKeyInvalidatedMsg_Graphite(const UniqueKeyInvalidatedMsg_Graphite&) = default;
374 
375     UniqueKeyInvalidatedMsg_Graphite& operator=(const UniqueKeyInvalidatedMsg_Graphite&) = default;
376 
key()377     const UniqueKey& key() const { return fKey; }
recorderID()378     uint32_t recorderID() const { return fRecorderID; }
379 
380 private:
381     UniqueKey fKey;
382     uint32_t fRecorderID = SK_InvalidUniqueID;
383 };
384 
SkShouldPostMessageToBus(const UniqueKeyInvalidatedMsg_Graphite & msg,uint32_t msgBusUniqueID)385 static inline bool SkShouldPostMessageToBus(const UniqueKeyInvalidatedMsg_Graphite& msg,
386                                             uint32_t msgBusUniqueID) {
387     return msg.recorderID() == msgBusUniqueID;
388 }
389 
390 /**
391  * This is a special key that doesn't have domain and can only be used in a dedicated cache.
392  * Unlike UniqueKey & ScratchKey, this key has compile time size (in number of uint32_t)
393  * and doesn't need dynamic allocations. In comparison, UniqueKey & ScratchKey will need
394  * dynamic allocation if a key is larger than 6 uint32_ts.
395  */
396 template <size_t SizeInUInt32>
397 class FixedSizeKey {
398 public:
hash()399     uint32_t hash() const { return fHash; }
400 
401     bool operator==(const FixedSizeKey& that) const {
402         return fHash == that.fHash &&
403                0 == memcmp(fPackedData, that.fPackedData, sizeof(fPackedData));
404     }
405 
406     class Builder {
407     public:
Builder(FixedSizeKey * key)408         Builder(FixedSizeKey* key) : fKey(key) {}
409 
finish()410         void finish() {
411             SkASSERT(fKey);
412             fKey->fHash = ResourceKeyHash(fKey->fPackedData, sizeof(fKey->fPackedData));
413             fKey = nullptr;
414         }
415 
416         uint32_t& operator[](int dataIdx) {
417             SkASSERT(fKey);
418             SkASSERT(SkToU32(dataIdx) < SizeInUInt32);
419             return fKey->fPackedData[dataIdx];
420         }
421 
422     private:
423         FixedSizeKey* fKey = nullptr;
424     };
425 
426     struct Hash {
operatorHash427         uint32_t operator()(const FixedSizeKey& key) const { return key.hash(); }
428     };
429 
430 private:
431     uint32_t fHash = 0;
432     uint32_t fPackedData[SizeInUInt32] = {};
433 };
434 
435 } // namespace skgpu
436 
437 #endif // skgpu_ResourceKey_DEFINED
438