Debian Codegraph @

src/gpu/ganesh/GrResourceAllocator.h

raw
1 /*
2 * Copyright 2017 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 GrResourceAllocator_DEFINED
9 #define GrResourceAllocator_DEFINED
10
11 #include "include/core/SkRefCnt.h"
12 #include "include/private/base/SkAssert.h"
13 #include "include/private/base/SkDebug.h"
14 #include "include/private/base/SkTo.h"
15 #include "src/base/SkArenaAlloc.h"
16 #include "src/core/SkTHash.h"
17 #include "src/core/SkTMultiMap.h"
18 #include "src/gpu/ResourceKey.h"
19 #include "src/gpu/ganesh/GrCaps.h"
20 #include "src/gpu/ganesh/GrHashMapWithCache.h"
21 #include "src/gpu/ganesh/GrSurface.h"
22 #include "src/gpu/ganesh/GrSurfaceProxy.h"
23
24 #include <cstdint>
25
26 class GrDirectContext;
27 class GrResourceProvider;
28
29 // Print out explicit allocation information
30 #define GR_ALLOCATION_SPEW 0
31
32 // Print out information about interval creation
33 #define GR_TRACK_INTERVAL_CREATION 0
34
35 /*
36 * The ResourceAllocator explicitly distributes GPU resources at flush time. It operates by
37 * being given the usage intervals of the various proxies. It keeps these intervals in a singly
38 * linked list sorted by increasing start index. (It also maintains a hash table from proxyID
39 * to interval to find proxy reuse). The ResourceAllocator uses Registers (in the sense of register
40 * allocation) to represent a future surface that will be used for each proxy during
41 * `planAssignment`, and then assigns actual surfaces during `assign`.
42 *
43 * Note: the op indices (used in the usage intervals) come from the order of the ops in
44 * their opsTasks after the opsTask DAG has been linearized.
45 *
46 * The planAssignment method traverses the sorted list and:
47 * moves intervals from the active list that have completed (returning their registers
48 * to the free pool) into the finished list (sorted by increasing start)
49 *
50 * allocates a new register (preferably from the free pool) for the new interval
51 * adds the new interval to the active list (that is sorted by increasing end index)
52 *
53 * After assignment planning, the user can choose to call `makeBudgetHeadroom` which:
54 * computes how much VRAM would be needed for new resources for all extant Registers
55 *
56 * asks the resource cache to purge enough resources to get that much free space
57 *
58 * if it's not possible, do nothing and return false. The user may opt to reset
59 * the allocator and start over with a different DAG.
60 *
61 * If the user wants to commit to the current assignment plan, they call `assign` which:
62 * instantiates lazy proxies
63 *
64 * instantantiates new surfaces for all registers that need them
65 *
66 * assigns the surface for each register to all the proxies that will use it
67 *
68 *************************************************************************************************
69 * How does instantiation failure handling work when explicitly allocating?
70 *
71 * In the gather usage intervals pass all the GrSurfaceProxies used in the flush should be
72 * gathered (i.e., in OpsTask::gatherProxyIntervals).
73 *
74 * During addInterval, read-only lazy proxies are instantiated. If that fails, the resource
75 * allocator will note the failure and ignore pretty much anything else until `reset`.
76 *
77 * During planAssignment, fully-lazy proxies are instantiated so that we can know their size for
78 * budgeting purposes. If this fails, return false.
79 *
80 * During assign, partially-lazy proxies are instantiated and new surfaces are created for all other
81 * proxies. If any of these fails, return false.
82 *
83 * The drawing manager will drop the flush if any proxies fail to instantiate.
84 */
85 class GrResourceAllocator {
86 public:
87 explicit GrResourceAllocator(GrDirectContext* dContext) : fDContext(dContext) {}
88
89 ~GrResourceAllocator();
90
91 unsigned int curOp() const { return fNumOps; }
92 void incOps() { fNumOps++; }
93
94 /** Indicates whether a given call to addInterval represents an actual usage of the
95 * provided proxy. This is mainly here to accommodate deferred proxies attached to opsTasks.
96 * In that case we need to create an extra long interval for them (due to the upload) but
97 * don't want to count that usage/reference towards the proxy's recyclability.
98 */
99 enum class ActualUse : bool {
100 kNo = false,
101 kYes = true
102 };
103
104 /** Indicates whether we allow a gpu texture assigned to a register to be recycled or not. This
105 * comes up when dealing with with Vulkan Secondary CommandBuffers since offscreens sampled
106 * into the scb will all be drawn before being sampled in the scb. This is because the scb
107 * will get submitted in a later command buffer. Thus offscreens cannot share an allocation or
108 * later reuses will overwrite earlier ones.
109 */
110 enum class AllowRecycling : bool {
111 kNo = false,
112 kYes = true
113 };
114
115 // Add a usage interval from 'start' to 'end' inclusive. This is usually used for renderTargets.
116 // If an existing interval already exists it will be expanded to include the new range.
117 void addInterval(GrSurfaceProxy*, unsigned int start, unsigned int end, ActualUse actualUse,
118 AllowRecycling SkDEBUGCODE(, bool isDirectDstRead = false));
119
120 bool failedInstantiation() const { return fFailedInstantiation; }
121
122 // Generate an internal plan for resource allocation. After this you can optionally call
123 // `makeBudgetHeadroom` to check whether that plan would go over our memory budget.
124 // Fully-lazy proxies are also instantiated at this point so that their size can
125 // be known accurately. Returns false if any lazy proxy failed to instantiate, true otherwise.
126 bool planAssignment();
127
128 // Figure out how much VRAM headroom this plan requires. If there's enough purgeable resources,
129 // purge them and return true. Otherwise return false.
130 bool makeBudgetHeadroom();
131
132 // Clear all internal state in preparation for a new set of intervals.
133 void reset();
134
135 // Instantiate and assign resources to all proxies.
136 bool assign();
137
138 #if GR_ALLOCATION_SPEW
139 void dumpIntervals();
140 #endif
141
142 private:
143 class Interval;
144 class Register;
145
146 // Remove dead intervals from the active list
147 void expire(unsigned int curIndex);
148
149 // These two methods wrap the interactions with the free pool
150 void recycleRegister(Register* r);
151 Register* findOrCreateRegisterFor(GrSurfaceProxy* proxy);
152
153 struct FreePoolTraits {
154 static const skgpu::ScratchKey& GetKey(const Register& r) {
155 return r.scratchKey();
156 }
157
158 static uint32_t Hash(const skgpu::ScratchKey& key) { return key.hash(); }
159 static void OnFree(Register* r) { }
160 };
161 typedef SkTMultiMap<Register, skgpu::ScratchKey, FreePoolTraits> FreePoolMultiMap;
162
163 typedef skia_private::THashMap<uint32_t, Interval*, GrCheapHash> IntvlHash;
164
165 struct UniqueKeyHash {
166 uint32_t operator()(const skgpu::UniqueKey& key) const { return key.hash(); }
167 };
168 typedef skia_private::THashMap<skgpu::UniqueKey, Register*, UniqueKeyHash>
169 UniqueKeyRegisterHash;
170
171 // Each proxy – with some exceptions – is assigned a register. After all assignments are made,
172 // another pass is performed to instantiate and assign actual surfaces to the proxies. Right
173 // now these are performed in one call, but in the future they will be separable and the user
174 // will be able to query re: memory cost before committing to surface creation.
175 class Register {
176 public:
177 // It's OK to pass an invalid scratch key iff the proxy has a unique key.
178 Register(GrSurfaceProxy* originatingProxy, skgpu::ScratchKey, GrResourceProvider*);
179
180 const skgpu::ScratchKey& scratchKey() const { return fScratchKey; }
181 const skgpu::UniqueKey& uniqueKey() const { return fOriginatingProxy->getUniqueKey(); }
182
183 bool accountedForInBudget() const { return fAccountedForInBudget; }
184 void setAccountedForInBudget() { fAccountedForInBudget = true; }
185
186 GrSurface* existingSurface() const { return fExistingSurface.get(); }
187
188 // Can this register be used by other proxies after this one?
189 bool isRecyclable(const GrCaps&, GrSurfaceProxy* proxy, int knownUseCount,
190 AllowRecycling) const;
191
192 // Resolve the register allocation to an actual GrSurface. 'fOriginatingProxy'
193 // is used to cache the allocation when a given register is used by multiple
194 // proxies.
195 bool instantiateSurface(GrSurfaceProxy*, GrResourceProvider*);
196
197 SkDEBUGCODE(uint32_t uniqueID() const { return fUniqueID; })
198
199 private:
200 GrSurfaceProxy* fOriginatingProxy;
201 skgpu::ScratchKey fScratchKey; // free pool wants a reference to this.
202 sk_sp<GrSurface> fExistingSurface; // queried from resource cache. may be null.
203 bool fAccountedForInBudget = false;
204
205 #ifdef SK_DEBUG
206 uint32_t fUniqueID;
207
208 static uint32_t CreateUniqueID();
209 #endif
210 };
211
212 class Interval {
213 public:
214 Interval(GrSurfaceProxy* proxy, unsigned int start, unsigned int end)
215 : fProxy(proxy)
216 , fStart(start)
217 , fEnd(end) {
218 SkASSERT(proxy);
219 SkDEBUGCODE(fUniqueID = CreateUniqueID());
220 #if GR_TRACK_INTERVAL_CREATION
221 SkString proxyStr = proxy->dump();
222 SkDebugf("New intvl %d: %s [%d, %d]\n", fUniqueID, proxyStr.c_str(), start, end);
223 #endif
224 }
225
226 const GrSurfaceProxy* proxy() const { return fProxy; }
227 GrSurfaceProxy* proxy() { return fProxy; }
228
229 unsigned int start() const { return fStart; }
230 unsigned int end() const { return fEnd; }
231
232 void setNext(Interval* next) { fNext = next; }
233 const Interval* next() const { return fNext; }
234 Interval* next() { return fNext; }
235
236 Register* getRegister() const { return fRegister; }
237 void setRegister(Register* r) { fRegister = r; }
238
239 void addUse() { fUses++; }
240 int uses() const { return fUses; }
241
242 void extendEnd(unsigned int newEnd) {
243 if (newEnd > fEnd) {
244 fEnd = newEnd;
245 #if GR_TRACK_INTERVAL_CREATION
246 SkDebugf("intvl %d: extending from %d to %d\n", fUniqueID, fEnd, newEnd);
247 #endif
248 }
249 }
250
251 void disallowRecycling() {
252 fAllowRecycling = AllowRecycling::kNo;
253 }
254 AllowRecycling allowRecycling() const { return fAllowRecycling; }
255
256 SkDEBUGCODE(uint32_t uniqueID() const { return fUniqueID; })
257
258 private:
259 GrSurfaceProxy* fProxy;
260 unsigned int fStart;
261 unsigned int fEnd;
262 Interval* fNext = nullptr;
263 unsigned int fUses = 0;
264 Register* fRegister = nullptr;
265 AllowRecycling fAllowRecycling = AllowRecycling::kYes;
266
267 #ifdef SK_DEBUG
268 uint32_t fUniqueID;
269
270 static uint32_t CreateUniqueID();
271 #endif
272 };
273
274 class IntervalList {
275 public:
276 IntervalList() = default;
277 // N.B. No need for a destructor – the arena allocator will clean up for us.
278
279 bool empty() const {
280 SkASSERT(SkToBool(fHead) == SkToBool(fTail));
281 return !SkToBool(fHead);
282 }
283 const Interval* peekHead() const { return fHead; }
284 Interval* peekHead() { return fHead; }
285 Interval* popHead();
286 void insertByIncreasingStart(Interval*);
287 void insertByIncreasingEnd(Interval*);
288
289 private:
290 SkDEBUGCODE(void validate() const;)
291
292 Interval* fHead = nullptr;
293 Interval* fTail = nullptr;
294 };
295
296 // Compositing use cases can create > 80 intervals.
297 static const int kInitialArenaSize = 128 * sizeof(Interval);
298
299 GrDirectContext* fDContext;
300 FreePoolMultiMap fFreePool; // Recently created/used GrSurfaces
301 IntvlHash fIntvlHash; // All the intervals, hashed by proxyID
302
303 IntervalList fIntvlList; // All the intervals sorted by increasing start
304 IntervalList fActiveIntvls; // List of live intervals during assignment
305 // (sorted by increasing end)
306 IntervalList fFinishedIntvls; // All the completed intervals
307 // (sorted by increasing start)
308 UniqueKeyRegisterHash fUniqueKeyRegisters;
309 unsigned int fNumOps = 0;
310
311 SkDEBUGCODE(bool fPlanned = false;)
312 SkDEBUGCODE(bool fAssigned = false;)
313
314 SkSTArenaAllocWithReset<kInitialArenaSize> fInternalAllocator; // intervals & registers
315 bool fFailedInstantiation = false;
316 };
317
318 #endif // GrResourceAllocator_DEFINED