Debian Codegraph @

src/gpu/graphite/dawn/DawnBuffer.cpp

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*
2 * Copyright 2022 Google LLC
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 #include "src/gpu/graphite/dawn/DawnBuffer.h"
9
10 #include "include/core/SkTraceMemoryDump.h"
11 #include "include/private/base/SkAlign.h"
12 #include "src/gpu/graphite/Log.h"
13 #include "src/gpu/graphite/dawn/DawnAsyncWait.h"
14 #include "src/gpu/graphite/dawn/DawnSharedContext.h"
15
16 namespace skgpu::graphite {
17 namespace {
18 #if defined(__EMSCRIPTEN__)
19 bool is_map_succeeded(WGPUBufferMapAsyncStatus status) {
20 return status == WGPUBufferMapAsyncStatus_Success;
21 }
22
23 [[maybe_unused]]
24 void log_map_error(WGPUBufferMapAsyncStatus status, const char*) {
25 const char* statusStr;
26 LogPriority priority = LogPriority::kError;
27 switch (status) {
28 case WGPUBufferMapAsyncStatus_ValidationError:
29 statusStr = "ValidationError";
30 break;
31 case WGPUBufferMapAsyncStatus_Unknown:
32 statusStr = "Unknown";
33 break;
34 case WGPUBufferMapAsyncStatus_DeviceLost:
35 statusStr = "DeviceLost";
36 break;
37 case WGPUBufferMapAsyncStatus_DestroyedBeforeCallback:
38 statusStr = "DestroyedBeforeCallback";
39 priority = LogPriority::kDebug;
40 break;
41 case WGPUBufferMapAsyncStatus_UnmappedBeforeCallback:
42 statusStr = "UnmappedBeforeCallback";
43 priority = LogPriority::kDebug;
44 break;
45 case WGPUBufferMapAsyncStatus_MappingAlreadyPending:
46 statusStr = "MappingAlreadyPending";
47 break;
48 case WGPUBufferMapAsyncStatus_OffsetOutOfRange:
49 statusStr = "OffsetOutOfRange";
50 break;
51 case WGPUBufferMapAsyncStatus_SizeOutOfRange:
52 statusStr = "SizeOutOfRange";
53 break;
54 default:
55 statusStr = "<other>";
56 break;
57 }
58 SKGPU_LOG(priority, "Buffer async map failed with status %s.", statusStr);
59 }
60
61 #else
62
63 bool is_map_succeeded(wgpu::MapAsyncStatus status) {
64 return status == wgpu::MapAsyncStatus::Success;
65 }
66
67 void log_map_error(wgpu::MapAsyncStatus status, wgpu::StringView message) {
68 const char* statusStr;
69 switch (status) {
70 case wgpu::MapAsyncStatus::CallbackCancelled:
71 statusStr = "CallbackCancelled";
72 break;
73 case wgpu::MapAsyncStatus::Error:
74 statusStr = "Error";
75 break;
76 case wgpu::MapAsyncStatus::Aborted:
77 statusStr = "Aborted";
78 break;
79 case wgpu::MapAsyncStatus::Success:
80 SkDEBUGFAIL("This status is not an error");
81 return;
82 }
83 SKGPU_LOG(LogPriority::kError,
84 "Buffer async map failed with status %s, message '%.*s'.",
85 statusStr,
86 static_cast<int>(message.length),
87 message.data);
88 }
89 #endif // defined(__EMSCRIPTEN__)
90 } // namespace
91
92 sk_sp<DawnBuffer> DawnBuffer::Make(const DawnSharedContext* sharedContext,
93 size_t size,
94 BufferType type,
95 AccessPattern accessPattern) {
96 if (size <= 0) {
97 return nullptr;
98 }
99
100 wgpu::BufferUsage usage = wgpu::BufferUsage::None;
101
102 switch (type) {
103 case BufferType::kVertex:
104 usage = wgpu::BufferUsage::Vertex | wgpu::BufferUsage::CopyDst;
105 break;
106 case BufferType::kIndex:
107 usage = wgpu::BufferUsage::Index | wgpu::BufferUsage::CopyDst;
108 break;
109 case BufferType::kXferCpuToGpu:
110 usage = wgpu::BufferUsage::CopySrc | wgpu::BufferUsage::MapWrite;
111 break;
112 case BufferType::kXferGpuToCpu:
113 usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead;
114 break;
115 case BufferType::kUniform:
116 usage = wgpu::BufferUsage::Uniform | wgpu::BufferUsage::CopyDst;
117 break;
118 case BufferType::kStorage:
119 usage = wgpu::BufferUsage::Storage | wgpu::BufferUsage::CopyDst |
120 wgpu::BufferUsage::CopySrc;
121 break;
122 case BufferType::kQuery:
123 usage = wgpu::BufferUsage::QueryResolve | wgpu::BufferUsage::CopySrc;
124 break;
125 case BufferType::kIndirect:
126 usage = wgpu::BufferUsage::Indirect | wgpu::BufferUsage::Storage |
127 wgpu::BufferUsage::CopyDst;
128 break;
129 case BufferType::kVertexStorage:
130 usage = wgpu::BufferUsage::Vertex | wgpu::BufferUsage::Storage;
131 break;
132 case BufferType::kIndexStorage:
133 usage = wgpu::BufferUsage::Index | wgpu::BufferUsage::Storage;
134 break;
135 }
136
137 if (sharedContext->caps()->drawBufferCanBeMapped() &&
138 accessPattern == AccessPattern::kHostVisible && type != BufferType::kXferGpuToCpu) {
139 if (type == BufferType::kQuery) {
140 // We can map the query buffer to get the results directly rather than having to copy to
141 // a transfer buffer.
142 usage |= wgpu::BufferUsage::MapRead;
143 } else {
144 // If the buffer is intended to be mappable, add MapWrite usage and remove
145 // CopyDst.
146 // We don't want to allow both CPU and GPU to write to the same buffer.
147 usage |= wgpu::BufferUsage::MapWrite;
148 usage &= ~wgpu::BufferUsage::CopyDst;
149 }
150 }
151
152 if (accessPattern == AccessPattern::kGpuOnlyCopySrc) {
153 usage |= wgpu::BufferUsage::CopySrc;
154 }
155
156 wgpu::BufferDescriptor desc;
157 desc.usage = usage;
158 desc.size = size;
159 // Specifying mappedAtCreation avoids clearing the buffer on the GPU which can cause MapAsync to
160 // be very slow as it waits for GPU execution to complete.
161 desc.mappedAtCreation = SkToBool(usage & wgpu::BufferUsage::MapWrite);
162
163 auto buffer = sharedContext->device().CreateBuffer(&desc);
164 if (!buffer) {
165 return {};
166 }
167
168 void* mappedAtCreationPtr = nullptr;
169 if (desc.mappedAtCreation) {
170 mappedAtCreationPtr = buffer.GetMappedRange();
171 SkASSERT(mappedAtCreationPtr);
172 }
173
174 return sk_sp<DawnBuffer>(
175 new DawnBuffer(sharedContext, size, std::move(buffer), mappedAtCreationPtr));
176 }
177
178 DawnBuffer::DawnBuffer(const DawnSharedContext* sharedContext,
179 size_t size,
180 wgpu::Buffer buffer,
181 void* mappedAtCreationPtr)
182 : Buffer(sharedContext,
183 size,
184 Protected::kNo, // Dawn doesn't support protected memory
185 /*reusableRequiresPurgeable=*/buffer.GetUsage() & wgpu::BufferUsage::MapWrite,
186 #if defined(__EMSCRIPTEN__)
187 // prepareForReturnToCache only needs to be called for a buffer that is mappable
188 // for writing
189 /* requiresPrepareForReturnToCache= */
190 fBuffer.GetUsage() & wgpu::BufferUsage::MapWrite
191 #else
192 /* requiresPrepareForReturnToCache= */ false)
193 #endif
194 , fBuffer(std::move(buffer)) {
195
196 fMapPtr = mappedAtCreationPtr;
197 }
198
199 #if defined(__EMSCRIPTEN__)
200 bool DawnBuffer::prepareForReturnToCache(Resource::TakeRefFunc takeRef, void* takeRefCtx) {
201 // This function is only useful for Emscripten where we have to pre-map the buffer
202 // once it is returned to the cache.
203 SkASSERT(this->sharedContext()->caps()->bufferMapsAreAsync());
204
205 // This implementation is almost Dawn-agnostic. However, Buffer base class doesn't have any
206 // way of distinguishing a buffer that is mappable for writing from one mappable for reading.
207 // We only need to re-map the former.
208 SkASSERT(fBuffer.GetUsage() & wgpu::BufferUsage::MapWrite);
209
210 // We cannot start an async map while the GPU is still using the buffer. We asked that
211 // our Resource not become reusable until it was purgeable (no outstanding CPU or GPU refs)
212 SkASSERT(this->isPurgeable());
213 // Note that the map state cannot change on another thread when we are here. We got here
214 // because there were no UsageRefs on the buffer but async mapping holds a UsageRef until it
215 // completes.
216 if (this->isMapped()) {
217 return false;
218 }
219 takeRef(takeRefCtx);
220 this->asyncMap([](void* ctx, skgpu::CallbackResult result) {
221 sk_sp<DawnBuffer> buffer(static_cast<DawnBuffer*>(ctx));
222 if (result != skgpu::CallbackResult::kSuccess) {
223 buffer->setDeleteASAP();
224 }
225 },
226 this);
227 return true;
228 }
229
230 void DawnBuffer::onAsyncMap(GpuFinishedProc proc, GpuFinishedContext ctx) {
231 // This function is only useful for Emscripten where we have to use asyncMap().
232 SkASSERT(this->sharedContext()->caps()->bufferMapsAreAsync());
233
234 if (proc) {
235 SkAutoMutexExclusive ex(fAsyncMutex);
236 if (this->isMapped()) {
237 proc(ctx, CallbackResult::kSuccess);
238 return;
239 }
240 fAsyncMapCallbacks.emplace_back(proc, ctx);
241 }
242 if (this->isUnmappable()) {
243 return;
244 }
245 SkASSERT(fBuffer);
246 SkASSERT((fBuffer.GetUsage() & wgpu::BufferUsage::MapRead) ||
247 (fBuffer.GetUsage() & wgpu::BufferUsage::MapWrite));
248 SkASSERT(fBuffer.GetMapState() == wgpu::BufferMapState::Unmapped);
249 bool isWrite = fBuffer.GetUsage() & wgpu::BufferUsage::MapWrite;
250 auto buffer = sk_ref_sp(this);
251
252 fBuffer.MapAsync(
253 isWrite ? wgpu::MapMode::Write : wgpu::MapMode::Read,
254 0,
255 fBuffer.GetSize(),
256 [](WGPUBufferMapAsyncStatus s, void* userData) {
257 sk_sp<DawnBuffer> buffer(static_cast<DawnBuffer*>(userData));
258 buffer->mapCallback(s, /*message=*/nullptr);
259 },
260 buffer.release());
261 }
262
263 void DawnBuffer::onMap() {
264 SKGPU_LOG_W("Synchronous buffer mapping not supported in Dawn. Failing map request.");
265 }
266
267 #else
268
269 void DawnBuffer::onMap() {
270 SkASSERT(!this->sharedContext()->caps()->bufferMapsAreAsync());
271 SkASSERT(fBuffer);
272 SkASSERT((fBuffer.GetUsage() & wgpu::BufferUsage::MapRead) ||
273 (fBuffer.GetUsage() & wgpu::BufferUsage::MapWrite));
274 bool isWrite = fBuffer.GetUsage() & wgpu::BufferUsage::MapWrite;
275
276 // Use wgpu::Future and WaitAny with timeout=0 to trigger callback immediately.
277 // This should work because our resource tracking mechanism should make sure that
278 // the buffer is free of any GPU use at this point.
279 wgpu::FutureWaitInfo mapWaitInfo{};
280
281 mapWaitInfo.future = fBuffer.MapAsync(
282 isWrite ? wgpu::MapMode::Write : wgpu::MapMode::Read,
283 0,
284 fBuffer.GetSize(),
285 wgpu::CallbackMode::WaitAnyOnly,
286 [this](wgpu::MapAsyncStatus s, wgpu::StringView m) { this->mapCallback(s, m); });
287
288 wgpu::Instance instance = static_cast<const DawnSharedContext*>(sharedContext())->instance();
289 [[maybe_unused]] auto status = instance.WaitAny(1, &mapWaitInfo, /*timeoutNS=*/0);
290
291 if (status != wgpu::WaitStatus::Success) {
292 // WaitAny(timeout=0) might fail in this scenario:
293 // - Allocates a buffer.
294 // - Encodes a command buffer to copy a texture to this buffer.
295 // - Submits the command buffer. If OOM happens, this command buffer will fail to
296 // be submitted.
297 // - The buffer is *supposed* to be free of any GPU use since the command buffer that would
298 // have used it wasn't submitted successfully.
299 // - If we try to map this buffer at this point, internally Dawn will try to use GPU to
300 // clear this buffer to zeros, since this is its 1st use. WaitAny(timeout=0) won't work
301 // since the buffer now has a pending GPU clear operation.
302 //
303 // To work around this, we need to try again with a blocking WaitAny(), to wait for the
304 // clear operation to finish.
305 // Notes:
306 // - This fallback should be rare since it is caused by an OOM error during buffer
307 // readbacks.
308 // - For buffer writing cases, since we use mappedAtCreation, the GPU clear won't happen.
309 status = instance.WaitAny(
310 1, &mapWaitInfo, /*timeoutNS=*/std::numeric_limits<uint64_t>::max());
311 }
312
313 SkASSERT(status == wgpu::WaitStatus::Success);
314 SkASSERT(mapWaitInfo.completed);
315 }
316 #endif // defined(__EMSCRIPTEN__)
317
318 void DawnBuffer::onUnmap() {
319 SkASSERT(fBuffer);
320 SkASSERT(this->isUnmappable());
321
322 fMapPtr = nullptr;
323 fBuffer.Unmap();
324 }
325
326 template <typename StatusT, typename MessageT>
327 void DawnBuffer::mapCallback(StatusT status, MessageT message) {
328 SkAutoMutexExclusive em(this->fAsyncMutex);
329 if (is_map_succeeded(status)) {
330 if (this->fBuffer.GetUsage() & wgpu::BufferUsage::MapWrite) {
331 this->fMapPtr = this->fBuffer.GetMappedRange();
332 } else {
333 // If buffer is only created with MapRead usage, Dawn only allows returning
334 // constant pointer. We need to use const_cast as a workaround here.
335 this->fMapPtr = const_cast<void*>(this->fBuffer.GetConstMappedRange());
336 }
337 } else {
338 log_map_error(status, message);
339 for (auto& cb : this->fAsyncMapCallbacks) {
340 cb.setFailureResult();
341 }
342 }
343 this->fAsyncMapCallbacks.clear();
344 }
345
346 bool DawnBuffer::isUnmappable() const {
347 return fBuffer.GetMapState() != wgpu::BufferMapState::Unmapped;
348 }
349
350 void DawnBuffer::freeGpuData() {
351 if (fBuffer) {
352 // Explicitly destroy the buffer since it might be ref'd by cached bind groups which are
353 // not immediately cleaned up. Graphite should already guarantee that all command buffers
354 // using this buffer (indirectly via BindGroups) are already completed.
355 fBuffer.Destroy();
356 fBuffer = nullptr;
357 }
358 }
359
360 void DawnBuffer::setBackendLabel(char const* label) {
361 SkASSERT(label);
362 if (sharedContext()->caps()->setBackendLabels()) {
363 fBuffer.SetLabel(label);
364 }
365 }
366
367 } // namespace skgpu::graphite