wgpu_core/device/
global.rs

1use alloc::{borrow::Cow, boxed::Box, string::String, sync::Arc, vec::Vec};
2use core::{ptr::NonNull, sync::atomic::Ordering};
3
4#[cfg(feature = "trace")]
5use crate::device::trace::{self, IntoTrace};
6use crate::{
7    api_log,
8    binding_model::{
9        self, BindGroupEntry, BindingResource, BufferBinding, ResolvedBindGroupDescriptor,
10        ResolvedBindGroupEntry, ResolvedBindingResource, ResolvedBufferBinding,
11    },
12    command::{self, CommandEncoder},
13    conv,
14    device::{life::WaitIdleError, DeviceError, DeviceLostClosure},
15    global::Global,
16    id::{self, AdapterId, DeviceId, QueueId, SurfaceId},
17    instance::{self, Adapter, Surface},
18    pipeline::{
19        self, RenderPipelineVertexProcessor, ResolvedComputePipelineDescriptor,
20        ResolvedFragmentState, ResolvedGeneralRenderPipelineDescriptor, ResolvedMeshState,
21        ResolvedProgrammableStageDescriptor, ResolvedTaskState, ResolvedVertexState,
22    },
23    present,
24    resource::{
25        self, BufferAccessError, BufferAccessResult, BufferMapOperation, CreateBufferError,
26        Fallible,
27    },
28    storage::Storage,
29    Label, LabelHelpers,
30};
31
32use wgt::{BufferAddress, TextureFormat};
33
34use super::UserClosures;
35
36impl Global {
37    pub fn adapter_is_surface_supported(
38        &self,
39        adapter_id: AdapterId,
40        surface_id: SurfaceId,
41    ) -> bool {
42        let surface = self.surfaces.get(surface_id);
43        let adapter = self.hub.adapters.get(adapter_id);
44        adapter.is_surface_supported(&surface)
45    }
46
47    pub fn surface_get_capabilities(
48        &self,
49        surface_id: SurfaceId,
50        adapter_id: AdapterId,
51    ) -> Result<wgt::SurfaceCapabilities, instance::GetSurfaceSupportError> {
52        profiling::scope!("Surface::get_capabilities");
53        self.fetch_adapter_and_surface::<_, _>(surface_id, adapter_id, |adapter, surface| {
54            let mut hal_caps = surface.get_capabilities(adapter)?;
55
56            hal_caps.formats.sort_by_key(|f| !f.is_srgb());
57
58            let usages = conv::map_texture_usage_from_hal(hal_caps.usage);
59
60            Ok(wgt::SurfaceCapabilities {
61                formats: hal_caps.formats,
62                present_modes: hal_caps.present_modes,
63                alpha_modes: hal_caps.composite_alpha_modes,
64                usages,
65            })
66        })
67    }
68
69    fn fetch_adapter_and_surface<F: FnOnce(&Adapter, &Surface) -> B, B>(
70        &self,
71        surface_id: SurfaceId,
72        adapter_id: AdapterId,
73        get_supported_callback: F,
74    ) -> B {
75        let surface = self.surfaces.get(surface_id);
76        let adapter = self.hub.adapters.get(adapter_id);
77        get_supported_callback(&adapter, &surface)
78    }
79
80    pub fn device_features(&self, device_id: DeviceId) -> wgt::Features {
81        let device = self.hub.devices.get(device_id);
82        device.features
83    }
84
85    pub fn device_limits(&self, device_id: DeviceId) -> wgt::Limits {
86        let device = self.hub.devices.get(device_id);
87        device.limits.clone()
88    }
89
90    pub fn device_adapter_info(&self, device_id: DeviceId) -> wgt::AdapterInfo {
91        let device = self.hub.devices.get(device_id);
92        device.adapter.get_info()
93    }
94
95    pub fn device_downlevel_properties(&self, device_id: DeviceId) -> wgt::DownlevelCapabilities {
96        let device = self.hub.devices.get(device_id);
97        device.downlevel.clone()
98    }
99
100    pub fn device_create_buffer(
101        &self,
102        device_id: DeviceId,
103        desc: &resource::BufferDescriptor,
104        id_in: Option<id::BufferId>,
105    ) -> (id::BufferId, Option<CreateBufferError>) {
106        profiling::scope!("Device::create_buffer");
107
108        let hub = &self.hub;
109        let fid = hub.buffers.prepare(id_in);
110
111        let error = 'error: {
112            let device = self.hub.devices.get(device_id);
113
114            let buffer = match device.create_buffer(desc) {
115                Ok(buffer) => buffer,
116                Err(e) => {
117                    break 'error e;
118                }
119            };
120
121            #[cfg(feature = "trace")]
122            if let Some(ref mut trace) = *device.trace.lock() {
123                let mut desc = desc.clone();
124                let mapped_at_creation = core::mem::replace(&mut desc.mapped_at_creation, false);
125                if mapped_at_creation && !desc.usage.contains(wgt::BufferUsages::MAP_WRITE) {
126                    desc.usage |= wgt::BufferUsages::COPY_DST;
127                }
128                trace.add(trace::Action::CreateBuffer(buffer.to_trace(), desc));
129            }
130
131            let id = fid.assign(Fallible::Valid(buffer));
132
133            api_log!(
134                "Device::create_buffer({:?}{}) -> {id:?}",
135                desc.label.as_deref().unwrap_or(""),
136                if desc.mapped_at_creation {
137                    ", mapped_at_creation"
138                } else {
139                    ""
140                }
141            );
142
143            return (id, None);
144        };
145
146        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
147        (id, Some(error))
148    }
149
150    /// Assign `id_in` an error with the given `label`.
151    ///
152    /// Ensure that future attempts to use `id_in` as a buffer ID will propagate
153    /// the error, following the WebGPU ["contagious invalidity"] style.
154    ///
155    /// Firefox uses this function to comply strictly with the WebGPU spec,
156    /// which requires [`GPUBufferDescriptor`] validation to be generated on the
157    /// Device timeline and leave the newly created [`GPUBuffer`] invalid.
158    ///
159    /// Ideally, we would simply let [`device_create_buffer`] take care of all
160    /// of this, but some errors must be detected before we can even construct a
161    /// [`wgpu_types::BufferDescriptor`] to give it. For example, the WebGPU API
162    /// allows a `GPUBufferDescriptor`'s [`usage`] property to be any WebIDL
163    /// `unsigned long` value, but we can't construct a
164    /// [`wgpu_types::BufferUsages`] value from values with unassigned bits
165    /// set. This means we must validate `usage` before we can call
166    /// `device_create_buffer`.
167    ///
168    /// When that validation fails, we must arrange for the buffer id to be
169    /// considered invalid. This method provides the means to do so.
170    ///
171    /// ["contagious invalidity"]: https://www.w3.org/TR/webgpu/#invalidity
172    /// [`GPUBufferDescriptor`]: https://www.w3.org/TR/webgpu/#dictdef-gpubufferdescriptor
173    /// [`GPUBuffer`]: https://www.w3.org/TR/webgpu/#gpubuffer
174    /// [`wgpu_types::BufferDescriptor`]: wgt::BufferDescriptor
175    /// [`device_create_buffer`]: Global::device_create_buffer
176    /// [`usage`]: https://www.w3.org/TR/webgpu/#dom-gputexturedescriptor-usage
177    /// [`wgpu_types::BufferUsages`]: wgt::BufferUsages
178    pub fn create_buffer_error(
179        &self,
180        id_in: Option<id::BufferId>,
181        desc: &resource::BufferDescriptor,
182    ) {
183        let fid = self.hub.buffers.prepare(id_in);
184        fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
185    }
186
187    /// Assign `id_in` an error with the given `label`.
188    ///
189    /// See [`Self::create_buffer_error`] for more context and explanation.
190    pub fn create_render_bundle_error(
191        &self,
192        id_in: Option<id::RenderBundleId>,
193        desc: &command::RenderBundleDescriptor,
194    ) {
195        let fid = self.hub.render_bundles.prepare(id_in);
196        fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
197    }
198
199    /// Assign `id_in` an error with the given `label`.
200    ///
201    /// See [`Self::create_buffer_error`] for more context and explanation.
202    pub fn create_texture_error(
203        &self,
204        id_in: Option<id::TextureId>,
205        desc: &resource::TextureDescriptor,
206    ) {
207        let fid = self.hub.textures.prepare(id_in);
208        fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
209    }
210
211    /// Assign `id_in` an error with the given `label`.
212    ///
213    /// See [`Self::create_buffer_error`] for more context and explanation.
214    pub fn create_external_texture_error(
215        &self,
216        id_in: Option<id::ExternalTextureId>,
217        desc: &resource::ExternalTextureDescriptor,
218    ) {
219        let fid = self.hub.external_textures.prepare(id_in);
220        fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
221    }
222
223    /// Assign `id_in` an error with the given `label`.
224    ///
225    /// In JavaScript environments, it is possible to call `GPUDevice.createBindGroupLayout` with
226    /// entries that are invalid. Because our Rust's types for bind group layouts prevent even
227    /// calling [`Self::device_create_bind_group`], we let standards-compliant environments
228    /// register an invalid bind group layout so this crate's API can still be consistently used.
229    ///
230    /// See [`Self::create_buffer_error`] for additional context and explanation.
231    pub fn create_bind_group_layout_error(
232        &self,
233        id_in: Option<id::BindGroupLayoutId>,
234        label: Option<Cow<'_, str>>,
235    ) {
236        let fid = self.hub.bind_group_layouts.prepare(id_in);
237        fid.assign(Fallible::Invalid(Arc::new(label.to_string())));
238    }
239
240    pub fn buffer_destroy(&self, buffer_id: id::BufferId) {
241        profiling::scope!("Buffer::destroy");
242        api_log!("Buffer::destroy {buffer_id:?}");
243
244        let hub = &self.hub;
245
246        let Ok(buffer) = hub.buffers.get(buffer_id).get() else {
247            // If the buffer is already invalid, there's nothing to do.
248            return;
249        };
250
251        #[cfg(feature = "trace")]
252        if let Some(trace) = buffer.device.trace.lock().as_mut() {
253            trace.add(trace::Action::FreeBuffer(buffer.to_trace()));
254        }
255
256        let _ = buffer.unmap();
257
258        buffer.destroy();
259    }
260
261    pub fn buffer_drop(&self, buffer_id: id::BufferId) {
262        profiling::scope!("Buffer::drop");
263        api_log!("Buffer::drop {buffer_id:?}");
264
265        let hub = &self.hub;
266
267        let buffer = match hub.buffers.remove(buffer_id).get() {
268            Ok(buffer) => buffer,
269            Err(_) => {
270                return;
271            }
272        };
273
274        #[cfg(feature = "trace")]
275        if let Some(t) = buffer.device.trace.lock().as_mut() {
276            t.add(trace::Action::DestroyBuffer(buffer.to_trace()));
277        }
278
279        let _ = buffer.unmap();
280    }
281
282    pub fn device_create_texture(
283        &self,
284        device_id: DeviceId,
285        desc: &resource::TextureDescriptor,
286        id_in: Option<id::TextureId>,
287    ) -> (id::TextureId, Option<resource::CreateTextureError>) {
288        profiling::scope!("Device::create_texture");
289
290        let hub = &self.hub;
291
292        let fid = hub.textures.prepare(id_in);
293
294        let error = 'error: {
295            let device = self.hub.devices.get(device_id);
296
297            let texture = match device.create_texture(desc) {
298                Ok(texture) => texture,
299                Err(error) => break 'error error,
300            };
301
302            #[cfg(feature = "trace")]
303            if let Some(ref mut trace) = *device.trace.lock() {
304                trace.add(trace::Action::CreateTexture(
305                    texture.to_trace(),
306                    desc.clone(),
307                ));
308            }
309
310            let id = fid.assign(Fallible::Valid(texture));
311            api_log!("Device::create_texture({desc:?}) -> {id:?}");
312
313            return (id, None);
314        };
315
316        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
317        (id, Some(error))
318    }
319
320    /// # Safety
321    ///
322    /// - `hal_texture` must be created from `device_id` corresponding raw handle.
323    /// - `hal_texture` must be created respecting `desc`
324    /// - `hal_texture` must be initialized
325    pub unsafe fn create_texture_from_hal(
326        &self,
327        hal_texture: Box<dyn hal::DynTexture>,
328        device_id: DeviceId,
329        desc: &resource::TextureDescriptor,
330        id_in: Option<id::TextureId>,
331    ) -> (id::TextureId, Option<resource::CreateTextureError>) {
332        profiling::scope!("Device::create_texture_from_hal");
333
334        let hub = &self.hub;
335
336        let fid = hub.textures.prepare(id_in);
337
338        let error = 'error: {
339            let device = self.hub.devices.get(device_id);
340
341            let texture = match device.create_texture_from_hal(hal_texture, desc) {
342                Ok(texture) => texture,
343                Err(error) => break 'error error,
344            };
345
346            // NB: Any change done through the raw texture handle will not be
347            // recorded in the replay
348            #[cfg(feature = "trace")]
349            if let Some(ref mut trace) = *device.trace.lock() {
350                trace.add(trace::Action::CreateTexture(
351                    texture.to_trace(),
352                    desc.clone(),
353                ));
354            }
355
356            let id = fid.assign(Fallible::Valid(texture));
357            api_log!("Device::create_texture({desc:?}) -> {id:?}");
358
359            return (id, None);
360        };
361
362        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
363        (id, Some(error))
364    }
365
366    /// # Safety
367    ///
368    /// - `hal_buffer` must be created from `device_id` corresponding raw handle.
369    /// - `hal_buffer` must be created respecting `desc`
370    /// - `hal_buffer` must be initialized
371    /// - `hal_buffer` must not have zero size.
372    pub unsafe fn create_buffer_from_hal<A: hal::Api>(
373        &self,
374        hal_buffer: A::Buffer,
375        device_id: DeviceId,
376        desc: &resource::BufferDescriptor,
377        id_in: Option<id::BufferId>,
378    ) -> (id::BufferId, Option<CreateBufferError>) {
379        profiling::scope!("Device::create_buffer");
380
381        let hub = &self.hub;
382        let fid = hub.buffers.prepare(id_in);
383
384        let device = self.hub.devices.get(device_id);
385
386        let (buffer, err) = unsafe { device.create_buffer_from_hal(Box::new(hal_buffer), desc) };
387
388        // NB: Any change done through the raw buffer handle will not be
389        // recorded in the replay
390        #[cfg(feature = "trace")]
391        if let Some(trace) = device.trace.lock().as_mut() {
392            match &buffer {
393                Fallible::Valid(arc) => {
394                    trace.add(trace::Action::CreateBuffer(arc.to_trace(), desc.clone()))
395                }
396                Fallible::Invalid(_) => {}
397            }
398        }
399
400        let id = fid.assign(buffer);
401        api_log!("Device::create_buffer -> {id:?}");
402
403        (id, err)
404    }
405
406    pub fn texture_destroy(&self, texture_id: id::TextureId) {
407        profiling::scope!("Texture::destroy");
408        api_log!("Texture::destroy {texture_id:?}");
409
410        let hub = &self.hub;
411
412        let Ok(texture) = hub.textures.get(texture_id).get() else {
413            // If the texture is already invalid, there's nothing to do.
414            return;
415        };
416
417        #[cfg(feature = "trace")]
418        if let Some(trace) = texture.device.trace.lock().as_mut() {
419            trace.add(trace::Action::FreeTexture(texture.to_trace()));
420        }
421
422        texture.destroy();
423    }
424
425    pub fn texture_drop(&self, texture_id: id::TextureId) {
426        profiling::scope!("Texture::drop");
427        api_log!("Texture::drop {texture_id:?}");
428
429        let hub = &self.hub;
430
431        let _texture = hub.textures.remove(texture_id);
432        #[cfg(feature = "trace")]
433        if let Ok(texture) = _texture.get() {
434            if let Some(t) = texture.device.trace.lock().as_mut() {
435                t.add(trace::Action::DestroyTexture(texture.to_trace()));
436            }
437        }
438    }
439
440    pub fn texture_create_view(
441        &self,
442        texture_id: id::TextureId,
443        desc: &resource::TextureViewDescriptor,
444        id_in: Option<id::TextureViewId>,
445    ) -> (id::TextureViewId, Option<resource::CreateTextureViewError>) {
446        profiling::scope!("Texture::create_view");
447
448        let hub = &self.hub;
449
450        let fid = hub.texture_views.prepare(id_in);
451
452        let error = 'error: {
453            let texture = match hub.textures.get(texture_id).get() {
454                Ok(texture) => texture,
455                Err(e) => break 'error e.into(),
456            };
457            let device = &texture.device;
458
459            let view = match device.create_texture_view(&texture, desc) {
460                Ok(view) => view,
461                Err(e) => break 'error e,
462            };
463
464            #[cfg(feature = "trace")]
465            if let Some(ref mut trace) = *device.trace.lock() {
466                trace.add(trace::Action::CreateTextureView {
467                    id: view.to_trace(),
468                    parent: texture.to_trace(),
469                    desc: desc.clone(),
470                });
471            }
472
473            let id = fid.assign(Fallible::Valid(view));
474
475            api_log!("Texture::create_view({texture_id:?}) -> {id:?}");
476
477            return (id, None);
478        };
479
480        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
481        (id, Some(error))
482    }
483
484    pub fn texture_view_drop(&self, texture_view_id: id::TextureViewId) {
485        profiling::scope!("TextureView::drop");
486        api_log!("TextureView::drop {texture_view_id:?}");
487
488        let hub = &self.hub;
489
490        let _view = hub.texture_views.remove(texture_view_id);
491
492        #[cfg(feature = "trace")]
493        if let Ok(view) = _view.get() {
494            if let Some(t) = view.device.trace.lock().as_mut() {
495                t.add(trace::Action::DestroyTextureView(view.to_trace()));
496            }
497        }
498    }
499
500    pub fn device_create_external_texture(
501        &self,
502        device_id: DeviceId,
503        desc: &resource::ExternalTextureDescriptor,
504        planes: &[id::TextureViewId],
505        id_in: Option<id::ExternalTextureId>,
506    ) -> (
507        id::ExternalTextureId,
508        Option<resource::CreateExternalTextureError>,
509    ) {
510        profiling::scope!("Device::create_external_texture");
511
512        let hub = &self.hub;
513
514        let fid = hub.external_textures.prepare(id_in);
515
516        let error = 'error: {
517            let device = self.hub.devices.get(device_id);
518
519            let planes = planes
520                .iter()
521                .map(|plane_id| self.hub.texture_views.get(*plane_id).get())
522                .collect::<Result<Vec<_>, _>>();
523            let planes = match planes {
524                Ok(planes) => planes,
525                Err(error) => break 'error error.into(),
526            };
527
528            let external_texture = match device.create_external_texture(desc, &planes) {
529                Ok(external_texture) => external_texture,
530                Err(error) => break 'error error,
531            };
532
533            #[cfg(feature = "trace")]
534            if let Some(ref mut trace) = *device.trace.lock() {
535                let planes = Box::from(
536                    planes
537                        .into_iter()
538                        .map(|plane| plane.to_trace())
539                        .collect::<Vec<_>>(),
540                );
541                trace.add(trace::Action::CreateExternalTexture {
542                    id: external_texture.to_trace(),
543                    desc: desc.clone(),
544                    planes,
545                });
546            }
547
548            let id = fid.assign(Fallible::Valid(external_texture));
549            api_log!("Device::create_external_texture({desc:?}) -> {id:?}");
550
551            return (id, None);
552        };
553
554        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
555        (id, Some(error))
556    }
557
558    pub fn external_texture_destroy(&self, external_texture_id: id::ExternalTextureId) {
559        profiling::scope!("ExternalTexture::destroy");
560        api_log!("ExternalTexture::destroy {external_texture_id:?}");
561
562        let hub = &self.hub;
563
564        let Ok(external_texture) = hub.external_textures.get(external_texture_id).get() else {
565            // If the external texture is already invalid, there's nothing to do.
566            return;
567        };
568
569        #[cfg(feature = "trace")]
570        if let Some(trace) = external_texture.device.trace.lock().as_mut() {
571            trace.add(trace::Action::FreeExternalTexture(
572                external_texture.to_trace(),
573            ));
574        }
575
576        external_texture.destroy();
577    }
578
579    pub fn external_texture_drop(&self, external_texture_id: id::ExternalTextureId) {
580        profiling::scope!("ExternalTexture::drop");
581        api_log!("ExternalTexture::drop {external_texture_id:?}");
582
583        let hub = &self.hub;
584
585        let _external_texture = hub.external_textures.remove(external_texture_id);
586
587        #[cfg(feature = "trace")]
588        if let Ok(external_texture) = _external_texture.get() {
589            if let Some(t) = external_texture.device.trace.lock().as_mut() {
590                t.add(trace::Action::DestroyExternalTexture(
591                    external_texture.to_trace(),
592                ));
593            }
594        }
595    }
596
597    pub fn device_create_sampler(
598        &self,
599        device_id: DeviceId,
600        desc: &resource::SamplerDescriptor,
601        id_in: Option<id::SamplerId>,
602    ) -> (id::SamplerId, Option<resource::CreateSamplerError>) {
603        profiling::scope!("Device::create_sampler");
604
605        let hub = &self.hub;
606        let fid = hub.samplers.prepare(id_in);
607
608        let error = 'error: {
609            let device = self.hub.devices.get(device_id);
610
611            let sampler = match device.create_sampler(desc) {
612                Ok(sampler) => sampler,
613                Err(e) => break 'error e,
614            };
615
616            #[cfg(feature = "trace")]
617            if let Some(ref mut trace) = *device.trace.lock() {
618                trace.add(trace::Action::CreateSampler(
619                    sampler.to_trace(),
620                    desc.clone(),
621                ));
622            }
623
624            let id = fid.assign(Fallible::Valid(sampler));
625            api_log!("Device::create_sampler -> {id:?}");
626
627            return (id, None);
628        };
629
630        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
631        (id, Some(error))
632    }
633
634    pub fn sampler_drop(&self, sampler_id: id::SamplerId) {
635        profiling::scope!("Sampler::drop");
636        api_log!("Sampler::drop {sampler_id:?}");
637
638        let hub = &self.hub;
639
640        let _sampler = hub.samplers.remove(sampler_id);
641
642        #[cfg(feature = "trace")]
643        if let Ok(sampler) = _sampler.get() {
644            if let Some(t) = sampler.device.trace.lock().as_mut() {
645                t.add(trace::Action::DestroySampler(sampler.to_trace()));
646            }
647        }
648    }
649
650    pub fn device_create_bind_group_layout(
651        &self,
652        device_id: DeviceId,
653        desc: &binding_model::BindGroupLayoutDescriptor,
654        id_in: Option<id::BindGroupLayoutId>,
655    ) -> (
656        id::BindGroupLayoutId,
657        Option<binding_model::CreateBindGroupLayoutError>,
658    ) {
659        profiling::scope!("Device::create_bind_group_layout");
660
661        let hub = &self.hub;
662        let fid = hub.bind_group_layouts.prepare(id_in);
663
664        let error = 'error: {
665            let device = self.hub.devices.get(device_id);
666
667            let layout = match device.create_bind_group_layout(desc) {
668                Ok(layout) => layout,
669                Err(e) => break 'error e,
670            };
671
672            #[cfg(feature = "trace")]
673            if let Some(ref mut trace) = *device.trace.lock() {
674                trace.add(trace::Action::CreateBindGroupLayout(
675                    layout.to_trace(),
676                    desc.clone(),
677                ));
678            }
679
680            let id = fid.assign(Fallible::Valid(layout.clone()));
681
682            api_log!("Device::create_bind_group_layout -> {id:?}");
683            return (id, None);
684        };
685
686        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
687        (id, Some(error))
688    }
689
690    pub fn bind_group_layout_drop(&self, bind_group_layout_id: id::BindGroupLayoutId) {
691        profiling::scope!("BindGroupLayout::drop");
692        api_log!("BindGroupLayout::drop {bind_group_layout_id:?}");
693
694        let hub = &self.hub;
695
696        let _layout = hub.bind_group_layouts.remove(bind_group_layout_id);
697
698        #[cfg(feature = "trace")]
699        if let Ok(layout) = _layout.get() {
700            if let Some(t) = layout.device.trace.lock().as_mut() {
701                t.add(trace::Action::DestroyBindGroupLayout(layout.to_trace()));
702            }
703        }
704    }
705
706    pub fn device_create_pipeline_layout(
707        &self,
708        device_id: DeviceId,
709        desc: &binding_model::PipelineLayoutDescriptor,
710        id_in: Option<id::PipelineLayoutId>,
711    ) -> (
712        id::PipelineLayoutId,
713        Option<binding_model::CreatePipelineLayoutError>,
714    ) {
715        profiling::scope!("Device::create_pipeline_layout");
716
717        let hub = &self.hub;
718        let fid = hub.pipeline_layouts.prepare(id_in);
719
720        let error = 'error: {
721            let device = self.hub.devices.get(device_id);
722
723            if let Err(e) = device.check_is_valid() {
724                break 'error e.into();
725            }
726
727            let bind_group_layouts = {
728                let bind_group_layouts_guard = hub.bind_group_layouts.read();
729                desc.bind_group_layouts
730                    .iter()
731                    .map(|bgl_id| match bgl_id {
732                        Some(bgl_id) => bind_group_layouts_guard.get(*bgl_id).get().map(Some),
733                        None => Ok(None),
734                    })
735                    .collect::<Result<Vec<_>, _>>()
736            };
737
738            let bind_group_layouts = match bind_group_layouts {
739                Ok(bind_group_layouts) => bind_group_layouts,
740                Err(e) => break 'error e.into(),
741            };
742
743            let desc = binding_model::ResolvedPipelineLayoutDescriptor {
744                label: desc.label.clone(),
745                bind_group_layouts: Cow::Owned(bind_group_layouts),
746                immediate_size: desc.immediate_size,
747            };
748
749            let layout = match device.create_pipeline_layout(&desc) {
750                Ok(layout) => layout,
751                Err(e) => break 'error e,
752            };
753
754            #[cfg(feature = "trace")]
755            if let Some(ref mut trace) = *device.trace.lock() {
756                trace.add(trace::Action::CreatePipelineLayout(
757                    layout.to_trace(),
758                    desc.to_trace(),
759                ));
760            }
761
762            let id = fid.assign(Fallible::Valid(layout));
763            api_log!("Device::create_pipeline_layout -> {id:?}");
764            return (id, None);
765        };
766
767        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
768        (id, Some(error))
769    }
770
771    pub fn pipeline_layout_drop(&self, pipeline_layout_id: id::PipelineLayoutId) {
772        profiling::scope!("PipelineLayout::drop");
773        api_log!("PipelineLayout::drop {pipeline_layout_id:?}");
774
775        let hub = &self.hub;
776
777        let _layout = hub.pipeline_layouts.remove(pipeline_layout_id);
778
779        #[cfg(feature = "trace")]
780        if let Ok(layout) = _layout.get() {
781            if let Some(t) = layout.device.trace.lock().as_mut() {
782                t.add(trace::Action::DestroyPipelineLayout(layout.to_trace()));
783            }
784        }
785    }
786
787    pub fn device_create_bind_group(
788        &self,
789        device_id: DeviceId,
790        desc: &binding_model::BindGroupDescriptor,
791        id_in: Option<id::BindGroupId>,
792    ) -> (id::BindGroupId, Option<binding_model::CreateBindGroupError>) {
793        profiling::scope!("Device::create_bind_group");
794
795        let hub = &self.hub;
796        let fid = hub.bind_groups.prepare(id_in);
797
798        let error = 'error: {
799            let device = self.hub.devices.get(device_id);
800
801            if let Err(e) = device.check_is_valid() {
802                break 'error e.into();
803            }
804
805            let layout = match hub.bind_group_layouts.get(desc.layout).get() {
806                Ok(layout) => layout,
807                Err(e) => break 'error e.into(),
808            };
809
810            fn resolve_entry<'a>(
811                e: &BindGroupEntry<'a>,
812                buffer_storage: &Storage<Fallible<resource::Buffer>>,
813                sampler_storage: &Storage<Fallible<resource::Sampler>>,
814                texture_view_storage: &Storage<Fallible<resource::TextureView>>,
815                tlas_storage: &Storage<Fallible<resource::Tlas>>,
816                external_texture_storage: &Storage<Fallible<resource::ExternalTexture>>,
817            ) -> Result<ResolvedBindGroupEntry<'a>, binding_model::CreateBindGroupError>
818            {
819                let resolve_buffer = |bb: &BufferBinding| {
820                    buffer_storage
821                        .get(bb.buffer)
822                        .get()
823                        .map(|buffer| ResolvedBufferBinding {
824                            buffer,
825                            offset: bb.offset,
826                            size: bb.size,
827                        })
828                        .map_err(binding_model::CreateBindGroupError::from)
829                };
830                let resolve_sampler = |id: &id::SamplerId| {
831                    sampler_storage
832                        .get(*id)
833                        .get()
834                        .map_err(binding_model::CreateBindGroupError::from)
835                };
836                let resolve_view = |id: &id::TextureViewId| {
837                    texture_view_storage
838                        .get(*id)
839                        .get()
840                        .map_err(binding_model::CreateBindGroupError::from)
841                };
842                let resolve_tlas = |id: &id::TlasId| {
843                    tlas_storage
844                        .get(*id)
845                        .get()
846                        .map_err(binding_model::CreateBindGroupError::from)
847                };
848                let resolve_external_texture = |id: &id::ExternalTextureId| {
849                    external_texture_storage
850                        .get(*id)
851                        .get()
852                        .map_err(binding_model::CreateBindGroupError::from)
853                };
854                let resource = match e.resource {
855                    BindingResource::Buffer(ref buffer) => {
856                        ResolvedBindingResource::Buffer(resolve_buffer(buffer)?)
857                    }
858                    BindingResource::BufferArray(ref buffers) => {
859                        let buffers = buffers
860                            .iter()
861                            .map(resolve_buffer)
862                            .collect::<Result<Vec<_>, _>>()?;
863                        ResolvedBindingResource::BufferArray(Cow::Owned(buffers))
864                    }
865                    BindingResource::Sampler(ref sampler) => {
866                        ResolvedBindingResource::Sampler(resolve_sampler(sampler)?)
867                    }
868                    BindingResource::SamplerArray(ref samplers) => {
869                        let samplers = samplers
870                            .iter()
871                            .map(resolve_sampler)
872                            .collect::<Result<Vec<_>, _>>()?;
873                        ResolvedBindingResource::SamplerArray(Cow::Owned(samplers))
874                    }
875                    BindingResource::TextureView(ref view) => {
876                        ResolvedBindingResource::TextureView(resolve_view(view)?)
877                    }
878                    BindingResource::TextureViewArray(ref views) => {
879                        let views = views
880                            .iter()
881                            .map(resolve_view)
882                            .collect::<Result<Vec<_>, _>>()?;
883                        ResolvedBindingResource::TextureViewArray(Cow::Owned(views))
884                    }
885                    BindingResource::AccelerationStructure(ref tlas) => {
886                        ResolvedBindingResource::AccelerationStructure(resolve_tlas(tlas)?)
887                    }
888                    BindingResource::ExternalTexture(ref et) => {
889                        ResolvedBindingResource::ExternalTexture(resolve_external_texture(et)?)
890                    }
891                };
892                Ok(ResolvedBindGroupEntry {
893                    binding: e.binding,
894                    resource,
895                })
896            }
897
898            let entries = {
899                let buffer_guard = hub.buffers.read();
900                let texture_view_guard = hub.texture_views.read();
901                let sampler_guard = hub.samplers.read();
902                let tlas_guard = hub.tlas_s.read();
903                let external_texture_guard = hub.external_textures.read();
904                desc.entries
905                    .iter()
906                    .map(|e| {
907                        resolve_entry(
908                            e,
909                            &buffer_guard,
910                            &sampler_guard,
911                            &texture_view_guard,
912                            &tlas_guard,
913                            &external_texture_guard,
914                        )
915                    })
916                    .collect::<Result<Vec<_>, _>>()
917            };
918            let entries = match entries {
919                Ok(entries) => Cow::Owned(entries),
920                Err(e) => break 'error e,
921            };
922
923            let desc = ResolvedBindGroupDescriptor {
924                label: desc.label.clone(),
925                layout,
926                entries,
927            };
928            #[cfg(feature = "trace")]
929            let trace_desc = (&desc).to_trace();
930
931            let bind_group = match device.create_bind_group(desc) {
932                Ok(bind_group) => bind_group,
933                Err(e) => break 'error e,
934            };
935
936            #[cfg(feature = "trace")]
937            if let Some(ref mut trace) = *device.trace.lock() {
938                trace.add(trace::Action::CreateBindGroup(
939                    bind_group.to_trace(),
940                    trace_desc,
941                ));
942            }
943
944            let id = fid.assign(Fallible::Valid(bind_group));
945
946            api_log!("Device::create_bind_group -> {id:?}");
947
948            return (id, None);
949        };
950
951        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
952        (id, Some(error))
953    }
954
955    pub fn bind_group_drop(&self, bind_group_id: id::BindGroupId) {
956        profiling::scope!("BindGroup::drop");
957        api_log!("BindGroup::drop {bind_group_id:?}");
958
959        let hub = &self.hub;
960
961        let _bind_group = hub.bind_groups.remove(bind_group_id);
962
963        #[cfg(feature = "trace")]
964        if let Ok(bind_group) = _bind_group.get() {
965            if let Some(t) = bind_group.device.trace.lock().as_mut() {
966                t.add(trace::Action::DestroyBindGroup(bind_group.to_trace()));
967            }
968        }
969    }
970
971    /// Create a shader module with the given `source`.
972    ///
973    /// <div class="warning">
974    // NOTE: Keep this in sync with `naga::front::wgsl::parse_str`!
975    // NOTE: Keep this in sync with `wgpu::Device::create_shader_module`!
976    ///
977    /// This function may consume a lot of stack space. Compiler-enforced limits for parsing
978    /// recursion exist; if shader compilation runs into them, it will return an error gracefully.
979    /// However, on some build profiles and platforms, the default stack size for a thread may be
980    /// exceeded before this limit is reached during parsing. Callers should ensure that there is
981    /// enough stack space for this, particularly if calls to this method are exposed to user
982    /// input.
983    ///
984    /// </div>
985    pub fn device_create_shader_module(
986        &self,
987        device_id: DeviceId,
988        desc: &pipeline::ShaderModuleDescriptor,
989        source: pipeline::ShaderModuleSource,
990        id_in: Option<id::ShaderModuleId>,
991    ) -> (
992        id::ShaderModuleId,
993        Option<pipeline::CreateShaderModuleError>,
994    ) {
995        profiling::scope!("Device::create_shader_module");
996
997        let hub = &self.hub;
998        let fid = hub.shader_modules.prepare(id_in);
999
1000        let error = 'error: {
1001            let device = self.hub.devices.get(device_id);
1002
1003            #[cfg(feature = "trace")]
1004            let data = device.trace.lock().as_mut().map(|trace| {
1005                use crate::device::trace::DataKind;
1006
1007                match source {
1008                    #[cfg(feature = "wgsl")]
1009                    pipeline::ShaderModuleSource::Wgsl(ref code) => {
1010                        trace.make_binary(DataKind::Wgsl, code.as_bytes())
1011                    }
1012                    #[cfg(feature = "glsl")]
1013                    pipeline::ShaderModuleSource::Glsl(ref code, _) => {
1014                        trace.make_binary(DataKind::Glsl, code.as_bytes())
1015                    }
1016                    #[cfg(feature = "spirv")]
1017                    pipeline::ShaderModuleSource::SpirV(ref code, _) => {
1018                        trace.make_binary(DataKind::Spv, bytemuck::cast_slice::<u32, u8>(code))
1019                    }
1020                    pipeline::ShaderModuleSource::Naga(ref module) => {
1021                        let string =
1022                            ron::ser::to_string_pretty(module, ron::ser::PrettyConfig::default())
1023                                .unwrap();
1024                        trace.make_binary(DataKind::Ron, string.as_bytes())
1025                    }
1026                    pipeline::ShaderModuleSource::Dummy(_) => {
1027                        panic!("found `ShaderModuleSource::Dummy`")
1028                    }
1029                }
1030            });
1031
1032            let shader = match device.create_shader_module(desc, source) {
1033                Ok(shader) => shader,
1034                Err(e) => break 'error e,
1035            };
1036
1037            #[cfg(feature = "trace")]
1038            if let Some(data) = data {
1039                // We don't need these two operations with the trace to be atomic.
1040                device
1041                    .trace
1042                    .lock()
1043                    .as_mut()
1044                    .expect("trace went away during create_shader_module?")
1045                    .add(trace::Action::CreateShaderModule {
1046                        id: shader.to_trace(),
1047                        desc: desc.clone(),
1048                        data,
1049                    });
1050            };
1051
1052            let id = fid.assign(Fallible::Valid(shader));
1053            api_log!("Device::create_shader_module -> {id:?}");
1054            return (id, None);
1055        };
1056
1057        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
1058        (id, Some(error))
1059    }
1060
1061    /// # Safety
1062    ///
1063    /// This function passes source code or binary to the backend as-is and can potentially result in a
1064    /// driver crash.
1065    pub unsafe fn device_create_shader_module_passthrough(
1066        &self,
1067        device_id: DeviceId,
1068        desc: &pipeline::ShaderModuleDescriptorPassthrough<'_>,
1069        id_in: Option<id::ShaderModuleId>,
1070    ) -> (
1071        id::ShaderModuleId,
1072        Option<pipeline::CreateShaderModuleError>,
1073    ) {
1074        profiling::scope!("Device::create_shader_module_passthrough");
1075
1076        let hub = &self.hub;
1077        let fid = hub.shader_modules.prepare(id_in);
1078
1079        let error = 'error: {
1080            let device = self.hub.devices.get(device_id);
1081
1082            let result = unsafe { device.create_shader_module_passthrough(desc) };
1083
1084            let shader = match result {
1085                Ok(shader) => shader,
1086                Err(e) => break 'error e,
1087            };
1088
1089            #[cfg(feature = "trace")]
1090            if let Some(ref mut trace) = *device.trace.lock() {
1091                use crate::device::trace::DataKind;
1092
1093                let mut file_names = Vec::new();
1094                for (data, kind) in [
1095                    (
1096                        desc.spirv.as_ref().map(|a| bytemuck::cast_slice(a)),
1097                        DataKind::Spv,
1098                    ),
1099                    (desc.dxil.as_deref(), DataKind::Dxil),
1100                    (desc.hlsl.as_ref().map(|a| a.as_bytes()), DataKind::Hlsl),
1101                    (desc.metallib.as_deref(), DataKind::MetalLib),
1102                    (desc.msl.as_ref().map(|a| a.as_bytes()), DataKind::Msl),
1103                    (desc.glsl.as_ref().map(|a| a.as_bytes()), DataKind::Glsl),
1104                    (desc.wgsl.as_ref().map(|a| a.as_bytes()), DataKind::Wgsl),
1105                ] {
1106                    if let Some(data) = data {
1107                        file_names.push(trace.make_binary(kind, data));
1108                    }
1109                }
1110                trace.add(trace::Action::CreateShaderModulePassthrough {
1111                    id: shader.to_trace(),
1112                    data: file_names,
1113                    label: desc.label.clone(),
1114                    num_workgroups: desc.num_workgroups,
1115                });
1116            };
1117
1118            let id = fid.assign(Fallible::Valid(shader));
1119            api_log!("Device::create_shader_module_spirv -> {id:?}");
1120            return (id, None);
1121        };
1122
1123        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
1124        (id, Some(error))
1125    }
1126
1127    pub fn shader_module_drop(&self, shader_module_id: id::ShaderModuleId) {
1128        profiling::scope!("ShaderModule::drop");
1129        api_log!("ShaderModule::drop {shader_module_id:?}");
1130
1131        let hub = &self.hub;
1132
1133        let _shader_module = hub.shader_modules.remove(shader_module_id);
1134
1135        #[cfg(feature = "trace")]
1136        if let Ok(shader_module) = _shader_module.get() {
1137            if let Some(t) = shader_module.device.trace.lock().as_mut() {
1138                t.add(trace::Action::DestroyShaderModule(shader_module.to_trace()));
1139            }
1140        }
1141    }
1142
1143    pub fn device_create_command_encoder(
1144        &self,
1145        device_id: DeviceId,
1146        desc: &wgt::CommandEncoderDescriptor<Label>,
1147        id_in: Option<id::CommandEncoderId>,
1148    ) -> (id::CommandEncoderId, Option<DeviceError>) {
1149        profiling::scope!("Device::create_command_encoder");
1150
1151        let hub = &self.hub;
1152        let fid = hub.command_encoders.prepare(id_in);
1153
1154        let device = self.hub.devices.get(device_id);
1155
1156        let error = 'error: {
1157            let cmd_enc = match device.create_command_encoder(&desc.label) {
1158                Ok(cmd_enc) => cmd_enc,
1159                Err(e) => break 'error e,
1160            };
1161
1162            let id = fid.assign(cmd_enc);
1163            api_log!("Device::create_command_encoder -> {id:?}");
1164            return (id, None);
1165        };
1166
1167        let id = fid.assign(Arc::new(CommandEncoder::new_invalid(
1168            &device,
1169            &desc.label,
1170            error.clone().into(),
1171        )));
1172        (id, Some(error))
1173    }
1174
1175    pub fn command_encoder_drop(&self, command_encoder_id: id::CommandEncoderId) {
1176        profiling::scope!("CommandEncoder::drop");
1177        api_log!("CommandEncoder::drop {command_encoder_id:?}");
1178        let _cmd_enc = self.hub.command_encoders.remove(command_encoder_id);
1179    }
1180
1181    pub fn command_buffer_drop(&self, command_buffer_id: id::CommandBufferId) {
1182        profiling::scope!("CommandBuffer::drop");
1183        api_log!("CommandBuffer::drop {command_buffer_id:?}");
1184        let _cmd_buf = self.hub.command_buffers.remove(command_buffer_id);
1185    }
1186
1187    pub fn device_create_render_bundle_encoder(
1188        &self,
1189        device_id: DeviceId,
1190        desc: &command::RenderBundleEncoderDescriptor,
1191    ) -> (
1192        *mut command::RenderBundleEncoder,
1193        Option<command::CreateRenderBundleError>,
1194    ) {
1195        profiling::scope!("Device::create_render_bundle_encoder");
1196        api_log!("Device::device_create_render_bundle_encoder");
1197        let (encoder, error) = match command::RenderBundleEncoder::new(desc, device_id) {
1198            Ok(encoder) => (encoder, None),
1199            Err(e) => (command::RenderBundleEncoder::dummy(device_id), Some(e)),
1200        };
1201        (Box::into_raw(Box::new(encoder)), error)
1202    }
1203
1204    pub fn render_bundle_encoder_finish(
1205        &self,
1206        bundle_encoder: command::RenderBundleEncoder,
1207        desc: &command::RenderBundleDescriptor,
1208        id_in: Option<id::RenderBundleId>,
1209    ) -> (id::RenderBundleId, Option<command::RenderBundleError>) {
1210        profiling::scope!("RenderBundleEncoder::finish");
1211
1212        let hub = &self.hub;
1213
1214        let fid = hub.render_bundles.prepare(id_in);
1215
1216        let error = 'error: {
1217            let device = self.hub.devices.get(bundle_encoder.parent());
1218
1219            #[cfg(feature = "trace")]
1220            let trace_desc = trace::new_render_bundle_encoder_descriptor(
1221                desc.label.clone(),
1222                &bundle_encoder.context,
1223                bundle_encoder.is_depth_read_only,
1224                bundle_encoder.is_stencil_read_only,
1225            );
1226
1227            let render_bundle = match bundle_encoder.finish(desc, &device, hub) {
1228                Ok(bundle) => bundle,
1229                Err(e) => break 'error e,
1230            };
1231
1232            #[cfg(feature = "trace")]
1233            if let Some(ref mut trace) = *device.trace.lock() {
1234                trace.add(trace::Action::CreateRenderBundle {
1235                    id: render_bundle.to_trace(),
1236                    desc: trace_desc,
1237                    base: render_bundle.to_base_pass().to_trace(),
1238                });
1239            }
1240
1241            let id = fid.assign(Fallible::Valid(render_bundle));
1242            api_log!("RenderBundleEncoder::finish -> {id:?}");
1243
1244            return (id, None);
1245        };
1246
1247        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
1248        (id, Some(error))
1249    }
1250
1251    pub fn render_bundle_drop(&self, render_bundle_id: id::RenderBundleId) {
1252        profiling::scope!("RenderBundle::drop");
1253        api_log!("RenderBundle::drop {render_bundle_id:?}");
1254
1255        let hub = &self.hub;
1256
1257        let _bundle = hub.render_bundles.remove(render_bundle_id);
1258
1259        #[cfg(feature = "trace")]
1260        if let Ok(bundle) = _bundle.get() {
1261            if let Some(t) = bundle.device.trace.lock().as_mut() {
1262                t.add(trace::Action::DestroyRenderBundle(bundle.to_trace()));
1263            }
1264        }
1265    }
1266
1267    pub fn device_create_query_set(
1268        &self,
1269        device_id: DeviceId,
1270        desc: &resource::QuerySetDescriptor,
1271        id_in: Option<id::QuerySetId>,
1272    ) -> (id::QuerySetId, Option<resource::CreateQuerySetError>) {
1273        profiling::scope!("Device::create_query_set");
1274
1275        let hub = &self.hub;
1276        let fid = hub.query_sets.prepare(id_in);
1277
1278        let error = 'error: {
1279            let device = self.hub.devices.get(device_id);
1280
1281            let query_set = match device.create_query_set(desc) {
1282                Ok(query_set) => query_set,
1283                Err(err) => break 'error err,
1284            };
1285
1286            #[cfg(feature = "trace")]
1287            if let Some(ref mut trace) = *device.trace.lock() {
1288                trace.add(trace::Action::CreateQuerySet {
1289                    id: query_set.to_trace(),
1290                    desc: desc.clone(),
1291                });
1292            }
1293
1294            let id = fid.assign(Fallible::Valid(query_set));
1295            api_log!("Device::create_query_set -> {id:?}");
1296
1297            return (id, None);
1298        };
1299
1300        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
1301        (id, Some(error))
1302    }
1303
1304    pub fn query_set_drop(&self, query_set_id: id::QuerySetId) {
1305        profiling::scope!("QuerySet::drop");
1306        api_log!("QuerySet::drop {query_set_id:?}");
1307
1308        let hub = &self.hub;
1309
1310        let _query_set = hub.query_sets.remove(query_set_id);
1311
1312        #[cfg(feature = "trace")]
1313        if let Ok(query_set) = _query_set.get() {
1314            if let Some(trace) = query_set.device.trace.lock().as_mut() {
1315                trace.add(trace::Action::DestroyQuerySet(query_set.to_trace()));
1316            }
1317        }
1318    }
1319
1320    pub fn device_create_render_pipeline(
1321        &self,
1322        device_id: DeviceId,
1323        desc: &pipeline::RenderPipelineDescriptor,
1324        id_in: Option<id::RenderPipelineId>,
1325    ) -> (
1326        id::RenderPipelineId,
1327        Option<pipeline::CreateRenderPipelineError>,
1328    ) {
1329        profiling::scope!("Device::create_render_pipeline");
1330
1331        let hub = &self.hub;
1332
1333        let fid = hub.render_pipelines.prepare(id_in);
1334
1335        let device = self.hub.devices.get(device_id);
1336
1337        self.device_create_general_render_pipeline(desc.clone().into(), device, fid)
1338    }
1339
1340    pub fn device_create_mesh_pipeline(
1341        &self,
1342        device_id: DeviceId,
1343        desc: &pipeline::MeshPipelineDescriptor,
1344        id_in: Option<id::RenderPipelineId>,
1345    ) -> (
1346        id::RenderPipelineId,
1347        Option<pipeline::CreateRenderPipelineError>,
1348    ) {
1349        let hub = &self.hub;
1350
1351        let fid = hub.render_pipelines.prepare(id_in);
1352
1353        let device = self.hub.devices.get(device_id);
1354        self.device_create_general_render_pipeline(desc.clone().into(), device, fid)
1355    }
1356
1357    fn device_create_general_render_pipeline(
1358        &self,
1359        desc: pipeline::GeneralRenderPipelineDescriptor,
1360        device: Arc<crate::device::resource::Device>,
1361        fid: crate::registry::FutureId<Fallible<pipeline::RenderPipeline>>,
1362    ) -> (
1363        id::RenderPipelineId,
1364        Option<pipeline::CreateRenderPipelineError>,
1365    ) {
1366        profiling::scope!("Device::create_general_render_pipeline");
1367
1368        let hub = &self.hub;
1369
1370        let error = 'error: {
1371            if let Err(e) = device.check_is_valid() {
1372                break 'error e.into();
1373            }
1374
1375            let layout = desc
1376                .layout
1377                .map(|layout| hub.pipeline_layouts.get(layout).get())
1378                .transpose();
1379            let layout = match layout {
1380                Ok(layout) => layout,
1381                Err(e) => break 'error e.into(),
1382            };
1383
1384            let cache = desc
1385                .cache
1386                .map(|cache| hub.pipeline_caches.get(cache).get())
1387                .transpose();
1388            let cache = match cache {
1389                Ok(cache) => cache,
1390                Err(e) => break 'error e.into(),
1391            };
1392            let mut passthrough_stages = wgt::ShaderStages::empty();
1393
1394            let vertex = match desc.vertex {
1395                RenderPipelineVertexProcessor::Vertex(ref vertex) => {
1396                    let module = hub
1397                        .shader_modules
1398                        .get(vertex.stage.module)
1399                        .get()
1400                        .map_err(|e| pipeline::CreateRenderPipelineError::Stage {
1401                            stage: wgt::ShaderStages::VERTEX,
1402                            error: e.into(),
1403                        });
1404                    let module = match module {
1405                        Ok(module) => module,
1406                        Err(e) => break 'error e,
1407                    };
1408                    if module.interface.is_none() {
1409                        passthrough_stages |= wgt::ShaderStages::VERTEX;
1410                    }
1411                    let stage = ResolvedProgrammableStageDescriptor {
1412                        module,
1413                        entry_point: vertex.stage.entry_point.clone(),
1414                        constants: vertex.stage.constants.clone(),
1415                        zero_initialize_workgroup_memory: vertex
1416                            .stage
1417                            .zero_initialize_workgroup_memory,
1418                    };
1419                    RenderPipelineVertexProcessor::Vertex(ResolvedVertexState {
1420                        stage,
1421                        buffers: vertex.buffers.clone(),
1422                    })
1423                }
1424                RenderPipelineVertexProcessor::Mesh(ref task, ref mesh) => {
1425                    let task_module = if let Some(task) = task {
1426                        let module = hub
1427                            .shader_modules
1428                            .get(task.stage.module)
1429                            .get()
1430                            .map_err(|e| pipeline::CreateRenderPipelineError::Stage {
1431                                stage: wgt::ShaderStages::VERTEX,
1432                                error: e.into(),
1433                            });
1434                        let module = match module {
1435                            Ok(module) => module,
1436                            Err(e) => break 'error e,
1437                        };
1438                        if module.interface.is_none() {
1439                            passthrough_stages |= wgt::ShaderStages::TASK;
1440                        }
1441                        let state = ResolvedProgrammableStageDescriptor {
1442                            module,
1443                            entry_point: task.stage.entry_point.clone(),
1444                            constants: task.stage.constants.clone(),
1445                            zero_initialize_workgroup_memory: task
1446                                .stage
1447                                .zero_initialize_workgroup_memory,
1448                        };
1449                        Some(ResolvedTaskState { stage: state })
1450                    } else {
1451                        None
1452                    };
1453                    let mesh_module =
1454                        hub.shader_modules
1455                            .get(mesh.stage.module)
1456                            .get()
1457                            .map_err(|e| pipeline::CreateRenderPipelineError::Stage {
1458                                stage: wgt::ShaderStages::MESH,
1459                                error: e.into(),
1460                            });
1461                    let mesh_module = match mesh_module {
1462                        Ok(module) => module,
1463                        Err(e) => break 'error e,
1464                    };
1465                    if mesh_module.interface.is_none() {
1466                        passthrough_stages |= wgt::ShaderStages::VERTEX;
1467                    }
1468                    let mesh_stage = ResolvedProgrammableStageDescriptor {
1469                        module: mesh_module,
1470                        entry_point: mesh.stage.entry_point.clone(),
1471                        constants: mesh.stage.constants.clone(),
1472                        zero_initialize_workgroup_memory: mesh
1473                            .stage
1474                            .zero_initialize_workgroup_memory,
1475                    };
1476                    RenderPipelineVertexProcessor::Mesh(
1477                        task_module,
1478                        ResolvedMeshState { stage: mesh_stage },
1479                    )
1480                }
1481            };
1482
1483            let fragment = if let Some(ref state) = desc.fragment {
1484                let module = hub
1485                    .shader_modules
1486                    .get(state.stage.module)
1487                    .get()
1488                    .map_err(|e| pipeline::CreateRenderPipelineError::Stage {
1489                        stage: wgt::ShaderStages::FRAGMENT,
1490                        error: e.into(),
1491                    });
1492                let module = match module {
1493                    Ok(module) => module,
1494                    Err(e) => break 'error e,
1495                };
1496                if module.interface.is_none() {
1497                    passthrough_stages |= wgt::ShaderStages::FRAGMENT;
1498                }
1499                let stage = ResolvedProgrammableStageDescriptor {
1500                    module,
1501                    entry_point: state.stage.entry_point.clone(),
1502                    constants: state.stage.constants.clone(),
1503                    zero_initialize_workgroup_memory: state.stage.zero_initialize_workgroup_memory,
1504                };
1505                Some(ResolvedFragmentState {
1506                    stage,
1507                    targets: state.targets.clone(),
1508                })
1509            } else {
1510                None
1511            };
1512
1513            if !passthrough_stages.is_empty() && layout.is_none() {
1514                break 'error pipeline::CreateRenderPipelineError::Implicit(
1515                    pipeline::ImplicitLayoutError::Passthrough(passthrough_stages),
1516                );
1517            }
1518
1519            let desc = ResolvedGeneralRenderPipelineDescriptor {
1520                label: desc.label.clone(),
1521                layout,
1522                vertex,
1523                primitive: desc.primitive,
1524                depth_stencil: desc.depth_stencil.clone(),
1525                multisample: desc.multisample,
1526                fragment,
1527                multiview_mask: desc.multiview_mask,
1528                cache,
1529            };
1530
1531            #[cfg(feature = "trace")]
1532            let trace_desc = desc.clone().into_trace();
1533
1534            let pipeline = match device.create_render_pipeline(desc) {
1535                Ok(pair) => pair,
1536                Err(e) => break 'error e,
1537            };
1538
1539            #[cfg(feature = "trace")]
1540            if let Some(ref mut trace) = *device.trace.lock() {
1541                trace.add(trace::Action::CreateGeneralRenderPipeline {
1542                    id: pipeline.to_trace(),
1543                    desc: trace_desc,
1544                });
1545            }
1546
1547            let id = fid.assign(Fallible::Valid(pipeline));
1548            api_log!("Device::create_render_pipeline -> {id:?}");
1549
1550            return (id, None);
1551        };
1552
1553        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
1554
1555        (id, Some(error))
1556    }
1557
1558    /// Get an ID of one of the bind group layouts. The ID adds a refcount,
1559    /// which needs to be released by calling `bind_group_layout_drop`.
1560    pub fn render_pipeline_get_bind_group_layout(
1561        &self,
1562        pipeline_id: id::RenderPipelineId,
1563        index: u32,
1564        id_in: Option<id::BindGroupLayoutId>,
1565    ) -> (
1566        id::BindGroupLayoutId,
1567        Option<binding_model::GetBindGroupLayoutError>,
1568    ) {
1569        let hub = &self.hub;
1570
1571        let fid = hub.bind_group_layouts.prepare(id_in);
1572
1573        let error = 'error: {
1574            let pipeline = match hub.render_pipelines.get(pipeline_id).get() {
1575                Ok(pipeline) => pipeline,
1576                Err(e) => break 'error e.into(),
1577            };
1578            match pipeline.get_bind_group_layout(index) {
1579                Ok(bgl) => {
1580                    #[cfg(feature = "trace")]
1581                    if let Some(ref mut trace) = *pipeline.device.trace.lock() {
1582                        trace.add(trace::Action::GetRenderPipelineBindGroupLayout {
1583                            id: bgl.to_trace(),
1584                            pipeline: pipeline.to_trace(),
1585                            index,
1586                        });
1587                    }
1588
1589                    let id = fid.assign(Fallible::Valid(bgl.clone()));
1590                    return (id, None);
1591                }
1592                Err(err) => break 'error err,
1593            };
1594        };
1595
1596        let id = fid.assign(Fallible::Invalid(Arc::new(String::new())));
1597        (id, Some(error))
1598    }
1599
1600    pub fn render_pipeline_drop(&self, render_pipeline_id: id::RenderPipelineId) {
1601        profiling::scope!("RenderPipeline::drop");
1602        api_log!("RenderPipeline::drop {render_pipeline_id:?}");
1603
1604        let hub = &self.hub;
1605
1606        let _pipeline = hub.render_pipelines.remove(render_pipeline_id);
1607
1608        #[cfg(feature = "trace")]
1609        if let Ok(pipeline) = _pipeline.get() {
1610            if let Some(t) = pipeline.device.trace.lock().as_mut() {
1611                t.add(trace::Action::DestroyRenderPipeline(pipeline.to_trace()));
1612            }
1613        }
1614    }
1615
1616    pub fn device_create_compute_pipeline(
1617        &self,
1618        device_id: DeviceId,
1619        desc: &pipeline::ComputePipelineDescriptor,
1620        id_in: Option<id::ComputePipelineId>,
1621    ) -> (
1622        id::ComputePipelineId,
1623        Option<pipeline::CreateComputePipelineError>,
1624    ) {
1625        profiling::scope!("Device::create_compute_pipeline");
1626
1627        let hub = &self.hub;
1628
1629        let fid = hub.compute_pipelines.prepare(id_in);
1630
1631        let error = 'error: {
1632            let device = self.hub.devices.get(device_id);
1633
1634            if let Err(e) = device.check_is_valid() {
1635                break 'error e.into();
1636            }
1637
1638            let layout = desc
1639                .layout
1640                .map(|layout| hub.pipeline_layouts.get(layout).get())
1641                .transpose();
1642            let layout = match layout {
1643                Ok(layout) => layout,
1644                Err(e) => break 'error e.into(),
1645            };
1646
1647            let cache = desc
1648                .cache
1649                .map(|cache| hub.pipeline_caches.get(cache).get())
1650                .transpose();
1651            let cache = match cache {
1652                Ok(cache) => cache,
1653                Err(e) => break 'error e.into(),
1654            };
1655
1656            let module = hub.shader_modules.get(desc.stage.module).get();
1657            let module = match module {
1658                Ok(module) => module,
1659                Err(e) => break 'error e.into(),
1660            };
1661            if module.interface.is_none() && layout.is_none() {
1662                break 'error pipeline::CreateComputePipelineError::Implicit(
1663                    pipeline::ImplicitLayoutError::Passthrough(wgt::ShaderStages::COMPUTE),
1664                );
1665            }
1666            let stage = ResolvedProgrammableStageDescriptor {
1667                module,
1668                entry_point: desc.stage.entry_point.clone(),
1669                constants: desc.stage.constants.clone(),
1670                zero_initialize_workgroup_memory: desc.stage.zero_initialize_workgroup_memory,
1671            };
1672
1673            let desc = ResolvedComputePipelineDescriptor {
1674                label: desc.label.clone(),
1675                layout,
1676                stage,
1677                cache,
1678            };
1679
1680            #[cfg(feature = "trace")]
1681            let trace_desc = desc.clone().into_trace();
1682
1683            let pipeline = match device.create_compute_pipeline(desc) {
1684                Ok(pair) => pair,
1685                Err(e) => break 'error e,
1686            };
1687
1688            #[cfg(feature = "trace")]
1689            if let Some(ref mut trace) = *device.trace.lock() {
1690                trace.add(trace::Action::CreateComputePipeline {
1691                    id: pipeline.to_trace(),
1692                    desc: trace_desc,
1693                });
1694            }
1695
1696            let id = fid.assign(Fallible::Valid(pipeline));
1697            api_log!("Device::create_compute_pipeline -> {id:?}");
1698
1699            return (id, None);
1700        };
1701
1702        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
1703
1704        (id, Some(error))
1705    }
1706
1707    /// Get an ID of one of the bind group layouts. The ID adds a refcount,
1708    /// which needs to be released by calling `bind_group_layout_drop`.
1709    pub fn compute_pipeline_get_bind_group_layout(
1710        &self,
1711        pipeline_id: id::ComputePipelineId,
1712        index: u32,
1713        id_in: Option<id::BindGroupLayoutId>,
1714    ) -> (
1715        id::BindGroupLayoutId,
1716        Option<binding_model::GetBindGroupLayoutError>,
1717    ) {
1718        let hub = &self.hub;
1719
1720        let fid = hub.bind_group_layouts.prepare(id_in);
1721
1722        let error = 'error: {
1723            let pipeline = match hub.compute_pipelines.get(pipeline_id).get() {
1724                Ok(pipeline) => pipeline,
1725                Err(e) => break 'error e.into(),
1726            };
1727
1728            match pipeline.get_bind_group_layout(index) {
1729                Ok(bgl) => {
1730                    #[cfg(feature = "trace")]
1731                    if let Some(ref mut trace) = *pipeline.device.trace.lock() {
1732                        trace.add(trace::Action::GetComputePipelineBindGroupLayout {
1733                            id: bgl.to_trace(),
1734                            pipeline: pipeline.to_trace(),
1735                            index,
1736                        });
1737                    }
1738
1739                    let id = fid.assign(Fallible::Valid(bgl.clone()));
1740                    return (id, None);
1741                }
1742                Err(err) => break 'error err,
1743            };
1744        };
1745
1746        let id = fid.assign(Fallible::Invalid(Arc::new(String::new())));
1747        (id, Some(error))
1748    }
1749
1750    pub fn compute_pipeline_drop(&self, compute_pipeline_id: id::ComputePipelineId) {
1751        profiling::scope!("ComputePipeline::drop");
1752        api_log!("ComputePipeline::drop {compute_pipeline_id:?}");
1753
1754        let hub = &self.hub;
1755
1756        let _pipeline = hub.compute_pipelines.remove(compute_pipeline_id);
1757
1758        #[cfg(feature = "trace")]
1759        if let Ok(pipeline) = _pipeline.get() {
1760            if let Some(t) = pipeline.device.trace.lock().as_mut() {
1761                t.add(trace::Action::DestroyComputePipeline(pipeline.to_trace()));
1762            }
1763        }
1764    }
1765
1766    /// # Safety
1767    /// The `data` argument of `desc` must have been returned by
1768    /// [Self::pipeline_cache_get_data] for the same adapter
1769    pub unsafe fn device_create_pipeline_cache(
1770        &self,
1771        device_id: DeviceId,
1772        desc: &pipeline::PipelineCacheDescriptor<'_>,
1773        id_in: Option<id::PipelineCacheId>,
1774    ) -> (
1775        id::PipelineCacheId,
1776        Option<pipeline::CreatePipelineCacheError>,
1777    ) {
1778        profiling::scope!("Device::create_pipeline_cache");
1779
1780        let hub = &self.hub;
1781
1782        let fid = hub.pipeline_caches.prepare(id_in);
1783        let error: pipeline::CreatePipelineCacheError = 'error: {
1784            let device = self.hub.devices.get(device_id);
1785
1786            let cache = unsafe { device.create_pipeline_cache(desc) };
1787            match cache {
1788                Ok(cache) => {
1789                    #[cfg(feature = "trace")]
1790                    if let Some(ref mut trace) = *device.trace.lock() {
1791                        trace.add(trace::Action::CreatePipelineCache {
1792                            id: cache.to_trace(),
1793                            desc: desc.clone(),
1794                        });
1795                    }
1796
1797                    let id = fid.assign(Fallible::Valid(cache));
1798                    api_log!("Device::create_pipeline_cache -> {id:?}");
1799                    return (id, None);
1800                }
1801                Err(e) => break 'error e,
1802            }
1803        };
1804
1805        let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string())));
1806
1807        (id, Some(error))
1808    }
1809
1810    pub fn pipeline_cache_drop(&self, pipeline_cache_id: id::PipelineCacheId) {
1811        profiling::scope!("PipelineCache::drop");
1812        api_log!("PipelineCache::drop {pipeline_cache_id:?}");
1813
1814        let hub = &self.hub;
1815
1816        let _cache = hub.pipeline_caches.remove(pipeline_cache_id);
1817
1818        #[cfg(feature = "trace")]
1819        if let Ok(cache) = _cache.get() {
1820            if let Some(t) = cache.device.trace.lock().as_mut() {
1821                t.add(trace::Action::DestroyPipelineCache(cache.to_trace()));
1822            }
1823        }
1824    }
1825
1826    pub fn surface_configure(
1827        &self,
1828        surface_id: SurfaceId,
1829        device_id: DeviceId,
1830        config: &wgt::SurfaceConfiguration<Vec<TextureFormat>>,
1831    ) -> Option<present::ConfigureSurfaceError> {
1832        let device = self.hub.devices.get(device_id);
1833        let surface = self.surfaces.get(surface_id);
1834
1835        #[cfg(feature = "trace")]
1836        if let Some(ref mut trace) = *device.trace.lock() {
1837            trace.add(trace::Action::ConfigureSurface(
1838                surface.to_trace(),
1839                config.clone(),
1840            ));
1841        }
1842
1843        device.configure_surface(&surface, config)
1844    }
1845
1846    /// Check `device_id` for freeable resources and completed buffer mappings.
1847    ///
1848    /// Return `queue_empty` indicating whether there are more queue submissions still in flight.
1849    pub fn device_poll(
1850        &self,
1851        device_id: DeviceId,
1852        poll_type: wgt::PollType<crate::SubmissionIndex>,
1853    ) -> Result<wgt::PollStatus, WaitIdleError> {
1854        api_log!("Device::poll {poll_type:?}");
1855
1856        let device = self.hub.devices.get(device_id);
1857
1858        let (closures, result) = device.poll_and_return_closures(poll_type);
1859
1860        closures.fire();
1861
1862        result
1863    }
1864
1865    /// Poll all devices belonging to the specified backend.
1866    ///
1867    /// If `force_wait` is true, block until all buffer mappings are done.
1868    ///
1869    /// Return `all_queue_empty` indicating whether there are more queue
1870    /// submissions still in flight.
1871    fn poll_all_devices_of_api(
1872        &self,
1873        force_wait: bool,
1874        closure_list: &mut UserClosures,
1875    ) -> Result<bool, WaitIdleError> {
1876        profiling::scope!("poll_device");
1877
1878        let hub = &self.hub;
1879        let mut all_queue_empty = true;
1880        {
1881            let device_guard = hub.devices.read();
1882
1883            for (_id, device) in device_guard.iter() {
1884                let poll_type = if force_wait {
1885                    // TODO(#8286): Should expose timeout to poll_all.
1886                    wgt::PollType::wait_indefinitely()
1887                } else {
1888                    wgt::PollType::Poll
1889                };
1890
1891                let (closures, result) = device.poll_and_return_closures(poll_type);
1892
1893                let is_queue_empty = matches!(result, Ok(wgt::PollStatus::QueueEmpty));
1894
1895                all_queue_empty &= is_queue_empty;
1896
1897                closure_list.extend(closures);
1898            }
1899        }
1900
1901        Ok(all_queue_empty)
1902    }
1903
1904    /// Poll all devices on all backends.
1905    ///
1906    /// This is the implementation of `wgpu::Instance::poll_all`.
1907    ///
1908    /// Return `all_queue_empty` indicating whether there are more queue
1909    /// submissions still in flight.
1910    pub fn poll_all_devices(&self, force_wait: bool) -> Result<bool, WaitIdleError> {
1911        api_log!("poll_all_devices");
1912        let mut closures = UserClosures::default();
1913        let all_queue_empty = self.poll_all_devices_of_api(force_wait, &mut closures)?;
1914
1915        closures.fire();
1916
1917        Ok(all_queue_empty)
1918    }
1919
1920    /// # Safety
1921    ///
1922    /// - See [wgpu::Device::start_graphics_debugger_capture][api] for details the safety.
1923    ///
1924    /// [api]: ../../wgpu/struct.Device.html#method.start_graphics_debugger_capture
1925    pub unsafe fn device_start_graphics_debugger_capture(&self, device_id: DeviceId) {
1926        unsafe {
1927            self.hub
1928                .devices
1929                .get(device_id)
1930                .start_graphics_debugger_capture();
1931        }
1932    }
1933
1934    /// # Safety
1935    ///
1936    /// - See [wgpu::Device::stop_graphics_debugger_capture][api] for details the safety.
1937    ///
1938    /// [api]: ../../wgpu/struct.Device.html#method.stop_graphics_debugger_capture
1939    pub unsafe fn device_stop_graphics_debugger_capture(&self, device_id: DeviceId) {
1940        unsafe {
1941            self.hub
1942                .devices
1943                .get(device_id)
1944                .stop_graphics_debugger_capture();
1945        }
1946    }
1947
1948    pub fn pipeline_cache_get_data(&self, id: id::PipelineCacheId) -> Option<Vec<u8>> {
1949        use crate::pipeline_cache;
1950        api_log!("PipelineCache::get_data");
1951        let hub = &self.hub;
1952
1953        if let Ok(cache) = hub.pipeline_caches.get(id).get() {
1954            // TODO: Is this check needed?
1955            if !cache.device.is_valid() {
1956                return None;
1957            }
1958            let mut vec = unsafe { cache.device.raw().pipeline_cache_get_data(cache.raw()) }?;
1959            let validation_key = cache.device.raw().pipeline_cache_validation_key()?;
1960
1961            let mut header_contents = [0; pipeline_cache::HEADER_LENGTH];
1962            pipeline_cache::add_cache_header(
1963                &mut header_contents,
1964                &vec,
1965                &cache.device.adapter.raw.info,
1966                validation_key,
1967            );
1968
1969            let deleted = vec.splice(..0, header_contents).collect::<Vec<_>>();
1970            debug_assert!(deleted.is_empty());
1971
1972            return Some(vec);
1973        }
1974        None
1975    }
1976
1977    pub fn device_drop(&self, device_id: DeviceId) {
1978        profiling::scope!("Device::drop");
1979        api_log!("Device::drop {device_id:?}");
1980
1981        self.hub.devices.remove(device_id);
1982    }
1983
1984    /// `device_lost_closure` might never be called.
1985    pub fn device_set_device_lost_closure(
1986        &self,
1987        device_id: DeviceId,
1988        device_lost_closure: DeviceLostClosure,
1989    ) {
1990        let device = self.hub.devices.get(device_id);
1991
1992        device
1993            .device_lost_closure
1994            .lock()
1995            .replace(device_lost_closure);
1996    }
1997
1998    pub fn device_destroy(&self, device_id: DeviceId) {
1999        api_log!("Device::destroy {device_id:?}");
2000
2001        let device = self.hub.devices.get(device_id);
2002
2003        // Follow the steps at
2004        // https://gpuweb.github.io/gpuweb/#dom-gpudevice-destroy.
2005        // It's legal to call destroy multiple times, but if the device
2006        // is already invalid, there's nothing more to do. There's also
2007        // no need to return an error.
2008        if !device.is_valid() {
2009            return;
2010        }
2011
2012        // The last part of destroy is to lose the device. The spec says
2013        // delay that until all "currently-enqueued operations on any
2014        // queue on this device are completed." This is accomplished by
2015        // setting valid to false, and then relying upon maintain to
2016        // check for empty queues and a DeviceLostClosure. At that time,
2017        // the DeviceLostClosure will be called with "destroyed" as the
2018        // reason.
2019        device.valid.store(false, Ordering::Release);
2020    }
2021
2022    pub fn device_get_internal_counters(&self, device_id: DeviceId) -> wgt::InternalCounters {
2023        let device = self.hub.devices.get(device_id);
2024        wgt::InternalCounters {
2025            hal: device.get_hal_counters(),
2026            core: wgt::CoreCounters {},
2027        }
2028    }
2029
2030    pub fn device_generate_allocator_report(
2031        &self,
2032        device_id: DeviceId,
2033    ) -> Option<wgt::AllocatorReport> {
2034        let device = self.hub.devices.get(device_id);
2035        device.generate_allocator_report()
2036    }
2037
2038    #[cfg(feature = "trace")]
2039    pub fn device_take_trace(
2040        &self,
2041        device_id: DeviceId,
2042    ) -> Option<Box<dyn trace::Trace + Send + Sync + 'static>> {
2043        let device = self.hub.devices.get(device_id);
2044        device.take_trace()
2045    }
2046
2047    pub fn queue_drop(&self, queue_id: QueueId) {
2048        profiling::scope!("Queue::drop");
2049        api_log!("Queue::drop {queue_id:?}");
2050
2051        self.hub.queues.remove(queue_id);
2052    }
2053
2054    /// `op.callback` is guaranteed to be called.
2055    pub fn buffer_map_async(
2056        &self,
2057        buffer_id: id::BufferId,
2058        offset: BufferAddress,
2059        size: Option<BufferAddress>,
2060        op: BufferMapOperation,
2061    ) -> Result<crate::SubmissionIndex, BufferAccessError> {
2062        profiling::scope!("Buffer::map_async");
2063        api_log!("Buffer::map_async {buffer_id:?} offset {offset:?} size {size:?} op: {op:?}");
2064
2065        let hub = &self.hub;
2066
2067        let map_result = match hub.buffers.get(buffer_id).get() {
2068            Ok(buffer) => buffer.map_async(offset, size, op),
2069            Err(e) => Err((op, e.into())),
2070        };
2071
2072        match map_result {
2073            Ok(submission_index) => Ok(submission_index),
2074            Err((mut operation, err)) => {
2075                if let Some(callback) = operation.callback.take() {
2076                    callback(Err(err.clone()));
2077                }
2078                Err(err)
2079            }
2080        }
2081    }
2082
2083    pub fn buffer_get_mapped_range(
2084        &self,
2085        buffer_id: id::BufferId,
2086        offset: BufferAddress,
2087        size: Option<BufferAddress>,
2088    ) -> Result<(NonNull<u8>, u64), BufferAccessError> {
2089        profiling::scope!("Buffer::get_mapped_range");
2090        api_log!("Buffer::get_mapped_range {buffer_id:?} offset {offset:?} size {size:?}");
2091
2092        let hub = &self.hub;
2093
2094        let buffer = hub.buffers.get(buffer_id).get()?;
2095
2096        buffer.get_mapped_range(offset, size)
2097    }
2098
2099    pub fn buffer_unmap(&self, buffer_id: id::BufferId) -> BufferAccessResult {
2100        profiling::scope!("unmap", "Buffer");
2101        api_log!("Buffer::unmap {buffer_id:?}");
2102
2103        let hub = &self.hub;
2104
2105        let buffer = hub.buffers.get(buffer_id).get()?;
2106
2107        let snatch_guard = buffer.device.snatchable_lock.read();
2108        buffer.check_destroyed(&snatch_guard)?;
2109        drop(snatch_guard);
2110
2111        buffer.device.check_is_valid()?;
2112        buffer.unmap()
2113    }
2114}