Debian Codegraph @

third_party/rust/wgpu-core/src/hub.rs

raw
1 /*! Allocating resource ids, and tracking the resources they refer to.
2
3 The `wgpu_core` API uses identifiers of type [`Id<R>`] to refer to
4 resources of type `R`. For example, [`id::DeviceId`] is an alias for
5 `Id<markers::Device>`, and [`id::BufferId`] is an alias for
6 `Id<markers::Buffer>`. `Id` implements `Copy`, `Hash`, `Eq`, `Ord`, and
7 of course `Debug`.
8
9 [`id::DeviceId`]: crate::id::DeviceId
10 [`id::BufferId`]: crate::id::BufferId
11
12 Each `Id` contains not only an index for the resource it denotes but
13 also a Backend indicating which `wgpu` backend it belongs to.
14
15 `Id`s also incorporate a generation number, for additional validation.
16
17 The resources to which identifiers refer are freed explicitly.
18 Attempting to use an identifier for a resource that has been freed
19 elicits an error result.
20
21 ## Assigning ids to resources
22
23 The users of `wgpu_core` generally want resource ids to be assigned
24 in one of two ways:
25
26 - Users like `wgpu` want `wgpu_core` to assign ids to resources itself.
27 For example, `wgpu` expects to call `Global::device_create_buffer`
28 and have the return value indicate the newly created buffer's id.
29
30 - Users like `player` and Firefox want to allocate ids themselves, and
31 pass `Global::device_create_buffer` and friends the id to assign the
32 new resource.
33
34 To accommodate either pattern, `wgpu_core` methods that create
35 resources all expect an `id_in` argument that the caller can use to
36 specify the id, and they all return the id used. For example, the
37 declaration of `Global::device_create_buffer` looks like this:
38
39 ```ignore
40 impl Global {
41 /* ... */
42 pub fn device_create_buffer<A: HalApi>(
43 &self,
44 device_id: id::DeviceId,
45 desc: &resource::BufferDescriptor,
46 id_in: Input<G>,
47 ) -> (id::BufferId, Option<resource::CreateBufferError>) {
48 /* ... */
49 }
50 /* ... */
51 }
52 ```
53
54 Users that want to assign resource ids themselves pass in the id they
55 want as the `id_in` argument, whereas users that want `wgpu_core`
56 itself to choose ids always pass `()`. In either case, the id
57 ultimately assigned is returned as the first element of the tuple.
58
59 Producing true identifiers from `id_in` values is the job of an
60 [`crate::identity::IdentityManager`] or ids will be received from outside through `Option<Id>` arguments.
61
62 ## Id allocation and streaming
63
64 Perhaps surprisingly, allowing users to assign resource ids themselves
65 enables major performance improvements in some applications.
66
67 The `wgpu_core` API is designed for use by Firefox's [WebGPU]
68 implementation. For security, web content and GPU use must be kept
69 segregated in separate processes, with all interaction between them
70 mediated by an inter-process communication protocol. As web content uses
71 the WebGPU API, the content process sends messages to the GPU process,
72 which interacts with the platform's GPU APIs on content's behalf,
73 occasionally sending results back.
74
75 In a classic Rust API, a resource allocation function takes parameters
76 describing the resource to create, and if creation succeeds, it returns
77 the resource id in a `Result::Ok` value. However, this design is a poor
78 fit for the split-process design described above: content must wait for
79 the reply to its buffer-creation message (say) before it can know which
80 id it can use in the next message that uses that buffer. On a common
81 usage pattern, the classic Rust design imposes the latency of a full
82 cross-process round trip.
83
84 We can avoid incurring these round-trip latencies simply by letting the
85 content process assign resource ids itself. With this approach, content
86 can choose an id for the new buffer, send a message to create the
87 buffer, and then immediately send the next message operating on that
88 buffer, since it already knows its id. Allowing content and GPU process
89 activity to be pipelined greatly improves throughput.
90
91 To help propagate errors correctly in this style of usage, when resource
92 creation fails, the id supplied for that resource is marked to indicate
93 as much, allowing subsequent operations using that id to be properly
94 flagged as errors as well.
95
96 [`process`]: crate::identity::IdentityManager::process
97 [`Id<R>`]: crate::id::Id
98 [wrapped in a mutex]: trait.IdentityHandler.html#impl-IdentityHandler%3CI%3E-for-Mutex%3CIdentityManager%3E
99 [WebGPU]: https://www.w3.org/TR/webgpu/
100
101 */
102
103 use alloc::sync::Arc;
104 use core::fmt::Debug;
105
106 use crate::{
107 binding_model::{BindGroup, BindGroupLayout, PipelineLayout},
108 command::{CommandBuffer, RenderBundle},
109 device::{queue::Queue, Device},
110 instance::Adapter,
111 pipeline::{ComputePipeline, PipelineCache, RenderPipeline, ShaderModule},
112 registry::{Registry, RegistryReport},
113 resource::{
114 Blas, Buffer, Fallible, QuerySet, Sampler, StagingBuffer, Texture, TextureView, Tlas,
115 },
116 };
117
118 #[derive(Debug, PartialEq, Eq)]
119 pub struct HubReport {
120 pub adapters: RegistryReport,
121 pub devices: RegistryReport,
122 pub queues: RegistryReport,
123 pub pipeline_layouts: RegistryReport,
124 pub shader_modules: RegistryReport,
125 pub bind_group_layouts: RegistryReport,
126 pub bind_groups: RegistryReport,
127 pub command_buffers: RegistryReport,
128 pub render_bundles: RegistryReport,
129 pub render_pipelines: RegistryReport,
130 pub compute_pipelines: RegistryReport,
131 pub pipeline_caches: RegistryReport,
132 pub query_sets: RegistryReport,
133 pub buffers: RegistryReport,
134 pub textures: RegistryReport,
135 pub texture_views: RegistryReport,
136 pub samplers: RegistryReport,
137 }
138
139 impl HubReport {
140 pub fn is_empty(&self) -> bool {
141 self.adapters.is_empty()
142 }
143 }
144
145 #[allow(rustdoc::private_intra_doc_links)]
146 /// All the resources tracked by a [`crate::global::Global`].
147 ///
148 /// ## Locking
149 ///
150 /// Each field in `Hub` is a [`Registry`] holding all the values of a
151 /// particular type of resource, all protected by a single RwLock.
152 /// So for example, to access any [`Buffer`], you must acquire a read
153 /// lock on the `Hub`s entire buffers registry. The lock guard
154 /// gives you access to the `Registry`'s [`Storage`], which you can
155 /// then index with the buffer's id. (Yes, this design causes
156 /// contention; see [#2272].)
157 ///
158 /// But most `wgpu` operations require access to several different
159 /// kinds of resource, so you often need to hold locks on several
160 /// different fields of your [`Hub`] simultaneously.
161 ///
162 /// Inside the `Registry` there are `Arc<T>` where `T` is a Resource
163 /// Lock of `Registry` happens only when accessing to get the specific resource
164 ///
165 /// [`Storage`]: crate::storage::Storage
166 pub struct Hub {
167 pub(crate) adapters: Registry<Arc<Adapter>>,
168 pub(crate) devices: Registry<Arc<Device>>,
169 pub(crate) queues: Registry<Arc<Queue>>,
170 pub(crate) pipeline_layouts: Registry<Fallible<PipelineLayout>>,
171 pub(crate) shader_modules: Registry<Fallible<ShaderModule>>,
172 pub(crate) bind_group_layouts: Registry<Fallible<BindGroupLayout>>,
173 pub(crate) bind_groups: Registry<Fallible<BindGroup>>,
174 pub(crate) command_buffers: Registry<Arc<CommandBuffer>>,
175 pub(crate) render_bundles: Registry<Fallible<RenderBundle>>,
176 pub(crate) render_pipelines: Registry<Fallible<RenderPipeline>>,
177 pub(crate) compute_pipelines: Registry<Fallible<ComputePipeline>>,
178 pub(crate) pipeline_caches: Registry<Fallible<PipelineCache>>,
179 pub(crate) query_sets: Registry<Fallible<QuerySet>>,
180 pub(crate) buffers: Registry<Fallible<Buffer>>,
181 pub(crate) staging_buffers: Registry<StagingBuffer>,
182 pub(crate) textures: Registry<Fallible<Texture>>,
183 pub(crate) texture_views: Registry<Fallible<TextureView>>,
184 pub(crate) samplers: Registry<Fallible<Sampler>>,
185 pub(crate) blas_s: Registry<Fallible<Blas>>,
186 pub(crate) tlas_s: Registry<Fallible<Tlas>>,
187 }
188
189 impl Hub {
190 pub(crate) fn new() -> Self {
191 Self {
192 adapters: Registry::new(),
193 devices: Registry::new(),
194 queues: Registry::new(),
195 pipeline_layouts: Registry::new(),
196 shader_modules: Registry::new(),
197 bind_group_layouts: Registry::new(),
198 bind_groups: Registry::new(),
199 command_buffers: Registry::new(),
200 render_bundles: Registry::new(),
201 render_pipelines: Registry::new(),
202 compute_pipelines: Registry::new(),
203 pipeline_caches: Registry::new(),
204 query_sets: Registry::new(),
205 buffers: Registry::new(),
206 staging_buffers: Registry::new(),
207 textures: Registry::new(),
208 texture_views: Registry::new(),
209 samplers: Registry::new(),
210 blas_s: Registry::new(),
211 tlas_s: Registry::new(),
212 }
213 }
214
215 pub fn generate_report(&self) -> HubReport {
216 HubReport {
217 adapters: self.adapters.generate_report(),
218 devices: self.devices.generate_report(),
219 queues: self.queues.generate_report(),
220 pipeline_layouts: self.pipeline_layouts.generate_report(),
221 shader_modules: self.shader_modules.generate_report(),
222 bind_group_layouts: self.bind_group_layouts.generate_report(),
223 bind_groups: self.bind_groups.generate_report(),
224 command_buffers: self.command_buffers.generate_report(),
225 render_bundles: self.render_bundles.generate_report(),
226 render_pipelines: self.render_pipelines.generate_report(),
227 compute_pipelines: self.compute_pipelines.generate_report(),
228 pipeline_caches: self.pipeline_caches.generate_report(),
229 query_sets: self.query_sets.generate_report(),
230 buffers: self.buffers.generate_report(),
231 textures: self.textures.generate_report(),
232 texture_views: self.texture_views.generate_report(),
233 samplers: self.samplers.generate_report(),
234 }
235 }
236 }