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