GrGpuResource.h 13 KB

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