xref: /linux-6.15/rust/kernel/alloc.rs (revision 01b2196e)
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     /// Suppresses allocation failure reports.
96     ///
97     /// This is normally or'd with other flags.
98     pub const __GFP_NOWARN: Flags = Flags(bindings::__GFP_NOWARN);
99 }
100 
101 /// The kernel's [`Allocator`] trait.
102 ///
103 /// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffers described
104 /// via [`Layout`].
105 ///
106 /// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on
107 /// an object instance.
108 ///
109 /// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design
110 /// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind
111 /// of `self` parameter.
112 ///
113 /// # Safety
114 ///
115 /// - A memory allocation returned from an allocator must remain valid until it is explicitly freed.
116 ///
117 /// - Any pointer to a valid memory allocation must be valid to be passed to any other [`Allocator`]
118 ///   function of the same type.
119 ///
120 /// - Implementers must ensure that all trait functions abide by the guarantees documented in the
121 ///   `# Guarantees` sections.
122 pub unsafe trait Allocator {
123     /// Allocate memory based on `layout` and `flags`.
124     ///
125     /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout
126     /// constraints (i.e. minimum size and alignment as specified by `layout`).
127     ///
128     /// This function is equivalent to `realloc` when called with `None`.
129     ///
130     /// # Guarantees
131     ///
132     /// When the return value is `Ok(ptr)`, then `ptr` is
133     /// - valid for reads and writes for `layout.size()` bytes, until it is passed to
134     ///   [`Allocator::free`] or [`Allocator::realloc`],
135     /// - aligned to `layout.align()`,
136     ///
137     /// Additionally, `Flags` are honored as documented in
138     /// <https://docs.kernel.org/core-api/mm-api.html#mm-api-gfp-flags>.
139     fn alloc(layout: Layout, flags: Flags) -> Result<NonNull<[u8]>, AllocError> {
140         // SAFETY: Passing `None` to `realloc` is valid by its safety requirements and asks for a
141         // new memory allocation.
142         unsafe { Self::realloc(None, layout, Layout::new::<()>(), flags) }
143     }
144 
145     /// Re-allocate an existing memory allocation to satisfy the requested `layout`.
146     ///
147     /// If the requested size is zero, `realloc` behaves equivalent to `free`.
148     ///
149     /// If the requested size is larger than the size of the existing allocation, a successful call
150     /// to `realloc` guarantees that the new or grown buffer has at least `Layout::size` bytes, but
151     /// may also be larger.
152     ///
153     /// If the requested size is smaller than the size of the existing allocation, `realloc` may or
154     /// may not shrink the buffer; this is implementation specific to the allocator.
155     ///
156     /// On allocation failure, the existing buffer, if any, remains valid.
157     ///
158     /// The buffer is represented as `NonNull<[u8]>`.
159     ///
160     /// # Safety
161     ///
162     /// - If `ptr == Some(p)`, then `p` must point to an existing and valid memory allocation
163     ///   created by this [`Allocator`]; if `old_layout` is zero-sized `p` does not need to be a
164     ///   pointer returned by this [`Allocator`].
165     /// - `ptr` is allowed to be `None`; in this case a new memory allocation is created and
166     ///   `old_layout` is ignored.
167     /// - `old_layout` must match the `Layout` the allocation has been created with.
168     ///
169     /// # Guarantees
170     ///
171     /// This function has the same guarantees as [`Allocator::alloc`]. When `ptr == Some(p)`, then
172     /// it additionally guarantees that:
173     /// - the contents of the memory pointed to by `p` are preserved up to the lesser of the new
174     ///   and old size, i.e. `ret_ptr[0..min(layout.size(), old_layout.size())] ==
175     ///   p[0..min(layout.size(), old_layout.size())]`.
176     /// - when the return value is `Err(AllocError)`, then `ptr` is still valid.
177     unsafe fn realloc(
178         ptr: Option<NonNull<u8>>,
179         layout: Layout,
180         old_layout: Layout,
181         flags: Flags,
182     ) -> Result<NonNull<[u8]>, AllocError>;
183 
184     /// Free an existing memory allocation.
185     ///
186     /// # Safety
187     ///
188     /// - `ptr` must point to an existing and valid memory allocation created by this [`Allocator`];
189     ///   if `old_layout` is zero-sized `p` does not need to be a pointer returned by this
190     ///   [`Allocator`].
191     /// - `layout` must match the `Layout` the allocation has been created with.
192     /// - The memory allocation at `ptr` must never again be read from or written to.
193     unsafe fn free(ptr: NonNull<u8>, layout: Layout) {
194         // SAFETY: The caller guarantees that `ptr` points at a valid allocation created by this
195         // allocator. We are passing a `Layout` with the smallest possible alignment, so it is
196         // smaller than or equal to the alignment previously used with this allocation.
197         let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), layout, Flags(0)) };
198     }
199 }
200 
201 #[allow(dead_code)]
202 /// Returns a properly aligned dangling pointer from the given `layout`.
203 pub(crate) fn dangling_from_layout(layout: Layout) -> NonNull<u8> {
204     let ptr = layout.align() as *mut u8;
205 
206     // SAFETY: `layout.align()` (and hence `ptr`) is guaranteed to be non-zero.
207     unsafe { NonNull::new_unchecked(ptr) }
208 }
209