1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Extensions to the [`alloc`] crate. 4 5 #[cfg(not(any(test, testlib)))] 6 pub mod allocator; 7 pub mod kbox; 8 pub mod kvec; 9 pub mod layout; 10 pub mod vec_ext; 11 12 #[cfg(any(test, testlib))] 13 pub mod allocator_test; 14 15 #[cfg(any(test, testlib))] 16 pub use self::allocator_test as allocator; 17 18 pub use self::kbox::Box; 19 pub use self::kbox::KBox; 20 pub use self::kbox::KVBox; 21 pub use self::kbox::VBox; 22 23 pub use self::kvec::IntoIter; 24 pub use self::kvec::KVVec; 25 pub use self::kvec::KVec; 26 pub use self::kvec::VVec; 27 pub use self::kvec::Vec; 28 29 /// Indicates an allocation error. 30 #[derive(Copy, Clone, PartialEq, Eq, Debug)] 31 pub struct AllocError; 32 use core::{alloc::Layout, ptr::NonNull}; 33 34 /// Flags to be used when allocating memory. 35 /// 36 /// They can be combined with the operators `|`, `&`, and `!`. 37 /// 38 /// Values can be used from the [`flags`] module. 39 #[derive(Clone, Copy)] 40 pub struct Flags(u32); 41 42 impl Flags { 43 /// Get the raw representation of this flag. 44 pub(crate) fn as_raw(self) -> u32 { 45 self.0 46 } 47 } 48 49 impl core::ops::BitOr for Flags { 50 type Output = Self; 51 fn bitor(self, rhs: Self) -> Self::Output { 52 Self(self.0 | rhs.0) 53 } 54 } 55 56 impl core::ops::BitAnd for Flags { 57 type Output = Self; 58 fn bitand(self, rhs: Self) -> Self::Output { 59 Self(self.0 & rhs.0) 60 } 61 } 62 63 impl core::ops::Not for Flags { 64 type Output = Self; 65 fn not(self) -> Self::Output { 66 Self(!self.0) 67 } 68 } 69 70 /// Allocation flags. 71 /// 72 /// These are meant to be used in functions that can allocate memory. 73 pub mod flags { 74 use super::Flags; 75 76 /// Zeroes out the allocated memory. 77 /// 78 /// This is normally or'd with other flags. 79 pub const __GFP_ZERO: Flags = Flags(bindings::__GFP_ZERO); 80 81 /// Allow the allocation to be in high memory. 82 /// 83 /// Allocations in high memory may not be mapped into the kernel's address space, so this can't 84 /// be used with `kmalloc` and other similar methods. 85 /// 86 /// This is normally or'd with other flags. 87 pub const __GFP_HIGHMEM: Flags = Flags(bindings::__GFP_HIGHMEM); 88 89 /// Users can not sleep and need the allocation to succeed. 90 /// 91 /// A lower watermark is applied to allow access to "atomic reserves". The current 92 /// implementation doesn't support NMI and few other strict non-preemptive contexts (e.g. 93 /// raw_spin_lock). The same applies to [`GFP_NOWAIT`]. 94 pub const GFP_ATOMIC: Flags = Flags(bindings::GFP_ATOMIC); 95 96 /// Typical for kernel-internal allocations. The caller requires ZONE_NORMAL or a lower zone 97 /// for direct access but can direct reclaim. 98 pub const GFP_KERNEL: Flags = Flags(bindings::GFP_KERNEL); 99 100 /// The same as [`GFP_KERNEL`], except the allocation is accounted to kmemcg. 101 pub const GFP_KERNEL_ACCOUNT: Flags = Flags(bindings::GFP_KERNEL_ACCOUNT); 102 103 /// For kernel allocations that should not stall for direct reclaim, start physical IO or 104 /// use any filesystem callback. It is very likely to fail to allocate memory, even for very 105 /// small allocations. 106 pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT); 107 108 /// Suppresses allocation failure reports. 109 /// 110 /// This is normally or'd with other flags. 111 pub const __GFP_NOWARN: Flags = Flags(bindings::__GFP_NOWARN); 112 } 113 114 /// The kernel's [`Allocator`] trait. 115 /// 116 /// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffers described 117 /// via [`Layout`]. 118 /// 119 /// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on 120 /// an object instance. 121 /// 122 /// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design 123 /// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind 124 /// of `self` parameter. 125 /// 126 /// # Safety 127 /// 128 /// - A memory allocation returned from an allocator must remain valid until it is explicitly freed. 129 /// 130 /// - Any pointer to a valid memory allocation must be valid to be passed to any other [`Allocator`] 131 /// function of the same type. 132 /// 133 /// - Implementers must ensure that all trait functions abide by the guarantees documented in the 134 /// `# Guarantees` sections. 135 pub unsafe trait Allocator { 136 /// Allocate memory based on `layout` and `flags`. 137 /// 138 /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout 139 /// constraints (i.e. minimum size and alignment as specified by `layout`). 140 /// 141 /// This function is equivalent to `realloc` when called with `None`. 142 /// 143 /// # Guarantees 144 /// 145 /// When the return value is `Ok(ptr)`, then `ptr` is 146 /// - valid for reads and writes for `layout.size()` bytes, until it is passed to 147 /// [`Allocator::free`] or [`Allocator::realloc`], 148 /// - aligned to `layout.align()`, 149 /// 150 /// Additionally, `Flags` are honored as documented in 151 /// <https://docs.kernel.org/core-api/mm-api.html#mm-api-gfp-flags>. 152 fn alloc(layout: Layout, flags: Flags) -> Result<NonNull<[u8]>, AllocError> { 153 // SAFETY: Passing `None` to `realloc` is valid by its safety requirements and asks for a 154 // new memory allocation. 155 unsafe { Self::realloc(None, layout, Layout::new::<()>(), flags) } 156 } 157 158 /// Re-allocate an existing memory allocation to satisfy the requested `layout`. 159 /// 160 /// If the requested size is zero, `realloc` behaves equivalent to `free`. 161 /// 162 /// If the requested size is larger than the size of the existing allocation, a successful call 163 /// to `realloc` guarantees that the new or grown buffer has at least `Layout::size` bytes, but 164 /// may also be larger. 165 /// 166 /// If the requested size is smaller than the size of the existing allocation, `realloc` may or 167 /// may not shrink the buffer; this is implementation specific to the allocator. 168 /// 169 /// On allocation failure, the existing buffer, if any, remains valid. 170 /// 171 /// The buffer is represented as `NonNull<[u8]>`. 172 /// 173 /// # Safety 174 /// 175 /// - If `ptr == Some(p)`, then `p` must point to an existing and valid memory allocation 176 /// created by this [`Allocator`]; if `old_layout` is zero-sized `p` does not need to be a 177 /// pointer returned by this [`Allocator`]. 178 /// - `ptr` is allowed to be `None`; in this case a new memory allocation is created and 179 /// `old_layout` is ignored. 180 /// - `old_layout` must match the `Layout` the allocation has been created with. 181 /// 182 /// # Guarantees 183 /// 184 /// This function has the same guarantees as [`Allocator::alloc`]. When `ptr == Some(p)`, then 185 /// it additionally guarantees that: 186 /// - the contents of the memory pointed to by `p` are preserved up to the lesser of the new 187 /// and old size, i.e. `ret_ptr[0..min(layout.size(), old_layout.size())] == 188 /// p[0..min(layout.size(), old_layout.size())]`. 189 /// - when the return value is `Err(AllocError)`, then `ptr` is still valid. 190 unsafe fn realloc( 191 ptr: Option<NonNull<u8>>, 192 layout: Layout, 193 old_layout: Layout, 194 flags: Flags, 195 ) -> Result<NonNull<[u8]>, AllocError>; 196 197 /// Free an existing memory allocation. 198 /// 199 /// # Safety 200 /// 201 /// - `ptr` must point to an existing and valid memory allocation created by this [`Allocator`]; 202 /// if `old_layout` is zero-sized `p` does not need to be a pointer returned by this 203 /// [`Allocator`]. 204 /// - `layout` must match the `Layout` the allocation has been created with. 205 /// - The memory allocation at `ptr` must never again be read from or written to. 206 unsafe fn free(ptr: NonNull<u8>, layout: Layout) { 207 // SAFETY: The caller guarantees that `ptr` points at a valid allocation created by this 208 // allocator. We are passing a `Layout` with the smallest possible alignment, so it is 209 // smaller than or equal to the alignment previously used with this allocation. 210 let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), layout, Flags(0)) }; 211 } 212 } 213 214 #[allow(dead_code)] 215 /// Returns a properly aligned dangling pointer from the given `layout`. 216 pub(crate) fn dangling_from_layout(layout: Layout) -> NonNull<u8> { 217 let ptr = layout.align() as *mut u8; 218 219 // SAFETY: `layout.align()` (and hence `ptr`) is guaranteed to be non-zero. 220 unsafe { NonNull::new_unchecked(ptr) } 221 } 222