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