GrGpuResource.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. #ifndef GrGpuResource_DEFINED
  8. #define GrGpuResource_DEFINED
  9. #include "include/private/GrResourceKey.h"
  10. #include "include/private/GrTypesPriv.h"
  11. #include "include/private/SkNoncopyable.h"
  12. class GrContext;
  13. class GrGpu;
  14. class GrResourceCache;
  15. class SkTraceMemoryDump;
  16. /**
  17. * Base class for GrGpuResource. Handles the various types of refs we need. Separated out as a base
  18. * class to isolate the ref-cnting behavior and provide friendship without exposing all of
  19. * GrGpuResource.
  20. *
  21. * Gpu resources can have three types of refs:
  22. * 1) Normal ref (+ by ref(), - by unref()): These are used by code that is issuing draw calls
  23. * that read and write the resource via GrOpList and by any object that must own a
  24. * GrGpuResource and is itself owned (directly or indirectly) by Skia-client code.
  25. * 2) Pending read (+ by addPendingRead(), - by completedRead()): GrContext has scheduled a read
  26. * of the resource by the GPU as a result of a skia API call but hasn't executed it yet.
  27. * 3) Pending write (+ by addPendingWrite(), - by completedWrite()): GrContext has scheduled a
  28. * write to the resource by the GPU as a result of a skia API call but hasn't executed it yet.
  29. *
  30. * The latter two ref types are private and intended only for Gr core code.
  31. *
  32. * PRIOR to the last ref/IO count being removed DERIVED::notifyAllCntsWillBeZero() will be called
  33. * (static poly morphism using CRTP). It is legal for additional ref's or pending IOs to be added
  34. * during this time. AFTER all the ref/io counts reach zero DERIVED::notifyAllCntsAreZero() will be
  35. * called. Similarly when the ref (but not necessarily pending read/write) count reaches 0
  36. * DERIVED::notifyRefCountIsZero() will be called. In the case when an unref() causes both
  37. * the ref cnt to reach zero and the other counts are zero, notifyRefCountIsZero() will be called
  38. * before notifyAllCntsAreZero(). Moreover, if notifyRefCountIsZero() returns false then
  39. * notifyAllCntsAreZero() won't be called at all. notifyRefCountIsZero() must return false if the
  40. * object may be deleted after notifyRefCntIsZero() returns.
  41. *
  42. * GrIORef and GrGpuResource are separate classes for organizational reasons and to be
  43. * able to give access via friendship to only the functions related to pending IO operations.
  44. */
  45. template <typename DERIVED> class GrIORef : public SkNoncopyable {
  46. public:
  47. // Some of the signatures are written to mirror SkRefCnt so that GrGpuResource can work with
  48. // templated helper classes (e.g. sk_sp). However, we have different categories of
  49. // refs (e.g. pending reads). We also don't require thread safety as GrCacheable objects are
  50. // not intended to cross thread boundaries.
  51. void ref() const {
  52. // Only the cache should be able to add the first ref to a resource.
  53. SkASSERT(fRefCnt > 0);
  54. this->validate();
  55. ++fRefCnt;
  56. }
  57. void unref() const {
  58. this->validate();
  59. if (fRefCnt == 1) {
  60. if (!this->internalHasPendingIO()) {
  61. static_cast<const DERIVED*>(this)->notifyAllCntsWillBeZero();
  62. }
  63. SkASSERT(fRefCnt > 0);
  64. }
  65. if (--fRefCnt == 0) {
  66. if (!static_cast<const DERIVED*>(this)->notifyRefCountIsZero()) {
  67. return;
  68. }
  69. }
  70. this->didRemoveRefOrPendingIO(kRef_CntType);
  71. }
  72. void validate() const {
  73. #ifdef SK_DEBUG
  74. SkASSERT(fRefCnt >= 0);
  75. SkASSERT(fPendingReads >= 0);
  76. SkASSERT(fPendingWrites >= 0);
  77. SkASSERT(fRefCnt + fPendingReads + fPendingWrites >= 0);
  78. #endif
  79. }
  80. #if GR_TEST_UTILS
  81. int32_t testingOnly_getRefCnt() const { return fRefCnt; }
  82. int32_t testingOnly_getPendingReads() const { return fPendingReads; }
  83. int32_t testingOnly_getPendingWrites() const { return fPendingWrites; }
  84. #endif
  85. protected:
  86. GrIORef() : fRefCnt(1), fPendingReads(0), fPendingWrites(0) { }
  87. enum CntType {
  88. kRef_CntType,
  89. kPendingRead_CntType,
  90. kPendingWrite_CntType,
  91. };
  92. bool internalHasPendingRead() const { return SkToBool(fPendingReads); }
  93. bool internalHasPendingWrite() const { return SkToBool(fPendingWrites); }
  94. bool internalHasPendingIO() const { return SkToBool(fPendingWrites | fPendingReads); }
  95. bool internalHasRef() const { return SkToBool(fRefCnt); }
  96. bool internalHasUniqueRef() const { return fRefCnt == 1; }
  97. // Privileged method that allows going from ref count = 0 to ref count = 1.
  98. void addInitialRef() const {
  99. this->validate();
  100. ++fRefCnt;
  101. }
  102. private:
  103. void addPendingRead() const {
  104. this->validate();
  105. ++fPendingReads;
  106. }
  107. void completedRead() const {
  108. this->validate();
  109. if (fPendingReads == 1 && !fPendingWrites && !fRefCnt) {
  110. static_cast<const DERIVED*>(this)->notifyAllCntsWillBeZero();
  111. }
  112. --fPendingReads;
  113. this->didRemoveRefOrPendingIO(kPendingRead_CntType);
  114. }
  115. void addPendingWrite() const {
  116. this->validate();
  117. ++fPendingWrites;
  118. }
  119. void completedWrite() const {
  120. this->validate();
  121. if (fPendingWrites == 1 && !fPendingReads && !fRefCnt) {
  122. static_cast<const DERIVED*>(this)->notifyAllCntsWillBeZero();
  123. }
  124. --fPendingWrites;
  125. this->didRemoveRefOrPendingIO(kPendingWrite_CntType);
  126. }
  127. void didRemoveRefOrPendingIO(CntType cntTypeRemoved) const {
  128. if (0 == fPendingReads && 0 == fPendingWrites && 0 == fRefCnt) {
  129. static_cast<const DERIVED*>(this)->notifyAllCntsAreZero(cntTypeRemoved);
  130. }
  131. }
  132. mutable int32_t fRefCnt;
  133. mutable int32_t fPendingReads;
  134. mutable int32_t fPendingWrites;
  135. friend class GrResourceCache; // to check IO ref counts.
  136. template <typename, GrIOType> friend class GrPendingIOResource;
  137. };
  138. /**
  139. * Base class for objects that can be kept in the GrResourceCache.
  140. */
  141. class SK_API GrGpuResource : public GrIORef<GrGpuResource> {
  142. public:
  143. /**
  144. * Tests whether a object has been abandoned or released. All objects will
  145. * be in this state after their creating GrContext is destroyed or has
  146. * contextLost called. It's up to the client to test wasDestroyed() before
  147. * attempting to use an object if it holds refs on objects across
  148. * ~GrContext, freeResources with the force flag, or contextLost.
  149. *
  150. * @return true if the object has been released or abandoned,
  151. * false otherwise.
  152. */
  153. bool wasDestroyed() const { return nullptr == fGpu; }
  154. /**
  155. * Retrieves the context that owns the object. Note that it is possible for
  156. * this to return NULL. When objects have been release()ed or abandon()ed
  157. * they no longer have an owning context. Destroying a GrContext
  158. * automatically releases all its resources.
  159. */
  160. const GrContext* getContext() const;
  161. GrContext* getContext();
  162. /**
  163. * Retrieves the amount of GPU memory used by this resource in bytes. It is
  164. * approximate since we aren't aware of additional padding or copies made
  165. * by the driver.
  166. *
  167. * @return the amount of GPU memory used in bytes
  168. */
  169. size_t gpuMemorySize() const {
  170. if (kInvalidGpuMemorySize == fGpuMemorySize) {
  171. fGpuMemorySize = this->onGpuMemorySize();
  172. SkASSERT(kInvalidGpuMemorySize != fGpuMemorySize);
  173. }
  174. return fGpuMemorySize;
  175. }
  176. class UniqueID {
  177. public:
  178. UniqueID() = default;
  179. explicit UniqueID(uint32_t id) : fID(id) {}
  180. uint32_t asUInt() const { return fID; }
  181. bool operator==(const UniqueID& other) const { return fID == other.fID; }
  182. bool operator!=(const UniqueID& other) const { return !(*this == other); }
  183. void makeInvalid() { fID = SK_InvalidUniqueID; }
  184. bool isInvalid() const { return fID == SK_InvalidUniqueID; }
  185. protected:
  186. uint32_t fID = SK_InvalidUniqueID;
  187. };
  188. /**
  189. * Gets an id that is unique for this GrGpuResource object. It is static in that it does
  190. * not change when the content of the GrGpuResource object changes. This will never return
  191. * 0.
  192. */
  193. UniqueID uniqueID() const { return fUniqueID; }
  194. /** Returns the current unique key for the resource. It will be invalid if the resource has no
  195. associated unique key. */
  196. const GrUniqueKey& getUniqueKey() const { return fUniqueKey; }
  197. /**
  198. * Internal-only helper class used for manipulations of the resource by the cache.
  199. */
  200. class CacheAccess;
  201. inline CacheAccess cacheAccess();
  202. inline const CacheAccess cacheAccess() const;
  203. /**
  204. * Internal-only helper class used for manipulations of the resource by GrSurfaceProxy.
  205. */
  206. class ProxyAccess;
  207. inline ProxyAccess proxyAccess();
  208. /**
  209. * Internal-only helper class used for manipulations of the resource by internal code.
  210. */
  211. class ResourcePriv;
  212. inline ResourcePriv resourcePriv();
  213. inline const ResourcePriv resourcePriv() const;
  214. /**
  215. * Dumps memory usage information for this GrGpuResource to traceMemoryDump.
  216. * Typically, subclasses should not need to override this, and should only
  217. * need to override setMemoryBacking.
  218. **/
  219. virtual void dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const;
  220. /**
  221. * Describes the type of gpu resource that is represented by the implementing
  222. * class (e.g. texture, buffer object, stencil). This data is used for diagnostic
  223. * purposes by dumpMemoryStatistics().
  224. *
  225. * The value returned is expected to be long lived and will not be copied by the caller.
  226. */
  227. virtual const char* getResourceType() const = 0;
  228. static uint32_t CreateUniqueID();
  229. protected:
  230. // This must be called by every non-wrapped GrGpuObject. It should be called once the object is
  231. // fully initialized (i.e. only from the constructors of the final class).
  232. void registerWithCache(SkBudgeted);
  233. // This must be called by every GrGpuObject that references any wrapped backend objects. It
  234. // should be called once the object is fully initialized (i.e. only from the constructors of the
  235. // final class).
  236. void registerWithCacheWrapped(GrWrapCacheable);
  237. GrGpuResource(GrGpu*);
  238. virtual ~GrGpuResource();
  239. GrGpu* getGpu() const { return fGpu; }
  240. /** Overridden to free GPU resources in the backend API. */
  241. virtual void onRelease() { }
  242. /** Overridden to abandon any internal handles, ptrs, etc to backend API resources.
  243. This may be called when the underlying 3D context is no longer valid and so no
  244. backend API calls should be made. */
  245. virtual void onAbandon() { }
  246. /**
  247. * Allows subclasses to add additional backing information to the SkTraceMemoryDump.
  248. **/
  249. virtual void setMemoryBacking(SkTraceMemoryDump*, const SkString&) const {}
  250. /**
  251. * Returns a string that uniquely identifies this resource.
  252. */
  253. SkString getResourceName() const;
  254. /**
  255. * A helper for subclasses that override dumpMemoryStatistics(). This method using a format
  256. * consistent with the default implementation of dumpMemoryStatistics() but allows the caller
  257. * to customize various inputs.
  258. */
  259. void dumpMemoryStatisticsPriv(SkTraceMemoryDump* traceMemoryDump, const SkString& resourceName,
  260. const char* type, size_t size) const;
  261. private:
  262. bool isPurgeable() const;
  263. bool hasRef() const;
  264. bool hasRefOrPendingIO() const;
  265. /**
  266. * Called by the registerWithCache if the resource is available to be used as scratch.
  267. * Resource subclasses should override this if the instances should be recycled as scratch
  268. * resources and populate the scratchKey with the key.
  269. * By default resources are not recycled as scratch.
  270. **/
  271. virtual void computeScratchKey(GrScratchKey*) const {}
  272. /**
  273. * Removes references to objects in the underlying 3D API without freeing them.
  274. * Called by CacheAccess.
  275. */
  276. void abandon();
  277. /**
  278. * Frees the object in the underlying 3D API. Called by CacheAccess.
  279. */
  280. void release();
  281. virtual size_t onGpuMemorySize() const = 0;
  282. /**
  283. * Called by GrResourceCache when a resource loses its last ref or pending IO.
  284. */
  285. virtual void willRemoveLastRefOrPendingIO() {}
  286. // See comments in CacheAccess and ResourcePriv.
  287. void setUniqueKey(const GrUniqueKey&);
  288. void removeUniqueKey();
  289. void notifyAllCntsWillBeZero() const;
  290. void notifyAllCntsAreZero(CntType) const;
  291. bool notifyRefCountIsZero() const;
  292. void removeScratchKey();
  293. void makeBudgeted();
  294. void makeUnbudgeted();
  295. #ifdef SK_DEBUG
  296. friend class GrGpu; // for assert in GrGpu to access getGpu
  297. #endif
  298. // An index into a heap when this resource is purgeable or an array when not. This is maintained
  299. // by the cache.
  300. int fCacheArrayIndex;
  301. // This value reflects how recently this resource was accessed in the cache. This is maintained
  302. // by the cache.
  303. uint32_t fTimestamp;
  304. GrStdSteadyClock::time_point fTimeWhenBecamePurgeable;
  305. static const size_t kInvalidGpuMemorySize = ~static_cast<size_t>(0);
  306. GrScratchKey fScratchKey;
  307. GrUniqueKey fUniqueKey;
  308. // This is not ref'ed but abandon() or release() will be called before the GrGpu object
  309. // is destroyed. Those calls set will this to NULL.
  310. GrGpu* fGpu;
  311. mutable size_t fGpuMemorySize = kInvalidGpuMemorySize;
  312. GrBudgetedType fBudgetedType = GrBudgetedType::kUnbudgetedUncacheable;
  313. bool fRefsWrappedObjects = false;
  314. const UniqueID fUniqueID;
  315. typedef GrIORef<GrGpuResource> INHERITED;
  316. friend class GrIORef<GrGpuResource>; // to access notifyAllCntsAreZero and notifyRefCntIsZero.
  317. };
  318. class GrGpuResource::ProxyAccess {
  319. private:
  320. ProxyAccess(GrGpuResource* resource) : fResource(resource) {}
  321. /** Proxies are allowed to take a resource from no refs to one ref. */
  322. void ref(GrResourceCache* cache);
  323. // No taking addresses of this type.
  324. const CacheAccess* operator&() const = delete;
  325. CacheAccess* operator&() = delete;
  326. GrGpuResource* fResource;
  327. friend class GrGpuResource;
  328. friend class GrSurfaceProxy;
  329. friend class GrIORefProxy;
  330. };
  331. inline GrGpuResource::ProxyAccess GrGpuResource::proxyAccess() { return ProxyAccess(this); }
  332. #endif