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