Debian Codegraph @

src/gpu/graphite/BufferManager.h

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 * Copyright 2021 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 skgpu_graphite_BufferManager_DEFINED
8 #define skgpu_graphite_BufferManager_DEFINED
9
10 #include "include/core/SkRefCnt.h"
11 #include "include/private/base/SkTArray.h"
12 #include "src/core/SkTHash.h"
13 #include "src/gpu/BufferWriter.h"
14 #include "src/gpu/graphite/Buffer.h"
15 #include "src/gpu/graphite/ResourceTypes.h"
16 #include "src/gpu/graphite/UploadBufferManager.h"
17
18 #include <array>
19 #include <cstddef>
20 #include <cstdint>
21 #include <string_view>
22 #include <utility>
23
24 namespace skgpu::graphite {
25
26 class Caps;
27 class Context;
28 class DrawBufferManager;
29 class GlobalCache;
30 class QueueManager;
31 class Recording;
32 class ResourceProvider;
33
34 /**
35 * BufferSubAllocator provides an entire GPU buffer to the caller so that the caller can sub
36 * allocate intervals within the buffer. Each buffer type has a minimum required alignment for
37 * binding. This alignment is automatically used for the *first* suballocation from an allocator
38 * instance. Scoping the lifetime of an allocator to when the contents are bound allows these
39 * binding requirements to automatically be met and use a tighter alignment for additional
40 * suballocations that can be accessed without requiring a new binding.
41 *
42 * When a BufferSubAllocator goes out of scope, its underlying Buffer is returned to the manager. By
43 * default, any remaining space can be returned by subsequent allocation requests but written bytes
44 * will not be able to be overwritten by later BufferSubAllocators. The exception is with the
45 * BufferSubAllocator instances returned by BufferManager::getScratchStorage(), whose Buffers will
46 * be Shareable::kScratch resources, and can be fully reused by other Recorders or once the
47 * BufferSubAllocator goes out of scope.
48 *
49 * Buffers created by the DrawBufferManager for an allocator are automatically transferred to the
50 * Recording and CommandBuffers when snapped or inserted.
51 */
52 class BufferSubAllocator final {
53 public:
54 BufferSubAllocator() = default;
55
56 // Disallow copy
57 BufferSubAllocator(const BufferSubAllocator&) = delete;
58 BufferSubAllocator& operator=(const BufferSubAllocator&) = delete;
59
60 // Allow move
61 BufferSubAllocator(BufferSubAllocator&& b) { *this = std::move(b); }
62 BufferSubAllocator& operator=(BufferSubAllocator&&);
63
64 ~BufferSubAllocator() { this->reset(); }
65
66 // Returns false if the underlying buffer has been returned to the reuse pool or moved.
67 bool isValid() const { return SkToBool(fBuffer); }
68 explicit operator bool() const { return this->isValid(); }
69
70 // Returns the underlying buffer object back to the pool and invalidates this allocator.
71 // Depending on the GPU buffer's Shareable value, either:
72 // - kNo: The remaining space that hasn't been written to can be used by another allocator,
73 // but it will assume that use will involve a new buffer binding command.
74 // - kScratch: The entire buffer can be overwritten by another allocator.
75 void reset();
76
77 // Causes the next call to get[Mapped]Subrange() to also align with the minimum binding
78 // requirement for the buffer's type. It resets any remaining strided blocks following the
79 // last suballocation or appended range.
80 void resetForNewBinding() {
81 fRemaining = 0;
82 fStride = 0; // signals prepForStride() to factor in minimum binding alignment next time.
83 }
84
85 // Returns the number of remaining bytes in the GPU buffer, assuming an alignment of 1.
86 uint32_t remainingBytes() const {
87 return fBuffer ? SkTo<uint32_t>(fBuffer->size()) - fOffset : 0;
88 }
89
90 /**
91 * Suballocate `count*stride` bytes and a pointer (wrapped in a BufferWriter) to the mapped
92 * range and the BindBufferInfo defining that range in a GPU-backed Buffer. The returned
93 * subrange will be aligned according to the following rules:
94 * - The first suballocation, or the first after resetForNewBinding(), will be aligned to the
95 * lowest common multiple of `stride`, the binding's required alignment, and any extra base
96 * alignment passed in as `align`.
97 * - Subsequent suballocations will be aligned to just `stride` and any extra base alignment.
98 *
99 * It is assumed the caller will write all `count*stride` bytes to the returned address. If
100 * `reservedCount` is greater than `count`, the suballocation will only succeed if the buffer
101 * has room for an aligned `reservedCount*stride` bytes. The returned pointer can still only
102 * write `count*stride` bytes, the remaining `reservedCount-count` is available for future
103 * suballocations guaranteed to then fit within the same buffer (assuming the same or lower
104 * alignment).
105 *
106 * It is acceptable to pass `count=0` to this function, which will still succeed if there is
107 * space to align at least one more aligned `stride` block. In this case, the BufferWriter will
108 * be null but the BindBufferInfo will have a valid Buffer and byte offset (just a zero size).
109 * This then represents the start of the binding range for future calls to appendMappedStride().
110 *
111 * An invalid BufferWriter and empty BindBufferInfo are returned if the buffer does not have
112 * enough room remaining to fulfill the suballocation in this buffer.
113 */
114 std::pair<BufferWriter, BindBufferInfo> getMappedSubrange(size_t count,
115 size_t stride,
116 size_t align=1) {
117 SkASSERT(fMappedPtr || !fBuffer); // Writing should have checked validity of allocator first
118 this->prepForStride(stride, align, count);
119 return this->reserve(count, &BufferSubAllocator::getWriterAndBinding);
120 }
121
122 // Sub-allocate a slice within the scratch buffer object. This variation should be used when the
123 // returned range will be written to by the GPU as part of executing a command buffer.
124 //
125 // Other than returning just a buffer slice to be written to later by a GPU task, the
126 // suballocation behaves identically to getMappedSubrange().
127 BindBufferInfo getSubrange(size_t count, size_t stride, size_t align=1) {
128 SkASSERT(!fMappedPtr); // Should not be used when data is intended to be written by CPU
129 this->prepForStride(stride, align, count);
130 return this->reserve(count, &BufferSubAllocator::binding);
131 }
132
133 // Returns the number of `stride` blocks left in the buffer, where `stride` was the last
134 // value passed into get[Mapped]Subrange().
135 uint32_t availableWithStride() const { return fRemaining; }
136
137 /**
138 * Returns a buffer writer for `count*stride` bytes, where `stride` was the last value passed
139 * to getMappedSubrange.
140 *
141 * If `count <= this->availableWithStride()`, then the appended range will be contiguous with
142 * the BindBufferInfo returned from the last call to getMappedSubrange (and/or other calls to
143 * appendMappedStride). The binding's size should be increased by count*stride, which is the
144 * caller's responsibility.
145 *
146 * Otherwise, a null BufferWriter will be returned and no change is made to the allocator.
147 */
148 BufferWriter appendMappedWithStride(size_t count) {
149 SkASSERT(count > 0 && (fMappedPtr || fRemaining == 0));
150 return this->reserve(count, &BufferSubAllocator::getWriter);
151 }
152
153 private:
154 friend class DrawBufferManager;
155
156 BufferSubAllocator(DrawBufferManager* owner,
157 int stateIndex,
158 sk_sp<Buffer> buffer,
159 BindBufferInfo transferBuffer, // optional (when direct mapping unavailable)
160 void* mappedPtr, // `buffer` or `transferBuffer`'s ptr, or null if GPU-only
161 size_t stride); // initial stride to compute `fRemaining`
162
163 // If minCount*stride bytes fit when aligned to the LCM of stride, align, and possibly the
164 // binding alignment (when fStride == 0), then fOffset is updated and fRemaining is set to the
165 // number of stride units that fit in the rest of the buffer after fOffset. If not, fRemaining
166 // is set to 0 and fOffset is unmodified.
167 void prepForStride(size_t stride, size_t align, size_t minCount);
168
169 template <typename T>
170 T reserve(size_t count, T (BufferSubAllocator::*create)(uint32_t offset, uint32_t size) const) {
171 if (!fBuffer || count > fRemaining) {
172 return T();
173 }
174
175 SkASSERT(fStride > 0); // fRemaining should be set to 0 if fStride is 0
176 // fRemaining and fStride were already validated in prepForStride() so we can cast `count`
177 const uint32_t requiredBytes32 = SkTo<uint32_t>(count) * fStride;
178
179 uint32_t offset = fOffset;
180 fOffset += requiredBytes32;
181 fRemaining -= count;
182 return (this->*create)(offset, requiredBytes32);
183 }
184
185 BindBufferInfo binding(uint32_t offset, uint32_t size) const {
186 SkASSERT(fBuffer);
187 SkASSERT(fOffset >= size && fOffset - size >= offset);
188 return BindBufferInfo{fBuffer.get(), offset, size};
189 }
190
191 BufferWriter getWriter(uint32_t offset, uint32_t size) const {
192 SkASSERT(fMappedPtr);
193 SkASSERT(fBuffer);
194 SkASSERT(fOffset >= size && fOffset - size >= offset);
195 return BufferWriter(SkTAddOffset<void>(fMappedPtr, offset), size);
196 }
197
198 std::pair<BufferWriter, BindBufferInfo> getWriterAndBinding(
199 uint32_t offset, uint32_t size) const {
200 return {this->getWriter(offset, size), this->binding(offset, size)};
201 }
202
203 // Non-null when valid and not already returned to the pool
204 DrawBufferManager* fOwner = nullptr;
205 int fStateIndex = 0;
206
207 sk_sp<Buffer> fBuffer;
208 BindBufferInfo fTransferBuffer;
209
210 // If mapped for writing, this is the CPU address of offset 0 of the buffer. When a mapped
211 // buffer is returned to the DrawBufferManager, only the bytes after fOffset can be reused.
212 // If there is no mapped buffer pointer, it's assumed the GPU buffer is reusable for another
213 // BufferSubAllocator instance (this default reuse policy can be revisited if needed).
214 void* fMappedPtr = nullptr;
215 uint32_t fOffset = 0; // Next suballocation can start at fOffset at the earliest
216 uint32_t fStride = 1; // The byte count of blocks for the optimized append() function
217 uint32_t fRemaining = 0; // The number of `fStride` contiguous blocks fitting after fOffset
218 };
219
220 /**
221 * DrawBufferManager controls writing to buffer data ranges within larger, cacheable Buffers and
222 * automatically handles either mapping or copying via transfer buffer depending on what the GPU
223 * hardware supports for the requested buffer type and use case. It is intended for repeatedly
224 * uploading dynamic data to the GPU.
225 */
226 class DrawBufferManager {
227 public:
228 struct Options {
229 Options() = default;
230
231 uint32_t fVertexBufferMinSize = 16 << 10; // 16 KB;
232 uint32_t fVertexBufferMaxSize = 1 << 20; // 1 MB
233 uint32_t fIndexBufferSize = 2 << 10; // 2 KB
234 uint32_t fStorageBufferMinSize = 2 << 10; // 2 KB;
235 uint32_t fStorageBufferMaxSize = 1 << 20; // 1 MB;
236
237 #if defined(GPU_TEST_UTILS)
238 bool fUseExactBuffSizes = false; // Disables automatic buffer growth
239 bool fAllowCopyingGpuOnly = false; // Adds kCopySrc to GPU-only buffer usage
240 #endif
241 };
242
243 DrawBufferManager(ResourceProvider* resourceProvider, const Caps* caps,
244 UploadBufferManager* uploadManager,
245 Options dbmOpts);
246 ~DrawBufferManager();
247
248 // Let possible users check if the manager is already in a bad mapping state and skip any extra
249 // work that will be wasted because the next Recording snap will fail.
250 bool hasMappingFailed() const { return fMappingFailed; }
251
252 // Return a BufferWriter to write to the count*dataStride bytes of the GPU buffer subrange
253 // represented by the returned BindBufferInfo. The returned BufferSubAllocator represents the
254 // entire GPU buffer that the mapped subrange belongs to; it can be used to get additional
255 // mapped suballocations, which when successful are guaranteed to be in the same buffer. This
256 // allows callers to more easily manage when buffers must be bound.
257 //
258 // The returned {BufferWriter, BindBufferInfo} are effectively an automatic call to
259 // BufferSubAllocator.getMappedSubrange(count, stride, reservedCount). The offset of this first
260 // allocation will be aligned to the LCM of `stride` and the minimum required alignment for the
261 // buffer type. For function variants that take an extra `alignment`, the initial suballocation
262 // will also be aligned to that, equivalent to if resetForNewBinding(alignment) had been called
263 // before. Subsequent suballocations from the returned allocator will only be aligned to their
264 // requested stride unless resetForNewBinding() was called.
265 //
266 // When the returned BufferSubAllocator goes out of scope, any remaining bytes that were never
267 // returned from either this function or later calls to getMappedSubrange() can be used to
268 // satisfy a future call to getMapped[X]Buffer.
269 using MappedAllocationInfo = std::tuple<BufferWriter, BindBufferInfo, BufferSubAllocator>;
270
271 MappedAllocationInfo getMappedVertexBuffer(size_t count, size_t stride,
272 size_t reservedCount=0, size_t alignment=1) {
273 return this->getMappedBuffer(kVertexBufferIndex, count, stride, reservedCount, alignment);
274 }
275 MappedAllocationInfo getMappedIndexBuffer(size_t count) {
276 return this->getMappedBuffer(kIndexBufferIndex, count, sizeof(uint16_t));
277 }
278 MappedAllocationInfo getMappedUniformBuffer(size_t count, size_t stride) {
279 return this->getMappedBuffer(kUniformBufferIndex, count, stride);
280 }
281 MappedAllocationInfo getMappedStorageBuffer(size_t count, size_t stride) {
282 return this->getMappedBuffer(kStorageBufferIndex, count, stride);
283 }
284
285 // The remaining writers and buffer allocator functions assume that byte counts are safely
286 // calculated by the caller (e.g. Vello).
287
288 // Utilities that return an unmapped buffer suballocation for a particular usage. These buffers
289 // are intended to be only accessed by the GPU and are not intended for CPU data uploads.
290 BindBufferInfo getStorage(size_t requiredBytes, ClearBuffer cleared = ClearBuffer::kNo) {
291 return this->getBinding(kGpuOnlyStorageBufferIndex, requiredBytes, cleared);
292 }
293 BindBufferInfo getVertexStorage(size_t requiredBytes) {
294 return this->getBinding(kVertexStorageBufferIndex, requiredBytes, ClearBuffer::kNo);
295 }
296 BindBufferInfo getIndexStorage(size_t requiredBytes) {
297 return this->getBinding(kIndexStorageBufferIndex, requiredBytes, ClearBuffer::kNo);
298 }
299 BindBufferInfo getIndirectStorage(size_t requiredBytes, ClearBuffer cleared=ClearBuffer::kNo) {
300 return this->getBinding(kIndirectStorageBufferIndex, requiredBytes, cleared);
301 }
302
303 // Returns an entire storage buffer object that is large enough to fit `requiredBytes`. The
304 // returned BufferSubAllocator can be used to sub-allocate one or more storage buffer bindings
305 // that reference the same buffer object.
306 //
307 // When the BufferSubAllocator goes out of scope, the buffer object gets added to an internal
308 // pool and is available for immediate reuse. getScratchStorage() returns buffers from this pool
309 // if possible. A BufferSubAllocator can be explicitly returned to the pool by calling
310 // `returnToPool()`.
311 //
312 // Returning a BufferSubAllocator back to the buffer too early can result in validation failures
313 // and/or data races. It is the callers responsibility to manage reuse within a Recording and
314 // guarantee synchronized access to buffer bindings.
315 //
316 // This type of usage is currently limited to GPU-only storage buffers.
317 BufferSubAllocator getScratchStorage(size_t requiredBytes) {
318 return this->getBuffer(kGpuOnlyStorageBufferIndex, requiredBytes,
319 /*stride=*/1, /*xtraAlignment=*/1,
320 ClearBuffer::kNo, Shareable::kScratch);
321 }
322
323 // Finalizes all buffers and transfers ownership of them to a Recording. Returns true on success
324 // and false if a mapping had previously failed.
325 //
326 // Regardless of success or failure, the DrawBufferManager is reset to a valid initial state
327 // for recording buffer data for the next Recording.
328 [[nodiscard]] bool transferToRecording(Recording*);
329
•330 #if defined(GPU_TEST_UTILS)
331 void testingOnly_onFailedBuffer() { this->onFailedBuffer(); }
332 #endif
333
334 private:
335 friend class BufferSubAllocator;
336
337 struct BufferState {
338 const BufferType fType;
339 const AccessPattern fAccessPattern;
340 const bool fUseTransferBuffer;
341 const char* fLabel;
342
343 const uint32_t fMinAlignment; // guaranteed power of two, required for binding
344 const uint32_t fMinBlockSize;
345 const uint32_t fMaxBlockSize;
346
347 BufferSubAllocator fAvailableBuffer;
348
349 // Buffers held in this array are owned by still-alive BufferSubAllocators that were created
350 // with Shareable::kScratch. This is compatible with ResourceCache::ScratchResourceSet.
351 skia_private::THashSet<const Resource*> fUnavailableScratchBuffers;
352
353 // The size of the last allocated Buffer, pinned to min/max block size, for amortizing the
354 // number of buffer allocations for large Recordings.
355 uint32_t fLastBufferSize = 0;
356
357 BufferState(BufferType, const char* label, bool isGpuOnly,
358 const Options&, const Caps* caps);
359
360 sk_sp<Buffer> findOrCreateBuffer(ResourceProvider*, Shareable, uint32_t byteCount);
361 };
362
363 // The returned sub allocator will have an offset that is aligned to `stride`, `xtraAlignment`
364 // and the minimum alignment for `stateIndex`. Its `availableWithStride()` will be >= `count`.
365 BufferSubAllocator getBuffer(int stateIndex,
366 size_t count,
367 size_t stride,
368 size_t xtraAlignment,
369 ClearBuffer cleared,
370 Shareable shareable);
371
372 MappedAllocationInfo getMappedBuffer(int stateIndex, size_t count, size_t stride,
373 size_t reservedCount=0, size_t xtraAlignment=1) {
374 BufferSubAllocator buffer = this->getBuffer(stateIndex,
375 std::max(count, reservedCount),
376 stride,
377 xtraAlignment,
378 ClearBuffer::kNo,
379 Shareable::kNo);
380 auto [writer, binding] = buffer.getMappedSubrange(count, stride);
381 return {std::move(writer), binding, std::move(buffer)};
382 }
383
384 // Helper method for the public GPU-only BufferBindInfo methods
385 BindBufferInfo getBinding(int stateIndex, size_t requiredBytes, ClearBuffer cleared) {
386 auto alloc = this->getBuffer(stateIndex, requiredBytes,
387 /*stride=*/1, /*xtraAlignment=*/1,
388 cleared, Shareable::kNo);
389 // `alloc` goes out of scope when this returns, but that is okay because it is only used
390 // for GPU-only, non-shareable buffers. The returned BindBufferInfo will be unique still.
391 return alloc.getSubrange(requiredBytes, /*stride=*/1);
392 }
393
394 // Marks manager in a failed state, unmaps any previously collected buffers.
395 void onFailedBuffer();
396
397 ResourceProvider* const fResourceProvider;
398 const Caps* const fCaps;
399 UploadBufferManager* fUploadManager;
400
401 static constexpr size_t kVertexBufferIndex = 0;
402 static constexpr size_t kIndexBufferIndex = 1;
403 static constexpr size_t kUniformBufferIndex = 2;
404 static constexpr size_t kStorageBufferIndex = 3;
405 static constexpr size_t kGpuOnlyStorageBufferIndex = 4;
406 static constexpr size_t kVertexStorageBufferIndex = 5;
407 static constexpr size_t kIndexStorageBufferIndex = 6;
408 static constexpr size_t kIndirectStorageBufferIndex = 7;
409 std::array<BufferState, 8> fCurrentBuffers;
410
411 // Vector of buffer and transfer buffer pairs.
412 skia_private::TArray<std::pair<sk_sp<Buffer>, BindBufferInfo>> fUsedBuffers;
413
414 // List of buffer regions that were requested to be cleared at the time of allocation.
415 skia_private::TArray<BindBufferInfo> fClearList;
416
417 // If mapping failed on Buffers created/managed by this DrawBufferManager or by the mapped
418 // transfer buffers from the UploadManager, remember so that the next Recording will fail.
419 bool fMappingFailed = false;
420 };
421
422 /**
423 * The StaticBufferManager is the one-time-only analog to DrawBufferManager and provides "static"
424 * Buffers to RenderSteps and other Context-lifetime-tied objects, where the Buffers' contents will
425 * not change and can benefit from prioritizing GPU reads. The assumed use case is that they remain
426 * read-only on the GPU as well, so a single static buffer can be shared by all Recorders.
427 *
428 * Unlike DrawBufferManager's getXWriter() functions that return both a Writer and a BindBufferInfo,
429 * StaticBufferManager returns only a Writer and accepts a BindBufferInfo* as an argument. This will
430 * be re-written with the final binding info for the GPU-private data once that can be determined
431 * after *all* static buffers have been requested.
432 */
433 class StaticBufferManager {
434 public:
435 StaticBufferManager(ResourceProvider*, const Caps*);
436 ~StaticBufferManager();
437
438 // The passed in BindBufferInfos are updated when finalize() is later called, to point to the
439 // packed, GPU-private buffer at the appropriate offset. The data written to the returned Writer
440 // is copied to the private buffer at that offset. 'binding' must live until finalize() returns.
441
442 // For the vertex writer, the count and stride of the buffer is passed to allow alignment of
443 // future vertices.
444 VertexWriter getVertexWriter(size_t count, size_t stride, BindBufferInfo* binding);
445 // TODO: Update the tessellation index buffer generation functions to use an IndexWriter so this
446 // can return an IndexWriter vs. a VertexWriter that happens to just write uint16s...
447 VertexWriter getIndexWriter(size_t size, BindBufferInfo* binding);
448
449 enum class FinishResult : int {
450 kFailure, // Unable to create or copy static buffers
451 kSuccess, // Successfully created static buffers and added GPU tasks to the queue
452 kNoWork // No static buffers required, no GPU tasks add to the queue
453 };
454
455 // Finalizes all buffers and records a copy task to compact and privatize static data. The
456 // final static buffers will become owned by the Context's GlobalCache.
457 FinishResult finalize(Context*, QueueManager*, GlobalCache*);
458
459 private:
460 struct CopyRange {
461 BindBufferInfo fSource; // The CPU-to-GPU buffer and offset for the source of the copy
462 BindBufferInfo* fTarget; // The late-assigned destination of the copy
463 uint32_t fRequiredAlignment; // The requested stride of the data.
464 #if defined(GPU_TEST_UTILS)
465 uint32_t fUnalignedSize; // The requested size without count-4 alignment
466 #endif
467 };
468 struct BufferState {
469 BufferState(BufferType type, const Caps* caps);
470
471 bool createAndUpdateBindings(ResourceProvider*, Context*, QueueManager*, GlobalCache*,
472 std::string_view label) const;
473 void reset() {
474 fData.clear();
475 fTotalRequiredBytes = 0;
476 }
477
478 const BufferType fBufferType;
479 // This is the lcm of the alignment requirement of the buffer type and the transfer buffer
480 // alignment requirement.
481 const uint32_t fMinimumAlignment;
482
483 skia_private::TArray<CopyRange> fData;
484 uint32_t fTotalRequiredBytes;
485 };
486
487 void* prepareStaticData(BufferState* info,
488 size_t requiredBytes,
489 size_t requiredAlignment,
490 BindBufferInfo* target);
491
492 ResourceProvider* const fResourceProvider;
493 UploadBufferManager fUploadManager;
494 const uint32_t fRequiredTransferAlignment;
495
496 // The source data that's copied into a final GPU-private buffer
497 BufferState fVertexBufferState;
498 BufferState fIndexBufferState;
499
500 // If mapping failed on Buffers created/managed by this StaticBufferManager or by the mapped
501 // transfer buffers from the UploadManager, remember so that finalize() will fail.
502 bool fMappingFailed = false;
503 };
504
505 } // namespace skgpu::graphite
506
507 #endif // skgpu_graphite_BufferManager_DEFINED