Skip to main content

wgpu_core/
registry.rs

1use alloc::sync::Arc;
2
3use crate::{
4    id::Id,
5    identity::IdentityManager,
6    lock::{
7        rank::{self, LockRank},
8        RwLock, RwLockReadGuard,
9    },
10    storage::{Element, Storage, StorageItem},
11};
12
13#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
14pub struct RegistryReport {
15    /// Count of IDs allocated by [`IdentityManager`]
16    ///
17    /// This may be inconsistent with other fields of the report if
18    /// IDs are allocated or released concurrently with report
19    /// generation.
20    pub num_allocated: usize,
21    pub num_kept_from_user: usize,
22    pub num_released_from_user: usize,
23    pub element_size: usize,
24}
25
26impl RegistryReport {
27    pub fn is_empty(&self) -> bool {
28        self.num_allocated + self.num_kept_from_user == 0
29    }
30}
31
32/// Registry is the primary holder of each resource type
33/// Every resource is now arcanized so the last arc released
34/// will in the end free the memory and release the inner raw resource
35///
36/// Registry act as the main entry point to keep resource alive
37/// when created and released from user land code
38///
39/// A resource may still be alive when released from user land code
40/// if it's used in active submission or anyway kept alive from
41/// any other dependent resource
42///
43#[derive(Debug)]
44pub(crate) struct Registry<T: StorageItem> {
45    // Must only contain an id which has either never been used or has been released from `storage`
46    identity: Arc<IdentityManager<T::Marker>>,
47    storage: RwLock<Storage<T>>,
48}
49
50impl<T: StorageItem> Registry<T> {
51    pub(crate) fn new() -> Self {
52        Self::with_rank(rank::HUB_OTHER)
53    }
54
55    pub(crate) fn with_rank(rank: LockRank) -> Self {
56        Self {
57            identity: Arc::new(IdentityManager::new()),
58            storage: RwLock::new(rank, Storage::new()),
59        }
60    }
61}
62
63#[must_use]
64pub(crate) struct FutureId<'a, T: StorageItem> {
65    id: Id<T::Marker>,
66    identity: &'a IdentityManager<T::Marker>,
67    data: &'a RwLock<Storage<T>>,
68}
69
70impl<T: StorageItem> FutureId<'_, T> {
71    /// Assign a new resource to this ID.
72    ///
73    /// Registers it with the registry.
74    pub fn assign(self, value: T) -> Id<T::Marker> {
75        let mut data = self.data.write();
76        data.insert(self.id, value);
77        // Assigned ids are freed by `Registry::remove`, not `Drop`.
78        let id = self.id;
79        core::mem::forget(self);
80        id
81    }
82}
83
84/// Free the id if it was never assigned, so that its index can be reused.
85impl<T: StorageItem> Drop for FutureId<'_, T> {
86    fn drop(&mut self) {
87        self.identity.free(self.id);
88    }
89}
90
91impl<T: StorageItem> Registry<T> {
92    pub(crate) fn prepare(&self, id_in: Option<Id<T::Marker>>) -> FutureId<'_, T> {
93        FutureId {
94            id: match id_in {
95                Some(id_in) => {
96                    self.identity.mark_as_used(id_in);
97                    id_in
98                }
99                None => self.identity.process(),
100            },
101            identity: &self.identity,
102            data: &self.storage,
103        }
104    }
105
106    #[track_caller]
107    pub(crate) fn read<'a>(&'a self) -> RwLockReadGuard<'a, Storage<T>> {
108        self.storage.read()
109    }
110    pub(crate) fn remove(&self, id: Id<T::Marker>) -> T {
111        let value = self.storage.write().remove(id);
112        // This needs to happen *after* removing it from the storage, to maintain the
113        // invariant that `self.identity` only contains ids which are actually available
114        // See https://github.com/gfx-rs/wgpu/issues/5372
115        self.identity.free(id);
116        //Returning None is legal if it's an error ID
117        value
118    }
119
120    pub(crate) fn generate_report(&self) -> RegistryReport {
121        let mut report = RegistryReport {
122            element_size: size_of::<T>(),
123            ..Default::default()
124        };
125
126        // Acquiring the identity values lock while holding the storage lock
127        // would require adding an edge in the lock graph, and would still not
128        // ensure a consistent report, because the storage lock is not otherwise
129        // acquired when managing IDs.
130        report.num_allocated = self.identity.values.lock().count();
131
132        let storage = self.storage.read();
133        for element in storage.map.iter() {
134            match *element {
135                Element::Occupied(..) => report.num_kept_from_user += 1,
136                Element::Vacant => report.num_released_from_user += 1,
137            }
138        }
139        report
140    }
141}
142
143impl<T: StorageItem + Clone> Registry<T> {
144    pub(crate) fn get(&self, id: Id<T::Marker>) -> T {
145        self.read().get(id)
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::Registry;
152    use crate::{id::Marker, resource::ResourceType, storage::StorageItem};
153    use alloc::sync::Arc;
154
155    struct TestData;
156    struct TestDataId;
157    impl Marker for TestDataId {
158        const TYPE: &'static str = "TestData";
159    }
160
161    impl ResourceType for TestData {
162        const TYPE: &'static str = "TestData";
163    }
164    impl StorageItem for TestData {
165        type Marker = TestDataId;
166    }
167
168    #[test]
169    fn simultaneous_registration() {
170        let registry = Registry::new();
171        std::thread::scope(|s| {
172            for _ in 0..5 {
173                s.spawn(|| {
174                    for _ in 0..1000 {
175                        let value = Arc::new(TestData);
176                        let new_id = registry.prepare(None);
177                        let id = new_id.assign(value);
178                        registry.remove(id);
179                    }
180                });
181            }
182        })
183    }
184
185    #[test]
186    fn dropped_ids_are_reused() {
187        let registry = Registry::new();
188
189        let fid = registry.prepare(None);
190        let index = fid.id.unzip().0;
191        drop(fid);
192
193        let fid = registry.prepare(None);
194        assert_eq!(fid.id.unzip().0, index);
195        fid.assign(Arc::new(TestData));
196    }
197}