Debian Codegraph @

src/gpu/graphite/vk/VulkanBuffer.cpp

raw
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/vk/VulkanBuffer.h"
9
10 #include "include/gpu/vk/VulkanMemoryAllocator.h"
11 #include "src/gpu/graphite/vk/VulkanCommandBuffer.h"
12 #include "src/gpu/graphite/vk/VulkanGraphiteUtils.h"
13 #include "src/gpu/vk/VulkanMemory.h"
14
15 namespace skgpu::graphite {
16
17 sk_sp<Buffer> VulkanBuffer::Make(const VulkanSharedContext* sharedContext,
18 size_t size,
19 BufferType type,
20 AccessPattern accessPattern) {
21 if (size <= 0) {
22 return nullptr;
23 }
24 VkBuffer buffer;
25 skgpu::VulkanAlloc alloc;
26
27 // TODO (b/374749633): We can't use protected buffers in the vertex shader. The checks below
28 // make sure we don't use it for vertex or index buffers. But we currently don't have a way to
29 // check here if it is a uniform or storage buffer that is used in the vertex shader. If we hit
30 // that issue and need those GpuOnly buffers, we'll need to pass in some information to the
31 // factory to say what stage the buffer is for. Maybe expand AccessPattern to be
32 // GpuOnly_NotVertex or some better name like that.
33 bool isProtected = sharedContext->isProtected() == Protected::kYes &&
34 (accessPattern == AccessPattern::kGpuOnly ||
35 accessPattern == AccessPattern::kGpuOnlyCopySrc) &&
36 type != BufferType::kVertex &&
37 type != BufferType::kIndex;
38
39 // kGpuOnlyCopySrc is used during testing to overwrite buffer accessPatterns that would normally
40 // be AccessPattern::kGpuOnly. So make sure that buffers that *should* be protected, don't
41 // accidentally expose access here.
42 SkASSERT(!isProtected || accessPattern != AccessPattern::kGpuOnlyCopySrc);
43
44 // Protected memory _never_ uses mappable buffers.
45 // Otherwise, the only time we don't require mappable buffers is when we're on a device
46 // where gpu only memory has faster reads on the gpu than memory that is also mappable
47 // on the cpu.
48 bool requiresMappable = !isProtected &&
49 (accessPattern == AccessPattern::kHostVisible ||
50 !sharedContext->vulkanCaps().gpuOnlyBuffersMorePerformant());
51
52 using BufferUsage = skgpu::VulkanMemoryAllocator::BufferUsage;
53
54 BufferUsage allocUsage;
55 if (type == BufferType::kXferCpuToGpu) {
56 allocUsage = BufferUsage::kTransfersFromCpuToGpu;
57 } else if (type == BufferType::kXferGpuToCpu) {
58 allocUsage = BufferUsage::kTransfersFromGpuToCpu;
59 } else {
60 // GPU-only buffers are preferred unless mappability is required.
61 allocUsage = requiresMappable ? BufferUsage::kCpuWritesGpuReads : BufferUsage::kGpuOnly;
62 }
63
64 // Create the buffer object
65 VkBufferCreateInfo bufInfo = {};
66 bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
67 bufInfo.flags = isProtected ? VK_BUFFER_CREATE_PROTECTED_BIT : 0;
68 bufInfo.size = size;
69
70 // To support SkMesh buffer updates we make Vertex and Index buffers capable of being transfer
71 // dsts. To support rtAdjust uniform buffer updates, we make host-visible uniform buffers also
72 // capable of being transfer dsts.
73 switch (type) {
74 case BufferType::kVertex:
75 bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
76 break;
77 case BufferType::kIndex:
78 bufInfo.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
79 break;
80 case BufferType::kStorage:
81 bufInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
82 break;
83 case BufferType::kQuery:
84 SK_ABORT("Query buffers not supported on Vulkan");
85 break;
86 case BufferType::kIndirect:
87 bufInfo.usage =
88 VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
89 break;
90 case BufferType::kVertexStorage:
91 bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
92 break;
93 case BufferType::kIndexStorage:
94 bufInfo.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
95 break;
96 case BufferType::kUniform:
97 bufInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
98 break;
99 case BufferType::kXferCpuToGpu:
100 bufInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
101 break;
102 case BufferType::kXferGpuToCpu:
103 bufInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
104 break;
105 }
106
107 // We may not always get a mappable buffer for non-dynamic access buffers. Thus we set the
108 // transfer dst usage bit in case we need to do a copy to write data. It doesn't really hurt
109 // to set this extra usage flag, but we could narrow the scope of buffers we set it on more than
110 // just not dynamic.
111 if (!requiresMappable || accessPattern == AccessPattern::kGpuOnly ||
112 accessPattern == AccessPattern::kGpuOnlyCopySrc) {
113 bufInfo.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT;
114 }
115
116 if (accessPattern == AccessPattern::kGpuOnlyCopySrc) {
117 bufInfo.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
118 }
119
120 bufInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
121 bufInfo.queueFamilyIndexCount = 0;
122 bufInfo.pQueueFamilyIndices = nullptr;
123
124 VkResult result;
125 VULKAN_CALL_RESULT(sharedContext,
126 result,
127 CreateBuffer(sharedContext->device(),
128 &bufInfo,
129 nullptr, /*const VkAllocationCallbacks*/
130 &buffer));
131 if (result != VK_SUCCESS) {
132 return nullptr;
133 }
134
135 auto allocator = sharedContext->memoryAllocator();
136 bool shouldPersistentlyMapCpuToGpu =
137 sharedContext->vulkanCaps().shouldPersistentlyMapCpuToGpuBuffers();
138 //AllocBufferMemory
139 auto checkResult = [](VkResult result) {
140 return result == VK_SUCCESS;
141 };
142 if (!skgpu::VulkanMemory::AllocBufferMemory(allocator,
143 buffer,
144 skgpu::Protected(isProtected),
145 allocUsage,
146 shouldPersistentlyMapCpuToGpu,
147 checkResult,
148 &alloc)) {
149 VULKAN_CALL(sharedContext->interface(),
150 DestroyBuffer(sharedContext->device(),
151 buffer,
152 /*const VkAllocationCallbacks*=*/nullptr));
153 return nullptr;
154 }
155
156 // Bind buffer
157 VULKAN_CALL_RESULT(
158 sharedContext,
159 result,
160 BindBufferMemory(sharedContext->device(), buffer, alloc.fMemory, alloc.fOffset));
161 if (result != VK_SUCCESS) {
162 skgpu::VulkanMemory::FreeBufferMemory(allocator, alloc);
163 VULKAN_CALL(sharedContext->interface(),
164 DestroyBuffer(sharedContext->device(),
165 buffer,
166 /*const VkAllocationCallbacks*=*/nullptr));
167 return nullptr;
168 }
169
170 return sk_sp<Buffer>(new VulkanBuffer(
171 sharedContext, size, type, accessPattern, std::move(buffer), alloc, bufInfo.usage,
172 Protected(isProtected)));
173 }
174
175 VulkanBuffer::VulkanBuffer(const VulkanSharedContext* sharedContext,
176 size_t size,
177 BufferType type,
178 AccessPattern accessPattern,
179 VkBuffer buffer,
180 const skgpu::VulkanAlloc& alloc,
181 const VkBufferUsageFlags usageFlags,
182 Protected isProtected)
183 : Buffer(sharedContext,
184 size,
185 isProtected,
186 /*reusableRequiresPurgeable=*/alloc.fFlags & skgpu::VulkanAlloc::kMappable_Flag)
187 , fBuffer(std::move(buffer))
188 , fAlloc(alloc)
189 , fBufferUsageFlags(usageFlags)
190 // We assume a buffer is used for CPU reads only in the case of GPU->CPU transfer buffers.
191 , fBufferUsedForCPURead(type == BufferType::kXferGpuToCpu) {}
192
193 void VulkanBuffer::freeGpuData() {
194 if (fMapPtr) {
195 this->internalUnmap(0, this->size());
196 fMapPtr = nullptr;
197 }
198
199 const VulkanSharedContext* sharedContext =
200 static_cast<const VulkanSharedContext*>(this->sharedContext());
201 SkASSERT(fBuffer);
202 SkASSERT(fAlloc.fMemory && fAlloc.fBackendMemory);
203 VULKAN_CALL(sharedContext->interface(),
204 DestroyBuffer(sharedContext->device(), fBuffer, nullptr));
205 fBuffer = VK_NULL_HANDLE;
206
207 skgpu::VulkanMemory::FreeBufferMemory(sharedContext->memoryAllocator(), fAlloc);
208 fAlloc.fMemory = VK_NULL_HANDLE;
209 fAlloc.fBackendMemory = 0;
210 }
211
212 void VulkanBuffer::internalMap(size_t readOffset, size_t readSize) {
213 SkASSERT(!fMapPtr);
214 if (this->isMappable()) {
215 SkASSERT(fAlloc.fSize > 0);
216 SkASSERT(fAlloc.fSize >= readOffset + readSize);
217
218 const VulkanSharedContext* sharedContext = this->vulkanSharedContext();
219
220 auto allocator = sharedContext->memoryAllocator();
221 auto checkResult = [sharedContext](VkResult result) {
222 VULKAN_LOG_IF_NOT_SUCCESS(sharedContext, result, "skgpu::VulkanMemory::MapAlloc");
223 return sharedContext->checkVkResult(result);
224 };
225 fMapPtr = skgpu::VulkanMemory::MapAlloc(allocator, fAlloc, checkResult);
226 if (fMapPtr && readSize != 0) {
227 auto checkResult_invalidate = [sharedContext, readOffset, readSize](VkResult result) {
228 VULKAN_LOG_IF_NOT_SUCCESS(sharedContext,
229 result,
230 "skgpu::VulkanMemory::InvalidateMappedAlloc "
231 "(readOffset:%zu, readSize:%zu)",
232 readOffset,
233 readSize);
234 return sharedContext->checkVkResult(result);
235 };
236 // "Invalidate" here means make device writes visible to the host. That is, it makes
237 // sure any GPU writes are finished in the range we might read from.
238 skgpu::VulkanMemory::InvalidateMappedAlloc(allocator,
239 fAlloc,
240 readOffset,
241 readSize,
242 checkResult_invalidate);
243 }
244 }
245 }
246
247 void VulkanBuffer::internalUnmap(size_t flushOffset, size_t flushSize) {
248 SkASSERT(fMapPtr && this->isMappable());
249
250 SkASSERT(fAlloc.fSize > 0);
251 SkASSERT(fAlloc.fSize >= flushOffset + flushSize);
252
253 const VulkanSharedContext* sharedContext = this->vulkanSharedContext();
254 auto checkResult = [sharedContext, flushOffset, flushSize](VkResult result) {
255 VULKAN_LOG_IF_NOT_SUCCESS(sharedContext,
256 result,
257 "skgpu::VulkanMemory::FlushMappedAlloc "
258 "(flushOffset:%zu, flushSize:%zu)",
259 flushOffset,
260 flushSize);
261 return sharedContext->checkVkResult(result);
262 };
263
264 auto allocator = sharedContext->memoryAllocator();
265 skgpu::VulkanMemory::FlushMappedAlloc(allocator, fAlloc, flushOffset, flushSize, checkResult);
266 skgpu::VulkanMemory::UnmapAlloc(allocator, fAlloc);
267 }
268
269 void VulkanBuffer::onMap() {
270 SkASSERT(fBuffer);
271 SkASSERT(!this->isMapped());
272
273 this->internalMap(0, fBufferUsedForCPURead ? this->size() : 0);
274 }
275
276 void VulkanBuffer::onUnmap() {
277 SkASSERT(fBuffer);
278 SkASSERT(this->isMapped());
279 this->internalUnmap(0, fBufferUsedForCPURead ? 0 : this->size());
280 }
281
282 namespace {
283
284 VkPipelineStageFlags access_to_pipeline_srcStageFlags(const VkAccessFlags srcAccess) {
285 // For now this function assumes the access flags equal a specific bit and don't act like true
286 // flags (i.e. set of bits). If we ever start having buffer usages that have multiple accesses
287 // in one usage we'll need to update this.
288 switch (srcAccess) {
289 case 0:
290 return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
291 case (VK_ACCESS_TRANSFER_WRITE_BIT): // fallthrough
292 case (VK_ACCESS_TRANSFER_READ_BIT):
293 return VK_PIPELINE_STAGE_TRANSFER_BIT;
294 case (VK_ACCESS_UNIFORM_READ_BIT):
295 // TODO(b/307577875): It is possible that uniforms could have simply been used in the
296 // vertex shader and not the fragment shader, so using the fragment shader pipeline
297 // stage bit indiscriminately is a bit overkill. This call should be modified to check &
298 // allow for selecting VK_PIPELINE_STAGE_VERTEX_SHADER_BIT when appropriate.
299 return (VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
300 case (VK_ACCESS_SHADER_WRITE_BIT):
301 return VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
302 case (VK_ACCESS_INDEX_READ_BIT): // fallthrough
303 case (VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT):
304 return VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
305 case (VK_ACCESS_INDIRECT_COMMAND_READ_BIT):
306 return VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
307 case (VK_ACCESS_HOST_READ_BIT): // fallthrough
308 case (VK_ACCESS_HOST_WRITE_BIT):
309 return VK_PIPELINE_STAGE_HOST_BIT;
310 default:
311 SkUNREACHABLE;
312 }
313 }
314
315 bool access_is_read_only(VkAccessFlags access) {
316 switch (access) {
317 case 0: // initialization state
318 case (VK_ACCESS_TRANSFER_READ_BIT):
319 case (VK_ACCESS_UNIFORM_READ_BIT):
320 case (VK_ACCESS_INDEX_READ_BIT):
321 case (VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT):
322 case (VK_ACCESS_INDIRECT_COMMAND_READ_BIT):
323 case (VK_ACCESS_HOST_READ_BIT):
324 return true;
325 case (VK_ACCESS_TRANSFER_WRITE_BIT):
326 case (VK_ACCESS_SHADER_WRITE_BIT):
327 case (VK_ACCESS_HOST_WRITE_BIT):
328 return false;
329 default:
330 SkUNREACHABLE;
331 }
332 }
333
334 } // anonymous namespace
335
336 void VulkanBuffer::setBufferAccess(VulkanCommandBuffer* cmdBuffer,
337 VkAccessFlags dstAccess,
338 VkPipelineStageFlags dstStageMask) const {
339 SkASSERT(dstAccess == VK_ACCESS_HOST_READ_BIT ||
340 dstAccess == VK_ACCESS_TRANSFER_WRITE_BIT ||
341 dstAccess == VK_ACCESS_TRANSFER_READ_BIT ||
342 dstAccess == VK_ACCESS_UNIFORM_READ_BIT ||
343 dstAccess == VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT ||
344 dstAccess == VK_ACCESS_INDEX_READ_BIT);
345
346 VkPipelineStageFlags srcStageMask = access_to_pipeline_srcStageFlags(fCurrentAccess);
347 SkASSERT(srcStageMask);
348
349 bool needsBarrier = true;
350
351 // When the buffer was last used on the host, we don't need to add any barrier as writes on the
352 // CPU host are implicitly synchronized what you submit new commands.
353 if (srcStageMask == VK_PIPELINE_STAGE_HOST_BIT) {
354 needsBarrier = false;
355 } else if (access_is_read_only(fCurrentAccess) && access_is_read_only(dstAccess)) {
356 // We don't need a barrier if we're going from a read access to another read access, and we
357 // have the same type of read only access.
358 if (fCurrentAccess == dstAccess) {
359 needsBarrier = false;
360 } else {
361 /*needBarrier=true*/
362 // NOTE: Currently this setup *only* correctly handles copying from a vertex
363 // kGpuOnlyCopySrc buffer to kXferGpuToCpu buffer for read backs during testing on
364 // non-protected data.
365 //
366 // In the future we'll need to update the logic in this file to store all the read
367 // accesses in a mask. Additionally we'll need to keep track of what the last write was
368 // since we will need to add a barrier for the new read access--even if we have to put
369 // in a barrier for a previous read already. For example if we have the sequence
370 // Write_1, Read_Access1, Read_Access2. We will first put a barrier going from Write_1
371 // to Read_Access1. But with the current logic when we add Read_Access2 it will think
372 // its going from a read -> read. Thus no barrier would be added. But we need do to add
373 // another barrier for Write_1 to Read_Access2 so that the changes from write become
374 // visibile.
375 }
376 }
377
378 if (needsBarrier) {
379 VkBufferMemoryBarrier bufferMemoryBarrier = {
380 VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, // sType
381 nullptr, // pNext
382 fCurrentAccess, // srcAccessMask
383 dstAccess, // dstAccessMask
384 VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex
385 VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex
386 fBuffer, // buffer
387 0, // offset
388 this->size(), // size
389 };
390 cmdBuffer->addBufferMemoryBarrier(srcStageMask, dstStageMask, &bufferMemoryBarrier);
391 }
392
393 fCurrentAccess = dstAccess;
394 }
395
396 } // namespace skgpu::graphite