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