From f50e148e92add93b63dbff7245c90509382a437e Mon Sep 17 00:00:00 2001 From: sagudev <16504129+sagudev@users.noreply.github.com> Date: Fri, 21 Aug 2026 06:15:13 +0200 Subject: [PATCH] [core-remote] Write/update docs and make Global as Instance wrapper Signed-off-by: sagudev <16504129+sagudev@users.noreply.github.com> --- wgpu-core-remote-types/Cargo.toml | 2 +- wgpu-core-remote-types/src/binding_model.rs | 8 +- wgpu-core-remote-types/src/id.rs | 5 +- wgpu-core-remote-types/src/identity.rs | 2 +- wgpu-core-remote-types/src/lib.rs | 14 +++ wgpu-core-remote/Cargo.toml | 2 +- wgpu-core-remote/src/global/compute_pass.rs | 4 +- wgpu-core-remote/src/global/device.rs | 2 +- wgpu-core-remote/src/global/instance.rs | 4 +- wgpu-core-remote/src/global/mod.rs | 35 +++----- wgpu-core-remote/src/global/render_pass.rs | 4 +- wgpu-core-remote/src/hub.rs | 97 ++++++++------------- wgpu-core-remote/src/id.rs | 2 +- wgpu-core-remote/src/lib.rs | 13 +++ wgpu-core-remote/src/storage.rs | 16 ++-- 15 files changed, 101 insertions(+), 109 deletions(-) diff --git a/wgpu-core-remote-types/Cargo.toml b/wgpu-core-remote-types/Cargo.toml index fbce0cf9d..8dbe2abaa 100644 --- a/wgpu-core-remote-types/Cargo.toml +++ b/wgpu-core-remote-types/Cargo.toml @@ -2,7 +2,7 @@ name = "wgpu-core-remote-types" version.workspace = true edition.workspace = true -description = "Remoting version of wgpu-core" +description = "Types for remoting version of wgpu-core for browser implementing WebGPU" homepage.workspace = true repository.workspace = true keywords.workspace = true diff --git a/wgpu-core-remote-types/src/binding_model.rs b/wgpu-core-remote-types/src/binding_model.rs index dd9a0a2ac..5cac34146 100644 --- a/wgpu-core-remote-types/src/binding_model.rs +++ b/wgpu-core-remote-types/src/binding_model.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; use crate::id::{BindGroupLayoutId, BufferId, ExternalTextureId, SamplerId, TextureViewId}; use crate::Label; +/// Corresponds to [`GPUBufferBinding`](https://www.w3.org/TR/webgpu/#dictdef-gpubufferbinding). #[repr(C)] #[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize)] pub struct BufferBinding { @@ -21,6 +22,7 @@ pub struct BufferBinding { pub size: Option, } +/// Corresponds to [`GPUBindingResource`](https://www.w3.org/TR/webgpu/#typedefdef-gpubindingresource). #[derive(Debug, Clone, Serialize, Deserialize)] pub enum BindingResource { Buffer(BufferBinding), @@ -30,6 +32,8 @@ pub enum BindingResource { } /// Bindable resource and the slot to bind it to. +/// +/// This corresponds to [`GPUBindGroupEntry`](https://www.w3.org/TR/webgpu/#dictdef-gpubindgroupentry). #[derive(Clone, Debug, Serialize, Deserialize)] pub struct BindGroupEntry { /// Slot for which binding provides resource. Corresponds to an entry of the same @@ -40,6 +44,8 @@ pub struct BindGroupEntry { } /// Describes a group of bindings and the resources to be bound. +/// +/// This corresponds to [`GPUBindGroupDescriptor`](https://www.w3.org/TR/webgpu/#dictdef-gpubindgroupdescriptor). #[derive(Clone, Debug, Serialize, Deserialize)] pub struct BindGroupDescriptor<'a> { /// Debug label of the bind group. @@ -52,7 +58,7 @@ pub struct BindGroupDescriptor<'a> { pub entries: Cow<'a, [BindGroupEntry]>, } -/// Describes a [`BindGroupLayout`]. +/// Corresponds to [`GPUBindGroupLayoutDescriptor`](https://www.w3.org/TR/webgpu/#dictdef-gpubindgrouplayoutdescriptor). #[derive(Clone, Debug, Serialize, Deserialize)] pub struct BindGroupLayoutDescriptor<'a> { /// Debug label of the bind group layout. diff --git a/wgpu-core-remote-types/src/id.rs b/wgpu-core-remote-types/src/id.rs index 4ae169b89..27559414f 100644 --- a/wgpu-core-remote-types/src/id.rs +++ b/wgpu-core-remote-types/src/id.rs @@ -50,10 +50,7 @@ impl RawId { /// An identifier for a wgpu object. /// -/// An `Id` value identifies a value stored in a [`Global`]'s [`Hub`]. -/// -/// [`Global`]: crate::global::Global -/// [`Hub`]: crate::hub::Hub +/// An `Id` value identifies a value stored in a `Global`'s `Hub`. #[repr(transparent)] #[derive(serde::Serialize, serde::Deserialize)] #[serde(transparent)] diff --git a/wgpu-core-remote-types/src/identity.rs b/wgpu-core-remote-types/src/identity.rs index a0855473a..07db699b2 100644 --- a/wgpu-core-remote-types/src/identity.rs +++ b/wgpu-core-remote-types/src/identity.rs @@ -100,7 +100,7 @@ impl Default for IdentityManager { /// A collection of identity managers for all resource types. /// /// This is to be used in content process for ID generation. -/// IDs are then sent to the GPU process for resource creation in [`crate::hub::Hub`]. +/// IDs are then sent to the GPU process for resource creation in `Hub`. #[derive(Debug, Default)] pub struct IdentityHub { pub adapters: IdentityManager, diff --git a/wgpu-core-remote-types/src/lib.rs b/wgpu-core-remote-types/src/lib.rs index 01480738f..eaed1114c 100644 --- a/wgpu-core-remote-types/src/lib.rs +++ b/wgpu-core-remote-types/src/lib.rs @@ -1,3 +1,17 @@ +//! This crate contains types for the remoting version of wgpu-core for browser implementing WebGPU. +//! +//! It contains types that are used for IPC communication between the browser's untrusted content process +//! and the browser's trusted GPU process and [`IdentityHub`](crate::identity::IdentityHub) for Id generation. +//! All in all it contains all types needed for content process. +//! +//! All IPC types implement `serde::Serialize` and `serde::Deserialize` so that they can be sent over IPC. +//! +//! Types are defined entirely separately from wgpu-core's (and eventually wgpu-types's) public types, +//! so that even as experimental features like raytracing and native wpgu features that are not standard WebGPU, +//! cannot be expressed in untrusted (thus potentially malicious) content processes, +//! as Serde's standard deserialization rejects invalid values of the IPC types. +//! +//! For more information about the remoting architecture, see the wgpu-core-remote crate's documentation. extern crate alloc; extern crate wgpu_types as wgt; diff --git a/wgpu-core-remote/Cargo.toml b/wgpu-core-remote/Cargo.toml index 0a0067c6a..964f627f8 100644 --- a/wgpu-core-remote/Cargo.toml +++ b/wgpu-core-remote/Cargo.toml @@ -2,7 +2,7 @@ name = "wgpu-core-remote" version.workspace = true edition.workspace = true -description = "Remoting version of wgpu-core" +description = "Remoting version of wgpu-core for browser implementing WebGPU" homepage.workspace = true repository.workspace = true keywords.workspace = true diff --git a/wgpu-core-remote/src/global/compute_pass.rs b/wgpu-core-remote/src/global/compute_pass.rs index 1f5f2ae9a..80b88100b 100644 --- a/wgpu-core-remote/src/global/compute_pass.rs +++ b/wgpu-core-remote/src/global/compute_pass.rs @@ -19,9 +19,7 @@ impl Global { /// ultimately be generated when the parent encoder is finished, and it is /// not possible to run any commands from the invalid pass. /// - /// If successful, puts the encoder into the [`Locked`] state. - /// - /// [`Locked`]: crate::command::CommandEncoderStatus::Locked + /// If successful, puts the encoder into the `Locked` state. pub fn command_encoder_begin_compute_pass<'a>( &self, encoder_id: id::CommandEncoderId, diff --git a/wgpu-core-remote/src/global/device.rs b/wgpu-core-remote/src/global/device.rs index 160f38c75..e3373edac 100644 --- a/wgpu-core-remote/src/global/device.rs +++ b/wgpu-core-remote/src/global/device.rs @@ -112,7 +112,7 @@ impl Global { /// [`GPUBufferDescriptor`]: https://www.w3.org/TR/webgpu/#dictdef-gpubufferdescriptor /// [`GPUBuffer`]: https://www.w3.org/TR/webgpu/#gpubuffer /// [`wgpu_types::BufferDescriptor`]: wgt::BufferDescriptor - /// [`Device::create_buffer`]: crate::device::Device::create_buffer + /// [`Device::create_buffer`]: wgpu_core::device::Device::create_buffer /// [`usage`]: https://www.w3.org/TR/webgpu/#dom-gputexturedescriptor-usage /// [`wgpu_types::BufferUsages`]: wgt::BufferUsages pub fn create_buffer_error( diff --git a/wgpu-core-remote/src/global/instance.rs b/wgpu-core-remote/src/global/instance.rs index 116a9cc51..1ed1a6ef7 100644 --- a/wgpu-core-remote/src/global/instance.rs +++ b/wgpu-core-remote/src/global/instance.rs @@ -32,14 +32,14 @@ impl Global { /// The HAL adapter may be obtained e.g. by calling `enumerate_adapters` on /// the HAL directly. /// - /// If [limit bucketing][lt] is desired, [`crate::limits::apply_limit_buckets`] + /// If [limit bucketing][lt] is desired, [`wgpu_core::limits::apply_limit_buckets`] /// should be called with the HAL adapter before calling this function. /// /// # Safety /// /// `hal_adapter` must be created from this global internal instance handle. /// - /// [lt]: crate::limits#Limit-bucketing + /// [lt]: wgpu_core::limits#Limit-bucketing pub unsafe fn create_adapter_from_hal( &self, hal_adapter: hal::DynExposedAdapter, diff --git a/wgpu-core-remote/src/global/mod.rs b/wgpu-core-remote/src/global/mod.rs index 4ae0995f5..af8415e16 100644 --- a/wgpu-core-remote/src/global/mod.rs +++ b/wgpu-core-remote/src/global/mod.rs @@ -1,4 +1,4 @@ -use alloc::{borrow::ToOwned as _, sync::Arc}; +use alloc::sync::Arc; use core::cell::RefCell; use core::fmt; use wgpu_core::binding_model::{BindGroupLayout, PipelineLayout}; @@ -24,6 +24,13 @@ mod instance; mod queue; mod render_pass; +/// Wrapper around [`Instance`] that uses [`Hub`] to store all resources created by the instance behind an [`Id`]. +/// +/// All resource methods are implemented on [`Global`] and accept types from [`wgpu_core_remote_types`] +/// (which use [`Id`]s instead of concrete resources) and maps them into [`wgpu_core`] types +/// (the process which also includes resolving the IDs). +/// +/// [`Id`]: crate::id::Id pub struct Global { pub(crate) hub: RefCell, // the instance must be dropped last @@ -42,32 +49,16 @@ impl Global { } } - /// # Safety - /// - /// Refer to the creation of wgpu-hal Instance for every backend. - pub unsafe fn from_hal_instance(name: &str, hal_instance: A::Instance) -> Self { - Self { - instance: Instance::from_hal_instance::(name.to_owned(), hal_instance), - hub: RefCell::new(Hub::new()), - } - } - - /// # Safety - /// - /// - The raw instance handle returned must not be manually destroyed. - pub unsafe fn instance_as_hal(&self) -> Option<&A::Instance> { - unsafe { self.instance.as_hal::() } - } - - /// # Safety - /// - /// - The raw handles obtained from the Instance must not be manually destroyed - pub unsafe fn from_instance(instance: Arc) -> Self { + pub fn from_instance(instance: Arc) -> Self { Self { instance, hub: RefCell::new(Hub::new()), } } + + pub fn instance(&self) -> &Arc { + &self.instance + } } // methods to import and resolve resources in the global hub diff --git a/wgpu-core-remote/src/global/render_pass.rs b/wgpu-core-remote/src/global/render_pass.rs index 11e56ff6a..1583811ac 100644 --- a/wgpu-core-remote/src/global/render_pass.rs +++ b/wgpu-core-remote/src/global/render_pass.rs @@ -40,9 +40,7 @@ impl Global { /// ultimately be generated when the parent encoder is finished, and it is /// not possible to run any commands from the invalid pass. /// - /// If successful, puts the encoder into the [`Locked`] state. - /// - /// [`Locked`]: crate::command::CommandEncoderStatus::Locked + /// If successful, puts the encoder into the `Locked` state. pub fn command_encoder_begin_render_pass<'a>( &self, encoder_id: id::CommandEncoderId, diff --git a/wgpu-core-remote/src/hub.rs b/wgpu-core-remote/src/hub.rs index 9343b03e6..8536423c7 100644 --- a/wgpu-core-remote/src/hub.rs +++ b/wgpu-core-remote/src/hub.rs @@ -9,66 +9,45 @@ of course `Debug`. [`id::DeviceId`]: crate::id::DeviceId [`id::BufferId`]: crate::id::BufferId -Each `Id` contains not only an index for the resource it denotes but -also a Backend indicating which `wgpu` backend it belongs to. - -`Id`s also incorporate a generation number, for additional validation. +[`Id`]s also incorporate a generation number, for additional validation. The resources to which identifiers refer are freed explicitly. Attempting to use an identifier for a resource that has been freed -elicits an error result. - -Eventually, we would like to remove numeric IDs from wgpu-core. -See . +elicits an panic. ## Assigning ids to resources -The users of `wgpu_core` generally want resource ids to be assigned -in one of two ways: +Firefox and Servo allocate ids themselves in the content process using [`IdentityHub`], +then pass then via IPC to GPU process where it's passed down to +`Global::device_create_buffer` and friends the id to assign the new +resource. -- Users like `wgpu` want `wgpu_core` to assign ids to resources itself. - For example, `wgpu` expects to call `Global::device_create_buffer` - and have the return value indicate the newly created buffer's id. - -- Users like Firefox want to allocate ids themselves, and pass - `Global::device_create_buffer` and friends the id to assign the new - resource. - -To accommodate either pattern, `wgpu_core` methods that create -resources all expect an `id_in` argument that the caller can use to -specify the id, and they all return the id used. For example, the +Methods that create resources all expect an `id_in` argument +that the caller uses to specify the id. For example, the declaration of `Global::device_create_buffer` looks like this: ```ignore impl Global { /* ... */ - pub fn device_create_buffer( + pub fn device_create_buffer( &self, device_id: id::DeviceId, - desc: &resource::BufferDescriptor, - id_in: Input, - ) -> (id::BufferId, Option) { + desc: &BufferDescriptor, + id_in: id::BufferId, + ) { /* ... */ } /* ... */ } ``` -Users that want to assign resource ids themselves pass in the id they -want as the `id_in` argument, whereas users that want `wgpu_core` -itself to choose ids always pass `()`. In either case, the id -ultimately assigned is returned as the first element of the tuple. - -Producing true identifiers from `id_in` values is the job of an -[`crate::identity::IdentityManager`] or ids will be received from outside through `Option` arguments. - ## Id allocation and streaming -Perhaps surprisingly, allowing users to assign resource ids themselves +Allowing users to assign resource ids themselves enables major performance improvements in some applications. -The `wgpu_core` API is designed for use by Firefox's [WebGPU] -implementation. For security, web content and GPU use must be kept +This is designed for use by Firefox's and Servo's [WebGPU] implementation. +For security, web content and GPU use must be kept segregated in separate processes, with all interaction between them mediated by an inter-process communication protocol. As web content uses the WebGPU API, the content process sends messages to the GPU process, @@ -94,12 +73,13 @@ activity to be pipelined greatly improves throughput. To help propagate errors correctly in this style of usage, when resource creation fails, the id supplied for that resource is marked to indicate as much, allowing subsequent operations using that id to be properly -flagged as errors as well. +flagged as errors as well. This is called [Contagious Invalidity]. -[`process`]: crate::identity::IdentityManager::process [`Id`]: crate::id::Id -[wrapped in a mutex]: trait.IdentityHandler.html#impl-IdentityHandler%3CI%3E-for-Mutex%3CIdentityManager%3E +[`Id`]: crate::id::Id [WebGPU]: https://www.w3.org/TR/webgpu/ +[`IdentityHub`]: wgpu_core_remote_types::identity::IdentityHub +[Contagious Invalidity]: https://www.w3.org/TR/webgpu/#invalidity */ @@ -120,24 +100,22 @@ use wgpu_core::{ #[allow(rustdoc::private_intra_doc_links)] /// All the resources tracked by a [`crate::global::Global`]. /// -/// ## Locking +/// Each field in [`Hub`] is a [`Registry`] holding all the values of a +/// particular type of resource. /// -/// Each field in `Hub` is a [`Registry`] holding all the values of a -/// particular type of resource, all protected by a single RwLock. -/// So for example, to access any [`Buffer`], you must acquire a read -/// lock on the `Hub`s entire buffers registry. The lock guard -/// gives you access to the `Registry`'s [`Storage`], which you can -/// then index with the buffer's id. (Yes, this design causes -/// contention; see [#2272].) -/// -/// But most `wgpu` operations require access to several different -/// kinds of resource, so you often need to hold locks on several -/// different fields of your [`Hub`] simultaneously. -/// -/// Inside the `Registry` there are `Arc` where `T` is a Resource -/// Lock of `Registry` happens only when accessing to get the specific resource -/// -/// [`Storage`]: crate::storage::Storage +/// Most `wgpu` operations require access to several different +/// kinds of resource, so to obtain mutable references +/// to different fields of your [`Hub`] simultaneously, use +/// destructing: +/// ```ignore +/// fn f(hub: &mut Hub) { +/// let Hub { +/// command_encoders, +/// command_buffers, +/// .. +/// } = hub; +/// } +/// ``` pub struct Hub { pub(crate) adapters: Registry>, pub(crate) devices: Registry>, @@ -165,13 +143,6 @@ pub struct Hub { impl Hub { pub(crate) fn new() -> Self { - // Unique lock ranks are required only for registries that are accessed concurrently. - // This happens in render pass/bundle encoding, and bind group creation. (Concurrent - // access could probably be avoided even in those cases, but acquiring all the locks - // at once simplifies the code.) - // - // The _first_ concurrently-held registry lock uses REGISTRY_STORAGE. Others have - // their own named lock rank. Self { adapters: Registry::new(), devices: Registry::new(), diff --git a/wgpu-core-remote/src/id.rs b/wgpu-core-remote/src/id.rs index 2700503b1..bf1a9fc09 100644 --- a/wgpu-core-remote/src/id.rs +++ b/wgpu-core-remote/src/id.rs @@ -1,6 +1,6 @@ pub use wgpu_core_remote_types::id::*; -/// Reference wgpu objects via numeric IDs assigned by [`crate::identity::IdentityManager`]. +/// Reference wgpu objects via numeric IDs assigned by [`wgpu_core_remote_types::identity::IdentityManager`]. #[derive(Clone, Debug)] pub struct IdReferences; diff --git a/wgpu-core-remote/src/lib.rs b/wgpu-core-remote/src/lib.rs index a01cfe0b4..fc6940093 100644 --- a/wgpu-core-remote/src/lib.rs +++ b/wgpu-core-remote/src/lib.rs @@ -1,3 +1,16 @@ +/*! +This crate is a remoting version of [`wgpu_core`] for browser implementing WebGPU. + +Modern browsers have content processes that are untrusted and cannot directly access the GPU. +Instead, they communicate with a trusted GPU process that has access to the GPU. + +wgpu-core-remote provides a remoting wrapper around [`wgpu_core`] named [`Global`](crate::global::Global), +that is used in the GPU process to execute commands from the content process. +All stuff that is needed in the content process is provided in the [`wgpu_core_remote_types`] crate. + +The key part of remoting are [`Id`](crate::id::Id) which are described in [`crate::hub`]. +*/ + #![allow( // Need many arguments for some core functions to be able to re-use code in many situations. clippy::too_many_arguments, diff --git a/wgpu-core-remote/src/storage.rs b/wgpu-core-remote/src/storage.rs index a814db91a..da8f7ccd0 100644 --- a/wgpu-core-remote/src/storage.rs +++ b/wgpu-core-remote/src/storage.rs @@ -175,7 +175,7 @@ mod tests { #[test] #[should_panic( - expected = "Cannot insert UntypedId(0,1), found existing resource UntypedId(0,1)" + expected = "Cannot insert TestMarkerId(0,1), found existing resource TestMarkerId(0,1)" )] fn insert_occupied_same_epoch() { let mut storage = Storage::new(); @@ -185,7 +185,7 @@ mod tests { #[test] #[should_panic( - expected = "Cannot insert UntypedId(0,2), found existing resource UntypedId(0,1)" + expected = "Cannot insert TestMarkerId(0,2), found existing resource TestMarkerId(0,1)" )] fn insert_occupied_different_epoch() { let mut storage = Storage::new(); @@ -194,7 +194,9 @@ mod tests { } #[test] - #[should_panic(expected = "Cannot remove UntypedId(0,2), found other resource UntypedId(0,1)")] + #[should_panic( + expected = "Cannot remove TestMarkerId(0,2), found other resource TestMarkerId(0,1)" + )] fn remove_epoch_mismatch() { let mut storage = Storage::new(); storage.insert(id(0, 1), TestItem); @@ -202,21 +204,23 @@ mod tests { } #[test] - #[should_panic(expected = "Cannot remove non-existent resource UntypedId(0,1)")] + #[should_panic(expected = "Cannot remove non-existent resource TestMarkerId(0,1)")] fn remove_vacant() { let mut storage = Storage::::new(); storage.remove(id(0, 1)); } #[test] - #[should_panic(expected = "Cannot get non-existent resource UntypedId(0,1)")] + #[should_panic(expected = "Cannot get non-existent resource TestMarkerId(0,1)")] fn get_vacant() { let storage = Storage::::new(); storage.get(id(0, 1)); } #[test] - #[should_panic(expected = "Cannot get UntypedId(0,2), found other resource UntypedId(0,1)")] + #[should_panic( + expected = "Cannot get TestMarkerId(0,2), found other resource TestMarkerId(0,1)" + )] fn get_epoch_mismatch() { let mut storage = Storage::new(); storage.insert(id(0, 1), TestItem);