Skip to main content

wgpu_core/device/
queue.rs

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    // The device needs to be dropped last (`Device.zero_buffer` might be referenced by the encoder in pending writes).
55    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    /// Ensure the surface texture is in the PRESENT state, clearing it if it was never rendered to.
124    /// Submits any necessary work to the GPU before the HAL present call.
125    ///
126    /// See <https://github.com/gfx-rs/wgpu/issues/6748>
127    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        // If the texture is uninitialized it needs to be cleared before presenting
136        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            // After encoding the clear operation, we must not return without
148            // adding the texture to `pending_writes`.
149            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        // Transition the texture to PRESENT in the device tracker.
173        // If it's already in PRESENT, this produces no barriers and we can skip the submission.
174        //
175        // This has to be after any clear_texture call because clear_texture modifies the tracker state internally.
176        // Computing transitions afterward ensures they reflect the actual current state.
177        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            // This assert checks that we don't return here if we encoded a
192            // clear operation for the texture, which would be a problem since
193            // we haven't done anything yet to ensure it stays alive. If we
194            // cleared the texture, then we must have produced a barrier to put
195            // it in PRESENT state, so `pending` will not be empty.
196            debug_assert!(!needs_clear);
197            return Ok(());
198        }
199
200        // Emit the transition barriers to PRESENT.
201        {
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            // SAFETY:
212            // - The encoder is in the recording state after `activate()`
213            // - The texture is kept alive by adding it to `PendingWrites` below
214            unsafe {
215                encoder.transition_textures(&barriers);
216            }
217        }
218
219        // Add the texture to `PendingWrites`. This will cause `submit()` to:
220        // - Flush any pending writes to the texture.
221        // - Include the texture in `surface_textures` for the submission.
222        // - Keep the texture alive so the texture and its clear_view aren't
223        //   destroyed before the GPU finishes the `clear_texture` operation
224        //   encoded above.
225        pending_writes.insert_texture(texture);
226
227        submission.submit(pending_writes)?;
228
229        Ok(())
230    }
231
232    /// Maintains the queue's list of finished command buffers.
233    ///
234    /// Command buffers submitted before `submission_index` was submitted
235    /// stop being tracked and callbacks which are waiting for them are
236    /// returned. Also returned is whether the queue is empty. This may
237    /// be stale unless new submissions are prevented by locking
238    /// [`Device::command_indices`]
239    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        // On Vulkan, pending presents are not tracked by fences.
279        // wait_for_idle covers both fence-tracked submissions and pending presents.
280        let result = {
281            // Synchronizes with surfaces being configured on other threads.
282            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/// A texture or buffer to be freed soon.
328///
329/// This is just a tagged raw texture or buffer, generally about to be added to
330/// some other more specific container like:
331///
332/// - `PendingWrites::temp_resources`: resources used by queue writes and
333///   unmaps, waiting to be folded in with the next queue submission
334///
335/// - `ActiveSubmission::temp_resources`: temporary resources used by a queue
336///   submission, to be freed when it completes
337#[derive(Debug)]
338pub enum TempResource {
339    StagingBuffer(FlushedStagingBuffer),
340    ScratchBuffer(ScratchBuffer),
341    DestroyedBuffer(DestroyedBuffer),
342    DestroyedTexture(DestroyedTexture),
343    DestroyedQuerySet(DestroyedQuerySet),
344}
345
346/// A series of raw [`CommandBuffer`]s that have been submitted to a
347/// queue, and the [`wgpu_hal::CommandEncoder`] that built them.
348///
349/// [`CommandBuffer`]: hal::Api::CommandBuffer
350/// [`wgpu_hal::CommandEncoder`]: hal::CommandEncoder
351pub(crate) struct EncoderInFlight {
352    inner: crate::command::InnerCommandEncoder,
353    pub(crate) trackers: Tracker,
354    pub(crate) temp_resources: Vec<TempResource>,
355    /// We only need to keep these resources alive.
356    _indirect_draw_validation_resources: crate::indirect_validation::DrawResources,
357
358    /// These are the buffers that have been tracked by `PendingWrites`.
359    pub(crate) pending_buffers: FastHashMap<TrackerIndex, Arc<Buffer>>,
360    /// These are the textures that have been tracked by `PendingWrites`.
361    pub(crate) pending_textures: FastHashMap<TrackerIndex, Arc<Texture>>,
362    /// These are the BLASes that have been tracked by `PendingWrites`.
363    pub(crate) pending_blas_s: FastHashMap<TrackerIndex, Arc<Blas>>,
364    /// These are the shader binding data buffers that have been tracked by `PendingWrites`.
365    /// Only need to keep these live while the writes wait.
366    _pending_shader_binding_data: Vec<Arc<ray_tracing_pipeline::ShaderBindingData>>,
367}
368
369/// A private command encoder for writes made directly on the device
370/// or queue.
371///
372/// Operations like `buffer_unmap`, `queue_write_buffer`, and
373/// `queue_write_texture` need to copy data to the GPU. At the hal
374/// level, this must be done by encoding and submitting commands, but
375/// these operations are not associated with any specific wgpu command
376/// buffer.
377///
378/// Instead, `Device::pending_writes` owns one of these values, which
379/// has its own hal command encoder and resource lists. The commands
380/// accumulated here are automatically submitted to the queue at the
381/// sooner of:
382///
383/// 1. The user's next wgpu command buffer submission. (Pending writes
384///    are inserted ahead of the user's commands.)
385/// 2. The next `mapAsync` request for a buffer that has pending
386///    writes.
387///
388/// Important:
389/// When locking pending_writes be sure that tracker is not locked
390/// and try to lock trackers for the minimum timespan possible
391///
392/// All uses of [`StagingBuffer`]s end up here.
393#[derive(Debug)]
394pub(crate) struct PendingWrites {
395    // The command encoder needs to be destroyed before any other resource in pending writes.
396    pub command_encoder: Box<dyn hal::DynCommandEncoder>,
397
398    /// True if `command_encoder` is in the "recording" state, as
399    /// described in the docs for the [`wgpu_hal::CommandEncoder`]
400    /// trait.
401    ///
402    /// [`wgpu_hal::CommandEncoder`]: hal::CommandEncoder
403    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    /// Buffers of shader binding data that have been written to when creating their
410    /// ray tracing pipelines.
411    written_shader_binding_data: Vec<Arc<ray_tracing_pipeline::ShaderBindingData>>,
412    instance_flags: wgt::InstanceFlags,
413
414    /// Staging buffers that are the source of a copy recorded in
415    /// `command_encoder`, and so need a `MAP_WRITE` -> `COPY_SRC` transition.
416    ///
417    /// See [`hoisted_buffer_barriers`] for why these are not recorded
418    /// immediately. Moved to `temp_resources` in [`pre_submit`].
419    ///
420    /// [`hoisted_buffer_barriers`]: PendingWrites::hoisted_buffer_barriers
421    /// [`pre_submit`]: PendingWrites::pre_submit
422    hoisted_staging_buffers: Vec<FlushedStagingBuffer>,
423
424    /// Buffer transitions that must happen before the copies recorded in
425    /// `command_encoder`.
426    ///
427    /// Recording a barrier immediately before each copy means that a frame
428    /// which calls `Queue::write_buffer` a few dozen times ends up with many
429    /// back-to-back barrier/copy pairs, when a single barrier covering every
430    /// buffer would have done just as well.
431    ///
432    /// Instead we accumulate the transitions here and record them all at once,
433    /// into a command buffer that [`pre_submit`] places in front of
434    /// `command_encoder`'s.
435    ///
436    /// Only a buffer's *first* transition in a batch may be hoisted like this.
437    /// A buffer written more than once per batch gets a second, `COPY_DST` ->
438    /// `COPY_DST` transition from the tracker (unless the adapter reports
439    /// `COPY_DST` as an ordered usage), and that barrier exists precisely to
440    /// separate the two copies, so it has to stay where it was recorded. See
441    /// [`hoist_buffer_barrier`].
442    ///
443    /// [`pre_submit`]: PendingWrites::pre_submit
444    /// [`hoist_buffer_barrier`]: PendingWrites::hoist_buffer_barrier
445    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    /// Take ownership of a staging buffer that is the source of a copy
499    /// recorded into this batch.
500    ///
501    /// This also queues up the staging buffer's `MAP_WRITE` -> `COPY_SRC`
502    /// transition, so callers must not record one themselves.
503    pub fn consume(&mut self, buffer: FlushedStagingBuffer) {
504        self.hoisted_staging_buffers.push(buffer);
505    }
506
507    /// Queue up a buffer transition to be recorded ahead of this batch's
508    /// copies.
509    ///
510    /// Returns the transition instead if it cannot be hoisted, in which case
511    /// the caller must record it immediately, before its own copy. This happens
512    /// when this batch has already copied into `buffer`: the transition is then
513    /// a `COPY_DST` -> `COPY_DST` write-after-write barrier separating the
514    /// earlier copy from the caller's, as hoisting it to the front of the
515    /// batch would leave the two copies unsynchronized.
516    ///
517    /// See [`hoisted_buffer_barriers`].
518    ///
519    /// [`hoisted_buffer_barriers`]: PendingWrites::hoisted_buffer_barriers
520    #[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        // `dst_buffers` is only populated once a copy has been recorded, so
529        // true here means an earlier copy in this batch already wrote `buffer`.
530        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        // Ensure the overwritten bytes are marked as initialized so
567        // they don't need to be nulled prior to mapping or binding.
568        buffer.initialization_status.write().drain(range);
569
570        Ok(())
571    }
572
573    /// Record every transition this batch of writes needs as a single barrier,
574    /// into a command buffer placed ahead of the one holding the batch's
575    /// copies.
576    ///
577    /// Returns the staging buffers whose transitions were recorded. The caller
578    /// is responsible for keeping them alive until the submission completes.
579    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                // The buffer may have been destroyed since the copy was
598                // recorded, in which case there is nothing to sync.
599                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
773/// A command submission in the process of being assembled.
774///
775/// Within `wgpu_core`, enqueuing commands for execution on the GPU is a
776/// three-step process:
777///
778/// 1) Call [`Queue::allocate_submission`] to acquire the necessary locks,
779///    assign a submission index, wrap them all up as a [`PendingSubmission`],
780///    and return it.
781///
782/// 2) Add the command buffers to be submitted to [`executions`], and note any
783///    surface textures they reference in [`surface_textures`]. Contribute to
784///    [`Queue::pending_writes`] as necessary.
785///
786/// 3) Acquire the pending writes lock. This may be done at any point between
787///    the return from [`Queue::allocate_submission`] and the call to
788///    [`submit`]. Typically it should be done as late as is possible given
789///    any necessary pending writes activity.
790///
791/// 4) Call the `PendingSubmission`'s [`submit`] method (which is a convenience
792///    wrapper around [`Queue::submit_pending_submission`]). Pass the pending
793///    writes mutex guard to [`submit`].
794///
795/// It is also acceptable to drop the `PendingSubmission` without submitting;
796/// this frees its locks in the appropriate order. This may be necessary when
797/// those locks are required to access the state that determines whether a
798/// submission is needed at all.
799///
800/// This split allows the various places in `wgpu_core` that need to submit
801/// commands to the GPU to share the common initial code for locking and final
802/// code for actually submitting the commands to `wgpu_hal`:
803///
804/// - [`Queue::submit`] just submits user-constructed [`CommandBuffer`]s.
805///
806/// - [`Queue::prepare_surface_texture_for_present`] examines the surface
807///   texture being presented, and submits deferred initialization commands and
808///   barriers to get it ready.
809///
810/// - [`Queue::flush_writes_for_buffer`] and [`Queue::flush_pending_writes`]
811///   simply submit the operations already staged in [`Queue::pending_writes`].
812///
813/// Returned from [`Queue::allocate_submission`] and consumed by [`submit`].
814/// These are internal APIs used in `Queue::submit` and other places within
815/// `wgpu-core` that need to submit work.
816///
817/// [`submit`]: PendingSubmission::submit
818/// [`executions`]: PendingSubmission::executions
819/// [`surface_textures`]: PendingSubmission::surface_textures
820pub(crate) struct PendingSubmission<'a> {
821    queue: &'a Queue,
822
823    // These lock guards must appear in this struct in the order given.
824    //
825    // The instrumented locks in [`lock::ranked`] require that locks be acquired
826    // and released in a stack-like order. Since `rank::DEVICE_COMMAND_INDICES`
827    // follows `rank::DEVICE_SNATCHABLE_LOCK`, the lock on
828    // `Device::command_indices` must be released before the lock on
829    // `Device::snatchable_lock`. Rust drops struct members from first to last,
830    // so this ordering of fields ensures the order we want.
831    /// A guard for the lock on `Device::command_indices`.
832    command_index_guard: RwLockWriteGuard<'a, CommandIndices>,
833
834    /// A guard for the lock on `Device::snatchable_lock`.
835    snatch_guard: SnatchGuard<'a>,
836
837    /// Command buffers to be submitted, along with trackers for the resources
838    /// they use.
839    pub executions: Vec<EncoderInFlight>,
840
841    /// Surface textures referenced by command buffers in this submission.
842    ///
843    /// These need to be passed to [`wgpu_hal::Queue::submit`], which
844    /// requires that the list contains no duplicates, so we store them in a
845    /// `HashMap` keyed by `SurfaceTexture` address.
846    surface_textures: FastHashMap<*const Texture, Arc<Texture>>,
847
848    /// The index this submission has been assigned.
849    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
865//TODO: move out common parts of write_xxx.
866
867impl 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            // even though a zero-length write is a no-op and no copy operation will occur,
902            // we must still validate the copy operation. This ensures that invalid
903            // API calls—like writing to a mapped buffer or out-of-bounds offsets—are
904            // caught consistently, even if no data is actually moved.
905            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        // Platform validation requires that the staging buffer always be
912        // freed, even if an error occurs. All paths from here must call
913        // `device.pending_writes.consume`.
914        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        // At this point, we have taken ownership of the staging_buffer from the
977        // user. Platform validation requires that the staging buffer always
978        // be freed, even if an error occurs. All paths from here must call
979        // `device.pending_writes.consume`.
980        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        // The staging buffer's own `MAP_WRITE` -> `COPY_SRC` transition is
1083        // hoisted by `PendingWrites::consume`, which our caller invokes.
1084        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        // Ensure the overwritten bytes are marked as initialized so
1096        // they don't need to be nulled prior to mapping or binding.
1097        {
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        // Note: Doing the copy range validation early is important because ensures that the
1147        // dimensions are not going to cause overflow in other parts of the validation.
1148        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, // alignment not required for buffer offset or bytes per row
1163            self.device.features,
1164        )?;
1165
1166        // Note: `_source_bytes_per_array_layer` is ignored since we
1167        // have a staging copy, and it can have a different value.
1168        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        // This must happen after parameter validation (so that errors are reported
1189        // as required by the spec), but before any side effects.
1190        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        // If the copy does not fully cover the layers, we need to initialize to
1199        // zero *first* as we don't keep track of partial texture layer inits.
1200        //
1201        // Strictly speaking we only need to clear the areas of a layer
1202        // untouched, but this would get increasingly messy.
1203        let init_layer_range = if dst.desc.dimension == wgt::TextureDimension::D3 {
1204            // volume textures don't have a layer range as array volumes aren't supported
1205            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        // Platform validation requires that the staging buffer always be
1271        // freed, even if an error occurs. All paths from here must call
1272        // `device.pending_writes.consume`.
1273        let staging_buffer = if stage_bytes_per_row == bytes_per_row {
1274            profiling::scope!("copy aligned");
1275            // Fast path if the data is already being aligned optimally.
1276            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            // Copy row by row into the optimal alignment.
1284            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            // The copy size was validated against the source buffer, however,
1288            // `stage_bytes_per_row` can differ, so let's be paranoid.
1289            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            // The staging buffer's `MAP_WRITE` -> `COPY_SRC` transition is
1343            // hoisted to the front of the batch by `PendingWrites::consume`,
1344            // below.
1345            unsafe {
1346                encoder.transition_textures(&texture_barriers);
1347                encoder.copy_buffer_to_texture(staging_buffer.raw(), dst_raw, &regions);
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        // `OffscreenCanvas` needs no downlevel flag: WebGL2's `texSubImage2D`
1385        // accepts it as a `TexImageSource` and the gles backend uploads it the
1386        // same way as `HTMLCanvasElement`.
1387        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        // Note: Doing the copy range validation early is important because ensures that the
1467        // dimensions are not going to cause overflow in other parts of the validation.
1468        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        // Ensured by is_valid_external_image_copy_dst_texture_format.
1476        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        // This must happen after parameter validation (so that errors are reported
1483        // as required by the spec), but before any side effects.
1484        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        // If the copy does not fully cover the layers, we need to initialize to
1493        // zero *first* as we don't keep track of partial texture layer inits.
1494        //
1495        // Strictly speaking we only need to clear the areas of a layer
1496        // untouched, but this would get increasingly messy.
1497        let init_layer_range = if dst.desc.dimension == wgt::TextureDimension::D3 {
1498            // volume textures don't have a layer range as array volumes aren't supported
1499            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        // `copy_external_image_to_texture` is exclusive to the WebGL backend.
1560        // Don't go through the `DynCommandEncoder` abstraction and directly to the WebGL backend.
1561        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    /// Flush `PendingWrites` if it contains a write to `buffer`.
1596    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        // If we encounter an error after we have started updating global state and before
1667        // successful submission, we must lose the device to avoid continuing with
1668        // potentially inaccurate resource state.
1669        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                // We are required to invalidate all command buffers in both the success and
1682                // failure paths, so we `continue` after errors, and disallow `?`.
1683                #[deny(clippy::question_mark_used)]
1684                for command_buffer in command_buffers {
1685                    profiling::scope!("process command buffer");
1686
1687                    // we reset the used surface textures every time we use
1688                    // it, so make sure to set_size on it.
1689                    used_surface_textures.set_size(self.device.tracker_indices.textures.size());
1690
1691                    // Anything other than our own submission work in the remainder of this
1692                    // function that attempts to use the WebGPU command buffer after this
1693                    // point, will find it vacant (invalid), and produce an error.
1694                    #[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                // At this point we have validated all the command buffers, and we start
1758                // making updates to global state. If we fail between here and successful
1759                // submission, we must lose the device, or else we could leave that global
1760                // state inaccurate or inconsistent.
1761                //
1762                // At time of writing, there were two kinds of errors that can occur in
1763                // this stage:
1764                //  - `hal` command encoding errors. These produce device loss in
1765                //    `handle_hal_error`, independent of what we do here.
1766                //  - Errors from texture initialization. The error cases that
1767                //    can actually occur should also be encoder errors, but we map
1768                //    everything to device loss, just in case.
1769                lose_device_on_error = true;
1770
1771                // Note: locking the trackers has to be done after the storages
1772                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                    // execute resource transitions
1784                    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                    //Note: stateless trackers are not merged:
1807                    // device already knows these resources exist.
1808                    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                        // Transition surface textures into `Present` state.
1839                        // Note: we could technically do it after all of the command buffers,
1840                        // but here we have a command encoder by hand, so it's easier to use it.
1841                        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                    // done
1858                    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            // Failing in `Device::maintain` won't put resource state at risk, but returning
1883            // an error from a successful submission could be confusing, do we really want
1884            // to do that?
1885            lose_device_on_error = false;
1886
1887            // This will schedule destruction of all resources that are no longer needed
1888            // by the user but used in the command stream, among other things.
1889            // `device.maintain` consumes and will release the snatch guard.
1890            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        }; // 'error
1907
1908        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        // the closures should execute with nothing locked!
1922        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    /// Allocate a submission index and prepare for a submission.
1944    ///
1945    /// This is an internal API used in [`Queue::submit`] and other places within
1946    /// `wgpu-core` that need to submit work.
1947    ///
1948    /// Returns the index and a [`PendingSubmission`].
1949    ///
1950    /// The caller passes in the already-acquired [`SnatchGuard`]. This function acquires
1951    /// the command index lock.
1952    ///
1953    /// The caller should update [`PendingSubmission::executions`] with details of the
1954    /// submission.
1955    ///
1956    /// To finalize and submit the submission, call [`PendingSubmission::submit`] (which is
1957    /// a convenience wrapper around [`Queue::submit_pending_submission`]).
1958    ///
1959    /// After calling this function and before submitting, the caller must acquire the
1960    /// pending writes lock, and pass it to `submit`.
1961    ///
1962    /// It is also acceptable to drop the `PendingSubmission` without submitting. This may
1963    /// be necessary when locks are required to access the state that determines whether a
1964    /// submission is needed.
1965    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    /// Finalize and submit a [`PendingSubmission`] that was returned by
1988    /// [`Queue::allocate_submission`].
1989    ///
1990    /// This is an internal API used in `Queue::submit` and other places within
1991    /// `wgpu-core` that need to submit work. See [`Queue::allocate_submission`]
1992    /// for more details.
1993    ///
1994    /// This function:
1995    ///
1996    /// - Performs a HAL submission of the pending writes command
1997    ///   encoder and any other command encoders that were added to the
1998    ///   [`PendingSubmission`].
1999    /// - Advances `last_successful_submission_index` and registers the
2000    ///   submission with the lifetime tracker.
2001    /// - Returns a [`SubmissionResult`], which contains the snatch guard.
2002    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                    // Compare the Arcs by pointer as Textures don't implement Eq
2023                    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                // The texture must not have been destroyed when its usage here was
2032                // encoded. If it was destroyed after that, then it was transferred
2033                // to `pending_writes.temp_resources` at the time of destruction, so
2034                // we are still okay to use it.
2035                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            // Submissions must have strictly increasing indices, so we must hold the
2094            // command index guard until we have submitted, to prevent another submission
2095            // from claiming the next index and reaching `submit` before we do.
2096            drop(pending_writes);
2097
2098            // Advance the successful submission index.
2099            self.device
2100                .last_successful_submission_index
2101                .fetch_max(submit_index, Ordering::SeqCst);
2102        }
2103
2104        // this will register the new submission to the life time tracker
2105        self.lock_life().track_submission(submit_index, executions);
2106
2107        // `device.maintain` relies on being able to prevent new submissions by
2108        // using `command_index_guard` while also checking whether there are
2109        // no tracked submissions to guarantee no new submissions will happen
2110        // after a device is lost. This requires `command_index_guard` to be
2111        // held over `self.lock_life()`
2112        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    /// `closure` is guaranteed to be called.
2130    pub fn on_submitted_work_done(
2131        &self,
2132        closure: SubmittedWorkDoneClosure,
2133    ) -> Option<SubmissionIndex> {
2134        api_log!("Queue::on_submitted_work_done");
2135
2136        // A `DeviceError` means we're losing the device anyways, so we can ignore it here
2137        // (mostly to avoid a breaking change to the `on_submitted_work_done` signature
2138        // for an error case that it is unlikely the caller will be able to handle).
2139        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        // TODO: Tracing
2171
2172        (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            // Bypass the submit checks which update this because we don't submit this normally.
2249            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        // We should have no more errors after this because we have marked the command encoder as successful.
2261        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                        // Compare the Arcs by pointer as Textures don't implement Eq.
2302                        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        // WebGPU requires that we check every bind group referenced during
2323        // encoding, even ones that may have been replaced before being used.
2324        // TODO(<https://github.com/gfx-rs/wgpu/issues/8510>): Optimize this.
2325        {
2326            profiling::scope!("bind groups");
2327            for bind_group in &cmd_buf_data.trackers.bind_groups {
2328                // This checks the bind group and all resources it references.
2329                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}