| 1 |
/* |
| 2 |
* Copyright 2022 Google LLC |
| 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_graphite_Resource_DEFINED |
| 9 |
#define skgpu_graphite_Resource_DEFINED |
| 10 |
|
| 11 |
#include "include/gpu/GpuTypes.h" |
| 12 |
#include "include/private/base/SkMutex.h" |
| 13 |
#include "src/gpu/GpuTypesPriv.h" |
| 14 |
#include "src/gpu/graphite/GraphiteResourceKey.h" |
| 15 |
#include "src/gpu/graphite/ResourceTypes.h" |
| 16 |
|
| 17 |
#include <atomic> |
| 18 |
#include <functional> |
| 19 |
#include <string> |
| 20 |
#include <string_view> |
| 21 |
|
| 22 |
class SkMutex; |
| 23 |
class SkTraceMemoryDump; |
| 24 |
|
| 25 |
namespace skgpu::graphite { |
| 26 |
|
| 27 |
class GlobalCache; |
| 28 |
class ResourceCache; |
| 29 |
class SharedContext; |
| 30 |
class Texture; |
| 31 |
|
| 32 |
/** |
| 33 |
* Base class for objects that can be kept in the ResourceCache and created or fetched by a |
| 34 |
* ResourceProvider. A ResourceProvider controls the creation of a Resource and determines how |
| 35 |
* its lifecycle is managed (e.g. is it cached, shareable, etc.). Once created, however, the |
| 36 |
* Resource's lifecycle is controlled by the provider's ResourceCache so that GPU resources can |
| 37 |
* be reused when ref counts reach 0; a Resource that has no more refs and does not belong to a |
| 38 |
* cache is simply deleted. |
| 39 |
* |
| 40 |
* Resource Threading Model |
| 41 |
* ======================== |
| 42 |
* |
| 43 |
* A Resource is allowed to be used in multiple threads and be deleted from any thread safely. |
| 44 |
* Resource refs are broken into several categories: usage (public C++ references), command buffer |
| 45 |
* (representing active GPU work), and internal (managed by the ResourceCache). Non-cache refs can |
| 46 |
* be removed and reach zero from any thread and be safely returned to the ResourceCache. Unlike |
| 47 |
* Resource, ResourceCache and ResourceProvider are not thread safe and are only used by a single |
| 48 |
* thread. |
| 49 |
* |
| 50 |
* Active Threads: |
| 51 |
* 1. Context thread: this is the primary thread where Recordings are inserted and GPU work is |
| 52 |
* scheduled. |
| 53 |
* 2. Cache thread: this is the thread that the ResourceCache is associated with. This can be the |
| 54 |
* same as the context thread if the ResourceCache and ResourceProvider belong to the Context. |
| 55 |
* However, a Recorder's ResourceCache/Provider can be used on an arbitrary single thread the |
| 56 |
* client is using for that specific Recorder. |
| 57 |
* 3. Usage threads: once created on the cache thread, a Resource is not restricted to just the |
| 58 |
* cache thread and context thread. The Resource can have references held on any other |
| 59 |
* Recorder's thread if multiple work streams use the resource, or may end up held in other |
| 60 |
* client threads naturally as part of their lifecycle management of Skia's API objects. |
| 61 |
* - A Resource could be accessed by an arbitrary number of usage threads. |
| 62 |
* |
| 63 |
* Reference Types: |
| 64 |
* 1. Usage refs: a Resource starts with a single usage ref when created by the ResourceProvider, |
| 65 |
* which is then given to the caller as an `sk_sp<R>`. Once it escapes the ResourceProvider, |
| 66 |
* operations on the `sk_sp` can add more usage refs. Usage refs track the liveness of the |
| 67 |
* Resource from C++ code external to the ResourceCache (either higher-level Skia/Graphite |
| 68 |
* objects or client objects keeping it alive). |
| 69 |
* 2. Command buffer refs: every Resource used in a command buffer has command buffer refs added |
| 70 |
* when referencing work (e.g. a Recording) is inserted into the Context. These refs are |
| 71 |
* released when the command buffer's finish procs are called and it's known that the GPU-side |
| 72 |
* operations are completely done with the Resources. |
| 73 |
* 3. Cache ref: A ResourceProvider can choose to register a Resource with its ResourceCache at |
| 74 |
* creation time before returning the Resource. The ResourceCache holds a single ref on every |
| 75 |
* Resource registered with it until the cache is shutdown. |
| 76 |
* 4. Return queue ref: At most one ref held while the Resource is being added to the cache's |
| 77 |
* return queue and held until it's removed from the queue on the cache thread. |
| 78 |
|
| 79 |
* |
| 80 |
* Lifecycle: |
| 81 |
* 1. Initialization: all Resources are created via the ResourceProvider, which also coordinates |
| 82 |
* with its ResourceCache. If an existing resource can't be used, a new one is created. The |
| 83 |
* initialization phase is the period between when the provider creates the Resource object and |
| 84 |
* when it's returned to the caller. The resource can be assigned a key and added to the cache |
| 85 |
* at this point. |
| 86 |
* 2. Reusable: when all usage refs are removed, some Resources can become reusable and move into |
| 87 |
* the return queue (on any thread). On the cache thread, the queue is regularly processed and |
| 88 |
* resources that remain reusable are tracked appropriately within the cache. |
| 89 |
* - Resources that are only modified via command buffer operations can be reusable when |
| 90 |
* usage refs reach 0 because future modifications won't conflict with any outstanding |
| 91 |
* work that is holding current command buffer refs. |
| 92 |
* - Resources that can be modified directly (e.g. mapped buffers) are not reusable until |
| 93 |
* there are no usage or command buffer refs to ensure modifications don't become visible |
| 94 |
* to the GPU before intended. |
| 95 |
* 3. Purgeable: when all usage refs and command buffer refs are removed, a Resource is purgeable. |
| 96 |
* Resources that weren't considered reusable while having outstanding command buffer refs are |
| 97 |
* now also reusable. Purgeable resources are also added to the return queue so that the cache |
| 98 |
* can decide whether or not to keep the resource alive (based on budget limits). |
| 99 |
* 4. Destruction: if a Resource has no refs at all, it can be destroyed. A purgeable resource |
| 100 |
* that was not registered with a cache will never have a cache ref or return queue ref so is |
| 101 |
* immediately destroyed. When a cache processes a purgeable resource from the return queue, it |
| 102 |
* can choose to drop its cache ref (and return queue ref) so the resource will be destroyed. |
| 103 |
* Purgeable resources that had been kept alive for reuse can also be dropped by the cache when |
| 104 |
* it is being purged (for budget or idleness reasons). |
| 105 |
* 5. Shutdown: when a Context or Recorder are deleted, its ResourceCache is shutdown. The cache |
| 106 |
* removes all of its cache refs and blocks any further changes to the return queue. This |
| 107 |
* allows Resources to be destroyed ASAP when they become purgeable instead of going back to |
| 108 |
* the shutdown cache. However, every Resource registered with the cache keeps the cache alive. |
| 109 |
* Once every cached resource is destroyed, the cache itself will be destroyed. |
| 110 |
* |
| 111 |
* Ref Counting and State Transition Properties: |
| 112 |
* - The cache ref can only be added during initialization (it is uniquely held and on the cache |
| 113 |
* thread). |
| 114 |
* - The cache ref can only be removed by the ResourceCache on the cache thread (purging |
| 115 |
* operations and shutdown are all single-threaded functions on the cache thread). |
| 116 |
* - The return queue ref can be added by any thread when the Resource transitions to reusable |
| 117 |
* and/or purgeable. |
| 118 |
* - The return queue ref cannot be added more than once; if the Resource goes through multiple |
| 119 |
* transitions before being processed by the cache, the second transition does not need to be |
| 120 |
* put into the queue. |
| 121 |
* - The return queue ref cannot be added directly, but only as part of a usage/CB unref that |
| 122 |
* transitions the resource to being reusable or purgeable. The return queue ref is added |
| 123 |
* atomically with the other unref. |
| 124 |
* - The return queue ref can only be removed by the resource cache on the cache thread, unless |
| 125 |
* the cache was shutdown already. In that case the ref is removed by the adding thread. The |
| 126 |
* cache will only remove the return queue ref *after* the resource is removed from the queue. |
| 127 |
* - If the resource was not registered with a cache during initialization, its cache and return |
| 128 |
* queue refs will always be zero. |
| 129 |
* - Regular usage refs can only be added when there was prior usage ref held by the caller. This |
| 130 |
* can happen on any thread. |
| 131 |
* - Command buffer refs can only be added if the resource has a usage ref (that is held through |
| 132 |
* the CB ref'ing operation). This can happen on any thread (although in practice just the |
| 133 |
* context thread). |
| 134 |
* - A command buffer ref cannot be promoted back to a usage ref. |
| 135 |
* - Both command buffer and usage refs can be removed from any thread (although CB refs are |
| 136 |
* likely to be unreffed on the context thread). |
| 137 |
* - When the usage ref count reaches zero, it can only become non-zero via the cache thread by |
| 138 |
* actions of its ResourceCache. |
| 139 |
* - Actions predicated on usage refs being 0 on the cache thread are safe. |
| 140 |
* - Such actions on other threads are not safe because the cache thread could process the |
| 141 |
* return queue and reuse the resource, or skip the return queue entirely for shareable |
| 142 |
* resources. |
| 143 |
* - When the resource becomes purgeable, it can only become non-purgeable on the cache thread |
| 144 |
* by action of the ResourceCache. |
| 145 |
* - Since there are no other usage refs (beyond what the cache might re-add), no other |
| 146 |
* thread can re-add a command buffer ref. |
| 147 |
* |
| 148 |
* |
| 149 |
* Resource Thread Safe Labeling Model |
| 150 |
* =================================== |
| 151 |
* |
| 152 |
* Every Resource object should have a label. Backend objects may additionally store a backend |
| 153 |
* resource label which can be useful for memory dumps or other debugging. A Caps flag controls |
| 154 |
* whether or not backend labels are enabled. |
| 155 |
* |
| 156 |
* A resource's label can change over time as it gets reused. This can happen on any thread at |
| 157 |
* almost any time. These label updates must be synchronized to its backend resource label, and both |
| 158 |
* update steps must be thread safe. |
| 159 |
* |
| 160 |
* To enforce this, a Resource's label can only be updated at certain points within its lifecycle |
| 161 |
* (depending upon its shareability as outlined below). Outside of initial resource creation and |
| 162 |
* cache insertion (at which point there is no contention for explicitly and immediately syncing a |
| 163 |
* new backend resource's label), propagating label updates to existing backend objects will be |
| 164 |
* deferred until recording insertion. This way, previously-set backend labels are guaranteed to |
| 165 |
* remain stable during a GPU frame capture. |
| 166 |
* |
| 167 |
* Resource thread safe label update policy based on shareability: |
| 168 |
* TODO(b/387505250): Currently, these policies are enforced for shareable resources. Implement and |
| 169 |
* enforce backend resource label update policies for non-shareable and scratch resources. |
| 170 |
* - Any resource can have its label set when it is first created or inserted into the cache. |
| 171 |
* - A shareable resource can be returned from the cache at any time, and its label should not |
| 172 |
* change upon reuse. Therefore, shareable resource labels are effectively only set once. |
| 173 |
* - A non-shareable resource will never returned from the cache for simultaneous usage. |
| 174 |
* Therefore, its label can be set by the ResourceCache when it returns a resource from |
| 175 |
* findOrCreate(...), re-adding an initial usage ref. |
| 176 |
* - Scratch resource labels have complex label management since they can be changed across |
| 177 |
* recorder threads and within the same recorder thread as it is used for different purposes. |
| 178 |
* - Within a recording, a scratch resource's label is the union of all TextureProxy labels |
| 179 |
* instantiated with the same resource. |
| 180 |
* - Scratch resources are only ever used for Graphite-internal rendering purposes, so we |
| 181 |
* know all of their possible usages at compile time. These usages can be represented as a |
| 182 |
* bitmask. The flags within the mask can then be mapped to constant strings which |
| 183 |
* represent the various possible scratch resource usages in order to generate a label. |
| 184 |
* - Storing usages as a bitmask allows us to quickly determine whether a resource's usage |
| 185 |
* is actually different than before. If it does not differ, then we can avoid the |
| 186 |
* overhead of generating a union of strings and updating the label. |
| 187 |
* - Across recorder threads, we don’t want to intermingle proxy labels on the resource’s |
| 188 |
* final label. To manage this while making it such that backend scratch resource labels |
| 189 |
* can be synchronized during recording insertion, the ScratchResourceManager will |
| 190 |
* maintain a label map for all the scratch resources it creates. This map will only |
| 191 |
* be modifiable on the recorder thread, becoming immutable after snap() and being |
| 192 |
* transferred on to the Recording. |
| 193 |
*/ |
| 194 |
class Resource { |
| 195 |
enum class RefType { |
| 196 |
kUsage, // Counts controlled by `sk_sp` and tracks liveness from external C++ code. |
| 197 |
kCommandBuffer, // Incremented in Context::insertRecording, decremented by finish procs. |
| 198 |
kCache, // At most 1 ref, added in registerWithCache(), removed on cache shutdown or purge. |
| 199 |
kReturnQueue, // At most 1 ref, held while in the cache's return queue. |
| 200 |
}; |
| 201 |
|
| 202 |
public: |
| 203 |
Resource(const Resource&) = delete; |
| 204 |
Resource(Resource&&) = delete; |
| 205 |
Resource& operator=(const Resource&) = delete; |
| 206 |
Resource& operator=(Resource&&) = delete; |
| 207 |
|
| 208 |
// Adds a usage ref to the resource. Named ref so we can easily manage usage refs with sk_sp. |
| 209 |
void ref() const { |
| 210 |
// Only the cache should be able to add the first usage ref to a resource. |
| 211 |
this->addRef<RefType::kUsage>(); |
| 212 |
} |
| 213 |
|
| 214 |
// Removes a usage ref from the resource |
| 215 |
void unref() const { |
| 216 |
this->removeRef<RefType::kUsage>(); |
| 217 |
} |
| 218 |
|
| 219 |
// Adds a command buffer ref to the resource |
| 220 |
void refCommandBuffer() const { |
| 221 |
this->addRef<RefType::kCommandBuffer>(); |
| 222 |
} |
| 223 |
|
| 224 |
// Removes a command buffer ref from the resource |
| 225 |
void unrefCommandBuffer() const { |
| 226 |
this->removeRef<RefType::kCommandBuffer>(); |
| 227 |
} |
| 228 |
|
| 229 |
// Whether the resource is currently in use by the GPU: any resource that is used in a command |
| 230 |
// buffer is considered in use by the GPU. |
| 231 |
// |
| 232 |
// NOTE: This is currently only correct for textures, hence the name. Once the rest of the |
| 233 |
// resources use the command buffer ref instead of usage ref appropriately, this can be made |
| 234 |
// more generaic. |
| 235 |
bool isTextureBusyOnGPU() const { |
| 236 |
return (fRefs.load(std::memory_order_acquire) & RefMask(RefType::kCommandBuffer)) != 0; |
| 237 |
} |
| 238 |
|
| 239 |
Ownership ownership() const { return fOwnership; } |
| 240 |
bool requiresPrepareForReturnToCache() const { return fRequiresPrepareForReturnToCache; } |
| 241 |
|
| 242 |
Budgeted budgeted() const { return fBudgeted; } |
| 243 |
Shareable shareable() const { return fShareable; } |
| 244 |
const GraphiteResourceKey& key() const { return fKey; } |
| 245 |
|
| 246 |
// Retrieves the amount of GPU memory used by this resource in bytes. It is approximate since we |
| 247 |
// aren't aware of additional padding or copies made by the driver. |
| 248 |
size_t gpuMemorySize() const { return fGpuMemorySize; } |
| 249 |
|
| 250 |
class UniqueID { |
| 251 |
public: |
| 252 |
UniqueID() = default; |
| 253 |
|
| 254 |
explicit UniqueID(uint32_t id) : fID(id) {} |
| 255 |
|
| 256 |
uint32_t asUInt() const { return fID; } |
| 257 |
|
| 258 |
bool operator==(const UniqueID& other) const { return fID == other.fID; } |
| 259 |
bool operator!=(const UniqueID& other) const { return !(*this == other); } |
| 260 |
|
| 261 |
private: |
| 262 |
uint32_t fID = SK_InvalidUniqueID; |
| 263 |
}; |
| 264 |
|
| 265 |
// Gets an id that is unique for this Resource object. It is static in that it does not change |
| 266 |
// when the content of the Resource object changes. This will never return 0. |
| 267 |
UniqueID uniqueID() const { return fUniqueID; } |
| 268 |
|
| 269 |
const char* getLabel() const { return fLabel.c_str(); } |
| 270 |
|
| 271 |
// We allow the label on a Resource to change when used for a different function. For example |
| 272 |
// when reusing a scratch Texture we can change the label to match callers current use. |
| 273 |
void setLabel(std::string_view label) { |
| 274 |
if (fLabel == label) { |
| 275 |
return; |
| 276 |
} |
| 277 |
|
| 278 |
fLabel = label; |
| 279 |
|
| 280 |
if (!fLabel.empty()) { |
| 281 |
const std::string fullLabel = "Skia_" + fLabel; |
| 282 |
this->setBackendLabel(fullLabel.c_str()); |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
// Tests whether a object has been abandoned or released. All objects will be in this state |
| 287 |
// after their creating Context is destroyed or abandoned. |
| 288 |
// |
| 289 |
// @return true if the object has been released or abandoned, |
| 290 |
// false otherwise. |
| 291 |
// TODO: As of now this function isn't really needed because in freeGpuData we are always |
| 292 |
// deleting this object. However, I want to implement all the purging logic first to make sure |
| 293 |
// we don't have a use case for calling internalDispose but not wanting to delete the actual |
| 294 |
// object yet. |
| 295 |
bool wasDestroyed() const { return fSharedContext == nullptr; } |
| 296 |
|
| 297 |
// Describes the type of gpu resource that is represented by the implementing |
| 298 |
// class (e.g. texture, buffer, etc). This data is used for diagnostic |
| 299 |
// purposes by dumpMemoryStatistics(). |
| 300 |
// |
| 301 |
// The value returned is expected to be long lived and will not be copied by the caller. |
| 302 |
virtual const char* getResourceType() const = 0; |
| 303 |
|
| 304 |
virtual const Texture* asTexture() const { return nullptr; } |
| 305 |
|
| 306 |
#if defined(GPU_TEST_UTILS) |
| 307 |
bool testingShouldDeleteASAP() const { return fDeleteASAP == DeleteASAP::kYes; } |
| 308 |
#endif |
| 309 |
|
| 310 |
protected: |
| 311 |
Resource(const SharedContext*, |
| 312 |
Ownership, |
| 313 |
size_t gpuMemorySize, |
| 314 |
bool reusableRequiresPurgeable = false, |
| 315 |
bool requiresPrepareForReturnToCache = false); |
| 316 |
virtual ~Resource(); |
| 317 |
|
| 318 |
const SharedContext* sharedContext() const { return fSharedContext; } |
| 319 |
|
| 320 |
// Needs to be protected for DawnBuffer's emscripten prepareForReturnToCache |
| 321 |
void setDeleteASAP() { fDeleteASAP = DeleteASAP::kYes; } |
| 322 |
|
| 323 |
using TakeRefFunc = void (*)(void* ctx); |
| 324 |
|
| 325 |
private: |
| 326 |
/////////////////////////////////////////////////////////////////////////////////////////////// |
| 327 |
// The following set of functions are only meant to be called by the [Global|Proxy]Cache. We |
| 328 |
// don't want them public general users of a Resource, but they also aren't purely internal. |
| 329 |
/////////////////////////////////////////////////////////////////////////////////////////////// |
| 330 |
friend class ProxyCache; // for setDeleteASAP and updateAccessTime |
| 331 |
friend GlobalCache; // for lastAccessTime and updateAccessTime |
| 332 |
|
| 333 |
enum class DeleteASAP : bool { |
| 334 |
kNo = false, |
| 335 |
kYes = true, |
| 336 |
}; |
| 337 |
|
| 338 |
DeleteASAP shouldDeleteASAP() const { return fDeleteASAP; } |
| 339 |
|
| 340 |
// In the ResourceCache this is called whenever a Resource is moved into the purgeableQueue. It |
| 341 |
// may also be called by the ProxyCache and GlobalCache to track the time on Resources they are |
| 342 |
// holding on to. |
| 343 |
void updateAccessTime() { fLastAccess = skgpu::StdSteadyClock::now(); } |
| 344 |
skgpu::StdSteadyClock::time_point lastAccessTime() const { return fLastAccess; } |
| 345 |
|
| 346 |
/////////////////////////////////////////////////////////////////////////////////////////////// |
| 347 |
// The following set of functions are only meant to be called by the ResourceCache. We don't |
| 348 |
// want them public general users of a Resource, but they also aren't purely internal calls. |
| 349 |
/////////////////////////////////////////////////////////////////////////////////////////////// |
| 350 |
friend class ResourceCache; |
| 351 |
|
| 352 |
void setBudgeted(Budgeted budgeted) { |
| 353 |
SkASSERT(budgeted == Budgeted::kNo || fOwnership == Ownership::kOwned); |
| 354 |
fBudgeted = budgeted; |
| 355 |
} |
| 356 |
void setShareable(Shareable shareable) { |
| 357 |
SkASSERT(shareable == Shareable::kNo || fBudgeted == Budgeted::kYes); |
| 358 |
fShareable = shareable; |
| 359 |
} |
| 360 |
|
| 361 |
void setAvailableForReuse(bool avail) { fAvailableForReuse = avail; } |
| 362 |
bool isAvailableForReuse() const { return fAvailableForReuse; } |
| 363 |
|
| 364 |
uint32_t lastUseToken() const { return fLastUseToken; } |
| 365 |
void setLastUseToken(uint32_t token) { fLastUseToken = token; } |
| 366 |
|
| 367 |
void setNextInReturnQueue(Resource* next) { |
| 368 |
SkASSERT(this->hasReturnQueueRef()); |
| 369 |
fNextInReturnQueue = next; |
| 370 |
} |
| 371 |
|
| 372 |
int* accessCacheIndex() const { return &fCacheArrayIndex; } |
| 373 |
const ResourceCache* cache() const { return fReturnCache.get(); } |
| 374 |
|
| 375 |
// If possible, queries the backend API to check the current allocation size of the gpu |
| 376 |
// resource and updates the tracked value. This is specifically useful for Vulkan backends which |
| 377 |
// use lazy allocated memory for "memoryless" resources. Ideally that memory should stay zero |
| 378 |
// throughout its usage, but certain usage patterns can trigger the device to commit real memory |
| 379 |
// to the resource. So this will allow us to have a more accurate tracking of our memory usage. |
| 380 |
void updateGpuMemorySize() { fGpuMemorySize = this->onUpdateGpuMemorySize(); } |
| 381 |
|
| 382 |
// Dumps memory usage information for this Resource to traceMemoryDump. |
| 383 |
void dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump, bool inPurgeableQueue) const; |
| 384 |
|
| 385 |
/** |
| 386 |
* If the resource has a non-shareable key then this gives the resource subclass an opportunity |
| 387 |
* to prepare itself to re-enter the cache. The ResourceCache extends its privilege to take the |
| 388 |
* first UsageRef to this function via takeRef. If takeRef is called this resource will not |
| 389 |
* immediately enter the cache but will be re-reprocessed when the usage ref count again reaches |
| 390 |
* zero. |
| 391 |
* |
| 392 |
* Return true if takeRef() was invoked. |
| 393 |
*/ |
| 394 |
virtual bool prepareForReturnToCache(TakeRefFunc takeRef, void* takeRefCtx) { return false; } |
| 395 |
|
| 396 |
// Adds a cache ref to the resource. May only be called once. |
| 397 |
void registerWithCache(sk_sp<ResourceCache>, const GraphiteResourceKey&, Budgeted, Shareable); |
| 398 |
|
| 399 |
// This version of ref allows adding a ref when the usage count is 0. This should only be called |
| 400 |
// from the ResourceCache. |
| 401 |
void initialUsageRef() const { |
| 402 |
this->addRef<RefType::kUsage, /*MustHaveUsageRefs=*/false>(); |
| 403 |
} |
| 404 |
|
| 405 |
// Removes a cache ref from the resource. The unref here should only ever be called from the |
| 406 |
// ResourceCache and only in the Recorder/Context thread the ResourceCache is part of. |
| 407 |
void unrefCache() const { |
| 408 |
SkASSERT(fReturnCache); |
| 409 |
this->removeRef<RefType::kCache>(); |
| 410 |
} |
| 411 |
|
| 412 |
// Removes the return queue ref that was held while the Resource was in the queue. This can only |
| 413 |
// be called by the ResourceCache on its thread. It should not be called after unrefCache(). |
| 414 |
// It must only be called after the cache has removed the resource from its return queue. |
| 415 |
// |
| 416 |
// Returns {isReusable, isPurgeable} atomically based on the reference state when the return |
| 417 |
// queue ref was removed. `isReusable` is true if all refs affecting reusability were zero |
| 418 |
// when the queue ref was removed. `isPurgeable` is true if all usage and command buffer refs |
| 419 |
// were zero. |
| 420 |
// |
| 421 |
// If true is returned there are no other refs that could trigger a reusable or purgeable state |
| 422 |
// change. A resource that entered the return queue due to becoming reusable or purgeable only |
| 423 |
// happens if that ref count reached zero, so there should be no external ref holder (other than |
| 424 |
// the ResourceCache with its separate cache ref). However, unrefReturnQueue() is only called by |
| 425 |
// the ResourceCache so it won't be simultaneously handing out usage refs. |
| 426 |
// |
| 427 |
// If false is returned, it is possible for the resource to immediately become purgeable on |
| 428 |
// another thread but since this thread has released its return queue ref, the Resource will |
| 429 |
// simply go back in the next return queue. |
| 430 |
// |
| 431 |
// The cache should track the Resource based on this return value instead of re-checking the |
| 432 |
// ref counts as that would not be an atomic operation. |
| 433 |
std::tuple<bool, bool, Resource*> unrefReturnQueue() { |
| 434 |
// We must reset the fNextInReturnQueue value *before* removing the return queue ref, but we |
| 435 |
// need to return the old value to the ResourceCache so that it can continue iterating over |
| 436 |
// the linked list. |
| 437 |
Resource* next = fNextInReturnQueue; |
| 438 |
fNextInReturnQueue = nullptr; |
| 439 |
|
| 440 |
uint64_t origRefs = this->removeRef<RefType::kReturnQueue>(); |
| 441 |
|
| 442 |
// Since we should always have a cache ref when this is called, the Resource will never be |
| 443 |
// transitioning to having zero refs, although if `true` is returned the cache may choose to |
| 444 |
// then drop its cache ref. |
| 445 |
SkASSERT((origRefs & RefMask(RefType::kCache)) != 0); |
| 446 |
// `fReusableRefMask` always includes the ReturnQueue ref mask, and since we just removed |
| 447 |
// the return ref value, `origRefs` also includes the the ReturnQueue ref mask bit. We have |
| 448 |
// to compare to the ref mask to detect the case when the actual reusable refs are all zero. |
| 449 |
// Since PurgeableMask() does not add the ReturnQueue ref mask, it *can* compare to zero. |
| 450 |
return {(origRefs & fReusableRefMask) == RefMask(RefType::kReturnQueue), |
| 451 |
(origRefs & PurgeableMask()) == 0, |
| 452 |
next}; |
| 453 |
} |
| 454 |
|
| 455 |
#if defined(SK_DEBUG) || defined(GPU_TEST_UTILS) |
| 456 |
bool hasCacheRef() const { |
| 457 |
return (fRefs.load(std::memory_order_acquire) & RefMask(RefType::kCache)) != 0; |
| 458 |
} |
| 459 |
|
| 460 |
bool hasReturnQueueRef() const { |
| 461 |
return (fRefs.load(std::memory_order_acquire) & RefMask(RefType::kReturnQueue)) != 0; |
| 462 |
} |
| 463 |
|
| 464 |
bool inReturnQueue() const { |
| 465 |
return this->hasReturnQueueRef() && SkToBool(fNextInReturnQueue); |
| 466 |
} |
| 467 |
|
| 468 |
bool isUsableAsScratch() const { |
| 469 |
// This is only called by the ResourceCache, so the state of the Resource's refs won't |
| 470 |
// be changed by another thread when isReusable is true. |
| 471 |
uint64_t origRefs = fRefs.load(std::memory_order_acquire) & ~RefMask(RefType::kReturnQueue); |
| 472 |
bool isReusable = (origRefs & fReusableRefMask) == 0; |
| 473 |
return fShareable == Shareable::kScratch || (fShareable == Shareable::kNo && isReusable); |
| 474 |
} |
| 475 |
|
| 476 |
bool isPurgeable() const { |
| 477 |
// This is only called by the ResourceCache on its thread; if the usage and CB ref counts |
| 478 |
// are 0, the ResourceCache is the only way in which they can become non-zero again. |
| 479 |
return (fRefs.load(std::memory_order_acquire) & PurgeableMask()) == 0; |
| 480 |
} |
| 481 |
|
| 482 |
bool isUniquelyHeld() const { |
| 483 |
// This intentionally checks that the cache ref and return queue refs are 0, so that fRefs |
| 484 |
// is compared to the value it is initialized with. |
| 485 |
return fRefs.load(std::memory_order_acquire) == RefIncrement(RefType::kUsage); |
| 486 |
} |
| 487 |
|
| 488 |
bool hasAnyRefs() const { |
| 489 |
// Because all ref counts are packed into the same atomic, when this load is actually 0 |
| 490 |
// there are no other threads that can reach the object and add new refs (assuming a raw |
| 491 |
// pointer has never leaked). |
| 492 |
return fRefs.load(std::memory_order_acquire) != 0; |
| 493 |
} |
| 494 |
#endif |
| 495 |
|
| 496 |
/////////////////////////////////////////////////////////////////////////////////////////////// |
| 497 |
// The remaining calls are meant to be truely private (including virtuals for subclasses) |
| 498 |
/////////////////////////////////////////////////////////////////////////////////////////////// |
| 499 |
|
| 500 |
// Overridden to free GPU resources in the backend API. |
| 501 |
virtual void freeGpuData() = 0; |
| 502 |
|
| 503 |
// Overridden to call any release callbacks, if necessary |
| 504 |
virtual void invokeReleaseProc() {} |
| 505 |
|
| 506 |
// Overridden to set the label on the underlying GPU resource |
| 507 |
virtual void setBackendLabel(char const* label) {} |
| 508 |
|
| 509 |
// Overridden to add extra information to the memory dump. |
| 510 |
virtual void onDumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump, |
| 511 |
const char* dumpName) const {} |
| 512 |
|
| 513 |
|
| 514 |
// Overridden to calculate a more up-to-date size in bytes. |
| 515 |
virtual size_t onUpdateGpuMemorySize() { return fGpuMemorySize; } |
| 516 |
|
| 517 |
// Try to add the Resource to the cache's return queue for pending reuse. |
| 518 |
// This should only be called when there is a cache to return to, and the calling thread |
| 519 |
// successfully transitioned from no "return queue" ref to setting the return queue ref. |
| 520 |
// |
| 521 |
// Returns true if the cache accepted the Resource (in which case the set return ref should |
| 522 |
// remain set for the cache to remove). If false is returned, the caller should clear the |
| 523 |
// return queue ref (and possible dispose of the object). |
| 524 |
bool returnToCache() const; |
| 525 |
|
| 526 |
// Frees the object in the underlying 3D API *and* deletes the object itself. |
| 527 |
void internalDispose(); |
| 528 |
|
| 529 |
// Resource tracks its different ref counts packed into a single atomic 64-bit value. |
| 530 |
// The bits are split into subfields: |
| 531 |
// commandBufferRefs:31 e.g. RefMask(kCB) |
| 532 |
// usageRefs:31 RefMask(kUsage) |
| 533 |
// returnQueueRef: 1 RefMask(kReturnQueue) |
| 534 |
// cacheRefs:1 RefMask(kCache) |
| 535 |
// |
| 536 |
// RefIncrement() and RefMask() help access specific ref type's values. |
| 537 |
static constexpr uint64_t RefIncrement(RefType refType) { |
| 538 |
switch (refType) { |
| 539 |
case RefType::kCommandBuffer: return (uint64_t) 1 << 33; |
| 540 |
case RefType::kUsage: return (uint64_t) 1 << 2; |
| 541 |
case RefType::kCache: return (uint64_t) 1 << 1; |
| 542 |
case RefType::kReturnQueue: return (uint64_t) 1 << 0; |
| 543 |
} |
| 544 |
SkUNREACHABLE; |
| 545 |
} |
| 546 |
static inline constexpr uint64_t RefMask(RefType refType) { |
| 547 |
switch (refType) { |
| 548 |
case RefType::kCommandBuffer: return (((uint64_t)1 << 31) - 1) << 33; |
| 549 |
case RefType::kUsage: return (((uint64_t)1 << 31) - 1) << 2; |
| 550 |
case RefType::kCache: return 0b10; |
| 551 |
case RefType::kReturnQueue: return 0b01; |
| 552 |
} |
| 553 |
SkUNREACHABLE; |
| 554 |
} |
| 555 |
static inline constexpr uint64_t PurgeableMask() { |
| 556 |
return RefMask(RefType::kUsage) | RefMask(RefType::kCommandBuffer); |
| 557 |
} |
| 558 |
|
| 559 |
template <RefType kType, bool MustHaveUsageRefs=true> |
| 560 |
void addRef() const { |
| 561 |
static_assert(kType != RefType::kReturnQueue, "return queue refs cannot be added directly"); |
| 562 |
static constexpr uint64_t kRefIncrement = RefIncrement(kType); |
| 563 |
// No barrier required |
| 564 |
[[maybe_unused]] uint64_t origCnt = |
| 565 |
fRefs.fetch_add(kRefIncrement, std::memory_order_relaxed); |
| 566 |
// Require that there was an already held usage ref in order to add this new ref, |
| 567 |
// e.g. to add a command buffer ref, a usage ref must already be held; calling code can't |
| 568 |
// add usage refs if it wasn't explicitly handed out by the cache. |
| 569 |
SkASSERT(!MustHaveUsageRefs || (origCnt & RefMask(RefType::kUsage)) > 0); |
| 570 |
// And make sure that the specific type of ref did not overflow into another field |
| 571 |
SkASSERT((RefMask(kType) - (origCnt & RefMask(kType))) >= kRefIncrement); |
| 572 |
} |
| 573 |
|
| 574 |
template <RefType kType> |
| 575 |
uint64_t removeRef() const { |
| 576 |
static constexpr uint64_t kRefIncrement = RefIncrement(kType); |
| 577 |
|
| 578 |
uint64_t origRefs; |
| 579 |
if (kType == RefType::kCache || kType == RefType::kReturnQueue || !fReturnCache) { |
| 580 |
// Without a ResourceCache, or when it's a cache/return-queue unref, there is no |
| 581 |
// non-atomic work that has to happen so simply update the ref count. If the net ref |
| 582 |
// count reaches 0 we can safely delete the resource because no other thread will |
| 583 |
// increase the refs. |
| 584 |
origRefs = fRefs.fetch_sub(kRefIncrement, std::memory_order_acq_rel); |
| 585 |
SkASSERT((origRefs & RefMask(kType)) >= kRefIncrement); // had a ref to remove |
| 586 |
|
| 587 |
if (origRefs == kRefIncrement) { |
| 588 |
SkASSERT(!this->hasAnyRefs()); |
| 589 |
Resource* mutableThis = const_cast<Resource*>(this); |
| 590 |
mutableThis->internalDispose(); |
| 591 |
} |
| 592 |
} else { |
| 593 |
SkASSERT(kType == RefType::kCommandBuffer || kType == RefType::kUsage); |
| 594 |
// When removing a usage or CB ref and the resource is registered with the cache, |
| 595 |
// it may need to be returned to the cache. A resource can only be in the return queue |
| 596 |
// a single time and must remain alive until cache removes it from the queue. A CAS |
| 597 |
// loop is used to atomically decrement the ref and add the return queue ref. |
| 598 |
uint64_t nextRefs; |
| 599 |
bool needsReturn; |
| 600 |
do { |
| 601 |
origRefs = fRefs.load(std::memory_order_acquire); |
| 602 |
SkASSERT((origRefs & RefMask(kType)) >= kRefIncrement); // have a ref to remove |
| 603 |
|
| 604 |
// When unreffing a usage or command buffer ref, the Resource needs to return to |
| 605 |
// the queue when: |
| 606 |
// - it's not already in the return queue (return queue ref is 0) AND |
| 607 |
// - it's transitioning from non-reusable -> reusable OR non-purgeable -> purgeable |
| 608 |
// |
| 609 |
// Including RefMask(kReturnQueue) in the bitwise &'s before comparing to the |
| 610 |
// ref increment ensures that the return queue ref was 0 in origRefs. |
| 611 |
static constexpr uint64_t kPurgeableReturnMask = PurgeableMask() | |
| 612 |
RefMask(RefType::kReturnQueue); |
| 613 |
// fReusableRefMask should have added this bit added during construction. |
| 614 |
SkASSERT((fReusableRefMask & RefMask(RefType::kReturnQueue)) != 0); |
| 615 |
// This expression matches the above logic for returning because: |
| 616 |
// - Both kPurgeableReturnMask and fReusableRefMask include the return queue bit, |
| 617 |
// but kRefIncrement does not. The only way the comparisons can be true is if |
| 618 |
// the return queue bit is unset. |
| 619 |
// - When the resource is reusable only when purgeable, then both sides of the || |
| 620 |
// are identical because fReusableRefMask will equal kPurgeableReturnMask. |
| 621 |
// And if the == returns true, we know origRefs was non-zero and nextRefs will |
| 622 |
// be zero since it subtracts kRefIncrement. |
| 623 |
// - When the resource is reusable when just the usage refs reach 0, the purgeable |
| 624 |
// state transition works like before. But fReusableRefMask will mask out any |
| 625 |
// non-zero bits in the command buffer subfield. |
| 626 |
// - When kRefType==kUsage, the right-hand == will be true when origRefs had |
| 627 |
// one usage ref left and nextRefs holds zero. |
| 628 |
// - When kRefType==kCommandBuffer, the right-hand side of the || will always |
| 629 |
// be false because kRefIncrement will hold bits outside of fReusableRefMask. |
| 630 |
// This ensures that the non-reusable -> reusable transition occurs solely |
| 631 |
// on removing a usage ref. |
| 632 |
SkASSERT((kRefIncrement & RefMask(RefType::kReturnQueue)) == 0); |
| 633 |
needsReturn = ((origRefs & kPurgeableReturnMask) == kRefIncrement) || |
| 634 |
((origRefs & fReusableRefMask) == kRefIncrement); |
| 635 |
|
| 636 |
nextRefs = (origRefs - kRefIncrement) | |
| 637 |
(needsReturn ? RefMask(RefType::kReturnQueue) : 0); |
| 638 |
// If origRefs already included a return queue ref, nextRefs hasn't changed that |
| 639 |
SkASSERT((origRefs & RefMask(RefType::kReturnQueue)) == |
| 640 |
(nextRefs & RefMask(RefType::kReturnQueue)) || needsReturn); |
| 641 |
} while (!fRefs.compare_exchange_weak(origRefs, nextRefs, |
| 642 |
std::memory_order_release, |
| 643 |
std::memory_order_relaxed)); |
| 644 |
// NOTE: because RefMask(RefType::kReturnQueue) was included in the `needsReturn` check, |
| 645 |
// we know that it was unset in `origRefs`, and was added to `nextRefs`. The CAS ensures |
| 646 |
// that this was the thread that added the return queue ref if `needsReturn` is true |
| 647 |
// when the do-while loop exits. |
| 648 |
|
| 649 |
if (needsReturn && !this->returnToCache()) { |
| 650 |
// The cache rejected the resource, so we need to unset the "return queue" ref that |
| 651 |
// we added above, which may be the last ref keeping the object alive. |
| 652 |
SkASSERT(!fNextInReturnQueue); |
| 653 |
origRefs = this->removeRef<RefType::kReturnQueue>(); |
| 654 |
// so do not access *this* after this point! |
| 655 |
} |
| 656 |
// else we weren't returning the resource yet, or the cache is maintaining the return |
| 657 |
// ref until the return queue has been drained. |
| 658 |
} |
| 659 |
|
| 660 |
return origRefs; |
| 661 |
} |
| 662 |
|
| 663 |
static constexpr size_t kInvalidGpuMemorySize = ~static_cast<size_t>(0); |
| 664 |
|
| 665 |
// See RefIncrement() for how the bits in this field are interpreted. |
| 666 |
mutable std::atomic<uint64_t> fRefs; |
| 667 |
|
| 668 |
// Depending on when the resource can be reused, there are two base values: |
| 669 |
// 1. RefMask(kUsage): reused while there is outstanding GPU work (CB ref count is ignored). |
| 670 |
// 2. RefMask(kUsage) | RefMask(kCB): cannot be reused until it is also purgeable. |
| 671 |
// To simplify logic in removeRef(), this value always includes RefMask(kReturnQueue). |
| 672 |
// See removeRef() for rationale. |
| 673 |
// |
| 674 |
// NOTE: Reusability is related but distinct from shareability. Shareability takes into account |
| 675 |
// external information about when and for how long the state of the resource must remain stable |
| 676 |
// We track when all resources become "reusable" again even if they were fully shareable because |
| 677 |
// that marks when the resource can also change its Shareable type. |
| 678 |
const uint64_t fReusableRefMask; |
| 679 |
|
| 680 |
// This is not ref'ed but internalDispose() will be called before the Gpu object is destroyed. |
| 681 |
// That call will set this to nullptr. |
| 682 |
const SharedContext* fSharedContext; |
| 683 |
|
| 684 |
const UniqueID fUniqueID; |
| 685 |
const Ownership fOwnership; |
| 686 |
const bool fRequiresPrepareForReturnToCache; |
| 687 |
|
| 688 |
// The resource key and return cache are both set at most once, during registerWithCache(). |
| 689 |
/*const*/ GraphiteResourceKey fKey; |
| 690 |
/*const*/ sk_sp<ResourceCache> fReturnCache; |
| 691 |
|
| 692 |
// Resources added to their return cache's queue are tracked in a lock-free thread-safe |
| 693 |
// singly-linked list whose head element is stored on the cache, and next elements are stored |
| 694 |
// inline in Resource. This can only be modified by the thread that set the return queue ref, |
| 695 |
// or by the thread that is removing said ref. |
| 696 |
// |
| 697 |
// A null value means the Resource is not in the return queue. A non-null value means it is in |
| 698 |
// the queue, although the ResourceCache assigns a special sentinel value for the tail address. |
| 699 |
Resource* fNextInReturnQueue = nullptr; |
| 700 |
|
| 701 |
// The remaining fields are mutable state that is only modified by the ResourceCache on the |
| 702 |
// cache's thread, guarded by `fReturnCache::fSingleOwner`. |
| 703 |
|
| 704 |
size_t fGpuMemorySize = kInvalidGpuMemorySize; |
| 705 |
|
| 706 |
// All resources created internally by Graphite that are held in the ResourceCache as shared or |
| 707 |
// available scratch resources are considered budgeted. Resources that back client-owned objects |
| 708 |
// (e.g. SkSurface or SkImage) and wrapper objects (e.g. BackendTexture) do not count against |
| 709 |
// cache limits and therefore should never be budgeted. |
| 710 |
Budgeted fBudgeted = Budgeted::kNo; |
| 711 |
// All resources start out as non-shareable (the strictest mode) and revert to non-shareable |
| 712 |
// when they are returned to the cache and have no more usage refs. An available resource can |
| 713 |
// be returned if its shareable type matches the request, or if it was non-shareable at which |
| 714 |
// point the resource is upgraded to the more permissive mode (until all shared usages are |
| 715 |
// dropped at which point it can be used for any purpose again). |
| 716 |
Shareable fShareable = Shareable::kNo; |
| 717 |
|
| 718 |
// This is only used by ProxyCache::purgeProxiesNotUsedSince which is called from |
| 719 |
// ResourceCache::purgeResourcesNotUsedSince. When kYes, this signals that the Resource |
| 720 |
// should've been purged based on its timestamp at some point regardless of what its |
| 721 |
// current timestamp may indicate (since the timestamp will be updated when the Resource |
| 722 |
// is returned to the ResourceCache). |
| 723 |
DeleteASAP fDeleteASAP = DeleteASAP::kNo; |
| 724 |
|
| 725 |
// Set to true when the resource is contained in its cache's `fResourceMap`, which allows it to |
| 726 |
// be returned from findAndRefResource(). |
| 727 |
bool fAvailableForReuse = false; |
| 728 |
|
| 729 |
// An index into a heap when this resource is purgeable or an array when not. This is maintained |
| 730 |
// by the cache. Must be mutable to fit SkTDPQueue's access API. |
| 731 |
mutable int fCacheArrayIndex = -1; |
| 732 |
|
| 733 |
// This value reflects how recently this resource was accessed in the cache. This is maintained |
| 734 |
// by the cache. It defines a total order over resources, even if their fLastAccess times are |
| 735 |
// the same (i.e. returned at time points less than the system's granularity). |
| 736 |
uint32_t fLastUseToken; |
| 737 |
skgpu::StdSteadyClock::time_point fLastAccess; |
| 738 |
|
| 739 |
// String used to describe the current use of this Resource. |
| 740 |
std::string fLabel; |
| 741 |
}; |
| 742 |
|
| 743 |
} // namespace skgpu::graphite |
| 744 |
|
| 745 |
#endif // skgpu_graphite_Resource_DEFINED |