Debian Codegraph @

src/gpu/graphite/BufferManager.cpp

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 #include "src/gpu/graphite/BufferManager.h"
8
9 #include "include/gpu/GpuTypes.h"
10 #include "include/gpu/graphite/Recording.h"
11 #include "include/private/base/SkAlign.h"
12 #include "include/private/base/SkAssert.h"
13 #include "include/private/base/SkMath.h"
14 #include "include/private/base/SkTo.h"
15 #include "src/gpu/graphite/Caps.h"
16 #include "src/gpu/graphite/GlobalCache.h"
17 #include "src/gpu/graphite/Log.h"
18 #include "src/gpu/graphite/QueueManager.h"
19 #include "src/gpu/graphite/RecordingPriv.h"
20 #include "src/gpu/graphite/Resource.h"
21 #include "src/gpu/graphite/ResourceProvider.h"
22 #include "src/gpu/graphite/UploadBufferManager.h"
23 #include "src/gpu/graphite/task/ClearBuffersTask.h"
24 #include "src/gpu/graphite/task/CopyTask.h"
25 #include "src/gpu/graphite/task/Task.h"
26 #include "src/gpu/graphite/task/TaskList.h"
27
28 #include <algorithm>
29 #include <cstddef>
30 #include <cstring>
31 #include <limits>
32 #include <numeric>
33 #include <tuple>
34
35 namespace skgpu::graphite {
36
37 namespace {
38
39 // The limit for all data created by the StaticBufferManager. This data remains alive for
40 // the entire SharedContext so we want to keep it small and give a concrete upper bound to
41 // clients for our steady-state memory usage.
42 // FIXME The current usage is 4732 bytes across static vertex and index buffers, but that includes
43 // multiple copies of tessellation data, and an unoptimized AnalyticRRect mesh. Once those issues
44 // are addressed, we can tighten this and decide on the transfer buffer sizing as well.
45 [[maybe_unused]] static constexpr uint32_t kMaxStaticDataSize = 6 << 10;
46
47 uint32_t validate_count_and_stride(size_t count, size_t stride, uint32_t alignment) {
48 // size_t may just be uint32_t, so this ensures we have enough bits to
49 // compute the required byte product.
50 uint64_t count64 = SkTo<uint64_t>(count);
51 uint64_t stride64 = SkTo<uint64_t>(stride);
52 uint64_t bytes64 = count64*stride64;
53 if (count64 > std::numeric_limits<uint32_t>::max() ||
54 stride64 > std::numeric_limits<uint32_t>::max() ||
55 bytes64 > std::numeric_limits<uint32_t>::max() - (alignment + 1)) {
56 // Return 0 to skip further allocation attempts.
57 return 0;
58 }
59 // Since count64 and stride64 fit into 32-bits, their product won't overflow a 64-bit multiply,
60 // and we've confirmed product fits into 32-bits with head room to be aligned w/o overflow.
61 return SkTo<uint32_t>(bytes64);
62 }
63
64 // Calculates the LCM of `alignMaybePow2` and `alignProbNonPow2`. Neither value needs to be a
65 // power of 2, but this is optimized to check for whether or not `alignMaybePow2` is a power of 2.
66 // It assumes the probability of the 2nd alignment value being a power of 2 is low enough to not
67 // be worth checking.
68 uint32_t lcm_alignment(uint32_t alignMaybePow2, uint32_t alignProbNonPow2) {
69 SkASSERT(alignMaybePow2 != 0 && alignProbNonPow2 != 0);
70 if (alignMaybePow2 == 1 ||
71 alignMaybePow2 == alignProbNonPow2 ||
72 (SkIsPow2(alignMaybePow2) &&
73 alignProbNonPow2 > alignMaybePow2 &&
74 (alignProbNonPow2 & (alignMaybePow2 - 1)) == 0)) {
75 // Trivial LCM since alignProbNonPow2 is the same or a larger multiple of alignMaybePow2
76 return alignProbNonPow2;
77 } else {
78 return std::lcm(alignMaybePow2, alignProbNonPow2);
79 }
80 }
81
82 // Helpers for creating a BufferState based on type, options, and caps
83
84 AccessPattern get_gpu_access_pattern(bool isGpuOnlyAccess, const DrawBufferManager::Options& opts) {
85 if (isGpuOnlyAccess) {
86 #if defined(GPU_TEST_UTILS)
87 if (opts.fAllowCopyingGpuOnly) {
88 return AccessPattern::kGpuOnlyCopySrc;
89 }
90 #endif
91 return AccessPattern::kGpuOnly;
92 } else {
93 return AccessPattern::kHostVisible;
94 }
95 }
96
97 // This returns the minimum required alignment depending on the type of buffer. This is guaranteed
98 // to be a power of two.
99 uint32_t minimum_alignment(BufferType type, bool useTransferBuffers, const Caps* caps) {
100 uint32_t alignment = 4;
101 if (type == BufferType::kUniform) {
102 alignment = SkTo<uint32_t>(caps->requiredUniformBufferAlignment());
103 } else if (type == BufferType::kStorage || type == BufferType::kVertexStorage ||
104 type == BufferType::kIndexStorage || type == BufferType::kIndirect) {
105 alignment = SkTo<uint32_t>(caps->requiredStorageBufferAlignment());
106 }
107 if (useTransferBuffers) {
108 // Both alignment and the requiredTransferBufferAlignment must be powers of two, so max
109 // provides the correct alignment semantics
110 alignment = std::max(alignment, SkTo<uint32_t>(caps->requiredTransferBufferAlignment()));
111 }
112 return alignment;
113 }
114
115 uint32_t min_block_size(BufferType type,
116 uint32_t minAlignment,
117 const DrawBufferManager::Options& opts) {
118 uint32_t size;
119 if (type == BufferType::kIndex || type == BufferType::kIndexStorage) {
120 size = opts.fIndexBufferSize;
121 } else if (type == BufferType::kVertex || type == BufferType::kVertexStorage) {
122 size = opts.fVertexBufferMinSize;
123 } else {
124 size = opts.fStorageBufferMinSize;
125 }
126 #if defined(GPU_TEST_UTILS)
127 if (opts.fUseExactBuffSizes) {
128 return size; // No extra alignment
129 }
130 #endif
131
132 return SkAlignTo(size, minAlignment);
133 }
134
135 uint32_t max_block_size(BufferType type,
136 uint32_t minAlignment,
137 const DrawBufferManager::Options& opts) {
138 #if defined(GPU_TEST_UTILS)
139 if (opts.fUseExactBuffSizes) {
140 // Clamp to the minimum size
141 return min_block_size(type, minAlignment, opts);
142 }
143 #endif
144
145 uint32_t size;
146 if (type == BufferType::kIndex || type == BufferType::kIndexStorage) {
147 size = opts.fIndexBufferSize;
148 } else if (type == BufferType::kVertex || type == BufferType::kVertexStorage) {
149 size = opts.fVertexBufferMaxSize;
150 } else {
151 size = opts.fStorageBufferMaxSize;
152 }
153
154 return SkAlignTo(size, minAlignment);
155 }
156
157 } // anonymous namespace
158
159 // ------------------------------------------------------------------------------------------------
160 // BufferSubAllocator
161
162 BufferSubAllocator::BufferSubAllocator(DrawBufferManager* owner,
163 int stateIndex,
164 sk_sp<Buffer> buffer,
165 BindBufferInfo transferBuffer,
166 void* mappedPtr,
167 size_t stride)
168 : fOwner(owner)
169 , fStateIndex(stateIndex)
170 , fBuffer(std::move(buffer))
171 , fTransferBuffer(transferBuffer)
172 , fMappedPtr(mappedPtr)
173 , fOffset(0)
174 , fStride(SkTo<uint32_t>(stride)) {
175 // A starting offset of 0 means we don't need to explicitly lookup the minimum binding alignment
176 // since the first sub-allocation is automatically aligned.
177 if (fBuffer && fStride > 0 && fStride <= fBuffer->size()) {
178 // This puts the BufferSubAllocator in the same state as prepForStride(stride, *)
179 fRemaining = SkTo<uint32_t>(fBuffer->size()) / fStride;
180 } else {
181 fRemaining = 0;
182 }
183
184 SkASSERT(fStride != 0);
185 }
186
187 BufferSubAllocator& BufferSubAllocator::operator=(BufferSubAllocator&& other) {
188 if (this == &other) {
189 return *this; // no-op moving into itself
190 }
191
192 // Reset the destination allocator first since other's contents will overwrite whatever came
193 // beforehand and that must go back to the manager.
194 this->reset();
195
196 // Copy fields
197 fOwner = other.fOwner;
198 fStateIndex = other.fStateIndex;
199 fTransferBuffer = other.fTransferBuffer;
200 fMappedPtr = other.fMappedPtr;
201 fOffset = other.fOffset;
202 fStride = other.fStride;
203 fRemaining = other.fRemaining;
204
205 // Move buffer (leaving other in an invalid state)
206 fBuffer = std::move(other.fBuffer);
207 SkASSERT(!other);
208 return *this;
209 }
210
211 void BufferSubAllocator::prepForStride(size_t stride, size_t align, size_t minCount) {
212 SkASSERT(stride > 0 && align > 0); // Expect valid inputs
213 if (fBuffer) {
214 if (fStride == stride && (align == 1 || align == stride)) {
215 // Shortcut if we're already aligned with the last call to prepForStride().
216 // Leave fRemaining alone, it's either enough for minCount or not, but reserve() will
217 // do the right thing regardless.
218 SkASSERT(fOffset % align == 0);
219 SkASSERT(fOffset % stride == 0);
220 return;
221 }
222
223 // On re-aligning to a new stride, the offset needs to be aligned to the LCM of `align` and
224 // `stride` so that repeated suballocations of `stride` can be performed by simply adding to
225 // fOffset without additional instructions. If `fStride == 0`, it's a signal that the first
226 // offset also needs to be aligned to the minimum binding requirement.
227 uint32_t align32 = lcm_alignment(SkTo<uint32_t>(align), SkTo<uint32_t>(stride));
228 if (fStride == 0) {
229 const uint32_t minAlignment = fOwner->fCurrentBuffers[fStateIndex].fMinAlignment;
230 align32 = lcm_alignment(minAlignment, align32);
231 }
232
233 // Ensures we won't overflow fOffset past buffer size once we align it
234 if (this->remainingBytes() >= align32 - 1) {
235 const uint32_t offset = SkAlignNonPow2(fOffset, align32);
236 SkASSERT(offset <= fBuffer->size());
237 fStride = SkTo<uint32_t>(stride);
238 fRemaining = (SkTo<uint32_t>(fBuffer->size()) - offset) / fStride;
239 if (fRemaining > 0 && fRemaining >= minCount) {
240 // Successful prep, so preserve the aligned offset
241 fOffset = offset;
242 return;
243 }
244 }
245 }
246
247 // If we've reached here, there wasn't a buffer or enough room to align, or enough room to
248 // satisfy minCount, so set fRemaining=0 to fail subsequent reservations.
249 fRemaining = 0;
250 }
251
252 void BufferSubAllocator::reset() {
253 if (fBuffer) {
254 SkASSERT(fOwner);
255
•256 if (fOwner->fMappingFailed) {
257 fBuffer = nullptr;
258 fRemaining = 0;
259 fTransferBuffer = {};
260 return;
261 }
262
263 DrawBufferManager::BufferState& state = fOwner->fCurrentBuffers[fStateIndex];
264 if (fBuffer->shareable() == Shareable::kScratch) {
265 // TODO: Merge this reuse of scratch resources with the ScratchResourceManager, but
266 // currently this is resolved outside of Task::prepareResources().
267
268 // The scratch buffer's availability for reuse (scoped to the owning DrawBufferManager)
269 // was tied to this BufferSubAllocator, so when that is reset, we just remove the buffer
270 // from the set of unavailable buffers.
•271 SkASSERT(state.fUnavailableScratchBuffers.contains(fBuffer.get()));
272 state.fUnavailableScratchBuffers.remove(fBuffer.get());
273
274 SkASSERT(!fTransferBuffer); // Scratch buffers shouldn't be using transfer buffers
275 fOwner->fUsedBuffers.emplace_back(std::move(fBuffer), BindBufferInfo{});
276 } else if (state.fAvailableBuffer.fBuffer.get() == fBuffer.get() || // can't stash itself
277 this->remainingBytes() < state.fAvailableBuffer.remainingBytes() || // too small
278 this->remainingBytes() < state.fMinAlignment) { // basically empty
279 // Transfer ownership of the buffer (and any transfer buffer) back to the manager, using
280 // the current offset as a more restricted limit for copying.
281 if (fTransferBuffer) {
282 // This alignment ensures we are copying a subset that still respects xfer alignment
283 fTransferBuffer.fSize = SkAlignTo(fOffset, state.fMinAlignment);
284 }
285 fOwner->fUsedBuffers.emplace_back(std::move(fBuffer), fTransferBuffer);
286 } else {
287 // Save this buffer for later, which leaves this instance empty and resets the prior
288 // value of fAvailableBuffer (which then goes through the true branch of this if).
289 state.fAvailableBuffer = std::move(*this);
290 }
291
292 fRemaining = 0;
293 SkASSERT(!fBuffer);
294 } // else nothing to reset
295 }
296
297 // ------------------------------------------------------------------------------------------------
298 // DrawBufferManager::BufferState
299
300 DrawBufferManager::BufferState::BufferState(BufferType type,
301 const char* label,
302 bool isGpuOnly,
303 const Options& opts,
304 const Caps* caps)
305 : fType(type)
306 // The buffer can be GPU-only if
307 // a) the caller does not intend to ever upload CPU data to the buffer; or
308 // b) CPU data will get uploaded to fBuffer only via a transfer buffer
309 , fAccessPattern(get_gpu_access_pattern(isGpuOnly || !caps->drawBufferCanBeMapped(), opts))
310 , fUseTransferBuffer(!isGpuOnly && !caps->drawBufferCanBeMapped())
311 , fLabel(label)
312 , fMinAlignment(minimum_alignment(type, fUseTransferBuffer, caps))
313 , fMinBlockSize(min_block_size(type, fMinAlignment, opts))
314 , fMaxBlockSize(max_block_size(type, fMinAlignment, opts)) {
315 SkASSERT(SkIsPow2(fMinAlignment));
316 SkASSERT(fMinBlockSize <= fMaxBlockSize);
317 }
318
319 sk_sp<Buffer> DrawBufferManager::BufferState::findOrCreateBuffer(ResourceProvider* provider,
320 Shareable shareable,
321 uint32_t byteCount) {
322 if (shareable == Shareable::kScratch) {
323 sk_sp<Buffer> scratchBuffer = provider->findOrCreateScratchBuffer(
324 byteCount, fType, fAccessPattern, fLabel, fUnavailableScratchBuffers);
325 if (scratchBuffer) {
326 fUnavailableScratchBuffers.add(scratchBuffer.get());
327 }
328 return scratchBuffer;
329 } else {
330 return provider->findOrCreateNonShareableBuffer(byteCount, fType, fAccessPattern, fLabel);
331 }
332 }
333
334 // ------------------------------------------------------------------------------------------------
335 // DrawBufferManager
336
337 DrawBufferManager::DrawBufferManager(ResourceProvider* resourceProvider,
338 const Caps* caps,
339 UploadBufferManager* uploadManager,
340 Options dbmOpts)
341 : fResourceProvider(resourceProvider)
342 , fCaps(caps)
343 , fUploadManager(uploadManager)
344 , fCurrentBuffers{{
345 // Mappable buffers
346 {BufferType::kVertex, "VertexBuffer", /*isGpuOnly=*/false, dbmOpts, caps},
347 {BufferType::kIndex, "IndexBuffer", /*isGpuOnly=*/false, dbmOpts, caps},
348 {BufferType::kUniform, "UniformBuffer", /*isGpuOnly=*/false, dbmOpts, caps},
349 {BufferType::kStorage, "StorageBuffer", /*isGpuOnly=*/false, dbmOpts, caps},
350 // GPU-only buffers
351 {BufferType::kStorage, "GPUOnlyStorageBuffer", /*isGpuOnly=*/true, dbmOpts, caps},
352 {BufferType::kVertexStorage, "VertexStorageBuffer", /*isGpuOnly=*/true, dbmOpts, caps},
353 {BufferType::kIndexStorage, "IndexStorageBuffer", /*isGpuOnly=*/true, dbmOpts, caps},
354 {BufferType::kIndirect, "IndirectStorageBuffer", /*isGpuOnly=*/true, dbmOpts, caps}}} {}
355
356 DrawBufferManager::~DrawBufferManager() {
357 // Must reset these *before* we are deleted
358 for (auto& b : fCurrentBuffers) {
359 b.fAvailableBuffer.reset();
360 }
361 }
362
363 void DrawBufferManager::onFailedBuffer() {
364 fMappingFailed = true;
365
366 // Clean up and unmap everything now
367 fClearList.clear();
368 for (auto& state : fCurrentBuffers) {
369 state.fAvailableBuffer.reset();
370 // We aren't allocating anything anymore so don't maintain this list. Their outstanding
371 // BufferSubAllocators will have a no-op when they get reset.
372 state.fUnavailableScratchBuffers.reset();
373 state.fLastBufferSize = 0;
374 }
375
376 for (auto& [buffer, _] : fUsedBuffers) {
377 if (buffer->isMapped()) {
378 buffer->unmap();
379 }
380 }
381 fUsedBuffers.clear();
382 }
383
384 bool DrawBufferManager::transferToRecording(Recording* recording) {
385 if (fMappingFailed) {
386 // All state should have been reset by onFailedBuffer() except for this error flag.
387 SkASSERT(fUsedBuffers.empty() && fClearList.empty());
388 #if defined(SK_DEBUG)
389 for (const auto& state : fCurrentBuffers) {
390 SkASSERT(!SkToBool(state.fAvailableBuffer));
391 SkASSERT(state.fUnavailableScratchBuffers.empty());
392 }
393 #endif
394
395 fMappingFailed = false;
396 return false;
397 }
398
399 for (auto& state : fCurrentBuffers) {
400 // Reset all available buffer sub allocators since they won't be allocatable anymore.
401 // This pushes the underlying resource and transfer range to fUsedBuffers
402 state.fAvailableBuffer.reset();
403 // BufferSubAllocators should have gone out of scope well before Recorder::snap() is called.
404 SkASSERT(state.fUnavailableScratchBuffers.empty());
405
406 // We reset the last buffer size back to 0 to keep the buffer growth behavior the same
407 // across calls to snap(). If we knew every snap() would be approximately the same workload,
408 // we could choose to keep the last alloc size as-is so that subsequent frames create
409 // fewer buffers. We choose *not* to do this because:
410 // - Chrome often snaps Recordings with disparate workloads within a frame (e.g. tile vs
411 // canvas2d) and we don't want to overallocate on a small recording.
412 // - It obfuscates the performance cost of the first frame if we reach a steady state that
413 // requires no additional buffer allocations.
414 // We could choose to reduce fLastBufferSize (e.g. halve it) to get a head start and reduce
415 // the potential for over-allocation, but in performance measurements on buffer-heavy scenes
416 // this did not lead to measurable improvements. Thus, we reset so every frame is the same.
417 state.fLastBufferSize = 0;
418 }
419
420 if (!fClearList.empty()) {
421 recording->priv().taskList()->add(ClearBuffersTask::Make(std::move(fClearList)));
422 }
423
424 for (auto& [buffer, transferBuffer] : fUsedBuffers) {
425 if (transferBuffer) {
426 SkASSERT(buffer);
427 SkASSERT(!fCaps->drawBufferCanBeMapped());
428 // Since the transfer buffer is managed by the UploadManager, we don't manually unmap
429 // it here or need to pass a ref into CopyBufferToBufferTask.
430 size_t copySize = buffer->size();
431 recording->priv().taskList()->add(
432 CopyBufferToBufferTask::Make(transferBuffer.fBuffer,
433 transferBuffer.fOffset,
434 std::move(buffer),
435 /*dstOffset=*/0,
436 copySize));
437 } else {
438 if (buffer->isMapped()) {
439 buffer->unmap();
440 }
441 recording->priv().addResourceRef(std::move(buffer));
442 }
443 }
444
445 fUsedBuffers.clear();
446
447 return true;
448 }
449
450 BufferSubAllocator DrawBufferManager::getBuffer(
451 int stateIndex,
452 size_t count,
453 size_t stride,
454 size_t xtraAlignment,
455 ClearBuffer cleared,
456 Shareable shareable) {
457 BufferState& state = fCurrentBuffers[stateIndex];
458 // The size for a buffer is aligned to the minimum block size for better resource reuse, which
459 // is more conservative than fMinAlignment.
460 uint32_t requiredBytes32 = validate_count_and_stride(count, stride, state.fMinBlockSize);
461 if (fMappingFailed || !requiredBytes32) {
462 return {};
463 }
464
465 const bool supportCpuUpload = state.fAccessPattern == AccessPattern::kHostVisible ||
466 state.fUseTransferBuffer;
467 // Shareable buffers must be GPU-only to actually share effectively.
468 SkASSERT(shareable == Shareable::kNo || !supportCpuUpload);
469
470 // For non-shareable buffers, we keep the largest relinquished non-shareable buffer in case it
471 // has room leftover to be used by future allocations. Scratch buffer ownership is entirely
472 // managed by the caller, so always create a new BufferSubAllocator.
473 if (shareable == Shareable::kNo) {
474 state.fAvailableBuffer.resetForNewBinding(); // ensure we include min binding alignment
475 state.fAvailableBuffer.prepForStride(stride, xtraAlignment, count);
476 if (state.fAvailableBuffer.availableWithStride() >= count) {
477 SkASSERT(state.fAvailableBuffer.fBuffer);
478 SkASSERT(state.fAvailableBuffer.fBuffer->shareable() == shareable);
479 SkASSERT(SkToBool(state.fAvailableBuffer.fMappedPtr) == supportCpuUpload);
480 return std::move(state.fAvailableBuffer);
481 }
482
483 // Not enough room in the available buffer so release it and create a new buffer.
484 state.fAvailableBuffer.reset();
485 }
486
487 // Create the next buffer by doubling the size of the previous buffer and clamping to be within
488 // the min and max block sizes if `requiredBytes` is less than the max. Otherwise, create a
489 // buffer large enough to satisfy `requiredBytes` but align it to minBlockSize.
490 uint32_t bufferSize = SkAlignTo(requiredBytes32, state.fMinBlockSize);
491 if (bufferSize < state.fMaxBlockSize) {
492 // fMaxBlockSize should be sufficiently small that there's no risk of overflowing here.
493 SkASSERT(std::numeric_limits<uint32_t>::max() /2 > state.fLastBufferSize);
494 bufferSize = std::max(bufferSize, std::min(state.fLastBufferSize * 2, state.fMaxBlockSize));
495 state.fLastBufferSize = bufferSize;
496 SkASSERT(bufferSize <= state.fMaxBlockSize);
497 } else {
498 // Jump to the max block size for subsequent amortized allocations if we get a really big
499 // buffer request.
500 state.fLastBufferSize = state.fMaxBlockSize;
501 }
502 SkASSERT(bufferSize >= requiredBytes32 && bufferSize >= state.fMinBlockSize);
503
504 sk_sp<Buffer> buffer = state.findOrCreateBuffer(fResourceProvider, shareable, bufferSize);
505 if (!buffer) {
506 this->onFailedBuffer();
507 return {};
508 }
509
510 BindBufferInfo transferBuffer;
511 void* mappedPtr = nullptr;
512 if (supportCpuUpload) {
513 if (state.fUseTransferBuffer) {
514 std::tie(mappedPtr, transferBuffer) = fUploadManager->makeBindInfo(buffer->size(),
515 fCaps->requiredTransferBufferAlignment(), "TransferForDataBuffer");
516 } else {
517 mappedPtr = buffer->map();
518 }
519
520 if (!mappedPtr) {
521 this->onFailedBuffer(); // Either transfer buffer failed or direct mapping failed
522 return {};
523 }
524 }
525
526 if (cleared == ClearBuffer::kYes) {
527 fClearList.push_back(BindBufferInfo{buffer.get(), 0, bufferSize});
528 }
529
530 // The returned buffer is not set to fAvailableBuffer because it is going to be passed up to
531 // the caller for their use first. Since a new BufferSubAllocator starts at offset 0, there's no
532 // need to account for `xtraAlignment`.
533 return BufferSubAllocator(this, stateIndex, std::move(buffer),
534 transferBuffer, mappedPtr, stride);
535 }
536
537 // ------------------------------------------------------------------------------------------------
538 // StaticBufferManager
539
540 StaticBufferManager::StaticBufferManager(ResourceProvider* resourceProvider,
541 const Caps* caps)
542 : fResourceProvider(resourceProvider)
543 , fUploadManager(resourceProvider, caps)
544 , fRequiredTransferAlignment(SkTo<uint32_t>(caps->requiredTransferBufferAlignment()))
545 , fVertexBufferState(BufferType::kVertex, caps)
546 , fIndexBufferState(BufferType::kIndex, caps) {}
547 StaticBufferManager::~StaticBufferManager() = default;
548
549 StaticBufferManager::BufferState::BufferState(BufferType type, const Caps* caps)
550 : fBufferType(type)
551 , fMinimumAlignment(minimum_alignment(type, /*useTransferBuffers=*/true, caps))
552 , fTotalRequiredBytes(0) {}
553
554 // ARM hardware b/399631317 also means that static vertex data must be padded and zeroed out. So we
555 // always request a count 4 aligned offset, count 4 aligned amount of space, and zero it.
556 VertexWriter StaticBufferManager::getVertexWriter(size_t count,
557 size_t stride,
558 BindBufferInfo* binding) {
559 const size_t size = count * stride;
560 const size_t alignedCount = SkAlign4(count);
561 void* data = this->prepareStaticData(&fVertexBufferState, size, stride * 4, binding);
562 if (alignedCount > count) {
563 const uint32_t byteDiff = (alignedCount - count) * stride;
564 void* zPtr = SkTAddOffset<void>(data, count * stride);
565 memset(zPtr, 0, byteDiff);
566 }
567 return VertexWriter{data, size};
568 }
569
570 VertexWriter StaticBufferManager::getIndexWriter(size_t size, BindBufferInfo* binding) {
571 // The index writer does not have the same alignment requirements as a vertex, so we simply pass
572 // in the minimum alignment as the required alignment
573 void* data = this->prepareStaticData(&fIndexBufferState,
574 size,
575 fIndexBufferState.fMinimumAlignment,
576 binding);
577 return VertexWriter{data, size};
578 }
579
580 void* StaticBufferManager::prepareStaticData(BufferState* state,
581 size_t requiredBytes,
582 size_t requiredAlignment,
583 BindBufferInfo* target) {
584 // Zero-out the target binding in the event of any failure in actually transfering data later.
585 // Unlike in BufferSubAllocator::reserve(), we do use SkTo<uint32_t> to check
586 // `requiredAlignment`. This is not dynamic data and is fully controlled by Graphite, so if it
587 // asserts, then there is a bug in the static data for a Renderer that must be fixed.
588 const uint32_t align32 = lcm_alignment(state->fMinimumAlignment,
589 SkTo<uint32_t>(requiredAlignment));
590
591 SkASSERT(target);
592 *target = {nullptr, 0};
593 uint32_t size32 = validate_count_and_stride(requiredBytes, /*stride=*/1, align32);
594 if (!size32 || fMappingFailed) {
595 return nullptr;
596 }
597
598 // Copy data must be aligned to the transfer alignment, so align the reserved size to the LCM
599 // of the minimum alignment (already net buffer and transfer alignment) and the required
600 // alignment stride.
601 size32 = SkAlignNonPow2(size32, align32);
602 auto [transferMapPtr, transferBindInfo] =
603 fUploadManager.makeBindInfo(size32,
604 fRequiredTransferAlignment,
605 "TransferForStaticBuffer");
606 if (!transferMapPtr) {
607 SKGPU_LOG_E("Failed to create or map transfer buffer that initializes static GPU data.");
608 fMappingFailed = true;
609 return nullptr;
610 }
611
612 state->fData.push_back(
613 {transferBindInfo,
614 target,
615 SkTo<uint32_t>(requiredAlignment),
616 #if defined(GPU_TEST_UTILS)
617 SkTo<uint32_t>(requiredBytes)
618 #endif
619 });
620
621 state->fTotalRequiredBytes = SkAlignNonPow2(state->fTotalRequiredBytes, align32) + size32;
622
623 return transferMapPtr;
624 }
625
626 bool StaticBufferManager::BufferState::createAndUpdateBindings(
627 ResourceProvider* resourceProvider,
628 Context* context,
629 QueueManager* queueManager,
630 GlobalCache* globalCache,
631 std::string_view label) const {
632 if (!fTotalRequiredBytes) {
633 return true; // No buffer needed
634 }
635
636 // The static buffer is always copyable when testing.
637 constexpr AccessPattern gpuAccessPattern =
638 #if defined(GPU_TEST_UTILS)
639 AccessPattern::kGpuOnlyCopySrc;
640 #else
641 AccessPattern::kGpuOnly;
642 #endif
643
644 sk_sp<Buffer> staticBuffer = resourceProvider->findOrCreateNonShareableBuffer(
645 fTotalRequiredBytes,
646 fBufferType,
647 gpuAccessPattern,
648 label);
649 if (!staticBuffer) {
650 SKGPU_LOG_E("Failed to create static buffer for type %d of size %u bytes.\n",
651 (int) fBufferType, fTotalRequiredBytes);
652 return false;
653 }
654
655 uint32_t offset = 0;
656 for (const CopyRange& data : fData) {
657 // Each copy range's size should be aligned to the lcm of the required alignment and minimum
658 // alignment so we can increment the offset in the static buffer.
659 const uint32_t alignment = lcm_alignment(fMinimumAlignment, data.fRequiredAlignment);
660 offset = SkAlignNonPow2(offset, alignment);
661 SkASSERT(!(offset % fMinimumAlignment) && !(offset % data.fRequiredAlignment));
662 uint32_t size = data.fSource.fSize;
663 data.fTarget->fBuffer = staticBuffer.get();
664 data.fTarget->fOffset = offset;
665 data.fTarget->fSize = size;
666
667 auto copyTask = CopyBufferToBufferTask::Make(
668 data.fSource.fBuffer, data.fSource.fOffset,
669 sk_ref_sp(data.fTarget->fBuffer), data.fTarget->fOffset,
670 size);
671 // For static buffers, we want them all to be optimized as GPU only buffers. If we are in
672 // a protected context, this means the buffers must be non-protected since they will be
673 // read in the vertex shader which doesn't allow protected memory access. Thus all the
674 // uploads to these buffers must be done as non-protected commands.
675 if (!queueManager->addTask(copyTask.get(), context, Protected::kNo)) {
676 SKGPU_LOG_E("Failed to copy data to static buffer.\n");
677 return false;
678 }
679
680 offset += size;
681 }
682
683 SkASSERT(offset == fTotalRequiredBytes);
684 globalCache->addStaticResource(std::move(staticBuffer));
685 return true;
686 }
687
688 StaticBufferManager::FinishResult StaticBufferManager::finalize(Context* context,
689 QueueManager* queueManager,
690 GlobalCache* globalCache) {
691 if (fMappingFailed) {
692 return FinishResult::kFailure;
693 }
694
695 const size_t totalRequiredBytes = fVertexBufferState.fTotalRequiredBytes +
696 fIndexBufferState.fTotalRequiredBytes;
697 SkASSERT(totalRequiredBytes <= kMaxStaticDataSize);
698 if (!totalRequiredBytes) {
699 return FinishResult::kNoWork;
700 }
701
702 if (!fVertexBufferState.createAndUpdateBindings(fResourceProvider,
703 context,
704 queueManager,
705 globalCache,
706 "StaticVertexBuffer")) {
707 return FinishResult::kFailure;
708 }
709
710 #if defined(GPU_TEST_UTILS)
711 skia_private::TArray<GlobalCache::StaticVertexCopyRanges> statVertCopy;
712 for (const CopyRange& data : fVertexBufferState.fData) {
713 statVertCopy.push_back({data.fTarget->fOffset,
714 data.fUnalignedSize,
715 data.fTarget->fSize,
716 data.fRequiredAlignment});
717 }
718 globalCache->testingOnly_SetStaticVertexInfo(
719 statVertCopy,
720 fVertexBufferState.fData[0].fTarget->fBuffer);
721 #endif
722
723 if (!fIndexBufferState.createAndUpdateBindings(fResourceProvider,
724 context,
725 queueManager,
726 globalCache,
727 "StaticIndexBuffer")) {
728 return FinishResult::kFailure;
729 }
730 queueManager->addUploadBufferManagerRefs(&fUploadManager);
731
732 // Reset the static buffer manager since the Recording's copy tasks now manage ownership of
733 // the transfer buffers and the GlobalCache owns the final static buffers.
734 fVertexBufferState.reset();
735 fIndexBufferState.reset();
736
737 return FinishResult::kSuccess;
738 }
739
740 } // namespace skgpu::graphite