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