xref: /linux-6.15/rust/kernel/alloc.rs (revision 08d3f549)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Extensions to the [`alloc`] crate.
4 
5 #[cfg(not(test))]
6 #[cfg(not(testlib))]
7 mod allocator;
8 pub mod box_ext;
9 pub mod vec_ext;
10 
11 /// Flags to be used when allocating memory.
12 ///
13 /// They can be combined with the operators `|`, `&`, and `!`.
14 ///
15 /// Values can be used from the [`flags`] module.
16 #[derive(Clone, Copy)]
17 pub struct Flags(u32);
18 
19 impl core::ops::BitOr for Flags {
20     type Output = Self;
21     fn bitor(self, rhs: Self) -> Self::Output {
22         Self(self.0 | rhs.0)
23     }
24 }
25 
26 impl core::ops::BitAnd for Flags {
27     type Output = Self;
28     fn bitand(self, rhs: Self) -> Self::Output {
29         Self(self.0 & rhs.0)
30     }
31 }
32 
33 impl core::ops::Not for Flags {
34     type Output = Self;
35     fn not(self) -> Self::Output {
36         Self(!self.0)
37     }
38 }
39 
40 /// Allocation flags.
41 ///
42 /// These are meant to be used in functions that can allocate memory.
43 pub mod flags {
44     use super::Flags;
45     use crate::bindings;
46 
47     /// Zeroes out the allocated memory.
48     ///
49     /// This is normally or'd with other flags.
50     pub const __GFP_ZERO: Flags = Flags(bindings::__GFP_ZERO);
51 
52     /// Users can not sleep and need the allocation to succeed.
53     ///
54     /// A lower watermark is applied to allow access to "atomic reserves". The current
55     /// implementation doesn't support NMI and few other strict non-preemptive contexts (e.g.
56     /// raw_spin_lock). The same applies to [`GFP_NOWAIT`].
57     pub const GFP_ATOMIC: Flags = Flags(bindings::GFP_ATOMIC);
58 
59     /// Typical for kernel-internal allocations. The caller requires ZONE_NORMAL or a lower zone
60     /// for direct access but can direct reclaim.
61     pub const GFP_KERNEL: Flags = Flags(bindings::GFP_KERNEL);
62 
63     /// The same as [`GFP_KERNEL`], except the allocation is accounted to kmemcg.
64     pub const GFP_KERNEL_ACCOUNT: Flags = Flags(bindings::GFP_KERNEL_ACCOUNT);
65 
66     /// Ror kernel allocations that should not stall for direct reclaim, start physical IO or
67     /// use any filesystem callback.  It is very likely to fail to allocate memory, even for very
68     /// small allocations.
69     pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT);
70 }
71