1#[cfg(feature = "trace")]
2use alloc::string::ToString as _;
3use alloc::{boxed::Box, string::String, sync::Arc, vec, vec::Vec};
4use core::{
5 mem::{self, ManuallyDrop},
6 num::NonZeroU64,
7 ptr::NonNull,
8 sync::atomic::Ordering,
9};
10use smallvec::SmallVec;
11use thiserror::Error;
12use wgt::{
13 error::{ErrorType, WebGpuError},
14 AccelerationStructureFlags,
15};
16
17use super::{life::LifetimeTracker, Device};
18#[cfg(feature = "trace")]
19use crate::device::trace::{Action, IntoTrace};
20use crate::{
21 api_log,
22 command::{
23 validate_linear_texture_data, validate_texture_buffer_copy,
24 validate_texture_copy_dst_format, validate_texture_copy_range, ClearError,
25 CommandAllocator, CommandBuffer, CommandEncoder, CommandEncoderError, CopyRange, CopySide,
26 TransferError,
27 },
28 device::{DeviceError, QueueDescriptor, WaitIdleError},
29 get_lowest_common_denom, hal_label,
30 init_tracker::{has_copy_partial_init_tracker_coverage, TextureInitRange},
31 lock::{rank, Mutex, MutexGuard, RwLock, RwLockWriteGuard},
32 ray_tracing::{BlasCompactReadyPendingClosure, CompactBlasError},
33 ray_tracing_pipeline,
34 resource::{
35 Blas, BlasCompactState, BlasDescriptor, BlasState, Buffer, BufferAccessError,
36 BufferMapState, DestroyedBuffer, DestroyedQuerySet, DestroyedResourceError,
37 DestroyedTexture, FlushedStagingBuffer, InvalidOrDestroyedResourceError,
38 InvalidResourceError, Labeled, ParentDevice, ResourceErrorIdent, ResourceState,
39 StagingBuffer, Texture, TextureInner, Trackable, TrackingData,
40 },
41 resource_log,
42 scratch::ScratchBuffer,
43 snatch::{SnatchGuard, Snatchable},
44 track::{self, Tracker, TrackerIndex},
45 FastHashMap, LabelHelpers, SubmissionIndex,
46};
47use crate::{device::resource::CommandIndices, resource::RawResourceAccess};
48
49pub struct Queue {
50 raw: Box<dyn hal::DynQueue>,
51 pub(crate) pending_writes: Mutex<PendingWrites>,
52 life_tracker: Mutex<LifetimeTracker>,
53 label: String,
54 pub(crate) device: Arc<Device>,
56}
57
58impl Queue {
59 pub(crate) fn new(
60 device: Arc<Device>,
61 raw: Box<dyn hal::DynQueue>,
62 desc: QueueDescriptor,
63 instance_flags: wgt::InstanceFlags,
64 ) -> Result<Self, DeviceError> {
65 let pending_encoder = device
66 .command_allocator
67 .acquire_encoder(device.raw(), raw.as_ref())
68 .map_err(DeviceError::from_hal);
69
70 let pending_encoder = match pending_encoder {
71 Ok(pending_encoder) => pending_encoder,
72 Err(e) => {
73 return Err(e);
74 }
75 };
76
77 let mut pending_writes = PendingWrites::new(pending_encoder, instance_flags);
78
79 let zero_buffer = device.zero_buffer.as_ref();
80 pending_writes.activate();
81 unsafe {
82 pending_writes
83 .command_encoder
84 .transition_buffers(&[hal::BufferBarrier {
85 buffer: zero_buffer,
86 usage: hal::StateTransition {
87 from: wgt::BufferUses::empty(),
88 to: wgt::BufferUses::COPY_DST,
89 },
90 }]);
91 pending_writes
92 .command_encoder
93 .clear_buffer(zero_buffer, 0..super::ZERO_BUFFER_SIZE);
94 pending_writes
95 .command_encoder
96 .transition_buffers(&[hal::BufferBarrier {
97 buffer: zero_buffer,
98 usage: hal::StateTransition {
99 from: wgt::BufferUses::COPY_DST,
100 to: wgt::BufferUses::COPY_SRC,
101 },
102 }]);
103 }
104
105 Ok(Queue {
106 raw,
107 device,
108 label: desc.label.to_string(),
109 pending_writes: Mutex::new(rank::QUEUE_PENDING_WRITES, pending_writes),
110 life_tracker: Mutex::new(rank::QUEUE_LIFE_TRACKER, LifetimeTracker::new()),
111 })
112 }
113
114 pub(crate) fn raw(&self) -> &dyn hal::DynQueue {
115 self.raw.as_ref()
116 }
117
118 #[track_caller]
119 pub(crate) fn lock_life<'a>(&'a self) -> MutexGuard<'a, LifetimeTracker> {
120 self.life_tracker.lock()
121 }
122
123 pub(crate) fn prepare_surface_texture_for_present(
128 &self,
129 texture: &Arc<Texture>,
130 ) -> Result<(), DeviceError> {
131 let snatch_guard = self.device.snatchable_lock.read();
132 let submission = self.allocate_submission(snatch_guard)?;
133 let device = &self.device;
134
135 let needs_clear = {
137 let status = texture.initialization_status.read();
138 status
139 .mips
140 .first()
141 .is_some_and(|mip| mip.check(0..1).is_some())
142 };
143
144 let mut pending_writes = self.pending_writes.lock();
145
146 if needs_clear {
147 let encoder = pending_writes.activate();
150 let mut trackers = device.trackers.lock();
151 crate::command::clear_texture(
152 texture,
153 TextureInitRange {
154 mip_range: 0..1,
155 layer_range: 0..1,
156 },
157 None,
158 encoder,
159 &mut trackers.textures,
160 &device.alignments,
161 device.zero_buffer.as_ref(),
162 &submission.snatch_guard,
163 device.instance_flags,
164 )
165 .map_err(|e| match e {
166 ClearError::Device(e) => e,
167 _ => DeviceError::Lost,
168 })?;
169 texture.initialization_status.write().mips[0].drain(0..1);
170 }
171
172 let pending = {
178 let mut trackers = device.trackers.lock();
179 let pending: Vec<track::PendingTransition<wgt::TextureUses>> = trackers
180 .textures
181 .set_single(
182 texture,
183 texture.full_range.clone(),
184 wgt::TextureUses::PRESENT,
185 )
186 .collect();
187 pending
188 };
189
190 if pending.is_empty() {
191 debug_assert!(!needs_clear);
197 return Ok(());
198 }
199
200 {
202 let raw_texture = texture
203 .raw(&submission.snatch_guard)
204 .ok_or(DeviceError::Lost)?;
205 let barriers: Vec<hal::TextureBarrier<'_, dyn hal::DynTexture>> = pending
206 .into_iter()
207 .map(|pt| pt.into_hal(raw_texture))
208 .collect();
209
210 let encoder = pending_writes.activate();
211 unsafe {
215 encoder.transition_textures(&barriers);
216 }
217 }
218
219 pending_writes.insert_texture(texture);
226
227 submission.submit(pending_writes)?;
228
229 Ok(())
230 }
231
232 pub(crate) fn maintain(
240 &self,
241 submission_index: u64,
242 snatch_guard: &SnatchGuard,
243 ) -> (
244 SmallVec<[SubmittedWorkDoneClosure; 1]>,
245 Vec<super::BufferMapPendingClosure>,
246 Vec<BlasCompactReadyPendingClosure>,
247 bool,
248 ) {
249 let mut life_tracker = self.lock_life();
250 let submission_closures = life_tracker.triage_submissions(submission_index);
251
252 let mapping_closures = life_tracker.handle_mapping(snatch_guard);
253 let blas_closures = life_tracker.handle_compact_read_back();
254
255 let queue_empty = life_tracker.queue_empty();
256
257 (
258 submission_closures,
259 mapping_closures,
260 blas_closures,
261 queue_empty,
262 )
263 }
264}
265
266crate::impl_resource_type!(Queue);
267crate::impl_labeled!(Queue);
268crate::impl_parent_device!(Queue);
269crate::impl_storage_item!(Queue);
270
271impl Drop for Queue {
272 #[allow(trivial_casts)]
273 fn drop(&mut self) {
274 profiling::scope!("Queue::drop");
275 api_log!("Queue::drop {:?}", self as *const _);
276 resource_log!("Drop {}", self.error_ident());
277
278 let result = {
281 let _command_indices = self.device.command_indices.write();
283 unsafe { self.raw.wait_for_idle() }
284 };
285 match result {
286 Ok(()) => {}
287 Err(hal::DeviceError::Lost) => {
288 self.device.handle_hal_error(hal::DeviceError::Lost);
289 }
290 Err(e) => {
291 log::error!("Unexpected error while waiting for queue idle on drop: {e:?}");
292 #[cfg(feature = "std")]
293 std::process::abort();
294 #[cfg(not(feature = "std"))]
295 panic!("Unexpected error while waiting for queue idle on drop: {e:?}");
296 }
297 }
298
299 let last_successful_submission_index = self
300 .device
301 .last_successful_submission_index
302 .load(Ordering::Acquire);
303
304 let snatch_guard = self.device.snatchable_lock.read();
305 let (submission_closures, mapping_closures, blas_compact_ready_closures, queue_empty) =
306 self.maintain(last_successful_submission_index, &snatch_guard);
307 drop(snatch_guard);
308
309 assert!(queue_empty);
310
311 let closures = crate::device::UserClosures {
312 mappings: mapping_closures,
313 blas_compact_ready: blas_compact_ready_closures,
314 submissions: submission_closures,
315 device_lost_invocations: SmallVec::new(),
316 };
317
318 closures.fire();
319 }
320}
321
322#[cfg(send_sync)]
323pub type SubmittedWorkDoneClosure = Box<dyn FnOnce() + Send + 'static>;
324#[cfg(not(send_sync))]
325pub type SubmittedWorkDoneClosure = Box<dyn FnOnce() + 'static>;
326
327#[derive(Debug)]
338pub enum TempResource {
339 StagingBuffer(FlushedStagingBuffer),
340 ScratchBuffer(ScratchBuffer),
341 DestroyedBuffer(DestroyedBuffer),
342 DestroyedTexture(DestroyedTexture),
343 DestroyedQuerySet(DestroyedQuerySet),
344}
345
346pub(crate) struct EncoderInFlight {
352 inner: crate::command::InnerCommandEncoder,
353 pub(crate) trackers: Tracker,
354 pub(crate) temp_resources: Vec<TempResource>,
355 _indirect_draw_validation_resources: crate::indirect_validation::DrawResources,
357
358 pub(crate) pending_buffers: FastHashMap<TrackerIndex, Arc<Buffer>>,
360 pub(crate) pending_textures: FastHashMap<TrackerIndex, Arc<Texture>>,
362 pub(crate) pending_blas_s: FastHashMap<TrackerIndex, Arc<Blas>>,
364 _pending_shader_binding_data: Vec<Arc<ray_tracing_pipeline::ShaderBindingData>>,
367}
368
369#[derive(Debug)]
394pub(crate) struct PendingWrites {
395 pub command_encoder: Box<dyn hal::DynCommandEncoder>,
397
398 pub is_recording: bool,
404
405 temp_resources: Vec<TempResource>,
406 dst_buffers: FastHashMap<TrackerIndex, Arc<Buffer>>,
407 dst_textures: FastHashMap<TrackerIndex, Arc<Texture>>,
408 copied_blas_s: FastHashMap<TrackerIndex, Arc<Blas>>,
409 written_shader_binding_data: Vec<Arc<ray_tracing_pipeline::ShaderBindingData>>,
412 instance_flags: wgt::InstanceFlags,
413
414 hoisted_staging_buffers: Vec<FlushedStagingBuffer>,
423
424 hoisted_buffer_barriers: Vec<(Arc<Buffer>, hal::StateTransition<wgt::BufferUses>)>,
446}
447
448impl PendingWrites {
449 pub fn new(
450 command_encoder: Box<dyn hal::DynCommandEncoder>,
451 instance_flags: wgt::InstanceFlags,
452 ) -> Self {
453 Self {
454 command_encoder,
455 is_recording: false,
456 temp_resources: Vec::new(),
457 dst_buffers: FastHashMap::default(),
458 dst_textures: FastHashMap::default(),
459 copied_blas_s: FastHashMap::default(),
460 instance_flags,
461 hoisted_staging_buffers: Vec::new(),
462 hoisted_buffer_barriers: Vec::new(),
463 written_shader_binding_data: Vec::new(),
464 }
465 }
466
467 pub fn insert_buffer(&mut self, buffer: &Arc<Buffer>) {
468 self.dst_buffers
469 .insert(buffer.tracker_index(), buffer.clone());
470 }
471
472 pub fn insert_texture(&mut self, texture: &Arc<Texture>) {
473 self.dst_textures
474 .insert(texture.tracker_index(), texture.clone());
475 }
476
477 pub fn insert_blas(&mut self, blas: &Arc<Blas>) {
478 self.copied_blas_s
479 .insert(blas.tracker_index(), blas.clone());
480 }
481
482 pub fn use_shader_binding_data(&mut self, sbd: &Arc<ray_tracing_pipeline::ShaderBindingData>) {
483 self.written_shader_binding_data.push(sbd.clone())
484 }
485
486 pub fn contains_buffer(&self, buffer: &Arc<Buffer>) -> bool {
487 self.dst_buffers.contains_key(&buffer.tracker_index())
488 }
489
490 pub fn contains_texture(&self, texture: &Arc<Texture>) -> bool {
491 self.dst_textures.contains_key(&texture.tracker_index())
492 }
493
494 pub fn consume_temp(&mut self, resource: TempResource) {
495 self.temp_resources.push(resource);
496 }
497
498 pub fn consume(&mut self, buffer: FlushedStagingBuffer) {
504 self.hoisted_staging_buffers.push(buffer);
505 }
506
507 #[must_use]
521 fn hoist_buffer_barrier(
522 &mut self,
523 buffer: &Arc<Buffer>,
524 transition: Option<track::PendingTransition<wgt::BufferUses>>,
525 ) -> Option<track::PendingTransition<wgt::BufferUses>> {
526 let transition = transition?;
527
528 if self.dst_buffers.contains_key(&buffer.tracker_index()) {
531 return Some(transition);
532 }
533
534 self.hoisted_buffer_barriers
535 .push((buffer.clone(), transition.usage));
536 None
537 }
538
539 pub fn clear_buffer(
540 &mut self,
541 device: &Arc<Device>,
542 buffer: &Arc<Buffer>,
543 range: core::ops::Range<wgt::BufferAddress>,
544 snatch_guard: &SnatchGuard,
545 ) -> Result<(), QueueWriteError> {
546 let transition = {
547 let mut trackers = device.trackers.lock();
548 trackers
549 .buffers
550 .set_single(buffer, wgt::BufferUses::COPY_DST)
551 };
552 let inline_transition = self.hoist_buffer_barrier(buffer, transition);
553
554 let dst_raw = buffer.try_raw(snatch_guard)?;
555
556 let encoder = self.activate();
557 unsafe {
558 if let Some(transition) = inline_transition {
559 encoder.transition_buffers(&[transition.into_hal(buffer, snatch_guard)]);
560 }
561 encoder.clear_buffer(dst_raw, range.clone());
562 }
563
564 self.insert_buffer(buffer);
565
566 buffer.initialization_status.write().drain(range);
569
570 Ok(())
571 }
572
573 fn record_hoisted_barriers(
580 &mut self,
581 encoder: &mut EncoderInFlight,
582 snatch_guard: &SnatchGuard,
583 ) -> Result<Vec<FlushedStagingBuffer>, DeviceError> {
584 let staging_buffers = mem::take(&mut self.hoisted_staging_buffers);
585 let buffer_barriers = mem::take(&mut self.hoisted_buffer_barriers);
586
587 let barriers = staging_buffers
588 .iter()
589 .map(|staging_buffer| hal::BufferBarrier {
590 buffer: staging_buffer.raw(),
591 usage: hal::StateTransition {
592 from: wgt::BufferUses::MAP_WRITE,
593 to: wgt::BufferUses::COPY_SRC,
594 },
595 })
596 .chain(buffer_barriers.iter().filter_map(|(buffer, usage)| {
597 Some(hal::BufferBarrier {
600 buffer: buffer.raw(snatch_guard)?,
601 usage: usage.clone(),
602 })
603 }))
604 .collect::<Vec<_>>();
605
606 if !barriers.is_empty() {
607 encoder
608 .inner
609 .open_pass(Some("(wgpu internal) PendingWrites Transit"))?;
610 unsafe { encoder.inner.raw.transition_buffers(&barriers) };
611 encoder.inner.close_and_push_front()?;
612 }
613
614 Ok(staging_buffers)
615 }
616
617 fn pre_submit(
618 &mut self,
619 command_allocator: &CommandAllocator,
620 device: &Arc<Device>,
621 queue: &Queue,
622 snatch_guard: &SnatchGuard,
623 ) -> Result<Option<EncoderInFlight>, DeviceError> {
624 if self.is_recording {
625 let pending_buffers = mem::take(&mut self.dst_buffers);
626 let pending_textures = mem::take(&mut self.dst_textures);
627 let pending_blas_s = mem::take(&mut self.copied_blas_s);
628 let pending_shader_binding_data = mem::take(&mut self.written_shader_binding_data);
629
630 let cmd_buf = unsafe { self.command_encoder.end_encoding() }
631 .map_err(|e| device.handle_hal_error(e))?;
632 self.is_recording = false;
633
634 let new_encoder = command_allocator
635 .acquire_encoder(device.raw(), queue.raw())
636 .map_err(|e| device.handle_hal_error(e))?;
637
638 let mut encoder = EncoderInFlight {
639 inner: crate::command::InnerCommandEncoder {
640 raw: ManuallyDrop::new(mem::replace(&mut self.command_encoder, new_encoder)),
641 list: vec![cmd_buf],
642 device: device.clone(),
643 is_open: false,
644 api: crate::command::EncodingApi::InternalUse,
645 label: "(wgpu internal) PendingWrites command encoder".into(),
646 },
647 trackers: Tracker::new(device.ordered_buffer_usages, device.ordered_texture_usages),
648 temp_resources: mem::take(&mut self.temp_resources),
649 _indirect_draw_validation_resources: crate::indirect_validation::DrawResources::new(
650 device.clone(),
651 ),
652 pending_buffers,
653 pending_textures,
654 pending_blas_s,
655 _pending_shader_binding_data: pending_shader_binding_data,
656 };
657
658 let staging_buffers = self.record_hoisted_barriers(&mut encoder, snatch_guard)?;
659 encoder
660 .temp_resources
661 .extend(staging_buffers.into_iter().map(TempResource::StagingBuffer));
662
663 Ok(Some(encoder))
664 } else {
665 self.dst_buffers.clear();
666 self.dst_textures.clear();
667 self.copied_blas_s.clear();
668 self.written_shader_binding_data.clear();
669 Ok(None)
670 }
671 }
672
673 pub fn activate(&mut self) -> &mut dyn hal::DynCommandEncoder {
674 if !self.is_recording {
675 unsafe {
676 self.command_encoder
677 .begin_encoding(hal_label(
678 Some("(wgpu internal) PendingWrites"),
679 self.instance_flags,
680 ))
681 .unwrap();
682 }
683 self.is_recording = true;
684 }
685 self.command_encoder.as_mut()
686 }
687}
688
689impl Drop for PendingWrites {
690 fn drop(&mut self) {
691 unsafe {
692 if self.is_recording {
693 self.command_encoder.discard_encoding();
694 }
695 }
696 }
697}
698
699#[derive(Clone, Debug, Error)]
700#[non_exhaustive]
701pub enum QueueWriteError {
702 #[error(transparent)]
703 Queue(#[from] DeviceError),
704 #[error(transparent)]
705 Transfer(#[from] TransferError),
706 #[error(transparent)]
707 MemoryInitFailure(#[from] ClearError),
708 #[error(transparent)]
709 DestroyedResource(#[from] DestroyedResourceError),
710 #[error(transparent)]
711 InvalidResource(#[from] InvalidResourceError),
712}
713
714impl From<InvalidOrDestroyedResourceError> for QueueWriteError {
715 fn from(e: InvalidOrDestroyedResourceError) -> Self {
716 match e {
717 InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
718 InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
719 }
720 }
721}
722
723impl WebGpuError for QueueWriteError {
724 fn webgpu_error_type(&self) -> ErrorType {
725 match self {
726 Self::Queue(e) => e.webgpu_error_type(),
727 Self::Transfer(e) => e.webgpu_error_type(),
728 Self::MemoryInitFailure(e) => e.webgpu_error_type(),
729 Self::DestroyedResource(e) => e.webgpu_error_type(),
730 Self::InvalidResource(e) => e.webgpu_error_type(),
731 }
732 }
733}
734
735#[derive(Clone, Debug, Error)]
736#[non_exhaustive]
737pub enum QueueSubmitError {
738 #[error(transparent)]
739 Queue(#[from] DeviceError),
740 #[error(transparent)]
741 DestroyedResource(#[from] DestroyedResourceError),
742 #[error("{0} is still mapped")]
743 BufferStillMapped(ResourceErrorIdent),
744 #[error(transparent)]
745 InvalidResource(#[from] InvalidResourceError),
746 #[error(transparent)]
747 CommandEncoder(#[from] CommandEncoderError),
748 #[error(transparent)]
749 ValidateAsActionsError(#[from] crate::ray_tracing::ValidateAsActionsError),
750}
751
752impl From<InvalidOrDestroyedResourceError> for QueueSubmitError {
753 fn from(e: InvalidOrDestroyedResourceError) -> Self {
754 match e {
755 InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
756 InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
757 }
758 }
759}
760
761impl WebGpuError for QueueSubmitError {
762 fn webgpu_error_type(&self) -> ErrorType {
763 match self {
764 Self::Queue(e) => e.webgpu_error_type(),
765 Self::CommandEncoder(e) => e.webgpu_error_type(),
766 Self::ValidateAsActionsError(e) => e.webgpu_error_type(),
767 Self::InvalidResource(e) => e.webgpu_error_type(),
768 Self::DestroyedResource(_) | Self::BufferStillMapped(_) => ErrorType::Validation,
769 }
770 }
771}
772
773pub(crate) struct PendingSubmission<'a> {
821 queue: &'a Queue,
822
823 command_index_guard: RwLockWriteGuard<'a, CommandIndices>,
833
834 snatch_guard: SnatchGuard<'a>,
836
837 pub executions: Vec<EncoderInFlight>,
840
841 surface_textures: FastHashMap<*const Texture, Arc<Texture>>,
847
848 pub index: SubmissionIndex,
850}
851
852pub(crate) struct SubmissionResult<'a> {
853 pub snatch_guard: SnatchGuard<'a>,
854}
855
856impl<'a> PendingSubmission<'a> {
857 fn submit(
858 self,
859 pending_writes: MutexGuard<'a, PendingWrites>,
860 ) -> Result<SubmissionResult<'a>, DeviceError> {
861 self.queue.submit_pending_submission(pending_writes, self)
862 }
863}
864
865impl Queue {
868 pub(crate) fn write_buffer_inner(
869 &self,
870 buffer: Arc<Buffer>,
871 buffer_offset: wgt::BufferAddress,
872 data: &[u8],
873 ) -> Result<(), QueueWriteError> {
874 profiling::scope!("Queue::write_buffer");
875 api_log!("Queue::write_buffer");
876
877 #[cfg(feature = "trace")]
878 if let Some(ref mut trace) = *self.device.trace.lock() {
879 use crate::device::trace::DataKind;
880 let size = data.len() as u64;
881 let data = trace.make_binary(DataKind::Bin, data);
882 trace.add(Action::WriteBuffer {
883 id: buffer.to_trace(),
884 data,
885 offset: buffer_offset,
886 size,
887 queued: true,
888 });
889 }
890
891 buffer.check_is_valid()?;
892 self.device.check_is_valid()?;
893
894 let data_size = data.len() as wgt::BufferAddress;
895
896 self.same_device_as(buffer.as_ref())?;
897
898 let data_size = if let Some(data_size) = wgt::BufferSize::new(data_size) {
899 data_size
900 } else {
901 self.validate_write_buffer_impl(buffer.as_ref(), buffer_offset, 0)?;
906
907 log::trace!("Ignoring write_buffer of size 0");
908 return Ok(());
909 };
910
911 let mut staging_buffer = StagingBuffer::new(&self.device, data_size)?;
915
916 let staging_buffer = {
917 profiling::scope!("copy");
918 staging_buffer.write_exact(data);
919 staging_buffer.flush()
920 };
921
922 let snatch_guard = self.device.snatchable_lock.read();
923 let mut pending_writes = self.pending_writes.lock();
924
925 let result = self.write_staging_buffer_impl(
926 &snatch_guard,
927 &mut pending_writes,
928 &staging_buffer,
929 buffer,
930 buffer_offset,
931 );
932
933 pending_writes.consume(staging_buffer);
934
935 result
936 }
937
938 pub fn write_buffer(
939 &self,
940 buffer: Arc<Buffer>,
941 buffer_offset: wgt::BufferAddress,
942 data: &[u8],
943 ) {
944 if let Err(error) = self.write_buffer_inner(buffer, buffer_offset, data) {
945 self.device
946 .handle_error(error, Some(self.label()), "Queue::write_buffer");
947 }
948 }
949
950 pub fn create_staging_buffer(
951 &self,
952 buffer_size: wgt::BufferSize,
953 ) -> Result<(StagingBuffer, NonNull<u8>), QueueWriteError> {
954 profiling::scope!("Queue::create_staging_buffer");
955 resource_log!("Queue::create_staging_buffer");
956
957 self.device.check_is_valid()?;
958
959 let staging_buffer = StagingBuffer::new(&self.device, buffer_size)?;
960 let ptr = unsafe { staging_buffer.ptr() };
961
962 Ok((staging_buffer, ptr))
963 }
964
965 pub fn write_staging_buffer(
966 &self,
967 buffer: Arc<Buffer>,
968 buffer_offset: wgt::BufferAddress,
969 staging_buffer: StagingBuffer,
970 ) -> Result<(), QueueWriteError> {
971 profiling::scope!("Queue::write_staging_buffer");
972
973 buffer.check_is_valid()?;
974 self.device.check_is_valid()?;
975
976 let staging_buffer = staging_buffer.flush();
981
982 let snatch_guard = self.device.snatchable_lock.read();
983 let mut pending_writes = self.pending_writes.lock();
984
985 let result = self.write_staging_buffer_impl(
986 &snatch_guard,
987 &mut pending_writes,
988 &staging_buffer,
989 buffer,
990 buffer_offset,
991 );
992
993 drop(snatch_guard);
994
995 pending_writes.consume(staging_buffer);
996
997 drop(pending_writes);
998
999 result
1000 }
1001
1002 pub fn validate_write_buffer(
1003 &self,
1004 buffer: Arc<Buffer>,
1005 buffer_offset: u64,
1006 buffer_size: wgt::BufferSize,
1007 ) -> Result<(), QueueWriteError> {
1008 profiling::scope!("Queue::validate_write_buffer");
1009
1010 self.device.check_is_valid()?;
1011 buffer.check_is_valid()?;
1012
1013 self.validate_write_buffer_impl(&buffer, buffer_offset, buffer_size.into())?;
1014
1015 Ok(())
1016 }
1017
1018 fn validate_write_buffer_impl(
1019 &self,
1020 buffer: &Buffer,
1021 buffer_offset: u64,
1022 buffer_size: u64,
1023 ) -> Result<(), TransferError> {
1024 if !matches!(&*buffer.map_state.read(), BufferMapState::Idle) {
1025 return Err(TransferError::BufferNotAvailable);
1026 }
1027 buffer.check_usage(wgt::BufferUsages::COPY_DST)?;
1028 if !buffer_size.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
1029 return Err(TransferError::UnalignedCopySize(buffer_size));
1030 }
1031 if !buffer_offset.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
1032 return Err(TransferError::UnalignedBufferOffset(buffer_offset));
1033 }
1034
1035 if buffer_offset > buffer.size {
1036 return Err(TransferError::BufferStartOffsetOverrun {
1037 start_offset: buffer_offset,
1038 buffer_size: buffer.size,
1039 side: CopySide::Destination,
1040 });
1041 }
1042 if buffer_size > buffer.size - buffer_offset {
1043 return Err(TransferError::BufferEndOffsetOverrun {
1044 start_offset: buffer_offset,
1045 size: buffer_size,
1046 buffer_size: buffer.size,
1047 side: CopySide::Destination,
1048 });
1049 }
1050
1051 Ok(())
1052 }
1053
1054 fn write_staging_buffer_impl(
1055 &self,
1056 snatch_guard: &SnatchGuard,
1057 pending_writes: &mut PendingWrites,
1058 staging_buffer: &FlushedStagingBuffer,
1059 buffer: Arc<Buffer>,
1060 buffer_offset: u64,
1061 ) -> Result<(), QueueWriteError> {
1062 self.device.check_is_valid()?;
1063
1064 let transition = {
1065 let mut trackers = self.device.trackers.lock();
1066 trackers
1067 .buffers
1068 .set_single(&buffer, wgt::BufferUses::COPY_DST)
1069 };
1070
1071 let dst_raw = buffer.try_raw(snatch_guard)?;
1072
1073 self.same_device_as(buffer.as_ref())?;
1074
1075 self.validate_write_buffer_impl(&buffer, buffer_offset, staging_buffer.size.into())?;
1076
1077 let region = hal::BufferCopy {
1078 src_offset: 0,
1079 dst_offset: buffer_offset,
1080 size: staging_buffer.size,
1081 };
1082 let inline_transition = pending_writes.hoist_buffer_barrier(&buffer, transition);
1085 let encoder = pending_writes.activate();
1086 unsafe {
1087 if let Some(transition) = inline_transition {
1088 encoder.transition_buffers(&[transition.into_hal(&buffer, snatch_guard)]);
1089 }
1090 encoder.copy_buffer_to_buffer(staging_buffer.raw(), dst_raw, &[region]);
1091 }
1092
1093 pending_writes.insert_buffer(&buffer);
1094
1095 {
1098 buffer
1099 .initialization_status
1100 .write()
1101 .drain(buffer_offset..(buffer_offset + staging_buffer.size.get()));
1102 }
1103
1104 Ok(())
1105 }
1106
1107 pub fn write_texture_inner(
1108 &self,
1109 destination: wgt::TexelCopyTextureInfo<Arc<Texture>>,
1110 data: &[u8],
1111 data_layout: &wgt::TexelCopyBufferLayout,
1112 size: &wgt::Extent3d,
1113 ) -> Result<(), QueueWriteError> {
1114 profiling::scope!("Queue::write_texture");
1115 api_log!("Queue::write_texture");
1116
1117 #[cfg(feature = "trace")]
1118 if let Some(ref mut trace) = *self.device.trace.lock() {
1119 use crate::device::trace::DataKind;
1120 let data = trace.make_binary(DataKind::Bin, data);
1121 trace.add(Action::WriteTexture {
1122 to: destination.to_trace(),
1123 data,
1124 layout: *data_layout,
1125 size: *size,
1126 });
1127 }
1128
1129 self.device.check_is_valid()?;
1130
1131 let dst = destination.texture;
1132 let destination = wgt::TexelCopyTextureInfo {
1133 texture: (),
1134 mip_level: destination.mip_level,
1135 origin: destination.origin,
1136 aspect: destination.aspect,
1137 };
1138
1139 self.same_device_as(dst.as_ref())?;
1140
1141 dst.check_valid()?;
1142
1143 dst.check_usage(wgt::TextureUsages::COPY_DST)
1144 .map_err(TransferError::MissingTextureUsage)?;
1145
1146 let CopyRange {
1149 hal_copy_extent,
1150 hal_base: dst_base,
1151 array_layer_count,
1152 selector,
1153 } = validate_texture_copy_range(&destination, &dst.desc, CopySide::Destination, size)?;
1154
1155 validate_texture_copy_dst_format(dst.desc.format, destination.aspect)?;
1156
1157 validate_texture_buffer_copy(
1158 &destination,
1159 dst_base.aspect,
1160 &dst.desc,
1161 data_layout,
1162 false, self.device.features,
1164 )?;
1165
1166 let (required_bytes_in_copy, _source_bytes_per_array_layer, _) =
1169 validate_linear_texture_data(
1170 data_layout,
1171 dst.desc.format,
1172 destination.aspect,
1173 data.len() as wgt::BufferAddress,
1174 CopySide::Source,
1175 size,
1176 )?;
1177
1178 if dst.desc.format.is_depth_stencil_format() {
1179 self.device
1180 .require_downlevel_flags(wgt::DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES)
1181 .map_err(TransferError::from)?;
1182 }
1183
1184 let snatch_guard = self.device.snatchable_lock.read();
1185
1186 let dst_raw = dst.try_inner(&snatch_guard)?.raw();
1187
1188 if size.width == 0 || size.height == 0 || size.depth_or_array_layers == 0 {
1191 log::trace!("Ignoring write_texture of size 0");
1192 return Ok(());
1193 }
1194
1195 let mut pending_writes = self.pending_writes.lock();
1196 let encoder = pending_writes.activate();
1197
1198 let init_layer_range = if dst.desc.dimension == wgt::TextureDimension::D3 {
1204 0..1
1206 } else {
1207 destination.origin.z..destination.origin.z + size.depth_or_array_layers
1208 };
1209 let layer_ranges_to_clear = {
1210 let mut dst_initialization_status = dst.initialization_status.write();
1211 if dst_initialization_status.mips[destination.mip_level as usize]
1212 .check(init_layer_range.clone())
1213 .is_some()
1214 {
1215 if has_copy_partial_init_tracker_coverage(size, &destination, &dst.desc) {
1216 dst_initialization_status.mips[destination.mip_level as usize]
1217 .drain(init_layer_range)
1218 .collect::<Vec<core::ops::Range<u32>>>()
1219 } else {
1220 dst_initialization_status.mips[destination.mip_level as usize]
1221 .drain(init_layer_range);
1222 vec![]
1223 }
1224 } else {
1225 vec![]
1226 }
1227 };
1228 if !layer_ranges_to_clear.is_empty() {
1229 let mut trackers = self.device.trackers.lock();
1230 for layer_range in layer_ranges_to_clear {
1231 crate::command::clear_texture(
1232 &dst,
1233 TextureInitRange {
1234 mip_range: destination.mip_level..(destination.mip_level + 1),
1235 layer_range,
1236 },
1237 None,
1238 encoder,
1239 &mut trackers.textures,
1240 &self.device.alignments,
1241 self.device.zero_buffer.as_ref(),
1242 &snatch_guard,
1243 self.device.instance_flags,
1244 )
1245 .map_err(QueueWriteError::from)?;
1246 }
1247 }
1248
1249 let (block_width, block_height) = dst.desc.format.block_dimensions();
1250 let width_in_blocks = size.width / block_width;
1251 let height_in_blocks = size.height / block_height;
1252
1253 let block_size = dst
1254 .desc
1255 .format
1256 .block_copy_size(Some(destination.aspect))
1257 .unwrap();
1258 let bytes_in_last_row = width_in_blocks * block_size;
1259
1260 let bytes_per_row = data_layout.bytes_per_row.unwrap_or(bytes_in_last_row);
1261 let rows_per_image = data_layout.rows_per_image.unwrap_or(height_in_blocks);
1262
1263 let bytes_per_row_alignment = get_lowest_common_denom(
1264 self.device.alignments.buffer_copy_pitch.get() as u32,
1265 block_size,
1266 );
1267 assert!(u32::MAX - bytes_in_last_row >= bytes_per_row_alignment);
1268 let stage_bytes_per_row = wgt::math::align_to(bytes_in_last_row, bytes_per_row_alignment);
1269
1270 let staging_buffer = if stage_bytes_per_row == bytes_per_row {
1274 profiling::scope!("copy aligned");
1275 let stage_size = wgt::BufferSize::new(required_bytes_in_copy).unwrap();
1277 let mut staging_buffer = StagingBuffer::new(&self.device, stage_size)?;
1278 staging_buffer
1279 .write_exact(&data[data_layout.offset as usize..][..stage_size.get() as usize]);
1280 staging_buffer
1281 } else {
1282 profiling::scope!("copy chunked");
1283 let block_rows_in_copy = u64::from(size.depth_or_array_layers - 1)
1285 * u64::from(rows_per_image)
1286 + u64::from(height_in_blocks);
1287 let stage_size = u64::from(stage_bytes_per_row)
1290 .checked_mul(block_rows_in_copy)
1291 .and_then(wgt::BufferSize::new)
1292 .unwrap();
1293 let mut staging_buffer = StagingBuffer::new(&self.device, stage_size)?;
1294 for layer in 0..u64::from(size.depth_or_array_layers) {
1295 let rows_offset = layer * u64::from(rows_per_image);
1296 for row in rows_offset..rows_offset + u64::from(height_in_blocks) {
1297 let src_offset = data_layout.offset + row * u64::from(bytes_per_row);
1298 let dst_offset = row * u64::from(stage_bytes_per_row);
1299 unsafe {
1300 staging_buffer.write_with_offset(
1301 data,
1302 src_offset as isize,
1303 dst_offset as isize,
1304 bytes_in_last_row as usize,
1305 )
1306 }
1307 }
1308 }
1309 staging_buffer
1310 };
1311
1312 let staging_buffer = staging_buffer.flush();
1313
1314 let regions = (0..array_layer_count)
1315 .map(|array_layer_offset| {
1316 let mut texture_base = dst_base.clone();
1317 texture_base.array_layer += array_layer_offset;
1318 hal::BufferTextureCopy {
1319 buffer_layout: wgt::TexelCopyBufferLayout {
1320 offset: array_layer_offset as u64
1321 * rows_per_image as u64
1322 * stage_bytes_per_row as u64,
1323 bytes_per_row: Some(stage_bytes_per_row),
1324 rows_per_image: Some(rows_per_image),
1325 },
1326 texture_base,
1327 size: hal_copy_extent,
1328 }
1329 })
1330 .collect::<Vec<_>>();
1331
1332 {
1333 let mut trackers = self.device.trackers.lock();
1334 let transition =
1335 trackers
1336 .textures
1337 .set_single(&dst, selector, wgt::TextureUses::COPY_DST);
1338 let texture_barriers = transition
1339 .map(|pending| pending.into_hal(dst_raw))
1340 .collect::<Vec<_>>();
1341
1342 unsafe {
1346 encoder.transition_textures(&texture_barriers);
1347 encoder.copy_buffer_to_texture(staging_buffer.raw(), dst_raw, ®ions);
1348 }
1349 }
1350
1351 pending_writes.consume(staging_buffer);
1352 pending_writes.insert_texture(&dst);
1353
1354 Ok(())
1355 }
1356
1357 pub fn write_texture(
1358 &self,
1359 destination: wgt::TexelCopyTextureInfo<Arc<Texture>>,
1360 data: &[u8],
1361 data_layout: &wgt::TexelCopyBufferLayout,
1362 size: &wgt::Extent3d,
1363 ) {
1364 if let Err(error) = self.write_texture_inner(destination, data, data_layout, size) {
1365 self.device
1366 .handle_error(error, Some(self.label()), "Queue::write_texture");
1367 }
1368 }
1369
1370 #[cfg(webgl)]
1371 pub fn copy_external_image_to_texture(
1372 &self,
1373 source: &wgt::CopyExternalImageSourceInfo,
1374 destination: wgt::CopyExternalImageDestInfo<Arc<Texture>>,
1375 size: wgt::Extent3d,
1376 ) -> Result<(), QueueWriteError> {
1377 use crate::conv;
1378
1379 profiling::scope!("Queue::copy_external_image_to_texture");
1380
1381 self.device.check_is_valid()?;
1382
1383 let mut needs_flag = false;
1384 needs_flag |= source.origin != wgt::Origin2d::ZERO;
1388 needs_flag |= destination.color_space != wgt::PredefinedColorSpace::Srgb;
1389 #[allow(clippy::bool_comparison)]
1390 if matches!(source.source, wgt::ExternalImageSource::ImageBitmap(_)) {
1391 needs_flag |= source.flip_y != false;
1392 needs_flag |= destination.premultiplied_alpha != false;
1393 }
1394
1395 if needs_flag {
1396 self.device
1397 .require_downlevel_flags(wgt::DownlevelFlags::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES)
1398 .map_err(TransferError::from)?;
1399 }
1400
1401 let src_width = source.source.width();
1402 let src_height = source.source.height();
1403
1404 let dst = destination.texture;
1405 let premultiplied_alpha = destination.premultiplied_alpha;
1406 let destination = wgt::TexelCopyTextureInfo {
1407 texture: (),
1408 mip_level: destination.mip_level,
1409 origin: destination.origin,
1410 aspect: destination.aspect,
1411 };
1412
1413 dst.check_valid()?;
1414
1415 if !conv::is_valid_external_image_copy_dst_texture_format(dst.desc.format) {
1416 return Err(
1417 TransferError::ExternalCopyToForbiddenTextureFormat(dst.desc.format).into(),
1418 );
1419 }
1420 if dst.desc.dimension != wgt::TextureDimension::D2 {
1421 return Err(TransferError::InvalidDimensionExternal.into());
1422 }
1423 dst.check_usage(wgt::TextureUsages::COPY_DST | wgt::TextureUsages::RENDER_ATTACHMENT)
1424 .map_err(TransferError::MissingTextureUsage)?;
1425 if dst.desc.sample_count != 1 {
1426 return Err(TransferError::InvalidSampleCount {
1427 sample_count: dst.desc.sample_count,
1428 }
1429 .into());
1430 }
1431
1432 if source.origin.x > src_width || src_width - source.origin.x < size.width {
1433 return Err(TransferError::TextureOverrun {
1434 start_offset: source.origin.x,
1435 end_offset: source.origin.x.saturating_add(size.width),
1436 texture_size: src_width,
1437 dimension: crate::resource::TextureErrorDimension::X,
1438 side: CopySide::Source,
1439 plane: None,
1440 }
1441 .into());
1442 }
1443 if source.origin.y > src_height || src_height - source.origin.y < size.height {
1444 return Err(TransferError::TextureOverrun {
1445 start_offset: source.origin.y,
1446 end_offset: source.origin.y.saturating_add(size.height),
1447 texture_size: src_height,
1448 dimension: crate::resource::TextureErrorDimension::Y,
1449 side: CopySide::Source,
1450 plane: None,
1451 }
1452 .into());
1453 }
1454 if size.depth_or_array_layers != 1 {
1455 return Err(TransferError::TextureOverrun {
1456 start_offset: 0,
1457 end_offset: size.depth_or_array_layers,
1458 texture_size: 1,
1459 dimension: crate::resource::TextureErrorDimension::Z,
1460 side: CopySide::Source,
1461 plane: None,
1462 }
1463 .into());
1464 }
1465
1466 let CopyRange {
1469 hal_copy_extent,
1470 hal_base: dst_base,
1471 array_layer_count: _,
1472 selector,
1473 } = validate_texture_copy_range(&destination, &dst.desc, CopySide::Destination, &size)?;
1474
1475 assert!(dst_base.aspect == hal::FormatAspects::COLOR);
1477
1478 let snatch_guard = self.device.snatchable_lock.read();
1479
1480 let dst_raw = dst.try_raw(&snatch_guard)?;
1481
1482 if size.width == 0 || size.height == 0 || size.depth_or_array_layers == 0 {
1485 log::trace!("Ignoring copy_external_image_to_texture of size 0");
1486 return Ok(());
1487 }
1488
1489 let mut pending_writes = self.pending_writes.lock();
1490 let encoder = pending_writes.activate();
1491
1492 let init_layer_range = if dst.desc.dimension == wgt::TextureDimension::D3 {
1498 0..1
1500 } else {
1501 destination.origin.z..destination.origin.z + size.depth_or_array_layers
1502 };
1503 let layer_ranges_to_clear = {
1504 let mut dst_initialization_status = dst.initialization_status.write();
1505 if dst_initialization_status.mips[destination.mip_level as usize]
1506 .check(init_layer_range.clone())
1507 .is_some()
1508 {
1509 if has_copy_partial_init_tracker_coverage(&size, &destination, &dst.desc) {
1510 dst_initialization_status.mips[destination.mip_level as usize]
1511 .drain(init_layer_range)
1512 .collect::<Vec<core::ops::Range<u32>>>()
1513 } else {
1514 dst_initialization_status.mips[destination.mip_level as usize]
1515 .drain(init_layer_range);
1516 vec![]
1517 }
1518 } else {
1519 vec![]
1520 }
1521 };
1522 if !layer_ranges_to_clear.is_empty() {
1523 let mut trackers = self.device.trackers.lock();
1524 for layer_range in layer_ranges_to_clear {
1525 crate::command::clear_texture(
1526 &dst,
1527 TextureInitRange {
1528 mip_range: destination.mip_level..(destination.mip_level + 1),
1529 layer_range,
1530 },
1531 None,
1532 encoder,
1533 &mut trackers.textures,
1534 &self.device.alignments,
1535 self.device.zero_buffer.as_ref(),
1536 &snatch_guard,
1537 self.device.instance_flags,
1538 )
1539 .map_err(QueueWriteError::from)?;
1540 }
1541 }
1542
1543 let regions = hal::TextureCopy {
1544 src_base: hal::TextureCopyBase {
1545 mip_level: 0,
1546 array_layer: 0,
1547 origin: source.origin.to_3d(0),
1548 aspect: hal::FormatAspects::COLOR,
1549 },
1550 dst_base,
1551 size: hal_copy_extent,
1552 };
1553
1554 let mut trackers = self.device.trackers.lock();
1555 let transitions = trackers
1556 .textures
1557 .set_single(&dst, selector, wgt::TextureUses::COPY_DST);
1558
1559 let encoder_webgl = encoder
1562 .as_any_mut()
1563 .downcast_mut::<hal::gles::CommandEncoder>()
1564 .unwrap();
1565 let dst_raw_webgl = dst_raw
1566 .as_any()
1567 .downcast_ref::<hal::gles::Texture>()
1568 .unwrap();
1569 let transitions_webgl = transitions.map(|pending| {
1570 let dyn_transition = pending.into_hal(dst_raw);
1571 hal::TextureBarrier {
1572 texture: dst_raw_webgl,
1573 range: dyn_transition.range,
1574 usage: dyn_transition.usage,
1575 queue_family_ownership_transfer: None,
1576 }
1577 });
1578
1579 use hal::CommandEncoder as _;
1580 unsafe {
1581 encoder_webgl.transition_textures(transitions_webgl);
1582 encoder_webgl.copy_external_image_to_texture(
1583 source,
1584 dst_raw_webgl,
1585 premultiplied_alpha,
1586 core::iter::once(regions),
1587 );
1588 }
1589
1590 pending_writes.insert_texture(&dst);
1591
1592 Ok(())
1593 }
1594
1595 pub fn flush_writes_for_buffer(
1597 &self,
1598 buffer: &Arc<Buffer>,
1599 snatch_guard: SnatchGuard,
1600 ) -> Result<(), BufferAccessError> {
1601 let submission = self.allocate_submission(snatch_guard)?;
1602
1603 let pending_writes = self.pending_writes.lock();
1604 if !pending_writes.contains_buffer(buffer) {
1605 return Ok(());
1606 }
1607
1608 submission.submit(pending_writes)?;
1609
1610 Ok(())
1611 }
1612
1613 fn flush_pending_writes(&self) -> Result<Option<SubmissionIndex>, DeviceError> {
1614 let snatch_guard = self.device.snatchable_lock.read();
1615 let submission = self.allocate_submission(snatch_guard)?;
1616 let submit_index = submission.index;
1617 let pending_writes = self.pending_writes.lock();
1618 if pending_writes.is_recording {
1619 submission.submit(pending_writes)?;
1620 Ok(Some(submit_index))
1621 } else {
1622 Ok(None)
1623 }
1624 }
1625
1626 #[cfg(feature = "trace")]
1627 fn trace_submission(
1628 &self,
1629 submit_index: SubmissionIndex,
1630 commands: Vec<crate::command::Command<crate::command::PointerReferences>>,
1631 ) {
1632 if let Some(ref mut trace) = *self.device.trace.lock() {
1633 trace.add(Action::Submit(submit_index, commands));
1634 }
1635 }
1636
1637 #[cfg(feature = "trace")]
1638 fn trace_failed_submission(
1639 &self,
1640 submit_index: SubmissionIndex,
1641 commands: Option<Vec<crate::command::Command<crate::command::PointerReferences>>>,
1642 error: String,
1643 ) {
1644 if let Some(ref mut trace) = *self.device.trace.lock() {
1645 trace.add(Action::FailedCommands {
1646 commands,
1647 failed_at_submit: Some(submit_index),
1648 error,
1649 });
1650 }
1651 }
1652
1653 fn submit_inner(
1654 &self,
1655 command_buffers: &[Arc<CommandBuffer>],
1656 ) -> Result<SubmissionIndex, Box<(Option<SubmissionIndex>, QueueSubmitError)>> {
1657 profiling::scope!("Queue::submit");
1658 api_log!("Queue::submit");
1659
1660 let snatch_guard = self.device.snatchable_lock.read();
1661 let mut submission = self
1662 .allocate_submission(snatch_guard)
1663 .map_err(|e| (None, e.into()))?;
1664 let submit_index = submission.index;
1665
1666 let mut lose_device_on_error = false;
1670 let mut successfully_submitted = false;
1671
1672 let res = 'error: {
1673 let mut used_surface_textures = track::TextureUsageScope::default();
1674 let mut baked_command_buffers = Vec::with_capacity(command_buffers.len());
1675
1676 if !command_buffers.is_empty() {
1677 profiling::scope!("prepare");
1678
1679 let mut first_error = None;
1680
1681 #[deny(clippy::question_mark_used)]
1684 for command_buffer in command_buffers {
1685 profiling::scope!("process command buffer");
1686
1687 used_surface_textures.set_size(self.device.tracker_indices.textures.size());
1690
1691 #[cfg_attr(not(feature = "trace"), expect(unused_mut))]
1695 let mut cmd_buf_data = command_buffer.take_finished();
1696
1697 if first_error.is_some() {
1698 continue;
1699 }
1700
1701 #[cfg(feature = "trace")]
1702 let trace_commands = cmd_buf_data
1703 .as_mut()
1704 .ok()
1705 .and_then(|data| mem::take(&mut data.trace_commands));
1706
1707 let baked = match cmd_buf_data {
1708 Ok(cmd_buf_data) => {
1709 let res = validate_command_buffer(
1710 command_buffer,
1711 self,
1712 &cmd_buf_data,
1713 &submission.snatch_guard,
1714 &mut submission.surface_textures,
1715 &mut used_surface_textures,
1716 &mut submission.command_index_guard,
1717 );
1718 if let Err(err) = res {
1719 #[cfg(feature = "trace")]
1720 self.trace_failed_submission(
1721 submit_index,
1722 trace_commands,
1723 err.to_string(),
1724 );
1725 first_error.get_or_insert(err);
1726 continue;
1727 }
1728
1729 #[cfg(feature = "trace")]
1730 if let Some(commands) = trace_commands {
1731 self.trace_submission(submit_index, commands);
1732 }
1733
1734 cmd_buf_data
1735 .set_acceleration_structure_dependencies(&submission.snatch_guard);
1736 cmd_buf_data.into_baked_commands()
1737 }
1738 Err(err) => {
1739 #[cfg(feature = "trace")]
1740 self.trace_failed_submission(
1741 submit_index,
1742 trace_commands,
1743 err.to_string(),
1744 );
1745 first_error.get_or_insert(err.into());
1746 continue;
1747 }
1748 };
1749
1750 baked_command_buffers.push(baked);
1751 }
1752
1753 if let Some(first_error) = first_error {
1754 break 'error Err(first_error);
1755 }
1756
1757 lose_device_on_error = true;
1770
1771 let mut trackers = self.device.trackers.lock();
1773
1774 for mut baked in baked_command_buffers {
1775 profiling::scope!("process baked commands");
1776
1777 if let Err(e) = baked
1778 .process_deferred_query_set_resolves(&self.device, &submission.snatch_guard)
1779 {
1780 break 'error Err(e.into());
1781 }
1782
1783 if let Err(e) = baked.encoder.open_pass(hal_label(
1785 Some("(wgpu internal) Transit"),
1786 self.device.instance_flags,
1787 )) {
1788 break 'error Err(e.into());
1789 }
1790
1791 baked.initialize_buffer_memory(&mut trackers, &submission.snatch_guard);
1792
1793 let depth_slice_discards = match baked.initialize_texture_memory(
1794 &mut trackers,
1795 &self.device,
1796 &submission.snatch_guard,
1797 ) {
1798 Ok(discards) => discards,
1799 Err(e) => {
1800 break 'error Err(QueueSubmitError::CommandEncoder(
1801 CommandEncoderError::Clear(e),
1802 ));
1803 }
1804 };
1805
1806 CommandEncoder::insert_barriers_from_device_tracker(
1809 baked.encoder.raw.as_mut(),
1810 &mut trackers,
1811 &baked.trackers,
1812 &submission.snatch_guard,
1813 );
1814
1815 if let Err(e) = baked.encoder.close_and_push_front() {
1816 break 'error Err(e.into());
1817 }
1818
1819 if !depth_slice_discards.is_empty() || !used_surface_textures.is_empty() {
1820 if let Err(e) = baked.encoder.open_pass(hal_label(
1821 Some("(wgpu internal) Finalize"),
1822 self.device.instance_flags,
1823 )) {
1824 break 'error Err(e.into());
1825 }
1826
1827 if let Err(e) = baked.initialize_discarded_depth_slices(
1828 depth_slice_discards,
1829 &mut trackers,
1830 &self.device,
1831 &submission.snatch_guard,
1832 ) {
1833 break 'error Err(QueueSubmitError::CommandEncoder(
1834 CommandEncoderError::Clear(e),
1835 ));
1836 }
1837
1838 let texture_barriers = trackers
1842 .textures
1843 .set_from_usage_scope_and_drain_transitions(
1844 &used_surface_textures,
1845 &submission.snatch_guard,
1846 )
1847 .collect::<Vec<_>>();
1848 unsafe {
1849 baked.encoder.raw.transition_textures(&texture_barriers);
1850 };
1851 if let Err(e) = baked.encoder.close() {
1852 break 'error Err(e.into());
1853 }
1854 used_surface_textures = track::TextureUsageScope::default();
1855 }
1856
1857 submission.executions.push(EncoderInFlight {
1859 inner: baked.encoder,
1860 trackers: baked.trackers,
1861 temp_resources: baked.temp_resources,
1862 _indirect_draw_validation_resources: baked
1863 .indirect_draw_validation_resources,
1864 pending_buffers: FastHashMap::default(),
1865 pending_textures: FastHashMap::default(),
1866 pending_blas_s: FastHashMap::default(),
1867 _pending_shader_binding_data: Vec::new(),
1868 });
1869 }
1870 }
1871
1872 let pending_writes = self.pending_writes.lock();
1873
1874 let SubmissionResult { snatch_guard } = match submission.submit(pending_writes) {
1875 Ok(result) => result,
1876 Err(e) => break 'error Err(e.into()),
1877 };
1878 successfully_submitted = true;
1879
1880 profiling::scope!("cleanup");
1881
1882 lose_device_on_error = false;
1886
1887 let (closures, result) = self.device.maintain(wgt::PollType::Poll, snatch_guard);
1891 match result {
1892 Ok(status) => {
1893 debug_assert!(matches!(
1894 status,
1895 wgt::PollStatus::QueueEmpty | wgt::PollStatus::Poll
1896 ));
1897 }
1898 Err(WaitIdleError::Device(err)) => break 'error Err(QueueSubmitError::Queue(err)),
1899 Err(WaitIdleError::WrongSubmissionIndex(..)) => {
1900 unreachable!("Cannot get WrongSubmissionIndex from Poll")
1901 }
1902 Err(WaitIdleError::Timeout) => unreachable!("Cannot get Timeout from Poll"),
1903 };
1904
1905 Ok(closures)
1906 }; let callbacks = match res {
1909 Ok(ok) => ok,
1910 Err(e) => {
1911 if lose_device_on_error {
1912 self.device.lose("submission failed");
1913 }
1914 return Err(Box::new((
1915 successfully_submitted.then_some(submit_index),
1916 e,
1917 )));
1918 }
1919 };
1920
1921 callbacks.fire();
1923
1924 self.device.lose_if_oom();
1925
1926 api_log!("Queue::submit returned submit index {submit_index}");
1927
1928 Ok(submit_index)
1929 }
1930
1931 pub fn submit(&self, command_buffers: &[Arc<CommandBuffer>]) -> Option<SubmissionIndex> {
1932 match self.submit_inner(command_buffers) {
1933 Ok(submit_index) => Some(submit_index),
1934 Err(e) => {
1935 let (submit_index, e) = *e;
1936 self.device
1937 .handle_error(e, Some(self.label()), "Queue::submit");
1938 submit_index
1939 }
1940 }
1941 }
1942
1943 fn allocate_submission<'a>(
1966 &'a self,
1967 snatch_guard: SnatchGuard<'a>,
1968 ) -> Result<PendingSubmission<'a>, DeviceError> {
1969 let mut command_index_guard = self.device.command_indices.write();
1970 command_index_guard.active_submission_index += 1;
1971 let index = command_index_guard.active_submission_index;
1972
1973 self.device.check_is_valid()?;
1974
1975 let submission = PendingSubmission {
1976 queue: self,
1977 command_index_guard,
1978 snatch_guard,
1979 executions: Vec::new(),
1980 surface_textures: FastHashMap::default(),
1981 index,
1982 };
1983
1984 Ok(submission)
1985 }
1986
1987 fn submit_pending_submission<'a>(
2003 &self,
2004 mut pending_writes: MutexGuard<'_, PendingWrites>,
2005 prepared: PendingSubmission<'a>,
2006 ) -> Result<SubmissionResult<'a>, DeviceError> {
2007 let PendingSubmission {
2008 queue: _,
2009 snatch_guard,
2010 command_index_guard,
2011 mut executions,
2012 mut surface_textures,
2013 index: submit_index,
2014 } = prepared;
2015
2016 let mut used_surface_textures = track::TextureUsageScope::default();
2017 used_surface_textures.set_size(self.device.tracker_indices.textures.size());
2018 for texture in pending_writes.dst_textures.values() {
2019 match texture.try_inner(&snatch_guard) {
2020 Ok(TextureInner::Native { .. }) => {}
2021 Ok(TextureInner::Surface { .. }) => {
2022 surface_textures.insert(Arc::as_ptr(texture), texture.clone());
2024
2025 unsafe {
2026 used_surface_textures
2027 .merge_single(texture, None, wgt::TextureUses::PRESENT)
2028 .unwrap()
2029 };
2030 }
2031 Err(InvalidOrDestroyedResourceError::DestroyedResource(_)) => {}
2036 Err(InvalidOrDestroyedResourceError::InvalidResource(_)) => {
2037 unreachable!()
2038 }
2039 }
2040 }
2041
2042 if !used_surface_textures.is_empty() {
2043 let mut trackers = self.device.trackers.lock();
2044
2045 let texture_barriers = trackers
2046 .textures
2047 .set_from_usage_scope_and_drain_transitions(&used_surface_textures, &snatch_guard)
2048 .collect::<Vec<_>>();
2049 unsafe {
2050 pending_writes
2051 .command_encoder
2052 .transition_textures(&texture_barriers);
2053 };
2054 }
2055
2056 match pending_writes.pre_submit(
2057 &self.device.command_allocator,
2058 &self.device,
2059 self,
2060 &snatch_guard,
2061 ) {
2062 Ok(Some(pending_execution)) => {
2063 executions.insert(0, pending_execution);
2064 }
2065 Ok(None) => {}
2066 Err(e) => return Err(e),
2067 }
2068 let hal_command_buffers = executions
2069 .iter()
2070 .flat_map(|e| e.inner.list.iter().map(|b| b.as_ref()))
2071 .collect::<Vec<_>>();
2072
2073 {
2074 let mut submit_surface_textures =
2075 SmallVec::<[&dyn hal::DynSurfaceTexture; 2]>::with_capacity(surface_textures.len());
2076 for texture in surface_textures.values() {
2077 let raw = match texture.try_inner(&snatch_guard).ok() {
2078 Some(TextureInner::Surface { raw, .. }) => raw.as_ref(),
2079 _ => unreachable!(),
2080 };
2081 submit_surface_textures.push(raw);
2082 }
2083
2084 unsafe {
2085 self.raw().submit(
2086 &hal_command_buffers,
2087 &submit_surface_textures,
2088 (self.device.fence.as_ref(), submit_index),
2089 )
2090 }
2091 .map_err(|e| self.device.handle_hal_error(e))?;
2092
2093 drop(pending_writes);
2097
2098 self.device
2100 .last_successful_submission_index
2101 .fetch_max(submit_index, Ordering::SeqCst);
2102 }
2103
2104 self.lock_life().track_submission(submit_index, executions);
2106
2107 drop(command_index_guard);
2113
2114 Ok(SubmissionResult { snatch_guard })
2115 }
2116
2117 pub(crate) fn get_raw_timestamp_period(&self) -> f32 {
2118 unsafe { self.raw().get_timestamp_period() }
2119 }
2120
2121 pub fn get_timestamp_period(&self) -> f32 {
2122 if self.device.timestamp_normalizer.get().unwrap().enabled() {
2123 return 1.0;
2124 }
2125
2126 self.get_raw_timestamp_period()
2127 }
2128
2129 pub fn on_submitted_work_done(
2131 &self,
2132 closure: SubmittedWorkDoneClosure,
2133 ) -> Option<SubmissionIndex> {
2134 api_log!("Queue::on_submitted_work_done");
2135
2136 let _: Result<_, DeviceError> = self.flush_pending_writes();
2140
2141 self.lock_life().add_work_done_closure(closure)
2142 }
2143
2144 #[allow(trivial_casts)]
2145 pub fn compact_blas(&self, blas: &Arc<Blas>) -> (Arc<Blas>, Option<CompactBlasError>) {
2146 api_log!(
2147 "Queue::compact_blas {:?}, {:?}",
2148 self as *const _,
2149 Arc::as_ptr(blas)
2150 );
2151
2152 let (blas, error) = match self.compact_blas_inner(blas) {
2153 Ok(blas) => (blas, None),
2154 Err(err) => {
2155 let new_label = blas.label.clone() + " (compacted)";
2156 (
2157 Blas::invalid(
2158 self.device.clone(),
2159 &BlasDescriptor {
2160 label: Some(new_label.into()),
2161 flags: blas.flags,
2162 update_mode: blas.update_mode,
2163 },
2164 ),
2165 Some(err),
2166 )
2167 }
2168 };
2169
2170 (blas, error)
2173 }
2174
2175 pub(crate) fn compact_blas_inner(
2176 &self,
2177 blas: &Arc<Blas>,
2178 ) -> Result<Arc<Blas>, CompactBlasError> {
2179 profiling::scope!("Queue::compact_blas");
2180 api_log!("Queue::compact_blas");
2181
2182 let new_label = blas.label.clone() + " (compacted)";
2183
2184 self.device.check_is_valid()?;
2185
2186 self.device.require_acceleration_structures()?;
2187
2188 blas.check_is_valid()?;
2189 self.same_device_as(blas.as_ref())?;
2190
2191 let device = blas.device.clone();
2192
2193 let snatch_guard = device.snatchable_lock.read();
2194
2195 let BlasCompactState::Ready { size } = *blas.compacted_state.lock() else {
2196 return Err(CompactBlasError::BlasNotReady);
2197 };
2198
2199 let mut size_info = blas.size_info;
2200 size_info.acceleration_structure_size = size;
2201
2202 let mut command_indices_lock = device.command_indices.write();
2203 let mut pending_writes = self.pending_writes.lock();
2204 let cmd_buf_raw = pending_writes.activate();
2205
2206 let raw = unsafe {
2207 device
2208 .raw()
2209 .create_acceleration_structure(&hal::AccelerationStructureDescriptor {
2210 label: hal_label(Some(&new_label), device.instance_flags),
2211 size: size_info.acceleration_structure_size,
2212 format: hal::AccelerationStructureFormat::BottomLevel,
2213 allow_compaction: false,
2214 })
2215 }
2216 .map_err(DeviceError::from_hal)?;
2217
2218 let src_raw = blas.try_raw(&snatch_guard)?;
2219
2220 unsafe {
2221 cmd_buf_raw.copy_acceleration_structure_to_acceleration_structure(
2222 src_raw,
2223 raw.as_ref(),
2224 wgt::AccelerationStructureCopy::Compact,
2225 )
2226 };
2227
2228 let handle = unsafe {
2229 device
2230 .raw()
2231 .get_acceleration_structure_device_address(raw.as_ref())
2232 };
2233
2234 command_indices_lock.next_acceleration_structure_build_command_index += 1;
2235 let built_index =
2236 NonZeroU64::new(command_indices_lock.next_acceleration_structure_build_command_index)
2237 .unwrap();
2238
2239 let new_blas = Arc::new(Blas {
2240 state: ResourceState::Valid(BlasState {
2241 raw: Snatchable::new(raw),
2242 }),
2243 device: device.clone(),
2244 size_info,
2245 sizes: blas.sizes.clone(),
2246 flags: blas.flags & !AccelerationStructureFlags::ALLOW_COMPACTION,
2247 update_mode: blas.update_mode,
2248 built_index: RwLock::new(rank::BLAS_BUILT_INDEX, Some(built_index)),
2250 handle,
2251 label: new_label,
2252 tracking_data: TrackingData::new(blas.device.tracker_indices.blas_s.clone()),
2253 compaction_buffer: None,
2254 compacted_state: Mutex::new(rank::BLAS_COMPACTION_STATE, BlasCompactState::Compacted),
2255 });
2256
2257 pending_writes.insert_blas(blas);
2258 pending_writes.insert_blas(&new_blas);
2259
2260 let old_blas_size = blas.size_info.acceleration_structure_size;
2262 let new_blas_size = new_blas.size_info.acceleration_structure_size;
2263
2264 api_log!("CommandEncoder::compact_blas {:?} (size: {old_blas_size}) -> {:?} (size: {new_blas_size})", Arc::as_ptr(blas), Arc::as_ptr(&new_blas));
2265
2266 Ok(new_blas)
2267 }
2268}
2269
2270fn validate_command_buffer(
2271 command_buffer: &CommandBuffer,
2272 queue: &Queue,
2273 cmd_buf_data: &crate::command::CommandBufferMutable,
2274 snatch_guard: &SnatchGuard,
2275 surface_textures: &mut FastHashMap<*const Texture, Arc<Texture>>,
2276 used_surface_textures: &mut track::TextureUsageScope,
2277 command_index_guard: &mut RwLockWriteGuard<CommandIndices>,
2278) -> Result<(), QueueSubmitError> {
2279 command_buffer.same_device_as(queue)?;
2280
2281 {
2282 profiling::scope!("check resource state");
2283
2284 {
2285 profiling::scope!("buffers");
2286 for buffer in cmd_buf_data.trackers.buffers.used_resources() {
2287 buffer.check_destroyed(snatch_guard)?;
2288
2289 match *buffer.map_state.read() {
2290 BufferMapState::Idle => (),
2291 _ => return Err(QueueSubmitError::BufferStillMapped(buffer.error_ident())),
2292 }
2293 }
2294 }
2295 {
2296 profiling::scope!("textures");
2297 for texture in cmd_buf_data.trackers.textures.used_resources() {
2298 let should_extend = match texture.try_inner(snatch_guard)? {
2299 TextureInner::Native { .. } => false,
2300 TextureInner::Surface { .. } => {
2301 surface_textures.insert(Arc::as_ptr(texture), texture.clone());
2303
2304 true
2305 }
2306 };
2307 if should_extend {
2308 unsafe {
2309 used_surface_textures
2310 .merge_single(texture, None, wgt::TextureUses::PRESENT)
2311 .unwrap();
2312 };
2313 }
2314 }
2315 }
2316 {
2317 profiling::scope!("query sets");
2318 for query_set in cmd_buf_data.trackers.query_sets.used_resources() {
2319 query_set.try_raw(snatch_guard)?;
2320 }
2321 }
2322 {
2326 profiling::scope!("bind groups");
2327 for bind_group in &cmd_buf_data.trackers.bind_groups {
2328 bind_group.try_raw(snatch_guard)?;
2330 }
2331 }
2332
2333 if let Err(e) =
2334 cmd_buf_data.validate_acceleration_structure_actions(snatch_guard, command_index_guard)
2335 {
2336 return Err(e.into());
2337 }
2338 }
2339 Ok(())
2340}