-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathdevice.rs
More file actions
2840 lines (2528 loc) · 109 KB
/
Copy pathdevice.rs
File metadata and controls
2840 lines (2528 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use alloc::{borrow::ToOwned as _, collections::BTreeMap, ffi::CString, sync::Arc, vec::Vec};
use core::{
ffi::CStr,
mem::{self, MaybeUninit},
num::NonZeroU32,
ptr,
time::Duration,
};
use arrayvec::ArrayVec;
use ash::{ext, vk};
use hashbrown::hash_map::Entry;
use parking_lot::Mutex;
use super::{conv, RawTlasInstance};
use crate::TlasInstance;
impl super::DeviceShared {
/// Set the name of `object` to `name`.
///
/// If `name` contains an interior null byte, then the name set will be truncated to that byte.
///
/// # Safety
///
/// This method inherits the safety contract from [`vkSetDebugUtilsObjectName`]. In particular:
///
/// - `object` must be a valid handle for one of the following:
/// - An instance-level object from the same instance as this device.
/// - A physical-device-level object that descends from the same physical device as this
/// device.
/// - A device-level object that descends from this device.
/// - `object` must be externally synchronized—only the calling thread should access it during
/// this call.
///
/// [`vkSetDebugUtilsObjectName`]: https://registry.khronos.org/vulkan/specs/latest/man/html/vkSetDebugUtilsObjectNameEXT.html
pub(super) unsafe fn set_object_name(&self, object: impl vk::Handle, name: &str) {
let Some(extension) = self.extension_fns.debug_utils.as_ref() else {
return;
};
// Keep variables outside the if-else block to ensure they do not
// go out of scope while we hold a pointer to them
let mut buffer: [u8; 64] = [0u8; 64];
let buffer_vec: Vec<u8>;
// Append a null terminator to the string
let name_bytes = if name.len() < buffer.len() {
// Common case, string is very small. Allocate a copy on the stack.
buffer[..name.len()].copy_from_slice(name.as_bytes());
// Add null terminator
buffer[name.len()] = 0;
&buffer[..name.len() + 1]
} else {
// Less common case, the string is large.
// This requires a heap allocation.
buffer_vec = name
.as_bytes()
.iter()
.cloned()
.chain(core::iter::once(0))
.collect();
&buffer_vec
};
let name = CStr::from_bytes_until_nul(name_bytes).expect("We have added a null byte");
let _result = unsafe {
extension.set_debug_utils_object_name(
&vk::DebugUtilsObjectNameInfoEXT::default()
.object_handle(object)
.object_name(name),
)
};
}
pub fn make_render_pass(
&self,
key: super::RenderPassKey,
) -> Result<vk::RenderPass, crate::DeviceError> {
Ok(match self.render_passes.lock().entry(key) {
Entry::Occupied(e) => *e.get(),
Entry::Vacant(e) => {
let super::RenderPassKey {
ref colors,
ref depth_stencil,
sample_count,
multiview_mask,
} = *e.key();
let mut vk_attachments = Vec::new();
let mut color_refs = Vec::with_capacity(colors.len());
let mut resolve_refs = Vec::with_capacity(color_refs.capacity());
let mut ds_ref = None;
let samples = vk::SampleCountFlags::from_raw(sample_count);
let unused = vk::AttachmentReference {
attachment: vk::ATTACHMENT_UNUSED,
layout: vk::ImageLayout::UNDEFINED,
};
for cat in colors.iter() {
let (color_ref, resolve_ref) =
if let Some(super::ColorAttachmentKey { base, resolve }) = cat {
let super::AttachmentKey {
format,
layout,
ops,
} = *base;
let color_ref = vk::AttachmentReference {
attachment: vk_attachments.len() as u32,
layout,
};
vk_attachments.push({
let (load_op, store_op) = conv::map_attachment_ops(ops);
vk::AttachmentDescription::default()
.format(format)
.samples(samples)
.load_op(load_op)
.store_op(store_op)
.initial_layout(layout)
.final_layout(layout)
});
let resolve_ref = if let Some(rat) = resolve {
let super::AttachmentKey {
format,
layout,
ops,
} = *rat;
let (load_op, store_op) = conv::map_attachment_ops(ops);
let vk_attachment = vk::AttachmentDescription::default()
.format(format)
.samples(vk::SampleCountFlags::TYPE_1)
.load_op(load_op)
.store_op(store_op)
.initial_layout(layout)
.final_layout(layout);
vk_attachments.push(vk_attachment);
vk::AttachmentReference {
attachment: vk_attachments.len() as u32 - 1,
layout,
}
} else {
unused
};
(color_ref, resolve_ref)
} else {
(unused, unused)
};
color_refs.push(color_ref);
resolve_refs.push(resolve_ref);
}
if let Some(ds) = depth_stencil {
let super::DepthStencilAttachmentKey {
ref base,
stencil_ops,
} = *ds;
let super::AttachmentKey {
format,
layout,
ops,
} = *base;
ds_ref = Some(vk::AttachmentReference {
attachment: vk_attachments.len() as u32,
layout,
});
let (load_op, store_op) = conv::map_attachment_ops(ops);
let (stencil_load_op, stencil_store_op) = conv::map_attachment_ops(stencil_ops);
let vk_attachment = vk::AttachmentDescription::default()
.format(format)
.samples(samples)
.load_op(load_op)
.store_op(store_op)
.stencil_load_op(stencil_load_op)
.stencil_store_op(stencil_store_op)
.initial_layout(layout)
.final_layout(layout);
vk_attachments.push(vk_attachment);
}
let vk_subpasses = [{
let mut vk_subpass = vk::SubpassDescription::default()
.pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS)
.color_attachments(&color_refs)
.resolve_attachments(&resolve_refs);
if self
.workarounds
.contains(super::Workarounds::EMPTY_RESOLVE_ATTACHMENT_LISTS)
&& resolve_refs.is_empty()
{
vk_subpass.p_resolve_attachments = ptr::null();
}
if let Some(ref reference) = ds_ref {
vk_subpass = vk_subpass.depth_stencil_attachment(reference)
}
vk_subpass
}];
let mut vk_info = vk::RenderPassCreateInfo::default()
.attachments(&vk_attachments)
.subpasses(&vk_subpasses);
let mut multiview_info;
let mask;
if let Some(multiview_mask) = multiview_mask {
mask = [multiview_mask.get()];
// On Vulkan 1.1 or later, this is an alias for core functionality
multiview_info = vk::RenderPassMultiviewCreateInfoKHR::default()
.view_masks(&mask)
.correlation_masks(&mask);
vk_info = vk_info.push_next(&mut multiview_info);
}
let raw = unsafe {
self.raw
.create_render_pass(&vk_info, None)
.map_err(super::map_host_device_oom_err)?
};
*e.insert(raw)
}
})
}
fn make_memory_ranges<'a, I: 'a + Iterator<Item = crate::MemoryRange>>(
&self,
buffer: &'a super::Buffer,
ranges: I,
) -> Option<impl 'a + Iterator<Item = vk::MappedMemoryRange<'a>>> {
let allocation = buffer.allocation.as_ref()?.lock();
let mask = self.private_caps.non_coherent_map_mask;
Some(ranges.map(move |range| {
vk::MappedMemoryRange::default()
.memory(allocation.memory())
.offset((allocation.offset() + range.start) & !mask)
.size((range.end - range.start + mask) & !mask)
}))
}
}
impl
gpu_descriptor::DescriptorDevice<vk::DescriptorSetLayout, vk::DescriptorPool, vk::DescriptorSet>
for super::DeviceShared
{
unsafe fn create_descriptor_pool(
&self,
descriptor_count: &gpu_descriptor::DescriptorTotalCount,
max_sets: u32,
flags: gpu_descriptor::DescriptorPoolCreateFlags,
) -> Result<vk::DescriptorPool, gpu_descriptor::CreatePoolError> {
//Note: ignoring other types, since they can't appear here
let unfiltered_counts = [
(vk::DescriptorType::SAMPLER, descriptor_count.sampler),
(
vk::DescriptorType::SAMPLED_IMAGE,
descriptor_count.sampled_image,
),
(
vk::DescriptorType::STORAGE_IMAGE,
descriptor_count.storage_image,
),
(
vk::DescriptorType::UNIFORM_BUFFER,
descriptor_count.uniform_buffer,
),
(
vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC,
descriptor_count.uniform_buffer_dynamic,
),
(
vk::DescriptorType::STORAGE_BUFFER,
descriptor_count.storage_buffer,
),
(
vk::DescriptorType::STORAGE_BUFFER_DYNAMIC,
descriptor_count.storage_buffer_dynamic,
),
(
vk::DescriptorType::ACCELERATION_STRUCTURE_KHR,
descriptor_count.acceleration_structure,
),
];
let filtered_counts = unfiltered_counts
.iter()
.cloned()
.filter(|&(_, count)| count != 0)
.map(|(ty, count)| vk::DescriptorPoolSize {
ty,
descriptor_count: count,
})
.collect::<ArrayVec<_, 8>>();
let mut vk_flags =
if flags.contains(gpu_descriptor::DescriptorPoolCreateFlags::UPDATE_AFTER_BIND) {
vk::DescriptorPoolCreateFlags::UPDATE_AFTER_BIND
} else {
vk::DescriptorPoolCreateFlags::empty()
};
if flags.contains(gpu_descriptor::DescriptorPoolCreateFlags::FREE_DESCRIPTOR_SET) {
vk_flags |= vk::DescriptorPoolCreateFlags::FREE_DESCRIPTOR_SET;
}
let vk_info = vk::DescriptorPoolCreateInfo::default()
.max_sets(max_sets)
.flags(vk_flags)
.pool_sizes(&filtered_counts);
match unsafe { self.raw.create_descriptor_pool(&vk_info, None) } {
Ok(pool) => Ok(pool),
Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY) => {
Err(gpu_descriptor::CreatePoolError::OutOfHostMemory)
}
Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => {
Err(gpu_descriptor::CreatePoolError::OutOfDeviceMemory)
}
Err(vk::Result::ERROR_FRAGMENTATION) => {
Err(gpu_descriptor::CreatePoolError::Fragmentation)
}
Err(err) => handle_unexpected(err),
}
}
unsafe fn destroy_descriptor_pool(&self, pool: vk::DescriptorPool) {
unsafe { self.raw.destroy_descriptor_pool(pool, None) }
}
unsafe fn alloc_descriptor_sets<'a>(
&self,
pool: &mut vk::DescriptorPool,
layouts: impl ExactSizeIterator<Item = &'a vk::DescriptorSetLayout>,
sets: &mut impl Extend<vk::DescriptorSet>,
) -> Result<(), gpu_descriptor::DeviceAllocationError> {
let result = unsafe {
self.raw.allocate_descriptor_sets(
&vk::DescriptorSetAllocateInfo::default()
.descriptor_pool(*pool)
.set_layouts(
&smallvec::SmallVec::<[vk::DescriptorSetLayout; 32]>::from_iter(
layouts.cloned(),
),
),
)
};
match result {
Ok(vk_sets) => {
sets.extend(vk_sets);
Ok(())
}
Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY)
| Err(vk::Result::ERROR_OUT_OF_POOL_MEMORY) => {
Err(gpu_descriptor::DeviceAllocationError::OutOfHostMemory)
}
Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => {
Err(gpu_descriptor::DeviceAllocationError::OutOfDeviceMemory)
}
Err(vk::Result::ERROR_FRAGMENTED_POOL) => {
Err(gpu_descriptor::DeviceAllocationError::FragmentedPool)
}
Err(err) => handle_unexpected(err),
}
}
unsafe fn dealloc_descriptor_sets<'a>(
&self,
pool: &mut vk::DescriptorPool,
sets: impl Iterator<Item = vk::DescriptorSet>,
) {
let result = unsafe {
self.raw.free_descriptor_sets(
*pool,
&smallvec::SmallVec::<[vk::DescriptorSet; 32]>::from_iter(sets),
)
};
match result {
Ok(()) => {}
Err(err) => handle_unexpected(err),
}
}
}
struct CompiledStage {
create_info: vk::PipelineShaderStageCreateInfo<'static>,
_entry_point: CString,
temp_raw_module: Option<vk::ShaderModule>,
}
impl super::Device {
/// # Safety
///
/// - `vk_image` must be created respecting `desc`
/// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `vk_image`. If
/// `drop_callback` is [`Some`], `vk_image` must be valid until the callback is called.
/// - If the `ImageCreateFlags` does not contain `MUTABLE_FORMAT`, the `view_formats` of `desc` must be empty.
/// - If `memory` is not [`super::TextureMemory::External`], wgpu-hal will take ownership of the
/// memory (which is presumed to back `vk_image`). Otherwise, the memory must remain valid until
/// `drop_callback` is called.
pub unsafe fn texture_from_raw(
&self,
vk_image: vk::Image,
desc: &crate::TextureDescriptor,
drop_callback: Option<crate::DropCallback>,
memory: super::TextureMemory,
) -> super::Texture {
let identity = self.shared.texture_identity_factory.next();
let drop_guard = crate::DropGuard::from_option(drop_callback);
if let Some(label) = desc.label {
unsafe { self.shared.set_object_name(vk_image, label) };
}
super::Texture {
raw: vk_image,
drop_guard,
memory,
format: desc.format,
copy_size: desc.copy_extent(),
identity,
}
}
fn find_memory_type_index(
&self,
type_bits_req: u32,
flags_req: vk::MemoryPropertyFlags,
) -> Option<usize> {
let mem_properties = unsafe {
self.shared
.instance
.raw
.get_physical_device_memory_properties(self.shared.physical_device)
};
// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceMemoryProperties.html
for (i, mem_ty) in mem_properties.memory_types_as_slice().iter().enumerate() {
let types_bits = 1 << i;
let is_required_memory_type = type_bits_req & types_bits != 0;
let has_required_properties = mem_ty.property_flags & flags_req == flags_req;
if is_required_memory_type && has_required_properties {
return Some(i);
}
}
None
}
fn create_image_without_memory(
&self,
desc: &crate::TextureDescriptor,
external_memory_image_create_info: Option<&mut vk::ExternalMemoryImageCreateInfo>,
) -> Result<ImageWithoutMemory, crate::DeviceError> {
let copy_size = desc.copy_extent();
let mut raw_flags = vk::ImageCreateFlags::empty();
if desc.dimension == wgt::TextureDimension::D3
&& desc.usage.contains(wgt::TextureUses::COLOR_TARGET)
{
raw_flags |= vk::ImageCreateFlags::TYPE_2D_ARRAY_COMPATIBLE;
}
if desc.is_cube_compatible() {
raw_flags |= vk::ImageCreateFlags::CUBE_COMPATIBLE;
}
let original_format = self.shared.private_caps.map_texture_format(desc.format);
let mut vk_view_formats = vec![];
if !desc.view_formats.is_empty() {
raw_flags |= vk::ImageCreateFlags::MUTABLE_FORMAT;
if self.shared.private_caps.image_format_list {
vk_view_formats = desc
.view_formats
.iter()
.map(|f| self.shared.private_caps.map_texture_format(*f))
.collect();
vk_view_formats.push(original_format)
}
}
if desc.format.is_multi_planar_format() {
raw_flags |=
vk::ImageCreateFlags::MUTABLE_FORMAT | vk::ImageCreateFlags::EXTENDED_USAGE;
}
let mut vk_info = vk::ImageCreateInfo::default()
.flags(raw_flags)
.image_type(conv::map_texture_dimension(desc.dimension))
.format(original_format)
.extent(conv::map_copy_extent(©_size))
.mip_levels(desc.mip_level_count)
.array_layers(desc.array_layer_count())
.samples(vk::SampleCountFlags::from_raw(desc.sample_count))
.tiling(vk::ImageTiling::OPTIMAL)
.usage(conv::map_texture_usage(desc.usage))
.sharing_mode(vk::SharingMode::EXCLUSIVE)
.initial_layout(vk::ImageLayout::UNDEFINED);
let mut format_list_info = vk::ImageFormatListCreateInfo::default();
if !vk_view_formats.is_empty() {
format_list_info = format_list_info.view_formats(&vk_view_formats);
vk_info = vk_info.push_next(&mut format_list_info);
}
if let Some(ext_info) = external_memory_image_create_info {
vk_info = vk_info.push_next(ext_info);
}
let raw = unsafe { self.shared.raw.create_image(&vk_info, None) }.map_err(map_err)?;
fn map_err(err: vk::Result) -> crate::DeviceError {
// We don't use VK_EXT_image_compression_control
// VK_ERROR_COMPRESSION_EXHAUSTED_EXT
super::map_host_device_oom_and_ioca_err(err)
}
let mut req = unsafe { self.shared.raw.get_image_memory_requirements(raw) };
if desc.usage.contains(wgt::TextureUses::TRANSIENT) {
let mem_type_index = self.find_memory_type_index(
req.memory_type_bits,
vk::MemoryPropertyFlags::LAZILY_ALLOCATED,
);
if let Some(mem_type_index) = mem_type_index {
req.memory_type_bits = 1 << mem_type_index;
}
}
Ok(ImageWithoutMemory {
raw,
requirements: req,
})
}
/// # Safety
///
/// - Vulkan (with VK_KHR_external_memory_win32)
/// - The `d3d11_shared_handle` must be valid and respecting `desc`
/// - `VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT` flag is used because we need to hold a reference to the handle
#[cfg(windows)]
pub unsafe fn texture_from_d3d11_shared_handle(
&self,
d3d11_shared_handle: windows::Win32::Foundation::HANDLE,
desc: &crate::TextureDescriptor,
) -> Result<super::Texture, crate::DeviceError> {
if !self
.shared
.features
.contains(wgt::Features::VULKAN_EXTERNAL_MEMORY_WIN32)
{
log::error!("Vulkan driver does not support VK_KHR_external_memory_win32");
return Err(crate::DeviceError::Unexpected);
}
let mut external_memory_image_info = vk::ExternalMemoryImageCreateInfo::default()
.handle_types(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE);
let image =
self.create_image_without_memory(desc, Some(&mut external_memory_image_info))?;
// Some external memory types require dedicated allocation
// https://docs.vulkan.org/guide/latest/extensions/external.html#_importing_memory
let mut dedicated_allocate_info =
vk::MemoryDedicatedAllocateInfo::default().image(image.raw);
let mut import_memory_info = vk::ImportMemoryWin32HandleInfoKHR::default()
.handle_type(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE)
.handle(d3d11_shared_handle.0 as _);
// TODO: We should use `push_next` instead, but currently ash does not provide this method for the `ImportMemoryWin32HandleInfoKHR` type.
#[allow(clippy::unnecessary_mut_passed)]
{
import_memory_info.p_next = <*const _>::cast(&mut dedicated_allocate_info);
}
let mem_type_index = self
.find_memory_type_index(
image.requirements.memory_type_bits,
vk::MemoryPropertyFlags::DEVICE_LOCAL,
)
.ok_or(crate::DeviceError::Unexpected)?;
let memory_allocate_info = vk::MemoryAllocateInfo::default()
.allocation_size(image.requirements.size)
.memory_type_index(mem_type_index as _)
.push_next(&mut import_memory_info);
let memory = unsafe { self.shared.raw.allocate_memory(&memory_allocate_info, None) }
.map_err(super::map_host_device_oom_err)?;
unsafe { self.shared.raw.bind_image_memory(image.raw, memory, 0) }
.map_err(super::map_host_device_oom_err)?;
Ok(unsafe {
self.texture_from_raw(
image.raw,
desc,
None,
super::TextureMemory::Dedicated(memory),
)
})
}
fn create_shader_module_impl(
&self,
spv: &[u32],
label: &crate::Label<'_>,
) -> Result<vk::ShaderModule, crate::DeviceError> {
let vk_info = vk::ShaderModuleCreateInfo::default()
.flags(vk::ShaderModuleCreateFlags::empty())
.code(spv);
let raw = unsafe {
profiling::scope!("vkCreateShaderModule");
self.shared
.raw
.create_shader_module(&vk_info, None)
.map_err(map_err)?
};
fn map_err(err: vk::Result) -> crate::DeviceError {
// We don't use VK_NV_glsl_shader
// VK_ERROR_INVALID_SHADER_NV
super::map_host_device_oom_err(err)
}
if let Some(label) = label {
unsafe { self.shared.set_object_name(raw, label) };
}
Ok(raw)
}
fn compile_stage(
&self,
stage: &crate::ProgrammableStage<super::ShaderModule>,
naga_stage: naga::ShaderStage,
binding_map: &naga::back::spv::BindingMap,
) -> Result<CompiledStage, crate::PipelineError> {
let stage_flags = crate::auxil::map_naga_stage(naga_stage);
let vk_module = match *stage.module {
super::ShaderModule::Raw(raw) => raw,
super::ShaderModule::Intermediate {
ref naga_shader,
runtime_checks,
} => {
let pipeline_options = naga::back::spv::PipelineOptions {
entry_point: stage.entry_point.to_owned(),
shader_stage: naga_stage,
};
let needs_temp_options = !runtime_checks.bounds_checks
|| !runtime_checks.force_loop_bounding
|| !runtime_checks.ray_query_initialization_tracking
|| !binding_map.is_empty()
|| naga_shader.debug_source.is_some()
|| !stage.zero_initialize_workgroup_memory
|| !runtime_checks.task_shader_dispatch_tracking
|| !runtime_checks.mesh_shader_primitive_indices_clamp;
let mut temp_options;
let options = if needs_temp_options {
temp_options = self.naga_options.clone();
if !runtime_checks.bounds_checks {
temp_options.bounds_check_policies = naga::proc::BoundsCheckPolicies {
index: naga::proc::BoundsCheckPolicy::Unchecked,
buffer: naga::proc::BoundsCheckPolicy::Unchecked,
image_load: naga::proc::BoundsCheckPolicy::Unchecked,
binding_array: naga::proc::BoundsCheckPolicy::Unchecked,
};
}
if !runtime_checks.force_loop_bounding {
temp_options.force_loop_bounding = false;
}
if !runtime_checks.ray_query_initialization_tracking {
temp_options.ray_query_initialization_tracking = false;
}
if !binding_map.is_empty() {
temp_options.binding_map = binding_map.clone();
}
if let Some(ref debug) = naga_shader.debug_source {
temp_options.debug_info = Some(naga::back::spv::DebugInfo {
source_code: &debug.source_code,
file_name: debug.file_name.as_ref(),
language: naga::back::spv::SourceLanguage::WGSL,
})
}
if !stage.zero_initialize_workgroup_memory {
temp_options.zero_initialize_workgroup_memory =
naga::back::spv::ZeroInitializeWorkgroupMemoryMode::None;
}
if !runtime_checks.task_shader_dispatch_tracking {
temp_options.task_dispatch_limits = None;
}
temp_options.mesh_shader_primitive_indices_clamp =
runtime_checks.mesh_shader_primitive_indices_clamp;
&temp_options
} else {
&self.naga_options
};
let (module, info) = naga::back::pipeline_constants::process_overrides(
&naga_shader.module,
&naga_shader.info,
Some((naga_stage, stage.entry_point)),
stage.constants,
)
.map_err(|e| {
crate::PipelineError::PipelineConstants(stage_flags, format!("{e}"))
})?;
let spv = {
profiling::scope!("naga::spv::write_vec");
naga::back::spv::write_vec(&module, &info, options, Some(&pipeline_options))
}
.map_err(|e| crate::PipelineError::Linkage(stage_flags, format!("{e}")))?;
self.create_shader_module_impl(&spv, &None)?
}
};
let mut flags = vk::PipelineShaderStageCreateFlags::empty();
if self.shared.features.contains(wgt::Features::SUBGROUP) {
flags |= vk::PipelineShaderStageCreateFlags::ALLOW_VARYING_SUBGROUP_SIZE
}
let entry_point = CString::new(stage.entry_point).unwrap();
let mut create_info = vk::PipelineShaderStageCreateInfo::default()
.flags(flags)
.stage(conv::map_shader_stage(stage_flags))
.module(vk_module);
// Circumvent struct lifetime check because of a self-reference inside CompiledStage
create_info.p_name = entry_point.as_ptr();
Ok(CompiledStage {
create_info,
_entry_point: entry_point,
temp_raw_module: match *stage.module {
super::ShaderModule::Raw(_) => None,
super::ShaderModule::Intermediate { .. } => Some(vk_module),
},
})
}
/// Returns the queue family index of the device's internal queue.
///
/// This is useful for constructing memory barriers needed for queue family ownership transfer when
/// external memory is involved (from/to `VK_QUEUE_FAMILY_EXTERNAL_KHR` and `VK_QUEUE_FAMILY_FOREIGN_EXT`
/// for example).
pub fn queue_family_index(&self) -> u32 {
self.shared.family_index
}
pub fn queue_index(&self) -> u32 {
self.shared.queue_index
}
pub fn raw_device(&self) -> &ash::Device {
&self.shared.raw
}
pub fn raw_physical_device(&self) -> vk::PhysicalDevice {
self.shared.physical_device
}
pub fn raw_queue(&self) -> vk::Queue {
self.shared.raw_queue
}
pub fn enabled_device_extensions(&self) -> &[&'static CStr] {
&self.shared.enabled_extensions
}
pub fn shared_instance(&self) -> &super::InstanceShared {
&self.shared.instance
}
fn error_if_would_oom_on_resource_allocation(
&self,
needs_host_access: bool,
size: u64,
) -> Result<(), crate::DeviceError> {
let Some(threshold) = self
.shared
.instance
.memory_budget_thresholds
.for_resource_creation
else {
return Ok(());
};
if !self
.shared
.enabled_extensions
.contains(&ext::memory_budget::NAME)
{
return Ok(());
}
let get_physical_device_properties = self
.shared
.instance
.get_physical_device_properties
.as_ref()
.unwrap();
let mut memory_budget_properties = vk::PhysicalDeviceMemoryBudgetPropertiesEXT::default();
let mut memory_properties =
vk::PhysicalDeviceMemoryProperties2::default().push_next(&mut memory_budget_properties);
unsafe {
get_physical_device_properties.get_physical_device_memory_properties2(
self.shared.physical_device,
&mut memory_properties,
);
}
let mut host_visible_heaps = [false; vk::MAX_MEMORY_HEAPS];
let mut device_local_heaps = [false; vk::MAX_MEMORY_HEAPS];
let memory_properties = memory_properties.memory_properties;
for i in 0..memory_properties.memory_type_count {
let memory_type = memory_properties.memory_types[i as usize];
let flags = memory_type.property_flags;
if flags.intersects(
vk::MemoryPropertyFlags::LAZILY_ALLOCATED | vk::MemoryPropertyFlags::PROTECTED,
) {
continue; // not used by gpu-alloc
}
if flags.contains(vk::MemoryPropertyFlags::HOST_VISIBLE) {
host_visible_heaps[memory_type.heap_index as usize] = true;
}
if flags.contains(vk::MemoryPropertyFlags::DEVICE_LOCAL) {
device_local_heaps[memory_type.heap_index as usize] = true;
}
}
let heaps = if needs_host_access {
host_visible_heaps
} else {
device_local_heaps
};
// NOTE: We might end up checking multiple heaps since gpu-alloc doesn't have a way
// for us to query the heap the resource will end up on. But this is unlikely,
// there is usually only one heap on integrated GPUs and two on dedicated GPUs.
for (i, check) in heaps.iter().enumerate() {
if !check {
continue;
}
let heap_usage = memory_budget_properties.heap_usage[i];
let heap_budget = memory_budget_properties.heap_budget[i];
if heap_usage + size >= heap_budget / 100 * threshold as u64 {
return Err(crate::DeviceError::OutOfMemory);
}
}
Ok(())
}
}
impl crate::Device for super::Device {
type A = super::Api;
unsafe fn create_buffer(
&self,
desc: &crate::BufferDescriptor,
) -> Result<super::Buffer, crate::DeviceError> {
let vk_info = vk::BufferCreateInfo::default()
.size(desc.size)
.usage(conv::map_buffer_usage(desc.usage))
.sharing_mode(vk::SharingMode::EXCLUSIVE);
let raw = unsafe {
self.shared
.raw
.create_buffer(&vk_info, None)
.map_err(super::map_host_device_oom_and_ioca_err)?
};
let mut requirements = unsafe { self.shared.raw.get_buffer_memory_requirements(raw) };
let is_cpu_read = desc.usage.contains(wgt::BufferUses::MAP_READ);
let is_cpu_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE);
let location = match (is_cpu_read, is_cpu_write) {
(true, true) => gpu_allocator::MemoryLocation::CpuToGpu,
(true, false) => gpu_allocator::MemoryLocation::GpuToCpu,
(false, true) => gpu_allocator::MemoryLocation::CpuToGpu,
(false, false) => gpu_allocator::MemoryLocation::GpuOnly,
};
let needs_host_access = is_cpu_read || is_cpu_write;
self.error_if_would_oom_on_resource_allocation(needs_host_access, requirements.size)
.inspect_err(|_| {
unsafe { self.shared.raw.destroy_buffer(raw, None) };
})?;
let name = desc.label.unwrap_or("Unlabeled buffer");
if desc
.usage
.contains(wgt::BufferUses::ACCELERATION_STRUCTURE_SCRATCH)
{
// There is no way to specify this usage to Vulkan so we must make sure the alignment requirement is large enough.
requirements.alignment = requirements
.alignment
.max(self.shared.private_caps.scratch_buffer_alignment as u64);
}
let allocation = self
.mem_allocator
.lock()
.allocate(&gpu_allocator::vulkan::AllocationCreateDesc {
name,
requirements: vk::MemoryRequirements {
memory_type_bits: requirements.memory_type_bits & self.valid_ash_memory_types,
..requirements
},
location,
linear: true, // Buffers are always linear
allocation_scheme: gpu_allocator::vulkan::AllocationScheme::GpuAllocatorManaged,
})
.inspect_err(|_| {
unsafe { self.shared.raw.destroy_buffer(raw, None) };
})?;
unsafe {
self.shared
.raw
.bind_buffer_memory(raw, allocation.memory(), allocation.offset())
}
.map_err(super::map_host_device_oom_and_ioca_err)
.inspect_err(|_| {
unsafe { self.shared.raw.destroy_buffer(raw, None) };
})?;
if let Some(label) = desc.label {
unsafe { self.shared.set_object_name(raw, label) };
}
self.counters.buffer_memory.add(allocation.size() as isize);
self.counters.buffers.add(1);
Ok(super::Buffer {
raw,
allocation: Some(Mutex::new(super::BufferMemoryBacking::Managed(allocation))),
})
}
unsafe fn destroy_buffer(&self, buffer: super::Buffer) {
unsafe { self.shared.raw.destroy_buffer(buffer.raw, None) };
if let Some(allocation) = buffer.allocation {
let allocation = allocation.into_inner();
self.counters.buffer_memory.sub(allocation.size() as isize);
match allocation {
super::BufferMemoryBacking::Managed(allocation) => {
let result = self.mem_allocator.lock().free(allocation);
if let Err(err) = result {
log::warn!("Failed to free buffer allocation: {err}");
}
}
super::BufferMemoryBacking::VulkanMemory { memory, .. } => unsafe {
self.shared.raw.free_memory(memory, None);
},
}
}
self.counters.buffers.sub(1);
}
unsafe fn add_raw_buffer(&self, _buffer: &super::Buffer) {
self.counters.buffers.add(1);
}
unsafe fn map_buffer(
&self,
buffer: &super::Buffer,
range: crate::MemoryRange,
) -> Result<crate::BufferMapping, crate::DeviceError> {
if let Some(ref allocation) = buffer.allocation {
let mut allocation = allocation.lock();
if let super::BufferMemoryBacking::Managed(ref mut allocation) = *allocation {
let is_coherent = allocation
.memory_properties()
.contains(vk::MemoryPropertyFlags::HOST_COHERENT);
Ok(crate::BufferMapping {
ptr: unsafe {
allocation
.mapped_ptr()
.unwrap()