1 // SPDX-License-Identifier: GPL-2.0 1 // SPDX-License-Identifier: GPL-2.0 2 2 3 //! A wrapper for data protected by a lock tha 3 //! A wrapper for data protected by a lock that does not wrap it. 4 4 5 use super::{lock::Backend, lock::Lock}; 5 use super::{lock::Backend, lock::Lock}; 6 use crate::build_assert; 6 use crate::build_assert; 7 use core::{cell::UnsafeCell, mem::size_of, ptr 7 use core::{cell::UnsafeCell, mem::size_of, ptr}; 8 8 9 /// Allows access to some data to be serialise 9 /// Allows access to some data to be serialised by a lock that does not wrap it. 10 /// 10 /// 11 /// In most cases, data protected by a lock is 11 /// In most cases, data protected by a lock is wrapped by the appropriate lock type, e.g., 12 /// [`Mutex`] or [`SpinLock`]. [`LockedBy`] is !! 12 /// [`super::Mutex`] or [`super::SpinLock`]. [`LockedBy`] is meant for cases when this is not 13 /// For example, if a container has a lock and !! 13 /// possible. For example, if a container has a lock and some data in the contained elements needs 14 /// to be protected by the same lock. 14 /// to be protected by the same lock. 15 /// 15 /// 16 /// [`LockedBy`] wraps the data in lieu of ano 16 /// [`LockedBy`] wraps the data in lieu of another locking primitive, and only allows access to it 17 /// when the caller shows evidence that the 'e 17 /// when the caller shows evidence that the 'external' lock is locked. It panics if the evidence 18 /// refers to the wrong instance of the lock. 18 /// refers to the wrong instance of the lock. 19 /// 19 /// 20 /// [`Mutex`]: super::Mutex << 21 /// [`SpinLock`]: super::SpinLock << 22 /// << 23 /// # Examples 20 /// # Examples 24 /// 21 /// 25 /// The following is an example for illustrati 22 /// The following is an example for illustrative purposes: `InnerDirectory::bytes_used` is an 26 /// aggregate of all `InnerFile::bytes_used` a 23 /// aggregate of all `InnerFile::bytes_used` and must be kept consistent; so we wrap `InnerFile` in 27 /// a `LockedBy` so that it shares a lock with 24 /// a `LockedBy` so that it shares a lock with `InnerDirectory`. This allows us to enforce at 28 /// compile-time that access to `InnerFile` is 25 /// compile-time that access to `InnerFile` is only granted when an `InnerDirectory` is also 29 /// locked; we enforce at run time that the ri 26 /// locked; we enforce at run time that the right `InnerDirectory` is locked. 30 /// 27 /// 31 /// ``` 28 /// ``` 32 /// use kernel::sync::{LockedBy, Mutex}; 29 /// use kernel::sync::{LockedBy, Mutex}; 33 /// 30 /// 34 /// struct InnerFile { 31 /// struct InnerFile { 35 /// bytes_used: u64, 32 /// bytes_used: u64, 36 /// } 33 /// } 37 /// 34 /// 38 /// struct File { 35 /// struct File { 39 /// _ino: u32, 36 /// _ino: u32, 40 /// inner: LockedBy<InnerFile, InnerDirect 37 /// inner: LockedBy<InnerFile, InnerDirectory>, 41 /// } 38 /// } 42 /// 39 /// 43 /// struct InnerDirectory { 40 /// struct InnerDirectory { 44 /// /// The sum of the bytes used by all f 41 /// /// The sum of the bytes used by all files. 45 /// bytes_used: u64, 42 /// bytes_used: u64, 46 /// _files: Vec<File>, 43 /// _files: Vec<File>, 47 /// } 44 /// } 48 /// 45 /// 49 /// struct Directory { 46 /// struct Directory { 50 /// _ino: u32, 47 /// _ino: u32, 51 /// inner: Mutex<InnerDirectory>, 48 /// inner: Mutex<InnerDirectory>, 52 /// } 49 /// } 53 /// 50 /// 54 /// /// Prints `bytes_used` from both the dire 51 /// /// Prints `bytes_used` from both the directory and file. 55 /// fn print_bytes_used(dir: &Directory, file: 52 /// fn print_bytes_used(dir: &Directory, file: &File) { 56 /// let guard = dir.inner.lock(); 53 /// let guard = dir.inner.lock(); 57 /// let inner_file = file.inner.access(&gu 54 /// let inner_file = file.inner.access(&guard); 58 /// pr_info!("{} {}", guard.bytes_used, in 55 /// pr_info!("{} {}", guard.bytes_used, inner_file.bytes_used); 59 /// } 56 /// } 60 /// 57 /// 61 /// /// Increments `bytes_used` for both the d 58 /// /// Increments `bytes_used` for both the directory and file. 62 /// fn inc_bytes_used(dir: &Directory, file: & 59 /// fn inc_bytes_used(dir: &Directory, file: &File) { 63 /// let mut guard = dir.inner.lock(); 60 /// let mut guard = dir.inner.lock(); 64 /// guard.bytes_used += 10; 61 /// guard.bytes_used += 10; 65 /// 62 /// 66 /// let file_inner = file.inner.access_mut 63 /// let file_inner = file.inner.access_mut(&mut guard); 67 /// file_inner.bytes_used += 10; 64 /// file_inner.bytes_used += 10; 68 /// } 65 /// } 69 /// 66 /// 70 /// /// Creates a new file. 67 /// /// Creates a new file. 71 /// fn new_file(ino: u32, dir: &Directory) -> 68 /// fn new_file(ino: u32, dir: &Directory) -> File { 72 /// File { 69 /// File { 73 /// _ino: ino, 70 /// _ino: ino, 74 /// inner: LockedBy::new(&dir.inner, I 71 /// inner: LockedBy::new(&dir.inner, InnerFile { bytes_used: 0 }), 75 /// } 72 /// } 76 /// } 73 /// } 77 /// ``` 74 /// ``` 78 pub struct LockedBy<T: ?Sized, U: ?Sized> { 75 pub struct LockedBy<T: ?Sized, U: ?Sized> { 79 owner: *const U, 76 owner: *const U, 80 data: UnsafeCell<T>, 77 data: UnsafeCell<T>, 81 } 78 } 82 79 83 // SAFETY: `LockedBy` can be transferred acros 80 // SAFETY: `LockedBy` can be transferred across thread boundaries iff the data it protects can. 84 unsafe impl<T: ?Sized + Send, U: ?Sized> Send 81 unsafe impl<T: ?Sized + Send, U: ?Sized> Send for LockedBy<T, U> {} 85 82 86 // SAFETY: If `T` is not `Sync`, then parallel !! 83 // SAFETY: `LockedBy` serialises the interior mutability it provides, so it is `Sync` as long as the 87 // `access_mut` to hand out `&mut T` on one th !! 84 // data it protects is `Send`. 88 // sufficient to allow that. << 89 // << 90 // If `T` is `Sync`, then the `access` method << 91 // several `&T` from several threads at once. << 92 unsafe impl<T: ?Sized + Send, U: ?Sized> Sync 85 unsafe impl<T: ?Sized + Send, U: ?Sized> Sync for LockedBy<T, U> {} 93 86 94 impl<T, U> LockedBy<T, U> { 87 impl<T, U> LockedBy<T, U> { 95 /// Constructs a new instance of [`LockedB 88 /// Constructs a new instance of [`LockedBy`]. 96 /// 89 /// 97 /// It stores a raw pointer to the owner t 90 /// It stores a raw pointer to the owner that is never dereferenced. It is only used to ensure 98 /// that the right owner is being used to 91 /// that the right owner is being used to access the protected data. If the owner is freed, the 99 /// data becomes inaccessible; if another 92 /// data becomes inaccessible; if another instance of the owner is allocated *on the same 100 /// memory location*, the data becomes acc 93 /// memory location*, the data becomes accessible again: none of this affects memory safety 101 /// because in any case at most one thread 94 /// because in any case at most one thread (or CPU) can access the protected data at a time. 102 pub fn new<B: Backend>(owner: &Lock<U, B>, 95 pub fn new<B: Backend>(owner: &Lock<U, B>, data: T) -> Self { 103 build_assert!( 96 build_assert!( 104 size_of::<Lock<U, B>>() > 0, 97 size_of::<Lock<U, B>>() > 0, 105 "The lock type cannot be a ZST bec 98 "The lock type cannot be a ZST because it may be impossible to distinguish instances" 106 ); 99 ); 107 Self { 100 Self { 108 owner: owner.data.get(), 101 owner: owner.data.get(), 109 data: UnsafeCell::new(data), 102 data: UnsafeCell::new(data), 110 } 103 } 111 } 104 } 112 } 105 } 113 106 114 impl<T: ?Sized, U> LockedBy<T, U> { 107 impl<T: ?Sized, U> LockedBy<T, U> { 115 /// Returns a reference to the protected d 108 /// Returns a reference to the protected data when the caller provides evidence (via a 116 /// reference) that the owner is locked. 109 /// reference) that the owner is locked. 117 /// 110 /// 118 /// `U` cannot be a zero-sized type (ZST) 111 /// `U` cannot be a zero-sized type (ZST) because there are ways to get an `&U` that matches 119 /// the data protected by the lock without 112 /// the data protected by the lock without actually holding it. 120 /// 113 /// 121 /// # Panics 114 /// # Panics 122 /// 115 /// 123 /// Panics if `owner` is different from th 116 /// Panics if `owner` is different from the data protected by the lock used in 124 /// [`new`](LockedBy::new). 117 /// [`new`](LockedBy::new). 125 pub fn access<'a>(&'a self, owner: &'a U) !! 118 pub fn access<'a>(&'a self, owner: &'a U) -> &'a T { 126 where << 127 T: Sync, << 128 { << 129 build_assert!( 119 build_assert!( 130 size_of::<U>() > 0, 120 size_of::<U>() > 0, 131 "`U` cannot be a ZST because `owne 121 "`U` cannot be a ZST because `owner` wouldn't be unique" 132 ); 122 ); 133 if !ptr::eq(owner, self.owner) { 123 if !ptr::eq(owner, self.owner) { 134 panic!("mismatched owners"); 124 panic!("mismatched owners"); 135 } 125 } 136 126 137 // SAFETY: `owner` is evidence that th !! 127 // SAFETY: `owner` is evidence that the owner is locked. 138 // duration of 'a, so it's not possibl << 139 // reference to the inner value that a << 140 // so there are no other requirements. << 141 unsafe { &*self.data.get() } 128 unsafe { &*self.data.get() } 142 } 129 } 143 130 144 /// Returns a mutable reference to the pro 131 /// Returns a mutable reference to the protected data when the caller provides evidence (via a 145 /// mutable owner) that the owner is locke 132 /// mutable owner) that the owner is locked mutably. 146 /// 133 /// 147 /// `U` cannot be a zero-sized type (ZST) 134 /// `U` cannot be a zero-sized type (ZST) because there are ways to get an `&mut U` that 148 /// matches the data protected by the lock 135 /// matches the data protected by the lock without actually holding it. 149 /// 136 /// 150 /// Showing a mutable reference to the own 137 /// Showing a mutable reference to the owner is sufficient because we know no other references 151 /// can exist to it. 138 /// can exist to it. 152 /// 139 /// 153 /// # Panics 140 /// # Panics 154 /// 141 /// 155 /// Panics if `owner` is different from th 142 /// Panics if `owner` is different from the data protected by the lock used in 156 /// [`new`](LockedBy::new). 143 /// [`new`](LockedBy::new). 157 pub fn access_mut<'a>(&'a self, owner: &'a 144 pub fn access_mut<'a>(&'a self, owner: &'a mut U) -> &'a mut T { 158 build_assert!( 145 build_assert!( 159 size_of::<U>() > 0, 146 size_of::<U>() > 0, 160 "`U` cannot be a ZST because `owne 147 "`U` cannot be a ZST because `owner` wouldn't be unique" 161 ); 148 ); 162 if !ptr::eq(owner, self.owner) { 149 if !ptr::eq(owner, self.owner) { 163 panic!("mismatched owners"); 150 panic!("mismatched owners"); 164 } 151 } 165 152 166 // SAFETY: `owner` is evidence that th 153 // SAFETY: `owner` is evidence that there is only one reference to the owner. 167 unsafe { &mut *self.data.get() } 154 unsafe { &mut *self.data.get() } 168 } 155 } 169 } 156 }
Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.