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