wgpu_core/device/
queue.rs

1use alloc::{boxed::Box, string::ToString, sync::Arc, vec, vec::Vec};
2use core::{
3    iter,
4    mem::{self, ManuallyDrop},
5    num::NonZeroU64,
6    ptr::NonNull,
7    sync::atomic::Ordering,
8};
9use smallvec::SmallVec;
10use thiserror::Error;
11use wgt::{
12    error::{ErrorType, WebGpuError},
13    AccelerationStructureFlags,
14};
15
16use super::{life::LifetimeTracker, Device};
17#[cfg(feature = "trace")]
18use crate::device::trace::{Action, IntoTrace};
19use crate::{
20    api_log,
21    command::{
22        extract_texture_selector, validate_linear_texture_data, validate_texture_buffer_copy,
23        validate_texture_copy_dst_format, validate_texture_copy_range, ClearError,
24        CommandAllocator, CommandBuffer, CommandEncoder, CommandEncoderError, CopySide,
25        TransferError,
26    },
27    device::{DeviceError, WaitIdleError},
28    get_lowest_common_denom,
29    global::Global,
30    hal_label,
31    id::{self, BlasId, QueueId},
32    init_tracker::{has_copy_partial_init_tracker_coverage, TextureInitRange},
33    lock::{rank, Mutex, MutexGuard, RwLock, RwLockWriteGuard},
34    ray_tracing::{BlasCompactReadyPendingClosure, CompactBlasError},
35    resource::{
36        Blas, BlasCompactState, Buffer, BufferAccessError, BufferMapState, DestroyedBuffer,
37        DestroyedResourceError, DestroyedTexture, Fallible, FlushedStagingBuffer,
38        InvalidResourceError, Labeled, ParentDevice, ResourceErrorIdent, StagingBuffer, Texture,
39        TextureInner, Trackable, TrackingData,
40    },
41    resource_log,
42    scratch::ScratchBuffer,
43    snatch::{SnatchGuard, Snatchable},
44    track::{self, Tracker, TrackerIndex},
45    FastHashMap, 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    // The device needs to be dropped last (`Device.zero_buffer` might be referenced by the encoder in pending writes).
54    pub(crate) device: Arc<Device>,
55}
56
57impl Queue {
58    pub(crate) fn new(
59        device: Arc<Device>,
60        raw: Box<dyn hal::DynQueue>,
61        instance_flags: wgt::InstanceFlags,
62    ) -> Result<Self, DeviceError> {
63        let pending_encoder = device
64            .command_allocator
65            .acquire_encoder(device.raw(), raw.as_ref())
66            .map_err(DeviceError::from_hal);
67
68        let pending_encoder = match pending_encoder {
69            Ok(pending_encoder) => pending_encoder,
70            Err(e) => {
71                return Err(e);
72            }
73        };
74
75        let mut pending_writes = PendingWrites::new(pending_encoder, instance_flags);
76
77        let zero_buffer = device.zero_buffer.as_ref();
78        pending_writes.activate();
79        unsafe {
80            pending_writes
81                .command_encoder
82                .transition_buffers(&[hal::BufferBarrier {
83                    buffer: zero_buffer,
84                    usage: hal::StateTransition {
85                        from: wgt::BufferUses::empty(),
86                        to: wgt::BufferUses::COPY_DST,
87                    },
88                }]);
89            pending_writes
90                .command_encoder
91                .clear_buffer(zero_buffer, 0..super::ZERO_BUFFER_SIZE);
92            pending_writes
93                .command_encoder
94                .transition_buffers(&[hal::BufferBarrier {
95                    buffer: zero_buffer,
96                    usage: hal::StateTransition {
97                        from: wgt::BufferUses::COPY_DST,
98                        to: wgt::BufferUses::COPY_SRC,
99                    },
100                }]);
101        }
102
103        Ok(Queue {
104            raw,
105            device,
106            pending_writes: Mutex::new(rank::QUEUE_PENDING_WRITES, pending_writes),
107            life_tracker: Mutex::new(rank::QUEUE_LIFE_TRACKER, LifetimeTracker::new()),
108        })
109    }
110
111    pub(crate) fn raw(&self) -> &dyn hal::DynQueue {
112        self.raw.as_ref()
113    }
114
115    #[track_caller]
116    pub(crate) fn lock_life<'a>(&'a self) -> MutexGuard<'a, LifetimeTracker> {
117        self.life_tracker.lock()
118    }
119
120    pub(crate) fn maintain(
121        &self,
122        submission_index: u64,
123        snatch_guard: &SnatchGuard,
124    ) -> (
125        SmallVec<[SubmittedWorkDoneClosure; 1]>,
126        Vec<super::BufferMapPendingClosure>,
127        Vec<BlasCompactReadyPendingClosure>,
128        bool,
129    ) {
130        let mut life_tracker = self.lock_life();
131        let submission_closures = life_tracker.triage_submissions(submission_index);
132
133        let mapping_closures = life_tracker.handle_mapping(snatch_guard);
134        let blas_closures = life_tracker.handle_compact_read_back();
135
136        let queue_empty = life_tracker.queue_empty();
137
138        (
139            submission_closures,
140            mapping_closures,
141            blas_closures,
142            queue_empty,
143        )
144    }
145}
146
147crate::impl_resource_type!(Queue);
148// TODO: https://github.com/gfx-rs/wgpu/issues/4014
149impl Labeled for Queue {
150    fn label(&self) -> &str {
151        ""
152    }
153}
154crate::impl_parent_device!(Queue);
155crate::impl_storage_item!(Queue);
156
157impl Drop for Queue {
158    fn drop(&mut self) {
159        resource_log!("Drop {}", self.error_ident());
160
161        let last_successful_submission_index = self
162            .device
163            .last_successful_submission_index
164            .load(Ordering::Acquire);
165
166        let fence = self.device.fence.read();
167
168        // Try waiting on the last submission using the following sequence of timeouts
169        let timeouts_in_ms = [100, 200, 400, 800, 1600, 3200];
170
171        for (i, timeout_ms) in timeouts_in_ms.into_iter().enumerate() {
172            let is_last_iter = i == timeouts_in_ms.len() - 1;
173
174            api_log!(
175                "Waiting on last submission. try: {}/{}. timeout: {}ms",
176                i + 1,
177                timeouts_in_ms.len(),
178                timeout_ms
179            );
180
181            let wait_res = unsafe {
182                self.device.raw().wait(
183                    fence.as_ref(),
184                    last_successful_submission_index,
185                    #[cfg(not(target_arch = "wasm32"))]
186                    Some(core::time::Duration::from_millis(timeout_ms)),
187                    #[cfg(target_arch = "wasm32")]
188                    Some(core::time::Duration::ZERO), // WebKit and Chromium don't support a non-0 timeout
189                )
190            };
191            // Note: If we don't panic below we are in UB land (destroying resources while they are still in use by the GPU).
192            match wait_res {
193                Ok(true) => break,
194                Ok(false) => {
195                    // It's fine that we timed out on WebGL; GL objects can be deleted early as they
196                    // will be kept around by the driver if GPU work hasn't finished.
197                    // Moreover, the way we emulate read mappings on WebGL allows us to execute map_buffer earlier than on other
198                    // backends since getBufferSubData is synchronous with respect to the other previously enqueued GL commands.
199                    // Relying on this behavior breaks the clean abstraction wgpu-hal tries to maintain and
200                    // we should find ways to improve this. See https://github.com/gfx-rs/wgpu/issues/6538.
201                    #[cfg(target_arch = "wasm32")]
202                    {
203                        break;
204                    }
205                    #[cfg(not(target_arch = "wasm32"))]
206                    {
207                        if is_last_iter {
208                            panic!(
209                                "We timed out while waiting on the last successful submission to complete!"
210                            );
211                        }
212                    }
213                }
214                Err(e) => match e {
215                    hal::DeviceError::OutOfMemory => {
216                        if is_last_iter {
217                            panic!(
218                                "We ran into an OOM error while waiting on the last successful submission to complete!"
219                            );
220                        }
221                    }
222                    hal::DeviceError::Lost => {
223                        self.device.handle_hal_error(e); // will lose the device
224                        break;
225                    }
226                    hal::DeviceError::Unexpected => {
227                        panic!(
228                            "We ran into an unexpected error while waiting on the last successful submission to complete!"
229                        );
230                    }
231                },
232            }
233        }
234        drop(fence);
235
236        let snatch_guard = self.device.snatchable_lock.read();
237        let (submission_closures, mapping_closures, blas_compact_ready_closures, queue_empty) =
238            self.maintain(last_successful_submission_index, &snatch_guard);
239        drop(snatch_guard);
240
241        assert!(queue_empty);
242
243        let closures = crate::device::UserClosures {
244            mappings: mapping_closures,
245            blas_compact_ready: blas_compact_ready_closures,
246            submissions: submission_closures,
247            device_lost_invocations: SmallVec::new(),
248        };
249
250        closures.fire();
251    }
252}
253
254#[cfg(send_sync)]
255pub type SubmittedWorkDoneClosure = Box<dyn FnOnce() + Send + 'static>;
256#[cfg(not(send_sync))]
257pub type SubmittedWorkDoneClosure = Box<dyn FnOnce() + 'static>;
258
259/// A texture or buffer to be freed soon.
260///
261/// This is just a tagged raw texture or buffer, generally about to be added to
262/// some other more specific container like:
263///
264/// - `PendingWrites::temp_resources`: resources used by queue writes and
265///   unmaps, waiting to be folded in with the next queue submission
266///
267/// - `ActiveSubmission::temp_resources`: temporary resources used by a queue
268///   submission, to be freed when it completes
269#[derive(Debug)]
270pub enum TempResource {
271    StagingBuffer(FlushedStagingBuffer),
272    ScratchBuffer(ScratchBuffer),
273    DestroyedBuffer(DestroyedBuffer),
274    DestroyedTexture(DestroyedTexture),
275}
276
277/// A series of raw [`CommandBuffer`]s that have been submitted to a
278/// queue, and the [`wgpu_hal::CommandEncoder`] that built them.
279///
280/// [`CommandBuffer`]: hal::Api::CommandBuffer
281/// [`wgpu_hal::CommandEncoder`]: hal::CommandEncoder
282pub(crate) struct EncoderInFlight {
283    inner: crate::command::InnerCommandEncoder,
284    pub(crate) trackers: Tracker,
285    pub(crate) temp_resources: Vec<TempResource>,
286    /// We only need to keep these resources alive.
287    _indirect_draw_validation_resources: crate::indirect_validation::DrawResources,
288
289    /// These are the buffers that have been tracked by `PendingWrites`.
290    pub(crate) pending_buffers: FastHashMap<TrackerIndex, Arc<Buffer>>,
291    /// These are the textures that have been tracked by `PendingWrites`.
292    pub(crate) pending_textures: FastHashMap<TrackerIndex, Arc<Texture>>,
293    /// These are the BLASes that have been tracked by `PendingWrites`.
294    pub(crate) pending_blas_s: FastHashMap<TrackerIndex, Arc<Blas>>,
295}
296
297/// A private command encoder for writes made directly on the device
298/// or queue.
299///
300/// Operations like `buffer_unmap`, `queue_write_buffer`, and
301/// `queue_write_texture` need to copy data to the GPU. At the hal
302/// level, this must be done by encoding and submitting commands, but
303/// these operations are not associated with any specific wgpu command
304/// buffer.
305///
306/// Instead, `Device::pending_writes` owns one of these values, which
307/// has its own hal command encoder and resource lists. The commands
308/// accumulated here are automatically submitted to the queue the next
309/// time the user submits a wgpu command buffer, ahead of the user's
310/// commands.
311///
312/// Important:
313/// When locking pending_writes be sure that tracker is not locked
314/// and try to lock trackers for the minimum timespan possible
315///
316/// All uses of [`StagingBuffer`]s end up here.
317#[derive(Debug)]
318pub(crate) struct PendingWrites {
319    // The command encoder needs to be destroyed before any other resource in pending writes.
320    pub command_encoder: Box<dyn hal::DynCommandEncoder>,
321
322    /// True if `command_encoder` is in the "recording" state, as
323    /// described in the docs for the [`wgpu_hal::CommandEncoder`]
324    /// trait.
325    ///
326    /// [`wgpu_hal::CommandEncoder`]: hal::CommandEncoder
327    pub is_recording: bool,
328
329    temp_resources: Vec<TempResource>,
330    dst_buffers: FastHashMap<TrackerIndex, Arc<Buffer>>,
331    dst_textures: FastHashMap<TrackerIndex, Arc<Texture>>,
332    copied_blas_s: FastHashMap<TrackerIndex, Arc<Blas>>,
333    instance_flags: wgt::InstanceFlags,
334}
335
336impl PendingWrites {
337    pub fn new(
338        command_encoder: Box<dyn hal::DynCommandEncoder>,
339        instance_flags: wgt::InstanceFlags,
340    ) -> Self {
341        Self {
342            command_encoder,
343            is_recording: false,
344            temp_resources: Vec::new(),
345            dst_buffers: FastHashMap::default(),
346            dst_textures: FastHashMap::default(),
347            copied_blas_s: FastHashMap::default(),
348            instance_flags,
349        }
350    }
351
352    pub fn insert_buffer(&mut self, buffer: &Arc<Buffer>) {
353        self.dst_buffers
354            .insert(buffer.tracker_index(), buffer.clone());
355    }
356
357    pub fn insert_texture(&mut self, texture: &Arc<Texture>) {
358        self.dst_textures
359            .insert(texture.tracker_index(), texture.clone());
360    }
361
362    pub fn insert_blas(&mut self, blas: &Arc<Blas>) {
363        self.copied_blas_s
364            .insert(blas.tracker_index(), blas.clone());
365    }
366
367    pub fn contains_buffer(&self, buffer: &Arc<Buffer>) -> bool {
368        self.dst_buffers.contains_key(&buffer.tracker_index())
369    }
370
371    pub fn contains_texture(&self, texture: &Arc<Texture>) -> bool {
372        self.dst_textures.contains_key(&texture.tracker_index())
373    }
374
375    pub fn consume_temp(&mut self, resource: TempResource) {
376        self.temp_resources.push(resource);
377    }
378
379    pub fn consume(&mut self, buffer: FlushedStagingBuffer) {
380        self.temp_resources
381            .push(TempResource::StagingBuffer(buffer));
382    }
383
384    fn pre_submit(
385        &mut self,
386        command_allocator: &CommandAllocator,
387        device: &Arc<Device>,
388        queue: &Queue,
389    ) -> Result<Option<EncoderInFlight>, DeviceError> {
390        if self.is_recording {
391            let pending_buffers = mem::take(&mut self.dst_buffers);
392            let pending_textures = mem::take(&mut self.dst_textures);
393            let pending_blas_s = mem::take(&mut self.copied_blas_s);
394
395            let cmd_buf = unsafe { self.command_encoder.end_encoding() }
396                .map_err(|e| device.handle_hal_error(e))?;
397            self.is_recording = false;
398
399            let new_encoder = command_allocator
400                .acquire_encoder(device.raw(), queue.raw())
401                .map_err(|e| device.handle_hal_error(e))?;
402
403            let encoder = EncoderInFlight {
404                inner: crate::command::InnerCommandEncoder {
405                    raw: ManuallyDrop::new(mem::replace(&mut self.command_encoder, new_encoder)),
406                    list: vec![cmd_buf],
407                    device: device.clone(),
408                    is_open: false,
409                    api: crate::command::EncodingApi::InternalUse,
410                    label: "(wgpu internal) PendingWrites command encoder".into(),
411                },
412                trackers: Tracker::new(),
413                temp_resources: mem::take(&mut self.temp_resources),
414                _indirect_draw_validation_resources: crate::indirect_validation::DrawResources::new(
415                    device.clone(),
416                ),
417                pending_buffers,
418                pending_textures,
419                pending_blas_s,
420            };
421            Ok(Some(encoder))
422        } else {
423            self.dst_buffers.clear();
424            self.dst_textures.clear();
425            self.copied_blas_s.clear();
426            Ok(None)
427        }
428    }
429
430    pub fn activate(&mut self) -> &mut dyn hal::DynCommandEncoder {
431        if !self.is_recording {
432            unsafe {
433                self.command_encoder
434                    .begin_encoding(hal_label(
435                        Some("(wgpu internal) PendingWrites"),
436                        self.instance_flags,
437                    ))
438                    .unwrap();
439            }
440            self.is_recording = true;
441        }
442        self.command_encoder.as_mut()
443    }
444}
445
446impl Drop for PendingWrites {
447    fn drop(&mut self) {
448        unsafe {
449            if self.is_recording {
450                self.command_encoder.discard_encoding();
451            }
452        }
453    }
454}
455
456#[derive(Clone, Debug, Error)]
457#[non_exhaustive]
458pub enum QueueWriteError {
459    #[error(transparent)]
460    Queue(#[from] DeviceError),
461    #[error(transparent)]
462    Transfer(#[from] TransferError),
463    #[error(transparent)]
464    MemoryInitFailure(#[from] ClearError),
465    #[error(transparent)]
466    DestroyedResource(#[from] DestroyedResourceError),
467    #[error(transparent)]
468    InvalidResource(#[from] InvalidResourceError),
469}
470
471impl WebGpuError for QueueWriteError {
472    fn webgpu_error_type(&self) -> ErrorType {
473        let e: &dyn WebGpuError = match self {
474            Self::Queue(e) => e,
475            Self::Transfer(e) => e,
476            Self::MemoryInitFailure(e) => e,
477            Self::DestroyedResource(e) => e,
478            Self::InvalidResource(e) => e,
479        };
480        e.webgpu_error_type()
481    }
482}
483
484#[derive(Clone, Debug, Error)]
485#[non_exhaustive]
486pub enum QueueSubmitError {
487    #[error(transparent)]
488    Queue(#[from] DeviceError),
489    #[error(transparent)]
490    DestroyedResource(#[from] DestroyedResourceError),
491    #[error(transparent)]
492    Unmap(#[from] BufferAccessError),
493    #[error("{0} is still mapped")]
494    BufferStillMapped(ResourceErrorIdent),
495    #[error(transparent)]
496    InvalidResource(#[from] InvalidResourceError),
497    #[error(transparent)]
498    CommandEncoder(#[from] CommandEncoderError),
499    #[error(transparent)]
500    ValidateAsActionsError(#[from] crate::ray_tracing::ValidateAsActionsError),
501}
502
503impl WebGpuError for QueueSubmitError {
504    fn webgpu_error_type(&self) -> ErrorType {
505        let e: &dyn WebGpuError = match self {
506            Self::Queue(e) => e,
507            Self::Unmap(e) => e,
508            Self::CommandEncoder(e) => e,
509            Self::ValidateAsActionsError(e) => e,
510            Self::InvalidResource(e) => e,
511            Self::DestroyedResource(_) | Self::BufferStillMapped(_) => {
512                return ErrorType::Validation
513            }
514        };
515        e.webgpu_error_type()
516    }
517}
518
519//TODO: move out common parts of write_xxx.
520
521impl Queue {
522    pub fn write_buffer(
523        &self,
524        buffer: Arc<Buffer>,
525        buffer_offset: wgt::BufferAddress,
526        data: &[u8],
527    ) -> Result<(), QueueWriteError> {
528        profiling::scope!("Queue::write_buffer");
529        api_log!("Queue::write_buffer");
530
531        self.device.check_is_valid()?;
532
533        let data_size = data.len() as wgt::BufferAddress;
534
535        self.same_device_as(buffer.as_ref())?;
536
537        let data_size = if let Some(data_size) = wgt::BufferSize::new(data_size) {
538            data_size
539        } else {
540            log::trace!("Ignoring write_buffer of size 0");
541            return Ok(());
542        };
543
544        // Platform validation requires that the staging buffer always be
545        // freed, even if an error occurs. All paths from here must call
546        // `device.pending_writes.consume`.
547        let mut staging_buffer = StagingBuffer::new(&self.device, data_size)?;
548
549        let staging_buffer = {
550            profiling::scope!("copy");
551            staging_buffer.write(data);
552            staging_buffer.flush()
553        };
554
555        let snatch_guard = self.device.snatchable_lock.read();
556        let mut pending_writes = self.pending_writes.lock();
557
558        let result = self.write_staging_buffer_impl(
559            &snatch_guard,
560            &mut pending_writes,
561            &staging_buffer,
562            buffer,
563            buffer_offset,
564        );
565
566        drop(snatch_guard);
567
568        pending_writes.consume(staging_buffer);
569
570        drop(pending_writes);
571
572        result
573    }
574
575    pub fn create_staging_buffer(
576        &self,
577        buffer_size: wgt::BufferSize,
578    ) -> Result<(StagingBuffer, NonNull<u8>), QueueWriteError> {
579        profiling::scope!("Queue::create_staging_buffer");
580        resource_log!("Queue::create_staging_buffer");
581
582        self.device.check_is_valid()?;
583
584        let staging_buffer = StagingBuffer::new(&self.device, buffer_size)?;
585        let ptr = unsafe { staging_buffer.ptr() };
586
587        Ok((staging_buffer, ptr))
588    }
589
590    pub fn write_staging_buffer(
591        &self,
592        buffer: Fallible<Buffer>,
593        buffer_offset: wgt::BufferAddress,
594        staging_buffer: StagingBuffer,
595    ) -> Result<(), QueueWriteError> {
596        profiling::scope!("Queue::write_staging_buffer");
597
598        self.device.check_is_valid()?;
599
600        let buffer = buffer.get()?;
601
602        // At this point, we have taken ownership of the staging_buffer from the
603        // user. Platform validation requires that the staging buffer always
604        // be freed, even if an error occurs. All paths from here must call
605        // `device.pending_writes.consume`.
606        let staging_buffer = staging_buffer.flush();
607
608        let snatch_guard = self.device.snatchable_lock.read();
609        let mut pending_writes = self.pending_writes.lock();
610
611        let result = self.write_staging_buffer_impl(
612            &snatch_guard,
613            &mut pending_writes,
614            &staging_buffer,
615            buffer,
616            buffer_offset,
617        );
618
619        drop(snatch_guard);
620
621        pending_writes.consume(staging_buffer);
622
623        drop(pending_writes);
624
625        result
626    }
627
628    pub fn validate_write_buffer(
629        &self,
630        buffer: Fallible<Buffer>,
631        buffer_offset: u64,
632        buffer_size: wgt::BufferSize,
633    ) -> Result<(), QueueWriteError> {
634        profiling::scope!("Queue::validate_write_buffer");
635
636        self.device.check_is_valid()?;
637
638        let buffer = buffer.get()?;
639
640        self.validate_write_buffer_impl(&buffer, buffer_offset, buffer_size)?;
641
642        Ok(())
643    }
644
645    fn validate_write_buffer_impl(
646        &self,
647        buffer: &Buffer,
648        buffer_offset: u64,
649        buffer_size: wgt::BufferSize,
650    ) -> Result<(), TransferError> {
651        if !matches!(&*buffer.map_state.lock(), BufferMapState::Idle) {
652            return Err(TransferError::BufferNotAvailable);
653        }
654        buffer.check_usage(wgt::BufferUsages::COPY_DST)?;
655        if buffer_size.get() % wgt::COPY_BUFFER_ALIGNMENT != 0 {
656            return Err(TransferError::UnalignedCopySize(buffer_size.get()));
657        }
658        if buffer_offset % wgt::COPY_BUFFER_ALIGNMENT != 0 {
659            return Err(TransferError::UnalignedBufferOffset(buffer_offset));
660        }
661        if buffer_offset + buffer_size.get() > buffer.size {
662            return Err(TransferError::BufferOverrun {
663                start_offset: buffer_offset,
664                end_offset: buffer_offset + buffer_size.get(),
665                buffer_size: buffer.size,
666                side: CopySide::Destination,
667            });
668        }
669
670        Ok(())
671    }
672
673    fn write_staging_buffer_impl(
674        &self,
675        snatch_guard: &SnatchGuard,
676        pending_writes: &mut PendingWrites,
677        staging_buffer: &FlushedStagingBuffer,
678        buffer: Arc<Buffer>,
679        buffer_offset: u64,
680    ) -> Result<(), QueueWriteError> {
681        self.device.check_is_valid()?;
682
683        let transition = {
684            let mut trackers = self.device.trackers.lock();
685            trackers
686                .buffers
687                .set_single(&buffer, wgt::BufferUses::COPY_DST)
688        };
689
690        let dst_raw = buffer.try_raw(snatch_guard)?;
691
692        self.same_device_as(buffer.as_ref())?;
693
694        self.validate_write_buffer_impl(&buffer, buffer_offset, staging_buffer.size)?;
695
696        let region = hal::BufferCopy {
697            src_offset: 0,
698            dst_offset: buffer_offset,
699            size: staging_buffer.size,
700        };
701        let barriers = iter::once(hal::BufferBarrier {
702            buffer: staging_buffer.raw(),
703            usage: hal::StateTransition {
704                from: wgt::BufferUses::MAP_WRITE,
705                to: wgt::BufferUses::COPY_SRC,
706            },
707        })
708        .chain(transition.map(|pending| pending.into_hal(&buffer, snatch_guard)))
709        .collect::<Vec<_>>();
710        let encoder = pending_writes.activate();
711        unsafe {
712            encoder.transition_buffers(&barriers);
713            encoder.copy_buffer_to_buffer(staging_buffer.raw(), dst_raw, &[region]);
714        }
715
716        pending_writes.insert_buffer(&buffer);
717
718        // Ensure the overwritten bytes are marked as initialized so
719        // they don't need to be nulled prior to mapping or binding.
720        {
721            buffer
722                .initialization_status
723                .write()
724                .drain(buffer_offset..(buffer_offset + staging_buffer.size.get()));
725        }
726
727        Ok(())
728    }
729
730    pub fn write_texture(
731        &self,
732        destination: wgt::TexelCopyTextureInfo<Arc<Texture>>,
733        data: &[u8],
734        data_layout: &wgt::TexelCopyBufferLayout,
735        size: &wgt::Extent3d,
736    ) -> Result<(), QueueWriteError> {
737        profiling::scope!("Queue::write_texture");
738        api_log!("Queue::write_texture");
739
740        self.device.check_is_valid()?;
741
742        let dst = destination.texture;
743        let destination = wgt::TexelCopyTextureInfo {
744            texture: (),
745            mip_level: destination.mip_level,
746            origin: destination.origin,
747            aspect: destination.aspect,
748        };
749
750        self.same_device_as(dst.as_ref())?;
751
752        dst.check_usage(wgt::TextureUsages::COPY_DST)
753            .map_err(TransferError::MissingTextureUsage)?;
754
755        // Note: Doing the copy range validation early is important because ensures that the
756        // dimensions are not going to cause overflow in other parts of the validation.
757        let (hal_copy_size, array_layer_count) =
758            validate_texture_copy_range(&destination, &dst.desc, CopySide::Destination, size)?;
759
760        let (selector, dst_base) = extract_texture_selector(&destination, size, &dst)?;
761
762        validate_texture_copy_dst_format(dst.desc.format, destination.aspect)?;
763
764        validate_texture_buffer_copy(
765            &destination,
766            dst_base.aspect,
767            &dst.desc,
768            data_layout,
769            false, // alignment not required for buffer offset or bytes per row
770        )?;
771
772        // Note: `_source_bytes_per_array_layer` is ignored since we
773        // have a staging copy, and it can have a different value.
774        let (required_bytes_in_copy, _source_bytes_per_array_layer, _) =
775            validate_linear_texture_data(
776                data_layout,
777                dst.desc.format,
778                destination.aspect,
779                data.len() as wgt::BufferAddress,
780                CopySide::Source,
781                size,
782            )?;
783
784        if dst.desc.format.is_depth_stencil_format() {
785            self.device
786                .require_downlevel_flags(wgt::DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES)
787                .map_err(TransferError::from)?;
788        }
789
790        let snatch_guard = self.device.snatchable_lock.read();
791
792        let dst_raw = dst.try_raw(&snatch_guard)?;
793
794        if size.width == 0 || size.height == 0 || size.depth_or_array_layers == 0 {
795            log::trace!("Ignoring write_texture of size 0");
796            return Ok(());
797        }
798
799        let mut pending_writes = self.pending_writes.lock();
800        let encoder = pending_writes.activate();
801
802        // If the copy does not fully cover the layers, we need to initialize to
803        // zero *first* as we don't keep track of partial texture layer inits.
804        //
805        // Strictly speaking we only need to clear the areas of a layer
806        // untouched, but this would get increasingly messy.
807        let init_layer_range = if dst.desc.dimension == wgt::TextureDimension::D3 {
808            // volume textures don't have a layer range as array volumes aren't supported
809            0..1
810        } else {
811            destination.origin.z..destination.origin.z + size.depth_or_array_layers
812        };
813        let mut dst_initialization_status = dst.initialization_status.write();
814        if dst_initialization_status.mips[destination.mip_level as usize]
815            .check(init_layer_range.clone())
816            .is_some()
817        {
818            if has_copy_partial_init_tracker_coverage(size, destination.mip_level, &dst.desc) {
819                for layer_range in dst_initialization_status.mips[destination.mip_level as usize]
820                    .drain(init_layer_range)
821                    .collect::<Vec<core::ops::Range<u32>>>()
822                {
823                    let mut trackers = self.device.trackers.lock();
824                    crate::command::clear_texture(
825                        &dst,
826                        TextureInitRange {
827                            mip_range: destination.mip_level..(destination.mip_level + 1),
828                            layer_range,
829                        },
830                        encoder,
831                        &mut trackers.textures,
832                        &self.device.alignments,
833                        self.device.zero_buffer.as_ref(),
834                        &snatch_guard,
835                        self.device.instance_flags,
836                    )
837                    .map_err(QueueWriteError::from)?;
838                }
839            } else {
840                dst_initialization_status.mips[destination.mip_level as usize]
841                    .drain(init_layer_range);
842            }
843        }
844
845        let (block_width, block_height) = dst.desc.format.block_dimensions();
846        let width_in_blocks = size.width / block_width;
847        let height_in_blocks = size.height / block_height;
848
849        let block_size = dst
850            .desc
851            .format
852            .block_copy_size(Some(destination.aspect))
853            .unwrap();
854        let bytes_in_last_row = width_in_blocks * block_size;
855
856        let bytes_per_row = data_layout.bytes_per_row.unwrap_or(bytes_in_last_row);
857        let rows_per_image = data_layout.rows_per_image.unwrap_or(height_in_blocks);
858
859        let bytes_per_row_alignment = get_lowest_common_denom(
860            self.device.alignments.buffer_copy_pitch.get() as u32,
861            block_size,
862        );
863        let stage_bytes_per_row = wgt::math::align_to(bytes_in_last_row, bytes_per_row_alignment);
864
865        // Platform validation requires that the staging buffer always be
866        // freed, even if an error occurs. All paths from here must call
867        // `device.pending_writes.consume`.
868        let staging_buffer = if stage_bytes_per_row == bytes_per_row {
869            profiling::scope!("copy aligned");
870            // Fast path if the data is already being aligned optimally.
871            let stage_size = wgt::BufferSize::new(required_bytes_in_copy).unwrap();
872            let mut staging_buffer = StagingBuffer::new(&self.device, stage_size)?;
873            staging_buffer.write(&data[data_layout.offset as usize..]);
874            staging_buffer
875        } else {
876            profiling::scope!("copy chunked");
877            // Copy row by row into the optimal alignment.
878            let block_rows_in_copy =
879                (size.depth_or_array_layers - 1) * rows_per_image + height_in_blocks;
880            let stage_size =
881                wgt::BufferSize::new(stage_bytes_per_row as u64 * block_rows_in_copy as u64)
882                    .unwrap();
883            let mut staging_buffer = StagingBuffer::new(&self.device, stage_size)?;
884            for layer in 0..size.depth_or_array_layers {
885                let rows_offset = layer * rows_per_image;
886                for row in rows_offset..rows_offset + height_in_blocks {
887                    let src_offset = data_layout.offset as u32 + row * bytes_per_row;
888                    let dst_offset = row * stage_bytes_per_row;
889                    unsafe {
890                        staging_buffer.write_with_offset(
891                            data,
892                            src_offset as isize,
893                            dst_offset as isize,
894                            bytes_in_last_row as usize,
895                        )
896                    }
897                }
898            }
899            staging_buffer
900        };
901
902        let staging_buffer = staging_buffer.flush();
903
904        let regions = (0..array_layer_count)
905            .map(|array_layer_offset| {
906                let mut texture_base = dst_base.clone();
907                texture_base.array_layer += array_layer_offset;
908                hal::BufferTextureCopy {
909                    buffer_layout: wgt::TexelCopyBufferLayout {
910                        offset: array_layer_offset as u64
911                            * rows_per_image as u64
912                            * stage_bytes_per_row as u64,
913                        bytes_per_row: Some(stage_bytes_per_row),
914                        rows_per_image: Some(rows_per_image),
915                    },
916                    texture_base,
917                    size: hal_copy_size,
918                }
919            })
920            .collect::<Vec<_>>();
921
922        {
923            let buffer_barrier = hal::BufferBarrier {
924                buffer: staging_buffer.raw(),
925                usage: hal::StateTransition {
926                    from: wgt::BufferUses::MAP_WRITE,
927                    to: wgt::BufferUses::COPY_SRC,
928                },
929            };
930
931            let mut trackers = self.device.trackers.lock();
932            let transition =
933                trackers
934                    .textures
935                    .set_single(&dst, selector, wgt::TextureUses::COPY_DST);
936            let texture_barriers = transition
937                .map(|pending| pending.into_hal(dst_raw))
938                .collect::<Vec<_>>();
939
940            unsafe {
941                encoder.transition_textures(&texture_barriers);
942                encoder.transition_buffers(&[buffer_barrier]);
943                encoder.copy_buffer_to_texture(staging_buffer.raw(), dst_raw, &regions);
944            }
945        }
946
947        pending_writes.consume(staging_buffer);
948        pending_writes.insert_texture(&dst);
949
950        Ok(())
951    }
952
953    #[cfg(webgl)]
954    pub fn copy_external_image_to_texture(
955        &self,
956        source: &wgt::CopyExternalImageSourceInfo,
957        destination: wgt::CopyExternalImageDestInfo<Fallible<Texture>>,
958        size: wgt::Extent3d,
959    ) -> Result<(), QueueWriteError> {
960        use crate::conv;
961
962        profiling::scope!("Queue::copy_external_image_to_texture");
963
964        self.device.check_is_valid()?;
965
966        if size.width == 0 || size.height == 0 || size.depth_or_array_layers == 0 {
967            log::trace!("Ignoring write_texture of size 0");
968            return Ok(());
969        }
970
971        let mut needs_flag = false;
972        needs_flag |= matches!(source.source, wgt::ExternalImageSource::OffscreenCanvas(_));
973        needs_flag |= source.origin != wgt::Origin2d::ZERO;
974        needs_flag |= destination.color_space != wgt::PredefinedColorSpace::Srgb;
975        #[allow(clippy::bool_comparison)]
976        if matches!(source.source, wgt::ExternalImageSource::ImageBitmap(_)) {
977            needs_flag |= source.flip_y != false;
978            needs_flag |= destination.premultiplied_alpha != false;
979        }
980
981        if needs_flag {
982            self.device
983                .require_downlevel_flags(wgt::DownlevelFlags::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES)
984                .map_err(TransferError::from)?;
985        }
986
987        let src_width = source.source.width();
988        let src_height = source.source.height();
989
990        let dst = destination.texture.get()?;
991        let premultiplied_alpha = destination.premultiplied_alpha;
992        let destination = wgt::TexelCopyTextureInfo {
993            texture: (),
994            mip_level: destination.mip_level,
995            origin: destination.origin,
996            aspect: destination.aspect,
997        };
998
999        if !conv::is_valid_external_image_copy_dst_texture_format(dst.desc.format) {
1000            return Err(
1001                TransferError::ExternalCopyToForbiddenTextureFormat(dst.desc.format).into(),
1002            );
1003        }
1004        if dst.desc.dimension != wgt::TextureDimension::D2 {
1005            return Err(TransferError::InvalidDimensionExternal.into());
1006        }
1007        dst.check_usage(wgt::TextureUsages::COPY_DST | wgt::TextureUsages::RENDER_ATTACHMENT)
1008            .map_err(TransferError::MissingTextureUsage)?;
1009        if dst.desc.sample_count != 1 {
1010            return Err(TransferError::InvalidSampleCount {
1011                sample_count: dst.desc.sample_count,
1012            }
1013            .into());
1014        }
1015
1016        if source.origin.x + size.width > src_width {
1017            return Err(TransferError::TextureOverrun {
1018                start_offset: source.origin.x,
1019                end_offset: source.origin.x + size.width,
1020                texture_size: src_width,
1021                dimension: crate::resource::TextureErrorDimension::X,
1022                side: CopySide::Source,
1023            }
1024            .into());
1025        }
1026        if source.origin.y + size.height > src_height {
1027            return Err(TransferError::TextureOverrun {
1028                start_offset: source.origin.y,
1029                end_offset: source.origin.y + size.height,
1030                texture_size: src_height,
1031                dimension: crate::resource::TextureErrorDimension::Y,
1032                side: CopySide::Source,
1033            }
1034            .into());
1035        }
1036        if size.depth_or_array_layers != 1 {
1037            return Err(TransferError::TextureOverrun {
1038                start_offset: 0,
1039                end_offset: size.depth_or_array_layers,
1040                texture_size: 1,
1041                dimension: crate::resource::TextureErrorDimension::Z,
1042                side: CopySide::Source,
1043            }
1044            .into());
1045        }
1046
1047        // Note: Doing the copy range validation early is important because ensures that the
1048        // dimensions are not going to cause overflow in other parts of the validation.
1049        let (hal_copy_size, _) =
1050            validate_texture_copy_range(&destination, &dst.desc, CopySide::Destination, &size)?;
1051
1052        let (selector, dst_base) = extract_texture_selector(&destination, &size, &dst)?;
1053
1054        let mut pending_writes = self.pending_writes.lock();
1055        let encoder = pending_writes.activate();
1056
1057        // If the copy does not fully cover the layers, we need to initialize to
1058        // zero *first* as we don't keep track of partial texture layer inits.
1059        //
1060        // Strictly speaking we only need to clear the areas of a layer
1061        // untouched, but this would get increasingly messy.
1062        let init_layer_range = if dst.desc.dimension == wgt::TextureDimension::D3 {
1063            // volume textures don't have a layer range as array volumes aren't supported
1064            0..1
1065        } else {
1066            destination.origin.z..destination.origin.z + size.depth_or_array_layers
1067        };
1068        let mut dst_initialization_status = dst.initialization_status.write();
1069        if dst_initialization_status.mips[destination.mip_level as usize]
1070            .check(init_layer_range.clone())
1071            .is_some()
1072        {
1073            if has_copy_partial_init_tracker_coverage(&size, destination.mip_level, &dst.desc) {
1074                for layer_range in dst_initialization_status.mips[destination.mip_level as usize]
1075                    .drain(init_layer_range)
1076                    .collect::<Vec<core::ops::Range<u32>>>()
1077                {
1078                    let mut trackers = self.device.trackers.lock();
1079                    crate::command::clear_texture(
1080                        &dst,
1081                        TextureInitRange {
1082                            mip_range: destination.mip_level..(destination.mip_level + 1),
1083                            layer_range,
1084                        },
1085                        encoder,
1086                        &mut trackers.textures,
1087                        &self.device.alignments,
1088                        self.device.zero_buffer.as_ref(),
1089                        &self.device.snatchable_lock.read(),
1090                        self.device.instance_flags,
1091                    )
1092                    .map_err(QueueWriteError::from)?;
1093                }
1094            } else {
1095                dst_initialization_status.mips[destination.mip_level as usize]
1096                    .drain(init_layer_range);
1097            }
1098        }
1099
1100        let snatch_guard = self.device.snatchable_lock.read();
1101        let dst_raw = dst.try_raw(&snatch_guard)?;
1102
1103        let regions = hal::TextureCopy {
1104            src_base: hal::TextureCopyBase {
1105                mip_level: 0,
1106                array_layer: 0,
1107                origin: source.origin.to_3d(0),
1108                aspect: hal::FormatAspects::COLOR,
1109            },
1110            dst_base,
1111            size: hal_copy_size,
1112        };
1113
1114        let mut trackers = self.device.trackers.lock();
1115        let transitions = trackers
1116            .textures
1117            .set_single(&dst, selector, wgt::TextureUses::COPY_DST);
1118
1119        // `copy_external_image_to_texture` is exclusive to the WebGL backend.
1120        // Don't go through the `DynCommandEncoder` abstraction and directly to the WebGL backend.
1121        let encoder_webgl = encoder
1122            .as_any_mut()
1123            .downcast_mut::<hal::gles::CommandEncoder>()
1124            .unwrap();
1125        let dst_raw_webgl = dst_raw
1126            .as_any()
1127            .downcast_ref::<hal::gles::Texture>()
1128            .unwrap();
1129        let transitions_webgl = transitions.map(|pending| {
1130            let dyn_transition = pending.into_hal(dst_raw);
1131            hal::TextureBarrier {
1132                texture: dst_raw_webgl,
1133                range: dyn_transition.range,
1134                usage: dyn_transition.usage,
1135            }
1136        });
1137
1138        use hal::CommandEncoder as _;
1139        unsafe {
1140            encoder_webgl.transition_textures(transitions_webgl);
1141            encoder_webgl.copy_external_image_to_texture(
1142                source,
1143                dst_raw_webgl,
1144                premultiplied_alpha,
1145                iter::once(regions),
1146            );
1147        }
1148
1149        Ok(())
1150    }
1151
1152    pub fn submit(
1153        &self,
1154        command_buffers: &[Arc<CommandBuffer>],
1155    ) -> Result<SubmissionIndex, (SubmissionIndex, QueueSubmitError)> {
1156        profiling::scope!("Queue::submit");
1157        api_log!("Queue::submit");
1158
1159        let submit_index;
1160
1161        let res = 'error: {
1162            let snatch_guard = self.device.snatchable_lock.read();
1163
1164            // Fence lock must be acquired after the snatch lock everywhere to avoid deadlocks.
1165            let mut fence = self.device.fence.write();
1166
1167            let mut command_index_guard = self.device.command_indices.write();
1168            command_index_guard.active_submission_index += 1;
1169            submit_index = command_index_guard.active_submission_index;
1170
1171            if let Err(e) = self.device.check_is_valid() {
1172                break 'error Err(e.into());
1173            }
1174
1175            let mut active_executions = Vec::new();
1176
1177            let mut used_surface_textures = track::TextureUsageScope::default();
1178
1179            // Use a hashmap here to deduplicate the surface textures that are used in the command buffers.
1180            // This avoids vulkan deadlocking from the same surface texture being submitted multiple times.
1181            let mut submit_surface_textures_owned = FastHashMap::default();
1182
1183            {
1184                if !command_buffers.is_empty() {
1185                    profiling::scope!("prepare");
1186
1187                    let mut first_error = None;
1188
1189                    //TODO: if multiple command buffers are submitted, we can re-use the last
1190                    // native command buffer of the previous chain instead of always creating
1191                    // a temporary one, since the chains are not finished.
1192
1193                    // finish all the command buffers first
1194                    for command_buffer in command_buffers {
1195                        profiling::scope!("process command buffer");
1196
1197                        // we reset the used surface textures every time we use
1198                        // it, so make sure to set_size on it.
1199                        used_surface_textures.set_size(self.device.tracker_indices.textures.size());
1200
1201                        // Note that we are required to invalidate all command buffers in both the success and failure paths.
1202                        // This is why we `continue` and don't early return via `?`.
1203                        #[allow(unused_mut)]
1204                        let mut cmd_buf_data = command_buffer.take_finished();
1205
1206                        #[cfg(feature = "trace")]
1207                        if let Some(ref mut trace) = *self.device.trace.lock() {
1208                            if let Ok(ref mut cmd_buf_data) = cmd_buf_data {
1209                                trace.add(Action::Submit(
1210                                    submit_index,
1211                                    cmd_buf_data.trace_commands.take().unwrap(),
1212                                ));
1213                            }
1214                        }
1215
1216                        if first_error.is_some() {
1217                            continue;
1218                        }
1219
1220                        let mut baked = match cmd_buf_data {
1221                            Ok(cmd_buf_data) => {
1222                                let res = validate_command_buffer(
1223                                    command_buffer,
1224                                    self,
1225                                    &cmd_buf_data,
1226                                    &snatch_guard,
1227                                    &mut submit_surface_textures_owned,
1228                                    &mut used_surface_textures,
1229                                    &mut command_index_guard,
1230                                );
1231                                if let Err(err) = res {
1232                                    first_error.get_or_insert(err);
1233                                    continue;
1234                                }
1235                                cmd_buf_data.into_baked_commands()
1236                            }
1237                            Err(err) => {
1238                                first_error.get_or_insert(err.into());
1239                                continue;
1240                            }
1241                        };
1242
1243                        // execute resource transitions
1244                        if let Err(e) = baked.encoder.open_pass(hal_label(
1245                            Some("(wgpu internal) Transit"),
1246                            self.device.instance_flags,
1247                        )) {
1248                            break 'error Err(e.into());
1249                        }
1250
1251                        //Note: locking the trackers has to be done after the storages
1252                        let mut trackers = self.device.trackers.lock();
1253                        if let Err(e) = baked.initialize_buffer_memory(&mut trackers, &snatch_guard)
1254                        {
1255                            break 'error Err(e.into());
1256                        }
1257                        if let Err(e) = baked.initialize_texture_memory(
1258                            &mut trackers,
1259                            &self.device,
1260                            &snatch_guard,
1261                        ) {
1262                            break 'error Err(e.into());
1263                        }
1264
1265                        //Note: stateless trackers are not merged:
1266                        // device already knows these resources exist.
1267                        CommandEncoder::insert_barriers_from_device_tracker(
1268                            baked.encoder.raw.as_mut(),
1269                            &mut trackers,
1270                            &baked.trackers,
1271                            &snatch_guard,
1272                        );
1273
1274                        if let Err(e) = baked.encoder.close_and_push_front() {
1275                            break 'error Err(e.into());
1276                        }
1277
1278                        // Transition surface textures into `Present` state.
1279                        // Note: we could technically do it after all of the command buffers,
1280                        // but here we have a command encoder by hand, so it's easier to use it.
1281                        if !used_surface_textures.is_empty() {
1282                            if let Err(e) = baked.encoder.open_pass(hal_label(
1283                                Some("(wgpu internal) Present"),
1284                                self.device.instance_flags,
1285                            )) {
1286                                break 'error Err(e.into());
1287                            }
1288                            let texture_barriers = trackers
1289                                .textures
1290                                .set_from_usage_scope_and_drain_transitions(
1291                                    &used_surface_textures,
1292                                    &snatch_guard,
1293                                )
1294                                .collect::<Vec<_>>();
1295                            unsafe {
1296                                baked.encoder.raw.transition_textures(&texture_barriers);
1297                            };
1298                            if let Err(e) = baked.encoder.close() {
1299                                break 'error Err(e.into());
1300                            }
1301                            used_surface_textures = track::TextureUsageScope::default();
1302                        }
1303
1304                        // done
1305                        active_executions.push(EncoderInFlight {
1306                            inner: baked.encoder,
1307                            trackers: baked.trackers,
1308                            temp_resources: baked.temp_resources,
1309                            _indirect_draw_validation_resources: baked
1310                                .indirect_draw_validation_resources,
1311                            pending_buffers: FastHashMap::default(),
1312                            pending_textures: FastHashMap::default(),
1313                            pending_blas_s: FastHashMap::default(),
1314                        });
1315                    }
1316
1317                    if let Some(first_error) = first_error {
1318                        break 'error Err(first_error);
1319                    }
1320                }
1321            }
1322
1323            let mut pending_writes = self.pending_writes.lock();
1324
1325            {
1326                used_surface_textures.set_size(self.device.tracker_indices.textures.size());
1327                for texture in pending_writes.dst_textures.values() {
1328                    match texture.try_inner(&snatch_guard) {
1329                        Ok(TextureInner::Native { .. }) => {}
1330                        Ok(TextureInner::Surface { .. }) => {
1331                            // Compare the Arcs by pointer as Textures don't implement Eq
1332                            submit_surface_textures_owned
1333                                .insert(Arc::as_ptr(texture), texture.clone());
1334
1335                            unsafe {
1336                                used_surface_textures
1337                                    .merge_single(texture, None, wgt::TextureUses::PRESENT)
1338                                    .unwrap()
1339                            };
1340                        }
1341                        // The texture must not have been destroyed when its usage here was
1342                        // encoded. If it was destroyed after that, then it was transferred
1343                        // to `pending_writes.temp_resources` at the time of destruction, so
1344                        // we are still okay to use it.
1345                        Err(DestroyedResourceError(_)) => {}
1346                    }
1347                }
1348
1349                if !used_surface_textures.is_empty() {
1350                    let mut trackers = self.device.trackers.lock();
1351
1352                    let texture_barriers = trackers
1353                        .textures
1354                        .set_from_usage_scope_and_drain_transitions(
1355                            &used_surface_textures,
1356                            &snatch_guard,
1357                        )
1358                        .collect::<Vec<_>>();
1359                    unsafe {
1360                        pending_writes
1361                            .command_encoder
1362                            .transition_textures(&texture_barriers);
1363                    };
1364                }
1365            }
1366
1367            match pending_writes.pre_submit(&self.device.command_allocator, &self.device, self) {
1368                Ok(Some(pending_execution)) => {
1369                    active_executions.insert(0, pending_execution);
1370                }
1371                Ok(None) => {}
1372                Err(e) => break 'error Err(e.into()),
1373            }
1374            let hal_command_buffers = active_executions
1375                .iter()
1376                .flat_map(|e| e.inner.list.iter().map(|b| b.as_ref()))
1377                .collect::<Vec<_>>();
1378
1379            {
1380                let mut submit_surface_textures =
1381                    SmallVec::<[&dyn hal::DynSurfaceTexture; 2]>::with_capacity(
1382                        submit_surface_textures_owned.len(),
1383                    );
1384
1385                for texture in submit_surface_textures_owned.values() {
1386                    let raw = match texture.inner.get(&snatch_guard) {
1387                        Some(TextureInner::Surface { raw, .. }) => raw.as_ref(),
1388                        _ => unreachable!(),
1389                    };
1390                    submit_surface_textures.push(raw);
1391                }
1392
1393                if let Err(e) = unsafe {
1394                    self.raw().submit(
1395                        &hal_command_buffers,
1396                        &submit_surface_textures,
1397                        (fence.as_mut(), submit_index),
1398                    )
1399                }
1400                .map_err(|e| self.device.handle_hal_error(e))
1401                {
1402                    break 'error Err(e.into());
1403                }
1404
1405                drop(command_index_guard);
1406
1407                // Advance the successful submission index.
1408                self.device
1409                    .last_successful_submission_index
1410                    .fetch_max(submit_index, Ordering::SeqCst);
1411            }
1412
1413            profiling::scope!("cleanup");
1414
1415            // this will register the new submission to the life time tracker
1416            self.lock_life()
1417                .track_submission(submit_index, active_executions);
1418            drop(pending_writes);
1419
1420            // This will schedule destruction of all resources that are no longer needed
1421            // by the user but used in the command stream, among other things.
1422            let fence_guard = RwLockWriteGuard::downgrade(fence);
1423            let (closures, result) =
1424                self.device
1425                    .maintain(fence_guard, wgt::PollType::Poll, snatch_guard);
1426            match result {
1427                Ok(status) => {
1428                    debug_assert!(matches!(
1429                        status,
1430                        wgt::PollStatus::QueueEmpty | wgt::PollStatus::Poll
1431                    ));
1432                }
1433                Err(WaitIdleError::Device(err)) => break 'error Err(QueueSubmitError::Queue(err)),
1434                Err(WaitIdleError::WrongSubmissionIndex(..)) => {
1435                    unreachable!("Cannot get WrongSubmissionIndex from Poll")
1436                }
1437                Err(WaitIdleError::Timeout) => unreachable!("Cannot get Timeout from Poll"),
1438            };
1439
1440            Ok(closures)
1441        };
1442
1443        let callbacks = match res {
1444            Ok(ok) => ok,
1445            Err(e) => return Err((submit_index, e)),
1446        };
1447
1448        // the closures should execute with nothing locked!
1449        callbacks.fire();
1450
1451        self.device.lose_if_oom();
1452
1453        api_log!("Queue::submit returned submit index {submit_index}");
1454
1455        Ok(submit_index)
1456    }
1457
1458    pub fn get_timestamp_period(&self) -> f32 {
1459        unsafe { self.raw().get_timestamp_period() }
1460    }
1461
1462    /// `closure` is guaranteed to be called.
1463    pub fn on_submitted_work_done(
1464        &self,
1465        closure: SubmittedWorkDoneClosure,
1466    ) -> Option<SubmissionIndex> {
1467        api_log!("Queue::on_submitted_work_done");
1468        //TODO: flush pending writes
1469        self.lock_life().add_work_done_closure(closure)
1470    }
1471
1472    pub fn compact_blas(&self, blas: &Arc<Blas>) -> Result<Arc<Blas>, CompactBlasError> {
1473        profiling::scope!("Queue::compact_blas");
1474        api_log!("Queue::compact_blas");
1475
1476        let new_label = blas.label.clone() + " (compacted)";
1477
1478        self.device.check_is_valid()?;
1479        self.same_device_as(blas.as_ref())?;
1480
1481        let device = blas.device.clone();
1482
1483        let snatch_guard = device.snatchable_lock.read();
1484
1485        let BlasCompactState::Ready { size } = *blas.compacted_state.lock() else {
1486            return Err(CompactBlasError::BlasNotReady);
1487        };
1488
1489        let mut size_info = blas.size_info;
1490        size_info.acceleration_structure_size = size;
1491
1492        let mut pending_writes = self.pending_writes.lock();
1493        let cmd_buf_raw = pending_writes.activate();
1494
1495        let raw = unsafe {
1496            device
1497                .raw()
1498                .create_acceleration_structure(&hal::AccelerationStructureDescriptor {
1499                    label: hal_label(Some(&new_label), device.instance_flags),
1500                    size: size_info.acceleration_structure_size,
1501                    format: hal::AccelerationStructureFormat::BottomLevel,
1502                    allow_compaction: false,
1503                })
1504        }
1505        .map_err(DeviceError::from_hal)?;
1506
1507        let src_raw = blas.try_raw(&snatch_guard)?;
1508
1509        unsafe {
1510            cmd_buf_raw.copy_acceleration_structure_to_acceleration_structure(
1511                src_raw,
1512                raw.as_ref(),
1513                wgt::AccelerationStructureCopy::Compact,
1514            )
1515        };
1516
1517        let handle = unsafe {
1518            device
1519                .raw()
1520                .get_acceleration_structure_device_address(raw.as_ref())
1521        };
1522
1523        drop(snatch_guard);
1524
1525        let mut command_indices_lock = device.command_indices.write();
1526        command_indices_lock.next_acceleration_structure_build_command_index += 1;
1527        let built_index =
1528            NonZeroU64::new(command_indices_lock.next_acceleration_structure_build_command_index)
1529                .unwrap();
1530
1531        let new_blas = Arc::new(Blas {
1532            raw: Snatchable::new(raw),
1533            device: device.clone(),
1534            size_info,
1535            sizes: blas.sizes.clone(),
1536            flags: blas.flags & !AccelerationStructureFlags::ALLOW_COMPACTION,
1537            update_mode: blas.update_mode,
1538            // Bypass the submit checks which update this because we don't submit this normally.
1539            built_index: RwLock::new(rank::BLAS_BUILT_INDEX, Some(built_index)),
1540            handle,
1541            label: new_label,
1542            tracking_data: TrackingData::new(blas.device.tracker_indices.blas_s.clone()),
1543            compaction_buffer: None,
1544            compacted_state: Mutex::new(rank::BLAS_COMPACTION_STATE, BlasCompactState::Compacted),
1545        });
1546
1547        pending_writes.insert_blas(blas);
1548        pending_writes.insert_blas(&new_blas);
1549
1550        Ok(new_blas)
1551    }
1552}
1553
1554impl Global {
1555    pub fn queue_write_buffer(
1556        &self,
1557        queue_id: QueueId,
1558        buffer_id: id::BufferId,
1559        buffer_offset: wgt::BufferAddress,
1560        data: &[u8],
1561    ) -> Result<(), QueueWriteError> {
1562        let queue = self.hub.queues.get(queue_id);
1563        let buffer = self.hub.buffers.get(buffer_id).get()?;
1564
1565        #[cfg(feature = "trace")]
1566        if let Some(ref mut trace) = *queue.device.trace.lock() {
1567            let data_path = trace.make_binary("bin", data);
1568            trace.add(Action::WriteBuffer {
1569                id: buffer.to_trace(),
1570                data: data_path,
1571                range: buffer_offset..buffer_offset + data.len() as u64,
1572                queued: true,
1573            });
1574        }
1575
1576        queue.write_buffer(buffer, buffer_offset, data)
1577    }
1578
1579    pub fn queue_create_staging_buffer(
1580        &self,
1581        queue_id: QueueId,
1582        buffer_size: wgt::BufferSize,
1583        id_in: Option<id::StagingBufferId>,
1584    ) -> Result<(id::StagingBufferId, NonNull<u8>), QueueWriteError> {
1585        let queue = self.hub.queues.get(queue_id);
1586        let (staging_buffer, ptr) = queue.create_staging_buffer(buffer_size)?;
1587
1588        let fid = self.hub.staging_buffers.prepare(id_in);
1589        let id = fid.assign(staging_buffer);
1590
1591        Ok((id, ptr))
1592    }
1593
1594    pub fn queue_write_staging_buffer(
1595        &self,
1596        queue_id: QueueId,
1597        buffer_id: id::BufferId,
1598        buffer_offset: wgt::BufferAddress,
1599        staging_buffer_id: id::StagingBufferId,
1600    ) -> Result<(), QueueWriteError> {
1601        let queue = self.hub.queues.get(queue_id);
1602        let buffer = self.hub.buffers.get(buffer_id);
1603        let staging_buffer = self.hub.staging_buffers.remove(staging_buffer_id);
1604        queue.write_staging_buffer(buffer, buffer_offset, staging_buffer)
1605    }
1606
1607    pub fn queue_validate_write_buffer(
1608        &self,
1609        queue_id: QueueId,
1610        buffer_id: id::BufferId,
1611        buffer_offset: u64,
1612        buffer_size: wgt::BufferSize,
1613    ) -> Result<(), QueueWriteError> {
1614        let queue = self.hub.queues.get(queue_id);
1615        let buffer = self.hub.buffers.get(buffer_id);
1616        queue.validate_write_buffer(buffer, buffer_offset, buffer_size)
1617    }
1618
1619    pub fn queue_write_texture(
1620        &self,
1621        queue_id: QueueId,
1622        destination: &wgt::TexelCopyTextureInfo<id::TextureId>,
1623        data: &[u8],
1624        data_layout: &wgt::TexelCopyBufferLayout,
1625        size: &wgt::Extent3d,
1626    ) -> Result<(), QueueWriteError> {
1627        let queue = self.hub.queues.get(queue_id);
1628        let texture = self.hub.textures.get(destination.texture).get()?;
1629        let destination = wgt::TexelCopyTextureInfo {
1630            texture,
1631            mip_level: destination.mip_level,
1632            origin: destination.origin,
1633            aspect: destination.aspect,
1634        };
1635
1636        #[cfg(feature = "trace")]
1637        if let Some(ref mut trace) = *queue.device.trace.lock() {
1638            let data_path = trace.make_binary("bin", data);
1639            trace.add(Action::WriteTexture {
1640                to: destination.to_trace(),
1641                data: data_path,
1642                layout: *data_layout,
1643                size: *size,
1644            });
1645        }
1646
1647        queue.write_texture(destination, data, data_layout, size)
1648    }
1649
1650    #[cfg(webgl)]
1651    pub fn queue_copy_external_image_to_texture(
1652        &self,
1653        queue_id: QueueId,
1654        source: &wgt::CopyExternalImageSourceInfo,
1655        destination: crate::command::CopyExternalImageDestInfo,
1656        size: wgt::Extent3d,
1657    ) -> Result<(), QueueWriteError> {
1658        let queue = self.hub.queues.get(queue_id);
1659        let destination = wgt::CopyExternalImageDestInfo {
1660            texture: self.hub.textures.get(destination.texture),
1661            mip_level: destination.mip_level,
1662            origin: destination.origin,
1663            aspect: destination.aspect,
1664            color_space: destination.color_space,
1665            premultiplied_alpha: destination.premultiplied_alpha,
1666        };
1667        queue.copy_external_image_to_texture(source, destination, size)
1668    }
1669
1670    pub fn queue_submit(
1671        &self,
1672        queue_id: QueueId,
1673        command_buffer_ids: &[id::CommandBufferId],
1674    ) -> Result<SubmissionIndex, (SubmissionIndex, QueueSubmitError)> {
1675        let queue = self.hub.queues.get(queue_id);
1676        let command_buffer_guard = self.hub.command_buffers.read();
1677        let command_buffers = command_buffer_ids
1678            .iter()
1679            .map(|id| command_buffer_guard.get(*id))
1680            .collect::<Vec<_>>();
1681        drop(command_buffer_guard);
1682        queue.submit(&command_buffers)
1683    }
1684
1685    pub fn queue_get_timestamp_period(&self, queue_id: QueueId) -> f32 {
1686        let queue = self.hub.queues.get(queue_id);
1687
1688        if queue.device.timestamp_normalizer.get().unwrap().enabled() {
1689            return 1.0;
1690        }
1691
1692        queue.get_timestamp_period()
1693    }
1694
1695    pub fn queue_on_submitted_work_done(
1696        &self,
1697        queue_id: QueueId,
1698        closure: SubmittedWorkDoneClosure,
1699    ) -> SubmissionIndex {
1700        api_log!("Queue::on_submitted_work_done {queue_id:?}");
1701
1702        //TODO: flush pending writes
1703        let queue = self.hub.queues.get(queue_id);
1704        let result = queue.on_submitted_work_done(closure);
1705        result.unwrap_or(0) // '0' means no wait is necessary
1706    }
1707
1708    pub fn queue_compact_blas(
1709        &self,
1710        queue_id: QueueId,
1711        blas_id: BlasId,
1712        id_in: Option<BlasId>,
1713    ) -> (BlasId, Option<u64>, Option<CompactBlasError>) {
1714        api_log!("Queue::compact_blas {queue_id:?}, {blas_id:?}");
1715
1716        let fid = self.hub.blas_s.prepare(id_in);
1717
1718        let queue = self.hub.queues.get(queue_id);
1719        let blas = self.hub.blas_s.get(blas_id);
1720        let device = &queue.device;
1721
1722        // TODO: Tracing
1723
1724        let error = 'error: {
1725            match device.require_features(wgpu_types::Features::EXPERIMENTAL_RAY_QUERY) {
1726                Ok(_) => {}
1727                Err(err) => break 'error err.into(),
1728            }
1729
1730            let blas = match blas.get() {
1731                Ok(blas) => blas,
1732                Err(err) => break 'error err.into(),
1733            };
1734
1735            let new_blas = match queue.compact_blas(&blas) {
1736                Ok(blas) => blas,
1737                Err(err) => break 'error err,
1738            };
1739
1740            // We should have no more errors after this because we have marked the command encoder as successful.
1741            let old_blas_size = blas.size_info.acceleration_structure_size;
1742            let new_blas_size = new_blas.size_info.acceleration_structure_size;
1743            let handle = new_blas.handle;
1744
1745            let id = fid.assign(Fallible::Valid(new_blas));
1746
1747            api_log!("CommandEncoder::compact_blas {blas_id:?} (size: {old_blas_size}) -> {id:?} (size: {new_blas_size})");
1748
1749            return (id, Some(handle), None);
1750        };
1751
1752        let id = fid.assign(Fallible::Invalid(Arc::new(error.to_string())));
1753
1754        (id, None, Some(error))
1755    }
1756}
1757
1758fn validate_command_buffer(
1759    command_buffer: &CommandBuffer,
1760    queue: &Queue,
1761    cmd_buf_data: &crate::command::CommandBufferMutable,
1762    snatch_guard: &SnatchGuard,
1763    submit_surface_textures_owned: &mut FastHashMap<*const Texture, Arc<Texture>>,
1764    used_surface_textures: &mut track::TextureUsageScope,
1765    command_index_guard: &mut RwLockWriteGuard<CommandIndices>,
1766) -> Result<(), QueueSubmitError> {
1767    command_buffer.same_device_as(queue)?;
1768
1769    {
1770        profiling::scope!("check resource state");
1771
1772        {
1773            profiling::scope!("buffers");
1774            for buffer in cmd_buf_data.trackers.buffers.used_resources() {
1775                buffer.check_destroyed(snatch_guard)?;
1776
1777                match *buffer.map_state.lock() {
1778                    BufferMapState::Idle => (),
1779                    _ => return Err(QueueSubmitError::BufferStillMapped(buffer.error_ident())),
1780                }
1781            }
1782        }
1783        {
1784            profiling::scope!("textures");
1785            for texture in cmd_buf_data.trackers.textures.used_resources() {
1786                let should_extend = match texture.try_inner(snatch_guard)? {
1787                    TextureInner::Native { .. } => false,
1788                    TextureInner::Surface { .. } => {
1789                        // Compare the Arcs by pointer as Textures don't implement Eq.
1790                        submit_surface_textures_owned.insert(Arc::as_ptr(texture), texture.clone());
1791
1792                        true
1793                    }
1794                };
1795                if should_extend {
1796                    unsafe {
1797                        used_surface_textures
1798                            .merge_single(texture, None, wgt::TextureUses::PRESENT)
1799                            .unwrap();
1800                    };
1801                }
1802            }
1803        }
1804        // WebGPU requires that we check every bind group referenced during
1805        // encoding, even ones that may have been replaced before being used.
1806        // TODO(<https://github.com/gfx-rs/wgpu/issues/8510>): Optimize this.
1807        {
1808            profiling::scope!("bind groups");
1809            for bind_group in &cmd_buf_data.trackers.bind_groups {
1810                // This checks the bind group and all resources it references.
1811                bind_group.try_raw(snatch_guard)?;
1812            }
1813        }
1814
1815        if let Err(e) =
1816            cmd_buf_data.validate_acceleration_structure_actions(snatch_guard, command_index_guard)
1817        {
1818            return Err(e.into());
1819        }
1820    }
1821    Ok(())
1822}